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
0.8.1 F1: a delivery counts the pictures any of its turns shared (#482)
Oleksandr Ivanchenko0153efe0b3bc
diff --git a/src/server/decide.rs b/src/server/decide.rsindex a9e470f7..eb00f0df 100644--- a/src/server/decide.rs+++ b/src/server/decide.rs@@ -87,6 +87,8 @@ pub struct Held {/// The held turn's slot for the delivery check's one continuation: the decided reply, checked/// against [`Held::delivery`], fills it when it misses what the person expected.pub delivery_next: Option<super::routes::DeliveryNext>,+ /// What the held turn's delivery did so far (an image it shared counts for the decided reply).+ pub delivery_seen: Option<super::routes::DeliverySeen>,}/// Shared with a turn's save step (see [`TurnOpts`]): whether to hold a reply with open choices,@@ -776,6 +778,7 @@ pub(super) async fn decide(scope: &TurnScope, kwant: &Kwant, mut held: Held) ->// The decided reply is the one the person sees: it delivers what their message asked foropts.delivery = held.delivery.clone();opts.delivery_next = held.delivery_next.clone();+ opts.delivery_seen = held.delivery_seen.clone();let mut extra = json!({"decide_first": {"consulted": consulted, "held_turn_id": held.turn_id, "kwant_id": kwant.id}});// The decided reply answers the same routed message: it keeps the routing line and "Wrong bot?"if let Some(routing) = held.meta.as_ref().map(|m| &m["routing"]).filter(|r| !r.is_null()) {diff --git a/src/server/delivery_check.rs b/src/server/delivery_check.rsindex 21a12427..0a91ce41 100644--- a/src/server/delivery_check.rs+++ b/src/server/delivery_check.rs@@ -52,6 +52,17 @@ pub struct Seen {pub pushed: bool,}+impl Seen {+ /// This turn's `self` counted with what its delivery's earlier turns did (`so_far`, which it+ /// then joins): an image shared or a push made by any turn of the delivery counts (0.8.1 F1).+ /// `has_shot` stays this turn's own: only its own screenshot can be shared under its reply.+ pub fn with_earlier(self, so_far: &mut Seen) -> Seen {+ so_far.image_shared |= self.image_shared;+ so_far.pushed |= self.pushed;+ Seen { image_shared: so_far.image_shared, has_shot: self.has_shot, pushed: so_far.pushed }+ }+}+/// Something the person expected that the turn didn't deliver.#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]#[serde(rename_all = "snake_case")]@@ -631,4 +642,54 @@ mod tests {assert!(!Expect::from_plan(&lean).unwrap().firm);assert!(Expect::from_plan(&plan(Deliverable::Visual, &[Show::Image], &[])).unwrap().firm);}++ /// 0.8.1 F1 (Rigel's 0.8.0 final QA): a visible change whose first turn shared the screenshot+ /// but gave no PR link. Its continuation only adds the link; counted per turn it asked for the+ /// picture again and ended with the no-picture line. Counted per delivery it doesn't.+ #[test]+ fn a_continuation_counts_the_picture_its_first_turn_shared() {+ let visible = Expect { image: true, link: true, done_when: vec![], firm: true };+ let mut delivery = Seen::default();+ let first = SHARED.with_earlier(&mut delivery);+ let v1 = check("I changed the footer; here is the screenshot.", Some(&visible), false, &first);+ assert_eq!(v1.missing, vec![Missing::Link], "{v1:?}");+ let prompt = v1.continue_with.clone().expect("a missing link continues");+ assert!(prompt.contains("a PR or branch link") && !prompt.contains("an image"), "{prompt}");++ // The continuation shares nothing new and adds the link+ let reply = "Pushed: https://github.com/o/r/pull/12";+ let then = NOTHING.with_earlier(&mut delivery);+ let v2 = check(reply, Some(&visible), true, &then);+ assert!(v2.missing.is_empty() && !v2.no_picture_line && !v2.share_last_shot, "{v2:?}");+ assert_eq!(v2.outcome, Some(Outcome::Hit));+ assert!(!apply(reply.into(), &v2).contains(NO_PICTURE_LINE));++ // What the bug did: the continuation's own pictures only+ let per_turn = check(reply, Some(&visible), true, &NOTHING);+ assert_eq!(per_turn.missing, vec![Missing::Image], "{per_turn:?}");+ assert!(per_turn.no_picture_line);+ }++ /// F1: a new ask starts a new delivery, so it never inherits an earlier ask's picture; and a+ /// push one turn made counts for the next, while a screenshot stays the turn's own.+ #[test]+ fn a_new_ask_never_inherits_an_earlier_delivery() {+ let visible = Expect { image: true, link: true, done_when: vec![], firm: true };+ let mut earlier = Seen::default();+ let _ = SHARED.with_earlier(&mut earlier);+ assert!(earlier.image_shared);+ // The next ask: a fresh delivery+ let mut fresh = Seen::default();+ let v = check("I changed the header.", Some(&visible), false, &NOTHING.with_earlier(&mut fresh));+ assert_eq!(v.missing, vec![Missing::Image, Missing::Link], "{v:?}");+ let prompt = v.continue_with.expect("it still asks");+ assert!(prompt.contains("an image in the chat and a PR or branch link"), "{prompt}");++ let mut delivery = Seen::default();+ let pushed = Seen { pushed: true, ..SHOT }.with_earlier(&mut delivery);+ assert_eq!(pushed, Seen { image_shared: false, has_shot: true, pushed: true });+ let next = NOTHING.with_earlier(&mut delivery);+ assert_eq!(next, Seen { image_shared: false, has_shot: false, pushed: true }, "the shot stays the first turn's");+ assert!(!check("Done, no link here.", Some(&change()), true, &next).missing.contains(&Missing::Link));+ }}diff --git a/src/server/routes.rs b/src/server/routes.rsindex 9ffe524a..5e532cfd 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -1882,6 +1882,13 @@ pub(super) struct TurnOpts {/// prompt and the plan it is checked against, for [`try_kwant_turn`] to run once the turn has/// ended. A held reply passes it on to the decided reply (see [`super::decide::Held`]).pub(super) delivery_next: Option<DeliveryNext>,+ /// What the turns of one delivery did so far: the person's ask, the decided reply of a held+ /// one and the delivery check's one continuation share it, so an image one of them shared (or+ /// a push one of them made) counts for the others. Before 0.8.1 F1 a continuation that only+ /// had to add the PR link asked for the picture the first turn had already shared, and ended+ /// with "No picture was attached". Each [`try_kwant_turn`] starts a new one, so a later ask+ /// never inherits it. `None`: only the turn's own pictures and pushes count.+ pub(super) delivery_seen: Option<DeliverySeen>,/// The chat slot passed from a turn to its delivery continuation: the first turn leaves its/// slot here when it holds the chat and the save step asked for a continuation, and the/// continuation starts on it instead of queueing. So a message that arrived meanwhile (and@@ -1909,6 +1916,9 @@ pub(super) struct TurnOpts {/// See [`TurnOpts::chat_handover`].pub(super) type ChatHandover = std::sync::Arc<std::sync::Mutex<Option<super::turns::Slot>>>;+/// See [`TurnOpts::delivery_seen`].+pub(super) type DeliverySeen = std::sync::Arc<std::sync::Mutex<super::delivery_check::Seen>>;+/// See [`TurnOpts::delivery_next`].pub(super) type DeliveryNext = std::sync::Arc<std::sync::Mutex<Option<(String, crate::router::delivery::DeliveryPlan)>>>;@@ -2011,6 +2021,8 @@ pub(super) async fn try_kwant_turn(// behind a message that waits for the chat (P6's one turn per bot per chat)let handover = next.as_ref().map(|_| ChatHandover::default());opts.chat_handover = handover.clone();+ // A new delivery: what this ask's turns share (see [`TurnOpts::delivery_seen`])+ opts.delivery_seen = Some(DeliverySeen::default());let carried = Carried::of(&opts);let first = try_kwant_turn_once(scope, target_kwant, prompt, opts).await;let Some((prompt, plan)) = next.and_then(|n| n.lock().ok().and_then(|mut n| n.take())) else {@@ -2088,6 +2100,8 @@ struct Carried {/// A turn that ran beside its bot's running turn in the chat (a lead hearing its hand-offs)/// is continued beside it too: it never waits for that turn.beside_running: bool,+ /// The delivery it belongs to: the continuation counts what the first turn already did.+ delivery_seen: Option<DeliverySeen>,}impl Carried {@@ -2101,23 +2115,27 @@ impl Carried {purpose: o.purpose.clone(),task: o.task.clone(),beside_running: o.beside_running,+ delivery_seen: o.delivery_seen.clone(),}}fn into_opts(self) -> TurnOpts {- let Carried { always_ask, delegation_id, routed, routing, tier, purpose, task, beside_running } = self;+ let Carried { always_ask, delegation_id, routed, routing, tier, purpose, task, beside_running, delivery_seen: _ } = self;TurnOpts { always_ask, delegation_id, routed, routing, tier, purpose, task, beside_running, ..Default::default() }}/// The delivery check's continuation of the turn: checked against the first turn's `plan`/// (kwant's continuation prompt never makes a new one), and never continued again. It starts- /// on the first turn's chat slot when `handover` holds it (see [`TurnOpts::chat_handover`]).+ /// on the first turn's chat slot when `handover` holds it (see [`TurnOpts::chat_handover`]),+ /// and counts what the delivery's earlier turns did (see [`TurnOpts::delivery_seen`]).fn continuation(self, plan: crate::router::delivery::DeliveryPlan, handover: Option<ChatHandover>) -> TurnOpts {+ let delivery_seen = self.delivery_seen.clone();TurnOpts {label: Some("Automatic continuation (once): the reply was missing what the person expected".into()),delivery: Some(plan),delivery_continued: true,chat_handover: handover,+ delivery_seen,..self.into_opts()}}@@ -3453,11 +3471,16 @@ async fn run_kwant_turn_inner(let expect = plan.as_ref().and_then(super::delivery_check::Expect::from_plan);let checked = opts.delivery_checked();let verdict = if checked {- let seen = super::delivery_check::Seen {+ let own = super::delivery_check::Seen {image_shared: pictures.shared_image,has_shot: pictures.last_shot.is_some(),pushed: super::delivery_check::pushed_in(activity.as_ref()),};+ // ...counting what the delivery's earlier turns did (F1)+ let seen = match opts.delivery_seen.as_ref().map(|d| d.lock()) {+ Some(Ok(mut so_far)) => own.with_earlier(&mut so_far),+ _ => own,+ };super::delivery_check::check(&text, expect.as_ref(), opts.delivery_continued, &seen)} else {super::delivery_check::Verdict::default()@@ -3512,8 +3535,14 @@ async fn run_kwant_turn_inner(// so "the bot's latest message" is still its reply (the app shows the two together)if let (true, Some(shot)) = (verdict.share_last_shot, &pictures.last_shot) {let name = super::continuity::screenshot_name(&shot.url);- if let Err(why) = super::attachments::post_screenshot(state, &turn_scope, &shot.data, &name, true).await {- tracing::warn!(kwant = %target_kwant.id, %why, "couldn't share the turn's screenshot with its reply");+ match super::attachments::post_screenshot(state, &turn_scope, &shot.data, &name, true).await {+ // The delivery's later turns count it too+ Ok(_) => {+ if let Some(Ok(mut so_far)) = opts.delivery_seen.as_ref().map(|d| d.lock()) {+ so_far.image_shared = true;+ }+ }+ Err(why) => tracing::warn!(kwant = %target_kwant.id, %why, "couldn't share the turn's screenshot with its reply"),}}let hold = opts.hook.as_ref().and_then(|h| {@@ -3537,6 +3566,7 @@ async fn run_kwant_turn_inner(meta,delivery: plan.clone(),delivery_next: opts.delivery_next.clone(),+ delivery_seen: opts.delivery_seen.clone(),});}}diff --git a/tests/decide_first_test.rs b/tests/decide_first_test.rsindex 98c1f778..e59129be 100644--- a/tests/decide_first_test.rs+++ b/tests/decide_first_test.rs@@ -26,6 +26,7 @@ use std::sync::OnceLock;use std::time::Duration;use tower::ServiceExt;+/// - kwant's one automatic delivery continuation: a reply with a PR link;/// - the hidden round's prompt: a decided reply with a [DECISIONS] block;/// - a teammate's view: "I'd pick B";/// - CHOICE: the screenshot's ending ("A, B or C?"), naming Bob;@@ -37,6 +38,7 @@ case "$1" inesacfor a; do last="$a"; donecase "$last" in+ *"[kwnt: one automatic continuation."*) out='Pushed the footer change: https://github.com/o/r/pull/7' ;;*"[Decide first] Your last reply"*)out='I checked contrast on A and C and went with B: Wax seal. Change it any time.\n\n[DECISIONS]\nquestion: Which direction? | options: A: Classic; B: Wax seal; C: Green desk | picked: B: Wax seal | why: reads best\n[/DECISIONS]' ;;*"[Decide first]"*) out="I'd pick B: it reads best." ;;@@ -78,7 +80,8 @@ struct Env {app: Router,state: AppState,channel: String,- _tmp: tempfile::TempDir,+ ann: String,+ tmp: tempfile::TempDir,}/// Ann and Bob on the fake claude in one channel; Ann leads.@@ -107,7 +110,7 @@ async fn setup() -> Env {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 c = ok(&app, "POST", "/api/channels", Some(json!({"name": "desk", "lead_kwant_id": ann, "member_kwants": [bob]}))).await;- Env { app, state, channel: c["id"].as_str().unwrap().to_string(), _tmp: tmp }+ Env { app, state, channel: c["id"].as_str().unwrap().to_string(), ann, tmp }}impl Env {@@ -285,3 +288,45 @@ async fn the_settings_round_trip_and_are_validated() {assert_eq!(v["error"], "work_ahead_daily_cap must be 1–10");}}++/// #469 round 5 (0.8.1 F1): a firm Change whose reply is held and decided. The decided reply runs+/// with decide-first's purpose, so it holds no chat slot to hand over; it has no PR link, so the+/// delivery check continues it once, and that continuation queues for the chat like any turn and+/// runs. Two replies reach the chat, in order: the decided one, then the continuation.+#[tokio::test]+async fn a_decided_change_without_a_link_is_continued_once() {+ let env = setup().await;+ // Ann's folder is a git repository, so "Fix the design ..." is a firm visible Change+ let data = kwnt::db::spaces::space_data_dir(env.tmp.path(), &SpaceId::default_space());+ std::fs::create_dir_all(kwnt::tools::bot_workspace(&data, &env.ann).join(".git")).unwrap();+ // Routed to Ann, the lead: a leading "@Ann" makes the keyword plan a lean Visual today+ env.say("Fix the design of the footer CHOICE").await;++ for _ in 0..300 {+ if env.replies().await.len() >= 2 && env.state.turns.active_turns().is_empty() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ tokio::time::sleep(Duration::from_millis(500)).await;+ let replies = env.replies().await;+ let texts: Vec<(&str, &str, Value)> = replies.iter().map(|m| (m.sender_id.as_str(), m.text.as_str(), meta(m))).collect();+ assert_eq!(replies.len(), 2, "the decided reply and its one continuation: {texts:#?}");++ // The decided reply: the plan the held turn had, missing the link (and the picture), continues+ let decided = meta(&replies[0]);+ assert_eq!(replies[0].text, "I checked contrast on A and C and went with B: Wax seal. Change it any time.");+ assert!(decided["decide_first"]["held_turn_id"].is_string(), "{decided}");+ assert_eq!(decided["delivery"]["continues"], true, "{decided}");+ assert_eq!(decided["delivery"]["missing"], json!(["image", "link"]), "{decided}");++ // The continuation ran (it wasn't stuck behind the decided reply's slot) and is never continued+ let cont = meta(&replies[1]);+ assert_eq!(replies[1].sender_id, "Ann");+ assert!(replies[1].text.starts_with("Pushed the footer change: https://github.com/o/r/pull/7"), "{}", replies[1].text);+ assert_eq!(cont["delivery"]["continues"], false, "{cont}");+ assert_eq!(cont["delivery"]["missing"], json!(["image"]), "the link is there now: {cont}");+ assert!(cont.get("decide_first").is_none(), "the continuation isn't held again: {cont}");+ assert!(replies[1].text.ends_with("No picture was attached to this reply."), "{}", replies[1].text);+ assert!(replies[0].created_at <= replies[1].created_at);+}diff --git a/tests/delivery_continuation_test.rs b/tests/delivery_continuation_test.rsindex dd2268fe..70974fef 100644--- a/tests/delivery_continuation_test.rs+++ b/tests/delivery_continuation_test.rs@@ -5,6 +5,9 @@//!//! The bot's folder is a git repository (a `.git` folder), so "Fix ..." is a firm Change, and//! the fake claude's reply has no link: the check asks for exactly one continuation.+//!+//! 0.8.1 F1: the delivery (the ask and its continuation) counts an image any of its turns shared,+//! and a new ask never inherits it.mod common;@@ -133,3 +136,68 @@ async fn a_stall_retried_try_that_misses_is_continued_once() {assert_eq!(delivery_meta(first)["continues"], true, "{:?}", first.meta);assert!(!msgs.iter().any(|m| m.text.contains("sent nothing for")), "no stall stop line after one stall: {msgs:#?}");}++/// A real 1x1 PNG.+const PNG_B64: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";++/// The bot's replies, without the file cards it shared.+async fn replies_of(env: &Env, kwant: &str) -> Vec<kwnt::db::models::Message> {+ let msgs = messages(env, kwant).await;+ msgs.into_iter().filter(|m| m.sender_role == "kwant" && !m.meta.as_deref().is_some_and(|s| s.contains(r#""kind":"file""#))).collect()+}++/// 0.8.1 F1 (Rigel, 0.8.0 final QA): a visible change whose first turn shares the screenshot but+/// gives no PR link. The continuation only asks for the link, and its reply doesn't say "No+/// picture was attached". The next, unrelated ask shares nothing and is still asked for both.+#[tokio::test]+async fn a_continuation_counts_the_picture_its_first_turn_shared() {+ use base64::Engine;+ let env = setup().await;+ let a = env.a.clone();+ in_a_repo(&env, &a);+ let ws = kwnt::tools::bot_workspace(&env.tmp.path().join("data"), &a);+ std::fs::write(ws.join("footer-after.png"), base64::engine::general_purpose::STANDARD.decode(PNG_B64).unwrap()).unwrap();+ let share = call_tool_marker("share_file", serde_json::json!({"path": "footer-after.png", "name": "footer-after.png"}));++ // Turn 1 shares the picture and gives no link: a firm visible Change continues for the link only+ send_direct(&env, &a, &format!("Fix the design of the footer. {share} REPLYTAG:zqpic"), serde_json::json!({})).await;+ wait_for("the continuation to run", || async { !started(&runs(&env), CONTINUATION).is_empty() }).await;+ wait_for("two replies", || async { replies_of(&env, &a).await.len() >= 2 }).await;+ wait_for("the bot to finish", || async { bot_idle(&env, &a) }).await;+ tokio::time::sleep(Duration::from_millis(300)).await;+ let msgs = messages(&env, &a).await;+ assert_eq!(msgs.iter().filter(|m| m.text == "Shared a file: footer-after.png").count(), 1, "turn 1 shared it once: {msgs:#?}");+ let replies = replies_of(&env, &a).await;+ assert_eq!(replies.len(), 2, "{replies:#?}");+ let first = delivery_meta(&replies[0]);+ assert_eq!((first["missing"].clone(), first["continues"].clone()), (serde_json::json!(["link"]), serde_json::json!(true)), "{first}");+ let all = runs(&env);+ let asked: Vec<&String> = all.iter().map(|(_, r)| r).filter(|r| r.contains(CONTINUATION)).collect();+ assert_eq!(asked.len(), 1, "{all:#?}");+ assert!(asked[0].contains("Missing from your last reply: a PR or branch link."), "only the link: {}", asked[0]);+ // The continuation: no picture asked for, none said missing+ let cont = delivery_meta(&replies[1]);+ assert_eq!(cont["missing"], serde_json::json!(["link"]), "the fake never links; the picture counts: {cont}");+ assert_eq!((cont["no_picture"].clone(), cont["continues"].clone()), (serde_json::json!(false), serde_json::json!(false)), "{cont}");+ assert!(!replies[1].text.contains(NO_PICTURE), "{}", replies[1].text);++ // A new ask: a new delivery, which shares nothing and is asked for the image and the link+ send_direct(&env, &a, "Fix the design of the header. REPLYTAG:zqnext", serde_json::json!({})).await;+ wait_for("four replies", || async { replies_of(&env, &a).await.len() >= 4 }).await;+ wait_for("the bot to finish", || async { bot_idle(&env, &a) }).await;+ tokio::time::sleep(Duration::from_millis(300)).await;+ let replies = replies_of(&env, &a).await;+ assert_eq!(replies.len(), 4, "{replies:#?}");+ let next = delivery_meta(&replies[2]);+ assert_eq!((next["missing"].clone(), next["continues"].clone()), (serde_json::json!(["image", "link"]), serde_json::json!(true)), "{next}");+ let all = runs(&env);+ let asked: Vec<&String> = all.iter().map(|(_, r)| r).filter(|r| r.contains(CONTINUATION)).collect();+ assert_eq!(asked.len(), 2, "{all:#?}");+ assert!(asked.iter().any(|r| r.contains("Missing from your last reply: an image in the chat and a PR or branch link.")), "{asked:#?}");+ let cont = delivery_meta(&replies[3]);+ assert_eq!((cont["missing"].clone(), cont["no_picture"].clone()), (serde_json::json!(["image", "link"]), serde_json::json!(true)), "{cont}");+ assert!(replies[3].text.contains(NO_PICTURE), "{}", replies[3].text);+}++/// `NO_PICTURE_LINE` (src/server/picture_claims.rs).+const NO_PICTURE: &str = "No picture was attached to this reply.";