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.

Desktop island server side: GET /api/glance + quick ask (0.9.13) (#646)

Oleksandr Ivanchenko8ef02ce181e1
diff --git a/src/db/away.rs b/src/db/away.rs
index 3447fe6c..39df2d2e 100644
--- a/src/db/away.rs
+++ b/src/db/away.rs
@@ -104,6 +104,27 @@ impl Database {
.await?)
}
+ /// Bots in spaces that aren't archived as `(id, name, space_id)`: those the person wrote to or
+ /// heard from in a direct chat most recently first, then the rest by name (the island's quick
+ /// ask, `GET /api/glance`). Reads `messages_by_direct`.
+ pub async fn ask_targets(&self, limit: i64) -> Result<Vec<(String, String, String)>, DbError> {
+ Ok(sqlx::query_as(
+ "SELECT id, name, space_id FROM ( \
+ SELECT k.id, k.name, k.space_id, \
+ (SELECT MAX(m.created_at) FROM messages m WHERE m.direct_kwant_id = k.id) AS last_at \
+ FROM kwants k JOIN spaces s ON s.id = k.space_id WHERE s.archived_at IS NULL) \
+ ORDER BY last_at IS NULL, last_at DESC, name, id LIMIT ?",
+ )
+ .bind(limit)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// Every bot's saved avatar sprite, by bot id (the glance puts the face on each item).
+ pub async fn avatar_sprites(&self) -> Result<Vec<(String, String)>, DbError> {
+ Ok(sqlx::query_as("SELECT id, avatar_sprite FROM kwants").fetch_all(&self.pool).await?)
+ }
+
pub async fn away_count_open_questions(&self, space: &SpaceId) -> Result<i64, DbError> {
Ok(sqlx::query_scalar(&format!("SELECT COUNT(*) FROM ({OPEN_QUESTIONS})"))
.bind(Utc::now())
diff --git a/src/server/activity.rs b/src/server/activity.rs
index 33a4d398..30d6290f 100644
--- a/src/server/activity.rs
+++ b/src/server/activity.rs
@@ -169,6 +169,27 @@ fn waits_of(steps: &[Step]) -> TurnWaits {
}
}
+/// What a running turn is doing now, for a glance (the desktop island's "Working now"): the
+/// title of its newest step that still runs or waits, and when that step started. Thinking text is
+/// never read (a running thinking step isn't redacted yet), only its kind; titles are the log's own
+/// one-line, redacted summaries ("Reading acme.com"). `None` when the turn has no steps yet.
+pub fn current_step(turn_id: &str) -> Option<(String, String)> {
+ let turn = TurnActivity::find(turn_id)?;
+ turn.with_log(|log| step_now(log.steps()))
+}
+
+fn step_now(steps: &[Step]) -> Option<(String, String)> {
+ let open = |s: &&Step| matches!(s.status, "running" | "waiting");
+ if let Some(s) = steps.iter().rev().filter(open).find(|s| s.kind != "thinking") {
+ return Some((s.title.clone(), s.started_at.clone()));
+ }
+ if let Some(s) = steps.iter().rev().find(open) {
+ return Some(("Thinking".to_string(), s.started_at.clone()));
+ }
+ // Between steps: the last one that ended says where it got to
+ steps.iter().rev().find(|s| s.kind != "thinking").map(|s| (s.title.clone(), s.started_at.clone()))
+}
+
/// Adds `meta.activity` to a reply's meta.
pub fn with_activity(meta: Option<Value>, activity: Option<Value>) -> Option<Value> {
let Some(activity) = activity else { return meta };
@@ -184,6 +205,20 @@ mod tests {
use super::*;
use serde_json::json;
+ #[test]
+ fn current_step_names_the_running_tool_never_thinking_text() {
+ let (tx, _rx) = broadcast::channel(16);
+ let tag = TurnTag { turn_id: "turn-step-test".into(), kwant_id: "k".into(), context_id: "c".into(), thread_id: None };
+ let turn = TurnActivity::start(tx, tag);
+ assert_eq!(current_step("turn-step-test"), None);
+ turn.observe(&RuntimeEvent::ToolCallPending { id: "1".into(), name: "Bash".into(), args: json!({"command": "ls"}) });
+ let (title, started) = current_step("turn-step-test").unwrap();
+ assert!(!title.is_empty() && !started.is_empty(), "{title}");
+ approval_waiting("turn-step-test", "ap", "Bash");
+ assert!(current_step("turn-step-test").unwrap().0.starts_with("Waiting for your approval"));
+ assert_eq!(current_step("no-such-turn"), None);
+ }
+
#[test]
fn turn_waits_reads_the_waiting_step_and_the_running_tool() {
let (tx, _rx) = broadcast::channel(16);
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 33e8b98e..07b8b538 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -367,6 +367,8 @@ pub fn person_only(method: &Method, path: &str) -> bool {
["", "api", "waiting", ..] => true,
// The review inbox (0.9 V1): what the person approves, sends back or rolls back, with held actions
["", "api", "inbox", ..] => true,
+ // The desktop island's glance (0.9.13): every space's Needs you, and a quick ask as the person
+ ["", "api", "glance", ..] => true,
// Starting work-ahead runs now spends the person's tokens
["", "api", "work-ahead", ..] => true,
// The idea jar is the person's: what they drop in, Look now, Do it and the shelf
@@ -942,6 +944,8 @@ mod tests {
let (get, post, put, del) = (Method::GET, Method::POST, Method::PUT, Method::DELETE);
assert!(person_only(&get, "/api/sandbox/t1/passwords"));
assert!(person_only(&get, "/api/tool-notes"));
+ assert!(person_only(&get, "/api/glance"));
+ assert!(person_only(&post, "/api/glance/ask"));
assert!(person_only(&post, "/api/questions/q1/answer"));
assert!(person_only(&post, "/api/questions/q1/answer/"));
assert!(!person_only(&get, "/api/questions/q1"));
diff --git a/src/server/away.rs b/src/server/away.rs
index 72f4d89b..bba511e1 100644
--- a/src/server/away.rs
+++ b/src/server/away.rs
@@ -19,6 +19,7 @@ use axum::{
use chrono::{DateTime, Duration, SecondsFormat, Utc};
use serde::Deserialize;
use serde_json::{json, Value};
+use std::collections::HashMap;
/// Most items per list.
pub const MAX_ITEMS: i64 = 50;
@@ -27,7 +28,7 @@ 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;
+pub(super) 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"];
@@ -281,19 +282,22 @@ pub async fn unread_total(state: &AppState, space: &SpaceId) -> Result<i64, crat
/// The space's approvals the broker still waits on, each linked to the chat its turn runs in.
pub(super) async fn waiting_approvals(state: &AppState, space: &SpaceId) -> Result<Vec<AwayRow>, crate::db::DbError> {
+ Ok(approvals_by_space(state, Some(space)).await?.remove(space).unwrap_or_default())
+}
+
+/// The waiting approvals of every space (`only`: just that one), in one pass: each card's space
+/// is looked up once, and only the cards that are kept are linked to their chat.
+pub(super) async fn approvals_by_space(state: &AppState, only: Option<&SpaceId>) -> Result<HashMap<SpaceId, Vec<AwayRow>>, crate::db::DbError> {
+ let mut spaces: HashMap<String, SpaceId> = HashMap::new();
+ let mut by_space: HashMap<SpaceId, Vec<AwayRow>> = HashMap::new();
let live = state.broker.pending_ids().await;
- let mut rows = state.db.away_pending_approvals(&live).await?;
- let mut mine = Vec::with_capacity(rows.len());
- for row in rows.drain(..) {
- let of = state.db.space_of_kwant(&row.kwant_id).await?.unwrap_or_else(SpaceId::default_space);
- if &of == space {
- mine.push(row);
- }
- }
- let mut rows = mine;
let turns = state.turns.active_turns();
- // turn_id isn't in the row; look it up by ticket
- for row in &mut rows {
+ for mut row in state.db.away_pending_approvals(&live).await? {
+ let of = space_of(state, &mut spaces, &row.kwant_id).await?;
+ if only.is_some_and(|s| s != &of) {
+ continue;
+ }
+ // turn_id isn't in the row; look it up by ticket
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 {
@@ -304,15 +308,30 @@ pub(super) async fn waiting_approvals(state: &AppState, space: &SpaceId) -> Resu
},
None => row.direct_kwant_id = Some(row.kwant_id.clone()),
}
+ by_space.entry(of).or_default().push(row);
}
// Cards whose turn stopped waiting: still answerable, and a late Allow resumes the work
for row in state.db.away_waiting_approvals().await? {
- let of = state.db.space_of_kwant(&row.kwant_id).await?.unwrap_or_else(SpaceId::default_space);
- if &of == space && !rows.iter().any(|r| r.id == row.id) {
+ let of = space_of(state, &mut spaces, &row.kwant_id).await?;
+ if only.is_some_and(|s| s != &of) {
+ continue;
+ }
+ let rows = by_space.entry(of).or_default();
+ if !rows.iter().any(|r| r.id == row.id) {
rows.push(row);
}
}
- Ok(rows)
+ Ok(by_space)
+}
+
+/// A bot's space, read once per call ([`approvals_by_space`]).
+async fn space_of(state: &AppState, cache: &mut HashMap<String, SpaceId>, kwant_id: &str) -> Result<SpaceId, crate::db::DbError> {
+ if let Some(s) = cache.get(kwant_id) {
+ return Ok(s.clone());
+ }
+ let of = state.db.space_of_kwant(kwant_id).await?.unwrap_or_else(SpaceId::default_space);
+ cache.insert(kwant_id.to_string(), of.clone());
+ Ok(of)
}
/// The space's open stopped items, as Needs-you cards: `title` is what stopped and what resumes
@@ -367,6 +386,34 @@ pub(super) async fn stopped_items(state: &AppState, space: &SpaceId) -> Vec<Valu
out
}
+/// What waits on the person in a space, as `GET /api/away` lists it under `waiting`: open
+/// questions, approvals, what a mission watcher left (P1) and work that stopped and waits to be
+/// resumed (0.9.5), newest first and cut to [`MAX_ITEMS`], with how many there are in all.
+/// `GET /api/glance` reads the same list, so the island and the nudge agree.
+pub(super) async fn waiting(state: &AppState, space: &SpaceId) -> Result<(Vec<Value>, i64), crate::db::DbError> {
+ let approvals = waiting_approvals(state, space).await?;
+ let watch = crate::server::missions::watch::waiting_items(state, space).await;
+ waiting_with(state, space, approvals, watch).await
+}
+
+/// [`waiting`] with the space's approvals and watch items already read (the glance reads them
+/// for every space in one pass).
+pub(super) async fn waiting_with(state: &AppState, space: &SpaceId, approvals: Vec<AwayRow>, watch: Vec<Value>) -> Result<(Vec<Value>, i64), crate::db::DbError> {
+ let mut rows = state.db.away_open_questions(space, MAX_ITEMS).await?;
+ let count = state.db.away_count_open_questions(space).await? + approvals.len() as i64;
+ rows.extend(approvals);
+ rows.sort_by(|a, b| b.at.cmp(&a.at).then_with(|| b.id.cmp(&a.id)));
+ rows.truncate(MAX_ITEMS as usize);
+ let stopped = stopped_items(state, space).await;
+ let count = count + watch.len() as i64 + stopped.len() as i64;
+ let mut waiting: Vec<Value> = rows.into_iter().map(item).collect();
+ waiting.extend(watch);
+ waiting.extend(stopped);
+ waiting.sort_by(|a, b| b["timestamp"].as_str().unwrap_or("").cmp(a["timestamp"].as_str().unwrap_or("")));
+ waiting.truncate(MAX_ITEMS as usize);
+ Ok((waiting, count))
+}
+
#[derive(Debug, Deserialize)]
pub struct AwayQuery {
pub since: Option<String>,
@@ -390,12 +437,7 @@ pub async fn get(State(state): State<AppState>, Scope(space): Scope, Query(q): Q
let stuck_before = now - Duration::minutes(STUCK_AFTER_MINUTES);
let result = async {
- let mut waiting = state.db.away_open_questions(&space, MAX_ITEMS).await?;
- let approvals = waiting_approvals(&state, &space).await?;
- let waiting_count = state.db.away_count_open_questions(&space).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 (waiting, waiting_count) = waiting(&state, &space).await?;
let finished = state.db.away_finished(&space, since, MAX_ITEMS).await?;
let failed = state.db.away_failed(&space, since, stuck_before, MAX_ITEMS).await?;
// The badge counts from the marker, whatever this page asked for
@@ -406,16 +448,6 @@ pub async fn get(State(state): State<AppState>, Scope(space): Scope, Query(q): Q
let Ok((waiting, finished, failed, waiting_count, unseen_finished, unseen_failed)) = result else {
return internal();
};
- // What a mission watcher left for the person (P1)
- let watch = crate::server::missions::watch::waiting_items(&state, &space).await;
- // Work that stopped without finishing and waits for the person to resume it (0.9.5)
- let stopped = stopped_items(&state, &space).await;
- let waiting_count = waiting_count + watch.len() as i64 + stopped.len() as i64;
- let mut waiting: Vec<Value> = waiting.into_iter().map(item).collect();
- waiting.extend(watch);
- waiting.extend(stopped);
- waiting.sort_by(|a, b| b["timestamp"].as_str().unwrap_or("").cmp(a["timestamp"].as_str().unwrap_or("")));
- waiting.truncate(MAX_ITEMS as usize);
Json(json!({
"since": rfc3339(since),
"last_seen": seen.map(rfc3339),
diff --git a/src/server/glance.rs b/src/server/glance.rs
new file mode 100644
index 00000000..81e34fa0
--- /dev/null
+++ b/src/server/glance.rs
@@ -0,0 +1,856 @@
+//! The desktop island's one call (0.9.13): `GET /api/glance` says, across every space that isn't
+//! archived, what needs the person, what is working now and what just finished, in one cheap
+//! response the app polls every 5 s per place with `If-None-Match`. `POST /api/glance/ask` sends a
+//! quick ask into the person's chat with a bot, as if typed there. Both are the person's only.
+//!
+//! Needs you is exactly `GET /api/away`'s `waiting` list (the same builder), so the island and the
+//! nudge agree. Each approval says whether the island may offer Allow once inline
+//! ([`can_allow_inline`]): never for money, the production or push floor, a tier-forced ask, a
+//! risky step or anything else whose only safe answer is the full card. Text from bots is
+//! untrusted: titles are one masked line, a working bot's step is its activity log's own redacted
+//! title, and no tool output, message body or argument value is ever sent.
+
+use super::away::{self, mask_words, rfc3339};
+use super::AppState;
+use crate::db::spaces::{Space, SpaceId};
+use axum::{
+ extract::State,
+ http::{header, HeaderMap, HeaderValue, StatusCode},
+ response::{IntoResponse, Response},
+ Json,
+};
+use chrono::{DateTime, Duration, Utc};
+use serde::Deserialize;
+use serde_json::{json, Value};
+use sha2::{Digest, Sha256};
+use std::collections::HashMap;
+
+/// Most Needs-you items in one glance (the counts say how many there are in all).
+pub const NEEDS_YOU_MAX: usize = 20;
+/// Most running turns listed under Working now.
+pub const WORKING_MAX: usize = 12;
+/// Just finished: at most this many, from the last [`FINISHED_HOURS`].
+pub const FINISHED_MAX: usize = 5;
+pub const FINISHED_HOURS: i64 = 24;
+/// Most bots offered for a quick ask.
+pub const ASK_TARGETS_MAX: i64 = 8;
+/// Most answer choices a question shows inline; a question with more says so (`choices_total`).
+pub const CHOICES_MAX: usize = 6;
+const CHOICE_CHARS: usize = 60;
+const STEP_CHARS: usize = 80;
+/// Longest quick ask. The chat composer has no cap of its own (only the 2 MB request limit); a
+/// quick ask is one line from a small box, so it gets a generous fixed one.
+pub const ASK_MAX_CHARS: usize = 8_000;
+
+fn error(status: StatusCode, code: &str, message: &str) -> Response {
+ (status, Json(json!({ "error": message, "code": code }))).into_response()
+}
+
+fn internal() -> Response {
+ error(StatusCode::INTERNAL_SERVER_ERROR, "internal", "Couldn't read what's happening. Try again.")
+}
+
+/// One line of at most `max` characters, with key-like words masked.
+fn line(text: &str, max: usize) -> String {
+ let one = mask_words(&text.split_whitespace().collect::<Vec<_>>().join(" "));
+ match one.chars().count() > max {
+ true => format!("{}…", one.chars().take(max - 1).collect::<String>().trim_end()),
+ false => one,
+ }
+}
+
+/// Percent-encodes everything but RFC 3986 unreserved characters (a path segment or query value),
+/// as the desktop app's nudge does.
+fn encode(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for b in s.bytes() {
+ match b {
+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
+ _ => out.push_str(&format!("%{b:02X}")),
+ }
+ }
+ out
+}
+
+/// Where an item opens in the app (the nudge's `target_path`): its channel, its bot's
+/// conversation, else its bot's chat, each with `?card=<id>` when a card should show; with no bot,
+/// the space's Inbox.
+pub fn app_path(space: &str, link: &Value, kwant_id: &str, card: Option<&str>) -> String {
+ let base = format!("/s/{}", encode(space));
+ let card = card.filter(|c| !c.is_empty()).map(|c| format!("?card={}", encode(c))).unwrap_or_default();
+ if let Some(c) = link["channel_id"].as_str().filter(|c| !c.is_empty()) {
+ return format!("{base}/c/{}{card}", encode(c));
+ }
+ let bot = link["direct_kwant_id"].as_str().filter(|b| !b.is_empty()).unwrap_or(kwant_id);
+ if bot.is_empty() {
+ return format!("{base}/inbox");
+ }
+ match link["thread_id"].as_str().filter(|t| !t.is_empty()) {
+ Some(t) => format!("{base}/b/{}/t/{}{card}", encode(bot), encode(t)),
+ None => format!("{base}/b/{}{card}", encode(bot)),
+ }
+}
+
+/// GitHub tool names that merge, push or change a branch without a file write [`mcp_writes`]
+/// would see (a merge, a branch update, a release). Any case, any prefix.
+///
+/// [`mcp_writes`]: super::dev::prepush::mcp_writes
+const PUSH_WORDS: &[&str] = &["MERGE", "PUSH", "UPDATE_BRANCH", "UPDATE_A_REFERENCE", "UPDATE_REF", "CREATE_A_REFERENCE", "DELETE_A_REFERENCE", "RELEASE"];
+
+/// Parts of a tool or server name (any case) that mark a tool taking free text to run: a command,
+/// a script, code or a query. A one-line peek can't show what that text does, and a list of bad
+/// commands is never complete, so all of them need the full card.
+const RUNS_TEXT_NAMES: &[&str] = &["RUN", "EXEC", "COMMAND", "CMD", "SHELL", "BASH", "TERMINAL", "SSH", "SCRIPT", "EVAL", "CODE", "SQL"];
+
+/// Argument keys (any depth, any case) that carry free text to run.
+const RUNS_TEXT_KEYS: &[&str] = &["command", "cmd", "argv", "args", "script", "code", "shell", "query", "sql"];
+
+/// Parts of an argument key (any depth; lowercased with `_`, `-`, `.` and spaces dropped) that
+/// carry free text to run, matched by containment: `command_line`, `commandLine`, `shell_command`,
+/// `cmdline`, `bash_command`, `exec_args` (0.9.14, Rigel's hole 1).
+const RUNS_TEXT_KEY_PARTS: &[&str] = &["command", "cmd", "shell", "exec", "argv"];
+
+/// Whole words of an argument key (split at `_`, `-`, camelCase) that carry a script. Not by
+/// containment, which would catch `description`, `subscription` and `transcript`.
+const RUNS_TEXT_KEY_WORDS: &[&str] = &["script", "scripts", "javascript", "applescript", "stdin"];
+
+/// HTTP verbs that change something, in a `method` argument (any depth, any case).
+const WRITE_METHODS: &[&str] = &["DELETE", "PUT", "PATCH", "POST"];
+
+/// HTTP verbs that only read; on an HTTP-shaped call (it has a URL argument) any other `method`
+/// value, or one that isn't a plain string, needs the full card.
+const READ_METHODS: &[&str] = &["GET", "HEAD", "OPTIONS"];
+
+/// Whole words (in the tool name, any argument key or any string value) that push, merge, publish
+/// or release, or move refs and tags.
+const PUSH_FAMILY: &[&[&str]] = &[&["push"], &["merge"], &["publish"], &["release"], &["send", "pack"], &["receive", "pack"], &["refs"], &["deploy"], &["tag"]];
+
+/// Parts of a tool name (any case) that act outside kwant or destroy something: publishing,
+/// sending, deleting, posting or paying.
+const OUTWARD_NAMES: &[&str] = &[
+ "PUBLISH", "DEPLOY", "SEND", "EMAIL", "MAIL", "DELETE", "REMOVE", "DESTROY", "DROP", "POST", "PAY",
+ // 0.9.14 (Rigel's hole 3)
+ "TRANSFER", "SUBMIT", "TWEET", "SHARE", "INVITE", "FORWARD", "UPLOAD", "WIPE", "TERMINATE", "REVOKE", "PURCHASE",
+];
+
+const PUSHES: &str = "This pushes code, so it needs the full card.";
+const RUNS: &str = "This runs a command, so it needs the full card.";
+const OUTWARD: &str = "This acts outside kwant, so it needs the full card.";
+
+/// Every argument key and string value, at any depth, in document order (array items in turn).
+fn texts<'a>(v: &'a Value, out: &mut Vec<&'a str>) {
+ match v {
+ Value::String(s) => out.push(s),
+ Value::Array(items) => items.iter().for_each(|i| texts(i, out)),
+ Value::Object(map) => map.iter().for_each(|(k, v)| {
+ out.push(k);
+ texts(v, out);
+ }),
+ _ => {}
+ }
+}
+
+/// Whether `f(key, value)` holds for any key at any depth.
+fn any_key(v: &Value, f: &dyn Fn(&str, &Value) -> bool) -> bool {
+ match v {
+ Value::Array(items) => items.iter().any(|i| any_key(i, f)),
+ Value::Object(map) => map.iter().any(|(k, v)| f(k, v) || any_key(v, f)),
+ _ => false,
+ }
+}
+
+/// `text` lowercased, letters and digits only: `command_line`, `commandLine` and `Command-Line`
+/// all become `commandline`.
+fn flat(text: &str) -> String {
+ text.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect()
+}
+
+/// The lowercased words of `text`. Anything but letters and digits (spaces, tabs, `_`, `-`, `/`,
+/// quotes, dots) is a break, and so is a camelCase hump: `pushToOrigin` is push, to, origin, and
+/// `HTTPPush` is http, push. A word in one case throughout (`Pushkin`, `PUSHKIN`) stays whole.
+fn words(text: &str) -> Vec<String> {
+ let chars: Vec<char> = text.chars().collect();
+ let mut out = Vec::new();
+ let mut cur = String::new();
+ for (i, &c) in chars.iter().enumerate() {
+ if !c.is_alphanumeric() {
+ if !cur.is_empty() {
+ out.push(std::mem::take(&mut cur));
+ }
+ continue;
+ }
+ if c.is_uppercase() && !cur.is_empty() {
+ // cur is non-empty, so chars[i - 1] is a letter or digit of this word
+ let prev = chars[i - 1];
+ let next_lower = chars.get(i + 1).is_some_and(|n| n.is_lowercase());
+ if prev.is_lowercase() || prev.is_numeric() || (prev.is_uppercase() && next_lower) {
+ out.push(std::mem::take(&mut cur));
+ }
+ }
+ cur.extend(c.to_lowercase());
+ }
+ if !cur.is_empty() {
+ out.push(cur);
+ }
+ out
+}
+
+/// Whether an argument key carries free text to run: one of [`RUNS_TEXT_KEYS`], a key holding a
+/// [`RUNS_TEXT_KEY_PARTS`] part once flattened, or one with a [`RUNS_TEXT_KEY_WORDS`] word.
+fn is_run_key(k: &str) -> bool {
+ RUNS_TEXT_KEYS.iter().any(|r| k.eq_ignore_ascii_case(r))
+ || RUNS_TEXT_KEY_PARTS.iter().any(|p| flat(k).contains(p))
+ || words(k).iter().any(|w| RUNS_TEXT_KEY_WORDS.contains(&w.as_str()))
+}
+
+/// Whether any key at any depth carries free text to run ([`is_run_key`]).
+fn has_run_key(v: &Value) -> bool {
+ any_key(v, &|k, _| is_run_key(k))
+}
+
+/// Whether `text` holds a [`PUSH_FAMILY`] word as a whole word ([`words`]).
+fn has_push_word(text: &str) -> bool {
+ let words = words(text);
+ PUSH_FAMILY.iter().any(|phrase| words.windows(phrase.len()).any(|w| w.iter().zip(phrase.iter()).all(|(a, b)| a == b)))
+}
+
+/// Whether the arguments ask for an HTTP verb that changes something. A `method` key (any depth;
+/// `method`, `http_method`, `httpMethod`, `verb`) whose value is one of [`WRITE_METHODS`] always
+/// does. On an HTTP-shaped call (a `url`, `uri` or `endpoint` key anywhere) a method that isn't a
+/// plain [`READ_METHODS`] string does too: `CONNECT`, a made-up verb, a list or a number.
+fn writes_by_method(args: &Value) -> bool {
+ let http = any_key(args, &|k, _| {
+ let f = flat(k);
+ f == "uri" || f == "endpoint" || f.ends_with("url")
+ });
+ any_key(args, &|k, v| {
+ let f = flat(k);
+ if !(f.ends_with("method") || f == "verb" || f == "httpverb") {
+ return false;
+ }
+ match v.as_str() {
+ Some(s) => {
+ let verb = s.trim().to_ascii_uppercase();
+ WRITE_METHODS.contains(&verb.as_str()) || (http && !READ_METHODS.contains(&verb.as_str()))
+ }
+ None => http && !v.is_null(),
+ }
+ })
+}
+
+/// Why an approval may only be answered on its full card, from its stored details alone; `None`
+/// when the island may offer Allow once. Starts from Telegram's rule (money, the production floor,
+/// a tier-forced ask, a turn that read outside text or that kwant started on its own, a shell
+/// command, kwant's own tools, wrappers that run other actions, file tools outside the bot's
+/// folder), then adds what a one-line peek can't show safely: a risky step (`smart_reason`), the
+/// push floor (a prepush grant, a GitHub write, a merge) and details it can't read.
+///
+/// It fails closed in four layers, each of which refuses on its own (Ada, #646 round 2; 0.9.14):
+/// 1. a push-family word ([`PUSH_FAMILY`]) anywhere in the tool name, an argument key or a string
+/// value, as a whole word, camelCase humps included ([`words`]);
+/// 2. a tool that runs free text: its tool or server name says so ([`RUNS_TEXT_NAMES`]) or an
+/// argument key at any depth does ([`is_run_key`]: exact, by containment, or by word);
+/// 3. a tool whose name acts outside kwant or destroys something ([`OUTWARD_NAMES`]);
+/// 4. an HTTP verb that changes something in a `method` argument ([`writes_by_method`]).
+pub fn inline_refusal(details: &Value) -> Option<&'static str> {
+ if !details.is_object() {
+ return Some("Open it to see what it does.");
+ }
+ if let Some(why) = super::telegram::link_only_reason(details) {
+ return Some(match why {
+ "This kind of step can't be approved from Telegram." => "This kind of step needs the full card.",
+ other => other,
+ });
+ }
+ let set = |k: &str| details.get(k).is_some_and(|v| !v.is_null() && v != false);
+ if set("smart_reason") {
+ return Some("kwant flagged this step as risky.");
+ }
+ if set("prepush_grant") || set("strict_ask") {
+ return Some(PUSHES);
+ }
+ let tool = details["tool"].as_str().unwrap_or_default();
+ let server = details["server"].as_str().unwrap_or_default();
+ let args = &details["arguments"];
+ if !super::dev::prepush::mcp_writes(tool, args).is_empty() {
+ return Some(PUSHES);
+ }
+ let upper = tool.to_ascii_uppercase();
+ if PUSH_WORDS.iter().any(|w| upper.contains(w)) {
+ return Some(PUSHES);
+ }
+ // 1. A push-family word wherever it hides: the name, a key, a value, an argv item
+ let mut all = vec![tool];
+ texts(args, &mut all);
+ if has_push_word(&all.join(" ")) {
+ return Some(PUSHES);
+ }
+ // 2. Free text to run, whatever it says
+ let names = format!("{} {}", server.to_ascii_uppercase(), upper);
+ if RUNS_TEXT_NAMES.iter().any(|w| names.contains(w)) || has_run_key(args) {
+ return Some(RUNS);
+ }
+ // 3. Acts outside kwant or destroys something
+ if OUTWARD_NAMES.iter().any(|w| upper.contains(w)) {
+ return Some(OUTWARD);
+ }
+ // 4. An HTTP call that changes something, whatever the tool is called
+ if writes_by_method(args) {
+ return Some(OUTWARD);
+ }
+ None
+}
+
+/// [`inline_refusal`], plus the space's production marks (as Telegram's [`link_only_in`]).
+///
+/// [`link_only_in`]: super::telegram::link_only_in
+pub async fn can_allow_inline(state: &AppState, space: &str, details: &Value) -> Result<(), &'static str> {
+ if let Some(why) = inline_refusal(details) {
+ return Err(why);
+ }
+ match super::telegram::link_only_in(state, space, details).await {
+ None => Ok(()),
+ Some("This is a production connection.") => Err("This is a production connection."),
+ Some(_) => Err("This kind of step needs the full card."),
+ }
+}
+
+/// One Needs-you item: `/api/away`'s waiting item in the island's shape.
+async fn needs_you_item(state: &AppState, space: &Space, v: &Value) -> Value {
+ let kind = match (v["kind"].as_str().unwrap_or(""), v.get("human_step_id").is_some_and(|h| !h.is_null())) {
+ ("stopped", true) => "human_step",
+ (k, _) => k,
+ };
+ let id = v["id"].as_str().unwrap_or("");
+ let kwant_id = v["kwant_id"].as_str().unwrap_or("");
+ let card = matches!(kind, "approval" | "question").then_some(id);
+ let mut out = json!({
+ "kind": kind,
+ "id": id,
+ "space_id": space.id,
+ "space_name": line(&space.name, 60),
+ "kwant_id": kwant_id,
+ "kwant_name": line(v["kwant_name"].as_str().unwrap_or("A bot"), 60),
+ "title": line(v["title"].as_str().unwrap_or(""), 120),
+ "since": v["timestamp"],
+ "path": app_path(&space.id, &v["link"], kwant_id, card),
+ "approval": Value::Null,
+ "question": Value::Null,
+ });
+ if kind == "approval" {
+ // The stored details, unmasked, decide; none of them is sent
+ let details = match state.db.get_approval(id).await {
+ Ok(Some(a)) => serde_json::from_str(&a.parameters).unwrap_or(Value::Null),
+ _ => Value::Null,
+ };
+ let verdict = can_allow_inline(state, &space.id, &details).await;
+ out["approval"] = json!({
+ "risk": if verdict.is_ok() { "normal" } else { "high" },
+ "can_allow_inline": verdict.is_ok(),
+ "why_open": verdict.err(),
+ });
+ }
+ if kind == "question" {
+ let all: Vec<&str> = v["choices"].as_array().map(|c| c.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
+ let shown: Vec<String> = all.iter().take(CHOICES_MAX).map(|c| line(c, CHOICE_CHARS)).collect();
+ out["question"] = json!({ "choices": shown, "choices_total": all.len(), "allow_text": true });
+ }
+ out
+}
+
+/// A running turn, as Working now shows it.
+struct Working {
+ since: DateTime<Utc>,
+ value: Value,
+}
+
+async fn working(state: &AppState, spaces: &HashMap<String, &Space>, names: &mut HashMap<String, (String, String)>) -> Vec<Working> {
+ let mut out = Vec::new();
+ for t in state.turns.active_turns() {
+ // The hidden decide-first round isn't work anyone asked for; a queued turn isn't working
+ if t.purpose.as_deref() == Some("decide") || t.state != "running" {
+ continue;
+ }
+ if !names.contains_key(&t.kwant_id) {
+ let Ok(Some(k)) = state.db.get_kwant(&t.kwant_id).await else { continue };
+ names.insert(t.kwant_id.clone(), (k.name, k.space_id));
+ }
+ let (name, space_id) = names[&t.kwant_id].clone();
+ if !spaces.contains_key(&space_id) {
+ continue;
+ }
+ let link = match &t.thread_id {
+ Some(thread) => json!({"thread_id": thread}),
+ None => match state.db.get_channel(&t.context_id).await {
+ Ok(Some(_)) => json!({"channel_id": t.context_id}),
+ _ => json!({"direct_kwant_id": t.context_id}),
+ },
+ };
+ let (step, step_at) = super::activity::current_step(&t.turn_id).unwrap_or_else(|| ("Getting started".into(), rfc3339(t.since)));
+ out.push(Working {
+ since: t.since,
+ value: json!({
+ "turn_id": t.turn_id,
+ "kwant_id": t.kwant_id,
+ "kwant_name": line(&name, 60),
+ "space_id": space_id,
+ "step": line(&step, STEP_CHARS),
+ "step_started_at": step_at,
+ "started_at": rfc3339(t.since),
+ "path": app_path(&space_id, &link, &t.kwant_id, None),
+ }),
+ });
+ }
+ out
+}
+
+/// One Just-finished item, with its done-check line when the item has one.
+async fn finished_item(state: &AppState, space: &Space, row: crate::db::away::AwayRow, unseen: bool) -> Value {
+ let facts = super::inbox_done::away_facts(state, &row.kind, &row.id).await.unwrap_or_default();
+ let check = (!facts.tasks.is_empty()).then(|| {
+ let c = super::inbox_done::checked(&facts.tasks, facts.message.as_ref().map(super::inbox_done::meta_of).as_ref());
+ let status = match c["state"].as_str() {
+ Some("checked") => "verified",
+ Some("failed") => "failed",
+ _ => "not_checked",
+ };
+ json!({ "status": status, "line": line(c["line"].as_str().unwrap_or(""), 120) })
+ });
+ let at = row.at;
+ let v = away::item(row);
+ let kwant_id = v["kwant_id"].as_str().unwrap_or("");
+ let result_link = facts.message.as_ref().map(|m| json!({"thread_id": m.thread_id, "channel_id": m.channel_id, "direct_kwant_id": m.direct_kwant_id}));
+ json!({
+ "kind": v["kind"],
+ "id": v["id"],
+ "space_id": space.id,
+ "kwant_id": kwant_id,
+ "kwant_name": line(v["kwant_name"].as_str().unwrap_or("A bot"), 60),
+ "title": line(v["title"].as_str().unwrap_or(""), 120),
+ "status": v["status"],
+ "finished_at": rfc3339(at),
+ "unseen": unseen,
+ "check": check,
+ "path": app_path(&space.id, result_link.as_ref().unwrap_or(&v["link"]), kwant_id, None),
+ })
+}
+
+/// The bots a quick ask can go to: the person's most recent direct chats in live spaces, then the
+/// rest by name. There are no server-side pins (the sidebar's pins live in the browser), so the
+/// app puts its own pins first.
+async fn ask_targets(state: &AppState) -> Result<Vec<Value>, crate::db::DbError> {
+ let rows = state.db.ask_targets(ASK_TARGETS_MAX).await?;
+ Ok(rows.into_iter().map(|(id, name, space)| json!({"kwant_id": id, "name": line(&name, 60), "space_id": space})).collect())
+}
+
+/// A bot's saved `avatar_sprite` (as the bot's own settings return it), or `null` when the item
+/// names no bot, the bot is gone, or its sprite is empty.
+pub fn avatar_of(avatars: &HashMap<String, String>, kwant_id: Option<&str>) -> Value {
+ match kwant_id.filter(|k| !k.is_empty()).and_then(|k| avatars.get(k)) {
+ Some(sprite) if !sprite.trim().is_empty() => Value::String(sprite.clone()),
+ _ => Value::Null,
+ }
+}
+
+/// The glance without `now`, which the ETag is taken over.
+pub async fn build(state: &AppState, now: DateTime<Utc>) -> Result<Value, crate::db::DbError> {
+ let spaces: Vec<Space> = state.db.list_spaces().await?.into_iter().filter(|s| s.archived_at.is_none()).collect();
+ let live: HashMap<String, &Space> = spaces.iter().map(|s| (s.id.clone(), s)).collect();
+ // Approvals and mission watches are read once for every space, not once per space
+ let mut approvals = away::approvals_by_space(state, None).await?;
+ let mut watch = crate::server::missions::watch::waiting_items_by_space(state).await;
+ let mut waiting: Vec<(&Space, Value)> = Vec::new();
+ let mut needs_you_count = 0;
+ let mut finished_rows: Vec<(bool, &Space, crate::db::away::AwayRow)> = Vec::new();
+ let mut finished_unseen = 0;
+ let day_ago = now - Duration::hours(FINISHED_HOURS);
+ let stuck_before = now - Duration::minutes(away::STUCK_AFTER_MINUTES);
+ for space in &spaces {
+ let id = SpaceId::new(space.id.clone());
+ let mine = approvals.remove(&id).unwrap_or_default();
+ let watching = watch.remove(&space.id).unwrap_or_default();
+ let (items, count) = away::waiting_with(state, &id, mine, watching).await?;
+ needs_you_count += count;
+ waiting.extend(items.into_iter().take(NEEDS_YOU_MAX).map(|v| (space, v)));
+ let seen = away::last_seen(state, &id).await?;
+ let from = seen.map_or(day_ago, |s| s.max(day_ago));
+ finished_unseen += state.db.away_counts(&id, from, stuck_before).await?.0;
+ for row in state.db.away_finished(&id, day_ago, FINISHED_MAX as i64).await? {
+ finished_rows.push((seen.is_none_or(|s| row.at > s), space, row));
+ }
+ }
+ // Cut first, then build only the items that are sent
+ waiting.sort_by(|(_, a), (_, b)| b["timestamp"].as_str().unwrap_or("").cmp(a["timestamp"].as_str().unwrap_or("")).then_with(|| b["id"].as_str().cmp(&a["id"].as_str())));
+ waiting.truncate(NEEDS_YOU_MAX);
+ let mut needs_you = Vec::with_capacity(waiting.len());
+ for (space, v) in &waiting {
+ needs_you.push(needs_you_item(state, space, v).await);
+ }
+ finished_rows.sort_by(|a, b| b.0.cmp(&a.0).then(b.2.at.cmp(&a.2.at)));
+ finished_rows.truncate(FINISHED_MAX);
+ let mut finished = Vec::with_capacity(finished_rows.len());
+ for (unseen, space, row) in finished_rows {
+ finished.push(finished_item(state, space, row, unseen).await);
+ }
+
+ let mut names = HashMap::new();
+ let mut work = working(state, &live, &mut names).await;
+ let working_count = work.len();
+ work.sort_by(|a, b| b.since.cmp(&a.since).then_with(|| b.value["turn_id"].as_str().cmp(&a.value["turn_id"].as_str())));
+ work.truncate(WORKING_MAX);
+
+ // The bot's face for every item that names one (`null` when there's no bot or no sprite).
+ // It is part of the body, so a changed face gives a new ETag.
+ let avatars: HashMap<String, String> = state.db.avatar_sprites().await?.into_iter().collect();
+ let mut work: Vec<Value> = work.into_iter().map(|w| w.value).collect();
+ let mut targets = ask_targets(state).await?;
+ for v in needs_you.iter_mut().chain(work.iter_mut()).chain(finished.iter_mut()).chain(targets.iter_mut()) {
+ let avatar = avatar_of(&avatars, v["kwant_id"].as_str());
+ v["avatar"] = avatar;
+ }
+
+ Ok(json!({
+ "counts": {
+ "needs_you": needs_you_count,
+ "working": working_count,
+ "finished_unseen": finished_unseen,
+ },
+ "needs_you": needs_you,
+ "working": work,
+ "finished": finished,
+ "ask_targets": targets,
+ }))
+}
+
+/// A weak ETag over the glance's content (not its `now`).
+pub fn etag_of(body: &Value) -> String {
+ let digest = Sha256::digest(body.to_string().as_bytes());
+ let hex: String = digest.iter().take(12).map(|b| format!("{b:02x}")).collect();
+ format!("W/\"g-{hex}\"")
+}
+
+/// Whether `If-None-Match` names this ETag (or `*`). Weak comparison, as for a GET.
+pub fn matches(header: Option<&str>, etag: &str) -> bool {
+ let Some(h) = header else { return false };
+ let bare = |t: &str| t.trim().trim_start_matches("W/").to_string();
+ h.split(',').any(|t| t.trim() == "*" || bare(t) == bare(etag))
+}
+
+/// `GET /api/glance`: see the module docs. 304 with no body when `If-None-Match` names the
+/// current ETag.
+pub async fn get(State(state): State<AppState>, headers: HeaderMap) -> Response {
+ let now = Utc::now();
+ let Ok(mut body) = build(&state, now).await else {
+ return internal();
+ };
+ let etag = etag_of(&body);
+ let cache = [(header::CACHE_CONTROL, HeaderValue::from_static("private, no-cache"))];
+ let etag_header = HeaderValue::from_str(&etag).unwrap_or_else(|_| HeaderValue::from_static("W/\"g\""));
+ if matches(headers.get(header::IF_NONE_MATCH).and_then(|h| h.to_str().ok()), &etag) {
+ return (StatusCode::NOT_MODIFIED, cache, [(header::ETAG, etag_header)]).into_response();
+ }
+ body["now"] = json!(rfc3339(now));
+ (cache, [(header::ETAG, etag_header)], Json(body)).into_response()
+}
+
+#[derive(Debug, Deserialize)]
+pub struct AskPayload {
+ pub space_id: String,
+ pub kwant_id: String,
+ pub text: String,
+ /// The app's own id for this ask, the same on every retry: sent once (as the composer's).
+ #[serde(default)]
+ pub client_message_id: Option<String>,
+}
+
+/// `POST /api/glance/ask {space_id, kwant_id, text, client_message_id?}`: sends `text` into the
+/// person's chat with that bot, exactly as if typed there (the bot answers there; nothing opens).
+/// 200 `{path, user_message_id}`; 400 for an empty or too long text, 404 for a bot not in that
+/// space, 409 for an archived space.
+pub async fn ask(State(state): State<AppState>, Json(p): Json<AskPayload>) -> Response {
+ let text = p.text.trim();
+ if text.is_empty() {
+ return error(StatusCode::BAD_REQUEST, "empty", "Type something to ask.");
+ }
+ if text.chars().count() > ASK_MAX_CHARS {
+ return error(StatusCode::BAD_REQUEST, "too_long", "That's too long for a quick ask. Open the chat to send it.");
+ }
+ let kwant = match state.db.get_kwant(&p.kwant_id).await {
+ Ok(Some(k)) if k.space_id == p.space_id => k,
+ Ok(_) => return error(StatusCode::NOT_FOUND, "not_found", "That bot isn't in this space."),
+ Err(_) => return internal(),
+ };
+ let space = SpaceId::new(p.space_id.clone());
+ if let Err(r) = super::spaces::ensure_active(&state, &space).await {
+ return r;
+ }
+ let payload = super::routes::SendChatPayload {
+ channel_id: None,
+ kwant_id: Some(kwant.id.clone()),
+ team_id: None,
+ thread_id: None,
+ prompt: text.to_string(),
+ sender_id: "PlayerHero".into(),
+ attachment_ids: Vec::new(),
+ reply_to_message_id: None,
+ source: None,
+ meta: None,
+ client_message_id: p.client_message_id,
+ message_id: None,
+ };
+ match super::routes::send_chat_inner(state, payload, true).await {
+ Ok(Json(v)) => Json(json!({
+ "path": app_path(&p.space_id, &json!({"direct_kwant_id": kwant.id}), &kwant.id, None),
+ "user_message_id": v["user_message_id"],
+ "deduped": v["deduped"].as_bool().unwrap_or(false),
+ }))
+ .into_response(),
+ Err(StatusCode::CONFLICT) => error(StatusCode::CONFLICT, "archived", "This space is archived."),
+ Err(StatusCode::BAD_REQUEST) => error(StatusCode::BAD_REQUEST, "bad_request", "That ask couldn't be sent."),
+ Err(_) => internal(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn mcp(server: &str, tool: &str, args: Value) -> Value {
+ json!({"source": "mcp", "server": server, "tool": tool, "arguments": args})
+ }
+
+ #[test]
+ fn a_plain_mcp_call_may_be_allowed_inline() {
+ assert_eq!(inline_refusal(&mcp("notion", "create_page", json!({"title": "Notes"}))), None);
+ let read = json!({"source": "claude_builtin", "tool": "Read", "outside_folder": false, "arguments": {"file_path": "a.txt"}});
+ assert_eq!(inline_refusal(&read), None);
+ }
+
+ #[test]
+ fn money_risk_and_the_floors_need_the_full_card() {
+ let with = |k: &str, v: Value| {
+ let mut d = mcp("stripe", "create_invoice", json!({}));
+ d[k] = v;
+ d
+ };
+ for (k, v) in [
+ ("payment_reason", json!("Sends money")),
+ ("prod_floor", json!({"server": "db"})),
+ ("tier_reason", json!("Tier 3")),
+ ("smart_reason", json!("Deletes records")),
+ ("prepush_grant", json!({"repo": "x"})),
+ ("tainted", json!(true)),
+ ("always_ask", json!(true)),
+ ] {
+ assert!(inline_refusal(&with(k, v)).is_some(), "{k}");
+ }
+ // A shell command, kwant's own tools, wrappers and files outside the folder
+ assert!(inline_refusal(&json!({"source": "local_shell", "tool": "shell", "arguments": {"command": "ls"}})).is_some());
+ assert!(inline_refusal(&json!({"source": "claude_builtin", "tool": "Bash", "arguments": {"command": "ls"}})).is_some());
+ assert!(inline_refusal(&json!({"source": "claude_builtin", "tool": "Write", "arguments": {}})).is_some());
+ assert!(inline_refusal(&mcp("composio", "COMPOSIO_MULTI_EXECUTE_TOOL", json!({}))).is_some());
+ assert!(inline_refusal(&Value::Null).is_some(), "unreadable details: false");
+ assert!(inline_refusal(&json!({"tool": "x"})).is_some(), "no source: false");
+ }
+
+ #[test]
+ fn pushes_and_merges_need_the_full_card() {
+ let write = mcp("github", "create_or_update_file", json!({"owner": "o", "repo": "r", "path": "a", "content": "x", "message": "m", "branch": "main"}));
+ assert!(inline_refusal(&write).is_some());
+ assert!(inline_refusal(&mcp("github", "merge_pull_request", json!({"owner": "o", "repo": "r", "pull_number": 1}))).is_some());
+ assert!(inline_refusal(&mcp("composio", "GITHUB_MERGE_A_PULL_REQUEST", json!({}))).is_some());
+ assert!(inline_refusal(&mcp("runner", "run", json!({"cmd": "cd x && git push origin main"}))).is_some());
+ assert!(inline_refusal(&mcp("github", "create_issue", json!({"owner": "o", "repo": "r", "title": "Bug"}))).is_none());
+ }
+
+ /// Rigel's round-2 risk-4 rows (#646): fifteen commands and four outward tools that came back
+ /// Allow once at 184d8fd0. tests/glance_test.rs reads the same rows back through the API.
+ fn risky_rows() -> Vec<(&'static str, Value)> {
+ let run = |c: &str| mcp("runner", "run", json!({ "command": c }));
+ vec![
+ ("git push (two spaces)", run("git push origin main")),
+ ("git<TAB>push", run("git\tpush origin main")),
+ ("git -C dir push", run("git -C /repo push origin main")),
+ ("git -c k=v push", run("git -c core.x=1 push")),
+ ("argv [git, push]", mcp("runner", "run", json!({"argv": ["git", "push", "origin", "main"]}))),
+ ("gh pr merge", run("gh pr merge 5 --squash")),
+ ("gh release create", run("gh release create v1")),
+ ("gh api -X PUT merge", run("gh api -X PUT repos/o/r/pulls/5/merge")),
+ ("git send-pack", run("git send-pack origin main")),
+ ("npm publish", run("npm publish")),
+ ("cargo publish", run("cargo publish")),
+ ("docker push", run("docker push img")),
+ ("curl POST git/refs", run("curl -X POST https://api.github.com/repos/o/r/git/refs")),
+ ("rm -rf /", run("rm -rf /")),
+ ("bitbucket pr_action merge", mcp("bitbucket", "pr_action", json!({"action": "merge"}))),
+ ("publish_site", mcp("netlify", "publish_site", json!({}))),
+ ("deploy", mcp("vercel", "deploy", json!({}))),
+ ("send_email", mcp("gmail", "send_email", json!({}))),
+ ("delete_page", mcp("notion", "delete_page", json!({}))),
+ ]
+ }
+
+ #[test]
+ fn every_round_two_row_needs_the_full_card() {
+ let rows = risky_rows();
+ assert_eq!(rows.len(), 19);
+ for (name, d) in rows {
+ assert!(inline_refusal(&d).is_some(), "{name}");
+ }
+ }
+
+ #[test]
+ fn each_layer_refuses_on_its_own() {
+ // 1. Push-family words, whole words only, in any key or value, at any depth
+ let words = |args: Value| inline_refusal(&mcp("notes", "save_note", args));
+ assert_eq!(words(json!({"a": {"b": ["x", "Push it"]}})), Some(PUSHES));
+ assert_eq!(words(json!({"what_to_merge": "a"})), Some(PUSHES), "a key");
+ assert_eq!(words(json!({"t": "receive-pack"})), Some(PUSHES));
+ assert_eq!(words(json!({"t": "v1 TAG"})), Some(PUSHES));
+ assert_eq!(words(json!({"t": "pushkin, merger, tags, published"})), None, "whole words only");
+ assert_eq!(inline_refusal(&mcp("github", "create_tag", json!({}))), Some(PUSHES), "a name word");
+ // 2. Free text to run: by tool name, server name or a key at any depth
+ assert_eq!(inline_refusal(&mcp("notes", "Execute", json!({}))), Some(RUNS));
+ assert_eq!(inline_refusal(&mcp("my-ssh", "connect", json!({}))), Some(RUNS));
+ assert_eq!(inline_refusal(&mcp("db", "read_rows", json!({"filter": {"SQL": "select 1"}}))), Some(RUNS));
+ assert_eq!(inline_refusal(&mcp("notes", "save_note", json!({"items": [{"code": "x"}]}))), Some(RUNS));
+ // 3. Outward or destructive names
+ assert_eq!(inline_refusal(&mcp("x", "Remove_Item", json!({}))), Some(OUTWARD));
+ assert_eq!(inline_refusal(&mcp("x", "create_post", json!({}))), Some(OUTWARD));
+ assert_eq!(inline_refusal(&mcp("x", "pay_invoice", json!({}))), Some(OUTWARD));
+ }
+
+ /// The 0.9.14 hardening (Rigel's holes 1–4 on #646): one row per new rule, each on a tool name
+ /// no older layer refuses, with the reason it must give.
+ fn hardening_rows() -> Vec<(&'static str, Value, &'static str)> {
+ let note = |args: Value| mcp("notes", "save_note", args);
+ let http = |args: Value| mcp("http", "http_request", args);
+ let url = "https://api.example.com/items/1";
+ vec![
+ // 1. Command keys by containment or word
+ ("key command_line", note(json!({"command_line": "ls -la"})), RUNS),
+ ("key commandLine, nested", note(json!({"opts": {"commandLine": "ls -la"}})), RUNS),
+ ("key shell_command", note(json!({"shell_command": "whoami"})), RUNS),
+ ("key cmdline", note(json!({"cmdline": "whoami"})), RUNS),
+ ("key bash_command", note(json!({"bash_command": "whoami"})), RUNS),
+ ("key exec_args in a list", note(json!({"steps": [{"exec_args": ["x"]}]})), RUNS),
+ ("key user_script", note(json!({"user_script": "x()"})), RUNS),
+ // 2. camelCase push-family words
+ ("key pushToOrigin", note(json!({"pushToOrigin": true})), PUSHES),
+ ("key mergeBranch", note(json!({"mergeBranch": "dev"})), PUSHES),
+ ("value forcePush", note(json!({"op": "forcePush"})), PUSHES),
+ ("value HTTPPush", note(json!({"op": "HTTPPush"})), PUSHES),
+ ("tool createTag", mcp("git_ops", "createTag", json!({})), PUSHES),
+ ("tool v2Deploy", mcp("site", "v2Deploy", json!({})), PUSHES),
+ // 3. Outward names
+ ("submit_form", mcp("x", "submit_form", json!({})), OUTWARD),
+ ("transfer_funds", mcp("x", "transfer_funds", json!({})), OUTWARD),
+ ("tweet", mcp("x", "tweet", json!({})), OUTWARD),
+ ("share_page", mcp("x", "share_page", json!({})), OUTWARD),
+ ("invite_user", mcp("x", "invite_user", json!({})), OUTWARD),
+ ("forward_message", mcp("x", "forward_message", json!({})), OUTWARD),
+ ("upload_file", mcp("x", "upload_file", json!({})), OUTWARD),
+ ("wipe_disk", mcp("x", "wipe_disk", json!({})), OUTWARD),
+ ("terminate_instance", mcp("x", "terminate_instance", json!({})), OUTWARD),
+ ("revoke_token", mcp("x", "revoke_token", json!({})), OUTWARD),
+ ("purchase_item", mcp("x", "purchase_item", json!({})), OUTWARD),
+ // 4. HTTP verbs that change something
+ ("method DELETE", http(json!({"url": url, "method": "DELETE"})), OUTWARD),
+ ("method PUT", http(json!({"url": url, "method": "PUT"})), OUTWARD),
+ ("method PATCH", http(json!({"url": url, "method": "PATCH"})), OUTWARD),
+ ("method POST", http(json!({"url": url, "method": "POST"})), OUTWARD),
+ ("httpMethod post, nested, no url", mcp("api", "call", json!({"options": {"httpMethod": " post "}})), OUTWARD),
+ ("method CONNECT on a URL", http(json!({"url": url, "method": "CONNECT"})), OUTWARD),
+ ("method as a list on a URL", http(json!({"url": url, "method": ["GET", "DELETE"]})), OUTWARD),
+ ]
+ }
+
+ #[test]
+ fn every_0914_hardening_row_needs_the_full_card() {
+ let rows = hardening_rows();
+ assert_eq!(rows.len(), 31);
+ for (name, d, why) in rows {
+ assert_eq!(inline_refusal(&d), Some(why), "{name}");
+ }
+ }
+
+ /// What the 0.9.14 rules must not catch: a read, a `description` key (it holds "script"), a
+ /// camelCase key with no push word, "Pushkin" in a hump, and a `method` that isn't HTTP.
+ #[test]
+ fn the_0914_hardening_keeps_ordinary_steps_inline() {
+ let url = "https://api.example.com/items/1";
+ for (name, d) in [
+ ("method GET on a URL", mcp("http", "http_request", json!({"url": url, "method": "get"}))),
+ ("method HEAD on a URL", mcp("http", "http_request", json!({"url": url, "method": "HEAD"}))),
+ ("a description key", mcp("linear", "create_issue", json!({"title": "Bug", "description": "Steps to reproduce"}))),
+ ("a camelCase key", mcp("notion", "create_page", json!({"pageTitle": "Reading list"}))),
+ ("Pushkin in a hump", mcp("notion", "create_page", json!({"title": "readPushkin"}))),
+ ("a method that isn't HTTP", mcp("stats", "summarize", json!({"method": "median"}))),
+ ] {
+ assert_eq!(inline_refusal(&d), None, "{name}");
+ }
+ assert_eq!(words("pushToOrigin HTTPPush v2Deploy Pushkin PUSHKIN git_push"), ["push", "to", "origin", "http", "push", "v2", "deploy", "pushkin", "pushkin", "git", "push"]);
+ for (name, d) in realistic_rows() {
+ assert_eq!(inline_refusal(&d), None, "{name}");
+ }
+ }
+
+ /// Realistic steps that still get Allow once, so the rule isn't "always no".
+ fn realistic_rows() -> Vec<(&'static str, Value)> {
+ vec![
+ (
+ "a file write inside the bot's folder",
+ json!({"source": "claude_builtin", "tool": "Write", "outside_folder": false, "arguments": {"file_path": "notes/todo.md", "content": "Buy milk\nCall Ana"}}),
+ ),
+ ("a read-only fetch", mcp("fetch", "fetch", json!({"url": "https://example.com/docs", "max_length": 5000}))),
+ ("a page that mentions Pushkin", mcp("notion", "create_page", json!({"title": "Pushkin reading list", "parent": {"page_id": "abc"}}))),
+ ]
+ }
+
+ #[test]
+ fn realistic_steps_may_still_be_allowed_inline() {
+ for (name, d) in realistic_rows() {
+ assert_eq!(inline_refusal(&d), None, "{name}");
+ }
+ }
+
+ #[test]
+ fn avatars_are_the_saved_sprite_or_null() {
+ let avatars: HashMap<String, String> = [("a".to_string(), "architect".to_string()), ("b".to_string(), " ".to_string())].into();
+ assert_eq!(avatar_of(&avatars, Some("a")), json!("architect"));
+ assert_eq!(avatar_of(&avatars, Some("b")), Value::Null);
+ assert_eq!(avatar_of(&avatars, Some("gone")), Value::Null);
+ assert_eq!(avatar_of(&avatars, Some("")), Value::Null);
+ assert_eq!(avatar_of(&avatars, None), Value::Null);
+ }
+
+ #[test]
+ fn etags_match_weakly_and_ignore_now() {
+ let a = json!({"counts": {"needs_you": 1}});
+ let tag = etag_of(&a);
+ assert!(tag.starts_with("W/\"g-"));
+ assert_eq!(tag, etag_of(&a.clone()));
+ assert_ne!(tag, etag_of(&json!({"counts": {"needs_you": 2}})));
+ assert!(matches(Some(&tag), &tag));
+ assert!(matches(Some(&tag.replace("W/", "")), &tag));
+ assert!(matches(Some(&format!("\"other\", {tag}")), &tag));
+ assert!(matches(Some("*"), &tag));
+ assert!(!matches(Some("W/\"g-0\""), &tag));
+ assert!(!matches(None, &tag));
+ }
+
+ #[test]
+ fn paths_follow_the_nudge() {
+ assert_eq!(app_path("s", &json!({"channel_id": "c 1"}), "k", Some("ap")), "/s/s/c/c%201?card=ap");
+ assert_eq!(app_path("s", &json!({"thread_id": "t1"}), "k1", Some("ap")), "/s/s/b/k1/t/t1?card=ap");
+ assert_eq!(app_path("s", &json!({"direct_kwant_id": "k2"}), "k1", None), "/s/s/b/k2");
+ assert_eq!(app_path("s", &json!({}), "", None), "/s/s/inbox");
+ }
+
+ #[test]
+ fn lines_are_short_one_line_and_masked() {
+ assert_eq!(line("a\n b", 10), "a b");
+ assert!(!line("token sk-ant-api03-abcdefghijklmnop1234", 120).contains("sk-ant"));
+ assert_eq!(line(&"x".repeat(200), 10).chars().count(), 10);
+ }
+}
diff --git a/src/server/missions/watch.rs b/src/server/missions/watch.rs
index ef355b66..dc3aa7a4 100644
--- a/src/server/missions/watch.rs
+++ b/src/server/missions/watch.rs
@@ -1316,6 +1316,19 @@ pub async fn resume_after_restart(state: &AppState) {
/// latest check that left something for the person, while that is still open. Each has the away
/// feed's keys (`timestamp`, `link`) and the contract's (`at`, `mission_id`, `task_id`, `thread_id`).
pub async fn waiting_items(state: &AppState, space: &SpaceId) -> Vec<Value> {
+ waiting_items_in(state, Some(space)).await.into_iter().map(|(_, v)| v).collect()
+}
+
+/// [`waiting_items`] of every space in one pass, by space id (the desktop glance).
+pub async fn waiting_items_by_space(state: &AppState) -> HashMap<String, Vec<Value>> {
+ let mut out: HashMap<String, Vec<Value>> = HashMap::new();
+ for (space, v) in waiting_items_in(state, None).await {
+ out.entry(space).or_default().push(v);
+ }
+ out
+}
+
+async fn waiting_items_in(state: &AppState, only: Option<&SpaceId>) -> Vec<(String, Value)> {
let mut out = Vec::new();
let mut seen = HashSet::new();
for c in state.db.watch_checks_needing_you(200).await.unwrap_or_default() {
@@ -1323,7 +1336,7 @@ pub async fn waiting_items(state: &AppState, space: &SpaceId) -> Vec<Value> {
continue;
}
let Ok(Some(m)) = state.db.get_mission(&c.mission_id).await else { continue };
- if m.space_id != space.as_str() || matches!(m.status.as_str(), "done" | "cancelled") {
+ if only.is_some_and(|s| m.space_id != s.as_str()) || matches!(m.status.as_str(), "done" | "cancelled") {
continue;
}
// A newer check of the mission that found nothing for the person closes the item
@@ -1336,7 +1349,7 @@ pub async fn waiting_items(state: &AppState, space: &SpaceId) -> Vec<Value> {
}
let first = actions_of(&c).into_iter().find(|a| a["kind"] == "needs_you");
let at = c.finished_at.unwrap_or(c.started_at);
- out.push(json!({
+ out.push((m.space_id.clone(), json!({
"kind": "watch", "id": c.id, "kwant_id": c.kwant_id,
"kwant_name": super::name_of(state, Some(&c.kwant_id)).await.unwrap_or_else(|| "A bot".into()),
"title": clip(&clean(&m.title), 120), "summary": inbox["line"], "status": "open",
@@ -1344,7 +1357,7 @@ pub async fn waiting_items(state: &AppState, space: &SpaceId) -> Vec<Value> {
"mission_id": m.id, "task_id": first.map(|a| a["task_id"].clone()),
"thread_id": m.thread_id,
"link": {"thread_id": m.thread_id, "channel_id": m.channel_id, "direct_kwant_id": m.direct_kwant_id},
- }));
+ })));
}
out
}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 38d7cc88..c96f552c 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -43,6 +43,7 @@ pub mod skills;
pub mod spaces;
pub mod asks;
pub mod away;
+pub mod glance;
pub mod computer;
pub mod mcp_directory;
pub mod mcp_suggest;
@@ -623,6 +624,9 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/tool-notes/:id", axum::routing::patch(tool_notes::edit).delete(tool_notes::delete))
.route("/api/away/seen", post(away::seen))
.route("/api/inbox", get(inbox::get))
+ // The desktop island (0.9.13): what needs you, works and just finished, in every space
+ .route("/api/glance", get(glance::get))
+ .route("/api/glance/ask", post(glance::ask))
.route("/api/events", get(sse::sse_handler))
.merge(show_once::routes::router())
.fallback(crate::embedded::static_handler)
diff --git a/tests/glance_test.rs b/tests/glance_test.rs
new file mode 100644
index 00000000..b045ee94
--- /dev/null
+++ b/tests/glance_test.rs
@@ -0,0 +1,664 @@
+//! The desktop island's glance (0.9.13): `GET /api/glance` and `POST /api/glance/ask`, and the
+//! approval and question calls the desktop app makes with the person's cookie.
+
+use axum::{
+ body::{to_bytes, Body},
+ extract::ConnectInfo,
+ http::{HeaderMap, Request, StatusCode},
+ Router,
+};
+use chrono::Utc;
+use kwnt::{
+ broker::{ApprovalDecision, ApprovalRequest, PermissionBroker},
+ config::Config,
+ db::{
+ models::{NewApproval, NewChannel, NewKwant, NewMessage, UpdateKwant},
+ questions::QuestionPlace,
+ spaces::{NewSpace, SpaceId},
+ threads::NewDelegation,
+ Database,
+ },
+ drivers::events::{RuntimeEvent, TurnTag},
+ router::LayaRouter,
+ server::{
+ activity::TurnActivity,
+ auth::{ApiToken, Require},
+ continuity::{SelfScope, TurnOrigin},
+ create_router, mcp_runtime,
+ turns::ActiveTurn,
+ AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::collections::BTreeSet;
+use std::net::SocketAddr;
+use std::sync::Arc;
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+const TOKEN: &str = "glance-test-token-0123456789abcdef";
+const REMOTE: &str = "203.0.113.9:40000";
+const SECRET: &str = "sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789";
+
+async fn setup() -> (Router, AppState, TempDir) {
+ let tmp = tempdir().unwrap();
+ let data = tmp.path().to_path_buf();
+ let db = Database::init(&data).await.unwrap();
+ db.set_setting("keep_going_turns", "0").await.unwrap();
+ db.set_space_approvals(&SpaceId::default_space(), "ask").await.unwrap();
+ let config = Config { data_dir: data.clone(), ..Config::default() };
+ let mut state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(data.join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ state.api_token = Arc::new(ApiToken::for_tests(TOKEN, Require::Auto, config.port));
+ (create_router(state.clone()), state, tmp)
+}
+
+#[derive(Default)]
+struct Req<'a> {
+ body: Option<Value>,
+ /// From another machine (the desktop app reaching a server), else from loopback.
+ remote: bool,
+ bearer: Option<&'a str>,
+ cookie: Option<&'a str>,
+ origin: Option<&'a str>,
+ if_none_match: Option<&'a str>,
+}
+
+async fn send(app: &Router, method: &str, uri: &str, r: Req<'_>) -> (StatusCode, HeaderMap, Value) {
+ let host = if r.remote { "kwnt.example.com" } else { "127.0.0.1:8799" };
+ let mut b = Request::builder().method(method).uri(uri).header("host", host);
+ if let Some(t) = r.bearer {
+ b = b.header("authorization", format!("Bearer {t}"));
+ }
+ if let Some(c) = r.cookie {
+ b = b.header("cookie", format!("kwnt_token={c}"));
+ }
+ if let Some(o) = r.origin {
+ b = b.header("origin", o);
+ }
+ if let Some(e) = r.if_none_match {
+ b = b.header("if-none-match", e);
+ }
+ let body = match r.body {
+ Some(v) => {
+ b = b.header("content-type", "application/json");
+ Body::from(v.to_string())
+ }
+ None => Body::empty(),
+ };
+ let mut req = b.body(body).unwrap();
+ if r.remote {
+ req.extensions_mut().insert(ConnectInfo(REMOTE.parse::<SocketAddr>().unwrap()));
+ }
+ let res = app.clone().oneshot(req).await.unwrap();
+ let (status, headers) = (res.status(), res.headers().clone());
+ let bytes = to_bytes(res.into_body(), 1 << 22).await.unwrap();
+ (status, headers, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+async fn glance(app: &Router) -> (Value, String) {
+ let (s, h, v) = send(app, "GET", "/api/glance", Req::default()).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ (v, h["etag"].to_str().unwrap().to_string())
+}
+
+async fn approval(state: &AppState, kwant: &str, tool_name: &str, details: Value) -> (String, tokio::sync::oneshot::Receiver<ApprovalDecision>) {
+ let a = state
+ .db
+ .save_approval(&NewApproval { turn_id: "turn-gone".into(), kwant_id: kwant.into(), tool_name: tool_name.into(), parameters: details })
+ .await
+ .unwrap();
+ let rx = state
+ .broker
+ .request_approval(ApprovalRequest { id: a.id.clone(), kwant_id: kwant.into(), tool_name: tool_name.into(), details: json!({}) })
+ .await;
+ (a.id, rx)
+}
+
+/// Gives a bot a hand-picked face ("" = none), keeping the rest of it.
+async fn set_sprite(state: &AppState, id: &str, sprite: &str) {
+ let k = state.db.get_kwant(id).await.unwrap().unwrap();
+ let input = UpdateKwant {
+ name: k.name,
+ title: k.title,
+ persona_prompt: k.persona_prompt,
+ soul: k.soul,
+ avatar_sprite: sprite.into(),
+ preferred_model: k.preferred_model,
+ };
+ state.db.update_kwant(id, &input).await.unwrap().unwrap();
+}
+
+fn new_bot(name: &str) -> NewKwant {
+ NewKwant {
+ name: name.into(),
+ title: "Helper".into(),
+ persona_prompt: "Helps.".into(),
+ soul: String::new(),
+ avatar_sprite: "ben".into(),
+ driver_type: "api".into(),
+ preferred_model: "auto".into(),
+ }
+}
+
+fn direct(kwant: &str, role: &str, text: &str) -> NewMessage {
+ NewMessage {
+ channel_id: None,
+ direct_kwant_id: Some(kwant.into()),
+ sender_role: role.into(),
+ sender_id: if role == "user" { "PlayerHero".into() } else { kwant.into() },
+ text: text.into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 1,
+ }
+}
+
+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} not in {list}"))
+}
+
+fn ids(list: &Value) -> BTreeSet<String> {
+ list.as_array().unwrap().iter().map(|i| i["id"].as_str().unwrap().to_string()).collect()
+}
+
+#[tokio::test]
+async fn the_glance_lists_what_needs_you_works_and_finished_and_leaks_nothing() {
+ let (app, state, _tmp) = setup().await;
+ let space = SpaceId::default_space();
+ let kwants = state.db.list_kwants(&space).await.unwrap();
+ let (lead, spec) = (kwants[0].clone(), kwants[1].clone());
+ // A face picked by hand, and a bot with none
+ set_sprite(&state, &spec.id, "fox").await;
+ set_sprite(&state, &lead.id, "").await;
+
+ // Empty: every list there, nothing in them
+ let (v, _) = glance(&app).await;
+ assert_eq!(v["counts"], json!({"needs_you": 0, "working": 0, "finished_unseen": 0}));
+ for k in ["needs_you", "working", "finished"] {
+ assert_eq!(v[k], json!([]), "{k}");
+ }
+ assert!(v["now"].as_str().is_some());
+
+ // Needs you: a question in a team chat, and approvals of every kind
+ 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(), spec.id.clone()],
+ routing_mode: "auto".into(),
+ })
+ .await
+ .unwrap();
+ let place = QuestionPlace { kwant_id: spec.id.clone(), channel_id: Some(chan.id.clone()), ..Default::default() };
+ let choices: Vec<String> = (1..=8).map(|i| format!("Option {i}")).collect();
+ let q = state.db.create_question(&place, "Which one ships tonight?", &choices).await.unwrap();
+ let mcp = |server: &str, tool: &str, args: Value| json!({"source": "mcp", "server": server, "tool": tool, "arguments": args});
+ let (plain, _r1) = approval(&state, &lead.id, "mcp__notion__create_page", mcp("notion", "create_page", json!({"title": "Notes", "api_key": SECRET}))).await;
+ let mut pay = mcp("stripe", "create_invoice", json!({"amount": 500}));
+ pay["payment_reason"] = json!("Sends an invoice for $5");
+ let (money, _r2) = approval(&state, &lead.id, "mcp__stripe__create_invoice", pay).await;
+ let mut prod = mcp("db", "query", json!({"sql": "delete from users"}));
+ prod["prod_floor"] = json!({"server": "db"});
+ let (floor, _r3) = approval(&state, &lead.id, "mcp__db__query", prod).await;
+ let push = mcp("github", "create_or_update_file", json!({"owner": "o", "repo": "r", "path": "a.md", "content": "x", "message": "m", "branch": "main"}));
+ let (pushes, _r4) = approval(&state, &lead.id, "mcp__github__create_or_update_file", push).await;
+ let mut risky = mcp("notion", "delete_page", json!({"id": "p1"}));
+ risky["smart_reason"] = json!("Deletes a page");
+ let (high, _r5) = approval(&state, &lead.id, "mcp__notion__delete_page", risky).await;
+ let shell = json!({"source": "local_shell", "tool": "shell", "arguments": {"command": format!("curl -H 'x: {SECRET}' x && git push")}});
+ let (cmd, _r6) = approval(&state, &lead.id, "shell", shell).await;
+
+ // Working: a running turn with a tool step whose command holds a key
+ let (tx, _keep) = tokio::sync::broadcast::channel(16);
+ let tag = TurnTag { turn_id: "turn-glance-1".into(), kwant_id: spec.id.clone(), context_id: spec.id.clone(), thread_id: None };
+ let activity = TurnActivity::start(tx, tag);
+ activity.observe(&RuntimeEvent::ToolCallPending { id: "1".into(), name: "Bash".into(), args: json!({"command": format!("export KEY={SECRET}; ls")}) });
+ state.turns.set_turn(ActiveTurn {
+ turn_id: "turn-glance-1".into(),
+ kwant_id: spec.id.clone(),
+ context_id: spec.id.clone(),
+ thread_id: None,
+ state: "running".into(),
+ since: Utc::now(),
+ purpose: None,
+ audit: None,
+ });
+ // The hidden decide-first round and a queued turn aren't working
+ for (id, st, purpose) in [("turn-decide", "running", Some("decide".to_string())), ("turn-queued", "queued", None)] {
+ state.turns.set_turn(ActiveTurn {
+ turn_id: id.into(),
+ kwant_id: lead.id.clone(),
+ context_id: lead.id.clone(),
+ thread_id: None,
+ state: st.into(),
+ since: Utc::now(),
+ purpose,
+ audit: None,
+ });
+ }
+
+ // Finished: a hand-off with a result
+ let (_thread, d) = state
+ .db
+ .create_delegation(&NewDelegation {
+ lead_kwant_id: lead.id.clone(),
+ specialist_kwant_id: spec.id.clone(),
+ origin_channel_id: None,
+ origin_kwant_id: Some(lead.id.clone()),
+ origin_thread_id: None,
+ team_id: None,
+ task: "do the brief".into(),
+ title: "Write the brief".into(),
+ continue_lead: false,
+ depth: 1,
+ follow_up_at: None,
+ })
+ .await
+ .unwrap();
+ assert!(state.db.mark_delegation_running(&d.id).await.unwrap());
+ let m = state.db.insert_message(&direct(&spec.id, "kwant", &format!("Done. key {SECRET}"))).await.unwrap();
+ assert!(state.db.finish_delegation(&d.id, "completed", None, Some(&m.id)).await.unwrap());
+
+ // Ask targets: the bot the person wrote to last comes first
+ state.db.insert_message(&direct(&spec.id, "user", "hi")).await.unwrap();
+
+ let (v, _) = glance(&app).await;
+ println!("GLANCE_SAMPLE {}", serde_json::to_string_pretty(&v).unwrap());
+ let text = v.to_string();
+ assert!(!text.contains("sk-ant"), "no secret anywhere: {text}");
+ assert!(!text.contains("delete from users") && !text.contains("Done. key"), "no arguments or message bodies: {text}");
+
+ // Needs you is exactly what /api/away lists as waiting
+ let (_, _, away) = send(&app, "GET", "/api/away", Req::default()).await;
+ assert_eq!(ids(&v["needs_you"]), ids(&away["waiting"]));
+ assert_eq!(v["counts"]["needs_you"], away["unseen"]["waiting"]);
+ assert_eq!(v["counts"]["needs_you"], 7);
+
+ let qi = find(&v["needs_you"], &q.id);
+ assert_eq!(qi["kind"], "question");
+ assert_eq!(qi["space_id"], "spc_default");
+ assert_eq!(qi["kwant_id"], spec.id);
+ assert_eq!(qi["title"], "Which one ships tonight?");
+ assert_eq!(qi["approval"], Value::Null);
+ assert_eq!(qi["question"]["choices"].as_array().unwrap().len(), 6);
+ assert_eq!(qi["question"]["choices_total"], 8);
+ assert_eq!(qi["question"]["allow_text"], true);
+ assert_eq!(qi["path"], format!("/s/spc_default/c/{}?card={}", chan.id, q.id));
+ for k in ["space_name", "kwant_name", "since"] {
+ assert!(qi[k].as_str().is_some_and(|s| !s.is_empty()), "{k}: {qi}");
+ }
+
+ let inline = |id: &str| find(&v["needs_you"], id)["approval"]["can_allow_inline"].clone();
+ assert_eq!(inline(&plain), true);
+ assert_eq!(find(&v["needs_you"], &plain)["approval"]["risk"], "normal");
+ for (name, id) in [("money", &money), ("production floor", &floor), ("push", &pushes), ("risky", &high), ("shell", &cmd)] {
+ assert_eq!(inline(id), false, "{name}");
+ let a = &find(&v["needs_you"], id)["approval"];
+ assert_eq!(a["risk"], "high", "{name}");
+ assert!(a["why_open"].as_str().is_some_and(|w| !w.is_empty()), "{name}: {a}");
+ }
+ assert_eq!(find(&v["needs_you"], &plain)["path"], format!("/s/spc_default/b/{}?card={plain}", lead.id));
+
+ // Working: the running turn only, its step in plain words
+ assert_eq!(v["counts"]["working"], 1);
+ let w = &v["working"][0];
+ assert_eq!(w["kwant_id"], spec.id);
+ assert_eq!(w["space_id"], "spc_default");
+ assert_eq!(w["path"], format!("/s/spc_default/b/{}", spec.id));
+ assert!(w["step"].as_str().is_some_and(|s| !s.is_empty()), "{w}");
+ assert!(w["started_at"].as_str().is_some());
+
+ // Finished: unseen, linked to its result
+ assert_eq!(v["counts"]["finished_unseen"], 1);
+ let f = find(&v["finished"], &d.id);
+ assert_eq!(f["title"], "Write the brief");
+ assert_eq!(f["unseen"], true);
+ assert_eq!(f["kwant_id"], spec.id);
+ assert!(f["finished_at"].as_str().is_some());
+ assert!(f["check"].is_null() || ["verified", "not_checked", "failed"].contains(&f["check"]["status"].as_str().unwrap()));
+
+ // Marking the space seen makes it seen
+ let (s, _, _) = send(&app, "POST", "/api/away/seen", Req::default()).await;
+ assert_eq!(s, StatusCode::OK);
+ let (v2, _) = glance(&app).await;
+ assert_eq!(find(&v2["finished"], &d.id)["unseen"], false);
+ assert_eq!(v2["counts"]["finished_unseen"], 0);
+
+ let targets = v["ask_targets"].as_array().unwrap();
+ assert!(targets.len() <= 8 && !targets.is_empty());
+ assert_eq!(targets[0]["kwant_id"], spec.id);
+ assert_eq!(targets[0]["space_id"], "spc_default");
+
+ // Every item that names a bot carries its saved face, or null when it has none
+ let face = |id: &str| match id {
+ i if i == spec.id => json!("fox"),
+ i if i == lead.id => Value::Null,
+ i => kwants.iter().find(|k| k.id == i && !k.avatar_sprite.is_empty()).map_or(Value::Null, |k| json!(k.avatar_sprite)),
+ };
+ for list in ["needs_you", "working", "finished", "ask_targets"] {
+ let items = v[list].as_array().unwrap();
+ assert!(!items.is_empty(), "{list}");
+ for it in items {
+ let id = it["kwant_id"].as_str().unwrap();
+ assert_eq!(it.get("avatar"), Some(&face(id)), "{list}: {it}");
+ }
+ }
+ assert_eq!(qi["avatar"], "fox");
+ assert_eq!(find(&v["needs_you"], &plain)["avatar"], Value::Null);
+ assert_eq!(w["avatar"], "fox");
+ assert_eq!(f["avatar"], "fox");
+ assert_eq!(targets[0]["avatar"], "fox");
+ drop(activity);
+}
+
+#[tokio::test]
+async fn an_unchanged_glance_is_a_304() {
+ let (app, state, _tmp) = setup().await;
+ let (_, tag) = glance(&app).await;
+ assert!(tag.starts_with("W/\""), "{tag}");
+ let (s, h, v) = send(&app, "GET", "/api/glance", Req { if_none_match: Some(&tag), ..Default::default() }).await;
+ assert_eq!(s, StatusCode::NOT_MODIFIED, "{v}");
+ assert_eq!(h["etag"].to_str().unwrap(), tag);
+ assert_eq!(v, Value::Null, "no body");
+ // `now` moves, the tag doesn't
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ assert_eq!(glance(&app).await.1, tag);
+
+ // Something new: a fresh tag and the full body
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();
+ let place = QuestionPlace { kwant_id: bot.id.clone(), direct_kwant_id: Some(bot.id.clone()), ..Default::default() };
+ state.db.create_question(&place, "Go?", &["Yes".into()]).await.unwrap();
+ let (s, h, v) = send(&app, "GET", "/api/glance", Req { if_none_match: Some(&tag), ..Default::default() }).await;
+ assert_eq!(s, StatusCode::OK);
+ let tag = h["etag"].to_str().unwrap().to_string();
+ assert_ne!(tag, "");
+ assert_eq!(v["counts"]["needs_you"], 1);
+
+ // A new face is a change too
+ set_sprite(&state, &bot.id, "owl").await;
+ let (s, h, v) = send(&app, "GET", "/api/glance", Req { if_none_match: Some(&tag), ..Default::default() }).await;
+ assert_eq!(s, StatusCode::OK);
+ assert_ne!(h["etag"].to_str().unwrap(), tag);
+ assert_eq!(v["needs_you"][0]["avatar"], "owl");
+}
+
+#[tokio::test]
+async fn archived_spaces_are_left_out() {
+ let (app, state, _tmp) = setup().await;
+ let lab = state.db.create_space(&NewSpace { name: "Lab".into(), icon: "🧪".into(), color: None, this_machine_enabled: true }).await.unwrap();
+ let lab_id = SpaceId::new(&lab.id);
+ let bot = state.db.create_kwant(&lab_id, &new_bot("Labby")).await.unwrap();
+ let place = QuestionPlace { kwant_id: bot.id.clone(), direct_kwant_id: Some(bot.id.clone()), ..Default::default() };
+ let q = state.db.create_question(&place, "Lab question?", &["Yes".into()]).await.unwrap();
+ let (a, _rx) = approval(&state, &bot.id, "mcp__notion__create_page", json!({"source": "mcp", "server": "notion", "tool": "create_page", "arguments": {}})).await;
+ state.db.insert_message(&direct(&bot.id, "user", "hello lab")).await.unwrap();
+
+ let (v, _) = glance(&app).await;
+ let qi = find(&v["needs_you"], &q.id);
+ assert_eq!((qi["space_id"].as_str(), qi["space_name"].as_str()), (Some(lab.id.as_str()), Some("Lab")));
+ assert_eq!(qi["path"], format!("/s/{}/b/{}?card={}", lab.id, bot.id, q.id));
+ find(&v["needs_you"], &a);
+ assert_eq!(v["counts"]["needs_you"], 2);
+ assert_eq!(v["ask_targets"][0]["kwant_id"], bot.id);
+
+ state.db.archive_space(&lab_id).await.unwrap();
+ let (v, _) = glance(&app).await;
+ assert_eq!(v["needs_you"], json!([]), "{v}");
+ assert_eq!(v["counts"]["needs_you"], 0);
+ assert!(!v.to_string().contains(&lab.id), "nothing from the archived space: {v}");
+}
+
+async fn turn_token(state: &AppState) -> String {
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();
+ let scope = SelfScope {
+ kwant_id: bot.id.clone(),
+ kwant_name: bot.name.clone(),
+ origin: Some(TurnOrigin { direct_kwant_id: Some(bot.id.clone()), ..Default::default() }),
+ cancel: Some(tokio_util::sync::CancellationToken::new()),
+ turn_id: Some("turn-glance-bot".into()),
+ sandbox_target: Some(bot.id.clone()),
+ ..Default::default()
+ };
+ mcp_runtime::prepare_turn_with_self(state, &bot, Some("turn-glance-bot".into()), None, Some(scope)).await.unwrap().1
+}
+
+#[tokio::test]
+async fn only_the_person_reads_the_glance_or_asks_from_it() {
+ let (app, state, _tmp) = setup().await;
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();
+ let ask = json!({"space_id": "spc_default", "kwant_id": bot.id, "text": "hi"});
+
+ // A bot's turn token: 403 on both, even from this machine
+ let token = turn_token(&state).await;
+ let (s, _, v) = send(&app, "GET", "/api/glance", Req { bearer: Some(&token), ..Default::default() }).await;
+ assert_eq!((s, v["code"].as_str()), (StatusCode::FORBIDDEN, Some("person_only")), "{v}");
+ let (s, _, v) = send(&app, "POST", "/api/glance/ask", Req { body: Some(ask.clone()), bearer: Some(&token), ..Default::default() }).await;
+ assert_eq!((s, v["code"].as_str()), (StatusCode::FORBIDDEN, Some("person_only")), "{v}");
+
+ // From another machine: no token 401, a wrong one 401, a foreign page's origin 403
+ let (s, _, _) = send(&app, "GET", "/api/glance", Req { remote: true, ..Default::default() }).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED);
+ let (s, _, _) = send(&app, "GET", "/api/glance", Req { remote: true, cookie: Some("nope"), ..Default::default() }).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED);
+ let (s, _, _) = send(&app, "GET", "/api/glance", Req { remote: true, cookie: Some(TOKEN), origin: Some("https://evil.example"), ..Default::default() }).await;
+ assert_eq!(s, StatusCode::FORBIDDEN);
+
+ // The desktop app: the person's cookie (or bearer), no Origin
+ let (s, h, v) = send(&app, "GET", "/api/glance", Req { remote: true, cookie: Some(TOKEN), ..Default::default() }).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(h["cache-control"], "private, no-cache");
+ let (s, _, _) = send(&app, "GET", "/api/glance", Req { remote: true, bearer: Some(TOKEN), ..Default::default() }).await;
+ assert_eq!(s, StatusCode::OK);
+}
+
+#[tokio::test]
+async fn the_desktop_app_answers_with_the_cookie_alone() {
+ let (app, state, _tmp) = setup().await;
+ let kwants = state.db.list_kwants(&SpaceId::default_space()).await.unwrap();
+ let bot = kwants[0].clone();
+ let rust = |body: Value| Req { body: Some(body), remote: true, cookie: Some(TOKEN), ..Default::default() };
+
+ // Allow once on an approval the glance offers inline
+ let (a, rx) = approval(&state, &bot.id, "mcp__notion__create_page", json!({"source": "mcp", "server": "notion", "tool": "create_page", "arguments": {}})).await;
+ let (v, _) = glance(&app).await;
+ assert_eq!(find(&v["needs_you"], &a)["approval"]["can_allow_inline"], true);
+ let (s, _, body) = send(&app, "POST", &format!("/api/approvals/{a}/resolve"), rust(json!({"decision": "allow_once"}))).await;
+ assert_eq!(s, StatusCode::OK, "{body}");
+ assert!(matches!(rx.await, Ok(ApprovalDecision::AllowOnce)));
+ // Deny
+ let (b, rx) = approval(&state, &bot.id, "mcp__notion__create_page", json!({"source": "mcp", "server": "notion", "tool": "create_page", "arguments": {}})).await;
+ let (s, _, body) = send(&app, "POST", &format!("/api/approvals/{b}/resolve"), rust(json!({"decision": "deny"}))).await;
+ assert_eq!(s, StatusCode::OK, "{body}");
+ assert!(matches!(rx.await, Ok(ApprovalDecision::Deny)));
+
+ // A question: by choice index, or in the person's own words
+ let place = QuestionPlace { kwant_id: bot.id.clone(), direct_kwant_id: Some(bot.id.clone()), ..Default::default() };
+ let q1 = state.db.create_question(&place, "Which?", &["Red".into(), "Blue".into()]).await.unwrap();
+ let q2 = state.db.create_question(&place, "Why?", &["Because".into()]).await.unwrap();
+ let (s, _, body) = send(&app, "POST", &format!("/api/questions/{}/answer", q1.id), rust(json!({"choice": 1}))).await;
+ assert_eq!(s, StatusCode::OK, "{body}");
+ let (s, _, body) = send(&app, "POST", &format!("/api/questions/{}/answer", q2.id), rust(json!({"text": "It's simpler"}))).await;
+ assert_eq!(s, StatusCode::OK, "{body}");
+ let (v, _) = glance(&app).await;
+ assert_eq!(v["counts"]["needs_you"], 0, "{v}");
+}
+
+#[tokio::test]
+async fn a_quick_ask_lands_in_the_bots_chat() {
+ let (app, state, _tmp) = setup().await;
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();
+ let rust = |body: Value| Req { body: Some(body), remote: true, cookie: Some(TOKEN), ..Default::default() };
+
+ let (s, _, v) = send(&app, "POST", "/api/glance/ask", rust(json!({"space_id": "spc_default", "kwant_id": bot.id, "text": " What's left today? ", "client_message_id": "island-1"}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["path"], format!("/s/spc_default/b/{}", bot.id));
+ let id = v["user_message_id"].as_str().unwrap().to_string();
+ let m = state.db.get_message(&id).await.unwrap().unwrap();
+ assert_eq!((m.text.as_str(), m.direct_kwant_id.as_deref(), m.sender_role.as_str()), ("What's left today?", Some(bot.id.as_str()), "user"));
+ // The same ask again (a retry) is sent once
+ let (s, _, again) = send(&app, "POST", "/api/glance/ask", rust(json!({"space_id": "spc_default", "kwant_id": bot.id, "text": "What's left today?", "client_message_id": "island-1"}))).await;
+ assert_eq!(s, StatusCode::OK, "{again}");
+ assert_eq!((again["user_message_id"].as_str(), again["deduped"].as_bool()), (Some(id.as_str()), Some(true)));
+
+ // Empty, too long, a bot from another space, an archived space
+ let (s, _, v) = send(&app, "POST", "/api/glance/ask", rust(json!({"space_id": "spc_default", "kwant_id": bot.id, "text": " "}))).await;
+ assert_eq!((s, v["code"].as_str()), (StatusCode::BAD_REQUEST, Some("empty")));
+ let (s, _, v) = send(&app, "POST", "/api/glance/ask", rust(json!({"space_id": "spc_default", "kwant_id": bot.id, "text": "x".repeat(8_001)}))).await;
+ assert_eq!((s, v["code"].as_str()), (StatusCode::BAD_REQUEST, Some("too_long")));
+ let lab = state.db.create_space(&NewSpace { name: "Lab".into(), icon: "🧪".into(), color: None, this_machine_enabled: true }).await.unwrap();
+ let (s, _, v) = send(&app, "POST", "/api/glance/ask", rust(json!({"space_id": lab.id, "kwant_id": bot.id, "text": "hi"}))).await;
+ assert_eq!((s, v["code"].as_str()), (StatusCode::NOT_FOUND, Some("not_found")));
+ let lab_bot = state.db.create_kwant(&SpaceId::new(&lab.id), &new_bot("Labby")).await.unwrap();
+ state.db.archive_space(&SpaceId::new(&lab.id)).await.unwrap();
+ let (s, _, v) = send(&app, "POST", "/api/glance/ask", rust(json!({"space_id": lab.id, "kwant_id": lab_bot.id, "text": "hi"}))).await;
+ assert_eq!(s, StatusCode::CONFLICT, "{v}");
+}
+
+/// The island polls this every 5 s per place: it has to stay cheap with 30 spaces. Prints the
+/// timing (`--nocapture`); the bound is loose because this is a debug build on a shared machine.
+#[tokio::test]
+async fn thirty_busy_spaces_glance_quickly() {
+ let (app, state, _tmp) = setup().await;
+ let mut keep = Vec::new();
+ for i in 0..30 {
+ let s = state.db.create_space(&NewSpace { name: format!("Space {i}"), icon: "📦".into(), color: None, this_machine_enabled: true }).await.unwrap();
+ let sid = SpaceId::new(&s.id);
+ let a = state.db.create_kwant(&sid, &new_bot(&format!("Ana {i}"))).await.unwrap();
+ let b = state.db.create_kwant(&sid, &new_bot(&format!("Ben {i}"))).await.unwrap();
+ let place = QuestionPlace { kwant_id: a.id.clone(), direct_kwant_id: Some(a.id.clone()), ..Default::default() };
+ state.db.create_question(&place, &format!("Ship {i}?"), &["Yes".into(), "No".into()]).await.unwrap();
+ keep.push(approval(&state, &b.id, "mcp__notion__create_page", json!({"source": "mcp", "server": "notion", "tool": "create_page", "arguments": {}})).await);
+ for n in 0..5 {
+ state.db.insert_message(&direct(&a.id, if n % 2 == 0 { "user" } else { "kwant" }, "hello")).await.unwrap();
+ }
+ let (_t, d) = state
+ .db
+ .create_delegation(&NewDelegation {
+ lead_kwant_id: a.id.clone(),
+ specialist_kwant_id: b.id.clone(),
+ origin_channel_id: None,
+ origin_kwant_id: Some(a.id.clone()),
+ origin_thread_id: None,
+ team_id: None,
+ task: "t".into(),
+ title: format!("Task {i}"),
+ continue_lead: false,
+ depth: 1,
+ follow_up_at: None,
+ })
+ .await
+ .unwrap();
+ state.db.mark_delegation_running(&d.id).await.unwrap();
+ let m = state.db.insert_message(&direct(&b.id, "kwant", "done")).await.unwrap();
+ state.db.finish_delegation(&d.id, "completed", None, Some(&m.id)).await.unwrap();
+ }
+ let (v, tag) = glance(&app).await;
+ assert_eq!(v["counts"]["needs_you"], 60, "{}", v["counts"]);
+ let mut full = Vec::new();
+ let mut not_modified = Vec::new();
+ let mut spaces_list = Vec::new();
+ let mut one_away = Vec::new();
+ for _ in 0..20 {
+ let t = std::time::Instant::now();
+ glance(&app).await;
+ full.push(t.elapsed().as_secs_f64() * 1000.0);
+ let t = std::time::Instant::now();
+ let (s, _, _) = send(&app, "GET", "/api/glance", Req { if_none_match: Some(&tag), ..Default::default() }).await;
+ not_modified.push(t.elapsed().as_secs_f64() * 1000.0);
+ assert_eq!(s, StatusCode::NOT_MODIFIED);
+ // Baselines on the same machine at the same moment: one list read, one space's /api/away
+ let t = std::time::Instant::now();
+ let (s, _, _) = send(&app, "GET", "/api/spaces", Req::default()).await;
+ spaces_list.push(t.elapsed().as_secs_f64() * 1000.0);
+ assert_eq!(s, StatusCode::OK);
+ let t = std::time::Instant::now();
+ let (s, _, _) = send(&app, "GET", "/api/away", Req::default()).await;
+ one_away.push(t.elapsed().as_secs_f64() * 1000.0);
+ assert_eq!(s, StatusCode::OK);
+ }
+ let median = |v: &mut Vec<f64>| {
+ v.sort_by(|a, b| a.partial_cmp(b).unwrap());
+ (v[v.len() / 2], v[v.len() * 9 / 10])
+ };
+ let (f50, f90) = median(&mut full);
+ let (n50, n90) = median(&mut not_modified);
+ let (s50, _) = median(&mut spaces_list);
+ let (a50, _) = median(&mut one_away);
+ println!("GLANCE 31 spaces, 60 waiting, 30 finished: 200 median {f50:.1} ms p90 {f90:.1} ms; 304 median {n50:.1} ms p90 {n90:.1} ms; body {} bytes; baseline /api/spaces median {s50:.1} ms, one space's /api/away median {a50:.1} ms", v.to_string().len());
+ assert!(f50 < 1000.0, "{f50} ms");
+}
+
+/// Rigel's round-2 risk-4 rows (#646) plus one row per 0.9.14 rule, read back through
+/// `GET /api/glance`: twenty-three steps that must never get Allow once inline, and four ordinary
+/// ones that still do.
+#[tokio::test]
+async fn risky_steps_never_get_allow_once_and_ordinary_ones_still_do() {
+ let (app, state, _tmp) = setup().await;
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();
+ let mcp = |server: &str, tool: &str, args: Value| json!({"source": "mcp", "server": server, "tool": tool, "arguments": args});
+ let run = |c: &str| mcp("runner", "run", json!({ "command": c }));
+ let rows: Vec<(&str, Value, bool)> = vec![
+ ("git push (two spaces)", run("git push origin main"), false),
+ ("git<TAB>push", run("git\tpush origin main"), false),
+ ("git -C dir push", run("git -C /repo push origin main"), false),
+ ("git -c k=v push", run("git -c core.x=1 push"), false),
+ ("argv [git, push]", mcp("runner", "run", json!({"argv": ["git", "push", "origin", "main"]})), false),
+ ("gh pr merge", run("gh pr merge 5 --squash"), false),
+ ("gh release create", run("gh release create v1"), false),
+ ("gh api -X PUT merge", run("gh api -X PUT repos/o/r/pulls/5/merge"), false),
+ ("git send-pack", run("git send-pack origin main"), false),
+ ("npm publish", run("npm publish"), false),
+ ("cargo publish", run("cargo publish"), false),
+ ("docker push", run("docker push img"), false),
+ ("curl POST git/refs", run("curl -X POST https://api.github.com/repos/o/r/git/refs"), false),
+ ("rm -rf /", run("rm -rf /"), false),
+ ("bitbucket pr_action merge", mcp("bitbucket", "pr_action", json!({"action": "merge"})), false),
+ ("publish_site", mcp("netlify", "publish_site", json!({})), false),
+ ("deploy", mcp("vercel", "deploy", json!({})), false),
+ ("send_email", mcp("gmail", "send_email", json!({})), false),
+ ("delete_page", mcp("notion", "delete_page", json!({})), false),
+ // 0.9.14 hardening, one row per rule
+ ("key commandLine", mcp("notes", "save_note", json!({"commandLine": "ls -la"})), false),
+ ("key pushToOrigin", mcp("notes", "save_note", json!({"pushToOrigin": true})), false),
+ ("transfer_funds", mcp("bank", "transfer_funds", json!({})), false),
+ ("method DELETE", mcp("http", "http_request", json!({"url": "https://api.example.com/items/1", "method": "DELETE"})), false),
+ ("method GET", mcp("http", "http_request", json!({"url": "https://api.example.com/items/1", "method": "GET"})), true),
+ (
+ "a file write inside the bot's folder",
+ json!({"source": "claude_builtin", "tool": "Write", "outside_folder": false, "arguments": {"file_path": "notes/todo.md", "content": "Buy milk\nCall Ana"}}),
+ true,
+ ),
+ ("a read-only fetch", mcp("fetch", "fetch", json!({"url": "https://example.com/docs", "max_length": 5000})), true),
+ ("a page that mentions Pushkin", mcp("notion", "create_page", json!({"title": "Pushkin reading list", "parent": {"page_id": "abc"}})), true),
+ ];
+ assert_eq!(rows.iter().filter(|r| !r.2).count(), 23);
+ let person = |body: Value| Req { body: Some(body), remote: true, cookie: Some(TOKEN), ..Default::default() };
+ // Ten at a time keeps them under the Needs-you cap; each batch is denied before the next
+ for batch in rows.chunks(10) {
+ let mut made = Vec::new();
+ for (name, details, _) in batch {
+ let tool = details["tool"].as_str().unwrap().to_string();
+ made.push((name, approval(&state, &bot.id, &tool, details.clone()).await));
+ }
+ let (v, _) = glance(&app).await;
+ for ((name, (id, _rx)), (_, _, inline)) in made.iter().zip(batch) {
+ let a = &find(&v["needs_you"], id)["approval"];
+ assert_eq!(a["can_allow_inline"], *inline, "{name}: {a}");
+ assert_eq!(a["risk"], if *inline { "normal" } else { "high" }, "{name}");
+ assert_eq!(a["why_open"].is_null(), *inline, "{name}: {a}");
+ }
+ for (_, (id, _rx)) in &made {
+ let (s, _, body) = send(&app, "POST", &format!("/api/approvals/{id}/resolve"), person(json!({"decision": "deny"}))).await;
+ assert_eq!(s, StatusCode::OK, "{body}");
+ }
+ }
+}