Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(mobile): 原生接收远程桌面并保留后台画中画 (#4630)

Dashf58c2f110e79
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
index ea14741f91..4edeb9d713 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
@@ -59,6 +59,7 @@ import {
wireInboundDispatch,
} from '../dispatch';
import * as subscriptions from '../subscriptions';
+import { remoteDesktop } from '../../remote-desktop';
function mkClient(
over: Partial<{
@@ -232,6 +233,7 @@ beforeEach(() => {
afterEach(() => {
vi.useRealTimers();
+ vi.restoreAllMocks();
});
describe('[1] link-accept 发送失败的有限重试', () => {
@@ -649,6 +651,8 @@ describe('[5] orphan 截止时间按 channel 收窄', () => {
describe('[6] active controller 生命周期与故障半径', () => {
it('真实双 peer 链路中 A 的 DEVICE_OFFLINE 不清 B,B 的在途请求仍能完成', async () => {
+ const lost = vi.spyOn(remoteDesktop, 'signalingLost');
+ const stop = vi.spyOn(remoteDesktop, 'stop');
vi.useRealTimers();
const relay = new DispatchTestRelay();
const target = makeDispatchTestClient(relay, 'target');
@@ -697,9 +701,14 @@ describe('[6] active controller 生命周期与故障半径', () => {
// 模拟 relay 对 target→A 的真实路由错误:DeviceLinkClient 先发 typed offline,
// 再由 host 接入唯一的 deactivateController 状态转换。
relay.offline.add('ctrl-a');
+ lost.mockClear();
+ stop.mockClear();
target.sendInvokeResult('ctrl-a', 'offline-probe', { ok: true, result: null });
expect(routeChanges).toContain('ctrl-a:offline');
+ expect(lost).toHaveBeenCalledWith('ctrl-a');
+ expect(lost).not.toHaveBeenCalledWith('ctrl-b');
+ expect(stop).not.toHaveBeenCalledWith('ctrl-b');
expect(__testing.getActiveControllers().map((controller) => controller.deviceId).sort()).toEqual([
'ctrl-b',
]);
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 4a45094469..20e3d7f785 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -2083,6 +2083,7 @@ function deactivateControllerState(
deviceId: string,
observedConnectionEpoch?: number,
observedLinkGeneration?: number,
+ transientSignalingLoss = false,
): boolean {
const activeEpoch = controllerConnectionEpochByDevice.get(deviceId);
const activeLinkGeneration = controllerLinkGenerationByDevice.get(deviceId);
@@ -2109,7 +2110,8 @@ function deactivateControllerState(
let changed = false;
changed = acceptedLinkControllers.delete(deviceId) || changed;
stopFilePeers(deviceId);
- remoteDesktop.stop(deviceId);
+ if (transientSignalingLoss) remoteDesktop.signalingLost(deviceId);
+ else remoteDesktop.stop(deviceId);
void remoteCredentialHost.close(deviceId).catch(() => remoteCredentialHost.dispose());
changed = controllerConnectionEpochByDevice.delete(deviceId) || changed;
changed = controllerLinkGenerationByDevice.delete(deviceId) || changed;
@@ -2136,11 +2138,13 @@ export function deactivateController(
reason: string,
observedConnectionEpoch?: number,
observedLinkGeneration?: number,
+ transientSignalingLoss = false,
): boolean {
const changed = deactivateControllerState(
deviceId,
observedConnectionEpoch,
observedLinkGeneration,
+ transientSignalingLoss,
);
if (changed) {
log.info(`controller ${shortId(deviceId)} deactivated (${reason})`);
@@ -2152,7 +2156,7 @@ export function deactivateController(
/** Relay 连接离开 online:清本连接代所有 active controller,但保留恢复意图。 */
export function deactivateAllControllers(reason: string): void {
stopFilePeers();
- remoteDesktop.stop();
+ remoteDesktop.signalingLost();
const controllerIds = new Set([
...subscriptions.getControllerIds(),
...topicSubscriptionControllers,
@@ -2163,7 +2167,7 @@ export function deactivateAllControllers(reason: string): void {
]);
let changed = false;
for (const deviceId of controllerIds) {
- changed = deactivateControllerState(deviceId) || changed;
+ changed = deactivateControllerState(deviceId, undefined, undefined, true) || changed;
}
if (changed) {
log.info(`all active controllers deactivated (${reason}, count=${controllerIds.size})`);
@@ -2181,6 +2185,7 @@ export function handleControllerOffline(
routeChange ? 'relay-device-offline' : 'presence-offline',
routeChange?.connectionEpoch,
routeChange?.linkGeneration,
+ true,
);
}
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts
index 315dfa854d..1cb874861d 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts
@@ -129,6 +129,50 @@ describe('remote desktop authority and lifecycle', () => {
}
},
);
+ it('keeps only a live view-only presentation across signaling loss', async () => {
+ const h = harness();
+ const { lease } = await h.start();
+ await h.controller.request('phone', { op: 'presentation', lease, enabled: true });
+ h.controller.signalingLost('other-phone');
+ h.controller.signalingLost('phone');
+ h.controller.signalingLost();
+ expect(h.deps.stopVideo).not.toHaveBeenCalled();
+ for (let i = 0; i < 10; i++) {
+ h.advance(10_000);
+ h.controller.viewHeartbeat(lease);
+ h.controller.tick();
+ }
+ expect(h.deps.stopVideo).not.toHaveBeenCalled();
+ h.advance(12_000);
+ h.controller.tick();
+ expect(h.deps.stopVideo).toHaveBeenCalledOnce();
+ });
+
+ it('does not preserve foreground control or revoked presentations when signaling disappears', async () => {
+ const foreground = harness();
+ const { lease } = await foreground.start();
+ await foreground.controller.request('phone', { op: 'control', lease, enabled: true });
+ foreground.controller.signalingLost('phone');
+ expect(foreground.deps.stopVideo).toHaveBeenCalledOnce();
+ const revoked = harness();
+ const presentation = await revoked.start();
+ await revoked.controller.request('phone', { op: 'presentation', lease: presentation.lease, enabled: true });
+ revoked.revoke();
+ revoked.controller.signalingLost('phone');
+ revoked.controller.viewHeartbeat(presentation.lease);
+ expect(revoked.deps.stopVideo).toHaveBeenCalled();
+ });
+
+ it('explicit disconnect still stops a presentation after signaling loss', async () => {
+ const h = harness();
+ const { lease } = await h.start();
+ await h.controller.request('phone', { op: 'presentation', lease, enabled: true });
+ h.controller.signalingLost('phone');
+ h.controller.stopByUser();
+ h.controller.viewHeartbeat(lease);
+ expect(h.deps.stopVideo).toHaveBeenCalledOnce();
+ await expect(h.controller.request('phone', { op: 'heartbeat', lease })).rejects.toThrow('DESKTOP_STOPPED');
+ });
it('does not publish selected geometry or resume control before it is observed', async () => {
const h = harness();
h.deps.displayModes = async () => [
diff --git a/apps/desktop/src/main/remote-desktop/controller.ts b/apps/desktop/src/main/remote-desktop/controller.ts
index 89411ef368..72ee29d894 100644
--- a/apps/desktop/src/main/remote-desktop/controller.ts
+++ b/apps/desktop/src/main/remote-desktop/controller.ts
@@ -211,6 +211,16 @@ export class RemoteDesktopController {
)
this.stop();
}
+ /** Losing the signaling socket is expected while the phone shows PiP.
+ * Only an authorized, view-only presentation may outlive it, and only while
+ * the media channel keeps renewing the existing bounded lease. */
+ signalingLost(peer?: string): void {
+ this.tick();
+ const active = this.active;
+ if (active && (!peer || active.peer === peer) && active.backgroundViewing && !active.controlling)
+ return;
+ this.stop(peer);
+ }
stop(peer?: string): Promise<void> {
if (peer && this.active?.peer !== peer) {
// Cancelling a takeover candidate must not revoke the current owner's work.
diff --git a/apps/mobile/app.json b/apps/mobile/app.json
index ccf7ea69b9..46a678f6b5 100644
--- a/apps/mobile/app.json
+++ b/apps/mobile/app.json
@@ -65,7 +65,8 @@
"expo-build-properties",
{
"ios": {
- "buildReactNativeFromSource": true
+ "buildReactNativeFromSource": true,
+ "enableSceneSupport": true
}
}
],
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index e173d8f178..e705f4ed32 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -77,6 +77,7 @@ import {
} from '@/session/precreatedWorktreeRecovery';
import { IncomingShareBridge } from '@/session/IncomingShareBridge';
import { HomeEntryProvider, useHomeEntrySplashRelease } from '@/session/HomeEntryProvider';
+import { RemoteDesktopHost } from '@/remote-desktop/RemoteDesktopHost';
function NavigationGate() {
const auth = useAuth();
@@ -148,27 +149,29 @@ function NavigationGate() {
style={splashActive || mode === 'dark' ? 'light' : 'dark'}
/>
) : null}
- <Stack
- screenOptions={{
- headerShown: false,
- contentStyle: { backgroundColor: colors.surface },
- ...(Platform.OS === 'ios'
- ? { statusBarStyle: statusBarTheme === 'dark' ? 'light' : 'dark' }
- : null),
- // iOS 26 起 react-native-screens 的返回手势默认全屏识别(fullScreenSwipe 默认 true),
- // 判定范围过大:会与消息内表格/代码块的横向 ScrollView 抢手势,拖动内容时还会误触返回。
- // 限定手势起始点在屏幕前缘 44pt 内(end = 距前缘最大 x),恢复经典边缘返回的判定范围;
- // iOS < 26 默认就是边缘返回,本配置不改变其行为;Android 返回手势不走这条路径,不受影响。
- gestureResponseDistance: { end: 44 },
- }}
- >
- {/* 设置从左侧抽屉进入:接着抽屉方向从左边推出,不要默认从右边盖上来。 */}
- <Stack.Screen name="settings" options={{ animation: 'slide_from_left' }} />
- <Stack.Screen
- name="add-account"
- options={{ animation: 'fade', gestureEnabled: false }}
- />
- </Stack>
+ <RemoteDesktopHost>
+ <Stack
+ screenOptions={{
+ headerShown: false,
+ contentStyle: { backgroundColor: colors.surface },
+ ...(Platform.OS === 'ios'
+ ? { statusBarStyle: statusBarTheme === 'dark' ? 'light' : 'dark' }
+ : null),
+ // iOS 26 起 react-native-screens 的返回手势默认全屏识别(fullScreenSwipe 默认 true),
+ // 判定范围过大:会与消息内表格/代码块的横向 ScrollView 抢手势,拖动内容时还会误触返回。
+ // 限定手势起始点在屏幕前缘 44pt 内(end = 距前缘最大 x),恢复经典边缘返回的判定范围;
+ // iOS < 26 默认就是边缘返回,本配置不改变其行为;Android 返回手势不走这条路径,不受影响。
+ gestureResponseDistance: { end: 44 },
+ }}
+ >
+ {/* 设置从左侧抽屉进入:接着抽屉方向从左边推出,不要默认从右边盖上来。 */}
+ <Stack.Screen name="settings" options={{ animation: 'slide_from_left' }} />
+ <Stack.Screen
+ name="add-account"
+ options={{ animation: 'fade', gestureEnabled: false }}
+ />
+ </Stack>
+ </RemoteDesktopHost>
</NavigationThemeProvider>
);
}
diff --git a/apps/mobile/app/devices/desktop/[deviceId].tsx b/apps/mobile/app/devices/desktop/[deviceId].tsx
index 4a9cee553b..1edf3be840 100644
--- a/apps/mobile/app/devices/desktop/[deviceId].tsx
+++ b/apps/mobile/app/devices/desktop/[deviceId].tsx
@@ -1 +1,16 @@
-export { default } from "@/remote-desktop/RemoteDesktopScreen";
+import { Stack } from "expo-router";
+import RemoteDesktopScreen from "@/remote-desktop/RemoteDesktopScreen";
+import { NativeRemoteDesktopView } from "@/remote-desktop/NativeRemoteDesktopView";
+
+export default function RemoteDesktopRoute() {
+ if (!NativeRemoteDesktopView) return <RemoteDesktopScreen />;
+ return (
+ <Stack.Screen
+ options={{
+ headerShown: false,
+ gestureEnabled: false,
+ statusBarHidden: true,
+ }}
+ />
+ );
+}
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 99832d9ec0..afeb539b75 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -38,7 +38,6 @@ import {
import {
getRecordingPermissionsAsync,
requestRecordingPermissionsAsync,
- setAudioModeAsync,
} from 'expo-audio';
import {
addScreenshotListener,
@@ -4959,7 +4958,6 @@ export default function SessionScreen() {
let permissionRequestSeq: number | null = null;
let permissionRequestAbortController: AbortController | null = null;
let startupSeq: number | null = null;
- let audioModeEnabled = false;
// The controller THIS startup created. Stale-teardown paths must only touch
// this one: by the time a superseded continuation resumes, the shared ref
// may already point at a newer session's live recording. Read through the
@@ -5027,11 +5025,8 @@ export default function SessionScreen() {
startupSeq = voiceStartupSeqRef.current + 1;
voiceStartupSeqRef.current = startupSeq;
voiceStartupInFlightRef.current = true;
- await setAudioModeAsync({
- allowsRecording: true,
- playsInSilentMode: true,
- });
- audioModeEnabled = true;
+ // The capture backend owns audio-session configuration and teardown.
+ // Screen-level Expo mode changes also affect remote desktop PiP.
// Open the device link in the background: voice dictation writes into the
// local composer via the cloud ASR proxy and does not need the mobile↔desktop
// link (only submitting the composed message later does). Awaiting it used
@@ -5064,21 +5059,8 @@ export default function SessionScreen() {
CINDY_MANAGED_REFINER_PROVIDER,
);
if (voiceStartupSeqRef.current !== startupSeq) {
- // The startup was superseded while we awaited: close the claimed
- // connection instead of opening a mic for a dead run. Session switches
- // supersede IN PLACE here (the cleanup effect keys on [sessionId], no
- // unmount), so a NEWER voice run may already be starting or live — and
- // audio mode is app-global. Only undo the recording mode this startup
- // enabled when no newer run is active, otherwise the reset could land
- // after the new run's native capture started and silently kill it.
+ // This run never opened the microphone; release only its claimed ASR.
void prewarmedVoice?.asr.stop().catch(() => undefined);
- if (
- !voiceControllerSessionRef.current
- && !voiceStartupInFlightRef.current
- && !voiceRecordingActiveRef.current
- ) {
- await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
- }
return;
}
const startController = async () => {
@@ -5146,7 +5128,6 @@ export default function SessionScreen() {
voiceControllerSessionRef.current = null;
voiceRecordingActiveRef.current = false;
voiceStopInFlightRef.current = false;
- await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
}
await created.cancel().catch(() => undefined);
}
@@ -5177,14 +5158,6 @@ export default function SessionScreen() {
}
await created.cancel().catch(() => undefined);
}
- if (
- audioModeEnabled
- && !voiceControllerSessionRef.current
- && !voiceStartupInFlightRef.current
- && !voiceRecordingActiveRef.current
- ) {
- await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
- }
return;
}
const controller = voiceControllerSessionRef.current;
@@ -5197,7 +5170,6 @@ export default function SessionScreen() {
voiceStopAfterStartRef.current = false;
setVoiceState('error');
setVoiceError(formatRemoteError(err));
- await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
}
}, [deviceId, openLink, renderItems, t, voiceIsProcessing, voiceState, writeVoiceDraft]);
@@ -5229,7 +5201,6 @@ export default function SessionScreen() {
setVoiceError(null);
discardPendingPrewarm();
if (controller) void controller.cancel().catch(() => undefined);
- void setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
}, [setVoiceState]);
useEffect(() => {
@@ -5280,7 +5251,6 @@ export default function SessionScreen() {
setComposerVoiceHoldArmed(false);
if (controller) void controller.cancel().catch(() => undefined);
discardPendingPrewarm();
- void setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
};
}, [sessionId]);
@@ -5305,7 +5275,6 @@ export default function SessionScreen() {
const documentBeforeStop = composerDocumentRef.current;
const inputBeforeStop = composerInputRef.current;
const latestDraft = await controller.stop();
- await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
setVoiceState('done');
// chat-text-quote:纯引用(无转写文字、无附件)也要发出去——发送按钮在
// quote-only 时可见,漏了引用会变成「点发送只停了录音、消息没发」。
@@ -5329,7 +5298,6 @@ export default function SessionScreen() {
voiceRecordingActiveRef.current = false;
setVoiceState('error');
setVoiceError(formatRemoteError(err));
- await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
} finally {
voiceStopInFlightRef.current = false;
}
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index c56a9d354d..139fb7875f 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -57,7 +57,6 @@ import {
import {
getRecordingPermissionsAsync,
requestRecordingPermissionsAsync,
- setAudioModeAsync,
} from 'expo-audio';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { ScreenBackButton } from '@/components/MobilePrimitives';
@@ -1680,7 +1679,6 @@ export default function NewRemoteSessionScreen() {
setVoiceError(null);
discardPendingPrewarm();
if (controller) void controller.cancel().catch(() => undefined);
- void setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
}, [setVoiceState]);
useEffect(() => {
@@ -3146,7 +3144,6 @@ export default function NewRemoteSessionScreen() {
let permissionRequestAbortController: AbortController | null = null;
let startupSeq: number | null = null;
let claimedPrewarm: PrewarmedMobileVoiceAsr | null = null;
- let audioModeEnabled = false;
let createdController: MobileVoiceControllerSession | null = null;
try {
if (!selectedDeviceId) {
@@ -3209,11 +3206,8 @@ export default function NewRemoteSessionScreen() {
startupSeq = voiceStartupSeqRef.current + 1;
voiceStartupSeqRef.current = startupSeq;
voiceStartupInFlightRef.current = true;
- await setAudioModeAsync({
- allowsRecording: true,
- playsInSilentMode: true,
- });
- audioModeEnabled = true;
+ // The capture backend owns audio-session configuration and teardown.
+ // Screen-level Expo mode changes also affect remote desktop PiP.
// Open the device link in the background: voice dictation writes into the
// local composer via the cloud ASR proxy and does not need the mobile↔desktop
// link (only submitting the composed message later does). Awaiting it here
@@ -3248,18 +3242,8 @@ export default function NewRemoteSessionScreen() {
CINDY_MANAGED_REFINER_PROVIDER,
);
if (voiceStartupSeqRef.current !== startupSeq) {
- // Superseded while we awaited: close the claimed connection, and undo
- // the recording audio mode this startup enabled — but audio mode is
- // app-global, so leave it alone if a newer voice run (possibly on
- // another screen after this one unmounted) is already starting/live.
+ // This run never opened the microphone; release only its claimed ASR.
void prewarmedVoice?.asr.stop().catch(() => undefined);
- if (
- !voiceControllerSessionRef.current
- && !voiceStartupInFlightRef.current
- && !voiceRecordingActiveRef.current
- ) {
- await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
- }
return;
}
const selectionBefore = takeRefinementContextTail(currentDraft.slice(0, initialSelection.start));
@@ -3341,7 +3325,6 @@ export default function NewRemoteSessionScreen() {
voiceControllerSessionRef.current = null;
voiceRecordingActiveRef.current = false;
voiceStopInFlightRef.current = false;
- await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
}
await controller.cancel().catch(() => undefined);
return;
@@ -3365,14 +3348,6 @@ export default function NewRemoteSessionScreen() {
}
await createdController.cancel().catch(() => undefined);
}
- if (
- audioModeEnabled
- && !voiceControllerSessionRef.current
- && !voiceStartupInFlightRef.current
- && !voiceRecordingActiveRef.current
- ) {
- await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
- }
return;
}
const controller = voiceControllerSessionRef.current;
@@ -3383,7 +3358,6 @@ export default function NewRemoteSessionScreen() {
voiceRecordingActiveRef.current = false;
setVoiceState('error');
setVoiceError(formatRemoteError(err));
- await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
}
}, [openLink, selectedDeviceId, setFirstMessageDraft, voiceIsProcessing, voiceState]);
@@ -3401,7 +3375,6 @@ export default function NewRemoteSessionScreen() {
setVoiceError(null);
try {
const latestDraft = await controller.stop();
- await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
setVoiceState('done');
requestAnimationFrame(() => {
firstMessageInputRef.current?.setNativeProps({ selection: firstMessageSelectionRef.current });
@@ -3412,7 +3385,6 @@ export default function NewRemoteSessionScreen() {
voiceRecordingActiveRef.current = false;
setVoiceState('error');
setVoiceError(formatRemoteError(err));
- await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
return null;
} finally {
voiceStopInFlightRef.current = false;
@@ -3480,7 +3452,6 @@ export default function NewRemoteSessionScreen() {
voiceRecordingActiveRef.current = false;
if (controller) void controller.cancel().catch(() => undefined);
discardPendingPrewarm();
- void setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
};
}, []);
diff --git a/apps/mobile/modules/cindy-remote-presentation/ios/CindyRemotePresentation.podspec b/apps/mobile/modules/cindy-remote-presentation/ios/CindyRemotePresentation.podspec
index df30a2dbc6..ce8013e358 100644
--- a/apps/mobile/modules/cindy-remote-presentation/ios/CindyRemotePresentation.podspec
+++ b/apps/mobile/modules/cindy-remote-presentation/ios/CindyRemotePresentation.podspec
@@ -18,6 +18,7 @@ Pod::Spec.new do |s|
s.static_framework = true
s.dependency 'ExpoModulesCore'
+ s.dependency 'WebRTC-SDK', '150.7871.01'
s.pod_target_xcconfig = {
'DEFINES_MODULE' => 'YES',
diff --git a/apps/mobile/modules/cindy-remote-presentation/ios/CindyRemotePresentationModule.swift b/apps/mobile/modules/cindy-remote-presentation/ios/CindyRemotePresentationModule.swift
index 74a99d8db6..7375eeffd0 100644
--- a/apps/mobile/modules/cindy-remote-presentation/ios/CindyRemotePresentationModule.swift
+++ b/apps/mobile/modules/cindy-remote-presentation/ios/CindyRemotePresentationModule.swift
@@ -2,6 +2,7 @@ import ExpoModulesCore
import UIKit
import AVFoundation
import UniformTypeIdentifiers
+import WebRTC
public class CindyRemotePresentationModule: Module {
private var previousAudio: (AVAudioSession.Category, AVAudioSession.Mode, AVAudioSession.CategoryOptions)?
@@ -19,6 +20,19 @@ public class CindyRemotePresentationModule: Module {
try RemoteClipboard.write(json, expectedVersion: version)
return String(UIPasteboard.general.changeCount)
}.runOnQueue(.main)
+ Constants(["nativeVideo": true])
+ View(RemoteDesktopVideoView.self) {
+ Events("onMessage")
+ Prop("inlineVisible") { (view: RemoteDesktopVideoView, visible: Bool) in
+ view.inlineVisible = visible
+ }
+ AsyncFunction("receive") { (view: RemoteDesktopVideoView, message: [String: Any]) in
+ view.receive(message)
+ }
+ AsyncFunction("sendInput") { (view: RemoteDesktopVideoView, message: [String: Any]) -> Bool in
+ view.sendInput(message)
+ }
+ }
AsyncFunction("readClipboard") { () -> String in
try RemoteClipboard.read()
}.runOnQueue(.main)
@@ -47,6 +61,13 @@ public class CindyRemotePresentationModule: Module {
let session = AVAudioSession.sharedInstance()
if enabled {
if self.previousAudio == nil { self.previousAudio = (session.category, session.mode, session.categoryOptions) }
+ // WebRTC reapplies its own template when playout starts. Keep it aligned
+ // with PiP playback instead of restoring a cached ambient category.
+ let configuration = RTCAudioSessionConfiguration()
+ configuration.category = AVAudioSession.Category.playback.rawValue
+ configuration.mode = AVAudioSession.Mode.moviePlayback.rawValue
+ configuration.categoryOptions = [.mixWithOthers]
+ RTCAudioSessionConfiguration.setWebRTC(configuration)
try session.setCategory(.playback, mode: .moviePlayback, options: [.mixWithOthers])
try session.setActive(true)
} else if let previous = self.previousAudio {
diff --git a/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopBackdrop.swift b/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopBackdrop.swift
new file mode 100644
index 0000000000..e41cbc2dcf
--- /dev/null
+++ b/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopBackdrop.swift
@@ -0,0 +1,44 @@
+import CoreImage
+
+/// Mirrors the browser viewer's 5% / 90% / 5% ambient canvas, independent of pan/zoom.
+enum RemoteDesktopBackdrop {
+ static func image(source: CIImage, size: CGSize, fillHeight: Bool, context: CIContext) -> CGImage? {
+ guard size.width > 0, size.height > 0, source.extent.width > 0, source.extent.height > 0 else { return nil }
+ let sw = source.extent.width, sh = source.extent.height
+ let vw = size.width, vh = size.height
+ let scale = fillHeight ? vh / sh : min(vw / sw, vh / sh)
+ let w = sw * scale, h = sh * scale
+ let horizontal = w < vw - 0.01
+ guard horizontal || h < vh - 0.01 else {
+ return nil
+ }
+ let center = (horizontal ? w : h) * 0.9
+ let side = ((horizontal ? vw : vh) - center) / 2
+ let cuts: [CGFloat] = [0, 0.05, 0.95, 1]
+ let starts: [CGFloat] = [0, side, side + center]
+ let lengths: [CGFloat] = [side, center, side]
+ let resolution = min(1, 512 / max(vw, vh))
+ var composite = CIImage.empty()
+ for index in 0..<3 {
+ let src = horizontal
+ ? CGRect(x: sw * cuts[index], y: 0, width: sw * (cuts[index + 1] - cuts[index]), height: sh)
+ : CGRect(x: 0, y: sh * cuts[index], width: sw, height: sh * (cuts[index + 1] - cuts[index]))
+ let dst = horizontal
+ ? CGRect(x: starts[index], y: (vh - h) / 2, width: lengths[index], height: h)
+ : CGRect(x: (vw - w) / 2, y: starts[index], width: w, height: lengths[index])
+ let transform = CGAffineTransform(a: dst.width / src.width * resolution, b: 0,
+ c: 0, d: dst.height / src.height * resolution,
+ tx: (dst.minX - src.minX * dst.width / src.width) * resolution,
+ ty: (dst.minY - src.minY * dst.height / src.height) * resolution)
+ // Clamp before stretching: transparent pixels outside a 5% strip would
+ // otherwise become a visible faded border after magnification and blur.
+ let target = dst.applying(CGAffineTransform(scaleX: resolution, y: resolution))
+ composite = source.cropped(to: src).clampedToExtent().transformed(by: transform)
+ .cropped(to: target).composited(over: composite)
+ }
+ let extent = CGRect(x: 0, y: 0, width: vw * resolution, height: vh * resolution)
+ let blurred = composite.cropped(to: extent).clampedToExtent()
+ .applyingFilter("CIGaussianBlur", parameters: [kCIInputRadiusKey: 16 * resolution])
+ return context.createCGImage(blurred, from: extent)
+ }
+}
diff --git a/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopReceiver.swift b/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopReceiver.swift
new file mode 100644
index 0000000000..95cf53f26b
--- /dev/null
+++ b/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopReceiver.swift
@@ -0,0 +1,369 @@
+import Foundation
+import WebRTC
+import UIKit
+
+/// One lease owns one receiver. Signaling uses the existing JS adapter; media,
+/// decoding and PiP challenge replies never pass through JS. All state is main-queue
+/// confined, including callbacks from WebRTC's signaling and decoder threads.
+final class RemoteDesktopReceiver: NSObject, RTCPeerConnectionDelegate, RTCDataChannelDelegate {
+ private static let factory: RTCPeerConnectionFactory = {
+ RTCInitializeSSL()
+ return RTCPeerConnectionFactory(encoderFactory: RTCDefaultVideoEncoderFactory(),
+ decoderFactory: RTCDefaultVideoDecoderFactory())
+ }()
+ let epoch: String
+ let attempt = UUID().uuidString
+ var emit: ([String: Any]) -> Void = { _ in }
+ var onFrame: (RTCVideoFrame) -> Bool = { _ in false }
+ var isPresenting: () -> Bool = { false }
+ var isPresentationAuthorized: () -> Bool = { false }
+ private var peer: RTCPeerConnection?
+ private var channel: RTCDataChannel?
+ private var track: RTCVideoTrack?
+ private var audioTrack: RTCAudioTrack?
+ private var sink: RemoteDesktopFrameSink?
+ private var stopped = false
+ private var audio = false
+ private var trickle: Bool
+ private let net: [String: Any]
+ private var candidates: [[String: Any]] = []
+ private var localAck = 0
+ private var remoteAfter = 0
+ private var exchange = 0
+ private var pending: (id: Int, count: Int)?
+ private var remoteSeen = Set<String>()
+ private var exchangeUntil = Date.distantPast
+ private var timer: Timer?
+ private var iceTimer: Timer?
+ private var disconnectTimer: Timer?
+ private var statsTimer: Timer?
+ private var statsBusy = false
+ private var statsSample: (id: String, bytes: Double, time: Double)?
+ private var offerSent = false
+ private var frameReady = false
+ private var pendingViewChallenge: String?
+
+ init(epoch: String, audio: Bool, trickle: Bool, net: [String: Any]) {
+ self.epoch = epoch
+ self.audio = audio
+ self.trickle = trickle
+ self.net = net
+ super.init()
+ }
+ private func seconds(_ key: String, _ fallback: Double) -> Double {
+ ((net[key] as? Double) ?? fallback) / 1000
+ }
+ func post(_ type: String, _ payload: [String: Any] = [:]) {
+ guard !stopped else { return }
+ emit(payload.merging(["type": type, "epoch": epoch, "attemptId": attempt]) { _, new in new })
+ }
+ func begin(fallbackServers: [[String: Any]]) {
+ post("iceConfig")
+ timer = Timer.scheduledTimer(withTimeInterval: 3.5, repeats: false) { [weak self] _ in
+ self?.start(servers: fallbackServers)
+ }
+ }
+ 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 "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 in
+ DispatchQueue.main.async {
+ guard let self, !self.stopped else { return }
+ guard error == nil else { self.fail("answer"); return }
+ self.deadline(self.seconds("connectMs", 15_000), "connect-timeout")
+ self.exchangeUntil = Date().addingTimeInterval(self.seconds("exchangeMs", 30_000))
+ self.pollIce()
+ }
+ }
+ case "ice": receiveIce(message)
+ case "fallback": fail("host", retry: message["retry"] as? Bool != false)
+ default: break
+ }
+ }
+ private func start(servers: [[String: Any]]) {
+ guard !stopped, peer == nil else { return }
+ timer?.invalidate()
+ let config = RTCConfiguration()
+ config.sdpSemantics = .unifiedPlan
+ config.iceServers = servers.compactMap { server in
+ let urls = (server["urls"] as? [String]) ?? (server["urls"] as? String).map { [$0] } ?? []
+ guard !urls.isEmpty else { return nil }
+ return RTCIceServer(urlStrings: urls, username: server["username"] as? String,
+ credential: server["credential"] as? String)
+ }
+ let constraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)
+ guard let rtc = Self.factory.peerConnection(with: config, constraints: constraints, delegate: self) else {
+ fail("setup"); return
+ }
+ peer = rtc
+ // Receive-only: never create microphone or camera capture tracks.
+ let direction = RTCRtpTransceiverInit()
+ direction.direction = .recvOnly
+ rtc.addTransceiver(of: .video, init: direction)
+ rtc.addTransceiver(of: .audio, init: direction)
+ channel = rtc.dataChannel(forLabel: "input-v1", configuration: RTCDataChannelConfiguration())
+ channel?.delegate = self
+ rtc.offer(for: constraints) { [weak self] description, error in
+ DispatchQueue.main.async {
+ guard let self, !self.stopped else { return }
+ guard let description, error == nil else { self.fail("offer"); return }
+ rtc.setLocalDescription(description) { [weak self] error in
+ DispatchQueue.main.async {
+ guard let self, !self.stopped else { return }
+ guard error == nil else { self.fail("offer"); return }
+ if self.trickle || rtc.iceGatheringState == .complete { self.sendOffer() }
+ else {
+ self.timer = Timer.scheduledTimer(withTimeInterval: self.seconds("legacyGatherMs", 5_000), repeats: false) { [weak self] _ in self?.sendOffer() }
+ }
+ }
+ }
+ }
+ }
+ statsTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in self?.reportStats() }
+ }
+ private func sendOffer() {
+ guard !stopped, !offerSent, let sdp = peer?.localDescription?.sdp else { return }
+ offerSent = true
+ deadline(seconds("answerMs", 45_000), "answer-timeout")
+ post("offer", ["sdp": sdp])
+ }
+ private func deadline(_ duration: Double, _ reason: String) {
+ timer?.invalidate()
+ timer = Timer.scheduledTimer(withTimeInterval: duration, repeats: false) { [weak self] _ in
+ guard let self, self.peer?.connectionState != .connected else { return }
+ self.fail(reason)
+ }
+ }
+ private func pollIce() {
+ guard !stopped, trickle, peer?.remoteDescription != nil, pending == nil,
+ Date() < exchangeUntil else { return }
+ let batch = Array(candidates.dropFirst(localAck).prefix(16))
+ exchange += 1
+ pending = (exchange, batch.count)
+ post("ice", ["candidates": batch, "after": remoteAfter, "exchangeId": exchange])
+ scheduleIce(4.5)
+ }
+ private func scheduleIce(_ seconds: Double) {
+ iceTimer?.invalidate()
+ iceTimer = Timer.scheduledTimer(withTimeInterval: seconds, repeats: false) { [weak self] _ in
+ self?.pending = nil
+ self?.pollIce()
+ }
+ }
+ private func receiveIce(_ message: [String: Any]) {
+ guard let batch = pending, message["exchangeId"] as? Int == batch.id, let peer else { return }
+ iceTimer?.invalidate()
+ if message["error"] as? Bool == true { 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 {
+ fail("candidates"); return
+ }
+ // WebRTC serializes addIceCandidate internally. Mark the batch complete only
+ // after every callback, so an old exchange cannot acknowledge a newer batch.
+ func add(_ index: Int) {
+ guard !stopped, pending?.id == batch.id else { return }
+ if index == values.count {
+ localAck += batch.count
+ remoteAfter = next
+ pending = nil
+ if !(message["complete"] as? Bool == true && peer.iceGatheringState == .complete && localAck == candidates.count) {
+ scheduleIce(seconds("pollMs", 250))
+ }
+ return
+ }
+ 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 {
+ fail("candidates"); return
+ }
+ let key = "\(value["sdpMid"] as? String ?? ""):\(line):\(sdp)"
+ if remoteSeen.contains(key) { add(index + 1); return }
+ guard remoteSeen.count < 128 else { fail("candidates"); return }
+ peer.add(RTCIceCandidate(sdp: sdp, sdpMLineIndex: Int32(line), sdpMid: value["sdpMid"] as? String)) { [weak self] error in
+ DispatchQueue.main.async {
+ guard let self, !self.stopped else { return }
+ guard error == nil else { self.fail("candidates"); return }
+ self.remoteSeen.insert(key)
+ add(index + 1)
+ }
+ }
+ }
+ add(0)
+ }
+ func stop() {
+ guard !stopped else { return }
+ stopped = true
+ pendingViewChallenge = nil
+ for task in [timer, iceTimer, disconnectTimer, statsTimer] { task?.invalidate() }
+ if let sink { track?.remove(sink) }
+ sink?.onFrame = nil
+ sink = nil
+ track = nil
+ audioTrack?.isEnabled = false
+ audioTrack = nil
+ channel?.delegate = nil
+ channel?.close()
+ channel = nil
+ peer?.delegate = nil
+ peer?.close()
+ peer = nil
+ emit = { _ in }
+ onFrame = { _ in false }
+ }
+ func 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,
+ 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) {
+ post("fallback", ["reason": reason, "retry": retry])
+ stop()
+ }
+ private func reportStats() {
+ guard !stopped, !statsBusy, UIApplication.shared.applicationState == .active, let peer else { return }
+ statsBusy = true
+ peer.statistics { [weak self] report in
+ DispatchQueue.main.async {
+ guard let self, !self.stopped else { return }
+ self.statsBusy = false
+ let 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? String
+ let pair = pairID.flatMap { report.statistics[$0] }
+ let local = (pair?.values["localCandidateId"] as? String).flatMap { report.statistics[$0] }?.values["candidateType"] as? String
+ let remote = (pair?.values["remoteCandidateId"] as? String).flatMap { report.statistics[$0] }?.values["candidateType"] as? String
+ 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 {
+ let time = video.timestamp_us / 1_000_000
+ if let previous = self.statsSample, previous.id == video.id, time > previous.time, bytes >= previous.bytes {
+ data["bytesPerSecond"] = (bytes - previous.bytes) / (time - previous.time)
+ }
+ self.statsSample = (video.id, bytes, time)
+ }
+ self.post("network", data)
+ }
+ }
+ }
+ func peerConnection(_ peerConnection: RTCPeerConnection, didGenerate candidate: RTCIceCandidate) {
+ DispatchQueue.main.async { [weak self] in
+ guard let self, !self.stopped, 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 }
+ self.candidates.append(value)
+ }
+ }
+ func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceGatheringState) {
+ DispatchQueue.main.async { [weak self] in
+ if newState == .complete && self?.trickle == false { self?.sendOffer() }
+ }
+ }
+ func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCPeerConnectionState) {
+ DispatchQueue.main.async { [weak self] in
+ guard let self, !self.stopped else { return }
+ if newState == .failed || newState == .closed { self.fail("transport") }
+ else if newState == .disconnected {
+ guard self.disconnectTimer == nil else { return }
+ self.post("reconnecting")
+ self.disconnectTimer = Timer.scheduledTimer(withTimeInterval: self.seconds("disconnectedMs", 5_000), repeats: false) { [weak self] _ in self?.fail("disconnected") }
+ } else if newState == .connected {
+ self.timer?.invalidate()
+ self.disconnectTimer?.invalidate()
+ self.disconnectTimer = nil
+ if self.frameReady { self.post("streaming") }
+ }
+ }
+ }
+ func peerConnection(_ peerConnection: RTCPeerConnection, didStartReceivingOn transceiver: RTCRtpTransceiver) {
+ DispatchQueue.main.async { [weak self] in
+ guard let self, !self.stopped else { return }
+ if let audio = transceiver.receiver.track as? RTCAudioTrack {
+ self.audioTrack = audio
+ audio.isEnabled = self.audio
+ }
+ guard let video = transceiver.receiver.track as? RTCVideoTrack else { return }
+ if let sink = self.sink { self.track?.remove(sink) }
+ let sink = RemoteDesktopFrameSink()
+ sink.onFrame = { [weak self] frame in
+ guard let self, !self.stopped else { return }
+ guard self.onFrame(frame) else { return }
+ if !self.frameReady {
+ self.frameReady = true
+ self.post("videoFrameReady")
+ self.post("streaming")
+ }
+ }
+ self.sink = sink
+ self.track = video
+ video.add(sink)
+ }
+ }
+ func dataChannel(_ dataChannel: RTCDataChannel, didReceiveMessageWith buffer: RTCDataBuffer) {
+ guard !buffer.isBinary, buffer.data.count <= 80_000 else { return }
+ DispatchQueue.main.async { [weak self] in
+ guard let self, !self.stopped, self.channel === dataChannel,
+ let message = try? JSONSerialization.jsonObject(with: buffer.data) as? [String: Any] else { return }
+ if message["type"] as? String == "viewPing",
+ let challenge = message["challenge"] as? String, challenge.utf8.count <= 64,
+ dataChannel.readyState == .open {
+ // The host keeps one outstanding challenge. It can arrive before PiP
+ // starts, so retain it until AVKit confirms actual presentation.
+ self.pendingViewChallenge = challenge
+ self.replyToViewChallenge()
+ } else if message["type"] as? String == "cursor", UIApplication.shared.applicationState == .active {
+ self.post("nativeCursor", ["cursor": message["cursor"] ?? NSNull()])
+ }
+ }
+ }
+ func replyToViewChallenge() {
+ guard !stopped, isPresenting(), isPresentationAuthorized(), let challenge = pendingViewChallenge,
+ let channel, channel.readyState == .open else { return }
+ if channel.sendData(RTCDataBuffer(data: Data(challenge.utf8), isBinary: false)) {
+ pendingViewChallenge = nil
+ }
+ }
+ func dataChannelDidChangeState(_ dataChannel: RTCDataChannel) {}
+ func peerConnection(_ peerConnection: RTCPeerConnection, didChange stateChanged: RTCSignalingState) {}
+ func 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, didRemove candidates: [RTCIceCandidate]) {}
+ func peerConnection(_ peerConnection: RTCPeerConnection, didOpen dataChannel: RTCDataChannel) {}
+}
+
+/// A single-slot mailbox prevents decode callbacks from building a main-queue
+/// frame backlog. The native receiver still consumes frames while JS is suspended.
+private final class RemoteDesktopFrameSink: NSObject, RTCVideoRenderer {
+ var onFrame: ((RTCVideoFrame) -> Void)?
+ private let lock = NSLock()
+ private var latest: RTCVideoFrame?
+ private var queued = false
+ func setSize(_ size: CGSize) {}
+ func renderFrame(_ frame: RTCVideoFrame?) {
+ guard let frame else { return }
+ lock.lock()
+ latest = frame
+ if queued { lock.unlock(); return }
+ queued = true
+ lock.unlock()
+ DispatchQueue.main.async { [weak self] in
+ guard let self else { return }
+ self.lock.lock()
+ let frame = self.latest
+ self.latest = nil
+ self.queued = false
+ self.lock.unlock()
+ if let frame { self.onFrame?(frame) }
+ }
+ }
+}
diff --git a/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopVideoView.swift b/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopVideoView.swift
new file mode 100644
index 0000000000..44c64b7702
--- /dev/null
+++ b/apps/mobile/modules/cindy-remote-presentation/ios/RemoteDesktopVideoView.swift
@@ -0,0 +1,621 @@
+import ExpoModulesCore
+import AVKit
+import WebRTC
+import CoreImage
+
+private final class RemoteDesktopSampleBufferView: UIView {
+ override class var layerClass: AnyClass { AVSampleBufferDisplayLayer.self }
+ var displayLayer: AVSampleBufferDisplayLayer { layer as! AVSampleBufferDisplayLayer }
+}
+
+/// Native media surface beneath the existing HTML input overlay. HTML supplies
+/// its exact fitted/zoomed rectangle; pixels never cross the React bridge.
+final class RemoteDesktopVideoView: ExpoView, AVPictureInPictureControllerDelegate,
+ AVPictureInPictureSampleBufferPlaybackDelegate {
+ let onMessage = EventDispatcher()
+ private let videoSurface = RemoteDesktopSampleBufferView()
+ private var presentationDisplay: AVSampleBufferDisplayLayer { videoSurface.displayLayer }
+ private let display = AVSampleBufferDisplayLayer()
+ private let canvas = CALayer()
+ override var backgroundColor: UIColor? {
+ didSet { canvas.backgroundColor = backgroundColor?.cgColor }
+ }
+ private let backdrop = CALayer()
+ private let backdropContext = CIContext(options: [.cacheIntermediates: false])
+ private var backdropActive = false
+ private var backdropFillHeight = false
+ private var backdropTime: CFTimeInterval = 0
+ private var pip: AVPictureInPictureController?
+ private var receiver: RemoteDesktopReceiver?
+ private var configuration: [String: Any]?
+ private var retryTimer: Timer?
+ private var stableTimer: Timer?
+ private var retries = 0
+ private var presenting = false
+ private var presentationAuthorized = false
+ private var startingPresentation = false
+ var inlineVisible = true {
+ didSet {
+ updateInlineVisibility()
+ if !inlineVisible { inlineFrameReady = false }
+ if inlineVisible && !oldValue {
+ if let latestFrame { render(latestFrame) }
+ refreshBackdrop()
+ }
+ completeInlineRestoreIfVisible()
+ }
+ }
+ private func updateInlineVisibility() {
+ // Keep the source ready until PiP has actually started. Once detached,
+ // hide the native source itself, not just its React parent's opacity.
+ // The layer, receiver and PiP controller remain attached and alive.
+ isHidden = !inlineVisible && presenting
+ }
+ private var wantsPresentation = false
+ private var automaticPresentation = false
+ private var restoreCompletion: ((Bool) -> Void)?
+ private var restoreGeneration = 0
+ private var inlineRestoreRequested = false
+ private var restoringInterface = false
+ private var lastCapability: Bool?
+ private var latestFrame: RTCVideoFrame?
+ private var inlineFrameReady = false
+ private var renderedFrames = 0
+ private var playbackReady = false {
+ didSet {
+ guard playbackReady != oldValue else { return }
+ // AVKit caches the sample-buffer delegate's state. Publish the real
+ // transition from no content to live playback, and invalidate on teardown.
+ pip?.invalidatePlaybackState()
+ }
+ }
+ private var pool: CVPixelBufferPool?
+ private var poolSize = CGSize.zero
+ private var backgroundGeneration = 0
+ private var backgroundObserver: NSObjectProtocol?
+ private var foregroundObserver: NSObjectProtocol?
+ private var inactiveObserver: NSObjectProtocol?
+ private var pipObservation: NSKeyValueObservation?
+
+ required init(appContext: AppContext? = nil) {
+ super.init(appContext: appContext)
+ clipsToBounds = true
+ isUserInteractionEnabled = false
+ display.videoGravity = .resizeAspect
+ presentationDisplay.videoGravity = .resizeAspect
+ // AVKit keeps a stable viewport-sized projection of the same decoded frame.
+ // The inline layer remains free to follow the viewer's pan/zoom rectangle.
+ addSubview(videoSurface)
+ canvas.backgroundColor = (backgroundColor ?? .systemBackground).cgColor
+ layer.addSublayer(canvas)
+ backdrop.opacity = 0.72
+ layer.addSublayer(backdrop)
+ layer.addSublayer(display)
+ if AVPictureInPictureController.isPictureInPictureSupported() {
+ pip = AVPictureInPictureController(contentSource: .init(sampleBufferDisplayLayer: presentationDisplay, playbackDelegate: self))
+ pip?.delegate = self
+ pip?.requiresLinearPlayback = true
+ // System readiness is separate from host authorization; challenge replies
+ // remain gated until the host has confirmed view-only access.
+ pip?.canStartPictureInPictureAutomaticallyFromInline = false
+ pipObservation = pip?.observe(\.isPictureInPicturePossible, options: [.new]) { [weak self] _, _ in
+ DispatchQueue.main.async { self?.reportCapability() }
+ }
+ }
+ inactiveObserver = NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { [weak self] _ in
+ guard let self else { return }
+ self.reportPresentationState("willResignActive")
+ // The source scene has already resigned active by this notification,
+ // even when UIApplication still reports .active. A manual start here is
+ // rejected by AVKit and its failure can cancel the automatic handoff.
+ // Automatic entry was armed while inline; let AVKit own this transition.
+ }
+ backgroundObserver = NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weak self] _ in
+ guard let self else { return }
+ self.backgroundGeneration += 1
+ let generation = self.backgroundGeneration
+ self.reportPresentationState("didEnterBackground")
+ if !self.presentationAuthorized || self.pip?.isPictureInPictureActive != true {
+ if self.automaticPresentation || self.wantsPresentation {
+ // AVKit may finish the automatic transition after background entry.
+ // A failed transition must still release media without relying on JS.
+ let current = self.receiver
+ DispatchQueue.main.asyncAfter(deadline: .now() + 4) { [weak self, weak current] in
+ guard let self, let current, self.receiver === current,
+ self.backgroundGeneration == generation,
+ UIApplication.shared.applicationState != .active,
+ !(self.presentationAuthorized && self.pip?.isPictureInPictureActive == true) else { return }
+ self.suspend()
+ }
+ } else { self.suspend() }
+ }
+ }
+ foregroundObserver = NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in
+ // JS may not receive the PiP stop callback until foreground. Replay the
+ // actual native state so it cannot retain a stale presentation exemption.
+ guard let self else { return }
+ self.backgroundGeneration += 1
+ if let epoch = self.configuration?["epoch"] as? String {
+ self.emit(["type": "presentation", "epoch": epoch, "active": self.presenting])
+ }
+ self.reportCapability()
+ self.reportPresentationState("didBecomeActive")
+ if self.inlineVisible, let frame = self.latestFrame { self.render(frame) }
+ self.refreshBackdrop()
+ }
+ }
+ deinit {
+ if let backgroundObserver { NotificationCenter.default.removeObserver(backgroundObserver) }
+ if let foregroundObserver { NotificationCenter.default.removeObserver(foregroundObserver) }
+ if let inactiveObserver { NotificationCenter.default.removeObserver(inactiveObserver) }
+ retryTimer?.invalidate()
+ stableTimer?.invalidate()
+ receiver?.stop()
+ }
+ override func didMoveToWindow() {
+ super.didMoveToWindow()
+ reportPresentationState(window == nil ? "sourceDetached" : "sourceAttached")
+ if window == nil { stop() }
+ }
+ func receive(_ message: [String: Any]) {
+ let type = message["type"] as? String
+ if type == "init" {
+ stop()
+ configuration = message
+ retries = 0
+ connect()
+ return
+ }
+ guard let config = configuration, message["epoch"] as? String == config["epoch"] as? String else { return }
+ switch type {
+ case "stop": stop()
+ case "pipPolicy":
+ automaticPresentation = message["enabled"] as? Bool == true
+ if let preparing = message["preparing"] as? Bool { wantsPresentation = preparing }
+ if let authorized = message["authorized"] as? Bool { presentationAuthorized = authorized }
+ else if !automaticPresentation { presentationAuthorized = false }
+ pip?.canStartPictureInPictureAutomaticallyFromInline = automaticPresentation
+ if presentationAuthorized { receiver?.replyToViewChallenge() }
+ reportPresentationState("policy")
+ case "restorePresentation":
+ guard restoreCompletion != nil, !inlineRestoreRequested else { return }
+ inlineRestoreRequested = true
+ reportPresentationState("restoreRequested")
+ setNeedsLayout()
+ waitForInlineRestore(generation: restoreGeneration)
+ case "videoSettings":
+ configuration?.merge(message) { _, new in new }
+ retries = 0
+ connect()
+ case "nativeViewport":
+ guard let x = message["x"] as? Double, let y = message["y"] as? Double,
+ let width = message["width"] as? Double, let height = message["height"] as? Double,
+ [x, y, width, height].allSatisfy({ $0.isFinite }), width > 0, height > 0 else { return }
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ display.frame = CGRect(x: x, y: y, width: width, height: height)
+ let fill = message["fillHeight"] as? Bool == true
+ if fill != backdropFillHeight {
+ backdropFillHeight = fill
+ refreshBackdrop()
+ }
+ CATransaction.commit()
+ case "presentation":
+ if message["enabled"] as? Bool == true {
+ startSystemPresentation()
+ } else {
+ presentationAuthorized = false
+ wantsPresentation = false
+ presenting = false
+ pip?.stopPictureInPicture()
+ }
+ case "resume":
+ if let latestFrame { render(latestFrame) }
+ if receiver == nil { connect() }
+ receiver?.post("presentation", ["active": presenting])
+ default: receiver?.receive(message)
+ }
+ }
+ private func connect() {
+ playbackReady = false
+ inlineFrameReady = false
+ retryTimer?.invalidate()
+ stableTimer?.invalidate()
+ stableTimer = nil
+ receiver?.stop()
+ receiver = nil
+ guard let config = configuration, let epoch = config["epoch"] as? String,
+ UIApplication.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] ?? [:])
+ receiver = current
+ lastCapability = nil
+ current.isPresenting = { [weak self] in self?.presenting == true && self?.pip?.isPictureInPictureActive == true }
+ current.isPresentationAuthorized = { [weak self] in self?.presentationAuthorized == true }
+ current.onFrame = { [weak self, weak current] frame in
+ guard let self, let current, self.receiver === current else { return false }
+ guard self.render(frame, liveFrame: true) else { return false }
+ self.latestFrame = frame
+ self.completeInlineRestoreIfVisible()
+ self.reportCapability()
+ return true
+ }
+ current.emit = { [weak self, weak current] event in
+ guard let self, let current, self.receiver === current else { return }
+ self.emit(event)
+ if event["type"] as? String == "streaming", self.stableTimer == nil {
+ let stableMs = (config["net"] as? [String: Any])?["stableMs"] as? Double ?? 30_000
+ self.stableTimer = Timer.scheduledTimer(withTimeInterval: stableMs / 1000, repeats: false) { [weak self, weak current] _ in
+ guard let self, let current, self.receiver === current else { return }
+ self.retries = 0
+ }
+ }
+ if event["type"] as? String == "reconnecting" || event["type"] as? String == "fallback" {
+ self.stableTimer?.invalidate()
+ self.stableTimer = nil
+ }
+ if event["type"] as? String == "fallback" {
+ self.playbackReady = false
+ self.presentationAuthorized = false
+ self.backdropActive = false
+ self.backdrop.contents = nil
+ self.backdropTime = 0
+ self.wantsPresentation = false
+ self.presenting = false
+ self.pip?.stopPictureInPicture()
+ self.receiver = nil
+ let delays = (config["net"] as? [String: Any])?["retryMs"] as? [Double] ?? [1000, 3000, 8000]
+ if event["retry"] as? Bool != false, self.retries < delays.count {
+ let delay = delays[self.retries] / 1000
+ self.retries += 1
+ self.retryTimer = Timer.scheduledTimer(withTimeInterval: delay, repeats: false) { [weak self] _ in self?.connect() }
+ }
+ }
+ }
+ current.begin(fallbackServers: config["iceServers"] as? [[String: Any]] ?? [])
+ }
+ func sendInput(_ message: [String: Any]) -> Bool {
+ guard !presenting, message["epoch"] as? String == configuration?["epoch"] as? String else { return false }
+ return receiver?.sendInput(message) == true
+ }
+ private func emit(_ value: [String: Any]) {
+ guard let data = try? JSONSerialization.data(withJSONObject: value),
+ let json = String(data: data, encoding: .utf8) else { return }
+ onMessage(["data": json])
+ }
+ private func reportCapability() {
+ let supported = pip?.isPictureInPicturePossible == true && playbackReady
+ guard supported != lastCapability else { return }
+ lastCapability = supported
+ receiver?.post("pipCapability", ["supported": supported])
+ }
+ private func suspend() {
+ let saved = configuration
+ let current = receiver
+ current?.post("presentation", ["active": false])
+ current?.post("fallback", ["retry": false, "reason": "background"])
+ // The synchronous fallback observer detaches receiver; retain the old owner
+ // until its tracks, channel and pending callbacks have been explicitly stopped.
+ current?.stop()
+ stop()
+ configuration = saved
+ }
+ private func stop() {
+ playbackReady = false
+ // Stop pongs before asynchronous AVKit callbacks, even with JS suspended.
+ presentationAuthorized = false
+ startingPresentation = false
+ presenting = false
+ updateInlineVisibility()
+ wantsPresentation = false
+ automaticPresentation = false
+ restoringInterface = false
+ inlineRestoreRequested = false
+ restoreGeneration += 1
+ pip?.canStartPictureInPictureAutomaticallyFromInline = false
+ let completion = restoreCompletion
+ restoreCompletion = nil
+ completion?(false)
+ retryTimer?.invalidate()
+ retryTimer = nil
+ stableTimer?.invalidate()
+ stableTimer = nil
+ receiver?.stop()
+ receiver = nil
+ configuration = nil
+ pip?.stopPictureInPicture()
+ display.flushAndRemoveImage()
+ presentationDisplay.flushAndRemoveImage()
+ inlineFrameReady = false
+ backdropActive = false
+ backdrop.contents = nil
+ backdropTime = 0
+ latestFrame = nil
+ pool = nil
+ }
+ @discardableResult private func render(_ frame: RTCVideoFrame, liveFrame: Bool = false) -> Bool {
+ guard let buffer = pixelBuffer(frame) else { return false }
+ var format: CMVideoFormatDescription?
+ guard CMVideoFormatDescriptionCreateForImageBuffer(allocator: kCFAllocatorDefault, imageBuffer: buffer, formatDescriptionOut: &format) == noErr,
+ let format else { return false }
+ var timing = CMSampleTimingInfo(duration: .invalid, presentationTimeStamp: CMClockGetTime(CMClockGetHostTimeClock()), decodeTimeStamp: .invalid)
+ var sample: CMSampleBuffer?
+ guard CMSampleBufferCreateReadyWithImageBuffer(allocator: kCFAllocatorDefault, imageBuffer: buffer, formatDescription: format, sampleTiming: &timing, sampleBufferOut: &sample) == noErr,
+ let sample else { return false }
+ // Live remote desktop has no seekable timeline; display every decoded frame
+ // immediately rather than accumulating latency behind presentation timestamps.
+ if let attachments = CMSampleBufferGetSampleAttachmentsArray(sample, createIfNecessary: true) {
+ let entry = unsafeBitCast(CFArrayGetValueAtIndex(attachments, 0), to: CFMutableDictionary.self)
+ CFDictionarySetValue(entry, Unmanaged.passUnretained(kCMSampleAttachmentKey_DisplayImmediately).toOpaque(), Unmanaged.passUnretained(kCFBooleanTrue).toOpaque())
+ }
+ if presentationDisplay.status == .failed {
+ playbackReady = false
+ presentationDisplay.flush()
+ }
+ let projected = presentationDisplay.isReadyForMoreMediaData
+ if projected {
+ presentationDisplay.enqueue(sample)
+ if liveFrame { playbackReady = true; renderedFrames += 1 }
+ }
+ // The second renderer shares the sample buffer; no second decode or copy.
+ // Only the system projection consumes frames while inline is not visible.
+ let needsInline = inlineVisible && UIApplication.shared.applicationState == .active
+ var renderedInline = false
+ if needsInline {
+ if display.status == .failed { display.flush() }
+ if display.isReadyForMoreMediaData {
+ display.enqueue(sample)
+ inlineFrameReady = true
+ renderedInline = true
+ }
+ }
+ // Replaying the last main frame after fallback must not revive its backdrop.
+ if liveFrame { backdropActive = true }
+ renderBackdrop(buffer)
+ return needsInline ? renderedInline : projected
+ }
+ override func layoutSubviews() {
+ super.layoutSubviews()
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ // Match the HTML ambient canvas overscan without moving the main picture.
+ backdrop.frame = bounds.insetBy(dx: -bounds.width * 0.06, dy: -bounds.height * 0.06)
+ canvas.frame = bounds
+ videoSurface.frame = bounds
+ CATransaction.commit()
+ refreshBackdrop()
+ completeInlineRestoreIfVisible()
+ }
+
+ private func refreshBackdrop() {
+ guard backdropActive, inlineVisible, UIApplication.shared.applicationState == .active,
+ let latestFrame, let buffer = pixelBuffer(latestFrame) else { return }
+ backdropTime = 0
+ renderBackdrop(buffer)
+ }
+
+ private func renderBackdrop(_ buffer: CVPixelBuffer) {
+ guard backdropActive, inlineVisible, UIApplication.shared.applicationState == .active,
+ bounds.width > 0, bounds.height > 0 else { return }
+ let now = CACurrentMediaTime()
+ // A blurred ambient image needs neither full desktop resolution nor 60 fps.
+ guard now - backdropTime >= 1.0 / 15 else { return }
+ backdropTime = now
+ let image = RemoteDesktopBackdrop.image(source: CIImage(cvPixelBuffer: buffer),
+ size: bounds.size, fillHeight: backdropFillHeight, context: backdropContext)
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ backdrop.contents = image
+ CATransaction.commit()
+ }
+
+ private func pixelBuffer(_ frame: RTCVideoFrame) -> CVPixelBuffer? {
+ if let native = frame.buffer as? RTCCVPixelBuffer,
+ native.width == CVPixelBufferGetWidth(native.pixelBuffer),
+ native.height == CVPixelBufferGetHeight(native.pixelBuffer),
+ native.cropX == 0, native.cropY == 0,
+ native.cropWidth == native.width, native.cropHeight == native.height {
+ return native.pixelBuffer
+ }
+ let source = frame.buffer.toI420()
+ let width = Int(source.width), height = Int(source.height)
+ let size = CGSize(width: width, height: height)
+ if pool == nil || poolSize != size {
+ poolSize = size
+ let attributes: [String: Any] = [
+ kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange,
+ kCVPixelBufferWidthKey as String: width, kCVPixelBufferHeightKey as String: height,
+ kCVPixelBufferIOSurfacePropertiesKey as String: [:],
+ ]
+ CVPixelBufferPoolCreate(nil, nil, attributes as CFDictionary, &pool)
+ }
+ guard let pool else { return nil }
+ var output: CVPixelBuffer?
+ let limits = [kCVPixelBufferPoolAllocationThresholdKey as String: 4] as CFDictionary
+ guard CVPixelBufferPoolCreatePixelBufferWithAuxAttributes(nil, pool, limits, &output) == kCVReturnSuccess,
+ let output else { return nil }
+ CVPixelBufferLockBaseAddress(output, [])
+ defer { CVPixelBufferUnlockBaseAddress(output, []) }
+ guard let y = CVPixelBufferGetBaseAddressOfPlane(output, 0), let uv = CVPixelBufferGetBaseAddressOfPlane(output, 1) else { return nil }
+ for row in 0..<height {
+ memcpy(y.advanced(by: row * CVPixelBufferGetBytesPerRowOfPlane(output, 0)), source.dataY.advanced(by: row * Int(source.strideY)), width)
+ }
+ for row in 0..<((height + 1) / 2) {
+ let destination = uv.advanced(by: row * CVPixelBufferGetBytesPerRowOfPlane(output, 1)).assumingMemoryBound(to: UInt8.self)
+ let u = source.dataU.advanced(by: row * Int(source.strideU))
+ let v = source.dataV.advanced(by: row * Int(source.strideV))
+ for column in 0..<((width + 1) / 2) {
+ destination[column * 2] = u[column]
+ destination[column * 2 + 1] = v[column]
+ }
+ }
+ return output
+ }
+ private func startSystemPresentation() {
+ guard !startingPresentation, pip?.isPictureInPictureActive != true else { return }
+ guard let pip, pip.isPictureInPicturePossible, playbackReady else {
+ reportPresentationFailure("not-ready")
+ return
+ }
+ guard window?.windowScene?.activationState == .foregroundActive else {
+ reportPresentationFailure("scene-not-active")
+ return
+ }
+ startingPresentation = true
+ wantsPresentation = true
+ reportPresentationState("explicitStart")
+ pip.startPictureInPicture()
+ }
+ func pictureInPictureControllerWillStartPictureInPicture(_ controller: AVPictureInPictureController) {
+ startingPresentation = true
+ if automaticPresentation { wantsPresentation = true }
+ reportPresentationState("willStart")
+ receiver?.post("presentationStarting")
+ }
+ func pictureInPictureControllerDidStartPictureInPicture(_ controller: AVPictureInPictureController) {
+ startingPresentation = false
+ guard wantsPresentation || automaticPresentation, receiver != nil else {
+ controller.stopPictureInPicture(); return
+ }
+ presenting = true
+ updateInlineVisibility()
+ receiver?.replyToViewChallenge()
+ receiver?.post("presentation", ["active": true])
+ }
+ func pictureInPictureControllerWillStopPictureInPicture(_ controller: AVPictureInPictureController) {
+ reportPresentationState("willStop")
+ presentationAuthorized = false
+ wantsPresentation = false
+ presenting = false
+ }
+ func pictureInPictureControllerDidStopPictureInPicture(_ controller: AVPictureInPictureController) {
+ startingPresentation = false
+ updateInlineVisibility()
+ receiver?.post("presentation", ["active": false])
+ if UIApplication.shared.applicationState != .active && !restoringInterface { suspend() }
+ restoringInterface = false
+ // Returning inline keeps live playback running. Refresh the delegate state
+ // after AVKit has finished its PiP stop transition.
+ controller.invalidatePlaybackState()
+ }
+ func pictureInPictureController(_ controller: AVPictureInPictureController, failedToStartPictureInPictureWithError error: Error) {
+ startingPresentation = false
+ wantsPresentation = false
+ presenting = false
+ updateInlineVisibility()
+ reportPresentationFailure("avkit", error: error as NSError)
+ }
+ private func sourceVisibility() -> (visible: Bool, opacity: CGFloat) {
+ var visible = true
+ var opacity: CGFloat = 1
+ var ancestor: UIView? = self
+ while let view = ancestor {
+ visible = visible && !view.isHidden
+ opacity *= view.alpha
+ ancestor = view.superview
+ }
+ return (visible, opacity)
+ }
+ private func waitForInlineRestore(generation: Int) {
+ guard restoreGeneration == generation, inlineRestoreRequested, restoreCompletion != nil else { return }
+ completeInlineRestoreIfVisible()
+ guard restoreCompletion != nil else { return }
+ // Parent-only opacity commits need not deliver layout or a new video frame.
+ // This check ends with the existing five-second restore deadline.
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in
+ self?.waitForInlineRestore(generation: generation)
+ }
+ }
+ private func completeInlineRestoreIfVisible() {
+ guard inlineRestoreRequested, let completion = restoreCompletion,
+ inlineVisible, inlineFrameReady, window != nil, !bounds.isEmpty,
+ !display.bounds.isEmpty, !presentationDisplay.bounds.isEmpty,
+ window?.windowScene?.activationState == .foregroundActive else { return }
+ let visibility = sourceVisibility()
+ guard visibility.visible, visibility.opacity >= 0.99 else { return }
+ inlineRestoreRequested = false
+ restoreCompletion = nil
+ reportPresentationState("restoreCompletion")
+ completion(true)
+ }
+ private func reportPresentationState(_ event: String, error: NSError? = nil) {
+ let (visible, opacity) = sourceVisibility()
+ let audio = AVAudioSession.sharedInstance()
+ var fields: [String: Any] = [
+ "event": event, "nativeState": UIApplication.shared.applicationState.rawValue,
+ "sceneState": window?.windowScene?.activationState.rawValue ?? -2,
+ "armed": automaticPresentation, "authorized": presentationAuthorized,
+ "possible": pip?.isPictureInPicturePossible == true,
+ "suspended": pip?.isPictureInPictureSuspended == true,
+ "active": pip?.isPictureInPictureActive == true, "starting": wantsPresentation,
+ "inlineVisible": inlineVisible, "sourceHidden": isHidden,
+ "inWindow": window != nil, "ancestorsVisible": visible, "opacity": opacity,
+ "width": bounds.width, "height": bounds.height,
+ "layerWidth": display.bounds.width, "layerHeight": display.bounds.height,
+ "sourceX": videoSurface.frame.minX, "sourceY": videoSurface.frame.minY,
+ "sourceWidth": videoSurface.bounds.width, "sourceHeight": videoSurface.bounds.height,
+ "surfaceHidden": videoSurface.isHidden, "surfaceOpacity": videoSurface.alpha,
+ "inlineFrameReady": inlineFrameReady, "renderedFrames": renderedFrames,
+ "hasFrame": latestFrame != nil, "playbackReady": playbackReady, "restoring": restoringInterface,
+ "audioCategory": audio.category.rawValue, "audioMode": audio.mode.rawValue,
+ "rtcAudioActive": RTCAudioSession.sharedInstance().isActive,
+ "rtcAudioActivations": RTCAudioSession.sharedInstance().activationCount,
+ ]
+ if let error { fields["domain"] = error.domain; fields["code"] = error.code }
+ receiver?.post("presentationDiagnostic", fields)
+ }
+ private func reportPresentationFailure(_ reason: String, error: NSError? = nil) {
+ var fields: [String: Any] = [
+ "reason": reason, "nativeState": UIApplication.shared.applicationState.rawValue,
+ "sceneState": window?.windowScene?.activationState.rawValue ?? -2,
+ "possible": pip?.isPictureInPicturePossible == true,
+ "active": pip?.isPictureInPictureActive == true, "hasFrame": latestFrame != nil,
+ "armed": automaticPresentation, "authorized": presentationAuthorized,
+ ]
+ fields["rtcAudioActive"] = RTCAudioSession.sharedInstance().isActive
+ fields["rtcAudioActivations"] = RTCAudioSession.sharedInstance().activationCount
+ if let error {
+ fields["domain"] = error.domain; fields["code"] = error.code
+ fields["description"] = String(error.localizedDescription.prefix(400))
+ if let reason = error.localizedFailureReason { fields["failureReason"] = String(reason.prefix(400)) }
+ if let underlying = error.userInfo[NSUnderlyingErrorKey] as? NSError {
+ fields["underlyingDomain"] = underlying.domain
+ fields["underlyingCode"] = underlying.code
+ fields["underlyingDescription"] = String(underlying.localizedDescription.prefix(400))
+ }
+ }
+ receiver?.post("presentationFailed", fields)
+ presentationAuthorized = false
+ }
+ func pictureInPictureController(_ controller: AVPictureInPictureController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void) {
+ let previous = restoreCompletion
+ restoreCompletion = nil
+ inlineRestoreRequested = false
+ previous?(false)
+ restoreCompletion = completionHandler
+ inlineRestoreRequested = false
+ restoringInterface = true
+ restoreGeneration += 1
+ let generation = restoreGeneration
+ receiver?.post("presentationRestore", ["inlineVisible": inlineVisible, "sourceHidden": isHidden])
+ DispatchQueue.main.asyncAfter(deadline: .now() + 5) { [weak self] in
+ guard let self, self.restoreGeneration == generation else { return }
+ let completion = self.restoreCompletion
+ self.restoreCompletion = nil
+ self.inlineRestoreRequested = false
+ if completion != nil { self.reportPresentationState("restoreTimeout") }
+ completion?(false)
+ }
+ }
+ func pictureInPictureController(_ controller: AVPictureInPictureController, setPlaying playing: Bool) {
+ reportPresentationState(playing ? "setPlayingTrue" : "setPlayingFalse")
+ if !playing { wantsPresentation = false; presenting = false; controller.stopPictureInPicture() }
+ }
+ func pictureInPictureControllerTimeRangeForPlayback(_ controller: AVPictureInPictureController) -> CMTimeRange {
+ playbackReady ? CMTimeRange(start: .negativeInfinity, duration: .positiveInfinity) : .invalid
+ }
+ func pictureInPictureControllerIsPlaybackPaused(_ controller: AVPictureInPictureController) -> Bool { !playbackReady }
+ func pictureInPictureController(_ controller: AVPictureInPictureController, didTransitionToRenderSize newRenderSize: CMVideoDimensions) {}
+ func pictureInPictureController(_ controller: AVPictureInPictureController, skipByInterval skipInterval: CMTime, completion: @escaping () -> Void) { completion() }
+}
diff --git a/apps/mobile/modules/cindy-remote-presentation/src/index.ts b/apps/mobile/modules/cindy-remote-presentation/src/index.ts
index 8b4301858d..5dc956dbdb 100644
--- a/apps/mobile/modules/cindy-remote-presentation/src/index.ts
+++ b/apps/mobile/modules/cindy-remote-presentation/src/index.ts
@@ -1,5 +1,6 @@
import { requireOptionalNativeModule } from "expo-modules-core";
export const remotePresentation = requireOptionalNativeModule<{
+ nativeVideo?: boolean;
readClipboard?(): Promise<string>;
writeClipboard?(json: string): Promise<void>;
clipboardVersion?(): Promise<string>;
diff --git a/apps/mobile/modules/xdt-mobile-realtime-audio/ios/XdtMobileRealtimeAudioModule.swift b/apps/mobile/modules/xdt-mobile-realtime-audio/ios/XdtMobileRealtimeAudioModule.swift
index 7a157e6146..feb5c0ac87 100644
--- a/apps/mobile/modules/xdt-mobile-realtime-audio/ios/XdtMobileRealtimeAudioModule.swift
+++ b/apps/mobile/modules/xdt-mobile-realtime-audio/ios/XdtMobileRealtimeAudioModule.swift
@@ -7,6 +7,7 @@ private let onAudioError = "onAudioError"
public class XdtMobileRealtimeAudioModule: Module {
private let engine = AVAudioEngine()
private var isCapturing = false
+ private var ownsAudioSession = false
private var targetSampleRate = 16_000.0
private var chunkIndex = 0
private var interruptionObserver: NSObjectProtocol?
@@ -91,6 +92,7 @@ public class XdtMobileRealtimeAudioModule: Module {
do {
try session.setCategory(.playAndRecord, mode: .measurement, options: [.duckOthers, .defaultToSpeaker])
try session.setActive(true)
+ ownsAudioSession = true
// Deliberately do NOT touch the engine here: engine.prepare() with no
// attached nodes raises an uncatchable NSException (AVAudioEngineGraph
// Initialize: inputNode != nullptr || outputNode != nullptr). Session
@@ -113,7 +115,7 @@ public class XdtMobileRealtimeAudioModule: Module {
if self.isCapturing {
return
}
- try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
+ self.deactivateOwnedSessionLocked()
}
deactivateWorkItem = workItem
sessionStateQueue.asyncAfter(deadline: .now() + sessionKeepAliveSeconds, execute: workItem)
@@ -124,6 +126,19 @@ public class XdtMobileRealtimeAudioModule: Module {
deactivateWorkItem = nil
}
+ // AVAudioSession is shared with remote desktop PiP and other playback. A
+ // background notification is not ownership: never release a session we did
+ // not activate, or one whose configuration has since been taken over.
+ private func deactivateOwnedSessionLocked() {
+ guard ownsAudioSession else { return }
+ ownsAudioSession = false
+ let session = AVAudioSession.sharedInstance()
+ // iOS may add mixWithOthers implicitly when duckOthers is requested.
+ guard session.category == .playAndRecord, session.mode == .measurement,
+ session.categoryOptions.subtracting(.mixWithOthers) == [.duckOthers, .defaultToSpeaker] else { return }
+ try? session.setActive(false, options: .notifyOthersOnDeactivation)
+ }
+
private func startCapture(options: [String: Any]?) throws {
try sessionStateQueue.sync {
try self.startCaptureLocked(options: options)
@@ -154,6 +169,7 @@ public class XdtMobileRealtimeAudioModule: Module {
do {
try session.setCategory(.playAndRecord, mode: .measurement, options: [.duckOthers, .defaultToSpeaker])
try session.setActive(true)
+ ownsAudioSession = true
} catch {
scheduleDeactivateLocked()
throw Exception(name: "ERR_AUDIO_SESSION", description: "Failed to configure audio session: \(error.localizedDescription)")
@@ -200,7 +216,7 @@ public class XdtMobileRealtimeAudioModule: Module {
// holding a keep-alive claim on a session the system just reclaimed (or
// while the module is being destroyed) serves nobody.
cancelScheduledDeactivateLocked()
- try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
+ deactivateOwnedSessionLocked()
} else {
scheduleDeactivateLocked()
}
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index b7b57596ad..099f208344 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -18,12 +18,12 @@
"@react-native-google-signin/google-signin": "16.1.2",
"@react-native-menu/menu": "^2.0.0",
"@types/pako": "^2.0.4",
- "expo": "~57.0.17",
+ "expo": "~57.0.23",
"expo-apple-authentication": "~57.0.1",
"expo-audio": "^57.0.4",
"expo-auth-session": "^57.0.10",
"expo-blur": "~57.0.2",
- "expo-build-properties": "~57.0.15",
+ "expo-build-properties": "~57.0.20",
"expo-clipboard": "^57.0.1",
"expo-constants": "^57.0.15",
"expo-crypto": "^57.0.2",
diff --git a/apps/mobile/scripts/fixtures/remote-desktop-backdrop.swift b/apps/mobile/scripts/fixtures/remote-desktop-backdrop.swift
new file mode 100644
index 0000000000..810dc8b242
--- /dev/null
+++ b/apps/mobile/scripts/fixtures/remote-desktop-backdrop.swift
@@ -0,0 +1,49 @@
+import CoreImage
+
+@main
+struct BackdropTests {
+ static func main() {
+ let context = CIContext()
+ func solid(_ color: CIColor, _ rect: CGRect) -> CIImage {
+ CIImage(color: color).cropped(to: rect)
+ }
+ func render(_ source: CIImage, _ size: CGSize, _ fill: Bool = false) -> CGImage? {
+ RemoteDesktopBackdrop.image(source: source, size: size, fillHeight: fill, context: context)
+ }
+ func pixel(_ image: CGImage, _ x: CGFloat, _ y: CGFloat) -> [UInt8] {
+ var bytes = [UInt8](repeating: 0, count: 4)
+ context.render(CIImage(cgImage: image), toBitmap: &bytes, rowBytes: 4,
+ bounds: CGRect(x: x, y: y, width: 1, height: 1), format: .RGBA8,
+ colorSpace: CGColorSpaceCreateDeviceRGB())
+ return bytes
+ }
+ // Distinct edge colors prove the narrow source strips stretch across the
+ // bars, stay the right way up, and remain opaque after the blur.
+ let wide = solid(.green, CGRect(x: 0, y: 0, width: 1000, height: 500))
+ .composited(over: CIImage.empty())
+ let vertical = solid(.red, CGRect(x: 0, y: 0, width: 1000, height: 25))
+ .composited(over: solid(.blue, CGRect(x: 0, y: 475, width: 1000, height: 25)))
+ .composited(over: wide)
+ let portrait = render(vertical, CGSize(width: 300, height: 500))!
+ let bottom = pixel(portrait, 150, 20), top = pixel(portrait, 150, 480)
+ assert(bottom[0] > 240 && bottom[2] < 15 && bottom[3] == 255)
+ assert(top[2] > 240 && top[0] < 15 && top[3] == 255)
+ let tall = solid(.green, CGRect(x: 0, y: 0, width: 500, height: 1000))
+ let horizontal = solid(.red, CGRect(x: 0, y: 0, width: 25, height: 1000))
+ .composited(over: solid(.blue, CGRect(x: 475, y: 0, width: 25, height: 1000)))
+ .composited(over: tall)
+ let landscape = render(horizontal, CGSize(width: 500, height: 300), true)!
+ assert(pixel(landscape, 20, 150)[0] > 240)
+ assert(pixel(landscape, 480, 150)[2] > 240)
+ // Fill-height removes vertical bars; equal-aspect content needs no backdrop.
+ assert(render(vertical, CGSize(width: 300, height: 500), true) == nil)
+ assert(render(vertical, CGSize(width: 1000, height: 500)) == nil)
+ assert(render(vertical, .zero) == nil)
+ // A later frame replaces the image, rather than retaining the first JPEG.
+ let changed = render(solid(.blue, vertical.extent), CGSize(width: 300, height: 500))!
+ assert(pixel(changed, 150, 20)[2] > 240)
+ let large = render(vertical, CGSize(width: 1200, height: 2400))!
+ assert(max(large.width, large.height) <= 512)
+ print("PASS: native backdrop edges, orientation, live frame replacement, fit and resolution")
+ }
+}
diff --git a/apps/mobile/scripts/fixtures/remote-desktop-receiver.swift b/apps/mobile/scripts/fixtures/remote-desktop-receiver.swift
new file mode 100644
index 0000000000..74ffb4ed20
--- /dev/null
+++ b/apps/mobile/scripts/fixtures/remote-desktop-receiver.swift
@@ -0,0 +1,206 @@
+// Test-only framework doubles. SDP/ICE completions are explicitly controlled;
+// production Timer and DispatchQueue behavior is exercised using the run loop.
+final class UIApplication {
+ enum State { case active, background }
+ static let shared = UIApplication()
+ var applicationState = State.active
+}
+func RTCInitializeSSL() {}
+protocol RTCPeerConnectionDelegate: AnyObject {}
+protocol RTCDataChannelDelegate: AnyObject {}
+protocol RTCVideoRenderer: AnyObject {
+ func setSize(_ size: CGSize)
+ func renderFrame(_ frame: RTCVideoFrame?)
+}
+final class RTCDefaultVideoEncoderFactory {}
+final class RTCDefaultVideoDecoderFactory {}
+final class RTCPeerConnectionFactory {
+ static var latest: RTCPeerConnection!
+ init(encoderFactory: RTCDefaultVideoEncoderFactory, decoderFactory: RTCDefaultVideoDecoderFactory) {}
+ func peerConnection(with: RTCConfiguration, constraints: RTCMediaConstraints, delegate: RTCPeerConnectionDelegate) -> RTCPeerConnection? {
+ let peer = RTCPeerConnection(); peer.delegate = delegate; Self.latest = peer; return peer
+ }
+}
+enum RTCSignalingState { case stable }
+enum RTCIceConnectionState { case connected }
+enum RTCIceGatheringState { case gathering, complete }
+enum RTCPeerConnectionState { case new, connected, disconnected, failed, closed }
+final class RTCConfiguration {
+ enum Semantics { case unifiedPlan }
+ var sdpSemantics = Semantics.unifiedPlan
+ var iceServers: [RTCIceServer] = []
+}
+final class RTCIceServer {
+ init(urlStrings: [String], username: String?, credential: String?) {}
+}
+final class RTCMediaConstraints {
+ init(mandatoryConstraints: [String: String]?, optionalConstraints: [String: String]?) {}
+}
+final class RTCSessionDescription {
+ enum Kind { case offer, answer }
+ let sdp: String
+ init(type: Kind, sdp: String) { self.sdp = sdp }
+}
+final class RTCRtpTransceiverInit {
+ enum Direction { case recvOnly }
+ var direction = Direction.recvOnly
+}
+class RTCMediaStreamTrack {}
+final class RTCAudioTrack: RTCMediaStreamTrack { var isEnabled = false }
+final class RTCVideoFrame {}
+final class RTCVideoTrack: RTCMediaStreamTrack {
+ var sink: RTCVideoRenderer?
+ func add(_ sink: RTCVideoRenderer) { self.sink = sink }
+ func remove(_ sink: RTCVideoRenderer) { self.sink = nil }
+}
+final class RTCRtpTransceiver {
+ final class Receiver { var track: RTCMediaStreamTrack? }
+ let receiver = Receiver()
+}
+final class RTCMediaStream {}
+final class RTCDataChannelConfiguration {}
+final class RTCDataBuffer {
+ let data: Data; let isBinary: Bool
+ init(data: Data, isBinary: Bool) { self.data = data; self.isBinary = isBinary }
+}
+final class RTCDataChannel {
+ enum State { case open, closed }
+ weak var delegate: RTCDataChannelDelegate?
+ var readyState = State.open
+ var bufferedAmount = 0
+ var sent: [Data] = []
+ var closes = 0
+ func sendData(_ data: RTCDataBuffer) -> Bool { sent.append(data.data); return true }
+ func close() { closes += 1; readyState = .closed }
+}
+final class RTCIceCandidate {
+ let sdp: String; let sdpMLineIndex: Int32; let sdpMid: String?
+ init(sdp: String, sdpMLineIndex: Int32, sdpMid: String?) {
+ self.sdp = sdp; self.sdpMLineIndex = sdpMLineIndex; self.sdpMid = sdpMid
+ }
+}
+final class RTCStatistics {
+ var type = ""; var values: [String: Any] = [:]; var timestamp_us = 0.0; var id = ""
+}
+final class RTCStatisticsReport { var statistics: [String: RTCStatistics] = [:] }
+final class RTCPeerConnection {
+ enum Media { case video, audio }
+ weak var delegate: RTCPeerConnectionDelegate?
+ var localDescription: RTCSessionDescription?
+ var remoteDescription: RTCSessionDescription?
+ var iceGatheringState = RTCIceGatheringState.complete
+ var connectionState = RTCPeerConnectionState.new
+ let channel = RTCDataChannel()
+ var offerCallback: ((RTCSessionDescription?, Error?) -> Void)?
+ var answerCallback: ((Error?) -> Void)?
+ var candidateCallbacks: [(Error?) -> Void] = []
+ var closes = 0
+ var answers = 0
+ func addTransceiver(of: Media, init: RTCRtpTransceiverInit) {}
+ func dataChannel(forLabel: String, configuration: RTCDataChannelConfiguration) -> RTCDataChannel? { channel }
+ func offer(for: RTCMediaConstraints, completionHandler: @escaping (RTCSessionDescription?, Error?) -> Void) { offerCallback = completionHandler }
+ func setLocalDescription(_ description: RTCSessionDescription, completionHandler: @escaping (Error?) -> Void) { localDescription = description; completionHandler(nil) }
+ func setRemoteDescription(_ description: RTCSessionDescription, completionHandler: @escaping (Error?) -> Void) { answers += 1; remoteDescription = description; answerCallback = completionHandler }
+ func add(_ candidate: RTCIceCandidate, completionHandler: @escaping (Error?) -> Void) { candidateCallbacks.append(completionHandler) }
+ func statistics(_ completionHandler: @escaping (RTCStatisticsReport) -> Void) { completionHandler(RTCStatisticsReport()) }
+ func close() { closes += 1; connectionState = .closed }
+}
+
+@main
+struct ReceiverTests {
+ static func drain(_ seconds: Double = 0.02) { RunLoop.main.run(until: Date().addingTimeInterval(seconds)) }
+ static func main() {
+ func message(_ receiver: RemoteDesktopReceiver, _ type: String, _ data: [String: Any] = [:]) -> [String: Any] {
+ data.merging(["type": type, "epoch": receiver.epoch, "attemptId": receiver.attempt]) { _, value in value }
+ }
+ func start() -> (RemoteDesktopReceiver, RTCPeerConnection) {
+ let receiver = RemoteDesktopReceiver(epoch: "lease", audio: false, trickle: true, net: ["disconnectedMs": 30.0])
+ receiver.receive(message(receiver, "iceConfig"))
+ return (receiver, RTCPeerConnectionFactory.latest)
+ }
+ // A replacement attempt must reject SDP and ICE from its predecessor.
+ let (old, oldPeer) = start()
+ old.stop(); old.stop()
+ assert(oldPeer.closes == 1 && oldPeer.channel.closes == 1)
+ let (current, peer) = start()
+ current.receive(message(old, "answer", ["sdp": "stale"]))
+ current.receive(message(old, "fallback"))
+ assert(peer.answers == 0 && peer.closes == 0)
+ var events: [String] = []
+ current.emit = { events.append($0["type"] as! String) }
+ oldPeer.offerCallback?(RTCSessionDescription(type: .offer, sdp: "late"), nil)
+ drain()
+ assert(events.isEmpty && oldPeer.localDescription == nil)
+ // Late answer completion and disconnect timer cannot revive stopped media.
+ current.receive(message(current, "answer", ["sdp": "answer"]))
+ current.peerConnection(peer, didChange: RTCPeerConnectionState.disconnected)
+ drain()
+ current.stop(); let count = events.count
+ peer.answerCallback?(nil); drain(0.06)
+ assert(events.count == count && peer.closes == 1)
+
+ let (ice, icePeer) = start()
+ var iceEvents: [[String: Any]] = []
+ ice.emit = { iceEvents.append($0) }
+ 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]
+ 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]))
+ assert(icePeer.candidateCallbacks.count == 1)
+ ice.stop(); let iceCount = iceEvents.count
+ icePeer.candidateCallbacks[0](nil); drain()
+ assert(iceEvents.count == iceCount)
+
+ // A decoder frame already queued when stop occurs must not announce readiness.
+ let (frames, framePeer) = start()
+ let transceiver = RTCRtpTransceiver()
+ let track = RTCVideoTrack()
+ transceiver.receiver.track = track
+ var rendered = 0
+ frames.onFrame = { _ in rendered += 1; return true }
+ frames.peerConnection(framePeer, didStartReceivingOn: transceiver); drain()
+ let sink = track.sink!
+ sink.renderFrame(RTCVideoFrame()); drain()
+ assert(rendered == 1)
+ sink.renderFrame(RTCVideoFrame())
+ frames.stop(); drain()
+ assert(rendered == 1 && track.sink == nil)
+
+ // Challenges require BOTH actual PiP and current authorization; stop clears it.
+ let (view, viewPeer) = start()
+ var presenting = false; var authorized = false
+ view.isPresenting = { presenting }; view.isPresentationAuthorized = { authorized }
+ UIApplication.shared.applicationState = .background
+ let ping = RTCDataBuffer(data: Data("{\"type\":\"viewPing\",\"challenge\":\"nonce\"}".utf8), isBinary: false)
+ view.dataChannel(viewPeer.channel, didReceiveMessageWith: ping); drain()
+ assert(viewPeer.channel.sent.isEmpty)
+ authorized = true; view.replyToViewChallenge(); assert(viewPeer.channel.sent.isEmpty)
+ authorized = false
+ presenting = true; view.replyToViewChallenge(); assert(viewPeer.channel.sent.isEmpty)
+ authorized = true; view.replyToViewChallenge(); view.replyToViewChallenge()
+ assert(viewPeer.channel.sent == [Data("nonce".utf8)])
+ authorized = false; view.dataChannel(viewPeer.channel, didReceiveMessageWith: ping); drain()
+ view.stop(); authorized = true; view.replyToViewChallenge()
+ assert(viewPeer.channel.sent.count == 1)
+ UIApplication.shared.applicationState = .active
+
+ // Recovery cancels the disconnect deadline; an unrecovered disconnect fails once.
+ let (recovered, recoveredPeer) = start()
+ recovered.peerConnection(recoveredPeer, didChange: RTCPeerConnectionState.disconnected)
+ recoveredPeer.connectionState = .connected
+ recovered.peerConnection(recoveredPeer, didChange: RTCPeerConnectionState.connected); drain(0.06)
+ assert(recoveredPeer.closes == 0); recovered.stop()
+ let (failed, failedPeer) = start()
+ var failures = 0
+ failed.emit = { if $0["type"] as? String == "fallback" { failures += 1 } }
+ failed.peerConnection(failedPeer, didChange: RTCPeerConnectionState.disconnected); drain(0.08)
+ assert(failures == 1 && failedPeer.closes == 1)
+ failed.stop(); assert(failedPeer.closes == 1)
+ print("Receiver lifecycle tests passed")
+ }
+}
diff --git a/apps/mobile/scripts/test-remote-desktop-backdrop.mjs b/apps/mobile/scripts/test-remote-desktop-backdrop.mjs
new file mode 100644
index 0000000000..f73b19c06c
--- /dev/null
+++ b/apps/mobile/scripts/test-remote-desktop-backdrop.mjs
@@ -0,0 +1,26 @@
+#!/usr/bin/env node
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const directory = mkdtempSync(join(tmpdir(), "cindy-backdrop-test-"));
+try {
+ const source = fileURLToPath(
+ new URL(
+ "../modules/cindy-remote-presentation/ios/RemoteDesktopBackdrop.swift",
+ import.meta.url,
+ ),
+ );
+ const fixture = fileURLToPath(
+ new URL("./fixtures/remote-desktop-backdrop.swift", import.meta.url),
+ );
+ const executable = join(directory, "backdrop-tests");
+ execFileSync("xcrun", ["swiftc", source, fixture, "-o", executable], {
+ stdio: "inherit",
+ });
+ execFileSync(executable, [], { stdio: "inherit" });
+} finally {
+ rmSync(directory, { recursive: true, force: true });
+}
diff --git a/apps/mobile/scripts/test-remote-desktop-receiver.mjs b/apps/mobile/scripts/test-remote-desktop-receiver.mjs
new file mode 100644
index 0000000000..ae75beb000
--- /dev/null
+++ b/apps/mobile/scripts/test-remote-desktop-receiver.mjs
@@ -0,0 +1,33 @@
+#!/usr/bin/env node
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, readFileSync, writeFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+// Execute the production state machine with controllable framework callbacks.
+// Only framework imports are replaced; no production logic is rewritten.
+const directory = mkdtempSync(join(tmpdir(), "cindy-receiver-test-"));
+try {
+ const source = readFileSync(
+ new URL(
+ "../modules/cindy-remote-presentation/ios/RemoteDesktopReceiver.swift",
+ import.meta.url,
+ ),
+ "utf8",
+ ).replace(/^import (WebRTC|UIKit)\n/gm, "");
+ const fixture = readFileSync(
+ new URL("./fixtures/remote-desktop-receiver.swift", import.meta.url),
+ "utf8",
+ );
+ const input = join(directory, "ReceiverTests.swift");
+ const executable = join(directory, "receiver-tests");
+ writeFileSync(input, source + "\n" + fixture);
+ execFileSync(
+ "xcrun",
+ ["swiftc", "-parse-as-library", input, "-o", executable],
+ { stdio: "inherit" },
+ );
+ execFileSync(executable, [], { stdio: "inherit" });
+} finally {
+ rmSync(directory, { recursive: true, force: true });
+}
diff --git a/apps/mobile/src/__tests__/composerAudioCleanup.test.ts b/apps/mobile/src/__tests__/composerAudioCleanup.test.ts
new file mode 100644
index 0000000000..6d45864d0c
--- /dev/null
+++ b/apps/mobile/src/__tests__/composerAudioCleanup.test.ts
@@ -0,0 +1,105 @@
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import ts from "typescript";
+import { describe, expect, it, vi } from "vitest";
+
+// Execute the real page cleanup without mounting unrelated network/UI services.
+// The audio session represents the already-playing remote desktop PiP.
+function pageCleanup(page: string, recording: boolean, starting: boolean) {
+ const source = ts.createSourceFile(
+ page,
+ readFileSync(resolve(process.cwd(), "app/sessions", page), "utf8"),
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ const cleanups: ts.ArrowFunction[] = [];
+ function visit(node: ts.Node) {
+ if (
+ ts.isCallExpression(node) &&
+ node.expression.getText(source) === "useEffect"
+ ) {
+ const effect = node.arguments[0];
+ if (effect && ts.isArrowFunction(effect) && ts.isBlock(effect.body)) {
+ for (const statement of effect.body.statements) {
+ if (
+ ts.isReturnStatement(statement) &&
+ statement.expression &&
+ ts.isArrowFunction(statement.expression) &&
+ statement.expression
+ .getText(source)
+ .includes("voiceControllerSessionRef.current = null")
+ ) {
+ cleanups.push(statement.expression);
+ }
+ }
+ }
+ }
+ ts.forEachChild(node, visit);
+ }
+ visit(source);
+ expect(cleanups).toHaveLength(1);
+ const cancel = vi.fn(async () => undefined);
+ const abort = vi.fn();
+ const discardPendingPrewarm = vi.fn();
+ const audio = { category: "playback", active: true };
+ const setAudioModeAsync = vi.fn(async () => {
+ audio.category = "ambient";
+ });
+ const bindings: Record<string, unknown> = {
+ voiceControllerSessionRef: { current: recording ? { cancel } : null },
+ voicePermissionRequestSeqRef: { current: 1 },
+ voicePermissionRequestAbortRef: { current: { abort } },
+ voicePermissionRequestInFlightRef: { current: starting },
+ voiceStartupSeqRef: { current: 1 },
+ voiceStartupInFlightRef: { current: starting },
+ voiceStopInFlightRef: { current: false },
+ voiceRecordingActiveRef: { current: recording },
+ voiceLongPressActiveRef: { current: false },
+ voiceSuppressNextPressRef: { current: false },
+ voiceStopAfterStartRef: { current: false },
+ voiceDictionaryLearningTrackerRef: { current: null },
+ voiceStateTransitionRef: { current: "idle" },
+ setComposerVoiceHoldArmed: vi.fn(),
+ discardPendingPrewarm,
+ setAudioModeAsync,
+ };
+ const compiled = ts.transpileModule(
+ `const cleanup = ${cleanups[0].getText(source)};`,
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },
+ ).outputText;
+ const cleanup = new Function(
+ ...Object.keys(bindings),
+ `${compiled}; return cleanup;`,
+ )(...Object.values(bindings)) as () => void;
+ return {
+ cleanup,
+ cancel,
+ abort,
+ discardPendingPrewarm,
+ audio,
+ setAudioModeAsync,
+ bindings,
+ };
+}
+
+describe.each(["new.tsx", "[sessionId].tsx"])("%s audio cleanup", (page) => {
+ it.each([
+ { recording: false, starting: false },
+ { recording: false, starting: true },
+ { recording: true, starting: false },
+ ])(
+ "preserves PiP and releases only voice resources: %j",
+ ({ recording, starting }) => {
+ const run = pageCleanup(page, recording, starting);
+ run.cleanup();
+ expect(run.audio).toEqual({ category: "playback", active: true });
+ expect(run.setAudioModeAsync).not.toHaveBeenCalled();
+ expect(run.cancel).toHaveBeenCalledTimes(recording ? 1 : 0);
+ expect(run.abort).toHaveBeenCalledOnce();
+ expect(run.discardPendingPrewarm).toHaveBeenCalledOnce();
+ expect(run.bindings.voiceControllerSessionRef).toEqual({ current: null });
+ expect(run.bindings.voiceStartupSeqRef).toEqual({ current: 2 });
+ },
+ );
+});
diff --git a/apps/mobile/src/__tests__/mobilePushRecovery.test.ts b/apps/mobile/src/__tests__/mobilePushRecovery.test.ts
index 4fda9d9d09..6e1c8e1aed 100644
--- a/apps/mobile/src/__tests__/mobilePushRecovery.test.ts
+++ b/apps/mobile/src/__tests__/mobilePushRecovery.test.ts
@@ -18,7 +18,7 @@ describe('background push recovery', () => {
beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(100_000); });
afterEach(() => vi.useRealTimers());
- function fixture() {
+ function fixture(pendingTransitions?: () => Promise<void>[]) {
let background = true;
const release = deferred<void>();
const stop = vi.fn();
@@ -28,6 +28,7 @@ describe('background push recovery', () => {
const lifecycle = createBackgroundConnection({
isBackground: () => background,
releaseTopics, stop, connect, report,
+ pendingTransitions,
graceMs: 2500, releaseWaitMs: 1000, suspendMs: 10_000,
});
return { lifecycle, release, stop, connect, releaseTopics, report, active: () => { background = false; lifecycle.active(); } };
@@ -50,7 +51,7 @@ describe('background push recovery', () => {
f.lifecycle.background();
expect(f.report).toHaveBeenLastCalledWith({ phase: 'background', generation: 1, elapsedMs: 0, releases: 1 });
await vi.advanceTimersByTimeAsync(2500);
- expect(f.report).toHaveBeenLastCalledWith({ phase: 'grace-fired', generation: 1, elapsedMs: 2500 });
+ expect(f.report).toHaveBeenLastCalledWith({ phase: 'grace-fired', generation: 1, elapsedMs: 2500, transitions: 0 });
f.active();
const count = f.report.mock.calls.length;
f.release.resolve();
@@ -91,6 +92,33 @@ describe('background push recovery', () => {
expect(f.connect).toHaveBeenCalledTimes(1);
});
+ it.each(['authorize', 'reject', 'timeout', 'foreground', 'dispose'])(
+ 'keeps signaling through a slow media handoff without retaining heavy topics: %s', async (outcome) => {
+ const handoff = deferred<void>();
+ const f = fixture(() => [handoff.promise]);
+ f.lifecycle.background();
+ expect(f.releaseTopics).toHaveBeenCalledTimes(1);
+ f.release.resolve();
+ await vi.advanceTimersByTimeAsync(3200);
+ expect(f.stop).not.toHaveBeenCalled();
+ if (outcome === 'foreground') f.active();
+ if (outcome === 'dispose') f.lifecycle.dispose();
+ if (outcome === 'reject') handoff.reject(new Error('denied'));
+ else if (outcome !== 'timeout') handoff.resolve();
+ await vi.advanceTimersByTimeAsync(0);
+ if (outcome === 'timeout') {
+ await vi.advanceTimersByTimeAsync(799);
+ expect(f.stop).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ }
+ expect(f.stop).toHaveBeenCalledTimes(['foreground', 'dispose'].includes(outcome) ? 0 : 1);
+ handoff.resolve();
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(f.stop).toHaveBeenCalledTimes(['foreground', 'dispose'].includes(outcome) ? 0 : 1);
+ f.lifecycle.dispose();
+ },
+ );
+
it('bounds final unsubscribe and prevents an old tail from stopping a later background generation', async () => {
const f = fixture();
f.lifecycle.background();
diff --git a/apps/mobile/src/__tests__/mobileRealtimeAudio.test.ts b/apps/mobile/src/__tests__/mobileRealtimeAudio.test.ts
index fc929437fc..8a5bbf65d4 100644
--- a/apps/mobile/src/__tests__/mobileRealtimeAudio.test.ts
+++ b/apps/mobile/src/__tests__/mobileRealtimeAudio.test.ts
@@ -249,7 +249,7 @@ describe('mobileRealtimeAudio', () => {
expect(source).toContain("nextState !== 'background'");
expect(source).toContain('voiceControllerSessionRef.current = null');
expect(source).toContain('discardPendingPrewarm()');
- expect(source).toContain("setAudioModeAsync({ allowsRecording: false })");
+ expect(source).not.toContain("setAudioModeAsync");
}
expect(newSessionSource).toContain('cancelVoiceForDeviceSwitch();');
expect(existingSessionSource).toContain('cancelVoiceForAppBackground();');
diff --git a/apps/mobile/src/__tests__/nativeAppConfig.test.ts b/apps/mobile/src/__tests__/nativeAppConfig.test.ts
index a73475fe40..64742181d9 100644
--- a/apps/mobile/src/__tests__/nativeAppConfig.test.ts
+++ b/apps/mobile/src/__tests__/nativeAppConfig.test.ts
@@ -521,6 +521,17 @@ describe('mobile native app config', () => {
expect(cn.ios.infoPlist.UIViewControllerBasedStatusBarAppearance).toBe(true);
});
+ it('enables the scene lifecycle required to launch iOS 27 SDK builds', () => {
+ const appJson = JSON.parse(readFileSync(resolve(process.cwd(), 'app.json'), 'utf8'));
+ const buildConfig = require(resolve(process.cwd(), 'app.config.js'));
+ for (const config of [appJson.expo, buildConfig({ config: appJson.expo })]) {
+ const properties = config.plugins.find(
+ (plugin: unknown) => Array.isArray(plugin) && plugin[0] === 'expo-build-properties',
+ );
+ expect(properties?.[1]?.ios?.enableSceneSupport).toBe(true);
+ }
+ });
+
it('keeps audio capture foreground-only in native builds', () => {
const appJson = JSON.parse(
readFileSync(resolve(process.cwd(), 'app.json'), 'utf8'),
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index df2a4abcb2..929cb863b5 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -164,6 +164,8 @@ export interface DeviceLinkContextValue {
/** 丢弃已结算的开链缓存并真正重开;并发重开仍按设备单飞。 */
reopenLink(deviceId: string): Promise<LinkAcceptPayload>;
closeLink(deviceId: string): void;
+ /** Acquire before background grace ends; always release on settlement/cancellation. Hard deadline enforced by lifecycle. */
+ beginBackgroundTransition?(): () => void;
/**
* opts.preSend:在连接就绪之后、真正 client.invoke 之前的最后同步检查点。抛错即
* 中止本次发送(错误原样上抛)。供写序敏感的调用方(patchHomeSession 的 isLatest
@@ -381,6 +383,16 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
// 后台释放 heavy session 订阅期间仍保留 registry 所有权;此时 unsubscribe ack
// 可以修正 stale offline verdict,但不能顺带触发 rehydrate 把刚释放的订阅加回来。
const backgroundReleaseInFlightRef = useRef(false);
+ const backgroundTransitions = useRef(new Set<Promise<void>>());
+ const beginBackgroundTransition = useCallback(() => {
+ let settle!: () => void;
+ const pending = new Promise<void>((resolve) => { settle = resolve; });
+ backgroundTransitions.current.add(pending);
+ return () => {
+ backgroundTransitions.current.delete(pending);
+ settle();
+ };
+ }, []);
// 每次后台释放都翻代。subscribe 即使跨 background→active 才收到 ACK,也只能在
// 发起代仍为当前代时登记远端 ACK,避免迟到成功覆盖较新的 unsubscribe。
const backgroundReleaseGenerationRef = useRef(0);
@@ -1173,6 +1185,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const backgroundConnection = createBackgroundConnection({
isBackground: () => AppState.currentState === 'background',
releaseTopics: releaseHeavyTopics,
+ pendingTransitions: () => [...backgroundTransitions.current],
stop: () => client.stop(),
connect: () => client.connectNow('appstate-active', { overrideCongestionCooldown: true }),
graceMs: BACKGROUND_STOP_GRACE_MS,
@@ -1241,6 +1254,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
networkSubscription?.remove();
sub.remove();
backgroundConnection.dispose();
+ backgroundTransitions.current.clear();
offUnresponsive();
offResponseEvidence();
offBeforeLink();
@@ -1375,6 +1389,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
), []);
const value = useMemo<DeviceLinkContextValue>(() => ({
+ beginBackgroundTransition,
status,
recoveringDeviceIds,
connectionIssue,
@@ -1393,6 +1408,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
onAgentsChanged: subscribeRemoteAgentRoster,
onRemoteResourceChanged: subscribeRemoteResourceChanged,
}), [
+ beginBackgroundTransition,
closeLink,
recoveringDeviceIds,
connectionEpoch,
diff --git a/apps/mobile/src/device-link/backgroundConnection.ts b/apps/mobile/src/device-link/backgroundConnection.ts
index 9c616e606a..0ad853e1fa 100644
--- a/apps/mobile/src/device-link/backgroundConnection.ts
+++ b/apps/mobile/src/device-link/backgroundConnection.ts
@@ -1,9 +1,12 @@
+export const BACKGROUND_TRANSITION_TIMEOUT_MS = 4_000;
+
export interface BackgroundConnectionDiagnostic {
phase: "background" | "release-settled" | "grace-fired" | "stop" | "active";
generation: number;
elapsedMs: number;
reason?: "grace" | "suspended";
releases?: number;
+ transitions?: number;
failed?: number;
releaseOutcome?: "settled" | "timed-out";
}
@@ -11,6 +14,7 @@ export interface BackgroundConnectionDiagnostic {
interface BackgroundConnectionOptions {
isBackground(): boolean;
releaseTopics(): Promise<void>[];
+ pendingTransitions?(): Promise<void>[];
stop(): void;
connect(): void;
graceMs: number;
@@ -67,10 +71,23 @@ export function createBackgroundConnection(
stopTimer = setTimeout(() => {
stopTimer = null;
if (!options.isBackground() || generation !== captured) return;
- report("grace-fired");
- const releases = Promise.allSettled(options.releaseTopics());
+ const transitions = options.pendingTransitions?.() ?? [];
+ report("grace-fired", { transitions: transitions.length });
+ // A media handoff must finish host authorization before signaling stops.
+ // This does not retain subscriptions or extend the media/lease deadline.
+ const topicReleases = options.releaseTopics();
+ const releases = Promise.allSettled([...topicReleases, ...transitions]);
+ const remainingTransitionMs = transitions.length
+ ? Math.max(
+ 0,
+ BACKGROUND_TRANSITION_TIMEOUT_MS - (Date.now() - backgroundAt!),
+ )
+ : 0;
const boundedWait = new Promise<void>((resolve) => {
- releaseTimer = setTimeout(resolve, options.releaseWaitMs);
+ releaseTimer = setTimeout(
+ resolve,
+ transitions.length ? remainingTransitionMs : options.releaseWaitMs,
+ );
});
void Promise.race([releases, boundedWait]).then((result) => {
if (generation !== captured) return;
@@ -81,10 +98,10 @@ export function createBackgroundConnection(
releaseOutcome: Array.isArray(result) ? "settled" : "timed-out",
...(Array.isArray(result)
? {
- releases: result.length,
- failed: result.filter(
- (entry) => entry.status === "rejected",
- ).length,
+ releases: topicReleases.length,
+ failed: result
+ .slice(0, topicReleases.length)
+ .filter((entry) => entry.status === "rejected").length,
}
: {}),
});
@@ -103,7 +120,11 @@ export function createBackgroundConnection(
// A timer reference cannot tell whether the socket was actually stopped:
// JS can be suspended while the final unsubscribe is still awaiting ACK.
if (elapsed > options.suspendMs) {
- report("stop", { reason: "suspended", elapsedMs: elapsed, generation: backgroundGeneration });
+ report("stop", {
+ reason: "suspended",
+ elapsedMs: elapsed,
+ generation: backgroundGeneration,
+ });
options.stop();
}
options.connect();
diff --git a/apps/mobile/src/i18n/locales/en/remoteDesktop.json b/apps/mobile/src/i18n/locales/en/remoteDesktop.json
index aaaeb11e80..4f6749c3d7 100644
--- a/apps/mobile/src/i18n/locales/en/remoteDesktop.json
+++ b/apps/mobile/src/i18n/locales/en/remoteDesktop.json
@@ -11,6 +11,7 @@
"clipboardSyncSkipped": "This content could not be synced and was skipped. Check paste access, or copy text or an image to try again.",
"clipboardSyncPermission": "Sync is paused. Allow paste access, then retry. Your setting stays on.",
"clipboardSyncRetry": "Retry sync",
+ "connectionTakingLong": "Connecting is taking longer than usual…",
"credentialSigningRequired": "The Mac development build is missing its signing configuration. Restart Cindy on the Mac with signing configured, then try again.",
"credentialPasswordRejected": "The Mac login password was not accepted. Enter it again.",
"credentialCancelled": "Password verification was cancelled. Tap reconnect when you are ready.",
@@ -110,7 +111,9 @@
"frameTime": "Frame Preparation {{ms}} ms",
"rotate": "Rotate screen",
"sound": "Sound",
- "smallWindow": "Picture in picture",
+ "smallWindow": "Run in background",
+ "controlUnavailableHint": "Computer control is temporarily unavailable. You can still pan and zoom the screen.",
+ "backgroundRunningHint": "Keep displaying the screen in a floating window when you leave remote desktop or switch apps.",
"displaySettings": "Display",
"frameRate": "Frame rate",
"fps": "{{count}} fps",
diff --git a/apps/mobile/src/i18n/locales/ja/remoteDesktop.json b/apps/mobile/src/i18n/locales/ja/remoteDesktop.json
index 2603576c31..70e6c60d2e 100644
--- a/apps/mobile/src/i18n/locales/ja/remoteDesktop.json
+++ b/apps/mobile/src/i18n/locales/ja/remoteDesktop.json
@@ -11,6 +11,7 @@
"clipboardSyncSkipped": "この内容は同期できないためスキップしました。ペーストの許可を確認するか、テキストや画像をコピーして再試行してください。",
"clipboardSyncPermission": "同期を一時停止しました。ペーストを許可してから再試行してください。設定はオンのままです。",
"clipboardSyncRetry": "同期を再試行",
+ "connectionTakingLong": "接続に時間がかかっています…",
"credentialSigningRequired": "Mac の開発版に署名設定がありません。Mac で署名を設定して Cindy を再起動し、もう一度お試しください。",
"credentialPasswordRejected": "Mac のログインパスワードを確認できませんでした。もう一度入力してください。",
"credentialCancelled": "パスワードの確認をキャンセルしました。準備ができたら再接続してください。",
@@ -110,7 +111,9 @@
"frameTime": "画像準備 {{ms}} ms",
"rotate": "画面を回転",
"sound": "サウンド",
- "smallWindow": "ピクチャインピクチャ",
+ "smallWindow": "バックグラウンド実行",
+ "controlUnavailableHint": "現在パソコンを操作できません。画面の移動や拡大・縮小はできます。",
+ "backgroundRunningHint": "リモートデスクトップを離れたり、アプリを切り替えたりしても、小さなウィンドウで画面を表示し続けます。",
"displaySettings": "表示",
"frameRate": "フレームレート",
"fps": "{{count}} fps",
diff --git a/apps/mobile/src/i18n/locales/ko/remoteDesktop.json b/apps/mobile/src/i18n/locales/ko/remoteDesktop.json
index 0f10e15b69..0adf248237 100644
--- a/apps/mobile/src/i18n/locales/ko/remoteDesktop.json
+++ b/apps/mobile/src/i18n/locales/ko/remoteDesktop.json
@@ -11,6 +11,7 @@
"clipboardSyncSkipped": "현재 콘텐츠를 동기화할 수 없어 건너뛰었습니다. 붙여넣기 권한을 확인하거나 텍스트 또는 이미지를 복사한 후 다시 시도해 주세요.",
"clipboardSyncPermission": "동기화가 일시 중지되었습니다. 붙여넣기를 허용한 후 다시 시도해 주세요. 설정은 켜진 상태로 유지됩니다.",
"clipboardSyncRetry": "동기화 재시도",
+ "connectionTakingLong": "연결에 평소보다 시간이 걸리고 있어요…",
"credentialSigningRequired": "Mac 개발 버전에 서명 설정이 없습니다. Mac에서 서명을 설정하고 Cindy를 다시 시작한 후 다시 시도해 주세요.",
"credentialPasswordRejected": "Mac 로그인 암호를 확인하지 못했습니다. 다시 입력해 주세요.",
"credentialCancelled": "암호 확인을 취소했습니다. 준비되면 다시 연결해 주세요.",
@@ -110,7 +111,9 @@
"frameTime": "화면 준비 {{ms}} ms",
"rotate": "화면 회전",
"sound": "소리",
- "smallWindow": "화면 속 화면",
+ "smallWindow": "백그라운드 실행",
+ "controlUnavailableHint": "일시적으로 컴퓨터를 조작할 수 없습니다. 화면 이동과 확대·축소는 가능합니다.",
+ "backgroundRunningHint": "원격 데스크톱을 나가거나 다른 앱으로 전환해도 작은 창으로 화면을 계속 표시합니다.",
"displaySettings": "디스플레이",
"frameRate": "프레임 속도",
"fps": "{{count}} fps",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/remoteDesktop.json b/apps/mobile/src/i18n/locales/zh-CN/remoteDesktop.json
index 88e14f4970..4972ea0cf2 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/remoteDesktop.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/remoteDesktop.json
@@ -11,6 +11,7 @@
"clipboardSyncSkipped": "当前内容无法同步,已跳过。请检查粘贴权限,或复制文字、图片后重试。",
"clipboardSyncPermission": "同步已暂停,请允许粘贴权限后重试。开关保持开启。",
"clipboardSyncRetry": "重试同步",
+ "connectionTakingLong": "连接时间较长,请稍候…",
"credentialSigningRequired": "Mac 上的开发版缺少签名配置。请在 Mac 上配置签名并重新启动 Cindy,然后重试。",
"credentialPasswordRejected": "Mac 登录密码验证失败,请重新输入。",
"credentialCancelled": "已取消密码验证,准备好后可重新连接。",
@@ -110,7 +111,9 @@
"frameTime": "画面准备 {{ms}} ms",
"rotate": "旋转屏幕",
"sound": "声音",
- "smallWindow": "小窗模式",
+ "smallWindow": "后台运行",
+ "controlUnavailableHint": "暂时无法操作电脑,仍可移动和缩放画面。",
+ "backgroundRunningHint": "离开远程桌面或切到后台时,以小窗继续显示画面。",
"displaySettings": "显示",
"frameRate": "帧率",
"fps": "{{count}} 帧",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/remoteDesktop.json b/apps/mobile/src/i18n/locales/zh-TW/remoteDesktop.json
index 4c621e63fe..d481dc3ad2 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/remoteDesktop.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/remoteDesktop.json
@@ -11,6 +11,7 @@
"clipboardSyncSkipped": "目前內容無法同步,已略過。請檢查貼上權限,或複製文字、圖片後重試。",
"clipboardSyncPermission": "同步已暫停,請允許貼上權限後重試。開關保持開啟。",
"clipboardSyncRetry": "重試同步",
+ "connectionTakingLong": "連線時間較長,請稍候…",
"credentialSigningRequired": "Mac 上的開發版缺少簽名設定。請在 Mac 上設定簽名並重新啟動 Cindy,然後重試。",
"credentialPasswordRejected": "Mac 登入密碼驗證失敗,請重新輸入。",
"credentialCancelled": "已取消密碼驗證,準備好後可重新連線。",
@@ -110,7 +111,9 @@
"frameTime": "畫面準備 {{ms}} ms",
"rotate": "旋轉螢幕",
"sound": "聲音",
- "smallWindow": "小窗模式",
+ "smallWindow": "背景執行",
+ "controlUnavailableHint": "暫時無法操作電腦,仍可移動及縮放畫面。",
+ "backgroundRunningHint": "離開遠端桌面或切到背景時,以小視窗繼續顯示畫面。",
"displaySettings": "顯示",
"frameRate": "幀率",
"fps": "{{count}} 幀",
diff --git a/apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx b/apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx
new file mode 100644
index 0000000000..f49931be7e
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx
@@ -0,0 +1,35 @@
+import { requireNativeViewManager } from "expo-modules-core";
+import { Platform, type ViewProps } from "react-native";
+import type { Ref } from "react";
+import { remotePresentation } from "../../modules/cindy-remote-presentation/src";
+
+export interface NativeRemoteDesktopHandle {
+ receive(message: Record<string, unknown>): Promise<void>;
+ sendInput(message: Record<string, unknown>): Promise<boolean>;
+}
+type Props = ViewProps & {
+ inlineVisible: boolean;
+ ref?: Ref<NativeRemoteDesktopHandle>;
+ onMessage: (event: { nativeEvent: { data: string } }) => void;
+};
+
+// An OTA loaded by an older binary must continue using its WebView receiver.
+export const NativeRemoteDesktopView =
+ Platform.OS === "ios" && remotePresentation?.nativeVideo === true
+ ? requireNativeViewManager<Props>("CindyRemotePresentation")
+ : null;
+
+export const nativeMediaCommands = new Set([
+ "init",
+ "stop",
+ "videoSettings",
+ "iceConfig",
+ "answer",
+ "ice",
+ "fallback",
+ "presentation",
+ "pipPolicy",
+ "restorePresentation",
+ "resume",
+ "nativeViewport",
+]);
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx
index 7fd407a4b7..2e3bdbf678 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx
@@ -8,6 +8,7 @@ export type RemoteDesktopActionButtonProps = Pick<
| "disabled"
| "testID"
| "accessibilityLabel"
+ | "accessibilityHint"
| "accessibilityState"
| "accessibilityRole"
> & { onPress(): void; variant?: "plain" | "glass"; systemImage?: string };
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx
index 2cd6d15f8b..6eab4869c7 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx
@@ -48,6 +48,7 @@ import {
export function RemoteDesktopControls({
connected,
controlling,
+ viewOnly = !controlling,
controlDisabled,
inputMode,
displays,
@@ -68,6 +69,7 @@ export function RemoteDesktopControls({
connected: boolean;
security?: RemoteDesktopSecuritySettingsProps;
controlling: boolean;
+ viewOnly?: boolean;
controlDisabled: boolean;
inputMode: "touch" | "pointer";
displays: RemoteDesktopDisplay[];
@@ -81,6 +83,7 @@ export function RemoteDesktopControls({
canRotate: boolean;
canPip: boolean;
canAudio: boolean;
+ enabled?: boolean;
onRotate(): void;
onPip(): void;
};
@@ -108,7 +111,11 @@ export function RemoteDesktopControls({
const currentDisplay = displays.find((display) => display.id === displayId);
const canChooseDisplay = connected && displays.length > 1;
const nativeDisplayMenu = canChooseDisplay && usesNativePullDownMenu();
- const hint = !controlling ? "viewOnlyHint" : `${inputMode}Hint`;
+ const hint = viewOnly
+ ? "viewOnlyHint"
+ : !controlling
+ ? "controlUnavailableHint"
+ : `${inputMode}Hint`;
const displayLabel = (display: RemoteDesktopDisplay, index: number) =>
display.name?.trim() ||
t("remoteDesktop.displayNumber", { number: index + 1 });
@@ -137,13 +144,14 @@ export function RemoteDesktopControls({
icon: Eye,
onPress: onViewOnly,
disabled: controlDisabled,
- selected: connected && !controlling,
+ selected: connected && viewOnly,
},
{
key: "smallWindow",
icon: PictureInPicture2,
onPress: presentation.onPip,
- disabled: !presentation.canPip || !connected,
+ disabled: !presentation.enabled && (!presentation.canPip || !connected),
+ selected: presentation.enabled,
},
];
@@ -161,6 +169,11 @@ export function RemoteDesktopControls({
testID={`remoteDesktop.${key}`}
accessibilityRole="button"
accessibilityLabel={t(`remoteDesktop.${key}`)}
+ accessibilityHint={
+ key === "smallWindow"
+ ? t("remoteDesktop.backgroundRunningHint")
+ : undefined
+ }
accessibilityState={{ disabled, selected }}
disabled={disabled}
onPress={onPress}
@@ -190,6 +203,12 @@ export function RemoteDesktopControls({
</View>
)}
+ {!displaySettings && (
+ <Text style={styles.hint}>
+ {t("remoteDesktop.backgroundRunningHint")}
+ </Text>
+ )}
+
{!displaySettings && (
<View style={styles.section}>
<Text style={styles.sectionTitle}>
@@ -244,7 +263,12 @@ export function RemoteDesktopControls({
importantForAccessibility="no-hide-descendants"
style={{ flexDirection: "row", opacity: 0 }}
>
- {["touchHint", "pointerHint", "viewOnlyHint"].map((key) => (
+ {[
+ "touchHint",
+ "pointerHint",
+ "viewOnlyHint",
+ "controlUnavailableHint",
+ ].map((key) => (
<Text
key={key}
style={[styles.hint, { width: "100%", flexShrink: 0 }]}
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx
new file mode 100644
index 0000000000..0456bf1dfe
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx
@@ -0,0 +1,192 @@
+import { useEffect, useRef, useState, type ReactNode } from "react";
+import { StyleSheet, View } from "react-native";
+import { useNavigationContainerRef, useRouter } from "expo-router";
+import { useNavigationState } from "expo-router/react-navigation";
+import { useAuth } from "@/auth/AuthContext";
+import {
+ removeDesktopHistory,
+ activeDesktopRoute,
+ REMOTE_DESKTOP_ROUTE,
+} from "./remoteDesktopNavigation";
+import { NativeRemoteDesktopView } from "./NativeRemoteDesktopView";
+import { RemoteDesktopSession } from "./RemoteDesktopScreen";
+import { logDesktopNavigation } from "./remoteDesktopNavigationDebug";
+
+type Session = { account: string; deviceId: string; deviceName: string };
+
+/** One connected viewer survives its route, but never its signed-in owner. */
+export function RemoteDesktopHost({ children }: { children: ReactNode }) {
+ const auth = useAuth();
+ const router = useRouter();
+ const navigation = useNavigationContainerRef();
+ const rootState = useNavigationState((state) => state);
+ const route = activeDesktopRoute(rootState);
+ const params = route?.params as
+ { deviceId?: string; deviceName?: string } | undefined;
+ const account =
+ auth.isAuthenticated && auth.user?.id
+ ? `${auth.user.id}:${auth.accountGeneration}`
+ : undefined;
+ const inDesktop = route?.name === REMOTE_DESKTOP_ROUTE;
+ const routeDevice =
+ inDesktop && typeof params?.deviceId === "string" ? params.deviceId : "";
+ const routeName =
+ typeof params?.deviceName === "string" ? params.deviceName : routeDevice;
+ const [session, setSession] = useState<Session | null>(null);
+ const [visible, setVisible] = useState(true);
+ const restorePending = useRef<Session | null>(null);
+ useEffect(() => {
+ if (!NativeRemoteDesktopView || !account) {
+ setSession(null);
+ return;
+ }
+ if (routeDevice) {
+ setSession((current) =>
+ current?.account === account && current.deviceId === routeDevice
+ ? current
+ : { account, deviceId: routeDevice, deviceName: routeName },
+ );
+ setVisible(true);
+ } else
+ setSession((current) => (current?.account === account ? current : null));
+ }, [account, routeDevice, routeName]);
+ const current = session?.account === account ? session : null;
+ const owner = useRef(current);
+ owner.current = current;
+ useEffect(
+ () =>
+ navigation.addListener("state", () => {
+ logDesktopNavigation("container event", navigation.getRootState());
+ }),
+ [navigation],
+ );
+ useEffect(() => {
+ logDesktopNavigation("host observed", rootState, {
+ hasSession: Boolean(current),
+ focused: Boolean(current && routeDevice === current.deviceId),
+ visible,
+ });
+ }, [rootState, current, routeDevice, visible]);
+ useEffect(() => {
+ if (restorePending.current !== current || routeDevice === current?.deviceId)
+ restorePending.current = null;
+ }, [current, routeDevice]);
+ useEffect(() => {
+ if (!NativeRemoteDesktopView || !rootState) return;
+ // Drop abandoned desktop entries even if another page was pushed before
+ // a delayed PiP transition completed. Ordinary Back then stays ordinary.
+ const next = removeDesktopHistory(
+ rootState,
+ inDesktop ? route?.key : undefined,
+ );
+ if (next && next !== rootState) {
+ logDesktopNavigation("cleanup before", navigation.getRootState());
+ logDesktopNavigation("cleanup requested", next);
+ navigation.resetRoot(next);
+ logDesktopNavigation("cleanup dispatched", navigation.getRootState());
+ }
+ }, [rootState, inDesktop, route?.key, navigation]);
+ const foreground = visible && routeDevice === current?.deviceId;
+ return (
+ <View style={styles.root}>
+ {children}
+ {NativeRemoteDesktopView && current && (
+ <View
+ style={[StyleSheet.absoluteFill, { opacity: foreground ? 1 : 0 }]}
+ pointerEvents={foreground ? "auto" : "none"}
+ accessibilityElementsHidden={!foreground}
+ importantForAccessibility={
+ foreground ? "auto" : "no-hide-descendants"
+ }
+ collapsable={false}
+ >
+ <RemoteDesktopSession
+ key={`${current.account}:${current.deviceId}`}
+ deviceId={current.deviceId}
+ deviceName={current.deviceName}
+ focused={routeDevice === current.deviceId}
+ onBack={() => {
+ logDesktopNavigation("back callback", navigation.getRootState(), {
+ sameOwner: owner.current === current,
+ sourceFocused: routeDevice === current.deviceId,
+ });
+ if (owner.current !== current || routeDevice !== current.deviceId)
+ return;
+ restorePending.current = null;
+ const state = navigation.getRootState();
+ if (!state) return;
+ const active = activeDesktopRoute(state);
+ const keepKey =
+ active?.name === REMOTE_DESKTOP_ROUTE &&
+ active.key !== route?.key
+ ? active.key
+ : undefined;
+ const next = removeDesktopHistory(state, keepKey);
+ logDesktopNavigation("back decision", next ?? undefined, {
+ sameSourceRoute: active?.key === route?.key,
+ preserveNewDesktop: Boolean(keepKey),
+ action: !next
+ ? "replace-home"
+ : next !== state
+ ? "reset"
+ : "none",
+ });
+ if (!next) router.replace("/");
+ else if (next !== state) navigation.resetRoot(next);
+ logDesktopNavigation(
+ "back dispatched",
+ navigation.getRootState(),
+ );
+ }}
+ onRestore={() => {
+ logDesktopNavigation(
+ "restore callback",
+ navigation.getRootState(),
+ {
+ sameOwner: owner.current === current,
+ pending: restorePending.current === current,
+ },
+ );
+ if (
+ owner.current !== current ||
+ restorePending.current === current
+ )
+ return;
+ const state = navigation.getRootState();
+ const active = activeDesktopRoute(state);
+ if (
+ active?.name === REMOTE_DESKTOP_ROUTE &&
+ (active.params as { deviceId?: string } | undefined)
+ ?.deviceId === current.deviceId
+ )
+ return;
+ restorePending.current = current;
+ logDesktopNavigation("restore push", state);
+ router.push({
+ pathname: "/devices/desktop/[deviceId]",
+ params: {
+ deviceId: current.deviceId,
+ deviceName: current.deviceName,
+ },
+ });
+ }}
+ onVisibility={(next) => {
+ logDesktopNavigation("visibility", navigation.getRootState(), {
+ visible: next,
+ sameOwner: owner.current === current,
+ });
+ if (owner.current === current) setVisible(next);
+ }}
+ onEnded={() => {
+ logDesktopNavigation("ended", navigation.getRootState(), {
+ sameOwner: owner.current === current,
+ });
+ setSession((owner) => (owner === current ? null : owner));
+ }}
+ />
+ </View>
+ )}
+ </View>
+ );
+}
+const styles = StyleSheet.create({ root: { flex: 1 } });
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
index c40bacb56f..73018f754c 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
@@ -22,6 +22,10 @@ import {
View,
useWindowDimensions,
} from "react-native";
+import Animated from "react-native-reanimated";
+import { Monitor } from "lucide-react-native";
+import { useReduceMotionEnabled } from "@/hooks/useReduceMotion";
+import { motionDuration } from "@/theme/tokens";
import {
Stack,
useLocalSearchParams,
@@ -47,6 +51,8 @@ import {
remoteDesktopFailureKey,
REMOTE_DESKTOP_CHANNEL,
REMOTE_DESKTOP_MAX_FRAME_BYTES,
+ REMOTE_DESKTOP_NETWORK,
+ REMOTE_DESKTOP_ICE_SERVERS,
isRemoteDesktopCursor,
type RemoteDesktopCursor,
REMOTE_DESKTOP_MAX_CLIPBOARD_CHARS,
@@ -59,6 +65,7 @@ import {
type RemoteDesktopDisplayMode,
} from "@cindy/device-link";
import { useDeviceLink } from "@/device-link/DeviceLinkContext";
+import { BACKGROUND_TRANSITION_TIMEOUT_MS } from "@/device-link/backgroundConnection";
import { useAuth } from "@/auth/AuthContext";
import { DEVICE_LINK_API_BASE_URL } from "@/config/env";
import {
@@ -69,6 +76,7 @@ import {
import { Text } from "@/components/AppText";
import { useScreenEdgePadding } from "@/components/screenEdgeInsets";
import { goBackGuarded } from "@/utils/backGuard";
+import { mobileDebugLog } from "@/debug/mobileDebugLog";
import {
fontWeight,
iconSize,
@@ -82,6 +90,11 @@ import {
} from "@/theme";
import { remotePresentation } from "../../modules/cindy-remote-presentation/src";
import { remoteDesktopViewerHtml } from "./viewerHtml";
+import {
+ NativeRemoteDesktopView,
+ nativeMediaCommands,
+ type NativeRemoteDesktopHandle,
+} from "./NativeRemoteDesktopView";
import { useMouseButtonsPreference } from "./useMouseButtonsPreference";
import { useInputModePreference } from "./useInputModePreference";
import { useAutoUnlockSettings } from "./useAutoUnlockSettings";
@@ -89,6 +102,7 @@ import { supportsAutoUnlock } from "./autoUnlockSupport";
import { useLockOnExitPreference } from "./useLockOnExitPreference";
import { useRemoteDesktopSafety } from "./useRemoteDesktopSafety";
import { useVideoSettingsPreference } from "./useVideoSettingsPreference";
+import { usePictureInPicturePreference } from "./usePictureInPicturePreference";
import { PermissionGuide } from "./PermissionGuide";
import { RemoteDesktopBackButton } from "./RemoteDesktopBackButton";
import { RemoteDesktopNetworkStatus } from "./RemoteDesktopNetworkStatus";
@@ -158,7 +172,6 @@ const LABELS: Record<string, string> = {
};
export default function RemoteDesktopScreen() {
- const auth = useAuth();
const { deviceId: rawId, deviceName: rawName } = useLocalSearchParams<{
deviceId: string;
deviceName?: string;
@@ -167,6 +180,45 @@ export default function RemoteDesktopScreen() {
const deviceName = typeof rawName === "string" ? rawName : deviceId;
const router = useRouter();
const focused = useIsFocused();
+ return (
+ <>
+ <Stack.Screen
+ options={{
+ headerShown: false,
+ gestureEnabled: false,
+ statusBarHidden: true,
+ }}
+ />
+ <RemoteDesktopSession
+ deviceId={deviceId}
+ deviceName={deviceName}
+ focused={focused}
+ onBack={() => goBackGuarded(router)}
+ />
+ </>
+ );
+}
+
+export function RemoteDesktopSession({
+ deviceId,
+ deviceName,
+ focused,
+ onBack,
+ onRestore,
+ onVisibility,
+ onEnded,
+}: {
+ deviceId: string;
+ deviceName: string;
+ focused: boolean;
+ onBack(): void;
+ onRestore?(): void;
+ onVisibility?(visible: boolean): void;
+ onEnded?(): void;
+}) {
+ const auth = useAuth();
+ const navigation = useRef({ onBack, onRestore, onVisibility, onEnded });
+ navigation.current = { onBack, onRestore, onVisibility, onEnded };
const focusedRef = useRef(focused);
focusedRef.current = focused;
const link = useDeviceLink();
@@ -210,16 +262,26 @@ export default function RemoteDesktopScreen() {
(interfaceAngle === 270 ||
(interfaceAngle === null && insets.right > insets.left));
const webview = useRef<ComponentRef<typeof WebView>>(null);
+ const nativeViewer = useRef<NativeRemoteDesktopHandle>(null);
const html = useRef(
- remoteDesktopViewerHtml(colors.surface, colors.textPrimary),
+ remoteDesktopViewerHtml(
+ colors.surface,
+ colors.textPrimary,
+ Boolean(NativeRemoteDesktopView),
+ ),
).current;
const active = useRef<RemoteDesktopLease | null>(null);
const wantsControl = useRef(true);
+ const [viewOnlySelected, setViewOnlySelected] = useState(false);
// Last control bit we asked the host for but have not confirmed. Overflow and
// take-control can time out after the local bit already moved; heartbeats use
// this to retry a release or restore local control instead of ignoring host-true.
const pendingHostControl = useRef<boolean | null>(null);
const controlInFlight = useRef(false);
+ const controlRestoration = useRef<Promise<void> | null>(null);
+ // Revoking background permission must not lose the pending fullscreen input restore.
+ const restoreAfterPipDisabled = useRef(false);
+ const finishBackgroundTransition = useRef<(() => void) | null>(null);
const recovery = useRef({
enabled: true,
at: 0,
@@ -277,11 +339,25 @@ export default function RemoteDesktopScreen() {
);
}, [error, t]);
const [frameReady, setFrameReady] = useState(false);
+ const reduceMotion = useReduceMotionEnabled();
+ const mediaReveal = {
+ opacity: frameReady ? 1 : 0,
+ transitionProperty: "opacity" as const,
+ transitionDuration:
+ frameReady && reduceMotion === false ? motionDuration.fast : 0,
+ };
const [controlReady, setControlReady] = useState(false);
const connectionPending = !error && (!lease || !frameReady || !controlReady);
const showConnectionStatus =
!isLeaving && (connectionPending || (!error && status === "reconnecting"));
const showExitLockStatus = isLeaving && exitLockPending;
+ const [connectionTakingLong, setConnectionTakingLong] = useState(false);
+ useEffect(() => {
+ setConnectionTakingLong(false);
+ if (frameReady || !showConnectionStatus) return;
+ const timer = setTimeout(() => setConnectionTakingLong(true), 8000);
+ return () => clearTimeout(timer);
+ }, [frameReady, showConnectionStatus, deviceId]);
const connectionLabel = t(
showExitLockStatus
? "remoteDesktop.lockingOnExit"
@@ -311,7 +387,19 @@ export default function RemoteDesktopScreen() {
const applyPendingVideoSettings = useRef<() => void>(() => {});
const [canPip, setCanPip] = useState(false);
const presentation = useRef(false);
+ const actualPresentation = useRef(false);
+ const [pipEnabled, setPipEnabled] = usePictureInPicturePreference();
+ const pipEnabledRef = useRef(pipEnabled);
+ pipEnabledRef.current = pipEnabled;
+ const pipPrepared = useRef(false);
+ const presentationGeneration = useRef(0);
+ const restoringPresentation = useRef(false);
+ const startPresentationRef = useRef<(enter?: boolean) => Promise<void>>(
+ async () => {},
+ );
+ const pendingPresentation = useRef<((active: boolean) => void) | null>(null);
const presentationTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const presentationReturnedToActive = useRef(false);
const [showMouseButtons, setShowMouseButtons] = useMouseButtonsPreference();
const [keyboard, setKeyboard] = useState(false);
const [fullKeys, setFullKeys] = useState(false);
@@ -330,10 +418,49 @@ export default function RemoteDesktopScreen() {
const [keyPage, setKeyPage] = useState(0);
const [comboMode, setComboMode] = useState(true);
const [modifiers, setModifiers] = useState<string[]>([]);
- const send = useCallback(
- (message: object) => webview.current?.postMessage(JSON.stringify(message)),
- [],
- );
+ const send = useCallback((message: object) => {
+ const command = message as Record<string, unknown>;
+ const owner = active.current;
+ const attempt = command.attemptId ?? mediaAttempt.current;
+ webview.current?.postMessage(JSON.stringify(message));
+ if (
+ NativeRemoteDesktopView &&
+ nativeMediaCommands.has(String(command.type))
+ ) {
+ void nativeViewer.current
+ ?.receive({
+ ...command,
+ epoch: command.epoch ?? owner?.lease,
+ ...(command.type === "init"
+ ? {
+ net: REMOTE_DESKTOP_NETWORK,
+ iceServers: REMOTE_DESKTOP_ICE_SERVERS,
+ }
+ : {}),
+ })
+ .catch(() => {
+ if (
+ !owner ||
+ active.current !== owner ||
+ mediaAttempt.current !== attempt
+ )
+ return;
+ // Route a native bridge failure through the existing recovery path.
+ nativeMessage.current({
+ nativeEvent: {
+ data: JSON.stringify({
+ type: "fallback",
+ epoch: owner.lease,
+ attemptId: attempt,
+ }),
+ },
+ });
+ });
+ }
+ }, []);
+ const nativeMessage = useRef<
+ (event: { nativeEvent: { data: string } }) => void
+ >(() => {});
useEffect(() => {
const enabled =
keyboard && !fullKeys && focused && Boolean(lease?.controlling);
@@ -512,12 +639,22 @@ export default function RemoteDesktopScreen() {
unlockFrame.current?.(false);
unlockFrame.current = null;
presentation.current = false;
+ actualPresentation.current = false;
+ pipPrepared.current = false;
+ restoreAfterPipDisabled.current = false;
+ presentationGeneration.current++;
+ settingInFlight.current = false;
+ pendingPresentation.current?.(false);
+ pendingPresentation.current = null;
if (presentationTimer.current) clearTimeout(presentationTimer.current);
presentationTimer.current = null;
void remotePresentation?.playback(false).catch(() => {});
connecting.current = false;
pendingHostControl.current = null;
controlInFlight.current = false;
+ controlRestoration.current = null;
+ finishBackgroundTransition.current?.();
+ finishBackgroundTransition.current = null;
const previous = active.current;
setExitLockPending(Boolean(previous && exiting && exitLock.current));
active.current = null;
@@ -533,7 +670,7 @@ export default function RemoteDesktopScreen() {
frameMs: null,
frameAt: 0,
};
- send({ type: "stop", preserveFrame });
+ send({ type: "stop", preserveFrame, epoch: previous?.lease });
if (alive.current) {
setLease(null);
setViewerDisplayApplied(false);
@@ -687,7 +824,7 @@ export default function RemoteDesktopScreen() {
if (controlInFlight.current) return;
controlInFlight.current = true;
pendingHostControl.current = enabled;
- void request<{ controlling: boolean }>({
+ return request<{ controlling: boolean }>({
op: "control",
lease: current.lease,
enabled,
@@ -705,6 +842,48 @@ export default function RemoteDesktopScreen() {
});
};
const requestHostControlRef = useRef(requestHostControl);
+ const restoreInlinePresentation = () => {
+ const current = active.current;
+ if (
+ !current ||
+ (!pipPrepared.current && !restoreAfterPipDisabled.current) ||
+ presentation.current ||
+ actualPresentation.current ||
+ !focusedRef.current ||
+ linkRef.current.status !== "online" ||
+ AppState.currentState !== "active"
+ )
+ return;
+ pipPrepared.current = false;
+ restoreAfterPipDisabled.current = false;
+ send({
+ type: "pipPolicy",
+ enabled: pipEnabledRef.current && frameReady,
+ authorized: false,
+ });
+ // Returning to a visible viewer restores the user's previous input mode
+ // through the host's normal authorization path, never by a local override.
+ const restoration = wantsControl.current
+ ? requestHostControlRef.current(current, true)
+ : request({
+ op: "presentation",
+ lease: current.lease,
+ enabled: false,
+ })
+ .then(() => {})
+ .catch((cause) => {
+ if (active.current === current) fail(cause);
+ });
+ if (restoration) {
+ controlRestoration.current = restoration;
+ void restoration.finally(() => {
+ if (controlRestoration.current === restoration)
+ controlRestoration.current = null;
+ });
+ }
+ };
+ const restoreInlinePresentationRef = useRef(restoreInlinePresentation);
+ restoreInlinePresentationRef.current = restoreInlinePresentation;
requestHostControlRef.current = requestHostControl;
const connect = useCallback(
async (displayId?: string, takeover = false) => {
@@ -777,7 +956,12 @@ export default function RemoteDesktopScreen() {
setStatus("compatibility");
audioUnavailable.current = false;
setSettingNotice(null);
- if (result.systemAudio && videoSettingsRef.current.audio) {
+ // Native video needs a playback session for AVKit PiP readiness even
+ // when its audio track is disabled. Release it when the viewer stops.
+ if (
+ NativeRemoteDesktopView ||
+ (result.systemAudio && videoSettingsRef.current.audio)
+ ) {
try {
await remotePresentation?.playback(true);
} catch {
@@ -876,7 +1060,7 @@ export default function RemoteDesktopScreen() {
},
[stop],
);
- const leave = async () => {
+ const leave = async (returnToSource = navigation.current.onBack) => {
if (leaving.current) return;
leaving.current = true;
setIsLeaving(true);
@@ -884,7 +1068,49 @@ export default function RemoteDesktopScreen() {
Keyboard.dismiss();
const ending = stop(false, true);
if (exitLock.current) await ending;
- goBackGuarded(router);
+ returnToSource();
+ };
+ const back = async () => {
+ if (pendingPresentation.current) return;
+ const returnToSource = navigation.current.onBack;
+ const startedAt = performance.now();
+ mobileDebugLog("info", "lifecycle", "remote desktop back requested", {
+ backgroundRunning: pipEnabledRef.current,
+ pipReady: canPip,
+ pipActive: actualPresentation.current,
+ });
+ if (
+ !pipEnabledRef.current ||
+ !NativeRemoteDesktopView ||
+ !active.current ||
+ !canPip
+ ) {
+ await leave(returnToSource);
+ return;
+ }
+ Keyboard.dismiss();
+ if (!actualPresentation.current) {
+ const started = new Promise<boolean>((resolve) => {
+ pendingPresentation.current = resolve;
+ });
+ await startPresentationRef.current();
+ const entered = await started;
+ mobileDebugLog(
+ "info",
+ "lifecycle",
+ "remote desktop back presentation settled",
+ {
+ entered,
+ elapsedMs: Math.round(performance.now() - startedAt),
+ },
+ );
+ if (!alive.current) return;
+ if (!entered) {
+ await leave(returnToSource);
+ return;
+ }
+ }
+ returnToSource();
};
const retry = () => {
securityRef.current.resetConnectionAttempt();
@@ -925,17 +1151,31 @@ export default function RemoteDesktopScreen() {
alive.current = true;
const subscription = AppState.addEventListener("change", (state) => {
setAppState(state);
+ if (state === "active") presentationReturnedToActive.current = true;
// iOS enters inactive during an interrupted Home gesture or a system
// overlay. Release held input, but keep this viewer's lease and stream.
if (state === "inactive") {
send({ type: "releaseInput" });
heldKeys.current.clear();
setModifiers([]);
- } else if (state === "background" && !presentation.current) {
+ if (
+ pipEnabledRef.current &&
+ NativeRemoteDesktopView &&
+ !presentation.current &&
+ !settingInFlight.current
+ )
+ void startPresentationRef.current(false);
+ } else if (
+ state === "background" &&
+ !presentation.current &&
+ !pipPrepared.current
+ ) {
securityRef.current.resetConnectionAttempt();
pause();
- } else if (state === "active" && active.current) send({ type: "resume" });
- else if (
+ } else if (state === "active" && active.current) {
+ send({ type: "resume" });
+ restoreInlinePresentationRef.current();
+ } else if (
state === "active" &&
recovery.current.enabled &&
!active.current
@@ -968,6 +1208,9 @@ export default function RemoteDesktopScreen() {
if (
!current ||
heartbeatBusy === current.lease ||
+ (NativeRemoteDesktopView &&
+ pipPrepared.current &&
+ linkRef.current.status !== "online") ||
(presentation.current && AppState.currentState !== "active")
)
return;
@@ -1099,15 +1342,40 @@ export default function RemoteDesktopScreen() {
}, [request, fail, send, stop, pause, releaseControl]);
useEffect(() => {
// Route blur means leaving this desktop (including a native back swipe).
+ mobileDebugLog("info", "lifecycle", "remote desktop focus effect", {
+ focused,
+ pipActive: actualPresentation.current,
+ preparing: presentation.current,
+ restoring: restoringPresentation.current,
+ backgroundRunning: pipEnabledRef.current,
+ });
// App background/inactive events use pause() without the exit flag.
- if (!focused && !presentation.current) {
+ if (!focused && actualPresentation.current) {
+ navigation.current.onVisibility?.(false);
+ } else if (
+ !focused &&
+ pipEnabledRef.current &&
+ NativeRemoteDesktopView &&
+ active.current
+ ) {
+ if (!presentation.current) void startPresentationRef.current();
+ } else if (!focused) {
leaving.current = true;
setIsLeaving(true);
pause(true);
+ navigation.current.onEnded?.();
} else if (focused) {
+ navigation.current.onVisibility?.(true);
+ if (restoringPresentation.current) {
+ send({ type: "restorePresentation" });
+ restoringPresentation.current = false;
+ } else if (presentation.current) {
+ send({ type: "presentation", enabled: false });
+ }
leaving.current = false;
setIsLeaving(false);
setExitLockPending(false);
+ restoreInlinePresentationRef.current();
if (!active.current) void connectRef.current();
}
}, [focused, pause, videoPreferencesLoaded]);
@@ -1180,11 +1448,23 @@ export default function RemoteDesktopScreen() {
t,
]);
useEffect(() => {
- if (link.status !== "online" && !presentation.current) pause();
- else if (!active.current) void connectRef.current();
+ if (link.status !== "online") {
+ // A native stream with an acknowledged background lease outlives signaling.
+ // Restoring fullscreen must not tear it down while that socket reconnects.
+ if (
+ !presentation.current &&
+ !(NativeRemoteDesktopView && pipPrepared.current)
+ )
+ pause();
+ } else if (!active.current) void connectRef.current();
+ else restoreInlinePresentationRef.current();
}, [link.status, pause]);
- const onMessage = (event: WebViewMessageEvent) => {
+ const onMessage = (
+ event:
+ | Pick<WebViewMessageEvent, "nativeEvent">
+ | { nativeEvent: { data: string } },
+ ) => {
if (!alive.current || event.nativeEvent.data.length > 65_536) return;
let message: Record<string, unknown>;
try {
@@ -1215,7 +1495,20 @@ export default function RemoteDesktopScreen() {
});
return;
}
+ if (
+ NativeRemoteDesktopView &&
+ typeof message.attemptId === "string" &&
+ message.attemptId !== mediaAttempt.current
+ )
+ return;
switch (message.type) {
+ case "nativeViewport":
+ if (NativeRemoteDesktopView)
+ void nativeViewer.current?.receive(message).catch(() => {});
+ break;
+ case "nativeCursor":
+ webview.current?.postMessage(JSON.stringify(message));
+ break;
case "viewportChanged":
if (
typeof message.width === "number" &&
@@ -1249,23 +1542,187 @@ export default function RemoteDesktopScreen() {
case "pipCapability":
setCanPip(message.supported === true);
break;
+ case "presentationDiagnostic":
+ mobileDebugLog(
+ "info",
+ "lifecycle",
+ "remote desktop native presentation diagnostic",
+ {
+ event: message.event,
+ domain: message.domain,
+ code: message.code,
+ nativeState: message.nativeState,
+ sceneState: message.sceneState,
+ armed: message.armed,
+ authorized: message.authorized,
+ possible: message.possible,
+ active: message.active,
+ suspended: message.suspended,
+ starting: message.starting,
+ inlineVisible: message.inlineVisible,
+ sourceHidden: message.sourceHidden,
+ inWindow: message.inWindow,
+ ancestorsVisible: message.ancestorsVisible,
+ opacity: message.opacity,
+ width: message.width,
+ height: message.height,
+ layerWidth: message.layerWidth,
+ layerHeight: message.layerHeight,
+ sourceX: message.sourceX,
+ sourceY: message.sourceY,
+ sourceWidth: message.sourceWidth,
+ sourceHeight: message.sourceHeight,
+ surfaceHidden: message.surfaceHidden,
+ surfaceOpacity: message.surfaceOpacity,
+ hasFrame: message.hasFrame,
+ playbackReady: message.playbackReady,
+ inlineFrameReady: message.inlineFrameReady,
+ renderedFrames: message.renderedFrames,
+ restoring: message.restoring,
+ audioCategory: message.audioCategory,
+ audioMode: message.audioMode,
+ rtcAudioActive: message.rtcAudioActive,
+ rtcAudioActivations: message.rtcAudioActivations,
+ },
+ );
+ break;
+ case "presentationStarting":
+ if (
+ pipEnabledRef.current &&
+ !presentation.current &&
+ !settingInFlight.current
+ )
+ void startPresentationRef.current(false);
+ break;
case "presentation":
- if (presentationTimer.current) clearTimeout(presentationTimer.current);
- presentationTimer.current = null;
+ // AVKit can start before the Home AppState event / host acknowledgement.
+ if (
+ NativeRemoteDesktopView &&
+ message.active === true &&
+ pipEnabledRef.current &&
+ !presentation.current &&
+ !settingInFlight.current
+ )
+ void startPresentationRef.current(false);
+ mobileDebugLog(
+ "info",
+ "lifecycle",
+ "remote desktop presentation state",
+ {
+ active: message.active === true,
+ previousActive: actualPresentation.current,
+ preparing: presentationTimer.current !== null,
+ focused: focusedRef.current,
+ appState: AppState.currentState,
+ },
+ );
+ const authorized = !NativeRemoteDesktopView || pipPrepared.current;
+ if (
+ NativeRemoteDesktopView &&
+ message.active !== true &&
+ actualPresentation.current &&
+ !pipPrepared.current &&
+ presentationTimer.current !== null &&
+ settingInFlight.current &&
+ (AppState.currentState !== "active" || !focusedRef.current)
+ ) {
+ // A window closed before its host handoff completed. Retire the lease
+ // so a late ACK cannot leave the host in background-viewing mode.
+ pause(!focusedRef.current);
+ if (!focusedRef.current) navigation.current.onEnded?.();
+ break;
+ }
+ if (
+ (message.active !== true &&
+ actualPresentation.current &&
+ !settingInFlight.current) ||
+ authorized
+ ) {
+ if (presentationTimer.current)
+ clearTimeout(presentationTimer.current);
+ presentationTimer.current = null;
+ pendingPresentation.current?.(message.active === true && authorized);
+ pendingPresentation.current = null;
+ }
presentation.current = message.active === true;
- if (!presentation.current) {
- void request({
- op: "presentation",
- lease: current.lease,
- enabled: false,
- }).catch(() => {});
- if (!videoSettingsRef.current.audio)
+ actualPresentation.current = presentation.current;
+ if (presentation.current && !focusedRef.current)
+ navigation.current.onVisibility?.(false);
+ if (
+ !presentation.current &&
+ !focusedRef.current &&
+ !restoringPresentation.current
+ ) {
+ recovery.current.enabled = false;
+ void stop(false, true);
+ navigation.current.onEnded?.();
+ } else if (!presentation.current) {
+ restoreInlinePresentationRef.current();
+ if (!NativeRemoteDesktopView && !videoSettingsRef.current.audio)
void remotePresentation?.playback(false).catch(() => {});
- if (AppState.currentState === "background") pause();
+ if (
+ !NativeRemoteDesktopView &&
+ AppState.currentState === "background"
+ )
+ pause();
}
break;
+ case "presentationRestore":
+ mobileDebugLog(
+ "info",
+ "lifecycle",
+ "remote desktop native restore requested",
+ {
+ focused: focusedRef.current,
+ pipActive: actualPresentation.current,
+ restoring: restoringPresentation.current,
+ inlineVisible: message.inlineVisible === true,
+ sourceHidden: message.sourceHidden === true,
+ },
+ );
+ restoringPresentation.current = true;
+ navigation.current.onVisibility?.(true);
+ if (focusedRef.current) {
+ send({ type: "restorePresentation" });
+ restoringPresentation.current = false;
+ } else navigation.current.onRestore?.();
+ break;
case "presentationFailed":
+ presentationGeneration.current++;
+ settingInFlight.current = false;
+ mobileDebugLog(
+ "warn",
+ "lifecycle",
+ "remote desktop presentation failed",
+ {
+ focused: focusedRef.current,
+ appState: AppState.currentState,
+ reason: message.reason,
+ description: message.description,
+ failureReason: message.failureReason,
+ underlyingDomain: message.underlyingDomain,
+ underlyingCode: message.underlyingCode,
+ underlyingDescription: message.underlyingDescription,
+ rtcAudioActive: message.rtcAudioActive,
+ rtcAudioActivations: message.rtcAudioActivations,
+ domain: message.domain,
+ code: message.code,
+ nativeState: message.nativeState,
+ sceneState: message.sceneState,
+ possible: message.possible,
+ active: message.active,
+ authorized: message.authorized,
+ armed: message.armed,
+ hasFrame: message.hasFrame,
+ },
+ );
presentation.current = false;
+ actualPresentation.current = false;
+ restoreInlinePresentationRef.current();
+ pipPrepared.current = false;
+ pendingPresentation.current?.(false);
+ pendingPresentation.current = null;
+ send({ type: "pipPolicy", enabled: false });
if (presentationTimer.current) clearTimeout(presentationTimer.current);
presentationTimer.current = null;
void request({
@@ -1273,18 +1730,35 @@ export default function RemoteDesktopScreen() {
lease: current.lease,
enabled: false,
}).catch(() => {});
- if (!videoSettingsRef.current.audio)
+ if (!NativeRemoteDesktopView && !videoSettingsRef.current.audio)
void remotePresentation?.playback(false).catch(() => {});
setSettingNotice(t("remoteDesktop.pipUnavailable"));
setControlPage("controls");
setOperations(true);
if (AppState.currentState === "background") pause();
+ if (!focusedRef.current) {
+ void stop(false, true);
+ navigation.current.onEnded?.();
+ }
break;
case "videoFrameReady":
if (mediaAttempt.current === message.attemptId)
timing.current?.("video-frame-ready");
break;
case "streaming":
+ if (
+ NativeRemoteDesktopView &&
+ message.attemptId !== mediaAttempt.current
+ )
+ return;
+ if (NativeRemoteDesktopView)
+ webview.current?.postMessage(
+ JSON.stringify({
+ type: "nativeVideo",
+ epoch: current.lease,
+ active: true,
+ }),
+ );
timing.current?.("video-presented");
setFrameReady(true);
setSettingBusy(false);
@@ -1298,6 +1772,37 @@ export default function RemoteDesktopScreen() {
setFrameReady(true);
break;
case "fallback":
+ if (
+ NativeRemoteDesktopView &&
+ message.attemptId !== mediaAttempt.current
+ )
+ return;
+ mobileDebugLog("warn", "lifecycle", "remote desktop media fallback", {
+ pipActive: actualPresentation.current,
+ appState: AppState.currentState,
+ retry: message.retry !== false,
+ // Never log signaling, peer identifiers or arbitrary remote text.
+ reason: [
+ "background",
+ "host",
+ "disconnected",
+ "failed",
+ "closed",
+ "connect-timeout",
+ "answer",
+ "offer",
+ ].includes(String(message.reason))
+ ? String(message.reason)
+ : "other",
+ });
+ if (NativeRemoteDesktopView)
+ webview.current?.postMessage(
+ JSON.stringify({
+ type: "nativeVideo",
+ epoch: current.lease,
+ active: false,
+ }),
+ );
setCanPip(false);
setSettingBusy(false);
streaming.current = false;
@@ -1355,12 +1860,21 @@ export default function RemoteDesktopScreen() {
return;
}
inputBusy.current = current.lease;
- void request({
- op: "input",
- lease: current.lease,
- sequence: message.sequence as number,
- events: message.events,
- })
+ const events = message.events;
+ void (async () => {
+ if (
+ NativeRemoteDesktopView &&
+ (await nativeViewer.current?.sendInput(message).catch(() => false))
+ )
+ return;
+ if (active.current !== current || !current.controlling) return;
+ await request({
+ op: "input",
+ lease: current.lease,
+ sequence: message.sequence as number,
+ events,
+ });
+ })()
.catch((cause) => {
if (active.current !== current) return;
resolveControlFailure(cause);
@@ -1375,17 +1889,29 @@ export default function RemoteDesktopScreen() {
};
const toggleControl = async () => {
const current = active.current;
- if (!current || busy || controlInFlight.current) return;
+ if (
+ !current ||
+ busy ||
+ controlInFlight.current ||
+ settingInFlight.current ||
+ presentationTimer.current
+ )
+ return;
setBusy(true);
setError(null);
controlInFlight.current = true;
try {
+ pipPrepared.current = false;
+ presentationGeneration.current++;
+ send({ type: "pipPolicy", enabled: false });
if (presentation.current) {
presentation.current = false;
send({ type: "presentation", enabled: false });
}
send({ type: "control", enabled: false });
- const enabled = !current.controlling;
+ const enabled = viewOnlySelected;
+ setViewOnlySelected(!enabled);
+ wantsControl.current = enabled;
if (pendingHostControl.current === false && enabled) {
// Overflow timed out with an unconfirmed host release. Taking control
// first would skip stopInput while a key/button may still be held.
@@ -1442,6 +1968,11 @@ export default function RemoteDesktopScreen() {
setSettingBusy(true);
setSettingNotice(null);
try {
+ // Preserve the pending fullscreen control restoration until AVKit stops.
+ if (!presentation.current && !actualPresentation.current)
+ pipPrepared.current = false;
+ presentationGeneration.current++;
+ send({ type: "pipPolicy", enabled: false });
const wasPresenting = presentation.current;
if (wasPresenting) {
if (presentationTimer.current) clearTimeout(presentationTimer.current);
@@ -1455,7 +1986,11 @@ export default function RemoteDesktopScreen() {
});
}
if (audioChanged || wasPresenting)
- await remotePresentation?.playback(settings.audio);
+ await remotePresentation?.playback(
+ Boolean(NativeRemoteDesktopView) ||
+ settings.audio ||
+ pipEnabledRef.current,
+ );
if (active.current !== current) return;
if (audioChanged) audioUnavailable.current = false;
const latest = { ...videoSettingsRef.current, audio: settings.audio };
@@ -1491,69 +2026,210 @@ export default function RemoteDesktopScreen() {
pendingVideoSettings.current = null;
applyPendingVideoSettings.current();
}, [videoSettings, settingBusy, settingsRevision, status, lease]);
- const startPresentation = async () => {
+ nativeMessage.current = onMessage;
+ const startPresentation = async (enter = true) => {
const current = active.current;
+ const restoration = controlRestoration.current;
if (
!current ||
!caps?.backgroundViewing ||
- !canPip ||
+ (NativeRemoteDesktopView ? !frameReady : !canPip) ||
!remotePresentation ||
+ (controlInFlight.current && !restoration) ||
settingInFlight.current
- )
+ ) {
+ pendingPresentation.current?.(false);
+ pendingPresentation.current = null;
+ // A saved preference alone cannot keep an invisible lease alive. Back
+ // already handles refusal via its waiter; route blur has no such waiter.
+ // Do not interrupt another transition that already owns presentation.
+ if (
+ !focusedRef.current &&
+ !presentation.current &&
+ !actualPresentation.current
+ ) {
+ leaving.current = true;
+ setIsLeaving(true);
+ pause(true);
+ navigation.current.onEnded?.();
+ }
return;
+ }
settingInFlight.current = true;
+ const startedAt = performance.now();
+ const alreadyAuthorized = Boolean(
+ NativeRemoteDesktopView && pipPrepared.current && !restoration,
+ );
+ const finishTransition = linkRef.current.beginBackgroundTransition?.();
+ finishBackgroundTransition.current = finishTransition ?? null;
+ presentationReturnedToActive.current = false;
setSettingNotice(null);
+ const transition = ++presentationGeneration.current;
+ const currentTransition = () =>
+ active.current === current &&
+ presentationGeneration.current === transition;
+ // Reserve this bounded transition immediately, including native willStart
+ // arriving before JS sees inactive. System readiness is not host permission.
+ presentation.current = true;
+ send({
+ type: "pipPolicy",
+ enabled: pipEnabledRef.current,
+ preparing: true,
+ authorized: alreadyAuthorized,
+ });
+ if (presentationTimer.current) clearTimeout(presentationTimer.current);
+ presentationTimer.current = setTimeout(() => {
+ if (!currentTransition()) return;
+ mobileDebugLog(
+ "warn",
+ "lifecycle",
+ "remote desktop presentation deadline",
+ {
+ elapsedMs: Math.round(performance.now() - startedAt),
+ active: actualPresentation.current,
+ authorized: pipPrepared.current,
+ },
+ );
+ pendingPresentation.current?.(false);
+ pendingPresentation.current = null;
+ setSettingNotice(t("remoteDesktop.pipUnavailable"));
+ setControlPage("controls");
+ setOperations(true);
+ pause(!focusedRef.current);
+ if (!focusedRef.current) navigation.current.onEnded?.();
+ }, BACKGROUND_TRANSITION_TIMEOUT_MS);
try {
+ // Finish foreground restoration before asking the host to release input
+ // again; a late control grant must never overtake background authorization.
+ if (restoration) await restoration;
+ if (!currentTransition()) return;
await remotePresentation.playback(true);
- if (active.current !== current) return;
- await request({
- op: "presentation",
- lease: current.lease,
- enabled: true,
- }).catch((cause) => {
- // A lost reply leaves the host transition uncertain. Retire only this
- // lease and use normal recovery instead of guessing its control state.
- if (active.current === current) pause();
- throw cause;
- });
- if (active.current !== current) return;
+ if (!currentTransition()) return;
+ if (!alreadyAuthorized)
+ await request({
+ op: "presentation",
+ lease: current.lease,
+ enabled: true,
+ });
+ if (!currentTransition()) return;
+ mobileDebugLog(
+ "info",
+ "lifecycle",
+ "remote desktop presentation authorized",
+ {
+ elapsedMs: Math.round(performance.now() - startedAt),
+ enter,
+ reused: alreadyAuthorized,
+ appState: AppState.currentState,
+ },
+ );
send({ type: "control", enabled: false });
current.controlling = false;
- wantsControl.current = false;
+ // Background presentation temporarily releases input; it does not
+ // change the user's fullscreen control preference.
heldKeys.current.clear();
setModifiers([]);
setKeyboard(false);
setLease({ ...current });
+ pipPrepared.current = true;
+ send({
+ type: "pipPolicy",
+ enabled: pipEnabledRef.current,
+ authorized: true,
+ });
+ if (actualPresentation.current) {
+ if (presentationTimer.current) clearTimeout(presentationTimer.current);
+ presentationTimer.current = null;
+ pendingPresentation.current?.(true);
+ pendingPresentation.current = null;
+ }
+ if (
+ !enter &&
+ presentationReturnedToActive.current &&
+ AppState.currentState === "active" &&
+ !actualPresentation.current
+ ) {
+ presentation.current = actualPresentation.current;
+ if (presentationTimer.current) clearTimeout(presentationTimer.current);
+ presentationTimer.current = null;
+ restoreInlinePresentationRef.current();
+ return;
+ }
presentation.current = true;
setOperations(false);
- send({ type: "presentation", enabled: true });
- presentationTimer.current = setTimeout(() => {
- presentationTimer.current = null;
- presentation.current = false;
- send({ type: "presentation", enabled: false });
- void request({
- op: "presentation",
- lease: current.lease,
- enabled: false,
- }).catch(() => {});
- if (!videoSettingsRef.current.audio)
- void remotePresentation?.playback(false).catch(() => {});
- setSettingNotice(t("remoteDesktop.pipUnavailable"));
- setControlPage("controls");
- setOperations(true);
- if (AppState.currentState === "background") pause();
- }, 4000);
+ // Automatic Home entry is already armed; never attempt a late manual
+ // start from background. Explicit in-app Back still requests AVKit here.
+ if (enter && !actualPresentation.current)
+ send({ type: "presentation", enabled: true });
} catch {
+ if (!currentTransition()) return;
+ pendingPresentation.current?.(false);
+ pendingPresentation.current = null;
if (active.current !== current) return;
presentation.current = false;
- if (!videoSettingsRef.current.audio)
+ if (!NativeRemoteDesktopView && !videoSettingsRef.current.audio)
void remotePresentation?.playback(false).catch(() => {});
setSettingNotice(t("remoteDesktop.pipUnavailable"));
+ pause(!focusedRef.current);
+ if (!focusedRef.current) navigation.current.onEnded?.();
} finally {
- settingInFlight.current = false;
+ finishTransition?.();
+ if (finishBackgroundTransition.current === finishTransition)
+ finishBackgroundTransition.current = null;
+ if (presentationGeneration.current === transition)
+ settingInFlight.current = false;
if (alive.current) setSettingsRevision((value) => value + 1);
}
};
+ startPresentationRef.current = startPresentation;
+ useEffect(() => {
+ if (!NativeRemoteDesktopView || !lease) return;
+ send({
+ type: "pipPolicy",
+ enabled:
+ pipEnabled &&
+ frameReady &&
+ caps?.backgroundViewing === true &&
+ !settingBusy,
+ });
+ }, [
+ pipEnabled,
+ frameReady,
+ caps?.backgroundViewing,
+ settingBusy,
+ settingsRevision,
+ lease?.lease,
+ lease?.controlling,
+ send,
+ ]);
+ const togglePictureInPicture = () => {
+ const enabled = !pipEnabledRef.current;
+ pipEnabledRef.current = enabled;
+ setPipEnabled(enabled);
+ if (enabled) {
+ // The native option is persistent intent, not an immediate PiP action.
+ if (!NativeRemoteDesktopView) void startPresentationRef.current();
+ } else {
+ if (presentationTimer.current) {
+ pause();
+ return;
+ }
+ presentationGeneration.current++;
+ send({ type: "pipPolicy", enabled: false });
+ send({ type: "presentation", enabled: false });
+ restoreAfterPipDisabled.current ||= pipPrepared.current;
+ pipPrepared.current = false;
+ const current = active.current;
+ if (current)
+ void request({
+ op: "presentation",
+ lease: current.lease,
+ enabled: false,
+ }).catch(() => {});
+ if (!NativeRemoteDesktopView && !videoSettingsRef.current.audio)
+ void remotePresentation?.playback(false).catch(() => {});
+ }
+ };
const changeResolution = async (modeId: string) => {
const current = active.current;
if (!current?.controlling || settingInFlight.current) return;
@@ -1794,13 +2470,6 @@ export default function RemoteDesktopScreen() {
behavior={Platform.OS === "ios" ? "padding" : undefined}
style={styles.root}
>
- <Stack.Screen
- options={{
- headerShown: false,
- gestureEnabled: false,
- statusBarHidden: true,
- }}
- />
{Platform.OS === "android" && focused && <StatusBar hidden />}
<View style={[styles.body, landscape && styles.landscape]}>
<View
@@ -1809,42 +2478,64 @@ export default function RemoteDesktopScreen() {
{ marginLeft: landscape ? 0 : edgePadding.paddingLeft },
]}
>
- <WebView
- ref={webview}
- source={{ html, baseUrl: "https://cindy-desktop.invalid/" }}
- originWhitelist={["*"]}
- onShouldStartLoadWithRequest={(request) =>
- request.url === "about:blank" ||
- request.url === "https://cindy-desktop.invalid/"
- }
- onMessage={onMessage}
- onError={restartViewer}
- onContentProcessDidTerminate={restartViewer}
- onRenderProcessGone={restartViewer}
- keyboardDisplayRequiresUserAction={false}
- hideKeyboardAccessoryView
- textInteractionEnabled={false}
- allowsLinkPreview={false}
- {...(Platform.OS === "ios"
- ? { dataDetectorTypes: "none" as const }
- : {})}
- javaScriptEnabled
- allowsInlineMediaPlayback
- mediaPlaybackRequiresUserAction={false}
- allowsPictureInPictureMediaPlayback
- scrollEnabled={false}
- contentInsetAdjustmentBehavior="never"
- bounces={false}
- allowFileAccess={false}
- allowUniversalAccessFromFileURLs={false}
- allowFileAccessFromFileURLs={false}
- setSupportMultipleWindows={false}
- javaScriptCanOpenWindowsAutomatically={false}
- mixedContentMode="never"
- style={styles.webview}
- testID="remoteDesktop.viewer"
- />
- {Platform.OS === "ios" &&
+ <Animated.View
+ testID="remoteDesktop.media"
+ pointerEvents={frameReady ? "auto" : "none"}
+ style={[StyleSheet.absoluteFill, mediaReveal]}
+ >
+ {NativeRemoteDesktopView && (
+ <NativeRemoteDesktopView
+ ref={nativeViewer}
+ inlineVisible={focused}
+ onMessage={(event) => nativeMessage.current(event)}
+ pointerEvents="none"
+ style={[
+ StyleSheet.absoluteFill,
+ { backgroundColor: colors.surface },
+ ]}
+ />
+ )}
+ <WebView
+ ref={webview}
+ source={{ html, baseUrl: "https://cindy-desktop.invalid/" }}
+ originWhitelist={["*"]}
+ onShouldStartLoadWithRequest={(request) =>
+ request.url === "about:blank" ||
+ request.url === "https://cindy-desktop.invalid/"
+ }
+ onMessage={onMessage}
+ onError={restartViewer}
+ onContentProcessDidTerminate={restartViewer}
+ onRenderProcessGone={restartViewer}
+ keyboardDisplayRequiresUserAction={false}
+ hideKeyboardAccessoryView
+ textInteractionEnabled={false}
+ allowsLinkPreview={false}
+ {...(Platform.OS === "ios"
+ ? { dataDetectorTypes: "none" as const }
+ : {})}
+ javaScriptEnabled
+ allowsInlineMediaPlayback
+ mediaPlaybackRequiresUserAction={false}
+ allowsPictureInPictureMediaPlayback
+ scrollEnabled={false}
+ contentInsetAdjustmentBehavior="never"
+ bounces={false}
+ allowFileAccess={false}
+ allowUniversalAccessFromFileURLs={false}
+ allowFileAccessFromFileURLs={false}
+ setSupportMultipleWindows={false}
+ javaScriptCanOpenWindowsAutomatically={false}
+ mixedContentMode="never"
+ style={[
+ styles.webview,
+ NativeRemoteDesktopView && { backgroundColor: "transparent" },
+ ]}
+ testID="remoteDesktop.viewer"
+ />
+ </Animated.View>
+ {frameReady &&
+ Platform.OS === "ios" &&
showMouseButtons &&
focused &&
!operations &&
@@ -1875,7 +2566,12 @@ export default function RemoteDesktopScreen() {
pointerEvents="box-none"
style={[
styles.connectionStatus,
- { top: edgePadding.paddingTop + spacing.xs + 44 + spacing.lg },
+ !frameReady && error !== "permissionHint"
+ ? styles.initialConnection
+ : {
+ top:
+ edgePadding.paddingTop + spacing.xs + 44 + spacing.lg,
+ },
error === "permissionHint" && {
bottom:
(landscape ? insets.bottom : toolbarSize.height) +
@@ -1884,16 +2580,43 @@ export default function RemoteDesktopScreen() {
},
]}
>
+ {!frameReady && error !== "permissionHint" && (
+ <View style={styles.waitingComputer}>
+ <Monitor
+ size={iconSize.lg}
+ strokeWidth={iconStroke.regular}
+ color={colors.textTertiary}
+ />
+ <Text numberOfLines={2} style={styles.waitingComputerName}>
+ {deviceName}
+ </Text>
+ </View>
+ )}
{showConnectionStatus || showExitLockStatus ? (
<View
- style={styles.connectionBadge}
+ style={[
+ styles.connectionBadge,
+ !frameReady && styles.initialConnectionBadge,
+ ]}
accessibilityRole="progressbar"
accessibilityLabel={connectionLabel}
accessibilityState={{ busy: true }}
testID="remoteDesktop.connectingStatus"
>
- <ActivityIndicator size="small" color={colors.textPrimary} />
- <Text style={styles.connectionLabel}>{connectionLabel}</Text>
+ {reduceMotion === false && (
+ <ActivityIndicator
+ size="small"
+ color={colors.textSecondary}
+ />
+ )}
+ <Text
+ style={[
+ styles.connectionLabel,
+ !frameReady && styles.waitingLabel,
+ ]}
+ >
+ {connectionLabel}
+ </Text>
</View>
) : (
error !== "permissionHint" && (
@@ -1909,6 +2632,11 @@ export default function RemoteDesktopScreen() {
</Text>
)
)}
+ {!frameReady && showConnectionStatus && connectionTakingLong && (
+ <Text style={styles.waitingLabel}>
+ {t("remoteDesktop.connectionTakingLong")}
+ </Text>
+ )}
{error &&
error !== "permissionHint" &&
button(
@@ -1933,7 +2661,7 @@ export default function RemoteDesktopScreen() {
)}
{lease &&
!showConnectionStatus &&
- !lease.controlling &&
+ viewOnlySelected &&
!operations && (
<Text
style={[
@@ -1990,7 +2718,9 @@ export default function RemoteDesktopScreen() {
}
caption={`${deviceName} · ${showConnectionStatus ? connectionLabel : t(`remoteDesktop.${status}`)}`}
onClose={() => setOperations(false)}
- footer={<RemoteDesktopDisconnect onPress={leave} />}
+ footer={
+ <RemoteDesktopDisconnect onPress={() => void leave()} />
+ }
>
<RemoteDesktopControls
page={controlPage}
@@ -2006,13 +2736,22 @@ export default function RemoteDesktopScreen() {
}}
connected={Boolean(lease) && !connectionPending}
controlling={Boolean(lease?.controlling)}
+ viewOnly={viewOnlySelected}
controlDisabled={
- !lease || busy || connecting.current || !caps?.canControl
+ !lease ||
+ busy ||
+ settingInFlight.current ||
+ Boolean(presentationTimer.current) ||
+ connecting.current ||
+ !caps?.canControl
}
presentation={{
+ enabled: pipEnabled,
canRotate: typeof remotePresentation?.rotate === "function",
canPip: Boolean(
- remotePresentation && caps?.backgroundViewing && canPip,
+ remotePresentation &&
+ caps?.backgroundViewing &&
+ (NativeRemoteDesktopView || canPip),
),
canAudio: Boolean(caps?.systemAudio),
onRotate: () => {
@@ -2023,9 +2762,7 @@ export default function RemoteDesktopScreen() {
setSettingNotice(t("remoteDesktop.settingFailed")),
);
},
- onPip: () => {
- void startPresentation();
- },
+ onPip: togglePictureInPicture,
}}
video={{
supported: Boolean(caps?.videoSettings),
@@ -2073,10 +2810,14 @@ export default function RemoteDesktopScreen() {
)}
</View>
{!keyboard && (
- <View
+ <Animated.View
key={landscape ? "landscape-toolbar" : "portrait-toolbar"}
testID="remoteDesktop.toolbarPosition"
- pointerEvents="box-none"
+ pointerEvents={frameReady ? "box-none" : "none"}
+ accessibilityElementsHidden={!frameReady}
+ importantForAccessibility={
+ frameReady ? "auto" : "no-hide-descendants"
+ }
onLayout={({ nativeEvent: { layout } }) => {
setToolbarSize((previous) =>
previous.width === layout.width &&
@@ -2087,6 +2828,7 @@ export default function RemoteDesktopScreen() {
}}
style={[
styles.floatingToolbar,
+ mediaReveal,
landscape ? styles.floatingRail : styles.floatingBottom,
{
paddingRight: landscape ? spacing.xs : edgePadding.paddingRight,
@@ -2152,7 +2894,7 @@ export default function RemoteDesktopScreen() {
setOperations(!operations);
}}
/>
- </View>
+ </Animated.View>
)}
</View>
<View
@@ -2182,7 +2924,7 @@ export default function RemoteDesktopScreen() {
>
<RemoteDesktopBackButton
label={t("remoteDesktop.back")}
- onPress={leave}
+ onPress={back}
/>
</View>
{keyboard && (
@@ -2452,6 +3194,34 @@ const makeStyles = (colors: ThemeColors) =>
right: spacing.md,
gap: spacing.sm,
},
+ initialConnection: {
+ top: 0,
+ bottom: 0,
+ justifyContent: "center",
+ alignItems: "center",
+ },
+ waitingComputer: {
+ alignItems: "center",
+ gap: spacing.md,
+ paddingHorizontal: spacing.lg,
+ },
+ waitingComputerName: {
+ color: colors.textPrimary,
+ fontSize: typeScale.body,
+ fontWeight: fontWeight.semibold,
+ textAlign: "center",
+ },
+ initialConnectionBadge: {
+ backgroundColor: "transparent",
+ paddingHorizontal: 0,
+ paddingVertical: spacing.xs,
+ },
+ waitingLabel: {
+ color: colors.textSecondary,
+ fontSize: typeScale.caption,
+ fontWeight: fontWeight.regular,
+ textAlign: "center",
+ },
connectionBadge: {
alignSelf: "center",
flexDirection: "row",
diff --git a/apps/mobile/src/remote-desktop/__tests__/host.test.tsx b/apps/mobile/src/remote-desktop/__tests__/host.test.tsx
new file mode 100644
index 0000000000..5143e24a0d
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/__tests__/host.test.tsx
@@ -0,0 +1,242 @@
+// @vitest-environment jsdom
+import { act, createElement, useEffect } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { RemoteDesktopHost } from "../RemoteDesktopHost";
+import { REMOTE_DESKTOP_ROUTE } from "../remoteDesktopNavigation";
+const fixture = vi.hoisted(() => ({
+ account: "owner-a",
+ generation: 1,
+ authenticated: true,
+ state: {} as any,
+ navigationState: () => ({}) as any,
+ mounted: vi.fn(),
+ stopped: vi.fn(),
+ push: vi.fn(),
+ replace: vi.fn(),
+ resetRoot: vi.fn(),
+ props: {} as Record<string, any>,
+}));
+vi.mock("react-native", () => ({
+ StyleSheet: { create: (value: unknown) => value, absoluteFill: {} },
+ View: ({ children, pointerEvents }: any) =>
+ createElement("div", { "data-pointer-events": pointerEvents }, children),
+}));
+vi.mock("expo-router", () => ({
+ useNavigationContainerRef: () => ({
+ getRootState: () => fixture.navigationState(),
+ resetRoot: fixture.resetRoot,
+ addListener: () => () => {},
+ }),
+ useRouter: () => ({ push: fixture.push, replace: fixture.replace }),
+}));
+vi.mock("expo-router/react-navigation", () => ({
+ useNavigationState: (select: (state: any) => unknown) =>
+ select(fixture.navigationState()),
+}));
+vi.mock("@/auth/AuthContext", () => ({
+ useAuth: () => ({
+ user: { id: fixture.account },
+ accountGeneration: fixture.generation,
+ isAuthenticated: fixture.authenticated,
+ }),
+}));
+vi.mock("../NativeRemoteDesktopView", () => ({
+ NativeRemoteDesktopView: true,
+}));
+vi.mock("../RemoteDesktopScreen", () => ({
+ RemoteDesktopSession: (props: any) => {
+ fixture.props = props;
+ useEffect(() => {
+ fixture.mounted();
+ return () => {
+ fixture.stopped();
+ };
+ }, []);
+ return createElement("span", {}, props.deviceId);
+ },
+}));
+let root: Root;
+let host: HTMLDivElement;
+const home = {
+ key: "home",
+ name: "devices/index",
+ params: { deviceId: "computer-b", filter: "active" },
+};
+const task = {
+ key: "task-b",
+ name: "sessions/[sessionId]",
+ params: { sessionId: "task-b", deviceId: "computer-b" },
+};
+const desktop = (key = "desktop-a") => ({
+ key,
+ name: REMOTE_DESKTOP_ROUTE,
+ params: { deviceId: "computer", deviceName: "Computer" },
+});
+const stack = (...routes: any[]) => ({
+ key: "root",
+ type: "stack",
+ stale: false,
+ routeNames: ["devices/index", "sessions/[sessionId]", REMOTE_DESKTOP_ROUTE],
+ routes,
+ index: routes.length - 1,
+});
+const render = () =>
+ act(() =>
+ root.render(
+ <RemoteDesktopHost>
+ <span>navigation</span>
+ </RemoteDesktopHost>,
+ ),
+ );
+describe.each([false, true])(
+ "desktop navigation with Expo root wrapper=%s",
+ (nested) => {
+ beforeEach(() => {
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+ vi.clearAllMocks();
+ fixture.account = "owner-a";
+ fixture.generation = 1;
+ fixture.authenticated = true;
+ fixture.state = stack(home, desktop());
+ fixture.navigationState = () =>
+ nested
+ ? {
+ ...stack({
+ key: "expo-root-route",
+ name: "__root",
+ state: fixture.state,
+ }),
+ key: "expo-root-stack",
+ routeNames: ["__root"],
+ }
+ : fixture.state;
+ fixture.resetRoot.mockImplementation((state) => {
+ if (nested) {
+ expect(state.key).toBe("expo-root-stack");
+ expect(state.routes[0].name).toBe("__root");
+ fixture.state = state.routes[0].state;
+ } else fixture.state = state;
+ });
+ host = document.createElement("div");
+ root = createRoot(host);
+ render();
+ });
+ afterEach(() => act(() => root.unmount()));
+ it("mounts the native desktop from the active page under the router wrapper", () => {
+ expect(fixture.mounted).toHaveBeenCalledOnce();
+ expect(fixture.props.deviceId).toBe("computer");
+ expect(fixture.props.focused).toBe(true);
+ expect(host.querySelector('[data-pointer-events="auto"]')).not.toBeNull();
+ expect(fixture.resetRoot).not.toHaveBeenCalled();
+ });
+ it("retains one mounted viewer across back and fullscreen restoration", () => {
+ act(() => fixture.props.onBack());
+ render();
+ expect(fixture.props.focused).toBe(false);
+ act(() => fixture.props.onVisibility(false));
+ expect(host.querySelector('[data-pointer-events="none"]')).not.toBeNull();
+ fixture.props.onRestore();
+ expect(fixture.push).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: { deviceId: "computer", deviceName: "Computer" },
+ }),
+ );
+ fixture.state = stack(home, desktop("restored-a"));
+ render();
+ expect(fixture.props.focused).toBe(true);
+ expect(fixture.mounted).toHaveBeenCalledTimes(1);
+ expect(fixture.stopped).not.toHaveBeenCalled();
+ });
+ it("releases the retained viewer when its detached presentation ends", () => {
+ fixture.state = stack(home);
+ render();
+ act(() => fixture.props.onEnded());
+ expect(fixture.stopped).toHaveBeenCalledTimes(1);
+ expect(host.textContent).toBe("navigation");
+ });
+ it.each(["account", "generation", "logout"])(
+ "never retains a detached stream across %s changes",
+ (kind) => {
+ fixture.state = stack(home);
+ render();
+ if (kind === "account") fixture.account = "owner-b";
+ if (kind === "generation") fixture.generation++;
+ if (kind === "logout") fixture.authenticated = false;
+ render();
+ expect(fixture.stopped).toHaveBeenCalledTimes(1);
+ expect(host.textContent).toBe("navigation");
+ },
+ );
+ it("keeps a minimized desktop out of another computer's task Back history", () => {
+ const delayedBack = fixture.props.onBack;
+ act(() => fixture.props.onBack());
+ render();
+ expect(fixture.state.routes).toEqual([home]);
+ fixture.state = stack(home, task);
+ render();
+ expect(fixture.props.focused).toBe(false);
+ // A late completion from the old desktop must not pop this task.
+ act(() => delayedBack());
+ expect(fixture.state.routes).toEqual([home, task]);
+ fixture.state = stack(...fixture.state.routes.slice(0, -1));
+ render();
+ expect(fixture.state.routes).toEqual([home]);
+ expect(fixture.props.focused).toBe(false);
+ expect(fixture.stopped).not.toHaveBeenCalled();
+ });
+ it("returns an explicitly reopened desktop to the exact prior task and preserves its params", () => {
+ act(() => fixture.props.onBack());
+ fixture.state = stack(home, task, desktop("new-desktop"));
+ render();
+ expect(fixture.props.focused).toBe(true);
+ act(() => fixture.props.onBack());
+ render();
+ expect(fixture.state.routes).toEqual([home, task]);
+ expect(fixture.state.routes[1]).toBe(task);
+ expect(fixture.state.index).toBe(1);
+ expect(fixture.props.focused).toBe(false);
+ });
+ it("removes stale desktop history underneath a task without moving the task", () => {
+ fixture.state = stack(home, desktop(), task);
+ render();
+ expect(fixture.state.routes).toEqual([home, task]);
+ expect(fixture.state.index).toBe(1);
+ });
+ it("does not remove a new explicit desktop entry when an older Back completes", () => {
+ const delayedBack = fixture.props.onBack;
+ fixture.state = stack(home, task, desktop("new-desktop"));
+ render();
+ act(() => delayedBack());
+ expect(fixture.state.routes.map((r: any) => r.key)).toEqual([
+ "home",
+ "task-b",
+ "new-desktop",
+ ]);
+ });
+ it("deduplicates native restoration and waits for its route before showing the overlay", () => {
+ act(() => fixture.props.onBack());
+ fixture.state = stack(home, task);
+ render();
+ act(() => {
+ fixture.props.onVisibility(true);
+ fixture.props.onRestore();
+ fixture.props.onRestore();
+ });
+ expect(fixture.push).toHaveBeenCalledTimes(1);
+ expect(host.querySelector('[data-pointer-events="none"]')).not.toBeNull();
+ fixture.state = stack(home, task, desktop("restored-a"));
+ render();
+ expect(host.querySelector('[data-pointer-events="auto"]')).not.toBeNull();
+ act(() => fixture.props.onRestore());
+ expect(fixture.push).toHaveBeenCalledTimes(1);
+ expect(fixture.mounted).toHaveBeenCalledTimes(1);
+ });
+ it("replaces a desktop-only deep link with home when minimizing", () => {
+ fixture.state = stack(desktop());
+ render();
+ act(() => fixture.props.onBack());
+ expect(fixture.replace).toHaveBeenCalledWith("/");
+ });
+ },
+);
diff --git a/apps/mobile/src/remote-desktop/__tests__/navigationDebug.test.ts b/apps/mobile/src/remote-desktop/__tests__/navigationDebug.test.ts
new file mode 100644
index 0000000000..c265d74159
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/__tests__/navigationDebug.test.ts
@@ -0,0 +1,53 @@
+import { expect, it, vi } from "vitest";
+import {
+ desktopNavigationSummary,
+ logDesktopNavigation,
+} from "../remoteDesktopNavigationDebug";
+const fixture = vi.hoisted(() => ({ enabled: true, log: vi.fn() }));
+vi.mock("@/debug/mobileDebugLog", () => ({
+ mobileDebugEnabled: () => fixture.enabled,
+ mobileDebugLog: fixture.log,
+}));
+it("records nested stack positions without paths, keys, parameters or unknown names", () => {
+ const state = {
+ index: 0,
+ routes: [
+ {
+ name: "__root",
+ key: "private-key",
+ state: {
+ index: 1,
+ routes: [
+ {
+ name: "devices/index",
+ params: { deviceName: "private-computer" },
+ },
+ {
+ name: "devices/desktop/[deviceId]",
+ path: "private-path",
+ params: { deviceId: "private-device" },
+ },
+ { name: "private-route", params: { sessionId: "private-task" } },
+ ],
+ },
+ },
+ ],
+ };
+ expect(desktopNavigationSummary(state)).toBe(
+ "0:[root(1:[devices,desktop,other])]",
+ );
+ logDesktopNavigation("test", state);
+ expect(JSON.stringify(fixture.log.mock.calls)).not.toContain("private");
+});
+it("does not inspect navigation state or log when recording is disabled", () => {
+ fixture.enabled = false;
+ fixture.log.mockClear();
+ const state = {
+ get routes(): never {
+ throw new Error("must not inspect");
+ },
+ };
+ logDesktopNavigation("test", state);
+ expect(fixture.log).not.toHaveBeenCalled();
+ fixture.enabled = true;
+});
diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
index c6fafbd210..b759c240b7 100644
--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
@@ -1,11 +1,25 @@
// @vitest-environment jsdom
-import { act, createElement, forwardRef, useImperativeHandle } from "react";
+import {
+ act,
+ createElement,
+ forwardRef,
+ useImperativeHandle,
+ useState,
+} from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import RemoteDesktopScreen from "../RemoteDesktopScreen";
+import RemoteDesktopScreen, {
+ RemoteDesktopSession,
+} from "../RemoteDesktopScreen";
import { RemoteDesktopDisplaySettings } from "../RemoteDesktopDisplaySettings";
import { AppState } from "react-native";
import { goBackGuarded } from "@/utils/backGuard";
+import AsyncStorage from "@react-native-async-storage/async-storage";
+
+vi.mock("react-native-reanimated", async () => {
+ const { View } = await import("react-native");
+ return { default: { View } };
+});
vi.mock("../useAutoUnlockSettings", () => ({
useAutoUnlockSettings: (
@@ -37,8 +51,26 @@ vi.mock("../useLockOnExitPreference", () => ({
true,
],
}));
+vi.mock("../usePictureInPicturePreference", () => ({
+ usePictureInPicturePreference: () => {
+ const [enabled, setEnabled] = useState(fixture.pipEnabled);
+ return [
+ enabled,
+ (value: boolean) => {
+ fixture.pipEnabled = value;
+ setEnabled(value);
+ },
+ ];
+ },
+}));
const fixture = vi.hoisted(() => ({
+ nativeMedia: false,
+ pipEnabled: false,
+ nativeReceive: vi.fn(async (_message: object) => {}),
+ nativeInput: vi.fn(async (_message: object) => true),
+ nativeMessage: null as
+ null | ((event: { nativeEvent: { data: string } }) => void),
nativeMenus: false,
safe: { top: 59, bottom: 34, left: 0, right: 0 },
securityAutoUnlock: false,
@@ -56,6 +88,8 @@ const fixture = vi.hoisted(() => ({
keyboardListeners: {} as Record<string, (event: unknown) => void>,
views: {} as Record<string, any>,
invoke: vi.fn(),
+ finishBackgroundTransition: vi.fn(),
+ beginBackgroundTransition: vi.fn(),
apiFetch: vi.fn(),
openLink: vi.fn(),
post: vi.fn(),
@@ -265,6 +299,7 @@ vi.mock("@/device-link/DeviceLinkContext", () => ({
useDeviceLink: () => ({
status: fixture.status,
invoke: fixture.invoke,
+ beginBackgroundTransition: fixture.beginBackgroundTransition,
openLink: fixture.openLink,
}),
}));
@@ -293,6 +328,26 @@ vi.mock("react-native-webview", () => ({
return createElement("div", { "data-testid": p.testID });
}),
}));
+vi.mock("../NativeRemoteDesktopView", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("../NativeRemoteDesktopView")>();
+ const Native = forwardRef((props: any, ref) => {
+ fixture.nativeMessage = props.onMessage;
+ useImperativeHandle(ref, () => ({
+ receive: fixture.nativeReceive,
+ sendInput: fixture.nativeInput,
+ }));
+ return createElement("div", {
+ "data-native-inline": String(props.inlineVisible),
+ });
+ });
+ return {
+ ...actual,
+ get NativeRemoteDesktopView() {
+ return fixture.nativeMedia ? Native : null;
+ },
+ };
+});
let root: Root;
let host: HTMLDivElement;
@@ -305,9 +360,17 @@ const visibleInputHint = () =>
?.lastElementChild?.textContent;
const button = (key: string) =>
host.querySelector<HTMLButtonElement>(`[aria-label="remoteDesktop.${key}"]`)!;
-beforeEach(() => {
+beforeEach(async () => {
+ await AsyncStorage.removeItem("cindy.mobile.remote-desktop.audio.v1");
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
vi.clearAllMocks();
+ fixture.beginBackgroundTransition.mockImplementation(
+ () => fixture.finishBackgroundTransition,
+ );
+ fixture.nativeMedia = false;
+ fixture.pipEnabled = false;
+ fixture.nativeReceive.mockReset().mockResolvedValue(undefined);
+ fixture.nativeInput.mockReset().mockResolvedValue(true);
fixture.platform = "ios";
fixture.safe = { top: 59, bottom: 34, left: 0, right: 0 };
fixture.hostPlatform = "darwin";
@@ -448,6 +511,881 @@ describe("remote desktop controls", () => {
expect(host.textContent).toContain("remoteDesktop.connectionTimeout");
});
+ const nativePresentation = async (
+ type: string,
+ values: Record<string, unknown> = {},
+ ) => {
+ await act(async () =>
+ fixture.nativeMessage!({
+ nativeEvent: {
+ data: JSON.stringify({ type, epoch: "lease", ...values }),
+ },
+ }),
+ );
+ };
+ const retainedViewer = async () => {
+ fixture.nativeMedia = true;
+ const callbacks = {
+ onBack: vi.fn(),
+ onRestore: vi.fn(),
+ onVisibility: vi.fn(),
+ onEnded: vi.fn(),
+ };
+ const render = (focused: boolean) =>
+ act(() =>
+ root.render(
+ <RemoteDesktopSession
+ deviceId="computer"
+ deviceName="My Mac"
+ focused={focused}
+ {...callbacks}
+ />,
+ ),
+ );
+ render(true);
+ await connect();
+ await nativePresentation("pipCapability", { supported: true });
+ act(() => button("operations").click());
+ await act(async () => button("smallWindow").click());
+ await act(async () => {
+ AppState.currentState = "inactive";
+ fixture.appState!("inactive");
+ AppState.currentState = "background";
+ fixture.appState!("background");
+ });
+ await nativePresentation("presentation", { active: true });
+ await act(async () => {
+ AppState.currentState = "active";
+ fixture.appState!("active");
+ });
+ return { ...callbacks, render };
+ };
+ it.each(["unsupported", "no-frame", "control-busy", "settings-busy"])(
+ "ends a detached native lease when PiP admission is refused: %s",
+ async (reason) => {
+ fixture.nativeMedia = true;
+ fixture.pipEnabled = true;
+ fixture.systemAudio = true;
+ fixture.lockOnExit = true;
+ const invoke = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation(async (...args) => {
+ const result = await invoke(...args);
+ return args[2][0].op === "capabilities" && reason === "unsupported"
+ ? { ...result, backgroundViewing: false }
+ : result;
+ });
+ const onEnded = vi.fn();
+ const render = (focused: boolean) =>
+ root.render(
+ <RemoteDesktopSession
+ deviceId="computer"
+ deviceName="My Mac"
+ focused={focused}
+ onEnded={onEnded}
+ onBack={() => {}}
+ />,
+ );
+ await act(async () => render(true));
+ if (reason === "no-frame") {
+ await act(async () =>
+ fixture.message!({ nativeEvent: { data: '{"type":"ready"}' } }),
+ );
+ } else await connect();
+ let finish: (() => void) | undefined;
+ if (reason === "control-busy") {
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) => {
+ const op = args[2][0].op;
+ if (op === "control") {
+ return new Promise((resolve) => {
+ finish = () => resolve({ controlling: false });
+ });
+ }
+ return original(...args);
+ });
+ } else if (reason === "settings-busy") {
+ fixture.playback.mockImplementation((enabled) =>
+ enabled
+ ? new Promise((resolve) => {
+ finish = () => resolve();
+ })
+ : Promise.resolve(),
+ );
+ }
+ if (reason === "control-busy" || reason === "settings-busy") {
+ act(() => button("operations").click());
+ await act(async () =>
+ button(reason === "control-busy" ? "viewOnly" : "sound").click(),
+ );
+ expect(finish).toBeDefined();
+ }
+ await act(async () => render(false));
+ expect(onEnded).toHaveBeenCalledOnce();
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(1);
+ expect(requests().find((r) => r.op === "stop")).toMatchObject({
+ lockScreen: true,
+ });
+ expect(
+ requests().filter((r) => r.op === "presentation" && r.enabled),
+ ).toHaveLength(0);
+ fixture.invoke.mockClear();
+ await act(async () => {
+ finish?.();
+ await vi.advanceTimersByTimeAsync(30_000);
+ });
+ expect(
+ requests().filter((r) =>
+ ["heartbeat", "start", "presentation"].includes(r.op),
+ ),
+ ).toHaveLength(0);
+ expect(fixture.pipEnabled).toBe(true);
+ },
+ );
+ it("arms automatic native PiP in foreground without releasing control", async () => {
+ fixture.nativeMedia = true;
+ act(() => root.render(<RemoteDesktopScreen />));
+ await connect();
+ await nativePresentation("pipCapability", { supported: true });
+ act(() => button("operations").click());
+ await act(async () => button("smallWindow").click());
+ expect(sent()).toContainEqual(
+ expect.objectContaining({ type: "pipPolicy", enabled: true }),
+ );
+ expect(requests().filter((r) => r.op === "presentation")).toHaveLength(0);
+ expect(
+ requests()
+ .filter((r) => r.op === "control")
+ .at(-1),
+ ).toMatchObject({ enabled: true });
+ });
+
+ it("does not confuse a fast native Home handoff with a cancelled gesture", async () => {
+ fixture.nativeMedia = true;
+ act(() => root.render(<RemoteDesktopScreen />));
+ await connect();
+ await nativePresentation("pipCapability", { supported: true });
+ act(() => button("operations").click());
+ await act(async () => button("smallWindow").click());
+ const controls = requests().filter((r) => r.op === "control").length;
+ await nativePresentation("presentationStarting");
+ expect(
+ sent()
+ .filter((m) => m.type === "pipPolicy" && "authorized" in m)
+ .at(-1),
+ ).toMatchObject({ authorized: true });
+ expect(requests().filter((r) => r.op === "control")).toHaveLength(controls);
+ await act(async () => {
+ AppState.currentState = "inactive";
+ fixture.appState!("inactive");
+ AppState.currentState = "background";
+ fixture.appState!("background");
+ });
+ await nativePresentation("presentation", { active: true });
+ await act(async () => vi.advanceTimersByTimeAsync(5000));
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ expect(
+ requests().filter((r) => r.op === "presentation" && r.enabled),
+ ).toHaveLength(1);
+ });
+
+ it.each(["grant", "timeout", "reject", "close"])(
+ "keeps authorization bounded when native PiP starts before the host reply: %s",
+ async (outcome) => {
+ fixture.nativeMedia = true;
+ act(() => root.render(<RemoteDesktopScreen />));
+ await connect();
+ await nativePresentation("pipCapability", { supported: true });
+ act(() => button("operations").click());
+ await act(async () => button("smallWindow").click());
+ let grant!: (value: unknown) => void;
+ let reject!: (cause: Error) => void;
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "presentation" && args[2][0].enabled
+ ? new Promise((resolve, fail) => {
+ grant = resolve;
+ reject = fail;
+ })
+ : original(...args),
+ );
+ // willStart may precede JS inactive; a second event must not duplicate auth.
+ await nativePresentation("presentationStarting");
+ expect(fixture.beginBackgroundTransition).toHaveBeenCalledTimes(1);
+ expect(fixture.finishBackgroundTransition).not.toHaveBeenCalled();
+ await act(async () => {
+ AppState.currentState = "inactive";
+ fixture.appState!("inactive");
+ });
+ await nativePresentation("presentation", { active: true });
+ await act(async () => {
+ AppState.currentState = "background";
+ fixture.appState!("background");
+ await vi.advanceTimersByTimeAsync(800);
+ });
+ expect(
+ requests().filter((r) => r.op === "presentation" && r.enabled),
+ ).toHaveLength(1);
+ expect(
+ sent().filter((m) => m.type === "pipPolicy" && m.authorized),
+ ).toHaveLength(0);
+ if (outcome === "grant") {
+ await act(async () => grant({}));
+ expect(sent()).toContainEqual(
+ expect.objectContaining({ type: "pipPolicy", authorized: true }),
+ );
+ expect(
+ sent().filter((m) => m.type === "presentation" && m.enabled),
+ ).toHaveLength(0);
+ await act(async () => vi.advanceTimersByTimeAsync(5000));
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ } else {
+ if (outcome === "timeout")
+ await act(async () => vi.advanceTimersByTimeAsync(4000));
+ if (outcome === "reject")
+ await act(async () => reject(new Error("denied")));
+ if (outcome === "close")
+ await nativePresentation("presentation", { active: false });
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(1);
+ await act(async () => grant({}));
+ expect(
+ sent().filter((m) => m.type === "pipPolicy" && m.authorized),
+ ).toHaveLength(0);
+ }
+ expect(fixture.finishBackgroundTransition).toHaveBeenCalled();
+ },
+ );
+
+ it("reveals media and toolbar only after the first presented frame", async () => {
+ expect(fixture.views["remoteDesktop.media"].pointerEvents).toBe("none");
+ expect(
+ fixture.views["remoteDesktop.toolbarPosition"]
+ .accessibilityElementsHidden,
+ ).toBe(true);
+ expect(host.textContent).toContain("My Mac");
+ expect(fixture.views["remoteDesktop.connectingStatus"].style).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ backgroundColor: "transparent" }),
+ ]),
+ );
+ await act(async () => vi.advanceTimersByTimeAsync(8000));
+ expect(host.textContent).toContain("remoteDesktop.connectionTakingLong");
+ await connect();
+ expect(fixture.views["remoteDesktop.media"].pointerEvents).toBe("auto");
+ expect(
+ fixture.views["remoteDesktop.toolbarPosition"]
+ .accessibilityElementsHidden,
+ ).toBe(false);
+ expect(host.textContent).not.toContain(
+ "remoteDesktop.connectionTakingLong",
+ );
+ });
+
+ it("changes only the background preference while controlling and during sound renegotiation", async () => {
+ fixture.nativeMedia = true;
+ fixture.systemAudio = true;
+ act(() => root.render(<RemoteDesktopScreen />));
+ await connect();
+ await nativePresentation("pipCapability", { supported: true });
+ act(() => button("operations").click());
+ const controls = requests().filter((r) => r.op === "control").length;
+ await act(async () => button("smallWindow").click());
+ expect(fixture.pipEnabled).toBe(true);
+ expect(requests().filter((r) => r.op === "presentation")).toHaveLength(0);
+ expect(requests().filter((r) => r.op === "control")).toHaveLength(controls);
+ expect(button("viewOnly").getAttribute("aria-selected")).toBe("false");
+ await act(async () => button("sound").click());
+ await nativePresentation("pipCapability", { supported: false });
+ await act(async () => button("smallWindow").click());
+ expect(fixture.pipEnabled).toBe(false);
+ expect(button("smallWindow").disabled).toBe(false);
+ await act(async () => button("smallWindow").click());
+ expect(fixture.pipEnabled).toBe(true);
+ expect(
+ requests().filter((r) => r.op === "presentation" && r.enabled),
+ ).toHaveLength(0);
+ expect(requests().filter((r) => r.op === "control")).toHaveLength(controls);
+ expect(button("viewOnly").getAttribute("aria-selected")).toBe("false");
+ });
+ it("keeps native PiP available after muting, restoring fullscreen and disabling PiP", async () => {
+ fixture.nativeMedia = true;
+ fixture.systemAudio = true;
+ act(() => root.render(<RemoteDesktopScreen />));
+ await connect();
+ await nativePresentation("pipCapability", { supported: true });
+ act(() => button("operations").click());
+ fixture.playback.mockClear();
+ await act(async () => button("sound").click());
+ expect(fixture.playback).toHaveBeenLastCalledWith(true);
+ expect(
+ sent()
+ .filter((m) => m.type === "videoSettings")
+ .at(-1),
+ ).toMatchObject({ audio: false });
+ // Native readiness is reported again after the muted stream reconnects.
+ await nativePresentation("streaming");
+ await nativePresentation("pipCapability", { supported: true });
+ expect(button("smallWindow").disabled).toBe(false);
+ await act(async () => button("smallWindow").click());
+ await act(async () => button("back").click());
+ await nativePresentation("presentation", { active: true });
+ await nativePresentation("presentation", { active: false });
+ act(() => button("operations").click());
+ await act(async () => button("smallWindow").click());
+ await nativePresentation("presentation", { active: false });
+ await nativePresentation("presentationFailed");
+ expect(fixture.playback).not.toHaveBeenCalledWith(false);
+ expect(fixture.pipEnabled).toBe(false);
+ expect(button("smallWindow").disabled).toBe(false);
+ act(() => root.unmount());
+ mounted = false;
+ expect(fixture.playback).toHaveBeenLastCalledWith(false);
+ });
+ it("prepares native video playback even when the host has no audio", async () => {
+ fixture.nativeMedia = true;
+ fixture.systemAudio = false;
+ act(() => root.render(<RemoteDesktopScreen />));
+ await connect();
+ expect(fixture.playback).toHaveBeenCalledWith(true);
+ expect(sent().find((m) => m.type === "init")).toMatchObject({
+ audio: false,
+ });
+ });
+ it.each([true, false])(
+ "restores browser PiP's prior control choice (%s) without clearing the preference",
+ async (controlling) => {
+ await connect();
+ const web = async (
+ type: string,
+ values: Record<string, unknown> = {},
+ ) => {
+ await act(async () =>
+ fixture.message!({
+ nativeEvent: {
+ data: JSON.stringify({ type, epoch: "lease", ...values }),
+ },
+ }),
+ );
+ };
+ await web("pipCapability", { supported: true });
+ act(() => button("operations").click());
+ if (!controlling) await act(async () => button("viewOnly").click());
+ await act(async () => button("smallWindow").click());
+ await web("presentation", { active: true });
+ fixture.invoke.mockClear();
+ await web("presentation", { active: false });
+ await web("presentation", { active: false });
+ expect(fixture.pipEnabled).toBe(true);
+ if (controlling) {
+ expect(
+ requests().filter((r) => r.op === "control" && r.enabled),
+ ).toHaveLength(1);
+ } else {
+ expect(
+ requests().filter((r) => r.op === "control" && r.enabled),
+ ).toHaveLength(0);
+ expect(
+ requests().filter((r) => r.op === "presentation" && !r.enabled),
+ ).toHaveLength(1);
+ }
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ },
+ );
+ it("keeps the background option and restores control after returning fullscreen", async () => {
+ const viewer = await retainedViewer();
+ const controls = requests().filter(
+ (r) => r.op === "control" && r.enabled,
+ ).length;
+ await nativePresentation("presentationRestore");
+ await nativePresentation("presentation", { active: false });
+ expect(fixture.pipEnabled).toBe(true);
+ expect(sent()).toContainEqual(
+ expect.objectContaining({ type: "restorePresentation" }),
+ );
+ expect(
+ requests().filter((r) => r.op === "presentation" && !r.enabled),
+ ).toHaveLength(0);
+ expect(viewer.onEnded).not.toHaveBeenCalled();
+ expect(
+ requests().filter((r) => r.op === "control" && r.enabled),
+ ).toHaveLength(controls + 1);
+ act(() => button("operations").click());
+ expect(button("viewOnly").getAttribute("aria-selected")).toBe("false");
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ });
+ it("does not select view-only or label the viewer as view-only during actual PiP", async () => {
+ await retainedViewer();
+ expect(host.textContent).not.toContain("remoteDesktop.viewOnly");
+ act(() => button("operations").click());
+ expect(button("viewOnly").getAttribute("aria-selected")).toBe("false");
+ expect(visibleInputHint()).toBe("remoteDesktop.controlUnavailableHint");
+ await act(async () => button("viewOnly").click());
+ expect(button("viewOnly").getAttribute("aria-selected")).toBe("true");
+ await nativePresentation("presentation", { active: false });
+ expect(button("viewOnly").getAttribute("aria-selected")).toBe("true");
+ expect(visibleInputHint()).toBe("remoteDesktop.viewOnlyHint");
+ });
+ it("waits for actual PiP before navigating back and keeps the connection mounted", async () => {
+ const viewer = await retainedViewer();
+ await nativePresentation("presentation", { active: false });
+ await act(async () => button("back").click());
+ expect(viewer.onBack).not.toHaveBeenCalled();
+ await nativePresentation("presentation", { active: true });
+ expect(viewer.onBack).toHaveBeenCalledOnce();
+ viewer.render(false);
+ expect(host.querySelector('[data-native-inline="false"]')).not.toBeNull();
+ expect(viewer.onVisibility).toHaveBeenLastCalledWith(false);
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ await nativePresentation("presentationRestore");
+ expect(viewer.onRestore).toHaveBeenCalledOnce();
+ viewer.render(true);
+ expect(host.querySelector('[data-native-inline="true"]')).not.toBeNull();
+ });
+ it("finishes delayed Back using the callback from its original route", async () => {
+ const viewer = await retainedViewer();
+ await nativePresentation("presentation", { active: false });
+ await act(async () => button("back").click());
+ const laterBack = vi.fn();
+ act(() =>
+ root.render(
+ <RemoteDesktopSession
+ deviceId="computer"
+ deviceName="My Mac"
+ focused={true}
+ onBack={laterBack}
+ onRestore={viewer.onRestore}
+ onVisibility={viewer.onVisibility}
+ onEnded={viewer.onEnded}
+ />,
+ ),
+ );
+ await nativePresentation("presentation", { active: true });
+ expect(viewer.onBack).toHaveBeenCalledOnce();
+ expect(laterBack).not.toHaveBeenCalled();
+ });
+ it("starts PiP on route blur before hiding and restores the route on system fullscreen", async () => {
+ const viewer = await retainedViewer();
+ await nativePresentation("presentation", { active: false });
+ viewer.onVisibility.mockClear();
+ await act(async () => viewer.render(false));
+ expect(viewer.onVisibility).not.toHaveBeenCalledWith(false);
+ await nativePresentation("presentation", { active: true });
+ expect(viewer.onVisibility).toHaveBeenLastCalledWith(false);
+ await nativePresentation("presentationRestore");
+ expect(viewer.onRestore).toHaveBeenCalledOnce();
+ expect(viewer.onVisibility).toHaveBeenLastCalledWith(true);
+ viewer.render(true);
+ await nativePresentation("presentation", { active: false });
+ expect(fixture.pipEnabled).toBe(true);
+ expect(viewer.onEnded).not.toHaveBeenCalled();
+ });
+ it("does not let a control toggle strand an in-flight PiP handoff", async () => {
+ await retainedViewer();
+ await nativePresentation("presentation", { active: false });
+ act(() => button("operations").click());
+ let finish!: (value: unknown) => void;
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "presentation"
+ ? new Promise((resolve) => {
+ finish = resolve;
+ })
+ : original(...args),
+ );
+ const before = requests().filter((r) => r.op === "control").length;
+ await act(async () => button("back").click());
+ await act(async () => button("viewOnly").click());
+ expect(requests().filter((r) => r.op === "control")).toHaveLength(before);
+ await act(async () => finish({}));
+ await nativePresentation("presentation", { active: true });
+ await nativePresentation("presentation", { active: false });
+ expect(
+ requests()
+ .filter((r) => r.op === "control")
+ .at(-1),
+ ).toMatchObject({ enabled: true });
+ act(() => button("operations").click());
+ await act(async () => button("viewOnly").click());
+ expect(requests().filter((r) => r.op === "control")).toHaveLength(
+ before + 2,
+ );
+ });
+ it.each([true, false])(
+ "restores the prior control choice (%s) when a Home gesture is cancelled during preparation",
+ async (controlling) => {
+ fixture.nativeMedia = true;
+ act(() => root.render(<RemoteDesktopScreen />));
+ await connect();
+ await nativePresentation("pipCapability", { supported: true });
+ act(() => button("operations").click());
+ if (!controlling) await act(async () => button("viewOnly").click());
+ await act(async () => button("smallWindow").click());
+ const before = requests().filter((r) => r.op === "control").length;
+ let finish!: (value: unknown) => void;
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "presentation" && args[2][0].enabled
+ ? new Promise((resolve) => {
+ finish = resolve;
+ })
+ : original(...args),
+ );
+ await act(async () => {
+ AppState.currentState = "inactive";
+ fixture.appState!("inactive");
+ });
+ await act(async () => {
+ AppState.currentState = "active";
+ fixture.appState!("active");
+ });
+ await act(async () => finish({}));
+ expect(fixture.pipEnabled).toBe(true);
+ expect(button("viewOnly").getAttribute("aria-selected")).toBe(
+ String(!controlling),
+ );
+ expect(requests().filter((r) => r.op === "control")).toHaveLength(
+ before + Number(controlling),
+ );
+ expect(
+ sent().filter((m) => m.type === "presentation" && m.enabled),
+ ).toHaveLength(0);
+ },
+ );
+ it.each(["grant", "timeout"])(
+ "keeps a cancelled foreground PiP start bounded until authorization: %s",
+ async (outcome) => {
+ fixture.nativeMedia = true;
+ act(() => root.render(<RemoteDesktopScreen />));
+ await connect();
+ await nativePresentation("pipCapability", { supported: true });
+ act(() => button("operations").click());
+ await act(async () => button("smallWindow").click());
+ let finish!: (value: unknown) => void;
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "presentation" && args[2][0].enabled
+ ? new Promise((resolve) => {
+ finish = resolve;
+ })
+ : original(...args),
+ );
+ await nativePresentation("presentationStarting");
+ await act(async () => {
+ AppState.currentState = "inactive";
+ fixture.appState!("inactive");
+ });
+ await nativePresentation("presentation", { active: true });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(3000);
+ AppState.currentState = "active";
+ fixture.appState!("active");
+ });
+ await nativePresentation("presentation", { active: false });
+ await nativePresentation("presentation", { active: false });
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ if (outcome === "grant") await act(async () => finish({}));
+ await act(async () => vi.advanceTimersByTimeAsync(1100));
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(
+ outcome === "grant" ? 0 : 1,
+ );
+ expect(fixture.pipEnabled).toBe(true);
+ if (outcome === "grant") {
+ expect(button("viewOnly").getAttribute("aria-selected")).toBe("false");
+ } else await act(async () => finish({}));
+ },
+ );
+ it("ends a detached connection when PiP closes without clearing the option", async () => {
+ const viewer = await retainedViewer();
+ viewer.render(false);
+ await nativePresentation("presentation", { active: false });
+ expect(viewer.onEnded).toHaveBeenCalledOnce();
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(1);
+ expect(fixture.pipEnabled).toBe(true);
+ });
+ it.each(["smallWindow", "sound"])(
+ "restores control when %s stops an active PiP window",
+ async (action) => {
+ fixture.systemAudio = true;
+ await retainedViewer();
+ const controls = requests().filter(
+ (r) => r.op === "control" && r.enabled,
+ ).length;
+ act(() => button("operations").click());
+ await act(async () => button(action).click());
+ await nativePresentation("presentation", { active: false });
+ expect(
+ requests().filter((r) => r.op === "control" && r.enabled),
+ ).toHaveLength(controls + 1);
+ expect(button("viewOnly").getAttribute("aria-selected")).toBe("false");
+ },
+ );
+ it.each(["grant", "timeout"])(
+ "orders rapid Home entry after pending fullscreen restoration: %s",
+ async (outcome) => {
+ await retainedViewer();
+ let finish!: (value: unknown) => void;
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "control" && args[2][0].enabled
+ ? new Promise((resolve) => {
+ finish = resolve;
+ })
+ : original(...args),
+ );
+ await nativePresentation("presentation", { active: false });
+ const grants = () =>
+ requests().filter((r) => r.op === "presentation" && r.enabled).length;
+ const before = grants();
+ await act(async () => {
+ AppState.currentState = "inactive";
+ fixture.appState!("inactive");
+ AppState.currentState = "background";
+ fixture.appState!("background");
+ });
+ await nativePresentation("presentation", { active: true });
+ expect(grants()).toBe(before);
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ if (outcome === "timeout")
+ await act(async () => vi.advanceTimersByTimeAsync(4100));
+ await act(async () => finish({ controlling: true }));
+ expect(grants()).toBe(before + (outcome === "grant" ? 1 : 0));
+ await act(async () => vi.advanceTimersByTimeAsync(4100));
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(
+ outcome === "grant" ? 0 : 1,
+ );
+ },
+ );
+ it("preserves authorized native media while fullscreen signaling reconnects", async () => {
+ const viewer = await retainedViewer();
+ const controls = requests().filter((r) => r.op === "control").length;
+ const authorizations = requests().filter(
+ (r) => r.op === "presentation" && r.enabled,
+ ).length;
+ fixture.status = "offline";
+ viewer.render(true);
+ await nativePresentation("presentation", { active: false });
+ await act(async () => vi.advanceTimersByTimeAsync(5000));
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ expect(requests().filter((r) => r.op === "control")).toHaveLength(controls);
+ // Another immediate Home entry uses the still-acknowledged host permission.
+ const beforeReentry = sent().length;
+ await act(async () => {
+ AppState.currentState = "inactive";
+ fixture.appState!("inactive");
+ AppState.currentState = "background";
+ fixture.appState!("background");
+ });
+ await nativePresentation("presentation", { active: true });
+ expect(sent().slice(beforeReentry)).toContainEqual(
+ expect.objectContaining({ type: "pipPolicy", authorized: true }),
+ );
+ expect(
+ requests().filter((r) => r.op === "presentation" && r.enabled),
+ ).toHaveLength(authorizations);
+ await act(async () => {
+ AppState.currentState = "active";
+ fixture.appState!("active");
+ });
+ await nativePresentation("presentation", { active: false });
+ fixture.status = "online";
+ await act(async () => viewer.render(true));
+ expect(requests().filter((r) => r.op === "control")).toHaveLength(
+ controls + 1,
+ );
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ act(() => button("operations").click());
+ expect(button("viewOnly").getAttribute("aria-selected")).toBe("false");
+ });
+
+ it("revokes cached presentation permission when disabled during signaling recovery", async () => {
+ const viewer = await retainedViewer();
+ fixture.status = "offline";
+ viewer.render(true);
+ await nativePresentation("presentation", { active: false });
+ act(() => button("operations").click());
+ await act(async () => button("smallWindow").click());
+ const beforeBackground = sent().length;
+ await act(async () => {
+ AppState.currentState = "inactive";
+ fixture.appState!("inactive");
+ AppState.currentState = "background";
+ fixture.appState!("background");
+ });
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(1);
+ expect(
+ sent()
+ .slice(beforeBackground)
+ .some((m) => m.type === "pipPolicy" && m.authorized),
+ ).toBe(false);
+ });
+
+ it("does not restore control from a preparation reply after disconnect", async () => {
+ await retainedViewer();
+ await nativePresentation("presentation", { active: false });
+ act(() => button("operations").click());
+ let finish!: (value: unknown) => void;
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "presentation" && args[2][0].enabled
+ ? new Promise((resolve) => {
+ finish = resolve;
+ })
+ : original(...args),
+ );
+ await act(async () => {
+ AppState.currentState = "inactive";
+ fixture.appState!("inactive");
+ });
+ await act(async () => button("disconnect").click());
+ const controls = requests().filter((r) => r.op === "control").length;
+ await act(async () => finish({}));
+ expect(requests().filter((r) => r.op === "control")).toHaveLength(controls);
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(1);
+ });
+ it("explicit disconnect still ends an enabled PiP connection", async () => {
+ const viewer = await retainedViewer();
+ act(() => button("operations").click());
+ await act(async () => button("disconnect").click());
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(1);
+ expect(viewer.onBack).toHaveBeenCalledOnce();
+ expect(fixture.pipEnabled).toBe(true);
+ });
+ it("keeps a bounded Home transition while waiting for view-only authorization", async () => {
+ await retainedViewer();
+ await nativePresentation("presentation", { active: false });
+ act(() => button("operations").click());
+ await act(async () => button("viewOnly").click());
+ let finish!: (value: unknown) => void;
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "presentation"
+ ? new Promise((resolve) => {
+ finish = resolve;
+ })
+ : original(...args),
+ );
+ await act(async () => {
+ AppState.currentState = "inactive";
+ fixture.appState!("inactive");
+ AppState.currentState = "background";
+ fixture.appState!("background");
+ });
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ expect(sent()).toContainEqual(
+ expect.objectContaining({ type: "pipPolicy", preparing: true }),
+ );
+ await act(async () => finish({}));
+ await nativePresentation("presentation", { active: true });
+ await act(async () => vi.advanceTimersByTimeAsync(5000));
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ });
+ it("routes native negotiation and stops the exact old native lease on pause", async () => {
+ fixture.nativeMedia = true;
+ act(() => root.render(<RemoteDesktopScreen />));
+ await connect();
+ expect(fixture.nativeReceive).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: "init",
+ epoch: "lease",
+ net: expect.any(Object),
+ }),
+ );
+ await act(async () =>
+ fixture.nativeMessage!({
+ nativeEvent: {
+ data: JSON.stringify({
+ type: "iceConfig",
+ epoch: "lease",
+ attemptId: "native-1",
+ }),
+ },
+ }),
+ );
+ expect(fixture.nativeReceive).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: "iceConfig",
+ epoch: "lease",
+ attemptId: "native-1",
+ iceServers: expect.any(Array),
+ }),
+ );
+ act(() => {
+ AppState.currentState = "background";
+ fixture.appState!("background");
+ });
+ expect(fixture.nativeReceive).toHaveBeenCalledWith(
+ expect.objectContaining({ type: "stop", epoch: "lease" }),
+ );
+ });
+
+ it("uses native input transport with RPC fallback and rejects stale native streaming", async () => {
+ fixture.nativeMedia = true;
+ act(() => root.render(<RemoteDesktopScreen />));
+ await connect();
+ await act(async () =>
+ fixture.nativeMessage!({
+ nativeEvent: {
+ data: JSON.stringify({
+ type: "iceConfig",
+ epoch: "lease",
+ attemptId: "native-2",
+ }),
+ },
+ }),
+ );
+ act(() =>
+ fixture.nativeMessage!({
+ nativeEvent: {
+ data: JSON.stringify({
+ type: "streaming",
+ epoch: "lease",
+ attemptId: "native-1",
+ }),
+ },
+ }),
+ );
+ expect(sent().some((m) => m.type === "nativeVideo" && m.active)).toBe(
+ false,
+ );
+ act(() =>
+ fixture.nativeMessage!({
+ nativeEvent: {
+ data: JSON.stringify({
+ type: "streaming",
+ epoch: "lease",
+ attemptId: "native-2",
+ }),
+ },
+ }),
+ );
+ expect(sent()).toContainEqual({
+ type: "nativeVideo",
+ epoch: "lease",
+ active: true,
+ });
+ const input = {
+ type: "input",
+ epoch: "lease",
+ sequence: 1,
+ events: [{ kind: "move", x: 0.5, y: 0.5 }],
+ };
+ await act(async () =>
+ fixture.message!({ nativeEvent: { data: JSON.stringify(input) } }),
+ );
+ expect(fixture.nativeInput).toHaveBeenCalledWith(input);
+ expect(requests().filter((r) => r.op === "input")).toHaveLength(0);
+ fixture.nativeInput.mockResolvedValue(false);
+ await act(async () =>
+ fixture.message!({
+ nativeEvent: { data: JSON.stringify({ ...input, sequence: 2 }) },
+ }),
+ );
+ expect(requests()).toContainEqual({
+ op: "input",
+ lease: "lease",
+ sequence: 2,
+ events: input.events,
+ });
+ });
it("retries an initial capabilities timeout normally on a legacy host", async () => {
const original = fixture.invoke.getMockImplementation()!;
let attempts = 0;
@@ -491,7 +1429,7 @@ describe("remote desktop controls", () => {
expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
expect(requests().filter((r) => r.op === "start")).toHaveLength(1);
});
- it("reflects a host-side input failure as view-only without replacing the video lease", async () => {
+ it("reports unavailable host input without selecting view-only or replacing the video lease", async () => {
await connect();
const original = fixture.invoke.getMockImplementation()!;
fixture.invoke.mockImplementation((...args) =>
@@ -506,7 +1444,8 @@ describe("remote desktop controls", () => {
expect(requests().filter((r) => r.op === "start")).toHaveLength(1);
expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
act(() => button("operations").click());
- expect(visibleInputHint()).toBe("remoteDesktop.viewOnlyHint");
+ expect(visibleInputHint()).toBe("remoteDesktop.controlUnavailableHint");
+ expect(button("viewOnly").getAttribute("aria-selected")).toBe("false");
});
it("keeps iOS data detection disabled without passing its prop to Android", async () => {
await act(async () => {});
@@ -2274,7 +3213,8 @@ describe("remote desktop controls", () => {
expect(host.textContent).not.toContain("remoteDesktop.reconnecting");
expect(sent()).toContainEqual({ type: "control", enabled: false });
act(() => button("operations").click());
- expect(visibleInputHint()).toBe("remoteDesktop.viewOnlyHint");
+ expect(visibleInputHint()).toBe("remoteDesktop.controlUnavailableHint");
+ expect(button("viewOnly").getAttribute("aria-selected")).toBe("false");
});
it("keeps control and the session when an input reply is lost", async () => {
await connect();
@@ -2303,7 +3243,7 @@ describe("remote desktop controls", () => {
expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
expect(host.textContent).not.toContain("remoteDesktop.reconnecting");
});
- it("follows the host to view only when its heartbeat stops counting this viewer as controlling", async () => {
+ it("stops input without changing the user's view-only choice when host control is revoked", async () => {
await connect();
const original = fixture.invoke.getMockImplementation()!;
fixture.invoke.mockImplementation((...args) =>
@@ -2316,7 +3256,8 @@ describe("remote desktop controls", () => {
expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
expect(host.textContent).not.toContain("remoteDesktop.reconnecting");
act(() => button("operations").click());
- expect(visibleInputHint()).toBe("remoteDesktop.viewOnlyHint");
+ expect(visibleInputHint()).toBe("remoteDesktop.controlUnavailableHint");
+ expect(button("viewOnly").getAttribute("aria-selected")).toBe("false");
});
it("releases a stalled input batch instead of rebuilding the session", async () => {
await connect();
@@ -2406,7 +3347,14 @@ describe("remote desktop controls", () => {
.map((r) => r.enabled);
// Overflow timed out with pending release. Take control must finish that
// release (host stopInput) before asking to enable, so the helper restarts.
- expect(controlOps).toEqual([true, false, false, true]);
+ expect(controlOps).toEqual([true, false, false]);
+ expect(button("viewOnly").getAttribute("aria-selected")).toBe("true");
+ await act(async () => button("viewOnly").click());
+ expect(
+ requests()
+ .filter((r) => r.op === "control")
+ .map((r) => r.enabled),
+ ).toEqual([true, false, false, true]);
expect(
sent()
.filter((m) => m.type === "control")
@@ -2662,7 +3610,7 @@ describe("remote desktop controls", () => {
fixture.status = "offline";
act(() => root.render(<RemoteDesktopScreen />));
expect(host.textContent).toContain("remoteDesktop.reconnecting");
- expect(host.textContent).not.toContain("My Mac");
+ expect(host.textContent).toContain("My Mac");
act(() => button("back").click());
expect(goBackGuarded).toHaveBeenCalledTimes(1);
fixture.status = "online";
diff --git a/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts b/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts
index 314f8fe40e..ac879f1d91 100644
--- a/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts
+++ b/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts
@@ -16,7 +16,7 @@ const desktopTransform = vm.runInNewContext(
fillHeight?: boolean,
) => { x: number; y: number; width: number; height: number; scale: number };
-function viewer(rtc = false, frameCallback = true) {
+function viewer(rtc = false, frameCallback = true, nativeMedia = false) {
const messages: Array<{
type: string;
epoch: string;
@@ -136,7 +136,7 @@ function viewer(rtc = false, frameCallback = true) {
}
let now = 0;
let orientation: number | undefined;
- const source = remoteDesktopViewerHtml("#fff", "#111").match(
+ const source = remoteDesktopViewerHtml("#fff", "#111", nativeMedia).match(
/<script>([\s\S]*)<\/script>/,
)![1];
vm.runInNewContext(source, {
@@ -242,6 +242,57 @@ function viewer(rtc = false, frameCallback = true) {
};
}
+describe("native media overlay", () => {
+ it("leaves RTC negotiation to native and shares the exact input geometry", () => {
+ const v = viewer(true, true, true);
+ v.send({ type: "init", epoch: "native", width: 1920, height: 1080 });
+ expect(v.messages.some((m) => m.type === "iceConfig")).toBe(false);
+ const viewport = v.messages.findLast(
+ (m) => m.type === "nativeViewport",
+ ) as unknown as { x: number; y: number; width: number; height: number };
+ expect(v.elements.image.style.left).toBe(viewport.x + "px");
+ expect(v.elements.image.style.top).toBe(viewport.y + "px");
+ expect(v.elements.image.style.width).toBe(viewport.width + "px");
+ expect(v.elements.image.style.height).toBe(viewport.height + "px");
+ v.send({ type: "videoSettings", audio: true });
+ expect(v.messages.some((m) => m.type === "iceConfig")).toBe(false);
+ });
+
+ it("shares backdrop fit policy across native video and orientation changes", () => {
+ const v = viewer(false, true, true);
+ v.send({ type: "init", epoch: "native", width: 1920, height: 1080 });
+ const viewport = () =>
+ v.messages.findLast((m) => m.type === "nativeViewport");
+ expect(viewport()).toMatchObject({ fillHeight: false });
+ v.send({ type: "nativeVideo", epoch: "native", active: true });
+ v.send({ type: "viewport", fillHeight: true });
+ expect(viewport()).toMatchObject({ fillHeight: true });
+ v.send({ type: "fit" });
+ expect(viewport()).toMatchObject({ fillHeight: true });
+ expect(v.elements.bg.style.display).toBe("none");
+ v.send({ type: "viewport", fillHeight: false });
+ expect(viewport()).toMatchObject({ fillHeight: false });
+ });
+
+ it("keeps browser pixels out of native video and restores JPEG after stop/reconnect", () => {
+ const v = viewer(false, true, true);
+ v.send({ type: "init", epoch: "first", width: 1920, height: 1080 });
+ v.send({ type: "nativeVideo", epoch: "first", active: true });
+ v.send({ type: "fit" });
+ v.frame();
+ expect(v.elements.image.style.visibility).toBe("hidden");
+ expect(v.elements.bg.style.display).toBe("none");
+ v.send({ type: "stop" });
+ expect(v.elements.image.style.visibility).toBe("visible");
+ v.send({ type: "init", epoch: "next", width: 1920, height: 1080 });
+ v.send({ type: "nativeVideo", epoch: "first", active: true });
+ expect(v.elements.image.style.visibility).toBe("visible");
+ v.send({ type: "nativeVideo", epoch: "next", active: true });
+ v.send({ type: "nativeVideo", epoch: "next", active: false });
+ expect(v.elements.image.style.visibility).toBe("visible");
+ });
+});
+
describe("remote desktop viewport", () => {
it.each([0, 59])(
"fits between the top safe area (%s) and toolbar with correct touch coordinates",
diff --git a/apps/mobile/src/remote-desktop/remoteDesktopNavigation.ts b/apps/mobile/src/remote-desktop/remoteDesktopNavigation.ts
new file mode 100644
index 0000000000..3dee2a845d
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/remoteDesktopNavigation.ts
@@ -0,0 +1,48 @@
+import type {
+ NavigationState,
+ PartialState,
+} from "expo-router/react-navigation";
+
+export const REMOTE_DESKTOP_ROUTE = "devices/desktop/[deviceId]";
+type State = NavigationState | PartialState<NavigationState>;
+
+/** Expo Router owns an outer navigator; the actual page may be nested. */
+export function activeDesktopRoute(
+ state: State | undefined,
+): State["routes"][number] | undefined {
+ if (!state) return undefined;
+ const route = state.routes[state.index ?? 0];
+ return route?.state ? activeDesktopRoute(route.state) : route;
+}
+
+/** A retained PiP surface is not a page in the user's Back history. */
+export function removeDesktopHistory<T extends State>(
+ state: T,
+ keepKey?: string,
+): T | null {
+ const routes = state.routes.flatMap((route) => {
+ if (route.name === REMOTE_DESKTOP_ROUTE && route.key !== keepKey) return [];
+ if (!route.state) return [route];
+ const nested = removeDesktopHistory(route.state, keepKey);
+ if (!nested) return [];
+ return [nested === route.state ? route : { ...route, state: nested }];
+ });
+ if (
+ routes.length === state.routes.length &&
+ routes.every((route, i) => route === state.routes[i])
+ )
+ return state;
+ if (!routes.length) return null;
+ const activeKey = state.routes[state.index ?? 0]?.key;
+ const activeIndex = routes.findIndex((route) => route.key === activeKey);
+ // Preserve the current non-desktop page, or return to the last surviving
+ // page before the removed desktop. Keep original route keys and params.
+ const previousCount = state.routes
+ .slice(0, state.index)
+ .filter((route) => routes.some((kept) => kept.key === route.key)).length;
+ return {
+ ...state,
+ routes,
+ index: activeIndex >= 0 ? activeIndex : Math.max(0, previousCount - 1),
+ };
+}
diff --git a/apps/mobile/src/remote-desktop/remoteDesktopNavigationDebug.ts b/apps/mobile/src/remote-desktop/remoteDesktopNavigationDebug.ts
new file mode 100644
index 0000000000..0703b848a9
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/remoteDesktopNavigationDebug.ts
@@ -0,0 +1,49 @@
+import type {
+ NavigationState,
+ PartialState,
+} from "expo-router/react-navigation";
+import { mobileDebugEnabled, mobileDebugLog } from "@/debug/mobileDebugLog";
+
+type State = NavigationState | PartialState<NavigationState>;
+const pages: Record<string, string> = {
+ __root: "root",
+ index: "home",
+ "devices/index": "devices",
+ "devices/[deviceId]": "device",
+ "devices/desktop/[deviceId]": "desktop",
+ "sessions/[sessionId]": "task",
+ "devices/manage/[deviceId]": "manage-device",
+ settings: "settings",
+};
+
+/** Fixed page categories and indices only: never route keys, paths or params. */
+export function desktopNavigationSummary(state: State | undefined): string {
+ let remaining = 60;
+ const visit = (value: State | undefined, depth: number): string => {
+ if (!value) return "absent";
+ if (depth > 5 || remaining <= 0) return "truncated";
+ return `${value.index ?? 0}:[${value.routes
+ .slice(0, 30)
+ .map((route) => {
+ if (--remaining < 0) return "truncated";
+ const page = Object.hasOwn(pages, route.name)
+ ? pages[route.name]
+ : "other";
+ return route.state ? `${page}(${visit(route.state, depth + 1)})` : page;
+ })
+ .join(",")}]`;
+ };
+ return visit(state, 0);
+}
+
+export function logDesktopNavigation(
+ event: string,
+ state: State | undefined,
+ flags: Record<string, boolean | number | string> = {},
+) {
+ if (!mobileDebugEnabled()) return;
+ mobileDebugLog("info", "lifecycle", `remote desktop navigation ${event}`, {
+ stack: desktopNavigationSummary(state),
+ ...flags,
+ });
+}
diff --git a/apps/mobile/src/remote-desktop/usePictureInPicturePreference.ts b/apps/mobile/src/remote-desktop/usePictureInPicturePreference.ts
new file mode 100644
index 0000000000..6574ffed7a
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/usePictureInPicturePreference.ts
@@ -0,0 +1,31 @@
+import AsyncStorage from "@react-native-async-storage/async-storage";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+// Phone-local override. The default is off; closing the floating window is not
+// a preference change. Serialize writes across navigation/remounts.
+const key = "cindy.mobile.remote-desktop.picture-in-picture.v1";
+let writes: Promise<void> = Promise.resolve();
+export function usePictureInPicturePreference() {
+ const [enabled, setEnabled] = useState(false);
+ const edited = useRef(false);
+ useEffect(() => {
+ let current = true;
+ void writes
+ .then(() => AsyncStorage.getItem(key))
+ .then((value) => {
+ if (current && !edited.current) setEnabled(value === "true");
+ })
+ .catch(() => {});
+ return () => {
+ current = false;
+ };
+ }, []);
+ const update = useCallback((value: boolean) => {
+ edited.current = true;
+ setEnabled(value);
+ writes = writes
+ .then(() => AsyncStorage.setItem(key, String(value)))
+ .catch(() => {});
+ }, []);
+ return [enabled, update] as const;
+}
diff --git a/apps/mobile/src/remote-desktop/viewerHtml.ts b/apps/mobile/src/remote-desktop/viewerHtml.ts
index e5b5e2f841..5f777f0c06 100644
--- a/apps/mobile/src/remote-desktop/viewerHtml.ts
+++ b/apps/mobile/src/remote-desktop/viewerHtml.ts
@@ -1,5 +1,18 @@
-import { remoteDesktopViewerHtml as createHtml } from '@cindy/maker-shared/remote-desktop-mobile';
-import { DESKTOP_KEY_CODES, REMOTE_DESKTOP_NETWORK, REMOTE_DESKTOP_ICE_SERVERS } from '@cindy/device-link';
-export function remoteDesktopViewerHtml(surface: string, foreground: string): string {
- return createHtml(surface, foreground, {net: REMOTE_DESKTOP_NETWORK, iceServers: REMOTE_DESKTOP_ICE_SERVERS, keyCodes: DESKTOP_KEY_CODES});
+import { remoteDesktopViewerHtml as createHtml } from "@cindy/maker-shared/remote-desktop-mobile";
+import {
+ DESKTOP_KEY_CODES,
+ REMOTE_DESKTOP_NETWORK,
+ REMOTE_DESKTOP_ICE_SERVERS,
+} from "@cindy/device-link";
+export function remoteDesktopViewerHtml(
+ surface: string,
+ foreground: string,
+ nativeMedia = false,
+): string {
+ return createHtml(surface, foreground, {
+ net: REMOTE_DESKTOP_NETWORK,
+ iceServers: REMOTE_DESKTOP_ICE_SERVERS,
+ keyCodes: DESKTOP_KEY_CODES,
+ nativeMedia,
+ });
}
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index 7a57ec66af..d1895cbd5a 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -51,20 +51,20 @@
| `desktop.window.sidebar` | desktop | 右侧栏独立窗口 | `?sidebarWindow=1` → renderer/sidebar-window-entry.tsx;hash `/sidebar-window` | RightSidebar, RightSidebarShell, SidebarWindowLayout | apps/desktop/src/main/right-sidebar-window/controller.ts, apps/desktop/src/main/right-sidebar-window/ipc.ts, apps/desktop/src/main/right-sidebar-window/registry.ts, apps/desktop/src/main/right-sidebar-window/resolveHostContext.ts, apps/desktop/src/main/right-sidebar-window/settings-store.ts, apps/desktop/src/main/right-sidebar-window/window.ts, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/sidebar-window-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 106 | 45 | 198 |
| `desktop.window.voice-dictionary-toast` | desktop | 语音词典 Toast 窗 | `?view=voice-input-dictionary-toast` → main-entry.tsx → VoiceInputDictionaryToast | VoiceInputDictionaryToast | apps/desktop/src/renderer/voice-input/VoiceInputDictionaryToast.tsx | 6 | 0 | 2 |
| `desktop.window.voice-overlay` | desktop | 语音输入浮窗 | `?view=voice-input-overlay` → main-entry.tsx → VoiceInputOverlay | VoiceInputOverlay, VoiceInputStatusNotice | apps/desktop/src/main/voice-input/global.ts, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css, apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx, apps/desktop/src/renderer/voice-input/VoiceInputStatusNotice.tsx | 71 | 38 | 25 |
-| `mobile.account-deletion` | mobile | 账号注销 | app/account-deletion.tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, account-deletion, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/account-deletion.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 23 |
-| `mobile.auth` | mobile | 登录与添加账号 | app/(auth)/login.tsx / app/add-account.tsx | AccountSwitcherSheet, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, IncomingShareBridge, LoginCaptchaWebView, LoginSkinControls, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, PushNotificationsBridge, QuietSyncIndicator, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, _layout, add-account, gestureHandler, login, peerFileTransport, useLocale | apps/mobile/app/(auth)/login.tsx, apps/mobile/app/_layout.tsx, apps/mobile/app/add-account.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/LoginCaptchaWebView.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/LoginSkinControls.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 177 | 44 |
-| `mobile.automations` | mobile | 自动化 | app/automations/[deviceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/automations/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 39 |
-| `mobile.chat.new` | mobile | 新建任务 | app/sessions/new.tsx | AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerAttachmentTray, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, ImageLightbox, IncomingShareBridge, MobileAgentMark, MobileAgentSwitcher, MobileChoicePickerList, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, MobileVendorIcon, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeSwitch, NewTaskSelectionSheet, NewTaskSelectionSheet.ios, PaperPlaneIcon, PlanModeChip, PushNotificationsBridge, QuietSyncIndicator, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, _layout, gestureHandler, new, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/new.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx, apps/mobile/src/session/NewTaskSelectionSheet.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 202 | 78 |
-| `mobile.chat.session` | mobile | 任务内容与输入 | app/sessions/[sessionId].tsx | AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, AuthorizationMessageCard, BlurBackdrop, CenteredScreen, ChatFileChipMenuSheet, CompanionMessageCard, ComposerAttachmentTray, ComposerExpandButton, ComposerExpandButton.ios, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerNativeInput, ComposerNativeInput.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerRichInput, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, ConversationSearchFilterSheet, ConversationShareSvg, ConversationShareWebView, DeviceLinkContext, FailedScheduleNotice, HomeEntryProvider, HomeGlassMenuPanel, HomeNativeStackHeader, HomeSearchBar, ImageLightbox, IncomingShareBridge, InlineQueueSection, InlineQuoteChip, InlineReferenceChip, InteractionPanel, MarkdownBlockContent, MessageActionSheet, MessageRenderer, MobileAgentMark, MobileAgentSwitcher, MobileBoundaryNotice, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeSwitch, PaperPlaneIcon, PendingSendBubble, PiSessionTreeSheet, PlanModeChip, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, RewindPreviewPanel, SentInlineAtomBody, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionListDrawer, SessionMenuSheet, SessionSearchNative, SessionSearchNative.ios, SessionTailBanner, SessionUsageSummary, ShareMessageCheckbox, ShareSelectAllButton, ShareSelectionBar, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, StreamingStatusText, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, [sessionId], _layout, gestureHandler, mathWebView, mediaPlayerWebView, mermaidWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/AuthorizationMessageCard.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ChatFileChipMenuSheet.tsx, apps/mobile/src/session/CompanionMessageCard.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerExpandButton.ios.tsx, apps/mobile/src/session/ComposerExpandButton.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerNativeInput.ios.tsx, apps/mobile/src/session/ComposerNativeInput.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerRichInput.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/ConversationShareSvg.tsx, apps/mobile/src/session/ConversationShareWebView.tsx, apps/mobile/src/session/FailedScheduleNotice.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/InlineQueueSection.tsx, apps/mobile/src/session/InlineQuoteChip.tsx, apps/mobile/src/session/InlineReferenceChip.tsx, apps/mobile/src/session/InteractionPanel.tsx, apps/mobile/src/session/MarkdownBlockContent.tsx, apps/mobile/src/session/MessageActionSheet.tsx, apps/mobile/src/session/MessageRenderer.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileBoundaryNotice.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/PendingSendBubble.tsx, apps/mobile/src/session/PiSessionTreeSheet.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/RewindPreviewPanel.tsx, apps/mobile/src/session/SentInlineAtomBody.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionListDrawer.tsx, apps/mobile/src/session/SessionMenuSheet.tsx, apps/mobile/src/session/SessionSearchNative.ios.tsx, apps/mobile/src/session/SessionSearchNative.tsx, apps/mobile/src/session/SessionTailBanner.tsx, apps/mobile/src/session/SessionUsageSummary.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/ShareSelectAllButton.tsx, apps/mobile/src/session/ShareSelectionBar.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/StreamingStatusText.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/session/composerRichInputHtml.ts, apps/mobile/src/session/conversationShareWebViewHtml.ts, apps/mobile/src/session/mathWebView.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/mermaidWebView.tsx, apps/mobile/src/session/mermaidWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 7 | 203 | 199 |
-| `mobile.companions.direct` | mobile | 伙伴私聊回看 | app/companions/direct/[threadId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [threadId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/direct/[threadId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 18 |
-| `mobile.device-management` | mobile | 设备管理 | app/devices/manage.tsx / app/devices/manage/[deviceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceInformationFields, DeviceInformationFields.ios, DeviceLinkContext, DeviceManagementDialogs, DeviceManagementList, DeviceManagementList.ios, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, RenameDeviceModal, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, manage, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/manage.tsx, apps/mobile/app/devices/manage/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceInformationFields.ios.tsx, apps/mobile/src/device-link/DeviceInformationFields.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/DeviceManagementDialogs.tsx, apps/mobile/src/device-link/DeviceManagementList.ios.tsx, apps/mobile/src/device-link/DeviceManagementList.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RenameDeviceModal.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 21 |
-| `mobile.devices` | mobile | 主机详情 | app/devices/[deviceId].tsx | AccountSwitcherSheet, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeNativeStackHeader, HomeProjectMachineLabel, HomeSearchBar, IncomingShareBridge, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, RemoteAccessGuide, RemoteTaskSuggestions, RenameSessionModal, SessionActionSheet, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, ThemeProvider, [deviceId], _layout, gestureHandler, index, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/[deviceId].tsx, apps/mobile/app/devices/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 64 |
-| `mobile.files` | mobile | 任务文件与预览 | app/files/[sessionId].tsx / app/files/preview/[sessionId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HtmlFileReader, ImageLightbox, IncomingShareBridge, MarkdownFileReader, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, PushNotificationsBridge, QuietSyncIndicator, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, [sessionId], _layout, gestureHandler, mediaPlayerWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/files/[sessionId].tsx, apps/mobile/app/files/preview/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HtmlFileReader.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MarkdownFileReader.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 202 | 39 |
-| `mobile.home` | mobile | 主机与资源首页 | app/index.tsx / app/devices/index.tsx | AccountSwitcherSheet, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeNativeStackHeader, HomeProjectMachineLabel, HomeSearchBar, IncomingShareBridge, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, RemoteAccessGuide, RemoteTaskSuggestions, RenameSessionModal, SessionActionSheet, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, ThemeProvider, _layout, gestureHandler, index, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/index.tsx, apps/mobile/app/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 60 |
-| `mobile.overlay.connection-startup` | mobile | 根布局挂载的启动与连接反馈 | app/_layout.tsx → StartupSplashOverlay / ConnectionNoticeProvider;各页面 ConnectionBanner | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ConnectionNoticeProvider, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, PushNotificationsBridge, QuietSyncIndicator, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 16 |
-| `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/desktop/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 47 |
-| `mobile.resources` | mobile | 远程资源列表与详情 | app/resources/[collectionId].tsx / app/resources/[collectionId]/[resourceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, RemoteCompanionAvatar, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [collectionId], [resourceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/resources/[collectionId].tsx, apps/mobile/app/resources/[collectionId]/[resourceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 22 |
-| `mobile.settings` | mobile | 设置(含调试与日志上传可见入口) | app/settings.tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileChoicePickerList, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, settings, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/settings.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 24 |
+| `mobile.account-deletion` | mobile | 账号注销 | app/account-deletion.tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, account-deletion, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/account-deletion.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 54 |
+| `mobile.auth` | mobile | 登录与添加账号 | app/(auth)/login.tsx / app/add-account.tsx | AccountSwitcherSheet, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, IncomingShareBridge, LoginCaptchaWebView, LoginSkinControls, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, _layout, add-account, gestureHandler, login, peerFileTransport, useLocale | apps/mobile/app/(auth)/login.tsx, apps/mobile/app/_layout.tsx, apps/mobile/app/add-account.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/LoginCaptchaWebView.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/LoginSkinControls.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 177 | 75 |
+| `mobile.automations` | mobile | 自动化 | app/automations/[deviceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/automations/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 70 |
+| `mobile.chat.new` | mobile | 新建任务 | app/sessions/new.tsx | AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerAttachmentTray, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, ImageLightbox, IncomingShareBridge, MobileAgentMark, MobileAgentSwitcher, MobileChoicePickerList, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, MobileVendorIcon, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, NewTaskSelectionSheet, NewTaskSelectionSheet.ios, PaperPlaneIcon, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, _layout, gestureHandler, new, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/new.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx, apps/mobile/src/session/NewTaskSelectionSheet.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 202 | 109 |
+| `mobile.chat.session` | mobile | 任务内容与输入 | app/sessions/[sessionId].tsx | AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, AuthorizationMessageCard, BlurBackdrop, CenteredScreen, ChatFileChipMenuSheet, CompanionMessageCard, ComposerAttachmentTray, ComposerExpandButton, ComposerExpandButton.ios, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerNativeInput, ComposerNativeInput.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerRichInput, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, ConversationSearchFilterSheet, ConversationShareSvg, ConversationShareWebView, DeviceLinkContext, FailedScheduleNotice, HomeEntryProvider, HomeGlassMenuPanel, HomeNativeStackHeader, HomeSearchBar, ImageLightbox, IncomingShareBridge, InlineQueueSection, InlineQuoteChip, InlineReferenceChip, InteractionPanel, MarkdownBlockContent, MessageActionSheet, MessageRenderer, MobileAgentMark, MobileAgentSwitcher, MobileBoundaryNotice, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PaperPlaneIcon, PendingSendBubble, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PiSessionTreeSheet, PlanModeChip, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RewindPreviewPanel, SentInlineAtomBody, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionListDrawer, SessionMenuSheet, SessionSearchNative, SessionSearchNative.ios, SessionTailBanner, SessionUsageSummary, ShareMessageCheckbox, ShareSelectAllButton, ShareSelectionBar, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, StreamingStatusText, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, [sessionId], _layout, gestureHandler, mathWebView, mediaPlayerWebView, mermaidWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/AuthorizationMessageCard.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ChatFileChipMenuSheet.tsx, apps/mobile/src/session/CompanionMessageCard.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerExpandButton.ios.tsx, apps/mobile/src/session/ComposerExpandButton.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerNativeInput.ios.tsx, apps/mobile/src/session/ComposerNativeInput.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerRichInput.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/ConversationShareSvg.tsx, apps/mobile/src/session/ConversationShareWebView.tsx, apps/mobile/src/session/FailedScheduleNotice.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/InlineQueueSection.tsx, apps/mobile/src/session/InlineQuoteChip.tsx, apps/mobile/src/session/InlineReferenceChip.tsx, apps/mobile/src/session/InteractionPanel.tsx, apps/mobile/src/session/MarkdownBlockContent.tsx, apps/mobile/src/session/MessageActionSheet.tsx, apps/mobile/src/session/MessageRenderer.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileBoundaryNotice.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/PendingSendBubble.tsx, apps/mobile/src/session/PiSessionTreeSheet.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/RewindPreviewPanel.tsx, apps/mobile/src/session/SentInlineAtomBody.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionListDrawer.tsx, apps/mobile/src/session/SessionMenuSheet.tsx, apps/mobile/src/session/SessionSearchNative.ios.tsx, apps/mobile/src/session/SessionSearchNative.tsx, apps/mobile/src/session/SessionTailBanner.tsx, apps/mobile/src/session/SessionUsageSummary.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/ShareSelectAllButton.tsx, apps/mobile/src/session/ShareSelectionBar.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/StreamingStatusText.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/session/composerRichInputHtml.ts, apps/mobile/src/session/conversationShareWebViewHtml.ts, apps/mobile/src/session/mathWebView.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/mermaidWebView.tsx, apps/mobile/src/session/mermaidWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 7 | 203 | 230 |
+| `mobile.companions.direct` | mobile | 伙伴私聊回看 | app/companions/direct/[threadId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [threadId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/direct/[threadId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 49 |
+| `mobile.device-management` | mobile | 设备管理 | app/devices/manage.tsx / app/devices/manage/[deviceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceInformationFields, DeviceInformationFields.ios, DeviceLinkContext, DeviceManagementDialogs, DeviceManagementList, DeviceManagementList.ios, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RenameDeviceModal, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, manage, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/manage.tsx, apps/mobile/app/devices/manage/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceInformationFields.ios.tsx, apps/mobile/src/device-link/DeviceInformationFields.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/DeviceManagementDialogs.tsx, apps/mobile/src/device-link/DeviceManagementList.ios.tsx, apps/mobile/src/device-link/DeviceManagementList.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RenameDeviceModal.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 52 |
+| `mobile.devices` | mobile | 主机详情 | app/devices/[deviceId].tsx | AccountSwitcherSheet, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeNativeStackHeader, HomeProjectMachineLabel, HomeSearchBar, IncomingShareBridge, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteAccessGuide, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteTaskSuggestions, RenameSessionModal, SessionActionSheet, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, ThemeProvider, [deviceId], _layout, gestureHandler, index, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/[deviceId].tsx, apps/mobile/app/devices/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 95 |
+| `mobile.files` | mobile | 任务文件与预览 | app/files/[sessionId].tsx / app/files/preview/[sessionId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HtmlFileReader, ImageLightbox, IncomingShareBridge, MarkdownFileReader, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, [sessionId], _layout, gestureHandler, mediaPlayerWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/files/[sessionId].tsx, apps/mobile/app/files/preview/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HtmlFileReader.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MarkdownFileReader.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 202 | 70 |
+| `mobile.home` | mobile | 主机与资源首页 | app/index.tsx / app/devices/index.tsx | AccountSwitcherSheet, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeNativeStackHeader, HomeProjectMachineLabel, HomeSearchBar, IncomingShareBridge, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteAccessGuide, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteTaskSuggestions, RenameSessionModal, SessionActionSheet, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, ThemeProvider, _layout, gestureHandler, index, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/index.tsx, apps/mobile/app/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 91 |
+| `mobile.overlay.connection-startup` | mobile | 根布局挂载的启动与连接反馈 | app/_layout.tsx → StartupSplashOverlay / ConnectionNoticeProvider;各页面 ConnectionBanner | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ConnectionNoticeProvider, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 47 |
+| `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/desktop/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 47 |
+| `mobile.resources` | mobile | 远程资源列表与详情 | app/resources/[collectionId].tsx / app/resources/[collectionId]/[resourceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [collectionId], [resourceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/resources/[collectionId].tsx, apps/mobile/app/resources/[collectionId]/[resourceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 53 |
+| `mobile.settings` | mobile | 设置(含调试与日志上传可见入口) | app/settings.tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileChoicePickerList, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, settings, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/settings.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 170 | 55 |
### 生产路由覆盖
@@ -125,7 +125,7 @@
| apps/mobile/app/automations/[deviceId].tsx | AutomationsScreen | `mobile.automations` |
| apps/mobile/app/companions/direct/[threadId].tsx | CompanionDirectMessages | `mobile.companions.direct` |
| apps/mobile/app/devices/[deviceId].tsx | DeviceDetailScreen | `mobile.devices` |
-| apps/mobile/app/devices/desktop/[deviceId].tsx | @/remote-desktop/RemoteDesktopScreen | `mobile.remote-desktop` |
+| apps/mobile/app/devices/desktop/[deviceId].tsx | RemoteDesktopRoute | `mobile.remote-desktop` |
| apps/mobile/app/devices/index.tsx | HomeScreen | `mobile.home` |
| apps/mobile/app/devices/manage/[deviceId].tsx | DeviceInformationScreen | `mobile.device-management` |
| apps/mobile/app/devices/manage.tsx | DeviceManagementScreen | `mobile.device-management` |
diff --git a/docs/dev-rules/remote-desktop-connectivity.md b/docs/dev-rules/remote-desktop-connectivity.md
index da3d44699c..45d9564020 100644
--- a/docs/dev-rules/remote-desktop-connectivity.md
+++ b/docs/dev-rules/remote-desktop-connectivity.md
@@ -38,6 +38,106 @@ TURN; old viewer + new Desktop can use host-side TURN. Existing full-SDP and tri
ICE capabilities stay unchanged. The desktop-video connectivity change adds no new wire kinds or native dependencies.
The independent file transport below has its own authorized IPC channel.
+## iOS native video and Picture in Picture
+
+New iOS binaries expose `CindyRemotePresentation.nativeVideo`. They receive and
+decode WebRTC in `RemoteDesktopReceiver`, and display sample buffers through
+`RemoteDesktopVideoView` / AVKit. The WebView retains input, cursor and viewport
+geometry only. Older binaries and Android retain the browser receiver; JPEG
+compatibility frames remain available on every platform. The native receiver uses
+the same full-SDP/trickle-ICE signaling adapter, scoped TURN configuration and
+bounded retry policy. No protocol version or service endpoint changes.
+
+While system PiP is actually active and host presentation authorization is confirmed,
+the native DataChannel answers the existing
+viewing challenges without React or WebView JavaScript. Desktop preserves only
+an authorized, non-controlling presentation across transient signaling loss;
+ordinary subscriptions and file transfers still stop. The existing 12-second
+lease expires if media pongs stop. Explicit disconnect, revocation, disabling
+remote control and host shutdown still stop the presentation immediately.
+An offline event for a different peer cannot terminate the active viewer.
+The native receiver retains the host's single pending challenge if it arrives
+before PiP entry, and answers only after both AVKit active presentation and host
+authorization are confirmed.
+Voice-input cleanup releases only its own recording session; background entry
+and delayed prewarm cleanup must not deactivate PiP's playback session.
+
+Run in background is an explicit phone-local preference (default off), separate
+from the current AVKit presentation state and the user's control choice. Toggling
+it does not enter PiP or release control, and audio renegotiation does not disable
+the preference. Only actual entry uses the host's view-only presentation handoff;
+returning to an active, visible fullscreen viewer restores the previous control
+choice through normal host authorization. A cancelled Home gesture also restores
+that choice after any pending preparation settles. Restoring fullscreen does not clear
+the preference. While enabled, leaving the desktop route minimizes into PiP;
+the foreground viewer arms AVKit after its first frame. Home entry is owned by
+AVKit automatic entry: do not manually start from willResignActive, because the
+source UIScene may already be inactive even while UIApplication reports active.
+Explicit in-app entry requires the source scene to be foreground-active. The host
+handoff runs in parallel, without delaying AVKit for its network reply.
+The sample-buffer delegate reports no playable content until a frame is rendered.
+First-frame and teardown transitions invalidate AVKit's cached playback state;
+returning inline refreshes that state after the PiP stop completes. A cached old
+frame alone does not make a reconnecting receiver ready for PiP.
+Keep the AVKit sample-buffer projection at the native viewport's bounds, separate
+from the inline layer's fitted/panned/zoomed rectangle. Both renderers share one
+decoded sample buffer; their readiness must not block each other. Only the system
+projection receives frames while inline is hidden or the app is inactive. Restore
+replays the latest frame into the inline renderer before completing the visible
+source handoff. In physical-device A/B testing, a fitted or transformed source
+missed interactive Home entry even while AVKit reported PiP possible; a fixed
+viewport-sized source started successfully. This is an observed regression guard,
+not a claim about Apple's private eligibility rules. Test actual upward Home
+gestures after restore: an automation Home-button event does not cover that path.
+System readiness alone never authorizes viewing challenge replies.
+Both JS and native background cleanup bound an unfinished handoff to four seconds.
+The signaling connection's ordinary 2.5-second background grace must wait for an
+in-flight presentation handoff, capped at four seconds after background entry.
+Heavy subscriptions are still released immediately. Success, failure, cancellation
+and the handoff deadline release this wait; it never authorizes media or renews a lease.
+Rapid Home re-entry waits for pending fullscreen control restoration before sending
+a new presentation request; expired lease/generation results cannot revive it.
+Fullscreen restoration waits for signaling to be online before relinquishing its
+acknowledged background-viewing authorization or requesting input control. While
+reconnecting, the native stream keeps that authorization; another Home entry can
+reuse it. A stopped signaling socket alone must not destroy this authorized stream.
+One account-generation-scoped root host retains the same media surface across
+routes. A minimized desktop is removed from navigation history without changing
+the other pages or their parameters. Fullscreen restoration opens one desktop
+entry above the current page; Back returns to that page. Delayed PiP callbacks
+are bound to their source route and cannot pop a newly opened page. The retained
+surface only becomes visible once its desktop route is current. AVKit restore
+completion waits for JS route readiness and a visible, laid-out native source
+(including ancestor opacity), not merely attachment to a window. A generation-scoped
+check covers parent-only visibility commits and expires at the existing five-second
+restore deadline.
+Closing a detached PiP window or explicitly disconnecting ends the connection,
+but keeps the preference. Back-to-PiP does not run lock-on-exit; disconnect does.
+Preparation has a bounded deadline and never renews a controlling lease.
+
+Closing PiP in the background stops native media even if JS is suspended. Network
+changes that require a new SDP exchange recover after foreground signaling
+returns; continuous background renegotiation is not promised. Frames and ICE
+credentials stay in memory, with no recording or new media store.
+
+The WebRTC SDK and Swift module change require a rebuilt iOS binary (cold update),
+not OTA alone. Verify silent and audible streams, explicit stop/revoke, switching
+apps for several minutes, PiP close/restore, network loss, zoom/keyboard geometry,
+and Light/Dark on a physical phone. Unit tests and simulator builds do not establish
+background PiP acceptance. Roll out the Desktop signaling-loss fix with the native
+phone build; older Desktop hosts may still stop media when signaling disconnects.
+
+Run `node apps/mobile/scripts/test-remote-desktop-receiver.mjs` on macOS to
+compile and execute the production receiver against test-only UIKit/WebRTC doubles.
+It covers attempt isolation, late SDP/ICE/frame callbacks, idempotent stop,
+disconnect timer cancellation and presentation challenge authorization. The doubles
+control SDK callbacks; they do not validate framework ABI, decoding or AVKit behavior.
+
+iOS 27 SDK builds also require the scene lifecycle. Expo 57.0.23 or newer and
+`expo-build-properties`'s `ios.enableSceneSupport` generate Expo's scene delegate
+manifest and move window startup out of the legacy app delegate. Verify actual
+device launch: compilation alone does not detect UIKit's missing-scene launch trap.
+
## Verification
Unit tests cover invalid/expired tickets, old/disabled backends, bounded requests,
diff --git a/docs/remote-desktop.md b/docs/remote-desktop.md
index 51eae651ef..b0245b2594 100644
--- a/docs/remote-desktop.md
+++ b/docs/remote-desktop.md
@@ -197,15 +197,15 @@ both sides. Duplicate candidates are applied once. A timed-out exchange does
not tear down healthy video; polling is bounded to 30 seconds. SDP, candidate
addresses, credentials and desktop content are not added to logs.
-| Phase | Bound |
-| --- | --- |
-| Desktop source enumeration | 2 seconds with native capture, 5 seconds otherwise |
-| Desktop offer command | 18 seconds |
-| Remote-desktop invoke | 30 seconds; other invoke channels are unchanged |
-| Viewer waiting for answer | 25 seconds |
-| ICE checks after answer | 15 seconds |
-| Temporary media disconnect | 5-second grace period |
-| Automatic media retries | 1, 3 and 8 seconds; restored after 30 seconds connected |
+| Phase | Bound |
+| -------------------------- | ------------------------------------------------------- |
+| Desktop source enumeration | 2 seconds with native capture, 5 seconds otherwise |
+| Desktop offer command | 18 seconds |
+| Remote-desktop invoke | 30 seconds; other invoke channels are unchanged |
+| Viewer waiting for answer | 25 seconds |
+| ICE checks after answer | 15 seconds |
+| Temporary media disconnect | 5-second grace period |
+| Automatic media retries | 1, 3 and 8 seconds; restored after 30 seconds connected |
On a transient disconnect the viewer keeps the picture, releases held input and
shows the existing reconnecting badge. Input uses the existing authorized invoke
@@ -410,10 +410,13 @@ remote desktop reconnects with fresh dimensions. The shared relay and other
peer links remain untouched. Windows/Linux display mode changes are currently
unavailable and are not advertised.
-System PiP is offered only when WebKit reports support for this video and the
-native presentation module and host backgroundViewing capability are present.
+System PiP requires the native presentation module and host backgroundViewing
+capability. New iOS binaries use AVKit readiness; browser receivers require WebKit
+support for the video. Native automatic entry is armed in the foreground after the
+first frame, with host authorization completed in parallel during Home entry.
Entering releases control. A capture-renderer challenge/pong heartbeat renews
-only a view-only lease while the viewer reports actual system PiP presentation.
+only a view-only lease after host authorization while the viewer reports actual
+system PiP presentation.
Closing PiP, closing WebRTC, local disconnect, revocation and the ordinary finite
lease timeout all terminate background viewing. This does not grant indefinite
background control or extend the lifetime of unrelated device links.
@@ -486,7 +489,6 @@ Remaining platform adapters are explicitly separate:
The macOS pre-login and Linux service adapters remain unimplemented. The remote business protocol and shared relay are unchanged. Recovery
affects only this desktop lease/video track, not other connected peers.
-
### Windows system service (implementation awaiting Windows runtime validation)
Packaged Windows builds include a native SCM service, a Main-only Node-API pipe
@@ -522,7 +524,6 @@ Windows display-mode changes and pre-login/unattended post-reboot control are no
implemented. Linux remains deferred. Do not present this as fully validated
Windows support or advertise high-frame-rate secure capture.
-
### Keyboard clipboard actions
The keyboard's leading clipboard button opens two actions in both phone and
@@ -554,7 +555,6 @@ TypeScript and native compilation checks cover this implementation. Keyboard/men
interaction, application-specific selection support, and physical-phone transfer
have not been exercised; manual verification remains with the user.
-
### Portable clipboard content
New peers advertise optional `clipboardContent`; legacy `clipboardText` and its
@@ -656,7 +656,6 @@ capture returning cursor geometry/raster metadata. Real phone gestures,
application-by-application cursor transitions and sustained frame rate remain
for manual verification.
-
## Clipboard and connection handoff
The keyboard clipboard menu offers Copy to phone and Paste from phone. Copy
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index 22d939e2d7..80b1db525e 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -395,6 +395,10 @@ dev 版登录页区域徽标上的标签值(DESIGN.md §16.3),四语同值
同账号手机查看和操作电脑真实桌面,独立于 Cindy 内部设备控制授权。
+### Run in background
+
+远程桌面的持续开关,用户已确认中文名。离开页面或切到后台时以小窗继续显示,回到全屏后仍保持开启;不是任意后台任务或强制退出后继续运行的承诺。其他语言译名登记为 proposed。
+
### Direct to computer
远程桌面传输状态,桌面端沿用手机端现有用语。表示画面不经过中转服务器;直连也可能穿过公网 NAT,不能据此标成内网直连。
diff --git a/i18n/glossary.json b/i18n/glossary.json
index fe7540bfcc..0297e51ed4 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -44,6 +44,18 @@
},
"note": "用于 Desktop 本机范围标签。translations 中带任务/セッション/세션 的译法仅用于侧栏任务范围标题 ccAgent.sidebar.scopeLocalSessions;设备菜单、新建任务按钮和设备分组标题使用 alsoAllowed 中不带任务的设备标签译法,不可互换。英文统一使用 Local,表示当前电脑或其上的任务;其他语言保留各位置现有表达。不表示本地模型、离线模式或未登录状态,也不约束其他语境中的 local。"
},
+ {
+ "id": "remote-desktop-background-running",
+ "status": "proposed",
+ "en": "Run in background",
+ "translations": {
+ "zh-CN": "后台运行",
+ "zh-TW": "背景執行",
+ "ja": "バックグラウンド実行",
+ "ko": "백그라운드 실행"
+ },
+ "note": "远程桌面的持续开关,用户已确认中文名。离开页面或切到后台时以小窗继续显示,回到全屏后仍保持开启;不是任意后台任务或强制退出后继续运行的承诺。其他语言译名登记为 proposed。"
+ },
{
"id": "remote-desktop-direct",
"status": "proposed",
diff --git a/packages/maker-shared/src/remote-desktop/mobileHtml.ts b/packages/maker-shared/src/remote-desktop/mobileHtml.ts
index 50bec4ffa8..cb53c4137e 100644
--- a/packages/maker-shared/src/remote-desktop/mobileHtml.ts
+++ b/packages/maker-shared/src/remote-desktop/mobileHtml.ts
@@ -3,7 +3,12 @@ import { DESKTOP_VIEWER_SOURCE } from "./viewerSource";
export function remoteDesktopViewerHtml(
surface: string,
foreground: string,
- config: { net: unknown; iceServers: unknown; keyCodes: readonly string[] },
+ config: {
+ net: unknown;
+ iceServers: unknown;
+ keyCodes: readonly string[];
+ nativeMedia?: boolean;
+ },
): string {
// Only theme token colors enter markup. No device names, SDP, or remote HTML.
const color = (v: string) =>
@@ -32,6 +37,7 @@ export function remoteDesktopViewerHtml(
#mouse-wheel>*{pointer-events:none}
#mouse-wheel-grip{width:20px;height:34px}
@media(max-height:400px){#mouse-wheel{bottom:12px}}
+ ${config.nativeMedia ? "html,body{background:transparent}" : ""}
</style></head><body><div id="stage"><div id="bg"><canvas id="bg-canvas"></canvas></div><div id="network-status"></div><img id="image" alt=""><video id="video" autoplay muted playsinline></video><div id="cursor"><img id="cursor-image" alt=""></div></div>
<div id="mouse-buttons">
${(["left", "right"] as const).map((button) => `<button type="button" id="mouse-${button}" class="mouse-button" aria-pressed="false"><svg viewBox="0 0 24 32" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="2" width="18" height="28" rx="9"/><path d="M12 2v12M3 14h18"/><path d="${button === "left" ? "M11 3C6 3 4 6 4 10v3h7Z" : "M13 3c5 0 7 3 7 7v3h-7Z"}" fill="currentColor" stroke="none"/></svg></button>`).join("")}
diff --git a/packages/maker-shared/src/remote-desktop/viewerRuntime.d.ts b/packages/maker-shared/src/remote-desktop/viewerRuntime.d.ts
index 44b60b57f5..04a0586d91 100644
--- a/packages/maker-shared/src/remote-desktop/viewerRuntime.d.ts
+++ b/packages/maker-shared/src/remote-desktop/viewerRuntime.d.ts
@@ -2,5 +2,11 @@
export function mountRemoteDesktopViewer(
root: Document | HTMLElement,
post: (message: Record<string, unknown>) => void,
- config: { net: object; iceServers: readonly object[]; keyCodes: readonly string[]; desktop?: boolean },
+ config: {
+ net: object;
+ iceServers: readonly object[];
+ keyCodes: readonly string[];
+ desktop?: boolean;
+ nativeMedia?: boolean;
+ },
): { receive(message: object): void; dispose(): void };
diff --git a/packages/maker-shared/src/remote-desktop/viewerRuntime.js b/packages/maker-shared/src/remote-desktop/viewerRuntime.js
index 86baa6ed79..f70b995157 100644
--- a/packages/maker-shared/src/remote-desktop/viewerRuntime.js
+++ b/packages/maker-shared/src/remote-desktop/viewerRuntime.js
@@ -10,6 +10,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
? root.getElementById(id)
: root.querySelector("#" + id);
const { net, iceServers } = config;
+ let nativeVideoActive = false;
const validKeys = new Set(config.keyCodes);
const transform =
/* BEGIN TRANSFORM */
@@ -321,6 +322,10 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
return null;
}
function paintBackground() {
+ if (nativeVideoActive) {
+ if (bg) bg.style.display = "none";
+ return;
+ }
if (!bg || !bgCanvas || !bgContext) return;
const vw = stage.clientWidth,
vh = stage.clientHeight;
@@ -611,6 +616,15 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
}
function render() {
const r = layout();
+ if (config.nativeMedia && epoch)
+ post({
+ type: "nativeViewport",
+ fillHeight,
+ x: r.x,
+ y: r.y,
+ width: r.width,
+ height: r.height,
+ });
const touchFeedback = control && mode === "touch" && touchCursorVisible;
const cursorX = mode === "touch" && touchCursor ? touchCursor.x : cx;
const cursorY = mode === "touch" && touchCursor ? touchCursor.y : cy;
@@ -1753,6 +1767,11 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
});
break;
case "presentation":
+ if (config.nativeMedia) {
+ release();
+ showKeyboard(false);
+ break;
+ }
try {
if (message.enabled) {
release();
@@ -1793,7 +1812,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
}
video.muted = !message.audio;
retries = 0;
- connect();
+ if (!config.nativeMedia) connect();
break;
case "keyboard":
showKeyboard(message.enabled === true);
@@ -1806,8 +1825,12 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
break;
case "theme":
if (/^#[0-9a-f]{3,8}$/i.test(message.surface)) {
- document.body.style.background = message.surface;
- document.documentElement.style.background = message.surface;
+ document.body.style.background = config.nativeMedia
+ ? "transparent"
+ : message.surface;
+ document.documentElement.style.background = config.nativeMedia
+ ? "transparent"
+ : message.surface;
document.documentElement.style.setProperty(
"--surface",
message.surface,
@@ -1970,6 +1993,8 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
break;
}
case "init":
+ nativeVideoActive = false;
+ image.style.visibility = "visible";
viewerSized = false;
followRest = null;
cursorNeedsEntry = true;
@@ -1992,7 +2017,17 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
trickleIce = message.trickleIce === true;
retries = 0;
render();
- connect();
+ if (!config.nativeMedia) connect();
+ break;
+ case "nativeVideo":
+ if (!config.nativeMedia || message.epoch !== epoch) break;
+ nativeVideoActive = message.active === true;
+ image.style.visibility = nativeVideoActive ? "hidden" : "visible";
+ paintBackground();
+ break;
+ case "nativeCursor":
+ if (config.nativeMedia && message.epoch === epoch)
+ receiveCursor(message.cursor);
break;
case "viewport":
fillHeight = message.fillHeight === true;
@@ -2064,6 +2099,8 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
sending = false;
break;
case "stop":
+ nativeVideoActive = false;
+ image.style.visibility = "visible";
showKeyboard(false);
control = false;
release();
diff --git a/packages/maker-shared/src/remote-desktop/viewerSource.ts b/packages/maker-shared/src/remote-desktop/viewerSource.ts
index 3378c7f7e8..47fc280c86 100644
--- a/packages/maker-shared/src/remote-desktop/viewerSource.ts
+++ b/packages/maker-shared/src/remote-desktop/viewerSource.ts
@@ -1,2 +1,2 @@
// Generated by scripts/sync-remote-desktop-viewer.mjs. Do not edit.
-export const DESKTOP_VIEWER_SOURCE = "/** Shared browser viewer. Mobile bundles this exact source; Desktop imports it as a CSP-safe module. */\nfunction mountRemoteDesktopViewer(root, postMessage, config) {\n const cleanups = [];\n const listen = (target, type, fn, options) => {\n target.addEventListener(type, fn, options);\n cleanups.push(() => target.removeEventListener(type, fn, options));\n };\n const find = (id) =>\n root.getElementById\n ? root.getElementById(id)\n : root.querySelector(\"#\" + id);\n const { net, iceServers } = config;\n const validKeys = new Set(config.keyCodes);\n const transform =\n /* BEGIN TRANSFORM */\n function desktopTransform(\n vw,\n vh,\n dw,\n dh,\n zoom,\n fx,\n fy,\n fillHeight = false,\n ) {\n const scale =\n (fillHeight\n ? vh / Math.max(1, dh)\n : Math.min(vw / Math.max(1, dw), vh / Math.max(1, dh))) *\n Math.max(1, Math.min(5, zoom));\n const width = dw * scale;\n const height = dh * scale;\n const x =\n width <= vw\n ? (vw - width) / 2\n : Math.min(0, Math.max(vw - width, vw / 2 - fx * width));\n const y =\n height <= vh\n ? (vh - height) / 2\n : Math.min(0, Math.max(vh - height, vh / 2 - fy * height));\n return { x, y, width, height, scale };\n };\n /* END TRANSFORM */ const networkStats =\n /* BEGIN NETWORK_STATS */\n function networkStats(stats, previous) {\n const rows = [...stats.values()];\n const video = rows.find(\n (s) =>\n s.type === \"inbound-rtp\" &&\n (s.kind === \"video\" || s.mediaType === \"video\"),\n );\n const transport = rows.find(\n (s) => s.type === \"transport\" && s.selectedCandidatePairId,\n );\n const pair = transport\n ? stats.get(transport.selectedCandidatePairId)\n : rows.find(\n (s) =>\n s.type === \"candidate-pair\" &&\n s.state === \"succeeded\" &&\n s.nominated,\n );\n const local = pair && stats.get(pair.localCandidateId),\n remote = pair && stats.get(pair.remoteCandidateId);\n const direct = [\"host\", \"srflx\", \"prflx\"];\n const route =\n local?.candidateType === \"relay\" || remote?.candidateType === \"relay\"\n ? \"relay\"\n : direct.includes(local?.candidateType) &&\n direct.includes(remote?.candidateType)\n ? \"direct\"\n : \"video\";\n const sample =\n video &&\n Number.isFinite(video.bytesReceived) &&\n Number.isFinite(video.timestamp)\n ? {\n id: video.id,\n path: pair?.id,\n bytes: video.bytesReceived,\n time: video.timestamp,\n }\n : null;\n let bytesPerSecond = null;\n if (\n sample &&\n previous &&\n sample.id === previous.id &&\n sample.path === previous.path &&\n sample.time > previous.time &&\n sample.bytes >= previous.bytes\n )\n bytesPerSecond =\n ((sample.bytes - previous.bytes) * 1000) /\n (sample.time - previous.time);\n const latencyMs =\n Number.isFinite(pair?.currentRoundTripTime) &&\n pair.currentRoundTripTime >= 0\n ? pair.currentRoundTripTime * 1000\n : null;\n return { transport: route, bytesPerSecond, latencyMs, sample };\n };\n\n /* END NETWORK_STATS */ const stage = find(\"stage\"),\n image = find(\"image\"),\n video = find(\"video\"),\n cursor = find(\"cursor\");\n // 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 (!bg || !bgCanvas || !bgContext) return;\n const vw = stage.clientWidth,\n vh = stage.clientHeight;\n const seg = backgroundSegments(vw, vh, dw, dh, fillHeight);\n if (!seg) {\n bg.style.display = \"none\";\n bgRects = null;\n stopBackgroundLoop();\n return;\n }\n bg.style.display = \"block\";\n bgAxis = seg.axis;\n // The ambient layer also fills the notch and the area beneath native\n // controls. Only the interactive picture respects viewport insets.\n const originX = 0;\n // Source segments are resolved at draw time from the live source dimensions;\n // these dest rects only encode where each segment lands on the stage.\n bgRects =\n seg.axis === \"x\"\n ? [\n {\n x: originX,\n y: seg.top,\n w: seg.sideW,\n h: seg.h,\n },\n {\n x: originX + seg.centerX,\n y: seg.top,\n w: seg.centerW,\n h: seg.h,\n },\n {\n x: originX + seg.centerX + seg.centerW,\n y: seg.top,\n w: seg.sideW,\n h: seg.h,\n },\n ]\n : [\n {\n x: seg.left,\n y: 0,\n w: seg.w,\n h: seg.sideH,\n },\n {\n x: seg.left,\n y: seg.centerY,\n w: seg.w,\n h: seg.centerH,\n },\n {\n x: seg.left,\n y: seg.centerY + seg.centerH,\n w: seg.w,\n h: seg.sideH,\n },\n ];\n // Keep the backing store at stage resolution (capped) so the stretched\n // edges stay crisp without oversized allocations.\n bgDpr = Math.min(2, window.devicePixelRatio || 1);\n const bw = Math.round(stage.clientWidth * bgDpr),\n bh = Math.round(vh * bgDpr);\n if (bgCanvas.width !== bw || bgCanvas.height !== bh) {\n bgCanvas.width = bw;\n bgCanvas.height = bh;\n }\n scheduleBackgroundDraw();\n startBackgroundLoop();\n }\n // One canvas, three draws: each source segment stretches into whatever bar\n // the picture leaves open. The live video feeds it once presented; until\n // then the decoded JPEG frame does, so the backdrop always matches the\n // picture's own pixels and scale in the center segment.\n let bgRects = null,\n bgAxis = \"x\",\n bgDpr = 1,\n bgDrawFrame = null,\n bgLoopFrame = null;\n function drawBackground() {\n if (!bgContext || !bgRects) return;\n bgContext.setTransform(bgDpr, 0, 0, bgDpr, 0, 0);\n bgContext.clearRect(0, 0, stage.clientWidth, stage.clientHeight);\n const useVideo =\n videoPresented && video.videoWidth > 0 && video.videoHeight > 0;\n const src = useVideo ? video : image;\n // drawImage source rects live in the source's own pixel space, which can\n // differ from dw/dh; fractions of the real bitmap keep every segment lined\n // up with what the picture element actually shows.\n const sw = useVideo ? video.videoWidth : image.naturalWidth;\n const sh = useVideo ? video.videoHeight : image.naturalHeight;\n if (!(sw > 0 && sh > 0)) return;\n const horizontal = bgAxis === \"x\";\n const sourceLength = horizontal ? sw : sh;\n const cuts = [0, bgEdgeFraction, 1 - bgEdgeFraction, 1];\n for (let i = 0; i < bgRects.length; i++) {\n const rect = bgRects[i];\n const origin = cuts[i] * sourceLength;\n const length = (cuts[i + 1] - cuts[i]) * sourceLength;\n bgContext.drawImage(\n src,\n horizontal ? origin : 0,\n horizontal ? 0 : origin,\n horizontal ? length : sw,\n horizontal ? sh : length,\n rect.x,\n rect.y,\n rect.w,\n rect.h,\n );\n }\n }\n function scheduleBackgroundDraw() {\n if (bgDrawFrame !== null || !bgRects || !bgContext) return;\n bgDrawFrame = requestAnimationFrame(() => {\n bgDrawFrame = null;\n drawBackground();\n });\n }\n function startBackgroundLoop() {\n if (\n bgLoopFrame !== null ||\n !bgContext ||\n !bgRects ||\n !videoPresented ||\n typeof video.requestVideoFrameCallback !== \"function\"\n )\n return;\n const frame = video.requestVideoFrameCallback(() => {\n if (bgLoopFrame !== frame) return;\n bgLoopFrame = null;\n drawBackground();\n startBackgroundLoop();\n });\n bgLoopFrame = frame;\n }\n // Only the streaming loop stops here; a pending one-shot draw is harmless\n // (it re-paints the preserved frame) and must survive reconnects.\n function stopBackgroundLoop() {\n if (bgLoopFrame !== null) video.cancelVideoFrameCallback?.(bgLoopFrame);\n bgLoopFrame = null;\n }\n function clearBackground() {\n stopBackgroundLoop();\n bgRects = null;\n // Resizing a canvas resets its bitmap; same-value assignment still clears.\n if (bgCanvas) bgCanvas.width = bgCanvas.width;\n }\n listen(image, \"load\", () => scheduleBackgroundDraw());\n // Older WebViews update the ambient layer on media progress, never with an\n // idle display-refresh loop. Geometry changes still get a one-shot repaint.\n listen(video, \"timeupdate\", () => {\n if (videoPresented && typeof video.requestVideoFrameCallback !== \"function\")\n scheduleBackgroundDraw();\n });\n function panBounds(r) {\n const vw = viewportWidth(),\n vh = viewportHeight();\n // Grow extra resting travel continuously from zero at fit to 180 screen\n // points at maximum zoom. Never count the unused space of a fitting axis.\n const clearance = (180 * (Math.max(1, Math.min(5, zoom)) - 1)) / 4;\n const axis = (viewport, content) =>\n content <= viewport\n ? {\n min: (viewport - content) / 2 - clearance,\n max: (viewport - content) / 2 + clearance,\n }\n : { min: viewport - content - clearance, max: clearance };\n const x = axis(vw, r.width),\n y = axis(vh, r.height);\n const bounds = {\n minX: viewportLeft() + x.min,\n maxX: viewportLeft() + x.max,\n minY: y.min + verticalOffset(r.height),\n maxY: y.max + verticalOffset(r.height),\n };\n // A camera position required to expose the cursor is a valid resting point,\n // not elastic overshoot. Preserve it across the next pan/pinch handoff.\n if (followRest) {\n const restX = viewportLeft() + vw / 2 - followRest.fx * r.width,\n restY = vh / 2 + verticalOffset(r.height) - followRest.fy * r.height;\n const weight =\n followRest.zoom > 1 ? clamp((zoom - 1) / (followRest.zoom - 1)) : 1;\n bounds.minX += Math.min(0, restX - bounds.minX) * weight;\n bounds.maxX += Math.max(0, restX - bounds.maxX) * weight;\n bounds.minY += Math.min(0, restY - bounds.minY) * weight;\n bounds.maxY += Math.max(0, restY - bounds.maxY) * weight;\n }\n return bounds;\n }\n const bounded = (v, min, max) => Math.max(min, Math.min(max, v));\n // Convert displayed overshoot back to finger travel before the next delta,\n // so reversing direction unwinds smoothly without an edge jump.\n function rubber(v, min, max, inverse = false) {\n const edge = bounded(v, min, max),\n d = v - edge;\n const reach = 40 + 10 * (Math.max(1, Math.min(5, zoom)) - 1);\n return (\n edge +\n Math.sign(d) *\n (inverse\n ? (reach * Math.abs(d)) / Math.max(1, reach - Math.abs(d))\n : (reach * Math.abs(d)) / (reach + Math.abs(d)))\n );\n }\n function place(x, y, r) {\n fx = (viewportLeft() + viewportWidth() / 2 - x) / r.width;\n fy = (viewportHeight() / 2 + verticalOffset(r.height) - y) / r.height;\n }\n function cursorViewport() {\n const hotX = remoteCursor?.hotX ?? 9,\n hotY = remoteCursor?.hotY ?? 9;\n const w = remoteCursor?.width ?? 18,\n h = remoteCursor?.height ?? 18;\n const left = viewportLeft(),\n right = left + viewportWidth(),\n bottom = Math.max(1, stage.clientHeight - viewportBottomInset);\n // Keep the entire cursor, including its hotspot offset, clear of chrome.\n const minX = Math.min(right - 1, left + 8 + hotX),\n minY = Math.min(\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 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 if (canRetry && epoch && retries < net.retryMs.length) {\n const delay = net.retryMs[retries++];\n retryTimer = setTimeout(() => {\n retryTimer = null;\n if (epoch) connect();\n }, delay);\n }\n }\n function pollIce() {\n if (\n !pc ||\n !trickleIce ||\n !pc.remoteDescription ||\n icePending ||\n Date.now() >= exchangeUntil\n )\n return;\n const candidates = localCandidates.slice(\n localAck,\n localAck + net.batchSize,\n );\n icePending = {\n after: remoteAfter,\n sent: candidates.length,\n exchangeId: ++exchangeId,\n };\n post({\n type: \"ice\",\n attemptId,\n candidates,\n after: remoteAfter,\n exchangeId,\n });\n iceTimer = setTimeout(() => {\n icePending = null;\n pollIce();\n }, 4500);\n }\n async function receiveIce(message) {\n if (\n !pc ||\n !icePending ||\n message.attemptId !== attemptId ||\n message.exchangeId !== icePending.exchangeId\n )\n return;\n const rtc = pc,\n g = generation,\n batch = icePending;\n clearTimeout(iceTimer);\n try {\n if (message.error) {\n icePending = null;\n iceTimer = setTimeout(pollIce, 1000);\n return;\n }\n if (\n !Array.isArray(message.candidates) ||\n message.candidates.length > net.batchSize ||\n message.next !== batch.after + message.candidates.length ||\n message.next > net.maxCandidates\n )\n throw new Error();\n for (const candidate of message.candidates) {\n if (g !== generation) return;\n const key = JSON.stringify(candidate);\n if (remoteSeen.has(key)) continue;\n if (remoteSeen.size >= net.maxCandidates) throw new Error();\n await rtc.addIceCandidate(candidate);\n if (g !== generation) return;\n remoteSeen.add(key);\n }\n if (g !== generation) return;\n localAck += batch.sent;\n remoteAfter = message.next;\n remoteComplete = message.complete === true;\n icePending = null;\n if (!(\n remoteComplete &&\n rtc.iceGatheringState === \"complete\" &&\n localAck === localCandidates.length\n ))\n iceTimer = setTimeout(pollIce, net.pollMs);\n } catch {\n if (g === generation) failRtc(\"candidates\");\n }\n }\n async function receiveAnswer(message) {\n if (!pc || message.attemptId !== attemptId) return;\n const rtc = pc,\n g = generation;\n try {\n await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n if (g !== generation) return;\n clearTimeout(deadlineTimer);\n deadlineTimer = setTimeout(() => {\n if (g === generation && rtc.connectionState !== \"connected\")\n failRtc(\"connect-timeout\");\n }, net.connectMs);\n exchangeUntil = Date.now() + net.exchangeMs;\n pollIce();\n } catch {\n if (g === generation) failRtc(\"answer\");\n }\n }\n async function connect() {\n closeRtc();\n const g = generation;\n attemptId = String(g);\n if (!window.RTCPeerConnection) {\n failRtc(\"unsupported\", false);\n return;\n }\n configPending = true;\n deadlineTimer = setTimeout(() => {\n if (g === generation && configPending) {\n configPending = false;\n void startRtc(g, iceServers);\n }\n }, 3500);\n return post({ type: \"iceConfig\", attemptId });\n }\n async function receiveIceConfig(message) {\n if (!epoch || !configPending || message.attemptId !== attemptId) return;\n configPending = false;\n clearTimeout(deadlineTimer);\n deadlineTimer = null;\n await startRtc(generation, message.iceServers);\n }\n async function startRtc(g, servers) {\n try {\n const rtc = new RTCPeerConnection({ iceServers: servers });\n pc = rtc;\n dc = rtc.createDataChannel(\"input-v1\");\n rtc.addTransceiver(\"video\", { direction: \"recvonly\" });\n rtc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n rtc.onicecandidate = ({ candidate }) => {\n if (g !== generation || !candidate?.candidate || !trickleIce) return;\n if (localCandidates.length >= net.maxCandidates) {\n failRtc(\"candidate-limit\", false);\n return;\n }\n localCandidates.push({\n candidate: candidate.candidate,\n sdpMid: candidate.sdpMid,\n sdpMLineIndex: candidate.sdpMLineIndex,\n ...(candidate.usernameFragment\n ? { usernameFragment: candidate.usernameFragment }\n : {}),\n });\n // Gathering continues after the offer; the serial exchange flushes late addresses.\n };\n dc.onmessage = (e) => {\n try {\n if (g !== generation || pc !== rtc) return;\n if (typeof e.data !== \"string\" || e.data.length > 80000) return;\n const message = JSON.parse(e.data);\n if (message.type === \"cursor\") receiveCursor(message.cursor);\n if (\n (video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video) &&\n message.type === \"viewPing\" &&\n typeof message.challenge === \"string\" &&\n message.challenge.length <= 64 &&\n dc?.readyState === \"open\"\n )\n dc.send(message.challenge);\n } catch {}\n };\n let readingStats = false;\n statsTimer = setInterval(async () => {\n if (readingStats || g !== generation) return;\n readingStats = true;\n try {\n const stats = await rtc.getStats();\n if (g !== generation || pc !== rtc) return;\n const result = networkStats(stats, statsSample);\n statsSample = result.sample;\n post({\n type: \"network\",\n transport: result.transport,\n bytesPerSecond: result.bytesPerSecond,\n latencyMs: result.latencyMs,\n });\n } catch {\n } finally {\n readingStats = false;\n }\n }, 1000);\n rtc.ontrack = (e) => {\n if (g !== generation) return;\n video.srcObject = e.streams[0] || new MediaStream([e.track]);\n video.play().catch(() => {});\n };\n video.onplaying = () => {\n if (\n g !== generation ||\n videoPresented ||\n videoFrameCallback !== null ||\n videoPaintCallback !== null\n )\n return;\n video.style.display = \"block\";\n render();\n if (typeof scheduleBackgroundDraw === \"function\")\n scheduleBackgroundDraw();\n if (typeof video.requestVideoFrameCallback === \"function\") {\n videoFrameCallback = video.requestVideoFrameCallback(() => {\n if (g !== generation) return;\n videoFrameCallback = null;\n revealVideo(g);\n });\n } else waitForVideoFrame(g);\n };\n rtc.onconnectionstatechange = () => {\n if (g !== generation) return;\n if ([\"failed\", \"closed\"].includes(rtc.connectionState)) {\n failRtc(\"transport\");\n return;\n }\n if (rtc.connectionState === \"disconnected\") {\n clearTimeout(stableTimer);\n stableTimer = null;\n if (!disconnectTimer) {\n release();\n post({ type: \"reconnecting\", attemptId });\n disconnectTimer = setTimeout(() => {\n if (g === generation) failRtc(\"disconnected\");\n }, net.disconnectedMs);\n }\n } else if (rtc.connectionState === \"connected\") {\n clearTimeout(disconnectTimer);\n disconnectTimer = null;\n clearTimeout(deadlineTimer);\n if (!stableTimer)\n stableTimer = setTimeout(() => {\n if (g === generation) retries = 0;\n }, net.stableMs);\n if (videoPresented) post({ type: \"streaming\", attemptId });\n }\n };\n await rtc.setLocalDescription(await rtc.createOffer());\n if (!trickleIce)\n await new Promise((resolve) => {\n if (rtc.iceGatheringState === \"complete\") return resolve();\n gatherDone = resolve;\n gatherTimer = setTimeout(resolve, net.legacyGatherMs);\n rtc.onicegatheringstatechange = () => {\n if (rtc.iceGatheringState === \"complete\") {\n clearTimeout(gatherTimer);\n resolve();\n }\n };\n });\n if (g !== generation) return;\n post({ type: \"offer\", attemptId, sdp: rtc.localDescription.sdp });\n deadlineTimer = setTimeout(() => {\n if (g === generation) failRtc(\"answer-timeout\");\n }, net.answerMs);\n } catch {\n if (g === generation) failRtc(\"setup\");\n }\n }\n\n /* END RTC */\n function reportPresentation() {\n post({\n type: \"presentation\",\n active:\n video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video,\n });\n }\n listen(video, \"webkitpresentationmodechanged\", reportPresentation);\n listen(video, \"enterpictureinpicture\", reportPresentation);\n listen(video, \"leavepictureinpicture\", reportPresentation);\n function receive(event) {\n let message;\n try {\n message = JSON.parse(event.data);\n } catch {\n return;\n }\n switch (message.type) {\n case \"measureViewport\":\n post({\n type: \"viewportSize\",\n width: viewportWidth(),\n height: usableHeight(),\n });\n break;\n case \"presentation\":\n try {\n if (message.enabled) {\n release();\n showKeyboard(false);\n if (video.webkitSupportsPresentationMode?.(\"picture-in-picture\"))\n video.webkitSetPresentationMode(\"picture-in-picture\");\n else if (video.requestPictureInPicture)\n video\n .requestPictureInPicture()\n .catch(() => post({ type: \"presentationFailed\" }));\n else post({ type: \"presentationFailed\" });\n } else if (video.webkitSetPresentationMode)\n video.webkitSetPresentationMode(\"inline\");\n else if (document.pictureInPictureElement)\n document.exitPictureInPicture().catch(() => {});\n } catch {\n post({ type: \"presentationFailed\" });\n }\n break;\n case \"videoSettings\":\n if (\n Number.isInteger(message.width) &&\n Number.isInteger(message.height) &&\n message.width >= 320 &&\n message.height >= 320 &&\n (message.restore === true ||\n (message.width <= 2560 && message.height <= 2560))\n ) {\n release();\n stopPanAnimation();\n viewerSized = message.restore !== true;\n zoom = 1;\n fx = fy = 0.5;\n followRest = null;\n dw = message.width;\n dh = message.height;\n render();\n }\n video.muted = !message.audio;\n retries = 0;\n connect();\n break;\n case \"keyboard\":\n showKeyboard(message.enabled === true);\n break;\n case \"resume\":\n if (video.srcObject) video.play().catch(() => {});\n break;\n case \"releaseInput\":\n release();\n break;\n case \"theme\":\n if (/^#[0-9a-f]{3,8}$/i.test(message.surface)) {\n document.body.style.background = message.surface;\n document.documentElement.style.background = message.surface;\n document.documentElement.style.setProperty(\n \"--surface\",\n message.surface,\n );\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.foreground)) {\n cursor.style.borderColor = message.foreground;\n document.documentElement.style.setProperty(\n \"--foreground\",\n message.foreground,\n );\n }\n break;\n case \"networkStatus\": {\n const status = document.getElementById(\"network-status\");\n if (!status) break;\n status.textContent =\n typeof message.text === \"string\" ? message.text : \"\";\n status.style.display = status.textContent ? \"block\" : \"none\";\n for (const key of [\"top\", \"right\", \"fontSize\"]) {\n if (Number.isFinite(message[key]) && message[key] >= 0)\n status.style[key] = message[key] + \"px\";\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.color))\n status.style.color = message.color;\n break;\n }\n case \"nativeMouse\": {\n if (\n !nativeMouseControls ||\n ![\"left\", \"right\", \"wheel\"].includes(message.control)\n )\n break;\n if (\n ![\n \"pointerdown\",\n \"pointermove\",\n \"pointerup\",\n \"pointercancel\",\n \"click\",\n ].includes(message.event)\n )\n break;\n if (!Number.isFinite(message.id) || !Number.isFinite(message.y)) break;\n mouseControlHandlers.get(\n \"mouse-\" + message.control + \":\" + message.event,\n )?.({\n pointerId: message.id,\n clientY: message.y,\n detail: 0,\n nativeInput: true,\n preventDefault() {},\n });\n break;\n }\n case \"mouseButtons\": {\n nativeMouseControls = message.native === true;\n const before = layout(),\n 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 viewerSized = false;\n followRest = null;\n cursorNeedsEntry = true;\n stopPanAnimation();\n resetCursor();\n control = false;\n release();\n pending = [];\n sending = false;\n seq = 0;\n epoch = message.epoch;\n clipboardShortcuts =\n config.desktop && message.clipboardShortcuts === true;\n clipboardModifier =\n message.clipboardModifier === \"meta\" ? \"meta\" : \"control\";\n dw = message.width;\n dh = message.height;\n fillHeight = message.fillHeight === true;\n video.muted = !message.audio;\n trickleIce = message.trickleIce === true;\n retries = 0;\n render();\n connect();\n break;\n case \"viewport\":\n fillHeight = message.fillHeight === true;\n release();\n render();\n break;\n case \"answer\":\n if (message.epoch === epoch) void receiveAnswer(message);\n break;\n case \"iceConfig\":\n if (message.epoch === epoch) void receiveIceConfig(message);\n break;\n case \"ice\":\n if (message.epoch === epoch) void receiveIce(message);\n break;\n case \"fallback\":\n if (message.epoch === epoch && message.attemptId === attemptId)\n failRtc(\"host\", message.retry !== false);\n break;\n case \"frame\": {\n if (\"cursor\" in message) receiveCursor(message.cursor);\n else resetCursor();\n const frameEpoch = epoch;\n image.onload = () => {\n if (epoch === frameEpoch) {\n scheduleBackgroundDraw();\n post({ type: \"framePresented\" });\n }\n };\n image.src = \"data:image/jpeg;base64,\" + message.jpeg;\n break;\n }\n case \"control\":\n release();\n control = message.enabled;\n if (!control) showKeyboard(false);\n pending = [];\n updateMouseButtons();\n render();\n break;\n case \"mode\":\n release();\n if (message.mode !== \"pointer\") followRest = null;\n settlePan();\n clearTimeout(touchCursorTimer);\n touchCursorVisible = false;\n mode = message.mode;\n render();\n break;\n case \"fit\":\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = false;\n stopPanAnimation();\n zoom = 1;\n fx = 0.5;\n fy = 0.5;\n render();\n break;\n case \"rightClick\":\n click(2);\n break;\n case \"events\":\n for (const e of message.events) queue(e);\n flush();\n break;\n case \"ack\":\n if (message.epoch === epoch && message.sequence === seq)\n sending = false;\n break;\n case \"stop\":\n showKeyboard(false);\n control = false;\n release();\n pending = [];\n sending = false;\n epoch = null;\n closeRtc(message.preserveFrame === true);\n updateMouseButtons();\n render();\n break;\n }\n }\n // iOS can report equal left/right safe areas in both landscape directions.\n // Its interface angle distinguishes the notch side even on a 180-degree turn.\n const reportOrientation = () => {\n const angle =\n typeof window.orientation === \"number\"\n ? window.orientation\n : window.screen?.orientation?.angle;\n if (Number.isFinite(angle)) post({ type: \"orientation\", angle });\n };\n listen(window, \"orientationchange\", reportOrientation);\n if (window.screen?.orientation?.addEventListener)\n listen(window.screen.orientation, \"change\", reportOrientation);\n render();\n reportOrientation();\n post({ type: \"ready\" });\n return {\n receive: (message) => receive({ data: JSON.stringify(message) }),\n dispose: () => {\n release();\n epoch = null;\n closeRtc(false);\n if (bgDrawFrame !== null) cancelAnimationFrame(bgDrawFrame);\n bgDrawFrame = null;\n for (const cleanup of cleanups) cleanup();\n },\n };\n}\n";
+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 bgContext.setTransform(bgDpr, 0, 0, bgDpr, 0, 0);\n bgContext.clearRect(0, 0, stage.clientWidth, stage.clientHeight);\n const useVideo =\n videoPresented && video.videoWidth > 0 && video.videoHeight > 0;\n const src = useVideo ? video : image;\n // drawImage source rects live in the source's own pixel space, which can\n // differ from dw/dh; fractions of the real bitmap keep every segment lined\n // up with what the picture element actually shows.\n const sw = useVideo ? video.videoWidth : image.naturalWidth;\n const sh = useVideo ? video.videoHeight : image.naturalHeight;\n if (!(sw > 0 && sh > 0)) return;\n const horizontal = bgAxis === \"x\";\n const sourceLength = horizontal ? sw : sh;\n const cuts = [0, bgEdgeFraction, 1 - bgEdgeFraction, 1];\n for (let i = 0; i < bgRects.length; i++) {\n const rect = bgRects[i];\n const origin = cuts[i] * sourceLength;\n const length = (cuts[i + 1] - cuts[i]) * sourceLength;\n bgContext.drawImage(\n src,\n horizontal ? origin : 0,\n horizontal ? 0 : origin,\n horizontal ? length : sw,\n horizontal ? sh : length,\n rect.x,\n rect.y,\n rect.w,\n rect.h,\n );\n }\n }\n function scheduleBackgroundDraw() {\n if (bgDrawFrame !== null || !bgRects || !bgContext) return;\n bgDrawFrame = requestAnimationFrame(() => {\n bgDrawFrame = null;\n drawBackground();\n });\n }\n function startBackgroundLoop() {\n if (\n bgLoopFrame !== null ||\n !bgContext ||\n !bgRects ||\n !videoPresented ||\n typeof video.requestVideoFrameCallback !== \"function\"\n )\n return;\n const frame = video.requestVideoFrameCallback(() => {\n if (bgLoopFrame !== frame) return;\n bgLoopFrame = null;\n drawBackground();\n startBackgroundLoop();\n });\n bgLoopFrame = frame;\n }\n // Only the streaming loop stops here; a pending one-shot draw is harmless\n // (it re-paints the preserved frame) and must survive reconnects.\n function stopBackgroundLoop() {\n if (bgLoopFrame !== null) video.cancelVideoFrameCallback?.(bgLoopFrame);\n bgLoopFrame = null;\n }\n function clearBackground() {\n stopBackgroundLoop();\n bgRects = null;\n // Resizing a canvas resets its bitmap; same-value assignment still clears.\n if (bgCanvas) bgCanvas.width = bgCanvas.width;\n }\n listen(image, \"load\", () => scheduleBackgroundDraw());\n // Older WebViews update the ambient layer on media progress, never with an\n // idle display-refresh loop. Geometry changes still get a one-shot repaint.\n listen(video, \"timeupdate\", () => {\n if (videoPresented && typeof video.requestVideoFrameCallback !== \"function\")\n scheduleBackgroundDraw();\n });\n function panBounds(r) {\n const vw = viewportWidth(),\n vh = viewportHeight();\n // Grow extra resting travel continuously from zero at fit to 180 screen\n // points at maximum zoom. Never count the unused space of a fitting axis.\n const clearance = (180 * (Math.max(1, Math.min(5, zoom)) - 1)) / 4;\n const axis = (viewport, content) =>\n content <= viewport\n ? {\n min: (viewport - content) / 2 - clearance,\n max: (viewport - content) / 2 + clearance,\n }\n : { min: viewport - content - clearance, max: clearance };\n const x = axis(vw, r.width),\n y = axis(vh, r.height);\n const bounds = {\n minX: viewportLeft() + x.min,\n maxX: viewportLeft() + x.max,\n minY: y.min + verticalOffset(r.height),\n maxY: y.max + verticalOffset(r.height),\n };\n // A camera position required to expose the cursor is a valid resting point,\n // not elastic overshoot. Preserve it across the next pan/pinch handoff.\n if (followRest) {\n const restX = viewportLeft() + vw / 2 - followRest.fx * r.width,\n restY = vh / 2 + verticalOffset(r.height) - followRest.fy * r.height;\n const weight =\n followRest.zoom > 1 ? clamp((zoom - 1) / (followRest.zoom - 1)) : 1;\n bounds.minX += Math.min(0, restX - bounds.minX) * weight;\n bounds.maxX += Math.max(0, restX - bounds.maxX) * weight;\n bounds.minY += Math.min(0, restY - bounds.minY) * weight;\n bounds.maxY += Math.max(0, restY - bounds.maxY) * weight;\n }\n return bounds;\n }\n const bounded = (v, min, max) => Math.max(min, Math.min(max, v));\n // Convert displayed overshoot back to finger travel before the next delta,\n // so reversing direction unwinds smoothly without an edge jump.\n function rubber(v, min, max, inverse = false) {\n const edge = bounded(v, min, max),\n d = v - edge;\n const reach = 40 + 10 * (Math.max(1, Math.min(5, zoom)) - 1);\n return (\n edge +\n Math.sign(d) *\n (inverse\n ? (reach * Math.abs(d)) / Math.max(1, reach - Math.abs(d))\n : (reach * Math.abs(d)) / (reach + Math.abs(d)))\n );\n }\n function place(x, y, r) {\n fx = (viewportLeft() + viewportWidth() / 2 - x) / r.width;\n fy = (viewportHeight() / 2 + verticalOffset(r.height) - y) / r.height;\n }\n function cursorViewport() {\n const hotX = remoteCursor?.hotX ?? 9,\n hotY = remoteCursor?.hotY ?? 9;\n const w = remoteCursor?.width ?? 18,\n h = remoteCursor?.height ?? 18;\n const left = viewportLeft(),\n right = left + viewportWidth(),\n bottom = Math.max(1, stage.clientHeight - viewportBottomInset);\n // Keep the entire cursor, including its hotspot offset, clear of chrome.\n const minX = Math.min(right - 1, left + 8 + hotX),\n minY = Math.min(\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 if (canRetry && epoch && retries < net.retryMs.length) {\n const delay = net.retryMs[retries++];\n retryTimer = setTimeout(() => {\n retryTimer = null;\n if (epoch) connect();\n }, delay);\n }\n }\n function pollIce() {\n if (\n !pc ||\n !trickleIce ||\n !pc.remoteDescription ||\n icePending ||\n Date.now() >= exchangeUntil\n )\n return;\n const candidates = localCandidates.slice(\n localAck,\n localAck + net.batchSize,\n );\n icePending = {\n after: remoteAfter,\n sent: candidates.length,\n exchangeId: ++exchangeId,\n };\n post({\n type: \"ice\",\n attemptId,\n candidates,\n after: remoteAfter,\n exchangeId,\n });\n iceTimer = setTimeout(() => {\n icePending = null;\n pollIce();\n }, 4500);\n }\n async function receiveIce(message) {\n if (\n !pc ||\n !icePending ||\n message.attemptId !== attemptId ||\n message.exchangeId !== icePending.exchangeId\n )\n return;\n const rtc = pc,\n g = generation,\n batch = icePending;\n clearTimeout(iceTimer);\n try {\n if (message.error) {\n icePending = null;\n iceTimer = setTimeout(pollIce, 1000);\n return;\n }\n if (\n !Array.isArray(message.candidates) ||\n message.candidates.length > net.batchSize ||\n message.next !== batch.after + message.candidates.length ||\n message.next > net.maxCandidates\n )\n throw new Error();\n for (const candidate of message.candidates) {\n if (g !== generation) return;\n const key = JSON.stringify(candidate);\n if (remoteSeen.has(key)) continue;\n if (remoteSeen.size >= net.maxCandidates) throw new Error();\n await rtc.addIceCandidate(candidate);\n if (g !== generation) return;\n remoteSeen.add(key);\n }\n if (g !== generation) return;\n localAck += batch.sent;\n remoteAfter = message.next;\n remoteComplete = message.complete === true;\n icePending = null;\n if (!(\n remoteComplete &&\n rtc.iceGatheringState === \"complete\" &&\n localAck === localCandidates.length\n ))\n iceTimer = setTimeout(pollIce, net.pollMs);\n } catch {\n if (g === generation) failRtc(\"candidates\");\n }\n }\n async function receiveAnswer(message) {\n if (!pc || message.attemptId !== attemptId) return;\n const rtc = pc,\n g = generation;\n try {\n await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n if (g !== generation) return;\n clearTimeout(deadlineTimer);\n deadlineTimer = setTimeout(() => {\n if (g === generation && rtc.connectionState !== \"connected\")\n failRtc(\"connect-timeout\");\n }, net.connectMs);\n exchangeUntil = Date.now() + net.exchangeMs;\n pollIce();\n } catch {\n if (g === generation) failRtc(\"answer\");\n }\n }\n async function connect() {\n closeRtc();\n const g = generation;\n attemptId = String(g);\n if (!window.RTCPeerConnection) {\n failRtc(\"unsupported\", false);\n return;\n }\n configPending = true;\n deadlineTimer = setTimeout(() => {\n if (g === generation && configPending) {\n configPending = false;\n void startRtc(g, iceServers);\n }\n }, 3500);\n return post({ type: \"iceConfig\", attemptId });\n }\n async function receiveIceConfig(message) {\n if (!epoch || !configPending || message.attemptId !== attemptId) return;\n configPending = false;\n clearTimeout(deadlineTimer);\n deadlineTimer = null;\n await startRtc(generation, message.iceServers);\n }\n async function startRtc(g, servers) {\n try {\n const rtc = new RTCPeerConnection({ iceServers: servers });\n pc = rtc;\n dc = rtc.createDataChannel(\"input-v1\");\n rtc.addTransceiver(\"video\", { direction: \"recvonly\" });\n rtc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n rtc.onicecandidate = ({ candidate }) => {\n if (g !== generation || !candidate?.candidate || !trickleIce) return;\n if (localCandidates.length >= net.maxCandidates) {\n failRtc(\"candidate-limit\", false);\n return;\n }\n localCandidates.push({\n candidate: candidate.candidate,\n sdpMid: candidate.sdpMid,\n sdpMLineIndex: candidate.sdpMLineIndex,\n ...(candidate.usernameFragment\n ? { usernameFragment: candidate.usernameFragment }\n : {}),\n });\n // Gathering continues after the offer; the serial exchange flushes late addresses.\n };\n dc.onmessage = (e) => {\n try {\n if (g !== generation || pc !== rtc) return;\n if (typeof e.data !== \"string\" || e.data.length > 80000) return;\n const message = JSON.parse(e.data);\n if (message.type === \"cursor\") receiveCursor(message.cursor);\n if (\n (video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video) &&\n message.type === \"viewPing\" &&\n typeof message.challenge === \"string\" &&\n message.challenge.length <= 64 &&\n dc?.readyState === \"open\"\n )\n dc.send(message.challenge);\n } catch {}\n };\n let readingStats = false;\n statsTimer = setInterval(async () => {\n if (readingStats || g !== generation) return;\n readingStats = true;\n try {\n const stats = await rtc.getStats();\n if (g !== generation || pc !== rtc) return;\n const result = networkStats(stats, statsSample);\n statsSample = result.sample;\n post({\n type: \"network\",\n transport: result.transport,\n bytesPerSecond: result.bytesPerSecond,\n latencyMs: result.latencyMs,\n });\n } catch {\n } finally {\n readingStats = false;\n }\n }, 1000);\n rtc.ontrack = (e) => {\n if (g !== generation) return;\n video.srcObject = e.streams[0] || new MediaStream([e.track]);\n video.play().catch(() => {});\n };\n video.onplaying = () => {\n if (\n g !== generation ||\n videoPresented ||\n videoFrameCallback !== null ||\n videoPaintCallback !== null\n )\n return;\n video.style.display = \"block\";\n render();\n if (typeof scheduleBackgroundDraw === \"function\")\n scheduleBackgroundDraw();\n if (typeof video.requestVideoFrameCallback === \"function\") {\n videoFrameCallback = video.requestVideoFrameCallback(() => {\n if (g !== generation) return;\n videoFrameCallback = null;\n revealVideo(g);\n });\n } else waitForVideoFrame(g);\n };\n rtc.onconnectionstatechange = () => {\n if (g !== generation) return;\n if ([\"failed\", \"closed\"].includes(rtc.connectionState)) {\n failRtc(\"transport\");\n return;\n }\n if (rtc.connectionState === \"disconnected\") {\n clearTimeout(stableTimer);\n stableTimer = null;\n if (!disconnectTimer) {\n release();\n post({ type: \"reconnecting\", attemptId });\n disconnectTimer = setTimeout(() => {\n if (g === generation) failRtc(\"disconnected\");\n }, net.disconnectedMs);\n }\n } else if (rtc.connectionState === \"connected\") {\n clearTimeout(disconnectTimer);\n disconnectTimer = null;\n clearTimeout(deadlineTimer);\n if (!stableTimer)\n stableTimer = setTimeout(() => {\n if (g === generation) retries = 0;\n }, net.stableMs);\n if (videoPresented) post({ type: \"streaming\", attemptId });\n }\n };\n await rtc.setLocalDescription(await rtc.createOffer());\n if (!trickleIce)\n await new Promise((resolve) => {\n if (rtc.iceGatheringState === \"complete\") return resolve();\n gatherDone = resolve;\n gatherTimer = setTimeout(resolve, net.legacyGatherMs);\n rtc.onicegatheringstatechange = () => {\n if (rtc.iceGatheringState === \"complete\") {\n clearTimeout(gatherTimer);\n resolve();\n }\n };\n });\n if (g !== generation) return;\n post({ type: \"offer\", attemptId, sdp: rtc.localDescription.sdp });\n deadlineTimer = setTimeout(() => {\n if (g === generation) failRtc(\"answer-timeout\");\n }, net.answerMs);\n } catch {\n if (g === generation) failRtc(\"setup\");\n }\n }\n\n /* END RTC */\n function reportPresentation() {\n post({\n type: \"presentation\",\n active:\n video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video,\n });\n }\n listen(video, \"webkitpresentationmodechanged\", reportPresentation);\n listen(video, \"enterpictureinpicture\", reportPresentation);\n listen(video, \"leavepictureinpicture\", reportPresentation);\n function receive(event) {\n let message;\n try {\n message = JSON.parse(event.data);\n } catch {\n return;\n }\n switch (message.type) {\n case \"measureViewport\":\n post({\n type: \"viewportSize\",\n width: viewportWidth(),\n height: 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(\"host\", message.retry !== false);\n break;\n case \"frame\": {\n if (\"cursor\" in message) receiveCursor(message.cursor);\n else resetCursor();\n const frameEpoch = epoch;\n image.onload = () => {\n if (epoch === frameEpoch) {\n scheduleBackgroundDraw();\n post({ type: \"framePresented\" });\n }\n };\n image.src = \"data:image/jpeg;base64,\" + message.jpeg;\n break;\n }\n case \"control\":\n release();\n control = message.enabled;\n if (!control) showKeyboard(false);\n pending = [];\n updateMouseButtons();\n render();\n break;\n case \"mode\":\n release();\n if (message.mode !== \"pointer\") followRest = null;\n settlePan();\n clearTimeout(touchCursorTimer);\n touchCursorVisible = false;\n mode = message.mode;\n render();\n break;\n case \"fit\":\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = false;\n stopPanAnimation();\n zoom = 1;\n fx = 0.5;\n fy = 0.5;\n render();\n break;\n case \"rightClick\":\n click(2);\n break;\n case \"events\":\n for (const e of message.events) queue(e);\n flush();\n break;\n case \"ack\":\n if (message.epoch === epoch && message.sequence === seq)\n sending = false;\n break;\n case \"stop\":\n 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";
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1b5283e3ed..cc8351afbe 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -610,13 +610,13 @@ importers:
version: link:../../packages/voice-input-core
'@expo/dom-webview':
specifier: ~57.0.1
'@expo/metro-runtime':
specifier: ^57.0.14
'@expo/ui':
specifier: ~57.0.14
'@legendapp/list':
specifier: ^3.3.3
@@ -628,7 +628,7 @@ importers:
'@react-native-google-signin/google-signin':
specifier: 16.1.2
'@react-native-menu/menu':
specifier: ^2.0.0
@@ -636,92 +636,92 @@ importers:
specifier: ^2.0.4
version: 2.0.4
expo:
- specifier: ~57.0.17
+ specifier: ~57.0.23
expo-apple-authentication:
specifier: ~57.0.1
expo-audio:
specifier: ^57.0.4
expo-auth-session:
specifier: ^57.0.10
expo-blur:
specifier: ~57.0.2
expo-build-properties:
- specifier: ~57.0.15
- version: 57.0.15([email protected])
+ specifier: ~57.0.20
+ version: 57.0.20([email protected])
expo-clipboard:
specifier: ^57.0.1
expo-constants:
specifier: ^57.0.15
expo-crypto:
specifier: ^57.0.2
- version: 57.0.2([email protected])
+ version: 57.0.2([email protected])
expo-document-picker:
specifier: ~57.0.1
- version: 57.0.1([email protected])
+ version: 57.0.1([email protected])
expo-file-system:
specifier: ^57.0.6
expo-font:
specifier: ~57.0.1
expo-glass-effect:
specifier: ~57.0.1
expo-image:
specifier: ~57.0.3
expo-image-manipulator:
specifier: ~57.0.14
- version: 57.0.14(patch_hash=78594ca2235bdbbee2665f37b86d4e1e892733c4f9bd38fa7085338b90486e2b)([email protected])
+ version: 57.0.14(patch_hash=78594ca2235bdbbee2665f37b86d4e1e892733c4f9bd38fa7085338b90486e2b)([email protected])
expo-image-picker:
specifier: ^57.0.14
- version: 57.0.14([email protected])
+ version: 57.0.14([email protected])
expo-linking:
specifier: ^57.0.8
expo-localization:
specifier: ~57.0.1
expo-media-library:
specifier: ~57.0.4
expo-network:
specifier: ~57.0.1
expo-notifications:
specifier: ~57.0.15
expo-paste-input:
specifier: 0.2.2
- version: 0.2.2(patch_hash=53be555646735a171c1624f074ef30e5ca897a7b8893724bc2d0d51682f769d8)([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ version: 0.2.2(patch_hash=53be555646735a171c1624f074ef30e5ca897a7b8893724bc2d0d51682f769d8)([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-router:
specifier: ^57.0.17
- version: 57.0.17(2378d4467649e87a2be422b81281c63c)
+ version: 57.0.17(e2df021366f5afb705d6bf2fb591ffad)
expo-secure-store:
specifier: ^57.0.2
- version: 57.0.2([email protected])
+ version: 57.0.2([email protected])
expo-sharing:
specifier: ~57.0.16
expo-splash-screen:
specifier: ~57.0.8
expo-status-bar:
specifier: ~57.0.1
expo-updates:
specifier: ~57.0.18
expo-web-browser:
specifier: ^57.0.2
i18next:
specifier: ^26.3.6
version: 26.3.6([email protected])
@@ -775,7 +775,7 @@ importers:
version: file:apps/mobile/modules/xdt-ios-action-sheet
xdt-ios-app-distribution:
specifier: file:./modules/xdt-ios-app-distribution
xdt-mobile-realtime-audio:
specifier: file:./modules/xdt-mobile-realtime-audio
version: file:apps/mobile/modules/xdt-mobile-realtime-audio
@@ -784,10 +784,10 @@ importers:
version: file:apps/mobile/modules/xdt-screenshot-monitor
xdt-tapdb:
specifier: file:./modules/xdt-tapdb
xdt-wechat-login:
specifier: file:./modules/xdt-wechat-login
devDependencies:
'@types/react':
specifier: ~19.2.0
@@ -2775,8 +2775,8 @@ packages:
'@expo-google-fonts/[email protected]':
resolution: {integrity: sha512-UehORuVy7riqirvjLumVzmVvh6qGTJ2ndP2y4/y0uiSDNBA3kpILNGvvOo26qd56bECjHu1nn5Q9at6O5PjyDA==}
- resolution: {integrity: sha512-HcvVmm0FNL1P3Lf23z1L/sLZtdcWfKW8P5L/doQbICWVG/PL7uI5+G2Ttxnj9QGNmpYgJ89E7+LJefS5jJMUlQ==}
+ resolution: {integrity: sha512-G2FJfwClIPNPhH2sJlIFAkhQLYaKNGzSarIQUl6sVA8oGdrmBnhRvbtTzxDzjS6WzO2aDX8DY7y1aNbCFILodg==}
hasBin: true
peerDependencies:
expo: '*'
@@ -2825,11 +2825,15 @@ packages:
resolution: {integrity: sha512-28pqaEqwnmLduZ00Pq9HkSzE5wbj1MTwp5/n8nm8rD8MCjR9eUnVOwmNksPI3Be2ReAPO/DbPn1puy0mvoocsQ==}
engines: {node: '>=20.12.0'}
+ resolution: {integrity: sha512-M1NXeZCA1mkMkYOyIe7PlyRX0/jqFtMoJgyblnlq/vpCRfmueFT7RnGSQG8uEFDF5WHOFGijAQ3fogPh3/n5Ng==}
+ engines: {node: '>=20.12.0'}
+
resolution: {integrity: sha512-cpsLZE4rqkc1Y3eZTkxB98jrqY1YXgetmtxFt8q89jBRmk3quRuk1BZo+VcnCSObZardjg99r1k5xijEMONFGA==}
- resolution: {integrity: sha512-Ox/smKlpPpyTUwZAXS927xuJ8qICwNxHOtZElv0anp6xJ80FzwkfvCdC/NjCxlALS2Hp3IsmwyKd975gYgW12Q==}
+ resolution: {integrity: sha512-h1x+w+JpNRu88a/5SMZRzJs9YDGR/f7R8ApCr7OdenhqmJ00hFxQMzvxajDLL+1P2Y2g/ND0xksusqvBqWSW5Q==}
hasBin: true
@@ -2852,16 +2856,16 @@ packages:
react: '*'
react-native: '*'
- resolution: {integrity: sha512-aIKcCAQALafeIf+HOoHgjj7hOb771VQRFZARDjm+GJRT74Lb3bYHjkATtS4Wv2zqVx/aFYkNqYNqPF/Py3kSlw==}
+ resolution: {integrity: sha512-S62Lrq35HZqBFD55423pmWb8PjaiR/W02zQC1uECBmw1vTN8WZaFz4TJ0i21EeJzwfebMb9MLxL8JZ102Z6VbA==}
peerDependencies:
expo: '*'
peerDependenciesMeta:
expo:
optional: true
- resolution: {integrity: sha512-tb50nSIWwKpRufSkGuivOK0FbUxv1Uwqptb0SzFTk0bkmYmcy3gIwnCbOHTfmrQDVndRhPEiu2SYgh9Z0PCvGg==}
+ resolution: {integrity: sha512-1OXy+uPYY5uc7Tm4VBsd2NRn+3wHhqeqNuEO/Xo4kmYgv8FjYgUAc+bUXON9FpC2ikcLn4EVlGM9ce2exx9Mlg==}
resolution: {integrity: sha512-LVpsfF0QOzlLSKlHYpxgW1cP1NKcYeaoalLO18jYHgqseSveEkb9VOffFpicTQ7AN03odZ4fgkUF+p5YpoY4yw==}
@@ -2888,8 +2892,8 @@ packages:
resolution: {integrity: sha512-3gTReGIUm0oRaMClsAJYxBnVPCl6fVpsl8HS+DTVxDhW4GyVyxg9E/Znm3BvcHtUJ51RJJI14pC1wvrNilCRHw==}
- resolution: {integrity: sha512-xTbWHroj0PDmlbqvmU+zF9ZZxveJkiuyiPoeRJYRGruFHebRAWnoTdw5S7d/UCzDBI8ropGGu9g2eb2nMxtvAw==}
+ resolution: {integrity: sha512-QA8oMZ7y70kjOzw+abhRl9uYC8Nu/abeUTHr0YVxb3pgIC14gc7w543bYtI+5gEDI3q55jKUViIauC76QvZN1w==}
resolution: {integrity: sha512-kTAXj9lDFEIPMsbAOGCGbjBbMF0oi7CqkYM79KOX0DDD9wSwXmlKL1z2h8OwsrBf7mbOo2DjlRvZu4BEjrIxGw==}
@@ -2899,13 +2903,13 @@ packages:
typescript:
optional: true
- resolution: {integrity: sha512-lEPGYoDmh97yyEcY/MFWQsfE7yIgMRnGDcnsBN7B6AiWBFSJIMEcGnO0aYPgY0ZjNWyJDi7Ee8QZRGqB+LhI6w==}
+ resolution: {integrity: sha512-8rGh6N5di7jzu7UC1SuIA1TWmVd+vBwOHwC7/1ww+FA6CcxcWyQlcPl39h2+Jpnul78CVzWpIjOcdKsZsp2zXw==}
peerDependencies:
- '@expo/metro-runtime': ^57.0.14
+ '@expo/metro-runtime': ^57.0.15
expo: '*'
- expo-constants: ^57.0.15
- expo-font: ^57.0.1
+ expo-constants: ^57.0.18
+ expo-font: ^57.0.4
expo-router: '*'
expo-server: ^57.0.3
react: '*'
@@ -5322,8 +5326,8 @@ packages:
resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}
engines: {node: '>= 14'}
- resolution: {integrity: sha512-vKrPeEVN3upDF3GjWxsWBbwQgMtNJ8VB1cduPvK3svmmz4ENpS7yaPxbogsbe3w+xp9xp2Cu+0Ar41rjAR4+lA==}
+ resolution: {integrity: sha512-d8OWDVdZMgjhLUT9ZPgSv/BdFFF9pVuscC0JdUSz3bjwE15gcp6u/o0/JooM2yyAWC49KThFhXlgTXRa9B7yng==}
engines: {node: '>=18.18'}
hasBin: true
@@ -5549,12 +5553,12 @@ packages:
resolution: {integrity: sha512-g4aaCrDDOsWjbm0PUUeVnkcVd6AKJsVc/MbnPhEotEpkeJQP6b8nzewohQi7+QS8UyPehOhGWn0nOwjvWpmMvQ==}
- resolution: {integrity: sha512-T19biGOBTnMp161PyBqWOoSIEeZug8/EjtuUdVob8JPQKZMTalHUQaQt+qtQQE7XsEkZJ6erb3k0CohneTFzQg==}
+ resolution: {integrity: sha512-rrZqJPYbVevy7rqibJZQFd3AsleGslJ63vmB3Qs8b5poOO5AHaehUGbZHjb0HoOZO59d86BEifYbq0/ncoM2UQ==}
peerDependencies:
'@babel/runtime': ^7.20.0
expo: '*'
- expo-widgets: ^57.0.13
+ expo-widgets: ^57.0.19
react-refresh: '>=0.14.0 <1.0.0'
peerDependenciesMeta:
'@babel/runtime':
@@ -6896,8 +6900,8 @@ packages:
peerDependencies:
expo: '*'
- resolution: {integrity: sha512-ZoiUftQb1Nn1jvL6l1kZoUXvgRCx57tMQYxSsp+g4ZvY+jgVWp/THruXOtPtZVdC/WWZxPUTct53bfAm2EPDAQ==}
+ resolution: {integrity: sha512-qSdWZBSfEg06o3GJMwcj36tw0vXkB6eYjqkQistWmyJkHxhUOKnsKJnev6OraXxLdoI+KOd1+qgp/ENx8gcqYA==}
peerDependencies:
expo: '*'
react: '*'
@@ -6924,8 +6928,8 @@ packages:
react: '*'
react-native: '*'
- resolution: {integrity: sha512-qZe9pnxlBpHT7SSNDR2a3C+P34xv67Ep9I0Erh+3xCczGlokyRd4pu9h0PrBdsVlr1d0QREQ1Do/+IgrIWkQQA==}
+ resolution: {integrity: sha512-rQ3Xt5slDXJQL+vevO1AsYAiCQsIq8c8bz1JfSK/UstPr3Md8fypaS/wcp6f67yZu4CzQSuPFC0hR46raHLTzg==}
peerDependencies:
expo: '*'
@@ -6942,6 +6946,12 @@ packages:
expo: '*'
react-native: '*'
+ resolution: {integrity: sha512-cLDwDOniPfuCZPHNY++cAY2ZkK97u5aobbBvilPK2LLmaWxR4ZpD31LWUIzUDLrwMPxLjmh1uURnbeYEf0Mivw==}
+ peerDependencies:
+ expo: '*'
+ react-native: '*'
+
resolution: {integrity: sha512-OGLvHK7Hb7qsONMWGB9pJw3n+iY4OnZQmM/KwQEHRMrrOmNg0Lxj9+tp9bj46aAMMzXx0FTVA2jUKoplpXPnkA==}
peerDependencies:
@@ -6961,6 +6971,12 @@ packages:
expo: '*'
react-native: '*'
+ resolution: {integrity: sha512-1vkZRadOsIputFDBcclqBa1pO3iXOO6iIsdqJipQWw4V5TSnWgmRTuOF7ro8IzrVue+PHbum++KCG3Tawem4cg==}
+ peerDependencies:
+ expo: '*'
+ react-native: '*'
+
resolution: {integrity: sha512-QyS9L1Kh9sKJg4gfU6rdbpxpmH+DyzBX8z6jVvXMUDoqLr1GqmkO/Wu379KCXjL///kWbhpNlbi7AgBuj4VdIQ==}
peerDependencies:
@@ -6968,6 +6984,13 @@ packages:
react: '*'
react-native: '*'
+ resolution: {integrity: sha512-7WOMC2oA6xCfOm8bbofqWn2bIqyWFm7YLEnpc/gA1MJH0Ll0TfT/3+CqRkoW2eNRWMS8sxrz5WukUmSvmNquHA==}
+ peerDependencies:
+ expo: '*'
+ react: '*'
+ react-native: '*'
+
resolution: {integrity: sha512-m/n8maxqNcHk6ZDhuqXBfD5Kt1Iz3M8xykVgdB0iSCIXvF70IqWXmQhX8Psswhrp8eZ+3r0mAD0Jh/2gFA3QaA==}
peerDependencies:
@@ -7004,8 +7027,8 @@ packages:
resolution: {integrity: sha512-cgTe1NqzQdYs/WN+3nIY5IZg8s0pb0xaTUbhYvxQDn137GbwRfHoGM2se3m3Vsl4Qu+B9G4RPEK5WJDEU2Do7g==}
- resolution: {integrity: sha512-28lkFImeXTS+bhAjuCFV7w7tW5bXg27BJVrxv+nC/nyYa86qEa0oFeHwqol6ha5k4pdVDQgBF09GM4A1k76Ssg==}
+ resolution: {integrity: sha512-GqgH746wtJImmsbyHmCQoi7cOslKuWQBbJHXr53S35Bpf5UvxCAztvnitUEd7D0QvFN2rvkOhylbZpgZZfBLlQ==}
peerDependencies:
expo: '*'
react: '*'
@@ -7033,12 +7056,12 @@ packages:
expo: '*'
react-native: '*'
- resolution: {integrity: sha512-Q8KAlq37nLKsQ+HsS9NpQVpd5jCgqtu694TDUNHBUBpV9ViD82mRBh8Uug/h68RG9xnLS+kuL4nYaCuFRghHjg==}
+ resolution: {integrity: sha512-Hj5NjZRlfccazhKab+wK19leRVUr1Y/PUERaRvegIbUSkq4GVxKq6lU9QHlKQyC16MdD/VS4iwsiLivB4o7lvQ==}
hasBin: true
- resolution: {integrity: sha512-Cg3aQnVsQhZcMOF/RFgPGzMuhIak5W9eR9ecwmFSeQ813r4/49ut6RMA6PqUuUKuPCUIRqnBAHfSyTm1W9nfzg==}
+ resolution: {integrity: sha512-ovB7C+GVQTlKAOIsOIHJVVXN9Mn0ljf2SYBS+afrRaGqq+HZEn1D3o+HReIVeH1NjCn/xDBb7I4HjldHs6luZA==}
peerDependencies:
react: '*'
react-native: '*'
@@ -7047,8 +7070,8 @@ packages:
react-native-worklets:
optional: true
- resolution: {integrity: sha512-WK0xFEe0FdZTCLCdfXK+HVNYfAmEbA6goecRxqjr0gh3XYRKAr9tikxqcM0ItLQoEPKntscPZhWcPLGvr97Tfw==}
+ resolution: {integrity: sha512-a5ckeHfnbYfonhcHGkM0EU/a0Keh+/OufXy/HyFS+spr5Ib0N4Oh1ZsSYFQhp5xdOUFkVofKRhfH+VmcccIIpA==}
peerDependencies:
react-native: '*'
@@ -7166,8 +7189,8 @@ packages:
expo: '*'
react-native: '*'
- resolution: {integrity: sha512-RG9BItgEObzSafkJKHPUh5iCnaPCFXJTDwfEJe3t7uhmqipVhcsf6gAJEtME0xaGaMp4Z3C+HLbPW9DMea8G0w==}
+ resolution: {integrity: sha512-/aBLZFTD7+BNHWV/q5XbNRFqMhW/CrHsYeq8CcS/iGz6lJHYwEMm4XFcdoaeliuMdo6ZjNrsTHkBIdGB8VMHTg==}
hasBin: true
peerDependencies:
'@expo/dom-webview': '*'
@@ -8186,73 +8209,36 @@ packages:
resolution: {integrity: sha512-gPWxznF6TKmUHrOQjlVo2UbaL2EJ71mb2CCeRs/2qBpi4L/g4LUVc9+3lKQ6DTUZwJswfM7ainGrLO1+fOqa2g==}
- resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==}
- engines: {node: '>= 12.0.0'}
- cpu: [arm64]
- os: [android]
-
resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [android]
- resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==}
- engines: {node: '>= 12.0.0'}
- cpu: [arm64]
- os: [darwin]
-
resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [darwin]
- resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==}
- engines: {node: '>= 12.0.0'}
- cpu: [x64]
- os: [darwin]
-
resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [darwin]
- resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==}
- engines: {node: '>= 12.0.0'}
- cpu: [x64]
- os: [freebsd]
-
resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [freebsd]
- resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==}
- engines: {node: '>= 12.0.0'}
- cpu: [arm]
- os: [linux]
-
resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==}
engines: {node: '>= 12.0.0'}
cpu: [arm]
os: [linux]
- resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==}
- engines: {node: '>= 12.0.0'}
- cpu: [arm64]
- os: [linux]
- libc: [glibc]
-
resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==}
engines: {node: '>= 12.0.0'}
@@ -8260,13 +8246,6 @@ packages:
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}
- engines: {node: '>= 12.0.0'}
- cpu: [arm64]
- os: [linux]
- libc: [musl]
-
resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==}
engines: {node: '>= 12.0.0'}
@@ -8274,13 +8253,6 @@ packages:
os: [linux]
libc: [musl]
- resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}
- engines: {node: '>= 12.0.0'}
- cpu: [x64]
- os: [linux]
- libc: [glibc]
-
resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==}
engines: {node: '>= 12.0.0'}
@@ -8288,13 +8260,6 @@ packages:
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}
- engines: {node: '>= 12.0.0'}
- cpu: [x64]
- os: [linux]
- libc: [musl]
-
resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==}
engines: {node: '>= 12.0.0'}
@@ -8302,34 +8267,18 @@ packages:
os: [linux]
libc: [musl]
- resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==}
- engines: {node: '>= 12.0.0'}
- cpu: [arm64]
- os: [win32]
-
resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [win32]
- resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==}
- engines: {node: '>= 12.0.0'}
- cpu: [x64]
- os: [win32]
-
resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [win32]
- resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==}
- engines: {node: '>= 12.0.0'}
-
resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==}
engines: {node: '>= 12.0.0'}
@@ -13061,33 +13010,33 @@ snapshots:
'@expo-google-fonts/[email protected]': {}
dependencies:
'@expo/code-signing-certificates': 0.0.6
'@expo/config': 57.0.9([email protected])
'@expo/config-plugins': 57.0.9([email protected])
'@expo/devcert': 1.2.1
- '@expo/env': 2.4.2
+ '@expo/env': 2.4.3
'@expo/image-utils': 0.11.5([email protected])
'@expo/inline-modules': 0.1.7([email protected])
'@expo/json-file': 11.0.1
'@expo/metro': 56.0.2
- '@expo/metro-config': 57.0.11([email protected])([email protected])
- '@expo/metro-file-map': 57.0.2
+ '@expo/metro-config': 57.0.12([email protected])([email protected])
+ '@expo/metro-file-map': 57.0.3
'@expo/osascript': 2.7.1
'@expo/package-manager': 1.13.1
'@expo/plist': 0.8.1
- '@expo/prebuild-config': 57.0.15([email protected])
+ '@expo/prebuild-config': 57.0.16([email protected])
'@expo/require-utils': 57.0.5([email protected])
'@expo/schema-utils': 57.0.2
'@expo/spawn-async': 1.8.0
'@expo/ws-tunnel': 2.0.0([email protected])
'@expo/xcpretty': 4.4.4
'@react-native/dev-middleware': 0.86.3
accepts: 1.3.8
- agent-cli-detector: 0.1.6
+ agent-cli-detector: 0.1.7
arg: 5.0.2
bplist-creator: 0.1.0
bplist-parser: 0.3.2
@@ -13097,7 +13046,7 @@ snapshots:
connect: 3.7.0
debug: 4.4.3
dnssd-advertise: 1.1.6
expo-server: 57.0.3
fetch-nodeshim: 0.4.10
getenv: 2.0.0
@@ -13124,7 +13073,7 @@ snapshots:
ws: 8.21.1
zod: 4.3.6
optionalDependencies:
- expo-router: 57.0.17(2378d4467649e87a2be422b81281c63c)
+ expo-router: 57.0.17(e2df021366f5afb705d6bf2fb591ffad)
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
transitivePeerDependencies:
- '@expo/dom-webview'
@@ -13194,9 +13143,9 @@ snapshots:
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
@@ -13208,11 +13157,19 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ chalk: 4.1.2
+ debug: 4.4.3
+ getenv: 2.0.0
+ transitivePeerDependencies:
+ - supports-color
+
'@expo/[email protected]': {}
dependencies:
- '@expo/env': 2.4.2
+ '@expo/env': 2.4.3
'@expo/spawn-async': 1.8.0
arg: 5.0.2
chalk: 4.1.2
@@ -13259,22 +13216,22 @@ snapshots:
- supports-color
- typescript
dependencies:
anser: 1.4.10
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
stacktrace-parser: 0.1.11
dependencies:
'@babel/code-frame': 7.29.7
'@babel/core': 7.29.7
'@babel/generator': 7.29.7
'@expo/config': 57.0.9([email protected])
- '@expo/env': 2.4.2
+ '@expo/env': 2.4.3
'@expo/json-file': 11.0.1
'@expo/metro': 56.0.2
'@expo/require-utils': 57.0.5([email protected])
@@ -13289,19 +13246,19 @@ snapshots:
glob: 13.0.6
hermes-parser: 0.36.1
jsc-safe-url: 0.2.4
- lightningcss: 1.32.0
+ lightningcss: 1.33.0
picomatch: 4.0.5
- postcss: 8.5.19
+ postcss: 8.5.28
resolve-from: 5.0.0
optionalDependencies:
transitivePeerDependencies:
- bufferutil
- supports-color
- typescript
- utf-8-validate
dependencies:
debug: 4.4.3
fb-watchman: 2.0.2
@@ -13312,11 +13269,11 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
anser: 1.4.10
pretty-format: 29.7.0
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
@@ -13365,7 +13322,7 @@ snapshots:
base64-js: 1.5.1
xmlbuilder: 15.1.1
dependencies:
'@expo/config': 57.0.9([email protected])
'@expo/config-plugins': 57.0.9([email protected])
@@ -13374,7 +13331,7 @@ snapshots:
'@expo/json-file': 11.0.1
'@react-native/normalize-colors': 0.86.3
debug: 4.4.3
- expo-modules-autolinking: 57.0.12([email protected])
+ expo-modules-autolinking: 57.0.13([email protected])
resolve-from: 5.0.0
semver: 7.8.5
transitivePeerDependencies:
@@ -13391,17 +13348,17 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
debug: 4.4.3
expo-server: 57.0.3
react: 19.2.3
optionalDependencies:
- expo-router: 57.0.17(2378d4467649e87a2be422b81281c63c)
+ expo-router: 57.0.17(e2df021366f5afb705d6bf2fb591ffad)
react-dom: 19.2.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -13416,9 +13373,9 @@ snapshots:
'@expo/[email protected]': {}
dependencies:
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
sf-symbols-typescript: 2.2.0
@@ -14800,12 +14757,12 @@ snapshots:
merge-options: 3.0.4
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
optionalDependencies:
dependencies:
@@ -14941,7 +14898,9 @@ snapshots:
metro-runtime: 0.84.5
transitivePeerDependencies:
- '@babel/core'
+ - bufferutil
- supports-color
+ - utf-8-validate
'@react-native/[email protected]': {}
@@ -16007,7 +15966,7 @@ snapshots:
dependencies:
@@ -16306,7 +16265,7 @@ snapshots:
transitivePeerDependencies:
- '@babel/core'
dependencies:
'@babel/generator': 7.29.7
'@babel/helper-module-imports': 7.29.7
@@ -16353,7 +16312,7 @@ snapshots:
react-refresh: 0.14.2
optionalDependencies:
'@babel/runtime': 7.29.7
transitivePeerDependencies:
- '@babel/core'
- supports-color
@@ -17821,41 +17780,41 @@ snapshots:
dependencies:
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
dependencies:
'@expo/image-utils': 0.11.5([email protected])
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
transitivePeerDependencies:
- supports-color
- typescript
dependencies:
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
- expo-application: 57.0.2([email protected])
- expo-crypto: 57.0.2([email protected])
+ expo-application: 57.0.2([email protected])
+ expo-crypto: 57.0.2([email protected])
invariant: 2.2.4
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
@@ -17863,78 +17822,98 @@ snapshots:
- expo
- supports-color
dependencies:
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
'@expo/schema-utils': 57.0.2
resolve-from: 5.0.0
semver: 7.8.5
dependencies:
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
'@expo/env': 2.4.2
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
transitivePeerDependencies:
- supports-color
dependencies:
+ '@expo/env': 2.4.3
+ react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
dependencies:
dependencies:
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
+ react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+
+ dependencies:
fontfaceobserver: 2.3.0
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
+ fontfaceobserver: 2.3.0
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
+ react: 19.2.3
+ react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+
+ dependencies:
- [email protected](patch_hash=78594ca2235bdbbee2665f37b86d4e1e892733c4f9bd38fa7085338b90486e2b)([email protected]):
+ [email protected](patch_hash=78594ca2235bdbbee2665f37b86d4e1e892733c4f9bd38fa7085338b90486e2b)([email protected]):
dependencies:
- expo-image-loader: 57.0.1([email protected])
+ expo-image-loader: 57.0.1([email protected])
dependencies:
- expo-image-loader: 57.0.1([email protected])
+ expo-image-loader: 57.0.1([email protected])
dependencies:
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
sf-symbols-typescript: 2.2.0
@@ -17943,14 +17922,14 @@ snapshots:
dependencies:
react: 19.2.3
dependencies:
invariant: 2.2.4
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
@@ -17958,23 +17937,23 @@ snapshots:
- expo
- supports-color
dependencies:
react: 19.2.3
rtl-detect: 1.1.2
dependencies:
expo-json-utils: 57.0.1
dependencies:
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
'@expo/require-utils': 57.0.5([email protected])
'@expo/spawn-async': 1.8.0
@@ -17984,51 +17963,51 @@ snapshots:
- supports-color
- typescript
dependencies:
'@expo/expo-modules-macros-plugin': 0.6.1
- expo-modules-jsi: 57.0.6([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
+ expo-modules-jsi: 57.1.0([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
invariant: 2.2.4
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
optionalDependencies:
dependencies:
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
react: 19.2.3
dependencies:
'@expo/image-utils': 0.11.5([email protected])
abort-controller: 3.0.0
badgin: 1.2.3
- expo-application: 57.0.2([email protected])
+ expo-application: 57.0.2([email protected])
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
transitivePeerDependencies:
- supports-color
- typescript
- [email protected](patch_hash=53be555646735a171c1624f074ef30e5ca897a7b8893724bc2d0d51682f769d8)([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
+ [email protected](patch_hash=53be555646735a171c1624f074ef30e5ca897a7b8893724bc2d0d51682f769d8)([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
- [email protected](2378d4467649e87a2be422b81281c63c):
+ [email protected](e2df021366f5afb705d6bf2fb591ffad):
dependencies:
'@expo/schema-utils': 57.0.2
'@radix-ui/react-slot': 1.3.0(@types/[email protected])([email protected])
'@react-native-masked-view/masked-view': 0.3.2([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
@@ -18036,12 +18015,12 @@ snapshots:
color: 4.2.3
debug: 4.4.3
escape-string-regexp: 4.0.0
expo-server: 57.0.3
fast-deep-equal: 3.1.3
invariant: 2.2.4
nanoid: 3.3.16
@@ -18071,56 +18050,56 @@ snapshots:
- react-native-worklets
- supports-color
dependencies:
dependencies:
'@expo/config-plugins': 57.0.9([email protected])
'@expo/config-types': 57.0.2
'@expo/plist': 0.8.1
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
transitivePeerDependencies:
- supports-color
- typescript
dependencies:
'@expo/config-plugins': 57.0.9([email protected])
'@expo/image-utils': 0.11.5([email protected])
xml2js: 0.6.0
transitivePeerDependencies:
- supports-color
- typescript
dependencies:
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
'@expo-google-fonts/material-symbols': 0.4.40
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
sf-symbols-typescript: 2.2.0
dependencies:
dependencies:
'@expo/code-signing-certificates': 0.0.6
'@expo/plist': 0.8.1
@@ -18128,11 +18107,11 @@ snapshots:
arg: 4.1.3
chalk: 4.1.2
debug: 4.4.3
expo-eas-client: 57.0.2
- expo-manifests: 57.0.1([email protected])
+ expo-manifests: 57.0.1([email protected])
expo-structured-headers: 57.0.0
- expo-updates-interface: 57.0.1([email protected])
+ expo-updates-interface: 57.0.1([email protected])
getenv: 2.0.0
glob: 13.0.6
ignore: 5.3.2
@@ -18143,40 +18122,40 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
'@babel/runtime': 7.29.7
'@expo/config': 57.0.9([email protected])
'@expo/config-plugins': 57.0.9([email protected])
- '@expo/fingerprint': 0.20.10
+ '@expo/fingerprint': 0.20.13
'@expo/local-build-cache-provider': 57.0.8([email protected])
'@expo/metro': 56.0.2
- '@expo/metro-config': 57.0.11([email protected])([email protected])
+ '@expo/metro-config': 57.0.12([email protected])([email protected])
'@ungap/structured-clone': 1.3.3
- babel-preset-expo: 57.0.9(@babel/[email protected])(@babel/[email protected])([email protected])([email protected])
- expo-keep-awake: 57.0.1([email protected])([email protected])
- expo-modules-autolinking: 57.0.12([email protected])
+ babel-preset-expo: 57.0.12(@babel/[email protected])(@babel/[email protected])([email protected])([email protected])
+ expo-keep-awake: 57.0.2([email protected])([email protected])
+ expo-modules-autolinking: 57.0.13([email protected])
pretty-format: 29.7.0
react: 19.2.3
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
react-refresh: 0.14.2
whatwg-url-minimum: 0.1.2
optionalDependencies:
react-dom: 19.2.3([email protected])
react-native-webview: 13.16.1(patch_hash=4f76ca2497d14d136ef6ff35060f4c35b57319a3edf53fa334b82771a9405c16)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
@@ -19335,88 +19314,39 @@ snapshots:
transitivePeerDependencies:
- supports-color
- optional: true
-
optional: true
- optional: true
-
optional: true
- optional: true
-
optional: true
- optional: true
-
optional: true
- optional: true
-
optional: true
- optional: true
-
optional: true
- optional: true
-
optional: true
- optional: true
-
optional: true
- optional: true
-
optional: true
- optional: true
-
optional: true
- optional: true
-
optional: true
- dependencies:
- detect-libc: 2.1.2
- optionalDependencies:
- lightningcss-android-arm64: 1.32.0
- lightningcss-darwin-arm64: 1.32.0
- lightningcss-darwin-x64: 1.32.0
- lightningcss-freebsd-x64: 1.32.0
- lightningcss-linux-arm-gnueabihf: 1.32.0
- lightningcss-linux-arm64-gnu: 1.32.0
- lightningcss-linux-arm64-musl: 1.32.0
- lightningcss-linux-x64-gnu: 1.32.0
- lightningcss-linux-x64-musl: 1.32.0
- lightningcss-win32-arm64-msvc: 1.32.0
- lightningcss-win32-x64-msvc: 1.32.0
-
dependencies:
detect-libc: 2.1.2
@@ -23019,24 +22949,24 @@ snapshots:
xdt-ios-action-sheet@file:apps/mobile/modules/xdt-ios-action-sheet: {}
dependencies:
xdt-mobile-realtime-audio@file:apps/mobile/modules/xdt-mobile-realtime-audio: {}
xdt-screenshot-monitor@file:apps/mobile/modules/xdt-screenshot-monitor: {}
dependencies:
dependencies:
dependencies:
diff --git a/scripts/__tests__/design-inventory.test.mjs b/scripts/__tests__/design-inventory.test.mjs
index f100abbd6c..9fa6b710fc 100644
--- a/scripts/__tests__/design-inventory.test.mjs
+++ b/scripts/__tests__/design-inventory.test.mjs
@@ -1267,7 +1267,7 @@ test('Mobile actual route families and shared visible consumers are discoverable
const coverage = mobileRouteCoverage(ROOT);
assert.deepEqual(coverage.missing, []);
assert.deepEqual(coverage.stale, []);
- assert.equal(coverage.mapped.find(r=>r.path.endsWith('devices/desktop/[deviceId].tsx')).component, '@/remote-desktop/RemoteDesktopScreen');
+ assert.equal(coverage.mapped.find(r=>r.path.endsWith('devices/desktop/[deviceId].tsx')).component, 'RemoteDesktopRoute');
const { surfaces } = buildGeneratedSurfaces(ROOT);
for (const [id, ends] of [
['mobile.chat.session', ['MessageRenderer.tsx', 'CompanionMessageCard.tsx', 'AuthorizationMessageCard.tsx', 'FailedScheduleNotice.tsx']],