diff --git a/README.md b/README.md index ddb532a..0c290df 100644 --- a/README.md +++ b/README.md @@ -12,9 +12,11 @@ hx --provider codex -p "hello" # one-shot, Codex hx -c # continue last session in this directory ``` -TUI: `enter` send, `alt-enter`/`ctrl-j` newline, `esc` abort, `ctrl-o` expand tool output, `tab` completes `@file` -(mentioned files are attached), `pgup`/`pgdn` scroll. Commands: `/model `, `/provider claude|codex`, -`/compact`, `/clear`, `/quit`. Messages typed while the agent works are queued. +TUI: `enter` send, `alt-enter`/`ctrl-j` newline, `esc` abort, `ctrl-o` expand tool output, `pgup`/`pgdn` scroll. +`/help` lists commands: builtins (`/model`, `/provider`, `/compact`, `/clear`, `/lsp`, `/mcp`, `/quit`), MCP +prompts (`/server:prompt`) and skills. Typing `/` opens a completion popup for commands and their arguments +(`up`/`down` select, `tab`/`enter` accept, `esc` close); `tab` completes `@file` (mentioned files are +attached). Messages typed while the agent works are queued. Config: `~/.hx/config.toml`, overridden per project by `.hx/config.toml`: @@ -48,6 +50,9 @@ description go into the system prompt; the model reads the file when a task matc `~/.agent/skills` (shared with other agents), `~/.hx/skills`, then `.hx/skills` in the project; a later directory wins when names collide. +Each skill is also a command: `/ [args]` sends the skill file plus `args` as the prompt. Builtin +commands win when names collide. + ## Lens After every tool round, hx asks the language server about files the agent wrote or edited and appends @@ -137,8 +142,10 @@ One JSON object per line on stdout. `type` is one of: JSON-RPC 2.0, one message per line on stdin/stdout. Events arrive as `event` notifications (params = the event object above). Methods: `prompt {text}` (replies `{message, usage}` when the run ends), `abort`, -`state`, `messages`, `fork {id}`, `clear`, `set_model {model}`, `compact`. One prompt at a time; other -methods are rejected while it runs (except `abort`). Example client: `examples/rpc_client.py`. +`state`, `messages`, `fork {id}`, `clear`, `set_model {model}`, `compact`, `complete {line, cursor?}` +(replies `{start, items: [{label, detail}]}`; `label` replaces `line[start..cursor]`, cursor is a byte +offset defaulting to the end). One prompt at a time; other methods are rejected while it runs (except +`abort` and `complete`). Example client: `examples/rpc_client.py`. ### Extensions diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index ee482c8..1e248e3 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -118,6 +118,40 @@ impl Config { } } +/// Offered by `/model` completion; any other id still works. +const MODELS: &[&str] = &[ + "claude-sonnet-4-5", + "claude-opus-4-1", + "claude-haiku-4-5", + "gpt-5-codex", + "gpt-5", +]; + +/// Builtins, MCP prompts (`/server:prompt`), then skills (builtins win name clashes). +fn command_specs(mcp: &hx_mcp::Hub, cwd: &std::path::Path) -> Vec { + use hx_core::command::{self as c, ArgKind, CmdSpec, Source}; + let mut v = c::builtins(MODELS); + v.push(CmdSpec::new( + "mcp", + "MCP servers and prompts", + Source::Builtin, + ArgKind::None, + )); + for (n, s) in &mcp.servers { + v.extend(s.prompts.iter().map(|p| { + CmdSpec::new( + &format!("{n}:{}", p["name"].as_str().unwrap_or_default()), + p["description"].as_str().unwrap_or_default(), + Source::Mcp, + ArgKind::Free, + ) + })); + } + let sk = c::skill_specs(&context::skills(&context::hx_home(), cwd), &v); + v.extend(sk); + v +} + fn default_model(k: Kind) -> String { match k { Kind::Claude => "claude-sonnet-4-5", @@ -377,8 +411,9 @@ async fn main() -> Result<()> { .collect(); mgr.warm(probe).await; } + let specs = command_specs(&mcp, &cwd); if cli.mode == Mode::Rpc { - let r = rpc::serve(agent, abort).await; + let r = rpc::serve(agent, abort, specs, hx_tui::project_files(&cwd)).await; mgr.shutdown().await; return r; } @@ -392,6 +427,7 @@ async fn main() -> Result<()> { make_provider: Box::new(provider), default_model, pricing, + specs, commands: { let mcp = mcp.clone(); Box::new(move |name: &str, arg: &str| { diff --git a/crates/hx-cli/src/rpc.rs b/crates/hx-cli/src/rpc.rs index 563dc65..ab3ea33 100644 --- a/crates/hx-cli/src/rpc.rs +++ b/crates/hx-cli/src/rpc.rs @@ -44,8 +44,14 @@ fn reply(id: &Value, r: Result) { } /// Methods: `prompt {text}` (replies when the run ends; events stream meanwhile), `abort`, -/// `state`, `messages`, `fork {id}`, `clear`, `set_model {model}`, `compact`. One prompt at a time. -pub async fn serve(mut agent: Agent, abort: AbortHandle) -> Result<()> { +/// `state`, `messages`, `fork {id}`, `clear`, `set_model {model}`, `compact`, +/// `complete {line, cursor?}` (cursor = byte offset, default end). One prompt at a time. +pub async fn serve( + mut agent: Agent, + abort: AbortHandle, + specs: Vec, + files: Vec, +) -> Result<()> { agent.bus.add(Notify); let agent = Arc::new(Mutex::new(agent)); let busy = Arc::new(std::sync::atomic::AtomicBool::new(false)); @@ -62,7 +68,22 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle) -> Result<()> { let id = m["id"].clone(); let p = &m["params"]; let method = m["method"].as_str().unwrap_or_default(); - // abort must work while a prompt holds the agent lock + // abort and complete must work while a prompt holds the agent lock + if method == "complete" { + let Some(line) = p["line"].as_str() else { + reply(&id, Err("params.line required".into())); + continue; + }; + let cur = p["cursor"].as_u64().map_or(line.len(), |c| c as usize); + let c = hx_core::command::complete(line, cur, &specs, &files); + let items: Vec<_> = c + .items + .iter() + .map(|i| json!({"label": i.label, "detail": i.detail})) + .collect(); + reply(&id, Ok(json!({"start": c.start, "items": items}))); + continue; + } if method == "abort" { abort.abort(); reply(&id, Ok(json!({}))); diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index a3bb18e..f8ea83f 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -98,6 +98,10 @@ impl AbortHandle { pub fn abort(&self) { let _ = self.0.send(true); } + /// A handle not tied to any agent (tests, frontends before the agent exists). + pub fn detached() -> Self { + AbortHandle(Arc::new(watch::channel(false).0)) + } } impl Agent { diff --git a/crates/hx-core/src/command.rs b/crates/hx-core/src/command.rs new file mode 100644 index 0000000..cfdd2c3 --- /dev/null +++ b/crates/hx-core/src/command.rs @@ -0,0 +1,321 @@ +//! Slash-command registry and the completion engine shared by the TUI and RPC mode. + +use crate::context::Skill; +use std::path::PathBuf; + +#[derive(Debug, Clone, PartialEq)] +pub enum Source { + Builtin, + /// `SKILL.md` path; running the command sends its body as a prompt. + Skill(PathBuf), + Mcp, + Ext, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ArgKind { + None, + Free, + Enum(Vec), + Path, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CmdSpec { + /// Without the leading `/`. + pub name: String, + pub summary: String, + pub source: Source, + pub args: ArgKind, +} + +impl CmdSpec { + pub fn new(name: &str, summary: &str, source: Source, args: ArgKind) -> Self { + Self { + name: name.into(), + summary: summary.into(), + source, + args, + } + } +} + +/// Commands handled by the TUI itself. `models` feeds `/model` completion. +pub fn builtins(models: &[&str]) -> Vec { + use ArgKind::*; + let b = |n, s, a| CmdSpec::new(n, s, Source::Builtin, a); + vec![ + b("help", "list commands and keys", None), + b( + "model", + "show or switch model", + Enum(models.iter().map(|m| m.to_string()).collect()), + ), + b( + "provider", + "switch provider", + Enum(vec!["claude".into(), "codex".into()]), + ), + b("compact", "summarize old context", None), + b("clear", "start an empty session", None), + b("lsp", "language server status", None), + b("quit", "exit hx", None), + b("exit", "exit hx", None), + ] +} + +/// One `/` per skill; names taken by `taken` (builtins) are skipped, so builtins win. +pub fn skill_specs(skills: &[Skill], taken: &[CmdSpec]) -> Vec { + skills + .iter() + .filter(|s| { + !s.name.contains(char::is_whitespace) && !taken.iter().any(|t| t.name == s.name) + }) + .map(|s| CmdSpec { + name: s.name.clone(), + summary: s.description.clone(), + source: Source::Skill(s.path.clone()), + args: ArgKind::Free, + }) + .collect() +} + +/// The prompt a `/ args` command sends. +pub fn skill_prompt(name: &str, path: &std::path::Path, arg: &str) -> std::io::Result { + let body = std::fs::read_to_string(path)?; + let ask = if arg.is_empty() { + "Apply this skill." + } else { + arg + }; + Ok(format!( + "\n{body}\n\n\n{ask}", + path.display() + )) +} + +/// `/help` text generated from the registry. +pub fn help(specs: &[CmdSpec]) -> String { + specs + .iter() + .map(|s| { + let arg = match &s.args { + ArgKind::None => "", + ArgKind::Path => " ", + _ => " [args]", + }; + format!("/{}{arg} — {}", s.name, s.summary) + }) + .collect::>() + .join("\n") +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Candidate { + /// Replaces `line[start..cursor]`. + pub label: String, + pub detail: String, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Completion { + /// Byte offset where the completed token starts. + pub start: usize, + pub items: Vec, +} + +pub const MAX_ITEMS: usize = 8; + +/// Complete the token ending at byte `cur` of `line`: +/// `/cmd` at line start → commands; `/cmd partial` → the command's args; `@partial` → files. +pub fn complete(line: &str, cur: usize, specs: &[CmdSpec], files: &[String]) -> Completion { + let cur = floor_boundary(line, cur.min(line.len())); + let before = &line[..cur]; + let start = before + .char_indices() + .rev() + .find(|(_, c)| c.is_whitespace()) + .map_or(0, |(i, c)| i + c.len_utf8()); + let tok = &before[start..]; + let cand = |label: String, detail: &str| Candidate { + label, + detail: detail.into(), + }; + let items = if let Some(q) = tok.strip_prefix('@') { + rank(files.iter().map(String::as_str), q, MAX_ITEMS) + .into_iter() + .map(|f| cand(format!("@{f}"), "")) + .collect() + } else if start == 0 + && let Some(q) = tok.strip_prefix('/') + { + let names: Vec<&str> = specs.iter().map(|s| s.name.as_str()).collect(); + rank(names.iter().copied(), q, MAX_ITEMS) + .into_iter() + .filter_map(|n| specs.iter().find(|s| s.name == n)) + .map(|s| cand(format!("/{}", s.name), &detail(s))) + .collect() + } else if let Some(cmd) = before[..start].strip_prefix('/') + && let [name] = cmd.split_whitespace().collect::>()[..] + && let Some(spec) = specs.iter().find(|s| s.name == name) + { + match &spec.args { + ArgKind::Enum(v) => rank(v.iter().map(String::as_str), tok, MAX_ITEMS) + .into_iter() + .map(|x| cand(x.into(), "")) + .collect(), + ArgKind::Path => rank(files.iter().map(String::as_str), tok, MAX_ITEMS) + .into_iter() + .map(|x| cand(x.into(), "")) + .collect(), + ArgKind::None | ArgKind::Free => vec![], + } + } else { + vec![] + }; + Completion { start, items } +} + +fn detail(s: &CmdSpec) -> String { + let tag = match s.source { + Source::Builtin => "", + Source::Skill(_) => "skill · ", + Source::Mcp => "mcp · ", + Source::Ext => "ext · ", + }; + format!("{tag}{}", s.summary) +} + +fn floor_boundary(s: &str, mut i: usize) -> usize { + while !s.is_char_boundary(i) { + i -= 1; + } + i +} + +/// Case-insensitive subsequence match. Order: basename prefix, basename substring, substring, +/// subsequence; shorter first within a tier. +pub fn rank<'a>(xs: impl Iterator, q: &str, n: usize) -> Vec<&'a str> { + let q = q.to_lowercase(); + let mut hits: Vec<(usize, usize, &str)> = xs + .filter_map(|x| { + let l = x.to_lowercase(); + let mut it = l.chars(); + if !q.chars().all(|c| it.any(|y| y == c)) { + return None; + } + let base = l.rsplit('/').next().unwrap_or(&l); + let tier = if base.starts_with(&q) { + 0 + } else if base.contains(&q) { + 1 + } else if l.contains(&q) { + 2 + } else { + 3 + }; + Some((tier, x.len(), x)) + }) + .collect(); + hits.sort(); + hits.into_iter().take(n).map(|(_, _, x)| x).collect() +} + +/// Longest common prefix of all candidates (char-boundary safe). +pub fn common_prefix>(xs: &[S]) -> String { + let Some(first) = xs.first().map(AsRef::as_ref) else { + return String::new(); + }; + let mut end = first.len(); + for x in &xs[1..] { + end = end.min( + first + .bytes() + .zip(x.as_ref().bytes()) + .take_while(|(a, b)| a == b) + .count(), + ); + } + first[..floor_boundary(first, end)].to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn labels(c: &Completion) -> Vec<&str> { + c.items.iter().map(|i| i.label.as_str()).collect() + } + + #[test] + fn completion_table() { + let t = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(t.path().join("review")).unwrap(); + std::fs::write( + t.path().join("review/SKILL.md"), + "---\nname: review\ndescription: code review\n---\nREVIEW BODY", + ) + .unwrap(); + std::fs::create_dir_all(t.path().join("help")).unwrap(); + std::fs::write(t.path().join("help/SKILL.md"), "---\nname: help\n---\nx").unwrap(); + let skills = crate::context::skills_in(&[t.path().to_path_buf()]); + let mut specs = builtins(&["claude-sonnet-4-5", "claude-opus-4-1", "gpt-5-codex"]); + let sk = skill_specs(&skills, &specs); + assert_eq!(sk.len(), 1, "builtin /help wins over the skill"); + specs.extend(sk); + specs.push(CmdSpec::new( + "fs:grep", + "mcp prompt", + Source::Mcp, + ArgKind::Path, + )); + let files: Vec = [ + "src/main.rs", + "src/lib.rs", + "crates/x/src/main.rs", + "docs/ü.md", + ] + .map(String::from) + .into(); + let c = |l: &str| complete(l, l.len(), &specs, &files); + + assert_eq!(c("/").items.len(), MAX_ITEMS); + assert_eq!(labels(&c("/mo")), ["/model"]); + assert_eq!(labels(&c("/co")), ["/compact"]); + let r = c("/rev"); + assert_eq!(labels(&r), ["/review"]); + assert_eq!(r.items[0].detail, "skill · code review"); + let m = c("/model op"); + assert_eq!((m.start, labels(&m)), (7, vec!["claude-opus-4-1"])); + assert_eq!(c("/model ").items.len(), 3); + assert_eq!(labels(&c("/provider c")), ["codex", "claude"]); + assert_eq!(labels(&c("/fs:grep lib")), ["src/lib.rs"]); + assert!( + c("/review foo").items.is_empty(), + "free args: nothing to offer" + ); + assert!(c("/model a b").items.is_empty()); + assert!(c("say /mo").items.is_empty(), "commands only at line start"); + let a = c("look at @src/ma"); + assert_eq!( + (a.start, labels(&a)), + (8, vec!["@src/main.rs", "@crates/x/src/main.rs"]) + ); + // cursor mid-line, non-ASCII before and inside the token + let l = "héllo @ü rest"; + let u = complete(l, "héllo @ü".len(), &specs, &files); + assert_eq!((u.start, labels(&u)), (7, vec!["@docs/ü.md"])); + assert_eq!( + complete(l, 2, &specs, &files).items.len(), + 0, + "mid-char cursor is safe" + ); + assert_eq!(common_prefix(&["src/a", "src/b"]), "src/"); + assert_eq!(common_prefix(&["ü1", "ü2"]), "ü"); + + let p = skill_prompt("review", &skills[1].path, "PR 7").unwrap(); + assert!(p.contains("REVIEW BODY") && p.ends_with("PR 7"), "{p}"); + let h = help(&specs); + assert!(h.contains("/model [args] — show or switch model") && h.contains("/review")); + } +} diff --git a/crates/hx-core/src/lib.rs b/crates/hx-core/src/lib.rs index c915307..834026c 100644 --- a/crates/hx-core/src/lib.rs +++ b/crates/hx-core/src/lib.rs @@ -1,6 +1,7 @@ //! hx core: tools, hooks, agent loop, sessions, context. pub mod agent; +pub mod command; pub mod context; pub mod ext; pub mod hook; diff --git a/crates/hx-tui/src/editor.rs b/crates/hx-tui/src/editor.rs index 2daa772..3616beb 100644 --- a/crates/hx-tui/src/editor.rs +++ b/crates/hx-tui/src/editor.rs @@ -1,4 +1,4 @@ -//! Multi-line input editor with history and `@file` completion. +//! Multi-line input editor with history. #[derive(Default)] pub struct Editor { @@ -144,26 +144,10 @@ impl Editor { Action::Submit(s) } - /// The `@partial` token ending at the cursor, if any: (start byte, text after '@'). - pub fn at_token(&self) -> Option<(usize, &str)> { - let before = &self.buf[..self.cur]; - let start = before - .rfind(|c: char| c.is_whitespace()) - .map_or(0, |i| i + 1); - before[start..].strip_prefix('@').map(|t| (start, t)) - } - - /// Replace the current `@token` with `@path`. - pub fn complete(&mut self, path: &str, done: bool) { - if let Some((s, _)) = self.at_token() { - let rep = if done { - format!("@{path} ") - } else { - format!("@{path}") - }; - self.buf.replace_range(s..self.cur, &rep); - self.cur = s + rep.len(); - } + /// Replace `buf[start..cur]` with `text`; cursor lands after it. + pub fn replace(&mut self, start: usize, text: &str) { + self.buf.replace_range(start..self.cur, text); + self.cur = start + text.len(); } /// (row, col) of the cursor in chars. @@ -184,52 +168,6 @@ fn advance(buf: &str, from: usize, to: usize, col: usize) -> usize { .map_or(to, |(i, _)| from + i) } -/// Case-insensitive subsequence match; shorter paths and basename hits rank first. -pub fn fuzzy<'a>(files: &'a [String], q: &str, n: usize) -> Vec<&'a String> { - let q = q.to_lowercase(); - let mut hits: Vec<(usize, &String)> = files - .iter() - .filter_map(|f| { - let l = f.to_lowercase(); - let mut it = l.chars(); - if !q.chars().all(|c| it.any(|x| x == c)) { - return None; - } - let base = l.rsplit('/').next().unwrap_or(&l); - let bonus = if base.contains(&q) { - 0 - } else if l.contains(&q) { - 1000 - } else { - 2000 - }; - Some((bonus + f.len(), f)) - }) - .collect(); - hits.sort(); - hits.into_iter().take(n).map(|(_, f)| f).collect() -} - -pub fn common_prefix(xs: &[&String]) -> String { - let Some(first) = xs.first() else { - return String::new(); - }; - let mut end = first.len(); - for x in &xs[1..] { - end = end.min( - first - .bytes() - .zip(x.bytes()) - .take_while(|(a, b)| a == b) - .count(), - ); - } - while !first.is_char_boundary(end) { - end -= 1; - } - first[..end].to_string() -} - #[cfg(test)] mod tests { use super::*; @@ -276,28 +214,10 @@ mod tests { } #[test] - fn at_completion() { - let files: Vec = [ - "src/main.rs", - "src/lib.rs", - "crates/x/src/main.rs", - "README.md", - ] - .map(String::from) - .into(); - assert_eq!(fuzzy(&files, "main", 5), [&files[0], &files[2]]); - assert_eq!(fuzzy(&files, "srlib", 5), [&files[1]]); + fn replace_token() { let mut e = Editor::default(); e.insert("look at @mai"); - assert_eq!(e.at_token(), Some((8, "mai"))); - let hits = fuzzy(&files, "mai", 5); - assert_eq!(common_prefix(&hits), ""); - e.complete("src/main.rs", true); - assert_eq!(e.buf, "look at @src/main.rs "); - assert_eq!(e.at_token(), None); - assert_eq!( - common_prefix(&[&"src/a".to_string(), &"src/b".to_string()]), - "src/" - ); + e.replace(8, "@src/main.rs "); + assert_eq!((e.buf.as_str(), e.cur), ("look at @src/main.rs ", 21)); } } diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index 4b5d818..86bf8a4 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -11,11 +11,13 @@ use futures::StreamExt; use hx_ai::auth::Kind; use hx_ai::{Provider, Usage}; use hx_core::agent::{AbortHandle, Agent}; +use hx_core::command::{self as cmd, CmdSpec, Completion, Source}; use hx_core::hook::{Event, Hook, HookAction}; -use ratatui::layout::{Constraint, Layout}; +use ratatui::layout::{Constraint, Layout, Rect}; use ratatui::style::{Color, Style}; use ratatui::text::Line; -use ratatui::widgets::{Block, Borders, Paragraph, Wrap}; +use ratatui::text::Span; +use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap}; use std::collections::VecDeque; use std::sync::Arc; use tokio::sync::{Mutex, mpsc}; @@ -36,6 +38,8 @@ pub struct Setup { /// Extra slash commands (MCP prompts, `/mcp`): `(name, arg)` -> None = not mine, /// Some(Ok(Send(text))) = send as a user prompt, Some(Ok(Show(text))) = show, Some(Err) = error. pub commands: Commands, + /// Everything completable/listed by `/help`: builtins, skills, MCP prompts, extensions. + pub specs: Vec, } pub enum CmdOut { @@ -89,14 +93,17 @@ struct App { ctx_tokens: usize, quit: bool, hint: String, + specs: Vec, + /// open completion popup and selected row + popup: Option<(Completion, usize)>, /// pending yes/no question from a tool ask: Option<(String, tokio::sync::oneshot::Sender)>, } -const HELP: &str = "enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand tools · pgup/pgdn scroll · tab @file · \ -/model · /provider claude|codex · /compact · /clear · /lsp · /quit"; +const KEYS: &str = "enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand tools · pgup/pgdn scroll · \ +tab complete @file / command · /help commands"; -fn project_files(root: &std::path::Path) -> Vec { +pub fn project_files(root: &std::path::Path) -> Vec { ignore::WalkBuilder::new(root) .hidden(true) .build() @@ -135,6 +142,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { pricing, lsp_status, commands, + specs, } = setup; let (tx, mut rx) = mpsc::unbounded_channel(); agent.bus.add(Forward(tx.clone())); @@ -166,6 +174,8 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { ctx_tokens: hx_core::agent::estimate_tokens(&agent.session.messages()), quit: false, hint: String::new(), + specs, + popup: None, ask: None, }; // show resumed history @@ -183,7 +193,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { } } app.t.push(Item::Info(format!( - "hx · {:?} · {} · {HELP}", + "hx · {:?} · {} · {KEYS}", app.kind, app.model ))); let agent = Arc::new(Mutex::new(agent)); @@ -288,6 +298,38 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option { let alt = k.modifiers.contains(KeyModifiers::ALT); let shift = k.modifiers.contains(KeyModifiers::SHIFT); app.hint.clear(); + if let Some((c, sel)) = &mut app.popup { + let n = c.items.len(); + match k.code { + KeyCode::Up => { + *sel = (*sel + n - 1) % n; + return None; + } + KeyCode::Down => { + *sel = (*sel + 1) % n; + return None; + } + KeyCode::Esc => { + app.popup = None; + return None; + } + KeyCode::Tab => { + accept(app); + return None; + } + // Enter accepts a partly typed token; on an empty or complete one it submits + KeyCode::Enter + if !alt + && !shift + && !matches!(&app.ed.buf[c.start..app.ed.cur], "" | "/" | "@") + && app.ed.buf[c.start..app.ed.cur] != c.items[*sel].label => + { + accept(app); + return None; + } + _ => app.popup = None, + } + } match k.code { KeyCode::Char('c') if ctrl => { if app.busy { @@ -318,8 +360,14 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option { KeyCode::Char('w') if ctrl => app.ed.kill_word(), KeyCode::Char('a') if ctrl => app.ed.home(), KeyCode::Char('e') if ctrl => app.ed.end(), - KeyCode::Char(c) if !ctrl => app.ed.insert(c.encode_utf8(&mut [0; 4])), - KeyCode::Backspace => app.ed.backspace(), + KeyCode::Char(c) if !ctrl => { + app.ed.insert(c.encode_utf8(&mut [0; 4])); + live_popup(app); + } + KeyCode::Backspace => { + app.ed.backspace(); + live_popup(app); + } KeyCode::Delete => app.ed.delete(), KeyCode::Left => app.ed.left(), KeyCode::Right => app.ed.right(), @@ -330,25 +378,20 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option { KeyCode::PageUp => app.scroll = app.scroll.saturating_add(10), KeyCode::PageDown => app.scroll = app.scroll.saturating_sub(10), KeyCode::Tab => { - if let Some((_, q)) = app.ed.at_token() { - let hits = editor::fuzzy(&app.files, q, 8); - match hits.len() { - 0 => app.hint = "no match".into(), - 1 => { - let h = hits[0].clone(); - app.ed.complete(&h, true); - } - _ => { - let pre = editor::common_prefix(&hits); - if pre.len() > q.len() { - app.ed.complete(&pre, false); - } - app.hint = hits - .iter() - .map(|s| s.as_str()) - .collect::>() - .join(" "); + let c = completion(app); + let labels: Vec<&str> = c.items.iter().map(|i| i.label.as_str()).collect(); + match labels.len() { + 0 => app.hint = "no match".into(), + 1 => { + let l = format!("{} ", labels[0]); + app.ed.replace(c.start, &l); + } + _ => { + let pre = cmd::common_prefix(&labels); + if pre.len() > app.ed.cur - c.start { + app.ed.replace(c.start, &pre); } + app.popup = Some((completion(app), 0)); } } } @@ -357,6 +400,29 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option { None } +fn completion(app: &App) -> Completion { + cmd::complete(&app.ed.buf, app.ed.cur, &app.specs, &app.files) +} + +/// Commands and their arguments complete as you type; `@file` waits for Tab (the file list is big). +fn live_popup(app: &mut App) { + app.popup = None; + if !app.ed.buf.starts_with('/') || app.ed.buf.contains('\n') { + return; + } + let c = completion(app); + if !c.items.is_empty() && !app.ed.buf[c.start..app.ed.cur].starts_with('@') { + app.popup = Some((c, 0)); + } +} + +fn accept(app: &mut App) { + if let Some((c, sel)) = app.popup.take() { + app.ed.replace(c.start, &format!("{} ", c.items[sel].label)); + live_popup(app); + } +} + /// Everything `submit` needs besides the app state. struct Ctx<'a> { agent: &'a Arc>, @@ -379,6 +445,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { commands, } = *c; app.scroll = 0; + let shown = line.clone(); if let Some(cmd) = line.clone().strip_prefix('/') { let (c, arg) = cmd .split_once(' ') @@ -389,7 +456,9 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { } match c { "quit" | "exit" => app.quit = true, - "help" => app.t.push(Item::Info(HELP.into())), + "help" => app + .t + .push(Item::Info(format!("{}\n{KEYS}", cmd::help(&app.specs)))), "lsp" => { let st = lsp_status().await; app.t.push(Item::Info(if st.is_empty() { @@ -441,6 +510,14 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { app.ctx_tokens = 0; app.t.push(Item::Info("cleared".into())); } + _ if let Some(Source::Skill(p)) = + app.specs.iter().find(|s| s.name == c).map(|s| &s.source) => + { + match cmd::skill_prompt(c, p, arg) { + Ok(t) => line = t, + Err(e) => app.t.push(Item::Error(format!("/{c}: {e}"))), + } + } _ => match commands(c, arg) { None => app .t @@ -464,7 +541,12 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { app.queue.push_back(line); return; } - app.t.push(Item::User(line.clone())); + // a command that expanded into a prompt shows as typed + app.t.push(Item::User(if shown.starts_with('/') { + shown + } else { + line.clone() + })); app.busy = true; let prompt = expand_mentions(&line, cwd); let (agent, tx) = (agent.clone(), tx.clone()); @@ -541,11 +623,45 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) { .border_style(Style::default().fg(Color::DarkGray)); let inner = block.inner(input); f.render_widget(Paragraph::new(app.ed.buf.as_str()).block(block), input); + if let Some((c, sel)) = &app.popup { + draw_popup(f, c, *sel, input); + } let (r, c) = app.ed.cursor_rc(); let skip = (r as u16).saturating_sub(inner.height.saturating_sub(1)); f.set_cursor_position((inner.x + c as u16, inner.y + r as u16 - skip)); } +/// Candidates stacked just above the input box. +fn draw_popup(f: &mut ratatui::Frame, c: &Completion, sel: usize, input: Rect) { + let h = (c.items.len() as u16).min(input.y); + let w = c + .items + .iter() + .map(|i| i.label.chars().count() + i.detail.chars().count() + 3) + .max() + .unwrap_or(0) + .min(f.area().width as usize) as u16; + let area = Rect::new(input.x, input.y - h, w, h); + let lines: Vec = c + .items + .iter() + .enumerate() + .map(|(n, i)| { + let base = if n == sel { + Style::default().bg(Color::DarkGray).fg(Color::White) + } else { + Style::default() + }; + Line::from(vec![ + Span::styled(format!(" {} ", i.label), base), + Span::styled(format!("{} ", i.detail), base.fg(Color::Gray)), + ]) + }) + .collect(); + f.render_widget(Clear, area); + f.render_widget(Paragraph::new(lines), area); +} + #[cfg(test)] mod tests { use super::*; @@ -577,6 +693,8 @@ mod tests { ctx_tokens: 12_000, quit: false, hint: String::new(), + specs: vec![], + popup: None, ask: None, }; app.t.push(Item::User("hello".into())); @@ -594,4 +712,99 @@ mod tests { assert!(all.contains("Claude · m1 · ctx 12k"), "{all}"); assert!(rows[8].starts_with("typing"), "{all}"); } + + fn key(app: &mut App, code: KeyCode) -> Option { + on_key( + app, + KeyEvent::new(code, KeyModifiers::NONE), + &AbortHandle::detached(), + ) + } + + fn test_app() -> App { + App { + t: Transcript::default(), + ed: Editor::default(), + files: vec!["src/main.rs".into(), "src/lib.rs".into()], + scroll: 0, + expanded: false, + busy: false, + queue: VecDeque::new(), + kind: Kind::Claude, + model: "m1".into(), + usage: Usage::default(), + ctx_tokens: 0, + quit: false, + hint: String::new(), + specs: cmd::builtins(&["sonnet", "opus"]), + popup: None, + ask: None, + } + } + + #[test] + fn popup_keys_and_render() { + let mut app = test_app(); + for c in "/c".chars() { + key(&mut app, KeyCode::Char(c)); + } + let labels = |a: &App| { + a.popup.as_ref().map(|(c, s)| { + ( + c.items.iter().map(|i| i.label.clone()).collect::>(), + *s, + ) + }) + }; + assert_eq!( + labels(&app), + Some((vec!["/clear".into(), "/compact".into()], 0)) + ); + let mut term = ratatui::Terminal::new(TestBackend::new(40, 10)).unwrap(); + term.draw(|f| draw(f, &mut app)).unwrap(); + let buf = term.backend().buffer().clone(); + let rows: Vec = (0..10) + .map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect()) + .collect(); + assert!( + rows[5].starts_with(" /clear start an empty session"), + "{rows:#?}" + ); + assert!(rows[6].starts_with(" /compact summarize"), "{rows:#?}"); + key(&mut app, KeyCode::Down); + key(&mut app, KeyCode::Up); + key(&mut app, KeyCode::Up); + assert_eq!(labels(&app).unwrap().1, 1, "wraps"); + assert_eq!( + key(&mut app, KeyCode::Enter), + None, + "enter accepts partial token" + ); + assert_eq!(app.ed.buf, "/compact "); + assert!(app.popup.is_none(), "no args for /compact"); + assert_eq!(key(&mut app, KeyCode::Enter).as_deref(), Some("/compact ")); + + // args complete live; empty arg + enter submits (shows current model) + for c in "/model ".chars() { + key(&mut app, KeyCode::Char(c)); + } + assert_eq!(labels(&app).unwrap().0, ["opus", "sonnet"]); + assert_eq!(key(&mut app, KeyCode::Enter).as_deref(), Some("/model ")); + + // @file waits for tab; esc closes; up with popup closed browses history + for c in "x @src".chars() { + key(&mut app, KeyCode::Char(c)); + } + assert!(app.popup.is_none()); + key(&mut app, KeyCode::Tab); + assert_eq!(app.ed.buf, "x @src/", "common prefix filled"); + assert_eq!(labels(&app).unwrap().0.len(), 2); + key(&mut app, KeyCode::Esc); + assert!(app.popup.is_none()); + key(&mut app, KeyCode::Char('m')); + key(&mut app, KeyCode::Tab); + assert_eq!(app.ed.buf, "x @src/main.rs "); + key(&mut app, KeyCode::Up); + assert_eq!(app.ed.buf, "/model "); + } } diff --git a/examples/rpc_client.py b/examples/rpc_client.py index ad05165..7001967 100644 --- a/examples/rpc_client.py +++ b/examples/rpc_client.py @@ -29,6 +29,8 @@ def call(method, params=None): return m["result"] +c = call("complete", {"line": "/mo"}) +print(f"COMPLETE {c['start']} {[i['label'] for i in c['items']]}") r = call("prompt", {"text": sys.argv[-1]}) print() s = call("state") diff --git a/tests/m7_e2e.sh b/tests/m7_e2e.sh index 90619cc..55c3e30 100644 --- a/tests/m7_e2e.sh +++ b/tests/m7_e2e.sh @@ -40,6 +40,7 @@ grep -q "Done: file says hi from hx." "$tmp/rpc" || fail "rpc text" "$tmp/rpc" grep -q "> bash" "$tmp/rpc" || fail "rpc events" "$tmp/rpc" grep -q "STATE messages=6 " "$tmp/rpc" || fail "rpc state" "$tmp/rpc" grep -q "BUSY_CHECK claude-x" "$tmp/rpc" || fail "rpc set_model" "$tmp/rpc" +grep -q "COMPLETE 0 \['/model'\]" "$tmp/rpc" || fail "rpc complete" "$tmp/rpc" kill $srv; rm -f hello.txt # 3) extension blocks the bash call (cat) and registers its tool