- 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:
1 parent
21d4d2bb3d
commit
89c9833e43
13 files changed
+2875
-48
No files matched your search
@@ -15,7 +15,10 @@ clap = { version = "4.6.7", features = ["derive", "env"] }
|
||||
hx-ai = { version = "0.1.0", path = "../hx-ai" }
|
||||
hx-core = { version = "0.1.0", path = "../hx-core" }
|
||||
hx-tools = { version = "0.1.0", path = "../hx-tools" }
|
||||
hx-tui = { version = "0.1.0", path = "../hx-tui" }
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "signal"] }
|
||||
toml = "1.1.6"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+112
-13
@@ -18,9 +18,9 @@ struct Cli {
|
||||
/// Print mode: send one prompt, stream the reply to stdout, exit.
|
||||
#[arg(short, long)]
|
||||
print: Option<String>,
|
||||
/// claude | codex
|
||||
#[arg(long, env = "HX_PROVIDER", default_value = "claude")]
|
||||
provider: Kind,
|
||||
/// claude | codex (default from ~/.hx/config.toml, else claude)
|
||||
#[arg(long, env = "HX_PROVIDER")]
|
||||
provider: Option<Kind>,
|
||||
#[arg(short, long, env = "HX_MODEL")]
|
||||
model: Option<String>,
|
||||
/// Session file to resume (JSONL). Default: new file under ~/.hx/sessions.
|
||||
@@ -39,11 +39,70 @@ enum Cmd {
|
||||
Logout { provider: Kind },
|
||||
}
|
||||
|
||||
fn default_model(k: Kind) -> &'static str {
|
||||
/// `~/.hx/config.toml`, overridden by `.hx/config.toml` in the project.
|
||||
#[derive(Default, serde::Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
struct Config {
|
||||
provider: Option<Kind>,
|
||||
model: Option<String>,
|
||||
claude_model: Option<String>,
|
||||
codex_model: Option<String>,
|
||||
/// Auto-compact threshold in estimated tokens.
|
||||
compact_at: Option<usize>,
|
||||
max_tokens: Option<u32>,
|
||||
/// Replaces the built-in system prompt (AGENTS.md etc. are still appended).
|
||||
system_prompt: Option<String>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
fn load(cwd: &std::path::Path) -> Result<Self> {
|
||||
let mut c = Config::default();
|
||||
for p in [
|
||||
context::hx_home().join("config.toml"),
|
||||
cwd.join(".hx/config.toml"),
|
||||
] {
|
||||
let Ok(s) = std::fs::read_to_string(&p) else {
|
||||
continue;
|
||||
};
|
||||
let o: Config =
|
||||
toml::from_str(&s).map_err(|e| anyhow::anyhow!("{}: {e}", p.display()))?;
|
||||
c = Config {
|
||||
provider: o.provider.or(c.provider),
|
||||
model: o.model.or(c.model),
|
||||
claude_model: o.claude_model.or(c.claude_model),
|
||||
codex_model: o.codex_model.or(c.codex_model),
|
||||
compact_at: o.compact_at.or(c.compact_at),
|
||||
max_tokens: o.max_tokens.or(c.max_tokens),
|
||||
system_prompt: o.system_prompt.or(c.system_prompt),
|
||||
};
|
||||
}
|
||||
Ok(c)
|
||||
}
|
||||
}
|
||||
|
||||
fn default_model(k: Kind) -> String {
|
||||
match k {
|
||||
Kind::Claude => "claude-sonnet-4-5",
|
||||
Kind::Codex => "gpt-5-codex",
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// USD per million tokens. ponytail: subscription usage isn't billed per token; this is an API-equivalent estimate.
|
||||
fn pricing(model: &str) -> Option<hx_ai::Pricing> {
|
||||
let p = |input, output, cache_read, cache_write| hx_ai::Pricing {
|
||||
input,
|
||||
output,
|
||||
cache_read,
|
||||
cache_write,
|
||||
};
|
||||
Some(match model {
|
||||
m if m.contains("opus") => p(15.0, 75.0, 1.5, 18.75),
|
||||
m if m.contains("sonnet") => p(3.0, 15.0, 0.3, 3.75),
|
||||
m if m.contains("haiku") => p(1.0, 5.0, 0.1, 1.25),
|
||||
m if m.starts_with("gpt-5") => p(1.25, 10.0, 0.125, 0.0),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn provider(k: Kind) -> hx_ai::Result<Arc<dyn Provider>> {
|
||||
@@ -117,10 +176,16 @@ async fn main() -> Result<()> {
|
||||
Some(Cmd::Logout { provider }) => return Ok(auth::logout(provider)?),
|
||||
None => {}
|
||||
}
|
||||
let Some(prompt) = cli.print else {
|
||||
anyhow::bail!("interactive mode not implemented yet; use -p \"prompt\"");
|
||||
};
|
||||
let cwd = std::env::current_dir()?;
|
||||
let cfg = Config::load(&cwd)?;
|
||||
let kind = cli.provider.or(cfg.provider).unwrap_or(Kind::Claude);
|
||||
let model = cli.model.or(cfg.model).unwrap_or_else(|| {
|
||||
match kind {
|
||||
Kind::Claude => cfg.claude_model.clone(),
|
||||
Kind::Codex => cfg.codex_model.clone(),
|
||||
}
|
||||
.unwrap_or_else(|| default_model(kind))
|
||||
});
|
||||
let dir = session_dir(&cwd);
|
||||
let path = match (cli.session, cli.r#continue) {
|
||||
(Some(p), _) => p,
|
||||
@@ -140,15 +205,30 @@ async fn main() -> Result<()> {
|
||||
state: Default::default(),
|
||||
};
|
||||
let (mut agent, abort) = Agent::new(
|
||||
provider(cli.provider)?,
|
||||
provider(kind)?,
|
||||
hx_tools::registry(),
|
||||
Session::open(&path)?,
|
||||
cx,
|
||||
);
|
||||
agent.model = cli
|
||||
.model
|
||||
.unwrap_or_else(|| default_model(cli.provider).into());
|
||||
agent.system = context::system_prompt(None, &context::hx_home(), &cwd);
|
||||
agent.model = model;
|
||||
agent.system = context::system_prompt(cfg.system_prompt.as_deref(), &context::hx_home(), &cwd);
|
||||
if let Some(n) = cfg.compact_at {
|
||||
agent.compact_at = n;
|
||||
}
|
||||
if let Some(n) = cfg.max_tokens {
|
||||
agent.max_tokens = n;
|
||||
}
|
||||
let Some(prompt) = cli.print else {
|
||||
hx_tui::run(hx_tui::Setup {
|
||||
agent,
|
||||
kind,
|
||||
make_provider: Box::new(provider),
|
||||
default_model,
|
||||
pricing,
|
||||
})
|
||||
.await?;
|
||||
return Ok(());
|
||||
};
|
||||
agent.bus.add(Printer);
|
||||
tokio::spawn(async move {
|
||||
if tokio::signal::ctrl_c().await.is_ok() {
|
||||
@@ -157,8 +237,11 @@ async fn main() -> Result<()> {
|
||||
});
|
||||
let r = agent.run(prompt).await;
|
||||
let u = &agent.usage;
|
||||
let cost = pricing(&agent.model)
|
||||
.map(|p| format!(" ~${:.4}", u.cost(&p)))
|
||||
.unwrap_or_default();
|
||||
eprintln!(
|
||||
"[{} in / {} out tokens; session {}]",
|
||||
"[{} in / {} out tokens{cost}; session {}]",
|
||||
u.input_tokens + u.cache_read_tokens,
|
||||
u.output_tokens,
|
||||
path.display()
|
||||
@@ -166,3 +249,19 @@ async fn main() -> Result<()> {
|
||||
r?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn config_parse() {
|
||||
let c: Config =
|
||||
toml::from_str("provider = \"codex\"\ncodex_model = \"gpt-5\"\ncompact_at = 1000")
|
||||
.unwrap();
|
||||
assert_eq!(c.provider, Some(Kind::Codex));
|
||||
assert_eq!(c.codex_model.as_deref(), Some("gpt-5"));
|
||||
assert!(toml::from_str::<Config>("typo = 1").is_err());
|
||||
assert!(pricing("claude-sonnet-4-5").is_some() && pricing("mystery").is_none());
|
||||
}
|
||||
}
|
||||
+150
-2
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,8 @@ pub enum Event {
|
||||
/// Streaming output from the model (UI).
|
||||
Stream(StreamEvent),
|
||||
Message(Message),
|
||||
/// Human-readable notice for the UI (compaction etc).
|
||||
Info(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
|
||||
@@ -72,6 +72,15 @@ impl Session {
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Start a new root with `msgs` (used by compaction). Old entries stay in the file.
|
||||
pub fn rebase(&mut self, msgs: Vec<Message>) -> std::io::Result<()> {
|
||||
self.head = None;
|
||||
for m in msgs {
|
||||
self.append(m)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Move head to `id` so the next append branches from it.
|
||||
pub fn fork(&mut self, id: u64) -> bool {
|
||||
let ok = self.entries.iter().any(|e| e.id == id);
|
||||
|
||||
@@ -5,6 +5,15 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
async-trait = "0.1.92"
|
||||
crossterm = { version = "0.29.0", features = ["event-stream"] }
|
||||
futures = "0.3.34"
|
||||
hx-ai = { version = "0.1.0", path = "../hx-ai" }
|
||||
hx-core = { version = "0.1.0", path = "../hx-core" }
|
||||
ignore = "0.4.33"
|
||||
ratatui = { version = "0.30.2", features = ["unstable-rendered-line-info"] }
|
||||
serde_json = "1.0.151"
|
||||
tokio = { version = "1.53.1", features = ["rt", "macros", "sync", "time", "rt-multi-thread"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -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/"
|
||||
);
|
||||
}
|
||||
}
|
||||
+491
-5
@@ -1,14 +1,500 @@
|
||||
pub fn add(left: u64, right: u64) -> u64 {
|
||||
left + right
|
||||
//! Interactive terminal UI.
|
||||
|
||||
pub mod editor;
|
||||
pub mod transcript;
|
||||
|
||||
use crossterm::event::{
|
||||
Event as TEvent, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers,
|
||||
};
|
||||
use editor::{Action, Editor};
|
||||
use futures::StreamExt;
|
||||
use hx_ai::auth::Kind;
|
||||
use hx_ai::{Provider, Usage};
|
||||
use hx_core::agent::{AbortHandle, Agent};
|
||||
use hx_core::hook::{Event, Hook, HookAction};
|
||||
use ratatui::layout::{Constraint, Layout};
|
||||
use ratatui::style::{Color, Style};
|
||||
use ratatui::text::Line;
|
||||
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{Mutex, mpsc};
|
||||
use transcript::{Item, Transcript};
|
||||
|
||||
pub type MakeProvider = Box<dyn Fn(Kind) -> hx_ai::Result<Arc<dyn Provider>> + Send>;
|
||||
|
||||
pub struct Setup {
|
||||
pub agent: Agent,
|
||||
pub kind: Kind,
|
||||
pub make_provider: MakeProvider,
|
||||
/// Default model per provider, used on `/provider`.
|
||||
pub default_model: fn(Kind) -> String,
|
||||
/// Pricing lookup for the footer; None = unknown.
|
||||
pub pricing: fn(&str) -> Option<hx_ai::Pricing>,
|
||||
}
|
||||
|
||||
enum Ui {
|
||||
Ev(Event),
|
||||
Done(Result<(), String>),
|
||||
Compacted(Result<bool, String>),
|
||||
}
|
||||
|
||||
/// Forwards agent events to the UI loop.
|
||||
struct Forward(mpsc::UnboundedSender<Ui>);
|
||||
#[async_trait::async_trait]
|
||||
impl Hook for Forward {
|
||||
async fn on(&self, ev: &Event) -> HookAction {
|
||||
let _ = self.0.send(Ui::Ev(ev.clone()));
|
||||
HookAction::Continue
|
||||
}
|
||||
}
|
||||
|
||||
struct App {
|
||||
t: Transcript,
|
||||
ed: Editor,
|
||||
files: Vec<String>,
|
||||
/// lines scrolled up from the bottom
|
||||
scroll: u16,
|
||||
expanded: bool,
|
||||
busy: bool,
|
||||
queue: VecDeque<String>,
|
||||
kind: Kind,
|
||||
model: String,
|
||||
usage: Usage,
|
||||
ctx_tokens: usize,
|
||||
quit: bool,
|
||||
hint: String,
|
||||
}
|
||||
|
||||
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 · /quit";
|
||||
|
||||
fn project_files(root: &std::path::Path) -> Vec<String> {
|
||||
ignore::WalkBuilder::new(root)
|
||||
.hidden(true)
|
||||
.build()
|
||||
.flatten()
|
||||
.filter(|e| e.file_type().is_some_and(|t| t.is_file()))
|
||||
.filter_map(|e| {
|
||||
e.path()
|
||||
.strip_prefix(root)
|
||||
.ok()
|
||||
.map(|p| p.to_string_lossy().into_owned())
|
||||
})
|
||||
.take(20_000)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Expand `@path` mentions of existing files into attached contents.
|
||||
fn expand_mentions(s: &str, root: &std::path::Path) -> String {
|
||||
let mut att = String::new();
|
||||
for w in s.split_whitespace().filter_map(|w| w.strip_prefix('@')) {
|
||||
let p = root.join(w);
|
||||
if let Ok(c) = std::fs::read_to_string(&p)
|
||||
&& c.len() < 200_000
|
||||
{
|
||||
att.push_str(&format!("\n\n<file path=\"{w}\">\n{c}\n</file>"));
|
||||
}
|
||||
}
|
||||
format!("{s}{att}")
|
||||
}
|
||||
|
||||
pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
let Setup {
|
||||
mut agent,
|
||||
kind,
|
||||
make_provider,
|
||||
default_model,
|
||||
pricing,
|
||||
} = setup;
|
||||
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||
agent.bus.add(Forward(tx.clone()));
|
||||
let abort: AbortHandle = agent.abort_handle();
|
||||
let cwd = agent.cx.cwd.clone();
|
||||
let mut app = App {
|
||||
t: Transcript::default(),
|
||||
ed: Editor::default(),
|
||||
files: project_files(&cwd),
|
||||
scroll: 0,
|
||||
expanded: false,
|
||||
busy: false,
|
||||
queue: VecDeque::new(),
|
||||
kind,
|
||||
model: agent.model.clone(),
|
||||
usage: Usage::default(),
|
||||
ctx_tokens: hx_core::agent::estimate_tokens(&agent.session.messages()),
|
||||
quit: false,
|
||||
hint: String::new(),
|
||||
};
|
||||
// show resumed history
|
||||
for m in agent.session.messages() {
|
||||
for b in &m.content {
|
||||
match (m.role, b) {
|
||||
(hx_ai::Role::User, hx_ai::ContentBlock::Text { text }) => {
|
||||
app.t.push(Item::User(text.clone()))
|
||||
}
|
||||
(hx_ai::Role::Assistant, hx_ai::ContentBlock::Text { text }) => {
|
||||
app.t.push(Item::Assistant(text.clone()))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
app.t.push(Item::Info(format!(
|
||||
"hx · {:?} · {} · {HELP}",
|
||||
app.kind, app.model
|
||||
)));
|
||||
let agent = Arc::new(Mutex::new(agent));
|
||||
|
||||
let mut term = ratatui::init();
|
||||
let mut keys = EventStream::new();
|
||||
let mut tick = tokio::time::interval(std::time::Duration::from_millis(50));
|
||||
let mut dirty = true;
|
||||
while !app.quit {
|
||||
if std::mem::take(&mut dirty) {
|
||||
term.draw(|f| draw(f, &mut app))?;
|
||||
}
|
||||
tokio::select! {
|
||||
k = keys.next() => {
|
||||
let Some(Ok(ev)) = k else { break };
|
||||
dirty = true;
|
||||
match ev {
|
||||
TEvent::Key(k) if k.kind != KeyEventKind::Release => {
|
||||
if let Some(line) = on_key(&mut app, k, &abort) {
|
||||
submit(&mut app, line, &agent, &tx, &make_provider, default_model, &cwd).await;
|
||||
}
|
||||
}
|
||||
TEvent::Paste(s) => app.ed.insert(&s),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some(u) = rx.recv() => {
|
||||
dirty = true;
|
||||
match u {
|
||||
Ui::Ev(e) => {
|
||||
if let Event::Stream(hx_ai::StreamEvent::Done { usage, .. }) = &e {
|
||||
app.usage.add(usage);
|
||||
app.ctx_tokens = (usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens + usage.output_tokens) as usize;
|
||||
}
|
||||
app.t.apply(&e);
|
||||
}
|
||||
Ui::Done(r) => {
|
||||
app.busy = false;
|
||||
match r {
|
||||
Err(e) if e == "aborted" => app.t.push(Item::Info("aborted".into())),
|
||||
Err(e) => app.t.push(Item::Error(e)),
|
||||
Ok(()) => {}
|
||||
}
|
||||
if let Some(next) = app.queue.pop_front() {
|
||||
submit(&mut app, next, &agent, &tx, &make_provider, default_model, &cwd).await;
|
||||
}
|
||||
}
|
||||
Ui::Compacted(r) => {
|
||||
app.busy = false;
|
||||
app.t.push(match r {
|
||||
Ok(true) => Item::Info("context compacted".into()),
|
||||
Ok(false) => Item::Info("nothing to compact".into()),
|
||||
Err(e) => Item::Error(e),
|
||||
});
|
||||
app.ctx_tokens = hx_core::agent::estimate_tokens(&agent.lock().await.session.messages());
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = tick.tick(), if app.busy => dirty = true,
|
||||
}
|
||||
}
|
||||
ratatui::restore();
|
||||
let a = agent.lock().await;
|
||||
let cost = pricing(&a.model)
|
||||
.map(|p| format!(" ${:.4}", app.usage.cost(&p)))
|
||||
.unwrap_or_default();
|
||||
eprintln!(
|
||||
"[{} in / {} out tokens{cost}; session {}]",
|
||||
app.usage.input_tokens + app.usage.cache_read_tokens,
|
||||
app.usage.output_tokens,
|
||||
a.session.path().display()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns a line to submit, if any.
|
||||
fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
|
||||
let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
|
||||
let alt = k.modifiers.contains(KeyModifiers::ALT);
|
||||
let shift = k.modifiers.contains(KeyModifiers::SHIFT);
|
||||
app.hint.clear();
|
||||
match k.code {
|
||||
KeyCode::Char('c') if ctrl => {
|
||||
if app.busy {
|
||||
app.queue.clear();
|
||||
abort.abort();
|
||||
} else if app.ed.buf.is_empty() {
|
||||
app.quit = true;
|
||||
} else {
|
||||
app.ed = std::mem::take(&mut app.ed);
|
||||
app.ed.buf.clear();
|
||||
app.ed.cur = 0;
|
||||
}
|
||||
}
|
||||
KeyCode::Char('d') if ctrl && app.ed.buf.is_empty() && !app.busy => app.quit = true,
|
||||
KeyCode::Esc if app.busy => {
|
||||
app.queue.clear();
|
||||
abort.abort();
|
||||
}
|
||||
KeyCode::Char('o') if ctrl => app.expanded = !app.expanded,
|
||||
KeyCode::Char('j') if ctrl => app.ed.insert("\n"),
|
||||
KeyCode::Enter if alt || shift => app.ed.insert("\n"),
|
||||
KeyCode::Enter => {
|
||||
if let Action::Submit(s) = app.ed.submit() {
|
||||
return Some(s);
|
||||
}
|
||||
}
|
||||
KeyCode::Char('u') if ctrl => app.ed.kill_line(),
|
||||
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::Delete => app.ed.delete(),
|
||||
KeyCode::Left => app.ed.left(),
|
||||
KeyCode::Right => app.ed.right(),
|
||||
KeyCode::Home => app.ed.home(),
|
||||
KeyCode::End => app.ed.end(),
|
||||
KeyCode::Up => app.ed.up(),
|
||||
KeyCode::Down => app.ed.down(),
|
||||
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(" ");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
async fn submit(
|
||||
app: &mut App,
|
||||
line: String,
|
||||
agent: &Arc<Mutex<Agent>>,
|
||||
tx: &mpsc::UnboundedSender<Ui>,
|
||||
make_provider: &MakeProvider,
|
||||
default_model: fn(Kind) -> String,
|
||||
cwd: &std::path::Path,
|
||||
) {
|
||||
app.scroll = 0;
|
||||
if let Some(cmd) = line.strip_prefix('/') {
|
||||
let (c, arg) = cmd
|
||||
.split_once(' ')
|
||||
.map_or((cmd, ""), |(a, b)| (a, b.trim()));
|
||||
if app.busy && c != "quit" {
|
||||
app.t.push(Item::Error("busy; esc to abort first".into()));
|
||||
return;
|
||||
}
|
||||
match c {
|
||||
"quit" | "exit" => app.quit = true,
|
||||
"help" => app.t.push(Item::Info(HELP.into())),
|
||||
"model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.model))),
|
||||
"model" => {
|
||||
agent.lock().await.model = arg.into();
|
||||
app.model = arg.into();
|
||||
app.t.push(Item::Info(format!("model → {arg}")));
|
||||
}
|
||||
"provider" => match arg
|
||||
.parse::<Kind>()
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|k| make_provider(k).map(|p| (k, p)).map_err(|e| e.to_string()))
|
||||
{
|
||||
Ok((k, p)) => {
|
||||
let mut a = agent.lock().await;
|
||||
a.provider = p;
|
||||
a.model = default_model(k);
|
||||
app.kind = k;
|
||||
app.model = a.model.clone();
|
||||
app.t
|
||||
.push(Item::Info(format!("provider → {k:?} ({})", app.model)));
|
||||
}
|
||||
Err(e) => app.t.push(Item::Error(e)),
|
||||
},
|
||||
"compact" => {
|
||||
app.busy = true;
|
||||
app.t.push(Item::Info("compacting…".into()));
|
||||
let (agent, tx) = (agent.clone(), tx.clone());
|
||||
tokio::spawn(async move {
|
||||
let r = agent
|
||||
.lock()
|
||||
.await
|
||||
.compact(4)
|
||||
.await
|
||||
.map_err(|e| e.to_string());
|
||||
let _ = tx.send(Ui::Compacted(r));
|
||||
});
|
||||
}
|
||||
"clear" => {
|
||||
let mut a = agent.lock().await;
|
||||
let _ = a.session.rebase(vec![]);
|
||||
app.t = Transcript::default();
|
||||
app.ctx_tokens = 0;
|
||||
app.t.push(Item::Info("cleared".into()));
|
||||
}
|
||||
_ => app
|
||||
.t
|
||||
.push(Item::Error(format!("unknown command /{c}; /help"))),
|
||||
}
|
||||
return;
|
||||
}
|
||||
if app.busy {
|
||||
app.t.push(Item::Info(format!(
|
||||
"queued: {}",
|
||||
line.lines().next().unwrap_or_default()
|
||||
)));
|
||||
app.queue.push_back(line);
|
||||
return;
|
||||
}
|
||||
app.t.push(Item::User(line.clone()));
|
||||
app.busy = true;
|
||||
let prompt = expand_mentions(&line, cwd);
|
||||
let (agent, tx) = (agent.clone(), tx.clone());
|
||||
tokio::spawn(async move {
|
||||
let r = agent
|
||||
.lock()
|
||||
.await
|
||||
.run(prompt)
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(|e| e.to_string());
|
||||
let _ = tx.send(Ui::Done(r));
|
||||
});
|
||||
}
|
||||
|
||||
fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
let input_h = (app.ed.buf.lines().count().max(1) + usize::from(app.ed.buf.ends_with('\n')))
|
||||
.min(10) as u16
|
||||
+ 2;
|
||||
let [main, status, input] = Layout::vertical([
|
||||
Constraint::Min(3),
|
||||
Constraint::Length(1),
|
||||
Constraint::Length(input_h),
|
||||
])
|
||||
.areas(f.area());
|
||||
|
||||
let para = Paragraph::new(app.t.lines(app.expanded)).wrap(Wrap { trim: false });
|
||||
let total = para.line_count(main.width) as u16;
|
||||
let max_up = total.saturating_sub(main.height);
|
||||
app.scroll = app.scroll.min(max_up);
|
||||
f.render_widget(para.scroll((max_up - app.scroll, 0)), main);
|
||||
|
||||
let spin = if app.busy {
|
||||
["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"][(std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis()
|
||||
/ 80
|
||||
% 10) as usize]
|
||||
} else {
|
||||
" "
|
||||
};
|
||||
let q = if app.queue.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" · {} queued", app.queue.len())
|
||||
};
|
||||
let up = if app.scroll > 0 {
|
||||
format!(" · ↑{}", app.scroll)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let st = if app.hint.is_empty() {
|
||||
format!(
|
||||
"{spin} {:?} · {} · ctx {}k · {}↑ {}↓{q}{up}",
|
||||
app.kind,
|
||||
app.model,
|
||||
app.ctx_tokens / 1000,
|
||||
app.usage.input_tokens + app.usage.cache_read_tokens,
|
||||
app.usage.output_tokens
|
||||
)
|
||||
} else {
|
||||
app.hint.clone()
|
||||
};
|
||||
f.render_widget(
|
||||
Line::styled(st, Style::default().fg(Color::DarkGray)),
|
||||
status,
|
||||
);
|
||||
|
||||
let block = Block::default()
|
||||
.borders(Borders::TOP | Borders::BOTTOM)
|
||||
.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);
|
||||
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));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ratatui::backend::TestBackend;
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
let result = add(2, 2);
|
||||
assert_eq!(result, 4);
|
||||
fn mentions() {
|
||||
let d = std::env::temp_dir().join(format!("hx-tui-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
std::fs::write(d.join("a.txt"), "AAA").unwrap();
|
||||
let s = expand_mentions("see @a.txt and @nope", &d);
|
||||
assert!(s.starts_with("see @a.txt and @nope") && s.contains("<file path=\"a.txt\">\nAAA"));
|
||||
assert!(!s.contains("nope\">"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draw_snapshot() {
|
||||
let mut app = App {
|
||||
t: Transcript::default(),
|
||||
ed: Editor::default(),
|
||||
files: vec![],
|
||||
scroll: 0,
|
||||
expanded: false,
|
||||
busy: false,
|
||||
queue: VecDeque::new(),
|
||||
kind: Kind::Claude,
|
||||
model: "m1".into(),
|
||||
usage: Usage::default(),
|
||||
ctx_tokens: 12_000,
|
||||
quit: false,
|
||||
hint: String::new(),
|
||||
};
|
||||
app.t.push(Item::User("hello".into()));
|
||||
app.t.push(Item::Assistant("hi **there**".into()));
|
||||
app.ed.insert("typing");
|
||||
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();
|
||||
let all = rows.join("\n");
|
||||
assert!(all.contains("> hello"), "{all}");
|
||||
assert!(all.contains("hi there"), "{all}");
|
||||
assert!(all.contains("Claude · m1 · ctx 12k"), "{all}");
|
||||
assert!(rows[8].starts_with("typing"), "{all}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
//! Transcript model and rendering (markdown-ish text, tool calls, diffs).
|
||||
|
||||
use hx_ai::StreamEvent;
|
||||
use hx_core::hook::Event;
|
||||
use ratatui::style::{Color, Modifier, Style};
|
||||
use ratatui::text::{Line, Span};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Item {
|
||||
User(String),
|
||||
Assistant(String),
|
||||
Thinking(String),
|
||||
Tool {
|
||||
id: String,
|
||||
name: String,
|
||||
args: Value,
|
||||
result: Option<(String, bool)>,
|
||||
},
|
||||
Info(String),
|
||||
Error(String),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Transcript {
|
||||
pub items: Vec<Item>,
|
||||
/// true while the last Assistant/Thinking item is still streaming
|
||||
streaming: bool,
|
||||
}
|
||||
|
||||
impl Transcript {
|
||||
pub fn push(&mut self, i: Item) {
|
||||
self.streaming = false;
|
||||
self.items.push(i);
|
||||
}
|
||||
|
||||
pub fn apply(&mut self, ev: &Event) {
|
||||
match ev {
|
||||
Event::Stream(StreamEvent::TextDelta { text }) => match self.items.last_mut() {
|
||||
Some(Item::Assistant(s)) if self.streaming => s.push_str(text),
|
||||
_ => {
|
||||
self.push(Item::Assistant(text.clone()));
|
||||
self.streaming = true;
|
||||
}
|
||||
},
|
||||
Event::Stream(StreamEvent::ThinkingDelta { text }) => match self.items.last_mut() {
|
||||
Some(Item::Thinking(s)) if self.streaming => s.push_str(text),
|
||||
_ => {
|
||||
self.push(Item::Thinking(text.clone()));
|
||||
self.streaming = true;
|
||||
}
|
||||
},
|
||||
Event::Stream(StreamEvent::Done { .. }) => self.streaming = false,
|
||||
Event::ToolCall { id, name, args } => self.push(Item::Tool {
|
||||
id: id.clone(),
|
||||
name: name.clone(),
|
||||
args: args.clone(),
|
||||
result: None,
|
||||
}),
|
||||
Event::ToolResult {
|
||||
id,
|
||||
content,
|
||||
is_error,
|
||||
..
|
||||
} => {
|
||||
if let Some(Item::Tool { result, .. }) = self
|
||||
.items
|
||||
.iter_mut()
|
||||
.rev()
|
||||
.find(|i| matches!(i, Item::Tool { id: x, .. } if x == id))
|
||||
{
|
||||
*result = Some((content.clone(), *is_error));
|
||||
}
|
||||
}
|
||||
Event::Info(s) => self.push(Item::Info(s.clone())),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lines(&self, expanded: bool) -> Vec<Line<'static>> {
|
||||
let mut out = vec![];
|
||||
for it in &self.items {
|
||||
render(it, expanded, &mut out);
|
||||
out.push(Line::default());
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn dim() -> Style {
|
||||
Style::default().fg(Color::DarkGray)
|
||||
}
|
||||
|
||||
fn summary(name: &str, args: &Value) -> String {
|
||||
let s = ["path", "command", "pattern", "query"]
|
||||
.iter()
|
||||
.find_map(|k| args[*k].as_str());
|
||||
let s = s.map_or_else(|| args.to_string(), str::to_string);
|
||||
let first = s.lines().next().unwrap_or_default();
|
||||
let mut t: String = first.chars().take(120).collect();
|
||||
if t.len() < s.len() {
|
||||
t.push('…');
|
||||
}
|
||||
format!("{name} {t}")
|
||||
}
|
||||
|
||||
fn render(it: &Item, expanded: bool, out: &mut Vec<Line<'static>>) {
|
||||
match it {
|
||||
Item::User(s) => {
|
||||
for (i, l) in s.lines().enumerate() {
|
||||
let p = if i == 0 { "> " } else { " " };
|
||||
out.push(Line::from(vec![
|
||||
Span::styled(
|
||||
p,
|
||||
Style::default()
|
||||
.fg(Color::Cyan)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
Span::styled(l.to_string(), Style::default().add_modifier(Modifier::BOLD)),
|
||||
]));
|
||||
}
|
||||
}
|
||||
Item::Assistant(s) => markdown(s, out),
|
||||
Item::Thinking(s) => {
|
||||
for l in s.lines() {
|
||||
out.push(Line::styled(
|
||||
l.to_string(),
|
||||
dim().add_modifier(Modifier::ITALIC),
|
||||
));
|
||||
}
|
||||
}
|
||||
Item::Info(s) => out.push(Line::styled(format!("· {s}"), dim())),
|
||||
Item::Error(s) => out.push(Line::styled(
|
||||
format!("error: {s}"),
|
||||
Style::default().fg(Color::Red),
|
||||
)),
|
||||
Item::Tool {
|
||||
name, args, result, ..
|
||||
} => {
|
||||
let (mark, color) = match result {
|
||||
None => ("○", Color::Yellow),
|
||||
Some((_, false)) => ("●", Color::Green),
|
||||
Some((_, true)) => ("●", Color::Red),
|
||||
};
|
||||
out.push(Line::from(vec![
|
||||
Span::styled(format!("{mark} "), Style::default().fg(color)),
|
||||
Span::styled(
|
||||
summary(name, args),
|
||||
Style::default().add_modifier(Modifier::BOLD),
|
||||
),
|
||||
]));
|
||||
if let Some((content, err)) = result {
|
||||
tool_body(name, content, *err, expanded, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Collapsed: diffs in full (edits are what you want to review), bash tail, others 1 line.
|
||||
fn tool_body(name: &str, content: &str, err: bool, expanded: bool, out: &mut Vec<Line<'static>>) {
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
let is_diff = name == "edit" && !err;
|
||||
let (show, skipped_front): (Vec<&str>, usize) = if expanded || is_diff {
|
||||
(lines.clone(), 0)
|
||||
} else if name == "bash" || err {
|
||||
let n = lines.len().saturating_sub(5);
|
||||
(lines[n..].to_vec(), n)
|
||||
} else {
|
||||
(lines.iter().take(1).copied().collect(), 0)
|
||||
};
|
||||
let hidden = lines.len() - show.len();
|
||||
if skipped_front > 0 {
|
||||
out.push(Line::styled(
|
||||
format!(" ⋮ {skipped_front} earlier lines (ctrl-o)"),
|
||||
dim(),
|
||||
));
|
||||
}
|
||||
for l in &show {
|
||||
let style = if is_diff {
|
||||
match l.as_bytes().first() {
|
||||
Some(b'+') if !l.starts_with("+++") => Style::default().fg(Color::Green),
|
||||
Some(b'-') if !l.starts_with("---") => Style::default().fg(Color::Red),
|
||||
Some(b'@') => Style::default().fg(Color::Cyan),
|
||||
_ => dim(),
|
||||
}
|
||||
} else if err {
|
||||
Style::default().fg(Color::Red)
|
||||
} else {
|
||||
dim()
|
||||
};
|
||||
out.push(Line::styled(format!(" {l}"), style));
|
||||
}
|
||||
if hidden > 0 && skipped_front == 0 {
|
||||
out.push(Line::styled(
|
||||
format!(" … {hidden} more lines (ctrl-o)"),
|
||||
dim(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal markdown: fenced code, headings, bullets, inline `code` and **bold**.
|
||||
fn markdown(s: &str, out: &mut Vec<Line<'static>>) {
|
||||
let mut code = false;
|
||||
for l in s.lines() {
|
||||
if l.trim_start().starts_with("```") {
|
||||
code = !code;
|
||||
out.push(Line::styled(l.to_string(), dim()));
|
||||
continue;
|
||||
}
|
||||
if code {
|
||||
out.push(Line::styled(
|
||||
l.to_string(),
|
||||
Style::default().fg(Color::Cyan),
|
||||
));
|
||||
} else if l.starts_with('#') {
|
||||
out.push(Line::styled(
|
||||
l.trim_start_matches('#').trim().to_string(),
|
||||
Style::default().add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
|
||||
));
|
||||
} else {
|
||||
out.push(inline(l));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn inline(l: &str) -> Line<'static> {
|
||||
let mut spans = vec![];
|
||||
let mut rest = l;
|
||||
while !rest.is_empty() {
|
||||
let next = [
|
||||
("`", Style::default().fg(Color::Yellow)),
|
||||
("**", Style::default().add_modifier(Modifier::BOLD)),
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|(d, st)| {
|
||||
let i = rest.find(d)?;
|
||||
let j = rest[i + d.len()..].find(d)?;
|
||||
Some((i, j, d, st))
|
||||
})
|
||||
.min_by_key(|x| x.0);
|
||||
match next {
|
||||
Some((i, j, d, st)) => {
|
||||
spans.push(Span::raw(rest[..i].to_string()));
|
||||
spans.push(Span::styled(
|
||||
rest[i + d.len()..i + d.len() + j].to_string(),
|
||||
st,
|
||||
));
|
||||
rest = &rest[i + d.len() * 2 + j..];
|
||||
}
|
||||
None => {
|
||||
spans.push(Span::raw(rest.to_string()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Line::from(spans)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn text(ls: &[Line]) -> Vec<String> {
|
||||
ls.iter()
|
||||
.map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_and_tools() {
|
||||
let mut t = Transcript::default();
|
||||
t.push(Item::User("hi".into()));
|
||||
for d in ["Hel", "lo"] {
|
||||
t.apply(&Event::Stream(StreamEvent::TextDelta { text: d.into() }));
|
||||
}
|
||||
t.apply(&Event::ToolCall {
|
||||
id: "1".into(),
|
||||
name: "edit".into(),
|
||||
args: json!({"path": "a.rs"}),
|
||||
});
|
||||
t.apply(&Event::ToolResult {
|
||||
id: "1".into(),
|
||||
name: "edit".into(),
|
||||
args: json!({}),
|
||||
content: "edited a.rs\n@@ -1 +1 @@\n-old\n+new".into(),
|
||||
is_error: false,
|
||||
});
|
||||
t.apply(&Event::Stream(StreamEvent::TextDelta {
|
||||
text: "After".into(),
|
||||
}));
|
||||
assert_eq!(t.items[1], Item::Assistant("Hello".into()));
|
||||
assert_eq!(t.items[3], Item::Assistant("After".into()));
|
||||
let ls = t.lines(false);
|
||||
let s = text(&ls);
|
||||
assert!(s.contains(&"● edit a.rs".to_string()));
|
||||
let minus = ls
|
||||
.iter()
|
||||
.find(|l| text(std::slice::from_ref(l))[0] == " -old")
|
||||
.unwrap();
|
||||
assert_eq!(minus.style.fg, Some(Color::Red));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapse_bash_tail() {
|
||||
let mut out = vec![];
|
||||
let body: String = (1..=20).map(|i| format!("l{i}\n")).collect();
|
||||
tool_body("bash", &body, false, false, &mut out);
|
||||
let s = text(&out);
|
||||
assert_eq!(s[0], " ⋮ 15 earlier lines (ctrl-o)");
|
||||
assert_eq!(s.last().unwrap(), " l20");
|
||||
out.clear();
|
||||
tool_body("bash", &body, false, true, &mut out);
|
||||
assert_eq!(out.len(), 20);
|
||||
out.clear();
|
||||
tool_body("read", &body, false, false, &mut out);
|
||||
assert_eq!(text(&out), [" l1", " … 19 more lines (ctrl-o)"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_md() {
|
||||
assert_eq!(text(&[inline("a `b` **c** d")]), ["a b c d"]);
|
||||
assert_eq!(inline("a `b` c").spans[1].style.fg, Some(Color::Yellow));
|
||||
assert_eq!(text(&[inline("x ` unclosed")]), ["x ` unclosed"]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user