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: new spaces start on "Ask only when risky"
Lin (kwant bot)6a4c1c4b6b34
diff --git a/docs/approvals.md b/docs/approvals.mdindex 2721f44d..4b557808 100644--- a/docs/approvals.md+++ b/docs/approvals.md@@ -7,10 +7,15 @@ refuse it.| Mode | UI label | What happens ||---|---|---|-| `ask` (default) | Ask before running commands | Every tool call outside the bot's folder shows an approval card. |-| `smart` | Ask only when risky | Ordinary work runs without a card; anything risky or unclear shows the card, with the reason. |+| `ask` | Ask before running commands | Every tool call outside the bot's folder shows an approval card. |+| `smart` (default for new spaces) | Ask only when risky | Ordinary work runs without a card; anything risky or unclear shows the card, with the reason. || `off` | Don’t ask | Everything runs. |+A new space, and a fresh install's Default space, start on `smart`. A space made before that+default (it has no approvals row) keeps asking after an upgrade, so updating kwnt never loosens+an install; switch it in Settings when you're ready. While the built-in password store holds+passwords, a new space starts on `ask` instead (see below). An unknown bot always asks.+Whatever the mode, a call that names kwnt's own secret files (the vault, its key, the API token)is refused and recorded as `denied`. Calls that run without a card are recorded as`auto_allowed` (`GET /api/approvals?status=auto_allowed`); under `smart` the row'sdiff --git a/docs/saved-passwords.md b/docs/saved-passwords.mdindex 1694f3b5..23bc512f 100644--- a/docs/saved-passwords.md+++ b/docs/saved-passwords.md@@ -21,6 +21,7 @@ Since 2026-10-20, approvals off and passwords in the built-in store are not allo- While any space or bot has approvals off, going back from Bitwarden to the built-in store (`DELETE /api/passwords/bitwarden`) returns 409 `{error, needs_bitwarden: true, local_count}`, unless the built-in store is empty.- A space that is off counts even if every bot in it overrides to `ask`, because a new bot there would inherit `off`.- `local_count` counts every file in `<data>/kwnt-vault/`, including those of deleted teams, channels and bots (audit F-11). A file that won't open counts as one. Deleting a bot, team or channel now deletes its file. Leftovers from before this change are kept, because they are the person's data. They still count, and `POST /api/passwords/migrate` moves them to Bitwarden too. Spaces are only archived, so their bots' passwords keep counting. Deleting an owner never deletes items in Bitwarden.+- New spaces, and a fresh install's Default space, start on `smart` (since 2026-10-24). So on a new install, saving into the built-in store answers 409 until every space and bot is on "Ask before running commands", or Bitwarden is set up. A space created while the built-in store holds passwords starts on `ask` instead, and a fresh database next to a leftover `kwnt-vault/` folder starts its Default space on `ask`.- An install that was already in this state keeps its approvals as they are. `GET /api/passwords/store` shows `exposed: true`, and kwnt logs one warning at start (a count, no secrets). Moving the passwords to Bitwarden or turning approvals back on clears it.With Bitwarden, the API token alone doesn't show a password: that needs the master password. The DevTools gap below still applies in Bitwarden mode.diff --git a/site-src/docs-approvals.html b/site-src/docs-approvals.htmlindex 4ed58d92..f6e8036e 100644--- a/site-src/docs-approvals.html+++ b/site-src/docs-approvals.html@@ -28,11 +28,12 @@ card_art: avatar:qa<div class="table-wrap"><table><thead><tr><th>Mode</th><th>In the app</th><th>What happens</th></tr></thead><tbody>- <tr><td><code>ask</code> (default)</td><td>Ask before running commands</td><td>Every tool call outside the bot's folder shows a card.</td></tr>- <tr><td><code>smart</code></td><td>Ask only when risky</td><td>Ordinary work runs without a card. Anything risky or unclear shows the card, with the reason.</td></tr>+ <tr><td><code>ask</code></td><td>Ask before running commands</td><td>Every tool call outside the bot's folder shows a card.</td></tr>+ <tr><td><code>smart</code> (default)</td><td>Ask only when risky</td><td>Ordinary work runs without a card. Anything risky or unclear shows the card, with the reason.</td></tr><tr><td><code>off</code></td><td>Don't ask</td><td>Everything runs.</td></tr></tbody></table></div>+<p>New spaces start on <code>smart</code>, and so does the Default space of a new install. Spaces from before this default keep asking after an update, so updating kwant never loosens your setup; switch them in Settings when you're ready. While passwords are saved in the built-in store, a new space starts on <code>ask</code> instead (see <a href="#passwords">Saved passwords</a>).</p><p>In every mode, a call that names kwant's own secret files (the vault, its key, the API token) is refused and recorded as denied. Calls that run without a card are recorded too, and under <code>smart</code> each record says why it was judged safe.</p><h3 id="smart">What "Ask only when risky" lets through</h3>diff --git a/site/docs/approvals.html b/site/docs/approvals.htmlindex 6def9421..b86cadd8 100644--- a/site/docs/approvals.html+++ b/site/docs/approvals.html@@ -20,7 +20,7 @@<meta property="og:image:height" content="630"><meta property="og:image:alt" content="Approvals & saved passwords: Three approval modes, and saved website passwords, including Bitwarden."><meta property="article:published_time" content="2026-10-22">-<meta property="article:modified_time" content="2026-10-22">+<meta property="article:modified_time" content="2026-10-24"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="Human approval for AI agent actions · kwant"><meta name="twitter:description" content="kwant asks before bots run commands or edit outside their folder. Three approval modes per space or bot, plus saved passwords in a vault or Bitwarden.">@@ -77,11 +77,12 @@<div class="table-wrap"><table><thead><tr><th>Mode</th><th>In the app</th><th>What happens</th></tr></thead><tbody>- <tr><td><code>ask</code> (default)</td><td>Ask before running commands</td><td>Every tool call outside the bot's folder shows a card.</td></tr>- <tr><td><code>smart</code></td><td>Ask only when risky</td><td>Ordinary work runs without a card. Anything risky or unclear shows the card, with the reason.</td></tr>+ <tr><td><code>ask</code></td><td>Ask before running commands</td><td>Every tool call outside the bot's folder shows a card.</td></tr>+ <tr><td><code>smart</code> (default)</td><td>Ask only when risky</td><td>Ordinary work runs without a card. Anything risky or unclear shows the card, with the reason.</td></tr><tr><td><code>off</code></td><td>Don't ask</td><td>Everything runs.</td></tr></tbody></table></div>+<p>New spaces start on <code>smart</code>, and so does the Default space of a new install. Spaces from before this default keep asking after an update, so updating kwant never loosens your setup; switch them in Settings when you're ready. While passwords are saved in the built-in store, a new space starts on <code>ask</code> instead (see <a href="#passwords">Saved passwords</a>).</p><p>In every mode, a call that names kwant's own secret files (the vault, its key, the API token) is refused and recorded as denied. Calls that run without a card are recorded too, and under <code>smart</code> each record says why it was judged safe.</p><h3 id="smart">What "Ask only when risky" lets through</h3>@@ -152,6 +153,6 @@</footer><script src="../assets/js/site.js?v=c490c973ba" defer></script><script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>-<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/approvals#article","headline":"Human approval for AI agent actions","description":"kwant asks before bots run commands or edit outside their folder. Three approval modes per space or bot, plus saved passwords in a vault or Bitwarden.","url":"https://kwant.si/docs/approvals","mainEntityOfPage":"https://kwant.si/docs/approvals","image":"https://kwant.si/assets/og/docs-approvals.png?v=188ab5dbec","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-10-22","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Approvals & passwords","item":"https://kwant.si/docs/approvals"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>+<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/approvals#article","headline":"Human approval for AI agent actions","description":"kwant asks before bots run commands or edit outside their folder. Three approval modes per space or bot, plus saved passwords in a vault or Bitwarden.","url":"https://kwant.si/docs/approvals","mainEntityOfPage":"https://kwant.si/docs/approvals","image":"https://kwant.si/assets/og/docs-approvals.png?v=188ab5dbec","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-10-24","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Approvals & passwords","item":"https://kwant.si/docs/approvals"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script></body></html>diff --git a/site/sitemap.xml b/site/sitemap.xmlindex dd0dd940..5235642e 100644--- a/site/sitemap.xml+++ b/site/sitemap.xml@@ -1,7 +1,7 @@<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><url><loc>https://kwant.si/docs/accounts</loc><lastmod>2026-10-22</lastmod></url>- <url><loc>https://kwant.si/docs/approvals</loc><lastmod>2026-10-22</lastmod></url>+ <url><loc>https://kwant.si/docs/approvals</loc><lastmod>2026-10-24</lastmod></url><url><loc>https://kwant.si/docs/bots-and-teams</loc><lastmod>2026-10-22</lastmod></url><url><loc>https://kwant.si/docs/browser</loc><lastmod>2026-10-23</lastmod></url><url><loc>https://kwant.si/docs/install</loc><lastmod>2026-10-24</lastmod></url>diff --git a/src/db/approval_modes.rs b/src/db/approval_modes.rsindex c303ac2e..adc37073 100644--- a/src/db/approval_modes.rs+++ b/src/db/approval_modes.rs@@ -3,15 +3,22 @@//! `smart` ("Ask only when risky") runs ordinary work in the bot's folder without a card and asks//! for anything risky (see `mcp::shell_risk`).//! Kept in its own table, outside exports, so an imported bundle can't switch approvals off.+//!+//! A space made from now on gets an explicit [`NEW_SPACE`] row (`smart`) when it is created, and+//! a fresh install's Default space gets one too. A space with no row is one that existed before+//! that default changed, so it still asks: upgrading never loosens an install.use super::{spaces::SpaceId, Database, DbError};use chrono::Utc;-/// The default for a space with no row, and for a bot with no override.+/// What a space with no row resolves to (one made before [`NEW_SPACE`]), and an unknown bot.pub const ASK: &str = "ask";pub const OFF: &str = "off";/// Ask only when risky.pub const SMART: &str = "smart";+/// What a new space starts with, and a fresh install's Default space: ask only when risky. Not+/// while the built-in password store holds passwords (`smart` would expose them), then `ask`.+pub const NEW_SPACE: &str = SMART;/// A bot's setting as the person chose it: `inherit` follows its space.pub const INHERIT: &str = "inherit";@@ -40,6 +47,15 @@ impl ApprovalMode {}}+/// Whether the built-in password store has any file in `data_dir` (a database deleted next to a+/// vault it left behind). Read errors count as yes, so the Default space then asks.+fn holds_local_passwords(data_dir: &std::path::Path) -> bool {+ match std::fs::read_dir(data_dir.join(crate::sandbox::credentials::VAULT_DIR)) {+ Ok(mut entries) => entries.next().is_some(),+ Err(e) => e.kind() != std::io::ErrorKind::NotFound,+ }+}+/// `ask`, `smart` or `off`; anything else is not a mode.pub fn valid_mode(mode: &str) -> bool {matches!(mode, ASK | SMART | OFF)@@ -54,7 +70,9 @@ const CREATE_APPROVAL_MODES: &str = "CREATE TABLE IF NOT EXISTS approval_modes ()";impl Database {- pub(super) async fn migrate_approval_modes(&self) -> Result<(), DbError> {+ /// `fresh`: the database was just made, so its Default space is new and starts with+ /// [`NEW_SPACE`], unless `data_dir` already holds built-in saved passwords.+ pub(super) async fn migrate_approval_modes(&self, fresh: bool, data_dir: &std::path::Path) -> Result<(), DbError> {sqlx::query(CREATE_APPROVAL_MODES).execute(&self.pool).await?;// Tables made before `smart` existed only allow 'ask' and 'off': rebuild them oncelet sql: Option<(String,)> = sqlx::query_as("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'approval_modes'")@@ -70,6 +88,15 @@ impl Database {sqlx::query("DROP TABLE approval_modes_old").execute(&mut *tx).await?;tx.commit().await?;}+ if fresh {+ let mode = if holds_local_passwords(data_dir) { ASK } else { NEW_SPACE };+ sqlx::query("INSERT OR IGNORE INTO approval_modes (scope, id, mode, updated_at) VALUES ('space', ?, ?, ?)")+ .bind(super::spaces::DEFAULT_SPACE_ID)+ .bind(mode)+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ }Ok(())}@@ -82,7 +109,8 @@ impl Database {Ok(row.map(|r| r.0))}- /// The space's approvals: `ask` (the default), `smart` or `off`.+ /// The space's approvals: `ask`, `smart` or `off`. No row (a space older than [`NEW_SPACE`])+ /// is `ask`.pub async fn space_approvals(&self, space: &SpaceId) -> Result<String, DbError> {Ok(self.approval_mode_row("space", space.as_str()).await?.unwrap_or_else(|| ASK.into()))}diff --git a/src/db/mod.rs b/src/db/mod.rsindex 34e96715..b7b6213d 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -162,7 +162,7 @@ impl Database {db.migrate_hires().await?;db.migrate_imports().await?;db.repair_team_channels().await?;- db.migrate_approval_modes().await?;+ db.migrate_approval_modes(fresh, data_dir).await?;}db.pool.close().await;diff --git a/src/db/spaces.rs b/src/db/spaces.rsindex 86fa1a32..ec0a21b2 100644--- a/src/db/spaces.rs+++ b/src/db/spaces.rs@@ -447,8 +447,15 @@ impl Database {}/// A new, empty space with its own This machine row per engine (the space's default for- /// each engine). Its #general and bots come with S2's create flow.+ /// each engine), and approvals set to [`super::approval_modes::NEW_SPACE`]. Its #general and+ /// bots come with S2's create flow.pub async fn create_space(&self, input: &NewSpace) -> Result<Space, DbError> {+ self.create_space_with_approvals(input, super::approval_modes::NEW_SPACE).await+ }++ /// [`Self::create_space`] with its approvals row set to `approvals` (`ask`, `smart` or+ /// `off`), written in the same transaction, so the space never exists without one.+ pub async fn create_space_with_approvals(&self, input: &NewSpace, approvals: &str) -> Result<Space, DbError> {let id = SpaceId::new(format!("spc_{}", uuid::Uuid::new_v4().simple()));let mut tx = self.pool.begin().await?;sqlx::query("INSERT INTO spaces (id, name, icon, color, sort) VALUES (?, ?, ?, ?, (SELECT IFNULL(MAX(sort), 0) + 1 FROM spaces))")@@ -470,6 +477,12 @@ impl Database {.execute(&mut *tx).await?;}+ sqlx::query("INSERT INTO approval_modes (scope, id, mode, updated_at) VALUES ('space', ?, ?, ?)")+ .bind(id.as_str())+ .bind(approvals)+ .bind(chrono::Utc::now())+ .execute(&mut *tx)+ .await?;tx.commit().await?;self.get_space(&id).await?.ok_or(DbError::Sqlx(sqlx::Error::RowNotFound))}diff --git a/src/server/spaces.rs b/src/server/spaces.rsindex cc250d06..cf81d043 100644--- a/src/server/spaces.rs+++ b/src/server/spaces.rs@@ -8,6 +8,7 @@#![allow(clippy::result_large_err)]use super::AppState;+use crate::db::approval_modes::{ASK, NEW_SPACE};use crate::db::spaces::{NewSpace, Space, SpaceId, SpaceUpdate};use crate::db::DbError;use axum::{@@ -316,7 +317,8 @@ fn unique_violation(e: &DbError) -> bool {}/// `POST /api/spaces`: a new, empty space with its own This machine accounts and work folder.-/// Its #general appears with its first bot (a channel needs a lead).+/// Its #general appears with its first bot (a channel needs a lead). Its approvals start on+/// `smart`, or `ask` while the built-in password store holds passwords.pub async fn create(State(state): State<AppState>, Json(body): Json<CreateBody>) -> Response {let name = match check_name(&body.name) {Ok(n) => n,@@ -335,7 +337,9 @@ pub async fn create(State(state): State<AppState>, Json(body): Json<CreateBody>)color: body.color.map(|c| c.trim().to_string()).filter(|c| !c.is_empty()),this_machine_enabled: body.this_machine_enabled.unwrap_or(true),};- let space = match state.db.create_space(&input).await {+ // Ask only when risky, unless passwords in the built-in store would then be readable+ let approvals = if super::passwords::local_count(&state).await > 0 { ASK } else { NEW_SPACE };+ let space = match state.db.create_space_with_approvals(&input, approvals).await {Ok(s) => s,Err(e) if unique_violation(&e) => return error(StatusCode::CONFLICT, "another space already has that name"),Err(_) => return internal(),diff --git a/tests/approvals_off_test.rs b/tests/approvals_off_test.rsindex bd1db558..4299a3fc 100644--- a/tests/approvals_off_test.rs+++ b/tests/approvals_off_test.rs@@ -1,4 +1,4 @@-//! The person's approvals switch: `ask` (the default) shows an approval card before a bot's tool+//! The person's approvals switch: `ask` shows an approval card before a bot's tool//! runs; `off` runs it and records it as `auto_allowed`. Set per space, overridden per bot, and//! never changed by a bot.@@ -44,6 +44,8 @@ struct Env {async fn setup() -> Env {let tmp = tempdir().unwrap();let db = Database::init(tmp.path()).await.unwrap();+ // Start from an asking install (a fresh one asks only when risky)+ db.set_space_approvals(&kwnt::db::spaces::SpaceId::default_space(), "ask").await.unwrap();let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };let state = AppState::new(config.clone(),@@ -171,7 +173,7 @@ fn bot_in<'a>(list: &'a Value, id: &str) -> &'a Value {}#[tokio::test]-async fn approvals_ask_by_default() {+async fn bots_follow_an_asking_space_by_default() {let e = setup().await;let space = get(&e, "/api/spaces/spc_default/approvals").await;assert_eq!(space["approvals"], "ask");diff --git a/tests/approvals_passwords_test.rs b/tests/approvals_passwords_test.rsindex e95fd0d1..ae175f77 100644--- a/tests/approvals_passwords_test.rs+++ b/tests/approvals_passwords_test.rs@@ -44,6 +44,8 @@ async fn setup(bitwarden: bool) -> Env {let tmp = tempdir().unwrap();let data = tmp.path().join("data");let db = Database::init(&data).await.unwrap();+ // Start from an asking install (a fresh one asks only when risky)+ db.set_space_approvals(&kwnt::db::spaces::SpaceId::default_space(), "ask").await.unwrap();if bitwarden {let dir = data.join(VAULT_DIR);std::fs::create_dir_all(&dir).unwrap();diff --git a/tests/away_test.rs b/tests/away_test.rsindex 1ffd6712..00036441 100644--- a/tests/away_test.rs+++ b/tests/away_test.rs@@ -31,6 +31,8 @@ const SECRET: &str = "sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789";async fn setup() -> (Router, AppState, TempDir) {let tmp = tempdir().unwrap();let db = Database::init(tmp.path()).await.unwrap();+ // Start from an asking install (a fresh one asks only when risky)+ db.set_space_approvals(&kwnt::db::spaces::SpaceId::default_space(), "ask").await.unwrap();let config = Config {data_dir: tmp.path().to_path_buf(),..Config::default()diff --git a/tests/builtin_tools_test.rs b/tests/builtin_tools_test.rsindex 81305655..176d819a 100644--- a/tests/builtin_tools_test.rs+++ b/tests/builtin_tools_test.rs@@ -26,6 +26,8 @@ use tower::ServiceExt;async fn setup() -> (Router, AppState, TempDir) {let tmp = tempdir().unwrap();let db = Database::init(tmp.path()).await.unwrap();+ // Start from an asking install (a fresh one asks only when risky)+ db.set_space_approvals(&kwnt::db::spaces::SpaceId::default_space(), "ask").await.unwrap();let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };let state = AppState::new(config.clone(),diff --git a/tests/default_approvals_test.rs b/tests/default_approvals_test.rsnew file mode 100644index 00000000..4fe44e42--- /dev/null+++ b/tests/default_approvals_test.rs@@ -0,0 +1,192 @@+//! New spaces start on "Ask only when risky" (`smart`); upgrading never loosens an install. A+//! space made before that default has no approvals row and still asks, explicit rows are kept,+//! a new space asks while the built-in password store holds passwords, and an imported bundle+//! can't switch approvals off.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{spaces::SpaceId, Database},+ router::LayaRouter,+ server::{create_router, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::path::Path;+use tempfile::tempdir;+use tower::ServiceExt;++fn state_for(data: &Path, db: Database) -> AppState {+ let config = Config { data_dir: data.to_path_buf(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };+ AppState::new(config.clone(), db, ToolRunner::new(data.join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url.clone()))+}++async fn call(app: &Router, state: &AppState, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {+ let req = Request::builder()+ .method(method)+ .uri(uri)+ .header("content-type", "application/json")+ .header("authorization", format!("Bearer {}", state.api_token.reveal()));+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();+ let status = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++async fn raw_pool(data: &Path) -> sqlx::SqlitePool {+ sqlx::SqlitePool::connect(&format!("sqlite://{}", data.join("kwnt.db").display())).await.unwrap()+}++#[tokio::test]+async fn a_fresh_install_and_a_new_space_ask_only_when_risky() {+ let tmp = tempdir().unwrap();+ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ let dflt = SpaceId::default_space();+ assert_eq!(db.space_approvals(&dflt).await.unwrap(), "smart");+ let bot = db.list_kwants(&dflt).await.unwrap().remove(0);+ let m = db.kwant_approvals(&bot.id).await.unwrap();+ assert_eq!((m.bot.as_str(), m.effective.as_str()), ("inherit", "smart"));++ let state = state_for(&data, db);+ let app = create_router(state.clone());+ let (s, v) = call(&app, &state, "POST", "/api/spaces", Some(json!({"name": "Lab"}))).await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ assert_eq!(v["approvals"], "smart", "{v}");+ let (_, v) = call(&app, &state, "GET", &format!("/api/spaces/{}/approvals", v["id"].as_str().unwrap()), None).await;+ assert_eq!(v["approvals"], "smart");++ // The database API's own create path starts there too+ let other = state.db.create_space(&kwnt::db::spaces::NewSpace { name: "Other".into(), icon: "box".into(), color: None, this_machine_enabled: true }).await.unwrap();+ assert_eq!(state.db.space_approvals(&SpaceId::new(&other.id)).await.unwrap(), "smart");+}++/// An install from before the default changed: no approvals rows at all. After the upgrade its+/// spaces still ask, and explicit rows (space and bot) are exactly as they were.+#[tokio::test]+async fn an_upgrade_keeps_spaces_without_a_row_on_ask_and_explicit_rows_unchanged() {+ let tmp = tempdir().unwrap();+ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ let dflt = SpaceId::default_space();+ let bot = db.list_kwants(&dflt).await.unwrap().remove(0);+ let other_bot = db.list_kwants(&dflt).await.unwrap().remove(1);+ drop(db);++ // Make it look like the old version wrote it: no row for Default or "Old", an explicit `off`+ // on "Kept", `smart` on a bot, `ask` on another+ let pool = raw_pool(&data).await;+ sqlx::query("DELETE FROM approval_modes").execute(&pool).await.unwrap();+ for (id, name, sort) in [("spc_old", "Old", 5), ("spc_kept", "Kept", 6)] {+ sqlx::query("INSERT INTO spaces (id, name, icon, sort) VALUES (?, ?, 'box', ?)").bind(id).bind(name).bind(sort).execute(&pool).await.unwrap();+ }+ for (scope, id, mode) in [("space", "spc_kept", "off"), ("kwant", bot.id.as_str(), "smart"), ("kwant", other_bot.id.as_str(), "ask")] {+ sqlx::query("INSERT INTO approval_modes (scope, id, mode, updated_at) VALUES (?, ?, ?, '2026-01-01T00:00:00Z')")+ .bind(scope)+ .bind(id)+ .bind(mode)+ .execute(&pool)+ .await+ .unwrap();+ }+ pool.close().await;++ // Upgrade: the new version opens the existing database, twice for good measure+ for _ in 0..2 {+ let db = Database::init(&data).await.unwrap();+ assert_eq!(db.space_approvals(&dflt).await.unwrap(), "ask");+ assert_eq!(db.space_approvals(&SpaceId::new("spc_old")).await.unwrap(), "ask");+ assert_eq!(db.space_approvals(&SpaceId::new("spc_kept")).await.unwrap(), "off");+ let m = db.kwant_approvals(&bot.id).await.unwrap();+ assert_eq!((m.space.as_str(), m.bot.as_str(), m.effective.as_str()), ("ask", "smart", "smart"));+ let m = db.kwant_approvals(&other_bot.id).await.unwrap();+ assert_eq!((m.bot.as_str(), m.effective.as_str()), ("ask", "ask"));+ let third = db.list_kwants(&dflt).await.unwrap().into_iter().find(|k| k.id != bot.id && k.id != other_bot.id);+ if let Some(k) = third {+ assert_eq!(db.kwant_approvals(&k.id).await.unwrap().effective, "ask");+ }+ drop(db);+ }+ // No row was written for the spaces that had none+ let pool = raw_pool(&data).await;+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM approval_modes WHERE scope = 'space'").fetch_one(&pool).await.unwrap();+ assert_eq!(n, 1);+ pool.close().await;+}++/// `smart` would let a bot read the built-in store, so a space made while it holds passwords asks.+#[tokio::test]+async fn a_new_space_asks_while_the_built_in_store_holds_passwords() {+ let tmp = tempdir().unwrap();+ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ let dflt = SpaceId::default_space();+ db.set_space_approvals(&dflt, "ask").await.unwrap();+ let bot = db.list_kwants(&dflt).await.unwrap().remove(0);+ let state = state_for(&data, db);+ let app = create_router(state.clone());+ let (s, v) = call(&app, &state, "POST", &format!("/api/sandbox/{}/passwords", bot.id), Some(json!({"origin": "https://zed.test", "username": "zed", "password": "DUMMY-DEFAULT-PW-1"}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");++ let (s, v) = call(&app, &state, "POST", "/api/spaces", Some(json!({"name": "Lab"}))).await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ assert_eq!(v["approvals"], "ask", "{v}");+ let (_, st) = call(&app, &state, "GET", "/api/passwords/store", None).await;+ assert_ne!(st["exposed"], true, "{st}");+}++/// A database deleted next to a vault it left behind: the fresh Default space asks.+#[tokio::test]+async fn a_fresh_database_next_to_saved_passwords_asks() {+ let tmp = tempdir().unwrap();+ let data = tmp.path().join("data");+ std::fs::create_dir_all(data.join(kwnt::sandbox::credentials::VAULT_DIR)).unwrap();+ std::fs::write(data.join(kwnt::sandbox::credentials::VAULT_DIR).join("owner.bin"), b"x").unwrap();+ let db = Database::init(&data).await.unwrap();+ assert_eq!(db.space_approvals(&SpaceId::default_space()).await.unwrap(), "ask");+}++/// Approvals stay outside bundles: an `approvals: "off"` anywhere in one is ignored, imported+/// bots follow their space and get no override.+#[tokio::test]+async fn an_import_cant_switch_approvals_off() {+ let tmp = tempdir().unwrap();+ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ let state = state_for(&data, db);+ let app = create_router(state.clone());+ let bundle = json!({+ "format": "kwant.bundle/1",+ "source": {"kind": "kwant", "label": "hostile"},+ "approvals": "off",+ "approval_modes": [{"scope": "space", "id": "spc_default", "mode": "off"}],+ "bots": [{"ref": "free", "name": "Free", "title": "t", "persona_prompt": "p", "soul": "", "approvals": "off", "approvals_effective": "off"}]+ });+ check_import(&app, &state, "spc_default", &bundle, "smart").await;+ let asking = state.db.create_space(&kwnt::db::spaces::NewSpace { name: "Asking".into(), icon: "box".into(), color: None, this_machine_enabled: true }).await.unwrap();+ state.db.set_space_approvals(&SpaceId::new(&asking.id), "ask").await.unwrap();+ check_import(&app, &state, &asking.id, &bundle, "ask").await;+ // Nothing in approval_modes for a bot came from either bundle+ let pool = raw_pool(&data).await;+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM approval_modes WHERE scope = 'kwant'").fetch_one(&pool).await.unwrap();+ assert_eq!(n, 0);+ pool.close().await;+}++async fn check_import(app: &Router, state: &AppState, space: &str, bundle: &Value, expected: &str) {+ let (s, p) = call(app, state, "POST", &format!("/api/import/preview?space={space}&filename=x.kwant.json"), Some(json!({"text": bundle.to_string()}))).await;+ assert_eq!(s, StatusCode::OK, "{p}");+ let (s, v) = call(app, state, "POST", &format!("/api/import/apply?space={space}"), Some(json!({"bundle": p["bundle"], "skip": []}))).await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ let sid = SpaceId::new(space);+ assert_eq!(state.db.space_approvals(&sid).await.unwrap(), expected);+ let free = state.db.list_kwants(&sid).await.unwrap().into_iter().find(|k| k.name == "Free").expect("imported bot");+ let m = state.db.kwant_approvals(&free.id).await.unwrap();+ assert_eq!((m.bot.as_str(), m.effective.as_str()), ("inherit", expected));+}diff --git a/tests/orphan_passwords_test.rs b/tests/orphan_passwords_test.rsindex 286a0d3d..8e492a33 100644--- a/tests/orphan_passwords_test.rs+++ b/tests/orphan_passwords_test.rs@@ -44,6 +44,8 @@ async fn setup() -> Env {let tmp = tempdir().unwrap();let data = tmp.path().join("data");let db = Database::init(&data).await.unwrap();+ // Start from an asking install (a fresh one asks only when risky)+ db.set_space_approvals(&kwnt::db::spaces::SpaceId::default_space(), "ask").await.unwrap();let config = Config { data_dir: data.clone(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };let state = AppState::new(config.clone(),@@ -212,6 +214,7 @@ async fn an_archived_space_keeps_counting() {let (s, v) = e.person("POST", "/api/spaces", Some(json!({"name": "Side"}))).await;assert_eq!(s, StatusCode::CREATED, "{v}");let space = SpaceId::new(v["id"].as_str().unwrap());+ e.state.db.set_space_approvals(&space, "ask").await.unwrap();let new_bot = NewKwant {name: "Sidey".into(),title: "t".into(),diff --git a/tests/person_only_deletes_test.rs b/tests/person_only_deletes_test.rsindex 65c37de6..51aeac95 100644--- a/tests/person_only_deletes_test.rs+++ b/tests/person_only_deletes_test.rs@@ -33,6 +33,8 @@ async fn setup() -> Env {let tmp = tempdir().unwrap();let data = tmp.path().join("data");let db = Database::init(&data).await.unwrap();+ // Start from an asking install (a fresh one asks only when risky)+ db.set_space_approvals(&kwnt::db::spaces::SpaceId::default_space(), "ask").await.unwrap();let config = Config { data_dir: data.clone(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };let state = AppState::new(config.clone(),diff --git a/tests/saved_passwords_test.rs b/tests/saved_passwords_test.rsindex 1dd8f9f4..236b29de 100644--- a/tests/saved_passwords_test.rs+++ b/tests/saved_passwords_test.rs@@ -44,6 +44,8 @@ async fn setup() -> Env {let tmp = tempdir().unwrap();let data = tmp.path().join("data");let db = Database::init(&data).await.unwrap();+ // Start from an asking install (a fresh one asks only when risky)+ db.set_space_approvals(&kwnt::db::spaces::SpaceId::default_space(), "ask").await.unwrap();let config = Config { data_dir: data.clone(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };let state = AppState::new(config.clone(),@@ -285,6 +287,7 @@ async fn f1_f7_passwords_leave_bot_folders_encrypted_and_private() {async fn f4_other_spaces_and_names_are_not_found() {let e = setup().await;let lab = e.state.db.create_space(&NewSpace { name: "Lab".into(), icon: "🧪".into(), color: None, this_machine_enabled: true }).await.unwrap();+ e.state.db.set_space_approvals(&SpaceId::new(&lab.id), "ask").await.unwrap();let lab_bot = e.state.dbdiff --git a/tests/server_test.rs b/tests/server_test.rsindex feb46a85..57683031 100644--- a/tests/server_test.rs+++ b/tests/server_test.rs@@ -367,6 +367,7 @@ async fn test_system_select_folder_endpoint() {async fn test_sandbox_password_vault_api() {let tmp = tempdir().unwrap();let db = Database::init(tmp.path()).await.unwrap();+ db.set_space_approvals(&kwnt::db::spaces::SpaceId::default_space(), "ask").await.unwrap();let config = Config { data_dir: tmp.path().to_path_buf(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };let tools = ToolRunner::new(tmp.path().join("workspace"));let broker = PermissionBroker::new();diff --git a/tests/smart_approvals_test.rs b/tests/smart_approvals_test.rsindex b4d9cecc..54455a66 100644--- a/tests/smart_approvals_test.rs+++ b/tests/smart_approvals_test.rs@@ -45,6 +45,8 @@ struct Env {async fn setup() -> Env {let tmp = tempdir().unwrap();let db = Database::init(tmp.path()).await.unwrap();+ // Start from an asking install (a fresh one asks only when risky)+ db.set_space_approvals(&kwnt::db::spaces::SpaceId::default_space(), "ask").await.unwrap();let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };let state = AppState::new(config.clone(),diff --git a/tests/zombie_test.rs b/tests/zombie_test.rsindex aa8dd12b..08a396a6 100644--- a/tests/zombie_test.rs+++ b/tests/zombie_test.rs@@ -382,6 +382,8 @@ async fn setup() -> Env {let tmp = tempdir().unwrap();let data = tmp.path().join("data");let db = Database::init(&data).await.unwrap();+ // Start from an asking install (a fresh one asks only when risky)+ db.set_space_approvals(&kwnt::db::spaces::SpaceId::default_space(), "ask").await.unwrap();// No owner-bot turns here: they would reach a real model (see loose_ends_test for those)no_owner_turns(&db).await;let config = Config { data_dir: data.clone(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };