Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
0.9.5 B: Inbox "Done while you were away" backend (answer, trail, why, team jobs) (#543)
Oleksandr Ivanchenko8c2c52ba428a
diff --git a/src/db/away.rs b/src/db/away.rsindex 4355b41f..3447fe6c 100644--- a/src/db/away.rs+++ b/src/db/away.rs@@ -3,6 +3,8 @@//! routine runs). Read-only apart from the user's last-seen marker.use super::spaces::SpaceId;+use super::models::Message;+use super::threads::Delegation;use super::{Database, DbError};use chrono::{DateTime, Utc};use sqlx::FromRow;@@ -83,6 +85,9 @@ impl Database {"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",+ // 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",] {sqlx::query(stmt).execute(&self.pool).await?;}@@ -204,6 +209,146 @@ impl Database {}}+/// A lead's reply that ended with `Done: …` (0.9.5 B team jobs). `meta` holds `chain_done`.+#[derive(Debug, Clone, FromRow)]+pub struct DoneReplyRow {+ pub id: String,+ pub channel_id: Option<String>,+ pub direct_kwant_id: Option<String>,+ pub thread_id: Option<String>,+ pub sender_id: String,+ pub text: String,+ pub meta: Option<String>,+ pub created_at: DateTime<Utc>,+}++/// `?1` = since. The partial index `messages_chain_done` matches this filter exactly.+const DONE_REPLIES: &str = "+ SELECT id, channel_id, direct_kwant_id, thread_id, sender_id, text, meta, created_at+ FROM messages+ WHERE instr(meta, '\"chain_done\"') > 0 AND created_at > ?1 AND sender_role = 'kwant'";++/// The kinds of chat a message belongs to; each column has its partial index+/// (`messages_by_channel`, `messages_by_direct`, `messages_by_thread`) on `(col, created_at)`.+const CHAT_COLUMNS: [&str; 3] = ["channel_id", "direct_kwant_id", "thread_id"];++const ROUTINE_RUN_RESULT: &str =+ "SELECT r.message_id, rt.instructions, r.routine_id, r.trigger FROM routine_runs r JOIN routines rt ON rt.id = r.routine_id WHERE r.id = ?";++/// `?` = chat id, at.+fn person_before_sql(col: &str) -> String {+ format!("SELECT * FROM messages WHERE {col} = ? AND created_at <= ? AND sender_role = 'user' ORDER BY created_at DESC, rowid DESC LIMIT 1")+}++/// `?` = chat id, bot name, from, to.+fn task_reply_after_sql(col: &str) -> String {+ format!(+ "SELECT * FROM messages WHERE {col} = ? AND sender_role = 'kwant' AND sender_id = ? AND created_at >= ? AND created_at <= ? \+ ORDER BY created_at, rowid LIMIT 1"+ )+}++/// `?` = chat id, bot name, before.+fn task_reply_before_sql(col: &str) -> String {+ format!(+ "SELECT * FROM messages WHERE {col} = ? AND sender_role = 'kwant' AND sender_id = ? AND created_at < ? \+ ORDER BY created_at DESC, rowid DESC LIMIT 1"+ )+}++/// `?` = lead, from, to. `delegations_by_lead` is on `(lead_kwant_id, created_at)`.+const LEAD_DELEGATIONS: &str =+ "SELECT * FROM delegations WHERE lead_kwant_id = ? AND created_at >= ? AND created_at <= ? ORDER BY created_at DESC, rowid DESC LIMIT 100";++impl Database {+ /// The hand-offs `lead` made between `from` and `to` (at most 100, newest first): a team+ /// job's members.+ pub async fn lead_delegations(&self, lead: &str, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<Vec<Delegation>, DbError> {+ Ok(sqlx::query_as(LEAD_DELEGATIONS).bind(lead).bind(from).bind(to).fetch_all(&self.pool).await?)+ }++ /// Lead replies that ended with `Done: …` after `since`, newest first (any space: the caller+ /// keeps the ones whose lead is in its space).+ pub async fn done_replies(&self, since: DateTime<Utc>, limit: i64) -> Result<Vec<DoneReplyRow>, DbError> {+ Ok(sqlx::query_as(&format!("{DONE_REPLIES} ORDER BY created_at DESC, rowid DESC LIMIT ?2"))+ .bind(since)+ .bind(limit)+ .fetch_all(&self.pool)+ .await?)+ }++ /// A routine run's result message, its routine's instructions, the routine's id and what+ /// started the run (`schedule`, `manual`, `event`).+ pub async fn routine_run_result(&self, run_id: &str) -> Result<Option<(Option<String>, String, String, String)>, DbError> {+ Ok(sqlx::query_as(ROUTINE_RUN_RESULT)+ .bind(run_id)+ .fetch_optional(&self.pool)+ .await?)+ }++ /// The kwant called `name` in `space` (a reply's `sender_id` is its kwant's name).+ pub async fn kwant_id_named(&self, name: &str, space: &SpaceId) -> Result<Option<String>, DbError> {+ Ok(sqlx::query_scalar(+ "SELECT id FROM kwants WHERE name = ? AND COALESCE(space_id, 'spc_default') = ? ORDER BY created_at, rowid LIMIT 1",+ )+ .bind(name)+ .bind(space.as_str())+ .fetch_optional(&self.pool)+ .await?)+ }++ /// The person's last message in a chat (channel, direct chat or thread) at or before `at`:+ /// where the request a lead's `Done:` closes started.+ pub async fn last_person_message_before(&self, context: &str, at: DateTime<Utc>) -> Result<Option<Message>, DbError> {+ // One indexed lookup per kind of chat; a context id is only ever one of them+ for col in CHAT_COLUMNS {+ let row = sqlx::query_as::<_, Message>(&person_before_sql(col))+ .bind(context)+ .bind(at)+ .fetch_optional(&self.pool)+ .await?;+ if row.is_some() {+ return Ok(row);+ }+ }+ Ok(None)+ }++ /// The bot's reply that holds a task's result: its first reply in the task's chat from+ /// `review_at` (the hand-in is a tool call, the reply lands when the turn ends) within+ /// `slack`, else its last one before.+ pub async fn task_result_message(+ &self,+ context: &str,+ bot_name: &str,+ review_at: DateTime<Utc>,+ slack: chrono::Duration,+ ) -> Result<Option<Message>, DbError> {+ for col in ["thread_id", "channel_id", "direct_kwant_id"] {+ let after = sqlx::query_as::<_, Message>(&task_reply_after_sql(col))+ .bind(context)+ .bind(bot_name)+ .bind(review_at)+ .bind(review_at + slack)+ .fetch_optional(&self.pool)+ .await?;+ if after.is_some() {+ return Ok(after);+ }+ let before = sqlx::query_as::<_, Message>(&task_reply_before_sql(col))+ .bind(context)+ .bind(bot_name)+ .bind(review_at)+ .fetch_optional(&self.pool)+ .await?;+ if before.is_some() {+ return Ok(before);+ }+ }+ Ok(None)+ }+}+/// 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)));@@ -245,5 +390,57 @@ mod tests {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:?}");}+ // Team jobs (0.9.5 B): two parameters, no space+ let rows: Vec<(i64, i64, i64, String)> = sqlx::query_as(&format!("EXPLAIN QUERY PLAN {DONE_REPLIES} ORDER BY created_at DESC LIMIT ?2"))+ .bind(Utc::now())+ .bind(50)+ .fetch_all(&db.pool)+ .await+ .unwrap();+ let detail: Vec<String> = rows.into_iter().map(|r| r.3).collect();+ assert!(!detail.iter().any(|d| d.starts_with("SCAN")), "full scan: {detail:?}");+ assert!(detail.iter().any(|d| d.contains("messages_chain_done")), "messages_chain_done unused: {detail:?}");+ }++ /// The plan with every `?` bound (to a string: the plan doesn't depend on the value).+ async fn plan_of(db: &Database, sql: &str) -> Vec<String> {+ let params = sql.matches('?').count();+ let explain = format!("EXPLAIN QUERY PLAN {sql}");+ let mut q = sqlx::query_as::<_, (i64, i64, i64, String)>(&explain);+ for _ in 0..params {+ q = q.bind("x");+ }+ q.fetch_all(&db.pool).await.unwrap().into_iter().map(|r| r.3).collect()+ }++ /// The per-item lookups behind the Inbox's done items (0.9.5 B) reach messages,+ /// turn_tool_calls and the rest through an index or a primary key, never by a full scan.+ #[tokio::test]+ async fn inbox_done_lookups_use_indexes() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let index_of = |col: &str| match col {+ "channel_id" => "messages_by_channel",+ "direct_kwant_id" => "messages_by_direct",+ _ => "messages_by_thread",+ };+ let mut cases: Vec<(String, &str)> = vec![+ (ROUTINE_RUN_RESULT.to_string(), "sqlite_autoindex_routine_runs_1"),+ (format!("{DONE_REPLIES} ORDER BY created_at DESC, rowid DESC LIMIT ?2"), "messages_chain_done"),+ // tool_calls_of (db/checkpoints.rs)+ ("SELECT * FROM turn_tool_calls WHERE task_id = ? ORDER BY id".to_string(), "turn_tool_calls_task"),+ (LEAD_DELEGATIONS.to_string(), "delegations_by_lead"),+ ];+ for col in CHAT_COLUMNS {+ cases.push((person_before_sql(col), index_of(col)));+ cases.push((task_reply_after_sql(col), index_of(col)));+ cases.push((task_reply_before_sql(col), index_of(col)));+ }+ for (sql, idx) in cases {+ let detail = plan_of(&db, &sql).await;+ println!("{idx}: {}", detail.join(" | "));+ 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:?}\n{sql}");+ }}}diff --git a/src/server/inbox.rs b/src/server/inbox.rsindex 2d7f6cc3..da953857 100644--- a/src/server/inbox.rs+++ b/src/server/inbox.rs@@ -17,9 +17,14 @@//! live status without a verdict, then one row per must_not_change entry from `scope_status`.//! Acceptance lines as `not_checked` are only the fallback for a task with no stored contract.//!-//! `POST /api/away/seen` only moves the marker for finished and failed items: review items stay-//! listed until they are approved, sent back or rolled back.-+//! `POST /api/away/seen` only moves the marker: every item carries `unread` (newer than the+//! marker), and the badge counts unread ones as `GET /api/away` does: team jobs carry `unread`+//! but are not in the badge, so it matches `/api/away`. Since 0.9.5 B, finished and failed items stay+//! listed for 7 days whether seen or not; review items stay until they are approved, sent back+//! or rolled back. Done items (finished, failed, to review) and team jobs carry the answer, the+//! trail and the why ([`super::inbox_done`]).++use super::inbox_done;use super::away::{self, item, last_seen, rfc3339, waiting_approvals, DEFAULT_LOOKBACK_DAYS, MAX_ITEMS, STUCK_AFTER_MINUTES};use super::missions::contract::{self, Contract};use super::spaces::Scope;@@ -536,6 +541,7 @@ fn watch_item(mut v: Value, last_seen: Option<DateTime<Utc>>) -> Value {let id = v["id"].as_str().unwrap_or("").to_string();v["group"] = json!(Group::WaitingOnYou.key());v["sort_key"] = sort_key(Group::WaitingOnYou, None, at_ms, unread, &name, &id);+ v["unread"] = json!(unread);v}@@ -693,6 +699,7 @@ fn away_item(row: crate::db::away::AwayRow, group: Group, last_seen: Option<Datelet id = v["id"].as_str().unwrap_or("").to_string();v["group"] = json!(group.key());v["sort_key"] = sort_key(group, None, at.timestamp_millis(), unread, &name, &id);+ v["unread"] = json!(unread);v}@@ -779,8 +786,10 @@ pub struct InboxQuery {pub since: Option<String>,}-/// `GET /api/inbox?since=<RFC 3339>&space=`: `since` defaults to the last-seen marker, else 7-/// days ago, as on `GET /api/away`; it only bounds finished and failed items.+/// `GET /api/inbox?since=<RFC 3339>&space=`: `since` bounds finished and failed items and team+/// jobs. It defaults to 7 days ago, and an older one is cut to that ([`inbox_done::done_since`]):+/// done items stay for 7 days, seen or not. The badge still counts what is newer than the+/// last-seen marker, as on `GET /api/away`; unread team jobs are not counted.pub async fn get(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<InboxQuery>) -> Response {let now = Utc::now();let Ok(seen) = last_seen(&state, &space).await else {@@ -788,9 +797,9 @@ pub async fn get(State(state): State<AppState>, Scope(space): Scope, Query(q): Q};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,+ None => inbox_done::done_since(now, None),Some(s) => match DateTime::parse_from_rfc3339(s) {- Ok(t) => t.with_timezone(&Utc),+ Ok(t) => inbox_done::done_since(now, Some(t.with_timezone(&Utc))),Err(_) => {let msg = "since must be an RFC 3339 time, e.g. 2026-10-17T09:00:00Z";return (StatusCode::BAD_REQUEST, Json(json!({ "error": msg }))).into_response();@@ -810,10 +819,24 @@ pub async fn get(State(state): State<AppState>, Scope(space): Scope, Query(q): Qlet prepush = state.db.prepush_cards(space.as_str(), 50).await?;let prepush_needs_you = prepush.iter().filter(|c| (c.status == BLOCKED || c.status == PREPUSH_FAILED) && c.tries >= NEEDS_YOU_TRIES).count() as i64;let reviews = gather(&state, &space).await?;- Ok::<_, DbError>((waiting, finished, failed, waiting_count + unseen_finished + unseen_failed, prepush_needs_you, reviews))+ let team_jobs = inbox_done::team_jobs(&state, &space, since, seen).await?;+ // The same sum as `/api/away`'s `unseen.total` (`away::unread_total`): team jobs carry+ // `unread` in the list but are not counted, so the two badges agree.+ let unseen = waiting_count + unseen_finished + unseen_failed;+ // The answer, trail and why of each done item+ let mut done = Vec::with_capacity(finished.len() + failed.len());+ for (row, group) in failed.into_iter().map(|r| (r, Group::FailedOrStuck)).chain(finished.into_iter().map(|r| (r, Group::Finished))) {+ let facts = inbox_done::away_facts(&state, &row.kind, &row.id).await?;+ done.push((row, group, facts));+ }+ let mut review_facts = Vec::with_capacity(reviews.len());+ for r in &reviews {+ review_facts.push(inbox_done::task_facts(&state, &r.task, &r.kwant_name, r.in_review_since).await?);+ }+ Ok::<_, DbError>((waiting, done, unseen, prepush_needs_you, reviews, review_facts, team_jobs))}.await;- let Ok((waiting, finished, failed, unseen_total, prepush_needs_you, reviews)) = result else {+ let Ok((waiting, done, unseen_total, prepush_needs_you, reviews, review_facts, team_jobs)) = result else {return StatusCode::INTERNAL_SERVER_ERROR.into_response();};// What a mission watcher left for the person (P1), listed and counted as on /api/away@@ -829,9 +852,28 @@ pub async fn get(State(state): State<AppState>, Scope(space): Scope, Query(q): Qitems.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(connections.into_iter().map(|(at, v)| connection_item(at, &v, seen)));- items.extend(failed.into_iter().map(|r| away_item(r, Group::FailedOrStuck, seen)));- items.extend(finished.into_iter().map(|r| away_item(r, Group::Finished, seen)));- items.extend(reviews.iter().filter_map(|r| review_item(r, seen)).map(|(v, _)| v));+ // 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+ // in `title` when there is none (every screen prints `title`).+ for v in items.iter_mut().filter(|v| v["kind"] == "approval") {+ if let Some(q) = inbox_done::approval_question(&v["details"]) {+ v["title"] = json!(q);+ v["question"] = json!(q);+ }+ }+ 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);+ }+ 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));+ items.push(v);+ }+ }+ items.extend(team_jobs);Json(response(items, unseen_total, prepush_needs_you, since, seen, now)).into_response()}diff --git a/src/server/inbox_done.rs b/src/server/inbox_done.rsnew file mode 100644index 00000000..05c32005--- /dev/null+++ b/src/server/inbox_done.rs@@ -0,0 +1,695 @@+//! 0.9.5 B: Inbox "Done while you were away" (release-095/inbox-away/brief-b.md, Mira's+//! ux-audit-090 §1). What `GET /api/inbox` adds to each done item (finished, failed, to review):+//!+//! - `result_message_id`, `result_conversation_id` and `result_link`: the message that holds the+//! answer. A routine run's is `routine_runs.message_id`, a hand-off's the delegation's result,+//! a task's the routine run or hand-off it came from, else the owner's reply at the hand-in;+//! a team job's is the lead's `Done:` reply.+//! - `answer_excerpt`: that message as plain text, at most [`EXCERPT_CHARS`], secrets masked.+//! - `trail` (`trail_dropped`): up to [`TRAIL_MAX`] `{at, kind, label, detail, status, by}`+//! steps from the message's saved `meta.activity` (the activity store; no second one). `kind`+//! is `page` (opened or read a web page), `message` (sent something to a person or a place+//! outside this chat, from the fixed [`MESSAGE_TOOLS`] list), `write` (anything else that may+//! have changed something) or `tool` (read only).+//! - `why` (`why_kind`): the routine's instruction, or the task's, hand-off's or request's first+//! line, at most [`WHY_CHARS`].+//! - `changed` (Iris's name, part F) and `changed_nothing`: whether the job wrote anything.+//! A task's side-effect ledger (`turn_tool_calls`) decides when it has rows; otherwise the trail+//! does, with the ledger's rule that only reading tools change nothing. `null` when neither+//! is known, and then the UI draws no "Read only" chip.+//! - `unread`: newer than the last-seen marker. `POST /api/away/seen` only clears this now; done+//! items stay listed for [`DONE_DAYS`] days.+//!+//! A lead's reply that ended with `Done: …` (keep_going's `chain_done` meta) is a done item of+//! kind `team_job`, with the lead, the members it handed work to for that request, and the fields+//! above.++use super::away::{self, rfc3339, DEFAULT_LOOKBACK_DAYS, MAX_ITEMS};+use super::inbox::{sort_key, Group};+use super::keep_going::DONE_KEY;+use super::AppState;+use crate::db::away::DoneReplyRow;+use crate::db::missions::Task;+use crate::db::models::Message;+use crate::db::spaces::SpaceId;+use crate::db::DbError;+use crate::server::missions::checkpoints::NO_EFFECT_TOOLS;+use chrono::{DateTime, Duration, Utc};+use serde_json::{json, Value};++/// Done items stay this many days, seen or not.+pub const DONE_DAYS: i64 = DEFAULT_LOOKBACK_DAYS;+pub const EXCERPT_CHARS: usize = 600;+pub const WHY_CHARS: usize = 300;+pub const TRAIL_MAX: usize = 30;+const TITLE_CHARS: usize = 120;+/// How long after a task's hand-in its owner's reply still counts as the result.+const REPLY_SLACK_MINUTES: i64 = 30;++/// The oldest a finished or failed item may be: 7 days back, or a later `since` the caller asked for.+pub fn done_since(now: DateTime<Utc>, requested: Option<DateTime<Utc>>) -> DateTime<Utc> {+ let floor = now - Duration::days(DONE_DAYS);+ requested.map_or(floor, |r| r.max(floor))+}++fn cut(text: &str, max: usize) -> String {+ match text.char_indices().nth(max - 1) {+ Some((at, _)) if text.chars().count() > max => format!("{}…", text[..at].trim_end()),+ _ => text.to_string(),+ }+}++/// One line of markdown as plain text: heading, quote and list markers, emphasis and code ticks gone.+fn plain_line(line: &str) -> String {+ let l = line.trim();+ let l = l.trim_start_matches(['#', '>']).trim_start();+ let l = match l.strip_prefix("- ").or_else(|| l.strip_prefix("* ")) {+ Some(rest) => rest,+ None => l,+ };+ l.replace("**", "").replace("__", "").replace('`', "")+}++/// The answer as plain text, at most [`EXCERPT_CHARS`], with secrets masked line by line; code+/// blocks dropped and runs of blank lines folded. `None` when there is no text.+pub fn excerpt(text: &str) -> Option<String> {+ let mut lines: Vec<String> = Vec::new();+ let mut in_code = false;+ for raw in text.lines() {+ if raw.trim_start().starts_with("```") {+ in_code = !in_code;+ continue;+ }+ if in_code {+ continue;+ }+ let line = away::mask_words(&plain_line(raw));+ if line.is_empty() && lines.last().is_none_or(|l| l.is_empty()) {+ continue;+ }+ lines.push(line);+ }+ while lines.last().is_some_and(|l| l.is_empty()) {+ lines.pop();+ }+ let joined = lines.join("\n");+ (!joined.is_empty()).then(|| cut(&joined, EXCERPT_CHARS))+}++/// A routine's instruction (all of it, lines kept) or a task's first line, masked, at most [`WHY_CHARS`].+pub fn why_of(text: &str, whole: bool) -> Option<String> {+ let text = match whole {+ true => text.lines().map(|l| away::mask_words(l.trim())).collect::<Vec<_>>().join("\n").trim().to_string(),+ false => text.lines().map(plain_line).find(|l| !l.trim().is_empty()).map(|l| away::mask_words(&l)).unwrap_or_default(),+ };+ (!text.is_empty()).then(|| cut(&text, WHY_CHARS))+}++/// A tool's own name without kwnt's `mcp__kwnt__` prefix; other servers keep theirs.+fn own_tool(tool: &str) -> &str {+ tool.strip_prefix("mcp__kwnt__").or_else(|| tool.strip_prefix("mcp__kwant__")).unwrap_or(tool)+}++/// Tools that open or read a web page: a trail step of kind `page`.+const PAGE_TOOLS: [&str; 12] = [+ "WebFetch",+ "webfetch",+ "web_fetch",+ "fetch",+ "browser_open",+ "browser_navigate",+ "navigate",+ "open_url",+ "browser_page",+ "browser_snapshot",+ "browser_read",+ "browser_screenshot",+];++/// Reading tools beyond the ledger's [`NO_EFFECT_TOOLS`]: opening and reading pages, kwnt's own+/// task tools, asking the person. Anything else (a command, a file write, another server's tool,+/// clicking in the browser) may change something.+const READ_TOOLS: [&str; 6] = ["browser_cite", "web_search", "websearch", "ask_user", "mission_plan", "update_plan"];++fn is_page(tool: &str) -> bool {+ PAGE_TOOLS.contains(&own_tool(tool))+}++/// Tools that send something to a person or a place outside this chat: a trail step of kind+/// `message`, which counts as a change. Matched without case on the tool's own name (the part+/// after the last `__`, so `mcp__gmail__send_email` and Composio's `GMAIL_SEND_EMAIL` both match).+/// A fixed list: any other tool that may change something stays `write`.+const MESSAGE_TOOLS: [&str; 26] = [+ "send_email",+ "send_mail",+ "sendmail",+ "reply_to_email",+ "gmail_send_email",+ "gmail_reply_to_thread",+ "outlook_send_email",+ // Slack+ "slack_post_message",+ "slack_send_message",+ "slack_sends_a_message_to_a_slack_channel",+ "chat_postmessage",+ // Discord+ "discord_send_message",+ "discordbot_create_message",+ // Telegram+ "telegram_send_message",+ "send_telegram_message",+ // X+ "post_tweet",+ "create_tweet",+ "twitter_creation_of_a_post",+ "twitter_create_post",+ "x_create_post",+ "x_post",+ // kwnt's own send and post tools+ "send_message",+ "post_message",+ "post_to_room",+ "message_person",+ "send_voice_note",+];++/// Whether a tool sends a message outside this chat ([`MESSAGE_TOOLS`]).+pub fn is_message(tool: &str) -> bool {+ let own = own_tool(tool);+ let name = own.rsplit("__").next().unwrap_or(own);+ MESSAGE_TOOLS.iter().any(|m| m.eq_ignore_ascii_case(name))+}++/// Whether a saved activity step may have changed something.+pub fn step_changes(step: &Value) -> bool {+ match step["kind"].as_str() {+ Some("tool") | Some("approval") => {}+ // thinking, notes and human steps run no tool+ _ => return false,+ }+ // A tool that never ran (declined, stopped before it started) changed nothing+ if matches!(step["status"].as_str(), Some("declined")) {+ return false;+ }+ let Some(tool) = step["tool"].as_str() else {+ return true;+ };+ let own = own_tool(tool);+ let kwnt_own = own.len() != tool.len();+ !(NO_EFFECT_TOOLS.contains(&own) || is_page(tool) || READ_TOOLS.contains(&own) || (kwnt_own && own.starts_with("task_")))+}++fn activity_steps(meta: &Value) -> (Vec<Value>, i64) {+ let a = &meta["activity"];+ let steps = a["steps"].as_array().cloned().unwrap_or_default();+ (steps, a["dropped"].as_i64().unwrap_or(0))+}++/// A message's meta as JSON (`Null` when it has none or it doesn't parse).+pub fn meta_of(m: &Message) -> Value {+ m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null)+}++/// A step's status in Iris's three words: `failed` is `error`; a step that never ran or never+/// finished (declined, stopped, still running or waiting when the reply was saved) is `skipped`.+fn trail_status(status: Option<&str>) -> &'static str {+ match status {+ Some("failed") => "error",+ Some("declined" | "stopped" | "running" | "waiting") => "skipped",+ _ => "ok",+ }+}++/// One message's steps as trail rows: tools, approvals and human steps (thinking and notes left+/// out), with who did them when it isn't the item's own bot. Already redacted when saved.+pub fn trail_rows(meta: &Value, by: Option<&str>) -> (Vec<Value>, i64) {+ let (steps, dropped) = activity_steps(meta);+ let rows = steps+ .iter()+ .filter(|s| matches!(s["kind"].as_str(), Some("tool" | "approval" | "human_step")))+ .map(|s| {+ let kind = match s["tool"].as_str() {+ Some(t) if is_page(t) => "page",+ Some(t) if is_message(t) && step_changes(s) => "message",+ _ if step_changes(s) => "write",+ _ => "tool",+ };+ json!({+ "at": s["started_at"],+ "kind": kind,+ "label": s["title"].as_str().map(away::mask_words).unwrap_or_default(),+ "detail": s["detail"].as_str().map(away::mask_words),+ "status": trail_status(s["status"].as_str()),+ "by": by,+ })+ })+ .collect();+ (rows, dropped)+}++/// Whether the steps saved on these messages changed anything; `None` with no message at all.+pub fn trail_changed(metas: &[Value]) -> Option<bool> {+ if metas.is_empty() {+ return None;+ }+ Some(metas.iter().any(|m| activity_steps(m).0.iter().any(step_changes)))+}++/// What a done item's fields come from.+#[derive(Debug, Default)]+pub struct DoneFacts {+ pub message: Option<Message>,+ pub why: Option<String>,+ /// `routine`, `task`, `ask` (a hand-off) or `request` (the person's message a team job answered).+ pub why_kind: Option<&'static str>,+ /// The task's side-effect ledger: `Some(true)` when a call that wasn't denied had an effect.+ pub ledger_changed: Option<bool>,+ /// Further result messages whose steps join the trail (a team job's members), with who.+ pub more: Vec<(Message, String)>,+ /// What the item came from (Iris's `source`): `{kind: "routine", routine_id, run_id, trigger}`,+ /// `{kind: "task", task_id}`, `{kind: "delegation", delegation_id}` or+ /// `{kind: "team_job", delegation_id}`; `null` when unknown.+ pub source: Value,+}++/// The ledger's answer, else the trail's.+pub fn changed(ledger: Option<bool>, trail: Option<bool>) -> Option<bool> {+ match (ledger, trail) {+ (Some(true), _) | (_, Some(true)) => Some(true),+ (Some(false), _) | (_, Some(false)) => Some(false),+ _ => None,+ }+}++fn link_of(m: &Message) -> Value {+ json!({"thread_id": m.thread_id, "channel_id": m.channel_id, "direct_kwant_id": m.direct_kwant_id})+}++fn context_of(m: &Message) -> Option<&str> {+ m.thread_id.as_deref().or(m.channel_id.as_deref()).or(m.direct_kwant_id.as_deref())+}++/// Adds the done fields and `unread` to an item.+pub fn apply(v: &mut Value, f: &DoneFacts, unread: bool) {+ let m = f.message.as_ref();+ let mut metas: Vec<Value> = m.map(meta_of).into_iter().collect();+ let (mut trail, mut dropped) = m.map(|m| trail_rows(&meta_of(m), None)).unwrap_or_default();+ for (msg, by) in &f.more {+ let meta = meta_of(msg);+ let (rows, d) = trail_rows(&meta, Some(by));+ trail.extend(rows);+ dropped += d;+ metas.push(meta);+ }+ trail.sort_by(|a, b| a["at"].as_str().unwrap_or("").cmp(b["at"].as_str().unwrap_or("")));+ if trail.len() > TRAIL_MAX {+ // The last steps: the ones that led to the answer+ dropped += (trail.len() - TRAIL_MAX) as i64;+ trail.drain(..trail.len() - TRAIL_MAX);+ }+ let changed = changed(f.ledger_changed, trail_changed(&metas));+ v["unread"] = json!(unread);+ v["result_message_id"] = json!(m.map(|m| m.id.clone()));+ v["result_conversation_id"] = json!(m.and_then(context_of));+ v["result_thread_id"] = json!(m.and_then(|m| m.thread_id.clone()));+ v["result_link"] = m.map(link_of).unwrap_or(Value::Null);+ v["source"] = f.source.clone();+ v["answer_excerpt"] = json!(m.and_then(|m| excerpt(&m.text)));+ v["trail"] = json!(trail);+ v["trail_dropped"] = json!(dropped);+ v["why"] = json!(f.why);+ v["why_kind"] = json!(f.why_kind);+ v["changed"] = json!(changed);+ v["changed_nothing"] = json!(changed.map(|c| !c));+}++async fn message(state: &AppState, id: Option<&str>) -> Result<Option<Message>, DbError> {+ match id {+ Some(id) => state.db.get_message(id).await,+ None => Ok(None),+ }+}++/// A routine run's result and instruction.+async fn routine_facts(state: &AppState, run_id: &str) -> Result<DoneFacts, DbError> {+ let Some((message_id, instructions, routine_id, trigger)) = state.db.routine_run_result(run_id).await? else {+ return Ok(DoneFacts::default());+ };+ Ok(DoneFacts {+ message: message(state, message_id.as_deref()).await?,+ why: why_of(&instructions, true),+ why_kind: Some("routine"),+ source: json!({"kind": "routine", "routine_id": routine_id, "run_id": run_id, "trigger": trigger}),+ ..Default::default()+ })+}++/// A hand-off's result and its ask.+async fn delegation_facts(state: &AppState, id: &str) -> Result<DoneFacts, DbError> {+ let Some(d) = state.db.get_delegation(id).await? else {+ return Ok(DoneFacts::default());+ };+ Ok(DoneFacts {+ message: message(state, d.result_message_id.as_deref()).await?,+ why: why_of(&d.task, false),+ why_kind: Some("ask"),+ source: json!({"kind": "delegation", "delegation_id": d.id}),+ ..Default::default()+ })+}++/// A finished or failed away item (`delegation` or `routine_run`).+pub async fn away_facts(state: &AppState, kind: &str, id: &str) -> Result<DoneFacts, DbError> {+ match kind {+ "routine_run" => routine_facts(state, id).await,+ "delegation" => delegation_facts(state, id).await,+ _ => Ok(DoneFacts::default()),+ }+}++/// Whether the task's ledger saw a call with an effect go through; `None` with no rows.+async fn ledger_changed(state: &AppState, task_id: &str) -> Result<Option<bool>, DbError> {+ let calls = state.db.tool_calls_of(task_id).await?;+ if calls.is_empty() {+ return Ok(None);+ }+ Ok(Some(calls.iter().any(|c| c.effect != "none" && c.decision != "denied")))+}++/// A task in review: the routine run or hand-off it came from, else its owner's reply at the hand-in.+pub async fn task_facts(state: &AppState, task: &Task, owner_name: &str, in_review_since: DateTime<Utc>) -> Result<DoneFacts, DbError> {+ let mut f = match (task.source_kind.as_str(), task.source_id.as_deref()) {+ ("routine", Some(run)) => routine_facts(state, run).await?,+ ("delegation", Some(d)) => delegation_facts(state, d).await?,+ _ => DoneFacts::default(),+ };+ if f.message.is_none() {+ let context = task.thread_id.as_deref().or(task.channel_id.as_deref()).or(task.direct_kwant_id.as_deref());+ if let Some(c) = context {+ f.message = state.db.task_result_message(c, owner_name, in_review_since, Duration::minutes(REPLY_SLACK_MINUTES)).await?;+ }+ }+ if f.why.is_none() {+ f.why = why_of(&task.acceptance, false).or_else(|| why_of(&task.title, false));+ f.why_kind = f.why.as_ref().map(|_| "task");+ }+ f.ledger_changed = ledger_changed(state, &task.id).await?;+ // A review links to its own task; the routine run it came from is still exact (`run_id`)+ f.source = match f.source.take() {+ Value::Object(mut o) if o.get("kind") == Some(&json!("routine")) => {+ o.insert("task_id".into(), json!(task.id));+ Value::Object(o)+ }+ _ => json!({"kind": "task", "task_id": task.id}),+ };+ Ok(f)+}++/// The arguments an approval's question names, in this order.+const ASK_FACTS: [&str; 3] = ["subject", "title", "name"];++/// An approval's own question for its Inbox title, from what the call is about (its masked+/// arguments' subject, title or name): `Approve “Spring sale”?`. `None` when they name nothing;+/// the title stays the tool's (`Use gmail`).+pub fn approval_question(details: &Value) -> Option<String> {+ let args = details["arguments"].as_object().or_else(|| details["input"].as_object())?;+ let fact = ASK_FACTS.iter().find_map(|k| args.get(*k).and_then(Value::as_str).map(str::trim).filter(|v| !v.is_empty() && *v != "[redacted]"))?;+ let fact = away::mask_words(fact);+ Some(format!("Approve “{}”?", cut(&fact, TITLE_CHARS - 12)))+}++// ---- Team jobs ----++/// The lead of a `Done:` reply in `space`: the direct chat's bot, else the bot of that name.+async fn lead_of(state: &AppState, r: &DoneReplyRow, space: &SpaceId) -> Result<Option<crate::db::models::Kwant>, DbError> {+ // Replies name their bot (older ones carried its id)+ let id = match r.direct_kwant_id.as_deref() {+ Some(k) => k.to_string(),+ None => state.db.kwant_id_named(&r.sender_id, space).await?.unwrap_or_else(|| r.sender_id.clone()),+ };+ let Some(k) = state.db.get_kwant(&id).await? else { return Ok(None) };+ let of = state.db.space_of_kwant(&k.id).await?.unwrap_or_else(SpaceId::default_space);+ Ok(((k.name == r.sender_id || k.id == r.sender_id) && &of == space).then_some(k))+}++fn done_at(meta: &Value, fallback: DateTime<Utc>) -> DateTime<Utc> {+ meta[DONE_KEY]["at"]+ .as_str()+ .and_then(|t| DateTime::parse_from_rfc3339(t).ok())+ .map(|t| t.with_timezone(&Utc))+ .unwrap_or(fallback)+}++/// A message row with only the stored columns this module reads.+fn bare_message(id: &str, text: &str, meta: Option<String>) -> Message {+ Message {+ id: id.to_string(),+ channel_id: None,+ direct_kwant_id: None,+ sender_role: "kwant".into(),+ sender_id: String::new(),+ text: text.to_string(),+ reasoning_content: None,+ tool_calls: None,+ tokens_used: 0,+ created_at: None,+ thread_id: None,+ meta,+ results: None,+ reply_to_message_id: None,+ reaction: None,+ reply_to: None,+ }+}++fn as_message(r: &DoneReplyRow) -> Message {+ Message {+ channel_id: r.channel_id.clone(),+ direct_kwant_id: r.direct_kwant_id.clone(),+ sender_id: r.sender_id.clone(),+ created_at: Some(r.created_at),+ thread_id: r.thread_id.clone(),+ ..bare_message(&r.id, &r.text, r.meta.clone())+ }+}++/// The space's `Done:` replies since `since` that count as team jobs (their lead is in the+/// space), with the lead. Newest first, at most [`MAX_ITEMS`].+async fn done_replies(state: &AppState, space: &SpaceId, since: DateTime<Utc>) -> Result<Vec<(DoneReplyRow, crate::db::models::Kwant)>, DbError> {+ let mut out = Vec::new();+ for r in state.db.done_replies(since, MAX_ITEMS * 4).await? {+ let meta: Value = r.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null);+ if !meta[DONE_KEY].is_object() {+ continue;+ }+ if let Some(lead) = lead_of(state, &r, space).await? {+ out.push((r, lead));+ }+ if out.len() >= MAX_ITEMS as usize {+ break;+ }+ }+ Ok(out)+}++/// The space's team jobs since `since`, as finished inbox items.+pub async fn team_jobs(state: &AppState, space: &SpaceId, since: DateTime<Utc>, seen: Option<DateTime<Utc>>) -> Result<Vec<Value>, DbError> {+ let mut items = Vec::new();+ for (r, lead) in done_replies(state, space, since).await? {+ let msg = as_message(&r);+ let meta = meta_of(&msg);+ let at = done_at(&meta, r.created_at);+ let context = context_of(&msg).unwrap_or(&lead.id).to_string();+ let request = state.db.last_person_message_before(&context, r.created_at).await?;+ let from = request.as_ref().and_then(|m| m.created_at);+ // The hand-offs the lead made from this chat for this request (with no request found,+ // the 7 days before the `Done:`)+ let from = from.unwrap_or(r.created_at - Duration::days(DONE_DAYS));+ let handoffs: Vec<_> = state+ .db+ .lead_delegations(&lead.id, from, r.created_at)+ .await?+ .into_iter()+ .filter(|d| [&d.origin_thread_id, &d.origin_channel_id, &d.origin_kwant_id].iter().any(|o| o.as_deref() == Some(context.as_str())))+ .collect();+ let mut members: Vec<Value> = Vec::new();+ let mut more = Vec::new();+ for d in &handoffs {+ let name = state.db.get_kwant(&d.specialist_kwant_id).await?.map(|k| k.name).unwrap_or_else(|| "A bot".into());+ if !members.iter().any(|m| m["kwant_id"] == json!(d.specialist_kwant_id)) {+ members.push(json!({"kwant_id": d.specialist_kwant_id, "kwant_name": name}));+ }+ if let Some(m) = message(state, d.result_message_id.as_deref()).await? {+ more.push((m, name));+ }+ }+ let request_text = request.as_ref().map(|m| m.text.as_str()).unwrap_or("");+ let why = why_of(request_text, false);+ let done_text = meta[DONE_KEY]["text"].as_str().unwrap_or("").to_string();+ let title = why_of(request_text, false).map(|t| cut(&t, TITLE_CHARS)).unwrap_or_else(|| format!("Team job led by {}", lead.name));+ let unread = seen.is_none_or(|s| at > s);+ let mut v = json!({+ "kind": "team_job",+ "id": r.id,+ "kwant_id": lead.id,+ "kwant_name": lead.name,+ "title": title,+ "summary": away::summarize(&format!("Done: {done_text}")),+ "status": "completed",+ "timestamp": rfc3339(at),+ "link": link_of(&msg),+ "group": Group::Finished.key(),+ "sort_key": sort_key(Group::Finished, None, at.timestamp_millis(), unread, &lead.name, &r.id),+ "lead": {"kwant_id": lead.id, "kwant_name": lead.name},+ "members": members,+ "handoffs": handoffs.len(),+ "done_line": away::mask_words(&done_text),+ });+ let source = json!({"kind": "team_job", "delegation_id": handoffs.first().map(|d| d.id.clone())});+ let facts = DoneFacts { message: Some(msg), why: why.clone(), why_kind: why.as_ref().map(|_| "request"), ledger_changed: None, more, source };+ apply(&mut v, &facts, unread);+ items.push(v);+ }+ Ok(items)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn done_items_look_back_seven_days_whatever_was_seen() {+ let now = Utc::now();+ assert_eq!(done_since(now, None), now - Duration::days(7));+ // An older since is cut to the window; a later one narrows it+ assert_eq!(done_since(now, Some(now - Duration::days(30))), now - Duration::days(7));+ assert_eq!(done_since(now, Some(now - Duration::hours(1))), now - Duration::hours(1));+ }++ #[test]+ fn excerpts_are_plain_masked_and_short() {+ let e = excerpt("## Result\n\n\n**Site is up.** Key: sk-ant-api03-abcdefghijklmnop1234\n```\ncode\n```\n- `200` on /\n").unwrap();+ assert_eq!(e, "Result\n\nSite is up. Key: [redacted]\n200 on /");+ let long = excerpt(&"word ".repeat(300)).unwrap();+ assert_eq!(long.chars().count(), EXCERPT_CHARS);+ assert!(long.ends_with('…'));+ assert_eq!(excerpt(" \n```\n```"), None);+ }++ #[test]+ fn why_is_the_whole_instruction_or_a_first_line() {+ assert_eq!(why_of("Check booktun.ing is up.\nPost the status.", true).as_deref(), Some("Check booktun.ing is up.\nPost the status."));+ assert_eq!(why_of("\n# Ship the fix\nthen tell me", false).as_deref(), Some("Ship the fix"));+ assert_eq!(why_of(&"x".repeat(400), false).unwrap().chars().count(), WHY_CHARS);+ assert_eq!(why_of(" ", true), None);+ }++ #[test]+ fn reading_steps_change_nothing_and_writes_do() {+ let step = |tool: &str| json!({"kind": "tool", "status": "ok", "tool": tool, "title": "x", "started_at": "2026-11-12T10:00:00Z"});+ for t in ["Read", "Grep", "WebSearch", "WebFetch", "mcp__kwnt__browser_open", "mcp__kwnt__browser_page", "mcp__kwnt__task_done"] {+ assert!(!step_changes(&step(t)), "{t}");+ }+ for t in ["Bash", "Write", "Edit", "mcp__github__create_issue", "mcp__kwnt__browser_act", "mcp__kwnt__send_email"] {+ assert!(step_changes(&step(t)), "{t}");+ }+ assert!(!step_changes(&json!({"kind": "thinking", "status": "ok"})));+ assert!(!step_changes(&json!({"kind": "approval", "status": "declined", "tool": "Bash"})));+ assert!(step_changes(&json!({"kind": "tool", "status": "ok"})), "a step with no tool name may write");+ }++ #[test]+ fn the_trail_keeps_tools_and_pages_and_says_who() {+ let meta = json!({"activity": {"dropped": 2, "steps": [+ {"kind": "thinking", "status": "ok", "title": "Thinking", "started_at": "2026-11-12T10:00:00Z"},+ {"kind": "tool", "status": "ok", "tool": "WebFetch", "title": "Opening booktun.ing", "detail": "https://booktun.ing", "started_at": "2026-11-12T10:00:01Z"},+ {"kind": "tool", "status": "failed", "tool": "Bash", "title": "Running `curl`", "started_at": "2026-11-12T10:00:02Z"},+ ]}});+ let (rows, dropped) = trail_rows(&meta, Some("Ben"));+ assert_eq!(dropped, 2);+ assert_eq!(rows.len(), 2);+ assert_eq!(rows[0], json!({"at": "2026-11-12T10:00:01Z", "kind": "page", "label": "Opening booktun.ing", "detail": "https://booktun.ing", "status": "ok", "by": "Ben"}));+ assert_eq!((rows[1]["kind"].as_str(), rows[1]["status"].as_str()), (Some("write"), Some("error")));+ assert_eq!(trail_status(Some("declined")), "skipped");+ assert_eq!(trail_status(Some("done")), "ok");+ assert_eq!(trail_changed(std::slice::from_ref(&meta)), Some(true));+ assert_eq!(trail_changed(&[json!({})]), Some(false), "a reply with no steps only answered");+ assert_eq!(trail_changed(&[]), None);+ }++ #[test]+ fn sending_tools_on_the_list_are_message_steps() {+ for t in [+ "mcp__kwnt__send_email",+ "mcp__gmail__send_email",+ "GMAIL_SEND_EMAIL",+ "SLACK_SENDS_A_MESSAGE_TO_A_SLACK_CHANNEL",+ "mcp__slack__slack_post_message",+ "TELEGRAM_SEND_MESSAGE",+ "TWITTER_CREATION_OF_A_POST",+ "mcp__agents__post_to_room",+ "mcp__agents__message_person",+ ] {+ assert!(is_message(t), "{t}");+ }+ // Off the list: still a change, but `write`+ for t in ["mcp__github__create_issue", "Bash", "SLACK_LIST_CHANNELS", "send_money"] {+ assert!(!is_message(t), "{t}");+ }+ let step = |tool: &str, status: &str| json!({"kind": "tool", "status": status, "tool": tool, "title": "t", "started_at": "2026-11-12T10:00:00Z"});+ let meta = json!({"activity": {"steps": [+ step("GMAIL_SEND_EMAIL", "ok"),+ step("mcp__github__create_issue", "ok"),+ step("mcp__agents__post_to_room", "failed"),+ ]}});+ let (rows, _) = trail_rows(&meta, None);+ let kinds: Vec<_> = rows.iter().map(|r| r["kind"].as_str().unwrap()).collect();+ assert_eq!(kinds, ["message", "write", "message"]);+ assert_eq!(trail_changed(std::slice::from_ref(&json!({"activity": {"steps": [step("TELEGRAM_SEND_MESSAGE", "ok")]}}))), Some(true), "a message counts as changed");+ // A send that was declined never ran: not a message, nothing changed+ let declined = json!({"kind": "approval", "status": "declined", "tool": "send_email"});+ assert!(!step_changes(&declined));+ }++ #[test]+ fn an_approval_asks_about_what_the_call_names() {+ let d = json!({"tool": "send_email", "arguments": {"to": "[email protected]", "subject": "Spring sale: 15% off"}});+ assert_eq!(approval_question(&d).as_deref(), Some("Approve “Spring sale: 15% off”?"));+ assert_eq!(approval_question(&json!({"arguments": {"title": "Fix login"}})).as_deref(), Some("Approve “Fix login”?"));+ assert_eq!(approval_question(&json!({"arguments": {"command": "rm -rf build"}})), None);+ assert_eq!(approval_question(&json!({"arguments": {"name": "[redacted]"}})), None);+ assert_eq!(approval_question(&Value::Null), None);+ }++ #[test]+ fn the_ledger_wins_over_the_trail() {+ assert_eq!(changed(Some(true), Some(false)), Some(true));+ assert_eq!(changed(Some(false), None), Some(false));+ assert_eq!(changed(None, Some(true)), Some(true));+ assert_eq!(changed(None, None), None);+ }++ #[test]+ fn apply_caps_the_trail_at_the_last_thirty_steps() {+ let steps: Vec<Value> = (0..40)+ .map(|i| json!({"kind": "tool", "status": "ok", "tool": "Read", "title": format!("Reading f{i:02}"), "started_at": format!("2026-11-12T10:00:{i:02}Z")}))+ .collect();+ let msg = Message { direct_kwant_id: Some("k1".into()), ..bare_message("m1", "All fine.", Some(json!({"activity": {"steps": steps}}).to_string())) };+ let mut v = json!({});+ apply(&mut v, &DoneFacts { message: Some(msg), why: Some("Check it".into()), why_kind: Some("routine"), ..Default::default() }, false);+ assert_eq!(v["trail"].as_array().unwrap().len(), TRAIL_MAX);+ assert_eq!(v["trail"][0]["label"], "Reading f10");+ assert_eq!(v["trail_dropped"], 10);+ assert_eq!((v["changed"].clone(), v["changed_nothing"].clone()), (json!(false), json!(true)));+ assert_eq!(v["result_message_id"], "m1");+ assert_eq!(v["result_conversation_id"], "k1");+ assert_eq!((v["result_thread_id"].clone(), v["source"].clone()), (Value::Null, Value::Null));+ assert_eq!(v["answer_excerpt"], "All fine.");+ assert_eq!(v["unread"], false);+ // No message: nothing invented+ let mut v = json!({});+ apply(&mut v, &DoneFacts::default(), true);+ assert_eq!((v["result_message_id"].clone(), v["changed"].clone(), v["trail"].clone()), (Value::Null, Value::Null, json!([])));+ }+}diff --git a/src/server/missions/checkpoints.rs b/src/server/missions/checkpoints.rsindex bdc5ec6e..4f1ff61c 100644--- a/src/server/missions/checkpoints.rs+++ b/src/server/missions/checkpoints.rs@@ -994,7 +994,7 @@ pub async fn after_run(state: &AppState, task: &Task) {// The side-effect ledger/// Claude's tools that only read or plan.-const NO_EFFECT_TOOLS: [&str; 11] =+pub const NO_EFFECT_TOOLS: [&str; 11] =["Read", "Glob", "Grep", "LS", "WebSearch", "TodoWrite", "TodoRead", "NotebookRead", "ToolSearch", "BashOutput", "ExitPlanMode"];/// Claude's tools that write one file.const FILE_TOOLS: [&str; 4] = ["Write", "Edit", "MultiEdit", "NotebookEdit"];diff --git a/src/server/mod.rs b/src/server/mod.rsindex 0a658dce..b990c108 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -51,6 +51,7 @@ pub mod concierge;pub mod rerouting;pub mod import_routes;pub mod inbox;+pub mod inbox_done;pub mod isolated_folders_routes;pub mod approval_modes;pub mod passwords;diff --git a/tests/inbox_away_b_test.rs b/tests/inbox_away_b_test.rsnew file mode 100644index 00000000..c77fb72c--- /dev/null+++ b/tests/inbox_away_b_test.rs@@ -0,0 +1,440 @@+//! 0.9.5 B: Inbox "Done while you were away" (release-095/inbox-away/brief-b.md). Done items stay+//! for 7 days whatever was seen, carry their answer, trail and why, and a lead's `Done:` is a+//! team job.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use chrono::{DateTime, Duration, Utc};+use kwnt::{+ broker::{ApprovalRequest, PermissionBroker},+ config::Config,+ db::{+ continuity::NewRoutine,+ missions::{NewTask, TaskChange},+ models::{Kwant, NewApproval, NewChannel, NewMessage},+ spaces::SpaceId,+ 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;++async fn setup() -> (Router, AppState, TempDir) {+ let tmp = tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ db.set_setting("keep_going_turns", "0").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) -> (StatusCode, Value) {+ let req = Request::builder().method(method).uri(uri).body(Body::empty()).unwrap();+ let resp = app.clone().oneshot(req).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 inbox(app: &Router) -> Value {+ let (s, v) = call(app, "GET", "/api/inbox").await;+ assert_eq!(s, StatusCode::OK, "{v}");+ v+}++fn find<'a>(v: &'a Value, id: &str) -> Option<&'a Value> {+ v["items"].as_array().unwrap().iter().find(|i| i["id"] == id)+}++/// 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 message(role: &str, sender: &str, direct: &str, text: &str) -> NewMessage {+ NewMessage {+ channel_id: None,+ direct_kwant_id: Some(direct.into()),+ sender_role: role.into(),+ sender_id: sender.into(),+ text: text.into(),+ reasoning_content: None,+ tool_calls: None,+ tokens_used: 1,+ }+}++fn step(tool: &str, title: &str, at: &str) -> Value {+ json!({"kind": "tool", "status": "ok", "tool": tool, "title": title, "started_at": at, "ended_at": at})+}++/// A reply of `k` in its direct chat with `steps` saved as its activity, as turns save them.+async fn reply(state: &AppState, k: &Kwant, text: &str, steps: Vec<Value>, extra: Value) -> String {+ let m = state.db.insert_message(&message("kwant", &k.name, &k.id, text)).await.unwrap();+ let mut meta = json!({"activity": {"steps": steps}});+ if let Value::Object(o) = extra {+ for (key, v) in o {+ meta[key] = v;+ }+ }+ state.db.set_message_meta(&m.id, &meta).await.unwrap();+ m.id+}++async fn routine_run(state: &AppState, k: &Kwant, name: &str, instructions: &str, answer: &str, steps: Vec<Value>) -> (String, String) {+ let routine = state+ .db+ .create_routine(&NewRoutine {+ kwant_id: k.id.clone(),+ channel_id: None,+ name: name.into(),+ instructions: instructions.into(),+ schedule: json!({"type": "interval", "every_minutes": 60}).to_string(),+ enabled: false,+ next_run_at: None,+ thread_id: None,+ context_message_id: None,+ ..Default::default()+ })+ .await+ .unwrap();+ let run = state.db.start_routine_run(&routine.id, "manual", "running", None).await.unwrap();+ let msg = reply(state, k, answer, steps, json!({})).await;+ state.db.finish_routine_run(&run.id, "ok", None, Some(&msg)).await.unwrap();+ (run.id, msg)+}++#[tokio::test]+async fn a_finished_run_stays_after_seen_with_its_answer_trail_and_why_until_seven_days() {+ let (app, state, _tmp) = setup().await;+ let k = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();+ let at = "2026-11-12T09:00:00.000Z";+ let read_only = vec![+ json!({"kind": "thinking", "status": "ok", "title": "Thinking", "started_at": at}),+ step("WebFetch", "Opening booktun.ing", at),+ step("Read", "Reading status.md", at),+ ];+ let (run, msg) = routine_run(&state, &k, "Uptime", "Check booktun.ing is up.\nPost one line.", "## Status\n**booktun.ing is up**, 200 in 180 ms.", read_only).await;+ let writes = vec![step("Bash", "Running `deploy.sh`", at)];+ let (wrote, _) = routine_run(&state, &k, "Deploy", "Deploy the site.", "Deployed.", writes).await;++ let v = inbox(&app).await;+ let item = find(&v, &run).unwrap_or_else(|| panic!("{run} missing: {v}"));+ assert_eq!(item["group"], "finished");+ assert_eq!(item["unread"], true);+ assert_eq!(item["result_message_id"], json!(msg));+ assert_eq!(item["result_conversation_id"], json!(k.id));+ assert_eq!(item["result_link"]["direct_kwant_id"], json!(k.id));+ assert_eq!(item["answer_excerpt"], "Status\nbooktun.ing is up, 200 in 180 ms.");+ assert_eq!(item["why"], "Check booktun.ing is up.\nPost one line.");+ assert_eq!(item["why_kind"], "routine");+ assert_eq!(+ item["trail"],+ json!([+ {"at": at, "kind": "page", "label": "Opening booktun.ing", "detail": null, "status": "ok", "by": null},+ {"at": at, "kind": "tool", "label": "Reading status.md", "detail": null, "status": "ok", "by": null},+ ])+ );+ assert_eq!(item["trail_dropped"], 0);+ assert_eq!(item["result_thread_id"], Value::Null);+ assert_eq!(item["source"], json!({"kind": "routine", "routine_id": item["source"]["routine_id"], "run_id": run, "trigger": "manual"}));+ assert!(item["source"]["routine_id"].is_string());+ // A job that only read changed nothing; one that ran a command may have+ assert_eq!((item["changed"].clone(), item["changed_nothing"].clone()), (json!(false), json!(true)));+ let w = find(&v, &wrote).unwrap();+ assert_eq!((w["changed"].clone(), w["changed_nothing"].clone()), (json!(true), json!(false)));+ assert_eq!(w["trail"][0]["kind"], "write");+ assert_eq!(v["counts"]["badge"], 2, "{v}");++ // Seen only clears unread: both stay, and the badge counts unread only+ let (s, _) = call(&app, "POST", "/api/away/seen").await;+ assert_eq!(s, StatusCode::OK);+ let v = inbox(&app).await;+ let item = find(&v, &run).unwrap_or_else(|| panic!("{run} cleared by seen: {v}"));+ assert_eq!(item["unread"], false);+ assert_eq!(item["answer_excerpt"], "Status\nbooktun.ing is up, 200 in 180 ms.");+ assert_eq!(find(&v, &wrote).unwrap()["unread"], false);+ assert_eq!(v["counts"]["badge"], 0, "{v}");+ assert_eq!(v["counts"]["finished"], 2);+ // An older since is cut to the 7 days+ let (s, old) = call(&app, "GET", "/api/inbox?since=2020-01-01T00:00:00Z").await;+ assert_eq!(s, StatusCode::OK);+ let floor = DateTime::parse_from_rfc3339(old["since"].as_str().unwrap()).unwrap().with_timezone(&Utc);+ assert!(floor > Utc::now() - Duration::days(7) - Duration::minutes(1), "{old}");++ // Gone once it ended more than 7 days ago+ set_time(&state, "routine_runs", "ended_at", &run, Utc::now() - Duration::days(7) - Duration::minutes(5)).await;+ let v = inbox(&app).await;+ assert!(find(&v, &run).is_none(), "{v}");+ assert!(find(&v, &wrote).is_some());+}++#[tokio::test]+async fn a_leads_done_line_is_a_team_job_with_members_trail_and_why() {+ let (app, state, _tmp) = setup().await;+ let kwants = state.db.list_kwants(&SpaceId::default_space()).await.unwrap();+ let (lead, member) = (kwants[0].clone(), kwants[1].clone());+ let now = Utc::now();++ // The person's request in the lead's chat, then a hand-off from that chat+ let ask = state.db.insert_message(&message("user", "user", &lead.id, "Find three book bloggers\nwho review fantasy")).await.unwrap();+ set_time(&state, "messages", "created_at", &ask.id, now - Duration::minutes(10)).await;+ let (_, d) = state+ .db+ .create_delegation(&NewDelegation {+ lead_kwant_id: lead.id.clone(),+ specialist_kwant_id: member.id.clone(),+ origin_channel_id: None,+ origin_kwant_id: Some(lead.id.clone()),+ origin_thread_id: None,+ team_id: None,+ task: "List fantasy book bloggers".into(),+ title: "Bloggers".into(),+ continue_lead: false,+ depth: 1,+ follow_up_at: None,+ })+ .await+ .unwrap();+ set_time(&state, "delegations", "created_at", &d.id, now - Duration::minutes(8)).await;+ assert!(state.db.mark_delegation_running(&d.id).await.unwrap());+ let t1 = "2026-11-12T09:01:00.000Z";+ let found = reply(&state, &member, "Three bloggers: A, B, C.", vec![step("mcp__kwnt__browser_open", "Opening fantasyreads.example", t1)], json!({})).await;+ assert!(state.db.finish_delegation(&d.id, "completed", None, Some(&found)).await.unwrap());++ // The lead's last reply, which keep-going marked with its Done: line+ let t2 = "2026-11-12T09:02:00.000Z";+ let done = reply(+ &state,+ &lead,+ "Here are three fantasy book bloggers.\n\nDone: three bloggers listed with links.",+ vec![step("Read", "Reading the list", t2)],+ json!({"chain_done": {"text": "three bloggers listed with links.", "at": Utc::now()}}),+ )+ .await;+ // A plain reply is not a team job+ let plain = reply(&state, &lead, "Hello", vec![], json!({})).await;++ let v = inbox(&app).await;+ let job = find(&v, &done).unwrap_or_else(|| panic!("no team job: {v}"));+ assert!(find(&v, &plain).is_none());+ assert_eq!(job["kind"], "team_job");+ assert_eq!(job["group"], "finished");+ assert_eq!(job["lead"], json!({"kwant_id": lead.id, "kwant_name": lead.name}));+ assert_eq!(job["kwant_name"], json!(lead.name));+ assert_eq!(job["members"], json!([{"kwant_id": member.id, "kwant_name": member.name}]));+ assert_eq!(job["source"], json!({"kind": "team_job", "delegation_id": d.id}));+ assert_eq!(job["status"], "completed");+ assert_eq!(job["done_line"], "three bloggers listed with links.");+ assert_eq!(job["title"], "Find three book bloggers");+ assert_eq!(job["why"], "Find three book bloggers");+ assert_eq!(job["why_kind"], "request");+ assert_eq!(job["result_message_id"], json!(done));+ assert_eq!(job["result_conversation_id"], json!(lead.id));+ assert!(job["answer_excerpt"].as_str().unwrap().starts_with("Here are three fantasy book bloggers."));+ // The members' steps join the lead's, in time order, with who did them+ let trail = job["trail"].as_array().unwrap();+ assert_eq!(trail.len(), 2, "{job}");+ assert_eq!((trail[0]["kind"].as_str(), trail[0]["by"].clone()), (Some("page"), json!(member.name)));+ assert_eq!((trail[1]["label"].as_str(), trail[1]["by"].clone()), (Some("Reading the list"), Value::Null));+ assert_eq!(job["changed_nothing"], true, "opening a page and reading changed nothing");+ assert_eq!(job["unread"], true);+ // Team jobs carry unread but are not in the badge: only the member's finished hand-off is,+ // as on /api/away+ assert_eq!(v["counts"]["badge"], 1, "{v}");+ let (_, away) = call(&app, "GET", "/api/away").await;+ assert_eq!(v["counts"]["badge"], away["unseen"]["total"], "{away}");++ // Seen: still listed, now read+ call(&app, "POST", "/api/away/seen").await;+ let v = inbox(&app).await;+ assert_eq!(find(&v, &done).unwrap()["unread"], false, "{v}");+ assert_eq!(v["counts"]["badge"], 0, "{v}");+}++#[tokio::test]+async fn an_approval_is_titled_with_its_own_question() {+ let (app, state, _tmp) = setup().await;+ let k = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();+ let ask = |tool: &str, args: Value| NewApproval {+ turn_id: "turn-gone".into(),+ kwant_id: k.id.clone(),+ tool_name: format!("mcp__mail__{tool}"),+ parameters: json!({"server": "mail", "tool": tool, "arguments": args}),+ };+ let (mut ids, mut waiting) = (Vec::new(), Vec::new());+ for (tool, args) in [("send", json!({"to": "[email protected]", "subject": "Spring sale: 15% off"})), ("delete", json!({"id": 42}))] {+ let a = state.db.save_approval(&ask(tool, args)).await.unwrap();+ // The broker keeps it pending while its receiver lives+ waiting.push(state.broker.request_approval(ApprovalRequest { id: a.id.clone(), kwant_id: k.id.clone(), tool_name: a.tool_name.clone(), details: json!({}) }).await);+ ids.push(a.id);+ }+ let v = inbox(&app).await;+ let send = find(&v, &ids[0]).unwrap_or_else(|| panic!("{v}"));+ assert_eq!(send["title"], "Approve “Spring sale: 15% off”?");+ assert_eq!(send["question"], "Approve “Spring sale: 15% off”?");+ assert_eq!(send["tool_name"], "mcp__mail__send", "the card still knows its tool");+ assert_eq!(send["unread"], true);+ // Nothing named: no question, and today's tool title+ let del = find(&v, &ids[1]).unwrap();+ assert!(del.get("question").is_none(), "{del}");+ assert_eq!(del["title"], "Use delete (mail)");+ // /api/away keeps today's title+ let (_, away) = call(&app, "GET", "/api/away").await;+ let a = away["waiting"].as_array().unwrap().iter().find(|i| i["id"] == json!(ids[0])).unwrap();+ assert_eq!(a["title"], "Use send (mail)");+}++/// A lead's `Done:` reply in its direct chat, as keep-going marks it.+async fn done_reply(state: &AppState, lead: &Kwant, text: &str, steps: Vec<Value>) -> String {+ reply(state, lead, text, steps, json!({"chain_done": {"text": text, "at": Utc::now()}})).await+}++#[tokio::test]+async fn the_inbox_badge_matches_away_without_team_jobs() {+ let (app, state, _tmp) = setup().await;+ let k = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();+ let at = "2026-11-12T09:00:00.000Z";+ let (run, _) = routine_run(&state, &k, "Uptime", "Check the site.", "Up.", vec![step("WebFetch", "Opening booktun.ing", at)]).await;+ let job = done_reply(&state, &k, "Done: three bloggers listed.", vec![step("GMAIL_SEND_EMAIL", "Sending the list", at)]).await;++ let v = inbox(&app).await;+ assert_eq!(find(&v, &run).unwrap()["unread"], true);+ let j = find(&v, &job).unwrap_or_else(|| panic!("no team job: {v}"));+ assert_eq!(j["unread"], true, "a team job still says it is unread");+ assert_eq!(j["trail"][0]["kind"], "message", "sending mail is a message step");+ assert_eq!(j["changed"], true, "a message counts as changed");+ let (_, away) = call(&app, "GET", "/api/away").await;+ assert_eq!(away["unseen"]["total"], 1, "{away}");+ assert_eq!(v["counts"]["badge"], 1, "the routine run only: {v}");+ assert_eq!(v["counts"]["badge"], away["unseen"]["total"]);+}++/// Timing for impl-b.md: 50 finished and 50 failed done items with a 30-step activity each, 10+/// reviews and 5 team jobs; prints the median of 5 `GET /api/inbox`. Run by hand:+/// `cargo test --test inbox_away_b_test inbox_timing -- --ignored --nocapture`.+#[tokio::test]+#[ignore]+async fn inbox_timing() {+ let (app, state, _tmp) = setup().await;+ let space = SpaceId::default_space();+ let kwants = state.db.list_kwants(&space).await.unwrap();+ let (lead, member) = (kwants[0].clone(), kwants[1].clone());+ let steps = |n: usize| -> Vec<Value> {+ (0..30)+ .map(|i| match i % 3 {+ 0 => step("WebFetch", &format!("Opening page {n}.{i}"), "2026-11-12T09:00:00.000Z"),+ 1 => step("Read", &format!("Reading file {n}.{i}"), "2026-11-12T09:00:01.000Z"),+ _ => step("Bash", &format!("Running step {n}.{i}"), "2026-11-12T09:00:02.000Z"),+ })+ .collect()+ };+ for n in 0..50 {+ routine_run(&state, &k_of(&kwants, n), &format!("Finished {n}"), "Check the site.\nPost one line.", "## Status\nAll good.", steps(n)).await;+ }+ for n in 0..50 {+ let k = k_of(&kwants, n);+ let routine = state+ .db+ .create_routine(&NewRoutine {+ kwant_id: k.id.clone(),+ name: format!("Failed {n}"),+ instructions: "Deploy the site.".into(),+ schedule: json!({"type": "interval", "every_minutes": 60}).to_string(),+ ..Default::default()+ })+ .await+ .unwrap();+ let run = state.db.start_routine_run(&routine.id, "manual", "running", None).await.unwrap();+ let msg = reply(&state, &k, "Deploy failed: 401.", steps(100 + n), json!({})).await;+ state.db.finish_routine_run(&run.id, "error", Some("401 from the host"), Some(&msg)).await.unwrap();+ }+ let chan = state+ .db+ .create_channel(&space, &NewChannel {+ name: "ops".into(),+ description: None,+ lead_kwant_id: lead.id.clone(),+ member_kwants: vec![lead.id.clone(), member.id.clone()],+ routing_mode: "auto".into(),+ })+ .await+ .unwrap();+ let change = |r: &str| TaskChange { kind: "state".into(), reason: Some(r.into()), ..Default::default() };+ for n in 0..10 {+ let t = state+ .db+ .create_task(&space, &NewTask {+ title: format!("Review {n}"),+ acceptance: "- Works\n- No new dependencies".into(),+ state: "ready".into(),+ owner_kwant_id: Some(member.id.clone()),+ max_attempts: 10,+ source_kind: "person".into(),+ channel_id: Some(chan.id.clone()),+ created_by: "person".into(),+ ..Default::default()+ })+ .await+ .unwrap();+ state.db.claim_task(&t.id, &member.id, None, None, 600_000, false, &member.id).await.unwrap().unwrap();+ assert!(state.db.move_task(&t.id, "working", "review", &member.id, &change("done")).await.unwrap());+ }+ for n in 0..5 {+ state.db.insert_message(&message("user", "user", &lead.id, &format!("Job {n}: find bloggers"))).await.unwrap();+ let (_, d) = state+ .db+ .create_delegation(&NewDelegation {+ lead_kwant_id: lead.id.clone(),+ specialist_kwant_id: member.id.clone(),+ origin_channel_id: None,+ origin_kwant_id: Some(lead.id.clone()),+ origin_thread_id: None,+ team_id: None,+ task: format!("Part of job {n}"),+ title: format!("Job {n}"),+ continue_lead: false,+ depth: 1,+ follow_up_at: None,+ })+ .await+ .unwrap();+ assert!(state.db.mark_delegation_running(&d.id).await.unwrap());+ let found = reply(&state, &member, "Found them.", steps(200 + n), json!({})).await;+ assert!(state.db.finish_delegation(&d.id, "completed", None, Some(&found)).await.unwrap());+ done_reply(&state, &lead, &format!("Done: job {n} finished."), steps(300 + n)).await;+ }++ let v = inbox(&app).await;+ let c = &v["counts"];+ println!("items {} counts {c}", v["items"].as_array().unwrap().len());+ let mut ms = Vec::new();+ for _ in 0..5 {+ let t = std::time::Instant::now();+ let v = inbox(&app).await;+ ms.push(t.elapsed().as_secs_f64() * 1000.0);+ assert!(v["items"].as_array().unwrap().len() >= 100);+ }+ ms.sort_by(f64::total_cmp);+ let profile = if cfg!(debug_assertions) { "debug (test profile)" } else { "release" };+ println!("GET /api/inbox: median {:.1} ms of 5 {ms:?}, {profile}", ms[2]);+}++fn k_of(kwants: &[Kwant], n: usize) -> Kwant {+ kwants[n % kwants.len()].clone()+}diff --git a/tests/inbox_test.rs b/tests/inbox_test.rsindex e3cb2d5c..d93da3ff 100644--- a/tests/inbox_test.rs+++ b/tests/inbox_test.rs@@ -146,6 +146,22 @@ async fn review_task(state: &AppState, owner: &str, title: &str, acceptance: &stt.id}+/// What 0.9.5 B adds to each done item.+const DONE_KEYS: [&str; 12] = [+ "result_message_id",+ "result_conversation_id",+ "result_thread_id",+ "result_link",+ "source",+ "answer_excerpt",+ "trail",+ "trail_dropped",+ "why",+ "why_kind",+ "changed",+ "changed_nothing",+];+fn find<'a>(v: &'a Value, id: &str) -> &'a Value {v["items"].as_array().unwrap().iter().find(|i| i["id"] == id).unwrap_or_else(|| panic!("{id} missing from {v}"))}@@ -280,13 +296,18 @@ async fn inbox_joins_away_and_review_tasks_with_fallbacks() {assert_eq!(r2["criteria"][0]["text"], "Runs at 2am");assert_eq!(r2["verdict"]["line"], "No required checks yet.");- // Away items come through unchanged, with their group and key added+ // Away items come through unchanged, with their group, key and unread flag added, and the+ // done fields (0.9.5 B) on finished and failed oneslet away = get(&app, "/api/away").await;for section in ["waiting", "finished", "failed"] {for a in away[section].as_array().unwrap() {let mut i = find(&v, a["id"].as_str().unwrap()).clone();let o = i.as_object_mut().unwrap();assert!(o.remove("group").is_some() && o.remove("sort_key").is_some());+ assert_eq!(o.remove("unread"), Some(json!(true)), "{a}");+ for key in DONE_KEYS {+ assert_eq!(o.remove(key).is_some(), section != "waiting", "{key} on {a}");+ }assert_eq!(&i, a);}}@@ -298,15 +319,17 @@ async fn inbox_joins_away_and_review_tasks_with_fallbacks() {// GET /api/away is byte for byte what it was before review tasks and the inbox existedassert_eq!(away_bytes(&app).await, away_before);- // Marking seen clears finished and failed, never review items+ // Marking seen only clears unread (0.9.5 B): finished and failed stay for 7 days, and the+ // badge counts unread oneslet (s, _) = raw(&app, "POST", "/api/away/seen").await;assert_eq!(s, StatusCode::OK);let v = get(&app, "/api/inbox").await;assert!(v["last_seen"].is_string());- for id in [&t1, &t2, &t3, &q.id] {+ for id in [&t1, &t2, &t3, &q.id, &done, &failed] {assert!(has(&v, id), "{id} cleared by seen: {v}");}- assert!(!has(&v, &done) && !has(&v, &failed), "{v}");+ assert_eq!(find(&v, &done)["unread"], false, "{v}");+ assert_eq!(find(&v, &failed)["unread"], false, "{v}");assert_eq!(v["counts"]["badge"], 4, "1 question + 3 review items: {v}");// since must parse