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
AutoFix retries notify once per task; poll for the card in approvals_off_test (#244)
Oleksandr Ivanchenko597eff0fe8d1
diff --git a/docs/mission-control.md b/docs/mission-control.mdindex 78239c1f..590f0ed8 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -510,6 +510,7 @@ acceptance, a routine) is only ever proposed; it applies when the person approve- The retry prompt (runner and `task_claim`) says which attempt it is and why, the failing check and its redacted output, `KWANT_IDEMPOTENCY_KEY=<key>`, and the external tool calls earlier attempts already made. Calls in an attempt's turns record the key in `turn_tool_calls.idempotency_key`.- An attempt ends `succeeded` when its task is verified, `skipped` when it is cancelled, `failed` at the next failure.- Scheduled attempts live in the table; the scheduler tick runs the due ones, so a restart loses nothing.+- Notifications: a mission runner turn sends no `turn_finished` of its own (`turn_ended` carries `quiet: true`). After the turn the runner sends one, unless an AutoFix attempt of the task is `scheduled`, so a failing task notifies once, for its final outcome, and a passing one once as before. A runner turn that errored notifies only when its task ended `failed` or `blocked`. Routine retries are new routine runs and notify as routines do.### Workflow changes (person only)diff --git a/src/drivers/events.rs b/src/drivers/events.rsindex da3d3bfd..8b8df3b2 100644--- a/src/drivers/events.rs+++ b/src/drivers/events.rs@@ -64,6 +64,10 @@ pub enum RuntimeEvent {turn_id: Option<String>,#[serde(default, skip_serializing_if = "Option::is_none")]thread_id: Option<String>,+ /// No `turn_finished` notification for this turn: a mission runner turn, whose runner+ /// notifies once for the task's outcome instead (an AutoFix retry stays silent).+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ quiet: bool,},/// A turn is waiting for a free slot: its agent already runs as many turns as allowed/// (`reason` "agent_busy") or the whole server does ("server_busy"). It starts on its own,diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 40b6cda3..dd37ccdb 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -1764,6 +1764,20 @@ async fn place(state: &AppState, context_id: Option<&str>) -> (Option<String>, S}}+/// "<bot> finished replying in <place>", for a turn of `kwant_id` in `context_id`.+pub async fn turn_finished(state: &AppState, kwant_id: &str, context_id: Option<&str>) -> Notification {+ let name = kwant_name(state, kwant_id).await;+ let (channel_id, where_) = place(state, context_id).await;+ Notification {+ kind: "turn_finished",+ kwant_id: kwant_id.to_string(),+ title: format!("{name} replied"),+ body: format!("{name} finished replying in {where_}."),+ kwant_name: name,+ channel_id,+ }+}+async fn notification_for(state: &AppState, event: &RuntimeEvent) -> Option<Notification> {match event.unscoped() {RuntimeEvent::TurnEnded {@@ -1771,24 +1785,16 @@ async fn notification_for(state: &AppState, event: &RuntimeEvent) -> Option<Noticontext_id,outcome,thread_id,+ quiet,..- } if outcome == "completed" => {+ } if outcome == "completed" && !quiet => {// A delegated task reports with delegation_finished insteadif let Some(t) = thread_id {if state.db.delegation_for_thread(t).await.ok().flatten().is_some() {return None;}}- let name = kwant_name(state, kwant_id).await;- let (channel_id, where_) = place(state, context_id.as_deref()).await;- Some(Notification {- kind: "turn_finished",- kwant_id: kwant_id.clone(),- title: format!("{name} replied"),- body: format!("{name} finished replying in {where_}."),- kwant_name: name,- channel_id,- })+ Some(turn_finished(state, kwant_id, context_id.as_deref()).await)}RuntimeEvent::ApprovalRequired {tool_name, details, ..diff --git a/src/server/missions/runner.rs b/src/server/missions/runner.rsindex b0cd3c29..1806db67 100644--- a/src/server/missions/runner.rs+++ b/src/server/missions/runner.rs@@ -179,6 +179,8 @@ async fn run_one(state: &AppState, m: &Mission, task: &Task, bot: &crate::db::moOk(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 p = prompt(state, m, task).await;if let Some(note) = super::autofix::retry_note(state, task).await {p.push_str(¬e);@@ -192,6 +194,28 @@ async fn run_one(state: &AppState, m: &Mission, task: &Task, bot: &crate::db::mo}let err = reply.as_ref().err().map(ToString::to_string);after_turn(state, &task.id, err.as_deref(), started).await;+ notify_outcome(state, &task.id, &bot.id, &context, reply.is_ok()).await;+}++/// 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`.+async fn notify_outcome(state: &AppState, task_id: &str, kwant_id: &str, context: &str, replied: bool) {+ let Ok(Some(t)) = state.db.get_task(task_id).await else { return };+ if retry_coming(state, task_id).await {+ return;+ }+ if !replied && !matches!(t.state.as_str(), "failed" | "blocked") {+ return;+ }+ let n = crate::server::continuity::turn_finished(state, kwant_id, Some(context)).await;+ crate::server::continuity::notify(state, n).await;+}++/// Whether an AutoFix attempt of the task is scheduled. It can't have started yet: it waits for+/// this mission's runner slot, which the caller still holds.+async fn retry_coming(state: &AppState, task_id: &str) -> bool {+ state.db.attempts_of(task_id).await.unwrap_or_default().iter().any(|a| a.status == "scheduled")}/// After a runner turn of `task_id`: still `working` means the bot didn't finish or let go, so thediff --git a/src/server/routes.rs b/src/server/routes.rsindex ecd91456..bfb3eb8a 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -1783,6 +1783,9 @@ pub(super) struct TurnOpts {pub(super) unsaved: bool,/// A failed turn saves no `turn_failed` note (the caller posts something else).pub(super) quiet_failure: bool,+ /// The turn sends no `turn_finished` notification when it ends (the caller notifies, see+ /// [`super::missions::runner`]).+ pub(super) quiet_finish: bool,/// Shown as the turn's `purpose` in `GET /api/turns` (`turns[]`).pub(super) purpose: Option<String>,/// The model tier this turn runs on whatever Laya's effort says (see [`crate::router::with_tier`]).@@ -1903,6 +1906,7 @@ pub(super) async fn turn_once(tag: tag.clone(),outcome: "cancelled",running_row: None,+ quiet: opts.quiet_finish,};let Some(_slot) = turns.acquire(&tag, &scope.cancel_token, &scope.state.event_sender).await else {return Err("stopped by the user".into());@@ -2033,6 +2037,8 @@ struct TurnEndedGuard {outcome: &'static str,/// Set once the turn is recorded as running; the record is removed when the turn ends.running_row: Option<crate::db::Database>,+ /// See [`TurnOpts::quiet_finish`].+ quiet: bool,}impl Drop for TurnEndedGuard {@@ -2053,6 +2059,7 @@ impl Drop for TurnEndedGuard {outcome: self.outcome.to_string(),turn_id: Some(tag.turn_id),thread_id: tag.thread_id,+ quiet: self.quiet,});}}diff --git a/src/server/sse.rs b/src/server/sse.rsindex adde9386..27d75bf1 100644--- a/src/server/sse.rs+++ b/src/server/sse.rs@@ -221,7 +221,7 @@ mod tests {E::ApprovalWithdrawn { id: s("a") },E::TurnComplete { tokens: 1, duration_ms: 1, kwant_id: Some(s("k")), profile_id: None },E::TurnStarted { kwant_id: s("k"), context_id: Some(s("c")), turn_id: None, thread_id: None },- E::TurnEnded { kwant_id: s("k"), context_id: None, outcome: s("completed"), turn_id: None, thread_id: None },+ E::TurnEnded { kwant_id: s("k"), context_id: None, outcome: s("completed"), turn_id: None, thread_id: None, quiet: false },E::TurnQueued { turn_id: s("x"), kwant_id: s("k"), context_id: None, thread_id: None, position: 1, reason: s("x") },E::ThreadUpdated { thread: json!({"id": "th", "kwant_id": "k"}) },E::DelegationUpdated { delegation: json!({"id": "d", "lead_kwant_id": "k", "thread_id": "th"}) },diff --git a/tests/approvals_off_test.rs b/tests/approvals_off_test.rsindex f86240b4..b0195d71 100644--- a/tests/approvals_off_test.rs+++ b/tests/approvals_off_test.rs@@ -133,32 +133,46 @@ async fn ask_tool(e: &Env, bot: &Kwant, tool: &str, input: Value, always_ask: bolet path = format!("/api/mcp/permission/{token}");let mut prompt = tokio::spawn(async move { call(&app, "POST", &path, None, Some(ask)).await });- let answered = tokio::time::timeout(Duration::from_millis(1500), &mut prompt).await;- let carded = loop {- match events.try_recv() {- Ok(RuntimeEvent::ApprovalRequired { id, .. }) => break Some(id),- Ok(_) => continue,- Err(_) => break None,- }- };+ // Polled, not one fixed wait: under load the answer or the card can take seconds to come+ let deadline = tokio::time::Instant::now() + Duration::from_secs(15);+ let mut carded = card_in(&mut events);+ while carded.is_none() && !prompt.is_finished() && tokio::time::Instant::now() < deadline {+ tokio::time::sleep(Duration::from_millis(50)).await;+ carded = card_in(&mut events);+ }+ // An answer without a card must not have raised one on its way either+ let answered = prompt.is_finished();+ let carded = carded.or_else(|| card_in(&mut events));let outcome = match (answered, carded) {- (Ok(done), None) => {- let (status, v) = done.unwrap();+ (true, None) => {+ let (status, v) = (&mut prompt).await.unwrap();assert_eq!(status, StatusCode::OK, "{v}");Some(v["result"]["content"][0]["text"].as_str().unwrap().contains(r#""behavior":"allow""#))}- (Err(_), Some(id)) => {+ (false, Some(id)) => {assert!(e.state.broker.resolve(&id, ApprovalDecision::Deny).await);prompt.await.unwrap();None}- (answered, carded) => panic!("answered {} with card {carded:?}", answered.is_ok()),+ (answered, carded) => panic!("answered {answered} with card {carded:?} (15 s)"),};mcp_runtime::finish_turn(&e.state, &token).await;e.state.turns.end_turn(&turn_id);outcome}+/// The id of an approval card among the events received so far, if one was shown.+fn card_in(events: &mut tokio::sync::broadcast::Receiver<RuntimeEvent>) -> Option<String> {+ use tokio::sync::broadcast::error::TryRecvError;+ loop {+ match events.try_recv() {+ Ok(RuntimeEvent::ApprovalRequired { id, .. }) => return Some(id),+ Ok(_) | Err(TryRecvError::Lagged(_)) => continue,+ Err(_) => return None,+ }+ }+}+async fn self_tool(e: &Env, token: &str, name: &str, args: Value) -> (String, bool) {let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}});let (status, v) = call(&e.app, "POST", "/api/mcp/self", Some(token), Some(rpc)).await;diff --git a/tests/continuity_test.rs b/tests/continuity_test.rsindex f999a6f6..7da077c1 100644--- a/tests/continuity_test.rs+++ b/tests/continuity_test.rs@@ -1725,6 +1725,7 @@ async fn notifications_are_filtered_and_content_free() {outcome: "completed".into(),turn_id: None,thread_id: None,+ quiet: false,});let _ = state.event_sender.send(RuntimeEvent::TurnEnded {kwant_id: k.id.clone(),@@ -1732,6 +1733,16 @@ async fn notifications_are_filtered_and_content_free() {outcome: "failed".into(),turn_id: None,thread_id: None,+ quiet: false,+ });+ // A quiet turn (a mission runner turn) leaves its notification to the runner+ let _ = state.event_sender.send(RuntimeEvent::TurnEnded {+ kwant_id: k.id.clone(),+ context_id: Some(general.id.clone()),+ outcome: "completed".into(),+ turn_id: None,+ thread_id: None,+ quiet: true,});let _ = state.event_sender.send(RuntimeEvent::ApprovalRequired {id: "a1".into(),diff --git a/tests/mission_autofix_test.rs b/tests/mission_autofix_test.rsindex f636bc14..e007f040 100644--- a/tests/mission_autofix_test.rs+++ b/tests/mission_autofix_test.rs@@ -18,9 +18,10 @@ use kwnt::{broker::PermissionBroker,config::Config,db::{autofix::NewAttempt, continuity::NewRoutine, models::Kwant, spaces::SpaceId, Database},+ drivers::events::RuntimeEvent,router::LayaRouter,server::{- continuity::{SelfScope, TurnOrigin},+ continuity::{self, SelfScope, TurnOrigin},create_router, mcp_runtime,missions::{autofix::classify, listener, runner},AppState,@@ -376,6 +377,83 @@ async fn a_failing_check_is_retried_with_its_diagnostics_until_the_attempts_run_assert!(err.contains("within the task's attempts"), "{err}");}+/// The notifier, and the `turn_finished` notifications of `bot` it sends, collected as they come+/// (the event bus holds only 128 events, so they can't be read afterwards).+fn finished_notes(state: &AppState, bot: &str) -> (tokio::task::JoinHandle<()>, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {+ let notes = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let (mut rx, seen, bot) = (state.event_sender.subscribe(), notes.clone(), bot.to_string());+ let notifier = continuity::spawn_notifier(state.clone());+ let collector = tokio::spawn(async move {+ loop {+ match rx.recv().await {+ Ok(RuntimeEvent::Notify { kind, kwant_id, body, .. }) if kind == "turn_finished" && kwant_id == bot => seen.lock().unwrap().push(body),+ Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,+ Err(_) => return,+ }+ }+ });+ let both = tokio::spawn(async move {+ let _ = collector.await;+ notifier.abort();+ });+ (both, notes)+}++// M1 of the 0.6.5 defaults-on QA: AutoFix is on by default, and its retries are background turns+#[tokio::test]+async fn a_failing_task_notifies_once_for_its_outcome_and_a_passing_one_still_notifies() {+ let e = setup().await;+ autofix(&e, "on", 25).await;+ let (mid, tid) = cli_mission(&e, 50_000).await;+ let ann = e.state.db.get_mission(&mid).await.unwrap().unwrap().lead_kwant_id;+ let (watch, notes) = finished_notes(&e.state, &ann);+ person(&e, "POST", &format!("/api/missions/{mid}/run"), Some(json!({"max_tasks": 1}))).await;+ // Three runs: the first, then two AutoFix retries; the last one has no attempt left+ for _ in 0..600 {+ let t = task(&e, &tid).await;+ if t["state"] == "failed" && t["attempts"] == 3 && attempts(&e, &tid).await.iter().any(|a| a.status == "skipped") {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ runner_idle(&e.state, &mid).await;+ assert_eq!(prompts(&tid).len(), 3, "three runner turns ran");+ for _ in 0..40 {+ if !notes.lock().unwrap().is_empty() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ // Late ones would show up here+ tokio::time::sleep(Duration::from_millis(500)).await;+ let got = notes.lock().unwrap().clone();+ assert_eq!(got.len(), 1, "one notification for the task's final outcome, not one per attempt: {got:?}");+ assert!(got[0].contains("#general"), "{got:?}");++ // A task that passes on its first run still notifies, once+ let body = json!({"title": "Ship more", "goal": "another release", "lead_kwant_id": ann, "budget_tokens": 900_000,+ "channel_id": e.general, "tasks": [{"title": "B", "owner": ann, "budget_tokens": 50_000,+ "checks": [{"kind": "command", "spec": {"command": "echo fine"}}]}]});+ let m2 = id(&person(&e, "POST", "/api/missions", Some(body)).await);+ let t2 = id(&person(&e, "GET", &format!("/api/missions/{m2}"), None).await["tasks"][0]);+ let row = e.state.db.get_mission(&m2).await.unwrap().unwrap();+ std::fs::create_dir_all(&row.workspace_path).unwrap();+ person(&e, "POST", &format!("/api/missions/{m2}/run"), Some(json!({"max_tasks": 1}))).await;+ wait_state(&e, &t2, "verified").await;+ runner_idle(&e.state, &m2).await;+ for _ in 0..40 {+ if notes.lock().unwrap().len() >= 2 {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ tokio::time::sleep(Duration::from_millis(300)).await;+ let got = notes.lock().unwrap().clone();+ assert_eq!(got.len(), 2, "the passing task's turn notified once: {got:?}");+ assert!(attempts(&e, &t2).await.is_empty(), "no AutoFix attempt for a passing task");+ watch.abort();+}+// 3#[tokio::test]async fn off_records_only_and_suggest_waits_for_the_person() {