Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Takeover on a phone: the page takes the overlay's size, and gets its own back on every close (B2) (#310)

Oleksandr Ivanchenko1893db92f8df
diff --git a/frontend/src/components/BrowserControlOverlay.tsx b/frontend/src/components/BrowserControlOverlay.tsx
index 20a600b6..5747286f 100644
--- a/frontend/src/components/BrowserControlOverlay.tsx
+++ b/frontend/src/components/BrowserControlOverlay.tsx
@@ -1,6 +1,6 @@
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
-import { CheckCircle2, Hand, Keyboard, Loader2, Maximize, Puzzle } from 'lucide-react';
+import { CheckCircle2, Hand, Keyboard, Loader2, Maximize, Move, Puzzle } from 'lucide-react';
import {
Box,
PAGE_H,
@@ -16,6 +16,7 @@ import {
stageToPageClamped,
zoomToBox,
} from '../browserGestures';
+import { resizeFor } from '../browserInput';
import { domainOf } from '../humanSteps';
import { haptic } from '../haptics';
import type { BrowserStream } from '../useBrowserStream';
@@ -26,6 +27,22 @@ export function sendPageInput(send: (payload: Record<string, unknown>, input?: b
send(input.action === 'scroll' ? input : { ...input, delta_x: 0, delta_y: 0 }, input.action !== 'pointer_move');
}
+/** How long the overlay waits for a rotate or a keyboard to settle before sizing the page again. */
+export const OVERLAY_RESIZE_DEBOUNCE_MS = 150;
+/** Set once the pinch hint has shown on this device. */
+export const PINCH_HINT_KEY = 'kw-pinch-hint';
+export const PINCH_HINT_MS = 4000;
+export const PINCH_HINT_FADE_MS = 160;
+
+/**
+ * The page's width fills the stage and its top sits at the top: for a page that keeps its own
+ * size (a real window), where fit-contain would leave it small with bands beside it.
+ */
+export function fitWidthView(stage: Size, page: Size = { width: PAGE_W, height: PAGE_H }): View {
+ if (stage.width <= 0 || stage.height <= 0 || page.width <= 0) return fitView(stage, page);
+ return clampView({ scale: stage.width / page.width, tx: 0, ty: 0 }, stage, page);
+}
+
/** A live page image the person drives with a finger (tap, drag) and zooms with two (pinch, pan). */
function ZoomStage({
image,
@@ -35,8 +52,19 @@ function ZoomStage({
onTap,
label,
page = { width: PAGE_W, height: PAGE_H },
+ fitWidth = false,
+ onStage,
+ liftButtons = false,
+ children,
}: {
page?: Size;
+ /** The page keeps its own size: open at fit-width, top-aligned, instead of fit-contain. */
+ fitWidth?: boolean;
+ /** The stage's size whenever it changes (open, rotate, the phone's keyboard). */
+ onStage?: (stage: Size) => void;
+ /** Something sits at the stage's bottom centre (the pinch hint): the buttons move up. */
+ liftButtons?: boolean;
+ children?: React.ReactNode;
image: string | null;
onFrameDone: () => void;
send: (input: PageInput) => void;
@@ -58,12 +86,23 @@ function ZoomStage({
useLayoutEffect(() => {
const el = stageRef.current;
if (!el) return;
- const measure = () => setStage({ width: el.clientWidth, height: el.clientHeight });
+ const measure = () => setStage((s) => (s.width === el.clientWidth && s.height === el.clientHeight ? s : { width: el.clientWidth, height: el.clientHeight }));
measure();
const ro = new ResizeObserver(measure);
ro.observe(el);
- return () => ro.disconnect();
+ // a rotate on iOS can settle the visual viewport after the layout box
+ const vv = window.visualViewport;
+ vv?.addEventListener('resize', measure);
+ return () => {
+ ro.disconnect();
+ vv?.removeEventListener('resize', measure);
+ };
}, []);
+ const onStageRef = useRef(onStage);
+ onStageRef.current = onStage;
+ useEffect(() => {
+ if (stage.width > 0 && stage.height > 0) onStageRef.current?.(stage);
+ }, [stage]);
const targetKey = target ? `${target.x},${target.y},${target.width},${target.height}` : '';
useEffect(() => {
@@ -74,10 +113,10 @@ function ZoomStage({
useLayoutEffect(() => {
if (!stage.width || !stage.height) return;
if (mode === 'box' && target) setView(zoomToBox(target, stage, page));
- else if (mode === 'fit' || (mode === 'box' && !target)) setView(fitView(stage, page));
+ else if (mode === 'fit' || (mode === 'box' && !target)) setView(fitWidth ? fitWidthView(stage, page) : fitView(stage, page));
else setView((v) => clampView(v, stage, page));
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [stage.width, stage.height, mode, targetKey, page.width, page.height]);
+ }, [stage.width, stage.height, mode, targetKey, page.width, page.height, fitWidth]);
const pageRef = useRef(page);
pageRef.current = page;
@@ -150,7 +189,9 @@ function ZoomStage({
</div>
)}
- <div className="absolute right-3 bottom-3 flex gap-2" style={{ marginBottom: 'env(safe-area-inset-bottom)' }}>
+ {children}
+
+ <div className={`absolute right-3 flex gap-2 ${liftButtons ? 'bottom-16' : 'bottom-3'}`} style={{ marginBottom: 'env(safe-area-inset-bottom)' }}>
{target && mode !== 'box' && (
<button
type="button"
@@ -186,6 +227,41 @@ export function textEdits(before: string, after: string): Array<{ action: 'key';
return out;
}
+/** The overlay's own history entry, left for the next overlay when one opens right away (a re-mount). */
+let leaving: { timer: number } | null = null;
+const OVERLAY_ENTRY = 'kwBrowserOverlay';
+
+/**
+ * Adds a history entry while the overlay is up, so the phone's back gesture (or Back) lands on it
+ * and calls `onBack` instead of leaving the page. Closed any other way, the entry is taken off
+ * again. Returns the cleanup.
+ */
+export function backGestureEntry(onBack: () => void): () => void {
+ if (typeof window === 'undefined' || !window.history) return () => {};
+ const ours = () => !!(window.history.state && (window.history.state as Record<string, unknown>)[OVERLAY_ENTRY]);
+ if (leaving) {
+ // the entry from a moment ago is still there: keep it
+ window.clearTimeout(leaving.timer);
+ leaving = null;
+ }
+ if (!ours()) {
+ const state = window.history.state && typeof window.history.state === 'object' ? window.history.state : {};
+ window.history.pushState({ ...state, [OVERLAY_ENTRY]: true }, '');
+ }
+ const onPop = () => {
+ if (!ours()) onBack();
+ };
+ window.addEventListener('popstate', onPop);
+ return () => {
+ window.removeEventListener('popstate', onPop);
+ const timer = window.setTimeout(() => {
+ leaving = null;
+ if (ours()) window.history.back();
+ }, 0);
+ leaving = { timer };
+ };
+}
+
const PASSED_KEYS = ['Enter', 'Tab', 'Escape', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'];
export interface BrowserControlOverlayProps {
@@ -209,6 +285,12 @@ export interface BrowserControlOverlayProps {
stream?: Pick<BrowserStream, 'select' | 'dialog' | 'clearSelect' | 'clearDialog'>;
/** An open sign-in, code or other step for this browser: its Done sits on the status line. */
step?: { need: string; doneLabel: string; onDone: () => Promise<string | void> | void } | null;
+ /** The person controls the page (or a human step lets their input through): size it to the stage. */
+ controlling?: boolean;
+ /** The browser answered a resize with `ignored` (a real window keeps its own size). */
+ resizeIgnored?: boolean;
+ /** Gives the page its own size back without handing back (the overlay closes or the app goes to the background). */
+ restoreSize?: () => void;
}
/**
@@ -231,8 +313,75 @@ export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({
page,
stream,
step = null,
+ controlling = false,
+ resizeIgnored = false,
+ restoreSize,
}) => {
const keys = useRef<HTMLInputElement>(null);
+ const sendRef = useRef(send);
+ sendRef.current = send;
+ const restoreRef = useRef(restoreSize);
+ restoreRef.current = restoreSize;
+ const onHandBackRef = useRef(onHandBack);
+ onHandBackRef.current = onHandBack;
+
+ // The page takes the stage's size, so it shows 1:1: at once on open, again after a rotate
+ // settles. `sized` is true while this overlay's size is on the page.
+ const [stageSize, setStageSize] = useState<Size>({ width: 0, height: 0 });
+ const [wake, setWake] = useState(0);
+ const lastResize = useRef('');
+ const sized = useRef(false);
+ useEffect(() => {
+ if (!controlling) {
+ lastResize.current = '';
+ return;
+ }
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;
+ const msg = resizeFor(stageSize, window.devicePixelRatio);
+ if (!msg) return;
+ const key = `${msg.width}x${msg.height}@${msg.dpr}`;
+ if (key === lastResize.current) return;
+ const t = window.setTimeout(() => {
+ lastResize.current = key;
+ sized.current = true;
+ sendRef.current(msg);
+ }, lastResize.current ? OVERLAY_RESIZE_DEBOUNCE_MS : 0);
+ return () => window.clearTimeout(t);
+ }, [controlling, stageSize.width, stageSize.height, wake]);
+
+ // Every way the overlay goes away gives the bot its own size back. Hand back does it on the
+ // server; the app going to the background, or the overlay closing any other way, does it here.
+ // (A dropped socket: the server restores on close.)
+ const letGo = useCallback(() => {
+ if (!sized.current) return;
+ sized.current = false;
+ lastResize.current = '';
+ restoreRef.current?.();
+ }, []);
+ useEffect(() => {
+ const onVisibility = () => {
+ if (document.visibilityState === 'hidden') letGo();
+ else setWake((w) => w + 1);
+ };
+ document.addEventListener('visibilitychange', onVisibility);
+ window.addEventListener('pagehide', letGo);
+ return () => {
+ document.removeEventListener('visibilitychange', onVisibility);
+ window.removeEventListener('pagehide', letGo);
+ letGo();
+ };
+ }, [letGo]);
+ const handBack = useCallback(() => {
+ // release_control puts the size back on the server
+ sized.current = false;
+ lastResize.current = '';
+ onHandBackRef.current();
+ }, []);
+
+ // The phone's back gesture hands back instead of leaving the chat under the overlay
+ useEffect(() => backGestureEntry(() => handBack()), [handBack]);
+
+ const [hintUp, setHintUp] = useState(false);
const [stepBusy, setStepBusy] = useState(false);
const [stepError, setStepError] = useState<string | null>(null);
const answerStep = async () => {
@@ -242,7 +391,7 @@ export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({
try {
const err = await step.onDone();
if (err) setStepError(err);
- else onHandBack();
+ else handBack();
} finally {
setStepBusy(false);
}
@@ -327,7 +476,7 @@ export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({
type="button"
onClick={() => {
haptic('tap');
- onHandBack();
+ handBack();
}}
data-primary={step ? undefined : true}
className={`shrink-0 inline-flex items-center gap-1.5 h-11 px-3 rounded-[10px] text-sm font-semibold focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300 ${
@@ -341,7 +490,7 @@ export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({
<p
role="status"
aria-live="polite"
- className={`px-3 pb-2 text-xs ${solved ? 'text-[#5eead4]' : error || stepError ? 'text-rose-300' : 'text-[#fcd34d]'}`}
+ className={`px-3 pb-2 text-[13px] leading-[18px] ${solved ? 'text-[#5eead4]' : error || stepError ? 'text-rose-300' : 'text-[#fcd34d]'}`}
>
{solved ? (
<span className="inline-flex items-center gap-1.5">
@@ -354,7 +503,7 @@ export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({
)}
</p>
) : step ? (
- <div className="min-h-[52px] pl-3 pr-2 pb-2 flex items-center gap-2 text-xs">
+ <div className="min-h-[52px] pl-3 pr-2 pb-2 flex items-center gap-2 text-[13px] leading-[18px]">
<span role="status" aria-live="polite" className="flex-1 min-w-0 truncate font-semibold text-[#fcd34d]">
@{botName} {step.need}
</span>
@@ -379,7 +528,12 @@ export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({
target={captcha?.target ?? null}
label={`${botName}'s page. Tap to click, drag with one finger, pinch to zoom.`}
page={page}
- />
+ fitWidth={resizeIgnored}
+ onStage={setStageSize}
+ liftButtons={hintUp}
+ >
+ <PinchHint show={resizeIgnored} onGone={setHintUp} />
+ </ZoomStage>
{stream?.select && (
<SelectPopover
@@ -445,4 +599,54 @@ export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({
);
};
+/**
+ * "Pinch to zoom · drag to move", once per device, for a page that keeps its own size. It stays
+ * PINCH_HINT_MS, then fades (or, under reduced motion, just goes).
+ */
+function PinchHint({ show, onGone }: { show: boolean; onGone?: (shown: boolean) => void }) {
+ const [state, setState] = useState<'hidden' | 'shown' | 'fading'>('hidden');
+ const onGoneRef = useRef(onGone);
+ onGoneRef.current = onGone;
+ useEffect(() => {
+ if (!show) return;
+ try {
+ if (window.localStorage.getItem(PINCH_HINT_KEY)) return;
+ window.localStorage.setItem(PINCH_HINT_KEY, '1');
+ } catch {
+ return;
+ }
+ const still = typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+ setState('shown');
+ onGoneRef.current?.(true);
+ const timers: number[] = [];
+ const gone = () => {
+ setState('hidden');
+ onGoneRef.current?.(false);
+ };
+ timers.push(
+ window.setTimeout(() => {
+ if (still) gone();
+ else {
+ setState('fading');
+ timers.push(window.setTimeout(gone, PINCH_HINT_FADE_MS));
+ }
+ }, PINCH_HINT_MS)
+ );
+ return () => timers.forEach((t) => window.clearTimeout(t));
+ }, [show]);
+ if (state === 'hidden') return null;
+ return (
+ <div
+ role="status"
+ data-pinch-hint
+ className={`absolute left-1/2 -translate-x-1/2 bottom-4 h-10 px-4 inline-flex items-center gap-2 whitespace-nowrap rounded-full bg-[#231d4b] text-[13px] leading-4 text-[#ecebfa] pointer-events-none transition-opacity duration-[160ms] motion-reduce:transition-none ${
+ state === 'fading' ? 'opacity-0' : 'opacity-100'
+ }`}
+ style={{ marginBottom: 'env(safe-area-inset-bottom)' }}
+ >
+ <Move size={14} aria-hidden="true" /> Pinch to zoom · drag to move
+ </div>
+ );
+}
+
export { ZoomStage };
diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsx
index 354075f4..8508a618 100644
--- a/frontend/src/components/VirtualMachinePane.tsx
+++ b/frontend/src/components/VirtualMachinePane.tsx
@@ -710,6 +710,9 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
onHandBack={handBack}
stream={stream}
step={stepForStage}
+ controlling={stream.controlling}
+ resizeIgnored={stream.resizeIgnored}
+ restoreSize={stream.restoreViewport}
/>
)}
diff --git a/frontend/src/useBrowserStream.ts b/frontend/src/useBrowserStream.ts
index 53d92a99..c0a3f10c 100644
--- a/frontend/src/useBrowserStream.ts
+++ b/frontend/src/useBrowserStream.ts
@@ -32,6 +32,8 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {
const [select, setSelect] = useState<SelectRequest | null>(null);
const [dialog, setDialog] = useState<PageDialog | null>(null);
const [cursor, setCursor] = useState<string>('default');
+ // The last resize was answered `ignored`: the page follows a real window and keeps its size
+ const [resizeIgnored, setResizeIgnored] = useState(false);
// Actions the server answered "Invalid browser input" for (an older server): hide their buttons
const [unsupported, setUnsupported] = useState<ReadonlySet<string>>(new Set());
const actionsById = useRef(new Map<number, string>());
@@ -96,6 +98,7 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {
break;
}
case 'ack':
+ if (actionsById.current.get(message.id) === 'resize') setResizeIgnored(message.ignored === true);
pending.current.delete(message.id);
actionsById.current.delete(message.id);
setBusy(pending.current.size > 0);
@@ -116,6 +119,7 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {
lastImage.current = null;
setSelect(null);
setDialog(null);
+ setResizeIgnored(false);
setError((current) => current || 'Browser disconnected. Reconnecting…');
reconnect = setTimeout(connect, Math.min(1000 * 2 ** attempts++, 10000));
};
@@ -137,6 +141,7 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {
setSelect(null);
setDialog(null);
setViewport(null);
+ setResizeIgnored(false);
};
}, [id, visible]);
@@ -168,13 +173,22 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {
if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ action: 'frame_ack', id }));
}, []);
+ /**
+ * Gives the page its own size back while keeping control (the phone overlay closing or going to
+ * the background). Quiet: a closed socket already restored it on the server.
+ */
+ const restoreViewport = useCallback(() => {
+ const ws = socket.current;
+ if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ action: 'restore_viewport', id: ++sequence.current }));
+ }, []);
+
const clearSelect = useCallback(() => setSelect(null), []);
const clearDialog = useCallback(() => setDialog(null), []);
const clearError = useCallback(() => setError(null), []);
return {
- connected, controlling, busy, error, frame, location, tapFocus, viewport, select, dialog, cursor, unsupported,
- send, acknowledgeFrame, clearSelect, clearDialog, clearError,
+ connected, controlling, busy, error, frame, location, tapFocus, viewport, select, dialog, cursor, unsupported, resizeIgnored,
+ send, acknowledgeFrame, restoreViewport, clearSelect, clearDialog, clearError,
};
}
diff --git a/frontend/tests/browserOverlayResize.test.mjs b/frontend/tests/browserOverlayResize.test.mjs
new file mode 100644
index 00000000..60e76671
--- /dev/null
+++ b/frontend/tests/browserOverlayResize.test.mjs
@@ -0,0 +1,244 @@
+// Mobile 0.6.13, B2 (Mira's audit P0-1): taking over on a phone showed the 1280 px page shrunk to a
+// third of the screen. The overlay now sizes the page to its own stage, as the desktop stage does,
+// opens a page that keeps its own size (a real window) at fit-width with a one-time pinch hint, and
+// gives the bot its size back on every way it closes (Ada's ask), not only on Hand back.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/spc_default', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLImageElement', 'Element', 'Node', 'Event', 'PopStateEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'history']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+// The stage's size is whatever the test says; ResizeObserver callbacks run when it asks
+let stageSize = { width: 390, height: 748 };
+for (const [prop, key] of [['clientWidth', 'width'], ['clientHeight', 'height']]) {
+ Object.defineProperty(g.HTMLElement.prototype, prop, {
+ configurable: true,
+ get() { return this.hasAttribute?.('data-browser-stage') ? stageSize[key] : 0; },
+ });
+}
+const observers = new Set();
+g.ResizeObserver = g.window.ResizeObserver = class {
+ constructor(cb) { this.cb = cb; }
+ observe() { observers.add(this); }
+ unobserve() {}
+ disconnect() { observers.delete(this); }
+};
+g.window.devicePixelRatio = 3;
+let reducedMotion = false;
+g.window.matchMedia = (q) => ({ matches: q.includes('reduce') && reducedMotion, addEventListener() {}, removeEventListener() {} });
+let visibility = 'visible';
+Object.defineProperty(g.document, 'visibilityState', { configurable: true, get: () => visibility });
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { BrowserControlOverlay, fitWidthView, PINCH_HINT_KEY, PINCH_HINT_MS, PINCH_HINT_FADE_MS, OVERLAY_RESIZE_DEBOUNCE_MS } from './src/components/BrowserControlOverlay';
+ export { fitView, zoomToBox } from './src/browserGestures';
+`);
+const settle = async () => {
+ for (let i = 0; i < 30; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const wait = (ms) => new Promise((r) => setTimeout(r, ms));
+// Waits for `ok()` up to `ms`, so a loaded CI machine doesn't fail a timing step
+const until = async (ok, ms = 2000) => {
+ const end = Date.now() + ms;
+ while (!ok() && Date.now() < end) await wait(10);
+ await settle();
+};
+
+async function renderOverlay(props = {}) {
+ const sent = [];
+ const calls = { handBack: 0, restore: 0 };
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ const base = {
+ botName: 'Ada', pageUrl: 'https://gearhub.example/checkout', image: 'data:image/png;base64,AAAA', onFrameDone() {},
+ send: (msg) => sent.push(msg), busy: false, error: null, tapFocus: null, captcha: null, solved: false,
+ onHandBack: () => { calls.handBack += 1; }, restoreSize: () => { calls.restore += 1; },
+ page: { width: 1280, height: 800 }, controlling: true,
+ };
+ let current = { ...base, ...props };
+ const draw = () => root.render(m.React.createElement(m.BrowserControlOverlay, current));
+ draw();
+ await settle();
+ return {
+ sent, calls,
+ resizes: () => sent.filter((s) => s.action === 'resize'),
+ rerender: async (next) => { current = { ...current, ...next }; draw(); await settle(); },
+ img: () => document.querySelector('[data-browser-fullscreen] img'),
+ hint: () => document.querySelector('[data-pinch-hint]'),
+ unmount: async () => { root.unmount(); host.remove(); await settle(); },
+ };
+}
+
+test('the overlay sizes the page to its own stage as it opens', async () => {
+ stageSize = { width: 390, height: 748 };
+ const o = await renderOverlay();
+ assert.deepEqual(o.resizes(), [{ action: 'resize', width: 390, height: 748, dpr: 2 }], 'one resize at once, dpr capped at 2');
+ await o.unmount();
+});
+
+test('no resize before the person controls the page, one as soon as they do', async () => {
+ stageSize = { width: 360, height: 700 };
+ const o = await renderOverlay({ controlling: false });
+ assert.deepEqual(o.resizes(), []);
+ await o.rerender({ controlling: true });
+ assert.deepEqual(o.resizes().map((r) => r.width), [360]);
+ await o.unmount();
+});
+
+test('a rotate sizes the page again once it settles', async () => {
+ stageSize = { width: 412, height: 780 };
+ const o = await renderOverlay();
+ stageSize = { width: 892, height: 330 };
+ for (const ob of observers) ob.cb([]);
+ await settle();
+ assert.equal(o.resizes().length, 1, 'not straight away');
+ await until(() => o.resizes().length > 1);
+ assert.deepEqual(o.resizes().map((r) => [r.width, r.height]), [[412, 780], [892, 360]], 'height clamps to the 360 minimum');
+ await o.unmount();
+});
+
+test('a page that keeps its own size opens fit-width and top-aligned, not fit-contain', async () => {
+ // a phone on its side: contain would leave bands beside the page
+ stageSize = { width: 844, height: 340 };
+ const page = { width: 1280, height: 800 };
+ const o = await renderOverlay({ resizeIgnored: true, page });
+ const scale = 844 / 1280;
+ assert.notEqual(m.fitView(stageSize, page).scale, scale, 'contain would differ here');
+ assert.deepEqual(m.fitWidthView(stageSize, page), { scale, tx: 0, ty: 0 });
+ assert.equal(o.img().style.transform, `translate(0px, 0px) scale(${scale})`);
+ await o.unmount();
+});
+
+test('a known CAPTCHA box still wins over fit-width', async () => {
+ stageSize = { width: 390, height: 748 };
+ const page = { width: 1280, height: 800 };
+ const target = { x: 500, y: 300, width: 300, height: 80 };
+ const o = await renderOverlay({ resizeIgnored: true, page, captcha: { target } });
+ const v = m.zoomToBox(target, stageSize, page);
+ assert.equal(o.img().style.transform, `translate(${v.tx}px, ${v.ty}px) scale(${v.scale})`);
+ await o.unmount();
+});
+
+test('the pinch hint shows once per device, for 4 s, then fades', async () => {
+ localStorage.removeItem(m.PINCH_HINT_KEY);
+ stageSize = { width: 390, height: 748 };
+ const sized = await renderOverlay();
+ assert.equal(sized.hint(), null, 'no hint when the page takes the stage size');
+ await sized.unmount();
+
+ const o = await renderOverlay({ resizeIgnored: true });
+ const hint = o.hint();
+ assert.ok(hint, 'the hint shows');
+ assert.match(hint.textContent, /Pinch to zoom · drag to move/);
+ assert.match(hint.className, /h-10/);
+ assert.match(hint.className, /bottom-4/);
+ assert.match(hint.className, /bg-\[#231d4b\]/);
+ assert.match(hint.className, /text-\[13px\] leading-4 text-\[#ecebfa\]/);
+ assert.match(hint.className, /rounded-full/);
+ assert.ok(hint.querySelector('svg'), 'with the Move icon');
+ assert.equal(localStorage.getItem(m.PINCH_HINT_KEY), '1');
+ await wait(m.PINCH_HINT_MS - 500);
+ assert.match(o.hint()?.className ?? '', /opacity-100/, 'still up just before 4 s');
+ await until(() => /opacity-0/.test(o.hint()?.className ?? '') || !o.hint(), 2500);
+ assert.match(o.hint()?.className ?? '', /opacity-0/, 'fading');
+ await until(() => !o.hint());
+ assert.equal(o.hint(), null, 'gone');
+ await o.unmount();
+
+ const again = await renderOverlay({ resizeIgnored: true });
+ assert.equal(again.hint(), null, 'never twice on one device');
+ await again.unmount();
+});
+
+test('under reduced motion the hint goes after 4 s with no fade', async () => {
+ localStorage.removeItem(m.PINCH_HINT_KEY);
+ reducedMotion = true;
+ try {
+ const o = await renderOverlay({ resizeIgnored: true });
+ assert.ok(o.hint());
+ let faded = false;
+ await until(() => { faded ||= /opacity-0/.test(o.hint()?.className ?? ''); return !o.hint(); }, m.PINCH_HINT_MS + 2500);
+ assert.equal(o.hint(), null);
+ assert.equal(faded, false, 'never faded');
+ await o.unmount();
+ } finally {
+ reducedMotion = false;
+ }
+});
+
+test('the status line under the bar is 13/18 and keeps its colour', async () => {
+ const o = await renderOverlay({ captcha: { target: null } });
+ const line = document.querySelector('[data-browser-fullscreen] p[role="status"]');
+ assert.match(line.className, /text-\[13px\] leading-\[18px\]/);
+ assert.match(line.className, /text-\[#fcd34d\]/);
+ assert.doesNotMatch(line.className, /text-xs/);
+ await o.unmount();
+});
+
+test('the app going to the background gives the size back; coming back sizes the page again', async () => {
+ stageSize = { width: 390, height: 748 };
+ const o = await renderOverlay();
+ visibility = 'hidden';
+ document.dispatchEvent(new window.Event('visibilitychange'));
+ await settle();
+ assert.equal(o.calls.restore, 1);
+ visibility = 'visible';
+ document.dispatchEvent(new window.Event('visibilitychange'));
+ await settle();
+ assert.equal(o.resizes().length, 2, 'sized again at once');
+ await o.unmount();
+ assert.equal(o.calls.restore, 2, 'and closing gives it back once more');
+});
+
+test('closing the overlay any other way gives the size back once', async () => {
+ const o = await renderOverlay();
+ await o.unmount();
+ assert.equal(o.calls.restore, 1);
+ assert.equal(o.calls.handBack, 0);
+});
+
+test('Hand back leaves the restore to release_control: no second restore', async () => {
+ const o = await renderOverlay();
+ const button = [...document.querySelectorAll('button')].find((b) => /Hand back/.test(b.textContent));
+ button.click();
+ await settle();
+ assert.equal(o.calls.handBack, 1);
+ await o.unmount();
+ assert.equal(o.calls.restore, 0);
+});
+
+test("the phone's back gesture hands back instead of leaving the chat", async () => {
+ await until(() => !history.state?.kwBrowserOverlay);
+ assert.ok(!history.state?.kwBrowserOverlay);
+ const o = await renderOverlay();
+ assert.ok(history.state?.kwBrowserOverlay, 'the overlay has its own history entry');
+ history.back();
+ await until(() => o.calls.handBack > 0);
+ assert.equal(o.calls.handBack, 1);
+ await o.unmount();
+});
+
+test('Hand back takes the overlay history entry off again', async () => {
+ const o = await renderOverlay();
+ assert.ok(history.state?.kwBrowserOverlay);
+ await o.unmount();
+ await until(() => !history.state?.kwBrowserOverlay);
+ assert.ok(!history.state?.kwBrowserOverlay, 'back to the entry before the overlay');
+ assert.equal(o.calls.handBack, 0, 'its own pop is not a back gesture');
+});
+
+test('no resize without a page size from the stage', async () => {
+ stageSize = { width: 0, height: 0 };
+ const o = await renderOverlay();
+ assert.deepEqual(o.resizes(), []);
+ await o.unmount();
+ stageSize = { width: 390, height: 748 };
+});
diff --git a/frontend/tests/browserStreamAck.test.mjs b/frontend/tests/browserStreamAck.test.mjs
index 31ab9a4f..fc0692b1 100644
--- a/frontend/tests/browserStreamAck.test.mjs
+++ b/frontend/tests/browserStreamAck.test.mjs
@@ -69,3 +69,45 @@ test('an identical frame is acknowledged at once; a changed one waits for the im
m.flushSync(() => root.unmount());
});
+
+// Mobile 0.6.13 B2: the phone overlay opens fit-width when the browser keeps its own size, and
+// gives the size back quietly when it closes without handing back.
+test('a resize answered `ignored` is surfaced; restoreViewport is quiet on a closed socket', async () => {
+ let stream;
+ function Hold() {
+ stream = m.useBrowserStream('k2', true);
+ return null;
+ }
+ const root = m.createRoot(document.createElement('div'));
+ m.flushSync(() => root.render(m.React.createElement(Hold)));
+ await settle();
+ const ws = sockets.at(-1);
+ ws.onopen?.();
+ assert.equal(stream.resizeIgnored, false);
+ stream.send({ action: 'resize', width: 390, height: 748, dpr: 2 });
+ const id = ws.sent.at(-1).id;
+ ws.receive({ type: 'ack', id, ignored: true, viewport: { width: 1440, height: 900 } });
+ await settle();
+ assert.equal(stream.resizeIgnored, true);
+ // a later resize the page takes clears it
+ stream.send({ action: 'resize', width: 390, height: 748, dpr: 2 });
+ ws.receive({ type: 'ack', id: ws.sent.at(-1).id, viewport: { width: 390, height: 748, dpr: 2 } });
+ await settle();
+ assert.equal(stream.resizeIgnored, false);
+ // an ack for anything else leaves it alone
+ ws.receive({ type: 'ack', id, ignored: true });
+ stream.send({ action: 'mouse', type: 'down', x: 1, y: 1 }, true);
+ ws.receive({ type: 'ack', id: ws.sent.at(-1).id });
+ await settle();
+ assert.equal(stream.resizeIgnored, false);
+
+ stream.restoreViewport();
+ assert.equal(ws.sent.at(-1).action, 'restore_viewport');
+ ws.readyState = 3;
+ const before = ws.sent.length;
+ stream.restoreViewport();
+ await settle();
+ assert.equal(ws.sent.length, before, 'nothing sent on a closed socket');
+ assert.equal(stream.error, null, 'and no "reconnecting" error for it');
+ m.flushSync(() => root.unmount());
+});
diff --git a/frontend/tests/haptics.test.mjs b/frontend/tests/haptics.test.mjs
index d5a4b6e6..28315f1e 100644
--- a/frontend/tests/haptics.test.mjs
+++ b/frontend/tests/haptics.test.mjs
@@ -174,7 +174,7 @@ test('wiring: meaningful actions buzz, typing and scrolling do not', () => {
const overlay = src('components/BrowserControlOverlay.tsx');
assert.match(overlay, /if \(solved\) haptic\('success'\)/);
- assert.match(overlay, /haptic\('tap'\);\s*onHandBack\(\);/);
+ assert.match(overlay, /haptic\('tap'\);\s*handBack\(\);/);
const settings = src('components/SettingsModal.tsx');
assert.match(settings, /hapticsAvailable\(\) && \(/, 'the switch only shows where the phone can vibrate');
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index ed856247..66f9c3ac 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -937,6 +937,60 @@ pub struct HeldPointer {
pub buttons: u8,
}
+/// One live view's own page size: the size its stage asked for with `resize`.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct ViewClaim {
+ pub socket: u64,
+ pub width: u32,
+ pub height: u32,
+ pub dpr: f64,
+}
+
+/// What a live view letting go of its size leaves the page at.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum ViewRelease {
+ /// It had no size of its own, or a newer view's size is on the page: nothing changes.
+ Keep,
+ /// Its size was on the page and another view still has one: the newest of those.
+ Reapply(ViewClaim),
+ /// The last sized view let go: the bot's own viewport comes back.
+ Restore,
+}
+
+/// The sizes the open live views asked for, oldest first. The newest is the one on the page:
+/// the last resize wins, and the bot's viewport comes back when the last sized view lets go.
+#[derive(Debug, Default)]
+pub struct ViewClaims(Vec<ViewClaim>);
+
+impl ViewClaims {
+ /// `claim` resized the page: it replaces that view's earlier size and becomes the newest.
+ pub fn claim(&mut self, claim: ViewClaim) {
+ self.0.retain(|c| c.socket != claim.socket);
+ self.0.push(claim);
+ }
+
+ /// The view on `socket` hands back, goes to the background or closes.
+ pub fn release(&mut self, socket: u64) -> ViewRelease {
+ let Some(at) = self.0.iter().position(|c| c.socket == socket) else { return ViewRelease::Keep };
+ let newest = at + 1 == self.0.len();
+ self.0.remove(at);
+ match (newest, self.0.last()) {
+ (false, _) => ViewRelease::Keep,
+ (true, Some(next)) => ViewRelease::Reapply(*next),
+ (true, None) => ViewRelease::Restore,
+ }
+ }
+
+ /// A view asking again for the size it already has while a newer view's size is on the page:
+ /// the desktop stage re-asking when the page doesn't match it, which would take the page back
+ /// from the phone that opened after it. Only a new size wins.
+ pub fn repeats_older(&self, claim: &ViewClaim) -> bool {
+ self.0.last().is_some_and(|newest| newest.socket != claim.socket) && self.0.contains(claim)
+ }
+
+ pub fn is_empty(&self) -> bool { self.0.is_empty() }
+}
+
/// CDP button names for each bit of a `buttons` mask, in bit order.
pub const MOUSE_BUTTON_BITS: [(u8, &str); 5] = [(1, "left"), (2, "right"), (4, "middle"), (8, "back"), (16, "forward")];
@@ -962,6 +1016,9 @@ pub struct BrowserController {
held_for_person: Arc<std::sync::Mutex<Option<OwnedRwLockWriteGuard<()>>>>,
/// Which mouse buttons live-view input holds down, and where, if any.
pointer_held: Arc<std::sync::Mutex<Option<HeldPointer>>>,
+ /// The page sizes open live views asked for. Async: a resize holds it while it applies, so
+ /// two views resizing at once leave the newest claim's size on the page.
+ view_claims: Arc<Mutex<ViewClaims>>,
/// VM mode: this bot's cookies, saved outside the throwaway browser context.
cookie_jar: Arc<std::sync::Mutex<Option<std::path::PathBuf>>>,
/// The fixed viewport set for a windowless browser, restored after a bot's sized screenshot.
@@ -1031,6 +1088,7 @@ impl BrowserController {
control: Arc::new(RwLock::new(())),
held_for_person: Arc::default(),
pointer_held: Arc::default(),
+ view_claims: Arc::default(),
cookie_jar: Arc::default(),
viewport: Arc::default(),
progress: Arc::default(),
@@ -1093,6 +1151,8 @@ impl BrowserController {
pub(crate) fn pointer_held_slot(&self) -> &std::sync::Mutex<Option<HeldPointer>> { &self.pointer_held }
+ pub(crate) fn view_claims(&self) -> &Mutex<ViewClaims> { &self.view_claims }
+
/// The fixed viewport of a windowless browser (normally 1280x800), or `None` when the page
/// follows a real window. The live view restores it when the person hands back.
pub fn fixed_viewport(&self) -> Option<(u32, u32)> {
@@ -2082,3 +2142,70 @@ mod ref_tests {
assert_eq!(line(json!({"ref": 12, "role": "option", "name": "Large", "new": false})).as_deref(), Some("[12] option \"Large\""));
}
}
+
+#[cfg(test)]
+mod view_claim_tests {
+ use super::{ViewClaim, ViewClaims, ViewRelease};
+
+ fn size(socket: u64, width: u32) -> ViewClaim { ViewClaim { socket, width, height: 700, dpr: 2.0 } }
+
+ #[test]
+ fn one_view_restores_when_it_lets_go() {
+ let mut claims = ViewClaims::default();
+ claims.claim(size(1, 390));
+ claims.claim(size(1, 412)); // a rotate replaces its own claim
+ assert_eq!(claims.release(1), ViewRelease::Restore);
+ assert!(claims.is_empty());
+ assert_eq!(claims.release(1), ViewRelease::Keep, "letting go twice changes nothing");
+ }
+
+ #[test]
+ fn a_view_without_a_size_changes_nothing() {
+ let mut claims = ViewClaims::default();
+ claims.claim(size(1, 390));
+ assert_eq!(claims.release(2), ViewRelease::Keep);
+ assert_eq!(claims.release(1), ViewRelease::Restore);
+ }
+
+ #[test]
+ fn last_resize_wins_and_restore_waits_for_the_last_view() {
+ // the desktop stage (1) then the phone overlay (2)
+ let mut claims = ViewClaims::default();
+ claims.claim(size(1, 1100));
+ claims.claim(size(2, 390));
+ // the phone closes: the desktop's size comes back, not 1280
+ assert_eq!(claims.release(2), ViewRelease::Reapply(size(1, 1100)));
+ assert_eq!(claims.release(1), ViewRelease::Restore);
+ }
+
+ #[test]
+ fn an_older_view_closing_leaves_the_newest_size_on_the_page() {
+ let mut claims = ViewClaims::default();
+ claims.claim(size(1, 1100));
+ claims.claim(size(2, 390));
+ assert_eq!(claims.release(1), ViewRelease::Keep);
+ assert_eq!(claims.release(2), ViewRelease::Restore);
+ }
+
+ #[test]
+ fn repeating_an_older_size_does_not_take_the_page_back() {
+ let mut claims = ViewClaims::default();
+ claims.claim(size(1, 1100));
+ assert!(!claims.repeats_older(&size(1, 1100)), "the newest view re-asking applies again (a navigation reset)");
+ claims.claim(size(2, 390));
+ assert!(claims.repeats_older(&size(1, 1100)));
+ assert!(!claims.repeats_older(&size(1, 1000)), "a new size wins");
+ assert!(!claims.repeats_older(&size(2, 390)));
+ assert!(!claims.repeats_older(&size(3, 1100)), "another view's size is not a repeat");
+ }
+
+ #[test]
+ fn a_view_that_resizes_again_becomes_the_newest() {
+ let mut claims = ViewClaims::default();
+ claims.claim(size(1, 1100));
+ claims.claim(size(2, 390));
+ claims.claim(size(1, 1000));
+ assert_eq!(claims.release(1), ViewRelease::Reapply(size(2, 390)));
+ assert_eq!(claims.release(2), ViewRelease::Restore);
+ }
+}
diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rs
index 48e12a2f..9de5d299 100644
--- a/src/server/browser_stream.rs
+++ b/src/server/browser_stream.rs
@@ -8,7 +8,7 @@
use super::browser_input::{self as bi, KeyEvent, KeyKind, MouseButton, RateLimit};
use super::{routes::get_or_create_browser_controller, AppState};
use crate::sandbox::app_links::{self, AppLinkWatch, Verdict};
-use crate::sandbox::browser::{web_address, BrowserController, BrowserError, HeldPointer, FOCUSED_EDITABLE_JS, MOUSE_BUTTON_BITS};
+use crate::sandbox::browser::{web_address, BrowserController, BrowserError, HeldPointer, ViewClaim, ViewRelease, FOCUSED_EDITABLE_JS, MOUSE_BUTTON_BITS};
use crate::sandbox::browser_history::HistoryDirection;
use axum::{extract::{Path, State, WebSocketUpgrade, ws::{Message, WebSocket}}, http::{HeaderMap, StatusCode}, response::Response};
use futures::{SinkExt, StreamExt};
@@ -361,6 +361,8 @@ impl FrameGate {
/// State the stream and its worker share.
struct Shared {
+ /// This live view among the open ones, for its claim on the page size.
+ socket: u64,
/// The page viewport in CSS px, from frame metadata or the last resize.
view: std::sync::Mutex<(f64, f64)>,
/// A `resize` is applied and must be put back on hand back.
@@ -474,6 +476,8 @@ impl Shared {
enum Job {
Input { input: BrowserInput, id: Value },
HandBack(Option<oneshot::Sender<()>>),
+ /// The view closes or goes to the background but keeps control: only its size goes.
+ Restore(Value),
}
/// Runs input in the order it came, on the stream's socket.
@@ -545,6 +549,11 @@ impl Worker {
self.hand_back().await;
if let Some(done) = done { let _ = done.send(()); }
}
+ Job::Restore(id) => {
+ restore_viewport(&self.ctrl, &self.cdp, &self.shared).await;
+ let (w, h) = self.shared.view();
+ let _ = self.client.send(ack(&id, json!({"viewport": {"width": w, "height": h}})));
+ }
}
}
}
@@ -698,9 +707,20 @@ impl Worker {
return Ok(());
};
let (w, h, dpr) = bi::clamp_resize(width, height, dpr).map_err(protocol)?;
+ // held while it applies: of two views resizing at once, the newest claim is on the page
+ let mut claims = self.ctrl.view_claims().lock().await;
+ let claim = ViewClaim { socket: self.shared.socket, width: w, height: h, dpr };
+ if claims.repeats_older(&claim) {
+ drop(claims);
+ let (w, h) = self.shared.view();
+ let _ = self.client.send(ack(id, json!({"superseded": true, "viewport": {"width": w, "height": h}})));
+ return Ok(());
+ }
// on the controller's session, which owns the saved 1280x800 override
self.ctrl.send_cdp_command("Emulation.setDeviceMetricsOverride",
json!({"width": w, "height": h, "deviceScaleFactor": dpr, "mobile": false})).await?;
+ claims.claim(claim);
+ drop(claims);
self.shared.resized.store(true, Ordering::SeqCst);
self.shared.set_view(w as f64, h as f64);
restart_screencast(&self.cdp, (w as f64 * dpr).round() as u32, (h as f64 * dpr).round() as u32).await?;
@@ -802,14 +822,28 @@ async fn release_on(cdp: &Cdp, held: Option<HeldPointer>) {
}
}
+/// This view lets go of its page size. The page keeps a newer view's size, takes the newest
+/// remaining one, or gets the bot's own viewport back when no other view has a size.
async fn restore_viewport(ctrl: &BrowserController, cdp: &Cdp, shared: &Shared) {
if !shared.resized.swap(false, Ordering::SeqCst) { return; }
- let (w, h) = ctrl.fixed_viewport().unwrap_or(DEFAULT_VIEW);
- let _ = ctrl.send_cdp_command("Emulation.setDeviceMetricsOverride", json!({"width": w, "height": h, "deviceScaleFactor": 1, "mobile": false})).await;
+ let mut claims = ctrl.view_claims().lock().await;
+ let (w, h, dpr) = match claims.release(shared.socket) {
+ // a newer view's size is on the page; this view's frames follow it
+ ViewRelease::Keep => return,
+ ViewRelease::Reapply(next) => (next.width, next.height, next.dpr),
+ ViewRelease::Restore => { let (w, h) = ctrl.fixed_viewport().unwrap_or(DEFAULT_VIEW); (w, h, 1.0) }
+ };
+ // the bot's own override is sent with a whole 1, as `set_viewport` sends it
+ let scale = if dpr == 1.0 { json!(1) } else { json!(dpr) };
+ let _ = ctrl.send_cdp_command("Emulation.setDeviceMetricsOverride", json!({"width": w, "height": h, "deviceScaleFactor": scale, "mobile": false})).await;
+ drop(claims);
shared.set_view(w as f64, h as f64);
- let _ = restart_screencast(cdp, w, h).await;
+ let _ = restart_screencast(cdp, (w as f64 * dpr).round() as u32, (h as f64 * dpr).round() as u32).await;
}
+/// Numbers the live views, for their claims on the page size.
+static NEXT_SOCKET: AtomicU64 = AtomicU64::new(1);
+
async fn restart_screencast(cdp: &Cdp, max_width: u32, max_height: u32) -> Result<(), BrowserError> {
cdp.call("Page.stopScreencast", json!({}), PROBE_WAIT).await?;
cdp.call("Page.startScreencast", screencast_params(max_width, max_height), PROBE_WAIT).await?;
@@ -849,6 +883,7 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(),
let (cdp, mut events, tasks) = Cdp::open(ws);
let (w, h) = ctrl.fixed_viewport().unwrap_or(DEFAULT_VIEW);
let shared = Arc::new(Shared {
+ socket: NEXT_SOCKET.fetch_add(1, Ordering::Relaxed),
view: std::sync::Mutex::new((w as f64, h as f64)),
resized: AtomicBool::new(false),
cursor: std::sync::Mutex::new("auto".into()),
@@ -1024,6 +1059,9 @@ async fn stream(
let (vw, vh) = shared.view();
send(socket, json!({"type":"control","active":false,"viewport":{"width":vw,"height":vh}})).await?;
}
+ // the view closes or goes to the background: only this view's own size
+ // goes, so it needs no control (a human step's view holds none)
+ "restore_viewport" => { let _ = jobs.send(Job::Restore(id)); }
_ => {
if lease.is_none() && !ctrl.is_held_for_person() {
send(socket, error(&id, not_in_control(ctrl.control.try_read().is_err()))).await?;
diff --git a/tests/browser_stream_test.rs b/tests/browser_stream_test.rs
index e50e167b..123c5b2d 100644
--- a/tests/browser_stream_test.rs
+++ b/tests/browser_stream_test.rs
@@ -884,3 +884,77 @@ async fn a_host_and_port_open_as_a_web_page_and_a_phone_number_is_refused_by_bot
assert_eq!(navigated().await.last(), Some(&json!("http://localhost:9411/target.html")));
app_task.abort(); cdp_task.abort();
}
+
+/// The widths `Emulation.setDeviceMetricsOverride` set the page to, in order.
+async fn page_widths(mock: &Mock) -> Vec<i64> {
+ mock.commands.lock().await.iter().filter(|c| c["method"]=="Emulation.setDeviceMetricsOverride").filter_map(|c| c["params"]["width"].as_i64()).collect()
+}
+
+#[tokio::test]
+async fn two_views_last_resize_wins_and_the_bot_size_returns_when_the_last_one_lets_go() {
+ let (mock, cdp_task) = mock().await;
+ let tmp = tempfile::tempdir().unwrap();
+ let config = Config {data_dir:tmp.path().into(),browser_cdp_url:Some(format!("http://127.0.0.1:{}",mock.port)),..Config::default()};
+ let db = Database::init(tmp.path()).await.unwrap();
+ let id=db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap()[0].id.clone();
+ let state=AppState::new(config.clone(),db,ToolRunner::new(tmp.path().join("workspace")),PermissionBroker::new(),LayaRouter::new(config.laya_url));
+ let ctrl=kwnt::server::routes::get_or_create_browser_controller(&state,&id).await.unwrap();
+ let listener=TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port=listener.local_addr().unwrap().port();
+ let app_task=tokio::spawn(async move {axum::serve(listener,create_router(state)).await.unwrap();});
+ let open = || async {
+ let mut request=format!("ws://127.0.0.1:{port}/api/sandbox/{id}/stream").into_client_request().unwrap();
+ request.headers_mut().insert("Origin",format!("http://127.0.0.1:{port}").parse().unwrap());
+ let (mut ws,_)=connect_async(request).await.unwrap();
+ receive(&mut ws,"frame").await;
+ ws
+ };
+ let send = |payload: Value| WsMessage::Text(payload.to_string());
+ // a CAPTCHA step holds the browser for the person: every open view may size the page
+ assert!(ctrl.hold_for_person().await);
+ let mut desktop = open().await;
+ let mut phone = open().await;
+
+ // restoring needs no control and is a no-op for a view that never resized
+ mock.commands.lock().await.clear();
+ phone.send(send(json!({"action":"restore_viewport","id":"noop"}))).await.unwrap();
+ assert_eq!(until_reply(&mut phone,"noop").await.last().unwrap()["type"], "ack");
+ assert!(page_widths(&mock).await.is_empty());
+
+ // the desktop stage, then the phone overlay: the phone's size is on the page
+ desktop.send(send(json!({"action":"resize","width":1100,"height":700,"id":"d1"}))).await.unwrap();
+ until_reply(&mut desktop,"d1").await;
+ phone.send(send(json!({"action":"resize","width":390,"height":700,"dpr":2,"id":"p1"}))).await.unwrap();
+ until_reply(&mut phone,"p1").await;
+ assert_eq!(page_widths(&mock).await, vec![1100, 390]);
+ // the desktop re-asks for its old size because the page no longer matches it: the phone keeps it
+ mock.commands.lock().await.clear();
+ desktop.send(send(json!({"action":"resize","width":1100,"height":700,"id":"d2"}))).await.unwrap();
+ let kept = until_reply(&mut desktop,"d2").await.pop().unwrap();
+ assert_eq!((kept["type"].clone(), kept["superseded"].clone()), (json!("ack"), json!(true)));
+ assert!(page_widths(&mock).await.is_empty(), "no resize for a repeat");
+
+ // the phone goes to the background: the desktop's size comes back, not the bot's 1280
+ mock.commands.lock().await.clear();
+ phone.send(send(json!({"action":"restore_viewport","id":"p2"}))).await.unwrap();
+ let back = until_reply(&mut phone,"p2").await.pop().unwrap();
+ assert_eq!((back["type"].clone(), back["viewport"]["width"].as_f64()), (json!("ack"), Some(1100.0)));
+ assert_eq!(page_widths(&mock).await, vec![1100]);
+
+ // the phone comes back and sizes the page again; the desktop closes first: nothing moves
+ phone.send(send(json!({"action":"resize","width":390,"height":700,"dpr":2,"id":"p3"}))).await.unwrap();
+ until_reply(&mut phone,"p3").await;
+ mock.commands.lock().await.clear();
+ drop(desktop);
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ assert!(page_widths(&mock).await.is_empty(), "an older view closing leaves the newest size");
+
+ // the last view drops: the bot's 1280x800 is back
+ drop(phone);
+ timeout(Duration::from_secs(5),async {loop {
+ if page_widths(&mock).await == vec![1280] {break;}
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }}).await.unwrap();
+ ctrl.release_person_hold();
+ app_task.abort(); cdp_task.abort();
+}