M2: interactive TUI, config, model switching, compaction
ci / check (push) Canceled after 0s

- hx-tui: ratatui app with streaming transcript, markdown-ish rendering, tool call status,
  colored edit diffs, collapsible bash/read output (ctrl-o), scrollback, spinner + footer (provider, model, ctx, tokens)
- editor: multi-line, history, word/line kill, bracketed paste, @file fuzzy tab completion; mentioned files attached
- message queue while agent runs; esc/ctrl-c abort; /model /provider /compact /clear /help /quit; resumed history shown
- hx-core: compaction (summarize older prompts, keep recent verbatim, session rebase keeps full file history),
  auto-compact at threshold; abort only ends current run
- config: ~/.hx/config.toml + project .hx/config.toml (provider, per-provider models, compact_at, max_tokens, system_prompt)
- API-equivalent cost estimate in exit summary
- tests/tui_smoke.py drives the real TUI in a pty against the fake API

Closes #15, closes #16, closes #17, closes #18, closes #19
This commit is contained in:
hermes committed 2026-09-30 10:37:56 +00:00
1 parent 21d4d2bb3d
commit 89c9833e43
13 files changed
+2875 -48

No files matched your search

+303
View File
@@ -0,0 +1,303 @@
//! Multi-line input editor with history and `@file` completion.
#[derive(Default)]
pub struct Editor {
pub buf: String,
/// byte offset, always on a char boundary
pub cur: usize,
history: Vec<String>,
/// index into history while browsing; None = editing a fresh line
hist_pos: Option<usize>,
stash: String,
}
pub enum Action {
None,
Submit(String),
}
impl Editor {
pub fn insert(&mut self, s: &str) {
// normalize pasted CRLF
let s = s.replace("\r\n", "\n").replace('\r', "\n");
self.buf.insert_str(self.cur, &s);
self.cur += s.len();
}
fn prev_boundary(&self) -> usize {
self.buf[..self.cur]
.char_indices()
.next_back()
.map_or(0, |(i, _)| i)
}
fn next_boundary(&self) -> usize {
self.buf[self.cur..]
.chars()
.next()
.map_or(self.cur, |c| self.cur + c.len_utf8())
}
fn line_start(&self) -> usize {
self.buf[..self.cur].rfind('\n').map_or(0, |i| i + 1)
}
fn line_end(&self) -> usize {
self.buf[self.cur..]
.find('\n')
.map_or(self.buf.len(), |i| self.cur + i)
}
pub fn backspace(&mut self) {
if self.cur > 0 {
let p = self.prev_boundary();
self.buf.replace_range(p..self.cur, "");
self.cur = p;
}
}
pub fn delete(&mut self) {
let n = self.next_boundary();
self.buf.replace_range(self.cur..n, "");
}
pub fn left(&mut self) {
self.cur = self.prev_boundary();
}
pub fn right(&mut self) {
self.cur = self.next_boundary();
}
pub fn home(&mut self) {
self.cur = self.line_start();
}
pub fn end(&mut self) {
self.cur = self.line_end();
}
/// Delete from line start to cursor.
pub fn kill_line(&mut self) {
let s = self.line_start();
self.buf.replace_range(s..self.cur, "");
self.cur = s;
}
pub fn kill_word(&mut self) {
let before = &self.buf[..self.cur];
let trimmed = before.trim_end();
let s = trimmed.rfind(char::is_whitespace).map_or(0, |i| i + 1);
self.buf.replace_range(s..self.cur, "");
self.cur = s;
}
/// Up: previous line in a multi-line buffer, else history.
pub fn up(&mut self) {
let ls = self.line_start();
if ls > 0 {
let col = self.buf[ls..self.cur].chars().count();
let pls = self.buf[..ls - 1].rfind('\n').map_or(0, |i| i + 1);
self.cur = advance(&self.buf, pls, ls - 1, col);
return;
}
if self.history.is_empty() {
return;
}
let i = match self.hist_pos {
None => {
self.stash = std::mem::take(&mut self.buf);
self.history.len() - 1
}
Some(0) => 0,
Some(i) => i - 1,
};
self.hist_pos = Some(i);
self.buf = self.history[i].clone();
self.cur = self.buf.len();
}
pub fn down(&mut self) {
let le = self.line_end();
if le < self.buf.len() {
let col = self.buf[self.line_start()..self.cur].chars().count();
let nle = self.buf[le + 1..]
.find('\n')
.map_or(self.buf.len(), |i| le + 1 + i);
self.cur = advance(&self.buf, le + 1, nle, col);
return;
}
match self.hist_pos {
None => {}
Some(i) if i + 1 < self.history.len() => {
self.hist_pos = Some(i + 1);
self.buf = self.history[i + 1].clone();
}
Some(_) => {
self.hist_pos = None;
self.buf = std::mem::take(&mut self.stash);
}
}
self.cur = self.buf.len();
}
pub fn submit(&mut self) -> Action {
let s = std::mem::take(&mut self.buf);
self.cur = 0;
self.hist_pos = None;
if s.trim().is_empty() {
return Action::None;
}
if self.history.last() != Some(&s) {
self.history.push(s.clone());
}
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();
}
}
/// (row, col) of the cursor in chars.
pub fn cursor_rc(&self) -> (usize, usize) {
let before = &self.buf[..self.cur];
(
before.matches('\n').count(),
before[self.line_start()..].chars().count(),
)
}
}
/// Byte offset `col` chars into `buf[from..to]`, clamped to `to`.
fn advance(buf: &str, from: usize, to: usize, col: usize) -> usize {
buf[from..to]
.char_indices()
.nth(col)
.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::*;
#[test]
fn edit_and_multiline_nav() {
let mut e = Editor::default();
e.insert("héllo");
e.left();
e.backspace();
assert_eq!(e.buf, "hélo");
e.insert("\r\nworld");
assert_eq!(e.buf, "hél\r\nworldo".replace("\r\n", "\n"));
assert_eq!(e.cursor_rc(), (1, 5));
e.up();
assert_eq!(e.cursor_rc(), (0, 3));
e.down();
assert_eq!(e.cursor_rc(), (1, 3));
e.end();
e.kill_line();
assert_eq!(e.buf, "hél\n");
e.insert("a b");
e.kill_word();
assert_eq!(e.buf, "hél\na ");
}
#[test]
fn history_and_submit() {
let mut e = Editor::default();
assert!(matches!(e.submit(), Action::None));
for s in ["a", "b"] {
e.insert(s);
assert!(matches!(e.submit(), Action::Submit(x) if x == s));
}
e.insert("draft");
e.up();
assert_eq!(e.buf, "b");
e.up();
e.up();
assert_eq!(e.buf, "a");
e.down();
e.down();
assert_eq!(e.buf, "draft");
}
#[test]
fn at_completion() {
let files: Vec<String> = [
"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]]);
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/"
);
}
}