Merge pull request 'ask_user tool and choose popup' (#112) from ask-user-tool into main
ci / check (push) Canceled after 0s

This commit was merged in pull request #112.
This commit is contained in:
hermes committed 2026-10-02 11:26:05 +00:00
commit 6b980591ed
4 files changed
+481 -2

No files matched your search

+31
View File
@@ -24,6 +24,27 @@ pub type Ask = std::sync::Arc<
+ Sync, + Sync,
>; >;
/// A multiple-choice question for the user (the `ask_user` tool).
#[derive(Debug, Clone, PartialEq)]
pub struct Question {
pub text: String,
/// (label, description)
pub options: Vec<(String, String)>,
pub multi: bool,
/// offer a free-text "Other" row
pub other: bool,
}
/// Shows a [`Question`]; resolves to the chosen labels / typed text, None when dismissed.
pub type Choose = std::sync::Arc<
dyn Fn(
Question,
)
-> std::pin::Pin<Box<dyn std::future::Future<Output = Option<Vec<String>>> + Send>>
+ Send
+ Sync,
>;
/// Cross-tool shared state. /// Cross-tool shared state.
#[derive(Default)] #[derive(Default)]
pub struct State { pub struct State {
@@ -31,6 +52,8 @@ pub struct State {
pub seen: Mutex<HashMap<PathBuf, Option<SystemTime>>>, pub seen: Mutex<HashMap<PathBuf, Option<SystemTime>>>,
/// Set by interactive frontends; None = nobody to ask (print mode, mcp-serve). /// Set by interactive frontends; None = nobody to ask (print mode, mcp-serve).
pub ask: std::sync::OnceLock<Ask>, pub ask: std::sync::OnceLock<Ask>,
/// Same for multiple-choice questions.
pub choose: std::sync::OnceLock<Choose>,
} }
impl State { impl State {
@@ -42,6 +65,14 @@ impl State {
} }
} }
/// Err when no interactive frontend is attached; Ok(None) when the user dismissed it.
pub async fn choose(&self, q: Question) -> Result<Option<Vec<String>>, &'static str> {
match self.choose.get() {
Some(c) => Ok(c(q).await),
None => Err("no interactive user attached; decide yourself or state your assumption"),
}
}
pub fn mark_seen(&self, p: &std::path::Path) { pub fn mark_seen(&self, p: &std::path::Path) {
let m = std::fs::metadata(p).and_then(|m| m.modified()).ok(); let m = std::fs::metadata(p).and_then(|m| m.modified()).ok();
self.seen self.seen
+68 -1
View File
@@ -57,7 +57,7 @@ fn tail(s: &str, max: usize) -> &str {
pub fn registry() -> Registry { pub fn registry() -> Registry {
let mut r = Registry::default(); let mut r = Registry::default();
r.add(Read).add(Write).add(Edit).add(Bash); r.add(Read).add(Write).add(Edit).add(Bash).add(AskUser);
r r
} }
@@ -257,6 +257,50 @@ impl Tool for Edit {
} }
} }
pub struct AskUser;
#[async_trait]
impl Tool for AskUser {
fn spec(&self) -> ToolSpec {
spec(
"ask_user",
"Ask the user to pick between options (they may also type their own answer). Only when a decision blocks you and cannot be inferred; otherwise pick a default and say so.",
json!({"type":"object","properties":{
"question":{"type":"string"},
"options":{"type":"array","maxItems":6,"items":{"type":"object","properties":{
"label":{"type":"string"},"description":{"type":"string"}},"required":["label"]}},
"multi":{"type":"boolean","description":"allow several options"}},
"required":["question"]}),
)
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
let options = a["options"]
.as_array()
.into_iter()
.flatten()
.filter_map(|o| {
Some((
o["label"].as_str()?.to_string(),
o["description"].as_str().unwrap_or_default().to_string(),
))
})
.take(6)
.collect();
let q = hx_core::Question {
text: a["question"].as_str().unwrap_or_default().into(),
options,
multi: a["multi"].as_bool().unwrap_or(false),
other: true,
};
match cx.state.choose(q).await {
Err(e) => ToolResult::err(e),
Ok(None) => {
ToolResult::ok("user dismissed the question; proceed with your best default")
}
Ok(Some(v)) => ToolResult::ok(v.join(", ")),
}
}
}
pub struct Bash; pub struct Bash;
#[async_trait] #[async_trait]
impl Tool for Bash { impl Tool for Bash {
@@ -342,6 +386,29 @@ mod tests {
} }
} }
#[tokio::test]
async fn ask_user_paths() {
let d = tempfile::tempdir().unwrap();
let c = cx(d.path());
let a =
json!({"question":"db?","options":[{"label":"pg","description":"x"},{"label":"lite"}]});
let r = AskUser.call(a.clone(), &c).await;
assert!(r.is_error && r.content.contains("no interactive user"));
let _ = c.state.choose.set(std::sync::Arc::new(|q| {
Box::pin(async move {
assert!(!q.multi && q.other);
if q.text == "db?" {
Some(vec!["pg".into(), "me".into()])
} else {
None
}
})
}));
assert_eq!(AskUser.call(a, &c).await, ToolResult::ok("pg, me"));
let r = AskUser.call(json!({"question":"other"}), &c).await;
assert!(!r.is_error && r.content.contains("dismissed"));
}
#[tokio::test] #[tokio::test]
async fn read_ranges_binary_missing() { async fn read_ranges_binary_missing() {
let d = tempfile::tempdir().unwrap(); let d = tempfile::tempdir().unwrap();
+348
View File
@@ -0,0 +1,348 @@
//! Popup for the `ask_user` tool: pick one or several options, or type an own answer.
use crate::theme;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use hx_core::Question;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Clear, Paragraph, Wrap};
pub enum Act {
None,
/// Close and answer: chosen labels / typed text, None = dismissed.
Done(Option<Vec<String>>),
}
pub struct Choose {
q: Question,
sel: usize,
picked: Vec<bool>,
/// Some while typing an own answer
typing: Option<String>,
}
impl Choose {
pub fn new(q: Question) -> Self {
Self {
picked: vec![false; q.options.len()],
q,
sel: 0,
typing: None,
}
}
fn rows(&self) -> usize {
self.q.options.len() + usize::from(self.q.other)
}
fn is_other(&self) -> bool {
self.q.other && self.sel == self.q.options.len()
}
fn labels(&self) -> Vec<String> {
let mut v: Vec<String> = (0..self.picked.len())
.filter(|&i| self.picked[i])
.map(|i| self.q.options[i].0.clone())
.collect();
if v.is_empty() && !self.is_other() && self.sel < self.q.options.len() {
v.push(self.q.options[self.sel].0.clone());
}
v
}
pub fn key(&mut self, k: KeyEvent) -> Act {
if k.modifiers.contains(KeyModifiers::CONTROL) && k.code == KeyCode::Char('c') {
return Act::Done(None);
}
let picked = if self.q.multi { self.labels() } else { vec![] };
if let Some(t) = &mut self.typing {
match k.code {
KeyCode::Esc => self.typing = None,
KeyCode::Backspace => {
t.pop();
}
KeyCode::Char(c) => t.push(c),
KeyCode::Enter if !t.trim().is_empty() => {
let mut v = picked;
v.push(t.trim().to_string());
return Act::Done(Some(v));
}
_ => {}
}
return Act::None;
}
let n = self.rows();
match k.code {
KeyCode::Esc => return Act::Done(None),
KeyCode::Up | KeyCode::Char('k') => self.sel = (self.sel + n.max(1) - 1) % n.max(1),
KeyCode::Down | KeyCode::Char('j') => self.sel = (self.sel + 1) % n.max(1),
KeyCode::Char(' ') if self.q.multi && !self.is_other() => {
self.picked[self.sel] = !self.picked[self.sel];
}
KeyCode::Char(c @ '1'..='9') => {
let i = c as usize - '1' as usize;
if i < n {
self.sel = i;
if self.q.multi && !self.is_other() {
self.picked[i] = !self.picked[i];
} else {
return self.enter();
}
}
}
KeyCode::Enter => return self.enter(),
_ => {}
}
Act::None
}
fn enter(&mut self) -> Act {
if self.is_other() || self.rows() == 0 {
self.typing = Some(String::new());
return Act::None;
}
Act::Done(Some(self.labels()))
}
pub fn help(&self) -> &'static str {
if self.typing.is_some() {
"enter send · esc back"
} else if self.q.multi {
"↑↓ move · space toggle · enter confirm · esc skip"
} else {
"↑↓ move · 1-9 · enter pick · esc skip"
}
}
/// Centered in the first `bottom` rows (the transcript area).
pub fn draw(&self, f: &mut ratatui::Frame, bottom: u16) {
use ratatui::layout::{Constraint, Layout};
use ratatui::style::Modifier;
use ratatui::widgets::Padding;
let th = theme::t();
let area = f.area();
let (on, off) = if th.sym.bar_full == "#" {
("[x]", "[ ]")
} else {
("◉", "○")
};
let w = (area.width * 3 / 5).clamp(60, 140).min(area.width);
let inner = w.saturating_sub(4).max(1) as usize;
let mut lines: Vec<Line> = vec![];
// first line of the selected row, to keep it visible when the list scrolls
let mut sel_line = 0;
for (i, (l, d)) in self.q.options.iter().enumerate() {
let on_row = i == self.sel && self.typing.is_none();
if i == self.sel {
sel_line = lines.len();
}
let st = if on_row { th.sel() } else { th.plain() };
let mark = if !self.q.multi {
""
} else if self.picked[i] {
on
} else {
off
};
lines.push(Line::from(vec![
Span::styled(format!("{} ", i + 1), th.accent()),
Span::styled(format!("{mark} {l} ").replace(" ", " "), st),
]));
for dl in wrap(d, inner.saturating_sub(3)) {
lines.push(Line::styled(format!(" {dl}"), th.dim()));
}
lines.push(Line::raw(""));
}
if self.q.other {
let n = self.q.options.len();
if self.is_other() {
sel_line = lines.len();
}
lines.push(match &self.typing {
Some(t) => Line::from(vec![
Span::styled(format!("{} ", n + 1), th.accent()),
Span::styled("other: ", th.accent()),
Span::raw(format!("{t}▏")),
]),
None => Line::from(vec![
Span::styled(format!("{} ", n + 1), th.accent()),
Span::styled(
"other…",
if self.is_other() {
th.sel()
} else {
th.plain()
},
),
]),
});
}
let q = Paragraph::new(self.q.text.as_str())
.wrap(Wrap { trim: false })
.style(th.plain().add_modifier(Modifier::BOLD));
let qh = q.line_count(inner as u16) as u16;
// borders 2 + padding top 1, question, gap, list, help row
let h = (qh + lines.len() as u16 + 5).min(bottom).max(6.min(bottom));
let r = Rect::new((area.width - w) / 2, (bottom - h) / 2, w, h);
f.render_widget(Clear, r);
let block = Block::bordered()
.border_style(th.accent())
.padding(Padding::new(1, 1, 1, 0));
let body = block.inner(r);
f.render_widget(block, r);
let [qa, _, la, ha] = Layout::vertical([
Constraint::Length(qh.min(body.height.saturating_sub(2))),
Constraint::Length(1),
Constraint::Min(0),
Constraint::Length(1),
])
.areas(body);
f.render_widget(q, qa);
let skip = (sel_line as u16).saturating_sub(la.height.saturating_sub(2));
f.render_widget(Paragraph::new(lines).scroll((skip, 0)), la);
f.render_widget(Span::styled(self.help(), th.dim()), ha);
}
pub fn summary(&self, answer: &Option<Vec<String>>) -> String {
match answer {
Some(v) => format!("? {} → {}", self.q.text, v.join(", ")),
None => format!("? {} → (skipped)", self.q.text),
}
}
}
/// Greedy word wrap to `w` chars (a single longer word is kept whole).
fn wrap(s: &str, w: usize) -> Vec<String> {
let mut out: Vec<String> = vec![];
for word in s.split_whitespace() {
match out.last_mut() {
Some(l) if l.chars().count() + 1 + word.chars().count() <= w => {
l.push(' ');
l.push_str(word);
}
_ => out.push(word.to_string()),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn q(multi: bool) -> Choose {
Choose::new(Question {
text: "which db?".into(),
options: vec![
("pg".into(), "postgres".into()),
("lite".into(), String::new()),
],
multi,
other: true,
})
}
fn k(c: KeyCode) -> KeyEvent {
KeyEvent::new(c, KeyModifiers::NONE)
}
fn done(a: Act) -> Option<Vec<String>> {
match a {
Act::Done(v) => v,
Act::None => panic!("not done"),
}
}
#[test]
fn single_pick_by_enter_number_esc() {
let mut c = q(false);
c.key(k(KeyCode::Down));
assert_eq!(done(c.key(k(KeyCode::Enter))), Some(vec!["lite".into()]));
assert_eq!(
done(q(false).key(k(KeyCode::Char('1')))),
Some(vec!["pg".into()])
);
assert_eq!(done(q(false).key(k(KeyCode::Esc))), None);
// wraps up from the top onto "other"
let mut c = q(false);
c.key(k(KeyCode::Up));
assert!(c.is_other());
}
#[test]
fn multi_toggle_and_other_text() {
let mut c = q(true);
c.key(k(KeyCode::Char(' ')));
c.key(k(KeyCode::Char('2')));
assert_eq!(
done(c.key(k(KeyCode::Enter))),
Some(vec!["pg".into(), "lite".into()])
);
let mut c = q(true);
c.key(k(KeyCode::Char('1')));
c.key(k(KeyCode::Char('3')));
assert!(matches!(c.key(k(KeyCode::Enter)), Act::None)); // empty text: stays
for ch in "duck".chars() {
c.key(k(KeyCode::Char(ch)));
}
assert_eq!(
done(c.key(k(KeyCode::Enter))),
Some(vec!["pg".into(), "duck".into()])
);
}
#[test]
fn typing_esc_goes_back_and_renders() {
let mut c = q(false);
c.key(k(KeyCode::Char('3')));
assert!(c.typing.is_some());
c.key(k(KeyCode::Esc));
assert!(c.typing.is_none());
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(60, 20)).unwrap();
term.draw(|f| c.draw(f, 19)).unwrap();
let b = term.backend().buffer().clone();
let all: String = (0..20)
.map(|y| {
(0..60)
.map(|x| b[(x, y)].symbol().to_string())
.collect::<String>()
+ "\n"
})
.collect();
assert!(
all.contains("which db?") && all.contains("postgres") && all.contains("other…"),
"{all}"
);
}
#[test]
fn big_screen_is_wide_centered_and_wraps_descriptions() {
let c = Choose::new(Question {
text: "Which storage backend should the cache use?".into(),
options: vec![
("redis".into(), "word ".repeat(40)),
("none".into(), String::new()),
],
multi: false,
other: true,
});
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(200, 50)).unwrap();
term.draw(|f| c.draw(f, 45)).unwrap();
let b = term.backend().buffer().clone();
let rows: Vec<String> = (0..50)
.map(|y| (0..200).map(|x| b[(x, y)].symbol().to_string()).collect())
.collect();
let top = rows
.iter()
.position(|r| r.contains('┌') || r.contains('╭'))
.unwrap();
let bot = rows
.iter()
.rposition(|r| r.contains('└') || r.contains('╰'))
.unwrap();
assert!(top > 10 && bot < 45, "centered: {top}..{bot}");
let border = &rows[top];
let wd = border.matches('─').count() + 2;
assert_eq!(wd, 120, "{border}");
assert!(rows.iter().filter(|r| r.contains("word word")).count() >= 2);
assert!(rows[bot - 1].contains("enter pick"), "{}", rows[bot - 1]);
}
}
+34 -1
View File
@@ -1,5 +1,6 @@
//! Interactive terminal UI. //! Interactive terminal UI.
pub mod choose;
pub mod editor; pub mod editor;
pub mod picker; pub mod picker;
pub mod popup; pub mod popup;
@@ -69,6 +70,10 @@ pub type LspStatus = Box<
enum Ui { enum Ui {
Ev(Event), Ev(Event),
Ask(String, tokio::sync::oneshot::Sender<bool>), Ask(String, tokio::sync::oneshot::Sender<bool>),
Choose(
hx_core::Question,
tokio::sync::oneshot::Sender<Option<Vec<String>>>,
),
Done(Result<(), String>), Done(Result<(), String>),
Compacted(Result<bool, String>), Compacted(Result<bool, String>),
} }
@@ -116,6 +121,11 @@ struct App {
ask: Option<(String, tokio::sync::oneshot::Sender<bool>)>, ask: Option<(String, tokio::sync::oneshot::Sender<bool>)>,
/// condensed lens state for the footer, refreshed by a timer /// condensed lens state for the footer, refreshed by a timer
lens: (String, bool), lens: (String, bool),
/// open `ask_user` popup and where its answer goes
choose: Option<(
choose::Choose,
tokio::sync::oneshot::Sender<Option<Vec<String>>>,
)>,
} }
impl App { impl App {
@@ -194,6 +204,14 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
Box::pin(async move { orx.await.unwrap_or(false) }) Box::pin(async move { orx.await.unwrap_or(false) })
})); }));
} }
{
let tx = tx.clone();
let _ = agent.cx.state.choose.set(std::sync::Arc::new(move |q| {
let (otx, orx) = tokio::sync::oneshot::channel();
let _ = tx.send(Ui::Choose(q, otx));
Box::pin(async move { orx.await.unwrap_or(None) })
}));
}
let abort: AbortHandle = agent.abort_handle(); let abort: AbortHandle = agent.abort_handle();
let cwd = agent.cx.cwd.clone(); let cwd = agent.cx.cwd.clone();
let mut app = App { let mut app = App {
@@ -227,6 +245,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
wide: false, wide: false,
ask: None, ask: None,
lens: (String::new(), false), lens: (String::new(), false),
choose: None,
}; };
sessions::history(&mut app.t, &agent.session().messages()); sessions::history(&mut app.t, &agent.session().messages());
if open_sessions { if open_sessions {
@@ -267,6 +286,15 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
let Some(Ok(ev)) = k else { break }; let Some(Ok(ev)) = k else { break };
dirty = true; dirty = true;
match ev { match ev {
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)
&& let Some((c, reply)) = app.choose.take()
{
app.t.push(Item::Info(c.summary(&ans)));
let _ = reply.send(ans);
}
}
TEvent::Key(k) if k.kind != KeyEventKind::Release && app.ask.is_some() => { TEvent::Key(k) if k.kind != KeyEventKind::Release && app.ask.is_some() => {
let yes = match k.code { let yes = match k.code {
KeyCode::Char('y' | 'Y') => Some(true), KeyCode::Char('y' | 'Y') => Some(true),
@@ -293,6 +321,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
dirty = true; dirty = true;
match u { match u {
Ui::Ask(q, reply) => app.ask = Some((q, reply)), Ui::Ask(q, reply) => app.ask = Some((q, reply)),
Ui::Choose(q, reply) => app.choose = Some((choose::Choose::new(q), reply)),
Ui::Ev(e) => { Ui::Ev(e) => {
if let Event::Stream(hx_ai::StreamEvent::Quota(q)) = &e { if let Event::Stream(hx_ai::StreamEvent::Quota(q)) = &e {
app.st.quota = Some(q.clone()); app.st.quota = Some(q.clone());
@@ -796,7 +825,7 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
} }
let chrome = status::Chrome { let chrome = status::Chrome {
ask: app.ask.as_ref().map(|(q, _)| q.as_str()), ask: app.ask.as_ref().map(|(q, _)| q.as_str()),
hint: &app.hint, hint: app.choose.as_ref().map_or(&app.hint, |(c, _)| c.help()),
queued: app.queue.len(), queued: app.queue.len(),
scroll: app.scroll, scroll: app.scroll,
title: app.title.as_deref(), title: app.title.as_deref(),
@@ -812,6 +841,9 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
)), )),
status_row, status_row,
); );
if let Some((c, _)) = &app.choose {
c.draw(f, input.y);
}
if let Some(popup::Popup { comp, sel }) = &app.popup { if let Some(popup::Popup { comp, sel }) = &app.popup {
let col = Span::raw( let col = Span::raw(
&app.ed.buf[app.ed.buf[..comp.start].rfind('\n').map_or(0, |i| i + 1)..comp.start], &app.ed.buf[app.ed.buf[..comp.start].rfind('\n').map_or(0, |i| i + 1)..comp.start],
@@ -976,6 +1008,7 @@ mod tests {
wide: false, wide: false,
ask: None, ask: None,
lens: (String::new(), false), lens: (String::new(), false),
choose: None,
} }
} }