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.

Model badge server: turn_runs_on event and last_ran_on on the bot list (#554)

Oleksandr Ivanchenko3c95cdf5d0bf
diff --git a/src/db/last_ran_on.rs b/src/db/last_ran_on.rs
new file mode 100644
index 00000000..2f338e17
--- /dev/null
+++ b/src/db/last_ran_on.rs
@@ -0,0 +1,198 @@
+//! The engine and model each bot's newest reply ran on, for the model badge on resting rows:
+//! `kwants.last_ran_on`, one nullable JSON column written as a reply's turn ends and read with
+//! the bot list. A column (not a query on the newest reply's `meta.ran_on`) because replies carry
+//! the bot's name, not its id, and the per-bot lookup needed a new index on every message to stay
+//! fast; see autonomy/model-badge/impl.md "Lin server" for the measurements.
+
+use super::{Database, DbError};
+use chrono::{DateTime, NaiveDateTime, Utc};
+use serde_json::{json, Value};
+use std::collections::{HashMap, HashSet};
+
+/// `{engine, family, model, model_label, tier, picked_by, at}` from a reply's `meta.ran_on` and
+/// the time the reply was made. `picked_by` is "laya", "pinned" or "fallback" (the reply's own
+/// "pinned_model" / "pinned_engine" read as "pinned"; a reply that failed over is "fallback").
+pub fn last_ran_on(ran_on: &Value, failed_over: bool, at: DateTime<Utc>) -> Value {
+ let picked_by = match ran_on["picked_by"].as_str() {
+ _ if failed_over => Some("fallback"),
+ Some("pinned_model" | "pinned_engine" | "pinned") => Some("pinned"),
+ Some("laya") => Some("laya"),
+ Some("fallback") => Some("fallback"),
+ _ => None,
+ };
+ json!({
+ "engine": ran_on["engine"],
+ "family": ran_on["family"],
+ "model": ran_on["model"],
+ "model_label": ran_on["model_label"],
+ "tier": ran_on["tier"],
+ "picked_by": picked_by,
+ "at": at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
+ })
+}
+
+/// A stored `created_at`: SQLite's "YYYY-MM-DD HH:MM:SS" (UTC) or RFC 3339.
+fn parse_at(s: &str) -> Option<DateTime<Utc>> {
+ DateTime::parse_from_rfc3339(s)
+ .map(|d| d.with_timezone(&Utc))
+ .ok()
+ .or_else(|| NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f").ok().map(|n| n.and_utc()))
+}
+
+/// The `last_ran_on` of a saved reply's meta, when it has a `ran_on`.
+fn from_meta(meta: &str, at: &str) -> Option<Value> {
+ let meta: Value = serde_json::from_str(meta).ok()?;
+ let ran_on = meta.get("ran_on").filter(|r| r.is_object())?;
+ let failed_over = meta["failover"].as_array().is_some_and(|a| !a.is_empty());
+ Some(last_ran_on(ran_on, failed_over, parse_at(at)?))
+}
+
+/// Replies with a `ran_on`, the newest per sender name; one scan of `messages`.
+const NEWEST_BY_NAME: &str = "SELECT sender_id, meta, MAX(created_at) FROM messages
+ WHERE sender_role = 'kwant' AND meta LIKE '%\"ran_on\"%'
+ AND CASE WHEN json_valid(meta) THEN json_type(meta, '$.ran_on') = 'object' ELSE 0 END
+ GROUP BY sender_id";
+
+/// The newest reply with a `ran_on` in the bot's own direct chat or threads, for a bot whose name
+/// another bot (in another space) also has.
+const NEWEST_OF_BOT: &str = "SELECT meta, created_at FROM messages
+ WHERE sender_role = 'kwant' AND sender_id = ?1
+ AND (direct_kwant_id = ?2 OR thread_id IN (SELECT id FROM threads WHERE kwant_id = ?2))
+ AND meta LIKE '%\"ran_on\"%'
+ AND CASE WHEN json_valid(meta) THEN json_type(meta, '$.ran_on') = 'object' ELSE 0 END
+ ORDER BY created_at DESC, rowid DESC LIMIT 1";
+
+impl Database {
+ /// Adds `kwants.last_ran_on` once and fills it from each bot's newest reply. Run after every
+ /// step that can rebuild `kwants`.
+ pub(super) async fn migrate_last_ran_on(&self) -> Result<(), DbError> {
+ let has: Option<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info('kwants') WHERE name = 'last_ran_on'")
+ .fetch_optional(&self.pool)
+ .await?;
+ if has.is_some() {
+ return Ok(());
+ }
+ let mut tx = self.begin_write().await?;
+ sqlx::query("ALTER TABLE kwants ADD COLUMN last_ran_on TEXT").execute(&mut *tx).await?;
+ let bots: Vec<(String, String)> = sqlx::query_as("SELECT id, name FROM kwants").fetch_all(&mut *tx).await?;
+ let mut seen = HashSet::new();
+ let shared: HashSet<String> = bots.iter().filter(|(_, n)| !seen.insert(n.as_str())).map(|(_, n)| n.clone()).collect();
+ let newest: HashMap<String, (String, String)> = sqlx::query_as::<_, (String, String, String)>(NEWEST_BY_NAME)
+ .fetch_all(&mut *tx)
+ .await?
+ .into_iter()
+ .map(|(name, meta, at)| (name, (meta, at)))
+ .collect();
+ for (id, name) in &bots {
+ let row = if shared.contains(name) {
+ sqlx::query_as::<_, (String, String)>(NEWEST_OF_BOT).bind(name).bind(id).fetch_optional(&mut *tx).await?
+ } else {
+ // Very old replies were saved under the bot's id
+ newest.get(name).or_else(|| newest.get(id)).cloned()
+ };
+ if let Some(v) = row.and_then(|(meta, at)| from_meta(&meta, &at)) {
+ sqlx::query("UPDATE kwants SET last_ran_on = ? WHERE id = ?").bind(v.to_string()).bind(id).execute(&mut *tx).await?;
+ }
+ }
+ tx.commit().await?;
+ Ok(())
+ }
+
+ /// Records what `kwant_id`'s turn just ran on (see [`last_ran_on`]).
+ pub async fn set_last_ran_on(&self, kwant_id: &str, value: &Value) -> Result<(), DbError> {
+ sqlx::query("UPDATE kwants SET last_ran_on = ? WHERE id = ?")
+ .bind(value.to_string())
+ .bind(kwant_id)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ /// Every bot's `last_ran_on` by id; a bot that never replied has none.
+ pub async fn last_ran_on_all(&self) -> Result<HashMap<String, Value>, DbError> {
+ let rows: Vec<(String, String)> = sqlx::query_as("SELECT id, last_ran_on FROM kwants WHERE last_ran_on IS NOT NULL")
+ .fetch_all(&self.pool)
+ .await?;
+ Ok(rows.into_iter().filter_map(|(id, v)| Some((id, serde_json::from_str(&v).ok()?))).collect())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_reply_ran_on_becomes_the_badge_value() {
+ let at = DateTime::parse_from_rfc3339("2026-11-13T02:00:00Z").unwrap().with_timezone(&Utc);
+ let ran_on = json!({"engine": "claude", "engine_name": "Claude Code CLI", "family": "claude", "model": "sonnet",
+ "model_label": "Sonnet", "tier": "balanced", "picked_by": "pinned_model", "effort": "medium", "profile_id": "p", "account": "This machine"});
+ assert_eq!(
+ last_ran_on(&ran_on, false, at),
+ json!({"engine": "claude", "family": "claude", "model": "sonnet", "model_label": "Sonnet", "tier": "balanced",
+ "picked_by": "pinned", "at": "2026-11-13T02:00:00Z"})
+ );
+ assert_eq!(last_ran_on(&ran_on, true, at)["picked_by"], "fallback");
+ assert_eq!(last_ran_on(&json!({"engine": "grok", "picked_by": "laya"}), false, at)["tier"], Value::Null);
+ }
+
+ async fn reply(db: &Database, sender: &str, direct: &str, meta: Option<Value>, at: &str) {
+ let msg = crate::db::models::NewMessage {
+ channel_id: None,
+ direct_kwant_id: Some(direct.into()),
+ sender_role: "kwant".into(),
+ sender_id: sender.into(),
+ text: "hi".into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ };
+ let m = db.insert_message_with(&msg, &crate::db::models::MessageExtra { thread_id: None, meta }).await.unwrap();
+ sqlx::query("UPDATE messages SET created_at = ? WHERE id = ?").bind(at).bind(&m.id).execute(&db.pool).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn an_existing_database_is_backfilled_once_from_each_bots_newest_reply() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let bots: Vec<(String, String)> = sqlx::query_as("SELECT id, name FROM kwants ORDER BY name").fetch_all(&db.pool).await.unwrap();
+ assert!(bots.len() >= 3, "{bots:?}");
+ let ((a, a_name), (b, b_name), (c, _)) = (bots[0].clone(), bots[1].clone(), bots[2].clone());
+ // A database from before the column: replies saved, no column
+ sqlx::query("ALTER TABLE kwants DROP COLUMN last_ran_on").execute(&db.pool).await.unwrap();
+ let ran = |engine: &str, model: &str, tier: &str| json!({"ran_on": {"engine": engine, "family": engine, "model": model, "model_label": model, "tier": tier, "picked_by": "laya"}});
+ reply(&db, &a_name, &a, Some(ran("claude", "opus", "deep")), "2026-11-10 09:00:00").await;
+ reply(&db, &a_name, &a, Some(ran("codex", "gpt-6.1-sol", "balanced")), "2026-11-12 09:00:00").await;
+ // Newer, with no ran_on (a gave-up line) or a broken meta: skipped, never fatal
+ reply(&db, &a_name, &a, None, "2026-11-12 10:00:00").await;
+ reply(&db, &a_name, &a, Some(json!({"kind": "notice"})), "2026-11-12 11:00:00").await;
+ sqlx::query("UPDATE messages SET meta = '{\"ran_on\": oops' WHERE created_at = '2026-11-12 11:00:00'").execute(&db.pool).await.unwrap();
+ // B's name is shared with C (another space may reuse a name): each gets its own chat's reply
+ sqlx::query("UPDATE kwants SET name = ? WHERE id = ?").bind(&b_name).bind(&c).execute(&db.pool).await.unwrap();
+ reply(&db, &b_name, &b, Some(ran("grok", "grok-4-heavy", "deep")), "2026-11-11 09:00:00").await;
+ reply(&db, &b_name, &c, Some(ran("claude", "haiku", "fast")), "2026-11-12 12:00:00").await;
+
+ db.migrate_last_ran_on().await.unwrap();
+ let all = db.last_ran_on_all().await.unwrap();
+ assert_eq!(
+ all[&a],
+ json!({"engine": "codex", "family": "codex", "model": "gpt-6.1-sol", "model_label": "gpt-6.1-sol", "tier": "balanced",
+ "picked_by": "laya", "at": "2026-11-12T09:00:00Z"})
+ );
+ assert_eq!((all[&b]["engine"].clone(), all[&c]["engine"].clone()), (json!("grok"), json!("claude")), "{all:?}");
+ assert!(bots[3..].iter().all(|(id, _)| !all.contains_key(id)), "a bot that never replied has none: {all:?}");
+
+ // Once: a value written since is never overwritten by a later start
+ db.set_last_ran_on(&a, &json!({"engine": "grok"})).await.unwrap();
+ db.migrate_last_ran_on().await.unwrap();
+ assert_eq!(db.last_ran_on_all().await.unwrap()[&a], json!({"engine": "grok"}));
+ }
+
+ #[test]
+ fn stored_times_and_bad_meta_read_safely() {
+ assert_eq!(parse_at("2026-11-13 01:02:03").unwrap().to_rfc3339(), "2026-11-13T01:02:03+00:00");
+ assert!(parse_at("2026-11-13T01:02:03.5+00:00").is_some());
+ assert!(from_meta("{not json", "2026-11-13 01:02:03").is_none());
+ assert!(from_meta(r#"{"ran_on": "vm"}"#, "2026-11-13 01:02:03").is_none());
+ assert!(from_meta(r#"{"ran_on": {"engine": "codex"}, "failover": [{}]}"#, "2026-11-13 01:02:03").is_some_and(|v| v["picked_by"] == "fallback"));
+ }
+}
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 8bc5dca8..71cd7068 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -61,6 +61,7 @@ pub mod isolated_folders;
pub mod tool_notes;
pub mod mission_watch;
pub mod verifier;
+pub mod last_ran_on;
/// What a space's #general says about itself.
pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";
@@ -282,6 +283,9 @@ impl Database {
db.migrate_isolated_folders().await?;
// 0.9.0 wave 3: task contracts and verifier verdicts (add-only)
db.migrate_verifier().await?;
+ // 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?;
db.pool.close().await;
// Said out loud rather than left to sqlx's default: every writer, a goal proposal
diff --git a/src/drivers/events.rs b/src/drivers/events.rs
index 5a0e1149..f4797eba 100644
--- a/src/drivers/events.rs
+++ b/src/drivers/events.rs
@@ -112,6 +112,29 @@ pub enum RuntimeEvent {
#[serde(default, skip_serializing_if = "Option::is_none")]
slots: Option<usize>,
},
+ /// The engine and model a kwant's turn runs on, sent as its driver starts (before any reply
+ /// text) and again with the new values when the turn moves to another engine, model or
+ /// account (failover). Placed like `turn_started`. `model`, `model_label` and `tier` are the
+ /// same values the saved reply's `meta.ran_on` carries; `model` is null when the engine picks
+ /// its own. `picked_by` is "laya" (an auto bot: Laya picked), "pinned" (the bot's settings
+ /// pin the engine or the model) or "fallback" (the turn left its first account).
+ #[serde(rename = "turn_runs_on", alias = "TurnRunsOn")]
+ TurnRunsOn {
+ kwant_id: String,
+ turn_id: String,
+ context_id: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ thread_id: Option<String>,
+ /// The engine id: "claude", "codex", "grok", "anthropic_api", "ollama", "custom", …
+ engine: String,
+ /// The model family: "claude", "codex", "grok" or "ollama" (a custom API's own family).
+ family: String,
+ model: Option<String>,
+ model_label: Option<String>,
+ /// "fast", "balanced" or "deep"; null when the model has no known tier.
+ tier: Option<String>,
+ picked_by: String,
+ },
/// A thread was created, renamed or archived.
#[serde(rename = "thread_updated", alias = "ThreadUpdated")]
ThreadUpdated { thread: Value },
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 0e163915..32b81b86 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -69,7 +69,8 @@ pub(crate) fn db_status(e: &DbError) -> StatusCode {
}
}
-/// The space's kwants, each with `runs_on`: the account its next turn would use.
+/// The space's kwants, each with `runs_on`: the account its next turn would use, and
+/// `last_ran_on`: what its newest reply ran on, or null (see `crate::db::last_ran_on`).
pub async fn list_kwants(
State(state): State<AppState>,
Scope(space): Scope,
@@ -79,11 +80,14 @@ pub async fn list_kwants(
.kwant_views(&space)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+ // What each bot's newest reply ran on: the model badge on a resting row
+ let mut last_ran_on = state.db.last_ran_on_all().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut out = Vec::with_capacity(views.len());
for v in views {
let runs_on = super::profile_turn::runs_on(&state, &v.kwant).await;
let mut item = serde_json::to_value(&v).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
item["runs_on"] = runs_on;
+ item["last_ran_on"] = last_ran_on.remove(&v.kwant.id).unwrap_or(serde_json::Value::Null);
let mode = state
.db
.kwant_approvals_in(&space, &v.kwant.id)
@@ -2742,6 +2746,25 @@ impl RanOn {
}
}
+/// The `turn_runs_on` event for the attempt that is about to run on `r`; its model fields are the
+/// ones the saved reply's `meta.ran_on` gets.
+fn turn_runs_on(r: &RanOn, tag: &crate::drivers::events::TurnTag, picked_by: &str) -> RuntimeEvent {
+ let v = r.to_json(None, picked_by, "");
+ let text = |key: &str| v[key].as_str().map(str::to_string);
+ RuntimeEvent::TurnRunsOn {
+ kwant_id: tag.kwant_id.clone(),
+ turn_id: tag.turn_id.clone(),
+ context_id: Some(tag.context_id.clone()),
+ thread_id: tag.thread_id.clone(),
+ engine: r.engine.as_str().to_string(),
+ family: text("family").unwrap_or_default(),
+ model: text("model"),
+ model_label: text("model_label"),
+ tier: text("tier"),
+ picked_by: picked_by.to_string(),
+ }
+}
+
/// Setting: seconds a streaming model may stay silent (outside tool runs) before its turn is stopped.
pub const STALL_SETTING: &str = "turn_stall_secs";
pub const DEFAULT_STALL_SECS: u64 = 120;
@@ -3312,6 +3335,12 @@ async fn run_kwant_turn_inner(
model: None,
profile: p,
});
+ // `turn_runs_on`'s `picked_by`: who chose what the first account runs; "fallback" once
+ // the turn has left it (or skipped it as known to be out)
+ let picked_first = if pinned_model.is_some() || pinned_family { "pinned" } else { "laya" };
+ let mut left_first = moved_from.is_some();
+ // The last `turn_runs_on` sent, so a stall retry on the same account doesn't repeat it
+ let mut sent_runs_on: Option<RuntimeEvent> = None;
// The switches as the reply's `meta.failover` (one object per switch), so they survive a reload
let mut switch_meta: Vec<serde_json::Value> = Vec::new();
let chat_key = format!("{}|{:?}|{:?}", target_kwant.id, scope.channel_id, scope.thread_id);
@@ -3343,6 +3372,7 @@ async fn run_kwant_turn_inner(
(pinned_model.clone(), tier)
};
let (driver_key, driver_endpoint) = if cross { (None, None) } else { (configured_key.clone(), endpoint.clone()) };
+ left_first |= i > 0;
let (driver, host_engine) = match super::profile_turn::driver_for(
state,
profile.as_ref(),
@@ -3476,6 +3506,14 @@ async fn run_kwant_turn_inner(
account: super::profile_turn::account_name(profile.as_ref(), e),
choice: if unlisted_api { None } else { choice.clone() },
});
+ if let Some(r) = &ran_on {
+ let picked_by = if left_first { "fallback" } else { picked_first };
+ let event = turn_runs_on(r, tag, picked_by);
+ if sent_runs_on.as_ref() != Some(&event) {
+ let _ = state.event_sender.send(event.clone());
+ sent_runs_on = Some(event);
+ }
+ }
let stall_limit = if driver.streams_progress() { stall_after } else { None };
state.turns.note_driver(&tag.turn_id, driver.streams_progress(), runs_on.map(super::bot_status::engine_label));
let (driver_tx, mut driver_rx) = mpsc::channel(32);
@@ -3896,6 +3934,13 @@ async fn run_kwant_turn_inner(
let mut meta = ran_on
.as_ref()
.map(|r| serde_json::json!({ "ran_on": r.to_json(output.model.as_deref(), pick, &effort_level) }));
+ // The badge's resting value, kept for the bot list before the reply goes out
+ if let Some(r) = meta.as_ref().map(|m| &m["ran_on"]) {
+ let last = crate::db::last_ran_on::last_ran_on(r, left_first, chrono::Utc::now());
+ if let Err(e) = state.db.set_last_ran_on(&target_kwant.id, &last).await {
+ tracing::warn!(kwant = %target_kwant.id, error = %e, "could not save last_ran_on");
+ }
+ }
if let Some(usage) = &output.usage {
meta.get_or_insert_with(|| serde_json::json!({}))["usage"] = serde_json::json!(usage);
}
diff --git a/src/server/sse.rs b/src/server/sse.rs
index 2ca2520d..f491e364 100644
--- a/src/server/sse.rs
+++ b/src/server/sse.rs
@@ -63,7 +63,8 @@ pub fn owners(event: &RuntimeEvent) -> Vec<Owner> {
E::TurnComplete { kwant_id, .. } => contexts([kwant_id]),
E::TurnStarted { kwant_id, context_id, thread_id, .. }
| E::TurnEnded { kwant_id, context_id, thread_id, .. }
- | E::TurnQueued { kwant_id, context_id, thread_id, .. } => {
+ | E::TurnQueued { kwant_id, context_id, thread_id, .. }
+ | E::TurnRunsOn { kwant_id, context_id, thread_id, .. } => {
contexts([context_id, thread_id, &Some(kwant_id.clone())])
}
E::ThreadUpdated { thread } => fields(thread, &["kwant_id", "id"], Owner::Context),
@@ -241,6 +242,18 @@ mod tests {
E::TurnStarted { kwant_id: s("k"), context_id: Some(s("c")), turn_id: None, thread_id: None },
E::TurnEnded { kwant_id: s("k"), context_id: None, outcome: s("completed"), turn_id: None, thread_id: None, quiet: false },
E::TurnQueued { turn_id: s("x"), kwant_id: s("k"), context_id: None, thread_id: None, position: 1, reason: s("x"), slots: None },
+ E::TurnRunsOn {
+ kwant_id: s("k"),
+ turn_id: s("x"),
+ context_id: Some(s("c")),
+ thread_id: None,
+ engine: s("claude"),
+ family: s("claude"),
+ model: Some(s("sonnet")),
+ model_label: Some(s("Sonnet")),
+ tier: Some(s("balanced")),
+ picked_by: s("laya"),
+ },
E::ThreadUpdated { thread: json!({"id": "th", "kwant_id": "k"}) },
E::DelegationUpdated { delegation: json!({"id": "d", "lead_kwant_id": "k", "thread_id": "th"}) },
E::MessageAdded { message: json!({"id": "m", "channel_id": "c"}) },
@@ -358,6 +371,7 @@ mod tests {
| E::TurnStarted { .. }
| E::TurnEnded { .. }
| E::TurnQueued { .. }
+ | E::TurnRunsOn { .. }
| E::ThreadUpdated { .. }
| E::DelegationUpdated { .. }
| E::MessageAdded { .. }
@@ -428,6 +442,27 @@ mod tests {
}
}
+ #[test]
+ fn turn_runs_on_is_placed_like_turn_started() {
+ let s = |x: &str| x.to_string();
+ for thread_id in [None, Some(s("th"))] {
+ let started = RuntimeEvent::TurnStarted { kwant_id: s("k"), context_id: Some(s("c")), turn_id: Some(s("t")), thread_id: thread_id.clone() };
+ let runs_on = RuntimeEvent::TurnRunsOn {
+ kwant_id: s("k"),
+ turn_id: s("t"),
+ context_id: Some(s("c")),
+ thread_id,
+ engine: s("codex"),
+ family: s("codex"),
+ model: None,
+ model_label: None,
+ tier: None,
+ picked_by: s("fallback"),
+ };
+ assert_eq!(owners(&runs_on), owners(&started));
+ }
+ }
+
#[test]
fn nested_ids_place_records() {
let msg = RuntimeEvent::MessageAdded { message: json!({"channel_id": null, "direct_kwant_id": "k1"}) };
diff --git a/tests/model_badge_test.rs b/tests/model_badge_test.rs
new file mode 100644
index 00000000..bb45cc9f
--- /dev/null
+++ b/tests/model_badge_test.rs
@@ -0,0 +1,302 @@
+//! The model badge's server side: `turn_runs_on` says which engine and model a turn runs on as
+//! the driver starts (again on failover), and `last_ran_on` on GET /api/kwants keeps what each
+//! bot's newest reply ran on across restarts. Fake claude and codex CLIs on PATH.
+//! Its own test binary: it changes PATH, HOME and the process env.
+
+#[path = "common/exe.rs"]
+mod exe;
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::Database,
+ drivers::RuntimeEvent,
+ router::LayaRouter,
+ server::{create_router, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::collections::BTreeSet;
+use std::path::Path;
+use std::time::Duration;
+use tower::ServiceExt;
+
+/// Prints Claude's session-limit line as its whole reply while `$FAKE_DIR/claude.out` exists.
+const FAKE_CLAUDE: &str = r#"#!/bin/sh
+case "$1" in
+ --version) echo "7.0.1 (Claude Code)"; exit 0 ;;
+ auth) echo '{"loggedIn":true,"authMethod":"claude.ai"}'; exit 0 ;;
+esac
+echo "$*" | tr "\n" " " >> "$FAKE_DIR/claude.argv"; echo >> "$FAKE_DIR/claude.argv"
+if [ -f "$FAKE_DIR/claude.out" ]; then
+ echo '{"type":"result","is_error":false,"num_turns":1,"result":"You'"'"'ve hit your session limit · resets 3am (Europe/Berlin)"}'
+ exit 0
+fi
+echo '{"type":"result","is_error":false,"num_turns":1,"result":"hello from fake claude","usage":{"input_tokens":3,"output_tokens":4}}'
+"#;
+
+const FAKE_CODEX: &str = r#"#!/bin/sh
+case "$1 $2" in
+ "--version "*) echo "codex-cli 0.162.1"; exit 0 ;;
+ "login status") echo "Logged in using ChatGPT"; exit 0 ;;
+ "debug models") cat <<'JSON'
+{"models":[
+ {"slug":"gpt-6.1-sol","display_name":"GPT-6.1 Sol","description":"Latest workhorse model","visibility":"list","priority":1},
+ {"slug":"gpt-6-astra","display_name":"GPT-6 Astra","description":"Frontier intelligence for the most demanding work","visibility":"list","priority":2},
+ {"slug":"gpt-6-luna","display_name":"GPT-6 Luna","description":"Fast and affordable model for easier tasks","visibility":"list","priority":3}]}
+JSON
+ exit 0 ;;
+ "mcp list") echo '[]'; exit 0 ;;
+esac
+echo "$*" | tr "\n" " " >> "$FAKE_DIR/codex.argv"; echo >> "$FAKE_DIR/codex.argv"
+out=""
+prev=""
+for a in "$@"; do
+ if [ "$prev" = "-o" ]; then out="$a"; fi
+ prev="$a"
+done
+[ -n "$out" ] && echo "hello from fake codex" > "$out"
+exit 0
+"#;
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let resp = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method(method)
+ .uri(uri)
+ .header("content-type", "application/json")
+ .body(body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ let s = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (s, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+async fn app_on(data: &Path) -> (Router, AppState) {
+ let db = Database::init(data).await.unwrap();
+ let config = Config {
+ data_dir: data.to_path_buf(),
+ laya_url: "http://127.0.0.1:9".into(),
+ browser_cdp_url: Some("http://127.0.0.1:9".into()),
+ ..Config::default()
+ };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(data.join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ (create_router(state.clone()), state)
+}
+
+/// Sends a prompt and collects the turn's events (scoped as sent) up to `turn_ended`.
+async fn run_turn(app: &Router, state: &AppState, kwant_id: &str) -> Vec<RuntimeEvent> {
+ let mut rx = state.event_sender.subscribe();
+ let (s, v) = call(app, "POST", "/api/chat/send", Some(json!({"kwant_id": kwant_id, "prompt": "hi", "sender_id": "user"}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ let mut events = Vec::new();
+ tokio::time::timeout(Duration::from_secs(60), async {
+ while let Ok(e) = rx.recv().await {
+ let end = matches!(e.unscoped(), RuntimeEvent::TurnEnded { kwant_id: k, .. } if k == kwant_id);
+ events.push(e);
+ if end {
+ break;
+ }
+ }
+ })
+ .await
+ .expect("turn did not end");
+ events
+}
+
+/// The turn's `turn_runs_on` events, as the wire sends them.
+fn runs_on(events: &[RuntimeEvent]) -> Vec<Value> {
+ events.iter().filter(|e| matches!(e.unscoped(), RuntimeEvent::TurnRunsOn { .. })).map(|e| e.to_wire()).collect()
+}
+
+/// Where each kind of event sits in the turn: the first index of each.
+fn first(events: &[RuntimeEvent], f: impl Fn(&RuntimeEvent) -> bool) -> usize {
+ events.iter().position(|e| f(e.unscoped())).unwrap_or_else(|| panic!("missing: {events:?}"))
+}
+
+async fn last_reply_meta(state: &AppState, kwant_id: &str) -> Value {
+ let msgs = state.db.list_messages(kwant_id, 50).await.unwrap();
+ let m = msgs.iter().rev().find(|m| m.sender_role == "kwant").expect("a saved reply");
+ m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null)
+}
+
+async fn kwant(app: &Router, id: &str) -> Value {
+ let (s, list) = call(app, "GET", "/api/kwants", None).await;
+ assert_eq!(s, StatusCode::OK, "{list}");
+ list.as_array().unwrap().iter().find(|k| k["id"] == id).cloned().unwrap_or_else(|| panic!("{id} in {list}"))
+}
+
+fn keys(v: &Value) -> BTreeSet<String> {
+ v.as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default()
+}
+
+/// The event's model fields match the saved reply's `ran_on`.
+fn same_model(ev: &Value, ran_on: &Value) {
+ for k in ["engine", "family", "model", "model_label", "tier"] {
+ assert_eq!(ev["data"][k], ran_on[k], "{k}: {ev} vs {ran_on}");
+ }
+}
+
+async fn pin(app: &Router, id: &str, model: &str) {
+ let mut body = kwant(app, id).await;
+ body.as_object_mut().unwrap().retain(|key, _| ["name", "title", "persona_prompt", "soul", "avatar_sprite"].contains(&key.as_str()));
+ body["preferred_model"] = json!(model);
+ let (s, v) = call(app, "PUT", &format!("/api/kwants/{id}"), Some(body)).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+}
+
+#[tokio::test]
+async fn turns_say_what_they_run_on_and_the_bot_list_remembers_it() {
+ let tmp = tempfile::tempdir().unwrap();
+ let bin = tmp.path().join("bin");
+ std::fs::create_dir_all(&bin).unwrap();
+ for (name, script) in [("claude", FAKE_CLAUDE), ("codex", FAKE_CODEX)] {
+ exe::write_executable(bin.join(name), script);
+ }
+ std::env::set_var("PATH", format!("{}:/usr/bin:/bin", bin.display()));
+ std::env::set_var("HOME", tmp.path());
+ std::env::set_var("FAKE_DIR", tmp.path());
+ for var in ["ANTHROPIC_API_KEY", "OPENAI_API_KEY", "XAI_API_KEY", "OLLAMA_MODEL", "CLAUDE_CONFIG_DIR"] {
+ std::env::remove_var(var);
+ }
+ std::env::set_var("OLLAMA_URL", "http://127.0.0.1:9");
+
+ let data = tmp.path().join("data");
+ let (app, state) = app_on(&data).await;
+ let (s, v) = call(&app, "POST", "/api/engines/recheck", None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ for (id, priority) in [("prf_system_claude", 10), ("prf_system_codex", 20)] {
+ let (s, v) = call(&app, "PATCH", &format!("/api/profiles/{id}"), Some(json!({"priority": priority}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ }
+
+ // 1. A new bot has never run: last_ran_on is there, and null (so is a starter bot's)
+ let (s, created) = call(&app, "POST", "/api/kwants", Some(json!({"name": "Badge", "title": "Badge tester", "persona_prompt": "Test persona",
+ "avatar_sprite": "s", "driver_type": "api", "preferred_model": "auto"}))).await;
+ assert!(s.is_success(), "{s} {created}");
+ let new_id = created["id"].as_str().unwrap().to_string();
+ let fresh = kwant(&app, &new_id).await;
+ assert!(fresh.as_object().unwrap().contains_key("last_ran_on") && fresh["last_ran_on"].is_null(), "{fresh}");
+ let (_, list) = call(&app, "GET", "/api/kwants", None).await;
+ let kid = list[0]["id"].as_str().unwrap().to_string();
+ assert_ne!(kid, new_id);
+ let before = kwant(&app, &kid).await;
+ assert!(before["last_ran_on"].is_null(), "{before}");
+ pin(&app, &kid, "auto").await;
+
+ // 2. Auto: one turn_runs_on with Laya's pick (Laya offline: "hi" is the fast tier, Haiku),
+ // after turn_started and before the reply's first text, scoped like turn_started
+ let events = run_turn(&app, &state, &kid).await;
+ let ro = runs_on(&events);
+ assert_eq!(ro.len(), 1, "{events:?}");
+ let ev = &ro[0];
+ assert_eq!(ev["type"], "turn_runs_on");
+ assert_eq!(
+ keys(&ev["data"]),
+ ["context_id", "engine", "family", "kwant_id", "model", "model_label", "picked_by", "tier", "turn_id"].map(String::from).into(),
+ "{ev}"
+ );
+ let d = &ev["data"];
+ assert_eq!(
+ (d["kwant_id"].clone(), d["engine"].clone(), d["family"].clone(), d["model"].clone(), d["tier"].clone(), d["picked_by"].clone()),
+ (json!(kid), json!("claude"), json!("claude"), json!("haiku"), json!("fast"), json!("laya")),
+ "{ev}"
+ );
+ assert!(d["model_label"].is_string() && d["turn_id"].is_string() && d["context_id"].is_string(), "{ev}");
+ let started = first(&events, |e| matches!(e, RuntimeEvent::TurnStarted { .. }));
+ let runs = first(&events, |e| matches!(e, RuntimeEvent::TurnRunsOn { .. }));
+ let text = first(&events, |e| matches!(e, RuntimeEvent::TextDelta(_)));
+ assert!(started < runs && runs < text, "{started} {runs} {text}: {events:?}");
+ let RuntimeEvent::TurnStarted { context_id, turn_id, .. } = events[started].unscoped() else { unreachable!() };
+ assert_eq!((Some(d["context_id"].as_str().unwrap()), Some(d["turn_id"].as_str().unwrap())), (context_id.as_deref(), turn_id.as_deref()));
+
+ // An older client's payload is unchanged: turn_started's shape, the reply's ran_on keys
+ let wire = events[started].to_wire();
+ assert_eq!(wire["type"], "turn_started");
+ assert_eq!(keys(&wire["data"]), ["context_id", "kwant_id", "turn_id"].map(String::from).into(), "{wire}");
+ let meta = last_reply_meta(&state, &kid).await;
+ let ran_on = meta["ran_on"].clone();
+ assert_eq!(
+ keys(&ran_on),
+ ["account", "effort", "engine", "engine_name", "family", "model", "model_label", "picked_by", "profile_id", "tier"].map(String::from).into(),
+ "{ran_on}"
+ );
+ assert_eq!(ran_on["picked_by"], "laya", "the reply keeps its own vocabulary");
+ same_model(ev, &ran_on);
+
+ // 3. last_ran_on right after the reply: the reply's model, Laya's pick, its time
+ let after = kwant(&app, &kid).await;
+ let last = after["last_ran_on"].clone();
+ for k in ["engine", "family", "model", "model_label", "tier"] {
+ assert_eq!(last[k], ran_on[k], "{k}: {last} vs {ran_on}");
+ }
+ assert_eq!(last["picked_by"], "laya");
+ let at = chrono::DateTime::parse_from_rfc3339(last["at"].as_str().unwrap()).unwrap();
+ assert!((chrono::Utc::now() - at.with_timezone(&chrono::Utc)).num_seconds().abs() < 60, "{last}");
+ // Every key the list had before is still there; only last_ran_on is new
+ assert!(keys(&before).is_subset(&keys(&after)), "{before} vs {after}");
+
+ // 4. A pinned model: picked_by "pinned" on both
+ pin(&app, &kid, "claude/sonnet").await;
+ let events = run_turn(&app, &state, &kid).await;
+ let ro = runs_on(&events);
+ assert_eq!(ro.len(), 1, "{events:?}");
+ assert_eq!((ro[0]["data"]["model"].clone(), ro[0]["data"]["picked_by"].clone()), (json!("sonnet"), json!("pinned")), "{ro:?}");
+ let ran_on = last_reply_meta(&state, &kid).await["ran_on"].clone();
+ assert_eq!(ran_on["picked_by"], "pinned_model");
+ same_model(&ro[0], &ran_on);
+ let last = kwant(&app, &kid).await["last_ran_on"].clone();
+ assert_eq!((last["model"].clone(), last["picked_by"].clone()), (json!("sonnet"), json!("pinned")), "{last}");
+
+ // 5. Failover: Claude is out, so a second turn_runs_on names Codex, picked_by "fallback"
+ pin(&app, &kid, "claude").await;
+ std::fs::write(tmp.path().join("claude.out"), "").unwrap();
+ let events = run_turn(&app, &state, &kid).await;
+ let ro = runs_on(&events);
+ assert_eq!(ro.len(), 2, "{events:?}");
+ assert_eq!((ro[0]["data"]["engine"].clone(), ro[0]["data"]["picked_by"].clone()), (json!("claude"), json!("pinned")), "{ro:?}");
+ assert_eq!((ro[1]["data"]["engine"].clone(), ro[1]["data"]["picked_by"].clone()), (json!("codex"), json!("fallback")), "{ro:?}");
+ assert_eq!(ro[0]["data"]["turn_id"], ro[1]["data"]["turn_id"], "one turn");
+ let sw = first(&events, |e| matches!(e, RuntimeEvent::ProfileSwitched { .. }));
+ let second = events.iter().rposition(|e| matches!(e.unscoped(), RuntimeEvent::TurnRunsOn { .. })).unwrap();
+ assert!(sw < second, "the switch line comes first: {events:?}");
+ let ran_on = last_reply_meta(&state, &kid).await["ran_on"].clone();
+ assert_eq!(ran_on["engine"], "codex");
+ same_model(&ro[1], &ran_on);
+ let last = kwant(&app, &kid).await["last_ran_on"].clone();
+ assert_eq!((last["engine"].clone(), last["picked_by"].clone()), (json!("codex"), json!("fallback")), "{last}");
+ // A later turn that skips Claude unasked also says so from the start
+ let ro = runs_on(&run_turn(&app, &state, &kid).await);
+ assert_eq!(ro.len(), 1, "{ro:?}");
+ assert_eq!((ro[0]["data"]["engine"].clone(), ro[0]["data"]["picked_by"].clone()), (json!("codex"), json!("fallback")), "{ro:?}");
+ let last = kwant(&app, &kid).await["last_ran_on"].clone();
+
+ // 6. A restart: the same last_ran_on for every bot, read back from the database
+ let all_before: Vec<(Value, Value)> = {
+ let (_, list) = call(&app, "GET", "/api/kwants", None).await;
+ list.as_array().unwrap().iter().map(|k| (k["id"].clone(), k["last_ran_on"].clone())).collect()
+ };
+ drop(app);
+ let (app2, _state2) = app_on(&data).await;
+ assert_eq!(kwant(&app2, &kid).await["last_ran_on"], last);
+ let (_, list) = call(&app2, "GET", "/api/kwants", None).await;
+ let all_after: Vec<(Value, Value)> = list.as_array().unwrap().iter().map(|k| (k["id"].clone(), k["last_ran_on"].clone())).collect();
+ assert_eq!(all_after, all_before);
+ assert_eq!(kwant(&app2, &new_id).await["last_ran_on"], Value::Null, "a bot that never ran stays null");
+}