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.

Browser takeover: live view protocol v2 (mouse, keys, wheel, resize, select, dialogs) (#270)

Oleksandr Ivanchenko30e0b62dfcd2
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index 21275a0b..550339a3 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -13,7 +13,7 @@ use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
-type WsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;
+pub(crate) type WsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;
/// The DevTools WebSocket request for `url`. Chrome refuses a DevTools connection whose Host is a
/// name other than localhost (500 on the upgrade), so a plain-ws name such as the compose service
@@ -461,7 +461,7 @@ fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
std::fs::rename(&tmp, path)
}
-const FOCUSED_EDITABLE_JS: &str = r#"(() => {
+pub(crate) const FOCUSED_EDITABLE_JS: &str = r#"(() => {
let el = document.activeElement;
for (let i = 0; el && i < 8; i++) {
if (el.shadowRoot && el.shadowRoot.activeElement) { el = el.shadowRoot.activeElement; continue; }
@@ -809,6 +809,18 @@ const COLLECT_SCRIPT: &str = r#"
})()
"#;
+/// Mouse buttons held down by the person's live-view input: a CDP `buttons` bitmask (left 1,
+/// right 2, middle 4, back 8, forward 16) and where the pointer was last seen.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct HeldPointer {
+ pub x: f64,
+ pub y: f64,
+ pub buttons: u8,
+}
+
+/// 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")];
+
#[derive(Clone)]
pub struct BrowserController {
pub cdp_port: u16,
@@ -829,8 +841,8 @@ pub struct BrowserController {
/// Held while a human step (sign in, CAPTCHA) waits on the person: bot actions get
/// `HumanControl` and the person's live-view input goes through without taking control.
held_for_person: Arc<std::sync::Mutex<Option<OwnedRwLockWriteGuard<()>>>>,
- /// Where the left button is held down from live-view pointer input, if it is.
- pointer_held: Arc<std::sync::Mutex<Option<(f64, f64)>>>,
+ /// Which mouse buttons live-view input holds down, and where, if any.
+ pointer_held: Arc<std::sync::Mutex<Option<HeldPointer>>>,
/// 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.
@@ -960,7 +972,13 @@ impl BrowserController {
pub fn is_managed_session(&self) -> bool { self.target_id.is_some() }
- pub(crate) fn pointer_held_slot(&self) -> &std::sync::Mutex<Option<(f64, f64)>> { &self.pointer_held }
+ pub(crate) fn pointer_held_slot(&self) -> &std::sync::Mutex<Option<HeldPointer>> { &self.pointer_held }
+
+ /// 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)> {
+ *self.viewport.lock().unwrap_or_else(|e| e.into_inner())
+ }
pub async fn refresh_location(&self) -> Result<(), BrowserError> {
let result = self.send_cdp_command("Runtime.evaluate", json!({
diff --git a/src/sandbox/browser_history.rs b/src/sandbox/browser_history.rs
new file mode 100644
index 00000000..8bee86cd
--- /dev/null
+++ b/src/sandbox/browser_history.rs
@@ -0,0 +1,120 @@
+//! Back, forward and reload for the person's takeover view (`{action:"history"}`).
+//!
+//! The target entry comes from `Page.getNavigationHistory`, so the move stays inside the tab's
+//! own history. Like `navigate`, the person may only land on an HTTP(S) page (or about:blank).
+
+use super::browser::{BrowserController, BrowserError};
+use serde::Deserialize;
+use serde_json::{json, Value};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum HistoryDirection {
+ Back,
+ Forward,
+ Reload,
+}
+
+/// The history entry id a back or forward move goes to, from a `Page.getNavigationHistory`
+/// result. An error at either end of the history, on a malformed result, or when the entry is
+/// not a web page.
+pub fn history_target(history: &Value, direction: HistoryDirection) -> Result<i64, BrowserError> {
+ let step: i64 = match direction {
+ HistoryDirection::Back => -1,
+ HistoryDirection::Forward => 1,
+ HistoryDirection::Reload => return Err(BrowserError::Protocol("Reload has no history entry".into())),
+ };
+ let entries = history["entries"].as_array()
+ .ok_or_else(|| BrowserError::Protocol("No navigation history".into()))?;
+ let current = history["currentIndex"].as_i64()
+ .filter(|i| *i >= 0 && (*i as usize) < entries.len())
+ .ok_or_else(|| BrowserError::Protocol("No navigation history".into()))?;
+ let index = current + step;
+ if index < 0 || index as usize >= entries.len() {
+ return Err(BrowserError::Protocol(match direction {
+ HistoryDirection::Back => "No page to go back to".into(),
+ _ => "No page to go forward to".into(),
+ }));
+ }
+ let entry = &entries[index as usize];
+ let url = entry["url"].as_str().unwrap_or_default();
+ let web = url == "about:blank"
+ || reqwest::Url::parse(url).is_ok_and(|u| matches!(u.scheme(), "http" | "https"));
+ if !web { return Err(BrowserError::Protocol("That history entry isn't a web page".into())); }
+ entry["id"].as_i64().ok_or_else(|| BrowserError::Protocol("No navigation history".into()))
+}
+
+impl BrowserController {
+ /// Moves the tab one entry back or forward, or reloads it. Returns once Chrome accepted the
+ /// command; the screencast and the location tick show the result.
+ pub async fn navigate_history(&self, direction: HistoryDirection) -> Result<(), BrowserError> {
+ if direction == HistoryDirection::Reload {
+ self.send_cdp_command("Page.reload", json!({})).await?;
+ return Ok(());
+ }
+ let history = self.send_cdp_command("Page.getNavigationHistory", json!({})).await?;
+ let entry = history_target(&history, direction)?;
+ self.send_cdp_command("Page.navigateToHistoryEntry", json!({"entryId": entry})).await?;
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn history(current: i64, urls: &[&str]) -> Value {
+ json!({
+ "currentIndex": current,
+ "entries": urls.iter().enumerate().map(|(i, url)| json!({"id": 100 + i as i64, "url": url, "title": ""})).collect::<Vec<_>>(),
+ })
+ }
+
+ fn message(result: Result<i64, BrowserError>) -> String {
+ result.expect_err("expected an error").to_string()
+ }
+
+ #[test]
+ fn back_and_forward_pick_the_neighbouring_entry() {
+ let h = history(1, &["https://a.example/", "https://b.example/", "https://c.example/"]);
+ assert_eq!(history_target(&h, HistoryDirection::Back).unwrap(), 100);
+ assert_eq!(history_target(&h, HistoryDirection::Forward).unwrap(), 102);
+ }
+
+ #[test]
+ fn the_ends_of_history_are_errors() {
+ let h = history(0, &["https://a.example/", "https://b.example/"]);
+ assert!(message(history_target(&h, HistoryDirection::Back)).contains("go back"));
+ let h = history(1, &["https://a.example/", "https://b.example/"]);
+ assert!(message(history_target(&h, HistoryDirection::Forward)).contains("go forward"));
+ }
+
+ #[test]
+ fn only_web_pages_and_blank_are_reachable() {
+ let h = history(1, &["about:blank", "https://b.example/", "chrome://settings/"]);
+ assert_eq!(history_target(&h, HistoryDirection::Back).unwrap(), 100);
+ assert!(message(history_target(&h, HistoryDirection::Forward)).contains("isn't a web page"));
+ let h = history(1, &["file:///etc/passwd", "http://b.example/"]);
+ assert!(history_target(&h, HistoryDirection::Back).is_err());
+ let h = history(1, &["data:text/html,hi", "http://b.example/"]);
+ assert!(history_target(&h, HistoryDirection::Back).is_err());
+ }
+
+ #[test]
+ fn malformed_history_is_an_error() {
+ for bad in [json!(null), json!({"entries": []}), json!({"currentIndex": 3, "entries": [{"id": 1, "url": "https://a.example/"}]}),
+ json!({"currentIndex": -1, "entries": [{"id": 1, "url": "https://a.example/"}]}),
+ json!({"currentIndex": 1, "entries": [{"url": "https://a.example/"}, {"id": 2, "url": "https://b.example/"}]})] {
+ assert!(history_target(&bad, HistoryDirection::Back).is_err(), "{bad}");
+ }
+ assert!(history_target(&history(0, &["https://a.example/"]), HistoryDirection::Reload).is_err());
+ }
+
+ #[test]
+ fn direction_parses_from_the_wire() {
+ for (wire, want) in [("back", HistoryDirection::Back), ("forward", HistoryDirection::Forward), ("reload", HistoryDirection::Reload)] {
+ assert_eq!(serde_json::from_value::<HistoryDirection>(json!(wire)).unwrap(), want);
+ }
+ assert!(serde_json::from_value::<HistoryDirection>(json!("sideways")).is_err());
+ }
+}
diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs
index 31398830..c52c8980 100644
--- a/src/sandbox/mod.rs
+++ b/src/sandbox/mod.rs
@@ -1,5 +1,6 @@
pub mod bitwarden;
pub mod browser;
+pub mod browser_history;
pub mod computer;
pub mod credentials;
pub mod manager;
diff --git a/src/server/browser_input.rs b/src/server/browser_input.rs
new file mode 100644
index 00000000..c26eaaf2
--- /dev/null
+++ b/src/server/browser_input.rs
@@ -0,0 +1,561 @@
+//! Pure pieces of the live-view input protocol (v2): the key table, key event building, the
+//! resize clamp, cursor names and the move rate limit. No I/O, so every rule is unit-tested here;
+//! [`super::browser_stream`] does the sending.
+
+use serde_json::{json, Value};
+use std::time::{Duration, Instant};
+
+/// CDP modifier bits.
+pub const ALT: u8 = 1;
+pub const CTRL: u8 = 2;
+pub const META: u8 = 4;
+pub const SHIFT: u8 = 8;
+
+/// The Windows virtual key code Chromium expects for a `KeyboardEvent.code`, or `None` for a
+/// code we don't know (refused, so a page never sees a key we can't describe properly).
+pub fn virtual_key_code(code: &str) -> Option<u16> {
+ let bytes = code.as_bytes();
+ // KeyA..KeyZ -> 65..90
+ if let Some(rest) = code.strip_prefix("Key") {
+ if rest.len() == 1 && bytes[3].is_ascii_uppercase() {
+ return Some(bytes[3] as u16);
+ }
+ return None;
+ }
+ // Digit0..Digit9 -> 48..57
+ if let Some(rest) = code.strip_prefix("Digit") {
+ if rest.len() == 1 && bytes[5].is_ascii_digit() {
+ return Some(bytes[5] as u16);
+ }
+ return None;
+ }
+ // Numpad0..Numpad9 -> 96..105
+ if let Some(rest) = code.strip_prefix("Numpad") {
+ if rest.len() == 1 && bytes[6].is_ascii_digit() {
+ return Some(96 + (bytes[6] - b'0') as u16);
+ }
+ }
+ // F1..F24 -> 112..135
+ if let Some(n) = code.strip_prefix('F').and_then(|n| n.parse::<u16>().ok()) {
+ if (1..=24).contains(&n) && !code[1..].starts_with('0') {
+ return Some(111 + n);
+ }
+ return None;
+ }
+ Some(match code {
+ "Backspace" => 8,
+ "Tab" => 9,
+ "Enter" | "NumpadEnter" => 13,
+ "ShiftLeft" | "ShiftRight" => 16,
+ "ControlLeft" | "ControlRight" => 17,
+ "AltLeft" | "AltRight" => 18,
+ "Pause" => 19,
+ "CapsLock" => 20,
+ "Escape" => 27,
+ "Space" => 32,
+ "PageUp" => 33,
+ "PageDown" => 34,
+ "End" => 35,
+ "Home" => 36,
+ "ArrowLeft" => 37,
+ "ArrowUp" => 38,
+ "ArrowRight" => 39,
+ "ArrowDown" => 40,
+ "PrintScreen" => 44,
+ "Insert" => 45,
+ "Delete" => 46,
+ "MetaLeft" => 91,
+ "MetaRight" => 92,
+ "ContextMenu" => 93,
+ "NumpadMultiply" => 106,
+ "NumpadAdd" => 107,
+ "NumpadComma" => 108,
+ "NumpadSubtract" => 109,
+ "NumpadDecimal" => 110,
+ "NumpadDivide" => 111,
+ "NumpadEqual" => 187,
+ "NumLock" => 144,
+ "ScrollLock" => 145,
+ "Semicolon" => 186,
+ "Equal" => 187,
+ "Comma" => 188,
+ "Minus" => 189,
+ "Period" => 190,
+ "Slash" => 191,
+ "Backquote" => 192,
+ "BracketLeft" => 219,
+ "Backslash" => 220,
+ "BracketRight" => 221,
+ "Quote" => 222,
+ "IntlBackslash" => 226,
+ "IntlRo" => 193,
+ "IntlYen" => 255,
+ _ => return None,
+ })
+}
+
+/// `KeyboardEvent.location` for a code: 1 left, 2 right, 3 numpad, else 0.
+pub fn key_location(code: &str) -> u8 {
+ if code.starts_with("Numpad") {
+ 3
+ } else if code.ends_with("Left") && !code.starts_with("Arrow") && code != "BracketLeft" {
+ 1
+ } else if code.ends_with("Right") && !code.starts_with("Arrow") && code != "BracketRight" {
+ 2
+ } else {
+ 0
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum KeyKind {
+ Down,
+ Up,
+}
+
+/// One v2 key event as sent by the client.
+#[derive(Debug, Clone, PartialEq)]
+pub struct KeyEvent<'a> {
+ pub kind: KeyKind,
+ pub key: &'a str,
+ pub code: &'a str,
+ pub text: Option<&'a str>,
+ pub modifiers: u8,
+ pub location: Option<u8>,
+ pub auto_repeat: bool,
+}
+
+/// The text a key press types: what the client sent, else the key itself when it is one
+/// printable character, `\r` for Enter. `None` while Meta, or Ctrl without Alt, is held: those
+/// are shortcuts (Ctrl+A selects, it doesn't type "a"). Ctrl+Alt stays text, which is AltGr on
+/// Windows keyboards.
+pub fn key_text(event: &KeyEvent<'_>) -> Result<Option<String>, &'static str> {
+ if event.kind == KeyKind::Up {
+ return Ok(None);
+ }
+ let derived = match event.text {
+ Some(text) => (!text.is_empty()).then(|| text.to_string()),
+ None if event.code == "Enter" || event.code == "NumpadEnter" => Some("\r".to_string()),
+ None if event.key.chars().count() == 1 => Some(event.key.to_string()),
+ None => None,
+ };
+ if let Some(text) = &derived {
+ if text.chars().count() > 4 || text.chars().any(|c| c.is_control() && c != '\r') {
+ return Err("Invalid key text");
+ }
+ }
+ let shortcut = event.modifiers & META != 0 || (event.modifiers & CTRL != 0 && event.modifiers & ALT == 0);
+ Ok(if shortcut { None } else { derived })
+}
+
+/// The editing command a shortcut runs, sent with the key so it works on every platform the
+/// browser runs on (headless Chrome on a Mac doesn't bind Ctrl+A to select all).
+pub fn shortcut_command(event: &KeyEvent<'_>) -> Option<&'static str> {
+ if event.kind != KeyKind::Down {
+ return None;
+ }
+ let m = event.modifiers;
+ // exactly one of Ctrl and Meta, and no Alt
+ if m & ALT != 0 || (m & CTRL != 0) == (m & META != 0) {
+ return None;
+ }
+ let shift = m & SHIFT != 0;
+ Some(match (event.code, shift) {
+ ("KeyA", false) => "selectAll",
+ ("KeyC", false) => "copy",
+ ("KeyX", false) => "cut",
+ ("KeyV", false) => "paste",
+ ("KeyZ", false) => "undo",
+ ("KeyZ", true) | ("KeyY", false) => "redo",
+ _ => return None,
+ })
+}
+
+/// The `Input.dispatchKeyEvent` params for one v2 key event: `keyDown` with text for keys that
+/// type something (so keydown, keypress and input all fire), `rawKeyDown` otherwise, `keyUp`.
+pub fn key_params(event: &KeyEvent<'_>) -> Result<Value, &'static str> {
+ if event.key.is_empty() || event.key.chars().count() > 32 || event.code.len() > 32 {
+ return Err("Invalid key");
+ }
+ let vk = virtual_key_code(event.code).ok_or("Unsupported key code")?;
+ if event.modifiers > 15 {
+ return Err("Invalid modifiers");
+ }
+ let location = match event.location {
+ Some(l) if l <= 3 => l,
+ Some(_) => return Err("Invalid key location"),
+ None => key_location(event.code),
+ };
+ let text = key_text(event)?;
+ let kind = match (event.kind, &text) {
+ (KeyKind::Down, Some(_)) => "keyDown",
+ (KeyKind::Down, None) => "rawKeyDown",
+ (KeyKind::Up, _) => "keyUp",
+ };
+ let mut params = json!({
+ "type": kind,
+ "key": event.key,
+ "code": event.code,
+ "windowsVirtualKeyCode": vk,
+ "nativeVirtualKeyCode": vk,
+ "modifiers": event.modifiers,
+ "location": location,
+ "autoRepeat": event.auto_repeat,
+ "isKeypad": location == 3,
+ });
+ if let Some(text) = text {
+ params["text"] = json!(text);
+ params["unmodifiedText"] = json!(text);
+ }
+ if let Some(command) = shortcut_command(event) {
+ params["commands"] = json!([command]);
+ }
+ Ok(params)
+}
+
+/// Viewport limits for `resize`, in CSS px, and the device pixel ratio.
+pub const RESIZE_WIDTH: (f64, f64) = (360.0, 1920.0);
+pub const RESIZE_HEIGHT: (f64, f64) = (360.0, 1200.0);
+pub const RESIZE_DPR: (f64, f64) = (1.0, 2.0);
+
+/// A `resize` request clamped to the limits: `(width, height, dpr)`. Non-finite values are
+/// refused, a missing dpr is 1.
+pub fn clamp_resize(width: f64, height: f64, dpr: Option<f64>) -> Result<(u32, u32, f64), &'static str> {
+ let dpr = dpr.unwrap_or(1.0);
+ if !width.is_finite() || !height.is_finite() || !dpr.is_finite() {
+ return Err("Invalid size");
+ }
+ let w = width.round().clamp(RESIZE_WIDTH.0, RESIZE_WIDTH.1) as u32;
+ let h = height.round().clamp(RESIZE_HEIGHT.0, RESIZE_HEIGHT.1) as u32;
+ // two decimals is plenty and keeps the screencast size an integer
+ let dpr = (dpr.clamp(RESIZE_DPR.0, RESIZE_DPR.1) * 100.0).round() / 100.0;
+ Ok((w, h, dpr))
+}
+
+/// The point if it is inside a `width` x `height` viewport (CSS px), else an error.
+pub fn in_viewport(x: f64, y: f64, width: f64, height: f64) -> Result<(f64, f64), &'static str> {
+ if x.is_finite() && y.is_finite() && x >= 0.0 && y >= 0.0 && x < width && y < height {
+ Ok((x, y))
+ } else {
+ Err("Pointer outside viewport")
+ }
+}
+
+/// Mouse buttons as the client names them, with their CDP `buttons` bit.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum MouseButton {
+ #[default]
+ None,
+ Left,
+ Middle,
+ Right,
+ Back,
+ Forward,
+}
+
+impl MouseButton {
+ pub fn bit(self) -> u8 {
+ match self {
+ MouseButton::None => 0,
+ MouseButton::Left => 1,
+ MouseButton::Right => 2,
+ MouseButton::Middle => 4,
+ MouseButton::Back => 8,
+ MouseButton::Forward => 16,
+ }
+ }
+
+ pub fn name(self) -> &'static str {
+ match self {
+ MouseButton::None => "none",
+ MouseButton::Left => "left",
+ MouseButton::Middle => "middle",
+ MouseButton::Right => "right",
+ MouseButton::Back => "back",
+ MouseButton::Forward => "forward",
+ }
+ }
+}
+
+/// The button a move reports while `buttons` are held: the first held one, else "none".
+pub fn moving_button(buttons: u8) -> &'static str {
+ crate::sandbox::browser::MOUSE_BUTTON_BITS
+ .iter()
+ .find(|(bit, _)| buttons & bit != 0)
+ .map(|(_, name)| *name)
+ .unwrap_or("none")
+}
+
+/// A computed CSS cursor reduced to one plain keyword: custom `url(...)` cursors give their
+/// fallback, anything odd gives "auto".
+pub fn sanitize_cursor(raw: &str) -> String {
+ let last = raw.rsplit(',').next().unwrap_or("").trim();
+ if !last.is_empty() && last.len() <= 32 && last.bytes().all(|b| b.is_ascii_lowercase() || b == b'-') {
+ last.to_string()
+ } else {
+ "auto".to_string()
+ }
+}
+
+/// A token bucket: at most `rate` per second, bursts up to `burst`. Extra moves are dropped.
+#[derive(Debug)]
+pub struct RateLimit {
+ rate: f64,
+ burst: f64,
+ tokens: f64,
+ at: Instant,
+}
+
+impl RateLimit {
+ pub fn new(rate: f64, burst: f64, now: Instant) -> Self {
+ Self { rate, burst, tokens: burst, at: now }
+ }
+
+ pub fn allow(&mut self, now: Instant) -> bool {
+ let elapsed = now.saturating_duration_since(self.at).as_secs_f64();
+ self.at = now;
+ self.tokens = (self.tokens + elapsed * self.rate).min(self.burst);
+ if self.tokens >= 1.0 {
+ self.tokens -= 1.0;
+ true
+ } else {
+ false
+ }
+ }
+}
+
+/// Moves per second the stream forwards.
+pub const MOVES_PER_SECOND: f64 = 120.0;
+/// How often a cursor change is looked up after moves.
+pub const CURSOR_EVERY: Duration = Duration::from_millis(125);
+
+/// Finds the `<select>` under a point, in the top document. Evaluated with returnByValue false,
+/// so the element comes back as a remote object for [`SELECT_INFO_FN`] and [`SELECT_SET_FN`].
+pub fn select_probe_js(x: f64, y: f64) -> String {
+ format!("(() => {{ const s = document.elementFromPoint({x}, {y})?.closest('select'); return s && !s.disabled ? s : null; }})()")
+}
+
+/// Called on the select: focuses it and describes its options and where it is.
+pub const SELECT_INFO_FN: &str = r#"function () {
+ this.focus();
+ const r = this.getBoundingClientRect();
+ const cut = (s) => String(s ?? '').slice(0, 200);
+ return {
+ multiple: this.multiple,
+ rect: { x: r.x, y: r.y, width: r.width, height: r.height },
+ options: Array.from(this.options).slice(0, 500).map((o) => ({
+ label: cut(o.label || o.text),
+ value: cut(o.value),
+ disabled: o.disabled || (o.parentElement && o.parentElement.tagName === 'OPTGROUP' && o.parentElement.disabled),
+ selected: o.selected,
+ group: o.parentElement && o.parentElement.tagName === 'OPTGROUP' ? cut(o.parentElement.label) : null,
+ })),
+ };
+}"#;
+
+/// Called on the select with the chosen indexes: selects them (only the first unless multiple,
+/// never a disabled one) and fires bubbling input and change, as a real pick does.
+pub const SELECT_SET_FN: &str = r#"function (indexes) {
+ const opts = Array.from(this.options);
+ const ok = indexes.filter((i) => Number.isInteger(i) && i >= 0 && i < opts.length && !opts[i].disabled);
+ if (!ok.length) return false;
+ if (this.multiple) { opts.forEach((o, i) => { o.selected = ok.includes(i); }); }
+ else { this.selectedIndex = ok[0]; }
+ this.dispatchEvent(new Event('input', { bubbles: true }));
+ this.dispatchEvent(new Event('change', { bubbles: true }));
+ return true;
+}"#;
+
+/// The page's selected text, for `copy`. Never from a password field.
+pub const COPY_JS: &str = r#"(() => {
+ const a = document.activeElement;
+ if (a && (a.tagName === 'INPUT' || a.tagName === 'TEXTAREA')) {
+ if (a.type === 'password' || typeof a.selectionStart !== 'number') return '';
+ return a.value.slice(a.selectionStart, a.selectionEnd);
+ }
+ return String(getSelection() || '');
+})()"#;
+
+/// Longest text `copy` returns.
+pub const COPY_MAX: usize = 65536;
+
+pub fn cursor_js(x: f64, y: f64) -> String {
+ format!(
+ "(() => {{ const e = document.elementFromPoint({x}, {y}); if (!e) return 'auto'; const c = getComputedStyle(e).cursor; \
+ if (c !== 'auto') return c; if (e.isContentEditable || e.tagName === 'TEXTAREA' || (e.tagName === 'INPUT' && !['button','submit','reset','checkbox','radio','range','color','file','image'].includes(e.type))) return 'text'; return 'default'; }})()"
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn down<'a>(key: &'a str, code: &'a str, modifiers: u8) -> KeyEvent<'a> {
+ KeyEvent { kind: KeyKind::Down, key, code, text: None, modifiers, location: None, auto_repeat: false }
+ }
+
+ #[test]
+ fn the_key_table_covers_letters_digits_function_numpad_punctuation_and_editing_keys() {
+ assert_eq!(virtual_key_code("KeyA"), Some(65));
+ assert_eq!(virtual_key_code("KeyZ"), Some(90));
+ assert_eq!(virtual_key_code("Digit0"), Some(48));
+ assert_eq!(virtual_key_code("Digit9"), Some(57));
+ assert_eq!(virtual_key_code("F1"), Some(112));
+ assert_eq!(virtual_key_code("F12"), Some(123));
+ assert_eq!(virtual_key_code("F24"), Some(135));
+ assert_eq!(virtual_key_code("Numpad0"), Some(96));
+ assert_eq!(virtual_key_code("Numpad9"), Some(105));
+ assert_eq!(virtual_key_code("NumpadEnter"), Some(13));
+ assert_eq!(virtual_key_code("NumpadAdd"), Some(107));
+ assert_eq!(virtual_key_code("Semicolon"), Some(186));
+ assert_eq!(virtual_key_code("Quote"), Some(222));
+ assert_eq!(virtual_key_code("BracketLeft"), Some(219));
+ assert_eq!(virtual_key_code("PageUp"), Some(33));
+ assert_eq!(virtual_key_code("PageDown"), Some(34));
+ assert_eq!(virtual_key_code("Tab"), Some(9));
+ assert_eq!(virtual_key_code("Space"), Some(32));
+ assert_eq!(virtual_key_code("ShiftRight"), Some(16));
+ assert_eq!(virtual_key_code("MetaLeft"), Some(91));
+ // unknown codes are refused, whatever the key says
+ for bad in ["", "Keya", "KeyAA", "Key1", "Digit", "Digit10", "F0", "F25", "F01", "Numpad", "NumpadX", "Unidentified", "keyA"] {
+ assert_eq!(virtual_key_code(bad), None, "{bad}");
+ }
+ }
+
+ #[test]
+ fn key_locations_follow_the_code() {
+ assert_eq!(key_location("ShiftLeft"), 1);
+ assert_eq!(key_location("ControlRight"), 2);
+ assert_eq!(key_location("Numpad5"), 3);
+ assert_eq!(key_location("ArrowLeft"), 0);
+ assert_eq!(key_location("BracketRight"), 0);
+ assert_eq!(key_location("KeyA"), 0);
+ }
+
+ #[test]
+ fn printable_keys_go_down_with_text_and_others_raw() {
+ let p = key_params(&down("a", "KeyA", 0)).unwrap();
+ assert_eq!(p["type"], "keyDown");
+ assert_eq!(p["text"], "a");
+ assert_eq!(p["windowsVirtualKeyCode"], 65);
+ let p = key_params(&down("A", "KeyA", SHIFT)).unwrap();
+ assert_eq!((p["type"].as_str(), p["text"].as_str(), p["modifiers"].as_u64()), (Some("keyDown"), Some("A"), Some(8)));
+ let p = key_params(&down("Enter", "Enter", 0)).unwrap();
+ assert_eq!((p["type"].as_str(), p["text"].as_str()), (Some("keyDown"), Some("\r")));
+ let p = key_params(&down(" ", "Space", 0)).unwrap();
+ assert_eq!(p["text"], " ");
+ let p = key_params(&down("Tab", "Tab", SHIFT)).unwrap();
+ assert_eq!((p["type"].as_str(), p.get("text"), p["modifiers"].as_u64()), (Some("rawKeyDown"), None, Some(8)));
+ let p = key_params(&down("PageDown", "PageDown", 0)).unwrap();
+ assert_eq!((p["type"].as_str(), p["windowsVirtualKeyCode"].as_u64()), (Some("rawKeyDown"), Some(34)));
+ let p = key_params(&down("1", "Numpad1", 0)).unwrap();
+ assert_eq!((p["location"].as_u64(), p["isKeypad"].as_bool()), (Some(3), Some(true)));
+ let up = KeyEvent { kind: KeyKind::Up, ..down("a", "KeyA", 0) };
+ let p = key_params(&up).unwrap();
+ assert_eq!((p["type"].as_str(), p.get("text")), (Some("keyUp"), None));
+ // client text wins (a dead key's composed character), within limits
+ let p = key_params(&KeyEvent { text: Some("é"), ..down("é", "KeyE", 0) }).unwrap();
+ assert_eq!(p["text"], "é");
+ assert!(key_params(&KeyEvent { text: Some("toolong"), ..down("a", "KeyA", 0) }).is_err());
+ assert!(key_params(&KeyEvent { text: Some("\u{7}"), ..down("a", "KeyA", 0) }).is_err());
+ let auto = key_params(&KeyEvent { auto_repeat: true, ..down("ArrowDown", "ArrowDown", 0) }).unwrap();
+ assert_eq!(auto["autoRepeat"], true);
+ }
+
+ #[test]
+ fn shortcuts_carry_no_text_and_an_editing_command() {
+ let p = key_params(&down("a", "KeyA", CTRL)).unwrap();
+ assert_eq!((p["type"].as_str(), p.get("text")), (Some("rawKeyDown"), None));
+ assert_eq!(p["commands"], json!(["selectAll"]));
+ assert_eq!(key_params(&down("a", "KeyA", META)).unwrap()["commands"], json!(["selectAll"]));
+ assert_eq!(key_params(&down("z", "KeyZ", CTRL)).unwrap()["commands"], json!(["undo"]));
+ assert_eq!(key_params(&down("Z", "KeyZ", CTRL | SHIFT)).unwrap()["commands"], json!(["redo"]));
+ assert_eq!(key_params(&down("c", "KeyC", CTRL)).unwrap()["commands"], json!(["copy"]));
+ assert!(key_params(&down("b", "KeyB", CTRL)).unwrap().get("commands").is_none());
+ // AltGr (Ctrl+Alt) still types its character and runs no command
+ let p = key_params(&down("@", "KeyQ", CTRL | ALT)).unwrap();
+ assert_eq!((p["text"].as_str(), p.get("commands")), (Some("@"), None));
+ // Alt alone (Mac Option) types too
+ assert_eq!(key_params(&down("å", "KeyA", ALT)).unwrap()["text"], "å");
+ // Ctrl+Meta together is not a known shortcut
+ assert!(key_params(&down("a", "KeyA", CTRL | META)).unwrap().get("commands").is_none());
+ // the up of a shortcut runs nothing
+ assert!(key_params(&KeyEvent { kind: KeyKind::Up, ..down("a", "KeyA", CTRL) }).unwrap().get("commands").is_none());
+ }
+
+ #[test]
+ fn bad_keys_are_refused() {
+ assert_eq!(key_params(&down("a", "Unidentified", 0)), Err("Unsupported key code"));
+ assert_eq!(key_params(&down("", "KeyA", 0)), Err("Invalid key"));
+ assert_eq!(key_params(&down("a", "KeyA", 16)), Err("Invalid modifiers"));
+ assert_eq!(key_params(&KeyEvent { location: Some(4), ..down("a", "KeyA", 0) }), Err("Invalid key location"));
+ let long = "x".repeat(33);
+ assert_eq!(key_params(&down(&long, "KeyA", 0)), Err("Invalid key"));
+ }
+
+ #[test]
+ fn resize_is_clamped_and_refuses_nonsense() {
+ assert_eq!(clamp_resize(1440.0, 900.0, Some(2.0)), Ok((1440, 900, 2.0)));
+ assert_eq!(clamp_resize(100.0, 100.0, Some(0.5)), Ok((360, 360, 1.0)));
+ assert_eq!(clamp_resize(5000.0, 5000.0, Some(3.0)), Ok((1920, 1200, 2.0)));
+ assert_eq!(clamp_resize(1280.4, 799.6, None), Ok((1280, 800, 1.0)));
+ assert_eq!(clamp_resize(1000.0, 700.0, Some(1.333333)), Ok((1000, 700, 1.33)));
+ assert!(clamp_resize(f64::NAN, 800.0, None).is_err());
+ assert!(clamp_resize(1280.0, f64::INFINITY, None).is_err());
+ assert!(clamp_resize(1280.0, 800.0, Some(f64::NAN)).is_err());
+ }
+
+ #[test]
+ fn points_are_checked_against_the_current_viewport() {
+ assert!(in_viewport(0.0, 0.0, 1280.0, 800.0).is_ok());
+ assert!(in_viewport(1279.9, 799.9, 1280.0, 800.0).is_ok());
+ assert!(in_viewport(1280.0, 10.0, 1280.0, 800.0).is_err());
+ assert!(in_viewport(10.0, 800.0, 1280.0, 800.0).is_err());
+ assert!(in_viewport(-1.0, 10.0, 1280.0, 800.0).is_err());
+ assert!(in_viewport(f64::NAN, 10.0, 1280.0, 800.0).is_err());
+ // after a resize to 1600x1000 the old limits no longer apply
+ assert!(in_viewport(1500.0, 900.0, 1600.0, 1000.0).is_ok());
+ assert!(in_viewport(1500.0, 900.0, 1280.0, 800.0).is_err());
+ }
+
+ #[test]
+ fn buttons_and_moves() {
+ assert_eq!(MouseButton::Left.bit() | MouseButton::Right.bit() | MouseButton::Middle.bit(), 7);
+ assert_eq!(moving_button(0), "none");
+ assert_eq!(moving_button(1), "left");
+ assert_eq!(moving_button(2), "right");
+ assert_eq!(moving_button(6), "right");
+ assert_eq!(moving_button(4), "middle");
+ }
+
+ #[test]
+ fn cursors_are_plain_keywords() {
+ assert_eq!(sanitize_cursor("pointer"), "pointer");
+ assert_eq!(sanitize_cursor("url(\"x.png\") 2 2, pointer"), "pointer");
+ assert_eq!(sanitize_cursor("url(x.png)"), "auto");
+ assert_eq!(sanitize_cursor("ns-resize"), "ns-resize");
+ assert_eq!(sanitize_cursor("<script>"), "auto");
+ assert_eq!(sanitize_cursor(""), "auto");
+ }
+
+ #[test]
+ fn moves_are_limited_to_the_rate_with_a_small_burst() {
+ let t0 = Instant::now();
+ let mut limit = RateLimit::new(MOVES_PER_SECOND, 10.0, t0);
+ let burst = (0..50).filter(|_| limit.allow(t0)).count();
+ assert_eq!(burst, 10, "a burst is capped");
+ // one second at 1000 moves/s lets about 120 through
+ let mut passed = 0;
+ for i in 1..=1000 {
+ if limit.allow(t0 + Duration::from_millis(i)) {
+ passed += 1;
+ }
+ }
+ assert!((118..=122).contains(&passed), "{passed}");
+ // 60 moves/s (one per frame) all pass
+ let mut limit = RateLimit::new(MOVES_PER_SECOND, 10.0, t0);
+ assert!((1..=120).all(|i| limit.allow(t0 + Duration::from_micros(16_667 * i))));
+ }
+}
diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rs
index 7f5856b7..1cdc99b4 100644
--- a/src/server/browser_stream.rs
+++ b/src/server/browser_stream.rs
@@ -1,19 +1,58 @@
+//! The live view of a bot's browser: a CDP screencast out, the person's input in.
+//!
+//! Protocol v1 (`click`, `type`, `key` without `type`, `scroll`, `navigate`, `pointer_*`) keeps
+//! working for the phone overlay. Protocol v2 adds full mouse events, wheel and key events with
+//! modifiers, `resize`, select interception, JS dialogs, `copy` and cursor updates. Input goes
+//! out on the stream's own DevTools socket, in order, so moves are fire-and-forget and never
+//! wait behind a bot's command.
+use super::browser_input::{self as bi, KeyEvent, KeyKind, MouseButton, RateLimit};
use super::{routes::get_or_create_browser_controller, AppState};
-use crate::sandbox::browser::{BrowserController, BrowserError};
+use crate::sandbox::browser::{BrowserController, BrowserError, HeldPointer, 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};
use serde::Deserialize;
use serde_json::{json, Value};
-use std::time::Duration;
-use tokio::{sync::OwnedRwLockWriteGuard, time::{timeout, Instant}};
+use std::{collections::HashMap, sync::{Arc, atomic::{AtomicBool, AtomicU64, Ordering}}, time::Duration};
+use tokio::{sync::{mpsc, oneshot, OwnedRwLockWriteGuard}, task::JoinHandle, time::{timeout, Instant}};
use tokio_tungstenite::tungstenite::Message as CdpMessage;
+/// The viewport the screencast starts at when the controller has none saved.
+const DEFAULT_VIEW: (u32, u32) = (1280, 800);
+/// How long a discrete action may take before its ack becomes an error. Long, because a click
+/// that opens `alert()` only completes once the person answers the dialog.
+const ACTION_WAIT: Duration = Duration::from_secs(30);
+/// Page lookups (select under the pointer, cursor, focus) give up fast: they block while a
+/// dialog is open.
+const PROBE_WAIT: Duration = Duration::from_secs(2);
+const SELECT_GROUP: &str = "kwnt-select";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum MouseKind {
+ Move,
+ Down,
+ Up,
+}
+
#[derive(Debug, Deserialize)]
#[serde(tag = "action", rename_all = "snake_case")]
pub enum BrowserInput {
Click { x: f64, y: f64 },
Type { text: String },
- Key { key: String, code: Option<String> },
+ /// v1 when `type` is missing: a named key pressed and released. v2 with `type` down or up.
+ Key {
+ key: String,
+ code: Option<String>,
+ #[serde(rename = "type")]
+ kind: Option<KeyKind>,
+ text: Option<String>,
+ #[serde(default)]
+ modifiers: u8,
+ location: Option<u8>,
+ #[serde(default)]
+ auto_repeat: bool,
+ },
Scroll { x: f64, y: f64, delta_x: f64, delta_y: f64 },
Navigate { url: String },
/// Left button down, for drags such as slider CAPTCHAs. Held until `pointer_up`, control
@@ -21,88 +60,602 @@ pub enum BrowserInput {
PointerDown { x: f64, y: f64 },
PointerMove { x: f64, y: f64 },
PointerUp { x: f64, y: f64 },
+ /// v2: any button, click count and modifiers. Moves get no ack.
+ Mouse {
+ #[serde(rename = "type")]
+ kind: MouseKind,
+ x: f64,
+ y: f64,
+ #[serde(default)]
+ button: MouseButton,
+ buttons: Option<u8>,
+ click_count: Option<u32>,
+ #[serde(default)]
+ modifiers: u8,
+ },
+ /// v2 wheel with modifiers (Ctrl+wheel zooms a map, Shift+wheel scrolls sideways). No ack.
+ Wheel {
+ x: f64,
+ y: f64,
+ #[serde(default)]
+ delta_x: f64,
+ #[serde(default)]
+ delta_y: f64,
+ #[serde(default)]
+ modifiers: u8,
+ },
+ /// The person's viewer size, applied while they control and put back afterwards.
+ Resize { width: f64, height: f64, dpr: Option<f64> },
+ /// Picks options in the select the last `select` message described.
+ SelectOption { index: Option<i64>, indexes: Option<Vec<i64>> },
+ /// Answers the open JS dialog.
+ Dialog { accept: bool, prompt_text: Option<String> },
+ /// The page's selected text, sent back as `clipboard`.
+ Copy,
+ /// Back, forward or reload in the tab's own history, acked like `navigate`.
+ History { direction: HistoryDirection },
+}
+
+impl BrowserInput {
+ pub fn parse(value: &Value) -> Result<Self, BrowserError> {
+ let input = serde_json::from_value::<BrowserInput>(value.clone()).map_err(|_| BrowserError::Protocol("Invalid browser input".into()))?;
+ let modifiers = match &input {
+ BrowserInput::Key { modifiers, .. } | BrowserInput::Mouse { modifiers, .. } | BrowserInput::Wheel { modifiers, .. } => *modifiers,
+ _ => 0,
+ };
+ if modifiers > 15 {
+ return Err(BrowserError::Protocol("Invalid modifiers".into()));
+ }
+ Ok(input)
+ }
+
+ /// Streamed input: no ack, and dropped rather than queued while a dialog is open.
+ pub fn is_stream(&self) -> bool {
+ matches!(self, BrowserInput::Mouse { kind: MouseKind::Move, .. } | BrowserInput::Wheel { .. })
+ }
+
+ /// Lets go of something already held (a button or key up), so it still goes through while a
+ /// dialog is open and nothing stays pressed.
+ fn is_release(&self) -> bool {
+ matches!(self, BrowserInput::Mouse { kind: MouseKind::Up, .. } | BrowserInput::PointerUp { .. } | BrowserInput::Key { kind: Some(KeyKind::Up), .. })
+ }
}
impl BrowserController {
- /// Input only: the independent screencast delivers visual changes.
+ /// Where a live-view button is held down, if one is.
+ pub fn pointer_held(&self) -> Option<(f64, f64)> {
+ self.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner()).map(|p| (p.x, p.y))
+ }
+
+ /// Lets go of every held live-view button where it was last seen, so the bot never gets a
+ /// page mid-drag.
+ pub async fn release_pointer(&self) {
+ let held = self.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner()).take();
+ for params in held.map(release_events).unwrap_or_default() {
+ let _ = self.send_cdp_command("Input.dispatchMouseEvent", params).await;
+ }
+ }
+
+ /// Sends one v1 action over the controller's own connection, outside a live view. Tests and
+ /// callers without a stream use it; the live view itself goes through its own socket.
pub async fn dispatch_input(&self, input: BrowserInput) -> Result<(), BrowserError> {
- let point = |x: f64, y: f64| -> Result<(), BrowserError> {
- if x.is_finite() && y.is_finite() && x >= 0.0 && y >= 0.0 && x < 1280.0 && y < 800.0 { Ok(()) }
- else { Err(BrowserError::Protocol("Pointer outside viewport".into())) }
- };
+ let (width, height) = self.fixed_viewport().unwrap_or((1280, 800));
+ let point = |x: f64, y: f64| bi::in_viewport(x, y, width as f64, height as f64).map_err(protocol);
+ let mouse = |params: Value| self.send_cdp_command("Input.dispatchMouseEvent", params);
match input {
BrowserInput::Click { x, y } => {
- point(x, y)?;
+ let (x, y) = point(x, y)?;
for event in ["mousePressed", "mouseReleased"] {
- self.send_cdp_command("Input.dispatchMouseEvent", json!({"type":event,"x":x,"y":y,"button":"left","clickCount":1})).await?;
+ mouse(json!({"type":event,"x":x,"y":y,"button":"left","buttons": if event == "mousePressed" {1} else {0},"clickCount":1})).await?;
}
}
BrowserInput::Type { text } => {
- if text.len() > 16384 { return Err(BrowserError::Protocol("Text too long".into())); }
+ if text.len() > 16384 { return Err(protocol("Text too long")); }
self.send_cdp_command("Input.insertText", json!({"text":text})).await?;
}
- BrowserInput::Key { key, code } => {
+ BrowserInput::Scroll { x, y, delta_x, delta_y } => {
+ let (x, y) = point(x, y)?;
+ if !delta_x.is_finite() || !delta_y.is_finite() { return Err(protocol("Invalid scroll")); }
+ mouse(json!({"type":"mouseWheel","x":x,"y":y,"deltaX":delta_x,"deltaY":delta_y})).await?;
+ }
+ BrowserInput::PointerDown { x, y } => {
+ let (x, y) = point(x, y)?;
+ self.release_pointer().await;
+ mouse(json!({"type":"mousePressed","x":x,"y":y,"button":"left","buttons":1,"clickCount":1})).await?;
+ *self.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner()) = Some(HeldPointer { x, y, buttons: 1 });
+ }
+ BrowserInput::PointerMove { x, y } => {
+ let (x, y) = point(x, y)?;
+ let buttons = self.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner()).map(|h| h.buttons).unwrap_or(0);
+ mouse(json!({"type":"mouseMoved","x":x,"y":y,"button":bi::moving_button(buttons),"buttons":buttons})).await?;
+ if buttons != 0 {
+ *self.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner()) = Some(HeldPointer { x, y, buttons });
+ }
+ }
+ BrowserInput::PointerUp { x, y } => {
+ let (x, y) = point(x, y)?;
+ let held = self.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner()).take();
+ if held.is_some_and(|h| h.buttons & 1 != 0) {
+ mouse(json!({"type":"mouseReleased","x":x,"y":y,"button":"left","buttons":0,"clickCount":1})).await?;
+ }
+ }
+ BrowserInput::Navigate { url } => {
+ let parsed = reqwest::Url::parse(&url).map_err(|e| BrowserError::Protocol(e.to_string()))?;
+ if !matches!(parsed.scheme(), "http"|"https") { return Err(protocol("Use an HTTP or HTTPS URL")); }
+ self.navigate_unlocked(&url).await?;
+ }
+ BrowserInput::History { direction } => self.navigate_history(direction).await?,
+ _ => return Err(protocol("This action needs the live view")),
+ }
+ Ok(())
+ }
+}
+
+/// The `mouseReleased` events that let go of every held button, one per button in bit order.
+fn release_events(held: HeldPointer) -> Vec<Value> {
+ let mut buttons = held.buttons;
+ MOUSE_BUTTON_BITS.iter().filter(|(bit, _)| held.buttons & bit != 0).map(|(bit, name)| {
+ buttons &= !bit;
+ json!({"type":"mouseReleased","x":held.x,"y":held.y,"button":name,"buttons":buttons,"clickCount":1})
+ }).collect()
+}
+
+type Reply = oneshot::Receiver<Result<Value, BrowserError>>;
+type Waiters = Arc<std::sync::Mutex<HashMap<u64, oneshot::Sender<Result<Value, BrowserError>>>>>;
+
+/// A DevTools socket shared by the stream's tasks: one writer keeps commands in order, one reader
+/// routes replies to whoever waits and events to the stream.
+#[derive(Clone)]
+struct Cdp {
+ out: mpsc::UnboundedSender<String>,
+ pending: Waiters,
+ next: Arc<AtomicU64>,
+}
+
+impl Cdp {
+ fn open(ws: crate::sandbox::browser::WsStream) -> (Self, mpsc::Receiver<Value>, [JoinHandle<()>; 2]) {
+ let (mut sink, mut stream) = ws.split();
+ let (out, mut out_rx) = mpsc::unbounded_channel::<String>();
+ let (event_tx, events) = mpsc::channel::<Value>(64);
+ let cdp = Cdp { out, pending: Arc::default(), next: Arc::new(AtomicU64::new(1)) };
+ let writer = tokio::spawn(async move {
+ while let Some(text) = out_rx.recv().await {
+ if sink.send(CdpMessage::Text(text)).await.is_err() { break; }
+ }
+ let _ = sink.close().await;
+ });
+ let pending = cdp.pending.clone();
+ let reader = tokio::spawn(async move {
+ while let Some(message) = stream.next().await {
+ let text = match message {
+ Ok(CdpMessage::Text(text)) => text,
+ Ok(CdpMessage::Ping(_)) | Ok(CdpMessage::Pong(_)) => continue,
+ _ => break,
+ };
+ let value: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
+ if let Some(id) = value.get("id").and_then(Value::as_u64) {
+ let waiter = pending.lock().unwrap_or_else(|e| e.into_inner()).remove(&id);
+ if let Some(waiter) = waiter {
+ let _ = waiter.send(match value.get("error") {
+ Some(error) => Err(BrowserError::Protocol(error["message"].as_str().map(str::to_string).unwrap_or_else(|| error.to_string()))),
+ None => Ok(value.get("result").cloned().unwrap_or(Value::Null)),
+ });
+ }
+ } else if value.get("method").is_some() && event_tx.send(value).await.is_err() {
+ break;
+ }
+ }
+ // waiters see a closed channel; the stream sees its events end
+ pending.lock().unwrap_or_else(|e| e.into_inner()).clear();
+ });
+ (cdp, events, [writer, reader])
+ }
+
+ fn send(&self, id: u64, method: &str, params: Value) {
+ let _ = self.out.send(json!({"id":id,"method":method,"params":params}).to_string());
+ }
+
+ /// Sends without waiting; the reply is dropped.
+ fn fire(&self, method: &str, params: Value) {
+ self.send(self.next.fetch_add(1, Ordering::SeqCst), method, params);
+ }
+
+ /// Sends now; the reply arrives on the returned channel.
+ fn request(&self, method: &str, params: Value) -> Reply {
+ let id = self.next.fetch_add(1, Ordering::SeqCst);
+ let (tx, rx) = oneshot::channel();
+ self.pending.lock().unwrap_or_else(|e| e.into_inner()).insert(id, tx);
+ self.send(id, method, params);
+ rx
+ }
+
+ async fn call(&self, method: &str, params: Value, wait: Duration) -> Result<Value, BrowserError> {
+ settle(self.request(method, params), wait).await
+ }
+}
+
+async fn settle(reply: Reply, wait: Duration) -> Result<Value, BrowserError> {
+ match timeout(wait, reply).await {
+ Ok(Ok(result)) => result,
+ Ok(Err(_)) => Err(BrowserError::Ws("Browser connection closed".into())),
+ Err(_) => Err(BrowserError::Timeout),
+ }
+}
+
+/// State the stream and its worker share.
+struct Shared {
+ /// 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.
+ resized: AtomicBool,
+ cursor: std::sync::Mutex<String>,
+ cursor_busy: AtomicBool,
+ cursor_at: std::sync::Mutex<Option<Instant>>,
+}
+
+impl Shared {
+ fn point(&self, x: f64, y: f64) -> Result<(f64, f64), BrowserError> {
+ let (w, h) = *self.view.lock().unwrap_or_else(|e| e.into_inner());
+ bi::in_viewport(x, y, w, h).map_err(|e| BrowserError::Protocol(e.into()))
+ }
+
+ fn set_view(&self, width: f64, height: f64) {
+ *self.view.lock().unwrap_or_else(|e| e.into_inner()) = (width, height);
+ }
+
+ fn view(&self) -> (f64, f64) {
+ *self.view.lock().unwrap_or_else(|e| e.into_inner())
+ }
+}
+
+enum Job {
+ Input { input: BrowserInput, id: Value },
+ HandBack(Option<oneshot::Sender<()>>),
+}
+
+/// Runs input in the order it came, on the stream's socket.
+struct Worker {
+ ctrl: BrowserController,
+ cdp: Cdp,
+ shared: Arc<Shared>,
+ client: mpsc::UnboundedSender<Value>,
+ /// Left presses that opened our select list instead of reaching the page: their up is
+ /// swallowed too.
+ swallowed: u8,
+ /// The select the last `select` message described, as a remote object.
+ open_select: Option<String>,
+}
+
+fn ack(id: &Value, extra: Value) -> Value {
+ let mut ack = json!({"type":"ack","id":id});
+ if let (Some(ack), Value::Object(extra)) = (ack.as_object_mut(), extra) {
+ ack.extend(extra);
+ }
+ ack
+}
+
+fn error(id: &Value, error: impl std::fmt::Display) -> Value {
+ json!({"type":"error","id":id,"error":error.to_string()})
+}
+
+fn protocol(message: &str) -> BrowserError {
+ BrowserError::Protocol(message.into())
+}
+
+impl Worker {
+ fn held(&self) -> Option<HeldPointer> {
+ *self.ctrl.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner())
+ }
+
+ fn set_held(&self, held: Option<HeldPointer>) {
+ *self.ctrl.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner()) = held.filter(|h| h.buttons != 0);
+ }
+
+ fn mouse(&self, params: Value) -> Reply {
+ self.cdp.request("Input.dispatchMouseEvent", params)
+ }
+
+ /// Acks once every reply is in, with whether a text field has focus when `editable`.
+ fn finish(&self, id: Value, replies: Vec<Reply>, editable: bool) {
+ let (client, cdp) = (self.client.clone(), self.cdp.clone());
+ tokio::spawn(async move {
+ for reply in replies {
+ if let Err(e) = settle(reply, ACTION_WAIT).await {
+ let _ = client.send(error(&id, e));
+ return;
+ }
+ }
+ let extra = if editable { json!({"editable": focused_editable(&cdp).await}) } else { json!({}) };
+ let _ = client.send(ack(&id, extra));
+ });
+ }
+
+ async fn run(mut self, mut jobs: mpsc::UnboundedReceiver<Job>) {
+ while let Some(job) = jobs.recv().await {
+ match job {
+ Job::Input { input, id } => {
+ if let Err(e) = self.handle(input, &id).await {
+ let _ = self.client.send(error(&id, e));
+ }
+ }
+ Job::HandBack(done) => {
+ self.hand_back().await;
+ if let Some(done) = done { let _ = done.send(()); }
+ }
+ }
+ }
+ }
+
+ async fn handle(&mut self, input: BrowserInput, id: &Value) -> Result<(), BrowserError> {
+ match input {
+ BrowserInput::Click { x, y } => {
+ let (x, y) = self.shared.point(x, y)?;
+ if self.offer_select(x, y).await {
+ let _ = self.client.send(ack(id, json!({"editable": false})));
+ return Ok(());
+ }
+ let replies = ["mousePressed", "mouseReleased"].into_iter()
+ .map(|kind| self.mouse(json!({"type":kind,"x":x,"y":y,"button":"left","buttons": if kind == "mousePressed" {1} else {0},"clickCount":1})))
+ .collect();
+ self.finish(id.clone(), replies, true);
+ }
+ BrowserInput::Type { text } => {
+ if text.len() > 16384 { return Err(protocol("Text too long")); }
+ let reply = self.cdp.request("Input.insertText", json!({"text":text}));
+ self.finish(id.clone(), vec![reply], false);
+ }
+ BrowserInput::Key { key, code, kind: None, .. } => {
let keycode = match key.as_str() {
"Enter"=>13,"Backspace"=>8,"Tab"=>9,"Escape"=>27,"ArrowLeft"=>37,
"ArrowUp"=>38,"ArrowRight"=>39,"ArrowDown"=>40,"Delete"=>46,"Home"=>36,"End"=>35,
- _ => return Err(BrowserError::Protocol("Unsupported key".into())),
+ _ => return Err(protocol("Unsupported key")),
};
- for event in ["rawKeyDown", "keyUp"] {
- self.send_cdp_command("Input.dispatchKeyEvent", json!({"type":event,"key":key,"code":code.as_deref().unwrap_or_default(),"windowsVirtualKeyCode":keycode})).await?;
- }
+ let replies = ["rawKeyDown", "keyUp"].into_iter().map(|kind| self.cdp.request("Input.dispatchKeyEvent",
+ json!({"type":kind,"key":key,"code":code.as_deref().unwrap_or_default(),"windowsVirtualKeyCode":keycode}))).collect();
+ self.finish(id.clone(), replies, false);
+ }
+ BrowserInput::Key { key, code, kind: Some(kind), text, modifiers, location, auto_repeat } => {
+ let event = KeyEvent { kind, key: &key, code: code.as_deref().unwrap_or_default(), text: text.as_deref(), modifiers, location, auto_repeat };
+ let params = bi::key_params(&event).map_err(protocol)?;
+ let reply = self.cdp.request("Input.dispatchKeyEvent", params);
+ self.finish(id.clone(), vec![reply], false);
}
BrowserInput::Scroll { x, y, delta_x, delta_y } => {
- point(x,y)?;
- if !delta_x.is_finite() || !delta_y.is_finite() { return Err(BrowserError::Protocol("Invalid scroll".into())); }
- self.send_cdp_command("Input.dispatchMouseEvent", json!({"type":"mouseWheel","x":x,"y":y,"deltaX":delta_x,"deltaY":delta_y})).await?;
+ let (x, y) = self.shared.point(x, y)?;
+ if !delta_x.is_finite() || !delta_y.is_finite() { return Err(protocol("Invalid scroll")); }
+ let reply = self.mouse(json!({"type":"mouseWheel","x":x,"y":y,"deltaX":delta_x,"deltaY":delta_y}));
+ self.finish(id.clone(), vec![reply], false);
+ }
+ BrowserInput::Wheel { x, y, delta_x, delta_y, modifiers } => {
+ let (x, y) = self.shared.point(x, y)?;
+ if !delta_x.is_finite() || !delta_y.is_finite() || delta_x.abs() > 100_000.0 || delta_y.abs() > 100_000.0 {
+ return Err(protocol("Invalid scroll"));
+ }
+ let buttons = self.held().map(|h| h.buttons).unwrap_or(0);
+ self.cdp.fire("Input.dispatchMouseEvent", json!({"type":"mouseWheel","x":x,"y":y,"deltaX":delta_x,"deltaY":delta_y,"modifiers":modifiers,"buttons":buttons}));
+ }
+ BrowserInput::Navigate { url } => {
+ let parsed = reqwest::Url::parse(&url).map_err(|e| BrowserError::Protocol(e.to_string()))?;
+ if !matches!(parsed.scheme(), "http"|"https") { return Err(protocol("Use an HTTP or HTTPS URL")); }
+ self.ctrl.navigate_unlocked(&url).await?;
+ let _ = self.client.send(ack(id, json!({})));
+ }
+ BrowserInput::History { direction } => {
+ self.close_select();
+ self.ctrl.navigate_history(direction).await?;
+ let _ = self.client.send(ack(id, json!({})));
}
BrowserInput::PointerDown { x, y } => {
- point(x, y)?;
+ let (x, y) = self.shared.point(x, y)?;
// A second press without a release (lost pointerup) lets go of the first one
- self.release_pointer().await;
- self.send_cdp_command("Input.dispatchMouseEvent", json!({"type":"mousePressed","x":x,"y":y,"button":"left","buttons":1,"clickCount":1})).await?;
- self.set_pointer_held(Some((x, y)));
+ self.release_held().await;
+ // a phone tap-and-drag on a select shows kwant's list; nothing is held, so the
+ // pointer_up that follows does nothing
+ if self.offer_select(x, y).await {
+ let _ = self.client.send(ack(id, json!({})));
+ return Ok(());
+ }
+ let reply = self.mouse(json!({"type":"mousePressed","x":x,"y":y,"button":"left","buttons":1,"clickCount":1}));
+ self.set_held(Some(HeldPointer { x, y, buttons: 1 }));
+ self.finish(id.clone(), vec![reply], false);
}
BrowserInput::PointerMove { x, y } => {
- point(x, y)?;
- let held = self.pointer_held().is_some();
- self.send_cdp_command("Input.dispatchMouseEvent", json!({"type":"mouseMoved","x":x,"y":y,"button": if held {"left"} else {"none"},"buttons": if held {1} else {0}})).await?;
- if held { self.set_pointer_held(Some((x, y))); }
+ let (x, y) = self.shared.point(x, y)?;
+ let held = self.held();
+ let buttons = held.map(|h| h.buttons).unwrap_or(0);
+ let reply = self.mouse(json!({"type":"mouseMoved","x":x,"y":y,"button":bi::moving_button(buttons),"buttons":buttons}));
+ if held.is_some() { self.set_held(Some(HeldPointer { x, y, buttons })); }
+ self.finish(id.clone(), vec![reply], false);
}
BrowserInput::PointerUp { x, y } => {
- point(x, y)?;
- if self.pointer_held().is_some() {
- self.set_pointer_held(None);
- self.send_cdp_command("Input.dispatchMouseEvent", json!({"type":"mouseReleased","x":x,"y":y,"button":"left","buttons":0,"clickCount":1})).await?;
+ let (x, y) = self.shared.point(x, y)?;
+ let mut replies = vec![];
+ if let Some(held) = self.held().filter(|h| h.buttons & 1 != 0) {
+ let buttons = held.buttons & !1;
+ self.set_held(Some(HeldPointer { x, y, buttons }));
+ replies.push(self.mouse(json!({"type":"mouseReleased","x":x,"y":y,"button":"left","buttons":buttons,"clickCount":1})));
}
+ self.finish(id.clone(), replies, true);
}
- BrowserInput::Navigate { url } => {
- let parsed = reqwest::Url::parse(&url).map_err(|e| BrowserError::Protocol(e.to_string()))?;
- if !matches!(parsed.scheme(), "http"|"https") { return Err(BrowserError::Protocol("Use an HTTP or HTTPS URL".into())); }
- self.navigate_unlocked(&url).await?;
+ BrowserInput::Mouse { kind, x, y, button, buttons: _, click_count, modifiers } => {
+ let (x, y) = self.shared.point(x, y)?;
+ let held = self.held().map(|h| h.buttons).unwrap_or(0);
+ let clicks = click_count.unwrap_or(1).clamp(1, 3);
+ match kind {
+ MouseKind::Move => {
+ self.cdp.fire("Input.dispatchMouseEvent", json!({"type":"mouseMoved","x":x,"y":y,"button":bi::moving_button(held),"buttons":held,"modifiers":modifiers}));
+ if held != 0 { self.set_held(Some(HeldPointer { x, y, buttons: held })); }
+ self.check_cursor(x, y);
+ }
+ MouseKind::Down => {
+ let bit = button.bit();
+ if bit == 0 { return Err(protocol("Invalid mouse button")); }
+ if button == MouseButton::Left && clicks == 1 && modifiers == 0 && self.offer_select(x, y).await {
+ self.swallowed |= bit;
+ let _ = self.client.send(ack(id, json!({})));
+ return Ok(());
+ }
+ let mut replies = vec![];
+ if held & bit != 0 {
+ // a lost up: let go first so the page sees a clean press
+ replies.push(self.mouse(json!({"type":"mouseReleased","x":x,"y":y,"button":button.name(),"buttons":held & !bit,"clickCount":1,"modifiers":modifiers})));
+ }
+ let buttons = held | bit;
+ replies.push(self.mouse(json!({"type":"mousePressed","x":x,"y":y,"button":button.name(),"buttons":buttons,"clickCount":clicks,"modifiers":modifiers})));
+ self.set_held(Some(HeldPointer { x, y, buttons }));
+ self.finish(id.clone(), replies, false);
+ }
+ MouseKind::Up => {
+ let bit = button.bit();
+ if bit == 0 { return Err(protocol("Invalid mouse button")); }
+ if self.swallowed & bit != 0 {
+ self.swallowed &= !bit;
+ let _ = self.client.send(ack(id, json!({})));
+ return Ok(());
+ }
+ let mut replies = vec![];
+ if held & bit != 0 {
+ let buttons = held & !bit;
+ self.set_held(Some(HeldPointer { x, y, buttons }));
+ replies.push(self.mouse(json!({"type":"mouseReleased","x":x,"y":y,"button":button.name(),"buttons":buttons,"clickCount":clicks,"modifiers":modifiers})));
+ }
+ self.finish(id.clone(), replies, button == MouseButton::Left);
+ }
+ }
+ }
+ BrowserInput::Resize { width, height, dpr } => {
+ let Some(_) = self.ctrl.fixed_viewport() else {
+ // the page follows a real window: its size is the window's
+ let (w, h) = self.shared.view();
+ let _ = self.client.send(ack(id, json!({"ignored": true, "viewport": {"width": w, "height": h}})));
+ return Ok(());
+ };
+ let (w, h, dpr) = bi::clamp_resize(width, height, dpr).map_err(protocol)?;
+ // 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?;
+ 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?;
+ let _ = self.client.send(ack(id, json!({"viewport": {"width": w, "height": h, "dpr": dpr}})));
}
+ BrowserInput::SelectOption { index, indexes } => {
+ let Some(object) = self.open_select.clone() else { return Err(protocol("No select is open")) };
+ let indexes = indexes.or(index.map(|i| vec![i])).unwrap_or_default();
+ if indexes.is_empty() || indexes.len() > 500 { return Err(protocol("Choose an option")); }
+ let result = self.cdp.call("Runtime.callFunctionOn", json!({
+ "objectId": object, "functionDeclaration": bi::SELECT_SET_FN,
+ "arguments": [{"value": indexes}], "returnByValue": true,
+ }), PROBE_WAIT).await?;
+ if result["result"]["value"] != true { return Err(protocol("That option can't be picked")); }
+ self.close_select();
+ let _ = self.client.send(ack(id, json!({})));
+ }
+ BrowserInput::Copy => {
+ let result = self.cdp.call("Runtime.evaluate", json!({"expression": bi::COPY_JS, "returnByValue": true}), PROBE_WAIT).await?;
+ let text: String = result["result"]["value"].as_str().unwrap_or_default().chars().take(bi::COPY_MAX).collect();
+ let _ = self.client.send(json!({"type":"clipboard","id":id,"text":text}));
+ let _ = self.client.send(ack(id, json!({})));
+ }
+ // answered by the stream itself, never queued behind the input a dialog blocks
+ BrowserInput::Dialog { .. } => return Err(protocol("No dialog is open")),
}
Ok(())
}
- pub fn pointer_held(&self) -> Option<(f64, f64)> {
- *self.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner())
+ /// If a select is under the point, describes it to the person instead of pressing on it:
+ /// a headless browser draws its option list nowhere the screencast can see.
+ async fn offer_select(&mut self, x: f64, y: f64) -> bool {
+ // a press anywhere closes the list we described; free its object before probing again
+ self.close_select();
+ let Ok(found) = self.cdp.call("Runtime.evaluate", json!({
+ "expression": bi::select_probe_js(x, y), "returnByValue": false, "objectGroup": SELECT_GROUP,
+ }), PROBE_WAIT).await else { return false };
+ let Some(object) = found["result"]["objectId"].as_str().map(str::to_string) else { return false };
+ let Ok(info) = self.cdp.call("Runtime.callFunctionOn", json!({
+ "objectId": object, "functionDeclaration": bi::SELECT_INFO_FN, "returnByValue": true,
+ }), PROBE_WAIT).await else { return false };
+ let info = &info["result"]["value"];
+ if !info["options"].is_array() { return false; }
+ self.open_select = Some(object);
+ let _ = self.client.send(json!({"type":"select","options":info["options"],"multiple":info["multiple"],"rect":info["rect"]}));
+ true
}
- fn set_pointer_held(&self, at: Option<(f64, f64)>) {
- *self.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner()) = at;
+ fn close_select(&mut self) {
+ if self.open_select.take().is_some() {
+ self.cdp.fire("Runtime.releaseObjectGroup", json!({"objectGroup": SELECT_GROUP}));
+ }
}
- /// Lets go of a held left button where it was last seen, so a dropped socket or released
- /// control never leaves the page mid-drag.
- pub async fn release_pointer(&self) {
- let held = self.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner()).take();
- if let Some((x, y)) = held {
- let _ = self.send_cdp_command("Input.dispatchMouseEvent", json!({"type":"mouseReleased","x":x,"y":y,"button":"left","buttons":0,"clickCount":1})).await;
+ /// After a move, looks up the cursor at most every 125 ms and tells the person when it
+ /// changes.
+ fn check_cursor(&self, x: f64, y: f64) {
+ {
+ let mut at = self.shared.cursor_at.lock().unwrap_or_else(|e| e.into_inner());
+ if at.is_some_and(|t| t.elapsed() < bi::CURSOR_EVERY) { return; }
+ if self.shared.cursor_busy.swap(true, Ordering::SeqCst) { return; }
+ *at = Some(Instant::now());
}
+ let (cdp, shared, client) = (self.cdp.clone(), self.shared.clone(), self.client.clone());
+ tokio::spawn(async move {
+ if let Ok(result) = cdp.call("Runtime.evaluate", json!({"expression": bi::cursor_js(x, y), "returnByValue": true}), PROBE_WAIT).await {
+ let cursor = bi::sanitize_cursor(result["result"]["value"].as_str().unwrap_or("auto"));
+ let changed = {
+ let mut last = shared.cursor.lock().unwrap_or_else(|e| e.into_inner());
+ let changed = *last != cursor;
+ *last = cursor.clone();
+ changed
+ };
+ if changed { let _ = client.send(json!({"type":"cursor","cursor":cursor})); }
+ }
+ shared.cursor_busy.store(false, Ordering::SeqCst);
+ });
+ }
+
+ async fn release_held(&self) {
+ let held = self.ctrl.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner()).take();
+ release_on(&self.cdp, held).await;
+ }
+
+ /// The person handed back: nothing stays pressed and the bot gets its own viewport back.
+ async fn hand_back(&mut self) {
+ self.release_held().await;
+ self.swallowed = 0;
+ self.close_select();
+ restore_viewport(&self.ctrl, &self.cdp, &self.shared).await;
}
}
+async fn release_on(cdp: &Cdp, held: Option<HeldPointer>) {
+ for params in held.map(release_events).unwrap_or_default() {
+ let _ = cdp.call("Input.dispatchMouseEvent", params, PROBE_WAIT).await;
+ }
+}
+
+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;
+ shared.set_view(w as f64, h as f64);
+ let _ = restart_screencast(cdp, w, h).await;
+}
+
+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?;
+ Ok(())
+}
+
+fn screencast_params(max_width: u32, max_height: u32) -> Value {
+ json!({"format":"jpeg","quality":65,"maxWidth":max_width,"maxHeight":max_height,"everyNthFrame":1})
+}
+
+async fn focused_editable(cdp: &Cdp) -> bool {
+ cdp.call("Runtime.evaluate", json!({"expression": FOCUSED_EDITABLE_JS, "returnByValue": true}), PROBE_WAIT).await
+ .ok().and_then(|r| r["result"]["value"].as_bool()).unwrap_or(false)
+}
+
pub async fn upgrade(State(state): State<AppState>, Path(id): Path<String>, headers: HeaderMap, ws: WebSocketUpgrade) -> Result<Response, StatusCode> {
// Prevent a third-party website from controlling an authenticated same-origin session.
let origin = headers.get("origin").and_then(|v| v.to_str().ok()).and_then(|s| reqwest::Url::parse(s).ok()).ok_or(StatusCode::FORBIDDEN)?;
@@ -123,126 +676,281 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(),
return Ok(());
}
};
- let mut cdp = crate::sandbox::browser::connect_cdp(&ctrl.get_ws_url().await?).await?;
- let mut command_id = 1u64;
- for method in ["Page.enable", "Page.startScreencast"] {
- cdp.send(CdpMessage::Text(json!({"id":command_id,"method":method,"params": if method == "Page.startScreencast" {json!({"format":"jpeg","quality":65,"maxWidth":1280,"maxHeight":800,"everyNthFrame":1})} else {json!({})}}).to_string())).await.map_err(|e| BrowserError::Ws(e.to_string()))?;
- command_id += 1;
- }
+ let ws = crate::sandbox::browser::connect_cdp(&ctrl.get_ws_url().await?).await?;
+ let (cdp, mut events, tasks) = Cdp::open(ws);
+ let (w, h) = ctrl.fixed_viewport().unwrap_or(DEFAULT_VIEW);
+ let shared = Arc::new(Shared {
+ view: std::sync::Mutex::new((w as f64, h as f64)),
+ resized: AtomicBool::new(false),
+ cursor: std::sync::Mutex::new("auto".into()),
+ cursor_busy: AtomicBool::new(false),
+ cursor_at: std::sync::Mutex::new(None),
+ });
+ let (client_tx, mut client_rx) = mpsc::unbounded_channel::<Value>();
+ let (jobs, jobs_rx) = mpsc::unbounded_channel::<Job>();
+ let worker = Worker { ctrl: ctrl.clone(), cdp: cdp.clone(), shared: shared.clone(), client: client_tx.clone(), swallowed: 0, open_select: None };
+ let worker = tokio::spawn(worker.run(jobs_rx));
+ let result = stream(&mut socket, &ctrl, &cdp, &mut events, &shared, &client_tx, &mut client_rx, &jobs).await;
+ // Let go of anything held and put the viewport back, then drop the lease so bot actions
+ // resume even on disconnect or timeout.
+ worker.abort();
+ let held = ctrl.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner()).take();
+ release_on(&cdp, held).await;
+ restore_viewport(&ctrl, &cdp, &shared).await;
+ drop(result.1);
+ for task in tasks { task.abort(); }
+ result.0
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn stream(
+ socket: &mut WebSocket,
+ ctrl: &BrowserController,
+ cdp: &Cdp,
+ events: &mut mpsc::Receiver<Value>,
+ shared: &Arc<Shared>,
+ client_tx: &mpsc::UnboundedSender<Value>,
+ client_rx: &mut mpsc::UnboundedReceiver<Value>,
+ jobs: &mpsc::UnboundedSender<Job>,
+) -> (Result<(), BrowserError>, Option<OwnedRwLockWriteGuard<()>>) {
let mut lease: Option<OwnedRwLockWriteGuard<()>> = None;
- let mut last_client = Instant::now();
- let mut heartbeat = tokio::time::interval(Duration::from_secs(10));
- let mut pending_frame: Option<i64> = None;
- let mut frame_sent = Instant::now();
- let mut next_frame = 0u64;
- let mut pending_token = 0u64;
- let mut location_tick = tokio::time::interval(Duration::from_secs(2));
- loop {
- tokio::select! {
- _ = heartbeat.tick() => {
- if last_client.elapsed() > Duration::from_secs(35) { break; }
- if pending_frame.is_some() && frame_sent.elapsed() > Duration::from_secs(15) { break; }
- send(&mut socket, json!({"type":"ping"})).await?;
- }
- _ = location_tick.tick() => {
- let _ = ctrl.refresh_location().await;
- send(&mut socket, json!({"type":"location","url":ctrl.current_url.lock().await.clone(),"title":ctrl.current_title.lock().await.clone()})).await?;
- }
- message = cdp.next() => {
- let text = match message {
- Some(Ok(CdpMessage::Text(text))) => text,
- Some(Ok(CdpMessage::Ping(_))) | Some(Ok(CdpMessage::Pong(_))) => continue,
- _ => break,
- };
- let event: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
- if let Some(error) = event.get("error") {
- send(&mut socket, json!({"type":"error","error":format!("Browser stream failed: {error}")})).await?;
- break;
+ let result = async {
+ cdp.call("Page.enable", json!({}), Duration::from_secs(10)).await?;
+ let (w, h) = shared.view();
+ cdp.call("Page.startScreencast", screencast_params(w as u32, h as u32), Duration::from_secs(10)).await?;
+ let mut last_client = Instant::now();
+ let mut heartbeat = tokio::time::interval(Duration::from_secs(10));
+ let mut pending_frame: Option<i64> = None;
+ let mut frame_sent = Instant::now();
+ let mut next_frame = 0u64;
+ let mut pending_token = 0u64;
+ let mut location_tick = tokio::time::interval(Duration::from_secs(2));
+ let location_busy = Arc::new(AtomicBool::new(false));
+ let mut moves = RateLimit::new(bi::MOVES_PER_SECOND, 10.0, std::time::Instant::now());
+ let mut dialog_open = false;
+ loop {
+ tokio::select! {
+ _ = heartbeat.tick() => {
+ if last_client.elapsed() > Duration::from_secs(35) { break; }
+ if pending_frame.is_some() && frame_sent.elapsed() > Duration::from_secs(15) { break; }
+ send(socket, json!({"type":"ping"})).await?;
}
- if event["method"] == "Page.screencastFrame" {
- let session = event["params"]["sessionId"].as_i64().unwrap_or_default();
- if pending_frame.is_some() {
- cdp.send(CdpMessage::Text(json!({"id":command_id,"method":"Page.screencastFrameAck","params":{"sessionId":session}}).to_string())).await.map_err(|e| BrowserError::Ws(e.to_string()))?;
- command_id += 1;
- continue;
+ _ = location_tick.tick() => {
+ // the person handed back a resized page without releasing (a human step ended)
+ if lease.is_none() && !ctrl.is_held_for_person() && shared.resized.load(Ordering::SeqCst) {
+ let _ = jobs.send(Job::HandBack(None));
+ }
+ // read on the stream's socket, off the loop: it blocks while a dialog is open
+ if !location_busy.swap(true, Ordering::SeqCst) {
+ let (cdp, ctrl, client, busy) = (cdp.clone(), ctrl.clone(), client_tx.clone(), location_busy.clone());
+ tokio::spawn(async move {
+ if let Ok(result) = cdp.call("Runtime.evaluate", json!({"expression": "({url: location.href, title: document.title})", "returnByValue": true}), PROBE_WAIT).await {
+ if let Some(url) = result["result"]["value"]["url"].as_str() { *ctrl.current_url.lock().await = Some(url.to_string()); }
+ if let Some(title) = result["result"]["value"]["title"].as_str() { *ctrl.current_title.lock().await = Some(title.to_string()); }
+ }
+ let _ = client.send(json!({"type":"location","url":ctrl.current_url.lock().await.clone(),"title":ctrl.current_title.lock().await.clone()}));
+ busy.store(false, Ordering::SeqCst);
+ });
}
- next_frame += 1;
- pending_token = next_frame;
- pending_frame = Some(session);
- frame_sent = Instant::now();
- send(&mut socket, json!({"type":"frame","id":next_frame,"image":event["params"]["data"],"width":1280,"height":800})).await?;
}
- }
- message = socket.next() => {
- let text = match message {
- Some(Ok(Message::Text(text))) => text,
- Some(Ok(Message::Ping(_))) | Some(Ok(Message::Pong(_))) => { last_client = Instant::now(); continue; },
- _ => break,
- };
- last_client = Instant::now();
- let value: Value = match serde_json::from_str(&text) { Ok(v) => v, Err(_) => break };
- match value["action"].as_str().unwrap_or("") {
- "pong" => {},
- "frame_ack" => {
- if value["id"].as_u64() == Some(pending_token) {
- if let Some(session) = pending_frame.take() {
- cdp.send(CdpMessage::Text(json!({"id":command_id,"method":"Page.screencastFrameAck","params":{"sessionId":session}}).to_string())).await.map_err(|e| BrowserError::Ws(e.to_string()))?;
- command_id += 1;
+ Some(value) = client_rx.recv() => send(socket, value).await?,
+ event = events.recv() => {
+ let Some(event) = event else { break };
+ let params = &event["params"];
+ match event["method"].as_str().unwrap_or_default() {
+ "Page.screencastFrame" => {
+ let session = params["sessionId"].as_i64().unwrap_or_default();
+ let (dw, dh) = (params["metadata"]["deviceWidth"].as_f64().unwrap_or(0.0), params["metadata"]["deviceHeight"].as_f64().unwrap_or(0.0));
+ if dw >= 1.0 && dh >= 1.0 { shared.set_view(dw, dh); }
+ if pending_frame.is_some() {
+ cdp.fire("Page.screencastFrameAck", json!({"sessionId":session}));
+ continue;
}
+ next_frame += 1;
+ pending_token = next_frame;
+ pending_frame = Some(session);
+ frame_sent = Instant::now();
+ let (fw, fh) = shared.view();
+ send(socket, json!({"type":"frame","id":next_frame,"image":params["data"],"width":fw,"height":fh})).await?;
+ }
+ "Page.javascriptDialogOpening" => {
+ dialog_open = true;
+ send(socket, json!({"type":"dialog","kind":params["type"],"message":params["message"].as_str().unwrap_or_default().chars().take(4000).collect::<String>(),
+ "default_prompt":params["defaultPrompt"].as_str().unwrap_or_default().chars().take(4000).collect::<String>(),
+ "url":params["url"].as_str().unwrap_or_default().chars().take(300).collect::<String>()})).await?;
+ }
+ "Page.javascriptDialogClosed" => {
+ dialog_open = false;
+ send(socket, json!({"type":"dialog_closed","accepted":params["result"]})).await?;
}
+ _ => {}
}
- "take_control" => {
- // A pending human step already holds the browser for the person
- if lease.is_none() && !ctrl.is_held_for_person() {
- match ctrl.take_control().await {
- Ok(guard) => lease = Some(guard),
- Err(error) => { send(&mut socket, json!({"type":"error","error":error.to_string()})).await?; continue; }
+ }
+ message = socket.next() => {
+ let text = match message {
+ Some(Ok(Message::Text(text))) => text,
+ Some(Ok(Message::Ping(_))) | Some(Ok(Message::Pong(_))) => { last_client = Instant::now(); continue; },
+ _ => break,
+ };
+ last_client = Instant::now();
+ let value: Value = match serde_json::from_str(&text) { Ok(v) => v, Err(_) => break };
+ let id = value.get("id").cloned().unwrap_or(Value::Null);
+ match value["action"].as_str().unwrap_or("") {
+ "pong" => {},
+ "frame_ack" => {
+ if value["id"].as_u64() == Some(pending_token) {
+ if let Some(session) = pending_frame.take() {
+ cdp.fire("Page.screencastFrameAck", json!({"sessionId":session}));
+ }
}
}
- send(&mut socket, json!({"type":"control","active":true})).await?;
- }
- "release_control" => {
- ctrl.release_pointer().await;
- lease = None;
- send(&mut socket, json!({"type":"control","active":false})).await?;
- }
- _ => {
- let result = if lease.is_none() && !ctrl.is_held_for_person() { Err(BrowserError::HumanControl) } else {
- match serde_json::from_value::<BrowserInput>(value.clone()) {
- Ok(input) => {
- // The person's own input: never held to a bot's site rules
- ctrl.site_guard.set_actor(crate::sandbox::site_guard::Actor::Person);
- ctrl.dispatch_input(input).await
+ "take_control" => {
+ // A pending human step already holds the browser for the person
+ if lease.is_none() && !ctrl.is_held_for_person() {
+ match ctrl.take_control().await {
+ Ok(guard) => lease = Some(guard),
+ Err(error) => { send(socket, json!({"type":"error","error":error.to_string()})).await?; continue; }
}
- Err(_) => Err(BrowserError::Protocol("Invalid browser input".into())),
}
- };
- // After a tap, say whether it landed in a text field so a phone can open its keyboard
- let editable = match (&result, value["action"].as_str().unwrap_or("")) {
- (Ok(()), "click" | "pointer_up") => Some(ctrl.focused_editable().await),
- _ => None,
- };
- send(&mut socket, match result {
- Ok(()) => match editable {
- Some(editable) => json!({"type":"ack","id":value["id"],"editable":editable}),
- None => json!({"type":"ack","id":value["id"]}),
- },
- Err(error) => json!({"type":"error","id":value["id"],"error":error.to_string()}),
- }).await?;
+ let (vw, vh) = shared.view();
+ send(socket, json!({"type":"control","active":true,"viewport":{"width":vw,"height":vh}})).await?;
+ }
+ "release_control" => {
+ let (done, wait) = oneshot::channel();
+ if jobs.send(Job::HandBack(Some(done))).is_ok() {
+ let _ = timeout(Duration::from_secs(8), wait).await;
+ }
+ lease = None;
+ let (vw, vh) = shared.view();
+ send(socket, json!({"type":"control","active":false,"viewport":{"width":vw,"height":vh}})).await?;
+ }
+ _ => {
+ if lease.is_none() && !ctrl.is_held_for_person() {
+ send(socket, error(&id, BrowserError::HumanControl)).await?;
+ continue;
+ }
+ let input = match BrowserInput::parse(&value) {
+ Ok(input) => input,
+ Err(e) => { send(socket, error(&id, e)).await?; continue; }
+ };
+ // The person's own input: never held to a bot's site rules
+ ctrl.site_guard.set_actor(crate::sandbox::site_guard::Actor::Person);
+ if let BrowserInput::Dialog { accept, prompt_text } = input {
+ if !dialog_open { send(socket, error(&id, protocol("No dialog is open"))).await?; continue; }
+ let mut params = json!({"accept": accept});
+ if let Some(text) = prompt_text { params["promptText"] = json!(text.chars().take(16384).collect::<String>()); }
+ let (reply, client) = (cdp.request("Page.handleJavaScriptDialog", params), client_tx.clone());
+ tokio::spawn(async move {
+ let _ = client.send(match settle(reply, PROBE_WAIT).await { Ok(_) => ack(&id, json!({})), Err(e) => error(&id, e) });
+ });
+ continue;
+ }
+ if input.is_stream() {
+ // moves and wheel never queue: extra moves and anything under a dialog are dropped
+ if dialog_open { continue; }
+ if matches!(input, BrowserInput::Mouse { .. }) && !moves.allow(std::time::Instant::now()) { continue; }
+ } else if dialog_open && !input.is_release() {
+ send(socket, error(&id, protocol("The page is showing a dialog. Answer it first."))).await?;
+ continue;
+ }
+ let _ = jobs.send(Job::Input { input, id });
+ }
}
}
}
}
- }
- // Let go of a drag in progress, then drop the lease so bot actions resume even on
- // disconnect or timeout.
- ctrl.release_pointer().await;
- drop(lease);
- let _ = cdp.close(None).await;
- Ok(())
+ Ok(())
+ }.await;
+ (result, lease)
}
async fn send(socket: &mut WebSocket, value: Value) -> Result<(), BrowserError> {
timeout(Duration::from_secs(5), socket.send(Message::Text(value.to_string()))).await
.map_err(|_| BrowserError::Timeout)?.map_err(|e| BrowserError::Ws(e.to_string()))
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn v1_actions_still_parse() {
+ for value in [
+ json!({"action":"click","x":1,"y":2}),
+ json!({"action":"type","text":"hi"}),
+ json!({"action":"key","key":"Enter","code":"Enter"}),
+ json!({"action":"scroll","x":1,"y":2,"delta_x":0,"delta_y":100}),
+ json!({"action":"navigate","url":"https://example.com"}),
+ json!({"action":"pointer_down","x":1,"y":2}),
+ json!({"action":"pointer_move","x":1,"y":2}),
+ json!({"action":"pointer_up","x":1,"y":2}),
+ ] {
+ let input = BrowserInput::parse(&value).unwrap_or_else(|_| panic!("{value}"));
+ assert!(!input.is_stream(), "v1 input is always acked: {value}");
+ }
+ assert!(matches!(BrowserInput::parse(&json!({"action":"key","key":"Tab"})).unwrap(), BrowserInput::Key { kind: None, .. }));
+ }
+
+ #[test]
+ fn v2_actions_parse_with_defaults() {
+ match BrowserInput::parse(&json!({"action":"mouse","type":"down","x":5,"y":6,"button":"right","click_count":2,"modifiers":8})).unwrap() {
+ BrowserInput::Mouse { kind, button, click_count, modifiers, .. } => {
+ assert_eq!((kind, button, click_count, modifiers), (MouseKind::Down, MouseButton::Right, Some(2), 8));
+ }
+ other => panic!("{other:?}"),
+ }
+ let moved = BrowserInput::parse(&json!({"action":"mouse","type":"move","x":5,"y":6})).unwrap();
+ assert!(moved.is_stream());
+ assert!(matches!(moved, BrowserInput::Mouse { button: MouseButton::None, modifiers: 0, click_count: None, .. }));
+ let wheel = BrowserInput::parse(&json!({"action":"wheel","x":1,"y":1,"delta_y":120,"modifiers":2})).unwrap();
+ assert!(wheel.is_stream());
+ assert!(matches!(wheel, BrowserInput::Wheel { delta_x, delta_y, modifiers: 2, .. } if delta_x == 0.0 && delta_y == 120.0));
+ match BrowserInput::parse(&json!({"action":"key","type":"down","key":"a","code":"KeyA","modifiers":2})).unwrap() {
+ BrowserInput::Key { kind, modifiers, auto_repeat, .. } => assert_eq!((kind, modifiers, auto_repeat), (Some(KeyKind::Down), 2, false)),
+ other => panic!("{other:?}"),
+ }
+ assert!(BrowserInput::parse(&json!({"action":"key","type":"up","key":"a","code":"KeyA"})).unwrap().is_release());
+ assert!(matches!(BrowserInput::parse(&json!({"action":"resize","width":900,"height":700})).unwrap(), BrowserInput::Resize { dpr: None, .. }));
+ assert!(matches!(BrowserInput::parse(&json!({"action":"select_option","index":2})).unwrap(), BrowserInput::SelectOption { index: Some(2), indexes: None }));
+ assert!(matches!(BrowserInput::parse(&json!({"action":"dialog","accept":true,"prompt_text":"x"})).unwrap(), BrowserInput::Dialog { accept: true, .. }));
+ assert!(matches!(BrowserInput::parse(&json!({"action":"copy","id":3})).unwrap(), BrowserInput::Copy));
+ }
+
+ #[test]
+ fn history_parses_each_direction_and_refuses_others() {
+ for (wire, direction) in [("back", HistoryDirection::Back), ("forward", HistoryDirection::Forward), ("reload", HistoryDirection::Reload)] {
+ match BrowserInput::parse(&json!({"action":"history","direction":wire,"id":3})).unwrap() {
+ BrowserInput::History { direction: got } => assert_eq!(got, direction, "{wire}"),
+ other => panic!("{other:?}"),
+ }
+ }
+ for bad in [json!({"action":"history","direction":"sideways"}), json!({"action":"history"})] {
+ assert_eq!(BrowserInput::parse(&bad).unwrap_err().to_string(), BrowserError::Protocol("Invalid browser input".into()).to_string(), "{bad}");
+ }
+ }
+
+ #[test]
+ fn bad_messages_are_refused() {
+ for value in [
+ json!({"action":"mouse","type":"hover","x":1,"y":1}),
+ json!({"action":"mouse","type":"down","x":1,"y":1,"button":"thumb"}),
+ json!({"action":"mouse","type":"down","x":1,"y":1,"modifiers":16}),
+ json!({"action":"wheel","x":1,"y":1,"modifiers":300}),
+ json!({"action":"key","type":"sideways","key":"a","code":"KeyA"}),
+ json!({"action":"dialog"}),
+ json!({"action":"resize","width":"wide","height":700}),
+ json!({"action":"teleport"}),
+ ] {
+ assert!(BrowserInput::parse(&value).is_err(), "{value}");
+ }
+ }
+
+ #[test]
+ fn letting_go_releases_every_held_button_in_order() {
+ let events = release_events(HeldPointer { x: 3.0, y: 4.0, buttons: 1 | 2 | 4 });
+ let shape: Vec<_> = events.iter().map(|e| (e["button"].as_str().unwrap().to_string(), e["buttons"].as_u64().unwrap())).collect();
+ assert_eq!(shape, vec![("left".into(), 6), ("right".into(), 4), ("middle".into(), 0)]);
+ assert!(events.iter().all(|e| e["type"] == "mouseReleased" && e["x"] == 3.0 && e["y"] == 4.0));
+ assert!(release_events(HeldPointer { x: 0.0, y: 0.0, buttons: 0 }).is_empty());
+ }
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 9002c63c..6e51f35a 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -1,6 +1,7 @@
pub mod discussion;
pub mod routes;
pub mod sse;
+pub mod browser_input;
pub mod browser_stream;
pub mod mcp_oauth;
pub mod mcp_routes;
diff --git a/tests/browser_stream_test.rs b/tests/browser_stream_test.rs
index 470a7c01..0a1f9d9a 100644
--- a/tests/browser_stream_test.rs
+++ b/tests/browser_stream_test.rs
@@ -240,6 +240,143 @@ async fn pointer_drags_press_move_release_in_order_and_let_go_on_release_or_disc
app_task.abort(); cdp_task.abort();
}
+/// Messages up to and including the ack or error for `id`, skipping frames, pings and locations.
+async fn until_reply(ws: &mut tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>, id: &str) -> Vec<Value> {
+ timeout(Duration::from_secs(5), async {
+ let mut seen = vec![];
+ loop {
+ if let WsMessage::Text(text) = ws.next().await.unwrap().unwrap() {
+ let value: Value = serde_json::from_str(&text).unwrap();
+ match value["type"].as_str().unwrap_or_default() {
+ "ping" => ws.send(WsMessage::Text(json!({"action":"pong"}).to_string())).await.unwrap(),
+ "frame" => ws.send(WsMessage::Text(json!({"action":"frame_ack","id":value["id"]}).to_string())).await.unwrap(),
+ "location" => {}
+ _ => {
+ let done = value["id"] == id && matches!(value["type"].as_str(), Some("ack" | "error"));
+ seen.push(value);
+ if done { return seen; }
+ }
+ }
+ }
+ }
+ }).await.unwrap()
+}
+
+#[tokio::test]
+async fn protocol_v2_mouse_keys_wheel_and_resize_reach_the_page_in_order_and_restore() {
+ 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 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();
+ let frame = receive(&mut ws,"frame").await;
+ assert_eq!((frame["width"].as_f64(), frame["height"].as_f64()), (Some(1280.0), Some(800.0)));
+ let send = |payload: Value| WsMessage::Text(payload.to_string());
+
+ // input needs control first
+ ws.send(send(json!({"action":"mouse","type":"down","x":5,"y":5,"button":"left","id":"early"}))).await.unwrap();
+ assert!(until_reply(&mut ws,"early").await.last().unwrap()["error"].as_str().unwrap().contains("controlled"));
+ ws.send(send(json!({"action":"take_control"}))).await.unwrap();
+ let control = receive(&mut ws,"control").await;
+ assert_eq!((control["active"].clone(), control["viewport"]["width"].as_f64()), (json!(true), Some(1280.0)));
+ mock.commands.lock().await.clear();
+
+ // a hover move is never acked; a right press with Shift and its release are, in order
+ ws.send(send(json!({"action":"mouse","type":"move","x":10,"y":20,"id":"m"}))).await.unwrap();
+ ws.send(send(json!({"action":"mouse","type":"down","x":10,"y":20,"button":"right","modifiers":8,"id":"d"}))).await.unwrap();
+ ws.send(send(json!({"action":"mouse","type":"up","x":10,"y":20,"button":"right","modifiers":8,"id":"u"}))).await.unwrap();
+ let seen = until_reply(&mut ws,"u").await;
+ assert!(!seen.iter().any(|m| m["id"]=="m"), "moves are fire-and-forget: {seen:?}");
+ // a double click: the second press carries clickCount 2
+ for (i, (kind, count)) in [("down",1),("up",1),("down",2),("up",2)].into_iter().enumerate() {
+ ws.send(send(json!({"action":"mouse","type":kind,"x":30,"y":40,"button":"left","click_count":count,"id":format!("c{i}")}))).await.unwrap();
+ }
+ until_reply(&mut ws,"c3").await;
+ let mouse: Vec<_> = mock.commands.lock().await.iter().filter(|c| c["method"]=="Input.dispatchMouseEvent").map(|c| c["params"].clone()).collect();
+ let shape: Vec<_> = mouse.iter().map(|p| (p["type"].as_str().unwrap().to_string(), p["button"].as_str().unwrap().to_string(), p["buttons"].as_i64().unwrap(), p["clickCount"].as_i64().unwrap_or(0), p["modifiers"].as_i64().unwrap())).collect();
+ assert_eq!(shape, vec![
+ ("mouseMoved".into(),"none".into(),0,0,0),
+ ("mousePressed".into(),"right".into(),2,1,8),
+ ("mouseReleased".into(),"right".into(),0,1,8),
+ ("mousePressed".into(),"left".into(),1,1,0),
+ ("mouseReleased".into(),"left".into(),0,1,0),
+ ("mousePressed".into(),"left".into(),1,2,0),
+ ("mouseReleased".into(),"left".into(),0,2,0),
+ ]);
+ mock.commands.lock().await.clear();
+
+ // keys: Ctrl+A is a raw key down with the selectAll command, a letter types its text,
+ // Shift+Tab is a raw key with Shift, an unknown code is refused
+ for (i, (key, code, modifiers)) in [("a","KeyA",2),("b","KeyB",0),("Tab","Tab",8)].into_iter().enumerate() {
+ ws.send(send(json!({"action":"key","type":"down","key":key,"code":code,"modifiers":modifiers,"id":format!("k{i}")}))).await.unwrap();
+ assert_eq!(until_reply(&mut ws,&format!("k{i}")).await.last().unwrap()["type"],"ack");
+ }
+ ws.send(send(json!({"action":"key","type":"down","key":"x","code":"Bogus","id":"bad"}))).await.unwrap();
+ assert!(until_reply(&mut ws,"bad").await.last().unwrap()["error"].as_str().unwrap().contains("Unsupported key code"));
+ let keys: Vec<_> = mock.commands.lock().await.iter().filter(|c| c["method"]=="Input.dispatchKeyEvent").map(|c| c["params"].clone()).collect();
+ assert_eq!(keys.len(), 3);
+ assert_eq!((keys[0]["type"].clone(), keys[0]["windowsVirtualKeyCode"].clone(), keys[0]["commands"].clone(), keys[0].get("text")), (json!("rawKeyDown"), json!(65), json!(["selectAll"]), None));
+ assert_eq!((keys[1]["type"].clone(), keys[1]["text"].clone()), (json!("keyDown"), json!("b")));
+ assert_eq!((keys[2]["type"].clone(), keys[2]["windowsVirtualKeyCode"].clone(), keys[2]["modifiers"].clone()), (json!("rawKeyDown"), json!(9), json!(8)));
+ mock.commands.lock().await.clear();
+
+ // wheel carries modifiers and is not acked
+ ws.send(send(json!({"action":"wheel","x":100,"y":100,"delta_y":120,"modifiers":2,"id":"w"}))).await.unwrap();
+ ws.send(send(json!({"action":"type","text":"z","id":"t"}))).await.unwrap();
+ assert!(!until_reply(&mut ws,"t").await.iter().any(|m| m["id"]=="w"));
+ let wheel = mock.commands.lock().await.iter().find(|c| c["params"]["type"]=="mouseWheel").cloned().unwrap();
+ assert_eq!((wheel["params"]["deltaY"].as_f64(), wheel["params"]["modifiers"].as_i64()), (Some(120.0), Some(2)));
+
+ // resize: applied, screencast restarted at device pixels, bounds follow the new viewport
+ mock.commands.lock().await.clear();
+ ws.send(send(json!({"action":"resize","width":900,"height":5000,"dpr":2,"id":"r"}))).await.unwrap();
+ let resized = until_reply(&mut ws,"r").await.pop().unwrap();
+ assert_eq!(resized["viewport"], json!({"width":900,"height":1200,"dpr":2.0}), "height clamps to 1200");
+ let commands = mock.commands.lock().await.clone();
+ let metrics = commands.iter().find(|c| c["method"]=="Emulation.setDeviceMetricsOverride").unwrap();
+ assert_eq!((metrics["params"]["width"].clone(), metrics["params"]["height"].clone(), metrics["params"]["deviceScaleFactor"].clone()), (json!(900), json!(1200), json!(2.0)));
+ let cast = commands.iter().find(|c| c["method"]=="Page.startScreencast").unwrap();
+ assert_eq!((cast["params"]["maxWidth"].clone(), cast["params"]["maxHeight"].clone()), (json!(1800), json!(2400)));
+ ws.send(send(json!({"action":"mouse","type":"down","x":950,"y":10,"button":"left","id":"o"}))).await.unwrap();
+ assert!(until_reply(&mut ws,"o").await.last().unwrap()["error"].as_str().unwrap().contains("outside"));
+ ws.send(send(json!({"action":"mouse","type":"down","x":850,"y":1100,"button":"left","id":"in"}))).await.unwrap();
+ assert_eq!(until_reply(&mut ws,"in").await.last().unwrap()["type"],"ack");
+
+ // release: the held button is let go and the bot's 1280x800 comes back
+ mock.commands.lock().await.clear();
+ ws.send(send(json!({"action":"release_control"}))).await.unwrap();
+ let released = receive(&mut ws,"control").await;
+ assert_eq!((released["active"].clone(), released["viewport"]["width"].as_f64()), (json!(false), Some(1280.0)));
+ let commands = mock.commands.lock().await.clone();
+ assert!(commands.iter().any(|c| c["params"]["type"]=="mouseReleased" && c["params"]["button"]=="left"));
+ let metrics = commands.iter().find(|c| c["method"]=="Emulation.setDeviceMetricsOverride").unwrap();
+ assert_eq!((metrics["params"]["width"].clone(), metrics["params"]["height"].clone(), metrics["params"]["deviceScaleFactor"].clone()), (json!(1280), json!(800), json!(1)));
+ assert_eq!(commands.iter().find(|c| c["method"]=="Page.startScreencast").unwrap()["params"]["maxWidth"], 1280);
+ assert!(ctrl.pointer_held().is_none());
+
+ // a resize then a dropped socket: restored as well
+ ws.send(send(json!({"action":"take_control"}))).await.unwrap();
+ receive(&mut ws,"control").await;
+ ws.send(send(json!({"action":"resize","width":700,"height":500,"id":"r2"}))).await.unwrap();
+ until_reply(&mut ws,"r2").await;
+ mock.commands.lock().await.clear();
+ drop(ws);
+ timeout(Duration::from_secs(5),async {loop {
+ let restored = mock.commands.lock().await.iter().any(|c| c["method"]=="Emulation.setDeviceMetricsOverride" && c["params"]["width"]==1280);
+ if restored && ctrl.control.try_read().is_ok() {break;}
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }}).await.unwrap();
+ app_task.abort(); cdp_task.abort();
+}
+
/// Opt in after building docker/browser.Dockerfile. Uses disposable data and a local HTML page.
#[tokio::test]
#[ignore = "requires Docker and the kwnt-browser:v2 image"]