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
0.9.6: mission task turns retry a busy browser step by themselves, bounded (#559)
Oleksandr Ivanchenko1003900e739e
diff --git a/src/server/busy_retry.rs b/src/server/busy_retry.rsindex 11f2290e..012739ef 100644--- a/src/server/busy_retry.rs+++ b/src/server/busy_retry.rs@@ -24,9 +24,9 @@ use std::future::Future;use std::sync::{Arc, Mutex, OnceLock};use std::time::Duration;-/// The `code` of a browser call that failed because the browser is there but overloaded.-// TODO(#544): use `crate::sandbox::service::BROWSER_BUSY_CODE` once #544 is on main.-pub const BROWSER_BUSY_CODE: &str = "BROWSER_BUSY";+/// The `code` of a browser call that failed because the browser is there but overloaded: the+/// browser recovery's own (#544), so the two can't drift apart.+pub use crate::sandbox::service::BROWSER_BUSY_CODE;/// How many times kwnt runs a reply again by itself after it ended on a busy browser step.pub const MAX_RETRIES: u8 = 2;@@ -330,8 +330,11 @@ mod tests {#[test]fn the_code_matches_the_browser_recovery_constant() {- // TODO(#544): assert_eq!(BROWSER_BUSY_CODE, crate::sandbox::service::BROWSER_BUSY_CODE)- assert_eq!(BROWSER_BUSY_CODE, "BROWSER_BUSY");+ assert_eq!(BROWSER_BUSY_CODE, crate::sandbox::service::BROWSER_BUSY_CODE);+ // ...so #544's busy answer, built from its own constants, is what `is_busy` matches+ let body = json!({"error": crate::sandbox::service::BROWSER_BUSY, "code": crate::sandbox::service::BROWSER_BUSY_CODE,+ "retryable": true, "is_running": true});+ assert!(is_busy(&body));}#[test]diff --git a/src/server/missions/runner.rs b/src/server/missions/runner.rsindex 35185b9f..0360fd13 100644--- a/src/server/missions/runner.rs+++ b/src/server/missions/runner.rs@@ -4,9 +4,11 @@use super::{lease_ms, transition, Actor};use crate::db::missions::{ClaimRefused, Mission, Task, TaskChange};+use crate::server::busy_retry::{self, Slot as BusySlot};use crate::server::routes::{scope_for, turn_once, TurnOpts};use crate::server::AppState;use std::collections::HashSet;+use std::future::Future;use std::sync::{Arc, Mutex};pub const MAX_RUNNING: usize = 2;@@ -230,23 +232,39 @@ async fn run_one(state: &AppState, m: &Mission, task: &Task, bot: &crate::db::molet (channel, thread) = mission_place(m, bot);let reply = match scope_for(state, bot, channel, thread, &job, 0).await {Ok(scope) => {- let mut opts = TurnOpts::default();- (opts.unsaved, opts.quiet_failure, opts.purpose) = (true, true, Some(PURPOSE.into()));- // One notification per task outcome, sent below, not one per attempt- opts.quiet_finish = true;+ let mut hint = None;let mut p = prompt(state, m, task).await;if let Some(note) = super::autofix::retry_note(state, task).await {p.push_str(¬e);}// C1: lessons from the bot's earlier tasks; held out for 1 in 5 tasks (still logged)- if let Some((block, hint)) = super::lessons::for_brief(state, &bot.id, &task.id).await {+ if let Some((block, h)) = super::lessons::for_brief(state, &bot.id, &task.id).await {if !block.is_empty() {p.truncate(p.trim_end().len());p.push_str(&block);}- opts.task = Some(hint);+ hint = Some(h);}- turn_once(&scope, bot, p, opts).await+ // 0.9.6: nobody watches a runner turn, so a busy browser step it ends on is retried+ // here with the hand-offs' bounds (see [`busy_retry::unwatched`]), while the task is+ // still this bot's to work on; one that still ends busy fails the task as any failed+ // turn does (below). Every retry is `quiet_finish` too: one notification per outcome+ let mut first = true;+ busy_retry::unwatched(&scope, &bot.name, &p, |p, slot| {+ let mut opts = TurnOpts::default();+ (opts.unsaved, opts.quiet_failure, opts.purpose) = (true, true, Some(PURPOSE.into()));+ // One notification per task outcome, sent below, not one per attempt+ opts.quiet_finish = true;+ opts.task = hint.clone();+ opts.busy_slot = Some(slot.clone());+ let retry = !std::mem::replace(&mut first, false);+ let (scope, task_id, bot_id) = (&scope, task.id.as_str(), bot.id.as_str());+ attempt(retry, slot, move || still_held(state, task_id, bot_id), async move {+ // boxed, so the retry loop around the turn adds no stack to it+ Box::pin(turn_once(scope, bot, p, opts)).await+ })+ })+ .await}Err(e) => Err(e),};@@ -258,6 +276,43 @@ async fn run_one(state: &AppState, m: &Mission, task: &Task, bot: &crate::db::monotify_outcome(state, &task.id, &bot.id, &context, reply.is_ok()).await;}+/// Why a busy browser step's retry didn't run: the task stopped being the runner's while it+/// waited (the person took it, moved it on, or the mission let it go).+pub const MOVED_ON: &str = "the task moved on while its busy browser step waited for a retry";++/// One turn of a runner's [`busy_retry::retry_loop`]: a retry (`retry`) runs only while the task+/// is still held ([`still_held`]), and a busy end is left in `slot` for a retry only if the task+/// is still held after the turn: a bot that handed the task in, blocked it or asked the person+/// meanwhile is not run again.+async fn attempt<H, HF, T>(retry: bool, slot: BusySlot, held: H, turn: T) -> Result<String, String>+where+ H: Fn() -> HF,+ HF: Future<Output = bool>,+ T: Future<Output = Result<String, String>>,+{+ if retry && !held().await {+ return Err(MOVED_ON.into());+ }+ let outcome = turn.await;+ if let Some(step) = slot.take() {+ if held().await {+ slot.put(step);+ }+ }+ outcome+}++/// Whether `task_id` is still `working` for `bot_id`. Renews its lease when it is, so a busy+/// browser retry's cooldown (1 min, then 2) never runs a short lease out.+async fn still_held(state: &AppState, task_id: &str, bot_id: &str) -> bool {+ let Ok(Some(t)) = state.db.get_task(task_id).await else { return false };+ let held = t.state == "working" && t.owner_kwant_id.as_deref() == Some(bot_id);+ if held {+ let _ = state.db.renew_claim(task_id, lease_ms(state).await).await;+ }+ held+}+/// The runner turn's one `turn_finished` notification: none while AutoFix has a retry of the task/// scheduled (that retry's turn notifies, or the one after it), so a failing task gives one for/// its final outcome. A turn that failed notifies only when the task ended `failed` or `blocked`.@@ -340,6 +395,110 @@ pub async fn after_turn(state: &AppState, task_id: &str, err: Option<&str>, star#[cfg(test)]mod tests {use super::*;+ use crate::server::busy_retry::{retry_loop, Step};+ use serde_json::json;+ use std::collections::VecDeque;+ use std::time::Duration;++ fn act(args: serde_json::Value) -> Step {+ Step { tool: "browser_act".into(), args: args.to_string() }+ }++ /// What a fake runner task did: the outcome, the prompts its turns got and the waits+ /// (attempt, cooldown) between them.+ struct Ran {+ outcome: Result<String, String>,+ prompts: Vec<String>,+ waits: Vec<(u8, Duration)>,+ }++ /// A runner task through [`attempt`] and the same loop [`busy_retry::unwatched`] runs: turn n+ /// replies "reply n" and ends on `step` where `busy[n]`; each "is the task still held?"+ /// answers the next of `held` (then yes), as the database would.+ async fn run_task(step: &Step, busy: &[bool], held: &[bool]) -> Ran {+ let prompts = Mutex::new(Vec::new());+ let waits = Mutex::new(Vec::new());+ let held = Mutex::new(held.iter().copied().collect::<VecDeque<bool>>());+ let mut first = true;+ let outcome = retry_loop(+ "[Mission Control] You hold task t1",+ |p, slot| {+ let retry = !std::mem::replace(&mut first, false);+ let (prompts, held) = (&prompts, &held);+ attempt(retry, slot.clone(), move || async move { held.lock().unwrap().pop_front().unwrap_or(true) }, async move {+ let n = {+ let mut ps = prompts.lock().unwrap();+ ps.push(p);+ ps.len() - 1+ };+ if busy.get(n).copied().unwrap_or(false) {+ slot.put(step.clone());+ }+ Ok(format!("reply {n}"))+ })+ },+ |s, attempt, after| {+ assert_eq!(&s, step, "the retry is for the same step");+ waits.lock().unwrap().push((attempt, after));+ async { true }+ },+ )+ .await;+ Ran { outcome, prompts: prompts.into_inner().unwrap(), waits: waits.into_inner().unwrap() }+ }++ #[tokio::test]+ async fn a_task_turn_that_ends_busy_is_retried_twice_then_fails_as_today() {+ let step = act(json!({"action": "scroll", "delta_y": 400}));+ let ran = run_task(&step, &[true, true, true], &[]).await;+ assert_eq!(ran.prompts.len(), 3, "the turn, then 2 retries, never a third");+ assert_eq!(ran.prompts[0], "[Mission Control] You hold task t1");+ for p in &ran.prompts[1..] {+ assert!(p.contains("the browser was busy") && p.contains("`browser_act`"), "{p}");+ assert_eq!(p.matches("You hold task t1").count(), 1, "the brief once");+ }+ assert_eq!(ran.waits, vec![(1, Duration::from_secs(60)), (2, Duration::from_secs(120))]);+ // The turn's error, which `after_turn` records like any failed runner turn: AutoFix's+ // `unknown` (one retry_same per task), never a class of its own+ let err = ran.outcome.expect_err("the task fails once the retries are used up");+ assert_eq!(err, "the browser stayed busy after 2 automatic retries of `browser_act`");+ assert_eq!(super::super::autofix::classify("turn", "error", &err), "unknown");+ }++ #[tokio::test]+ async fn a_task_turn_that_gets_through_on_retry_1_ends_with_that_reply() {+ let ran = run_task(&act(json!({"action": "click", "ref": "e9"})), &[true, false], &[]).await;+ assert_eq!(ran.outcome, Ok("reply 1".into()));+ assert_eq!((ran.prompts.len(), ran.waits.len()), (2, 1));+ // and one that never ends busy runs once, as before+ let ran = run_task(&act(json!({})), &[false], &[]).await;+ assert_eq!((ran.outcome, ran.prompts.len(), ran.waits.len()), (Ok("reply 0".into()), 1, 0));+ }++ #[tokio::test]+ async fn a_busy_task_step_that_may_reach_outside_is_never_run_again() {+ let send = act(json!({"action": "click", "ref": "e4", "name": "Send"}));+ let ran = run_task(&send, &[true, true, true], &[]).await;+ assert_eq!((ran.prompts.len(), ran.waits.len()), (1, 0), "straight to the one failure");+ let err = ran.outcome.unwrap_err();+ assert!(err.contains("may reach outside") && err.contains("wasn't run again by itself"), "{err}");+ }++ #[tokio::test]+ async fn a_task_the_bot_let_go_of_in_its_busy_turn_is_not_run_again() {+ // It ended busy, but it handed the task in (or blocked it, or asked the person) first+ let ran = run_task(&act(json!({"action": "scroll"})), &[true, true], &[false]).await;+ assert_eq!(ran.outcome, Ok("reply 0".into()), "the turn's own reply, as before");+ assert_eq!((ran.prompts.len(), ran.waits.len()), (1, 0));+ }++ #[tokio::test]+ async fn a_task_that_moved_on_during_the_cooldown_is_not_run_again() {+ // Held when the busy turn ended, gone by the time the retry is due+ let ran = run_task(&act(json!({"action": "scroll"})), &[true, true], &[true, false]).await;+ assert_eq!(ran.outcome, Err(MOVED_ON.into()));+ assert_eq!((ran.prompts.len(), ran.waits.len()), (1, 1), "no retry turn ran");+ }#[test]fn slots_are_per_server_and_freed_when_dropped() {diff --git a/tests/delegation_test.rs b/tests/delegation_test.rsindex f4524ffd..661807a7 100644--- a/tests/delegation_test.rs+++ b/tests/delegation_test.rs@@ -62,6 +62,8 @@ credit=$(printf '%s\n' "$last" | sed -n 's/.*CREDIT:\([A-Za-z0-9_]*\).*/\1/p' |case "$last" in *"finished the task you delegated"*|*"tasks you delegated have ended"*) ;; *) followup=""; credit="" ;; esaclines=$(printf '%s\n' "$last" | sed -n 's/.*LINES:\([A-Za-z0-9_]*:[0-9]*\).*/\1/p' | head -n 1)case "$last" in *"finished the task you delegated"*|*"tasks you delegated have ended"*|*"mentioned you"*) lines="" ;; esac+# A hand-off turn that works a while (for a test to see it running)+case "$last" in *SLOWHANDOFF*) case "$last" in *"delegated this task to you"*|*"handed this conversation to you"*) sleep 3 ;; esac ;; esacout="answer ${tag:-none}"for n in $(printf '%s' "$mention" | tr '+' ' '); do out="$out @$n"; donefor n in $(printf '%s' "$followup" | tr '+' ' '); do out="$out \`@$n\` please revise your part."; done@@ -1041,6 +1043,87 @@ async fn non_lead_mentions_hand_off_and_refused_mentions_are_reported() {}}+/// The running turn of `kwant` (up to ~5 s).+async fn running_turn_of(env: &Env, kwant: &str) -> String {+ for _ in 0..200 {+ if let Some(t) = env.state.turns.active_turns().into_iter().find(|t| t.kwant_id == kwant && t.state == "running") {+ return t.turn_id;+ }+ tokio::time::sleep(Duration::from_millis(25)).await;+ }+ panic!("no running turn of {kwant}");+}++/// Its last browser step was refused because the browser was busy (by code, as a browser tool+/// call notes it).+fn ends_busy(turn_id: &str) {+ kwnt::server::busy_retry::note(turn_id, "browser_act", &json!({"action": "scroll"}), true);+}++/// 0.9.6 (#541's Q3): a lead's @mention in its team channel is a delegation, so it already runs+/// through the hand-offs' wrapper (delegation.rs, `busy_retry::unwatched`): a delegated turn that+/// ends on a busy browser step is retried by kwnt, said in the delegation's thread, and the+/// hand-off keeps running instead of failing back to the lead.+#[tokio::test]+async fn a_leads_mention_that_ends_on_a_busy_browser_step_is_retried_as_a_hand_off() {+ let env = setup().await;+ let (lead, specialist) = (name(&env, &env.lead).await, name(&env, &env.specialist).await);+ let channel = team_channel(&env, "busy-squad").await;+ say_in(&env, &channel, &format!("@{lead} Fetch it BUSYMARK SLOWHANDOFF\nREPLYTAG:fetched MENTION:{specialist}")).await;+ wait_for("the delegation from the mention", || async {+ env.state.db.list_delegations(Some(&env.lead), None, 10).await.unwrap().iter().any(|d| d.origin_channel_id.as_deref() == Some(channel.as_str()))+ })+ .await;+ let d = env.state.db.list_delegations(Some(&env.lead), None, 10).await.unwrap().into_iter().find(|d| d.origin_channel_id.as_deref() == Some(channel.as_str())).unwrap();+ assert_eq!(d.specialist_kwant_id, env.specialist);++ ends_busy(&running_turn_of(&env, &env.specialist).await);+ wait_for("the retry note in the hand-off's thread", || async {+ channel_messages(&env, &d.thread_id).await.iter().any(|m| meta_kind(m).as_deref() == Some("browser_busy_retry"))+ })+ .await;+ let note = channel_messages(&env, &d.thread_id).await.into_iter().find(|m| meta_kind(m).as_deref() == Some("browser_busy_retry")).unwrap();+ assert!(note.text.contains(&specialist) && note.text.contains("retry 1 of 2"), "{}", note.text);+ // It waits its cooldown, still running: no result, nothing failed back to the lead+ assert_eq!(delegation_status(&env, &d.id).await, "running");+ let d = env.state.db.get_delegation(&d.id).await.unwrap().unwrap();+ assert!(d.result_message_id.is_none(), "no result while the retry waits");+ assert!(+ channel_messages(&env, &channel).await.iter().all(|m| meta_kind(m).as_deref() != Some("delegation_result")),+ "nothing is posted back while the retry waits"+ );+ assert!(+ env.state.db.list_parked().await.unwrap().iter().all(|p| p.kwant_id != env.specialist),+ "a hand-off retries in its own run, nothing is parked in a chat"+ );+}++/// ...and a teammate's @mention (not the lead's) is a direct hand-off turn in the person's chat,+/// which #541's chat path already covers: its busy step is parked for one retry in that chat.+#[tokio::test]+async fn a_teammates_mention_that_ends_on_a_busy_browser_step_parks_a_retry_in_the_chat() {+ let env = setup().await;+ let (lead, specialist) = (name(&env, &env.lead).await, name(&env, &env.specialist).await);+ let channel = team_channel(&env, "busy-plain-squad").await;+ say_in(&env, &channel, &format!("@{specialist} Look BUSYPLAIN SLOWHANDOFF REPLYTAG:plain MENTION:{lead}")).await;+ wait_for("the lead's handoff turn", || async {+ prompts_with("BUSYPLAIN").iter().any(|p| p.contains("handed this conversation to you"))+ })+ .await;+ ends_busy(&running_turn_of(&env, &env.lead).await);+ wait_for("the parked retry", || async {+ env.state.db.list_parked().await.unwrap().iter().any(|p| p.kwant_id == env.lead)+ })+ .await;+ let parked = env.state.db.list_parked().await.unwrap().into_iter().find(|p| p.kwant_id == env.lead).unwrap();+ assert_eq!(parked.channel_id.as_deref(), Some(channel.as_str()));+ assert_eq!(parked.reason, "browser_busy_1");+ assert!(parked.prompt.contains("browser_act"), "{}", parked.prompt);+ let note = channel_messages(&env, &channel).await.into_iter().find(|m| meta_kind(m).as_deref() == Some("browser_busy_retry"));+ assert!(note.is_some_and(|n| n.text.contains(&lead) && n.text.contains("retry 1 of 2")), "the retry is said in the chat");+ assert!(env.state.db.list_delegations(Some(&env.specialist), None, 10).await.unwrap().is_empty(), "not a delegation");+}+/// A third bot on the fake claude, named `name`.async fn add_bot(env: &Env, name: &str) -> String {let (s, v) = call(&env.app, "POST", "/api/kwants", Some(json!({"name": name, "title": "Growth Marketer", "persona_prompt": "", "soul": "", "avatar_sprite": "default", "driver_type": "cli", "preferred_model": "claude"}))).await;diff --git a/tests/mission_autofix_test.rs b/tests/mission_autofix_test.rsindex 14712393..898e18b5 100644--- a/tests/mission_autofix_test.rs+++ b/tests/mission_autofix_test.rs@@ -40,8 +40,9 @@ use tower::ServiceExt;/// On a Mission Control prompt: logs the prompt (with the task it holds) to prompts.log next to/// itself, streams its usage so far (10 input, 10 output), moves the task to review through its/// kwant tools, then reports the same final usage: 20 fresh tokens a turn, all known at hand-in.+/// A task titled SLOWBUSY: works 3 s, then ends without handing it in.const FAKE_CLAUDE: &str = r#"#!/usr/bin/env python3-import json, os, re, sys, urllib.request+import json, os, re, sys, time, urllib.requestargs = sys.argv[1:]if args[:1] == ["auth"]:print('{"loggedIn":true}')@@ -51,6 +52,12 @@ held = re.search(r"You hold task (\S+) of", prompt)if held and "--mcp-config" in args:with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "prompts.log"), "a") as f:f.write(json.dumps({"task": held.group(1), "prompt": prompt}) + "\n")+ if "SLOWBUSY" in prompt:+ # A turn that works a while (for a test to see it running), then ends without hand-in+ time.sleep(3)+ print(json.dumps({"type": "result", "is_error": False, "num_turns": 1, "result": "still on it",+ "usage": {"input_tokens": 10, "output_tokens": 10}}))+ sys.exit(0)start = {"type": "message_start", "message": {"id": "msg_1", "usage": {"input_tokens": 10, "output_tokens": 1}}}print(json.dumps({"type": "stream_event", "event": start}), flush=True)print(json.dumps({"type": "stream_event", "event": {"type": "message_delta", "usage": {"output_tokens": 10}}}), flush=True)@@ -455,6 +462,61 @@ async fn a_failing_task_notifies_once_for_its_outcome_and_a_passing_one_still_nowatch.abort();}+// 0.9.6: nobody watches a runner turn, so one that ends on a busy browser step (by code) is+// retried by kwnt with the hand-offs' bounds: the retry is said in the mission's chat, and the+// task stays the bot's, `working`, with no failure recorded while the retry waits+#[tokio::test]+async fn a_mission_task_turn_that_ends_on_a_busy_browser_step_is_retried_and_the_task_stays_working() {+ let e = setup().await;+ autofix(&e, "on", 25).await;+ let ann = cli_bot(&e).await;+ let body = json!({"title": "Ship it", "goal": "a release", "lead_kwant_id": ann, "budget_tokens": 900_000,+ "channel_id": e.general, "tasks": [{"title": "SLOWBUSY", "owner": ann, "budget_tokens": 50_000,+ "checks": failing_check()}]});+ let mid = id(&person(&e, "POST", "/api/missions", Some(body)).await);+ let tid = id(&person(&e, "GET", &format!("/api/missions/{mid}"), None).await["tasks"][0]);+ let row = e.state.db.get_mission(&mid).await.unwrap().unwrap();+ std::fs::create_dir_all(&row.workspace_path).unwrap();+ person(&e, "POST", &format!("/api/missions/{mid}/run"), Some(json!({"max_tasks": 1}))).await;++ // Ann's runner turn is working: its last browser step is refused, the browser busy+ let mut turn = None;+ for _ in 0..200 {+ turn = e.state.turns.active_turns().into_iter().find(|t| t.kwant_id == ann && t.state == "running");+ if turn.is_some() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(25)).await;+ }+ let turn = turn.expect("Ann's runner turn started");+ kwnt::server::busy_retry::note(&turn.turn_id, "browser_act", &json!({"action": "scroll"}), true);++ // When the turn ends, kwnt says the retry in the mission's chat, then waits its cooldown+ let mut said = None;+ for _ in 0..300 {+ let msgs = e.state.db.list_messages(&e.general, 50).await.unwrap();+ said = msgs.into_iter().find(|m| m.meta.as_deref().is_some_and(|x| x.contains("browser_busy_retry")));+ if said.is_some() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ let said = said.expect("the retry is said in the mission's chat");+ let meta: Value = serde_json::from_str(said.meta.as_deref().unwrap()).unwrap();+ assert_eq!(meta["attempt"], 1, "{meta}");+ assert!(said.text.contains("`browser_act`") && said.text.contains("retry 1 of 2"), "{}", said.text);+ assert_eq!(said.sender_role, "system");++ // ...while the task is still Ann's to work on: not failed, no failure recorded, no AutoFix run+ let t = task(&e, &tid).await;+ assert_eq!(t["state"], "working", "{t}");+ assert_eq!(t["owner_kwant_id"], ann.as_str(), "{t}");+ assert!(failures(&e, &tid).await.is_empty(), "no failure while the retry waits");+ assert!(attempts(&e, &tid).await.is_empty(), "no AutoFix attempt while the retry waits");+ assert_eq!(prompts(&tid).len(), 1, "the retry waits its cooldown first");+ assert!(runner::is_running(&e.state, &mid), "the runner holds the task through the cooldown");+}+// 3#[tokio::test]async fn off_records_only_and_suggest_waits_for_the_person() {