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.

Discussions: an @mentioned teammate goes next (audit #4) (#573)

Oleksandr Ivanchenkoafa77fc2d6a8
diff --git a/src/server/discussion.rs b/src/server/discussion.rs
index ddeb1e3a..b6be03e2 100644
--- a/src/server/discussion.rs
+++ b/src/server/discussion.rs
@@ -21,6 +21,38 @@ pub const MAX_TURNS: usize = 5;
/// How often one kwant may speak in a discussion (a reply when a teammate @mentions them back).
pub const MAX_TURNS_PER_KWANT: usize = 2;
+/// Puts the teammates the speaker just @mentioned at the front of the discussion `queue`, in
+/// mention order, each marked as asked by the speaker: "@Ben, get the prices" means Ben goes
+/// next, before any planned reactor. A mentioned teammate already in the queue (a planned
+/// reactor or an earlier mention) moves to the front instead of keeping its late place. The
+/// speaker itself, a teammate mentioned twice, and one who already spoke
+/// [`MAX_TURNS_PER_KWANT`] times (`spoke`, by id) are left out. The queue never grows past one
+/// entry per mentioned teammate; [`MAX_TURNS`] still ends the discussion.
+pub fn put_mentions_first<K: Clone>(
+ queue: &mut std::collections::VecDeque<(K, Option<String>)>,
+ mentioned: &[K],
+ id_of: impl Fn(&K) -> &str,
+ speaker_id: &str,
+ speaker_name: &str,
+ spoke: &std::collections::HashMap<String, usize>,
+) {
+ let mut front: Vec<(K, Option<String>)> = Vec::new();
+ for k in mentioned {
+ let id = id_of(k);
+ if id == speaker_id
+ || spoke.get(id).copied().unwrap_or(0) >= MAX_TURNS_PER_KWANT
+ || front.iter().any(|(f, _)| id_of(f) == id)
+ {
+ continue;
+ }
+ queue.retain(|(q, _)| id_of(q) != id);
+ front.push((k.clone(), Some(speaker_name.to_string())));
+ }
+ for entry in front.into_iter().rev() {
+ queue.push_front(entry);
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Reply {
Speak(String),
@@ -57,7 +89,7 @@ pub fn opening_prompt(user_prompt: &str, team: &str, responders: &[String]) -> S
"You'll then wrap up with a short summary.".to_string()
} else {
format!(
- "{} will react to your points next (they get the turn automatically, so don't @mention them), then you'll wrap up with a short summary.",
+ "{} will react to your points next (they get the turn anyway; @mention one of them only to hand that teammate a specific task, which makes them go first), then you'll wrap up with a short summary.",
responders.join(" and ")
)
};
@@ -147,6 +179,59 @@ mod tests {
assert!(!summary.contains("only if decisions remain for the user"), "{summary}");
}
+ use std::collections::{HashMap, VecDeque};
+
+ /// The queue after `speaker` (Ann) mentions `mentioned`, as "name<-asked_by" (or just "name").
+ fn reorder(queue: &[(&str, Option<&str>)], mentioned: &[&str], spoke: &[(&str, usize)]) -> Vec<String> {
+ let mut q: VecDeque<(String, Option<String>)> =
+ queue.iter().map(|(n, a)| (n.to_string(), a.map(str::to_string))).collect();
+ let mentioned: Vec<String> = mentioned.iter().map(|s| s.to_string()).collect();
+ let spoke: HashMap<String, usize> = spoke.iter().map(|(n, c)| (n.to_string(), *c)).collect();
+ put_mentions_first(&mut q, &mentioned, |k| k.as_str(), "Ann", "Ann", &spoke);
+ q.into_iter().map(|(n, a)| a.map_or(n.clone(), |a| format!("{n}<-{a}"))).collect()
+ }
+
+ #[test]
+ fn a_mentioned_teammate_who_was_not_planned_goes_next() {
+ // Ann opened; Cody is the planned reactor; Ann asks Ben for the prices.
+ assert_eq!(reorder(&[("Cody", None)], &["Ben"], &[("Ann", 1)]), ["Ben<-Ann", "Cody"]);
+ }
+
+ #[test]
+ fn a_mentioned_planned_reactor_moves_ahead_of_the_others_and_is_asked_by_the_speaker() {
+ assert_eq!(reorder(&[("Ben", None), ("Cody", None)], &["Cody"], &[("Ann", 1)]), ["Cody<-Ann", "Ben"]);
+ // Never queued twice
+ let after = reorder(&[("Ben", None), ("Cody", None), ("Dana", Some("Ben"))], &["Dana"], &[]);
+ assert_eq!(after, ["Dana<-Ann", "Ben", "Cody"]);
+ }
+
+ #[test]
+ fn two_mentions_keep_mention_order_ahead_of_the_queue() {
+ assert_eq!(reorder(&[("Ben", None)], &["Dana", "Cody"], &[]), ["Dana<-Ann", "Cody<-Ann", "Ben"]);
+ assert_eq!(reorder(&[("Cody", None), ("Dana", None)], &["Dana", "Cody", "Dana"], &[]), ["Dana<-Ann", "Cody<-Ann"]);
+ }
+
+ #[test]
+ fn a_teammate_out_of_turns_or_the_speaker_is_not_requeued() {
+ let out = MAX_TURNS_PER_KWANT;
+ // Ben already spoke his share: nothing changes, not even his planned place (he has none).
+ assert_eq!(reorder(&[("Cody", None)], &["Ben"], &[("Ben", out)]), ["Cody"]);
+ // A mention of the speaker hands nothing on.
+ assert_eq!(reorder(&[("Cody", None)], &["Ann"], &[]), ["Cody"]);
+ // One under the cap still goes next.
+ assert_eq!(reorder(&[("Cody", None)], &["Ben"], &[("Ben", out - 1)]), ["Ben<-Ann", "Cody"]);
+ // No mentions: the planned order stands.
+ assert_eq!(reorder(&[("Ben", None), ("Cody", None)], &[], &[]), ["Ben", "Cody"]);
+ }
+
+ #[test]
+ fn the_opening_lets_the_lead_hand_a_planned_reactor_a_task() {
+ let open = opening_prompt("Plan the launch", "core", &["Ben".into(), "Cody".into()]);
+ assert!(!open.contains("don't @mention"), "{open}");
+ assert!(open.contains("Ben and Cody will react to your points next"), "{open}");
+ assert!(open.contains("@mention one of them only to hand that teammate a specific task, which makes them go first"), "{open}");
+ }
+
#[test]
fn labels_share_prefixes_the_ui_groups_on() {
assert!(turn_label(2, "core").starts_with(TURN_LABEL));
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 32b81b86..2565727f 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1949,16 +1949,12 @@ async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, use
if !contributors.contains(&kwant.name) {
contributors.push(kwant.name.clone());
}
- for i in crate::router::handoff_targets(&text, &names) {
- let k = &scope.teammates[i];
- let turns_taken = spoke.get(&k.id).copied().unwrap_or(0);
- if k.id != kwant.id
- && turns_taken < discussion::MAX_TURNS_PER_KWANT
- && !queue.iter().any(|(q, _)| q.id == k.id)
- {
- queue.push_back((k.clone(), Some(kwant.name.clone())));
- }
- }
+ // Whoever was @mentioned goes next, in mention order, ahead of the planned reactors.
+ let mentioned: Vec<Kwant> = crate::router::handoff_targets(&text, &names)
+ .into_iter()
+ .map(|i| scope.teammates[i].clone())
+ .collect();
+ discussion::put_mentions_first(&mut queue, &mentioned, |k| k.id.as_str(), &kwant.id, &kwant.name, &spoke);
previous = Some(kwant.clone());
}
}
diff --git a/tests/discussion_mention_order_test.rs b/tests/discussion_mention_order_test.rs
new file mode 100644
index 00000000..db3bca1e
--- /dev/null
+++ b/tests/discussion_mention_order_test.rs
@@ -0,0 +1,180 @@
+//! In a team discussion, the teammate the speaker @mentions goes next, before the planned
+//! reactors (Mira's UX audit #4). A 3-bot team runs a real discussion through the server on a
+//! fake claude CLI: Ann leads, Bob and Cody are the planned reactors, and Ann's opening asks
+//! @Cody for the data. Cody must speak second, answering Ann, then Bob, then Ann's summary.
+//! Its own test binary: it changes PATH.
+
+#[path = "common/exe.rs"]
+mod exe;
+
+use axum::{
+ body::{to_bytes, Body},
+ http::Request,
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::Database,
+ drivers::events::RuntimeEvent,
+ 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;
+
+/// - the opening: asks @Cody for the numbers;
+/// - a teammate the speaker asked directly: hands over the data;
+/// - any other reply: reacts;
+/// - the wrap-up: a plain summary.
+const FAKE_CLAUDE: &str = r#"#!/bin/sh
+case "$1" in
+ auth) echo '{"loggedIn":true}'; exit 0 ;;
+esac
+for a; do last="$a"; done
+case "$last" in
+ *"opening a team discussion"*) out='Blue-green cutover. @Cody please get the current table sizes first.' ;;
+ *"Wrap up the team discussion"*) out='Summary: blue-green, sized from the table numbers.' ;;
+ *"asked you directly"*) out='Here are the table sizes: orders 40 GB, users 2 GB.' ;;
+ *"Team discussion in"*) out='Reacting: add a rollback window.' ;;
+ *) out="answer" ;;
+esac
+printf '%s\n' "{\"type\":\"result\",\"is_error\":false,\"num_turns\":1,\"result\":\"$out\",\"usage\":{\"input_tokens\":10,\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0,\"output_tokens\":20}}"
+"#;
+
+fn fake_cli() {
+ static DONE: OnceLock<PathBuf> = OnceLock::new();
+ DONE.get_or_init(|| {
+ let bin = tempfile::tempdir().unwrap().keep().join("bin");
+ std::fs::create_dir_all(&bin).unwrap();
+ exe::write_executable(bin.join("claude"), FAKE_CLAUDE);
+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));
+ bin
+ });
+}
+
+async fn ok(app: &Router, method: &str, uri: &str, body: Option<Value>) -> Value {
+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ let body = body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let s = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ let v = serde_json::from_slice(&bytes).unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into()));
+ assert!(s.is_success(), "{method} {uri}: {s} {v}");
+ v
+}
+
+#[tokio::test]
+async fn the_teammate_the_lead_mentions_speaks_before_the_planned_reactors() {
+ fake_cli();
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config {
+ data_dir: tmp.path().to_path_buf(),
+ 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(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ let app = create_router(state.clone());
+ let bot = |name: &str| {
+ json!({"name": name, "title": format!("{name} the engineer"), "persona_prompt": "Test persona",
+ "avatar_sprite": "s", "driver_type": "cli", "preferred_model": "claude"})
+ };
+ let ann = ok(&app, "POST", "/api/kwants", Some(bot("Ann"))).await["id"].as_str().unwrap().to_string();
+ let bob = ok(&app, "POST", "/api/kwants", Some(bot("Bob"))).await["id"].as_str().unwrap().to_string();
+ let cody = ok(&app, "POST", "/api/kwants", Some(bot("Cody"))).await["id"].as_str().unwrap().to_string();
+ let team = ok(
+ &app,
+ "POST",
+ "/api/teams",
+ Some(json!({"name": "infra", "lead_kwant_id": ann, "member_kwants": [ann, bob, cody]})),
+ )
+ .await;
+ let channels = ok(&app, "GET", "/api/channels", None).await;
+ let channel = channels
+ .as_array()
+ .or_else(|| channels["channels"].as_array())
+ .unwrap()
+ .iter()
+ .find(|c| c["name"] == "team-infra")
+ .expect("the team's chat")["id"]
+ .as_str()
+ .unwrap()
+ .to_string();
+
+ let mut events = state.event_sender.subscribe();
+ let sent = ok(
+ &app,
+ "POST",
+ "/api/chat/send",
+ Some(json!({"channel_id": channel, "team_id": team["id"], "sender_id": "user",
+ "prompt": "How should we design the zero-downtime database migration architecture? Weigh the tradeoff."})),
+ )
+ .await;
+ assert_eq!(sent["status"], "dispatched", "{sent}");
+
+ // Every turn as the server announced it, until the discussion completes
+ let mut planned: Vec<String> = Vec::new();
+ let mut turns: Vec<String> = Vec::new();
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(60);
+ loop {
+ let event = tokio::time::timeout_at(deadline, events.recv()).await.expect("discussion completes").unwrap();
+ match event {
+ RuntimeEvent::DiscussionStarted { speakers, .. } => {
+ let name = |id: &String| [(&ann, "Ann"), (&bob, "Bob"), (&cody, "Cody")].iter().find(|(i, _)| *i == id).unwrap().1;
+ planned = speakers.iter().map(|id| name(id).to_string()).collect();
+ }
+ RuntimeEvent::DiscussionTurnStarted { speaker_name, turn_index, total_turns, asked_by, phase, .. } => {
+ turns.push(format!(
+ "{turn_index}/{total_turns} {speaker_name} ({}){}",
+ phase.unwrap_or_default(),
+ asked_by.map(|a| format!(" asked by {a}")).unwrap_or_default()
+ ));
+ }
+ RuntimeEvent::DiscussionCompleted { .. } => break,
+ _ => {}
+ }
+ }
+ println!("planned: {planned:?}\nturns:\n {}", turns.join("\n "));
+
+ let messages = state.db.list_messages(&channel, 100).await.unwrap();
+ let order: Vec<(&str, &str)> = messages
+ .iter()
+ .filter(|m| m.sender_role == "kwant")
+ // A bot's message is saved under its name; map an id too, in case that changes
+ .map(|m| {
+ let who = [(&ann, "Ann"), (&bob, "Bob"), (&cody, "Cody")]
+ .iter()
+ .find(|(id, name)| m.sender_id == **id || m.sender_id == *name)
+ .map_or(m.sender_id.as_str(), |&(_, name)| name);
+ (who, m.text.as_str())
+ })
+ .collect();
+ println!("chat:\n {}", order.iter().map(|(w, t)| format!("{w}: {t}")).collect::<Vec<_>>().join("\n "));
+
+ assert_eq!(planned, ["Ann", "Bob", "Cody"], "the router plans Ann, then Bob and Cody");
+ assert_eq!(
+ turns,
+ [
+ "1/4 Ann (open)",
+ "2/4 Cody (reply) asked by Ann",
+ "3/4 Bob (reply)",
+ "4/4 Ann (summary)",
+ ],
+ "Cody, whom Ann asked, goes before Bob"
+ );
+ let who: Vec<&str> = order.iter().map(|(w, _)| *w).collect();
+ assert_eq!(who, ["Ann", "Cody", "Bob", "Ann"], "{order:#?}");
+ assert!(order[1].1.starts_with("Here are the table sizes"), "Cody answers Ann: {order:#?}");
+}