M8: command registry, skills as slash commands, completion engine + popup, rpc complete
ci / check (push) Canceled after 0s
ci / check (pull_request) Canceled after 0s

Closes #68, closes #69, closes #70, closes #71, closes #72
This commit is contained in:
hermes committed 2026-09-30 22:05:04 +00:00
1 parent 6f0addcd47
commit 65765ce2b3
10 files changed
+651 -125

No files matched your search

+241 -28
View File
@@ -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<CmdSpec>,
}
pub enum CmdOut {
@@ -89,14 +93,17 @@ struct App {
ctx_tokens: usize,
quit: bool,
hint: String,
specs: Vec<CmdSpec>,
/// open completion popup and selected row
popup: Option<(Completion, usize)>,
/// pending yes/no question from a tool
ask: Option<(String, tokio::sync::oneshot::Sender<bool>)>,
}
const HELP: &str = "enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand tools · pgup/pgdn scroll · tab @file · \
/model <m> · /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<String> {
pub fn project_files(root: &std::path::Path) -> Vec<String> {
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<String> {
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<String> {
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<String> {
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::<Vec<_>>()
.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<String> {
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<Mutex<Agent>>,
@@ -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<Line> = 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<String> {
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::<Vec<_>>(),
*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<String> = (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 ");
}
}