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.

Engines: ready and uses on GET /api/engines from the engine's accounts

Lin (kwant bot)8689cf11f127
diff --git a/src/drivers/engines.rs b/src/drivers/engines.rs
index 20be8bca..66d6a25b 100644
--- a/src/drivers/engines.rs
+++ b/src/drivers/engines.rs
@@ -208,6 +208,18 @@ pub struct EngineReport {
pub version: Option<String>,
pub models: Vec<EngineModel>,
pub checked_at: Option<DateTime<Utc>>,
+ /// On, and its own login (`status` ready) or one of its accounts can take a turn: set
+ /// from the profiles by `profile_turn::with_accounts`.
+ pub ready: bool,
+ /// The account a kwant on this engine runs on; `None` when not ready.
+ pub uses: Option<EngineAccount>,
+}
+
+/// An account (profile) an engine runs on, as `GET /api/engines` names it.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct EngineAccount {
+ pub profile_id: String,
+ pub label: String,
}
impl EngineReport {
@@ -226,6 +238,8 @@ impl EngineReport {
version: p.version,
models: if p.status == EngineStatus::Ready { p.models } else { Vec::new() },
checked_at,
+ ready: false,
+ uses: None,
}
}
diff --git a/src/profiles/mod.rs b/src/profiles/mod.rs
index 20a8d942..d746bb83 100644
--- a/src/profiles/mod.rs
+++ b/src/profiles/mod.rs
@@ -230,9 +230,30 @@ pub struct Availability {
pub with_key: HashSet<String>,
/// Profiles whose last login check said signed out.
pub signed_out: HashSet<String>,
+ /// Profiles whose last login check said signed in.
+ pub signed_in: HashSet<String>,
+}
+
+/// How sure an account check must be that a profile is signed in.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SignInBar {
+ /// Not known to be signed out: what turn routing uses, so a profile isn't skipped before
+ /// its first sign-in check.
+ NotSignedOut,
+ /// Signed in on its last check (an API-key profile: has its key): what Engines calls ready.
+ SignedIn,
}
impl Availability {
+ /// Whether `p` passes `bar`: also never out of quota, and never an API-key profile without
+ /// its key.
+ pub fn admits(&self, p: &LlmProfile, now: DateTime<Utc>, bar: SignInBar) -> bool {
+ self.usable(p, now)
+ && (bar == SignInBar::NotSignedOut
+ || p.kind == "api_key"
+ || self.signed_in.contains(&p.id))
+ }
+
fn usable(&self, p: &LlmProfile, now: DateTime<Utc>) -> bool {
let limited = self
.states
@@ -244,6 +265,28 @@ impl Availability {
}
}
+/// `engine`'s enabled profiles in the order failover prefers them: `bound` (if it is one of
+/// them) or else the default first, then the rest by priority.
+pub fn preference_order<'a>(
+ profiles: &'a [LlmProfile],
+ engine: Engine,
+ bound: Option<&str>,
+) -> Vec<&'a LlmProfile> {
+ let mut mine: Vec<&LlmProfile> = profiles
+ .iter()
+ .filter(|p| p.engine == engine.as_str() && p.enabled)
+ .collect();
+ mine.sort_by(|a, b| (a.priority, a.created_at, &a.id).cmp(&(b.priority, b.created_at, &b.id)));
+ let first = bound
+ .and_then(|id| mine.iter().position(|p| p.id == id))
+ .or_else(|| mine.iter().position(|p| p.is_default));
+ if let Some(i) = first {
+ let p = mine.remove(i);
+ mine.insert(0, p);
+ }
+ mine
+}
+
/// Profiles a turn on `engine` tries, in order. First the kwant's own profile (`bound`, if it is
/// an enabled profile of this engine) or else the engine default; then, with failover on, the
/// engine's other enabled profiles by priority that aren't out of quota, keyless or signed out.
@@ -257,25 +300,16 @@ pub fn failover_order(
avail: &Availability,
now: DateTime<Utc>,
) -> Vec<LlmProfile> {
- let mut mine: Vec<&LlmProfile> = profiles
- .iter()
- .filter(|p| p.engine == engine.as_str() && p.enabled)
- .collect();
- mine.sort_by(|a, b| (a.priority, a.created_at, &a.id).cmp(&(b.priority, b.created_at, &b.id)));
- let first = bound
- .and_then(|id| mine.iter().find(|p| p.id == id))
- .or_else(|| mine.iter().find(|p| p.is_default))
- .or_else(|| mine.first())
- .copied();
- let Some(first) = first else {
+ let mine = preference_order(profiles, engine, bound);
+ let Some(&first) = mine.first() else {
return Vec::new();
};
if !failover {
return vec![first.clone()];
}
- let rest: Vec<LlmProfile> = mine
+ let rest: Vec<LlmProfile> = mine[1..]
.iter()
- .filter(|p| p.id != first.id && avail.usable(p, now))
+ .filter(|p| avail.usable(p, now))
.map(|p| (*p).clone())
.collect();
let mut order = Vec::with_capacity(MAX_ATTEMPTS);
@@ -442,6 +476,7 @@ mod tests {
states,
with_key: HashSet::new(),
signed_out: HashSet::from(["a".to_string()]),
+ ..Default::default()
};
// sys is limited so it's skipped even as the default; a is signed out; b has no key; d is disabled
assert_eq!(
diff --git a/src/profiles/status.rs b/src/profiles/status.rs
index 6366f396..487d6467 100644
--- a/src/profiles/status.rs
+++ b/src/profiles/status.rs
@@ -72,6 +72,17 @@ impl ProfileManager {
.collect()
}
+ /// Profiles whose last check said signed in, for Engines to call ready.
+ pub fn signed_in(&self) -> HashSet<String> {
+ self.cache
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|(_, (_, s))| s.signed_in == Some(true))
+ .map(|(id, _)| id.clone())
+ .collect()
+ }
+
/// Sign-in status of every profile; checks run concurrently, only for stale entries.
/// `with_key`: profiles (and system profiles whose engine has a Settings or env key) that
/// count as signed in through an API key.
diff --git a/src/server/engine_routes.rs b/src/server/engine_routes.rs
index e0d2e3bc..3737dcbc 100644
--- a/src/server/engine_routes.rs
+++ b/src/server/engine_routes.rs
@@ -1,6 +1,7 @@
//! `GET /api/engines`, `POST /api/engines/recheck` and `POST /api/engines/{id}`: whether each
//! engine can run, why not, the models it offers, and turning one off or on.
+use super::profile_turn::{self, with_accounts};
use super::AppState;
use crate::drivers::engines::{parse_disabled, EngineId, EngineReport, ProbeEnv, DISABLED_SETTING};
use axum::{
@@ -15,9 +16,13 @@ pub struct EnginesResponse {
pub engines: Vec<EngineReport>,
}
-/// The cached checks; never waits on one. Engines not checked yet show as "checking".
+/// The cached checks; never waits on one. Engines not checked yet show as "checking". Stale
+/// profile sign-in checks run in the background for the next call.
pub async fn list(State(state): State<AppState>) -> Json<EnginesResponse> {
- Json(EnginesResponse { engines: state.engines.snapshot() })
+ let engines = with_accounts(&state, state.engines.snapshot()).await;
+ let bg = state.clone();
+ tokio::spawn(async move { profile_turn::refresh_sign_ins(&bg).await });
+ Json(EnginesResponse { engines })
}
/// Checks every engine again and answers once done (each check is capped at 10s).
@@ -25,10 +30,12 @@ pub async fn recheck(State(state): State<AppState>) -> Json<EnginesResponse> {
Json(EnginesResponse { engines: recheck_all(&state).await })
}
+/// Every engine and every profile's sign-in, checked again.
pub async fn recheck_all(state: &AppState) -> Vec<EngineReport> {
load_disabled(state).await;
let env = probe_env(state).await;
- state.engines.recheck(&env).await
+ let (engines, ()) = tokio::join!(state.engines.recheck(&env), profile_turn::refresh_sign_ins(state));
+ with_accounts(state, engines).await
}
/// What the checks run with: Settings and the env, and Claude's sign-in config dir.
@@ -74,7 +81,7 @@ pub async fn set_enabled(
let env = probe_env(&state).await;
state.engines.recheck_one(id, &env).await;
}
- Ok(Json(EnginesResponse { engines: state.engines.snapshot() }))
+ Ok(Json(EnginesResponse { engines: with_accounts(&state, state.engines.snapshot()).await }))
}
/// Checks every engine in the background, so the first turns after startup see real status.
diff --git a/src/server/profile_routes.rs b/src/server/profile_routes.rs
index 6c749650..542c1da9 100644
--- a/src/server/profile_routes.rs
+++ b/src/server/profile_routes.rs
@@ -59,7 +59,7 @@ pub struct ProfileOut {
/// Profiles that count as signed in through a key: their own, or for a system profile the
/// engine's Settings key or env key, as before profiles.
-async fn keyed_ids(state: &AppState, profiles: &[LlmProfile]) -> HashSet<String> {
+pub(super) async fn keyed_ids(state: &AppState, profiles: &[LlmProfile]) -> HashSet<String> {
let mut ids = state.db.profile_ids_with_key().await.unwrap_or_default();
for p in profiles.iter().filter(|p| p.kind == "system") {
let Some(engine) = Engine::parse(&p.engine) else {
diff --git a/src/server/profile_turn.rs b/src/server/profile_turn.rs
index f47e10fe..1530bfba 100644
--- a/src/server/profile_turn.rs
+++ b/src/server/profile_turn.rs
@@ -3,34 +3,47 @@
use super::AppState;
use crate::db::models::LlmProfile;
-use crate::drivers::engines::EngineId;
+use crate::drivers::engines::{EngineAccount, EngineId, EngineReport, EngineStatus};
use crate::drivers::{find_cli_binary, resolve_driver_for_model, ApiDriver, CliDriver, Driver};
use std::collections::HashSet;
+use std::sync::atomic::{AtomicBool, Ordering};
use crate::profiles::{
- failover_order, Availability, Engine, FailClass, ProfileStatus, ProviderFailure,
+ failover_order, preference_order, Availability, Engine, FailClass, ProfileStatus,
+ ProviderFailure, SignInBar,
};
-/// Profiles to try for a turn on `engine`, in order. Empty when the model has no profiles
-/// (e.g. Ollama) or the engine has none enabled: the turn then runs as before profiles.
-pub async fn plan(state: &AppState, engine: Option<Engine>, kwant_id: &str) -> Vec<LlmProfile> {
- let Some(engine) = engine else {
- return Vec::new();
- };
+/// Every profile and what decides whether each can take a turn now, from the db and the
+/// cached sign-in checks (never waits on a check). `None` when the db can't be read.
+async fn accounts(state: &AppState) -> Option<(Vec<LlmProfile>, Availability)> {
let db = &state.db;
- let (Ok(profiles), Ok(binding), Ok(states), Ok(with_key)) = (
+ let (Ok(profiles), Ok(states), Ok(with_key)) = (
db.list_profiles().await,
- db.get_kwant_binding(kwant_id).await,
db.list_profile_states().await,
db.profile_ids_with_key().await,
) else {
- return Vec::new();
+ return None;
};
- let (bound, failover) = binding.unwrap_or((None, true));
let avail = Availability {
states,
with_key,
signed_out: state.profiles.signed_out(),
+ signed_in: state.profiles.signed_in(),
+ };
+ Some((profiles, avail))
+}
+
+/// Profiles to try for a turn on `engine`, in order. Empty when the model has no profiles
+/// (e.g. Ollama) or the engine has none enabled: the turn then runs as before profiles.
+pub async fn plan(state: &AppState, engine: Option<Engine>, kwant_id: &str) -> Vec<LlmProfile> {
+ let Some(engine) = engine else {
+ return Vec::new();
};
+ let (Some((profiles, avail)), Ok(binding)) =
+ (accounts(state).await, state.db.get_kwant_binding(kwant_id).await)
+ else {
+ return Vec::new();
+ };
+ let (bound, failover) = binding.unwrap_or((None, true));
failover_order(
&profiles,
engine,
@@ -98,35 +111,104 @@ pub async fn driver_for(
))
}
+/// `family`'s own accounts (not the system profile) that pass `bar` and whose engine is on,
+/// in the order failover prefers them. The one rule for "this account can take a turn".
+fn own_accounts<'a>(
+ state: &AppState,
+ profiles: &'a [LlmProfile],
+ family: Engine,
+ avail: &Availability,
+ bar: SignInBar,
+) -> Vec<&'a LlmProfile> {
+ let now = chrono::Utc::now();
+ preference_order(profiles, family, None)
+ .into_iter()
+ .filter(|p| p.kind != "system" && avail.admits(p, now, bar))
+ .filter(|p| profile_engine_on(state, p))
+ .collect()
+}
+
/// Engines with an enabled account of their own (not the system profile) that failover
-/// would use: these engines can run even when the host's own CLI or key can't.
+/// would use: these engines can run even when the host's own CLI or key can't. Routing keeps
+/// the lenient bar (an unchecked profile counts) so turns right after startup, before any
+/// sign-in check, still reach a profile that is in fact signed in.
pub async fn profile_engines(state: &AppState) -> HashSet<Engine> {
- let db = &state.db;
- let (Ok(profiles), Ok(states), Ok(with_key)) = (
- db.list_profiles().await,
- db.list_profile_states().await,
- db.profile_ids_with_key().await,
- ) else {
+ let Some((profiles, avail)) = accounts(state).await else {
return HashSet::new();
};
- let signed_out = state.profiles.signed_out();
- let now = chrono::Utc::now();
- profiles
- .iter()
- .filter(|p| p.enabled && p.kind != "system")
- .filter(|p| profile_engine_on(state, p))
- .filter(|p| p.kind != "api_key" || with_key.contains(&p.id))
- .filter(|p| !signed_out.contains(&p.id))
- .filter(|p| {
- !states
- .get(&p.id)
- .and_then(|s| s.limited_until)
- .is_some_and(|t| t > now)
- })
- .filter_map(|p| Engine::parse(&p.engine))
+ [Engine::Claude, Engine::Codex, Engine::Grok]
+ .into_iter()
+ .filter(|f| !own_accounts(state, &profiles, *f, &avail, SignInBar::NotSignedOut).is_empty())
.collect()
}
+/// Whether `report`'s engine is ready and the account a kwant on it uses: the first of the
+/// engine's accounts in failover order (the default first) that can take a turn, the system
+/// profile ("This machine") counting when the engine's own login is ready. Off ⇒ not ready.
+pub fn readiness(
+ report: &EngineReport,
+ profiles: &[LlmProfile],
+ avail: &Availability,
+ now: chrono::DateTime<chrono::Utc>,
+) -> (bool, Option<EngineAccount>) {
+ if !report.enabled {
+ return (false, None);
+ }
+ let host = report.status == EngineStatus::Ready;
+ let Some(family) = report.id.family() else {
+ return (host, None);
+ };
+ let system = |p: &&LlmProfile| p.kind == "system";
+ let picked = preference_order(profiles, family, None)
+ .into_iter()
+ .filter(|p| system(p) || profile_engine(p) == Some(report.id))
+ .find(|p| {
+ if system(p) {
+ host
+ } else {
+ avail.admits(p, now, SignInBar::SignedIn)
+ }
+ })
+ .or_else(|| {
+ // This machine turned off as a profile still runs turns when nothing else does
+ host.then(|| profiles.iter().find(|p| p.engine == family.as_str() && system(p)))
+ .flatten()
+ });
+ let uses = picked.map(|p| EngineAccount { profile_id: p.id.clone(), label: p.name.clone() });
+ (host || uses.is_some(), uses)
+}
+
+/// Fills in `ready` and `uses` on every report.
+pub async fn with_accounts(state: &AppState, mut reports: Vec<EngineReport>) -> Vec<EngineReport> {
+ let accounts = accounts(state).await;
+ let now = chrono::Utc::now();
+ for r in &mut reports {
+ let (ready, uses) = match &accounts {
+ Some((profiles, avail)) => readiness(r, profiles, avail, now),
+ None => (r.enabled && r.status == EngineStatus::Ready, None),
+ };
+ // An engine switched off is off for its accounts too (see profile_engine_on)
+ r.ready = ready;
+ r.uses = uses;
+ }
+ reports
+}
+
+static REFRESHING: AtomicBool = AtomicBool::new(false);
+
+/// Runs the stale profile sign-in checks so `ready` is current; one run at a time, others
+/// return at once.
+pub async fn refresh_sign_ins(state: &AppState) {
+ if REFRESHING.swap(true, Ordering::AcqRel) {
+ return;
+ }
+ if let Ok(profiles) = state.db.list_profiles().await {
+ let keyed = super::profile_routes::keyed_ids(state, &profiles).await;
+ state.profiles.statuses(&profiles, &keyed).await;
+ }
+ REFRESHING.store(false, Ordering::Release);
+}
+
/// Remembers a refusal so failover skips the profile: until its quota resets, or until it is
/// signed in again.
pub async fn record_failure(state: &AppState, profile: &LlmProfile, failure: &ProviderFailure) {
@@ -188,3 +270,171 @@ pub fn give_up_notice(
};
format!("⚠️ [{kwant_name}] {which} {}. {fix}", reason(failure))
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::db::models::LlmProfileState;
+ use chrono::{DateTime, Duration, TimeZone, Utc};
+ use std::collections::HashMap;
+
+ fn now() -> DateTime<Utc> {
+ Utc.with_ymd_and_hms(2026, 10, 17, 12, 0, 0).unwrap()
+ }
+
+ fn profile(id: &str, name: &str, kind: &str, priority: i64, default: bool) -> LlmProfile {
+ LlmProfile {
+ id: id.into(),
+ engine: "claude".into(),
+ name: name.into(),
+ kind: kind.into(),
+ home_dir: None,
+ priority,
+ enabled: true,
+ is_default: default,
+ created_at: None,
+ }
+ }
+
+ fn report(id: EngineId, enabled: bool, status: EngineStatus) -> EngineReport {
+ EngineReport {
+ id,
+ name: id.name().into(),
+ kind: id.kind(),
+ enabled,
+ status,
+ detail: None,
+ version: None,
+ models: Vec::new(),
+ checked_at: None,
+ ready: false,
+ uses: None,
+ }
+ }
+
+ fn signed_in(ids: &[&str]) -> Availability {
+ Availability {
+ signed_in: ids.iter().map(|s| s.to_string()).collect(),
+ ..Default::default()
+ }
+ }
+
+ fn uses(r: (bool, Option<EngineAccount>)) -> (bool, Option<String>) {
+ (r.0, r.1.map(|a| a.label))
+ }
+
+ /// Oleks's setup: This machine plus a Personal Claude account that is the default.
+ fn oleks() -> Vec<LlmProfile> {
+ vec![
+ profile("prf_system_claude", "This machine", "system", 0, false),
+ profile("p_personal", "Personal", "cli_home", 100, true),
+ ]
+ }
+
+ #[test]
+ fn engine_off_is_not_ready_even_with_a_signed_in_account() {
+ let r = report(EngineId::Claude, false, EngineStatus::Disabled);
+ let avail = signed_in(&["p_personal"]);
+ assert_eq!(readiness(&r, &oleks(), &avail, now()), (false, None));
+ }
+
+ #[test]
+ fn host_signed_out_but_personal_signed_in_is_ready_on_personal() {
+ let r = report(EngineId::Claude, true, EngineStatus::SignedOut);
+ let got = readiness(&r, &oleks(), &signed_in(&["p_personal"]), now());
+ assert!(got.0);
+ assert_eq!(
+ got.1,
+ Some(EngineAccount { profile_id: "p_personal".into(), label: "Personal".into() })
+ );
+ // Host signed out and no account signed in: not ready
+ let got = readiness(&r, &oleks(), &Availability::default(), now());
+ assert_eq!(got, (false, None));
+ }
+
+ #[test]
+ fn unknown_sign_in_is_not_ready_but_routing_still_tries_it() {
+ let r = report(EngineId::Claude, true, EngineStatus::SignedOut);
+ let unknown = Availability::default();
+ assert_eq!(readiness(&r, &oleks(), &unknown, now()), (false, None));
+ // Routing keeps the lenient bar: an unchecked profile is still tried by a turn
+ let personal = &oleks()[1];
+ assert!(unknown.admits(personal, now(), SignInBar::NotSignedOut));
+ assert!(!unknown.admits(personal, now(), SignInBar::SignedIn));
+ }
+
+ #[test]
+ fn quota_limited_account_is_not_ready_until_it_resets() {
+ let r = report(EngineId::Claude, true, EngineStatus::SignedOut);
+ let limited = |until: DateTime<Utc>| Availability {
+ states: HashMap::from([(
+ "p_personal".to_string(),
+ LlmProfileState {
+ profile_id: "p_personal".into(),
+ limited_until: Some(until),
+ last_error: Some("quota".into()),
+ },
+ )]),
+ ..signed_in(&["p_personal"])
+ };
+ let avail = limited(now() + Duration::hours(1));
+ assert_eq!(readiness(&r, &oleks(), &avail, now()), (false, None));
+ let avail = limited(now() - Duration::minutes(1));
+ assert_eq!(uses(readiness(&r, &oleks(), &avail, now())), (true, Some("Personal".into())));
+ }
+
+ #[test]
+ fn uses_the_default_first_then_priority_order() {
+ let r = report(EngineId::Claude, true, EngineStatus::Ready);
+ let profiles = vec![
+ profile("prf_system_claude", "This machine", "system", 0, false),
+ profile("p_work", "Work", "cli_home", 10, false),
+ profile("p_personal", "Personal", "cli_home", 20, true),
+ ];
+ // The default wins over a higher priority, signed-in account and the host's own login
+ let all = signed_in(&["p_work", "p_personal"]);
+ assert_eq!(uses(readiness(&r, &profiles, &all, now())), (true, Some("Personal".into())));
+ // Default not signed in: next by priority, here This machine (host ready)
+ let work = signed_in(&["p_work"]);
+ assert_eq!(uses(readiness(&r, &profiles, &work, now())), (true, Some("This machine".into())));
+ // Host signed out too: Work
+ let r = report(EngineId::Claude, true, EngineStatus::SignedOut);
+ assert_eq!(uses(readiness(&r, &profiles, &work, now())), (true, Some("Work".into())));
+ }
+
+ #[test]
+ fn disabled_profiles_and_other_engines_accounts_do_not_count() {
+ let r = report(EngineId::Claude, true, EngineStatus::SignedOut);
+ let mut profiles = oleks();
+ profiles[1].enabled = false;
+ assert_eq!(readiness(&r, &profiles, &signed_in(&["p_personal"]), now()), (false, None));
+ // An API-key account runs on the Anthropic API, not the Claude CLI, and needs its key
+ let profiles = vec![
+ profile("prf_system_claude", "This machine", "system", 0, true),
+ profile("p_key", "Team key", "api_key", 10, false),
+ ];
+ assert_eq!(readiness(&r, &profiles, &Availability::default(), now()), (false, None));
+ let api = report(EngineId::AnthropicApi, true, EngineStatus::SignedOut);
+ assert_eq!(readiness(&api, &profiles, &Availability::default(), now()), (false, None));
+ let keyed = Availability {
+ with_key: HashSet::from(["p_key".to_string()]),
+ ..Default::default()
+ };
+ assert_eq!(uses(readiness(&api, &profiles, &keyed, now())), (true, Some("Team key".into())));
+ assert_eq!(readiness(&r, &profiles, &keyed, now()), (false, None));
+ }
+
+ #[test]
+ fn host_ready_uses_this_machine_even_when_its_profile_is_off() {
+ let r = report(EngineId::Claude, true, EngineStatus::Ready);
+ let mut profiles = oleks();
+ profiles[0].enabled = false;
+ assert_eq!(
+ uses(readiness(&r, &profiles, &Availability::default(), now())),
+ (true, Some("This machine".into()))
+ );
+ // Ollama has no accounts: ready from its own check alone
+ let o = report(EngineId::Ollama, true, EngineStatus::Ready);
+ assert_eq!(readiness(&o, &profiles, &Availability::default(), now()), (true, None));
+ }
+}
diff --git a/tests/engine_model_test.rs b/tests/engine_model_test.rs
index dc65567b..e502fd6d 100644
--- a/tests/engine_model_test.rs
+++ b/tests/engine_model_test.rs
@@ -187,6 +187,10 @@ async fn laya_picks_model_tier_pins_and_engine_switches() {
by_id(&v, id)["models"].as_array().unwrap().iter().map(|m| (m["id"].as_str().unwrap().to_string(), m["tier"].clone())).collect()
};
assert_eq!(by_id(&v, "claude")["status"], "ready");
+ // Ready on its own login, so a kwant uses This machine; keyless APIs are neither
+ assert_eq!(by_id(&v, "claude")["ready"], true);
+ assert_eq!(by_id(&v, "claude")["uses"], json!({"profile_id": "prf_system_claude", "label": "This machine"}));
+ assert_eq!((by_id(&v, "anthropic_api")["ready"].clone(), by_id(&v, "anthropic_api")["uses"].clone()), (json!(false), Value::Null));
assert!(tiers("claude").contains(&("haiku".into(), json!("fast"))));
assert!(tiers("claude").contains(&("opus".into(), json!("deep"))));
assert_eq!(tiers("codex"), [("gpt-6.1-sol".into(), json!("balanced")), ("gpt-6-astra".into(), json!("deep")), ("gpt-6-luna".into(), json!("fast"))]);
@@ -200,6 +204,9 @@ async fn laya_picks_model_tier_pins_and_engine_switches() {
assert_eq!(v["engines"].as_array().unwrap().len(), 7, "the full GET /api/engines shape");
let codex = by_id(&v, "codex");
assert_eq!((codex["status"].clone(), codex["enabled"].clone(), codex["models"].clone()), (json!("disabled"), json!(false), json!([])));
+ assert_eq!((codex["ready"].clone(), codex["uses"].clone()), (json!(false), Value::Null));
+ let (_, listed) = call(&app, "GET", "/api/engines", None).await;
+ assert_eq!(by_id(&listed, "claude")["ready"], true, "GET carries ready/uses too");
let (s, _) = call(&app, "PUT", "/api/engines/grok", Some(json!({"enabled": false}))).await;
assert_eq!(s, StatusCode::OK);
assert_eq!(state.db.get_setting("engines_disabled").await.unwrap().as_deref(), Some(r#"["codex","grok"]"#));