Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Model failover: one priority order across engines, session-limit detection (#239)
Oleksandr Ivanchenkoe6fe2e321e1e
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex c85e52ed..a8ccd04d 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -1355,7 +1355,10 @@ impl Driver for CliDriver {} else {match ClaudeResult::parse(&stdout) {Some(result) => {- if result.is_error && result.num_turns <= 1 {+ // A result that is nothing but a usage-limit line is a refusal, whether or not+ // the CLI flagged it as an error: it is never the reply+ let bare_limit = crate::profiles::classify::is_limit_line(&result.result);+ if (result.is_error && result.num_turns <= 1) || bare_limit {if let Some(failure) = refusal(&result.result) {return Ok(TurnOutput::refused(failure));}diff --git a/src/drivers/engines.rs b/src/drivers/engines.rsindex 9581515b..2c9ea43f 100644--- a/src/drivers/engines.rs+++ b/src/drivers/engines.rs@@ -778,6 +778,23 @@ impl EngineRegistry {report}+ /// When a turn's usage-limit refusal says this engine is back, while that is still ahead. Such+ /// a mark is a limit, not a setup problem: the engine is installed and signed in, just out of+ /// usage, so it still counts as an account that exists and its reset can be waited for.+ pub fn quota_until(&self, id: EngineId) -> Option<DateTime<Utc>> {+ if !self.is_enabled(id) {+ return None;+ }+ let now = Utc::now();+ self.marks+ .read()+ .unwrap()+ .get(&id)+ .filter(|m| m.status == EngineStatus::Error)+ .and_then(|m| m.until)+ .filter(|u| *u > now)+ }+pub fn is_enabled(&self, id: EngineId) -> bool {!self.disabled.read().unwrap().contains(&id)}@@ -930,6 +947,27 @@ pub fn choose_model(models: &[EngineModel], pinned: Option<&str>, tier: Tier) ->of_tier(tier).or(default).map(ModelChoice::of)}+/// [`choose_model`] for a turn that moved here from another engine: the model of the same+/// tier, else of the nearest tier (Deep → Balanced → Fast), else the engine's default.+pub fn choose_model_near(models: &[EngineModel], pinned: Option<&str>, tier: Tier) -> Option<ModelChoice> {+ let rank = |t: Tier| match t {+ Tier::Fast => 0i32,+ Tier::Balanced => 1,+ Tier::Deep => 2,+ };+ if pinned.map(str::trim).is_none_or(str::is_empty) && !models.iter().any(|m| m.tier == Some(tier)) {+ let nearest = models+ .iter()+ .filter_map(|m| m.tier.map(|t| ((rank(t) - rank(tier)).abs(), m)))+ .min_by_key(|(d, _)| *d)+ .map(|(_, m)| m);+ if let Some(m) = nearest {+ return Some(ModelChoice::of(m));+ }+ }+ choose_model(models, pinned, tier)+}+/// The models a turn on `id` can pick from: the last check's, or for Claude Code (whose aliases/// never change) its aliases even when the host's own login is out and an account runs it.pub fn known_models(engines: &EngineRegistry, id: EngineId) -> Vec<EngineModel> {@@ -1134,6 +1172,12 @@ mod tests {let r = reg.report(EngineId::Codex);assert_eq!(r.status, EngineStatus::Error);assert!(r.detail.unwrap().starts_with("Quota exceeded until"));+ // It is a limit with a known end, which a signed-out mark or a lapsed one is not+ assert_eq!(reg.quota_until(EngineId::Codex), future.retry_at);+ reg.record_failure(EngineId::Codex, &past);+ assert_eq!(reg.quota_until(EngineId::Codex), None);+ reg.record_failure(EngineId::Codex, &auth);+ assert_eq!(reg.quota_until(EngineId::Codex), None);let transient = ProviderFailure { class: FailClass::Transient, retry_at: None, detail: String::new() };reg.record_failure(EngineId::Claude, &transient);@@ -1252,6 +1296,25 @@ mod tests {assert_eq!(choose_model(&unknown, None, Tier::Deep).unwrap().run_id(), None);}+ #[test]+ fn a_turn_moved_from_another_engine_gets_the_nearest_tier() {+ let near = |models: &[EngineModel], tier| choose_model_near(models, None, tier).map(|c| c.id);+ let codex = vec![+ EngineModel::new("gpt-6.1-pro", "pro", true, Some(Tier::Deep)),+ EngineModel::new("gpt-6.1-mini", "mini", false, Some(Tier::Fast)),+ ];+ assert_eq!(near(&codex, Tier::Deep).as_deref(), Some("gpt-6.1-pro"));+ assert_eq!(near(&codex, Tier::Fast).as_deref(), Some("gpt-6.1-mini"));+ // Sonnet's tier is missing: the nearest listed, the better one first+ assert_eq!(near(&codex, Tier::Balanced).as_deref(), Some("gpt-6.1-pro"));+ let only_fast = vec![EngineModel::new("grok-fast", "fast", true, Some(Tier::Fast))];+ assert_eq!(near(&only_fast, Tier::Deep).as_deref(), Some("grok-fast"));+ // Untiered models: the engine's default, and nothing listed: none+ let grok = vec![EngineModel::new("grok-4.6", "grok-4.6", true, None)];+ assert_eq!(near(&grok, Tier::Deep).as_deref(), Some("grok-4.6"));+ assert_eq!(near(&[], Tier::Deep), None);+ }+#[test]fn pinned_models_run_as_is_or_as_the_same_tier() {let claude = claude_cli_models();diff --git a/src/drivers/events.rs b/src/drivers/events.rsindex e8ef06db..da3d3bfd 100644--- a/src/drivers/events.rs+++ b/src/drivers/events.rs@@ -143,8 +143,9 @@ pub enum RuntimeEvent {tag: TurnTag,event: Box<RuntimeEvent>,},- /// A turn moved to another profile of the same engine because the first ran out of quota- /// or was signed out. `class` is "quota" or "auth".+ /// A turn moved to another account because the first ran out of quota or was signed out,+ /// on the same engine or another one (`from_engine` ≠ `to_engine`). `class` is "quota" or+ /// "auth". Sent once per chat per outage. Engines are "claude", "codex", "grok" or "custom".#[serde(rename = "profile_switched", alias = "ProfileSwitched")]ProfileSwitched {kwant_id: String,@@ -155,6 +156,15 @@ pub enum RuntimeEvent {class: String,#[serde(default, skip_serializing_if = "Option::is_none")]retry_at: Option<chrono::DateTime<chrono::Utc>>,+ #[serde(default)]+ from_engine: String,+ #[serde(default)]+ to_engine: String,+ /// The model the turn was on, when it had started one; the one it moved to.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ from_model: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ to_model: Option<String>,},#[serde(rename = "discussion_started", alias = "DiscussionStarted")]DiscussionStarted {diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex 56b45760..7f51c1fb 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -590,16 +590,20 @@ pub async fn detect_available_models(for (family, api_desc, cli_desc) in families {let key = db.get_setting(family.key_setting()).await.ok().flatten();let route = engines::system_route(engines, family.as_str(), key, find_cli_binary);+ let (cli, api) = EngineId::of_family(family);let engine = match &route {Ok(SystemRoute::Api { engine, .. }) | Ok(SystemRoute::Cli { engine, .. }) if !host_off.contains(&family) => {Some(*engine)}+ // Out of usage until a known time: still on offer, the failover plan waits for the reset+ _ if !host_off.contains(&family) && (engines.quota_until(cli).is_some() || engines.quota_until(api).is_some()) => {+ Some(if engines.quota_until(api).is_some() { api } else { cli })+ }_ => None,};if engine.is_none() && !profile_engines.contains(&family) {continue;}- let (cli, api) = EngineId::of_family(family);let report = engines.report(engine.unwrap_or(cli));let model = report.default_model().map(|m| m.label.clone());let fallback_name = match family {diff --git a/src/profiles/classify.rs b/src/profiles/classify.rsindex 90c6e20e..0b523235 100644--- a/src/profiles/classify.rs+++ b/src/profiles/classify.rs@@ -45,7 +45,13 @@ pub const DEFAULT_QUOTA_COOLDOWN_MINS: i64 = 60;const QUOTA_PATTERNS: &[&str] = &["usage limit","hit your limit",+ "hit your session limit",+ "hit your weekly limit",+ "hit your opus limit",+ "session limit",+ "weekly limit","reached your limit",+ "limit reached","out of credits","insufficient_quota","exceeded your current quota",@@ -115,13 +121,157 @@ pub fn classify(/// "resets in 45m", else now plus the default cooldown. Never more than 7 days out.fn quota_reset(text: &str, lower: &str, now: DateTime<Utc>) -> DateTime<Utc> {let fallback = now + Duration::minutes(DEFAULT_QUOTA_COOLDOWN_MINS);- let at = epoch_after_pipe(text, now).or_else(|| relative_reset(lower).map(|d| now + d));+ let at = epoch_after_pipe(text, now)+ .or_else(|| relative_reset(lower).map(|d| now + d))+ .or_else(|| clock_reset(text, now, &crate::zombie::settings::host_tz().unwrap_or_else(|| "UTC".into())));match at {Some(t) if t > now && t <= now + Duration::days(7) => t,_ => fallback,}}+/// Wordings a CLI uses when it has run out of usage, matched against a whole reply to tell a+/// limit line from an answer. Narrower than [`QUOTA_PATTERNS`]: a bare "quota" is a word a real+/// answer can contain.+const LIMIT_LINE_PATTERNS: &[&str] = &[+ "hit your limit",+ "hit your session limit",+ "hit your weekly limit",+ "hit your opus limit",+ "session limit",+ "weekly limit",+ "usage limit",+ "reached your limit",+ "limit reached",+];++/// Longest reply still treated as "nothing but a limit line".+const LIMIT_LINE_MAX_CHARS: usize = 300;++/// Whether `text` is nothing but a provider's usage-limit message ("You've hit your session+/// limit · resets 3am (Europe/Berlin)"): short, one limit wording, no second paragraph. Such a+/// text is never a reply and never a "While you were away" summary.+pub fn is_limit_line(text: &str) -> bool {+ let t = text.trim();+ if t.is_empty() || t.chars().count() > LIMIT_LINE_MAX_CHARS || t.lines().filter(|l| !l.trim().is_empty()).count() > 2 {+ return false;+ }+ let lower = t.to_lowercase();+ LIMIT_LINE_PATTERNS.iter().any(|p| lower.contains(p))+}++/// "resets 3am (Europe/Berlin)", "resets 5pm", "resets Mon 3:30pm (UTC)", "resets Nov 4, 9am",+/// "reset at 17:00": the next time the wall clock reads that, in the named IANA zone (else+/// `default_tz`, the server's own). `None` when the time or the zone doesn't parse, so the caller+/// falls back to the default cooldown.+fn clock_reset(text: &str, now: DateTime<Utc>, default_tz: &str) -> Option<DateTime<Utc>> {+ let lower = text.to_lowercase();+ let start = ["resets at ", "reset at ", "resets ", "reset "]+ .iter()+ .find_map(|k| lower.find(k).map(|i| i + k.len()))?;+ let tail = &text[start..];+ let zone = tail+ .split_once('(')+ .and_then(|(_, z)| z.split_once(')'))+ .map(|(z, _)| z.trim())+ .filter(|z| !z.is_empty() && z.len() <= 64 && z.chars().all(|c| c.is_ascii_alphanumeric() || "/_+-".contains(c)))+ .unwrap_or(default_tz);+ let head = tail.split('(').next().unwrap_or(tail);+ let mut weekday: Option<chrono::Weekday> = None;+ let mut month: Option<u32> = None;+ let mut day: Option<u32> = None;+ let mut time: Option<chrono::NaiveTime> = None;+ for word in head+ .split(|c: char| c.is_whitespace() || c == ',' || c == '·' || c == '.')+ .filter(|w| !w.is_empty())+ {+ let w = word.to_ascii_lowercase();+ if let Some(t) = parse_clock(&w) {+ time = Some(t);+ break;+ }+ if month.is_some() && day.is_none() {+ day = w.trim_end_matches(|c: char| c.is_ascii_alphabetic()).parse::<u32>().ok();+ if day.is_some() {+ continue;+ }+ }+ if let Some(m) = w.get(..3).and_then(month_number).filter(|_| w.chars().all(|c| c.is_ascii_alphabetic())) {+ month = Some(m);+ continue;+ }+ if weekday.is_none() {+ weekday = w.get(..3).and_then(|d| match d {+ "mon" => Some(chrono::Weekday::Mon),+ "tue" => Some(chrono::Weekday::Tue),+ "wed" => Some(chrono::Weekday::Wed),+ "thu" => Some(chrono::Weekday::Thu),+ "fri" => Some(chrono::Weekday::Fri),+ "sat" => Some(chrono::Weekday::Sat),+ "sun" => Some(chrono::Weekday::Sun),+ _ => None,+ });+ }+ }+ let time = time?;+ let today = crate::routines::local_date(zone, now).ok()??;+ if let (Some(m), Some(d)) = (month, day) {+ use chrono::Datelike;+ for year in [today.year(), today.year() + 1] {+ let date = chrono::NaiveDate::from_ymd_opt(year, m, d)?;+ if let Some(at) = crate::routines::local_instant(zone, date, time).ok()?.filter(|at| *at > now) {+ return Some(at);+ }+ }+ return None;+ }+ let mut date = today;+ // Today at that time, else the next day (or the named weekday) when it has already passed.+ for _ in 0..8 {+ let day_ok = weekday.is_none_or(|w| chrono::Datelike::weekday(&date) == w);+ if day_ok {+ if let Some(at) = crate::routines::local_instant(zone, date, time).ok()?.filter(|at| *at > now) {+ return Some(at);+ }+ }+ date = date.succ_opt()?;+ }+ None+}++fn month_number(m: &str) -> Option<u32> {+ ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]+ .iter()+ .position(|n| *n == m)+ .map(|i| i as u32 + 1)+}++/// "3am", "3:30pm", "12am", "17:00" (already lower-cased) as a time of day.+fn parse_clock(word: &str) -> Option<chrono::NaiveTime> {+ let (body, pm) = if let Some(b) = word.strip_suffix("am") {+ (b, Some(false))+ } else if let Some(b) = word.strip_suffix("pm") {+ (b, Some(true))+ } else {+ (word, None)+ };+ let (h, m) = match body.split_once(':') {+ Some((h, m)) => (h.parse::<u32>().ok()?, m.parse::<u32>().ok()?),+ None if pm.is_some() => (body.parse::<u32>().ok()?, 0),+ None => return None,+ };+ let h = match pm {+ Some(p) => {+ if !(1..=12).contains(&h) {+ return None;+ }+ (h % 12) + if p { 12 } else { 0 }+ }+ None => h,+ };+ chrono::NaiveTime::from_hms_opt(h, m, 0)+}+fn epoch_after_pipe(text: &str, now: DateTime<Utc>) -> Option<DateTime<Utc>> {let (_, rest) = text.split_once('|')?;let digits: String = rest@@ -468,6 +618,61 @@ mod tests {assert_eq!(classify(Some(402), "", now()).unwrap().0, FailClass::Quota);}+ #[test]+ fn session_and_weekly_limit_lines_are_quota() {+ for text in [+ "You've hit your session limit · resets 3am (Europe/Berlin)",+ "You've hit your weekly limit · resets Mon 3am (Europe/Berlin)",+ "Session limit reached",+ "You've hit your Opus limit",+ ] {+ let (class, at) = classify(None, text, now()).unwrap();+ assert_eq!(class, FailClass::Quota, "{text}");+ assert!(at.unwrap() > now(), "{text}");+ assert!(is_limit_line(text), "{text}");+ }+ }++ #[test]+ fn clock_resets_use_the_named_zone() {+ // 12:00 UTC on 16 Oct is 14:00 in Berlin (CEST), so 3am there is 01:00 UTC the next day.+ let (_, at) = classify(None, "You've hit your session limit · resets 3am (Europe/Berlin)", now()).unwrap();+ assert_eq!(at.unwrap(), Utc.with_ymd_and_hms(2026, 10, 17, 1, 0, 0).unwrap());+ // No zone: the server's own (UTC here), and a time still ahead today stays today.+ let at = clock_reset("You've hit your limit · resets 5pm", now(), "UTC");+ assert_eq!(at.unwrap(), Utc.with_ymd_and_hms(2026, 10, 16, 17, 0, 0).unwrap());+ let at = clock_reset("You've hit your limit · resets 5pm", now(), "Europe/Berlin");+ assert_eq!(at.unwrap(), Utc.with_ymd_and_hms(2026, 10, 16, 15, 0, 0).unwrap());+ let (_, at) = classify(None, "limit reached · resets Oct 20, 9am (UTC)", now()).unwrap();+ assert_eq!(at.unwrap(), Utc.with_ymd_and_hms(2026, 10, 20, 9, 0, 0).unwrap());+ // Further than 7 days out is not believed+ let (_, at) = classify(None, "limit reached · resets Nov 4, 9am (UTC)", now()).unwrap();+ assert_eq!(at.unwrap(), now() + Duration::minutes(DEFAULT_QUOTA_COOLDOWN_MINS));+ // A time already past today rolls to tomorrow.+ let (_, at) = classify(None, "You've hit your limit · resets 9am (UTC)", now()).unwrap();+ assert_eq!(at.unwrap(), Utc.with_ymd_and_hms(2026, 10, 17, 9, 0, 0).unwrap());+ let (_, at) = classify(None, "limit reached, resets 3:30pm (America/New_York)", now()).unwrap();+ assert_eq!(at.unwrap(), Utc.with_ymd_and_hms(2026, 10, 16, 19, 30, 0).unwrap());+ // A named weekday: Monday 19 Oct.+ let (_, at) = classify(None, "You've hit your weekly limit · resets Mon 3am (UTC)", now()).unwrap();+ assert_eq!(at.unwrap(), Utc.with_ymd_and_hms(2026, 10, 19, 3, 0, 0).unwrap());+ // An unknown zone or a time that doesn't parse falls back to the default cooldown.+ let (_, at) = classify(None, "hit your session limit · resets 3am (Mars/Base)", now()).unwrap();+ assert_eq!(at.unwrap(), now() + Duration::minutes(DEFAULT_QUOTA_COOLDOWN_MINS));+ let (_, at) = classify(None, "hit your session limit · resets soon", now()).unwrap();+ assert_eq!(at.unwrap(), now() + Duration::minutes(DEFAULT_QUOTA_COOLDOWN_MINS));+ }++ #[test]+ fn only_a_bare_limit_message_is_a_limit_line() {+ assert!(is_limit_line(" You've hit your session limit · resets 3am (Europe/Berlin)\n"));+ assert!(!is_limit_line("Here is the summary of the weekly limit work."+ .repeat(10).as_str()));+ assert!(!is_limit_line("Done. The quota table now has an index."));+ assert!(!is_limit_line(""));+ assert!(!is_limit_line("I fixed it.\n\nNote: the session limit message no longer shows.\n\nAlso more text."));+ }+#[test]fn quota_reset_times() {let (_, at) = classify(None, "Claude AI usage limit reached|1792162800", now()).unwrap();diff --git a/src/profiles/mod.rs b/src/profiles/mod.rsindex 99241fbf..ea28c6aa 100644--- a/src/profiles/mod.rs+++ b/src/profiles/mod.rs@@ -13,8 +13,9 @@ use std::path::{Path, PathBuf};pub use classify::{classify, FailClass, ProviderFailure};pub use status::{ProfileManager, ProfileStatus};-/// Most profiles one turn may try.-pub const MAX_ATTEMPTS: usize = 3;+/// Most accounts one turn may try, across every engine of the space (Claude, Claude API key,+/// Codex, Grok, Custom API, plus a second account on a couple of them).+pub const MAX_ATTEMPTS: usize = 6;#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub enum Engine {@@ -371,7 +372,9 @@ impl Availability {|| self.signed_in.contains(&p.id))}- fn usable(&self, p: &LlmProfile, now: DateTime<Utc>) -> bool {+ /// Whether `p` could take a turn now: not out of usage, not an API key without its key,+ /// not known to be signed out.+ pub fn usable(&self, p: &LlmProfile, now: DateTime<Utc>) -> bool {let limited = self.states.get(&p.id)@@ -438,6 +441,99 @@ pub fn failover_order(order}+/// What a turn on one engine may try across the whole space, and why it started where it did.+#[derive(Debug, Default, Clone, PartialEq)]+pub struct GlobalPlan {+ /// Accounts to try in order; `None` is the host's own login or Settings key when the bot's+ /// engine has no account of its own.+ pub attempts: Vec<Option<LlmProfile>>,+ /// The bot's own preferred account when it was left out because it is known to be out of+ /// usage, so the turn can say once why it runs elsewhere.+ pub skipped: Option<LlmProfile>,+ /// When the skipped account's limit resets (`None`: it is skipped for another reason).+ pub skipped_until: Option<DateTime<Utc>>,+ /// Set when every account that could take a turn is known to be out of usage: the earliest+ /// reset. The turn then parks instead of trying any of them.+ pub all_out_until: Option<DateTime<Utc>>,+}++/// What the caller knows that the profile list doesn't, for [`global_order`].+pub struct OrderRules<'a> {+ /// Whether the host's own login or key may serve a bot whose engine has no account of its own.+ pub host_head: bool,+ /// Whether an account's engine may run it at all (engine switched off, host login unusable).+ pub eligible: &'a dyn Fn(&LlmProfile) -> bool,+}++/// The accounts a turn on `engine` tries: its own preferred account first (`bound`, else the+/// engine's default), then, with failover on, every other usable account of the space across+/// all engines in ONE order, by `priority` (ties: oldest first). Accounts+/// known to be out of usage are skipped up front, the bot's own too, unless nothing else is+/// usable. With failover off the bot stays pinned to its own account.+pub fn global_order(+ profiles: &[LlmProfile],+ engine: Engine,+ bound: Option<&str>,+ failover: bool,+ avail: &Availability,+ now: DateTime<Utc>,+ rules: &OrderRules,+) -> GlobalPlan {+ let OrderRules { host_head, eligible } = rules;+ let host_head = *host_head;+ let elig: Vec<LlmProfile> = profiles.iter().filter(|p| p.enabled && eligible(p)).cloned().collect();+ // The Accounts list order (`priority`) is the one truth: `is_default` does not jump the queue+ // here. A bot explicitly bound to an enabled account of its engine starts on that account;+ // every other bot starts at the top of its engine's accounts in the list.+ let mut mine: Vec<&LlmProfile> = elig.iter().filter(|p| p.engine == engine.as_str()).collect();+ mine.sort_by(|a, b| (a.priority, a.created_at, &a.id).cmp(&(b.priority, b.created_at, &b.id)));+ if let Some(i) = bound.and_then(|id| mine.iter().position(|p| p.id == id)) {+ let p = mine.remove(i);+ mine.insert(0, p);+ }+ let first = mine.first().map(|p| (*p).clone());+ if !failover {+ let attempts = match first {+ Some(p) => vec![Some(p)],+ None if host_head => vec![None],+ None => Vec::new(),+ };+ return GlobalPlan { attempts, ..Default::default() };+ }+ let mut rest: Vec<&LlmProfile> = elig+ .iter()+ .filter(|p| first.as_ref().is_none_or(|f| f.id != p.id) && avail.usable(p, now))+ .collect();+ rest.sort_by(|a, b| (a.priority, a.created_at, &a.id).cmp(&(b.priority, b.created_at, &b.id)));+ let mut plan = GlobalPlan::default();+ match first {+ Some(f) if avail.usable(&f, now) || rest.is_empty() => plan.attempts.push(Some(f)),+ Some(f) => {+ plan.skipped_until = avail.states.get(&f.id).and_then(|s| s.limited_until).filter(|t| *t > now);+ plan.skipped = Some(f);+ }+ None if host_head => plan.attempts.push(None),+ None => {}+ }+ plan.attempts.extend(rest.into_iter().map(|p| Some(p.clone())));+ plan.attempts.truncate(MAX_ATTEMPTS);+ // Every account that could work, out of usage: nothing to try until the earliest reset+ if plan.attempts.iter().all(Option::is_some) {+ let limited_until = |p: &LlmProfile| {+ avail.states.get(&p.id).and_then(|s| s.limited_until).filter(|t| *t > now)+ };+ let live: Vec<&LlmProfile> = elig+ .iter()+ .filter(|p| !avail.signed_out.contains(&p.id) && !(p.kind == "api_key" && !avail.with_key.contains(&p.id)))+ .collect();+ if !live.is_empty() && live.iter().all(|p| limited_until(p).is_some()) {+ plan.all_out_until = live.iter().filter_map(|p| limited_until(p)).min();+ plan.attempts.clear();+ }+ }+ plan+}+/// Validates a profile name: 1 to 40 printable characters, trimmed.pub fn clean_name(raw: &str) -> Result<String, String> {let name = raw.trim();@@ -694,7 +790,7 @@ mod tests {#[test]fn order_is_capped() {- let profiles: Vec<_> = (0..6)+ let profiles: Vec<_> = (0..9).map(|i| profile(&format!("p{i}"), "codex", "cli_home", i, i == 0)).collect();assert_eq!(@@ -711,6 +807,140 @@ mod tests {);}+ fn limited(ids: &[(&str, i64)]) -> Availability {+ Availability {+ states: ids+ .iter()+ .map(|(id, hours)| {+ (+ id.to_string(),+ LlmProfileState {+ profile_id: id.to_string(),+ limited_until: Some(now() + chrono::Duration::hours(*hours)),+ last_error: Some("quota".into()),+ },+ )+ })+ .collect(),+ ..Default::default()+ }+ }++ fn all_on(_: &LlmProfile) -> bool {+ true+ }++ fn plan_ids(p: &GlobalPlan) -> Vec<String> {+ p.attempts.iter().map(|a| a.as_ref().map_or("host".into(), |p| p.id.clone())).collect()+ }++ /// Claude (default, priority 10), Codex (20), Custom/Maestro (5), Grok (30), one Claude key (40).+ fn space() -> Vec<LlmProfile> {+ vec![+ profile("claude", "claude", "cli_home", 10, true),+ profile("codex", "codex", "cli_home", 20, true),+ profile("maestro", "custom", "custom_api", 5, true),+ profile("grok", "grok", "cli_home", 30, true),+ profile("ckey", "claude", "api_key", 40, false),+ ]+ }++ fn global(engine: Engine, failover: bool, avail: &Availability) -> GlobalPlan {+ let mut avail_keys = Availability { with_key: HashSet::from(["ckey".to_string()]), ..Default::default() };+ avail_keys.states = avail.states.clone();+ avail_keys.signed_out = avail.signed_out.clone();+ global_order(&space(), engine, None, failover, &avail_keys, now(), &OrderRules { host_head: false, eligible: &all_on })+ }++ #[test]+ fn failover_crosses_engines_by_one_priority_order() {+ // Nothing limited: the bot's own account first, then everything else by priority+ let p = global(Engine::Claude, true, &Availability::default());+ assert_eq!(plan_ids(&p), ["claude", "maestro", "codex", "grok", "ckey"]);+ assert_eq!((p.skipped, p.all_out_until), (None, None));+ // A Codex bot starts on Codex, then Maestro (5) before Claude (10)+ assert_eq!(plan_ids(&global(Engine::Codex, true, &Availability::default())), ["codex", "maestro", "claude", "grok", "ckey"]);+ }++ #[test]+ fn the_list_order_decides_and_is_default_does_not_jump_the_queue() {+ let mut profiles = space();+ // A second Claude account sits above the default one in the Accounts list+ profiles.push(profile("claude2", "claude", "cli_home", 1, false));+ let plan = |bound: Option<&str>| {+ let p = global_order(&profiles, Engine::Claude, bound, true, &Availability::default(), now(), &OrderRules { host_head: false, eligible: &all_on });+ plan_ids(&p)+ };+ // Not bound: the top of the list for its engine, although `claude` is the default+ assert_eq!(plan(None), ["claude2", "maestro", "claude", "codex", "grok"]);+ // Bound to an account: that account first, then the list in order+ assert_eq!(plan(Some("claude")), ["claude", "claude2", "maestro", "codex", "grok"]);+ // A binding to an account of another engine, or a gone one, is not a binding+ assert_eq!(plan(Some("codex"))[0], "claude2");+ assert_eq!(plan(Some("gone"))[0], "claude2");+ }++ #[test]+ fn a_limited_account_is_skipped_up_front_and_named() {+ let p = global(Engine::Claude, true, &limited(&[("claude", 3)]));+ assert_eq!(plan_ids(&p), ["maestro", "codex", "grok", "ckey"]);+ assert_eq!(p.skipped_until, Some(now() + chrono::Duration::hours(3)));+ assert_eq!(p.skipped.map(|s| s.id), Some("claude".into()));+ // A limit that has already passed doesn't count: back on the preferred account+ let mut past = limited(&[("claude", 3)]);+ past.states.get_mut("claude").unwrap().limited_until = Some(now() - chrono::Duration::minutes(1));+ let p = global(Engine::Claude, true, &past);+ assert_eq!(plan_ids(&p)[0], "claude");+ assert!(p.skipped.is_none());+ }++ #[test]+ fn signed_out_keyless_and_ineligible_accounts_are_never_tried() {+ let mut avail = limited(&[]);+ avail.signed_out.insert("codex".into());+ let no_grok = |p: &LlmProfile| p.engine != "grok";+ let mut with_key = Availability { with_key: HashSet::new(), ..Default::default() };+ with_key.signed_out = avail.signed_out.clone();+ let p = global_order(&space(), Engine::Claude, None, true, &with_key, now(), &OrderRules { host_head: false, eligible: &no_grok });+ // codex signed out, grok switched off, the Claude key has no key+ assert_eq!(plan_ids(&p), ["claude", "maestro"]);+ }++ #[test]+ fn failover_off_pins_the_bot_to_its_own_account() {+ let p = global(Engine::Claude, false, &limited(&[("claude", 3)]));+ assert_eq!(plan_ids(&p), ["claude"]);+ assert!(p.skipped.is_none() && p.all_out_until.is_none());+ }++ #[test]+ fn everything_out_gives_the_earliest_reset_and_no_attempts() {+ let p = global(Engine::Claude, true, &limited(&[("claude", 3), ("codex", 5), ("maestro", 4), ("grok", 9), ("ckey", 6)]));+ assert!(p.attempts.is_empty());+ assert_eq!(p.all_out_until, Some(now() + chrono::Duration::hours(3)));+ // One account still usable: not all out+ let p = global(Engine::Claude, true, &limited(&[("claude", 3), ("codex", 5), ("maestro", 4), ("ckey", 6)]));+ assert_eq!(plan_ids(&p), ["grok"]);+ assert!(p.all_out_until.is_none());+ }++ #[test]+ fn a_bot_whose_engine_has_no_account_starts_on_the_host() {+ let profiles = vec![profile("codex", "codex", "cli_home", 20, true)];+ let rules = OrderRules { host_head: true, eligible: &all_on };+ let p = global_order(&profiles, Engine::Claude, None, true, &Availability::default(), now(), &rules);+ assert_eq!(plan_ids(&p), ["host", "codex"]);+ let rules = OrderRules { host_head: false, eligible: &all_on };+ let p = global_order(&profiles, Engine::Claude, None, true, &Availability::default(), now(), &rules);+ assert_eq!(plan_ids(&p), ["codex"]);+ }++ #[test]+ fn the_cap_covers_every_engine() {+ assert_eq!(global(Engine::Claude, true, &Availability::default()).attempts.len(), 5);+ const { assert!(MAX_ATTEMPTS >= 5) };+ }+#[test]fn user_home_validation() {let dir = tempfile::tempdir().unwrap();diff --git a/src/server/away.rs b/src/server/away.rsindex 5d7a1801..08dad4c3 100644--- a/src/server/away.rs+++ b/src/server/away.rs@@ -209,7 +209,13 @@ fn item(row: AwayRow) -> Value {(clip_title(&row.title), summary)}_ => {- let summary = row.body.as_deref().map(summarize).filter(|s| !s.is_empty());+ // A usage-limit line is not a summary of anything (also when an older run saved one)+ let summary = row+ .body+ .as_deref()+ .filter(|b| !crate::profiles::classify::is_limit_line(b))+ .map(summarize)+ .filter(|s| !s.is_empty());(clip_title(&row.title), summary.unwrap_or_else(|| fallback_summary(&row).into()))}};@@ -411,6 +417,28 @@ mod tests {assert_eq!(url["arguments"]["path"], "https://bob:[redacted]@host/x");}+ #[test]+ fn a_usage_limit_line_is_never_the_summary() {+ let row = |body: &str| AwayRow {+ kind: "task".into(),+ id: "t1".into(),+ kwant_id: "k1".into(),+ kwant_name: Some("Architect".into()),+ title: "Plan the release".into(),+ status: "completed".into(),+ body: Some(body.into()),+ at: chrono::Utc::now(),+ thread_id: None,+ channel_id: None,+ direct_kwant_id: None,+ choices: None,+ };+ let limit = item(row("You've hit your session limit · resets 3am (Europe/Berlin)"));+ assert_eq!(limit["summary"], "Finished");+ let real = item(row("Plan is ready: three steps."));+ assert_eq!(real["summary"], "Plan is ready: three steps.");+ }+#[test]fn summaries_mask_url_passwords_and_bearer_tokens() {let s = summarize("failed: postgres://bob:hunter2@db:5432/x with Authorization: Bearer abc123");diff --git a/src/server/profile_turn.rs b/src/server/profile_turn.rsindex f2e9d9e5..cea1aacb 100644--- a/src/server/profile_turn.rs+++ b/src/server/profile_turn.rs@@ -9,8 +9,8 @@ use crate::drivers::{find_cli_binary, resolve_driver_for_model, ApiDriver, CliDruse std::collections::HashSet;use std::sync::atomic::{AtomicBool, Ordering};use crate::profiles::{- failover_order, preference_order, Availability, Engine, FailClass, ProfileStatus,- ProviderFailure, SignInBar,+ failover_order, global_order, preference_order, Availability, Engine, FailClass, GlobalPlan,+ OrderRules, ProfileStatus, ProviderFailure, SignInBar,};/// The space's profiles and what decides whether each can take a turn now, from the db and the@@ -62,6 +62,80 @@ pub async fn plan(state: &AppState, engine: Option<Engine>, kwant_id: &str) -> V.collect()}+/// What a turn of a bot on `engine` may try across all the space's accounts, in order (see+/// [`crate::profiles::global_order`]). A bot on a model without accounts (Ollama) just runs.+pub async fn plan_global(state: &AppState, engine: Option<Engine>, kwant_id: &str) -> GlobalPlan {+ let Some(engine) = engine else {+ return GlobalPlan { attempts: vec![None], ..Default::default() };+ };+ let Ok(Some(space)) = state.db.space_of_kwant(kwant_id).await else {+ return GlobalPlan { attempts: vec![None], ..Default::default() };+ };+ let host_off = host_off(state, &space).await.contains(&engine);+ let (Some((profiles, mut avail)), Ok(binding)) =+ (accounts(state, &space).await, state.db.get_kwant_binding(kwant_id).await)+ else {+ return GlobalPlan { attempts: if host_off { Vec::new() } else { vec![None] }, ..Default::default() };+ };+ let (bound, failover) = binding.unwrap_or((None, true));+ let reports = state.engines.snapshot();+ // Another engine's own login (This machine) only counts when that CLI is ready here+ let host_ready = |family: Engine| {+ let (cli, _) = EngineId::of_family(family);+ // An engine out of usage until a known time is limited, not unready: its account stays+ // in the plan and its own limited-until time decides when it is tried again+ state.engines.quota_until(cli).is_some()+ || reports.iter().any(|r| r.id == cli && r.enabled && r.status == EngineStatus::Ready)+ };+ // The host's own login is judged by its engine check (ready here), not by an account probe+ // that may predate it: a "This machine" account never counts as signed out then+ for p in profiles.iter().filter(|p| p.kind == "system") {+ if Engine::parse(&p.engine).is_some_and(host_ready) {+ avail.signed_out.remove(&p.id);+ }+ }+ // An engine the person switched off, or that isn't installed, is a setup matter, not an+ // outage: a bot on it is told so rather than answered on another engine+ let own_engine_off = {+ let (cli, _) = EngineId::of_family(engine);+ reports.iter().any(|r| r.id == cli && (!r.enabled || r.status == EngineStatus::NotInstalled))+ };+ let eligible = |p: &LlmProfile| {+ profile_engine_on(state, p)+ && (!own_engine_off || Engine::parse(&p.engine) == Some(engine))+ && (p.kind != "system" || Engine::parse(&p.engine).is_some_and(|f| f == engine || host_ready(f)))+ };+ global_order(+ &profiles,+ engine,+ bound.as_deref(),+ failover,+ &avail,+ chrono::Utc::now(),+ &OrderRules { host_head: !host_off, eligible: &eligible },+ )+}++/// Engines whose every enabled account of `space` is known to be out right now (out of usage,+/// signed out, no key): Laya never routes a message to one of them. An engine with no account+/// rows is not listed; the host's own login is judged by its engine check instead.+pub async fn unusable_engines(state: &AppState, space: &SpaceId) -> HashSet<Engine> {+ let Some((profiles, avail)) = accounts(state, space).await else {+ return HashSet::new();+ };+ let now = chrono::Utc::now();+ [Engine::Claude, Engine::Codex, Engine::Grok, Engine::Custom]+ .into_iter()+ .filter(|f| {+ let mine: Vec<&LlmProfile> = profiles+ .iter()+ .filter(|p| p.enabled && Engine::parse(&p.engine) == Some(*f) && profile_engine_on(state, p))+ .collect();+ !mine.is_empty() && mine.iter().all(|p| !avail.usable(p, now))+ })+ .collect()+}+/// Engines whose This machine profile is off in `space`. A turn on one of them never falls back/// to the host's own login or Settings key there; it needs one of the space's own accounts.pub async fn host_off(state: &AppState, space: &SpaceId) -> HashSet<Engine> {@@ -427,6 +501,67 @@ pub fn give_up_notice(format!("⚠️ [{kwant_name}] {which} {}. {fix}", reason(failure))}+/// How a person names an account's engine: "Claude", "Codex", "Grok", or a Custom API+/// account by its own name ("Maestro").+pub fn engine_label(p: &LlmProfile) -> String {+ match Engine::parse(&p.engine) {+ Some(Engine::Claude) => "Claude".into(),+ Some(Engine::Codex) => "Codex".into(),+ Some(Engine::Grok) => "Grok".into(),+ _ => p.name.clone(),+ }+}++/// `at` as a wall-clock time in the person's zone ("03:00"), else the server's, else "03:00 UTC".+pub async fn clock_text(state: &AppState, at: chrono::DateTime<chrono::Utc>) -> String {+ let tz = crate::zombie::settings::local_tz(&state.db).await;+ match crate::routines::now_in(&tz, at) {+ Ok(local) => local.format("%H:%M").to_string(),+ Err(_) => format!("{} UTC", at.format("%H:%M")),+ }+}++/// The quiet line when a turn runs on another engine because its own is out:+/// "Claude is out until 03:00 · Architect is answering on Codex (gpt-6.1)".+pub fn cross_engine_notice(+ from: &LlmProfile,+ until_text: Option<&str>,+ kwant_name: &str,+ to: &LlmProfile,+ to_model: Option<&str>,+) -> String {+ let why = match until_text {+ Some(t) => format!("is out until {t}"),+ None => "is unavailable".to_string(),+ };+ let model = to_model.map(|m| format!(" ({m})")).unwrap_or_default();+ format!("🔁 {} {why} · {kwant_name} is answering on {}{model}", engine_label(from), engine_label(to))+}++/// The one line when no account of the space can answer: the turn waits for the earliest reset.+pub fn all_out_line(until_text: &str) -> String {+ format!("Every model is out until {until_text}; I'll answer then.")+}++/// Outages already announced in a chat: (chat, account that ran out) to when that outage ends.+static ANNOUNCED: std::sync::Mutex<Vec<(String, String, chrono::DateTime<chrono::Utc>)>> =+ std::sync::Mutex::new(Vec::new());++/// Whether the notice for `account` running out in `chat` hasn't been shown yet for this outage+/// (until `until`, else an hour). Marks it shown, so a chat gets one line per outage, however+/// many turns it takes. A later outage of the same account is announced again.+pub fn announce_once(chat: &str, account: &str, until: Option<chrono::DateTime<chrono::Utc>>) -> bool {+ let now = chrono::Utc::now();+ let end = until.unwrap_or(now + chrono::Duration::hours(1));+ let Ok(mut seen) = ANNOUNCED.lock() else { return true };+ seen.retain(|(_, _, t)| *t > now);+ if seen.iter().any(|(c, a, _)| c == chat && a == account) {+ return false;+ }+ seen.push((chat.to_string(), account.to_string(), end));+ true+}+#[cfg(test)]mod tests {use super::*;diff --git a/src/server/routes.rs b/src/server/routes.rsindex 011e076d..ecd91456 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -1826,6 +1826,31 @@ async fn run_kwant_turn(/// Longest failure reason kept for a routine run's history.const MAX_FAILURE_CHARS: usize = 500;+/// The account a turn just left, until the one that takes over shows the "moved" line.+struct MovedFrom {+ /// Why it was left; `None` when it was skipped up front as known to be out.+ failure: Option<crate::profiles::ProviderFailure>,+ /// When its usage resets, if known.+ until: Option<chrono::DateTime<chrono::Utc>>,+ /// The model the turn was on when it left.+ model: Option<String>,+ profile: LlmProfile,+}++/// The refusal a reply stands for when it is nothing but a provider's usage-limit message.+/// Such a text is never saved as a reply (nor shown as a "While you were away" summary).+fn limit_line_failure(text: &str) -> Option<crate::profiles::ProviderFailure> {+ if !crate::profiles::classify::is_limit_line(text) {+ return None;+ }+ let (class, retry_at) = crate::profiles::classify(None, text, chrono::Utc::now())?;+ class.fails_over().then(|| crate::profiles::ProviderFailure {+ class,+ retry_at,+ detail: crate::profiles::classify::redact_detail(text, 300),+ })+}+/// [`run_kwant_turn`], but a failed turn says why: the driver's error or the provider's refusal./// The turn first waits for a slot under the per-agent and server-wide caps (see [`super::turns`])./// A reply that ends by asking the person to choose may be held and decided first (see@@ -2160,7 +2185,18 @@ async fn run_kwant_turn_inner(model: None,reasoning: "Same agent and effort as the turn that asked for this tool".into(),}),- None => router.route_prompt_with_models(&prompt, "chat", &available_models).await,+ None => {+ // Laya never picks an engine whose accounts are all out right now; when that+ // would leave nothing, it routes as before and the failover plan parks the turn+ let out = super::profile_turn::unusable_engines(state, &space).await;+ let routable: Vec<_> = available_models+ .iter()+ .filter(|m| crate::profiles::Engine::parse(&m.id).is_none_or(|f| !out.contains(&f)))+ .cloned()+ .collect();+ let routable = if routable.is_empty() { &available_models } else { &routable };+ router.route_prompt_with_models(&prompt, "chat", routable).await+ }};let route = match route {Ok(r) => r,@@ -2325,19 +2361,14 @@ async fn run_kwant_turn_inner(// straight on this machine's loginlet engine = crate::profiles::Engine::parse(&target_model).or_else(|| crate::profiles::Engine::from_model(&target_model));- let candidates = super::profile_turn::plan(state, engine, &target_kwant.id).await;- // This machine turned off in the kwant's space: no host fallback, so nothing to try- let host_off = match engine {- Some(e) => super::profile_turn::host_off(state, &SpaceId::new(&target_kwant.space_id)).await.contains(&e),- None => false,- };- let attempts: Vec<Option<LlmProfile>> = if candidates.is_empty() && host_off {- Vec::new()- } else if candidates.is_empty() {- vec![None]- } else {- candidates.into_iter().map(Some).collect()- };+ // One order across every engine of the space: the bot's own account first, then the rest by+ // priority (known-limited ones left out up front). A skill replay stays on its own engine.+ let mut global = super::profile_turn::plan_global(state, engine, &target_kwant.id).await;+ if opts.rehearse.is_some() {+ global.attempts.retain(|a| a.as_ref().is_none_or(|p| crate::profiles::Engine::parse(&p.engine) == engine));+ global.all_out_until = None;+ }+ let attempts: Vec<Option<LlmProfile>> = std::mem::take(&mut global.attempts);// The agents' own continuity tools, for engines that can call MCP toolslet self_scope = (engine.is_some() && super::continuity::agent_tools_enabled(state).await).then(|| {super::continuity::SelfScope {@@ -2432,7 +2463,23 @@ async fn run_kwant_turn_inner(let rehearse_blocked = opts.rehearse.is_some()&& (engine != Some(crate::profiles::Engine::Claude) || mcp_turn.is_none());let attempts = if rehearse_blocked { Vec::new() } else { attempts };- if attempts.is_empty() {+ // Every account is known to be out: nothing is tried, the turn waits for the earliest reset+ if let (Some(until), false) = (global.all_out_until, rehearse_blocked) {+ let at = super::profile_turn::clock_text(state, until).await;+ let mut text = super::profile_turn::all_out_line(&at);+ let parked = super::parked::park(scope, target_kwant, &park_prompt, opts.retried || opts.discussion.is_some(), opts.delegation_id.clone(), Some(until)).await;+ if parked.is_none() {+ text = format!("Every model is out until {at}.");+ }+ event_broadcast.send(RuntimeEvent::TextDelta(text.clone()));+ event_broadcast.send(RuntimeEvent::TurnComplete {+ tokens: 0,+ duration_ms: turn_start.elapsed().as_millis() as u64,+ kwant_id: Some(target_kwant.id.clone()),+ profile_id: None,+ });+ gave_up = Some(text);+ } else if attempts.is_empty() {let text = if rehearse_blocked {format!("⚠️ [{}] A skill replay runs only on Claude, with kwant's tool checks on.", target_kwant.name)} else {@@ -2451,13 +2498,38 @@ async fn run_kwant_turn_inner(});gave_up = Some(text);}+ // Set when a turn leaves an account that ran out (or was skipped as known to be out), and+ // shown once the attempt that takes over knows its model+ let mut moved_from: Option<MovedFrom> = global.skipped.take().map(|p| MovedFrom {+ failure: None,+ until: global.skipped_until,+ model: None,+ profile: p,+ });+ // 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);for (i, profile) in attempts.iter().enumerate() {+ // An account of another engine than the bot's own runs the tier of the bot's model,+ // not its model id (which no other engine knows)+ let attempt_family = profile.as_ref().and_then(|p| crate::profiles::Engine::parse(&p.engine));+ let cross = engine.is_some() && attempt_family.is_some() && attempt_family != engine;+ let target_model = match (cross, attempt_family) {+ (true, Some(f)) => f.as_str().to_string(),+ _ => target_model.clone(),+ };+ let (pinned_model, tier) = if cross {+ (None, pinned_model.as_deref().and_then(crate::drivers::engines::tier_from_name).unwrap_or(tier))+ } else {+ (pinned_model.clone(), tier)+ };+ let (driver_key, driver_endpoint) = if cross { (None, None) } else { (configured_key.clone(), endpoint.clone()) };let (driver, host_engine) = match super::profile_turn::driver_for(state,profile.as_ref(),&target_model,- configured_key.clone(),- endpoint.clone(),+ driver_key,+ driver_endpoint,).await{@@ -2486,11 +2558,12 @@ async fn run_kwant_turn_inner(let choice = match custom {Some(p) => super::profile_turn::custom_model(state, p, pinned_model.as_deref(), tier).await,None => runs_on.and_then(|e| {- crate::drivers::engines::choose_model(- &crate::drivers::engines::known_models(&state.engines, e),- pinned_model.as_deref(),- tier,- )+ let models = crate::drivers::engines::known_models(&state.engines, e);+ if cross {+ crate::drivers::engines::choose_model_near(&models, pinned_model.as_deref(), tier)+ } else {+ crate::drivers::engines::choose_model(&models, pinned_model.as_deref(), tier)+ }}),};// An API account whose models weren't listed here picks its own from the tier@@ -2501,6 +2574,63 @@ async fn run_kwant_turn_inner(});let mut input = turn_input.clone();input.model = if unlisted_api { None } else { choice.as_ref().and_then(|c| c.run_id()).map(str::to_string) };+ if cross {+ input.model_override = Some(target_model.clone());+ }+ let model_label = input.model.clone().or_else(|| choice.as_ref().map(|c| c.label.clone()));+ if let Some(from) = moved_from.take() {+ let to_family = attempt_family.map_or("", |f| f.as_str());+ let from_family = crate::profiles::Engine::parse(&from.profile.engine).map_or("", |f| f.as_str());+ let same_engine = to_family == from_family;+ // Same engine: today's line, only when it failed just now. Another engine: one+ // quiet line per chat per outage, also when the account was skipped up front.+ let notice = match (profile.as_ref(), &from.failure) {+ (Some(to), Some(failure)) if same_engine => Some(super::profile_turn::switch_notice(&from.profile, to, failure)),+ (Some(to), _) if !same_engine => {+ let until = match from.until {+ Some(t) => Some(super::profile_turn::clock_text(state, t).await),+ None => None,+ };+ super::profile_turn::announce_once(&chat_key, &from.profile.id, from.until)+ .then(|| super::profile_turn::cross_engine_notice(&from.profile, until.as_deref(), &target_kwant.name, to, model_label.as_deref()))+ }+ _ => None,+ };+ if let (Some(to), Some(notice)) = (profile.as_ref(), notice) {+ let class: String = from.failure.as_ref().map_or(if from.until.is_some() { "quota" } else { "auth" }, |f| f.class.as_str()).into();+ switch_meta.push(serde_json::json!({+ "kwant_id": target_kwant.id,+ "from_profile_id": from.profile.id,+ "from_name": from.profile.name,+ "to_profile_id": to.id,+ "to_name": to.name,+ "class": class,+ "retry_at": from.until,+ "from_engine": from_family,+ "to_engine": to_family,+ "from_model": from.model,+ "to_model": model_label,+ "notice": notice,+ }));+ event_broadcast.send(RuntimeEvent::ProfileSwitched {+ kwant_id: target_kwant.id.clone(),+ from_profile_id: from.profile.id.clone(),+ from_name: from.profile.name.clone(),+ to_profile_id: to.id.clone(),+ to_name: to.name.clone(),+ class,+ retry_at: from.until,+ from_engine: from_family.into(),+ to_engine: to_family.into(),+ from_model: from.model.clone(),+ to_model: model_label.clone(),+ });+ event_broadcast.send(RuntimeEvent::ThinkingDelta(notice.clone()));+ tracing::info!(kwant = %target_kwant.id, from = %from.profile.id, to = %to.id, "turn moved to another account");+ notices.push(notice);+ }+ }+ let last_model = input.model.clone().or_else(|| choice.as_ref().map(|c| c.label.clone()));if let Some(e) = runs_on {event_broadcast.send(RuntimeEvent::ThinkingDelta(format!("Running on {}{} · {}{}",@@ -2591,7 +2721,7 @@ async fn run_kwant_turn_inner(}}let visible = match &event {- RuntimeEvent::TextDelta(t) => !t.trim().is_empty(),+ RuntimeEvent::TextDelta(t) => !t.trim().is_empty() && !crate::profiles::classify::is_limit_line(t),RuntimeEvent::ToolCallPending { .. } | RuntimeEvent::ApprovalRequired { .. } => true,_ => false,};@@ -2633,7 +2763,8 @@ async fn run_kwant_turn_inner(}let result = driver_task.await;let refused = match &result {- Ok(Ok(out)) => out.failure.clone(),+ // A reply that is nothing but a usage-limit line is the provider's refusal, never an answer+ Ok(Ok(out)) => out.failure.clone().or_else(|| limit_line_failure(&out.text)),_ => None,};if let Some(failure) = refused {@@ -2644,22 +2775,35 @@ async fn run_kwant_turn_inner(state.engines.record_failure(engine, &failure);}let next = attempts.get(i + 1).and_then(|n| n.as_ref());- if let (Some(from), Some(to), false) = (profile, next, side_effects) {- let notice = super::profile_turn::switch_notice(from, to, &failure);- event_broadcast.send(RuntimeEvent::ProfileSwitched {- kwant_id: target_kwant.id.clone(),- from_profile_id: from.id.clone(),- from_name: from.name.clone(),- to_profile_id: to.id.clone(),- to_name: to.name.clone(),- class: failure.class.as_str().into(),- retry_at: failure.retry_at,+ if let (Some(from), Some(_), false) = (profile, next, side_effects) {+ // The line is shown once the next account knows its model (see `moved_from`)+ moved_from = Some(MovedFrom {+ failure: Some(failure.clone()),+ until: failure.retry_at.filter(|_| failure.class == crate::profiles::classify::FailClass::Quota),+ model: last_model.clone(),+ profile: from.clone(),});- event_broadcast.send(RuntimeEvent::ThinkingDelta(notice.clone()));- tracing::info!(kwant = %target_kwant.id, from = %from.id, to = %to.id, class = failure.class.as_str(), "turn moved to another profile");- notices.push(notice);continue;}+ // Nothing left to try and every account of the space is now known to be out: one+ // line, and the turn waits for the earliest reset+ if failure.class == crate::profiles::classify::FailClass::Quota && !side_effects && !rehearse_blocked && opts.rehearse.is_none() {+ let again = super::profile_turn::plan_global(state, engine, &target_kwant.id).await;+ if let Some(until) = again.all_out_until {+ let at = super::profile_turn::clock_text(state, until).await;+ let parked = super::parked::park(scope, target_kwant, &park_prompt, opts.retried || opts.discussion.is_some(), opts.delegation_id.clone(), Some(until)).await;+ let text = if parked.is_some() { super::profile_turn::all_out_line(&at) } else { format!("Every model is out until {at}.") };+ event_broadcast.send(RuntimeEvent::TextDelta(text.clone()));+ event_broadcast.send(RuntimeEvent::TurnComplete {+ tokens: 0,+ duration_ms: turn_start.elapsed().as_millis() as u64,+ kwant_id: Some(target_kwant.id.clone()),+ profile_id: profile.as_ref().map(|p| p.id.clone()),+ });+ gave_up = Some(text);+ break;+ }+ }let text = match profile {Some(p) => {super::profile_turn::give_up_notice(&target_kwant.name, p, &failure, i + 1)@@ -2805,6 +2949,9 @@ async fn run_kwant_turn_inner(if let Some(usage) = &output.usage {meta.get_or_insert_with(|| serde_json::json!({}))["usage"] = serde_json::json!(usage);}+ if !switch_meta.is_empty() {+ meta.get_or_insert_with(|| serde_json::json!({}))["failover"] = serde_json::Value::Array(switch_meta.clone());+ }if let Some(routing) = &opts.routing {meta.get_or_insert_with(|| serde_json::json!({}))["routing"] = routing.clone();}diff --git a/src/server/sse.rs b/src/server/sse.rsindex 97590314..adde9386 100644--- a/src/server/sse.rs+++ b/src/server/sse.rs@@ -248,6 +248,10 @@ mod tests {to_name: s("x"),class: s("quota"),retry_at: None,+ from_engine: s("claude"),+ to_engine: s("codex"),+ from_model: Some(s("opus")),+ to_model: None,},E::DiscussionStarted { team_id: s("t"), team_name: s("x"), total_turns: 1, speakers: vec![], plan: vec![], kind: s("x") },E::DiscussionTurnStarted {diff --git a/tests/model_failover_test.rs b/tests/model_failover_test.rsnew file mode 100644index 00000000..cedf0209--- /dev/null+++ b/tests/model_failover_test.rs@@ -0,0 +1,274 @@+//! A bot whose engine is out of usage is answered by the next account in the one Accounts order,+//! across engines, with fake claude and codex CLIs on PATH. The limit line itself is never a reply.+//! 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 chrono::{Duration as Span, Utc};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::Database,+ drivers::{engines::EngineId, RuntimeEvent},+ profiles::classify::{FailClass, ProviderFailure},+ router::LayaRouter,+ server::{create_router, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+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))+}++/// Sends a prompt and collects the turn's events 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, RuntimeEvent::TurnEnded { kwant_id: k, .. } if k == kwant_id);+ events.push(e.unscoped().clone());+ if end {+ break;+ }+ }+ })+ .await+ .expect("turn did not end");+ events+}++fn text_of(events: &[RuntimeEvent]) -> String {+ events+ .iter()+ .filter_map(|e| match e {+ RuntimeEvent::TextDelta(t) => Some(t.as_str()),+ _ => None,+ })+ .collect()+}++fn switches(events: &[RuntimeEvent]) -> Vec<&RuntimeEvent> {+ events.iter().filter(|e| matches!(e, RuntimeEvent::ProfileSwitched { .. })).collect()+}++fn runs(dir: &Path, cli: &str) -> usize {+ std::fs::read_to_string(dir.join(format!("{cli}.argv"))).map(|s| s.lines().count()).unwrap_or(0)+}++/// The newest saved reply of the bot: its text and parsed meta.+async fn last_reply(state: &AppState, kwant_id: &str) -> (String, 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.text.clone(), m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null))+}++#[tokio::test]+async fn a_session_limit_moves_the_bot_to_the_next_engine_and_back() {+ 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");+ // Claude is out from the start+ std::fs::write(tmp.path().join("claude.out"), "").unwrap();++ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ let config = Config {+ data_dir: data.clone(),+ 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()),+ );+ let app = create_router(state.clone());+ let (s, v) = call(&app, "POST", "/api/engines/recheck", None).await;+ assert_eq!(s, StatusCode::OK, "{v}");++ // The Accounts order: Claude first, then Codex+ 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}");+ }++ let (_, kwants) = call(&app, "GET", "/api/kwants", None).await;+ let k = kwants[0].clone();+ let kid = k["id"].as_str().unwrap().to_string();+ let mut body = k.clone();+ body.as_object_mut().unwrap().retain(|key, _| ["name", "title", "persona_prompt", "soul", "avatar_sprite"].contains(&key.as_str()));+ body["preferred_model"] = json!("claude");+ let (s, v) = call(&app, "PUT", &format!("/api/kwants/{kid}"), Some(body)).await;+ assert_eq!(s, StatusCode::OK, "{v}");++ // 1. Claude prints the session-limit line: Codex answers, with one quiet notice+ let t0 = Utc::now();+ let events = run_turn(&app, &state, &kid).await;+ let text = text_of(&events);+ assert!(text.contains("hello from fake codex"), "{text}");+ assert!(!text.contains("session limit"), "the limit line is not a reply: {text}");+ assert_eq!(runs(tmp.path(), "claude"), 1);+ assert_eq!(runs(tmp.path(), "codex"), 1);+ let sw = switches(&events);+ assert_eq!(sw.len(), 1, "{events:?}");+ let RuntimeEvent::ProfileSwitched { from_profile_id, to_profile_id, class, retry_at, from_engine, to_engine, to_model, .. } = sw[0] else {+ unreachable!()+ };+ assert_eq!((from_profile_id.as_str(), to_profile_id.as_str(), class.as_str()), ("prf_system_claude", "prf_system_codex", "quota"));+ assert_eq!((from_engine.as_str(), to_engine.as_str()), ("claude", "codex"));+ assert!(to_model.as_deref().is_some_and(|m| m.to_lowercase().contains("gpt-6")), "{to_model:?}");+ assert!(matches!(events.last(), Some(RuntimeEvent::TurnEnded { outcome, .. }) if outcome == "completed"), "{events:?}");++ // The reply is Codex's, carries the notice in its meta, and no limit line is saved anywhere+ let (reply, meta) = last_reply(&state, &kid).await;+ assert_eq!(reply.trim(), "hello from fake codex");+ assert_eq!(meta["ran_on"]["engine"], "codex", "{meta}");+ assert_eq!(meta["failover"].as_array().map(Vec::len), Some(1), "{meta}");+ let ps = &meta["failover"][0];+ assert_eq!((ps["from_engine"].clone(), ps["to_engine"].clone()), (json!("claude"), json!("codex")), "{meta}");+ assert!(ps["to_model"].is_string() && ps["from_profile_id"] == "prf_system_claude" && ps["retry_at"].is_string(), "{meta}");+ let saved = state.db.list_messages(&kid, 50).await.unwrap();+ assert!(!saved.iter().any(|m| m.sender_role == "kwant" && m.text.contains("session limit")), "{saved:?}");++ // Claude is limited until the next 03:00 in Berlin (01:00 or 02:00 UTC), within a day+ let (_, list) = call(&app, "GET", "/api/profiles", None).await;+ let claude = list.as_array().unwrap().iter().find(|p| p["id"] == "prf_system_claude").unwrap().clone();+ assert_eq!(claude["last_error"], "quota");+ let until: chrono::DateTime<Utc> = claude["limited_until"].as_str().unwrap().parse().unwrap();+ assert_eq!(retry_at.unwrap(), until);+ assert!(until > t0 && until <= t0 + Span::hours(24) + Span::minutes(1), "{until}");+ let (h, m) = (chrono::Timelike::hour(&until), chrono::Timelike::minute(&until));+ assert!(m == 0 && (h == 1 || h == 2), "03:00 Berlin is 01:00 or 02:00 UTC, got {until}");++ // 2. The next turn skips Claude without an attempt, and says nothing more about it+ let events = run_turn(&app, &state, &kid).await;+ assert!(text_of(&events).contains("hello from fake codex"));+ assert_eq!(runs(tmp.path(), "claude"), 1, "no attempt on a known-limited account");+ assert_eq!(runs(tmp.path(), "codex"), 2);+ assert!(switches(&events).is_empty(), "one line per outage: {events:?}");+ assert!(last_reply(&state, &kid).await.1.get("failover").is_none());++ // 3. After the reset the bot goes back to Claude by itself+ std::fs::remove_file(tmp.path().join("claude.out")).unwrap();+ let reset = Utc::now() - Span::minutes(1);+ state.db.record_profile_failure("prf_system_claude", "quota", Some(reset)).await.unwrap();+ // The engine's own "quota exceeded until" mark lapses at the same moment+ state.engines.record_failure(+ EngineId::Claude,+ &ProviderFailure { class: FailClass::Quota, retry_at: Some(reset), detail: String::new() },+ );+ let events = run_turn(&app, &state, &kid).await;+ assert!(text_of(&events).contains("hello from fake claude"), "{events:?}");+ assert_eq!((runs(tmp.path(), "claude"), runs(tmp.path(), "codex")), (2, 2));+ assert!(switches(&events).is_empty());++ // 4. Everything out: nothing is tried, one line says when, and the turn parks once+ state.db.record_profile_failure("prf_system_claude", "quota", Some(Utc::now() + Span::hours(3))).await.unwrap();+ state.db.record_profile_failure("prf_system_codex", "quota", Some(Utc::now() + Span::hours(2))).await.unwrap();+ // The default host-login setup: a real refusal also marks the whole engine "quota exceeded+ // until", which must read as a limit (account still there, earliest reset wins), not as an+ // engine that cannot run+ for (engine, hours) in [(EngineId::Claude, 3), (EngineId::Codex, 2)] {+ state.engines.record_failure(+ engine,+ &ProviderFailure { class: FailClass::Quota, retry_at: Some(Utc::now() + Span::hours(hours)), detail: String::new() },+ );+ }+ let events = run_turn(&app, &state, &kid).await;+ let text = text_of(&events);+ assert!(text.contains("Every model is out until") && text.contains("I'll answer then."), "{text}");+ assert_eq!((runs(tmp.path(), "claude"), runs(tmp.path(), "codex")), (2, 2), "nothing was attempted");+ let parked = state.db.list_parked().await.unwrap();+ assert_eq!(parked.len(), 1, "{parked:?}");+ // The earliest reset is Codex's, two hours away+ let at = parked[0].retry_at;+ assert!(at > Utc::now() + Span::minutes(119) && at < Utc::now() + Span::minutes(121), "{at}");+ // A second message while everything is out is parked with the same line, never a setup card+ let events = run_turn(&app, &state, &kid).await;+ let text = text_of(&events);+ assert!(text.contains("Every model is out until") && !text.contains("No account can run bots"), "{text}");+ let (reply, meta) = last_reply(&state, &kid).await;+ assert!(!reply.contains("Settings") && meta.get("kind") != Some(&json!("setup_needed")), "{reply} {meta}");+ assert_eq!((runs(tmp.path(), "claude"), runs(tmp.path(), "codex")), (2, 2), "nothing was attempted");+ assert_eq!(state.db.list_parked().await.unwrap().len(), 1, "a chat parks at most once");+ let saved = state.db.list_messages(&kid, 50).await.unwrap();+ assert!(!saved.iter().any(|m| m.text.contains("session limit")));+}diff --git a/tests/quota_retry_test.rs b/tests/quota_retry_test.rsindex 1cd01e1d..9a9b47db 100644--- a/tests/quota_retry_test.rs+++ b/tests/quota_retry_test.rs@@ -27,8 +27,8 @@ async fn parked_rows(env: &Env) -> Vec<kwnt::db::parked::ParkedTurn> {async fn a_limited_turn_is_retried_once_when_the_limit_resets() {let env = setup().await;send_direct(&env, &env.a, "do it QUOTAONCE:q1 REPLYTAG:q1done", json!({})).await;- let notice = wait_reply(&env, &env.a, "will retry this once").await;- assert!(notice.text.contains("UTC"), "{}", notice.text);+ let notice = wait_reply(&env, &env.a, "I'll answer then").await;+ assert!(notice.text.contains("Every model is out until"), "{}", notice.text);let rows = parked_rows(&env).await;assert_eq!(rows.len(), 1);assert_eq!(rows[0].status, "pending");@@ -56,29 +56,32 @@ async fn a_limited_turn_is_retried_once_when_the_limit_resets() {async fn a_retry_that_hits_the_limit_again_is_not_parked_again() {let env = setup().await;send_direct(&env, &env.a, "do it QUOTAALWAYS REPLYTAG:never", json!({})).await;- wait_reply(&env, &env.a, "will retry this once").await;+ wait_reply(&env, &env.a, "I'll answer then").await;past_reset(&env).await;assert_eq!(parked::run_due(&env.state, later()).await, 1);wait_for("the retry to fail", || async {- messages(&env, &env.a).await.iter().filter(|m| m.sender_role == "kwant" && m.text.contains("out of usage")).count() == 2+ messages(&env, &env.a).await.iter().filter(|m| m.sender_role == "kwant" && m.text.contains("Every model is out until")).count() == 2}).await;tokio::time::sleep(Duration::from_millis(300)).await;let rows = parked_rows(&env).await;assert_eq!(rows.len(), 1, "no second park");let last = messages(&env, &env.a).await.into_iter().rfind(|m| m.sender_role == "kwant").unwrap();- assert!(!last.text.contains("will retry"), "{}", last.text);+ assert!(!last.text.contains("I'll answer then"), "{}", last.text);}#[tokio::test]async fn a_later_turn_that_got_through_drops_the_parked_one() {let env = setup().await;send_direct(&env, &env.b, "first QUOTAONCE:q3 REPLYTAG:q3a", json!({})).await;- wait_reply(&env, &env.b, "will retry this once").await;+ wait_reply(&env, &env.b, "I'll answer then").await;past_reset(&env).await;// A second limited message in the same chat doesn't add a second retrysend_direct(&env, &env.b, "second QUOTAONCE:q3c", json!({})).await;- wait_reply(&env, &env.b, "already set").await;+ wait_for("the second limited message to be answered", || async {+ messages(&env, &env.b).await.iter().filter(|m| m.sender_role == "kwant" && m.text.contains("I'll answer then")).count() == 2+ })+ .await;tokio::time::sleep(Duration::from_secs(4)).await;assert_eq!(parked_rows(&env).await.len(), 1);