Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Lead handoffs: follow-ups hand on, `@Name` in inline code counts, drops are said

Lin (kwant bot)effa88d8d08a
diff --git a/src/router/mod.rs b/src/router/mod.rs
index 8600835f..afcccad2 100644
--- a/src/router/mod.rs
+++ b/src/router/mod.rs
@@ -6,7 +6,7 @@ pub mod team;
pub use fallback::heuristic_fallback;
pub use laya::LayaRouter;
-pub use tags::{handoff_targets, parse_mentions, parse_mentions_with_lookup, TagMention};
+pub use tags::{handoff_mentions, handoff_targets, HandoffMentions, parse_mentions, parse_mentions_with_lookup, TagMention};
pub use team::{
heuristic_pick_kwant, heuristic_team_decision, matched_terms, parse_laya_kwant_choice,
parse_laya_team_answers, ChannelRoute, TeamDecision,
diff --git a/src/router/tags.rs b/src/router/tags.rs
index 4274fe43..84e20124 100644
--- a/src/router/tags.rs
+++ b/src/router/tags.rs
@@ -90,35 +90,94 @@ fn is_team_mention(token: &str) -> bool {
/// Teammates (as indices into `names`) that `text` hands the turn to with `@Name`,
/// in order of first mention. `@everyone` / `@all` selects every teammate.
-/// Mentions inside inline code or code fences are ignored.
+/// See [`handoff_mentions`] for what counts.
pub fn handoff_targets(text: &str, names: &[&str]) -> Vec<usize> {
+ handoff_mentions(text, names).targets
+}
+
+/// Words written after an `@` that address the person or the chat, not a bot.
+const NOT_A_BOT: [&str; 7] = ["you", "user", "me", "here", "channel", "team", "person"];
+
+/// What a reply's @mentions hand on, and the mentions that hand nothing on, so the caller can
+/// say why instead of dropping them.
+#[derive(Debug, Default, PartialEq, Eq)]
+pub struct HandoffMentions {
+ /// Teammates handed the turn, as indices into `names`, in order of first mention.
+ pub targets: Vec<usize>,
+ /// Teammates mentioned only inside a ``` code block.
+ pub in_code_block: Vec<usize>,
+ /// `@Name`s in prose that match no teammate, as written, once each.
+ pub unknown: Vec<String>,
+}
+
+/// Reads the @mentions in `text` against `names`. Prose mentions count, and so does inline
+/// code that is just a teammate's name (`` `@Growth` ``: models often format names that way).
+/// Other inline code, ``` code blocks and email addresses hand nothing on.
+pub fn handoff_mentions(text: &str, names: &[&str]) -> HandoffMentions {
+ let is_name = |tag: &str| names.iter().position(|n| n.eq_ignore_ascii_case(tag));
+ let chars: Vec<char> = text.chars().collect();
+ let find = |from: usize, pat: &[char]| (from..=chars.len().saturating_sub(pat.len())).find(|&j| chars[j..].starts_with(pat));
+ let fence = ['`', '`', '`'];
let mut prose = String::with_capacity(text.len());
- let mut in_code = false;
- for c in text.chars() {
- if c == '`' {
- in_code = !in_code;
+ let mut fenced = String::new();
+ let mut i = 0;
+ while i < chars.len() {
+ if chars[i..].starts_with(&fence) {
+ let end = find(i + 3, &fence).unwrap_or(chars.len());
+ fenced.extend(&chars[i + 3..end]);
+ fenced.push('\n');
prose.push(' ');
- } else if !in_code {
- prose.push(c);
+ i = (end + 3).min(chars.len());
+ } else if chars[i] == '`' {
+ match find(i + 1, &['`']) {
+ Some(end) => {
+ let span: String = chars[i + 1..end].iter().collect();
+ let span = span.trim();
+ match span.strip_prefix('@').filter(|tag| is_name(tag).is_some()) {
+ Some(tag) => prose.push_str(&format!(" @{tag} ")),
+ None => prose.push(' '),
+ }
+ i = end + 1;
+ }
+ // A lone backtick is just a character
+ None => {
+ prose.push(' ');
+ i += 1;
+ }
+ }
+ } else {
+ prose.push(chars[i]);
+ i += 1;
}
}
- let mut picked = Vec::new();
+ let mut out = HandoffMentions::default();
for mention in parse_mentions_with_lookup(&prose, |_| Some(false)) {
let tag = mention.name();
if tag.eq_ignore_ascii_case("everyone") || tag.eq_ignore_ascii_case("all") {
for i in 0..names.len() {
- if !picked.contains(&i) {
- picked.push(i);
+ if !out.targets.contains(&i) {
+ out.targets.push(i);
}
}
- } else if let Some(i) = names.iter().position(|n| n.eq_ignore_ascii_case(tag)) {
- if !picked.contains(&i) {
- picked.push(i);
+ } else if let Some(i) = is_name(tag) {
+ if !out.targets.contains(&i) {
+ out.targets.push(i);
}
+ } else if !NOT_A_BOT.iter().any(|w| w.eq_ignore_ascii_case(tag))
+ && !out.unknown.iter().any(|u| u.eq_ignore_ascii_case(tag))
+ {
+ out.unknown.push(tag.to_string());
}
}
- picked
+ for mention in parse_mentions_with_lookup(&fenced, |_| Some(false)) {
+ if let Some(i) = is_name(mention.name()) {
+ if !out.targets.contains(&i) && !out.in_code_block.contains(&i) {
+ out.in_code_block.push(i);
+ }
+ }
+ }
+ out
}
#[cfg(test)]
@@ -131,11 +190,42 @@ mod tests {
assert_eq!(handoff_targets("@techlead and @DevOps, say hi!", &names), vec![1, 2]);
assert_eq!(handoff_targets("@DevOps then @devops again", &names), vec![2]);
assert_eq!(handoff_targets("hey @everyone", &names), vec![0, 1, 2]);
- assert_eq!(handoff_targets("email [email protected] or run `@DevOps`", &names), Vec::<usize>::new());
+ assert_eq!(handoff_targets("email [email protected] or run `npm @DevOps`", &names), Vec::<usize>::new());
+ assert_eq!(handoff_targets("run `@DevOps`", &names), vec![2]);
assert_eq!(handoff_targets("@Stranger please help", &names), Vec::<usize>::new());
assert_eq!(handoff_targets("```\n@Architect\n``` ok @Architect", &names), vec![0]);
}
+ /// The reply Product wrote in team-Startup on 2026-10-21: the model put the name in inline
+ /// code, and Growth was never asked.
+ #[test]
+ fn a_name_in_inline_code_hands_on() {
+ let names = ["Product", "TechLead", "Designer", "Security", "Growth"];
+ let reply = "Security's and Designer's results cover what was asked, so no corrections were needed.\n\n\
+ **One thing I need from you:** where should we host it?\n\n\
+ `@Growth`, v0 is close to ready for the first 30 users. Please draft the launch plan: where to find \
+ people who journal or set goals, the invite message, and a list of 5 people to interview.";
+ assert_eq!(handoff_targets(reply, &names), vec![4]);
+ assert_eq!(handoff_targets("ask ` @growth ` please", &names), vec![4], "spaces and case inside the span");
+ assert_eq!(handoff_targets("`@Growth`/`@Security`", &names), vec![4, 3]);
+ // Inline code that is more than a name stays code; so do fences and emails
+ assert_eq!(handoff_targets("run `deploy @Growth` then", &names), Vec::<usize>::new());
+ assert_eq!(handoff_targets("mail [email protected]", &names), Vec::<usize>::new());
+ assert_eq!(handoff_targets("an odd ` tick then @Growth", &names), vec![4], "a lone backtick hides nothing");
+ }
+
+ #[test]
+ fn mentions_that_hand_nothing_on_are_reported() {
+ let names = ["Product", "Growth", "Security"];
+ let m = handoff_mentions("@Growth and @Marketer, cc @you\n```\n@Security run\n```\n@marketer again", &names);
+ assert_eq!(m.targets, vec![1]);
+ assert_eq!(m.unknown, vec!["Marketer".to_string()]);
+ assert_eq!(m.in_code_block, vec![2]);
+ // A teammate also named in prose isn't reported as only in code
+ let m = handoff_mentions("```\n@Growth\n``` ok @Growth", &names);
+ assert_eq!((m.targets, m.in_code_block), (vec![1], vec![]));
+ }
+
#[test]
fn test_mention_methods() {
let k = TagMention::Kwant("Architect".into());
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index 5dc4d507..df45d6bb 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -437,7 +437,23 @@ async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation]) {
correction. Otherwise continue with the user's request and give them one answer that uses the results. \
Don't repeat the results in full."
);
- let _ = try_kwant_turn(&scope, &lead, prompt, TurnOpts::default()).await;
+ // 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.
+ if let Ok(reply) = try_kwant_turn(&scope, &lead, prompt, TurnOpts::default()).await {
+ let mut spoken = vec![lead.id.clone()];
+ spoken.extend(batch.iter().map(|b| b.specialist_kwant_id.clone()));
+ let user_prompt = state
+ .db
+ .list_messages(d.origin_context().unwrap_or(&lead.id), 100)
+ .await
+ .unwrap_or_default()
+ .into_iter()
+ .rev()
+ .find(|m| m.sender_role == "user")
+ .map(|m| m.text)
+ .unwrap_or_else(|| d.task.clone());
+ super::routes::run_handoffs_boxed(&scope, &spoken, &[(lead.clone(), reply)], &user_prompt).await;
+ }
}
// Cancelling, follow-ups, restarts
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 3aec96d0..73d24787 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -755,6 +755,9 @@ fn team_context(t: &Team) -> crate::drivers::TeamContext {
/// Max follow-up turns kwants may trigger by @mentioning each other for one user message.
const MAX_HANDOFFS: usize = 4;
+/// Delegations a lead's @mentions may start for one user message, follow-up rounds included:
+/// a lead resumed with results can hand on again, but never in an endless loop.
+pub const MAX_DELEGATIONS_PER_REQUEST: usize = 8;
#[allow(clippy::too_many_arguments)]
fn execute_single_turn(
@@ -836,21 +839,40 @@ pub(super) async fn run_routine_turn(
/// Lets teammates that kwants @mentioned in `replies` answer in turn, so kwants can delegate to each other.
/// `already_spoken` kwants are not handed the turn again.
+/// [`run_handoffs`] for a lead's follow-up after delegation results: boxed with a named type,
+/// because handing on starts delegations whose end resumes the lead again (a cycle of futures).
+pub(super) fn run_handoffs_boxed<'a>(
+ scope: &'a TurnScope,
+ already_spoken: &'a [String],
+ replies: &'a [(Kwant, String)],
+ user_prompt: &'a str,
+) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>> {
+ Box::pin(run_handoffs(scope, already_spoken, replies, user_prompt))
+}
+
async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(Kwant, String)], user_prompt: &str) {
if let [(from, text)] = replies {
if is_team_channel_lead(scope, from).await {
- return delegate_mentions(scope, from, text, user_prompt).await;
+ return delegate_mentions(scope, from, text, user_prompt, already_spoken).await;
}
}
+ if scope.teammates.is_empty() {
+ return;
+ }
let mut spoken: Vec<String> = already_spoken.to_vec();
let mut queue: std::collections::VecDeque<(Kwant, String, String)> = std::collections::VecDeque::new();
- let enqueue = |queue: &mut std::collections::VecDeque<(Kwant, String, String)>,
- spoken: &[String],
- from: &Kwant,
- text: &str| {
+ 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 names: Vec<&str> = scope.teammates.iter().map(|k| k.name.as_str()).collect();
- for i in crate::router::handoff_targets(text, &names) {
+ let found = crate::router::handoff_mentions(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 {
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()));
}
@@ -860,7 +882,8 @@ async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(
enqueue(&mut queue, &spoken, from, text);
}
if queue.is_empty() {
- return;
+ drop(enqueue);
+ return report_skipped(scope, skipped).await;
}
let events = scope.state.event_sender.clone();
@@ -904,8 +927,50 @@ async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(
None => {}
}
}
+ drop(enqueue);
+ 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"))));
+ }
let _ = events.send(RuntimeEvent::DiscussionCompleted { total_turns: done + 1, context_id: Some(context_id.clone()) });
+ report_skipped(scope, skipped).await;
+}
+
+const IN_CODE_BLOCK: &str = "the mention was inside a code block";
+
+/// Says in the chat, and logs, each @mention that handed nothing on: "Growth wasn't asked: <why>".
+/// An empty reason means no teammate has that name; it's worked out here.
+async fn report_skipped(scope: &TurnScope, skipped: Vec<(String, String)>) {
+ let mut said: Vec<String> = Vec::new();
+ for (name, why) in skipped {
+ if said.iter().any(|n| n.eq_ignore_ascii_case(&name)) {
+ continue;
+ }
+ said.push(name.clone());
+ let why = if why.is_empty() { unknown_mention(scope, &name).await } else { why };
+ tracing::info!(context = ?scope.channel_id.as_ref().or(scope.thread_id.as_ref()), mention = %name, "mention handed nothing on: {why}");
+ let note = scope.message("system", "kwnt", format!("{name} wasn't asked: {why}"));
+ if let Some(saved) = scope.save(&note, Some(serde_json::json!({"kind": "handoff_refused", "mention": name}))).await {
+ let _ = scope
+ .state
+ .event_sender
+ .send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or_default() });
+ }
+ }
+}
+
+/// Why `@name` matched no one in this chat.
+async fn unknown_mention(scope: &TurnScope, name: &str) -> String {
+ let space = scope.teammates.first().map(|k| SpaceId::new(&k.space_id));
+ let in_space = match &space {
+ Some(space) => scope.state.db.list_kwants(space).await.unwrap_or_default().iter().any(|k| k.name.eq_ignore_ascii_case(name)),
+ None => false,
+ };
+ if in_space {
+ format!("{name} isn't in this chat")
+ } else {
+ format!("there's no teammate called {name} here")
+ }
}
/// Whether `kwant` leads the team channel this turn is in (a channel turn, not a thread).
@@ -922,25 +987,46 @@ async fn is_team_channel_lead(scope: &TurnScope, kwant: &Kwant) -> bool {
/// A team lead's @mentions in its team channel hand work on as delegations, not handoff turns:
/// each teammate gets the task in its own thread (Sent-to chip, queue, the same guards as the
/// delegate tool), and when the last one ends the lead is resumed once with every result to give
-/// the user one answer. A refused handoff is said in the channel. Teammates the lead already
-/// delegated to from this channel (with the tool) aren't sent it twice.
-async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_prompt: &str) {
+/// the user one answer; that follow-up may hand on again. `just_reported` teammates (whose results
+/// the follow-up is about) aren't sent it again by a mention, and one user message starts at most
+/// [`MAX_DELEGATIONS_PER_REQUEST`]. Every mention that hands nothing on is said in the channel.
+/// Teammates the lead already delegated to from this channel (with the tool) aren't sent it twice.
+async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_prompt: &str, just_reported: &[String]) {
let Some(cid) = scope.channel_id.clone() else { return };
let names: Vec<&str> = scope.teammates.iter().map(|k| k.name.as_str()).collect();
- let open: Vec<String> = scope
+ let found = crate::router::handoff_mentions(text, &names);
+ 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) {
+ return report_skipped(scope, skipped).await;
+ }
+ let mine: Vec<_> = scope
.state
.db
.list_delegations(Some(&lead.id), None, 50)
.await
.unwrap_or_default()
.into_iter()
- .filter(|d| d.is_open() && d.origin_channel_id.as_deref() == Some(cid.as_str()))
- .map(|d| d.specialist_kwant_id)
+ .filter(|d| d.origin_channel_id.as_deref() == Some(cid.as_str()))
.collect();
+ let open: Vec<&str> = mine.iter().filter(|d| d.is_open()).map(|d| d.specialist_kwant_id.as_str()).collect();
+ // Delegations this user message already started, counting earlier follow-up rounds
+ let messages = scope.state.db.list_messages(&cid, 100).await.unwrap_or_default();
+ let since = messages.iter().rev().find(|m| m.sender_role == "user").or(messages.first()).and_then(|m| m.created_at);
+ let started = mine.iter().filter(|d| d.continue_lead && since.is_some_and(|t| d.created_at >= t)).count();
+ let mut room = MAX_DELEGATIONS_PER_REQUEST.saturating_sub(started);
+
let mut targets: Vec<&Kwant> = Vec::new();
- for i in crate::router::handoff_targets(text, &names) {
+ for i in found.targets {
let k = &scope.teammates[i];
- if k.id != lead.id && !open.contains(&k.id) && !targets.iter().any(|t| t.id == k.id) {
+ if k.id == lead.id || targets.iter().any(|t| t.id == k.id) {
+ continue;
+ }
+ if just_reported.contains(&k.id) {
+ skipped.push((k.name.clone(), format!("{} just reported back on this. For a correction, delegate a concrete task", k.name)));
+ } else if open.contains(&k.id.as_str()) {
+ skipped.push((k.name.clone(), format!("{} is still working on an earlier task from this chat", k.name)));
+ } else {
targets.push(k);
}
}
@@ -952,7 +1038,18 @@ async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_pro
);
let title = truncate_chars(user.lines().find(|l| !l.trim().is_empty()).unwrap_or("Task").trim(), 80).to_string();
let allowed: Vec<String> = scope.teammates.iter().map(|k| k.id.clone()).collect();
- for specialist in targets.into_iter().take(MAX_HANDOFFS) {
+ for (n, specialist) in targets.into_iter().enumerate() {
+ if n >= MAX_HANDOFFS {
+ skipped.push((specialist.name.clone(), format!("a message hands work to at most {MAX_HANDOFFS} teammates")));
+ continue;
+ }
+ if room == 0 {
+ skipped.push((
+ specialist.name.clone(),
+ format!("this request has already gone to {MAX_DELEGATIONS_PER_REQUEST} teammates. Send a new message to go on"),
+ ));
+ continue;
+ }
let req = super::delegation::StartRequest {
lead: lead.clone(),
specialist: specialist.clone(),
@@ -963,17 +1060,12 @@ async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_pro
origin_depth: scope.delegation_depth,
allowed: Some(allowed.clone()),
};
- if let Err((_, why)) = super::delegation::start(&scope.state, req).await {
- tracing::info!(lead = %lead.id, specialist = %specialist.id, "mention handoff refused: {why}");
- let note = scope.message("system", "kwnt", format!("Couldn't hand this to {}: {why}", specialist.name));
- if let Some(saved) = scope.save(&note, Some(serde_json::json!({"kind": "handoff_refused"}))).await {
- let _ = scope
- .state
- .event_sender
- .send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or_default() });
- }
+ match super::delegation::start(&scope.state, req).await {
+ Ok(_) => room -= 1,
+ Err((_, why)) => skipped.push((specialist.name.clone(), why.trim_end_matches('.').to_string())),
}
}
+ report_skipped(scope, skipped).await;
}
/// Runs a moderated team discussion: the lead opens (or pauses to ask the user), teammates react to
diff --git a/tests/delegation_test.rs b/tests/delegation_test.rs
index 56a37071..341a42e7 100644
--- a/tests/delegation_test.rs
+++ b/tests/delegation_test.rs
@@ -23,7 +23,8 @@ use std::time::Duration;
use tower::ServiceExt;
/// Replies "answer <tag>" for a prompt with "REPLYTAG:<tag>", followed by "@<name>" for one with
-/// "MENTION:<name>"; a "LONGTASK:<file>" prompt waits (up to 60 s) for that file first. Every prompt is saved under `$KWNT_TEST_PROMPTS`.
+/// "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`.
const FAKE_CLAUDE: &str = r#"#!/bin/sh
case "$1" in
auth) echo '{"loggedIn":true}'; exit 0 ;;
@@ -37,7 +38,9 @@ if [ -n "$release" ]; then
fi
tag=$(printf '%s\n' "$last" | sed -n 's/.*REPLYTAG:\([A-Za-z0-9_]*\).*/\1/p' | tail -n 1)
mention=$(printf '%s\n' "$last" | sed -n 's/.*MENTION:\([A-Za-z0-9_]*\).*/\1/p' | head -n 1)
-echo "{\"type\":\"result\",\"is_error\":false,\"num_turns\":1,\"result\":\"answer ${tag:-none}${mention:+ @$mention}\"}"
+followup=$(printf '%s\n' "$last" | sed -n 's/.*FOLLOWUP:\([A-Za-z0-9_]*\).*/\1/p' | head -n 1)
+case "$last" in *"finished the task you delegated"*) ;; *) followup="" ;; esac
+echo "{\"type\":\"result\",\"is_error\":false,\"num_turns\":1,\"result\":\"answer ${tag:-none}${mention:+ @$mention}${followup:+ \`@$followup\`}\"}"
"#;
fn prompts_dir() -> &'static PathBuf {
@@ -891,3 +894,125 @@ async fn non_lead_mentions_hand_off_and_refused_mentions_are_reported() {
wait_for("a held task to finish", || async { delegation_status(&env, &id).await == "completed" }).await;
}
}
+
+/// A third bot on the fake claude, named `name`.
+async fn add_bot(env: &Env, name: &str) -> String {
+ let (s, v) = call(&env.app, "POST", "/api/kwants", Some(json!({"name": name, "title": "Growth Marketer", "persona_prompt": "", "soul": "", "avatar_sprite": "default", "driver_type": "cli", "preferred_model": "claude"}))).await;
+ assert!(s.is_success(), "{s} {v}");
+ v["id"].as_str().or(v["kwant"]["id"].as_str()).unwrap().to_string()
+}
+
+/// A team led by `env.lead` with `members`; returns its channel's id.
+async fn team_channel_with(env: &Env, team: &str, members: &[&str]) -> String {
+ let (s, v) = call(&env.app, "POST", "/api/teams", Some(json!({"name": team, "lead_kwant_id": env.lead, "member_kwants": members}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ let (_, channels) = call(&env.app, "GET", "/api/channels", None).await;
+ channels.as_array().unwrap().iter().find(|c| c["name"] == format!("team-{team}").as_str()).unwrap()["id"].as_str().unwrap().to_string()
+}
+
+/// A delegation from the lead, started from `channel`, that resumes the lead when it ends.
+async fn delegate_from(env: &Env, channel: &str, to: &str, task: &str, title: &str) -> String {
+ let (s, d) = call(
+ &env.app,
+ "POST",
+ "/api/delegations",
+ Some(json!({"lead_kwant_id": env.lead, "specialist_kwant_id": to, "task": task, "title": title, "channel_id": channel, "continue_lead": true})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::ACCEPTED, "{d}");
+ d["id"].as_str().unwrap().to_string()
+}
+
+fn refusals(msgs: &[kwnt::db::models::Message]) -> Vec<String> {
+ msgs.iter().filter(|m| meta_kind(m).as_deref() == Some("handoff_refused")).map(|m| m.text.clone()).collect()
+}
+
+/// Bug 3 (team-Startup, 2026-10-21): the lead's follow-up after results came back said "`@Growth`,
+/// please draft the launch plan" and Growth never ran. The follow-up now hands on like any lead
+/// reply, a name in inline code counts, and mentioning the teammate who just reported back hands
+/// nothing on but says so.
+#[tokio::test]
+async fn a_leads_follow_up_after_results_hands_on_to_the_next_teammate() {
+ let env = setup().await;
+ let growth = add_bot(&env, "Growth").await;
+ let channel = team_channel_with(&env, "startup-follow", &[&env.lead, &env.specialist, &growth]).await;
+ let first = delegate_from(&env, &channel, &env.specialist, "Review the app REPLYTAG:reviewed", "Security review FOLLOWUP:Growth").await;
+ wait_for("the review to complete", || async { delegation_status(&env, &first).await == "completed" }).await;
+
+ let to_growth = || async {
+ env.state.db.list_delegations(Some(&env.lead), None, 20).await.unwrap().into_iter().find(|d| d.specialist_kwant_id == growth)
+ };
+ wait_for("the follow-up's delegation to Growth", || async { to_growth().await.is_some() }).await;
+ let d = to_growth().await.unwrap();
+ assert_eq!(d.origin_channel_id.as_deref(), Some(channel.as_str()));
+ assert!(d.continue_lead && d.depth == 1, "same depth as the first round: {d:?}");
+ assert!(d.task.contains("`@Growth`"), "Growth gets the lead's words: {}", d.task);
+
+ wait_for("Growth's result", || async { delegation_status(&env, &d.id).await == "completed" }).await;
+ // Growth's own follow-up names Growth again (its title carries the marker): not sent back
+ wait_for("the just-reported notice", || async { !refusals(&channel_messages(&env, &channel).await).is_empty() }).await;
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+ let notes = refusals(&channel_messages(&env, &channel).await);
+ assert_eq!(notes.len(), 1, "{notes:?}");
+ assert!(notes[0].starts_with("Growth wasn't asked: Growth just reported back"), "{}", notes[0]);
+ let all = env.state.db.list_delegations(Some(&env.lead), None, 20).await.unwrap();
+ assert_eq!(all.len(), 2, "the review and Growth's plan, no loop: {all:?}");
+}
+
+/// Mentions that hand nothing on are said in the channel: a name no teammate has, and a follow-up
+/// after the request already went to the most teammates one message may reach.
+#[tokio::test]
+async fn mentions_that_hand_nothing_on_are_said_in_the_channel() {
+ let env = setup().await;
+ let lead = name(&env, &env.lead).await;
+ let growth = add_bot(&env, "Growth").await;
+ let channel = team_channel_with(&env, "startup-limits", &[&env.lead, &env.specialist, &growth]).await;
+ say_in(&env, &channel, &format!("@{lead} Who else? UNKNOWNMARK REPLYTAG:who MENTION:Marketer")).await;
+ wait_for("the unknown-name notice", || async { !refusals(&channel_messages(&env, &channel).await).is_empty() }).await;
+ let notes = refusals(&channel_messages(&env, &channel).await);
+ assert_eq!(notes, vec!["Marketer wasn't asked: there's no teammate called Marketer here".to_string()]);
+ assert!(env.state.db.list_delegations(Some(&env.lead), None, 20).await.unwrap().is_empty());
+
+ // This request already started the most delegations it may (earlier rounds, all ended)
+ for _ in 0..routes_limit() {
+ let (_, d) = env
+ .state
+ .db
+ .create_delegation(&kwnt::db::threads::NewDelegation {
+ lead_kwant_id: env.lead.clone(),
+ specialist_kwant_id: env.specialist.clone(),
+ origin_channel_id: Some(channel.clone()),
+ origin_kwant_id: None,
+ origin_thread_id: None,
+ team_id: None,
+ task: "earlier round".into(),
+ title: "Earlier round".into(),
+ continue_lead: true,
+ depth: 1,
+ follow_up_at: None,
+ })
+ .await
+ .unwrap();
+ assert!(env.state.db.finish_delegation(&d.id, "completed", None, None).await.unwrap());
+ }
+ let last = delegate_from(&env, &channel, &env.specialist, "One more REPLYTAG:more", "Last part FOLLOWUP:Growth").await;
+ wait_for("the last part", || async { delegation_status(&env, &last).await == "completed" }).await;
+ let limit_note = || async {
+ refusals(&channel_messages(&env, &channel).await).into_iter().find(|n| n.starts_with("Growth wasn't asked"))
+ };
+ for _ in 0..100 {
+ if limit_note().await.is_some() {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ let msgs: Vec<String> = channel_messages(&env, &channel).await.iter().map(|m| format!("{}: {}", m.sender_id, m.text)).collect();
+ let note = limit_note().await.unwrap_or_else(|| panic!("no limit notice: {msgs:#?}"));
+ assert!(note.starts_with("Growth wasn't asked: this request has already gone to"), "{note}");
+ let delegated_growth = env.state.db.list_delegations(Some(&env.lead), None, 50).await.unwrap().iter().any(|d| d.specialist_kwant_id == growth);
+ assert!(!delegated_growth, "over the limit, Growth isn't asked");
+}
+
+fn routes_limit() -> usize {
+ kwnt::server::routes::MAX_DELEGATIONS_PER_REQUEST
+}