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.

away: "While you were away" API (batch3)

Lin (kwant bot)2d64a409e116
diff --git a/src/broker/mod.rs b/src/broker/mod.rs
index e1ca3125..a6d3e214 100644
--- a/src/broker/mod.rs
+++ b/src/broker/mod.rs
@@ -48,6 +48,12 @@ impl PermissionBroker {
map.contains_key(ticket_id)
}
+ /// Tickets still waiting for the user. A stored ticket not in here (kwnt restarted, the
+ /// turn ended) can no longer be answered.
+ pub async fn pending_ids(&self) -> Vec<String> {
+ self.pending.lock().await.keys().cloned().collect()
+ }
+
/// Resolves an approval ticket by sending the user's decision to the waiting oneshot channel.
pub async fn resolve(&self, ticket_id: &str, decision: ApprovalDecision) -> bool {
let mut map = self.pending.lock().await;
diff --git a/src/db/away.rs b/src/db/away.rs
new file mode 100644
index 00000000..1a576ad5
--- /dev/null
+++ b/src/db/away.rs
@@ -0,0 +1,225 @@
+//! "While you were away": what's waiting on the user, what finished and what failed or got
+//! stuck, read from the tables that already record it (questions, approvals, delegations and
+//! routine runs). Read-only apart from the user's last-seen marker.
+
+use super::{Database, DbError};
+use chrono::{DateTime, Utc};
+use sqlx::FromRow;
+
+/// Settings row holding when the user last looked (RFC 3339). Not one of the `/api/settings`
+/// keys: only `POST /api/away/seen` writes it.
+pub const LAST_SEEN_KEY: &str = "away_last_seen";
+
+/// A row behind one item, before its summary is cleaned. Every query selects these columns.
+#[derive(Debug, Clone, FromRow)]
+pub struct AwayRow {
+ pub kind: String,
+ pub id: String,
+ pub kwant_id: String,
+ pub kwant_name: Option<String>,
+ pub title: String,
+ pub status: String,
+ /// Raw text the summary comes from: a result, an error or the question's choices.
+ pub body: Option<String>,
+ pub at: DateTime<Utc>,
+ pub thread_id: Option<String>,
+ pub channel_id: Option<String>,
+ pub direct_kwant_id: Option<String>,
+ /// Questions only: the JSON array of choices.
+ pub choices: Option<String>,
+}
+
+const OPEN_QUESTIONS: &str = "
+ SELECT 'question' AS kind, q.id, q.kwant_id, k.name AS kwant_name, q.question AS title, q.status,
+ NULL AS body, q.created_at AS at, q.thread_id, q.channel_id, q.direct_kwant_id, q.choices
+ FROM questions q LEFT JOIN kwants k ON k.id = q.kwant_id
+ WHERE q.status = 'open'";
+
+/// `?1` = since. Completed delegations report the specialist's result message.
+const DELEGATIONS_ENDED: &str = "
+ SELECT 'delegation' AS kind, d.id, d.specialist_kwant_id AS kwant_id, k.name AS kwant_name, d.title, d.status,
+ CASE WHEN d.status = 'completed' THEN COALESCE(m.text, d.error) ELSE COALESCE(d.error, m.text) END AS body,
+ d.ended_at AS at, d.thread_id, 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
+ LEFT JOIN messages m ON m.id = d.result_message_id
+ WHERE d.ended_at > ?1";
+
+/// `?1` = started before. Still running past the threshold.
+const DELEGATIONS_STUCK: &str = "
+ SELECT 'delegation' AS kind, d.id, d.specialist_kwant_id AS kwant_id, k.name AS kwant_name, d.title,
+ 'stuck' AS status, NULL AS body, d.started_at AS at, d.thread_id,
+ 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";
+
+/// `?1` = since. A routine posts in its channel, or the kwant's direct chat when it has none.
+const ROUTINE_RUNS_ENDED: &str = "
+ SELECT 'routine_run' AS kind, r.id, rt.kwant_id, k.name AS kwant_name, rt.name AS title, r.status,
+ CASE WHEN r.status = 'ok' THEN m.text ELSE r.error END AS body, r.ended_at AS at,
+ NULL AS thread_id, rt.channel_id,
+ CASE WHEN rt.channel_id IS NULL THEN rt.kwant_id END AS direct_kwant_id, NULL AS choices
+ FROM routine_runs r
+ JOIN routines rt ON rt.id = r.routine_id
+ LEFT JOIN kwants k ON k.id = rt.kwant_id
+ LEFT JOIN messages m ON m.id = r.message_id
+ WHERE r.ended_at > ?1";
+
+const FINISHED_DELEGATIONS: &str = "d.status = 'completed'";
+const FAILED_DELEGATIONS: &str = "d.status IN ('failed', 'interrupted')";
+const FINISHED_RUNS: &str = "r.status = 'ok'";
+const FAILED_RUNS: &str = "r.status = 'error'";
+
+impl Database {
+ /// Additive: partial indexes so the away queries never scan delegations or routine runs.
+ /// An old binary just doesn't use them.
+ pub(super) async fn migrate_away(&self) -> Result<(), DbError> {
+ for stmt in [
+ "CREATE INDEX IF NOT EXISTS delegations_by_end ON delegations (status, ended_at) WHERE ended_at IS NOT NULL",
+ "CREATE INDEX IF NOT EXISTS delegations_running ON delegations (started_at) WHERE status = 'running'",
+ "CREATE INDEX IF NOT EXISTS routine_runs_by_end ON routine_runs (status, ended_at) WHERE ended_at IS NOT NULL",
+ ] {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ Ok(())
+ }
+
+ /// Open questions, newest first.
+ pub async fn away_open_questions(&self, limit: i64) -> Result<Vec<AwayRow>, DbError> {
+ Ok(sqlx::query_as(&format!("{OPEN_QUESTIONS} ORDER BY q.created_at DESC, q.rowid DESC LIMIT ?1"))
+ .bind(limit)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ pub async fn away_count_open_questions(&self) -> Result<i64, DbError> {
+ Ok(sqlx::query_scalar("SELECT COUNT(*) FROM questions WHERE status = 'open'")
+ .fetch_one(&self.pool)
+ .await?)
+ }
+
+ /// Pending approvals among `ids` (the tickets the broker still waits on), newest first.
+ pub async fn away_pending_approvals(&self, ids: &[String]) -> Result<Vec<AwayRow>, DbError> {
+ if ids.is_empty() {
+ return Ok(Vec::new());
+ }
+ let marks = vec!["?"; ids.len()].join(", ");
+ let sql = format!(
+ "SELECT 'approval' AS kind, a.id, a.kwant_id, k.name AS kwant_name, a.tool_name AS title, a.status,
+ a.parameters AS body, a.created_at AS at, NULL AS thread_id, NULL AS channel_id,
+ NULL AS direct_kwant_id, NULL AS choices
+ FROM approvals a LEFT JOIN kwants k ON k.id = a.kwant_id
+ WHERE a.status = 'pending' AND a.id IN ({marks})
+ ORDER BY a.created_at DESC, a.rowid DESC"
+ );
+ let mut q = sqlx::query_as(&sql);
+ for id in ids {
+ q = q.bind(id);
+ }
+ Ok(q.fetch_all(&self.pool).await?)
+ }
+
+ /// Completed delegations and successful routine runs that ended after `since`, newest first.
+ pub async fn away_finished(&self, since: DateTime<Utc>, limit: i64) -> Result<Vec<AwayRow>, DbError> {
+ let mut rows = self.ended(DELEGATIONS_ENDED, FINISHED_DELEGATIONS, "d", since, limit).await?;
+ rows.extend(self.ended(ROUTINE_RUNS_ENDED, FINISHED_RUNS, "r", since, limit).await?);
+ Ok(newest(rows, limit))
+ }
+
+ /// Failed or interrupted delegations and failed routine runs that ended after `since`, plus
+ /// delegations still running that started before `stuck_before`, newest first.
+ pub async fn away_failed(
+ &self,
+ since: DateTime<Utc>,
+ stuck_before: DateTime<Utc>,
+ limit: i64,
+ ) -> Result<Vec<AwayRow>, DbError> {
+ let mut rows = self.ended(DELEGATIONS_ENDED, FAILED_DELEGATIONS, "d", since, limit).await?;
+ rows.extend(self.ended(ROUTINE_RUNS_ENDED, FAILED_RUNS, "r", since, limit).await?);
+ rows.extend(
+ sqlx::query_as::<_, AwayRow>(&format!("{DELEGATIONS_STUCK} ORDER BY d.started_at DESC, d.rowid DESC LIMIT ?2"))
+ .bind(stuck_before)
+ .bind(limit)
+ .fetch_all(&self.pool)
+ .await?,
+ );
+ Ok(newest(rows, limit))
+ }
+
+ /// Uncapped (finished, failed) counts for the same filters.
+ pub async fn away_counts(&self, since: DateTime<Utc>, stuck_before: DateTime<Utc>) -> Result<(i64, i64), DbError> {
+ let finished = self.count(DELEGATIONS_ENDED, FINISHED_DELEGATIONS, since).await?
+ + self.count(ROUTINE_RUNS_ENDED, FINISHED_RUNS, since).await?;
+ let failed = self.count(DELEGATIONS_ENDED, FAILED_DELEGATIONS, since).await?
+ + self.count(ROUTINE_RUNS_ENDED, FAILED_RUNS, since).await?
+ + self.count(DELEGATIONS_STUCK, "1", stuck_before).await?;
+ Ok((finished, failed))
+ }
+
+ async fn count(&self, sql: &str, cond: &str, t: DateTime<Utc>) -> Result<i64, DbError> {
+ Ok(sqlx::query_scalar(&format!("SELECT COUNT(*) FROM ({sql} AND {cond})"))
+ .bind(t)
+ .fetch_one(&self.pool)
+ .await?)
+ }
+
+ async fn ended(
+ &self,
+ sql: &str,
+ cond: &str,
+ alias: &str,
+ since: DateTime<Utc>,
+ limit: i64,
+ ) -> Result<Vec<AwayRow>, DbError> {
+ Ok(sqlx::query_as(&format!(
+ "{sql} AND {cond} ORDER BY {alias}.ended_at DESC, {alias}.rowid DESC LIMIT ?2"
+ ))
+ .bind(since)
+ .bind(limit)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+}
+
+/// Newest first, at most `limit`.
+fn newest(mut rows: Vec<AwayRow>, limit: i64) -> Vec<AwayRow> {
+ rows.sort_by(|a, b| b.at.cmp(&a.at).then_with(|| b.id.cmp(&a.id)));
+ rows.truncate(limit.max(0) as usize);
+ rows
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ async fn plan(db: &Database, sql: &str) -> Vec<String> {
+ let rows: Vec<(i64, i64, i64, String)> = sqlx::query_as(&format!("EXPLAIN QUERY PLAN {sql}"))
+ .bind(Utc::now())
+ .bind(50)
+ .fetch_all(&db.pool)
+ .await
+ .unwrap();
+ rows.into_iter().map(|r| r.3).collect()
+ }
+
+ /// Every away query reaches its rows through an index, never by scanning a whole table
+ /// (the small lookups joined in by primary key aside).
+ #[tokio::test]
+ async fn away_queries_use_indexes() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let cases = [
+ (format!("{DELEGATIONS_ENDED} AND {FINISHED_DELEGATIONS} ORDER BY d.ended_at DESC LIMIT ?2"), "delegations_by_end"),
+ (format!("{DELEGATIONS_ENDED} AND {FAILED_DELEGATIONS} ORDER BY d.ended_at DESC LIMIT ?2"), "delegations_by_end"),
+ (format!("{DELEGATIONS_STUCK} ORDER BY d.started_at DESC LIMIT ?2"), "delegations_running"),
+ (format!("{ROUTINE_RUNS_ENDED} AND {FINISHED_RUNS} ORDER BY r.ended_at DESC LIMIT ?2"), "routine_runs_by_end"),
+ (format!("{ROUTINE_RUNS_ENDED} AND {FAILED_RUNS} ORDER BY r.ended_at DESC LIMIT ?2"), "routine_runs_by_end"),
+ (format!("{OPEN_QUESTIONS} ORDER BY q.created_at DESC LIMIT ?2"), "questions_by_status"),
+ ];
+ for (sql, idx) in cases {
+ let detail = plan(&db, &sql).await;
+ assert!(!detail.iter().any(|d| d.starts_with("SCAN")), "full scan: {detail:?}\n{sql}");
+ assert!(detail.iter().any(|d| d.contains(idx)), "{idx} unused: {detail:?}");
+ }
+ }
+}
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 8c8c4919..35eed9aa 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -6,6 +6,7 @@ pub mod history;
pub mod attachments;
pub mod questions;
pub mod skills;
+pub mod away;
use models::*;
use sqlx::{sqlite::SqlitePoolOptions, Pool, Sqlite};
@@ -92,6 +93,7 @@ impl Database {
db.migrate_questions().await?;
db.migrate_attachments().await?;
db.migrate_history().await?;
+ db.migrate_away().await?;
db.seed_defaults().await?;
Ok(db)
diff --git a/src/server/away.rs b/src/server/away.rs
new file mode 100644
index 00000000..39c8d1c8
--- /dev/null
+++ b/src/server/away.rs
@@ -0,0 +1,293 @@
+//! "While you were away" (batch 3): `GET /api/away` lists what's waiting on the user, what
+//! finished and what failed or got stuck; `POST /api/away/seen` records that the user looked,
+//! which moves the default `since` and resets the unseen counts for the sidebar badge.
+//!
+//! Summaries are one line of at most [`SUMMARY_CHARS`] with anything key-like masked: results
+//! and errors can carry provider text.
+
+use super::AppState;
+use crate::db::away::{AwayRow, LAST_SEEN_KEY};
+use crate::profiles::classify::redact_detail;
+use axum::{
+ extract::{Query, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ Json,
+};
+use chrono::{DateTime, Duration, SecondsFormat, Utc};
+use serde::Deserialize;
+use serde_json::{json, Value};
+
+/// Most items per list.
+pub const MAX_ITEMS: i64 = 50;
+/// A delegation still running this long after it started counts as stuck.
+pub const STUCK_AFTER_MINUTES: i64 = 30;
+/// How far back the page looks when the user has never marked it seen.
+pub const DEFAULT_LOOKBACK_DAYS: i64 = 7;
+pub const SUMMARY_CHARS: usize = 200;
+const TITLE_CHARS: usize = 120;
+/// Argument names whose values are never shown in an approval's summary.
+const SECRET_ARG_HINTS: [&str; 6] = ["key", "token", "secret", "password", "auth", "cookie"];
+
+fn error(status: StatusCode, message: impl Into<String>) -> Response {
+ (status, Json(json!({ "error": message.into() }))).into_response()
+}
+
+fn internal() -> Response {
+ StatusCode::INTERNAL_SERVER_ERROR.into_response()
+}
+
+fn rfc3339(t: DateTime<Utc>) -> String {
+ t.to_rfc3339_opts(SecondsFormat::Millis, true)
+}
+
+/// Whether `word` looks like a key or token, by the same rule provider errors are masked with.
+fn looks_secret(word: &str) -> bool {
+ !word.is_empty() && redact_detail(word, usize::MAX) == "[redacted]"
+}
+
+/// One line for a card: the first non-empty line without markdown markers, at most
+/// [`SUMMARY_CHARS`], with any word that has a key-like part (`"sk-…"`, `key=…`) masked.
+pub fn summarize(text: &str) -> String {
+ let line = text
+ .lines()
+ .map(|l| l.trim().trim_start_matches(['#', '>', '*', '-', ' ']).trim())
+ .find(|l| !l.is_empty())
+ .unwrap_or_default();
+ let masked: Vec<&str> = line
+ .split_whitespace()
+ .map(|w| {
+ if w.split(|c: char| "\"'`=:,;()[]{}<>".contains(c)).any(looks_secret) {
+ "[redacted]"
+ } else {
+ w
+ }
+ })
+ .collect();
+ let joined = masked.join(" ");
+ if joined.chars().count() > SUMMARY_CHARS {
+ let cut: String = joined.chars().take(SUMMARY_CHARS - 1).collect();
+ format!("{}…", cut.trim_end())
+ } else {
+ joined
+ }
+}
+
+fn clip_title(text: &str) -> String {
+ let line = text.split_whitespace().collect::<Vec<_>>().join(" ");
+ if line.chars().count() <= TITLE_CHARS {
+ return line;
+ }
+ let cut: String = line.chars().take(TITLE_CHARS - 1).collect();
+ format!("{cut}…")
+}
+
+/// An approval's stored details as `name: value` pairs, sensitive argument names masked.
+fn approval_summary(parameters: &str) -> String {
+ let details: Value = serde_json::from_str(parameters).unwrap_or(Value::Null);
+ let mut parts = Vec::new();
+ if let Some(args) = details["arguments"].as_object() {
+ for (k, v) in args {
+ let lower = k.to_ascii_lowercase();
+ let shown = if SECRET_ARG_HINTS.iter().any(|h| lower.contains(h)) {
+ "[redacted]".to_string()
+ } else {
+ match v {
+ Value::String(s) => s.clone(),
+ other => other.to_string(),
+ }
+ };
+ parts.push(format!("{k}: {shown}"));
+ }
+ }
+ if parts.is_empty() {
+ return "Wants your approval to use this tool".into();
+ }
+ summarize(&parts.join(", "))
+}
+
+fn approval_title(tool_name: &str, parameters: &str) -> String {
+ let details: Value = serde_json::from_str(parameters).unwrap_or(Value::Null);
+ match (details["tool"].as_str(), details["server"].as_str()) {
+ (Some(tool), Some(server)) => clip_title(&format!("Use {tool} ({server})")),
+ _ => clip_title(&format!("Use {tool_name}")),
+ }
+}
+
+fn fallback_summary(row: &AwayRow) -> &'static str {
+ match (row.kind.as_str(), row.status.as_str()) {
+ (_, "stuck") => "Still running with no result yet",
+ (_, "completed" | "ok") => "Finished",
+ (_, "interrupted") => "Stopped before it finished",
+ _ => "Failed",
+ }
+}
+
+fn item(row: AwayRow) -> Value {
+ let (title, summary) = match row.kind.as_str() {
+ "approval" => {
+ let params = row.body.as_deref().unwrap_or("");
+ (approval_title(&row.title, params), approval_summary(params))
+ }
+ "question" => {
+ let choices: Vec<String> = row
+ .choices
+ .as_deref()
+ .and_then(|c| serde_json::from_str(c).ok())
+ .unwrap_or_default();
+ let summary = if choices.is_empty() {
+ "Waiting for your answer".to_string()
+ } else {
+ summarize(&format!("Choices: {}", choices.join(" · ")))
+ };
+ (clip_title(&row.title), summary)
+ }
+ _ => {
+ let summary = row.body.as_deref().map(summarize).filter(|s| !s.is_empty());
+ (clip_title(&row.title), summary.unwrap_or_else(|| fallback_summary(&row).into()))
+ }
+ };
+ let mut v = json!({
+ "kind": row.kind,
+ "id": row.id,
+ "kwant_id": row.kwant_id,
+ "kwant_name": row.kwant_name.unwrap_or_else(|| "An agent".into()),
+ "title": title,
+ "summary": summary,
+ "status": row.status,
+ "timestamp": rfc3339(row.at),
+ "link": {
+ "thread_id": row.thread_id,
+ "channel_id": row.channel_id,
+ "direct_kwant_id": row.direct_kwant_id,
+ },
+ });
+ if row.kind == "question" {
+ v["choices"] = row
+ .choices
+ .as_deref()
+ .and_then(|c| serde_json::from_str(c).ok())
+ .unwrap_or_else(|| json!([]));
+ }
+ v
+}
+
+async fn last_seen(state: &AppState) -> Result<Option<DateTime<Utc>>, crate::db::DbError> {
+ Ok(state
+ .db
+ .get_setting(LAST_SEEN_KEY)
+ .await?
+ .and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
+ .map(|t| t.with_timezone(&Utc)))
+}
+
+/// Approvals the broker still waits on, each linked to the chat its turn runs in.
+async fn waiting_approvals(state: &AppState) -> Result<Vec<AwayRow>, crate::db::DbError> {
+ let live = state.broker.pending_ids().await;
+ let mut rows = state.db.away_pending_approvals(&live).await?;
+ let turns = state.turns.active_turns();
+ // turn_id isn't in the row; look it up by ticket
+ for row in &mut rows {
+ let turn_id = state.db.get_approval(&row.id).await?.map(|a| a.turn_id);
+ let turn = turns.iter().find(|t| Some(&t.turn_id) == turn_id.as_ref());
+ match turn {
+ Some(t) if t.thread_id.is_some() => row.thread_id = t.thread_id.clone(),
+ Some(t) => match state.db.get_channel(&t.context_id).await?.is_some() {
+ true => row.channel_id = Some(t.context_id.clone()),
+ false => row.direct_kwant_id = Some(t.context_id.clone()),
+ },
+ None => row.direct_kwant_id = Some(row.kwant_id.clone()),
+ }
+ }
+ Ok(rows)
+}
+
+#[derive(Debug, Deserialize)]
+pub struct AwayQuery {
+ pub since: Option<String>,
+}
+
+/// `GET /api/away?since=<RFC 3339>`: `since` defaults to the last-seen marker, else 7 days ago.
+/// Waiting items and stuck delegations are listed whatever `since` is: they still need you.
+pub async fn get(State(state): State<AppState>, Query(q): Query<AwayQuery>) -> Response {
+ let now = Utc::now();
+ let Ok(seen) = last_seen(&state).await else {
+ return internal();
+ };
+ let default_since = seen.unwrap_or(now - Duration::days(DEFAULT_LOOKBACK_DAYS));
+ let since = match q.since.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
+ None => default_since,
+ Some(s) => match DateTime::parse_from_rfc3339(s) {
+ Ok(t) => t.with_timezone(&Utc),
+ Err(_) => return error(StatusCode::BAD_REQUEST, "since must be an RFC 3339 time, e.g. 2026-10-17T09:00:00Z"),
+ },
+ };
+ let stuck_before = now - Duration::minutes(STUCK_AFTER_MINUTES);
+
+ let result = async {
+ let mut waiting = state.db.away_open_questions(MAX_ITEMS).await?;
+ let approvals = waiting_approvals(&state).await?;
+ let waiting_count = state.db.away_count_open_questions().await? + approvals.len() as i64;
+ waiting.extend(approvals);
+ waiting.sort_by(|a, b| b.at.cmp(&a.at).then_with(|| b.id.cmp(&a.id)));
+ waiting.truncate(MAX_ITEMS as usize);
+ let finished = state.db.away_finished(since, MAX_ITEMS).await?;
+ let failed = state.db.away_failed(since, stuck_before, MAX_ITEMS).await?;
+ // The badge counts from the marker, whatever this page asked for
+ let (unseen_finished, unseen_failed) = state.db.away_counts(default_since, stuck_before).await?;
+ Ok::<_, crate::db::DbError>((waiting, finished, failed, waiting_count, unseen_finished, unseen_failed))
+ }
+ .await;
+ let Ok((waiting, finished, failed, waiting_count, unseen_finished, unseen_failed)) = result else {
+ return internal();
+ };
+ Json(json!({
+ "since": rfc3339(since),
+ "last_seen": seen.map(rfc3339),
+ "now": rfc3339(now),
+ "stuck_after_minutes": STUCK_AFTER_MINUTES,
+ "waiting": waiting.into_iter().map(item).collect::<Vec<_>>(),
+ "finished": finished.into_iter().map(item).collect::<Vec<_>>(),
+ "failed": failed.into_iter().map(item).collect::<Vec<_>>(),
+ "unseen": {
+ "waiting": waiting_count,
+ "finished": unseen_finished,
+ "failed": unseen_failed,
+ "total": waiting_count + unseen_finished + unseen_failed,
+ },
+ }))
+ .into_response()
+}
+
+/// `POST /api/away/seen`: the user has looked; returns the stored marker.
+pub async fn seen(State(state): State<AppState>) -> Response {
+ let now = Utc::now();
+ if state.db.set_setting(LAST_SEEN_KEY, &rfc3339(now)).await.is_err() {
+ return internal();
+ }
+ Json(json!({ "last_seen": rfc3339(now) })).into_response()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn summaries_are_one_short_masked_line() {
+ assert_eq!(summarize("\n\n## Done\nmore"), "Done");
+ let s = summarize(r#"401 from provider: {"key":"sk-ant-api03-abcdefghijklmnop1234"} key=xai-ABCDEFGH12345678abcd"#);
+ assert!(!s.contains("sk-ant") && !s.contains("xai-"), "{s}");
+ assert!(s.starts_with("401 from provider:"));
+ let long = summarize(&"word ".repeat(100));
+ assert_eq!(long.chars().count(), SUMMARY_CHARS);
+ assert!(long.ends_with('…'));
+ }
+
+ #[test]
+ fn approval_summaries_hide_sensitive_arguments() {
+ let p = r#"{"tool":"send","server":"mail","arguments":{"to":"[email protected]","api_token":"plain-but-hidden"}}"#;
+ assert_eq!(approval_title("mcp__mail__send", p), "Use send (mail)");
+ let s = approval_summary(p);
+ assert!(s.contains("to: [email protected]") && !s.contains("plain-but-hidden"), "{s}");
+ }
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 39c3f59c..f7384585 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -15,6 +15,7 @@ pub mod delegation;
pub mod attachments;
pub mod questions;
pub mod skills;
+pub mod away;
use crate::broker::PermissionBroker;
use crate::config::Config;
@@ -193,6 +194,8 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/skills/:id/diff", get(skills::diff))
.route("/api/skills/:id/approve", post(skills::approve))
.route("/api/skills/:id/reject", post(skills::reject))
+ .route("/api/away", get(away::get))
+ .route("/api/away/seen", post(away::seen))
.route("/api/events", get(sse::sse_handler))
.fallback(crate::embedded::static_handler)
.layer(axum::middleware::from_fn_with_state(state.clone(), auth::guard))
diff --git a/tests/away_test.rs b/tests/away_test.rs
new file mode 100644
index 00000000..f77d96b5
--- /dev/null
+++ b/tests/away_test.rs
@@ -0,0 +1,365 @@
+//! "While you were away" (batch 3): `GET /api/away` and `POST /api/away/seen`.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use chrono::{DateTime, Duration, SecondsFormat, Utc};
+use kwnt::{
+ broker::{ApprovalRequest, PermissionBroker},
+ config::Config,
+ db::{
+ continuity::NewRoutine,
+ models::{NewApproval, NewChannel, NewMessage},
+ questions::QuestionPlace,
+ threads::NewDelegation,
+ Database,
+ },
+ router::LayaRouter,
+ server::{create_router, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use sqlx::sqlite::SqlitePoolOptions;
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+const SECRET: &str = "sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789";
+
+async fn setup() -> (Router, AppState, TempDir) {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config {
+ data_dir: tmp.path().to_path_buf(),
+ ..Config::default()
+ };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ (create_router(state.clone()), state, tmp)
+}
+
+async fn call(app: &Router, method: &str, uri: &str, headers: &[(&str, &str)]) -> (StatusCode, Value) {
+ let mut b = Request::builder().method(method).uri(uri);
+ for (k, v) in headers {
+ b = b.header(*k, *v);
+ }
+ let resp = app.clone().oneshot(b.body(Body::empty()).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+async fn get(app: &Router, uri: &str) -> Value {
+ let (s, v) = call(app, "GET", uri, &[]).await;
+ assert_eq!(s, StatusCode::OK, "{uri}: {v}");
+ v
+}
+
+/// Sets a timestamp column the way kwnt writes it (sqlx's encoding), so comparisons line up.
+async fn set_time(state: &AppState, table: &str, column: &str, id: &str, t: DateTime<Utc>) {
+ let pool = SqlitePoolOptions::new()
+ .max_connections(1)
+ .connect(&format!("sqlite://{}", state.config.data_dir.join("kwnt.db").display()))
+ .await
+ .unwrap();
+ sqlx::query(&format!("UPDATE {table} SET {column} = ? WHERE id = ?"))
+ .bind(t)
+ .bind(id)
+ .execute(&pool)
+ .await
+ .unwrap();
+ pool.close().await;
+}
+
+fn reply(kwant: &str, text: &str) -> NewMessage {
+ NewMessage {
+ channel_id: None,
+ direct_kwant_id: Some(kwant.into()),
+ sender_role: "kwant".into(),
+ sender_id: kwant.into(),
+ text: text.into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 1,
+ }
+}
+
+/// A delegation from `lead` to `specialist` left in `status` (with `error`, or a result message).
+async fn delegation(state: &AppState, lead: &str, specialist: &str, title: &str, status: &str, text: Option<&str>) -> (String, String) {
+ let (thread, d) = state
+ .db
+ .create_delegation(&NewDelegation {
+ lead_kwant_id: lead.into(),
+ specialist_kwant_id: specialist.into(),
+ origin_channel_id: None,
+ origin_kwant_id: Some(lead.into()),
+ origin_thread_id: None,
+ team_id: None,
+ task: format!("do {title}"),
+ title: title.into(),
+ continue_lead: false,
+ depth: 1,
+ follow_up_at: None,
+ })
+ .await
+ .unwrap();
+ assert!(state.db.mark_delegation_running(&d.id).await.unwrap());
+ match status {
+ "running" => {}
+ "completed" => {
+ let m = state.db.insert_message(&reply(specialist, text.unwrap_or(""))).await.unwrap();
+ assert!(state.db.finish_delegation(&d.id, "completed", None, Some(&m.id)).await.unwrap());
+ }
+ s => assert!(state.db.finish_delegation(&d.id, s, text, None).await.unwrap()),
+ }
+ (d.id, thread.id)
+}
+
+fn ids(list: &Value) -> Vec<String> {
+ list.as_array().unwrap().iter().map(|i| i["id"].as_str().unwrap().to_string()).collect()
+}
+
+fn find<'a>(list: &'a Value, id: &str) -> &'a Value {
+ list.as_array().unwrap().iter().find(|i| i["id"] == id).unwrap_or_else(|| panic!("{id} missing from {list}"))
+}
+
+fn assert_newest_first(list: &Value) {
+ let ts: Vec<&str> = list.as_array().unwrap().iter().map(|i| i["timestamp"].as_str().unwrap()).collect();
+ assert!(ts.windows(2).all(|w| w[0] >= w[1]), "not newest first: {ts:?}");
+}
+
+fn rfc(t: DateTime<Utc>) -> String {
+ t.to_rfc3339_opts(SecondsFormat::Secs, true)
+}
+
+#[tokio::test]
+async fn away_lists_every_kind_filters_caps_and_marks_seen() {
+ let (app, state, _tmp) = setup().await;
+ let kwants = state.db.list_kwants().await.unwrap();
+ let (lead, spec) = (kwants[0].clone(), kwants[1].clone());
+ let chan = state
+ .db
+ .create_channel(&NewChannel {
+ name: "ops".into(),
+ description: None,
+ lead_kwant_id: lead.id.clone(),
+ member_kwants: vec![lead.id.clone(), spec.id.clone()],
+ routing_mode: "auto".into(),
+ })
+ .await
+ .unwrap();
+ let now = Utc::now();
+
+ // Empty, never seen: looks back 7 days
+ let v = get(&app, "/api/away").await;
+ assert_eq!(v["waiting"], json!([]));
+ assert_eq!(v["last_seen"], Value::Null);
+ let since = DateTime::parse_from_rfc3339(v["since"].as_str().unwrap()).unwrap();
+ assert!((now - Duration::days(7) - since.with_timezone(&Utc)).num_seconds().abs() < 5);
+ assert_eq!(v["unseen"], json!({"waiting": 0, "finished": 0, "failed": 0, "total": 0}));
+
+ // Waiting: an open question, an answered one (hidden), a live approval and a stale one
+ let place = QuestionPlace {
+ kwant_id: spec.id.clone(),
+ channel_id: Some(chan.id.clone()),
+ ..Default::default()
+ };
+ let q = state.db.create_question(&place, "Ship tonight?", &["Yes".into(), "No".into()]).await.unwrap();
+ let answered = state.db.create_question(&place, "Old one?", &["A".into()]).await.unwrap();
+ assert!(state.db.close_question(&answered.id, "answered", Some("A")).await.unwrap());
+ set_time(&state, "questions", "created_at", &q.id, now - Duration::days(30)).await;
+ let approval = |tool: &str| NewApproval {
+ turn_id: "turn-gone".into(),
+ kwant_id: lead.id.clone(),
+ tool_name: format!("mcp__mail__{tool}"),
+ parameters: json!({"server": "mail", "tool": tool, "arguments": {"to": "[email protected]", "api_key": "hidden-value"}}),
+ };
+ let live = state.db.save_approval(&approval("send")).await.unwrap();
+ let _rx = state
+ .broker
+ .request_approval(ApprovalRequest {
+ id: live.id.clone(),
+ kwant_id: lead.id.clone(),
+ tool_name: live.tool_name.clone(),
+ details: json!({}),
+ })
+ .await;
+ let stale = state.db.save_approval(&approval("delete")).await.unwrap();
+
+ // Finished: a delegation with a result, a successful routine run; one too old for the default window
+ let (done, done_thread) = delegation(&state, &lead.id, &spec.id, "Write the brief", "completed", Some("## Brief\nAll three sections drafted.")).await;
+ let (old, _) = delegation(&state, &lead.id, &spec.id, "Ancient", "completed", Some("old")).await;
+ set_time(&state, "delegations", "ended_at", &old, now - Duration::days(8)).await;
+ let (two_days, _) = delegation(&state, &lead.id, &spec.id, "Two days ago", "completed", Some("ok")).await;
+ set_time(&state, "delegations", "ended_at", &two_days, now - Duration::days(2)).await;
+ let routine = state
+ .db
+ .create_routine(&NewRoutine {
+ kwant_id: lead.id.clone(),
+ channel_id: None,
+ name: "Morning briefing".into(),
+ instructions: "Summarise".into(),
+ schedule: json!({"type": "interval", "every_minutes": 60}).to_string(),
+ enabled: false,
+ next_run_at: None,
+ })
+ .await
+ .unwrap();
+ let ok_run = state.db.start_routine_run(&routine.id, "manual", "running", None).await.unwrap();
+ let briefing = state.db.insert_message(&reply(&lead.id, "3 new orders, 1 refund.")).await.unwrap();
+ state.db.finish_routine_run(&ok_run.id, "ok", None, Some(&briefing.id)).await.unwrap();
+
+ // Failed: failed and interrupted delegations, a failed run (error carries a key), stuck work
+ let (failed, _) = delegation(&state, &lead.id, &spec.id, "Deploy", "failed", Some(&format!("401 invalid key {SECRET}"))).await;
+ let (interrupted, _) = delegation(&state, &lead.id, &spec.id, "Audit", "interrupted", Some("kwnt stopped before the task finished")).await;
+ let err_run = state
+ .db
+ .start_routine_run(&routine.id, "schedule", "error", Some(&format!("provider said: {{\"key\":\"{SECRET}\"}}")))
+ .await
+ .unwrap();
+ let (stuck, stuck_thread) = delegation(&state, &lead.id, &spec.id, "Long crawl", "running", None).await;
+ set_time(&state, "delegations", "started_at", &stuck, now - Duration::minutes(31)).await;
+ let (busy, _) = delegation(&state, &lead.id, &spec.id, "Short crawl", "running", None).await;
+ set_time(&state, "delegations", "started_at", &busy, now - Duration::minutes(29)).await;
+
+ let v = get(&app, "/api/away").await;
+ let body = v.to_string();
+ assert!(!body.contains(SECRET) && !body.contains("hidden-value"), "secret leaked: {body}");
+
+ // Waiting ignores since; the stale ticket and the answered question aren't there
+ assert_eq!(ids(&v["waiting"]), vec![live.id.clone(), q.id.clone()]);
+ let qi = find(&v["waiting"], &q.id);
+ assert_eq!(qi["kind"], "question");
+ assert_eq!(qi["kwant_name"], spec.name.as_str());
+ assert_eq!(qi["title"], "Ship tonight?");
+ assert_eq!(qi["summary"], "Choices: Yes · No");
+ assert_eq!(qi["choices"], json!(["Yes", "No"]));
+ assert_eq!(qi["link"], json!({"thread_id": null, "channel_id": chan.id, "direct_kwant_id": null}));
+ let ai = find(&v["waiting"], &live.id);
+ assert_eq!(ai["kind"], "approval");
+ assert_eq!(ai["status"], "pending");
+ assert_eq!(ai["title"], "Use send (mail)");
+ assert!(ai["summary"].as_str().unwrap().contains("to: [email protected]"));
+ // No live turn to follow: it opens the agent's direct chat
+ assert_eq!(ai["link"]["direct_kwant_id"], lead.id.as_str());
+ assert!(!ids(&v["waiting"]).contains(&stale.id));
+
+ // Finished within the default 7 days
+ assert_eq!(ids(&v["finished"]), vec![ok_run.id.clone(), done.clone(), two_days.clone()]);
+ let di = find(&v["finished"], &done);
+ assert_eq!(di["kind"], "delegation");
+ assert_eq!(di["kwant_id"], spec.id.as_str());
+ assert_eq!(di["status"], "completed");
+ assert_eq!(di["summary"], "Brief");
+ assert_eq!(di["link"]["thread_id"], done_thread.as_str());
+ let ri = find(&v["finished"], &ok_run.id);
+ assert_eq!(ri["kind"], "routine_run");
+ assert_eq!(ri["title"], "Morning briefing");
+ assert_eq!(ri["summary"], "3 new orders, 1 refund.");
+ assert_eq!(ri["link"], json!({"thread_id": null, "channel_id": null, "direct_kwant_id": lead.id}));
+
+ // Failed, plus stuck (31 min) but not busy (29 min)
+ let failed_ids = ids(&v["failed"]);
+ for id in [&failed, &interrupted, &err_run.id, &stuck] {
+ assert!(failed_ids.contains(id), "{id} not failed: {failed_ids:?}");
+ }
+ assert!(!failed_ids.contains(&busy));
+ assert_eq!(failed_ids.len(), 4);
+ assert_eq!(find(&v["failed"], &stuck)["status"], "stuck");
+ assert_eq!(find(&v["failed"], &stuck)["link"]["thread_id"], stuck_thread.as_str());
+ assert_eq!(find(&v["failed"], &interrupted)["status"], "interrupted");
+ let fe = find(&v["failed"], &failed)["summary"].as_str().unwrap().to_string();
+ assert!(fe.starts_with("401 invalid key") && fe.contains("[redacted]"), "{fe}");
+ assert_eq!(find(&v["failed"], &err_run.id)["status"], "error");
+ for list in ["waiting", "finished", "failed"] {
+ assert_newest_first(&v[list]);
+ }
+ assert_eq!(v["unseen"], json!({"waiting": 2, "finished": 3, "failed": 4, "total": 9}));
+ assert_eq!(v["stuck_after_minutes"], 30);
+
+ // An explicit since narrows finished and failed, but not waiting or stuck
+ let v = get(&app, &format!("/api/away?since={}", rfc(now - Duration::days(1)))).await;
+ assert_eq!(ids(&v["finished"]), vec![ok_run.id.clone(), done.clone()]);
+ assert_eq!(v["waiting"].as_array().unwrap().len(), 2);
+ let v = get(&app, &format!("/api/away?since={}", rfc(now + Duration::minutes(5)))).await;
+ assert_eq!(v["finished"], json!([]));
+ assert_eq!(ids(&v["failed"]), vec![stuck.clone()]);
+ let v = get(&app, &format!("/api/away?since={}", rfc(now - Duration::days(9)).replace('+', "%2B"))).await;
+ assert!(ids(&v["finished"]).contains(&old));
+ // The badge still counts from the default window, whatever since asked for
+ assert_eq!(v["unseen"]["finished"], 3);
+ for bad in ["yesterday", "2026-10-17", "2026-13-01T00:00:00Z"] {
+ let (s, e) = call(&app, "GET", &format!("/api/away?since={bad}"), &[]).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{bad}");
+ assert!(e["error"].as_str().unwrap().contains("RFC 3339"));
+ }
+
+ // Seen: the marker becomes the default since and the badge resets (waiting and stuck remain)
+ let (s, seen) = call(&app, "POST", "/api/away/seen", &[]).await;
+ assert_eq!(s, StatusCode::OK);
+ let v = get(&app, "/api/away").await;
+ assert_eq!(v["last_seen"], seen["last_seen"]);
+ assert_eq!(v["since"], seen["last_seen"]);
+ assert_eq!(v["finished"], json!([]));
+ assert_eq!(v["unseen"], json!({"waiting": 2, "finished": 0, "failed": 1, "total": 3}));
+ // Not a settings key, and not writable through /api/settings
+ let (s, _) = call(&app, "GET", "/api/settings", &[]).await;
+ assert_eq!(s, StatusCode::OK);
+ let resp = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/api/settings")
+ .header("content-type", "application/json")
+ .body(Body::from(json!({"away_last_seen": "2000-01-01T00:00:00Z"}).to_string()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+ assert_eq!(get(&app, "/api/away").await["last_seen"], seen["last_seen"]);
+
+ // Something finishing after the marker shows up again
+ let (fresh, _) = delegation(&state, &lead.id, &spec.id, "Fresh", "completed", Some("new")).await;
+ let v = get(&app, "/api/away").await;
+ assert_eq!(ids(&v["finished"]), vec![fresh]);
+ assert_eq!(v["unseen"]["finished"], 1);
+
+ // Same auth as the rest of the API
+ for (method, uri) in [("GET", "/api/away"), ("POST", "/api/away/seen")] {
+ let (s, _) = call(&app, method, uri, &[("host", "kwnt.example.com")]).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{method} {uri}");
+ }
+}
+
+#[tokio::test]
+async fn away_lists_are_capped_at_50_newest_first() {
+ let (app, state, _tmp) = setup().await;
+ let kwants = state.db.list_kwants().await.unwrap();
+ let (lead, spec) = (&kwants[0].id, &kwants[1].id);
+ let now = Utc::now();
+ let mut done = Vec::new();
+ let mut failed = Vec::new();
+ for i in 0..60 {
+ let (d, _) = delegation(&state, lead, spec, &format!("done {i}"), "completed", Some("ok")).await;
+ set_time(&state, "delegations", "ended_at", &d, now - Duration::minutes(60 - i)).await;
+ done.push(d);
+ let (f, _) = delegation(&state, lead, spec, &format!("failed {i}"), "failed", Some("boom")).await;
+ set_time(&state, "delegations", "ended_at", &f, now - Duration::minutes(60 - i)).await;
+ failed.push(f);
+ }
+ let v = get(&app, "/api/away").await;
+ let newest = |all: &[String]| all.iter().rev().take(50).cloned().collect::<Vec<_>>();
+ assert_eq!(ids(&v["finished"]), newest(&done));
+ assert_eq!(ids(&v["failed"]), newest(&failed));
+ // The badge counts everything, not just what fits
+ assert_eq!(v["unseen"]["finished"], 60);
+ assert_eq!(v["unseen"]["failed"], 60);
+}