TUI: permission prompt, /diff review, /stats dashboard, lens/context/MCP side panel
ci / check (push) Canceled after 0s
ci / check (pull_request) Canceled after 0s

This commit is contained in:
hermes committed 2026-10-02 21:30:32 +00:00
1 parent 90c51de8a1
commit 1825b1833e
15 files changed
+945 -2

No files matched your search

Generated
+1
View File
@@ -1064,6 +1064,7 @@ dependencies = [
"ignore",
"ratatui",
"serde_json",
"similar",
"tempfile",
"tokio",
]
+5
View File
@@ -616,6 +616,11 @@ async fn main() -> Result<()> {
pricing,
specs,
open_sessions,
mcp: mcp
.servers
.iter()
.map(|(n, s)| (n.clone(), s.error.is_none()))
.collect(),
mouse: cfg.mouse.unwrap_or(true)
&& std::env::var_os("HX_MOUSE").is_none_or(|v| v != "0"),
commands: {
+10
View File
@@ -62,6 +62,16 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
b("sessions", "browse, resume, delete sessions", None),
b("lsp", "language server status", None),
b("usage", "subscription limits, resets, credits", None),
b(
"stats",
"token dashboard: cache hit, per-request usage",
None,
),
b(
"diff",
"diff of this session's edits; reject reverts a file",
None,
),
b("skills", "list skills and where they load from", None),
b(
"resume",
+18
View File
@@ -7,6 +7,7 @@ pub mod context;
pub mod ext;
pub mod hook;
mod mask;
pub mod permit;
pub mod session;
pub mod stats;
pub mod subagent;
@@ -54,6 +55,12 @@ pub struct State {
pub seen: Mutex<HashMap<PathBuf, Option<SystemTime>>>,
/// Set by interactive frontends; None = nobody to ask (print mode, mcp-serve).
pub ask: std::sync::OnceLock<Ask>,
/// Permission prompt for bash/write/edit; unset = everything runs.
pub permit: std::sync::OnceLock<permit::Permit>,
/// Rules the user allowed for good.
pub allow: Mutex<permit::Allow>,
/// Every write/edit this session, for `/review`.
pub edits: Mutex<Vec<permit::FileEdit>>,
/// Same for multiple-choice questions.
pub choose: std::sync::OnceLock<Choose>,
/// The owning agent's abort signal (set by `Agent::new`), so subagents stop with it.
@@ -81,6 +88,17 @@ impl State {
}
}
pub fn log_edit(&self, p: &std::path::Path, old: Option<String>, new: &str) {
self.edits
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(permit::FileEdit {
path: p.to_path_buf(),
old,
new: new.into(),
});
}
pub fn mark_seen(&self, p: &std::path::Path) {
let m = std::fs::metadata(p).and_then(|m| m.modified()).ok();
self.seen
+124
View File
@@ -0,0 +1,124 @@
//! Permission gate for mutating tools (bash, write, edit) and the edits log behind `/review`.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
/// Tools that need a yes before they run.
pub fn gated(tool: &str) -> bool {
matches!(tool, "bash" | "write" | "edit")
}
/// What the user is asked.
#[derive(Debug, Clone, PartialEq)]
pub struct Request {
pub tool: String,
/// One line: the command or the path.
pub detail: String,
/// What "allow always" stores and shows.
pub rule: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Decision {
Once,
Always,
Deny,
}
/// Asks the user; set by interactive frontends only (None = everything runs, as in print mode).
pub type Permit = std::sync::Arc<
dyn Fn(Request) -> std::pin::Pin<Box<dyn std::future::Future<Output = Decision> + Send>>
+ Send
+ Sync,
>;
/// `bash` rules cover a command's first word (`bash:cargo`); file tools are covered as a whole.
// ponytail: first-word granularity; add glob/argument patterns when people want `rm target/*` only.
pub fn request(tool: &str, args: &serde_json::Value) -> Request {
let s = |k: &str| args[k].as_str().unwrap_or_default().to_string();
if tool == "bash" {
let cmd = s("command");
let word = cmd.split_whitespace().next().unwrap_or_default();
Request {
tool: tool.into(),
detail: cmd.clone(),
rule: format!("bash:{word}"),
}
} else {
Request {
tool: tool.into(),
detail: s("path"),
rule: tool.into(),
}
}
}
/// Always-allowed rules, persisted in `<project>/.hx/allow.json`.
#[derive(Default)]
pub struct Allow {
rules: HashSet<String>,
file: Option<PathBuf>,
}
impl Allow {
pub fn load(cwd: &Path) -> Self {
let file = cwd.join(".hx/allow.json");
let rules = std::fs::read_to_string(&file)
.ok()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default();
Self {
rules,
file: Some(file),
}
}
pub fn has(&self, rule: &str) -> bool {
self.rules.contains(rule)
}
/// Remember a rule; the file is best effort (the rule holds for this session either way).
pub fn add(&mut self, rule: &str) {
self.rules.insert(rule.into());
if let Some(f) = &self.file {
let mut v: Vec<_> = self.rules.iter().collect();
v.sort();
if let Some(d) = f.parent() {
let _ = std::fs::create_dir_all(d);
}
let _ = std::fs::write(f, serde_json::to_string_pretty(&v).unwrap_or_default());
}
}
}
/// One file change by write/edit; `old` None = the file did not exist.
#[derive(Debug, Clone, PartialEq)]
pub struct FileEdit {
pub path: PathBuf,
pub old: Option<String>,
pub new: String,
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn rules_from_requests() {
let r = request("bash", &json!({"command": "cargo test -q"}));
assert_eq!(
(r.rule.as_str(), r.detail.as_str()),
("bash:cargo", "cargo test -q")
);
assert_eq!(request("edit", &json!({"path": "a.rs"})).rule, "edit");
assert!(gated("bash") && !gated("read"));
}
#[test]
fn allow_persists() {
let d = tempfile::tempdir().unwrap();
let mut a = Allow::load(d.path());
assert!(!a.has("bash:ls"));
a.add("bash:ls");
assert!(Allow::load(d.path()).has("bash:ls"));
}
}
+25
View File
@@ -42,6 +42,31 @@ pub fn sub_report(session_path: &std::path::Path) -> String {
)
}
/// Numbers behind the `/stats` dashboard.
#[derive(Debug, Default, PartialEq)]
pub struct Summary {
pub fresh: u64,
pub cache_read: u64,
pub cache_write: u64,
pub output: u64,
/// per request: (total input, output, cache hit %)
pub reqs: Vec<(u64, u64, u64)>,
}
pub fn summary(s: &Session) -> Summary {
let mut o = Summary::default();
for (_, u) in s.usages() {
o.fresh += u.input_tokens;
o.cache_read += u.cache_read_tokens;
o.cache_write += u.cache_write_tokens;
o.output += u.output_tokens;
let tot = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens;
o.reqs
.push((tot, u.output_tokens, 100 * u.cache_read_tokens / tot.max(1)));
}
o
}
pub fn report(s: &Session) -> String {
let msgs = s.messages();
let mut o = String::new();
+81
View File
@@ -105,6 +105,34 @@ impl Registry {
if let Err(e) = validate(&t.spec().input_schema, &args) {
return ToolResult::err(e);
}
if crate::permit::gated(name)
&& let Some(ask) = cx.state.permit.get()
{
let req = crate::permit::request(name, &args);
let known = cx
.state
.allow
.lock()
.unwrap_or_else(|e| e.into_inner())
.has(&req.rule);
if !known {
let rule = req.rule.clone();
match ask(req).await {
crate::permit::Decision::Once => {}
crate::permit::Decision::Always => cx
.state
.allow
.lock()
.unwrap_or_else(|e| e.into_inner())
.add(&rule),
crate::permit::Decision::Deny => {
return ToolResult::err(
"denied by the user; do not retry, ask what to do instead",
);
}
}
}
}
t.call(args, cx).await
}
@@ -149,6 +177,59 @@ mod tests {
}
}
#[tokio::test]
async fn gate_asks_remembers_and_denies() {
use crate::permit::{Decision, Permit};
struct Nop;
#[async_trait]
impl Tool for Nop {
fn spec(&self) -> ToolSpec {
ToolSpec {
name: "bash".into(),
description: String::new(),
input_schema: json!({"type":"object"}),
}
}
async fn call(&self, _: Value, _: &ToolCtx) -> ToolResult {
ToolResult::ok("ran")
}
}
let mut r = Registry::default();
r.add(Nop);
let c = cx();
// no frontend: runs
assert_eq!(
r.call("bash", json!({"command": "ls"}), &c).await.content,
"ran"
);
let asked = Arc::new(std::sync::Mutex::new(0));
let (n, next) = (
asked.clone(),
Arc::new(std::sync::Mutex::new(Decision::Always)),
);
let p: Permit = Arc::new(move |_| {
*n.lock().unwrap() += 1;
let d = *next.lock().unwrap();
*next.lock().unwrap() = Decision::Deny;
Box::pin(async move { d })
});
let _ = c.state.permit.set(p);
assert_eq!(
r.call("bash", json!({"command": "ls -l"}), &c)
.await
.content,
"ran"
);
// rule bash:ls remembered: no second prompt
assert_eq!(
r.call("bash", json!({"command": "ls"}), &c).await.content,
"ran"
);
assert_eq!(*asked.lock().unwrap(), 1);
let d = r.call("bash", json!({"command": "rm x"}), &c).await;
assert!(d.is_error && d.content.contains("denied"));
}
#[tokio::test]
async fn registry_validation_parallel() {
let mut r = Registry::default();
+3
View File
@@ -163,9 +163,11 @@ impl Tool for Write {
{
return ToolResult::err(format!("{}: {e}", d.display()));
}
let old = tokio::fs::read_to_string(&p).await.ok();
match tokio::fs::write(&p, c).await {
Ok(()) => {
cx.state.mark_seen(&p);
cx.state.log_edit(&p, old, c);
ToolResult::ok(format!(
"wrote {} ({} lines)",
p.display(),
@@ -245,6 +247,7 @@ impl Tool for Edit {
return ToolResult::err(format!("{}: {e}", p.display()));
}
cx.state.mark_seen(&p);
cx.state.log_edit(&p, Some(src.clone()), &out);
let diff = similar::TextDiff::from_lines(&src, &out)
.unified_diff()
.context_radius(2)
+1
View File
@@ -13,6 +13,7 @@ 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"
similar = "3.2.0"
tokio = { version = "1.53.1", features = ["rt", "macros", "sync", "time", "rt-multi-thread"] }
[lints]
+219
View File
@@ -3,10 +3,13 @@
pub mod agents;
pub mod choose;
pub mod editor;
pub mod permit_view;
pub mod picker;
pub mod popup;
pub mod review;
pub mod scroll;
pub mod sessions;
pub mod stats_view;
pub mod status;
pub mod theme;
pub mod transcript;
@@ -50,6 +53,8 @@ pub struct Setup {
pub open_sessions: bool,
/// Capture the mouse (wheel scrolling); terminal text selection then needs shift-drag.
pub mouse: bool,
/// MCP servers for the side panel: (name, connected).
pub mcp: Vec<(String, bool)>,
}
/// Screen regions of the last draw, for routing the mouse wheel.
@@ -85,6 +90,10 @@ pub type LspStatus = Box<
enum Ui {
Ev(Event),
Ask(String, tokio::sync::oneshot::Sender<bool>),
Permit(
hx_core::permit::Request,
tokio::sync::oneshot::Sender<hx_core::permit::Decision>,
),
Choose(
hx_core::Question,
tokio::sync::oneshot::Sender<Option<Vec<String>>>,
@@ -140,6 +149,17 @@ struct App {
/// condensed lens state for the footer, refreshed by a timer
lens: (String, bool),
/// open `ask_user` popup and where its answer goes
/// pending permission prompt for bash/write/edit
perm: Option<(
permit_view::Prompt,
tokio::sync::oneshot::Sender<hx_core::permit::Decision>,
)>,
review: Option<review::Review>,
stats: Option<(hx_core::stats::Summary, String)>,
/// lens/context/MCP side panel (ctrl-l), wide terminals only
side: bool,
lens_lines: Vec<String>,
mcp: Vec<(String, bool)>,
choose: Option<(
choose::Choose,
tokio::sync::oneshot::Sender<Option<Vec<String>>>,
@@ -214,6 +234,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
specs,
open_sessions,
mouse,
mcp,
} = setup;
let (tx, mut rx) = mpsc::unbounded_channel();
agent.bus.add(Forward(tx.clone()));
@@ -229,6 +250,14 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
Box::pin(async move { orx.await.unwrap_or(false) })
}));
}
{
let tx = tx.clone();
let _ = agent.cx.state.permit.set(std::sync::Arc::new(move |r| {
let (otx, orx) = tokio::sync::oneshot::channel();
let _ = tx.send(Ui::Permit(r, otx));
Box::pin(async move { orx.await.unwrap_or(hx_core::permit::Decision::Deny) })
}));
}
{
let tx = tx.clone();
let _ = agent.cx.state.choose.set(std::sync::Arc::new(move |q| {
@@ -275,6 +304,12 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
ask: None,
lens: (String::new(), false),
choose: None,
perm: None,
review: None,
stats: None,
side: true,
lens_lines: vec![],
mcp,
state: agent.cx.state.clone(),
sub_t: Default::default(),
agents: None,
@@ -321,6 +356,20 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
let Some(Ok(ev)) = k else { break };
dirty = true;
match ev {
TEvent::Key(k) if k.kind != KeyEventKind::Release && app.perm.is_some() => {
if let Some((p, _)) = &mut app.perm
&& let Some(d) = p.key(k)
&& let Some((p, reply)) = app.perm.take()
{
app.t.push(Item::Info(format!(
"{} {} {}",
permit_view::Prompt::label(d),
p.req.tool,
p.req.detail
)));
let _ = reply.send(d);
}
}
TEvent::Key(k) if k.kind != KeyEventKind::Release && app.choose.is_some() => {
if let Some((c, _)) = &mut app.choose
&& let choose::Act::Done(ans) = c.key(k)
@@ -357,6 +406,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
dirty = true;
match u {
Ui::Ask(q, reply) => app.ask = Some((q, reply)),
Ui::Permit(r, reply) => app.perm = Some((permit_view::Prompt::new(r), reply)),
Ui::Choose(q, reply) => app.choose = Some((choose::Choose::new(q), reply)),
Ui::Ev(e) => {
if let Event::SubUsage(u) = &e {
@@ -409,6 +459,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
let to = std::time::Duration::from_millis(200);
if let Ok(v) = tokio::time::timeout(to, lsp_status()).await {
let s = status::lens_summary(&v);
app.lens_lines = v;
dirty |= s != app.lens;
app.lens = s;
}
@@ -668,6 +719,32 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
if app.sessions.is_some() {
return sessions_key(app, k);
}
if app.stats.is_some() {
if matches!(k.code, KeyCode::Esc | KeyCode::Char('q')) {
app.stats = None;
}
return None;
}
if let Some(r) = &mut app.review {
match r.key(k) {
review::Act::Close => app.review = None,
review::Act::Reverted(p) => {
app.state
.edits
.lock()
.unwrap_or_else(|e| e.into_inner())
.retain(|e| e.path != p);
app.t.push(Item::Info(format!("reverted {}", p.display())));
}
review::Act::Error(e) => app.t.push(Item::Error(e)),
review::Act::None => {}
}
return None;
}
if ctrl && k.code == KeyCode::Char('l') {
app.side = !app.side;
return None;
}
if ctrl && k.code == KeyCode::Char('g') {
app.popup = None;
app.agents = match (app.agents.take(), app.state.subs.list().len()) {
@@ -850,6 +927,23 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
let h = format!("{}\n\nkeys: {KEYS} · ctrl-p picker", cmd::help(&app.specs));
show(app, "help", h);
}
"stats" => {
let sess = agent.lock().await;
let sum = hx_core::stats::summary(sess.session());
app.stats = Some((sum, app.title.clone().unwrap_or_default()));
}
"diff" => {
let edits = app
.state
.edits
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
match review::Review::new(&edits) {
Some(r) => app.review = Some(r),
None => app.t.push(Item::Info("no edits to review".into())),
}
}
"usage" => {
let r = status::report(&app.st, status::now_secs());
show(app, "usage", r);
@@ -1052,6 +1146,19 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
app.areas.panel = side;
m
}
None if app.wide && app.side => {
let [m, side] =
Layout::horizontal([Constraint::Min(60), Constraint::Length(34)]).areas(main);
let block = Block::new()
.borders(Borders::LEFT)
.border_style(th.dim())
.title(Span::styled(" lens · ctrl-l ", th.dim()));
let body = block.inner(side);
f.render_widget(block, side);
f.render_widget(Paragraph::new(side_lines(app)), body);
app.areas.panel = Rect::default();
m
}
_ => {
app.areas.panel = Rect::default();
main
@@ -1142,6 +1249,56 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
if let Some(s) = &mut app.sessions {
s.draw(f);
}
if let Some((s, t)) = &app.stats {
stats_view::draw(f, s, t);
}
if let Some(r) = &app.review {
r.draw(f);
}
if let Some((p, _)) = &app.perm {
p.draw(f, input.y);
}
}
/// Right-hand overview on wide terminals: lens state, context numbers, MCP servers.
fn side_lines(app: &App) -> Vec<Line<'static>> {
let th = theme::t();
let head = |t: &str| Line::styled(t.to_string(), th.accent());
let mut l = vec![head("LSP / LINT")];
if app.lens_lines.is_empty() {
l.push(Line::styled("(none started)", th.dim()));
}
l.extend(app.lens_lines.iter().map(|x| {
let bad = x.contains("dead") || x.contains("error") || x.contains("missing");
Line::styled(x.clone(), if bad { th.warn() } else { th.plain() })
}));
let u = &app.st.usage;
let tot = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens;
l.push(Line::default());
l.push(head("CONTEXT"));
l.push(Line::raw(format!(
"window {}k / {}k",
app.st.ctx_tokens / 1000,
app.st.ctx_max / 1000
)));
if let Some(p) = (100 * u.cache_read_tokens).checked_div(tot) {
l.push(Line::raw(format!("cache {p}%")));
}
l.push(Line::raw(format!("output {}k", u.output_tokens / 1000)));
if !app.mcp.is_empty() {
l.push(Line::default());
l.push(head("MCP"));
l.extend(app.mcp.iter().map(|(n, ok)| {
Line::from(vec![
Span::styled(
if *ok { "● " } else { "○ " },
if *ok { th.ok() } else { th.err() },
),
Span::raw(n.clone()),
])
}));
}
l
}
/// `/skills`: each skill with its file, then the searched dirs (so a missing skill is easy to debug).
@@ -1247,6 +1404,62 @@ mod tests {
assert!(rows[9].ends_with("Claude · m1"), "{all}");
}
fn screen(app: &mut App, w: u16, h: u16) -> String {
let mut term = ratatui::Terminal::new(TestBackend::new(w, h)).unwrap();
term.draw(|f| draw(f, app)).unwrap();
let b = term.backend().buffer().clone();
(0..h)
.map(|y| {
(0..w)
.map(|x| b[(x, y)].symbol().to_string())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn side_panel_only_on_wide_terminals() {
let mut app = test_app();
app.mcp = vec![("git".into(), true), ("db".into(), false)];
app.lens_lines = vec!["rust-analyzer @ /p: running".into()];
assert!(screen(&mut app, 160, 50).contains("MCP"));
assert!(!screen(&mut app, 80, 24).contains("MCP"));
app.side = false;
assert!(!screen(&mut app, 160, 50).contains("MCP"));
}
#[test]
fn overlays_render_at_both_sizes() {
let mut app = test_app();
app.review = review::Review::new(&[hx_core::permit::FileEdit {
path: "/x/a.rs".into(),
old: Some("a\n".into()),
new: "b\n".into(),
}]);
let (tx, _rx) = tokio::sync::oneshot::channel();
app.perm = Some((
permit_view::Prompt::new(hx_core::permit::Request {
tool: "bash".into(),
detail: "rm -rf target".into(),
rule: "bash:rm".into(),
}),
tx,
));
for (w, h) in [(80, 24), (160, 50)] {
let s = screen(&mut app, w, h);
assert!(
s.contains("permission") && s.contains("rm -rf target"),
"{s}"
);
assert!(s.contains("review · 1 files · +1 -1"), "{s}");
}
app.review = None;
app.perm = None;
app.stats = Some((hx_core::stats::Summary::default(), "s".into()));
assert!(screen(&mut app, 80, 24).contains("stats · s"));
}
#[tokio::test]
async fn ctrl_g_opens_agents_list_detail_and_back() {
use hx_core::tool::{Tool, ToolCtx};
@@ -1478,6 +1691,12 @@ mod tests {
ask: None,
lens: (String::new(), false),
choose: None,
perm: None,
review: None,
stats: None,
side: true,
lens_lines: vec![],
mcp: vec![],
state: Default::default(),
sub_t: Default::default(),
agents: None,
+121
View File
@@ -0,0 +1,121 @@
//! Permission popup for bash/write/edit.
use crate::theme;
use crossterm::event::{KeyCode, KeyEvent};
use hx_core::permit::{Decision, Request};
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Clear, Paragraph, Wrap};
pub struct Prompt {
pub req: Request,
sel: usize,
}
impl Prompt {
pub fn new(req: Request) -> Self {
Self { req, sel: 0 }
}
/// Some = decided.
pub fn key(&mut self, k: KeyEvent) -> Option<Decision> {
match k.code {
KeyCode::Char('y' | 'Y') => Some(Decision::Once),
KeyCode::Char('a' | 'A') => Some(Decision::Always),
KeyCode::Char('n' | 'N') | KeyCode::Esc => Some(Decision::Deny),
KeyCode::Up | KeyCode::Left => {
self.sel = (self.sel + 2) % 3;
None
}
KeyCode::Down | KeyCode::Right | KeyCode::Tab => {
self.sel = (self.sel + 1) % 3;
None
}
KeyCode::Enter => Some([Decision::Once, Decision::Always, Decision::Deny][self.sel]),
_ => None,
}
}
pub fn label(d: Decision) -> &'static str {
match d {
Decision::Once => "allowed",
Decision::Always => "allowed always",
Decision::Deny => "denied",
}
}
/// Centered in the first `bottom` rows.
pub fn draw(&self, f: &mut ratatui::Frame, bottom: u16) {
let th = theme::t();
let a = f.area();
let w = (a.width * 3 / 5).clamp(44, 100).min(a.width);
let opts = [
"[y] allow once".to_string(),
format!("[a] allow always: {}", self.req.rule),
"[n] deny".to_string(),
];
let mut lines = vec![
Line::styled("hx wants to run:", th.dim()),
Line::default(),
Line::from(vec![
Span::styled(format!("{} ", self.req.tool), th.accent()),
Span::raw(self.req.detail.clone()),
]),
Line::default(),
];
lines.extend(opts.iter().enumerate().map(|(i, o)| {
let (mark, st) = if i == self.sel {
("▶ ", th.sel())
} else {
(" ", th.plain())
};
Line::styled(format!("{mark}{o}"), st)
}));
let inner = w.saturating_sub(4).max(1);
let h = (Paragraph::new(lines.clone())
.wrap(Wrap { trim: false })
.line_count(inner) as u16
+ 2)
.min(bottom)
.max(3);
let r = Rect::new((a.width - w) / 2, (bottom - h) / 2, w, h);
f.render_widget(Clear, r);
f.render_widget(
Paragraph::new(lines).wrap(Wrap { trim: false }).block(
Block::bordered()
.border_style(th.warn())
.padding(ratatui::widgets::Padding::horizontal(1))
.title(Span::styled(" permission ", th.warn()))
.title_bottom(Span::styled(" ↑↓ select · ⏎ confirm ", th.dim())),
),
r,
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crossterm::event::KeyModifiers;
fn p() -> Prompt {
Prompt::new(Request {
tool: "bash".into(),
detail: "rm -rf x".into(),
rule: "bash:rm".into(),
})
}
fn k(c: KeyCode) -> KeyEvent {
KeyEvent::new(c, KeyModifiers::NONE)
}
#[test]
fn letters_and_selection() {
assert_eq!(p().key(k(KeyCode::Char('y'))), Some(Decision::Once));
assert_eq!(p().key(k(KeyCode::Char('a'))), Some(Decision::Always));
assert_eq!(p().key(k(KeyCode::Esc)), Some(Decision::Deny));
let mut q = p();
assert_eq!(q.key(k(KeyCode::Down)), None);
assert_eq!(q.key(k(KeyCode::Enter)), Some(Decision::Always));
}
}
+3 -1
View File
@@ -133,7 +133,9 @@ impl Picker {
let th = theme::t();
let a = f.area();
// scales with the terminal: 60% of the width, 50..=110 cols, never wider than the screen
let w = (a.width * 6 / 10).clamp(50, 110).min(a.width.saturating_sub(4));
let w = (a.width * 6 / 10)
.clamp(50, 110)
.min(a.width.saturating_sub(4));
let ms = self.matches();
// borders + query line + spacer
let h = (ms.len() as u16 + 4)
+229
View File
@@ -0,0 +1,229 @@
//! `/diff`: file list + diff of this session's write/edit calls; reject reverts the file on disk.
use crate::theme;
use crossterm::event::{KeyCode, KeyEvent};
use hx_core::permit::FileEdit;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Clear, Paragraph};
use std::path::PathBuf;
#[derive(Debug, Clone, PartialEq)]
pub enum State {
Pending,
Accepted,
Reverted,
}
pub struct File {
pub path: PathBuf,
old: Option<String>,
new: String,
pub state: State,
diff: Vec<String>,
pub add: usize,
pub del: usize,
}
pub enum Act {
None,
Close,
/// A file was put back; the app drops it from the edits log.
Reverted(PathBuf),
Error(String),
}
pub struct Review {
pub files: Vec<File>,
pub sel: usize,
scroll: u16,
}
impl Review {
/// One entry per path: first `old` to last `new`; no-op edits drop out. None = nothing to review.
pub fn new(edits: &[FileEdit]) -> Option<Self> {
let mut files: Vec<File> = vec![];
for e in edits {
match files.iter_mut().find(|f| f.path == e.path) {
Some(f) => f.new = e.new.clone(),
None => files.push(File {
path: e.path.clone(),
old: e.old.clone(),
new: e.new.clone(),
state: State::Pending,
diff: vec![],
add: 0,
del: 0,
}),
}
}
files.retain(|f| f.old.as_deref() != Some(f.new.as_str()));
for f in &mut files {
let d = similar::TextDiff::from_lines(f.old.as_deref().unwrap_or(""), &f.new)
.unified_diff()
.context_radius(3)
.to_string();
f.diff = d.lines().map(String::from).collect();
f.add = f.diff.iter().filter(|l| l.starts_with('+')).count();
f.del = f.diff.iter().filter(|l| l.starts_with('-')).count();
}
(!files.is_empty()).then_some(Self {
files,
sel: 0,
scroll: 0,
})
}
pub fn key(&mut self, k: KeyEvent) -> Act {
let n = self.files.len();
match k.code {
KeyCode::Esc | KeyCode::Char('q') => return Act::Close,
KeyCode::Char('n') | KeyCode::Tab => {
self.sel = (self.sel + 1) % n;
self.scroll = 0;
}
KeyCode::Char('p') | KeyCode::BackTab => {
self.sel = (self.sel + n - 1) % n;
self.scroll = 0;
}
KeyCode::Char('j') | KeyCode::Down => self.scroll = self.scroll.saturating_add(1),
KeyCode::Char('k') | KeyCode::Up => self.scroll = self.scroll.saturating_sub(1),
KeyCode::PageDown => self.scroll = self.scroll.saturating_add(10),
KeyCode::PageUp => self.scroll = self.scroll.saturating_sub(10),
KeyCode::Char('a') => self.files[self.sel].state = State::Accepted,
KeyCode::Char('r') => {
let f = &mut self.files[self.sel];
match revert(f) {
Ok(()) => {
f.state = State::Reverted;
return Act::Reverted(f.path.clone());
}
Err(e) => return Act::Error(e),
}
}
_ => {}
}
Act::None
}
pub fn draw(&self, f: &mut ratatui::Frame) {
let th = theme::t();
let a = f.area();
let (w, h) = (a.width * 9 / 10, a.height * 9 / 10);
let r = Rect::new(a.x + (a.width - w) / 2, a.y + (a.height - h) / 2, w, h);
let (add, del) = self
.files
.iter()
.fold((0, 0), |(a, d), f| (a + f.add, d + f.del));
let block = Block::bordered()
.border_style(th.dim())
.title(Line::from(vec![
Span::styled(format!(" review · {} files · ", self.files.len()), th.dim()),
Span::styled(format!("+{add} "), th.add()),
Span::styled(format!("-{del} "), th.del()),
]))
.title_bottom(Span::styled(
" a accept · r reject (revert) · n/p file · j/k scroll · esc close ",
th.dim(),
));
let inner = block.inner(r);
f.render_widget(Clear, r);
f.render_widget(block, r);
let lw = (inner.width / 3).clamp(16, 36);
let [left, right] =
Layout::horizontal([Constraint::Length(lw), Constraint::Min(10)]).areas(inner);
let list: Vec<Line> = self
.files
.iter()
.enumerate()
.map(|(i, x)| {
let tag = match x.state {
State::Pending => " ",
State::Accepted => "✓",
State::Reverted => "↩",
};
let name = x
.path
.file_name()
.map_or_else(String::new, |n| n.to_string_lossy().into());
let st = if i == self.sel { th.sel() } else { th.plain() };
Line::styled(format!("{tag} {name} +{} -{}", x.add, x.del), st)
})
.collect();
f.render_widget(Paragraph::new(list), left);
let cur = &self.files[self.sel];
let mut lines = vec![Line::styled(cur.path.display().to_string(), th.accent())];
lines.extend(cur.diff.iter().map(|l| {
let st = match l.chars().next() {
Some('+') => th.add(),
Some('-') => th.del(),
Some('@') => th.hunk(),
_ => th.plain(),
};
Line::styled(l.clone(), st)
}));
let max = lines.len().saturating_sub(right.height as usize) as u16;
f.render_widget(
Paragraph::new(lines).scroll((self.scroll.min(max), 0)),
right,
);
}
}
/// Put the file back to `old` (delete it when the agent created it). Refuses when the file is not
/// what the agent left, so manual edits are never overwritten.
fn revert(f: &File) -> Result<(), String> {
if f.state == State::Reverted {
return Err("already reverted".into());
}
let now = std::fs::read_to_string(&f.path).map_err(|e| format!("{}: {e}", f.path.display()))?;
if now != f.new {
return Err(format!(
"{} changed on disk since; not reverting",
f.path.display()
));
}
match &f.old {
Some(o) => std::fs::write(&f.path, o),
None => std::fs::remove_file(&f.path),
}
.map_err(|e| format!("{}: {e}", f.path.display()))
}
#[cfg(test)]
mod tests {
use super::*;
use crossterm::event::KeyModifiers;
fn key(c: char) -> KeyEvent {
KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)
}
#[test]
fn collapses_counts_and_reverts() {
let d = tempfile::tempdir().unwrap();
let (p, q) = (d.path().join("a.txt"), d.path().join("b.txt"));
std::fs::write(&p, "one\nTWO\nthree\n").unwrap();
std::fs::write(&q, "new\n").unwrap();
let e = |path: &PathBuf, old: Option<&str>, new: &str| FileEdit {
path: path.clone(),
old: old.map(Into::into),
new: new.into(),
};
let mut r = Review::new(&[
e(&p, Some("one\ntwo\nthree\n"), "one\n2\nthree\n"),
e(&p, Some("one\n2\nthree\n"), "one\nTWO\nthree\n"),
e(&q, None, "new\n"),
e(&q, Some("same\n"), "same\n"),
])
.unwrap();
assert_eq!((r.files.len(), r.files[0].add, r.files[0].del), (2, 1, 1));
assert!(matches!(r.key(key('r')), Act::Reverted(_)));
assert_eq!(std::fs::read_to_string(&p).unwrap(), "one\ntwo\nthree\n");
r.key(key('n'));
std::fs::write(&q, "edited by hand").unwrap();
assert!(matches!(r.key(key('r')), Act::Error(_)));
assert!(q.exists());
assert!(Review::new(&[]).is_none());
}
}
+99
View File
@@ -0,0 +1,99 @@
//! `/stats` dashboard: token totals, cache hit, per-request table.
use crate::theme;
use hx_core::stats::Summary;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Clear, Paragraph};
fn bar(v: u64, max: u64, w: usize) -> String {
let th = theme::t();
let n = (v * w as u64 / max.max(1)) as usize;
format!(
"{}{}",
th.sym.bar_full.repeat(n),
th.sym.bar_empty.repeat(w - n)
)
}
fn k(n: u64) -> String {
format!("{:.1}k", n as f64 / 1000.0)
}
pub fn lines(s: &Summary, rows: usize) -> Vec<Line<'static>> {
let th = theme::t();
let total = s.fresh + s.cache_read + s.cache_write;
let hit = 100 * s.cache_read / total.max(1);
let row = |name: &str, v: u64, extra: String| {
Line::from(vec![
Span::raw(format!("{name:<8}{:>7} ", k(v))),
Span::styled(bar(v, total.max(s.output), 20), th.accent()),
Span::styled(extra, th.ok()),
])
};
let mut l = vec![
row("input", total, String::new()),
row("output", s.output, String::new()),
row("cache r", s.cache_read, format!(" {hit}% hit")),
Line::default(),
Line::styled(
format!("{:<5}{:>9}{:>9}{:>8}", "req", "in", "out", "cache"),
th.dim(),
),
];
let skip = s.reqs.len().saturating_sub(rows);
for (i, (inp, out, h)) in s.reqs.iter().enumerate().skip(skip) {
l.push(Line::from(vec![
Span::raw(format!("#{:<4}{:>9}{:>9}", i + 1, k(*inp), k(*out))),
Span::styled(
format!("{:>7}%", h),
if *h >= 80 { th.ok() } else { th.warn() },
),
]));
}
l
}
pub fn draw(f: &mut ratatui::Frame, s: &Summary, title: &str) {
let th = theme::t();
let a = f.area();
let w = (a.width * 6 / 10).clamp(50, 90).min(a.width);
let h = (a.height * 7 / 10).clamp(12, 30).min(a.height);
let r = Rect::new(a.x + (a.width - w) / 2, a.y + (a.height - h) / 2, w, h);
let body = if s.reqs.is_empty() {
vec![Line::styled("no usage recorded yet", th.dim())]
} else {
lines(s, (h as usize).saturating_sub(9))
};
f.render_widget(Clear, r);
f.render_widget(
Paragraph::new(body).block(
Block::bordered()
.border_style(th.dim())
.padding(ratatui::widgets::Padding::horizontal(1))
.title(Span::styled(format!(" stats · {title} "), th.dim()))
.title_bottom(Span::styled(" esc close ", th.dim())),
),
r,
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn table_keeps_latest_rows() {
let s = Summary {
fresh: 10,
cache_read: 90,
cache_write: 0,
output: 5,
reqs: (1..=10).map(|i| (100, 5, i)).collect(),
};
let l = lines(&s, 3);
assert_eq!(l.len(), 5 + 3);
assert!(l[2].to_string().contains("90% hit"));
assert!(l.last().unwrap().to_string().starts_with("#10"));
}
}
+6 -1
View File
@@ -61,7 +61,12 @@ check("project .agents skills", "/lint — project lint")
send(b"@not"); send(b"\t")
check("tab completion", "es.md")
send(b"\x15") # ctrl-u
send(b"make hello.txt"); send(b"\r", 3)
send(b"make hello.txt"); send(b"\r", 2)
check("permission prompt", "permission")
check("allow always rule", "allow always: write")
send(b"y", 2)
check("second prompt for bash", "allow always: bash:cat")
send(b"y", 3)
check("tool call shown", "hello.txt")
check("tool outcome", "1 lines")
check("final answer", "Done: file says hi from hx.")