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.

0.8.0: Undo of a ready-made team or an import survives an out-of-step search index (#473)

Oleksandr Ivanchenko39ae832dd149
diff --git a/frontend/src/imports.ts b/frontend/src/imports.ts
index 57cfbf6f..ccf9c5eb 100644
--- a/frontend/src/imports.ts
+++ b/frontend/src/imports.ts
@@ -196,6 +196,9 @@ export function importErrorText(err: unknown): { title: string; detail: string }
return { title: 'No connection', detail };
case 'person_cancelled':
return { title: 'Not undone', detail };
+ case 'undo_failed':
+ // The server's plain sentence (what went wrong and what to do), never SQL
+ return { title: 'Not undone', detail: detail || 'The server couldn’t finish this. Try again in a moment.' };
default:
return { title: 'Something went wrong', detail: 'The server couldn’t finish this. Try again in a moment.' };
}
diff --git a/frontend/tests/importDialog.test.mjs b/frontend/tests/importDialog.test.mjs
index f1c24d4b..5ca5967c 100644
--- a/frontend/tests/importDialog.test.mjs
+++ b/frontend/tests/importDialog.test.mjs
@@ -97,6 +97,10 @@ test('every error code gets a plain heading, and the server’s sentence when it
// A database error never shows its details.
assert.equal(E('internal', 'sqlite: disk I/O').detail, 'The server couldn’t finish this. Try again in a moment.');
assert.equal(m.importErrorText(new Error('x')).title, 'Something went wrong');
+ // A failed Undo shows the server's plain sentence
+ const undo = E('undo_failed', 'Couldn\'t undo this import: kwant is busy saving something else. Try again in a moment.');
+ assert.equal(undo.title, 'Not undone');
+ assert.match(undo.detail, /^Couldn't undo this import: kwant is busy/);
const box = text(html(m.ErrorBox, { error: new m.ImportError('', 'problems', 400, [], [{ message: 'Too many bots.' }]) }));
assert.match(box, /Fix these first.*Too many bots/);
});
diff --git a/src/db/bot_actions.rs b/src/db/bot_actions.rs
index c640c5e8..c8cc89d1 100644
--- a/src/db/bot_actions.rs
+++ b/src/db/bot_actions.rs
@@ -337,14 +337,28 @@ impl Database {
/// `SQLITE_CORRUPT_VTAB`, which the index's delete trigger raises), the delete is rolled
/// back, both search indexes are rebuilt from their tables and the delete runs once more.
pub async fn delete_kwant_and_history(&self, id: &str, new_lead: &str) -> Result<bool, DbError> {
- match self.delete_kwant_once(id, new_lead).await {
- Err(e) if sqlite_code(&e) == Some(SQLITE_CORRUPT_VTAB) => {
- tracing::warn!(kwant_id = %id, error = %e, "a chat search index is out of step; rebuilding it and deleting the bot again");
+ self.retry_after_index_repair(&format!("deleting bot {id}"), || self.delete_kwant_once(id, new_lead)).await
+ }
+
+ /// Runs `attempt` (one write transaction that removes rows) and, when a chat search index
+ /// turned out to be out of step with what it indexes (SQLite's `SQLITE_CORRUPT_VTAB`, which
+ /// the index's delete trigger raises), rebuilds both indexes from their tables and runs it
+ /// once more. Used by a bot's delete and by the Undo of a ready-made team or an import, which
+ /// remove bots with their messages and memories too. `what` names the job in the log.
+ pub(super) async fn retry_after_index_repair<T, E, F, Fut>(&self, what: &str, mut attempt: F) -> Result<T, E>
+ where
+ F: FnMut() -> Fut,
+ Fut: std::future::Future<Output = Result<T, E>>,
+ E: SqliteCause + std::fmt::Debug,
+ {
+ match attempt().await {
+ Err(e) if e.sqlite_code() == Some(SQLITE_CORRUPT_VTAB) => {
+ tracing::warn!(job = what, error = ?e, "a chat search index is out of step; rebuilding it and trying again");
if let Err(repair) = self.rebuild_search_indexes().await {
- tracing::warn!(kwant_id = %id, error = %repair, "rebuilding the chat search indexes failed");
+ tracing::warn!(job = what, error = %repair, "rebuilding the chat search indexes failed");
return Err(e);
}
- self.delete_kwant_once(id, new_lead).await
+ attempt().await
}
done => done,
}
@@ -472,6 +486,17 @@ pub(crate) fn sqlite_code(e: &DbError) -> Option<i32> {
}
}
+/// An error that may carry a SQLite result code (see [`sqlite_code`]).
+pub trait SqliteCause {
+ fn sqlite_code(&self) -> Option<i32>;
+}
+
+impl SqliteCause for DbError {
+ fn sqlite_code(&self) -> Option<i32> {
+ sqlite_code(self)
+ }
+}
+
/// What the Delete dialog says when deleting `name` failed: plain words, never SQL. The
/// full error goes to the log.
pub fn delete_failure_message(name: &str, e: &DbError) -> String {
@@ -479,8 +504,25 @@ pub fn delete_failure_message(name: &str, e: &DbError) -> String {
}
fn delete_failure_for_code(name: &str, code: Option<i32>) -> String {
+ format!("Couldn't delete {name}: {}.", failure_reason_for_code(code))
+}
+
+/// What an Undo that removes bots (a ready-made team's, an import's) says when it failed: the
+/// same plain words as [`delete_failure_message`], never SQL. The full error goes to the log.
+pub fn undo_failure_message(what: &str, e: &impl SqliteCause) -> String {
+ format!("Couldn't undo {what}: {}.", failure_reason_for_code(e.sqlite_code()))
+}
+
+/// Why removing rows failed, as the end of a sentence (no full stop); never SQL. For a card that
+/// says "Couldn't undo the team: " itself.
+pub fn failure_reason(e: &impl SqliteCause) -> &'static str {
+ failure_reason_for_code(e.sqlite_code())
+}
+
+/// See [`failure_reason`].
+fn failure_reason_for_code(code: Option<i32>) -> &'static str {
// The primary result code is the low byte of the extended one
- let why = match code {
+ match code {
Some(SQLITE_CORRUPT_VTAB) => "its chat search index needed repair and kwant couldn't finish it. Restart kwant and try again",
Some(787) => "other saved data still points to it, or to a bot that no longer exists, so nothing was deleted. The details are in kwant's log",
Some(c) if c & 0xff == 11 || c & 0xff == 26 => "kwant's database file looks damaged. Quit kwant, back up the kwnt.db file and ask for help before trying again",
@@ -488,13 +530,27 @@ fn delete_failure_for_code(name: &str, code: Option<i32>) -> String {
Some(c) if c & 0xff == 13 => "the disk is full. Free some space and try again",
Some(c) if c & 0xff == 8 || c & 0xff == 10 || c & 0xff == 14 => "kwant can't write to its database file. Check the disk and its permissions, then try again",
_ => "kwant couldn't save the change, so nothing was deleted. The details are in kwant's log",
- };
- format!("Couldn't delete {name}: {why}.")
+ }
}
#[cfg(test)]
mod delete_failure_tests {
- use super::delete_failure_for_code;
+ use super::{delete_failure_for_code, failure_reason_for_code};
+
+ #[test]
+ fn an_undo_failure_uses_the_same_plain_words() {
+ struct Code(Option<i32>);
+ impl super::SqliteCause for Code {
+ fn sqlite_code(&self) -> Option<i32> {
+ self.0
+ }
+ }
+ for c in [None, Some(5), Some(13), Some(267), Some(787), Some(1811)] {
+ let m = super::undo_failure_message("this import", &Code(c));
+ assert_eq!(m, format!("Couldn't undo this import: {}.", failure_reason_for_code(c)));
+ assert!(!m.contains("database error"), "{m}");
+ }
+ }
#[test]
fn each_failure_has_plain_words() {
diff --git a/src/db/imports.rs b/src/db/imports.rs
index 3a4d0cac..068d5506 100644
--- a/src/db/imports.rs
+++ b/src/db/imports.rs
@@ -78,6 +78,60 @@ impl TryFrom<ImportRow> for ImportRecord {
}
}
+/// The removal of [`Database::undo_import`] inside the caller's transaction.
+async fn undo_import_in(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, id: &str, c: &Created, live: &[Kwant]) -> Result<(), UndoError> {
+ for table in ["teams", "channels"] {
+ let list = if table == "teams" { &c.teams } else { &c.channels };
+ for row in list {
+ sqlx::query(&format!("DELETE FROM {table} WHERE id = ?")).bind(row).execute(&mut **tx).await?;
+ }
+ }
+ for skill in &c.skills {
+ sqlx::query("DELETE FROM skills WHERE id = ?").bind(skill).execute(&mut **tx).await?;
+ }
+ for routine in &c.routines {
+ sqlx::query("DELETE FROM routine_runs WHERE routine_id = ?").bind(routine).execute(&mut **tx).await?;
+ sqlx::query("DELETE FROM routines WHERE id = ?").bind(routine).execute(&mut **tx).await?;
+ }
+ for k in live {
+ for sql in [
+ "DELETE FROM routine_runs WHERE routine_id IN (SELECT id FROM routines WHERE kwant_id = ?)",
+ "DELETE FROM routines WHERE kwant_id = ?",
+ "DELETE FROM kwant_memories WHERE kwant_id = ?",
+ "DELETE FROM kwant_mcp_disabled WHERE kwant_id = ?",
+ "DELETE FROM kwant_mcp_servers WHERE kwant_id = ?",
+ "DELETE FROM kwant_scope WHERE kwant_id = ?",
+ ] {
+ sqlx::query(sql).bind(&k.id).execute(&mut **tx).await?;
+ }
+ for sql in super::truth_ledger::PURGE_BOT_FACTS {
+ sqlx::query(sql).bind(&k.id).execute(&mut **tx).await?;
+ }
+ // Memberships the person added since (another team or channel) go with it.
+ for table in ["channels", "teams"] {
+ let rows: Vec<(String, String)> = sqlx::query_as(&format!("SELECT id, member_kwants FROM {table} WHERE member_kwants LIKE '%' || ? || '%'"))
+ .bind(&k.id)
+ .fetch_all(&mut **tx)
+ .await?;
+ for (row_id, members) in rows {
+ let kept: Vec<String> = serde_json::from_str::<Vec<String>>(&members).unwrap_or_default().into_iter().filter(|m| *m != k.id).collect();
+ sqlx::query(&format!("UPDATE {table} SET member_kwants = ? WHERE id = ?"))
+ .bind(serde_json::to_string(&kept).map_err(DbError::from)?)
+ .bind(&row_id)
+ .execute(&mut **tx)
+ .await?;
+ }
+ }
+ sqlx::query("DELETE FROM kwants WHERE id = ?").bind(&k.id).execute(&mut **tx).await?;
+ }
+ sqlx::query("UPDATE imports SET status = 'undone', undone_at = ? WHERE id = ? AND status = 'applied'")
+ .bind(Utc::now())
+ .bind(id)
+ .execute(&mut **tx)
+ .await?;
+ Ok(())
+}
+
/// Why an import can't be undone.
#[derive(Debug)]
pub enum UndoError {
@@ -96,6 +150,15 @@ impl From<DbError> for UndoError {
}
}
+impl super::bot_actions::SqliteCause for UndoError {
+ fn sqlite_code(&self) -> Option<i32> {
+ match self {
+ UndoError::Db(e) => super::bot_actions::sqlite_code(e),
+ _ => None,
+ }
+ }
+}
+
impl From<sqlx::Error> for UndoError {
fn from(e: sqlx::Error) -> Self {
UndoError::Db(e.into())
@@ -349,58 +412,26 @@ impl Database {
return Err(UndoError::Edited(edited));
}
+ // Its bots go with their memories, so an out-of-step search index gets the same repair
+ // and one retry as a bot's delete
+ self.retry_after_index_repair(&format!("undoing import {id}"), || self.undo_import_once(id, c, &live)).await?;
+ self.get_import(id).await?.ok_or(UndoError::NotFound)
+ }
+
+ /// One attempt of [`Self::undo_import`]'s removal, in one transaction: rolled back whole
+ /// when any step fails.
+ async fn undo_import_once(&self, id: &str, c: &Created, live: &[Kwant]) -> Result<(), UndoError> {
let mut tx = self.pool.begin().await?;
- for table in ["teams", "channels"] {
- let list = if table == "teams" { &c.teams } else { &c.channels };
- for row in list {
- sqlx::query(&format!("DELETE FROM {table} WHERE id = ?")).bind(row).execute(&mut *tx).await?;
+ match undo_import_in(&mut tx, id, c, live).await {
+ Ok(()) => {
+ tx.commit().await?;
+ Ok(())
}
- }
- for skill in &c.skills {
- sqlx::query("DELETE FROM skills WHERE id = ?").bind(skill).execute(&mut *tx).await?;
- }
- for routine in &c.routines {
- sqlx::query("DELETE FROM routine_runs WHERE routine_id = ?").bind(routine).execute(&mut *tx).await?;
- sqlx::query("DELETE FROM routines WHERE id = ?").bind(routine).execute(&mut *tx).await?;
- }
- for k in &live {
- for sql in [
- "DELETE FROM routine_runs WHERE routine_id IN (SELECT id FROM routines WHERE kwant_id = ?)",
- "DELETE FROM routines WHERE kwant_id = ?",
- "DELETE FROM kwant_memories WHERE kwant_id = ?",
- "DELETE FROM kwant_mcp_disabled WHERE kwant_id = ?",
- "DELETE FROM kwant_mcp_servers WHERE kwant_id = ?",
- "DELETE FROM kwant_scope WHERE kwant_id = ?",
- ] {
- sqlx::query(sql).bind(&k.id).execute(&mut *tx).await?;
+ Err(e) => {
+ let _ = tx.rollback().await;
+ Err(e)
}
- for sql in super::truth_ledger::PURGE_BOT_FACTS {
- sqlx::query(sql).bind(&k.id).execute(&mut *tx).await?;
- }
- // Memberships the person added since (another team or channel) go with it.
- for table in ["channels", "teams"] {
- let rows: Vec<(String, String)> = sqlx::query_as(&format!("SELECT id, member_kwants FROM {table} WHERE member_kwants LIKE '%' || ? || '%'"))
- .bind(&k.id)
- .fetch_all(&mut *tx)
- .await?;
- for (row_id, members) in rows {
- let kept: Vec<String> = serde_json::from_str::<Vec<String>>(&members).unwrap_or_default().into_iter().filter(|m| *m != k.id).collect();
- sqlx::query(&format!("UPDATE {table} SET member_kwants = ? WHERE id = ?"))
- .bind(serde_json::to_string(&kept).map_err(DbError::from)?)
- .bind(&row_id)
- .execute(&mut *tx)
- .await?;
- }
- }
- sqlx::query("DELETE FROM kwants WHERE id = ?").bind(&k.id).execute(&mut *tx).await?;
}
- sqlx::query("UPDATE imports SET status = 'undone', undone_at = ? WHERE id = ? AND status = 'applied'")
- .bind(Utc::now())
- .bind(id)
- .execute(&mut *tx)
- .await?;
- tx.commit().await?;
- self.get_import(id).await?.ok_or(UndoError::NotFound)
}
/// Why an imported kwant can't be removed by undo: history, or rows the import didn't make.
diff --git a/src/db/team_templates.rs b/src/db/team_templates.rs
index 5d645ab4..ef7daa11 100644
--- a/src/db/team_templates.rs
+++ b/src/db/team_templates.rs
@@ -222,6 +222,15 @@ impl From<serde_json::Error> for UndoError {
}
}
+impl super::bot_actions::SqliteCause for UndoError {
+ fn sqlite_code(&self) -> Option<i32> {
+ match self {
+ UndoError::Db(e) => super::bot_actions::sqlite_code(e),
+ _ => None,
+ }
+ }
+}
+
impl From<sqlx::Error> for UndoError {
fn from(e: sqlx::Error) -> Self {
UndoError::Db(e.into())
@@ -541,14 +550,22 @@ impl Database {
if now() > c.undo_until() {
return Err(UndoError::Expired);
}
+ // Its bots go with their messages and memories, so an out-of-step search index gets
+ // the same repair and one retry as a bot's delete
+ self.retry_after_index_repair(&format!("undoing ready-made team {}", c.team_id), || self.undo_team_creation_once(&c)).await?;
+ Ok(c.created)
+ }
+
+ /// One attempt of [`Self::undo_team_creation`], in one write transaction.
+ async fn undo_team_creation_once(&self, c: &Creation) -> Result<(), UndoError> {
let mut tx = self.begin_write().await?;
- match undo_in(&mut tx, &c).await {
+ match undo_in(&mut tx, c).await {
Ok(()) => {
tx.commit().await?;
- Ok(c.created)
+ Ok(())
}
Err(e) => {
- tx.rollback().await?;
+ let _ = tx.rollback().await;
Err(e)
}
}
diff --git a/src/server/bot_actions.rs b/src/server/bot_actions.rs
index 3feed330..b9a9dfb3 100644
--- a/src/server/bot_actions.rs
+++ b/src/server/bot_actions.rs
@@ -1992,9 +1992,13 @@ async fn undo_action(state: &AppState, a: &BotAction) -> Result<Option<String>,
}
Err(e @ UndoError::NoKeeper) => return Err(refuse("no_bot_to_keep_chat", e.to_string(), Value::Null)),
Err(e @ UndoError::NotFound) => return Err(refuse("not_a_template_team", e.to_string(), Value::Null)),
- Err(UndoError::Db(e)) => {
+ Err(e @ UndoError::Db(_)) => {
+ // Plain words for the person (the card says "Couldn't undo the team: <error>"),
+ // the full sentence in `message`; the SQLite message stays in the log
tracing::warn!(error = %e, action_id = %a.id, "undoing a ready-made team");
- return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response());
+ let why = format!("{}.", crate::db::bot_actions::failure_reason(&e));
+ let message = crate::db::bot_actions::undo_failure_message("this ready-made team", &e);
+ return Err((StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": why, "code": "undo_failed", "message": message }))).into_response());
}
}
}
diff --git a/src/server/import_routes.rs b/src/server/import_routes.rs
index 6956cab1..250f5bb3 100644
--- a/src/server/import_routes.rs
+++ b/src/server/import_routes.rs
@@ -373,7 +373,11 @@ pub async fn undo(State(state): State<AppState>, Scope(space): Scope, Path(id):
})),
)
.into_response(),
- Err(UndoError::Db(e)) => internal(e),
+ Err(e @ UndoError::Db(_)) => {
+ // Plain words for the person; the SQLite message stays in the log
+ tracing::warn!(import_id = %id, error = ?e, "undoing an import failed");
+ error(StatusCode::INTERNAL_SERVER_ERROR, "undo_failed", crate::db::bot_actions::undo_failure_message("this import", &e))
+ }
}
}
diff --git a/tests/undo_repair_test.rs b/tests/undo_repair_test.rs
new file mode 100644
index 00000000..a2ca12f0
--- /dev/null
+++ b/tests/undo_repair_test.rs
@@ -0,0 +1,217 @@
+//! Undo for a ready-made team and for an import, from a database whose chat search index is out
+//! of step (h3 in tests/bot_delete_repair_test.rs, Ada's #465 review, Later 1). Both remove bots
+//! with their messages or memories, so the index's delete trigger used to fail them with
+//! "database disk image is malformed" and the person got a bare 500 or "database error". They
+//! now get the bot delete's repair (rebuild both indexes, try once more), and an Undo that still
+//! fails says why in the same plain words as the Delete dialog. All data is invented.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{models::NewMessage, spaces::SpaceId, Database},
+ router::LayaRouter,
+ server::{create_router, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use sqlx::SqlitePool;
+use std::path::PathBuf;
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+async fn setup() -> (Router, AppState, TempDir) {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ (create_router(state.clone()), state, tmp)
+}
+
+/// A second connection to the same file, for writing the broken states the app never writes.
+async fn raw(tmp: &TempDir) -> SqlitePool {
+ SqlitePool::connect(&format!("sqlite://{}", tmp.path().join("kwnt.db").display())).await.unwrap()
+}
+
+async fn call(app: &Router, state: &AppState, method: &str, uri: &str, content_type: &str, body: Option<Vec<u8>>) -> (StatusCode, Value) {
+ let req = Request::builder()
+ .method(method)
+ .uri(uri)
+ .header("content-type", content_type)
+ .header("authorization", format!("Bearer {}", state.api_token.reveal()));
+ let resp = app.clone().oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).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 post(app: &Router, state: &AppState, uri: &str, body: Value) -> (StatusCode, Value) {
+ call(app, state, "POST", uri, "application/json", Some(body.to_string().into_bytes())).await
+}
+
+fn dm(kwant: &str, role: &str, text: &str) -> NewMessage {
+ NewMessage {
+ channel_id: None,
+ direct_kwant_id: Some(kwant.into()),
+ sender_role: role.into(),
+ sender_id: if role == "user" { "user".into() } else { kwant.into() },
+ text: text.into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ }
+}
+
+/// h3: text changes without the search indexes hearing about it (as if written while the update
+/// triggers were missing). Deleting those rows then trips the index's delete trigger.
+async fn put_indexes_out_of_step(pool: &SqlitePool, bot: &str) {
+ for sql in ["DROP TRIGGER messages_fts_au", "DROP TRIGGER kwant_memories_fts_au"] {
+ sqlx::query(sql).execute(pool).await.unwrap();
+ }
+ sqlx::query("UPDATE messages SET text = text || ' edited outside the index' WHERE direct_kwant_id = ?").bind(bot).execute(pool).await.unwrap();
+ sqlx::query("UPDATE kwant_memories SET text = text || ' edited outside the index' WHERE kwant_id = ?").bind(bot).execute(pool).await.unwrap();
+ assert!(
+ sqlx::query("INSERT INTO kwant_memories_fts(kwant_memories_fts, rank) VALUES ('integrity-check', 1)").execute(pool).await.is_err(),
+ "the memory index is out of step before the Undo"
+ );
+}
+
+async fn assert_search_indexes_in_step(pool: &SqlitePool) {
+ for index in ["messages_fts", "kwant_memories_fts"] {
+ sqlx::query(&format!("INSERT INTO {index}({index}, rank) VALUES ('integrity-check', 1)"))
+ .execute(pool)
+ .await
+ .unwrap_or_else(|e| panic!("{index} is out of step: {e}"));
+ }
+}
+
+/// Something the Undo can't get past, with SQL-ish text the person must never see.
+async fn block_bot_deletes(pool: &SqlitePool) {
+ sqlx::query("CREATE TRIGGER block_delete BEFORE DELETE ON kwants BEGIN SELECT RAISE(ABORT, 'secret sql text from kwants'); END")
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+fn assert_plain(message: &str) {
+ for leak in ["database error", "secret", "sql", "SQL", "kwants", "RAISE", "malformed", "code"] {
+ assert!(!message.contains(leak), "{message} shows {leak}");
+ }
+}
+
+/// A ready-made "inbox" team: (bot action id, a bot it made).
+async fn ready_made_team(app: &Router, state: &AppState) -> (String, String) {
+ let (s, v) = post(app, state, "/api/teams/from-template", json!({"template_id": "inbox"})).await;
+ assert_eq!(s, StatusCode::CREATED, "{v}");
+ let bot = v["bots"].as_array().unwrap().iter().find(|b| b["lead"] != true).unwrap()["id"].as_str().unwrap().to_string();
+ (v["action_id"].as_str().unwrap().to_string(), bot)
+}
+
+#[tokio::test]
+async fn h3_undoing_a_ready_made_team_rebuilds_the_index_and_succeeds() {
+ let (app, state, tmp) = setup().await;
+ let (action, bot) = ready_made_team(&app, &state).await;
+ for i in 0..9 {
+ state.db.insert_message(&dm(&bot, if i % 2 == 0 { "user" } else { "kwant" }, &format!("message {i} about the inbox"))).await.unwrap();
+ }
+ state.db.add_memory(&bot, "Oleks files receipts on Fridays.", "user").await.unwrap();
+ let architect = state.db.list_kwants(&SpaceId::default_space()).await.unwrap().into_iter().find(|k| k.name == "Architect").unwrap().id;
+ state.db.insert_message(&dm(&architect, "user", "a message that stays")).await.unwrap();
+ let pool = raw(&tmp).await;
+ put_indexes_out_of_step(&pool, &bot).await;
+
+ let (s, v) = post(&app, &state, &format!("/api/bot-actions/{action}/undo"), json!({})).await;
+ assert!(s.is_success(), "{s} {v}");
+ assert!(state.db.get_kwant(&bot).await.unwrap().is_none(), "the bot the team made is gone");
+ let (left,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM messages WHERE direct_kwant_id = ?").bind(&bot).fetch_one(&pool).await.unwrap();
+ assert_eq!(left, 0);
+ assert_search_indexes_in_step(&pool).await;
+ let (hits,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM messages_fts WHERE messages_fts MATCH 'stays'").fetch_one(&pool).await.unwrap();
+ assert_eq!(hits, 1, "search still finds what is left");
+}
+
+#[tokio::test]
+async fn a_ready_made_team_undo_that_still_fails_says_why_in_plain_words() {
+ let (app, state, tmp) = setup().await;
+ let (action, bot) = ready_made_team(&app, &state).await;
+ let pool = raw(&tmp).await;
+ block_bot_deletes(&pool).await;
+
+ let (s, v) = post(&app, &state, &format!("/api/bot-actions/{action}/undo"), json!({})).await;
+ assert_eq!(s, StatusCode::INTERNAL_SERVER_ERROR, "{v}");
+ assert_eq!(v["code"], "undo_failed", "{v}");
+ // The card puts "Couldn't undo the team: " in front of `error`
+ let why = v["error"].as_str().unwrap();
+ assert!(why.contains("nothing was deleted"), "{why}");
+ assert_plain(why);
+ let message = v["message"].as_str().unwrap();
+ assert_eq!(message, format!("Couldn't undo this ready-made team: {why}"));
+ assert_plain(message);
+ // Rolled back whole
+ assert!(state.db.get_kwant(&bot).await.unwrap().is_some());
+}
+
+fn fixture(name: &str) -> Vec<u8> {
+ std::fs::read(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/import").join(name)).unwrap()
+}
+
+/// The kwant.bundle fixture applied in the default space: (import id, the bot it made, which
+/// has one memory).
+async fn imported(app: &Router, state: &AppState) -> (String, String) {
+ let space = SpaceId::default_space().as_str().to_string();
+ let (s, preview) =
+ call(app, state, "POST", &format!("/api/import/preview?space={space}&filename=kwant-bundle.json"), "application/octet-stream", Some(fixture("kwant-bundle.json"))).await;
+ assert_eq!(s, StatusCode::OK, "{preview}");
+ let (s, applied) = post(app, state, &format!("/api/import/apply?space={space}"), json!({ "bundle": preview["bundle"], "skip": [] })).await;
+ assert_eq!(s, StatusCode::CREATED, "{applied}");
+ let bot = applied["import"]["created"]["kwants"][0]["id"].as_str().unwrap().to_string();
+ assert_eq!(state.db.list_memories(&bot).await.unwrap().len(), 1);
+ (applied["import"]["id"].as_str().unwrap().to_string(), bot)
+}
+
+#[tokio::test]
+async fn h3_undoing_an_import_rebuilds_the_index_and_succeeds() {
+ let (app, state, tmp) = setup().await;
+ let (import, bot) = imported(&app, &state).await;
+ let pool = raw(&tmp).await;
+ put_indexes_out_of_step(&pool, &bot).await;
+
+ // force: the memory's text changed, which may count as an edit
+ let (s, v) = post(&app, &state, &format!("/api/imports/{import}/undo"), json!({ "force": true })).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["status"], "undone");
+ assert!(state.db.get_kwant(&bot).await.unwrap().is_none());
+ let (left,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM kwant_memories WHERE kwant_id = ?").bind(&bot).fetch_one(&pool).await.unwrap();
+ assert_eq!(left, 0);
+ assert_search_indexes_in_step(&pool).await;
+}
+
+#[tokio::test]
+async fn an_import_undo_that_still_fails_says_why_in_plain_words() {
+ let (app, state, tmp) = setup().await;
+ let (import, bot) = imported(&app, &state).await;
+ let pool = raw(&tmp).await;
+ block_bot_deletes(&pool).await;
+
+ let (s, v) = post(&app, &state, &format!("/api/imports/{import}/undo"), json!({ "force": true })).await;
+ assert_eq!(s, StatusCode::INTERNAL_SERVER_ERROR, "{v}");
+ assert_eq!(v["code"], "undo_failed", "{v}");
+ let message = v["error"].as_str().unwrap();
+ assert!(message.starts_with("Couldn't undo this import: "), "{message}");
+ assert!(message.contains("nothing was deleted"), "{message}");
+ assert_plain(message);
+ // Rolled back whole: the bot and the import's status stay
+ assert!(state.db.get_kwant(&bot).await.unwrap().is_some());
+ let (status,): (String,) = sqlx::query_as("SELECT status FROM imports WHERE id = ?").bind(&import).fetch_one(&pool).await.unwrap();
+ assert_eq!(status, "applied");
+}