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 on a teammate's result @mentions; one @mention wins routing (#143)
Lin (kwant bot)06aa5a2ec704
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 56dd21f7..4f489727 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -81,6 +81,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).the browser page as a picture, so a designer bot can check layout, colours and spacing. It can takethe shot at a set width (390 for a phone, 1280 for a desktop) and puts the browser back to its own sizeafterwards. Like the other browser tools, it waits while you sign in, solve a CAPTCHA or have control.+- **A teammate's result now hands on its @mentions.** In a team channel, when a teammate's result+ @mentions another teammate ("@Frontend could switch to …"), that teammate gets the task even if the+ lead doesn't pass it on. It follows the same caps as the lead's mentions (Continue past them), never+ hands work back to someone earlier in the same chain, and skips mentions that only credit someone.+ The lead is resumed once with all of these results.+- **"@Frontend why didn't you answer QA" goes to Frontend.** A message that @mentions exactly one+ teammate goes to that teammate even if it names others without an @. Two @mentions still go to+ the lead.- **A restart no longer leaves an audit running.** An audit cut off mid-turn by a restart ends`interrupted` and says so in the task's history; one still waiting to start runs after the restart(or is skipped if the auditor was turned off).diff --git a/src/db/threads.rs b/src/db/threads.rsindex 60fb910d..3536362e 100644--- a/src/db/threads.rs+++ b/src/db/threads.rs@@ -59,6 +59,10 @@ pub struct Delegation {/// has the numbers, …"). Set while it is parked as `queued`; cleared when it starts.#[sqlx(default)]pub after_delegation_id: Option<String>,+ /// The delegation whose result @mentioned this teammate, so this task was started from it.+ /// The lead hears both results in one batch (see `finished_batch`).+ #[sqlx(default)]+ pub relayed_from_delegation_id: Option<String>,}impl Delegation {@@ -155,6 +159,9 @@ impl Database {let _ = sqlx::query("ALTER TABLE delegations ADD COLUMN after_delegation_id TEXT;").execute(&self.pool).await;+ let _ = sqlx::query("ALTER TABLE delegations ADD COLUMN relayed_from_delegation_id TEXT;")+ .execute(&self.pool)+ .await;Ok(())}@@ -292,6 +299,7 @@ impl Database {ended_at: None,retries: 0,after_delegation_id: None,+ relayed_from_delegation_id: None,};sqlx::query("INSERT INTO delegations (id, thread_id, lead_kwant_id, specialist_kwant_id, origin_channel_id, origin_kwant_id, \@@ -457,6 +465,17 @@ impl Database {Ok(())}+ /// Marks `id` as started from `from`'s result by an @mention (see+ /// [`Delegation::relayed_from_delegation_id`]).+ pub async fn set_delegation_relayed_from(&self, id: &str, from: &str) -> Result<(), DbError> {+ sqlx::query("UPDATE delegations SET relayed_from_delegation_id = ? WHERE id = ?")+ .bind(from)+ .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>(diff --git a/src/router/team.rs b/src/router/team.rsindex d042bbf8..6bc4619e 100644--- a/src/router/team.rs+++ b/src/router/team.rs@@ -587,7 +587,26 @@ pub fn pick_member_after<'a>(Pick { kwant: k, basis: if agree { "skills" } else { "keywords" }, reason, terms }};- // 1. Named in the message ("Bea, can you…")+ // 1. @Named in the message: one @Name wins over plain names ("@Frontend why didn't you answer+ // QA" is for Frontend, not "Frontend and QA"); two or more @Names go to the lead+ let member_names: Vec<&str> = members.iter().map(|m| m.name.as_str()).collect();+ let at_named: Vec<&'a Kwant> =+ crate::router::handoff_mentions(prompt, &member_names).targets.into_iter().map(|i| &members[i]).collect();+ match at_named.as_slice() {+ [] => {}+ [k] => return Some(chosen(k, vec![k.name.trim().to_lowercase()], "was @mentioned in your message")),+ several => {+ let terms = several.iter().map(|k| k.name.trim().to_lowercase()).collect();+ let reason = format!(+ "Your message @mentions {}, so it went to the {lead_word}, {} ({}), to answer or hand parts on",+ names(several),+ lead.name,+ lead.title+ );+ return Some(Pick { kwant: lead, basis: "several", reason, terms });+ }+ }+ // Named without @ ("Bea, can you…")let named: Vec<&Kwant> = members.iter().filter(|m| words.iter().any(|w| *w == m.name.trim().to_lowercase())).collect();if let [k] = named.as_slice() {return Some(chosen(k, vec![k.name.trim().to_lowercase()], "was named in your message"));@@ -1262,6 +1281,37 @@ mod tests {assert!(!is_small_talk(""));}+ /// Oleks 2026-10-29: "@Frontend why you did not answer to QA" named two bots, so it went to+ /// the lead. One @Name wins over a plain name; two @Names still go to the lead.+ #[test]+ fn one_at_mention_wins_over_plain_names() {+ let (_, mut members) = make_test_fixture();+ let base = members[0].clone();+ let named = |id: &str, name: &str, title: &str| Kwant { id: id.into(), name: name.into(), title: title.into(), ..base.clone() };+ members.extend([+ named("kwant-fe", "Frontend", "Frontend and UX engineer"),+ named("kwant-qa", "QA", "QA and DevOps engineer"),+ named("kwant-de", "Designer", "Product and UI designer"),+ ]);+ let sure_qa = Some(LayaGuess { kwant: &members[members.len() - 2], confident: true });+ let p = pick_member_after("@Frontend why you did not answer to QA. It mentioned you", "kwant-1", &members, sure_qa, "lead", Some("kwant-qa"))+ .unwrap();+ assert_eq!((p.kwant.id.as_str(), p.basis), ("kwant-fe", "keywords"), "{p:?}");+ assert!(p.reason.contains("@mentioned"), "{p:?}");+ // Inline code that is just the name counts too, as in a chip+ let p = pick_member_after("`@Frontend` please answer QA's design report", "kwant-1", &members, None, "lead", None).unwrap();+ assert_eq!(p.kwant.id, "kwant-fe", "{p:?}");+ // Two @Names: the lead+ let p = pick_member_after("@Frontend and @QA, sort out the chip focus", "kwant-1", &members, None, "lead", None).unwrap();+ assert_eq!((p.kwant.id.as_str(), p.basis), ("kwant-1", "several"), "{p:?}");+ assert!(p.reason.contains("Frontend") && p.reason.contains("QA"), "{p:?}");+ // An email address or an unknown @name is no pick: the old rules apply+ let p = pick_member_after("mail [email protected] about QA", "kwant-1", &members, None, "lead", None).unwrap();+ assert_ne!(p.kwant.id, "kwant-fe", "{p:?}");+ let p = pick_member_after("@Nobody, Frontend please look", "kwant-1", &members, None, "lead", None).unwrap();+ assert_eq!(p.kwant.id, "kwant-fe", "{p:?}");+ }+/// F2a: a pick that went against Laya's unsure guess is logged as "low confidence".#[test]fn a_low_confidence_guess_is_named_as_the_fallback_reason() {diff --git a/src/server/budget.rs b/src/server/budget.rsindex abe73863..ecc8e20a 100644--- a/src/server/budget.rs+++ b/src/server/budget.rs@@ -190,7 +190,7 @@ async fn resume_capped(state: &AppState, notice_id: &str, mut meta: serde_json::.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "could not set up the chat"))?;tokio::spawn(async move {let _job = job;- super::routes::delegate_mentions(&scope, &lead, &text, &user_prompt, &[], Some(&waiting)).await;+ super::routes::delegate_mentions(&scope, &lead, &text, &user_prompt, &[], Some(&waiting), None).await;});Ok(())}diff --git a/src/server/delegation.rs b/src/server/delegation.rsindex b56e575e..96b854ca 100644--- a/src/server/delegation.rs+++ b/src/server/delegation.rs@@ -151,6 +151,9 @@ pub struct StartRequest {/// 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>,+ /// The ended delegation whose result @mentioned this teammate (see+ /// [`Delegation::relayed_from_delegation_id`]).+ pub relayed_from: Option<String>,}/// Checks a request, creates the thread and the delegation, and starts the specialist's turn@@ -261,6 +264,15 @@ pub async fn start(state: &AppState, req: StartRequest) -> Result<Delegation, (S.await.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "database error".into()))?;+ // Linked before it runs, so the lead's batch waits for it (see `finished_batch`)+ let d = match &req.relayed_from {+ Some(from) => {+ let _ = state.db.set_delegation_relayed_from(&d.id, from).await;+ state.db.get_delegation(&d.id).await.ok().flatten().unwrap_or(d)+ }+ None => d,+ };+// Waits for a sibling of the same lead and chat that is still open; anything else is ignoredlet prereq = match &req.after {Some(id) => state@@ -679,6 +691,10 @@ async fn finish(state: &AppState, d: &Delegation, specialist: &Kwant, outcome: R.await;release_dependents(state, &done.id).await;if !carried_on {+ // Teammates the result @mentions start first, so the lead's batch waits for them too+ if let Ok(reply) = &outcome {+ relay_mentions(state, &done, specialist, reply).await;+ }return report_to_lead(state, &done, None).await;}// Its batch already went to the lead: this result goes on its own (a stop was the person's)@@ -688,6 +704,66 @@ async fn finish(state: &AppState, d: &Delegation, specialist: &Kwant, outcome: R}}+/// How many relays back [`relay_chain`] looks; a chain is bounded by the hand-off caps anyway.+const MAX_RELAY_CHAIN: usize = 32;++/// Hands on the @mentions of other teammates in a completed result posted to a team channel+/// (Oleks, 2026-10-29: QA's result said "@Frontend could switch to …" and Frontend never heard).+/// Same rules as a lead's mentions ([`super::routes::delegate_mentions`]): per-bot and+/// per-request caps, a notice for each one not sent, never back to a bot in this chain.+async fn relay_mentions(state: &AppState, done: &Delegation, specialist: &Kwant, reply: &str) {+ let Some(cid) = done.origin_channel_id.clone() else { return };+ if !done.continue_lead || done.status != "completed" || !reply.contains('@') {+ return;+ }+ let Ok(Some(lead)) = state.db.get_kwant(&done.lead_kwant_id).await else { return };+ let job = state.turns.start_job([done.id.clone()]);+ let Ok(scope) = scope_for(state, &lead, Some(cid), None, &job, done.depth - 1).await else { return };+ if !scope.teammates.iter().any(|k| k.id == specialist.id) {+ return;+ }+ let user_prompt = state+ .db+ .list_messages(done.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(|| done.task.clone());+ let end = |d: &Delegation| d.ended_at.unwrap_or(d.created_at);+ let alongside = state+ .db+ .list_delegations(Some(&done.lead_kwant_id), None, 50)+ .await+ .unwrap_or_default()+ .into_iter()+ .filter(|s| s.continue_lead && s.origin_context() == done.origin_context())+ .filter(|s| s.is_open() || (s.created_at <= end(done) && end(s) >= done.created_at))+ .map(|s| s.specialist_kwant_id)+ .collect();+ let relay = super::routes::Relay { from: specialist, source: done, chain: relay_chain(state, done).await, alongside };+ super::routes::delegate_mentions(&scope, &lead, reply, &user_prompt, &[], None, Some(&relay)).await;+}++/// The teammates of `d` and of every delegation it was relayed from.+async fn relay_chain(state: &AppState, d: &Delegation) -> Vec<String> {+ let mut chain = vec![d.specialist_kwant_id.clone()];+ let mut from = d.relayed_from_delegation_id.clone();+ while let Some(id) = from.take() {+ if chain.len() > MAX_RELAY_CHAIN {+ break;+ }+ let Ok(Some(p)) = state.db.get_delegation(&id).await else { break };+ if !chain.contains(&p.specialist_kwant_id) {+ chain.push(p.specialist_kwant_id.clone());+ }+ from = p.relayed_from_delegation_id.clone();+ }+ chain+}+/// Resumes the lead once `d` ended, if it was the last of its batch to end (see/// [`finished_batch`]). `opening` replaces the first line of the lead's prompt.async fn report_to_lead(state: &AppState, d: &Delegation, opening: Option<String>) {@@ -794,13 +870,19 @@ async fn finished_batch(state: &AppState, d: &Delegation) -> Option<Vec<Delegatireturn None;}let end = |s: &Delegation| s.ended_at.unwrap_or(s.created_at);- // Grow from `d` to every delegation whose run overlaps the batch's span+ // Grow from `d` to every delegation whose run overlaps the batch's span, and to the results+ // that relayed work to a batch member or were relayed from one (they ran one after the other)let mut batch = vec![siblings.iter().find(|s| s.id == d.id)?.clone()];let (mut lo, mut hi) = (d.created_at, end(d));+ let linked = |s: &Delegation, batch: &[Delegation]| {+ batch.iter().any(|b| {+ s.relayed_from_delegation_id.as_deref() == Some(b.id.as_str()) || b.relayed_from_delegation_id.as_deref() == Some(s.id.as_str())+ })+ };loop {let more: Vec<Delegation> = siblings.iter()- .filter(|s| !batch.iter().any(|b| b.id == s.id) && s.created_at <= hi && end(s) >= lo)+ .filter(|s| !batch.iter().any(|b| b.id == s.id) && ((s.created_at <= hi && end(s) >= lo) || linked(s, &batch))).cloned().collect();if more.is_empty() {@@ -867,6 +949,12 @@ async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation], o_ => format!("({}: {})", b.status, b.error.as_deref().unwrap_or("no result")),};results.push_str(&format!("### {who}: “{}”\n{}\n", b.title, crate::drivers::peer_message(&who, &body)));+ if let Some(from) = b.relayed_from_delegation_id.as_ref().and_then(|id| batch.iter().find(|x| &x.id == id)) {+ results.push_str(&format!(+ "({who} got this task because {}'s result @mentioned it; you didn't send it yourself.)\n",+ name_of(state, &from.specialist_kwant_id).await+ ));+ }if let Some(q) = open_question(state, b).await {results.push_str(&format!("(Waiting: {who} asked the person “{}” in its thread and has no answer yet. Don't redo this task: tell the \@@ -1442,6 +1530,7 @@ pub async fn create_delegation(State(state): State<AppState>, Json(p): Json<Deleorigin_depth,allowed: None,after: None,+ relayed_from: None,};match start(&state, req).await {Ok(d) => (StatusCode::ACCEPTED, Json(d)).into_response(),@@ -1520,6 +1609,7 @@ pub async fn tool_delegate(state: &AppState, scope: &super::continuity::SelfScoporigin_depth: origin.depth,allowed: (!origin.member_ids.is_empty()).then(|| origin.member_ids.clone()),after: None,+ relayed_from: None,};match start(state, req).await {Ok(d) => (diff --git a/src/server/routes.rs b/src/server/routes.rsindex f6f060a7..3526e3ca 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -929,7 +929,7 @@ async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(}if let [(from, text)] = replies {if is_team_channel_lead(scope, from).await {- return delegate_mentions(scope, from, text, user_prompt, already_spoken, None).await;+ return delegate_mentions(scope, from, text, user_prompt, already_spoken, None, None).await;}}if scope.teammates.is_empty() {@@ -1125,6 +1125,8 @@ where}}+/// A teammate's result @mentioned one already in this chain of relays.+const RELAY_PING_PONG: &str = "it already worked on this chain of hand-offs, so a teammate's result can't hand it back. Ask the lead to send it";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";@@ -1191,6 +1193,21 @@ async fn is_team_channel_lead(scope: &TurnScope, kwant: &Kwant) -> bool {}}+/// A teammate's delegation result that @mentions other teammates: [`delegate_mentions`] hands+/// the work on for the lead, as if the lead had asked, and links each new task to `source` so the+/// lead hears every result in one batch.+pub(super) struct Relay<'a> {+ /// The teammate whose result it is.+ pub from: &'a Kwant,+ /// Its ended delegation.+ pub source: &'a crate::db::threads::Delegation,+ /// Teammates already in this chain of relays, `from` included: never handed the work back.+ pub chain: Vec<String>,+ /// Teammates the lead has working alongside it (open, or ran at the same time): the lead's one+ /// follow-up sees their results next to this one, so they aren't handed it again.+ pub alongside: Vec<String>,+}+/// 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@@ -1210,6 +1227,7 @@ pub(super) async fn delegate_mentions(user_prompt: &str,just_reported: &[String],resumed: Option<&[String]>,+ relay: Option<&Relay<'_>>,) {let Some(cid) = scope.channel_id.clone() else { return };let names: Vec<&str> = scope.teammates.iter().map(|k| k.name.as_str()).collect();@@ -1221,7 +1239,10 @@ pub(super) async fn delegate_mentions(.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) {+ // The lead hears a relayed result anyway, and a bot can't hand work to itself+ let speaker = relay.map_or(lead.id.as_str(), |r| r.from.id.as_str());+ let not_a_handoff = |id: &str| id == lead.id || id == speaker;+ if found.targets.iter().all(|&i| not_a_handoff(&scope.teammates[i].id)) {return report_skipped(scope, skipped).await;}let mine: Vec<_> = scope@@ -1249,10 +1270,18 @@ pub(super) async fn delegate_mentions(let mut capped: Vec<&Kwant> = Vec::new();for &i in &found.targets {let k = &scope.teammates[i];- if k.id == lead.id || targets.iter().any(|t| t.id == k.id) || resumed.is_some_and(|ids| !ids.contains(&k.id)) {+ if not_a_handoff(&k.id) || targets.iter().any(|t| t.id == k.id) || resumed.is_some_and(|ids| !ids.contains(&k.id)) {+ continue;+ }+ if relay.is_some() && crate::router::only_credited(text, &k.name) {+ // "As @SEO found, …" in a result asks nothing of SEOcontinue;}- if just_reported.contains(&k.id) && crate::router::only_credited(text, &k.name) {+ if relay.is_some_and(|r| r.chain.contains(&k.id)) {+ skipped.push((k.name.clone(), RELAY_PING_PONG.to_string()));+ } else if relay.is_some_and(|r| r.alongside.contains(&k.id)) {+ continue;+ } else if just_reported.contains(&k.id) && crate::router::only_credited(text, &k.name) {skipped.push((k.name.clone(), CREDIT_ONLY.to_string()));} else if open.contains(&k.id.as_str()) {skipped.push((k.name.clone(), "still working on an earlier task from this chat".to_string()));@@ -1274,12 +1303,28 @@ pub(super) async fn delegate_mentions(}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}",- lead = lead.name,- text = truncate_chars(text.trim(), 4000),- );- let title = truncate_chars(user.lines().find(|l| !l.trim().is_empty()).unwrap_or("Task").trim(), 80).to_string();+ let task = match relay {+ None => format!(+ "The user asked in the team channel:\n{user}\n\n{lead} mentioned you:\n{text}",+ lead = lead.name,+ text = truncate_chars(text.trim(), 4000),+ ),+ Some(r) => format!(+ "The user asked in the team channel:\n{user}\n\n{from} mentioned you in its result for {lead}'s task “{title}”. \+ Do what it asks of you; your result goes to {lead}.\n{text}",+ from = r.from.name,+ lead = lead.name,+ title = r.source.title,+ text = crate::drivers::peer_message(&r.from.name, truncate_chars(text.trim(), 4000)),+ ),+ };+ let first_line = |t: &str| truncate_chars(t.lines().find(|l| !l.trim().is_empty()).unwrap_or("Task").trim(), 80).to_string();+ let title = first_line(user);+ // A relayed task is named after what the result asked of that teammate+ let title_for = |k: &Kwant| match relay {+ Some(_) => mention_line(text, &k.name).map(|l| first_line(&l)).unwrap_or_else(|| title.clone()),+ None => title.clone(),+ };let allowed: Vec<String> = scope.teammates.iter().map(|k| k.id.clone()).collect();for (n, specialist) in targets.into_iter().enumerate() {if n >= MAX_HANDOFFS {@@ -1310,12 +1355,13 @@ pub(super) async fn delegate_mentions(lead: lead.clone(),specialist: specialist.clone(),task: task.clone(),- title: Some(handoff_title(text, &specialist.name).unwrap_or_else(|| title.clone())),+ title: Some(handoff_title(text, &specialist.name).unwrap_or_else(|| title_for(specialist))),origin: super::delegation::Origin { channel_id: Some(cid.clone()), ..Default::default() },continue_lead: true,origin_depth: scope.delegation_depth,allowed: Some(allowed.clone()),after,+ relayed_from: relay.map(|r| r.source.id.clone()),};match super::delegation::start(&scope.state, req).await {Ok(d) => {@@ -1361,6 +1407,14 @@ pub fn handoff_title(text: &str, name: &str) -> Option<String> {Some(truncate_chars(&title, 80).to_string())}+/// The first line of `text` that @mentions `name`, without its list marker, for a relayed task's title.+fn mention_line(text: &str, name: &str) -> Option<String> {+ let tag = format!("@{}", name.to_lowercase());+ text.lines().find(|l| l.to_lowercase().contains(&tag)).map(|l| {+ l.trim().trim_start_matches(['-', '*', '•', '>', ' ']).replace(['*', '`'], "").trim().to_string()+ })+}+/// 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)diff --git a/tests/delegation_test.rs b/tests/delegation_test.rsindex 33423a03..d96beae3 100644--- a/tests/delegation_test.rs+++ b/tests/delegation_test.rs@@ -1416,3 +1416,71 @@ async fn a_stop_resumes_the_lead_only_for_the_rest_of_its_batch() {let p = resumed().pop().unwrap();assert!(p.contains("answer keepme") && p.contains("It was stopped"), "{p}");}++/// Oleks (2026-10-29, "seems like not all mentions got notified"): QA's result said "@Frontend could+/// switch to …", the lead didn't relay it and Frontend never ran. A teammate's result now hands on+/// its own mentions of other teammates: Growth gets a task from Social's result, its title is the+/// line that asked, and the lead is resumed once with both results.+#[tokio::test]+async fn a_teammates_result_that_mentions_another_teammate_starts_its_task() {+ let env = setup().await;+ let social = add_bot(&env, "Social").await;+ let growth = add_bot(&env, "Growth").await;+ let channel = team_channel_with(&env, "relay", &[&env.lead, &social, &growth]).await;+ let first = delegate_from(&env, &channel, &social, "Draft the posts REPLYTAG:relayone MENTION:Growth", "Draft posts").await;+ // The link is written right after the task is created, before Growth runs+ wait_for("the relayed task", || async {+ env.state.db.list_delegations(Some(&env.lead), None, 50).await.unwrap().iter().any(|d| d.specialist_kwant_id == growth && d.relayed_from_delegation_id.is_some())+ })+ .await;+ let relayed = env.state.db.list_delegations(Some(&env.lead), None, 50).await.unwrap().into_iter().find(|d| d.specialist_kwant_id == growth).unwrap();+ assert_eq!(relayed.relayed_from_delegation_id.as_deref(), Some(first.as_str()));+ assert!(relayed.task.contains("Social mentioned you in its result"), "{}", relayed.task);+ assert!(relayed.title.contains("answer relayone"), "{}", relayed.title);+ wait_for("Growth's result", || async { delegation_status(&env, &relayed.id).await == "completed" }).await;+ wait_for("the lead's one follow-up", || async { !prompts_with("Growth got this task because Social's result").is_empty() }).await;+ tokio::time::sleep(Duration::from_millis(1000)).await;+ let resumes = prompts_with("Growth got this task because Social's result");+ assert_eq!(resumes.len(), 1, "the lead is resumed once with both results");+ assert!(resumes[0].contains("relayone"), "{}", resumes[0]);+ assert!(refusals(&channel_messages(&env, &channel).await).is_empty());+}++/// A relayed teammate whose result mentions a teammate earlier in the same chain is refused with a+/// notice instead of handing the work back and forth.+#[tokio::test]+async fn a_relayed_result_cannot_hand_work_back_up_its_chain() {+ let env = setup().await;+ let social = add_bot(&env, "Social").await;+ let growth = add_bot(&env, "Growth").await;+ let channel = team_channel_with(&env, "relay-pingpong", &[&env.lead, &social, &growth]).await;+ // Social's result mentions Growth; Growth's (it sees the same request) mentions Social back+ delegate_from(&env, &channel, &social, "Plan REPLYTAG:pp MENTION:Growth+Social", "Plan").await;+ wait_for("the ping-pong notice", || async { !refusals(&channel_messages(&env, &channel).await).is_empty() }).await;+ let refused = refusals(&channel_messages(&env, &channel).await);+ assert!(refused.iter().any(|r| r.contains("Social") && r.contains("already worked on this chain")), "{refused:?}");+ let ds = env.state.db.list_delegations(Some(&env.lead), None, 50).await.unwrap();+ assert_eq!(ds.iter().filter(|d| d.specialist_kwant_id == social && d.relayed_from_delegation_id.is_some()).count(), 0);+ assert_eq!(ds.iter().filter(|d| d.specialist_kwant_id == growth).count(), 1);+}++/// A result's mention of a teammate already asked up to the per-teammate cap leaves the Continue+/// notice, like the lead's own mentions.+#[tokio::test]+async fn a_relayed_mention_past_the_cap_waits_for_continue() {+ let env = setup().await;+ let lead = name(&env, &env.lead).await;+ let social = add_bot(&env, "Social").await;+ let growth = add_bot(&env, "Growth").await;+ let channel = team_channel_with(&env, "relay-cap", &[&env.lead, &social, &growth]).await;+ say_in(&env, &channel, &format!("@{lead} Plan the launch REPLYTAG:capplan")).await;+ wait_for("the lead's reply", || async { channel_messages(&env, &channel).await.iter().any(|m| m.text.contains("answer capplan")) }).await;+ seed_rounds(&env, &channel, &growth, per_bot_limit()).await;+ let d = delegate_from(&env, &channel, &social, "Review REPLYTAG:capped MENTION:Growth", "Review").await;+ wait_for("the review", || async { delegation_status(&env, &d).await == "completed" }).await;+ wait_for("the per-teammate notice", || async { !capped(&channel_messages(&env, &channel).await).is_empty() }).await;+ let notices = capped(&channel_messages(&env, &channel).await);+ assert!(notices[0].text.contains("Growth not sent yet"), "{}", notices[0].text);+ let to_growth = env.state.db.list_delegations(Some(&env.lead), None, 50).await.unwrap().iter().filter(|d| d.specialist_kwant_id == growth).count();+ assert_eq!(to_growth, per_bot_limit(), "nothing past the cap until Continue");+}