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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
0.8.0 F: a bot's Enter submits forms, Chrome for Testing on Windows, CI web-stage (#457)
Oleksandr Ivanchenko695a4b8fadba
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 45a0575f..8b01df4c 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -58,6 +58,21 @@ jobs:- name: Script testsrun: python3 -m unittest discover -s scripts -p 'test_*.py'+ # 077-ci-web-stage: the Dockerfile's web stage, as `docker compose up --build` runs it from source. It copies only+ # what it names, so a file the frontend build reads but the stage doesn't copy breaks source builds while the+ # frontend job (a full checkout) stays green. 0.7.6 shipped like that: vite.config.ts read ../CHANGELOG.md, the stage+ # had no CHANGELOG.md, and only the test server's build showed it.+ web-stage:+ name: web-stage+ runs-on: ubuntu-latest+ timeout-minutes: 20+ steps:+ - uses: actions/checkout@v4+ - name: docker build --target web+ env:+ DOCKER_BUILDKIT: 1+ run: docker build -f docker/kwnt.Dockerfile --target web --progress plain .+# O9, the new-computer test on every release: kwnt starts as a brand-new user (empty HOME, `env -i`, a bare PATH# with no AI tools), and the job checks that the Get started card shows, that the one-click Claude Code install# starts and finishes against a stand-in download (the real one is never fetched: the fake curl refuses everydiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 52813aa2..e36af2ba 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).## Unreleased+### Added+- **kwant's own browser on Windows and Linux ARM.** When no Chrome is found, kwant can now download Google's Chrome for Testing on 64-bit Windows and on Linux ARM (aarch64) too, as it already did on Mac and Linux x64. On Windows it's kept in `AppData\Local\kwant\chrome` in your user folder. (#457)++### Fixed+- **A bot's Enter now submits forms.** When a bot pressed Enter in kwant's browser, the page saw the key but a search box or login form never sent. Enter, Tab, Backspace, Space, the arrows and single characters now go out as a real keyboard sends them. A key kwant can't press, such as `Control+a` or a whole word, is refused with a hint to type text instead. (#457)+- Every pull request now builds the web part of `docker compose up --build`, so a source build can't break unnoticed again as it did in 0.7.6. (#457)+## [Mac 0.7.7] - 2026-11-09### Addeddiff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rsindex 209d8923..a9b51c4a 100644--- a/src/sandbox/browser.rs+++ b/src/sandbox/browser.rs@@ -372,6 +372,97 @@ pub enum BrowserError {/// The driving bot's site rules refused the page (see [`super::site_guard`]).#[error("{}", .0.message)]SiteRule(super::site_guard::Refusal),+ /// A key press kwnt can't describe to Chrome as a real key (see [`key_press_params`]).+ #[error("{0}")]+ UnsupportedKey(String),+}++/// The `KeyboardEvent.code` (and whether Shift is held, on a US layout) for a key a bot or the+/// v1 live view names without one: named keys, single letters, digits, space and punctuation.+fn code_for_key(key: &str) -> Option<(String, bool)> {+ use crate::server::browser_input::virtual_key_code;+ let named = match key {+ "Shift" => Some("ShiftLeft"),+ "Control" => Some("ControlLeft"),+ "Alt" => Some("AltLeft"),+ "Meta" => Some("MetaLeft"),+ _ => None,+ };+ if let Some(code) = named {+ return Some((code.into(), false));+ }+ let mut chars = key.chars();+ let (Some(c), None) = (chars.next(), chars.next()) else {+ // Enter, Tab, Escape, Backspace, arrows, Home, F5...: the key is its own code+ return virtual_key_code(key).map(|_| (key.to_string(), false));+ };+ let shifted = "~!@#$%^&*()_+{}|:\"<>?";+ let code = match c {+ 'a'..='z' | 'A'..='Z' => format!("Key{}", c.to_ascii_uppercase()),+ '0'..='9' => format!("Digit{c}"),+ ' ' => "Space".into(),+ '`' | '~' => "Backquote".into(),+ '!' => "Digit1".into(),+ '@' => "Digit2".into(),+ '#' => "Digit3".into(),+ '$' => "Digit4".into(),+ '%' => "Digit5".into(),+ '^' => "Digit6".into(),+ '&' => "Digit7".into(),+ '*' => "Digit8".into(),+ '(' => "Digit9".into(),+ ')' => "Digit0".into(),+ '-' | '_' => "Minus".into(),+ '=' | '+' => "Equal".into(),+ '[' | '{' => "BracketLeft".into(),+ ']' | '}' => "BracketRight".into(),+ '\\' | '|' => "Backslash".into(),+ ';' | ':' => "Semicolon".into(),+ '\'' | '"' => "Quote".into(),+ ',' | '<' => "Comma".into(),+ '.' | '>' => "Period".into(),+ '/' | '?' => "Slash".into(),+ _ => return None,+ };+ Some((code, c.is_ascii_uppercase() || shifted.contains(c)))+}++/// One key press (down, then up) as `Input.dispatchKeyEvent` params: the same event the person's+/// live view sends ([`crate::server::browser_input::key_params`]), with the Windows key code and,+/// for a key that types, `keyDown` with its text. Enter carries `\r`, which is what makes Chrome+/// submit a form; a bare `rawKeyDown` with only `key` and `code` fired keydown and nothing else.+/// `code` is worked out from `key` when the caller leaves it out. "Space"/"Spacebar" mean the+/// space bar, "Return" Enter and "Esc" Escape.+pub fn key_press_params(key: &str, code: Option<&str>) -> Result<[Value; 2], BrowserError> {+ use crate::server::browser_input::{key_params, KeyEvent, KeyKind, SHIFT};+ let key = match key {+ "Space" | "Spacebar" => " ",+ "Return" => "Enter",+ "Esc" => "Escape",+ k => k,+ };+ let unsupported = || {+ let shown: String = key.chars().take(32).collect();+ BrowserError::UnsupportedKey(format!(+ "Can't press \"{shown}\": press one key, such as Enter, Tab, Escape, Backspace, an arrow key or a single character. To enter text, type it."+ ))+ };+ let (code, shift) = match code.filter(|c| !c.is_empty()) {+ Some(c) => (c.to_string(), false),+ None => code_for_key(key).ok_or_else(unsupported)?,+ };+ let event = |kind| KeyEvent {+ kind,+ key,+ code: &code,+ text: None,+ modifiers: if shift { SHIFT } else { 0 },+ location: None,+ auto_repeat: false,+ };+ let down = key_params(&event(KeyKind::Down)).map_err(|_| unsupported())?;+ let up = key_params(&event(KeyKind::Up)).map_err(|_| unsupported())?;+ Ok([down, up])}/// A live view's control of the browser ([`BrowserController::take_control`]): the write lock,@@ -2063,23 +2154,9 @@ impl BrowserController {}pub async fn interact_key(&self, key: &str, code: Option<&str>) -> Result<String, BrowserError> {- let mut down_params = json!({- "type": "rawKeyDown",- "key": key- });- if let Some(c) = code {- down_params["code"] = json!(c);- }- self.send_cdp_command("Input.dispatchKeyEvent", down_params).await?;-- let mut up_params = json!({- "type": "keyUp",- "key": key- });- if let Some(c) = code {- up_params["code"] = json!(c);- }- self.send_cdp_command("Input.dispatchKeyEvent", up_params).await?;+ let [down, up] = key_press_params(key, code)?;+ self.send_cdp_command("Input.dispatchKeyEvent", down).await?;+ self.send_cdp_command("Input.dispatchKeyEvent", up).await?;tokio::time::sleep(Duration::from_millis(150)).await;let _ = self.collect_captured_credentials().await;@@ -2107,6 +2184,79 @@ impl BrowserController {}+#[cfg(test)]+mod key_tests {+ use super::{key_press_params, BrowserError};++ fn down(key: &str, code: Option<&str>) -> serde_json::Value {+ key_press_params(key, code).unwrap()[0].clone()+ }++ /// F-1 (0.8.0): a bot's Enter went out as a bare rawKeyDown with only key and code, so Chrome+ /// fired keydown and never submitted the form. It's now the live view's event: keyDown with+ /// "\r" and key code 13, then keyUp.+ #[test]+ fn enter_is_a_key_down_with_text_and_key_code() {+ for code in [None, Some("Enter")] {+ let [d, u] = key_press_params("Enter", code).unwrap();+ assert_eq!(d["type"], "keyDown", "{d}");+ assert_eq!(d["text"], "\r");+ assert_eq!(d["unmodifiedText"], "\r");+ assert_eq!(d["windowsVirtualKeyCode"], 13);+ assert_eq!(d["code"], "Enter");+ assert_eq!(u["type"], "keyUp");+ assert_eq!(u["windowsVirtualKeyCode"], 13);+ assert!(u.get("text").is_none(), "{u}");+ }+ assert_eq!(down("Return", None)["text"], "\r");+ }++ #[test]+ fn keys_without_text_are_raw_with_their_key_code() {+ for (key, vk) in [("Tab", 9), ("Escape", 27), ("Esc", 27), ("Backspace", 8), ("Delete", 46), ("ArrowLeft", 37), ("ArrowDown", 40), ("Home", 36), ("End", 35), ("PageDown", 34), ("F5", 116)] {+ let d = down(key, None);+ assert_eq!((d["type"].as_str(), d["windowsVirtualKeyCode"].as_u64()), (Some("rawKeyDown"), Some(vk)), "{key}: {d}");+ assert!(d.get("text").is_none(), "{key}: {d}");+ }+ assert_eq!(down("Shift", None)["code"], "ShiftLeft");+ }++ #[test]+ fn single_characters_type_with_their_code() {+ for (key, code, vk, shift) in [+ ("a", "KeyA", 65, false),+ ("Z", "KeyZ", 90, true),+ ("7", "Digit7", 55, false),+ ("!", "Digit1", 49, true),+ ("/", "Slash", 191, false),+ ("?", "Slash", 191, true),+ (" ", "Space", 32, false),+ ("Space", "Space", 32, false),+ ("Spacebar", "Space", 32, false),+ ] {+ let d = down(key, None);+ let text = if key.len() == 1 { key } else { " " };+ assert_eq!(d["type"], "keyDown", "{key}: {d}");+ assert_eq!(d["text"], text, "{key}: {d}");+ assert_eq!(d["code"], code, "{key}");+ assert_eq!(d["windowsVirtualKeyCode"], vk, "{key}");+ assert_eq!(d["modifiers"], if shift { 8 } else { 0 }, "{key}");+ }+ }++ #[test]+ fn a_key_kwnt_cant_describe_is_refused_with_a_hint() {+ for key in ["", "Control+a", "hello", "é", "Unidentified", "\u{7}"] {+ match key_press_params(key, None) {+ Err(e @ BrowserError::UnsupportedKey(_)) => assert!(e.to_string().contains("type it"), "{key}: {e}"),+ other => panic!("{key:?}: {other:?}"),+ }+ }+ // a code Chrome has no key number for is refused too, as in the live view+ assert!(matches!(key_press_params("x", Some("NotAKey")), Err(BrowserError::UnsupportedKey(_))));+ }+}+#[cfg(test)]mod tests {use super::cdp_ws_request;diff --git a/src/sandbox/chrome_download.rs b/src/sandbox/chrome_download.rsindex dcc3936f..67fbbdc8 100644--- a/src/sandbox/chrome_download.rs+++ b/src/sandbox/chrome_download.rs@@ -1,7 +1,8 @@//! The bots' private browser without Node (0.7.6, O5): when a bot first needs the local browser//! and this computer has no Chrome or Chromium, kwnt downloads Google's Chrome for Testing build//! into its own cache folder (`~/Library/Caches/kwant/chrome` on a Mac, `~/.cache/kwant/chrome`-//! on Linux) and uses that. No admin rights, no Homebrew, no Node.+//! on Linux, `%USERPROFILE%\AppData\Local\kwant\chrome` on Windows) and uses that. No admin+//! rights, no Homebrew, no Node.//!//! It is silent unless it fails. Then [`FAILED_LINE`] is what the person sees, with "Try again"//! ([`ChromeSetup::retry`]).@@ -11,9 +12,10 @@//! in Google's JSON), checked for a complete body and the expected browser inside, and has to//! start (`--version`) before it is used.//!-//! There's no build for Linux on ARM, and a Linux that blocks the sandbox of a browser in the-//! home folder (Ubuntu 23.10+) couldn't start one, so neither downloads: they keep the existing-//! "install Chromium" advice.+//! Google builds it for Mac (Apple silicon and Intel), Linux (x86-64 and, since 0.8.0 here, ARM)+//! and Windows (x64, since 0.8.0): see the `platform` of each download in [`CFT_JSON`]. A Linux+//! that blocks the sandbox of a browser in the home folder (Ubuntu 23.10+) couldn't start one, so+//! it doesn't download: it keeps the existing "install Chromium" advice.use std::path::{Path, PathBuf};use std::process::Stdio;use std::sync::Mutex;@@ -35,32 +37,49 @@ pub const RETRY_AFTER: Duration = Duration::from_secs(10 * 60);pub const MAX_BYTES: u64 = 1 << 30;/// The Chrome for Testing platform for this OS and CPU, or `None` where Google has no build-/// (Linux on ARM) or kwnt doesn't download one (Windows).+/// (32-bit and other CPUs; kwnt's Windows app is x64 only, so `win32` isn't used). The names are+/// Google's, as in [`CFT_JSON`]: `mac-arm64`, `mac-x64`, `linux64`, `linux-arm64`, `win64`.pub fn cft_platform(os: &str, arch: &str) -> Option<&'static str> {match (os, arch) {("macos", "aarch64") => Some("mac-arm64"),("macos", "x86_64") => Some("mac-x64"),("linux", "x86_64") => Some("linux64"),+ ("linux", "aarch64") => Some("linux-arm64"),+ ("windows", "x86_64") => Some("win64"),_ => None,}}-/// The browser inside a build's zip (and inside its install folder).+/// The browser inside a build's zip (and inside its install folder): the app bundle's binary on+/// a Mac, `chrome-win64/chrome.exe` on Windows, `chrome-<platform>/chrome` on Linux.pub fn binary_in(platform: &str) -> PathBuf {let app = "Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing";match platform {"mac-arm64" | "mac-x64" => PathBuf::from(format!("chrome-{platform}")).join(app),+ "win64" => PathBuf::from("chrome-win64").join("chrome.exe"),_ => PathBuf::from(format!("chrome-{platform}")).join("chrome"),}}/// kwnt's own browser cache under `home`: `Library/Caches/kwant/chrome` on a Mac,-/// `.cache/kwant/chrome` elsewhere.+/// `AppData/Local/kwant/chrome` (the default `%LOCALAPPDATA%`) on Windows, `.cache/kwant/chrome`+/// elsewhere.pub fn cache_root(os: &str, home: &Path) -> PathBuf {- if os == "macos" {- home.join("Library/Caches/kwant/chrome")+ match os {+ "macos" => home.join("Library/Caches/kwant/chrome"),+ "windows" => home.join("AppData").join("Local").join("kwant").join("chrome"),+ _ => home.join(".cache/kwant/chrome"),+ }+}++/// The home folder the private browser lives under: `$HOME`, or on Windows (where `HOME` is+/// usually unset) the user's profile folder.+pub fn browser_home() -> Option<PathBuf> {+ let home = std::env::var_os("HOME").filter(|h| !h.is_empty()).map(PathBuf::from);+ if cfg!(windows) {+ home.or_else(dirs::home_dir)} else {- home.join(".cache/kwant/chrome")+ home}}@@ -98,7 +117,7 @@ pub enum SetupState {Ready,/// The last attempt failed: show [`FAILED_LINE`] and "Try again".Failed,- /// No build for this computer (Linux on ARM, Windows) or its sandbox is blocked: the+ /// No build for this computer (32-bit, Docker, no home folder) or its sandbox is blocked: the/// existing "install Chrome" advice applies.Unavailable,}@@ -152,7 +171,7 @@ impl ChromeSetup {/// For this computer: `$HOME`'s cache folder and this OS and CPU. Linux whose sandbox is/// blocked, and Docker, get no download.pub fn system() -> Self {- let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default();+ let home = browser_home().unwrap_or_default();let os = std::env::consts::OS;let platform = cft_platform(os, std::env::consts::ARCH).filter(|_| {!super::computer::chrome_sandbox_blocked()@@ -400,7 +419,16 @@ impl ChromeSetup {use std::os::unix::fs::PermissionsExt;let _ = std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755));}- let said = starts(&bin).await?;+ let said = if cfg!(windows) {+ // `chrome.exe --version` opens a browser window instead of printing, so on Windows the+ // build has to start for real: windowless, on a scratch profile, until it listens+ let probe = self.root.join(format!(".probe.{}", std::process::id()));+ let started = starts_headless(&bin, &probe, Duration::from_secs(60)).await;+ remove_profile(&probe).await;+ started.map(|()| format!("Chrome for Testing {version}"))?+ } else {+ starts(&bin).await?+ };tracing::info!(version = %said, "the bots' private browser starts");let dest = self.root.join(format!("{version}-{platform}"));@@ -449,6 +477,55 @@ async fn starts(bin: &Path) -> Result<String, String> {Ok(said)}+/// Starts `bin` without a window on the scratch profile `profile`, and waits for it to write its+/// DevTools port there (it started and listens) for at most `wait`. The browser is stopped+/// either way. Used on Windows, where `--version` doesn't print.+pub async fn starts_headless(bin: &Path, profile: &Path, wait: Duration) -> Result<(), String> {+ std::fs::create_dir_all(profile).map_err(|_| "couldn't make a scratch profile to start the browser".to_string())?;+ let mut child = tokio::process::Command::new(bin)+ .args([+ "--headless".to_string(),+ "--no-first-run".into(),+ "--no-default-browser-check".into(),+ "--disable-gpu".into(),+ format!("--user-data-dir={}", profile.display()),+ "--remote-debugging-port=0".into(),+ "about:blank".into(),+ ])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .kill_on_drop(true)+ .spawn()+ .map_err(|_| "the downloaded browser couldn't be started".to_string())?;+ let until = Instant::now() + wait;+ let result = loop {+ if super::computer::read_devtools_port(profile).is_some() {+ break Ok(());+ }+ if let Ok(Some(_)) = child.try_wait() {+ break Err("the downloaded browser stopped right after starting (missing system files?)".to_string());+ }+ if Instant::now() >= until {+ break Err("the downloaded browser didn't start in time".to_string());+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ };+ let _ = child.kill().await;+ result+}++/// Removes a scratch profile; on Windows the stopped browser's helpers can hold its files for a+/// moment. Left behind if it still can't go (it's ignored as a build: no `<version>-<platform>`).+async fn remove_profile(profile: &Path) {+ for _ in 0..50 {+ if std::fs::remove_dir_all(profile).is_ok() || !profile.exists() {+ return;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+}+#[cfg(test)]mod tests {use super::*;@@ -458,9 +535,81 @@ mod tests {assert_eq!(cft_platform("macos", "aarch64"), Some("mac-arm64"));assert_eq!(cft_platform("macos", "x86_64"), Some("mac-x64"));assert_eq!(cft_platform("linux", "x86_64"), Some("linux64"));- // Google has no Linux ARM build; Windows isn't downloaded- assert_eq!(cft_platform("linux", "aarch64"), None);- assert_eq!(cft_platform("windows", "x86_64"), None);+ // 0.8.0: Google's list has linux-arm64 and win64 builds (F, Vega), see CFT_JSON+ assert_eq!(cft_platform("linux", "aarch64"), Some("linux-arm64"));+ assert_eq!(cft_platform("windows", "x86_64"), Some("win64"));+ // no build: 32-bit Windows (kwnt's app is x64), Windows on ARM, other CPUs and systems+ assert_eq!(cft_platform("windows", "x86"), None);+ assert_eq!(cft_platform("windows", "aarch64"), None);+ assert_eq!(cft_platform("linux", "x86"), None);+ assert_eq!(cft_platform("linux", "riscv64"), None);+ assert_eq!(cft_platform("freebsd", "x86_64"), None);+ }++ /// The paths inside Google's zips (read from the 157.0.8103.38 Stable zips' listings,+ /// 2026-11-09): chrome-win64/chrome.exe and chrome-linux-arm64/chrome.+ #[test]+ fn the_browser_inside_each_platforms_zip() {+ let path = |p: &str| binary_in(p).to_string_lossy().replace('\\', "/");+ assert_eq!(path("win64"), "chrome-win64/chrome.exe");+ assert_eq!(path("linux-arm64"), "chrome-linux-arm64/chrome");+ assert_eq!(path("linux64"), "chrome-linux64/chrome");+ assert_eq!(path("mac-x64"), "chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing");+ }++ #[test]+ fn windows_and_linux_arm_builds_are_found_in_their_cache() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ let win = cache_root("windows", home);+ assert_eq!(win, home.join("AppData").join("Local").join("kwant").join("chrome"));+ for (os, root, platform) in [("windows", win, "win64"), ("linux", cache_root("linux", home), "linux-arm64")] {+ assert_eq!(downloaded_chrome(os, home), None);+ for v in ["131.0.6778.85", "157.0.8103.38"] {+ let bin = root.join(format!("{v}-{platform}")).join(binary_in(platform));+ std::fs::create_dir_all(bin.parent().unwrap()).unwrap();+ std::fs::write(&bin, "").unwrap();+ }+ // a scratch profile from the Windows start check is never taken for a build+ std::fs::create_dir_all(root.join(".probe.42")).unwrap();+ assert_eq!(+ downloaded_chrome(os, home),+ Some(root.join(format!("157.0.8103.38-{platform}")).join(binary_in(platform))),+ "{os}"+ );+ }+ }++ #[cfg(windows)]+ #[test]+ fn windows_finds_its_home_without_home_set() {+ assert!(browser_home().is_some_and(|h| h.is_absolute()));+ }++ /// The Windows start check, run here against whatever Chrome this computer has (the GitHub+ /// Windows runner has Google Chrome; Linux uses the local one). Skipped without one.+ #[tokio::test]+ async fn the_headless_start_check_passes_a_real_browser_and_fails_a_non_browser() {+ let tmp = tempfile::tempdir().unwrap();+ // not a browser: this test binary rejects Chrome's flags and exits at once+ let me = std::env::current_exe().unwrap();+ let err = starts_headless(&me, &tmp.path().join("p0"), Duration::from_secs(30)).await.unwrap_err();+ assert!(err.contains("stopped right after starting"), "{err}");++ let installed = Path::new(r"C:\Program Files\Google\Chrome\Application\chrome.exe");+ let chrome = if cfg!(windows) && installed.is_file() {+ Some(installed.to_path_buf())+ } else {+ super::super::computer::local_chrome_path()+ };+ let Some(chrome) = chrome else {+ eprintln!("skipped: no Chrome or Chromium installed");+ return;+ };+ let profile = tmp.path().join("p1");+ starts_headless(&chrome, &profile, Duration::from_secs(60)).await.unwrap();+ remove_profile(&profile).await;+ assert!(!profile.exists() || cfg!(windows), "the scratch profile is removed");}#[test]diff --git a/src/sandbox/computer.rs b/src/sandbox/computer.rsindex 36317b55..fb0791f8 100644--- a/src/sandbox/computer.rs+++ b/src/sandbox/computer.rs@@ -210,7 +210,7 @@ pub fn vm_unavailable_reason(docker: bool, browser_url_configured: bool, platfor/// The local Chrome this process would launch, from the real environment. A Playwright Chromium,/// or one kwnt downloaded, counts only where its sandbox can start (see [`chrome_sandbox_blocked`]).pub fn local_chrome_path() -> Option<PathBuf> {- let home = std::env::var_os("HOME").map(PathBuf::from);+ let home = super::chrome_download::browser_home();let found = find_chrome(std::env::var(CHROME_PATH_ENV).ok().as_deref(),std::env::consts::OS,diff --git a/src/server/routes.rs b/src/server/routes.rsindex 032b447c..a1a3b3ef 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -5047,6 +5047,9 @@ pub async fn interact_sandbox(};// Returning an old screenshot as success hides failed input from the user.let screenshot = shot_res.map_err(|error| {+ if let crate::sandbox::browser::BrowserError::UnsupportedKey(why) = &error {+ return (StatusCode::BAD_REQUEST, Json(json!({ "error": why })));+ }tracing::warn!(team_id = %team_id, "Browser interaction failed: {}", error);(StatusCode::BAD_GATEWAY, Json(json!({"error": "Could not control the sandbox browser. Refresh the view or restart the browser and try again."diff --git a/tests/browser_keys_test.rs b/tests/browser_keys_test.rsnew file mode 100644index 00000000..ed89e189--- /dev/null+++ b/tests/browser_keys_test.rs@@ -0,0 +1,192 @@+//! A bot's key presses in kwnt's own browser, through a real headless Chrome (0.8.0 F-1): Enter+//! submits a form, and letters, Space, Backspace and Tab still do what they do on a keyboard.+//! Before the fix the bot's Enter went out as a bare `rawKeyDown` with only `key` and `code`:+//! keydown fired, the form never submitted. Skipped when no Chrome is installed.+#[path = "support/chrome_guard.rs"]+mod chrome_guard;+use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use chrome_guard::ChromeGuard;+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{models::Kwant, spaces::SpaceId, Database},+ router::LayaRouter,+ sandbox::{browser::BrowserController, computer},+ server::{create_router, routes::get_or_create_browser_controller, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::time::Duration;+use tempfile::{tempdir, TempDir};+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tower::ServiceExt;++/// A search form (two fields, no script that submits it) and the page it lands on.+const FORM: &str = "<!doctype html><title>form</title>\+ <form action=/done method=get><input id=q name=q><input id=other name=other><button>Go</button></form>\+ <script>window.keys=[];addEventListener('keydown',e=>keys.push(e.key),true)</script>";++async fn serve() -> String {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ tokio::spawn(async move {+ while let Ok((mut stream, _)) = listener.accept().await {+ tokio::spawn(async move {+ let mut buf = [0u8; 4096];+ let n = stream.read(&mut buf).await.unwrap_or(0);+ let head = String::from_utf8_lossy(&buf[..n]);+ let path = head.split_whitespace().nth(1).unwrap_or("/").to_string();+ let page = if path.starts_with("/done") {+ format!("<!doctype html><title>done</title><p>submitted {}</p>", path.replace('<', ""))+ } else {+ FORM.to_string()+ };+ let reply = format!(+ "HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{page}",+ page.len()+ );+ let _ = stream.write_all(reply.as_bytes()).await;+ });+ }+ });+ format!("http://127.0.0.1:{port}/form")+}++struct Env {+ app: Router,+ state: AppState,+ bot: Kwant,+ tmp: TempDir,+}++/// kwnt in Local mode, so the bot's browser is a real Chrome on this machine.+async fn setup() -> Env {+ let tmp = tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ db.set_setting(computer::SETTING_KEY, "local").await.unwrap();+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(tmp.path().join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();+ Env { app: create_router(state.clone()), state, bot, tmp }+}++/// The bot's own browser action route, as `browser_act` uses it.+async fn act(e: &Env, body: Value) -> (StatusCode, Value) {+ let req = Request::builder()+ .method("POST")+ .uri(format!("/api/sandbox/{}/act", e.bot.id))+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .unwrap();+ let resp = e.app.clone().oneshot(req).await.unwrap();+ let status = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++async fn press(e: &Env, key: &str) {+ let (status, v) = act(e, json!({"action": "key", "key": key})).await;+ assert_eq!(status, StatusCode::OK, "{key}: {v}");+ assert_eq!(v["result"], format!("pressed {key}"), "{key}: {v}");+}++async fn eval(ctrl: &BrowserController, js: &str) -> Value {+ let res = ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": js, "returnByValue": true})).await.unwrap();+ res["result"]["value"].clone()+}++/// The page's address once it stops being the form (or the form's, after `wait`).+async fn url_after(ctrl: &BrowserController, wait: Duration) -> String {+ let until = tokio::time::Instant::now() + wait;+ loop {+ let url = eval(ctrl, "location.href").await.as_str().unwrap_or_default().to_string();+ if url.contains("/done") || tokio::time::Instant::now() >= until {+ return url;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+}++#[tokio::test]+async fn a_bots_enter_submits_the_form_and_other_keys_still_type() {+ if computer::local_chrome_path().is_none() {+ eprintln!("skipped: no Chrome or Chromium installed");+ return;+ }+ let e = setup().await;+ let _chrome = ChromeGuard(e.tmp.path().join("local-chrome"));+ let url = serve().await;+ let ctrl = get_or_create_browser_controller(&e.state, &e.bot.id).await.expect("local Chrome session");++ // The old event, a bare rawKeyDown/keyUp with key and code: keydown fires, nothing submits.+ // This is what the bot sent before, so the test below can tell the two apart.+ ctrl.navigate(&url).await.unwrap();+ eval(&ctrl, "document.getElementById('q').focus(); q.value='old'").await;+ for kind in ["rawKeyDown", "keyUp"] {+ ctrl.send_cdp_command("Input.dispatchKeyEvent", json!({"type": kind, "key": "Enter", "code": "Enter"})).await.unwrap();+ }+ assert_eq!(eval(&ctrl, "keys.join()").await, "Enter", "the page saw the key");+ assert!(url_after(&ctrl, Duration::from_millis(1500)).await.ends_with("/form"), "the old event never submitted");++ // The bot's keys now: letters, Space and punctuation type, Backspace deletes+ ctrl.navigate(&url).await.unwrap();+ eval(&ctrl, "document.getElementById('q').focus()").await;+ for key in ["h", "i", "x", "Backspace", "Space", "A", "!", "/"] {+ press(&e, key).await;+ }+ assert_eq!(eval(&ctrl, "q.value").await, "hi A!/");+ assert_eq!(eval(&ctrl, "keys.join(' ')").await, "h i x Backspace A ! /");++ // Tab moves to the next field, and typing goes there+ press(&e, "Tab").await;+ assert_eq!(eval(&ctrl, "document.activeElement.id").await, "other");+ press(&e, "z").await;+ assert_eq!(eval(&ctrl, "other.value").await, "z");++ // Enter submits the form, with both fields+ press(&e, "Enter").await;+ let landed = url_after(&ctrl, Duration::from_secs(10)).await;+ assert!(landed.ends_with("/done?q=hi+A%21%2F&other=z"), "{landed}");+ assert_eq!(eval(&ctrl, "document.title").await, "done");++ // The default key of the act route is Enter too+ ctrl.navigate(&url).await.unwrap();+ eval(&ctrl, "document.getElementById('q').focus(); q.value='again'").await;+ let (status, v) = act(&e, json!({"action": "key"})).await;+ assert_eq!((status, &v["result"]), (StatusCode::OK, &json!("pressed Enter")), "{v}");+ assert!(url_after(&ctrl, Duration::from_secs(10)).await.ends_with("/done?q=again&other="));++ // A key kwnt can't describe is refused with a hint, and nothing reaches the page+ ctrl.navigate(&url).await.unwrap();+ let (status, v) = act(&e, json!({"action": "key", "key": "Control+a"})).await;+ assert_eq!(status, StatusCode::OK, "the act route answers the page: {v}");+ assert!(v.get("result").is_none(), "{v}");+ assert!(v["error"].as_str().unwrap_or_default().contains("To enter text, type it."), "{v}");+ assert_eq!(eval(&ctrl, "keys.length").await, 0);++ // The person's own v1 route: the same Enter, and a bad key is a 400 with the reason+ eval(&ctrl, "document.getElementById('q').focus(); q.value='person'").await;+ let person = |body: Value| {+ Request::builder()+ .method("POST")+ .uri(format!("/api/sandbox/{}/interact", e.bot.id))+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .unwrap()+ };+ let resp = e.app.clone().oneshot(person(json!({"action": "key", "key": "Unidentified"}))).await.unwrap();+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);+ let resp = e.app.clone().oneshot(person(json!({"action": "key", "key": "Enter", "code": "Enter"}))).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ assert!(url_after(&ctrl, Duration::from_secs(10)).await.ends_with("/done?q=person&other="));+}