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。

fix(mobile): 修复 Duo 旋转、分栏布局与折叠远控交互

Dash742cae7bb231
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index dbf310ca16..7e95fb8722 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -22,7 +22,7 @@ import { keyboardControlRegion, type LayoutRect } from '@/platform/windowGeometr
import { useAdaptiveWindow, PaneViewportProvider } from '@/platform/AdaptiveWindowContext';
import { useSessionHeaderHeight } from '@/session/useSessionHeaderHeight';
import { useDoubleTap } from '@/session/useDoubleTap';
-import { sessionPaneLayout } from '@/session/sessionPaneLayout';
+import { useSessionPaneLayout } from '@/session/ResidentHomeList';
import { ComposerExpandButton } from '@/session/ComposerExpandButton';
import { nativeComposerAvailable } from '@/session/ComposerNativeInput';
import { getActiveMobileSessionRealm } from '@/config/env';
@@ -3012,7 +3012,7 @@ function SessionScreenContent() {
[remoteAgentCatalogs],
);
const adaptiveWindow = useAdaptiveWindow();
- const paneLayout = sessionPaneLayout(adaptiveWindow);
+ const paneLayout = useSessionPaneLayout();
const horizontalSystemHeader = Platform.OS === 'ios' && adaptiveWindow.barEdge === 'none'
&& !paneLayout.persistent && !shareSelectionActive && !companionChat;
const composerRegion = keyboardControlRegion(adaptiveWindow, keyboardState.height);
@@ -3057,6 +3057,10 @@ function SessionScreenContent() {
windowDimensions.width, windowDimensions.height, windowDimensions.fontScale,
insets.top, insets.bottom, insets.left, insets.right, adaptiveWindow.barEdge,
]), sessionListDrawerOverlayMounted);
+ // Duo shares the status area with its native toolbar. Its measured height
+ // already includes that area; safeArea.top + 44 would count the toolbar twice.
+ const topChromeHeight = Math.max(topOverlayHeight,
+ horizontalSystemHeader ? nativeHeaderHeight : insets.top + navigationChrome.target);
// 退出宽屏后 layout.drawerWidth 会变 0;退场期间继续用最后一个有效宽度,避免面板几何跳变。
const sessionListDrawerWidthRef = useRef(wideSessionNav.drawerWidth);
if (wideSessionNav.enabled) sessionListDrawerWidthRef.current = wideSessionNav.drawerWidth;
@@ -9883,7 +9887,7 @@ function SessionScreenContent() {
style={[styles.keyboard, { marginLeft: paneLayout.detail.x, marginRight: Math.max(0, windowDimensions.width - paneLayout.detail.x - paneLayout.detail.width) }]}
>
{Platform.OS === 'ios' ? (
- <SessionHeaderNativeBlur height={Math.max(topOverlayHeight, insets.top + 44)}
+ <SessionHeaderNativeBlur height={topChromeHeight}
fadeInside={companionHeaderShown ? CHAT_HEADER_BLUR_FADE_INSIDE : undefined} />
) : null}
<SessionChromeLayer
@@ -11072,7 +11076,7 @@ function SessionScreenContent() {
<SessionTransientNotice
notice={transientNotice}
onDismiss={dismissTransientNotice}
- top={Math.max(topOverlayHeight, insets.top + 44) + spacing.sm}
+ top={topChromeHeight + spacing.sm}
/>
</MessageHistoryOverlay>
<MessageHistoryOverlay enabled={!paneLayout.persistent || sessionListDrawerOverlayMounted}>
@@ -11318,14 +11322,14 @@ function SessionHeaderBar({
<SystemNavigationBack label={t('shared.back')} onPress={onBack} />
{sessionListButton}
{systemBack ? <Stack.Toolbar placement="right">
- {workerHeader ? null : <>
+ {workerHeader ? null :
<Stack.Toolbar.Button icon={require('../../assets/navigation/monitor.png')} iconRenderingMode="template"
- accessibilityLabel={t('remoteDesktop.title')} disabled={!currentSession} onPress={onOpenRemoteDesktop} />
+ accessibilityLabel={t('remoteDesktop.title')} disabled={!currentSession} onPress={onOpenRemoteDesktop} />}
+ {workerHeader ? null :
<Stack.Toolbar.Button icon={require('../../assets/navigation/folder.png')} iconRenderingMode="template"
accessibilityLabel={t('session.presentation.overview.actions.files.a11y')}
disabled={!currentSession || !overview?.actions.some(action => action.id === 'files' && !action.disabled)}
- onPress={onOpenFiles} />
- </>}
+ onPress={onOpenFiles} />}
<Stack.Toolbar.Button icon="ellipsis" accessibilityLabel={t('session.menu.details')}
disabled={!currentSession} onPress={onOpenSettings} />
</Stack.Toolbar> : null}
diff --git a/apps/mobile/docs/navigation-and-composer.md b/apps/mobile/docs/navigation-and-composer.md
index b7b1f1784d..7b1e4c4783 100644
--- a/apps/mobile/docs/navigation-and-composer.md
+++ b/apps/mobile/docs/navigation-and-composer.md
@@ -18,6 +18,8 @@
- 已有任务或恢复草稿的模型后来被关闭时,保留原模型身份与输入内容;模型面板说明需要重选,发送前要求明确选择开启模型,不自动换模型。远程目录仍只传开启模型的详情。
- 减弱动态效果:不播形变与拉开,直接到位。
- 伙伴对话:左上角为返回(回到伙伴列表);Duo 系统栏已有返回时保留侧栏按钮,不出现两个返回。
+- Duo 等宽屏任务页可拖动中间把手调整两栏:列表宽度限制在 240–420pt,并为正文保留至少 400pt;真实折痕划分的两栏不允许移动。宽度在当前窗口内跨任务和旋转保留,不写入持久设置。
+- iOS 首页列表留在自己的原生路由内,进入任务后仍可供返回动画显示;常驻侧栏独立保留列表内容,拖动分栏时不叠加尺寸动画。系统顶栏已计入安全区时,磨砂高度直接采用原生测量值。
- 设置等整页滚动的二级页:顶栏透明、系统柔和边缘,内容滚到顶栏和底部指示条下面,无硬分界(设置、语音词典、账号注销、伙伴私聊、共享任务管理、资源列表);设备详情只去掉底部色带。
## 已知未完成
diff --git a/apps/mobile/src/__tests__/residentHomeList.test.tsx b/apps/mobile/src/__tests__/residentHomeList.test.tsx
index a0fbea255b..ee27fc75da 100644
--- a/apps/mobile/src/__tests__/residentHomeList.test.tsx
+++ b/apps/mobile/src/__tests__/residentHomeList.test.tsx
@@ -4,11 +4,15 @@ import { createRoot } from 'react-dom/client';
import { afterEach, expect, it, vi } from 'vitest';
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
import { homeRowPropsEqual } from '../session/homeRowPropsEqual';
-import { ResidentHomeList, ResidentHomeListProvider } from '../session/ResidentHomeList';
+import { ResidentHomeList, ResidentHomeListProvider, useResidentHomeList, useSessionPaneLayout } from '../session/ResidentHomeList';
const state = vi.hoisted(() => ({
- platform: 'ios', spring: vi.fn((target: number) => target), hydrated: true, reduceMotion: true, progress: null as any, slide: null as any, mode: 'tasks', segments: ['devices'], width: 1000, anchorWidth: 1000, mounts: 0, unmounts: 0,
+ pan: {} as Record<string, (...args: any[]) => any>, divider: null as any,
+ deferMeasure: false, measurements: [] as (() => void)[],
+ platform: 'android', spring: vi.fn((target: number) => target), hydrated: true, reduceMotion: true, progress: null as any, slide: null as any, mode: 'tasks', segments: ['devices'], width: 1000, anchorWidth: 1000, mounts: 0, unmounts: 0,
}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/theme', () => ({ useTheme: () => ({ colors: { textSecondary: 'gray', borderStrong: 'gray' } }) }));
vi.mock('../session/useHomeMode', () => ({ useHomeMode: () => ({ mode: state.mode, hydrated: state.hydrated }) }));
vi.mock('expo-router', () => ({ useSegments: () => state.segments }));
vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => state.reduceMotion }));
@@ -25,13 +29,18 @@ vi.mock('react-native', async () => {
return {
StyleSheet: { create: (v: any) => v },
Platform: { get OS() { return state.platform; } },
+ PanResponder: { create: (handlers: any) => { state.pan = handlers; return { panHandlers: {} }; } },
View: React.forwardRef(({ children, onLayout, ...props }: any, ref) => {
+ if (props.testID === 'session.paneDivider') state.divider = props;
React.useImperativeHandle(ref, () => ({
measureLayout: (_: any, callback: any) => callback(0, 80, state.anchorWidth, 720),
- measureInWindow: (callback: any) => callback(0, 80, state.anchorWidth, 720),
+ measureInWindow: (callback: any) => {
+ const measure = () => callback(0, 80, state.anchorWidth, 720);
+ if (state.deferMeasure) state.measurements.push(measure); else measure();
+ },
}));
React.useEffect(() => { onLayout?.(); }, [onLayout]);
- return <div data-pointer={props.pointerEvents}>{children}</div>;
+ return <div data-pointer={props.pointerEvents} data-testid={props.testID}>{children}</div>;
}),
};
});
@@ -46,8 +55,54 @@ vi.mock('react-native-reanimated', async () => {
const roots: ReturnType<typeof createRoot>[] = [];
afterEach(() => {
act(() => roots.splice(0).forEach(root => root.unmount()));
- state.platform = 'ios'; state.spring.mockClear(); state.hydrated = true; state.reduceMotion = true; state.mode = 'tasks'; state.segments = ['devices']; state.width = 1000; state.anchorWidth = 1000;
+ state.platform = 'android'; state.spring.mockClear(); state.hydrated = true; state.reduceMotion = true; state.mode = 'tasks'; state.segments = ['devices']; state.width = 1000; state.anchorWidth = 1000;
state.mounts = 0; state.unmounts = 0;
+ state.deferMeasure = false; state.measurements = [];
+ state.divider = null; state.pan = {};
+});
+
+// Unit: real divider handlers + provider layout. User's 2026-10-23 request adds
+// live bounded resizing; previous resident-list tests never drove a divider.
+it('drags both panes together, clamps the bounds and retains width through route and orientation changes', () => {
+ state.platform = 'ios'; state.segments = ['sessions', '[sessionId]'];
+ let layout: ReturnType<typeof useSessionPaneLayout>;
+ function Probe() {
+ layout = useSessionPaneLayout();
+ state.anchorWidth = layout.sidebarWidth;
+ return <><div data-detail={layout.detail.x} />
+ <ResidentHomeList focused top={80} left={0} right={0}><ListProbe onSelect={() => {}} /></ResidentHomeList>
+ </>;
+ }
+ const host = document.createElement('div'), root = createRoot(host); roots.push(root);
+ const render = (key: string) => act(() => root.render(<ResidentHomeListProvider><Probe key={key} /></ResidentHomeListProvider>));
+ render('task-a');
+ const list = host.querySelector('[data-select]');
+ act(() => (host.querySelector('[data-scroll]') as HTMLButtonElement).click());
+ expect(state.pan.onMoveShouldSetPanResponder(null, { dx: 2, dy: 20 })).toBe(false);
+ expect(state.pan.onMoveShouldSetPanResponder(null, { dx: 8, dy: 1 })).toBe(true);
+ const start = layout!.sidebarWidth;
+ act(() => state.pan.onPanResponderGrant());
+ act(() => state.pan.onPanResponderMove(null, { dx: 360 - start }));
+ expect(layout!.sidebarWidth).toBe(360);
+ expect(layout!.detail.x).toBe(360);
+ act(() => state.pan.onPanResponderRelease(null, { dx: 1000 }));
+ expect(layout!.sidebarWidth).toBe(420);
+ render('task-b'); expect(layout!.sidebarWidth).toBe(420);
+ state.width = 669; render('task-b');
+ expect(layout!.persistent).toBe(false);
+ expect(host.querySelector('[data-testid="session.paneDivider"]')).toBeNull();
+ state.width = 1000; render('task-b'); expect(layout!.sidebarWidth).toBe(420);
+ act(() => state.pan.onPanResponderGrant());
+ act(() => state.pan.onPanResponderMove(null, { dx: -1000 }));
+ expect(layout!.sidebarWidth).toBe(240);
+ act(() => state.pan.onPanResponderTerminate());
+ expect(layout!.sidebarWidth).toBe(420);
+ act(() => state.divider.onAccessibilityAction({ nativeEvent: { actionName: 'decrement' } }));
+ expect(layout!.sidebarWidth).toBe(396);
+ expect(host.querySelector('[data-select]')).toBe(list);
+ expect(list?.textContent).toBe('240');
+ expect(state.mounts).toBe(1);
+ expect(state.unmounts).toBe(0);
});
const ListProbe = memo(function ListProbe({ onSelect }: { onSelect(): void }) {
const [position, setPosition] = useState(0);
@@ -136,3 +191,99 @@ it('switches Android home modes in place, because each pane draws its own bar',
expect(state.spring).not.toHaveBeenCalled();
expect(state.progress.value).toBe(1);
});
+
+// Regression: Duo portrait → landscape briefly removed the task list while its
+// new host waited for native measurements. Existing tests only switched routes
+// at a fixed wide size. Exercise the real provider/slot (unit tier), preserving
+// visible content and component state even while measurements are outstanding.
+it.each([669, 951])('keeps the home list mounted across rotation, starting at width %i', (width) => {
+ const host = document.createElement('div'); const root = createRoot(host); roots.push(root);
+ const render = () => act(() => root.render(<Scene detail={false} homeSelect={() => {}} />));
+ state.width = width; render();
+ expect(host.querySelector('[data-scroll]')).not.toBeNull();
+ act(() => (host.querySelector('[data-scroll]') as HTMLButtonElement).click());
+ for (const next of [951, 669, 951, 430, 669]) {
+ state.deferMeasure = true; state.width = next; state.anchorWidth = next;
+ render();
+ expect(host.querySelector('[data-select]')?.textContent).toBe('240');
+ expect(host.querySelector('[data-host]')?.getAttribute('data-pointer')).toBe('box-none');
+ act(() => { while (state.measurements.length) state.measurements.shift()!(); });
+ expect(state.mounts).toBe(1); expect(state.unmounts).toBe(0);
+ }
+});
+
+it('hides the retained home list on a narrow task route, then reuses it on return', () => {
+ const host = document.createElement('div'); const root = createRoot(host); roots.push(root);
+ const render = () => act(() => root.render(<Scene detail={false} homeSelect={() => {}} />));
+ render();
+ act(() => (host.querySelector('[data-scroll]') as HTMLButtonElement).click());
+ state.width = 669; state.segments = ['sessions', '[sessionId]']; render();
+ expect(host.querySelector('[data-host]')?.getAttribute('data-pointer')).toBe('none');
+ expect(host.querySelector('[data-subscriptions]')?.getAttribute('data-subscriptions')).toBe('false');
+ state.segments = ['devices']; render();
+ expect(host.querySelector('[data-select]')?.textContent).toBe('240');
+ expect(state.mounts).toBe(1); expect(state.unmounts).toBe(0);
+});
+
+it('keeps iOS home inside its native route at every width, while only persistent drawers use the root host', () => {
+ state.platform = 'ios';
+ function Owners() {
+ const home = useResidentHomeList();
+ const drawer = useResidentHomeList(true);
+ return <div data-home={home.enabled} data-drawer={drawer.enabled} />;
+ }
+ const host = document.createElement('div'); const root = createRoot(host); roots.push(root);
+ const render = () => act(() => root.render(<ResidentHomeListProvider><Owners /></ResidentHomeListProvider>));
+ for (const width of [669, 951, 430]) {
+ state.width = width; render();
+ expect(host.querySelector('[data-home]')?.getAttribute('data-home')).toBe('false');
+ expect(host.querySelector('[data-drawer]')?.getAttribute('data-drawer')).toBe(String(width === 951));
+ }
+ act(() => root.render(<Owners />));
+ expect(host.querySelector('[data-home]')?.getAttribute('data-home')).toBe('false');
+});
+
+// The previous rotation test only checked mount counts in the root host. UIKit
+// needs the covered HOME ROUTE to still contain its list before JS focus changes
+// during interactive back. This unit test covers ownership; device video covers
+// the native transition itself.
+it('keeps the scrolled iOS home list in the covered route through rotation and back', () => {
+ state.platform = 'ios';
+ function HomeRoute({ focused }: { focused: boolean }) {
+ const resident = useResidentHomeList();
+ const list = <ListProbe onSelect={() => {}} />;
+ return <section data-home-route>{resident.enabled
+ ? <ResidentHomeList focused={focused} top={80} left={0} right={0}>{list}</ResidentHomeList>
+ : list}</section>;
+ }
+ const host = document.createElement('div'); const root = createRoot(host); roots.push(root);
+ const render = (focused: boolean) => act(() => root.render(
+ <ResidentHomeListProvider><HomeRoute focused={focused} /></ResidentHomeListProvider>,
+ ));
+ render(true);
+ const list = host.querySelector('[data-home-route] [data-select]');
+ expect(list).not.toBeNull();
+ act(() => (host.querySelector('[data-scroll]') as HTMLButtonElement).click());
+ for (const width of [669, 951, 430, 951]) {
+ state.width = width; render(true);
+ expect(host.querySelector('[data-home-route] [data-select]')).toBe(list);
+ state.segments = ['sessions', '[sessionId]']; render(false);
+ expect(host.querySelector('[data-home-route] [data-select]')).toBe(list);
+ expect(list?.textContent).toBe('240');
+ state.segments = []; render(true);
+ expect(host.querySelector('[data-home-route] [data-select]')).toBe(list);
+ }
+ expect(state.mounts).toBe(1); expect(state.unmounts).toBe(0);
+});
+
+it('does not draw the retained iOS sidebar over home during return', () => {
+ state.platform = 'ios';
+ state.segments = ['sessions', '[sessionId]'];
+ const host = document.createElement('div'); const root = createRoot(host); roots.push(root);
+ const render = () => act(() => root.render(<Scene detail homeSelect={() => {}} detailSelect={() => {}} />));
+ render();
+ expect(state.slide().opacity).toBe(1);
+ state.segments = []; render();
+ expect(state.slide().opacity).toBe(0);
+ expect(host.querySelector('[data-host]')?.getAttribute('data-pointer')).toBe('none');
+});
diff --git a/apps/mobile/src/__tests__/windowGeometry.test.ts b/apps/mobile/src/__tests__/windowGeometry.test.ts
index aeb44996aa..bf43cb5eb6 100644
--- a/apps/mobile/src/__tests__/windowGeometry.test.ts
+++ b/apps/mobile/src/__tests__/windowGeometry.test.ts
@@ -14,6 +14,24 @@ describe('adaptive window regions', () => {
expect(p.detail.x).toBe(p.sidebarWidth);
expect(p.detail.x + p.detail.width).toBe(840);
});
+ // Unit: Duo resize request (2026-10-23). Existing tests cover fixed panes only;
+ // dragging beyond either edge must not squeeze the list or message composer away.
+ it('clamps manual column widths and reserves at least 400pt for the conversation', () => {
+ for (const [requested, expected] of [[100, 240], [360, 360], [900, 420]]) {
+ const p = sessionPaneLayout(window(), requested);
+ expect(p.sidebarWidth).toBe(expected);
+ expect(p.detail.x + p.detail.width).toBe(840);
+ expect(p.detail.width).toBeGreaterThanOrEqual(400);
+ }
+ expect(sessionPaneLayout(window({ width: 820 }), 420).sidebarWidth).toBe(360);
+ expect(sessionPaneLayout(window({ width: 430 }), 420).sidebarWidth).toBe(0);
+ });
+ it('keeps an actual reserved fold fixed even with a manual width', () => {
+ const p = sessionPaneLayout(window({ regions: [{ kind: 'division', x: 360, y: 0, width: 32, height: 700 }] }), 240);
+ expect(p.sidebarWidth).toBe(360);
+ expect(p.detail.x).toBe(392);
+ expect(p.resizeBounds).toBeNull();
+ });
it('collapses in either side of Split View, regardless of phone/tablet identity', () => {
for (const insets of [{ top: 0, left: 60, right: 0, bottom: 20 }, { top: 0, left: 0, right: 60, bottom: 20 }]) {
const p = sessionPaneLayout(window({ width: 430, insets }));
@@ -47,22 +65,36 @@ describe('adaptive window regions', () => {
describe('folded desktop keyboard geometry', () => {
- const folded = window({ regions: [{ kind: 'division', x: 0, y: 300, width: 900, height: 30 }] });
+ const folded = window({ width: 600, barEdge: 'none', regions: [{ kind: 'division', x: 0, y: 300, width: 600, height: 30 }] });
+ // Unit: 2026-10-23 product correction. A landscape half-fold must use the
+ // ordinary full-width desktop, even though the window reports a division.
+ it('never splits a landscape desktop into video and trackpad', () => {
+ for (const region of [
+ { kind: 'division' as const, x: 430, y: 0, width: 30, height: 700 },
+ { kind: 'division' as const, x: 0, y: 300, width: 900, height: 30 },
+ ]) {
+ expect(foldDesktopLayout(window({ regions: [region] }), 0, 240, false)).toBeNull();
+ expect(foldDesktopLayout(window({ regions: [region] }), 200, 180, true)).toBeNull();
+ }
+ });
it('keeps video above the hinge and controls below it', () => {
const layout = foldDesktopLayout(folded, 0, 240, false)!;
- expect(layout.media).toEqual({ x: 0, y: 0, width: 840, height: 300 });
- expect(layout.controls).toEqual({ x: 0, y: 330, width: 840, height: 350 });
+ expect(layout.media).toEqual({ x: 0, y: 0, width: 540, height: 300 });
+ expect(layout.controls).toEqual({ x: 0, y: 330, width: 540, height: 350 });
});
it('keeps an input sheet in the upper region when the keyboard covers the lower half', () => {
- expect(keyboardControlRegion(folded, 350)).toEqual({ x: 0, y: 0, width: 840, height: 300 });
+ expect(keyboardControlRegion(folded, 350)).toEqual({ x: 0, y: 0, width: 540, height: 300 });
});
- it('moves custom keys above the fold when the system keyboard covers the lower region', () => {
- const layout = foldDesktopLayout(folded, 350, 180, true)!;
- expect(layout.controls).toEqual({ x: 0, y: 0, width: 840, height: 300 });
- expect(layout.media.height).toBe(120);
+ // Unit: 2026-10-23 Duo feedback replaces the old upper-screen fallback.
+ // With 100pt remaining below the hinge, the 60pt keyboard toolbar must stay
+ // above the system keyboard in that lower screen, leaving video unchanged.
+ it('keeps the keyboard toolbar below the hinge even with less than 140pt remaining', () => {
+ const layout = foldDesktopLayout(folded, 270, 60, true)!;
+ expect(layout.controls).toEqual({ x: 0, y: 330, width: 540, height: 100 });
+ expect(layout.media).toEqual({ x: 0, y: 0, width: 540, height: 300 });
});
it('keeps controls above a bottom camera occlusion', () => {
- const layout = foldDesktopLayout(window({ regions: [
+ const layout = foldDesktopLayout(window({ ...folded, regions: [
...folded.regions, { kind: 'occlusion', x: 0, y: 600, width: 900, height: 100 },
] }), 0, 240, false)!;
expect(layout.controls.y + layout.controls.height).toBe(600);
diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index a1a667195f..bca1b4a26a 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -1,4 +1,8 @@
{
+ "paneResize": {
+ "label": "Column width",
+ "hint": "Drag left or right to adjust the column widths"
+ },
"sideChat": {
"collapse": "Collapse side chat",
"resume": "Continue side chat",
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index 82121080f1..929a32dfc6 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -1,4 +1,8 @@
{
+ "paneResize": {
+ "label": "列の幅",
+ "hint": "左右にドラッグして列の幅を調整します"
+ },
"sideChat": {
"collapse": "サイドチャットを閉じる",
"resume": "サイドチャットを続ける",
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index d861d3fb6c..f887320c24 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -1,4 +1,8 @@
{
+ "paneResize": {
+ "label": "열 너비",
+ "hint": "좌우로 드래그하여 두 열의 너비를 조절합니다"
+ },
"sideChat": {
"collapse": "사이드 채팅 접기",
"resume": "사이드 채팅 계속",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index 92ae324ec6..a04806d592 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -1,4 +1,8 @@
{
+ "paneResize": {
+ "label": "分栏宽度",
+ "hint": "左右拖动可调整两栏宽度"
+ },
"sideChat": {
"collapse": "收起追问",
"resume": "继续追问",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.json
index 3479ab4794..96da665f9f 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/session.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json
@@ -1,4 +1,8 @@
{
+ "paneResize": {
+ "label": "分欄寬度",
+ "hint": "左右拖動可調整兩欄寬度"
+ },
"sideChat": {
"collapse": "收起追問",
"resume": "繼續追問",
diff --git a/apps/mobile/src/remote-desktop/FoldTouchpad.tsx b/apps/mobile/src/remote-desktop/FoldTouchpad.tsx
index dd20ca2173..b2dde7f615 100644
--- a/apps/mobile/src/remote-desktop/FoldTouchpad.tsx
+++ b/apps/mobile/src/remote-desktop/FoldTouchpad.tsx
@@ -16,7 +16,10 @@ export function FoldTouchpad({ send, enabled }: { send(message: object): void; e
accessibilityHint={t('remoteDesktop.pointerHint')}
accessibilityState={{ disabled: !enabled }}
onStartShouldSetResponder={() => enabled}
- onResponderGrant={(e) => { touch.current = { x: e.nativeEvent.pageX, y: e.nativeEvent.pageY, distance: 0, time: Date.now() }; }}
+ onResponderGrant={(e) => {
+ touch.current = { x: e.nativeEvent.pageX, y: e.nativeEvent.pageY, distance: 0, time: Date.now() };
+ send({ type: 'nativeTouchpad', phase: 'start' });
+ }}
onResponderMove={(e) => {
const last = touch.current;
if (!last || !enabled) return;
@@ -29,6 +32,7 @@ export function FoldTouchpad({ send, enabled }: { send(message: object): void; e
if (enabled && last && last.distance < 8 && Date.now() - last.time < 400) {
send({ type: 'nativeTouchpad', tap: true });
}
+ send({ type: 'nativeTouchpad', phase: 'end' });
}}
onResponderTerminate={() => { touch.current = null; send({ type: 'releaseInput' }); }}
style={[styles.pad, { borderColor: colors.border }]}>
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
index 90df912d60..623334fdce 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
@@ -1,6 +1,6 @@
-import { foldDesktopLayout } from './foldDesktopLayout';
+import { foldDesktopLayout, foldDesktopRegion } from './foldDesktopLayout';
import { useAdaptiveWindow } from '@/platform/AdaptiveWindowContext';
-import { windowDivision, controlRegion } from '@/platform/windowGeometry';
+import { controlRegion } from '@/platform/windowGeometry';
import { FoldTouchpad } from './FoldTouchpad';
import {
useCallback,
@@ -309,8 +309,7 @@ export function RemoteDesktopSession({
});
const screenSize = windowSize;
const geometry = useAdaptiveWindow();
- const division = windowDivision(geometry);
- const tableRegion = division && division.first.height >= 160 && division.second.height >= 160 && division.first.width >= 160 && division.second.width >= 160 ? division : null;
+ const tableRegion = foldDesktopRegion(geometry);
const systemSideRail = Platform.OS === 'ios' && !tableRegion && (geometry.barEdge !== 'none' || (geometry.reservedRegionsSupported && geometry.regularWidth && windowSize.width > windowSize.height));
// Android adjustResize shrinks the window for the IME, not the display.
@@ -500,6 +499,17 @@ export function RemoteDesktopSession({
const [nativeKeyboardHeight, setNativeKeyboardHeight] = useState(0);
const [keyboardPanelHeight, setKeyboardPanelHeight] = useState(0);
const [backControlHeight, setBackControlHeight] = useState(44);
+ // On a wide iOS window the status reservation can occupy only the trailing
+ // corner. Share that row, with the native toolbar's bottom spacing, when the
+ // complete back button fits in its unobstructed leading corner.
+ const sharedBackTop = insets.top - backControlHeight - spacing.md;
+ const portraitBackLeft = edgePadding.paddingLeft + spacing.lg;
+ const sharedStatusRow = Platform.OS === 'ios' && !landscape && !tableRegion
+ && geometry.reservedRegionsSupported && geometry.regularWidth
+ && statusReservation.length > 0 && sharedBackTop >= spacing.md
+ && !geometry.regions.some(region =>
+ region.x < portraitBackLeft + navigationChrome.target && region.x + region.width > portraitBackLeft
+ && region.y < sharedBackTop + backControlHeight && region.y + region.height > sharedBackTop);
// Android's system keyboard already resizes the window. Keep its existing
// flow layout; only iOS needs an offset above the native keyboard.
const landscapeKeyboardOverlay =
@@ -507,7 +517,7 @@ export function RemoteDesktopSession({
const keyboardBottom =
Platform.OS === "ios" && keyboard && !fullKeys ? nativeKeyboardHeight : 0;
const foldLayout = foldDesktopLayout(geometry, keyboardBottom, keyboardPanelHeight, keyboard);
- const fullScreenFoldBackground = Boolean(foldLayout && division?.axis === 'horizontal');
+ const fullScreenFoldBackground = Boolean(foldLayout);
const foldControls = foldLayout?.controls ?? controlRegion(geometry);
const heldKeys = useRef(new Map<string, string[]>());
const [keyPage, setKeyPage] = useState(0);
@@ -3632,7 +3642,7 @@ export function RemoteDesktopSession({
{
top: landscape
? insets.top + spacing.lg
- : edgePadding.paddingTop + spacing.xs,
+ : sharedStatusRow ? sharedBackTop : edgePadding.paddingTop + spacing.xs,
// iOS landscape: Island/notch sits mid-edge, so the top-left
// corner stays clear even when insets.left is large. Skip that
// inset unless the top edge is also unsafe — a physical cutout
@@ -3642,7 +3652,7 @@ export function RemoteDesktopSession({
? (Platform.OS === "ios" && !geometry.reservedRegionsSupported && insets.top === 0 ? 0 : insets.left) +
spacing.lg +
(Platform.OS === "ios" ? spacing.xs : 0)
- : edgePadding.paddingLeft + spacing.lg,
+ : portraitBackLeft,
},
systemSideRail && {
top: sideRailTop,
diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
index 2267f070bb..9f0a9d74cb 100644
--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
@@ -5227,10 +5227,31 @@ describe("remote desktop controls", () => {
const starts = requests().filter(r => r.op === 'start').length;
const stops = requests().filter(r => r.op === 'stop').length;
renderGeometry({ ...geometry, regions: [{ kind: 'division', x: 0, y: 300, width: 900, height: 30 }] });
+ expect(sent().filter(m => m.type === 'mouseButtons').at(-1)).toMatchObject({ fitToInsets: false });
+ expect(host.querySelector('[data-testid="remoteDesktop.foldTouchpad"]')).toBeNull();
+ fixture.size = { width: 700, height: 900 };
+ renderGeometry({ ...geometry, ...fixture.size, barEdge: 'none',
+ regions: [{ kind: 'division', x: 0, y: 400, width: 700, height: 30 }] });
expect(sent().filter(m => m.type === 'mouseButtons').at(-1)).toMatchObject({
- fitToInsets: true, topInset: 0, bottomInset: 400,
+ fitToInsets: true, topInset: 0, bottomInset: 500,
});
+ // Unit: Duo jitter regression. Drive the real folded-pad responder, not a
+ // synthetic viewer command, to ensure the cursor ownership reaches WebView.
+ const pad = fixture.views['remoteDesktop.foldTouchpad'];
+ fixture.post.mockClear();
+ act(() => pad.onResponderGrant({ nativeEvent: { pageX: 50, pageY: 550 } }));
+ act(() => pad.onResponderMove({ nativeEvent: { pageX: 70, pageY: 560 } }));
+ act(() => pad.onResponderRelease());
+ expect(sent().filter(m => m.type === 'nativeTouchpad')).toEqual([
+ { type: 'nativeTouchpad', phase: 'start' },
+ { type: 'nativeTouchpad', dx: 20, dy: 10 },
+ { type: 'nativeTouchpad', phase: 'end' },
+ ]);
+ act(() => pad.onResponderGrant({ nativeEvent: { pageX: 70, pageY: 560 } }));
+ act(() => pad.onResponderTerminate());
+ expect(sent().at(-1)).toEqual({ type: 'releaseInput' });
expect(host.querySelector('[data-testid="remoteDesktop.viewer"]')).toBe(viewerNode);
+ fixture.size = { width: 900, height: 700 };
renderGeometry(geometry);
expect(sent().filter(m => m.type === 'mouseButtons').at(-1)).toMatchObject({ fitToInsets: false });
expect(host.querySelector('[data-testid="remoteDesktop.viewer"]')).toBe(viewerNode);
diff --git a/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts b/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts
index 2cf2b09a86..e40a39d97e 100644
--- a/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts
+++ b/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts
@@ -352,6 +352,47 @@ describe("native media overlay", () => {
});
describe("remote desktop viewport", () => {
+ // Unit: Duo folded-pad jitter (2026-10-23). Existing nativeTouchpad coverage
+ // sends no host cursor feedback. Interleave delayed native cursor packets with
+ // a held lower-screen gesture, including its first cursor packet and a pause.
+ it.each(['touch', 'pointer'])('keeps folded-pad motion local across delayed host feedback in %s mode', (mode) => {
+ const v = viewer(false, true, true);
+ v.elements.stage.clientWidth = 800;
+ v.elements.stage.clientHeight = 400;
+ v.send({ type: 'init', epoch: 'fold', width: 1600, height: 800 });
+ v.send({ type: 'mode', mode });
+ v.send({ type: 'control', enabled: true });
+ v.send({ type: 'mouseButtons', native: true, enabled: true });
+ const hostCursor = (x: number) => v.send({ type: 'nativeCursor', epoch: 'fold', cursor: {
+ x, y: 0.5, visible: true, width: 16, height: 16, hotX: 0, hotY: 0, png: 'iVBORw0KGgo=',
+ } });
+ const moves = () => v.messages.flatMap(m => m.events ?? []).filter(e => e.kind === 'move');
+ v.send({ type: 'nativeTouchpad', phase: 'start' });
+ v.send({ type: 'nativeTouchpad', dx: 80, dy: 0 });
+ v.flush(); v.ack();
+ hostCursor(0.2);
+ v.send({ type: 'nativeTouchpad', dx: 80, dy: 0 });
+ v.flush(); v.ack();
+ expect(moves().at(-1)).toMatchObject({ x: 0.7, y: 0.5 });
+ // A resting finger still owns the gesture beyond the 200ms echo grace.
+ v.frame(1000); hostCursor(0.3);
+ v.send({ type: 'nativeTouchpad', dx: 80, dy: 0 });
+ v.flush(); v.ack();
+ expect(moves().at(-1)).toMatchObject({ x: expect.closeTo(0.8), y: 0.5 });
+ v.send({ type: 'nativeTouchpad', phase: 'end' });
+ hostCursor(0.3);
+ expect(parseFloat(v.elements.cursor.style.left)).toBeCloseTo(640);
+ v.frame(201); hostCursor(0.4);
+ v.send({ type: 'nativeTouchpad', phase: 'start' });
+ v.send({ type: 'nativeTouchpad', dx: 80, dy: 0 });
+ v.flush(); v.ack();
+ expect(moves().at(-1)).toMatchObject({ x: 0.5, y: 0.5 });
+ v.send({ type: 'releaseInput' }); v.ack();
+ v.frame(201); hostCursor(0.2);
+ v.send({ type: 'nativeTouchpad', dx: 80, dy: 0 });
+ v.flush();
+ expect(moves().at(-1)).toMatchObject({ x: expect.closeTo(0.3), y: 0.5 });
+ });
it('maps lower-pane relative motion against the upper video viewport and rejects invalid input', () => {
const v = viewer();
v.elements.stage.clientWidth = 800;
diff --git a/apps/mobile/src/remote-desktop/foldDesktopLayout.ts b/apps/mobile/src/remote-desktop/foldDesktopLayout.ts
index 2aeae3dcc8..3462ef9d88 100644
--- a/apps/mobile/src/remote-desktop/foldDesktopLayout.ts
+++ b/apps/mobile/src/remote-desktop/foldDesktopLayout.ts
@@ -1,17 +1,22 @@
import { controlRegion, windowDivision, type WindowGeometry } from '@/platform/windowGeometry';
+/** Tabletop controls are portrait-only. A landscape fold keeps the ordinary desktop. */
+export function foldDesktopRegion(g: WindowGeometry) {
+ if (g.width >= g.height) return null;
+ const split = windowDivision(g);
+ return split?.axis === 'horizontal' && split.first.width >= 160 && split.second.width >= 160
+ && split.first.height >= 160 && split.second.height >= 160 ? split : null;
+}
+
/** Both media layers receive this same rect. Software keyboard occlusion never changes the lease. */
export function foldDesktopLayout(g: WindowGeometry, keyboardBottom: number, panelHeight: number, keyboard: boolean) {
- const split = windowDivision(g);
- if (!split || split.first.width < 160 || split.second.width < 160 || split.first.height < 160 || split.second.height < 160) return null;
+ const split = foldDesktopRegion(g);
+ if (!split) return null;
const bottom = g.height - Math.max(0, keyboardBottom);
let controls = controlRegion(g);
controls = { ...controls, height: Math.max(0, Math.min(controls.height, bottom - controls.y)) };
- // A tall system keyboard may cover the lower half. Keep custom controls above
- // the fold in that case, and fit the video above those controls in the same region.
- if (keyboard && controls.height < 140 && split.axis === 'horizontal') {
- controls = { ...split.first, height: Math.max(0, Math.min(split.first.height, bottom - split.first.y)) };
- }
+ // Keyboard controls belong to the lower screen, including the compact toolbar
+ // above the system keyboard. Never move them into the video region.
const panel = keyboard ? Math.min(Math.max(0, panelHeight), controls.height) : 0;
const panelTop = controls.y + controls.height - panel;
const overlappingColumns = controls.x < split.first.x + split.first.width && controls.x + controls.width > split.first.x;
diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsx
index 6396e897de..fe957197b2 100644
--- a/apps/mobile/src/session/HomeSurface.tsx
+++ b/apps/mobile/src/session/HomeSurface.tsx
@@ -474,7 +474,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
// The retained page and its visible sidebar must never release each other's subscriptions.
const HOME_LIST_SUBSCRIPTION_OWNER = `device-list:${useId()}`;
const embedded = width !== undefined;
- const residentList = useResidentHomeList();
+ const residentList = useResidentHomeList(embedded);
const activeHomeSession = useContext(ActiveHomeSession);
const rememberTask = rememberRecentTask;
const viewSession = getHomeViewSession();
diff --git a/apps/mobile/src/session/ResidentHomeList.tsx b/apps/mobile/src/session/ResidentHomeList.tsx
index 822d99792b..d621340c48 100644
--- a/apps/mobile/src/session/ResidentHomeList.tsx
+++ b/apps/mobile/src/session/ResidentHomeList.tsx
@@ -9,19 +9,30 @@ import { useReduceMotionEnabled } from '@/hooks/useReduceMotion';
import { motionDuration } from '@/theme/tokens';
import { RemoteSessionStoreSubscriptionGate } from './remoteSessionStore';
import { sessionPaneLayout } from './sessionPaneLayout';
+import { SessionPaneDivider } from './SessionPaneDivider';
+
+const PaneLayoutContext = createContext<ReturnType<typeof sessionPaneLayout> | null>(null);
+
+export function useSessionPaneLayout() {
+ const geometry = useAdaptiveWindow();
+ return useContext(PaneLayoutContext) ?? sessionPaneLayout(geometry);
+}
type Frame = { left: number; top: number; width: number; height: number };
type Entry = { owner: string; frame: Frame; children: ReactNode };
const Context = createContext<{
- enabled: boolean;
+ persistent: boolean;
mounted: { current: boolean };
publish(entry: Entry): void;
host: React.RefObject<View | null>;
} | null>(null);
-export function useResidentHomeList() {
+export function useResidentHomeList(embedded = false) {
const context = useContext(Context);
- return { enabled: context?.enabled ?? false, mounted: context?.mounted };
+ // UIKit must find Home's list inside its covered screen during interactive
+ // back, before JS focus changes. Keep that ownership at every window width.
+ // Android retains the root host; modal drawers always stay in their surface.
+ return { enabled: !!context && (embedded ? context.persistent : Platform.OS !== 'ios'), mounted: context?.mounted };
}
/** Preserve the resident-list owner when route content is re-hosted above this
@@ -40,7 +51,11 @@ export function useResidentHomeListContextBridge(children: ReactNode) {
* never key the host by route, session, or presentation width. */
export function ResidentHomeListProvider({ children }: { children: ReactNode }) {
const geometry = useAdaptiveWindow();
- const enabled = sessionPaneLayout(geometry).persistent;
+ // Window preference, shared by retained routes; rotation clamps only the
+ // displayed width, so returning to a wide window restores the user's choice.
+ const [sidebarWidth, setSidebarWidth] = useState<number | null>(null);
+ const paneLayout = useMemo(() => sessionPaneLayout(geometry, sidebarWidth), [geometry, sidebarWidth]);
+ const { persistent } = paneLayout;
const segments = useSegments() as string[];
const { mode, hydrated } = useHomeMode();
const homeRoute = segments.length === 0 || segments[0] === 'index'
@@ -48,10 +63,11 @@ export function ResidentHomeListProvider({ children }: { children: ReactNode })
// Android pages draw their own bar inside each pane, so sliding them would move it; they switch in place.
const progress = useHomeModeProgress(mode, homeRoute && Platform.OS === 'ios', hydrated);
// Keep the outgoing resident list drawn during the slide, but never interactive over the new tab.
- const visible = enabled && ((mode === 'tasks' && homeRoute)
- || (segments[0] === 'sessions' && segments[1] === '[sessionId]'));
+ const rootHome = Platform.OS !== 'ios';
+ const visible = (rootHome && mode === 'tasks' && homeRoute)
+ || (persistent && segments[0] === 'sessions' && segments[1] === '[sessionId]');
const slide = useAnimatedStyle(() => ({
- opacity: homeRoute ? (progress.value < 1 ? 1 : 0) : (visible ? 1 : 0),
+ opacity: homeRoute ? (rootHome && progress.value < 1 ? 1 : 0) : (visible ? 1 : 0),
transform: [{ translateX: homeRoute ? -progress.value * geometry.width : 0 }],
}));
const host = useRef<View>(null);
@@ -59,25 +75,32 @@ export function ResidentHomeListProvider({ children }: { children: ReactNode })
const [entry, setEntry] = useState<Entry | null>(null);
const reduceMotion = useReduceMotionEnabled();
const publish = useCallback((next: Entry) => { setEntry(next); }, []);
- const context = useMemo(() => ({ enabled, mounted, publish, host }), [enabled, publish]);
+ const context = useMemo(() => ({ persistent, mounted, publish, host }), [persistent, publish]);
useLayoutEffect(() => {
- mounted.current = enabled && !!entry;
- if (!enabled) setEntry(null);
- }, [enabled, entry]);
- return <HomeModeProgressContext.Provider value={progress}><Context.Provider value={context}>
+ mounted.current = !!entry;
+ }, [entry]);
+ return <PaneLayoutContext.Provider value={paneLayout}><HomeModeProgressContext.Provider value={progress}><Context.Provider value={context}>
<View ref={host} collapsable={false} style={styles.root}>
{children}
- {entry ? <Animated.View pointerEvents={visible ? 'box-none' : 'none'}
+ {entry ? <Animated.View collapsable={false} pointerEvents={visible ? 'box-none' : 'none'}
accessibilityElementsHidden={!visible}
importantForAccessibility={visible ? 'auto' : 'no-hide-descendants'}
style={[styles.host, entry.frame, {
transitionProperty: ['left', 'top', 'width', 'height'],
- transitionDuration: reduceMotion === false ? motionDuration.fast : 0,
+ // The measured slot already follows the divider. Do not start a
+ // second size animation when the final asynchronous measure arrives
+ // after release; keep the sidebar's native host above the route.
+ transitionDuration: !persistent && reduceMotion === false ? motionDuration.fast : 0,
}, slide]}>
<RemoteSessionStoreSubscriptionGate enabled={visible}>{entry.children}</RemoteSessionStoreSubscriptionGate>
</Animated.View> : null}
+ {visible && !homeRoute && paneLayout.resizeBounds ? <SessionPaneDivider
+ width={paneLayout.sidebarWidth} bounds={paneLayout.resizeBounds}
+ left={paneLayout.detail.x} top={geometry.insets.top} bottom={geometry.insets.bottom}
+ onResize={setSidebarWidth}
+ /> : null}
</View>
- </Context.Provider></HomeModeProgressContext.Provider>;
+ </Context.Provider></HomeModeProgressContext.Provider></PaneLayoutContext.Provider>;
}
/** A route supplies a measuring slot, not another native list. Its header stays
@@ -93,7 +116,7 @@ export function ResidentHomeList({ children, focused, top, left, right }: {
const measureRevision = useRef(0);
const measure = useCallback(() => {
const revision = ++measureRevision.current;
- if (!context?.enabled || !latest.current.focused || !context.host.current) return;
+ if (!context || !latest.current.focused || !context.host.current) return;
anchor.current?.measureInWindow((x, y, width, height) => {
context.host.current?.measureInWindow((hostX, hostY) => {
if (revision !== measureRevision.current || !latest.current.focused || width <= 0 || height <= 0) return;
@@ -110,5 +133,5 @@ export function ResidentHomeList({ children, focused, top, left, right }: {
}
const styles = StyleSheet.create({
root: { flex: 1 },
- host: { position: 'absolute' },
+ host: { position: 'absolute', zIndex: 1 },
});
diff --git a/apps/mobile/src/session/SessionPaneDivider.tsx b/apps/mobile/src/session/SessionPaneDivider.tsx
new file mode 100644
index 0000000000..3fe5d6ee39
--- /dev/null
+++ b/apps/mobile/src/session/SessionPaneDivider.tsx
@@ -0,0 +1,59 @@
+import { useMemo, useRef, useState } from 'react';
+import { PanResponder, StyleSheet, View } from 'react-native';
+import { useTranslation } from 'react-i18next';
+import { useTheme } from '@/theme';
+import { navigationChrome, radius, spacing } from '@/theme/tokens';
+
+/** A dedicated edge target; vertical list scrolling never starts a resize. */
+export function SessionPaneDivider({ width, left, top, bottom, bounds, onResize }: {
+ width: number;
+ left: number;
+ top: number;
+ bottom: number;
+ bounds: { min: number; max: number };
+ onResize(width: number): void;
+}) {
+ const { colors } = useTheme();
+ const { t } = useTranslation();
+ const [dragging, setDragging] = useState(false);
+ const latest = useRef({ width, bounds, onResize });
+ latest.current = { width, bounds, onResize };
+ const responder = useMemo(() => {
+ let initial = 0;
+ const resize = (next: number) => {
+ const current = latest.current;
+ current.onResize(Math.round(Math.max(current.bounds.min, Math.min(current.bounds.max, next))));
+ };
+ const finish = () => {
+ setDragging(false);
+ };
+ return PanResponder.create({
+ onMoveShouldSetPanResponder: (_event, gesture) => Math.abs(gesture.dx) > 4 && Math.abs(gesture.dx) > Math.abs(gesture.dy),
+ onPanResponderGrant: () => {
+ initial = latest.current.width;
+ setDragging(true);
+ },
+ onPanResponderMove: (_event, gesture) => resize(initial + gesture.dx),
+ onPanResponderRelease: (_event, gesture) => { resize(initial + gesture.dx); finish(); },
+ onPanResponderTerminate: () => { resize(initial); finish(); },
+ });
+ }, []);
+ return <View {...responder.panHandlers} testID="session.paneDivider"
+ accessible accessibilityRole="adjustable"
+ accessibilityLabel={t('session.paneResize.label')}
+ accessibilityHint={t('session.paneResize.hint')}
+ accessibilityValue={{ min: bounds.min, max: bounds.max, now: width, text: String(width) }}
+ accessibilityActions={[{ name: 'increment' }, { name: 'decrement' }]}
+ onAccessibilityAction={({ nativeEvent }) => {
+ const direction = nativeEvent.actionName === 'increment' ? 1 : nativeEvent.actionName === 'decrement' ? -1 : 0;
+ if (direction) onResize(Math.max(bounds.min, Math.min(bounds.max, width + direction * spacing.xl)));
+ }}
+ style={[styles.target, { left: left - navigationChrome.target / 2, top, bottom }]}>
+ <View pointerEvents="none" style={[styles.grip, { backgroundColor: dragging ? colors.textSecondary : colors.borderStrong }]} />
+ </View>;
+}
+
+const styles = StyleSheet.create({
+ target: { position: 'absolute', width: navigationChrome.target, alignItems: 'center', justifyContent: 'center', zIndex: 40 },
+ grip: { width: 3, height: spacing.xxl, borderRadius: radius.pill },
+});
diff --git a/apps/mobile/src/session/sessionPaneLayout.ts b/apps/mobile/src/session/sessionPaneLayout.ts
index cccb758226..69251af462 100644
--- a/apps/mobile/src/session/sessionPaneLayout.ts
+++ b/apps/mobile/src/session/sessionPaneLayout.ts
@@ -1,13 +1,19 @@
import { safeWindowRect, windowDivision, type WindowGeometry } from '@/platform/windowGeometry';
/** Navigation consumes space only when the remaining conversation is comfortably usable. */
-export function sessionPaneLayout(g: WindowGeometry) {
+export function sessionPaneLayout(g: WindowGeometry, requestedWidth: number | null = null) {
const safe = safeWindowRect(g);
const division = windowDivision(g);
const splitAtFold = division?.axis === 'vertical' && division.first.width >= 240 && division.second.width >= 320;
const persistent = !!splitAtFold || (!division && g.regularWidth && safe.width >= 760 && safe.height >= 480);
- const sidebarWidth = persistent ? (splitAtFold ? division!.first.width : Math.min(320, Math.round(safe.width * 0.34))) : 0;
+ // An actual reserved hinge cannot move. Flat windows can trade space between
+ // the list and conversation without losing either pane's usable minimum.
+ const resizeBounds = persistent && !splitAtFold ? { min: 240, max: Math.min(420, safe.width - 400) } : null;
+ const preferredWidth = requestedWidth !== null && Number.isFinite(requestedWidth)
+ ? requestedWidth : Math.min(320, Math.round(safe.width * 0.34));
+ const sidebarWidth = splitAtFold ? division!.first.width : resizeBounds
+ ? Math.round(Math.max(resizeBounds.min, Math.min(resizeBounds.max, preferredWidth))) : 0;
const sidebarGap = splitAtFold ? division!.second.x - safe.x - sidebarWidth : 0;
const pane = { ...safe, x: safe.x + sidebarWidth + sidebarGap, width: safe.width - sidebarWidth - sidebarGap };
- return { persistent, sidebarWidth, sidebarGap, detail: pane };
+ return { persistent, sidebarWidth, sidebarGap, detail: pane, resizeBounds };
}
diff --git a/docs/remote-desktop.md b/docs/remote-desktop.md
index a71f7b6f33..39f9835922 100644
--- a/docs/remote-desktop.md
+++ b/docs/remote-desktop.md
@@ -1221,6 +1221,18 @@ old RTC generations are discarded. Hidden cursors are not drawn. Unsupported
cursor images fall back to the existing position indicator without killing video.
Both Light and Dark use the source raster rather than tinting it.
+On a portrait half-fold, the upper region shows the desktop and the lower region
+holds the touchpad or keyboard controls. Landscape half-folds use the ordinary
+full-width landscape viewer. The keyboard toolbar remains below the hinge rather
+than moving into the video region when the system keyboard leaves little room.
+The lower touchpad owns relative cursor movement for its entire contact, including
+pauses, regardless of the video surface's touch/pointer preference. Host position
+feedback resumes after lift and the existing 200ms local-input grace period;
+cancellation, control loss and leaving the pad clear that ownership. The local
+React Native/WebView bridge carries contact start/end; the remote input protocol
+is unchanged. Regression coverage lives in Mobile's `viewer.test.ts` and
+`screen.test.tsx` under `src/remote-desktop/__tests__/`.
+
Desktop viewers use the local system pointer instead of drawing this raster.
An optional `shape` hint selects a bounded standard cursor keyword (text, hand,
resize, etc.); size, DPI and accessibility appearance remain owned by the local
diff --git a/packages/maker-shared/src/remote-desktop/viewerRuntime.js b/packages/maker-shared/src/remote-desktop/viewerRuntime.js
index 32e60718ab..5015601df8 100644
--- a/packages/maker-shared/src/remote-desktop/viewerRuntime.js
+++ b/packages/maker-shared/src/remote-desktop/viewerRuntime.js
@@ -135,6 +135,9 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
let remoteCursor = null,
lastLocalMove = 0,
localCursorAwake = false;
+ // The lower native pad is always relative input, independently of the video
+ // surface's touch mode. Keep its contact alive while the finger pauses too.
+ let nativeTouchpad = null;
let touchCursor = null,
touchCursorTimer = null,
touchCursorVisible = false;
@@ -699,11 +702,12 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
post({ type: "scaleMode", mode: scaleMode });
}
}
- const touchFeedback = control && mode === "touch" && touchCursorVisible;
- const cursorX = mode === "touch" && touchCursor ? touchCursor.x : cx;
- const cursorY = mode === "touch" && touchCursor ? touchCursor.y : cy;
+ const directTouch = mode === "touch" && !nativeTouchpad;
+ const touchFeedback = control && directTouch && touchCursorVisible;
+ const cursorX = directTouch && touchCursor ? touchCursor.x : cx;
+ const cursorY = directTouch && touchCursor ? touchCursor.y : cy;
cursor.style.transition =
- mode === "touch" && !touchFeedback && !reducedMotion.matches
+ directTouch && !touchFeedback && !reducedMotion.matches
? "opacity 120ms ease-out"
: "none";
for (const el of [image, video]) {
@@ -724,15 +728,15 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
cursor.style.top = r.y + cursorY * r.height - remoteCursor.hotY + "px";
cursor.style.display = "block";
cursor.style.opacity = (
- mode === "touch"
+ directTouch
? touchFeedback
: remoteCursor.visible ||
- (control && mode === "pointer" && localCursorAwake)
+ (control && (mode === "pointer" || nativeTouchpad) && localCursorAwake)
)
? "1"
: "0";
} else {
- cursor.style.opacity = (mode === "touch" ? !touchFeedback : false)
+ cursor.style.opacity = (directTouch ? !touchFeedback : false)
? "0"
: "1";
cursor.style.width = "18px";
@@ -814,14 +818,16 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
if (!remoteCursor || remoteCursor.png !== value.png)
cursorImage.src = "data:image/png;base64," + value.png;
// Keep delayed host coordinates from pulling the local touchpad backwards.
+ const nativeOwnsCursor = nativeTouchpad &&
+ (nativeTouchpad.down || performance.now() - lastLocalMove <= 200);
if (
- !remoteCursor ||
!control ||
- mode !== "pointer" ||
- (!pointers.size && performance.now() - lastLocalMove > 200)
+ (!nativeOwnsCursor && (!remoteCursor || mode !== "pointer" ||
+ (!pointers.size && performance.now() - lastLocalMove > 200)))
) {
cx = value.x;
cy = value.y;
+ nativeTouchpad = null;
}
if (value.visible) localCursorAwake = false;
remoteCursor = value;
@@ -841,7 +847,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
if (!pending.length) pendingSince = performance.now();
// Remote visibility can remain hidden after synthetic mouse movement. Wake
// the local touchpad cursor until the host reports a visible cursor again.
- if (event.kind === "move" && mode === "pointer") localCursorAwake = true;
+ if (event.kind === "move" && (mode === "pointer" || nativeTouchpad)) localCursorAwake = true;
if (event.kind === "key" || event.kind === "text") {
localCursorAwake = false;
render();
@@ -920,6 +926,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
}, 33);
cleanups.push(() => clearInterval(inputTimer));
function release() {
+ nativeTouchpad = null;
stopEdgePan();
desktopPan = null;
clearTimeout(hold);
@@ -2224,15 +2231,23 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
}
case "nativeTouchpad": {
if (!nativeMouseControls || !control) break;
+ if (message.phase === "start") {
+ nativeTouchpad = { down: true };
+ cursorNeedsEntry = true;
+ break;
+ }
+ if (message.phase === "end") {
+ if (nativeTouchpad) nativeTouchpad.down = false;
+ break;
+ }
if (message.tap === true) {
if (!heldMouse.size) { click(); flush(); }
break;
}
if (!Number.isFinite(message.dx) || !Number.isFinite(message.dy)) break;
+ nativeTouchpad ??= { down: false };
moveTouchpad(message.dx, message.dy);
queue({ kind: "move", x: cx, y: cy });
- touchCursor = { x: cx, y: cy };
- touchCursorVisible = true;
render();
break;
}
diff --git a/packages/maker-shared/src/remote-desktop/viewerSource.ts b/packages/maker-shared/src/remote-desktop/viewerSource.ts
index 2054bd0c08..083862d00b 100644
--- a/packages/maker-shared/src/remote-desktop/viewerSource.ts
+++ b/packages/maker-shared/src/remote-desktop/viewerSource.ts
@@ -1,2 +1,2 @@
// Generated by scripts/sync-remote-desktop-viewer.mjs. Do not edit.
-export const DESKTOP_VIEWER_SOURCE = "/** Shared browser viewer. Mobile bundles this exact source; Desktop imports it as a CSP-safe module. */\nfunction mountRemoteDesktopViewer(root, postMessage, config) {\n const cleanups = [];\n const listen = (target, type, fn, options) => {\n target.addEventListener(type, fn, options);\n cleanups.push(() => target.removeEventListener(type, fn, options));\n };\n const find = (id) =>\n root.getElementById\n ? root.getElementById(id)\n : root.querySelector(\"#\" + id);\n const { net, iceServers } = config;\n let nativeVideoActive = false;\n const validKeys = new Set(config.keyCodes);\n const transform =\n /* BEGIN TRANSFORM */\n function desktopTransform(\n vw,\n vh,\n dw,\n dh,\n zoom,\n fx,\n fy,\n fillHeight = false,\n ) {\n const fit = fillHeight\n ? vh / Math.max(1, dh)\n : Math.min(vw / Math.max(1, dw), vh / Math.max(1, dh));\n // Pinch stops at two viewer points per desktop point, never below fit.\n const maxZoom = Math.max(1, 2 / fit);\n const scale = fit * Math.max(1, Math.min(maxZoom, zoom));\n const width = dw * scale;\n const height = dh * scale;\n const x =\n width <= vw\n ? (vw - width) / 2\n : Math.min(0, Math.max(vw - width, vw / 2 - fx * width));\n const y =\n height <= vh\n ? (vh - height) / 2\n : Math.min(0, Math.max(vh - height, vh / 2 - fy * height));\n return { x, y, width, height, scale, maxZoom };\n };\n /* END TRANSFORM */ const networkStats =\n /* BEGIN NETWORK_STATS */\n function networkStats(stats, previous) {\n const rows = [...stats.values()];\n const video = rows.find(\n (s) =>\n s.type === \"inbound-rtp\" &&\n (s.kind === \"video\" || s.mediaType === \"video\"),\n );\n const transport = rows.find(\n (s) => s.type === \"transport\" && s.selectedCandidatePairId,\n );\n const pair = transport\n ? stats.get(transport.selectedCandidatePairId)\n : rows.find(\n (s) =>\n s.type === \"candidate-pair\" &&\n s.state === \"succeeded\" &&\n s.nominated,\n );\n const local = pair && stats.get(pair.localCandidateId),\n remote = pair && stats.get(pair.remoteCandidateId);\n const direct = [\"host\", \"srflx\", \"prflx\"];\n const route =\n local?.candidateType === \"relay\" || remote?.candidateType === \"relay\"\n ? \"relay\"\n : direct.includes(local?.candidateType) &&\n direct.includes(remote?.candidateType)\n ? \"direct\"\n : \"video\";\n const sample =\n video &&\n Number.isFinite(video.bytesReceived) &&\n Number.isFinite(video.timestamp)\n ? {\n id: video.id,\n path: pair?.id,\n bytes: video.bytesReceived,\n time: video.timestamp,\n }\n : null;\n let bytesPerSecond = null;\n if (\n sample &&\n previous &&\n sample.id === previous.id &&\n sample.path === previous.path &&\n sample.time > previous.time &&\n sample.bytes >= previous.bytes\n )\n bytesPerSecond =\n ((sample.bytes - previous.bytes) * 1000) /\n (sample.time - previous.time);\n const latencyMs =\n Number.isFinite(pair?.currentRoundTripTime) &&\n pair.currentRoundTripTime >= 0\n ? pair.currentRoundTripTime * 1000\n : null;\n return { transport: route, bytesPerSecond, latencyMs, sample };\n };\n\n /* END NETWORK_STATS */ const stage = find(\"stage\"),\n image = find(\"image\"),\n video = find(\"video\"),\n cursor = find(\"cursor\");\n // Shared ambient backdrop. Minimal viewer embeds may omit its subtree.\n const bg = find(\"bg\") || null,\n bgCanvas = find(\"bg-canvas\") || null,\n bgContext = bgCanvas ? bgCanvas.getContext(\"2d\") : null;\n let dw = 1920,\n dh = 1080,\n viewerSized = false,\n zoom = 1,\n desktopScale = null,\n reportedScaleMode = null,\n desktopPan = null,\n edgePointer = null,\n edgeFrame = null,\n edgeTime = 0,\n fx = 0.5,\n fy = 0.5,\n mode = \"pointer\",\n control = false,\n macKeyboard = false,\n pc = null,\n dc = null,\n seq = 0,\n generation = 0,\n epoch = null,\n gestureFrame = null;\n let remoteCursor = null,\n lastLocalMove = 0,\n localCursorAwake = false;\n let touchCursor = null,\n touchCursorTimer = null,\n touchCursorVisible = false;\n const reducedMotion = matchMedia(\"(prefers-reduced-motion: reduce)\");\n const cursorImage = find(\"cursor-image\");\n let pending = [],\n pendingSince = 0,\n sending = false,\n // Deadline while a paste shortcut holds the queue (desktop only; 0 = open),\n // and which modifier is copy/paste on the controlled computer.\n inputGateUntil = 0,\n clipboardModifier = \"control\",\n cx = 0.5,\n cy = 0.5,\n drag = false,\n start = null,\n last = null,\n multi = null,\n hold = null,\n moved = false;\n const pointers = new Map();\n const mouseButtons = find(\"mouse-buttons\"),\n wheel = find(\"mouse-wheel\"),\n wheelGrip = find(\"mouse-wheel-grip\");\n let nativeMouseControls = false;\n const mouseControlHandlers = new Map();\n function listenMouse(el, type, handler) {\n listen(el, type, handler);\n mouseControlHandlers.set(el.id + \":\" + type, handler);\n }\n const keyboardInput = find(\"keyboard-input\");\n let keyboardEnabled = false,\n composing = false;\n const keyboardSentinel = \"\\u200b\";\n function resetKeyboard() {\n keyboardInput.value = keyboardSentinel;\n keyboardInput.setSelectionRange(1, 1);\n }\n function showKeyboard(enabled) {\n keyboardEnabled = enabled && control;\n if (!keyboardEnabled) {\n composing = false;\n resetKeyboard();\n keyboardInput.blur();\n return;\n }\n if (composing) return;\n if (config.desktop && document.activeElement === keyboardInput) return;\n // Keep focus inside the native evaluateJavaScript call; WebKit can reject\n // keyboard presentation after requestAnimationFrame loses user activation.\n keyboardInput.blur();\n resetKeyboard();\n keyboardInput.focus({ preventScroll: true });\n }\n function keyboardKey(code) {\n if (!keyboardEnabled || !control) return;\n queue({ kind: \"key\", code, down: true });\n queue({ kind: \"key\", code, down: false });\n flush();\n }\n function commitKeyboard() {\n if (!keyboardEnabled || !control || composing) return;\n const text = keyboardInput.value.replace(keyboardSentinel, \"\");\n if (text) {\n for (let i = 0; i < text.length; i += 4096)\n queue({ kind: \"text\", text: text.slice(i, i + 4096) });\n flush();\n }\n resetKeyboard();\n }\n listen(keyboardInput, \"compositionstart\", () => {\n composing = true;\n });\n listen(keyboardInput, \"compositionend\", () => {\n composing = false;\n commitKeyboard();\n });\n listen(keyboardInput, \"input\", (e) => {\n if (!e.isComposing) commitKeyboard();\n });\n listen(keyboardInput, \"beforeinput\", (e) => {\n if (composing || e.isComposing) return;\n if (e.inputType === \"deleteContentBackward\") {\n e.preventDefault();\n keyboardKey(\"Backspace\");\n resetKeyboard();\n } else if (\n e.inputType === \"insertLineBreak\" ||\n e.inputType === \"insertParagraph\"\n ) {\n e.preventDefault();\n keyboardKey(\"Enter\");\n resetKeyboard();\n }\n });\n const heldMouse = new Map();\n let showMouseButtons = false,\n wheelY = null;\n function resetWheel() {\n wheelY = null;\n wheelGrip.style.transform = \"translateY(0px)\";\n }\n let statsTimer = null,\n statsSample = null;\n const post = (message) => postMessage({ ...message, epoch });\n const clamp = (v) => Math.max(0, Math.min(1, v));\n let fillHeight = false;\n let fitToInsets = false;\n const usesViewportInsets = () => viewerSized || fitToInsets;\n let panAnimation = null,\n viewportRightInset = 0,\n viewportLeftInset = 0,\n viewportBottomInset = 0,\n viewportTopInset = 0,\n keyboardViewportInset = 0,\n portraitKeyboardTopInset = 0;\n let keyboardViewportOpen = false;\n let keyboardFitWidth = null;\n let cursorNeedsEntry = true,\n manualViewMoved = false,\n followRest = null;\n // Insets guide centering and pan limits without clipping the full-screen\n // video surface or adding an opaque strip beside the Dynamic Island.\n const viewportLeft = () => (fillHeight ? viewportLeftInset : 0);\n const usableHeight = () =>\n Math.max(1, stage.clientHeight - viewportTopInset - viewportBottomInset);\n const viewportHeight = () =>\n usesViewportInsets() ? usableHeight() : Math.max(1, stage.clientHeight);\n const viewportWidth = () =>\n Math.max(\n 1,\n stage.clientWidth -\n viewportLeft() -\n (fillHeight ? viewportRightInset : 0),\n );\n // Center between the measured top controls and the keyboard edge (stage bottom).\n // The usable center is (topInset + stageHeight) / 2, so shift by topInset / 2.\n // Keep the fitted size and cap the shift when the desktop is too tall to fit.\n const verticalOffset = (height) =>\n (usesViewportInsets() ? viewportTopInset : 0) +\n (fillHeight\n ? 0\n : Math.min(\n Math.max(\n 0,\n portraitKeyboardTopInset - (usesViewportInsets() ? viewportTopInset : 0),\n ) / 2,\n Math.max(0, (viewportHeight() - height) / 2),\n ));\n const layout = () => {\n const r =\n config.desktop && desktopScale !== null\n ? {\n scale: desktopScale,\n width: dw * desktopScale,\n height: dh * desktopScale,\n maxZoom: 1,\n }\n : transform(\n keyboardFitWidth?.stageWidth === stage.clientWidth\n ? keyboardFitWidth.width : viewportWidth(),\n viewportHeight(),\n dw,\n dh,\n zoom,\n fx,\n fy,\n // Mobile fits both axes; retain Desktop scale semantics.\n config.desktop ? fillHeight && !viewerSized : false,\n );\n return {\n ...r,\n x: viewportLeft() + viewportWidth() / 2 - fx * r.width,\n y: viewportHeight() / 2 + verticalOffset(r.height) - fy * r.height,\n };\n };\n // 0 at fit, 1 at the pinch limit for the current viewport and display.\n const zoomProgress = (r = layout()) =>\n r.maxZoom > 1\n ? Math.max(0, Math.min(1, (zoom - 1) / (r.maxZoom - 1)))\n : 0;\n // The backdrop uses 5% / 90% / 5% source segments. The middle 90%\n // keeps the fitted picture's scale; each outer 5% stretches uniformly\n // to fill the remaining space, horizontally or vertically as needed.\n // Zoom and pan never move the backdrop: where the picture covers it, the\n // opaque picture simply occludes it, so input mapping stays uniform. Returns\n // null when the fitted picture already covers the stage, unless a Desktop\n // viewer has shrunk its foreground below fit and still needs the backdrop.\n const bgEdgeFraction = 0.05;\n const bgCenterFraction = 1 - 2 * bgEdgeFraction;\n function backgroundSegments(vw, vh, dw, dh, fill, includeFitted = false) {\n if (!(vw > 0 && vh > 0 && dw > 0 && dh > 0)) return null;\n const s = fill\n ? vh / Math.max(1, dh)\n : Math.min(vw / dw, vh / Math.max(1, dh));\n const w = dw * s,\n h = dh * s;\n if (w < vw || (includeFitted && w === vw && h === vh)) {\n const centerW = w * bgCenterFraction,\n centerX = vw / 2 - centerW / 2,\n sideW = centerX,\n top = (vh - h) / 2;\n return { axis: \"x\", s, w, h, top, centerW, centerX, sideW };\n }\n if (h < vh) {\n const centerH = h * bgCenterFraction,\n centerY = vh / 2 - centerH / 2,\n sideH = centerY,\n left = (vw - w) / 2;\n return { axis: \"y\", s, w, h, left, centerH, centerY, sideH };\n }\n return null;\n }\n // Native video renders beneath this WebView, so z-order cannot hide the\n // status behind the picture; cut the picture's rectangle out instead.\n // Measure the status only after its text or the stage changes, not per frame.\n let statusOrigin = null;\n function clipNetworkStatus(r = layout()) {\n const status = find(\"network-status\");\n if (!status) return;\n if (!nativeVideoActive || status.style.display === \"none\") {\n status.style.clipPath = \"\";\n return;\n }\n if (!statusOrigin)\n statusOrigin = { x: status.offsetLeft, y: status.offsetTop };\n const left = r.x - statusOrigin.x,\n top = r.y - statusOrigin.y,\n right = left + r.width,\n bottom = top + r.height;\n status.style.clipPath = `polygon(evenodd,0 0,100% 0,100% 100%,0 100%,0 0,${left}px ${top}px,${right}px ${top}px,${right}px ${bottom}px,${left}px ${bottom}px,${left}px ${top}px)`;\n }\n function paintBackground() {\n if (nativeVideoActive) {\n if (bg) bg.style.display = \"none\";\n return;\n }\n if (!bg || !bgCanvas || !bgContext) return;\n const vw = stage.clientWidth,\n vh = stage.clientHeight;\n const picture = config.desktop ? layout() : null;\n const coversStage =\n picture &&\n picture.x <= 0 &&\n picture.y <= 0 &&\n picture.x + picture.width >= vw &&\n picture.y + picture.height >= vh;\n const seg = coversStage\n ? null\n : backgroundSegments(vw, vh, dw, dh, config.desktop ? fillHeight : false, config.desktop);\n if (!seg) {\n bg.style.display = \"none\";\n bgRects = null;\n stopBackgroundLoop();\n return;\n }\n bg.style.display = \"block\";\n bgAxis = seg.axis;\n // The ambient layer also fills the notch and the area beneath native\n // controls. Only the interactive picture respects viewport insets.\n const originX = 0;\n // Source segments are resolved at draw time from the live source dimensions;\n // these dest rects only encode where each segment lands on the stage.\n bgRects =\n seg.axis === \"x\"\n ? [\n {\n x: originX,\n y: seg.top,\n w: seg.sideW,\n h: seg.h,\n },\n {\n x: originX + seg.centerX,\n y: seg.top,\n w: seg.centerW,\n h: seg.h,\n },\n {\n x: originX + seg.centerX + seg.centerW,\n y: seg.top,\n w: seg.sideW,\n h: seg.h,\n },\n ]\n : [\n {\n x: seg.left,\n y: 0,\n w: seg.w,\n h: seg.sideH,\n },\n {\n x: seg.left,\n y: seg.centerY,\n w: seg.w,\n h: seg.centerH,\n },\n {\n x: seg.left,\n y: seg.centerY + seg.centerH,\n w: seg.w,\n h: seg.sideH,\n },\n ];\n // Keep the backing store at stage resolution (capped) so the stretched\n // edges stay crisp without oversized allocations.\n bgDpr = Math.min(2, window.devicePixelRatio || 1);\n const bw = Math.round(stage.clientWidth * bgDpr),\n bh = Math.round(vh * bgDpr);\n if (bgCanvas.width !== bw || bgCanvas.height !== bh) {\n bgCanvas.width = bw;\n bgCanvas.height = bh;\n }\n scheduleBackgroundDraw();\n startBackgroundLoop();\n }\n // One canvas, three draws: each source segment stretches into whatever bar\n // the picture leaves open. The live video feeds it once presented; until\n // then the decoded JPEG frame does, so the backdrop always matches the\n // picture's own pixels and scale in the center segment.\n let bgRects = null,\n bgAxis = \"x\",\n bgDpr = 1,\n bgDrawFrame = null,\n bgLoopFrame = null;\n function drawBackground() {\n if (!bgContext || !bgRects) return;\n const useVideo =\n videoPresented && video.videoWidth > 0 && video.videoHeight > 0;\n const src = useVideo ? video : image;\n // drawImage source rects live in the source's own pixel space, which can\n // differ from dw/dh; fractions of the real bitmap keep every segment lined\n // up with what the picture element actually shows.\n const sw = useVideo ? video.videoWidth : image.naturalWidth;\n const sh = useVideo ? video.videoHeight : image.naturalHeight;\n // Cursor updates can schedule a repaint while the next JPEG is loading.\n // Keep the last backdrop until the replacement has drawable pixels.\n if ((!useVideo && !image.complete) || !(sw > 0 && sh > 0)) return;\n bgContext.setTransform(bgDpr, 0, 0, bgDpr, 0, 0);\n bgContext.clearRect(0, 0, stage.clientWidth, stage.clientHeight);\n const horizontal = bgAxis === \"x\";\n const sourceLength = horizontal ? sw : sh;\n const cuts = [0, bgEdgeFraction, 1 - bgEdgeFraction, 1];\n for (let i = 0; i < bgRects.length; i++) {\n const rect = bgRects[i];\n const origin = cuts[i] * sourceLength;\n const length = (cuts[i + 1] - cuts[i]) * sourceLength;\n bgContext.drawImage(\n src,\n horizontal ? origin : 0,\n horizontal ? 0 : origin,\n horizontal ? length : sw,\n horizontal ? sh : length,\n rect.x,\n rect.y,\n rect.w,\n rect.h,\n );\n }\n }\n function scheduleBackgroundDraw() {\n if (bgDrawFrame !== null || !bgRects || !bgContext) return;\n bgDrawFrame = requestAnimationFrame(() => {\n bgDrawFrame = null;\n drawBackground();\n });\n }\n function startBackgroundLoop() {\n if (\n bgLoopFrame !== null ||\n !bgContext ||\n !bgRects ||\n !videoPresented ||\n typeof video.requestVideoFrameCallback !== \"function\"\n )\n return;\n const frame = video.requestVideoFrameCallback(() => {\n if (bgLoopFrame !== frame) return;\n bgLoopFrame = null;\n drawBackground();\n startBackgroundLoop();\n });\n bgLoopFrame = frame;\n }\n // Only the streaming loop stops here; a pending one-shot draw is harmless\n // (it re-paints the preserved frame) and must survive reconnects.\n function stopBackgroundLoop() {\n if (bgLoopFrame !== null) video.cancelVideoFrameCallback?.(bgLoopFrame);\n bgLoopFrame = null;\n }\n function clearBackground() {\n stopBackgroundLoop();\n bgRects = null;\n // Resizing a canvas resets its bitmap; same-value assignment still clears.\n if (bgCanvas) bgCanvas.width = bgCanvas.width;\n }\n listen(image, \"load\", () => scheduleBackgroundDraw());\n // Older WebViews update the ambient layer on media progress, never with an\n // idle display-refresh loop. Geometry changes still get a one-shot repaint.\n listen(video, \"timeupdate\", () => {\n if (videoPresented && typeof video.requestVideoFrameCallback !== \"function\")\n scheduleBackgroundDraw();\n });\n function panBounds(r) {\n const vw = viewportWidth(),\n vh = viewportHeight();\n // Grow extra resting travel continuously from zero at fit to its full reach\n // by 1.5x, so even a light zoom can pull edge content clear of the overlaid\n // chrome. Never count the unused space of a fitting axis.\n // Each axis reaches at most 240 points or 40% of its own viewport.\n const ramp = Math.min(0.5, r.maxZoom - 1);\n const grown = ramp > 0 ? clamp((zoom - 1) / ramp) : 0;\n const axis = (viewport, content) => {\n const clearance = grown * Math.min(240, viewport * 0.4);\n return content <= viewport\n ? {\n min: (viewport - content) / 2 - clearance,\n max: (viewport - content) / 2 + clearance,\n }\n : { min: viewport - content - clearance, max: clearance };\n };\n const x = axis(vw, r.width),\n y = axis(vh, r.height);\n const bounds = {\n minX: viewportLeft() + x.min,\n maxX: viewportLeft() + x.max,\n minY: y.min + verticalOffset(r.height),\n maxY: y.max + verticalOffset(r.height),\n };\n // A camera position required to expose the cursor is a valid resting point,\n // not elastic overshoot. Preserve it across the next pan/pinch handoff.\n if (followRest) {\n const restX = viewportLeft() + vw / 2 - followRest.fx * r.width,\n restY = vh / 2 + verticalOffset(r.height) - followRest.fy * r.height;\n const weight =\n followRest.zoom > 1 ? clamp((zoom - 1) / (followRest.zoom - 1)) : 1;\n bounds.minX += Math.min(0, restX - bounds.minX) * weight;\n bounds.maxX += Math.max(0, restX - bounds.maxX) * weight;\n bounds.minY += Math.min(0, restY - bounds.minY) * weight;\n bounds.maxY += Math.max(0, restY - bounds.maxY) * weight;\n }\n return bounds;\n }\n const bounded = (v, min, max) => Math.max(min, Math.min(max, v));\n // Convert displayed overshoot back to finger travel before the next delta,\n // so reversing direction unwinds smoothly without an edge jump.\n function rubber(v, min, max, inverse = false) {\n const edge = bounded(v, min, max),\n d = v - edge;\n const reach = 40 + 40 * zoomProgress();\n return (\n edge +\n Math.sign(d) *\n (inverse\n ? (reach * Math.abs(d)) / Math.max(1, reach - Math.abs(d))\n : (reach * Math.abs(d)) / (reach + Math.abs(d)))\n );\n }\n function place(x, y, r) {\n fx = (viewportLeft() + viewportWidth() / 2 - x) / r.width;\n fy = (viewportHeight() / 2 + verticalOffset(r.height) - y) / r.height;\n }\n function cursorViewport() {\n const hotX = remoteCursor?.hotX ?? 9,\n hotY = remoteCursor?.hotY ?? 9;\n const w = remoteCursor?.width ?? 18,\n h = remoteCursor?.height ?? 18;\n const left = viewportLeft(),\n right = left + viewportWidth(),\n bottom = Math.max(1, stage.clientHeight - viewportBottomInset);\n // Keep the entire cursor, including its hotspot offset, clear of chrome.\n const minX = Math.min(right - 1, left + 8 + hotX),\n minY = Math.min(\n bottom - 1,\n (usesViewportInsets() ? viewportTopInset : 0) + 8 + hotY,\n );\n return {\n minX,\n maxX: Math.max(minX, right - 8 - (w - hotX)),\n minY,\n maxY: Math.max(minY, bottom - 8 - (h - hotY)),\n };\n }\n function moveTouchpad(dx, dy) {\n stopPanAnimation();\n const r = layout(),\n v = cursorViewport();\n if (cursorNeedsEntry) {\n // Re-enter at the nearest visible edge; do not pull a manually positioned\n // desktop back to the old off-screen cursor before applying this movement.\n cx = clamp((bounded(r.x + cx * r.width, v.minX, v.maxX) - r.x) / r.width);\n cy = clamp(\n (bounded(r.y + cy * r.height, v.minY, v.maxY) - r.y) / r.height,\n );\n cursorNeedsEntry = false;\n }\n cx = clamp(cx + dx / r.width);\n cy = clamp(cy + dy / r.height);\n const x = r.x + cx * r.width,\n y = r.y + cy * r.height;\n if (\n zoom > 1 ||\n r.width > viewportWidth() ||\n r.height > stage.clientHeight - viewportBottomInset\n ) {\n place(\n r.x + bounded(x, v.minX, v.maxX) - x,\n r.y + bounded(y, v.minY, v.maxY) - y,\n r,\n );\n followRest = { fx, fy, zoom };\n }\n manualViewMoved = false;\n }\n function stopPanAnimation() {\n if (panAnimation !== null) cancelAnimationFrame(panAnimation);\n panAnimation = null;\n }\n function settlePan() {\n stopPanAnimation();\n const r = layout(),\n b = panBounds(r),\n x = bounded(r.x, b.minX, b.maxX),\n y = bounded(r.y, b.minY, b.maxY);\n if (x === r.x && y === r.y) return;\n if (reducedMotion.matches) {\n place(x, y, r);\n render();\n return;\n }\n const started = performance.now();\n const tick = (now) => {\n const t = Math.min(1, (now - started) / 280),\n ease = 1 - Math.pow(1 - t, 3);\n place(r.x + (x - r.x) * ease, r.y + (y - r.y) * ease, r);\n render();\n panAnimation = t < 1 ? requestAnimationFrame(tick) : null;\n };\n panAnimation = requestAnimationFrame(tick);\n }\n function render() {\n const r = layout();\n if (config.nativeMedia && epoch)\n post({\n type: \"nativeViewport\",\n fillHeight: false,\n x: r.x,\n y: r.y,\n width: r.width,\n height: r.height,\n });\n if (config.desktop && epoch) {\n const scaleMode =\n desktopScale === null\n ? \"fit\"\n : desktopScale === 1\n ? \"actual\"\n : \"custom\";\n if (reportedScaleMode !== scaleMode) {\n reportedScaleMode = scaleMode;\n post({ type: \"scaleMode\", mode: scaleMode });\n }\n }\n const touchFeedback = control && mode === \"touch\" && touchCursorVisible;\n const cursorX = mode === \"touch\" && touchCursor ? touchCursor.x : cx;\n const cursorY = mode === \"touch\" && touchCursor ? touchCursor.y : cy;\n cursor.style.transition =\n mode === \"touch\" && !touchFeedback && !reducedMotion.matches\n ? \"opacity 120ms ease-out\"\n : \"none\";\n for (const el of [image, video]) {\n el.style.width = r.width + \"px\";\n el.style.height = r.height + \"px\";\n el.style.left = r.x + \"px\";\n el.style.top = r.y + \"px\";\n }\n clipNetworkStatus(r);\n paintBackground();\n if (remoteCursor) {\n cursor.style.width = remoteCursor.width + \"px\";\n cursor.style.height = remoteCursor.height + \"px\";\n cursor.style.border = \"0\";\n cursor.style.borderRadius = \"0\";\n cursor.style.transform = \"none\";\n cursor.style.left = r.x + cursorX * r.width - remoteCursor.hotX + \"px\";\n cursor.style.top = r.y + cursorY * r.height - remoteCursor.hotY + \"px\";\n cursor.style.display = \"block\";\n cursor.style.opacity = (\n mode === \"touch\"\n ? touchFeedback\n : remoteCursor.visible ||\n (control && mode === \"pointer\" && localCursorAwake)\n )\n ? \"1\"\n : \"0\";\n } else {\n cursor.style.opacity = (mode === \"touch\" ? !touchFeedback : false)\n ? \"0\"\n : \"1\";\n cursor.style.width = \"18px\";\n cursor.style.height = \"18px\";\n cursor.style.border = \"2px solid var(--foreground)\";\n cursor.style.borderRadius = \"50%\";\n cursor.style.transform = \"translate(-50%,-50%)\";\n cursor.style.left = r.x + cursorX * r.width + \"px\";\n cursor.style.top = r.y + cursorY * r.height + \"px\";\n cursor.style.display =\n !config.desktop && control && (mode === \"pointer\" || mode === \"touch\")\n ? \"block\"\n : \"none\";\n }\n if (config.desktop) {\n // Let the local OS own pointer size, DPI and accessibility preferences.\n // Never use a remote URL or bitmap as the desktop's native cursor.\n cursor.style.display = \"none\";\n const shape = remoteCursor?.shape;\n stage.style.cursor =\n control &&\n [\n \"default\",\n \"text\",\n \"vertical-text\",\n \"pointer\",\n \"crosshair\",\n \"grab\",\n \"grabbing\",\n \"ew-resize\",\n \"ns-resize\",\n \"nwse-resize\",\n \"nesw-resize\",\n \"move\",\n \"not-allowed\",\n \"copy\",\n \"alias\",\n \"wait\",\n \"progress\",\n \"help\",\n ].includes(shape)\n ? shape\n : \"default\";\n }\n }\n // Literal source is required: Hermes function.toString() yields bytecode.\n function validCursor(v) {\n return (\n !!v &&\n typeof v === \"object\" &&\n typeof v.visible === \"boolean\" &&\n [v.x, v.y, v.width, v.height, v.hotX, v.hotY].every(Number.isFinite) &&\n v.x >= 0 &&\n v.x <= 1 &&\n v.y >= 0 &&\n v.y <= 1 &&\n v.width > 0 &&\n v.width <= 256 &&\n v.height > 0 &&\n v.height <= 256 &&\n v.hotX >= 0 &&\n v.hotX <= v.width &&\n v.hotY >= 0 &&\n v.hotY <= v.height &&\n typeof v.png === \"string\" &&\n v.png.length <= 65536 &&\n /^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/.test(v.png)\n );\n }\n function receiveCursor(value) {\n if (value === null) {\n if (remoteCursor) {\n remoteCursor = { ...remoteCursor, visible: false };\n render();\n }\n return;\n }\n if (!validCursor(value)) return;\n if (!remoteCursor || remoteCursor.png !== value.png)\n cursorImage.src = \"data:image/png;base64,\" + value.png;\n // Keep delayed host coordinates from pulling the local touchpad backwards.\n if (\n !remoteCursor ||\n !control ||\n mode !== \"pointer\" ||\n (!pointers.size && performance.now() - lastLocalMove > 200)\n ) {\n cx = value.x;\n cy = value.y;\n }\n if (value.visible) localCursorAwake = false;\n remoteCursor = value;\n render();\n }\n function resetCursor() {\n clearTimeout(touchCursorTimer);\n touchCursorVisible = false;\n touchCursor = null;\n localCursorAwake = false;\n remoteCursor = null;\n cursorImage.removeAttribute(\"src\");\n render();\n }\n function queue(event) {\n if (!control) return;\n if (!pending.length) pendingSince = performance.now();\n // Remote visibility can remain hidden after synthetic mouse movement. Wake\n // the local touchpad cursor until the host reports a visible cursor again.\n if (event.kind === \"move\" && mode === \"pointer\") localCursorAwake = true;\n if (event.kind === \"key\" || event.kind === \"text\") {\n localCursorAwake = false;\n render();\n }\n if (event.kind === \"move\" || event.kind === \"button\")\n lastLocalMove = performance.now();\n const tail = pending[pending.length - 1];\n if (event.kind === \"move\" && tail?.kind === \"move\")\n pending[pending.length - 1] = event;\n // Coalesce only adjacent scrolls, preserving button/key ordering. Bound the\n // accumulated distance so a delayed ACK cannot replay a large scroll backlog.\n else if (event.kind === \"scroll\" && tail?.kind === \"scroll\") {\n tail.dx = Math.max(-2000, Math.min(2000, tail.dx + event.dx));\n tail.dy = Math.max(-2000, Math.min(2000, tail.dy + event.dy));\n } else pending.push(event);\n if (pending.length > 64) {\n pending = [{ kind: \"release\" }];\n control = false;\n post({ type: \"inputOverflow\" });\n }\n }\n function flush() {\n if (!pending.length) return;\n // A paste shortcut waits for the controller to push the local clipboard\n // first. That hold is deliberate (and each further paste re-arms it), so\n // the batch's freshness clock only starts once the gate opens.\n if (inputGateUntil) {\n if (performance.now() < inputGateUntil) return;\n inputGateUntil = 0;\n pendingSince = performance.now();\n }\n // Input is an intent about the picture the user saw, not durable work.\n // Never replay old clicks/typing after a stalled ACK or data channel drains.\n if (performance.now() - pendingSince >= 2000) {\n pending = [];\n control = false;\n release();\n updateMouseButtons();\n post({ type: \"inputOverflow\" });\n return;\n }\n if (sending) return;\n // Do not route around a congested live data channel: the relay could\n // overtake its already-buffered key/button events and reorder input.\n if (pc?.connectionState === \"connected\" && dc?.readyState === \"open\" && dc.bufferedAmount >= 16384) return;\n const events = pending.splice(0, 64),\n sequence = ++seq;\n if (\n pc?.connectionState === \"connected\" &&\n dc &&\n dc.readyState === \"open\" &&\n dc.bufferedAmount < 16384\n ) {\n try {\n dc.send(JSON.stringify({ sequence, events }));\n } catch {\n pending = [];\n control = false;\n release();\n post({ type: \"inputOverflow\" });\n }\n } else {\n sending = true;\n post({ type: \"input\", sequence, events });\n }\n }\n const inputTimer = setInterval(() => {\n // Hold displacement controls speed, even without further pointer moves.\n // Skip missed ticks while awaiting ACK instead of building a scroll backlog.\n if (wheelY?.moved && !sending) {\n const offset = Math.max(-24, Math.min(24, wheelY.y - wheelY.start));\n if (Math.abs(offset) > 4)\n scrollMouse(Math.sign(offset) * (Math.abs(offset) - 4) * 1.5);\n }\n flush();\n }, 33);\n cleanups.push(() => clearInterval(inputTimer));\n function release() {\n stopEdgePan();\n desktopPan = null;\n clearTimeout(hold);\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n gestureFrame = null;\n // A paste still waiting for its clipboard push is abandoned, never sent\n // late; the release itself must reach the computer at once.\n if (inputGateUntil) {\n inputGateUntil = 0;\n pending = [];\n }\n if (control) {\n queue({ kind: \"release\" });\n flush();\n }\n heldMouse.clear();\n resetWheel();\n updateMouseButtons();\n drag = false;\n pointers.clear();\n start = null;\n last = null;\n multi = null;\n }\n function updateMouseButtons() {\n mouseButtons.style.display =\n showMouseButtons && control && !nativeMouseControls ? \"block\" : \"none\";\n for (const [name, button] of [\n [\"left\", 0],\n [\"right\", 2],\n ])\n find(\"mouse-\" + name).setAttribute(\n \"aria-pressed\",\n String(heldMouse.has(button)),\n );\n }\n for (const [name, button] of [\n [\"left\", 0],\n [\"right\", 2],\n ]) {\n const el = find(\"mouse-\" + name);\n listenMouse(el, \"pointerdown\", (e) => {\n e.preventDefault();\n if (!control || !showMouseButtons || heldMouse.has(button)) return;\n clearTimeout(hold);\n if (!e.nativeInput) el.setPointerCapture(e.pointerId);\n heldMouse.set(button, e.pointerId);\n queue({ kind: \"button\", button, down: true, x: cx, y: cy });\n flush();\n updateMouseButtons();\n });\n const up = (e) => {\n e.preventDefault();\n if (heldMouse.get(button) !== e.pointerId) return;\n heldMouse.delete(button);\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n flush();\n updateMouseButtons();\n };\n listenMouse(el, \"pointerup\", up);\n listenMouse(el, \"pointercancel\", up);\n listenMouse(el, \"lostpointercapture\", up);\n listenMouse(el, \"click\", (e) => {\n if (e.detail === 0 && control && showMouseButtons) {\n click(button);\n flush();\n }\n });\n }\n const scrollMouse = (dy) => {\n if (control && showMouseButtons && Number.isFinite(dy)) {\n queue({ kind: \"scroll\", dx: 0, dy: Math.max(-2000, Math.min(2000, dy)) });\n }\n };\n listenMouse(wheel, \"pointerdown\", (e) => {\n e.preventDefault();\n if (!control || !showMouseButtons || wheelY) return;\n if (!e.nativeInput) wheel.setPointerCapture(e.pointerId);\n wheelY = { id: e.pointerId, y: e.clientY, start: e.clientY, moved: false };\n });\n // A small dead zone preserves middle clicks; displacement drives the timer.\n listenMouse(wheel, \"pointermove\", (e) => {\n if (!wheelY || wheelY.id !== e.pointerId) return;\n e.preventDefault();\n wheelGrip.style.transform =\n \"translateY(\" +\n Math.max(-24, Math.min(24, e.clientY - wheelY.start)) +\n \"px)\";\n wheelY.y = e.clientY;\n if (Math.abs(e.clientY - wheelY.start) > 4) wheelY.moved = true;\n });\n listenMouse(wheel, \"pointerup\", (e) => {\n if (!wheelY || wheelY.id !== e.pointerId) return;\n e.preventDefault();\n if (!wheelY.moved && control && showMouseButtons) {\n click(1);\n flush();\n }\n resetWheel();\n });\n const cancelWheel = (e) => {\n if (wheelY?.id === e.pointerId) resetWheel();\n };\n listenMouse(wheel, \"pointercancel\", cancelWheel);\n listenMouse(wheel, \"lostpointercapture\", cancelWheel);\n listenMouse(wheel, \"click\", (e) => {\n if (e.detail === 0 && control && showMouseButtons) {\n click(1);\n flush();\n }\n });\n listenMouse(wheel, \"keydown\", (e) => {\n if (e.key === \"ArrowUp\" || e.key === \"ArrowDown\") {\n e.preventDefault();\n scrollMouse(e.key === \"ArrowUp\" ? -120 : 120);\n }\n });\n function insideDesktop(p) {\n const r = layout();\n return (\n p.x >= r.x && p.x <= r.x + r.width && p.y >= r.y && p.y <= r.y + r.height\n );\n }\n function point(p) {\n const r = layout();\n return {\n x: clamp((p.x - r.x) / r.width),\n y: clamp((p.y - r.y) / r.height),\n };\n }\n const desktopPoint = (e) => {\n const bounds = stage.getBoundingClientRect();\n return { x: e.clientX - bounds.left, y: e.clientY - bounds.top };\n };\n function stopEdgePan() {\n if (edgeFrame !== null) cancelAnimationFrame(edgeFrame);\n edgeFrame = null;\n edgePointer = null;\n }\n function edgePanTick(now) {\n edgeFrame = null;\n if (!edgePointer || desktopPan || !epoch) return;\n const r = layout(),\n vw = viewportWidth(),\n vh = viewportHeight();\n const p = edgePointer;\n const dt = Math.min(32, Math.max(0, now - edgeTime)) / 1000;\n edgeTime = now;\n // rAF timestamps describe the frame start and can precede the pointer\n // handler's performance.now(). A zero-time first frame is not a boundary.\n if (dt === 0) {\n edgeFrame = requestAnimationFrame(edgePanTick);\n return;\n }\n // A narrow edge band accelerates smoothly to 720 local pixels per second.\n const velocity = (position, extent) => {\n const band = Math.min(28, extent / 4);\n return position < band\n ? -(1 - position / band)\n : position > extent - band\n ? (position - extent + band) / band\n : 0;\n };\n const x =\n r.width > vw\n ? bounded(\n r.x - velocity(p.x - viewportLeft(), vw) * 720 * dt,\n viewportLeft() + vw - r.width,\n viewportLeft(),\n )\n : r.x;\n const y =\n r.height > vh\n ? bounded(r.y - velocity(p.y, vh) * 720 * dt, vh - r.height, 0)\n : r.y;\n if (Math.abs(x - r.x) < 0.001 && Math.abs(y - r.y) < 0.001) return;\n stopPanAnimation();\n manualViewMoved = true;\n place(x, y, r);\n // Keep remote hover/drag attached to the local pointer as the picture moves.\n if (control) {\n const next = point(p);\n cx = next.x;\n cy = next.y;\n queue({ kind: \"move\", x: cx, y: cy });\n }\n render();\n edgeFrame = requestAnimationFrame(edgePanTick);\n }\n function trackEdgePointer(e) {\n const p = desktopPoint(e);\n if (\n !epoch ||\n desktopPan ||\n p.x < viewportLeft() ||\n p.x > viewportLeft() + viewportWidth() ||\n p.y < 0 ||\n p.y > viewportHeight() ||\n !insideDesktop(p)\n ) {\n stopEdgePan();\n return;\n }\n edgePointer = p;\n if (edgeFrame === null) {\n edgeTime = performance.now();\n edgeFrame = requestAnimationFrame(edgePanTick);\n }\n }\n listen(stage, \"pointerleave\", stopEdgePan);\n function mouse(e, down) {\n if (!control || ![0, 1, 2].includes(e.button)) return;\n const local = desktopPoint(e);\n if (down && !insideDesktop(local)) return;\n const p = point(local);\n cx = p.x;\n cy = p.y;\n if (down) {\n showKeyboard(true);\n stage.setPointerCapture(e.pointerId);\n heldMouse.set(e.button, e.pointerId);\n } else if (!heldMouse.delete(e.button)) return;\n queue({ kind: \"button\", button: e.button, down, x: cx, y: cy });\n flush();\n render();\n }\n function click(button = 0) {\n if (control && mode === \"touch\") {\n clearTimeout(touchCursorTimer);\n touchCursor = { x: cx, y: cy };\n touchCursorVisible = true;\n render();\n touchCursorTimer = setTimeout(() => {\n touchCursorVisible = false;\n render();\n }, 450);\n }\n queue({ kind: \"button\", button, down: true, x: cx, y: cy });\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n }\n function pan(dx, dy) {\n manualViewMoved = true;\n cursorNeedsEntry = true;\n stopPanAnimation();\n const r = layout(),\n b = panBounds(r);\n place(\n rubber(rubber(r.x, b.minX, b.maxX, true) + dx, b.minX, b.maxX),\n rubber(rubber(r.y, b.minY, b.maxY, true) + dy, b.minY, b.maxY),\n r,\n );\n render();\n }\n function pair() {\n const [a, b] = [...pointers.values()];\n return {\n x: (a.x + b.x) / 2,\n y: (a.y + b.y) / 2,\n d: Math.hypot(a.x - b.x, a.y - b.y),\n };\n }\n function movePair() {\n gestureFrame = null;\n if (pointers.size < 2 || !multi) return;\n const next = pair(),\n span = Math.abs(next.d - multi.d),\n travel = Math.hypot(next.x - multi.x, next.y - multi.y);\n if (multi.kind !== \"pinch\") {\n const pinchSlop = Math.max(6, Math.min(12, multi.d * 0.04));\n if (span >= pinchSlop && span > travel * 0.65) {\n // A parallel scroll may deliver its two pointer updates in different\n // frames. Confirm separation briefly before taking over as a pinch.\n if (!multi.candidate)\n multi.candidate = {\n at: Date.now(),\n d: next.d,\n zoom,\n anchor: point(next),\n };\n if (Date.now() - multi.candidate.at >= 40) {\n if (multi.kind === \"scroll\") {\n multi.d = multi.candidate.d;\n multi.zoom = multi.candidate.zoom;\n multi.anchor = multi.candidate.anchor;\n }\n multi.kind = \"pinch\";\n multi.candidate = null;\n } else {\n gestureFrame = requestAnimationFrame(movePair);\n return;\n }\n } else {\n multi.candidate = null;\n if (!multi.kind && travel > 8 && travel > span) {\n multi.kind = \"scroll\";\n multi.restX = 0;\n multi.restY = 0;\n multi.aimed = mode !== \"touch\";\n }\n }\n }\n if (multi.kind === \"pinch\") {\n manualViewMoved = true;\n cursorNeedsEntry = true;\n const { maxZoom } = layout();\n zoom = Math.max(\n 1,\n Math.min(\n maxZoom,\n (Math.min(maxZoom, multi.zoom) * next.d) / Math.max(1, multi.d),\n ),\n );\n const r = layout();\n fx =\n multi.anchor.x +\n (viewportLeft() + viewportWidth() / 2 - next.x) / r.width;\n fy =\n multi.anchor.y +\n (viewportHeight() / 2 + verticalOffset(r.height) - next.y) / r.height;\n const moved = layout(),\n b = panBounds(moved);\n place(\n rubber(moved.x, b.minX, b.maxX),\n rubber(moved.y, b.minY, b.maxY),\n moved,\n );\n } else if (multi.kind === \"scroll\") {\n const dx = next.x - multi.lastX,\n dy = next.y - multi.lastY;\n if (control && mode !== \"pan\") {\n // Hosts scroll whatever is under the desktop cursor. Touch mode has no\n // visible pointer, so aim it at the fingers once they are over the\n // desktop; like taps, scrolling over the letterbox does nothing.\n if (!multi.aimed && insideDesktop(next)) {\n const p = point(next);\n cx = p.x;\n cy = p.y;\n queue({ kind: \"move\", x: cx, y: cy });\n multi.aimed = true;\n }\n // Hosts inject whole pixels; carry fractions so slow drags still scroll.\n const sx = multi.restX - dx,\n sy = multi.restY - dy,\n wx = Math.trunc(sx),\n wy = Math.trunc(sy);\n multi.restX = sx - wx;\n multi.restY = sy - wy;\n if (multi.aimed && (wx || wy))\n queue({\n kind: \"scroll\",\n dx: Math.max(-2000, Math.min(2000, wx)),\n dy: Math.max(-2000, Math.min(2000, wy)),\n });\n } else pan(dx, dy);\n }\n if (multi.kind) {\n multi.lastX = next.x;\n multi.lastY = next.y;\n }\n render();\n }\n listen(stage, \"pointerdown\", (e) => {\n if (config.desktop) {\n e.preventDefault();\n if (\n e.button === 1 &&\n (layout().width > viewportWidth() || layout().height > viewportHeight())\n ) {\n stopEdgePan();\n stopPanAnimation();\n desktopPan = {\n id: e.pointerId,\n x: e.clientX,\n y: e.clientY,\n start: e,\n moved: false,\n };\n stage.setPointerCapture(e.pointerId);\n return;\n }\n mouse(e, true);\n return;\n }\n e.preventDefault();\n stopPanAnimation();\n stage.setPointerCapture(e.pointerId);\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (pointers.size === 1) {\n cursorNeedsEntry = true;\n start = { x: e.clientX, y: e.clientY };\n last = start;\n moved = false;\n hold = setTimeout(() => {\n if (\n control &&\n mode !== \"pan\" &&\n !moved &&\n pointers.size === 1 &&\n !heldMouse.size &&\n (mode !== \"touch\" || insideDesktop(start))\n ) {\n if (mode === \"touch\") {\n const p = point(start);\n cx = p.x;\n cy = p.y;\n }\n queue({ kind: \"button\", button: 0, down: true, x: cx, y: cy });\n drag = true;\n }\n }, 400);\n } else {\n clearTimeout(hold);\n if (drag) queue({ kind: \"release\" });\n drag = false;\n start = null;\n const p = pair();\n multi = {\n ...p,\n lastX: p.x,\n lastY: p.y,\n zoom,\n anchor: point(p),\n kind: null,\n };\n }\n });\n listen(stage, \"pointermove\", (e) => {\n if (config.desktop) {\n if (desktopPan?.id === e.pointerId) {\n const dx = e.clientX - desktopPan.x,\n dy = e.clientY - desktopPan.y;\n if (!desktopPan.moved && Math.hypot(dx, dy) < 3) return;\n desktopPan.moved = true;\n desktopPan.x = e.clientX;\n desktopPan.y = e.clientY;\n pan(dx, dy);\n return;\n }\n trackEdgePointer(e);\n if (!control) return;\n const local = desktopPoint(e);\n if (!heldMouse.size && !insideDesktop(local)) return;\n const p = point(local);\n cx = p.x;\n cy = p.y;\n queue({ kind: \"move\", x: cx, y: cy });\n render();\n return;\n }\n if (!pointers.has(e.pointerId)) return;\n e.preventDefault();\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (pointers.size >= 2) {\n if (gestureFrame === null) gestureFrame = requestAnimationFrame(movePair);\n return;\n }\n if (!start || !last) return;\n const now = { x: e.clientX, y: e.clientY },\n dx = now.x - last.x,\n dy = now.y - last.y;\n last = now;\n if (Math.hypot(now.x - start.x, now.y - start.y) > 6) {\n moved = true;\n clearTimeout(hold);\n }\n if (\n !control ||\n mode === \"pan\" ||\n (mode === \"touch\" && !drag && !heldMouse.size)\n ) {\n pan(dx, dy);\n return;\n }\n if (mode === \"pointer\") {\n moveTouchpad(dx, dy);\n } else {\n const p = point(now);\n cx = p.x;\n cy = p.y;\n }\n queue({ kind: \"move\", x: cx, y: cy });\n render();\n });\n function up(e) {\n if (config.desktop) {\n if (desktopPan?.id === e.pointerId) {\n const gesture = desktopPan;\n desktopPan = null;\n if (gesture.moved) settlePan();\n else {\n mouse(gesture.start, true);\n mouse(e, false);\n }\n return;\n }\n mouse(e, false);\n return;\n }\n if (!pointers.has(e.pointerId)) return;\n clearTimeout(hold);\n if (pointers.size >= 2 && multi) {\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n movePair();\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n gestureFrame = null;\n }\n pointers.delete(e.pointerId);\n if (drag) {\n queue({ kind: \"button\", button: 0, down: false, x: cx, y: cy });\n drag = false;\n } else if (\n start &&\n !moved &&\n control &&\n mode !== \"pan\" &&\n !heldMouse.size &&\n e.type === \"pointerup\" &&\n (mode !== \"touch\" || insideDesktop({ x: e.clientX, y: e.clientY }))\n ) {\n if (mode === \"touch\") {\n const p = point({ x: e.clientX, y: e.clientY });\n cx = p.x;\n cy = p.y;\n }\n click();\n }\n start = null;\n last = null;\n multi = null;\n render();\n if (!pointers.size && manualViewMoved) settlePan();\n }\n listen(stage, \"pointerup\", up);\n listen(stage, \"pointercancel\", () => {\n release();\n settlePan();\n });\n listen(stage, \"lostpointercapture\", () => {\n desktopPan = null;\n if (config.desktop && heldMouse.size) release();\n });\n let wheelRestX = 0,\n wheelRestY = 0;\n if (config.desktop)\n listen(\n stage,\n \"wheel\",\n (e) => {\n e.preventDefault();\n if (!control) {\n wheelRestX = wheelRestY = 0;\n return;\n }\n const factor =\n e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? stage.clientHeight : 1;\n // Hosts inject whole pixels; carry fractions so slow trackpad and\n // scaled-display deltas still scroll.\n const sx = wheelRestX + e.deltaX * factor,\n sy = wheelRestY + e.deltaY * factor,\n wx = Math.trunc(sx) || 0,\n wy = Math.trunc(sy) || 0;\n wheelRestX = sx - wx;\n wheelRestY = sy - wy;\n if (!wx && !wy) return;\n queue({\n kind: \"scroll\",\n dx: Math.max(-2000, Math.min(2000, wx)),\n dy: Math.max(-2000, Math.min(2000, wy)),\n });\n // Let the existing input tick coalesce trackpad bursts. Key/button\n // edges still flush immediately, preserving their order with scrolls.\n },\n { passive: false },\n );\n listen(config.desktop ? stage : document, \"contextmenu\", (e) =>\n e.preventDefault(),\n );\n // Scope selection suppression to the desktop surface, preserving the hidden\n // textarea's native keyboard/IME editing and programmatic selection.\n listen(stage, \"selectstart\", (e) => e.preventDefault());\n listen(stage, \"dragstart\", (e) => e.preventDefault());\n const normalizedKey = (code) =>\n /^(Shift|Control|Alt|Meta)Right$/.test(code)\n ? code.replace(/Right$/, \"Left\")\n : code;\n // Remote key state: a key is held from its first keydown until its keyup.\n // macOS sends no keyup for keys first pressed while Command is held (Cmd+C);\n // only those are released together with Command. Membership is decided once,\n // on the not-held -> held transition, so auto-repeat never reclassifies a key.\n const hardwareKeys = new Set();\n const commandKeys = new Set();\n const isModifier = (code) => /^(Shift|Control|Alt|Meta)Left$/.test(code);\n function pressKey(code) {\n if (!hardwareKeys.has(code)) {\n if (macKeyboard && hardwareKeys.has(\"MetaLeft\") && !isModifier(code))\n commandKeys.add(code);\n hardwareKeys.add(code);\n }\n queue({ kind: \"key\", code, down: true });\n }\n function releaseKey(code, send) {\n commandKeys.delete(code);\n if (!hardwareKeys.delete(code)) return false;\n if (code === \"MetaLeft\") {\n for (const held of commandKeys)\n if (hardwareKeys.delete(held) && send)\n queue({ kind: \"key\", code: held, down: false });\n commandKeys.clear();\n }\n if (send) queue({ kind: \"key\", code, down: false });\n return send;\n }\n function forgetKeys() {\n hardwareKeys.clear();\n commandKeys.clear();\n }\n // Desktop only. Cmd/Ctrl+V holds the queue until the controller has pushed\n // the local clipboard (or `inputGate` / the deadline releases it); Cmd/Ctrl+C\n // and +X ask it to pull the computer's new copy soon after. Both are intents:\n // the keys themselves still reach the computer unchanged.\n function clipboardShortcut(e, code) {\n const chord = clipboardModifier === \"meta\" ? e.metaKey : e.ctrlKey;\n if (!config.desktop || e.repeat || e.altKey || !chord) return;\n if (code === \"KeyV\") {\n inputGateUntil = performance.now() + 1200;\n post({ type: \"clipboardIntent\", action: \"paste\" });\n } else if (code === \"KeyC\" || code === \"KeyX\")\n post({ type: \"clipboardIntent\", action: \"copy\" });\n }\n listen(document, \"keydown\", (e) => {\n if (config.desktop) {\n if (e.ctrlKey && e.altKey && e.code === \"Escape\") {\n e.preventDefault();\n release();\n showKeyboard(false);\n post({ type: \"releaseFocus\" });\n return;\n }\n if (\n document.activeElement !== keyboardInput ||\n e.isComposing ||\n composing\n )\n return;\n }\n // The focused textarea delivers characters through input (and editing\n // keys through beforeinput). Forwarding their keydown too types twice on\n // iOS, where the software keyboard reports both events.\n if (\n (config.desktop || keyboardEnabled) &&\n document.activeElement === keyboardInput &&\n !e.ctrlKey &&\n !e.metaKey &&\n !e.altKey &&\n (e.key?.length === 1 ||\n e.key === \"Process\" ||\n e.key === \"Dead\" ||\n (keyboardEnabled && [\"Backspace\", \"Enter\"].includes(e.code)))\n )\n return;\n if (control && validKeys.has(normalizedKey(e.code))) {\n e.preventDefault();\n const code = normalizedKey(e.code);\n clipboardShortcut(e, code);\n pressKey(code);\n }\n });\n listen(document, \"keyup\", (e) => {\n const code = normalizedKey(e.code);\n if (releaseKey(code, control && validKeys.has(code))) e.preventDefault();\n });\n if (config.desktop)\n listen(keyboardInput, \"blur\", () => {\n forgetKeys();\n release();\n });\n listen(window, \"blur\", () => {\n release();\n settlePan();\n });\n function reportViewport() {\n post({\n type: \"viewportChanged\",\n width: viewportWidth(),\n height: usableHeight(),\n });\n }\n const observer = new ResizeObserver(() => {\n statusOrigin = null;\n reportViewport();\n release();\n settlePan();\n render();\n });\n observer.observe(stage);\n cleanups.push(\n () => observer.disconnect(),\n () => stopPanAnimation(),\n () => stopBackgroundLoop(),\n () => clearTimeout(touchCursorTimer),\n );\n // Keep one bounded frame in this document only; never persist desktop pixels.\n // Snapshot before detaching the track. A JPEG fallback already lives in image.\n function retainFrame() {\n if (\n !videoPresented ||\n video.style.display !== \"block\" ||\n video.readyState < 2 ||\n !video.videoWidth ||\n !video.videoHeight\n )\n return;\n const canvas = document.createElement(\"canvas\");\n try {\n const scale = Math.min(\n 1,\n 1280 / Math.max(video.videoWidth, video.videoHeight),\n );\n canvas.width = Math.max(1, Math.round(video.videoWidth * scale));\n canvas.height = Math.max(1, Math.round(video.videoHeight * scale));\n const context = canvas.getContext(\"2d\");\n if (context) {\n context.drawImage(video, 0, 0, canvas.width, canvas.height);\n image.src = canvas.toDataURL(\"image/jpeg\", 0.7);\n }\n } catch {\n /* Keep the previous compatibility frame if WebKit cannot read video. */\n } finally {\n canvas.width = 0;\n canvas.height = 0;\n }\n }\n /* BEGIN RTC */\n\n let trickleIce = false,\n attemptId = null,\n retries = 0,\n exchangeId = 0;\n let configPending = false;\n let videoPresented = false,\n videoFrameCallback = null,\n videoPaintCallback = null;\n function cancelVideoHandoff() {\n if (videoFrameCallback !== null)\n video.cancelVideoFrameCallback?.(videoFrameCallback);\n if (videoPaintCallback !== null) cancelAnimationFrame(videoPaintCallback);\n videoFrameCallback = videoPaintCallback = null;\n }\n function revealVideo(g) {\n post({ type: \"videoFrameReady\", attemptId });\n // Keep the JPEG decoded and painted as a backing layer. Promote the video\n // only after its first frame; removing the image exposes WebKit repaint gaps.\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = null;\n videoPresented = true;\n video.style.zIndex = \"2\";\n if (typeof startBackgroundLoop === \"function\") startBackgroundLoop();\n post({ type: \"streaming\", attemptId });\n post({\n type: \"pipCapability\",\n supported: !!(\n video.webkitSupportsPresentationMode?.(\"picture-in-picture\") ||\n document.pictureInPictureEnabled\n ),\n });\n });\n });\n }\n function waitForVideoFrame(g) {\n if (g !== generation) return;\n if (\n video.readyState >= 2 &&\n video.videoWidth > 0 &&\n video.videoHeight > 0\n ) {\n revealVideo(g);\n return;\n }\n videoPaintCallback = requestAnimationFrame(() => waitForVideoFrame(g));\n }\n let retryTimer = null,\n deadlineTimer = null,\n disconnectTimer = null,\n stableTimer = null,\n iceTimer = null,\n gatherTimer = null,\n gatherDone = null;\n let localCandidates = [],\n localAck = 0,\n remoteAfter = 0,\n icePending = null,\n remoteSeen = new Set(),\n exchangeUntil = 0,\n remoteComplete = false;\n function clearRtcTimers() {\n for (const timer of [\n retryTimer,\n deadlineTimer,\n disconnectTimer,\n stableTimer,\n iceTimer,\n gatherTimer,\n ])\n clearTimeout(timer);\n retryTimer =\n deadlineTimer =\n disconnectTimer =\n stableTimer =\n iceTimer =\n gatherTimer =\n null;\n if (gatherDone) {\n gatherDone();\n gatherDone = null;\n }\n }\n function closeRtc(preserveFrame = true) {\n configPending = false;\n if (preserveFrame) retainFrame();\n generation++;\n clearRtcTimers();\n cancelVideoHandoff();\n videoPresented = false;\n localCandidates = [];\n localAck = remoteAfter = 0;\n icePending = null;\n remoteSeen = new Set();\n attemptId = null;\n clearInterval(statsTimer);\n statsTimer = null;\n statsSample = null;\n if (dc) dc.close();\n if (pc) pc.close();\n pc = null;\n dc = null;\n video.onplaying = null;\n video.srcObject = null;\n video.style.display = \"none\";\n video.style.zIndex = \"0\";\n image.style.display = \"block\";\n if (typeof stopBackgroundLoop === \"function\") stopBackgroundLoop();\n if (!preserveFrame) {\n image.removeAttribute(\"src\");\n if (typeof clearBackground === \"function\") clearBackground();\n }\n }\n function failRtc(reason, canRetry = true) {\n const failedAttempt = attemptId;\n release();\n closeRtc();\n post({ type: \"fallback\", attemptId: failedAttempt, reason });\n // Local consent is bounded by the host's picker lifetime. Reuse this retry\n // timer without consuming the finite network-recovery attempts.\n const capturePending = reason === \"capture-pending\";\n if (canRetry && epoch && (capturePending || retries < net.retryMs.length)) {\n const delay = capturePending\n ? net.retryMs[net.retryMs.length - 1]\n : net.retryMs[retries++];\n retryTimer = setTimeout(() => {\n retryTimer = null;\n if (epoch) connect();\n }, delay);\n }\n }\n function pollIce() {\n if (\n !pc ||\n !trickleIce ||\n !pc.remoteDescription ||\n icePending ||\n Date.now() >= exchangeUntil\n )\n return;\n const candidates = localCandidates.slice(\n localAck,\n localAck + net.batchSize,\n );\n icePending = {\n after: remoteAfter,\n sent: candidates.length,\n exchangeId: ++exchangeId,\n };\n post({\n type: \"ice\",\n attemptId,\n candidates,\n after: remoteAfter,\n exchangeId,\n });\n iceTimer = setTimeout(() => {\n icePending = null;\n pollIce();\n }, 4500);\n }\n async function receiveIce(message) {\n if (\n !pc ||\n !icePending ||\n message.attemptId !== attemptId ||\n message.exchangeId !== icePending.exchangeId\n )\n return;\n const rtc = pc,\n g = generation,\n batch = icePending;\n clearTimeout(iceTimer);\n try {\n if (message.error) {\n icePending = null;\n iceTimer = setTimeout(pollIce, 1000);\n return;\n }\n if (\n !Array.isArray(message.candidates) ||\n message.candidates.length > net.batchSize ||\n message.next !== batch.after + message.candidates.length ||\n message.next > net.maxCandidates\n )\n throw new Error();\n for (const candidate of message.candidates) {\n if (g !== generation) return;\n const key = JSON.stringify(candidate);\n if (remoteSeen.has(key)) continue;\n if (remoteSeen.size >= net.maxCandidates) throw new Error();\n await rtc.addIceCandidate(candidate);\n if (g !== generation) return;\n remoteSeen.add(key);\n }\n if (g !== generation) return;\n localAck += batch.sent;\n remoteAfter = message.next;\n remoteComplete = message.complete === true;\n icePending = null;\n if (!(\n remoteComplete &&\n rtc.iceGatheringState === \"complete\" &&\n localAck === localCandidates.length\n ))\n iceTimer = setTimeout(pollIce, net.pollMs);\n } catch {\n if (g === generation) failRtc(\"candidates\");\n }\n }\n async function receiveAnswer(message) {\n if (!pc || message.attemptId !== attemptId) return;\n const rtc = pc,\n g = generation;\n try {\n await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n if (g !== generation) return;\n clearTimeout(deadlineTimer);\n deadlineTimer = setTimeout(() => {\n if (g === generation && rtc.connectionState !== \"connected\")\n failRtc(\"connect-timeout\");\n }, net.connectMs);\n exchangeUntil = Date.now() + net.exchangeMs;\n pollIce();\n } catch {\n if (g === generation) failRtc(\"answer\");\n }\n }\n async function connect() {\n closeRtc();\n const g = generation;\n attemptId = String(g);\n if (!window.RTCPeerConnection) {\n failRtc(\"unsupported\", false);\n return;\n }\n configPending = true;\n deadlineTimer = setTimeout(\n () => {\n if (g === generation && configPending) {\n configPending = false;\n void startRtc(g, iceServers);\n }\n },\n (net.iceConfigMs ?? 8000) + (net.iceConfigBridgeMs ?? 500),\n );\n return post({ type: \"iceConfig\", attemptId });\n }\n async function receiveIceConfig(message) {\n if (!epoch || !configPending || message.attemptId !== attemptId) return;\n configPending = false;\n clearTimeout(deadlineTimer);\n deadlineTimer = null;\n await startRtc(generation, message.iceServers);\n }\n async function startRtc(g, servers) {\n try {\n const rtc = new RTCPeerConnection({ iceServers: servers });\n pc = rtc;\n dc = rtc.createDataChannel(\"input-v1\");\n rtc.addTransceiver(\"video\", { direction: \"recvonly\" });\n rtc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n rtc.onicecandidate = ({ candidate }) => {\n if (g !== generation || !candidate?.candidate || !trickleIce) return;\n if (localCandidates.length >= net.maxCandidates) {\n failRtc(\"candidate-limit\", false);\n return;\n }\n localCandidates.push({\n candidate: candidate.candidate,\n sdpMid: candidate.sdpMid,\n sdpMLineIndex: candidate.sdpMLineIndex,\n ...(candidate.usernameFragment\n ? { usernameFragment: candidate.usernameFragment }\n : {}),\n });\n // Gathering continues after the offer; the serial exchange flushes late addresses.\n };\n dc.onmessage = (e) => {\n try {\n if (g !== generation || pc !== rtc) return;\n if (typeof e.data !== \"string\" || e.data.length > 80000) return;\n const message = JSON.parse(e.data);\n if (message.type === \"cursor\") receiveCursor(message.cursor);\n if (\n message.type === \"reply\" &&\n typeof message.id === \"string\" &&\n message.id.length <= 64\n )\n post({\n type: \"channelReply\",\n id: message.id,\n ok: message.ok === true,\n result: message.result,\n error: typeof message.error === \"string\" ? message.error : null,\n });\n if (\n (video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video) &&\n message.type === \"viewPing\" &&\n typeof message.challenge === \"string\" &&\n message.challenge.length <= 64 &&\n dc?.readyState === \"open\"\n )\n dc.send(message.challenge);\n } catch {}\n };\n let readingStats = false;\n statsTimer = setInterval(async () => {\n if (readingStats || g !== generation) return;\n readingStats = true;\n try {\n const stats = await rtc.getStats();\n if (g !== generation || pc !== rtc) return;\n const result = networkStats(stats, statsSample);\n statsSample = result.sample;\n post({\n type: \"network\",\n transport: result.transport,\n bytesPerSecond: result.bytesPerSecond,\n latencyMs: result.latencyMs,\n });\n } catch {\n } finally {\n readingStats = false;\n }\n }, 1000);\n rtc.ontrack = (e) => {\n if (g !== generation) return;\n video.srcObject = e.streams[0] || new MediaStream([e.track]);\n video.play().catch(() => {});\n };\n video.onplaying = () => {\n if (\n g !== generation ||\n videoPresented ||\n videoFrameCallback !== null ||\n videoPaintCallback !== null\n )\n return;\n video.style.display = \"block\";\n render();\n if (typeof scheduleBackgroundDraw === \"function\")\n scheduleBackgroundDraw();\n if (typeof video.requestVideoFrameCallback === \"function\") {\n videoFrameCallback = video.requestVideoFrameCallback(() => {\n if (g !== generation) return;\n videoFrameCallback = null;\n revealVideo(g);\n });\n } else waitForVideoFrame(g);\n };\n rtc.onconnectionstatechange = () => {\n if (g !== generation) return;\n if ([\"failed\", \"closed\"].includes(rtc.connectionState)) {\n failRtc(\"transport\");\n return;\n }\n if (rtc.connectionState === \"disconnected\") {\n clearTimeout(stableTimer);\n stableTimer = null;\n if (!disconnectTimer) {\n release();\n post({ type: \"reconnecting\", attemptId });\n disconnectTimer = setTimeout(() => {\n if (g === generation) failRtc(\"disconnected\");\n }, net.disconnectedMs);\n }\n } else if (rtc.connectionState === \"connected\") {\n clearTimeout(disconnectTimer);\n disconnectTimer = null;\n clearTimeout(deadlineTimer);\n if (!stableTimer)\n stableTimer = setTimeout(() => {\n if (g === generation) retries = 0;\n }, net.stableMs);\n if (videoPresented) post({ type: \"streaming\", attemptId });\n }\n };\n await rtc.setLocalDescription(await rtc.createOffer());\n if (!trickleIce)\n await new Promise((resolve) => {\n if (rtc.iceGatheringState === \"complete\") return resolve();\n gatherDone = resolve;\n gatherTimer = setTimeout(resolve, net.legacyGatherMs);\n rtc.onicegatheringstatechange = () => {\n if (rtc.iceGatheringState === \"complete\") {\n clearTimeout(gatherTimer);\n resolve();\n }\n };\n });\n if (g !== generation) return;\n post({ type: \"offer\", attemptId, sdp: rtc.localDescription.sdp });\n deadlineTimer = setTimeout(() => {\n if (g === generation) failRtc(\"answer-timeout\");\n }, net.answerMs);\n } catch {\n if (g === generation) failRtc(\"setup\");\n }\n }\n\n /* END RTC */\n function reportPresentation() {\n post({\n type: \"presentation\",\n active:\n video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video,\n });\n }\n listen(video, \"webkitpresentationmodechanged\", reportPresentation);\n listen(video, \"enterpictureinpicture\", reportPresentation);\n listen(video, \"leavepictureinpicture\", reportPresentation);\n function applyDisplayGeometry(message) {\n if (\n !Number.isInteger(message.width) ||\n !Number.isInteger(message.height) ||\n message.width < 320 ||\n message.height < 320 ||\n (message.restore !== true &&\n (message.width > 2560 || message.height > 2560))\n )\n return;\n release();\n stopPanAnimation();\n viewerSized = message.restore !== true;\n zoom = 1;\n desktopScale = null;\n fx = fy = 0.5;\n followRest = null;\n dw = message.width;\n dh = message.height;\n render();\n }\n function receive(event) {\n let message;\n try {\n message = JSON.parse(event.data);\n } catch {\n return;\n }\n switch (message.type) {\n // A small control request routed over the live data channel. The host\n // only receives it after advertising support; otherwise the parent uses\n // the relay. `sent` tells the parent whether the channel took it.\n case \"channelRequest\": {\n const id =\n typeof message.id === \"string\" && message.id.length <= 64\n ? message.id\n : null;\n if (!id) break;\n let sent = false;\n try {\n const data = JSON.stringify({\n type: \"request\",\n id,\n request: message.request,\n });\n if (\n pc?.connectionState === \"connected\" &&\n dc?.readyState === \"open\" &&\n dc.bufferedAmount < 16384 &&\n data.length <= 32768\n ) {\n dc.send(data);\n sent = true;\n }\n } catch {}\n post({ type: \"channelRequestState\", id, sent });\n break;\n }\n case \"measureViewport\":\n post({\n type: \"viewportSize\",\n width: viewportWidth(),\n height: usableHeight(),\n });\n break;\n case \"presentation\":\n if (config.nativeMedia) {\n release();\n showKeyboard(false);\n break;\n }\n try {\n if (message.enabled) {\n release();\n showKeyboard(false);\n if (video.webkitSupportsPresentationMode?.(\"picture-in-picture\"))\n video.webkitSetPresentationMode(\"picture-in-picture\");\n else if (video.requestPictureInPicture)\n video\n .requestPictureInPicture()\n .catch(() => post({ type: \"presentationFailed\" }));\n else post({ type: \"presentationFailed\" });\n } else if (video.webkitSetPresentationMode)\n video.webkitSetPresentationMode(\"inline\");\n else if (document.pictureInPictureElement)\n document.exitPictureInPicture().catch(() => {});\n } catch {\n post({ type: \"presentationFailed\" });\n }\n break;\n case \"videoSettings\":\n applyDisplayGeometry(message);\n video.muted = !message.audio;\n retries = 0;\n if (!config.nativeMedia) connect();\n break;\n // The host kept the stream across a display change: layout only.\n case \"displayGeometry\":\n applyDisplayGeometry(message);\n break;\n case \"keyboard\":\n showKeyboard(message.enabled === true);\n break;\n case \"resume\":\n if (video.srcObject) video.play().catch(() => {});\n break;\n case \"releaseInput\":\n release();\n break;\n case \"inputGate\":\n if (inputGateUntil) pendingSince = performance.now();\n inputGateUntil = 0;\n flush();\n break;\n case \"theme\":\n if (/^#[0-9a-f]{3,8}$/i.test(message.surface)) {\n document.body.style.background = config.nativeMedia\n ? \"transparent\"\n : message.surface;\n document.documentElement.style.background = config.nativeMedia\n ? \"transparent\"\n : message.surface;\n document.documentElement.style.setProperty(\n \"--surface\",\n message.surface,\n );\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.foreground)) {\n cursor.style.borderColor = message.foreground;\n document.documentElement.style.setProperty(\n \"--foreground\",\n message.foreground,\n );\n }\n break;\n case \"networkStatus\": {\n const status = find(\"network-status\");\n if (!status) break;\n status.textContent =\n typeof message.text === \"string\" ? message.text : \"\";\n status.style.display = status.textContent ? \"block\" : \"none\";\n for (const key of [\"top\", \"right\", \"fontSize\"]) {\n if (Number.isFinite(message[key]) && message[key] >= 0)\n status.style[key] = message[key] + \"px\";\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.color))\n status.style.color = message.color;\n statusOrigin = null;\n clipNetworkStatus();\n break;\n }\n case \"nativeTouchpad\": {\n if (!nativeMouseControls || !control) break;\n if (message.tap === true) {\n if (!heldMouse.size) { click(); flush(); }\n break;\n }\n if (!Number.isFinite(message.dx) || !Number.isFinite(message.dy)) break;\n moveTouchpad(message.dx, message.dy);\n queue({ kind: \"move\", x: cx, y: cy });\n touchCursor = { x: cx, y: cy };\n touchCursorVisible = true;\n render();\n break;\n }\n case \"nativeMouse\": {\n if (\n !nativeMouseControls ||\n ![\"left\", \"right\", \"wheel\"].includes(message.control)\n )\n break;\n if (\n ![\n \"pointerdown\",\n \"pointermove\",\n \"pointerup\",\n \"pointercancel\",\n \"click\",\n ].includes(message.event)\n )\n break;\n if (!Number.isFinite(message.id) || !Number.isFinite(message.y)) break;\n mouseControlHandlers.get(\n \"mouse-\" + message.control + \":\" + message.event,\n )?.({\n pointerId: message.id,\n clientY: message.y,\n detail: 0,\n nativeInput: true,\n preventDefault() {},\n });\n break;\n }\n case \"mouseButtons\": {\n nativeMouseControls = message.native === true;\n const before = layout(),\n previousTopInset = viewportTopInset,\n previousBottomInset = viewportBottomInset,\n keyboardOpen = fillHeight && message.keyboardOpen === true;\n const keepHorizontal =\n fillHeight && (keyboardOpen || keyboardViewportOpen);\n // Hiding the rail for the keyboard must not enlarge a width-fitted desktop.\n if (keyboardOpen && (!keyboardViewportOpen || !keyboardFitWidth)) {\n keyboardFitWidth = { stageWidth: stage.clientWidth, width: viewportWidth() };\n }\n if (!keyboardOpen) keyboardFitWidth = null;\n // Opening is observable before the native keyboard has a measured height.\n keyboardViewportOpen = keyboardOpen;\n const fitChanged = fitToInsets !== (message.fitToInsets === true);\n fitToInsets = message.fitToInsets === true;\n const previousOffset = portraitKeyboardTopInset;\n if (Number.isFinite(message.portraitKeyboardTopInset))\n portraitKeyboardTopInset = Math.max(\n 0,\n message.portraitKeyboardTopInset,\n );\n const offsetChanged = previousOffset !== portraitKeyboardTopInset;\n let sideInsetsChanged = false;\n if (Number.isFinite(message.topInset))\n viewportTopInset = Math.max(\n 0,\n Math.min(stage.clientHeight - 1, message.topInset),\n );\n if (Number.isFinite(message.bottomInset))\n viewportBottomInset = Math.max(\n 0,\n Math.min(stage.clientHeight - 1, message.bottomInset),\n );\n if (Number.isFinite(message.leftInset)) {\n const inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.leftInset),\n );\n sideInsetsChanged = sideInsetsChanged || inset !== viewportLeftInset;\n viewportLeftInset = inset;\n }\n if (Number.isFinite(message.rightInset)) {\n const inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.rightInset),\n );\n sideInsetsChanged = sideInsetsChanged || inset !== viewportRightInset;\n viewportRightInset = inset;\n }\n // Hiding the side toolbar changes the viewport center. Keep the image's\n // actual horizontal position instead of following that center sideways.\n if (keepHorizontal) {\n stopPanAnimation();\n const r = layout();\n place(before.x, r.y, r);\n }\n const keyboardInset = keyboardOpen ? viewportBottomInset : 0;\n if (keyboardInset !== keyboardViewportInset) {\n const wasOpen = keyboardViewportInset > 0;\n keyboardViewportInset = keyboardInset;\n if (fillHeight && (keyboardInset > 0 || wasOpen)) {\n const r = layout(),\n v = cursorViewport();\n place(r.x, (v.minY + v.maxY) / 2 - cy * r.height, r);\n cursorNeedsEntry = false;\n manualViewMoved = false;\n }\n }\n if (keepHorizontal) {\n // Restoring the toolbar can cover the cursor even after a zero-height opening.\n if (!keyboardOpen || keyboardInset > 0) {\n const r = layout(),\n v = cursorViewport(),\n x = r.x + cx * r.width;\n place(r.x + bounded(x, v.minX, v.maxX) - x, r.y, r);\n }\n followRest = { fx, fy, zoom };\n render();\n } else if (\n fitChanged ||\n sideInsetsChanged ||\n offsetChanged ||\n (usesViewportInsets() && previousTopInset !== viewportTopInset) ||\n (usesViewportInsets() && previousBottomInset !== viewportBottomInset)\n ) {\n settlePan();\n render();\n }\n reportViewport();\n if (!message.enabled) {\n for (const button of heldMouse.keys())\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n heldMouse.clear();\n resetWheel();\n flush();\n }\n for (const [edge, value] of [\n [\"bottom\", message.bottomInset],\n [\"right\", message.rightInset],\n ])\n if (Number.isFinite(value) && value >= 0 && value <= 4096)\n mouseButtons.style[edge] = value + \"px\";\n showMouseButtons = message.enabled === true;\n for (const name of [\"left\", \"right\", \"wheel\"])\n if (typeof message.labels?.[name] === \"string\")\n find(\"mouse-\" + name).setAttribute(\n \"aria-label\",\n message.labels[name],\n );\n updateMouseButtons();\n break;\n }\n case \"init\":\n nativeVideoActive = false;\n // Clear instead of forcing visible: the stylesheet hides an image with\n // no frame yet, otherwise the browser paints a broken-image box.\n image.style.visibility = \"\";\n desktopScale = null;\n reportedScaleMode = null;\n if (config.desktop) {\n zoom = 1;\n fx = 0.5;\n fy = 0.5;\n }\n viewerSized = false;\n followRest = null;\n cursorNeedsEntry = true;\n stopPanAnimation();\n resetCursor();\n control = false;\n release();\n pending = [];\n sending = false;\n seq = 0;\n epoch = message.epoch;\n macKeyboard = config.desktop && message.macKeyboard === true;\n clipboardModifier =\n message.clipboardModifier === \"meta\" ? \"meta\" : \"control\";\n inputGateUntil = 0;\n dw = message.width;\n dh = message.height;\n fillHeight = message.fillHeight === true;\n video.muted = !message.audio;\n trickleIce = message.trickleIce === true;\n retries = 0;\n render();\n if (!config.nativeMedia) connect();\n break;\n case \"nativeVideo\":\n if (!config.nativeMedia || message.epoch !== epoch) break;\n nativeVideoActive = message.active === true;\n image.style.visibility = nativeVideoActive ? \"hidden\" : \"\";\n clipNetworkStatus();\n paintBackground();\n break;\n case \"nativeCursor\":\n if (config.nativeMedia && message.epoch === epoch)\n receiveCursor(message.cursor);\n break;\n case \"viewport\":\n if (fillHeight !== (message.fillHeight === true)) keyboardFitWidth = null;\n fillHeight = message.fillHeight === true;\n release();\n render();\n break;\n case \"answer\":\n if (message.epoch === epoch) void receiveAnswer(message);\n break;\n case \"iceConfig\":\n if (message.epoch === epoch) void receiveIceConfig(message);\n break;\n case \"ice\":\n if (message.epoch === epoch) void receiveIce(message);\n break;\n case \"fallback\":\n if (message.epoch === epoch && message.attemptId === attemptId)\n failRtc(\n message.capturePending === true ? \"capture-pending\" : \"host\",\n message.retry !== false,\n );\n break;\n case \"frame\": {\n if (\"cursor\" in message) receiveCursor(message.cursor);\n else resetCursor();\n const frameEpoch = epoch;\n image.onload = () => {\n if (epoch === frameEpoch) {\n scheduleBackgroundDraw();\n post({ type: \"framePresented\" });\n }\n };\n image.src = \"data:image/jpeg;base64,\" + message.jpeg;\n break;\n }\n case \"control\": {\n // A local view-only switch keeps host control, so its release must\n // still reach the host even if a batch was waiting for its ACK.\n const releaseHost =\n control && message.enabled !== true && message.release === true;\n release();\n // A new control intent abandons the previous relay batch. Advance the\n // existing sequence fence so a late old ACK cannot unlock a new batch.\n seq++;\n sending = false;\n inputGateUntil = 0;\n control = message.enabled;\n if (!control) showKeyboard(false);\n pending = [];\n if (releaseHost) {\n pending = [{ kind: \"release\" }];\n pendingSince = performance.now();\n flush();\n }\n updateMouseButtons();\n render();\n break;\n }\n case \"mode\":\n release();\n if (message.mode !== \"pointer\") followRest = null;\n settlePan();\n clearTimeout(touchCursorTimer);\n touchCursorVisible = false;\n mode = message.mode;\n render();\n break;\n case \"zoom\":\n stopEdgePan();\n if (\n !config.desktop ||\n !Number.isFinite(message.factor) ||\n message.factor <= 0\n )\n break;\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = true;\n stopPanAnimation();\n const fitScale = Math.min(viewportWidth() / dw, viewportHeight() / dh);\n // Include actual size even when it lies outside the fit-relative range.\n desktopScale = Math.max(\n Math.min(fitScale, 1) * 0.1,\n Math.min(Math.max(5 * fitScale, 5), layout().scale * message.factor),\n );\n if (Math.abs(desktopScale - fitScale) < 1e-9) desktopScale = null;\n if (desktopScale === null) {\n fx = 0.5;\n fy = 0.5;\n manualViewMoved = false;\n }\n render();\n settlePan();\n break;\n case \"actualSize\":\n stopEdgePan();\n if (!config.desktop) break;\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = true;\n stopPanAnimation();\n desktopScale = 1;\n fx = 0.5;\n fy = 0.5;\n render();\n break;\n case \"fit\":\n stopEdgePan();\n desktopScale = null;\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = false;\n stopPanAnimation();\n zoom = 1;\n fx = 0.5;\n fy = 0.5;\n render();\n break;\n case \"rightClick\":\n click(2);\n break;\n case \"events\":\n for (const e of message.events) queue(e);\n flush();\n break;\n case \"ack\":\n if (message.epoch === epoch && message.sequence === seq)\n sending = false;\n break;\n case \"stop\":\n nativeVideoActive = false;\n image.style.visibility = \"\";\n showKeyboard(false);\n control = false;\n release();\n pending = [];\n sending = false;\n epoch = null;\n closeRtc(message.preserveFrame === true);\n updateMouseButtons();\n render();\n break;\n }\n }\n // iOS can report equal left/right safe areas in both landscape directions.\n // Its interface angle distinguishes the notch side even on a 180-degree turn.\n const reportOrientation = () => {\n const angle =\n typeof window.orientation === \"number\"\n ? window.orientation\n : window.screen?.orientation?.angle;\n if (Number.isFinite(angle)) post({ type: \"orientation\", angle });\n };\n listen(window, \"orientationchange\", reportOrientation);\n if (window.screen?.orientation?.addEventListener)\n listen(window.screen.orientation, \"change\", reportOrientation);\n render();\n reportOrientation();\n post({ type: \"ready\" });\n return {\n receive: (message) => receive({ data: JSON.stringify(message) }),\n dispose: () => {\n release();\n epoch = null;\n closeRtc(false);\n if (bgDrawFrame !== null) cancelAnimationFrame(bgDrawFrame);\n bgDrawFrame = null;\n for (const cleanup of cleanups) cleanup();\n },\n };\n}\n";
+export const DESKTOP_VIEWER_SOURCE = "/** Shared browser viewer. Mobile bundles this exact source; Desktop imports it as a CSP-safe module. */\nfunction mountRemoteDesktopViewer(root, postMessage, config) {\n const cleanups = [];\n const listen = (target, type, fn, options) => {\n target.addEventListener(type, fn, options);\n cleanups.push(() => target.removeEventListener(type, fn, options));\n };\n const find = (id) =>\n root.getElementById\n ? root.getElementById(id)\n : root.querySelector(\"#\" + id);\n const { net, iceServers } = config;\n let nativeVideoActive = false;\n const validKeys = new Set(config.keyCodes);\n const transform =\n /* BEGIN TRANSFORM */\n function desktopTransform(\n vw,\n vh,\n dw,\n dh,\n zoom,\n fx,\n fy,\n fillHeight = false,\n ) {\n const fit = fillHeight\n ? vh / Math.max(1, dh)\n : Math.min(vw / Math.max(1, dw), vh / Math.max(1, dh));\n // Pinch stops at two viewer points per desktop point, never below fit.\n const maxZoom = Math.max(1, 2 / fit);\n const scale = fit * Math.max(1, Math.min(maxZoom, zoom));\n const width = dw * scale;\n const height = dh * scale;\n const x =\n width <= vw\n ? (vw - width) / 2\n : Math.min(0, Math.max(vw - width, vw / 2 - fx * width));\n const y =\n height <= vh\n ? (vh - height) / 2\n : Math.min(0, Math.max(vh - height, vh / 2 - fy * height));\n return { x, y, width, height, scale, maxZoom };\n };\n /* END TRANSFORM */ const networkStats =\n /* BEGIN NETWORK_STATS */\n function networkStats(stats, previous) {\n const rows = [...stats.values()];\n const video = rows.find(\n (s) =>\n s.type === \"inbound-rtp\" &&\n (s.kind === \"video\" || s.mediaType === \"video\"),\n );\n const transport = rows.find(\n (s) => s.type === \"transport\" && s.selectedCandidatePairId,\n );\n const pair = transport\n ? stats.get(transport.selectedCandidatePairId)\n : rows.find(\n (s) =>\n s.type === \"candidate-pair\" &&\n s.state === \"succeeded\" &&\n s.nominated,\n );\n const local = pair && stats.get(pair.localCandidateId),\n remote = pair && stats.get(pair.remoteCandidateId);\n const direct = [\"host\", \"srflx\", \"prflx\"];\n const route =\n local?.candidateType === \"relay\" || remote?.candidateType === \"relay\"\n ? \"relay\"\n : direct.includes(local?.candidateType) &&\n direct.includes(remote?.candidateType)\n ? \"direct\"\n : \"video\";\n const sample =\n video &&\n Number.isFinite(video.bytesReceived) &&\n Number.isFinite(video.timestamp)\n ? {\n id: video.id,\n path: pair?.id,\n bytes: video.bytesReceived,\n time: video.timestamp,\n }\n : null;\n let bytesPerSecond = null;\n if (\n sample &&\n previous &&\n sample.id === previous.id &&\n sample.path === previous.path &&\n sample.time > previous.time &&\n sample.bytes >= previous.bytes\n )\n bytesPerSecond =\n ((sample.bytes - previous.bytes) * 1000) /\n (sample.time - previous.time);\n const latencyMs =\n Number.isFinite(pair?.currentRoundTripTime) &&\n pair.currentRoundTripTime >= 0\n ? pair.currentRoundTripTime * 1000\n : null;\n return { transport: route, bytesPerSecond, latencyMs, sample };\n };\n\n /* END NETWORK_STATS */ const stage = find(\"stage\"),\n image = find(\"image\"),\n video = find(\"video\"),\n cursor = find(\"cursor\");\n // Shared ambient backdrop. Minimal viewer embeds may omit its subtree.\n const bg = find(\"bg\") || null,\n bgCanvas = find(\"bg-canvas\") || null,\n bgContext = bgCanvas ? bgCanvas.getContext(\"2d\") : null;\n let dw = 1920,\n dh = 1080,\n viewerSized = false,\n zoom = 1,\n desktopScale = null,\n reportedScaleMode = null,\n desktopPan = null,\n edgePointer = null,\n edgeFrame = null,\n edgeTime = 0,\n fx = 0.5,\n fy = 0.5,\n mode = \"pointer\",\n control = false,\n macKeyboard = false,\n pc = null,\n dc = null,\n seq = 0,\n generation = 0,\n epoch = null,\n gestureFrame = null;\n let remoteCursor = null,\n lastLocalMove = 0,\n localCursorAwake = false;\n // The lower native pad is always relative input, independently of the video\n // surface's touch mode. Keep its contact alive while the finger pauses too.\n let nativeTouchpad = null;\n let touchCursor = null,\n touchCursorTimer = null,\n touchCursorVisible = false;\n const reducedMotion = matchMedia(\"(prefers-reduced-motion: reduce)\");\n const cursorImage = find(\"cursor-image\");\n let pending = [],\n pendingSince = 0,\n sending = false,\n // Deadline while a paste shortcut holds the queue (desktop only; 0 = open),\n // and which modifier is copy/paste on the controlled computer.\n inputGateUntil = 0,\n clipboardModifier = \"control\",\n cx = 0.5,\n cy = 0.5,\n drag = false,\n start = null,\n last = null,\n multi = null,\n hold = null,\n moved = false;\n const pointers = new Map();\n const mouseButtons = find(\"mouse-buttons\"),\n wheel = find(\"mouse-wheel\"),\n wheelGrip = find(\"mouse-wheel-grip\");\n let nativeMouseControls = false;\n const mouseControlHandlers = new Map();\n function listenMouse(el, type, handler) {\n listen(el, type, handler);\n mouseControlHandlers.set(el.id + \":\" + type, handler);\n }\n const keyboardInput = find(\"keyboard-input\");\n let keyboardEnabled = false,\n composing = false;\n const keyboardSentinel = \"\\u200b\";\n function resetKeyboard() {\n keyboardInput.value = keyboardSentinel;\n keyboardInput.setSelectionRange(1, 1);\n }\n function showKeyboard(enabled) {\n keyboardEnabled = enabled && control;\n if (!keyboardEnabled) {\n composing = false;\n resetKeyboard();\n keyboardInput.blur();\n return;\n }\n if (composing) return;\n if (config.desktop && document.activeElement === keyboardInput) return;\n // Keep focus inside the native evaluateJavaScript call; WebKit can reject\n // keyboard presentation after requestAnimationFrame loses user activation.\n keyboardInput.blur();\n resetKeyboard();\n keyboardInput.focus({ preventScroll: true });\n }\n function keyboardKey(code) {\n if (!keyboardEnabled || !control) return;\n queue({ kind: \"key\", code, down: true });\n queue({ kind: \"key\", code, down: false });\n flush();\n }\n function commitKeyboard() {\n if (!keyboardEnabled || !control || composing) return;\n const text = keyboardInput.value.replace(keyboardSentinel, \"\");\n if (text) {\n for (let i = 0; i < text.length; i += 4096)\n queue({ kind: \"text\", text: text.slice(i, i + 4096) });\n flush();\n }\n resetKeyboard();\n }\n listen(keyboardInput, \"compositionstart\", () => {\n composing = true;\n });\n listen(keyboardInput, \"compositionend\", () => {\n composing = false;\n commitKeyboard();\n });\n listen(keyboardInput, \"input\", (e) => {\n if (!e.isComposing) commitKeyboard();\n });\n listen(keyboardInput, \"beforeinput\", (e) => {\n if (composing || e.isComposing) return;\n if (e.inputType === \"deleteContentBackward\") {\n e.preventDefault();\n keyboardKey(\"Backspace\");\n resetKeyboard();\n } else if (\n e.inputType === \"insertLineBreak\" ||\n e.inputType === \"insertParagraph\"\n ) {\n e.preventDefault();\n keyboardKey(\"Enter\");\n resetKeyboard();\n }\n });\n const heldMouse = new Map();\n let showMouseButtons = false,\n wheelY = null;\n function resetWheel() {\n wheelY = null;\n wheelGrip.style.transform = \"translateY(0px)\";\n }\n let statsTimer = null,\n statsSample = null;\n const post = (message) => postMessage({ ...message, epoch });\n const clamp = (v) => Math.max(0, Math.min(1, v));\n let fillHeight = false;\n let fitToInsets = false;\n const usesViewportInsets = () => viewerSized || fitToInsets;\n let panAnimation = null,\n viewportRightInset = 0,\n viewportLeftInset = 0,\n viewportBottomInset = 0,\n viewportTopInset = 0,\n keyboardViewportInset = 0,\n portraitKeyboardTopInset = 0;\n let keyboardViewportOpen = false;\n let keyboardFitWidth = null;\n let cursorNeedsEntry = true,\n manualViewMoved = false,\n followRest = null;\n // Insets guide centering and pan limits without clipping the full-screen\n // video surface or adding an opaque strip beside the Dynamic Island.\n const viewportLeft = () => (fillHeight ? viewportLeftInset : 0);\n const usableHeight = () =>\n Math.max(1, stage.clientHeight - viewportTopInset - viewportBottomInset);\n const viewportHeight = () =>\n usesViewportInsets() ? usableHeight() : Math.max(1, stage.clientHeight);\n const viewportWidth = () =>\n Math.max(\n 1,\n stage.clientWidth -\n viewportLeft() -\n (fillHeight ? viewportRightInset : 0),\n );\n // Center between the measured top controls and the keyboard edge (stage bottom).\n // The usable center is (topInset + stageHeight) / 2, so shift by topInset / 2.\n // Keep the fitted size and cap the shift when the desktop is too tall to fit.\n const verticalOffset = (height) =>\n (usesViewportInsets() ? viewportTopInset : 0) +\n (fillHeight\n ? 0\n : Math.min(\n Math.max(\n 0,\n portraitKeyboardTopInset - (usesViewportInsets() ? viewportTopInset : 0),\n ) / 2,\n Math.max(0, (viewportHeight() - height) / 2),\n ));\n const layout = () => {\n const r =\n config.desktop && desktopScale !== null\n ? {\n scale: desktopScale,\n width: dw * desktopScale,\n height: dh * desktopScale,\n maxZoom: 1,\n }\n : transform(\n keyboardFitWidth?.stageWidth === stage.clientWidth\n ? keyboardFitWidth.width : viewportWidth(),\n viewportHeight(),\n dw,\n dh,\n zoom,\n fx,\n fy,\n // Mobile fits both axes; retain Desktop scale semantics.\n config.desktop ? fillHeight && !viewerSized : false,\n );\n return {\n ...r,\n x: viewportLeft() + viewportWidth() / 2 - fx * r.width,\n y: viewportHeight() / 2 + verticalOffset(r.height) - fy * r.height,\n };\n };\n // 0 at fit, 1 at the pinch limit for the current viewport and display.\n const zoomProgress = (r = layout()) =>\n r.maxZoom > 1\n ? Math.max(0, Math.min(1, (zoom - 1) / (r.maxZoom - 1)))\n : 0;\n // The backdrop uses 5% / 90% / 5% source segments. The middle 90%\n // keeps the fitted picture's scale; each outer 5% stretches uniformly\n // to fill the remaining space, horizontally or vertically as needed.\n // Zoom and pan never move the backdrop: where the picture covers it, the\n // opaque picture simply occludes it, so input mapping stays uniform. Returns\n // null when the fitted picture already covers the stage, unless a Desktop\n // viewer has shrunk its foreground below fit and still needs the backdrop.\n const bgEdgeFraction = 0.05;\n const bgCenterFraction = 1 - 2 * bgEdgeFraction;\n function backgroundSegments(vw, vh, dw, dh, fill, includeFitted = false) {\n if (!(vw > 0 && vh > 0 && dw > 0 && dh > 0)) return null;\n const s = fill\n ? vh / Math.max(1, dh)\n : Math.min(vw / dw, vh / Math.max(1, dh));\n const w = dw * s,\n h = dh * s;\n if (w < vw || (includeFitted && w === vw && h === vh)) {\n const centerW = w * bgCenterFraction,\n centerX = vw / 2 - centerW / 2,\n sideW = centerX,\n top = (vh - h) / 2;\n return { axis: \"x\", s, w, h, top, centerW, centerX, sideW };\n }\n if (h < vh) {\n const centerH = h * bgCenterFraction,\n centerY = vh / 2 - centerH / 2,\n sideH = centerY,\n left = (vw - w) / 2;\n return { axis: \"y\", s, w, h, left, centerH, centerY, sideH };\n }\n return null;\n }\n // Native video renders beneath this WebView, so z-order cannot hide the\n // status behind the picture; cut the picture's rectangle out instead.\n // Measure the status only after its text or the stage changes, not per frame.\n let statusOrigin = null;\n function clipNetworkStatus(r = layout()) {\n const status = find(\"network-status\");\n if (!status) return;\n if (!nativeVideoActive || status.style.display === \"none\") {\n status.style.clipPath = \"\";\n return;\n }\n if (!statusOrigin)\n statusOrigin = { x: status.offsetLeft, y: status.offsetTop };\n const left = r.x - statusOrigin.x,\n top = r.y - statusOrigin.y,\n right = left + r.width,\n bottom = top + r.height;\n status.style.clipPath = `polygon(evenodd,0 0,100% 0,100% 100%,0 100%,0 0,${left}px ${top}px,${right}px ${top}px,${right}px ${bottom}px,${left}px ${bottom}px,${left}px ${top}px)`;\n }\n function paintBackground() {\n if (nativeVideoActive) {\n if (bg) bg.style.display = \"none\";\n return;\n }\n if (!bg || !bgCanvas || !bgContext) return;\n const vw = stage.clientWidth,\n vh = stage.clientHeight;\n const picture = config.desktop ? layout() : null;\n const coversStage =\n picture &&\n picture.x <= 0 &&\n picture.y <= 0 &&\n picture.x + picture.width >= vw &&\n picture.y + picture.height >= vh;\n const seg = coversStage\n ? null\n : backgroundSegments(vw, vh, dw, dh, config.desktop ? fillHeight : false, config.desktop);\n if (!seg) {\n bg.style.display = \"none\";\n bgRects = null;\n stopBackgroundLoop();\n return;\n }\n bg.style.display = \"block\";\n bgAxis = seg.axis;\n // The ambient layer also fills the notch and the area beneath native\n // controls. Only the interactive picture respects viewport insets.\n const originX = 0;\n // Source segments are resolved at draw time from the live source dimensions;\n // these dest rects only encode where each segment lands on the stage.\n bgRects =\n seg.axis === \"x\"\n ? [\n {\n x: originX,\n y: seg.top,\n w: seg.sideW,\n h: seg.h,\n },\n {\n x: originX + seg.centerX,\n y: seg.top,\n w: seg.centerW,\n h: seg.h,\n },\n {\n x: originX + seg.centerX + seg.centerW,\n y: seg.top,\n w: seg.sideW,\n h: seg.h,\n },\n ]\n : [\n {\n x: seg.left,\n y: 0,\n w: seg.w,\n h: seg.sideH,\n },\n {\n x: seg.left,\n y: seg.centerY,\n w: seg.w,\n h: seg.centerH,\n },\n {\n x: seg.left,\n y: seg.centerY + seg.centerH,\n w: seg.w,\n h: seg.sideH,\n },\n ];\n // Keep the backing store at stage resolution (capped) so the stretched\n // edges stay crisp without oversized allocations.\n bgDpr = Math.min(2, window.devicePixelRatio || 1);\n const bw = Math.round(stage.clientWidth * bgDpr),\n bh = Math.round(vh * bgDpr);\n if (bgCanvas.width !== bw || bgCanvas.height !== bh) {\n bgCanvas.width = bw;\n bgCanvas.height = bh;\n }\n scheduleBackgroundDraw();\n startBackgroundLoop();\n }\n // One canvas, three draws: each source segment stretches into whatever bar\n // the picture leaves open. The live video feeds it once presented; until\n // then the decoded JPEG frame does, so the backdrop always matches the\n // picture's own pixels and scale in the center segment.\n let bgRects = null,\n bgAxis = \"x\",\n bgDpr = 1,\n bgDrawFrame = null,\n bgLoopFrame = null;\n function drawBackground() {\n if (!bgContext || !bgRects) return;\n const useVideo =\n videoPresented && video.videoWidth > 0 && video.videoHeight > 0;\n const src = useVideo ? video : image;\n // drawImage source rects live in the source's own pixel space, which can\n // differ from dw/dh; fractions of the real bitmap keep every segment lined\n // up with what the picture element actually shows.\n const sw = useVideo ? video.videoWidth : image.naturalWidth;\n const sh = useVideo ? video.videoHeight : image.naturalHeight;\n // Cursor updates can schedule a repaint while the next JPEG is loading.\n // Keep the last backdrop until the replacement has drawable pixels.\n if ((!useVideo && !image.complete) || !(sw > 0 && sh > 0)) return;\n bgContext.setTransform(bgDpr, 0, 0, bgDpr, 0, 0);\n bgContext.clearRect(0, 0, stage.clientWidth, stage.clientHeight);\n const horizontal = bgAxis === \"x\";\n const sourceLength = horizontal ? sw : sh;\n const cuts = [0, bgEdgeFraction, 1 - bgEdgeFraction, 1];\n for (let i = 0; i < bgRects.length; i++) {\n const rect = bgRects[i];\n const origin = cuts[i] * sourceLength;\n const length = (cuts[i + 1] - cuts[i]) * sourceLength;\n bgContext.drawImage(\n src,\n horizontal ? origin : 0,\n horizontal ? 0 : origin,\n horizontal ? length : sw,\n horizontal ? sh : length,\n rect.x,\n rect.y,\n rect.w,\n rect.h,\n );\n }\n }\n function scheduleBackgroundDraw() {\n if (bgDrawFrame !== null || !bgRects || !bgContext) return;\n bgDrawFrame = requestAnimationFrame(() => {\n bgDrawFrame = null;\n drawBackground();\n });\n }\n function startBackgroundLoop() {\n if (\n bgLoopFrame !== null ||\n !bgContext ||\n !bgRects ||\n !videoPresented ||\n typeof video.requestVideoFrameCallback !== \"function\"\n )\n return;\n const frame = video.requestVideoFrameCallback(() => {\n if (bgLoopFrame !== frame) return;\n bgLoopFrame = null;\n drawBackground();\n startBackgroundLoop();\n });\n bgLoopFrame = frame;\n }\n // Only the streaming loop stops here; a pending one-shot draw is harmless\n // (it re-paints the preserved frame) and must survive reconnects.\n function stopBackgroundLoop() {\n if (bgLoopFrame !== null) video.cancelVideoFrameCallback?.(bgLoopFrame);\n bgLoopFrame = null;\n }\n function clearBackground() {\n stopBackgroundLoop();\n bgRects = null;\n // Resizing a canvas resets its bitmap; same-value assignment still clears.\n if (bgCanvas) bgCanvas.width = bgCanvas.width;\n }\n listen(image, \"load\", () => scheduleBackgroundDraw());\n // Older WebViews update the ambient layer on media progress, never with an\n // idle display-refresh loop. Geometry changes still get a one-shot repaint.\n listen(video, \"timeupdate\", () => {\n if (videoPresented && typeof video.requestVideoFrameCallback !== \"function\")\n scheduleBackgroundDraw();\n });\n function panBounds(r) {\n const vw = viewportWidth(),\n vh = viewportHeight();\n // Grow extra resting travel continuously from zero at fit to its full reach\n // by 1.5x, so even a light zoom can pull edge content clear of the overlaid\n // chrome. Never count the unused space of a fitting axis.\n // Each axis reaches at most 240 points or 40% of its own viewport.\n const ramp = Math.min(0.5, r.maxZoom - 1);\n const grown = ramp > 0 ? clamp((zoom - 1) / ramp) : 0;\n const axis = (viewport, content) => {\n const clearance = grown * Math.min(240, viewport * 0.4);\n return content <= viewport\n ? {\n min: (viewport - content) / 2 - clearance,\n max: (viewport - content) / 2 + clearance,\n }\n : { min: viewport - content - clearance, max: clearance };\n };\n const x = axis(vw, r.width),\n y = axis(vh, r.height);\n const bounds = {\n minX: viewportLeft() + x.min,\n maxX: viewportLeft() + x.max,\n minY: y.min + verticalOffset(r.height),\n maxY: y.max + verticalOffset(r.height),\n };\n // A camera position required to expose the cursor is a valid resting point,\n // not elastic overshoot. Preserve it across the next pan/pinch handoff.\n if (followRest) {\n const restX = viewportLeft() + vw / 2 - followRest.fx * r.width,\n restY = vh / 2 + verticalOffset(r.height) - followRest.fy * r.height;\n const weight =\n followRest.zoom > 1 ? clamp((zoom - 1) / (followRest.zoom - 1)) : 1;\n bounds.minX += Math.min(0, restX - bounds.minX) * weight;\n bounds.maxX += Math.max(0, restX - bounds.maxX) * weight;\n bounds.minY += Math.min(0, restY - bounds.minY) * weight;\n bounds.maxY += Math.max(0, restY - bounds.maxY) * weight;\n }\n return bounds;\n }\n const bounded = (v, min, max) => Math.max(min, Math.min(max, v));\n // Convert displayed overshoot back to finger travel before the next delta,\n // so reversing direction unwinds smoothly without an edge jump.\n function rubber(v, min, max, inverse = false) {\n const edge = bounded(v, min, max),\n d = v - edge;\n const reach = 40 + 40 * zoomProgress();\n return (\n edge +\n Math.sign(d) *\n (inverse\n ? (reach * Math.abs(d)) / Math.max(1, reach - Math.abs(d))\n : (reach * Math.abs(d)) / (reach + Math.abs(d)))\n );\n }\n function place(x, y, r) {\n fx = (viewportLeft() + viewportWidth() / 2 - x) / r.width;\n fy = (viewportHeight() / 2 + verticalOffset(r.height) - y) / r.height;\n }\n function cursorViewport() {\n const hotX = remoteCursor?.hotX ?? 9,\n hotY = remoteCursor?.hotY ?? 9;\n const w = remoteCursor?.width ?? 18,\n h = remoteCursor?.height ?? 18;\n const left = viewportLeft(),\n right = left + viewportWidth(),\n bottom = Math.max(1, stage.clientHeight - viewportBottomInset);\n // Keep the entire cursor, including its hotspot offset, clear of chrome.\n const minX = Math.min(right - 1, left + 8 + hotX),\n minY = Math.min(\n bottom - 1,\n (usesViewportInsets() ? viewportTopInset : 0) + 8 + hotY,\n );\n return {\n minX,\n maxX: Math.max(minX, right - 8 - (w - hotX)),\n minY,\n maxY: Math.max(minY, bottom - 8 - (h - hotY)),\n };\n }\n function moveTouchpad(dx, dy) {\n stopPanAnimation();\n const r = layout(),\n v = cursorViewport();\n if (cursorNeedsEntry) {\n // Re-enter at the nearest visible edge; do not pull a manually positioned\n // desktop back to the old off-screen cursor before applying this movement.\n cx = clamp((bounded(r.x + cx * r.width, v.minX, v.maxX) - r.x) / r.width);\n cy = clamp(\n (bounded(r.y + cy * r.height, v.minY, v.maxY) - r.y) / r.height,\n );\n cursorNeedsEntry = false;\n }\n cx = clamp(cx + dx / r.width);\n cy = clamp(cy + dy / r.height);\n const x = r.x + cx * r.width,\n y = r.y + cy * r.height;\n if (\n zoom > 1 ||\n r.width > viewportWidth() ||\n r.height > stage.clientHeight - viewportBottomInset\n ) {\n place(\n r.x + bounded(x, v.minX, v.maxX) - x,\n r.y + bounded(y, v.minY, v.maxY) - y,\n r,\n );\n followRest = { fx, fy, zoom };\n }\n manualViewMoved = false;\n }\n function stopPanAnimation() {\n if (panAnimation !== null) cancelAnimationFrame(panAnimation);\n panAnimation = null;\n }\n function settlePan() {\n stopPanAnimation();\n const r = layout(),\n b = panBounds(r),\n x = bounded(r.x, b.minX, b.maxX),\n y = bounded(r.y, b.minY, b.maxY);\n if (x === r.x && y === r.y) return;\n if (reducedMotion.matches) {\n place(x, y, r);\n render();\n return;\n }\n const started = performance.now();\n const tick = (now) => {\n const t = Math.min(1, (now - started) / 280),\n ease = 1 - Math.pow(1 - t, 3);\n place(r.x + (x - r.x) * ease, r.y + (y - r.y) * ease, r);\n render();\n panAnimation = t < 1 ? requestAnimationFrame(tick) : null;\n };\n panAnimation = requestAnimationFrame(tick);\n }\n function render() {\n const r = layout();\n if (config.nativeMedia && epoch)\n post({\n type: \"nativeViewport\",\n fillHeight: false,\n x: r.x,\n y: r.y,\n width: r.width,\n height: r.height,\n });\n if (config.desktop && epoch) {\n const scaleMode =\n desktopScale === null\n ? \"fit\"\n : desktopScale === 1\n ? \"actual\"\n : \"custom\";\n if (reportedScaleMode !== scaleMode) {\n reportedScaleMode = scaleMode;\n post({ type: \"scaleMode\", mode: scaleMode });\n }\n }\n const directTouch = mode === \"touch\" && !nativeTouchpad;\n const touchFeedback = control && directTouch && touchCursorVisible;\n const cursorX = directTouch && touchCursor ? touchCursor.x : cx;\n const cursorY = directTouch && touchCursor ? touchCursor.y : cy;\n cursor.style.transition =\n directTouch && !touchFeedback && !reducedMotion.matches\n ? \"opacity 120ms ease-out\"\n : \"none\";\n for (const el of [image, video]) {\n el.style.width = r.width + \"px\";\n el.style.height = r.height + \"px\";\n el.style.left = r.x + \"px\";\n el.style.top = r.y + \"px\";\n }\n clipNetworkStatus(r);\n paintBackground();\n if (remoteCursor) {\n cursor.style.width = remoteCursor.width + \"px\";\n cursor.style.height = remoteCursor.height + \"px\";\n cursor.style.border = \"0\";\n cursor.style.borderRadius = \"0\";\n cursor.style.transform = \"none\";\n cursor.style.left = r.x + cursorX * r.width - remoteCursor.hotX + \"px\";\n cursor.style.top = r.y + cursorY * r.height - remoteCursor.hotY + \"px\";\n cursor.style.display = \"block\";\n cursor.style.opacity = (\n directTouch\n ? touchFeedback\n : remoteCursor.visible ||\n (control && (mode === \"pointer\" || nativeTouchpad) && localCursorAwake)\n )\n ? \"1\"\n : \"0\";\n } else {\n cursor.style.opacity = (directTouch ? !touchFeedback : false)\n ? \"0\"\n : \"1\";\n cursor.style.width = \"18px\";\n cursor.style.height = \"18px\";\n cursor.style.border = \"2px solid var(--foreground)\";\n cursor.style.borderRadius = \"50%\";\n cursor.style.transform = \"translate(-50%,-50%)\";\n cursor.style.left = r.x + cursorX * r.width + \"px\";\n cursor.style.top = r.y + cursorY * r.height + \"px\";\n cursor.style.display =\n !config.desktop && control && (mode === \"pointer\" || mode === \"touch\")\n ? \"block\"\n : \"none\";\n }\n if (config.desktop) {\n // Let the local OS own pointer size, DPI and accessibility preferences.\n // Never use a remote URL or bitmap as the desktop's native cursor.\n cursor.style.display = \"none\";\n const shape = remoteCursor?.shape;\n stage.style.cursor =\n control &&\n [\n \"default\",\n \"text\",\n \"vertical-text\",\n \"pointer\",\n \"crosshair\",\n \"grab\",\n \"grabbing\",\n \"ew-resize\",\n \"ns-resize\",\n \"nwse-resize\",\n \"nesw-resize\",\n \"move\",\n \"not-allowed\",\n \"copy\",\n \"alias\",\n \"wait\",\n \"progress\",\n \"help\",\n ].includes(shape)\n ? shape\n : \"default\";\n }\n }\n // Literal source is required: Hermes function.toString() yields bytecode.\n function validCursor(v) {\n return (\n !!v &&\n typeof v === \"object\" &&\n typeof v.visible === \"boolean\" &&\n [v.x, v.y, v.width, v.height, v.hotX, v.hotY].every(Number.isFinite) &&\n v.x >= 0 &&\n v.x <= 1 &&\n v.y >= 0 &&\n v.y <= 1 &&\n v.width > 0 &&\n v.width <= 256 &&\n v.height > 0 &&\n v.height <= 256 &&\n v.hotX >= 0 &&\n v.hotX <= v.width &&\n v.hotY >= 0 &&\n v.hotY <= v.height &&\n typeof v.png === \"string\" &&\n v.png.length <= 65536 &&\n /^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/.test(v.png)\n );\n }\n function receiveCursor(value) {\n if (value === null) {\n if (remoteCursor) {\n remoteCursor = { ...remoteCursor, visible: false };\n render();\n }\n return;\n }\n if (!validCursor(value)) return;\n if (!remoteCursor || remoteCursor.png !== value.png)\n cursorImage.src = \"data:image/png;base64,\" + value.png;\n // Keep delayed host coordinates from pulling the local touchpad backwards.\n const nativeOwnsCursor = nativeTouchpad &&\n (nativeTouchpad.down || performance.now() - lastLocalMove <= 200);\n if (\n !control ||\n (!nativeOwnsCursor && (!remoteCursor || mode !== \"pointer\" ||\n (!pointers.size && performance.now() - lastLocalMove > 200)))\n ) {\n cx = value.x;\n cy = value.y;\n nativeTouchpad = null;\n }\n if (value.visible) localCursorAwake = false;\n remoteCursor = value;\n render();\n }\n function resetCursor() {\n clearTimeout(touchCursorTimer);\n touchCursorVisible = false;\n touchCursor = null;\n localCursorAwake = false;\n remoteCursor = null;\n cursorImage.removeAttribute(\"src\");\n render();\n }\n function queue(event) {\n if (!control) return;\n if (!pending.length) pendingSince = performance.now();\n // Remote visibility can remain hidden after synthetic mouse movement. Wake\n // the local touchpad cursor until the host reports a visible cursor again.\n if (event.kind === \"move\" && (mode === \"pointer\" || nativeTouchpad)) localCursorAwake = true;\n if (event.kind === \"key\" || event.kind === \"text\") {\n localCursorAwake = false;\n render();\n }\n if (event.kind === \"move\" || event.kind === \"button\")\n lastLocalMove = performance.now();\n const tail = pending[pending.length - 1];\n if (event.kind === \"move\" && tail?.kind === \"move\")\n pending[pending.length - 1] = event;\n // Coalesce only adjacent scrolls, preserving button/key ordering. Bound the\n // accumulated distance so a delayed ACK cannot replay a large scroll backlog.\n else if (event.kind === \"scroll\" && tail?.kind === \"scroll\") {\n tail.dx = Math.max(-2000, Math.min(2000, tail.dx + event.dx));\n tail.dy = Math.max(-2000, Math.min(2000, tail.dy + event.dy));\n } else pending.push(event);\n if (pending.length > 64) {\n pending = [{ kind: \"release\" }];\n control = false;\n post({ type: \"inputOverflow\" });\n }\n }\n function flush() {\n if (!pending.length) return;\n // A paste shortcut waits for the controller to push the local clipboard\n // first. That hold is deliberate (and each further paste re-arms it), so\n // the batch's freshness clock only starts once the gate opens.\n if (inputGateUntil) {\n if (performance.now() < inputGateUntil) return;\n inputGateUntil = 0;\n pendingSince = performance.now();\n }\n // Input is an intent about the picture the user saw, not durable work.\n // Never replay old clicks/typing after a stalled ACK or data channel drains.\n if (performance.now() - pendingSince >= 2000) {\n pending = [];\n control = false;\n release();\n updateMouseButtons();\n post({ type: \"inputOverflow\" });\n return;\n }\n if (sending) return;\n // Do not route around a congested live data channel: the relay could\n // overtake its already-buffered key/button events and reorder input.\n if (pc?.connectionState === \"connected\" && dc?.readyState === \"open\" && dc.bufferedAmount >= 16384) return;\n const events = pending.splice(0, 64),\n sequence = ++seq;\n if (\n pc?.connectionState === \"connected\" &&\n dc &&\n dc.readyState === \"open\" &&\n dc.bufferedAmount < 16384\n ) {\n try {\n dc.send(JSON.stringify({ sequence, events }));\n } catch {\n pending = [];\n control = false;\n release();\n post({ type: \"inputOverflow\" });\n }\n } else {\n sending = true;\n post({ type: \"input\", sequence, events });\n }\n }\n const inputTimer = setInterval(() => {\n // Hold displacement controls speed, even without further pointer moves.\n // Skip missed ticks while awaiting ACK instead of building a scroll backlog.\n if (wheelY?.moved && !sending) {\n const offset = Math.max(-24, Math.min(24, wheelY.y - wheelY.start));\n if (Math.abs(offset) > 4)\n scrollMouse(Math.sign(offset) * (Math.abs(offset) - 4) * 1.5);\n }\n flush();\n }, 33);\n cleanups.push(() => clearInterval(inputTimer));\n function release() {\n nativeTouchpad = null;\n stopEdgePan();\n desktopPan = null;\n clearTimeout(hold);\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n gestureFrame = null;\n // A paste still waiting for its clipboard push is abandoned, never sent\n // late; the release itself must reach the computer at once.\n if (inputGateUntil) {\n inputGateUntil = 0;\n pending = [];\n }\n if (control) {\n queue({ kind: \"release\" });\n flush();\n }\n heldMouse.clear();\n resetWheel();\n updateMouseButtons();\n drag = false;\n pointers.clear();\n start = null;\n last = null;\n multi = null;\n }\n function updateMouseButtons() {\n mouseButtons.style.display =\n showMouseButtons && control && !nativeMouseControls ? \"block\" : \"none\";\n for (const [name, button] of [\n [\"left\", 0],\n [\"right\", 2],\n ])\n find(\"mouse-\" + name).setAttribute(\n \"aria-pressed\",\n String(heldMouse.has(button)),\n );\n }\n for (const [name, button] of [\n [\"left\", 0],\n [\"right\", 2],\n ]) {\n const el = find(\"mouse-\" + name);\n listenMouse(el, \"pointerdown\", (e) => {\n e.preventDefault();\n if (!control || !showMouseButtons || heldMouse.has(button)) return;\n clearTimeout(hold);\n if (!e.nativeInput) el.setPointerCapture(e.pointerId);\n heldMouse.set(button, e.pointerId);\n queue({ kind: \"button\", button, down: true, x: cx, y: cy });\n flush();\n updateMouseButtons();\n });\n const up = (e) => {\n e.preventDefault();\n if (heldMouse.get(button) !== e.pointerId) return;\n heldMouse.delete(button);\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n flush();\n updateMouseButtons();\n };\n listenMouse(el, \"pointerup\", up);\n listenMouse(el, \"pointercancel\", up);\n listenMouse(el, \"lostpointercapture\", up);\n listenMouse(el, \"click\", (e) => {\n if (e.detail === 0 && control && showMouseButtons) {\n click(button);\n flush();\n }\n });\n }\n const scrollMouse = (dy) => {\n if (control && showMouseButtons && Number.isFinite(dy)) {\n queue({ kind: \"scroll\", dx: 0, dy: Math.max(-2000, Math.min(2000, dy)) });\n }\n };\n listenMouse(wheel, \"pointerdown\", (e) => {\n e.preventDefault();\n if (!control || !showMouseButtons || wheelY) return;\n if (!e.nativeInput) wheel.setPointerCapture(e.pointerId);\n wheelY = { id: e.pointerId, y: e.clientY, start: e.clientY, moved: false };\n });\n // A small dead zone preserves middle clicks; displacement drives the timer.\n listenMouse(wheel, \"pointermove\", (e) => {\n if (!wheelY || wheelY.id !== e.pointerId) return;\n e.preventDefault();\n wheelGrip.style.transform =\n \"translateY(\" +\n Math.max(-24, Math.min(24, e.clientY - wheelY.start)) +\n \"px)\";\n wheelY.y = e.clientY;\n if (Math.abs(e.clientY - wheelY.start) > 4) wheelY.moved = true;\n });\n listenMouse(wheel, \"pointerup\", (e) => {\n if (!wheelY || wheelY.id !== e.pointerId) return;\n e.preventDefault();\n if (!wheelY.moved && control && showMouseButtons) {\n click(1);\n flush();\n }\n resetWheel();\n });\n const cancelWheel = (e) => {\n if (wheelY?.id === e.pointerId) resetWheel();\n };\n listenMouse(wheel, \"pointercancel\", cancelWheel);\n listenMouse(wheel, \"lostpointercapture\", cancelWheel);\n listenMouse(wheel, \"click\", (e) => {\n if (e.detail === 0 && control && showMouseButtons) {\n click(1);\n flush();\n }\n });\n listenMouse(wheel, \"keydown\", (e) => {\n if (e.key === \"ArrowUp\" || e.key === \"ArrowDown\") {\n e.preventDefault();\n scrollMouse(e.key === \"ArrowUp\" ? -120 : 120);\n }\n });\n function insideDesktop(p) {\n const r = layout();\n return (\n p.x >= r.x && p.x <= r.x + r.width && p.y >= r.y && p.y <= r.y + r.height\n );\n }\n function point(p) {\n const r = layout();\n return {\n x: clamp((p.x - r.x) / r.width),\n y: clamp((p.y - r.y) / r.height),\n };\n }\n const desktopPoint = (e) => {\n const bounds = stage.getBoundingClientRect();\n return { x: e.clientX - bounds.left, y: e.clientY - bounds.top };\n };\n function stopEdgePan() {\n if (edgeFrame !== null) cancelAnimationFrame(edgeFrame);\n edgeFrame = null;\n edgePointer = null;\n }\n function edgePanTick(now) {\n edgeFrame = null;\n if (!edgePointer || desktopPan || !epoch) return;\n const r = layout(),\n vw = viewportWidth(),\n vh = viewportHeight();\n const p = edgePointer;\n const dt = Math.min(32, Math.max(0, now - edgeTime)) / 1000;\n edgeTime = now;\n // rAF timestamps describe the frame start and can precede the pointer\n // handler's performance.now(). A zero-time first frame is not a boundary.\n if (dt === 0) {\n edgeFrame = requestAnimationFrame(edgePanTick);\n return;\n }\n // A narrow edge band accelerates smoothly to 720 local pixels per second.\n const velocity = (position, extent) => {\n const band = Math.min(28, extent / 4);\n return position < band\n ? -(1 - position / band)\n : position > extent - band\n ? (position - extent + band) / band\n : 0;\n };\n const x =\n r.width > vw\n ? bounded(\n r.x - velocity(p.x - viewportLeft(), vw) * 720 * dt,\n viewportLeft() + vw - r.width,\n viewportLeft(),\n )\n : r.x;\n const y =\n r.height > vh\n ? bounded(r.y - velocity(p.y, vh) * 720 * dt, vh - r.height, 0)\n : r.y;\n if (Math.abs(x - r.x) < 0.001 && Math.abs(y - r.y) < 0.001) return;\n stopPanAnimation();\n manualViewMoved = true;\n place(x, y, r);\n // Keep remote hover/drag attached to the local pointer as the picture moves.\n if (control) {\n const next = point(p);\n cx = next.x;\n cy = next.y;\n queue({ kind: \"move\", x: cx, y: cy });\n }\n render();\n edgeFrame = requestAnimationFrame(edgePanTick);\n }\n function trackEdgePointer(e) {\n const p = desktopPoint(e);\n if (\n !epoch ||\n desktopPan ||\n p.x < viewportLeft() ||\n p.x > viewportLeft() + viewportWidth() ||\n p.y < 0 ||\n p.y > viewportHeight() ||\n !insideDesktop(p)\n ) {\n stopEdgePan();\n return;\n }\n edgePointer = p;\n if (edgeFrame === null) {\n edgeTime = performance.now();\n edgeFrame = requestAnimationFrame(edgePanTick);\n }\n }\n listen(stage, \"pointerleave\", stopEdgePan);\n function mouse(e, down) {\n if (!control || ![0, 1, 2].includes(e.button)) return;\n const local = desktopPoint(e);\n if (down && !insideDesktop(local)) return;\n const p = point(local);\n cx = p.x;\n cy = p.y;\n if (down) {\n showKeyboard(true);\n stage.setPointerCapture(e.pointerId);\n heldMouse.set(e.button, e.pointerId);\n } else if (!heldMouse.delete(e.button)) return;\n queue({ kind: \"button\", button: e.button, down, x: cx, y: cy });\n flush();\n render();\n }\n function click(button = 0) {\n if (control && mode === \"touch\") {\n clearTimeout(touchCursorTimer);\n touchCursor = { x: cx, y: cy };\n touchCursorVisible = true;\n render();\n touchCursorTimer = setTimeout(() => {\n touchCursorVisible = false;\n render();\n }, 450);\n }\n queue({ kind: \"button\", button, down: true, x: cx, y: cy });\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n }\n function pan(dx, dy) {\n manualViewMoved = true;\n cursorNeedsEntry = true;\n stopPanAnimation();\n const r = layout(),\n b = panBounds(r);\n place(\n rubber(rubber(r.x, b.minX, b.maxX, true) + dx, b.minX, b.maxX),\n rubber(rubber(r.y, b.minY, b.maxY, true) + dy, b.minY, b.maxY),\n r,\n );\n render();\n }\n function pair() {\n const [a, b] = [...pointers.values()];\n return {\n x: (a.x + b.x) / 2,\n y: (a.y + b.y) / 2,\n d: Math.hypot(a.x - b.x, a.y - b.y),\n };\n }\n function movePair() {\n gestureFrame = null;\n if (pointers.size < 2 || !multi) return;\n const next = pair(),\n span = Math.abs(next.d - multi.d),\n travel = Math.hypot(next.x - multi.x, next.y - multi.y);\n if (multi.kind !== \"pinch\") {\n const pinchSlop = Math.max(6, Math.min(12, multi.d * 0.04));\n if (span >= pinchSlop && span > travel * 0.65) {\n // A parallel scroll may deliver its two pointer updates in different\n // frames. Confirm separation briefly before taking over as a pinch.\n if (!multi.candidate)\n multi.candidate = {\n at: Date.now(),\n d: next.d,\n zoom,\n anchor: point(next),\n };\n if (Date.now() - multi.candidate.at >= 40) {\n if (multi.kind === \"scroll\") {\n multi.d = multi.candidate.d;\n multi.zoom = multi.candidate.zoom;\n multi.anchor = multi.candidate.anchor;\n }\n multi.kind = \"pinch\";\n multi.candidate = null;\n } else {\n gestureFrame = requestAnimationFrame(movePair);\n return;\n }\n } else {\n multi.candidate = null;\n if (!multi.kind && travel > 8 && travel > span) {\n multi.kind = \"scroll\";\n multi.restX = 0;\n multi.restY = 0;\n multi.aimed = mode !== \"touch\";\n }\n }\n }\n if (multi.kind === \"pinch\") {\n manualViewMoved = true;\n cursorNeedsEntry = true;\n const { maxZoom } = layout();\n zoom = Math.max(\n 1,\n Math.min(\n maxZoom,\n (Math.min(maxZoom, multi.zoom) * next.d) / Math.max(1, multi.d),\n ),\n );\n const r = layout();\n fx =\n multi.anchor.x +\n (viewportLeft() + viewportWidth() / 2 - next.x) / r.width;\n fy =\n multi.anchor.y +\n (viewportHeight() / 2 + verticalOffset(r.height) - next.y) / r.height;\n const moved = layout(),\n b = panBounds(moved);\n place(\n rubber(moved.x, b.minX, b.maxX),\n rubber(moved.y, b.minY, b.maxY),\n moved,\n );\n } else if (multi.kind === \"scroll\") {\n const dx = next.x - multi.lastX,\n dy = next.y - multi.lastY;\n if (control && mode !== \"pan\") {\n // Hosts scroll whatever is under the desktop cursor. Touch mode has no\n // visible pointer, so aim it at the fingers once they are over the\n // desktop; like taps, scrolling over the letterbox does nothing.\n if (!multi.aimed && insideDesktop(next)) {\n const p = point(next);\n cx = p.x;\n cy = p.y;\n queue({ kind: \"move\", x: cx, y: cy });\n multi.aimed = true;\n }\n // Hosts inject whole pixels; carry fractions so slow drags still scroll.\n const sx = multi.restX - dx,\n sy = multi.restY - dy,\n wx = Math.trunc(sx),\n wy = Math.trunc(sy);\n multi.restX = sx - wx;\n multi.restY = sy - wy;\n if (multi.aimed && (wx || wy))\n queue({\n kind: \"scroll\",\n dx: Math.max(-2000, Math.min(2000, wx)),\n dy: Math.max(-2000, Math.min(2000, wy)),\n });\n } else pan(dx, dy);\n }\n if (multi.kind) {\n multi.lastX = next.x;\n multi.lastY = next.y;\n }\n render();\n }\n listen(stage, \"pointerdown\", (e) => {\n if (config.desktop) {\n e.preventDefault();\n if (\n e.button === 1 &&\n (layout().width > viewportWidth() || layout().height > viewportHeight())\n ) {\n stopEdgePan();\n stopPanAnimation();\n desktopPan = {\n id: e.pointerId,\n x: e.clientX,\n y: e.clientY,\n start: e,\n moved: false,\n };\n stage.setPointerCapture(e.pointerId);\n return;\n }\n mouse(e, true);\n return;\n }\n e.preventDefault();\n stopPanAnimation();\n stage.setPointerCapture(e.pointerId);\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (pointers.size === 1) {\n cursorNeedsEntry = true;\n start = { x: e.clientX, y: e.clientY };\n last = start;\n moved = false;\n hold = setTimeout(() => {\n if (\n control &&\n mode !== \"pan\" &&\n !moved &&\n pointers.size === 1 &&\n !heldMouse.size &&\n (mode !== \"touch\" || insideDesktop(start))\n ) {\n if (mode === \"touch\") {\n const p = point(start);\n cx = p.x;\n cy = p.y;\n }\n queue({ kind: \"button\", button: 0, down: true, x: cx, y: cy });\n drag = true;\n }\n }, 400);\n } else {\n clearTimeout(hold);\n if (drag) queue({ kind: \"release\" });\n drag = false;\n start = null;\n const p = pair();\n multi = {\n ...p,\n lastX: p.x,\n lastY: p.y,\n zoom,\n anchor: point(p),\n kind: null,\n };\n }\n });\n listen(stage, \"pointermove\", (e) => {\n if (config.desktop) {\n if (desktopPan?.id === e.pointerId) {\n const dx = e.clientX - desktopPan.x,\n dy = e.clientY - desktopPan.y;\n if (!desktopPan.moved && Math.hypot(dx, dy) < 3) return;\n desktopPan.moved = true;\n desktopPan.x = e.clientX;\n desktopPan.y = e.clientY;\n pan(dx, dy);\n return;\n }\n trackEdgePointer(e);\n if (!control) return;\n const local = desktopPoint(e);\n if (!heldMouse.size && !insideDesktop(local)) return;\n const p = point(local);\n cx = p.x;\n cy = p.y;\n queue({ kind: \"move\", x: cx, y: cy });\n render();\n return;\n }\n if (!pointers.has(e.pointerId)) return;\n e.preventDefault();\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (pointers.size >= 2) {\n if (gestureFrame === null) gestureFrame = requestAnimationFrame(movePair);\n return;\n }\n if (!start || !last) return;\n const now = { x: e.clientX, y: e.clientY },\n dx = now.x - last.x,\n dy = now.y - last.y;\n last = now;\n if (Math.hypot(now.x - start.x, now.y - start.y) > 6) {\n moved = true;\n clearTimeout(hold);\n }\n if (\n !control ||\n mode === \"pan\" ||\n (mode === \"touch\" && !drag && !heldMouse.size)\n ) {\n pan(dx, dy);\n return;\n }\n if (mode === \"pointer\") {\n moveTouchpad(dx, dy);\n } else {\n const p = point(now);\n cx = p.x;\n cy = p.y;\n }\n queue({ kind: \"move\", x: cx, y: cy });\n render();\n });\n function up(e) {\n if (config.desktop) {\n if (desktopPan?.id === e.pointerId) {\n const gesture = desktopPan;\n desktopPan = null;\n if (gesture.moved) settlePan();\n else {\n mouse(gesture.start, true);\n mouse(e, false);\n }\n return;\n }\n mouse(e, false);\n return;\n }\n if (!pointers.has(e.pointerId)) return;\n clearTimeout(hold);\n if (pointers.size >= 2 && multi) {\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n movePair();\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n gestureFrame = null;\n }\n pointers.delete(e.pointerId);\n if (drag) {\n queue({ kind: \"button\", button: 0, down: false, x: cx, y: cy });\n drag = false;\n } else if (\n start &&\n !moved &&\n control &&\n mode !== \"pan\" &&\n !heldMouse.size &&\n e.type === \"pointerup\" &&\n (mode !== \"touch\" || insideDesktop({ x: e.clientX, y: e.clientY }))\n ) {\n if (mode === \"touch\") {\n const p = point({ x: e.clientX, y: e.clientY });\n cx = p.x;\n cy = p.y;\n }\n click();\n }\n start = null;\n last = null;\n multi = null;\n render();\n if (!pointers.size && manualViewMoved) settlePan();\n }\n listen(stage, \"pointerup\", up);\n listen(stage, \"pointercancel\", () => {\n release();\n settlePan();\n });\n listen(stage, \"lostpointercapture\", () => {\n desktopPan = null;\n if (config.desktop && heldMouse.size) release();\n });\n let wheelRestX = 0,\n wheelRestY = 0;\n if (config.desktop)\n listen(\n stage,\n \"wheel\",\n (e) => {\n e.preventDefault();\n if (!control) {\n wheelRestX = wheelRestY = 0;\n return;\n }\n const factor =\n e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? stage.clientHeight : 1;\n // Hosts inject whole pixels; carry fractions so slow trackpad and\n // scaled-display deltas still scroll.\n const sx = wheelRestX + e.deltaX * factor,\n sy = wheelRestY + e.deltaY * factor,\n wx = Math.trunc(sx) || 0,\n wy = Math.trunc(sy) || 0;\n wheelRestX = sx - wx;\n wheelRestY = sy - wy;\n if (!wx && !wy) return;\n queue({\n kind: \"scroll\",\n dx: Math.max(-2000, Math.min(2000, wx)),\n dy: Math.max(-2000, Math.min(2000, wy)),\n });\n // Let the existing input tick coalesce trackpad bursts. Key/button\n // edges still flush immediately, preserving their order with scrolls.\n },\n { passive: false },\n );\n listen(config.desktop ? stage : document, \"contextmenu\", (e) =>\n e.preventDefault(),\n );\n // Scope selection suppression to the desktop surface, preserving the hidden\n // textarea's native keyboard/IME editing and programmatic selection.\n listen(stage, \"selectstart\", (e) => e.preventDefault());\n listen(stage, \"dragstart\", (e) => e.preventDefault());\n const normalizedKey = (code) =>\n /^(Shift|Control|Alt|Meta)Right$/.test(code)\n ? code.replace(/Right$/, \"Left\")\n : code;\n // Remote key state: a key is held from its first keydown until its keyup.\n // macOS sends no keyup for keys first pressed while Command is held (Cmd+C);\n // only those are released together with Command. Membership is decided once,\n // on the not-held -> held transition, so auto-repeat never reclassifies a key.\n const hardwareKeys = new Set();\n const commandKeys = new Set();\n const isModifier = (code) => /^(Shift|Control|Alt|Meta)Left$/.test(code);\n function pressKey(code) {\n if (!hardwareKeys.has(code)) {\n if (macKeyboard && hardwareKeys.has(\"MetaLeft\") && !isModifier(code))\n commandKeys.add(code);\n hardwareKeys.add(code);\n }\n queue({ kind: \"key\", code, down: true });\n }\n function releaseKey(code, send) {\n commandKeys.delete(code);\n if (!hardwareKeys.delete(code)) return false;\n if (code === \"MetaLeft\") {\n for (const held of commandKeys)\n if (hardwareKeys.delete(held) && send)\n queue({ kind: \"key\", code: held, down: false });\n commandKeys.clear();\n }\n if (send) queue({ kind: \"key\", code, down: false });\n return send;\n }\n function forgetKeys() {\n hardwareKeys.clear();\n commandKeys.clear();\n }\n // Desktop only. Cmd/Ctrl+V holds the queue until the controller has pushed\n // the local clipboard (or `inputGate` / the deadline releases it); Cmd/Ctrl+C\n // and +X ask it to pull the computer's new copy soon after. Both are intents:\n // the keys themselves still reach the computer unchanged.\n function clipboardShortcut(e, code) {\n const chord = clipboardModifier === \"meta\" ? e.metaKey : e.ctrlKey;\n if (!config.desktop || e.repeat || e.altKey || !chord) return;\n if (code === \"KeyV\") {\n inputGateUntil = performance.now() + 1200;\n post({ type: \"clipboardIntent\", action: \"paste\" });\n } else if (code === \"KeyC\" || code === \"KeyX\")\n post({ type: \"clipboardIntent\", action: \"copy\" });\n }\n listen(document, \"keydown\", (e) => {\n if (config.desktop) {\n if (e.ctrlKey && e.altKey && e.code === \"Escape\") {\n e.preventDefault();\n release();\n showKeyboard(false);\n post({ type: \"releaseFocus\" });\n return;\n }\n if (\n document.activeElement !== keyboardInput ||\n e.isComposing ||\n composing\n )\n return;\n }\n // The focused textarea delivers characters through input (and editing\n // keys through beforeinput). Forwarding their keydown too types twice on\n // iOS, where the software keyboard reports both events.\n if (\n (config.desktop || keyboardEnabled) &&\n document.activeElement === keyboardInput &&\n !e.ctrlKey &&\n !e.metaKey &&\n !e.altKey &&\n (e.key?.length === 1 ||\n e.key === \"Process\" ||\n e.key === \"Dead\" ||\n (keyboardEnabled && [\"Backspace\", \"Enter\"].includes(e.code)))\n )\n return;\n if (control && validKeys.has(normalizedKey(e.code))) {\n e.preventDefault();\n const code = normalizedKey(e.code);\n clipboardShortcut(e, code);\n pressKey(code);\n }\n });\n listen(document, \"keyup\", (e) => {\n const code = normalizedKey(e.code);\n if (releaseKey(code, control && validKeys.has(code))) e.preventDefault();\n });\n if (config.desktop)\n listen(keyboardInput, \"blur\", () => {\n forgetKeys();\n release();\n });\n listen(window, \"blur\", () => {\n release();\n settlePan();\n });\n function reportViewport() {\n post({\n type: \"viewportChanged\",\n width: viewportWidth(),\n height: usableHeight(),\n });\n }\n const observer = new ResizeObserver(() => {\n statusOrigin = null;\n reportViewport();\n release();\n settlePan();\n render();\n });\n observer.observe(stage);\n cleanups.push(\n () => observer.disconnect(),\n () => stopPanAnimation(),\n () => stopBackgroundLoop(),\n () => clearTimeout(touchCursorTimer),\n );\n // Keep one bounded frame in this document only; never persist desktop pixels.\n // Snapshot before detaching the track. A JPEG fallback already lives in image.\n function retainFrame() {\n if (\n !videoPresented ||\n video.style.display !== \"block\" ||\n video.readyState < 2 ||\n !video.videoWidth ||\n !video.videoHeight\n )\n return;\n const canvas = document.createElement(\"canvas\");\n try {\n const scale = Math.min(\n 1,\n 1280 / Math.max(video.videoWidth, video.videoHeight),\n );\n canvas.width = Math.max(1, Math.round(video.videoWidth * scale));\n canvas.height = Math.max(1, Math.round(video.videoHeight * scale));\n const context = canvas.getContext(\"2d\");\n if (context) {\n context.drawImage(video, 0, 0, canvas.width, canvas.height);\n image.src = canvas.toDataURL(\"image/jpeg\", 0.7);\n }\n } catch {\n /* Keep the previous compatibility frame if WebKit cannot read video. */\n } finally {\n canvas.width = 0;\n canvas.height = 0;\n }\n }\n /* BEGIN RTC */\n\n let trickleIce = false,\n attemptId = null,\n retries = 0,\n exchangeId = 0;\n let configPending = false;\n let videoPresented = false,\n videoFrameCallback = null,\n videoPaintCallback = null;\n function cancelVideoHandoff() {\n if (videoFrameCallback !== null)\n video.cancelVideoFrameCallback?.(videoFrameCallback);\n if (videoPaintCallback !== null) cancelAnimationFrame(videoPaintCallback);\n videoFrameCallback = videoPaintCallback = null;\n }\n function revealVideo(g) {\n post({ type: \"videoFrameReady\", attemptId });\n // Keep the JPEG decoded and painted as a backing layer. Promote the video\n // only after its first frame; removing the image exposes WebKit repaint gaps.\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = null;\n videoPresented = true;\n video.style.zIndex = \"2\";\n if (typeof startBackgroundLoop === \"function\") startBackgroundLoop();\n post({ type: \"streaming\", attemptId });\n post({\n type: \"pipCapability\",\n supported: !!(\n video.webkitSupportsPresentationMode?.(\"picture-in-picture\") ||\n document.pictureInPictureEnabled\n ),\n });\n });\n });\n }\n function waitForVideoFrame(g) {\n if (g !== generation) return;\n if (\n video.readyState >= 2 &&\n video.videoWidth > 0 &&\n video.videoHeight > 0\n ) {\n revealVideo(g);\n return;\n }\n videoPaintCallback = requestAnimationFrame(() => waitForVideoFrame(g));\n }\n let retryTimer = null,\n deadlineTimer = null,\n disconnectTimer = null,\n stableTimer = null,\n iceTimer = null,\n gatherTimer = null,\n gatherDone = null;\n let localCandidates = [],\n localAck = 0,\n remoteAfter = 0,\n icePending = null,\n remoteSeen = new Set(),\n exchangeUntil = 0,\n remoteComplete = false;\n function clearRtcTimers() {\n for (const timer of [\n retryTimer,\n deadlineTimer,\n disconnectTimer,\n stableTimer,\n iceTimer,\n gatherTimer,\n ])\n clearTimeout(timer);\n retryTimer =\n deadlineTimer =\n disconnectTimer =\n stableTimer =\n iceTimer =\n gatherTimer =\n null;\n if (gatherDone) {\n gatherDone();\n gatherDone = null;\n }\n }\n function closeRtc(preserveFrame = true) {\n configPending = false;\n if (preserveFrame) retainFrame();\n generation++;\n clearRtcTimers();\n cancelVideoHandoff();\n videoPresented = false;\n localCandidates = [];\n localAck = remoteAfter = 0;\n icePending = null;\n remoteSeen = new Set();\n attemptId = null;\n clearInterval(statsTimer);\n statsTimer = null;\n statsSample = null;\n if (dc) dc.close();\n if (pc) pc.close();\n pc = null;\n dc = null;\n video.onplaying = null;\n video.srcObject = null;\n video.style.display = \"none\";\n video.style.zIndex = \"0\";\n image.style.display = \"block\";\n if (typeof stopBackgroundLoop === \"function\") stopBackgroundLoop();\n if (!preserveFrame) {\n image.removeAttribute(\"src\");\n if (typeof clearBackground === \"function\") clearBackground();\n }\n }\n function failRtc(reason, canRetry = true) {\n const failedAttempt = attemptId;\n release();\n closeRtc();\n post({ type: \"fallback\", attemptId: failedAttempt, reason });\n // Local consent is bounded by the host's picker lifetime. Reuse this retry\n // timer without consuming the finite network-recovery attempts.\n const capturePending = reason === \"capture-pending\";\n if (canRetry && epoch && (capturePending || retries < net.retryMs.length)) {\n const delay = capturePending\n ? net.retryMs[net.retryMs.length - 1]\n : net.retryMs[retries++];\n retryTimer = setTimeout(() => {\n retryTimer = null;\n if (epoch) connect();\n }, delay);\n }\n }\n function pollIce() {\n if (\n !pc ||\n !trickleIce ||\n !pc.remoteDescription ||\n icePending ||\n Date.now() >= exchangeUntil\n )\n return;\n const candidates = localCandidates.slice(\n localAck,\n localAck + net.batchSize,\n );\n icePending = {\n after: remoteAfter,\n sent: candidates.length,\n exchangeId: ++exchangeId,\n };\n post({\n type: \"ice\",\n attemptId,\n candidates,\n after: remoteAfter,\n exchangeId,\n });\n iceTimer = setTimeout(() => {\n icePending = null;\n pollIce();\n }, 4500);\n }\n async function receiveIce(message) {\n if (\n !pc ||\n !icePending ||\n message.attemptId !== attemptId ||\n message.exchangeId !== icePending.exchangeId\n )\n return;\n const rtc = pc,\n g = generation,\n batch = icePending;\n clearTimeout(iceTimer);\n try {\n if (message.error) {\n icePending = null;\n iceTimer = setTimeout(pollIce, 1000);\n return;\n }\n if (\n !Array.isArray(message.candidates) ||\n message.candidates.length > net.batchSize ||\n message.next !== batch.after + message.candidates.length ||\n message.next > net.maxCandidates\n )\n throw new Error();\n for (const candidate of message.candidates) {\n if (g !== generation) return;\n const key = JSON.stringify(candidate);\n if (remoteSeen.has(key)) continue;\n if (remoteSeen.size >= net.maxCandidates) throw new Error();\n await rtc.addIceCandidate(candidate);\n if (g !== generation) return;\n remoteSeen.add(key);\n }\n if (g !== generation) return;\n localAck += batch.sent;\n remoteAfter = message.next;\n remoteComplete = message.complete === true;\n icePending = null;\n if (!(\n remoteComplete &&\n rtc.iceGatheringState === \"complete\" &&\n localAck === localCandidates.length\n ))\n iceTimer = setTimeout(pollIce, net.pollMs);\n } catch {\n if (g === generation) failRtc(\"candidates\");\n }\n }\n async function receiveAnswer(message) {\n if (!pc || message.attemptId !== attemptId) return;\n const rtc = pc,\n g = generation;\n try {\n await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n if (g !== generation) return;\n clearTimeout(deadlineTimer);\n deadlineTimer = setTimeout(() => {\n if (g === generation && rtc.connectionState !== \"connected\")\n failRtc(\"connect-timeout\");\n }, net.connectMs);\n exchangeUntil = Date.now() + net.exchangeMs;\n pollIce();\n } catch {\n if (g === generation) failRtc(\"answer\");\n }\n }\n async function connect() {\n closeRtc();\n const g = generation;\n attemptId = String(g);\n if (!window.RTCPeerConnection) {\n failRtc(\"unsupported\", false);\n return;\n }\n configPending = true;\n deadlineTimer = setTimeout(\n () => {\n if (g === generation && configPending) {\n configPending = false;\n void startRtc(g, iceServers);\n }\n },\n (net.iceConfigMs ?? 8000) + (net.iceConfigBridgeMs ?? 500),\n );\n return post({ type: \"iceConfig\", attemptId });\n }\n async function receiveIceConfig(message) {\n if (!epoch || !configPending || message.attemptId !== attemptId) return;\n configPending = false;\n clearTimeout(deadlineTimer);\n deadlineTimer = null;\n await startRtc(generation, message.iceServers);\n }\n async function startRtc(g, servers) {\n try {\n const rtc = new RTCPeerConnection({ iceServers: servers });\n pc = rtc;\n dc = rtc.createDataChannel(\"input-v1\");\n rtc.addTransceiver(\"video\", { direction: \"recvonly\" });\n rtc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n rtc.onicecandidate = ({ candidate }) => {\n if (g !== generation || !candidate?.candidate || !trickleIce) return;\n if (localCandidates.length >= net.maxCandidates) {\n failRtc(\"candidate-limit\", false);\n return;\n }\n localCandidates.push({\n candidate: candidate.candidate,\n sdpMid: candidate.sdpMid,\n sdpMLineIndex: candidate.sdpMLineIndex,\n ...(candidate.usernameFragment\n ? { usernameFragment: candidate.usernameFragment }\n : {}),\n });\n // Gathering continues after the offer; the serial exchange flushes late addresses.\n };\n dc.onmessage = (e) => {\n try {\n if (g !== generation || pc !== rtc) return;\n if (typeof e.data !== \"string\" || e.data.length > 80000) return;\n const message = JSON.parse(e.data);\n if (message.type === \"cursor\") receiveCursor(message.cursor);\n if (\n message.type === \"reply\" &&\n typeof message.id === \"string\" &&\n message.id.length <= 64\n )\n post({\n type: \"channelReply\",\n id: message.id,\n ok: message.ok === true,\n result: message.result,\n error: typeof message.error === \"string\" ? message.error : null,\n });\n if (\n (video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video) &&\n message.type === \"viewPing\" &&\n typeof message.challenge === \"string\" &&\n message.challenge.length <= 64 &&\n dc?.readyState === \"open\"\n )\n dc.send(message.challenge);\n } catch {}\n };\n let readingStats = false;\n statsTimer = setInterval(async () => {\n if (readingStats || g !== generation) return;\n readingStats = true;\n try {\n const stats = await rtc.getStats();\n if (g !== generation || pc !== rtc) return;\n const result = networkStats(stats, statsSample);\n statsSample = result.sample;\n post({\n type: \"network\",\n transport: result.transport,\n bytesPerSecond: result.bytesPerSecond,\n latencyMs: result.latencyMs,\n });\n } catch {\n } finally {\n readingStats = false;\n }\n }, 1000);\n rtc.ontrack = (e) => {\n if (g !== generation) return;\n video.srcObject = e.streams[0] || new MediaStream([e.track]);\n video.play().catch(() => {});\n };\n video.onplaying = () => {\n if (\n g !== generation ||\n videoPresented ||\n videoFrameCallback !== null ||\n videoPaintCallback !== null\n )\n return;\n video.style.display = \"block\";\n render();\n if (typeof scheduleBackgroundDraw === \"function\")\n scheduleBackgroundDraw();\n if (typeof video.requestVideoFrameCallback === \"function\") {\n videoFrameCallback = video.requestVideoFrameCallback(() => {\n if (g !== generation) return;\n videoFrameCallback = null;\n revealVideo(g);\n });\n } else waitForVideoFrame(g);\n };\n rtc.onconnectionstatechange = () => {\n if (g !== generation) return;\n if ([\"failed\", \"closed\"].includes(rtc.connectionState)) {\n failRtc(\"transport\");\n return;\n }\n if (rtc.connectionState === \"disconnected\") {\n clearTimeout(stableTimer);\n stableTimer = null;\n if (!disconnectTimer) {\n release();\n post({ type: \"reconnecting\", attemptId });\n disconnectTimer = setTimeout(() => {\n if (g === generation) failRtc(\"disconnected\");\n }, net.disconnectedMs);\n }\n } else if (rtc.connectionState === \"connected\") {\n clearTimeout(disconnectTimer);\n disconnectTimer = null;\n clearTimeout(deadlineTimer);\n if (!stableTimer)\n stableTimer = setTimeout(() => {\n if (g === generation) retries = 0;\n }, net.stableMs);\n if (videoPresented) post({ type: \"streaming\", attemptId });\n }\n };\n await rtc.setLocalDescription(await rtc.createOffer());\n if (!trickleIce)\n await new Promise((resolve) => {\n if (rtc.iceGatheringState === \"complete\") return resolve();\n gatherDone = resolve;\n gatherTimer = setTimeout(resolve, net.legacyGatherMs);\n rtc.onicegatheringstatechange = () => {\n if (rtc.iceGatheringState === \"complete\") {\n clearTimeout(gatherTimer);\n resolve();\n }\n };\n });\n if (g !== generation) return;\n post({ type: \"offer\", attemptId, sdp: rtc.localDescription.sdp });\n deadlineTimer = setTimeout(() => {\n if (g === generation) failRtc(\"answer-timeout\");\n }, net.answerMs);\n } catch {\n if (g === generation) failRtc(\"setup\");\n }\n }\n\n /* END RTC */\n function reportPresentation() {\n post({\n type: \"presentation\",\n active:\n video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video,\n });\n }\n listen(video, \"webkitpresentationmodechanged\", reportPresentation);\n listen(video, \"enterpictureinpicture\", reportPresentation);\n listen(video, \"leavepictureinpicture\", reportPresentation);\n function applyDisplayGeometry(message) {\n if (\n !Number.isInteger(message.width) ||\n !Number.isInteger(message.height) ||\n message.width < 320 ||\n message.height < 320 ||\n (message.restore !== true &&\n (message.width > 2560 || message.height > 2560))\n )\n return;\n release();\n stopPanAnimation();\n viewerSized = message.restore !== true;\n zoom = 1;\n desktopScale = null;\n fx = fy = 0.5;\n followRest = null;\n dw = message.width;\n dh = message.height;\n render();\n }\n function receive(event) {\n let message;\n try {\n message = JSON.parse(event.data);\n } catch {\n return;\n }\n switch (message.type) {\n // A small control request routed over the live data channel. The host\n // only receives it after advertising support; otherwise the parent uses\n // the relay. `sent` tells the parent whether the channel took it.\n case \"channelRequest\": {\n const id =\n typeof message.id === \"string\" && message.id.length <= 64\n ? message.id\n : null;\n if (!id) break;\n let sent = false;\n try {\n const data = JSON.stringify({\n type: \"request\",\n id,\n request: message.request,\n });\n if (\n pc?.connectionState === \"connected\" &&\n dc?.readyState === \"open\" &&\n dc.bufferedAmount < 16384 &&\n data.length <= 32768\n ) {\n dc.send(data);\n sent = true;\n }\n } catch {}\n post({ type: \"channelRequestState\", id, sent });\n break;\n }\n case \"measureViewport\":\n post({\n type: \"viewportSize\",\n width: viewportWidth(),\n height: usableHeight(),\n });\n break;\n case \"presentation\":\n if (config.nativeMedia) {\n release();\n showKeyboard(false);\n break;\n }\n try {\n if (message.enabled) {\n release();\n showKeyboard(false);\n if (video.webkitSupportsPresentationMode?.(\"picture-in-picture\"))\n video.webkitSetPresentationMode(\"picture-in-picture\");\n else if (video.requestPictureInPicture)\n video\n .requestPictureInPicture()\n .catch(() => post({ type: \"presentationFailed\" }));\n else post({ type: \"presentationFailed\" });\n } else if (video.webkitSetPresentationMode)\n video.webkitSetPresentationMode(\"inline\");\n else if (document.pictureInPictureElement)\n document.exitPictureInPicture().catch(() => {});\n } catch {\n post({ type: \"presentationFailed\" });\n }\n break;\n case \"videoSettings\":\n applyDisplayGeometry(message);\n video.muted = !message.audio;\n retries = 0;\n if (!config.nativeMedia) connect();\n break;\n // The host kept the stream across a display change: layout only.\n case \"displayGeometry\":\n applyDisplayGeometry(message);\n break;\n case \"keyboard\":\n showKeyboard(message.enabled === true);\n break;\n case \"resume\":\n if (video.srcObject) video.play().catch(() => {});\n break;\n case \"releaseInput\":\n release();\n break;\n case \"inputGate\":\n if (inputGateUntil) pendingSince = performance.now();\n inputGateUntil = 0;\n flush();\n break;\n case \"theme\":\n if (/^#[0-9a-f]{3,8}$/i.test(message.surface)) {\n document.body.style.background = config.nativeMedia\n ? \"transparent\"\n : message.surface;\n document.documentElement.style.background = config.nativeMedia\n ? \"transparent\"\n : message.surface;\n document.documentElement.style.setProperty(\n \"--surface\",\n message.surface,\n );\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.foreground)) {\n cursor.style.borderColor = message.foreground;\n document.documentElement.style.setProperty(\n \"--foreground\",\n message.foreground,\n );\n }\n break;\n case \"networkStatus\": {\n const status = find(\"network-status\");\n if (!status) break;\n status.textContent =\n typeof message.text === \"string\" ? message.text : \"\";\n status.style.display = status.textContent ? \"block\" : \"none\";\n for (const key of [\"top\", \"right\", \"fontSize\"]) {\n if (Number.isFinite(message[key]) && message[key] >= 0)\n status.style[key] = message[key] + \"px\";\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.color))\n status.style.color = message.color;\n statusOrigin = null;\n clipNetworkStatus();\n break;\n }\n case \"nativeTouchpad\": {\n if (!nativeMouseControls || !control) break;\n if (message.phase === \"start\") {\n nativeTouchpad = { down: true };\n cursorNeedsEntry = true;\n break;\n }\n if (message.phase === \"end\") {\n if (nativeTouchpad) nativeTouchpad.down = false;\n break;\n }\n if (message.tap === true) {\n if (!heldMouse.size) { click(); flush(); }\n break;\n }\n if (!Number.isFinite(message.dx) || !Number.isFinite(message.dy)) break;\n nativeTouchpad ??= { down: false };\n moveTouchpad(message.dx, message.dy);\n queue({ kind: \"move\", x: cx, y: cy });\n render();\n break;\n }\n case \"nativeMouse\": {\n if (\n !nativeMouseControls ||\n ![\"left\", \"right\", \"wheel\"].includes(message.control)\n )\n break;\n if (\n ![\n \"pointerdown\",\n \"pointermove\",\n \"pointerup\",\n \"pointercancel\",\n \"click\",\n ].includes(message.event)\n )\n break;\n if (!Number.isFinite(message.id) || !Number.isFinite(message.y)) break;\n mouseControlHandlers.get(\n \"mouse-\" + message.control + \":\" + message.event,\n )?.({\n pointerId: message.id,\n clientY: message.y,\n detail: 0,\n nativeInput: true,\n preventDefault() {},\n });\n break;\n }\n case \"mouseButtons\": {\n nativeMouseControls = message.native === true;\n const before = layout(),\n previousTopInset = viewportTopInset,\n previousBottomInset = viewportBottomInset,\n keyboardOpen = fillHeight && message.keyboardOpen === true;\n const keepHorizontal =\n fillHeight && (keyboardOpen || keyboardViewportOpen);\n // Hiding the rail for the keyboard must not enlarge a width-fitted desktop.\n if (keyboardOpen && (!keyboardViewportOpen || !keyboardFitWidth)) {\n keyboardFitWidth = { stageWidth: stage.clientWidth, width: viewportWidth() };\n }\n if (!keyboardOpen) keyboardFitWidth = null;\n // Opening is observable before the native keyboard has a measured height.\n keyboardViewportOpen = keyboardOpen;\n const fitChanged = fitToInsets !== (message.fitToInsets === true);\n fitToInsets = message.fitToInsets === true;\n const previousOffset = portraitKeyboardTopInset;\n if (Number.isFinite(message.portraitKeyboardTopInset))\n portraitKeyboardTopInset = Math.max(\n 0,\n message.portraitKeyboardTopInset,\n );\n const offsetChanged = previousOffset !== portraitKeyboardTopInset;\n let sideInsetsChanged = false;\n if (Number.isFinite(message.topInset))\n viewportTopInset = Math.max(\n 0,\n Math.min(stage.clientHeight - 1, message.topInset),\n );\n if (Number.isFinite(message.bottomInset))\n viewportBottomInset = Math.max(\n 0,\n Math.min(stage.clientHeight - 1, message.bottomInset),\n );\n if (Number.isFinite(message.leftInset)) {\n const inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.leftInset),\n );\n sideInsetsChanged = sideInsetsChanged || inset !== viewportLeftInset;\n viewportLeftInset = inset;\n }\n if (Number.isFinite(message.rightInset)) {\n const inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.rightInset),\n );\n sideInsetsChanged = sideInsetsChanged || inset !== viewportRightInset;\n viewportRightInset = inset;\n }\n // Hiding the side toolbar changes the viewport center. Keep the image's\n // actual horizontal position instead of following that center sideways.\n if (keepHorizontal) {\n stopPanAnimation();\n const r = layout();\n place(before.x, r.y, r);\n }\n const keyboardInset = keyboardOpen ? viewportBottomInset : 0;\n if (keyboardInset !== keyboardViewportInset) {\n const wasOpen = keyboardViewportInset > 0;\n keyboardViewportInset = keyboardInset;\n if (fillHeight && (keyboardInset > 0 || wasOpen)) {\n const r = layout(),\n v = cursorViewport();\n place(r.x, (v.minY + v.maxY) / 2 - cy * r.height, r);\n cursorNeedsEntry = false;\n manualViewMoved = false;\n }\n }\n if (keepHorizontal) {\n // Restoring the toolbar can cover the cursor even after a zero-height opening.\n if (!keyboardOpen || keyboardInset > 0) {\n const r = layout(),\n v = cursorViewport(),\n x = r.x + cx * r.width;\n place(r.x + bounded(x, v.minX, v.maxX) - x, r.y, r);\n }\n followRest = { fx, fy, zoom };\n render();\n } else if (\n fitChanged ||\n sideInsetsChanged ||\n offsetChanged ||\n (usesViewportInsets() && previousTopInset !== viewportTopInset) ||\n (usesViewportInsets() && previousBottomInset !== viewportBottomInset)\n ) {\n settlePan();\n render();\n }\n reportViewport();\n if (!message.enabled) {\n for (const button of heldMouse.keys())\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n heldMouse.clear();\n resetWheel();\n flush();\n }\n for (const [edge, value] of [\n [\"bottom\", message.bottomInset],\n [\"right\", message.rightInset],\n ])\n if (Number.isFinite(value) && value >= 0 && value <= 4096)\n mouseButtons.style[edge] = value + \"px\";\n showMouseButtons = message.enabled === true;\n for (const name of [\"left\", \"right\", \"wheel\"])\n if (typeof message.labels?.[name] === \"string\")\n find(\"mouse-\" + name).setAttribute(\n \"aria-label\",\n message.labels[name],\n );\n updateMouseButtons();\n break;\n }\n case \"init\":\n nativeVideoActive = false;\n // Clear instead of forcing visible: the stylesheet hides an image with\n // no frame yet, otherwise the browser paints a broken-image box.\n image.style.visibility = \"\";\n desktopScale = null;\n reportedScaleMode = null;\n if (config.desktop) {\n zoom = 1;\n fx = 0.5;\n fy = 0.5;\n }\n viewerSized = false;\n followRest = null;\n cursorNeedsEntry = true;\n stopPanAnimation();\n resetCursor();\n control = false;\n release();\n pending = [];\n sending = false;\n seq = 0;\n epoch = message.epoch;\n macKeyboard = config.desktop && message.macKeyboard === true;\n clipboardModifier =\n message.clipboardModifier === \"meta\" ? \"meta\" : \"control\";\n inputGateUntil = 0;\n dw = message.width;\n dh = message.height;\n fillHeight = message.fillHeight === true;\n video.muted = !message.audio;\n trickleIce = message.trickleIce === true;\n retries = 0;\n render();\n if (!config.nativeMedia) connect();\n break;\n case \"nativeVideo\":\n if (!config.nativeMedia || message.epoch !== epoch) break;\n nativeVideoActive = message.active === true;\n image.style.visibility = nativeVideoActive ? \"hidden\" : \"\";\n clipNetworkStatus();\n paintBackground();\n break;\n case \"nativeCursor\":\n if (config.nativeMedia && message.epoch === epoch)\n receiveCursor(message.cursor);\n break;\n case \"viewport\":\n if (fillHeight !== (message.fillHeight === true)) keyboardFitWidth = null;\n fillHeight = message.fillHeight === true;\n release();\n render();\n break;\n case \"answer\":\n if (message.epoch === epoch) void receiveAnswer(message);\n break;\n case \"iceConfig\":\n if (message.epoch === epoch) void receiveIceConfig(message);\n break;\n case \"ice\":\n if (message.epoch === epoch) void receiveIce(message);\n break;\n case \"fallback\":\n if (message.epoch === epoch && message.attemptId === attemptId)\n failRtc(\n message.capturePending === true ? \"capture-pending\" : \"host\",\n message.retry !== false,\n );\n break;\n case \"frame\": {\n if (\"cursor\" in message) receiveCursor(message.cursor);\n else resetCursor();\n const frameEpoch = epoch;\n image.onload = () => {\n if (epoch === frameEpoch) {\n scheduleBackgroundDraw();\n post({ type: \"framePresented\" });\n }\n };\n image.src = \"data:image/jpeg;base64,\" + message.jpeg;\n break;\n }\n case \"control\": {\n // A local view-only switch keeps host control, so its release must\n // still reach the host even if a batch was waiting for its ACK.\n const releaseHost =\n control && message.enabled !== true && message.release === true;\n release();\n // A new control intent abandons the previous relay batch. Advance the\n // existing sequence fence so a late old ACK cannot unlock a new batch.\n seq++;\n sending = false;\n inputGateUntil = 0;\n control = message.enabled;\n if (!control) showKeyboard(false);\n pending = [];\n if (releaseHost) {\n pending = [{ kind: \"release\" }];\n pendingSince = performance.now();\n flush();\n }\n updateMouseButtons();\n render();\n break;\n }\n case \"mode\":\n release();\n if (message.mode !== \"pointer\") followRest = null;\n settlePan();\n clearTimeout(touchCursorTimer);\n touchCursorVisible = false;\n mode = message.mode;\n render();\n break;\n case \"zoom\":\n stopEdgePan();\n if (\n !config.desktop ||\n !Number.isFinite(message.factor) ||\n message.factor <= 0\n )\n break;\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = true;\n stopPanAnimation();\n const fitScale = Math.min(viewportWidth() / dw, viewportHeight() / dh);\n // Include actual size even when it lies outside the fit-relative range.\n desktopScale = Math.max(\n Math.min(fitScale, 1) * 0.1,\n Math.min(Math.max(5 * fitScale, 5), layout().scale * message.factor),\n );\n if (Math.abs(desktopScale - fitScale) < 1e-9) desktopScale = null;\n if (desktopScale === null) {\n fx = 0.5;\n fy = 0.5;\n manualViewMoved = false;\n }\n render();\n settlePan();\n break;\n case \"actualSize\":\n stopEdgePan();\n if (!config.desktop) break;\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = true;\n stopPanAnimation();\n desktopScale = 1;\n fx = 0.5;\n fy = 0.5;\n render();\n break;\n case \"fit\":\n stopEdgePan();\n desktopScale = null;\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = false;\n stopPanAnimation();\n zoom = 1;\n fx = 0.5;\n fy = 0.5;\n render();\n break;\n case \"rightClick\":\n click(2);\n break;\n case \"events\":\n for (const e of message.events) queue(e);\n flush();\n break;\n case \"ack\":\n if (message.epoch === epoch && message.sequence === seq)\n sending = false;\n break;\n case \"stop\":\n nativeVideoActive = false;\n image.style.visibility = \"\";\n showKeyboard(false);\n control = false;\n release();\n pending = [];\n sending = false;\n epoch = null;\n closeRtc(message.preserveFrame === true);\n updateMouseButtons();\n render();\n break;\n }\n }\n // iOS can report equal left/right safe areas in both landscape directions.\n // Its interface angle distinguishes the notch side even on a 180-degree turn.\n const reportOrientation = () => {\n const angle =\n typeof window.orientation === \"number\"\n ? window.orientation\n : window.screen?.orientation?.angle;\n if (Number.isFinite(angle)) post({ type: \"orientation\", angle });\n };\n listen(window, \"orientationchange\", reportOrientation);\n if (window.screen?.orientation?.addEventListener)\n listen(window.screen.orientation, \"change\", reportOrientation);\n render();\n reportOrientation();\n post({ type: \"ready\" });\n return {\n receive: (message) => receive({ data: JSON.stringify(message) }),\n dispose: () => {\n release();\n epoch = null;\n closeRtc(false);\n if (bgDrawFrame !== null) cancelAnimationFrame(bgDrawFrame);\n bgDrawFrame = null;\n for (const cleanup of cleanups) cleanup();\n },\n };\n}\n";