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.

AutoFix: a task whose browser stayed busy ends once with a fix line, no rerun (stacked on #559) (#563)

Oleksandr Ivanchenko300f560cf1f4
diff --git a/src/server/busy_retry.rs b/src/server/busy_retry.rs
index 012739ef..cc679abb 100644
--- a/src/server/busy_retry.rs
+++ b/src/server/busy_retry.rs
@@ -234,19 +234,54 @@ impl Slot {
}
}
+/// How [`unwatched_failure`]'s two errors start. AutoFix tells them apart from any other failed
+/// turn by these ([`gave_up`]), so the wording lives here once.
+const STAYED_BUSY: &str = "the browser stayed busy after ";
+const BUSY_OUTWARD: &str = "the browser was busy at `";
+const OUTWARD_TAIL: &str = "a step that may reach outside";
+
/// Why an unwatched run failed when kwnt didn't (or no longer) retry its busy step: the run's
/// error, which goes where a failed run goes today (a routine's Inbox item, a hand-off's lead).
pub fn unwatched_failure(step: &Step, exit: &Exit) -> String {
match exit {
Exit::Outward => format!(
- "the browser was busy at `{tool}`, a step that may reach outside (a send, a post, a payment), so it wasn't run again \
+ "{BUSY_OUTWARD}{tool}`, {OUTWARD_TAIL} (a send, a post, a payment), so it wasn't run again \
by itself. Check whether it went through before running it again",
tool = step.tool,
),
- _ => format!("the browser stayed busy after {MAX_RETRIES} automatic retries of `{tool}`", tool = step.tool),
+ _ => format!("{STAYED_BUSY}{MAX_RETRIES} automatic retries of `{tool}`", tool = step.tool),
}
}
+/// Whether a failed run's error (any case, possibly inside a longer one) is kwnt's own give-up on
+/// a busy browser step ([`unwatched_failure`]): `Some(Exit::Exhausted)` when its retries ran out,
+/// `Some(Exit::Outward)` when the step may reach outside and wasn't retried. Running the whole
+/// task again would only wait the same minutes again (or repeat a send), so AutoFix doesn't.
+pub fn gave_up(error: &str) -> Option<Exit> {
+ let t = error.to_lowercase();
+ if t.contains(STAYED_BUSY) {
+ Some(Exit::Exhausted)
+ } else if t.contains(BUSY_OUTWARD) && t.contains(OUTWARD_TAIL) {
+ Some(Exit::Outward)
+ } else {
+ None
+ }
+}
+
+/// Test-only: chats (by channel id) whose unwatched retries wait this long instead of
+/// [`cooldown`], so an end-to-end test can run the retries out without 3 minutes of waits. Empty
+/// in a real run.
+fn quick_chats() -> &'static Mutex<HashMap<String, Duration>> {
+ static CHATS: OnceLock<Mutex<HashMap<String, Duration>>> = OnceLock::new();
+ CHATS.get_or_init(Default::default)
+}
+
+/// Test-only: [`unwatched`] retries in channel `channel_id` wait `wait` instead of [`cooldown`].
+#[doc(hidden)]
+pub fn quick_cooldown_in(channel_id: &str, wait: Duration) {
+ quick_chats().lock().unwrap_or_else(|e| e.into_inner()).insert(channel_id.to_string(), wait);
+}
+
/// The bounded retry for a turn nobody watches. `run` runs the turn with a prompt and the
/// [`Slot`] it leaves a busy end in; `wait` says the retry in its chat, waits the cooldown and
/// answers `false` if the run was stopped meanwhile. A turn that ended on a busy step runs again
@@ -290,6 +325,8 @@ where
RF: Future<Output = Result<String, String>>,
{
retry_loop(original, run, |step, attempt, after| async move {
+ let quick = scope.channel_id.as_deref().and_then(|c| quick_chats().lock().unwrap_or_else(|e| e.into_inner()).get(c).copied());
+ let after = quick.unwrap_or(after);
let at = chrono::Utc::now() + chrono::Duration::from_std(after).unwrap_or_else(|_| chrono::Duration::seconds(60));
let note = scope.message("system", "kwnt", retry_note(name, &step, attempt, at));
scope.save(&note, Some(serde_json::json!({"kind": "browser_busy_retry", "attempt": attempt}))).await;
@@ -524,4 +561,26 @@ mod tests {
assert_eq!(runs, 1);
assert_eq!(outcome, Err("the claude driver failed: boom".into()));
}
+
+ #[test]
+ fn kwnts_own_busy_give_up_is_told_from_any_other_error() {
+ let step = act(json!({"action": "scroll"}));
+ let send = act(json!({"action": "click", "name": "Send"}));
+ let exhausted = unwatched_failure(&step, &Exit::Exhausted);
+ let outward = unwatched_failure(&send, &Exit::Outward);
+ assert_eq!(gave_up(&exhausted), Some(Exit::Exhausted));
+ assert_eq!(gave_up(&outward), Some(Exit::Outward));
+ // Inside a routine run's longer error, and whatever the case
+ assert_eq!(gave_up(&format!("the bot's turn failed: {exhausted}")), Some(Exit::Exhausted));
+ assert_eq!(gave_up(&exhausted.to_uppercase()), Some(Exit::Exhausted));
+ // #544's busy answer, the ask in a person's chat and other errors are not a give-up
+ for other in [
+ "The browser isn't responding right now (it is overloaded, not gone). This is temporary: retry the same step in a minute.",
+ "the claude driver failed: boom",
+ "the browser was busy at the time",
+ "",
+ ] {
+ assert_eq!(gave_up(other), None, "{other}");
+ }
+ }
}
diff --git a/src/server/missions/autofix.rs b/src/server/missions/autofix.rs
index ee488355..555bb8ed 100644
--- a/src/server/missions/autofix.rs
+++ b/src/server/missions/autofix.rs
@@ -12,7 +12,7 @@ use super::routes::{bad, conflict, internal, load_task, not_found};
use super::{emit_task, transition, Actor};
use crate::db::autofix::{Attempt, ChangeWrite, Failure, NewAttempt, NewFailure, WorkflowChange, TARGETS};
use crate::db::missions::{Task, TaskChange};
-use crate::server::AppState;
+use crate::server::{busy_retry, AppState};
use axum::{
extract::{Path, RawQuery, State},
http::{HeaderMap, StatusCode},
@@ -155,6 +155,9 @@ pub fn classify(source: &str, status: &str, text: &str) -> &'static str {
("turn", "stalled") => "stalled",
("turn", "denied") => "denied",
("turn", "needs_input") => "needs_input",
+ // kwnt's own give-up on a busy browser step (0.9.7): a temporary error, but one whose
+ // retries already ran, so [`strategy_of`] doesn't run it again
+ (_, _) if busy_retry::gave_up(&t).is_some() => "transient",
// quota and auth before transient: "429 usage limit reached" won't pass in a minute, and
// "401" next to "Reconnecting… timed out" is still a login problem
(_, _) if is_quota(&t) => "quota",
@@ -176,6 +179,37 @@ fn strategy_for(class: &str) -> &'static str {
}
}
+/// What the person must do after a task's browser stayed busy through kwnt's own retries.
+pub const BUSY_FIX: &str = "The browser stayed busy. Let the other job finish or close its page, then press Retry.";
+
+/// What the person must do after a busy browser step that may reach outside wasn't run again.
+pub const BUSY_OUTWARD_FIX: &str = "A step that may reach outside met a busy browser. Check whether it went through, then press Retry.";
+
+/// The fix for kwnt's own give-up on a busy browser step ([`busy_retry::gave_up`]), read from a
+/// failure's summary or excerpt. Its retries already waited 1, then 2 minutes (or the step may
+/// have reached outside), so running the whole task again would only repeat that: AutoFix
+/// doesn't, whatever the class says (0.9.7, busy-retry-transient).
+fn busy_fix(summary: &str, excerpt: Option<&str>) -> Option<&'static str> {
+ let exit = busy_retry::gave_up(summary).or_else(|| excerpt.and_then(busy_retry::gave_up))?;
+ Some(if exit == busy_retry::Exit::Outward { BUSY_OUTWARD_FIX } else { BUSY_FIX })
+}
+
+/// AutoFix's strategy for `failure`: its class's ([`strategy_for`]), except `none` for kwnt's own
+/// give-up on a busy browser step ([`busy_fix`]).
+fn strategy_of(failure: &Failure) -> &'static str {
+ if busy_fix(&failure.summary, failure.excerpt.as_deref()).is_some() {
+ "none"
+ } else {
+ strategy_for(&failure.class)
+ }
+}
+
+/// What the person must do for `failure` when AutoFix never retries it: the busy browser's fix,
+/// else its class's ([`fix_text`]).
+fn fix_of(failure: &Failure) -> Option<&'static str> {
+ busy_fix(&failure.summary, failure.excerpt.as_deref()).or_else(|| fix_text(&failure.class))
+}
+
/// What the person must do when AutoFix stopped short of the retry budget.
pub const RECOVERY_BUDGET_FIX: &str = "Retry budget used up: raise it or retry by hand.";
@@ -518,7 +552,7 @@ async fn plan(state: &AppState, task: &Task, failure: &Failure) -> Option<Attemp
if failure.class == "needs_input" || task.source_kind == "delegation" {
return None;
}
- let mut strategy = strategy_for(&failure.class);
+ let mut strategy = strategy_of(failure);
if failure.class == "stalled" && failure.checkpoint_id.is_some() {
strategy = "retry_from_checkpoint";
}
@@ -534,7 +568,7 @@ async fn plan(state: &AppState, task: &Task, failure: &Failure) -> Option<Attemp
let new = |status, not_before, reason: String| NewAttempt { task, failure_id: &failure.id, strategy, idempotency_key: k.clone(), status, not_before, reason };
if strategy == "none" {
// The code first, as for the other skips, so the attempt doesn't repeat the Needs-you text
- let why = fix_text(&failure.class).map_or_else(|| "AutoFix retried this once already".into(), |fix| format!("not_retryable: {fix}"));
+ let why = fix_of(failure).map_or_else(|| "AutoFix retried this once already".into(), |fix| format!("not_retryable: {fix}"));
return insert(state, &new("skipped", None, why)).await;
}
if strategy == "propose_change" {
@@ -863,7 +897,7 @@ pub async fn needs_you(state: &AppState, task: &Task) -> Vec<Value> {
let attempts = state.db.attempts_of(&task.id).await.unwrap_or_default();
attempts.iter().rev().find(|a| a.failure_id == f.id).is_some_and(|a| a.status == "skipped" && a.reason.starts_with("over_recovery_budget"))
};
- if let Some(text) = fix_text(&f.class) {
+ if let Some(text) = fix_of(f) {
items.push(json!({"kind": "fix_needed", "id": f.id, "text": text}));
} else if task.state == "failed" && over_budget().await {
items.push(json!({"kind": "fix_needed", "id": f.id, "text": RECOVERY_BUDGET_FIX}));
@@ -959,7 +993,7 @@ pub async fn run_autofix(State(state): State<AppState>, RawQuery(q): RawQuery, h
state.db.get_attempt(&s.id).await.map_err(internal)?.ok_or_else(|| not_found("autofix"))?
}
(None, None) => {
- let strategy = match strategy_for(&failure.class) {
+ let strategy = match strategy_of(&failure) {
"none" => "retry_same",
s => s,
};
@@ -1409,4 +1443,48 @@ mod tests {
}
assert_eq!(fix_text("transient"), None);
}
+
+ fn failure(class: &str, summary: &str, excerpt: Option<&str>) -> Failure {
+ Failure {
+ id: "f1".into(),
+ task_id: "t1".into(),
+ attempt: 1,
+ source: "turn".into(),
+ class: class.into(),
+ summary: redact(summary),
+ excerpt: excerpt.map(redact),
+ diagnostics_path: None,
+ checkpoint_id: None,
+ created_at: Utc::now(),
+ }
+ }
+
+ // 0.9.7 busy-retry-transient: a task whose browser stayed busy through kwnt's own 2 retries
+ // (1, then 2 min) ends once, with a plain fix line; AutoFix doesn't run it again
+ #[test]
+ fn busy_give_up_is_never_run_again() {
+ use crate::server::busy_retry::{unwatched_failure, Exit, Step};
+ let step = Step { tool: "browser_act".into(), args: json!({"action": "scroll"}).to_string() };
+ let send = Step { tool: "browser_act".into(), args: json!({"action": "click", "name": "Send"}).to_string() };
+ for (exit, step, fix) in [(Exit::Exhausted, &step, BUSY_FIX), (Exit::Outward, &send, BUSY_OUTWARD_FIX)] {
+ let err = unwatched_failure(step, &exit);
+ // Classed as what it is (a temporary error, never the bot's own doing, so no lesson)…
+ let class = classify("turn", "error", &err);
+ assert_eq!(class, "transient", "{err}");
+ assert_eq!(classify("routine", "error", &format!("the bot's turn failed: {err}")), "transient");
+ // …but not run again: no strategy, and the fix line says what to do
+ let f = failure(class, err.lines().next().unwrap(), Some(&err));
+ assert_eq!(f.summary, err, "masking leaves it whole");
+ assert_eq!(strategy_of(&f), "none", "{err}");
+ assert_eq!(fix_of(&f), Some(fix), "{err}");
+ // The excerpt alone is enough (a summary cut short)
+ assert_eq!(fix_of(&failure(class, "the turn failed", Some(&err))), Some(fix));
+ assert!(fix.ends_with("then press Retry.") && !fix.contains("retry:"), "{fix}");
+ }
+ // Any other temporary error still waits and runs again, with no fix line
+ let other = failure("transient", "rate limit exceeded, retry in 20s", None);
+ assert_eq!((strategy_of(&other), fix_of(&other)), ("wait_and_retry", None));
+ let unknown = failure("unknown", "the claude driver failed: boom", None);
+ assert_eq!((strategy_of(&unknown), fix_of(&unknown)), ("retry_same", None));
+ }
}
diff --git a/src/server/missions/runner.rs b/src/server/missions/runner.rs
index 0360fd13..0017039e 100644
--- a/src/server/missions/runner.rs
+++ b/src/server/missions/runner.rs
@@ -458,11 +458,11 @@ mod tests {
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
+ // The turn's error, which `after_turn` records like any failed runner turn: a temporary
+ // error AutoFix doesn't run again (0.9.7, see autofix's `busy_give_up_is_never_run_again`)
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");
+ assert_eq!(super::super::autofix::classify("turn", "error", &err), "transient");
}
#[tokio::test]
diff --git a/tests/mission_autofix_test.rs b/tests/mission_autofix_test.rs
index 898e18b5..434a2c92 100644
--- a/tests/mission_autofix_test.rs
+++ b/tests/mission_autofix_test.rs
@@ -517,6 +517,79 @@ async fn a_mission_task_turn_that_ends_on_a_busy_browser_step_is_retried_and_the
assert!(runner::is_running(&e.state, &mid), "the runner holds the task through the cooldown");
}
+// 0.9.7 busy-retry-transient: a task whose browser stays busy through both of kwnt's own retries
+// ends `failed` once, with a plain fix line: AutoFix doesn't run it again (its retries already
+// waited), and the person gets one notification. The cooldowns are cut to 300 ms for this chat
+#[tokio::test]
+async fn a_mission_task_whose_browser_stays_busy_ends_once_with_a_fix_line_and_no_autofix_rerun() {
+ let e = setup().await;
+ autofix(&e, "on", 25).await;
+ kwnt::server::busy_retry::quick_cooldown_in(&e.general, Duration::from_millis(300));
+ let ann = cli_bot(&e).await;
+ let (watch, notes) = finished_notes(&e.state, &ann);
+ 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;
+
+ // Every runner turn of Ann's ends on a busy browser step: the turn, then 2 retries
+ let mut busy: Vec<String> = Vec::new();
+ for _ in 0..1600 {
+ for t in e.state.turns.active_turns().into_iter().filter(|t| t.kwant_id == ann && t.state == "running") {
+ if !busy.contains(&t.turn_id) {
+ kwnt::server::busy_retry::note(&t.turn_id, "browser_act", &json!({"action": "scroll"}), true);
+ busy.push(t.turn_id);
+ }
+ }
+ if task(&e, &tid).await["state"] == "failed" {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ runner_idle(&e.state, &mid).await;
+ assert_eq!(busy.len(), 3, "the turn and 2 retries, never a third");
+ assert_eq!(prompts(&tid).len(), 3);
+
+ // It ended once: failed, a temporary error, with the plain fix line, and no AutoFix rerun
+ let t = task(&e, &tid).await;
+ assert_eq!(t["state"], "failed", "{t}");
+ assert_eq!(t["last_failure"]["class"], "transient", "{t}");
+ assert!(t["last_failure"]["summary"].as_str().unwrap().contains("stayed busy after 2 automatic retries"), "{t}");
+ let fix: Vec<&Value> = t["needs_you"].as_array().unwrap().iter().filter(|i| i["kind"] == "fix_needed").collect();
+ assert_eq!(fix.len(), 1, "{t}");
+ assert_eq!(fix[0]["text"], kwnt::server::missions::autofix::BUSY_FIX, "{t}");
+ let a = attempts(&e, &tid).await;
+ assert_eq!(a.len(), 1, "{a:?}");
+ assert_eq!((a[0].strategy.as_str(), a[0].status.as_str()), ("none", "skipped"), "{a:?}");
+ assert!(a[0].reason.starts_with("not_retryable: The browser stayed busy."), "{a:?}");
+ assert_eq!(failures(&e, &tid).await.len(), 1, "one failure, recorded once the retries ran out");
+ kwnt::server::missions::autofix::run_due(&e.state).await;
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ assert_eq!(prompts(&tid).len(), 3, "AutoFix runs nothing more");
+ assert_eq!(task(&e, &tid).await["state"], "failed");
+
+ // One notification for the task's outcome, none per retry
+ for _ in 0..40 {
+ if !notes.lock().unwrap().is_empty() {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ let got = notes.lock().unwrap().clone();
+ assert_eq!(got.len(), 1, "one notification for the outcome: {got:?}");
+ watch.abort();
+
+ // The person's Retry still runs it again, as the fix line says
+ let (status, v) = send(&e.app, "POST", &format!("/api/tasks/{tid}/autofix"), None, None).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ assert_eq!(v["strategy"], "retry_same", "{v}");
+}
+
// 3
#[tokio::test]
async fn off_records_only_and_suggest_waits_for_the_person() {