Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat(host): share an agent's model list asked for from several places at once

leepokaid9ea06438b5e
diff --git a/host/src/agent/auth.rs b/host/src/agent/auth.rs
index afc48a05..583d7e78 100644
--- a/host/src/agent/auth.rs
+++ b/host/src/agent/auth.rs
@@ -33,7 +33,7 @@ mod agent;
mod models;
pub use agent::authenticate;
use agent::start;
-pub use models::models;
+pub use models::{Recent, models, recent_models};
pub(crate) use models::{model_config, model_ids};
#[derive(Clone, Debug, Serialize)]
diff --git a/host/src/agent/auth/models.rs b/host/src/agent/auth/models.rs
index 16d8ebfd..a93dd5b2 100644
--- a/host/src/agent/auth/models.rs
+++ b/host/src/agent/auth/models.rs
@@ -1,11 +1,49 @@
//! The models an agent offers, read from a session it opens for that alone.
use super::{probe_dir, start, text};
+use crate::LockExt;
use crate::agent::acp::Incoming;
+use crate::hub::Hub;
use crate::store::Store;
use anyhow::{Context, Result, bail};
use serde_json::{Value, json};
-use std::time::Duration;
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex as StdMutex};
+use std::time::{Duration, Instant};
+use tokio::sync::Mutex;
+
+/// Model lists from the last minute, by agent: a settings screen asks for one from several places at once (the model
+/// picker, Approvals), and each would otherwise start the agent.
+#[derive(Default)]
+pub struct Recent(StdMutex<HashMap<String, Slot>>);
+
+/// One agent's list and when it came; locked while it's asked for.
+type Slot = Arc<Mutex<Option<(Instant, Value)>>>;
+
+impl Recent {
+ /// `fetch`'s list for `agent`, or the one fetched in the last minute; one in progress answers those that come
+ /// meanwhile. A failure is kept by no one.
+ async fn get(&self, agent: &str, fetch: impl Future<Output = Result<Value>>) -> Result<Value> {
+ let slot = self.0.locked().entry(agent.to_owned()).or_default().clone();
+ let mut listed = slot.lock().await;
+ if let Some((at, catalog)) = listed.as_ref()
+ && at.elapsed() < Duration::from_mins(1)
+ {
+ return Ok(catalog.clone());
+ }
+ let result = fetch.await;
+ match &result {
+ Ok(catalog) => *listed = Some((Instant::now(), catalog.clone())),
+ Err(_) => drop(self.0.locked().remove(agent)),
+ }
+ result
+ }
+}
+
+/// [`models`], shared with the asks of the last minute.
+pub async fn recent_models(hub: &Hub, backend: &str) -> Result<Value> {
+ hub.catalogs.get(backend, models(&hub.store, backend)).await
+}
/// Discover the agent's advertised models in an isolated, prompt-free session.
/// This uses the same credentials as actual bot sessions and never reads project files.
@@ -198,6 +236,26 @@ fn collect_values(options: &Value, out: &mut Vec<Value>) {
mod tests {
use super::*;
+ #[tokio::test]
+ async fn asks_at_once_start_the_agent_once_and_a_failure_is_asked_again() {
+ let recent = Recent::default();
+ let started = std::sync::atomic::AtomicUsize::new(0);
+ let fetch = |ok: bool| {
+ let started = &started;
+ async move {
+ started.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ if ok { Ok(json!({"models": []})) } else { Err(anyhow::anyhow!("signed out")) }
+ }
+ };
+ let (a, b) = tokio::join!(recent.get("claude", fetch(true)), recent.get("claude", fetch(true)));
+ assert_eq!((a.unwrap(), b.unwrap()), (json!({"models": []}), json!({"models": []})));
+ assert_eq!(started.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert!(recent.get("codex", fetch(false)).await.is_err());
+ assert!(recent.get("codex", fetch(true)).await.is_ok());
+ assert_eq!(started.load(std::sync::atomic::Ordering::SeqCst), 3);
+ }
+
#[tokio::test]
async fn an_unavailable_model_keeps_other_models_and_their_options() {
let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/model_options_agent.py");
diff --git a/host/src/api/host.rs b/host/src/api/host.rs
index 5be526fe..eec65a17 100644
--- a/host/src/api/host.rs
+++ b/host/src/api/host.rs
@@ -113,7 +113,7 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
let backend = if step == crate::agent::term::Step::Node { "" } else { str_arg(&b, "backend")? };
json!({"term": hub.terms.start(backend, step, b["method"].as_str(), cols, rows).await?})
}
- "agentModels" => crate::agent::auth::models(&hub.store, str_arg(&b, "backend")?).await?,
+ "agentModels" => crate::agent::auth::recent_models(hub, str_arg(&b, "backend")?).await?,
"agentAuth" | "agentAuthenticate" | "setAgentEnv" => {
let backend = str_arg(&b, "backend")?;
let status = match method {
diff --git a/host/src/hub.rs b/host/src/hub.rs
index 45410ef9..8878a5b8 100644
--- a/host/src/hub.rs
+++ b/host/src/hub.rs
@@ -112,6 +112,7 @@ pub struct Hub {
pub screen: Arc<Screen>,
/// Setup terminals (installs, sign-ins).
pub terms: Arc<crate::agent::term::Terms>,
+ pub catalogs: crate::agent::auth::Recent,
}
impl Hub {
@@ -150,6 +151,7 @@ impl Hub {
cloud: crate::remote::cloud::Cloud::default(),
screen,
terms: Arc::default(),
+ catalogs: crate::agent::auth::Recent::default(),
})
}
diff --git a/host/src/tui/app/forms.rs b/host/src/tui/app/forms.rs
index f3e7d928..78f3b476 100644
--- a/host/src/tui/app/forms.rs
+++ b/host/src/tui/app/forms.rs
@@ -176,8 +176,8 @@ impl App {
f.model_options = Default::default();
let own = f.backend.clone();
f.fallbacks.retain(|x| x.backend != own);
- // Nor its mode ids: its Auto mode, if it has one, is the only choice that carries over.
- f.mode = f.mode.take().filter(|m| m == crate::agent::modes::AUTO);
+ // Nor its mode ids: a picked mode becomes the new agent's Auto mode (or, without one, asking).
+ f.mode = f.mode.take().map(|_| crate::agent::modes::AUTO.to_owned());
self.want_models(&f.backend);
}
}