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
One sign-in card per site: a second turn waits on the open ask, and Decline stays declined (#273)
Oleksandr Ivanchenko6fde86c38528
diff --git a/src/db/human_steps.rs b/src/db/human_steps.rsindex db9139aa..1567e5c7 100644--- a/src/db/human_steps.rs+++ b/src/db/human_steps.rs@@ -121,6 +121,13 @@ pub fn clean_request(kind: &str, reason: &str, url: Option<&str>) -> Result<(StrOk((kind.to_string(), reason, url))}+/// The site a sign-in is for, as the prefix its kept URLs start with (`https://host[:port]/`).+/// `None` when the URL has no usable origin.+pub fn sign_in_site(url: &str) -> Option<String> {+ let origin = url::Url::parse(url).ok()?.origin();+ origin.is_tuple().then(|| format!("{}/", origin.ascii_serialization()))+}+/// Where a step is asked.#[derive(Debug, Clone, Default)]pub struct HumanStepPlace {@@ -132,9 +139,20 @@ pub struct HumanStepPlace {pub sandbox_target: Option<String>,}-/// A new step (with `true`), or the turn's step that is already open (with `false`).+/// A new step (with `true`), or one already open that the ask gets back (with `false`): the+/// turn's own, or the bot's open sign-in for the same site in the same chat.pub type Created = (HumanStep, bool, Option<Message>);+/// SQL matching the bot's open sign-in for a site in one chat, from the placeholders of the bot,+/// channel, direct chat, thread, bot browser and site (`sign_in_site`; NULL matches nothing).+fn same_sign_in([kwant, channel, direct, thread, browser, site]: [&str; 6]) -> String {+ format!(+ "status = 'open' AND {site} IS NOT NULL AND kind = 'sign_in' AND kwant_id = {kwant} AND channel_id IS {channel} \+ AND direct_kwant_id IS {direct} AND thread_id IS {thread} AND sandbox_target IS {browser} \+ AND substr(url, 1, length({site})) = {site}"+ )+}+const CREATE_HUMAN_STEPS: &str = "CREATE TABLE IF NOT EXISTS human_steps (id TEXT PRIMARY KEY,kwant_id TEXT NOT NULL,@@ -180,7 +198,10 @@ impl Database {/// Saves a step together with the chat message that shows it (built by `card`), in one/// transaction. A turn that asks again while its step is open gets that step back, so a- /// retrying agent (or the CAPTCHA check firing on every page) doesn't pile up cards.+ /// retrying agent (or the CAPTCHA check firing on every page) doesn't pile up cards. A sign-in+ /// also comes back to another turn of the same bot in the same chat while it is open for the+ /// same site (scheme, host and port): two turns running at once (the person's, and one a+ /// closed CAPTCHA step started) would otherwise show the person two identical cards.#[allow(clippy::too_many_arguments)]pub async fn create_human_step_with_card(&self,@@ -194,14 +215,17 @@ impl Database {) -> Result<Created, HumanStepError> {let mut tx = self.pool.begin().await?;let get = "SELECT * FROM human_steps WHERE id = ?";+ let site = if kind == "sign_in" { url.and_then(sign_in_site) } else { None };// Writes first so the transaction holds SQLite's write lock before it readslet id = Uuid::new_v4().to_string();- let inserted = sqlx::query(+ let inserted = sqlx::query(&format!("INSERT INTO human_steps (id, kwant_id, channel_id, direct_kwant_id, thread_id, turn_id, kind, reason, url, sandbox_target, source, status, created_at, target)SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, 'open', ?12, ?14WHERE (SELECT COUNT(*) FROM human_steps WHERE kwant_id = ?2 AND status = 'open') < ?13- AND NOT EXISTS (SELECT 1 FROM human_steps WHERE status = 'open' AND ?6 IS NOT NULL AND turn_id = ?6)",- )+ AND NOT EXISTS (SELECT 1 FROM human_steps WHERE status = 'open' AND ?6 IS NOT NULL AND turn_id = ?6)+ AND NOT EXISTS (SELECT 1 FROM human_steps WHERE {})",+ same_sign_in(["?2", "?3", "?4", "?5", "?10", "?15"])+ )).bind(&id).bind(&place.kwant_id).bind(&place.channel_id)@@ -216,10 +240,11 @@ impl Database {.bind(Utc::now()).bind(MAX_OPEN_PER_KWANT).bind(target)+ .bind(&site).execute(&mut *tx).await?;if inserted.rows_affected() == 0 {- let existing = match &place.turn_id {+ let mut existing = match &place.turn_id {Some(t) => {sqlx::query_as::<_, HumanStep>("SELECT * FROM human_steps WHERE status = 'open' AND turn_id = ? LIMIT 1").bind(t)@@ -228,6 +253,20 @@ impl Database {}None => None,};+ if existing.is_none() && site.is_some() {+ existing = sqlx::query_as::<_, HumanStep>(&format!(+ "SELECT * FROM human_steps WHERE {} ORDER BY created_at LIMIT 1",+ same_sign_in(["?1", "?2", "?3", "?4", "?5", "?6"])+ ))+ .bind(&place.kwant_id)+ .bind(&place.channel_id)+ .bind(&place.direct_kwant_id)+ .bind(&place.thread_id)+ .bind(&place.sandbox_target)+ .bind(&site)+ .fetch_optional(&mut *tx)+ .await?;+ }tx.commit().await?;return match existing {Some(step) => Ok((step, false, None)),@@ -365,6 +404,59 @@ mod tests {assert_eq!(db.list_human_steps(Some("open"), Some("k"), None).await.unwrap().len() as i64, MAX_OPEN_PER_KWANT);}+ #[test]+ fn a_sign_in_site_is_its_scheme_host_and_port() {+ assert_eq!(sign_in_site("https://www.instagram.com/accounts/login/").as_deref(), Some("https://www.instagram.com/"));+ assert_eq!(sign_in_site("https://example.com:8443/login").as_deref(), Some("https://example.com:8443/"));+ assert_eq!(sign_in_site("https://example.com:443/login").as_deref(), Some("https://example.com/"));+ assert_eq!(sign_in_site("not a url"), None);+ }++ #[tokio::test]+ async fn an_open_sign_in_comes_back_to_another_turn_of_the_bot_in_the_same_chat_for_the_same_site() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let in_chat = |kwant: &str, channel: &str, turn: &str| HumanStepPlace {+ kwant_id: kwant.into(),+ channel_id: Some(channel.into()),+ turn_id: Some(turn.into()),+ sandbox_target: Some(channel.into()),+ ..Default::default()+ };+ let ask = |place: HumanStepPlace, kind: &'static str, url: Option<&'static str>| {+ let db = db.clone();+ async move { db.create_human_step_with_card(&place, kind, "Sign in", url, None, "bot", |_| None).await.unwrap() }+ };+ let login = Some("https://www.instagram.com/accounts/login/");+ let (first, new, _) = ask(in_chat("k", "c", "t1"), "sign_in", login).await;+ assert!(new);+ // Another turn, same bot, chat and site (another page of it): the same step, no new card+ let (again, new, card) = ask(in_chat("k", "c", "t2"), "sign_in", Some("https://www.instagram.com/")).await;+ assert!(!new && card.is_none());+ assert_eq!(again.id, first.id);+ assert_eq!(again.turn_id.as_deref(), Some("t1"), "it stays the first turn's step");+ // Anything else is its own step: another site, scheme or port, another chat, another bot,+ // another kind, or a sign-in without a URL+ for (place, kind, url) in [+ (in_chat("k", "c", "t3"), "sign_in", Some("https://www.tiktok.com/login")),+ (in_chat("k", "c", "t4"), "sign_in", Some("http://www.instagram.com/accounts/login/")),+ (in_chat("k", "c", "t5"), "sign_in", Some("https://www.instagram.com:8443/accounts/login/")),+ (in_chat("k", "c2", "t6"), "sign_in", login),+ (in_chat("k2", "c", "t7"), "sign_in", login),+ (in_chat("k2", "c", "t8"), "two_factor", login),+ (in_chat("k3", "c", "t9"), "sign_in", None),+ (in_chat("k3", "c", "t10"), "sign_in", None),+ ] {+ let (s, new, _) = ask(place, kind, url).await;+ assert!(new, "{kind} {url:?} in {:?} for {}", s.channel_id, s.kwant_id);+ }+ // Once the person declined it, a later ask is a new step (the bot was told not to ask)+ assert!(db.close_human_step(&first.id, "declined").await.unwrap());+ let (after, new, _) = ask(in_chat("k", "c", "t11"), "sign_in", login).await;+ assert!(new);+ assert_ne!(after.id, first.id);+ }+#[tokio::test]async fn old_tables_gain_target_and_the_auto_statuses_and_keep_their_rows() {let tmp = tempfile::tempdir().unwrap();diff --git a/src/server/human_steps.rs b/src/server/human_steps.rsindex 1f4eeb83..b6e3a56d 100644--- a/src/server/human_steps.rs+++ b/src/server/human_steps.rs@@ -43,6 +43,9 @@ pub enum Outcome {ResolvedAuto,/// Nobody solved the CAPTCHA within the time limit.TimedOut,+ /// Not an answer: another turn of the bot in this chat already asked for the same sign-in and+ /// is waiting on it, so this turn steps aside. The step stays open.+ AlreadyAsked,}impl Outcome {@@ -52,6 +55,7 @@ impl Outcome {Outcome::Declined => "declined",Outcome::ResolvedAuto => "resolved_auto",Outcome::TimedOut => "timed_out",+ Outcome::AlreadyAsked => "open",}}}@@ -292,8 +296,8 @@ fn outcome_text(outcome: Option<Outcome>, captcha: bool) -> String {Some(Outcome::Done) => "The person says the step is done and handed the browser back. Look at the page \again (browser_page) before you continue.".into(),- Some(Outcome::Declined) => "The person declined the step. Don't ask again: carry on without it if you can, or \- end your turn and say plainly what is blocked."+ Some(Outcome::Declined) => "The person declined the step. Don't ask for it again in this turn unless the person \+ brings it up: carry on without it if you can, or end your turn and say plainly what is blocked.".into(),Some(Outcome::ResolvedAuto) => "The human check is gone from the page (solved or passed), and the browser is \yours again. Look at the page again (browser_page) and continue."@@ -302,6 +306,10 @@ fn outcome_text(outcome: Option<Outcome>, captcha: bool) -> String {it or ask again now: skip this site and use another source (an official API or a site you're signed in to), \or tell the person you'll try this site later.".into(),+ Some(Outcome::AlreadyAsked) => "You already asked the person for this sign-in in another turn in this chat, and \+ that turn is waiting for their answer, so no new card was made. Don't ask again: end your turn now, at most \+ with one line saying you're waiting for them to sign in. The other turn carries on once they answer."+ .into(),None if captcha => "The person hasn't solved the CAPTCHA yet. Don't ask again: end your turn now with a short \note on what you're waiting for. The step closes by itself once the check is gone or the time runs out, \and you'll get a new turn either way."@@ -373,7 +381,14 @@ pub async fn raise(});}};- // The turn asked again for a step it already has open: wait on that one+ // Another turn of this bot asked for the same sign-in and still waits on it: one card and one+ // waiter, and this turn steps aside instead of the person being asked twice+ if !is_new && step.turn_id != place.turn_id && hub.is_waiting(&step.id) {+ 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));+ }+ // The turn asked again for a step it already has open (or one no turn waits on any more):+ // wait on that onelet mut rx = match waiter {Some((_, rx)) => rx,None => hub.register(&step.id),@@ -639,7 +654,7 @@ async fn resume(state: &AppState, s: &HumanStep, outcome: Outcome) {s.reason),Outcome::Declined => format!(- "[The person declined the browser step you asked for earlier]\nStep: {}\n\nDon't ask again. Carry on without it if you can, or say plainly what is blocked.",+ "[The person declined the browser step you asked for earlier]\nStep: {}\n\nDon't ask for it again unless the person brings it up. Carry on without it if you can, or say plainly what is blocked.",s.reason),Outcome::ResolvedAuto => format!(@@ -651,6 +666,8 @@ async fn resume(state: &AppState, s: &HumanStep, outcome: Outcome) {continue with another source (an official API or a site you're signed in to), or tell the person you'll try this site later.",s.reason),+ // Not an answer: nothing to tell a new turn.+ Outcome::AlreadyAsked => return,};tokio::spawn(async move {let _job = job;@@ -687,7 +704,11 @@ mod tests {#[test]fn the_agent_hears_each_outcome_plainly() {assert!(outcome_text(Some(Outcome::Done), false).contains("Look at the page"));- assert!(outcome_text(Some(Outcome::Declined), false).contains("declined"));+ let declined = outcome_text(Some(Outcome::Declined), false);+ assert!(declined.contains("declined") && declined.contains("Don't ask for it again in this turn unless the person brings it up"));+ let asked = outcome_text(Some(Outcome::AlreadyAsked), false);+ assert!(asked.contains("already asked") && asked.contains("Don't ask again") && asked.contains("end your turn"));+ assert_eq!(Outcome::AlreadyAsked.status(), "open", "the step stays open for the turn that waits on it");assert!(outcome_text(None, false).contains("end your turn"));assert!(outcome_text(Some(Outcome::ResolvedAuto), true).contains("continue"));let timed_out = outcome_text(Some(Outcome::TimedOut), true);diff --git a/tests/human_step_test.rs b/tests/human_step_test.rsindex 81ca2b8d..ae54a21c 100644--- a/tests/human_step_test.rs+++ b/tests/human_step_test.rs@@ -1,11 +1,14 @@//! Human steps: `request_human_step` pauses the turn with a card and a `human_step`//! notification, Done or Decline resumes it with that outcome, Stop cancels it, a late answer-//! starts a new turn, and the bot's browser tools are refused while a step is open.+//! starts a new turn, and the bot's browser tools are refused while a step is open. Two turns of+//! a bot in one chat asking for the same sign-in share one step.mod common;use axum::http::StatusCode;use common::*;+use kwnt::server::continuity::{SelfScope, TurnOrigin};+use kwnt::server::mcp_runtime;use kwnt::RuntimeEvent;use serde_json::{json, Value};use std::time::Duration;@@ -169,3 +172,145 @@ async fn input_and_routes_are_checked() {assert_eq!(call_remote(&env.app, m, u).await, StatusCode::UNAUTHORIZED, "{m} {u}");}}++/// A turn of bot `a` in its direct chat (the person's, or one a closed step started), as the CLI+/// sees it: its token for kwnt's self tools.+async fn turn_token(env: &Env, turn_id: &str) -> String {+ let bot = env.state.db.get_kwant(&env.a).await.unwrap().unwrap();+ let scope = SelfScope {+ kwant_id: bot.id.clone(),+ kwant_name: bot.name.clone(),+ origin: Some(TurnOrigin { direct_kwant_id: Some(bot.id.clone()), ..Default::default() }),+ cancel: Some(tokio_util::sync::CancellationToken::new()),+ turn_id: Some(turn_id.into()),+ sandbox_target: Some(bot.id.clone()),+ ..Default::default()+ };+ mcp_runtime::prepare_turn_with_self(&env.state, &bot, Some(turn_id.into()), None, Some(scope)).await.unwrap().1+}++/// The turn asks for a sign-in at `url`, in the background as the CLI would while it waits;+/// gives the tool's text and whether it was an error.+fn ask_sign_in(env: &Env, token: &str, url: &str) -> tokio::task::JoinHandle<(String, bool)> {+ let (app, auth) = (env.app.clone(), format!("Bearer {token}"));+ let args = json!({"kind": "sign_in", "reason": "Please sign in to Instagram in the browser panel", "url": url});+ tokio::spawn(async move {+ let body = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "request_human_step", "arguments": args}});+ let (code, v) = call_with(&app, "POST", "/api/mcp/self", Some(body), &[("authorization", auth.as_str())]).await;+ assert_eq!(code, StatusCode::OK, "{v}");+ (v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string(), v["result"]["isError"].as_bool().unwrap_or(false))+ })+}++async fn finished(task: tokio::task::JoinHandle<(String, bool)>) -> (String, bool) {+ tokio::time::timeout(Duration::from_secs(20), task).await.expect("the tool call never hangs").unwrap()+}++async fn sign_in_cards(env: &Env) -> usize {+ messages(env, &env.a).await.iter().filter(|m| m.text.starts_with("Sign in needed")).count()+}++/// Rigel's QA of #269: the person's turn and a turn a closed CAPTCHA step started both asked for+/// the Instagram sign-in, and the person got two identical cards.+#[tokio::test]+async fn a_second_turn_asking_for_the_same_sign_in_steps_aside_and_the_first_hears_the_answer() {+ let env = setup().await;+ let first = ask_sign_in(&env, &turn_token(&env, "turn-person").await, "https://www.instagram.com/accounts/login/");+ let s = open_step(&env, &env.a).await;+ let id = s["id"].as_str().unwrap().to_string();+ wait_for("the first turn waiting", || async { step(&env, &id).await["waiting"] == true }).await;++ // Same site, another page of it, another turn of the same bot in the same chat+ let second = ask_sign_in(&env, &turn_token(&env, "turn-resumed").await, "https://www.instagram.com/?next=x");+ let (text, is_error) = finished(second).await;+ assert!(!is_error, "{text}");+ assert!(text.contains("already asked the person for this sign-in") && text.contains("Don't ask again"), "{text}");+ let (_, open) = call(&env.app, "GET", &format!("/api/human-steps?status=open&context_id={}", env.a), None).await;+ assert_eq!(open.as_array().unwrap().len(), 1, "one step: {open}");+ assert_eq!(sign_in_cards(&env).await, 1, "one card");+ assert_eq!(step(&env, &id).await["waiting"], true, "the first turn still waits on it");++ let (code, v) = call(&env.app, "POST", &format!("/api/human-steps/{id}/decline"), None).await;+ assert_eq!(code, StatusCode::OK, "{v}");+ assert_eq!(v["resumed"], "turn");+ let (text, is_error) = finished(first).await;+ assert!(!is_error, "{text}");+ assert!(text.contains("declined the step") && text.contains("Don't ask for it again in this turn unless the person brings it up"), "{text}");+}++/// A sign-in no turn waits on any more (the asking turn's wait ran out) is picked up by the next+/// turn that asks for the same site: it waits on that step and hears the answer.+#[tokio::test]+async fn a_turn_asking_for_a_sign_in_nobody_waits_on_any_more_waits_on_that_step() {+ let env = setup().await;+ env.state.human_steps.set_wait(Duration::from_millis(300));+ let (text, _) = finished(ask_sign_in(&env, &turn_token(&env, "turn-early").await, "https://www.instagram.com/accounts/login/")).await;+ assert!(text.contains("hasn't done the step yet"), "{text}");+ let s = open_step(&env, &env.a).await;+ let id = s["id"].as_str().unwrap().to_string();+ assert_eq!(step(&env, &id).await["waiting"], false);++ env.state.human_steps.set_wait(Duration::from_secs(30));+ let later = ask_sign_in(&env, &turn_token(&env, "turn-later").await, "https://www.instagram.com/accounts/login/");+ wait_for("the later turn waiting", || async { step(&env, &id).await["waiting"] == true }).await;+ assert_eq!(sign_in_cards(&env).await, 1, "no second card");+ let (code, v) = call(&env.app, "POST", &format!("/api/human-steps/{id}/done"), None).await;+ assert_eq!(code, StatusCode::OK, "{v}");+ assert_eq!(v["resumed"], "turn");+ let (text, is_error) = finished(later).await;+ assert!(!is_error && text.contains("The person says the step is done"), "{text}");+}++#[tokio::test]+async fn a_late_decline_tells_the_new_turn_not_to_ask_again() {+ let env = setup().await;+ env.state.human_steps.set_wait(Duration::from_millis(300));+ send_direct(&env, &env.a, &format!("{} REPLYTAG:h5", step_marker("sign_in", "LATE_DECLINE log in")), json!({})).await;+ wait_reply(&env, &env.a, "answer h5").await;+ let s = open_step(&env, &env.a).await;+ let (code, v) = call(&env.app, "POST", &format!("/api/human-steps/{}/decline", s["id"].as_str().unwrap()), None).await;+ assert_eq!(code, StatusCode::OK, "{v}");+ assert_eq!(v["resumed"], "new_turn");+ wait_for("the resumed turn", || async { !invocations_with("Step: LATE_DECLINE log in").is_empty() }).await;+ let prompt = invocations_with("Step: LATE_DECLINE log in").remove(0);+ assert!(prompt.contains("declined the browser step") && prompt.contains("Don't ask for it again unless the person brings it up"), "{prompt}");+}++/// Rigel's QA of #273: the dedupe is per site. While the bot's Instagram sign-in is open and+/// waited on, another turn of the same bot in the same chat asking for TikTok gets its own step+/// and card, waits on it, and neither answer reaches the other turn.+#[tokio::test]+async fn a_sign_in_for_another_site_gets_its_own_step_while_one_is_open() {+ let env = setup().await;+ let instagram = ask_sign_in(&env, &turn_token(&env, "turn-person").await, "https://www.instagram.com/accounts/login/");+ let s = open_step(&env, &env.a).await;+ let ig = s["id"].as_str().unwrap().to_string();+ wait_for("the Instagram turn waiting", || async { step(&env, &ig).await["waiting"] == true }).await;++ let tiktok = ask_sign_in(&env, &turn_token(&env, "turn-resumed").await, "https://www.tiktok.com/login");+ let open_steps = || async {+ let (_, open) = call(&env.app, "GET", &format!("/api/human-steps?status=open&context_id={}", env.a), None).await;+ open.as_array().unwrap().clone()+ };+ wait_for("a second open step", || async { open_steps().await.len() == 2 }).await;+ let tt = open_steps().await.into_iter().find(|s| s["id"] != ig.as_str()).unwrap();+ let tt_id = tt["id"].as_str().unwrap().to_string();+ assert!(tt["url"].as_str().unwrap_or("").starts_with("https://www.tiktok.com/"), "{tt}");+ wait_for("the TikTok turn waiting", || async { step(&env, &tt_id).await["waiting"] == true }).await;+ assert!(!tiktok.is_finished(), "the TikTok ask was not stepped aside as AlreadyAsked");+ assert_eq!(sign_in_cards(&env).await, 2, "one card per site");++ let (code, v) = call(&env.app, "POST", &format!("/api/human-steps/{tt_id}/done"), None).await;+ assert_eq!(code, StatusCode::OK, "{v}");+ assert_eq!(v["resumed"], "turn");+ let (text, is_error) = finished(tiktok).await;+ assert!(!is_error && text.contains("The person says the step is done"), "{text}");+ assert!(!text.contains("already asked"), "{text}");+ assert_eq!(step(&env, &ig).await["step"]["status"], "open", "Instagram is still open");+ assert!(!instagram.is_finished(), "the TikTok answer did not reach the Instagram turn");++ let (code, v) = call(&env.app, "POST", &format!("/api/human-steps/{ig}/decline"), None).await;+ assert_eq!(code, StatusCode::OK, "{v}");+ let (text, is_error) = finished(instagram).await;+ assert!(!is_error && text.contains("declined the step"), "{text}");+}