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
27d: held messages keep their order (#787)
Oleksandr Ivanchenko3f5cb4b88ca5
diff --git a/src/server/bot_status.rs b/src/server/bot_status.rsindex 6b76c998..fe9947ea 100644--- a/src/server/bot_status.rs+++ b/src/server/bot_status.rs@@ -212,9 +212,15 @@ pub struct Board {pub signals: HashMap<String, TurnSignals>,pub marks: HashMap<String, BotMarks>,pub held: Vec<HeldItem>,+ /// 27d: held messages released but not in their bot's line yet (see [`HeldPlace`]), oldest+ /// first. Not shown as held: the bot can take them, they only keep their place.+ releasing: Vec<HeldItem>,sent: HashMap<String, Sent>,/// Bots whose status may have changed outside the event bus (a hold, a mark, a snooze).nudged: HashSet<String>,+ /// Tests: how long a held send's work between its release and its queue place takes (the+ /// delivery plan's model call in a real chat), by send id. Taken once, at the release.+ pub release_lag: HashMap<String, std::time::Duration>,}impl Board {@@ -222,6 +228,16 @@ impl Board {self.nudged.insert(kwant_id.to_string());}+ /// 27d: an older held message of the person to the same bot in the same chat hasn't taken its+ /// place in the bot's line yet (still held, or released and on its way there), so `item` waits+ /// for it: the person's messages are answered in the order they sent them. Hand-offs keep+ /// their own way (never in this line, never waiting on it).+ fn older_message_first(&self, item: &HeldItem) -> bool {+ let same = |h: &HeldItem| h.kind == "message" && h.kwant_id == item.kwant_id && h.context_id == item.context_id;+ item.kind == "message"+ && (self.releasing.iter().any(same) || self.held.iter().take_while(|h| h.id != item.id).any(same))+ }+/// 0.9.5 (no silent stops): the person writing to `kwant_id` in the chat where it gave up after/// a stall is that stop's Retry (the notice's Retry button resends their message; the notice/// says "Send your message again to retry"). It ends the gave-up Stuck like "Try again" does,@@ -848,33 +864,84 @@ fn held_view(kwant: &crate::db::models::Kwant, r: &HoldReason) -> Value {}/// Waits until the held send `item_id` may go: `true` then (or when it wasn't held), `false`-/// when it was stopped first. Either way it is no longer held.+/// when it was stopped first. Either way it is no longer held. A message's place in its chat's+/// line is given up at once; [`wait_turn`] keeps it until the turn is queued.pub async fn wait_released(state: &AppState, item_id: &str, cancel: &CancellationToken) -> bool {+ // Boxed: hand-offs wait here inside their turn's future, which a debug-build test thread has+ // only just room for (see [`HeldPlace`])+ Box::pin(wait_turn(state, item_id, cancel)).await.is_some()+}++/// [`wait_released`] for the person's held message (27d): `Some` once it may go, and only after+/// the older messages they held for the same bot in the same chat have their places in the bot's+/// line. The [`HeldPlace`] keeps this one's place until its turn has one too (pass it to the+/// turn as [`super::routes::TurnOpts`]'s `held_place`), so the next message is released only+/// then, however long the work in between takes (the delivery plan's model call, up to ~3 s).+/// `None` when it was stopped first. Either way it is no longer held.+pub async fn wait_turn(state: &AppState, item_id: &str, cancel: &CancellationToken) -> Option<HeldPlace> {let Some(item) = state.turns.board(|b| b.held.iter().find(|h| h.id == item_id).cloned()) else {- return true;- };- let unhold = || {- state.turns.board(|b| {- b.held.retain(|h| h.id != item_id);- b.nudge(&item.kwant_id);- })+ return Some(HeldPlace::default());};+ // Takes it off the board however this ends (stopped, or the wait dropped), so it never holds+ // up the messages after it; once released, it is the place+ let place = HeldPlace(Some(Box::new(Place { turns: state.turns.clone(), id: item.id.clone(), kwant_id: item.kwant_id.clone() })));loop {tokio::select! {- _ = cancel.cancelled() => {- unhold();- return false;- }+ _ = cancel.cancelled() => return None,_ = tokio::time::sleep(HOLD_POLL) => {}}+ if state.turns.board(|b| b.older_message_first(&item)) {+ continue;+ }let free = match input_of(state, &item.kwant_id).await {Some(input) => hold_reason(&input, &item.context_id, Utc::now()).is_none(),None => true,};if free {- unhold();+ let lag = state.turns.board(|b| {+ if let Some(at) = b.held.iter().position(|h| h.id == item_id) {+ let h = b.held.remove(at);+ b.releasing.push(h);+ }+ b.nudge(&item.kwant_id);+ b.release_lag.remove(item_id)+ });tracing::info!(kwant = %item.kwant_id, kind = item.kind, "held send released");- return true;+ if let Some(lag) = lag {+ tokio::time::sleep(lag).await;+ }+ return Some(place);+ }+ }+}++/// 27d: a held message's place in its chat's line (see [`wait_turn`]): the younger messages held+/// for the same bot and chat wait while it lives. Dropped once the message's turn is in the bot's+/// line ([`super::turns::TurnRegistry::acquire_then`]), or when the turn ends before that+/// (stopped, or held back by a spending stop); dropping it takes the send off the board.+///+/// One pointer wide on purpose: it rides in [`super::routes::TurnOpts`], which is moved through+/// every layer of a turn's future, and a debug-build test thread (2 MiB) has only just room for+/// those (`keep_going_test` overflowed with this inline, as it did with `TurnOpts::audit`).+#[derive(Default)]+pub struct HeldPlace(Option<Box<Place>>);++const _: () = assert!(std::mem::size_of::<HeldPlace>() == std::mem::size_of::<usize>(), "HeldPlace stays one pointer wide");++struct Place {+ turns: super::turns::TurnRegistry,+ id: String,+ kwant_id: String,+}++impl Drop for HeldPlace {+ fn drop(&mut self) {+ if let Some(p) = self.0.take() {+ p.turns.board(|b| {+ b.held.retain(|h| h.id != p.id);+ b.releasing.retain(|h| h.id != p.id);+ b.nudge(&p.kwant_id);+ });}}}@@ -1348,6 +1415,43 @@ mod tests {// H3+ /// 27d: a held message of the person waits for the older ones in its chat to the same bot, held+ /// or released and not in the bot's line yet; other chats, other bots and hand-offs don't wait.+ #[test]+ fn a_held_message_goes_after_the_older_ones_in_its_chat() {+ let item = |kind: &'static str, id: &str, kwant: &str, ctx: &str| HeldItem {+ kind,+ id: id.into(),+ kwant_id: kwant.into(),+ since: at(0),+ reason_code: "waits_on_you",+ context_id: ctx.into(),+ };+ let mut b = Board {+ held: vec![+ item("handoff", "d1", "k1", "c1"),+ item("message", "m1", "k1", "c1"),+ item("message", "m2", "k1", "c1"),+ item("message", "x1", "k1", "c2"),+ item("message", "y1", "k2", "c1"),+ item("handoff", "d2", "k1", "c1"),+ ],+ ..Default::default()+ };+ let waits = |b: &Board, id: &str| b.older_message_first(&b.held.iter().find(|h| h.id == id).unwrap().clone());+ assert!(!waits(&b, "m1"), "the oldest message goes first; an older hand-off doesn't hold it");+ assert!(waits(&b, "m2"), "m2 waits for m1");+ assert!(!waits(&b, "x1"), "another chat of the bot doesn't wait");+ assert!(!waits(&b, "y1"), "another bot in the chat doesn't wait");+ assert!(!waits(&b, "d2"), "a hand-off never waits in the line");+ // m1 released, not in the bot's line yet: m2 still waits; once it is, m2 goes+ let m1 = b.held.remove(1);+ b.releasing.push(m1);+ assert!(waits(&b, "m2"), "m2 waits while m1 is on its way to the line");+ b.releasing.clear();+ assert!(!waits(&b, "m2"));+ }+#[test]fn a_send_to_a_stuck_bot_is_held() {let mut t = running("t1", at(0));diff --git a/src/server/decide.rs b/src/server/decide.rsindex 58e7d3f7..277efb21 100644--- a/src/server/decide.rs+++ b/src/server/decide.rs@@ -785,7 +785,7 @@ pub(super) async fn decide(scope: &TurnScope, kwant: &Kwant, mut held: Held) ->let mut opts = TurnOpts::default();(opts.quiet_failure, opts.purpose, opts.hook) = (true, Some(PURPOSE.into()), Some(hook.clone()));// The decided reply is the one the person sees: it delivers what their message asked for- opts.delivery = held.delivery.clone();+ opts.delivery = held.delivery.clone().map(Box::new);opts.delivery_next = held.delivery_next.clone();opts.delivery_seen = held.delivery_seen.clone();opts.failed_before = held.failed_before;diff --git a/src/server/routes.rs b/src/server/routes.rsindex ab9a2eb6..147fff48 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -1023,10 +1023,13 @@ fn execute_single_turn(tokio::spawn(async move {// Ends the job (its cancel keys) when the turn and its handoffs are donelet _job = job;- // H3: a message held for a stuck or waiting bot starts its turn once the bot can take it+ // H3: a message held for a stuck or waiting bot starts its turn once the bot can take it,+ // after the older ones the person held in this chat (27d: answered in the order sent)+ let mut held_place = super::bot_status::HeldPlace::default();if let Some(id) = &held {- if !super::bot_status::wait_released(&scope.state, id, &scope.cancel_token).await {- return;+ match Box::pin(super::bot_status::wait_turn(&scope.state, id, &scope.cancel_token)).await {+ Some(place) => held_place = place,+ None => return,}}// P10: what the person expects and how best to deliver it, planned once before the bot@@ -1045,7 +1048,7 @@ fn execute_single_turn(super::delivery_plan::remember(&scope.job_id, &message_id, plan);}// A full link in the person's own message may open the bot browser first- let opts = TurnOpts { routing, nav_prompt: Some(prompt.clone()), source: Some(source), ..TurnOpts::default() };+ let opts = TurnOpts { routing, nav_prompt: Some(prompt.clone()), source: Some(source), held_place, ..TurnOpts::default() };if let Some(reply) = run_kwant_turn(&scope, &target_kwant, turn_prompt, opts).await {run_handoffs(&scope, std::slice::from_ref(&target_kwant.id), &[(target_kwant.clone(), reply)], &prompt).await;// Several bots asked the person something: one list of it all (when the chain is over)@@ -2141,7 +2144,13 @@ pub(super) struct TurnOpts {/// reply's plan, though its prompt is kwant's; the delivery check's continuation keeps the/// first turn's, and is checked against it). `None`: the plan comes from the person's own/// message, or there is none (see [`crate::router::delivery::plan_for_turn`]).- pub(super) delivery: Option<crate::router::delivery::DeliveryPlan>,+ /// Boxed, like `audit` and `held_place`: `TurnOpts` rides in every layer of a turn's future.+ pub(super) delivery: Option<Box<crate::router::delivery::DeliveryPlan>>,+ /// 27d: a released held message's place in its chat's line, given up once this turn has its+ /// own place in the bot's line (see [`super::bot_status::wait_turn`]). Only the first attempt+ /// carries it. Empty for every turn that wasn't held. One pointer wide (see+ /// [`super::bot_status::HeldPlace`]).+ pub(super) held_place: super::bot_status::HeldPlace,}/// See [`TurnOpts::chat_handover`].@@ -2316,7 +2325,8 @@ fn turn_plan(opts: &TurnOpts, current: Option<&Message>, recent: &[&str], git_refresh_eyes: opts.fresh_eyes,carried: opts.delivery- .clone()+ .as_deref()+ .cloned().or_else(|| person.and_then(|m| super::delivery_plan::plan_for_answer(job_id, Some(m.id.as_str())))),person_message: person_words(opts.nav_prompt.is_some(), current),recent,@@ -2385,7 +2395,7 @@ impl Carried {let delivery_seen = self.delivery_seen.clone();TurnOpts {label: Some(label.into()),- delivery: plan,+ delivery: plan.map(Box::new),delivery_continued: true,chat_handover: handover,delivery_seen,@@ -2425,7 +2435,7 @@ pub(super) async fn turn_once(scope: &TurnScope,target_kwant: &Kwant,prompt: String,- opts: TurnOpts,+ mut opts: TurnOpts,) -> Result<String, String> {let tag = crate::drivers::events::TurnTag {turn_id: uuid::Uuid::new_v4().to_string(),@@ -2473,9 +2483,16 @@ pub(super) async fn turn_once(// A delivery continuation starts on the slot its first turn handed over (see// [`TurnOpts::chat_handover`]); every other turn takes onelet handed = opts.chat_handover.as_ref().and_then(|h| h.lock().ok()?.take());+ // 27d: a released held message keeps its chat's line until this turn is in the bot's line+ let place = std::mem::take(&mut opts.held_place);let slot = match handed {- Some(slot) => slot,- None => match turns.acquire(&tag, one_per_chat, &scope.cancel_token, &scope.state.event_sender).await {+ Some(slot) => {+ drop(place);+ slot+ }+ // Boxed, like the place itself: turn_once's future is part of every turn's (see+ // [`super::bot_status::HeldPlace`])+ None => match Box::pin(turns.acquire_then(&tag, one_per_chat, &scope.cancel_token, &scope.state.event_sender, move || drop(place))).await {Some(slot) => slot,None => return Err("stopped by the user".into()),},@@ -2974,7 +2991,7 @@ async fn run_kwant_turn_inner(no_tools: opts.no_tools,read_only,fresh_eyes: opts.fresh_eyes,- carried: opts.delivery.clone().or_else(|| job_plan.clone()),+ carried: opts.delivery.as_deref().cloned().or_else(|| job_plan.clone()),person_message: answered.map(|m| m.text.as_str()),recent: &[],git_repo: workspace_dir.as_deref().is_some_and(crate::router::delivery::in_git_repo),@@ -5089,7 +5106,7 @@ async fn send_to_thread(let job = state.turns.start_job([saved.id.clone(), thread.id.clone()]);let scope = scope_for(&state, &kwant, None, Some(thread.id.clone()), &job, depth).await.map_err(|_| StatusCode::NOT_FOUND)?;- let opts = TurnOpts {+ let mut opts = TurnOpts {nav_prompt: Some(payload.prompt.clone()),source: Some(super::bot_status::TurnSource::sender(from_person)),..TurnOpts::default()@@ -5102,9 +5119,11 @@ async fn send_to_thread(let held_id = held.as_ref().map(|_| saved.id.clone());tokio::spawn(async move {let _job = job;+ // After the older messages the person held in this thread (27d)if let Some(id) = &held_id {- if !super::bot_status::wait_released(&scope.state, id, &scope.cancel_token).await {- return;+ match Box::pin(super::bot_status::wait_turn(&scope.state, id, &scope.cancel_token)).await {+ Some(place) => opts.held_place = place,+ None => return,}}run_kwant_turn(&scope, &target, prompt, opts).await;@@ -7579,7 +7598,7 @@ mod tests {assert!(first.continuation_slot().is_some());let ideas = turn_plan(&first, Some(&saved("user", "user", "What cool feature can we add?", None)), &[], true, "").unwrap();let next = Carried::of(&first).continuation(Some(ideas.clone()), crate::server::delivery_check::continuation_label(&[crate::server::delivery_check::Missing::Link]), None);- assert_eq!(next.delivery.as_ref(), Some(&ideas));+ assert_eq!(next.delivery.as_deref(), Some(&ideas));assert!(next.delivery_continued && next.continuation_slot().is_none(), "continued once at most");// kwant's continuation prompt can't make a plan of its ownlet prompt = saved("user", "user", "Commit and push your work, then reply with the PR link", None);@@ -7613,9 +7632,9 @@ mod tests {TurnOpts { no_tools: true, ..person_turn() },TurnOpts { fresh_eyes: true, ..person_turn() },TurnOpts { purpose: brief.clone(), ..person_turn() },- TurnOpts { no_tools: true, delivery: carried.clone(), ..Default::default() },- TurnOpts { fresh_eyes: true, delivery: carried.clone(), ..Default::default() },- TurnOpts { purpose: brief.clone(), delivery: carried.clone(), ..Default::default() },+ TurnOpts { no_tools: true, delivery: carried.clone().map(Box::new), ..Default::default() },+ TurnOpts { fresh_eyes: true, delivery: carried.clone().map(Box::new), ..Default::default() },+ TurnOpts { purpose: brief.clone(), delivery: carried.clone().map(Box::new), ..Default::default() },] {assert_eq!(plan_of(&opts, &m, true), None, "no_tools={} fresh_eyes={} purpose={:?}", opts.no_tools, opts.fresh_eyes, opts.purpose);}diff --git a/src/server/turns.rs b/src/server/turns.rsindex 1f8372e5..f724b608 100644--- a/src/server/turns.rs+++ b/src/server/turns.rs@@ -481,10 +481,28 @@ impl TurnRegistry {one_per_chat: bool,cancel: &CancellationToken,events: &broadcast::Sender<RuntimeEvent>,+ ) -> Option<Slot> {+ // Boxed: callers keep this inline in their turn's future (see `bot_status::HeldPlace`)+ Box::pin(self.acquire_then(tag, one_per_chat, cancel, events, || {})).await+ }++ /// [`Self::acquire`], calling `in_line` as soon as the turn has its place: its slot, or its+ /// place in the line (after `turn_queued` is sent). A released held message passes its+ /// [`super::bot_status::HeldPlace`] here, so the next one in its chat goes only then (27d).+ pub async fn acquire_then(+ &self,+ tag: &crate::drivers::events::TurnTag,+ one_per_chat: bool,+ cancel: &CancellationToken,+ events: &broadcast::Sender<RuntimeEvent>,+ in_line: impl FnOnce(),) -> Option<Slot> {let chat = one_per_chat.then_some(tag.context_id.as_str());let rx = match self.limiter.try_acquire_in(&tag.kwant_id, chat) {- Ok(slot) => return Some(slot),+ Ok(slot) => {+ in_line();+ return Some(slot);+ }Err(wait) => wait,};self.set_turn(ActiveTurn {@@ -507,6 +525,7 @@ impl TurnRegistry {reason: rx.reason.into(),slots: None,});+ in_line();tokio::select! {slot = rx.rx => slot.ok(),_ = cancel.cancelled() => None,diff --git a/tests/held_order_test.rs b/tests/held_order_test.rsnew file mode 100644index 00000000..d13b2328--- /dev/null+++ b/tests/held_order_test.rs@@ -0,0 +1,167 @@+//! 27d: messages the person sends while their bot waits on them are held (H3), and when the+//! person answers, all of them are released in the same tick. Each then has work to do before it+//! takes its place in the bot's line (the delivery plan's model call, up to ~3 s), so on 0.9.21+//! they were answered in whatever order that work finished: 7 of 8 runs out of order in Rigel's+//! 27c QA. Here the work after the release takes longest for the oldest message, and the four+//! must still be queued and answered in the order the person sent them: in a direct chat and in+//! a thread. Nothing is lost or merged.++mod common;++use axum::http::StatusCode;+use common::*;+use kwnt::drivers::events::RuntimeEvent;+use serde_json::{json, Value};+use std::time::Duration;++fn ask_marker(question: &str, choices: &[&str]) -> String {+ call_tool_marker(+ "ask_user",+ json!({"question": question, "choices": choices, "why_you": "irreversible", "checked": "Read the release notes."}),+ )+}++async fn open_question(env: &Env, ctx: &str) -> String {+ for _ in 0..300 {+ let (s, list) = call(&env.app, "GET", &format!("/api/questions?status=open&context_id={ctx}"), None).await;+ assert_eq!(s, StatusCode::OK);+ if let Some(q) = list.as_array().and_then(|l| l.first()) {+ return q["id"].as_str().unwrap().to_string();+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ panic!("no open question in {ctx}");+}++async fn new_thread(env: &Env, title: &str) -> String {+ let (s, t) = call(&env.app, "POST", &format!("/api/kwants/{}/threads", env.a), Some(json!({"title": title}))).await;+ assert_eq!(s, StatusCode::CREATED, "{t}");+ t["id"].as_str().unwrap().to_string()+}++/// Bot A's direct chat, or one of its threads.+enum Chat {+ Direct,+ Thread(String),+}++impl Chat {+ fn context(&self, env: &Env) -> String {+ match self {+ Chat::Direct => env.a.clone(),+ Chat::Thread(t) => t.clone(),+ }+ }++ async fn send(&self, env: &Env, prompt: &str) -> Value {+ let mut body = json!({"prompt": prompt, "sender_id": "user"});+ match self {+ Chat::Direct => body["kwant_id"] = json!(env.a),+ Chat::Thread(t) => body["thread_id"] = json!(t),+ }+ let (s, v) = call(&env.app, "POST", "/api/chat/send", Some(body)).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ v+ }+}++/// Bot A is busy answering in a chat (a slow reply; a thread when `in_thread`, else its direct+/// chat) and waits on the person's answer in the other one. The person sends four messages to `chat`; all four are held. Their release work is+/// slowest for the first (`lags`, oldest first). Once the person answers, the four take their+/// places in A's line in the order sent (`turn_queued` positions 1..4) and are answered in it.+async fn four_held_messages_keep_their_order(in_thread: bool, tag: &str) {+ let env = setup().await;+ let thread = Chat::Thread(new_thread(&env, "side").await);+ let (chat, ask_in) = if in_thread { (thread, Chat::Direct) } else { (Chat::Direct, thread) };+ let ctx = chat.context(&env);+ let ask_ctx = ask_in.context(&env);++ // A slow reply holds the chat, so every released message has to queue for it+ chat.send(&env, &format!("Draft the summary. SLEEPONCE:{tag}s:20000 REPLYTAG:{tag}s")).await;+ wait_for("the slow reply to start", || async {+ env.state.turns.active_turns().iter().any(|t| t.context_id == ctx && t.state == "running")+ })+ .await;++ // The bot asks the person elsewhere, so sends to `chat` are held until the answer+ // The question names the test: the fake CLI runs each CALLTOOL marker once per test binary+ // (a `called-<sha1>` flag), and both tests run in it together, so a shared marker would open+ // the question in only one of them.+ let question = format!("Which branch should I ship ({tag})?");+ ask_in.send(&env, &format!("Ship it? {} REPLYTAG:{tag}q", ask_marker(&question, &["main", "batch2"]))).await;+ let qid = open_question(&env, &ask_ctx).await;++ let mut events = env.state.event_sender.subscribe();+ let lags = [1500u64, 1000, 600, 200];+ let mut sent = Vec::new();+ for (i, lag) in lags.iter().enumerate() {+ let v = chat.send(&env, &format!("Question {}? REPLYTAG:{tag}h{}", i + 1, i + 1)).await;+ assert_eq!(v["status"], "held", "message {} is held: {v}", i + 1);+ let id = v["user_message_id"].as_str().unwrap().to_string();+ env.state.turns.board(|b| b.release_lag.insert(id.clone(), Duration::from_millis(*lag)));+ sent.push(id);+ }++ let (s, v) = call(&env.app, "POST", &format!("/api/questions/{qid}/answer"), Some(json!({"choice": 1}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");++ // Every released message queues (the slow reply still holds the chat), in send order+ let mut queued: Vec<(String, usize)> = Vec::new();+ let mut started: Vec<String> = Vec::new();+ let deadline = tokio::time::Instant::now() + Duration::from_secs(60);+ while started.len() < 4 || queued.len() < 4 {+ let e = tokio::time::timeout_at(deadline, events.recv())+ .await+ .unwrap_or_else(|_| panic!("timed out: queued {queued:?}, started {started:?}"))+ .expect("event bus");+ match e {+ RuntimeEvent::TurnQueued { turn_id, context_id, position, .. } if context_id.as_deref() == Some(ctx.as_str()) => {+ assert!(started.is_empty(), "every message queued before the slow reply ended: {turn_id} at {position} after {started:?}");+ queued.push((turn_id, position));+ }+ RuntimeEvent::TurnStarted { turn_id: Some(t), context_id, .. } if context_id.as_deref() == Some(ctx.as_str()) => {+ started.push(t);+ }+ _ => {}+ }+ }+ let positions: Vec<usize> = queued.iter().map(|(_, p)| *p).collect();+ assert_eq!(positions, vec![1, 2, 3, 4], "{queued:?}");+ // The line is first come, first served: the turn queued k-th starts k-th (after the slow reply)+ let queued_ids: Vec<&str> = queued.iter().map(|(t, _)| t.as_str()).collect();+ let started_after: Vec<&str> = started.iter().map(String::as_str).filter(|t| queued_ids.contains(t)).collect();+ assert_eq!(started_after, queued_ids, "queued turns start in line order");++ // ...so the person reads the answers in the order they asked, and none is lost or merged+ wait_reply(&env, &ctx, &format!("answer {tag}h4")).await;+ wait_for("all four answers", || async {+ messages(&env, &ctx).await.iter().filter(|m| m.sender_role == "kwant" && m.text.contains(&format!("answer {tag}h"))).count() >= 4+ })+ .await;+ let msgs = messages(&env, &ctx).await;+ let answers: Vec<String> = msgs+ .iter()+ .filter(|m| m.sender_role == "kwant")+ .filter_map(|m| (1..=4).find(|i| m.text.contains(&format!("answer {tag}h{i}"))).map(|i| format!("h{i}")))+ .collect();+ assert_eq!(answers, vec!["h1", "h2", "h3", "h4"], "answers in send order");+ for id in &sent {+ assert_eq!(msgs.iter().filter(|m| &m.id == id).count(), 1, "message {id} saved once");+ }+ wait_for("the bot to be free and nothing held", || async {+ env.state.turns.active_turns().is_empty() && env.state.turns.board(|b| b.held.is_empty())+ })+ .await;+}++#[tokio::test]+async fn held_messages_in_a_direct_chat_are_queued_and_answered_in_send_order() {+ // The bot asks in a thread; the four go to its direct chat+ four_held_messages_keep_their_order(false, "ordd").await;+}++#[tokio::test]+async fn held_messages_in_a_thread_are_queued_and_answered_in_send_order() {+ // The bot asks in its direct chat; the four go to a thread+ four_held_messages_keep_their_order(true, "ordt").await;+}