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.

Zombie Hunter: refuse a source edit before testing it; cases name their bot

Lin (kwant bot)ea136bc81dfe
diff --git a/docs/zombie-hunter.md b/docs/zombie-hunter.md
index 0f561324..1615a329 100644
--- a/docs/zombie-hunter.md
+++ b/docs/zombie-hunter.md
@@ -27,7 +27,8 @@ only accepted for a server on this computer (Proton Bridge, a test server).
Like any saved password (see `saved-passwords.md`), a login is refused with 409
`{needs_bitwarden: true}` on the built-in store while approvals are off anywhere, before the
-connection test runs. Existing logins count toward `local_count` and move with "Move to Bitwarden".
+connection test runs. That holds for adding a source and for changing its settings or login
+(`PATCH sources/:id` with `config` or `secret`): a refused save never contacts the server. Existing logins count toward `local_count` and move with "Move to Bitwarden".
The case store is not tied to mail: `source`, `conv_kind`, `kind`, `evidence` and `deadline` fit
any open loop, and source kinds are checked in Rust, not by the table, so later sources (a
@@ -108,6 +109,9 @@ All routes are under `/api/zombie`. The full list and shapes are in the header o
- `age_days`, `last_activity_at`, `first_seen`, `status_changed_at`
- `snoozed_until`, `waiting_since`, `follow_ups`
- `deadline`, `resolution`, `dismiss_reason`, `space_id`
+- `kwant_id`: the bot whose chat the case is in, for `kwant_*` cases (link the card to the
+ chat with it and the thread in `link`); `null` for other sources and for cases found before
+ the field was added (filled in at the next scan)
## Settings (`GET|PUT /api/zombie/settings`)
diff --git a/src/db/zombie.rs b/src/db/zombie.rs
index f685283b..3f1f72df 100644
--- a/src/db/zombie.rs
+++ b/src/db/zombie.rs
@@ -51,6 +51,8 @@ pub struct CaseRow {
pub space_id: Option<String>,
/// Wiped by retention: only the key and status are left.
pub redacted: bool,
+ /// The bot whose chat the case is in, for kwant's own conversations (a link to the chat).
+ pub kwant_id: Option<String>,
}
#[derive(Debug, Clone, FromRow, PartialEq, Serialize)]
@@ -107,6 +109,8 @@ pub struct KwantDelegationRow {
pub task: String,
pub status: String,
pub error: Option<String>,
+ /// The bot whose thread the task ran in.
+ pub kwant_id: String,
pub kwant_name: String,
pub space_id: Option<String>,
pub created_at: DateTime<Utc>,
@@ -128,7 +132,7 @@ pub struct KwantQuestionRow {
const CASE_COLUMNS: &str = "id, dedupe_key, source, source_id, source_ref, kind, conv_kind, title, counterpart, \
counterpart_name, reference, link, why, evidence, draft, status, snoozed_until, waiting_since, follow_ups, \
first_seen, last_seen, last_activity_at, status_changed_at, resolution, dismiss_reason, deadline, \
- reply_to_message_id, space_id, redacted";
+ reply_to_message_id, space_id, redacted, kwant_id";
impl Database {
pub(super) async fn migrate_zombie(&self) -> Result<(), DbError> {
@@ -197,6 +201,12 @@ impl Database {
] {
sqlx::query(stmt).execute(&self.pool).await?;
}
+ // Added after the first release: nullable, so existing cases are fine as they are
+ let has_kwant_id: Option<(String,)> =
+ sqlx::query_as("SELECT name FROM pragma_table_info('zombie_cases') WHERE name = 'kwant_id'").fetch_optional(&self.pool).await?;
+ if has_kwant_id.is_none() {
+ sqlx::query("ALTER TABLE zombie_cases ADD COLUMN kwant_id TEXT").execute(&self.pool).await?;
+ }
Ok(())
}
@@ -234,7 +244,7 @@ impl Database {
/// Inserts `c`, or replaces every column of the case with its id.
pub async fn zombie_put_case(&self, c: &CaseRow) -> Result<(), DbError> {
sqlx::query(&format!(
- "INSERT INTO zombie_cases ({CASE_COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ "INSERT INTO zombie_cases ({CASE_COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
source_ref = excluded.source_ref, kind = excluded.kind, conv_kind = excluded.conv_kind,
title = excluded.title, counterpart = excluded.counterpart, counterpart_name = excluded.counterpart_name,
@@ -243,7 +253,8 @@ impl Database {
waiting_since = excluded.waiting_since, follow_ups = excluded.follow_ups, last_seen = excluded.last_seen,
last_activity_at = excluded.last_activity_at, status_changed_at = excluded.status_changed_at,
resolution = excluded.resolution, dismiss_reason = excluded.dismiss_reason, deadline = excluded.deadline,
- reply_to_message_id = excluded.reply_to_message_id, space_id = excluded.space_id, redacted = excluded.redacted"
+ reply_to_message_id = excluded.reply_to_message_id, space_id = excluded.space_id, redacted = excluded.redacted,
+ kwant_id = excluded.kwant_id"
))
.bind(&c.id)
.bind(&c.dedupe_key)
@@ -274,6 +285,7 @@ impl Database {
.bind(&c.reply_to_message_id)
.bind(&c.space_id)
.bind(c.redacted)
+ .bind(&c.kwant_id)
.execute(&self.pool)
.await?;
Ok(())
@@ -290,7 +302,7 @@ impl Database {
let wiped = sqlx::query(
"UPDATE zombie_cases SET title = '', counterpart = NULL, counterpart_name = NULL, reference = NULL,
link = NULL, why = '', evidence = '[]', draft = NULL, dismiss_reason = NULL, deadline = NULL,
- reply_to_message_id = NULL, redacted = 1
+ reply_to_message_id = NULL, kwant_id = NULL, redacted = 1
WHERE redacted = 0 AND status IN ('closed', 'dismissed') AND status_changed_at < ?",
)
.bind(before)
@@ -420,7 +432,9 @@ impl Database {
/// Failed or interrupted tasks since `since` that were never run again (same task text) after.
pub async fn zombie_kwant_delegations(&self, since: DateTime<Utc>) -> Result<Vec<KwantDelegationRow>, DbError> {
Ok(sqlx::query_as(
- "SELECT d.id, d.thread_id, d.title, d.task, d.status, d.error, k.name AS kwant_name, k.space_id,
+ "SELECT d.id, d.thread_id, d.title, d.task, d.status, d.error,
+ COALESCE((SELECT t.kwant_id FROM threads t WHERE t.id = d.thread_id), d.specialist_kwant_id) AS kwant_id,
+ k.name AS kwant_name, k.space_id,
d.created_at, COALESCE(d.ended_at, d.created_at) AS ended_at
FROM delegations d
JOIN kwants k ON k.id = d.specialist_kwant_id
diff --git a/src/server/zombie_routes.rs b/src/server/zombie_routes.rs
index 9ddd2fd4..fcd7374d 100644
--- a/src/server/zombie_routes.rs
+++ b/src/server/zombie_routes.rs
@@ -121,6 +121,8 @@ pub struct CaseView {
pub resolution: Option<String>,
pub dismiss_reason: Option<String>,
pub space_id: Option<String>,
+ /// The bot whose chat the case is in, for kwant's own conversations.
+ pub kwant_id: Option<String>,
}
impl CaseView {
@@ -151,6 +153,7 @@ impl CaseView {
resolution: c.resolution,
dismiss_reason: c.dismiss_reason,
space_id: c.space_id,
+ kwant_id: c.kwant_id,
}
}
}
@@ -482,6 +485,10 @@ pub async fn update_source(State(state): State<AppState>, headers: HeaderMap, Pa
}
let mut test = None;
if b.config.is_some() || b.secret.is_some() {
+ // Before the connection test, so a refused save never reaches the server
+ if let Some(refused) = super::passwords::refuse_local_save(&state).await {
+ return Err(refused);
+ }
let (config, origin) = match &b.config {
Some(c) => checked_config(&row.kind, c)?,
None => (row.config.clone(), hunt::origin_of(&row).map_err(|e| error(StatusCode::BAD_REQUEST, &e))?),
diff --git a/src/zombie/classify.rs b/src/zombie/classify.rs
index 3641527d..688f5157 100644
--- a/src/zombie/classify.rs
+++ b/src/zombie/classify.rs
@@ -334,6 +334,7 @@ mod tests {
deadline: None,
reply_to_message_id: None,
space_id: None,
+ kwant_id: None,
}
}
diff --git a/src/zombie/detect.rs b/src/zombie/detect.rs
index e8d5db46..83663809 100644
--- a/src/zombie/detect.rs
+++ b/src/zombie/detect.rs
@@ -250,6 +250,7 @@ pub fn detect(c: &Conversation, rules: &Rules) -> Option<Candidate> {
deadline,
reply_to_message_id: c.messages.iter().rev().find_map(|m| m.message_id.clone()),
space_id: c.space_id.clone(),
+ kwant_id: c.kwant_id.clone(),
})
};
diff --git a/src/zombie/hunt.rs b/src/zombie/hunt.rs
index 868d836b..a32a80ec 100644
--- a/src/zombie/hunt.rs
+++ b/src/zombie/hunt.rs
@@ -325,6 +325,7 @@ fn refresh(row: &mut CaseRow, cand: &Candidate, now: DateTime<Utc>) {
row.deadline = cand.deadline.map(|d| d.format("%Y-%m-%d").to_string());
row.reply_to_message_id = cand.reply_to_message_id.clone();
row.space_id = cand.space_id.clone();
+ row.kwant_id = cand.kwant_id.clone();
row.redacted = false;
// A model-written draft the person asked for stays until the conversation moves on
let keep_draft = !activity_changed && row.draft.as_deref().and_then(|d| serde_json::from_str::<Draft>(d).ok()).is_some();
@@ -410,6 +411,7 @@ fn new_row(cand: &Candidate, now: DateTime<Utc>) -> CaseRow {
deadline: None,
reply_to_message_id: None,
space_id: None,
+ kwant_id: None,
redacted: false,
};
refresh(&mut row, cand, now);
@@ -733,6 +735,7 @@ mod tests {
deadline: None,
reply_to_message_id: None,
space_id: None,
+ kwant_id: None,
redacted: false,
}
}
diff --git a/src/zombie/kwant_source.rs b/src/zombie/kwant_source.rs
index 68314c24..9c0c053d 100644
--- a/src/zombie/kwant_source.rs
+++ b/src/zombie/kwant_source.rs
@@ -42,6 +42,7 @@ impl MissionSource for KwantSource {
c.counterpart = Some(t.kwant_id.clone());
c.counterpart_name = Some(t.kwant_name.clone());
c.space_id = t.space_id.clone();
+ c.kwant_id = Some(t.kwant_id.clone());
c.messages = vec![msg("you", true, t.created_at, &t.text)];
out.push(with_ref(c, &t.thread_id));
}
@@ -49,6 +50,7 @@ impl MissionSource for KwantSource {
let mut c = Conversation::new(SourceKind::Kwant, SOURCE_ID, &format!("delegation:{}", d.id), ConvKind::KwantDelegation, &d.title);
c.counterpart_name = Some(d.kwant_name.clone());
c.space_id = d.space_id.clone();
+ c.kwant_id = Some(d.kwant_id.clone());
c.failed = true;
let outcome = match (d.status.as_str(), d.error.as_deref().map(str::trim).filter(|e| !e.is_empty())) {
(_, Some(e)) => format!("The task failed: {e}"),
@@ -63,6 +65,7 @@ impl MissionSource for KwantSource {
c.counterpart = Some(q.kwant_id.clone());
c.counterpart_name = Some(q.kwant_name.clone());
c.space_id = q.space_id.clone();
+ c.kwant_id = Some(q.kwant_id.clone());
c.messages = vec![msg(&q.kwant_name, false, q.created_at, &q.question)];
let thread = q.thread_id.clone().unwrap_or_default();
out.push(with_ref(c, &thread));
diff --git a/src/zombie/mod.rs b/src/zombie/mod.rs
index 6a04c93e..fdfbec33 100644
--- a/src/zombie/mod.rs
+++ b/src/zombie/mod.rs
@@ -122,6 +122,8 @@ pub struct Conversation {
pub failed: bool,
/// The kwant space it belongs to, for kwant's own conversations.
pub space_id: Option<String>,
+ /// The bot whose chat it is in, for kwant's own conversations.
+ pub kwant_id: Option<String>,
}
impl Conversation {
@@ -141,6 +143,7 @@ impl Conversation {
reference: None,
failed: false,
space_id: None,
+ kwant_id: None,
}
}
@@ -231,6 +234,7 @@ pub struct Candidate {
/// Message-ID of the last message, for a reply that threads under it.
pub reply_to_message_id: Option<String>,
pub space_id: Option<String>,
+ pub kwant_id: Option<String>,
}
impl Candidate {
diff --git a/tests/zombie_test.rs b/tests/zombie_test.rs
index 5a872dff..0f8eb47e 100644
--- a/tests/zombie_test.rs
+++ b/tests/zombie_test.rs
@@ -646,6 +646,120 @@ async fn a_source_login_is_refused_on_the_built_in_store_while_approvals_are_off
assert_eq!(e.state.credentials.list(kwnt::zombie::VAULT_OWNER).await.unwrap().len(), 1, "the saved login is left as it was");
}
+/// L-1: editing a source's settings or login with approvals off is refused before any
+/// connection is made. A plain TCP listener stands in for the mail and GitHub servers and counts
+/// every connection, so a test call that reached it in any way would show.
+#[tokio::test]
+async fn a_refused_source_edit_never_connects_to_the_server() {
+ let e = setup().await;
+ let (base, _) = github_mock().await;
+ let (s, v) = e.person("POST", "/api/zombie/sources", Some(json!({"kind": "github", "label": "GitHub", "config": {"api_base": base}, "secret": MOCK_TOKEN}))).await;
+ assert_eq!(s, StatusCode::CREATED, "{v}");
+ let id = v["source"]["id"].as_str().unwrap().to_string();
+ let before = e.state.db.zombie_source(&id).await.unwrap().unwrap();
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let connections = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let counted = connections.clone();
+ let accept = tokio::spawn(async move {
+ while let Ok((sock, _)) = listener.accept().await {
+ counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ drop(sock);
+ }
+ });
+ e.state.db.set_space_approvals(&SpaceId::default_space(), "off").await.unwrap();
+
+ let trap = format!("http://127.0.0.1:{port}");
+ let edits = [
+ json!({"config": {"api_base": trap}, "secret": MOCK_TOKEN}),
+ json!({"config": {"api_base": trap}}),
+ json!({"secret": "a-new-token"}),
+ ];
+ for body in edits {
+ let (s, v) = e.person("PATCH", &format!("/api/zombie/sources/{id}"), Some(body.clone())).await;
+ assert_eq!(s, StatusCode::CONFLICT, "{body}: {v}");
+ assert_eq!(v["needs_bitwarden"], true, "{v}");
+ }
+ let imap = json!({"kind": "imap", "label": "Mail", "secret": "dummy-password",
+ "config": {"host": "127.0.0.1", "port": port, "security": "plain", "username": "[email protected]"}});
+ let (s, v) = e.person("POST", "/api/zombie/sources", Some(imap)).await;
+ assert_eq!(s, StatusCode::CONFLICT, "{v}");
+ assert_eq!(v["needs_bitwarden"], true, "{v}");
+
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ assert_eq!(connections.load(std::sync::atomic::Ordering::SeqCst), 0, "a refused save never reaches the server");
+ assert_eq!(e.state.db.zombie_source(&id).await.unwrap().unwrap(), before, "the source is left as it was");
+ assert_eq!(e.state.db.zombie_sources().await.unwrap().len(), 1, "no mailbox was added");
+ assert_eq!(e.state.credentials.list(kwnt::zombie::VAULT_OWNER).await.unwrap().len(), 1, "the saved login is left as it was");
+
+ // The same edit is tested against the server once approvals are back on
+ e.state.db.set_space_approvals(&SpaceId::default_space(), "ask").await.unwrap();
+ let (s, v) = e.person("PATCH", &format!("/api/zombie/sources/{id}"), Some(json!({"config": {"api_base": trap}}))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");
+ assert!(connections.load(std::sync::atomic::Ordering::SeqCst) > 0, "the listener does see a real test");
+ accept.abort();
+}
+
+/// A case from a bot's chat names the bot, so the Loose ends card can link to the chat.
+#[tokio::test]
+async fn a_case_from_a_bot_chat_carries_the_bot_id() {
+ let e = setup().await;
+ let bot = e.state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);
+ let thread = e.state.db.create_thread(&bot.id, "Invoice summary", "chat", None, "user").await.unwrap();
+ let m = kwnt::db::models::NewMessage {
+ channel_id: None,
+ direct_kwant_id: Some(bot.id.clone()),
+ sender_role: "user".into(),
+ sender_id: "user".into(),
+ text: "Could you send me the invoice summary?".into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ };
+ let extra = kwnt::db::models::MessageExtra { thread_id: Some(thread.id.clone()), meta: None };
+ e.state.db.insert_message_with(&m, &extra).await.unwrap();
+
+ let sources: Vec<Box<dyn MissionSource>> = vec![Box::new(kwnt::zombie::kwant_source::KwantSource::new(e.state.db.clone()))];
+ let settings = Settings { kwant_source: true, ..Default::default() };
+ scan_with(&e.state.db, &sources, None, &settings, Utc::now() + Duration::days(10)).await.unwrap();
+ let cases = e.state.db.zombie_cases_of_source(kwnt::zombie::kwant_source::SOURCE_ID).await.unwrap();
+ assert_eq!(cases.len(), 1, "{cases:?}");
+ assert_eq!(cases[0].kwant_id.as_deref(), Some(bot.id.as_str()));
+
+ let (s, v) = e.person("GET", &format!("/api/zombie/cases/{}", cases[0].id), None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["kwant_id"], bot.id.as_str(), "{v}");
+ assert_eq!(v["link"], format!("kwant://thread/{}", thread.id), "{v}");
+}
+
+/// `kwant_id` came after the first release: a database without it gains the column on start,
+/// and the cases already in it read back with no bot.
+#[tokio::test]
+async fn cases_from_before_kwant_id_survive_the_upgrade() {
+ let tmp = tempdir().unwrap();
+ let data = tmp.path().join("data");
+ let key = {
+ let db = Database::init(&data).await.unwrap();
+ let src = FakeSource::default();
+ let now = Utc::now();
+ src.set(vec![asked("old", 20, now)]);
+ run(&db, &src, None, now).await;
+ case(&db, "old").await.dedupe_key
+ };
+ {
+ let pool = sqlx::SqlitePool::connect(&format!("sqlite://{}", data.join("kwnt.db").display())).await.unwrap();
+ sqlx::query("ALTER TABLE zombie_cases DROP COLUMN kwant_id").execute(&pool).await.unwrap();
+ pool.close().await;
+ }
+ let db = Database::init(&data).await.unwrap();
+ let mut c = db.zombie_case_by_key(&key).await.unwrap().expect("the old case is still there");
+ assert_eq!(c.kwant_id, None);
+ c.kwant_id = Some("bot-1".into());
+ db.zombie_put_case(&c).await.unwrap();
+ assert_eq!(db.zombie_case_by_key(&key).await.unwrap().unwrap().kwant_id.as_deref(), Some("bot-1"));
+}
+
/// The case store is not tied to mail: a later source (a photographed letter, a bank statement)
/// stores its cases in the same table without a schema change.
#[tokio::test]