ask_user tool and choose popup #112
No files matched your search
@@ -24,6 +24,27 @@ pub type Ask = std::sync::Arc<
|
||||
+ 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.
|
||||
#[derive(Default)]
|
||||
pub struct State {
|
||||
@@ -31,6 +52,8 @@ 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>,
|
||||
/// Same for multiple-choice questions.
|
||||
pub choose: std::sync::OnceLock<Choose>,
|
||||
}
|
||||
|
||||
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) {
|
||||
let m = std::fs::metadata(p).and_then(|m| m.modified()).ok();
|
||||
self.seen
|
||||
|
||||
@@ -57,7 +57,7 @@ fn tail(s: &str, max: usize) -> &str {
|
||||
|
||||
pub fn registry() -> Registry {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
#[async_trait]
|
||||
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]
|
||||
async fn read_ranges_binary_missing() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
//! 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"
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw(&self, f: &mut ratatui::Frame, bottom: u16) {
|
||||
let th = theme::t();
|
||||
let area = f.area();
|
||||
let (on, off) = if th.sym.bar_full == "#" {
|
||||
("[x]", "[ ]")
|
||||
} else {
|
||||
("◉", "○")
|
||||
};
|
||||
let mut lines: Vec<Line> = vec![];
|
||||
for (i, (l, d)) in self.q.options.iter().enumerate() {
|
||||
let st = if i == self.sel && self.typing.is_none() {
|
||||
th.sel()
|
||||
} else {
|
||||
th.plain()
|
||||
};
|
||||
let mark = if self.q.multi {
|
||||
if self.picked[i] { on } else { off }
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let mut s = vec![Span::styled(format!(" {} {mark} {l} ", i + 1), st)];
|
||||
if !d.is_empty() {
|
||||
s.push(Span::styled(format!(" {d}"), th.dim()));
|
||||
}
|
||||
lines.push(Line::from(s));
|
||||
}
|
||||
if self.q.other {
|
||||
let st = if self.is_other() && self.typing.is_none() {
|
||||
th.sel()
|
||||
} else {
|
||||
th.plain()
|
||||
};
|
||||
lines.push(match &self.typing {
|
||||
Some(t) => Line::from(vec![
|
||||
Span::styled(" other: ", th.accent()),
|
||||
Span::raw(format!("{t}▏")),
|
||||
]),
|
||||
None => Line::styled(format!(" {} other…", self.q.options.len() + 1), st),
|
||||
});
|
||||
}
|
||||
let w = area.width.min(80).max(20.min(area.width));
|
||||
let inner = w.saturating_sub(2).max(1) as usize;
|
||||
let qh = Paragraph::new(self.q.text.as_str())
|
||||
.wrap(Wrap { trim: false })
|
||||
.line_count(inner as u16) as u16;
|
||||
let h = (qh + lines.len() as u16 + 3).min(bottom);
|
||||
let r = Rect::new((area.width - w) / 2, bottom.saturating_sub(h), w, h);
|
||||
f.render_widget(Clear, r);
|
||||
let block = Block::bordered()
|
||||
.border_style(th.accent())
|
||||
.title(Span::styled(format!(" {} ", self.help()), th.dim()));
|
||||
let body = block.inner(r);
|
||||
f.render_widget(block, r);
|
||||
let [qa, la] = ratatui::layout::Layout::vertical([
|
||||
ratatui::layout::Constraint::Length(qh.min(body.height)),
|
||||
ratatui::layout::Constraint::Min(0),
|
||||
])
|
||||
.areas(body);
|
||||
f.render_widget(
|
||||
Paragraph::new(self.q.text.as_str()).wrap(Wrap { trim: false }),
|
||||
qa,
|
||||
);
|
||||
// keep the selection visible when the list is taller than the box
|
||||
let skip = (self.sel as u16).saturating_sub(la.height.saturating_sub(1));
|
||||
f.render_widget(Paragraph::new(lines).scroll((skip, 0)), la);
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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, 12)).unwrap();
|
||||
term.draw(|f| c.draw(f, 11)).unwrap();
|
||||
let b = term.backend().buffer().clone();
|
||||
let all: String = (0..12)
|
||||
.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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Interactive terminal UI.
|
||||
|
||||
pub mod choose;
|
||||
pub mod editor;
|
||||
pub mod picker;
|
||||
pub mod popup;
|
||||
@@ -69,6 +70,10 @@ pub type LspStatus = Box<
|
||||
enum Ui {
|
||||
Ev(Event),
|
||||
Ask(String, tokio::sync::oneshot::Sender<bool>),
|
||||
Choose(
|
||||
hx_core::Question,
|
||||
tokio::sync::oneshot::Sender<Option<Vec<String>>>,
|
||||
),
|
||||
Done(Result<(), String>),
|
||||
Compacted(Result<bool, String>),
|
||||
}
|
||||
@@ -116,6 +121,11 @@ struct App {
|
||||
ask: Option<(String, tokio::sync::oneshot::Sender<bool>)>,
|
||||
/// condensed lens state for the footer, refreshed by a timer
|
||||
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 {
|
||||
@@ -194,6 +204,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.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 cwd = agent.cx.cwd.clone();
|
||||
let mut app = App {
|
||||
@@ -227,6 +245,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
wide: false,
|
||||
ask: None,
|
||||
lens: (String::new(), false),
|
||||
choose: None,
|
||||
};
|
||||
sessions::history(&mut app.t, &agent.session().messages());
|
||||
if open_sessions {
|
||||
@@ -267,6 +286,15 @@ 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.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() => {
|
||||
let yes = match k.code {
|
||||
KeyCode::Char('y' | 'Y') => Some(true),
|
||||
@@ -293,6 +321,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
dirty = true;
|
||||
match u {
|
||||
Ui::Ask(q, reply) => app.ask = Some((q, reply)),
|
||||
Ui::Choose(q, reply) => app.choose = Some((choose::Choose::new(q), reply)),
|
||||
Ui::Ev(e) => {
|
||||
if let Event::Stream(hx_ai::StreamEvent::Quota(q)) = &e {
|
||||
app.st.quota = Some(q.clone());
|
||||
@@ -796,7 +825,7 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
}
|
||||
let chrome = status::Chrome {
|
||||
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(),
|
||||
scroll: app.scroll,
|
||||
title: app.title.as_deref(),
|
||||
@@ -812,6 +841,9 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
)),
|
||||
status_row,
|
||||
);
|
||||
if let Some((c, _)) = &app.choose {
|
||||
c.draw(f, input.y);
|
||||
}
|
||||
if let Some(popup::Popup { comp, sel }) = &app.popup {
|
||||
let col = Span::raw(
|
||||
&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,
|
||||
ask: None,
|
||||
lens: (String::new(), false),
|
||||
choose: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user