Add /btw: side question without tools, not saved, works mid-run
This commit is contained in:
1 parent
b223fd1f22
commit
28dff172f2
4 files changed
+233
-1
No files matched your search
@@ -10,6 +10,58 @@ use hx_ai::{ContentBlock, Message, Provider, Request, Role, StopReason, StreamEv
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::watch;
|
||||
|
||||
/// What `/btw` needs, readable while a run holds the agent lock.
|
||||
pub struct Snap {
|
||||
provider: Arc<dyn Provider>,
|
||||
model: String,
|
||||
system: String,
|
||||
messages: Vec<Message>,
|
||||
}
|
||||
|
||||
impl Snap {
|
||||
/// One tool-less request on the conversation so far plus `question`; nothing is saved.
|
||||
/// Returns the answer and the request's usage.
|
||||
pub async fn btw(&self, question: &str) -> Result<(String, Usage), Error> {
|
||||
let mut messages = self.messages.clone();
|
||||
// a run in flight may end on tool calls whose results are not in yet
|
||||
if messages.last().is_some_and(|m| {
|
||||
m.role == Role::Assistant
|
||||
&& m.content
|
||||
.iter()
|
||||
.any(|b| matches!(b, ContentBlock::ToolUse { .. }))
|
||||
}) {
|
||||
messages.pop();
|
||||
}
|
||||
let q = ContentBlock::Text {
|
||||
text: format!(
|
||||
"Side question; answer briefly from the conversation so far, without tools:\n{question}"
|
||||
),
|
||||
};
|
||||
match messages.last_mut() {
|
||||
Some(m) if m.role == Role::User => m.content.push(q),
|
||||
_ => messages.push(Message {
|
||||
role: Role::User,
|
||||
content: vec![q],
|
||||
}),
|
||||
}
|
||||
let req = Request {
|
||||
model: self.model.clone(),
|
||||
system: self.system.clone(),
|
||||
messages,
|
||||
tools: vec![],
|
||||
max_tokens: 2048,
|
||||
effort: hx_ai::Effort::Off,
|
||||
};
|
||||
let mut s = self.provider.stream(req).await?;
|
||||
while let Some(ev) = s.next().await {
|
||||
if let StreamEvent::Done { message, usage, .. } = ev? {
|
||||
return Ok((message.text(), usage));
|
||||
}
|
||||
}
|
||||
Err(Error::Truncated)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
@@ -39,6 +91,7 @@ pub struct Agent {
|
||||
window: ContextWindow,
|
||||
abort: watch::Receiver<bool>,
|
||||
abort_tx: Arc<watch::Sender<bool>>,
|
||||
snap: watch::Sender<Arc<Snap>>,
|
||||
}
|
||||
|
||||
/// Cheap handle to cancel a running `Agent::run`.
|
||||
@@ -64,6 +117,13 @@ impl Agent {
|
||||
let (tx, rx) = watch::channel(false);
|
||||
let tx = Arc::new(tx);
|
||||
let _ = cx.state.abort.set(rx.clone());
|
||||
let snap = watch::channel(Arc::new(Snap {
|
||||
provider: provider.clone(),
|
||||
model: String::new(),
|
||||
system: String::new(),
|
||||
messages: session.messages(),
|
||||
}))
|
||||
.0;
|
||||
let a = Self {
|
||||
provider,
|
||||
tools,
|
||||
@@ -79,10 +139,25 @@ impl Agent {
|
||||
window: ContextWindow::new(150_000),
|
||||
abort: rx,
|
||||
abort_tx: tx.clone(),
|
||||
snap,
|
||||
};
|
||||
(a, AbortHandle(tx))
|
||||
}
|
||||
|
||||
/// Live view for `/btw`; stays readable while `run` holds the agent.
|
||||
pub fn snap(&self) -> watch::Receiver<Arc<Snap>> {
|
||||
self.snap.subscribe()
|
||||
}
|
||||
|
||||
fn publish(&self) {
|
||||
self.snap.send_replace(Arc::new(Snap {
|
||||
provider: self.provider.clone(),
|
||||
model: self.model.clone(),
|
||||
system: self.system.clone(),
|
||||
messages: self.session.messages(),
|
||||
}));
|
||||
}
|
||||
|
||||
pub fn set_max_turns(&mut self, n: u32) {
|
||||
self.max_turns = n;
|
||||
}
|
||||
@@ -107,6 +182,7 @@ impl Agent {
|
||||
/// Use another model of the current provider. For a different provider use [`set_provider`](Self::set_provider).
|
||||
pub fn set_model(&mut self, model: impl Into<String>) {
|
||||
self.model = model.into();
|
||||
self.publish();
|
||||
}
|
||||
|
||||
pub fn effort(&self) -> hx_ai::Effort {
|
||||
@@ -120,12 +196,14 @@ impl Agent {
|
||||
|
||||
pub fn set_system(&mut self, system: impl Into<String>) {
|
||||
self.system = system.into();
|
||||
self.publish();
|
||||
}
|
||||
|
||||
/// Append a section to the system prompt.
|
||||
pub fn append_system(&mut self, section: &str) {
|
||||
self.system.push_str("\n\n");
|
||||
self.system.push_str(section);
|
||||
self.publish();
|
||||
}
|
||||
|
||||
/// Cap on tokens per reply. Set it before [`fit_window`](Self::fit_window), which reserves room for it.
|
||||
@@ -164,6 +242,7 @@ impl Agent {
|
||||
pub fn replace_session(&mut self, session: Session) {
|
||||
self.session = session;
|
||||
self.window.reset();
|
||||
self.publish();
|
||||
}
|
||||
|
||||
/// Move the session head to entry `id`. False (and no change) if there is no such entry.
|
||||
@@ -171,6 +250,7 @@ impl Agent {
|
||||
let ok = self.session.fork(id);
|
||||
if ok {
|
||||
self.window.reset();
|
||||
self.publish();
|
||||
}
|
||||
ok
|
||||
}
|
||||
@@ -179,6 +259,7 @@ impl Agent {
|
||||
pub fn clear(&mut self) -> Result<(), Error> {
|
||||
self.session.rebase(vec![])?;
|
||||
self.window.reset();
|
||||
self.publish();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -201,11 +282,13 @@ impl Agent {
|
||||
let summary = summary.ok_or(Error::Truncated)?;
|
||||
self.session.rebase(plan.apply(&summary))?;
|
||||
self.window.reset();
|
||||
self.publish();
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn push(&mut self, m: Message) -> Result<(), Error> {
|
||||
self.session.append(m)?;
|
||||
self.publish();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -213,6 +296,7 @@ impl Agent {
|
||||
fn push_reply(&mut self, m: Message, usage: Usage, mask: usize) -> Result<(), Error> {
|
||||
let by = Some(self.model.clone());
|
||||
self.session.append_masked(m, by, Some(usage), Some(mask))?;
|
||||
self.publish();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -476,6 +560,45 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn btw_reads_snapshot_without_touching_session() {
|
||||
let script = Arc::new(Script(
|
||||
Mutex::new(vec![
|
||||
asst(vec![ContentBlock::Text {
|
||||
text: "done".into(),
|
||||
}]),
|
||||
asst(vec![ContentBlock::Text {
|
||||
text: "side".into(),
|
||||
}]),
|
||||
]),
|
||||
Mutex::new(vec![]),
|
||||
));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cx = ToolCtx {
|
||||
cwd: dir.path().into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let (mut a, _h) = Agent::new(
|
||||
script.clone(),
|
||||
Registry::default(),
|
||||
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
||||
cx,
|
||||
);
|
||||
let snap = a.snap();
|
||||
a.run("go").await.unwrap();
|
||||
let before = a.session().messages().len();
|
||||
// taken from the receiver, no agent access: works while `run` holds the lock
|
||||
let s = snap.borrow().clone();
|
||||
let (text, _) = s.btw("why?").await.unwrap();
|
||||
assert_eq!(text, "side");
|
||||
assert_eq!(a.session().messages().len(), before);
|
||||
let reqs = script.1.lock().unwrap();
|
||||
let r = &reqs[1];
|
||||
assert!(r.tools.is_empty());
|
||||
assert_eq!(r.messages.len(), 3);
|
||||
assert!(r.messages[2].text().contains("why?"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn multi_turn_with_hooks() {
|
||||
let script = Arc::new(Script(
|
||||
|
||||
@@ -84,6 +84,7 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
|
||||
"diff of this session's edits; reject reverts a file",
|
||||
None,
|
||||
),
|
||||
b("btw", "side question; no tools, not saved", Free),
|
||||
b("skills", "list skills and where they load from", None),
|
||||
b(
|
||||
"resume",
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//! `/btw` overlay: the side question and its answer; esc closes (and cancels a pending request).
|
||||
|
||||
use crate::theme;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::text::{Line, Span};
|
||||
use ratatui::widgets::{Block, Clear, Paragraph, Wrap};
|
||||
|
||||
pub struct Btw {
|
||||
pub q: String,
|
||||
/// None while the request is running
|
||||
pub a: Option<Result<String, String>>,
|
||||
pub scroll: u16,
|
||||
pub task: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl Btw {
|
||||
pub fn close(self) {
|
||||
self.task.abort();
|
||||
}
|
||||
|
||||
pub fn draw(&self, f: &mut ratatui::Frame) {
|
||||
let th = theme::t();
|
||||
let a = f.area();
|
||||
let w = (a.width * 7 / 10).clamp(40, 110).min(a.width);
|
||||
let h = (a.height * 7 / 10).clamp(8, 40).min(a.height);
|
||||
let r = Rect::new(a.x + (a.width - w) / 2, a.y + (a.height - h) / 2, w, h);
|
||||
let mut body = vec![
|
||||
Line::styled(format!("> {}", self.q), th.dim()),
|
||||
Line::default(),
|
||||
];
|
||||
match &self.a {
|
||||
None => body.push(Line::styled("thinking…", th.dim())),
|
||||
Some(Ok(t)) => body.extend(t.lines().map(|l| Line::raw(l.to_string()))),
|
||||
Some(Err(e)) => body.push(Line::styled(e.clone(), th.err())),
|
||||
}
|
||||
f.render_widget(Clear, r);
|
||||
f.render_widget(
|
||||
Paragraph::new(body)
|
||||
.wrap(Wrap { trim: false })
|
||||
.scroll((self.scroll, 0))
|
||||
.block(
|
||||
Block::bordered()
|
||||
.border_style(th.dim())
|
||||
.padding(ratatui::widgets::Padding::horizontal(1))
|
||||
.title(Span::styled(" btw ", th.dim()))
|
||||
.title_bottom(Span::styled(" ↑↓ scroll · esc close ", th.dim())),
|
||||
),
|
||||
r,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Interactive terminal UI.
|
||||
|
||||
pub mod agents;
|
||||
pub mod btw_view;
|
||||
pub mod choose;
|
||||
pub mod editor;
|
||||
pub mod permit_view;
|
||||
@@ -104,6 +105,7 @@ enum Ui {
|
||||
),
|
||||
Done(Result<(), String>),
|
||||
Compacted(Result<bool, String>),
|
||||
Btw(Result<(String, hx_ai::Usage), String>),
|
||||
}
|
||||
|
||||
/// Forwards agent events to the UI loop.
|
||||
@@ -169,6 +171,9 @@ struct App {
|
||||
/// keyboard protocol was switched on (shift-enter is distinguishable)
|
||||
kbd: bool,
|
||||
stats: Option<(hx_core::stats::Summary, String)>,
|
||||
/// `/btw` overlay and the agent's live snapshot it answers from
|
||||
btw: Option<btw_view::Btw>,
|
||||
snap: Option<tokio::sync::watch::Receiver<Arc<hx_core::agent::Snap>>>,
|
||||
/// lens/context/MCP side panel (ctrl-l), wide terminals only
|
||||
side: bool,
|
||||
lens_lines: Vec<String>,
|
||||
@@ -340,6 +345,8 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
probe: false,
|
||||
kbd,
|
||||
stats: None,
|
||||
btw: None,
|
||||
snap: Some(agent.snap()),
|
||||
side: true,
|
||||
lens_lines: vec![],
|
||||
mcp,
|
||||
@@ -490,6 +497,17 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
submit(&mut app, next, &ctx).await;
|
||||
}
|
||||
}
|
||||
Ui::Btw(r) => {
|
||||
if let Some(b) = &mut app.btw {
|
||||
b.a = Some(match r {
|
||||
Ok((t, u)) => {
|
||||
app.st.usage.add(&u);
|
||||
Ok(t)
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ui::Compacted(r) => {
|
||||
app.busy = false;
|
||||
app.t.push(match r {
|
||||
@@ -912,6 +930,19 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
|
||||
if app.sessions.is_some() {
|
||||
return sessions_key(app, k);
|
||||
}
|
||||
if let Some(b) = &mut app.btw {
|
||||
match k.code {
|
||||
KeyCode::Esc | KeyCode::Char('q') | KeyCode::Enter => {
|
||||
if let Some(b) = app.btw.take() {
|
||||
b.close();
|
||||
}
|
||||
}
|
||||
KeyCode::Up => b.scroll = b.scroll.saturating_sub(1),
|
||||
KeyCode::Down => b.scroll = b.scroll.saturating_add(1),
|
||||
_ => {}
|
||||
}
|
||||
return None;
|
||||
}
|
||||
if app.stats.is_some() {
|
||||
if matches!(k.code, KeyCode::Esc | KeyCode::Char('q')) {
|
||||
app.stats = None;
|
||||
@@ -1116,7 +1147,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
let (c, arg) = cmd
|
||||
.split_once(' ')
|
||||
.map_or((cmd, ""), |(a, b)| (a, b.trim()));
|
||||
if app.busy && c != "quit" {
|
||||
if app.busy && !matches!(c, "quit" | "btw") {
|
||||
app.t.push(Item::Error("busy; esc to abort first".into()));
|
||||
return;
|
||||
}
|
||||
@@ -1150,6 +1181,27 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
None => app.t.push(Item::Info("no edits to review".into())),
|
||||
}
|
||||
}
|
||||
"btw" => {
|
||||
if arg.is_empty() {
|
||||
app.t.push(Item::Info("usage: /btw <question>".into()));
|
||||
} else {
|
||||
let Some(snap) = app.snap.as_ref().map(|r| r.borrow().clone()) else {
|
||||
return;
|
||||
};
|
||||
let (q, tx) = (arg.to_string(), tx.clone());
|
||||
let q2 = q.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
let r = snap.btw(&q2).await.map_err(|e| e.to_string());
|
||||
let _ = tx.send(Ui::Btw(r));
|
||||
});
|
||||
app.btw = Some(btw_view::Btw {
|
||||
q,
|
||||
a: None,
|
||||
scroll: 0,
|
||||
task,
|
||||
});
|
||||
}
|
||||
}
|
||||
"copy" => {
|
||||
let last = app.t.items.iter().rev().find_map(|i| match i {
|
||||
Item::Assistant(t) => Some(t.clone()),
|
||||
@@ -1496,6 +1548,9 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
if let Some(s) = &mut app.sessions {
|
||||
s.draw(f);
|
||||
}
|
||||
if let Some(b) = &app.btw {
|
||||
b.draw(f);
|
||||
}
|
||||
if let Some((s, t)) = &app.stats {
|
||||
stats_view::draw(f, s, t);
|
||||
}
|
||||
@@ -2034,6 +2089,8 @@ mod tests {
|
||||
probe: false,
|
||||
kbd: false,
|
||||
stats: None,
|
||||
btw: None,
|
||||
snap: None,
|
||||
side: true,
|
||||
lens_lines: vec![],
|
||||
mcp: vec![],
|
||||
|
||||
Reference in new issue
Block a user