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.

22i: Needs attention says what is needed and closes when it's done (server) (#700)

Oleksandr Ivanchenko9b8a30170b02
diff --git a/docs/live-activity.md b/docs/live-activity.md
index b3dfe235..bbbe0ed2 100644
--- a/docs/live-activity.md
+++ b/docs/live-activity.md
@@ -319,3 +319,46 @@ the same chat (`resumed: "new_turn"`).
`take_control` again.
- If the browser wasn't running when the step opened, only the database check protects it: bot
tools are refused, and the person takes control as usual.
+
+## 3. Needs attention: what each item asks, and when it closes (22i)
+
+### `GET /api/away` item fields
+
+Every item in `waiting`, `finished` and `failed` carries:
+
+- `action`: `"retry" | "continue" | "ask_again" | "answer" | "decide" | "browser"`, or `null`
+ for finished work (nothing to do but look).
+- `dismissable`: `true` for a stop and for a failed or stuck hand-off or routine run.
+- `link.thread_kwant_id`: present only when the item's thread belongs to another bot. Open the
+ thread under this bot, not the item's `kwant_id`.
+- `task_id`: only on a `failed` or `interrupted` hand-off (`kind: "delegation"`) whose board task
+ is `failed`. Its Retry is `POST /api/tasks/:task_id/retry`, and `action` is `"retry"` only then.
+ Without it (the board is off by default) a failed hand-off has `action: null` and
+ `dismissable: true`: the person opens its thread and asks the bot again there, and that bot's
+ next finished reply closes the row (`later_reply`), or they dismiss it. There is no
+ `/api/waiting/:id/retry`.
+
+### `POST /api/waiting/:id/dismiss` (the person only)
+
+Optional body `{"kind": "<the item's kind>"}`. Clears one item without resuming it, records
+why (`attention_closed`, reason `dismissed`) and sends `waiting_updated`.
+
+| Status | `code` | When |
+|---|---|---|
+| 200 | | `{id, kind, status: "closed", already_closed}` (`kind`: `waiting`, `delegation` or `routine_run`) |
+| 400 | `bad_kind`, `bad_body` | unknown kind, or a body that isn't JSON |
+| 403 | `person_only` | a bot's token |
+| 404 | `not_found` | nothing open or closed with that id |
+| 409 | `use_question_answer`, `use_approval_decide`, `use_step_decline`, `use_watch_decide` | it has its own answer, which tells the bot |
+
+### SSE `waiting_updated` (routed to the item's chat)
+
+Sent when an item opens and every time one closes, whatever closed it.
+
+```json
+{ "type": "waiting_updated", "data": { "item": {
+ "id": "…", "kind": "stopped|reply|question|delegation|routine_run",
+ "status": "open|closed",
+ "reason": null | "later_reply|person_wrote|answered|replaced|resumed|place_gone|dismissed",
+ "kwant_id": "…", "channel_id": null, "direct_kwant_id": "…", "thread_id": null } } }
+```
diff --git a/src/db/away.rs b/src/db/away.rs
index 39df2d2e..28be8d07 100644
--- a/src/db/away.rs
+++ b/src/db/away.rs
@@ -13,6 +13,20 @@ use sqlx::FromRow;
/// keys: only `POST /api/away/seen` writes it.
pub const LAST_SEEN_KEY: &str = "away_last_seen";
+/// 22i: what [`Database::dismiss_attention`] did.
+#[derive(Debug)]
+pub enum Dismissed {
+ /// Closed now. `kind` is "waiting", "delegation" or "routine_run"; `waiting` the closed row.
+ Closed { kind: String, kwant_id: Option<String>, waiting: Option<Box<super::waiting::WaitingItem>> },
+ /// It had already left Needs attention (a second Dismiss, or it closed by itself first).
+ AlreadyClosed { kind: String },
+ NotFound,
+ /// It isn't the person's to dismiss: the code names what to use instead.
+ Refused(&'static str),
+ /// `kind` is none of the kinds `/api/away` lists.
+ BadKind,
+}
+
/// A row behind one item, before its summary is cleaned. Every query selects these columns.
#[derive(Debug, Clone, FromRow)]
pub struct AwayRow {
@@ -57,7 +71,10 @@ const DELEGATIONS_STUCK: &str = "
NULL AS channel_id, NULL AS direct_kwant_id, NULL AS choices
FROM delegations d LEFT JOIN kwants k ON k.id = d.specialist_kwant_id
WHERE d.status = 'running' AND d.started_at < ?1
- AND COALESCE(k.space_id, 'spc_default') = ?3";
+ AND COALESCE(k.space_id, 'spc_default') = ?3
+ AND k.id IS NOT NULL
+ AND EXISTS (SELECT 1 FROM threads t WHERE t.id = d.thread_id)
+ AND NOT EXISTS (SELECT 1 FROM attention_closed x WHERE x.kind = 'delegation' AND x.ref_id = d.id)";
/// `?1` = since. A routine posts in its channel, or the kwant's direct chat when it has none.
const ROUTINE_RUNS_ENDED: &str = "
@@ -73,9 +90,29 @@ const ROUTINE_RUNS_ENDED: &str = "
AND COALESCE(k.space_id, 'spc_default') = ?3";
const FINISHED_DELEGATIONS: &str = "d.status = 'completed'";
-const FAILED_DELEGATIONS: &str = "d.status IN ('failed', 'interrupted')";
+/// 22i close rules for a failed hand-off (each one drops it from Needs attention, the Inbox and
+/// the badge): its bot or thread is gone, a later hand-off to the same bot in that thread started
+/// (a retry), or it is in `attention_closed` (a later reply of the bot there finished, or the
+/// person dismissed it).
+const FAILED_DELEGATIONS: &str = "d.status IN ('failed', 'interrupted')
+ AND k.id IS NOT NULL
+ AND EXISTS (SELECT 1 FROM threads t WHERE t.id = d.thread_id)
+ AND NOT EXISTS (SELECT 1 FROM delegations d2 WHERE d2.specialist_kwant_id = d.specialist_kwant_id
+ AND d2.thread_id = d.thread_id AND d2.created_at > d.created_at AND d2.status != 'cancelled')
+ AND NOT EXISTS (SELECT 1 FROM attention_closed x WHERE x.kind = 'delegation' AND x.ref_id = d.id)";
const FINISHED_RUNS: &str = "r.status = 'ok'";
-const FAILED_RUNS: &str = "r.status = 'error'";
+/// 22i close rules for a failed routine run: its bot or channel is gone, a later run of the same
+/// routine started (Run now or the next schedule), or it is in `attention_closed`.
+const FAILED_RUNS: &str = "r.status = 'error'
+ AND k.id IS NOT NULL
+ AND (rt.channel_id IS NULL OR EXISTS (SELECT 1 FROM channels c WHERE c.id = rt.channel_id))
+ AND NOT EXISTS (SELECT 1 FROM routine_runs r2 WHERE r2.routine_id = r.routine_id
+ AND r2.started_at > r.started_at AND r2.status != 'skipped')
+ AND NOT EXISTS (SELECT 1 FROM attention_closed x WHERE x.kind = 'routine_run' AND x.ref_id = r.id)";
+
+/// Why a failed or stuck item left Needs attention (`attention_closed.reason`).
+pub const CLOSED_LATER_REPLY: &str = "later_reply";
+pub const CLOSED_DISMISSED: &str = "dismissed";
impl Database {
/// Additive: partial indexes so the away queries never scan delegations or routine runs.
@@ -88,6 +125,18 @@ impl Database {
// 0.9.5 B: a lead's reply that ended with `Done: …` (keep_going's `chain_done` meta), so
// team jobs are found without scanning messages
"CREATE INDEX IF NOT EXISTS messages_chain_done ON messages (created_at) WHERE instr(meta, '\"chain_done\"') > 0",
+ // 22i: failed or stuck items that left Needs attention without their row changing (a
+ // later reply of the bot in that chat, or the person's Dismiss); also the Dismiss audit
+ // trail for waiting items (`kind` 'waiting'). Additive: an old binary ignores it.
+ "CREATE TABLE IF NOT EXISTS attention_closed (
+ kind TEXT NOT NULL,
+ ref_id TEXT NOT NULL,
+ kwant_id TEXT,
+ reason TEXT NOT NULL,
+ closed_at TIMESTAMP NOT NULL,
+ PRIMARY KEY (kind, ref_id)
+ )",
+ "CREATE INDEX IF NOT EXISTS delegations_by_specialist_thread ON delegations (specialist_kwant_id, thread_id, created_at)",
] {
sqlx::query(stmt).execute(&self.pool).await?;
}
@@ -210,6 +259,147 @@ impl Database {
.await?)
}
+ /// 22i: records that a failed or stuck item (`kind` "delegation" or "routine_run", or
+ /// "waiting" for the Dismiss audit of a waiting item) left Needs attention, and why. `false`
+ /// when it already had.
+ pub async fn close_attention(&self, kind: &str, ref_id: &str, kwant_id: Option<&str>, reason: &str) -> Result<bool, DbError> {
+ let res = sqlx::query("INSERT OR IGNORE INTO attention_closed (kind, ref_id, kwant_id, reason, closed_at) VALUES (?, ?, ?, ?, ?)")
+ .bind(kind)
+ .bind(ref_id)
+ .bind(kwant_id)
+ .bind(reason)
+ .bind(Utc::now())
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected() > 0)
+ }
+
+ /// Why `(kind, ref_id)` left Needs attention, if it did through [`Self::close_attention`].
+ pub async fn attention_closed_reason(&self, kind: &str, ref_id: &str) -> Result<Option<String>, DbError> {
+ Ok(sqlx::query_scalar("SELECT reason FROM attention_closed WHERE kind = ? AND ref_id = ?")
+ .bind(kind)
+ .bind(ref_id)
+ .fetch_optional(&self.pool)
+ .await?)
+ }
+
+ /// The bot behind a failed or stuck item the person can dismiss: a hand-off's specialist, a
+ /// routine run's bot. `None` when there is no such item.
+ pub async fn attention_item_owner(&self, kind: &str, ref_id: &str) -> Result<Option<String>, DbError> {
+ let sql = match kind {
+ "delegation" => "SELECT specialist_kwant_id FROM delegations WHERE id = ? AND status IN ('failed', 'interrupted', 'running')",
+ "routine_run" => "SELECT rt.kwant_id FROM routine_runs r JOIN routines rt ON rt.id = r.routine_id WHERE r.id = ? AND r.status = 'error'",
+ _ => return Ok(None),
+ };
+ Ok(sqlx::query_scalar(sql).bind(ref_id).fetch_optional(&self.pool).await?)
+ }
+
+ /// 22i: the board task a failed hand-off's Retry can rerun (`POST /api/tasks/:id/retry`, which
+ /// moves only a `failed` task). `None` when the board has no such task (it is off by default)
+ /// or the task isn't failed: the row then offers no Retry, only its thread and Dismiss.
+ pub async fn retryable_hand_off_task(&self, delegation_id: &str) -> Result<Option<String>, DbError> {
+ Ok(sqlx::query_scalar(
+ "SELECT id FROM tasks WHERE source_kind = 'delegation' AND source_id = ? AND state = 'failed' ORDER BY created_at DESC LIMIT 1",
+ )
+ .bind(delegation_id)
+ .fetch_optional(&self.pool)
+ .await?)
+ }
+
+ /// 22i: the person's Dismiss (`POST /api/waiting/:id/dismiss`) of one Needs-attention item.
+ /// `kind` is the item's `kind` from `/api/away` (`stopped`, `reply`, `delegation`,
+ /// `routine_run`, …); without it, `id` is looked up as a waiting item, then a hand-off, then a
+ /// routine run. Each dismiss is recorded in `attention_closed` (reason `dismissed`).
+ pub async fn dismiss_attention(&self, id: &str, kind: Option<&str>) -> Result<Dismissed, DbError> {
+ match kind {
+ Some("question") => return Ok(Dismissed::Refused("use_question_answer")),
+ Some("approval") => return Ok(Dismissed::Refused("use_approval_decide")),
+ Some("human_step" | "browser") => return Ok(Dismissed::Refused("use_step_decline")),
+ Some("watch") => return Ok(Dismissed::Refused("use_watch_decide")),
+ Some(k @ ("delegation" | "routine_run")) => return self.dismiss_failed(k, id).await,
+ None | Some("stopped" | "reply" | "waiting") => {}
+ Some(_) => return Ok(Dismissed::BadKind),
+ }
+ if let Some(w) = self.get_waiting(id).await? {
+ // Its question has an answer or a cancel that tells the bot; a dismiss would not
+ if w.question_id.is_some() {
+ return Ok(Dismissed::Refused("use_question_answer"));
+ }
+ let Some(closed) = self.claim_waiting(id).await? else {
+ return Ok(Dismissed::AlreadyClosed { kind: "waiting".into() });
+ };
+ self.close_attention("waiting", id, Some(&closed.kwant_id), CLOSED_DISMISSED).await?;
+ return Ok(Dismissed::Closed { kind: "waiting".into(), kwant_id: Some(closed.kwant_id.clone()), waiting: Some(Box::new(closed)) });
+ }
+ if kind.is_none() {
+ for k in ["delegation", "routine_run"] {
+ let r = self.dismiss_failed(k, id).await?;
+ if !matches!(r, Dismissed::NotFound) {
+ return Ok(r);
+ }
+ }
+ }
+ Ok(Dismissed::NotFound)
+ }
+
+ async fn dismiss_failed(&self, kind: &str, id: &str) -> Result<Dismissed, DbError> {
+ if self.attention_closed_reason(kind, id).await?.is_some() {
+ return Ok(Dismissed::AlreadyClosed { kind: kind.into() });
+ }
+ let Some(owner) = self.attention_item_owner(kind, id).await? else {
+ return Ok(Dismissed::NotFound);
+ };
+ if !self.close_attention(kind, id, Some(&owner), CLOSED_DISMISSED).await? {
+ return Ok(Dismissed::AlreadyClosed { kind: kind.into() });
+ }
+ Ok(Dismissed::Closed { kind: kind.into(), kwant_id: Some(owner), waiting: None })
+ }
+
+ /// 22i: a reply of `kwant_id` finished in this chat, so its failed items there are over: a
+ /// failed hand-off in this thread, a failed run of its routine that posts here. Records each
+ /// in `attention_closed` and returns them as `(kind, id)`.
+ pub async fn close_failed_in_chat(
+ &self,
+ kwant_id: &str,
+ channel_id: Option<&str>,
+ direct_kwant_id: Option<&str>,
+ thread_id: Option<&str>,
+ ) -> Result<Vec<(String, String)>, DbError> {
+ let mut found: Vec<(String, String)> = Vec::new();
+ if let Some(t) = thread_id {
+ let ids: Vec<String> = sqlx::query_scalar(
+ "SELECT d.id FROM delegations d WHERE d.specialist_kwant_id = ? AND d.thread_id = ? AND d.status IN ('failed', 'interrupted')
+ AND NOT EXISTS (SELECT 1 FROM attention_closed x WHERE x.kind = 'delegation' AND x.ref_id = d.id)",
+ )
+ .bind(kwant_id)
+ .bind(t)
+ .fetch_all(&self.pool)
+ .await?;
+ found.extend(ids.into_iter().map(|id| ("delegation".to_string(), id)));
+ } else {
+ // A routine posts in its channel's main chat, or its bot's direct chat when it has none
+ let ids: Vec<String> = sqlx::query_scalar(
+ "SELECT r.id FROM routine_runs r JOIN routines rt ON rt.id = r.routine_id
+ WHERE rt.kwant_id = ?1 AND r.status = 'error'
+ AND ((?2 IS NOT NULL AND rt.channel_id = ?2) OR (?2 IS NULL AND rt.channel_id IS NULL AND ?3 = ?1))
+ AND NOT EXISTS (SELECT 1 FROM attention_closed x WHERE x.kind = 'routine_run' AND x.ref_id = r.id)",
+ )
+ .bind(kwant_id)
+ .bind(channel_id)
+ .bind(direct_kwant_id)
+ .fetch_all(&self.pool)
+ .await?;
+ found.extend(ids.into_iter().map(|id| ("routine_run".to_string(), id)));
+ }
+ let mut closed = Vec::new();
+ for (kind, id) in found {
+ if self.close_attention(&kind, &id, Some(kwant_id), CLOSED_LATER_REPLY).await? {
+ closed.push((kind, id));
+ }
+ }
+ Ok(closed)
+ }
+
async fn ended(
&self,
sql: &str,
@@ -464,4 +654,256 @@ mod tests {
assert!(detail.iter().any(|d| d.contains(idx)), "{idx} unused: {detail:?}\n{sql}");
}
}
+
+ async fn bot(db: &Database, id: &str) {
+ sqlx::query("INSERT INTO kwants (id, name, title, persona_prompt, avatar_sprite, space_id) VALUES (?, ?, 't', 'p', 'a', 'spc_default')")
+ .bind(id)
+ .bind(format!("Bot {id}"))
+ .execute(&db.pool)
+ .await
+ .unwrap();
+ }
+
+ async fn hand_off(db: &Database, id: &str, thread: &str, specialist: &str, status: &str, mins_ago: i64) {
+ let at = Utc::now() - chrono::Duration::minutes(mins_ago);
+ let ended = (status != "running" && status != "queued").then_some(at + chrono::Duration::seconds(1));
+ sqlx::query(
+ "INSERT INTO delegations (id, thread_id, lead_kwant_id, specialist_kwant_id, task, title, status, created_at, started_at, ended_at) \
+ VALUES (?, ?, 'lead', ?, 'task', ?, ?, ?, ?, ?)",
+ )
+ .bind(id)
+ .bind(thread)
+ .bind(specialist)
+ .bind(format!("job {id}"))
+ .bind(status)
+ .bind(at)
+ .bind(at)
+ .bind(ended)
+ .execute(&db.pool)
+ .await
+ .unwrap();
+ }
+
+ async fn run(db: &Database, id: &str, routine: &str, status: &str, mins_ago: i64) {
+ let at = Utc::now() - chrono::Duration::minutes(mins_ago);
+ sqlx::query("INSERT INTO routine_runs (id, routine_id, trigger, started_at, ended_at, status, error) VALUES (?, ?, 'schedule', ?, ?, ?, 'boom')")
+ .bind(id)
+ .bind(routine)
+ .bind(at)
+ .bind(at + chrono::Duration::seconds(1))
+ .bind(status)
+ .execute(&db.pool)
+ .await
+ .unwrap();
+ }
+
+ async fn failed_ids(db: &Database) -> Vec<String> {
+ let space = SpaceId::default_space();
+ let since = Utc::now() - chrono::Duration::days(7);
+ let stuck_before = Utc::now() - chrono::Duration::minutes(30);
+ let mut ids: Vec<String> = db.away_failed(&space, since, stuck_before, 50).await.unwrap().into_iter().map(|r| r.id).collect();
+ ids.sort();
+ let (_, counted) = db.away_counts(&space, since, stuck_before).await.unwrap();
+ assert_eq!(counted as usize, ids.len(), "the badge counts what is listed");
+ ids
+ }
+
+ /// 22i close rules for a failed hand-off: a later reply of the bot in that thread, a retry
+ /// there, the person's Dismiss, or its thread or bot gone.
+ #[tokio::test]
+ async fn a_failed_hand_off_closes_on_a_later_reply_a_retry_dismiss_or_a_gone_place() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ bot(&db, "k1").await;
+ bot(&db, "k2").await;
+ let mut t = Vec::new();
+ for i in 0..5 {
+ t.push(db.create_thread("lead", &format!("t{i}"), "delegation", None, "lead").await.unwrap().id);
+ }
+ hand_off(&db, "d1", &t[0], "k1", "failed", 60).await;
+ hand_off(&db, "d2", &t[1], "k1", "interrupted", 60).await;
+ hand_off(&db, "d4", &t[2], "k1", "failed", 60).await;
+ hand_off(&db, "d5", &t[3], "k1", "failed", 60).await;
+ hand_off(&db, "d6", &t[4], "k2", "failed", 60).await;
+ assert_eq!(failed_ids(&db).await, vec!["d1", "d2", "d4", "d5", "d6"]);
+ // A later reply of k1 in t0 finished: d1 is over (only there, only k1's)
+ let closed = db.close_failed_in_chat("k1", None, None, Some(&t[0])).await.unwrap();
+ assert_eq!(closed, vec![("delegation".to_string(), "d1".to_string())]);
+ assert!(db.close_failed_in_chat("k1", None, None, Some(&t[0])).await.unwrap().is_empty(), "closes once");
+ assert_eq!(db.attention_closed_reason("delegation", "d1").await.unwrap().as_deref(), Some(CLOSED_LATER_REPLY));
+ // Retried: a later hand-off to k1 in t1
+ hand_off(&db, "d3", &t[1], "k1", "queued", 1).await;
+ // Dismissed by the person
+ assert_eq!(db.attention_item_owner("delegation", "d4").await.unwrap().as_deref(), Some("k1"));
+ assert!(db.close_attention("delegation", "d4", Some("k1"), CLOSED_DISMISSED).await.unwrap());
+ assert!(!db.close_attention("delegation", "d4", Some("k1"), CLOSED_DISMISSED).await.unwrap());
+ // Its thread was deleted; its bot was deleted
+ sqlx::query("DELETE FROM threads WHERE id = ?").bind(&t[3]).execute(&db.pool).await.unwrap();
+ sqlx::query("DELETE FROM kwants WHERE id = 'k2'").execute(&db.pool).await.unwrap();
+ assert!(failed_ids(&db).await.is_empty());
+ }
+
+ /// 22i close rules for a failed routine run: a later reply of its bot in the routine's chat,
+ /// a later run of the routine, the person's Dismiss, or its bot gone.
+ #[tokio::test]
+ async fn a_failed_routine_run_closes_on_a_later_reply_a_rerun_dismiss_or_a_gone_bot() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ bot(&db, "k1").await;
+ bot(&db, "k2").await;
+ for (id, kwant) in [("rt1", "k1"), ("rt2", "k1"), ("rt3", "k1"), ("rt4", "k2")] {
+ sqlx::query("INSERT INTO routines (id, kwant_id, name, instructions, schedule, space_id) VALUES (?, ?, ?, 'do it', '0 9 * * *', 'spc_default')")
+ .bind(id)
+ .bind(kwant)
+ .bind(format!("routine {id}"))
+ .execute(&db.pool)
+ .await
+ .unwrap();
+ }
+ run(&db, "r1", "rt1", "error", 60).await;
+ run(&db, "r2", "rt2", "error", 60).await;
+ run(&db, "r3", "rt3", "error", 60).await;
+ run(&db, "r4", "rt4", "error", 60).await;
+ assert_eq!(failed_ids(&db).await, vec!["r1", "r2", "r3", "r4"]);
+ // A reply in another chat closes nothing; one in the routines' chat (k1's direct) closes k1's
+ assert!(db.close_failed_in_chat("k1", Some("c-other"), None, None).await.unwrap().is_empty());
+ let closed = db.close_failed_in_chat("k1", None, Some("k1"), None).await.unwrap();
+ assert_eq!(closed.len(), 3);
+ sqlx::query("DELETE FROM attention_closed WHERE ref_id IN ('r2', 'r3')").execute(&db.pool).await.unwrap();
+ assert_eq!(failed_ids(&db).await, vec!["r2", "r3", "r4"]);
+ // Run again (any later run that wasn't skipped)
+ run(&db, "r2b", "rt2", "ok", 1).await;
+ // Dismissed
+ assert_eq!(db.attention_item_owner("routine_run", "r3").await.unwrap().as_deref(), Some("k1"));
+ db.close_attention("routine_run", "r3", Some("k1"), CLOSED_DISMISSED).await.unwrap();
+ // Its bot is gone
+ sqlx::query("DELETE FROM kwants WHERE id = 'k2'").execute(&db.pool).await.unwrap();
+ assert!(failed_ids(&db).await.is_empty());
+ assert_eq!(db.attention_item_owner("routine_run", "r2b").await.unwrap(), None, "only a failed run is dismissable");
+ }
+
+ /// 22i: a hand-off still running past the stuck threshold closes when it ends (as before) or
+ /// when the person dismisses it.
+ #[tokio::test]
+ async fn a_stuck_hand_off_closes_when_it_ends_or_is_dismissed() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ bot(&db, "k1").await;
+ let t = db.create_thread("lead", "t", "delegation", None, "lead").await.unwrap().id;
+ let t2 = db.create_thread("lead", "t2", "delegation", None, "lead").await.unwrap().id;
+ hand_off(&db, "s1", &t, "k1", "running", 120).await;
+ hand_off(&db, "s2", &t2, "k1", "running", 120).await;
+ assert_eq!(failed_ids(&db).await, vec!["s1", "s2"]);
+ db.close_attention("delegation", "s1", Some("k1"), CLOSED_DISMISSED).await.unwrap();
+ sqlx::query("UPDATE delegations SET status = 'completed', ended_at = ? WHERE id = 's2'").bind(Utc::now()).execute(&db.pool).await.unwrap();
+ assert!(failed_ids(&db).await.is_empty());
+ }
+
+ /// 22i: the person's Dismiss closes a stop or a failed hand-off once, says so on a second try,
+ /// refuses what has its own answer and knows nothing of an unknown id.
+ #[tokio::test]
+ async fn dismiss_closes_a_stop_or_failed_item_once_and_refuses_what_has_its_own_answer() {
+ use crate::db::waiting::NewWaitingItem;
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ bot(&db, "k1").await;
+ let (stop, _) = db.add_stopped("k1", None, Some("k1"), None, Some("m1"), "The model sent nothing for 120 s", None).await.unwrap();
+ let ask = NewWaitingItem {
+ kwant_id: "k1".into(),
+ channel_id: None,
+ direct_kwant_id: Some("k1".into()),
+ thread_id: None,
+ question_id: Some("q1".into()),
+ message_id: None,
+ question: "Which city?".into(),
+ due_at: None,
+ };
+ let asked = db.add_waiting(&ask).await.unwrap().unwrap();
+ let t = db.create_thread("lead", "t", "delegation", None, "lead").await.unwrap().id;
+ hand_off(&db, "d1", &t, "k1", "failed", 5).await;
+ assert_eq!(failed_ids(&db).await, vec!["d1"]);
+
+ match db.dismiss_attention(&stop.id, None).await.unwrap() {
+ Dismissed::Closed { kind, kwant_id, waiting } => {
+ assert_eq!((kind.as_str(), kwant_id.as_deref()), ("waiting", Some("k1")));
+ assert_eq!(waiting.unwrap().status, "closed");
+ }
+ other => panic!("expected Closed, got {other:?}"),
+ }
+ assert_eq!(db.get_waiting(&stop.id).await.unwrap().unwrap().status, "closed");
+ assert_eq!(db.attention_closed_reason("waiting", &stop.id).await.unwrap().as_deref(), Some(CLOSED_DISMISSED), "the audit row");
+ assert!(matches!(db.dismiss_attention(&stop.id, Some("stopped")).await.unwrap(), Dismissed::AlreadyClosed { .. }));
+
+ // A failed hand-off, found by id alone or with its kind
+ assert!(matches!(db.dismiss_attention("d1", None).await.unwrap(), Dismissed::Closed { ref kind, .. } if kind == "delegation"));
+ assert!(failed_ids(&db).await.is_empty());
+ assert!(matches!(db.dismiss_attention("d1", Some("delegation")).await.unwrap(), Dismissed::AlreadyClosed { .. }));
+
+ // A question's entry, a question, an approval: answered in their own card, so the bot hears
+ assert!(matches!(db.dismiss_attention(&asked.id, None).await.unwrap(), Dismissed::Refused("use_question_answer")));
+ assert_eq!(db.get_waiting(&asked.id).await.unwrap().unwrap().status, "open");
+ assert!(matches!(db.dismiss_attention("a1", Some("approval")).await.unwrap(), Dismissed::Refused("use_approval_decide")));
+ assert!(matches!(db.dismiss_attention("h1", Some("human_step")).await.unwrap(), Dismissed::Refused("use_step_decline")));
+ assert!(matches!(db.dismiss_attention("x", Some("nonsense")).await.unwrap(), Dismissed::BadKind));
+ assert!(matches!(db.dismiss_attention("nope", None).await.unwrap(), Dismissed::NotFound));
+ // A finished hand-off isn't in Needs attention: nothing to dismiss
+ hand_off(&db, "d2", &t, "k1", "completed", 5).await;
+ assert!(matches!(db.dismiss_attention("d2", Some("delegation")).await.unwrap(), Dismissed::NotFound));
+ }
+
+ /// 22i close rules for the sources that close by their own answer: a question leaves Needs you
+ /// when answered or cancelled, an approval once it isn't pending (allowed, denied, withdrawn or
+ /// expired), a browser step when done or declined; and a deleted bot takes its questions along.
+ #[tokio::test]
+ async fn a_question_approval_or_browser_step_closes_by_its_own_answer() {
+ use crate::db::human_steps::HumanStepPlace;
+ use crate::db::questions::QuestionPlace;
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let space = SpaceId::default_space();
+ bot(&db, "k1").await;
+ bot(&db, "k2").await;
+ let place = |k: &str| QuestionPlace { kwant_id: k.into(), channel_id: None, direct_kwant_id: Some(k.into()), thread_id: None, turn_id: None };
+ let q1 = db.create_question(&place("k1"), "Which city?", &[]).await.unwrap();
+ let q2 = db.create_question(&place("k1"), "Which day?", &[]).await.unwrap();
+ let q3 = db.create_question(&place("k2"), "Which colour?", &[]).await.unwrap();
+ let open = |rows: Vec<AwayRow>| rows.into_iter().map(|r| r.id).collect::<Vec<_>>();
+ assert_eq!(open(db.away_open_questions(&space, 50).await.unwrap()).len(), 3);
+ db.close_question(&q1.id, "answered", Some("Paris")).await.unwrap();
+ db.close_question(&q2.id, "cancelled", None).await.unwrap();
+ assert_eq!(open(db.away_open_questions(&space, 50).await.unwrap()), vec![q3.id.clone()]);
+ assert_eq!(db.away_count_open_questions(&space).await.unwrap(), 1);
+ db.delete_kwant_and_history("k2", "k1").await.unwrap();
+ assert!(db.away_open_questions(&space, 50).await.unwrap().is_empty());
+
+ // An approval: listed only while pending (and live in the broker: the caller's ids)
+ for (id, status) in [("a1", "pending"), ("a2", "approved"), ("a3", "denied")] {
+ sqlx::query("INSERT INTO approvals (id, turn_id, kwant_id, tool_name, parameters, status) VALUES (?, 't', 'k1', 'shell', '{}', ?)")
+ .bind(id)
+ .bind(status)
+ .execute(&db.pool)
+ .await
+ .unwrap();
+ }
+ let ids: Vec<String> = ["a1", "a2", "a3"].map(String::from).to_vec();
+ assert_eq!(open(db.away_pending_approvals(&ids).await.unwrap()), vec!["a1"]);
+ sqlx::query("UPDATE approvals SET status = 'expired' WHERE id = 'a1'").execute(&db.pool).await.unwrap();
+ assert!(db.away_pending_approvals(&ids).await.unwrap().is_empty());
+
+ // A browser step: open until done or declined
+ let step_place = HumanStepPlace {
+ kwant_id: "k1".into(),
+ channel_id: None,
+ direct_kwant_id: Some("k1".into()),
+ thread_id: None,
+ turn_id: None,
+ sandbox_target: None,
+ page_key: None,
+ };
+ db.create_human_step_with_card(&step_place, "captcha", "Solve the CAPTCHA", None, None, "auto", |_| None).await.unwrap();
+ let steps = db.list_human_steps(Some("open"), None, Some(&space)).await.unwrap();
+ assert_eq!(steps.len(), 1);
+ assert!(db.close_human_step(&steps[0].id, "declined").await.unwrap());
+ assert!(db.list_human_steps(Some("open"), None, Some(&space)).await.unwrap().is_empty());
+ }
}
diff --git a/src/db/bot_actions.rs b/src/db/bot_actions.rs
index c8cc89d1..1b1b13f4 100644
--- a/src/db/bot_actions.rs
+++ b/src/db/bot_actions.rs
@@ -401,6 +401,9 @@ pub(super) async fn purge_kwant(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, id
"DELETE FROM messages WHERE direct_kwant_id = ?1 OR thread_id IN (SELECT id FROM threads WHERE kwant_id = ?1)",
"DELETE FROM delegations WHERE lead_kwant_id = ?1 OR specialist_kwant_id = ?1 \
OR thread_id IN (SELECT id FROM threads WHERE kwant_id = ?1)",
+ // 22i: what this bot waited on the person for can never be seen or resumed again
+ "UPDATE waiting_on_person SET status = 'closed' WHERE status != 'closed' AND (kwant_id = ?1 OR direct_kwant_id = ?1 \
+ OR thread_id IN (SELECT id FROM threads WHERE kwant_id = ?1))",
"DELETE FROM threads WHERE kwant_id = ?1",
"DELETE FROM questions WHERE kwant_id = ?1 OR direct_kwant_id = ?1",
"DELETE FROM approvals WHERE kwant_id = ?1",
diff --git a/src/db/waiting.rs b/src/db/waiting.rs
index f62da47e..714470f7 100644
--- a/src/db/waiting.rs
+++ b/src/db/waiting.rs
@@ -150,13 +150,13 @@ impl Database {
.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'")
+ /// The question was answered or dismissed. Returns the items it closed (as every close
+ /// below does), so the caller can say so live (`server::waiting::closed`).
+ pub async fn close_waiting_for_question(&self, question_id: &str) -> Result<Vec<WaitingItem>, DbError> {
+ Ok(sqlx::query_as::<_, WaitingItem>("UPDATE waiting_on_person SET status = 'closed' WHERE question_id = ? AND status != 'closed' RETURNING *")
.bind(question_id)
- .execute(&self.pool)
- .await?;
- Ok(res.rows_affected())
+ .fetch_all(&self.pool)
+ .await?)
}
/// The person wrote in a chat: a thread (`thread_id`), a channel's main chat, or the direct
@@ -166,27 +166,21 @@ impl Database {
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(
+ ) -> Result<Vec<WaitingItem>, DbError> {
+ let (sql, id) = match (thread_id, channel_id, direct_kwant_id) {
+ (Some(t), _, _) => ("UPDATE waiting_on_person SET status = 'closed' WHERE status != 'closed' AND thread_id = ? RETURNING *", t),
+ (None, Some(c), _) => (
+ "UPDATE waiting_on_person SET status = 'closed' WHERE status != 'closed' AND channel_id = ? AND thread_id IS NULL RETURNING *",
+ c,
+ ),
+ (None, None, Some(k)) => (
"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),
+ AND thread_id IS NULL AND direct_kwant_id = ? RETURNING *",
+ k,
+ ),
+ (None, None, None) => return Ok(Vec::new()),
};
- Ok(res.rows_affected())
+ Ok(sqlx::query_as::<_, WaitingItem>(sql).bind(id).fetch_all(&self.pool).await?)
}
/// A bot's plain "waiting on a reply" entries in one chat (no question card) end: the ask
@@ -197,21 +191,21 @@ impl Database {
channel_id: Option<&str>,
direct_kwant_id: Option<&str>,
thread_id: Option<&str>,
- ) -> Result<u64, DbError> {
- let res = sqlx::query(&format!(
- "UPDATE waiting_on_person SET status = 'closed' WHERE question_id IS NULL AND kind IS NULL AND status != 'closed' AND {SAME_CHAT}"
+ ) -> Result<Vec<WaitingItem>, DbError> {
+ Ok(sqlx::query_as::<_, WaitingItem>(&format!(
+ "UPDATE waiting_on_person SET status = 'closed' WHERE question_id IS NULL AND kind IS NULL AND status != 'closed' AND {SAME_CHAT} RETURNING *"
))
- .bind(kwant_id)
- .bind(channel_id.unwrap_or(""))
- .bind(direct_kwant_id.unwrap_or(""))
- .bind(thread_id.unwrap_or(""))
- .execute(&self.pool)
- .await?;
- Ok(res.rows_affected())
+ .bind(kwant_id)
+ .bind(channel_id.unwrap_or(""))
+ .bind(direct_kwant_id.unwrap_or(""))
+ .bind(thread_id.unwrap_or(""))
+ .fetch_all(&self.pool)
+ .await?)
}
/// Records that a bot's work stopped in one chat: its earlier stopped item and its "waiting
/// on a reply" item there close (this says more), and one new item opens. Never reminded.
+ /// Returns the new item and the ones it replaced.
#[allow(clippy::too_many_arguments)]
pub async fn add_stopped(
&self,
@@ -222,15 +216,17 @@ impl Database {
message_id: Option<&str>,
line: &str,
retry: Option<&str>,
- ) -> Result<WaitingItem, DbError> {
+ ) -> Result<(WaitingItem, Vec<WaitingItem>), DbError> {
let mut tx = self.begin_write().await?;
- sqlx::query(&format!("UPDATE waiting_on_person SET status = 'closed' WHERE question_id IS NULL AND status != 'closed' AND {SAME_CHAT}"))
- .bind(kwant_id)
- .bind(channel_id.unwrap_or(""))
- .bind(direct_kwant_id.unwrap_or(""))
- .bind(thread_id.unwrap_or(""))
- .execute(&mut *tx)
- .await?;
+ let replaced = sqlx::query_as::<_, WaitingItem>(&format!(
+ "UPDATE waiting_on_person SET status = 'closed' WHERE question_id IS NULL AND status != 'closed' AND {SAME_CHAT} RETURNING *"
+ ))
+ .bind(kwant_id)
+ .bind(channel_id.unwrap_or(""))
+ .bind(direct_kwant_id.unwrap_or(""))
+ .bind(thread_id.unwrap_or(""))
+ .fetch_all(&mut *tx)
+ .await?;
let row = sqlx::query_as::<_, WaitingItem>(
"INSERT INTO waiting_on_person (id, kwant_id, channel_id, direct_kwant_id, thread_id, message_id, question, status, created_at, kind, retry) \
VALUES (?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?) RETURNING *",
@@ -248,7 +244,7 @@ impl Database {
.fetch_one(&mut *tx)
.await?;
tx.commit().await?;
- Ok(row)
+ Ok((row, replaced))
}
/// The bot's work in that chat went on (a later reply finished): its stopped items there close.
@@ -258,39 +254,65 @@ impl Database {
channel_id: Option<&str>,
direct_kwant_id: Option<&str>,
thread_id: Option<&str>,
- ) -> Result<u64, DbError> {
- let res = sqlx::query(&format!("UPDATE waiting_on_person SET status = 'closed' WHERE kind = 'stopped' AND status != 'closed' AND {SAME_CHAT}"))
- .bind(kwant_id)
- .bind(channel_id.unwrap_or(""))
- .bind(direct_kwant_id.unwrap_or(""))
- .bind(thread_id.unwrap_or(""))
- .execute(&self.pool)
- .await?;
- Ok(res.rows_affected())
+ ) -> Result<Vec<WaitingItem>, DbError> {
+ Ok(sqlx::query_as::<_, WaitingItem>(&format!(
+ "UPDATE waiting_on_person SET status = 'closed' WHERE kind = 'stopped' AND status != 'closed' AND {SAME_CHAT} RETURNING *"
+ ))
+ .bind(kwant_id)
+ .bind(channel_id.unwrap_or(""))
+ .bind(direct_kwant_id.unwrap_or(""))
+ .bind(thread_id.unwrap_or(""))
+ .fetch_all(&self.pool)
+ .await?)
}
- /// Closes one item if it is still open; `false` when it was already closed (a second Retry).
- pub async fn claim_waiting(&self, id: &str) -> Result<bool, DbError> {
- let res = sqlx::query("UPDATE waiting_on_person SET status = 'closed' WHERE id = ? AND status != 'closed'").bind(id).execute(&self.pool).await?;
- Ok(res.rows_affected() > 0)
+ /// Closes one item if it is still open; `None` when it was already closed or never existed
+ /// (a second Retry or Dismiss).
+ pub async fn claim_waiting(&self, id: &str) -> Result<Option<WaitingItem>, DbError> {
+ Ok(sqlx::query_as::<_, WaitingItem>("UPDATE waiting_on_person SET status = 'closed' WHERE id = ? AND status != 'closed' RETURNING *")
+ .bind(id)
+ .fetch_optional(&self.pool)
+ .await?)
}
/// Stopped items still open whose notice is `message_id` (a chain notice's Continue).
- pub async fn close_waiting_for_message(&self, message_id: &str) -> Result<u64, DbError> {
- let res = sqlx::query("UPDATE waiting_on_person SET status = 'closed' WHERE message_id = ? AND kind = 'stopped' AND status != 'closed'")
- .bind(message_id)
- .execute(&self.pool)
- .await?;
- Ok(res.rows_affected())
+ pub async fn close_waiting_for_message(&self, message_id: &str) -> Result<Vec<WaitingItem>, DbError> {
+ Ok(sqlx::query_as::<_, WaitingItem>(
+ "UPDATE waiting_on_person SET status = 'closed' WHERE message_id = ? AND kind = 'stopped' AND status != 'closed' RETURNING *",
+ )
+ .bind(message_id)
+ .fetch_all(&self.pool)
+ .await?)
}
/// The stopped item whose Retry asks again for approval card `approval_id`.
- pub async fn close_stopped_for_approval(&self, approval_id: &str) -> Result<u64, DbError> {
- let res = sqlx::query("UPDATE waiting_on_person SET status = 'closed' WHERE kind = 'stopped' AND status != 'closed' AND json_extract(retry, '$.approval_id') = ?")
- .bind(approval_id)
- .execute(&self.pool)
- .await?;
- Ok(res.rows_affected())
+ pub async fn close_stopped_for_approval(&self, approval_id: &str) -> Result<Vec<WaitingItem>, DbError> {
+ Ok(sqlx::query_as::<_, WaitingItem>(
+ "UPDATE waiting_on_person SET status = 'closed' WHERE kind = 'stopped' AND status != 'closed' \
+ AND json_extract(retry, '$.approval_id') = ? RETURNING *",
+ )
+ .bind(approval_id)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// 22i: open items whose place is gone, so nobody can see or resume them: the bot was
+ /// deleted, or the channel or thread they were asked in no longer exists. The caller closes
+ /// them ([`Self::claim_waiting`]); `space` limits it like [`Self::list_waiting`].
+ pub async fn waiting_places_gone(&self, space: Option<&super::spaces::SpaceId>) -> Result<Vec<WaitingItem>, DbError> {
+ Ok(sqlx::query_as::<_, WaitingItem>(
+ "SELECT * FROM waiting_on_person w WHERE w.status != 'closed'
+ AND (?1 IS NULL OR COALESCE((SELECT k.space_id FROM kwants k WHERE k.id = w.kwant_id), 'spc_default') = ?1)
+ AND (NOT EXISTS (SELECT 1 FROM kwants k WHERE k.id = w.kwant_id)
+ OR (w.channel_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM channels c WHERE c.id = w.channel_id))
+ OR (w.thread_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM threads t WHERE t.id = w.thread_id))
+ OR (w.channel_id IS NULL AND w.thread_id IS NULL AND w.direct_kwant_id IS NOT NULL
+ AND NOT EXISTS (SELECT 1 FROM kwants k WHERE k.id = w.direct_kwant_id)))
+ ORDER BY w.created_at",
+ )
+ .bind(space.map(|s| s.as_str()))
+ .fetch_all(&self.pool)
+ .await?)
}
/// The entries whose reminder is due by `now`, each claimed (`open` → `reminded`) so it goes
@@ -366,7 +388,7 @@ mod tests {
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_eq!(db.close_waiting_in_chat(None, Some("k"), None).await.unwrap().len(), 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());
@@ -380,9 +402,9 @@ mod tests {
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);
+ assert_eq!(db.close_waiting_in_chat(Some("c1"), None, None).await.unwrap().len(), 1);
+ assert_eq!(db.close_waiting_in_chat(None, None, Some("t1")).await.unwrap().len(), 1);
+ assert_eq!(db.close_waiting_for_question("q9").await.unwrap().len(), 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"));
@@ -396,23 +418,23 @@ mod tests {
let db = Database::init(tmp.path()).await.unwrap();
// A "waiting on your reply" item in the chat, then the work stops there
db.add_waiting(&item("k", None, Some("k"), None, None)).await.unwrap();
- let a = db.add_stopped("k", None, Some("k"), None, Some("m1"), "Stopped. Retry in the chat sends your message again.", None).await.unwrap();
+ let a = db.add_stopped("k", None, Some("k"), None, Some("m1"), "Stopped. Retry in the chat sends your message again.", None).await.unwrap().0;
assert_eq!(a.kind.as_deref(), Some(STOPPED));
let open = db.list_waiting(None).await.unwrap();
assert_eq!(open.len(), 1, "the stop says more than the plain ask: {open:?}");
// A second stop in the same chat replaces the first: one ask per chat
- let b = db.add_stopped("k", None, Some("k"), None, Some("m2"), "Again", None).await.unwrap();
+ let b = db.add_stopped("k", None, Some("k"), None, Some("m2"), "Again", None).await.unwrap().0;
let open = db.list_waiting(None).await.unwrap();
assert_eq!(open.iter().map(|w| w.id.as_str()).collect::<Vec<_>>(), vec![b.id.as_str()]);
// Never reminded
assert!(db.take_due_waiting(Utc::now() + Duration::days(30)).await.unwrap().is_empty());
// A stop elsewhere is untouched; a later reply of the bot there closes only that chat's
db.add_stopped("k", Some("c1"), None, None, None, "In the channel", None).await.unwrap();
- assert_eq!(db.close_stopped("k", None, Some("k"), None).await.unwrap(), 1);
+ assert_eq!(db.close_stopped("k", None, Some("k"), None).await.unwrap().len(), 1);
assert_eq!(db.list_waiting(None).await.unwrap().len(), 1);
// Plain closes don't take a stopped item with them, a write does
db.add_waiting(&item("k", Some("c1"), None, None, None)).await.unwrap();
- assert_eq!(db.close_waiting_in_chat(Some("c1"), None, None).await.unwrap(), 2);
+ assert_eq!(db.close_waiting_in_chat(Some("c1"), None, None).await.unwrap().len(), 2);
assert!(db.list_waiting(None).await.unwrap().is_empty());
}
@@ -420,16 +442,61 @@ mod tests {
async fn a_stopped_item_closes_by_its_notice_or_its_approval_once() {
let tmp = tempfile::tempdir().unwrap();
let db = Database::init(tmp.path()).await.unwrap();
- let cont = db.add_stopped("k", Some("c1"), None, None, Some("notice1"), "Paused", Some(r#"{"type":"continue"}"#)).await.unwrap();
+ let cont = db.add_stopped("k", Some("c1"), None, None, Some("notice1"), "Paused", Some(r#"{"type":"continue"}"#)).await.unwrap().0;
assert_eq!(cont.retry.as_deref(), Some(r#"{"type":"continue"}"#));
db.add_stopped("k", Some("c2"), None, None, Some("notice2"), "Expired", Some(r#"{"type":"approval","approval_id":"ap1"}"#)).await.unwrap();
- assert_eq!(db.close_waiting_for_message("notice1").await.unwrap(), 1);
- assert_eq!(db.close_waiting_for_message("notice1").await.unwrap(), 0);
- assert_eq!(db.close_stopped_for_approval("ap2").await.unwrap(), 0);
- assert_eq!(db.close_stopped_for_approval("ap1").await.unwrap(), 1);
+ assert_eq!(db.close_waiting_for_message("notice1").await.unwrap().len(), 1);
+ assert_eq!(db.close_waiting_for_message("notice1").await.unwrap().len(), 0);
+ assert_eq!(db.close_stopped_for_approval("ap2").await.unwrap().len(), 0);
+ assert_eq!(db.close_stopped_for_approval("ap1").await.unwrap().len(), 1);
assert!(db.list_waiting(None).await.unwrap().is_empty());
- let c = db.add_stopped("k", Some("c3"), None, None, None, "x", None).await.unwrap();
- assert!(db.claim_waiting(&c.id).await.unwrap());
- assert!(!db.claim_waiting(&c.id).await.unwrap(), "a second Retry gets nothing");
+ let c = db.add_stopped("k", Some("c3"), None, None, None, "x", None).await.unwrap().0;
+ assert!(db.claim_waiting(&c.id).await.unwrap().is_some());
+ assert!(db.claim_waiting(&c.id).await.unwrap().is_none(), "a second Retry gets nothing");
+ }
+
+ async fn bot(db: &Database, id: &str) {
+ sqlx::query("INSERT INTO kwants (id, name, title, persona_prompt, avatar_sprite, space_id) VALUES (?, ?, 't', 'p', 'a', 'spc_default')")
+ .bind(id)
+ .bind(format!("Bot {id}"))
+ .execute(&db.pool)
+ .await
+ .unwrap();
+ }
+
+ /// 22i: an item asked in a chat that no longer exists (bot, channel or thread deleted) is
+ /// found so it can close, and deleting a bot closes its items itself.
+ #[tokio::test]
+ async fn items_whose_place_is_gone_are_found_and_a_deleted_bot_closes_its_own() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ bot(&db, "k1").await;
+ bot(&db, "k2").await;
+ sqlx::query("INSERT INTO channels (id, name, description, lead_kwant_id, member_kwants, routing_mode, space_id) VALUES ('c1', 'ops', '', 'k1', '[\"k1\"]', 'auto', 'spc_default')")
+ .execute(&db.pool)
+ .await
+ .unwrap();
+ let t1 = db.create_thread("k1", "Fix-it: repo #1", "chat", None, "kwant").await.unwrap();
+ // Places that exist
+ db.add_stopped("k1", None, Some("k1"), None, Some("m1"), "direct", None).await.unwrap();
+ db.add_stopped("k1", Some("c1"), None, None, Some("m2"), "channel", None).await.unwrap();
+ db.add_stopped("k1", None, None, Some(&t1.id), Some("m3"), "thread", None).await.unwrap();
+ assert!(db.waiting_places_gone(None).await.unwrap().is_empty());
+ // Places that don't: a channel and a thread that were deleted, a bot that never was
+ db.add_stopped("k1", Some("c-gone"), None, None, Some("m4"), "gone channel", None).await.unwrap();
+ db.add_stopped("k1", None, None, Some("t-gone"), Some("m5"), "gone thread", None).await.unwrap();
+ db.add_stopped("k-gone", None, Some("k-gone"), None, Some("m6"), "gone bot", None).await.unwrap();
+ let gone: Vec<String> = db.waiting_places_gone(None).await.unwrap().into_iter().map(|w| w.question).collect();
+ assert_eq!(gone, vec!["gone channel", "gone thread", "gone bot"]);
+ for w in db.waiting_places_gone(None).await.unwrap() {
+ assert!(db.claim_waiting(&w.id).await.unwrap().is_some());
+ }
+ assert!(db.waiting_places_gone(None).await.unwrap().is_empty());
+ assert_eq!(db.list_waiting(None).await.unwrap().len(), 3);
+ // Deleting k1 closes its three (direct chat, channel ask, its thread) in the same transaction
+ db.add_stopped("k2", None, Some("k2"), None, Some("m7"), "k2's own", None).await.unwrap();
+ assert!(db.delete_kwant_and_history("k1", "k2").await.unwrap());
+ let left: Vec<String> = db.list_waiting(None).await.unwrap().into_iter().map(|w| w.question).collect();
+ assert_eq!(left, vec!["k2's own"]);
}
}
diff --git a/src/drivers/events.rs b/src/drivers/events.rs
index c4e3f561..be4d52d6 100644
--- a/src/drivers/events.rs
+++ b/src/drivers/events.rs
@@ -174,6 +174,15 @@ pub enum RuntimeEvent {
/// `crate::db::human_steps`.
#[serde(rename = "human_step_updated", alias = "HumanStepUpdated")]
HumanStepUpdated { step: Value },
+ /// 22i: an item in Needs you opened or closed, so clients refresh it live (the Needs-you
+ /// list and the badge re-read `GET /api/away`). `item` is `{id, kind, status, reason,
+ /// kwant_id, channel_id, direct_kwant_id, thread_id}`: `kind` "stopped", "reply" or
+ /// "question" (a waiting item), "delegation" or "routine_run" (a failed or stuck one);
+ /// `status` "open" or "closed"; `reason` why it closed ("later_reply", "person_wrote",
+ /// "answered", "replaced", "resumed", "place_gone", "dismissed"), `null` when it opened.
+ /// Questions, browser steps and approvals keep their own events too.
+ #[serde(rename = "waiting_updated", alias = "WaitingUpdated")]
+ WaitingUpdated { item: Value },
/// An MCP server an agent suggested was suggested, installed or dismissed; `suggestion` is the
/// whole record. See `crate::db::mcp_suggestions`.
#[serde(rename = "mcp_suggestion_updated", alias = "McpSuggestionUpdated")]
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 07b8b538..89bd6a4a 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -948,6 +948,8 @@ mod tests {
assert!(person_only(&post, "/api/glance/ask"));
assert!(person_only(&post, "/api/questions/q1/answer"));
assert!(person_only(&post, "/api/questions/q1/answer/"));
+ // 22i: Dismiss in Needs attention is the person's alone
+ assert!(person_only(&post, "/api/waiting/w1/dismiss"));
assert!(!person_only(&get, "/api/questions/q1"));
assert!(!person_only(&post, "/api/questions/q1/cancel"));
assert!(person_only(&post, "/api/spaces/s1/docs"));
diff --git a/src/server/away.rs b/src/server/away.rs
index bba511e1..3ec026ab 100644
--- a/src/server/away.rs
+++ b/src/server/away.rs
@@ -338,6 +338,7 @@ async fn space_of(state: &AppState, cache: &mut HashMap<String, SpaceId>, kwant_
/// it, `message_id` the chat notice that carries Retry or Continue, `retry` set when Retry is
/// `POST /api/waiting/:id/retry` rather than the chat's own.
pub(super) async fn stopped_items(state: &AppState, space: &SpaceId) -> Vec<Value> {
+ close_gone_places(state, space).await;
let rows = state.db.list_waiting(Some(space)).await.unwrap_or_default();
let mut out = Vec::new();
for w in rows.into_iter().filter(|w| w.kind.as_deref() == Some(crate::db::waiting::STOPPED)) {
@@ -386,6 +387,98 @@ pub(super) async fn stopped_items(state: &AppState, space: &SpaceId) -> Vec<Valu
out
}
+/// 22i: an item whose bot, channel or thread is gone has nowhere to open, and the client fell back
+/// to the bot's direct chat, where nothing says what is needed. Close those, live, before listing.
+async fn close_gone_places(state: &AppState, space: &SpaceId) {
+ for w in state.db.waiting_places_gone(Some(space)).await.unwrap_or_default() {
+ if let Ok(Some(closed)) = state.db.claim_waiting(&w.id).await {
+ tracing::info!(waiting_id = %closed.id, kwant_id = %closed.kwant_id, "closed a Needs-you item whose chat is gone");
+ super::waiting::closed(state, std::slice::from_ref(&closed), super::waiting::REASON_PLACE_GONE);
+ }
+ }
+}
+
+/// 22i: what the person does about an item, so its row can say it in one word:
+/// `retry` (rerun what stopped or failed), `continue` (a chain paused at its cap), `ask_again`
+/// (an approval that expired), `answer` (a bot's question), `decide` (an approval, a watch item or
+/// work that is stuck), `browser` (a sign-in, code or CAPTCHA step). `None` for what only needs a
+/// look (finished work).
+pub(super) fn action_of(v: &Value) -> Option<&'static str> {
+ let kind = v["kind"].as_str().unwrap_or("");
+ let status = v["status"].as_str().unwrap_or("");
+ Some(match kind {
+ "approval" | "watch" => "decide",
+ "question" => "answer",
+ "stopped" if v.get("human_step_id").is_some_and(|h| !h.is_null()) => "browser",
+ "stopped" => match v["retry"]["type"].as_str() {
+ Some("approval") => "ask_again",
+ Some("continue") => "continue",
+ _ => "retry",
+ },
+ // A failed hand-off reruns only through its board task (`task_id`); without one there is
+ // no Retry to offer: the person asks again in its thread (a later reply closes the row) or
+ // dismisses it
+ "delegation" => match status {
+ "stuck" => "decide",
+ "failed" | "interrupted" if v["task_id"].is_string() => "retry",
+ _ => return None,
+ },
+ "routine_run" => match status {
+ "stuck" => "decide",
+ "error" => "retry",
+ _ => return None,
+ },
+ _ => return None,
+ })
+}
+
+/// Whether the person may clear the item with `POST /api/waiting/:id/dismiss`: a stop, a failed or
+/// stuck hand-off or routine run. A question, approval, watch item or browser step has its own
+/// answer or decline, which tells the bot; dismissing it would leave the bot waiting.
+pub(super) fn dismissable(v: &Value) -> bool {
+ let kind = v["kind"].as_str().unwrap_or("");
+ let status = v["status"].as_str().unwrap_or("");
+ match kind {
+ "stopped" => v.get("human_step_id").is_none_or(|h| h.is_null()),
+ "delegation" | "routine_run" => matches!(status, "stuck" | "failed" | "interrupted" | "error"),
+ _ => false,
+ }
+}
+
+/// 22i: a failed or interrupted hand-off gets `task_id` when the board has a failed task for it,
+/// which `POST /api/tasks/:id/retry` reruns. Without it the row's `action` is `null`.
+async fn add_hand_off_task(db: &crate::db::Database, v: &mut Value) {
+ if v["kind"] != "delegation" || !matches!(v["status"].as_str(), Some("failed" | "interrupted")) {
+ return;
+ }
+ let Some(id) = v["id"].as_str() else { return };
+ if let Ok(Some(task_id)) = db.retryable_hand_off_task(id).await {
+ v["task_id"] = json!(task_id);
+ }
+}
+
+/// Adds `action`, `dismissable`, `task_id` on a failed hand-off with a board task and, when the item's thread belongs to another bot,
+/// `link.thread_kwant_id`: the client looks a thread up under its owner, and finding it under the
+/// item's bot failed, falling back to the direct chat (one way to Quant's case).
+pub(super) async fn annotate(state: &AppState, items: &mut [Value]) {
+ let mut owners: std::collections::HashMap<String, Option<String>> = std::collections::HashMap::new();
+ for v in items.iter_mut() {
+ add_hand_off_task(&state.db, v).await;
+ v["action"] = json!(action_of(v));
+ v["dismissable"] = json!(dismissable(v));
+ let Some(thread_id) = v["link"]["thread_id"].as_str().map(str::to_string) else { continue };
+ if !owners.contains_key(&thread_id) {
+ let owner = state.db.get_thread(&thread_id).await.ok().flatten().map(|t| t.kwant_id);
+ owners.insert(thread_id.clone(), owner);
+ }
+ if let Some(Some(owner)) = owners.get(&thread_id) {
+ if v["kwant_id"].as_str() != Some(owner.as_str()) {
+ v["link"]["thread_kwant_id"] = json!(owner);
+ }
+ }
+ }
+}
+
/// What waits on the person in a space, as `GET /api/away` lists it under `waiting`: open
/// questions, approvals, what a mission watcher left (P1) and work that stopped and waits to be
/// resumed (0.9.5), newest first and cut to [`MAX_ITEMS`], with how many there are in all.
@@ -411,6 +504,7 @@ pub(super) async fn waiting_with(state: &AppState, space: &SpaceId, approvals: V
waiting.extend(stopped);
waiting.sort_by(|a, b| b["timestamp"].as_str().unwrap_or("").cmp(a["timestamp"].as_str().unwrap_or("")));
waiting.truncate(MAX_ITEMS as usize);
+ annotate(state, &mut waiting).await;
Ok((waiting, count))
}
@@ -448,14 +542,18 @@ pub async fn get(State(state): State<AppState>, Scope(space): Scope, Query(q): Q
let Ok((waiting, finished, failed, waiting_count, unseen_finished, unseen_failed)) = result else {
return internal();
};
+ let mut finished: Vec<Value> = finished.into_iter().map(item).collect();
+ let mut failed: Vec<Value> = failed.into_iter().map(item).collect();
+ annotate(&state, &mut finished).await;
+ annotate(&state, &mut failed).await;
Json(json!({
"since": rfc3339(since),
"last_seen": seen.map(rfc3339),
"now": rfc3339(now),
"stuck_after_minutes": STUCK_AFTER_MINUTES,
"waiting": waiting,
- "finished": finished.into_iter().map(item).collect::<Vec<_>>(),
- "failed": failed.into_iter().map(item).collect::<Vec<_>>(),
+ "finished": finished,
+ "failed": failed,
"unseen": {
"waiting": waiting_count,
"finished": unseen_finished,
@@ -479,6 +577,76 @@ pub async fn seen(State(state): State<AppState>, Scope(space): Scope) -> Respons
mod tests {
use super::*;
+ /// 22i: every row says what the person does, and only stops and failed or stuck work can be
+ /// dismissed (the rest has an answer that tells the bot).
+ #[test]
+ fn items_say_what_is_needed_and_whether_they_can_be_dismissed() {
+ let cases = [
+ (json!({"kind": "approval", "status": "pending"}), Some("decide"), false),
+ (json!({"kind": "watch", "status": "open"}), Some("decide"), false),
+ (json!({"kind": "question", "status": "open"}), Some("answer"), false),
+ (json!({"kind": "stopped", "status": "open", "human_step_id": "h1", "retry": null}), Some("browser"), false),
+ (json!({"kind": "stopped", "status": "open", "retry": null}), Some("retry"), true),
+ (json!({"kind": "stopped", "status": "open", "retry": {"type": "continue"}}), Some("continue"), true),
+ (json!({"kind": "stopped", "status": "open", "retry": {"type": "approval", "approval_id": "a1"}}), Some("ask_again"), true),
+ (json!({"kind": "delegation", "status": "failed", "task_id": "t1"}), Some("retry"), true),
+ (json!({"kind": "delegation", "status": "interrupted", "task_id": "t1"}), Some("retry"), true),
+ (json!({"kind": "delegation", "status": "failed"}), None, true),
+ (json!({"kind": "delegation", "status": "interrupted"}), None, true),
+ (json!({"kind": "delegation", "status": "stuck"}), Some("decide"), true),
+ (json!({"kind": "routine_run", "status": "error"}), Some("retry"), true),
+ (json!({"kind": "delegation", "status": "completed"}), None, false),
+ (json!({"kind": "routine_run", "status": "success"}), None, false),
+ ];
+ for (v, action, can_dismiss) in cases {
+ assert_eq!(action_of(&v), action, "{v}");
+ assert_eq!(dismissable(&v), can_dismiss, "{v}");
+ }
+ }
+
+ /// 22i: a failed hand-off offers Retry only with a failed board task to rerun, and carries its
+ /// `task_id`; with the board off (no task) or a task that isn't failed it offers no Retry, so
+ /// the row never has a button with nowhere to go. It stays dismissable either way.
+ #[tokio::test]
+ async fn a_failed_hand_off_offers_retry_only_with_a_board_task_to_rerun() {
+ use crate::db::missions::NewTask;
+ let tmp = tempfile::tempdir().unwrap();
+ let db = crate::db::Database::init(tmp.path()).await.unwrap();
+ let row = |id: &str| json!({"kind": "delegation", "id": id, "status": "failed", "link": {"thread_id": "t"}});
+ // No board task (the board is off by default)
+ let mut v = row("d1");
+ add_hand_off_task(&db, &mut v).await;
+ assert!(v.get("task_id").is_none(), "{v}");
+ assert_eq!(action_of(&v), None);
+ assert!(dismissable(&v));
+ // A failed board task for it: Retry reruns that task
+ let task = |state: &str, source: &str| NewTask {
+ title: "Hand-off".into(),
+ state: state.into(),
+ priority: 1,
+ max_attempts: 3,
+ source_kind: "delegation".into(),
+ source_id: Some(source.into()),
+ created_by: "kwant".into(),
+ ..Default::default()
+ };
+ let t = db.create_task(&SpaceId::default_space(), &task("failed", "d1")).await.unwrap();
+ let mut v = row("d1");
+ add_hand_off_task(&db, &mut v).await;
+ assert_eq!(v["task_id"], json!(t.id));
+ assert_eq!(action_of(&v), Some("retry"));
+ // A task that isn't failed can't be retried there, so no Retry either
+ db.create_task(&SpaceId::default_space(), &task("blocked", "d2")).await.unwrap();
+ let mut v = row("d2");
+ add_hand_off_task(&db, &mut v).await;
+ assert!(v.get("task_id").is_none(), "{v}");
+ assert_eq!(action_of(&v), None);
+ // Other rows are left alone
+ let mut v = json!({"kind": "routine_run", "id": "d1", "status": "error"});
+ add_hand_off_task(&db, &mut v).await;
+ assert!(v.get("task_id").is_none());
+ }
+
#[test]
fn summaries_are_one_short_masked_line() {
assert_eq!(summarize("\n\n## Done\nmore"), "Done");
diff --git a/src/server/budget.rs b/src/server/budget.rs
index 3043258f..a800b169 100644
--- a/src/server/budget.rs
+++ b/src/server/budget.rs
@@ -155,7 +155,8 @@ async fn resume(state: &AppState, notice_id: &str) -> Result<(), (StatusCode, &'
return Err((StatusCode::CONFLICT, "this chain was already continued"));
}
// Its Needs-you item is answered either way
- let _ = state.db.close_waiting_for_message(notice_id).await;
+ let rows = state.db.close_waiting_for_message(notice_id).await.unwrap_or_default();
+ super::waiting::closed(state, &rows, super::waiting::REASON_RESUMED);
let channel_id = notice.channel_id.clone().ok_or((StatusCode::BAD_REQUEST, "not a channel message"))?;
if meta["kind"] == CAPPED_KIND {
return resume_capped(state, notice_id, meta, channel_id).await;
diff --git a/src/server/inbox.rs b/src/server/inbox.rs
index 1245aeb1..d722e009 100644
--- a/src/server/inbox.rs
+++ b/src/server/inbox.rs
@@ -855,6 +855,9 @@ pub async fn get(State(state): State<AppState>, Scope(space): Scope, Query(q): Q
items.extend(waiting.into_iter().map(|r| away_item(r, Group::WaitingOnYou, seen)));
items.extend(watch.into_iter().map(|v| watch_item(v, seen)));
items.extend(stopped.into_iter().map(|v| watch_item(v, seen)));
+ // 22i: the same `action`, `dismissable`, `task_id` and `link.thread_kwant_id` as /api/away
+ // puts on these items, so an away item comes through here unchanged
+ away::annotate(&state, &mut items).await;
items.extend(connections.into_iter().map(|(at, v)| connection_item(at, &v, seen)));
// An approval's title is its own question when the call names what it is about (Iris's #539).
// `question` is sent only then, so the Inbox can tell it from today's tool title, which stays
@@ -865,12 +868,15 @@ pub async fn get(State(state): State<AppState>, Scope(space): Scope, Query(q): Q
v["question"] = json!(q);
}
}
+ let mut done_items = Vec::with_capacity(done.len());
for (row, group, facts) in done {
let mut v = away_item(row, group, seen);
let unread = v["unread"].as_bool().unwrap_or(true);
inbox_done::apply(&mut v, &facts, unread);
- items.push(v);
+ done_items.push(v);
}
+ away::annotate(&state, &mut done_items).await;
+ items.extend(done_items);
for (r, facts) in reviews.iter().zip(&review_facts) {
if let Some((mut v, _)) = review_item(r, seen) {
inbox_done::apply(&mut v, facts, seen.is_none_or(|s| r.in_review_since > s));
diff --git a/src/server/keep_going.rs b/src/server/keep_going.rs
index a8283304..dbe00582 100644
--- a/src/server/keep_going.rs
+++ b/src/server/keep_going.rs
@@ -515,7 +515,8 @@ async fn ask_card(scope: &TurnScope, lead: &Kwant, question: &str, choices: &[St
if let Some(m) = card_message(state, &q).await {
super::asks::set_meta_key(state, &m, key, json!(true)).await;
}
- let _ = state.db.close_plain_waiting(&lead.id, scope.channel_id.as_deref(), direct.as_deref(), scope.thread_id.as_deref()).await;
+ let rows = state.db.close_plain_waiting(&lead.id, scope.channel_id.as_deref(), direct.as_deref(), scope.thread_id.as_deref()).await.unwrap_or_default();
+ super::waiting::closed(state, &rows, super::waiting::REASON_REPLACED);
let hours = super::waiting::follow_up_hours(state).await;
let item = NewWaitingItem {
kwant_id: lead.id.clone(),
@@ -527,7 +528,8 @@ async fn ask_card(scope: &TurnScope, lead: &Kwant, question: &str, choices: &[St
question: q.question.clone(),
due_at: (hours > 0).then(|| Utc::now() + Duration::hours(hours)),
};
- if matches!(state.db.add_waiting(&item).await, Ok(Some(_))) {
+ if let Ok(Some(w)) = state.db.add_waiting(&item).await {
+ super::waiting::opened(state, &w);
state.scheduler_wake.notify_one();
}
Some(q)
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index c2a8f77e..97767f9a 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -747,7 +747,8 @@ pub fn expired_text(kwant_name: &str, tool_name: &str, hours: i64) -> String {
/// expired (never, or Retry already ran).
pub async fn retry_expired(state: &AppState, ticket_id: &str) -> Option<Value> {
let (approval, chat) = state.db.claim_expired_approval(ticket_id).await.ok().flatten()?;
- let _ = state.db.close_stopped_for_approval(ticket_id).await;
+ let rows = state.db.close_stopped_for_approval(ticket_id).await.unwrap_or_default();
+ super::waiting::closed(state, &rows, super::waiting::REASON_RESUMED);
let not_resumed = |why: &str| Some(json!({"ticket_id": ticket_id, "status": "retried", "resumed": false, "reason": why}));
let Ok(Some(kwant)) = state.db.get_kwant(&approval.kwant_id).await else {
return not_resumed("the bot no longer exists");
diff --git a/src/server/mod.rs b/src/server/mod.rs
index b0c0a5bf..ba132fc4 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -520,6 +520,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/attachments/:id", get(attachments::get))
.route("/api/attachments/:id/content", get(attachments::content))
.route("/api/waiting", get(waiting::list))
+ .route("/api/waiting/:id/dismiss", post(waiting::dismiss))
.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 bb724a43..22099bf6 100644
--- a/src/server/questions.rs
+++ b/src/server/questions.rs
@@ -155,7 +155,8 @@ async fn close_via(state: &AppState, id: &str, status: &str, answer: Option<&str
let _ = state.db.set_answered_via("questions", id, via).await;
}
// 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 rows = state.db.close_waiting_for_question(id).await.unwrap_or_default();
+ super::waiting::closed(state, &rows, super::waiting::REASON_ANSWERED);
let q = state.db.get_question(id).await.ok().flatten()?;
changed(state, &q).await;
if status == "answered" {
diff --git a/src/server/sse.rs b/src/server/sse.rs
index 951d4a8c..ff2d609d 100644
--- a/src/server/sse.rs
+++ b/src/server/sse.rs
@@ -88,7 +88,7 @@ pub fn owners(event: &RuntimeEvent) -> Vec<Owner> {
out
}
E::TrialEnded { bot, .. } => vec![Owner::Context(bot.clone())],
- E::QuestionUpdated { question: v } | E::HumanStepUpdated { step: v } => fields(
+ E::QuestionUpdated { question: v } | E::HumanStepUpdated { step: v } | E::WaitingUpdated { item: v } => fields(
v,
&["kwant_id", "channel_id", "direct_kwant_id", "thread_id"],
Owner::Context,
@@ -261,6 +261,7 @@ mod tests {
E::QuestionUpdated { question: json!({"id": "q", "kwant_id": "k"}) },
E::Activity { step: json!({"id": "s1"}) },
E::HumanStepUpdated { step: json!({"id": "h", "kwant_id": "k"}) },
+ E::WaitingUpdated { item: json!({"id": "w", "kind": "stopped", "status": "closed", "kwant_id": "k"}) },
E::McpSuggestionUpdated { suggestion: json!({"id": "g", "space_id": "spc_default", "kwant_id": "k"}) },
E::BotActionUpdated { action: json!({"id": "b", "space_id": "spc_default", "kwant_id": "k"}) },
E::HireUpdated { hire: json!({"id": "h", "space_id": "spc_default", "kwant_id": "k"}) },
@@ -381,6 +382,7 @@ mod tests {
| E::QuestionUpdated { .. }
| E::Activity { .. }
| E::HumanStepUpdated { .. }
+ | E::WaitingUpdated { .. }
| E::McpSuggestionUpdated { .. }
| E::BotActionUpdated { .. }
| E::HireUpdated { .. }
diff --git a/src/server/stopped.rs b/src/server/stopped.rs
index c2536155..35cc9b0f 100644
--- a/src/server/stopped.rs
+++ b/src/server/stopped.rs
@@ -113,10 +113,24 @@ pub fn title(text: &str, max: usize) -> String {
format!("{}…", cut.trim_end())
}
-/// Records the ask (clients refresh Needs you on the notice's message, posted with it).
+/// 22i: whether a stop may become a Needs-you item. Only with its notice saved in the chat: the
+/// row opens that chat, and the notice is what says what is needed and carries Retry or
+/// Continue. An item without one (Quant's case: "The model sent nothing…" pinned, the chat it
+/// opened showing nothing to do) is worse than none. An expired approval is the exception: its
+/// Retry runs from Needs you itself (`POST /api/approvals/:id/retry`).
+pub(super) fn may_ask(message_id: Option<&str>, resume: &Resume) -> bool {
+ message_id.is_some_and(|m| !m.is_empty()) || matches!(resume, Resume::Approval { .. })
+}
+
+/// Records the ask and says so live (`waiting_updated`), closing the chat's earlier stop or plain
+/// ask it replaces. `None`, with no item, when its notice wasn't saved ([`may_ask`]).
pub async fn ask(state: &AppState, place: &Place, message_id: Option<&str>, line: &str, resume: Resume) -> Option<WaitingItem> {
+ if !may_ask(message_id, &resume) {
+ tracing::warn!(kwant_id = %place.kwant_id, "a bot's work stopped but its notice wasn't saved: no Needs-you item, it would open a chat with nothing to do");
+ return None;
+ }
let line: String = line.chars().take(MAX_LINE_CHARS + 120).collect();
- let item = state
+ let (item, replaced) = state
.db
.add_stopped(
&place.kwant_id,
@@ -130,15 +144,19 @@ pub async fn ask(state: &AppState, place: &Place, message_id: Option<&str>, line
.await
.ok()?;
tracing::info!(waiting_id = %item.id, kwant_id = %place.kwant_id, "a bot's work stopped: asked the person to resume it");
+ super::waiting::closed(state, &replaced, super::waiting::REASON_REPLACED);
+ super::waiting::opened(state, &item);
Some(item)
}
-/// A reply of the bot in that chat finished: whatever stopped there before has moved on.
+/// A reply of the bot in that chat finished: whatever stopped there before has moved on, and so
+/// has a failed hand-off or routine run of this bot there (22i). Each close is said live.
pub async fn recovered(state: &AppState, place: &Place) {
- let _ = state
- .db
- .close_stopped(&place.kwant_id, place.channel_id.as_deref(), place.direct_kwant_id.as_deref(), place.thread_id.as_deref())
- .await;
+ let (channel, direct, thread) = (place.channel_id.as_deref(), place.direct_kwant_id.as_deref(), place.thread_id.as_deref());
+ let rows = state.db.close_stopped(&place.kwant_id, channel, direct, thread).await.unwrap_or_default();
+ super::waiting::closed(state, &rows, super::waiting::REASON_LATER_REPLY);
+ let failed = state.db.close_failed_in_chat(&place.kwant_id, channel, direct, thread).await.unwrap_or_default();
+ super::waiting::closed_failed(state, &place.kwant_id, (channel, direct, thread), &failed, super::waiting::REASON_LATER_REPLY);
}
/// Whether a turn that stopped gets a Needs-you item of its own: only a person's chat (depth 0)
@@ -162,6 +180,18 @@ pub fn gave_up_meta(meta: Option<Value>, resumes_itself: bool) -> Option<Value>
mod tests {
use super::*;
+ /// 22i (Quant's case): no Needs-you item for a stop whose notice wasn't saved; the chat the
+ /// row opens would show nothing to do. An expired approval's Retry works from the row itself.
+ #[test]
+ fn a_stop_becomes_an_item_only_with_its_notice_saved() {
+ assert!(may_ask(Some("m1"), &Resume::ResendMessage));
+ assert!(may_ask(Some("m1"), &Resume::Continue));
+ assert!(!may_ask(None, &Resume::ResendMessage));
+ assert!(!may_ask(Some(""), &Resume::ResendMessage));
+ assert!(!may_ask(None, &Resume::Continue));
+ assert!(may_ask(None, &Resume::Approval { approval_id: "a1".into() }));
+ }
+
#[test]
fn lines_are_short_and_drop_the_bot_tag() {
assert_eq!(short_line("⚠️ [Ben] Couldn't finish this reply: boom\nmore"), "Couldn't finish this reply: boom");
diff --git a/src/server/waiting.rs b/src/server/waiting.rs
index 318f36c7..0242b43c 100644
--- a/src/server/waiting.rs
+++ b/src/server/waiting.rs
@@ -12,8 +12,9 @@ use crate::db::models::{Kwant, MessageExtra, NewMessage};
use crate::db::waiting::{NewWaitingItem, WaitingItem};
use crate::drivers::events::RuntimeEvent;
use axum::{
- extract::State,
- http::StatusCode,
+ body::Bytes,
+ extract::{Path, State},
+ http::{HeaderMap, StatusCode},
response::{IntoResponse, Response},
Json,
};
@@ -67,7 +68,9 @@ pub(super) async fn turn_ended(scope: &TurnScope, kwant: &Kwant, turn_id: &str,
question: q.question.clone(),
due_at,
};
- let _ = state.db.add_waiting(&item).await;
+ if let Ok(Some(w)) = state.db.add_waiting(&item).await {
+ opened(state, &w);
+ }
}
state.scheduler_wake.notify_one();
return;
@@ -92,14 +95,81 @@ pub(super) async fn turn_ended(scope: &TurnScope, kwant: &Kwant, turn_id: &str,
question: question.chars().take(crate::db::questions::MAX_QUESTION_CHARS).collect(),
due_at,
};
- if matches!(state.db.add_waiting(&item).await, Ok(Some(_))) {
+ if let Ok(Some(w)) = state.db.add_waiting(&item).await {
+ opened(state, &w);
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;
+ let rows = state.db.close_waiting_in_chat(channel_id, direct_kwant_id, thread_id).await.unwrap_or_default();
+ closed(state, &rows, REASON_PERSON_WROTE);
+}
+
+// ---- 22i: every open and close is said live, with one event ----
+
+/// Why an item left Needs you, as `waiting_updated`'s `item.reason` says it.
+pub const REASON_LATER_REPLY: &str = "later_reply";
+pub const REASON_PERSON_WROTE: &str = "person_wrote";
+pub const REASON_ANSWERED: &str = "answered";
+pub const REASON_REPLACED: &str = "replaced";
+pub const REASON_RESUMED: &str = "resumed";
+pub const REASON_PLACE_GONE: &str = "place_gone";
+pub const REASON_DISMISSED: &str = "dismissed";
+
+/// A waiting item's kind as the event and `GET /api/waiting` name it.
+fn kind_of(w: &WaitingItem) -> &'static str {
+ match (&w.question_id, w.kind.as_deref()) {
+ (Some(_), _) => "question",
+ (None, Some(crate::db::waiting::STOPPED)) => "stopped",
+ _ => "reply",
+ }
+}
+
+/// The `item` of a `waiting_updated` event.
+pub fn event_item(w: &WaitingItem, reason: Option<&str>) -> Value {
+ json!({
+ "id": w.id,
+ "kind": kind_of(w),
+ "status": if w.status == "closed" { "closed" } else { "open" },
+ "reason": reason,
+ "kwant_id": w.kwant_id,
+ "channel_id": w.channel_id,
+ "direct_kwant_id": w.direct_kwant_id,
+ "thread_id": w.thread_id,
+ })
+}
+
+/// A new item waits on the person: clients add it to Needs you now.
+pub fn opened(state: &AppState, w: &WaitingItem) {
+ let _ = state.event_sender.send(RuntimeEvent::WaitingUpdated { item: event_item(w, None) });
+}
+
+/// These items closed (`reason`): clients drop them from Needs you now, with the same event a
+/// new item uses.
+pub fn closed(state: &AppState, rows: &[WaitingItem], reason: &str) {
+ for w in rows {
+ let _ = state.event_sender.send(RuntimeEvent::WaitingUpdated { item: event_item(w, Some(reason)) });
+ }
+}
+
+/// Failed or stuck items (`(kind, id)`: "delegation" or "routine_run") of `kwant_id` closed.
+pub fn closed_failed(state: &AppState, kwant_id: &str, place: (Option<&str>, Option<&str>, Option<&str>), items: &[(String, String)], reason: &str) {
+ let (channel_id, direct_kwant_id, thread_id) = place;
+ for (kind, id) in items {
+ let item = json!({
+ "id": id,
+ "kind": kind,
+ "status": "closed",
+ "reason": reason,
+ "kwant_id": kwant_id,
+ "channel_id": channel_id,
+ "direct_kwant_id": direct_kwant_id,
+ "thread_id": thread_id,
+ });
+ let _ = state.event_sender.send(RuntimeEvent::WaitingUpdated { item });
+ }
}
/// The reminder's text: one short line quoting what the bot asked.
@@ -131,7 +201,8 @@ async fn remind(state: &AppState, w: &WaitingItem) -> bool {
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;
+ let rows = state.db.close_waiting_for_question(qid).await.unwrap_or_default();
+ closed(state, &rows, REASON_ANSWERED);
return false;
}
}
@@ -270,6 +341,66 @@ pub async fn list(State(state): State<AppState>, super::spaces::Scope(space): su
Json(json!({ "items": items, "follow_up_hours": follow_up_hours(&state).await })).into_response()
}
+/// `POST /api/waiting/:id/dismiss`, optional body `{"kind": "<item kind from /api/away>"}`, the
+/// person only (22i): clears one stopped, failed or stuck item from Needs attention without
+/// resuming it. Records why (`attention_closed`, reason `dismissed`) and says so live with the
+/// `waiting_updated` event a new item uses.
+///
+/// 200 `{id, kind, status: "closed", already_closed}`; 400 `bad_kind` / `bad_body`; 403
+/// `person_only` for a bot's token; 404 `not_found`; 409 `use_question_answer`,
+/// `use_approval_decide`, `use_step_decline` or `use_watch_decide` for an item that has its own
+/// answer, which tells the bot.
+pub async fn dismiss(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>, body: Bytes) -> Response {
+ if let Err(r) = super::mcp_suggest::refuse_agent_tokens(&state, &headers, "only the person can dismiss what needs their attention").await {
+ return r;
+ }
+ #[derive(serde::Deserialize, Default)]
+ struct Body {
+ kind: Option<String>,
+ }
+ let parsed: Body = if body.iter().all(u8::is_ascii_whitespace) {
+ Body::default()
+ } else {
+ match serde_json::from_slice(&body) {
+ Ok(b) => b,
+ Err(_) => return dismiss_error(StatusCode::BAD_REQUEST, "bad_body", "The body must be JSON like {\"kind\": \"stopped\"}, or empty."),
+ }
+ };
+ let kind = parsed.kind.as_deref().map(str::trim).filter(|k| !k.is_empty());
+ use crate::db::away::Dismissed;
+ match state.db.dismiss_attention(&id, kind).await {
+ Ok(Dismissed::Closed { kind, kwant_id, waiting }) => {
+ tracing::info!(target: "audit", item_id = %id, kind = %kind, kwant_id = kwant_id.as_deref().unwrap_or(""), "the person dismissed a Needs-attention item");
+ match &waiting {
+ Some(w) => closed(&state, std::slice::from_ref(w.as_ref()), REASON_DISMISSED),
+ None => closed_failed(&state, kwant_id.as_deref().unwrap_or(""), (None, None, None), &[(kind.clone(), id.clone())], REASON_DISMISSED),
+ }
+ Json(json!({"id": id, "kind": kind, "status": "closed", "already_closed": false})).into_response()
+ }
+ Ok(Dismissed::AlreadyClosed { kind }) => Json(json!({"id": id, "kind": kind, "status": "closed", "already_closed": true})).into_response(),
+ Ok(Dismissed::NotFound) => dismiss_error(StatusCode::NOT_FOUND, "not_found", "Nothing in Needs attention has that id."),
+ Ok(Dismissed::Refused(code)) => dismiss_error(StatusCode::CONFLICT, code, refused_text(code)),
+ Ok(Dismissed::BadKind) => dismiss_error(StatusCode::BAD_REQUEST, "bad_kind", "kind must be stopped, reply, delegation or routine_run."),
+ Err(e) => {
+ tracing::warn!(error = %e, "dismiss failed");
+ dismiss_error(StatusCode::INTERNAL_SERVER_ERROR, "internal", "Couldn't dismiss that just now.")
+ }
+ }
+}
+
+fn refused_text(code: &str) -> &'static str {
+ match code {
+ "use_question_answer" => "Answer or cancel the question instead, so the bot knows.",
+ "use_approval_decide" => "Allow or deny the approval instead, so the bot knows.",
+ "use_step_decline" => "Do or decline the browser step instead, so the bot knows.",
+ _ => "Decide it in its own card instead, so the bot knows.",
+ }
+}
+
+fn dismiss_error(status: StatusCode, code: &str, msg: &str) -> Response {
+ (status, Json(json!({"error": msg, "code": code}))).into_response()
+}
+
#[cfg(test)]
mod tests {
use super::*;