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.

0.9.0 H4 + P4 + H3: why this status, the quiet signal, held sends, no double send (server) (#499)

Oleksandr Ivanchenkoaec520379e52
diff --git a/src/drivers/events.rs b/src/drivers/events.rs
index bc4cc38e..5a0e1149 100644
--- a/src/drivers/events.rs
+++ b/src/drivers/events.rs
@@ -309,6 +309,10 @@ pub enum RuntimeEvent {
/// A kwant's memory changed (by the user or by the kwant's own tools); refetch it.
#[serde(rename = "memory_changed", alias = "MemoryChanged")]
MemoryChanged { kwant_id: String },
+ /// A bot's status, its reason and since when changed (H4); `status` is the whole status
+ /// object of `release-090/h4-contract.md` §1 (see `crate::server::bot_status`).
+ #[serde(rename = "bot_status", alias = "BotStatus")]
+ BotStatus { kwant_id: String, status: Value },
/// A routine run started or finished. `status` is "running", "ok", "error" or "skipped".
#[serde(rename = "routine_run", alias = "RoutineRun")]
RoutineRun {
diff --git a/src/server/activity.rs b/src/server/activity.rs
index 4cb0adc7..cecea3dd 100644
--- a/src/server/activity.rs
+++ b/src/server/activity.rs
@@ -144,6 +144,31 @@ pub fn turn_view(turn: &super::turns::ActiveTurn) -> Value {
v
}
+/// What a running turn's steps say it waits on right now (H4).
+#[derive(Debug, Default, Clone, PartialEq)]
+pub struct TurnWaits {
+ /// The newest step waiting for the person: its kind ("approval" or "human_step") and start.
+ pub waiting: Option<(&'static str, String)>,
+ /// The tool of the newest tool step that still runs.
+ pub running_tool: Option<String>,
+}
+
+pub fn turn_waits(turn_id: &str) -> TurnWaits {
+ let Some(turn) = TurnActivity::find(turn_id) else { return TurnWaits::default() };
+ turn.with_log(|log| waits_of(log.steps()))
+}
+
+fn waits_of(steps: &[Step]) -> TurnWaits {
+ TurnWaits {
+ waiting: steps
+ .iter()
+ .rev()
+ .find(|s| matches!(s.kind, "approval" | "human_step") && s.status == "waiting")
+ .map(|s| (s.kind, s.started_at.clone())),
+ running_tool: steps.iter().rev().find(|s| s.kind == "tool" && s.status == "running").and_then(|s| s.tool.clone()),
+ }
+}
+
/// Adds `meta.activity` to a reply's meta.
pub fn with_activity(meta: Option<Value>, activity: Option<Value>) -> Option<Value> {
let Some(activity) = activity else { return meta };
@@ -159,6 +184,21 @@ mod tests {
use super::*;
use serde_json::json;
+ #[test]
+ fn turn_waits_reads_the_waiting_step_and_the_running_tool() {
+ let (tx, _rx) = broadcast::channel(16);
+ let tag = TurnTag { turn_id: "turn-waits-test".into(), kwant_id: "k".into(), context_id: "c".into(), thread_id: None };
+ let turn = TurnActivity::start(tx, tag);
+ assert_eq!(turn_waits("turn-waits-test"), TurnWaits::default());
+ turn.observe(&RuntimeEvent::ToolCallPending { id: "1".into(), name: "Bash".into(), args: json!({"command": "ls"}) });
+ assert_eq!(turn_waits("turn-waits-test").running_tool.as_deref(), Some("Bash"));
+ approval_waiting("turn-waits-test", "ap", "Bash");
+ assert_eq!(turn_waits("turn-waits-test").waiting.map(|w| w.0), Some("approval"));
+ approval_settled("turn-waits-test", "ap", "ok");
+ assert_eq!(turn_waits("turn-waits-test").waiting, None);
+ assert_eq!(turn_waits("no-such-turn"), TurnWaits::default());
+ }
+
#[test]
fn steps_go_out_scoped_and_approvals_find_their_turn() {
let (tx, mut rx) = broadcast::channel(16);
diff --git a/src/server/bot_status.rs b/src/server/bot_status.rs
new file mode 100644
index 00000000..d6e8366a
--- /dev/null
+++ b/src/server/bot_status.rs
@@ -0,0 +1,1297 @@
+//! Why each bot has its status, and since when (H4); the quiet signal (P4); never sending to a
+//! stuck or waiting bot, and no double send (H3). The contract the frontend reads is
+//! `release-090/h4-contract.md`: the copy lives there, the server sends codes, times and names.
+//!
+//! The turn registry keeps the live signals ([`Board`]): each running turn's last streamed step,
+//! its stall, and its quiet snooze; each bot's gave-up mark and last finished turn; the held sends;
+//! the client message ids seen lately. [`compute`] turns one bot's signals into its status object
+//! and [`hold_reason`] says whether a send to it waits. Both are pure and tested below. A watcher
+//! ([`spawn_watcher`]) pushes `bot_status` on change and sends the 15 min quiet FYI once per turn.
+
+use super::turns::ActiveTurn;
+use super::AppState;
+use crate::db::spaces::SpaceId;
+use crate::drivers::events::RuntimeEvent;
+use axum::extract::{Path, State};
+use axum::http::{HeaderMap, StatusCode};
+use axum::response::{IntoResponse, Response};
+use axum::Json;
+use chrono::{DateTime, Duration as Span, Utc};
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use std::collections::{HashMap, HashSet};
+use tokio_util::sync::CancellationToken;
+
+/// A live-engine turn with no step for this long is Quiet.
+pub const QUIET_AFTER_MIN: i64 = 5;
+/// From here Quiet is "long" (amber) and the Inbox FYI goes out, once per turn.
+pub const QUIET_LONG_MIN: i64 = 15;
+/// An engine that reports only at the end is Quiet after this long running.
+pub const NO_LIVE_QUIET_AFTER_MIN: i64 = 15;
+/// How long a turn that gave up after a stall keeps its bot Stuck.
+pub const GAVE_UP_SHOWS_MIN: i64 = 30;
+/// "Check again in 30 min".
+pub const SNOOZE_MIN: i64 = 30;
+/// Text and thinking deltas move the last step at most this often.
+pub const STEP_BATCH_SECS: i64 = 10;
+/// The same client message id in the same chat within this window is sent once.
+pub const DEDUPE_MIN: i64 = 10;
+pub const MAX_CLIENT_ID_CHARS: usize = 100;
+/// Other turns listed beside the one the status is about.
+const MAX_ALSO: usize = 2;
+/// How often a held send checks whether its bot can take it.
+const HOLD_POLL: std::time::Duration = std::time::Duration::from_millis(500);
+/// How often the watcher re-checks every busy bot for quiet crossings, besides on events.
+const WATCH_SWEEP: std::time::Duration = std::time::Duration::from_secs(15);
+
+// ---------------------------------------------------------------------------------------------
+// Live signals, kept by the turn registry
+
+/// The stall watchdog fired in this turn and its retry hasn't answered yet.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Stall {
+ pub at: DateTime<Utc>,
+ pub secs: u64,
+}
+
+/// What a running (or queued) turn showed so far.
+#[derive(Debug, Clone, Default, PartialEq)]
+pub struct TurnSignals {
+ pub last_step_at: Option<DateTime<Utc>>,
+ /// The tool of the last step; `None` for text and thinking.
+ pub last_step_title: Option<String>,
+ /// `Some(false)`: the engine reports only at the end (`streams_progress() == false`). Any
+ /// streamed step proves otherwise.
+ pub live_steps: Option<bool>,
+ /// "Claude", "Codex", …
+ pub engine: Option<&'static str>,
+ pub stalled: Option<Stall>,
+ pub snooze_until: Option<DateTime<Utc>>,
+ pub muted: bool,
+ pub fyi_sent: bool,
+ /// Why a queued turn waits: "agent_busy", "server_busy" or "vm_busy".
+ pub queue_reason: Option<String>,
+ /// Who started the turn, when that is certain (see [`TurnSource`]).
+ pub source: Option<TurnSource>,
+}
+
+/// The longest `turn.source_name` sent: bot and routine names are the person's own text.
+pub const MAX_SOURCE_NAME_CHARS: usize = 100;
+
+/// Who started a turn, for the Why popover's "This turn" row ("from your message"). Set only where
+/// the start is certain: a chat message (the person's, or a bot's sent with its own token), a
+/// bot's hand-off, a routine's run. kwant has
+/// no webhook or app-event starts in v1, so "webhook" and "app_event" are reserved in the
+/// contract and never sent. Other turns (kwant's own follow-ups, a lead hearing its hand-offs'
+/// results, retries of parked turns) have no source, and the row reads without one.
+#[derive(Debug, Clone, PartialEq)]
+pub struct TurnSource {
+ /// "person", "bot" or "routine".
+ pub kind: &'static str,
+ /// The bot that handed the turn over, or the routine; never for "person".
+ pub name: Option<String>,
+}
+
+impl TurnSource {
+ pub fn person() -> Self {
+ Self { kind: "person", name: None }
+ }
+
+ /// Who sent a chat message that starts a turn: the person, or a bot posting with its own
+ /// token (its message is saved as sent by a bot; the token doesn't name the bot here).
+ pub fn sender(from_person: bool) -> Self {
+ if from_person {
+ Self::person()
+ } else {
+ Self { kind: "bot", name: None }
+ }
+ }
+
+ pub fn bot(name: &str) -> Self {
+ Self { kind: "bot", name: clean_name(name) }
+ }
+
+ pub fn routine(name: &str) -> Self {
+ Self { kind: "routine", name: clean_name(name) }
+ }
+}
+
+/// A name trimmed to one line of at most [`MAX_SOURCE_NAME_CHARS`]; `None` when blank.
+fn clean_name(name: &str) -> Option<String> {
+ let one_line: String = name.split_whitespace().collect::<Vec<_>>().join(" ");
+ let clipped: String = one_line.chars().take(MAX_SOURCE_NAME_CHARS).collect();
+ (!clipped.is_empty()).then_some(clipped)
+}
+
+impl TurnSignals {
+ /// Notes one streamed driver event. Tool events always count as a step; text, thinking and
+ /// driver progress at most once per [`STEP_BATCH_SECS`].
+ pub fn saw(&mut self, e: &RuntimeEvent, now: DateTime<Utc>) {
+ let (title, batched) = match e {
+ RuntimeEvent::ToolCallPending { name, .. } => (Some(Some(name.clone())), false),
+ RuntimeEvent::ToolCallCompleted { .. } => (None, false),
+ RuntimeEvent::TextDelta(_) | RuntimeEvent::ThinkingDelta(_) => (Some(None), true),
+ RuntimeEvent::Progress => (None, true),
+ _ => return,
+ };
+ // The engine answered: a stall's retry got through, and it streams after all
+ self.stalled = None;
+ self.live_steps = Some(true);
+ if batched && self.last_step_at.is_some_and(|t| now - t < Span::seconds(STEP_BATCH_SECS)) {
+ return;
+ }
+ self.last_step_at = Some(now);
+ if let Some(t) = title {
+ self.last_step_title = t;
+ }
+ }
+}
+
+/// A bot's turn stopped after the stall watchdog fired (`turn_stalled`).
+#[derive(Debug, Clone, PartialEq)]
+pub struct GaveUp {
+ pub at: DateTime<Utc>,
+ pub tries: u32,
+ pub secs: u64,
+ pub turn_id: String,
+ pub context_id: String,
+ pub thread_id: Option<String>,
+}
+
+#[derive(Debug, Clone, Default, PartialEq)]
+pub struct BotMarks {
+ pub gave_up: Option<GaveUp>,
+ pub last_finished_at: Option<DateTime<Utc>>,
+}
+
+/// A send that waits for its bot (H3): the person's message, or a bot's hand-off.
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct HeldItem {
+ /// "message" or "handoff".
+ pub kind: &'static str,
+ /// The user message id, or the delegation id.
+ pub id: String,
+ #[serde(skip)]
+ pub kwant_id: String,
+ pub since: DateTime<Utc>,
+ pub reason_code: &'static str,
+ pub context_id: String,
+}
+
+/// A client message id seen in a chat: when, and the message it saved (none while in flight).
+#[derive(Debug, Clone, PartialEq)]
+pub struct Sent {
+ pub at: DateTime<Utc>,
+ pub message_id: Option<String>,
+}
+
+#[derive(Debug, Default)]
+pub struct Board {
+ pub signals: HashMap<String, TurnSignals>,
+ pub marks: HashMap<String, BotMarks>,
+ pub held: 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>,
+}
+
+impl Board {
+ pub fn nudge(&mut self, kwant_id: &str) {
+ self.nudged.insert(kwant_id.to_string());
+ }
+
+ pub fn take_nudged(&mut self) -> HashSet<String> {
+ std::mem::take(&mut self.nudged)
+ }
+
+ /// Reserves `key` (chat + client message id) for one send. `Err` with the first send when
+ /// it was seen within [`DEDUPE_MIN`].
+ pub fn reserve_send(&mut self, key: &str, now: DateTime<Utc>) -> Result<(), Sent> {
+ let window = Span::minutes(DEDUPE_MIN);
+ self.sent.retain(|_, s| now - s.at < window);
+ if let Some(s) = self.sent.get(key) {
+ return Err(s.clone());
+ }
+ self.sent.insert(key.to_string(), Sent { at: now, message_id: None });
+ Ok(())
+ }
+
+ pub fn send_saved(&mut self, key: &str, message_id: &str) {
+ if let Some(s) = self.sent.get_mut(key) {
+ s.message_id = Some(message_id.to_string());
+ }
+ }
+
+ /// The send failed before it was saved: the id may be sent again.
+ pub fn release_send(&mut self, key: &str) {
+ if self.sent.get(key).is_some_and(|s| s.message_id.is_none()) {
+ self.sent.remove(key);
+ }
+ }
+}
+
+/// A client message id is 1–100 characters of `[A-Za-z0-9_.:-]`.
+pub fn valid_client_id(id: &str) -> bool {
+ !id.is_empty()
+ && id.chars().count() <= MAX_CLIENT_ID_CHARS
+ && id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | ':' | '-'))
+}
+
+/// The short engine name the copy uses ("the model (Claude)").
+pub fn engine_label(e: crate::drivers::engines::EngineId) -> &'static str {
+ use crate::drivers::engines::EngineId as E;
+ match e {
+ E::Claude | E::AnthropicApi => "Claude",
+ E::Codex | E::OpenaiApi => "Codex",
+ E::Grok | E::XaiApi => "Grok",
+ E::Ollama => "Ollama",
+ E::CustomApi => "Custom API",
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// The status object
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct WaitsOn {
+ /// "model", "tool", "person", "bot", "queue" or "budget".
+ pub kind: &'static str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub label: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct TurnRef {
+ pub turn_id: String,
+ pub context_id: String,
+ pub thread_id: Option<String>,
+ pub started_at: DateTime<Utc>,
+ pub live_steps: bool,
+ /// "person", "bot" or "routine"; omitted when not certain (see [`TurnSource`]).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub source: Option<&'static str>,
+ /// The bot or routine that started the turn; omitted for "person" and when unknown.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub source_name: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct Queue {
+ pub position: usize,
+ pub reason: String,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct Quiet {
+ /// "short" (5–14 min) or "long" (15 min and more).
+ pub level: &'static str,
+ pub snoozed_until: Option<DateTime<Utc>>,
+ pub muted: bool,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct Retry {
+ pub at: DateTime<Utc>,
+ #[serde(rename = "try")]
+ pub attempt: u32,
+ pub of: u32,
+ pub stall_secs: u64,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct Stuck {
+ pub gave_up_at: DateTime<Utc>,
+ pub tries: u32,
+ pub stall_secs: u64,
+ pub turn_id: String,
+ pub context_id: String,
+ pub thread_id: Option<String>,
+}
+
+/// An open question of the bot.
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct QuestionRef {
+ pub id: String,
+ pub asked_at: DateTime<Utc>,
+ pub context_id: String,
+ #[serde(skip)]
+ pub turn_id: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct Also {
+ pub status: &'static str,
+ pub reason_code: &'static str,
+ pub since: Option<DateTime<Utc>>,
+ pub context_id: String,
+ pub thread_id: Option<String>,
+}
+
+/// One bot's status, as the contract's §1 has it.
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct Status {
+ pub kwant_id: String,
+ /// "working", "queued", "needs_you", "quiet", "stuck", "paused" or "available".
+ pub status: &'static str,
+ pub reason_code: &'static str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub reason_text: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub since: Option<DateTime<Utc>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub last_step_at: Option<DateTime<Utc>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub last_step_title: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub waits_on: Option<WaitsOn>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub turn: Option<TurnRef>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub queue: Option<Queue>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub quiet: Option<Quiet>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub retry: Option<Retry>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub stuck: Option<Stuck>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub question: Option<QuestionRef>,
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub also: Vec<Also>,
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub held: Vec<HeldItem>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub last_finished_at: Option<DateTime<Utc>>,
+}
+
+impl Status {
+ fn new(kwant_id: &str, status: &'static str, reason_code: &'static str, since: Option<DateTime<Utc>>) -> Self {
+ Self {
+ kwant_id: kwant_id.to_string(),
+ status,
+ reason_code,
+ reason_text: None,
+ since,
+ last_step_at: None,
+ last_step_title: None,
+ waits_on: None,
+ turn: None,
+ queue: None,
+ quiet: None,
+ retry: None,
+ stuck: None,
+ question: None,
+ also: Vec::new(),
+ held: Vec::new(),
+ last_finished_at: None,
+ }
+ }
+
+ /// What a push compares: everything but the last step, which moves on every step.
+ pub fn fingerprint(&self) -> Value {
+ let mut v = serde_json::to_value(self).unwrap_or(Value::Null);
+ if let Some(o) = v.as_object_mut() {
+ o.remove("last_step_at");
+ o.remove("last_step_title");
+ }
+ v
+ }
+}
+
+/// What a running turn waits on the person for.
+#[derive(Debug, Clone, PartialEq)]
+pub enum Wait {
+ Question(QuestionRef),
+ Approval(DateTime<Utc>),
+ Browser(DateTime<Utc>),
+}
+
+/// One turn of the bot, with its signals.
+#[derive(Debug, Clone)]
+pub struct TurnInput {
+ pub turn: ActiveTurn,
+ pub signals: TurnSignals,
+ pub wait: Option<Wait>,
+ /// The tool of the newest step that still runs.
+ pub running_tool: Option<String>,
+ /// 1 for the next of this bot's queued turns to start.
+ pub position: usize,
+}
+
+/// Everything [`compute`] needs about one bot.
+#[derive(Debug, Clone)]
+pub struct BotInput {
+ pub kwant_id: String,
+ pub turns: Vec<TurnInput>,
+ /// The bot's open questions, newest first; their turn may have ended.
+ pub questions: Vec<QuestionRef>,
+ pub marks: BotMarks,
+ pub held: Vec<HeldItem>,
+}
+
+fn is_handoff_tool(name: &str) -> bool {
+ name == "delegate" || name.ends_with("__delegate")
+}
+
+fn rank(status: &str) -> u8 {
+ match status {
+ "needs_you" => 0,
+ "stuck" => 1,
+ "quiet" => 2,
+ "working" => 3,
+ "queued" => 4,
+ _ => 5,
+ }
+}
+
+/// Whether a turn is past its quiet threshold, ignoring snoozes: `Some(level)` if so.
+fn quiet_level(t: &TurnInput, now: DateTime<Utc>) -> Option<&'static str> {
+ let live = t.signals.live_steps.unwrap_or(true);
+ let last = t.signals.last_step_at.unwrap_or(t.turn.since);
+ if live {
+ let idle = now - last;
+ (idle >= Span::minutes(QUIET_AFTER_MIN)).then_some(if idle >= Span::minutes(QUIET_LONG_MIN) { "long" } else { "short" })
+ } else {
+ (now - t.turn.since >= Span::minutes(NO_LIVE_QUIET_AFTER_MIN)).then_some("long")
+ }
+}
+
+fn quiet_allowed(s: &TurnSignals, now: DateTime<Utc>) -> bool {
+ !s.muted && s.snooze_until.is_none_or(|u| now >= u)
+}
+
+/// The status of one turn.
+fn turn_status(kwant_id: &str, t: &TurnInput, now: DateTime<Utc>) -> Status {
+ let sig = &t.signals;
+ let live = sig.live_steps.unwrap_or(true);
+ let model = || WaitsOn { kind: "model", label: sig.engine.map(str::to_string) };
+ let turn = TurnRef {
+ turn_id: t.turn.turn_id.clone(),
+ context_id: t.turn.context_id.clone(),
+ thread_id: t.turn.thread_id.clone(),
+ started_at: t.turn.since,
+ live_steps: live,
+ source: sig.source.as_ref().map(|s| s.kind),
+ source_name: sig.source.as_ref().and_then(|s| s.name.clone()),
+ };
+ if t.turn.state == "queued" {
+ let mut s = Status::new(kwant_id, "queued", "in_line", Some(t.turn.since));
+ s.waits_on = Some(WaitsOn { kind: "queue", label: Some(t.position.to_string()) });
+ s.queue = Some(Queue { position: t.position, reason: sig.queue_reason.clone().unwrap_or_else(|| "agent_busy".into()) });
+ s.turn = Some(turn);
+ return s;
+ }
+ let mut s = match &t.wait {
+ Some(Wait::Question(q)) => {
+ let mut s = Status::new(kwant_id, "needs_you", "asked_question", Some(q.asked_at));
+ s.question = Some(q.clone());
+ s.waits_on = Some(WaitsOn { kind: "person", label: None });
+ s
+ }
+ Some(Wait::Approval(at)) => {
+ let mut s = Status::new(kwant_id, "needs_you", "wants_ok", Some(*at));
+ s.waits_on = Some(WaitsOn { kind: "person", label: None });
+ s
+ }
+ Some(Wait::Browser(at)) => {
+ let mut s = Status::new(kwant_id, "needs_you", "needs_browser", Some(*at));
+ s.waits_on = Some(WaitsOn { kind: "person", label: None });
+ s
+ }
+ None => match &sig.stalled {
+ Some(st) => {
+ let mut s = Status::new(kwant_id, "stuck", "stalled_retrying", Some(st.at));
+ s.waits_on = Some(model());
+ s.retry = Some(Retry { at: st.at, attempt: 2, of: 2, stall_secs: st.secs });
+ s
+ }
+ None => {
+ let (code, text, waits) = match &t.running_tool {
+ Some(tool) if is_handoff_tool(tool) => ("waiting_for_bot", None, WaitsOn { kind: "bot", label: None }),
+ Some(tool) => ("running_tool", Some(tool.clone()), WaitsOn { kind: "tool", label: Some(tool.clone()) }),
+ None if !live => ("reports_at_end", None, model()),
+ None => ("thinking", None, model()),
+ };
+ let level = quiet_level(t, now);
+ let mut s = match level {
+ Some(_) if quiet_allowed(sig, now) => Status::new(
+ kwant_id,
+ "quiet",
+ if live { "no_step" } else { "no_live_steps" },
+ Some(sig.last_step_at.unwrap_or(t.turn.since)),
+ ),
+ _ => Status::new(kwant_id, "working", code, Some(t.turn.since)),
+ };
+ s.reason_text = text;
+ s.waits_on = Some(waits);
+ if level.is_some() || sig.muted || sig.snooze_until.is_some_and(|u| now < u) {
+ s.quiet = Some(Quiet {
+ level: level.unwrap_or("short"),
+ snoozed_until: sig.snooze_until.filter(|u| now < *u),
+ muted: sig.muted,
+ });
+ }
+ s
+ }
+ },
+ };
+ s.last_step_at = sig.last_step_at;
+ s.last_step_title = sig.last_step_title.clone();
+ s.turn = Some(turn);
+ s
+}
+
+/// The bot's status (contract §2): its most pressing turn, the others in `also`.
+pub fn compute(b: &BotInput, now: DateTime<Utc>) -> Status {
+ let mut parts: Vec<Status> = b.turns.iter().map(|t| turn_status(&b.kwant_id, t, now)).collect();
+ // An open question whose turn ended (a late answer starts a new turn) still waits on the person
+ if !parts.iter().any(|p| p.status == "needs_you") {
+ if let Some(q) = b.questions.iter().max_by_key(|q| q.asked_at) {
+ let mut s = Status::new(&b.kwant_id, "needs_you", "asked_question", Some(q.asked_at));
+ s.question = Some(q.clone());
+ s.waits_on = Some(WaitsOn { kind: "person", label: None });
+ parts.push(s);
+ }
+ }
+ if parts.is_empty() {
+ if let Some(g) = b.marks.gave_up.as_ref().filter(|g| now - g.at < Span::minutes(GAVE_UP_SHOWS_MIN)) {
+ let mut s = Status::new(&b.kwant_id, "stuck", "stalled_gave_up", Some(g.at));
+ s.stuck = Some(Stuck {
+ gave_up_at: g.at,
+ tries: g.tries,
+ stall_secs: g.secs,
+ turn_id: g.turn_id.clone(),
+ context_id: g.context_id.clone(),
+ thread_id: g.thread_id.clone(),
+ });
+ parts.push(s);
+ }
+ }
+ let started = |s: &Status| s.turn.as_ref().map(|t| t.started_at).or(s.since);
+ parts.sort_by(|a, b| rank(a.status).cmp(&rank(b.status)).then_with(|| started(b).cmp(&started(a))));
+ let mut parts = parts.into_iter();
+ let mut out = parts.next().unwrap_or_else(|| Status::new(&b.kwant_id, "available", "idle", b.marks.last_finished_at));
+ out.also = parts
+ .take(MAX_ALSO)
+ .map(|p| {
+ let (context_id, thread_id) = match (&p.turn, &p.question) {
+ (Some(t), _) => (t.context_id.clone(), t.thread_id.clone()),
+ (None, Some(q)) => (q.context_id.clone(), None),
+ _ => (String::new(), None),
+ };
+ Also { status: p.status, reason_code: p.reason_code, since: p.since, context_id, thread_id }
+ })
+ .collect();
+ out.held = b.held.clone();
+ out.last_finished_at = b.marks.last_finished_at;
+ out
+}
+
+/// Why a send in `context_id` to this bot waits (contract §7a), or `None` to send it now.
+#[derive(Debug, Clone, PartialEq)]
+pub struct HoldReason {
+ /// "stuck" or "waits_on_you".
+ pub reason_code: &'static str,
+ pub since: DateTime<Utc>,
+ pub question: Option<QuestionRef>,
+}
+
+pub fn hold_reason(b: &BotInput, context_id: &str, now: DateTime<Utc>) -> Option<HoldReason> {
+ for t in b.turns.iter().filter(|t| t.turn.state == "running") {
+ if let Some(st) = &t.signals.stalled {
+ return Some(HoldReason { reason_code: "stuck", since: st.at, question: None });
+ }
+ }
+ if b.turns.iter().all(|t| t.turn.state != "running") {
+ if let Some(g) = b.marks.gave_up.as_ref().filter(|g| now - g.at < Span::minutes(GAVE_UP_SHOWS_MIN)) {
+ return Some(HoldReason { reason_code: "stuck", since: g.at, question: None });
+ }
+ }
+ // Only a turn that still runs and waits blocks the bot; an old open question doesn't
+ for t in b.turns.iter().filter(|t| t.turn.state == "running") {
+ match &t.wait {
+ // A message where the bot asked is the answer, never held
+ Some(Wait::Question(q)) if q.context_id == context_id => {}
+ Some(Wait::Question(q)) => {
+ return Some(HoldReason { reason_code: "waits_on_you", since: q.asked_at, question: Some(q.clone()) })
+ }
+ Some(Wait::Approval(at)) | Some(Wait::Browser(at)) => {
+ return Some(HoldReason { reason_code: "waits_on_you", since: *at, question: None })
+ }
+ None => {}
+ }
+ }
+ None
+}
+
+/// A live-engine turn that is quiet 15 min and hasn't been told about yet: send the FYI.
+pub fn fyi_due(t: &TurnInput, now: DateTime<Utc>) -> bool {
+ t.turn.state == "running"
+ && t.wait.is_none()
+ && t.signals.stalled.is_none()
+ && !t.signals.fyi_sent
+ && t.signals.live_steps.unwrap_or(true)
+ && quiet_allowed(&t.signals, now)
+ && quiet_level(t, now) == Some("long")
+}
+
+// ---------------------------------------------------------------------------------------------
+// Gathering from the server
+
+fn context_of(q: &crate::db::questions::Question) -> String {
+ q.thread_id.clone().or_else(|| q.channel_id.clone()).or_else(|| q.direct_kwant_id.clone()).unwrap_or_default()
+}
+
+fn parse_time(s: &str) -> Option<DateTime<Utc>> {
+ DateTime::parse_from_rfc3339(s).ok().map(|t| t.with_timezone(&Utc))
+}
+
+/// The inputs of `kwant_ids`, all in `space`.
+pub async fn inputs(state: &AppState, space: &SpaceId, kwant_ids: &[String]) -> Vec<BotInput> {
+ let turns = state.turns.active_turns();
+ let questions = state.db.list_questions(Some("open"), None, Some(space)).await.unwrap_or_default();
+ let (signals, marks, held) = state.turns.board(|b| {
+ let wanted: HashSet<&str> = kwant_ids.iter().map(String::as_str).collect();
+ let signals: HashMap<String, TurnSignals> = turns
+ .iter()
+ .filter(|t| wanted.contains(t.kwant_id.as_str()))
+ .filter_map(|t| b.signals.get(&t.turn_id).map(|s| (t.turn_id.clone(), s.clone())))
+ .collect();
+ (signals, b.marks.clone(), b.held.clone())
+ });
+ kwant_ids
+ .iter()
+ .map(|k| {
+ let mine: Vec<&ActiveTurn> = turns.iter().filter(|t| &t.kwant_id == k).collect();
+ let mut queued: Vec<&ActiveTurn> = mine.iter().copied().filter(|t| t.state == "queued").collect();
+ queued.sort_by_key(|t| t.since);
+ let qs: Vec<QuestionRef> = questions
+ .iter()
+ .filter(|q| &q.kwant_id == k)
+ .map(|q| QuestionRef { id: q.id.clone(), asked_at: q.created_at, context_id: context_of(q), turn_id: q.turn_id.clone() })
+ .collect();
+ let turns = mine
+ .iter()
+ .map(|t| {
+ let waits = super::activity::turn_waits(&t.turn_id);
+ let wait = qs
+ .iter()
+ .find(|q| q.turn_id.as_deref() == Some(t.turn_id.as_str()))
+ .map(|q| Wait::Question(q.clone()))
+ .or_else(|| {
+ waits.waiting.map(|(kind, at)| {
+ let at = parse_time(&at).unwrap_or(t.since);
+ if kind == "human_step" { Wait::Browser(at) } else { Wait::Approval(at) }
+ })
+ });
+ TurnInput {
+ turn: (*t).clone(),
+ signals: signals.get(&t.turn_id).cloned().unwrap_or_default(),
+ wait,
+ running_tool: waits.running_tool,
+ position: queued.iter().position(|q| q.turn_id == t.turn_id).map_or(0, |i| i + 1),
+ }
+ })
+ .collect();
+ BotInput {
+ kwant_id: k.clone(),
+ turns,
+ questions: qs,
+ marks: marks.get(k).cloned().unwrap_or_default(),
+ held: held.iter().filter(|h| &h.kwant_id == k).cloned().collect(),
+ }
+ })
+ .collect()
+}
+
+async fn input_of(state: &AppState, kwant_id: &str) -> Option<BotInput> {
+ let space = state.db.space_of_kwant(kwant_id).await.ok().flatten().unwrap_or_else(SpaceId::default_space);
+ inputs(state, &space, &[kwant_id.to_string()]).await.pop()
+}
+
+pub async fn status_of(state: &AppState, kwant_id: &str) -> Option<Status> {
+ Some(compute(&input_of(state, kwant_id).await?, Utc::now()))
+}
+
+// ---------------------------------------------------------------------------------------------
+// H3: holding a send, and releasing it
+
+/// Holds the send `item_id` ("message" or "handoff") to `kwant` in `context_id` when the bot is
+/// stuck or waits on the person elsewhere; the `held` object the response carries, or `None`
+/// to send it now. Run its turn after [`wait_released`].
+pub async fn hold(state: &AppState, kwant: &crate::db::models::Kwant, context_id: &str, kind: &'static str, item_id: &str) -> Option<Value> {
+ let input = inputs(state, &SpaceId::new(&kwant.space_id), std::slice::from_ref(&kwant.id)).await.pop()?;
+ let r = hold_reason(&input, context_id, Utc::now())?;
+ state.turns.board(|b| {
+ b.held.push(HeldItem {
+ kind,
+ id: item_id.to_string(),
+ kwant_id: kwant.id.clone(),
+ since: Utc::now(),
+ reason_code: r.reason_code,
+ context_id: context_id.to_string(),
+ });
+ b.nudge(&kwant.id);
+ });
+ tracing::info!(kwant = %kwant.id, kind, reason = r.reason_code, "send held until the bot can take it");
+ Some(held_view(kwant, &r))
+}
+
+fn held_view(kwant: &crate::db::models::Kwant, r: &HoldReason) -> Value {
+ let mut v = json!({ "kwant_id": kwant.id, "kwant_name": kwant.name, "reason_code": r.reason_code, "since": r.since });
+ if let Some(q) = &r.question {
+ v["question"] = json!(q);
+ }
+ v
+}
+
+/// 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.
+pub async fn wait_released(state: &AppState, item_id: &str, cancel: &CancellationToken) -> bool {
+ 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);
+ })
+ };
+ loop {
+ tokio::select! {
+ _ = cancel.cancelled() => {
+ unhold();
+ return false;
+ }
+ _ = tokio::time::sleep(HOLD_POLL) => {}
+ }
+ 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();
+ tracing::info!(kwant = %item.kwant_id, kind = item.kind, "held send released");
+ return true;
+ }
+ }
+}
+
+/// What a bot that hands work to a held bot is told (tool result text).
+pub fn handoff_held_text(name: &str, reason_code: &str) -> String {
+ if reason_code == "stuck" {
+ format!("{name} is stuck right now, so your request is queued, not lost. Don't send it again. It goes to {name} when {name} runs again.")
+ } else {
+ format!("{name} is waiting for the person to answer, so your request is queued, not lost. Don't send it again. It goes to {name} after the person answers.")
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Push
+
+fn kwant_of(e: &RuntimeEvent) -> Option<String> {
+ match e {
+ RuntimeEvent::TurnStarted { kwant_id, .. } | RuntimeEvent::TurnEnded { kwant_id, .. } | RuntimeEvent::TurnQueued { kwant_id, .. } => {
+ Some(kwant_id.clone())
+ }
+ RuntimeEvent::QuestionUpdated { question: v } | RuntimeEvent::HumanStepUpdated { step: v } => v["kwant_id"].as_str().map(str::to_string),
+ RuntimeEvent::Scoped { tag, event } => match event.as_ref() {
+ RuntimeEvent::Activity { .. } | RuntimeEvent::ApprovalRequired { .. } | RuntimeEvent::ApprovalWithdrawn { .. } => Some(tag.kwant_id.clone()),
+ _ => None,
+ },
+ _ => None,
+ }
+}
+
+/// Sends `bot_status` whenever a bot's status changes, and the quiet FYI once per turn.
+pub fn spawn_watcher(state: AppState) -> tokio::task::JoinHandle<()> {
+ let mut rx = state.event_sender.subscribe();
+ tokio::spawn(async move {
+ let mut last: HashMap<String, Value> = HashMap::new();
+ let mut dirty: HashSet<String> = HashSet::new();
+ let mut tick = tokio::time::interval(std::time::Duration::from_secs(1));
+ let mut sweep = tokio::time::interval(WATCH_SWEEP);
+ loop {
+ tokio::select! {
+ e = rx.recv() => match e {
+ Ok(e) => dirty.extend(kwant_of(&e)),
+ Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => dirty.extend(busy(&state, &last)),
+ Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
+ },
+ _ = sweep.tick() => dirty.extend(busy(&state, &last)),
+ _ = tick.tick() => {
+ dirty.extend(state.turns.board(|b| b.take_nudged()));
+ for k in std::mem::take(&mut dirty) {
+ push(&state, &k, &mut last).await;
+ }
+ }
+ }
+ }
+ })
+}
+
+/// Bots that may change on their own: running turns, gave-up marks, held sends, the last pushed.
+fn busy(state: &AppState, last: &HashMap<String, Value>) -> HashSet<String> {
+ let mut out: HashSet<String> = state.turns.active_turns().into_iter().map(|t| t.kwant_id).collect();
+ out.extend(last.keys().cloned());
+ state.turns.board(|b| {
+ out.extend(b.marks.iter().filter(|(_, m)| m.gave_up.is_some()).map(|(k, _)| k.clone()));
+ out.extend(b.held.iter().map(|h| h.kwant_id.clone()));
+ });
+ out
+}
+
+async fn push(state: &AppState, kwant_id: &str, last: &mut HashMap<String, Value>) {
+ let Some(input) = input_of(state, kwant_id).await else { return };
+ let now = Utc::now();
+ for t in input.turns.iter().filter(|t| fyi_due(t, now)) {
+ let first = state.turns.board(|b| match b.signals.get_mut(&t.turn.turn_id) {
+ Some(s) if !s.fyi_sent => {
+ s.fyi_sent = true;
+ true
+ }
+ _ => false,
+ });
+ if first {
+ let n = super::continuity::turn_quiet(state, kwant_id, Some(t.turn.context_id.as_str())).await;
+ super::continuity::notify(state, n).await;
+ }
+ }
+ let status = compute(&input, now);
+ let fp = status.fingerprint();
+ if last.get(kwant_id) == Some(&fp) {
+ return;
+ }
+ if status.status == "available" {
+ // Nothing pushed yet means the client already shows it as available
+ if last.remove(kwant_id).is_none() {
+ return;
+ }
+ } else {
+ last.insert(kwant_id.to_string(), fp);
+ }
+ let _ = state.event_sender.send(RuntimeEvent::BotStatus { kwant_id: kwant_id.to_string(), status: json!(status) });
+}
+
+// ---------------------------------------------------------------------------------------------
+// Routes
+
+/// `GET /api/bots/status?space=`: every bot of the space with its status object.
+pub async fn list(State(state): State<AppState>, super::spaces::Scope(space): super::spaces::Scope) -> Response {
+ let kwants = match state.db.list_kwants(&space).await {
+ Ok(k) => k,
+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ };
+ let ids: Vec<String> = kwants.into_iter().map(|k| k.id).collect();
+ let now = Utc::now();
+ let bots: Vec<Status> = inputs(&state, &space, &ids).await.iter().map(|b| compute(b, now)).collect();
+ Json(json!({ "bots": bots, "now": now })).into_response()
+}
+
+#[derive(Debug, Deserialize)]
+pub struct QuietAction {
+ pub action: String,
+}
+
+/// `POST /api/turns/:turn_id/quiet` `{action: "snooze" | "mute"}`, the person only.
+pub async fn quiet(State(state): State<AppState>, headers: HeaderMap, Path(turn_id): Path<String>, Json(body): Json<QuietAction>) -> Response {
+ if let Err(r) = super::mcp_suggest::refuse_agent_tokens(&state, &headers, "only the person can snooze a bot's quiet signal").await {
+ return r;
+ }
+ let Some(turn) = state.turns.active_turns().into_iter().find(|t| t.turn_id == turn_id && t.state == "running") else {
+ return (StatusCode::NOT_FOUND, Json(json!({ "error": "That turn isn't running." }))).into_response();
+ };
+ let now = Utc::now();
+ let set = |b: &mut Board, f: &dyn Fn(&mut TurnSignals)| {
+ f(b.signals.entry(turn_id.clone()).or_default());
+ b.nudge(&turn.kwant_id);
+ };
+ match body.action.as_str() {
+ "snooze" => state.turns.board(|b| set(b, &|s| s.snooze_until = Some(now + Span::minutes(SNOOZE_MIN)))),
+ "mute" => state.turns.board(|b| set(b, &|s| s.muted = true)),
+ _ => return (StatusCode::BAD_REQUEST, Json(json!({ "error": "action is snooze or mute" }))).into_response(),
+ }
+ Json(json!(status_of(&state, &turn.kwant_id).await)).into_response()
+}
+
+/// `POST /api/kwants/:id/status/retry` ("Try again"), the person only: the bot is no longer
+/// stuck, so the sends held for that go now.
+pub async fn retry(State(state): State<AppState>, headers: HeaderMap, Path(kwant_id): Path<String>) -> Response {
+ if let Err(r) = super::mcp_suggest::refuse_agent_tokens(&state, &headers, "only the person can retry a stuck bot").await {
+ return r;
+ }
+ match state.db.get_kwant(&kwant_id).await {
+ Ok(Some(_)) => {}
+ Ok(None) => return StatusCode::NOT_FOUND.into_response(),
+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ }
+ let released = state.turns.board(|b| {
+ if let Some(m) = b.marks.get_mut(&kwant_id) {
+ m.gave_up = None;
+ }
+ b.nudge(&kwant_id);
+ b.held.iter().filter(|h| h.kwant_id == kwant_id && h.reason_code == "stuck").count()
+ });
+ Json(json!({ "released": released, "status": status_of(&state, &kwant_id).await })).into_response()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn at(min: i64) -> DateTime<Utc> {
+ DateTime::parse_from_rfc3339("2026-11-10T14:00:00Z").unwrap().with_timezone(&Utc) + Span::minutes(min)
+ }
+
+ fn running(id: &str, since: DateTime<Utc>) -> TurnInput {
+ TurnInput {
+ turn: ActiveTurn {
+ turn_id: id.into(),
+ kwant_id: "k1".into(),
+ context_id: "c1".into(),
+ thread_id: None,
+ state: "running".into(),
+ since,
+ purpose: None,
+ },
+ signals: TurnSignals { engine: Some("Claude"), live_steps: Some(true), ..Default::default() },
+ wait: None,
+ running_tool: None,
+ position: 0,
+ }
+ }
+
+ fn bot(turns: Vec<TurnInput>) -> BotInput {
+ BotInput { kwant_id: "k1".into(), turns, questions: Vec::new(), marks: BotMarks::default(), held: Vec::new() }
+ }
+
+ fn question(id: &str, ctx: &str, asked: DateTime<Utc>, turn: Option<&str>) -> QuestionRef {
+ QuestionRef { id: id.into(), asked_at: asked, context_id: ctx.into(), turn_id: turn.map(str::to_string) }
+ }
+
+ #[test]
+ fn working_since_the_turn_start_and_waits_on_the_model() {
+ let mut t = running("t1", at(0));
+ t.signals.last_step_at = Some(at(3));
+ let s = compute(&bot(vec![t]), at(4));
+ assert_eq!((s.status, s.reason_code), ("working", "thinking"));
+ assert_eq!(s.since, Some(at(0)), "Working counts from the turn start, not the last step");
+ assert_eq!(s.last_step_at, Some(at(3)));
+ assert_eq!(s.waits_on, Some(WaitsOn { kind: "model", label: Some("Claude".into()) }));
+ assert_eq!(s.turn.as_ref().unwrap().turn_id, "t1");
+ assert!(s.quiet.is_none());
+ }
+
+ #[test]
+ fn a_running_tool_is_the_reason_and_its_name_the_only_text() {
+ let mut t = running("t1", at(0));
+ t.running_tool = Some("Bash".into());
+ t.signals.last_step_at = Some(at(1));
+ let s = compute(&bot(vec![t.clone()]), at(2));
+ assert_eq!((s.status, s.reason_code, s.reason_text.as_deref()), ("working", "running_tool", Some("Bash")));
+ assert_eq!(s.waits_on.unwrap().kind, "tool");
+ t.running_tool = Some("mcp__kwnt__delegate".into());
+ let s = compute(&bot(vec![t]), at(2));
+ assert_eq!((s.reason_code, s.reason_text), ("waiting_for_bot", None));
+ }
+
+ #[test]
+ fn quiet_starts_at_5_minutes_without_a_step_and_is_long_from_15() {
+ let mut t = running("t1", at(0));
+ t.signals.last_step_at = Some(at(10));
+ let b = bot(vec![t]);
+ let at_min = |m: i64, secs: i64| compute(&b, at(m) + Span::seconds(secs));
+ assert_eq!(at_min(14, 59).status, "working", "4 min 59 s is not quiet yet");
+ let s = at_min(15, 0);
+ assert_eq!((s.status, s.reason_code), ("quiet", "no_step"));
+ assert_eq!(s.since, Some(at(10)), "Quiet counts from the last step");
+ assert_eq!(s.quiet.as_ref().unwrap().level, "short");
+ assert_eq!(at_min(24, 59).quiet.unwrap().level, "short");
+ assert_eq!(at_min(25, 0).quiet.unwrap().level, "long");
+ }
+
+ #[test]
+ fn a_turn_with_no_step_yet_is_quiet_from_its_start() {
+ let s = compute(&bot(vec![running("t1", at(0))]), at(5));
+ assert_eq!((s.status, s.since), ("quiet", Some(at(0))));
+ }
+
+ #[test]
+ fn an_end_only_engine_is_quiet_only_at_15_minutes() {
+ let mut t = running("t1", at(0));
+ t.signals.live_steps = Some(false);
+ t.signals.engine = Some("Codex");
+ let b = bot(vec![t]);
+ let s = compute(&b, at(12));
+ assert_eq!((s.status, s.reason_code), ("working", "reports_at_end"));
+ assert!(!s.turn.as_ref().unwrap().live_steps);
+ let s = compute(&b, at(15));
+ assert_eq!((s.status, s.reason_code, s.since), ("quiet", "no_live_steps", Some(at(0))));
+ assert_eq!(s.quiet.unwrap().level, "long");
+ assert!(!fyi_due(&b.turns[0], at(20)), "no FYI for an engine that is always quiet");
+ }
+
+ #[test]
+ fn steps_move_the_clock_tools_always_text_every_10_seconds() {
+ let mut s = TurnSignals { live_steps: Some(false), ..Default::default() };
+ let t0 = at(0);
+ s.saw(&RuntimeEvent::TextDelta("a".into()), t0);
+ assert_eq!((s.last_step_at, s.live_steps), (Some(t0), Some(true)), "a streamed step proves live steps");
+ s.saw(&RuntimeEvent::TextDelta("b".into()), t0 + Span::seconds(9));
+ assert_eq!(s.last_step_at, Some(t0), "text within 10 s is batched");
+ s.saw(&RuntimeEvent::ToolCallPending { id: "1".into(), name: "Bash".into(), args: json!({}) }, t0 + Span::seconds(9));
+ assert_eq!((s.last_step_at, s.last_step_title.as_deref()), (Some(t0 + Span::seconds(9)), Some("Bash")));
+ s.saw(&RuntimeEvent::ThinkingDelta("hm".into()), t0 + Span::seconds(20));
+ assert_eq!((s.last_step_at, s.last_step_title.as_deref()), (Some(t0 + Span::seconds(20)), None));
+ s.saw(&RuntimeEvent::UsageSoFar { fresh: 5 }, t0 + Span::seconds(60));
+ assert_eq!(s.last_step_at, Some(t0 + Span::seconds(20)), "usage isn't a step");
+ }
+
+ #[test]
+ fn snooze_and_mute_hold_quiet_back_for_this_turn() {
+ let mut t = running("t1", at(0));
+ t.signals.snooze_until = Some(at(35));
+ let s = compute(&bot(vec![t.clone()]), at(20));
+ assert_eq!(s.status, "working");
+ assert_eq!(s.quiet.as_ref().unwrap().snoozed_until, Some(at(35)));
+ assert!(!fyi_due(&t, at(20)));
+ assert_eq!(compute(&bot(vec![t.clone()]), at(35)).status, "quiet", "the snooze ran out");
+ t.signals.snooze_until = None;
+ t.signals.muted = true;
+ let s = compute(&bot(vec![t]), at(90));
+ assert_eq!(s.status, "working");
+ assert!(s.quiet.unwrap().muted);
+ }
+
+ #[test]
+ fn the_fyi_is_due_once_at_15_minutes() {
+ let mut t = running("t1", at(0));
+ t.signals.last_step_at = Some(at(1));
+ assert!(!fyi_due(&t, at(15)));
+ assert!(fyi_due(&t, at(16)));
+ t.signals.fyi_sent = true;
+ assert!(!fyi_due(&t, at(30)));
+ }
+
+ #[test]
+ fn a_stall_is_stuck_retrying_from_when_it_fired() {
+ let mut t = running("t1", at(0));
+ t.signals.stalled = Some(Stall { at: at(2), secs: 120 });
+ let s = compute(&bot(vec![t.clone()]), at(3));
+ assert_eq!((s.status, s.reason_code, s.since), ("stuck", "stalled_retrying", Some(at(2))));
+ assert_eq!(s.retry, Some(Retry { at: at(2), attempt: 2, of: 2, stall_secs: 120 }));
+ let wire = json!(s);
+ assert_eq!(wire["retry"]["try"], 2);
+ // The retry answered
+ t.signals.saw(&RuntimeEvent::Progress, at(3));
+ assert_eq!(compute(&bot(vec![t]), at(3)).status, "working");
+ }
+
+ #[test]
+ fn a_turn_that_gave_up_keeps_the_bot_stuck_for_30_minutes() {
+ let mut b = bot(Vec::new());
+ b.marks.gave_up = Some(GaveUp { at: at(0), tries: 2, secs: 120, turn_id: "t1".into(), context_id: "c1".into(), thread_id: None });
+ b.marks.last_finished_at = Some(at(0));
+ let s = compute(&b, at(29));
+ assert_eq!((s.status, s.reason_code, s.since), ("stuck", "stalled_gave_up", Some(at(0))));
+ assert_eq!(s.stuck.as_ref().unwrap().tries, 2);
+ let s = compute(&b, at(30));
+ assert_eq!((s.status, s.reason_code, s.since), ("available", "idle", Some(at(0))));
+ assert_eq!(s.last_finished_at, Some(at(0)));
+ }
+
+ #[test]
+ fn needs_you_reasons_and_since() {
+ let mut t = running("t1", at(0));
+ t.wait = Some(Wait::Question(question("q1", "c1", at(3), Some("t1"))));
+ let s = compute(&bot(vec![t.clone()]), at(30));
+ assert_eq!((s.status, s.reason_code, s.since), ("needs_you", "asked_question", Some(at(3))));
+ assert_eq!(s.question.as_ref().unwrap().id, "q1");
+ assert_eq!(s.waits_on.as_ref().unwrap().kind, "person");
+ t.wait = Some(Wait::Approval(at(4)));
+ assert_eq!(compute(&bot(vec![t.clone()]), at(30)).reason_code, "wants_ok");
+ t.wait = Some(Wait::Browser(at(4)));
+ let s = compute(&bot(vec![t]), at(30));
+ assert_eq!((s.reason_code, s.since), ("needs_browser", Some(at(4))));
+ }
+
+ #[test]
+ fn an_open_question_of_an_ended_turn_still_needs_you() {
+ let mut b = bot(Vec::new());
+ b.questions = vec![question("q1", "c9", at(1), Some("gone"))];
+ let s = compute(&b, at(2));
+ assert_eq!((s.status, s.reason_code, s.since), ("needs_you", "asked_question", Some(at(1))));
+ assert!(s.turn.is_none());
+ }
+
+ #[test]
+ fn queued_has_its_place_in_line() {
+ let mut t = running("t1", at(1));
+ t.turn.state = "queued".into();
+ t.position = 2;
+ t.signals.queue_reason = Some("server_busy".into());
+ let s = compute(&bot(vec![t]), at(2));
+ assert_eq!((s.status, s.reason_code, s.since), ("queued", "in_line", Some(at(1))));
+ assert_eq!(s.queue, Some(Queue { position: 2, reason: "server_busy".into() }));
+ }
+
+ #[test]
+ fn available_with_nothing_running() {
+ let s = compute(&bot(Vec::new()), at(0));
+ assert_eq!((s.status, s.reason_code, s.since), ("available", "idle", None));
+ let wire = json!(s);
+ assert!(wire.get("since").is_none() && wire.get("turn").is_none(), "{wire}");
+ }
+
+ #[test]
+ fn several_turns_show_the_most_pressing_then_the_newest() {
+ let mut quiet = running("t1", at(0));
+ quiet.signals.last_step_at = Some(at(0));
+ let mut working = running("t2", at(9));
+ working.signals.last_step_at = Some(at(9));
+ working.turn.context_id = "c2".into();
+ let mut newer = running("t3", at(10));
+ newer.signals.last_step_at = Some(at(10));
+ newer.turn.context_id = "c3".into();
+ let mut asked = running("t4", at(1));
+ asked.wait = Some(Wait::Approval(at(2)));
+ let s = compute(&bot(vec![working.clone(), quiet.clone(), newer.clone()]), at(10));
+ assert_eq!((s.status, s.turn.as_ref().unwrap().turn_id.as_str()), ("quiet", "t1"));
+ assert_eq!(s.also.iter().map(|a| a.context_id.as_str()).collect::<Vec<_>>(), ["c3", "c2"], "newest first");
+ let s = compute(&bot(vec![working, quiet, newer, asked]), at(10));
+ assert_eq!(s.status, "needs_you");
+ assert_eq!(s.also.len(), MAX_ALSO);
+ }
+
+ #[test]
+ fn a_push_ignores_step_moves_but_not_status_moves() {
+ let mut t = running("t1", at(0));
+ t.signals.last_step_at = Some(at(1));
+ let a = compute(&bot(vec![t.clone()]), at(2)).fingerprint();
+ t.signals.last_step_at = Some(at(2));
+ t.signals.last_step_title = Some("Read".into());
+ assert_eq!(a, compute(&bot(vec![t.clone()]), at(2)).fingerprint());
+ t.running_tool = Some("Read".into());
+ assert_ne!(a, compute(&bot(vec![t]), at(2)).fingerprint());
+ }
+
+ // H3
+
+ #[test]
+ fn a_send_to_a_stuck_bot_is_held() {
+ let mut t = running("t1", at(0));
+ t.signals.stalled = Some(Stall { at: at(2), secs: 120 });
+ let r = hold_reason(&bot(vec![t]), "c5", at(3)).unwrap();
+ assert_eq!((r.reason_code, r.since), ("stuck", at(2)));
+
+ let mut b = bot(Vec::new());
+ b.marks.gave_up = Some(GaveUp { at: at(0), tries: 2, secs: 120, turn_id: "t1".into(), context_id: "c1".into(), thread_id: None });
+ assert_eq!(hold_reason(&b, "c1", at(5)).unwrap().reason_code, "stuck", "gave up, even in its own chat");
+ assert!(hold_reason(&b, "c1", at(30)).is_none(), "the gave-up window ended");
+ }
+
+ #[test]
+ fn a_send_to_a_bot_waiting_on_the_person_is_held_unless_it_is_the_answer() {
+ let mut t = running("t1", at(0));
+ t.wait = Some(Wait::Question(question("q1", "c1", at(3), Some("t1"))));
+ let b = bot(vec![t.clone()]);
+ let r = hold_reason(&b, "c2", at(4)).unwrap();
+ assert_eq!((r.reason_code, r.since), ("waits_on_you", at(3)));
+ assert_eq!(r.question.unwrap().id, "q1");
+ assert!(hold_reason(&b, "c1", at(4)).is_none(), "where it asked, the message is the answer");
+ t.wait = Some(Wait::Approval(at(5)));
+ assert_eq!(hold_reason(&bot(vec![t]), "c1", at(6)).unwrap().reason_code, "waits_on_you");
+ }
+
+ #[test]
+ fn an_old_open_question_or_a_busy_bot_does_not_hold() {
+ let mut b = bot(vec![running("t2", at(0))]);
+ b.questions = vec![question("q1", "c9", at(1), Some("gone"))];
+ assert!(hold_reason(&b, "c2", at(2)).is_none(), "the asking turn ended: a new message starts a turn");
+ let mut quiet = running("t3", at(0));
+ quiet.signals.last_step_at = Some(at(0));
+ assert!(hold_reason(&bot(vec![quiet]), "c2", at(40)).is_none(), "quiet isn't stuck");
+ }
+
+ #[test]
+ fn the_same_client_id_in_a_chat_goes_once_within_10_minutes() {
+ let mut b = Board::default();
+ assert!(b.reserve_send("c1|m1", at(0)).is_ok());
+ b.send_saved("c1|m1", "msg1");
+ let first = b.reserve_send("c1|m1", at(9)).unwrap_err();
+ assert_eq!((first.at, first.message_id.as_deref()), (at(0), Some("msg1")));
+ assert!(b.reserve_send("c2|m1", at(9)).is_ok(), "another chat is another send");
+ assert!(b.reserve_send("c1|m1", at(10)).is_ok(), "the window is 10 minutes");
+ }
+
+ #[test]
+ fn a_send_that_failed_before_saving_may_go_again() {
+ let mut b = Board::default();
+ assert!(b.reserve_send("c1|m1", at(0)).is_ok());
+ assert!(b.reserve_send("c1|m1", at(0)).is_err(), "in flight");
+ b.release_send("c1|m1");
+ assert!(b.reserve_send("c1|m1", at(0)).is_ok());
+ b.send_saved("c1|m1", "msg1");
+ b.release_send("c1|m1");
+ assert!(b.reserve_send("c1|m1", at(1)).is_err(), "a saved send is never released");
+ }
+
+ #[test]
+ fn client_ids_are_short_and_plain() {
+ assert!(valid_client_id("01HF-x_y.z:1"));
+ assert!(!valid_client_id(""));
+ assert!(!valid_client_id("a b"));
+ assert!(!valid_client_id("ü"));
+ assert!(!valid_client_id(&"a".repeat(101)));
+ assert!(valid_client_id(&"a".repeat(100)));
+ }
+
+ #[test]
+ fn the_sending_bot_is_told_it_is_queued_not_lost() {
+ assert_eq!(
+ handoff_held_text("Lin", "waits_on_you"),
+ "Lin is waiting for the person to answer, so your request is queued, not lost. Don't send it again. It goes to Lin after the person answers."
+ );
+ assert!(handoff_held_text("Juno", "stuck").starts_with("Juno is stuck right now"));
+ }
+
+ #[test]
+ fn the_turn_says_who_started_it_and_leaves_it_out_when_unknown() {
+ let mut t = running("t1", at(0));
+ let s = compute(&bot(vec![t.clone()]), at(1));
+ let turn = serde_json::to_value(&s).unwrap()["turn"].clone();
+ assert!(turn.get("source").is_none() && turn.get("source_name").is_none(), "{turn}");
+
+ t.signals.source = Some(TurnSource::person());
+ let turn = serde_json::to_value(compute(&bot(vec![t.clone()]), at(1))).unwrap()["turn"].clone();
+ assert_eq!(turn["source"], "person");
+ assert!(turn.get("source_name").is_none(), "the person is never named: {turn}");
+
+ t.signals.source = Some(TurnSource::bot("Ada"));
+ let turn = serde_json::to_value(compute(&bot(vec![t.clone()]), at(1))).unwrap()["turn"].clone();
+ assert_eq!((turn["source"].as_str(), turn["source_name"].as_str()), (Some("bot"), Some("Ada")));
+
+ t.signals.source = Some(TurnSource::routine("Morning digest"));
+ let turn = serde_json::to_value(compute(&bot(vec![t.clone()]), at(1))).unwrap()["turn"].clone();
+ assert_eq!((turn["source"].as_str(), turn["source_name"].as_str()), (Some("routine"), Some("Morning digest")));
+ }
+
+ #[test]
+ fn a_queued_turn_carries_its_source_too() {
+ let mut t = running("t1", at(0));
+ t.turn.state = "queued".into();
+ t.position = 1;
+ t.signals.source = Some(TurnSource::routine("Nightly"));
+ let s = compute(&bot(vec![t]), at(1));
+ assert_eq!(s.status, "queued");
+ assert_eq!(s.turn.as_ref().and_then(|t| t.source), Some("routine"));
+ }
+
+ #[test]
+ fn a_source_name_is_one_clipped_line_and_a_blank_one_is_left_out() {
+ assert_eq!(TurnSource::routine(" Daily\n report \t now ").name.as_deref(), Some("Daily report now"));
+ assert_eq!(TurnSource::bot(&"x".repeat(500)).name.map(|n| n.chars().count()), Some(MAX_SOURCE_NAME_CHARS));
+ assert_eq!(TurnSource::routine(" \n ").name, None);
+ assert_eq!(TurnSource::routine(" \n ").kind, "routine");
+ }
+}
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 8015a007..d04068c5 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -34,7 +34,7 @@ const AGENT_SEARCH_LIMIT: i64 = 20;
/// Longest notification body.
pub const NOTIFY_BODY_CHARS: usize = 200;
const WEBHOOK_TIMEOUT: Duration = Duration::from_secs(5);
-pub const NOTIFY_KINDS: [&str; 17] = [
+pub const NOTIFY_KINDS: [&str; 18] = [
"turn_finished",
"approval_needed",
"routine_failed",
@@ -52,6 +52,7 @@ pub const NOTIFY_KINDS: [&str; 17] = [
"goal_alert",
"idea_ready",
"spend_stopped",
+ "turn_quiet",
];
const MASK: &str = "••••••••";
@@ -1954,15 +1955,20 @@ async fn place(state: &AppState, context_id: Option<&str>) -> (Option<String>, S
}
}
+/// The bot's conversation a turn ran in, when it ran in one: a tap on its notification opens that
+/// thread (0.8.1 F6). `None` for a channel or the bot's direct chat.
+async fn turn_thread(state: &AppState, kwant_id: &str, channel_id: Option<&str>, context_id: Option<&str>) -> Option<String> {
+ match (channel_id, context_id) {
+ (None, Some(id)) if id != kwant_id && state.db.get_thread(id).await.ok().flatten().is_some() => Some(id.to_string()),
+ _ => None,
+ }
+}
+
/// "<bot> finished replying in <place>", for a turn of `kwant_id` in `context_id`.
pub async fn turn_finished(state: &AppState, kwant_id: &str, context_id: Option<&str>) -> Notification {
let name = kwant_name(state, kwant_id).await;
let (channel_id, where_) = place(state, context_id).await;
- // A turn in one of the bot's conversations opens that conversation (0.8.1 F6)
- let thread_id = match (&channel_id, context_id) {
- (None, Some(id)) if id != kwant_id && state.db.get_thread(id).await.ok().flatten().is_some() => Some(id.to_string()),
- _ => None,
- };
+ let thread_id = turn_thread(state, kwant_id, channel_id.as_deref(), context_id).await;
Notification {
kind: "turn_finished",
kwant_id: kwant_id.to_string(),
@@ -1975,6 +1981,23 @@ pub async fn turn_finished(state: &AppState, kwant_id: &str, context_id: Option<
}
}
+/// "<bot> is quiet": a live turn of `kwant_id` in `context_id` had no step for 15 min (H4/P4).
+pub async fn turn_quiet(state: &AppState, kwant_id: &str, context_id: Option<&str>) -> Notification {
+ let name = kwant_name(state, kwant_id).await;
+ let (channel_id, where_) = place(state, context_id).await;
+ let thread_id = turn_thread(state, kwant_id, channel_id.as_deref(), context_id).await;
+ Notification {
+ kind: "turn_quiet",
+ kwant_id: kwant_id.to_string(),
+ title: format!("{name} is quiet"),
+ body: format!("{name} has been quiet for {} min in {where_}.", super::bot_status::QUIET_LONG_MIN),
+ kwant_name: name,
+ channel_id,
+ thread_id,
+ card_id: None,
+ }
+}
+
async fn notification_for(state: &AppState, event: &RuntimeEvent) -> Option<Notification> {
match event.unscoped() {
RuntimeEvent::TurnEnded {
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index eb402441..18be5938 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -509,6 +509,10 @@ pub(super) fn is_parked(d: &Delegation) -> bool {
async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead: Kwant, specialist: Kwant, how: RunAs) {
let RunAs { retried, after_restart, carry_on, sent_back } = how;
let carried_on = carry_on.is_some() || sent_back.is_some();
+ // H3: a hand-off held for a stuck or waiting specialist starts once it can take it
+ if !super::bot_status::wait_released(&state, &d.id, &job.token).await {
+ return finish(&state, &d, &specialist, Err("stopped".into()), carried_on).await;
+ }
let scope = match scope_for(&state, &specialist, None, Some(d.thread_id.clone()), &job, d.depth).await {
Ok(s) => s,
Err(why) => return finish(&state, &d, &specialist, Err(why), carried_on).await,
@@ -556,6 +560,7 @@ async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead:
opts.on_started = Some(on_started);
opts.retried = retried;
opts.delegation_id = Some(d.id.clone());
+ opts.source = Some(super::bot_status::TurnSource::bot(&lead.name));
let outcome = try_kwant_turn(&scope, &specialist, prompt, opts).await;
let outcome = continue_once_if_capped(&scope, &specialist, outcome, false).await;
let outcome = match outcome {
@@ -1782,8 +1787,29 @@ pub async fn tool_delegate(state: &AppState, scope: &super::continuity::SelfScop
relayed_from: None,
lead_turn,
};
- match start(state, req).await {
- Ok(d) => (
+ let created = match create(state, req).await {
+ Ok(c) => c,
+ Err((_, m)) => return (m, true),
+ };
+ // H3: a specialist that is stuck or waits on the person gets it later, so it isn't sent twice
+ let held = match &created.next {
+ Next::Run(pair) => {
+ let d = &created.delegation;
+ super::bot_status::hold(state, &pair.1, &d.thread_id, "handoff", &d.id).await.map(|h| (pair.1.name.clone(), h))
+ }
+ Next::Wait(_) => None,
+ };
+ let d = created.start(state).await;
+ match held {
+ Some((name, h)) => (
+ format!(
+ "Delegated as [{}]. {}",
+ d.id,
+ super::bot_status::handoff_held_text(&name, h["reason_code"].as_str().unwrap_or("waits_on_you"))
+ ),
+ false,
+ ),
+ None => (
format!(
"Delegated as [{}]. It runs in the background; its result will be posted to this chat and you'll get a turn to continue. \
Tell the user who is working on it, then carry on.",
@@ -1791,7 +1817,6 @@ pub async fn tool_delegate(state: &AppState, scope: &super::continuity::SelfScop
),
false,
),
- Err((_, m)) => (m, true),
}
}
diff --git a/src/server/dev/line_notes.rs b/src/server/dev/line_notes.rs
index 61292748..2e29c3c4 100644
--- a/src/server/dev/line_notes.rs
+++ b/src/server/dev/line_notes.rs
@@ -851,6 +851,7 @@ pub async fn send(State(state): State<AppState>, headers: HeaderMap, Path(card_i
reply_to_message_id: None,
source: None,
meta: Some(meta),
+ client_message_id: None,
};
let sent = match crate::server::routes::send_chat_inner(state.clone(), payload, true).await {
Ok(Json(v)) => v,
diff --git a/src/server/mod.rs b/src/server/mod.rs
index b8ee7f7a..0fe56f46 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -30,6 +30,7 @@ pub mod delivery_check;
pub mod video;
pub mod questions;
pub mod activity;
+pub mod bot_status;
pub mod human_steps;
pub mod skills;
pub mod spaces;
@@ -456,6 +457,9 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/routines/:id/run", post(scheduler::run_now))
.route("/api/routines/:id/runs", get(scheduler::runs))
.route("/api/turns", get(delegation::list_turns))
+ .route("/api/turns/:id/quiet", post(bot_status::quiet))
+ .route("/api/bots/status", get(bot_status::list))
+ .route("/api/kwants/:id/status/retry", post(bot_status::retry))
.route("/api/kwants/:id/threads", get(delegation::list_threads).post(delegation::create_thread))
.route("/api/threads/:id", get(delegation::get_thread).patch(delegation::patch_thread))
.route("/api/threads/:id/messages", get(delegation::thread_messages))
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 770d5dbc..1d6d0605 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -714,6 +714,10 @@ pub struct SendChatPayload {
/// the server, never read from a request.
#[serde(skip)]
pub meta: Option<serde_json::Value>,
+ /// The composer's own id for this message, the same on every retry of it: the same id in
+ /// the same chat within 10 min is sent once (H3, `release-090/h4-contract.md` §7b).
+ #[serde(default)]
+ pub client_message_id: Option<String>,
}
async fn get_configured_key(db: &crate::db::Database, target_model: &str) -> Option<String> {
@@ -952,6 +956,8 @@ fn execute_single_turn(
workspace_dir: Option<std::path::PathBuf>,
teammates: Vec<Kwant>,
routing: Option<serde_json::Value>,
+ held: Option<String>,
+ source: super::bot_status::TurnSource,
) {
let scope = TurnScope {
channel_id: payload.channel_id.clone(),
@@ -984,6 +990,12 @@ fn execute_single_turn(
tokio::spawn(async move {
// Ends the job (its cancel keys) when the turn and its handoffs are done
let _job = job;
+ // H3: a message held for a stuck or waiting bot starts its turn once the bot can take it
+ if let Some(id) = &held {
+ if !super::bot_status::wait_released(&scope.state, id, &scope.cancel_token).await {
+ return;
+ }
+ }
// P10: what the person expects and how best to deliver it, planned once before the bot
// starts (the fast model within ~3 s, else the keyword plan), for the turn that answers
// the person's message. Read from their saved message, never `prompt` (attachment and
@@ -1000,7 +1012,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()), ..TurnOpts::default() };
+ let opts = TurnOpts { routing, nav_prompt: Some(prompt.clone()), source: Some(source), ..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)
@@ -1020,8 +1032,10 @@ pub(super) async fn run_routine_turn(
channel_id: Option<String>,
thread_id: Option<String>,
prompt: String,
+ routine_name: &str,
) -> Result<Option<String>, String> {
- run_routed_turn(state, kwant, channel_id, thread_id, prompt, None, Vec::new()).await
+ let opts = TurnOpts { source: Some(super::bot_status::TurnSource::routine(routine_name)), ..TurnOpts::default() };
+ run_turn_with(state, kwant, channel_id, thread_id, prompt, opts, Vec::new()).await
}
/// [`run_routine_turn`] with the routing card for the reply (`meta.routing`) and extra stop keys
@@ -1035,11 +1049,24 @@ pub(super) async fn run_routed_turn(
prompt: String,
routing: Option<serde_json::Value>,
stop_keys: Vec<String>,
+) -> Result<Option<String>, String> {
+ run_turn_with(state, kwant, channel_id, thread_id, prompt, TurnOpts { routing, ..TurnOpts::default() }, stop_keys).await
+}
+
+/// [`run_routed_turn`] with any turn options.
+async fn run_turn_with(
+ state: &AppState,
+ kwant: &Kwant,
+ channel_id: Option<String>,
+ thread_id: Option<String>,
+ prompt: String,
+ opts: TurnOpts,
+ stop_keys: Vec<String>,
) -> Result<Option<String>, String> {
let context_key = thread_id.clone().or_else(|| channel_id.clone()).unwrap_or_else(|| kwant.id.clone());
let job = state.turns.start_job(std::iter::once(context_key.clone()).chain(stop_keys));
let scope = scope_for(state, kwant, channel_id, thread_id, &job, 0).await?;
- let reply = try_kwant_turn(&scope, kwant, prompt.clone(), TurnOpts { routing, ..TurnOpts::default() }).await;
+ let reply = try_kwant_turn(&scope, kwant, prompt.clone(), opts).await;
let reply = continue_once_if_capped(&scope, kwant, reply, false).await;
match reply {
Ok(text) => {
@@ -1707,7 +1734,8 @@ fn targets_mentioned(targets: &[usize], scope: &TurnScope, id: &str) -> bool {
/// Runs a moderated team discussion: the lead opens (or pauses to ask the user), teammates react to
/// each other briefly or pass, @mentioned teammates join in, and the lead closes with one summary.
-async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, user_prompt: &str) {
+/// `source`: who sent the message; the opening turn answers it, later rounds have no source.
+async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, user_prompt: &str, source: super::bot_status::TurnSource) {
use std::collections::{HashMap, VecDeque};
let events = scope.state.event_sender.clone();
@@ -1764,6 +1792,7 @@ async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, use
label: Some(discussion::turn_label(turn, &team.name)),
// Only the opening turn may navigate the bot browser for a URL in the user's message
nav_prompt: opening.then(|| user_prompt.to_string()),
+ source: opening.then(|| source.clone()),
discussion: Some(opening.then(|| discussion::question_label(&kwant.name, &team.name))),
routing: None,
on_started: None,
@@ -1907,6 +1936,9 @@ pub(super) struct TurnOpts {
/// waits for the chat, P6) never gets in between the reply and its continuation. Empty for
/// every other turn, and for a decided reply (which holds no chat): that continuation queues.
pub(super) chat_handover: Option<ChatHandover>,
+ /// Who started the turn, for the status's `turn.source` (H4): the sender of a chat message, a
+ /// bot's hand-off or a routine's run. `None`: no source is sent (kwant started the turn).
+ pub(super) source: Option<super::bot_status::TurnSource>,
/// The turn may run beside a turn of the same bot in the same chat, instead of waiting for it
/// (P6's one reply per bot per chat). Only for the lead hearing its hand-offs while the turn
/// that handed them out still runs past the hold limit (see `delegation::continue_lead`):
@@ -2114,6 +2146,8 @@ struct Carried {
beside_running: bool,
/// The delivery it belongs to: the continuation counts what the first turn already did.
delivery_seen: Option<DeliverySeen>,
+ /// Who started the turn: the delivery check's continuation answers the same message.
+ source: Option<super::bot_status::TurnSource>,
}
impl Carried {
@@ -2128,12 +2162,13 @@ impl Carried {
task: o.task.clone(),
beside_running: o.beside_running,
delivery_seen: o.delivery_seen.clone(),
+ source: o.source.clone(),
}
}
fn into_opts(self) -> TurnOpts {
- 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() }
+ let Carried { always_ask, delegation_id, routed, routing, tier, purpose, task, beside_running, delivery_seen: _, source } = self;
+ TurnOpts { always_ask, delegation_id, routed, routing, tier, purpose, task, beside_running, source, ..Default::default() }
}
/// The delivery check's continuation of the turn: checked against the first turn's `plan`
@@ -2216,6 +2251,10 @@ pub(super) async fn turn_once(
running_row: None,
quiet: opts.quiet_finish,
};
+ // After the guard, which clears it however the turn ends
+ if let Some(source) = opts.source.clone() {
+ turns.note_source(&tag.turn_id, source);
+ }
// One reply per bot per chat: a second message to a bot that is still answering here waits
// for that reply (queued, "agent_busy") instead of starting a parallel turn (P6, 2026-11-09).
// Unsaved views and purpose turns (checks, audits) aren't replies in the chat.
@@ -3147,6 +3186,7 @@ async fn run_kwant_turn_inner(
choice: if unlisted_api { None } else { choice.clone() },
});
let stall_limit = if driver.streams_progress() { stall_after } else { None };
+ state.turns.note_driver(&tag.turn_id, driver.streams_progress(), runs_on.map(super::bot_status::engine_label));
let (driver_tx, mut driver_rx) = mpsc::channel(32);
let driver_task =
tokio::spawn(async move { driver.stream_turn(input, driver_tx).await });
@@ -3181,6 +3221,7 @@ async fn run_kwant_turn_inner(
event_opt = driver_rx.recv() => {
if let Some(e) = &event_opt {
stall_clock.saw(e, tokio::time::Instant::now());
+ state.turns.saw_step(&tag.turn_id, e);
}
match event_opt {
Some(RuntimeEvent::TurnComplete { tokens, duration_ms, .. }) => {
@@ -3192,6 +3233,7 @@ async fn run_kwant_turn_inner(
// stall clock (above) is off until it gets one
Some(RuntimeEvent::WaitingForRoom { reason, position, slots }) => {
state.turns.set_turn_state(&tag.turn_id, "queued");
+ state.turns.note_queue_reason(&tag.turn_id, &reason);
let _ = state.event_sender.send(RuntimeEvent::TurnQueued {
turn_id: tag.turn_id.clone(),
kwant_id: tag.kwant_id.clone(),
@@ -3257,6 +3299,7 @@ async fn run_kwant_turn_inner(
event_broadcast.send(RuntimeEvent::ThinkingDelta(note.clone()));
notices.push(note);
stall_retried = Some(secs);
+ state.turns.note_stall(&tag.turn_id, &tag.kwant_id, secs);
next_attempt = i;
continue;
}
@@ -3278,6 +3321,17 @@ async fn run_kwant_turn_inner(
"stall_secs": secs,
"retried": stall_retried.is_some(),
}));
+ state.turns.note_gave_up(
+ &tag.kwant_id,
+ super::bot_status::GaveUp {
+ at: chrono::Utc::now(),
+ tries: if stall_retried.is_some() { 2 } else { 1 },
+ secs,
+ turn_id: tag.turn_id.clone(),
+ context_id: tag.context_id.clone(),
+ thread_id: tag.thread_id.clone(),
+ },
+ );
break;
}
let result = driver_task.await;
@@ -3736,6 +3790,38 @@ fn merge_meta(meta: &mut Option<serde_json::Value>, extra: Option<&serde_json::V
}
pub(crate) async fn send_chat_inner(
+ state: AppState,
+ payload: SendChatPayload,
+ from_person: bool,
+) -> Result<Json<serde_json::Value>, StatusCode> {
+ let Some(client_id) = payload.client_message_id.clone() else {
+ return send_chat_routed(state, payload, from_person).await;
+ };
+ if !super::bot_status::valid_client_id(&client_id) {
+ return Err(StatusCode::BAD_REQUEST);
+ }
+ let chat = [&payload.thread_id, &payload.channel_id, &payload.team_id, &payload.kwant_id]
+ .into_iter()
+ .find_map(|c| c.clone())
+ .unwrap_or_default();
+ let key = format!("{chat}|{client_id}");
+ if let Err(first) = state.turns.board(|b| b.reserve_send(&key, chrono::Utc::now())) {
+ return Ok(Json(json!({
+ "status": "already_delivered",
+ "deduped": true,
+ "already_delivered_at": first.at,
+ "user_message_id": first.message_id,
+ })));
+ }
+ let sent = send_chat_routed(state.clone(), payload, from_person).await;
+ state.turns.board(|b| match sent.as_ref().ok().and_then(|j| j.0["user_message_id"].as_str()) {
+ Some(id) => b.send_saved(&key, id),
+ None => b.release_send(&key),
+ });
+ sent
+}
+
+async fn send_chat_routed(
state: AppState,
mut payload: SendChatPayload,
from_person: bool,
@@ -4074,6 +4160,7 @@ pub(crate) async fn send_chat_inner(
target_kwant.name, target_kwant.title, reason
)));
+ let held = held_send(&state, &target_kwant, &payload, &saved_user_msg.id).await;
execute_single_turn(
state.clone(),
target_kwant.clone(),
@@ -4084,14 +4171,18 @@ pub(crate) async fn send_chat_inner(
workspace_dir.clone(),
members.clone(),
Some(routing),
+ held.as_ref().map(|_| saved_user_msg.id.clone()),
+ super::bot_status::TurnSource::sender(from_person),
);
- Ok(Json(json!({
+ let mut reply = json!({
"status": "dispatched",
"user_message_id": saved_user_msg.id,
"kwant": target_kwant.name,
"team": team.name
- })))
+ });
+ with_held(&mut reply, held);
+ Ok(Json(reply))
}
TeamDecision::Discuss {
turns,
@@ -4146,7 +4237,7 @@ pub(crate) async fn send_chat_inner(
tokio::spawn(async move {
let _job = job;
- run_discussion(&scope, &team_clone, planned, &prompt).await;
+ run_discussion(&scope, &team_clone, planned, &prompt, super::bot_status::TurnSource::sender(from_person)).await;
});
Ok(Json(json!({
@@ -4304,6 +4395,7 @@ pub(crate) async fn send_chat_inner(
return Ok(Json(v));
}
let team_keys = active_team.as_ref().map(|t| (t.id.clone(), t.name.clone()));
+ let held = held_send(&state, &target_kwant, &payload, &saved_user_msg.id).await;
execute_single_turn(
state.clone(),
target_kwant.clone(),
@@ -4314,13 +4406,17 @@ pub(crate) async fn send_chat_inner(
workspace_dir,
chat_teammates,
routing,
+ held.as_ref().map(|_| saved_user_msg.id.clone()),
+ super::bot_status::TurnSource::sender(from_person),
);
- Ok(Json(json!({
+ let mut reply = json!({
"status": "dispatched",
"user_message_id": saved_user_msg.id,
"kwant": target_kwant.name
- })))
+ });
+ with_held(&mut reply, held);
+ Ok(Json(reply))
}
}
@@ -4414,19 +4510,47 @@ 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 { nav_prompt: Some(payload.prompt.clone()), ..TurnOpts::default() };
+ let opts = TurnOpts {
+ nav_prompt: Some(payload.prompt.clone()),
+ source: Some(super::bot_status::TurnSource::sender(from_person)),
+ ..TurnOpts::default()
+ };
let prompt = payload.prompt + &note;
let target = kwant.clone();
+ // H3: the message is saved and shows; its turn waits while the bot is stuck or waits on the person
+ let held = super::bot_status::hold(&state, &kwant, &thread.id, "message", &saved.id).await;
+ let held_id = held.as_ref().map(|_| saved.id.clone());
tokio::spawn(async move {
let _job = job;
+ if let Some(id) = &held_id {
+ if !super::bot_status::wait_released(&scope.state, id, &scope.cancel_token).await {
+ return;
+ }
+ }
run_kwant_turn(&scope, &target, prompt, opts).await;
});
- Ok(Json(json!({
+ let mut reply = json!({
"status": "dispatched",
"user_message_id": saved.id,
"kwant": kwant.name,
"thread_id": thread.id,
- })))
+ });
+ with_held(&mut reply, held);
+ Ok(Json(reply))
+}
+
+/// Holds a chat or 1:1 message to `kwant` while it is stuck or waits on the person elsewhere (H3).
+async fn held_send(state: &AppState, kwant: &Kwant, payload: &SendChatPayload, message_id: &str) -> Option<serde_json::Value> {
+ let context = payload.channel_id.clone().or_else(|| payload.kwant_id.clone()).unwrap_or_else(|| kwant.id.clone());
+ super::bot_status::hold(state, kwant, &context, "message", message_id).await
+}
+
+/// A held send answers `status: "held"` with why (`release-090/h4-contract.md` §7a).
+fn with_held(reply: &mut serde_json::Value, held: Option<serde_json::Value>) {
+ if let Some(h) = held {
+ reply["status"] = json!("held");
+ reply["held"] = h;
+ }
}
#[derive(Debug, Deserialize)]
@@ -6447,9 +6571,11 @@ mod tests {
delegation_id: Some("d1".into()),
nav_prompt: Some("open https://example.org".into()),
fresh_eyes: false,
+ source: Some(super::super::bot_status::TurnSource::person()),
..Default::default()
};
let next = Carried::of(&first).into_opts();
+ assert_eq!(next.source, first.source, "the continuation answers the same message");
assert_eq!(next.routed, first.routed);
assert_eq!(next.routing, first.routing);
assert_eq!(next.tier, first.tier);
@@ -6460,6 +6586,14 @@ mod tests {
assert!(next.nav_prompt.is_none(), "the continuation's prompt is kwnt's, it never moves the browser");
}
+ #[test]
+ fn a_bots_own_send_is_never_the_persons_message() {
+ use super::super::bot_status::TurnSource;
+ assert_eq!(TurnSource::sender(true), TurnSource::person());
+ assert_eq!(TurnSource::sender(false).kind, "bot");
+ assert_eq!(TurnSource::sender(false).name, None);
+ }
+
#[test]
fn fresh_eyes_and_no_tools_turns_skip_the_delivery_check() {
assert!(TurnOpts::default().delivery_checked());
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index 4b899605..ddab8098 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -681,7 +681,8 @@ async fn execute(state: &AppState, routine: &RoutineRow) -> Result<Option<String
let prompt = routine.instructions.clone()
+ &follow_up_context(state, routine, &kwant, &saved.id).await
+ &last_run_context(state, routine, &kwant).await;
- super::routes::run_routine_turn(state, &kwant, routine.channel_id.clone(), routine.thread_id.clone(), prompt).await
+ super::routes::run_routine_turn(state, &kwant, routine.channel_id.clone(), routine.thread_id.clone(), prompt, &routine.name)
+ .await
}
/// The chat id a routine delivers to: its thread, its channel, or its bot's direct chat.
@@ -871,6 +872,7 @@ pub fn spawn(state: AppState, shutdown: CancellationToken) -> tokio::task::JoinH
/// Starts the scheduler and the notifier.
pub fn spawn_background(state: AppState, shutdown: CancellationToken) {
super::continuity::spawn_notifier(state.clone());
+ super::bot_status::spawn_watcher(state.clone());
crate::zombie::hunt::spawn(state.clone(), shutdown.clone());
crate::documents::reminders::spawn(state.clone(), shutdown.clone());
super::missions::listener::spawn(state.clone(), shutdown.clone());
diff --git a/src/server/sse.rs b/src/server/sse.rs
index eb7ddbf5..2ca2520d 100644
--- a/src/server/sse.rs
+++ b/src/server/sse.rs
@@ -107,7 +107,9 @@ pub fn owners(event: &RuntimeEvent) -> Vec<Owner> {
out.extend(fields(v, &["kwant_id", "channel_id", "direct_kwant_id", "thread_id"], Owner::Context));
out
}
- E::ProfileSwitched { kwant_id, .. } | E::MemoryChanged { kwant_id } => contexts([&Some(kwant_id.clone())]),
+ E::ProfileSwitched { kwant_id, .. } | E::MemoryChanged { kwant_id } | E::BotStatus { kwant_id, .. } => {
+ contexts([&Some(kwant_id.clone())])
+ }
E::DiscussionStarted { team_id, .. }
| E::BrowserNavigated { team_id, .. }
| E::BrowserScreenshot { team_id, .. }
@@ -310,6 +312,7 @@ mod tests {
},
E::Error { code: s("x"), message: s("x"), kwant_id: Some(s("k")) },
E::MemoryChanged { kwant_id: s("k") },
+ E::BotStatus { kwant_id: s("k"), status: json!({}) },
E::RoutineRun { routine_id: s("r"), run_id: s("x"), status: s("ok") },
E::TaskUpdated { task: json!({"id": "t", "space_id": "spc_x"}) },
E::MissionUpdated { mission: json!({"id": "m", "space_id": "spc_x"}) },
@@ -384,6 +387,7 @@ mod tests {
| E::DecideUpdated { .. }
| E::Error { .. }
| E::MemoryChanged { .. }
+ | E::BotStatus { .. }
| E::RoutineRun { .. }
| E::TaskUpdated { .. }
| E::MissionUpdated { .. }
diff --git a/src/server/telegram/bridge.rs b/src/server/telegram/bridge.rs
index 36c8e331..97ee5a05 100644
--- a/src/server/telegram/bridge.rs
+++ b/src/server/telegram/bridge.rs
@@ -236,6 +236,7 @@ async fn person_message(state: &AppState, runner: &Runner, link: &TelegramLink,
reply_to_message_id: reply_to,
source: Some("telegram".into()),
meta: None,
+ client_message_id: None,
};
match crate::server::routes::send_chat_inner(state.clone(), payload, true).await {
Ok(axum::Json(v)) => {
diff --git a/src/server/turns.rs b/src/server/turns.rs
index c0c643da..bccc8cc7 100644
--- a/src/server/turns.rs
+++ b/src/server/turns.rs
@@ -63,6 +63,8 @@ struct Inner {
hold_limit: Option<Duration>,
/// The pictures of a running turn, by turn id (see [`TurnRegistry::note_screenshot`]).
pictures: HashMap<String, TurnPictures>,
+ /// Why each bot has its status, its held sends and recent client message ids (H4/H3).
+ board: super::bot_status::Board,
}
/// A bot's last screenshot in a turn, as the browser returned it.
@@ -210,7 +212,15 @@ impl TurnRegistry {
}
pub fn set_turn(&self, turn: ActiveTurn) {
- self.lock().turns.insert(turn.turn_id.clone(), turn);
+ let mut inner = self.lock();
+ if turn.state == "running" {
+ // A new turn ends the bot's gave-up Stuck
+ if let Some(m) = inner.board.marks.get_mut(&turn.kwant_id) {
+ m.gave_up = None;
+ }
+ }
+ inner.board.nudge(&turn.kwant_id);
+ inner.turns.insert(turn.turn_id.clone(), turn);
}
/// Marks a known turn "queued" or "running" again (an isolated reply waiting for the VM), keeping
@@ -228,9 +238,72 @@ impl TurnRegistry {
pub fn end_turn(&self, turn_id: &str) {
let mut inner = self.lock();
- inner.turns.remove(turn_id);
+ let ended = inner.turns.remove(turn_id);
inner.meters.remove(turn_id);
inner.pictures.remove(turn_id);
+ inner.board.signals.remove(turn_id);
+ if let Some(t) = ended {
+ if t.state == "running" {
+ inner.board.marks.entry(t.kwant_id.clone()).or_default().last_finished_at = Some(chrono::Utc::now());
+ }
+ inner.board.nudge(&t.kwant_id);
+ }
+ }
+
+ /// Reads or changes the status board (see [`super::bot_status`]).
+ pub fn board<R>(&self, f: impl FnOnce(&mut super::bot_status::Board) -> R) -> R {
+ f(&mut self.lock().board)
+ }
+
+ /// A streamed event of a running turn: its last step (and that its engine answered).
+ pub fn saw_step(&self, turn_id: &str, e: &RuntimeEvent) {
+ let mut inner = self.lock();
+ if inner.turns.contains_key(turn_id) {
+ inner.board.signals.entry(turn_id.to_string()).or_default().saw(e, chrono::Utc::now());
+ }
+ }
+
+ /// The driver an attempt of the turn runs on: whether it streams steps, and its engine.
+ pub fn note_driver(&self, turn_id: &str, live: bool, engine: Option<&'static str>) {
+ let mut inner = self.lock();
+ if inner.turns.contains_key(turn_id) {
+ let s = inner.board.signals.entry(turn_id.to_string()).or_default();
+ if s.live_steps != Some(true) {
+ s.live_steps = Some(live);
+ }
+ s.engine = engine.or(s.engine);
+ }
+ }
+
+ /// The stall watchdog fired and the turn retries now.
+ pub fn note_stall(&self, turn_id: &str, kwant_id: &str, secs: u64) {
+ let mut inner = self.lock();
+ if inner.turns.contains_key(turn_id) {
+ inner.board.signals.entry(turn_id.to_string()).or_default().stalled =
+ Some(super::bot_status::Stall { at: chrono::Utc::now(), secs });
+ }
+ inner.board.nudge(kwant_id);
+ }
+
+ /// The turn stopped after the stall watchdog fired: its bot shows Stuck for a while.
+ pub fn note_gave_up(&self, kwant_id: &str, g: super::bot_status::GaveUp) {
+ let mut inner = self.lock();
+ inner.board.marks.entry(kwant_id.to_string()).or_default().gave_up = Some(g);
+ inner.board.nudge(kwant_id);
+ }
+
+ /// Why a queued turn waits ("agent_busy", "server_busy", "vm_busy").
+ pub fn note_queue_reason(&self, turn_id: &str, reason: &str) {
+ let mut inner = self.lock();
+ if inner.turns.contains_key(turn_id) {
+ inner.board.signals.entry(turn_id.to_string()).or_default().queue_reason = Some(reason.to_string());
+ }
+ }
+
+ /// Notes who started a turn (H4 `turn.source`). Called before the turn takes its slot, so a
+ /// queued turn has it too; [`TurnRegistry::end_turn`] clears it with the turn's other signals.
+ pub fn note_source(&self, turn_id: &str, source: super::bot_status::TurnSource) {
+ self.lock().board.signals.entry(turn_id.to_string()).or_default().source = Some(source);
}
/// Keeps the turn's newest screenshot (one per turn), for the reply guard.
@@ -398,6 +471,7 @@ impl TurnRegistry {
since: chrono::Utc::now(),
purpose: None,
});
+ self.note_queue_reason(&tag.turn_id, rx.reason);
let _ = events.send(RuntimeEvent::TurnQueued {
turn_id: tag.turn_id.clone(),
kwant_id: tag.kwant_id.clone(),
@@ -761,6 +835,28 @@ mod tests {
assert_eq!(reg.usage_of("k", "foundry"), 0);
}
+ #[test]
+ fn a_turns_source_lasts_from_queued_to_running_and_goes_with_the_turn() {
+ use super::super::bot_status::TurnSource;
+ let reg = TurnRegistry::default();
+ let turn = |state: &str| ActiveTurn {
+ turn_id: "t".into(),
+ kwant_id: "k".into(),
+ context_id: "c".into(),
+ thread_id: None,
+ state: state.into(),
+ since: chrono::Utc::now(),
+ purpose: None,
+ };
+ reg.note_source("t", TurnSource::bot("Ada"));
+ reg.set_turn(turn("queued"));
+ reg.set_turn(turn("running"));
+ let source = reg.board(|b| b.signals.get("t").and_then(|s| s.source.clone()));
+ assert_eq!(source, Some(TurnSource::bot("Ada")));
+ reg.end_turn("t");
+ assert!(reg.board(|b| !b.signals.contains_key("t")));
+ }
+
#[test]
fn usage_booked_mid_turn_is_counted_once() {
let reg = TurnRegistry::default();
diff --git a/tests/ask_user_test.rs b/tests/ask_user_test.rs
index 08dcb13a..a34c30e8 100644
--- a/tests/ask_user_test.rs
+++ b/tests/ask_user_test.rs
@@ -122,27 +122,28 @@ async fn a_question_is_never_visible_without_its_card_and_waiter() {
}
#[tokio::test]
-async fn the_agent_keeps_working_elsewhere_while_it_waits() {
+async fn other_bots_keep_working_while_one_waits_and_its_other_chats_are_held() {
let env = setup().await;
send_direct(&env, &env.a, &format!("{} REPLYTAG:w1", ask_marker("Pick a colour", &["red", "blue"])), json!({})).await;
let q = open_question(&env, &env.a).await;
- // A thread of the same agent, and the other agent, both answer meanwhile
+ // The other agent answers meanwhile; a thread of the waiting agent is held until the answer (H3)
let (s, thread) = call(&env.app, "POST", &format!("/api/kwants/{}/threads", env.a), Some(json!({"title": "side"}))).await;
assert_eq!(s, StatusCode::CREATED);
let tid = thread["id"].as_str().unwrap();
- let (s, _) = call(&env.app, "POST", "/api/chat/send", Some(json!({"prompt": "quick one REPLYTAG:w2", "sender_id": "user", "thread_id": tid}))).await;
- assert_eq!(s, StatusCode::OK);
- wait_reply(&env, tid, "answer w2").await;
+ let (s, v) = call(&env.app, "POST", "/api/chat/send", Some(json!({"prompt": "quick one REPLYTAG:w2", "sender_id": "user", "thread_id": tid}))).await;
+ assert_eq!((s, v["status"].as_str()), (StatusCode::OK, Some("held")), "{v}");
send_direct(&env, &env.b, "disk space? REPLYTAG:w3", json!({})).await;
wait_reply(&env, &env.b, "answer w3").await;
assert_eq!(question(&env, q["id"].as_str().unwrap()).await["question"]["status"], "open", "still waiting");
+ assert!(!messages(&env, tid).await.iter().any(|m| m.sender_role == "kwant"), "the held thread has no reply yet");
- // Free text answer
+ // Free text answer: the question's turn goes on, then the held thread
let (s, _) = call(&env.app, "POST", &format!("/api/questions/{}/answer", q["id"].as_str().unwrap()), Some(json!({"text": " green, actually "}))).await;
assert_eq!(s, StatusCode::OK);
let reply = wait_reply(&env, &env.a, "answer w1").await;
assert!(reply.text.contains("The user answered: green, actually]"), "{}", reply.text);
+ wait_reply(&env, tid, "answer w2").await;
}
#[tokio::test]
diff --git a/tests/bot_status_test.rs b/tests/bot_status_test.rs
new file mode 100644
index 00000000..c5036c57
--- /dev/null
+++ b/tests/bot_status_test.rs
@@ -0,0 +1,128 @@
+//! H4 + H3 through the routes: a bot that asks the person shows `needs_you` with why and since;
+//! a message to it in another chat is held (saved, shown as held, no turn) and goes through once
+//! the person answers; the same `client_message_id` is sent once. See
+//! `release-090/h4-contract.md`.
+
+mod common;
+
+use axum::http::StatusCode;
+use common::*;
+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) -> Value {
+ 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.clone();
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ panic!("no open question in {ctx}");
+}
+
+async fn status_of(env: &Env, kwant: &str) -> Value {
+ let (s, v) = call(&env.app, "GET", "/api/bots/status", None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert!(v["now"].is_string(), "{v}");
+ v["bots"].as_array().unwrap().iter().find(|b| b["kwant_id"] == kwant).cloned().unwrap_or_else(|| panic!("{kwant} missing: {v}"))
+}
+
+async fn send(env: &Env, body: Value) -> (StatusCode, Value) {
+ call(&env.app, "POST", "/api/chat/send", Some(body)).await
+}
+
+#[tokio::test]
+async fn a_bot_waiting_on_the_person_holds_other_messages_until_the_answer_and_a_retry_is_sent_once() {
+ let env = setup().await;
+ let idle = status_of(&env, &env.a).await;
+ assert_eq!((idle["status"].as_str(), idle["reason_code"].as_str()), (Some("available"), Some("idle")), "{idle}");
+
+ send_direct(&env, &env.a, &format!("Ship it? {} REPLYTAG:q1", ask_marker("Which branch should I ship?", &["main", "batch2"])), json!({})).await;
+ let q = open_question(&env, &env.a).await;
+ let qid = q["id"].as_str().unwrap().to_string();
+
+ // H4: needs you, because it asked, since when it asked
+ let st = status_of(&env, &env.a).await;
+ assert_eq!((st["status"].as_str(), st["reason_code"].as_str()), (Some("needs_you"), Some("asked_question")), "{st}");
+ assert_eq!(st["question"]["id"], qid.as_str());
+ assert_eq!(st["question"]["context_id"], env.a.as_str());
+ assert_eq!(st["since"], st["question"]["asked_at"]);
+ assert_eq!(st["waits_on"]["kind"], "person");
+ assert_eq!(st["turn"]["context_id"], env.a.as_str());
+ let other = status_of(&env, &env.b).await;
+ assert_eq!(other["status"], "available", "{other}");
+
+ // H3: a message in another chat of that bot is saved and held, not run
+ let (s, thread) = call(&env.app, "POST", &format!("/api/kwants/{}/threads", env.a), Some(json!({"title": "side"}))).await;
+ assert_eq!(s, StatusCode::CREATED);
+ let tid = thread["id"].as_str().unwrap().to_string();
+ let body = json!({"prompt": "and the docs? REPLYTAG:h1", "sender_id": "user", "thread_id": tid, "client_message_id": "cm-01HF.1"});
+ let (s, v) = send(&env, body.clone()).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["status"], "held", "{v}");
+ let mid = v["user_message_id"].as_str().unwrap().to_string();
+ assert_eq!((v["held"]["kwant_id"].as_str(), v["held"]["reason_code"].as_str()), (Some(env.a.as_str()), Some("waits_on_you")), "{v}");
+ assert_eq!(v["held"]["question"]["id"], qid.as_str());
+ assert!(v["held"]["kwant_name"].is_string() && v["held"]["since"].is_string(), "{v}");
+ assert!(messages(&env, &tid).await.iter().any(|m| m.id == mid), "a held message is saved and shows");
+
+ let st = status_of(&env, &env.a).await;
+ let held = st["held"].as_array().unwrap_or_else(|| panic!("no held list: {st}"));
+ assert_eq!(held.len(), 1, "{st}");
+ assert_eq!((held[0]["kind"].as_str(), held[0]["id"].as_str()), (Some("message"), Some(mid.as_str())));
+ assert_eq!((held[0]["reason_code"].as_str(), held[0]["context_id"].as_str()), (Some("waits_on_you"), Some(tid.as_str())));
+
+ // H3: the same client message id again (a retry after a timeout) is not sent twice
+ let (s, again) = send(&env, body.clone()).await;
+ assert_eq!(s, StatusCode::OK, "{again}");
+ assert_eq!((again["status"].as_str(), again["deduped"].as_bool()), (Some("already_delivered"), Some(true)), "{again}");
+ assert_eq!(again["user_message_id"], mid.as_str());
+ assert!(again["already_delivered_at"].is_string());
+ let users = |msgs: Vec<kwnt::db::models::Message>| msgs.into_iter().filter(|m| m.sender_role == "user").count();
+ assert_eq!(users(messages(&env, &tid).await), 1, "nothing new saved");
+ let (s, _) = send(&env, json!({"prompt": "x", "sender_id": "user", "thread_id": tid, "client_message_id": "not ok"})).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+
+ // Nothing ran in the thread while held
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ assert!(!messages(&env, &tid).await.iter().any(|m| m.sender_role == "kwant"), "held: no reply yet");
+
+ // The answer: the question's turn goes on, then the held message gets its turn
+ let (s, v) = call(&env.app, "POST", &format!("/api/questions/{qid}/answer"), Some(json!({"choice": 1}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ wait_reply(&env, &env.a, "answer q1").await;
+ wait_reply(&env, &tid, "answer h1").await;
+ wait_for("the hold to clear and the bot to be available", || async {
+ let st = status_of(&env, &env.a).await;
+ st["held"].as_array().is_none_or(|h| h.is_empty()) && st["status"] == "available"
+ })
+ .await;
+ let st = status_of(&env, &env.a).await;
+ assert!(st["last_finished_at"].is_string() && st["since"] == st["last_finished_at"], "{st}");
+
+ // After the window's first send was delivered, a new id goes as usual
+ let (s, v) = send(&env, json!({"prompt": "thanks REPLYTAG:h2", "sender_id": "user", "thread_id": tid, "client_message_id": "cm-01HF.2"})).await;
+ assert_eq!((s, v["status"].as_str()), (StatusCode::OK, Some("dispatched")), "{v}");
+ wait_reply(&env, &tid, "answer h2").await;
+}
+
+#[tokio::test]
+async fn quiet_and_retry_routes_answer_for_the_person() {
+ let env = setup().await;
+ let (s, _) = call(&env.app, "POST", "/api/turns/no-such-turn/quiet", Some(json!({"action": "snooze"}))).await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+ let (s, v) = call(&env.app, "POST", &format!("/api/kwants/{}/status/retry", env.a), Some(json!({}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!((v["released"].as_u64(), v["status"]["status"].as_str()), (Some(0), Some("available")), "{v}");
+ let (s, _) = call(&env.app, "POST", "/api/kwants/no-such-bot/status/retry", Some(json!({}))).await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+}
diff --git a/tests/continuity_test.rs b/tests/continuity_test.rs
index 0bbe6e7a..9123b18b 100644
--- a/tests/continuity_test.rs
+++ b/tests/continuity_test.rs
@@ -1614,7 +1614,7 @@ async fn webhook_setting_is_https_only_and_masked() {
assert_eq!(s["notify_webhook_url"], "");
assert_eq!(
s["notify_on"],
- json!(["turn_finished", "approval_needed", "routine_failed", "delegation_finished", "delegation_stalled", "skill_proposed", "question_asked", "loose_ends", "human_step", "app_update", "work_ahead", "automation_suggested", "tier_proposed", "fact_disputed", "goal_alert", "idea_ready", "spend_stopped"])
+ json!(["turn_finished", "approval_needed", "routine_failed", "delegation_finished", "delegation_stalled", "skill_proposed", "question_asked", "loose_ends", "human_step", "app_update", "work_ahead", "automation_suggested", "tier_proposed", "fact_disputed", "goal_alert", "idea_ready", "spend_stopped", "turn_quiet"])
);
let (status, _) = req(
@@ -1952,3 +1952,20 @@ async fn a_turn_in_a_thread_notifies_with_the_thread() {
let n = continuity::turn_finished(&state, &k.id, Some(&k.id)).await;
assert_eq!(n.thread_id, None, "the direct chat is no thread");
}
+
+/// 0.9 P4: a bot that goes quiet in one of its conversations opens that thread, like F6's reply.
+#[tokio::test]
+async fn a_quiet_turn_in_a_thread_notifies_with_the_thread() {
+ let (_app, state, _tmp) = setup().await;
+ let kwants = state.db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
+ let k = &kwants[0];
+ let thread = state.db.create_thread(&k.id, "Launch plan", "chat", None, "user").await.unwrap();
+ let n = continuity::turn_quiet(&state, &k.id, Some(&thread.id)).await;
+ assert_eq!(n.kind, "turn_quiet");
+ assert_eq!(n.thread_id.as_deref(), Some(thread.id.as_str()));
+ assert_eq!((n.channel_id, n.card_id), (None, None));
+ let n = continuity::turn_quiet(&state, &k.id, Some(&k.id)).await;
+ assert_eq!(n.thread_id, None, "the direct chat is no thread");
+ let n = continuity::turn_quiet(&state, &k.id, Some("no-such-thread")).await;
+ assert_eq!(n.thread_id, None, "an unknown id is never sent as a thread");
+}