Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Agent chat: a searchable model picker with a custom entry, listed from every provider, and OpenClaw and OpenRouter presets (#2582) (#10255)

Rec0iL52f0b52b4527
diff --git a/assets/locales/pending/agent-chat-model-picker.json b/assets/locales/pending/agent-chat-model-picker.json
new file mode 100644
index 0000000000..c97b17710f
--- /dev/null
+++ b/assets/locales/pending/agent-chat-model-picker.json
@@ -0,0 +1,90 @@
+{
+ "en": {
+ "ui.agent_chat_custom_heading": "Custom model",
+ "ui.agent_chat_model_custom": "Use custom: {model}",
+ "ui.agent_chat_model_rejected": "The agent did not accept {model}: {error}",
+ "ui.agent_chat_model_search": "Search models…",
+ "ui.agent_chat_models_failed": "Couldn't list models: {error}",
+ "ui.agent_chat_models_heading": "Available models",
+ "ui.agent_chat_models_listing": "Listing models…",
+ "ui.agent_chat_models_none": "The endpoint lists no models",
+ "ui.agent_chat_models_not_a_list": "The answer was no model list"
+ },
+ "de": {
+ "ui.agent_chat_custom_heading": "Eigenes Modell",
+ "ui.agent_chat_model_custom": "Eigenes verwenden: {model}",
+ "ui.agent_chat_model_rejected": "Der Agent hat {model} nicht akzeptiert: {error}",
+ "ui.agent_chat_model_search": "Modelle suchen…",
+ "ui.agent_chat_models_failed": "Modelle konnten nicht abgerufen werden: {error}",
+ "ui.agent_chat_models_heading": "Verfügbare Modelle",
+ "ui.agent_chat_models_listing": "Modelle werden abgerufen…",
+ "ui.agent_chat_models_none": "Der Endpunkt listet keine Modelle",
+ "ui.agent_chat_models_not_a_list": "Die Antwort war keine Modellliste"
+ },
+ "ko": {
+ "ui.agent_chat_custom_heading": "사용자 지정 모델",
+ "ui.agent_chat_model_custom": "직접 입력 사용: {model}",
+ "ui.agent_chat_model_rejected": "에이전트가 {model}을(를) 받아들이지 않았습니다: {error}",
+ "ui.agent_chat_model_search": "모델 검색…",
+ "ui.agent_chat_models_failed": "모델 목록을 가져올 수 없습니다: {error}",
+ "ui.agent_chat_models_heading": "사용 가능한 모델",
+ "ui.agent_chat_models_listing": "모델 목록을 가져오는 중…",
+ "ui.agent_chat_models_none": "엔드포인트에 나열된 모델이 없습니다",
+ "ui.agent_chat_models_not_a_list": "응답이 모델 목록이 아닙니다"
+ },
+ "ar": {
+ "ui.agent_chat_custom_heading": "نموذج مخصص",
+ "ui.agent_chat_model_custom": "استخدام المخصص: {model}",
+ "ui.agent_chat_model_rejected": "لم يقبل الوكيل {model}: {error}",
+ "ui.agent_chat_model_search": "البحث عن النماذج…",
+ "ui.agent_chat_models_failed": "تعذّر جلب قائمة النماذج: {error}",
+ "ui.agent_chat_models_heading": "النماذج المتاحة",
+ "ui.agent_chat_models_listing": "جارٍ جلب قائمة النماذج…",
+ "ui.agent_chat_models_none": "لا تسرد نقطة النهاية أي نماذج",
+ "ui.agent_chat_models_not_a_list": "لم يكن الرد قائمة نماذج"
+ },
+ "he": {
+ "ui.agent_chat_custom_heading": "מודל מותאם אישית",
+ "ui.agent_chat_model_custom": "שימוש במותאם אישית: {model}",
+ "ui.agent_chat_model_rejected": "הסוכן לא קיבל את {model}: {error}",
+ "ui.agent_chat_model_search": "חיפוש מודלים…",
+ "ui.agent_chat_models_failed": "לא ניתן היה לטעון את רשימת המודלים: {error}",
+ "ui.agent_chat_models_heading": "מודלים זמינים",
+ "ui.agent_chat_models_listing": "טוען רשימת מודלים…",
+ "ui.agent_chat_models_none": "נקודת הקצה אינה מציגה מודלים",
+ "ui.agent_chat_models_not_a_list": "התשובה לא הייתה רשימת מודלים"
+ },
+ "ja": {
+ "ui.agent_chat_custom_heading": "カスタムモデル",
+ "ui.agent_chat_model_custom": "カスタムを使用: {model}",
+ "ui.agent_chat_model_rejected": "エージェントは {model} を受け付けませんでした: {error}",
+ "ui.agent_chat_model_search": "モデルを検索…",
+ "ui.agent_chat_models_failed": "モデルを一覧表示できませんでした: {error}",
+ "ui.agent_chat_models_heading": "利用可能なモデル",
+ "ui.agent_chat_models_listing": "モデルを一覧表示中…",
+ "ui.agent_chat_models_none": "エンドポイントにモデルがありません",
+ "ui.agent_chat_models_not_a_list": "応答はモデル一覧ではありませんでした"
+ },
+ "vi": {
+ "ui.agent_chat_custom_heading": "Mô hình tùy chỉnh",
+ "ui.agent_chat_model_custom": "Dùng tùy chỉnh: {model}",
+ "ui.agent_chat_model_rejected": "Tác tử không chấp nhận {model}: {error}",
+ "ui.agent_chat_model_search": "Tìm mô hình…",
+ "ui.agent_chat_models_failed": "Không thể lấy danh sách mô hình: {error}",
+ "ui.agent_chat_models_heading": "Các mô hình có sẵn",
+ "ui.agent_chat_models_listing": "Đang lấy danh sách mô hình…",
+ "ui.agent_chat_models_none": "Điểm cuối không liệt kê mô hình nào",
+ "ui.agent_chat_models_not_a_list": "Phản hồi không phải là danh sách mô hình"
+ },
+ "zh": {
+ "ui.agent_chat_custom_heading": "自定义模型",
+ "ui.agent_chat_model_custom": "使用自定义:{model}",
+ "ui.agent_chat_model_rejected": "智能体未接受 {model}:{error}",
+ "ui.agent_chat_model_search": "搜索模型…",
+ "ui.agent_chat_models_failed": "无法列出模型:{error}",
+ "ui.agent_chat_models_heading": "可用模型",
+ "ui.agent_chat_models_listing": "正在列出模型…",
+ "ui.agent_chat_models_none": "该端点未列出任何模型",
+ "ui.agent_chat_models_not_a_list": "响应不是模型列表"
+ }
+}
diff --git a/crates/ui-egui/src/agent_chat/acp_client.rs b/crates/ui-egui/src/agent_chat/acp_client.rs
index e9f88f4bbf..6b453964c8 100644
--- a/crates/ui-egui/src/agent_chat/acp_client.rs
+++ b/crates/ui-egui/src/agent_chat/acp_client.rs
@@ -166,6 +166,8 @@ impl AcpBackend {
out.push(Event::TurnEnded { reason: "auth".into() });
}
out.push(Event::AuthRequired { methods: self.auth.clone() });
+ } else if what == Pending::SetModel {
+ out.push(Event::ModelRejected(message));
} else if !config_error {
if what == Pending::Prompt {
out.push(Event::TurnEnded { reason: "error".into() });
@@ -382,4 +384,26 @@ mod tests {
assert!(matches!(events.as_slice(), [Event::ConfigOptionFinished { result: Ok(options), .. }] if options[0].current_value == "smart"));
backend.shutdown(true);
}
+
+ /// A refused model is the picker's business, not an error of the chat; signing in stays as it was.
+ #[test]
+ fn a_refused_model_is_reported_as_such() {
+ let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) };
+ let mut backend = AcpBackend::start(&["sh".into(), "-c".into(), "cat >/dev/null".into()], ctx).unwrap();
+ let mut events = Vec::new();
+ backend.handle(Incoming::Reply { id: 1, result: Ok(json!({"agentInfo":{"name":"fake"}})) }, &mut events);
+ backend.handle(Incoming::Reply { id: 2, result: Ok(json!({"sessionId":"s1"})) }, &mut events);
+ events.clear();
+ backend.set_model("zzz");
+ backend.handle(Incoming::Reply { id: backend.next_id, result: Err((-32602, "no such model".into())) }, &mut events);
+ assert!(matches!(events.as_slice(), [Event::ModelRejected(message)] if message == "no such model"), "{events:?}");
+ events.clear();
+ backend.set_model("fast");
+ backend.handle(Incoming::Reply { id: backend.next_id, result: Ok(json!({})) }, &mut events);
+ assert!(events.is_empty(), "{events:?}");
+ backend.set_model("zzz");
+ backend.handle(Incoming::Reply { id: backend.next_id, result: Err((acp::AUTH_REQUIRED, "sign in".into())) }, &mut events);
+ assert!(matches!(events.as_slice(), [Event::AuthRequired { .. }]), "{events:?}");
+ backend.shutdown(true);
+ }
}
diff --git a/crates/ui-egui/src/agent_chat/agents.rs b/crates/ui-egui/src/agent_chat/agents.rs
index b7d6b8a81b..51e49b9739 100644
--- a/crates/ui-egui/src/agent_chat/agents.rs
+++ b/crates/ui-egui/src/agent_chat/agents.rs
@@ -76,7 +76,7 @@ impl Kind {
}
/// The wire protocol of an endpoint the user added.
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Protocol {
/// `{base}/chat/completions`, as Ollama, LM Studio, OpenAI and their kin speak.
#[default]
@@ -303,9 +303,11 @@ pub struct ApiPreset {
pub const OPENAI_PRESETS: &[ApiPreset] = &[
ApiPreset { name: "Ollama", base_url: "http://localhost:11434/v1" },
ApiPreset { name: "LM Studio", base_url: "http://localhost:1234/v1" },
+ ApiPreset { name: "OpenClaw", base_url: "http://localhost:18789/v1" },
ApiPreset { name: "OpenAI", base_url: "https://api.openai.com/v1" },
ApiPreset { name: "Mammouth AI", base_url: "https://api.mammouth.ai/v1" },
ApiPreset { name: "OpenCode Go", base_url: "https://opencode.ai/zen/go/v1" },
+ ApiPreset { name: "OpenRouter", base_url: "https://openrouter.ai/api/v1" },
];
/// Anthropic-compatible endpoints people use. The base URL is the one their documentation calls
@@ -400,6 +402,18 @@ mod tests {
assert!(presets(Protocol::Anthropic).iter().any(|p| p.base_url == "https://api.anthropic.com/v1"));
}
+ /// The first preset is the one an Add dialog opens with, and the one taken for Ollama.
+ #[test]
+ fn ollama_stays_the_first_preset_and_every_preset_can_take_a_key() {
+ assert_eq!(OPENAI_PRESETS.first().map(|p| p.name), Some("Ollama"));
+ assert_eq!(OPENAI_PRESETS.last().map(|p| p.name), Some("OpenRouter"));
+ assert!(OPENAI_PRESETS.iter().any(|p| p.name == "OpenClaw"));
+ for preset in OPENAI_PRESETS.iter().chain(ANTHROPIC_PRESETS) {
+ assert_eq!(normalize_url(preset.base_url).as_deref(), Ok(preset.base_url), "{}", preset.name);
+ assert!(key_safe_for(preset.base_url), "{}", preset.name);
+ }
+ }
+
#[test]
fn request_timeouts_default_to_300_s_and_stay_between_30_s_and_an_hour() {
assert_eq!(AgentConfig::default().request_timeout_s, 300);
diff --git a/crates/ui-egui/src/agent_chat/api_client.rs b/crates/ui-egui/src/agent_chat/api_client.rs
index 88c38e39af..e3bc37ecb2 100644
--- a/crates/ui-egui/src/agent_chat/api_client.rs
+++ b/crates/ui-egui/src/agent_chat/api_client.rs
@@ -15,6 +15,7 @@ use std::time::Duration;
use serde_json::{Map, Value, json};
+use super::MODEL_LIST_CAP;
use super::acp::ModelInfo;
use super::agents::Protocol;
use super::backend::{ChatBackend, Event, HttpFn, HttpRequest, PromptPart, StartContext, ToolStatus};
@@ -22,6 +23,8 @@ use super::process::{AgentProcess, FromAgent, ProcessHandle};
/// Longest tool result handed back to the model.
const MAX_TOOL_TEXT: usize = 20_000;
+/// Longest name kept for a listed model.
+const MODEL_NAME_CAP: usize = 256;
/// Messages kept in the conversation (the system note stays).
const MAX_HISTORY: usize = 240;
/// Pictures of the view kept in the conversation. The whole history goes with every request
@@ -795,15 +798,24 @@ impl Worker {
}
self.emit(Event::ToolsAvailable(!self.tools.is_empty()));
self.emit(Event::Ready { agent: format!("{} · {}", self.cfg.name, self.cfg.model), images: true });
- // The endpoint's models for the picker; an endpoint that does not list them shows none.
- if let Ok(list) = self.model_list() {
- let mut available = list;
- if !self.cfg.model.is_empty() && !available.iter().any(|m| m.id == self.cfg.model) {
- available.insert(0, ModelInfo { id: self.cfg.model.clone(), name: self.cfg.model.clone(), description: String::new() });
+ // The endpoint's models for the picker. An endpoint that does not list them still shows the
+ // configured model, and says why there are no others.
+ let configured = ModelInfo { id: self.cfg.model.clone(), name: self.cfg.model.clone(), description: String::new() };
+ let available = match self.model_list() {
+ Ok(mut list) => {
+ self.emit(Event::ModelsNote(None));
+ if !self.cfg.model.is_empty() && !list.iter().any(|m| m.id == self.cfg.model) {
+ list.insert(0, configured);
+ }
+ list
}
- if !available.is_empty() {
- self.emit(Event::Models { current: self.cfg.model.clone(), available });
+ Err(e) => {
+ self.emit(Event::ModelsNote(Some(e)));
+ if self.cfg.model.is_empty() { Vec::new() } else { vec![configured] }
}
+ };
+ if !available.is_empty() {
+ self.emit(Event::Models { current: self.cfg.model.clone(), available });
}
for cmd in cmds {
match cmd {
@@ -1628,7 +1640,7 @@ fn anthropic_headers(base_url: &str, key: Option<&str>) -> Result<Vec<(String, S
}
/// The endpoint's models for the picker. The Messages API has no models endpoint at every
-/// compatible provider (Qwen's has none), so a failure here simply leaves the picker empty.
+/// compatible provider (Qwen's has none), so a failure here leaves only the configured model.
pub fn anthropic_model_list(http: &HttpFn, base_url: &str, key: Option<&str>) -> Result<Vec<ModelInfo>, String> {
let req = HttpRequest { method: "GET", url: endpoint(base_url, "models"), headers: anthropic_headers(base_url, key)?, body: None, timeout_s: 15 };
let (status, bytes) = http(&req)?;
@@ -1636,19 +1648,10 @@ pub fn anthropic_model_list(http: &HttpFn, base_url: &str, key: Option<&str>) ->
if status != 200 {
return Err(http_error(status, &v));
}
- Ok(v.get("data")
- .and_then(Value::as_array)
- .map(|a| {
- a.iter()
- .take(500)
- .filter_map(|m| {
- let id = m.get("id").and_then(Value::as_str)?.to_string();
- let name = m.get("display_name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| id.clone());
- Some(ModelInfo { id, name, description: String::new() })
- })
- .collect()
- })
- .unwrap_or_default())
+ Ok(listed_models(&v, "display_name")?
+ .into_iter()
+ .map(|(id, name)| ModelInfo { name: name.unwrap_or_else(|| id.clone()), id, description: String::new() })
+ .collect())
}
/// Test an Anthropic-compatible endpoint: send the smallest message there is, so the check covers
@@ -1721,18 +1724,35 @@ fn tool_title(name: &str, args: &Value) -> String {
}
}
-/// `GET {base_url}/models`: the model ids, in the order the endpoint lists them.
-fn model_ids(http: &HttpFn, base_url: &str, headers: Vec<(String, String)>) -> Result<Vec<String>, String> {
+/// The ids of a `/models` body and the names the endpoint gives them (when not just the id), in
+/// its order. The body is the endpoint's to write: an id that could not be sent back is left out,
+/// and a name is cut. A body without a `data` array is no model list (a web page where the
+/// endpoint should be, say): an error, so the picker says so and asks again later.
+fn listed_models(body: &Value, name_key: &str) -> Result<Vec<(String, Option<String>)>, String> {
+ let Some(entries) = body.get("data").and_then(Value::as_array) else {
+ return Err(crate::i18n::tr("ui.agent_chat_models_not_a_list").to_string());
+ };
+ Ok(entries
+ .iter()
+ .filter_map(|m| {
+ let id = m.get("id").and_then(Value::as_str).filter(|id| super::model_id_valid(id))?;
+ let name = m.get(name_key).and_then(Value::as_str).filter(|name| *name != id).map(|name| name.chars().take(MODEL_NAME_CAP).collect());
+ Some((id.to_string(), name))
+ })
+ .take(MODEL_LIST_CAP)
+ .collect())
+}
+
+/// `GET {base_url}/models`: the models, in the order the endpoint lists them. The picker shows the
+/// ids, so an endpoint's own name for a model is its description.
+fn model_entries(http: &HttpFn, base_url: &str, headers: Vec<(String, String)>) -> Result<Vec<ModelInfo>, String> {
let req = HttpRequest { method: "GET", url: format!("{base_url}/models"), headers, body: None, timeout_s: 15 };
let (status, bytes) = http(&req)?;
let v: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
if status != 200 {
return Err(http_error(status, &v));
}
- Ok(v.get("data")
- .and_then(Value::as_array)
- .map(|a| a.iter().take(500).filter_map(|m| m.get("id").and_then(Value::as_str).map(String::from)).collect())
- .unwrap_or_default())
+ Ok(listed_models(&v, "name")?.into_iter().map(|(id, name)| ModelInfo { name: id.clone(), id, description: name.unwrap_or_default() }).collect())
}
/// The endpoint's models for the picker.
@@ -1744,7 +1764,7 @@ pub fn model_list(http: &HttpFn, base_url: &str, key: Option<&str>) -> Result<Ve
}
headers.push(("Authorization".to_string(), format!("Bearer {k}")));
}
- Ok(model_ids(http, base_url, headers)?.into_iter().map(|id| ModelInfo { name: id.clone(), id, description: String::new() }).collect())
+ model_entries(http, base_url, headers)
}
/// Ask an endpoint for its models (Test connection): how many, and whether `model` is one.
@@ -1756,10 +1776,9 @@ pub fn test_endpoint(http: &HttpFn, base_url: &str, key: Option<&str>, model: &s
}
headers.push(("Authorization".to_string(), format!("Bearer {k}")));
}
- let ids = model_ids(http, base_url, headers)?;
- let ids: Vec<&str> = ids.iter().map(String::as_str).collect();
- let found = model.is_empty() || ids.contains(&model);
- Ok(crate::i18n::format(if found { "ui.ai_test_ok" } else { "ui.ai_test_no_model" }, &[("count", &ids.len().to_string()), ("model", model)]))
+ let models = model_entries(http, base_url, headers)?;
+ let found = model.is_empty() || models.iter().any(|m| m.id == model);
+ Ok(crate::i18n::format(if found { "ui.ai_test_ok" } else { "ui.ai_test_no_model" }, &[("count", &models.len().to_string()), ("model", model)]))
}
#[cfg(test)]
@@ -2059,6 +2078,7 @@ mod tests {
let Some(Event::Models { current, available }) = events.iter().find(|e| matches!(e, Event::Models { .. })) else { panic!("{events:?}") };
assert_eq!(current, "local");
assert_eq!(available.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["local", "big", "small"]);
+ assert!(events.iter().any(|e| matches!(e, Event::ModelsNote(None))), "{events:?}");
b.set_model("big");
b.prompt(&[PromptPart::Text("hi".into())]);
wait_for_seen(&seen);
@@ -2561,6 +2581,87 @@ mod tests {
assert!(tools[0].pointer("/parameters/additionalProperties").is_none(), "{tools:?}");
}
+ /// An endpoint that refuses the listing still shows the configured model, and says why first.
+ #[test]
+ fn a_refused_listing_keeps_the_configured_model_and_says_why() {
+ let http: HttpFn = Arc::new(|r: &HttpRequest| {
+ assert_eq!(r.method, "GET");
+ Ok((401, json!({"error": {"message": "No auth credentials"}}).to_string().into_bytes()))
+ });
+ let cfg = ApiConfig {
+ name: "Test".into(),
+ protocol: Protocol::OpenAi,
+ base_url: "http://localhost:1/v1".into(),
+ model: "local".into(),
+ key: None,
+ http,
+ request_timeout_s: 300,
+ reasoning_effort: String::new(),
+ };
+ let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) };
+ let mut b = ApiBackend::start(cfg, ctx).unwrap();
+ let mut events = Vec::new();
+ let start = std::time::Instant::now();
+ while !events.iter().any(|e| matches!(e, Event::Models { .. })) && start.elapsed() < Duration::from_secs(10) {
+ events.extend(b.poll());
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ let listing: Vec<&Event> = events.iter().filter(|e| matches!(e, Event::Models { .. } | Event::ModelsNote(_))).collect();
+ let [Event::ModelsNote(Some(note)), Event::Models { current, available }] = listing[..] else { panic!("{events:?}") };
+ assert!(note.contains("No auth credentials"), "{note}");
+ assert_eq!(current, "local");
+ assert_eq!(available.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["local"]);
+ b.shutdown(true);
+ }
+
+ /// OpenRouter's shape: the name is the description, whatever else an entry holds is ignored, an
+ /// id that could not be sent back is left out, and the list stays within its caps.
+ #[test]
+ fn a_listing_keeps_the_names_and_stays_within_its_caps() {
+ let mut data = vec![
+ json!({"id": "openai/gpt-x", "name": "OpenAI: GPT X", "description": "Long text", "supported_parameters": ["tools"]}),
+ json!({"id": "same", "name": "same", "display_name": "Same One"}),
+ json!({"id": "long", "name": "n".repeat(MODEL_NAME_CAP + 10), "display_name": "d".repeat(MODEL_NAME_CAP + 10)}),
+ json!({"id": "x".repeat(super::super::MODEL_ID_CAP + 1)}),
+ json!({"id": "bell\u{7}"}),
+ json!({"id": ""}),
+ json!({"id": 7}),
+ json!({"name": "no id"}),
+ ];
+ data.extend((0..MODEL_LIST_CAP + 500).map(|i| json!({"id": format!("m{i}")})));
+ let body = json!({"data": data}).to_string().into_bytes();
+ let http: HttpFn = Arc::new(move |_: &HttpRequest| Ok((200, body.clone())));
+ let list = model_list(&http, "https://openrouter.ai/api/v1", None).unwrap();
+ assert_eq!(list.len(), MODEL_LIST_CAP);
+ let [first, same, long, next] = &list[..4] else { panic!("{}", list.len()) };
+ assert_eq!((first.id.as_str(), first.name.as_str(), first.description.as_str()), ("openai/gpt-x", "openai/gpt-x", "OpenAI: GPT X"));
+ assert_eq!((same.id.as_str(), same.description.as_str()), ("same", ""));
+ assert_eq!(long.description.chars().count(), MODEL_NAME_CAP);
+ assert_eq!(next.id, "m0");
+ let list = anthropic_model_list(&http, "https://openrouter.ai/api/v1", None).unwrap();
+ assert_eq!(list.len(), MODEL_LIST_CAP);
+ let [first, same, long] = &list[..3] else { panic!("{}", list.len()) };
+ assert_eq!(first.name, "openai/gpt-x");
+ assert_eq!(same.name, "Same One");
+ assert_eq!(long.name.chars().count(), MODEL_NAME_CAP);
+ assert!(test_endpoint(&http, "https://openrouter.ai/api/v1", None, "openai/gpt-x").unwrap().contains(&MODEL_LIST_CAP.to_string()));
+ }
+
+ /// A 200 that is no model list (a web page where the endpoint should be) is an error, so the
+ /// picker says why and asks again later; a list with nothing in it is a list.
+ #[test]
+ fn an_answer_that_is_no_model_list_is_an_error() {
+ let expected = crate::i18n::tr("ui.agent_chat_models_not_a_list").to_string();
+ let page: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, b"<!doctype html><html><body>Control UI</body></html>".to_vec())));
+ assert_eq!(model_list(&page, "http://localhost:18789/v1", None).unwrap_err(), expected);
+ assert_eq!(anthropic_model_list(&page, "http://localhost:18789/v1", None).unwrap_err(), expected);
+ assert_eq!(test_endpoint(&page, "http://localhost:18789/v1", None, "").unwrap_err(), expected);
+ let object: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, json!({"object": "list"}).to_string().into_bytes())));
+ assert_eq!(model_list(&object, "http://localhost:18789/v1", None).unwrap_err(), expected);
+ let empty: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, json!({"data": []}).to_string().into_bytes())));
+ assert!(model_list(&empty, "http://localhost:18789/v1", None).unwrap().is_empty());
+ }
+
#[test]
fn tool_arguments_are_an_object_or_an_error() {
assert_eq!(tool_arguments(None), Ok(json!({})));
diff --git a/crates/ui-egui/src/agent_chat/backend.rs b/crates/ui-egui/src/agent_chat/backend.rs
index c7976a8d51..ccd404c09e 100644
--- a/crates/ui-egui/src/agent_chat/backend.rs
+++ b/crates/ui-egui/src/agent_chat/backend.rs
@@ -96,6 +96,11 @@ pub enum Event {
current: String,
available: Vec<super::acp::ModelInfo>,
},
+ /// Why an endpoint's models could not be listed (`None`: they could). It comes before the
+ /// [`Event::Models`] of that listing, which then holds only the configured model.
+ ModelsNote(Option<String>),
+ /// The agent refused the model it was just sent, and says why.
+ ModelRejected(String),
ConfigOptions(Vec<ConfigOption>),
ConfigOptionFinished {
id: String,
diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs
index b1554a06c8..9292af175f 100644
--- a/crates/ui-egui/src/agent_chat/mod.rs
+++ b/crates/ui-egui/src/agent_chat/mod.rs
@@ -316,6 +316,15 @@ impl Loading {
}
}
+/// The model before an ACP agent was sent another, for when it refuses that one.
+struct ModelRevert {
+ model: String,
+ /// The one sent was not listed, so it leaves the list again.
+ unlisted: bool,
+ /// The model remembered for this agent.
+ saved: Option<String>,
+}
+
#[derive(Default)]
pub struct AgentChat {
/// The panel is shown (View menu, the application bar's chat button, Ctrl+Shift+A).
@@ -402,6 +411,12 @@ pub struct AgentChat {
/// The provider picked in the header when the models come from several providers (`None`: the
/// current model's). It only narrows the model list; the agent keeps its model until one is chosen.
pub model_provider: Option<String>,
+ /// Why the running endpoint's models could not be listed, for the picker.
+ pub models_note: Option<String>,
+ /// What to put back if the running ACP agent refuses the model it was last sent.
+ model_revert: Option<ModelRevert>,
+ /// The typed model an agent's model option was sent, until it answers.
+ typed_model: Option<String>,
pub config_options: Option<Vec<acp::ConfigOption>>,
pub config_pending: bool,
/// An API endpoint's models, kept per endpoint (its base URL) for the next connection.
@@ -484,6 +499,7 @@ impl AgentChat {
self.model_provider = None;
}
self.config_pending = false;
+ self.typed_model = None;
}
fn apply_config_snapshot(&mut self, options: Vec<acp::ConfigOption>) {
@@ -575,6 +591,11 @@ impl AgentChat {
pictures.push(Picture::shared(Arc::new(png), "", true));
}
}
+ /// Say that the agent refused a model, and in its words why.
+ fn model_refused(&mut self, model: &str, error: &str) {
+ let text = trf("ui.agent_chat_model_rejected", &[("model", model), ("error", error)]);
+ self.notice(text.chars().take(MODELS_NOTE_CAP).collect::<String>(), true);
+ }
fn notice(&mut self, text: impl Into<String>, error: bool) {
self.push(Item::Notice { text: text.into(), error });
}
@@ -718,11 +739,21 @@ impl AgentChat {
}
}
Event::Models { current, available } => {
+ self.model_revert = None;
if self.config_options.is_none() && !available.is_empty() {
- if !self.running_endpoint.is_empty() {
- self.models_cache.insert(self.running_endpoint.clone(), available.clone());
+ if self.models_note.is_some() {
+ // The listing failed: last time's list stays, with the configured model in it.
+ for model in available {
+ if !self.models.iter().any(|m| m.id == model.id) {
+ self.models.insert(0, model);
+ }
+ }
+ } else {
+ if !self.running_endpoint.is_empty() {
+ self.models_cache.insert(self.running_endpoint.clone(), available.clone());
+ }
+ self.models = available;
}
- self.models = available;
}
if self.config_options.is_none() {
if current != self.model {
@@ -731,16 +762,36 @@ impl AgentChat {
self.model = current;
}
}
+ // Formatted here: the listing's thread has no language of its own.
+ Event::ModelsNote(error) => {
+ self.models_note =
+ error.map(|error| trf("ui.agent_chat_models_failed", &[("error", &error)]).chars().take(MODELS_NOTE_CAP).collect());
+ }
+ Event::ModelRejected(message) => {
+ let refused = self.model.clone();
+ self.model_refused(&refused, &message);
+ if let Some(revert) = self.model_revert.take() {
+ if revert.unlisted {
+ let refused = std::mem::take(&mut self.model);
+ self.models.retain(|m| m.id != refused);
+ }
+ self.model = revert.model;
+ self.model_provider = None;
+ }
+ }
Event::ConfigOptions(options) => {
self.apply_config_snapshot(options);
}
Event::ConfigOptionFinished { result, .. } => {
self.config_pending = false;
- match result {
- Ok(options) => {
+ let typed = self.typed_model.take();
+ match (result, typed) {
+ (Ok(options), _) => {
self.apply_config_snapshot(options);
}
- Err(message) => self.notice(message, true),
+ // An agent's own words may not say what it refused ("Internal error").
+ (Err(message), Some(model)) => self.model_refused(&model, &message),
+ (Err(message), None) => self.notice(message, true),
}
}
Event::AuthRequired { methods } => {
@@ -986,6 +1037,8 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) {
chat.mode.clear();
chat.models.clear();
chat.model.clear();
+ chat.models_note = None;
+ chat.model_revert = None;
chat.running_endpoint = if entry.kind.is_api() { entry.base_url.clone() } else { String::new() };
// An endpoint's models from the last time, until the new list arrives.
if let Some(list) = chat.models_cache.get(&chat.running_endpoint) {
@@ -1352,6 +1405,7 @@ pub fn new_chat(app: &mut SolveApp) {
chat.stopped = false;
chat.ended = None;
chat.discard_end = running;
+ chat.model_revert = None;
if matches!(chat.state(), State::Ready | State::Busy) {
chat.restore_mode = Some(chat.mode.clone()).filter(|m| !m.is_empty());
chat.state = Some(State::Starting);
@@ -1880,6 +1934,7 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) {
}
_ => None,
};
+ let refused = if matches!(e, Event::ModelRejected(_)) { app.agent_chat.model_revert.as_ref().map(|r| r.saved.clone()) } else { None };
match app.agent_chat.on_event(e) {
Some(Outcome::TurnEnd) => {
end_turn(app);
@@ -1895,10 +1950,19 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) {
}
if let Some(model) = confirmed_model {
app.preferences.agent_models.insert(app.agent_chat.running_id.clone(), model.clone());
- if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == app.agent_chat.running_id && a.kind == agents::Kind::Api) {
+ if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == app.agent_chat.running_id && a.kind.is_api()) {
a.model = model;
}
}
+ match refused {
+ Some(Some(saved)) => {
+ app.preferences.agent_models.insert(app.agent_chat.running_id.clone(), saved);
+ }
+ Some(None) => {
+ app.preferences.agent_models.remove(&app.agent_chat.running_id);
+ }
+ None => {}
+ }
if ready {
apply_saved_model(app);
}
@@ -1919,6 +1983,7 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) {
#[cfg(not(target_arch = "wasm32"))]
{
settings::poll_capabilities(app, ctx);
+ settings::poll_listing(app, ctx);
connect_at_start(app, ctx);
}
pump_tools(app);
@@ -1953,15 +2018,66 @@ pub fn set_model(app: &mut SolveApp, model: &str) {
set_config_option(app, &id, model);
return;
}
- if !app.agent_chat.models.iter().any(|m| m.id == model) {
- return;
+ if app.agent_chat.models.iter().any(|m| m.id == model) {
+ send_model(app, model);
}
- if let Some(b) = app.agent_chat.backend.as_mut() {
- b.set_model(model);
+}
+
+/// Whether a model the agent did not list can be sent: an endpoint, an ACP agent with a model
+/// option, or a legacy ACP agent that listed models.
+pub fn custom_models_accepted(app: &SolveApp) -> bool {
+ let chat = &app.agent_chat;
+ if chat.backend.is_none() || !chat.state().running() {
+ return false;
+ }
+ match chat.config_options.as_ref() {
+ Some(options) => options.iter().any(|o| o.category == "model"),
+ None => !chat.running_endpoint.is_empty() || !chat.models.is_empty(),
+ }
+}
+
+/// A typed model (the pickers' custom row). A listed id goes the usual way, others by the agent's
+/// kind; an agent that refuses it keeps its model and the chat says so. Returns whether it was sent.
+pub fn set_custom_model(app: &mut SolveApp, text: &str) -> bool {
+ let model = text.trim();
+ if !model_id_valid(model) || !custom_models_accepted(app) {
+ return false;
}
- app.agent_chat.model = model.to_string();
- app.agent_chat.model_provider = None;
+ let option = app.agent_chat.config_options.as_ref().and_then(|options| options.iter().find(|o| o.category == "model"));
+ if let Some(id) = option.map(|o| o.id.clone()) {
+ let sent = set_config_option_checked(app, &id, model, false);
+ if sent {
+ app.agent_chat.typed_model = Some(model.to_string());
+ }
+ return sent;
+ }
+ send_model(app, model);
+ true
+}
+
+/// Switch a legacy ACP agent or an endpoint to `model`: it shows as current at once and is
+/// remembered for this agent; an endpoint also keeps it as its default model.
+fn send_model(app: &mut SolveApp, model: &str) {
let agent = app.agent_chat.running_id.clone();
+ let chat = &mut app.agent_chat;
+ let unlisted = !chat.models.iter().any(|m| m.id == model);
+ let entry = || acp::ModelInfo { id: model.to_string(), name: model.to_string(), description: String::new() };
+ if unlisted {
+ chat.models.insert(0, entry());
+ chat.models.truncate(MODEL_LIST_CAP);
+ }
+ if chat.running_endpoint.is_empty() {
+ chat.model_revert = Some(ModelRevert { model: chat.model.clone(), unlisted, saved: app.preferences.agent_models.get(&agent).cloned() });
+ } else if unlisted {
+ let cached = chat.models_cache.entry(chat.running_endpoint.clone()).or_default();
+ cached.insert(0, entry());
+ cached.truncate(MODEL_LIST_CAP);
+ }
+ if let Some(b) = chat.backend.as_mut() {
+ b.set_model(model);
+ }
+ chat.model = model.to_string();
+ chat.model_provider = None;
if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == agent && a.kind.is_api()) {
a.model = model.to_string();
}
@@ -1984,10 +2100,22 @@ pub fn models_shown(app: &SolveApp) -> bool {
/// Longest provider name kept from an agent's model list.
const PROVIDER_NAME_CAP: usize = 128;
+/// Most models kept for a picker, whether listed or typed.
+const MODEL_LIST_CAP: usize = 2000;
+/// Longest model id kept from a listing or sent to an agent.
+pub const MODEL_ID_CAP: usize = 256;
+/// Longest note about a listing that failed or a model the agent refused.
+const MODELS_NOTE_CAP: usize = 1024;
+
+/// Whether a model id can go to an agent: not empty, not too long, no control characters.
+fn model_id_valid(id: &str) -> bool {
+ !id.is_empty() && id.chars().count() <= MODEL_ID_CAP && !id.chars().any(char::is_control)
+}
/// A model's provider and its name at that provider, when the agent says which provider serves it:
-/// a name `Provider · model` (Hermes, OpenCode) or a description `Provider: …` (up to a ` • `).
-/// `None`: the agent names no provider.
+/// a name `Provider · model` (Hermes, OpenCode), a description `Provider: …` (up to a ` • `), or
+/// an endpoint's listing whose id reads `vendor/model` and whose description (the endpoint's own
+/// name for it) reads `Vendor: Model` (OpenRouter). `None`: the agent names no provider.
pub fn model_provider(m: &acp::ModelInfo) -> Option<(String, String)> {
let cap = |s: &str| s.trim().chars().take(PROVIDER_NAME_CAP).collect::<String>();
if let Some((provider, name)) = m.name.split_once(" · ")
@@ -1996,9 +2124,48 @@ pub fn model_provider(m: &acp::ModelInfo) -> Option<(String, String)> {
{
return Some((cap(provider), name.trim().to_string()));
}
- let rest = m.description.strip_prefix("Provider:")?;
- let provider = rest.lines().next().unwrap_or("").split(" • ").next().unwrap_or("");
- (!provider.trim().is_empty()).then(|| (cap(provider), m.name.clone()))
+ if let Some(rest) = m.description.strip_prefix("Provider:") {
+ let provider = rest.lines().next().unwrap_or("").split(" • ").next().unwrap_or("");
+ return (!provider.trim().is_empty()).then(|| (cap(provider), m.name.clone()));
+ }
+ let first_line = m.description.lines().next().unwrap_or("");
+ if m.id.contains('/')
+ && let Some((vendor, name)) = first_line.split_once(": ")
+ && !vendor.trim().is_empty()
+ && vendor.chars().count() <= PROVIDER_NAME_CAP
+ && !name.trim().is_empty()
+ {
+ return Some((cap(vendor), name.trim().to_string()));
+ }
+ None
+}
+
+/// How a picker shows `models`: each one's label, the group it folds under and its tooltip. With
+/// models from two or more providers the label is the name at the provider, the group the
+/// provider and the tooltip the id (or the description where the label already is the id);
+/// otherwise the name as it is, no group, and the description.
+#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
+pub fn model_rows(models: &[acp::ModelInfo]) -> Vec<(String, Option<String>, String)> {
+ let mut providers: Vec<String> = Vec::new();
+ for m in models {
+ let p = provider_of(m);
+ if !providers.contains(&p) {
+ providers.push(p);
+ }
+ }
+ let grouped = providers.len() >= 2;
+ models
+ .iter()
+ .map(|m| {
+ if grouped {
+ let (provider, name) = model_provider(m).unwrap_or_else(|| (provider_of(m), m.name.clone()));
+ let tip = if name == m.id { m.description.clone() } else { m.id.clone() };
+ (name, Some(provider), tip)
+ } else {
+ (m.name.clone(), None, m.description.clone())
+ }
+ })
+ .collect()
}
/// The provider a model is listed under: its own, or "Other" when the agent names none.
@@ -2051,8 +2218,17 @@ pub fn listed_models(app: &SolveApp) -> Vec<(acp::ModelInfo, String)> {
.collect()
}
-/// Show one provider's models in the model picker (the header's provider picker). The agent keeps
-/// its model until one of them is chosen. A provider the agent does not offer is ignored.
+/// Every model the header's picker lists, with its label, the group it folds under and its tooltip
+/// ([`model_rows`]).
+#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
+pub fn grouped_models(app: &SolveApp) -> Vec<(acp::ModelInfo, String, Option<String>, String)> {
+ let rows = model_rows(&app.agent_chat.models);
+ app.agent_chat.models.iter().cloned().zip(rows).map(|(m, (label, group, tip))| (m, label, group, tip)).collect()
+}
+
+/// The provider whose group the header's model picker opens first (the control channel's
+/// `provider`). The agent keeps its model until one is chosen. A provider the agent does not offer
+/// is ignored.
pub fn set_model_provider(app: &mut SolveApp, provider: &str) {
if model_providers(app).iter().any(|(n, _)| n == provider) {
app.agent_chat.model_provider = Some(provider.to_string());
@@ -2079,19 +2255,25 @@ pub fn set_mode(app: &mut SolveApp, mode: &str) {
/// Change a reported modern ACP configuration option; only acknowledged snapshots change state.
pub fn set_config_option(app: &mut SolveApp, id: &str, value: &str) {
+ set_config_option_checked(app, id, value, true);
+}
+
+/// [`set_config_option`], with a choice the agent did not list (`listed_only` false: a typed
+/// model, which the agent may refuse). Returns whether it was sent.
+fn set_config_option_checked(app: &mut SolveApp, id: &str, value: &str, listed_only: bool) -> bool {
let Some(option) = app.agent_chat.config_options.as_ref().and_then(|xs| xs.iter().find(|x| x.id == id)) else {
- return;
+ return false;
};
if app.agent_chat.config_pending
|| !matches!(app.agent_chat.state(), State::Ready | State::Busy)
- || !option.options.iter().any(|x| x.value == value)
+ || (listed_only && !option.options.iter().any(|x| x.value == value))
{
- return;
- }
- if let Some(b) = app.agent_chat.backend.as_mut() {
- b.set_config_option(id, value);
- app.agent_chat.config_pending = true;
+ return false;
}
+ let Some(b) = app.agent_chat.backend.as_mut() else { return false };
+ b.set_config_option(id, value);
+ app.agent_chat.config_pending = true;
+ true
}
/// `ui.agent_chat` on the control channel (tests and screenshots): `enabled`, `command`,
@@ -2186,7 +2368,11 @@ pub fn control(app: &mut SolveApp, ctx: &egui::Context, p: &Value) -> Result<Val
set_model_provider(app, m);
}
if let Some(m) = p.get("model").and_then(Value::as_str) {
- set_model(app, m);
+ if app.agent_chat.models.iter().any(|x| x.id == m) {
+ set_model(app, m);
+ } else {
+ set_custom_model(app, m);
+ }
}
if let Some(option) = p.get("config_option") {
let id = option.get("id").and_then(Value::as_str).ok_or("config_option.id must be a string")?;
@@ -2313,7 +2499,7 @@ pub fn status(app: &SolveApp) -> Value {
#[cfg(target_arch = "wasm32")]
let detection: Option<Value> = None;
let pid = c.backend.as_ref().and_then(|b| b.pid());
- json!({
+ let mut state = json!({
"features": app.preferences.ai_features,
"configOptions": c.config_options,
"configPending": c.config_pending,
@@ -2355,7 +2541,13 @@ pub fn status(app: &SolveApp) -> Value {
"turnWarning": c.turn_warning,
"detection": detection,
"items": items,
- })
+ });
+ // Added apart: `json!` has reached the compiler's recursion limit above.
+ if let Some(state) = state.as_object_mut() {
+ state.insert("modelsNote".into(), json!(c.models_note));
+ state.insert("customModels".into(), json!(custom_models_accepted(app)));
+ }
+ state
}
#[cfg(test)]
diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs
index 389a20148e..8b69a7e89b 100644
--- a/crates/ui-egui/src/agent_chat/panel.rs
+++ b/crates/ui-egui/src/agent_chat/panel.rs
@@ -1044,11 +1044,8 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) {
);
let models = !modern && models_shown(app);
let providers = if models { model_providers(app) } else { Vec::new() };
- let w = (ui.available_width()
- - if modern || app.agent_chat.modes.is_empty() { 4.0 } else { 116.0 }
- - if models { 146.0 } else { 0.0 }
- - if providers.is_empty() { 0.0 } else { 146.0 })
- .clamp(90.0, 260.0);
+ let w = (ui.available_width() - if modern || app.agent_chat.modes.is_empty() { 4.0 } else { 116.0 } - if models { 146.0 } else { 0.0 })
+ .clamp(90.0, 260.0);
let mut picked: Option<String> = None;
let mut add = false;
let combo = ui
@@ -1109,61 +1106,47 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) {
set_mode(app, &m);
}
}
- // Models from several providers: pick the provider first, then one of its models.
- if let Some(shown) = shown_provider(app).filter(|_| !providers.is_empty()) {
- let mut pick: Option<String> = None;
- let width = picker_width(ui, &shown);
- let r = ui
- .allocate_ui(vec2(width, t.control_height), |ui| {
- ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
- ui_kit::dropdown_menu(ui, "sc_agent_provider", &shown, |ui| {
- for (name, count) in &providers {
- let row = ui_kit::list_picker(ui, &format!("provider:{name}"), name, *name == shown)
- .on_hover_text(trf("ui.agent_chat_provider_models", &[("count", &count.to_string())]));
- crate::scenario::publish_handle(&format!("agent_chat:provider:{name}"), row.rect.center());
- if row.clicked() {
- pick = Some(name.clone());
- }
- }
- })
- })
- .inner;
- crate::scenario::publish_rect("agent_chat:provider", r.rect);
- crate::scenario::publish_handle("agent_chat:provider", r.rect.center());
- r.on_hover_text(tr("ui.agent_chat_provider_tip"));
- if let Some(p) = pick {
- set_model_provider(app, &p);
- }
- }
// The agent's models (ACP `models`, or an endpoint's list): shown only when it reports some.
if models {
- let list = listed_models(app);
- let cur = list.iter().find(|(m, _)| m.id == app.agent_chat.model).map_or_else(
- || if providers.is_empty() { app.agent_chat.model.clone() } else { tr("ui.agent_chat_choose_model").to_string() },
- |(_, name)| name.clone(),
- );
- let mut pick: Option<String> = None;
+ // Models from several providers fold under their providers inside the picker, the
+ // current model's provider open.
+ let list = grouped_models(app);
+ let open = shown_provider(app).filter(|_| !providers.is_empty());
+ let cur = list
+ .iter()
+ .find(|(m, _, _, _)| m.id == app.agent_chat.model)
+ .map_or_else(|| app.agent_chat.model.clone(), |(_, name, _, _)| name.clone());
let width = if providers.is_empty() { t.form_label_width } else { picker_width(ui, &cur) };
- let r = ui
+ let choices: Vec<ui_kit::SearchChoice<'_>> =
+ list.iter().map(|(m, name, group, tip)| ui_kit::SearchChoice { value: &m.id, label: name, tip, group: group.as_deref() }).collect();
+ let custom = custom_models_accepted(app);
+ let picker = ui
.allocate_ui(vec2(width, t.control_height), |ui| {
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
- ui_kit::dropdown_menu(ui, "sc_agent_model", &cur, |ui| {
- for (m, name) in &list {
- let row = ui_kit::list_picker(ui, &m.id, name, m.id == app.agent_chat.model);
- let row = if m.description.is_empty() { row } else { row.on_hover_text(&m.description) };
- crate::scenario::publish_handle(&format!("agent_chat:model:{}", m.id), row.rect.center());
- if row.clicked() {
- pick = Some(m.id.clone());
- }
- }
- })
+ ui_kit::search_picker(
+ ui,
+ ui_kit::SearchPicker {
+ id: "sc_agent_model",
+ handles: "agent_chat:model",
+ current: &cur,
+ current_value: &app.agent_chat.model,
+ hint: tr("ui.agent_chat_model_search"),
+ choices: &choices,
+ custom,
+ note: app.agent_chat.models_note.as_deref(),
+ open_group: open.as_deref(),
+ enabled: true,
+ },
+ )
})
.inner;
- crate::scenario::publish_rect("agent_chat:model", r.rect);
- crate::scenario::publish_handle("agent_chat:model", r.rect.center());
- r.on_hover_text(tr("ui.agent_chat_model_tip"));
- if let Some(m) = pick {
- set_model(app, &m);
+ picker.response.on_hover_text(tr("ui.agent_chat_model_tip"));
+ match picker.inner {
+ Some(ui_kit::Picked::Listed(m)) => set_model(app, &m),
+ Some(ui_kit::Picked::Custom(m)) => {
+ set_custom_model(app, &m);
+ }
+ None => {}
}
}
});
@@ -1288,52 +1271,95 @@ fn config_select(app: &mut SolveApp, ui: &mut egui::Ui, option: &acp::ConfigOpti
.collect::<Vec<_>>()
.join("\n");
let mut picked = None;
- let response = ui
- .add_enabled_ui(!pending && !option.options.is_empty(), |ui| {
- ui.allocate_ui(vec2(width, t.control_height), |ui| {
- ui_kit::dropdown_menu(ui, ("sc_agent_config", &option.id), &displayed, |ui| {
- let mut previous_group: Option<&str> = None;
- for choice in &option.options {
- let group = choice.group.as_deref().filter(|g| !g.is_empty());
- if let Some(group) = group
- && previous_group != Some(group)
- {
- ui.label(RichText::new(compact_text(group, 32)).color(t.text_dim).size(t.font_small)).on_hover_text(group);
- }
- previous_group = group;
- let row = ui_kit::list_picker(ui, &choice.value, &compact_text(&choice.name, 32), choice.value == option.current_value);
- let row = row.on_hover_text(
- [choice.name.as_str(), choice.description.as_str()]
- .into_iter()
- .filter(|part| !part.is_empty())
- .collect::<Vec<_>>()
- .join("\n"),
- );
- crate::scenario::publish_handle(&format!("agent_chat:config:{}:{}", option.id, choice.value), row.rect.center());
- if option.category == "model" {
- crate::scenario::publish_handle(&format!("agent_chat:model:{}", choice.value), row.rect.center());
- }
- if row.clicked() {
- picked = Some(choice.value.clone());
+ let enabled = !pending && !option.options.is_empty();
+ let handles = format!("agent_chat:config:{}", option.id);
+ let response = if option.category == "model" {
+ let choices: Vec<ui_kit::SearchChoice<'_>> = option
+ .options
+ .iter()
+ .map(|choice| ui_kit::SearchChoice {
+ value: &choice.value,
+ label: &choice.name,
+ tip: &choice.description,
+ group: choice.group.as_deref(),
+ })
+ .collect();
+ let id = format!("sc_agent_config:{}", option.id);
+ let picker = ui
+ .allocate_ui(vec2(width, t.control_height), |ui| {
+ ui_kit::search_picker(
+ ui,
+ ui_kit::SearchPicker {
+ id: &id,
+ handles: &handles,
+ current: &displayed,
+ current_value: &option.current_value,
+ hint: tr("ui.agent_chat_model_search"),
+ choices: &choices,
+ custom: true,
+ note: None,
+ open_group: None,
+ enabled,
+ },
+ )
+ })
+ .inner;
+ picked = picker.inner;
+ // Under the names every kind of agent's model picker goes by.
+ let rows = format!("{handles}:");
+ for (name, at) in crate::scenario::handles(&rows) {
+ if let Some(row) = name.strip_prefix(&rows) {
+ crate::scenario::publish_handle(&format!("agent_chat:model:{row}"), at);
+ }
+ }
+ crate::scenario::publish_target("agent_chat:model", picker.response.rect);
+ picker.response
+ } else {
+ let response = ui
+ .add_enabled_ui(enabled, |ui| {
+ ui.allocate_ui(vec2(width, t.control_height), |ui| {
+ ui_kit::dropdown_menu(ui, ("sc_agent_config", &option.id), &displayed, |ui| {
+ let mut previous_group: Option<&str> = None;
+ for choice in &option.options {
+ let group = choice.group.as_deref().filter(|g| !g.is_empty());
+ if let Some(group) = group
+ && previous_group != Some(group)
+ {
+ ui.label(RichText::new(compact_text(group, 32)).color(t.text_dim).size(t.font_small)).on_hover_text(group);
+ }
+ previous_group = group;
+ let row = ui_kit::list_picker(ui, &choice.value, &compact_text(&choice.name, 32), choice.value == option.current_value);
+ let row = row.on_hover_text(
+ [choice.name.as_str(), choice.description.as_str()]
+ .into_iter()
+ .filter(|part| !part.is_empty())
+ .collect::<Vec<_>>()
+ .join("\n"),
+ );
+ crate::scenario::publish_handle(&format!("{handles}:{}", choice.value), row.rect.center());
+ if row.clicked() {
+ picked = Some(ui_kit::Picked::Listed(choice.value.clone()));
+ }
}
- }
+ })
})
+ .inner
})
- .inner
- })
- .inner;
- crate::scenario::publish_handle(&format!("agent_chat:config:{}", option.id), response.rect.center());
- crate::scenario::publish_rect(&format!("agent_chat:config:{}", option.id), response.rect);
- if option.category == "model" {
- crate::scenario::publish_handle("agent_chat:model", response.rect.center());
- } else if option.category == "mode" {
- crate::scenario::publish_handle("agent_chat:mode", response.rect.center());
- }
- response
- .widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, !pending && !option.options.is_empty(), format!("{name}: {selected}")));
+ .inner;
+ crate::scenario::publish_target(&handles, response.rect);
+ if option.category == "mode" {
+ crate::scenario::publish_handle("agent_chat:mode", response.rect.center());
+ }
+ response
+ };
+ response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, enabled, format!("{name}: {selected}")));
response.on_hover_text(tip);
- if let Some(value) = picked {
- super::set_config_option(app, &option.id, &value);
+ match picked {
+ Some(ui_kit::Picked::Listed(value)) => super::set_config_option(app, &option.id, &value),
+ Some(ui_kit::Picked::Custom(value)) => {
+ super::set_custom_model(app, &value);
+ }
+ None => {}
}
}
@@ -2347,7 +2373,7 @@ mod tests {
ui_kit::scope(ui, |ui| switcher(&mut app, ui));
});
output.textures_delta.clear();
- let rects: Vec<_> = ["switcher", "mode", "provider", "model"]
+ let rects: Vec<_> = ["switcher", "mode", "model"]
.into_iter()
.map(|name| {
let rect = crate::scenario::rect_of(&format!("agent_chat:{name}")).expect("picker retained");
diff --git a/crates/ui-egui/src/agent_chat/settings.rs b/crates/ui-egui/src/agent_chat/settings.rs
index 98527212b7..07f584e70b 100644
--- a/crates/ui-egui/src/agent_chat/settings.rs
+++ b/crates/ui-egui/src/agent_chat/settings.rs
@@ -38,6 +38,10 @@ pub struct AddState {
/// Editing an endpoint whose key is in the keychain: an empty key field keeps it.
pub saved_key: bool,
test: Option<Test>,
+ /// The endpoint the model picker lists: what the fields said when they were last left.
+ listing: Option<ListingKey>,
+ /// The fields were left, or the picker opened: take what they say now.
+ list_again: bool,
}
/// A connection test running or done.
@@ -80,6 +84,147 @@ pub struct State {
capabilities: std::collections::HashMap<(String, String), Option<bool>>,
#[cfg(not(target_arch = "wasm32"))]
checking: Option<CapabilityCheck>,
+ /// Endpoints' models as they were last listed here, or why they could not be.
+ endpoint_models: std::collections::HashMap<ListingKey, Result<Vec<acp::ModelInfo>, String>>,
+ #[cfg(not(target_arch = "wasm32"))]
+ listing: Option<ModelListing>,
+ /// An agent card's picker asked for this listing (with the agent whose key goes along).
+ #[cfg(not(target_arch = "wasm32"))]
+ card_listing: Option<(ListingKey, String)>,
+}
+
+/// What an endpoint's models are listed by: its protocol, its base URL, and whether a key goes along.
+type ListingKey = (Protocol, String, bool);
+
+/// Most endpoints' listings kept.
+const ENDPOINT_LISTINGS_CAP: usize = 128;
+
+/// The listing of `base_url`, if that is an address. A key goes along only where it may be sent.
+fn listing_key(protocol: Protocol, base_url: &str, with_key: bool) -> Option<ListingKey> {
+ let url = agents::normalize_url(base_url).ok().filter(|url| url.len() <= 4096)?;
+ let with_key = with_key && agents::key_safe_for(&url);
+ Some((protocol, url, with_key))
+}
+
+/// The models listed for `key`, and the note for under them: still listing, or why it could not.
+fn listed_for<'a>(
+ listings: &'a std::collections::HashMap<ListingKey, Result<Vec<acp::ModelInfo>, String>>,
+ key: Option<&ListingKey>,
+) -> (&'a [acp::ModelInfo], Option<String>) {
+ match key.and_then(|key| listings.get(key)) {
+ Some(Ok(models)) if models.is_empty() => (&[], Some(tr("ui.agent_chat_models_none").to_string())),
+ Some(Ok(models)) => (models, None),
+ Some(Err(error)) => (&[], Some(trf("ui.agent_chat_models_failed", &[("error", error)]))),
+ None => (&[], key.map(|_| tr("ui.agent_chat_models_listing").to_string())),
+ }
+}
+
+/// Whether a listing is worth asking for again: it failed, or it listed nothing.
+#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
+fn listing_wants_retry(listing: Option<&Result<Vec<acp::ModelInfo>, String>>) -> bool {
+ match listing {
+ Some(Err(_)) => true,
+ Some(Ok(models)) => models.is_empty(),
+ None => false,
+ }
+}
+
+/// `models` as a model picker's rows: the id chooses, the endpoint's name for it is searched too.
+fn model_choices<'a>(models: &'a [acp::ModelInfo], rows: &'a [(String, Option<String>, String)]) -> Vec<ui_kit::SearchChoice<'a>> {
+ models.iter().zip(rows).map(|(m, (label, group, tip))| ui_kit::SearchChoice { value: &m.id, label, tip, group: group.as_deref() }).collect()
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+struct ModelListing {
+ key: ListingKey,
+ rx: std::sync::mpsc::Receiver<Result<Vec<acp::ModelInfo>, String>>,
+}
+
+/// List an endpoint's models in the background, one listing at a time; a finished one stays until
+/// it is asked for again. `secret` runs on that thread too: a keychain may take its time to answer.
+#[cfg(not(target_arch = "wasm32"))]
+fn start_listing(app: &mut SolveApp, ctx: &egui::Context, key: ListingKey, secret: impl FnOnce() -> Result<Option<String>, String> + Send + 'static) {
+ let state = &mut app.agent_chat.settings;
+ if state.listing.is_some() || state.endpoint_models.contains_key(&key) {
+ return;
+ }
+ if state.endpoint_models.len() >= ENDPOINT_LISTINGS_CAP {
+ state.endpoint_models.clear();
+ }
+ let Some(http) = app.services.agent_http.clone() else {
+ state.endpoint_models.insert(key, Err(tr("ui.ai_no_http").to_string()));
+ return;
+ };
+ let (tx, rx) = std::sync::mpsc::channel();
+ let (protocol, url) = (key.0, key.1.clone());
+ let language = crate::i18n::language();
+ let wake = ctx.clone();
+ let spawned = std::thread::Builder::new().name("endpoint-models".into()).spawn(move || {
+ let _language = crate::i18n::scope(language);
+ let list = secret().and_then(|secret| match protocol {
+ Protocol::OpenAi => super::api_client::model_list(&http, &url, secret.as_deref()),
+ Protocol::Anthropic => super::api_client::anthropic_model_list(&http, &url, secret.as_deref()),
+ });
+ let _ = tx.send(list);
+ wake.request_repaint();
+ });
+ match spawned {
+ Ok(_) => state.listing = Some(ModelListing { key, rx }),
+ Err(e) => {
+ state.endpoint_models.insert(key, Err(e.to_string()));
+ }
+ }
+}
+
+/// Take in a finished listing, and start the one an agent card asked for.
+#[cfg(not(target_arch = "wasm32"))]
+pub(super) fn poll_listing(app: &mut SolveApp, ctx: &egui::Context) {
+ use std::sync::mpsc::TryRecvError;
+ let state = &mut app.agent_chat.settings;
+ if let Some(listing) = &state.listing {
+ let result = match listing.rx.try_recv() {
+ Ok(result) => result,
+ Err(TryRecvError::Disconnected) => Err(tr("ui.ai_no_answer").to_string()),
+ Err(TryRecvError::Empty) => return,
+ };
+ state.endpoint_models.insert(listing.key.clone(), result);
+ state.listing = None;
+ }
+ let Some((key, agent)) = state.card_listing.take() else { return };
+ let secrets = app.services.secrets.clone().filter(|_| key.2);
+ start_listing(app, ctx, key, move || match secrets {
+ Some(secrets) => secrets.get(&agent).map_err(|e| trf("ui.ai_keychain_error", &[("error", &e)])),
+ None => Ok(None),
+ });
+}
+
+/// The Add dialog's listing, of what its fields said when last left, never of a half-typed address.
+#[cfg(not(target_arch = "wasm32"))]
+fn list_for_dialog(app: &mut SolveApp, ctx: &egui::Context) {
+ let state = &mut app.agent_chat.settings;
+ let Some(s) = state.add.as_mut().filter(|s| s.kind == AddKind::Api) else { return };
+ let typed = Some(s.key.trim().to_string()).filter(|typed| !typed.is_empty());
+ // Editing an agent whose key is kept: the listing goes with that key, read on its thread.
+ let stored = s.editing.clone().filter(|_| s.saved_key && typed.is_none());
+ if std::mem::take(&mut s.list_again) {
+ s.listing = listing_key(s.protocol, &s.base_url, typed.is_some() || stored.is_some());
+ // Asked again: what failed may work now, with another key or the server back up.
+ if let Some(key) = &s.listing
+ && listing_wants_retry(state.endpoint_models.get(key))
+ {
+ state.endpoint_models.remove(key);
+ }
+ }
+ let Some(key) = s.listing.clone() else { return };
+ if state.listing.is_some() || state.endpoint_models.contains_key(&key) {
+ return;
+ }
+ let typed = typed.filter(|_| key.2);
+ let stored = stored.filter(|_| key.2).and_then(|agent| app.services.secrets.clone().map(|secrets| (secrets, agent)));
+ start_listing(app, ctx, key, move || match stored {
+ Some((secrets, agent)) => secrets.get(&agent).map_err(|e| trf("ui.ai_keychain_error", &[("error", &e)])),
+ None => Ok(typed),
+ });
}
#[cfg(not(target_arch = "wasm32"))]
@@ -171,6 +316,7 @@ pub fn open_add(app: &mut SolveApp) {
base_url: preset.map(|p| p.base_url.to_string()).unwrap_or_default(),
name: preset.map(|p| p.name.to_string()).unwrap_or_default(),
request_timeout_s: agents::DEFAULT_REQUEST_TIMEOUT_S,
+ list_again: true,
..Default::default()
});
}
@@ -185,6 +331,7 @@ pub fn open_edit(app: &mut SolveApp, id: &str) -> bool {
request_timeout_s: c.request_timeout_s.clamp(agents::MIN_REQUEST_TIMEOUT_S, agents::MAX_REQUEST_TIMEOUT_S),
reasoning_effort: c.reasoning_effort.clone(),
editing: Some(c.id.clone()),
+ list_again: true,
..Default::default()
};
if c.kind.is_api() {
@@ -222,6 +369,7 @@ pub(super) fn choose_preset(s: &mut AddState, protocol: Protocol, index: usize)
}
s.error = None;
s.test = None;
+ s.list_again = true;
}
/// Run a connection test in the background (it starts the agent briefly, or asks the endpoint
@@ -455,6 +603,7 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) {
let mut edit: Option<String> = None;
let mut retimed: Option<(String, u64)> = None;
let mut reeffort: Option<(String, String)> = None;
+ let mut picked_model: Option<(String, ui_kit::Picked)> = None;
let t = crate::theme::Tokens::get();
ui_kit::settings_section(ui, "agents", tr("ui.ai_agents"), |ui| {
if app.agent_chat.detecting.is_some() {
@@ -545,6 +694,55 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) {
None => {}
}
});
+ if let Some(protocol) = entry.kind.protocol() {
+ ui_kit::row(ui, tr("ui.ai_model"), |ui| {
+ let chat = &mut app.agent_chat;
+ let running = chat.running_id == entry.id && chat.backend.is_some();
+ let key = listing_key(protocol, &entry.base_url, entry.key);
+ let (models, note) = if running {
+ (chat.models.as_slice(), chat.models_note.clone())
+ } else if let Some(models) = chat.models_cache.get(&entry.base_url).filter(|models| !models.is_empty()) {
+ (models.as_slice(), None)
+ } else {
+ listed_for(&chat.settings.endpoint_models, key.as_ref())
+ };
+ let listed = !models.is_empty();
+ let rows = super::model_rows(models);
+ let choices = model_choices(models, &rows);
+ let id = format!("sc_ai_model:{}", entry.id);
+ let handles = format!("prefs:ai_model:{}", entry.id);
+ let picker = ui_kit::search_picker(
+ ui,
+ ui_kit::SearchPicker {
+ id: &id,
+ handles: &handles,
+ current: &entry.model,
+ current_value: &entry.model,
+ hint: tr("ui.agent_chat_model_search"),
+ choices: &choices,
+ custom: true,
+ note: note.as_deref(),
+ open_group: None,
+ enabled: true,
+ },
+ );
+ // Nobody is asked until the picker opens: not for looking at this page.
+ if picker.response.clicked()
+ && !running
+ && !listed
+ && let Some(key) = key
+ {
+ // Asked again: what failed may work now.
+ if listing_wants_retry(chat.settings.endpoint_models.get(&key)) {
+ chat.settings.endpoint_models.remove(&key);
+ }
+ chat.settings.card_listing = Some((key, entry.id.clone()));
+ }
+ if let Some(pick) = picker.inner {
+ picked_model = Some((entry.id.clone(), pick));
+ }
+ });
+ }
});
if entry.kind == Kind::Api
&& let Some(c) = app.preferences.agents.iter_mut().find(|c| c.id == entry.id)
@@ -594,6 +792,25 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) {
if let Some(id) = edit {
open_edit(app, &id);
}
+ if let Some((id, pick)) = picked_model {
+ if app.agent_chat.running_id == id && app.agent_chat.backend.is_some() {
+ match pick {
+ ui_kit::Picked::Listed(model) => set_model(app, &model),
+ ui_kit::Picked::Custom(model) => {
+ set_custom_model(app, &model);
+ }
+ }
+ } else {
+ let (ui_kit::Picked::Listed(model) | ui_kit::Picked::Custom(model)) = pick;
+ let model = model.trim();
+ if model_id_valid(model) {
+ if let Some(c) = app.preferences.agents.iter_mut().find(|c| c.id == id) {
+ c.model = model.to_string();
+ }
+ app.preferences.agent_models.insert(id, model.to_string());
+ }
+ }
+ }
// The running conversation uses a new timeout from its next request on.
if let Some((id, secs)) = retimed
&& app.agent_chat.running_id == id
@@ -748,10 +965,34 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) {
ui_kit::text_field(ui, &mut s.name, "");
});
ui_kit::row(ui, tr("ui.ai_base_url"), |ui| {
- ui_kit::text_field(ui, &mut s.base_url, tr("ui.ai_url_hint"));
+ s.list_again |=
+ ui_kit::cell_editor(ui, egui::Id::new("sc_ai_add_url"), &mut s.base_url, tr("ui.ai_url_hint"), false).lost_focus();
});
ui_kit::row(ui, tr("ui.ai_model"), |ui| {
- ui_kit::text_field(ui, &mut s.model, tr("ui.ai_model_hint"));
+ let (models, note) = listed_for(&app.agent_chat.settings.endpoint_models, s.listing.as_ref());
+ let rows = super::model_rows(models);
+ let choices = model_choices(models, &rows);
+ let current = if s.model.is_empty() { tr("ui.agent_chat_choose_model") } else { s.model.as_str() };
+ let picker = ui_kit::search_picker(
+ ui,
+ ui_kit::SearchPicker {
+ id: "sc_ai_add_model",
+ handles: "ai_add:model",
+ current,
+ current_value: &s.model,
+ hint: tr("ui.agent_chat_model_search"),
+ choices: &choices,
+ custom: true,
+ note: note.as_deref(),
+ open_group: None,
+ enabled: true,
+ },
+ );
+ s.list_again |= picker.response.clicked();
+ if let Some(ui_kit::Picked::Listed(model) | ui_kit::Picked::Custom(model)) = picker.inner {
+ s.model = model;
+ s.error = None;
+ }
});
ui_kit::row(ui, tr("ui.ai_request_timeout"), |ui| {
timeout_field(ui, &mut s.request_timeout_s, "ai_add:request_timeout");
@@ -764,6 +1005,7 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) {
let hint = tr(if s.saved_key { "ui.ai_key_keep_hint" } else { "ui.ai_key_hint" });
let r = ui_kit::password_field(ui, egui::Id::new("sc_ai_add_key"), &mut s.key, hint);
crate::scenario::publish_target("ai_add:key", r.rect);
+ s.list_again |= r.lost_focus();
});
});
ui_kit::text(ui, tr(if has_keychain { "ui.ai_key_note" } else { "ui.ai_no_keychain" }), ui_kit::Text::Note("keychain"));
@@ -782,6 +1024,8 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) {
}
add |= action == ui_kit::Action::Ok;
open &= !closed && action != ui_kit::Action::Cancel;
+ #[cfg(not(target_arch = "wasm32"))]
+ list_for_dialog(app, ctx);
if test {
#[cfg(not(target_arch = "wasm32"))]
if let Some(s) = app.agent_chat.settings.add.as_ref() {
@@ -1179,4 +1423,267 @@ mod card_tests {
assert_eq!(add_agent(&mut h.app), Err(tr("ui.ai_edit_gone").to_string()));
assert!(h.app.preferences.agents.is_empty());
}
+
+ /// An `agent_http` that may not be called on the window's thread: it answers `/models` as
+ /// OpenRouter does, or 401 for an address with `refused` in it, and records what it was asked.
+ fn listing_http(h: &mut Harness) -> std::sync::Arc<std::sync::Mutex<Vec<(String, bool)>>> {
+ let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
+ let log = seen.clone();
+ let ui_thread = std::thread::current().id();
+ h.app.services.agent_http = Some(std::sync::Arc::new(move |request: &super::super::backend::HttpRequest| {
+ assert_ne!(std::thread::current().id(), ui_thread);
+ // The running agent's capability check goes through here too.
+ if request.url.ends_with("/models")
+ && let Ok(mut log) = log.lock()
+ {
+ log.push((request.url.clone(), request.headers.iter().any(|(name, _)| name == "Authorization")));
+ }
+ if request.url.contains("refused") {
+ return Ok((401, br#"{"error":{"message":"no such key"}}"#.to_vec()));
+ }
+ if request.url.contains("/page/") {
+ return Ok((200, b"<!doctype html><html><body>Control UI</body></html>".to_vec()));
+ }
+ if request.url.contains("/empty/") {
+ return Ok((200, br#"{"data":[]}"#.to_vec()));
+ }
+ Ok((200, json!({"data": [{"id": "vendor/big", "name": "Vendor: Big"}, {"id": "vendor/small"}]}).to_string().into_bytes()))
+ }));
+ seen
+ }
+
+ /// A web page where the models should be, or a list with nothing in it, says so under the
+ /// picker, and is asked for again the next time.
+ #[test]
+ fn a_listing_that_is_no_list_or_lists_nothing_says_so_and_is_asked_again() {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.preferences.ai_features = true;
+ h.app.agent_chat.detection = Some(Default::default());
+ let seen = listing_http(&mut h);
+ let requests = || seen.lock().unwrap().len();
+ open_add(&mut h.app);
+ h.frames(3);
+ h.step(&json!({"click":{"handle":"ai_add:ui.ai_add_endpoint"}})).unwrap();
+ list_settled(&mut h);
+ assert_eq!(requests(), 1);
+ let note = |h: &Harness| {
+ let add = h.app.agent_chat.settings.add.as_ref().unwrap();
+ listed_for(&h.app.agent_chat.settings.endpoint_models, add.listing.as_ref()).1.unwrap_or_default()
+ };
+ // What the dialog's listing holds for the fields as they are (the words are the language's).
+ let listing = |h: &Harness| {
+ let add = h.app.agent_chat.settings.add.as_ref().unwrap();
+ add.listing.as_ref().and_then(|key| h.app.agent_chat.settings.endpoint_models.get(key)).cloned()
+ };
+ let ask = |h: &mut Harness, url: &str| {
+ let add = h.app.agent_chat.settings.add.as_mut().unwrap();
+ add.base_url = url.into();
+ add.list_again = true;
+ list_settled(h);
+ };
+ ask(&mut h, "http://localhost:18789/page/v1");
+ assert_eq!(requests(), 2);
+ assert!(matches!(listing(&h), Some(Err(_))), "a page where the list should be is an error: {:?}", listing(&h));
+ assert!(!note(&h).is_empty(), "and the picker says so");
+ ask(&mut h, "http://localhost:18789/page/v1");
+ assert_eq!(requests(), 3, "a page where the list should be is asked for again");
+ ask(&mut h, "http://localhost:18789/empty/v1");
+ assert_eq!(requests(), 4);
+ assert!(matches!(listing(&h), Some(Ok(models)) if models.is_empty()), "{:?}", listing(&h));
+ assert!(!note(&h).is_empty(), "an empty list is said so too");
+ ask(&mut h, "http://localhost:18789/empty/v1");
+ assert_eq!(requests(), 5, "an empty list is asked for again");
+ ask(&mut h, "http://localhost:11434/v1");
+ assert_eq!(requests(), 5, "a list that had models is kept");
+ assert_eq!(note(&h), "");
+ }
+
+ /// Editing an endpoint whose key is kept lists its models at once, with that key from the
+ /// keychain (never shown).
+ #[test]
+ fn editing_an_endpoint_lists_with_its_stored_key() {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.preferences.ai_features = true;
+ h.app.agent_chat.detection = Some(Default::default());
+ let keys = std::sync::Arc::new(MemoryKeys::default());
+ h.app.services.secrets = Some(keys.clone());
+ keys.set("api-1", "test-key-1").unwrap();
+ let seen = listing_http(&mut h);
+ let requests = || seen.lock().unwrap().clone();
+ h.app.preferences.agents.push(AgentConfig {
+ id: "api-1".into(),
+ name: "Endpoint".into(),
+ kind: Kind::Api,
+ base_url: "https://openrouter.ai/api/v1".into(),
+ model: "vendor/big".into(),
+ key: true,
+ ..Default::default()
+ });
+ h.call("ui.prefs", json!({"open": "AI"}));
+ h.frames(3);
+ assert!(open_edit(&mut h.app, "api-1"));
+ list_settled(&mut h);
+ assert_eq!(requests(), [("https://openrouter.ai/api/v1/models".to_string(), true)], "listed on opening, with the kept key");
+ assert!(h.app.agent_chat.settings.add.as_ref().unwrap().key.is_empty(), "the kept key stays out of the field");
+ }
+
+ fn list_settled(h: &mut Harness) {
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
+ h.frames(2);
+ while (h.app.agent_chat.settings.listing.is_some() || h.app.agent_chat.settings.card_listing.is_some())
+ && std::time::Instant::now() < deadline
+ {
+ std::thread::sleep(std::time::Duration::from_millis(1));
+ h.frames(1);
+ }
+ assert!(h.app.agent_chat.settings.listing.is_none());
+ h.frames(2);
+ }
+
+ /// The dialog lists an endpoint's models off the window's thread, once per endpoint and key, of
+ /// what the fields say when they are left and not while they are typed in; a key goes only
+ /// where it may. A row and a typed model both fill the field, and Add takes either.
+ #[test]
+ fn the_add_dialog_lists_an_endpoints_models_once_and_takes_a_row_or_a_typed_model() {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.preferences.ai_features = true;
+ h.app.agent_chat.detection = Some(Default::default());
+ let seen = listing_http(&mut h);
+ let requests = || seen.lock().unwrap().clone();
+ open_add(&mut h.app);
+ h.frames(3);
+ assert!(requests().is_empty(), "no endpoint chosen yet");
+ h.step(&json!({"click":{"handle":"ai_add:ui.ai_add_endpoint"}})).unwrap();
+ list_settled(&mut h);
+ assert_eq!(requests(), [("http://localhost:11434/v1/models".to_string(), false)]);
+ h.frames(5);
+ assert_eq!(requests().len(), 1, "once");
+
+ h.step(&json!({"click":{"handle":"ai_add:preset"}})).unwrap();
+ h.frames(3);
+ h.step(&json!({"click":{"handle":"ai_add:preset:OpenRouter"}})).unwrap();
+ list_settled(&mut h);
+ assert_eq!(requests().last().cloned(), Some(("https://openrouter.ai/api/v1/models".to_string(), false)));
+
+ // Typed in: no request until the field is left, which here the flag stands for.
+ let add = h.app.agent_chat.settings.add.as_mut().unwrap();
+ add.base_url = "http://10.0.0.2:1234/v1".into();
+ add.key = "not-a-real-key".into();
+ h.frames(5);
+ assert_eq!(requests().len(), 2, "not while it is typed");
+ h.app.agent_chat.settings.add.as_mut().unwrap().list_again = true;
+ list_settled(&mut h);
+ assert_eq!(
+ requests().last().cloned(),
+ Some(("http://10.0.0.2:1234/v1/models".to_string(), false)),
+ "no key over plain http to another computer"
+ );
+ let add = h.app.agent_chat.settings.add.as_mut().unwrap();
+ add.base_url = "https://openrouter.ai/api/v1".into();
+ add.list_again = true;
+ list_settled(&mut h);
+ assert_eq!(requests().last().cloned(), Some(("https://openrouter.ai/api/v1/models".to_string(), true)), "with a key is another listing");
+
+ // A row and a typed model.
+ assert!(scenario::handle_at("ai_add:model").is_some());
+ h.step(&json!({"click":{"handle":"ai_add:model"}})).unwrap();
+ h.frames(3);
+ assert!(scenario::handle_at("ai_add:model:search").is_some());
+ assert!(scenario::handle_at("ai_add:model:group:Vendor").is_some(), "an endpoint's vendors are the groups");
+ h.step(&json!({"click":{"handle":"ai_add:model:vendor/big"}})).unwrap();
+ h.frames(3);
+ assert_eq!(h.app.agent_chat.settings.add.as_ref().unwrap().model, "vendor/big");
+ h.step(&json!({"click":{"handle":"ai_add:model"}})).unwrap();
+ h.frames(3);
+ h.step(&json!({"text":"vendor/own:free"})).unwrap();
+ h.frames(3);
+ h.step(&json!({"click":{"handle":"ai_add:model:custom"}})).unwrap();
+ h.frames(3);
+ assert_eq!(h.app.agent_chat.settings.add.as_ref().unwrap().model, "vendor/own:free");
+ assert_eq!(requests().len(), 4, "opening the picker asks nobody again");
+
+ // A refusal shows in the popup, and opening it again asks again.
+ let add = h.app.agent_chat.settings.add.as_mut().unwrap();
+ add.base_url = "https://refused.example/v1".into();
+ add.key.clear();
+ add.list_again = true;
+ list_settled(&mut h);
+ h.step(&json!({"click":{"handle":"ai_add:model"}})).unwrap();
+ list_settled(&mut h);
+ assert_eq!(requests().len(), 6, "asked again on opening");
+ let listing = h.app.agent_chat.settings.add.as_ref().unwrap().listing.clone();
+ let (models, note) = listed_for(&h.app.agent_chat.settings.endpoint_models, listing.as_ref());
+ assert!(models.is_empty());
+ assert!(note.as_deref().is_some_and(|note| note.contains("no such key")), "{note:?}");
+ h.step(&json!({"key":"Escape"})).unwrap();
+ h.frames(3);
+ let add = h.app.agent_chat.settings.add.as_mut().unwrap();
+ add.base_url = "https://openrouter.ai/api/v1".into();
+ h.step(&json!({"click":{"handle":"ai_add:add"}})).unwrap();
+ assert!(h.app.agent_chat.settings.add.is_none());
+ assert_eq!(h.app.preferences.agents.last().map(|a| a.model.as_str()), Some("vendor/own:free"));
+ }
+
+ /// The keychain answers on the listing's thread, not on the window's.
+ struct KeyOffTheWindow(std::thread::ThreadId);
+ impl super::super::backend::Secrets for KeyOffTheWindow {
+ fn get(&self, _: &str) -> Result<Option<String>, String> {
+ assert_ne!(std::thread::current().id(), self.0);
+ Ok(Some("not-a-real-key".into()))
+ }
+ fn set(&self, _: &str, _: &str) -> Result<(), String> {
+ Ok(())
+ }
+ fn delete(&self, _: &str) -> Result<(), String> {
+ Ok(())
+ }
+ }
+
+ /// An endpoint's card has a model row. The page asks nobody; opening the picker lists, with the
+ /// agent's key from the keychain, and a row or a typed model becomes an idle agent's model.
+ #[test]
+ fn the_card_lists_when_its_picker_opens_and_changes_an_idle_endpoints_model() {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.preferences.ai_features = true;
+ h.app.agent_chat.detection = Some(Default::default());
+ h.app.services.secrets = Some(std::sync::Arc::new(KeyOffTheWindow(std::thread::current().id())));
+ let seen = listing_http(&mut h);
+ h.app.preferences.agents.push(AgentConfig {
+ id: "api-1".into(),
+ name: "Endpoint".into(),
+ kind: Kind::Api,
+ base_url: "http://localhost:1/v1".into(),
+ model: "local".into(),
+ key: true,
+ ..Default::default()
+ });
+ h.step(&json!({"call":"ui.prefs","params":{"open":"AI"}})).unwrap();
+ h.frames(4);
+ assert!(scenario::handle_at("prefs:ai_model:api-1").is_some());
+ assert!(seen.lock().unwrap().is_empty(), "looking at the page asks nobody");
+
+ h.step(&json!({"click":{"handle":"prefs:ai_model:api-1"}})).unwrap();
+ list_settled(&mut h);
+ assert_eq!(*seen.lock().unwrap(), [("http://localhost:1/v1/models".to_string(), true)]);
+ h.step(&json!({"click":{"handle":"prefs:ai_model:api-1:vendor/big"}})).unwrap();
+ h.frames(3);
+ let model = |h: &Harness| h.app.preferences.agents.iter().find(|a| a.id == "api-1").map(|a| a.model.clone());
+ assert_eq!(model(&h).as_deref(), Some("vendor/big"));
+ assert_eq!(h.app.preferences.agent_models.get("api-1").map(String::as_str), Some("vendor/big"));
+
+ h.step(&json!({"click":{"handle":"prefs:ai_model:api-1"}})).unwrap();
+ h.frames(3);
+ h.step(&json!({"text":" vendor/own "})).unwrap();
+ h.frames(3);
+ assert!(h.ctx.memory(|m| m.has_focus(egui::Id::new("sc_ai_model:api-1").with("search"))), "the box keeps the focus over Preferences");
+ h.step(&json!({"click":{"handle":"prefs:ai_model:api-1:custom"}})).unwrap();
+ h.frames(3);
+ assert_eq!(model(&h).as_deref(), Some("vendor/own"));
+ assert_eq!(h.app.preferences.agent_models.get("api-1").map(String::as_str), Some("vendor/own"));
+ assert_eq!(seen.lock().unwrap().len(), 1, "listed once");
+ }
}
diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs
index 9277669437..9f2054c916 100644
--- a/crates/ui-egui/src/agent_chat/tests.rs
+++ b/crates/ui-egui/src/agent_chat/tests.rs
@@ -1400,6 +1400,83 @@ fn models_reply(current: &str) -> Event {
Event::Models { current: current.into(), available: vec![m("fast"), m("smart")] }
}
+/// An endpoint's listing whose ids read `vendor/model` and whose names (the descriptions here) read
+/// `Vendor: Model`, as OpenRouter's, names its providers; the rows then read the model's name with
+/// the id as the tooltip. One vendor is one flat list.
+#[test]
+fn an_endpoints_vendor_named_listing_names_its_providers() {
+ let m = |id: &str, description: &str| acp::ModelInfo { id: id.into(), name: id.into(), description: description.into() };
+ assert_eq!(model_provider(&m("openai/gpt-6.1-terra", "OpenAI: GPT-6.1 Terra")), Some(("OpenAI".into(), "GPT-6.1 Terra".into())));
+ assert_eq!(model_provider(&m("openai/gpt-6.1-terra", "OpenAI: GPT-6.1 Terra\nmore")), Some(("OpenAI".into(), "GPT-6.1 Terra".into())));
+ assert_eq!(model_provider(&m("gpt-6.1-terra", "OpenAI: GPT-6.1 Terra")), None, "no vendor in the id");
+ assert_eq!(model_provider(&m("openai/gpt-6.1-terra", "OpenAI: ")), None, "no name");
+ assert_eq!(model_provider(&m("openai/gpt-6.1-terra", "")), None);
+ assert_eq!(
+ model_provider(&m("openai/gpt-6.1-terra", "Provider: Host • current")),
+ Some(("Host".into(), "openai/gpt-6.1-terra".into())),
+ "an agent's own word first"
+ );
+ let rows = model_rows(&[m("openai/gpt-6.1-terra", "OpenAI: GPT-6.1 Terra"), m("qwen/qwen3.8-flash", "Qwen: Qwen3.8 Flash"), m("free-model", "")]);
+ assert_eq!(
+ rows,
+ [
+ ("GPT-6.1 Terra".to_string(), Some("OpenAI".to_string()), "openai/gpt-6.1-terra".to_string()),
+ ("Qwen3.8 Flash".to_string(), Some("Qwen".to_string()), "qwen/qwen3.8-flash".to_string()),
+ ("free-model".to_string(), Some(tr("ui.agent_chat_provider_other").to_string()), String::new()),
+ ]
+ );
+ let rows = model_rows(&[m("openai/gpt-6.1-terra", "OpenAI: GPT-6.1 Terra"), m("openai/gpt-5.6-luna", "OpenAI: GPT-5.6 Luna")]);
+ assert_eq!(rows[0], ("openai/gpt-6.1-terra".to_string(), None, "OpenAI: GPT-6.1 Terra".to_string()), "one vendor is one flat list");
+}
+
+/// Models from several providers fold under their providers inside the picker: the current model's
+/// provider is open and the others folded; a header opens or folds its group; a typed search opens
+/// every group with a match but one folded by hand; the provider asked for over the control channel
+/// is open at the next opening.
+#[cfg(not(target_arch = "wasm32"))]
+#[test]
+fn the_header_groups_models_by_provider_and_folds_them() {
+ use crate::scenario::handle_at;
+ let mut h = narrow_chat();
+ let script = Script::default();
+ h.app.agent_chat.backend = Some(Box::new(script.clone()));
+ h.app.agent_chat.state = Some(State::Ready);
+ h.app.agent_chat.running_id = "claude".into();
+ let m = |id: &str, name: &str| acp::ModelInfo { id: id.into(), name: name.into(), description: String::new() };
+ script.report(Event::Models {
+ current: "a".into(),
+ available: vec![m("a", "Host · Alpha"), m("c", "Nous Portal · Gamma"), m("b", "Host · Beta"), m("d", "Nous Portal · Delta")],
+ });
+ h.frames(4);
+ assert!(handle_at("agent_chat:provider").is_none(), "no provider drop-down of its own");
+ h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap();
+ h.frames(3);
+ assert!(handle_at("agent_chat:model:group:Host").is_some() && handle_at("agent_chat:model:group:Nous Portal").is_some());
+ assert!(handle_at("agent_chat:model:a").is_some() && handle_at("agent_chat:model:b").is_some(), "the current model's provider is open");
+ assert!(handle_at("agent_chat:model:c").is_none() && handle_at("agent_chat:model:d").is_none(), "the other provider is folded");
+ h.step(&json!({"click": {"handle": "agent_chat:model:group:Nous Portal"}})).unwrap();
+ h.frames(3);
+ assert!(handle_at("agent_chat:model:c").is_some(), "a header opens its group");
+ h.step(&json!({"click": {"handle": "agent_chat:model:group:Host"}})).unwrap();
+ h.frames(3);
+ assert!(handle_at("agent_chat:model:a").is_none(), "and folds it");
+ h.step(&json!({"text": "ta"})).unwrap();
+ h.frames(3);
+ assert!(handle_at("agent_chat:model:b").is_none(), "a fold made by hand stays while searching, Beta or not");
+ assert!(handle_at("agent_chat:model:d").is_some() && handle_at("agent_chat:model:c").is_none(), "Delta matches, Gamma does not");
+ h.step(&json!({"click": {"handle": "agent_chat:model:d"}})).unwrap();
+ h.frames(3);
+ assert_eq!(script.calls(), ["set_model: d"]);
+ assert_eq!(h.app.agent_chat.model, "d");
+ assert!(handle_at("agent_chat:model:search").is_none(), "a choice closes it");
+
+ control(&mut h.app, &h.ctx, &json!({"provider": "Host"})).unwrap();
+ h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap();
+ h.frames(3);
+ assert!(handle_at("agent_chat:model:a").is_some(), "the provider asked for is open");
+ assert!(handle_at("agent_chat:model:d").is_some(), "and the current model's");
+}
+
/// Choosing a model tells the agent, shows it as current and remembers it for this agent; a model
/// the agent did not offer is ignored.
#[test]
@@ -1423,6 +1500,388 @@ fn choosing_a_model_sets_it_and_remembers_it() {
assert_eq!(app.agent_chat.models.len(), 2, "the list stays");
}
+/// A scripted endpoint: its agent is configured, and it is running with these models.
+#[cfg(not(target_arch = "wasm32"))]
+fn endpoint_with_script() -> (SolveApp, Script, egui::Context) {
+ let (mut app, script, ctx) = app_with_script();
+ let endpoint = "http://localhost:11434/v1";
+ app.agent_chat.running_id = "api-1".into();
+ app.agent_chat.running_endpoint = endpoint.into();
+ app.preferences.agents.push(agents::AgentConfig {
+ id: "api-1".into(),
+ kind: agents::Kind::Api,
+ base_url: endpoint.into(),
+ model: "fast".into(),
+ ..Default::default()
+ });
+ script.report(models_reply("fast"));
+ poll(&mut app, &ctx);
+ (app, script, ctx)
+}
+
+/// A typed model goes straight to an endpoint, joins the list for the next connection and becomes
+/// the agent's default.
+#[cfg(not(target_arch = "wasm32"))]
+#[test]
+fn a_typed_model_goes_to_an_endpoint_and_is_remembered() {
+ let (mut app, script, _ctx) = endpoint_with_script();
+ assert!(custom_models_accepted(&app));
+ assert!(set_custom_model(&mut app, " openai/gpt-x "));
+ assert_eq!(script.calls(), ["set_model: openai/gpt-x"]);
+ assert_eq!(app.agent_chat.models.first().map(|m| m.id.as_str()), Some("openai/gpt-x"));
+ assert_eq!(app.agent_chat.models_cache.get("http://localhost:11434/v1").and_then(|l| l.first()).map(|m| m.id.as_str()), Some("openai/gpt-x"));
+ assert_eq!(app.preferences.agents.iter().find(|a| a.id == "api-1").unwrap().model, "openai/gpt-x");
+ assert_eq!(app.preferences.agent_models.get("api-1").map(String::as_str), Some("openai/gpt-x"));
+ assert_eq!(status(&app)["model"], "openai/gpt-x");
+ assert_eq!(status(&app)["customModels"], true);
+ let listed = app.agent_chat.models.len();
+ assert!(set_custom_model(&mut app, "smart"));
+ assert_eq!(app.agent_chat.models.len(), listed, "a listed id goes the usual way");
+ assert_eq!(app.agent_chat.model, "smart");
+}
+
+/// A typed model is only sent when it could be a model at all, and the list stays within its cap.
+#[cfg(not(target_arch = "wasm32"))]
+#[test]
+fn a_typed_model_that_cannot_be_one_is_not_sent() {
+ let (mut app, script, _ctx) = endpoint_with_script();
+ for text in ["", " ", "x".repeat(MODEL_ID_CAP + 1).as_str(), "bell\u{7}", "two\nlines"] {
+ assert!(!set_custom_model(&mut app, text), "{text:?}");
+ }
+ assert!(script.calls().is_empty());
+ assert!(set_custom_model(&mut app, &"x".repeat(MODEL_ID_CAP)));
+ app.agent_chat.models =
+ (0..MODEL_LIST_CAP).map(|i| acp::ModelInfo { id: format!("m{i}"), name: String::new(), description: String::new() }).collect();
+ assert!(set_custom_model(&mut app, "one-more"));
+ assert_eq!(app.agent_chat.models.len(), MODEL_LIST_CAP);
+ assert_eq!(app.agent_chat.models.first().map(|m| m.id.as_str()), Some("one-more"));
+}
+
+/// An agent with a model option gets a typed model through it. Nothing changes until it answers,
+/// and a refusal leaves the old model with the agent's reason in the chat.
+#[test]
+fn a_typed_model_is_sent_to_a_modern_agent_and_a_rejection_keeps_the_old_one() {
+ let (mut app, script, ctx) = app_with_script();
+ app.agent_chat.running_id = "modern".into();
+ script.report(Event::ConfigOptions(modern_options("fast")));
+ poll(&mut app, &ctx);
+ assert!(custom_models_accepted(&app));
+ assert!(set_custom_model(&mut app, "claude-x"));
+ assert_eq!(script.calls(), ["set_config_option: some.provider.model=claude-x"]);
+ assert!(app.agent_chat.config_pending);
+ assert_eq!(app.agent_chat.model, "fast");
+ assert!(!set_custom_model(&mut app, "claude-y"), "one request at a time");
+
+ script.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Err("no such model".into()) });
+ poll(&mut app, &ctx);
+ assert!(!app.agent_chat.config_pending);
+ assert_eq!(app.agent_chat.model, "fast");
+ assert!(
+ app.agent_chat
+ .items
+ .iter()
+ .any(|i| matches!(i, Item::Notice { text, error: true } if text.contains("claude-x") && text.contains("no such model"))),
+ "the notice names the model and the reason"
+ );
+ assert!(!app.preferences.agent_models.contains_key("modern"));
+ assert_eq!(app.agent_chat.typed_model, None);
+
+ // An agent that takes it says so in its snapshot, and that is what is remembered.
+ assert!(set_custom_model(&mut app, "claude-x"));
+ script.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Ok(modern_options("claude-x")) });
+ poll(&mut app, &ctx);
+ assert_eq!(app.agent_chat.model, "claude-x");
+ assert_eq!(app.preferences.agent_models.get("modern").map(String::as_str), Some("claude-x"));
+}
+
+/// A legacy agent shows a typed model at once; a refusal puts everything back and says why.
+#[test]
+fn a_typed_model_is_sent_to_a_legacy_agent_and_a_rejection_reverts_it() {
+ let (mut app, script, ctx) = app_with_script();
+ app.agent_chat.running_id = "claude".into();
+ app.preferences.agent_models.insert("claude".into(), "fast".into());
+ script.report(models_reply("fast"));
+ poll(&mut app, &ctx);
+ assert!(set_custom_model(&mut app, "zzz"));
+ assert_eq!(script.calls(), ["set_model: zzz"]);
+ assert_eq!(app.agent_chat.model, "zzz");
+ assert_eq!(app.preferences.agent_models.get("claude").map(String::as_str), Some("zzz"));
+
+ script.report(Event::ModelRejected("no such model".into()));
+ poll(&mut app, &ctx);
+ assert_eq!(app.agent_chat.model, "fast");
+ assert_eq!(app.agent_chat.models.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["fast", "smart"]);
+ assert_eq!(app.preferences.agent_models.get("claude").map(String::as_str), Some("fast"));
+ assert!(
+ app.agent_chat
+ .items
+ .iter()
+ .any(|i| matches!(i, Item::Notice { text, error: true } if text.contains("zzz") && text.contains("no such model"))),
+ "the notice names the model and the reason"
+ );
+
+ // A listed model the agent refuses goes back too, and nothing was remembered before it here.
+ app.preferences.agent_models.remove("claude");
+ set_model(&mut app, "smart");
+ script.report(Event::ModelRejected("x".repeat(MODELS_NOTE_CAP * 2)));
+ poll(&mut app, &ctx);
+ assert_eq!(app.agent_chat.model, "fast");
+ assert_eq!(app.agent_chat.models.len(), 2);
+ assert!(!app.preferences.agent_models.contains_key("claude"));
+ let Some(Item::Notice { text, .. }) = app.agent_chat.items.last() else { panic!("no notice") };
+ assert_eq!(text.chars().count(), MODELS_NOTE_CAP);
+
+ // The agent confirming its model ends the wait: a later refusal has nothing to put back.
+ assert!(set_custom_model(&mut app, "zzz"));
+ script.report(Event::Models { current: "zzz".into(), available: vec![] });
+ script.report(Event::ModelRejected("late".into()));
+ poll(&mut app, &ctx);
+ assert_eq!(app.agent_chat.model, "zzz");
+}
+
+/// An agent that lists no models and has no model option cannot be sent one; a stopped one neither.
+#[test]
+fn an_agent_without_models_takes_no_typed_model() {
+ let (mut app, script, ctx) = app_with_script();
+ app.agent_chat.running_id = "other".into();
+ script.report(Event::Ready { agent: "fake".into(), images: false });
+ poll(&mut app, &ctx);
+ assert!(!custom_models_accepted(&app));
+ assert_eq!(status(&app)["customModels"], false);
+ assert!(!set_custom_model(&mut app, "zzz"));
+ assert!(script.calls().is_empty());
+ script.report(Event::ConfigOptions(vec![]));
+ poll(&mut app, &ctx);
+ assert!(!custom_models_accepted(&app), "its options name no model");
+
+ let (mut app, script, ctx) = app_with_script();
+ script.report(models_reply("fast"));
+ poll(&mut app, &ctx);
+ assert!(custom_models_accepted(&app));
+ app.agent_chat.backend = None;
+ assert!(!custom_models_accepted(&app));
+ assert!(!set_custom_model(&mut app, "zzz"));
+}
+
+/// The control channel's `model`: a listed one as before, an unlisted one when the agent takes
+/// typed models, otherwise ignored as before.
+#[cfg(not(target_arch = "wasm32"))]
+#[test]
+fn the_control_channel_sends_an_unlisted_model_where_it_can_go() {
+ let (mut app, script, ctx) = endpoint_with_script();
+ let reply = control(&mut app, &ctx, &json!({"model": "smart"})).unwrap();
+ assert_eq!(reply["model"], "smart");
+ let reply = control(&mut app, &ctx, &json!({"model": "unlisted"})).unwrap();
+ assert_eq!(reply["model"], "unlisted");
+ assert_eq!(reply["customModels"], true);
+ assert_eq!(reply["modelsNote"], Value::Null);
+ assert_eq!(script.calls(), ["set_model: smart", "set_model: unlisted"]);
+
+ let (mut app, script, ctx) = app_with_script();
+ let reply = control(&mut app, &ctx, &json!({"model": "unlisted"})).unwrap();
+ assert_eq!(reply["model"], "");
+ assert_eq!(reply["customModels"], false);
+ assert!(script.calls().is_empty());
+}
+
+/// The header's picker on an agent that lists models: it searches, a row chooses, and what was typed
+/// can be chosen too. The control and the popup stay in a narrow chat's window.
+#[test]
+fn the_header_model_picker_searches_and_takes_a_typed_model() {
+ use crate::scenario::{handle_at, rect_of};
+ let mut h = narrow_chat();
+ let script = Script::default();
+ h.app.agent_chat.backend = Some(Box::new(script.clone()));
+ h.app.agent_chat.state = Some(State::Ready);
+ h.app.agent_chat.running_id = "claude".into();
+ script.report(models_reply("fast"));
+ h.frames(4);
+ let panel = rect_of("agent_chat:panel").expect("the panel");
+ let control = rect_of("agent_chat:model").expect("the picker");
+ assert!(control.left() >= panel.left() && control.right() <= panel.right(), "{control:?} in {panel:?}");
+ assert!(handle_at("agent_chat:model:search").is_none(), "closed");
+
+ h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap();
+ h.frames(3);
+ for name in ["search", "fast", "smart"] {
+ assert!(handle_at(&format!("agent_chat:model:{name}")).is_some(), "{name}");
+ }
+ assert!(handle_at("agent_chat:model:custom").is_none(), "nothing typed");
+ let search = rect_of("agent_chat:model:search").expect("the search box");
+ assert!(search.left() >= 0.0 && search.right() <= 1600.0, "inside the harness's window: {search:?}");
+
+ h.step(&json!({"text": "SMA"})).unwrap();
+ h.frames(3);
+ assert!(handle_at("agent_chat:model:fast").is_none() && handle_at("agent_chat:model:smart").is_some());
+ assert!(handle_at("agent_chat:model:custom").is_some(), "the typed text is not a listed model");
+ h.step(&json!({"click": {"handle": "agent_chat:model:smart"}})).unwrap();
+ h.frames(3);
+ assert_eq!(script.calls(), ["set_model: smart"]);
+ assert_eq!(h.app.agent_chat.model, "smart");
+ assert!(handle_at("agent_chat:model:search").is_none(), "a choice closes it");
+
+ h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap();
+ h.frames(3);
+ h.step(&json!({"text": "zzz"})).unwrap();
+ h.frames(3);
+ h.step(&json!({"click": {"handle": "agent_chat:model:custom"}})).unwrap();
+ h.frames(3);
+ assert_eq!(script.calls(), ["set_model: smart", "set_model: zzz"]);
+ assert_eq!(h.app.agent_chat.model, "zzz");
+ disconnect(&mut h.app);
+}
+
+/// The picker on an agent with a model option goes by the same names. A row and a typed model both
+/// go through the option, and other options stay plain dropdowns.
+#[test]
+fn the_header_model_option_searches_and_takes_a_typed_model() {
+ use crate::scenario::handle_at;
+ let mut h = narrow_chat();
+ let script = Script::default();
+ h.app.agent_chat.backend = Some(Box::new(script.clone()));
+ h.app.agent_chat.state = Some(State::Ready);
+ script.report(Event::ConfigOptions(modern_options("fast")));
+ h.frames(4);
+ assert_eq!(handle_at("agent_chat:model"), handle_at("agent_chat:config:some.provider.model"));
+
+ h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap();
+ h.frames(3);
+ for name in ["search", "fast", "smart"] {
+ assert!(handle_at(&format!("agent_chat:model:{name}")).is_some(), "{name}");
+ assert_eq!(handle_at(&format!("agent_chat:model:{name}")), handle_at(&format!("agent_chat:config:some.provider.model:{name}")));
+ }
+ h.step(&json!({"click": {"handle": "agent_chat:model:smart"}})).unwrap();
+ h.frames(3);
+ assert_eq!(script.calls(), ["set_config_option: some.provider.model=smart"]);
+ script.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Ok(modern_options("smart")) });
+ h.frames(3);
+ assert_eq!(h.app.agent_chat.model, "smart");
+
+ h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap();
+ h.frames(3);
+ h.step(&json!({"text": "zzz"})).unwrap();
+ h.frames(3);
+ assert!(handle_at("agent_chat:model:custom").is_some());
+ h.step(&json!({"click": {"handle": "agent_chat:model:custom"}})).unwrap();
+ h.frames(3);
+ assert_eq!(script.calls().last().map(String::as_str), Some("set_config_option: some.provider.model=zzz"));
+ assert_eq!(h.app.agent_chat.model, "smart", "not until the agent says so");
+ assert!(h.app.agent_chat.config_pending);
+ disconnect(&mut h.app);
+}
+
+/// Nothing typed can be chosen where it could not be sent, and the reason a listing failed shows
+/// in the popup.
+#[test]
+fn the_header_model_picker_offers_no_typed_model_it_cannot_send_and_shows_why_listing_failed() {
+ use crate::scenario::handle_at;
+ let mut h = narrow_chat();
+ h.app.agent_chat.state = Some(State::Ready);
+ h.app.agent_chat.models = vec![acp::ModelInfo { id: "fast".into(), name: "fast".into(), description: String::new() }];
+ h.app.agent_chat.model = "fast".into();
+ h.app.agent_chat.models_note = Some("Couldn't list models: offline".into());
+ h.frames(4);
+ assert!(!custom_models_accepted(&h.app));
+ h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap();
+ h.frames(3);
+ assert!(h.widget("Couldn't list models: offline").is_some());
+ h.step(&json!({"text": "zzz"})).unwrap();
+ h.frames(3);
+ assert!(handle_at("agent_chat:model:search").is_some());
+ assert!(handle_at("agent_chat:model:custom").is_none());
+}
+
+/// A running endpoint's card uses the chat's list and changes the chat's model.
+#[cfg(not(target_arch = "wasm32"))]
+#[test]
+fn the_card_of_a_running_endpoint_changes_the_chats_model() {
+ use crate::scenario::handle_at;
+ let mut h = crate::scenario::Harness::new();
+ h.app.home.open = false;
+ h.app.preferences.ai_features = true;
+ h.app.agent_chat.detection = Some(Default::default());
+ let script = Script::default();
+ h.app.agent_chat.backend = Some(Box::new(script.clone()));
+ h.app.agent_chat.state = Some(State::Ready);
+ h.app.agent_chat.running_id = "api-1".into();
+ h.app.agent_chat.running_endpoint = "http://localhost:1/v1".into();
+ h.app.preferences.agents.push(agents::AgentConfig {
+ id: "api-1".into(),
+ name: "Endpoint".into(),
+ kind: agents::Kind::Api,
+ base_url: "http://localhost:1/v1".into(),
+ model: "fast".into(),
+ ..Default::default()
+ });
+ script.report(models_reply("fast"));
+ h.step(&json!({"call": "ui.prefs", "params": {"open": "AI"}})).unwrap();
+ h.frames(4);
+ h.step(&json!({"click": {"handle": "prefs:ai_model:api-1"}})).unwrap();
+ h.frames(3);
+ assert!(handle_at("prefs:ai_model:api-1:smart").is_some());
+ h.step(&json!({"click": {"handle": "prefs:ai_model:api-1:smart"}})).unwrap();
+ h.frames(3);
+ assert_eq!(script.calls(), ["set_model: smart"]);
+ assert_eq!(h.app.agent_chat.model, "smart");
+ h.step(&json!({"click": {"handle": "prefs:ai_model:api-1"}})).unwrap();
+ h.frames(3);
+ h.step(&json!({"text": "zzz"})).unwrap();
+ h.frames(3);
+ h.step(&json!({"click": {"handle": "prefs:ai_model:api-1:custom"}})).unwrap();
+ h.frames(3);
+ assert_eq!(script.calls(), ["set_model: smart", "set_model: zzz"]);
+ assert_eq!(h.app.preferences.agents.iter().find(|a| a.id == "api-1").map(|a| a.model.as_str()), Some("zzz"));
+ disconnect(&mut h.app);
+}
+
+/// A listing that fails says why and leaves last time's list, with the configured model in it; the
+/// next connection starts without the note.
+#[cfg(not(target_arch = "wasm32"))]
+#[test]
+fn a_listing_that_fails_says_why_and_keeps_the_list_of_last_time() {
+ let (mut app, script, ctx) = app_with_script();
+ let endpoint = "http://localhost:11434/v1";
+ app.agent_chat.running_endpoint = endpoint.into();
+ script.report(Event::ModelsNote(None));
+ script.report(models_reply("fast"));
+ poll(&mut app, &ctx);
+ assert_eq!(app.agent_chat.models_note, None);
+ let ids = |app: &SolveApp| app.agent_chat.models.iter().map(|m| m.id.clone()).collect::<Vec<_>>();
+ assert_eq!(ids(&app), ["fast", "smart"]);
+
+ let only = |id: &str| acp::ModelInfo { id: id.into(), name: id.into(), description: String::new() };
+ script.report(Event::ModelsNote(Some("x".repeat(MODELS_NOTE_CAP + 10))));
+ script.report(Event::Models { current: "local".into(), available: vec![only("local")] });
+ poll(&mut app, &ctx);
+ let note = app.agent_chat.models_note.clone().unwrap();
+ assert!(note.starts_with(&trf("ui.agent_chat_models_failed", &[("error", "x")])), "{note}");
+ assert_eq!(note.chars().count(), MODELS_NOTE_CAP);
+ assert_eq!(ids(&app), ["local", "fast", "smart"]);
+ assert_eq!(app.agent_chat.model, "local");
+ assert_eq!(app.agent_chat.models_cache.get(endpoint).map(Vec::len), Some(2), "the failed listing is not remembered");
+
+ script.report(Event::ModelsNote(Some("again".into())));
+ script.report(Event::Models { current: "fast".into(), available: vec![only("fast")] });
+ poll(&mut app, &ctx);
+ assert_eq!(ids(&app), ["local", "fast", "smart"], "a model already listed is not listed twice");
+
+ // A real listing on an endpoint that cannot be reached.
+ let mut app = app_with_endpoints();
+ app.agent_chat.models_note = Some("from before".into());
+ app.agent_chat.agent_id = Some("api-1".into());
+ connect(&mut app, &ctx);
+ assert_eq!(app.agent_chat.models_note, None);
+ let start = std::time::Instant::now();
+ while app.agent_chat.models.is_empty() && start.elapsed() < std::time::Duration::from_secs(10) {
+ poll(&mut app, &ctx);
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
+ assert!(app.agent_chat.models_note.as_deref().is_some_and(|note| note.contains("offline")), "{:?}", app.agent_chat.models_note);
+ assert_eq!(ids(&app), ["m"]);
+ assert!(models_shown(&app));
+ disconnect(&mut app);
+}
+
/// The next session puts back the model chosen last time, when the agent offers it.
#[test]
fn the_remembered_model_is_set_on_the_next_session() {
@@ -1944,7 +2403,8 @@ done
}
/// An agent that lists `models` but does not serve the unstable `session/set_model` answers
-/// "method not found": the choice stays and no error shows (#9970). Other errors still show.
+/// "method not found": the choice stays and no error shows (#9970). Other errors still show, as
+/// the refusal of the model they were about.
#[cfg(unix)]
#[test]
fn set_model_method_not_found_shows_no_error() {
@@ -1986,12 +2446,13 @@ done
set_model(&mut app, "fast");
// Replies come in order: once the second one's error shows, the first reply was handled too.
let t = std::time::Instant::now();
- while !errors(&app).iter().any(|e| e == "model unavailable") {
+ let refused = trf("ui.agent_chat_model_rejected", &[("model", "fast"), ("error", "model unavailable")]);
+ while !errors(&app).contains(&refused) {
poll(&mut app, &ctx);
assert!(t.elapsed() < std::time::Duration::from_secs(20), "no error for the second choice: {:?}", errors(&app));
std::thread::sleep(std::time::Duration::from_millis(10));
}
- assert_eq!(errors(&app), ["model unavailable"], "method not found is no error to show");
+ assert_eq!(errors(&app), [refused], "method not found is no error to show");
assert!(app.agent_chat.state().running(), "the chat goes on");
assert_eq!(std::fs::read_to_string(&log).unwrap().matches("session/set_model").count(), 2);
disconnect(&mut app);
diff --git a/crates/ui-egui/src/ui_kit/fields.rs b/crates/ui-egui/src/ui_kit/fields.rs
index af10715834..b93f4e07af 100644
--- a/crates/ui-egui/src/ui_kit/fields.rs
+++ b/crates/ui-egui/src/ui_kit/fields.rs
@@ -256,6 +256,397 @@ fn searchable_dropdown_with(
chosen
}
+/// Longest search text and custom value a `search_picker` takes.
+const SEARCH_TEXT_CAP: usize = 256;
+/// Characters of a label shown on a `search_picker` row, and of a tip or note shown with it.
+const SEARCH_LABEL_CAP: usize = 64;
+const SEARCH_NOTE_CAP: usize = 1024;
+/// Characters of a `search_picker` note shown under its list; the rest shows on hover.
+const SEARCH_NOTE_SHOWN: usize = 200;
+/// Rows a `search_picker` makes room for when it opens with none.
+const SEARCH_ROWS_AWAITED: usize = 6;
+
+/// One row of a `search_picker`. The value, label and tip are searched; `tip` also shows on hover,
+/// and a change of `group` between rows draws a heading.
+pub(crate) struct SearchChoice<'a> {
+ pub value: &'a str,
+ pub label: &'a str,
+ pub tip: &'a str,
+ pub group: Option<&'a str>,
+}
+
+/// What a `search_picker` shows.
+pub(crate) struct SearchPicker<'a> {
+ /// ComboBox id salt; it also keys the search text, so one per picker in the window.
+ pub id: &'a str,
+ /// Scenario names: the control `{handles}`, its box `{handles}:search`, its custom row
+ /// `{handles}:custom` and its rows `{handles}:{value}`.
+ pub handles: &'a str,
+ /// The text on the closed control, and the value of the row to highlight.
+ pub current: &'a str,
+ pub current_value: &'a str,
+ /// The search box's empty-text hint.
+ pub hint: &'a str,
+ pub choices: &'a [SearchChoice<'a>],
+ /// Offer what was typed as a value of its own when it is not a listed one.
+ pub custom: bool,
+ /// A dim line under the list: still listing, or why it could not.
+ pub note: Option<&'a str>,
+ /// With two or more groups, each folds under its header. Before anything is typed, only the
+ /// current value's group and this one are open (every group, when neither names one); a group
+ /// with a match opens once something is typed; a fold made by hand stays until the popup closes.
+ pub open_group: Option<&'a str>,
+ pub enabled: bool,
+}
+
+/// A `search_picker` choice: a listed value, or one typed into the box.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum Picked {
+ Listed(String),
+ Custom(String),
+}
+
+/// Dropdown whose popup opens on a focused search box over a list of `choices`, filtered as the
+/// box is typed in, with an optional row taking the typed text as a value of its own. Enter picks
+/// the exact or first match, else the typed text. Only the rows in view are laid out, so a long
+/// list stays cheap. Returns the pick and the control's response.
+/// Tokens: dropdown tokens, field tokens, `space_24`, `font_small`, `text_dim`, `form_card_width`.
+pub(crate) fn search_picker(ui: &mut Ui, p: SearchPicker<'_>) -> egui::InnerResponse<Option<Picked>> {
+ crate::prefs_search::note_current(ui, p.current);
+ // As in `dropdown_menu_with_close_behavior`: only a search probe skips the real control.
+ if crate::prefs_search::querying(ui)
+ && (!ui.is_visible() || (crate::prefs_search::suppress_chrome(ui) && !crate::prefs_search::texts_hit(ui, &[p.current])))
+ {
+ return egui::InnerResponse::new(None, crate::prefs_search::hidden_response(ui));
+ }
+ let state = egui::Id::new(p.id);
+ let mut picked = None;
+ let response = ui
+ .add_enabled_ui(p.enabled, |ui| {
+ let response = egui::ComboBox::from_id_salt(p.id)
+ .width(dimension(ui.available_width()))
+ .height(Tokens::get().space_24 * 20.0)
+ .selected_text(p.current)
+ .icon(dropdown_arrow)
+ .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
+ .show_ui(ui, |ui| picked = search_picker_popup(ui, &p, state))
+ .response;
+ // Closed: the next opening starts with an empty box that has the focus.
+ if !egui::ComboBox::is_open(ui.ctx(), response.id) {
+ ui.data_mut(|data| {
+ data.remove::<String>(state.with("filter"));
+ data.remove::<bool>(state.with("focused"));
+ data.remove::<f32>(state.with("height"));
+ data.remove::<SearchFolds>(state.with("folds"));
+ });
+ }
+ response
+ })
+ .inner;
+ publish(ui, &response, egui::WidgetType::ComboBox);
+ scenario::publish_target(p.handles, response.rect);
+ egui::InnerResponse::new(picked, response)
+}
+
+/// What a `search_picker` shows while it is open; the pick, if one was made this frame.
+fn search_picker_popup(ui: &mut Ui, p: &SearchPicker<'_>, state: egui::Id) -> Option<Picked> {
+ let t = Tokens::get();
+ let (filter_id, focused_id, folds_id) = (state.with("filter"), state.with("focused"), state.with("folds"));
+ // Esc closes this popup only: left in the input, it would also cancel a dialog around it.
+ if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {
+ ui.close();
+ }
+ ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
+ // The rows' text starts where the box's and the headings' do.
+ ui.spacing_mut().button_padding.x = t.form_inset;
+ ui.set_min_width(search_popup_width(ui, p));
+ let mut filter: String = ui.data(|data| data.get_temp(filter_id)).unwrap_or_default();
+ let search = ui.add(
+ text_input(egui::TextEdit::singleline(&mut filter))
+ .id(state.with("search"))
+ .char_limit(SEARCH_TEXT_CAP)
+ .hint_text(p.hint)
+ .background_color(t.input_fill())
+ .desired_width(f32::INFINITY),
+ );
+ t.input_bevel(ui, &search);
+ scenario::publish_target(&format!("{}:search", p.handles), search.rect);
+ // Asked until it has it: over a modal window egui drops the request of the opening's first frame.
+ if !ui.data(|data| data.get_temp::<bool>(focused_id)).unwrap_or(false) {
+ if search.has_focus() {
+ ui.data_mut(|data| data.insert_temp(focused_id, true));
+ } else {
+ search.request_focus();
+ ui.ctx().request_repaint();
+ }
+ }
+ if search.has_focus() {
+ crate::prefs_search::note_key_sink(ui.ctx());
+ }
+ if search.changed() {
+ ui.data_mut(|data| data.insert_temp(filter_id, filter.clone()));
+ }
+ let typed = filter.trim();
+ let query: String = typed.chars().flat_map(char::to_lowercase).collect();
+ // One buffer for every row: this runs each frame the popup is open, over a list of thousands.
+ let mut searched = String::new();
+ let mut hit = |choice: &SearchChoice<'_>| {
+ searched.clear();
+ for text in [choice.value, choice.label, choice.tip] {
+ searched.extend(text.chars().take(SEARCH_TEXT_CAP).flat_map(char::to_lowercase));
+ searched.push('\n');
+ }
+ searched.contains(&query)
+ };
+ let visible: Vec<&SearchChoice<'_>> = p.choices.iter().filter(|choice| query.is_empty() || hit(choice)).collect();
+ // Two or more groups fold under their headers: open by default are the current value's group,
+ // `open_group`, and every group once something is typed; a fold made by hand stays until the
+ // popup closes.
+ let grouped = search_groups(p.choices).iter().filter(|(group, _)| group.is_some()).count() >= 2;
+ let folds: SearchFolds = ui.data(|data| data.get_temp(folds_id)).unwrap_or_default();
+ let current_group = p.choices.iter().find(|c| c.value == p.current_value).and_then(|c| c.group).filter(|g| !g.is_empty());
+ let nothing_preferred = p.open_group.is_none() && current_group.is_none();
+ let is_open = |group: &str| {
+ folds.get(group).copied().unwrap_or(!query.is_empty() || nothing_preferred || Some(group) == p.open_group || Some(group) == current_group)
+ };
+ let rows = search_rows(&visible, grouped, &is_open);
+ let shown: Vec<&SearchChoice<'_>> = rows.iter().filter_map(|row| if let SearchRow::Choice(c) = row { Some(*c) } else { None }).collect();
+ let custom = (p.custom && !typed.is_empty() && !p.choices.iter().any(|c| c.value == typed)).then_some(typed);
+ let mut picked = None;
+ let mut toggled: Option<(String, bool)> = None;
+ if search.lost_focus() && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {
+ let found = visible.iter().find(|c| c.value == typed).or_else(|| shown.first());
+ picked = match (typed.is_empty(), found, custom) {
+ // Nothing asked for: the choice stands.
+ (true, ..) => {
+ ui.close();
+ None
+ }
+ (_, Some(choice), _) => Some(Picked::Listed(choice.value.to_owned())),
+ (_, None, Some(model)) => Some(Picked::Custom(model.to_owned())),
+ (_, None, None) => {
+ search.request_focus();
+ None
+ }
+ };
+ }
+ let width = ui.available_width();
+ let note = p.note.map(|note| {
+ let shown = compact(note, SEARCH_NOTE_SHOWN);
+ ui.painter().layout(shown, egui::FontId::proportional(t.font_small), t.text_dim, width)
+ });
+ let gap = ui.spacing().item_spacing.y;
+ let note_height = note.as_ref().map_or(0.0, |note| note.size().y + gap);
+ let row_height = row_height();
+ let most = ui.ctx().content_rect().height() - t.space_24 * 4.0;
+ // A popup's Ui stays within its size of the last frame, so it can't grow once it is open. All
+ // that can change below the box shares a height fixed when it opens, the list taking the rest.
+ let height = ui.data_mut(|data| {
+ *data.get_temp_mut_or_insert_with(state.with("height"), || {
+ let rows = p.choices.len() + search_groups(p.choices).iter().filter(|(group, _)| group.is_some()).count();
+ // No rows yet: they may still be on their way, and this can't grow to take them.
+ let rows = if rows == 0 { SEARCH_ROWS_AWAITED } else { rows };
+ let heading = t.space_16 + gap;
+ let custom = if p.custom { heading + row_height + gap } else { 0.0 };
+ let list = (rows as f32 * (row_height + gap)).clamp(custom + row_height + gap, t.space_24 * 10.0);
+ (heading + list + note_height).min(most).max(heading + custom + row_height + gap)
+ })
+ });
+ ui.allocate_ui(vec2(dimension(width), height), |ui| {
+ ui.set_min_height(height);
+ if let Some(model) = custom {
+ search_heading(ui, crate::i18n::tr("ui.agent_chat_custom_heading"), t.space_16);
+ let text = crate::i18n::format("ui.agent_chat_model_custom", &[("model", &compact(model, SEARCH_LABEL_CAP))]);
+ let row = search_row(ui, &text, false);
+ scenario::publish_target(&format!("{}:custom", p.handles), row.rect);
+ if row.clicked() {
+ picked = Some(Picked::Custom(model.to_owned()));
+ }
+ }
+ if !visible.is_empty() {
+ search_heading(ui, crate::i18n::tr("ui.agent_chat_models_heading"), t.space_16);
+ // Rows of one height, group headings too: only those in view are laid out.
+ let list = (ui.available_height() - note_height).max(row_height);
+ egui::ScrollArea::vertical()
+ .id_salt(state.with("list"))
+ .max_height(list)
+ .min_scrolled_height(list)
+ .auto_shrink([false, false])
+ .show_rows(ui, row_height, rows.len(), |ui, range| {
+ for row in rows.get(range).unwrap_or_default() {
+ match row {
+ SearchRow::Heading(group) => search_heading(ui, group, row_height),
+ SearchRow::Group { name, count, open } => {
+ let response = search_group_row(ui, name, *count, *open);
+ scenario::publish_target(&format!("{}:group:{}", p.handles, name), response.rect);
+ if response.clicked() {
+ toggled = Some(((*name).to_owned(), !*open));
+ }
+ }
+ SearchRow::Choice(choice) => {
+ let response = search_row(ui, &compact(choice.label, SEARCH_LABEL_CAP), choice.value == p.current_value);
+ scenario::publish_target(&format!("{}:{}", p.handles, choice.value), response.rect);
+ let response =
+ if choice.tip.is_empty() { response } else { response.on_hover_text(compact(choice.tip, SEARCH_NOTE_CAP)) };
+ if response.clicked() {
+ picked = Some(Picked::Listed(choice.value.to_owned()));
+ }
+ }
+ }
+ }
+ });
+ }
+ if let Some((group, open)) = toggled {
+ let mut folds = folds;
+ folds.insert(group, open);
+ ui.data_mut(|data| data.insert_temp(folds_id, folds));
+ // The click took the focus from the box; typing goes on filtering.
+ search.request_focus();
+ }
+ if let Some(note) = note {
+ let response = ui.add(egui::Label::new(note));
+ if let Some(whole) = p.note.filter(|whole| whole.chars().count() > SEARCH_NOTE_SHOWN) {
+ response.on_hover_text(compact(whole, SEARCH_NOTE_CAP));
+ }
+ }
+ });
+ if picked.is_some() {
+ ui.close();
+ }
+ picked
+}
+
+enum SearchRow<'a> {
+ /// A lone group's dim heading.
+ Heading(&'a str),
+ /// One of several groups: its header, with how many of its choices are listed, folded or open.
+ Group {
+ name: &'a str,
+ count: usize,
+ open: bool,
+ },
+ Choice(&'a SearchChoice<'a>),
+}
+
+/// The folds made by hand in one opening of a `search_picker`: group name to open.
+type SearchFolds = std::collections::HashMap<String, bool>;
+
+/// The groups among `choices` in order of first appearance, each with its choices; `None` is the
+/// choices with no group.
+fn search_groups<'a, 'c, I>(choices: I) -> Vec<(Option<&'a str>, Vec<&'c SearchChoice<'a>>)>
+where
+ 'a: 'c,
+ I: IntoIterator<Item = &'c SearchChoice<'a>>,
+{
+ let mut groups: Vec<(Option<&'a str>, Vec<&'c SearchChoice<'a>>)> = Vec::new();
+ for choice in choices {
+ let group = choice.group.filter(|g| !g.is_empty());
+ match groups.iter_mut().find(|(name, _)| *name == group) {
+ Some((_, members)) => members.push(choice),
+ None => groups.push((group, vec![choice])),
+ }
+ }
+ groups
+}
+
+/// The list's rows: each group's choices under its header, which folds them when there are several
+/// groups and is a plain heading when there is one; choices with no group as they are.
+fn search_rows<'a>(visible: &[&'a SearchChoice<'a>], grouped: bool, is_open: &dyn Fn(&str) -> bool) -> Vec<SearchRow<'a>> {
+ let mut rows = Vec::with_capacity(visible.len());
+ for (group, members) in search_groups(visible.iter().copied()) {
+ match group {
+ Some(name) if grouped => {
+ let open = is_open(name);
+ rows.push(SearchRow::Group { name, count: members.len(), open });
+ if open {
+ rows.extend(members.into_iter().map(SearchRow::Choice));
+ }
+ }
+ Some(name) => {
+ rows.push(SearchRow::Heading(name));
+ rows.extend(members.into_iter().map(SearchRow::Choice));
+ }
+ None => rows.extend(members.into_iter().map(SearchRow::Choice)),
+ }
+ }
+ rows
+}
+
+/// The header of one of several groups in a `search_picker`: a chevron, the name, how many of its
+/// choices are listed, and a rule. A click folds or opens the group.
+fn search_group_row(ui: &mut Ui, name: &str, count: usize, open: bool) -> Response {
+ let t = Tokens::get();
+ let (rect, response) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), row_height()), egui::Sense::click());
+ if !ui.is_rect_visible(rect) {
+ return response;
+ }
+ let painter = ui.painter();
+ if response.hovered() {
+ painter.rect_filled(rect, t.radius_sm, t.hover);
+ }
+ let y = rect.center().y;
+ super::disclosure(painter, egui::pos2(rect.left() + t.form_inset + t.space_8 * 0.5, y), open, t.text_dim);
+ let small = egui::FontId::proportional(t.font_small);
+ let title = painter.layout_no_wrap(compact(&name.to_uppercase(), SEARCH_LABEL_CAP), small.clone(), t.text);
+ let title_pos = egui::pos2(rect.left() + t.form_inset + t.space_16, y - title.size().y / 2.0);
+ let title_width = title.size().x;
+ painter.galley(title_pos, title, t.text);
+ let number = painter.layout_no_wrap(count.to_string(), small, t.text_dim);
+ let pad = t.space_8 * 0.75;
+ let badge_height = (number.size().y + pad).min(rect.height());
+ let badge = egui::Rect::from_min_size(
+ egui::pos2(title_pos.x + title_width + t.space_8, y - badge_height / 2.0),
+ vec2(number.size().x + pad * 2.0, badge_height),
+ );
+ painter.rect_filled(badge, t.radius_sm, t.chip);
+ painter.galley(egui::pos2(badge.left() + pad, y - number.size().y / 2.0), number, t.text_dim);
+ let (rule_from, rule_to) = (badge.right() + t.space_8, rect.right() - t.form_inset);
+ if rule_from < rule_to {
+ painter.hline(rule_from..=rule_to, y, egui::Stroke::new(1.0, t.border));
+ }
+ response.on_hover_text(crate::i18n::format("ui.agent_chat_provider_models", &[("count", &count.to_string())]))
+}
+
+/// A `search_picker` row: as `list_picker`, but read from the left, as a list of ids is.
+fn search_row(ui: &mut Ui, text: &str, selected: bool) -> Response {
+ ui.add_sized(vec2(dimension(ui.available_width()), row_height()), egui::Button::selectable(selected, (text, egui::Atom::grow())))
+}
+
+/// A dim one-line heading in a `search_picker`'s popup.
+fn search_heading(ui: &mut Ui, text: &str, height: f32) {
+ let t = Tokens::get();
+ let (rect, response) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), height), egui::Sense::hover());
+ paint_text(
+ ui,
+ rect.shrink2(vec2(t.form_inset, 0.0)),
+ &compact(text, SEARCH_LABEL_CAP),
+ egui::FontId::proportional(t.font_small),
+ t.text_dim,
+ false,
+ );
+ if text.chars().count() > SEARCH_LABEL_CAP {
+ response.on_hover_text(compact(text, SEARCH_NOTE_CAP));
+ }
+}
+
+/// A `search_picker` popup's width: the control's, wide enough for the longest label and to search
+/// in, and never wider than the window.
+fn search_popup_width(ui: &Ui, p: &SearchPicker<'_>) -> f32 {
+ let t = Tokens::get();
+ let longest = p.choices.iter().map(|c| c.label).max_by_key(|label| label.chars().take(SEARCH_LABEL_CAP + 1).count()).unwrap_or("");
+ let text = ui.painter().layout_no_wrap(compact(longest, SEARCH_LABEL_CAP), egui::TextStyle::Button.resolve(ui.style()), t.text).size().x;
+ let wanted = text + ui.spacing().button_padding.x * 2.0 + ui.spacing().scroll.bar_width + t.space_8;
+ let most = (ui.ctx().content_rect().width() - t.space_24 * 2.0).max(0.0);
+ dimension(wanted.max(ui.available_width()).max(t.form_card_width).min(most))
+}
+
+/// `text` cut to `max_chars`, with an ellipsis if anything was left out.
+fn compact(text: &str, max_chars: usize) -> String {
+ let mut chars = text.chars();
+ let short: String = chars.by_ref().take(max_chars).collect();
+ if chars.next().is_some() { format!("{short}…") } else { short }
+}
+
/// Completion/focus implementation shared by field variants. Tokens: `same as field`.
fn editor(ui: &mut Ui, value: &mut String, hint: &str, completion: bool) -> (bool, bool, Response) {
editor_reserving(ui, value, hint, completion, 0.0)
diff --git a/crates/ui-egui/src/ui_kit/fields_tests.rs b/crates/ui-egui/src/ui_kit/fields_tests.rs
index 0a84b8a16e..135c9a2477 100644
--- a/crates/ui-egui/src/ui_kit/fields_tests.rs
+++ b/crates/ui-egui/src/ui_kit/fields_tests.rs
@@ -122,6 +122,363 @@ fn searchable_dropdown_filters_selects_and_accepts_custom_values() {
}
}
+#[test]
+fn search_picker_filters_focuses_picks_and_takes_custom_values() {
+ let ctx = crate::fonts::test_context();
+ let picked = std::cell::RefCell::new(Vec::new());
+ let custom = std::cell::Cell::new(true);
+ let enabled = std::cell::Cell::new(true);
+ let choices = [
+ SearchChoice { value: "a/one", label: "One", tip: "The first model", group: None },
+ SearchChoice { value: "b/two", label: "Two", tip: "The second model", group: Some("Group") },
+ SearchChoice { value: "b/three", label: "Three", tip: "", group: Some("Group") },
+ ];
+ let draw = |ui: &mut Ui| {
+ row(ui, "Model", |ui| {
+ let shown = search_picker(
+ ui,
+ SearchPicker {
+ id: "search_picker_test",
+ handles: "test:model",
+ current: "One",
+ current_value: "a/one",
+ hint: "Search models…",
+ choices: &choices,
+ custom: custom.get(),
+ note: Some("Listing models…"),
+ open_group: None,
+ enabled: enabled.get(),
+ },
+ );
+ picked.borrow_mut().extend(shown.inner);
+ });
+ };
+ let open = || {
+ let at = scenario::handle_at("test:model").unwrap();
+ frame(&ctx, pointer(at, true), draw);
+ frame(&ctx, pointer(at, false), draw);
+ frame(&ctx, vec![], draw);
+ };
+ let click = |name: &str| {
+ let at = scenario::handle_at(name).unwrap_or_else(|| panic!("no {name}"));
+ frame(&ctx, pointer(at, true), draw);
+ frame(&ctx, pointer(at, false), draw);
+ frame(&ctx, vec![], draw);
+ };
+ let typing = |text: &str| {
+ frame(&ctx, vec![egui::Event::Text(text.into())], draw);
+ frame(&ctx, vec![], draw);
+ };
+ let is_open = || scenario::handle_at("test:model:search").is_some();
+ frame(&ctx, vec![], draw);
+ assert!(!is_open() && scenario::handle_at("test:model:a/one").is_none(), "closed: only the control");
+
+ // Opening focuses the box: what is typed filters over labels, tips and values.
+ open();
+ assert!(is_open());
+ assert!(ctx.memory(|m| m.has_focus(egui::Id::new("search_picker_test").with("search"))), "the box has the focus");
+ for row in ["a/one", "b/two", "b/three"] {
+ assert!(scenario::handle_at(&format!("test:model:{row}")).is_some(), "{row}");
+ }
+ assert!(scenario::handle_at("test:model:custom").is_none(), "nothing typed, nothing to use");
+ typing("SECOND");
+ assert!(scenario::handle_at("test:model:b/two").is_some(), "a tip is searched, whatever the case");
+ assert!(scenario::handle_at("test:model:a/one").is_none() && scenario::handle_at("test:model:b/three").is_none());
+ assert!(scenario::handle_at("test:model:custom").is_some(), "a substring is no listed value");
+
+ // A click picks the row, closes the popup and forgets the text.
+ click("test:model:b/two");
+ assert_eq!(picked.take(), [Picked::Listed("b/two".into())]);
+ assert!(!is_open());
+ open();
+ assert!(scenario::handle_at("test:model:a/one").is_some(), "the next opening starts unfiltered");
+
+ // A value exactly as listed needs no custom row; a text nothing matches gets one.
+ typing("b/three");
+ assert!(scenario::handle_at("test:model:custom").is_none());
+ assert!(scenario::handle_at("test:model:b/three").is_some());
+ frame(&ctx, key(egui::Key::Escape), draw);
+ frame(&ctx, vec![], draw);
+ assert!(!is_open() && picked.borrow().is_empty(), "Esc closes without a pick");
+ open();
+ typing(" vendor/model:free ");
+ assert!(scenario::handle_at("test:model:a/one").is_none());
+ click("test:model:custom");
+ assert_eq!(picked.take(), [Picked::Custom("vendor/model:free".into())], "trimmed");
+ assert!(!is_open());
+
+ // Enter picks the first row shown; with no match, the typed text.
+ open();
+ typing("t");
+ frame(&ctx, key(egui::Key::Enter), draw);
+ frame(&ctx, vec![], draw);
+ assert_eq!(picked.take(), [Picked::Listed("a/one".into())], "the first row with a t");
+ assert!(!is_open());
+ open();
+ typing("b/");
+ typing("three");
+ frame(&ctx, key(egui::Key::Enter), draw);
+ frame(&ctx, vec![], draw);
+ assert_eq!(picked.take(), [Picked::Listed("b/three".into())]);
+ open();
+ typing("nothing");
+ frame(&ctx, key(egui::Key::Enter), draw);
+ frame(&ctx, vec![], draw);
+ assert_eq!(picked.take(), [Picked::Custom("nothing".into())]);
+
+ // Enter on an empty box leaves the choice as it is.
+ open();
+ frame(&ctx, key(egui::Key::Enter), draw);
+ frame(&ctx, vec![], draw);
+ assert!(picked.borrow().is_empty() && !is_open());
+
+ // Without custom values, a miss offers nothing and Enter keeps the box.
+ custom.set(false);
+ open();
+ typing("nothing");
+ assert!(scenario::handle_at("test:model:custom").is_none());
+ frame(&ctx, key(egui::Key::Enter), draw);
+ frame(&ctx, vec![], draw);
+ assert!(picked.borrow().is_empty() && is_open());
+ typing("!");
+ frame(&ctx, key(egui::Key::Escape), draw);
+ frame(&ctx, vec![], draw);
+ assert!(!is_open());
+
+ // A disabled control does not open.
+ enabled.set(false);
+ open();
+ assert!(!is_open());
+}
+
+/// A long list costs only the rows in view, and a long label neither widens the popup past the
+/// window nor reaches past its edge.
+/// A popup can't grow once it is open, so what appears in it later must fit in the room it opened
+/// with: a custom row above a short list, a list that was empty, a note, and a list again after a
+/// search that matched nothing.
+#[test]
+fn search_picker_keeps_every_row_reachable_as_its_contents_change() {
+ use std::cell::{Cell, RefCell};
+ let ctx = crate::fonts::test_context();
+ let values = RefCell::new(vec!["a/one", "b/two"]);
+ let note: Cell<Option<&str>> = Cell::new(None);
+ let picked = RefCell::new(Vec::new());
+ let frame = |events: Vec<egui::Event>| {
+ scenario::clear_handles();
+ let raw =
+ egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))), ..Default::default() };
+ let _ = ctx.run_ui(raw, |ui| {
+ ui.allocate_ui(egui::vec2(160.0, 40.0), |ui| {
+ crate::ui_kit::scope(ui, |ui| {
+ let values = values.borrow();
+ let choices: Vec<SearchChoice<'_>> =
+ values.iter().map(|value| SearchChoice { value, label: value, tip: "", group: None }).collect();
+ let result = search_picker(
+ ui,
+ SearchPicker {
+ id: "search_picker_room",
+ handles: "room",
+ current: "b/two",
+ current_value: "b/two",
+ hint: "Search",
+ choices: &choices,
+ custom: true,
+ note: note.get(),
+ open_group: None,
+ enabled: true,
+ },
+ );
+ if let Some(pick) = result.inner {
+ picked.borrow_mut().push(pick);
+ }
+ });
+ });
+ });
+ };
+ let pointer = |at: egui::Pos2, pressed: bool| {
+ vec![
+ egui::Event::PointerMoved(at),
+ egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },
+ ]
+ };
+ let click = |name: &str| {
+ let at = scenario::handle_at(name).unwrap_or_else(|| panic!("no {name}"));
+ frame(pointer(at, true));
+ frame(pointer(at, false));
+ frame(vec![]);
+ frame(vec![]);
+ };
+ let typing = |text: &str| {
+ frame(vec![egui::Event::Text(text.into())]);
+ frame(vec![]);
+ frame(vec![]);
+ };
+ let erase = |times: usize| {
+ for _ in 0..times {
+ frame(vec![egui::Event::Key {
+ key: egui::Key::Backspace,
+ physical_key: None,
+ pressed: true,
+ repeat: false,
+ modifiers: egui::Modifiers::NONE,
+ }]);
+ frame(vec![]);
+ }
+ frame(vec![]);
+ };
+ frame(vec![]);
+ frame(vec![]);
+
+ // The custom row appears above the two rows: the row under it can still be clicked.
+ click("room");
+ typing("two");
+ assert!(scenario::handle_at("room:custom").is_some());
+ click("room:b/two");
+ assert_eq!(picked.take(), [Picked::Listed("b/two".into())]);
+
+ // A search that matches nothing leaves no list; taking it back brings the rows, in reach.
+ click("room");
+ typing("zzz");
+ assert!(scenario::handle_at("room:a/one").is_none());
+ frame(vec![]);
+ frame(vec![]);
+ erase(3);
+ click("room:b/two");
+ assert_eq!(picked.take(), [Picked::Listed("b/two".into())]);
+
+ // A list that arrives while it is open, with a long note, stays in reach; the custom row too.
+ values.borrow_mut().clear();
+ note.set(Some("Listing models…"));
+ frame(vec![]);
+ click("room");
+ frame(vec![]);
+ values.borrow_mut().extend(["a/one", "b/two", "c/three", "d/four"]);
+ note.set(Some("A long reason, repeated until it wraps over a few lines of the popup, repeated until it wraps over a few lines of the popup."));
+ frame(vec![]);
+ frame(vec![]);
+ typing("four");
+ click("room:d/four");
+ assert_eq!(picked.take(), [Picked::Listed("d/four".into())]);
+ click("room");
+ typing("nothing");
+ click("room:custom");
+ assert_eq!(picked.take(), [Picked::Custom("nothing".into())]);
+}
+
+#[test]
+fn search_picker_lays_out_the_rows_in_view_inside_a_narrow_window() {
+ let ctx = crate::fonts::test_context();
+ let values: Vec<String> = (0..2000).map(|n| format!("vendor/a-model-with-a-rather-long-name-{n:04}-and-then-some-more-of-it-and-more")).collect();
+ let choices: Vec<SearchChoice<'_>> = values.iter().map(|v| SearchChoice { value: v, label: v, tip: "", group: None }).collect();
+ let draw = |ui: &mut Ui| {
+ ui.allocate_ui(egui::vec2(120.0, 28.0), |ui| {
+ search_picker(
+ ui,
+ SearchPicker {
+ id: "search_picker_long",
+ handles: "test:long",
+ current: "One",
+ current_value: "",
+ hint: "",
+ choices: &choices,
+ custom: false,
+ note: None,
+ open_group: None,
+ enabled: true,
+ },
+ );
+ });
+ };
+ frame(&ctx, vec![], draw);
+ let at = scenario::handle_at("test:long").unwrap();
+ frame(&ctx, pointer(at, true), draw);
+ frame(&ctx, pointer(at, false), draw);
+ frame(&ctx, vec![], draw);
+ frame(&ctx, vec![], draw);
+ let rows = scenario::handles("test:long:vendor/");
+ assert!(!rows.is_empty() && rows.len() < 30, "{} rows laid out", rows.len());
+ let row = scenario::rect_of("test:long:vendor/a-model-with-a-rather-long-name-0000-and-then-some-more-of-it-and-more").unwrap();
+ assert!(row.left() >= 0.0 && row.right() <= 320.0, "{row:?} reaches past the window");
+ let search = scenario::rect_of("test:long:search").unwrap();
+ assert!(search.left() >= 0.0 && search.right() <= 320.0, "{search:?} reaches past the window");
+}
+
+/// Several groups fold under their headers: at first only the current value's group and the one
+/// asked for are open; a header opens or folds its group; a typed search opens the groups with a
+/// match but one folded by hand; Enter takes the first row shown; a fresh opening forgets the folds.
+#[test]
+fn search_picker_folds_groups_under_their_headers() {
+ let ctx = crate::fonts::test_context();
+ let picked = std::cell::RefCell::new(Vec::new());
+ let open_group = std::cell::Cell::new(None::<&'static str>);
+ let current = std::cell::Cell::new("b1");
+ let choices = [
+ SearchChoice { value: "a1", label: "Alpha one", tip: "", group: Some("A") },
+ SearchChoice { value: "b1", label: "Beta one", tip: "", group: Some("B") },
+ SearchChoice { value: "a2", label: "Alpha two", tip: "", group: Some("A") },
+ SearchChoice { value: "c1", label: "Gamma one", tip: "", group: Some("C") },
+ ];
+ let draw = |ui: &mut Ui| {
+ row(ui, "Model", |ui| {
+ let shown = search_picker(
+ ui,
+ SearchPicker {
+ id: "search_picker_groups",
+ handles: "grp",
+ current: "Beta one",
+ current_value: current.get(),
+ hint: "",
+ choices: &choices,
+ custom: false,
+ note: None,
+ open_group: open_group.get(),
+ enabled: true,
+ },
+ );
+ picked.borrow_mut().extend(shown.inner);
+ });
+ };
+ let click = |name: &str| {
+ let at = scenario::handle_at(name).unwrap_or_else(|| panic!("no {name}"));
+ frame(&ctx, pointer(at, true), draw);
+ frame(&ctx, pointer(at, false), draw);
+ frame(&ctx, vec![], draw);
+ };
+ let typing = |text: &str| {
+ frame(&ctx, vec![egui::Event::Text(text.into())], draw);
+ frame(&ctx, vec![], draw);
+ };
+ let has = |name: &str| scenario::handle_at(name).is_some();
+ frame(&ctx, vec![], draw);
+ click("grp");
+ assert!(has("grp:group:A") && has("grp:group:B") && has("grp:group:C"), "a header per group");
+ assert!(has("grp:b1") && !has("grp:a1") && !has("grp:c1"), "only the current value's group is open");
+ click("grp:group:A");
+ assert!(has("grp:a1") && has("grp:a2"), "a header opens its group");
+ click("grp:group:A");
+ assert!(!has("grp:a1"), "and folds it again");
+ typing("one");
+ assert!(!has("grp:a1"), "a fold made by hand stays while searching");
+ assert!(has("grp:b1") && has("grp:c1"), "groups with a match open");
+ frame(&ctx, key(egui::Key::Enter), draw);
+ frame(&ctx, vec![], draw);
+ assert_eq!(picked.take(), [Picked::Listed("b1".into())], "Enter takes the first row shown, not one folded away");
+ assert!(!has("grp:search"));
+
+ open_group.set(Some("C"));
+ click("grp");
+ assert!(!has("grp:a1") && has("grp:b1") && has("grp:c1"), "C opens as asked, B as the current value's, A folds");
+ frame(&ctx, key(egui::Key::Escape), draw);
+ frame(&ctx, vec![], draw);
+
+ open_group.set(None);
+ current.set("");
+ click("grp");
+ assert!(has("grp:a1") && has("grp:b1") && has("grp:c1"), "nothing to prefer: every group starts open");
+ frame(&ctx, key(egui::Key::Escape), draw);
+ frame(&ctx, vec![], draw);
+}
+
#[test]
fn preference_dropdown_keeps_disabled_choices_inert_and_closes_after_selection() {
let ctx = crate::fonts::test_context();
diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rs
index 608422d427..30c1a1ad45 100644
--- a/crates/ui-egui/src/ui_kit/gallery.rs
+++ b/crates/ui-egui/src/ui_kit/gallery.rs
@@ -1299,6 +1299,25 @@ const ELEMENTS: &[Element] = &[
searchable_dropdown(ui, "gallery", "One", &mut String::new(), &[SearchOption { value: "one", label: "One", handle: None }], None, None);
});
}),
+ element!("search_picker", "dialog:row:Gallery", Some("dialog:Gallery"), |ui, _| {
+ row(ui, "Gallery", |ui| {
+ search_picker(
+ ui,
+ SearchPicker {
+ id: "gallery_search_picker",
+ handles: "gallery:search_picker",
+ current: "One",
+ current_value: "one",
+ hint: "Search",
+ choices: &[SearchChoice { value: "one", label: "One", tip: "", group: None }],
+ custom: true,
+ note: None,
+ open_group: None,
+ enabled: true,
+ },
+ );
+ });
+ }),
element!("text_emphasis", "dialog:row:Gallery", Some("dialog:Bold"), |ui, s| {
row(ui, "Gallery", |ui| {
text_emphasis(ui, &mut s.checked, &mut false, true);
diff --git a/docs/agent-chat.md b/docs/agent-chat.md
index 0dd8cbded4..9a06bbd3e8 100644
--- a/docs/agent-chat.md
+++ b/docs/agent-chat.md
@@ -75,10 +75,22 @@ clicks and scrolling over the panel stay in the chat. The docked layout retains
the last model choice for each agent and puts it back on the next session when still available.
An endpoint's agent also keeps it as its default model. An agent that reports no choices shows
no drop-down. When these model lists include more than one provider (Hermes and OpenCode name
- each model `Provider · model`, or say `Provider: …` in its description), a provider drop-down
- comes first and the model drop-down lists only that provider's models, without the provider in
- front. It opens on the provider of the model in use; picking another provider changes nothing
- until one of its models is chosen. Models with no provider named are listed under *Other*.
+ each model `Provider · model`, or say `Provider: …` in its description), the picker groups the
+ models under their providers, each a header with the count of its models that a click folds or
+ opens: the provider of the model in use starts open and the others folded, a search opens every
+ provider with a match, and a provider folded by hand stays folded until the picker closes. Models
+ with no provider named are listed under *Other*. An endpoint whose listing names its models
+ `Vendor: Model` under ids `vendor/model` (OpenRouter) is grouped by vendor the same way; its rows
+ read the model's name, and the id stays in the tooltip and in the search.
+- **Picking a model.** Every model picker opens on a search box over the list the agent or endpoint
+ gave at this connection: SolidCraft has no list of its own. The search covers ids, names and
+ descriptions, and Enter takes the exact match or the first one shown. A model that isn't listed
+ can be typed: **Use custom: …** takes what is in the box, for an endpoint, an ACP agent with a
+ model option, or an older agent that listed models. An endpoint takes it as it is and keeps it as
+ its default model. An agent may refuse it: its model stays as it was and the chat says why. Only
+ an endpoint keeps a typed model for the next session; an agent gets it back only if it then
+ lists it. An endpoint that can't list its models (it has no such address, or refuses the key)
+ still shows its configured model, and the popup says why there are no others.
- **Reasoning effort is not permissions.** The agent's thinking setting does not change
SolidCraft's Ask / Edits / All approval policy. Reasoning options belong to the current session;
changing them here does not rewrite OpenCode's configuration or another OpenCode session.
@@ -246,16 +258,27 @@ Grok Build also supports `XAI_API_KEY` for users who choose API authentication.
- **Custom command:** any other program that speaks ACP on stdin and stdout, such as
`my-agent --acp`. SolidCraft starts it directly, not through a shell.
- **OpenAI-compatible API:** a preset (Ollama `http://localhost:11434/v1`, LM Studio
- `http://localhost:1234/v1`, OpenAI, Mammouth AI `https://api.mammouth.ai/v1`, OpenCode Go `https://opencode.ai/zen/go/v1`) or a custom URL, the model name, and an optional key.
+ `http://localhost:1234/v1`, OpenClaw `http://localhost:18789/v1`, OpenAI, Mammouth AI
+ `https://api.mammouth.ai/v1`, OpenCode Go `https://opencode.ai/zen/go/v1`, OpenRouter
+ `https://openrouter.ai/api/v1`) or a custom URL, the model name, and an optional key.
OpenCode Go models are routed to their endpoint by themselves (`/responses`,
`/messages` or Gemini for those families, `/chat/completions` for the rest),
each conversation request carrying the session header Go asks for, so one
preset covers every model.
A model the list does not know is retried on the next protocol when Go names
the mismatch.
+ For OpenClaw, turn on its chat endpoint (`gateway.http.endpoints.chatCompletions.enabled` in its
+ config) and use its gateway token as the key; the models it lists are its agents, such as `openclaw/default`.
- **Anthropic-compatible API:** a preset (Anthropic) or a custom URL, for an endpoint that
speaks the Anthropic Messages API (`{base}/v1/messages`). This covers Anthropic itself and
providers that offer an Anthropic-compatible endpoint, such as DeepSeek and Qwen.
+- The **Model** picker lists the endpoint's models, without a key where the endpoint allows that
+ (OpenRouter does), once you leave the address and key fields; opening it asks again after a
+ failure. You can also type a model.
+- An endpoint's card under Preferences → AI → **Agents** has the same **Model** picker. While the
+ agent isn't running, opening the picker lists the models (just viewing the page asks nothing),
+ and a pick becomes the model for its next connection. While it runs, a pick changes the chat's
+ model at once.
- The key goes into the system keychain (Keychain on macOS, Credential Manager on Windows, the
Secret Service on Linux) and is only ever sent over HTTPS or to this computer. **Test** asks an
OpenAI-compatible endpoint for its models; an Anthropic-compatible one gets a short message,
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 43440ed5ae..7bcd5ea29f 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -414,7 +414,7 @@ no box selection.
| `engine.execute` → `browser.expand_all` | `path?`: occurrence ids; `component?`: id; omit both for the whole tree | Open every Browser row under that scope, including folders that start closed (Origin, Named Views, Features). Display only: not saved in the design, not an undo step. |
| `engine.execute` → `browser.collapse_all` | same | Close those rows. The design row stays open when the whole tree is collapsed. |
| `engine.execute` → `view.history_layout` | `width?`, `dock?`: `bottom`, `left`, `under_browser`, `collapsed?` | Resize/dock the history without opening a dialog or changing the design. Contents respond to measured width; browser-stacked history shares its width and splits the height at the remembered share (`browser_share`, half until the seam between the two cards is dragged). One folded header gives the expanded card the rest; two folded headers stay at the top. |
-| `ui.agent_chat` | `features?`, `toolbar_button?`, `connect_at_start?` and `open_at_start?` (connect the agent started last, and open the panel, when SolidCraft starts; both off by default, never with `--control`), `permissions?` (`ask`, `edits`, `all`), `add_agent?` ({`name`, `kind`: `acp`, `api` or `anthropic` (`api` is OpenAI-compatible, `anthropic` Anthropic-compatible), `command` or `base_url` + `model` + `request_timeout_s?` (seconds one model request may take, 300 by default, rounded and clamped to 30 to 3600)}; no keys), `add_dialog?` (`installed`, `custom`, `api`, `anthropic`, or `false` to close), `edit_dialog?` (the id of an agent you added: the same dialog filled with what it holds, as its **Edit** button opens it; the key is never shown), `default_agent?`, `agent?` (the conversation's agent, by id), `mode?` (the agent's own mode), `provider?` (which provider's models the model picker lists, when they come from several), `model?` (one of its models), `open?`, `side?` (`left`, `right`), `minimized?`, `popped?` (in its own window), `width?`, `picker?`, `refresh?`, `connect?`, `stop?`, `attach?`: a file's path (a picture, a text file or a CAD file, for the next message; CAD files are imported at once), `remove_file?` (index of a file on the next message), `send?`: text (files alone make a message too), `attach_view?`, `attach_selection?`, `pick?` (true: open the context picker), `permission?`: an option id or `"cancel"` (the newest question of the agent's own), `approve?`: true, false or `"always"` (the oldest request held for Allow/Deny), `cancel?` (Stop: the queue stays), `send_now?` (stop the running step, then send the queued messages), `remove_pending?` (index), `new_chat?` (clear the chat, new session), `undo?` (the last message's changes) | the chat's state: `features`, `agents` (found and added), `currentAgent`, `state` (off, starting, ready, busy, auth, exited, failed: the agent never got ready, and Connect reads Retry), `connectAtStart`, `openAtStart`, `lastAgent` (the agent started last), `popped`, `window` (its place and size), `agent`, `modes`, `mode`, `models`, `model`, `modelWarning` (the model capability warning text, or `null` when unknown or tool support is reported; checked asynchronously and never blocks sending), `turnWarning` (the latest completed turn's no-tool notice, otherwise `null`; cleared on the next turn or new chat), `providers` (`name` and `count` of each, empty with one provider), `provider` (the one listed), `authMethods`, `toolsPort`, `pid`, `waiting`, `turn`, `pending` (queued messages, with their `files`), `attachments` (the files on the next message, by name), `loading` (pictures still being read for it, by name), `stopped`, `detection` and the conversation (`items`). With `features` off only the settings apply. Desktop only; see [Agent chat](agent-chat.md) |
+| `ui.agent_chat` | `features?`, `toolbar_button?`, `connect_at_start?` and `open_at_start?` (connect the agent started last, and open the panel, when SolidCraft starts; both off by default, never with `--control`), `permissions?` (`ask`, `edits`, `all`), `add_agent?` ({`name`, `kind`: `acp`, `api` or `anthropic` (`api` is OpenAI-compatible, `anthropic` Anthropic-compatible), `command` or `base_url` + `model` + `request_timeout_s?` (seconds one model request may take, 300 by default, rounded and clamped to 30 to 3600)}; no keys), `add_dialog?` (`installed`, `custom`, `api`, `anthropic`, or `false` to close), `edit_dialog?` (the id of an agent you added: the same dialog filled with what it holds, as its **Edit** button opens it; the key is never shown), `default_agent?`, `agent?` (the conversation's agent, by id), `mode?` (the agent's own mode), `provider?` (which provider's group the model picker opens first, when the models come from several), `model?` (one of its models, or see below), `open?`, `side?` (`left`, `right`), `minimized?`, `popped?` (in its own window), `width?`, `picker?`, `refresh?`, `connect?`, `stop?`, `attach?`: a file's path (a picture, a text file or a CAD file, for the next message; CAD files are imported at once), `remove_file?` (index of a file on the next message), `send?`: text (files alone make a message too), `attach_view?`, `attach_selection?`, `pick?` (true: open the context picker), `permission?`: an option id or `"cancel"` (the newest question of the agent's own), `approve?`: true, false or `"always"` (the oldest request held for Allow/Deny), `cancel?` (Stop: the queue stays), `send_now?` (stop the running step, then send the queued messages), `remove_pending?` (index), `new_chat?` (clear the chat, new session), `undo?` (the last message's changes) | the chat's state: `features`, `agents` (found and added), `currentAgent`, `state` (off, starting, ready, busy, auth, exited, failed: the agent never got ready, and Connect reads Retry), `connectAtStart`, `openAtStart`, `lastAgent` (the agent started last), `popped`, `window` (its place and size), `agent`, `modes`, `mode`, `models`, `model`, `modelWarning` (the model capability warning text, or `null` when unknown or tool support is reported; checked asynchronously and never blocks sending), `turnWarning` (the latest completed turn's no-tool notice, otherwise `null`; cleared on the next turn or new chat), `providers` (`name` and `count` of each, empty with one provider), `provider` (the one listed), `authMethods`, `toolsPort`, `pid`, `waiting`, `turn`, `pending` (queued messages, with their `files`), `attachments` (the files on the next message, by name), `loading` (pictures still being read for it, by name), `stopped`, `detection` and the conversation (`items`). With `features` off only the settings apply. Desktop only; see [Agent chat](agent-chat.md) |
| `ui.resize` | `width`, `height` | |
| `app.quit` | `force?` (quit without asking about unsaved designs) | `quitting` (the window closes), `asking` (a "save changes?" prompt is open) |
@@ -427,6 +427,12 @@ the agent's reply. Read the confirmed state after that reply; submitting a chang
confirmation. The existing `model` and `mode` inputs use the corresponding configuration option
when advertised, and retain their existing behavior for agents using legacy lists or API endpoints.
+`model` may also name a model the agent did not list, as the picker's custom row does: it goes to an
+API endpoint, to an agent with a model option, and to a legacy agent that listed models; the reply's
+`customModels` says whether this agent takes one. Otherwise it is ignored. A model an agent refuses
+leaves its previous model and adds a notice. `modelsNote` says why an endpoint's models could not be
+listed, or is `null`.
+
### `ui.prefs` settings
`render_previous_geometry_budget` (Graphics, default false) restores the previous fixed Render preview geometry budget: 512 MiB on 64-bit desktop, 128 MiB elsewhere. With it off, desktop uses the device-based budget.
diff --git a/docs/design/in-app-agent-chat.md b/docs/design/in-app-agent-chat.md
index bc6cd06c37..8085a5f7b6 100644
--- a/docs/design/in-app-agent-chat.md
+++ b/docs/design/in-app-agent-chat.md
@@ -126,8 +126,10 @@ requests, for a backend that runs tools in process). Two backends exist:
that speaks the Messages API), and runs the tool loop itself: it starts the same
`solidcraft-cli mcp --connect` server an ACP agent would get and is its MCP client
(`tools/list` becomes the endpoint's tools, `crash_reports` left out), so its calls pass the
- same gate, limits, questions and undo as an ACP agent's. At most 24 model requests per
- message. The HTTP request is the desktop host's (`Services::agent_http`, ureq with no
+ same gate, limits, questions and undo as an ACP agent's. There is no cap on model requests
+ per message; Stop ends it. It lists the endpoint's models at each connection (`Event::Models`),
+ and when it can't, `Event::ModelsNote` says why and only the configured model is offered. The
+ HTTP request is the desktop host's (`Services::agent_http`, ureq with no
redirects); the key comes from the system keychain (`Services::secrets`, the keyring crate)
for the connection only and is refused over plain HTTP to another computer. The two protocols
differ only in their wire shape: OpenAI sends the system note as a message, function tools
@@ -264,7 +266,7 @@ returns the whole state, for tests and screenshots.
| Area | Work |
|---|---|
| Conversation | Diffs, persisted conversation history, resume (`session/load`) |
-| Session controls | Model and mode pickers from `configOptions` / `modes`, slash commands |
+| Session controls | Slash commands |
| Auth | An embedded terminal or "open a terminal here" for terminal logins on each OS; logout |
| Discovery | Read the ACP registry; keychain-aware login check on macOS |
| Packaging | Make sure every desktop package ships `solidcraft-cli` next to `solidcraft` (Flatpak, AppImage, macOS bundle, Windows zip), or serve MCP from the app binary itself |
diff --git a/docs/ui-kit.md b/docs/ui-kit.md
index 742314845f..9e95888e07 100644
--- a/docs/ui-kit.md
+++ b/docs/ui-kit.md
@@ -232,6 +232,7 @@ table. Panel/Window/Confirm compositions also have dedicated geometry and intera
| `text_area` | Bounded multiline JSON/data editor | field tokens |
| `dropdown`, `dropdown_menu`, `compact_dropdown_menu` | Indexed choices or caller-supplied menu controls | `control_height`, `text_dim`, form tokens |
| `searchable_dropdown`, `SearchOption` | Filtered choices, custom-value action and pending message | dropdown tokens |
+| `search_picker`, `SearchPicker`, `SearchChoice`, `Picked` | Dropdown whose popup opens on a focused search box over rows filtered by value, label and tip, with group headings (two or more groups fold under headers with a count, the current value's open), per-row tips, an optional "use what was typed" row and a dim note; Enter picks the exact or first match, Esc closes the popup only; only the rows in view are laid out, and the popup keeps the height it opened with, the list taking what the rest leaves. Handles `{handles}`, `{handles}:search`, `{handles}:custom`, `{handles}:{value}`; returns the pick and the control's response | dropdown and field tokens, `space_16/24`, `font_small`, `text_dim`, `form_card_width` |
| `selection_field`, `Selection` | Selection chip with explicit `active` and `filled` state, in three looks: the active input (where the next pick goes) has a `form_primary` border and `selected_bg` tint; a filled inactive one a quiet neutral tint, a stronger neutral border and its count in `form_ink`; an empty inactive one the plain control with a dim prompt | `selected_bg/ink`, `form_primary/ink/dim`, `control_*`, `form_inset`, `space_2/8/24` |
| `value_pair` | Paired captions/expressions; optional independent field names | row/field tokens, `space_8` |
| `fraction_field`, `scalar_field`, `mixed_scalar_field` | Locale-aware bounded dimensionless values; scalar fields fill their control column; the mixed variant accepts a translated placeholder | form control/font tokens |