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.

26b: an approval nobody answered is never "ok" (#766)

Oleksandr Ivanchenkoe3e3c562cde1
diff --git a/src/db/away.rs b/src/db/away.rs
index 28be8d07..29787402 100644
--- a/src/db/away.rs
+++ b/src/db/away.rs
@@ -102,8 +102,9 @@ const FAILED_DELEGATIONS: &str = "d.status IN ('failed', 'interrupted')
AND NOT EXISTS (SELECT 1 FROM attention_closed x WHERE x.kind = 'delegation' AND x.ref_id = d.id)";
const FINISHED_RUNS: &str = "r.status = 'ok'";
/// 22i close rules for a failed routine run: its bot or channel is gone, a later run of the same
-/// routine started (Run now or the next schedule), or it is in `attention_closed`.
-const FAILED_RUNS: &str = "r.status = 'error'
+/// routine started (Run now or the next schedule), or it is in `attention_closed`. 26b: a run whose
+/// step waits on the person (`needs_you`) or failed (`incomplete`) didn't finish either.
+const FAILED_RUNS: &str = "r.status IN ('error', 'incomplete', 'needs_you')
AND k.id IS NOT NULL
AND (rt.channel_id IS NULL OR EXISTS (SELECT 1 FROM channels c WHERE c.id = rt.channel_id))
AND NOT EXISTS (SELECT 1 FROM routine_runs r2 WHERE r2.routine_id = r.routine_id
@@ -288,7 +289,7 @@ impl Database {
pub async fn attention_item_owner(&self, kind: &str, ref_id: &str) -> Result<Option<String>, DbError> {
let sql = match kind {
"delegation" => "SELECT specialist_kwant_id FROM delegations WHERE id = ? AND status IN ('failed', 'interrupted', 'running')",
- "routine_run" => "SELECT rt.kwant_id FROM routine_runs r JOIN routines rt ON rt.id = r.routine_id WHERE r.id = ? AND r.status = 'error'",
+ "routine_run" => "SELECT rt.kwant_id FROM routine_runs r JOIN routines rt ON rt.id = r.routine_id WHERE r.id = ? AND r.status IN ('error', 'incomplete', 'needs_you')",
_ => return Ok(None),
};
Ok(sqlx::query_scalar(sql).bind(ref_id).fetch_optional(&self.pool).await?)
@@ -380,7 +381,7 @@ impl Database {
// A routine posts in its channel's main chat, or its bot's direct chat when it has none
let ids: Vec<String> = sqlx::query_scalar(
"SELECT r.id FROM routine_runs r JOIN routines rt ON rt.id = r.routine_id
- WHERE rt.kwant_id = ?1 AND r.status = 'error'
+ WHERE rt.kwant_id = ?1 AND r.status IN ('error', 'incomplete', 'needs_you')
AND ((?2 IS NOT NULL AND rt.channel_id = ?2) OR (?2 IS NULL AND rt.channel_id IS NULL AND ?3 = ?1))
AND NOT EXISTS (SELECT 1 FROM attention_closed x WHERE x.kind = 'routine_run' AND x.ref_id = r.id)",
)
diff --git a/src/db/continuity.rs b/src/db/continuity.rs
index d2c8c4ff..ca0cbeea 100644
--- a/src/db/continuity.rs
+++ b/src/db/continuity.rs
@@ -1024,6 +1024,53 @@ impl Database {
Ok(row.and_then(|r| r.0))
}
+ /// 26b: routine runs can also end `needs_you` (a step waits on an approval card) or
+ /// `incomplete` (a step failed). SQLite can't widen a CHECK, so the table is rebuilt once with
+ /// every row, column (`note` included) and index; older binaries read and write it as before.
+ pub(super) async fn migrate_run_statuses(&self) -> Result<(), DbError> {
+ let sql: Option<(String,)> = sqlx::query_as(
+ "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'routine_runs'",
+ )
+ .fetch_optional(&self.pool)
+ .await?;
+ if sql.is_none_or(|(sql,)| sql.contains("'needs_you'")) {
+ return Ok(());
+ }
+ let mut tx = self.pool.begin().await?;
+ super::spaces::rebuild(
+ &mut tx,
+ "routine_runs",
+ "CREATE TABLE routine_runs__spaces_new (
+ id TEXT PRIMARY KEY,
+ routine_id TEXT NOT NULL,
+ trigger TEXT NOT NULL CHECK (trigger IN ('schedule', 'manual')),
+ started_at TIMESTAMP NOT NULL,
+ ended_at TIMESTAMP,
+ status TEXT NOT NULL CHECK (status IN ('running', 'ok', 'error', 'skipped', 'needs_you', 'incomplete')),
+ error TEXT,
+ message_id TEXT,
+ note TEXT
+ )",
+ &[
+ "CREATE INDEX IF NOT EXISTS routine_runs_by_routine ON routine_runs (routine_id, started_at)",
+ "CREATE INDEX IF NOT EXISTS routine_runs_by_end ON routine_runs (status, ended_at) WHERE ended_at IS NOT NULL",
+ ],
+ )
+ .await?;
+ tx.commit().await?;
+ Ok(())
+ }
+
+ /// 26b: a manual run's start is the routine's last run too. `next_run_at` is left alone.
+ pub async fn set_routine_last_run(&self, id: &str, at: DateTime<Utc>) -> Result<(), DbError> {
+ sqlx::query("UPDATE routines SET last_run_at = ? WHERE id = ?")
+ .bind(at)
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
pub async fn set_routine_schedule_state(
&self,
id: &str,
diff --git a/src/db/mod.rs b/src/db/mod.rs
index ca87450f..993ea444 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -243,6 +243,9 @@ impl Database {
db.migrate_spend().await?;
// 0.9.0 G2: per-bot monthly budgets (add-only; after usage, parked and routines)
db.migrate_bot_budget().await?;
+ // 26b: routine runs can end `needs_you` or `incomplete` (rebuilds `routine_runs` once;
+ // after the step that adds its `note` column)
+ db.migrate_run_statuses().await?;
// 0.9.0 P5: tool notes (add-only)
db.migrate_tool_notes().await?;
// 0.9.0 P1: mission watches and their checks (add-only)
diff --git a/src/db/schema.sql b/src/db/schema.sql
index f0a0edde..8e45e898 100644
--- a/src/db/schema.sql
+++ b/src/db/schema.sql
@@ -193,7 +193,7 @@ CREATE TABLE IF NOT EXISTS routine_runs (
trigger TEXT NOT NULL CHECK (trigger IN ('schedule', 'manual')),
started_at TIMESTAMP NOT NULL,
ended_at TIMESTAMP,
- status TEXT NOT NULL CHECK (status IN ('running', 'ok', 'error', 'skipped')),
+ status TEXT NOT NULL CHECK (status IN ('running', 'ok', 'error', 'skipped', 'needs_you', 'incomplete')),
error TEXT,
message_id TEXT
);
diff --git a/src/drivers/activity.rs b/src/drivers/activity.rs
index ff3866c4..c5647cb3 100644
--- a/src/drivers/activity.rs
+++ b/src/drivers/activity.rs
@@ -33,7 +33,9 @@ pub struct Step {
pub id: String,
/// "thinking", "tool", "approval", "human_step" or "note".
pub kind: &'static str,
- /// "running", "waiting", "ok", "failed", "done", "declined" or "stopped".
+ /// "running", "waiting", "ok", "failed", "done", "declined", "stopped", "unanswered" (a
+ /// tool call whose approval card nobody answered in time: it didn't run) or "rehearsed" (a
+ /// Skill Foundry dry run recorded the call instead of running it).
pub status: &'static str,
pub title: String,
/// The tool's own name (`Bash`, `mcp__github__create_issue`), for tool and approval steps.
@@ -200,18 +202,18 @@ impl ActivityLog {
RuntimeEvent::ToolCallCompleted { id, result } => {
changed.extend(self.close_thinking());
if let Some(i) = self.tools.remove(id) {
- let failed = failed_reason(result);
- if let Some(Some(why)) = failed {
- self.steps[i].detail = Some(cut(&self.redact(why), MAX_DETAIL));
+ let (status, why) = step_end(result);
+ if let Some(why) = why {
+ self.steps[i].detail = Some(cut(&self.redact(&why), MAX_DETAIL));
}
- if failed.is_none() && self.steps[i].tool.as_deref().is_some_and(opens_page) {
+ if status == "ok" && self.steps[i].tool.as_deref().is_some_and(opens_page) {
self.steps[i].page_title = result["title"]
.as_str()
.map(str::trim)
.filter(|t| !t.is_empty())
.map(|t| cut(&self.redact(t), MAX_TITLE));
}
- changed.push(self.end(i, if failed.is_some() { "failed" } else { "ok" }));
+ changed.push(self.end(i, status));
}
}
_ => {}
@@ -237,12 +239,16 @@ impl ActivityLog {
changed
}
- /// Ends the waiting step for `ref_id` with `status` ("ok", "done", "declined", "stopped").
+ /// Ends the waiting step for `ref_id` with `status` ("ok", "done", "declined", "stopped", or
+ /// "unanswered" for an approval card the turn stopped waiting for, still open for a late answer).
pub fn settle(&mut self, ref_id: &str, status: &'static str) -> Option<Step> {
let i = self
.steps
.iter()
.rposition(|s| s.ref_id.as_deref() == Some(ref_id) && s.is_open())?;
+ if status == "unanswered" {
+ self.steps[i].detail = Some(crate::mcp::UNANSWERED_STEP_DETAIL.to_string());
+ }
Some(self.end(i, status))
}
@@ -561,6 +567,46 @@ pub fn failed_reason(result: &Value) -> Option<Option<&str>> {
)
}
+/// How a finished tool call's step ends, and the detail it shows (26b). A call nobody approved
+/// in time is `unanswered` and a dry-run call `rehearsed`, never "ok": by the result's status
+/// (kwnt's own tools) or by the refusal kwnt gave the engine (the claude CLI reports both as an
+/// error carrying that text). Otherwise `failed` with its reason, as [`failed_reason`], or "ok".
+/// The once-per-turn reminder to the model ([`crate::mcp::NO_FALSE_CLAIMS_TEXT`]) never shows.
+pub fn step_end(result: &Value) -> (&'static str, Option<String>) {
+ let said = |marker: &str| {
+ ["error", "content", "message"]
+ .iter()
+ .any(|k| result[*k].as_str().is_some_and(|t| t.contains(marker)))
+ };
+ let first_sentence = |text: &'static str| text.split_inclusive('.').next().unwrap_or(text);
+ let status = result["status"].as_str().unwrap_or("");
+ let refused = matches!(status, "error" | "failed" | "denied");
+ if status == "unanswered" || (refused && said(first_sentence(crate::mcp::UNANSWERED_TEXT))) {
+ return (
+ "unanswered",
+ Some(crate::mcp::UNANSWERED_STEP_DETAIL.to_string()),
+ );
+ }
+ if status == "rehearsed" || (refused && said(first_sentence(crate::mcp::REHEARSED_TEXT))) {
+ return (
+ "rehearsed",
+ Some(crate::mcp::REHEARSED_STEP_DETAIL.to_string()),
+ );
+ }
+ match failed_reason(result) {
+ None => ("ok", None),
+ Some(why) => (
+ "failed",
+ why.map(|w| {
+ w.replace(crate::mcp::NO_FALSE_CLAIMS_TEXT, "")
+ .trim()
+ .to_string()
+ })
+ .filter(|w| !w.is_empty()),
+ ),
+ }
+}
+
pub fn redact(text: &str, secrets: &[String]) -> String {
let text = crate::mcp::redact(text, secrets);
let text = crate::profiles::classify::mask_credentials(&text);
@@ -1050,6 +1096,76 @@ mod tests {
assert_eq!(ended[0].detail.as_deref(), Some("401 for token ********"));
}
+ /// 26b: a call nobody approved in time didn't run, so its step is `unanswered`, never "ok"
+ /// (and not lumped into "failed"), and says so.
+ #[test]
+ fn an_unanswered_call_is_never_ok() {
+ let mut log = ActivityLog::default();
+ log.observe(&pending("a", "mcp__ha__turn_on", json!({})));
+ let ended = log.observe(&done("a", "unanswered"));
+ assert_eq!(ended[0].status, "unanswered");
+ assert_eq!(
+ ended[0].detail.as_deref(),
+ Some("Waited 5 minutes for your answer; nothing ran")
+ );
+ assert!(crate::mcp::UNANSWERED_STEP_DETAIL
+ .contains(&(crate::mcp::APPROVAL_TIMEOUT_SECS / 60).to_string()));
+ // The claude CLI reports kwnt's refusal as an error carrying its text (and the reminder)
+ log.observe(&pending("b", "mcp__ha__turn_on", json!({})));
+ let refusal = crate::mcp::with_no_false_claims(crate::mcp::UNANSWERED_TEXT);
+ let ended = log.observe(&RuntimeEvent::ToolCallCompleted {
+ id: "b".into(),
+ result: json!({"status": "error", "error": refusal}),
+ });
+ assert_eq!(ended[0].status, "unanswered");
+ assert_eq!(
+ ended[0].detail.as_deref(),
+ Some(crate::mcp::UNANSWERED_STEP_DETAIL)
+ );
+ }
+
+ /// 26b: a Skill Foundry dry run recorded the call instead of running it: its own status.
+ #[test]
+ fn a_rehearsed_call_has_its_own_status() {
+ let mut log = ActivityLog::default();
+ log.observe(&pending("a", "mcp__mail__send", json!({})));
+ let ended = log.observe(&done("a", "rehearsed"));
+ assert_eq!(
+ (ended[0].status, ended[0].detail.as_deref()),
+ ("rehearsed", Some(crate::mcp::REHEARSED_STEP_DETAIL))
+ );
+ log.observe(&pending("b", "Bash", json!({})));
+ let ended = log.observe(&RuntimeEvent::ToolCallCompleted {
+ id: "b".into(),
+ result: json!({"status": "error", "error": crate::mcp::REHEARSED_TEXT}),
+ });
+ assert_eq!(ended[0].status, "rehearsed");
+ }
+
+ /// 26b: the reminder to the model never shows as a step's reason; a denial stays "failed".
+ #[test]
+ fn the_reminder_to_the_model_stays_out_of_details() {
+ let (status, why) = step_end(
+ &json!({"status": "error", "content": crate::mcp::with_no_false_claims("boom: 500")}),
+ );
+ assert_eq!((status, why.as_deref()), ("failed", Some("boom: 500")));
+ let (status, why) = step_end(
+ &json!({"status": "error", "error": crate::mcp::with_no_false_claims(crate::mcp::DENIED_TEXT)}),
+ );
+ assert_eq!(
+ (status, why.as_deref()),
+ ("failed", Some(crate::mcp::DENIED_TEXT))
+ );
+ assert_eq!(
+ step_end(&json!({"status": "ok", "content": "fine"})),
+ ("ok", None)
+ );
+ assert_eq!(
+ step_end(&json!({"status": "error", "content": crate::mcp::NO_FALSE_CLAIMS_TEXT})),
+ ("failed", None)
+ );
+ }
+
#[test]
fn steps_and_thinking_are_capped() {
let mut log = ActivityLog::default();
@@ -1072,6 +1188,17 @@ mod tests {
let w = log.wait("approval", "ap1", "Waiting for your approval: Bash", Some("Bash")).remove(0);
assert_eq!((w.kind, w.status, w.ref_id.as_deref()), ("approval", "waiting", Some("ap1")));
assert_eq!(log.settle("ap1", "ok").unwrap().status, "ok");
+ log.wait(
+ "approval",
+ "ap2",
+ "Waiting for your approval: Bash",
+ Some("Bash"),
+ );
+ let late = log.settle("ap2", "unanswered").unwrap();
+ assert_eq!(
+ (late.status, late.detail.as_deref()),
+ ("unanswered", Some(crate::mcp::UNANSWERED_STEP_DETAIL))
+ );
assert!(log.settle("ap1", "ok").is_none(), "settled once");
log.observe(&pending("t", "Read", json!({})));
log.wait("human_step", "hs1", "Waiting for you to sign in", None);
diff --git a/src/drivers/api.rs b/src/drivers/api.rs
index 64e8c93f..97e0720f 100644
--- a/src/drivers/api.rs
+++ b/src/drivers/api.rs
@@ -1409,7 +1409,7 @@ impl ApiDriver {
),
})
.await;
- results.push(&mut messages, id, name, outcome.text, outcome.status == "ok");
+ results.push(&mut messages, id, name, outcome.model_text(), outcome.status == "ok");
}
}
Err(ApiError {
diff --git a/src/drivers/events.rs b/src/drivers/events.rs
index be4d52d6..b254a4f2 100644
--- a/src/drivers/events.rs
+++ b/src/drivers/events.rs
@@ -349,12 +349,22 @@ pub enum RuntimeEvent {
/// object of `release-090/h4-contract.md` §1 (see `crate::server::bot_status`).
#[serde(rename = "bot_status", alias = "BotStatus")]
BotStatus { kwant_id: String, status: Value },
- /// A routine run started or finished. `status` is "running", "ok", "error" or "skipped".
+ /// A routine run started or finished. `status` is "running", "ok", "error", "skipped",
+ /// "needs_you" (a step waits on an approval card nobody answered, so it didn't run) or
+ /// "incomplete" (a step failed and no later call of that tool worked) (26b).
#[serde(rename = "routine_run", alias = "RoutineRun")]
RoutineRun {
routine_id: String,
run_id: String,
status: String,
+ /// 26b: a "running" run whose turn waits on an approval card right now. Sent `true` when
+ /// the card opens and `false` when it's answered or the turn stops waiting. Old events and
+ /// old clients: missing means `false`.
+ #[serde(default)]
+ waiting: bool,
+ /// The approval card the run waits on, while `waiting`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ approval_id: Option<String>,
},
/// A Mission Control task changed (state, claim, checks, evidence). `task` is the board's Task
/// shape and carries `space_id`.
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
index b86753e5..62a1b4cb 100644
--- a/src/mcp/mod.rs
+++ b/src/mcp/mod.rs
@@ -44,7 +44,8 @@ pub const DEFAULT_TIMEOUT_SECS: i64 = 30;
pub const DEFAULT_MAX_TOOL_ITERATIONS: usize = 25;
/// Longest tool result kept in a message's `tool_calls` record.
pub const RECORD_RESULT_MAX_CHARS: usize = 4000;
-/// How long an MCP tool call waits for the user's approval before it is denied.
+/// How long a tool call waits for the person's approval card. After that the call is `unanswered`:
+/// it didn't run, the card stays open (a late Allow starts a new turn to make it) and the bot is told so.
pub const APPROVAL_TIMEOUT_SECS: u64 = 300;
/// kwnt's permission-prompt tool for the claude CLI, called as `mcp__kwnt__approve`.
pub const PERMISSION_TOOL: &str = "approve";
@@ -462,6 +463,37 @@ pub const DENIED_TEXT: &str = "The user denied this tool call.";
pub const UNANSWERED_TEXT: &str = "No one has answered the approval card for this call yet, so it did not run. \
The card stays open: if the person allows it later, you will be started again to make this same call and continue. \
Don't retry it now. Finish what you can without it, then end your turn saying what you were about to do and why.";
+/// Said once per turn, with the first tool result that failed or didn't run (error, denied,
+/// unanswered), so the model's final reply doesn't claim what didn't happen (26b).
+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 a Skill Foundry replay recorded instead of running.
+pub const REHEARSED_STEP_DETAIL: &str = "Dry run: kwant recorded this call instead of running it";
+
+/// Whether a tool call record's `status` means the call failed or didn't run, so the turn's
+/// reply must not say it worked: `error`, `failed`, `denied`, `cancelled` or `unanswered`.
+/// A `rehearsed` call (a dry run) isn't one: the bot is told to say what it would have done.
+pub fn missed_status(status: &str) -> bool {
+ matches!(
+ status,
+ "error" | "failed" | "denied" | "cancelled" | "unanswered"
+ )
+}
+
+/// Whether a call that ended with record `status` gets the once-per-turn
+/// [`NO_FALSE_CLAIMS_TEXT`] reminder (26b): a failed or unanswered result. A plain denial
+/// doesn't: the person said no and the bot is already told so ([`DENIED_TEXT`]).
+pub fn reminds(status: &str) -> bool {
+ missed_status(status) && status != "denied"
+}
+
+/// `text` with [`NO_FALSE_CLAIMS_TEXT`] after it, on its own line.
+pub fn with_no_false_claims(text: &str) -> String {
+ format!("{}\n\n{NO_FALSE_CLAIMS_TEXT}", text.trim_end())
+}
+
/// What the bot is told in a Skill Foundry replay when a call could change something.
pub const REHEARSED_TEXT: &str = "This is a dry run on a scratch copy of an earlier task: calls that could change \
anything outside the scratch folder (send, publish, sign in, pay, run commands, write elsewhere, other servers' tools) \
@@ -579,6 +611,18 @@ impl McpTurnContext {
}
}
+ /// Whether a call this turn already failed or went unanswered (see [`reminds`]): the
+ /// [`NO_FALSE_CLAIMS_TEXT`] reminder went with that one, so it isn't said again.
+ pub fn had_miss(&self) -> bool {
+ self.records
+ .lock()
+ .map(|r| {
+ r.iter()
+ .any(|c| c["status"].as_str().is_some_and(reminds))
+ })
+ .unwrap_or(true)
+ }
+
pub fn take_records(&self) -> Vec<Value> {
self.records.lock().map(|mut r| std::mem::take(&mut *r)).unwrap_or_default()
}
@@ -731,4 +775,18 @@ mod tests {
assert_eq!(namespaced_tool_name("gh", "x"), "mcp__gh__x");
assert_eq!(truncate_text("héllo", 2), "hé… [truncated]");
}
+
+ /// 26b: the reminder goes with a failed or unanswered result, never a plain denial (the bot
+ /// is told it was denied) or a call that ran or was a dry run. `had_miss` reads the same rule,
+ /// so a denial alone doesn't use up the turn's one reminder.
+ #[test]
+ fn the_reminder_goes_with_failed_or_unanswered_calls_only() {
+ for status in ["error", "failed", "cancelled", "unanswered"] {
+ assert!(reminds(status), "{status}");
+ }
+ for status in ["denied", "ok", "rehearsed", "allowed", ""] {
+ assert!(!reminds(status), "{status}");
+ }
+ assert!(missed_status("denied"), "a denial still didn't run");
+ }
}
diff --git a/src/mcp/session.rs b/src/mcp/session.rs
index 5f6a98dd..12073818 100644
--- a/src/mcp/session.rs
+++ b/src/mcp/session.rs
@@ -97,6 +97,20 @@ pub struct CallOutcome {
pub text: String,
pub status: &'static str,
pub record: Value,
+ /// 26b: this is the turn's first call that failed or didn't run, so the model's copy of
+ /// `text` gets [`super::NO_FALSE_CLAIMS_TEXT`] (see [`CallOutcome::model_text`]).
+ pub remind: bool,
+}
+
+impl CallOutcome {
+ /// What goes back to the model: `text`, plus the once-per-turn reminder when `remind`.
+ pub fn model_text(&self) -> String {
+ if self.remind {
+ super::with_no_false_claims(&self.text)
+ } else {
+ self.text.clone()
+ }
+ }
}
impl McpToolSession {
@@ -248,8 +262,14 @@ impl McpToolSession {
"result": truncate_text(&stopped.text, RECORD_RESULT_MAX_CHARS),
"repeat_stopped": stopped.count,
});
+ let remind = !self.ctx.had_miss();
self.ctx.record(record.clone());
- return CallOutcome { text: stopped.text, status: "error", record };
+ return CallOutcome {
+ text: stopped.text,
+ status: "error",
+ record,
+ remind,
+ };
}
let offered = self.tools.iter().find(|t| t.name == name);
let (status, text) = match offered {
@@ -301,6 +321,8 @@ impl McpToolSession {
if status == "ok" && offered.is_some_and(|t| !t.tool.read_only) && !crate::server::restart_resume::read_only(name) {
self.repeats.changed();
}
+ // 26b: the turn's first call that failed or went unanswered carries the one reminder
+ let remind = super::reminds(status) && !self.ctx.had_miss();
let (server, tool) = super::split_tool_name(name).unwrap_or(("", name));
let mut record = json!({
"id": call_id,
@@ -315,7 +337,12 @@ impl McpToolSession {
record["result"] = json!(truncate_text(&text, RECORD_RESULT_MAX_CHARS));
}
self.ctx.record(record.clone());
- CallOutcome { text, status, record }
+ CallOutcome {
+ text,
+ status,
+ record,
+ remind,
+ }
}
pub async fn shutdown(mut self) {
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index a82dbf11..6f55505f 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -605,7 +605,7 @@ async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead:
// boxed, so the retry loop around the turn adds no stack to it
async move {
let outcome = Box::pin(try_kwant_turn(scope, specialist, p, opts)).await;
- Box::pin(continue_once_if_capped_into(scope, specialist, outcome, None, Some(&slot))).await
+ Box::pin(continue_once_if_capped_into(scope, specialist, outcome, None, Some(&slot), None)).await
}
})
.await;
diff --git a/src/server/inbox_done.rs b/src/server/inbox_done.rs
index 2e2105b8..bf663e7e 100644
--- a/src/server/inbox_done.rs
+++ b/src/server/inbox_done.rs
@@ -218,11 +218,14 @@ pub fn meta_of(m: &Message) -> Value {
}
/// A step's status in Iris's three words: `failed` is `error`; a step that never ran or never
-/// finished (declined, stopped, still running or waiting when the reply was saved) is `skipped`.
+/// finished (declined, stopped, unanswered, rehearsed, still running or waiting when the reply was
+/// saved) is `skipped`.
fn trail_status(status: Option<&str>) -> &'static str {
match status {
Some("failed") => "error",
- Some("declined" | "stopped" | "running" | "waiting") => "skipped",
+ Some("declined" | "stopped" | "unanswered" | "rehearsed" | "running" | "waiting") => {
+ "skipped"
+ }
_ => "ok",
}
}
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index 97767f9a..09abd3dc 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -510,16 +510,27 @@ impl BrokerApprover {
details,
});
super::activity::approval_waiting(&req.turn_id, &ticket, &req.tool_name);
+ // 26b: a routine run's turn waits on this card: its run says so until the wait ends
+ let chat_key = ["thread_id", "channel_id", "direct_kwant_id"]
+ .iter()
+ .find_map(|k| chat[*k].as_str())
+ .unwrap_or(&req.kwant_id)
+ .to_string();
+ super::scheduler::approval_wait(&self.events, &req.kwant_id, &chat_key, Some(&ticket));
let decision = tokio::time::timeout(self.timeout, rx).await;
guard.id = None;
- let settled = match &decision {
- Ok(Ok(ApprovalDecision::AllowOnce | ApprovalDecision::AlwaysAllowSession)) => "ok",
- Ok(_) => "declined",
- // the card stays up, but this turn stops waiting for it
- Err(_) => "stopped",
+ super::scheduler::approval_wait(&self.events, &req.kwant_id, &chat_key, None);
+ let answered = match &decision {
+ Ok(Ok(ApprovalDecision::AllowOnce | ApprovalDecision::AlwaysAllowSession)) => {
+ Some("ok")
+ }
+ Ok(_) => Some("declined"),
+ Err(_) => None,
};
- super::activity::approval_settled(&req.turn_id, &ticket, settled);
+ if let Some(settled) = answered {
+ super::activity::approval_settled(&req.turn_id, &ticket, settled);
+ }
let outcome = match decision {
Ok(Ok(ApprovalDecision::AllowOnce)) => ApprovalOutcome::Allowed,
// A payment's "always allow" covers this one call: nothing is remembered
@@ -534,17 +545,31 @@ impl BrokerApprover {
// Nobody answered: the card stays up as `waiting`, and a late Allow resumes the work
// (see `resume_late_approval`)
Err(_) => {
- if !self.broker.cancel(&ticket).await {
- return (ApprovalOutcome::Denied, "denied", Some(ticket));
- }
- match self.db.park_approval(&ticket, &chat).await {
- Ok(true) => ApprovalOutcome::Unanswered,
- _ => {
- let _ = self.db.update_approval_status(&ticket, "expired").await;
- let _ = self.events.send(RuntimeEvent::approval_withdrawn(ticket.clone(), "expired", None));
- ApprovalOutcome::Denied
+ let outcome = if !self.broker.cancel(&ticket).await {
+ ApprovalOutcome::Denied
+ } else {
+ match self.db.park_approval(&ticket, &chat).await {
+ Ok(true) => ApprovalOutcome::Unanswered,
+ _ => {
+ let _ = self.db.update_approval_status(&ticket, "expired").await;
+ let _ = self.events.send(RuntimeEvent::approval_withdrawn(
+ ticket.clone(),
+ "expired",
+ None,
+ ));
+ ApprovalOutcome::Denied
+ }
}
- }
+ };
+ // The card stays up, but this turn stops waiting for it: `unanswered` (26b) when
+ // it was parked for a late answer, else `stopped`
+ let settled = if outcome == ApprovalOutcome::Unanswered {
+ "unanswered"
+ } else {
+ "stopped"
+ };
+ super::activity::approval_settled(&req.turn_id, &ticket, settled);
+ outcome
}
};
let class = if outcome.allowed() { "approved" } else { "denied" };
@@ -1017,7 +1042,11 @@ pub async fn prepare_turn_with_opts(
db: state.db.clone(),
broker: state.broker.clone(),
events: state.event_sender.clone(),
- timeout: APPROVAL_TIMEOUT,
+ timeout: Duration::from_millis(
+ state
+ .approval_wait_ms
+ .load(std::sync::atomic::Ordering::Relaxed),
+ ),
conversation: turn_conversation(state, &turn_id),
chat,
always_ask: opts.always_ask,
@@ -1266,6 +1295,11 @@ async fn decide(session: &PermissionSession, args: &Value, smart: bool, grant: O
return json!({"behavior": "deny", "message": "The turn ended before the user answered."});
}
};
+ // 26b: the turn's first unanswered (or otherwise failed) call carries the one reminder; a
+ // plain denial doesn't
+ let remind = !outcome.allowed()
+ && mcp::reminds(outcome.record_status())
+ && !session.ctx.had_miss();
session.ctx.record(json!({
"id": tool_use_id,
"name": tool_name,
@@ -1276,6 +1310,8 @@ async fn decide(session: &PermissionSession, args: &Value, smart: bool, grant: O
}));
if outcome.allowed() {
json!({"behavior": "allow", "updatedInput": input})
+ } else if remind {
+ json!({"behavior": "deny", "message": mcp::with_no_false_claims(outcome.refusal_text())})
} else {
json!({"behavior": "deny", "message": outcome.refusal_text()})
}
@@ -1465,7 +1501,7 @@ async fn gateway_rpc(
}
rpc_result(
id,
- json!({"content": [{"type": "text", "text": outcome.text}], "isError": outcome.status != "ok"}),
+ json!({"content": [{"type": "text", "text": outcome.model_text()}], "isError": outcome.status != "ok"}),
)
}
_ => rpc_error(id, -32601, "method not found"),
diff --git a/src/server/missions/listener.rs b/src/server/missions/listener.rs
index b31aa727..a1ef9d64 100644
--- a/src/server/missions/listener.rs
+++ b/src/server/missions/listener.rs
@@ -43,7 +43,7 @@ async fn handle(state: &AppState, ev: RuntimeEvent) {
on_delegation(state, id).await;
}
}
- RuntimeEvent::RoutineRun { routine_id, run_id, status } => on_routine_run(state, &routine_id, &run_id, &status).await,
+ RuntimeEvent::RoutineRun { routine_id, run_id, status, .. } => on_routine_run(state, &routine_id, &run_id, &status).await,
RuntimeEvent::QuestionUpdated { .. }
| RuntimeEvent::HumanStepUpdated { .. }
| RuntimeEvent::ApprovalRequired { .. }
@@ -554,7 +554,12 @@ pub async fn on_routine_run(state: &AppState, routine_id: &str, run_id: &str, st
(Some(t), "skipped") => {
finish(state, &t, "cancelled", "skipped: today's spending stop holds new turns").await;
}
- (Some(t), "error") => {
+ // 26b: a step waits on the person's card. The card already tells them; an AutoFix retry
+ // would only open another card, so there is none
+ (Some(t), "needs_you") => {
+ finish(state, &t, "failed", crate::server::scheduler::NEEDS_YOU_ERROR).await;
+ }
+ (Some(t), "error" | "incomplete") => {
let failed = finish(state, &t, "failed", "the routine run failed").await;
if failed {
let err = state.db.routine_run_error(run_id).await.ok().flatten().unwrap_or_else(|| "the routine run failed".into());
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 0ee6814c..331fe971 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -134,6 +134,9 @@ pub struct AppState {
pub self_tools: Arc<Mutex<HashMap<String, continuity::SelfScope>>>,
/// Routines with a run in progress; a run that would overlap is skipped.
pub running_routines: Arc<Mutex<std::collections::HashSet<String>>>,
+ /// How long a turn's tool call waits for its approval card, in ms: always
+ /// [`crate::mcp::APPROVAL_TIMEOUT_SECS`]; only tests shorten it (26b).
+ pub approval_wait_ms: Arc<std::sync::atomic::AtomicU64>,
/// Wakes the scheduler early when routines change.
pub scheduler_wake: Arc<tokio::sync::Notify>,
/// `ask_user` calls waiting for the user's answer.
@@ -212,6 +215,9 @@ impl AppState {
api_token,
self_tools: Default::default(),
running_routines: Default::default(),
+ approval_wait_ms: Arc::new(std::sync::atomic::AtomicU64::new(
+ crate::mcp::APPROVAL_TIMEOUT_SECS * 1000,
+ )),
scheduler_wake: Default::default(),
questions: Default::default(),
human_steps: Default::default(),
diff --git a/src/server/routes.rs b/src/server/routes.rs
index b538e5e6..dc6a37a5 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1047,7 +1047,9 @@ fn execute_single_turn(
/// Runs a routine's turn as if the user had sent `prompt` to `kwant` in `thread_id`, in
/// `channel_id` or in their direct chat: same team context, workspace, approvals and profile failover, and the
/// chat's stop button cancels it. The prompt message must already be saved. Returns the id of
-/// the kwant's reply, or `Err` with why there is none.
+/// the kwant's reply, or `Err` with why there is none. Every reply of the turn (its busy retries
+/// and automatic continuation too) has `run_id` in its meta under
+/// [`super::scheduler::ROUTINE_RUN_KEY`], so the run reads only its own steps (26b D1).
pub(super) async fn run_routine_turn(
state: &AppState,
kwant: &Kwant,
@@ -1055,10 +1057,16 @@ pub(super) async fn run_routine_turn(
thread_id: Option<String>,
prompt: String,
routine_name: &str,
+ run_id: &str,
) -> Result<Option<String>, String> {
// 0.9.5: nobody watches a routine run, so a busy browser step it ends on is retried here,
// bounded (see [`super::busy_retry::unwatched`]); a run that still ends busy fails to the Inbox
- let opts = || TurnOpts { source: Some(super::bot_status::TurnSource::routine(routine_name)), ..TurnOpts::default() };
+ let key = super::scheduler::ROUTINE_RUN_KEY;
+ let opts = || TurnOpts {
+ source: Some(super::bot_status::TurnSource::routine(routine_name)),
+ extra_meta: Some(serde_json::json!({ key: run_id })),
+ ..TurnOpts::default()
+ };
run_turn_with(state, kwant, channel_id, thread_id, prompt, opts, true, Vec::new()).await
}
@@ -1100,10 +1108,12 @@ async fn run_turn_with(
super::busy_retry::unwatched(scope, &kwant.name, &prompt, |p, slot| {
let mut o = opts();
o.busy_slot = Some(slot.clone());
+ // The continuation's reply is the same turn's, so it keeps the turn's extra meta
+ let extra_meta = o.extra_meta.clone();
// boxed, so the retry loop around the turn adds no stack to it
async move {
let reply = Box::pin(try_kwant_turn(scope, kwant, p, o)).await;
- Box::pin(continue_once_if_capped_into(scope, kwant, reply, None, Some(&slot))).await
+ Box::pin(continue_once_if_capped_into(scope, kwant, reply, None, Some(&slot), extra_meta)).await
}
})
.await
@@ -1153,17 +1163,19 @@ pub(super) async fn continue_once_if_capped(
first: Result<String, String>,
started_by: Option<&str>,
) -> Result<String, String> {
- continue_once_if_capped_into(scope, kwant, first, started_by, None).await
+ continue_once_if_capped_into(scope, kwant, first, started_by, None, None).await
}
/// [`continue_once_if_capped`] for an unwatched turn: the continuation, when there is one, is the
-/// turn that ended last, so only its busy step (if any) is left in `busy_slot`.
+/// turn that ended last, so only its busy step (if any) is left in `busy_slot`. `extra_meta` is
+/// the first turn's [`TurnOpts::extra_meta`], saved on the continuation's reply too.
pub(super) async fn continue_once_if_capped_into(
scope: &TurnScope,
kwant: &Kwant,
first: Result<String, String>,
started_by: Option<&str>,
busy_slot: Option<&super::busy_retry::Slot>,
+ extra_meta: Option<serde_json::Value>,
) -> Result<String, String> {
let Ok(text) = &first else {
return first;
@@ -1180,6 +1192,7 @@ pub(super) async fn continue_once_if_capped_into(
always_ask: started_by.is_some(),
started_by: started_by.map(str::to_string),
busy_slot: busy_slot.cloned(),
+ extra_meta,
..Default::default()
};
match try_kwant_turn(scope, kwant, CONTINUE_PROMPT.to_string(), opts).await {
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index 654792ef..ce7f0a54 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -557,17 +557,30 @@ pub async fn start_run_noted(state: &AppState, routine: RoutineRow, trigger: &st
if let Some(note) = note {
let _ = state.db.set_routine_run_note(&run.id, note).await;
}
+ // 26b: "Run now" counts as the routine's last run too. Only `last_run_at`: the next scheduled
+ // run stays where the schedule put it
+ if trigger == "manual" {
+ let _ = state
+ .db
+ .set_routine_last_run(&routine.id, run.started_at)
+ .await;
+ }
send_run_event(state, &run);
let state = state.clone();
let run_id = run.id.clone();
tokio::spawn(async move {
- let result = execute(&state, &routine).await;
- let (status, err, message_id) = match &result {
- Ok(message_id) => ("ok", None, message_id.clone()),
+ let result = execute(&state, &routine, &run_id).await;
+ let (status, err, message_id) = match result {
+ // A reply alone isn't "ok": what its steps did decides (26b)
+ Ok(ran) => {
+ let (status, why) = ran.outcome;
+ (status, why, ran.reply_id)
+ }
// The stop came down while the run was starting: a skip, like one caught above
- Err(e) if super::spend_stop::is_stop_error(e) => ("skipped", Some(e.as_str()), None),
- Err(e) => ("error", Some(e.as_str()), None),
+ Err(e) if super::spend_stop::is_stop_error(&e) => ("skipped", Some(e), None),
+ Err(e) => ("error", Some(e), None),
};
+ let err = err.as_deref();
if let Err(e) = state
.db
.finish_routine_run(&run_id, status, err, message_id.as_deref())
@@ -580,8 +593,11 @@ pub async fn start_run_noted(state: &AppState, routine: RoutineRow, trigger: &st
routine_id: routine.id.clone(),
run_id,
status: status.into(),
+ waiting: false,
+ approval_id: None,
});
- if status == "error" {
+ // A run that needs the person already has its card in the Inbox: no second notice
+ if matches!(status, "error" | "incomplete") {
let kwant_name = state
.db
.get_kwant(&routine.kwant_id)
@@ -628,11 +644,213 @@ fn send_run_event(state: &AppState, run: &RoutineRun) {
routine_id: run.routine_id.clone(),
run_id: run.id.clone(),
status: run.status.clone(),
+ waiting: false,
+ approval_id: None,
+ });
+}
+
+/// A routine run's error when a step waits on an approval card nobody answered (status
+/// `needs_you`, 26b).
+pub const NEEDS_YOU_ERROR: &str = "A step is waiting for your approval, so it didn't run";
+
+/// What a routine's turn did, once it replied.
+struct Ran {
+ reply_id: Option<String>,
+ /// The run's status and error (see [`run_outcome`]).
+ outcome: (&'static str, Option<String>),
+}
+
+/// One tool call or step of a run's turn, as [`run_outcome`] reads it.
+#[derive(Debug, Clone, PartialEq)]
+pub struct StepSeen {
+ pub tool: String,
+ /// "ok", "failed", "unanswered", or anything else (ignored).
+ pub status: &'static str,
+ pub reason: Option<String>,
+}
+
+/// 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;
+/// - 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 why = s
+ .reason
+ .as_deref()
+ .map(super::stopped::short_line)
+ .filter(|w| !w.trim().is_empty());
+ (
+ "incomplete",
+ Some(why.unwrap_or_else(|| format!("{} failed", s.tool))),
+ )
+ }
+ None => ("ok", None),
+ }
+}
+
+/// The steps a reply's saved tool calls (`tool_calls`) and activity (`meta.activity`) show. The
+/// two are read separately, each in its own order: kwnt's tool calls record every engine's
+/// approvals, and the activity has the claude CLI's own tool results.
+pub fn steps_seen(
+ tool_calls: Option<&serde_json::Value>,
+ meta: Option<&serde_json::Value>,
+) -> Vec<StepSeen> {
+ let text = |v: &serde_json::Value| v.as_str().map(str::to_string);
+ 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("") {
+ "ok" => "ok",
+ "unanswered" => "unanswered",
+ s if crate::mcp::missed_status(s) => "failed",
+ _ => continue,
+ };
+ 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 reason = match c["status"].as_str() {
+ Some("denied") => Some(format!("{tool} was denied")),
+ _ => reason.map(|r| {
+ r.replace(crate::mcp::NO_FALSE_CLAIMS_TEXT, "")
+ .trim()
+ .to_string()
+ }),
+ };
+ seen.push(StepSeen {
+ tool,
+ status,
+ reason,
+ });
+ }
+ for step in meta
+ .and_then(|m| m["activity"]["steps"].as_array())
+ .into_iter()
+ .flatten()
+ {
+ let status = match (step["kind"].as_str(), step["status"].as_str()) {
+ (_, Some("unanswered")) => "unanswered",
+ (Some("tool"), Some("ok")) => "ok",
+ (Some("tool"), Some("failed")) => "failed",
+ _ => continue,
+ };
+ seen.push(StepSeen {
+ tool: text(&step["tool"]).unwrap_or_default(),
+ status,
+ reason: text(&step["detail"]),
+ });
+ }
+ seen
+}
+
+/// 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";
+
+/// What a run's own replies show: their steps, and the id of the last one.
+struct OwnReplies {
+ steps: Vec<StepSeen>,
+ last_id: Option<String>,
+}
+
+/// The bot's replies after the routine's message (`prompt_id`) that belong to run `run_id` (its
+/// turn, busy retries and automatic continuation; [`ROUTINE_RUN_KEY`] in their meta), and every
+/// step they show. 26b D1: another routine's run, or the person's own turn, in the same chat at
+/// the same time never counts.
+async fn own_replies(
+ state: &AppState,
+ chat: &str,
+ bot_name: &str,
+ prompt_id: &str,
+ run_id: &str,
+) -> OwnReplies {
+ let messages = state.db.list_messages(chat, 40).await.unwrap_or_default();
+ let mut own = OwnReplies { steps: Vec::new(), last_id: None };
+ let Some(start) = messages.iter().position(|m| m.id == prompt_id) else {
+ return own;
+ };
+ let parse = |s: &Option<String>| {
+ s.as_deref()
+ .and_then(|t| serde_json::from_str::<serde_json::Value>(t).ok())
+ };
+ for m in messages[start + 1..]
+ .iter()
+ .filter(|m| m.sender_role == "kwant" && m.sender_id == bot_name)
+ {
+ let meta = parse(&m.meta);
+ if meta.as_ref().map(|v| &v[ROUTINE_RUN_KEY]).and_then(|v| v.as_str()) != Some(run_id) {
+ continue;
+ }
+ own.steps.extend(steps_seen(parse(&m.tool_calls).as_ref(), meta.as_ref()));
+ own.last_id = Some(m.id.clone());
+ }
+ own
+}
+
+/// 26b: routine runs whose turn is going, by bot and chat (one reply per bot per chat at a time),
+/// so an approval card the turn opens can mark its run as waiting.
+static RUNS_IN_CHATS: std::sync::LazyLock<std::sync::Mutex<RunsInChats>> = std::sync::LazyLock::new(Default::default);
+
+/// (bot id, chat key) → (routine id, run id).
+type RunsInChats = std::collections::HashMap<(String, String), (String, String)>;
+
+/// Holds a run's place in [`RUNS_IN_CHATS`] while its turn runs.
+struct RunInChat((String, String));
+
+impl RunInChat {
+ fn new(kwant_id: &str, chat: &str, routine_id: &str, run_id: &str) -> Self {
+ let key = (kwant_id.to_string(), chat.to_string());
+ if let Ok(mut runs) = RUNS_IN_CHATS.lock() {
+ runs.insert(key.clone(), (routine_id.to_string(), run_id.to_string()));
+ }
+ RunInChat(key)
+ }
+}
+
+impl Drop for RunInChat {
+ fn drop(&mut self) {
+ if let Ok(mut runs) = RUNS_IN_CHATS.lock() {
+ runs.remove(&self.0);
+ }
+ }
+}
+
+/// An approval card of `kwant_id`'s turn in `chat` opened (`Some(id)`) or closed (`None`): when
+/// that turn is a routine run's, its `running` event says so (`waiting`, `approval_id`). `chat` is
+/// the thread, channel or direct-chat bot id, as the run's message was posted.
+pub fn approval_wait(
+ events: &tokio::sync::broadcast::Sender<RuntimeEvent>,
+ kwant_id: &str,
+ chat: &str,
+ approval_id: Option<&str>,
+) {
+ let run = RUNS_IN_CHATS
+ .lock()
+ .ok()
+ .and_then(|runs| runs.get(&(kwant_id.to_string(), chat.to_string())).cloned());
+ if let Some((routine_id, run_id)) = run {
+ let _ = events.send(RuntimeEvent::RoutineRun {
+ routine_id,
+ run_id,
+ status: "running".into(),
+ waiting: approval_id.is_some(),
+ approval_id: approval_id.map(str::to_string),
+ });
+ }
}
/// Posts the routine's instructions as a message from "Routine: <name>" and runs the kwant's turn.
-async fn execute(state: &AppState, routine: &RoutineRow) -> Result<Option<String>, String> {
+async fn execute(state: &AppState, routine: &RoutineRow, run_id: &str) -> Result<Ran, String> {
let kwant = state
.db
.get_kwant(&routine.kwant_id)
@@ -692,8 +910,28 @@ async fn execute(state: &AppState, routine: &RoutineRow) -> Result<Option<String
let prompt = routine.instructions.clone()
+ &follow_up_context(state, routine, &kwant, &saved.id).await
+ &last_run_context(state, routine, &kwant).await;
- super::routes::run_routine_turn(state, &kwant, routine.channel_id.clone(), routine.thread_id.clone(), prompt, &routine.name)
- .await
+ let chat = delivery_chat(
+ routine.thread_id.as_deref(),
+ routine.channel_id.as_deref(),
+ &kwant.id,
+ )
+ .to_string();
+ let in_chat = RunInChat::new(&kwant.id, &chat, &routine.id, run_id);
+ let reply_id = super::routes::run_routine_turn(
+ state,
+ &kwant,
+ routine.channel_id.clone(),
+ routine.thread_id.clone(),
+ prompt,
+ &routine.name,
+ run_id,
+ )
+ .await?;
+ drop(in_chat);
+ let own = own_replies(state, &chat, &kwant.name, &saved.id, run_id).await;
+ // The run's own last reply; the turn's answer is the chat's latest reply by the bot, which
+ // can be another run's when two share the chat
+ Ok(Ran { reply_id: own.last_id.or(reply_id), outcome: run_outcome(&own.steps) })
}
/// The chat id a routine delivers to: its thread, its channel, or its bot's direct chat.
@@ -922,3 +1160,140 @@ mod no_silent_stop_tests {
assert!(long.contains(&format!("{}…", "x".repeat(160))) && !long.contains(&"x".repeat(161)), "{long}");
}
}
+
+#[cfg(test)]
+mod run_outcome_tests {
+ use super::*;
+
+ fn step(tool: &str, status: &'static str, reason: Option<&str>) -> StepSeen {
+ StepSeen {
+ tool: tool.into(),
+ status,
+ reason: reason.map(str::to_string),
+ }
+ }
+
+ /// 26b: a run whose only call nobody approved needs the person, whatever the reply says.
+ #[test]
+ fn an_unanswered_call_needs_you() {
+ assert_eq!(
+ run_outcome(&[step("ha", "unanswered", None)]),
+ ("needs_you", Some(NEEDS_YOU_ERROR.into()))
+ );
+ // even after other calls worked
+ assert_eq!(
+ run_outcome(&[step("a", "ok", None), step("ha", "unanswered", None)]).0,
+ "needs_you"
+ );
+ }
+
+ #[test]
+ fn a_failure_fixed_by_a_later_call_of_the_same_tool_is_ok() {
+ assert_eq!(
+ run_outcome(&[
+ step("web", "failed", Some("timeout")),
+ step("web", "ok", None)
+ ]),
+ ("ok", None)
+ );
+ assert_eq!(run_outcome(&[]), ("ok", None));
+ }
+
+ #[test]
+ fn a_failure_with_no_later_success_is_incomplete_with_its_reason() {
+ let steps = [
+ step("web", "ok", None),
+ step("web", "failed", Some("⚠️ 502 from the site\nstack…")),
+ step("mail", "ok", None),
+ ];
+ assert_eq!(
+ run_outcome(&steps),
+ ("incomplete", Some("502 from the site".into()))
+ );
+ // another tool's success doesn't fix it; no reason names the tool
+ assert_eq!(
+ run_outcome(&[step("web", "failed", None), step("mail", "ok", None)]),
+ ("incomplete", Some("web failed".into()))
+ );
+ }
+
+ /// The saved tool calls (every engine's approvals, kwnt's own tools) and the activity (the
+ /// claude CLI's own tool results) are both read; the reminder to the model is left out.
+ #[test]
+ fn steps_come_from_tool_calls_and_activity() {
+ let calls = json!([
+ {"name": "ha__turn_on", "status": "unanswered"},
+ {"name": "web__get", "status": "error", "result": crate::mcp::with_no_false_claims("502")},
+ {"name": "mail__send", "status": "denied", "result": crate::mcp::DENIED_TEXT},
+ {"name": "x", "status": "allowed"},
+ {"name": "y", "status": "rehearsed"},
+ ]);
+ // As the reply saves it (`ActivityLog::to_json`): the steps under `steps`
+ let meta = json!({"activity": {"steps": [
+ {"kind": "thinking", "status": "ok"},
+ {"kind": "approval", "status": "unanswered", "tool": "Bash"},
+ {"kind": "tool", "status": "failed", "tool": "Bash", "detail": "exit 1"},
+ {"kind": "tool", "status": "ok", "tool": "Bash"},
+ ]}});
+ let seen = steps_seen(Some(&calls), Some(&meta));
+ assert_eq!(
+ seen,
+ vec![
+ step("ha__turn_on", "unanswered", None),
+ step("web__get", "failed", Some("502")),
+ step("mail__send", "failed", Some("mail__send was denied")),
+ step("Bash", "unanswered", None),
+ step("Bash", "failed", Some("exit 1")),
+ step("Bash", "ok", None),
+ ]
+ );
+ assert_eq!(
+ run_outcome(&steps_seen(Some(&json!([calls[1].clone()])), None)),
+ ("incomplete", Some("502".into()))
+ );
+ assert_eq!(run_outcome(&steps_seen(None, None)), ("ok", None));
+ }
+
+ /// The waiting flag goes only to the routine run whose bot and chat the card belongs to, and
+ /// stops when the run's turn is over.
+ #[test]
+ fn a_card_marks_only_its_own_run_as_waiting() {
+ let (tx, mut rx) = tokio::sync::broadcast::channel(8);
+ let held = RunInChat::new("bot_w1", "chat_w1", "routine_w1", "run_w1");
+ approval_wait(&tx, "bot_w1", "chat_w1", Some("apr_1"));
+ approval_wait(&tx, "bot_other", "chat_w1", Some("apr_2"));
+ approval_wait(&tx, "bot_w1", "chat_w1", None);
+ drop(held);
+ approval_wait(&tx, "bot_w1", "chat_w1", Some("apr_3"));
+ let got: Vec<_> = std::iter::from_fn(|| rx.try_recv().ok()).collect();
+ assert_eq!(
+ got,
+ vec![
+ RuntimeEvent::RoutineRun {
+ routine_id: "routine_w1".into(),
+ run_id: "run_w1".into(),
+ status: "running".into(),
+ waiting: true,
+ approval_id: Some("apr_1".into()),
+ },
+ RuntimeEvent::RoutineRun {
+ routine_id: "routine_w1".into(),
+ run_id: "run_w1".into(),
+ status: "running".into(),
+ waiting: false,
+ approval_id: None,
+ },
+ ]
+ );
+ // Old clients: the new fields are optional both ways
+ let old: RuntimeEvent = serde_json::from_value(json!({"type": "routine_run", "data": {"routine_id": "r", "run_id": "x", "status": "ok"}})).unwrap();
+ assert!(matches!(
+ old,
+ RuntimeEvent::RoutineRun {
+ waiting: false,
+ approval_id: None,
+ ..
+ }
+ ));
+ }
+}
diff --git a/src/server/sse.rs b/src/server/sse.rs
index ff2d609d..c4fffa45 100644
--- a/src/server/sse.rs
+++ b/src/server/sse.rs
@@ -327,7 +327,7 @@ mod tests {
E::Error { code: s("x"), message: s("x"), kwant_id: Some(s("k")) },
E::MemoryChanged { kwant_id: s("k") },
E::BotStatus { kwant_id: s("k"), status: json!({}) },
- E::RoutineRun { routine_id: s("r"), run_id: s("x"), status: s("ok") },
+ E::RoutineRun { routine_id: s("r"), run_id: s("x"), status: s("ok"), waiting: false, approval_id: None },
E::TaskUpdated { task: json!({"id": "t", "space_id": "spc_x"}) },
E::MissionUpdated { mission: json!({"id": "m", "space_id": "spc_x"}) },
E::GoalUpdated { id: s("g"), status: s("met"), space_id: s("spc_x") },
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index f7fd5d32..7e47e8ff 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -6,7 +6,10 @@
//! (the last marker counts, and each marker runs once: later turns see it again in history).
//! It calls kwnt's own tools straight away; with `ASKFIRST` in the prompt too it first asks
//! kwnt's permission prompt (`--permission-prompt-tool`), as claude does, and on a deny replies
-//! `TOOLDENIED` without calling.
+//! `TOOLDENIED[<what kwnt said>]` without calling. `ASKAS:<tool>` too (say `ASKAS:Bash`): the
+//! prompt is asked for that tool, with the marker's arguments as its input, and the call shows
+//! as claude's own `stream-json` tool_use and, on a deny, its error tool_result (kwant's
+//! own tools never get a card in a person's turn; Bash always asks).
//! - `REPLYTAG:<tag>`: reply "answer <tag>" (after any tool call).
//! - `REPLYTEXT:<base64 text>`: reply exactly that text (say, a markdown table), and nothing else.
//! - `REPLYSEQ:<tag>`: reply the test's planned answers in turn: the files `seq-<tag>-1`, `seq-<tag>-2`, …
@@ -181,15 +184,25 @@ if m and "--mcp-config" in args:
# ASKFIRST: ask kwnt's permission prompt first, as claude does before an MCP tool call
if "ASKFIRST" in prompt and "--permission-prompt-tool" in args:
perm = cfg["mcpServers"]["kwnt"]
+ ask_as = re.findall(r"ASKAS:([A-Za-z_]+)", prompt)
+ asked = ask_as[-1] if ask_as else "mcp__kwnt_tools__" + m.group(1)
+ if ask_as:
+ # claude prints the call before it asks, and its result after
+ print(json.dumps({"type": "assistant", "message": {"id": "msg_askas", "content": [
+ {"type": "tool_use", "id": "toolu_askfirst", "name": asked, "input": call_args}]}}), flush=True)
ask = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "approve",
- "arguments": {"tool_name": "mcp__kwnt_tools__" + m.group(1), "input": call_args, "tool_use_id": "toolu_askfirst"}}}).encode()
+ "arguments": {"tool_name": asked, "input": call_args, "tool_use_id": "toolu_askfirst"}}}).encode()
preq = urllib.request.Request(perm["url"], data=ask, method="POST",
headers={"content-type": "application/json", **perm.get("headers", {})})
verdict = json.loads(json.load(urllib.request.urlopen(preq, timeout=600))["result"]["content"][0]["text"])
if verdict.get("behavior") == "allow":
call_args = verdict.get("updatedInput", call_args)
else:
- reply.append("TOOLDENIED")
+ # what kwnt told the bot, in brackets, so tests can read it
+ reply.append("TOOLDENIED[" + verdict.get("message", "") + "]")
+ if ask_as:
+ print(json.dumps({"type": "user", "message": {"content": [{"type": "tool_result",
+ "tool_use_id": "toolu_askfirst", "is_error": True, "content": verdict.get("message", "")}]}}), flush=True)
m = None
if m and "--mcp-config" in args:
body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call",
diff --git a/tests/late_approval_test.rs b/tests/late_approval_test.rs
index de440d98..76070a75 100644
--- a/tests/late_approval_test.rs
+++ b/tests/late_approval_test.rs
@@ -286,3 +286,79 @@ async fn an_expired_card_says_so_once_and_retry_asks_again() {
assert_eq!(s.as_u16(), 409);
assert_eq!(env.state.db.get_approval(&fresh).await.unwrap().unwrap().status, "waiting");
}
+
+/// 26b: a real turn whose call nobody answered saves that step as `unanswered` (not ok, not
+/// stopped) and tells the bot once not to claim it worked; the card stays open for a late answer.
+#[tokio::test]
+async fn an_unanswered_call_is_saved_as_unanswered_in_the_chat() {
+ let env = setup().await;
+ env.state
+ .db
+ .set_space_approvals(&kwnt::db::spaces::SpaceId::default_space(), "ask")
+ .await
+ .unwrap();
+ env.state
+ .approval_wait_ms
+ .store(300, std::sync::atomic::Ordering::Relaxed);
+ // A shell command always asks (kwnt's own tools never get a card in a person's turn); the fake
+ // CLI asks for it as Bash and shows claude's own tool_use / tool_result lines
+ let marker = call_tool_marker(
+ "bash",
+ json!({"command": "touch LATE26B_MARK", "description": "make a file"}),
+ );
+ send_direct(
+ &env,
+ &env.a,
+ &format!("Save this {marker} ASKFIRST ASKAS:Bash REPLYTAG:late26b"),
+ json!({}),
+ )
+ .await;
+ let reply = wait_reply(&env, &env.a, "answer late26b").await;
+
+ 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 step = steps
+ .iter()
+ .find(|s| s["kind"] == "approval")
+ .unwrap_or_else(|| panic!("{meta}"));
+ assert_eq!(step["status"], "unanswered", "{step}");
+ assert_eq!(step["detail"], kwnt::mcp::UNANSWERED_STEP_DETAIL, "{step}");
+ // claude's own step for the call reads the same, not "failed" and never the reminder
+ let tool = steps
+ .iter()
+ .find(|s| s["kind"] == "tool" && s["tool"] == "Bash")
+ .unwrap_or_else(|| panic!("{meta}"));
+ assert_eq!(tool["status"], "unanswered", "{tool}");
+ assert_eq!(tool["detail"], kwnt::mcp::UNANSWERED_STEP_DETAIL, "{tool}");
+ assert!(
+ reply
+ .text
+ .contains(UNANSWERED_TEXT.split(". ").next().unwrap()),
+ "{}",
+ reply.text
+ );
+ assert_eq!(
+ reply.text.matches(kwnt::mcp::NO_FALSE_CLAIMS_TEXT).count(),
+ 1,
+ "{}",
+ reply.text
+ );
+ let waiting = env
+ .state
+ .db
+ .list_approvals(
+ &kwnt::db::spaces::SpaceId::default_space(),
+ Some("waiting"),
+ Some(&env.a),
+ )
+ .await
+ .unwrap();
+ assert_eq!(waiting.len(), 1, "the card stays open");
+}
diff --git a/tests/routine_run_statuses_migration_test.rs b/tests/routine_run_statuses_migration_test.rs
new file mode 100644
index 00000000..6d461192
--- /dev/null
+++ b/tests/routine_run_statuses_migration_test.rs
@@ -0,0 +1,130 @@
+//! 26b: routine runs can end `needs_you` or `incomplete`. A database whose `routine_runs` still
+//! has the old status rule is rebuilt once at start: every run, column and index kept, and a
+//! restart still ends a run that was going as "kwnt stopped during the run".
+
+use kwnt::db::Database;
+use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions};
+use std::path::Path;
+use std::str::FromStr;
+
+async fn raw(path: &Path) -> SqlitePool {
+ let opts = SqliteConnectOptions::from_str(&format!("sqlite://{}", path.display())).unwrap();
+ SqlitePoolOptions::new()
+ .max_connections(1)
+ .connect_with(opts)
+ .await
+ .unwrap()
+}
+
+async fn exec(pool: &SqlitePool, sql: &str) {
+ sqlx::query(sql)
+ .execute(pool)
+ .await
+ .unwrap_or_else(|e| panic!("{sql}: {e}"));
+}
+
+/// `routine_runs` as 0.9.20 leaves it: the old status rule, a run of each kind and one going.
+async fn legacy(dir: &Path) {
+ Database::init(dir).await.unwrap();
+ let pool = raw(&dir.join("kwnt.db")).await;
+ for sql in [
+ "DROP TABLE routine_runs",
+ "CREATE TABLE routine_runs (
+ id TEXT PRIMARY KEY,
+ routine_id TEXT NOT NULL,
+ trigger TEXT NOT NULL CHECK (trigger IN ('schedule', 'manual')),
+ started_at TIMESTAMP NOT NULL,
+ ended_at TIMESTAMP,
+ status TEXT NOT NULL CHECK (status IN ('running', 'ok', 'error', 'skipped')),
+ error TEXT,
+ message_id TEXT
+ , note TEXT)",
+ "CREATE INDEX routine_runs_by_routine ON routine_runs (routine_id, started_at)",
+ "CREATE INDEX routine_runs_by_end ON routine_runs (status, ended_at) WHERE ended_at IS NOT NULL",
+ "INSERT INTO routine_runs VALUES
+ ('run_ok', 'r1', 'schedule', '2026-11-01T09:00:00Z', '2026-11-01T09:01:00Z', 'ok', NULL, 'msg_1', NULL),
+ ('run_err', 'r1', 'manual', '2026-11-02T09:00:00Z', '2026-11-02T09:01:00Z', 'error', 'boom', NULL, 'Ran late'),
+ ('run_going', 'r1', 'schedule', '2026-11-03T09:00:00Z', NULL, 'running', NULL, NULL, NULL)",
+ ] {
+ exec(&pool, sql).await;
+ }
+ let refused = sqlx::query("UPDATE routine_runs SET status = 'needs_you' WHERE id = 'run_ok'")
+ .execute(&pool)
+ .await;
+ assert!(refused.is_err(), "the old rule refuses the new statuses");
+ pool.close().await;
+}
+
+type Row = (
+ String,
+ String,
+ String,
+ Option<String>,
+ Option<String>,
+ Option<String>,
+);
+
+async fn runs(pool: &SqlitePool) -> Vec<Row> {
+ sqlx::query_as(
+ "SELECT id, trigger, status, error, message_id, note FROM routine_runs ORDER BY rowid",
+ )
+ .fetch_all(pool)
+ .await
+ .unwrap()
+}
+
+#[tokio::test]
+async fn old_run_history_is_kept_and_takes_the_new_statuses() {
+ let tmp = tempfile::tempdir().unwrap();
+ legacy(tmp.path()).await;
+ let before = runs(&raw(&tmp.path().join("kwnt.db")).await).await;
+
+ let db = Database::init(tmp.path()).await.unwrap();
+ let pool = raw(&tmp.path().join("kwnt.db")).await;
+ assert_eq!(runs(&pool).await, before, "every run kept as it was");
+ let indexes: Vec<(String,)> = sqlx::query_as("SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'routine_runs' AND sql IS NOT NULL ORDER BY name")
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ assert_eq!(
+ indexes,
+ vec![
+ ("routine_runs_by_end".to_string(),),
+ ("routine_runs_by_routine".to_string(),)
+ ]
+ );
+ pool.close().await;
+
+ // The new statuses are taken; anything else still isn't
+ db.finish_routine_run(
+ "run_ok",
+ "needs_you",
+ Some("A step is waiting for your approval, so it didn't run"),
+ None,
+ )
+ .await
+ .unwrap();
+ db.finish_routine_run("run_err", "incomplete", Some("502"), None)
+ .await
+ .unwrap();
+ assert!(db
+ .finish_routine_run("run_err", "great", None, None)
+ .await
+ .is_err());
+
+ // A restart still ends the run that was going, as before
+ assert_eq!(db.fail_interrupted_runs().await.unwrap(), 1);
+ let pool = raw(&tmp.path().join("kwnt.db")).await;
+ let after = runs(&pool).await;
+ assert_eq!(after[0].2, "needs_you");
+ assert_eq!(after[1].2, "incomplete");
+ assert_eq!(
+ (after[2].2.as_str(), after[2].3.as_deref()),
+ ("error", Some("kwnt stopped during the run"))
+ );
+
+ // Once is enough: a second start changes nothing
+ drop(db);
+ Database::init(tmp.path()).await.unwrap();
+ assert_eq!(runs(&raw(&tmp.path().join("kwnt.db")).await).await, after);
+}
diff --git a/tests/routine_unanswered_test.rs b/tests/routine_unanswered_test.rs
new file mode 100644
index 00000000..4ecb082a
--- /dev/null
+++ b/tests/routine_unanswered_test.rs
@@ -0,0 +1,293 @@
+//! 26b: an approval nobody answered is never "ok". A routine run whose only call waits on a card
+//! nobody answers ends `needs_you` (its run event says `waiting` while the card is open), its
+//! activity step is `unanswered`; a step that failed with no later success ends `incomplete`; a
+//! failure fixed by a later call of the same tool stays `ok`; "Run now" sets `last_run_at`; two
+//! runs in one chat each read only their own replies (D1).
+
+mod common;
+
+use common::*;
+use kwnt::db::spaces::SpaceId;
+use kwnt::drivers::events::RuntimeEvent;
+use serde_json::{json, Value};
+use std::sync::atomic::Ordering;
+
+/// A daily routine of bot A in its direct chat (so "Run now" is the only run in a test).
+async fn routine(env: &Env, name: &str, instructions: &str) -> String {
+ let (s, r) = call(
+ &env.app,
+ "POST",
+ "/api/routines",
+ Some(
+ json!({"kwant_id": env.a, "name": name, "instructions": instructions,
+ "schedule": {"type": "daily", "time": "03:00", "tz": "UTC"}}),
+ ),
+ )
+ .await;
+ assert_eq!(s.as_u16(), 201, "{r}");
+ r["id"].as_str().unwrap().to_string()
+}
+
+async fn routine_row(env: &Env, id: &str) -> Value {
+ let (_, list) = call(&env.app, "GET", "/api/routines", None).await;
+ list.as_array()
+ .unwrap()
+ .iter()
+ .find(|r| r["id"] == id)
+ .cloned()
+ .expect("routine listed")
+}
+
+/// Starts a manual run and waits for it to end; returns the run.
+async fn run_now(env: &Env, id: &str) -> Value {
+ 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();
+ 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;
+ find(runs)
+}
+
+/// The reply a run saved (its `message_id`), with its meta parsed.
+async fn reply_of(env: &Env, run: &Value) -> Value {
+ let id = run["message_id"].as_str().expect("the run saved a reply");
+ let m = env.state.db.get_message(id).await.unwrap().unwrap();
+ m.meta
+ .as_deref()
+ .and_then(|s| serde_json::from_str(s).ok())
+ .unwrap_or(Value::Null)
+}
+
+#[tokio::test]
+async fn a_routine_whose_only_call_nobody_answers_needs_you() {
+ let env = setup().await;
+ env.state
+ .db
+ .set_space_approvals(&SpaceId::default_space(), "ask")
+ .await
+ .unwrap();
+ env.state.approval_wait_ms.store(400, Ordering::Relaxed);
+ // A shell command always asks (kwnt's own tools don't); the fake CLI asks for it as Bash
+ let marker = call_tool_marker(
+ "bash",
+ json!({"command": "touch LIGHTS26B_MARK", "description": "check the lights"}),
+ );
+ let id = routine(
+ &env,
+ "Lights",
+ &format!("Check the lights {marker} ASKFIRST ASKAS:Bash REPLYTAG:lights26b"),
+ )
+ .await;
+ let before = routine_row(&env, &id).await;
+ assert!(before["last_run_at"].is_null(), "{before}");
+ let mut events = env.state.event_sender.subscribe();
+
+ let run = run_now(&env, &id).await;
+ assert_eq!(run["status"], "needs_you", "{run}");
+ assert_eq!(
+ run["error"],
+ "A step is waiting for your approval, so it didn't run"
+ );
+
+ // The card is still open for a late answer, and the run's events said so while it waited
+ let waiting = env
+ .state
+ .db
+ .list_approvals(&SpaceId::default_space(), Some("waiting"), Some(&env.a))
+ .await
+ .unwrap();
+ let card = waiting.first().expect("the card stays open").id.clone();
+ let mut seen = Vec::new();
+ while let Ok(e) = events.try_recv() {
+ if let RuntimeEvent::RoutineRun {
+ run_id,
+ status,
+ waiting,
+ approval_id,
+ ..
+ } = e
+ {
+ if run_id == run["id"].as_str().unwrap() {
+ seen.push((status, waiting, approval_id));
+ }
+ }
+ }
+ let open = seen
+ .iter()
+ .position(|(s, w, a)| s == "running" && *w && a.as_deref() == Some(card.as_str()));
+ let open = open.unwrap_or_else(|| panic!("a waiting event with the card: {seen:?}"));
+ // Search only after the waiting event: the run's first "running" event
+ // (before any card) also has the flag off.
+ let closed = seen
+ .iter()
+ .skip(open + 1)
+ .position(|(s, w, a)| s == "running" && !*w && a.is_none())
+ .map(|i| i + open + 1);
+ assert!(
+ closed.is_some_and(|c| c > open),
+ "the flag clears when the wait ends: {seen:?}"
+ );
+ assert_eq!(
+ seen.last().map(|(s, w, _)| (s.as_str(), *w)),
+ Some(("needs_you", false)),
+ "{seen:?}"
+ );
+
+ // Its approval step is `unanswered`, not ok or stopped
+ let meta = reply_of(&env, &run).await;
+ let steps = meta["activity"]["steps"]
+ .as_array()
+ .cloned()
+ .unwrap_or_default();
+ let approval = steps
+ .iter()
+ .find(|s| s["kind"] == "approval")
+ .unwrap_or_else(|| panic!("{meta}"));
+ assert_eq!(approval["status"], "unanswered", "{approval}");
+ // The bot was told once not to claim the step worked
+ let text = env
+ .state
+ .db
+ .get_message(run["message_id"].as_str().unwrap())
+ .await
+ .unwrap()
+ .unwrap()
+ .text;
+ assert_eq!(
+ text.matches(kwnt::mcp::NO_FALSE_CLAIMS_TEXT).count(),
+ 1,
+ "{text}"
+ );
+
+ // "Run now" counts as the last run; the next scheduled run stays where it was
+ let after = routine_row(&env, &id).await;
+ assert!(after["last_run_at"].is_string(), "{after}");
+ assert_eq!(after["next_run_at"], before["next_run_at"]);
+}
+
+#[tokio::test]
+async fn a_step_that_failed_for_good_is_incomplete_and_one_fixed_later_is_ok() {
+ let env = setup().await;
+ let use_tool = |id: &str, cmd: &str| {
+ json!({"type": "assistant", "message": {"id": format!("msg_{id}"), "content": [
+ {"type": "tool_use", "id": id, "name": "Bash", "input": {"command": cmd, "description": "fetch the report"}}]}})
+ };
+ let result = |id: &str, error: bool, text: &str| {
+ json!({"type": "user", "message": {"content": [
+ {"type": "tool_result", "tool_use_id": id, "is_error": error, "content": text}]}})
+ };
+
+ let failed = stream_lines_marker(&[
+ use_tool("toolu_f1", "fetch.sh"),
+ result("toolu_f1", true, "exit 7: the report server said 502"),
+ ]);
+ let id = routine(
+ &env,
+ "Report",
+ &format!("Fetch the report {failed} REPLYTAG:report26b"),
+ )
+ .await;
+ let run = run_now(&env, &id).await;
+ assert_eq!(run["status"], "incomplete", "{run}");
+ assert_eq!(run["error"], "exit 7: the report server said 502");
+
+ let fixed = stream_lines_marker(&[
+ use_tool("toolu_g1", "fetch.sh"),
+ result("toolu_g1", true, "exit 7: 502"),
+ use_tool("toolu_g2", "fetch.sh --retry"),
+ result("toolu_g2", false, "report.pdf"),
+ ]);
+ let id = routine(
+ &env,
+ "Report again",
+ &format!("Fetch the report {fixed} REPLYTAG:again26b"),
+ )
+ .await;
+ let run = run_now(&env, &id).await;
+ assert_eq!(run["status"], "ok", "{run}");
+ assert!(run["error"].is_null(), "{run}");
+}
+
+/// 26b D1 (Rigel, QA at 6923ad4b): two routines of one bot deliver to the same chat at the same
+/// time. The one whose step failed ends `incomplete`; the plain one, whose turn ran no tool,
+/// ends `ok`: a run reads only its own replies, never the other run's.
+#[tokio::test]
+async fn two_runs_in_one_chat_each_read_only_their_own_steps() {
+ let env = setup().await;
+ let failed = stream_lines_marker(&[
+ json!({"type": "assistant", "message": {"id": "msg_s1", "content": [
+ {"type": "tool_use", "id": "toolu_s1", "name": "Bash", "input": {"command": "fetch.sh", "description": "fetch the report"}}]}}),
+ json!({"type": "user", "message": {"content": [
+ {"type": "tool_result", "tool_use_id": "toolu_s1", "is_error": true, "content": "exit 7: the report server said 502"}]}}),
+ ]);
+ // The failing one is slow, so the plain one's message is posted while its turn still runs
+ let fails = routine(
+ &env,
+ "Sibling fails",
+ &format!("Fetch the report {failed} SLEEPONCE:sib26b:2000 REPLYTAG:sibfail26b"),
+ )
+ .await;
+ let plain = routine(
+ &env,
+ "Sibling plain",
+ "Say hi, no tools. REPLYTAG:sibplain26b",
+ )
+ .await;
+ let (fails_run, plain_run) = tokio::join!(run_now(&env, &fails), async {
+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+ run_now(&env, &plain).await
+ });
+
+ assert_eq!(fails_run["status"], "incomplete", "{fails_run}");
+ assert_eq!(fails_run["error"], "exit 7: the report server said 502");
+ assert_eq!(plain_run["status"], "ok", "{plain_run}");
+ assert!(plain_run["error"].is_null(), "{plain_run}");
+
+ // Each run's reply is its own, and says which run it is
+ for (run, tag) in [
+ (&fails_run, "answer sibfail26b"),
+ (&plain_run, "answer sibplain26b"),
+ ] {
+ let id = run["message_id"].as_str().expect("the run saved a reply");
+ let reply = env.state.db.get_message(id).await.unwrap().unwrap();
+ assert!(reply.text.contains(tag), "{run}: {}", reply.text);
+ assert_eq!(reply_of(&env, run).await["routine_run"], run["id"], "{run}");
+ }
+}
+
+#[tokio::test]
+async fn a_second_run_while_one_is_going_is_still_skipped() {
+ let env = setup().await;
+ let id = routine(
+ &env,
+ "Slow",
+ "Take your time SLEEPONCE:slow26b:1500 REPLYTAG:slow26b",
+ )
+ .await;
+ let (s, first) = call(&env.app, "POST", &format!("/api/routines/{id}/run"), None).await;
+ assert_eq!(
+ (s.as_u16(), first["status"].as_str()),
+ (202, Some("running")),
+ "{first}"
+ );
+ let (s, second) = call(&env.app, "POST", &format!("/api/routines/{id}/run"), None).await;
+ assert_eq!(s.as_u16(), 202);
+ assert_eq!(
+ (second["status"].as_str(), second["error"].as_str()),
+ (Some("skipped"), Some("the previous run was still going"))
+ );
+ wait_reply(&env, &env.a, "answer slow26b").await;
+}