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
Ask the person every time a CAPTCHA stops a bot (#295)
Oleksandr Ivanchenkof0213a8e464a
diff --git a/docs/live-activity.md b/docs/live-activity.mdindex 5c6cec31..f98dae69 100644--- a/docs/live-activity.md+++ b/docs/live-activity.md@@ -157,9 +157,44 @@ fragment.**Auto-raise:** when a `browser_open`, `browser_page` or `browser_act` tool lands on a CAPTCHA oranti-bot wall (`detect_bot_wall`), kwnt raises a `captcha` step itself (`source: "auto"`), waits-the same way, and after Done shows the agent the page again. Login pages are **not**+the same way, and after Done shows the agent the page again. This also happens when the tool call+itself fails (a click that stalls, is covered or times out because a check slid over the page):+kwnt reads the page and raises the step if it shows a wall. Login pages are **not**auto-detected. Agents ask for those with the tool.+kwnt also raises the step where no tool call can wait on it. It does not wait; the person's answer+(Done, Skip, solved or timed out) starts a **new turn** in the same chat:++- **The person's link.** When kwnt opens a link from the person's message before the turn starts+ and the page is a wall, the card is up before the bot runs. The bot's prompt says the person was+ asked and tells it to end its turn in one line.+- **The shell browser API.** A bot without kwnt's tools (agent tools off, or the tools didn't+ start) drives the browser with curl. `POST /navigate`, `GET /page` and `POST /act` on+ `/api/sandbox/:id/` raise the step in the chat of the turn running on that browser. The answer+ gets `"human_step": "asked"` and a `notice` telling the bot to end its turn. While the step is+ open, `navigate` and `act` answer **409** ("The browser is waiting on the person …"). With no+ turn on the browser (someone curling it by hand), nobody is asked and the answer keeps the plain+ `blocked` notice.++Every bot's prompt says that a CAPTCHA met by the engine's own web fetch, search or built-in+browser goes to the person too. The bot opens that address in kwnt's browser, where the card comes+up, and never solves, bypasses or routes around the check. A bot with no browser at all is told to+name the page to the person.++**What counts as a wall** (`detect_bot_wall`, plus the in-page probe):++- Google's "unusual traffic" page.+- Cloudflare's "Just a moment", "Attention Required!" and "Checking your browser" pages, including+ Turnstile drawn in a closed shadow root.+- Pages that ask you to verify, confirm or prove you are human or not a robot (curly apostrophes+ included). This covers Amazon's "Enter the characters you see", PerimeterX "Press & Hold",+ DataDome, DuckDuckGo's "bots use DuckDuckGo too" and "solve the CAPTCHA" forms.+- An address whose host or path names a CAPTCHA.+- Widgets from reCAPTCHA, hCaptcha, Turnstile, Arkose, DataDome, GeeTest, PerimeterX and TikTok.++Phrases and addresses count only on a short page (at most 3000 characters of text) or in the+title. An article or a search about CAPTCHAs is not a wall.+While a step is open in a bot browser:- the bot's browser tools are refused ("The browser is waiting on the person …")diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex 7f51c1fb..e0e0f150 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -435,7 +435,8 @@ impl TurnInput {});let control_rules = "A 409 / \"taken control\" answer means the user is using the browser: stop browser actions and wait for the user to hand it back. Never bypass the control API or connect to CDP directly.\n\Report browser errors honestly. Never claim a page opened unless navigation succeeded, and only describe content that appears in the returned page text. If a response has \"blocked\": true (CAPTCHA / bot check), follow its \"notice\" instead of claiming results.\n\- On a CAPTCHA, stop and wait for the person to solve it: never try to solve, bypass or click through it yourself. Prefer sites you are already signed in to and official APIs over scraping pages that challenge bots.";+ On a CAPTCHA, stop and wait for the person to solve it: never try to solve, bypass or click through it yourself. Prefer sites you are already signed in to and official APIs over scraping pages that challenge bots.\n\+ CAPTCHAs anywhere else go to the person too: if your own web fetch, web search or built-in browser meets a CAPTCHA, an \"unusual traffic\" page or another human check, don't give up on the site, don't only describe the block and don't switch sites to get around it. Open that same address in this bot browser: when the check shows there, the person gets a \"Human check needed\" card to solve it and you continue after they do.";let browser_block = match browser {BrowserAccess::Tools => format!("\n\n[Bot Browser]\n\@@ -470,7 +471,8 @@ impl TurnInput {),BrowserAccess::Unavailable => "\n\n[Bot Browser]\n\You have no way to use the browser in the user's side panel this turn. If the user asks you to browse, say so plainly and \- suggest they open the page themselves (Take Control in the panel); never claim you opened or read a page."+ suggest they open the page themselves (Take Control in the panel); never claim you opened or read a page. \+ If anything you read was stopped by a CAPTCHA or another human check, never try to solve or bypass it: tell the person which page asked for the check, so they can solve it themselves.".to_string(),};let sandbox_rules = format!(@@ -877,6 +879,23 @@ pub(crate) mod tests {}}+ /// A CAPTCHA the engine's own web tools meet is the person's to solve too, for every engine:+ /// a bot with kwnt's browser opens the address there (which raises the card), one without it+ /// tells the person; none is told to solve, bypass or route around it.+ #[test]+ fn every_turn_hands_a_captcha_from_the_engines_own_web_tools_to_the_person() {+ for access in [BrowserAccess::Tools, BrowserAccess::Shell] {+ let prompt = input().format_system_prompt_with(access);+ assert!(prompt.contains("your own web fetch, web search or built-in browser meets a CAPTCHA"), "{access:?}");+ assert!(prompt.contains("Open that same address in this bot browser"), "{access:?}");+ assert!(prompt.contains("\"Human check needed\" card"), "{access:?}");+ assert!(prompt.contains("don't switch sites to get around it"), "{access:?}");+ assert!(prompt.contains("never try to solve, bypass or click through it yourself"), "{access:?}");+ }+ let prompt = input().format_system_prompt_with(BrowserAccess::Unavailable);+ assert!(prompt.contains("never try to solve or bypass it: tell the person which page asked for the check"), "{prompt}");+ }+/// Plan §A.4: one line asks for structure the Smart Results selectors can read, once per turn.#[test]fn every_turn_asks_for_structure_once() {diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rsindex 3d039855..ed856247 100644--- a/src/sandbox/browser.rs+++ b/src/sandbox/browser.rs@@ -470,19 +470,80 @@ pub fn web_address(target: &str) -> Result<std::borrow::Cow<'_, str>, BrowserErr})}+/// Longest page text a wall phrase counts on: a check page is short (Cloudflare, Amazon,+/// PerimeterX and Google's "sorry" page are all well under this), while an article or a help page+/// that only quotes "verify you are human" is not a wall.+pub const WALL_TEXT_MAX_CHARS: usize = 3000;++/// Phrases a human-check page shows (lower case, straight apostrophes). Each one names the check+/// itself, never a passing mention: "press and hold" alone is a power button, "captcha" alone is+/// an article.+const WALL_PHRASES: &[&str] = &[+ "i'm not a robot",+ "i am not a robot",+ "are you a robot",+ "make sure you're not a robot",+ "confirm you're not a robot",+ "verify you're not a robot",+ "prove you're not a robot",+ "confirm you are not a robot",+ "confirm that you are not a robot",+ "verify you are not a robot",+ "verify that you are not a robot",+ "verify you are human",+ "verify you are a human",+ "verify that you are human",+ "verify that you are a human",+ "verify you're human",+ "verifying you are human",+ "confirm you are human",+ "confirm you are a human",+ "confirm that you are human",+ "prove you're human",+ "prove you are human",+ "complete the captcha",+ "solve the captcha",+ "complete the security check",+ "complete the following challenge",+ "enter the characters you see",+ "type the characters you see",+ "press & hold to confirm",+ "press and hold to confirm",+ "performing security verification",+ "bots use duckduckgo too",+];++/// Whether a page address is a CAPTCHA page by itself: a host or a path segment about one+/// (`geo.captcha-delivery.com`, `/errors/validateCaptcha`, `/showcaptcha`), not a query that only+/// mentions it.+fn captcha_url(url: &str) -> bool {+ let Ok(u) = url::Url::parse(url) else { return false };+ u.host_str().is_some_and(|h| h.contains("captcha")) || u.path().to_lowercase().split('/').any(|seg| seg.contains("captcha"))+}+/// Recognises CAPTCHA / anti-bot interstitials that replace the requested content.+///+/// Phrases count only on a short page (or in the title): a check page carries little else. A+/// widget on an otherwise normal page is the job of [`CAPTCHA_PROBE_JS`].pub fn detect_bot_wall(url: &str, title: &str, text: &str) -> Option<&'static str> {- let url = url.to_lowercase();- let title = title.to_lowercase();- let text = text.to_lowercase();- if url.contains("google.") && url.contains("/sorry/") || text.contains("unusual traffic from your computer network") {+ // Curly apostrophes ("you’re") read as straight ones+ let norm = |s: &str| s.to_lowercase().replace(['\u{2019}', '\u{2018}'], "'");+ let title = norm(title);+ let text = norm(text);+ let lower_url = url.to_lowercase();+ let short = text.chars().count() <= WALL_TEXT_MAX_CHARS;+ if lower_url.contains("google.") && lower_url.contains("/sorry/") || text.contains("unusual traffic from your computer network") {return Some("Google \"unusual traffic\" CAPTCHA");}- if title.starts_with("just a moment") || text.contains("checking your browser") || text.contains("checking if the site connection is secure") {+ if title.starts_with("just a moment")+ || title.starts_with("attention required! | cloudflare")+ || title.starts_with("checking your browser")+ || title.starts_with("checking if the site connection is secure")+ || short && (text.contains("checking your browser") || text.contains("checking if the site connection is secure"))+ {return Some("Cloudflare bot check");}- let captcha_markers = ["i'm not a robot", "i am not a robot", "are you a robot", "verify you are human", "verifying you are human", "prove you're human", "complete the captcha"];- if captcha_markers.iter().any(|m| text.contains(m) || title.contains(m)) || url.contains("captcha") {+ if WALL_PHRASES.iter().any(|m| title.contains(m) || short && text.contains(m)) || short && captcha_url(url) {return Some("CAPTCHA / human verification");}None@@ -638,6 +699,19 @@ pub const CAPTCHA_PROBE_JS: &str = r##"(function () {}}if (!found && anchor && wallPage()) found = box('recaptcha', anchor);+ // Turnstile now draws its iframe inside a closed shadow root, so on Cloudflare's own check page+ // (or a bare Turnstile form) only its host box is visible. On a page with fields to fill, a+ // Turnstile box is part of a form the person submits, not a wall.+ if (!found && wallPage()) {+ // the widget's own box first, then the stage Cloudflare wraps it in+ var TS = ['.cf-turnstile, #cf-turnstile', '#turnstile-wrapper, #challenge-stage'];+ for (var q = 0; q < TS.length && !found; q++) {+ for (var rt = 0; rt < roots.length && !found; rt++) {+ var ts = roots[rt].querySelectorAll(TS[q]);+ for (var t = 0; t < ts.length && !found; t++) found = box('turnstile', ts[t]);+ }+ }+ }for (var ri2 = 0; ri2 < roots.length && !found; ri2++) {for (var s = 0; s < SELECTORS.length && !found; s++) {var els = roots[ri2].querySelectorAll(SELECTORS[s][1]);diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 62af8146..98fb07be 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -757,23 +757,39 @@ async fn call_browser_tool(state: &AppState, scope: &SelfScope, target: &str, nactrl.site_guard.set_driver(&scope.kwant_id);}let (text, is_error) = run_browser_tool(state, target, &reader, name, args).await;- // A CAPTCHA wall: ask the person to solve it, then show the agent the page they left- if !is_error {- if let Ok(page) = serde_json::from_str::<Value>(&text) {- if page["blocked"] == json!(true) {- if let Some(note) = super::human_steps::raise_for_bot_wall(state, scope, &page).await {- if super::human_steps::browser_is_held(state, target).await {- return (note, false);- }- let (after, _) = run_browser_tool(state, target, &reader, BROWSER_PAGE, &json!({"full": true})).await;- return (format!("{note}\n\nThe page now:\n{after}"), false);- }+ // A CAPTCHA wall: ask the person to solve it, then show the agent the page they left. Also+ // when the call itself failed: a click that stalled, was covered or timed out because a+ // check slid over the page is still a check for the person+ let page = serde_json::from_str::<Value>(&text).ok().filter(Value::is_object);+ let blocked = match &page {+ Some(page) if page["blocked"] == json!(true) => Some(page.clone()),+ _ if is_error && wall_check_helps(&text, page.as_ref()) => {+ let (now, failed) = run_browser_tool(state, target, "", BROWSER_PAGE, &json!({"full": true})).await;+ serde_json::from_str::<Value>(&now).ok().filter(|p| !failed && p["blocked"] == json!(true))+ }+ _ => None,+ };+ if let Some(page) = blocked {+ if let Some(note) = super::human_steps::raise_for_bot_wall(state, scope, &page).await {+ if super::human_steps::browser_is_held(state, target).await {+ return (note, false);}+ let (after, _) = run_browser_tool(state, target, &reader, BROWSER_PAGE, &json!({"full": true})).await;+ return (format!("{note}\n\nThe page now:\n{after}"), false);}}(text, is_error)}+/// Whether a failed browser call is worth a look for a CAPTCHA: not when the person holds the+/// browser, the call was malformed, or the answer already carries the page (and it isn't blocked).+fn wall_check_helps(text: &str, page: Option<&Value>) -> bool {+ if page.is_some_and(|p| p.get("url").is_some()) {+ return false;+ }+ !(text.starts_with("The user has taken control") || text.ends_with(" is required") || text.starts_with("action is required"))+}+/// `reader` names who reads (empty: nobody known), for `browser_page` to answer "unchanged" when/// that reader's last page (from any browser tool) still reads the same.async fn run_browser_tool(state: &AppState, target: &str, reader: &str, name: &str, args: &Value) -> (String, bool) {diff --git a/src/server/human_steps.rs b/src/server/human_steps.rsindex b6e3a56d..2a59e6f2 100644--- a/src/server/human_steps.rs+++ b/src/server/human_steps.rs@@ -28,7 +28,7 @@ use serde::Deserialize;use serde_json::{json, Value};use std::collections::HashMap;use std::sync::atomic::{AtomicU64, Ordering};-use std::sync::Mutex;+use std::sync::{Arc, Mutex};use std::time::Duration;use tokio::sync::oneshot;@@ -74,6 +74,11 @@ pub struct HumanStepHub {/// Tests only: CAPTCHA time limit and probe interval in ms (0 = setting / default).captcha_timeout_ms: AtomicU64,probe_ms: AtomicU64,+ /// The turn running on each bot browser (by sandbox target), so a CAPTCHA met through the+ /// shell browser API, which carries no turn of its own, is still asked of the person in that+ /// turn's chat.+ turns: Mutex<HashMap<String, (u64, SelfScope)>>,+ next_turn: AtomicU64,}impl Default for HumanStepHub {@@ -84,6 +89,8 @@ impl Default for HumanStepHub {wait_ms: AtomicU64::new((crate::mcp::APPROVAL_TIMEOUT_SECS - 10) * 1000),captcha_timeout_ms: AtomicU64::new(0),probe_ms: AtomicU64::new(0),+ turns: Mutex::default(),+ next_turn: AtomicU64::new(1),}}}@@ -130,6 +137,36 @@ impl HumanStepHub {pub fn is_waiting(&self, id: &str) -> bool {self.waiters.lock().unwrap_or_else(|e| e.into_inner()).contains_key(id)}++ /// Records the turn now running on a bot browser until the guard drops (the turn ends). The+ /// newest turn on a browser wins; an older one ending leaves it be.+ pub fn track_turn(self: &Arc<Self>, target: &str, scope: SelfScope) -> TurnOnBrowser {+ let token = self.next_turn.fetch_add(1, Ordering::Relaxed);+ self.turns.lock().unwrap_or_else(|e| e.into_inner()).insert(target.to_string(), (token, scope));+ TurnOnBrowser { hub: self.clone(), target: target.to_string(), token }+ }++ /// The turn running on this bot browser, if one is (and can ask in a chat).+ pub fn turn_on(&self, target: &str) -> Option<SelfScope> {+ let turns = self.turns.lock().unwrap_or_else(|e| e.into_inner());+ turns.get(target).map(|(_, s)| s.clone()).filter(|s| s.origin.is_some() && !s.cancel.as_ref().is_some_and(|c| c.is_cancelled()))+ }+}++/// Keeps a turn recorded on its bot browser while it runs ([`HumanStepHub::track_turn`]).+pub struct TurnOnBrowser {+ hub: Arc<HumanStepHub>,+ target: String,+ token: u64,+}++impl Drop for TurnOnBrowser {+ fn drop(&mut self) {+ let mut turns = self.hub.turns.lock().unwrap_or_else(|e| e.into_inner());+ if turns.get(&self.target).is_some_and(|(t, _)| *t == self.token) {+ turns.remove(&self.target);+ }+ }}/// Removes the waiter when the tool call ends any way (also when the CLI hangs up).@@ -331,9 +368,32 @@ pub async fn raise(target: Option<&CaptchaHit>,source: &str,) -> Result<Option<Outcome>, String> {- let (Some(origin), Some(cancel)) = (&scope.origin, &scope.cancel) else {+ raise_step(state, scope, kind, reason, url, target, source, true).await+}++/// [`raise`]; `wait: false` only asks (card, notification, held browser, CAPTCHA watcher) and+/// returns at once with `Ok(None)`: no turn waits, so the answer starts a new turn in the chat+/// ([`resume`]). For a CAPTCHA kwnt meets where nothing can wait on it (before the bot's turn+/// starts, or through the shell browser API).+#[allow(clippy::too_many_arguments)]+async fn raise_step(+ state: &AppState,+ scope: &SelfScope,+ kind: &str,+ reason: &str,+ url: Option<&str>,+ target: Option<&CaptchaHit>,+ source: &str,+ wait_for_it: bool,+) -> Result<Option<Outcome>, String> {+ let Some(origin) = &scope.origin else {return Err("You can only ask the person for a step from a chat.".into());};+ let cancel = match (&scope.cancel, wait_for_it) {+ (Some(c), _) => c.clone(),+ (None, false) => tokio_util::sync::CancellationToken::new(),+ (None, true) => return Err("You can only ask the person for a step from a chat.".into()),+ };let place = HumanStepPlace {kwant_id: scope.kwant_id.clone(),channel_id: origin.channel_id.clone(),@@ -353,7 +413,9 @@ pub async fn raise(let created = state.db.create_human_step_with_card(&place, kind, reason, url, target_json.as_deref(), source, |s| {- waiter = Some((s.id.clone(), hub.register(&s.id)));+ if wait_for_it {+ waiter = Some((s.id.clone(), hub.register(&s.id)));+ }let mut text = format!("{}: {}", kind_label(&s.kind), s.reason);if let Some(u) = &s.url {text.push_str(&format!("\n{u}"));@@ -387,13 +449,18 @@ pub async fn raise(tracing::info!(human_step_id = %step.id, kwant_id = %scope.kwant_id, "sign-in already asked for in another turn");return Ok(Some(Outcome::AlreadyAsked));}+ if !wait_for_it && !is_new {+ // Already asked (the card is up): nothing new to show+ return Ok(None);+ }// The turn asked again for a step it already has open (or one no turn waits on any more):// wait on that one- let mut rx = match waiter {- Some((_, rx)) => rx,- None => hub.register(&step.id),+ let rx = match waiter {+ Some((_, rx)) => Some(rx),+ None if wait_for_it => Some(hub.register(&step.id)),+ None => None,};- let _guard = WaiterGuard { hub, id: step.id.clone() };+ let _guard = rx.is_some().then(|| WaiterGuard { hub, id: step.id.clone() });let mut wait = hub.wait();let mut captcha_deadline = None;if step.kind == "captcha" {@@ -410,7 +477,7 @@ pub async fn raise(hold_browser(state, step.sandbox_target.as_deref()).await;if step.kind == "captcha" && step.sandbox_target.is_some() {// a CAPTCHA kwnt saw is on the page already; one the bot named must show up first- tokio::spawn(watch_captcha(state.clone(), step.id.clone(), source == "auto"));+ spawn_watch_captcha(state.clone(), step.id.clone(), source == "auto");}if let Some(card) = card {if let Some(t) = &step.thread_id {@@ -419,7 +486,8 @@ pub async fn raise(let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&card).unwrap_or(Value::Null) });}changed(state, &step).await;- if let Some(turn) = step.turn_id.as_deref().and_then(super::activity::TurnActivity::find) {+ // A turn that doesn't wait on the step isn't shown as waiting+ if let Some(turn) = step.turn_id.as_deref().and_then(super::activity::TurnActivity::find).filter(|_| wait_for_it) {let title = format!("Waiting for you: {}", step.reason);turn.wait("human_step", &step.id, &title, Some(TOOL));}@@ -435,9 +503,10 @@ pub async fn raise(},).await;- tracing::info!(human_step_id = %step.id, kwant_id = %scope.kwant_id, source, "agent asked the person for a browser step");+ tracing::info!(human_step_id = %step.id, kwant_id = %scope.kwant_id, source, wait_for_it, "agent asked the person for a browser step");}+ let Some(mut rx) = rx else { return Ok(None) };tokio::select! {r = &mut rx => Ok(r.ok()),_ = cancel.cancelled() => {@@ -445,18 +514,27 @@ pub async fn raise(Err("The user stopped this turn. End it now.".into())}_ = tokio::time::sleep(wait) => {- hub.take(&step.id);- // An answer that arrived just as the wait ran out still counts- if let Ok(outcome) = rx.try_recv() {- return Ok(Some(outcome));- }// A CAPTCHA past its time limit has timed out, whoever notices first: the watcher can// lag behind this wait on a busy machine, and the bot would be told to wait for a step// that is already over (as CI saw once on c185fc9)if captcha_deadline.is_some_and(|d| chrono::Utc::now() >= d) && close(state, &step.id, Outcome::TimedOut.status()).await.is_some() {+ hub.take(&step.id);tracing::info!(human_step_id = %step.id, "CAPTCHA step timed out at the end of the turn's wait");return Ok(Some(Outcome::TimedOut));}+ // Closed by someone else just now (the watcher, or the person): the answer is on its+ // way to this turn's waiter, which is still registered, so it reaches this turn+ // instead of starting a new one+ if state.db.get_human_step(&step.id).await.ok().flatten().is_some_and(|s| s.status != "open") {+ if let Ok(Ok(outcome)) = tokio::time::timeout(Duration::from_secs(5), &mut rx).await {+ return Ok(Some(outcome));+ }+ }+ hub.take(&step.id);+ // An answer that arrived just as the wait ran out still counts+ if let Ok(outcome) = rx.try_recv() {+ return Ok(Some(outcome));+ }Ok(None)}}@@ -467,6 +545,38 @@ pub async fn raise(pub async fn raise_for_bot_wall(state: &AppState, scope: &SelfScope, page: &Value) -> Option<String> {scope.origin.as_ref()?;scope.cancel.as_ref()?;+ let (reason, url, target) = wall_request(page);+ Some(match raise(state, scope, "captcha", &reason, url.as_deref(), target.as_ref(), "auto").await {+ Ok(outcome) => format!("A CAPTCHA blocked the page, so the person was asked to solve it. {}", outcome_text(outcome, true)),+ Err(e) => e,+ })+}++/// What the bot hears after kwnt asked the person for a CAPTCHA it can't wait on.+pub const ASKED_NOTE: &str = "A CAPTCHA / human check blocked the page, so kwnt showed the person a \"Human check needed\" card \+ and handed them the browser. Don't try to solve, bypass or click through it, don't use the browser until it is solved, and don't \+ switch to another site to get around it. End your turn now with one short line saying you're waiting for the person to solve \+ the check. You get a new turn when it is solved, or if nobody solves it in time.";++/// [`raise_for_bot_wall`] for a CAPTCHA no tool call can wait on: kwnt opened the page before+/// the bot's turn, or the bot met it through the shell browser API. The person gets the card and+/// the notification at once; the answer starts a new turn. `None` when there's no chat to ask in+/// (the note for the bot otherwise).+pub async fn ask_for_bot_wall(state: &AppState, scope: &SelfScope, page: &Value) -> Option<String> {+ scope.origin.as_ref()?;+ let (reason, url, target) = wall_request(page);+ match raise_step(state, scope, "captcha", &reason, url.as_deref(), target.as_ref(), "auto", false).await {+ Ok(Some(outcome)) => Some(format!("A CAPTCHA blocked the page, so the person was asked to solve it. {}", outcome_text(Some(outcome), true))),+ Ok(None) => Some(ASKED_NOTE.to_string()),+ Err(e) => {+ tracing::warn!(kwant_id = %scope.kwant_id, error = %e, "couldn't ask the person for a CAPTCHA");+ None+ }+ }+}++/// The step to ask for on a blocked page: reason, address and the widget's box.+fn wall_request(page: &Value) -> (String, Option<String>, Option<CaptchaHit>) {let target = CaptchaHit::parse(&page["captcha"]).and_then(CaptchaHit::on_screen);let url = page["url"].as_str().and_then(crate::db::human_steps::clean_url);let host = url.as_deref().and_then(|u| url::Url::parse(u).ok()).and_then(|u| u.host_str().map(str::to_string));@@ -474,10 +584,7 @@ pub async fn raise_for_bot_wall(state: &AppState, scope: &SelfScope, page: &ValuSome(h) => format!("{h} is showing a CAPTCHA / human check to the bot browser. Please solve it."),None => "The page is showing a CAPTCHA / human check to the bot browser. Please solve it.".into(),};- Some(match raise(state, scope, "captcha", &reason, url.as_deref(), target.as_ref(), "auto").await {- Ok(outcome) => format!("A CAPTCHA blocked the page, so the person was asked to solve it. {}", outcome_text(outcome, true)),- Err(e) => e,- })+ (reason, url, target)}/// Whether the page still shows a human check: a CAPTCHA widget, or a bot-wall page (Cloudflare's@@ -493,6 +600,12 @@ async fn wall_on_page(ctrl: &BrowserController) -> Option<(bool, Option<CaptchaH/// Watches an open CAPTCHA step until it closes: keeps its box current, closes it as/// `resolved_auto` once the check is gone, or as `timed_out` at the time limit, and tells the bot.+/// Spawns [`watch_captcha`] from a plain fn, so `raise_step`'s future type doesn't depend on the+/// watcher's (watcher → resume → a new turn → raise_step would be a type cycle).+fn spawn_watch_captcha(state: AppState, id: String, seen: bool) {+ tokio::spawn(watch_captcha(state, id, seen));+}+async fn watch_captcha(state: AppState, id: String, mut seen: bool) {let limit = captcha_timeout(&state).await;let started = tokio::time::Instant::now();diff --git a/src/server/mod.rs b/src/server/mod.rsindex 6e51f35a..2b86558e 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -257,11 +257,11 @@ pub fn create_router(state: AppState) -> Router {.route("/api/sandbox/:team_id/status", get(routes::get_sandbox_status)).route("/api/sandbox/:team_id/screenshot", get(routes::get_browser_screenshot)).route("/api/sandbox/:team_id/restart", post(routes::restart_sandbox))- .route("/api/sandbox/:team_id/navigate", post(routes::navigate_sandbox))+ .route("/api/sandbox/:team_id/navigate", post(routes::navigate_sandbox_api)).route("/api/sandbox/:team_id/interact", post(routes::interact_sandbox)).route("/api/sandbox/:team_id/stream", get(browser_stream::upgrade))- .route("/api/sandbox/:team_id/page", get(routes::get_sandbox_page))- .route("/api/sandbox/:team_id/act", post(routes::act_sandbox))+ .route("/api/sandbox/:team_id/page", get(routes::get_sandbox_page_api))+ .route("/api/sandbox/:team_id/act", post(routes::act_sandbox_api)).route("/api/sandbox/:team_id/cite", post(routes::cite_sandbox)).route("/api/sandbox/:team_id/passwords", get(passwords::list).post(passwords::save)).route("/api/sandbox/:team_id/passwords/pending", post(passwords::save_pending).delete(passwords::discard_pending))diff --git a/src/server/routes.rs b/src/server/routes.rsindex ad2557dd..d887c757 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -2270,6 +2270,28 @@ async fn run_kwant_turn_inner(.or_else(|| kwant_id.clone()).unwrap_or_else(|| target_kwant.id.clone());+ // This turn, as the person's chat sees it: what a CAPTCHA step is asked in, whether kwnt+ // meets it opening the person's link below, through the browser tools or the shell API+ let turn_scope = super::continuity::SelfScope {+ kwant_id: target_kwant.id.clone(),+ kwant_name: target_kwant.name.clone(),+ origin: Some(super::continuity::TurnOrigin {+ channel_id: channel_id.clone(),+ direct_kwant_id: kwant_id.clone(),+ thread_id: scope.thread_id.clone(),+ team_id: scope.team_context.as_ref().map(|t| t.id.clone()),+ member_ids: scope.teammates.iter().map(|k| k.id.clone()).collect(),+ depth: scope.delegation_depth,+ message_id: opts.routing.as_ref().and_then(|r| r["message_id"].as_str()).map(str::to_string),+ }),+ cancel: Some(cancel_token.clone()),+ turn_id: Some(tag.turn_id.clone()),+ workspace: workspace_dir.clone(),+ sandbox_target: Some(sandbox_target.clone()),+ };+ // A replay works in its own scratch browser and asks nobody+ let _turn_on_browser = opts.rehearse.is_none().then(|| state.human_steps.track_turn(&sandbox_target, turn_scope.clone()));+let active_ctrl = state.browser_controllers.lock().await.get(&sandbox_target).cloned();// The user may have browsed in the live viewer since the last turn; read the real locationlet active_browser_url = if let Some(ref ctrl) = active_ctrl {@@ -2314,7 +2336,17 @@ async fn run_kwant_turn_inner(}let captcha = ctrl.probe_captcha().await.ok().flatten();let wall = crate::sandbox::detect_bot_wall(&nav.url, &nav.title, &page_text).or(captcha.as_ref().map(|c| c.label()));- final_prompt = if let Some(kind) = wall {+ // The person is asked at once; the bot hears it was, instead of a block to report+ let asked = match wall {+ Some(_) => super::human_steps::ask_for_bot_wall(state, &turn_scope, &json!({"url": nav.url, "captcha": captcha})).await,+ None => None,+ };+ final_prompt = if let (Some(kind), Some(note)) = (wall, asked) {+ format!(+ "{}\n\n[Sandbox Browser State: Tried to open {} in the right-panel bot browser, but it showed a {} instead of the page. {}]",+ prompt, target_url, kind, note+ )+ } else if let Some(kind) = wall {format!("{}\n\n[Sandbox Browser State: Tried to open {} in the right-panel bot browser. {}]",prompt, target_url, bot_wall_notice(kind, &nav.url)@@ -2381,25 +2413,7 @@ async fn run_kwant_turn_inner(}let attempts: Vec<Option<LlmProfile>> = std::mem::take(&mut global.attempts);// The agents' own continuity tools, for engines that can call MCP tools- let self_scope = (engine.is_some() && super::continuity::agent_tools_enabled(state).await).then(|| {- super::continuity::SelfScope {- kwant_id: target_kwant.id.clone(),- kwant_name: target_kwant.name.clone(),- origin: Some(super::continuity::TurnOrigin {- channel_id: channel_id.clone(),- direct_kwant_id: kwant_id.clone(),- thread_id: scope.thread_id.clone(),- team_id: scope.team_context.as_ref().map(|t| t.id.clone()),- member_ids: scope.teammates.iter().map(|k| k.id.clone()).collect(),- depth: scope.delegation_depth,- message_id: opts.routing.as_ref().and_then(|r| r["message_id"].as_str()).map(str::to_string),- }),- cancel: Some(cancel_token.clone()),- turn_id: Some(tag.turn_id.clone()),- workspace: workspace_dir.clone(),- sandbox_target: Some(sandbox_target.clone()),- }- });+ let self_scope = (engine.is_some() && super::continuity::agent_tools_enabled(state).await).then(|| turn_scope.clone());let browser_sign_in = self_scope.as_ref().is_some_and(super::continuity::offers_browser_sign_in);let card_opts = super::mcp_runtime::TurnApprovalOpts {routed: Some((target_model.clone(), effort_level.clone())),@@ -4829,13 +4843,98 @@ async fn page_state_from(pub fn bot_wall_notice(kind: &str, url: &str) -> String {format!("BLOCKED: the site answered with a {} ({}) instead of the requested content. \- Do NOT describe results you have not seen. Tell the user plainly that the site blocked the automated browser, then either \- retry once on another engine via the browser API and say you switched (web: https://www.bing.com/search?q=<query>, images: https://www.bing.com/images/search?q=<query>), \- or offer that they solve the check themselves in the live browser panel.",+ Do NOT describe results you have not seen, and never try to solve, bypass or click through the check yourself. \+ It is the person's to solve: if you have request_human_step, call it (kind captcha, this url) and wait; otherwise tell the person \+ plainly that a human check is waiting in the browser panel and ask them to solve it there, then end your turn. \+ Only if the person declines or nobody solves it in time, use another source and say you switched.",kind, url)}+/// The browser API's own routes (`/api/sandbox/:id/navigate|page|act`), for bots that drive the+/// browser with curl: like the handlers, and a page that shows a CAPTCHA (or a failed action+/// over one) asks the person to solve it in the chat of the turn running on that browser, with a+/// "Human check needed" card. Nothing waits on it there, so the bot is told to end its turn; the+/// answer starts a new one. The `browser_*` tools call the handlers directly and ask themselves.+pub async fn navigate_sandbox_api(+ State(state): State<AppState>,+ Path(team_id): Path<String>,+ payload: Json<NavigatePayload>,+) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {+ refuse_while_held(&state, &team_id).await?;+ let result = navigate_sandbox(State(state.clone()), Path(team_id.clone()), payload).await;+ ask_on_wall(&state, &team_id, result).await+}++pub async fn get_sandbox_page_api(+ State(state): State<AppState>,+ Path(team_id): Path<String>,+ query: Query<PageQuery>,+) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {+ let result = get_sandbox_page(State(state.clone()), Path(team_id.clone()), query).await;+ // A page held for the person's step was already asked about+ if super::human_steps::browser_is_held(&state, &team_id).await {+ return result;+ }+ ask_on_wall(&state, &team_id, result).await+}++pub async fn act_sandbox_api(+ State(state): State<AppState>,+ Path(team_id): Path<String>,+ payload: Json<InteractPayload>,+) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {+ refuse_while_held(&state, &team_id).await?;+ let result = act_sandbox(State(state.clone()), Path(team_id.clone()), payload).await;+ ask_on_wall(&state, &team_id, result).await+}++/// A bot action on a browser the person was handed for a step waits until they finish it.+async fn refuse_while_held(state: &AppState, team_id: &str) -> Result<(), (StatusCode, Json<serde_json::Value>)> {+ if super::human_steps::browser_is_held(state, team_id).await {+ return Err((+ StatusCode::CONFLICT,+ Json(json!({"error": "The browser is waiting on the person (a sign-in or CAPTCHA step). Stop browser actions and end your turn; you get a new one when they finish."})),+ ));+ }+ Ok(())+}++/// Asks the person when the answer shows a CAPTCHA, or when a failed request left one on the+/// page, and tells the bot so in place of the plain notice.+async fn ask_on_wall(+ state: &AppState,+ team_id: &str,+ result: Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)>,+) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {+ let Some(turn) = state.human_steps.turn_on(team_id) else { return result };+ match result {+ Ok(Json(mut page)) => {+ if page["blocked"] == json!(true) {+ if let Some(note) = super::human_steps::ask_for_bot_wall(state, &turn, &page).await {+ page["notice"] = json!(note);+ page["human_step"] = json!("asked");+ }+ }+ Ok(Json(page))+ }+ Err((status, Json(mut body))) if status != StatusCode::CONFLICT && status != StatusCode::BAD_REQUEST => {+ let page = match state.browser_controllers.lock().await.get(team_id).cloned() {+ Some(ctrl) => Some(sandbox_page_state(&ctrl).await),+ None => None,+ };+ if let Some(page) = page.filter(|p| p["blocked"] == json!(true)) {+ if let Some(note) = super::human_steps::ask_for_bot_wall(state, &turn, &page).await {+ body["notice"] = json!(note);+ body["human_step"] = json!("asked");+ }+ }+ Err((status, Json(body)))+ }+ other => other,+ }+}+async fn broadcast_sandbox_screenshot(state: &AppState, team_id: &str, ctrl: &crate::sandbox::BrowserController) {if let Some(b64) = ctrl.last_screenshot.lock().await.clone() {let url = ctrl.current_url.lock().await.clone().unwrap_or_default();diff --git a/tests/browser_test.rs b/tests/browser_test.rsindex eff27408..bdf03a5b 100644--- a/tests/browser_test.rs+++ b/tests/browser_test.rs@@ -718,6 +718,48 @@ fn detects_captcha_and_bot_check_pages() {assert!(detect_bot_wall("https://www.bing.com/images/search?q=cat", "cat - Bing images", "Cat pictures, kittens").is_none());}+/// The walls a bot meets in the wild, each with the text it actually shows, and pages that only+/// talk about CAPTCHAs, which must not raise a check.+#[test]+fn detects_the_common_walls_and_not_pages_about_them() {+ use kwnt::sandbox::detect_bot_wall;+ let walls = [+ ("Cloudflare Turnstile", "https://site.example/", "Just a moment...", "site.example Verify you are human by completing the action below. site.example needs to review the security of your connection before proceeding."),+ ("Cloudflare new wording", "https://site.example/", "site.example", "Performing security verification. This website uses a security service to protect against malicious bots."),+ ("Cloudflare block page", "https://site.example/", "Attention Required! | Cloudflare", "Please enable cookies. One more step. Please complete the security check to access site.example"),+ ("Cloudflare curly apostrophe", "https://site.example/", "site.example", "Let\u{2019}s confirm you are human. Complete the security check before continuing."),+ ("DataDome", "https://geo.captcha-delivery.com/captcha/?initialCid=abc", "", ""),+ ("DataDome text", "https://shop.example/p/1", "shop.example", "We want to make sure it is actually you we are dealing with and not a robot. Please slide to the right. Verify you are a human."),+ ("PerimeterX", "https://store.example/", "Access to this page has been denied", "Press & Hold to confirm you are a human (and not a bot). Reference ID 1234"),+ ("PerimeterX spelled out", "https://store.example/", "store.example", "Press and hold to confirm you are human"),+ ("Amazon", "https://www.amazon.com/errors/validateCaptcha", "Amazon.com", "Enter the characters you see below. Sorry, we just need to make sure you're not a robot. For best results, please make sure your browser is accepting cookies."),+ ("Amazon curly", "https://www.amazon.de/", "Amazon.de", "Sorry, we just need to make sure you\u{2019}re not a robot."),+ ("generic robot", "https://news.example/", "news.example", "Please confirm you're not a robot to continue reading."),+ ("hCaptcha form", "https://forum.example/login", "Security check", "Please solve the CAPTCHA below to continue."),+ ("DuckDuckGo", "https://duckduckgo.com/html/?q=cats", "DuckDuckGo", "Unfortunately, bots use DuckDuckGo too. Please complete the following challenge to confirm this search was made by a human."),+ ("Yandex", "https://yandex.com/showcaptcha?cc=1", "Are you not a robot?", "Confirm that you are not a robot"),+ ];+ for (name, url, title, text) in walls {+ assert!(detect_bot_wall(url, title, text).is_some(), "{name} should read as a wall");+ }++ let article = format!(+ "A CAPTCHA is a test to tell computers and humans apart. Sites ask you to verify you are human, \+ or show a box saying I'm not a robot. {}",+ "Researchers have studied the usability of these tests for many years. ".repeat(60)+ );+ let not_walls = [+ ("Wikipedia article", "https://en.wikipedia.org/wiki/CAPTCHA", "CAPTCHA - Wikipedia", article.as_str()),+ ("search for captcha", "https://www.bing.com/search?q=captcha+solver", "captcha solver - Search", "Results"),+ ("long help page", "https://help.example/robots", "Help", article.as_str()),+ ("power button", "https://phone.example/manual", "Manual", "Press and hold the power button to restart."),+ ("Bing images", "https://www.bing.com/images/search?q=cat", "cat - Bing images", "Cat pictures, kittens"),+ ];+ for (name, url, title, text) in not_walls {+ assert!(detect_bot_wall(url, title, text).is_none(), "{name} should not read as a wall");+ }+}+/// A fake Chrome whose main frame is at `url` and whose capture returns `captured`; records every/// CDP call.async fn fake_page(diff --git a/tests/captcha_test.rs b/tests/captcha_test.rsindex 7b1dd749..e0315088 100644--- a/tests/captcha_test.rs+++ b/tests/captcha_test.rs@@ -111,13 +111,16 @@ async fn the_probe_finds_each_vendor_with_its_box_and_ignores_lookalikes() {let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].id.clone();let ctrl = kwnt::server::routes::get_or_create_browser_controller(&state, &bot).await.expect("browser");let base = serve_fixtures().await;- let cases: [(&str, Option<Expected>); 20] = [+ let cases: [(&str, Option<Expected>); 22] = [// a bare sign-up form with nothing but the checkbox counts as a wall("recaptcha.html", Some(("recaptcha", 304.0, 78.0))),// an open image challenge counts on any page, with the challenge's box("recaptcha_challenge.html", Some(("recaptcha", 400.0, 580.0))),("hcaptcha.html", Some(("hcaptcha", 303.0, 78.0))),("turnstile.html", Some(("turnstile", 300.0, 65.0))),+ // Cloudflare's own check page: Turnstile's iframe is in a closed shadow root, only its+ // host box shows+ ("turnstile_closed_shadow.html", Some(("turnstile", 300.0, 65.0))),("arkose.html", Some(("arkose", 400.0, 400.0))),("datadome.html", Some(("datadome", 400.0, 500.0))),("geetest.html", Some(("geetest", 342.0, 382.0))),@@ -137,6 +140,8 @@ async fn the_probe_finds_each_vendor_with_its_box_and_ignores_lookalikes() {// newsletter dialog or a sticky cookie bar isn't a CAPTCHA("contact_recaptcha.html", None),("footer_recaptcha.html", None),+ // a Turnstile box on a login form is ticked when logging in, not a wall+ ("login_turnstile.html", None),("recaptcha_challenge_closed.html", None),("consent_dialog_phrases.html", None),// below the fold: found, but without a box, and the page isn't scrolled@@ -352,6 +357,53 @@ async fn a_bot_landing_on_a_slider_gets_a_step_with_its_box_that_closes_once_solassert_eq!(resp.status(), StatusCode::CONFLICT);}+#[tokio::test]+async fn a_check_that_slides_in_after_a_click_asks_the_person_even_when_the_call_fails() {+ let tmp = tempdir().unwrap();+ let Some((endpoint, _chrome)) = start_chrome(&tmp.path().join("chrome")).await else { return };+ let state = state_with(&tmp, Some(endpoint)).await;+ state.human_steps.set_captcha_timing(Duration::from_secs(60), Duration::from_millis(200));+ let app = create_router(state.clone());+ let base = serve_fixtures().await;+ let decline = |id: String| {+ let app = app.clone();+ async move {+ let req = Request::builder().method("POST").uri(format!("/api/human-steps/{id}/decline")).body(Body::empty()).unwrap();+ assert_eq!(app.oneshot(req).await.unwrap().status(), StatusCode::OK);+ }+ };++ // A plain shop page: nothing to ask+ let token = turn(&state, "turn-click").await;+ let (text, is_error) = call(&app, &token, "browser_open", json!({"url": format!("{base}reveal_wall.html")})).await.unwrap();+ assert!(!is_error, "{text}");+ assert!(state.db.list_human_steps(Some("open"), None, None).await.unwrap().is_empty(), "no wall, no card");++ // Its search button swaps in PerimeterX's Press & Hold wall: the click lands on a check+ let task = call(&app, &token, "browser_act", json!({"action": "click_text", "text": "Search"}));+ let step = open_step(&state).await;+ assert_eq!((step.kind.as_str(), step.source.as_str()), ("captcha", "auto"));+ let json = serde_json::to_value(&step).unwrap();+ assert_eq!(json["target"]["kind"], "perimeterx", "{json}");+ assert!(step.message_id.is_some(), "a card in the chat");+ decline(step.id.clone()).await;+ let (text, _) = tokio::time::timeout(Duration::from_secs(20), task).await.expect("the turn resumes").unwrap();+ assert!(text.contains("declined"), "{text}");++ // A later turn's click fails on the wall (nothing called Checkout is left): the failed call+ // still hands the check to the person instead of ending in an error+ let token = turn(&state, "turn-failed-click").await;+ let task = call(&app, &token, "browser_act", json!({"action": "click_text", "text": "Checkout"}));+ let again = open_step(&state).await;+ assert_ne!(again.id, step.id);+ assert_eq!((again.kind.as_str(), again.source.as_str(), again.turn_id.as_deref()), ("captcha", "auto", Some("turn-failed-click")));+ assert!(again.message_id.is_some(), "a card in the chat");+ decline(again.id.clone()).await;+ let (text, is_error) = tokio::time::timeout(Duration::from_secs(20), task).await.expect("the turn resumes").unwrap();+ assert!(!is_error, "the bot hears about the check, not a failed click: {text}");+ assert!(text.contains("A CAPTCHA blocked the page") && text.contains("declined"), "{text}");+}+#[tokio::test]async fn a_captcha_step_nobody_solves_times_out_without_a_browser() {let tmp = tempdir().unwrap();diff --git a/tests/captcha_turn_test.rs b/tests/captcha_turn_test.rsnew file mode 100644index 00000000..409c678c--- /dev/null+++ b/tests/captcha_turn_test.rs@@ -0,0 +1,270 @@+//! A CAPTCHA kwnt meets outside a browser tool call still reaches the person as a "Human check+//! needed" card with a notification: when kwnt opens the person's link before the bot's turn, and+//! when a bot drives the browser through the shell API (curl, no kwnt tools). The bot is told the+//! person was asked, not to report a block or switch sites, and the person's answer starts a new+//! turn. A fake claude CLI on PATH records its prompt and, for a bot with a `curl` behaviour, calls+//! the browser API the prompt gives it. Its own test binary: it changes PATH. Skipped when no+//! Chrome or Chromium is installed.++#[path = "common/exe.rs"]+mod exe;+#[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::{human_steps::HumanStep, Database},+ drivers::events::RuntimeEvent,+ router::LayaRouter,+ sandbox::computer,+ server::{create_router, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::path::{Path, PathBuf};+use std::sync::OnceLock;+use std::time::Duration;+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tower::ServiceExt;++/// Records its arguments to `$KWNT_TEST_BEHAVE/<bot>.prompt`; with `<bot>.curl` holding a page+/// address, opens it twice through the browser API from the system prompt, saving each answer+/// (and its HTTP status) to `<bot>.curl1` / `<bot>.curl2`.+const FAKE_CLAUDE: &str = r#"#!/bin/sh+case "$1" in+ auth) echo '{"loggedIn":true}'; exit 0 ;;+esac+me=$(printf '%s\n' "$@" | sed -n 's/.*You are \([A-Za-z0-9]*\), .*/\1/p' | head -n 1)+dir="$KWNT_TEST_BEHAVE"+printf '%s\n' "$@" > "$dir/$me.prompt"+if [ -f "$dir/$me.curl" ]; then+ api=$(printf '%s\n' "$@" | sed -n 's/^Browser API: \(http[^ ]*\).*/\1/p' | head -n 1)+ url=$(cat "$dir/$me.curl")+ for n in 1 2; do+ curl -sS -o "$dir/$me.curl$n" -w '%{http_code}' -X POST "$api/navigate" -H 'Content-Type: application/json' -d "{\"url\":\"$url\"}" > "$dir/$me.status$n"+ done+fi+echo '{"type":"result","is_error":false,"num_turns":1,"result":"Waiting for you to solve the check."}'+"#;++fn behave_dir() -> &'static PathBuf {+ static DIR: OnceLock<PathBuf> = OnceLock::new();+ DIR.get_or_init(|| {+ let root = tempfile::tempdir().unwrap().keep();+ let (bin, behave) = (root.join("bin"), root.join("behave"));+ for d in [&bin, &behave] {+ std::fs::create_dir_all(d).unwrap();+ }+ exe::write_executable(bin.join("claude"), FAKE_CLAUDE);+ std::env::set_var("KWNT_TEST_BEHAVE", &behave);+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));+ behave+ })+}++fn read(bot: &str, what: &str) -> String {+ std::fs::read_to_string(behave_dir().join(format!("{bot}.{what}"))).unwrap_or_default()+}++/// Serves `tests/fixtures/captcha/<name>` on 127.0.0.1.+async fn serve_fixtures() -> String {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/captcha");+ tokio::spawn(async move {+ while let Ok((mut stream, _)) = listener.accept().await {+ let dir = dir.clone();+ tokio::spawn(async move {+ let mut buf = [0u8; 4096];+ let n = stream.read(&mut buf).await.unwrap_or(0);+ let request = String::from_utf8_lossy(&buf[..n]);+ let path = request.split_whitespace().nth(1).unwrap_or("/").trim_start_matches('/').to_string();+ let (status, body) = match (path.contains("..") || path.contains('/'), std::fs::read_to_string(dir.join(&path))) {+ (false, Ok(body)) => ("200 OK", body),+ _ => ("404 Not Found", String::new()),+ };+ let reply = format!("HTTP/1.1 {status}\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len());+ let _ = stream.write_all(reply.as_bytes()).await;+ });+ }+ });+ format!("http://127.0.0.1:{port}/")+}++struct Env {+ app: Router,+ state: AppState,+ fixtures: String,+ _chrome: ChromeGuard,+ _tmp: tempfile::TempDir,+}++/// kwnt on a real port (the shell API is curled), with a windowless Chrome as the VM browser.+async fn setup() -> Option<Env> {+ behave_dir();+ if computer::local_chrome_path().is_none() {+ eprintln!("skipped: no Chrome or Chromium installed");+ return None;+ }+ let tmp = tempfile::tempdir().unwrap();+ let profile = tmp.path().join("chrome");+ let (endpoint, _) = computer::ensure_local_chrome(&profile, true).await.expect("Chrome starts");+ let chrome = ChromeGuard(profile);+ std::env::set_var("KWNT_COMPUTER_MODE", "vm");+ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let config = Config {+ data_dir: data.clone(),+ port: listener.local_addr().unwrap().port(),+ laya_url: "http://127.0.0.1:9".into(),+ browser_cdp_url: Some(endpoint),+ ..Config::default()+ };+ let state = AppState::new(config.clone(), db, ToolRunner::new(data.join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url.clone()));+ // Long enough that nothing times out while the test looks+ state.human_steps.set_captcha_timing(Duration::from_secs(120), Duration::from_millis(200));+ let app = create_router(state.clone());+ let served = app.clone();+ tokio::spawn(async move { axum::serve(listener, served).await.unwrap() });+ Some(Env { app, state, fixtures: serve_fixtures().await, _chrome: chrome, _tmp: tmp })+}++async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json");+ let resp = app.clone().oneshot(req.body(body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();+ let s = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (s, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++async fn add_bot(env: &Env, name: &str) -> String {+ let (s, v) = call(&env.app, "POST", "/api/kwants", Some(json!({"name": name, "title": "Researcher", "persona_prompt": "", "soul": "", "avatar_sprite": "default", "driver_type": "cli", "preferred_model": "claude"}))).await;+ assert!(s.is_success(), "{s} {v}");+ v["id"].as_str().or(v["kwant"]["id"].as_str()).unwrap().to_string()+}++/// Waits until no turn runs (for a while).+async fn settle(env: &Env) {+ let mut quiet = 0;+ for _ in 0..600 {+ quiet = if env.state.turns.active_turns().is_empty() { quiet + 1 } else { 0 };+ if quiet >= 10 {+ return;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ panic!("the turn never ended");+}++fn open_steps(steps: Vec<HumanStep>, bot: &str) -> Vec<HumanStep> {+ steps.into_iter().filter(|s| s.kwant_id == bot).collect()+}++/// The person sees the step: one open CAPTCHA step of this bot's turn, its card in the bot's+/// chat, a `human_step` notification, and the browser handed to them.+async fn assert_asked(env: &Env, bot: &str, events: &mut tokio::sync::broadcast::Receiver<RuntimeEvent>) -> HumanStep {+ let steps = open_steps(env.state.db.list_human_steps(Some("open"), None, None).await.unwrap(), bot);+ assert_eq!(steps.len(), 1, "one card, not one per read: {steps:?}");+ let step = steps.into_iter().next().unwrap();+ assert_eq!((step.kind.as_str(), step.source.as_str()), ("captcha", "auto"));+ assert!(step.turn_id.is_some(), "the step belongs to the turn that met the check");+ let card = env.state.db.get_message(step.message_id.as_deref().unwrap()).await.unwrap().unwrap();+ assert!(card.text.starts_with("Human check needed: "), "{}", card.text);+ assert!(card.text.contains("Solve it in the browser panel"), "{}", card.text);+ let msgs = env.state.db.list_messages(bot, 50).await.unwrap();+ assert!(msgs.iter().any(|m| m.id == card.id), "the card is in the bot's chat");+ let mut notified = false;+ while let Ok(ev) = events.try_recv() {+ if let RuntimeEvent::Notify { kind, kwant_id, title, .. } = ev {+ if kind == "human_step" && kwant_id == bot {+ assert!(title.ends_with("needs you in the browser"), "{title}");+ notified = true;+ }+ }+ }+ assert!(notified, "the person is notified");+ assert!(env.state.human_steps.turn_on(step.sandbox_target.as_deref().unwrap()).is_none(), "the turn ended and left the browser");+ step+}++/// The person's link opens on a CAPTCHA before the bot's turn starts: the card is up before the+/// bot runs, the bot hears the person was asked (not to report a block or try Bing), and Done+/// starts a new turn in the same chat.+#[tokio::test]+async fn a_link_the_person_sends_that_opens_on_a_captcha_asks_them_to_solve_it() {+ let Some(env) = setup().await else { return };+ let bot = add_bot(&env, "Wren").await;+ let mut events = env.state.event_sender.subscribe();+ let link = format!("{}px_wall.html", env.fixtures);+ let (s, v) = call(&env.app, "POST", "/api/chat/send", Some(json!({"kwant_id": bot, "prompt": format!("what does {link} say?"), "sender_id": "user"}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ settle(&env).await;++ let step = assert_asked(&env, &bot, &mut events).await;+ assert_eq!(step.url.as_deref(), Some(link.as_str()));+ let prompt = read("Wren", "prompt");+ assert!(prompt.contains("\"Human check needed\" card"), "{prompt}");+ assert!(prompt.contains("End your turn now"), "{prompt}");+ assert!(!prompt.contains("retry once on another engine"), "no route around the check: {prompt}");++ // The person solves it and presses Done: a new turn picks the task up+ std::fs::remove_file(behave_dir().join("Wren.prompt")).unwrap();+ let (s, v) = call(&env.app, "POST", &format!("/api/human-steps/{}/done", step.id), None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["resumed"], "new_turn");+ tokio::time::sleep(Duration::from_millis(300)).await;+ settle(&env).await;+ assert!(read("Wren", "prompt").contains("The person did the browser step you asked for earlier"));+}++/// A bot without kwnt's tools (agent tools off) opens a CAPTCHA page with curl: the person gets+/// the card in that turn's chat, the bot is told so, and its next browser action waits for them.+#[tokio::test]+async fn a_captcha_met_through_the_shell_browser_api_asks_the_person() {+ let Some(env) = setup().await else { return };+ let (s, v) = call(&env.app, "POST", "/api/settings", Some(json!({"agent_tools": false}))).await;+ assert!(s.is_success(), "{s} {v}");+ let bot = add_bot(&env, "Ossi").await;+ let link = format!("{}px_wall.html", env.fixtures);+ std::fs::write(behave_dir().join("Ossi.curl"), &link).unwrap();+ let mut events = env.state.event_sender.subscribe();+ let (s, v) = call(&env.app, "POST", "/api/chat/send", Some(json!({"kwant_id": bot, "prompt": "check the store page for me", "sender_id": "user"}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ settle(&env).await;++ let prompt = read("Ossi", "prompt");+ assert!(prompt.contains("Browser API: http://127.0.0.1:"), "the bot drives the browser with curl: {prompt}");+ assert_eq!(read("Ossi", "status1"), "200");+ let first: Value = serde_json::from_str(&read("Ossi", "curl1")).unwrap();+ assert_eq!(first["blocked"], true, "{first}");+ assert_eq!(first["human_step"], "asked", "{first}");+ assert!(first["notice"].as_str().unwrap().contains("\"Human check needed\" card"), "{first}");+ // The browser is the person's until they finish+ assert_eq!(read("Ossi", "status2"), "409");+ assert!(read("Ossi", "curl2").contains("waiting on the person"));+ assert_asked(&env, &bot, &mut events).await;+}++/// Without a turn on the browser (someone curling it by hand) nobody is asked, and the answer+/// keeps the plain notice, which never tells the bot to solve or go around the check.+#[tokio::test]+async fn the_browser_api_asks_nobody_without_a_turn() {+ let Some(env) = setup().await else { return };+ let bot = add_bot(&env, "Pim").await;+ let (s, page) = call(&env.app, "POST", &format!("/api/sandbox/{bot}/navigate"), Some(json!({"url": format!("{}px_wall.html", env.fixtures)}))).await;+ assert_eq!(s, StatusCode::OK, "{page}");+ assert_eq!(page["blocked"], true, "{page}");+ assert!(page.get("human_step").is_none(), "{page}");+ let notice = page["notice"].as_str().unwrap();+ assert!(notice.contains("never try to solve, bypass or click through the check"), "{notice}");+ assert!(notice.contains("request_human_step"), "{notice}");+ assert!(env.state.db.list_human_steps(Some("open"), None, None).await.unwrap().is_empty());+}diff --git a/tests/fixtures/captcha/login_turnstile.html b/tests/fixtures/captcha/login_turnstile.htmlnew file mode 100644index 00000000..5c9964dd--- /dev/null+++ b/tests/fixtures/captcha/login_turnstile.html@@ -0,0 +1,4 @@+<!doctype html><title>Log in</title><body style="margin:0;font:16px sans-serif"><h1>Log in</h1>+<form><label>Email <input type="email" name="email"></label><br><label>Password <input type="password" name="pw"></label><br>+<div class="cf-turnstile" style="width:300px;height:65px"></div><button>Log in</button></form>+<script>document.querySelector('.cf-turnstile').attachShadow({mode:'closed'}).innerHTML='<iframe style="width:300px;height:65px;border:0"></iframe>';</script></body>diff --git a/tests/fixtures/captcha/px_wall.html b/tests/fixtures/captcha/px_wall.htmlnew file mode 100644index 00000000..fd68e8b1--- /dev/null+++ b/tests/fixtures/captcha/px_wall.html@@ -0,0 +1,2 @@+<!doctype html><title>Access to this page has been denied</title><body style="margin:0;font:16px sans-serif"><h1>Before we continue...</h1>+<p>Press & Hold to confirm you are a human (and not a bot).</p><div id="px-captcha" style="width:312px;height:102px;border:1px solid #ccc"></div><p>Reference ID 7f3a</p></body>diff --git a/tests/fixtures/captcha/reveal_wall.html b/tests/fixtures/captcha/reveal_wall.htmlnew file mode 100644index 00000000..22a27ab6--- /dev/null+++ b/tests/fixtures/captcha/reveal_wall.html@@ -0,0 +1,7 @@+<!doctype html><title>Shop</title><body style="margin:0;font:16px sans-serif"><h1>Shop</h1><button id="go" style="width:120px;height:40px">Search</button>+<script>+document.getElementById('go').addEventListener('click', function () {+ document.title = 'Access to this page has been denied';+ document.body.innerHTML = '<p>Press & Hold to confirm you are a human (and not a bot).</p><div id="px-captcha" style="width:312px;height:102px"></div>';+});+</script></body>diff --git a/tests/fixtures/captcha/turnstile_closed_shadow.html b/tests/fixtures/captcha/turnstile_closed_shadow.htmlnew file mode 100644index 00000000..4f56f994--- /dev/null+++ b/tests/fixtures/captcha/turnstile_closed_shadow.html@@ -0,0 +1,3 @@+<!doctype html><title>Just a moment...</title><body style="margin:0;font:16px sans-serif"><h1>site.example</h1><p>Verify you are human by completing the action below.</p>+<div id="challenge-stage"><div class="cf-turnstile" style="width:300px;height:65px"></div></div>+<script>document.querySelector('.cf-turnstile').attachShadow({mode:'closed'}).innerHTML='<iframe style="width:300px;height:65px;border:0" srcdoc="<p>Verify</p>"></iframe>';</script></body>