The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(tui): add, edit and delete a saved API from the Models view
bitcoinbuilderf9562ef564a8
diff --git a/tui/src/dialog.rs b/tui/src/dialog.rsindex 6264ec6c6..fa515cbfa 100644--- a/tui/src/dialog.rs+++ b/tui/src/dialog.rs@@ -73,7 +73,9 @@ pub fn areas(area: Rect, parts: Parts) -> Areas {/// [text] as lines of at most [width] columns, broken between words, in [style].pub fn wrap(text: &str, width: u16, style: Style) -> Vec<Line<'static>> {if text.is_empty() { return Vec::new() }- crate::workspace_menu::wrap(text, width as usize).into_iter().map(|l| Line::styled(l, style)).collect()+ // (Each line of [text] wrapped on its own: a line break starts a new line, an empty one a gap.)+ text.split('\n').flat_map(|para| if para.trim().is_empty() { vec![String::new()] } else { crate::workspace_menu::wrap(para, width as usize) })+ .map(|l| Line::styled(l, style)).collect()}/// [text] cut to [width] columns, ending in … where it was cut.diff --git a/tui/src/input.rs b/tui/src/input.rsindex 154a7ed13..b74121f58 100644--- a/tui/src/input.rs+++ b/tui/src/input.rs@@ -281,6 +281,7 @@ fn on_paste(app: &mut App, text: String) {chars.splice(at..at, pasted);prompt.value = chars.into_iter().collect();prompt.buttons = false;+ prompt.error.clear();return;}app.tab_mut().home = false;@@ -1761,10 +1762,10 @@ fn prompt_mouse(app: &mut App, mouse: MouseEvent) {if !matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left)) { return }let at = ratatui::layout::Position::new(mouse.column, mouse.row);let Some(Modal::Prompt(mut p)) = app.modal.take() else { return };- if !r.contains(at) { return after_prompt(app) }+ if !r.contains(at) { prompt_cancelled(app, &p); return after_prompt(app) }match p.row().click(a.row, at) {Some(1) => submit_prompt(app, p),- Some(_) => {}+ Some(_) => prompt_cancelled(app, &p),None => {if a.input.is_some_and(|i| i.contains(at)) { p.buttons = false }app.modal = Some(Modal::Prompt(p));@@ -1814,14 +1815,14 @@ fn prompt_key(app: &mut App, key: KeyEvent, mut p: Prompt) {let mut row = p.row();match row.key(key.code, key.modifiers) {crate::buttons::Answer::Chosen(1) => return submit_prompt(app, p),- crate::buttons::Answer::Chosen(_) | crate::buttons::Answer::Cancel => return,+ crate::buttons::Answer::Chosen(_) | crate::buttons::Answer::Cancel => return prompt_cancelled(app, &p),crate::buttons::Answer::Moved => p.chosen = row.chosen,crate::buttons::Answer::Ignored => {}}app.modal = Some(Modal::Prompt(p));return;}- if key.code == KeyCode::Esc { return }+ if key.code == KeyCode::Esc { return prompt_cancelled(app, &p) }}let (single, incremental, ptype) = match &p.kind { PromptKind::Command { one, incremental, ptype, .. } => (*one, *incremental, *ptype), PromptKind::Tree { ask, .. } => (false, false, ask.ptype()), _ => (false, false, 0) };// status-keys vi (tmux's default when $EDITOR names vi): Esc leaves insert for normal mode.@@ -1846,11 +1847,11 @@ fn prompt_key(app: &mut App, key: KeyEvent, mut p: Prompt) {let at = p.cursor.min(size);let space = |i: usize| chars.get(i) == Some(&' ');let in_list = |i: usize| chars.get(i).map(|c| ws.contains(*c)).unwrap_or(false);- let set = |p: &mut Prompt, v: Vec<char>, c: usize| { p.value = v.into_iter().collect(); p.cursor = c; };+ let set = |p: &mut Prompt, v: Vec<char>, c: usize| { p.value = v.into_iter().collect(); p.cursor = c; p.error.clear(); };let (mut changed, mut appended, mut prefix) = (false, false, '=');match key.code {- KeyCode::Esc => return,- KeyCode::Char('c' | 'g') if ctrl => return,+ KeyCode::Esc => return prompt_cancelled(app, &p),+ KeyCode::Char('c' | 'g') if ctrl => return prompt_cancelled(app, &p),KeyCode::Enter => {if !p.value.is_empty() && matches!(p.kind, PromptKind::Command { .. } | PromptKind::Tree { .. }) { add_history(app, ptype, &p.value) }// An incremental prompt has done its work as it went.@@ -3126,8 +3127,8 @@ fn choose(app: &mut App, kind: PickerKind, mut picker: Picker, choice: Choice) {PickerKind::Models if id.as_deref().is_some_and(crate::models::is_row) => {if !matches!(choice, Choice::Enter | Choice::SplitDown) { return keep(app, kind, picker) }crate::models::choose(app, &mut picker, id.as_deref().unwrap_or(""), choice == Choice::SplitDown);- // (Set up signed out opened the account page: the sign-in is shown, not this list.)- if matches!(app.modal, Some(Modal::Picker { kind: PickerKind::Account, .. })) { return }+ // (Set up signed out opened the account page, Add API its dialog: that is shown, not this list.)+ if app.modal.is_some() { return }fill(app, &kind, &mut picker);return keep(app, kind, picker);}@@ -3254,11 +3255,17 @@ fn store_install(app: &mut App, kind: PickerKind, mut picker: Picker) {app.modal = Some(Modal::Picker { kind, picker });}+/// A dialog put away without its answer: one of the Models view's goes back to the view.+fn prompt_cancelled(app: &mut App, p: &Prompt) {+ if let PromptKind::Api(draft) = &p.kind { crate::models::api_cancelled(app, draft) }+}+fn submit_prompt(app: &mut App, p: Prompt) {let value = p.value.trim().to_string();match p.kind {// Answered by a key press in prompt_key; nothing to submit.PromptKind::Key { .. } => {}+ PromptKind::Api(draft) => crate::models::api_answer(app, *draft, value),PromptKind::Tree { pane, ask } => crate::tree::answer(app, pane, ask, Some(&p.value)),PromptKind::Command { template, mut more, mut answers, one, digits, incremental, ptype, last } => {// The answer as typed (tmux keeps its spaces); the next prompt, if there is one.diff --git a/tui/src/modal.rs b/tui/src/modal.rsindex 1faaba66e..1186985df 100644--- a/tui/src/modal.rs+++ b/tui/src/modal.rs@@ -93,6 +93,8 @@ pub enum PromptKind {/// A prompt of choose-tree's for the tree in [pane]: search, filter, kill (one key), a/// command for the tagged items.Tree { pane: u64, ask: crate::tree::Ask },+ /// One step of adding or editing a saved API in the Models view: its name, its URL or its key.+ Api(Box<crate::models::ApiDraft>),}/// A line typed: tmux's in the status line (`(rename-window) name`, `:split-window -h`), hn's own@@ -119,16 +121,18 @@ pub struct Prompt {pub body: String,pub buttons: bool,pub chosen: usize,+ /// What was wrong with the last answer, under the input in the danger colour; typing clears it.+ pub error: String,}impl Prompt {pub fn status(kind: PromptKind, label: &str, initial: &str) -> Prompt {- Prompt { kind, title: String::new(), label: label.to_string(), hint: String::new(), value: initial.to_string(), secret: false, cursor: initial.chars().count(), history_at: None, vi_normal: false, saved: None, field: String::new(), body: String::new(), buttons: false, chosen: 1 }+ Prompt { kind, title: String::new(), label: label.to_string(), hint: String::new(), value: initial.to_string(), secret: false, cursor: initial.chars().count(), history_at: None, vi_normal: false, saved: None, field: String::new(), body: String::new(), buttons: false, chosen: 1, error: String::new() }}/// hn's own questions are dialogs; tmux's (command-prompt, choose-tree's) keep the status line.pub fn dialog(&self) -> bool {- matches!(self.kind, PromptKind::RenameTab { .. } | PromptKind::RenameHarness { .. } | PromptKind::Send | PromptKind::Broadcast | PromptKind::Answer { .. } | PromptKind::Message { .. })+ matches!(self.kind, PromptKind::RenameTab { .. } | PromptKind::RenameHarness { .. } | PromptKind::Send | PromptKind::Broadcast | PromptKind::Answer { .. } | PromptKind::Message { .. } | PromptKind::Api(_))}/// The dialog's `[ Cancel ] [ Rename ]` (Send, Broadcast, Answer), the chosen button only@@ -138,6 +142,7 @@ impl Prompt {PromptKind::RenameTab { .. } | PromptKind::RenameHarness { .. } => "Rename",PromptKind::Broadcast => "Broadcast",PromptKind::Answer { .. } => "Answer",+ PromptKind::Api(ref d) => if d.step == crate::models::ApiStep::Key { "Save" } else { "Next" },_ => "Send",};let button = |label: &str| crate::buttons::Button { label: label.into(), key: None };diff --git a/tui/src/models.rs b/tui/src/models.rsindex 5dbfb280a..6e58ff5f0 100644--- a/tui/src/models.rs+++ b/tui/src/models.rs@@ -198,15 +198,18 @@ pub fn section_words(s: &Section, asking: bool) -> Words {/// An API saved on this computer (`api_connections`) — its key stays in the daemon.#[derive(Clone, Debug, Default, PartialEq)]-pub struct Api { pub id: String, pub name: String, pub base_url: String, pub header: String, pub prefix: String }+pub struct Api { pub id: String, pub name: String, pub base_url: String, pub header: String, pub prefix: String, pub provider: String, pub key_env: String }impl Api {/// Coding agents send a custom endpoint only `Authorization: Bearer <key>`: only such an API/// lists models a harness can run on (the CLI's `servesModels`).pub fn serves_models(&self) -> bool { self.header.eq_ignore_ascii_case("authorization") && self.prefix.eq_ignore_ascii_case("bearer") }- pub fn host(&self) -> String { let rest = self.base_url.split_once("://").map(|(_, r)| r).unwrap_or(&self.base_url); rest.split(['/', '?', '#']).next().unwrap_or(rest).to_string() }+ pub fn host(&self) -> String { host_of(&self.base_url) }}+/// The host of [url]: `openrouter.ai` of `https://openrouter.ai/api/v1`.+pub fn host_of(url: &str) -> String { let rest = url.split_once("://").map(|(_, r)| r).unwrap_or(url); rest.split(['/', '?', '#']).next().unwrap_or(rest).to_string() }+/// One model an API lists: no key, only what the API says of it.#[derive(Clone, Debug, PartialEq)]pub struct ApiModel { pub id: String, pub name: Option<String>, pub context: Option<u64> }@@ -217,10 +220,37 @@ pub fn parse_apis(reply: &Value) -> Result<Vec<Api>, String> {Ok(rows.iter().filter_map(|c| {let s = |k: &str, d: &str| c[k].as_str().unwrap_or(d).to_string();let id = text(&c["id"])?;- Some(Api { id, name: s("name", ""), base_url: s("baseUrl", ""), header: s("authHeader", "Authorization"), prefix: s("authPrefix", "Bearer") })+ Some(Api { id, name: s("name", ""), base_url: s("baseUrl", ""), header: s("authHeader", "Authorization"), prefix: s("authPrefix", "Bearer"),+ provider: s("provider", "custom"), key_env: s("keyEnv", "") })}).collect())}+/// An API the daemon knows how to add (`api_connections`' `presets`): its name, where it answers and+/// where its key is made. OpenAI and Anthropic are left out, as the desktop's Add leaves them out:+/// their keys would stand in for the subscriptions above.+#[derive(Clone, Debug, PartialEq)]+pub struct ApiPreset { pub provider: String, pub name: String, pub base_url: String, pub key_url: String }++pub fn parse_api_presets(reply: &Value) -> Vec<ApiPreset> {+ reply["presets"].as_array().map(|rows| rows.iter().filter_map(|p| {+ let provider = text(&p["provider"])?;+ if matches!(provider.as_str(), "openai" | "anthropic") { return None }+ Some(ApiPreset { provider, name: text(&p["name"])?, base_url: text(&p["baseUrl"]).unwrap_or_default(), key_url: text(&p["keyUrl"]).unwrap_or_default() })+ }).collect()).unwrap_or_default()+}++/// Adding or editing a saved API, one dialog step at a time: a preset asks only its key, a Custom+/// API its name, then its URL, then its key (the desktop's form, as hn's dialogs ask). `id`: the+/// API being edited, whose key a blank answer keeps.+#[derive(Clone, Debug, PartialEq)]+pub struct ApiDraft {+ pub id: Option<String>, pub provider: String, pub name: String, pub base_url: String, pub key_url: String,+ pub key_env: String, pub header: String, pub prefix: String, pub step: ApiStep,+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub enum ApiStep { Name, Url, Key }+pub fn parse_api_models(reply: &Value) -> Option<Vec<ApiModel>> {Some(reply["models"].as_array()?.iter().filter_map(|m| Some(ApiModel {id: text(&m["id"])?, name: text(&m["name"]), context: m["contextWindow"].as_u64().filter(|w| *w > 0),@@ -362,6 +392,10 @@ pub struct Models {pub apis_at: Option<Instant>,pub api_models: HashMap<String, Result<Vec<ApiModel>, String>>,pub api_open: HashSet<String>,+ /// What the daemon can add (its presets; none from one too old to save), and whether Add API is+ /// showing them.+ pub api_presets: Vec<ApiPreset>,+ pub api_adding: bool,/// "More models": the whole catalog shown, not its first five.pub more: bool,/// A Set up asked of this computer's daemon and not yet answered; one that waits on a sign-in@@ -646,6 +680,12 @@ fn note(key: &str, words: &str, group: &str) -> Row {/// The row that sets grid up here (the desktop's `model:grid-setup`), and the note over an empty/// Your models whose Enter goes to the models to get.const SET_UP: &str = "mv:setup";+/// The APIs section's Add API row, the APIs it adds (`mv:apinew:<provider>`), and an opened API's Edit+/// connection and Delete (`…:<id>`).+const API_ADD: &str = "mv:apiadd";+const API_NEW: &str = "mv:apinew:";+const API_EDIT: &str = "mv:apiedit:";+const API_DELETE: &str = "mv:apidel:";const NONE_YET: &str = "mv:note:none";/// Grid is not set up on this computer (or its Set up is under way): the view offers to set it up.@@ -753,12 +793,13 @@ pub fn rows(app: &App, query: &str) -> Vec<Row> {// APIs saved on this computer: each folds its models until Enter (or a search) opens it.match &v.apis {Some(Err(why)) if !searching => out.push(note("apis", why, APIS)),- Some(Ok(apis)) => for api in apis {+ Some(Ok(apis)) => { for api in apis {let listed = v.api_models.get(&api.id);- let open = v.api_open.contains(&api.id) || searching;+ let opened = v.api_open.contains(&api.id);+ let open = opened || searching;let hint = match listed { _ if !api.serves_models() => "Tools".to_string(), Some(Ok(l)) if !l.is_empty() => format!("{} model{}", l.len(), if l.len() == 1 { "" } else { "s" }), None => "Loading…".into(), _ => "Tools".into() };out.push(Row::new(format!("mv:api:{}", api.id), api.name.clone()).group(APIS).extra(format!("{} api", api.host()))- .lead(vec![span(if open && api.serves_models() { "▾ " } else { "▸ " }, fg(theme::MUTED))])+ .lead(vec![span(if opened || (open && api.serves_models()) { "▾ " } else { "▸ " }, fg(theme::MUTED))]).detail(vec![span(api.host(), fg(theme::MUTED))]).right(hint));if !open { continue }if let Some(Ok(models)) = listed {@@ -774,7 +815,26 @@ pub fn rows(app: &App, query: &str) -> Vec<Row> {.right(format!("{word:>9}")));}}- },+ // Opened by hand (not by a search): what can be done to the API itself, under its models.+ if opened && !v.api_presets.is_empty() {+ let action = |id: String, label: &str, mark: &str, words: &str| Row::new(id, label).group(APIS).extra(format!("{} {words} api", api.name))+ .lead(vec![span(" ", Style::default()), span(mark.to_string(), fg(theme::MUTED))]);+ out.push(action(format!("{API_EDIT}{}", api.id), "Edit connection", "✎ ", "edit change key"));+ out.push(action(format!("{API_DELETE}{}", api.id), "Delete", "✕ ", "delete remove"));+ }+ }+ // Add API, last under them (and the only row when none is saved yet), and once opened the+ // APIs it adds: the daemon's presets, then Custom API. Not offered by a daemon too old to save.+ if !v.api_presets.is_empty() {+ out.push(Row::new(API_ADD, "Add API").group(APIS).extra("add new api key connection")+ .lead(vec![span(if v.api_adding { "− " } else { "+ " }, fg(theme::accent()))]));+ if v.api_adding {+ let choice = |id: String, label: &str, detail: String| Row::new(id, label).group(APIS).extra(format!("add {label} api"))+ .lead(vec![span(" ", Style::default()), span("· ", fg(theme::MUTED))]).detail(vec![span(detail, fg(theme::MUTED))]);+ for p in &v.api_presets { out.push(choice(format!("{API_NEW}{}", p.provider), &p.name, host_of(&p.base_url))) }+ out.push(choice(format!("{API_NEW}custom"), "Custom API", "any OpenAI-compatible API".into()));+ }+ } },_ => {}}@@ -895,6 +955,14 @@ pub enum Plan {SetUp,/// The cursor to row [0] (from the empty Your models' note to the first model to get).Select(String),+ /// Add API: its list of APIs to add, shown or hidden.+ ApiAdd,+ /// The dialog that adds the API of [0] (a preset's provider, or `custom`).+ ApiNew(String),+ /// The dialog that edits the saved API [0].+ ApiEdit(String),+ /// The saved API [0] and its key, removed from this computer.+ ApiRemove(String),}fn local_model(app: &App, id: &str) -> Option<LocalModel> { app.models_view.local.get(&app.fleet.local_id)?.models.iter().find(|m| m.id == id).cloned() }@@ -929,6 +997,13 @@ pub fn plan_enter(app: &App, id: &str) -> Plan {let v = &app.models_view;let say = |s: &str| Plan::Say(s.to_string());if id == "mv:more" { return Plan::More }+ if id == API_ADD { return Plan::ApiAdd }+ if let Some(provider) = id.strip_prefix(API_NEW) { return Plan::ApiNew(provider.to_string()) }+ if let Some(key) = id.strip_prefix(API_EDIT) { return Plan::ApiEdit(key.to_string()) }+ if let Some(key) = id.strip_prefix(API_DELETE) {+ let name = saved_api(app, key).map(|a| a.name).unwrap_or_else(|| "this API".into());+ return Plan::Arm(format!("Delete {name}? Its key leaves this computer. Enter · Esc"), Box::new(Plan::ApiRemove(key.to_string())));+ }if id == SET_UP { return if v.setting_up { say("Setting up…") } else { Plan::SetUp } }if id == NONE_YET {let head = catalog_heading(v.local.get(&app.fleet.local_id));@@ -1065,6 +1140,166 @@ fn run(app: &mut App, picker: &mut Picker, plan: Plan, key: &str) {}Plan::SetUp => set_up(app),Plan::Select(id) => picker.select(&id),+ Plan::ApiAdd => app.models_view.api_adding = !app.models_view.api_adding,+ Plan::ApiNew(provider) => api_begin(app, &provider),+ Plan::ApiEdit(key) => api_begin_edit(app, &key),+ Plan::ApiRemove(key) => { picker.say("Deleting…"); api_remove(app, &key) }+ }+}++// ── adding, editing and deleting a saved API ──────────────────────────────────────++fn saved_api(app: &App, id: &str) -> Option<Api> { app.models_view.apis.as_ref()?.as_ref().ok()?.iter().find(|a| a.id == id).cloned() }++/// Add API's [provider]: a preset asks only its key, under the preset's name (`OpenRouter 2` when one+/// is saved by that name already, as the desktop names it); Custom API starts at its name.+fn api_begin(app: &mut App, provider: &str) {+ let draft = if provider == "custom" {+ ApiDraft { id: None, provider: "custom".into(), name: String::new(), base_url: String::new(), key_url: String::new(), key_env: String::new(), header: String::new(), prefix: String::new(), step: ApiStep::Name }+ } else {+ let Some(p) = app.models_view.api_presets.iter().find(|p| p.provider == provider).cloned() else { return };+ let taken = |n: &str| app.models_view.apis.as_ref().and_then(|a| a.as_ref().ok()).is_some_and(|l| l.iter().any(|a| a.name.eq_ignore_ascii_case(n)));+ let (mut name, mut n) = (p.name.clone(), 2);+ while taken(&name) { name = format!("{} {n}", p.name); n += 1 }+ ApiDraft { id: None, provider: p.provider, name, base_url: p.base_url, key_url: p.key_url, key_env: String::new(), header: String::new(), prefix: String::new(), step: ApiStep::Key }+ };+ api_prompt(app, draft, "", "");+}++/// Edit connection: a preset's key alone; a Custom API's name, URL and key. Its key variable, header+/// and prefix go back as they are (a save without them would put the defaults back).+fn api_begin_edit(app: &mut App, id: &str) {+ let Some(a) = saved_api(app, id) else { return };+ let custom = a.provider == "custom" || !app.models_view.api_presets.iter().any(|p| p.provider == a.provider);+ let key_url = app.models_view.api_presets.iter().find(|p| p.provider == a.provider).map(|p| p.key_url.clone()).unwrap_or_default();+ let name = a.name.clone();+ let draft = ApiDraft { id: Some(a.id), provider: a.provider, name: a.name, base_url: a.base_url, key_url, key_env: a.key_env, header: a.header, prefix: a.prefix,+ step: if custom { ApiStep::Name } else { ApiStep::Key } };+ api_prompt(app, draft, if custom { &name } else { "" }, "");+}++/// The dialog for [draft]'s step, [value] in its input and [error] under it.+fn api_prompt(app: &mut App, draft: ApiDraft, value: &str, error: &str) {+ let editing = draft.id.is_some();+ let title = if editing { format!("Edit {}", draft.name) } else if draft.provider == "custom" { "Add Custom API".into() } else { format!("Add {}", draft.name) };+ let (field, body) = match draft.step {+ ApiStep::Name => ("Name", "Any OpenAI-compatible API. Harnesses can run on its models.".to_string()),+ ApiStep::Url => ("URL", "Its base URL, for example https://api.example.com/v1".to_string()),+ ApiStep::Key if editing => ("Key", "Leave it blank to keep the saved key.".to_string()),+ ApiStep::Key => ("Key", [draft.base_url.clone(), if draft.key_url.is_empty() { String::new() } else { format!("Get a key: {}", draft.key_url) }, "The key stays on this computer.".into()]+ .into_iter().filter(|l| !l.is_empty()).collect::<Vec<_>>().join("\n")),+ };+ let secret = draft.step == ApiStep::Key;+ let mut p = crate::modal::Prompt::status(crate::modal::PromptKind::Api(Box::new(draft)), "", value);+ (p.title, p.field, p.body, p.secret, p.error) = (title, field.into(), body, secret, error.into());+ app.modal = Some(crate::modal::Modal::Prompt(p));+}++/// A step answered: the next one, the same again with what was wrong, or the save.+pub fn api_answer(app: &mut App, mut draft: ApiDraft, value: String) {+ match draft.step {+ ApiStep::Name => {+ if value.is_empty() { return api_prompt(app, draft, "", "Enter a name for this API.") }+ draft.name = value;+ draft.step = ApiStep::Url;+ let url = draft.base_url.clone();+ api_prompt(app, draft, &url, "");+ }+ ApiStep::Url => {+ if let Some(why) = url_problem(&value) { return api_prompt(app, draft, &value, why) }+ draft.base_url = value.trim_end_matches('/').to_string();+ draft.step = ApiStep::Key;+ api_prompt(app, draft, "", "");+ }+ ApiStep::Key => {+ if draft.id.is_none() && value.is_empty() { return api_prompt(app, draft, "", "Paste the API key.") }+ api_save(app, draft, value);+ }+ }+}++/// What is wrong with [text] as an API's URL (the desktop's `apiUrlProblem`); None when nothing.+pub fn url_problem(text: &str) -> Option<&'static str> {+ const FULL: &str = "Enter the full URL, starting with https://, for example https://openrouter.ai/api/v1.";+ let v = text.trim();+ if v.is_empty() { return Some("Enter the API's URL.") }+ let Some((scheme, rest)) = v.split_once("://") else { return Some(FULL) };+ let authority = rest.split(['/', '?', '#']).next().unwrap_or("");+ if !matches!(scheme.to_ascii_lowercase().as_str(), "http" | "https") || v.contains(char::is_whitespace) { return Some(FULL) }+ if authority.contains('@') { return Some("Take the username or password out of the URL. The key has its own field.") }+ let host = match authority.rsplit_once(':') { Some((h, port)) if port.chars().all(|c| c.is_ascii_digit()) => h, _ => authority };+ if host.is_empty() { return Some(FULL) }+ if rest.contains(['?', '#']) { return Some("Take the ? or # part off the end of the URL.") }+ None+}++/// Saved through this computer's daemon (`api_connections` save). The key goes only into that+/// request: never into a line said, a log, or the prompt's history.+fn api_save(app: &mut App, draft: ApiDraft, key: String) {+ let machine = app.fleet.local_id.clone();+ let mut connection = json!({ "provider": draft.provider, "name": draft.name, "baseUrl": draft.base_url });+ if let Some(id) = &draft.id { connection["id"] = json!(id); connection["keyEnv"] = json!(draft.key_env); connection["authHeader"] = json!(draft.header); connection["authPrefix"] = json!(draft.prefix); }+ if !key.is_empty() { connection["apiKey"] = json!(key) }+ app.say(format!("Saving {}…", draft.name), theme::SOFT);+ let (m, d, k) = (machine.clone(), draft.clone(), key.clone());+ if !rpc(app, &machine, "api_connections", json!({ "action": "save", "connection": connection }), Duration::from_secs(20), move |app, reply| on_api_saved(app, &m, d, k, reply)) {+ api_prompt(app, draft, &key, "This computer is not connected. Try again.");+ }+}++/// Saved: the list again, the new API open under it, and the Models view back on it. Refused: the+/// same step again, with what the daemon said (a name already used goes back to the name).+pub fn on_api_saved(app: &mut App, machine: &str, draft: ApiDraft, key: String, reply: Result<Value, RpcError>) {+ match reply {+ Ok(r) => {+ on_apis_from(app, machine, Ok(r));+ let id = app.models_view.apis.as_ref().and_then(|a| a.as_ref().ok()).and_then(|l| l.iter().find(|a| a.name.eq_ignore_ascii_case(&draft.name)).map(|a| a.id.clone()));+ app.models_view.api_adding = false;+ if let Some(id) = &id {+ app.models_view.api_open.insert(id.clone());+ app.models_view.api_models.remove(id);+ read_api_models(app, id);+ }+ app.say(format!("Saved {}", draft.name), theme::ONLINE);+ back_to_models(app, id.map(|i| format!("mv:api:{i}")));+ }+ Err(e) => {+ let why = why(&e);+ if app.modal.is_some() { return app.say(why, theme::WARN) }+ if draft.provider == "custom" && why.contains("name") { let name = draft.name.clone(); return api_prompt(app, ApiDraft { step: ApiStep::Name, ..draft }, &name, &why) }+ api_prompt(app, ApiDraft { step: ApiStep::Key, ..draft }, &key, &why);+ }+ }+}++/// Deleted through the daemon (`api_connections` remove): the API, its key and its models go.+fn api_remove(app: &mut App, id: &str) {+ let machine = app.fleet.local_id.clone();+ let name = saved_api(app, id).map(|a| a.name).unwrap_or_default();+ let (m, key) = (machine.clone(), id.to_string());+ if !rpc(app, &machine, "api_connections", json!({ "action": "remove", "id": id }), Duration::from_secs(20), move |app, reply| match reply {+ Ok(r) => {+ app.models_view.api_open.remove(&key);+ app.models_view.api_models.remove(&key);+ on_apis_from(app, &m, Ok(r));+ app.say(format!("Deleted {name}"), theme::ONLINE);+ }+ Err(e) => app.say(why(&e), theme::WARN),+ }) { app.say("This computer is not connected", theme::WARN) }+}++/// An API dialog put away (Esc, Cancel): back to the Models view, on the row it came from.+pub fn api_cancelled(app: &mut App, draft: &ApiDraft) {+ back_to_models(app, Some(match &draft.id { Some(id) => format!("mv:api:{id}"), None => format!("{API_NEW}{}", draft.provider) }));+}++/// The Models view again, with the cursor on [row] — unless something else is open by now.+fn back_to_models(app: &mut App, row: Option<String>) {+ if app.modal.is_some() { return }+ crate::input::run(app, "models");+ if let (Some(row), Some(crate::modal::Modal::Picker { kind: crate::modal::PickerKind::Models, picker })) = (row, app.modal.as_mut()) {+ picker.selected_id = Some(row.clone());+ picker.select(&row);}}@@ -1387,7 +1622,10 @@ fn read_apis(app: &mut App) {}pub fn on_apis(app: &mut App, reply: Result<Value, RpcError>) {- let list = match reply { Ok(r) => parse_apis(&r), Err(e) => Err(if e.detail.is_empty() { "APIs are unavailable. Try again.".into() } else { e.detail.clone() }) };+ let list = match reply {+ Ok(r) => { app.models_view.api_presets = parse_api_presets(&r); parse_apis(&r) }+ Err(e) => Err(if e.detail.is_empty() { "APIs are unavailable. Try again.".into() } else { e.detail.clone() }),+ };let serving: Vec<String> = list.as_ref().map(|l| l.iter().filter(|a| a.serves_models()).map(|a| a.id.clone()).collect()).unwrap_or_default();app.models_view.apis = Some(list);app.models_view.apis_at = Some(Instant::now());@@ -1395,6 +1633,12 @@ pub fn on_apis(app: &mut App, reply: Result<Value, RpcError>) {crate::input::refill(app);}+/// A save's or a remove's answer, which is the list again (`{ connections, presets }`): read as a list+/// read is, for the computer it was asked of.+fn on_apis_from(app: &mut App, machine: &str, reply: Result<Value, RpcError>) {+ if machine == app.fleet.local_id { on_apis(app, reply) }+}+fn read_api_models(app: &mut App, id: &str) {let machine = app.fleet.local_id.clone();let key = id.to_string();@@ -1842,9 +2086,48 @@ pub fn preview(app: &App, id: &str) -> Vec<Line<'static>> {Some(Err(e)) => out.push(warn(e.clone())),None => out.push(dim("Reading its models…")),}- if api.serves_models() { out.push(Line::raw("")); out.push(Line::from(span(if v.api_open.contains(&api.id) { "Enter folds its models." } else { "Enter shows its models." }, fg(theme::accent())))) }+ // (Opened, it shows its models — when it lists any — and Edit connection and Delete.)+ let open = v.api_open.contains(&api.id);+ let said = match (api.serves_models(), open, v.api_presets.is_empty()) {+ (true, false, _) => "Enter shows its models.",+ (true, true, _) => "Enter folds its models.",+ (false, false, false) => "Enter shows Edit connection and Delete.",+ (false, true, false) => "Enter folds Edit connection and Delete.",+ (false, _, true) => "",+ };+ if !said.is_empty() { out.push(Line::raw("")); out.push(Line::from(span(said, fg(theme::accent())))) }+ return out;+ }+ if id == API_ADD {+ return vec![bold("Add an API key"), Line::raw(""),+ Line::raw("OpenRouter or a Custom API: use its models to run a harness."),+ Line::raw("fal.ai or Replicate: harness agents can call it as a tool."), Line::raw(""),+ Line::raw("The key stays on this computer."), Line::raw(""),+ Line::from(span(if v.api_adding { "Enter hides the APIs to add." } else { "Enter lists the APIs to add." }, fg(theme::accent())))];+ }+ if let Some(provider) = id.strip_prefix(API_NEW) {+ if provider == "custom" {+ return vec![bold("Custom API"), Line::raw("Any OpenAI-compatible API. Harnesses can run on its models."), Line::raw(""),+ Line::from(span("Enter asks its name, URL and key.", fg(theme::accent())))];+ }+ let Some(p) = v.api_presets.iter().find(|p| p.provider == provider) else { return vec![] };+ let mut out = vec![bold(p.name.clone()), Line::raw(p.base_url.clone())];+ if !p.key_url.is_empty() { out.push(Line::raw("")); out.push(kv("Get key", p.key_url.clone())) }+ out.push(Line::raw(""));+ out.push(Line::from(span("Enter asks its key.", fg(theme::accent()))));return out;}+ if let Some(key) = id.strip_prefix(API_EDIT) {+ let Some(api) = saved_api(app, key) else { return vec![] };+ let custom = api.provider == "custom" || !v.api_presets.iter().any(|p| p.provider == api.provider);+ return vec![bold(format!("Edit {}", api.name)), Line::raw(api.base_url.clone()), Line::raw(""),+ Line::from(span(if custom { "Enter changes its name, URL or key." } else { "Enter changes its key." }, fg(theme::accent())))];+ }+ if let Some(key) = id.strip_prefix(API_DELETE) {+ let Some(api) = saved_api(app, key) else { return vec![] };+ return vec![bold(format!("Delete {}", api.name)), Line::raw("Removes this saved connection and its key from this computer."), Line::raw(""),+ Line::from(span("Enter asks first.", fg(theme::accent())))];+ }if let Some(rest) = id.strip_prefix("mv:apimodel:") {let Some((key, model)) = rest.split_once('\t') else { return vec![] };let Some(api) = v.apis.as_ref().and_then(|a| a.as_ref().ok()).and_then(|l| l.iter().find(|x| x.id == key)) else { return vec![] };@@ -2960,4 +3243,163 @@ mod tests {on_local(&mut app, "local", Ok(json!({ "models": [], "notice": "The model catalog is unavailable." })));assert_eq!(text(&preview(&app, "mv:note:notice")), "The model catalog is unavailable.");}++ /// The daemon's API list with its presets (OpenAI and Anthropic among them, which Add leaves out).+ fn apis_reply(connections: Value) -> Value {+ let preset = |provider: &str, name: &str, url: &str, key: &str| json!({ "provider": provider, "name": name, "baseUrl": url, "keyUrl": key, "keyEnv": "K", "authHeader": "Authorization", "authPrefix": "Bearer" });+ json!({ "connections": connections, "presets": [+ preset("openrouter", "OpenRouter", "https://openrouter.ai/api/v1", "https://openrouter.ai/settings/keys"),+ preset("requesty", "Requesty", "https://router.requesty.ai/v1", "https://app.requesty.ai/api-keys"),+ preset("fal", "fal.ai", "https://queue.fal.run", "https://fal.ai/dashboard/keys"),+ preset("openai", "OpenAI", "https://api.openai.com/v1", "https://platform.openai.com/api-keys"),+ preset("anthropic", "Anthropic", "https://api.anthropic.com/v1", "https://platform.claude.com/settings/keys"),+ ] })+ }++ fn api_dialog(app: &App) -> (String, String, String, bool, String, ApiStep) {+ let Some(crate::modal::Modal::Prompt(p)) = &app.modal else { panic!("no dialog: {:?}", app.modal.is_some()) };+ let crate::modal::PromptKind::Api(d) = &p.kind else { panic!("not an API dialog") };+ assert!(p.dialog());+ (p.title.clone(), p.field.clone(), p.value.clone(), p.secret, p.error.clone(), d.step)+ }++ fn answer(app: &mut App, value: &str) {+ let Some(crate::modal::Modal::Prompt(p)) = app.modal.take() else { panic!("no dialog") };+ let crate::modal::PromptKind::Api(d) = p.kind else { panic!("not an API dialog") };+ api_answer(app, *d, value.to_string());+ }++ /// Add API, last under the saved APIs (alone when none is saved), lists the daemon's presets but+ /// OpenAI and Anthropic, then Custom API; a daemon too old to save offers no Add.+ #[test]+ fn add_api_lists_what_it_can_add() {+ let mut app = loaded();+ on_apis(&mut app, Ok(json!({ "connections": [] })));+ assert!(!rows_of(&app).iter().any(|r| r.id == API_ADD), "no presets: an older daemon, no Add");+ on_apis(&mut app, Ok(apis_reply(json!([]))));+ let rows = rows_of(&app);+ assert_eq!(row(&rows, API_ADD).group.as_deref(), Some(APIS));+ assert!(!rows.iter().any(|r| r.id.starts_with(API_NEW)));+ assert_eq!(plan_enter(&app, API_ADD), Plan::ApiAdd);+ let mut picker = Picker::new("models", "");+ choose(&mut app, &mut picker, API_ADD, false);+ let added: Vec<String> = rows_of(&app).iter().filter(|r| r.id.starts_with(API_NEW)).map(|r| r.label.clone()).collect();+ assert_eq!(added, ["OpenRouter", "Requesty", "fal.ai", "Custom API"]);+ assert!(text(&preview(&app, "mv:apinew:openrouter")).contains("Get key https://openrouter.ai/settings/keys"));+ }++ /// A preset asks only its key — masked, required — and saves through the daemon; the Models view+ /// comes back on the new API, open, its models read.+ #[test]+ fn a_preset_is_added_with_its_key() {+ let mut app = loaded();+ on_apis(&mut app, Ok(apis_reply(json!([{ "id": "openrouter", "provider": "openrouter", "name": "OpenRouter", "baseUrl": "https://openrouter.ai/api/v1" }]))));+ let mut picker = Picker::new("models", "");+ choose(&mut app, &mut picker, "mv:apinew:openrouter", false);+ let (title, field, _, secret, _, step) = api_dialog(&app);+ assert_eq!((title.as_str(), field.as_str(), secret, step), ("Add OpenRouter 2", "Key", true, ApiStep::Key), "named as the desktop names a second one");+ answer(&mut app, "");+ assert_eq!(api_dialog(&app).4, "Paste the API key.");+ answer(&mut app, "sk-test");+ assert_eq!(last_sent(&app), ("local".into(), "api_connections".into(), json!({ "action": "save",+ "connection": { "provider": "openrouter", "name": "OpenRouter 2", "baseUrl": "https://openrouter.ai/api/v1", "apiKey": "sk-test" } })));+ assert!(!toast(&app).contains("sk-test"), "the key is never said");+ let saved = apis_reply(json!([+ { "id": "openrouter", "provider": "openrouter", "name": "OpenRouter", "baseUrl": "https://openrouter.ai/api/v1" },+ { "id": "openrouter-2", "provider": "openrouter", "name": "OpenRouter 2", "baseUrl": "https://openrouter.ai/api/v1" }]));+ let draft = ApiDraft { id: None, provider: "openrouter".into(), name: "OpenRouter 2".into(), base_url: "https://openrouter.ai/api/v1".into(), key_url: String::new(),+ key_env: String::new(), header: String::new(), prefix: String::new(), step: ApiStep::Key };+ on_api_saved(&mut app, "local", draft, "sk-test".into(), Ok(saved));+ assert!(app.models_view.api_open.contains("openrouter-2"));+ assert_eq!(last_sent(&app), ("local".into(), "api_connections".into(), json!({ "action": "models", "id": "openrouter-2" })));+ assert!(toast(&app).contains("Saved OpenRouter 2"));+ }++ /// Custom API: its name, its URL (checked as the desktop checks it), then its key.+ #[test]+ fn a_custom_api_is_asked_its_name_url_and_key() {+ let mut app = loaded();+ on_apis(&mut app, Ok(apis_reply(json!([]))));+ let mut picker = Picker::new("models", "");+ choose(&mut app, &mut picker, "mv:apinew:custom", false);+ assert_eq!(api_dialog(&app).5, ApiStep::Name);+ answer(&mut app, "");+ assert_eq!(api_dialog(&app).4, "Enter a name for this API.");+ answer(&mut app, "DeepSeek");+ let (title, field, _, secret, _, step) = api_dialog(&app);+ assert_eq!((title.as_str(), field.as_str(), secret, step), ("Add Custom API", "URL", false, ApiStep::Url));+ answer(&mut app, "api.deepseek.com");+ assert!(api_dialog(&app).4.starts_with("Enter the full URL"));+ answer(&mut app, "https://api.deepseek.com/v1/");+ assert_eq!(api_dialog(&app).5, ApiStep::Key);+ assert!(api_dialog(&app).3, "the key is masked");+ answer(&mut app, "sk-ds");+ assert_eq!(last_sent(&app).2, json!({ "action": "save", "connection": { "provider": "custom", "name": "DeepSeek", "baseUrl": "https://api.deepseek.com/v1", "apiKey": "sk-ds" } }));+ }++ /// A refused save comes back to its step with the daemon's words, the key still there (masked);+ /// a name already used sends a Custom API back to its name.+ #[test]+ fn a_refused_save_says_why_where_it_can_be_fixed() {+ let mut app = loaded();+ on_apis(&mut app, Ok(apis_reply(json!([]))));+ let draft = |provider: &str| ApiDraft { id: None, provider: provider.into(), name: "DeepSeek".into(), base_url: "https://api.deepseek.com/v1".into(), key_url: String::new(),+ key_env: String::new(), header: String::new(), prefix: String::new(), step: ApiStep::Key };+ on_api_saved(&mut app, "local", draft("openrouter"), "sk".into(), Err(RpcError::new("API_CONNECTIONS_FAILED", "This API could not be saved. Try again.")));+ let (_, _, value, secret, error, step) = api_dialog(&app);+ assert_eq!((value.as_str(), secret, error.as_str(), step), ("sk", true, "This API could not be saved. Try again.", ApiStep::Key));+ app.modal = None;+ on_api_saved(&mut app, "local", draft("custom"), "sk".into(), Err(RpcError::new("API_CONNECTIONS_FAILED", "An API with this name already exists. Choose another name.")));+ let (_, field, value, _, error, step) = api_dialog(&app);+ assert_eq!((field.as_str(), value.as_str(), step), ("Name", "DeepSeek", ApiStep::Name));+ assert!(error.contains("already exists"));+ }++ /// Edit connection: a preset's key alone — blank keeps it — sent with the API's id and its key+ /// variable, header and prefix as they are; a custom one starts at its name.+ #[test]+ fn a_saved_api_is_edited_and_deleted() {+ let mut app = loaded();+ let custom = json!({ "id": "deepseek", "provider": "custom", "name": "DeepSeek", "baseUrl": "https://api.deepseek.com/v1", "keyEnv": "DEEPSEEK_API_KEY", "authHeader": "Authorization", "authPrefix": "Bearer" });+ let preset = json!({ "id": "replicate", "provider": "replicate", "name": "Replicate", "baseUrl": "https://api.replicate.com/v1", "keyEnv": "REPLICATE_API_TOKEN", "authHeader": "Authorization", "authPrefix": "Bearer" });+ let mut reply = apis_reply(json!([custom, preset]));+ reply["presets"].as_array_mut().unwrap().push(json!({ "provider": "replicate", "name": "Replicate", "baseUrl": "https://api.replicate.com/v1", "keyUrl": "" }));+ on_apis(&mut app, Ok(reply));+ assert!(!rows_of(&app).iter().any(|r| r.id.starts_with(API_EDIT)), "folded: no Edit or Delete");+ let mut picker = Picker::new("models", "");+ choose(&mut app, &mut picker, "mv:api:replicate", false);+ let rows = rows_of(&app);+ assert!(rows.iter().any(|r| r.id == "mv:apiedit:replicate") && rows.iter().any(|r| r.id == "mv:apidel:replicate"));+ choose(&mut app, &mut picker, "mv:apiedit:replicate", false);+ assert_eq!(api_dialog(&app).0, "Edit Replicate");+ assert_eq!(api_dialog(&app).5, ApiStep::Key);+ answer(&mut app, "");+ assert_eq!(last_sent(&app).2, json!({ "action": "save", "connection": { "id": "replicate", "provider": "replicate", "name": "Replicate",+ "baseUrl": "https://api.replicate.com/v1", "keyEnv": "REPLICATE_API_TOKEN", "authHeader": "Authorization", "authPrefix": "Bearer" } }), "no key: the saved one stays");++ app.modal = None;+ choose(&mut app, &mut picker, "mv:apiedit:deepseek", false);+ assert_eq!((api_dialog(&app).2.as_str(), api_dialog(&app).5), ("DeepSeek", ApiStep::Name));++ // Delete asks first, then removes it.+ app.modal = None;+ assert!(matches!(plan_enter(&app, "mv:apidel:deepseek"), Plan::Arm(ref w, ref then) if w.starts_with("Delete DeepSeek?") && **then == Plan::ApiRemove("deepseek".into())));+ let mut picker = Picker::new("models", "");+ choose(&mut app, &mut picker, "mv:apidel:deepseek", false);+ assert!(!app.models_view.sent.iter().any(|s| s.2["action"] == "remove"), "asked first");+ choose(&mut app, &mut picker, "mv:apidel:deepseek", false);+ assert_eq!(last_sent(&app), ("local".into(), "api_connections".into(), json!({ "action": "remove", "id": "deepseek" })));+ }++ /// The desktop's URL rules.+ #[test]+ fn an_api_url_is_checked_as_the_desktop_checks_it() {+ assert_eq!(url_problem(""), Some("Enter the API's URL."));+ assert!(url_problem("api.example.com").unwrap().starts_with("Enter the full URL"));+ assert!(url_problem("ftp://example.com").unwrap().starts_with("Enter the full URL"));+ assert!(url_problem("https://user:[email protected]/v1").unwrap().starts_with("Take the username"));+ assert!(url_problem("https://example.com/v1?x=1").unwrap().starts_with("Take the ? or #"));+ assert_eq!(url_problem("https://api.example.com/v1"), None);+ assert_eq!(url_problem("http://localhost:8080/v1"), None);+ }}diff --git a/tui/src/ui.rs b/tui/src/ui.rsindex 2c3bdc1cf..c078cc200 100644--- a/tui/src/ui.rs+++ b/tui/src/ui.rs@@ -405,6 +405,7 @@ pub fn prompt_dialog<'a>(app: &App, p: &'a crate::modal::Prompt, row: &'a crate:let mut d = crate::dialog::Dialog::new(&p.title, body, row, c);d.border = dialog_border(&lines);d.input = Some(crate::dialog::Input { label: &p.field, value: &p.value, caret: p.cursor, select: None, secret: p.secret, focused: !p.buttons, width: crate::dialog::INPUT_W });+ if !p.error.is_empty() { d.message = crate::dialog::wrap(&p.error, room.min(crate::dialog::INPUT_W), c.danger) }if !d.fit(over.height) { return None }Some((d.place(over), d))}@@ -4297,6 +4298,25 @@ mod prompt_dialog_tests {}}+ /// Add API's key step: its lines (the URL, where to get a key), the key as dots, what was wrong+ /// under it, and Save; typing clears what was wrong. Esc goes back to the Models view.+ #[test]+ fn an_api_key_is_asked_masked_with_what_was_wrong() {+ let mut app = app((120, 30));+ let draft = crate::models::ApiDraft { id: None, provider: "openrouter".into(), name: "OpenRouter".into(), base_url: "https://openrouter.ai/api/v1".into(),+ key_url: "https://openrouter.ai/settings/keys".into(), key_env: String::new(), header: String::new(), prefix: String::new(), step: crate::models::ApiStep::Key };+ let mut p = crate::modal::Prompt::status(crate::modal::PromptKind::Api(Box::new(draft)), "", "sk-secret");+ (p.title, p.field, p.body, p.secret, p.error) = ("Add OpenRouter".into(), "Key".into(), "https://openrouter.ai/api/v1\nGet a key: https://openrouter.ai/settings/keys".into(), true, "Paste the API key.".into());+ app.modal = Some(Modal::Prompt(p));+ let (s, _) = screen(&mut app);+ for want in ["┌─Add OpenRouter", "https://openrouter.ai/api/v1", "Get a key: https://openrouter.ai/settings/keys", "Paste the API key.", "•••••••••", "[ Cancel ] [ Save ]"] { assert!(s.contains(want), "{want}:\n{s}") }+ assert!(!s.contains("sk-secret"), "the key is never drawn:\n{s}");+ press(&mut app, KeyCode::Char('x'));+ assert!(open(&app).is_some_and(|p| p.error.is_empty()), "typing clears what was wrong");+ press(&mut app, KeyCode::Esc);+ assert!(matches!(app.modal, Some(Modal::Picker { kind: crate::modal::PickerKind::Models, .. })), "Esc goes back to Models");+ }+/// tmux's own prompts (C-b , and every command-prompt, choose-tree's) stay on the status line.#[test]fn tmux_s_command_prompt_keeps_the_status_line() {