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.

Decisions: channel replies get choice chips, never a raw [DECISIONS] block (#139)

Lin (kwant bot)e5169df0cdcf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 85b9b95c..d705b4b8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -59,6 +59,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- **No raw `[DECISIONS]` text in older channel replies.** Replies saved in a team channel could end with
the bot's raw `[DECISIONS] … [/DECISIONS]` block. The chat now hides it and shows its choices as
read-only chips (a line it can't read is dropped, never shown); a block being typed live is hidden too.
+- **Choices in channels show as chips, not raw text.** A bot's `[DECISIONS] …` block in a team
+ discussion or a "While you were away" post now becomes choice chips you can change, as in direct
+ chats. A garbled block (two choices on one line, no closing tag, in a code fence) is removed, never shown.
- **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/server/decide.rs b/src/server/decide.rs
index 026712cc..98436c5b 100644
--- a/src/server/decide.rs
+++ b/src/server/decide.rs
@@ -431,20 +431,44 @@ fn parse_line(line: &str) -> Option<(String, Vec<String>, String, String)> {
Some((question, options, picked, why))
}
+/// A line split where another `question:` starts mid-line, so two choices run together on one
+/// line still parse as two.
+fn entries(line: &str) -> Vec<&str> {
+ let lower = line.to_ascii_lowercase();
+ let mut cuts: Vec<usize> = lower
+ .match_indices("question:")
+ .map(|(i, _)| i)
+ .filter(|&i| i > 0 && lower[..i].ends_with(|c: char| c.is_whitespace() || c == '|'))
+ .collect();
+ cuts.insert(0, 0);
+ cuts.push(line.len());
+ cuts.windows(2).map(|w| &line[w[0]..w[1]]).collect()
+}
+
+/// Whether a line is only markdown wrapping the block: a code fence or bold/italic marks.
+fn wrapper_line(line: &str) -> bool {
+ let t = line.trim();
+ !t.is_empty() && (t.starts_with("```") || t.chars().all(|c| matches!(c, '*' | '_' | '`')))
+}
+
/// Takes a `[DECISIONS] … [/DECISIONS]` block off the end of a reply: the reply without it, and
/// its valid lines (`question: … | options: A; B | picked: B | why: …`). A reply without the
-/// block comes back as it was.
+/// block comes back as it was. The whole block always comes off, even when none of its lines
+/// parse, the closing tag is missing, the tags are lowercase or it sits in a code fence.
pub fn take_decisions(text: &str) -> (String, Vec<Decision>) {
- let Some(start) = text.rfind(OPEN) else {
+ // ASCII lowercasing keeps byte offsets, so they index `text` too
+ let lower = text.to_ascii_lowercase();
+ let Some(start) = lower.rfind(&OPEN.to_ascii_lowercase()) else {
return (text.to_string(), Vec::new());
};
let body_start = start + OPEN.len();
- let (body, rest) = match text[body_start..].find(CLOSE) {
+ let (body, rest) = match lower[body_start..].find(&CLOSE.to_ascii_lowercase()) {
Some(end) => (&text[body_start..body_start + end], &text[body_start + end + CLOSE.len()..]),
None => (&text[body_start..], ""),
};
let decisions = body
.lines()
+ .flat_map(entries)
.filter_map(parse_line)
.take(MAX_DECISIONS)
.enumerate()
@@ -458,8 +482,19 @@ pub fn take_decisions(text: &str) -> (String, Vec<Decision>) {
changed_to: None,
})
.collect();
- let stripped = format!("{}{}", text[..start].trim_end(), if rest.trim().is_empty() { "" } else { "\n\n" });
- (format!("{stripped}{}", rest.trim()).trim_end().to_string(), decisions)
+ let mut before = text[..start].trim_end();
+ let (head, last) = before.rsplit_once('\n').unwrap_or(("", before));
+ if wrapper_line(last) {
+ before = head.trim_end();
+ }
+ let mut after = rest.trim_start();
+ let (first, tail) = after.split_once('\n').unwrap_or((after, ""));
+ if wrapper_line(first) {
+ after = tail;
+ }
+ let after = after.trim();
+ let sep = if before.is_empty() || after.is_empty() { "" } else { "\n\n" };
+ (format!("{before}{sep}{after}").trim().to_string(), decisions)
}
/// `meta` with `decisions` set (when there are any).
@@ -1005,6 +1040,38 @@ mod tests {
assert_eq!(take_decisions("no block").0, "no block");
}
+ #[test]
+ fn a_garbled_decisions_block_still_comes_off_whole() {
+ // The screenshot: the block starts on the tag's line and two choices run together
+ let text = "Leave by 07:47.\n\n[DECISIONS] question: Arrival buffer | options: 5 min; 10 min; 15 min | picked: 10 min | \
+ why: time to park question: Traffic | options: Run Maps anyway; One-line note | picked: One-line note | why: noise [/DECISIONS]";
+ let (stripped, ds) = take_decisions(text);
+ assert_eq!(stripped, "Leave by 07:47.");
+ assert_eq!(ds.iter().map(|d| (d.question.as_str(), d.picked.as_str(), d.why.as_str())).collect::<Vec<_>>(), [
+ ("Arrival buffer", "10 min", "time to park"),
+ ("Traffic", "One-line note", "noise")
+ ]);
+ assert_eq!((ds[0].index, ds[1].index), (0, 1));
+
+ // Nothing parses, lowercase tags, no closing tag: still no raw text
+ for text in [
+ "Done.\n\n[DECISIONS]\nI picked the blue one because it reads best\n[/DECISIONS]",
+ "Done.\n[decisions]\nquestion: x | options: only | picked: only\n[/decisions]",
+ "Done.\n\n[DECISIONS]\nquestion: Which? | options: A; B | picked: A | why: cut off mid",
+ "Done.\n\n```\n[DECISIONS]\nquestion: Which? | options: A; B | picked: C\n[/DECISIONS]\n```",
+ "Done.\n\n**[DECISIONS]**\nquestion: Which? | options: A; B | picked: Z\n**[/DECISIONS]**",
+ ] {
+ let (stripped, _) = take_decisions(text);
+ assert_eq!(stripped, "Done.", "{text}");
+ }
+ // Text after the block stays, and a "question:" inside other words isn't a cut
+ let (stripped, ds) =
+ take_decisions("Before.\n[DECISIONS]\nquestion: Q? | options: A; B | picked: B | why: the subquestion: none\n[/DECISIONS]\nAfter.");
+ assert_eq!(stripped, "Before.\n\nAfter.");
+ assert_eq!(ds[0].why, "the subquestion: none");
+ assert_eq!(take_decisions("[DECISIONS]\n[/DECISIONS]").0, "");
+ }
+
#[test]
fn the_change_prompt_names_the_bot_in_channels() {
let d = Decision {
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 72c41792..ef197c27 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -2486,11 +2486,9 @@ async fn run_kwant_turn_inner(
},
};
if let Some((text, reasoning_content)) = saved {
- // A reply's own choices come off its text into meta.decisions
- let (text, decisions) = match opts.discussion {
- None => super::decide::take_decisions(&text),
- Some(_) => (text, Vec::new()),
- };
+ // A reply's own choices come off its text into meta.decisions, in channel rounds too
+ // (a discussion's raw reply still goes back to the round, which reads its markers)
+ let (text, decisions) = super::decide::take_decisions(&text);
if opts.discussion.is_none() {
reply_text = text.clone();
}
diff --git a/src/server/work_ahead.rs b/src/server/work_ahead.rs
index c539db15..bb0a91b5 100644
--- a/src/server/work_ahead.rs
+++ b/src/server/work_ahead.rs
@@ -194,12 +194,18 @@ pub async fn run(state: &AppState, c: Candidate, row: WorkAheadRun) -> Option<Me
let _ = state.db.finish_work_ahead_run(&row.id, "failed", None, tokens).await;
return None;
};
+ // The post's own choices come off its text into meta.decisions, as in any other reply
+ let (reply, decisions) = super::decide::take_decisions(&reply);
let Some(text) = message_text(&reply) else {
let _ = state.db.finish_work_ahead_run(&row.id, "nothing", None, tokens).await;
return None;
};
let meta = json!({"kind": "work_ahead", "date": day, "run_id": row.id});
- let saved = scope.save(&scope.message("kwant", &c.lead.name, text), Some(meta)).await;
+ let meta = super::decide::with_decisions(Some(meta), &decisions);
+ let saved = scope.save(&scope.message("kwant", &c.lead.name, text), meta).await;
+ if let (Some(m), false) = (&saved, decisions.is_empty()) {
+ super::decide::note_bot_decisions(state, &c.lead, m).await;
+ }
let _ = state.db.finish_work_ahead_run(&row.id, if saved.is_some() { "posted" } else { "failed" }, saved.as_ref().map(|m| m.id.as_str()), tokens).await;
let saved = saved?;
let place = (scope.channel_id.clone(), scope.kwant_id.clone(), scope.thread_id.clone());
diff --git a/tests/channel_decisions_test.rs b/tests/channel_decisions_test.rs
new file mode 100644
index 00000000..d1d7cee0
--- /dev/null
+++ b/tests/channel_decisions_test.rs
@@ -0,0 +1,165 @@
+//! A bot's `[DECISIONS]` block in a team channel comes off the saved text into `meta.decisions`
+//! (choice chips), as in direct chats, and a garbled block is never shown raw. A fake claude CLI
+//! answers by keyword. 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;
+
+/// - the opening of a team discussion: a reply with a well-formed block;
+/// - a reply in the discussion: the screenshot's block, two choices run together on one line and
+/// a line that doesn't parse, lowercase tags, no closing tag;
+/// - the wrap-up: a plain summary;
+/// - anything else: "answer".
+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='Go with a blue-green cutover. @Bob what do you think?\n\n[DECISIONS]\nquestion: Cutover style? | options: Blue-green; Rolling | picked: Blue-green | why: instant rollback\n[/DECISIONS]' ;;
+ *"Wrap up the team discussion"*) out='Summary: blue-green, 10 minute buffer.' ;;
+ *"Team discussion in"*)
+ out='Agreed, with a buffer.\n\n[decisions] question: Arrival buffer | options: 5 min; 10 min; 15 min | picked: 10 min | why: time to park question: Traffic on days off | options: Run Maps anyway; One-line note | picked: One-line note | why: noise\nthis line is not a decision' ;;
+ *) 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\":90}}"
+"#;
+
+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();
+ 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("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));
+ bin
+ });
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, 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();
+ (s, serde_json::from_slice(&bytes).unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into())))
+}
+
+async fn ok(app: &Router, method: &str, uri: &str, body: Option<Value>) -> Value {
+ let (s, v) = call(app, method, uri, body).await;
+ assert!(s.is_success(), "{method} {uri}: {s} {v}");
+ v
+}
+
+fn meta(m: &Message) -> Value {
+ m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null)
+}
+
+#[tokio::test]
+async fn a_team_discussion_reply_keeps_its_choices_as_chips_not_text() {
+ 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 team = ok(&app, "POST", "/api/teams", Some(json!({"name": "infra", "lead_kwant_id": ann, "member_kwants": [ann, bob]}))).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 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}");
+
+ // Opening, Bob's reply and the wrap-up
+ let mut replies = Vec::new();
+ for _ in 0..300 {
+ replies = state.db.list_messages(&channel, 100).await.unwrap().into_iter().filter(|m| m.sender_role == "kwant").collect();
+ if replies.iter().any(|m| m.text.starts_with("Summary:")) {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ let texts: Vec<_> = replies.iter().map(|m| (&m.sender_id, &m.text)).collect();
+ assert!(replies.len() >= 3, "{texts:#?}");
+ for m in &replies {
+ assert!(!m.text.to_lowercase().contains("decisions]"), "raw block shown: {}", m.text);
+ assert!(!m.text.contains("question:") && !m.text.contains("picked:"), "raw block shown: {}", m.text);
+ }
+
+ let opening = replies.iter().find(|m| m.text.starts_with("Go with a blue-green")).expect("the opening");
+ assert_eq!(opening.text, "Go with a blue-green cutover. @Bob what do you think?");
+ let d = &meta(opening)["decisions"];
+ assert_eq!(d.as_array().map(Vec::len), Some(1), "{d}");
+ assert_eq!((d[0]["question"].as_str(), d[0]["picked"].as_str()), (Some("Cutover style?"), Some("Blue-green")));
+
+ // The garbled block: both run-together choices come through and nothing of it is shown
+ let reply = replies.iter().find(|m| m.text.starts_with("Agreed")).expect("Bob's reply");
+ assert_eq!(reply.text, "Agreed, with a buffer.");
+ let d = &meta(reply)["decisions"];
+ assert_eq!(d.as_array().map(Vec::len), Some(2), "{d}");
+ assert_eq!((d[0]["question"].as_str(), d[0]["picked"].as_str(), d[0]["why"].as_str()), (Some("Arrival buffer"), Some("10 min"), Some("time to park")));
+ assert_eq!((d[1]["question"].as_str(), d[1]["picked"].as_str()), (Some("Traffic on days off"), Some("One-line note")));
+
+ // The chips' Change works on a channel message and names the bot that decided
+ let (s, v) = call(&app, "POST", &format!("/api/messages/{}/decisions/0/change", reply.id), Some(json!({"picked": "15 min"}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert!(v["prompt"].as_str().unwrap().starts_with(&format!("@{} Change of decision", reply.sender_id)), "{v}");
+ let after = state.db.get_message(&reply.id).await.unwrap().unwrap();
+ assert_eq!(meta(&after)["decisions"][0]["changed_to"], "15 min");
+}
diff --git a/tests/work_ahead_test.rs b/tests/work_ahead_test.rs
index f5ebfee5..2c39e5b4 100644
--- a/tests/work_ahead_test.rs
+++ b/tests/work_ahead_test.rs
@@ -25,6 +25,7 @@ use std::time::Duration;
use tower::ServiceExt;
/// - a work-ahead run in a chat that says QUIETNOTHING: `[NOTHING]`;
+/// - one that says QUIETDECIDE: a report ending in a `[DECISIONS]` block on one line;
/// - any other work-ahead run: a short report with a prediction;
/// - anything else: "answer".
const FAKE_CLAUDE: &str = r#"#!/bin/sh
@@ -36,6 +37,7 @@ case "$last" in
*"[Work ahead]"*)
case "$last" in
*QUIETNOTHING*) out='[NOTHING]' ;;
+ *QUIETDECIDE*) out='I updated the daily overview with a leave-by line.\n\n[DECISIONS] question: Arrival buffer | options: 5 min; 10 min; 15 min | picked: 10 min | why: time to park question: Traffic on days off | options: Run Maps anyway; One-line note | picked: One-line note | why: noise [/DECISIONS]' ;;
*) out='While you were away I ran the pricing page link check: all 14 links work.\nNext I expect you will want the press note draft.' ;;
esac ;;
*) out="answer" ;;
@@ -197,6 +199,21 @@ async fn a_quiet_chat_gets_one_run_and_one_message_with_a_prediction() {
assert_eq!(env.work_ahead_in(&env.channel).await.len(), 1);
}
+#[tokio::test]
+async fn a_work_ahead_post_keeps_its_choices_as_chips_not_text() {
+ let env = setup().await;
+ env.quiet_channel("Plan the school run. QUIETDECIDE").await;
+ assert_eq!(env.run_now().await.len(), 1);
+ env.settle().await;
+ let posted = env.work_ahead_in(&env.channel).await;
+ assert_eq!(posted.len(), 1);
+ assert_eq!(posted[0].text, "I updated the daily overview with a leave-by line.");
+ let d = &meta(&posted[0])["decisions"];
+ assert_eq!(d.as_array().map(Vec::len), Some(2), "{d}");
+ assert_eq!((d[0]["picked"].as_str(), d[1]["picked"].as_str()), (Some("10 min"), Some("One-line note")));
+ assert_eq!(meta(&posted[0])["kind"], "work_ahead");
+}
+
#[tokio::test]
async fn nothing_worth_doing_posts_nothing_and_isnt_retried_today() {
let env = setup().await;