Compare commits
5
Commits
v0.2.0
...
b06ae09a98
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b06ae09a98 | ||
|
|
a5c7b580ea | ||
|
|
531919a23c | ||
|
|
18eb31ec8b | ||
|
|
1c3b861fde |
No files matched your search
@@ -25,6 +25,14 @@ pub type Spawner = Arc<
|
|||||||
+ Sync,
|
+ Sync,
|
||||||
>;
|
>;
|
||||||
|
|
||||||
|
/// hx plan mode is on: claude runs with `--permission-mode plan`, else its `ExitPlanMode` is rejected.
|
||||||
|
// ponytail: process-wide flag; make it per-provider if two claude providers ever run at once.
|
||||||
|
static PLAN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||||
|
|
||||||
|
pub fn set_plan(on: bool) {
|
||||||
|
PLAN.store(on, std::sync::atomic::Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
pub struct ClaudeCli {
|
pub struct ClaudeCli {
|
||||||
spawner: Option<Spawner>,
|
spawner: Option<Spawner>,
|
||||||
bin: String,
|
bin: String,
|
||||||
@@ -187,6 +195,9 @@ impl Provider for ClaudeCli {
|
|||||||
cmd.args(["--permission-prompt-tool", "mcp__hx__approve"]);
|
cmd.args(["--permission-prompt-tool", "mcp__hx__approve"]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if PLAN.load(std::sync::atomic::Ordering::Relaxed) {
|
||||||
|
cmd.args(["--permission-mode", "plan"]);
|
||||||
|
}
|
||||||
cmd.args(&self.args)
|
cmd.args(&self.args)
|
||||||
.arg("--")
|
.arg("--")
|
||||||
.arg(prompt(&req.messages, sid.is_some()))
|
.arg(prompt(&req.messages, sid.is_some()))
|
||||||
|
|||||||
@@ -1015,7 +1015,7 @@ async fn main() -> Result<()> {
|
|||||||
{
|
{
|
||||||
// children get the parent's tools as of now (no `task`, so no recursion)
|
// children get the parent's tools as of now (no `task`, so no recursion)
|
||||||
let mut general = agent.tools.clone();
|
let mut general = agent.tools.clone();
|
||||||
general.retain(|n| n != "ask_user");
|
general.retain(|n| n != "ask_user" && n != "exit_plan");
|
||||||
let mut explore = agent.tools.clone();
|
let mut explore = agent.tools.clone();
|
||||||
explore.retain(|n| hx_core::subagent::EXPLORE_TOOLS.contains(&n));
|
explore.retain(|n| hx_core::subagent::EXPLORE_TOOLS.contains(&n));
|
||||||
let role = |model: String, tools, base: &str| hx_core::subagent::Role {
|
let role = |model: String, tools, base: &str| hx_core::subagent::Role {
|
||||||
|
|||||||
@@ -79,7 +79,9 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
|||||||
let v: Value = serde_json::from_str(&line).unwrap_or_default();
|
let v: Value = serde_json::from_str(&line).unwrap_or_default();
|
||||||
// hx tools run by `codemode` inside mcp-serve ask for their own permission
|
// hx tools run by `codemode` inside mcp-serve ask for their own permission
|
||||||
let mut input = None;
|
let mut input = None;
|
||||||
let ok = if v["tool_name"] == "AskUserQuestion" {
|
let ok = if v["tool_name"] == "ExitPlanMode" {
|
||||||
|
exit_plan(&cx, v["input"]["plan"].as_str().unwrap_or_default()).await
|
||||||
|
} else if v["tool_name"] == "AskUserQuestion" {
|
||||||
// claude's own question tool: show hx's popup, hand the answers back as input
|
// claude's own question tool: show hx's popup, hand the answers back as input
|
||||||
input = ask(&cx, &v["input"]).await;
|
input = ask(&cx, &v["input"]).await;
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -121,6 +123,38 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// claude's `ExitPlanMode`: the TUI shows the whole plan, then asks. Implement ends hx plan mode too.
|
||||||
|
async fn exit_plan(cx: &ToolCtx, plan: &str) -> Result<(), String> {
|
||||||
|
let q = crate::Question {
|
||||||
|
text: "Implement this plan?".into(),
|
||||||
|
options: vec![
|
||||||
|
("Implement".into(), "leave plan mode and start".into()),
|
||||||
|
(
|
||||||
|
"Keep planning".into(),
|
||||||
|
"stay read-only; type feedback below".into(),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
multi: false,
|
||||||
|
other: true,
|
||||||
|
plan: Some(plan.into()),
|
||||||
|
};
|
||||||
|
match cx.state.choose(q).await {
|
||||||
|
Ok(Some(v)) if v.first().is_some_and(|s| s == "Implement") => {
|
||||||
|
cx.state
|
||||||
|
.allow
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.set_plan(false);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Ok(Some(v)) if v.first().is_some_and(|s| s != "Keep planning") => Err(format!(
|
||||||
|
"plan not approved, user feedback: {}. Revise and present the plan again.",
|
||||||
|
v.join(", ")
|
||||||
|
)),
|
||||||
|
_ => Err("plan not approved; keep planning and ask what to change".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Run each `AskUserQuestion` question through the popup; `input` plus `answers` (question -> label(s)).
|
/// Run each `AskUserQuestion` question through the popup; `input` plus `answers` (question -> label(s)).
|
||||||
/// None = no frontend or dismissed.
|
/// None = no frontend or dismissed.
|
||||||
async fn ask(cx: &ToolCtx, input: &Value) -> Option<Value> {
|
async fn ask(cx: &ToolCtx, input: &Value) -> Option<Value> {
|
||||||
@@ -138,6 +172,7 @@ async fn ask(cx: &ToolCtx, input: &Value) -> Option<Value> {
|
|||||||
options: options.collect(),
|
options: options.collect(),
|
||||||
multi: q["multiSelect"].as_bool().unwrap_or(false),
|
multi: q["multiSelect"].as_bool().unwrap_or(false),
|
||||||
other: true,
|
other: true,
|
||||||
|
plan: None,
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.ok()??;
|
.ok()??;
|
||||||
@@ -249,6 +284,24 @@ mod tests {
|
|||||||
assert_eq!(ask(&cx, &inp).await.unwrap()["answers"]["Which?"], "B");
|
assert_eq!(ask(&cx, &inp).await.unwrap()["answers"]["Which?"], "B");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn exit_plan_shows_plan_and_implement_ends_plan_mode() {
|
||||||
|
let cx = ToolCtx {
|
||||||
|
cwd: ".".into(),
|
||||||
|
state: Default::default(),
|
||||||
|
};
|
||||||
|
cx.state.allow.lock().unwrap().set_plan(true);
|
||||||
|
let seen = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||||
|
let s = seen.clone();
|
||||||
|
let _ = cx.state.choose.set(std::sync::Arc::new(move |q| {
|
||||||
|
*s.lock().unwrap() = q.plan.clone();
|
||||||
|
Box::pin(async { Some(vec!["Keep planning".to_string()]) })
|
||||||
|
}));
|
||||||
|
assert!(exit_plan(&cx, "# P\nstep 1").await.is_err());
|
||||||
|
assert_eq!(seen.lock().unwrap().as_deref(), Some("# P\nstep 1"));
|
||||||
|
assert!(cx.state.allow.lock().unwrap().plan_on());
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn socket_round_trip_allows_and_denies() {
|
async fn socket_round_trip_allows_and_denies() {
|
||||||
use crate::permit::Decision;
|
use crate::permit::Decision;
|
||||||
|
|||||||
@@ -82,6 +82,11 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
|
|||||||
"auto permissions: refuse dangerous calls, run safe ones",
|
"auto permissions: refuse dangerous calls, run safe ones",
|
||||||
Enum(vec!["on".into(), "off".into(), "log".into()]),
|
Enum(vec!["on".into(), "off".into(), "log".into()]),
|
||||||
),
|
),
|
||||||
|
b(
|
||||||
|
"plan",
|
||||||
|
"plan mode: read-only research, then the full plan for approval",
|
||||||
|
Enum(vec!["on".into(), "off".into()]),
|
||||||
|
),
|
||||||
b("yolo", "toggle: run every tool without asking", None),
|
b("yolo", "toggle: run every tool without asking", None),
|
||||||
b(
|
b(
|
||||||
"sandbox",
|
"sandbox",
|
||||||
|
|||||||
@@ -43,6 +43,8 @@ pub struct Question {
|
|||||||
pub multi: bool,
|
pub multi: bool,
|
||||||
/// offer a free-text "Other" row
|
/// offer a free-text "Other" row
|
||||||
pub other: bool,
|
pub other: bool,
|
||||||
|
/// Long markdown (a plan) the frontend shows in full in the transcript before asking.
|
||||||
|
pub plan: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Shows a [`Question`]; resolves to the chosen labels / typed text, None when dismissed.
|
/// Shows a [`Question`]; resolves to the chosen labels / typed text, None when dismissed.
|
||||||
|
|||||||
@@ -328,6 +328,8 @@ pub struct Allow {
|
|||||||
all_edits: bool,
|
all_edits: bool,
|
||||||
yolo: bool,
|
yolo: bool,
|
||||||
auto: bool,
|
auto: bool,
|
||||||
|
/// Plan mode: read-only until the user approves a plan.
|
||||||
|
plan: bool,
|
||||||
/// Last calls auto mode refused (newest last), for `/auto`.
|
/// Last calls auto mode refused (newest last), for `/auto`.
|
||||||
blocks: Vec<String>,
|
blocks: Vec<String>,
|
||||||
file: Option<PathBuf>,
|
file: Option<PathBuf>,
|
||||||
@@ -345,6 +347,7 @@ impl Allow {
|
|||||||
all_edits: false,
|
all_edits: false,
|
||||||
yolo: false,
|
yolo: false,
|
||||||
auto: false,
|
auto: false,
|
||||||
|
plan: false,
|
||||||
blocks: Vec::new(),
|
blocks: Vec::new(),
|
||||||
file: Some(file),
|
file: Some(file),
|
||||||
}
|
}
|
||||||
@@ -381,6 +384,15 @@ impl Allow {
|
|||||||
self.yolo
|
self.yolo
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn plan_on(&self) -> bool {
|
||||||
|
self.plan
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_plan(&mut self, on: bool) {
|
||||||
|
self.plan = on;
|
||||||
|
hx_ai::claude_cli::set_plan(on);
|
||||||
|
}
|
||||||
|
|
||||||
pub fn auto_on(&self) -> bool {
|
pub fn auto_on(&self) -> bool {
|
||||||
self.auto
|
self.auto
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -93,6 +93,16 @@ pub async fn gate_why(cx: &ToolCtx, req: crate::permit::Request) -> Result<(), S
|
|||||||
use crate::danger::{Verdict, classify};
|
use crate::danger::{Verdict, classify};
|
||||||
use crate::permit::Decision;
|
use crate::permit::Decision;
|
||||||
const DENIED: &str = "denied by the user; do not retry, ask what to do instead";
|
const DENIED: &str = "denied by the user; do not retry, ask what to do instead";
|
||||||
|
if matches!(req.tool.as_str(), "bash" | "write" | "edit")
|
||||||
|
&& cx
|
||||||
|
.state
|
||||||
|
.allow
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.plan_on()
|
||||||
|
{
|
||||||
|
return Err("blocked by plan mode: read-only until the plan is approved. Explore with read/grep/ls, then call exit_plan with the full plan.".into());
|
||||||
|
}
|
||||||
let Some(ask) = cx.state.permit.get() else {
|
let Some(ask) = cx.state.permit.get() else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
@@ -263,6 +273,27 @@ mod tests {
|
|||||||
assert!(d.is_error && d.content.contains("denied"));
|
assert!(d.is_error && d.content.contains("denied"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn plan_mode_blocks_writes_even_without_prompt() {
|
||||||
|
let c = cx();
|
||||||
|
c.state.allow.lock().unwrap().set_plan(true);
|
||||||
|
let e = gate_why(
|
||||||
|
&c,
|
||||||
|
crate::permit::request("bash", &json!({"command":"touch x"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert!(e.unwrap_err().contains("plan mode"));
|
||||||
|
c.state.allow.lock().unwrap().set_plan(false);
|
||||||
|
assert!(
|
||||||
|
gate_why(
|
||||||
|
&c,
|
||||||
|
crate::permit::request("bash", &json!({"command":"touch x"}))
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.is_ok()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn auto_mode_blocks_allows_judges_without_prompting() {
|
async fn auto_mode_blocks_allows_judges_without_prompting() {
|
||||||
use crate::danger::Judge;
|
use crate::danger::Judge;
|
||||||
|
|||||||
@@ -66,6 +66,7 @@ pub fn registry() -> Registry {
|
|||||||
.add(Edit)
|
.add(Edit)
|
||||||
.add(Bash)
|
.add(Bash)
|
||||||
.add(AskUser)
|
.add(AskUser)
|
||||||
|
.add(ExitPlan)
|
||||||
.add(MemoryWrite)
|
.add(MemoryWrite)
|
||||||
.add(MemoryForget)
|
.add(MemoryForget)
|
||||||
.add(skill::Skill);
|
.add(skill::Skill);
|
||||||
@@ -313,6 +314,7 @@ impl Tool for AskUser {
|
|||||||
options,
|
options,
|
||||||
multi: a["multi"].as_bool().unwrap_or(false),
|
multi: a["multi"].as_bool().unwrap_or(false),
|
||||||
other: true,
|
other: true,
|
||||||
|
plan: None,
|
||||||
};
|
};
|
||||||
match cx.state.choose(q).await {
|
match cx.state.choose(q).await {
|
||||||
Err(e) => ToolResult::err(e),
|
Err(e) => ToolResult::err(e),
|
||||||
@@ -324,6 +326,52 @@ impl Tool for AskUser {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Plan mode's end: the TUI shows the plan in full, the user approves or sends feedback.
|
||||||
|
pub struct ExitPlan;
|
||||||
|
#[async_trait]
|
||||||
|
impl Tool for ExitPlan {
|
||||||
|
fn spec(&self) -> ToolSpec {
|
||||||
|
spec(
|
||||||
|
"exit_plan",
|
||||||
|
"Only in plan mode: present your finished plan (markdown, complete) for approval. Plan mode ends once the user approves.",
|
||||||
|
json!({"type":"object","properties":{"plan":{"type":"string"}},"required":["plan"]}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
||||||
|
let on = || cx.state.allow.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
if !on().plan_on() {
|
||||||
|
return ToolResult::ok("not in plan mode; just do the work");
|
||||||
|
}
|
||||||
|
let q = hx_core::Question {
|
||||||
|
text: "Implement this plan?".into(),
|
||||||
|
options: vec![
|
||||||
|
("Implement".into(), "leave plan mode and start".into()),
|
||||||
|
(
|
||||||
|
"Keep planning".into(),
|
||||||
|
"stay read-only; type feedback below".into(),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
multi: false,
|
||||||
|
other: true,
|
||||||
|
plan: a["plan"].as_str().map(Into::into),
|
||||||
|
};
|
||||||
|
match cx.state.choose(q).await {
|
||||||
|
Ok(Some(v)) if v.first().is_some_and(|s| s == "Implement") => {
|
||||||
|
on().set_plan(false);
|
||||||
|
ToolResult::ok("plan approved; plan mode is off, implement it now")
|
||||||
|
}
|
||||||
|
Ok(Some(v)) if v.first().is_some_and(|s| s != "Keep planning") => {
|
||||||
|
ToolResult::ok(format!(
|
||||||
|
"plan not approved, user feedback: {}. Revise and call exit_plan again.",
|
||||||
|
v.join(", ")
|
||||||
|
))
|
||||||
|
}
|
||||||
|
// no frontend (print mode) or dismissed: stay in plan mode
|
||||||
|
_ => ToolResult::ok("plan not approved; keep planning and ask what to change"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Bytes of running bash output kept for the live view.
|
/// Bytes of running bash output kept for the live view.
|
||||||
const LIVE_TAIL: usize = 2048;
|
const LIVE_TAIL: usize = 2048;
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ pub struct Choose {
|
|||||||
picked: Vec<bool>,
|
picked: Vec<bool>,
|
||||||
/// Some while typing an own answer
|
/// Some while typing an own answer
|
||||||
typing: Option<String>,
|
typing: Option<String>,
|
||||||
|
/// opened straight into the text input: esc dismisses instead of showing the list
|
||||||
|
direct: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Choose {
|
impl Choose {
|
||||||
@@ -28,9 +30,18 @@ impl Choose {
|
|||||||
q,
|
q,
|
||||||
sel: 0,
|
sel: 0,
|
||||||
typing: None,
|
typing: None,
|
||||||
|
direct: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Free-text question: starts in the input, no option list.
|
||||||
|
pub fn input(q: Question) -> Self {
|
||||||
|
let mut c = Self::new(q);
|
||||||
|
c.typing = Some(String::new());
|
||||||
|
c.direct = true;
|
||||||
|
c
|
||||||
|
}
|
||||||
|
|
||||||
fn rows(&self) -> usize {
|
fn rows(&self) -> usize {
|
||||||
self.q.options.len() + usize::from(self.q.other)
|
self.q.options.len() + usize::from(self.q.other)
|
||||||
}
|
}
|
||||||
@@ -57,6 +68,7 @@ impl Choose {
|
|||||||
let picked = if self.q.multi { self.labels() } else { vec![] };
|
let picked = if self.q.multi { self.labels() } else { vec![] };
|
||||||
if let Some(t) = &mut self.typing {
|
if let Some(t) = &mut self.typing {
|
||||||
match k.code {
|
match k.code {
|
||||||
|
KeyCode::Esc if self.direct => return Act::Done(None),
|
||||||
KeyCode::Esc => self.typing = None,
|
KeyCode::Esc => self.typing = None,
|
||||||
KeyCode::Backspace => {
|
KeyCode::Backspace => {
|
||||||
t.pop();
|
t.pop();
|
||||||
@@ -286,6 +298,7 @@ mod tests {
|
|||||||
],
|
],
|
||||||
multi,
|
multi,
|
||||||
other: true,
|
other: true,
|
||||||
|
plan: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
fn k(c: KeyCode) -> KeyEvent {
|
fn k(c: KeyCode) -> KeyEvent {
|
||||||
@@ -314,6 +327,23 @@ mod tests {
|
|||||||
assert!(c.is_other());
|
assert!(c.is_other());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn input_starts_typing_and_esc_dismisses() {
|
||||||
|
let q = || Question {
|
||||||
|
text: "why?".into(),
|
||||||
|
options: vec![],
|
||||||
|
multi: false,
|
||||||
|
other: true,
|
||||||
|
plan: None,
|
||||||
|
};
|
||||||
|
let mut c = Choose::input(q());
|
||||||
|
c.key(k(KeyCode::Char('h')));
|
||||||
|
c.key(k(KeyCode::Char('i')));
|
||||||
|
assert!(matches!(c.key(k(KeyCode::Enter)), Act::Done(Some(v)) if v == ["hi"]));
|
||||||
|
let mut c = Choose::input(q());
|
||||||
|
assert!(matches!(c.key(k(KeyCode::Esc)), Act::Done(None)));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn multi_toggle_and_other_text() {
|
fn multi_toggle_and_other_text() {
|
||||||
let mut c = q(true);
|
let mut c = q(true);
|
||||||
@@ -405,6 +435,7 @@ mod tests {
|
|||||||
],
|
],
|
||||||
multi: false,
|
multi: false,
|
||||||
other: true,
|
other: true,
|
||||||
|
plan: None,
|
||||||
});
|
});
|
||||||
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(200, 50)).unwrap();
|
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(200, 50)).unwrap();
|
||||||
term.draw(|f| c.draw(f, 45)).unwrap();
|
term.draw(|f| c.draw(f, 45)).unwrap();
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
//! Full-screen read-only text view with scrolling and a row of action keys. Used for plan approval;
|
||||||
|
//! meant to be reused for diffs (`lines` are plain styled lines).
|
||||||
|
|
||||||
|
use crate::{scroll::Scroll, theme};
|
||||||
|
use crossterm::event::{KeyCode, KeyEvent};
|
||||||
|
use ratatui::layout::Rect;
|
||||||
|
use ratatui::text::{Line, Span};
|
||||||
|
use ratatui::widgets::{Block, Clear, Paragraph, Wrap};
|
||||||
|
|
||||||
|
pub enum Act {
|
||||||
|
None,
|
||||||
|
/// An action key was pressed: its label.
|
||||||
|
Pick(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct DocView {
|
||||||
|
title: String,
|
||||||
|
lines: Vec<Line<'static>>,
|
||||||
|
scroll: Scroll,
|
||||||
|
/// (key, label); esc picks the one with key `\x1b`
|
||||||
|
actions: Vec<(KeyCode, &'static str, &'static str)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DocView {
|
||||||
|
/// `actions`: (key, key name shown, label returned/shown).
|
||||||
|
pub fn new(
|
||||||
|
title: impl Into<String>,
|
||||||
|
lines: Vec<Line<'static>>,
|
||||||
|
actions: Vec<(KeyCode, &'static str, &'static str)>,
|
||||||
|
) -> Self {
|
||||||
|
let mut scroll = Scroll::default();
|
||||||
|
scroll.start();
|
||||||
|
Self {
|
||||||
|
title: title.into(),
|
||||||
|
lines,
|
||||||
|
scroll,
|
||||||
|
actions,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn key(&mut self, k: KeyEvent) -> Act {
|
||||||
|
if let Some((_, _, l)) = self.actions.iter().find(|(c, _, _)| *c == k.code) {
|
||||||
|
return Act::Pick((*l).into());
|
||||||
|
}
|
||||||
|
let (p, h) = (self.scroll.page(), self.scroll.half_page());
|
||||||
|
match k.code {
|
||||||
|
KeyCode::Char('j') | KeyCode::Down => self.scroll.down(1),
|
||||||
|
KeyCode::Char('k') | KeyCode::Up => self.scroll.up(1),
|
||||||
|
KeyCode::PageDown | KeyCode::Char(' ') => self.scroll.down(p),
|
||||||
|
KeyCode::PageUp | KeyCode::Char('b') => self.scroll.up(p),
|
||||||
|
KeyCode::Char('d') => self.scroll.down(h),
|
||||||
|
KeyCode::Char('u') => self.scroll.up(h),
|
||||||
|
KeyCode::Char('g') | KeyCode::Home => self.scroll.start(),
|
||||||
|
KeyCode::Char('G') | KeyCode::End => self.scroll.end(),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
Act::None
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn wheel(&mut self, up: bool) {
|
||||||
|
if up {
|
||||||
|
self.scroll.up(3)
|
||||||
|
} else {
|
||||||
|
self.scroll.down(3)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw(&mut 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 mut hint = vec![Span::styled(" ", th.dim())];
|
||||||
|
for (_, name, label) in &self.actions {
|
||||||
|
hint.push(Span::styled(format!("{name} "), th.accent()));
|
||||||
|
hint.push(Span::styled(format!("{label} · "), th.dim()));
|
||||||
|
}
|
||||||
|
hint.push(Span::styled("j/k pgup/pgdn g/G scroll ", th.dim()));
|
||||||
|
let block = Block::bordered()
|
||||||
|
.border_style(th.dim())
|
||||||
|
.title(Span::styled(format!(" {} ", self.title), th.accent()))
|
||||||
|
.title_bottom(Line::from(hint));
|
||||||
|
let inner = block.inner(r);
|
||||||
|
f.render_widget(Clear, r);
|
||||||
|
f.render_widget(block, r);
|
||||||
|
let p = Paragraph::new(self.lines.clone()).wrap(Wrap { trim: false });
|
||||||
|
let total = p.line_count(inner.width).min(u16::MAX as usize) as u16;
|
||||||
|
let top = self.scroll.resolve(total, inner.height);
|
||||||
|
f.render_widget(p.scroll((top, 0)), inner);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crossterm::event::{KeyEventKind, KeyEventState, KeyModifiers};
|
||||||
|
|
||||||
|
fn k(c: KeyCode) -> KeyEvent {
|
||||||
|
KeyEvent {
|
||||||
|
code: c,
|
||||||
|
modifiers: KeyModifiers::NONE,
|
||||||
|
kind: KeyEventKind::Press,
|
||||||
|
state: KeyEventState::NONE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn long_text_scrolls_and_keys_pick() {
|
||||||
|
let lines = (0..100).map(|i| Line::raw(format!("line {i}"))).collect();
|
||||||
|
let mut v = DocView::new("plan", lines, vec![(KeyCode::Enter, "enter", "Implement")]);
|
||||||
|
let show = |v: &mut DocView| {
|
||||||
|
let mut t = ratatui::Terminal::new(ratatui::backend::TestBackend::new(60, 20)).unwrap();
|
||||||
|
t.draw(|f| v.draw(f)).unwrap();
|
||||||
|
format!("{}", t.backend())
|
||||||
|
};
|
||||||
|
let s = show(&mut v);
|
||||||
|
assert!(s.contains("line 0") && !s.contains("line 60"), "{s}");
|
||||||
|
v.key(k(KeyCode::Char('G')));
|
||||||
|
assert!(show(&mut v).contains("line 99"));
|
||||||
|
assert!(matches!(v.key(k(KeyCode::Enter)), Act::Pick(l) if l == "Implement"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
pub mod agents;
|
pub mod agents;
|
||||||
pub mod btw_view;
|
pub mod btw_view;
|
||||||
pub mod choose;
|
pub mod choose;
|
||||||
|
pub mod doc_view;
|
||||||
pub mod editor;
|
pub mod editor;
|
||||||
pub mod permit_view;
|
pub mod permit_view;
|
||||||
pub mod picker;
|
pub mod picker;
|
||||||
@@ -172,6 +173,12 @@ struct App {
|
|||||||
tokio::sync::oneshot::Sender<hx_core::permit::Decision>,
|
tokio::sync::oneshot::Sender<hx_core::permit::Decision>,
|
||||||
)>,
|
)>,
|
||||||
review: Option<review::Review>,
|
review: Option<review::Review>,
|
||||||
|
/// plan view and where the chosen label goes (Implement / Keep planning / Feedback)
|
||||||
|
doc: Option<(
|
||||||
|
doc_view::DocView,
|
||||||
|
hx_core::Question,
|
||||||
|
tokio::sync::oneshot::Sender<Option<Vec<String>>>,
|
||||||
|
)>,
|
||||||
/// `/keys`: show every key as hx receives it until esc
|
/// `/keys`: show every key as hx receives it until esc
|
||||||
probe: bool,
|
probe: bool,
|
||||||
/// keyboard protocol was switched on (shift-enter is distinguishable)
|
/// keyboard protocol was switched on (shift-enter is distinguishable)
|
||||||
@@ -382,6 +389,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
choose: None,
|
choose: None,
|
||||||
perm: None,
|
perm: None,
|
||||||
review: None,
|
review: None,
|
||||||
|
doc: None,
|
||||||
probe: false,
|
probe: false,
|
||||||
kbd,
|
kbd,
|
||||||
stats: None,
|
stats: None,
|
||||||
@@ -496,6 +504,22 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
let _ = reply.send(d);
|
let _ = reply.send(d);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
TEvent::Key(k) if k.kind != KeyEventKind::Release && app.doc.is_some() => {
|
||||||
|
if let Some((v, _, _)) = &mut app.doc
|
||||||
|
&& let doc_view::Act::Pick(l) = v.key(k)
|
||||||
|
&& let Some((_, mut q, reply)) = app.doc.take()
|
||||||
|
{
|
||||||
|
if l == "Feedback" {
|
||||||
|
q.plan = None;
|
||||||
|
q.text = "What should change in the plan?".into();
|
||||||
|
q.options = vec![];
|
||||||
|
app.choose = Some((choose::Choose::input(q), reply));
|
||||||
|
} else {
|
||||||
|
app.t.push(Item::Info(format!("plan: {l}")));
|
||||||
|
let _ = reply.send(Some(vec![l]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
TEvent::Key(k) if k.kind != KeyEventKind::Release && app.choose.is_some() => {
|
TEvent::Key(k) if k.kind != KeyEventKind::Release && app.choose.is_some() => {
|
||||||
if let Some((c, _)) = &mut app.choose
|
if let Some((c, _)) = &mut app.choose
|
||||||
&& let choose::Act::Done(ans) = c.key(k)
|
&& let choose::Act::Done(ans) = c.key(k)
|
||||||
@@ -539,7 +563,24 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
match u {
|
match u {
|
||||||
Ui::Ask(q, reply) => app.ask = Some((q, reply)),
|
Ui::Ask(q, reply) => app.ask = Some((q, reply)),
|
||||||
Ui::Permit(r, reply) => app.perm = Some((permit_view::Prompt::new(r), 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::Choose(q, reply) => {
|
||||||
|
if let Some(p) = &q.plan {
|
||||||
|
let mut md = vec![];
|
||||||
|
transcript::markdown(p, &mut md);
|
||||||
|
let v = doc_view::DocView::new(
|
||||||
|
"plan",
|
||||||
|
md,
|
||||||
|
vec![
|
||||||
|
(KeyCode::Enter, "enter", "Implement"),
|
||||||
|
(KeyCode::Char('f'), "f", "Feedback"),
|
||||||
|
(KeyCode::Esc, "esc", "Keep planning"),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
app.doc = Some((v, q, reply));
|
||||||
|
} else {
|
||||||
|
app.choose = Some((choose::Choose::new(q), reply))
|
||||||
|
}
|
||||||
|
}
|
||||||
Ui::Ev(e) => {
|
Ui::Ev(e) => {
|
||||||
if let Event::SubUsage(u) = &e {
|
if let Event::SubUsage(u) = &e {
|
||||||
app.st.usage.add(u);
|
app.st.usage.add(u);
|
||||||
@@ -908,7 +949,10 @@ fn chat_buf(app: &App) -> (Buffer, Vec<bool>) {
|
|||||||
let lines = app.t.lines(app.expanded, w);
|
let lines = app.t.lines(app.expanded, w);
|
||||||
let mut cont = vec![];
|
let mut cont = vec![];
|
||||||
for l in &lines {
|
for l in &lines {
|
||||||
let n = Paragraph::new(l.clone()).wrap(Wrap { trim: false }).line_count(w).max(1);
|
let n = Paragraph::new(l.clone())
|
||||||
|
.wrap(Wrap { trim: false })
|
||||||
|
.line_count(w)
|
||||||
|
.max(1);
|
||||||
cont.push(false);
|
cont.push(false);
|
||||||
cont.extend(std::iter::repeat(true).take(n - 1));
|
cont.extend(std::iter::repeat(true).take(n - 1));
|
||||||
}
|
}
|
||||||
@@ -942,6 +986,7 @@ fn select_mouse(app: &mut App, m: crossterm::event::MouseEvent) {
|
|||||||
|| app.sessions.is_some()
|
|| app.sessions.is_some()
|
||||||
|| app.choose.is_some()
|
|| app.choose.is_some()
|
||||||
|| app.review.is_some()
|
|| app.review.is_some()
|
||||||
|
|| app.doc.is_some()
|
||||||
|| app.perm.is_some()
|
|| app.perm.is_some()
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
@@ -1015,6 +1060,9 @@ fn select_mouse(app: &mut App, m: crossterm::event::MouseEvent) {
|
|||||||
fn wheel(app: &mut App, m: crossterm::event::MouseEvent, up: bool) {
|
fn wheel(app: &mut App, m: crossterm::event::MouseEvent, up: bool) {
|
||||||
let s = if let Some(agents::View::Detail { scroll, .. }) = &mut app.agents {
|
let s = if let Some(agents::View::Detail { scroll, .. }) = &mut app.agents {
|
||||||
scroll
|
scroll
|
||||||
|
} else if let Some((v, _, _)) = &mut app.doc {
|
||||||
|
v.wheel(up);
|
||||||
|
return;
|
||||||
} else if app.picker.is_some() || app.sessions.is_some() || app.choose.is_some() {
|
} else if app.picker.is_some() || app.sessions.is_some() || app.choose.is_some() {
|
||||||
return;
|
return;
|
||||||
} else if app.panel.is_some() && inside(app.areas.panel, m.column, m.row) {
|
} else if app.panel.is_some() && inside(app.areas.panel, m.column, m.row) {
|
||||||
@@ -1334,7 +1382,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
|||||||
let (c, arg) = cmd
|
let (c, arg) = cmd
|
||||||
.split_once(' ')
|
.split_once(' ')
|
||||||
.map_or((cmd, ""), |(a, b)| (a, b.trim()));
|
.map_or((cmd, ""), |(a, b)| (a, b.trim()));
|
||||||
if app.busy && !matches!(c, "quit" | "btw" | "yolo" | "auto") {
|
if app.busy && !matches!(c, "quit" | "btw" | "yolo" | "auto" | "plan") {
|
||||||
app.t.push(Item::Error("busy; esc to abort first".into()));
|
app.t.push(Item::Error("busy; esc to abort first".into()));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -1486,6 +1534,24 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
|||||||
drop(al);
|
drop(al);
|
||||||
app.t.push(Item::Info(m));
|
app.t.push(Item::Info(m));
|
||||||
}
|
}
|
||||||
|
"plan" => {
|
||||||
|
let mut al = app.state.allow.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
let on = match arg {
|
||||||
|
"on" => true,
|
||||||
|
"off" => false,
|
||||||
|
_ => !al.plan_on(),
|
||||||
|
};
|
||||||
|
al.set_plan(on);
|
||||||
|
drop(al);
|
||||||
|
app.t.push(Item::Info(
|
||||||
|
if on {
|
||||||
|
"plan on: read-only; the plan is shown in full for approval when ready"
|
||||||
|
} else {
|
||||||
|
"plan off"
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
"yolo" => {
|
"yolo" => {
|
||||||
let on = app
|
let on = app
|
||||||
.state
|
.state
|
||||||
@@ -1683,6 +1749,32 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
|||||||
)));
|
)));
|
||||||
line = r.prompt;
|
line = r.prompt;
|
||||||
}
|
}
|
||||||
|
// a prompt starting with the word `plan` turns plan mode on
|
||||||
|
if line
|
||||||
|
.split_whitespace()
|
||||||
|
.next()
|
||||||
|
.is_some_and(|w| w.eq_ignore_ascii_case("plan"))
|
||||||
|
{
|
||||||
|
let mut al = app.state.allow.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
if !al.plan_on() {
|
||||||
|
al.set_plan(true);
|
||||||
|
drop(al);
|
||||||
|
app.t.push(Item::Info(
|
||||||
|
"plan on (prompt starts with `plan`): read-only until the plan is approved".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if app
|
||||||
|
.state
|
||||||
|
.allow
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.plan_on()
|
||||||
|
{
|
||||||
|
line = format!(
|
||||||
|
"[plan mode: read-only. Research, then call exit_plan with the complete plan.]\n{line}"
|
||||||
|
);
|
||||||
|
}
|
||||||
app.busy = true;
|
app.busy = true;
|
||||||
app.since = Instant::now();
|
app.since = Instant::now();
|
||||||
app.run_tokens = (0, 0);
|
app.run_tokens = (0, 0);
|
||||||
@@ -1929,6 +2021,9 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
|||||||
if let Some(r) = &app.review {
|
if let Some(r) = &app.review {
|
||||||
r.draw(f);
|
r.draw(f);
|
||||||
}
|
}
|
||||||
|
if let Some((v, _, _)) = &mut app.doc {
|
||||||
|
v.draw(f);
|
||||||
|
}
|
||||||
if let Some((p, _)) = &app.perm {
|
if let Some((p, _)) = &app.perm {
|
||||||
p.draw(f, input.y);
|
p.draw(f, input.y);
|
||||||
}
|
}
|
||||||
@@ -2643,6 +2738,7 @@ mod tests {
|
|||||||
choose: None,
|
choose: None,
|
||||||
perm: None,
|
perm: None,
|
||||||
review: None,
|
review: None,
|
||||||
|
doc: None,
|
||||||
probe: false,
|
probe: false,
|
||||||
kbd: false,
|
kbd: false,
|
||||||
stats: None,
|
stats: None,
|
||||||
|
|||||||
@@ -555,7 +555,7 @@ fn advance(cur: Option<usize>, l: &str) -> Option<usize> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Minimal markdown: fenced code, headings, bullets, inline `code` and **bold**.
|
/// Minimal markdown: fenced code, headings, bullets, inline `code` and **bold**.
|
||||||
fn markdown(s: &str, out: &mut Vec<Line<'static>>) {
|
pub(crate) fn markdown(s: &str, out: &mut Vec<Line<'static>>) {
|
||||||
let mut code = false;
|
let mut code = false;
|
||||||
for l in s.lines() {
|
for l in s.lines() {
|
||||||
if l.trim_start().starts_with("```") {
|
if l.trim_start().starts_with("```") {
|
||||||
|
|||||||
Reference in new issue
Block a user