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
Automation Discovery hardening: cap and rollback tests, CAPTCHA timeout race
Lin (kwant bot)233f82af639a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9a609806..273ff635 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -51,6 +51,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).- **kwant.si footer says "Made in Germany with ❤️".** The line sits under the trademark note on everypage; screen readers read it as "Made in Germany with love".+### Fixed+- **A CAPTCHA nobody solved is always reported as timed out.** When the time limit ran out, the bot+ could sometimes be told to keep waiting for a step that was already over, if the page watcher was+ slow on a busy machine. The bot's own wait now closes the step as timed out once the limit has+ passed, so the bot moves on straight away.+## [Mac 0.4.1] - 2026-10-30### Changeddiff --git a/src/server/human_steps.rs b/src/server/human_steps.rsindex 63eda718..1f4eeb83 100644--- a/src/server/human_steps.rs+++ b/src/server/human_steps.rs@@ -380,11 +380,12 @@ pub async fn raise(};let _guard = WaiterGuard { hub, id: step.id.clone() };let mut wait = hub.wait();+ let mut captcha_deadline = None;if step.kind == "captcha" {let limit = captcha_timeout(state).await;- let left = (step.created_at + chrono::Duration::from_std(limit).unwrap_or_default() - chrono::Utc::now())- .to_std()- .unwrap_or_default();+ let deadline = step.created_at + chrono::Duration::from_std(limit).unwrap_or_default();+ captcha_deadline = Some(deadline);+ let left = (deadline - chrono::Utc::now()).to_std().unwrap_or_default();// A little past the limit, so the watcher's timed_out wakes the turn before the wait endswait = wait.min(left + hub.probe_interval() * 2);}@@ -431,7 +432,17 @@ pub async fn raise(_ = tokio::time::sleep(wait) => {hub.take(&step.id);// An answer that arrived just as the wait ran out still counts- Ok(rx.try_recv().ok())+ 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() {+ tracing::info!(human_step_id = %step.id, "CAPTCHA step timed out at the end of the turn's wait");+ return Ok(Some(Outcome::TimedOut));+ }+ Ok(None)}}}diff --git a/tests/automation_discovery_test.rs b/tests/automation_discovery_test.rsindex 1e9be892..fe02117a 100644--- a/tests/automation_discovery_test.rs+++ b/tests/automation_discovery_test.rs@@ -794,3 +794,117 @@ async fn keep_checks_saves_the_real_spec_not_the_mask() {let (checks,): (String,) = sqlx::query_as("SELECT checks FROM routines WHERE id = ?").bind(rid).fetch_one(&e.pool).await.unwrap();assert!(checks.contains(secret) && !checks.contains("[redacted]"), "{checks}");}++// Rigel's re-test of #165: what counts toward the cap, and replace_offer losing to the person++#[tokio::test]+async fn an_offer_ended_without_a_replacement_still_counts_for_its_day() {+ let e = setup().await;+ let a = bot(&e, "Ana").await;+ let space = SpaceId::default_space();+ person(&e, "POST", "/api/settings", Some(json!({"automation_discovery": "on", "automation_discovery_daily_cap": 1}))).await;+ mondays(&e, &a, "Weekly report", day("2026-10-12")).await;+ let mut rx = e.state.event_sender.subscribe();+ let monday = berlin(day("2026-10-12"), 10, 0);+ let old = discovery::scan_space(&e.state, &space, TZ, monday).await.unwrap().offered[0].clone();+ assert!(e.state.db.end_offer(&old, "superseded", monday + Duration::hours(1)).await.unwrap());++ // Its day's one offer was used: two hours on, nothing new, and no live offer+ let s = discovery::scan_space(&e.state, &space, TZ, monday + Duration::hours(2)).await.unwrap();+ assert!(s.offered.is_empty(), "{s:?}");+ assert_eq!(live(&e).await, 0);+ // A day on, the habit is offered again+ let s = discovery::scan_space(&e.state, &space, TZ, monday + Duration::hours(25)).await.unwrap();+ assert_eq!((s.offered.len(), live(&e).await), (1, 1), "{s:?}");+ assert_eq!(suggested(&mut rx).len(), 2);+ assert_eq!(e.state.db.suggestion_stats(space.as_str(), monday + Duration::hours(25)).await.unwrap().offered_30d, 2);+}++#[tokio::test]+async fn repeated_replacements_never_add_a_live_offer_or_a_notification() {+ let e = setup().await;+ let space = SpaceId::default_space();+ person(&e, "POST", "/api/settings", Some(json!({"automation_discovery": "on", "automation_discovery_daily_cap": 10}))).await;+ let mut owners = Vec::new();+ for (k, name) in ["Ana", "Ben", "Cleo", "Dan", "Eve"].iter().enumerate() {+ owners.push(habit_on(&e, k as i64, name).await);+ }+ let other = bot(&e, "Finn").await;+ let mut rx = e.state.event_sender.subscribe();+ let now = Utc::now();+ let s = discovery::scan_space(&e.state, &space, TZ, now).await.unwrap();+ assert_eq!((s.offered.len(), live(&e).await, suggested(&mut rx).len()), (5, 5, 5), "{s:?}");++ // Ana's habit moves between Ana and Finn six times: replaced each time, the space stays at 5+ for round in 1..=6 {+ let (from, to) = if round % 2 == 1 { (&owners[0], &other) } else { (&other, &owners[0]) };+ sqlx::query("UPDATE tasks SET owner_kwant_id = ? WHERE owner_kwant_id = ?").bind(&to.id).bind(&from.id).execute(&e.pool).await.unwrap();+ let s = discovery::scan_space(&e.state, &space, TZ, now + Duration::hours(round)).await.unwrap();+ assert_eq!((s.superseded.len(), s.offered.len(), live(&e).await), (1, 0, 5), "round {round}: {s:?}");+ assert!(suggested(&mut rx).is_empty(), "round {round}");+ }+ assert_eq!(count(&e, "routine_suggestions").await, 11);+ assert_eq!(e.state.db.suggestion_stats(space.as_str(), now + Duration::hours(6)).await.unwrap().offered_30d, 5);++ // A sixth habit still finds the space full+ habit_on(&e, 5, "Gus").await;+ let s = discovery::scan_space(&e.state, &space, TZ, now + Duration::hours(7)).await.unwrap();+ assert!(s.offered.is_empty() && s.skipped.iter().any(|k| k.title.starts_with("Gus")), "{s:?}");+ assert_eq!((live(&e).await, suggested(&mut rx).len()), (5, 0));+}++/// What a scan mined for `space` at `now`, before it stored anything: the habit as it is now.+async fn mined(e: &Env, space: &SpaceId, now: DateTime<Utc>) -> kwnt::automation_discovery::Scan {+ let db = &e.state.db;+ let tasks = db.discovery_tasks(space.as_str(), now).await.unwrap();+ let checks = db.discovery_checks(space.as_str(), now).await.unwrap();+ let routines = db.discovery_routines(space.as_str()).await.unwrap();+ let past = db.discovery_past(space.as_str(), now).await.unwrap();+ let bots = db.list_kwants(space).await.unwrap().into_iter().map(|k| k.id).collect();+ kwnt::automation_discovery::mine(&kwnt::automation_discovery::Input {+ tz: TZ,+ now,+ tasks: &tasks,+ checks: &checks,+ routines: &routines,+ bots: &bots,+ past: &past,+ daily_cap: 2,+ max_live: kwnt::automation_discovery::MAX_LIVE_PER_SPACE,+ })+}++#[tokio::test]+async fn a_replacement_loses_to_an_accept_or_dismiss_that_came_first() {+ for decision in ["accept", "dismiss"] {+ let e = setup().await;+ let a = bot(&e, "Ana").await;+ let b = bot(&e, "Ben").await;+ let space = SpaceId::default_space();+ discovery_on(&e).await;+ mondays(&e, &a, "Weekly report", day("2026-10-12")).await;+ let monday = berlin(day("2026-10-12"), 10, 0);+ let old = discovery::scan_space(&e.state, &space, TZ, monday).await.unwrap().offered[0].clone();++ // A scan mines the habit, now Ben's, while the offer is live...+ sqlx::query("UPDATE tasks SET owner_kwant_id = ? WHERE owner_kwant_id = ?").bind(&b.id).bind(&a.id).execute(&e.pool).await.unwrap();+ let later = monday + Duration::hours(2);+ let changed = mined(&e, &space, later).await.live.into_iter().next().expect("the habit is still live");+ assert_eq!(changed.kwant_id, b.id);+ // ...the person decides it before the scan replaces it...+ let (status, _, v) = call_with(&e.app, "POST", &format!("{LIST}/{old}/{decision}"), None, Some("k1"), Some(json!({}))).await;+ assert!(status.is_success(), "{decision}: {status} {v}");+ let before = (written_rows(&e).await, count(&e, "routines").await, events(&e, &old).await);++ // ...so the replacement writes nothing, and the decision stands+ assert_eq!(e.state.db.replace_offer(&old, space.as_str(), &changed, later).await.unwrap(), None, "{decision}");+ assert_eq!((written_rows(&e).await, count(&e, "routines").await, events(&e, &old).await), before, "{decision}");+ let row = e.state.db.get_suggestion(&old).await.unwrap().unwrap();+ assert_eq!(row.status, if decision == "accept" { "accepted" } else { "dismissed" });+ assert_eq!((row.kwant_id, live(&e).await), (a.id.clone(), 0));+ if decision == "accept" {+ let (sid,): (Option<String>,) = sqlx::query_as("SELECT suggestion_id FROM routines").fetch_one(&e.pool).await.unwrap();+ assert_eq!(sid.as_deref(), Some(old.as_str()));+ }+ }+}diff --git a/tests/captcha_test.rs b/tests/captcha_test.rsindex 0dc1d32f..7b1dd749 100644--- a/tests/captcha_test.rs+++ b/tests/captcha_test.rs@@ -252,6 +252,12 @@ async fn post(app: &Router, uri: &str, token: &str, body: Value) -> Value {}async fn turn(state: &AppState, turn_id: &str) -> String {+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);+ turn_in(state, turn_id, Some(bot.id)).await+}++/// A turn of the first bot, in bot browser `sandbox_target` (none: no browser, so no watcher).+async fn turn_in(state: &AppState, turn_id: &str, sandbox_target: Option<String>) -> String {let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);let scope = SelfScope {kwant_id: bot.id.clone(),@@ -259,7 +265,7 @@ async fn turn(state: &AppState, turn_id: &str) -> String {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()),+ sandbox_target,..Default::default()};mcp_runtime::prepare_turn_with_self(state, &bot, Some(turn_id.into()), None, Some(scope)).await.unwrap().1@@ -364,6 +370,41 @@ async fn a_captcha_step_nobody_solves_times_out_without_a_browser() {assert_eq!(state.db.get_human_step(&step.id).await.unwrap().unwrap().status, "timed_out");}+/// A CAPTCHA step whose watcher never gets there (none runs without a sandbox, as a watcher lagging+/// on a busy machine): the turn's own wait, ending past the limit, closes it as timed out rather+/// than telling the bot to wait for a step that is already over (the flake CI saw on c185fc9).+#[tokio::test]+async fn a_captcha_step_times_out_even_when_its_watcher_is_late() {+ let tmp = tempdir().unwrap();+ let state = state_with(&tmp, None).await;+ state.human_steps.set_captcha_timing(Duration::from_millis(300), Duration::from_millis(100));+ let app = create_router(state.clone());+ let token = turn_in(&state, "turn-late", None).await;+ let task = call(&app, &token, "request_human_step", json!({"kind": "captcha", "reason": "Solve the check on example.com"}));+ let step = open_step(&state).await;+ let (text, is_error) = tokio::time::timeout(Duration::from_secs(15), task).await.expect("the turn never hangs").unwrap();+ assert!(!is_error, "{text}");+ assert!(text.contains("didn't solve the CAPTCHA in time"), "{text}");+ assert_eq!(state.db.get_human_step(&step.id).await.unwrap().unwrap().status, "timed_out");+}++/// The turn's wait ending before the CAPTCHA's time limit leaves the step open for the person.+#[tokio::test]+async fn a_turn_that_stops_waiting_early_leaves_the_captcha_open() {+ let tmp = tempdir().unwrap();+ let state = state_with(&tmp, None).await;+ state.human_steps.set_captcha_timing(Duration::from_secs(60), Duration::from_millis(100));+ state.human_steps.set_wait(Duration::from_millis(300));+ let app = create_router(state.clone());+ let token = turn_in(&state, "turn-early", None).await;+ let task = call(&app, &token, "request_human_step", json!({"kind": "captcha", "reason": "Solve the check on example.com"}));+ let step = open_step(&state).await;+ let (text, is_error) = tokio::time::timeout(Duration::from_secs(15), task).await.expect("the turn never hangs").unwrap();+ assert!(!is_error, "{text}");+ assert!(text.contains("hasn't solved the CAPTCHA yet"), "{text}");+ assert_eq!(state.db.get_human_step(&step.id).await.unwrap().unwrap().status, "open");+}+#[tokio::test]async fn the_captcha_time_limit_is_a_checked_setting() {let tmp = tempdir().unwrap();