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.

Follow up once when a bot waits on the person

Lin (kwant bot)aeb856cce1ff
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a5154083..d44c46c7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- **One list of questions.** When two or more bots ask you something after one message, the team
lead (or the bot that started) posts one numbered list of everything they need. Your answer goes
to the lead, which passes each part on; bots waiting on a question card continue directly.
+- **Reminders when a bot waits on you.** When a bot's reply ends by asking you something, or it asks
+ with a question card (also Claude's own question tool, which now shows as a card you can answer),
+ it reminds you once in the same chat after 24 hours and sends a notification. Writing in that chat
+ or answering the question cancels the reminder. Set the delay with `waiting_follow_up_hours` in
+ settings (0 turns reminders off). `GET /api/waiting` (you only, never a bot) lists everything bots
+ are waiting on you for.
### Changed
- A bot reply that ends with a closing line such as "Anything else?", "Should I continue?" or
diff --git a/src/db/mod.rs b/src/db/mod.rs
index e68abc30..bc38145f 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -19,6 +19,7 @@ pub mod hires;
pub mod imports;
pub mod approval_modes;
pub mod parked;
+pub mod waiting;
pub mod api_context;
pub mod usage;
@@ -148,6 +149,7 @@ impl Database {
db.migrate_parallel().await?;
db.migrate_documents().await?;
db.migrate_parked().await?;
+ db.migrate_waiting().await?;
db.migrate_api_context().await?;
db.migrate_usage().await?;
if spaces {
diff --git a/src/db/waiting.rs b/src/db/waiting.rs
new file mode 100644
index 00000000..e4e7a9b4
--- /dev/null
+++ b/src/db/waiting.rs
@@ -0,0 +1,265 @@
+//! What a bot is waiting on the person for: an open question (its card) or a reply that ended by
+//! asking the person something. Each gets at most one reminder, `due_at` after the turn ended
+//! (none when reminders are off). The person writing in that chat, or the question closing, ends it.
+
+use super::{Database, DbError};
+use chrono::{DateTime, Utc};
+use serde::Serialize;
+use sqlx::FromRow;
+use uuid::Uuid;
+
+/// "open" (still waiting), "reminded" (its one reminder went out, still waiting) or "closed".
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct WaitingItem {
+ pub id: String,
+ pub kwant_id: String,
+ pub channel_id: Option<String>,
+ pub direct_kwant_id: Option<String>,
+ pub thread_id: Option<String>,
+ /// Set when the bot asked with a question card.
+ pub question_id: Option<String>,
+ /// The reply or card that asked.
+ pub message_id: Option<String>,
+ pub question: String,
+ /// When the reminder goes out; `None` when reminders were off as the turn ended.
+ pub due_at: Option<DateTime<Utc>>,
+ pub status: String,
+ pub created_at: DateTime<Utc>,
+ pub reminded_at: Option<DateTime<Utc>>,
+}
+
+pub struct NewWaitingItem {
+ pub kwant_id: String,
+ pub channel_id: Option<String>,
+ pub direct_kwant_id: Option<String>,
+ pub thread_id: Option<String>,
+ pub question_id: Option<String>,
+ pub message_id: Option<String>,
+ pub question: String,
+ pub due_at: Option<DateTime<Utc>>,
+}
+
+/// The same bot in the same chat, matched with NULLs as "".
+const SAME_CHAT: &str = "kwant_id = ? AND COALESCE(channel_id, '') = ? AND COALESCE(direct_kwant_id, '') = ? \
+ AND COALESCE(thread_id, '') = ?";
+
+impl Database {
+ pub(super) async fn migrate_waiting(&self) -> Result<(), DbError> {
+ for stmt in [
+ "CREATE TABLE IF NOT EXISTS waiting_on_person (
+ id TEXT PRIMARY KEY,
+ kwant_id TEXT NOT NULL,
+ channel_id TEXT,
+ direct_kwant_id TEXT,
+ thread_id TEXT,
+ question_id TEXT,
+ message_id TEXT,
+ question TEXT NOT NULL,
+ due_at TIMESTAMP,
+ status TEXT NOT NULL CHECK (status IN ('open', 'reminded', 'closed')),
+ created_at TIMESTAMP NOT NULL,
+ reminded_at TIMESTAMP
+ )",
+ "CREATE INDEX IF NOT EXISTS waiting_on_person_due ON waiting_on_person (status, due_at)",
+ // One entry per question, ever: a question is never reminded twice
+ "CREATE UNIQUE INDEX IF NOT EXISTS waiting_on_person_question ON waiting_on_person (question_id) WHERE question_id IS NOT NULL",
+ ] {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ Ok(())
+ }
+
+ /// Records what a bot waits for. `None` when it is already recorded: the same question, or
+ /// for a plain ask, an earlier one of this bot in this chat still waiting (it keeps its time,
+ /// so asking again doesn't bring a second reminder).
+ pub async fn add_waiting(&self, w: &NewWaitingItem) -> Result<Option<WaitingItem>, DbError> {
+ let mut tx = self.pool.begin().await?;
+ let existing: Option<(String,)> = match &w.question_id {
+ Some(q) => sqlx::query_as("SELECT id FROM waiting_on_person WHERE question_id = ?").bind(q).fetch_optional(&mut *tx).await?,
+ None => {
+ sqlx::query_as(&format!(
+ "SELECT id FROM waiting_on_person WHERE question_id IS NULL AND status != 'closed' AND {SAME_CHAT}"
+ ))
+ .bind(&w.kwant_id)
+ .bind(w.channel_id.as_deref().unwrap_or(""))
+ .bind(w.direct_kwant_id.as_deref().unwrap_or(""))
+ .bind(w.thread_id.as_deref().unwrap_or(""))
+ .fetch_optional(&mut *tx)
+ .await?
+ }
+ };
+ if existing.is_some() {
+ return Ok(None);
+ }
+ let row = sqlx::query_as::<_, WaitingItem>(
+ "INSERT INTO waiting_on_person (id, kwant_id, channel_id, direct_kwant_id, thread_id, question_id, message_id, question, due_at, status, created_at) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?) RETURNING *",
+ )
+ .bind(Uuid::new_v4().to_string())
+ .bind(&w.kwant_id)
+ .bind(&w.channel_id)
+ .bind(&w.direct_kwant_id)
+ .bind(&w.thread_id)
+ .bind(&w.question_id)
+ .bind(&w.message_id)
+ .bind(&w.question)
+ .bind(w.due_at)
+ .bind(Utc::now())
+ .fetch_one(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(Some(row))
+ }
+
+ pub async fn get_waiting(&self, id: &str) -> Result<Option<WaitingItem>, DbError> {
+ Ok(sqlx::query_as::<_, WaitingItem>("SELECT * FROM waiting_on_person WHERE id = ?").bind(id).fetch_optional(&self.pool).await?)
+ }
+
+ /// Still waiting (open or reminded), oldest first; `space` keeps that space's bots.
+ pub async fn list_waiting(&self, space: Option<&super::spaces::SpaceId>) -> Result<Vec<WaitingItem>, DbError> {
+ Ok(sqlx::query_as::<_, WaitingItem>(
+ "SELECT * FROM waiting_on_person WHERE status != 'closed'
+ AND (?1 IS NULL OR COALESCE((SELECT k.space_id FROM kwants k WHERE k.id = waiting_on_person.kwant_id), 'spc_default') = ?1)
+ ORDER BY created_at LIMIT 200",
+ )
+ .bind(space.map(|s| s.as_str()))
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// The question was answered or dismissed.
+ pub async fn close_waiting_for_question(&self, question_id: &str) -> Result<u64, DbError> {
+ let res = sqlx::query("UPDATE waiting_on_person SET status = 'closed' WHERE question_id = ? AND status != 'closed'")
+ .bind(question_id)
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected())
+ }
+
+ /// The person wrote in a chat: a thread (`thread_id`), a channel's main chat, or the direct
+ /// chat with a bot (`direct_kwant_id`, no channel). Everything waiting there ends.
+ pub async fn close_waiting_in_chat(
+ &self,
+ channel_id: Option<&str>,
+ direct_kwant_id: Option<&str>,
+ thread_id: Option<&str>,
+ ) -> Result<u64, DbError> {
+ let res = match (thread_id, channel_id, direct_kwant_id) {
+ (Some(t), _, _) => {
+ sqlx::query("UPDATE waiting_on_person SET status = 'closed' WHERE status != 'closed' AND thread_id = ?").bind(t).execute(&self.pool).await?
+ }
+ (None, Some(c), _) => sqlx::query(
+ "UPDATE waiting_on_person SET status = 'closed' WHERE status != 'closed' AND channel_id = ? AND thread_id IS NULL",
+ )
+ .bind(c)
+ .execute(&self.pool)
+ .await?,
+ (None, None, Some(k)) => sqlx::query(
+ "UPDATE waiting_on_person SET status = 'closed' WHERE status != 'closed' AND channel_id IS NULL \
+ AND thread_id IS NULL AND direct_kwant_id = ?",
+ )
+ .bind(k)
+ .execute(&self.pool)
+ .await?,
+ (None, None, None) => return Ok(0),
+ };
+ Ok(res.rows_affected())
+ }
+
+ /// The entries whose reminder is due by `now`, each claimed (`open` → `reminded`) so it goes
+ /// out once, whoever else is looking.
+ pub async fn take_due_waiting(&self, now: DateTime<Utc>) -> Result<Vec<WaitingItem>, DbError> {
+ let due = sqlx::query_as::<_, WaitingItem>(
+ "SELECT * FROM waiting_on_person WHERE status = 'open' AND due_at IS NOT NULL AND due_at <= ? ORDER BY due_at",
+ )
+ .bind(now)
+ .fetch_all(&self.pool)
+ .await?;
+ let mut claimed = Vec::new();
+ for w in due {
+ let res = sqlx::query("UPDATE waiting_on_person SET status = 'reminded', reminded_at = ? WHERE id = ? AND status = 'open'")
+ .bind(now)
+ .bind(&w.id)
+ .execute(&self.pool)
+ .await?;
+ if res.rows_affected() > 0 {
+ claimed.push(WaitingItem { status: "reminded".into(), reminded_at: Some(now), ..w });
+ }
+ }
+ Ok(claimed)
+ }
+
+ pub async fn next_waiting_due(&self) -> Result<Option<DateTime<Utc>>, DbError> {
+ let row: Option<(DateTime<Utc>,)> = sqlx::query_as(
+ "SELECT due_at FROM waiting_on_person WHERE status = 'open' AND due_at IS NOT NULL ORDER BY due_at LIMIT 1",
+ )
+ .fetch_optional(&self.pool)
+ .await?;
+ Ok(row.map(|(at,)| at))
+ }
+
+ /// Reminders were switched off: what is still waiting stays listed but is never reminded.
+ pub async fn clear_waiting_due(&self) -> Result<u64, DbError> {
+ let res = sqlx::query("UPDATE waiting_on_person SET due_at = NULL WHERE status = 'open' AND due_at IS NOT NULL")
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono::Duration;
+
+ fn item(kwant: &str, channel: Option<&str>, direct: Option<&str>, thread: Option<&str>, q: Option<&str>) -> NewWaitingItem {
+ NewWaitingItem {
+ kwant_id: kwant.into(),
+ channel_id: channel.map(Into::into),
+ direct_kwant_id: direct.map(Into::into),
+ thread_id: thread.map(Into::into),
+ question_id: q.map(Into::into),
+ message_id: None,
+ question: "Which one?".into(),
+ due_at: Some(Utc::now() - Duration::seconds(1)),
+ }
+ }
+
+ #[tokio::test]
+ async fn one_entry_per_question_and_one_reminder() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ assert!(db.add_waiting(&item("k", None, Some("k"), None, Some("q1"))).await.unwrap().is_some());
+ assert!(db.add_waiting(&item("k", None, Some("k"), None, Some("q1"))).await.unwrap().is_none());
+ // A plain ask in the same chat while one is waiting keeps the first
+ assert!(db.add_waiting(&item("k", None, Some("k"), None, None)).await.unwrap().is_some());
+ assert!(db.add_waiting(&item("k", None, Some("k"), None, None)).await.unwrap().is_none());
+ assert_eq!(db.take_due_waiting(Utc::now()).await.unwrap().len(), 2);
+ assert!(db.take_due_waiting(Utc::now()).await.unwrap().is_empty());
+ assert_eq!(db.next_waiting_due().await.unwrap(), None);
+ // Reminded entries are still listed until the person writes
+ assert_eq!(db.list_waiting(None).await.unwrap().len(), 2);
+ assert_eq!(db.close_waiting_in_chat(None, Some("k"), None).await.unwrap(), 2);
+ assert!(db.list_waiting(None).await.unwrap().is_empty());
+ // A closed question is never recorded again
+ assert!(db.add_waiting(&item("k", None, Some("k"), None, Some("q1"))).await.unwrap().is_none());
+ }
+
+ #[tokio::test]
+ async fn writing_closes_only_that_chat() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ db.add_waiting(&item("a", Some("c1"), None, None, None)).await.unwrap();
+ db.add_waiting(&item("b", Some("c1"), None, Some("t1"), None)).await.unwrap();
+ db.add_waiting(&item("a", None, Some("a"), None, None)).await.unwrap();
+ db.add_waiting(&item("b", Some("c2"), None, None, Some("q9"))).await.unwrap();
+ assert_eq!(db.close_waiting_in_chat(Some("c1"), None, None).await.unwrap(), 1);
+ assert_eq!(db.close_waiting_in_chat(None, None, Some("t1")).await.unwrap(), 1);
+ assert_eq!(db.close_waiting_for_question("q9").await.unwrap(), 1);
+ let left = db.list_waiting(None).await.unwrap();
+ assert_eq!(left.len(), 1);
+ assert_eq!(left[0].direct_kwant_id.as_deref(), Some("a"));
+ assert_eq!(db.clear_waiting_due().await.unwrap(), 1);
+ assert!(db.take_due_waiting(Utc::now()).await.unwrap().is_empty());
+ }
+}
diff --git a/src/router/sticky.rs b/src/router/sticky.rs
index 06ae3251..7afdee34 100644
--- a/src/router/sticky.rs
+++ b/src/router/sticky.rs
@@ -83,6 +83,11 @@ pub fn asks_the_person(text: &str) -> bool {
questions(last_line(text)).iter().any(|q| !is_closer(q))
}
+/// The question the last line of `text` asks the person, if it asks one (see [`asks_the_person`]).
+pub fn person_question(text: &str) -> Option<String> {
+ questions(last_line(text)).into_iter().rev().find(|q| !is_closer(q)).map(|q| q.trim().to_string())
+}
+
/// Closing offers that end a finished answer rather than wait for one. Matched on the question
/// sentence alone, so "Which city are you in? Anything else?" still asks.
const CLOSERS: &[&str] = &[
@@ -252,6 +257,13 @@ mod tests {
assert_eq!(a.kwant.id, "Analyst");
}
+ #[test]
+ fn the_question_asked_is_the_last_real_one() {
+ assert_eq!(person_question("Done.\nWhich city are you in? Anything else?").as_deref(), Some("Which city are you in?"));
+ assert_eq!(person_question("Done. Anything else?"), None);
+ assert_eq!(person_question("Which week?\nI'll start once you say."), None);
+ }
+
fn after(reply: &str) -> Option<String> {
let m = members();
let chat = [msg(0, "user", "user", "chart last week's signups"), msg(10, "kwant", "Analyst", reply)];
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 4f025577..fe1b96bc 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -307,7 +307,7 @@ fn exempt(path: &str) -> bool {
|| path == "/api/mcp/self"
}
-/// Routes only the person may call: saved passwords and the password vault (Bitwarden), changing app-wide settings, answering an approval card, Loose ends, Connections and Parallel Universe, the
+/// Routes only the person may call: saved passwords and the password vault (Bitwarden), changing app-wide settings, what bots wait on the person for, answering an approval card, Loose ends, Connections and Parallel Universe, the
/// approvals switch, and deleting a bot or team or undoing a bot action or import (those delete saved passwords too). A bot's turn token (or any
/// bearer that isn't the API token) is refused with 403 everywhere. From another machine they need the API token (401);
/// from this machine they don't, unless `KWNT_REQUIRE_TOKEN=always` (`person_token_needed`).
@@ -330,6 +330,8 @@ pub fn person_only(method: &Method, path: &str) -> bool {
["", "api", "signin", ..] => true,
// Web Push: where the person's notifications go
["", "api", "push", ..] => true,
+ // What the bots wait on the person for: their questions, across every chat
+ ["", "api", "waiting", ..] => true,
// App-wide settings, including where notifications go (`notify_webhook_url`), and the
// sub-routes such as `/computer` (which machine the bots run on) and `/computer/window`:
// bots change the allowed ones through their `settings_update` action, never these routes
@@ -836,6 +838,8 @@ mod tests {
assert!(person_only(&get, "/api/push/key"));
assert!(person_only(&post, "/api/push/subscribe"));
assert!(person_only(&post, "/api/push/unsubscribe"));
+ assert!(person_only(&get, "/api/waiting"));
+ assert!(person_only(&get, "/api/waiting/"));
assert!(person_only(&post, "/api/connections/composio"));
assert!(person_only(&get, "/api/parallel/prices"));
assert!(person_only(&post, "/api/parallel/scenarios"));
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 9c2d1e02..c8ebc707 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -39,6 +39,7 @@ pub mod document_routes;
pub mod connections;
pub mod setup_routes;
pub mod push;
+pub mod waiting;
use crate::broker::PermissionBroker;
use crate::config::Config;
@@ -336,6 +337,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/attachments", get(attachments::list).post(attachments::upload))
.route("/api/attachments/:id", get(attachments::get))
.route("/api/attachments/:id/content", get(attachments::content))
+ .route("/api/waiting", get(waiting::list))
.route("/api/questions", get(questions::list))
.route("/api/questions/:id", get(questions::get))
.route("/api/questions/:id/answer", post(questions::answer))
diff --git a/src/server/questions.rs b/src/server/questions.rs
index d81499c4..d5c9ca05 100644
--- a/src/server/questions.rs
+++ b/src/server/questions.rs
@@ -136,6 +136,8 @@ async fn close(state: &AppState, id: &str, status: &str, answer: Option<&str>) -
if !state.db.close_question(id, status, answer).await.ok()? {
return None;
}
+ // Nothing waits on the person for it any more, and its reminder (if not sent yet) never goes out
+ let _ = state.db.close_waiting_for_question(id).await;
let q = state.db.get_question(id).await.ok().flatten()?;
changed(state, &q).await;
Some(q)
@@ -447,3 +449,149 @@ pub async fn cancel(State(state): State<AppState>, Path(id): Path<String>) -> Re
}
Json(q).into_response()
}
+
+// The claude CLI's own question tool
+
+/// The claude CLI's built-in question tool. Under `-p` nobody can answer it inside the turn, so
+/// its questions are saved as open questions with cards: the person sees them, can answer later
+/// (a new turn gets the answer) and they count as waiting on the person.
+pub const NATIVE_ASK_TOOL: &str = "AskUserQuestion";
+
+/// The questions in an `AskUserQuestion` call, `{"questions": [{"question", "options": [{"label"}]}]}`,
+/// cleaned: each question clipped to the usual length, at most 5 distinct choices (it may have
+/// fewer than 2, the person can always type an answer). Inputs too long to pass whole arrive as
+/// a clipped JSON string; their question texts are still read, without choices.
+pub fn native_questions(args: &Value) -> Vec<(String, Vec<String>)> {
+ let clip = |s: &str, n: usize| -> String { s.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(n).collect() };
+ let parsed;
+ let args = match args {
+ Value::String(raw) => match serde_json::from_str::<Value>(raw) {
+ Ok(v) => {
+ parsed = v;
+ &parsed
+ }
+ Err(_) => {
+ return strings_after(raw, "\"question\"")
+ .iter()
+ .map(|q| clip(q, crate::db::questions::MAX_QUESTION_CHARS))
+ .filter(|q| !q.is_empty())
+ .map(|q| (q, Vec::new()))
+ .collect()
+ }
+ },
+ v => v,
+ };
+ let mut out = Vec::new();
+ for item in args["questions"].as_array().map(Vec::as_slice).unwrap_or_default() {
+ let q = clip(item["question"].as_str().unwrap_or(""), crate::db::questions::MAX_QUESTION_CHARS);
+ if q.is_empty() {
+ continue;
+ }
+ let mut choices: Vec<String> = Vec::new();
+ for o in item["options"].as_array().map(Vec::as_slice).unwrap_or_default() {
+ let label = o["label"].as_str().or_else(|| o.as_str()).unwrap_or("");
+ let c = clip(label, crate::db::questions::MAX_CHOICE_CHARS);
+ if !c.is_empty() && !choices.iter().any(|x| x.eq_ignore_ascii_case(&c)) && choices.len() < crate::db::questions::MAX_CHOICES {
+ choices.push(c);
+ }
+ }
+ out.push((q, choices));
+ }
+ out
+}
+
+/// The JSON string values after each `key:` in clipped JSON text; a string cut off at the end is
+/// skipped.
+fn strings_after(raw: &str, key: &str) -> Vec<String> {
+ let mut out = Vec::new();
+ let mut rest = raw;
+ while let Some(i) = rest.find(key) {
+ rest = &rest[i + key.len()..];
+ let Some(open) = rest.trim_start().strip_prefix(':').map(str::trim_start).and_then(|r| r.strip_prefix('"')) else {
+ continue;
+ };
+ let mut escaped = false;
+ let end = open.char_indices().find(|&(_, c)| {
+ let close = c == '"' && !escaped;
+ escaped = c == '\\' && !escaped;
+ close
+ });
+ if let Some((end, _)) = end {
+ if let Ok(s) = serde_json::from_str::<String>(&format!("\"{}\"", &open[..end])) {
+ out.push(s);
+ }
+ }
+ }
+ out
+}
+
+/// Saves the questions of a claude `AskUserQuestion` call as open questions with cards in the
+/// turn's chat, and tells the person. Returns how many were saved.
+pub async fn record_native(state: &AppState, place: &QuestionPlace, kwant_name: &str, args: &Value) -> usize {
+ let mut saved = 0;
+ for (question, choices) in native_questions(args) {
+ let created = state
+ .db
+ .create_question_with_card(place, &question, &choices, |q| {
+ let text = match choices.is_empty() {
+ true => q.question.clone(),
+ false => format!("{}\n\nChoices: {}", q.question, choices.join(" · ")),
+ };
+ let (msg, extra) = place_message(q, "kwant", &place.kwant_id, text);
+ Some((msg, MessageExtra { meta: Some(card_meta(q)), ..extra }))
+ })
+ .await;
+ let (q, card) = match created {
+ Ok(v) => v,
+ Err(e) => {
+ tracing::warn!(error = %e, kwant_id = %place.kwant_id, "could not save a claude AskUserQuestion");
+ break;
+ }
+ };
+ if let Some(card) = card {
+ if let Some(t) = &q.thread_id {
+ let _ = state.db.touch_thread(t).await;
+ }
+ let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&card).unwrap_or(Value::Null) });
+ }
+ changed(state, &q).await;
+ notify(
+ state,
+ Notification {
+ kind: "question_asked",
+ kwant_id: place.kwant_id.clone(),
+ kwant_name: kwant_name.to_string(),
+ channel_id: q.channel_id.clone(),
+ title: format!("{kwant_name} has a question"),
+ body: "Open the chat to answer.".into(),
+ },
+ )
+ .await;
+ tracing::info!(question_id = %q.id, kwant_id = %place.kwant_id, "saved a claude AskUserQuestion");
+ saved += 1;
+ }
+ saved
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn native_questions_are_read() {
+ let args = json!({"questions": [
+ {"question": "Which plan?", "header": "Plan", "multiSelect": false,
+ "options": [{"label": "Pro", "description": "x"}, {"label": "pro"}, {"label": "Max"}]},
+ {"question": " ", "options": []},
+ {"question": "Anything to add?"},
+ ]});
+ assert_eq!(
+ native_questions(&args),
+ vec![("Which plan?".to_string(), vec!["Pro".to_string(), "Max".to_string()]), ("Anything to add?".to_string(), vec![])]
+ );
+ let long = format!("{{\"questions\":[{{\"question\":\"Ship \\\"it\\\" now?\",\"options\":[{{\"label\":\"{}", "y".repeat(3000));
+ let clipped = Value::String(long.chars().take(2000).collect());
+ assert_eq!(native_questions(&clipped), vec![("Ship \"it\" now?".to_string(), vec![])]);
+ assert!(native_questions(&json!({"todos": []})).is_empty());
+ }
+}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index b436d9e6..dbe10718 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1551,10 +1551,14 @@ pub(super) async fn try_kwant_turn(
if let Some(started) = opts.on_started.take() {
started.await;
}
+ // A discussion round's reply isn't saved as is, so it isn't followed up
+ let follow_up = opts.discussion.is_none();
let reply = run_kwant_turn_inner(scope, target_kwant, prompt, opts, &tag).await;
if scope.cancel_token.is_cancelled() {
super::questions::cancel_for_turn(&scope.state, &tag.turn_id).await;
super::human_steps::cancel_for_turn(&scope.state, &tag.turn_id).await;
+ } else if let (Ok(text), true) = (&reply, follow_up) {
+ super::waiting::turn_ended(scope, target_kwant, &tag.turn_id, text).await;
}
ended.outcome = match (&reply, scope.cancel_token.is_cancelled()) {
(Ok(_), _) => "completed",
@@ -2155,6 +2159,18 @@ async fn run_kwant_turn_inner(
// Only resets the stall clock (above)
Some(RuntimeEvent::Progress) => {}
Some(event) => {
+ if let RuntimeEvent::ToolCallPending { name, args, .. } = &event {
+ if name == super::questions::NATIVE_ASK_TOOL {
+ let place = crate::db::questions::QuestionPlace {
+ kwant_id: target_kwant.id.clone(),
+ channel_id: scope.channel_id.clone(),
+ direct_kwant_id: scope.kwant_id.clone(),
+ thread_id: scope.thread_id.clone(),
+ turn_id: Some(tag.turn_id.clone()),
+ };
+ super::questions::record_native(state, &place, &target_kwant.name, args).await;
+ }
+ }
let visible = match &event {
RuntimeEvent::TextDelta(t) => !t.trim().is_empty(),
RuntimeEvent::ToolCallPending { .. } | RuntimeEvent::ApprovalRequired { .. } => true,
@@ -2658,6 +2674,8 @@ async fn send_chat_inner(
.insert_message_with(&user_msg, &user_extra)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+ // The person wrote here: the bots waiting on them in this chat don't need to remind them
+ super::waiting::person_wrote(&state, payload.channel_id.as_deref(), payload.kwant_id.as_deref(), None).await;
let note = super::attachments::attach_to_message(
&state,
&uploads,
@@ -3007,6 +3025,7 @@ async fn send_to_thread(
let extra = MessageExtra { thread_id: Some(thread.id.clone()), meta };
let saved = state.db.insert_message_with(&user_msg, &extra).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let _ = state.db.touch_thread(&thread.id).await;
+ super::waiting::person_wrote(&state, None, None, Some(&thread.id)).await;
let note = super::attachments::attach_to_message(&state, &uploads, &saved.id, None, None, Some(&thread.id)).await;
let job = state.turns.start_job([saved.id.clone(), thread.id.clone()]);
@@ -3101,6 +3120,8 @@ pub struct SettingsResponse {
pub location: String,
/// How long a CAPTCHA step waits for the person before the bot moves on (1–60).
pub captcha_timeout_minutes: u64,
+ /// Hours before a bot waiting on the person reminds them once; 0 = never.
+ pub waiting_follow_up_hours: i64,
}
/// Unknown keys are refused, so a typo or a key from another version fails loudly instead of
@@ -3128,6 +3149,7 @@ pub struct SaveSettingsPayload {
/// The person's city, plain text ("Ljubljana"); "" clears it. Never looked up anywhere.
pub location: Option<String>,
pub captcha_timeout_minutes: Option<u64>,
+ pub waiting_follow_up_hours: Option<i64>,
}
pub async fn get_settings(State(state): State<AppState>) -> Result<Json<SettingsResponse>, StatusCode> {
@@ -3164,6 +3186,7 @@ pub async fn get_settings(State(state): State<AppState>) -> Result<Json<Settings
.and_then(|v| v.parse::<u64>().ok())
.filter(|m| (1..=super::human_steps::MAX_CAPTCHA_TIMEOUT_MINUTES).contains(m))
.unwrap_or(super::human_steps::DEFAULT_CAPTCHA_TIMEOUT_MINUTES),
+ waiting_follow_up_hours: super::waiting::follow_up_hours(&state).await,
}))
}
@@ -3203,6 +3226,10 @@ pub async fn save_settings(
if payload.captcha_timeout_minutes.is_some_and(|m| !(1..=max_captcha).contains(&m)) {
return bad(format!("captcha_timeout_minutes must be 1–{max_captcha}"));
}
+ let max_hours = super::waiting::MAX_HOURS;
+ if payload.waiting_follow_up_hours.is_some_and(|h| !(0..=max_hours).contains(&h)) {
+ return bad(format!("waiting_follow_up_hours must be 0–{max_hours}"));
+ }
let timezone = payload.timezone.as_deref().map(crate::routines::canonical_tz);
if let Some(tz) = timezone.as_deref().filter(|t| !t.is_empty()) {
if let Err(e) = check_tz(tz) {
@@ -3273,6 +3300,10 @@ pub async fn save_settings(
if let Some(m) = payload.delegation_follow_up_minutes {
let _ = state.db.set_setting(super::delegation::FOLLOW_UP_SETTING, &m.to_string()).await;
}
+ if let Some(h) = payload.waiting_follow_up_hours {
+ let _ = state.db.set_setting(super::waiting::HOURS_SETTING, &h.to_string()).await;
+ state.scheduler_wake.notify_one();
+ }
if let Some(on) = payload.agent_tools {
let _ = state.db.set_setting("agent_tools", if on { "on" } else { "off" }).await;
}
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index f9fc6ecc..68a2a66b 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -649,11 +649,15 @@ pub fn spawn(state: AppState, shutdown: CancellationToken) -> tokio::task::JoinH
tick(&state, Utc::now()).await;
super::delegation::follow_ups(&state, Utc::now()).await;
super::parked::run_due(&state, Utc::now()).await;
- let next_parked = state.db.next_parked_due().await.ok().flatten();
- let next = match (state.db.next_routine_due().await.ok().flatten(), next_parked) {
- (Some(a), Some(b)) => Some(a.min(b)),
- (a, b) => a.or(b),
- };
+ super::waiting::run_due(&state, Utc::now()).await;
+ let next = [
+ state.db.next_routine_due().await.ok().flatten(),
+ state.db.next_parked_due().await.ok().flatten(),
+ state.db.next_waiting_due().await.ok().flatten(),
+ ]
+ .into_iter()
+ .flatten()
+ .min();
let sleep = match next {
Some(at) => (at - Utc::now())
.to_std()
diff --git a/src/server/waiting.rs b/src/server/waiting.rs
new file mode 100644
index 00000000..2c9bfcf2
--- /dev/null
+++ b/src/server/waiting.rs
@@ -0,0 +1,259 @@
+//! Follow-ups on what a bot waits for from the person. When a turn ends waiting (an open question
+//! card, or a reply whose last line asks the person something), one reminder is scheduled
+//! `waiting_follow_up_hours` later (default 24, 0 = none). The person writing in that chat, or the
+//! question closing, cancels it. The scheduler sends it once: a short note in the same chat and a
+//! notification. A reminder isn't a turn and is never scheduled again, so it can't loop.
+//! `GET /api/waiting` (person-only) lists everything waiting on the person.
+
+use super::continuity::{notify, Notification};
+use super::routes::TurnScope;
+use super::AppState;
+use crate::db::models::{Kwant, MessageExtra, NewMessage};
+use crate::db::waiting::{NewWaitingItem, WaitingItem};
+use crate::drivers::events::RuntimeEvent;
+use axum::{
+ extract::State,
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ Json,
+};
+use chrono::{DateTime, Duration, Utc};
+use serde_json::{json, Value};
+use std::collections::HashSet;
+
+pub const HOURS_SETTING: &str = "waiting_follow_up_hours";
+pub const DEFAULT_HOURS: i64 = 24;
+pub const MAX_HOURS: i64 = 30 * 24;
+/// Longest question quoted in a reminder.
+const REMINDER_QUOTE_CHARS: usize = 200;
+
+/// Hours before a reminder; 0 = no reminders.
+pub async fn follow_up_hours(state: &AppState) -> i64 {
+ state
+ .db
+ .get_setting(HOURS_SETTING)
+ .await
+ .ok()
+ .flatten()
+ .and_then(|v| v.trim().parse::<i64>().ok())
+ .map(|h| h.clamp(0, MAX_HOURS))
+ .unwrap_or(DEFAULT_HOURS)
+}
+
+fn last_line(text: &str) -> &str {
+ text.lines().rev().map(str::trim).find(|l| !l.is_empty()).unwrap_or("")
+}
+
+/// A turn ended with `reply` (not stopped, not failed). Records what its bot now waits for:
+/// the questions it asked in this turn that are still open, else (in a person's chat, not a
+/// delegation) a reply that ends by asking the person something without handing on to a teammate.
+pub(super) async fn turn_ended(scope: &TurnScope, kwant: &Kwant, turn_id: &str, reply: &str) {
+ let state = &scope.state;
+ let hours = follow_up_hours(state).await;
+ let due_at = (hours > 0).then(|| Utc::now() + Duration::hours(hours));
+ let open = state.db.list_questions(Some("open"), None, None).await.unwrap_or_default();
+ let asked: Vec<_> = open.into_iter().filter(|q| q.turn_id.as_deref() == Some(turn_id)).collect();
+ if !asked.is_empty() {
+ for q in asked {
+ let item = NewWaitingItem {
+ kwant_id: q.kwant_id.clone(),
+ channel_id: q.channel_id.clone(),
+ direct_kwant_id: q.direct_kwant_id.clone(),
+ thread_id: q.thread_id.clone(),
+ question_id: Some(q.id.clone()),
+ message_id: q.message_id.clone(),
+ question: q.question.clone(),
+ due_at,
+ };
+ let _ = state.db.add_waiting(&item).await;
+ }
+ state.scheduler_wake.notify_one();
+ return;
+ }
+ if scope.delegation_depth > 0 {
+ return;
+ }
+ let Some(question) = crate::router::sticky::person_question(reply) else {
+ return;
+ };
+ let names: Vec<&str> = scope.teammates.iter().filter(|k| k.id != kwant.id).map(|k| k.name.as_str()).collect();
+ if !crate::router::handoff_targets(last_line(reply), &names).is_empty() {
+ return;
+ }
+ let item = NewWaitingItem {
+ kwant_id: kwant.id.clone(),
+ channel_id: scope.channel_id.clone(),
+ direct_kwant_id: scope.kwant_id.clone(),
+ thread_id: scope.thread_id.clone(),
+ question_id: None,
+ message_id: None,
+ question: question.chars().take(crate::db::questions::MAX_QUESTION_CHARS).collect(),
+ due_at,
+ };
+ if matches!(state.db.add_waiting(&item).await, Ok(Some(_))) {
+ state.scheduler_wake.notify_one();
+ }
+}
+
+/// The person wrote in a chat: nothing there waits on them any more.
+pub async fn person_wrote(state: &AppState, channel_id: Option<&str>, direct_kwant_id: Option<&str>, thread_id: Option<&str>) {
+ let _ = state.db.close_waiting_in_chat(channel_id, direct_kwant_id, thread_id).await;
+}
+
+/// The reminder's text: one short line quoting what the bot asked.
+pub fn reminder_text(question: &str) -> String {
+ let q: String = question.chars().take(REMINDER_QUOTE_CHARS).collect();
+ let more = if q.chars().count() < question.chars().count() { "…" } else { "" };
+ format!("Still waiting on you: “{q}{more}”. Answer here when you can.")
+}
+
+/// Sends the reminders due by `now`, each once. With reminders switched off nothing is sent and
+/// what was scheduled is unscheduled. Returns how many went out.
+pub async fn run_due(state: &AppState, now: DateTime<Utc>) -> usize {
+ if follow_up_hours(state).await == 0 {
+ let _ = state.db.clear_waiting_due().await;
+ return 0;
+ }
+ let due = state.db.take_due_waiting(now).await.unwrap_or_default();
+ let mut sent = 0;
+ for w in due {
+ if remind(state, &w).await {
+ sent += 1;
+ }
+ }
+ sent
+}
+
+async fn remind(state: &AppState, w: &WaitingItem) -> bool {
+ // A question closed without its entry following (an older kwnt): nothing to remind of
+ if let Some(qid) = &w.question_id {
+ let open = state.db.get_question(qid).await.ok().flatten().is_some_and(|q| q.status == "open");
+ if !open {
+ let _ = state.db.close_waiting_for_question(qid).await;
+ return false;
+ }
+ }
+ let Ok(Some(kwant)) = state.db.get_kwant(&w.kwant_id).await else {
+ return false;
+ };
+ let msg = NewMessage {
+ channel_id: w.channel_id.clone(),
+ direct_kwant_id: w.direct_kwant_id.clone(),
+ sender_role: "kwant".into(),
+ sender_id: kwant.name.clone(),
+ text: reminder_text(&w.question),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ };
+ let meta = json!({"kind": "waiting_reminder", "waiting_id": w.id, "question_id": w.question_id, "question": w.question});
+ let extra = MessageExtra { thread_id: w.thread_id.clone(), meta: Some(meta) };
+ let Ok(saved) = state.db.insert_message_with(&msg, &extra).await else {
+ return false;
+ };
+ if let Some(t) = &w.thread_id {
+ let _ = state.db.touch_thread(t).await;
+ }
+ let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or(Value::Null) });
+ notify(
+ state,
+ Notification {
+ kind: "question_asked",
+ kwant_id: kwant.id.clone(),
+ kwant_name: kwant.name.clone(),
+ channel_id: w.channel_id.clone(),
+ title: format!("{} is still waiting on you", kwant.name),
+ body: "Open the chat to answer.".into(),
+ },
+ )
+ .await;
+ tracing::info!(waiting_id = %w.id, kwant_id = %kwant.id, "sent a waiting-on-you reminder");
+ true
+}
+
+/// `GET /api/waiting?space=`: everything the space's bots wait on the person for, oldest first:
+/// open question cards, replies that asked something, and open browser steps. `follow_up_at` is
+/// when the one reminder goes out (`null` once sent or with reminders off).
+pub async fn list(State(state): State<AppState>, super::spaces::Scope(space): super::spaces::Scope) -> Response {
+ let (Ok(waiting), Ok(questions), Ok(steps), Ok(kwants)) = (
+ state.db.list_waiting(Some(&space)).await,
+ state.db.list_questions(Some("open"), None, Some(&space)).await,
+ state.db.list_human_steps(Some("open"), None, Some(&space)).await,
+ state.db.list_kwants(&space).await,
+ ) else {
+ return StatusCode::INTERNAL_SERVER_ERROR.into_response();
+ };
+ let name = |id: &str| kwants.iter().find(|k| k.id == id).map(|k| k.name.clone());
+ let mut items = Vec::new();
+ let mut seen: HashSet<String> = HashSet::new();
+ for w in &waiting {
+ if let Some(q) = &w.question_id {
+ // Its question was closed without the entry following: not waiting any more
+ if !questions.iter().any(|x| &x.id == q) {
+ continue;
+ }
+ seen.insert(q.clone());
+ }
+ items.push((w.created_at, json!({
+ "kind": if w.question_id.is_some() { "question" } else { "reply" },
+ "kwant_id": w.kwant_id,
+ "kwant_name": name(&w.kwant_id),
+ "channel_id": w.channel_id,
+ "direct_kwant_id": w.direct_kwant_id,
+ "thread_id": w.thread_id,
+ "question_id": w.question_id,
+ "message_id": w.message_id,
+ "text": w.question,
+ "asked_at": w.created_at,
+ "follow_up_at": if w.status == "open" { w.due_at } else { None },
+ "reminded_at": w.reminded_at,
+ })));
+ }
+ // Questions whose turn is still running (or asked before this list existed)
+ for q in questions.iter().filter(|q| !seen.contains(&q.id)) {
+ items.push((q.created_at, json!({
+ "kind": "question",
+ "kwant_id": q.kwant_id,
+ "kwant_name": name(&q.kwant_id),
+ "channel_id": q.channel_id,
+ "direct_kwant_id": q.direct_kwant_id,
+ "thread_id": q.thread_id,
+ "question_id": q.id,
+ "message_id": q.message_id,
+ "text": q.question,
+ "asked_at": q.created_at,
+ "follow_up_at": null,
+ "reminded_at": null,
+ })));
+ }
+ for s in &steps {
+ items.push((s.created_at, json!({
+ "kind": "human_step",
+ "kwant_id": s.kwant_id,
+ "kwant_name": name(&s.kwant_id),
+ "channel_id": s.channel_id,
+ "direct_kwant_id": s.direct_kwant_id,
+ "thread_id": s.thread_id,
+ "human_step_id": s.id,
+ "text": s.reason,
+ "asked_at": s.created_at,
+ "follow_up_at": null,
+ "reminded_at": null,
+ })));
+ }
+ items.sort_by_key(|(at, _)| *at);
+ let items: Vec<Value> = items.into_iter().map(|(_, v)| v).collect();
+ Json(json!({ "items": items, "follow_up_hours": follow_up_hours(&state).await })).into_response()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn reminders_are_short() {
+ assert_eq!(reminder_text("Which city?"), "Still waiting on you: “Which city?”. Answer here when you can.");
+ let long = reminder_text(&"x".repeat(500));
+ assert!(long.contains("…") && long.chars().count() < 260);
+ }
+}
diff --git a/tests/waiting_test.rs b/tests/waiting_test.rs
new file mode 100644
index 00000000..adae0e00
--- /dev/null
+++ b/tests/waiting_test.rs
@@ -0,0 +1,292 @@
+//! Waiting on the person (F10): claude's own `AskUserQuestion` lands in the questions table, a
+//! turn that ends waiting on the person gets one reminder later, the person writing or answering
+//! cancels it, and `GET /api/waiting` (person-only) lists what waits. A fake claude CLI on PATH
+//! answers as the bot named in its system prompt ("You are <name>, …") from `$KWNT_TEST_BEHAVE/<name>`;
+//! a first line "ASK:<question>" makes it call `AskUserQuestion` (choices Yes / No) before it
+//! replies with the rest. Its own test binary: it changes PATH.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use chrono::{Duration as Hours, Utc};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{models::Message, Database},
+ router::LayaRouter,
+ server::{continuity::SelfScope, create_router, mcp_runtime, waiting, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::path::PathBuf;
+use std::sync::OnceLock;
+use std::time::Duration;
+use tower::ServiceExt;
+
+const FAKE_CLAUDE: &str = r#"#!/bin/sh
+case "$1" in
+ auth) echo '{"loggedIn":true}'; exit 0 ;;
+esac
+me=$(printf '%s\n' "$@" | sed -n 's/.*You are \([A-Za-z0-9]*\), .*/\1/p' | head -n 1)
+file="$KWNT_TEST_BEHAVE/$me"
+if [ ! -f "$file" ]; then
+ echo '{"type":"result","is_error":false,"num_turns":1,"result":"Done."}'
+ exit 0
+fi
+first=$(head -n 1 "$file")
+case "$first" in
+ ASK:*)
+ q="${first#ASK:}"
+ tu="tu_$(date +%s%N)"
+ printf '{"type":"assistant","message":{"content":[{"type":"tool_use","id":"%s","name":"AskUserQuestion","input":{"questions":[{"question":"%s","header":"Q","multiSelect":false,"options":[{"label":"Yes","description":"go"},{"label":"No","description":"stop"}]}]}}]}}\n' "$tu" "$q"
+ printf '{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"%s","is_error":true,"content":"no tty"}]}}\n' "$tu"
+ out=$(tail -n +2 "$file" | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/\\n/g') ;;
+ *) out=$(sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/\\n/g' "$file") ;;
+esac
+printf '{"type":"result","is_error":false,"num_turns":1,"result":"%s"}\n' "$out"
+"#;
+
+fn behave_dir() -> &'static PathBuf {
+ static DIR: OnceLock<PathBuf> = OnceLock::new();
+ DIR.get_or_init(|| {
+ let root = tempfile::tempdir().unwrap().keep();
+ let (bin, behave) = (root.join("bin"), root.join("behave"));
+ for d in [&bin, &behave] {
+ std::fs::create_dir_all(d).unwrap();
+ }
+ let fake = bin.join("claude");
+ std::fs::write(&fake, FAKE_CLAUDE).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ std::env::set_var("KWNT_TEST_BEHAVE", &behave);
+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));
+ behave
+ })
+}
+
+/// What bot `name` replies (see the module doc); names are unique per test.
+fn behave(name: &str, reply: &str) {
+ std::fs::write(behave_dir().join(name), reply).unwrap();
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>, bearer: Option<&str>) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ if let Some(t) = bearer {
+ req = req.header("authorization", format!("Bearer {t}"));
+ }
+ let resp = app
+ .clone()
+ .oneshot(req.body(body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty)).unwrap())
+ .await
+ .unwrap();
+ let s = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (s, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+struct Env {
+ app: Router,
+ state: AppState,
+ _tmp: tempfile::TempDir,
+}
+
+async fn setup() -> Env {
+ behave_dir();
+ let tmp = tempfile::tempdir().unwrap();
+ let data = tmp.path().join("data");
+ let db = Database::init(&data).await.unwrap();
+ // Laya is unreachable: turns use the kwant's preferred model, the fake claude
+ let config = Config {
+ data_dir: data.clone(),
+ laya_url: "http://127.0.0.1:9".into(),
+ browser_cdp_url: Some("http://127.0.0.1:9".into()),
+ ..Config::default()
+ };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(data.join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ Env { app: create_router(state.clone()), state, _tmp: tmp }
+}
+
+async fn add_bot(env: &Env, name: &str) -> String {
+ let (s, v) = call(&env.app, "POST", "/api/kwants", Some(json!({"name": name, "title": "Specialist", "persona_prompt": "", "soul": "", "avatar_sprite": "default", "driver_type": "cli", "preferred_model": "claude"})), None).await;
+ assert!(s.is_success(), "{s} {v}");
+ v["id"].as_str().or(v["kwant"]["id"].as_str()).unwrap().to_string()
+}
+
+/// The person writes in `bot`'s direct chat and the bot's turn runs to its end.
+async fn say_to(env: &Env, bot: &str, prompt: &str) {
+ let (s, v) = call(&env.app, "POST", "/api/chat/send", Some(json!({"kwant_id": bot, "prompt": prompt, "sender_id": "user"})), None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ settle(env).await;
+}
+
+async fn messages(env: &Env, bot: &str) -> Vec<Message> {
+ env.state.db.list_messages(bot, 200).await.unwrap()
+}
+
+fn meta(m: &Message) -> Value {
+ m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null)
+}
+
+fn reminders(msgs: &[Message]) -> usize {
+ msgs.iter().filter(|m| meta(m)["kind"] == "waiting_reminder").count()
+}
+
+async fn settle(env: &Env) {
+ let mut quiet = 0;
+ for _ in 0..400 {
+ quiet = if env.state.turns.active_turns().is_empty() { quiet + 1 } else { 0 };
+ if quiet >= 10 {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ panic!("the turn never ended");
+}
+
+async fn waiting_list(env: &Env) -> Vec<Value> {
+ let (s, v) = call(&env.app, "GET", "/api/waiting", None, None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ v["items"].as_array().cloned().unwrap_or_default()
+}
+
+/// One day and a bit from now: past any reminder scheduled with the default 24 h.
+fn tomorrow() -> chrono::DateTime<Utc> {
+ Utc::now() + Hours::hours(25)
+}
+
+#[tokio::test]
+async fn claude_ask_user_question_is_a_question_and_is_reminded_once() {
+ let env = setup().await;
+ let bot = add_bot(&env, "Asker1").await;
+ behave("Asker1", "ASK:Ship the release tonight?\nI asked whether to ship tonight.");
+ say_to(&env, &bot, "get the release ready").await;
+
+ let open = env.state.db.list_questions(Some("open"), None, None).await.unwrap();
+ assert_eq!(open.len(), 1, "{open:?}");
+ let q = &open[0];
+ assert_eq!((q.question.as_str(), q.choice_list()), ("Ship the release tonight?", vec!["Yes".to_string(), "No".to_string()]));
+ assert_eq!((q.kwant_id.as_str(), q.direct_kwant_id.as_deref()), (bot.as_str(), Some(bot.as_str())));
+ let msgs = messages(&env, &bot).await;
+ let card = msgs.iter().find(|m| Some(&m.id) == q.message_id.as_ref()).expect("the question has a card");
+ assert_eq!((meta(card)["kind"].as_str(), meta(card)["status"].as_str()), (Some("ask_user"), Some("open")));
+
+ // Waiting on the person, with one reminder in about a day
+ let items = waiting_list(&env).await;
+ assert_eq!(items.len(), 1, "{items:?}");
+ assert_eq!((items[0]["kind"].as_str(), items[0]["question_id"].as_str()), (Some("question"), Some(q.id.as_str())));
+ let at: chrono::DateTime<Utc> = serde_json::from_value(items[0]["follow_up_at"].clone()).unwrap();
+ assert!(at > Utc::now() + Hours::hours(23) && at < tomorrow(), "{at}");
+
+ // Not before it's due; then once, never twice
+ assert_eq!(waiting::run_due(&env.state, Utc::now()).await, 0);
+ assert_eq!(waiting::run_due(&env.state, tomorrow()).await, 1);
+ assert_eq!(waiting::run_due(&env.state, tomorrow() + Hours::hours(48)).await, 0);
+ let msgs = messages(&env, &bot).await;
+ assert_eq!(reminders(&msgs), 1);
+ let r = msgs.iter().find(|m| meta(m)["kind"] == "waiting_reminder").unwrap();
+ assert!(r.text.contains("Ship the release tonight?") && r.sender_role == "kwant", "{}", r.text);
+ // A reminder isn't a turn and ends no turn: nothing new is scheduled from it
+ settle(&env).await;
+ assert_eq!(env.state.db.next_waiting_due().await.unwrap(), None);
+ // Still waiting until the person answers
+ let items = waiting_list(&env).await;
+ assert_eq!(items.len(), 1);
+ assert!(items[0]["follow_up_at"].is_null() && !items[0]["reminded_at"].is_null(), "{items:?}");
+}
+
+#[tokio::test]
+async fn a_reply_that_asks_is_followed_up_and_a_plain_result_is_not() {
+ let env = setup().await;
+ let done = add_bot(&env, "Plain2").await;
+ behave("Plain2", "Here is the summary you wanted.\nAnything else?");
+ say_to(&env, &done, "summarise it").await;
+ assert!(waiting_list(&env).await.is_empty(), "a finished answer with a closer isn't waiting");
+
+ let asks = add_bot(&env, "Asks2").await;
+ behave("Asks2", "I can book it.\nWhich city are you in?");
+ say_to(&env, &asks, "book a table").await;
+ let items = waiting_list(&env).await;
+ assert_eq!(items.len(), 1, "{items:?}");
+ assert_eq!((items[0]["kind"].as_str(), items[0]["text"].as_str()), (Some("reply"), Some("Which city are you in?")));
+ assert_eq!(items[0]["kwant_name"], "Asks2");
+
+ // The person writes to that bot: no reminder, nothing waits any more
+ behave("Asks2", "Booked.");
+ say_to(&env, &asks, "Munich").await;
+ assert!(waiting_list(&env).await.is_empty());
+ assert_eq!(waiting::run_due(&env.state, tomorrow()).await, 0);
+ assert_eq!(reminders(&messages(&env, &asks).await), 0);
+}
+
+#[tokio::test]
+async fn answering_the_question_cancels_the_reminder() {
+ let env = setup().await;
+ let bot = add_bot(&env, "Asker3").await;
+ behave("Asker3", "ASK:Delete the old branch?\nWaiting for your answer.");
+ say_to(&env, &bot, "tidy the repo").await;
+ let q = env.state.db.list_questions(Some("open"), None, None).await.unwrap().pop().expect("a question");
+ behave("Asker3", "Deleted it.");
+ let (s, v) = call(&env.app, "POST", &format!("/api/questions/{}/answer", q.id), Some(json!({"choice": 0})), None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ settle(&env).await;
+ assert!(waiting_list(&env).await.is_empty());
+ assert_eq!(waiting::run_due(&env.state, tomorrow()).await, 0);
+ assert_eq!(reminders(&messages(&env, &bot).await), 0);
+}
+
+#[tokio::test]
+async fn zero_hours_turns_reminders_off() {
+ let env = setup().await;
+ let (s, v) = call(&env.app, "GET", "/api/settings", None, None).await;
+ assert_eq!((s, v["waiting_follow_up_hours"].as_i64()), (StatusCode::OK, Some(24)));
+ let bad = call(&env.app, "POST", "/api/settings", Some(json!({"waiting_follow_up_hours": -1})), None).await;
+ assert_eq!(bad.0, StatusCode::BAD_REQUEST);
+
+ // Scheduled with reminders on, then switched off: it never goes out
+ let bot = add_bot(&env, "Asks4").await;
+ behave("Asks4", "Which week should I chart?");
+ say_to(&env, &bot, "chart the signups").await;
+ assert!(env.state.db.next_waiting_due().await.unwrap().is_some());
+ let (s, _) = call(&env.app, "POST", "/api/settings", Some(json!({"waiting_follow_up_hours": 0})), None).await;
+ assert_eq!(s, StatusCode::OK);
+ assert_eq!(waiting::run_due(&env.state, tomorrow()).await, 0);
+
+ // Asked with reminders off: listed, never scheduled
+ let other = add_bot(&env, "Asks5").await;
+ behave("Asks5", "ASK:Which plan?\nWaiting.");
+ say_to(&env, &other, "pick a plan").await;
+ let items = waiting_list(&env).await;
+ assert_eq!(items.len(), 2, "{items:?}");
+ assert!(items.iter().all(|i| i["follow_up_at"].is_null()), "{items:?}");
+ assert_eq!(env.state.db.next_waiting_due().await.unwrap(), None);
+ assert_eq!(waiting::run_due(&env.state, tomorrow()).await, 0);
+ assert_eq!(reminders(&messages(&env, &bot).await) + reminders(&messages(&env, &other).await), 0);
+}
+
+#[tokio::test]
+async fn the_waiting_list_is_for_the_person_only() {
+ let env = setup().await;
+ let bot = add_bot(&env, "Bot6").await;
+ let kwant = env.state.db.get_kwant(&bot).await.unwrap().unwrap();
+ let turn_id = uuid::Uuid::new_v4().to_string();
+ let scope = SelfScope { kwant_id: bot.clone(), kwant_name: kwant.name.clone(), turn_id: Some(turn_id.clone()), ..Default::default() };
+ let (_, token) = mcp_runtime::prepare_turn_with_opts(&env.state, &kwant, Some(turn_id), None, Some(scope), Default::default())
+ .await
+ .unwrap();
+ let (s, v) = call(&env.app, "GET", "/api/waiting", None, Some(&token)).await;
+ assert_eq!(s, StatusCode::FORBIDDEN, "a bot's turn token: {v}");
+ let (s, _) = call(&env.app, "GET", "/api/waiting", None, None).await;
+ assert_eq!(s, StatusCode::OK);
+ mcp_runtime::finish_turn(&env.state, &token).await;
+}