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
Delegations: late answers reach the lead; failures, stops and restarts resume it
Lin (kwant bot)8dd9a80c6dd5
diff --git a/src/server/delegation.rs b/src/server/delegation.rsindex fd37a7e5..4d0187b5 100644--- a/src/server/delegation.rs+++ b/src/server/delegation.rs@@ -48,6 +48,17 @@ fn clip(text: &str, max: usize) -> String {out}+/// A specialist's reply as posted to the origin chat: clipped, saying where the rest is.+fn result_text(reply: &str) -> String {+ let full = reply.trim();+ let mut text = clip(full, RESULT_CHARS);+ // Counted in chars like `clip`: in bytes, the added "…" can make a clipped text look longer+ if text.chars().count() < full.chars().count() {+ text.push_str("\n\n(The full answer is in the delegation thread.)");+ }+ text+}+/// Minutes after which an unfinished delegation gets one "still working" note; 0 turns it off.pub async fn follow_up_minutes(state: &AppState) -> i64 {state@@ -369,14 +380,7 @@ async fn finish(state: &AppState, d: &Delegation, specialist: &Kwant, outcome: Rreturn;};let text = match &outcome {- Ok(reply) => {- let full = reply.trim();- let mut text = clip(full, RESULT_CHARS);- if text.len() < full.len() {- text.push_str("\n\n(The full answer is in the delegation thread.)");- }- text- }+ Ok(reply) => result_text(reply),Err(_) if status == "cancelled" => format!("Stopped work on “{}”.", done.title),Err(e) => format!("Couldn't finish “{}”: {}", done.title, clip(e, 500)),};@@ -384,6 +388,23 @@ async fn finish(state: &AppState, d: &Delegation, specialist: &Kwant, outcome: Rif let Some(id) = &result_id {let _ = state.db.set_delegation_result_message(&done.id, id).await;}+ // The specialist asked the person something and ended its turn waiting: say where to answer+ if let Some(q) = open_question(state, &done).await {+ post_to_origin(+ state,+ &done,+ "system",+ "kwnt",+ format!(+ "{} is waiting for your answer to “{}” in the thread of “{}”. Answer it there; the result will come back here.",+ specialist.name,+ clip(&q.question, 200),+ done.title+ ),+ meta("delegation_waiting", &done, &specialist.name),+ )+ .await;+ }let done = state.db.get_delegation(&d.id).await.ok().flatten().unwrap_or(done);emit_delegation(state, &done);tracing::info!(delegation = %done.id, status, "delegation finished");@@ -400,11 +421,83 @@ async fn finish(state: &AppState, d: &Delegation, specialist: &Kwant, outcome: R},).await;- if done.continue_lead {- if let Some(batch) = finished_batch(state, &done).await {- continue_lead(state, &done, &batch).await;- }+ report_to_lead(state, &done, None).await;+}++/// Resumes the lead once `d` ended, if it was the last of its batch to end (see+/// [`finished_batch`]). `opening` replaces the first line of the lead's prompt.+async fn report_to_lead(state: &AppState, d: &Delegation, opening: Option<String>) {+ if !d.continue_lead {+ return;+ }+ if let Some(batch) = finished_batch(state, d).await {+ continue_lead(state, d, &batch, opening).await;+ }+}++/// [`report_to_lead`] in the background, for callers that must not wait for the lead's turn.+fn spawn_report_to_lead(state: &AppState, d: Delegation) {+ let state = state.clone();+ tokio::spawn(async move { report_to_lead(&state, &d, None).await });+}++/// A question the specialist asked in the delegation's thread that the person hasn't answered.+async fn open_question(state: &AppState, d: &Delegation) -> Option<crate::db::questions::Question> {+ state+ .db+ .list_questions(Some("open"), Some(&d.thread_id), None)+ .await+ .ok()?+ .into_iter()+ .find(|q| q.kwant_id == d.specialist_kwant_id && q.thread_id.as_deref() == Some(d.thread_id.as_str()))+}++/// A late answer to a question the specialist asked in an ended delegation's thread: the+/// specialist continues there, its new result is posted to the origin chat, and the lead gets+/// a turn with it. `false` when the delegation can't continue (a bot is gone, or it is still+/// running and the answer is just a new turn in its thread).+pub async fn resume_after_answer(state: &AppState, d: Delegation, question_id: &str, prompt: String) -> bool {+ if d.is_open() {+ return false;}+ let (Ok(Some(_)), Ok(Some(specialist))) =+ (state.db.get_kwant(&d.lead_kwant_id).await, state.db.get_kwant(&d.specialist_kwant_id).await)+ else {+ return false;+ };+ let job = state.turns.start_job([d.id.clone(), d.thread_id.clone(), question_id.to_string()]);+ let state = state.clone();+ tokio::spawn(async move {+ let scope = match scope_for(&state, &specialist, None, Some(d.thread_id.clone()), &job, d.depth).await {+ Ok(s) => s,+ Err(_) => return,+ };+ let outcome = try_kwant_turn(&scope, &specialist, prompt, TurnOpts::default()).await;+ let outcome = continue_once_if_capped(&scope, &specialist, outcome, false).await;+ let stopped = job.token.is_cancelled();+ drop(job);+ let reply = match outcome {+ Ok(reply) => reply,+ // A failed turn already said why in the thread; a stopped one was the person's choice+ Err(e) if stopped => return tracing::info!(delegation = %d.id, error = %e, "late answer's turn stopped"),+ Err(e) => format!("Couldn't finish “{}” after your answer: {}", d.title, clip(&e, 500)),+ };+ let text = result_text(&reply);+ let mut m = meta("delegation_result", &d, &specialist.name);+ m["late"] = json!(true);+ if let Some(id) = post_to_origin(&state, &d, "kwant", &specialist.name, text, m).await {+ let _ = state.db.set_delegation_result_message(&d.id, &id).await;+ }+ tracing::info!(delegation = %d.id, "delegation continued after a late answer");+ if d.continue_lead {+ let opening = format!(+ "{} got the person's answer to its question and continued the task you delegated (“{}”).",+ specialist.name, d.title+ );+ continue_lead(&state, &d, std::slice::from_ref(&d), Some(opening)).await;+ }+ });+ true}/// The delegations a lead sent from one chat that ran at the same time as `d`, once all of them@@ -442,7 +535,9 @@ async fn finished_batch(state: &AppState, d: &Delegation) -> Option<Vec<Delegati}}let last = batch.iter().max_by(|a, b| end(a).cmp(&end(b)).then_with(|| a.id.cmp(&b.id)))?;- if last.id != d.id || !batch.iter().any(|b| b.status == "completed") {+ // A batch the person stopped entirely stays stopped; anything else (a result, a failure, a+ // restart cutting it short) is the lead's to report+ if last.id != d.id || batch.iter().all(|b| b.status == "cancelled") {return None;}batch.sort_by_key(|b| b.created_at);@@ -465,8 +560,8 @@ async fn result_of(state: &AppState, d: &Delegation) -> String {}/// Gives the lead one turn in the origin chat with every result of the batch, so it checks them-/// and gives the user one answer.-async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation]) {+/// and gives the user one answer. Tasks that didn't complete say what the lead should do about it.+async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation], opening: Option<String>) {let Ok(Some(lead)) = state.db.get_kwant(&d.lead_kwant_id).await else {return;};@@ -483,17 +578,38 @@ async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation]) {"completed" => clip(&result_of(state, b).await, budget),_ => format!("({}: {})", b.status, b.error.as_deref().unwrap_or("no result")),};- results.push_str(&format!("### {who}: “{}”\n{}\n\n", b.title, crate::drivers::peer_message(&who, &body)));+ results.push_str(&format!("### {who}: “{}”\n{}\n", b.title, crate::drivers::peer_message(&who, &body)));+ if let Some(q) = open_question(state, b).await {+ results.push_str(&format!(+ "(Waiting: {who} asked the person “{}” in its thread and has no answer yet. Don't redo this task: tell the \+ person the question is waiting in that thread. When they answer, {who} continues and you get its result.)\n",+ clip(&q.question, 200)+ ));+ }+ if let Some(next) = status_guidance(&b.status) {+ results.push_str(next);+ results.push('\n');+ }+ results.push('\n');}- let opening = match batch {- [one] => format!("{} finished the task you delegated (“{}”).", name_of(state, &one.specialist_kwant_id).await, one.title),- _ => format!("All {} tasks you delegated have ended.", batch.len()),+ let opening = match (opening, batch) {+ (Some(o), _) => o,+ (None, [one]) if one.status == "completed" => {+ format!("{} finished the task you delegated (“{}”).", name_of(state, &one.specialist_kwant_id).await, one.title)+ }+ (None, [one]) => format!(+ "The task you delegated to {} (“{}”) ended without a result: {}.",+ name_of(state, &one.specialist_kwant_id).await,+ one.title,+ one.status+ ),+ (None, _) => format!("All {} tasks you delegated have ended.", batch.len()),};let prompt = format!("{opening} The results are in the chat above, quoted here:\n\n{results}\Check each result against what the user asked. If something is missing or wrong, delegate a concrete \correction. Otherwise continue with the user's request and give them one answer that uses the results. \- Don't repeat the results in full."+ If a task failed, was stopped or was cut short, say so plainly. Don't repeat the results in full.");// The follow-up may hand on to the next teammate by @mention, like any lead reply. Not back to// the ones that just reported (the result is what it's about), and within the usual limits.@@ -514,6 +630,16 @@ async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation]) {}}+/// What the lead should do about a task that ended without a result.+fn status_guidance(status: &str) -> Option<&'static str> {+ match status {+ "failed" => Some("(It failed. Decide whether to retry it, give it to someone else or do it yourself, and tell the person which.)"),+ "cancelled" => Some("(It was stopped. Don't restart it unless the person asks.)"),+ "interrupted" => Some("(kwnt restarted twice while it ran, so it may be partly done. Tell the person and offer to run it again.)"),+ _ => None,+ }+}+// Cancelling, follow-ups, restarts/// Stops a delegation and reports it; `None` if it was already over.@@ -538,6 +664,8 @@ pub async fn cancel(state: &AppState, id: &str) -> Option<Delegation> {let _ = state.db.set_delegation_result_message(&done.id, &mid).await;}emit_delegation(state, &done);+ // A stopped task alone doesn't wake the lead, but other results of its batch must not be lost+ spawn_report_to_lead(state, done.clone());Some(done)}@@ -600,6 +728,7 @@ pub async fn interrupt_open(state: &AppState) {meta("delegation_result", &done, &specialist),).await;+ spawn_report_to_lead(state, done);}for d in again {let Ok(Some(d)) = state.db.get_delegation(&d.id).await else {@@ -646,7 +775,22 @@ async fn restart(state: &AppState, d: Delegation, retried: bool, after_restart:let (Ok(Some(lead)), Ok(Some(specialist))) =(state.db.get_kwant(&d.lead_kwant_id).await, state.db.get_kwant(&d.specialist_kwant_id).await)else {- let _ = state.db.finish_delegation(&d.id, "failed", Some("the bot no longer exists"), None).await;+ if state.db.finish_delegation(&d.id, "failed", Some("the bot no longer exists"), None).await.unwrap_or(false) {+ if let Ok(Some(done)) = state.db.get_delegation(&d.id).await {+ let specialist = name_of(state, &done.specialist_kwant_id).await;+ post_to_origin(+ state,+ &done,+ "system",+ "kwnt",+ format!("Couldn't restart “{}”: the bot no longer exists.", done.title),+ meta("delegation_result", &done, &specialist),+ )+ .await;+ emit_delegation(state, &done);+ spawn_report_to_lead(state, done);+ }+ }return false;};let job = state.turns.start_job([d.id.clone(), d.thread_id.clone()]);diff --git a/src/server/questions.rs b/src/server/questions.rsindex 232a1ffa..9f7c2d91 100644--- a/src/server/questions.rs+++ b/src/server/questions.rs@@ -361,23 +361,32 @@ pub async fn answer(State(state): State<AppState>, Path(id): Path<String>, Json(Json(json!({"question": q, "resumed": if live { "turn" } else { "new_turn" }})).into_response()}-/// A late answer: a new turn in the question's chat, queued like any other turn.+/// A late answer: a new turn in the question's chat, queued like any other turn. In an ended+/// delegation's thread the result also goes back to the lead (see+/// [`super::delegation::resume_after_answer`]).async fn resume(state: &AppState, q: &Question, answer: &str) {let Ok(Some(kwant)) = state.db.get_kwant(&q.kwant_id).await else {return;};- let depth = match &q.thread_id {- Some(t) => state.db.delegation_for_thread(t).await.ok().flatten().map(|d| d.depth).unwrap_or(0),- None => 0,- };- let job = state.turns.start_job([q.context_id(), q.id.clone()]);- let Ok(scope) = scope_for(state, &kwant, q.channel_id.clone(), q.thread_id.clone(), &job, depth).await else {- return;+ let delegation = match &q.thread_id {+ Some(t) => state.db.delegation_for_thread(t).await.ok().flatten(),+ None => None,};let prompt = format!("[The user answered the question you asked earlier]\nQuestion: {}\nAnswer: {answer}\n\nContinue the task with this answer.",q.question);+ // The specialist of an ended delegation asked it: its new result goes back to the lead+ if let Some(d) = delegation.clone().filter(|d| d.specialist_kwant_id == q.kwant_id) {+ if super::delegation::resume_after_answer(state, d, &q.id, prompt.clone()).await {+ return;+ }+ }+ let depth = delegation.map(|d| d.depth).unwrap_or(0);+ let job = state.turns.start_job([q.context_id(), q.id.clone()]);+ let Ok(scope) = scope_for(state, &kwant, q.channel_id.clone(), q.thread_id.clone(), &job, depth).await else {+ return;+ };tokio::spawn(async move {let _job = job;let _ = try_kwant_turn(&scope, &kwant, prompt, TurnOpts::default()).await;diff --git a/tests/ask_user_test.rs b/tests/ask_user_test.rsindex 7789a903..e05e33f9 100644--- a/tests/ask_user_test.rs+++ b/tests/ask_user_test.rs@@ -254,3 +254,45 @@ async fn every_question_route_needs_auth() {assert_eq!(call_remote(&env.app, m, u).await, StatusCode::UNAUTHORIZED, "{m} {u}");}}++/// A specialist's question in a delegation thread that the person answers after the wait ran+/// out: the lead hears the question is waiting, and once answered, the specialist continues, its+/// new result is posted where the task came from, and the lead is resumed with it.+#[tokio::test]+async fn a_late_answer_in_a_delegation_reaches_the_lead() {+ let env = setup().await;+ env.state.questions.set_wait(Duration::from_millis(300));+ let task = format!("Pick a region. {} REPLYTAG:asked", ask_marker("Which region for the delegated job?", &["eu", "us"]));+ let (s, d) = call(+ &env.app,+ "POST",+ "/api/delegations",+ Some(json!({"lead_kwant_id": env.a, "specialist_kwant_id": env.b, "task": task, "title": "Region pick", "kwant_id": env.a})),+ )+ .await;+ assert_eq!(s, StatusCode::ACCEPTED, "{d}");+ let thread = d["thread_id"].as_str().unwrap().to_string();++ // The wait runs out: the lead is told the question is waiting, not to redo the work+ wait_for("the lead's turn", || async { !invocations_with("finished the task you delegated (“Region pick”)").is_empty() }).await;+ let lead = invocations_with("finished the task you delegated (“Region pick”)").pop().unwrap();+ assert!(lead.contains("Which region for the delegated job?") && lead.contains("Don't redo this task"), "{lead}");+ let origin = messages(&env, &env.a).await;+ assert!(origin.iter().any(|m| m.text.contains("is waiting for your answer") && m.text.contains("Which region")), "{origin:?}");++ let q = open_question(&env, &thread).await;+ let id = q["id"].as_str().unwrap();+ let (s, v) = call(&env.app, "POST", &format!("/api/questions/{id}/answer"), Some(json!({"text": "eu REPLYTAG:afteranswer"}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["resumed"], "new_turn");++ // The specialist continues in the thread, the result comes back, and the lead gets it+ wait_for("the lead's turn with the late result", || async { !invocations_with("got the person's answer").is_empty() }).await;+ let lead = invocations_with("got the person's answer").pop().unwrap();+ assert!(lead.contains("“Region pick”") && lead.contains("answer afteranswer"), "{lead}");+ let origin = messages(&env, &env.a).await;+ let late = origin.iter().find(|m| m.text == "answer afteranswer").expect("the late result in the origin chat");+ let meta: Value = serde_json::from_str(late.meta.as_deref().unwrap()).unwrap();+ assert_eq!((meta["kind"].as_str(), meta["late"].as_bool()), (Some("delegation_result"), Some(true)));+ assert_eq!(invocations_with("got the person's answer").len(), 1, "the lead is resumed once");+}diff --git a/tests/delegation_test.rs b/tests/delegation_test.rsindex c7fcabf5..84de84fb 100644--- a/tests/delegation_test.rs+++ b/tests/delegation_test.rs@@ -24,13 +24,15 @@ use tower::ServiceExt;/// Replies "answer <tag>" for a prompt with "REPLYTAG:<tag>", followed by "@<name>" for one with/// "MENTION:<name>", and by "`@<name>`" (inline code, as models write it) for a lead's results-/// follow-up with "FOLLOWUP:<name>"; a "LONGTASK:<file>" prompt waits (up to 60 s) for that file first. Every prompt is saved under `$KWNT_TEST_PROMPTS`.+/// follow-up with "FOLLOWUP:<name>"; a "LONGTASK:<file>" prompt waits (up to 60 s) for that file first, and a+/// "FAILTASK" prompt fails. Every prompt is saved under `$KWNT_TEST_PROMPTS`.const FAKE_CLAUDE: &str = r#"#!/bin/shcase "$1" inauth) echo '{"loggedIn":true}'; exit 0 ;;esacfor a; do last="$a"; doneprintf '%s' "$last" > "$KWNT_TEST_PROMPTS/$$-$(date +%s%N)"+case "$last" in *FAILTASK*) echo "boom" >&2; exit 1 ;; esacrelease=$(printf '%s\n' "$last" | sed -n 's/.*LONGTASK:\([^ ]*\).*/\1/p' | head -n 1)if [ -n "$release" ]; theni=0@@ -847,9 +849,11 @@ async fn run_fan_in(env: &Env, third: String) {assert!(prompts_with("(“Fan part A”)").is_empty(), "no turn for A alone");std::fs::write(&rel_b, "").unwrap();wait_for("part B to complete", || async { delegation_status(env, &ids[1]).await == "completed" }).await;- wait_for("the lead's one continuation turn", || async { !prompts_with("All 2 tasks you delegated have ended").is_empty() }).await;+ // Other tests in this binary end batches of two as well+ let resumed = || prompts_with("All 2 tasks you delegated have ended").into_iter().filter(|p| p.contains("Fan part A")).collect::<Vec<_>>();+ wait_for("the lead's one continuation turn", || async { !resumed().is_empty() }).await;tokio::time::sleep(Duration::from_millis(500)).await;- let resumed = prompts_with("All 2 tasks you delegated have ended");+ let resumed = resumed();assert_eq!(resumed.len(), 1, "exactly one resume");let p = &resumed[0];assert!(p.contains("answer fanA") && p.contains("answer fanB"), "both results: {p}");@@ -1147,3 +1151,82 @@ fn per_bot_limit() -> usize {fn routes_limit() -> usize {kwnt::server::routes::MAX_DELEGATIONS_PER_REQUEST}++/// Starts a delegation from the lead to the specialist that resumes the lead when it ends.+async fn delegate_resuming(env: &Env, task: &str, title: &str) -> String {+ let (s, d) = call(+ &env.app,+ "POST",+ "/api/delegations",+ Some(json!({"lead_kwant_id": env.lead, "specialist_kwant_id": env.specialist, "task": task, "title": title, "kwant_id": env.lead})),+ )+ .await;+ assert_eq!(s, StatusCode::ACCEPTED, "{d}");+ d["id"].as_str().unwrap().to_string()+}++/// A task that fails or that restarts cut short twice still gives the lead a turn, with what+/// happened and what to do about it, so the person isn't left without an answer.+#[tokio::test]+async fn a_failed_or_interrupted_task_still_resumes_the_lead() {+ let env = setup().await;+ let id = delegate_resuming(&env, "Broken FAILTASK", "Doomed job").await;+ wait_for("the task to fail", || async { delegation_status(&env, &id).await == "failed" }).await;+ wait_for("the lead's turn", || async { !prompts_with("(“Doomed job”) ended without a result: failed").is_empty() }).await;+ let p = prompts_with("(“Doomed job”) ended without a result: failed").pop().unwrap();+ assert!(p.contains("Decide whether to retry it") && p.contains("say so plainly"), "{p}");++ let (_, open) = env+ .state+ .db+ .create_delegation(&kwnt::db::threads::NewDelegation {+ lead_kwant_id: env.lead.clone(),+ specialist_kwant_id: env.specialist.clone(),+ origin_channel_id: None,+ origin_kwant_id: Some(env.lead.clone()),+ origin_thread_id: None,+ team_id: None,+ task: "t REPLYTAG:never".into(),+ title: "Cut twice for the lead".into(),+ continue_lead: true,+ depth: 1,+ follow_up_at: None,+ })+ .await+ .unwrap();+ env.state.db.restart_open_delegations().await.unwrap();+ delegation::interrupt_open(&env.state).await;+ assert_eq!(delegation_status(&env, &open.id).await, "interrupted");+ let marker = "(“Cut twice for the lead”) ended without a result: interrupted";+ wait_for("the lead's turn", || async { !prompts_with(marker).is_empty() }).await;+ assert!(prompts_with(marker)[0].contains("kwnt restarted twice"));+}++/// The person's Stop on a lone task doesn't wake the lead, but stopping the last open task of a+/// batch still hands the lead the results that did come back.+#[tokio::test]+async fn a_stop_resumes_the_lead_only_for_the_rest_of_its_batch() {+ let env = setup().await;+ let solo = env.release_file("solo");+ let id = delegate_resuming(&env, &format!("Solo LONGTASK:{} REPLYTAG:solo", solo.display()), "Solo stop").await;+ wait_for("the task to run", || async { delegation_status(&env, &id).await == "running" }).await;+ let (s, _) = call(&env.app, "POST", &format!("/api/delegations/{id}/cancel"), None).await;+ assert_eq!(s, StatusCode::OK);+ std::fs::write(&solo, "").unwrap();+ tokio::time::sleep(Duration::from_millis(800)).await;+ assert!(prompts_with("(“Solo stop”) ended without a result").is_empty(), "a lone stop doesn't wake the lead");++ let (keep, drop_) = (env.release_file("keep"), env.release_file("drop"));+ let kept = delegate_resuming(&env, &format!("Part LONGTASK:{} REPLYTAG:keepme", keep.display()), "Kept part").await;+ let stopped = delegate_resuming(&env, &format!("Part LONGTASK:{} REPLYTAG:dropme", drop_.display()), "Stopped part").await;+ std::fs::write(&keep, "").unwrap();+ wait_for("the first part to complete", || async { delegation_status(&env, &kept).await == "completed" }).await;+ wait_for("the second part to run", || async { delegation_status(&env, &stopped).await == "running" }).await;+ let (s, _) = call(&env.app, "POST", &format!("/api/delegations/{stopped}/cancel"), None).await;+ assert_eq!(s, StatusCode::OK);+ std::fs::write(&drop_, "").unwrap();+ let resumed = || prompts_with("All 2 tasks you delegated have ended").into_iter().filter(|p| p.contains("Kept part")).collect::<Vec<_>>();+ wait_for("the lead's turn", || async { !resumed().is_empty() }).await;+ let p = resumed().pop().unwrap();+ assert!(p.contains("answer keepme") && p.contains("It was stopped"), "{p}");+}