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.

25e: Always allow survives a restart, and can be taken back (backend) (#761)

Oleksandr Ivanchenko1882b3708a8b
diff --git a/docs/approvals.md b/docs/approvals.md
index 109662ff..9608a89e 100644
--- a/docs/approvals.md
+++ b/docs/approvals.md
@@ -129,7 +129,8 @@ Writes and edits outside the folder and unknown tools still ask. Under every mod
## "Always this session"
Under `ask` and `smart`, "Always this session" on a claude tool's card allows that tool (e.g. all
-`Bash`) for that bot and conversation until kwnt restarts. Under `smart`, API drivers'
+`Bash`) for that bot and conversation, also after kwnt restarts (table `always_allowed`), until the
+person takes it back (`DELETE /api/kwants/:id/always-allowed`, see [mcp-api.md](mcp-api.md)). Under `smart`, API drivers'
`execute_shell` is remembered the same way, per conversation; under `ask` it covers that one
command only. Neither covers a payment, and "Always this session" on a payment's card allows that
one call.
diff --git a/docs/mcp-api.md b/docs/mcp-api.md
index 950661bb..f1ff315e 100644
--- a/docs/mcp-api.md
+++ b/docs/mcp-api.md
@@ -386,7 +386,18 @@ bot's approvals are `off`, or `smart` and the server marks the tool `readOnlyHin
and stores the ticket in `approvals`.
2. The UI resolves it with the existing `POST /api/approvals/:id/resolve`
`{"decision": "allow_once" | "always_allow" | "deny"}`.
- `always_allow` allows that tool for that kwant until kwnt restarts.
+ `always_allow` lets that kwant use that tool in that conversation (the thread, else the channel,
+ else the direct chat) without asking again, also after kwnt restarts (table `always_allowed`,
+ kept out of exports and imports). Never for a payment, a production step, a shell card or an
+ always-ask tool. The person sees each one, and takes it back, in the bot's settings; both
+ routes are person-only:
+ - `GET /api/kwants/:id/always-allowed` →
+ `[{"tool_name","conversation","conversation_kind":"thread"|"channel"|"direct"|"unknown","conversation_label","created_at"}]`,
+ newest first (`conversation_label` is the thread's title, `#<channel>` or `your chat`).
+ - `DELETE /api/kwants/:id/always-allowed` with `{"conversation","tool_name"}` takes back that
+ one, with `{}` all of them → `{"revoked": <count>, "always_allowed": [...what is left]}`.
+ An empty body or only one of the two fields is `400`. The next call asks again, no restart
+ needed. Deleting the bot, or its thread or channel, removes its answers too.
With Flight School on (`flight_school`), a bot below `act` for the task it works gets a card for calls
its tier doesn't allow even with approvals `off` or a smart Allow, with `details.tier_reason`; see
[mission-control.md](mission-control.md) §14.
diff --git a/site/docs/approvals.html b/site/docs/approvals.html
index 1cece153..4953b859 100644
--- a/site/docs/approvals.html
+++ b/site/docs/approvals.html
@@ -74,7 +74,7 @@
<p>When a bot wants to run a command, edit a file outside its folder or call a tool, you see a card with what it will do:</p>
<ul>
<li><strong>Allow once</strong> runs this one call.</li>
- <li><strong>Always allow</strong> allows that tool for that bot until kwant restarts.</li>
+ <li><strong>Always allow</strong> lets that bot use that tool in that conversation without asking again, also after kwant restarts. You can see each one, and take it back, in the bot's settings.</li>
<li><strong>Deny</strong> refuses it, and the bot is told.</li>
</ul>
<figure>
@@ -111,7 +111,7 @@
<div class="note warn"><strong><code>smart</code> guards against accidents. It isn't a sandbox.</strong> Scripts in the bot's folder, <code>make</code>, <code>cargo build</code> and <code>npm run</code> run without a card and can do anything the bot's user can, including a script the bot wrote a moment earlier. Use <code>ask</code> for bots or folders you don't trust.</div>
<h3 id="session">"Always this session"</h3>
-<p>Under <code>ask</code> and <code>smart</code>, "Always this session" on a Claude tool's card allows that tool, for example all <code>Bash</code>, for that bot and conversation until kwant restarts.</p>
+<p>Under <code>ask</code> and <code>smart</code>, "Always this session" on a Claude tool's card allows that tool, for example all <code>Bash</code>, for that bot and conversation, also after kwant restarts, until you take it back in the bot's settings.</p>
<h2 id="passwords">Saved passwords</h2>
<p>kwant can fill website logins in a team's, channel's or bot's browser. Passwords live in one of two stores:</p>
diff --git a/src/broker/mod.rs b/src/broker/mod.rs
index 62bfaadf..cfad5840 100644
--- a/src/broker/mod.rs
+++ b/src/broker/mod.rs
@@ -23,8 +23,14 @@ pub struct ApprovalRequest {
pub struct PermissionBroker {
pending: Arc<Mutex<HashMap<String, oneshot::Sender<ApprovalDecision>>>>,
/// (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.
+ /// that tool again in that one conversation. The fast path: each one is also written to the
+ /// `always_allowed` table once a database is attached, and loaded from it after a restart.
always_allowed: Arc<Mutex<HashSet<(String, String, String)>>>,
+ /// Where "always allow" answers are kept across restarts (see [`attach_store`](Self::attach_store)).
+ /// None: they last until kwnt restarts (a broker made on its own, in tests).
+ store: Arc<std::sync::OnceLock<crate::db::Database>>,
+ /// The stored answers were read into `always_allowed` (once per broker).
+ loaded: Arc<tokio::sync::OnceCell<()>>,
/// 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>>>,
@@ -60,9 +66,38 @@ impl PermissionBroker {
pending: Arc::new(Mutex::new(HashMap::new())),
always_allowed: Arc::new(Mutex::new(HashSet::new())),
grants: Default::default(),
+ store: Default::default(),
+ loaded: Default::default(),
}
}
+ /// Keeps "always allow" answers in `db` from now on, and reads the ones stored there before
+ /// the first lookup. The first database attached wins. [`AppState::new`](crate::server::AppState::new)
+ /// attaches its own.
+ pub fn attach_store(&self, db: crate::db::Database) {
+ let _ = self.store.set(db);
+ }
+
+ /// Reads the stored "always allow" answers into memory, once; how many were read (0 on the
+ /// later calls). kwnt calls it at startup; every lookup and change makes sure of it first.
+ pub async fn load_saved(&self) -> usize {
+ let mut read = 0;
+ self.loaded
+ .get_or_init(|| async {
+ let Some(db) = self.store.get() else { return };
+ match db.all_always_allowed().await {
+ Ok(rows) => {
+ read = rows.len();
+ self.always_allowed.lock().await.extend(rows);
+ }
+ // The answers in memory still hold for this run; a later start tries again
+ Err(e) => tracing::warn!(error = %e, "could not read the stored \"always allow\" answers"),
+ }
+ })
+ .await;
+ read
+ }
+
/// Lets one later call of `tool_name` with these `arguments` by this kwant, in this
/// `conversation`, run without a card (a late Allow). Lapses after [`GRANT_TTL`], or when
/// [`drop_grant`](Self::drop_grant) is called because the resumed turn ended without it.
@@ -148,8 +183,15 @@ impl PermissionBroker {
}
/// Remembers an "always allow" answer for this kwant and tool in one conversation (a thread,
- /// else the channel or direct chat). Another conversation with the same bot asks again.
+ /// else the channel or direct chat), also after kwnt restarts. Another conversation with the
+ /// same bot asks again. If it can't be stored it still holds until kwnt restarts.
pub async fn allow_for_session(&self, kwant_id: &str, conversation: &str, tool_name: &str) {
+ self.load_saved().await;
+ if let Some(db) = self.store.get() {
+ if let Err(e) = db.save_always_allowed(kwant_id, conversation, tool_name).await {
+ tracing::warn!(kwant = %kwant_id, tool = %tool_name, error = %e, "could not store an \"always allow\": it lasts until kwnt restarts");
+ }
+ }
self.always_allowed.lock().await.insert((
kwant_id.to_string(),
conversation.to_string(),
@@ -157,13 +199,65 @@ impl PermissionBroker {
));
}
- /// Forgets a deleted bot's "always allow" answers.
+ /// The person takes back one "always allow": the next call asks again. True when it was
+ /// there, in memory or stored.
+ pub async fn revoke(&self, kwant_id: &str, conversation: &str, tool_name: &str) -> Result<bool, crate::db::DbError> {
+ self.load_saved().await;
+ // Memory first: it stops working at once, even if the stored row can't be removed
+ let in_memory = self.always_allowed.lock().await.remove(&(
+ kwant_id.to_string(),
+ conversation.to_string(),
+ tool_name.to_string(),
+ ));
+ let stored = match self.store.get() {
+ Some(db) => db.delete_always_allowed(kwant_id, conversation, tool_name).await?,
+ None => false,
+ };
+ Ok(in_memory || stored)
+ }
+
+ /// The person takes back all of a bot's "always allow" answers; how many there were.
+ pub async fn revoke_all(&self, kwant_id: &str) -> Result<u64, crate::db::DbError> {
+ self.load_saved().await;
+ let in_memory = {
+ let mut set = self.always_allowed.lock().await;
+ let before = set.len();
+ set.retain(|(k, _, _)| k != kwant_id);
+ (before - set.len()) as u64
+ };
+ let stored = match self.store.get() {
+ Some(db) => db.delete_all_always_allowed(kwant_id).await?,
+ None => 0,
+ };
+ Ok(in_memory.max(stored))
+ }
+
+ /// Forgets a deleted bot's "always allow" answers (its stored rows go with the bot).
pub async fn forget_kwant(&self, kwant_id: &str) {
+ self.load_saved().await;
self.always_allowed.lock().await.retain(|(k, _, _)| k != kwant_id);
self.grants.lock().await.retain(|g| g.kwant_id != kwant_id);
+ if let Some(db) = self.store.get() {
+ if let Err(e) = db.delete_all_always_allowed(kwant_id).await {
+ tracing::warn!(kwant = %kwant_id, error = %e, "could not forget a deleted bot's \"always allow\" answers");
+ }
+ }
+ }
+
+ /// Forgets the "always allow" answers in a deleted thread or channel.
+ pub async fn forget_conversation(&self, conversation: &str) {
+ self.load_saved().await;
+ self.always_allowed.lock().await.retain(|(_, c, _)| c != conversation);
+ self.grants.lock().await.retain(|g| g.conversation != conversation);
+ if let Some(db) = self.store.get() {
+ if let Err(e) = db.delete_always_allowed_in(conversation).await {
+ tracing::warn!(conversation, error = %e, "could not forget a deleted conversation's \"always allow\" answers");
+ }
+ }
}
pub async fn is_allowed_for_session(&self, kwant_id: &str, conversation: &str, tool_name: &str) -> bool {
+ self.load_saved().await;
self.always_allowed.lock().await.contains(&(
kwant_id.to_string(),
conversation.to_string(),
@@ -171,3 +265,32 @@ impl PermissionBroker {
))
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn without_a_store_an_answer_lasts_for_this_broker_only() {
+ let b = PermissionBroker::new();
+ b.allow_for_session("k1", "th1", "Bash").await;
+ assert!(b.is_allowed_for_session("k1", "th1", "Bash").await);
+ assert!(!b.is_allowed_for_session("k1", "th2", "Bash").await);
+ assert!(!PermissionBroker::new().is_allowed_for_session("k1", "th1", "Bash").await);
+ assert!(b.revoke("k1", "th1", "Bash").await.unwrap());
+ assert!(!b.is_allowed_for_session("k1", "th1", "Bash").await);
+ assert!(!b.revoke("k1", "th1", "Bash").await.unwrap());
+ }
+
+ #[tokio::test]
+ async fn revoke_all_counts_one_bots_answers_only() {
+ let b = PermissionBroker::new();
+ b.allow_for_session("k1", "th1", "Bash").await;
+ b.allow_for_session("k1", "th2", "Write").await;
+ b.allow_for_session("k2", "th1", "Bash").await;
+ assert_eq!(b.revoke_all("k1").await.unwrap(), 2);
+ assert!(b.is_allowed_for_session("k2", "th1", "Bash").await);
+ b.forget_conversation("th1").await;
+ assert!(!b.is_allowed_for_session("k2", "th1", "Bash").await);
+ }
+}
diff --git a/src/db/always_allowed.rs b/src/db/always_allowed.rs
new file mode 100644
index 00000000..1ec1ffc8
--- /dev/null
+++ b/src/db/always_allowed.rs
@@ -0,0 +1,122 @@
+//! "Always allow" answers: that bot may use that tool again in that one conversation (a thread,
+//! else the channel, else the direct chat) without a card, also after kwnt restarts (25e). The
+//! broker keeps them in memory as its fast path and writes each one through to this table; it
+//! loads the table once when it starts.
+//!
+//! Kept in its own table, outside exports and imports (like `approval_modes`), so a bundle can't
+//! bring grants with it. A row goes when its bot, thread or channel is deleted (triggers below),
+//! or when the person takes it back (`DELETE /api/kwants/:id/always-allowed`).
+
+use super::{Database, DbError};
+use chrono::{DateTime, Utc};
+
+const CREATE_ALWAYS_ALLOWED: &str = "CREATE TABLE IF NOT EXISTS always_allowed (
+ kwant_id TEXT NOT NULL,
+ conversation TEXT NOT NULL,
+ tool_name TEXT NOT NULL,
+ created_at TIMESTAMP NOT NULL,
+ PRIMARY KEY (kwant_id, conversation, tool_name)
+)";
+
+/// A deleted bot, thread or channel takes its grants with it, whichever path deleted it. Made
+/// again on every start, after every step that can rebuild those tables (and drop the triggers).
+const TRIGGERS: [&str; 3] = [
+ "CREATE TRIGGER IF NOT EXISTS always_allowed_bot_gone AFTER DELETE ON kwants BEGIN \
+ DELETE FROM always_allowed WHERE kwant_id = OLD.id; END",
+ "CREATE TRIGGER IF NOT EXISTS always_allowed_thread_gone AFTER DELETE ON threads BEGIN \
+ DELETE FROM always_allowed WHERE conversation = OLD.id; END",
+ "CREATE TRIGGER IF NOT EXISTS always_allowed_channel_gone AFTER DELETE ON channels BEGIN \
+ DELETE FROM always_allowed WHERE conversation = OLD.id; END",
+];
+
+/// One grant as the bot's settings list it.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
+pub struct AlwaysAllowed {
+ pub tool_name: String,
+ /// The thread id, else the channel id, else the bot's id for its direct chat.
+ pub conversation: String,
+ /// `thread`, `channel` or `direct`; `unknown` for a conversation that no longer exists.
+ pub conversation_kind: &'static str,
+ /// The thread's title, `#<channel>`, or `your chat`.
+ pub conversation_label: String,
+ pub created_at: DateTime<Utc>,
+}
+
+impl Database {
+ pub(super) async fn migrate_always_allowed(&self) -> Result<(), DbError> {
+ sqlx::query(CREATE_ALWAYS_ALLOWED).execute(&self.pool).await?;
+ for sql in TRIGGERS {
+ sqlx::query(sql).execute(&self.pool).await?;
+ }
+ Ok(())
+ }
+
+ /// Stores an "always allow"; a second one for the same bot, conversation and tool keeps the
+ /// first one's time.
+ pub async fn save_always_allowed(&self, kwant_id: &str, conversation: &str, tool_name: &str) -> Result<(), DbError> {
+ sqlx::query("INSERT OR IGNORE INTO always_allowed (kwant_id, conversation, tool_name, created_at) VALUES (?, ?, ?, ?)")
+ .bind(kwant_id)
+ .bind(conversation)
+ .bind(tool_name)
+ .bind(Utc::now())
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ /// Every stored grant as (bot, conversation, tool), for the broker's start.
+ pub async fn all_always_allowed(&self) -> Result<Vec<(String, String, String)>, DbError> {
+ Ok(sqlx::query_as("SELECT kwant_id, conversation, tool_name FROM always_allowed").fetch_all(&self.pool).await?)
+ }
+
+ /// One bot's grants, newest first, with where each applies in words.
+ pub async fn list_always_allowed(&self, kwant_id: &str) -> Result<Vec<AlwaysAllowed>, DbError> {
+ type Row = (String, String, DateTime<Utc>, Option<String>, Option<String>);
+ let rows: Vec<Row> = sqlx::query_as(
+ "SELECT a.tool_name, a.conversation, a.created_at, t.title, c.name
+ FROM always_allowed a
+ LEFT JOIN threads t ON t.id = a.conversation
+ LEFT JOIN channels c ON c.id = a.conversation
+ WHERE a.kwant_id = ?
+ ORDER BY a.created_at DESC, a.tool_name",
+ )
+ .bind(kwant_id)
+ .fetch_all(&self.pool)
+ .await?;
+ Ok(rows
+ .into_iter()
+ .map(|(tool_name, conversation, created_at, thread, channel)| {
+ let (conversation_kind, conversation_label) = match (thread, channel) {
+ (Some(title), _) => ("thread", title),
+ (None, Some(name)) => ("channel", format!("#{name}")),
+ (None, None) if conversation == kwant_id => ("direct", "your chat".to_string()),
+ (None, None) => ("unknown", conversation.clone()),
+ };
+ AlwaysAllowed { tool_name, conversation, conversation_kind, conversation_label, created_at }
+ })
+ .collect())
+ }
+
+ /// Takes back one grant; true when there was one.
+ pub async fn delete_always_allowed(&self, kwant_id: &str, conversation: &str, tool_name: &str) -> Result<bool, DbError> {
+ let done = sqlx::query("DELETE FROM always_allowed WHERE kwant_id = ? AND conversation = ? AND tool_name = ?")
+ .bind(kwant_id)
+ .bind(conversation)
+ .bind(tool_name)
+ .execute(&self.pool)
+ .await?;
+ Ok(done.rows_affected() > 0)
+ }
+
+ /// Takes back all of a bot's grants; how many there were.
+ pub async fn delete_all_always_allowed(&self, kwant_id: &str) -> Result<u64, DbError> {
+ let done = sqlx::query("DELETE FROM always_allowed WHERE kwant_id = ?").bind(kwant_id).execute(&self.pool).await?;
+ Ok(done.rows_affected())
+ }
+
+ /// Forgets the grants in one conversation (its thread or channel was deleted).
+ pub async fn delete_always_allowed_in(&self, conversation: &str) -> Result<u64, DbError> {
+ let done = sqlx::query("DELETE FROM always_allowed WHERE conversation = ?").bind(conversation).execute(&self.pool).await?;
+ Ok(done.rows_affected())
+ }
+}
diff --git a/src/db/bot_actions.rs b/src/db/bot_actions.rs
index 1b1b13f4..630d7ba7 100644
--- a/src/db/bot_actions.rs
+++ b/src/db/bot_actions.rs
@@ -408,6 +408,7 @@ pub(super) async fn purge_kwant(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, id
"DELETE FROM questions WHERE kwant_id = ?1 OR direct_kwant_id = ?1",
"DELETE FROM approvals WHERE kwant_id = ?1",
"DELETE FROM approval_modes WHERE scope = 'kwant' AND id = ?1",
+ "DELETE FROM always_allowed WHERE kwant_id = ?1",
"DELETE FROM skills WHERE kwant_id = ?1",
"DELETE FROM mcp_suggestions WHERE kwant_id = ?1 OR direct_kwant_id = ?1",
"DELETE FROM hire_proposals WHERE kwant_id = ?1 OR direct_kwant_id = ?1",
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 993ea444..f51c4cda 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -21,6 +21,7 @@ pub mod hires;
pub mod imports;
pub mod team_templates;
pub mod approval_modes;
+pub mod always_allowed;
pub mod parked;
pub mod waiting;
pub mod decisions;
@@ -308,6 +309,9 @@ impl Database {
// 0.9.6: the model badge's resting value (add-only). Last, after every step that can
// rebuild `kwants`
db.migrate_last_ran_on().await?;
+ // 0.9.21 25e: "Always allow" kept across restarts (add-only, outside exports). After every
+ // step that can rebuild `kwants`, `threads` or `channels`, which would drop its triggers
+ db.migrate_always_allowed().await?;
db.pool.close().await;
// Said out loud rather than left to sqlx's default: every writer, a goal proposal
diff --git a/src/serve.rs b/src/serve.rs
index 244a2999..624ae343 100644
--- a/src/serve.rs
+++ b/src/serve.rs
@@ -55,6 +55,10 @@ pub async fn run(config: Config, shutdown: impl Future<Output = ()>) -> Result<(
}
let state = AppState::new(config.clone(), db, tools, broker, router);
+ let kept = state.broker.load_saved().await;
+ if kept > 0 {
+ tracing::info!(count = kept, "kept the \"always allow\" answers from before the restart");
+ }
// Saved passwords left in a bot's folder by older versions move into the vault
crate::server::passwords::migrate_all(&state).await;
crate::server::passwords::warn_if_exposed(&state).await;
diff --git a/src/server/always_allowed.rs b/src/server/always_allowed.rs
new file mode 100644
index 00000000..50cf089b
--- /dev/null
+++ b/src/server/always_allowed.rs
@@ -0,0 +1,103 @@
+//! The person's list of "always allow" answers for one bot (25e): which tool runs without a card
+//! in which conversation, and taking one or all of them back. Person-only (`auth::person_only`):
+//! a bot's turn token, the chat API's keys and bots' own tools can't reach either route.
+//!
+//! - `GET /api/kwants/:id/always-allowed` → `[{tool_name, conversation, conversation_kind,
+//! conversation_label, created_at}]`, newest first.
+//! - `DELETE /api/kwants/:id/always-allowed` with `{conversation, tool_name}` takes back that one,
+//! with `{}` all of them → `{revoked: <count>, always_allowed: [...what is left]}`. The very
+//! next call asks again, no restart needed.
+
+use super::AppState;
+use axum::{
+ body::Bytes,
+ extract::{Path, State},
+ http::{HeaderMap, StatusCode},
+ response::{IntoResponse, Response},
+ Json,
+};
+use serde::Deserialize;
+use serde_json::{json, Value};
+
+const REFUSAL: &str = "only the person sees and takes back \"always allow\" answers";
+
+fn error(status: StatusCode, message: &str) -> Response {
+ (status, Json(json!({"error": message}))).into_response()
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RevokeBody {
+ conversation: Option<String>,
+ tool_name: Option<String>,
+}
+
+#[allow(clippy::result_large_err)]
+async fn known_bot(state: &AppState, id: &str) -> Result<(), Response> {
+ match state.db.space_of_kwant(id).await {
+ Ok(Some(_)) => Ok(()),
+ Ok(None) => Err(error(StatusCode::NOT_FOUND, "no such bot")),
+ Err(e) => {
+ tracing::warn!(kwant = %id, error = %e, "could not look up a bot for its \"always allow\" answers");
+ Err(StatusCode::INTERNAL_SERVER_ERROR.into_response())
+ }
+ }
+}
+
+#[allow(clippy::result_large_err)]
+async fn listed(state: &AppState, id: &str) -> Result<Value, Response> {
+ match state.db.list_always_allowed(id).await {
+ Ok(rows) => Ok(json!(rows)),
+ Err(e) => {
+ tracing::warn!(kwant = %id, error = %e, "could not list a bot's \"always allow\" answers");
+ Err(StatusCode::INTERNAL_SERVER_ERROR.into_response())
+ }
+ }
+}
+
+pub async fn list(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {
+ if let Err(r) = super::mcp_suggest::refuse_agent_tokens(&state, &headers, REFUSAL).await {
+ return r;
+ }
+ if let Err(r) = known_bot(&state, &id).await {
+ return r;
+ }
+ // Answers stored before this start are in memory too from here on
+ state.broker.load_saved().await;
+ match listed(&state, &id).await {
+ Ok(v) => Json(v).into_response(),
+ Err(r) => r,
+ }
+}
+
+pub async fn revoke(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>, body: Bytes) -> Response {
+ if let Err(r) = super::mcp_suggest::refuse_agent_tokens(&state, &headers, REFUSAL).await {
+ return r;
+ }
+ // An empty body is not "all of them": the caller says so with `{}`
+ let body: RevokeBody = match serde_json::from_slice(&body) {
+ Ok(b) => b,
+ Err(_) => return error(StatusCode::BAD_REQUEST, "send {\"conversation\", \"tool_name\"} for one, or {} for all of them"),
+ };
+ if let Err(r) = known_bot(&state, &id).await {
+ return r;
+ }
+ let revoked = match (body.conversation.as_deref(), body.tool_name.as_deref()) {
+ (Some(conversation), Some(tool_name)) => state.broker.revoke(&id, conversation, tool_name).await.map(u64::from),
+ (None, None) => state.broker.revoke_all(&id).await,
+ _ => return error(StatusCode::BAD_REQUEST, "conversation and tool_name go together; send {} for all of them"),
+ };
+ let revoked = match revoked {
+ Ok(n) => n,
+ Err(e) => {
+ // Taken out of memory already, so it asks again until a restart; say it may come back
+ tracing::warn!(kwant = %id, error = %e, "could not remove a stored \"always allow\"");
+ return error(StatusCode::INTERNAL_SERVER_ERROR, "it asks again now, but couldn't be removed for good: try again");
+ }
+ };
+ tracing::info!(kwant = %id, revoked, one = body.tool_name.is_some(), "the person took back \"always allow\" answers");
+ match listed(&state, &id).await {
+ Ok(left) => Json(json!({"revoked": revoked, "always_allowed": left})).into_response(),
+ Err(r) => r,
+ }
+}
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 2ea95cae..6c09632d 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -474,6 +474,8 @@ pub fn person_only(method: &Method, path: &str) -> bool {
["", "api", "teams", _] => matches!(*method, Method::DELETE | Method::PUT | Method::PATCH),
["", "api", "channels", _] => *method == Method::PATCH,
["", "api", "kwants", _] => *method == Method::DELETE,
+ // 25e: what a bot may do without asking, and taking it back, are the person's
+ ["", "api", "kwants", _, "always-allowed"] => true,
// A bot's lessons (its failures and the person's send-backs): the person reads them; bots
// never read their own record, any method
["", "api", "kwants", _, "lessons", ..] => true,
@@ -1054,6 +1056,8 @@ mod tests {
assert!(!person_only(&get, "/api/team-templates"));
assert!(!person_only(&post, "/api/teams"));
assert!(!person_only(&get, "/api/teams/t1"));
+ assert!(person_only(&get, "/api/kwants/k1/always-allowed"));
+ assert!(person_only(&del, "/api/kwants/k1/always-allowed/"));
for (m, p) in [
(&get, "/api/spaces/s1/dev_mode"),
(&put, "/api/spaces/s1/dev_mode"),
diff --git a/src/server/bot_actions.rs b/src/server/bot_actions.rs
index b9a9dfb3..298ad27e 100644
--- a/src/server/bot_actions.rs
+++ b/src/server/bot_actions.rs
@@ -1937,7 +1937,10 @@ async fn undo_action(state: &AppState, a: &BotAction) -> Result<Option<String>,
.await?;
}
"channel_create" => match state.db.delete_empty_channel(&target).await {
- Ok(true) => super::passwords::forget_deleted_owners(state, &[&target]).await,
+ Ok(true) => {
+ super::passwords::forget_deleted_owners(state, &[&target]).await;
+ state.broker.forget_conversation(&target).await;
+ }
Ok(false) => return Err(error(StatusCode::CONFLICT, "the channel already has messages, so it is kept")),
Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response()),
},
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 331fe971..19d7e1ad 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -62,6 +62,7 @@ pub mod import_routes;
pub mod inbox;
pub mod inbox_done;
pub mod isolated_folders_routes;
+pub mod always_allowed;
pub mod approval_modes;
pub mod passwords;
pub mod loose_ends_owner;
@@ -197,6 +198,8 @@ impl AppState {
let api_token = Arc::new(auth::ApiToken::load(&config));
let browser_service = Arc::new(crate::sandbox::service::BrowserService::new(config.data_dir.clone(), config.browser_cdp_url.clone()));
let agent_vm = crate::sandbox::agent_vm::AgentVm::new(&config.data_dir, config.agents_in_vm.clone(), db.clone());
+ // "Always allow" answers are kept in this database and come back after a restart (25e)
+ broker.attach_store(db.clone());
Self {
config,
db,
@@ -359,6 +362,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/dev/notes/:note_id", patch(dev::line_notes::edit).delete(dev::line_notes::delete))
.route("/api/dev/notes/:note_id/restore", post(dev::line_notes::restore))
.route("/api/kwants/:id/approvals", get(approval_modes::get_kwant).put(approval_modes::put_kwant))
+ .route("/api/kwants/:id/always-allowed", get(always_allowed::list).delete(always_allowed::revoke))
.route("/api/settings", get(routes::get_settings).post(routes::save_settings))
.route("/api/settings/computer", get(computer::get_computer).put(computer::put_computer))
.route("/api/isolated-folders", get(isolated_folders_routes::list))
diff --git a/tests/always_allowed_test.rs b/tests/always_allowed_test.rs
new file mode 100644
index 00000000..ef7174cf
--- /dev/null
+++ b/tests/always_allowed_test.rs
@@ -0,0 +1,349 @@
+//! 25e: "Always allow" survives a kwnt restart, keeps the scope it was given for (that bot, that
+//! conversation, that tool), never covers a payment or a production step, stays out of exports
+//! and imports, goes with its bot, thread or channel, and the person can see and take back each
+//! one through person-only routes; the very next call asks again.
+
+mod common;
+
+use common::*;
+use kwnt::{
+ broker::{ApprovalDecision, PermissionBroker},
+ db::{models::NewChannel, spaces::SpaceId, Database},
+ drivers::events::RuntimeEvent,
+ mcp::{ApprovalOutcome, ToolApprovalRequest, ToolApprover},
+ server::{continuity::SelfScope, mcp_runtime::{self, BrokerApprover}},
+};
+use serde_json::{json, Value};
+use std::{sync::Arc, time::Duration};
+
+const STRIPE_POST: &str = "curl -X POST https://api.stripe.com/v1/charges -u sk_test_x: -d amount=100 -d currency=usd";
+const TOOL: &str = "mcp__notes__write_note";
+
+fn approver(db: &Database, broker: &PermissionBroker, env: &Env, conversation: &str, timeout: Duration) -> BrokerApprover {
+ BrokerApprover {
+ db: db.clone(),
+ data_dir: env.state.config.data_dir.clone(),
+ broker: broker.clone(),
+ events: env.state.event_sender.clone(),
+ timeout,
+ conversation: conversation.to_string(),
+ chat: None,
+ always_ask: false,
+ strict_ask: false,
+ started_by: None,
+ }
+}
+
+fn mcp_call(env: &Env, tool_name: &str) -> ToolApprovalRequest {
+ let (server, tool) = tool_name.strip_prefix("mcp__").and_then(|r| r.split_once("__")).unwrap_or(("", tool_name));
+ ToolApprovalRequest {
+ kwant_id: env.a.clone(),
+ kwant_name: "A".into(),
+ turn_id: "t-always".into(),
+ tool_name: tool_name.into(),
+ server: server.into(),
+ tool: tool.into(),
+ arguments: json!({"text": "hi"}),
+ builtin: None,
+ smart: None,
+ payment: None,
+ }
+}
+
+fn bash(env: &Env, command: &str) -> ToolApprovalRequest {
+ ToolApprovalRequest {
+ tool_name: "Bash".into(),
+ server: String::new(),
+ tool: "Bash".into(),
+ arguments: json!({"command": command}),
+ builtin: Some(kwnt::mcp::BuiltinCall { cwd: None, outside_folder: false }),
+ ..mcp_call(env, "Bash")
+ }
+}
+
+/// Makes the call, waits for its card and answers it with `decision`.
+async fn answer_card(env: &Env, conversation: &str, req: ToolApprovalRequest, decision: ApprovalDecision) -> ApprovalOutcome {
+ let mut events = env.state.event_sender.subscribe();
+ let a = Arc::new(approver(&env.state.db, &env.state.broker, env, conversation, Duration::from_secs(10)));
+ let pending = tokio::spawn(async move { a.decide(req).await });
+ let id = loop {
+ if let RuntimeEvent::ApprovalRequired { id, .. } = events.recv().await.unwrap() {
+ break id;
+ }
+ };
+ assert!(env.state.broker.resolve(&id, decision).await);
+ pending.await.unwrap()
+}
+
+/// Asks without anyone answering: `Allowed` means it ran without a card.
+async fn asks(env: &Env, db: &Database, broker: &PermissionBroker, conversation: &str, req: ToolApprovalRequest) -> bool {
+ match approver(db, broker, env, conversation, Duration::from_millis(200)).decide(req).await {
+ ApprovalOutcome::Allowed => false,
+ ApprovalOutcome::Unanswered => true,
+ other => panic!("unexpected outcome {other:?}"),
+ }
+}
+
+async fn stored(env: &Env) -> i64 {
+ let pool = sqlx::SqlitePool::connect(&format!("sqlite://{}", env.state.config.data_dir.join("kwnt.db").display())).await.unwrap();
+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM always_allowed").fetch_one(&pool).await.unwrap();
+ pool.close().await;
+ n
+}
+
+async fn ask_mode(env: &Env) {
+ env.state.db.set_kwant_approvals(&env.a, "ask").await.unwrap();
+}
+
+async fn thread(env: &Env, title: &str) -> String {
+ env.state.db.create_thread(&env.a, title, "chat", None, "person").await.unwrap().id
+}
+
+fn uri(env: &Env) -> String {
+ format!("/api/kwants/{}/always-allowed", env.a)
+}
+
+#[tokio::test]
+async fn a_grant_still_works_after_a_restart_and_another_conversation_still_asks() {
+ let env = setup().await;
+ ask_mode(&env).await;
+ let (t1, t2) = (thread(&env, "Weekly notes").await, thread(&env, "Other work").await);
+ assert_eq!(answer_card(&env, &t1, mcp_call(&env, TOOL), ApprovalDecision::AlwaysAllowSession).await, ApprovalOutcome::Allowed);
+ assert!(!asks(&env, &env.state.db, &env.state.broker, &t1, mcp_call(&env, TOOL)).await, "same run, same thread: no card");
+
+ // A restart: a new database handle and a new broker on the same file
+ let db = Database::init(&env.state.config.data_dir).await.unwrap();
+ let broker = PermissionBroker::new();
+ broker.attach_store(db.clone());
+ assert_eq!(broker.load_saved().await, 1);
+ assert!(!asks(&env, &db, &broker, &t1, mcp_call(&env, TOOL)).await, "the grant came back");
+ assert!(asks(&env, &db, &broker, &t2, mcp_call(&env, TOOL)).await, "another thread still asks");
+ assert!(asks(&env, &db, &broker, &env.a, mcp_call(&env, TOOL)).await, "the direct chat still asks");
+ assert!(asks(&env, &db, &broker, &t1, mcp_call(&env, "mcp__notes__delete_note")).await, "another tool still asks");
+ let mut other = mcp_call(&env, TOOL);
+ other.kwant_id = env.b.clone();
+ env.state.db.set_kwant_approvals(&env.b, "ask").await.unwrap();
+ assert!(asks(&env, &db, &broker, &t1, other).await, "another bot still asks");
+
+ // The person's list says where it applies
+ let (s, v) = call(&env.app, "GET", &uri(&env), None).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ let rows = v.as_array().unwrap();
+ assert_eq!(rows.len(), 1, "{v}");
+ assert_eq!(rows[0]["tool_name"], TOOL);
+ assert_eq!(rows[0]["conversation"], t1.as_str());
+ assert_eq!(rows[0]["conversation_kind"], "thread");
+ assert_eq!(rows[0]["conversation_label"], "Weekly notes");
+ assert!(rows[0]["created_at"].is_string(), "{v}");
+}
+
+#[tokio::test]
+async fn payments_and_production_steps_are_never_stored() {
+ let env = setup().await;
+ ask_mode(&env).await;
+ let t = thread(&env, "Pay").await;
+ assert_eq!(answer_card(&env, &t, bash(&env, STRIPE_POST), ApprovalDecision::AlwaysAllowSession).await, ApprovalOutcome::Allowed);
+ assert_eq!(stored(&env).await, 0, "a payment's always allow covers that one call");
+
+ let space = env.state.db.get_kwant(&env.a).await.unwrap().unwrap().space_id;
+ env.state.db.put_dev_mode(&space, true, "demo-org/demo-app", "main", None, Some("pg_dump demo > /tmp/demo.sql")).await.unwrap();
+ let step = bash(&env, "sqlite3 demo.db 'DROP TABLE demo'");
+ assert_eq!(answer_card(&env, &t, step, ApprovalDecision::AlwaysAllowSession).await, ApprovalOutcome::Allowed);
+ assert_eq!(stored(&env).await, 0, "a production step's always allow covers that one call");
+ assert!(!env.state.broker.is_allowed_for_session(&env.a, &t, "Bash").await);
+
+ // An ordinary tool is stored
+ assert_eq!(answer_card(&env, &t, mcp_call(&env, TOOL), ApprovalDecision::AlwaysAllowSession).await, ApprovalOutcome::Allowed);
+ assert_eq!(stored(&env).await, 1);
+}
+
+#[tokio::test]
+async fn deleting_the_bot_thread_or_channel_removes_its_rows() {
+ let env = setup().await;
+ let space = SpaceId::new(&env.state.db.get_kwant(&env.a).await.unwrap().unwrap().space_id);
+ let t = thread(&env, "Goes away").await;
+ let ch = env
+ .state
+ .db
+ .create_channel(&space, &NewChannel { name: "scratch".into(), description: None, lead_kwant_id: env.a.clone(), member_kwants: vec![env.a.clone()], routing_mode: "lead".into() })
+ .await
+ .unwrap()
+ .id;
+ let b = &env.state.broker;
+ for c in [&t, &ch, &env.a] {
+ b.allow_for_session(&env.a, c, TOOL).await;
+ }
+ b.allow_for_session(&env.b, &env.b, TOOL).await;
+ assert_eq!(stored(&env).await, 4);
+
+ let (_, v) = call(&env.app, "GET", &uri(&env), None).await;
+ let kinds: Vec<(&str, &str)> = v.as_array().unwrap().iter().map(|r| (r["conversation_kind"].as_str().unwrap(), r["conversation_label"].as_str().unwrap())).collect();
+ for want in [("thread", "Goes away"), ("channel", "#scratch"), ("direct", "your chat")] {
+ assert!(kinds.contains(&want), "{want:?} in {kinds:?}");
+ }
+
+ // Threads only go with their bot; whichever path deletes one, its rows go too
+ let pool = sqlx::SqlitePool::connect(&format!("sqlite://{}", env.state.config.data_dir.join("kwnt.db").display())).await.unwrap();
+ sqlx::query("DELETE FROM threads WHERE id = ?").bind(&t).execute(&pool).await.unwrap();
+ pool.close().await;
+ assert_eq!(stored(&env).await, 3);
+ assert!(env.state.db.delete_empty_channel(&ch).await.unwrap());
+ assert_eq!(stored(&env).await, 2);
+
+ let (s, v) = call(&env.app, "DELETE", &format!("/api/kwants/{}", env.a), None).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!(stored(&env).await, 1, "only the other bot's grant is left");
+ assert!(!b.is_allowed_for_session(&env.a, &env.a, TOOL).await);
+ assert!(b.is_allowed_for_session(&env.b, &env.b, TOOL).await);
+}
+
+#[tokio::test]
+async fn taking_back_one_or_all_works_on_the_very_next_call() {
+ let env = setup().await;
+ ask_mode(&env).await;
+ let (t1, t2) = (thread(&env, "One").await, thread(&env, "Two").await);
+ let b = &env.state.broker;
+ b.allow_for_session(&env.a, &t1, TOOL).await;
+ b.allow_for_session(&env.a, &t2, TOOL).await;
+ b.allow_for_session(&env.a, &t1, "Bash").await;
+ b.allow_for_session(&env.b, &env.b, TOOL).await;
+
+ // Bodies that don't say what to take back change nothing
+ for body in [None, Some(json!({"conversation": t1})), Some(json!({"tool_name": TOOL})), Some(json!({"everything": true})), Some(json!([]))] {
+ let (s, v) = call(&env.app, "DELETE", &uri(&env), body.clone()).await;
+ assert_eq!(s.as_u16(), 400, "{body:?}: {v}");
+ }
+ assert_eq!(stored(&env).await, 4);
+
+ let (s, v) = call(&env.app, "DELETE", &uri(&env), Some(json!({"conversation": t1, "tool_name": TOOL}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!(v["revoked"], 1);
+ assert_eq!(v["always_allowed"].as_array().unwrap().len(), 2, "{v}");
+ assert!(asks(&env, &env.state.db, b, &t1, mcp_call(&env, TOOL)).await, "taken back: asks at once");
+ assert!(!asks(&env, &env.state.db, b, &t2, mcp_call(&env, TOOL)).await, "the other thread's grant stays");
+ let (_, v) = call(&env.app, "DELETE", &uri(&env), Some(json!({"conversation": t1, "tool_name": TOOL}))).await;
+ assert_eq!(v["revoked"], 0, "a second take-back finds nothing");
+
+ let (s, v) = call(&env.app, "DELETE", &uri(&env), Some(json!({}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!(v["revoked"], 2);
+ assert_eq!(v["always_allowed"], json!([]));
+ assert!(asks(&env, &env.state.db, b, &t2, mcp_call(&env, TOOL)).await);
+ assert!(asks(&env, &env.state.db, b, &t1, bash(&env, "touch x")).await);
+ assert!(b.is_allowed_for_session(&env.b, &env.b, TOOL).await, "another bot keeps its own");
+
+ // And they stay taken back after a restart
+ let db = Database::init(&env.state.config.data_dir).await.unwrap();
+ let fresh = PermissionBroker::new();
+ fresh.attach_store(db.clone());
+ assert_eq!(fresh.load_saved().await, 1);
+ assert!(!fresh.is_allowed_for_session(&env.a, &t2, TOOL).await);
+
+ let (s, _) = call(&env.app, "GET", "/api/kwants/nobody/always-allowed", None).await;
+ assert_eq!(s.as_u16(), 404);
+}
+
+#[tokio::test]
+async fn an_export_has_no_grants_and_an_import_cant_add_any() {
+ let env = setup().await;
+ let space = env.state.db.get_kwant(&env.a).await.unwrap().unwrap().space_id;
+ env.state.broker.allow_for_session(&env.a, &env.a, TOOL).await;
+ for u in [format!("/api/kwants/{}/export?space={space}", env.a), format!("/api/export?space={space}")] {
+ let (s, v) = call(&env.app, "GET", &u, None).await;
+ assert_eq!(s.as_u16(), 200, "{u}: {v}");
+ assert!(!v.is_null(), "{u}");
+ let text = v.to_string();
+ assert!(!text.contains(TOOL) && !text.contains("always_allowed"), "{u}: {text}");
+ }
+
+ let bundle = json!({
+ "format": "kwant.bundle/1",
+ "source": {"kind": "kwant", "label": "hostile"},
+ "always_allowed": [{"kwant_id": env.b, "conversation": env.b, "tool_name": "Bash"}],
+ "bots": [{"ref": "free", "name": "Free", "title": "t", "persona_prompt": "p", "soul": "",
+ "always_allowed": [{"conversation": "x", "tool_name": "Bash"}]}]
+ });
+ let (s, p) = call(&env.app, "POST", &format!("/api/import/preview?space={space}&filename=x.kwant.json"), Some(json!({"text": bundle.to_string()}))).await;
+ assert_eq!(s.as_u16(), 200, "{p}");
+ let (s, v) = call(&env.app, "POST", &format!("/api/import/apply?space={space}"), Some(json!({"bundle": p["bundle"], "skip": []}))).await;
+ assert_eq!(s.as_u16(), 201, "{v}");
+ assert_eq!(stored(&env).await, 1, "only the person's own grant");
+}
+
+#[tokio::test]
+async fn a_bots_token_cant_call_either_route() {
+ let env = setup().await;
+ env.state.broker.allow_for_session(&env.a, &env.a, TOOL).await;
+ let bot = env.state.db.get_kwant(&env.a).await.unwrap().unwrap();
+ let folder = tempfile::tempdir().unwrap();
+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), ..Default::default() };
+ let (_, token) = mcp_runtime::prepare_turn_with_self(&env.state, &bot, None, Some(folder.path().to_path_buf()), Some(scope)).await.unwrap();
+ for bearer in [token.as_str(), "not-the-api-token"] {
+ let auth = format!("Bearer {bearer}");
+ let (s, v) = call_with(&env.app, "GET", &uri(&env), None, &[("authorization", &auth)]).await;
+ assert_eq!(s.as_u16(), 403, "{v}");
+ for body in [json!({}), json!({"conversation": env.a, "tool_name": TOOL})] {
+ let (s, v) = call_with(&env.app, "DELETE", &uri(&env), Some(body), &[("authorization", &auth)]).await;
+ assert_eq!(s.as_u16(), 403, "{v}");
+ }
+ }
+ assert_eq!(call_remote(&env.app, "GET", &uri(&env)).await.as_u16(), 401);
+ assert_eq!(call_remote(&env.app, "DELETE", &uri(&env)).await.as_u16(), 401);
+ assert_eq!(stored(&env).await, 1);
+ assert!(env.state.broker.is_allowed_for_session(&env.a, &env.a, TOOL).await);
+}
+
+/// A database from before 25e has no `always_allowed` table or triggers: starting on it makes
+/// them, and grants work and survive the next start.
+#[tokio::test]
+async fn an_upgrade_from_a_database_without_the_table_works() {
+ let tmp = tempfile::tempdir().unwrap();
+ let data = tmp.path().join("data");
+ let db = Database::init(&data).await.unwrap();
+ let bot = db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);
+ drop(db);
+ let pool = sqlx::SqlitePool::connect(&format!("sqlite://{}", data.join("kwnt.db").display())).await.unwrap();
+ for sql in [
+ "DROP TRIGGER always_allowed_bot_gone",
+ "DROP TRIGGER always_allowed_thread_gone",
+ "DROP TRIGGER always_allowed_channel_gone",
+ "DROP TABLE always_allowed",
+ ] {
+ sqlx::query(sql).execute(&pool).await.unwrap();
+ }
+ pool.close().await;
+
+ let db = Database::init(&data).await.unwrap();
+ let broker = PermissionBroker::new();
+ broker.attach_store(db.clone());
+ assert_eq!(broker.load_saved().await, 0);
+ assert!(db.list_always_allowed(&bot.id).await.unwrap().is_empty());
+ broker.allow_for_session(&bot.id, &bot.id, TOOL).await;
+ drop((db, broker));
+
+ let db = Database::init(&data).await.unwrap();
+ let broker = PermissionBroker::new();
+ broker.attach_store(db.clone());
+ assert!(broker.is_allowed_for_session(&bot.id, &bot.id, TOOL).await);
+ let pool = sqlx::SqlitePool::connect(&format!("sqlite://{}", data.join("kwnt.db").display())).await.unwrap();
+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM sqlite_master WHERE type = 'trigger' AND name LIKE 'always_allowed_%'").fetch_one(&pool).await.unwrap();
+ assert_eq!(n, 3);
+ pool.close().await;
+}
+
+/// The approvals list and the late Allow route still read the same: a waiting card answered
+/// "always allow" after its turn stopped also remembers the tool, across a restart.
+#[tokio::test]
+async fn a_late_always_allow_is_kept_too() {
+ let env = setup().await;
+ ask_mode(&env).await;
+ let a = BrokerApprover { chat: Some(json!({"direct_kwant_id": env.a})), ..approver(&env.state.db, &env.state.broker, &env, &env.a, Duration::from_millis(200)) };
+ assert_eq!(a.decide(mcp_call(&env, TOOL)).await, ApprovalOutcome::Unanswered);
+ let rows = env.state.db.list_approvals(&SpaceId::default_space(), Some("waiting"), Some(&env.a)).await.unwrap();
+ let ticket = rows.iter().find(|r| r.tool_name == TOOL).expect("a waiting card").id.clone();
+ let (s, v) = call(&env.app, "POST", &format!("/api/approvals/{ticket}/resolve"), Some(json!({"decision": "always_allow"}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ let listed: Value = call(&env.app, "GET", &uri(&env), None).await.1;
+ assert_eq!(listed.as_array().map(Vec::len), Some(1), "{listed}");
+ assert_eq!(listed[0]["conversation_kind"], "direct");
+}