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

+150 -2
View File
@@ -33,7 +33,62 @@ pub struct Agent {
pub max_turns: u32,
pub usage: Usage,
pub session: Session,
/// Auto-compact when the estimated context exceeds this many tokens.
pub compact_at: usize,
abort: watch::Receiver<bool>,
abort_tx: Arc<watch::Sender<bool>>,
}
const SUMMARY_PROMPT: &str = "Summarize the conversation below for a coding agent that will continue the work. \
Keep: the user's goals and constraints, decisions made, files touched and why, current state, open problems, next steps. \
Be concise and factual. Output only the summary.";
/// Rough token estimate (bytes / 4).
pub fn estimate_tokens(msgs: &[Message]) -> usize {
serde_json::to_string(msgs).map_or(0, |s| s.len() / 4)
}
fn is_prompt(m: &Message) -> bool {
m.role == Role::User
&& !m
.content
.iter()
.any(|b| matches!(b, ContentBlock::ToolResult { .. }))
}
fn transcript(msgs: &[Message]) -> String {
let cut = |s: &str| -> String {
if s.len() > 800 {
format!("{}…", s.chars().take(800).collect::<String>())
} else {
s.to_string()
}
};
let mut t = String::new();
for m in msgs {
let who = if m.role == Role::User {
"USER"
} else {
"ASSISTANT"
};
for b in &m.content {
match b {
ContentBlock::Text { text } => t.push_str(&format!("{who}: {text}\n")),
ContentBlock::ToolUse { name, input, .. } => {
t.push_str(&format!("TOOL CALL {name}: {}\n", cut(&input.to_string())))
}
ContentBlock::ToolResult {
content, is_error, ..
} => t.push_str(&format!(
"TOOL RESULT{}: {}\n",
if *is_error { " (error)" } else { "" },
cut(content)
)),
_ => {}
}
}
}
t
}
/// Cheap handle to cancel a running `Agent::run`.
@@ -53,6 +108,7 @@ impl Agent {
cx: ToolCtx,
) -> (Self, AbortHandle) {
let (tx, rx) = watch::channel(false);
let tx = Arc::new(tx);
let a = Self {
provider,
tools,
@@ -64,9 +120,53 @@ impl Agent {
max_turns: 200,
usage: Usage::default(),
session,
compact_at: 150_000,
abort: rx,
abort_tx: tx.clone(),
};
(a, AbortHandle(Arc::new(tx)))
(a, AbortHandle(tx))
}
pub fn abort_handle(&self) -> AbortHandle {
AbortHandle(self.abort_tx.clone())
}
/// Summarize everything before the most recent user prompts, keeping at least `keep` messages verbatim.
/// The session file keeps full history; the head moves to a new root. Returns false if nothing to cut.
/// ponytail: cuts only at user prompts, so one very long tool loop from a single prompt can't be compacted.
pub async fn compact(&mut self, keep: usize) -> Result<bool, Error> {
let msgs = self.session.messages();
let Some(cut) = (1..=msgs.len().saturating_sub(keep))
.rev()
.find(|&i| is_prompt(&msgs[i]))
else {
return Ok(false);
};
let req = Request {
model: self.model.clone(),
system: SUMMARY_PROMPT.into(),
messages: vec![Message::user(transcript(&msgs[..cut]))],
tools: vec![],
max_tokens: 4096,
};
let mut s = self.provider.stream(req).await?;
let mut summary = None;
while let Some(ev) = s.next().await {
if let StreamEvent::Done { message, usage, .. } = ev? {
self.usage.add(&usage);
summary = Some(message.text());
}
}
let summary = summary.ok_or(Error::Truncated)?;
let mut kept = msgs[cut..].to_vec();
kept[0].content.insert(
0,
ContentBlock::Text {
text: format!("[Summary of earlier conversation]\n{summary}\n[End of summary]"),
},
);
self.session.rebase(kept)?;
Ok(true)
}
fn push(&mut self, m: Message) -> Result<(), Error> {
@@ -83,12 +183,25 @@ impl Agent {
}
/// Run until the model stops calling tools (and no hook injects more work).
/// An abort ends this run only; the next `run` starts un-aborted.
pub async fn run(&mut self, prompt: impl Into<String>) -> Result<Message, Error> {
let r = self.run_inner(prompt.into()).await;
self.abort_tx
.send_if_modified(|a| std::mem::replace(a, false));
r
}
async fn run_inner(&mut self, prompt: String) -> Result<Message, Error> {
self.push(Message::user(prompt))?;
for _ in 0..self.max_turns {
if self.aborted() {
return Err(Error::Aborted);
}
if estimate_tokens(&self.session.messages()) > self.compact_at
&& self.compact(6).await?
{
self.emit(Event::Info("context compacted".into())).await;
}
self.emit(Event::TurnStart).await;
let req = Request {
model: self.model.clone(),
@@ -112,7 +225,7 @@ impl Agent {
}
None => break,
},
_ = abort.changed() => return Err(Error::Aborted),
_ = async { abort.wait_for(|a| *a).await.is_ok() } => return Err(Error::Aborted),
}
}
let (msg, stop, usage) = done.ok_or(Error::Truncated)?;
@@ -378,4 +491,39 @@ mod tests {
h.abort();
assert!(matches!(a.run("again").await, Err(Error::Aborted)));
}
#[tokio::test]
async fn compaction() {
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
let script = Arc::new(Script(
Mutex::new(vec![text("r1"), text("r2"), text("SUMMARY"), text("r3")]),
Mutex::new(vec![]),
));
let dir = tempfile::tempdir().unwrap();
let cx = ToolCtx {
cwd: dir.path().into(),
state: Default::default(),
};
let path = dir.path().join("s.jsonl");
let (mut a, _h) = Agent::new(
script.clone(),
Registry::default(),
Session::open(&path).unwrap(),
cx,
);
a.run("p1").await.unwrap();
a.run("p2").await.unwrap();
assert!(!a.compact(10).await.unwrap(), "nothing old enough to cut");
assert!(a.compact(2).await.unwrap());
let m = a.session.messages();
assert_eq!(m.len(), 2);
assert!(m[0].text().contains("SUMMARY") && m[0].text().ends_with("p2"));
{
let reqs = script.1.lock().unwrap();
let t = reqs[2].messages[0].text();
assert!(t.contains("USER: p1") && t.contains("ASSISTANT: r1") && !t.contains("p2"));
}
a.run("p3").await.unwrap();
assert_eq!(Session::open(&path).unwrap().messages().len(), 4);
}
}