Skip to content

armgit / kwant

Public Imported from GitHub
0

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

Ask a CAPTCHA in the chat of the bot whose call met it (N3, N1) (#298)

Oleksandr Ivanchenko1b581a9ad2b3
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index 7686e307..bd9cd22a 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -440,7 +440,7 @@ impl TurnInput {
.or_else(|| self.team_context.as_ref().map(|t| t.id.clone()))
.unwrap_or_else(|| self.kwant.id.clone());
let api = self.browser_api_url.clone().unwrap_or_else(|| {
- format!("http://127.0.0.1:{}/api/sandbox/{}", crate::config::DEFAULT_PORT, sandbox_target)
+ format!("http://127.0.0.1:{}/api/sandbox/{}/bot/{}", crate::config::DEFAULT_PORT, sandbox_target, self.kwant.id)
});
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\
diff --git a/src/server/human_steps.rs b/src/server/human_steps.rs
index 2a59e6f2..404fe3a4 100644
--- a/src/server/human_steps.rs
+++ b/src/server/human_steps.rs
@@ -74,10 +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)>>,
+ /// The turns running on each bot browser (by sandbox target), oldest first, so a CAPTCHA met
+ /// through the shell browser API, which carries no turn of its own, is still asked of the
+ /// person in the chat of the turn that met it. A team's browser is shared, so several bots'
+ /// turns can run on one at once.
+ turns: Mutex<HashMap<String, Vec<(u64, SelfScope)>>>,
next_turn: AtomicU64,
}
@@ -138,18 +139,34 @@ impl HumanStepHub {
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.
+ /// Records a turn now running on a bot browser until the guard drops (the turn ends). Other
+ /// turns on the same browser stay recorded.
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));
+ self.turns.lock().unwrap_or_else(|e| e.into_inner()).entry(target.to_string()).or_default().push((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).
+ /// The newest live turn on this bot browser that can ask in a chat, if one runs. Only for a
+ /// caller kwnt doesn't know: with two bots on a team browser it may be the other bot's.
pub fn turn_on(&self, target: &str) -> Option<SelfScope> {
+ 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> {
+ match by {
+ Some(kwant) => self.newest_on(target, |s| s.kwant_id == kwant),
+ None => self.turn_on(target),
+ }
+ }
+
+ fn newest_on(&self, target: &str, pick: impl Fn(&SelfScope) -> bool) -> 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()))
+ turns.get(target)?.iter().rev().map(|(_, s)| s).find(|s| {
+ pick(s) && s.origin.is_some() && !s.cancel.as_ref().is_some_and(|c| c.is_cancelled())
+ }).cloned()
}
}
@@ -163,8 +180,11 @@ pub struct TurnOnBrowser {
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);
+ if let Some(on) = turns.get_mut(&self.target) {
+ on.retain(|(t, _)| *t != self.token);
+ if on.is_empty() {
+ turns.remove(&self.target);
+ }
}
}
}
@@ -814,6 +834,43 @@ mod tests {
assert!(!hub.wake("s2", Outcome::Done), "the tool call already ended");
}
+ fn turn(kwant: &str) -> SelfScope {
+ SelfScope {
+ kwant_id: kwant.into(),
+ kwant_name: kwant.into(),
+ origin: Some(Default::default()),
+ cancel: None,
+ turn_id: Some(format!("turn-{kwant}")),
+ workspace: None,
+ sandbox_target: Some("team".into()),
+ }
+ }
+
+ /// Two bots on one team browser: the bot that made the call gets its own turn, never the
+ /// other bot's; only an unknown caller falls back to the newest turn, and each turn ending
+ /// leaves the other recorded.
+ #[test]
+ fn a_shared_browser_knows_each_bots_turn() {
+ 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);
+ 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");
+ assert_eq!(of(Some("cy")), None, "a bot with no turn here is never asked in another bot's chat");
+ drop(newer);
+ assert_eq!(of(None).as_deref(), Some("ann"));
+ assert_eq!(of(Some("bob")), None);
+ 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");
+ drop((older, stopped));
+ assert!(hub.turn_on("team").is_none());
+ assert!(hub.turns.lock().unwrap().is_empty());
+ }
+
#[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.rs
index a5202d86..0da01f20 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -264,6 +264,10 @@ pub fn create_router(state: AppState) -> Router {
.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/bot/:kwant_id/navigate", post(routes::navigate_sandbox_bot))
+ .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/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.rs
index 81e88575..dbee094d 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -2475,9 +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/{}",
- state.config.port, sandbox_target
+ "http://127.0.0.1:{}/api/sandbox/{}/bot/{}",
+ state.config.port, sandbox_target, target_kwant.id
)),
thread_id: context_id,
kwant: target_kwant.clone(),
@@ -4888,63 +4889,136 @@ pub fn bot_wall_notice(kind: &str, url: &str) -> String {
)
}
-/// 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
+/// The browser API's own routes (`/api/sandbox/:id/navigate|page|act`), as the person's panel
+/// 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
/// 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
+ navigate_as(state, team_id, None, payload).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>)> {
+ page_as(state, team_id, None, query).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>)> {
+ 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.
+pub async fn navigate_sandbox_bot(
+ State(state): State<AppState>,
+ Path((team_id, kwant_id)): 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
+}
+
+/// `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)>,
+ query: Query<PageQuery>,
+) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
+ page_as(state, team_id, Some(kwant_id), 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)>,
+ payload: Json<InteractPayload>,
+) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
+ act_as(state, team_id, Some(kwant_id), payload).await
+}
+
+/// `POST /api/sandbox/:id/bot/:kwant_id/cite`.
+pub async fn cite_sandbox_bot(
+ State(state): State<AppState>,
+ Path((team_id, _kwant_id)): Path<(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>,
+ 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
+}
+
+async fn page_as(
+ state: AppState,
+ team_id: String,
+ by: Option<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
+ ask_on_wall(&state, &team_id, by.as_deref(), result).await
}
-pub async fn act_sandbox_api(
- State(state): State<AppState>,
- Path(team_id): Path<String>,
+async fn act_as(
+ state: AppState,
+ team_id: String,
+ by: Option<String>,
payload: Json<InteractPayload>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
- refuse_while_held(&state, &team_id).await?;
+ 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, result).await
+ ask_on_wall(&state, &team_id, by.as_deref(), result).await
}
+/// What a browser call is told while the browser is held for the person's step: a bot (its own
+/// route) is told to stop and end its turn; the plain route is the person's panel, so it says
+/// where their step is instead.
+pub const HELD_FOR_BOT: &str = "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.";
+pub const HELD_FOR_PERSON: &str = "This browser is set aside for the step a bot asked you to do (a sign-in or human check). Take control in the browser panel to use it, or press Done or Decline on the card in the chat first.";
+
/// 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>)> {
+async fn refuse_while_held(state: &AppState, team_id: &str, bot: bool) -> 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."})),
- ));
+ return Err((StatusCode::CONFLICT, Json(json!({"error": if bot { HELD_FOR_BOT } else { HELD_FOR_PERSON }}))));
}
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.
+/// 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.
async fn ask_on_wall(
state: &AppState,
team_id: &str,
+ by: Option<&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 };
+ let Some(turn) = state.human_steps.turn_of(team_id, by) else { return result };
match result {
Ok(Json(mut page)) => {
if page["blocked"] == json!(true) {
diff --git a/tests/captcha_turn_test.rs b/tests/captcha_turn_test.rs
index 409c678c..685c5282 100644
--- a/tests/captcha_turn_test.rs
+++ b/tests/captcha_turn_test.rs
@@ -34,7 +34,8 @@ 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
+/// 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`.
const FAKE_CLAUDE: &str = r#"#!/bin/sh
@@ -44,6 +45,7 @@ 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.wait" ]; then sleep "$(cat "$dir/$me.wait")"; fi
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")
@@ -171,6 +173,11 @@ fn open_steps(steps: Vec<HumanStep>, bot: &str) -> Vec<HumanStep> {
/// 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 {
+ assert_asked_in(env, bot, bot, events).await
+}
+
+/// [`assert_asked`] for a turn in `chat` (the bot's DM, or one of its threads).
+async fn assert_asked_in(env: &Env, bot: &str, chat: &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();
@@ -179,8 +186,8 @@ async fn assert_asked(env: &Env, bot: &str, events: &mut tokio::sync::broadcast:
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 msgs = env.state.db.list_messages(chat, 50).await.unwrap();
+ assert!(msgs.iter().any(|m| m.id == card.id), "the card is in the chat of the turn");
let mut notified = false;
while let Ok(ev) = events.try_recv() {
if let RuntimeEvent::Notify { kind, kwant_id, title, .. } = ev {
@@ -242,6 +249,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_eq!(read("Ossi", "status1"), "200");
let first: Value = serde_json::from_str(&read("Ossi", "curl1")).unwrap();
assert_eq!(first["blocked"], true, "{first}");
@@ -251,6 +259,69 @@ async fn a_captcha_met_through_the_shell_browser_api_asks_the_person() {
assert_eq!(read("Ossi", "status2"), "409");
assert!(read("Ossi", "curl2").contains("waiting on the person"));
assert_asked(&env, &bot, &mut events).await;
+
+ // The person's own panel (the plain route) is told where their step is, not told to end a turn
+ let (s, v) = call(&env.app, "POST", &format!("/api/sandbox/{bot}/navigate"), Some(json!({"url": format!("{}px_wall.html", env.fixtures)}))).await;
+ assert_eq!(s, StatusCode::CONFLICT, "{v}");
+ let error = v["error"].as_str().unwrap();
+ assert_eq!(error, kwnt::server::routes::HELD_FOR_PERSON);
+ assert!(error.contains("Take control") && !error.contains("end your turn"), "{error}");
+}
+
+/// Two bots of one team share its browser and run at once (Rigel's N3, Oleks's "mixing
+/// contexts"): each works in its own team thread, the older turn's curl meets the CAPTCHA while
+/// the newer bot's turn is still running. The card, its notification and the browser hold are
+/// the older bot's, in the older bot's thread; the newer bot's thread gets nothing.
+#[tokio::test]
+async fn a_captcha_one_bot_meets_on_a_shared_team_browser_is_asked_in_that_bots_chat() {
+ 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 (older, newer) = (add_bot(&env, "Tove").await, add_bot(&env, "Ulla").await);
+ let (s, team) = call(&env.app, "POST", "/api/teams", Some(json!({"name": "shoppers", "lead_kwant_id": older, "member_kwants": [older, newer]}))).await;
+ assert!(s.is_success(), "{s} {team}");
+ let team_id = team["id"].as_str().or(team["team"]["id"].as_str()).unwrap().to_string();
+ let tove = env.state.db.create_thread(&older, "Store check", "chat", Some(&team_id), "user").await.unwrap().id;
+ let ulla = env.state.db.create_thread(&newer, "Price list", "chat", Some(&team_id), "user").await.unwrap().id;
+ // Tove starts first and curls the wall after 3 s; Ulla starts later and is still running then
+ std::fs::write(behave_dir().join("Tove.wait"), "3").unwrap();
+ std::fs::write(behave_dir().join("Tove.curl"), format!("{}px_wall.html", env.fixtures)).unwrap();
+ std::fs::write(behave_dir().join("Ulla.wait"), "8").unwrap();
+ let mut events = env.state.event_sender.subscribe();
+ let send = |thread: &str| json!({"thread_id": thread, "prompt": "check the store page for me", "sender_id": "user"});
+ let (s, v) = call(&env.app, "POST", "/api/chat/send", Some(send(&tove))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ for _ in 0..50 {
+ if env.state.human_steps.turn_on(&team_id).is_some() {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ let (s, v) = call(&env.app, "POST", "/api/chat/send", Some(send(&ulla))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ for _ in 0..50 {
+ if env.state.human_steps.turn_on(&team_id).is_some_and(|t| t.kwant_id == newer) {
+ break;
+ }
+ 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");
+ 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");
+ 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;
+ assert_eq!(step.sandbox_target.as_deref(), Some(team_id.as_str()));
+ assert_eq!(step.thread_id.as_deref(), Some(tove.as_str()), "the step is Tove's thread's");
+ let all = env.state.db.list_human_steps(None, None, None).await.unwrap();
+ assert!(all.iter().all(|s| s.kwant_id == older), "nothing is asked for Ulla: {all:?}");
+ for chat in [&ulla, &newer] {
+ 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 Ulla's chats: {msgs:?}");
+ }
}
/// Without a turn on the browser (someone curling it by hand) nobody is asked, and the answer