Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(host): manage memory, routines, marketplace and sign-in in the TUI
leepokai0cecdbeb0b36
diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.mdindex 0e18c1f6..634fa1e2 100644--- a/docs/architecture/file-structure.md+++ b/docs/architecture/file-structure.md@@ -17,7 +17,7 @@ Codync/│ │ ├── chat/ # Groups, bot-to-bot requests, prompt snapshots, memory│ │ ├── remote/ # Identity, wire crypto, E2E channel, cloud, relay socket, push│ │ ├── market/ # Marketplace, Composio, MCP OAuth-│ │ └── tui/ # Terminal client+│ │ └── tui/ # Terminal client (manage.rs + sheets.rs: memory, routines, marketplace, sign-in)│ └── tests/ # Host integration tests and scripted ACP agents├── kit/ # Shared Swift package│ ├── Sources/diff --git a/docs/features/routines.md b/docs/features/routines.mdindex ee70da49..175977c1 100644--- a/docs/features/routines.md+++ b/docs/features/routines.md@@ -146,7 +146,7 @@ completion reporting. Most automation modules it imports are absent. Its rendereand private cloud are not source-complete references.Remaining differences from the reference: provider subscription provisioning,-cloud execution/delivery while the host is offline, inactivity auto-pause, and Linux/TUI routine panels. The Apple UI+cloud execution/delivery while the host is offline, inactivity auto-pause, and a Linux routine panel (the TUI edits routines with a typed schedule: cron, `every 2h`, a date, or `webhook`). The Apple UIuses Codync's shared native controls. This is not a verified complete one-to-onereconstruction of every Grok Bot routine behavior.diff --git a/host/src/tui/app.rs b/host/src/tui/app.rsindex c7a05203..ec696525 100644--- a/host/src/tui/app.rs+++ b/host/src/tui/app.rs@@ -8,6 +8,7 @@ use std::io::Write as _;use std::time::{Duration, Instant};use tokio::sync::mpsc::UnboundedSender;+use super::manage::{AgentSetup, Fields, Market, MemorySheet, Reply, RoutineForm, RoutineList, Shell};use super::net::Client;pub enum Msg {@@ -16,6 +17,8 @@ pub enum Msg {Reply(After, Result<Value, String>),/// The stream is starting over from rev 0: drop what we have.Rewind,+ /// A setup terminal's output or exit.+ Term(String, Value),}/// What to do with a command's reply.@@ -32,6 +35,8 @@ pub enum After {Connectors,Skills,Installed,+ /// Memory, routines, marketplace, sign-in (`manage`).+ Sheet(Reply),}#[derive(Clone, Copy, PartialEq, Eq, Debug)]@@ -411,6 +416,9 @@ pub const FILTERS: [(&str, Option<Mark>); 5] = [pub enum Action {NewBot,NewGroup,+ Market,+ Memory,+ Routines,RefreshAgents,Pair,Usage,@@ -419,9 +427,12 @@ pub enum Action {pub const NEW_GROUP: &str = "New group chat";-pub const ACTIONS: [(&str, &str, Action); 6] = [+pub const ACTIONS: [(&str, &str, Action); 9] = [("New bot…", "n", Action::NewBot),("New group chat…", "m", Action::NewGroup),+ ("Marketplace: agents, connectors, skills…", "A", Action::Market),+ ("Memory of this bot…", "M", Action::Memory),+ ("Routines of this bot…", "R", Action::Routines),("Refresh agents", "", Action::RefreshAgents),("Pair a phone…", "P", Action::Pair),("Usage", "U", Action::Usage),@@ -442,6 +453,10 @@ pub struct Goto {pub enum ConfirmAct {Delete(String),NewSession(String),+ ClearMemory(String),+ DeleteRoutine(String, String),+ RemoveConnector(String),+ RemoveSkill(String),}pub struct Confirm {@@ -584,6 +599,12 @@ pub enum Overlay {Group(GroupForm),Usage,Pair(Option<String>),+ Memory(MemorySheet),+ Routines(RoutineList),+ Routine(Box<RoutineForm>),+ Market(Box<Market>),+ Agent(AgentSetup),+ Fields(Box<Fields>),}pub struct Toast {@@ -616,7 +637,7 @@ pub struct Hits {#[allow(clippy::struct_excessive_bools, reason = "independent UI flags, not a state machine")]pub struct App {pub client: Client,- tx: UnboundedSender<Msg>,+ pub(super) tx: UnboundedSender<Msg>,pub url: String,pub host: String,pub home: String,@@ -656,6 +677,12 @@ pub struct App {/// A main-chat message picked to reply to in its thread (`r`, then j/k and ↵).pub pick: Option<String>,pub market: (Vec<Toggle>, Vec<Toggle>),+ /// Installed connectors and skills as the host lists them.+ pub plugins: (Vec<Value>, Vec<Value>),+ /// Models each agent offers (`None` while loading).+ pub models: HashMap<String, Option<Vec<(String, String)>>>,+ /// A setup terminal holding the screen.+ pub shell: Option<Shell>,reading: HashSet<String>,history_busy: HashSet<String>,history_done: HashSet<String>,@@ -699,6 +726,9 @@ impl App {thread: None,pick: None,market: (vec![], vec![]),+ plugins: (vec![], vec![]),+ models: HashMap::new(),+ shell: None,reading: HashSet::new(),history_busy: HashSet::new(),history_done: HashSet::new(),@@ -943,6 +973,7 @@ impl App {}Msg::Event(v) => self.on_event(&v),Msg::Reply(after, r) => self.on_reply(after, r),+ Msg::Term(id, v) => self.on_term(&id, &v),}}@@ -996,6 +1027,10 @@ impl App {}fn on_reply(&mut self, after: After, r: Result<Value, String>) {+ if let After::Sheet(s) = after {+ self.on_sheet_reply(s, r);+ return;+ }let v = match r {Ok(v) => v,Err(e) => {@@ -1026,7 +1061,7 @@ impl App {}};match after {- After::Nothing => {}+ After::Nothing | After::Sheet(_) => {}After::Installed => {self.error = None;self.flash("Host installed; connecting…");@@ -1107,17 +1142,8 @@ impl App {}}After::Connectors | After::Skills => {- let list: Vec<Toggle> = v["items"]- .as_array()- .into_iter()- .flatten()- .filter_map(|c| {- let id = c["id"].as_str()?.to_owned();- let name = c["name"].as_str().unwrap_or(&id).to_owned();- Some(Toggle { id, name, on: false })- })- .collect();let connectors = matches!(after, After::Connectors);+ let list = self.set_plugins(connectors, v["items"].as_array().cloned().unwrap_or_default());if connectors {self.market.0 = list;} else {@@ -1140,6 +1166,10 @@ impl App {// ---------- input ----------pub fn on_paste(&mut self, s: &str) {+ if let Some(sh) = self.shell.as_ref().filter(|s| s.exited.is_none()) {+ let _ = sh.input.send(s.as_bytes().to_vec());+ return;+ }let s = s.replace("\r\n", "\n").replace('\r', "\n");if let Some(ed) = self.top_editor() {ed.insert(&s);@@ -1171,11 +1201,22 @@ impl App {Field::Model => Some(&mut f.model),_ => None,},+ Overlay::Market(m) => Some(&mut m.query),+ Overlay::Fields(f) => f.current().map(|i| &mut i.ed),+ Overlay::Routine(f) => Some(match f.field {+ super::manage::RoutineField::Name => &mut f.name,+ super::manage::RoutineField::Instruction => &mut f.instruction,+ super::manage::RoutineField::When => &mut f.when,+ }),_ => None,}}pub fn on_key(&mut self, k: KeyEvent) {+ if self.shell.is_some() {+ self.shell_key(k);+ return;+ }let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);if ctrl && k.code == KeyCode::Char('k') {if matches!(self.overlays.last(), Some(Overlay::Goto(_))) {@@ -1395,6 +1436,14 @@ impl App {}KeyCode::Char('b') => self.compact = !self.compact,KeyCode::Char('U') => self.overlays.push(Overlay::Usage),+ KeyCode::Char('M') => self.open_memory(),+ KeyCode::Char('R') => self.open_routines(),+ KeyCode::Char('A') => self.open_market(),+ KeyCode::Char('v') if !roster_page && self.selected.is_some() => {+ self.chat_page = true;+ self.focus = Focus::Chat;+ self.step_pick(0);+ }KeyCode::Char('P') => self.open_pair(),KeyCode::Char('s') => {if let Some(b) = self.bot() {@@ -1580,15 +1629,37 @@ impl App {/// Keys while a message is picked. Returns whether the key was used.fn pick_key(&mut self, k: KeyEvent) -> bool {+ let Some(id) = self.selected.clone() else { return false };+ let picked = self.pick.as_ref().and_then(|p| self.lane(&id).into_iter().find(|e| &e.id == p).cloned());match k.code {KeyCode::Char('j') | KeyCode::Down => self.step_pick(1),KeyCode::Char('k') | KeyCode::Up => self.step_pick(-1),+ KeyCode::Enter | KeyCode::Char('r') if self.thread.is_some() => {+ self.pick = None;+ self.start_typing();+ }KeyCode::Enter | KeyCode::Char('r') => {if let Some(root) = self.pick.take() {self.open_thread(root);self.start_typing();}}+ KeyCode::Char(c @ '1'..='6') => {+ if let Some(e) = picked {+ self.react(&e.id, (c as usize) - ('1' as usize));+ }+ }+ KeyCode::Char('f') => {+ if let Some(e) = picked {+ self.save_files(&id, &e.data);+ }+ }+ KeyCode::Char('c') => {+ if let Some(e) = picked {+ copy(e.text());+ self.flash("Copied");+ }+ }KeyCode::Esc => self.pick = None,_ => return false,}@@ -1616,11 +1687,7 @@ impl App {self.flash("No reply to copy");return;};- // OSC 52: the terminal puts it on the clipboard, over SSH too.- let mut out = std::io::stdout();- let _ =- write!(out, "\x1b]52;c;{}\x07", base64::Engine::encode(&base64::engine::general_purpose::STANDARD, text));- let _ = out.flush();+ copy(&text);self.flash("Copied the last reply");}@@ -1756,6 +1823,7 @@ impl App {};merge_toggles(&mut f.connectors, &self.market.0, false);merge_toggles(&mut f.skills, &self.market.1, false);+ self.want_models(&b.backend);self.overlays.push(Overlay::Form(Box::new(f)));self.call("connectors", json!({}), After::Connectors);self.call("skills", json!({}), After::Skills);@@ -1798,6 +1866,9 @@ impl App {match a {Action::NewBot => self.new_bot(),Action::NewGroup => self.new_group(),+ Action::Market => self.open_market(),+ Action::Memory => self.open_memory(),+ Action::Routines => self.open_routines(),Action::RefreshAgents => self.call("refreshBackends", json!({}), After::Backends),Action::Pair => self.open_pair(),Action::Usage => self.overlays.push(Overlay::Usage),@@ -1822,9 +1893,16 @@ impl App {}Overlay::Confirm(c) => match k.code {KeyCode::Enter => {+ let changed = After::Sheet(Reply::Changed);match &c.act {ConfirmAct::Delete(id) => self.call("deleteBot", json!({"botId": id}), After::Nothing),ConfirmAct::NewSession(id) => self.call("newSession", json!({"botId": id}), After::Nothing),+ ConfirmAct::ClearMemory(id) => self.call("clearMemory", json!({"botId": id}), changed),+ ConfirmAct::DeleteRoutine(bot, id) => {+ self.call("deleteRoutine", json!({"botId": bot, "id": id}), changed);+ }+ ConfirmAct::RemoveConnector(id) => self.call("removeConnector", json!({"id": id}), changed),+ ConfirmAct::RemoveSkill(id) => self.call("removeSkill", json!({"id": id}), changed),}None}@@ -1835,6 +1913,12 @@ impl App {Overlay::Folder(p) => self.folder_key(p, k),Overlay::Form(f) => self.form_key(f, k),Overlay::Group(g) => self.group_key(g, k),+ Overlay::Memory(m) => self.memory_key(m, k),+ Overlay::Routines(l) => self.routines_key(l, k),+ Overlay::Routine(f) => self.routine_key(f, k),+ Overlay::Market(m) => self.market_key(m, k),+ Overlay::Agent(a) => self.agent_key(a, k),+ Overlay::Fields(f) => self.fields_key(f, k),o @ (Overlay::Usage | Overlay::Pair(_)) => {if matches!(k.code, KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q' | 'U' | 'P')) {None@@ -2022,6 +2106,7 @@ impl App {error: None,saving: false,};+ self.want_models(&f.backend);self.overlays.push(Overlay::Form(Box::new(f)));self.call("connectors", json!({}), After::Connectors);self.call("skills", json!({}), After::Skills);@@ -2056,6 +2141,19 @@ impl App {self.open_folder(&start);return None;}+ KeyCode::Enter if field == Field::Agent => {+ let backend = f.backend.clone();+ self.overlays.push(Overlay::Form(f));+ self.open_agent(&backend);+ return None;+ }+ KeyCode::Left | KeyCode::Right if field == Field::Model => {+ let d: isize = if k.code == KeyCode::Left { -1 } else { 1 };+ self.want_models(&f.backend);+ if let Some(m) = self.cycle_model(&f.backend, f.model.text.trim(), d) {+ f.model = Editor::with(&m);+ }+ }KeyCode::Enter => self.save_form(&mut f),KeyCode::Left | KeyCode::Right | KeyCode::Char(' ')if matches!(@@ -2078,6 +2176,9 @@ impl App {if !ids.is_empty() {let i = ids.iter().position(|x| *x == f.backend).unwrap_or(0);f.backend.clone_from(&ids[cycle(i, d, ids.len())]);+ // Another agent's model ids mean nothing here.+ f.model.clear();+ self.want_models(&f.backend);}}Field::Approvals => f.auto = !f.auto,@@ -2206,11 +2307,18 @@ const NAMES: [&str; 24] = ["Gus", "Hal", "Ida", "Jin", "Kai", "Lux", "Nia", "Otto",];+/// OSC 52: the terminal puts it on the clipboard, over SSH too.+pub fn copy(text: &str) {+ let mut out = std::io::stdout();+ let _ = write!(out, "\x1b]52;c;{}\x07", base64::Engine::encode(&base64::engine::general_purpose::STANDARD, text));+ let _ = out.flush();+}+fn page(h: usize) -> isize {isize::try_from(h.max(4)).unwrap_or(20) - 2}-fn cycle(i: usize, d: isize, n: usize) -> usize {+pub(super) fn cycle(i: usize, d: isize, n: usize) -> usize {let n = isize::try_from(n).unwrap_or(1).max(1);usize::try_from((isize::try_from(i).unwrap_or(0) + d).rem_euclid(n)).unwrap_or(0)}diff --git a/host/src/tui/manage.rs b/host/src/tui/manage.rsnew file mode 100644index 00000000..5520d986--- /dev/null+++ b/host/src/tui/manage.rs@@ -0,0 +1,1364 @@+//! The settings the other apps keep next to the chat, as TUI sheets: a bot's memory and+//! routines, the marketplace (agents, connectors, skills), agent sign-in with its setup+//! terminal, and the pieces of a message you can act on (reactions, sent files).++// Key handlers read best with k (key), m / l / f / a (the sheet), n (rows).+#![allow(clippy::many_single_char_names)]++use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};+use serde_json::{Value, json};+use std::str::FromStr as _;++use super::app::{After, App, Confirm, ConfirmAct, Editor, Overlay, Toggle, fuzzy};++/// Quick reactions, as the other apps offer them.+pub const REACTIONS: [&str; 6] = ["👍", "❤️", "😂", "🎉", "👀", "✅"];++/// Replies to the sheets' commands.+#[derive(Clone)]+pub enum Reply {+ Memory(String),+ Routines(String),+ RoutineSaved,+ Webhook,+ Registry {+ more: bool,+ },+ Skills,+ Auth(String),+ Setup,+ FieldsSaved,+ SignIn,+ Models(String),+ Downloaded,+ /// Something changed: every open sheet loads again.+ Changed,+}++pub struct Fact {+ pub id: String,+ pub content: String,+ pub profile: bool,+}++pub struct MemorySheet {+ pub bot: String,+ pub facts: Option<Vec<Fact>>,+ pub cursor: usize,+}++pub struct RoutineList {+ pub bot: String,+ pub items: Option<Vec<Value>>,+ pub cursor: usize,+}++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum RoutineField {+ Name,+ Instruction,+ When,+}++pub struct RoutineForm {+ pub bot: String,+ pub id: Option<String>,+ pub name: Editor,+ pub instruction: Editor,+ pub when: Editor,+ /// What an edited routine runs on; kept when `when` stays empty.+ pub original: Value,+ pub original_text: String,+ pub field: RoutineField,+ pub error: Option<String>,+ pub saving: bool,+}++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum Tab {+ Agents,+ Connectors,+ Skills,+}++pub const TABS: [(Tab, &str); 3] = [(Tab::Agents, "Agents"), (Tab::Connectors, "Connectors"), (Tab::Skills, "Skills")];++pub struct Market {+ pub tab: Tab,+ pub query: Editor,+ /// The registry search the connector list shows; `None` before the first page.+ pub searched: Option<String>,+ pub registry: Vec<Value>,+ pub next: Option<String>,+ pub skills: Option<Vec<Value>>,+ pub loading: bool,+ pub cursor: usize,+ pub error: Option<String>,+}++pub enum Row<'a> {+ Agent(&'a Value),+ Installed(&'a Value),+ Custom,+ Registry(&'a Value),+ More,+ OwnSkill(&'a Value),+ Skill(&'a Value),+}++pub struct AgentSetup {+ pub backend: String,+ pub auth: Option<Value>,+ /// A check or a browser sign-in is running.+ pub busy: bool,+ pub cursor: usize,+ pub error: Option<String>,+}++pub enum SetupRow {+ Install,+ Login,+ Method(Value),+ Check,+}++pub struct Input {+ pub name: String,+ pub label: String,+ pub secret: bool,+ pub required: bool,+ pub multiline: bool,+ pub placeholder: String,+ pub ed: Editor,+}++pub enum Submit {+ AgentEnv(String),+ Connector(Value),+ Import,+}++/// A few labeled text fields: an agent's keys, a connector's setup, a pasted MCP config.+pub struct Fields {+ pub title: String,+ pub note: String,+ /// A connector's ways to run (row 0 when there are several).+ pub choices: Vec<String>,+ pub choice: usize,+ pub inputs: Vec<Input>,+ pub cursor: usize,+ pub error: Option<String>,+ pub saving: bool,+ pub submit: Submit,+}++impl Fields {+ fn offset(&self) -> usize {+ usize::from(self.choices.len() > 1)+ }++ pub fn current(&mut self) -> Option<&mut Input> {+ let i = self.cursor.checked_sub(self.offset())?;+ self.inputs.get_mut(i)+ }+}++/// The running setup terminal, which takes over the whole screen.+pub struct Shell {+ pub id: String,+ /// Keys in the order typed (one sender, one request at a time).+ pub input: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,+ pub backend: String,+ pub exited: Option<i64>,+ /// Output not yet written to the screen.+ pub out: Vec<u8>,+}++fn s(v: &Value, k: &str) -> String {+ v[k].as_str().unwrap_or_default().to_owned()+}++fn ctrl(k: KeyEvent) -> bool {+ k.modifiers.contains(KeyModifiers::CONTROL)+}++fn newline(k: KeyEvent) -> bool {+ k.code == KeyCode::Enter && k.modifiers.intersects(KeyModifiers::SHIFT | KeyModifiers::ALT)+ || k.code == KeyCode::Char('j') && ctrl(k)+}++impl App {+ fn sheet(&self, method: &'static str, body: Value, r: Reply) {+ self.call(method, body, After::Sheet(r));+ }++ // ---------- memory ----------++ pub fn open_memory(&mut self) {+ let Some(b) = self.bot().filter(|b| !b.group) else {+ self.flash("A group has no memory of its own");+ return;+ };+ let bot = b.id.clone();+ self.sheet("memory", json!({"botId": bot}), Reply::Memory(bot.clone()));+ self.overlays.push(Overlay::Memory(MemorySheet { bot, facts: None, cursor: 0 }));+ }++ pub(super) fn memory_key(&mut self, mut m: MemorySheet, k: KeyEvent) -> Option<Overlay> {+ let n = m.facts.as_ref().map_or(0, Vec::len);+ match k.code {+ KeyCode::Esc | KeyCode::Char('q' | 'M') => return None,+ KeyCode::Down | KeyCode::Char('j') => m.cursor = (m.cursor + 1).min(n.saturating_sub(1)),+ KeyCode::Up | KeyCode::Char('k') => m.cursor = m.cursor.saturating_sub(1),+ KeyCode::Char('x' | 'd') | KeyCode::Delete | KeyCode::Backspace => {+ if let Some(f) = m.facts.as_mut().filter(|f| m.cursor < f.len()) {+ let fact = f.remove(m.cursor);+ m.cursor = m.cursor.min(f.len().saturating_sub(1));+ self.sheet("forgetMemory", json!({"botId": m.bot, "id": fact.id}), Reply::Changed);+ }+ }+ KeyCode::Char('D') if n > 0 => {+ let name = self.bots.get(&m.bot).map_or_else(String::new, |b| b.name.clone());+ let c = Confirm {+ title: format!("Forget everything {name} remembers?"),+ detail: "Facts about you and its history go away.".into(),+ note: "The chat stays.".into(),+ button: "Forget everything",+ act: ConfirmAct::ClearMemory(m.bot.clone()),+ };+ self.overlays.push(Overlay::Memory(m));+ self.overlays.push(Overlay::Confirm(c));+ return None;+ }+ _ => {}+ }+ Some(Overlay::Memory(m))+ }++ // ---------- routines ----------++ pub fn open_routines(&mut self) {+ let Some(b) = self.bot().filter(|b| !b.group) else {+ self.flash("Routines belong to a bot, not a group");+ return;+ };+ let bot = b.id.clone();+ self.sheet("routines", json!({"botId": bot}), Reply::Routines(bot.clone()));+ self.overlays.push(Overlay::Routines(RoutineList { bot, items: None, cursor: 0 }));+ }++ pub(super) fn routines_key(&mut self, mut l: RoutineList, k: KeyEvent) -> Option<Overlay> {+ let n = l.items.as_ref().map_or(0, Vec::len);+ let current = l.items.as_ref().and_then(|v| v.get(l.cursor)).cloned();+ let bot = l.bot.clone();+ match (k.code, current) {+ (KeyCode::Esc | KeyCode::Char('q' | 'R'), _) => return None,+ (KeyCode::Down | KeyCode::Char('j'), _) => l.cursor = (l.cursor + 1).min(n.saturating_sub(1)),+ (KeyCode::Up | KeyCode::Char('k'), _) => l.cursor = l.cursor.saturating_sub(1),+ (KeyCode::Char('n'), _) => {+ self.overlays.push(Overlay::Routines(l));+ self.overlays.push(Overlay::Routine(Box::new(RoutineForm {+ bot,+ id: None,+ name: Editor::default(),+ instruction: Editor::default(),+ when: Editor::default(),+ original: Value::Null,+ original_text: String::new(),+ field: RoutineField::Name,+ error: None,+ saving: false,+ })));+ return None;+ }+ (KeyCode::Enter | KeyCode::Char('e'), Some(r)) => {+ let triggers = r["triggers"].clone();+ let text = when_text(&triggers, &local_zone());+ let original_text = r["triggerDescriptions"]+ .as_array()+ .map(|d| d.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(" · "))+ .unwrap_or_default();+ self.overlays.push(Overlay::Routines(l));+ self.overlays.push(Overlay::Routine(Box::new(RoutineForm {+ bot,+ id: Some(s(&r, "id")),+ name: Editor::with(&s(&r, "name")),+ instruction: Editor::with(&s(&r, "instruction")),+ when: Editor::with(text.as_deref().unwrap_or_default()),+ original: if text.is_some() { Value::Null } else { triggers },+ original_text,+ field: RoutineField::Name,+ error: None,+ saving: false,+ })));+ return None;+ }+ (KeyCode::Char(' '), Some(r)) => {+ let on = !r["enabled"].as_bool().unwrap_or(false);+ self.sheet(+ "setRoutineEnabled",+ json!({"botId": bot, "id": r["id"], "enabled": on}),+ Reply::Routines(bot.clone()),+ );+ if let Some(item) = l.items.as_mut().and_then(|v| v.get_mut(l.cursor)) {+ item["enabled"] = on.into();+ }+ }+ (KeyCode::Char('r'), Some(r)) => {+ self.sheet("runRoutine", json!({"botId": bot, "id": r["id"]}), Reply::Routines(bot.clone()));+ self.flash(&format!("Running {} now", s(&r, "name")));+ }+ (KeyCode::Char('w'), Some(r)) => {+ if r["triggers"].as_array().into_iter().flatten().any(|t| t["type"] == "webhook") {+ self.sheet("routineWebhook", json!({"botId": bot, "id": r["id"]}), Reply::Webhook);+ } else {+ self.flash("Only a routine whose When is webhook can be called");+ }+ }+ (KeyCode::Char('x'), Some(r)) => {+ let c = Confirm {+ title: format!("Delete the routine {}?", s(&r, "name")),+ detail: "It stops running.".into(),+ note: "What it already posted stays in the chat.".into(),+ button: "Delete",+ act: ConfirmAct::DeleteRoutine(bot, s(&r, "id")),+ };+ self.overlays.push(Overlay::Routines(l));+ self.overlays.push(Overlay::Confirm(c));+ return None;+ }+ _ => {}+ }+ Some(Overlay::Routines(l))+ }++ pub(super) fn routine_key(&mut self, mut f: Box<RoutineForm>, k: KeyEvent) -> Option<Overlay> {+ use RoutineField::{Instruction, Name, When};+ match k.code {+ KeyCode::Esc => return None,+ _ if newline(k) && f.field == Instruction => f.instruction.insert("\n"),+ KeyCode::Enter => self.save_routine(&mut f),+ KeyCode::Char('s') if ctrl(k) => self.save_routine(&mut f),+ KeyCode::Tab | KeyCode::Down => {+ f.field = match f.field {+ Name => Instruction,+ Instruction => When,+ When => Name,+ };+ }+ KeyCode::BackTab | KeyCode::Up => {+ f.field = match f.field {+ Name => When,+ Instruction => Name,+ When => Instruction,+ };+ }+ _ => {+ let ed = match f.field {+ Name => &mut f.name,+ Instruction => &mut f.instruction,+ When => &mut f.when,+ };+ ed.key(k);+ }+ }+ Some(Overlay::Routine(f))+ }++ fn save_routine(&mut self, f: &mut RoutineForm) {+ if f.saving {+ return;+ }+ let (name, instruction) = (f.name.text.trim(), f.instruction.text.trim());+ if name.is_empty() || instruction.is_empty() {+ f.error = Some("A routine needs a name and what to do.".into());+ return;+ }+ let triggers = if f.when.text.trim().is_empty() && !f.original.is_null() {+ f.original.clone()+ } else {+ match parse_when(&f.when.text, &local_zone(), crate::store::now_ms()) {+ Ok(t) => json!([t]),+ Err(e) => {+ f.error = Some(e);+ f.field = RoutineField::When;+ return;+ }+ }+ };+ let mut body = json!({"botId": f.bot, "name": name, "instruction": instruction, "triggers": triggers});+ if let Some(id) = &f.id {+ body["id"] = id.clone().into();+ }+ f.saving = true;+ f.error = None;+ self.sheet("saveRoutine", body, Reply::RoutineSaved);+ }++ // ---------- marketplace ----------++ pub fn open_market(&mut self) {+ self.call("refreshBackends", json!({}), After::Backends);+ self.call("connectors", json!({}), After::Connectors);+ self.call("skills", json!({}), After::Skills);+ self.sheet("marketSkills", json!({}), Reply::Skills);+ self.sheet("marketConnectors", json!({"search": ""}), Reply::Registry { more: false });+ self.overlays.push(Overlay::Market(Box::new(Market {+ tab: Tab::Agents,+ query: Editor::default(),+ searched: None,+ registry: vec![],+ next: None,+ skills: None,+ loading: true,+ cursor: 0,+ error: None,+ })));+ }++ /// The marketplace's rows on its current tab, filtered by the query.+ pub fn market_rows<'a>(&'a self, m: &'a Market) -> Vec<Row<'a>> {+ let q = m.query.text.trim();+ let hit = |v: &Value, keys: &[&str]| {+ let fields: Vec<&str> = keys.iter().map(|k| v[*k].as_str().unwrap_or_default()).collect();+ fuzzy(q, &fields)+ };+ match m.tab {+ Tab::Agents => self+ .backends+ .iter()+ .filter(|b| b["available"] == true || b["installed"] == true || b["curated"] == true)+ .filter(|b| hit(b, &["name", "id"]))+ .map(Row::Agent)+ .collect(),+ Tab::Connectors => {+ let installed: Vec<&str> = self.plugins.0.iter().filter_map(|c| c["registryName"].as_str()).collect();+ let mut rows: Vec<Row> =+ self.plugins.0.iter().filter(|c| hit(c, &["name", "description"])).map(Row::Installed).collect();+ rows.push(Row::Custom);+ rows.extend(+ m.registry+ .iter()+ .filter(|c| !installed.contains(&c["name"].as_str().unwrap_or_default()))+ .map(Row::Registry),+ );+ if m.next.is_some() {+ rows.push(Row::More);+ }+ rows+ }+ Tab::Skills => {+ let installed: Vec<String> = self.plugins.1.iter().map(|v| s(v, "id").to_lowercase()).collect();+ let mut rows: Vec<Row> =+ self.plugins.1.iter().filter(|v| hit(v, &["name", "description"])).map(Row::OwnSkill).collect();+ rows.extend(+ m.skills+ .iter()+ .flatten()+ .filter(|v| !installed.contains(&s(v, "source").to_lowercase()))+ .filter(|v| hit(v, &["name", "description"]))+ .map(Row::Skill),+ );+ rows+ }+ }+ }++ /// The query no longer matches what the registry list shows: ↵ searches first.+ pub fn market_stale(m: &Market) -> bool {+ m.tab == Tab::Connectors && m.searched.as_deref().is_some_and(|s| s != m.query.text.trim())+ }++ pub(super) fn market_key(&mut self, mut m: Box<Market>, k: KeyEvent) -> Option<Overlay> {+ let n = self.market_rows(&m).len();+ match k.code {+ KeyCode::Esc => return None,+ KeyCode::Tab | KeyCode::BackTab => {+ let i = TABS.iter().position(|(t, _)| *t == m.tab).unwrap_or(0);+ let d = if k.code == KeyCode::Tab { 1 } else { TABS.len() - 1 };+ m.tab = TABS[(i + d) % TABS.len()].0;+ m.cursor = 0;+ }+ KeyCode::Down => m.cursor = (m.cursor + 1).min(n.saturating_sub(1)),+ KeyCode::Up => m.cursor = m.cursor.saturating_sub(1),+ KeyCode::Char('n' | 'j') if ctrl(k) => m.cursor = (m.cursor + 1).min(n.saturating_sub(1)),+ KeyCode::Char('p') if ctrl(k) => m.cursor = m.cursor.saturating_sub(1),+ KeyCode::Char('r') if ctrl(k) => {+ self.call("connectors", json!({}), After::Connectors);+ self.call("skills", json!({}), After::Skills);+ self.call("refreshBackends", json!({}), After::Backends);+ }+ KeyCode::Enter if Self::market_stale(&m) => {+ let search = m.query.text.trim().to_owned();+ m.loading = true;+ m.cursor = 0;+ m.registry.clear();+ m.next = None;+ self.sheet("marketConnectors", json!({"search": search}), Reply::Registry { more: false });+ m.searched = Some(search);+ }+ KeyCode::Enter => return self.market_enter(m),+ KeyCode::Char('x') if ctrl(k) => {+ let (id, name, skill) = match self.market_rows(&m).get(m.cursor) {+ Some(Row::Installed(c)) => (s(c, "id"), s(c, "name"), false),+ Some(Row::OwnSkill(v)) => (s(v, "id"), s(v, "name"), true),+ _ => return Some(Overlay::Market(m)),+ };+ let c = Confirm {+ title: format!("Remove {name}?"),+ detail: if skill {+ "Bots stop using this skill.".into()+ } else {+ "Bots lose it, and the keys saved for it are deleted.".into()+ },+ note: String::new(),+ button: "Remove",+ act: if skill { ConfirmAct::RemoveSkill(id) } else { ConfirmAct::RemoveConnector(id) },+ };+ self.overlays.push(Overlay::Market(m));+ self.overlays.push(Overlay::Confirm(c));+ return None;+ }+ _ => {+ if m.query.key(k) {+ m.cursor = 0;+ }+ }+ }+ Some(Overlay::Market(m))+ }++ fn market_enter(&mut self, mut m: Box<Market>) -> Option<Overlay> {+ enum Act {+ Agent(String),+ SignIn(String),+ Custom,+ Install(Value),+ More,+ Skill(String),+ None,+ }+ let act = match self.market_rows(&m).get(m.cursor) {+ Some(Row::Agent(b)) => Act::Agent(s(b, "id")),+ Some(Row::Installed(c)) if c["auth"] == "signedOut" => Act::SignIn(s(c, "id")),+ Some(Row::Custom) => Act::Custom,+ Some(Row::Registry(c)) => Act::Install((*c).clone()),+ Some(Row::More) => Act::More,+ Some(Row::Skill(v)) => Act::Skill(s(v, "source")),+ _ => Act::None,+ };+ match act {+ Act::Agent(id) => {+ self.overlays.push(Overlay::Market(m));+ self.open_agent(&id);+ return None;+ }+ Act::SignIn(id) => {+ self.flash("Starting the sign-in…");+ self.sheet("connectorSignIn", json!({"id": id}), Reply::SignIn);+ }+ Act::Custom => {+ self.overlays.push(Overlay::Market(m));+ self.overlays.push(Overlay::Fields(Box::new(Fields {+ title: "Custom connector".into(),+ note: "Paste the MCP config from a README or another app (Claude, Cursor, VS Code). Every server in it is added.".into(),+ choices: vec![],+ choice: 0,+ inputs: vec![Input {+ name: "config".into(),+ label: "Config".into(),+ secret: false,+ required: true,+ multiline: true,+ placeholder: r#"{"mcpServers": {"name": {"command": "npx", "args": ["-y", "…"]}}}"#.into(),+ ed: Editor::default(),+ }],+ cursor: 0,+ error: None,+ saving: false,+ submit: Submit::Import,+ })));+ return None;+ }+ Act::Install(item) => {+ let options = item["options"].as_array().cloned().unwrap_or_default();+ if options.len() == 1 && options[0]["inputs"].as_array().is_none_or(Vec::is_empty) {+ self.flash(&format!("Adding {}…", s(&item, "title")));+ self.sheet(+ "installConnector",+ json!({"registryName": item["name"], "option": options[0]["id"], "inputs": {}}),+ Reply::FieldsSaved,+ );+ } else {+ let host = self.host.clone();+ let choices = options+ .iter()+ .map(|o| {+ if o["kind"] == "remote" {+ format!("Hosted by {}", s(&item, "title"))+ } else {+ format!("On {host} ({})", s(o, "kind"))+ }+ })+ .collect();+ let mut f = Fields {+ title: format!("Add {}", s(&item, "title")),+ note: format!("Keys are saved on {host} only."),+ choices,+ choice: 0,+ inputs: vec![],+ cursor: 0,+ error: None,+ saving: false,+ submit: Submit::Connector(item),+ };+ connector_inputs(&mut f);+ self.overlays.push(Overlay::Market(m));+ self.overlays.push(Overlay::Fields(Box::new(f)));+ return None;+ }+ }+ Act::More => {+ m.loading = true;+ let search = m.searched.clone().unwrap_or_default();+ self.sheet(+ "marketConnectors",+ json!({"search": search, "cursor": m.next}),+ Reply::Registry { more: true },+ );+ }+ Act::Skill(source) => {+ self.flash("Installing the skill…");+ self.sheet("installSkill", json!({"source": source}), Reply::FieldsSaved);+ }+ Act::None => {}+ }+ Some(Overlay::Market(m))+ }++ // ---------- agent sign-in ----------++ pub fn open_agent(&mut self, backend: &str) {+ let known = self.backends.iter().find(|b| b["id"] == backend).is_some_and(|b| b["signedIn"] == true);+ let mut a = AgentSetup { backend: backend.to_owned(), auth: None, busy: false, cursor: 0, error: None };+ if !known {+ a.busy = true;+ self.sheet("agentAuth", json!({"backend": backend}), Reply::Auth(backend.to_owned()));+ }+ self.overlays.push(Overlay::Agent(a));+ }++ pub fn agent_rows(&self, a: &AgentSetup) -> Vec<SetupRow> {+ let b = self.backends.iter().find(|b| b["id"] == a.backend.as_str());+ let mut rows = vec![];+ if b.is_some_and(|b| b["curated"] == true && b["installed"] != true && b["canInstall"] == true) {+ rows.push(SetupRow::Install);+ }+ let signed_in =+ a.auth.as_ref().map_or_else(|| b.map(|b| &b["signedIn"]) == Some(&json!(true)), |v| v["signedIn"] == true);+ if !signed_in && !a.busy {+ if a.auth.as_ref().is_some_and(|v| v["login"] == true) {+ rows.push(SetupRow::Login);+ }+ for m in a.auth.as_ref().and_then(|v| v["methods"].as_array()).into_iter().flatten() {+ rows.push(SetupRow::Method(m.clone()));+ }+ }+ rows.push(SetupRow::Check);+ rows+ }++ pub(super) fn agent_key(&mut self, mut a: AgentSetup, k: KeyEvent) -> Option<Overlay> {+ let rows = self.agent_rows(&a);+ match k.code {+ KeyCode::Esc | KeyCode::Char('q') => return None,+ KeyCode::Down | KeyCode::Char('j') => a.cursor = (a.cursor + 1).min(rows.len().saturating_sub(1)),+ KeyCode::Up | KeyCode::Char('k') => a.cursor = a.cursor.saturating_sub(1),+ KeyCode::Enter if !a.busy => {+ let backend = a.backend.clone();+ let (cols, rows_n) = crossterm::terminal::size().unwrap_or((80, 24));+ let size = json!({"cols": cols, "rows": rows_n});+ match rows.get(a.cursor) {+ Some(SetupRow::Install) => self.start_setup(&backend, "install", None, &size),+ Some(SetupRow::Login) => self.start_setup(&backend, "login", None, &size),+ Some(SetupRow::Method(m)) => match m["kind"].as_str() {+ Some("terminal") => self.start_setup(&backend, "login", m["id"].as_str(), &size),+ Some("envVar") => {+ let saved: Vec<String> = a+ .auth+ .as_ref()+ .and_then(|v| v["savedEnv"].as_array())+ .into_iter()+ .flatten()+ .filter_map(|x| x.as_str().map(str::to_owned))+ .collect();+ let f = env_fields(&backend, m, &saved, &self.host);+ self.overlays.push(Overlay::Agent(a));+ self.overlays.push(Overlay::Fields(Box::new(f)));+ return None;+ }+ _ => {+ a.busy = true;+ a.error = None;+ self.flash("Finish signing in in the browser on this computer");+ self.sheet(+ "agentAuthenticate",+ json!({"backend": backend, "method": m["id"]}),+ Reply::Auth(backend.clone()),+ );+ }+ },+ Some(SetupRow::Check) | None => {+ a.busy = true;+ a.error = None;+ self.sheet("agentAuth", json!({"backend": backend}), Reply::Auth(backend.clone()));+ }+ }+ }+ _ => {}+ }+ Some(Overlay::Agent(a))+ }++ fn start_setup(&mut self, backend: &str, step: &str, method: Option<&str>, size: &Value) {+ let mut body = json!({"backend": backend, "step": step, "cols": size["cols"], "rows": size["rows"]});+ if let Some(m) = method {+ body["method"] = m.into();+ }+ self.sheet("agentSetup", body, Reply::Setup);+ self.flash("Opening the terminal…");+ }++ /// Keys while the setup terminal has the screen: everything goes to it; ^] leaves.+ pub(super) fn shell_key(&mut self, k: KeyEvent) {+ let Some(sh) = &self.shell else { return };+ let id = sh.id.clone();+ if sh.exited.is_some() {+ self.close_shell();+ return;+ }+ if ctrl(k) && matches!(k.code, KeyCode::Char(']' | '5')) {+ self.call("termClose", json!({"term": id}), After::Nothing);+ self.close_shell();+ return;+ }+ let bytes = key_bytes(k);+ if !bytes.is_empty() {+ self.term_input(&bytes);+ }+ }++ pub(super) fn term_input(&self, bytes: &[u8]) {+ if let Some(sh) = &self.shell {+ let _ = sh.input.send(bytes.to_vec());+ }+ }++ pub fn on_resize(&self, cols: u16, rows: u16) {+ if let Some(sh) = self.shell.as_ref().filter(|s| s.exited.is_none()) {+ self.call("termResize", json!({"term": sh.id, "cols": cols, "rows": rows}), After::Nothing);+ }+ }++ pub(super) fn on_term(&mut self, id: &str, v: &Value) {+ let Some(sh) = self.shell.as_mut().filter(|s| s.id == id) else { return };+ match v["type"].as_str() {+ Some("output") => {+ use base64::Engine as _;+ if let Ok(bytes) =+ base64::engine::general_purpose::STANDARD.decode(v["data"].as_str().unwrap_or_default())+ {+ sh.out.extend_from_slice(&bytes);+ }+ }+ Some("exit") => {+ let code = v["code"].as_i64().unwrap_or(-1);+ sh.exited = Some(code);+ let how = if code == 0 { "Done" } else { "Stopped" };+ sh.out.extend_from_slice(+ format!("\r\n\x1b[2m{how}. Press any key to go back to Codync.\x1b[0m\r\n").as_bytes(),+ );+ }+ _ => {}+ }+ }++ fn close_shell(&mut self) {+ let Some(sh) = self.shell.take() else { return };+ self.call("refreshBackends", json!({}), After::Backends);+ if let Some(Overlay::Agent(a)) = self.overlays.last_mut() {+ a.busy = true;+ self.sheet("agentAuth", json!({"backend": sh.backend}), Reply::Auth(sh.backend.clone()));+ }+ }++ // ---------- fields ----------++ pub(super) fn fields_key(&mut self, mut f: Box<Fields>, k: KeyEvent) -> Option<Overlay> {+ let rows = f.offset() + f.inputs.len();+ let on_choice = f.offset() == 1 && f.cursor == 0;+ let multiline = f.current().is_some_and(|i| i.multiline);+ match k.code {+ KeyCode::Esc => return None,+ _ if newline(k) && multiline => {+ if let Some(i) = f.current() {+ i.ed.insert("\n");+ }+ }+ KeyCode::Enter => self.save_fields(&mut f),+ KeyCode::Char('s') if ctrl(k) => self.save_fields(&mut f),+ KeyCode::Tab | KeyCode::Down => f.cursor = (f.cursor + 1) % rows.max(1),+ KeyCode::BackTab | KeyCode::Up => f.cursor = (f.cursor + rows.max(1) - 1) % rows.max(1),+ KeyCode::Left | KeyCode::Right | KeyCode::Char(' ') if on_choice => {+ f.choice = (f.choice + 1) % f.choices.len();+ connector_inputs(&mut f);+ }+ _ => {+ if let Some(i) = f.current() {+ i.ed.key(k);+ }+ }+ }+ Some(Overlay::Fields(f))+ }++ fn save_fields(&mut self, f: &mut Fields) {+ if f.saving {+ return;+ }+ if let Some(i) = f.inputs.iter().find(|i| i.required && i.ed.text.trim().is_empty()) {+ f.error = Some(format!("{} is required.", i.label));+ return;+ }+ let values: serde_json::Map<String, Value> = f+ .inputs+ .iter()+ .filter(|i| !i.ed.text.trim().is_empty())+ .map(|i| (i.name.clone(), i.ed.text.trim().into()))+ .collect();+ f.saving = true;+ f.error = None;+ match &f.submit {+ Submit::AgentEnv(backend) => {+ if values.is_empty() {+ f.saving = false;+ f.error = Some("Type at least one key.".into());+ return;+ }+ self.sheet("setAgentEnv", json!({"backend": backend, "vars": values}), Reply::FieldsSaved);+ }+ Submit::Connector(item) => {+ let option = item["options"][f.choice]["id"].clone();+ self.sheet(+ "installConnector",+ json!({"registryName": item["name"], "option": option, "inputs": values}),+ Reply::FieldsSaved,+ );+ }+ Submit::Import => self.sheet("importConnectors", json!({"config": values["config"]}), Reply::FieldsSaved),+ }+ }++ // ---------- a message's actions ----------++ pub(super) fn react(&mut self, entry: &str, i: usize) {+ if let Some(e) = REACTIONS.get(i) {+ self.call("react", json!({"entryId": entry, "emoji": e}), After::Nothing);+ }+ }++ /// Saves a message's files to Downloads.+ pub(super) fn save_files(&mut self, bot: &str, data: &Value) {+ let files: Vec<(String, String)> = data["attachments"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|a| Some((a["id"].as_str()?.to_owned(), a["name"].as_str()?.to_owned())))+ .collect();+ if files.is_empty() {+ self.flash("No files on that message");+ return;+ }+ self.flash("Saving…");+ self.client.spawn_download(bot.to_owned(), files, self.tx.clone());+ }++ // ---------- model picker ----------++ /// Loads the models `backend` offers, once per run.+ pub(super) fn want_models(&mut self, backend: &str) {+ if !backend.is_empty() && !self.models.contains_key(backend) {+ self.models.insert(backend.to_owned(), None);+ self.sheet("agentModels", json!({"backend": backend}), Reply::Models(backend.to_owned()));+ }+ }++ /// ←→ on the model field: "default", then each advertised model.+ pub(super) fn cycle_model(&self, backend: &str, current: &str, d: isize) -> Option<String> {+ let list = self.models.get(backend)?.as_ref()?;+ let mut ids = vec![String::new()];+ ids.extend(list.iter().map(|(id, _)| id.clone()));+ let i = ids.iter().position(|x| x == current).unwrap_or(0);+ Some(ids[super::app::cycle(i, d, ids.len())].clone())+ }++ // ---------- replies ----------++ pub(super) fn on_sheet_reply(&mut self, r: Reply, res: Result<Value, String>) {+ let v = match res {+ Ok(v) => v,+ Err(e) => {+ self.sheet_error(&r, e);+ return;+ }+ };+ match r {+ Reply::Memory(bot) => {+ for o in &mut self.overlays {+ if let Overlay::Memory(m) = o+ && m.bot == bot+ {+ let facts: Vec<Fact> = v["facts"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|f| Fact { id: s(f, "id"), content: s(f, "content"), profile: f["kind"] == "profile" })+ .collect();+ m.cursor = m.cursor.min(facts.len().saturating_sub(1));+ m.facts = Some(facts);+ }+ }+ }+ Reply::Routines(bot) => {+ if v["routines"].is_array() {+ for o in &mut self.overlays {+ if let Overlay::Routines(l) = o+ && l.bot == bot+ {+ let items = v["routines"].as_array().cloned().unwrap_or_default();+ l.cursor = l.cursor.min(items.len().saturating_sub(1));+ l.items = Some(items);+ }+ }+ } else {+ // A change: the list comes again.+ self.sheet("routines", json!({"botId": bot}), Reply::Routines(bot.clone()));+ }+ }+ Reply::RoutineSaved => {+ if let Some(i) = self.overlays.iter().rposition(|o| matches!(o, Overlay::Routine(_))) {+ self.overlays.truncate(i);+ }+ self.refresh_sheets();+ }+ Reply::Webhook => {+ let text =+ format!("curl -X POST '{}' -H 'Authorization: Bearer {}' -d '{{}}'", s(&v, "url"), s(&v, "key"));+ super::app::copy(&text);+ self.flash("Copied a curl command that runs it (with its key)");+ }+ Reply::Registry { more } => {+ if let Some(Overlay::Market(m)) =+ self.overlays.iter_mut().rev().find(|o| matches!(o, Overlay::Market(_)))+ {+ let items = v["items"].as_array().cloned().unwrap_or_default();+ if more {+ m.registry.extend(items);+ } else {+ m.registry = items;+ }+ m.next = v["nextCursor"].as_str().filter(|c| !c.is_empty()).map(str::to_owned);+ m.searched.get_or_insert_with(String::new);+ m.loading = false;+ m.error = None;+ }+ }+ Reply::Skills => {+ if let Some(Overlay::Market(m)) =+ self.overlays.iter_mut().rev().find(|o| matches!(o, Overlay::Market(_)))+ {+ m.skills = Some(v["items"].as_array().cloned().unwrap_or_default());+ }+ }+ Reply::Auth(backend) => {+ for o in &mut self.overlays {+ if let Overlay::Agent(a) = o+ && a.backend == backend+ {+ a.auth = Some(v.clone());+ a.busy = false;+ a.error = None;+ a.cursor = 0;+ }+ }+ self.call("refreshBackends", json!({}), After::Nothing);+ }+ Reply::Setup => {+ let Some(id) = v["term"].as_str() else { return };+ let backend = match self.overlays.last() {+ Some(Overlay::Agent(a)) => a.backend.clone(),+ _ => String::new(),+ };+ let input = self.client.spawn_term(id.to_owned(), self.tx.clone());+ self.shell = Some(Shell { id: id.to_owned(), input, backend, exited: None, out: vec![] });+ }+ Reply::FieldsSaved => {+ if let Some(i) = self.overlays.iter().rposition(|o| matches!(o, Overlay::Fields(_))) {+ self.overlays.truncate(i);+ }+ if let Some(Overlay::Agent(a)) = self.overlays.last_mut()+ && v.get("signedIn").is_some()+ {+ a.auth = Some(v);+ a.busy = false;+ }+ self.flash("Saved");+ self.refresh_sheets();+ }+ Reply::SignIn => {+ let url = s(&v, "url");+ super::app::copy(&url);+ if open_browser(&url, &self.url) {+ self.flash("Finish in the browser, then ^r refreshes");+ } else {+ self.flash("Sign-in link copied: open it on this computer, then ^r refreshes");+ }+ }+ Reply::Models(backend) => {+ let list = v["models"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|m| {+ let id = m["id"].as_str()?.to_owned();+ Some((id.clone(), m["name"].as_str().unwrap_or(&id).to_owned()))+ })+ .collect();+ self.models.insert(backend, Some(list));+ }+ Reply::Downloaded => {+ let paths: Vec<String> =+ v["paths"].as_array().into_iter().flatten().filter_map(|p| p.as_str().map(str::to_owned)).collect();+ let names: Vec<&str> =+ paths.iter().filter_map(|p| std::path::Path::new(p).file_name()?.to_str()).collect();+ let dir = paths.first().and_then(|p| std::path::Path::new(p).parent()).map(|d| d.to_string_lossy());+ let home = dirs::home_dir().map(|h| h.to_string_lossy().into_owned()).unwrap_or_default();+ let dir = dir.map(|d| super::app::tilde(&d, &home)).unwrap_or_default();+ self.flash(&format!("Saved {} to {dir}", names.join(", ")));+ }+ Reply::Changed => self.refresh_sheets(),+ }+ }++ fn sheet_error(&mut self, r: &Reply, e: String) {+ match r {+ Reply::Models(backend) => {+ self.models.insert(backend.clone(), Some(vec![]));+ }+ Reply::RoutineSaved => {+ if let Some(Overlay::Routine(f)) = self.overlays.last_mut() {+ f.saving = false;+ f.error = Some(e);+ }+ }+ Reply::FieldsSaved => match self.overlays.last_mut() {+ Some(Overlay::Fields(f)) => {+ f.saving = false;+ f.error = Some(e);+ }+ _ => self.flash(&e),+ },+ Reply::Auth(backend) => {+ for o in &mut self.overlays {+ if let Overlay::Agent(a) = o+ && a.backend == *backend+ {+ a.busy = false;+ a.error = Some(e.clone());+ }+ }+ }+ Reply::Registry { .. } | Reply::Skills => {+ if let Some(Overlay::Market(m)) =+ self.overlays.iter_mut().rev().find(|o| matches!(o, Overlay::Market(_)))+ {+ m.loading = false;+ m.skills.get_or_insert_with(Vec::new);+ m.error = Some(e);+ }+ }+ Reply::Memory(_) | Reply::Routines(_) => {+ for o in &mut self.overlays {+ match o {+ Overlay::Memory(m) => {+ m.facts.get_or_insert_with(Vec::new);+ }+ Overlay::Routines(l) => {+ l.items.get_or_insert_with(Vec::new);+ }+ _ => {}+ }+ }+ self.flash(&e);+ }+ _ => self.flash(&e),+ }+ }++ /// Loads what every open sheet shows again, after a change.+ pub(super) fn refresh_sheets(&mut self) {+ let mut calls: Vec<(&'static str, Value, After)> = vec![];+ for o in &self.overlays {+ match o {+ Overlay::Memory(m) => {+ calls.push(("memory", json!({"botId": m.bot}), After::Sheet(Reply::Memory(m.bot.clone()))));+ }+ Overlay::Routines(l) => {+ calls.push(("routines", json!({"botId": l.bot}), After::Sheet(Reply::Routines(l.bot.clone()))));+ }+ Overlay::Market(_) | Overlay::Form(_) => {+ calls.push(("connectors", json!({}), After::Connectors));+ calls.push(("skills", json!({}), After::Skills));+ }+ _ => {}+ }+ }+ calls.dedup_by(|a, b| a.0 == b.0 && a.1 == b.1);+ for (m, body, after) in calls {+ self.call(m, body, after);+ }+ }++ /// Keeps the installed lists the marketplace and the bot form show.+ pub(super) fn set_plugins(&mut self, connectors: bool, items: Vec<Value>) -> Vec<Toggle> {+ let list = items+ .iter()+ .filter_map(|c| {+ let id = c["id"].as_str()?.to_owned();+ let name = c["name"].as_str().unwrap_or(&id).to_owned();+ Some(Toggle { id, name, on: false })+ })+ .collect();+ if connectors {+ self.plugins.0 = items;+ } else {+ self.plugins.1 = items;+ }+ list+ }+}++/// The inputs of a connector's chosen way to run, defaults filled in.+fn connector_inputs(f: &mut Fields) {+ let Submit::Connector(item) = &f.submit else { return };+ f.inputs = item["options"][f.choice]["inputs"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|i| {+ let name = s(i, "name");+ let description = s(i, "description");+ Input {+ label: name.clone(),+ name,+ secret: i["secret"] == true,+ required: i["required"] == true,+ multiline: false,+ placeholder: if description.is_empty() { s(i, "placeholder") } else { description },+ ed: Editor::with(i["default"].as_str().unwrap_or_default()),+ }+ })+ .collect();+ f.cursor = f.cursor.min(f.offset() + f.inputs.len().saturating_sub(1));+}++fn env_fields(backend: &str, method: &Value, saved: &[String], host: &str) -> Fields {+ let inputs = method["vars"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|v| {+ let name = s(v, "name");+ let has = saved.contains(&name);+ Input {+ label: s(v, "label"),+ secret: v["secret"] != false,+ required: v["optional"] != true && !has,+ multiline: false,+ placeholder: if has { "saved · type to replace".into() } else { name.clone() },+ name,+ ed: Editor::default(),+ }+ })+ .collect();+ let link = s(method, "link");+ Fields {+ title: s(method, "name"),+ note: if link.is_empty() {+ format!("Saved on {host} only.")+ } else {+ format!("Get one at {link} · saved on {host} only.")+ },+ choices: vec![],+ choice: 0,+ inputs,+ cursor: 0,+ error: None,+ saving: false,+ submit: Submit::AgentEnv(backend.to_owned()),+ }+}++/// Bytes a terminal sends for a key.+pub fn key_bytes(k: KeyEvent) -> Vec<u8> {+ let alt = k.modifiers.contains(KeyModifiers::ALT);+ let mut out: Vec<u8> = match k.code {+ KeyCode::Char(c) if ctrl(k) && c.is_ascii_alphabetic() => vec![(c.to_ascii_lowercase() as u8) & 0x1f],+ KeyCode::Char(c) => c.to_string().into_bytes(),+ KeyCode::Enter => b"\r".to_vec(),+ KeyCode::Tab => b"\t".to_vec(),+ KeyCode::BackTab => b"\x1b[Z".to_vec(),+ KeyCode::Backspace => vec![0x7f],+ KeyCode::Esc => vec![0x1b],+ KeyCode::Up => b"\x1b[A".to_vec(),+ KeyCode::Down => b"\x1b[B".to_vec(),+ KeyCode::Right => b"\x1b[C".to_vec(),+ KeyCode::Left => b"\x1b[D".to_vec(),+ KeyCode::Home => b"\x1b[H".to_vec(),+ KeyCode::End => b"\x1b[F".to_vec(),+ KeyCode::Delete => b"\x1b[3~".to_vec(),+ KeyCode::PageUp => b"\x1b[5~".to_vec(),+ KeyCode::PageDown => b"\x1b[6~".to_vec(),+ _ => vec![],+ };+ if alt && !out.is_empty() {+ out.insert(0, 0x1b);+ }+ out+}++/// This computer's IANA time zone (routines run on the host's clock in it).+pub fn local_zone() -> String {+ let valid = |z: &str| chrono_tz::Tz::from_str(z).is_ok();+ if let Ok(tz) = std::env::var("TZ")+ && valid(tz.trim_start_matches(':'))+ {+ return tz.trim_start_matches(':').to_owned();+ }+ std::fs::read_link("/etc/localtime")+ .ok()+ .and_then(|p| p.to_string_lossy().split_once("zoneinfo/").map(|(_, z)| z.to_owned()))+ .filter(|z| valid(z))+ .unwrap_or_else(|| "UTC".into())+}++/// One trigger from what's typed: `webhook`, `every 30m`, a date and time (once),+/// or five cron fields in `zone`.+pub fn parse_when(text: &str, zone: &str, now: i64) -> Result<Value, String> {+ let t = text.trim().to_lowercase();+ if t.is_empty() {+ return Err("Say when it runs.".into());+ }+ if t == "webhook" {+ return Ok(json!({"type": "webhook"}));+ }+ if let Some(rest) = t.strip_prefix("every") {+ let rest = rest.trim();+ let split = rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len());+ let (n, unit) = rest.split_at(split);+ let n: i64 = if n.is_empty() { 1 } else { n.parse().map_err(|_| "Use a whole number, like every 30m.")? };+ let unit = match unit.trim().trim_end_matches('s') {+ "sec" | "second" => 1,+ "m" | "min" | "minute" => 60,+ "h" | "hr" | "hour" => 3600,+ "d" | "day" => 86400,+ "" if n > 0 && !rest.is_empty() => return Err("Add a unit: s, m, h or d.".into()),+ _ => return Err("Use s, m, h or d, like every 2h.".into()),+ };+ return Ok(json!({"type": "interval", "seconds": n * unit}));+ }+ if let Ok(at) = chrono::NaiveDateTime::parse_from_str(&t, "%Y-%m-%d %H:%M") {+ let tz = chrono_tz::Tz::from_str(zone).map_err(|_| "Unknown time zone")?;+ let at = at.and_local_timezone(tz).earliest().ok_or("That time doesn't exist here.")?.timestamp_millis();+ if at <= now {+ return Err("That time has passed.".into());+ }+ return Ok(json!({"type": "once", "at": at}));+ }+ if t.split_whitespace().count() == 5 {+ return Ok(+ json!({"type": "cron", "expression": t.split_whitespace().collect::<Vec<_>>().join(" "), "timeZone": zone}),+ );+ }+ Err("Try 0 9 * * 1-5, every 2h, 2026-10-01 09:00 or webhook.".into())+}++/// A routine's triggers as `parse_when` reads them, when they're one it can write.+pub fn when_text(triggers: &Value, zone: &str) -> Option<String> {+ let [t] = triggers.as_array()?.as_slice() else { return None };+ match t["type"].as_str()? {+ "webhook" => Some("webhook".into()),+ "interval" => {+ let secs = t["seconds"].as_i64()?;+ let (n, u) = [(86400, "d"), (3600, "h"), (60, "m"), (1, "s")].into_iter().find(|(u, _)| secs % u == 0)?;+ Some(format!("every {}{u}", secs / n))+ }+ "cron" if t["timeZone"].as_str() == Some(zone) => t["expression"].as_str().map(str::to_owned),+ "once" => {+ let tz = chrono_tz::Tz::from_str(zone).ok()?;+ let at = chrono::DateTime::from_timestamp_millis(t["at"].as_i64()?)?.with_timezone(&tz);+ Some(at.format("%Y-%m-%d %H:%M").to_string())+ }+ _ => None,+ }+}++/// Opens `url` in this computer's browser, when the host is this computer.+fn open_browser(url: &str, host: &str) -> bool {+ let local = ["//127.0.0.1", "//localhost", "//[::1]"].iter().any(|h| host.contains(h));+ if !local || url.is_empty() {+ return false;+ }+ let cmd = if cfg!(target_os = "macos") { "open" } else { "xdg-open" };+ std::process::Command::new(cmd)+ .arg(url)+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .spawn()+ .is_ok()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn when_reads_what_it_writes() {+ let now = 1_790_470_800_000;+ let zone = "Asia/Taipei";+ assert_eq!(parse_when("webhook", zone, now), Ok(json!({"type": "webhook"})));+ assert_eq!(parse_when("every 30m", zone, now), Ok(json!({"type": "interval", "seconds": 1800})));+ assert_eq!(parse_when("Every 2 hours", zone, now), Ok(json!({"type": "interval", "seconds": 7200})));+ assert!(parse_when("every 5", zone, now).is_err());+ assert!(parse_when("2020-01-01 09:00", zone, now).is_err());+ assert!(parse_when("tomorrow", zone, now).is_err());+ for text in ["0 9 * * 1-5", "every 90m", "every 1d", "webhook", "2030-10-01 09:00"] {+ let t = parse_when(text, zone, now).expect(text);+ let back = when_text(&json!([t]), zone).expect(text);+ assert_eq!(parse_when(&back, zone, now), Ok(t), "{text}");+ }+ // Another zone's cron, or several triggers, stay as they were.+ assert_eq!(when_text(&json!([{"type": "cron", "expression": "0 9 * * *", "timeZone": "UTC"}]), zone), None);+ assert_eq!(when_text(&json!([{"type": "webhook"}, {"type": "webhook"}]), zone), None);+ }++ #[test]+ fn keys_become_terminal_bytes() {+ let k = |code, m| KeyEvent::new(code, m);+ assert_eq!(key_bytes(k(KeyCode::Char('c'), KeyModifiers::CONTROL)), [3]);+ assert_eq!(key_bytes(k(KeyCode::Char('é'), KeyModifiers::NONE)), "é".as_bytes());+ assert_eq!(key_bytes(k(KeyCode::Enter, KeyModifiers::NONE)), b"\r");+ assert_eq!(key_bytes(k(KeyCode::Char('b'), KeyModifiers::ALT)), b"\x1bb");+ assert_eq!(key_bytes(k(KeyCode::Up, KeyModifiers::NONE)), b"\x1b[A");+ }+}diff --git a/host/src/tui/mod.rs b/host/src/tui/mod.rsindex f3d44877..7cbb2d36 100644--- a/host/src/tui/mod.rs+++ b/host/src/tui/mod.rs@@ -2,8 +2,10 @@//! same HTTP + SSE API as the phone and desktop apps (locally: no pairing needed).mod app;+mod manage;mod md;mod net;+mod sheets;mod view;use anyhow::{Context, Result};@@ -17,6 +19,7 @@ use crossterm::terminal::{self, EnterAlternateScreen, LeaveAlternateScreen};use futures::StreamExt;use ratatui::Terminal;use ratatui::backend::CrosstermBackend;+use std::io::Write as _;use std::time::Duration;/// Puts the terminal back however we leave (including a panic).@@ -64,8 +67,26 @@ pub async fn run(url: String, token: Option<String>) -> Result<()> {let mut tick = tokio::time::interval(Duration::from_millis(100));tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);let mut dirty = true;+ // A setup terminal has the real screen (not the alternate one) while it runs.+ let mut in_shell = false;loop {- if dirty {+ if app.shell.is_some() != in_shell {+ in_shell = !in_shell;+ let out = term.backend_mut();+ if in_shell {+ execute!(out, DisableMouseCapture, LeaveAlternateScreen)?;+ write!(out, "\x1b[2J\x1b[H\x1b[2m^] closes the terminal and goes back to Codync\x1b[0m\r\n")?;+ } else {+ execute!(out, EnterAlternateScreen, EnableMouseCapture)?;+ term.clear()?;+ }+ }+ if let Some(sh) = app.shell.as_mut().filter(|s| !s.out.is_empty()) {+ let out = term.backend_mut();+ out.write_all(&std::mem::take(&mut sh.out))?;+ out.flush()?;+ }+ if dirty && !in_shell {app.tick();term.draw(|f| view::draw(f, &mut app))?;dirty = false;@@ -77,6 +98,7 @@ pub async fn run(url: String, token: Option<String>) -> Result<()> {Some(Ok(Event::Mouse(m))) => app.on_mouse(m),Some(Ok(Event::FocusGained)) => app.term_focused = true,Some(Ok(Event::FocusLost)) => app.term_focused = false,+ Some(Ok(Event::Resize(cols, rows))) => app.on_resize(cols, rows),Some(Ok(_)) => {}Some(Err(_)) | None => break,},diff --git a/host/src/tui/net.rs b/host/src/tui/net.rsindex 9c1f65e5..8eb487f0 100644--- a/host/src/tui/net.rs+++ b/host/src/tui/net.rs@@ -9,6 +9,18 @@ use std::time::Duration;use tokio::sync::mpsc::UnboundedSender;use super::app::{After, Msg};+use super::manage::Reply;++/// Methods that start an agent or download something: they can take minutes.+const SLOW: [&str; 7] = [+ "agentAuth",+ "agentAuthenticate",+ "agentModels",+ "setAgentEnv",+ "installConnector",+ "installSkill",+ "importConnectors",+];pub const NOT_INSTALLED: &str = "The Codync host isn't set up on this computer yet.";@@ -42,10 +54,16 @@ impl Client {.post(format!("{}/api/{method}", self.base)).bearer_auth(token).json(body)- .timeout(Duration::from_secs(60))+ .timeout(Duration::from_secs(if SLOW.contains(&method) { 11 * 60 } else { 60 })).send().await- .map_err(|_| format!("Can't reach codync-host at {}. Is it running?", self.base))?;+ .map_err(|e| {+ if e.is_timeout() {+ "The host took too long to answer.".to_owned()+ } else {+ format!("Can't reach codync-host at {}. Is it running?", self.base)+ }+ })?;let ok = res.status().is_success();let v: Value = res.json().await.unwrap_or(Value::Null);if ok { Ok(v) } else { Err(v["error"].as_str().unwrap_or("The host refused that.").to_owned()) }@@ -102,6 +120,80 @@ impl Client {});}+ /// Streams a setup terminal's output (scrollback first) until it exits; returns where its+ /// keys go, sent in order with whatever piled up meanwhile.+ pub fn spawn_term(&self, id: String, tx: UnboundedSender<Msg>) -> UnboundedSender<Vec<u8>> {+ let (keys, mut rx) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();+ let c = self.clone();+ let term = id.clone();+ tokio::spawn(async move {+ use base64::Engine as _;+ while let Some(mut bytes) = rx.recv().await {+ while let Ok(more) = rx.try_recv() {+ bytes.extend(more);+ }+ let data = base64::engine::general_purpose::STANDARD.encode(&bytes);+ let _ = c.call("termInput", &json!({"term": term, "data": data})).await;+ }+ });+ let c = self.clone();+ tokio::spawn(async move {+ let Some(token) = c.token() else { return };+ let res = crate::http().get(format!("{}/term/{id}", c.base)).bearer_auth(token).send().await;+ let Ok(res) = res.and_then(reqwest::Response::error_for_status) else {+ let _ = tx.send(Msg::Term(id, json!({"type": "exit", "code": -1})));+ return;+ };+ let mut body = res.bytes_stream();+ let mut buf = Vec::new();+ while let Some(Ok(chunk)) = body.next().await {+ buf.extend_from_slice(&chunk);+ while let Some(i) = buf.iter().position(|&b| b == b'\n') {+ let line: Vec<u8> = buf.drain(..=i).collect();+ let line = String::from_utf8_lossy(&line);+ let Some(data) = line.trim_end().strip_prefix("data:") else { continue };+ if let Ok(v) = serde_json::from_str::<Value>(data.trim_start())+ && tx.send(Msg::Term(id.clone(), v)).is_err()+ {+ return;+ }+ }+ }+ });+ keys+ }++ /// Saves sent files (`(upload id, name)`) to Downloads, 384 KiB at a time.+ pub fn spawn_download(&self, bot: String, files: Vec<(String, String)>, tx: UnboundedSender<Msg>) {+ use base64::Engine as _;+ let c = self.clone();+ tokio::spawn(async move {+ let save = async {+ let dir = dirs::download_dir().or_else(dirs::home_dir).ok_or("No Downloads folder")?;+ let mut paths = vec![];+ for (id, name) in files {+ let mut data = Vec::new();+ loop {+ let r =+ c.call("readUpload", &json!({"botId": bot, "uploadId": id, "offset": data.len()})).await?;+ let chunk = base64::engine::general_purpose::STANDARD+ .decode(r["data"].as_str().unwrap_or_default())+ .map_err(|e| e.to_string())?;+ data.extend_from_slice(&chunk);+ if chunk.is_empty() || data.len() as u64 >= r["size"].as_u64().unwrap_or(0) {+ break;+ }+ }+ let path = free_path(&dir, &name);+ tokio::fs::write(&path, data).await.map_err(|e| format!("Can't save {name}: {e}"))?;+ paths.push(path.to_string_lossy().into_owned());+ }+ Ok(json!({"paths": paths}))+ };+ let _ = tx.send(Msg::Reply(After::Sheet(Reply::Downloaded), save.await));+ });+ }+/// Streams host events forever, reconnecting with `since = last rev`.pub fn spawn_stream(&self, tx: UnboundedSender<Msg>) {let c = self.clone();@@ -149,3 +241,30 @@ impl Client {});}}++/// `dir/name`, or `name (2)` … when that's taken. The name is only its last part (no `../`).+fn free_path(dir: &std::path::Path, name: &str) -> PathBuf {+ let name =+ std::path::Path::new(name).file_name().map_or_else(|| "file".into(), |n| n.to_string_lossy().into_owned());+ let (stem, ext) = match name.rsplit_once('.') {+ Some((s, e)) if !s.is_empty() => (s.to_owned(), format!(".{e}")),+ _ => (name.clone(), String::new()),+ };+ (1..10_000)+ .map(|i| dir.join(if i == 1 { name.clone() } else { format!("{stem} ({i}){ext}") }))+ .find(|p| !p.exists())+ .unwrap_or_else(|| dir.join(&name))+}++#[cfg(test)]+mod tests {+ #[test]+ fn saved_files_never_overwrite_or_escape() {+ let dir = std::env::temp_dir().join(format!("codync-dl-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ assert_eq!(super::free_path(&dir, "../a.txt"), dir.join("a.txt"));+ std::fs::write(dir.join("a.txt"), "").unwrap();+ assert_eq!(super::free_path(&dir, "a.txt"), dir.join("a (2).txt"));+ std::fs::remove_dir_all(&dir).unwrap();+ }+}diff --git a/host/src/tui/sheets.rs b/host/src/tui/sheets.rsnew file mode 100644index 00000000..64938340--- /dev/null+++ b/host/src/tui/sheets.rs@@ -0,0 +1,406 @@+//! Drawing the `manage` sheets: memory, routines, marketplace, agent sign-in, fields.++// Drawing code reads best with x / y / w / t (theme) / r (rect).+#![allow(clippy::many_single_char_names, clippy::similar_names)]++use ratatui::buffer::Buffer;+use ratatui::layout::{Position, Rect};+use ratatui::style::{Modifier, Style};+use serde_json::Value;++use super::app::{App, Editor};+use super::manage::{+ AgentSetup, Fields, Market, MemorySheet, RoutineField, RoutineForm, RoutineList, Row, SetupRow, TABS, Tab,+};+use super::md::truncate;+use super::view::{+ centered, composer_lines, field_line, frame_box, hline, input_line, put, restyle, rput, set_cursor, theme, u,+ when_future,+};++fn s<'a>(v: &'a Value, k: &str) -> &'a str {+ v[k].as_str().unwrap_or_default()+}++/// Rows `off..` of a list that fit `h` lines with `cursor` on screen.+fn window(cursor: usize, h: usize) -> usize {+ cursor.saturating_sub(h.saturating_sub(1))+}++/// A selectable row's background, highlighted when `sel`.+fn row(buf: &mut Buffer, inner: Rect, y: u16, sel: bool) -> Style {+ let t = theme();+ if sel {+ restyle(buf, Rect::new(inner.x - 1, y, inner.width + 2, 1), t.sel);+ t.sel+ } else {+ t.panel+ }+}++fn footer(buf: &mut Buffer, inner: Rect, error: Option<&str>, keys: &str) {+ let t = theme();+ let by = inner.bottom() - 1;+ if let Some(e) = error {+ put(buf, inner.x, by - 1, inner.width, &truncate(e, usize::from(inner.width)), t.red.patch(t.panel));+ }+ put(buf, inner.x, by, inner.width, keys, t.dim.patch(t.panel));+}++fn name_of(app: &App, bot: &str) -> String {+ app.bots.get(bot).map_or_else(String::new, |b| b.name.clone())+}++pub fn memory(buf: &mut Buffer, area: Rect, app: &App, m: &MemorySheet) {+ let t = theme();+ let r = centered(area, 84, 24);+ let title = format!("{} remembers", name_of(app, &m.bot));+ let inner = frame_box(buf, r, t.text, t.panel, Some((&title, t.text)));+ let list_h = usize::from(inner.height.saturating_sub(3));+ match &m.facts {+ None => {+ put(buf, inner.x, inner.y + 1, inner.width, "Loading…", t.dim.patch(t.panel));+ }+ Some(f) if f.is_empty() => {+ put(+ buf,+ inner.x,+ inner.y + 1,+ inner.width,+ "Nothing yet. The bot remembers who you are and what you work on as you chat.",+ t.secondary.patch(t.panel),+ );+ }+ Some(facts) => {+ for (y, (i, f)) in (inner.y + 1..).zip(facts.iter().enumerate().skip(window(m.cursor, list_h)).take(list_h))+ {+ let base = row(buf, inner, y, i == m.cursor);+ put(buf, inner.x, y, 2, if f.profile { "●" } else { "◷" }, t.dim.patch(base));+ let room = usize::from(inner.width.saturating_sub(2));+ put(buf, inner.x + 2, y, u(room), &truncate(&f.content, room), t.text.patch(base));+ }+ }+ }+ footer(buf, inner, None, "● about you ◷ history · ↑↓ move · x forget · D forget everything · esc close");+}++pub fn routines(buf: &mut Buffer, area: Rect, app: &App, l: &RoutineList) {+ let t = theme();+ let r = centered(area, 90, 24);+ let title = format!("{}'s routines", name_of(app, &l.bot));+ let inner = frame_box(buf, r, t.text, t.panel, Some((&title, t.text)));+ let list_h = usize::from(inner.height.saturating_sub(3)) / 2;+ match &l.items {+ None => {+ put(buf, inner.x, inner.y + 1, inner.width, "Loading…", t.dim.patch(t.panel));+ }+ Some(v) if v.is_empty() => {+ put(+ buf,+ inner.x,+ inner.y + 1,+ inner.width,+ "No routines. n makes one: the bot does something on a schedule or when called.",+ t.secondary.patch(t.panel),+ );+ }+ Some(items) => {+ let mut y = inner.y + 1;+ for (i, it) in items.iter().enumerate().skip(window(l.cursor, list_h)).take(list_h) {+ let base = row(buf, inner, y, i == l.cursor);+ let on = it["enabled"] == true;+ put(buf, inner.x, y, 2, if on { "●" } else { "○" }, if on { t.green } else { t.dim }.patch(base));+ put(buf, inner.x + 2, y, inner.width / 2, s(it, "name"), t.bold.patch(base));+ let next = it["nextRunAt"].as_i64().map(|ms| format!("next {}", when_future(ms)));+ rput(+ buf,+ inner.right(),+ y,+ &next.unwrap_or_else(|| if on { String::new() } else { "off".into() }),+ t.dim.patch(base),+ );+ let when: Vec<&str> =+ it["triggerDescriptions"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();+ let (line, style) = match it["lastError"].as_str() {+ Some(e) => (format!("{} · {e}", when.join(" · ")), t.red),+ None => (when.join(" · "), t.secondary),+ };+ let room = usize::from(inner.width.saturating_sub(2));+ put(buf, inner.x + 2, y + 1, u(room), &truncate(&line, room), style.patch(t.panel));+ y += 2;+ }+ }+ }+ footer(buf, inner, None, "n new · ↵ edit · space on/off · r run now · w copy webhook · x delete · esc");+}++pub fn routine(buf: &mut Buffer, area: Rect, f: &RoutineForm) {+ let t = theme();+ let r = centered(area, 84, 14);+ let title = if f.id.is_some() { "Edit routine" } else { "New routine" };+ let inner = frame_box(buf, r, t.text, t.panel, Some((title, t.text)));+ let label = |on: bool| if on { t.bold } else { t.secondary }.patch(t.panel);+ let vx = inner.x + 9;+ let vw = inner.width.saturating_sub(9);+ let at = |y: u16| Rect::new(vx, y, vw, 1);+ put(buf, inner.x, inner.y, 9, "Name", label(f.field == RoutineField::Name));+ input_line(buf, at(inner.y), inner.y, &f.name, "Morning summary", f.field == RoutineField::Name, false);+ put(buf, inner.x, inner.y + 2, 9, "Do", label(f.field == RoutineField::Instruction));+ multiline(+ buf,+ Rect::new(vx, inner.y + 2, vw, 4),+ &f.instruction,+ "What the bot does each time",+ f.field == RoutineField::Instruction,+ );+ put(buf, inner.x, inner.y + 7, 9, "When", label(f.field == RoutineField::When));+ let placeholder = if f.original_text.is_empty() {+ "0 9 * * 1-5 · every 2h · 2026-10-01 09:00 · webhook"+ } else {+ &f.original_text+ };+ input_line(buf, at(inner.y + 7), inner.y + 7, &f.when, placeholder, f.field == RoutineField::When, false);+ put(+ buf,+ vx,+ inner.y + 8,+ vw,+ &format!("cron runs in {}; every = from now on; webhook = when called", super::manage::local_zone()),+ t.dim.patch(t.panel),+ );+ let by = inner.bottom() - 1;+ if let Some(e) = &f.error {+ put(buf, inner.x, by - 1, inner.width, e, t.red.patch(t.panel));+ }+ let x = put(buf, inner.x, by, 14, if f.saving { " … Saving " } else { " ↵ Save " }, t.btn_primary) + 1;+ put(buf, x, by, 12, " esc Cancel ", t.text.patch(t.btn).add_modifier(Modifier::BOLD));+ rput(buf, inner.right(), by, "tab next field · ⇧↵ new line", t.dim.patch(t.panel));+}++/// A text field over several lines, following its cursor.+fn multiline(buf: &mut Buffer, r: Rect, e: &Editor, placeholder: &str, active: bool) {+ let t = theme();+ if e.text.is_empty() {+ put(buf, r.x, r.y, r.width, placeholder, t.dim.patch(t.panel));+ if active {+ set_cursor(Position::new(r.x, r.y));+ }+ return;+ }+ let (lines, cur) = composer_lines(e, usize::from(r.width.saturating_sub(1)).max(1));+ let first = cur.1.saturating_sub(usize::from(r.height).saturating_sub(1));+ for (j, l) in lines.iter().skip(first).take(usize::from(r.height)).enumerate() {+ put(buf, r.x, r.y + u(j), r.width, l, t.text.patch(t.panel));+ }+ if active {+ set_cursor(Position::new(r.x + u(cur.0), r.y + u(cur.1 - first)));+ }+}++pub fn market(buf: &mut Buffer, area: Rect, app: &App, m: &Market) {+ let t = theme();+ let r = centered(area, 96, 30);+ let title = format!("Marketplace · {}", app.host);+ let inner = frame_box(buf, r, t.text, t.panel, Some((&title, t.text)));+ let mut x = inner.x;+ for (tab, label) in TABS {+ let style = if tab == m.tab { t.btn_primary } else { t.secondary.patch(t.btn) };+ x = put(buf, x, inner.y, 20, &format!(" {label} "), style) + 1;+ }+ let search = Rect::new(x + 2, inner.y, inner.right().saturating_sub(x + 2), 1);+ let placeholder = match m.tab {+ Tab::Connectors => "search the MCP registry",+ _ => "filter",+ };+ field_line(buf, search, inner.y, &m.query, placeholder, true);+ let rows = app.market_rows(m);+ let list_h = usize::from(inner.height.saturating_sub(5));+ let mut y = inner.y + 2;+ if App::market_stale(m) {+ put(buf, inner.x, y, inner.width, "↵ searches the registry", t.secondary.patch(t.panel));+ y += 1;+ }+ for (i, item) in rows.iter().enumerate().skip(window(m.cursor, list_h)).take(list_h) {+ let base = row(buf, inner, y, i == m.cursor);+ let (mark, name, detail, right): (&str, String, String, String) = match item {+ Row::Agent(b) => {+ let status = match (b["installed"] == true, b["signedIn"].as_bool()) {+ (_, Some(true)) => "signed in",+ (true, Some(false)) => "not signed in",+ (true, None) => "installed",+ (false, _) if b["curated"] == true => "not installed",+ (false, _) => "sets up on first use",+ };+ let mark = if b["signedIn"] == true || b["installed"] == true { "✓" } else { "↓" };+ (mark, s(b, "name").into(), s(b, "description").into(), status.into())+ }+ Row::Installed(c) => {+ let right = match s(c, "auth") {+ "signedOut" => "↵ sign in",+ _ if c["kind"] == "composio" => "Composio",+ _ => "installed",+ };+ let detail = c["command"].as_str().or(c["url"].as_str()).unwrap_or(s(c, "description"));+ ("✓", s(c, "name").into(), detail.into(), right.into())+ }+ Row::Custom => ("+", "Custom connector".into(), "Paste any MCP server's config".into(), String::new()),+ Row::Registry(c) => ("↓", s(c, "title").into(), s(c, "description").into(), String::new()),+ Row::More => ("…", "Load more connectors".into(), String::new(), String::new()),+ Row::OwnSkill(v) => ("✓", s(v, "name").into(), s(v, "description").into(), "installed".into()),+ Row::Skill(v) => ("↓", s(v, "name").into(), s(v, "description").into(), String::new()),+ };+ let ok = mark == "✓";+ put(buf, inner.x, y, 2, mark, if ok { t.green } else { t.dim }.patch(base));+ let nx = put(buf, inner.x + 2, y, 26, &truncate(&name, 26), t.bold.patch(base)) + 2;+ let rx = rput(buf, inner.right(), y, &right, t.dim.patch(base));+ let room = usize::from(rx.saturating_sub(nx + 1));+ put(buf, nx, y, u(room), &truncate(&detail.replace('\n', " "), room), t.secondary.patch(base));+ y += 1;+ }+ if rows.is_empty() {+ let msg = if m.loading { "Loading…" } else { "Nothing matches" };+ put(buf, inner.x, y, inner.width, msg, t.dim.patch(t.panel));+ }+ let keys = match m.tab {+ Tab::Agents => "tab switch · ↵ install / sign in · ^r refresh · esc close",+ Tab::Connectors => "tab switch · ↵ add / sign in · ^x remove · ^r refresh · esc",+ Tab::Skills => "tab switch · ↵ install · ^x remove · esc close",+ };+ let loading = m.loading && m.tab == Tab::Connectors && !rows.is_empty();+ footer(buf, inner, m.error.as_deref().or(loading.then_some("Loading the registry…")), keys);+}++pub fn agent(buf: &mut Buffer, area: Rect, app: &App, a: &AgentSetup) {+ let t = theme();+ let b = app.backends.iter().find(|b| b["id"] == a.backend.as_str());+ let name = b.map_or(a.backend.as_str(), |b| s(b, "name"));+ let rows = app.agent_rows(a);+ let r = centered(area, 80, u(rows.len() * 2 + 11).max(14));+ let inner = frame_box(buf, r, t.text, t.panel, Some((name, t.text)));+ let mut y = inner.y;+ if let Some(d) = b.map(|b| s(b, "description")).filter(|d| !d.is_empty()) {+ put(buf, inner.x, y, inner.width, &truncate(d, usize::from(inner.width)), t.secondary.patch(t.panel));+ y += 2;+ }+ let signed_in =+ a.auth.as_ref().map_or_else(|| b.and_then(|b| b["signedIn"].as_bool()), |v| v["signedIn"].as_bool());+ let status = if a.busy {+ if a.auth.is_none() {+ format!("Checking with {name}… the first check can download it.")+ } else {+ "Working…".into()+ }+ } else {+ match signed_in {+ Some(true) => "Signed in.".into(),+ Some(false) => "Not signed in yet.".into(),+ None => format!("Couldn't tell. Skip this if you've already signed in on {}.", app.host),+ }+ };+ let style = if signed_in == Some(true) { t.green } else { t.text };+ put(buf, inner.x, y, inner.width, &status, style.patch(t.panel).add_modifier(Modifier::BOLD));+ y += 1;+ if signed_in != Some(true)+ && let Some(d) = a.auth.as_ref().and_then(|v| v["detail"].as_str()).filter(|d| !d.is_empty())+ {+ put(buf, inner.x, y, inner.width, &truncate(d, usize::from(inner.width)), t.dim.patch(t.panel));+ y += 1;+ }+ y += 1;+ for (i, rw) in rows.iter().enumerate() {+ if y + 1 >= inner.bottom().saturating_sub(2) {+ break;+ }+ let base = row(buf, inner, y, i == a.cursor);+ let (icon, title, detail) = match rw {+ SetupRow::Install => ("↓", "Install".to_owned(), format!("Runs the official installer on {}.", app.host)),+ SetupRow::Login => ("›_", "Sign in".to_owned(), format!("In a terminal on {}.", app.host)),+ SetupRow::Method(m) => {+ let (icon, fallback) = match s(m, "kind") {+ "terminal" => ("›_", format!("In a terminal on {}.", app.host)),+ "envVar" => ("⚿", format!("Saved on {} only.", app.host)),+ _ => ("◎", format!("Opens a browser on {}.", app.host)),+ };+ let d = m["description"].as_str().map_or(fallback, str::to_owned);+ (icon, s(m, "name").to_owned(), d)+ }+ SetupRow::Check => ("↻", "Check again".to_owned(), String::new()),+ };+ put(buf, inner.x, y, 3, icon, t.secondary.patch(base));+ let nx = put(buf, inner.x + 3, y, 30, &title, t.bold.patch(base)) + 2;+ put(+ buf,+ nx,+ y,+ inner.right().saturating_sub(nx),+ &truncate(&detail, usize::from(inner.right().saturating_sub(nx))),+ t.secondary.patch(base),+ );+ y += 1;+ }+ footer(buf, inner, a.error.as_deref(), "↑↓ move · ↵ run · esc back");+}++pub fn fields(buf: &mut Buffer, area: Rect, f: &Fields) {+ let t = theme();+ let tall = f.inputs.iter().any(|i| i.multiline);+ let h = if tall { 20 } else { u(f.inputs.len() * 2 + usize::from(f.choices.len() > 1) * 2 + 8) };+ let r = centered(area, 84, h);+ let inner = frame_box(buf, r, t.text, t.panel, Some((&f.title, t.text)));+ let mut y = inner.y;+ put(buf, inner.x, y, inner.width, &truncate(&f.note, usize::from(inner.width)), t.dim.patch(t.panel));+ y += 2;+ let label_w = 18u16;+ let vx = inner.x + label_w;+ let vw = inner.width.saturating_sub(label_w);+ let mut row_i = 0;+ if f.choices.len() > 1 {+ let on = f.cursor == 0;+ put(buf, inner.x, y, label_w, "Runs", if on { t.bold } else { t.secondary }.patch(t.panel));+ let base = if on { t.sel } else { t.panel };+ put(buf, vx, y, vw, &format!("‹ {} ›", f.choices[f.choice]), t.text.patch(base));+ y += 2;+ row_i = 1;+ }+ for (i, input) in f.inputs.iter().enumerate() {+ let on = f.cursor == row_i + i;+ let star = if input.required { " *" } else { "" };+ put(+ buf,+ inner.x,+ y,+ label_w - 1,+ &truncate(&format!("{}{star}", input.label), usize::from(label_w - 1)),+ if on { t.bold } else { t.secondary }.patch(t.panel),+ );+ if input.multiline {+ multiline(+ buf,+ Rect::new(vx, y, vw, inner.bottom().saturating_sub(y + 3)),+ &input.ed,+ &input.placeholder,+ on,+ );+ break;+ }+ let shown = if input.secret {+ Editor {+ text: "•".repeat(input.ed.text.chars().count()),+ cursor: "•".len() * input.ed.text[..input.ed.cursor].chars().count(),+ }+ } else {+ input.ed.clone()+ };+ input_line(buf, Rect::new(vx, y, vw, 1), y, &shown, &input.placeholder, on, false);+ y += 2;+ }+ let by = inner.bottom() - 1;+ if let Some(e) = &f.error {+ put(buf, inner.x, by - 1, inner.width, e, t.red.patch(t.panel));+ }+ hline(buf, inner.x, by - 2, inner.width, t.line.patch(t.panel));+ let x = put(buf, inner.x, by, 14, if f.saving { " … Saving " } else { " ↵ Save " }, t.btn_primary) + 1;+ put(buf, x, by, 12, " esc Cancel ", t.text.patch(t.btn).add_modifier(Modifier::BOLD));+ let hint = if tall { "⇧↵ new line · paste works" } else { "tab next field" };+ rput(buf, inner.right(), by, hint, t.dim.patch(t.panel));+}diff --git a/host/src/tui/view.rs b/host/src/tui/view.rsindex c9bafa7b..06045927 100644--- a/host/src/tui/view.rs+++ b/host/src/tui/view.rs@@ -285,7 +285,7 @@ pub fn elapsed(start: Option<i64>) -> String {// ---------- buffer helpers -----------fn put(buf: &mut Buffer, x: u16, y: u16, max: u16, s: &str, style: Style) -> u16 {+pub(super) fn put(buf: &mut Buffer, x: u16, y: u16, max: u16, s: &str, style: Style) -> u16 {if max == 0 || y >= buf.area.bottom() {return x;}@@ -301,7 +301,7 @@ fn put_line(buf: &mut Buffer, x: u16, y: u16, max: u16, line: &Line<'_>) -> u16end}-fn rput(buf: &mut Buffer, right: u16, y: u16, s: &str, style: Style) -> u16 {+pub(super) fn rput(buf: &mut Buffer, right: u16, y: u16, s: &str, style: Style) -> u16 {let width = u16::try_from(w(s)).unwrap_or(0);let x = right.saturating_sub(width);put(buf, x, y, width, s, style);@@ -319,11 +319,11 @@ fn fill(buf: &mut Buffer, r: Rect, style: Style) {}}-fn restyle(buf: &mut Buffer, r: Rect, style: Style) {+pub(super) fn restyle(buf: &mut Buffer, r: Rect, style: Style) {buf.set_style(r, style);}-fn hline(buf: &mut Buffer, x: u16, y: u16, width: u16, style: Style) {+pub(super) fn hline(buf: &mut Buffer, x: u16, y: u16, width: u16, style: Style) {put(buf, x, y, width, &"─".repeat(usize::from(width)), style);}@@ -333,7 +333,7 @@ fn vline(buf: &mut Buffer, x: u16, y: u16, h: u16, style: Style) {}}-fn frame_box(buf: &mut Buffer, r: Rect, border: Style, bg: Style, title: Option<(&str, Style)>) -> Rect {+pub(super) fn frame_box(buf: &mut Buffer, r: Rect, border: Style, bg: Style, title: Option<(&str, Style)>) -> Rect {fill(buf, r, bg);if r.width < 2 || r.height < 2 {return r;@@ -359,13 +359,13 @@ fn dim_all(buf: &mut Buffer) {}}-fn centered(area: Rect, width: u16, height: u16) -> Rect {+pub(super) fn centered(area: Rect, width: u16, height: u16) -> Rect {let wd = width.min(area.width.saturating_sub(2));let h = height.min(area.height.saturating_sub(2));Rect::new(area.x + (area.width - wd) / 2, area.y + (area.height - h) / 3, wd, h)}-fn u(n: usize) -> u16 {+pub(super) fn u(n: usize) -> u16 {u16::try_from(n).unwrap_or(u16::MAX)}@@ -439,7 +439,7 @@ thread_local! {static CURSOR: std::cell::Cell<Option<Position>> = const { std::cell::Cell::new(None) };}-fn set_cursor(p: Position) {+pub(super) fn set_cursor(p: Position) {CURSOR.with(|c| c.set(Some(p)));}@@ -471,11 +471,9 @@ fn status_line(buf: &mut Buffer, r: Rect, app: &mut App) {if !app.online {x = put(buf, x, r.y, 20, "offline", t.amber.patch(t.panel)) + 2;}- if let Some((h, _)) = &app.hint {- put(buf, x, r.y, r.right().saturating_sub(x), h, t.amber.patch(t.panel));- }let hint = if insert { "↵ send · esc nav" } else { "? keys" };let mut right = rput(buf, r.right() - 1, r.y, hint, t.dim.patch(t.panel)).saturating_sub(3);+ let mut edge = right;// Usage: the first provider that has numbers, narrowest windows first.if r.width >= 100&& let Some(p) = app.usage["providers"]@@ -497,7 +495,12 @@ fn status_line(buf: &mut Buffer, r: Rect, app: &mut App) {right = sx.saturating_sub(3);}let name = p["name"].as_str().unwrap_or_default().to_lowercase();- rput(buf, right + 1, r.y, &name, t.dim.patch(t.panel));+ edge = rput(buf, right + 1, r.y, &name, t.dim.patch(t.panel)).saturating_sub(2);+ }+ // A flash gets the room between the host and the usage, cut short to fit.+ if let Some((h, _)) = &app.hint {+ let room = edge.saturating_sub(x);+ put(buf, x, r.y, room, &truncate(h, usize::from(room)), t.amber.patch(t.panel));}}@@ -772,7 +775,8 @@ fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {if draft.text.is_empty() {// The apps' wording.let placeholder = if app.pick.is_some() {- "Reply in thread: j k pick a message · ↵ open · esc cancel".to_owned()+ let reply = if app.thread.is_some() { "↵ reply" } else { "↵ thread" };+ format!("j k pick · {reply} · 1–6 react · f save files · c copy · esc")} else if app.thread.is_some() {"Reply…".to_owned()} else if b.group {@@ -780,6 +784,7 @@ fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {} else {format!("Message {}…", b.name)};+ let placeholder = truncate(&placeholder, usize::from(r.width.saturating_sub(5)));put(buf, r.x + 3, comp_top + 1, r.width.saturating_sub(4), &placeholder, t.dim);used = w(&placeholder);} else {@@ -854,7 +859,7 @@ fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {}/// Wraps the draft; returns display lines and the cursor's (column, line).-fn composer_lines(e: &Editor, width: usize) -> (Vec<String>, (usize, usize)) {+pub(super) fn composer_lines(e: &Editor, width: usize) -> (Vec<String>, (usize, usize)) {let mut lines = vec![String::new()];let mut col = 0;let mut cur = (0, 0);@@ -1095,6 +1100,7 @@ fn entry_lines(]));}out.lines.extend(with_bg(body, width, t.band));+ reactions(out, e);out.messages.push((e.id.clone(), from, out.lines.len()));if main {thread_line(out, app, e);@@ -1112,6 +1118,7 @@ fn entry_lines(Span::styled(format!(" {}", clock(e.created_at)), t.dim),]));out.lines.extend(md::render(e.text(), width, 1));+ reactions(out, e);out.messages.push((e.id.clone(), from, out.lines.len()));if let Some(ti) = info.get(&e.turn).filter(|ti| ti.steps > 0) {let files = if ti.files.is_empty() {@@ -1164,6 +1171,14 @@ fn entry_lines(}}+/// A message's reactions, under it.+fn reactions(out: &mut Built, e: &Entry) {+ let r: Vec<&str> = e.data["reactions"].as_array().into_iter().flatten().filter_map(|r| r.as_str()).collect();+ if !r.is_empty() {+ out.lines.push(Line::from(Span::raw(format!(" {}", r.join(" ")))));+ }+}+/// A user message on one line: its text, then its files.fn user_line(e: &Entry) -> String {let files = e.attachments().iter().map(|(n, _)| format!("▤ {n}")).collect::<Vec<_>>().join(" ");@@ -1755,16 +1770,22 @@ fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &Overlay) {Overlay::Group(g) => group_view(buf, area, app, g),Overlay::Usage => usage(buf, area, app),Overlay::Pair(url) => pair(buf, area, url.as_deref()),+ Overlay::Memory(m) => super::sheets::memory(buf, area, app, m),+ Overlay::Routines(l) => super::sheets::routines(buf, area, app, l),+ Overlay::Routine(f) => super::sheets::routine(buf, area, f),+ Overlay::Market(m) => super::sheets::market(buf, area, app, m),+ Overlay::Agent(a) => super::sheets::agent(buf, area, app, a),+ Overlay::Fields(f) => super::sheets::fields(buf, area, f),}}/// A one-line text field. A search shows "/ " first, unless the caller drew its own prefix/// (the folder path, with an empty placeholder).-fn field_line(buf: &mut Buffer, r: Rect, y: u16, e: &Editor, placeholder: &str, active: bool) {+pub(super) fn field_line(buf: &mut Buffer, r: Rect, y: u16, e: &Editor, placeholder: &str, active: bool) {input_line(buf, r, y, e, placeholder, active, !placeholder.is_empty());}-fn input_line(buf: &mut Buffer, r: Rect, y: u16, e: &Editor, placeholder: &str, active: bool, search: bool) {+pub(super) fn input_line(buf: &mut Buffer, r: Rect, y: u16, e: &Editor, placeholder: &str, active: bool, search: bool) {let t = theme();let x = if search { put(buf, r.x, y, 2, "/ ", t.dim.patch(t.panel)) } else { r.x };if e.text.is_empty() {@@ -1891,7 +1912,7 @@ fn goto(buf: &mut Buffer, area: Rect, app: &mut App, g: &super::app::Goto, items);}-const HELP: [(&str, &str, &str); 45] = [+const HELP: [(&str, &str, &str); 51] = [("MOVE", "j k ↑ ↓", "next / previous bot"),("MOVE", "[ ]", "previous / next bot"),("MOVE", "1…9", "jump to bot 1–9"),@@ -1911,7 +1932,10 @@ const HELP: [(&str, &str, &str); 45] = [("CHAT", "o", "last turn's steps"),("CHAT", "c", "copy the last reply"),("CHAT", "r", "reply in a thread"),+ ("CHAT", "v", "pick a message"),("CHAT", "j k ↵", "picking: move / open"),+ ("CHAT", "1…6", "picking: react"),+ ("CHAT", "f", "picking: save its files"),("CHAT", "esc", "close the thread"),("TYPE", "↵", "send"),("TYPE", "⇧↵ alt↵ ^j", "new line"),@@ -1926,6 +1950,9 @@ const HELP: [(&str, &str, &str); 45] = [("BOTS", "e", "edit bot or group"),("BOTS", "p", "pin / unpin"),("BOTS", "S", "new session"),+ ("BOTS", "M", "memory"),+ ("BOTS", "R", "routines"),+ ("BOTS", "A", "marketplace, sign-in"),("BOTS", "x", "delete bot or group"),("VIEW", "t", "trace pane"),("VIEW", "T", "trace full screen"),@@ -1941,8 +1968,8 @@ const HELP: [(&str, &str, &str); 45] = [fn help(buf: &mut Buffer, area: Rect, filter: &Editor) {let t = theme();- // Two columns fit everything from 36 rows up; shorter windows get a third.- let r = centered(area, if area.height >= 36 { 80 } else { 120 }, 34);+ // Two columns fit everything from 42 rows up; shorter windows get a third.+ let r = centered(area, if area.height >= 42 { 80 } else { 120 }, 40);let inner = frame_box(buf, r, t.text, t.panel, Some(("Keys", t.text)));field_line(buf, inner, inner.y, filter, "filter actions and keys", true);let q = filter.text.to_lowercase();@@ -2060,7 +2087,22 @@ fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {Field::Instructions => {text_field(buf, &f.instructions, "e.g. Reviews PRs. Never pushes without asking.", y);}- Field::Model => text_field(buf, &f.model, "default", y),+ Field::Model => {+ text_field(buf, &f.model, "default", y);+ let hint = match app.models.get(&f.backend) {+ Some(None) => "loading models…".to_owned(),+ Some(Some(list)) if !list.is_empty() => {+ let id = f.model.text.trim();+ list.iter()+ .find(|(m, _)| m == id)+ .map_or_else(|| format!("‹ › {} models", list.len()), |(_, name)| format!("‹ {name} ›"))+ }+ _ => String::new(),+ };+ if !hint.is_empty() && w(&f.model.text) + w(&hint) + 2 < usize::from(vw) {+ rput(buf, inner.right(), y, &hint, t.dim.patch(base));+ }+ }Field::Agent => {put(buf, vx, y, vw, &format!("‹ {agent_name} ›"), t.text.patch(base));}@@ -2138,9 +2180,11 @@ fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {let hint = match f.current() {Field::Folder => "↵ project folder · backspace personal · tab next field",Field::Connectors | Field::Skills => "←→ move · space toggle · tab next",- Field::Agent | Field::Color | Field::Shape | Field::Approvals | Field::Notify => "←→ change · tab next field",+ Field::Agent => "←→ change · ↵ install / sign in · tab next",+ Field::Model => "←→ pick a model · or type its id",+ Field::Color | Field::Shape | Field::Approvals | Field::Notify => "←→ change · tab next field",Field::Instructions => "⇧↵ new line · tab next field",- _ => "tab next field · ^s save",+ Field::Name => "tab next field · ^s save",};rput(buf, inner.right(), by, hint, t.dim.patch(t.panel));}@@ -2279,7 +2323,7 @@ fn usage(buf: &mut Buffer, area: Rect, app: &App) {put(buf, inner.x, inner.bottom() - 1, inner.width, "From your local installs. esc close", t.dim.patch(t.panel));}-fn when_future(ms: i64) -> String {+pub(super) fn when_future(ms: i64) -> String {let (day, _) = local(ms);let (today, _) = local(now_ms());if day == today {