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
Approvals: an unanswered card stays open; a late Allow resumes the turn
Lin (kwant bot)468fa78af6ae
diff --git a/src/broker/mod.rs b/src/broker/mod.rsindex 911cc707..75957dbc 100644--- a/src/broker/mod.rs+++ b/src/broker/mod.rs@@ -25,6 +25,30 @@ pub struct PermissionBroker {/// (kwant_id, conversation, tool_name) the user chose "always allow" for: that bot may use/// that tool again in that one conversation, until kwnt restarts.always_allowed: Arc<Mutex<HashSet<(String, String, String)>>>,+ /// Calls the person allowed after their turn had stopped waiting: the resumed turn's same+ /// call runs once without a new card, until the grant lapses.+ grants: Arc<Mutex<Vec<Grant>>>,+}++/// How long a late Allow waits for the resumed turn to make its call again.+pub const GRANT_TTL: std::time::Duration = std::time::Duration::from_secs(30 * 60);++#[derive(Debug, Clone)]+struct Grant {+ kwant_id: String,+ tool_name: String,+ arguments: Value,+ until: std::time::Instant,+}++/// Arguments compared for a grant: claude's free-text `description` of a Bash call may change+/// between attempts, what runs may not.+fn grant_arguments(arguments: &Value) -> Value {+ let mut a = arguments.clone();+ if let Some(map) = a.as_object_mut() {+ map.remove("description");+ }+ a}impl PermissionBroker {@@ -32,6 +56,35 @@ impl PermissionBroker {Self {pending: Arc::new(Mutex::new(HashMap::new())),always_allowed: Arc::new(Mutex::new(HashSet::new())),+ grants: Default::default(),+ }+ }++ /// Lets one later call of `tool_name` with these `arguments` by this kwant run without a+ /// card (a late Allow). Lapses after [`GRANT_TTL`].+ pub async fn grant_once(&self, kwant_id: &str, tool_name: &str, arguments: &Value) {+ let mut grants = self.grants.lock().await;+ grants.retain(|g| g.until > std::time::Instant::now());+ grants.push(Grant {+ kwant_id: kwant_id.to_string(),+ tool_name: tool_name.to_string(),+ arguments: grant_arguments(arguments),+ until: std::time::Instant::now() + GRANT_TTL,+ });+ }++ /// Uses up a matching [`grant_once`](Self::grant_once); false when there is none.+ pub async fn take_grant(&self, kwant_id: &str, tool_name: &str, arguments: &Value) -> bool {+ let mut grants = self.grants.lock().await;+ let now = std::time::Instant::now();+ grants.retain(|g| g.until > now);+ let wanted = grant_arguments(arguments);+ match grants.iter().position(|g| g.kwant_id == kwant_id && g.tool_name == tool_name && g.arguments == wanted) {+ Some(i) => {+ grants.remove(i);+ true+ }+ None => false,}}@@ -83,6 +136,7 @@ impl PermissionBroker {/// Forgets a deleted bot's "always allow" answers.pub async fn forget_kwant(&self, kwant_id: &str) {self.always_allowed.lock().await.retain(|(k, _, _)| k != kwant_id);+ self.grants.lock().await.retain(|g| g.kwant_id != kwant_id);}pub async fn is_allowed_for_session(&self, kwant_id: &str, conversation: &str, tool_name: &str) -> bool {diff --git a/src/db/approval_modes.rs b/src/db/approval_modes.rsindex 87718d08..5bb4573c 100644--- a/src/db/approval_modes.rs+++ b/src/db/approval_modes.rs@@ -12,6 +12,9 @@ pub const OFF: &str = "off";/// A bot's setting as the person chose it: `inherit` follows its space.pub const INHERIT: &str = "inherit";+/// How long a card that outlived its turn can still be answered to resume the work.+pub const WAITING_APPROVAL_HOURS: i64 = 24;+/// What `approvals` resolves to for one bot.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]pub struct ApprovalMode {@@ -145,6 +148,79 @@ impl Database {.await?)}+ /// A card nobody answered before its turn's wait ran out: it stays open as `waiting`, with+ /// the chat (`{"channel_id"|"thread_id"|"direct_kwant_id": …}`) a late Allow resumes in.+ /// False when the ticket was no longer pending.+ pub async fn park_approval(&self, id: &str, chat: &serde_json::Value) -> Result<bool, DbError> {+ let done = sqlx::query("UPDATE approvals SET status = 'waiting', resume = ? WHERE id = ? AND status = 'pending'")+ .bind(chat.to_string())+ .bind(id)+ .execute(&self.pool)+ .await?;+ Ok(done.rows_affected() == 1)+ }++ /// Answers a `waiting` card once: sets `status` and returns the ticket with its chat. `None`+ /// when it isn't waiting (answered, or never parked) or is older than [`WAITING_APPROVAL_HOURS`],+ /// which is then marked `expired`. Two answers at once: only one gets the ticket.+ pub async fn claim_waiting_approval(+ &self,+ id: &str,+ status: &str,+ ) -> Result<Option<(super::models::Approval, serde_json::Value)>, DbError> {+ let window = format!("-{WAITING_APPROVAL_HOURS} hours");+ sqlx::query("UPDATE approvals SET status = 'expired' WHERE id = ? AND status = 'waiting' AND created_at <= datetime('now', ?)")+ .bind(id)+ .bind(&window)+ .execute(&self.pool)+ .await?;+ let done = sqlx::query("UPDATE approvals SET status = ? WHERE id = ? AND status = 'waiting'")+ .bind(status)+ .bind(id)+ .execute(&self.pool)+ .await?;+ if done.rows_affected() != 1 {+ return Ok(None);+ }+ let resume: Option<(Option<String>,)> =+ sqlx::query_as("SELECT resume FROM approvals WHERE id = ?").bind(id).fetch_optional(&self.pool).await?;+ let chat = resume+ .and_then(|r| r.0)+ .and_then(|r| serde_json::from_str(&r).ok())+ .unwrap_or(serde_json::Value::Null);+ Ok(self.get_approval(id).await?.map(|a| (a, chat)))+ }++ /// Cards still `waiting` for a late answer (younger than [`WAITING_APPROVAL_HOURS`]), with+ /// the chat each one resumes in, newest first.+ pub async fn away_waiting_approvals(&self) -> Result<Vec<super::away::AwayRow>, DbError> {+ let window = format!("-{WAITING_APPROVAL_HOURS} hours");+ Ok(sqlx::query_as(+ "SELECT 'approval' AS kind, a.id, a.kwant_id, k.name AS kwant_name, a.tool_name AS title, a.status,+ a.parameters AS body, a.created_at AS at,+ json_extract(a.resume, '$.thread_id') AS thread_id,+ json_extract(a.resume, '$.channel_id') AS channel_id,+ json_extract(a.resume, '$.direct_kwant_id') AS direct_kwant_id, NULL AS choices+ FROM approvals a LEFT JOIN kwants k ON k.id = a.kwant_id+ WHERE a.status = 'waiting' AND a.created_at > datetime('now', ?)+ ORDER BY a.created_at DESC, a.rowid DESC",+ )+ .bind(window)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Moves a card's `created_at` back `hours` (tests of the waiting window).+ #[doc(hidden)]+ pub async fn backdate_approval_for_test(&self, id: &str, hours: i64) -> Result<(), DbError> {+ sqlx::query("UPDATE approvals SET created_at = datetime('now', ?) WHERE id = ?")+ .bind(format!("-{hours} hours"))+ .bind(id)+ .execute(&self.pool)+ .await?;+ Ok(())+ }+/// Records a call that ran without a card because approvals were off./// Records a call kwnt refused on its own (it named kwnt's secret files), as `denied`.pub async fn save_refused(&self, input: &super::models::NewApproval) -> Result<String, DbError> {diff --git a/src/db/mod.rs b/src/db/mod.rsindex 016a10be..88e00381 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -127,6 +127,8 @@ impl Database {let _ = sqlx::query("ALTER TABLE teams ADD COLUMN workspace_path TEXT;").execute(&pool).await;let _ = sqlx::query("ALTER TABLE teams ADD COLUMN repo_url TEXT;").execute(&pool).await;let _ = sqlx::query("ALTER TABLE kwants ADD COLUMN soul TEXT NOT NULL DEFAULT '';").execute(&pool).await;+ // The chat a card that outlived its turn resumes in (see `park_approval`)+ let _ = sqlx::query("ALTER TABLE approvals ADD COLUMN resume TEXT;").execute(&pool).await;let db = Self { pool };db.migrate_profiles().await?;diff --git a/src/mcp/mod.rs b/src/mcp/mod.rsindex 2792c342..d5a7f394 100644--- a/src/mcp/mod.rs+++ b/src/mcp/mod.rs@@ -273,6 +273,55 @@ pub struct BuiltinCall {#[async_trait]pub trait ToolApprover: Send + Sync {async fn approve(&self, request: ToolApprovalRequest) -> bool;++ /// [`approve`](Self::approve), telling a refusal apart from a card nobody answered in time.+ async fn decide(&self, request: ToolApprovalRequest) -> ApprovalOutcome {+ if self.approve(request).await {+ ApprovalOutcome::Allowed+ } else {+ ApprovalOutcome::Denied+ }+ }+}++/// What became of a call that may have needed a card.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ApprovalOutcome {+ Allowed,+ Denied,+ /// Nobody answered before the wait ran out. The card stays open, and a late Allow starts a+ /// new turn to continue.+ Unanswered,+}++/// What the bot is told when the person refused a call.+pub const DENIED_TEXT: &str = "The user denied this tool call.";+/// What the bot is told when nobody answered the card in time.+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.";++impl ApprovalOutcome {+ pub fn allowed(self) -> bool {+ self == ApprovalOutcome::Allowed+ }++ /// The tool result a call that didn't run gets.+ pub fn refusal_text(self) -> &'static str {+ match self {+ ApprovalOutcome::Unanswered => UNANSWERED_TEXT,+ _ => DENIED_TEXT,+ }+ }++ /// The record status of a call that didn't run.+ pub fn record_status(self) -> &'static str {+ match self {+ ApprovalOutcome::Allowed => "allowed",+ ApprovalOutcome::Denied => "denied",+ ApprovalOutcome::Unanswered => "unanswered",+ }+ }}/// Approves or denies everything; for tests and tooling.diff --git a/src/mcp/session.rs b/src/mcp/session.rsindex 2e8f77a4..aaa11ba2 100644--- a/src/mcp/session.rs+++ b/src/mcp/session.rs@@ -231,10 +231,10 @@ impl McpToolSession {Some(_) if !arguments.is_object() => ("error", "Tool arguments must be a JSON object.".to_string()),Some(t) => {let (server, client) = &self.clients[t.server_index];- let approved = self+ let outcome = self.ctx.approver- .approve(ToolApprovalRequest {+ .decide(ToolApprovalRequest {kwant_id: caller.kwant_id.clone(),kwant_name: caller.kwant_name.clone(),turn_id: caller.turn_id.clone(),@@ -245,8 +245,8 @@ impl McpToolSession {builtin: None,}).await;- if !approved {- ("denied", "The user denied this tool call.".to_string())+ if !outcome.allowed() {+ (outcome.record_status(), outcome.refusal_text().to_string())} else {match client.call_tool(&t.tool.name, arguments.clone()).await {Ok(r) if r.is_error => ("error", r.text),@@ -267,7 +267,7 @@ impl McpToolSession {"status": status,"duration_ms": start.elapsed().as_millis() as u64,});- if status != "denied" {+ if status != "denied" && status != "unanswered" {record["result"] = json!(truncate_text(&text, RECORD_RESULT_MAX_CHARS));}self.ctx.record(record.clone());diff --git a/src/server/away.rs b/src/server/away.rsindex 35731bfd..5d7a1801 100644--- a/src/server/away.rs+++ b/src/server/away.rs@@ -298,6 +298,13 @@ async fn waiting_approvals(state: &AppState, space: &SpaceId) -> Result<Vec<AwayNone => row.direct_kwant_id = Some(row.kwant_id.clone()),}}+ // Cards whose turn stopped waiting: still answerable, and a late Allow resumes the work+ for row in state.db.away_waiting_approvals().await? {+ let of = state.db.space_of_kwant(&row.kwant_id).await?.unwrap_or_else(SpaceId::default_space);+ if &of == space && !rows.iter().any(|r| r.id == row.id) {+ rows.push(row);+ }+ }Ok(rows)}diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 3109ccc7..7045eef5 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -240,7 +240,14 @@ pub struct SelfToolsApprover {#[async_trait]impl ToolApprover for SelfToolsApprover {async fn approve(&self, req: ToolApprovalRequest) -> bool {- req.server == SELF_SERVER_NAME || self.inner.approve(req).await+ self.decide(req).await.allowed()+ }++ async fn decide(&self, req: ToolApprovalRequest) -> crate::mcp::ApprovalOutcome {+ if req.server == SELF_SERVER_NAME {+ return crate::mcp::ApprovalOutcome::Allowed;+ }+ self.inner.decide(req).await}}diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex fb14f0f6..62125a34 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -12,7 +12,7 @@ use crate::mcp::{self,client::PROTOCOL_VERSION,session::{Caller, GatewayNaming, McpToolSession},- GatewayAccess, McpTurnContext, ToolApprovalRequest, ToolApprover,+ ApprovalOutcome, GatewayAccess, McpTurnContext, ToolApprovalRequest, ToolApprover,};use async_trait::async_trait;use axum::{@@ -31,7 +31,7 @@ use tokio_util::sync::CancellationToken;/// How long `finish_turn` waits for cancelled in-flight calls to release the turn's servers.const CLOSE_GRACE: Duration = Duration::from_secs(10);-/// How long a tool call waits for the user before it is denied.+/// How long a tool call waits for the user before its turn stops waiting (the card stays open).pub const APPROVAL_TIMEOUT: Duration = Duration::from_secs(mcp::APPROVAL_TIMEOUT_SECS);/// The tool claude calls for permission decisions: `mcp__kwnt__approve`.pub use crate::mcp::PERMISSION_TOOL;@@ -122,6 +122,9 @@ pub struct BrokerApprover {pub timeout: Duration,/// The conversation "always allow" answers are kept for (see [`turn_conversation`]).pub conversation: String,+ /// The chat a card left unanswered resumes in after a late Allow (see [`turn_chat`]);+ /// `None` resumes in the bot's direct chat.+ pub chat: Option<Value>,}/// Withdraws the ticket if the waiting turn is cancelled (its future dropped) mid-wait.@@ -150,6 +153,10 @@ impl Drop for TicketGuard {#[async_trait]impl ToolApprover for BrokerApprover {async fn approve(&self, req: ToolApprovalRequest) -> bool {+ self.decide(req).await.allowed()+ }++ async fn decide(&self, req: ToolApprovalRequest) -> ApprovalOutcome {// Approvals the person switched off: run, and keep a record of what ran. A setting that// can't be read asks, as before.let off = self.db.kwant_approvals(&req.kwant_id).await.is_ok_and(|m| m.is_off());@@ -186,16 +193,21 @@ impl ToolApprover for BrokerApprover {if let Err(e) = self.db.save_refused(&record).await {tracing::warn!(error = %e, "could not record a refused call");}- return false;+ return ApprovalOutcome::Denied;}if !off && self.broker.is_allowed_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await {- return true;+ return ApprovalOutcome::Allowed;}if off {if let Err(e) = self.db.save_auto_allowed(&record).await {tracing::warn!(error = %e, "could not record a call that ran with approvals off");}- return true;+ return ApprovalOutcome::Allowed;+ }+ // The person allowed this exact call on a card its earlier turn stopped waiting for+ if self.broker.take_grant(&req.kwant_id, &req.tool_name, &req.arguments).await {+ tracing::info!(kwant = %req.kwant_id, tool = %req.tool_name, "ran a call the person allowed after its turn ended");+ return ApprovalOutcome::Allowed;}let ticket = match self.db@@ -205,7 +217,7 @@ impl ToolApprover for BrokerApprover {Ok(a) => a.id,Err(e) => {tracing::warn!(error = %e, "could not store MCP approval ticket; denying");- return false;+ return ApprovalOutcome::Denied;}};let rx = self@@ -232,18 +244,27 @@ impl ToolApprover for BrokerApprover {let decision = tokio::time::timeout(self.timeout, rx).await;guard.id = None;match decision {- Ok(Ok(ApprovalDecision::AllowOnce)) => true,+ Ok(Ok(ApprovalDecision::AllowOnce)) => ApprovalOutcome::Allowed,Ok(Ok(ApprovalDecision::AlwaysAllowSession)) => {self.broker.allow_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await;- true+ ApprovalOutcome::Allowed}- Ok(Ok(ApprovalDecision::Deny)) | Ok(Err(_)) => false,+ Ok(Ok(ApprovalDecision::Deny)) | Ok(Err(_)) => ApprovalOutcome::Denied,+ // 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 {- let _ = self.db.update_approval_status(&ticket, "expired").await;- let _ = self.events.send(RuntimeEvent::ApprovalWithdrawn { id: ticket });+ if !self.broker.cancel(&ticket).await {+ return ApprovalOutcome::Denied;+ }+ let chat = self.chat.clone().unwrap_or_else(|| json!({"direct_kwant_id": req.kwant_id}));+ 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::ApprovalWithdrawn { id: ticket });+ ApprovalOutcome::Denied+ }}- false}}}@@ -270,6 +291,75 @@ fn turn_conversation(state: &AppState, turn_id: &str) -> String {.unwrap_or_else(|| format!("turn:{turn_id}"))}+/// The chat a tracked turn runs in, as `{"thread_id"}`, `{"channel_id"}` or+/// `{"direct_kwant_id"}`; `None` for a turn kwnt isn't tracking.+async fn turn_chat(state: &AppState, turn_id: &str) -> Option<Value> {+ let turn = state.turns.active_turns().into_iter().find(|t| t.turn_id == turn_id)?;+ Some(match turn.thread_id {+ Some(thread) => json!({"thread_id": thread}),+ None if state.db.get_channel(&turn.context_id).await.ok().flatten().is_some() => {+ json!({"channel_id": turn.context_id})+ }+ None => json!({"direct_kwant_id": turn.context_id}),+ })+}++/// A late answer to a card whose turn stopped waiting (`waiting`). Deny just closes it. Allow+/// lets that one call run once without a new card and starts a turn in the card's chat telling+/// the bot to make it again; "always allow" also remembers the tool for that conversation.+/// Approvals, secrets and the space are checked again when the call is made. Returns the JSON+/// reply, or `None` when the card isn't waiting (anymore).+pub async fn resume_late_approval(state: &AppState, ticket_id: &str, decision: ApprovalDecision, status: &str) -> Option<Value> {+ let (approval, chat) = state.db.claim_waiting_approval(ticket_id, status).await.ok().flatten()?;+ let _ = state.event_sender.send(RuntimeEvent::ApprovalWithdrawn { id: ticket_id.to_string() });+ if decision == ApprovalDecision::Deny {+ return Some(json!({"ticket_id": ticket_id, "resolved": true, "status": status, "resumed": false}));+ }+ let not_resumed = |why: &str| Some(json!({"ticket_id": ticket_id, "resolved": true, "status": status, "resumed": false, "reason": why}));+ let Ok(Some(kwant)) = state.db.get_kwant(&approval.kwant_id).await else {+ return not_resumed("the bot no longer exists");+ };+ if super::spaces::ensure_active(state, &crate::db::spaces::SpaceId::new(&kwant.space_id)).await.is_err() {+ return not_resumed("the bot's space is archived");+ }+ let details: Value = serde_json::from_str(&approval.parameters).unwrap_or(Value::Null);+ let arguments = details.get("arguments").cloned().unwrap_or_else(|| json!({}));+ let thread_id = chat["thread_id"].as_str().map(str::to_string);+ let channel_id = chat["channel_id"].as_str().map(str::to_string);+ let conversation = thread_id.clone().or_else(|| channel_id.clone()).or_else(|| chat["direct_kwant_id"].as_str().map(str::to_string)).unwrap_or_else(|| kwant.id.clone());+ state.broker.grant_once(&kwant.id, &approval.tool_name, &arguments).await;+ if decision == ApprovalDecision::AlwaysAllowSession {+ state.broker.allow_for_session(&kwant.id, &conversation, &approval.tool_name).await;+ }+ let depth = match &thread_id {+ Some(t) => state.db.delegation_for_thread(t).await.ok().flatten().map(|d| d.depth).unwrap_or(0),+ None => 0,+ };+ let job = state.turns.start_job([conversation.clone(), ticket_id.to_string()]);+ let scope = match super::routes::scope_for(state, &kwant, channel_id, thread_id, &job, depth).await {+ Ok(s) => s,+ Err(why) => return not_resumed(&why),+ };+ let prompt = late_approval_prompt(&approval.tool_name, &arguments);+ let target = kwant.clone();+ tokio::spawn(async move {+ let _job = job;+ let _ = super::routes::try_kwant_turn(&scope, &target, prompt, Default::default()).await;+ });+ Some(json!({"ticket_id": ticket_id, "resolved": true, "status": status, "resumed": "new_turn"}))+}++/// The resumed turn's prompt after a late Allow.+pub fn late_approval_prompt(tool_name: &str, arguments: &Value) -> String {+ let args = serde_json::to_string_pretty(arguments).unwrap_or_default();+ let args: String = args.chars().take(2000).collect();+ format!(+ "[The person allowed a tool call you asked for earlier]\nTool: {tool_name}\nArguments: {args}\n\n\+Your earlier turn ended before they answered. Make this same call again now, with the same arguments \+(it runs once without a new card), then continue the task from where you stopped."+ )+}+/// Address agent CLIs on this host use to reach kwnt.fn local_base_url(state: &AppState) -> String {let host = match state.config.host.as_str() {@@ -326,6 +416,7 @@ pub async fn prepare_turn_with_self(events: state.event_sender.clone(),timeout: APPROVAL_TIMEOUT,conversation: turn_conversation(state, &turn_id),+ chat: turn_chat(state, &turn_id).await,});let ctx = McpTurnContext {servers,@@ -390,7 +481,7 @@ async fn decide(session: &PermissionSession, args: &Value) -> Value {}}};- let approval = session.ctx.approver.approve(ToolApprovalRequest {+ let approval = session.ctx.approver.decide(ToolApprovalRequest {kwant_id: session.kwant_id.clone(),kwant_name: session.kwant_name.clone(),turn_id: session.turn_id.clone(),@@ -401,8 +492,8 @@ async fn decide(session: &PermissionSession, args: &Value) -> Value {builtin,});// Dropping the approval withdraws its card when the turn ends first- let allowed = tokio::select! {- allowed = approval => allowed,+ let outcome = tokio::select! {+ outcome = approval => outcome,_ = session.ended.cancelled() => {session.ctx.record(cancelled_record(&tool_use_id, tool_name, server, tool, &input));return json!({"behavior": "deny", "message": "The turn ended before the user answered."});@@ -414,12 +505,12 @@ async fn decide(session: &PermissionSession, args: &Value) -> Value {"server": server,"tool": tool,"arguments": input,- "status": if allowed { "allowed" } else { "denied" },+ "status": outcome.record_status(),}));- if allowed {+ if outcome.allowed() {json!({"behavior": "allow", "updatedInput": input})} else {- json!({"behavior": "deny", "message": "The user denied this tool call."})+ json!({"behavior": "deny", "message": outcome.refusal_text()})}}diff --git a/src/server/routes.rs b/src/server/routes.rsindex 19167168..de035a2c 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -2501,9 +2501,18 @@ pub async fn resolve_approval(// Only a ticket still waiting can be answered; a withdrawn one (turn ended, expired)// keeps its status and its tool never runs- let resolved = state.broker.resolve(&ticket_id, decision).await;+ let resolved = state.broker.resolve(&ticket_id, decision.clone()).await;if !resolved {- return Err(StatusCode::CONFLICT);+ // A card whose turn stopped waiting: a late answer, and Allow resumes the work+ return match super::mcp_runtime::resume_late_approval(&state, &ticket_id, decision, status_str).await {+ Some(mut reply) => {+ reply["ticket_id"] = json!(ticket_id);+ reply["resolved"] = json!(true);+ reply["status"] = json!(status_str);+ Ok(Json(reply))+ }+ None => Err(StatusCode::CONFLICT),+ };}let _ = state.db.update_approval_status(&ticket_id, status_str).await;diff --git a/tests/late_approval_test.rs b/tests/late_approval_test.rsnew file mode 100644index 00000000..50aa77b4--- /dev/null+++ b/tests/late_approval_test.rs@@ -0,0 +1,125 @@+//! A card nobody answers before its turn stops waiting: the bot is told the truth (not+//! "denied"), the card stays open, and a late Allow starts a new turn whose same call runs once+//! without another card. A late Deny just closes it.++mod common;++use common::*;+use kwnt::mcp::{ApprovalOutcome, ToolApprovalRequest, ToolApprover, UNANSWERED_TEXT};+use kwnt::server::mcp_runtime::BrokerApprover;+use serde_json::{json, Value};+use std::sync::Arc;+use std::time::Duration;++fn approver(env: &Env, timeout: Duration) -> Arc<BrokerApprover> {+ Arc::new(BrokerApprover {+ db: env.state.db.clone(),+ broker: env.state.broker.clone(),+ events: env.state.event_sender.clone(),+ timeout,+ conversation: env.a.clone(),+ chat: Some(json!({"direct_kwant_id": env.a})),+ })+}++fn request(env: &Env, args: Value) -> ToolApprovalRequest {+ ToolApprovalRequest {+ kwant_id: env.a.clone(),+ kwant_name: "A".into(),+ turn_id: "t-late".into(),+ tool_name: "Bash".into(),+ server: String::new(),+ tool: "Bash".into(),+ arguments: args,+ builtin: None,+ }+}++/// Runs one call that nobody answers and returns its ticket id.+async fn unanswered(env: &Env, args: Value) -> String {+ let a = approver(env, Duration::from_millis(200));+ assert_eq!(a.decide(request(env, args)).await, ApprovalOutcome::Unanswered);+ let rows = env.state.db.list_approvals(&kwnt::db::spaces::SpaceId::default_space(), Some("waiting"), Some(&env.a)).await.unwrap();+ rows.first().expect("a waiting card").id.clone()+}++#[tokio::test]+async fn an_unanswered_card_stays_open_and_a_late_allow_resumes_the_work() {+ let env = setup().await;+ let args = json!({"command": "ls LATE_ALLOW_MARK", "description": "list"});+ let ticket = unanswered(&env, args.clone()).await;+ assert!(!env.state.broker.is_pending(&ticket).await, "the turn stopped waiting");+ assert_eq!(env.state.db.get_approval(&ticket).await.unwrap().unwrap().status, "waiting");++ // Still in the person's waiting list, linked to the chat it resumes in+ let (_, away) = call(&env.app, "GET", "/api/away", None).await;+ let item = away["waiting"].as_array().unwrap().iter().find(|i| i["id"] == ticket.as_str()).expect("card listed").clone();+ assert_eq!(item["kind"], "approval");+ assert_eq!(item["link"]["direct_kwant_id"], env.a.as_str(), "{item}");++ let (s, v) = call(&env.app, "POST", &format!("/api/approvals/{ticket}/resolve"), Some(json!({"decision": "allow_once"}))).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(v["resumed"], "new_turn");+ assert_eq!(env.state.db.get_approval(&ticket).await.unwrap().unwrap().status, "allowed_once");+ wait_for("the resumed turn", || async { !invocations_with("ls LATE_ALLOW_MARK").is_empty() }).await;+ let prompt = invocations_with("ls LATE_ALLOW_MARK").pop().unwrap();+ assert!(prompt.contains("[The person allowed a tool call you asked for earlier]"), "{prompt}");+ assert!(prompt.contains("Tool: Bash"));++ // The resumed turn's same call runs once without a card (a new description is fine)+ let a = approver(&env, Duration::from_millis(200));+ let again = json!({"command": "ls LATE_ALLOW_MARK", "description": "list the files"});+ assert_eq!(tokio::time::timeout(Duration::from_secs(1), a.decide(request(&env, again.clone()))).await.unwrap(), ApprovalOutcome::Allowed);+ // Only once, and only that call+ assert_eq!(a.decide(request(&env, again)).await, ApprovalOutcome::Unanswered);+ assert_eq!(a.decide(request(&env, json!({"command": "rm -rf LATE_ALLOW_MARK"}))).await, ApprovalOutcome::Unanswered);++ // An answered card can't be answered again+ let (s, _) = call(&env.app, "POST", &format!("/api/approvals/{ticket}/resolve"), Some(json!({"decision": "allow_once"}))).await;+ assert_eq!(s.as_u16(), 409);+}++#[tokio::test]+async fn a_late_deny_closes_the_card_and_starts_nothing() {+ let env = setup().await;+ let args = json!({"command": "ls LATE_DENY_MARK"});+ let ticket = unanswered(&env, args.clone()).await;+ let (s, v) = call(&env.app, "POST", &format!("/api/approvals/{ticket}/resolve"), Some(json!({"decision": "deny"}))).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(v["resumed"], false);+ assert_eq!(env.state.db.get_approval(&ticket).await.unwrap().unwrap().status, "denied");+ tokio::time::sleep(Duration::from_millis(500)).await;+ assert!(invocations_with("ls LATE_DENY_MARK").is_empty(), "no turn after a deny");+ let a = approver(&env, Duration::from_millis(200));+ assert_eq!(a.decide(request(&env, args)).await, ApprovalOutcome::Unanswered, "a deny grants nothing");+}++#[tokio::test]+async fn kwnt_secrets_stay_refused_even_after_a_late_allow() {+ let env = setup().await;+ let a = approver(&env, Duration::from_millis(200));+ // A grant can't reach past the secret check (it runs first)+ let secret = json!({"command": "cat ~/.kwnt/api-token"});+ assert!(kwnt::sandbox::credentials::call_touches_kwnt_secrets(&secret, None));+ env.state.broker.grant_once(&env.a, "Bash", &secret).await;+ assert_eq!(a.decide(request(&env, secret)).await, ApprovalOutcome::Denied);+}++#[tokio::test]+async fn an_old_waiting_card_expires_instead_of_resuming() {+ let env = setup().await;+ let ticket = unanswered(&env, json!({"command": "ls OLD_CARD_MARK"})).await;+ env.state.db.backdate_approval_for_test(&ticket, 25).await.unwrap();+ let (s, _) = call(&env.app, "POST", &format!("/api/approvals/{ticket}/resolve"), Some(json!({"decision": "allow_once"}))).await;+ assert_eq!(s.as_u16(), 409);+ assert_eq!(env.state.db.get_approval(&ticket).await.unwrap().unwrap().status, "expired");+ let (_, away) = call(&env.app, "GET", "/api/away", None).await;+ assert!(!away["waiting"].as_array().unwrap().iter().any(|i| i["id"] == ticket.as_str()));+}++#[test]+fn the_bot_is_told_the_card_stays_open_not_that_it_was_denied() {+ assert!(!UNANSWERED_TEXT.contains("denied"));+ assert!(UNANSWERED_TEXT.contains("stays open"));+ assert_eq!(ApprovalOutcome::Unanswered.refusal_text(), UNANSWERED_TEXT);+}diff --git a/tests/mcp_gateway_test.rs b/tests/mcp_gateway_test.rsindex d449ab44..af45a676 100644--- a/tests/mcp_gateway_test.rs+++ b/tests/mcp_gateway_test.rs@@ -182,6 +182,7 @@ async fn gateway_calls_wait_for_the_approval_card() {events: state.event_sender.clone(),timeout: Duration::from_secs(10),conversation: "conv-test".into(),+ chat: None,});register(&state, "card-tok", approver).await;let mut events = state.event_sender.subscribe();@@ -239,6 +240,7 @@ async fn ending_the_turn_cancels_a_call_waiting_for_its_card() {events: state.event_sender.clone(),timeout: Duration::from_secs(300),conversation: "conv-test".into(),+ chat: None,});let marker = format!("KWNT_TEST_MARK_{}", uuid::Uuid::new_v4().simple());let mut server = echo_server();diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rsindex 669e41f4..3f21e453 100644--- a/tests/mcp_runtime_test.rs+++ b/tests/mcp_runtime_test.rs@@ -106,6 +106,7 @@ fn approver(state: &AppState, timeout: Duration) -> Arc<BrokerApprover> {events: state.event_sender.clone(),timeout,conversation: "conv-test".into(),+ chat: None,})}@@ -136,12 +137,12 @@ async fn broker_approver_follows_user_decisions() {}#[tokio::test]-async fn unanswered_approval_expires_as_denied() {+async fn unanswered_approval_stays_open_as_waiting() {let (state, _tmp) = state().await;let (h, ticket) = ask(&state, approver(&state, Duration::from_millis(300)), "echo").await;- assert!(!h.await.unwrap());- assert!(!state.broker.is_pending(&ticket).await);- assert_eq!(state.db.get_approval(&ticket).await.unwrap().unwrap().status, "expired");+ assert!(!h.await.unwrap(), "the call doesn't run");+ assert!(!state.broker.is_pending(&ticket).await, "the turn stopped waiting");+ assert_eq!(state.db.get_approval(&ticket).await.unwrap().unwrap().status, "waiting");}#[tokio::test]