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
28b: a Deny ends the tool step "declined", in the person's words (#792)
Oleksandr Ivanchenko0b6e25faa662
diff --git a/docs/live-activity.md b/docs/live-activity.mdindex bbbe0ed2..f9e01eb9 100644--- a/docs/live-activity.md+++ b/docs/live-activity.md@@ -42,7 +42,7 @@ turn's list (keyed by `turn_id`); append it if it's new.|---|---|| `id` | `s1`, `s2`, … in start order, unique within the turn || `kind` | `thinking`, `tool`, `approval`, `human_step`, `note` |-| `status` | `running` (thinking/tool), `waiting` (approval/human_step), `ok`, `failed`, `done`, `declined`, `stopped` (the turn ended while it was open, or an approval timed out) |+| `status` | `running` (thinking/tool), `waiting` (approval/human_step), `ok`, `failed`, `done`, `declined`, `stopped` (the turn ended while it was open, or an approval timed out). A `tool` step the person said no to on its card ends `declined` with the detail "You said no; nothing ran" (0.9.24; before, `failed` with "The user denied this tool call.") || `title` | short, human, already redacted: "Running `cargo test`", "Opening github.com", "Reading …/src/main.rs", "Searching the web for “rust sse”", "Using tool (github)", "Waiting for your approval: Running `rm -rf build`", "Waiting for you: Log in to GitHub" || `tool` | optional. The raw tool name (`Bash`, `mcp__github__create_issue`, `command_execution`) || `detail` | optional. The full command or address, or why the tool failed (redacted, ≤500 chars) |diff --git a/src/db/continuity.rs b/src/db/continuity.rsindex ca0cbeea..7cf5a9bd 100644--- a/src/db/continuity.rs+++ b/src/db/continuity.rs@@ -238,6 +238,8 @@ pub struct RoutineRow {pub last_run_at: Option<DateTime<Utc>>,pub created_at: DateTime<Utc>,pub last_status: Option<String>,+ /// The last run's error (28b round 2); `None` with no run or none recorded.+ pub last_error: Option<String>,/// Its kwant's space; the channel, when set, is in the same one.pub space_id: String,/// Delivers into this thread of its kwant (then `channel_id` is empty).@@ -294,7 +296,8 @@ pub struct NewRoutine {const ROUTINE_SELECT: &str = "SELECT r.id, r.kwant_id, r.channel_id, r.name, r.instructions, r.schedule, r.enabled, \r.next_run_at, r.last_run_at, r.created_at, r.space_id, r.thread_id, r.context_message_id, \r.origin, r.suggestion_id, r.task_class, r.acceptance, r.checks, \- (SELECT status FROM routine_runs x WHERE x.routine_id = r.id ORDER BY x.started_at DESC, x.rowid DESC LIMIT 1) AS last_status \+ (SELECT status FROM routine_runs x WHERE x.routine_id = r.id ORDER BY x.started_at DESC, x.rowid DESC LIMIT 1) AS last_status, \+ (SELECT error FROM routine_runs x WHERE x.routine_id = r.id ORDER BY x.started_at DESC, x.rowid DESC LIMIT 1) AS last_error \FROM routines r";impl Database {diff --git a/src/drivers/activity.rs b/src/drivers/activity.rsindex f322082f..18798ba2 100644--- a/src/drivers/activity.rs+++ b/src/drivers/activity.rs@@ -11,7 +11,7 @@use super::events::{RuntimeEvent, TurnTag};use serde::Serialize;use serde_json::{json, Value};-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use std::time::Instant;/// Most steps kept on one reply; later ones are counted in `dropped`.@@ -88,6 +88,9 @@ pub struct ActivityLog {/// Thinking text not yet streamed, per scope (the `Scoped` tags around it; none for the turn/// itself), sent with that scope's next chunk or when the thinking step ends.held: Vec<(Vec<TurnTag>, String)>,+ /// Indexes of `declined` approval steps already paired with the tool step they refused (28b),+ /// so one Deny ends one tool step `declined`.+ paired: HashSet<usize>,}fn now() -> String {@@ -203,6 +206,7 @@ impl ActivityLog {changed.extend(self.close_thinking());if let Some(i) = self.tools.remove(id) {let (status, why) = step_end(result);+ let card = self.declined_card_for(i, status, why.as_deref());if let Some(why) = why {self.steps[i].detail = Some(cut(&self.redact(&why), MAX_DETAIL));}@@ -213,6 +217,14 @@ impl ActivityLog {.filter(|t| !t.is_empty()).map(|t| cut(&self.redact(t), MAX_TITLE));}+ let status = match card {+ Some(card) => {+ self.paired.insert(card);+ self.steps[i].detail = Some(crate::mcp::DENIED_STEP_DETAIL.to_string());+ "declined"+ }+ None => status,+ };changed.push(self.end(i, status));}}@@ -221,6 +233,27 @@ impl ActivityLog {changed}+ /// The person's Deny behind tool step `i`, which [`step_end`] ended `status` with reason `why`+ /// (28b): when the step failed with the CLI's denial ([`denial_shown`]) and this+ /// turn has a `declined` approval step for the same tool not yet paired with a tool step, that+ /// approval step's index. The card settles before the denial reaches the engine, but the tool+ /// step usually started first, so step order isn't read. A denial with no declined card (kwnt+ /// refused a call that names its own secret files, or a ticket couldn't be stored) wasn't the+ /// person's no: `None`, and the step stays `failed`.+ fn declined_card_for(&self, i: usize, status: &str, why: Option<&str>) -> Option<usize> {+ if status != "failed" || !why.is_some_and(|w| w.starts_with(denial_shown())) {+ return None;+ }+ let tool = self.steps[i].tool.as_deref()?;+ (0..self.steps.len()).find(|j| {+ let s = &self.steps[*j];+ s.kind == "approval"+ && s.status == "declined"+ && s.tool.as_deref() == Some(tool)+ && !self.paired.contains(j)+ })+ }+/// A note from kwnt itself, such as which engine can't show its thinking.pub fn note(&mut self, title: &str) -> Option<Step> {let i = self.push("note", "ok", title.to_string())?;@@ -550,6 +583,15 @@ pub fn with_page_title(mut result: Value, tool: &str, text: &str) -> Value {result}+/// The part of [`crate::mcp::DENIED_TEXT`] a failed step shows, the CLI's own denial: [`step_end`]+/// leaves out [`crate::mcp::NOT_ANOTHER_WAY_TEXT`] (27b), so a Deny is matched on what's left (28b).+fn denial_shown() -> &'static str {+ crate::mcp::DENIED_TEXT+ .strip_suffix(crate::mcp::NOT_ANOTHER_WAY_TEXT)+ .unwrap_or(crate::mcp::DENIED_TEXT)+ .trim_end()+}+/// A finished tool call's result: `None` when it went fine, `Some(why)` when its step is/// `failed` (error, failed, denied or cancelled), with the reason it gave, trimmed, if any. The/// one rule for "a tool failed", shared with the chat's failure line (`server::tool_failures`).@@ -1551,4 +1593,103 @@ mod tests {let failed = json!({"status": "error", "error": "x"});assert_eq!(with_page_title(failed.clone(), "browser_open", &page), failed);}++ /// The CLI's result for a call the person said no to (28b).+ fn denied(id: &str) -> RuntimeEvent {+ RuntimeEvent::ToolCallCompleted {+ id: id.into(),+ result: json!({"status": "error", "error": crate::mcp::with_no_false_claims(crate::mcp::DENIED_TEXT)}),+ }+ }++ /// 28b: a Deny on the card ends the tool step `declined`, in the person's words, whether the+ /// card or the tool step started first.+ #[test]+ fn a_deny_on_the_card_ends_the_tool_step_declined() {+ // The card first, then the tool step+ let mut log = ActivityLog::default();+ log.wait("approval", "t1", "Waiting for your approval: Running `rm -rf build`", Some("Bash"));+ log.settle("t1", "declined");+ log.observe(&pending("a", "Bash", json!({"command": "rm -rf build"})));+ let ended = log.observe(&denied("a"));+ assert_eq!(+ (ended[0].kind, ended[0].status, ended[0].detail.as_deref()),+ ("tool", "declined", Some("You said no; nothing ran"))+ );+ assert_eq!(crate::mcp::DENIED_STEP_DETAIL, "You said no; nothing ran");+ // The tool step first (as the CLI usually sends it), then the card+ let mut log = ActivityLog::default();+ log.observe(&pending("a", "Bash", json!({"command": "rm -rf build"})));+ log.wait("approval", "t1", "Waiting for your approval: Running `rm -rf build`", Some("Bash"));+ log.settle("t1", "declined");+ let ended = log.observe(&denied("a"));+ assert_eq!(+ (ended[0].status, ended[0].detail.as_deref()),+ ("declined", Some(crate::mcp::DENIED_STEP_DETAIL))+ );+ let saved: Vec<_> = log.steps().iter().map(|s| (s.kind, s.status)).collect();+ assert_eq!(saved, vec![("tool", "declined"), ("approval", "declined")]);+ }++ /// 28b: a denial with no declined card (kwnt refused a call naming its own secret files, or a+ /// ticket couldn't be stored) wasn't the person's no: it stays `failed` with the CLI's text.+ /// A card for another tool, or one the person allowed, doesn't count either.+ #[test]+ fn a_denial_without_a_declined_card_stays_failed() {+ let mut log = ActivityLog::default();+ log.observe(&pending("a", "Bash", json!({"command": "cat ~/.kwnt/secrets"})));+ let ended = log.observe(&denied("a"));+ assert_eq!(+ (ended[0].status, ended[0].detail.as_deref()),+ ("failed", Some("The user denied this tool call."))+ );+ assert_eq!(denial_shown(), "The user denied this tool call.");+ log.wait("approval", "t1", "Waiting for your approval: Fetching", Some("WebFetch"));+ log.settle("t1", "declined");+ log.wait("approval", "t2", "Waiting for your approval: Running `ls`", Some("Bash"));+ log.settle("t2", "ok");+ log.observe(&pending("b", "Bash", json!({"command": "ls"})));+ let ended = log.observe(&denied("b"));+ assert_eq!(ended[0].status, "failed");+ // Another failure is never read as a no, even with a declined card for that tool+ log.wait("approval", "t3", "Waiting for your approval: Running `ls`", Some("Bash"));+ log.settle("t3", "declined");+ log.observe(&pending("c", "Bash", json!({"command": "make"})));+ let ended = log.observe(&RuntimeEvent::ToolCallCompleted {+ id: "c".into(),+ result: json!({"status": "error", "error": "exit 2"}),+ });+ assert_eq!((ended[0].status, ended[0].detail.as_deref()), ("failed", Some("exit 2")));+ }++ /// 28b: one Deny ends one tool step: two denied Bash calls and one declined card give one+ /// `declined` step and one `failed` step.+ #[test]+ fn one_declined_card_ends_one_tool_step() {+ let mut log = ActivityLog::default();+ log.observe(&pending("a", "Bash", json!({"command": "rm a"})));+ log.wait("approval", "t1", "Waiting for your approval: Running `rm a`", Some("Bash"));+ log.settle("t1", "declined");+ log.observe(&denied("a"));+ log.observe(&pending("b", "Bash", json!({"command": "rm b"})));+ log.observe(&denied("b"));+ let tools: Vec<_> = log+ .steps()+ .iter()+ .filter(|s| s.kind == "tool")+ .map(|s| (s.status, s.detail.as_deref()))+ .collect();+ assert_eq!(+ tools,+ vec![+ ("declined", Some(crate::mcp::DENIED_STEP_DETAIL)),+ ("failed", Some(denial_shown())),+ ]+ );+ // A second Deny pairs with the second call+ log.wait("approval", "t2", "Waiting for your approval: Running `rm c`", Some("Bash"));+ log.settle("t2", "declined");+ log.observe(&pending("c", "Bash", json!({"command": "rm c"})));+ assert_eq!(log.observe(&denied("c"))[0].status, "declined");+ }}diff --git a/src/mcp/mod.rs b/src/mcp/mod.rsindex ea63cd4a..2ffc08fe 100644--- a/src/mcp/mod.rs+++ b/src/mcp/mod.rs@@ -483,6 +483,9 @@ pub const NO_FALSE_CLAIMS_TEXT: &str ="A step failed or wasn't approved. Don't say it worked or that you checked something you didn't.";/// The step detail of a call nobody answered: the wait is [`APPROVAL_TIMEOUT_SECS`].pub const UNANSWERED_STEP_DETAIL: &str = "Waited 5 minutes for your answer; nothing ran";+/// The step detail of a call the person said no to on its card (28b): the tool step ends+/// `declined`, in the person's words. The bot is still told [`DENIED_TEXT`].+pub const DENIED_STEP_DETAIL: &str = "You said no; nothing ran";/// The step detail of a call a Skill Foundry replay recorded instead of running.pub const REHEARSED_STEP_DETAIL: &str = "Dry run: kwant recorded this call instead of running it";diff --git a/src/server/delivery_check.rs b/src/server/delivery_check.rsindex 3427f6fc..408fae09 100644--- a/src/server/delivery_check.rs+++ b/src/server/delivery_check.rs@@ -906,12 +906,15 @@ fn strip_leads(mut s: &str) -> &str {/// The turn's tool steps, from its saved activity (`{"steps": [...]}`): whether it ran any, its/// last one when that one failed (a refused tool call is a failed step too), and whether the-/// person declined an approval card in it.+/// person declined an approval card in it, or said no to a tool step (28b: a `declined` tool step,+/// with or without a card).pub fn tool_steps_in(activity: Option<&Value>) -> (bool, Option<FailedStep>, bool) {let Some(steps) = activity.and_then(|a| a["steps"].as_array()) else {return (false, None, false);};- let declined = steps.iter().any(|s| s["kind"] == "approval" && s["status"] == "declined");+ let declined = steps+ .iter()+ .any(|s| matches!(s["kind"].as_str(), Some("approval" | "tool")) && s["status"] == "declined");let last = steps.iter().rfind(|s| s["kind"] == "tool" && !matches!(s["status"].as_str(), Some("running" | "waiting")));let failed = last.filter(|s| s["status"] == "failed").map(|s| FailedStep {tool: s["tool"].as_str().unwrap_or("a tool").to_string(),@@ -1938,6 +1941,18 @@ mod tests {assert_eq!(FailedBefore::of_turn(reads.as_ref(), page), none);}+ /// 28b: a tool step the person said no to counts as declined, with or without a card (#781's+ /// no-card refusal has none), and isn't a failed step to follow through.+ #[test]+ fn a_declined_tool_step_counts_as_declined() {+ let activity = json!({"steps": [+ {"kind": "tool", "tool": "Bash", "title": "Running `rm -rf build`", "status": "declined", "detail": "You said no; nothing ran"},+ ]});+ let (_, failed, declined) = tool_steps_in(Some(&activity));+ assert!(declined);+ assert_eq!(failed, None);+ }+/// 27e: a turn on the Home Assistant server "house" with these activity steps.fn house(steps: Value) -> Seen {let activity = json!({ "steps": steps });@@ -2040,6 +2055,20 @@ mod tests {assert!(check(UNLOCKING, None, false, &declined).missing.is_empty());}+ /// 28b x 27e: a Home Assistant change the person said no to (a `declined` tool step, with or+ /// without a card) is never a miss: the turn counts as declined the way routes.rs builds it.+ #[test]+ fn a_home_change_the_person_said_no_to_is_never_a_miss() {+ let steps = json!([{ "kind": "tool", "tool": "mcp__house__intent__HassTurnOff", "status": "declined", "title": "HassTurnOff", "detail": "You said no; nothing ran" }]);+ let (_, failed, declined) = tool_steps_in(Some(&json!({ "steps": steps.clone() })));+ assert!(declined && failed.is_none());+ let seen = Seen { declined, ..house(steps) };+ let v = check(UNLOCKING, None, false, &seen);+ assert!(v.missing.is_empty() && v.continue_with.is_none() && v.home_lines.is_empty(), "{v:?}");+ let then = check(UNLOCKING, None, true, &seen);+ assert!(then.home_lines.is_empty(), "{then:?}");+ }+#[test]fn reads_that_all_failed_continue_once_then_get_kwants_line() {let failed = house(json!([read("failed", SWITCH_MISS)]));diff --git a/src/server/scheduler.rs b/src/server/scheduler.rsindex ce7f0a54..35e46f2d 100644--- a/src/server/scheduler.rs+++ b/src/server/scheduler.rs@@ -61,6 +61,9 @@ pub struct RoutineView {pub next_run_at: Option<DateTime<Utc>>,pub last_run_at: Option<DateTime<Utc>>,pub last_status: Option<String>,+ /// The last run's error, e.g. "You said no to Bash; nothing ran" (28b round 2), so the routine+ /// card can tell a no from a failure. `null`: no run yet, or it had none.+ pub last_error: Option<String>,pub created_at: DateTime<Utc>,/// The schedule in words, e.g. "monthly on the 1st at 09:00 Europe/Berlin".pub schedule_text: String,@@ -102,6 +105,7 @@ impl From<RoutineRow> for RoutineView {next_run_at: r.next_run_at,last_run_at: r.last_run_at,last_status: r.last_status,+ last_error: r.last_error,created_at: r.created_at,}}@@ -667,26 +671,39 @@ pub struct StepSeen {/// "ok", "failed", "unanswered", or anything else (ignored).pub status: &'static str,pub reason: Option<String>,+ /// A "failed" step the person said no to on its card (28b): its reason is the `said_no` sentence, and+ /// a real failure's reason wins over it.+ pub said_no: bool,}/// The run's status from what its turn's steps did, in order (26b; P1: never "ok" when nothing/// ran):/// - any call `unanswered` (its card is still open) → `needs_you`, [`NEEDS_YOU_ERROR`];/// - a call that failed (error, denied, cancelled) with no later "ok" call of the same tool →-/// `incomplete`, with the first such call's reason on one line;+/// `incomplete`, with the first such call's reason on one line. A real failure's reason wins+/// over a "You said no" one (28b round 2), so a no never hides what broke after it;/// - otherwise `ok`.pub fn run_outcome(steps: &[StepSeen]) -> (&'static str, Option<String>) {if steps.iter().any(|s| s.status == "unanswered") {return ("needs_you", Some(NEEDS_YOU_ERROR.to_string()));}- let unfixed = steps.iter().enumerate().find(|(i, s)| {- s.status == "failed"- && !steps[i + 1..]- .iter()- .any(|later| later.status == "ok" && later.tool == s.tool)- });- match unfixed {- Some((_, s)) => {+ let unfixed: Vec<&StepSeen> = steps+ .iter()+ .enumerate()+ .filter(|(i, s)| {+ s.status == "failed"+ && !steps[i + 1..]+ .iter()+ .any(|later| later.status == "ok" && later.tool == s.tool)+ })+ .map(|(_, s)| s)+ .collect();+ let first = unfixed+ .iter()+ .find(|s| !s.said_no)+ .or_else(|| unfixed.first());+ match first {+ Some(s) => {let why = s.reason.as_deref()@@ -709,6 +726,19 @@ pub fn steps_seen(meta: Option<&serde_json::Value>,) -> Vec<StepSeen> {let text = |v: &serde_json::Value| v.as_str().map(str::to_string);+ let activity: &[serde_json::Value] = meta+ .and_then(|m| m["activity"]["steps"].as_array())+ .map(Vec::as_slice)+ .unwrap_or_default();+ // A `denied` call is the person's no only when its card was declined (28b round 2): each+ // declined card of the same tool counts for one call. The pre-push gate, kwnt's secret files,+ // a ticket that couldn't be stored and a wait that ran out record `denied` with no card the+ // person said no on.+ let mut cards_left: Vec<&str> = activity+ .iter()+ .filter(|s| s["kind"] == "approval" && s["status"] == "declined")+ .filter_map(|s| s["tool"].as_str())+ .collect();let mut seen = Vec::new();for c in tool_calls.and_then(|v| v.as_array()).into_iter().flatten() {let status = match c["status"].as_str().unwrap_or("") {@@ -720,7 +750,17 @@ pub fn steps_seen(let tool = text(&c["name"]).unwrap_or_default();let reason = text(&c["error"]).or_else(|| text(&c["result"]));// A refusal's reason is what kwnt told the bot, not news; say what it was instead+ let card = if c["status"] == "denied" {+ cards_left.iter().position(|t| *t == tool)+ } else {+ None+ };+ let said = card.is_some();+ if let Some(k) = card {+ cards_left.remove(k);+ }let reason = match c["status"].as_str() {+ Some("denied") if said => Some(said_no(&tool)),Some("denied") => Some(format!("{tool} was denied")),_ => reason.map(|r| {r.replace(crate::mcp::NO_FALSE_CLAIMS_TEXT, "")@@ -732,28 +772,37 @@ pub fn steps_seen(tool,status,reason,+ said_no: said,});}- for step in meta- .and_then(|m| m["activity"]["steps"].as_array())- .into_iter()- .flatten()- {+ for step in activity {let status = match (step["kind"].as_str(), step["status"].as_str()) {(_, Some("unanswered")) => "unanswered",(Some("tool"), Some("ok")) => "ok",(Some("tool"), Some("failed")) => "failed",+ // The person said no on its card (28b): it didn't run, so the run isn't ok+ (Some("tool"), Some("declined")) => "failed",_ => continue,};+ let tool = text(&step["tool"]).unwrap_or_default();+ // `activity.rs` ends a tool step `declined` only when it paired it with its declined card+ let said = step["status"] == "declined";+ let reason = if said { Some(said_no(&tool)) } else { text(&step["detail"]) };seen.push(StepSeen {- tool: text(&step["tool"]).unwrap_or_default(),+ tool,status,- reason: text(&step["detail"]),+ reason,+ said_no: said,});}seen}+/// A routine run's reason when the person said no to `tool` (28b).+fn said_no(tool: &str) -> String {+ format!("You said no to {tool}; nothing ran")+}+/// The meta key of a routine run's id on each reply of its turn (see `run_routine_turn`).pub(super) const ROUTINE_RUN_KEY: &str = "routine_run";@@ -1170,6 +1219,15 @@ mod run_outcome_tests {tool: tool.into(),status,reason: reason.map(str::to_string),+ said_no: false,+ }+ }++ /// A step the person said no to on its card (28b).+ fn no(tool: &str) -> StepSeen {+ StepSeen {+ said_no: true,+ ..step(tool, "failed", Some(said_no(tool).as_str()))}}@@ -1241,6 +1299,7 @@ mod run_outcome_tests {vec![step("ha__turn_on", "unanswered", None),step("web__get", "failed", Some("502")),+ // no declined card of its own: main's words, not the person's no (28b round 2)step("mail__send", "failed", Some("mail__send was denied")),step("Bash", "unanswered", None),step("Bash", "failed", Some("exit 1")),@@ -1296,4 +1355,93 @@ mod run_outcome_tests {}));}++ /// 28b: a routine whose only step the person said no to on its card isn't ok: it stays+ /// `incomplete`, and its reason says so in the person's words. A Deny on a kwnt tool reads+ /// the same.+ #[test]+ fn a_no_ends_the_run_incomplete_in_the_persons_words() {+ let meta = json!({"activity": {"steps": [+ {"kind": "tool", "status": "declined", "tool": "Bash", "detail": crate::mcp::DENIED_STEP_DETAIL},+ {"kind": "approval", "status": "declined", "tool": "Bash"},+ ]}});+ let seen = steps_seen(None, Some(&meta));+ assert_eq!(seen, vec![no("Bash")]);+ assert_eq!(seen[0].reason.as_deref(), Some("You said no to Bash; nothing ran"));+ assert_eq!(+ run_outcome(&seen),+ ("incomplete", Some("You said no to Bash; nothing ran".into()))+ );+ let calls = json!([{"name": "mail__send", "status": "denied", "result": crate::mcp::DENIED_TEXT}]);+ let card = json!({"activity": {"steps": [{"kind": "approval", "status": "declined", "tool": "mail__send"}]}});+ assert_eq!(+ run_outcome(&steps_seen(Some(&calls), Some(&card))),+ ("incomplete", Some("You said no to mail__send; nothing ran".into()))+ );+ }++ /// 28b round 2: kwnt records `denied` for refusals the person never saw (the pre-push gate,+ /// kwnt's secret files, a ticket it couldn't store, a wait that ran out). Only a declined card+ /// of the same tool makes it the person's no, and each card counts for one call.+ #[test]+ fn a_denied_call_is_the_persons_no_only_with_its_declined_card() {+ let denied = |name: &str| json!({"name": name, "status": "denied", "result": crate::mcp::DENIED_TEXT});+ let cards = |steps: serde_json::Value| json!({"activity": {"steps": steps}});+ // no card at all+ let calls = json!([denied("github__push")]);+ assert_eq!(+ steps_seen(Some(&calls), None),+ vec![step("github__push", "failed", Some("github__push was denied"))]+ );+ // a declined card of the same tool+ let same = cards(json!([{"kind": "approval", "status": "declined", "tool": "github__push"}]));+ assert_eq!(steps_seen(Some(&calls), Some(&same)), vec![no("github__push")]);+ // a declined card of another tool, or a card of the same tool that wasn't declined+ let other = cards(json!([+ {"kind": "approval", "status": "declined", "tool": "Bash"},+ {"kind": "approval", "status": "stopped", "tool": "github__push"},+ {"kind": "approval", "status": "ok", "tool": "github__push"},+ ]));+ let seen = steps_seen(Some(&calls), Some(&other));+ assert_eq!(seen[0], step("github__push", "failed", Some("github__push was denied")));+ // one card, two denied calls of its tool: one no, one plain denial+ let twice = json!([denied("github__push"), denied("github__push")]);+ assert_eq!(+ steps_seen(Some(&twice), Some(&same)),+ vec![no("github__push"), step("github__push", "failed", Some("github__push was denied"))]+ );+ // a CLI builtin pairs by its raw name too+ let bash = json!([denied("Bash")]);+ let bash_card = cards(json!([{"kind": "approval", "status": "declined", "tool": "Bash"}]));+ assert_eq!(steps_seen(Some(&bash), Some(&bash_card))[0], no("Bash"));+ }++ /// 28b round 2: a real failure's reason wins over the person's no, whichever came first; the+ /// no is the reason only when nothing else failed. The run is `incomplete` either way.+ #[test]+ fn a_real_failure_wins_over_a_no_in_the_runs_reason() {+ let http = step("WebFetch", "failed", Some("HTTP 500"));+ assert_eq!(+ run_outcome(&[no("Bash"), http.clone()]),+ ("incomplete", Some("HTTP 500".into()))+ );+ assert_eq!(+ run_outcome(&[http.clone(), no("Bash")]),+ ("incomplete", Some("HTTP 500".into()))+ );+ assert_eq!(+ run_outcome(&[no("Bash")]),+ ("incomplete", Some("You said no to Bash; nothing ran".into()))+ );+ // a failure a later call fixed doesn't count; the no is what's left+ assert_eq!(+ run_outcome(&[no("Bash"), http, step("WebFetch", "ok", None)]),+ ("incomplete", Some("You said no to Bash; nothing ran".into()))+ );+ // two noes: the first one's tool+ assert_eq!(+ run_outcome(&[no("Bash"), no("Write")]),+ ("incomplete", Some("You said no to Bash; nothing ran".into()))+ );+ }}diff --git a/tests/deny_ends_declined_test.rs b/tests/deny_ends_declined_test.rsnew file mode 100644index 00000000..f4855ebe--- /dev/null+++ b/tests/deny_ends_declined_test.rs@@ -0,0 +1,163 @@+//! 28b: a Deny on a card ends the tool step `declined`, in the person's words. A routine whose+//! only step asks for a shell command, which the person denies on its card: the saved reply's+//! tool step is `declined` with "You said no; nothing ran" (not `failed` with the CLI's "The user+//! denied this tool call."), its card is `declined`, the bot was still told the CLI's own text,+//! and the run stays `incomplete` with "You said no to Bash; nothing ran".++mod common;++use common::*;+use kwnt::db::spaces::SpaceId;+use serde_json::{json, Value};+use std::sync::atomic::Ordering;++#[tokio::test]+async fn a_deny_on_the_card_ends_the_step_declined_and_the_run_incomplete() {+ let env = setup().await;+ env.state+ .db+ .set_space_approvals(&SpaceId::default_space(), "ask")+ .await+ .unwrap();+ // Long enough that the card is answered, never timed out+ env.state.approval_wait_ms.store(60_000, Ordering::Relaxed);+ // A shell command always asks; the fake CLI asks for it as Bash, then prints the CLI's denial+ let marker = call_tool_marker(+ "bash",+ json!({"command": "rm -rf DENY28B_BUILD", "description": "clean the build"}),+ );+ let (s, r) = call(+ &env.app,+ "POST",+ "/api/routines",+ Some(json!({"kwant_id": env.a, "name": "Clean", "instructions":+ format!("Clean the build {marker} ASKFIRST ASKAS:Bash REPLYTAG:deny28b"),+ "schedule": {"type": "daily", "time": "03:00", "tz": "UTC"}})),+ )+ .await;+ assert_eq!(s.as_u16(), 201, "{r}");+ let id = r["id"].as_str().unwrap().to_string();+ let (s, run) = call(&env.app, "POST", &format!("/api/routines/{id}/run"), None).await;+ assert_eq!(s.as_u16(), 202, "{run}");+ let run_id = run["id"].as_str().unwrap().to_string();++ // The person presses Deny on the card while it's open (`pending`; `waiting` is only a card+ // whose wait ran out)+ let open = || async {+ env.state+ .db+ .list_approvals(&SpaceId::default_space(), Some("pending"), Some(&env.a))+ .await+ .unwrap()+ };+ wait_for("the card", || async { !open().await.is_empty() }).await;+ let ticket = open().await[0].id.clone();+ let (s, v) = call(+ &env.app,+ "POST",+ &format!("/api/approvals/{ticket}/resolve"),+ Some(json!({"decision": "deny"})),+ )+ .await;+ assert!(s.is_success(), "{v}");++ let find = |runs: Value| {+ runs.as_array()+ .unwrap()+ .iter()+ .find(|r| r["id"] == run_id.as_str())+ .cloned()+ .unwrap_or(Value::Null)+ };+ wait_for("the run to end", || async {+ let (_, runs) = call(&env.app, "GET", &format!("/api/routines/{id}/runs"), None).await;+ let run = find(runs);+ !run.is_null() && run["status"] != "running"+ })+ .await;+ let (_, runs) = call(&env.app, "GET", &format!("/api/routines/{id}/runs"), None).await;+ let run = find(runs);++ // The saved reply: the tool step is the person's no, paired with its declined card+ let reply = env+ .state+ .db+ .get_message(run["message_id"].as_str().expect("the run saved a reply"))+ .await+ .unwrap()+ .unwrap();+ let meta: Value = reply+ .meta+ .as_deref()+ .and_then(|s| serde_json::from_str(s).ok())+ .unwrap_or(Value::Null);+ let steps = meta["activity"]["steps"].as_array().cloned().unwrap_or_default();+ let shown: Vec<_> = steps+ .iter()+ .filter(|s| s["kind"] == "tool" || s["kind"] == "approval")+ .map(|s| (s["kind"].clone(), s["status"].clone(), s["tool"].clone(), s["detail"].clone()))+ .collect();+ let tool = shown.iter().find(|s| s.0 == "tool").unwrap_or_else(|| panic!("{steps:?}"));+ assert_eq!(+ (&tool.1, &tool.2, &tool.3),+ (&json!("declined"), &json!("Bash"), &json!("You said no; nothing ran")),+ "{shown:?}"+ );+ let card = shown.iter().find(|s| s.0 == "approval").unwrap_or_else(|| panic!("{steps:?}"));+ assert_eq!((&card.1, &card.2), (&json!("declined"), &json!("Bash")), "{shown:?}");+ assert_eq!(shown.len(), 2, "{shown:?}");+ // The bot still heard the CLI's own text, word for word+ assert!(+ reply.text.contains(&format!("TOOLDENIED[{}]", kwnt::mcp::DENIED_TEXT)),+ "{}",+ reply.text+ );++ // The routine didn't run its step: never ok, in the person's words+ assert_eq!(+ (&run["status"], &run["error"]),+ (&json!("incomplete"), &json!("You said no to Bash; nothing ran")),+ "{run}"+ );+ // The routine list carries it, so its card can tell a no from a failure (28b round 2)+ let (_, list) = call(&env.app, "GET", "/api/routines", None).await;+ let listed = list.as_array().unwrap().iter().find(|r| r["id"] == id.as_str()).cloned().unwrap_or(Value::Null);+ assert_eq!(+ (&listed["last_status"], &listed["last_error"]),+ (&json!("incomplete"), &json!("You said no to Bash; nothing ran")),+ "{listed}"+ );+}++/// 28b round 2: a routine lists its last run's error next to its status: the error of an+/// `incomplete` run, `null` once a later run is `ok`, and `null` before any run.+#[tokio::test]+async fn the_routine_list_carries_the_last_runs_error() {+ let env = setup().await;+ let (s, r) = call(+ &env.app,+ "POST",+ "/api/routines",+ Some(json!({"kwant_id": env.a, "name": "Digest", "instructions": "Send the digest",+ "schedule": {"type": "daily", "time": "03:00", "tz": "UTC"}})),+ )+ .await;+ assert_eq!(s.as_u16(), 201, "{r}");+ assert_eq!(r["last_error"], Value::Null, "{r}");+ let id = r["id"].as_str().unwrap().to_string();+ let listed = || async {+ let (_, list) = call(&env.app, "GET", "/api/routines", None).await;+ let row = list.as_array().unwrap().iter().find(|r| r["id"] == id.as_str()).cloned().unwrap_or(Value::Null);+ (row["last_status"].clone(), row["last_error"].clone())+ };+ assert_eq!(listed().await, (Value::Null, Value::Null));++ let db = &env.state.db;+ db.start_routine_run(&id, "manual", "incomplete", Some("HTTP 500")).await.unwrap();+ assert_eq!(listed().await, (json!("incomplete"), json!("HTTP 500")));+ let (_, one) = call(&env.app, "GET", &format!("/api/routines/{id}"), None).await;+ assert_eq!(one["last_error"], "HTTP 500", "{one}");++ db.start_routine_run(&id, "manual", "ok", None).await.unwrap();+ assert_eq!(listed().await, (json!("ok"), Value::Null));+}