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
31k: a card is answerable as soon as it is listed (#923)
Oleksandr Ivanchenkob232483ee13b
diff --git a/src/db/mod.rs b/src/db/mod.rsindex b5ddb254..f6c5a3b5 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -684,13 +684,26 @@ impl Database {// Approvals CRUDpub async fn save_approval(&self, input: &NewApproval) -> Result<Approval, DbError> {- let id = Uuid::new_v4().to_string();+ self.save_approval_with_id(&Uuid::new_v4().to_string(), input, None).await+ }++ /// [`save_approval`](Self::save_approval) under an id picked beforehand, with the chat its+ /// card is in (as [`set_approval_chat`](Self::set_approval_chat) stores it) in the same+ /// write (31k): a card's waiter is registered under its id first, so the card is+ /// answerable, and links to its chat, from the moment it is listed.+ pub async fn save_approval_with_id(+ &self,+ id: &str,+ input: &NewApproval,+ chat: Option<&serde_json::Value>,+ ) -> Result<Approval, DbError> {+ let id = id.to_string();let params_json = serde_json::to_string(&input.parameters)?;sqlx::query(r#"- INSERT INTO approvals (id, turn_id, kwant_id, tool_name, parameters, status)- VALUES (?, ?, ?, ?, ?, 'pending')+ INSERT INTO approvals (id, turn_id, kwant_id, tool_name, parameters, status, resume)+ VALUES (?, ?, ?, ?, ?, 'pending', ?)"#,).bind(&id)@@ -698,6 +711,7 @@ impl Database {.bind(&input.kwant_id).bind(&input.tool_name).bind(¶ms_json)+ .bind(chat.map(|c| c.to_string())).execute(&self.pool).await?;diff --git a/src/server/computer.rs b/src/server/computer.rsindex c974a53a..e4661034 100644--- a/src/server/computer.rs+++ b/src/server/computer.rs@@ -394,22 +394,8 @@ async fn approve_local_shell_with(}return true;}- let ticket = match state- .db- .save_approval(&NewApproval {- turn_id: String::new(),- kwant_id: target_id.to_string(),- tool_name: "execute_shell".into(),- parameters: details.clone(),- })- .await- {- Ok(a) => a.id,- Err(e) => {- tracing::warn!(error = %e, "could not store local shell approval; denying");- return false;- }- };+ // 31k: the waiter first, then the row, so a listed card is always answerable+ let ticket = uuid::Uuid::new_v4().to_string();let rx = state.broker.request_approval(ApprovalRequest {@@ -419,6 +405,25 @@ async fn approve_local_shell_with(details: details.clone(),}).await;+ let saved = state+ .db+ .save_approval_with_id(+ &ticket,+ &NewApproval {+ turn_id: String::new(),+ kwant_id: target_id.to_string(),+ tool_name: "execute_shell".into(),+ parameters: details.clone(),+ },+ None,+ )+ .await;+ if let Err(e) = saved {+ state.broker.cancel(&ticket).await;+ tracing::warn!(error = %e, "could not store local shell approval; denying");+ return false;+ }+ super::mcp_runtime::card_listed(target_id).await;let _ = state.event_sender.send(RuntimeEvent::ApprovalRequired {id: ticket.clone(),tool_name: "execute_shell".into(),diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex 5a3cf900..22799eb1 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -159,6 +159,32 @@ pub struct BrokerApprover {pub data_dir: PathBuf,}+fn held_cards() -> &'static std::sync::Mutex<std::collections::HashMap<String, Arc<tokio::sync::Notify>>> {+ static HELD: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, Arc<tokio::sync::Notify>>>> =+ std::sync::OnceLock::new();+ HELD.get_or_init(Default::default)+}++/// Test-only (31k): the next card for `kwant_id` stops right after it is listed (its row is+/// `pending`, so /api/approvals, Needs you and the Inbox show it), before its bot finishes+/// setting it up, until the test calls `notify_one` on the returned gate. Lets a test answer a+/// card in that moment, the way a fast tap on a freshly listed card does on a busy machine.+#[doc(hidden)]+pub fn hold_next_card_after_listing(kwant_id: &str) -> Arc<tokio::sync::Notify> {+ let gate = Arc::new(tokio::sync::Notify::new());+ held_cards().lock().unwrap_or_else(|e| e.into_inner()).insert(kwant_id.to_string(), gate.clone());+ gate+}++/// Where a card held by [`hold_next_card_after_listing`] waits, once it is listed; every other+/// card goes straight on.+pub(crate) async fn card_listed(kwant_id: &str) {+ let gate = held_cards().lock().unwrap_or_else(|e| e.into_inner()).remove(kwant_id);+ if let Some(gate) = gate {+ gate.notified().await;+ }+}+/// Withdraws the ticket if the waiting turn is cancelled (its future dropped) mid-wait.struct TicketGuard {id: Option<String>,@@ -510,21 +536,10 @@ impl BrokerApprover {tracing::info!(kwant = %req.kwant_id, tool = %req.tool_name, "ran a call the person allowed after its turn ended");return (ApprovalOutcome::Allowed, "approved", None);}- let ticket = match self- .db- .save_approval(&record)- .await- {- Ok(a) => a.id,- Err(e) => {- tracing::warn!(error = %e, "could not store MCP approval ticket; denying");- return (ApprovalOutcome::Denied, "denied", None);- }- };- // Its chat is known from the start: the board links to it, and a card that outlives a- // restart still resumes there (see `keep_cards_after_restart`)- let chat = self.chat.clone().unwrap_or_else(|| json!({"direct_kwant_id": req.kwant_id}));- let _ = self.db.set_approval_chat(&ticket, &chat).await;+ // 31k: the waiter first, then the row. A card is listed (`pending` in /api/approvals,+ // Needs you, the Inbox) only once an answer to it reaches this call; before, a Deny in+ // between was told "This card expired" and the call kept waiting+ let ticket = uuid::Uuid::new_v4().to_string();let rx = self.broker.request_approval(ApprovalRequest {@@ -540,6 +555,16 @@ impl BrokerApprover {db: self.db.clone(),events: self.events.clone(),};+ // Its chat is known from the start, stored with the card: the board links to it, and a+ // card that outlives a restart still resumes there (see `keep_cards_after_restart`)+ let chat = self.chat.clone().unwrap_or_else(|| json!({"direct_kwant_id": req.kwant_id}));+ if let Err(e) = self.db.save_approval_with_id(&ticket, &record, Some(&chat)).await {+ guard.id = None;+ self.broker.cancel(&ticket).await;+ tracing::warn!(error = %e, "could not store MCP approval ticket; denying");+ return (ApprovalOutcome::Denied, "denied", None);+ }+ card_listed(&req.kwant_id).await;let _ = self.events.send(RuntimeEvent::ApprovalRequired {id: ticket.clone(),tool_name: req.tool_name.clone(),diff --git a/tests/deny_ends_declined_test.rs b/tests/deny_ends_declined_test.rsindex f4855ebe..7e273fa3 100644--- a/tests/deny_ends_declined_test.rs+++ b/tests/deny_ends_declined_test.rs@@ -161,3 +161,124 @@ async fn the_routine_list_carries_the_last_runs_error() {db.start_routine_run(&id, "manual", "ok", None).await.unwrap();assert_eq!(listed().await, (json!("ok"), Value::Null));}++/// 31k: a card is answerable as soon as it is listed. The bot is held right after its card shows+/// up `pending` (before it has finished setting the card up); the person's Deny in that moment+/// still reaches the bot, is never "This card expired", and the run ends on their no.+#[tokio::test]+async fn a_deny_on_a_card_just_listed_reaches_the_bot() {+ let env = setup().await;+ env.state+ .db+ .set_space_approvals(&SpaceId::default_space(), "ask")+ .await+ .unwrap();+ env.state.approval_wait_ms.store(60_000, Ordering::Relaxed);+ let gate = kwnt::server::mcp_runtime::hold_next_card_after_listing(&env.a);+ let marker = call_tool_marker(+ "bash",+ json!({"command": "rm -rf DENY31K_BUILD", "description": "clean the build"}),+ );+ let (s, r) = call(+ &env.app,+ "POST",+ "/api/routines",+ Some(json!({"kwant_id": env.a, "name": "Clean", "instructions":+ format!("Clean the build {marker} ASKFIRST ASKAS:Bash REPLYTAG:deny31k"),+ "schedule": {"type": "daily", "time": "03:00", "tz": "UTC"}})),+ )+ .await;+ assert_eq!(s.as_u16(), 201, "{r}");+ let id = r["id"].as_str().unwrap().to_string();+ let (s, run) = call(&env.app, "POST", &format!("/api/routines/{id}/run"), None).await;+ assert_eq!(s.as_u16(), 202, "{run}");+ let run_id = run["id"].as_str().unwrap().to_string();++ let open = || async {+ env.state+ .db+ .list_approvals(&SpaceId::default_space(), Some("pending"), Some(&env.a))+ .await+ .unwrap()+ };+ wait_for("the card", || async { !open().await.is_empty() }).await;+ let ticket = open().await[0].id.clone();+ let (s, v) = call(+ &env.app,+ "POST",+ &format!("/api/approvals/{ticket}/resolve"),+ Some(json!({"decision": "deny"})),+ )+ .await;+ assert!(s.is_success(), "a Deny on a listed card reaches the bot: {v}");+ // Listed with its chat in the same write, so the board links to it even when answered at once+ assert!(env.state.db.approval_chat(&ticket).await.unwrap().is_some(), "the card links to its chat");+ gate.notify_one();++ let find = |runs: Value| {+ runs.as_array()+ .unwrap()+ .iter()+ .find(|r| r["id"] == run_id.as_str())+ .cloned()+ .unwrap_or(Value::Null)+ };+ wait_for("the run to end", || async {+ let (_, runs) = call(&env.app, "GET", &format!("/api/routines/{id}/runs"), None).await;+ let run = find(runs);+ !run.is_null() && run["status"] != "running"+ })+ .await;+ let (_, runs) = call(&env.app, "GET", &format!("/api/routines/{id}/runs"), None).await;+ let run = find(runs);+ assert_eq!(+ (&run["status"], &run["error"]),+ (&json!("incomplete"), &json!("You said no to Bash; nothing ran")),+ "{run}"+ );+ let card = env.state.db.get_approval(&ticket).await.unwrap().unwrap();+ assert_eq!(card.status, "denied");+}++/// 31k: the same for a local shell command's card (`approve_local_shell`): a Deny the moment it+/// is listed reaches the waiting command, which does not run.+#[tokio::test]+async fn a_deny_on_a_local_shell_card_just_listed_reaches_it() {+ let env = setup().await;+ env.state+ .db+ .set_space_approvals(&SpaceId::default_space(), "ask")+ .await+ .unwrap();+ let gate = kwnt::server::mcp_runtime::hold_next_card_after_listing(&env.a);+ let folder = tempfile::tempdir().unwrap();+ let (state, a, f) = (env.state.clone(), env.a.clone(), folder.path().to_path_buf());+ let waiting = tokio::spawn(async move {+ kwnt::server::computer::approve_local_shell(&state, &a, "rm -rf DENY31K_LOCAL", &f).await+ });+ let open = || async {+ env.state+ .db+ .list_approvals(&SpaceId::default_space(), Some("pending"), Some(&env.a))+ .await+ .unwrap()+ };+ wait_for("the card", || async { !open().await.is_empty() }).await;+ let ticket = open().await[0].id.clone();+ let (s, v) = call(+ &env.app,+ "POST",+ &format!("/api/approvals/{ticket}/resolve"),+ Some(json!({"decision": "deny"})),+ )+ .await;+ assert!(s.is_success(), "a Deny on a listed card reaches the command: {v}");+ gate.notify_one();+ let ran = tokio::time::timeout(std::time::Duration::from_secs(30), waiting)+ .await+ .expect("the command heard the Deny")+ .unwrap();+ assert!(!ran, "nothing runs");+ let card = env.state.db.get_approval(&ticket).await.unwrap().unwrap();+ assert_eq!(card.status, "denied");+}