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
Hand-offs that wait for each other; one list of questions (F4, F5)
Lin (kwant bot)b9253b122fff
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 45d6b916..a5154083 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).is solved, with a different buzz for errors. A bot reply arriving while the app is on screen gives alight double buzz, once per reply and at most one every 3 seconds. A **Vibration** switch in Appsettings turns it off; it starts off when the phone asks for reduced motion. iPhones and desktops have no web vibration.+- **Hand-offs that wait for each other.** When a bot's reply asks one teammate to go "once @Analyst+ has the numbers" (also "after", "when … has finished", "wait for"), that teammate starts only when+ the other has finished, and gets its result. Other teammates in the same reply still start right+ away. If the first one fails or asks you something, the waiting one doesn't start, and the chat says why.+- **One list of questions.** When two or more bots ask you something after one message, the team+ lead (or the bot that started) posts one numbered list of everything they need. Your answer goes+ to the lead, which passes each part on; bots waiting on a question card continue directly.### Changed- A bot reply that ends with a closing line such as "Anything else?", "Should I continue?" ordiff --git a/src/db/threads.rs b/src/db/threads.rsindex 03214355..7a97d7e4 100644--- a/src/db/threads.rs+++ b/src/db/threads.rs@@ -55,6 +55,10 @@ pub struct Delegation {/// Times a kwnt restart sent it back to the queue (at most once).#[sqlx(default)]pub retries: i64,+ /// A delegation whose result this one waits for before it starts ("@Writer, once @Analyst+ /// has the numbers, …"). Set while it is parked as `queued`; cleared when it starts.+ #[sqlx(default)]+ pub after_delegation_id: Option<String>,}impl Delegation {@@ -148,6 +152,9 @@ impl Database {] {sqlx::query(stmt).execute(&self.pool).await?;}+ let _ = sqlx::query("ALTER TABLE delegations ADD COLUMN after_delegation_id TEXT;")+ .execute(&self.pool)+ .await;Ok(())}@@ -284,6 +291,7 @@ impl Database {started_at: None,ended_at: None,retries: 0,+ after_delegation_id: None,};sqlx::query("INSERT INTO delegations (id, thread_id, lead_kwant_id, specialist_kwant_id, origin_channel_id, origin_kwant_id, \@@ -412,6 +420,49 @@ impl Database {Ok(res.rows_affected() > 0)}+ /// Parks a queued delegation until `after` (another delegation) ends.+ pub async fn set_delegation_after(&self, id: &str, after: &str) -> Result<(), DbError> {+ sqlx::query("UPDATE delegations SET after_delegation_id = ? WHERE id = ? AND status = 'queued'")+ .bind(after)+ .bind(id)+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// Delegations parked until `after` ends.+ pub async fn list_dependent_delegations(&self, after: &str) -> Result<Vec<Delegation>, DbError> {+ Ok(sqlx::query_as::<_, Delegation>(+ "SELECT * FROM delegations WHERE after_delegation_id = ? AND status = 'queued' ORDER BY created_at",+ )+ .bind(after)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Every parked delegation, whatever it waits for.+ pub async fn list_parked_delegations(&self) -> Result<Vec<Delegation>, DbError> {+ Ok(sqlx::query_as::<_, Delegation>(+ "SELECT * FROM delegations WHERE after_delegation_id IS NOT NULL AND status = 'queued' ORDER BY created_at",+ )+ .fetch_all(&self.pool)+ .await?)+ }++ /// Unparks a delegation with its final `task` (the prerequisite's result added); `false`+ /// when it isn't parked any more (cancelled, or another caller started it).+ pub async fn unpark_delegation(&self, id: &str, task: &str) -> Result<bool, DbError> {+ let res = sqlx::query(+ "UPDATE delegations SET task = ?, after_delegation_id = NULL WHERE id = ? AND status = 'queued' \+ AND after_delegation_id IS NOT NULL",+ )+ .bind(task)+ .bind(id)+ .execute(&self.pool)+ .await?;+ Ok(res.rows_affected() > 0)+ }+pub async fn set_delegation_result_message(&self, id: &str, message_id: &str) -> Result<(), DbError> {sqlx::query("UPDATE delegations SET result_message_id = ? WHERE id = ?").bind(message_id)@@ -425,7 +476,7 @@ impl Database {pub async fn take_due_follow_ups(&self, now: DateTime<Utc>) -> Result<Vec<Delegation>, DbError> {let due = sqlx::query_as::<_, Delegation>("SELECT * FROM delegations WHERE status IN ('queued', 'running') AND followed_up = 0 \- AND follow_up_at IS NOT NULL AND follow_up_at <= ? ORDER BY follow_up_at",+ AND after_delegation_id IS NULL AND follow_up_at IS NOT NULL AND follow_up_at <= ? ORDER BY follow_up_at",).bind(now).fetch_all(&self.pool)@@ -444,7 +495,7 @@ impl Database {/// One waiting out a usage limit (a parked turn) is left alone: its retry restarts it.pub async fn restart_open_delegations(&self) -> Result<(Vec<Delegation>, Vec<Delegation>), DbError> {let open = sqlx::query_as::<_, Delegation>(- "SELECT * FROM delegations WHERE status IN ('queued', 'running') AND id NOT IN \+ "SELECT * FROM delegations WHERE status IN ('queued', 'running') AND after_delegation_id IS NULL AND id NOT IN \(SELECT delegation_id FROM parked_turns WHERE status = 'pending' AND delegation_id IS NOT NULL)",).fetch_all(&self.pool)diff --git a/src/router/depends.rs b/src/router/depends.rsnew file mode 100644index 00000000..65baf253--- /dev/null+++ b/src/router/depends.rs@@ -0,0 +1,185 @@+//! Which @mentions of one reply wait for another: "@Scriptwriter, once @Analyst has the numbers,+//! write the script" hands work to both, but the Scriptwriter only starts with the Analyst's result.++/// Words that open a dependency on the teammate named right after them.+const TRIGGERS: &[&str] = &["as soon as", "once", "after", "when", "waiting for", "waits for", "wait for", "until", "based on"];+/// Triggers that need a "done" verb (or a possessive) after the name: "when @Analyst is here"+/// isn't a dependency, "when @Analyst has the numbers" is.+const NEEDS_DONE_VERB: &[&str] = &["as soon as", "once", "when", "until"];+const DONE_VERBS: &[&str] = &[+ "has", "have", "had", "finishes", "finished", "is done", "is finished", "sends", "sent", "delivers", "delivered",+ "reports", "reported", "shares", "shared", "returns", "returned", "posts", "posted", "completes", "completed",+ "pulls", "pulled", "provides", "provided", "gets back", "got", "comes back", "hands", "wraps up", "gives",+];+/// How far after the trigger the teammate's name may start, in words.+const MAX_WORDS_TO_NAME: usize = 3;+/// How far after the name the done verb may start, in characters.+const DONE_VERB_WINDOW: usize = 30;++/// The dependencies in `text` among `names` (teammate names, matched case-insensitively, with or+/// without @): `(dependent, prerequisite)` index pairs into `names`. Each dependent waits for at+/// most one teammate; self-dependencies and cycles are dropped, so every pair can be run in order.+pub fn handoff_dependencies(text: &str, names: &[&str]) -> Vec<(usize, usize)> {+ let mut out: Vec<(usize, usize)> = Vec::new();+ let lower = text.to_lowercase();+ for sentence in lower.split(['\n', '!', '?', ';']).flat_map(|s| s.split(". ")) {+ for (trigger_at, trigger) in triggers(sentence) {+ let after_trigger = trigger_at + trigger.len();+ let Some((prereq, name_end)) = name_after(sentence, after_trigger, names) else { continue };+ if NEEDS_DONE_VERB.contains(&trigger) && !done_after(sentence, name_end) {+ continue;+ }+ let Some(dependent) = dependent_of(sentence, trigger_at, prereq, names) else { continue };+ if out.iter().any(|&(d, _)| d == dependent) || reaches(&out, prereq, dependent) {+ continue;+ }+ out.push((dependent, prereq));+ }+ }+ out+}++/// Trigger words in `sentence`, at word boundaries, in order.+fn triggers(sentence: &str) -> Vec<(usize, &'static str)> {+ let mut found: Vec<(usize, &'static str)> = Vec::new();+ for &t in TRIGGERS {+ for (at, _) in sentence.match_indices(t) {+ if bounded(sentence, at, at + t.len()) && !found.iter().any(|&(a, f)| at >= a && at < a + f.len()) {+ found.push((at, t));+ }+ }+ }+ found.sort();+ found+}++fn bounded(s: &str, start: usize, end: usize) -> bool {+ let word = |c: char| c.is_alphanumeric() || c == '_';+ !s[..start].chars().next_back().is_some_and(word) && !s[end..].chars().next().is_some_and(word)+}++/// The teammate named within a few words after `from` (no comma or colon in between), and where+/// the name ends (after a possessive "'s", which counts as done).+fn name_after(sentence: &str, from: usize, names: &[&str]) -> Option<(usize, usize)> {+ let rest = &sentence[from..];+ let mut best: Option<(usize, usize, usize)> = None; // (start in rest, index, end in sentence)+ for (i, n) in names.iter().enumerate() {+ let n = n.to_lowercase();+ for (at, _) in rest.match_indices(&n) {+ let end = at + n.len();+ if !bounded(rest, at, end) || best.is_some_and(|(b, _, _)| b <= at) {+ continue;+ }+ best = Some((at, i, from + end));+ break;+ }+ }+ let (at, i, end) = best?;+ let between = rest[..at].trim_end_matches('@');+ if between.contains([',', ':', '(', ')']) || between.split_whitespace().count() > MAX_WORDS_TO_NAME {+ return None;+ }+ Some((i, end))+}++/// Whether a possessive or a "done" verb follows the name ending at `end`.+fn done_after(sentence: &str, end: usize) -> bool {+ let rest = &sentence[end..];+ if rest.starts_with("'s") || rest.starts_with("’s") {+ return true;+ }+ let window: String = rest.chars().take(DONE_VERB_WINDOW).collect();+ DONE_VERBS.iter().any(|v| window.match_indices(v).any(|(at, _)| bounded(&window, at, at + v.len())))+}++/// The @mentioned teammate who waits: the last one before the trigger, else the first after it,+/// never the prerequisite itself.+fn dependent_of(sentence: &str, trigger_at: usize, prereq: usize, names: &[&str]) -> Option<usize> {+ let mut mentions: Vec<(usize, usize)> = Vec::new();+ for (i, n) in names.iter().enumerate() {+ let tag = format!("@{}", n.to_lowercase());+ for (at, _) in sentence.match_indices(&tag) {+ if i != prereq && bounded(sentence, at + 1, at + tag.len()) {+ mentions.push((at, i));+ }+ }+ }+ mentions.sort();+ mentions.iter().rev().find(|&&(at, _)| at < trigger_at).or_else(|| mentions.iter().find(|&&(at, _)| at > trigger_at)).map(|&(_, i)| i)+}++/// Whether `from` already (transitively) waits for `to` in `edges`.+fn reaches(edges: &[(usize, usize)], from: usize, to: usize) -> bool {+ let mut at = from;+ for _ in 0..=edges.len() {+ if at == to {+ return true;+ }+ match edges.iter().find(|&&(d, _)| d == at) {+ Some(&(_, p)) => at = p,+ None => return false,+ }+ }+ false+}++#[cfg(test)]+mod tests {+ use super::*;++ const NAMES: &[&str] = &["Analyst", "Scriptwriter", "Editor", "Designer"];++ #[test]+ fn once_has_makes_the_mention_wait() {+ let deps = handoff_dependencies("@Scriptwriter, once @Analyst has the numbers, write the script.", NAMES);+ assert_eq!(deps, vec![(1, 0)]);+ }++ #[test]+ fn after_and_possessive_count() {+ assert_eq!(handoff_dependencies("@Editor please polish it after @Scriptwriter finishes.", NAMES), vec![(2, 1)]);+ assert_eq!(handoff_dependencies("@Designer: when @Analyst's report is in, make the chart", NAMES), vec![(3, 0)]);+ assert_eq!(handoff_dependencies("@Designer, wait for @Analyst and then draw it", NAMES), vec![(3, 0)]);+ }++ #[test]+ fn independent_mentions_have_no_dependencies() {+ assert!(handoff_dependencies("@Analyst pull the numbers. @Scriptwriter draft the hook.", NAMES).is_empty());+ assert!(handoff_dependencies("@Analyst and @Designer, go ahead.", NAMES).is_empty());+ }++ #[test]+ fn when_without_a_done_verb_is_not_a_dependency() {+ assert!(handoff_dependencies("@Designer, when @Analyst is around, say hi.", NAMES).is_empty());+ }++ #[test]+ fn a_comma_between_trigger_and_name_is_not_a_dependency() {+ // "after you're done, ping @Editor" is about the Analyst's own order, not a wait on the Editor+ assert!(handoff_dependencies("@Analyst, after you're done, ping @Editor.", NAMES).is_empty());+ }++ #[test]+ fn dependent_may_come_after_the_trigger() {+ assert_eq!(handoff_dependencies("Once @Analyst has the data, @Designer makes the chart.", NAMES), vec![(3, 0)]);+ }++ #[test]+ fn cycles_and_self_waits_are_dropped() {+ let deps = handoff_dependencies(+ "@Analyst, once @Editor has the draft, check it. @Editor, once @Analyst has checked, edit it.",+ NAMES,+ );+ assert_eq!(deps, vec![(0, 2)]);+ assert!(handoff_dependencies("@Analyst, once @Analyst has it, go.", NAMES).is_empty());+ }++ #[test]+ fn chains_keep_one_prerequisite_each() {+ let deps = handoff_dependencies(+ "@Scriptwriter, after @Analyst sends the numbers write it. @Editor, once @Scriptwriter has the draft, cut it.",+ NAMES,+ );+ assert_eq!(deps, vec![(1, 0), (2, 1)]);+ }+}diff --git a/src/router/mod.rs b/src/router/mod.rsindex 96cf3c7c..c90b6467 100644--- a/src/router/mod.rs+++ b/src/router/mod.rs@@ -1,3 +1,4 @@+pub mod depends;pub mod fallback;pub mod laya;pub mod sidecar;@@ -5,6 +6,7 @@ pub mod sticky;pub mod tags;pub mod team;+pub use depends::handoff_dependencies;pub use fallback::heuristic_fallback;pub use laya::LayaRouter;pub use tags::{handoff_mentions, handoff_targets, only_credited, HandoffMentions, parse_mentions, parse_mentions_with_lookup, TagMention};diff --git a/src/router/sticky.rs b/src/router/sticky.rsindex 9af5cf35..06ae3251 100644--- a/src/router/sticky.rs+++ b/src/router/sticky.rs@@ -29,6 +29,8 @@ impl PartialEq for Awaiting<'_> {/// The bot waiting for the person's answer in a chat, if any. `recent` is the chat oldest first,/// without the message being routed; `open` are the chat's open `ask_user` questions. Only what/// came after the person's last message counts:+/// 0. a list that gathered several bots' questions into one (`meta.consolidated_asks`, see+/// `server::asks`): its bot gets the answer and passes it on;/// 1. the newest open `ask_user` question asked since then by one of `members`;/// 2. else the last bot message since then, when it is an `ask_user` card or ends by asking/// something (and isn't handing on to a teammate with an @mention).@@ -38,6 +40,15 @@ pub fn awaiting_answer<'a>(recent: &[Message], open: &[Question], members: &'a [let since = last_user.and_then(|i| recent[i].created_at);let tail = &recent[last_user.map_or(0, |i| i + 1)..];+ let gathered = tail.iter().rev().find_map(|m| {+ let meta = serde_json::from_str::<serde_json::Value>(m.meta.as_deref()?).ok()?;+ let id = meta.get("consolidated_asks")?["kwant_id"].as_str()?.to_string();+ member(&id)+ });+ if let Some(kwant) = gathered {+ return Some(Awaiting { kwant, question_id: None, card: true });+ }+let asked = open.iter().filter(|q| q.status == "open" && since.is_none_or(|t| q.created_at >= t))@@ -220,6 +231,27 @@ mod tests {assert_eq!(awaiting_answer(&chat, &[], &m).map(|a| a.kwant.id.as_str()), Some("Community"));}+ /// Two bots asked, the lead gathered both into one list: the answer goes to the lead,+ /// not to whichever card is newest.+ #[test]+ fn an_answer_to_a_gathered_list_goes_to_its_lead() {+ let m = members();+ let mut list = msg(30, "kwant", "Architect", "Two things I need from you:\n1. Community: which city?\n2. Analyst: which week?");+ list.meta = Some(r#"{"consolidated_asks":{"kwant_id":"Architect","askers":["Community","Analyst"]}}"#.into());+ let chat = [+ msg(0, "user", "user", "Plan the launch"),+ msg(10, "kwant", "Community", "Which city are you in?"),+ msg(20, "kwant", "Analyst", "Which week should I chart?"),+ list,+ ];+ let open = [question(25, "Analyst", "open")];+ let a = awaiting_answer(&chat, &open, &m).expect("someone waits");+ assert_eq!((a.kwant.id.as_str(), a.question_id, a.card), ("Architect", None, true));+ // Without the list, the newest open card wins as before+ let a = awaiting_answer(&chat[..3], &open, &m).expect("someone waits");+ assert_eq!(a.kwant.id, "Analyst");+ }+fn after(reply: &str) -> Option<String> {let m = members();let chat = [msg(0, "user", "user", "chart last week's signups"), msg(10, "kwant", "Analyst", reply)];diff --git a/src/server/asks.rs b/src/server/asks.rsnew file mode 100644index 00000000..b4c898e2--- /dev/null+++ b/src/server/asks.rs@@ -0,0 +1,263 @@+//! One "what I need from you" list: when the bots of one chain (started by one person message)+//! asked the person 2+ things, the channel's lead (or the bot that started the chain) gets one+//! short extra turn to gather them into a single numbered list, and the person's answer to that+//! list goes to it, which passes each part on.++use super::routes::{try_kwant_turn, TurnOpts, TurnScope};+use super::AppState;+use crate::db::models::{Kwant, Message};+use crate::drivers::RuntimeEvent;+use serde_json::{json, Value};++/// The key of a consolidated list's `meta`: `{kwant_id, askers, question_ids, message_ids}`.+pub const META_KEY: &str = "consolidated_asks";+/// The key an asker's message (a reply or a question card) gets: the list's message id.+pub const INTO_KEY: &str = "consolidated_into";++/// Something a bot asked the person in this chain.+#[derive(Debug, Clone)]+struct Ask {+ kwant: Kwant,+ question: String,+ /// An open question row (a card), if it was one.+ question_id: Option<String>,+ /// The message that shows it (a reply, or the card).+ message_id: Option<String>,+}++fn meta_of(m: &Message) -> Value {+ m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null)+}++/// The consolidated list among `tail` (messages since the person's last one), with its meta.+pub fn consolidated_in(tail: &[Message]) -> Option<(&Message, Value)> {+ tail.iter().rev().find_map(|m| {+ let meta = meta_of(m);+ (m.sender_role == "kwant" && meta.get(META_KEY).is_some()).then(|| (m, meta[META_KEY].clone()))+ })+}++/// The messages after the person's last one, and when that was. `None` when the person never wrote.+fn since_last_user(recent: &[Message]) -> Option<(&[Message], chrono::DateTime<chrono::Utc>)> {+ let i = recent.iter().rposition(|m| m.sender_role == "user")?;+ Some((&recent[i + 1..], recent[i].created_at?))+}++/// Whether a reply's last line hands on to a teammate ("@Writer, can you…?"): that question is+/// for the teammate, not the person.+fn hands_on(text: &str, names: &[&str]) -> bool {+ let last = text.trim_end().lines().last().unwrap_or("").to_lowercase();+ names.iter().any(|n| last.contains(&format!("@{}", n.to_lowercase())))+}++/// At a chain's end in a channel: if 2+ bots asked the person something since their last+/// message, the lead (or the bot that started the chain) posts one list of everything needed.+/// Nothing happens while a delegation from this channel still runs, when the list was already+/// posted, or when fewer than two bots asked.+pub(super) async fn consolidate(scope: &TurnScope) {+ let (Some(cid), None) = (&scope.channel_id, &scope.thread_id) else { return };+ if scope.cancel_token.is_cancelled() {+ return;+ }+ let state = &scope.state;+ let Ok(Some(channel)) = state.db.get_channel(cid).await else { return };+ let recent = state.db.list_messages(cid, 100).await.unwrap_or_default();+ let Some((tail, since)) = since_last_user(&recent) else { return };+ if consolidated_in(tail).is_some() {+ return;+ }+ let delegations: Vec<_> = state+ .db+ .list_delegations(None, None, 100)+ .await+ .unwrap_or_default()+ .into_iter()+ .filter(|d| d.origin_channel_id.as_deref() == Some(cid.as_str()) && d.created_at >= since)+ .collect();+ // The chain is still going: the last one to end consolidates+ if delegations.iter().any(|d| d.is_open() && !super::delegation::is_parked(d)) {+ return;+ }+ let members = &scope.teammates;+ let by_ref = |r: &str| members.iter().find(|k| k.id == r || k.name == r).cloned();+ let names: Vec<&str> = members.iter().map(|k| k.name.as_str()).collect();++ let mut asks: Vec<Ask> = Vec::new();+ // Question cards in the channel+ for q in state.db.list_questions(Some("open"), Some(cid), None).await.unwrap_or_default() {+ if q.channel_id.as_deref() != Some(cid.as_str()) || q.created_at < since {+ continue;+ }+ if let Some(kwant) = by_ref(&q.kwant_id) {+ asks.push(Ask { kwant, question: q.question.clone(), question_id: Some(q.id.clone()), message_id: q.message_id.clone() });+ }+ }+ // Questions specialists asked in the threads of this chain's delegations+ for d in &delegations {+ for q in state.db.list_questions(Some("open"), Some(&d.thread_id), None).await.unwrap_or_default() {+ if q.kwant_id != d.specialist_kwant_id || q.created_at < since {+ continue;+ }+ if let Some(kwant) = by_ref(&q.kwant_id) {+ asks.push(Ask { kwant, question: q.question.clone(), question_id: Some(q.id.clone()), message_id: q.message_id.clone() });+ }+ }+ }+ // Plain replies whose last line asks the person+ for m in tail.iter().filter(|m| m.sender_role == "kwant") {+ let meta = meta_of(m);+ if meta["kind"] == "ask_user" || !crate::router::sticky::asks_the_person(&m.text) || hands_on(&m.text, &names) {+ continue;+ }+ let Some(kwant) = by_ref(&m.sender_id) else { continue };+ if asks.iter().any(|a| a.kwant.id == kwant.id) {+ continue;+ }+ let question = m.text.trim_end().lines().last().unwrap_or("").trim().to_string();+ asks.push(Ask { kwant, question, question_id: None, message_id: Some(m.id.clone()) });+ }+ let mut askers: Vec<&Kwant> = Vec::new();+ for a in &asks {+ if !askers.iter().any(|k| k.id == a.kwant.id) {+ askers.push(&a.kwant);+ }+ }+ if askers.len() < 2 {+ return;+ }+ // The lead, else whoever answered the person first+ let coordinator = members+ .iter()+ .find(|k| k.id == channel.lead_kwant_id)+ .cloned()+ .or_else(|| tail.iter().filter(|m| m.sender_role == "kwant").find_map(|m| by_ref(&m.sender_id)))+ .unwrap_or_else(|| askers[0].clone());++ let lines: Vec<String> = asks.iter().map(|a| format!("- {}: “{}”", a.kwant.name, clip(&a.question, 300))).collect();+ let prompt = format!(+ "[kwnt: since the person's last message, {n} teammates asked them something:\n{list}\n\n\+ Post ONE short message with everything the person needs to answer, as one numbered list (one line each; say \+ whose question it is and merge duplicates), so they can answer it all in one reply. Don't @mention anyone, \+ don't answer the questions yourself and do no other work. When the person answers, you get the answer and pass \+ each part on.]",+ n = askers.len(),+ list = lines.join("\n"),+ );+ tracing::info!(channel = %cid, coordinator = %coordinator.id, askers = askers.len(), "consolidating the person's open questions");+ // Saved times have whole seconds: the list is the coordinator's newest message not seen before+ let seen: std::collections::HashSet<&str> = recent.iter().map(|m| m.id.as_str()).collect();+ let mut opts = TurnOpts::default();+ opts.label = Some("One list of what the team needs from you".into());+ if try_kwant_turn(scope, &coordinator, prompt, opts).await.is_err() {+ return;+ }+ let after = state.db.list_messages(cid, 20).await.unwrap_or_default();+ let Some(list) = after+ .iter()+ .rev()+ .find(|m| m.sender_role == "kwant" && m.sender_id == coordinator.name && !seen.contains(m.id.as_str()))+ else {+ return;+ };+ let link = json!({+ "kwant_id": coordinator.id,+ "askers": askers.iter().map(|k| k.id.clone()).collect::<Vec<_>>(),+ "question_ids": asks.iter().filter_map(|a| a.question_id.clone()).collect::<Vec<_>>(),+ "message_ids": asks.iter().filter_map(|a| a.message_id.clone()).collect::<Vec<_>>(),+ });+ set_meta_key(state, list, META_KEY, link).await;+ for a in &asks {+ let Some(mid) = &a.message_id else { continue };+ if let Some(m) = after.iter().chain(recent.iter()).find(|m| &m.id == mid) {+ set_meta_key(state, m, INTO_KEY, json!(list.id)).await;+ } else if let Ok(Some(m)) = state.db.get_message(mid).await {+ set_meta_key(state, &m, INTO_KEY, json!(list.id)).await;+ }+ }+}++/// Adds `key` to a message's meta, keeping the rest, and tells the clients.+async fn set_meta_key(state: &AppState, m: &Message, key: &str, value: Value) {+ let mut meta = match meta_of(m) {+ Value::Object(o) => Value::Object(o),+ _ => json!({}),+ };+ meta[key] = value;+ if state.db.set_message_meta(&m.id, &meta).await.is_ok() {+ let mut updated = m.clone();+ updated.meta = Some(meta.to_string());+ let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&updated).unwrap_or(Value::Null) });+ }+}++/// The person answered a consolidated list (their message goes to its lead): the questions on+/// cards close with that answer, and a specialist that asked in a delegation's thread continues+/// there with it. Returns the note for the lead's turn: who already has the answer and whom it+/// should pass it on to.+pub(super) async fn deliver_answer(state: &AppState, link: &Value, answer: &str, members: &[Kwant]) -> String {+ let mut continued: Vec<String> = Vec::new();+ let mut answered_cards: Vec<String> = Vec::new();+ for qid in link["question_ids"].as_array().into_iter().flatten().filter_map(Value::as_str) {+ let Ok(Some(q)) = state.db.get_question(qid).await else { continue };+ if q.status != "open" {+ continue;+ }+ let name = members.iter().find(|k| k.id == q.kwant_id).map(|k| k.name.clone()).unwrap_or_default();+ if q.thread_id.is_some() {+ // Its specialist continues in the thread, and its new result comes back here+ if super::questions::answer_with(state, qid, answer).await.is_some() && !continued.contains(&name) {+ continued.push(name);+ }+ } else if super::questions::answer_by_message(state, qid, answer).await {+ // A turn still waiting on its card took the answer+ if !continued.contains(&name) {+ continued.push(name);+ }+ } else if !answered_cards.contains(&name) {+ answered_cards.push(name);+ }+ }+ let others: Vec<String> = link["askers"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .filter(|&id| Some(id) != link["kwant_id"].as_str())+ .filter_map(|id| members.iter().find(|k| k.id == id).map(|k| k.name.clone()))+ .filter(|n| !continued.contains(n))+ .collect();+ let mut note = String::from("\n\n[kwnt: this message answers the list of questions you posted for the team.");+ if !continued.is_empty() {+ note.push_str(&format!(" {} already got the answer directly and continue on their own; don't hand it to them again.", continued.join(", ")));+ }+ if !others.is_empty() {+ note.push_str(&format!(+ " Pass the part that answers each of these teammates on to them by @mention, with what they asked for: {}.",+ others.join(", ")+ ));+ }+ note.push(']');+ note+}++fn clip(text: &str, max: usize) -> String {+ let t = text.trim();+ if t.chars().count() <= max {+ return t.to_string();+ }+ let mut out: String = t.chars().take(max.saturating_sub(1)).collect();+ out.push('…');+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_question_to_a_teammate_is_not_for_the_person() {+ let names = ["Writer", "Analyst"];+ assert!(hands_on("Here's the draft.\n@Analyst, can you check the numbers?", &names));+ assert!(!hands_on("Here's the draft.\nWhich tone do you want?", &names));+ }+}diff --git a/src/server/delegation.rs b/src/server/delegation.rsindex b5d7446b..d6038a5b 100644--- a/src/server/delegation.rs+++ b/src/server/delegation.rs@@ -148,6 +148,9 @@ pub struct StartRequest {pub origin_depth: i64,/// Agents the lead may delegate to, when its chat has a member list.pub allowed: Option<Vec<String>>,+ /// Another open delegation of the same lead and chat whose result this task waits for: it is+ /// created parked and starts with that result once it completes (see [`release_dependents`]).+ pub after: Option<String>,}/// Checks a request, creates the thread and the delegation, and starts the specialist's turn@@ -258,6 +261,25 @@ pub async fn start(state: &AppState, req: StartRequest) -> Result<Delegation, (S.await.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "database error".into()))?;+ // Waits for a sibling of the same lead and chat that is still open; anything else is ignored+ let prereq = match &req.after {+ Some(id) => state+ .db+ .get_delegation(id)+ .await+ .ok()+ .flatten()+ .filter(|p| p.lead_kwant_id == d.lead_kwant_id && p.origin_context() == d.origin_context() && p.is_open()),+ None => None,+ };+ let d = match &prereq {+ Some(p) => {+ let _ = state.db.set_delegation_after(&d.id, &p.id).await;+ state.db.get_delegation(&d.id).await.ok().flatten().unwrap_or(d)+ }+ None => d,+ };+// The task opens the thread, from the lead, so the specialist's history shows who askedlet task_msg = NewMessage {channel_id: None,@@ -273,26 +295,157 @@ pub async fn start(state: &AppState, req: StartRequest) -> Result<Delegation, (S.db.insert_message_with(&task_msg, &MessageExtra { thread_id: Some(thread.id.clone()), meta: None }).await;- post_to_origin(- state,- &d,- "system",- "kwnt",- format!("{} asked {} to work on “{}”. It runs in its own thread; the result will be posted here.", req.lead.name, req.specialist.name, d.title),- meta("delegation_started", &d, &req.specialist.name),- )- .await;+ let started = match &prereq {+ Some(p) => format!(+ "{} asked {} to work on “{}” once {} has finished “{}”. It waits until then, runs in its own thread, and the result will be posted here.",+ req.lead.name,+ req.specialist.name,+ d.title,+ name_of(state, &p.specialist_kwant_id).await,+ p.title+ ),+ None => format!("{} asked {} to work on “{}”. It runs in its own thread; the result will be posted here.", req.lead.name, req.specialist.name, d.title),+ };+ let mut m = meta("delegation_started", &d, &req.specialist.name);+ if let Some(p) = &prereq {+ m["after_delegation_id"] = json!(p.id);+ }+ post_to_origin(state, &d, "system", "kwnt", started, m).await;emit_thread(state, &thread);emit_delegation(state, &d);- tracing::info!(delegation = %d.id, lead = %req.lead.id, specialist = %req.specialist.id, depth = d.depth, "delegation started");+ tracing::info!(delegation = %d.id, lead = %req.lead.id, specialist = %req.specialist.id, depth = d.depth, after = ?d.after_delegation_id, "delegation started");+ if let Some(p) = prereq {+ // It may have ended while this one was being set up+ if !state.db.get_delegation(&p.id).await.ok().flatten().is_some_and(|p| p.is_open()) {+ release_dependents(state, &p.id).await;+ }+ return Ok(state.db.get_delegation(&d.id).await.ok().flatten().unwrap_or(d));+ }- let job = state.turns.start_job([d.id.clone(), thread.id.clone()]);- let runner_state = state.clone();- let (lead, specialist, delegation) = (req.lead, req.specialist, d.clone());- tokio::spawn(async move { run(runner_state, job, delegation, lead, specialist, false, false).await });+ spawn_run(state, d.clone(), req.lead, req.specialist);Ok(d)}+/// Starts a delegation's run in the background. A plain function, so the futures of [`run`] and+/// [`release_dependents`] (which starts runs) don't contain each other.+fn spawn_run(state: &AppState, d: Delegation, lead: Kwant, specialist: Kwant) {+ let job = state.turns.start_job([d.id.clone(), d.thread_id.clone()]);+ let runner_state = state.clone();+ tokio::spawn(async move { run(runner_state, job, d, lead, specialist, false, false).await });+}++/// What a parked task gets of the result it waited for, at most.+const WAITED_RESULT_CHARS: usize = 4000;++/// The delegations parked until `prereq_id` ended (see [`StartRequest::after`]) go on, and so on+/// down the chain:+/// - it completed and asked the person nothing: each starts, with the result added to its task;+/// - it completed but waits for the person's answer: they stay parked, and the chat says so+/// (the answer continues it, and [`resume_after_answer`] calls this again);+/// - it failed, was stopped or cut short: they don't start and end as failed, saying why.+///+/// Returns how many started.+pub(super) async fn release_dependents(state: &AppState, prereq_id: &str) -> usize {+ let mut started = 0;+ let mut work = vec![prereq_id.to_string()];+ while let Some(id) = work.pop() {+ let Ok(Some(p)) = state.db.get_delegation(&id).await else { continue };+ if p.is_open() {+ continue;+ }+ let waiting = state.db.list_dependent_delegations(&p.id).await.unwrap_or_default();+ if waiting.is_empty() {+ continue;+ }+ let who = name_of(state, &p.specialist_kwant_id).await;+ let asked = open_question(state, &p).await;+ // A result whose last line asks the person: there is no card to answer, so nothing+ // would start the waiting task later; it ends as not started, saying why+ let result = if p.status == "completed" { result_of(state, &p).await } else { String::new() };+ let asked_in_reply = asked.is_none() && crate::router::sticky::asks_the_person(&result);+ for d in waiting {+ 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 {+ continue;+ };+ match (p.status.as_str(), &asked) {+ ("completed", None) if !asked_in_reply => {+ let result = clip(&result, WAITED_RESULT_CHARS);+ let task = clip(&format!("{}\n\n{who}'s result, which this task waited for:\n{result}", d.task), MAX_TASK_CHARS);+ if !state.db.unpark_delegation(&d.id, &task).await.unwrap_or(false) {+ continue;+ }+ let Ok(Some(d)) = state.db.get_delegation(&d.id).await else { continue };+ post_to_origin(+ state,+ &d,+ "system",+ "kwnt",+ format!("{who} has finished, so {} starts on “{}” now, with {who}'s result.", specialist.name, d.title),+ meta("delegation_started", &d, &specialist.name),+ )+ .await;+ emit_delegation(state, &d);+ tracing::info!(delegation = %d.id, after = %p.id, "parked delegation started");+ spawn_run(state, d, lead, specialist);+ started += 1;+ }+ ("completed", Some(q)) => {+ let mut m = meta("delegation_waiting", &d, &specialist.name);+ m["after_delegation_id"] = json!(p.id);+ post_to_origin(+ state,+ &d,+ "system",+ "kwnt",+ format!(+ "{} hasn't started “{}”: it waits for {who}'s result, and {who} asked you “{}” first. Once you answer, {who} continues and {} starts.",+ specialist.name,+ d.title,+ clip(&q.question, 200),+ specialist.name+ ),+ m,+ )+ .await;+ }+ (status, _) => {+ let why = if asked_in_reply {+ format!("not started: it waits for {who}'s result, and {who} asked you something first. Answer {who}, then ask for it again")+ } else {+ format!("not started: it waited for {who}'s result, and {who}'s task was {status}")+ };+ if !state.db.finish_delegation(&d.id, "failed", Some(&why), None).await.unwrap_or(false) {+ continue;+ }+ let Ok(Some(done)) = state.db.get_delegation(&d.id).await else { continue };+ if let Some(mid) = post_to_origin(+ state,+ &done,+ "system",+ "kwnt",+ format!("{} didn't start “{}”: {}.", specialist.name, done.title, why.trim_start_matches("not started: ")),+ meta("delegation_result", &done, &specialist.name),+ )+ .await+ {+ let _ = state.db.set_delegation_result_message(&done.id, &mid).await;+ }+ emit_delegation(state, &done);+ work.push(done.id);+ }+ }+ }+ }+ started+}++/// Whether `d` is parked behind another delegation and hasn't started.+pub(super) fn is_parked(d: &Delegation) -> bool {+ d.status == "queued" && d.after_delegation_id.is_some()+}+/// The background part: the specialist's turn in the thread, then the report in the origin chat./// `retried`: the run after a usage limit reset, which never waits for one again./// The task's prompt says so when a restart cut an earlier run short (`after_restart`): that run@@ -494,6 +647,7 @@ async fn finish(state: &AppState, d: &Delegation, specialist: &Kwant, outcome: R},).await;+ release_dependents(state, &done.id).await;report_to_lead(state, &done, None).await;}@@ -562,6 +716,10 @@ pub async fn resume_after_answer(state: &AppState, d: Delegation, question_id: &let _ = state.db.set_delegation_result_message(&d.id, &id).await;}tracing::info!(delegation = %d.id, "delegation continued after a late answer");+ // A teammate waited for this result: it starts now, and the lead hears from both when it ends+ if release_dependents(&state, &d.id).await > 0 {+ return;+ }if d.continue_lead {let opening = format!("{} got the person's answer to its question and continued the task you delegated (“{}”).",@@ -591,7 +749,9 @@ async fn finished_batch(state: &AppState, d: &Delegation) -> Option<Vec<Delegati.await.ok()?.into_iter()- .filter(|s| s.continue_lead && s.origin_context() == d.origin_context())+ // A task parked behind one that waits for the person isn't running: the lead reports+ // the rest now, and that task comes back with its own batch once it ran+ .filter(|s| s.continue_lead && s.origin_context() == d.origin_context() && !is_parked(s)).collect();if siblings.iter().any(Delegation::is_open) {return None;@@ -680,6 +840,14 @@ async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation], oresults.push_str(next);results.push('\n');}+ for parked in state.db.list_dependent_delegations(&b.id).await.unwrap_or_default() {+ results.push_str(&format!(+ "(Not started yet: {} waits for {who}'s result on “{}”. It starts by itself once {who} has the person's answer; \+ don't hand it on again.)\n",+ name_of(state, &parked.specialist_kwant_id).await,+ parked.title+ ));+ }results.push('\n');}let opening = match (opening, batch) {@@ -720,6 +888,8 @@ async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation], o.map(|m| m.text).unwrap_or_else(|| d.task.clone());super::routes::run_handoffs_boxed(&scope, &spoken, &[(lead.clone(), reply)], &user_prompt).await;+ // The chain may be over now: several open questions for the person become one list+ super::asks::consolidate(&scope).await;}}@@ -772,6 +942,7 @@ 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);+ release_dependents(state, &done.id).await;// A stopped task alone doesn't wake the lead, but other results of its batch must not be lostspawn_report_to_lead(state, done.clone());Some(done)@@ -836,8 +1007,17 @@ pub async fn interrupt_open(state: &AppState) {meta("delegation_result", &done, &specialist),).await;+ release_dependents(state, &done.id).await;spawn_report_to_lead(state, done);}+ // Tasks parked behind one that ended while kwnt was down go on (or give up) now+ for parked in state.db.list_parked_delegations().await.unwrap_or_default() {+ if let Some(after) = &parked.after_delegation_id {+ if !state.db.get_delegation(after).await.ok().flatten().is_some_and(|p| p.is_open()) {+ release_dependents(state, after).await;+ }+ }+ }for d in again {let Ok(Some(d)) = state.db.get_delegation(&d.id).await else {continue;@@ -1061,6 +1241,7 @@ pub async fn create_delegation(State(state): State<AppState>, Json(p): Json<Delecontinue_lead: p.continue_lead.unwrap_or(true),origin_depth,allowed: None,+ after: None,};match start(&state, req).await {Ok(d) => (StatusCode::ACCEPTED, Json(d)).into_response(),@@ -1138,6 +1319,7 @@ pub async fn tool_delegate(state: &AppState, scope: &super::continuity::SelfScopcontinue_lead: true,origin_depth: origin.depth,allowed: (!origin.member_ids.is_empty()).then(|| origin.member_ids.clone()),+ after: None,};match start(state, req).await {Ok(d) => (diff --git a/src/server/mod.rs b/src/server/mod.rsindex 526f2dce..9c2d1e02 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -23,6 +23,7 @@ pub mod activity;pub mod human_steps;pub mod skills;pub mod spaces;+pub mod asks;pub mod away;pub mod computer;pub mod mcp_suggest;diff --git a/src/server/questions.rs b/src/server/questions.rsindex dcd5967c..d81499c4 100644--- a/src/server/questions.rs+++ b/src/server/questions.rs@@ -347,18 +347,27 @@ pub async fn answer(State(state): State<AppState>, Path(id): Path<String>, Json(if q.status != "open" {return error(StatusCode::CONFLICT, format!("the question is already {}", q.status));}- let Some(q) = close(&state, &id, "answered", Some(&text)).await else {+ let Some((q, live)) = answer_with(&state, &id, &text).await else {return error(StatusCode::CONFLICT, "the question was just closed");};- save_message(&state, &q, "user", "user", text.clone(), json!({"kind": "question_answer", "question_id": q.id})).await;+ Json(json!({"question": q, "resumed": if live { "turn" } else { "new_turn" }})).into_response()+}++/// Answers an open question as if on its card: it closes, the answer is saved where it was+/// asked, and the turn waiting on it gets it (`true`), or a new turn continues with it (`false`;+/// in a delegation's thread that goes back to the lead). `None` when it wasn't open any more.+pub async fn answer_with(state: &AppState, id: &str, text: &str) -> Option<(Question, bool)> {+ let text: String = text.trim().chars().take(MAX_ANSWER_CHARS).collect();+ let q = close(state, id, "answered", Some(&text)).await?;+ save_message(state, &q, "user", "user", text.clone(), json!({"kind": "question_answer", "question_id": q.id})).await;let live = match state.questions.take(&q.id) {Some(tx) => tx.send(Reply::Answer(text.clone())).is_ok(),None => false,};if !live {- resume(&state, &q, &text).await;+ resume(state, &q, &text).await;}- Json(json!({"question": q, "resumed": if live { "turn" } else { "new_turn" }})).into_response()+ Some((q, live))}/// The person answered an open question by typing in the chat instead of on its card (theirdiff --git a/src/server/routes.rs b/src/server/routes.rsindex 6da65a67..b436d9e6 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -832,6 +832,8 @@ fn execute_single_turn(let opts = TurnOpts { routing, ..TurnOpts::default() };if let Some(reply) = run_kwant_turn(&scope, &target_kwant, turn_prompt, opts).await {run_handoffs(&scope, std::slice::from_ref(&target_kwant.id), &[(target_kwant.clone(), reply)], &prompt).await;+ // Several bots asked the person something: one list of it all (when the chain is over)+ super::asks::consolidate(&scope).await;}});}@@ -926,22 +928,24 @@ async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(if scope.teammates.is_empty() {return;}+ // (teammate, asked by, asker's text, the teammate whose result it waits for)+ type Queued = (Kwant, String, String, Option<String>);let mut spoken: Vec<String> = already_spoken.to_vec();- let mut queue: std::collections::VecDeque<(Kwant, String, String)> = std::collections::VecDeque::new();+ let mut queue: std::collections::VecDeque<Queued> = std::collections::VecDeque::new();let mut skipped: Vec<(String, String)> = Vec::new();- let mut enqueue = |queue: &mut std::collections::VecDeque<(Kwant, String, String)>,- spoken: &[String],- from: &Kwant,- text: &str| {+ let mut enqueue = |queue: &mut std::collections::VecDeque<Queued>, spoken: &[String], from: &Kwant, text: &str| {let names: Vec<&str> = scope.teammates.iter().map(|k| k.name.as_str()).collect();let found = crate::router::handoff_mentions(text, &names);+ let deps = crate::router::handoff_dependencies(text, &names);skipped.extend(found.unknown.into_iter().map(|n| (n, String::new())));skipped.extend(found.in_code_block.iter().map(|&i| (scope.teammates[i].name.clone(), IN_CODE_BLOCK.to_string())));- for i in found.targets {+ for &i in &found.targets {let k = &scope.teammates[i];// Someone who already spoke isn't handed the turn back: no ping-pong- if k.id != from.id && !spoken.contains(&k.id) && !queue.iter().any(|(q, _, _)| q.id == k.id) {- queue.push_back((k.clone(), from.name.clone(), text.to_string()));+ if k.id != from.id && !spoken.contains(&k.id) && !queue.iter().any(|(q, _, _, _)| q.id == k.id) {+ // "@Writer, once @Analyst has the numbers…": the Writer goes after the Analyst+ let after = deps.iter().find(|&&(d, _)| d == i).map(|&(_, p)| scope.teammates[p].id.clone());+ queue.push_back((k.clone(), from.name.clone(), text.to_string(), after));}}};@@ -955,28 +959,60 @@ async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(let events = scope.state.event_sender.clone();let context_id = scope.context_id(&replies[0].0);+ let since = last_user_message_at(scope, &context_id).await;+ // How each bot's turn in this chain went, for the teammates that wait on it+ let mut outcomes: std::collections::HashMap<String, ChainOutcome> = std::collections::HashMap::new();+ for (k, text) in replies {+ outcomes.insert(k.id.clone(), chain_outcome(scope, &context_id, k, Some(text), since).await);+ }+ order_dependents(&mut queue);let total = |queue_len: usize, done: usize| (1 + done + queue_len).min(1 + MAX_HANDOFFS);+ let names_of = |id: &str| scope.teammates.iter().find(|k| k.id == id).map(|k| k.name.clone()).unwrap_or_default();let _ = events.send(RuntimeEvent::DiscussionStarted {team_id: context_id.clone(),team_name: scope.team_keys.as_ref().map(|(_, n)| n.clone()).unwrap_or_default(),total_turns: total(queue.len(), 0),- speakers: queue.iter().map(|(k, _, _)| k.id.clone()).collect(),- plan: queue.iter().map(|(k, from, _)| format!("{}: asked by {}", k.name, from)).collect(),+ speakers: queue.iter().map(|(k, _, _, _)| k.id.clone()).collect(),+ plan: queue+ .iter()+ .map(|(k, from, _, after)| match after {+ Some(p) => format!("{}: asked by {}, after {}", k.name, from, names_of(p)),+ None => format!("{}: asked by {}", k.name, from),+ })+ .collect(),kind: "handoff".into(),});+ // Teammates that waited for one who asked the person or failed+ let mut not_started: Vec<(String, String)> = Vec::new();let mut done = 0;- while let Some((kwant, from, from_text)) = queue.pop_front() {+ while let Some((kwant, from, from_text, after)) = queue.pop_front() {if done >= MAX_HANDOFFS || scope.cancel_token.is_cancelled() {+ queue.push_front((kwant, from, from_text, after));break;}- let prompt = format!(+ let waited_for = match after.as_ref().map(|p| (names_of(p), outcomes.get(p))) {+ // Waits for a teammate whose turn hasn't run: it was never handed one, so don't wait+ Some((_, None)) | None => None,+ Some((name, Some(ChainOutcome::Done(result)))) => Some((name, result.clone())),+ Some((name, Some(outcome))) => {+ not_started.push((kwant.name.clone(), outcome.not_started(&name)));+ continue;+ }+ };+ let mut prompt = format!("{from} handed this conversation to you by mentioning you.\n\nThe user's original request:\n{user}\n\n{text}\n\n\Reply to the user now with your own part of this, in character. Don't repeat what {from} already said.",from = from,user = user_prompt,text = crate::drivers::peer_message(&from, truncate_chars(&from_text, 4000)),);+ if let Some((name, result)) = &waited_for {+ prompt.push_str(&format!(+ "\n\n{from} asked you to wait for {name}'s result. {name} has finished:\n{}",+ crate::drivers::peer_message(name, truncate_chars(result, 4000)),+ ));+ }let _ = events.send(RuntimeEvent::DiscussionTurnStarted {speaker_id: kwant.id.clone(),speaker_name: kwant.name.clone(),@@ -989,20 +1025,92 @@ async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(done += 1;spoken.push(kwant.id.clone());match run_kwant_turn(scope, &kwant, prompt, TurnOpts::default()).await {- Some(reply) => enqueue(&mut queue, &spoken, &kwant, &reply),+ Some(reply) => {+ outcomes.insert(kwant.id.clone(), chain_outcome(scope, &context_id, &kwant, Some(&reply), since).await);+ enqueue(&mut queue, &spoken, &kwant, &reply);+ order_dependents(&mut queue);+ }None if scope.cancel_token.is_cancelled() => break,- None => {}+ None => {+ outcomes.insert(kwant.id.clone(), ChainOutcome::Failed);+ }}}drop(enqueue);+ skipped.extend(not_started);if !scope.cancel_token.is_cancelled() {- skipped.extend(queue.into_iter().map(|(k, _, _)| (k.name, format!("only {MAX_HANDOFFS} teammates take a turn per message"))));+ skipped.extend(queue.into_iter().map(|(k, _, _, _)| (k.name, format!("only {MAX_HANDOFFS} teammates take a turn per message"))));}let _ = events.send(RuntimeEvent::DiscussionCompleted { total_turns: done + 1, context_id: Some(context_id.clone()) });report_skipped(scope, skipped).await;}+/// How one bot's turn in a handoff chain ended, for a teammate that waits on its result.+#[derive(Debug, Clone, PartialEq)]+pub(super) enum ChainOutcome {+ /// Finished, with this reply.+ Done(String),+ /// Ended asking the person something (a question card, or a reply whose last line asks).+ Asked,+ /// Failed or was stopped.+ Failed,+}++impl ChainOutcome {+ /// Why a teammate waiting on `name` doesn't start.+ pub(super) fn not_started(&self, name: &str) -> String {+ match self {+ ChainOutcome::Asked => format!("waiting for {name}, who asked you something first. Answer {name} and the chain goes on"),+ _ => format!("waiting for {name}'s result, and {name} didn't finish"),+ }+ }+}++/// Whether `kwant`'s turn ended with `reply` asking the person: an open question card it raised in+/// this chat since `since`, or a last line that asks ([`crate::router::sticky::asks_the_person`]).+async fn chain_outcome(+ scope: &TurnScope,+ context_id: &str,+ kwant: &Kwant,+ reply: Option<&str>,+ since: Option<chrono::DateTime<chrono::Utc>>,+) -> ChainOutcome {+ let Some(reply) = reply else { return ChainOutcome::Failed };+ let open = scope.state.db.list_questions(Some("open"), Some(context_id), None).await.unwrap_or_default();+ let carded = open.iter().any(|q| q.kwant_id == kwant.id && since.is_none_or(|t| q.created_at >= t));+ if carded || crate::router::sticky::asks_the_person(reply) {+ ChainOutcome::Asked+ } else {+ ChainOutcome::Done(reply.to_string())+ }+}++/// When the person last wrote in this chat.+pub(super) async fn last_user_message_at(scope: &TurnScope, context_id: &str) -> Option<chrono::DateTime<chrono::Utc>> {+ let messages = scope.state.db.list_messages(context_id, 100).await.unwrap_or_default();+ messages.iter().rev().find(|m| m.sender_role == "user").and_then(|m| m.created_at)+}++/// Moves every queued teammate that waits for another queued one behind it; the rest keep+/// their order. Dependencies have no cycles ([`crate::router::handoff_dependencies`]).+fn order_dependents<T>(queue: &mut std::collections::VecDeque<(Kwant, String, String, Option<T>)>)+where+ T: AsRef<str>,+{+ for _ in 0..queue.len() {+ let misplaced = queue.iter().enumerate().find_map(|(i, (_, _, _, after))| {+ let p = after.as_ref()?;+ let at = queue.iter().position(|(k, _, _, _)| k.id == p.as_ref())?;+ (at > i).then_some((i, at))+ });+ let Some((i, at)) = misplaced else { return };+ if let Some(item) = queue.remove(i) {+ queue.insert(at, item);+ }+ }+}+const IN_CODE_BLOCK: &str = "the mention was inside code. Write the name as plain text to ask them";/// A follow-up that only credited a teammate who just reported ("As @SEO found, …").const CREDIT_ONLY: &str = "the mention only credited their result. To hand them more work, @mention them with the task";@@ -1082,6 +1190,11 @@ async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_prolet Some(cid) = scope.channel_id.clone() else { return };let names: Vec<&str> = scope.teammates.iter().map(|k| k.name.as_str()).collect();let found = crate::router::handoff_mentions(text, &names);+ // "@Writer, once @Analyst has the numbers…": the Writer's task waits for the Analyst's result+ let after_of: std::collections::HashMap<String, String> = crate::router::handoff_dependencies(text, &names)+ .into_iter()+ .map(|(d, p)| (scope.teammates[d].id.clone(), scope.teammates[p].id.clone()))+ .collect();let mut skipped: Vec<(String, String)> = found.unknown.into_iter().map(|n| (n, String::new())).collect();skipped.extend(found.in_code_block.iter().map(|&i| (scope.teammates[i].name.clone(), IN_CODE_BLOCK.to_string())));if found.targets.iter().all(|&i| scope.teammates[i].id == lead.id) {@@ -1105,7 +1218,7 @@ async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_prolet asked = |id: &str| this_request.iter().filter(|d| d.specialist_kwant_id == id).count();let mut targets: Vec<&Kwant> = Vec::new();- for i in found.targets {+ for &i in &found.targets {let k = &scope.teammates[i];if k.id == lead.id || targets.iter().any(|t| t.id == k.id) {continue;@@ -1123,6 +1236,17 @@ async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_protargets.push(k);}}+ // Teammates waited for start first, so their delegation exists when the waiting one is created+ for _ in 0..targets.len() {+ let misplaced = targets.iter().enumerate().find_map(|(i, k)| {+ let at = targets.iter().position(|t| Some(&t.id) == after_of.get(&k.id))?;+ (at > i).then_some((i, at))+ });+ let Some((i, at)) = misplaced else { break };+ let k = targets.remove(i);+ targets.insert(at, k);+ }+ let mut started: std::collections::HashMap<String, String> = std::collections::HashMap::new();let user = truncate_chars(user_prompt.trim(), 3000);let task = format!("The user asked in the team channel:\n{user}\n\n{lead} mentioned you:\n{text}",@@ -1143,6 +1267,22 @@ async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_pro));continue;}+ // Waits for a teammate started here, or for one still on an earlier task from this chat+ let after = match after_of.get(&specialist.id) {+ Some(p) => {+ let earlier = || mine.iter().find(|d| d.is_open() && &d.specialist_kwant_id == p).map(|d| d.id.clone());+ match started.get(p).cloned().or_else(earlier) {+ Some(id) => Some(id),+ None if targets_mentioned(&found.targets, scope, p) => {+ let name = scope.teammates.iter().find(|k| &k.id == p).map(|k| k.name.clone()).unwrap_or_default();+ skipped.push((specialist.name.clone(), format!("it was to wait for {name}'s result, and {name} wasn't sent the task")));+ continue;+ }+ None => None,+ }+ }+ None => None,+ };let req = super::delegation::StartRequest {lead: lead.clone(),specialist: specialist.clone(),@@ -1152,15 +1292,24 @@ async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_procontinue_lead: true,origin_depth: scope.delegation_depth,allowed: Some(allowed.clone()),+ after,};match super::delegation::start(&scope.state, req).await {- Ok(_) => room -= 1,+ Ok(d) => {+ started.insert(specialist.id.clone(), d.id);+ room -= 1;+ }Err((_, why)) => skipped.push((specialist.name.clone(), why.trim_end_matches('.').to_string())),}}report_skipped(scope, skipped).await;}+/// Whether the teammate with `id` is among the @mentioned `targets` (indices into the teammates).+fn targets_mentioned(targets: &[usize], scope: &TurnScope, id: &str) -> bool {+ targets.iter().any(|&i| scope.teammates[i].id == id)+}+/// Runs a moderated team discussion: the lead opens (or pauses to ask the user), teammates react to/// each other briefly or pass, @mentioned teammates join in, and the lead closes with one summary.async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, user_prompt: &str) {@@ -2347,6 +2496,8 @@ async fn send_chat_inner(// A reply with no @mention to a bot that just asked the person something goes back to that botlet mut awaiting: Option<(Kwant, Option<String>)> = None;+ // Set when that is the lead of a gathered list of questions (see `super::asks`)+ let mut gathered: Option<serde_json::Value> = None;let mut last_speaker: Option<String> = None;// The channel route worked out while deciding that, reused below instead of asking Laya twicelet mut pre_route: Option<crate::router::team::ChannelRoute> = None;@@ -2377,6 +2528,13 @@ async fn send_chat_inner(}}if sticks {+ // The answer to a list that gathered several bots' questions: its lead passes it on+ if a.question_id.is_none() {+ let tail_from = recent.iter().rposition(|m| m.sender_role == "user").map_or(0, |i| i + 1);+ gathered = super::asks::consolidated_in(&recent[tail_from..])+ .filter(|(_, link)| link["kwant_id"].as_str() == Some(a.kwant.id.as_str()))+ .map(|(_, link)| link);+ }awaiting = Some((a.kwant.clone(), a.question_id));}}@@ -2511,6 +2669,13 @@ async fn send_chat_inner(.await;payload.prompt.push_str(¬e);+ // The person answered the lead's list: the cards close, specialists waiting in threads go+ // on, and the lead is told whom to pass the rest to+ if let Some(link) = &gathered {+ let note = super::asks::deliver_answer(&state, link, &payload.prompt, &all_kwants).await;+ payload.prompt.push_str(¬e);+ }+// Typed instead of tapped: the answer closes the bot's open question, and a turn still waiting// on it carries on with it (no second turn)if let Some((asker, Some(qid))) = &awaiting {diff --git a/tests/chain_order_test.rs b/tests/chain_order_test.rsnew file mode 100644index 00000000..192b3bdd--- /dev/null+++ b/tests/chain_order_test.rs@@ -0,0 +1,387 @@+//! One reply that hands on to several bots (F4) and a chain where several bots ask the person+//! something (F5). A fake claude CLI on PATH answers as the bot named in its system prompt+//! ("You are <name>, …"), from files under `$KWNT_TEST_BEHAVE`: `<name>` for a turn, `<name>.list`+//! for the turn that gathers the person's questions and `<name>.resume` for a lead resumed with+//! results. A first line "FAIL" fails the turn and "WAIT:<file>" holds it until that file exists.+//! Every prompt is saved as `$KWNT_TEST_PROMPTS/<name>-<ns>`. Its own test binary: it changes PATH.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{models::Message, Database},+ router::LayaRouter,+ server::{create_router, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::path::PathBuf;+use std::sync::OnceLock;+use std::time::Duration;+use tower::ServiceExt;++const FAKE_CLAUDE: &str = r#"#!/bin/sh+case "$1" in+ auth) echo '{"loggedIn":true}'; exit 0 ;;+esac+for a; do last="$a"; done+me=$(printf '%s\n' "$@" | sed -n 's/.*You are \([A-Za-z0-9]*\), .*/\1/p' | head -n 1)+printf '%s' "$last" > "$KWNT_TEST_PROMPTS/$me-$(date +%s%N)"+file="$KWNT_TEST_BEHAVE/$me"+case "$last" in+ *"as one numbered list"*) [ -f "$file.list" ] && file="$file.list" ;;+ *"finished the task you delegated"*|*"tasks you delegated have ended"*) [ -f "$file.resume" ] && file="$file.resume" ;;+esac+if [ ! -f "$file" ]; then+ echo '{"type":"result","is_error":false,"num_turns":1,"result":"Done."}'+ exit 0+fi+first=$(head -n 1 "$file")+case "$first" in+ FAIL) echo "boom" >&2; exit 1 ;;+ WAIT:*)+ release="${first#WAIT:}"+ i=0+ while [ ! -f "$release" ] && [ $i -lt 600 ]; do sleep 0.1; i=$((i+1)); done+ out=$(tail -n +2 "$file" | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/\\n/g') ;;+ *) out=$(sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/\\n/g' "$file") ;;+esac+printf '{"type":"result","is_error":false,"num_turns":1,"result":"%s"}\n' "$out"+"#;++struct Dirs {+ prompts: PathBuf,+ behave: PathBuf,+ root: PathBuf,+}++fn dirs() -> &'static Dirs {+ static DIRS: OnceLock<Dirs> = OnceLock::new();+ DIRS.get_or_init(|| {+ let root = tempfile::tempdir().unwrap().keep();+ let (bin, prompts, behave) = (root.join("bin"), root.join("prompts"), root.join("behave"));+ for d in [&bin, &prompts, &behave] {+ std::fs::create_dir_all(d).unwrap();+ }+ let fake = bin.join("claude");+ std::fs::write(&fake, FAKE_CLAUDE).unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ std::env::set_var("KWNT_TEST_PROMPTS", &prompts);+ std::env::set_var("KWNT_TEST_BEHAVE", &behave);+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));+ Dirs { prompts, behave, root }+ })+}++/// What bot `name` replies (see the module doc); names are unique per test.+fn behave(name: &str, reply: &str) {+ std::fs::write(dirs().behave.join(name), reply).unwrap();+}++/// A file a "WAIT:" turn waits for.+fn release_file(name: &str) -> PathBuf {+ dirs().root.join(name)+}++/// Prompts bot `name` got, oldest first.+fn prompts_of(name: &str) -> Vec<String> {+ let mut found: Vec<(u128, String)> = std::fs::read_dir(&dirs().prompts)+ .unwrap()+ .filter_map(|e| {+ let e = e.ok()?;+ let file = e.file_name().into_string().ok()?;+ let ns = file.strip_prefix(&format!("{name}-"))?.parse().ok()?;+ Some((ns, std::fs::read_to_string(e.path()).ok()?))+ })+ .collect();+ found.sort();+ found.into_iter().map(|(_, p)| p).collect()+}++/// When bot `name` got its first prompt (ns).+fn first_prompt_at(name: &str) -> Option<u128> {+ std::fs::read_dir(&dirs().prompts)+ .unwrap()+ .filter_map(|e| e.ok()?.file_name().into_string().ok()?.strip_prefix(&format!("{name}-"))?.parse().ok())+ .min()+}++async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {+ let resp = app+ .clone()+ .oneshot(+ Request::builder()+ .method(method)+ .uri(uri)+ .header("content-type", "application/json")+ .body(body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty))+ .unwrap(),+ )+ .await+ .unwrap();+ let s = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (s, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++struct Env {+ app: Router,+ state: AppState,+ _tmp: tempfile::TempDir,+}++async fn setup() -> Env {+ dirs();+ let tmp = tempfile::tempdir().unwrap();+ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ // Laya is unreachable: turns use the kwant's preferred model, the fake claude+ let config = Config {+ data_dir: data.clone(),+ laya_url: "http://127.0.0.1:9".into(),+ browser_cdp_url: Some("http://127.0.0.1:9".into()),+ ..Config::default()+ };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(data.join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ Env { app: create_router(state.clone()), state, _tmp: tmp }+}++async fn add_bot(env: &Env, name: &str) -> String {+ let (s, v) = call(&env.app, "POST", "/api/kwants", Some(json!({"name": name, "title": "Specialist", "persona_prompt": "", "soul": "", "avatar_sprite": "default", "driver_type": "cli", "preferred_model": "claude"}))).await;+ assert!(s.is_success(), "{s} {v}");+ v["id"].as_str().or(v["kwant"]["id"].as_str()).unwrap().to_string()+}++/// A team led by the first of `names` with all of them in it; returns the channel and the bot ids.+async fn team(env: &Env, team: &str, names: &[&str]) -> (String, Vec<String>) {+ let mut ids = Vec::new();+ for n in names {+ ids.push(add_bot(env, n).await);+ }+ let (s, v) = call(&env.app, "POST", "/api/teams", Some(json!({"name": team, "lead_kwant_id": ids[0], "member_kwants": ids}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let (_, channels) = call(&env.app, "GET", "/api/channels", None).await;+ let channel = channels.as_array().unwrap().iter().find(|c| c["name"] == format!("team-{team}").as_str()).unwrap()["id"].as_str().unwrap().to_string();+ (channel, ids)+}++async fn say_in(env: &Env, channel: &str, prompt: &str) {+ let (s, v) = call(&env.app, "POST", "/api/chat/send", Some(json!({"channel_id": channel, "prompt": prompt, "sender_id": "user"}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+}++async fn messages(env: &Env, channel: &str) -> Vec<Message> {+ env.state.db.list_messages(channel, 200).await.unwrap()+}++fn meta(m: &Message) -> Value {+ m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null)+}++async fn wait_for<F, Fut>(what: &str, mut check: F)+where+ F: FnMut() -> Fut,+ Fut: std::future::Future<Output = bool>,+{+ for _ in 0..300 {+ if check().await {+ return;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ panic!("timed out waiting for {what}");+}++/// Waits until nothing runs in this test's chats any more.+async fn settle(env: &Env) {+ let mut quiet = 0;+ for _ in 0..400 {+ quiet = if env.state.turns.active_turns().is_empty() { quiet + 1 } else { 0 };+ if quiet >= 20 {+ return;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ panic!("the chain never went quiet");+}++async fn delegation_to(env: &Env, lead: &str, to: &str) -> Option<kwnt::db::threads::Delegation> {+ env.state.db.list_delegations(Some(lead), None, 20).await.unwrap().into_iter().find(|d| d.specialist_kwant_id == to)+}++// --- F4: handoffs (a teammate who isn't the lead hands on) ---++#[tokio::test]+async fn a_handoff_that_waits_for_another_gets_its_result() {+ let env = setup().await;+ let (channel, _) = team(&env, "f4-hand", &["Ld1", "Hub1", "Wr1", "An1"]).await;+ behave("Hub1", "Splitting it up. @Wr1, once @An1 has the numbers, write the summary. @An1 please crunch the numbers.");+ behave("An1", "Revenue is 42k ANRESULT1.");+ behave("Wr1", "Summary written.");+ say_in(&env, &channel, "@Hub1 plan the report").await;+ wait_for("Wr1's turn", || async { !prompts_of("Wr1").is_empty() }).await;+ settle(&env).await;++ assert!(first_prompt_at("An1") < first_prompt_at("Wr1"), "An1, mentioned second, runs first");+ let p = &prompts_of("Wr1")[0];+ assert!(p.contains("asked you to wait for An1's result") && p.contains("ANRESULT1"), "Wr1 gets An1's result: {p}");+ assert_eq!(prompts_of("An1").len(), 1);+}++#[tokio::test]+async fn a_handoff_waiting_for_a_failed_or_asking_teammate_does_not_start() {+ let env = setup().await;+ let (channel, _) = team(&env, "f4-fail", &["Ld2", "Hub2", "Wr2", "An2", "Sc2"]).await;+ behave("Hub2", "Splitting it up. @Wr2, once @An2 has the numbers, write the summary. @An2 please crunch the numbers. @Sc2 please scan the market.");+ behave("An2", "FAIL");+ behave("Sc2", "Market scanned.");+ say_in(&env, &channel, "@Hub2 plan the report").await;+ wait_for("Sc2's turn", || async { !prompts_of("Sc2").is_empty() }).await;+ settle(&env).await;+ assert!(prompts_of("Wr2").is_empty(), "Wr2 waited for An2, which failed");+ let msgs = messages(&env, &channel).await;+ assert!(msgs.iter().any(|m| m.text.contains("Wr2") && m.text.contains("An2")), "the chain says Wr2 didn't start: {:?}", msgs.iter().map(|m| &m.text).collect::<Vec<_>>());++ // A prerequisite that asks the person something holds its dependent too+ let (channel, _) = team(&env, "f4-ask", &["Ld7", "Hub7", "Wr7", "An7"]).await;+ behave("Hub7", "Splitting it up. @Wr7, once @An7 has the numbers, write the summary. @An7 please crunch the numbers.");+ behave("An7", "I can pull them.\nWhich quarter should I use?");+ say_in(&env, &channel, "@Hub7 plan the report").await;+ wait_for("An7's turn", || async { !prompts_of("An7").is_empty() }).await;+ settle(&env).await;+ assert!(prompts_of("Wr7").is_empty(), "Wr7 waits for the person's answer to An7");+}++// --- F4: a lead's delegations ---++#[tokio::test]+async fn a_leads_dependent_delegation_waits_while_independent_ones_run_in_parallel() {+ let env = setup().await;+ let (channel, ids) = team(&env, "f4-lead", &["Ld3", "Wr3", "An3", "Sc3"]).await;+ let (lead, wr, an, sc) = (&ids[0], &ids[1], &ids[2], &ids[3]);+ let release = release_file("an3-release");+ behave("Ld3", "On it. @Wr3, once @An3 has the numbers, write the summary. @An3 please crunch the numbers. @Sc3 please scan the market.");+ behave("Ld3.resume", "All three parts are in.");+ behave("An3", &format!("WAIT:{}\nRevenue is 42k ANRESULT3.", release.display()));+ behave("Sc3", "Market scanned.");+ behave("Wr3", "Summary written WRRESULT3.");+ say_in(&env, &channel, "@Ld3 get me the report").await;++ // Sc3 finishes while An3 still works: independent mentions run at once+ wait_for("Sc3's result", || async { delegation_to(&env, lead, sc).await.is_some_and(|d| d.status == "completed") }).await;+ let a = delegation_to(&env, lead, an).await.unwrap();+ assert!(a.is_open(), "An3 still works: {a:?}");+ let w = delegation_to(&env, lead, wr).await.expect("Wr3's task exists");+ assert_eq!(w.status, "queued");+ assert_eq!(w.after_delegation_id.as_deref(), Some(a.id.as_str()));+ assert!(prompts_of("Wr3").is_empty(), "Wr3 hasn't started");+ assert!(prompts_of("Ld3").iter().all(|p| !p.contains("tasks you delegated have ended")), "the lead isn't resumed while Wr3 waits");++ std::fs::write(&release, "").unwrap();+ wait_for("Wr3's result", || async { delegation_to(&env, lead, wr).await.is_some_and(|d| d.status == "completed") }).await;+ let p = &prompts_of("Wr3")[0];+ assert!(p.contains("ANRESULT3"), "Wr3 gets An3's result: {p}");+ wait_for("the lead's resume", || async { prompts_of("Ld3").iter().any(|p| p.contains("WRRESULT3")) }).await;+ settle(&env).await;+ let resumes: Vec<_> = prompts_of("Ld3").into_iter().filter(|p| p.contains("WRRESULT3")).collect();+ assert_eq!(resumes.len(), 1, "one resume with every result");+ assert!(resumes[0].contains("ANRESULT3"), "{}", resumes[0]);+}++#[tokio::test]+async fn a_leads_delegation_waiting_for_a_failed_or_asking_one_does_not_start() {+ let env = setup().await;+ let (channel, ids) = team(&env, "f4-lead-fail", &["Ld4", "Wr4", "An4"]).await;+ behave("Ld4", "On it. @Wr4, once @An4 has the numbers, write the summary. @An4 please crunch the numbers.");+ behave("Ld4.resume", "An4 failed, so nothing was written.");+ behave("An4", "FAIL");+ say_in(&env, &channel, "@Ld4 get me the report").await;+ wait_for("Wr4's task to end", || async { delegation_to(&env, &ids[0], &ids[1]).await.is_some_and(|d| !d.is_open()) }).await;+ settle(&env).await;+ let w = delegation_to(&env, &ids[0], &ids[1]).await.unwrap();+ assert_eq!(w.status, "failed");+ assert!(prompts_of("Wr4").is_empty(), "Wr4 never ran");+ assert!(messages(&env, &channel).await.iter().any(|m| m.text.contains("Wr4 didn't start")), "the channel says so");++ let (channel, ids) = team(&env, "f4-lead-ask", &["Ld5", "Wr5", "An5"]).await;+ behave("Ld5", "On it. @Wr5, once @An5 has the numbers, write the summary. @An5 please crunch the numbers.");+ behave("An5", "I can pull them.\nWhich quarter should I use?");+ say_in(&env, &channel, "@Ld5 get me the report").await;+ wait_for("Wr5's task to end", || async { delegation_to(&env, &ids[0], &ids[1]).await.is_some_and(|d| !d.is_open()) }).await;+ settle(&env).await;+ assert!(prompts_of("Wr5").is_empty(), "Wr5 never ran");+ let w = delegation_to(&env, &ids[0], &ids[1]).await.unwrap();+ assert!(w.error.as_deref().is_some_and(|e| e.contains("asked you something first")), "{w:?}");+}++// --- F5: one list of what the team needs from the person ---++#[tokio::test]+async fn two_askers_get_one_list_from_the_lead_and_the_answer_goes_to_it() {+ let env = setup().await;+ let (channel, _) = team(&env, "f5-two", &["Ld6", "Hub6", "As6", "Bs6"]).await;+ behave("Hub6", "Splitting it. @As6 please check the dates. @Bs6 please check the venues.");+ behave("As6", "Dates look tight.\nWhich month do you prefer?");+ behave("Bs6", "Venues found.\nWhat budget should I use?");+ behave("Ld6.list", "To go on we need:\n1. As6: which month\n2. Bs6: the budget");+ behave("Ld6", "Thanks, passing it on.");+ say_in(&env, &channel, "@Hub6 plan the offsite").await;+ wait_for("the list", || async { messages(&env, &channel).await.iter().any(|m| meta(m).get("consolidated_asks").is_some()) }).await;+ settle(&env).await;++ let gathering: Vec<_> = prompts_of("Ld6").into_iter().filter(|p| p.contains("as one numbered list")).collect();+ assert_eq!(gathering.len(), 1, "one extra turn");+ assert!(gathering[0].contains("Which month") && gathering[0].contains("What budget"), "{}", gathering[0]);+ let msgs = messages(&env, &channel).await;+ let list = msgs.iter().find(|m| meta(m).get("consolidated_asks").is_some()).unwrap();+ assert_eq!(list.sender_id, "Ld6");+ for asker in ["As6", "Bs6"] {+ let m = msgs.iter().find(|m| m.sender_id == asker).unwrap();+ assert_eq!(meta(m)["consolidated_into"], json!(list.id), "{asker}'s question links to the list");+ }++ let before = (prompts_of("As6").len(), prompts_of("Bs6").len());+ say_in(&env, &channel, "May, and 5000 EUR ANSWER6").await;+ wait_for("the lead's turn with the answer", || async { prompts_of("Ld6").iter().any(|p| p.contains("ANSWER6")) }).await;+ settle(&env).await;+ assert_eq!((prompts_of("As6").len(), prompts_of("Bs6").len()), before, "the answer went to the lead, not an asker");+ let p = prompts_of("Ld6").into_iter().find(|p| p.contains("ANSWER6")).unwrap();+ assert!(p.contains("Pass the part that answers") && p.contains("As6, Bs6"), "the lead is told whom to pass it to: {p}");+ assert_eq!(prompts_of("Ld6").iter().filter(|p| p.contains("as one numbered list")).count(), 1, "no second list");+}++#[tokio::test]+async fn one_asker_or_none_gets_no_extra_turn() {+ let env = setup().await;+ let (channel, _) = team(&env, "f5-one", &["Ld8", "Hub8", "As8", "Bs8"]).await;+ behave("Hub8", "Splitting it. @As8 please check the dates. @Bs8 please check the venues.");+ behave("As8", "Dates look tight.\nWhich month do you prefer?");+ behave("Bs8", "Venues found: three options.");+ say_in(&env, &channel, "@Hub8 plan the offsite").await;+ wait_for("Bs8's turn", || async { !prompts_of("Bs8").is_empty() }).await;+ settle(&env).await;+ assert!(prompts_of("Ld8").iter().all(|p| !p.contains("as one numbered list")), "one asker: no list");+ assert!(messages(&env, &channel).await.iter().all(|m| meta(m).get("consolidated_asks").is_none()));++ let (channel, _) = team(&env, "f5-none", &["Ld9", "Hub9", "As9"]).await;+ behave("Hub9", "Splitting it. @As9 please check the dates.");+ behave("As9", "Dates are fine.");+ say_in(&env, &channel, "@Hub9 plan the offsite").await;+ wait_for("As9's turn", || async { !prompts_of("As9").is_empty() }).await;+ settle(&env).await;+ assert!(prompts_of("Ld9").is_empty(), "nobody asked: the lead isn't woken");+}