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
CAPTCHA card goes to the calling thread of a bot running two threads; document the bot browser address (N3, N2 on #298) (#299)
Oleksandr Ivanchenko951888c51cb7
diff --git a/docs/bot-browser.md b/docs/bot-browser.mdindex 6bfcb40d..744b78c8 100644--- a/docs/bot-browser.md+++ b/docs/bot-browser.md@@ -1,9 +1,38 @@# How bots use their browserBots drive the browser in their side panel through `browser_open`, `browser_page` and `browser_act`-(kwnt's own tools) or the shell API (`/api/sandbox/:id/{navigate,page,act}`). Both return the same-compact page state: `url`, `title`, `text`, `clickable`. Payments are covered in-[payments.md](payments.md); the person's live view uses `/interact`, which bots can't call.+(kwnt's own tools) or the shell API. Both return the same compact page state: `url`, `title`,+`text`, `clickable`. Payments are covered in [payments.md](payments.md); the person's live view+uses `/interact`, which bots can't call.++## The shell API's addresses++Each turn's prompt gives the bot its own address for the browser API, naming the bot and the chat+the turn runs in:++ /api/sandbox/:id/bot/:kwant_id/chat/:chat_id/{navigate,page,act,cite}++`:id` is the browser (a team's, a channel's or the bot's own), `:kwant_id` the bot, and `:chat_id`+the turn's thread, else its channel, else its DM (`human_steps::chat_key`). The address is the+same for every turn of one thread, so it doesn't change the cached prompt. A team's bots and+threads share one browser; the address is how kwnt knows whose call met a CAPTCHA, so the "Human+check needed" card goes to the chat of exactly that turn ([live-activity.md](live-activity.md)).++- `/api/sandbox/:id/bot/:kwant_id/{navigate,page,act,cite}` (no chat) is the address prompts gave+ before the chat was added. It still works: a bot copying it out of old history is asked in its+ newest turn on that browser.+- `/api/sandbox/:id/{navigate,page,act,cite}` (no bot) is the person's browser panel. A CAPTCHA+ met there is asked in the newest turn on that browser. While the browser is held for a person's+ step it answers 409 with `HELD_FOR_PERSON` ("Take control in the browser panel … or press Done+ or Decline on the card"), where a bot's address gets `HELD_FOR_BOT` ("Stop browser actions and+ end your turn").+- If a bot's address matches no live turn on that browser (its turn ended, or a wrong id), nobody+ is asked: the card never goes to another bot or another thread.+- Known limit: the `kwant_id` and `chat_id` in the path are trusted. Any caller that can already+ drive the browser could name another bot's turn; binding the address to the turn's token would+ close that.++Below, `/page`, `/act`, `/navigate` and `/cite` mean any of these addresses.## Clicking by ref@@ -85,7 +114,8 @@ A bot backs facts it read on the web with links that open the page at the wordsthem against the page open now (`sandbox::cite`, plain text matching, no model call).- MCP: `browser_cite` with `text` (the exact words) or `block` (an id from a read with blocks). Itonly reads, so it is free in always-ask turns (`READ_ONLY_SELF_TOOLS`) and is a core tool.-- HTTP: `POST /api/sandbox/:id/cite` with `{"text": …}` or `{"block": …}`.+- HTTP: `POST <browser API>/cite` with `{"text": …}` or `{"block": …}` (the bot's own address+ from its prompt; see [The shell API's addresses](#the-shell-apis-addresses)).The answer is `{quote, url, link}`; `quote` is the page's own text and `url` the address it is on.The words must be on the page word for word: runs of spaces and line breaks count as one space,diff --git a/docs/live-activity.md b/docs/live-activity.mdindex f98dae69..85ce78f0 100644--- a/docs/live-activity.md+++ b/docs/live-activity.md@@ -169,12 +169,22 @@ kwnt also raises the step where no tool call can wait on it. It does not wait; tand the page is a wall, the card is up before the bot runs. The bot's prompt says the person wasasked 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.+ start) drives the browser with curl, on the address its prompt gives it:+ `/api/sandbox/:id/bot/:kwant_id/chat/:chat_id/` (the bot, and its turn's thread, channel or DM;+ see [bot-browser.md](bot-browser.md#the-shell-apis-addresses)). `POST /navigate`, `GET /page`+ and `POST /act` there raise the step in the chat of that bot's turn in that thread, even when+ other bots, or the same bot in another thread, run newer turns on the same team 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** with `HELD_FOR_BOT` ("The browser is waiting+ on the person … end your turn"). An address that matches no live turn there asks nobody, never+ another chat.+ - The older address without `/chat/:chat_id` still works and asks in that bot's newest turn on+ the browser.+ - The plain `/api/sandbox/:id/` address is the person's browser panel: a wall met there is asked+ in the newest turn on the browser, and while the step is open it answers **409** with+ `HELD_FOR_PERSON` ("Take control in the browser panel … or press Done or Decline on the card").+ - 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-inbrowser goes to the person too. The bot opens that address in kwnt's browser, where the card comesdiff --git a/docs/payments.md b/docs/payments.mdindex ee7eb308..17a56957 100644--- a/docs/payments.md+++ b/docs/payments.md@@ -79,8 +79,9 @@ rules in `payment_floor::page_reason`), so the bot's own words never decide:address, or anywhere on a page with a payment provider's card frame. Either key on a focusedbutton or link presses it, so the click rules above apply to it, by the text it shows.-The shell bots' browser API (`POST /api/sandbox/:id/act`) can't show a card, so it doesn't do an-action that looks like a payment: the page comes back with `error` ("Not done: this looks like a+The shell bots' browser API (`POST /api/sandbox/:id/bot/:kwant_id/chat/:chat_id/act`, the address+in each bot's prompt; the older `/bot/:kwant_id/act` and the person's plain `/api/sandbox/:id/act`+behave the same here) can't show a card, so it doesn't do an action that looks like a payment: the page comes back with `error` ("Not done: this looks like apayment …") and `payment` (why), and the bot is told to leave that step to the person in the livebrowser panel. Clicks by position (`/api/sandbox/:id/interact`) are the person's live view only.diff --git a/src/server/human_steps.rs b/src/server/human_steps.rsindex 404fe3a4..4081cc62 100644--- a/src/server/human_steps.rs+++ b/src/server/human_steps.rs@@ -153,11 +153,17 @@ impl HumanStepHub {self.newest_on(target, |_| true)}- /// The live turn on this bot browser that the call came from: `by` (the bot that made it)- /// picks that bot's newest turn there, and no other bot's; without `by`, [`Self::turn_on`].- pub fn turn_of(&self, target: &str, by: Option<&str>) -> Option<SelfScope> {+ /// The live turn on this bot browser that the call came from. `by` (the bot that made it)+ /// picks that bot's newest turn there, and no other bot's; with its chat as well (the turn's+ /// thread, channel or DM, [`chat_key`]), only that bot's turn in that chat, so one bot running+ /// two threads on a team browser is asked in the thread that met the wall. Without `by`,+ /// [`Self::turn_on`]. A caller that matches no turn gets `None`: it is never asked elsewhere.+ pub fn turn_of(&self, target: &str, by: Option<Caller<'_>>) -> Option<SelfScope> {match by {- Some(kwant) => self.newest_on(target, |s| s.kwant_id == kwant),+ Some(Caller { kwant, chat: Some(chat) }) => {+ self.newest_on(target, |s| s.kwant_id == kwant && chat_key(s).as_deref() == Some(chat))+ }+ Some(Caller { kwant, chat: None }) => self.newest_on(target, |s| s.kwant_id == kwant),None => self.turn_on(target),}}@@ -170,6 +176,22 @@ impl HumanStepHub {}}+/// Who made a call on a bot's own browser API (`/api/sandbox/:id/bot/:kwant_id[/chat/:chat]/...`):+/// the bot, and the chat its turn runs in when the address names one.+#[derive(Clone, Copy, Debug)]+pub struct Caller<'a> {+ pub kwant: &'a str,+ pub chat: Option<&'a str>,+}++/// The chat a turn runs in, as its browser address names it: its thread, else its channel, else+/// its DM (the bot it talks to). The same for every turn of one thread, so the address in the+/// bot's prompt never changes within a thread.+pub fn chat_key(scope: &SelfScope) -> Option<String> {+ let o = scope.origin.as_ref()?;+ o.thread_id.clone().or_else(|| o.channel_id.clone()).or_else(|| o.direct_kwant_id.clone())+}+/// Keeps a turn recorded on its bot browser while it runs ([`HumanStepHub::track_turn`]).pub struct TurnOnBrowser {hub: Arc<HumanStepHub>,@@ -854,7 +876,7 @@ mod tests {let hub = Arc::new(HumanStepHub::default());let older = hub.track_turn("team", turn("ann"));let newer = hub.track_turn("team", turn("bob"));- let of = |by: Option<&str>| hub.turn_of("team", by).map(|s| s.kwant_id);+ let of = |by: Option<&str>| hub.turn_of("team", by.map(|kwant| Caller { kwant, chat: None })).map(|s| s.kwant_id);assert_eq!(of(Some("ann")).as_deref(), Some("ann"));assert_eq!(of(Some("bob")).as_deref(), Some("bob"));assert_eq!(of(None).as_deref(), Some("bob"), "an unknown caller: the newest turn");@@ -865,12 +887,41 @@ mod tests {let cancelled = tokio_util::sync::CancellationToken::new();let stopped = hub.track_turn("team", SelfScope { cancel: Some(cancelled.clone()), ..turn("ann") });cancelled.cancel();- assert_eq!(hub.turn_of("team", Some("ann")).and_then(|s| s.cancel), None, "a stopped turn asks nobody; the live one does");+ assert_eq!(hub.turn_of("team", Some(Caller { kwant: "ann", chat: None })).and_then(|s| s.cancel), None, "a stopped turn asks nobody; the live one does");drop((older, stopped));assert!(hub.turn_on("team").is_none());assert!(hub.turns.lock().unwrap().is_empty());}+ fn turn_in(kwant: &str, thread: &str) -> SelfScope {+ let mut t = turn(kwant);+ t.origin = Some(super::super::continuity::TurnOrigin { thread_id: Some(thread.into()), ..Default::default() });+ t.turn_id = Some(format!("turn-{kwant}-{thread}"));+ t+ }++ /// One bot running two threads on one team browser: an address naming the thread gets that+ /// thread's turn, even while the other thread's turn is newer; a thread with no turn there is+ /// asked nowhere; the bot-only address (an old prompt) keeps the bot's newest turn.+ #[test]+ fn a_shared_browser_knows_each_threads_turn() {+ let hub = Arc::new(HumanStepHub::default());+ let a = hub.track_turn("team", turn_in("ann", "thread-a"));+ let _b = hub.track_turn("team", turn_in("ann", "thread-b"));+ let _other = hub.track_turn("team", turn_in("bob", "thread-c"));+ let of = |kwant: &str, chat: Option<&str>| hub.turn_of("team", Some(Caller { kwant, chat })).and_then(|s| s.turn_id);+ assert_eq!(of("ann", Some("thread-a")).as_deref(), Some("turn-ann-thread-a"), "the thread that called, not the newer one");+ assert_eq!(of("ann", Some("thread-b")).as_deref(), Some("turn-ann-thread-b"));+ assert_eq!(of("ann", None).as_deref(), Some("turn-ann-thread-b"), "no chat in the address: the bot's newest turn");+ assert_eq!(of("ann", Some("thread-c")), None, "another bot's thread is never this bot's");+ assert_eq!(of("ann", Some("thread-x")), None, "a thread with no turn here asks nobody");+ drop(a);+ assert_eq!(of("ann", Some("thread-a")), None, "thread A's turn ended: nobody, never thread B");+ assert_eq!(chat_key(&turn("ann")), None, "no thread, channel or DM: no chat to name");+ let dm = SelfScope { origin: Some(super::super::continuity::TurnOrigin { direct_kwant_id: Some("ann".into()), ..Default::default() }), ..turn("ann") };+ assert_eq!(chat_key(&dm).as_deref(), Some("ann"));+ }+#[test]fn the_agent_hears_each_outcome_plainly() {assert!(outcome_text(Some(Outcome::Done), false).contains("Look at the page"));diff --git a/src/server/mod.rs b/src/server/mod.rsindex 0da01f20..70fc6536 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -268,6 +268,10 @@ pub fn create_router(state: AppState) -> Router {.route("/api/sandbox/:team_id/bot/:kwant_id/page", get(routes::get_sandbox_page_bot)).route("/api/sandbox/:team_id/bot/:kwant_id/act", post(routes::act_sandbox_bot)).route("/api/sandbox/:team_id/bot/:kwant_id/cite", post(routes::cite_sandbox_bot))+ .route("/api/sandbox/:team_id/bot/:kwant_id/chat/:chat_id/navigate", post(routes::navigate_sandbox_bot_chat))+ .route("/api/sandbox/:team_id/bot/:kwant_id/chat/:chat_id/page", get(routes::get_sandbox_page_bot_chat))+ .route("/api/sandbox/:team_id/bot/:kwant_id/chat/:chat_id/act", post(routes::act_sandbox_bot_chat))+ .route("/api/sandbox/:team_id/bot/:kwant_id/chat/:chat_id/cite", post(routes::cite_sandbox_bot_chat)).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)).route("/api/sandbox/:team_id/passwords/:id", delete(passwords::remove))diff --git a/src/server/routes.rs b/src/server/routes.rsindex dbee094d..fdf02319 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -2475,11 +2475,10 @@ async fn run_kwant_turn_inner(.await;let skills = super::skills::prompt_block(state, &target_kwant.id, &prompt, with_tools).await;let turn_input = TurnInput {- // The bot's own copy of the browser API: a CAPTCHA it meets is asked in its chat- browser_api_url: Some(format!(- "http://127.0.0.1:{}/api/sandbox/{}/bot/{}",- state.config.port, sandbox_target, target_kwant.id- )),+ // The bot's own copy of the browser API, naming this chat (thread, channel or DM): a+ // CAPTCHA it meets is asked in the thread whose call met it. The same for every turn+ // of the thread, so the cached prompt tail doesn't change.+ browser_api_url: Some(bot_browser_api(state.config.port, &sandbox_target, &turn_scope)),thread_id: context_id,kwant: target_kwant.clone(),prompt: final_prompt,@@ -4893,9 +4892,9 @@ pub fn bot_wall_notice(kind: &str, url: &str) -> String {/// calls them: 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 newest turn running on that browser, with a/// "Human check needed" card. Bots get their own copy of these routes-/// (`/api/sandbox/:id/bot/:kwant_id/...`, [`navigate_sandbox_bot`]) in their prompt, so a CAPTCHA-/// one bot meets on a team's shared browser is asked in that bot's chat, not in whichever bot's-/// turn started last. Nothing waits on the card there, so the bot is told to end its turn; the+/// (`/api/sandbox/:id/bot/:kwant_id/chat/:chat/...`, [`navigate_sandbox_bot_chat`]) in their+/// prompt, so a CAPTCHA one bot meets on a team's shared browser is asked in that bot's thread+/// that met it, not in whichever turn started last. Nothing waits on the card 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>,@@ -4921,31 +4920,56 @@ pub async fn act_sandbox_api(act_as(state, team_id, None, payload).await}-/// `POST /api/sandbox/:id/bot/:kwant_id/navigate`: the browser API a bot's prompt gives it.+/// The browser API address a bot's prompt gives it for one turn:+/// `…/api/sandbox/:id/bot/:kwant_id/chat/:chat`, or without the chat segment when the turn has+/// no chat to name.+pub fn bot_browser_api(port: u16, sandbox_target: &str, turn: &super::continuity::SelfScope) -> String {+ let bot = format!("http://127.0.0.1:{port}/api/sandbox/{sandbox_target}/bot/{}", turn.kwant_id);+ match super::human_steps::chat_key(turn) {+ Some(chat) => format!("{bot}/chat/{chat}"),+ None => bot,+ }+}++/// The bot (and its chat, when the address names one) that called a bot's own browser route.+pub struct BotCall {+ kwant: String,+ chat: Option<String>,+}++impl BotCall {+ fn caller(&self) -> super::human_steps::Caller<'_> {+ super::human_steps::Caller { kwant: &self.kwant, chat: self.chat.as_deref() }+ }+}++/// `POST /api/sandbox/:id/bot/:kwant_id/navigate`: the browser API a bot's prompt gave it before+/// the address named its chat. Still served: a bot copying it out of history is asked in its+/// newest turn on the browser.pub async fn navigate_sandbox_bot(State(state): State<AppState>,- Path((team_id, kwant_id)): Path<(String, String)>,+ Path((team_id, kwant)): Path<(String, String)>,payload: Json<NavigatePayload>,) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {- navigate_as(state, team_id, Some(kwant_id), payload).await+ navigate_as(state, team_id, Some(BotCall { kwant, chat: None }), payload).await}/// `GET /api/sandbox/:id/bot/:kwant_id/page`.pub async fn get_sandbox_page_bot(State(state): State<AppState>,- Path((team_id, kwant_id)): Path<(String, String)>,+ Path((team_id, kwant)): Path<(String, String)>,query: Query<PageQuery>,) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {- page_as(state, team_id, Some(kwant_id), query).await+ page_as(state, team_id, Some(BotCall { kwant, chat: None }), query).await}/// `POST /api/sandbox/:id/bot/:kwant_id/act`.pub async fn act_sandbox_bot(State(state): State<AppState>,- Path((team_id, kwant_id)): Path<(String, String)>,+ Path((team_id, kwant)): Path<(String, String)>,payload: Json<InteractPayload>,) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {- act_as(state, team_id, Some(kwant_id), payload).await+ act_as(state, team_id, Some(BotCall { kwant, chat: None }), payload).await}/// `POST /api/sandbox/:id/bot/:kwant_id/cite`.@@ -4957,22 +4981,59 @@ pub async fn cite_sandbox_bot(cite_sandbox(State(state), Path(team_id), payload).await}+/// `POST /api/sandbox/:id/bot/:kwant_id/chat/:chat/navigate`: the browser API a bot's prompt+/// gives it now. A CAPTCHA it meets is asked in that chat's turn of that bot, and nowhere else.+pub async fn navigate_sandbox_bot_chat(+ State(state): State<AppState>,+ Path((team_id, kwant, chat)): Path<(String, String, String)>,+ payload: Json<NavigatePayload>,+) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {+ navigate_as(state, team_id, Some(BotCall { kwant, chat: Some(chat) }), payload).await+}++/// `GET /api/sandbox/:id/bot/:kwant_id/chat/:chat/page`.+pub async fn get_sandbox_page_bot_chat(+ State(state): State<AppState>,+ Path((team_id, kwant, chat)): Path<(String, String, String)>,+ query: Query<PageQuery>,+) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {+ page_as(state, team_id, Some(BotCall { kwant, chat: Some(chat) }), query).await+}++/// `POST /api/sandbox/:id/bot/:kwant_id/chat/:chat/act`.+pub async fn act_sandbox_bot_chat(+ State(state): State<AppState>,+ Path((team_id, kwant, chat)): Path<(String, String, String)>,+ payload: Json<InteractPayload>,+) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {+ act_as(state, team_id, Some(BotCall { kwant, chat: Some(chat) }), payload).await+}++/// `POST /api/sandbox/:id/bot/:kwant_id/chat/:chat/cite`.+pub async fn cite_sandbox_bot_chat(+ State(state): State<AppState>,+ Path((team_id, _kwant_id, _chat)): Path<(String, String, String)>,+ payload: Json<CitePayload>,+) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {+ cite_sandbox(State(state), Path(team_id), payload).await+}+/// `by`: the bot that made the call (its own route), `None` on the plain route.async fn navigate_as(state: AppState,team_id: String,- by: Option<String>,+ by: Option<BotCall>,payload: Json<NavigatePayload>,) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {refuse_while_held(&state, &team_id, by.is_some()).await?;let result = navigate_sandbox(State(state.clone()), Path(team_id.clone()), payload).await;- ask_on_wall(&state, &team_id, by.as_deref(), result).await+ ask_on_wall(&state, &team_id, by.as_ref().map(BotCall::caller), result).await}async fn page_as(state: AppState,team_id: String,- by: Option<String>,+ by: Option<BotCall>,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;@@ -4980,18 +5041,18 @@ async fn page_as(if super::human_steps::browser_is_held(&state, &team_id).await {return result;}- ask_on_wall(&state, &team_id, by.as_deref(), result).await+ ask_on_wall(&state, &team_id, by.as_ref().map(BotCall::caller), result).await}async fn act_as(state: AppState,team_id: String,- by: Option<String>,+ by: Option<BotCall>,payload: Json<InteractPayload>,) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {refuse_while_held(&state, &team_id, by.is_some()).await?;let result = act_sandbox(State(state.clone()), Path(team_id.clone()), payload).await;- ask_on_wall(&state, &team_id, by.as_deref(), result).await+ ask_on_wall(&state, &team_id, by.as_ref().map(BotCall::caller), result).await}/// What a browser call is told while the browser is held for the person's step: a bot (its own@@ -5010,12 +5071,12 @@ async fn refuse_while_held(state: &AppState, team_id: &str, bot: bool) -> Result/// 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.-/// The card goes to the chat of the calling bot's turn on this browser (`by`); only when the-/// caller isn't known (the plain route) does it fall back to the newest turn there.+/// The card goes to the calling bot's turn on this browser (`by`), in the chat its address names;+/// only when the caller isn't known (the plain route) does it fall back to the newest turn there.async fn ask_on_wall(state: &AppState,team_id: &str,- by: Option<&str>,+ by: Option<super::human_steps::Caller<'_>>,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_of(team_id, by) else { return result };diff --git a/tests/captcha_turn_test.rs b/tests/captcha_turn_test.rsindex 685c5282..7ff64cc6 100644--- a/tests/captcha_turn_test.rs+++ b/tests/captcha_turn_test.rs@@ -35,14 +35,17 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};use tower::ServiceExt;/// Records its arguments to `$KWNT_TEST_BEHAVE/<bot>.prompt`; with `<bot>.wait` holding seconds,-/// sleeps that long first (so two bots' turns overlap); 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`.+/// sleeps that long first (so two turns overlap); 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`. A message saying `(task-<x>)` uses+/// `<bot>-<x>.*` instead, so one bot can behave differently in two threads.const FAKE_CLAUDE: &str = r#"#!/bin/shcase "$1" inauth) echo '{"loggedIn":true}'; exit 0 ;;esacme=$(printf '%s\n' "$@" | sed -n 's/.*You are \([A-Za-z0-9]*\), .*/\1/p' | head -n 1)+task=$(printf '%s\n' "$@" | sed -n 's/.*(task-\([a-z]*\)).*/\1/p' | head -n 1)+me="$me${task:+-$task}"dir="$KWNT_TEST_BEHAVE"printf '%s\n' "$@" > "$dir/$me.prompt"if [ -f "$dir/$me.wait" ]; then sleep "$(cat "$dir/$me.wait")"; fi@@ -249,7 +252,7 @@ async fn a_captcha_met_through_the_shell_browser_api_asks_the_person() {let prompt = read("Ossi", "prompt");assert!(prompt.contains("Browser API: http://127.0.0.1:"), "the bot drives the browser with curl: {prompt}");- assert!(prompt.contains(&format!("/api/sandbox/{bot}/bot/{bot}")), "its own copy of the API names it: {prompt}");+ assert!(prompt.contains(&format!("/api/sandbox/{bot}/bot/{bot}/chat/{bot}")), "its own copy of the API names it and its chat: {prompt}");assert_eq!(read("Ossi", "status1"), "200");let first: Value = serde_json::from_str(&read("Ossi", "curl1")).unwrap();assert_eq!(first["blocked"], true, "{first}");@@ -306,11 +309,11 @@ async fn a_captcha_one_bot_meets_on_a_shared_team_browser_is_asked_in_that_bots_tokio::time::sleep(Duration::from_millis(50)).await;}assert_eq!(env.state.human_steps.turn_on(&team_id).map(|t| t.kwant_id), Some(newer.clone()), "Ulla's turn is the newest on the team browser");- assert_eq!(env.state.human_steps.turn_of(&team_id, Some(&older)).map(|t| t.kwant_id), Some(older.clone()), "Tove's turn is still running");+ assert_eq!(env.state.human_steps.turn_of(&team_id, Some(kwnt::server::human_steps::Caller { kwant: &older, chat: None })).map(|t| t.kwant_id), Some(older.clone()), "Tove's turn is still running");settle(&env).await;- assert!(read("Tove", "prompt").contains(&format!("/api/sandbox/{team_id}/bot/{older}")), "{}", read("Tove", "prompt"));- assert!(read("Ulla", "prompt").contains(&format!("/api/sandbox/{team_id}/bot/{newer}")), "both drive the team's browser");+ assert!(read("Tove", "prompt").contains(&format!("/api/sandbox/{team_id}/bot/{older}/chat/{tove}")), "{}", read("Tove", "prompt"));+ assert!(read("Ulla", "prompt").contains(&format!("/api/sandbox/{team_id}/bot/{newer}/chat/{ulla}")), "both drive the team's browser");let first: Value = serde_json::from_str(&read("Tove", "curl1")).unwrap();assert_eq!((first["blocked"].clone(), first["human_step"].clone()), (json!(true), json!("asked")), "{first}");let step = assert_asked_in(&env, &older, &tove, &mut events).await;@@ -324,6 +327,65 @@ async fn a_captcha_one_bot_meets_on_a_shared_team_browser_is_asked_in_that_bots_}}+/// One bot runs two team threads on the team's browser at once (Rigel's N3 on #298): thread A's+/// curl meets the CAPTCHA while the same bot's turn in thread B, started later, is still running.+/// The card, its notification and the step are thread A's; thread B and the bot's DM get nothing.+/// Before the address named the thread, the card went to thread B (the bot's newest turn).+#[tokio::test]+async fn a_captcha_met_in_one_of_a_bots_two_threads_on_a_team_browser_is_asked_in_that_thread() {+ 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, "Vesa").await;+ let (s, team) = call(&env.app, "POST", "/api/teams", Some(json!({"name": "checkers", "lead_kwant_id": bot, "member_kwants": [bot]}))).await;+ assert!(s.is_success(), "{s} {team}");+ let team_id = team["id"].as_str().or(team["team"]["id"].as_str()).unwrap().to_string();+ let thread_a = env.state.db.create_thread(&bot, "Store check", "chat", Some(&team_id), "user").await.unwrap().id;+ let thread_b = env.state.db.create_thread(&bot, "Price list", "chat", Some(&team_id), "user").await.unwrap().id;+ // Thread A starts first and curls the wall after 3 s; thread B starts later and is still running then+ std::fs::write(behave_dir().join("Vesa-a.wait"), "3").unwrap();+ std::fs::write(behave_dir().join("Vesa-a.curl"), format!("{}px_wall.html", env.fixtures)).unwrap();+ std::fs::write(behave_dir().join("Vesa-b.wait"), "8").unwrap();+ let mut events = env.state.event_sender.subscribe();+ let send = |thread: &str, task: &str| json!({"thread_id": thread, "prompt": format!("check the store page for me (task-{task})"), "sender_id": "user"});+ let newest = |env: &Env| env.state.human_steps.turn_on(&team_id).and_then(|t| t.origin).and_then(|o| o.thread_id);+ let (s, v) = call(&env.app, "POST", "/api/chat/send", Some(send(&thread_a, "a"))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ for _ in 0..50 {+ if newest(&env).is_some() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ let (s, v) = call(&env.app, "POST", "/api/chat/send", Some(send(&thread_b, "b"))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ for _ in 0..50 {+ if newest(&env).as_deref() == Some(thread_b.as_str()) {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ assert_eq!(newest(&env).as_deref(), Some(thread_b.as_str()), "thread B's turn is the newest on the team browser");+ let running: Vec<_> = env.state.turns.active_turns().into_iter().filter(|t| t.state == "running").filter_map(|t| t.thread_id).collect();+ assert!(running.contains(&thread_a) && running.contains(&thread_b), "both threads' turns are running: {running:?}");+ settle(&env).await;++ // Each thread's turn was given an address naming its own thread, the same bot in both+ assert!(read("Vesa-a", "prompt").contains(&format!("/api/sandbox/{team_id}/bot/{bot}/chat/{thread_a}")), "{}", read("Vesa-a", "prompt"));+ assert!(read("Vesa-b", "prompt").contains(&format!("/api/sandbox/{team_id}/bot/{bot}/chat/{thread_b}")), "{}", read("Vesa-b", "prompt"));+ assert_eq!(read("Vesa-a", "status1"), "200");+ let first: Value = serde_json::from_str(&read("Vesa-a", "curl1")).unwrap();+ assert_eq!((first["blocked"].clone(), first["human_step"].clone()), (json!(true), json!("asked")), "{first}");+ assert_eq!(read("Vesa-a", "status2"), "409", "the held browser waits for the person");+ let step = assert_asked_in(&env, &bot, &thread_a, &mut events).await;+ assert_eq!(step.sandbox_target.as_deref(), Some(team_id.as_str()));+ assert_eq!(step.thread_id.as_deref(), Some(thread_a.as_str()), "the step is thread A's");+ for chat in [&thread_b, &bot] {+ let msgs = env.state.db.list_messages(chat, 50).await.unwrap();+ assert!(!msgs.iter().any(|m| m.text.starts_with("Human check needed")), "no card in thread B or the DM: {msgs:?}");+ }+}+/// 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]