TUI: permission prompt, /diff review, /stats dashboard, lens/context/MCP side panel
This commit is contained in:
1 parent
4a8e920ab8
commit
5fd7044a2f
15 files changed
+945
-2
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
Reference in new issue
Block a user