Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(remote-desktop): 修复原生 ICE 数字桥接并统一中继配置等待预算 (#4686)
Dashe2089e1e0d9f
diff --git a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts b/apps/desktop/src/main/device-link/__tests__/filePeer.test.tsindex 3b9d6deb4e..e288bd7004 100644--- a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts@@ -7,6 +7,9 @@ const mock = vi.hoisted(() => ({settings: { remoteControlEnabled: true, revokedControllers: [] as string[] },current: true,resolve: vi.fn(),+ iceConfig: vi.fn(async () => []),+ ready: vi.fn(async () => {}),+ replyDelay: 0,}));vi.mock('electron', () => ({ipcMain: { handle: (key: string, fn: (...args: any[]) => any) => mock.handlers.set(key, fn) },@@ -18,15 +21,20 @@ vi.mock('../broadcast-tap', () => ({captureDataOwnerBroadcastScope: () => ({}),isDataOwnerBroadcastScopeCurrent: () => mock.current,}));-vi.mock('../../remote-desktop/iceConfig', () => ({ loadDesktopIceServers: async () => [] }));+vi.mock('../../remote-desktop/iceConfig', () => ({ loadDesktopIceServers: mock.iceConfig }));vi.mock('../../remote-desktop/captureWindow', () => ({DesktopCaptureWindow: class {contents: any = null;async start() {+ await mock.ready();this.contents = {isDestroyed: () => false,send: (_channel: string, id: string, c: { action: string }) => {- if (c.action !== 'close') mock.handlers.get('file-peer:host:reply')!({}, id, true, 'v=0');+ if (c.action !== 'close') {+ const reply = () => mock.handlers.get('file-peer:host:reply')!({}, id, true, 'v=0');+ if (mock.replyDelay) setTimeout(reply, mock.replyDelay);+ else reply();+ }},};}@@ -43,6 +51,9 @@ describe('authorized file peer source', () => {let directory: string, file: string;beforeEach(async () => {mock.current = true;+ mock.iceConfig.mockReset().mockResolvedValue([]);+ mock.ready.mockReset().mockResolvedValue();+ mock.replyDelay = 0;mock.settings = { remoteControlEnabled: true, revokedControllers: [] };mock.handlers.clear();registerFilePeerIpc();@@ -69,6 +80,49 @@ describe('authorized file peer source', () => {}const read = (connection: string, ticket: string, offset: number) =>mock.handlers.get('file-peer:host:read')!({}, connection, ticket, offset);+ it('fits slow config, cold host and command reply within the 30s offer RPC', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ try {+ mock.iceConfig.mockImplementationOnce(+ () => new Promise((resolve) => setTimeout(() => resolve([]), 8_000)),+ );+ mock.ready.mockImplementationOnce(+ () => new Promise((resolve) => setTimeout(resolve, 10_000)),+ );+ mock.replyDelay = 14_000;+ let settled = false;+ const result = connect().then((value) => {+ settled = true;+ return value;+ });+ await vi.advanceTimersByTimeAsync(23_999);+ expect(settled).toBe(false);+ await vi.advanceTimersByTimeAsync(1);+ expect(settled).toBe(true);+ expect((await result).connection).toEqual(expect.any(String));+ } finally {+ vi.useRealTimers();+ }+ });+ it('does not let one stopped config request close another peer', async () => {+ let finish!: (value: never[]) => void;+ mock.iceConfig.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const slow = connect('device-a');+ const rejected = expect(slow).rejects.toThrow('CLOSED');+ const healthy = await connect('device-b');+ stopFilePeers('device-a');+ finish([]);+ await rejected;+ const source = await open(healthy.connection, 'device-b');+ expect(await read(healthy.connection, source.ticket, 0)).toBe(+ Buffer.from('hello').toString('base64'),+ );+ });it('reads bounded bytes and consumes the ticket only after verified EOF', async () => {const { connection } = await connect(),{ ticket, size } = await open(connection);@@ -82,8 +136,15 @@ describe('authorized file peer source', () => {it('accepts a sparse 2 GiB source and rejects one byte above the transport limit', async () => {const limit = 2 * 1024 * 1024 * 1024;await truncate(file, limit);- mock.resolve.mockResolvedValue({ absPath: file, mimeType: 'application/octet-stream', maxBytes: limit });- expect(await requestFilePeer('device-a', { action: 'caps' })).toEqual({ version: 1, maxBytes: limit });+ mock.resolve.mockResolvedValue({+ absPath: file,+ mimeType: 'application/octet-stream',+ maxBytes: limit,+ });+ expect(await requestFilePeer('device-a', { action: 'caps' })).toEqual({+ version: 1,+ maxBytes: limit,+ });const first = await connect();expect((await open(first.connection)).size).toBe(limit);stopFilePeers();@@ -144,7 +205,8 @@ describe('authorized file peer source', () => {const next = await open(connection);await vi.advanceTimersByTimeAsync(61_000);await expect(read(connection, next.ticket, 0)).rejects.toThrow('FILE_PEER_BLOCK');- } finally { vi.useRealTimers(); }+ } finally {+ vi.useRealTimers();+ }});-});diff --git a/apps/desktop/src/main/device-link/filePeer.ts b/apps/desktop/src/main/device-link/filePeer.tsindex 9a3d2013c5..0aadd4bf10 100644--- a/apps/desktop/src/main/device-link/filePeer.ts+++ b/apps/desktop/src/main/device-link/filePeer.ts@@ -130,8 +130,8 @@ function stopConnection(id: string) {export function stopFilePeers(peer?: string) {for (const [id, c] of connections) if (!peer || peer === c.peer) stopConnection(id);}-async function command(c: FilePeerCommand): Promise<string | undefined> {- touch(c.connection);+async function prepareHost(connection: string): Promise<void> {+ touch(connection);if (!host.contents) {if (!starting)starting = host.start().finally(() => {@@ -139,7 +139,10 @@ async function command(c: FilePeerCommand): Promise<string | undefined> {});await starting;} else if (starting) await starting;- touch(c.connection);+ touch(connection);+}+async function command(c: FilePeerCommand): Promise<string | undefined> {+ await prepareHost(c.connection);return new Promise((resolve, reject) => {const id = randomUUID();const timer = setTimeout(@@ -163,10 +166,13 @@ export async function requestFilePeer(peer: string, value: unknown): Promise<unkconst id = randomUUID();track(id, peer, true);try {+ // Cold host readiness and TURN configuration share the outer 30s RPC+ // budget: max(10s, 8s) + 15s command leaves transport headroom.+ const [, servers] = await Promise.all([prepareHost(id), loadDesktopIceServers()]);const sdp = await command({action: 'accept',connection: id,- servers: await loadDesktopIceServers(),+ servers,sdp: r.sdp,});return { connection: id, sdp };@@ -346,10 +352,14 @@ type Invoke = (const queuePeerRead = createFileReadQueue();export function tryPeerFile(peer: string, url: string, invoke: Invoke, signal?: AbortSignal) {const owner = captureDataOwnerBroadcastScope();- return queuePeerRead(peer, () => {- if (!isDataOwnerBroadcastScopeCurrent(owner)) throw new Error('FILE_PEER_CANCELLED');- return receivePeerFile(peer, url, invoke, signal);- }, signal);+ return queuePeerRead(+ peer,+ () => {+ if (!isDataOwnerBroadcastScopeCurrent(owner)) throw new Error('FILE_PEER_CANCELLED');+ return receivePeerFile(peer, url, invoke, signal);+ },+ signal,+ );}async function receivePeerFile(peer: string, url: string, invoke: Invoke, signal?: AbortSignal) {if (signal?.aborted) throw new Error('FILE_PEER_CANCELLED');@@ -374,10 +384,11 @@ async function receivePeerFile(peer: string, url: string, invoke: Invoke, signalthrow new Error('FILE_PEER_CANCELLED');if (!caps.ok || (caps.result as { version?: unknown })?.version !== 1) return null;track(id, peer, false);+ const [, servers] = await Promise.all([prepareHost(id), loadDesktopIceServers()]);const offer = await command({action: 'offer',connection: id,- servers: await loadDesktopIceServers(),+ servers,});const response = await invoke(peer, FILE_PEER_CHANNEL, [{ action: 'offer', sdp: offer }]);const r = response.result as { connection?: string; sdp?: string };diff --git a/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopBridgeNumber.swift b/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopBridgeNumber.swiftnew file mode 100644index 0000000000..627f1f419e--- /dev/null+++ b/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopBridgeNumber.swift@@ -0,0 +1,14 @@+import Foundation+import CoreFoundation++enum RemoteDesktopBridgeNumber {+ /// Expo's untyped JS dictionaries contain Double, not Swift Int. Keep the+ /// wire contract strict: no truncation, booleans or unsafe JS integers.+ static func integer(_ value: Any?) -> Int? {+ guard let number = value as? NSNumber,+ CFGetTypeID(number) != CFBooleanGetTypeID() else { return nil }+ let value = number.doubleValue+ guard value.isFinite, abs(value) <= 9_007_199_254_740_991 else { return nil }+ return Int(exactly: value)+ }+}diff --git a/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopReceiver.swift b/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopReceiver.swiftindex 95cf53f26b..fb266e7cd6 100644--- a/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopReceiver.swift+++ b/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopReceiver.swift@@ -42,12 +42,18 @@ final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataCprivate var offerSent = falseprivate var frameReady = falseprivate var pendingViewChallenge: String?+ private let diagnostics: Bool+ private let diagnosticStart = ProcessInfo.processInfo.systemUptime+ private var candidateCounts: [String: Int] = [:]+ private var configuredTurnCount = 0+ private var lastPairKinds: String?- init(epoch: String, audio: Bool, trickle: Bool, net: [String: Any]) {+ init(epoch: String, audio: Bool, trickle: Bool, net: [String: Any], diagnostics: Bool = false) {self.epoch = epochself.audio = audioself.trickle = trickleself.net = net+ self.diagnostics = diagnosticssuper.init()}private func seconds(_ key: String, _ fallback: Double) -> Double {@@ -57,23 +63,55 @@ final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataCguard !stopped else { return }emit(payload.merging(["type": type, "epoch": epoch, "attemptId": attempt]) { _, new in new })}+ // Fixed enums and counts only. No SDP, addresses, URLs or TURN credentials.+ private func diagnose(_ stage: String, _ fields: [String: Any] = [:]) {+ guard diagnostics else { return }+ var values: [String: Any] = ["stage": stage,+ "elapsedMs": Int((ProcessInfo.processInfo.systemUptime - diagnosticStart) * 1000),+ "turnUrlCount": configuredTurnCount, "localAck": localAck, "remoteAfter": remoteAfter,+ "trickleEnabled": trickle]+ for (key, count) in candidateCounts { values[key] = count }+ values.merge(fields) { _, new in new }+ post("rtcDiagnostic", values)+ }+ private func serverSummary(_ servers: [[String: Any]]) -> [String: Any] {+ let urls = servers.flatMap { ($0["urls"] as? [String]) ?? ($0["urls"] as? String).map { [$0] } ?? [] }+ return ["serverCount": servers.count,+ "turnUrlCount": urls.filter { $0.hasPrefix("turn:") || $0.hasPrefix("turns:") }.count]+ }+ private func countCandidate(_ sdp: String, side: String) {+ guard diagnostics else { return }+ let parts = sdp.split(whereSeparator: { $0.isWhitespace })+ let kind = parts.firstIndex(of: "typ").flatMap { $0 + 1 < parts.count ? String(parts[$0 + 1]) : nil } ?? "unknown"+ let safeKind = ["host", "srflx", "prflx", "relay"].contains(kind) ? kind : "unknown"+ let key = side + "_" + safeKind+ candidateCounts[key, default: 0] += 1+ // First occurrence proves each candidate kind was seen without a per-candidate log flood.+ if candidateCounts[key] == 1 { diagnose("candidate-kind") }+ }func begin(fallbackServers: [[String: Any]]) {post("iceConfig")- timer = Timer.scheduledTimer(withTimeInterval: 3.5, repeats: false) { [weak self] _ in- self?.start(servers: fallbackServers)+ diagnose("config-requested")+ timer = Timer.scheduledTimer(withTimeInterval: seconds("iceConfigMs", 8_000) + seconds("iceConfigBridgeMs", 500), repeats: false) { [weak self] _ in+ self?.diagnose("config-deadline")+ self?.start(servers: fallbackServers, source: "native-deadline")}}func receive(_ message: [String: Any]) {guard !stopped, message["epoch"] as? String == epoch,message["attemptId"] as? String == attempt else { return }switch message["type"] as? String {- case "iceConfig": start(servers: message["iceServers"] as? [[String: Any]] ?? [])+ case "iceConfig":+ let servers = message["iceServers"] as? [[String: Any]] ?? []+ diagnose(peer == nil ? "config-received" : "config-late-ignored", serverSummary(servers))+ start(servers: servers, source: "bridge")case "answer":guard let peer, let sdp = message["sdp"] as? String, sdp.utf8.count <= 64_000 else { return }peer.setRemoteDescription(RTCSessionDescription(type: .answer, sdp: sdp)) { [weak self] error inDispatchQueue.main.async {guard let self, !self.stopped else { return }guard error == nil else { self.fail("answer"); return }+ self.diagnose("answer-applied")self.deadline(self.seconds("connectMs", 15_000), "connect-timeout")self.exchangeUntil = Date().addingTimeInterval(self.seconds("exchangeMs", 30_000))self.pollIce()@@ -84,7 +122,7 @@ final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataCdefault: break}}- private func start(servers: [[String: Any]]) {+ private func start(servers: [[String: Any]], source: String) {guard !stopped, peer == nil else { return }timer?.invalidate()let config = RTCConfiguration()@@ -95,6 +133,8 @@ final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataCreturn RTCIceServer(urlStrings: urls, username: server["username"] as? String,credential: server["credential"] as? String)}+ configuredTurnCount = serverSummary(servers)["turnUrlCount"] as? Int ?? 0+ diagnose("config-applied", ["source": source, "serverCount": config.iceServers.count])let constraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)guard let rtc = Self.factory.peerConnection(with: config, constraints: constraints, delegate: self) else {fail("setup"); return@@ -128,6 +168,7 @@ final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataCprivate func sendOffer() {guard !stopped, !offerSent, let sdp = peer?.localDescription?.sdp else { return }offerSent = true+ diagnose("offer-sent")deadline(seconds("answerMs", 45_000), "answer-timeout")post("offer", ["sdp": sdp])}@@ -144,6 +185,7 @@ final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataClet batch = Array(candidates.dropFirst(localAck).prefix(16))exchange += 1pending = (exchange, batch.count)+ diagnose("exchange-sent", ["exchangeId": exchange, "batchCount": batch.count])post("ice", ["candidates": batch, "after": remoteAfter, "exchangeId": exchange])scheduleIce(4.5)}@@ -155,11 +197,12 @@ final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataC}}private func receiveIce(_ message: [String: Any]) {- guard let batch = pending, message["exchangeId"] as? Int == batch.id, let peer else { return }+ guard let batch = pending,+ RemoteDesktopBridgeNumber.integer(message["exchangeId"]) == batch.id, let peer else { return }iceTimer?.invalidate()- if message["error"] as? Bool == true { pending = nil; scheduleIce(1); return }+ if message["error"] as? Bool == true { diagnose("exchange-error"); pending = nil; scheduleIce(1); return }guard let values = message["candidates"] as? [[String: Any]], values.count <= 16,- let next = message["next"] as? Int, next == remoteAfter + values.count, next <= 128 else {+ let next = RemoteDesktopBridgeNumber.integer(message["next"]), next == remoteAfter + values.count, next <= 128 else {fail("candidates"); return}// WebRTC serializes addIceCandidate internally. Mark the batch complete only@@ -170,6 +213,7 @@ final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataClocalAck += batch.countremoteAfter = nextpending = nil+ if batch.count > 0 || !values.isEmpty { diagnose("exchange-applied") }if !(message["complete"] as? Bool == true && peer.iceGatheringState == .complete && localAck == candidates.count) {scheduleIce(seconds("pollMs", 250))}@@ -177,7 +221,7 @@ final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataC}let value = values[index]guard let sdp = value["candidate"] as? String, sdp.utf8.count <= 4096,- let line = value["sdpMLineIndex"] as? Int, line >= 0, line <= 65535 else {+ let line = RemoteDesktopBridgeNumber.integer(value["sdpMLineIndex"]), line >= 0, line <= 65535 else {fail("candidates"); return}let key = "\(value["sdpMid"] as? String ?? ""):\(line):\(sdp)"@@ -188,6 +232,7 @@ final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataCguard let self, !self.stopped else { return }guard error == nil else { self.fail("candidates"); return }self.remoteSeen.insert(key)+ self.countCandidate(sdp, side: "remote")add(index + 1)}}@@ -217,13 +262,14 @@ final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataCfunc sendInput(_ message: [String: Any]) -> Bool {guard !stopped, !isPresenting(), UIApplication.shared.applicationState == .active,peer?.connectionState == .connected, let channel, channel.readyState == .open,- channel.bufferedAmount < 16384, let sequence = message["sequence"] as? Int,+ channel.bufferedAmount < 16384, let sequence = RemoteDesktopBridgeNumber.integer(message["sequence"]), sequence >= 0,let events = message["events"] as? [[String: Any]], events.count <= 64,let data = try? JSONSerialization.data(withJSONObject: ["sequence": sequence, "events": events]),data.count <= 32_768 else { return false }return channel.sendData(RTCDataBuffer(data: data, isBinary: false))}private func fail(_ reason: String, retry: Bool = true) {+ diagnose("failed", ["reason": reason])post("fallback", ["reason": reason, "retry": retry])stop()}@@ -235,11 +281,18 @@ final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataCguard let self, !self.stopped else { return }self.statsBusy = falselet rows = Array(report.statistics.values)- guard let video = rows.first(where: { $0.type == "inbound-rtp" && (($0.values["kind"] as? String) ?? ($0.values["mediaType"] as? String)) == "video" }) else { return }let pairID = rows.first(where: { $0.type == "transport" })?.values["selectedCandidatePairId"] as? Stringlet pair = pairID.flatMap { report.statistics[$0] }let local = (pair?.values["localCandidateId"] as? String).flatMap { report.statistics[$0] }?.values["candidateType"] as? Stringlet remote = (pair?.values["remoteCandidateId"] as? String).flatMap { report.statistics[$0] }?.values["candidateType"] as? String+ if let local, let remote {+ let kinds = local + "/" + remote+ if kinds != self.lastPairKinds {+ self.lastPairKinds = kinds+ self.diagnose("selected-pair", ["localKind": local, "remoteKind": remote])+ }+ }+ guard let video = rows.first(where: { $0.type == "inbound-rtp" && (($0.values["kind"] as? String) ?? ($0.values["mediaType"] as? String)) == "video" }) else { return }var data: [String: Any] = ["transport": local == "relay" || remote == "relay" ? "relay" : (local != nil && remote != nil ? "direct" : "video")]if let rtt = pair?.values["currentRoundTripTime"] as? Double { data["latencyMs"] = rtt * 1000 }if let bytes = video.values["bytesReceived"] as? Double {@@ -255,7 +308,9 @@ final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataC}func peerConnection(_ peerConnection: RTCPeerConnection, didGenerate candidate: RTCIceCandidate) {DispatchQueue.main.async { [weak self] in- guard let self, !self.stopped, self.trickle else { return }+ guard let self, !self.stopped else { return }+ self.countCandidate(candidate.sdp, side: "local")+ guard self.trickle else { return }guard self.candidates.count < 128 else { self.fail("candidate-limit", retry: false); return }var value: [String: Any] = ["candidate": candidate.sdp, "sdpMLineIndex": Int(candidate.sdpMLineIndex)]if let mid = candidate.sdpMid { value["sdpMid"] = mid }@@ -264,12 +319,14 @@ final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataC}func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceGatheringState) {DispatchQueue.main.async { [weak self] in+ self?.diagnose("gathering", ["stateCode": newState.rawValue])if newState == .complete && self?.trickle == false { self?.sendOffer() }}}func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCPeerConnectionState) {DispatchQueue.main.async { [weak self] inguard let self, !self.stopped else { return }+ self.diagnose("connection", ["stateCode": newState.rawValue])if newState == .failed || newState == .closed { self.fail("transport") }else if newState == .disconnected {guard self.disconnectTimer == nil else { return }@@ -298,6 +355,7 @@ final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataCguard self.onFrame(frame) else { return }if !self.frameReady {self.frameReady = true+ self.diagnose("first-frame")self.post("videoFrameReady")self.post("streaming")}@@ -336,7 +394,17 @@ final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataCfunc peerConnection(_ peerConnection: RTCPeerConnection, didAdd stream: RTCMediaStream) {}func peerConnection(_ peerConnection: RTCPeerConnection, didRemove stream: RTCMediaStream) {}func peerConnectionShouldNegotiate(_ peerConnection: RTCPeerConnection) {}- func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState) {}+ func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState) {+ DispatchQueue.main.async { [weak self] in self?.diagnose("ice-state", ["stateCode": newState.rawValue]) }+ }+ func peerConnection(_ peerConnection: RTCPeerConnection, didFailToGatherIceCandidate event: RTCIceCandidateErrorEvent) {+ let code = event.errorCode+ let kind = event.url.hasPrefix("turns:") ? "turns" : (event.url.hasPrefix("turn:") ? "turn" : "stun")+ let transport = event.url.hasPrefix("turns:") ? "tls" : (event.url.contains("transport=tcp") ? "tcp" : "udp")+ DispatchQueue.main.async { [weak self] in+ self?.diagnose("ice-error", ["errorCode": code, "serverKind": kind, "transportKind": transport])+ }+ }func peerConnection(_ peerConnection: RTCPeerConnection, didRemove candidates: [RTCIceCandidate]) {}func peerConnection(_ peerConnection: RTCPeerConnection, didOpen dataChannel: RTCDataChannel) {}}diff --git a/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopVideoView.swift b/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopVideoView.swiftindex 44c64b7702..461af9f039 100644--- a/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopVideoView.swift+++ b/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopVideoView.swift@@ -228,7 +228,8 @@ final class RemoteDesktopVideoView: ExpoView, AVPictureInPictureControllerDelegaUIApplication.shared.applicationState == .active else { return }let current = RemoteDesktopReceiver(epoch: epoch, audio: config["audio"] as? Bool == true,trickle: config["trickleIce"] as? Bool == true,- net: config["net"] as? [String: Any] ?? [:])+ net: config["net"] as? [String: Any] ?? [:],+ diagnostics: config["diagnostics"] as? Bool == true)receiver = currentlastCapability = nilcurrent.isPresenting = { [weak self] in self?.presenting == true && self?.pip?.isPictureInPictureActive == true }diff --git a/apps/mobile/scripts/fixtures/remote-desktop-receiver.swift b/apps/mobile/scripts/fixtures/remote-desktop-receiver.swiftindex 74ffb4ed20..1100a678c3 100644--- a/apps/mobile/scripts/fixtures/remote-desktop-receiver.swift+++ b/apps/mobile/scripts/fixtures/remote-desktop-receiver.swift@@ -22,9 +22,10 @@ final class RTCPeerConnectionFactory {}}enum RTCSignalingState { case stable }-enum RTCIceConnectionState { case connected }-enum RTCIceGatheringState { case gathering, complete }-enum RTCPeerConnectionState { case new, connected, disconnected, failed, closed }+enum RTCIceConnectionState: Int { case connected }+enum RTCIceGatheringState: Int { case gathering, complete }+enum RTCPeerConnectionState: Int { case new, connected, disconnected, failed, closed }+final class RTCIceCandidateErrorEvent { var errorCode = 701; var url = "stun:test.invalid:3478" }final class RTCConfiguration {enum Semantics { case unifiedPlan }var sdpSemantics = Semantics.unifiedPlan@@ -145,17 +146,50 @@ struct ReceiverTests {ice.receive(message(ice, "answer", ["sdp": "answer"]))icePeer.answerCallback?(nil); drain()let exchange = iceEvents.first { $0["type"] as? String == "ice" }!["exchangeId"] as! Int- let candidate: [String: Any] = ["candidate": "candidate:one", "sdpMLineIndex": 0]+ let candidate: [String: Any] = ["candidate": "candidate:one", "sdpMLineIndex": Double(0)]ice.receive(message(old, "ice", ["exchangeId": exchange, "candidates": [candidate], "next": 1]))assert(icePeer.candidateCallbacks.isEmpty)ice.receive(message(ice, "ice", ["exchangeId": exchange + 1, "candidates": [candidate], "next": 1]))assert(icePeer.candidateCallbacks.isEmpty)- ice.receive(message(ice, "ice", ["exchangeId": exchange, "candidates": [candidate], "next": 1]))+ // Expo's untyped dictionaries carry Double for all JS numbers.+ ice.receive(message(ice, "ice", ["exchangeId": Double(exchange), "candidates": [candidate], "next": Double(1)]))assert(icePeer.candidateCallbacks.count == 1)ice.stop(); let iceCount = iceEvents.counticePeer.candidateCallbacks[0](nil); drain()assert(iceEvents.count == iceCount)+ let (numeric, numericPeer) = start()+ var numericEvents: [[String: Any]] = []+ numeric.emit = { numericEvents.append($0) }+ numeric.peerConnection(numericPeer, didGenerate: RTCIceCandidate(sdp: "candidate:local", sdpMLineIndex: 0, sdpMid: "0"))+ drain()+ numeric.receive(message(numeric, "answer", ["sdp": "answer"]))+ numericPeer.answerCallback?(nil); drain()+ let sent = numericEvents.first { $0["type"] as? String == "ice" }!+ let numericID = Double(sent["exchangeId"] as! Int)+ numeric.receive(message(numeric, "ice", ["exchangeId": numericID, "candidates": [candidate], "next": Double(1)]))+ assert(numericPeer.candidateCallbacks.count == 1)+ numericPeer.candidateCallbacks[0](nil); drain(0.3)+ let next = numericEvents.last { $0["type"] as? String == "ice" }!+ assert(next["after"] as? Int == 1)+ assert((next["candidates"] as? [[String: Any]])?.isEmpty == true)+ numericPeer.connectionState = .connected+ assert(numeric.sendInput(["sequence": Double(1), "events": [["type": "move"]]]))+ assert(!numeric.sendInput(["sequence": true, "events": [["type": "move"]]]))+ assert(!numeric.sendInput(["sequence": 1.5, "events": [["type": "move"]]]))+ numeric.stop()++ // The native wait must cover a configuration that arrives after the old+ // 3.5-second fallback, while independent receivers remain usable.+ let slowConfig = RemoteDesktopReceiver(epoch: "slow", audio: false, trickle: true, net: ["iceConfigMs": 8_000.0])+ let beforeConfig = RTCPeerConnectionFactory.latest+ slowConfig.begin(fallbackServers: [])+ drain(3.6)+ assert(RTCPeerConnectionFactory.latest === beforeConfig)+ slowConfig.receive(message(slowConfig, "iceConfig"))+ assert(RTCPeerConnectionFactory.latest !== beforeConfig)+ slowConfig.stop()+// A decoder frame already queued when stop occurs must not announce readiness.let (frames, framePeer) = start()let transceiver = RTCRtpTransceiver()diff --git a/apps/mobile/scripts/test-remote-desktop-bridge-number.swift b/apps/mobile/scripts/test-remote-desktop-bridge-number.swiftnew file mode 100644index 0000000000..bd26f87e74--- /dev/null+++ b/apps/mobile/scripts/test-remote-desktop-bridge-number.swift@@ -0,0 +1,25 @@+// Compile with modules/cindy-remote-presentation/ios/RemoteDesktopBridgeNumber.swift.+import Foundation++@main+enum RemoteDesktopBridgeNumberTest {+ static func main() {+ // Actual Expo getAny representation, unlike JSONSerialization's NSNumber.+ let reply: [String: Any] = ["exchangeId": Double(1), "next": Double(16),+ "candidates": [["sdpMLineIndex": Double(0)]]]+ precondition(reply["exchangeId"] as? Int == nil)+ precondition(RemoteDesktopBridgeNumber.integer(reply["exchangeId"]) == 1)+ precondition(RemoteDesktopBridgeNumber.integer(reply["next"]) == 16)+ let candidates = reply["candidates"] as! [[String: Any]]+ precondition(RemoteDesktopBridgeNumber.integer(candidates[0]["sdpMLineIndex"]) == 0)+ for value: Any in [Int(12), Double(12), NSNumber(value: 12)] {+ precondition(RemoteDesktopBridgeNumber.integer(value) == 12)+ }+ for value: Any in [true, false, NSNumber(value: true), "1", Double.nan,+ Double.infinity, Double(1.5), Double(9_007_199_254_740_992)] {+ precondition(RemoteDesktopBridgeNumber.integer(value) == nil)+ }+ precondition(RemoteDesktopBridgeNumber.integer(nil) == nil)+ print("Remote desktop bridge numeric regression passed")+ }+}diff --git a/apps/mobile/scripts/test-remote-desktop-receiver.mjs b/apps/mobile/scripts/test-remote-desktop-receiver.mjsindex ae75beb000..8838668cec 100644--- a/apps/mobile/scripts/test-remote-desktop-receiver.mjs+++ b/apps/mobile/scripts/test-remote-desktop-receiver.mjs@@ -21,7 +21,14 @@ try {);const input = join(directory, "ReceiverTests.swift");const executable = join(directory, "receiver-tests");- writeFileSync(input, source + "\n" + fixture);+ const numbers = readFileSync(+ new URL(+ "../modules/cindy-remote-presentation/ios/RemoteDesktopBridgeNumber.swift",+ import.meta.url,+ ),+ "utf8",+ );+ writeFileSync(input, numbers + "\n" + source + "\n" + fixture);execFileSync("xcrun",["swiftc", "-parse-as-library", input, "-o", executable],diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsxindex 2c09b1c0ba..9ccaa9c404 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx@@ -77,7 +77,11 @@ import {import { Text } from "@/components/AppText";import { useScreenEdgePadding } from "@/components/screenEdgeInsets";import { goBackGuarded } from "@/utils/backGuard";-import { mobileDebugLog } from "@/debug/mobileDebugLog";+import { mobileDebugEnabled, mobileDebugLog } from "@/debug/mobileDebugLog";+import {+ RTC_DIAGNOSTIC_REVISION,+ rtcDiagnosticSummary,+} from "./rtcDiagnostics";import {fontWeight,iconSize,@@ -456,6 +460,7 @@ export function RemoteDesktopSession({}: REMOTE_DESKTOP_NETWORK,iceServers: REMOTE_DESKTOP_ICE_SERVERS,+ diagnostics: mobileDebugEnabled(),}: {}),})@@ -520,13 +525,25 @@ export function RemoteDesktopSession({new RemoteDesktopViewerMedia({request,send,- loadIce: () =>- resolveDesktopIceServers(() =>- authRef.current.apiFetch(REMOTE_DESKTOP_ICE_CONFIG_PATH, {- baseUrl: DEVICE_LINK_API_BASE_URL,- timeoutMs: REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,- cache: "no-store",- }),+ loadIce: (attemptId) =>+ resolveDesktopIceServers(+ () =>+ authRef.current.apiFetch(REMOTE_DESKTOP_ICE_CONFIG_PATH, {+ baseUrl: DEVICE_LINK_API_BASE_URL,+ timeoutMs: REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,+ cache: "no-store",+ }),+ (result) =>+ mobileDebugLog(+ "info",+ "device-link",+ "remote desktop ICE config",+ {+ revision: RTC_DIAGNOSTIC_REVISION,+ attempt: attemptId.slice(0, 8),+ ...result,+ },+ ),),current: () => {const lease = active.current,@@ -1544,6 +1561,17 @@ export function RemoteDesktopSession({)return;switch (message.type) {+ case "rtcDiagnostic": {+ const summary = rtcDiagnosticSummary(message);+ if (summary)+ mobileDebugLog(+ "info",+ "device-link",+ "remote desktop RTC diagnostic",+ summary,+ );+ break;+ }case "nativeViewport":if (NativeRemoteDesktopView)void nativeViewer.current?.receive(message).catch(() => {});diff --git a/apps/mobile/src/remote-desktop/__tests__/rtcDiagnostics.test.ts b/apps/mobile/src/remote-desktop/__tests__/rtcDiagnostics.test.tsnew file mode 100644index 0000000000..b92ba1b037--- /dev/null+++ b/apps/mobile/src/remote-desktop/__tests__/rtcDiagnostics.test.ts@@ -0,0 +1,59 @@+import { expect, it } from "vitest";+import {+ rtcDiagnosticSummary,+ RTC_DIAGNOSTIC_REVISION,+} from "../rtcDiagnostics";++it("projects only allowed counters and enums, excluding remote text and credentials", () => {+ expect(+ rtcDiagnosticSummary({+ stage: "config-applied",+ attemptId: "ABCDEF12-1234",+ elapsedMs: 3100,+ source: "native-deadline",+ serverCount: 2,+ turnUrlCount: 0,+ local_host: 3,+ credential: "private",+ urls: ["turn:private:3478"],+ sdp: "private",+ address: "1.2.3.4",+ reason: "secret error",+ localKind: "arbitrary remote text",+ remote_relay: NaN,+ }),+ ).toEqual({+ revision: RTC_DIAGNOSTIC_REVISION,+ stage: "config-applied",+ attempt: "ABCDEF12",+ elapsedMs: 3100,+ source: "native-deadline",+ serverCount: 2,+ turnUrlCount: 0,+ local_host: 3,+ reason: "other",+ });+ expect(rtcDiagnosticSummary({ stage: "unknown private event" })).toBeNull();+});++it("keeps candidate types and native gathering failure codes without their URLs or text", () => {+ expect(+ rtcDiagnosticSummary({+ stage: "ice-error",+ errorCode: 701,+ errorText: "private",+ url: "private",+ }),+ ).toEqual({+ revision: RTC_DIAGNOSTIC_REVISION,+ stage: "ice-error",+ errorCode: 701,+ });+ expect(+ rtcDiagnosticSummary({+ stage: "selected-pair",+ localKind: "relay",+ remoteKind: "host",+ }),+ ).toMatchObject({ localKind: "relay", remoteKind: "host" });+});diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsxindex d80a9d4f52..4125415f7f 100644--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx@@ -1355,7 +1355,10 @@ describe("remote desktop controls", () => {expect.objectContaining({type: "init",epoch: "lease",- net: expect.any(Object),+ net: expect.objectContaining({+ iceConfigMs: 8_000,+ iceConfigBridgeMs: 500,+ }),}),);await act(async () =>@@ -1377,6 +1380,10 @@ describe("remote desktop controls", () => {iceServers: expect.any(Array),}),);+ expect(fixture.apiFetch).toHaveBeenCalledWith(+ "/api/device-link/ice-servers",+ expect.objectContaining({ timeoutMs: 8_000 }),+ );act(() => {AppState.currentState = "background";fixture.appState!("background");@@ -1556,7 +1563,7 @@ describe("remote desktop controls", () => {"/api/device-link/ice-servers",{baseUrl: "https://relay.example.test",- timeoutMs: 3000,+ timeoutMs: 8000,cache: "no-store",},);diff --git a/apps/mobile/src/remote-desktop/__tests__/viewerRtc.test.ts b/apps/mobile/src/remote-desktop/__tests__/viewerRtc.test.tsindex 1d04b0bb49..895d45b7ba 100644--- a/apps/mobile/src/remote-desktop/__tests__/viewerRtc.test.ts+++ b/apps/mobile/src/remote-desktop/__tests__/viewerRtc.test.ts@@ -4,7 +4,12 @@ import { REMOTE_DESKTOP_NETWORK as net } from "@cindy/device-link";import { DESKTOP_RTC_SCRIPT } from "../viewerRtc";// Executes the exact static script embedded in WKWebView, with only RTC/DOM replaced.-function viewer(trickle = true, autoConfig = true, frameCallback = true) {+function viewer(+ trickle = true,+ autoConfig = true,+ frameCallback = true,+ network: object = net,+) {let api: any;const messages: any[] = [];const peers: any[] = [];@@ -64,7 +69,7 @@ function viewer(trickle = true, autoConfig = true, frameCallback = true) {const retained = vi.fn();const release = vi.fn();const context = vm.createContext({- net,+ net: network,iceServers: [],window: { RTCPeerConnection: Peer },RTCPeerConnection: Peer,@@ -349,13 +354,17 @@ it("reloads credentials on recovery and supplies the backup as well as the primah.api.stop();});-it("bounds native config wait, ignores late/duplicate config, and preserves another viewer", async () => {+it("bounds bridged config wait, ignores late/duplicate config, and preserves another viewer", async () => {const a = viewer(true, false),b = viewer();await a.api.start();await b.api.start();const pending = a.latest("iceConfig");- await vi.advanceTimersByTimeAsync(3500);+ await vi.advanceTimersByTimeAsync(+ net.iceConfigMs + net.iceConfigBridgeMs - 1,+ );+ expect(a.peers).toHaveLength(0);+ await vi.advanceTimersByTimeAsync(1);expect(a.peers).toHaveLength(1);await a.api.config({...pending,@@ -369,6 +378,31 @@ it("bounds native config wait, ignores late/duplicate config, and preserves anotexpect(vi.getTimerCount()).toBe(0);});+it.each([true, false])(+ "keeps slow TURN configuration when budget fields are present=%s",+ async (current) => {+ const { iceConfigMs, iceConfigBridgeMs, ...legacyNet } = net;+ const h = viewer(true, false, true, current ? net : legacyNet);+ await h.api.start();+ const pending = h.latest("iceConfig");+ await vi.advanceTimersByTimeAsync(5_000);+ expect(h.peers).toHaveLength(0);+ const servers = [+ {+ urls: ["turn:slow.example.test:3478"],+ username: "short-lived",+ credential: "test",+ },+ ];+ await h.api.config({ ...pending, iceServers: servers });+ expect(h.peers[0].configuration.iceServers).toEqual(servers);+ await vi.advanceTimersByTimeAsync(iceConfigMs + iceConfigBridgeMs);+ expect(h.peers).toHaveLength(1);+ h.api.stop();+ expect(vi.getTimerCount()).toBe(0);+ },+);+it("never starts media after exit while credentials are pending", async () => {const h = viewer(true, false);await h.api.start();diff --git a/apps/mobile/src/remote-desktop/rtcDiagnostics.ts b/apps/mobile/src/remote-desktop/rtcDiagnostics.tsnew file mode 100644index 0000000000..226661daa6--- /dev/null+++ b/apps/mobile/src/remote-desktop/rtcDiagnostics.ts@@ -0,0 +1,92 @@+/** The native bridge is not a license to persist arbitrary fields or remote text. */+export const RTC_DIAGNOSTIC_REVISION = "ice-diag-20260919-2";+const stages = new Set([+ "config-requested",+ "config-deadline",+ "config-received",+ "config-late-ignored",+ "config-applied",+ "answer-applied",+ "offer-sent",+ "exchange-error",+ "exchange-sent",+ "exchange-applied",+ "candidate-kind",+ "failed",+ "selected-pair",+ "gathering",+ "connection",+ "ice-state",+ "first-frame",+ "ice-error",+]);+const kinds = ["host", "srflx", "prflx", "relay", "unknown"];+const counts = [+ "serverCount",+ "turnUrlCount",+ "localAck",+ "remoteAfter",+ "exchangeId",+ "batchCount",+ ...["local", "remote"].flatMap((side) =>+ kinds.map((kind) => `${side}_${kind}`),+ ),+];++export function rtcDiagnosticSummary(message: Record<string, unknown>) {+ if (typeof message.stage !== "string" || !stages.has(message.stage))+ return null;+ const result: Record<string, string | number | boolean> = {+ revision: RTC_DIAGNOSTIC_REVISION,+ stage: message.stage,+ };+ if (typeof message.trickleEnabled === "boolean")+ result.trickleEnabled = message.trickleEnabled;+ if (+ typeof message.attemptId === "string" &&+ /^[a-z\d-]{1,80}$/i.test(message.attemptId)+ )+ result.attempt = message.attemptId.slice(0, 8);+ for (const key of [...counts, "elapsedMs", "stateCode", "errorCode"]) {+ const value = message[key];+ if (+ typeof value === "number" &&+ Number.isSafeInteger(value) &&+ value >= 0 &&+ value <= 86_400_000+ )+ result[key] = value;+ }+ for (const key of ["localKind", "remoteKind"]) {+ if (typeof message[key] === "string" && kinds.includes(message[key]))+ result[key] = message[key];+ }+ if (message.source === "bridge" || message.source === "native-deadline")+ result.source = message.source;+ if (+ typeof message.serverKind === "string" &&+ ["stun", "turn", "turns"].includes(message.serverKind)+ )+ result.serverKind = message.serverKind;+ if (+ typeof message.transportKind === "string" &&+ ["udp", "tcp", "tls"].includes(message.transportKind)+ )+ result.transportKind = message.transportKind;+ if (typeof message.reason === "string")+ result.reason = [+ "answer",+ "offer",+ "setup",+ "host",+ "transport",+ "disconnected",+ "candidates",+ "candidate-limit",+ "connect-timeout",+ "answer-timeout",+ ].includes(message.reason)+ ? message.reason+ : "other";+ return result;+}diff --git a/docs/dev-rules/remote-desktop-connectivity.md b/docs/dev-rules/remote-desktop-connectivity.mdindex 45d9564020..a4ec360ad0 100644--- a/docs/dev-rules/remote-desktop-connectivity.md+++ b/docs/dev-rules/remote-desktop-connectivity.md@@ -20,19 +20,26 @@ URL scheme/length/ports and credential lifetime are checked before bridge deliveRequire two minutes of remaining lifetime for cold capture/SDP/ICE headroom.The owning backend supplies its deployment's node pool; no new user region setting.-Missing endpoint, empty configuration, invalid response and a three-second timeout+Missing endpoint, empty configuration, invalid response and an eight-second timeoutfall back to the old public STUN list. With a valid self-hosted list, public STUNis not added. All configured nodes participate in ICE checks; a dead first nodedoes not prevent using candidates from the others. URI ordering is not a promiseof priority. Candidate statistics already distinguish direct, relay and JPEG paths.Every existing bounded media retry fetches fresh configuration on both peers.-No configuration cache, WSS reconnect or new global retry loop. The WebView bounds-its native bridge wait at 3.5 seconds. Lease/generation/attempt checks reject stale+No configuration cache, WSS reconnect or new global retry loop. All Desktop/Mobile+video and file callers share the configuration budget in+[`remoteDesktopIce.ts`](../../packages/device-link/src/remoteDesktopIce.ts).+The WebView and iOS native receiver allow another 500 ms for bridge delivery+(8.5 seconds total). Lease/generation/attempt checks reject staleresponses; explicit stop takes precedence. A failed media attempt affects only itsowner. Credential expiry may require rebuilding the connection; this change doesnot promise uninterrupted in-place renewal of TURN allocations.+Regression coverage includes slow configuration, bounded fallback and late-response+isolation in the [resolver tests](../../packages/device-link/src/__tests__/remoteDesktopIceConfig.test.ts)+and [viewer tests](../../apps/mobile/src/remote-desktop/__tests__/viewerRtc.test.ts).+Old clients continue unchanged. New viewer + old Desktop can still use viewer-sideTURN; old viewer + new Desktop can use host-side TURN. Existing full-SDP and trickleICE capabilities stay unchanged. The desktop-video connectivity change adds no new wire kinds or native dependencies.@@ -209,6 +216,11 @@ relay envelope kind or server file API. Both peers use the existing ICE endpointICE chooses a direct or TURN path. The file channel does not share desktop video,input handling, capture permissions or capture-process lifetime.+Desktop prepares the file-transfer host (up to 10 seconds) and fetches ICE+configuration (up to 8 seconds) concurrently, then rechecks the owning connection+before issuing the 15-second media command. This keeps the cold-start stages within+25 seconds and retains headroom inside the unchanged 30-second RPC budget.+File access has two layers. `packages/device-link/src/fileAccess.ts` owns theshared directory/text operation facade and whole-file transfer selection; Desktopand Mobile adapters provide platform I/O. Sidebar downloads, message files/media,diff --git a/docs/remote-desktop.md b/docs/remote-desktop.mdindex be0b87cf2b..7ca5b7e0d5 100644--- a/docs/remote-desktop.md+++ b/docs/remote-desktop.md@@ -167,8 +167,10 @@ labeled compatibility mode: JPEG at at most 1280 pixels per dimension, at most180 KB before base64, one frame in flight, and no more than four capture requestsper second. Images are transient and pass through the authenticated TLS relay.This mode trades frame rate and clarity for reachability. It is suitable for-ordinary desktop work, not game streaming. A production TURN service is the-follow-up needed for consistently smooth video across restrictive networks.+ordinary desktop work, not game streaming. Clients also support authenticated,+short-lived TURN configuration as described in+[connectivity](dev-rules/remote-desktop-connectivity.md); actual relay availability+depends on the service deployment.### Incremental ICE and media recovery@@ -218,8 +220,9 @@ not repeatedly start media attempts.For mainland-China deployment, restrictive NAT and UDP-blocked networks stillneed authenticated regional TURN with short-lived credentials and UDP plus-TCP/TLS fallback, tested across carriers. This change does not provision that-infrastructure or add an unconfigured TURN option. Native ICE retains available+TCP/TLS fallback, tested across carriers. Clients fetch deployed TURN configuration+through the authenticated ICE endpoint; this does not itself provision relay+infrastructure. Native ICE retains availableLAN, IPv6 and overlay-network candidates; being on Tailscale does not itselfprove that the media path is direct.diff --git a/packages/device-link/src/__tests__/remoteDesktopIceConfig.test.ts b/packages/device-link/src/__tests__/remoteDesktopIceConfig.test.tsindex 39a58ac478..dda5df1689 100644--- a/packages/device-link/src/__tests__/remoteDesktopIceConfig.test.ts+++ b/packages/device-link/src/__tests__/remoteDesktopIceConfig.test.ts@@ -26,6 +26,97 @@ const config = () => ({});afterEach(() => vi.useRealTimers());+it("accepts slow configuration for every caller and keeps independent requests bounded", async () => {+ vi.useFakeTimers();+ const diagnostic = vi.fn();+ const delayed = resolveDesktopIceServers(+ () => new Promise((resolve) => setTimeout(() => resolve(config()), 5_000)),+ diagnostic,+ );+ const independent = resolveDesktopIceServers(async () => config());+ await vi.advanceTimersByTimeAsync(3_000);+ expect(await independent).toEqual(servers);+ expect(diagnostic).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(2_000);+ expect(await delayed).toEqual(servers);+ const stalled = resolveDesktopIceServers(+ () => new Promise(() => {}),+ diagnostic,+ );+ await vi.advanceTimersByTimeAsync(REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS - 1);+ expect(diagnostic).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(1);+ expect((await stalled).every((server) => !server.credential)).toBe(true);+ expect(diagnostic.mock.lastCall?.[0].outcome).toBe("timeout");+ expect(vi.getTimerCount()).toBe(0);+});++it("reports only safe result categories and counts without altering returned configuration", async () => {+ const diagnostic = vi.fn();+ expect(+ await resolveDesktopIceServers(async () => config(), diagnostic),+ ).toEqual(servers);+ expect(diagnostic).toHaveBeenLastCalledWith({+ outcome: "configured",+ elapsedMs: expect.any(Number),+ serverCount: 2,+ turnUrlCount: 2,+ });+ for (const [fetch, outcome] of [+ [async () => ({ iceServers: [], expiresAt: null }), "empty"],+ [async () => ({ secret: "private" }), "invalid"],+ [+ async () => {+ throw Object.assign(new Error("private upstream body"), {+ status: 503,+ });+ },+ "request-failed",+ ],+ ] as const) {+ await resolveDesktopIceServers(fetch, diagnostic);+ expect(diagnostic.mock.lastCall?.[0]).toMatchObject({+ outcome,+ turnUrlCount: 0,+ });+ }+ expect(diagnostic.mock.lastCall?.[0].status).toBe(503);+ expect(JSON.stringify(diagnostic.mock.calls)).not.toMatch(+ /primary|backup|temporary|private|test-only/,+ );+ expect(+ await resolveDesktopIceServers(+ async () => config(),+ () => {+ throw new Error("sink");+ },+ ),+ ).toEqual(servers);+});++it("reports the deadline once and does not emit a late success", async () => {+ vi.useFakeTimers();+ const diagnostic = vi.fn();+ let finish!: (value: unknown) => void;+ const result = resolveDesktopIceServers(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ diagnostic,+ );+ await vi.advanceTimersByTimeAsync(REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS);+ await result;+ expect(diagnostic).toHaveBeenCalledTimes(1);+ expect(diagnostic.mock.lastCall?.[0]).toMatchObject({+ outcome: "timeout",+ turnUrlCount: 0,+ });+ finish(config());+ await Promise.resolve();+ expect(diagnostic).toHaveBeenCalledTimes(1);+});+it("passes all independent nodes to ICE, strips unrelated response secrets, and reloads on retry", async () => {const fetchConfig = vi.fn(async () => ({...config(),diff --git a/packages/device-link/src/remoteDesktopIce.ts b/packages/device-link/src/remoteDesktopIce.tsindex 92d33f9166..34ddbd8b48 100644--- a/packages/device-link/src/remoteDesktopIce.ts+++ b/packages/device-link/src/remoteDesktopIce.ts@@ -23,6 +23,9 @@ export const REMOTE_DESKTOP_ICE_SERVERS = [{ urls: "stun:stun.cloudflare.com:3478" },{ urls: "stun:stun.l.google.com:19302" },];+// Shared by every TURN configuration fetch (desktop/mobile, video/files).+// Viewer shells allow bridge delivery after this bounded HTTP/resolver budget.+export const REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS = 8_000;// Sequential host stages, followed by transport and WebView delivery headroom.// Keep the outer waits derived from these limits so a valid cold start is not discarded.export const REMOTE_DESKTOP_OFFER_BUDGET = {@@ -38,8 +41,11 @@ export const REMOTE_DESKTOP_INVOKE_MS =REMOTE_DESKTOP_OFFER_BUDGET.platformStatusMs +REMOTE_DESKTOP_OFFER_BUDGET.platformHandshakeMs +REMOTE_DESKTOP_OFFER_BUDGET.sourcesMs +- REMOTE_DESKTOP_OFFER_BUDGET.hostMs + 5_000;+ REMOTE_DESKTOP_OFFER_BUDGET.hostMs ++ 5_000;export const REMOTE_DESKTOP_NETWORK = {+ iceConfigMs: REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,+ iceConfigBridgeMs: 500,maxCandidates: 128,batchSize: 16,pollMs: 250,diff --git a/packages/device-link/src/remoteDesktopIceConfig.ts b/packages/device-link/src/remoteDesktopIceConfig.tsindex 5ce6db3560..5229215b49 100644--- a/packages/device-link/src/remoteDesktopIceConfig.ts+++ b/packages/device-link/src/remoteDesktopIceConfig.ts@@ -1,13 +1,25 @@-import { REMOTE_DESKTOP_ICE_SERVERS } from "./remoteDesktopIce.js";+import {+ REMOTE_DESKTOP_ICE_SERVERS,+ REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,+} from "./remoteDesktopIce.js";+export { REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS } from "./remoteDesktopIce.js";export const REMOTE_DESKTOP_ICE_CONFIG_PATH = "/api/device-link/ice-servers";-export const REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS = 3000;export interface DesktopIceServer {urls: string[];username?: string;credential?: string;}+/** Counts and fixed outcomes only; never expose URLs, credentials or upstream errors. */+export interface DesktopIceConfigDiagnostic {+ outcome: "configured" | "empty" | "invalid" | "timeout" | "request-failed";+ elapsedMs: number;+ serverCount: number;+ turnUrlCount: number;+ status?: number;+}+const ICE_URL =/^(stun|turn|turns):(?:[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?|\[[0-9a-fA-F:]+\]):([0-9]{1,5})(\?transport=(udp|tcp))?$/;@@ -83,24 +95,54 @@ export function parseDesktopIceConfig(/** Per attempt, no credential cache. A slow/missing API must not hold up legacy connectivity. */export async function resolveDesktopIceServers(fetchConfig: () => Promise<unknown>,+ diagnostic?: (result: DesktopIceConfigDiagnostic) => void,): Promise<DesktopIceServer[]> {let timer: ReturnType<typeof setTimeout> | undefined;+ const started = performance.now();+ let outcome: DesktopIceConfigDiagnostic["outcome"] = "request-failed";+ let status: number | undefined;+ let servers: DesktopIceServer[] = [];+ let validating = false;try {const value = await Promise.race([Promise.resolve().then(fetchConfig),new Promise<never>((_, reject) => {- timer = setTimeout(- () => reject(new Error("ICE_CONFIG_TIMEOUT")),- REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,- );+ timer = setTimeout(() => {+ outcome = "timeout";+ reject(new Error("ICE_CONFIG_TIMEOUT"));+ }, REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS);}),]);- const servers = parseDesktopIceConfig(value);- if (servers.length) return servers;- } catch {- // No upstream body/error/credential logging. Existing JPEG fallback is independent.+ validating = true;+ servers = parseDesktopIceConfig(value);+ outcome = servers.length ? "configured" : "empty";+ } catch (error) {+ if (validating) outcome = "invalid";+ // Inspect only an own numeric status; never read arbitrary error getters/text.+ if (error && typeof error === "object") {+ const value = Object.getOwnPropertyDescriptor(error, "status")?.value;+ if (Number.isInteger(value) && value >= 400 && value <= 599)+ status = value;+ }} finally {clearTimeout(timer);}- return REMOTE_DESKTOP_ICE_SERVERS.map((server) => ({ urls: [server.urls] }));+ if (!servers.length)+ servers = REMOTE_DESKTOP_ICE_SERVERS.map((server) => ({+ urls: [server.urls],+ }));+ try {+ diagnostic?.({+ outcome,+ elapsedMs: Math.max(0, Math.round(performance.now() - started)),+ serverCount: servers.length,+ turnUrlCount: servers+ .flatMap((server) => server.urls)+ .filter((url) => /^turns?:/.test(url)).length,+ ...(status === undefined ? {} : { status }),+ });+ } catch {+ /* Diagnostics must never change connectivity. */+ }+ return servers;}diff --git a/packages/maker-shared/src/remote-desktop/viewerRuntime.js b/packages/maker-shared/src/remote-desktop/viewerRuntime.jsindex e7dff4b130..003da4690d 100644--- a/packages/maker-shared/src/remote-desktop/viewerRuntime.js+++ b/packages/maker-shared/src/remote-desktop/viewerRuntime.js@@ -1596,12 +1596,15 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {return;}configPending = true;- deadlineTimer = setTimeout(() => {- if (g === generation && configPending) {- configPending = false;- void startRtc(g, iceServers);- }- }, 3500);+ deadlineTimer = setTimeout(+ () => {+ if (g === generation && configPending) {+ configPending = false;+ void startRtc(g, iceServers);+ }+ },+ (net.iceConfigMs ?? 8000) + (net.iceConfigBridgeMs ?? 500),+ );return post({ type: "iceConfig", attemptId });}async function receiveIceConfig(message) {diff --git a/packages/maker-shared/src/remote-desktop/viewerScripts.ts b/packages/maker-shared/src/remote-desktop/viewerScripts.tsindex 32e79d2c17..1f21cf0153 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 if (typeof startBackgroundLoop === \"function\") startBackgroundLoop();\n post({ type: \"streaming\", attemptId });\n post({\n type: \"pipCapability\",\n supported: !!(\n video.webkitSupportsPresentationMode?.(\"picture-in-picture\") ||\n document.pictureInPictureEnabled\n ),\n });\n });\n });\n }\n function waitForVideoFrame(g) {\n if (g !== generation) return;\n if (\n video.readyState >= 2 &&\n video.videoWidth > 0 &&\n video.videoHeight > 0\n ) {\n revealVideo(g);\n return;\n }\n videoPaintCallback = requestAnimationFrame(() => waitForVideoFrame(g));\n }\n let retryTimer = null,\n deadlineTimer = null,\n disconnectTimer = null,\n stableTimer = null,\n iceTimer = null,\n gatherTimer = null,\n gatherDone = null;\n let localCandidates = [],\n localAck = 0,\n remoteAfter = 0,\n icePending = null,\n remoteSeen = new Set(),\n exchangeUntil = 0,\n remoteComplete = false;\n function clearRtcTimers() {\n for (const timer of [\n retryTimer,\n deadlineTimer,\n disconnectTimer,\n stableTimer,\n iceTimer,\n gatherTimer,\n ])\n clearTimeout(timer);\n retryTimer =\n deadlineTimer =\n disconnectTimer =\n stableTimer =\n iceTimer =\n gatherTimer =\n null;\n if (gatherDone) {\n gatherDone();\n gatherDone = null;\n }\n }\n function closeRtc(preserveFrame = true) {\n configPending = false;\n if (preserveFrame) retainFrame();\n generation++;\n clearRtcTimers();\n cancelVideoHandoff();\n videoPresented = false;\n localCandidates = [];\n localAck = remoteAfter = 0;\n icePending = null;\n remoteSeen = new Set();\n attemptId = null;\n clearInterval(statsTimer);\n statsTimer = null;\n statsSample = null;\n if (dc) dc.close();\n if (pc) pc.close();\n pc = null;\n dc = null;\n video.onplaying = null;\n video.srcObject = null;\n video.style.display = \"none\";\n video.style.zIndex = \"0\";\n image.style.display = \"block\";\n if (typeof stopBackgroundLoop === \"function\") stopBackgroundLoop();\n if (!preserveFrame) {\n image.removeAttribute(\"src\");\n if (typeof clearBackground === \"function\") clearBackground();\n }\n }\n function failRtc(reason, canRetry = true) {\n const failedAttempt = attemptId;\n release();\n closeRtc();\n post({ type: \"fallback\", attemptId: failedAttempt, reason });\n // Local consent is bounded by the host's picker lifetime. Reuse this retry\n // timer without consuming the finite network-recovery attempts.\n const capturePending = reason === \"capture-pending\";\n if (canRetry && epoch && (capturePending || retries < net.retryMs.length)) {\n const delay = capturePending\n ? net.retryMs[net.retryMs.length - 1]\n : net.retryMs[retries++];\n retryTimer = setTimeout(() => {\n retryTimer = null;\n if (epoch) connect();\n }, delay);\n }\n }\n function pollIce() {\n if (\n !pc ||\n !trickleIce ||\n !pc.remoteDescription ||\n icePending ||\n Date.now() >= exchangeUntil\n )\n return;\n const candidates = localCandidates.slice(\n localAck,\n localAck + net.batchSize,\n );\n icePending = {\n after: remoteAfter,\n sent: candidates.length,\n exchangeId: ++exchangeId,\n };\n post({\n type: \"ice\",\n attemptId,\n candidates,\n after: remoteAfter,\n exchangeId,\n });\n iceTimer = setTimeout(() => {\n icePending = null;\n pollIce();\n }, 4500);\n }\n async function receiveIce(message) {\n if (\n !pc ||\n !icePending ||\n message.attemptId !== attemptId ||\n message.exchangeId !== icePending.exchangeId\n )\n return;\n const rtc = pc,\n g = generation,\n batch = icePending;\n clearTimeout(iceTimer);\n try {\n if (message.error) {\n icePending = null;\n iceTimer = setTimeout(pollIce, 1000);\n return;\n }\n if (\n !Array.isArray(message.candidates) ||\n message.candidates.length > net.batchSize ||\n message.next !== batch.after + message.candidates.length ||\n message.next > net.maxCandidates\n )\n throw new Error();\n for (const candidate of message.candidates) {\n if (g !== generation) return;\n const key = JSON.stringify(candidate);\n if (remoteSeen.has(key)) continue;\n if (remoteSeen.size >= net.maxCandidates) throw new Error();\n await rtc.addIceCandidate(candidate);\n if (g !== generation) return;\n remoteSeen.add(key);\n }\n if (g !== generation) return;\n localAck += batch.sent;\n remoteAfter = message.next;\n remoteComplete = message.complete === true;\n icePending = null;\n if (!(\n remoteComplete &&\n rtc.iceGatheringState === \"complete\" &&\n localAck === localCandidates.length\n ))\n iceTimer = setTimeout(pollIce, net.pollMs);\n } catch {\n if (g === generation) failRtc(\"candidates\");\n }\n }\n async function receiveAnswer(message) {\n if (!pc || message.attemptId !== attemptId) return;\n const rtc = pc,\n g = generation;\n try {\n await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n if (g !== generation) return;\n clearTimeout(deadlineTimer);\n deadlineTimer = setTimeout(() => {\n if (g === generation && rtc.connectionState !== \"connected\")\n failRtc(\"connect-timeout\");\n }, net.connectMs);\n exchangeUntil = Date.now() + net.exchangeMs;\n pollIce();\n } catch {\n if (g === generation) failRtc(\"answer\");\n }\n }\n async function connect() {\n closeRtc();\n const g = generation;\n attemptId = String(g);\n if (!window.RTCPeerConnection) {\n failRtc(\"unsupported\", false);\n return;\n }\n configPending = true;\n deadlineTimer = setTimeout(() => {\n 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_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 // Local consent is bounded by the host's picker lifetime. Reuse this retry\n // timer without consuming the finite network-recovery attempts.\n const capturePending = reason === \"capture-pending\";\n if (canRetry && epoch && (capturePending || retries < net.retryMs.length)) {\n const delay = capturePending\n ? net.retryMs[net.retryMs.length - 1]\n : net.retryMs[retries++];\n retryTimer = setTimeout(() => {\n retryTimer = null;\n if (epoch) connect();\n }, delay);\n }\n }\n function pollIce() {\n if (\n !pc ||\n !trickleIce ||\n !pc.remoteDescription ||\n icePending ||\n Date.now() >= exchangeUntil\n )\n return;\n const candidates = localCandidates.slice(\n localAck,\n localAck + net.batchSize,\n );\n icePending = {\n after: remoteAfter,\n sent: candidates.length,\n exchangeId: ++exchangeId,\n };\n post({\n type: \"ice\",\n attemptId,\n candidates,\n after: remoteAfter,\n exchangeId,\n });\n iceTimer = setTimeout(() => {\n icePending = null;\n pollIce();\n }, 4500);\n }\n async function receiveIce(message) {\n if (\n !pc ||\n !icePending ||\n message.attemptId !== attemptId ||\n message.exchangeId !== icePending.exchangeId\n )\n return;\n const rtc = pc,\n g = generation,\n batch = icePending;\n clearTimeout(iceTimer);\n try {\n if (message.error) {\n icePending = null;\n iceTimer = setTimeout(pollIce, 1000);\n return;\n }\n if (\n !Array.isArray(message.candidates) ||\n message.candidates.length > net.batchSize ||\n message.next !== batch.after + message.candidates.length ||\n message.next > net.maxCandidates\n )\n throw new Error();\n for (const candidate of message.candidates) {\n if (g !== generation) return;\n const key = JSON.stringify(candidate);\n if (remoteSeen.has(key)) continue;\n if (remoteSeen.size >= net.maxCandidates) throw new Error();\n await rtc.addIceCandidate(candidate);\n if (g !== generation) return;\n remoteSeen.add(key);\n }\n if (g !== generation) return;\n localAck += batch.sent;\n remoteAfter = message.next;\n remoteComplete = message.complete === true;\n icePending = null;\n if (!(\n remoteComplete &&\n rtc.iceGatheringState === \"complete\" &&\n localAck === localCandidates.length\n ))\n iceTimer = setTimeout(pollIce, net.pollMs);\n } catch {\n if (g === generation) failRtc(\"candidates\");\n }\n }\n async function receiveAnswer(message) {\n if (!pc || message.attemptId !== attemptId) return;\n const rtc = pc,\n g = generation;\n try {\n await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n if (g !== generation) return;\n clearTimeout(deadlineTimer);\n deadlineTimer = setTimeout(() => {\n if (g === generation && rtc.connectionState !== \"connected\")\n failRtc(\"connect-timeout\");\n }, net.connectMs);\n exchangeUntil = Date.now() + net.exchangeMs;\n pollIce();\n } catch {\n if (g === generation) failRtc(\"answer\");\n }\n }\n async function connect() {\n closeRtc();\n const g = generation;\n attemptId = String(g);\n if (!window.RTCPeerConnection) {\n failRtc(\"unsupported\", false);\n return;\n }\n configPending = true;\n deadlineTimer = setTimeout(\n () => {\n if (g === generation && configPending) {\n configPending = false;\n void startRtc(g, iceServers);\n }\n },\n (net.iceConfigMs ?? 8000) + (net.iceConfigBridgeMs ?? 500),\n );\n return post({ type: \"iceConfig\", attemptId });\n }\n async function receiveIceConfig(message) {\n if (!epoch || !configPending || message.attemptId !== attemptId) return;\n configPending = false;\n clearTimeout(deadlineTimer);\n deadlineTimer = null;\n await startRtc(generation, message.iceServers);\n }\n async function startRtc(g, servers) {\n try {\n const rtc = new RTCPeerConnection({ iceServers: servers });\n pc = rtc;\n dc = rtc.createDataChannel(\"input-v1\");\n rtc.addTransceiver(\"video\", { direction: \"recvonly\" });\n rtc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n rtc.onicecandidate = ({ candidate }) => {\n if (g !== generation || !candidate?.candidate || !trickleIce) return;\n if (localCandidates.length >= net.maxCandidates) {\n failRtc(\"candidate-limit\", false);\n return;\n }\n localCandidates.push({\n candidate: candidate.candidate,\n sdpMid: candidate.sdpMid,\n sdpMLineIndex: candidate.sdpMLineIndex,\n ...(candidate.usernameFragment\n ? { usernameFragment: candidate.usernameFragment }\n : {}),\n });\n // Gathering continues after the offer; the serial exchange flushes late addresses.\n };\n dc.onmessage = (e) => {\n try {\n if (g !== generation || pc !== rtc) return;\n if (typeof e.data !== \"string\" || e.data.length > 80000) return;\n const message = JSON.parse(e.data);\n if (message.type === \"cursor\") receiveCursor(message.cursor);\n if (\n (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 f24e3fd44c..dfa98f522c 100644--- a/packages/maker-shared/src/remote-desktop/viewerSource.ts+++ b/packages/maker-shared/src/remote-desktop/viewerSource.ts@@ -1,2 +1,2 @@// Generated by scripts/sync-remote-desktop-viewer.mjs. Do not edit.-export const DESKTOP_VIEWER_SOURCE = "/** Shared browser viewer. Mobile bundles this exact source; Desktop imports it as a CSP-safe module. */\nfunction mountRemoteDesktopViewer(root, postMessage, config) {\n const cleanups = [];\n const listen = (target, type, fn, options) => {\n target.addEventListener(type, fn, options);\n cleanups.push(() => target.removeEventListener(type, fn, options));\n };\n const find = (id) =>\n root.getElementById\n ? root.getElementById(id)\n : root.querySelector(\"#\" + id);\n const { net, iceServers } = config;\n let nativeVideoActive = false;\n const validKeys = new Set(config.keyCodes);\n const transform =\n /* BEGIN TRANSFORM */\n function desktopTransform(\n vw,\n vh,\n dw,\n dh,\n zoom,\n fx,\n fy,\n fillHeight = false,\n ) {\n const 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 viewportTopInset = 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 usableHeight = () =>\n Math.max(1, stage.clientHeight - viewportTopInset - viewportBottomInset);\n const viewportHeight = () =>\n viewerSized ? usableHeight() : Math.max(1, stage.clientHeight);\n const viewportWidth = () =>\n Math.max(\n 1,\n stage.clientWidth -\n viewportLeft() -\n (fillHeight ? viewportRightInset : 0),\n );\n // Center between the measured top controls and the keyboard edge (stage bottom).\n // The usable center is (topInset + stageHeight) / 2, so shift by topInset / 2.\n // Keep the fitted size and cap the shift when the desktop is too tall to fit.\n const verticalOffset = (height) =>\n (viewerSized ? viewportTopInset : 0) +\n (fillHeight\n ? 0\n : Math.min(\n Math.max(\n 0,\n portraitKeyboardTopInset - (viewerSized ? viewportTopInset : 0),\n ) / 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 (nativeVideoActive) {\n if (bg) bg.style.display = \"none\";\n return;\n }\n if (!bg || !bgCanvas || !bgContext) return;\n const vw = stage.clientWidth,\n vh = stage.clientHeight;\n const 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 const useVideo =\n videoPresented && video.videoWidth > 0 && video.videoHeight > 0;\n const src = useVideo ? video : image;\n // drawImage source rects live in the source's own pixel space, which can\n // differ from dw/dh; fractions of the real bitmap keep every segment lined\n // up with what the picture element actually shows.\n const sw = useVideo ? video.videoWidth : image.naturalWidth;\n const sh = useVideo ? video.videoHeight : image.naturalHeight;\n // Cursor updates can schedule a repaint while the next JPEG is loading.\n // Keep the last backdrop until the replacement has drawable pixels.\n if ((!useVideo && !image.complete) || !(sw > 0 && sh > 0)) return;\n bgContext.setTransform(bgDpr, 0, 0, bgDpr, 0, 0);\n bgContext.clearRect(0, 0, stage.clientWidth, stage.clientHeight);\n const horizontal = bgAxis === \"x\";\n const sourceLength = horizontal ? sw : sh;\n const cuts = [0, bgEdgeFraction, 1 - bgEdgeFraction, 1];\n for (let i = 0; i < bgRects.length; i++) {\n const rect = bgRects[i];\n const origin = cuts[i] * sourceLength;\n const length = (cuts[i + 1] - cuts[i]) * sourceLength;\n bgContext.drawImage(\n src,\n horizontal ? origin : 0,\n horizontal ? 0 : origin,\n horizontal ? length : sw,\n horizontal ? sh : length,\n rect.x,\n rect.y,\n rect.w,\n rect.h,\n );\n }\n }\n function scheduleBackgroundDraw() {\n if (bgDrawFrame !== null || !bgRects || !bgContext) return;\n bgDrawFrame = requestAnimationFrame(() => {\n bgDrawFrame = null;\n drawBackground();\n });\n }\n function startBackgroundLoop() {\n if (\n bgLoopFrame !== null ||\n !bgContext ||\n !bgRects ||\n !videoPresented ||\n typeof video.requestVideoFrameCallback !== \"function\"\n )\n return;\n const frame = video.requestVideoFrameCallback(() => {\n if (bgLoopFrame !== frame) return;\n bgLoopFrame = null;\n drawBackground();\n startBackgroundLoop();\n });\n bgLoopFrame = frame;\n }\n // Only the streaming loop stops here; a pending one-shot draw is harmless\n // (it re-paints the preserved frame) and must survive reconnects.\n function stopBackgroundLoop() {\n if (bgLoopFrame !== null) video.cancelVideoFrameCallback?.(bgLoopFrame);\n bgLoopFrame = null;\n }\n function clearBackground() {\n stopBackgroundLoop();\n bgRects = null;\n // Resizing a canvas resets its bitmap; same-value assignment still clears.\n if (bgCanvas) bgCanvas.width = bgCanvas.width;\n }\n listen(image, \"load\", () => scheduleBackgroundDraw());\n // Older WebViews update the ambient layer on media progress, never with an\n // idle display-refresh loop. Geometry changes still get a one-shot repaint.\n listen(video, \"timeupdate\", () => {\n if (videoPresented && typeof video.requestVideoFrameCallback !== \"function\")\n scheduleBackgroundDraw();\n });\n function panBounds(r) {\n const vw = viewportWidth(),\n vh = viewportHeight();\n // Grow extra resting travel continuously from zero at fit to 180 screen\n // points at maximum zoom. Never count the unused space of a fitting axis.\n const clearance = (180 * (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(\n bottom - 1,\n (viewerSized ? viewportTopInset : 0) + 8 + hotY,\n );\n return {\n minX,\n maxX: Math.max(minX, right - 8 - (w - hotX)),\n minY,\n maxY: Math.max(minY, bottom - 8 - (h - hotY)),\n };\n }\n function moveTouchpad(dx, dy) {\n stopPanAnimation();\n const r = layout(),\n v = cursorViewport();\n if (cursorNeedsEntry) {\n // Re-enter at the nearest visible edge; do not pull a manually positioned\n // desktop back to the old off-screen cursor before applying this movement.\n cx = clamp((bounded(r.x + cx * r.width, v.minX, v.maxX) - r.x) / r.width);\n cy = clamp(\n (bounded(r.y + cy * r.height, v.minY, v.maxY) - r.y) / r.height,\n );\n cursorNeedsEntry = false;\n }\n cx = clamp(cx + dx / r.width);\n cy = clamp(cy + dy / r.height);\n const x = r.x + cx * r.width,\n y = r.y + cy * r.height;\n if (\n zoom > 1 ||\n r.width > viewportWidth() ||\n r.height > stage.clientHeight - viewportBottomInset\n ) {\n place(\n r.x + bounded(x, v.minX, v.maxX) - x,\n r.y + bounded(y, v.minY, v.maxY) - y,\n r,\n );\n followRest = { fx, fy, zoom };\n }\n manualViewMoved = false;\n }\n function stopPanAnimation() {\n if (panAnimation !== null) cancelAnimationFrame(panAnimation);\n panAnimation = null;\n }\n function settlePan() {\n stopPanAnimation();\n const r = layout(),\n b = panBounds(r),\n x = bounded(r.x, b.minX, b.maxX),\n y = bounded(r.y, b.minY, b.maxY);\n if (x === r.x && y === r.y) return;\n if (reducedMotion.matches) {\n place(x, y, r);\n render();\n return;\n }\n const started = performance.now();\n const tick = (now) => {\n const t = Math.min(1, (now - started) / 280),\n ease = 1 - Math.pow(1 - t, 3);\n place(r.x + (x - r.x) * ease, r.y + (y - r.y) * ease, r);\n render();\n panAnimation = t < 1 ? requestAnimationFrame(tick) : null;\n };\n panAnimation = requestAnimationFrame(tick);\n }\n function render() {\n const r = layout();\n if (config.nativeMedia && epoch)\n post({\n type: \"nativeViewport\",\n fillHeight,\n x: r.x,\n y: r.y,\n width: r.width,\n height: r.height,\n });\n const touchFeedback = control && mode === \"touch\" && touchCursorVisible;\n const cursorX = mode === \"touch\" && touchCursor ? touchCursor.x : cx;\n const cursorY = mode === \"touch\" && touchCursor ? touchCursor.y : cy;\n cursor.style.transition =\n mode === \"touch\" && !touchFeedback && !reducedMotion.matches\n ? \"opacity 120ms ease-out\"\n : \"none\";\n for (const el of [image, video]) {\n el.style.width = r.width + \"px\";\n el.style.height = r.height + \"px\";\n el.style.left = r.x + \"px\";\n el.style.top = r.y + \"px\";\n }\n 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: usableHeight(),\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 // Local consent is bounded by the host's picker lifetime. Reuse this retry\n // timer without consuming the finite network-recovery attempts.\n const capturePending = reason === \"capture-pending\";\n if (canRetry && epoch && (capturePending || retries < net.retryMs.length)) {\n const delay = capturePending\n ? net.retryMs[net.retryMs.length - 1]\n : net.retryMs[retries++];\n retryTimer = setTimeout(() => {\n retryTimer = null;\n if (epoch) connect();\n }, delay);\n }\n }\n function pollIce() {\n if (\n !pc ||\n !trickleIce ||\n !pc.remoteDescription ||\n icePending ||\n Date.now() >= exchangeUntil\n )\n return;\n const candidates = localCandidates.slice(\n localAck,\n localAck + net.batchSize,\n );\n icePending = {\n after: remoteAfter,\n sent: candidates.length,\n exchangeId: ++exchangeId,\n };\n post({\n type: \"ice\",\n attemptId,\n candidates,\n after: remoteAfter,\n exchangeId,\n });\n iceTimer = setTimeout(() => {\n icePending = null;\n pollIce();\n }, 4500);\n }\n async function receiveIce(message) {\n if (\n !pc ||\n !icePending ||\n message.attemptId !== attemptId ||\n message.exchangeId !== icePending.exchangeId\n )\n return;\n const rtc = pc,\n g = generation,\n batch = icePending;\n clearTimeout(iceTimer);\n try {\n if (message.error) {\n icePending = null;\n iceTimer = setTimeout(pollIce, 1000);\n return;\n }\n if (\n !Array.isArray(message.candidates) ||\n message.candidates.length > net.batchSize ||\n message.next !== batch.after + message.candidates.length ||\n message.next > net.maxCandidates\n )\n throw new Error();\n for (const candidate of message.candidates) {\n if (g !== generation) return;\n const key = JSON.stringify(candidate);\n if (remoteSeen.has(key)) continue;\n if (remoteSeen.size >= net.maxCandidates) throw new Error();\n await rtc.addIceCandidate(candidate);\n if (g !== generation) return;\n remoteSeen.add(key);\n }\n if (g !== generation) return;\n localAck += batch.sent;\n remoteAfter = message.next;\n remoteComplete = message.complete === true;\n icePending = null;\n if (!(\n remoteComplete &&\n rtc.iceGatheringState === \"complete\" &&\n localAck === localCandidates.length\n ))\n iceTimer = setTimeout(pollIce, net.pollMs);\n } catch {\n if (g === generation) failRtc(\"candidates\");\n }\n }\n async function receiveAnswer(message) {\n if (!pc || message.attemptId !== attemptId) return;\n const rtc = pc,\n g = generation;\n try {\n await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n if (g !== generation) return;\n clearTimeout(deadlineTimer);\n deadlineTimer = setTimeout(() => {\n if (g === generation && rtc.connectionState !== \"connected\")\n failRtc(\"connect-timeout\");\n }, net.connectMs);\n exchangeUntil = Date.now() + net.exchangeMs;\n pollIce();\n } catch {\n if (g === generation) failRtc(\"answer\");\n }\n }\n async function connect() {\n closeRtc();\n const g = generation;\n attemptId = String(g);\n if (!window.RTCPeerConnection) {\n failRtc(\"unsupported\", false);\n return;\n }\n configPending = true;\n deadlineTimer = setTimeout(() => {\n 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: usableHeight(),\n });\n break;\n case \"presentation\":\n if (config.nativeMedia) {\n release();\n showKeyboard(false);\n break;\n }\n try {\n if (message.enabled) {\n release();\n showKeyboard(false);\n if (video.webkitSupportsPresentationMode?.(\"picture-in-picture\"))\n video.webkitSetPresentationMode(\"picture-in-picture\");\n else if (video.requestPictureInPicture)\n video\n .requestPictureInPicture()\n .catch(() => post({ type: \"presentationFailed\" }));\n else post({ type: \"presentationFailed\" });\n } else if (video.webkitSetPresentationMode)\n video.webkitSetPresentationMode(\"inline\");\n else if (document.pictureInPictureElement)\n document.exitPictureInPicture().catch(() => {});\n } catch {\n post({ type: \"presentationFailed\" });\n }\n break;\n case \"videoSettings\":\n if (\n Number.isInteger(message.width) &&\n Number.isInteger(message.height) &&\n message.width >= 320 &&\n message.height >= 320 &&\n (message.restore === true ||\n (message.width <= 2560 && message.height <= 2560))\n ) {\n release();\n stopPanAnimation();\n viewerSized = message.restore !== true;\n zoom = 1;\n fx = fy = 0.5;\n followRest = null;\n dw = message.width;\n dh = message.height;\n render();\n }\n video.muted = !message.audio;\n retries = 0;\n if (!config.nativeMedia) connect();\n break;\n case \"keyboard\":\n showKeyboard(message.enabled === true);\n break;\n case \"resume\":\n if (video.srcObject) video.play().catch(() => {});\n break;\n case \"releaseInput\":\n release();\n break;\n case \"theme\":\n if (/^#[0-9a-f]{3,8}$/i.test(message.surface)) {\n document.body.style.background = config.nativeMedia\n ? \"transparent\"\n : message.surface;\n document.documentElement.style.background = config.nativeMedia\n ? \"transparent\"\n : message.surface;\n document.documentElement.style.setProperty(\n \"--surface\",\n message.surface,\n );\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.foreground)) {\n cursor.style.borderColor = message.foreground;\n document.documentElement.style.setProperty(\n \"--foreground\",\n message.foreground,\n );\n }\n break;\n case \"networkStatus\": {\n const status = 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 previousTopInset = viewportTopInset,\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.topInset))\n viewportTopInset = Math.max(\n 0,\n Math.min(stage.clientHeight - 1, message.topInset),\n );\n if (Number.isFinite(message.bottomInset))\n viewportBottomInset = Math.max(\n 0,\n Math.min(stage.clientHeight - 1, message.bottomInset),\n );\n if (Number.isFinite(message.leftInset)) {\n const inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.leftInset),\n );\n sideInsetsChanged = sideInsetsChanged || inset !== viewportLeftInset;\n viewportLeftInset = inset;\n }\n if (Number.isFinite(message.rightInset)) {\n const inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.rightInset),\n );\n sideInsetsChanged = sideInsetsChanged || inset !== viewportRightInset;\n viewportRightInset = inset;\n }\n // Hiding the side toolbar changes the viewport center. Keep the image's\n // actual horizontal position instead of following that center sideways.\n if (keepHorizontal) {\n stopPanAnimation();\n const r = layout();\n place(before.x, r.y, r);\n }\n const keyboardInset = keyboardOpen ? viewportBottomInset : 0;\n if (keyboardInset !== keyboardViewportInset) {\n const wasOpen = keyboardViewportInset > 0;\n keyboardViewportInset = keyboardInset;\n if (fillHeight && (keyboardInset > 0 || wasOpen)) {\n const r = layout(),\n v = cursorViewport();\n place(r.x, (v.minY + v.maxY) / 2 - cy * r.height, r);\n cursorNeedsEntry = false;\n manualViewMoved = false;\n }\n }\n if (keepHorizontal) {\n // Restoring the toolbar can cover the cursor even after a zero-height opening.\n if (!keyboardOpen || keyboardInset > 0) {\n const r = layout(),\n v = cursorViewport(),\n x = r.x + cx * r.width;\n place(r.x + bounded(x, v.minX, v.maxX) - x, r.y, r);\n }\n followRest = { fx, fy, zoom };\n render();\n } else if (\n sideInsetsChanged ||\n offsetChanged ||\n (viewerSized && previousTopInset !== viewportTopInset) ||\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 nativeVideoActive = false;\n image.style.visibility = \"visible\";\n viewerSized = false;\n followRest = null;\n cursorNeedsEntry = true;\n stopPanAnimation();\n resetCursor();\n control = false;\n release();\n pending = [];\n sending = false;\n seq = 0;\n epoch = message.epoch;\n clipboardShortcuts =\n config.desktop && message.clipboardShortcuts === true;\n clipboardModifier =\n message.clipboardModifier === \"meta\" ? \"meta\" : \"control\";\n dw = message.width;\n dh = message.height;\n fillHeight = message.fillHeight === true;\n video.muted = !message.audio;\n trickleIce = message.trickleIce === true;\n retries = 0;\n render();\n if (!config.nativeMedia) connect();\n break;\n case \"nativeVideo\":\n if (!config.nativeMedia || message.epoch !== epoch) break;\n nativeVideoActive = message.active === true;\n image.style.visibility = nativeVideoActive ? \"hidden\" : \"visible\";\n paintBackground();\n break;\n case \"nativeCursor\":\n if (config.nativeMedia && message.epoch === epoch)\n receiveCursor(message.cursor);\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(\n message.capturePending === true ? \"capture-pending\" : \"host\",\n message.retry !== false,\n );\n break;\n case \"frame\": {\n if (\"cursor\" in message) receiveCursor(message.cursor);\n else resetCursor();\n const frameEpoch = epoch;\n image.onload = () => {\n if (epoch === frameEpoch) {\n scheduleBackgroundDraw();\n post({ type: \"framePresented\" });\n }\n };\n image.src = \"data:image/jpeg;base64,\" + message.jpeg;\n break;\n }\n case \"control\":\n release();\n 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 nativeVideoActive = false;\n image.style.visibility = \"visible\";\n showKeyboard(false);\n control = false;\n release();\n pending = [];\n sending = false;\n epoch = null;\n closeRtc(message.preserveFrame === true);\n updateMouseButtons();\n render();\n break;\n }\n }\n // iOS can report equal left/right safe areas in both landscape directions.\n // Its interface angle distinguishes the notch side even on a 180-degree turn.\n const reportOrientation = () => {\n const angle =\n typeof window.orientation === \"number\"\n ? window.orientation\n : window.screen?.orientation?.angle;\n if (Number.isFinite(angle)) post({ type: \"orientation\", angle });\n };\n listen(window, \"orientationchange\", reportOrientation);\n if (window.screen?.orientation?.addEventListener)\n listen(window.screen.orientation, \"change\", reportOrientation);\n render();\n reportOrientation();\n post({ type: \"ready\" });\n return {\n receive: (message) => receive({ data: JSON.stringify(message) }),\n dispose: () => {\n release();\n epoch = null;\n closeRtc(false);\n if (bgDrawFrame !== null) cancelAnimationFrame(bgDrawFrame);\n bgDrawFrame = null;\n for (const cleanup of cleanups) cleanup();\n },\n };\n}\n";+export const DESKTOP_VIEWER_SOURCE = "/** Shared browser viewer. Mobile bundles this exact source; Desktop imports it as a CSP-safe module. */\nfunction mountRemoteDesktopViewer(root, postMessage, config) {\n const cleanups = [];\n const listen = (target, type, fn, options) => {\n target.addEventListener(type, fn, options);\n cleanups.push(() => target.removeEventListener(type, fn, options));\n };\n const find = (id) =>\n root.getElementById\n ? root.getElementById(id)\n : root.querySelector(\"#\" + id);\n const { net, iceServers } = config;\n let nativeVideoActive = false;\n const validKeys = new Set(config.keyCodes);\n const transform =\n /* BEGIN TRANSFORM */\n function desktopTransform(\n vw,\n vh,\n dw,\n dh,\n zoom,\n fx,\n fy,\n fillHeight = false,\n ) {\n const 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 viewportTopInset = 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 usableHeight = () =>\n Math.max(1, stage.clientHeight - viewportTopInset - viewportBottomInset);\n const viewportHeight = () =>\n viewerSized ? usableHeight() : Math.max(1, stage.clientHeight);\n const viewportWidth = () =>\n Math.max(\n 1,\n stage.clientWidth -\n viewportLeft() -\n (fillHeight ? viewportRightInset : 0),\n );\n // Center between the measured top controls and the keyboard edge (stage bottom).\n // The usable center is (topInset + stageHeight) / 2, so shift by topInset / 2.\n // Keep the fitted size and cap the shift when the desktop is too tall to fit.\n const verticalOffset = (height) =>\n (viewerSized ? viewportTopInset : 0) +\n (fillHeight\n ? 0\n : Math.min(\n Math.max(\n 0,\n portraitKeyboardTopInset - (viewerSized ? viewportTopInset : 0),\n ) / 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 (nativeVideoActive) {\n if (bg) bg.style.display = \"none\";\n return;\n }\n if (!bg || !bgCanvas || !bgContext) return;\n const vw = stage.clientWidth,\n vh = stage.clientHeight;\n const 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 const useVideo =\n videoPresented && video.videoWidth > 0 && video.videoHeight > 0;\n const src = useVideo ? video : image;\n // drawImage source rects live in the source's own pixel space, which can\n // differ from dw/dh; fractions of the real bitmap keep every segment lined\n // up with what the picture element actually shows.\n const sw = useVideo ? video.videoWidth : image.naturalWidth;\n const sh = useVideo ? video.videoHeight : image.naturalHeight;\n // Cursor updates can schedule a repaint while the next JPEG is loading.\n // Keep the last backdrop until the replacement has drawable pixels.\n if ((!useVideo && !image.complete) || !(sw > 0 && sh > 0)) return;\n bgContext.setTransform(bgDpr, 0, 0, bgDpr, 0, 0);\n bgContext.clearRect(0, 0, stage.clientWidth, stage.clientHeight);\n const horizontal = bgAxis === \"x\";\n const sourceLength = horizontal ? sw : sh;\n const cuts = [0, bgEdgeFraction, 1 - bgEdgeFraction, 1];\n for (let i = 0; i < bgRects.length; i++) {\n const rect = bgRects[i];\n const origin = cuts[i] * sourceLength;\n const length = (cuts[i + 1] - cuts[i]) * sourceLength;\n bgContext.drawImage(\n src,\n horizontal ? origin : 0,\n horizontal ? 0 : origin,\n horizontal ? length : sw,\n horizontal ? sh : length,\n rect.x,\n rect.y,\n rect.w,\n rect.h,\n );\n }\n }\n function scheduleBackgroundDraw() {\n if (bgDrawFrame !== null || !bgRects || !bgContext) return;\n bgDrawFrame = requestAnimationFrame(() => {\n bgDrawFrame = null;\n drawBackground();\n });\n }\n function startBackgroundLoop() {\n if (\n bgLoopFrame !== null ||\n !bgContext ||\n !bgRects ||\n !videoPresented ||\n typeof video.requestVideoFrameCallback !== \"function\"\n )\n return;\n const frame = video.requestVideoFrameCallback(() => {\n if (bgLoopFrame !== frame) return;\n bgLoopFrame = null;\n drawBackground();\n startBackgroundLoop();\n });\n bgLoopFrame = frame;\n }\n // Only the streaming loop stops here; a pending one-shot draw is harmless\n // (it re-paints the preserved frame) and must survive reconnects.\n function stopBackgroundLoop() {\n if (bgLoopFrame !== null) video.cancelVideoFrameCallback?.(bgLoopFrame);\n bgLoopFrame = null;\n }\n function clearBackground() {\n stopBackgroundLoop();\n bgRects = null;\n // Resizing a canvas resets its bitmap; same-value assignment still clears.\n if (bgCanvas) bgCanvas.width = bgCanvas.width;\n }\n listen(image, \"load\", () => scheduleBackgroundDraw());\n // Older WebViews update the ambient layer on media progress, never with an\n // idle display-refresh loop. Geometry changes still get a one-shot repaint.\n listen(video, \"timeupdate\", () => {\n if (videoPresented && typeof video.requestVideoFrameCallback !== \"function\")\n scheduleBackgroundDraw();\n });\n function panBounds(r) {\n const vw = viewportWidth(),\n vh = viewportHeight();\n // Grow extra resting travel continuously from zero at fit to 180 screen\n // points at maximum zoom. Never count the unused space of a fitting axis.\n const clearance = (180 * (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(\n bottom - 1,\n (viewerSized ? viewportTopInset : 0) + 8 + hotY,\n );\n return {\n minX,\n maxX: Math.max(minX, right - 8 - (w - hotX)),\n minY,\n maxY: Math.max(minY, bottom - 8 - (h - hotY)),\n };\n }\n function moveTouchpad(dx, dy) {\n stopPanAnimation();\n const r = layout(),\n v = cursorViewport();\n if (cursorNeedsEntry) {\n // Re-enter at the nearest visible edge; do not pull a manually positioned\n // desktop back to the old off-screen cursor before applying this movement.\n cx = clamp((bounded(r.x + cx * r.width, v.minX, v.maxX) - r.x) / r.width);\n cy = clamp(\n (bounded(r.y + cy * r.height, v.minY, v.maxY) - r.y) / r.height,\n );\n cursorNeedsEntry = false;\n }\n cx = clamp(cx + dx / r.width);\n cy = clamp(cy + dy / r.height);\n const x = r.x + cx * r.width,\n y = r.y + cy * r.height;\n if (\n zoom > 1 ||\n r.width > viewportWidth() ||\n r.height > stage.clientHeight - viewportBottomInset\n ) {\n place(\n r.x + bounded(x, v.minX, v.maxX) - x,\n r.y + bounded(y, v.minY, v.maxY) - y,\n r,\n );\n followRest = { fx, fy, zoom };\n }\n manualViewMoved = false;\n }\n function stopPanAnimation() {\n if (panAnimation !== null) cancelAnimationFrame(panAnimation);\n panAnimation = null;\n }\n function settlePan() {\n stopPanAnimation();\n const r = layout(),\n b = panBounds(r),\n x = bounded(r.x, b.minX, b.maxX),\n y = bounded(r.y, b.minY, b.maxY);\n if (x === r.x && y === r.y) return;\n if (reducedMotion.matches) {\n place(x, y, r);\n render();\n return;\n }\n const started = performance.now();\n const tick = (now) => {\n const t = Math.min(1, (now - started) / 280),\n ease = 1 - Math.pow(1 - t, 3);\n place(r.x + (x - r.x) * ease, r.y + (y - r.y) * ease, r);\n render();\n panAnimation = t < 1 ? requestAnimationFrame(tick) : null;\n };\n panAnimation = requestAnimationFrame(tick);\n }\n function render() {\n const r = layout();\n if (config.nativeMedia && epoch)\n post({\n type: \"nativeViewport\",\n fillHeight,\n x: r.x,\n y: r.y,\n width: r.width,\n height: r.height,\n });\n const touchFeedback = control && mode === \"touch\" && touchCursorVisible;\n const cursorX = mode === \"touch\" && touchCursor ? touchCursor.x : cx;\n const cursorY = mode === \"touch\" && touchCursor ? touchCursor.y : cy;\n cursor.style.transition =\n mode === \"touch\" && !touchFeedback && !reducedMotion.matches\n ? \"opacity 120ms ease-out\"\n : \"none\";\n for (const el of [image, video]) {\n el.style.width = r.width + \"px\";\n el.style.height = r.height + \"px\";\n el.style.left = r.x + \"px\";\n el.style.top = r.y + \"px\";\n }\n 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: usableHeight(),\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 // Local consent is bounded by the host's picker lifetime. Reuse this retry\n // timer without consuming the finite network-recovery attempts.\n const capturePending = reason === \"capture-pending\";\n if (canRetry && epoch && (capturePending || retries < net.retryMs.length)) {\n const delay = capturePending\n ? net.retryMs[net.retryMs.length - 1]\n : net.retryMs[retries++];\n retryTimer = setTimeout(() => {\n retryTimer = null;\n if (epoch) connect();\n }, delay);\n }\n }\n function pollIce() {\n if (\n !pc ||\n !trickleIce ||\n !pc.remoteDescription ||\n icePending ||\n Date.now() >= exchangeUntil\n )\n return;\n const candidates = localCandidates.slice(\n localAck,\n localAck + net.batchSize,\n );\n icePending = {\n after: remoteAfter,\n sent: candidates.length,\n exchangeId: ++exchangeId,\n };\n post({\n type: \"ice\",\n attemptId,\n candidates,\n after: remoteAfter,\n exchangeId,\n });\n iceTimer = setTimeout(() => {\n icePending = null;\n pollIce();\n }, 4500);\n }\n async function receiveIce(message) {\n if (\n !pc ||\n !icePending ||\n message.attemptId !== attemptId ||\n message.exchangeId !== icePending.exchangeId\n )\n return;\n const rtc = pc,\n g = generation,\n batch = icePending;\n clearTimeout(iceTimer);\n try {\n if (message.error) {\n icePending = null;\n iceTimer = setTimeout(pollIce, 1000);\n return;\n }\n if (\n !Array.isArray(message.candidates) ||\n message.candidates.length > net.batchSize ||\n message.next !== batch.after + message.candidates.length ||\n message.next > net.maxCandidates\n )\n throw new Error();\n for (const candidate of message.candidates) {\n if (g !== generation) return;\n const key = JSON.stringify(candidate);\n if (remoteSeen.has(key)) continue;\n if (remoteSeen.size >= net.maxCandidates) throw new Error();\n await rtc.addIceCandidate(candidate);\n if (g !== generation) return;\n remoteSeen.add(key);\n }\n if (g !== generation) return;\n localAck += batch.sent;\n remoteAfter = message.next;\n remoteComplete = message.complete === true;\n icePending = null;\n if (!(\n remoteComplete &&\n rtc.iceGatheringState === \"complete\" &&\n localAck === localCandidates.length\n ))\n iceTimer = setTimeout(pollIce, net.pollMs);\n } catch {\n if (g === generation) failRtc(\"candidates\");\n }\n }\n async function receiveAnswer(message) {\n if (!pc || message.attemptId !== attemptId) return;\n const rtc = pc,\n g = generation;\n try {\n await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n if (g !== generation) return;\n clearTimeout(deadlineTimer);\n deadlineTimer = setTimeout(() => {\n if (g === generation && rtc.connectionState !== \"connected\")\n failRtc(\"connect-timeout\");\n }, net.connectMs);\n exchangeUntil = Date.now() + net.exchangeMs;\n pollIce();\n } catch {\n if (g === generation) failRtc(\"answer\");\n }\n }\n async function connect() {\n closeRtc();\n const g = generation;\n attemptId = String(g);\n if (!window.RTCPeerConnection) {\n failRtc(\"unsupported\", false);\n return;\n }\n configPending = true;\n deadlineTimer = setTimeout(\n () => {\n if (g === generation && configPending) {\n configPending = false;\n void startRtc(g, iceServers);\n }\n },\n (net.iceConfigMs ?? 8000) + (net.iceConfigBridgeMs ?? 500),\n );\n return post({ type: \"iceConfig\", attemptId });\n }\n async function receiveIceConfig(message) {\n if (!epoch || !configPending || message.attemptId !== attemptId) return;\n configPending = false;\n clearTimeout(deadlineTimer);\n deadlineTimer = null;\n await startRtc(generation, message.iceServers);\n }\n async function startRtc(g, servers) {\n try {\n const rtc = new RTCPeerConnection({ iceServers: servers });\n pc = rtc;\n dc = rtc.createDataChannel(\"input-v1\");\n rtc.addTransceiver(\"video\", { direction: \"recvonly\" });\n rtc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n rtc.onicecandidate = ({ candidate }) => {\n if (g !== generation || !candidate?.candidate || !trickleIce) return;\n if (localCandidates.length >= net.maxCandidates) {\n failRtc(\"candidate-limit\", false);\n return;\n }\n localCandidates.push({\n candidate: candidate.candidate,\n sdpMid: candidate.sdpMid,\n sdpMLineIndex: candidate.sdpMLineIndex,\n ...(candidate.usernameFragment\n ? { usernameFragment: candidate.usernameFragment }\n : {}),\n });\n // Gathering continues after the offer; the serial exchange flushes late addresses.\n };\n dc.onmessage = (e) => {\n try {\n if (g !== generation || pc !== rtc) return;\n if (typeof e.data !== \"string\" || e.data.length > 80000) return;\n const message = JSON.parse(e.data);\n if (message.type === \"cursor\") receiveCursor(message.cursor);\n if (\n (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: usableHeight(),\n });\n break;\n case \"presentation\":\n if (config.nativeMedia) {\n release();\n showKeyboard(false);\n break;\n }\n try {\n if (message.enabled) {\n release();\n showKeyboard(false);\n if (video.webkitSupportsPresentationMode?.(\"picture-in-picture\"))\n video.webkitSetPresentationMode(\"picture-in-picture\");\n else if (video.requestPictureInPicture)\n video\n .requestPictureInPicture()\n .catch(() => post({ type: \"presentationFailed\" }));\n else post({ type: \"presentationFailed\" });\n } else if (video.webkitSetPresentationMode)\n video.webkitSetPresentationMode(\"inline\");\n else if (document.pictureInPictureElement)\n document.exitPictureInPicture().catch(() => {});\n } catch {\n post({ type: \"presentationFailed\" });\n }\n break;\n case \"videoSettings\":\n if (\n Number.isInteger(message.width) &&\n Number.isInteger(message.height) &&\n message.width >= 320 &&\n message.height >= 320 &&\n (message.restore === true ||\n (message.width <= 2560 && message.height <= 2560))\n ) {\n release();\n stopPanAnimation();\n viewerSized = message.restore !== true;\n zoom = 1;\n fx = fy = 0.5;\n followRest = null;\n dw = message.width;\n dh = message.height;\n render();\n }\n video.muted = !message.audio;\n retries = 0;\n if (!config.nativeMedia) connect();\n break;\n case \"keyboard\":\n showKeyboard(message.enabled === true);\n break;\n case \"resume\":\n if (video.srcObject) video.play().catch(() => {});\n break;\n case \"releaseInput\":\n release();\n break;\n case \"theme\":\n if (/^#[0-9a-f]{3,8}$/i.test(message.surface)) {\n document.body.style.background = config.nativeMedia\n ? \"transparent\"\n : message.surface;\n document.documentElement.style.background = config.nativeMedia\n ? \"transparent\"\n : message.surface;\n document.documentElement.style.setProperty(\n \"--surface\",\n message.surface,\n );\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.foreground)) {\n cursor.style.borderColor = message.foreground;\n document.documentElement.style.setProperty(\n \"--foreground\",\n message.foreground,\n );\n }\n break;\n case \"networkStatus\": {\n const status = 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 previousTopInset = viewportTopInset,\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.topInset))\n viewportTopInset = Math.max(\n 0,\n Math.min(stage.clientHeight - 1, message.topInset),\n );\n if (Number.isFinite(message.bottomInset))\n viewportBottomInset = Math.max(\n 0,\n Math.min(stage.clientHeight - 1, message.bottomInset),\n );\n if (Number.isFinite(message.leftInset)) {\n const inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.leftInset),\n );\n sideInsetsChanged = sideInsetsChanged || inset !== viewportLeftInset;\n viewportLeftInset = inset;\n }\n if (Number.isFinite(message.rightInset)) {\n const inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.rightInset),\n );\n sideInsetsChanged = sideInsetsChanged || inset !== viewportRightInset;\n viewportRightInset = inset;\n }\n // Hiding the side toolbar changes the viewport center. Keep the image's\n // actual horizontal position instead of following that center sideways.\n if (keepHorizontal) {\n stopPanAnimation();\n const r = layout();\n place(before.x, r.y, r);\n }\n const keyboardInset = keyboardOpen ? viewportBottomInset : 0;\n if (keyboardInset !== keyboardViewportInset) {\n const wasOpen = keyboardViewportInset > 0;\n keyboardViewportInset = keyboardInset;\n if (fillHeight && (keyboardInset > 0 || wasOpen)) {\n const r = layout(),\n v = cursorViewport();\n place(r.x, (v.minY + v.maxY) / 2 - cy * r.height, r);\n cursorNeedsEntry = false;\n manualViewMoved = false;\n }\n }\n if (keepHorizontal) {\n // Restoring the toolbar can cover the cursor even after a zero-height opening.\n if (!keyboardOpen || keyboardInset > 0) {\n const r = layout(),\n v = cursorViewport(),\n x = r.x + cx * r.width;\n place(r.x + bounded(x, v.minX, v.maxX) - x, r.y, r);\n }\n followRest = { fx, fy, zoom };\n render();\n } else if (\n sideInsetsChanged ||\n offsetChanged ||\n (viewerSized && previousTopInset !== viewportTopInset) ||\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 nativeVideoActive = false;\n image.style.visibility = \"visible\";\n viewerSized = false;\n followRest = null;\n cursorNeedsEntry = true;\n stopPanAnimation();\n resetCursor();\n control = false;\n release();\n pending = [];\n sending = false;\n seq = 0;\n epoch = message.epoch;\n clipboardShortcuts =\n config.desktop && message.clipboardShortcuts === true;\n clipboardModifier =\n message.clipboardModifier === \"meta\" ? \"meta\" : \"control\";\n dw = message.width;\n dh = message.height;\n fillHeight = message.fillHeight === true;\n video.muted = !message.audio;\n trickleIce = message.trickleIce === true;\n retries = 0;\n render();\n if (!config.nativeMedia) connect();\n break;\n case \"nativeVideo\":\n if (!config.nativeMedia || message.epoch !== epoch) break;\n nativeVideoActive = message.active === true;\n image.style.visibility = nativeVideoActive ? \"hidden\" : \"visible\";\n paintBackground();\n break;\n case \"nativeCursor\":\n if (config.nativeMedia && message.epoch === epoch)\n receiveCursor(message.cursor);\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(\n message.capturePending === true ? \"capture-pending\" : \"host\",\n message.retry !== false,\n );\n break;\n case \"frame\": {\n if (\"cursor\" in message) receiveCursor(message.cursor);\n else resetCursor();\n const frameEpoch = epoch;\n image.onload = () => {\n if (epoch === frameEpoch) {\n scheduleBackgroundDraw();\n post({ type: \"framePresented\" });\n }\n };\n image.src = \"data:image/jpeg;base64,\" + message.jpeg;\n break;\n }\n case \"control\":\n release();\n 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 nativeVideoActive = false;\n image.style.visibility = \"visible\";\n showKeyboard(false);\n control = false;\n release();\n pending = [];\n sending = false;\n epoch = null;\n closeRtc(message.preserveFrame === true);\n updateMouseButtons();\n render();\n break;\n }\n }\n // iOS can report equal left/right safe areas in both landscape directions.\n // Its interface angle distinguishes the notch side even on a 180-degree turn.\n const reportOrientation = () => {\n const angle =\n typeof window.orientation === \"number\"\n ? window.orientation\n : window.screen?.orientation?.angle;\n if (Number.isFinite(angle)) post({ type: \"orientation\", angle });\n };\n listen(window, \"orientationchange\", reportOrientation);\n if (window.screen?.orientation?.addEventListener)\n listen(window.screen.orientation, \"change\", reportOrientation);\n render();\n reportOrientation();\n post({ type: \"ready\" });\n return {\n receive: (message) => receive({ data: JSON.stringify(message) }),\n dispose: () => {\n release();\n epoch = null;\n closeRtc(false);\n if (bgDrawFrame !== null) cancelAnimationFrame(bgDrawFrame);\n bgDrawFrame = null;\n for (const cleanup of cleanups) cleanup();\n },\n };\n}\n";