diff --git a/README.md b/README.md index ff7967df..2d96e593 100644 --- a/README.md +++ b/README.md @@ -234,8 +234,8 @@ file in the file list goes to that file, a click on a folder opens or closes it, click on a note selects it and shows its lines. The Send and `Review ▾` buttons in the header are clickable. Drag over lines to select them: a selection is whole lines on the side where the drag started, as in the browser's code review, and the lines are shaded while you drag. Drag past the top or bottom -of the diff to scroll. When you let go, a small toolbar next to the lines offers `💬 comment` -and `✎ suggest` (click it, or press `c` or `s`), and the note is anchored on exactly those +of the diff to scroll. When you let go, a small toolbar next to the lines offers `❓ ask`, +`💬 comment` and `✎ suggest` (click it, or press `a`, `c` or `s`), and the note is anchored on exactly those lines, with their code quoted for the agent. `Esc` clears the selection. Drag works the same in the whole-file view. Shift-click grows a selection to the clicked line, from the line the drag started on. A selection stays inside the hunk it started in, as GitHub's @@ -365,6 +365,28 @@ review started in the browser continues here and the other way round. A mark sto counting once its file changes. Set `PLANNOTATOR_REVIEW_PROGRESS=0` to keep marks for the session only. See [docs/spec-review-progress.md](docs/spec-review-progress.md). +### Ask the agent + +`a` (`ask`) on a selection or a line, or `❓ ask` on the toolbar after a drag, opens the +comment box for a question. Enter puts it in a box under the lines and types it into the +agent Send goes to, with the file, the lines and their code, so the question and its +answer are part of the agent's own conversation. When nothing names an agent, it asks +which one first, as Send does. The answer is read back from the agent's transcript and +shows in the box as it is written, whatever the Notes setting, each message under who +wrote it. A question typed while the agent is busy gets its answer when the agent takes +it. Nothing you ask becomes a note. + +A question on the same lines, or on lines inside them, goes into the same box: Enter or +`a` on the box asks one, and the question box opens at the box's end. `Delete` on the box, +or on one of its lines, removes the box (the agent's chat keeps the questions). + +The answer is read from the agent's own session, found as [`last`](#agent-replies) finds +it from the agent's process: a target that names the process (Rex, hc, or Pi's +`/plannotator-review`) for Claude Code, Copilot or Pi. Anything else would be the newest +session in the folder, a guess, so asking says so instead of sending. Codex is not +supported yet: its transcript reader gives only the agent's replies, so the question cannot +be found there. + ### Pick what to review `plannotator-tui review --pick`, or `p` (`pick-changes`) in a review, opens the change @@ -713,6 +735,7 @@ added in a later release leaves its default key to whatever your file already bo | `review-menu` | `m` | the Review menu | | `pick-target` | `P` | choose the agent Send goes to (see [Choosing the agent](#choosing-the-agent)) | | `pick-changes` | `p` | code review: [pick what to review](#pick-what-to-review); in the picker, back to the review | +| `ask` | `a` | code review: [ask the agent](#ask-the-agent) about the lines; on its box, ask again | | `resend-all` `finish-review` `undo-finish` `archive` | `R` `F` `U` `H` | file and folder review actions | | `toggle-hidden` | `.` | show/hide dot-prefixed entries in the tree | | `edit` `remove` | `e` `x`, `Delete` | the selected note | diff --git a/crates/plannotator-tui-hosts/src/claude/entries.rs b/crates/plannotator-tui-hosts/src/claude/entries.rs index 8fac3655..b65c0353 100644 --- a/crates/plannotator-tui-hosts/src/claude/entries.rs +++ b/crates/plannotator-tui-hosts/src/claude/entries.rs @@ -31,6 +31,9 @@ pub(crate) struct Entry { pub(crate) is_sidechain: bool, pub(crate) hidden: bool, pub(crate) is_compact_summary: bool, + /// A prompt typed while the agent worked: Claude Code takes it into the running turn and + /// records it as a `queued_command` attachment, not as a `user` entry. + pub(crate) queued: bool, } impl Entry { @@ -41,7 +44,14 @@ impl Entry { let string = |key: &str| object.get(key).and_then(Value::as_str).map(str::to_owned); let flag = |key: &str| object.get(key).and_then(Value::as_bool).unwrap_or(false); let message = object.get("message").and_then(Value::as_object); + let queued_prompt = object + .get("attachment") + .filter(|a| a.get("type").and_then(Value::as_str) == Some("queued_command")) + .filter(|a| a.get("commandMode").and_then(Value::as_str) == Some("prompt")) + .and_then(|a| a.get("prompt")) + .and_then(Value::as_str); let texts = match message.and_then(|m| m.get("content")) { + _ if let Some(prompt) = queued_prompt => vec![prompt.to_owned()], Some(Value::String(text)) => vec![text.clone()], Some(Value::Array(blocks)) => blocks .iter() @@ -71,6 +81,7 @@ impl Entry { is_sidechain: flag("isSidechain"), hidden, is_compact_summary: flag("isCompactSummary"), + queued: queued_prompt.is_some(), }) } @@ -83,7 +94,7 @@ impl Entry { } pub(crate) fn is_skipped(&self) -> bool { - SKIPPED_TYPES.contains(&self.kind.as_str()) || self.hidden || self.is_sidechain + (SKIPPED_TYPES.contains(&self.kind.as_str()) && !self.queued) || self.hidden || self.is_sidechain } /// A typed human prompt with text: not meta, not a compact summary, not machinery. @@ -91,7 +102,7 @@ impl Entry { if self.is_skipped() || self.is_meta || self.is_compact_summary - || self.effective_role() != Some("user") + || (self.effective_role() != Some("user") && !self.queued) { return false; } diff --git a/crates/plannotator-tui-hosts/tests/claude.rs b/crates/plannotator-tui-hosts/tests/claude.rs index 3284d67c..32f911a9 100644 --- a/crates/plannotator-tui-hosts/tests/claude.rs +++ b/crates/plannotator-tui-hosts/tests/claude.rs @@ -100,3 +100,26 @@ fn garbage_input_yields_no_messages_rather_than_an_error() { [] as [plannotator_tui_hosts::Message; 0] ); } + +#[test] +fn a_prompt_queued_while_the_agent_worked_is_a_human_prompt_and_other_attachments_are_not() { + let jsonl = [ + r#"{"type":"user","uuid":"u1","parentUuid":null,"message":{"role":"user","content":"first"}}"#, + r#"{"type":"assistant","uuid":"a1","parentUuid":"u1","message":{"role":"assistant","id":"m1","content":[{"type":"text","text":"working"}]}}"#, + r#"{"type":"attachment","uuid":"q1","parentUuid":"a1","attachment":{"type":"queued_command","prompt":"asked meanwhile","commandMode":"prompt"}}"#, + r#"{"type":"attachment","uuid":"f1","parentUuid":"q1","attachment":{"type":"edited_text_file","filename":"a.rs"}}"#, + r#"{"type":"assistant","uuid":"a2","parentUuid":"f1","message":{"role":"assistant","id":"m2","content":[{"type":"text","text":"the answer"}]}}"#, + ] + .join("\n"); + let messages = parse_messages(&jsonl, 5); + let shown: Vec<(Role, &str)> = messages.iter().map(|m| (m.role, m.text.as_str())).collect(); + assert_eq!( + shown, + [ + (Role::Assistant, "the answer"), + (Role::Human, "asked meanwhile"), + (Role::Assistant, "working"), + (Role::Human, "first") + ] + ); +} diff --git a/crates/plannotator-tui/src/delivery.rs b/crates/plannotator-tui/src/delivery.rs index 7bae62e9..3ec00d3d 100644 --- a/crates/plannotator-tui/src/delivery.rs +++ b/crates/plannotator-tui/src/delivery.rs @@ -78,6 +78,10 @@ pub(crate) trait Delivery { fn agent_host(&self) -> Option<&str> { None } + /// The receiving agent's process, when the target knows it: Ask finds its transcript. + fn agent_pid(&self) -> Option { + None + } fn deliver(&self, feedback: &str) -> Result<(), DeliveryError>; /// What the person still has to do after the last `deliver` succeeded, shown with its /// status: the feedback reached the agent but did not finish, e.g. it waits unsubmitted. diff --git a/crates/plannotator-tui/src/export.rs b/crates/plannotator-tui/src/export.rs index 16b55173..5bd7ae01 100644 --- a/crates/plannotator-tui/src/export.rs +++ b/crates/plannotator-tui/src/export.rs @@ -68,7 +68,7 @@ pub(crate) fn feedback(name: &str, entries: &[Entry<'_>]) -> String { } /// A fence longer than any backtick run inside the text, so quoted markdown cannot escape. -fn fenced(text: &str) -> String { +pub(crate) fn fenced(text: &str) -> String { let longest = text.split(|c| c != '`').map(str::len).max().unwrap_or(0); let fence = "`".repeat(longest.max(2) + 1); format!("{fence}\n{text}\n{fence}\n") diff --git a/crates/plannotator-tui/src/hc/agent.rs b/crates/plannotator-tui/src/hc/agent.rs index a6461bda..927122a6 100644 --- a/crates/plannotator-tui/src/hc/agent.rs +++ b/crates/plannotator-tui/src/hc/agent.rs @@ -47,6 +47,10 @@ impl Delivery for HcAgent { self.agent.as_deref() } + fn agent_pid(&self) -> Option { + Some(self.pid) + } + fn describe(&self) -> String { format!("{} in {}", self.agent.as_deref().unwrap_or("agent"), self.terminal) } diff --git a/crates/plannotator-tui/src/keys.rs b/crates/plannotator-tui/src/keys.rs index 97eb40d2..41023fde 100644 --- a/crates/plannotator-tui/src/keys.rs +++ b/crates/plannotator-tui/src/keys.rs @@ -134,6 +134,9 @@ pub(crate) enum Action { /// Pick what the code review shows: uncommitted, unstaged or staged changes, the branch, /// or one of the recent commits. PickChanges, + /// Ask the agent about the selected lines: the question goes to it as Send goes, and its + /// answer shows in a box under the lines. + Ask, } use Action::{ @@ -143,12 +146,12 @@ use Action::{ Reload, Remove, RemoveImage, ResendAll, ReviewMenu, Right, Send, SendAndClose, ToggleHidden, ToggleTree, Top, UndoFinish, Up, Visual, VisualLine, WordBack, WordEnd, WordForward, Yes, }; +use Action::{Ask, DiffSettings, PickChanges, SplitLeft, SplitRight, ToggleWhitespace}; use Action::{ ChangeComment, FileComment, Help, NextFile, NextHunk, NextMatch, NextUnviewed, PreviousFile, PreviousHunk, PreviousMatch, PreviousUnviewed, Search, Suggest, ToggleFiles, ToggleLayout, ToggleViewed, ToggleWrap, WholeBase, WholeFile, }; -use Action::{DiffSettings, PickChanges, SplitLeft, SplitRight, ToggleWhitespace}; use Action::{FilterFiles, FilterKinds, GoToDefinition, HideViewed, JumpBack, JumpForward}; use Action::{NarrowColumn, NarrowFiles, NarrowNotes, ToggleNotes, WidenColumn, WidenFiles, WidenNotes}; @@ -251,6 +254,7 @@ pub(crate) const DIFF: &[Action] = &[ Comment, Suggest, FileComment, + Ask, Down, Up, PageDown, @@ -542,14 +546,16 @@ const DEFAULTS: &[(Action, &[Key])] = &[ (SplitLeft, &[ch('(')]), (SplitRight, &[ch(')')]), (PickChanges, &[ch('p')]), + (Ask, &[ch('a')]), ]; /// Actions added after configs were written: `approve` (live only in a gated review), `copy` /// (on a waiting selection), `word-end`, `visual-line`, the code review's own, the reading -/// column's, `toggle-notes` and search. The newest come first (`pick-changes`, then -/// `toggle-whitespace`, then `diff-settings`, `split-left` and `split-right`, then -/// `copy-lines`), so they yield a key before an older action does. +/// column's, `toggle-notes` and search. The newest come first (`ask`, then +/// `pick-changes`, then `toggle-whitespace`, then `diff-settings`, `split-left` and +/// `split-right`, then `copy-lines`), so they yield a key before an older action does. const LATE: &[Action] = &[ + Ask, PickChanges, ToggleWhitespace, DiffSettings, @@ -798,6 +804,7 @@ impl Action { Self::SplitLeft => "split-left", Self::SplitRight => "split-right", Self::PickChanges => "pick-changes", + Self::Ask => "ask", } } } diff --git a/crates/plannotator-tui/src/keys/tests.rs b/crates/plannotator-tui/src/keys/tests.rs index 4d1f4813..a7c9b597 100644 --- a/crates/plannotator-tui/src/keys/tests.rs +++ b/crates/plannotator-tui/src/keys/tests.rs @@ -368,3 +368,11 @@ fn pick_changes_is_p_in_the_code_review_and_yields_to_an_older_config_that_gave_ assert_eq!(keymap.hint(PickChanges), key, "pick-changes in {config:?}"); } } + +#[test] +fn a_config_that_gave_asks_key_away_still_loads() { + // Written before `ask` existed: `a` is the user's file-comment key, and ask is left unbound. + let keymap = parse("file-comment = [\"a\"]\n").expect("an older config keeps loading"); + assert_eq!(keymap.action(&press(KeyCode::Char('a'), KeyModifiers::NONE), DIFF), Some(FileComment)); + assert_eq!(keymap.hint(Ask), ""); +} diff --git a/crates/plannotator-tui/src/last/mod.rs b/crates/plannotator-tui/src/last/mod.rs index ce0b7380..f244fd8e 100644 --- a/crates/plannotator-tui/src/last/mod.rs +++ b/crates/plannotator-tui/src/last/mod.rs @@ -10,6 +10,9 @@ mod fallback; mod locate; mod readers; mod roots; +mod transcript; + +pub(crate) use transcript::Transcript; use std::io::Read as _; use std::path::PathBuf; diff --git a/crates/plannotator-tui/src/last/transcript.rs b/crates/plannotator-tui/src/last/transcript.rs new file mode 100644 index 00000000..1161e8a0 --- /dev/null +++ b/crates/plannotator-tui/src/last/transcript.rs @@ -0,0 +1,67 @@ +//! An agent's transcript, found the way `last` finds it, then read again as it grows: the +//! code review's Ask reads its answers from there. + +#[cfg(test)] +use std::path::Path; +use std::path::PathBuf; + +use anyhow::{Result, bail}; +use plannotator_tui_hosts::{Host, Message}; + +use super::fallback::Discovery; +use super::{LastOptions, locate, readers}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Transcript { + host: Host, + path: PathBuf, + /// The host's session id, for hosts whose transcript holds several sessions. + session_id: Option, + /// The agent process, for hosts that read their place in the session from it (Pi). + pid: Option, +} + +impl Transcript { + /// The transcript of agent process `pid`, of host `host` when the target names one + /// (`claude`, `pi`, ...), else as detected. Only the agent's own session: the newest one + /// in its folder is a guess, and another session's answer would show as this one's. + pub(crate) fn find(host: Option<&str>, pid: Option) -> Result { + let options = LastOptions { host: host.map(str::to_owned), pid, pick: 1, ..LastOptions::default() }; + let located = locate::locate(&options)?; + if located.discovery != Discovery::Exact { + bail!( + "only a guess ({}) for {}: asking needs the agent's own session, which a target that names its \ + process gives for Claude Code, Copilot and Pi", + located.transcript.display(), + located.host.label() + ); + } + Ok(Self { host: located.host, path: located.transcript, session_id: located.session_id, pid }) + } + + /// A transcript of `host` at `path`, without looking anything up. + #[cfg(test)] + pub(crate) fn at(host: Host, path: &Path) -> Self { + Self { host, path: path.to_path_buf(), session_id: None, pid: None } + } + + pub(crate) fn host(&self) -> Host { + self.host + } + + /// The file that grows as the agent writes: Copilot's session is a folder whose + /// `events.jsonl` it appends to. + pub(crate) fn file(&self) -> PathBuf { + match self.host { + Host::Copilot => self.path.join("events.jsonl"), + _ => self.path.clone(), + } + } + + /// Prompts and replies, newest first, through the `pick`th reply. + pub(crate) fn conversation(&self, pick: usize) -> Result> { + let (_, messages) = + readers::explicit(self.host, &self.path, self.session_id.as_deref(), self.pid, pick)?; + Ok(messages) + } +} diff --git a/crates/plannotator-tui/src/layout.rs b/crates/plannotator-tui/src/layout.rs index 41c58879..500b6fcf 100644 --- a/crates/plannotator-tui/src/layout.rs +++ b/crates/plannotator-tui/src/layout.rs @@ -214,6 +214,12 @@ fn first_code(doc: &Document) -> Vec<(String, String)> { samples } +/// `markdown` styled as the document view styles a block, one `Line` per logical line and +/// unwrapped: an agent's answer in the code review's Ask panel. +pub(crate) fn styled(markdown: &str) -> Text<'static> { + own(tui_markdown::from_str_with_options(markdown, &Options::new(Styles { fences: true }))) +} + pub(crate) fn own(text: Text<'_>) -> Text<'static> { let lines = text .lines diff --git a/crates/plannotator-tui/src/pi/target.rs b/crates/plannotator-tui/src/pi/target.rs index 6b313942..bb150974 100644 --- a/crates/plannotator-tui/src/pi/target.rs +++ b/crates/plannotator-tui/src/pi/target.rs @@ -78,6 +78,10 @@ impl Delivery for PiSession { Some("pi") } + fn agent_pid(&self) -> Option { + Some(self.entry.pid) + } + fn deliver(&self, feedback: &str) -> Result<(), DeliveryError> { self.last.set(None); match super::send(&self.entry, feedback) { diff --git a/crates/plannotator-tui/src/review/ask.rs b/crates/plannotator-tui/src/review/ask.rs new file mode 100644 index 00000000..175b9268 --- /dev/null +++ b/crates/plannotator-tui/src/review/ask.rs @@ -0,0 +1,261 @@ +//! Asking the agent about lines (`ask`): the question goes to it the way Send goes, so it is +//! part of the agent's own conversation, and its answer is read back from the agent's +//! transcript into a box under the lines, the way a note's box sits there (`inline`). More +//! questions on those lines (or on lines inside them) add to that box. Nothing here is saved: +//! the transcript is the record. +//! +//! Finding and reading the transcript take a thread for each question (`watch`), so the +//! screen never waits on them; only the delivery itself, as quick as Send's, runs here once +//! that thread is ready. + +mod boxes; +mod text; +mod watch; + +use anyhow::Result; + +use super::diff::Lines; +use super::{Mode, Screen}; +use crate::keys::Action; +#[cfg(test)] +use crate::last::Transcript; + +/// The first box id an Ask thread takes: far above any note's (`inline` counts those from 1). +const FIRST_ID: u64 = 1 << 40; + +/// The questions of this review, by the lines they are about. +#[derive(Debug, Default)] +pub(super) struct Ask { + threads: Vec, + /// The box id the next thread takes, less [`FIRST_ID`]. Ids are never reused. + made: u64, + /// A question waiting for the agent picker that asking opened. + waiting: Option<(Lines, Turn)>, + /// The transcript questions are read from, instead of finding the agent's: tests. + #[cfg(test)] + transcript: Option, +} + +/// The questions on one set of lines, and their answers: one box. +#[derive(Debug)] +pub(super) struct Thread { + /// The box's id. + pub(super) id: u64, + pub(super) lines: Lines, + turns: Vec, +} + +#[derive(Debug)] +struct Turn { + question: String, + /// Who answers: the agent's host (`claude`, `pi`, ...), else `agent`. + agent: String, + /// What the agent is sent. + prompt: String, + /// Whether it reached the agent. + sent: bool, + /// The answer read so far: the agent's replies since the question, oldest first. + answer: String, + /// Another prompt followed the answer: nothing more comes. + complete: bool, + /// Why the question could not go, or its answer cannot be read. + failed: Option, + /// The thread finding the transcript and then reading the answer, until it is complete. + watch: Option, +} + +impl Ask { + pub(super) fn threads(&self) -> &[Thread] { + &self.threads + } + + /// The thread whose box is `id`. + pub(super) fn thread(&self, id: u64) -> Option<&Thread> { + self.threads.iter().find(|thread| thread.id == id) + } + + /// The thread a question on `lines` goes into, when one is there already. + pub(super) fn box_for(&self, lines: &Lines) -> Option<&Thread> { + self.threads.iter().find(|thread| covers(&thread.lines, lines)) + } + + /// Add `turn` to the thread on `lines` or on lines around them, or start one there. + fn add(&mut self, lines: Lines, turn: Turn) { + if let Some(thread) = self.threads.iter_mut().find(|thread| covers(&thread.lines, &lines)) { + thread.turns.push(turn); + return; + } + let id = FIRST_ID + self.made; + self.made += 1; + self.threads.push(Thread { id, lines, turns: vec![turn] }); + } +} + +impl Screen { + /// Take what the questions' threads have done: send a question once its thread is ready, + /// and show the answers read so far. True when a box changed. + pub(super) fn poll_ask(&mut self) -> bool { + let mut changed = false; + for turn in self.ask.threads.iter_mut().flat_map(|thread| thread.turns.iter_mut()) { + let Some(watch) = &turn.watch else { continue }; + let mut ended = false; + while let Some(update) = watch.next() { + changed = true; + match update { + watch::Update::Ready => { + let target = self.delivery.describe(); + match self.delivery.deliver(&turn.prompt) { + Ok(()) => { + turn.sent = true; + let notice = self + .delivery + .notice() + .map(|n| format!(" \u{b7} {n}")) + .unwrap_or_default(); + self.status = + Some(format!("asked {target}; the answer shows under the lines{notice}")); + } + Err(error) => { + let why = error.status(&target, false, 'a'); + self.status = Some(format!("not asked: {why}")); + turn.failed = Some(why); + ended = true; + } + } + } + watch::Update::Answer { text, complete } => { + turn.answer = text; + turn.complete = complete; + ended |= complete; + } + watch::Update::Failed(why) => { + if !turn.sent { + self.status = Some(format!("not asked: {why}")); + } + turn.failed = Some(why); + ended = true; + } + } + } + if ended { + turn.watch = None; + } + } + changed + } + + /// `ask`: a question about the selection or the cursor's line. + pub(super) fn start_ask(&mut self) -> Result<()> { + let Some(lines) = self.target_lines()? else { + self.status = Some("move the cursor onto a line of code first".into()); + return Ok(()); + }; + self.open_question(lines) + } + + /// Ask what the comment box holds. When Send would ask which agent first, so does this. + pub(super) fn save_question(&mut self, lines: &Lines) { + self.mode = Mode::Browse; + let question = self.compose.value().trim().to_owned(); + if question.is_empty() { + self.status = Some("nothing asked".into()); + return; + } + let prompt = self.question_prompt(lines, &question); + if prompt.len() > super::send::MAX_SEND_BYTES { + self.status = Some(format!( + "the question and its code are {} KiB, over the {} KiB one send carries; select fewer lines", + prompt.len().div_ceil(1024), + super::send::MAX_SEND_BYTES / 1024 + )); + return; + } + let turn = Turn { + question, + agent: String::new(), + prompt, + sent: false, + answer: String::new(), + complete: false, + failed: None, + watch: None, + }; + if let Some(picker) = self.reach.picker_for_send(self.delivery.as_ref(), &self.real_root()) { + self.picker = picker; + self.pick_then = None; + self.ask.waiting = Some((lines.clone(), turn)); + self.mode = Mode::PickTarget; + return; + } + self.start_question(lines.clone(), turn); + } + + /// The agent picker that asking opened closed: ask now if it chose a target. + pub(super) fn after_ask_picker(&mut self, chose: bool) { + if let Some((lines, turn)) = self.ask.waiting.take() { + if chose { + self.start_question(lines, turn); + } else { + self.status = Some("nothing asked".into()); + } + } + } + + /// The question as the agent reads it: where it comes from, the lines and their code, and + /// the question itself. + fn question_prompt(&self, lines: &Lines, question: &str) -> String { + let diff = self.capture.scope.describe(self.capture.commit_subject.as_deref()); + let about = super::draw::lines_label(lines); + let from = format!( + "A question from the code review of {diff} in {}, about `{about}`", + self.root().display() + ); + match self.selected_code(lines) { + Some(code) => format!("{from}:\n\n{}\n{question}", crate::export::fenced(&code)), + None => format!("{from}:\n\n{question}"), + } + } + + /// Put the question in its box and start its thread; it goes to the agent once the thread + /// has noted where the answer will start ([`Self::poll_ask`]). + fn start_question(&mut self, lines: Lines, mut turn: Turn) { + if !self.delivery.is_agent() { + self.status = Some(match self.keys.hint(Action::PickTarget) { + key if key.is_empty() => "asking needs an agent to answer".to_owned(), + key => format!("asking needs an agent to answer; {key} picks one"), + }); + return; + } + let host = self.delivery.agent_host().map(str::to_owned); + turn.agent = host.clone().unwrap_or_else(|| "agent".to_owned()); + let first = turn.prompt.lines().next().unwrap_or_default().to_owned(); + let question = watch::Question { + host, + pid: self.delivery.agent_pid(), + marks: [first, turn.question.clone()], + #[cfg(test)] + transcript: self.ask.transcript.clone(), + }; + match watch::Watch::start(question, self.wake.clone()) { + Ok(watch) => turn.watch = Some(watch), + Err(error) => { + self.status = Some(format!("not asked: could not start reading the answer: {error}")); + return; + } + } + self.ask.add(lines, turn); + self.status = Some(format!("asking {}\u{2026}", self.delivery.describe())); + let _ = self.diff.clear_selection(); + } + + /// Read answers from `transcript` instead of finding the agent's: tests. + #[cfg(test)] + pub(super) fn answer_from(&mut self, transcript: Transcript) { + self.ask.transcript = Some(transcript); + } +} + +/// Whether a box on `on` is about `lines` too: the same file and side, and `lines` inside. +fn covers(on: &Lines, lines: &Lines) -> bool { + on.path == lines.path && on.side == lines.side && on.first <= lines.first && lines.last <= on.last +} diff --git a/crates/plannotator-tui/src/review/ask/boxes.rs b/crates/plannotator-tui/src/review/ask/boxes.rs new file mode 100644 index 00000000..d4212590 --- /dev/null +++ b/crates/plannotator-tui/src/review/ask/boxes.rs @@ -0,0 +1,104 @@ +//! An Ask box under its lines: asking again there (the question box opens at its end, scrolled +//! into view), removing it, and what its border says. + +use anyhow::Result; +use ratatui::crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers, MouseEvent, MouseEventKind}; + +use super::Thread; +use crate::keys::{self, Action}; +use crate::review::diff::Lines; +use crate::review::{Draft, Mode, Screen}; +use crate::ui::compose::Compose; + +impl Screen { + /// The question box for `lines`. When they have a box already the question goes into, it + /// opens at that box's end: the diff scrolls, as the wheel does, until the end and room + /// for the question box under it show, which a long answer pushes below the pane. + pub(super) fn open_question(&mut self, lines: Lines) -> Result<()> { + if let Some(id) = self.ask.box_for(&lines).map(|thread| thread.id) { + let pane = self.geometry.diff; + if let Some(area) = self.diff.box_areas().iter().find(|area| area.id == id) { + let cut = area.height.saturating_sub(area.clipped_top + area.area.height); + let below = pane.bottom().saturating_sub(area.area.bottom()); + let rows = (cut + crate::review::compose_at::ROOM).saturating_sub(below); + let wheel = MouseEvent { + kind: MouseEventKind::ScrollDown, + column: pane.x + 1, + row: pane.y + 1, + modifiers: KeyModifiers::NONE, + }; + // The viewer scrolls three rows a wheel step. + for _ in 0..rows.div_ceil(3) { + self.diff.handle_event(Event::Mouse(wheel))?; + } + } + } + self.compose = Compose::default(); + self.mode = Mode::Compose(Draft::Ask(lines)); + Ok(()) + } + + /// A key on an Ask box: Enter or `ask` asks again about its lines, the remove key removes + /// the box. With the cursor on a box's lines, where the click that focused the pane may + /// have put it, the remove key removes that box too. True when the key was the box's. + pub(in crate::review) fn ask_box_key(&mut self, key: &KeyEvent) -> bool { + let diff = self.keys.action(key, keys::DIFF); + let remove = diff.is_none() && self.keys.is(Action::Remove, key); + if let Some(thread) = self.cursor_thread() { + let (id, lines) = (thread.id, thread.lines.clone()); + if matches!(diff, Some(Action::Confirm | Action::Ask)) { + if let Err(error) = self.open_question(lines) { + self.status = Some(format!("{error:#}")); + } + } else if remove { + self.remove_thread(id); + } else { + return false; + } + return true; + } + let on_lines = self.diff.cursor().ok().flatten().filter(|_| remove && self.whole.is_none()); + match on_lines.and_then(|lines| self.ask.box_for(&lines).map(|thread| thread.id)) { + Some(id) => { + self.remove_thread(id); + true + } + None => false, + } + } + + fn remove_thread(&mut self, id: u64) { + self.ask.threads.retain(|thread| thread.id != id); + self.status = Some("questions removed from the diff; the agent's chat keeps them".into()); + } + + /// What an Ask box's border says it does, each with its key: `ask again (⏎ Enter) · + /// remove (⌦ Delete)`, or the keys the config binds. + pub(in crate::review) fn ask_box_hint(&self) -> String { + let bound = |action, code| self.keys.is(action, &KeyEvent::from(code)); + let again = if bound(Action::Confirm, KeyCode::Enter) { + "\u{23ce} Enter".to_owned() + } else { + self.keys.hint(Action::Ask) + }; + let remove = if bound(Action::Remove, KeyCode::Delete) { + "\u{2326} Delete".to_owned() + } else { + self.keys.hint_besides(Action::Remove, keys::DIFF) + }; + [("ask again", again), ("remove", remove)] + .into_iter() + .filter(|(_, key)| !key.is_empty()) + .map(|(what, key)| format!("{what} ({key})")) + .collect::>() + .join(" \u{b7} ") + } + + /// The thread whose box the cursor is on, in the diff (not the whole file). + fn cursor_thread(&self) -> Option<&Thread> { + if self.whole.is_some() { + return None; + } + self.ask.thread(self.diff.cursor_box()?) + } +} diff --git a/crates/plannotator-tui/src/review/ask/text.rs b/crates/plannotator-tui/src/review/ask/text.rs new file mode 100644 index 00000000..b0ca0c4f --- /dev/null +++ b/crates/plannotator-tui/src/review/ask/text.rs @@ -0,0 +1,73 @@ +//! What an Ask box says: its lines in the title, then each question and its answer, each +//! under who wrote it, with a rule between one question and the next. + +use std::hash::{Hash as _, Hasher as _}; + +use plannotator_tui_review::Side; +use ratatui::style::{Style, Stylize as _}; +use ratatui::text::{Line, Span}; + +use super::Thread; +use crate::review::diff::Lines; +use crate::theme::palette; + +impl Thread { + /// `ask · L9`, `ask · L9–12`, `ask · L7 old`, as a note's box names its lines. + pub(in crate::review) fn label(&self) -> String { + let Lines { side, first, last, .. } = &self.lines; + let lines = if first == last { format!("L{first}") } else { format!("L{first}\u{2013}{last}") }; + let old = if *side == Side::Old { " old" } else { "" }; + format!("ask \u{b7} {lines}{old}") + } + + /// A number that changes whenever what the box shows does. + pub(in crate::review) fn revision(&self) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + for turn in &self.turns { + (&turn.question, &turn.agent, turn.sent, turn.complete, &turn.answer, &turn.failed) + .hash(&mut hasher); + } + hasher.finish() + } + + /// The box's text at `width` columns: each question, then its answer as Markdown, all of it. + pub(in crate::review) fn body(&self, width: usize) -> Vec> { + let speaker = + |who: &str, colour| Line::from(Span::styled(who.to_owned(), Style::new().fg(colour).bold())); + let mut rows = Vec::new(); + for (index, turn) in self.turns.iter().enumerate() { + if index > 0 { + let rule = "\u{254c}".repeat(width); + rows.push(Line::from(Span::styled(rule, Style::new().fg(palette().idle_fg)))); + } + rows.push(speaker("You", palette().accent)); + for line in turn.question.lines() { + rows.extend(wrapped(&Line::from(line.to_owned()), width)); + } + rows.push(Line::default()); + rows.push(speaker(&turn.agent, palette().heading)); + for line in crate::layout::styled(&turn.answer).lines { + rows.extend(wrapped(&line, width)); + } + let state = match (&turn.failed, turn.sent, turn.complete) { + (Some(why), true, _) => { + Some(Span::styled(format!("cannot read the answer: {why}"), palette().delete)) + } + (Some(why), false, _) => Some(Span::styled(format!("not sent: {why}"), palette().delete)), + (None, _, _) if !turn.answer.is_empty() => None, + (None, false, _) => Some(Span::raw("sending\u{2026}").italic()), + (None, true, false) => Some(Span::raw("waiting for the answer\u{2026}").italic()), + (None, true, true) => Some(Span::raw("no answer").italic()), + }; + if let Some(state) = state { + rows.extend(wrapped(&Line::from(state), width)); + } + } + rows + } +} + +fn wrapped(line: &Line<'_>, width: usize) -> impl Iterator> { + let chars: usize = line.spans.iter().map(|span| span.content.chars().count()).sum(); + crate::wrap::wrap_line(line, &vec![None; chars], width).into_iter().map(|row| row.line) +} diff --git a/crates/plannotator-tui/src/review/ask/watch.rs b/crates/plannotator-tui/src/review/ask/watch.rs new file mode 100644 index 00000000..b9e434ea --- /dev/null +++ b/crates/plannotator-tui/src/review/ask/watch.rs @@ -0,0 +1,205 @@ +//! The work one Ask question waits on, on a thread of its own so the screen never does: find +//! the agent's transcript, note the newest prompt in it, say the question can go, then read +//! the transcript again each time it grows until the answer is complete. +//! +//! The question is the first prompt after the noted one that holds the question's first line +//! and its text, so a prompt typed into the agent meanwhile, or another question still +//! waiting in its queue, is not taken for it. The answer is the replies after it up to the +//! next prompt. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{self, Receiver, SyncSender}; +use std::time::{Duration, SystemTime}; + +use plannotator_tui_hosts::{Host, Message, Role}; + +use crate::last::Transcript; + +/// How often the transcript's size and time are looked at; it is read only when they change. +const POLL: Duration = Duration::from_millis(300); + +/// How many replies a read of the transcript goes back through: an answer can be many +/// messages between tool calls, and the noted prompt must still be in reach. +const PICK: usize = 400; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum Update { + /// The transcript was found and its newest prompt noted: the question can go now. + Ready, + /// The answer as far as the transcript has it; `complete` once another prompt followed. + Answer { text: String, complete: bool }, + /// The question cannot be asked, or its answer cannot be read; nothing more comes. + Failed(String), +} + +/// One question, as its thread looks for it. +#[derive(Debug)] +pub(super) struct Question { + /// The agent's host and process, as the target names them. + pub(super) host: Option, + pub(super) pid: Option, + /// What the prompt holds that tells it apart: its first line (the file and lines) and the + /// question as typed. + pub(super) marks: [String; 2], + /// The transcript to read instead of finding the agent's: tests. + #[cfg(test)] + pub(super) transcript: Option, +} + +#[derive(Debug)] +pub(super) struct Watch { + updates: Receiver, + stop: Arc, +} + +impl Watch { + /// Start the thread for `question`, which sends each step and pokes `wake`. + pub(super) fn start(question: Question, wake: SyncSender<()>) -> std::io::Result { + let (sender, updates) = mpsc::channel(); + let stop = Arc::new(AtomicBool::new(false)); + let stopped = Arc::clone(&stop); + std::thread::Builder::new().name("review-ask".into()).spawn(move || { + let send = |update: Update| { + let sent = sender.send(update).is_ok(); + let _ = wake.try_send(()); + sent + }; + run(&question, &send, &stopped); + })?; + Ok(Self { updates, stop }) + } + + pub(super) fn next(&self) -> Option { + self.updates.try_recv().ok() + } +} + +impl Drop for Watch { + /// The thread ends at its next look, with the review or the question. + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + } +} + +fn run(question: &Question, send: &impl Fn(Update) -> bool, stop: &AtomicBool) { + let noted = transcript(question).and_then(|transcript| { + // Codex's reader gives only the replies of the newest turn: no prompt to find. + if transcript.host() == Host::Codex { + return Err( + "asking is not supported for codex yet: its transcript reader gives only the agent's replies" + .to_owned(), + ); + } + let messages = transcript + .conversation(PICK) + .map_err(|error| format!("cannot read the agent's transcript: {error:#}"))?; + Ok((newest_prompt(&messages), transcript)) + }); + match noted { + Ok((after, transcript)) if send(Update::Ready) => { + follow(&transcript, after.as_deref(), question, send, stop); + } + Ok(_) => {} + Err(why) => { + send(Update::Failed(why)); + } + } +} + +fn transcript(question: &Question) -> Result { + #[cfg(test)] + if let Some(transcript) = &question.transcript { + return Ok(transcript.clone()); + } + Transcript::find(question.host.as_deref(), question.pid) + .map_err(|error| format!("cannot find the agent's session: {error:#}")) +} + +/// Read `transcript` each time it changes for the answer to `question` after prompt `after`. +/// A read that fails is tried again at the next change: the file may be mid-write. +fn follow( + transcript: &Transcript, + after: Option<&str>, + question: &Question, + send: &impl Fn(Update) -> bool, + stop: &AtomicBool, +) { + let marks = question.marks.each_ref().map(String::as_str); + let file = transcript.file(); + let mut seen: Option<(u64, Option)> = None; + let mut last: Option = None; + while !stop.load(Ordering::Relaxed) { + let now = std::fs::metadata(&file).ok().map(|meta| (meta.len(), meta.modified().ok())); + if now.is_none() || now != seen { + seen = now; + // shortcut: the whole transcript is read again on each change (a few MB, a few + // hundred ms on this thread), not just what was added; read only the tail if a + // large transcript makes answers lag. + let update = match transcript.conversation(PICK).map(|messages| answer(&messages, after, &marks)) + { + Ok(Found::Answer { text, complete }) => Some(Update::Answer { text, complete }), + Ok(Found::Lost) => { + Some(Update::Failed("the question is out of reach in the transcript".to_owned())) + } + Ok(Found::Waiting) | Err(_) => None, + }; + if let Some(update) = update + && last.as_ref() != Some(&update) + { + let ends = matches!(update, Update::Answer { complete: true, .. } | Update::Failed(_)); + if !send(update.clone()) || ends { + return; + } + last = Some(update); + } + } + std::thread::sleep(POLL); + } +} + +/// The id of the newest prompt in `newest_first`, if it has one. +fn newest_prompt(newest_first: &[Message]) -> Option { + newest_first.iter().find(|message| message.role == Role::Human).map(|message| message.id.clone()) +} + +/// What the transcript says of a question. +#[derive(Debug, PartialEq, Eq)] +enum Found { + /// The question is not in it yet. + Waiting, + /// The replies to it so far, oldest first; `complete` once another prompt followed. + Answer { text: String, complete: bool }, + /// The noted prompt is out of reach, so the question cannot be told from older ones. + Lost, +} + +/// The answer, in `newest_first`, to the first prompt after prompt `after` (with `None`, after +/// none) that holds every one of `marks`. +fn answer(newest_first: &[Message], after: Option<&str>, marks: &[&str]) -> Found { + let newer = match after { + Some(id) => match newest_first.iter().position(|message| message.id == id) { + Some(at) => newest_first.get(..at).unwrap_or_default(), + None => return Found::Lost, + }, + None => newest_first, + }; + // Newest first, so the last match in `newer` is the oldest: the question. + let holds = |message: &Message| { + message.role == Role::Human && marks.iter().all(|mark| message.text.contains(mark)) + }; + let Some(asked) = newer.iter().rposition(holds) else { return Found::Waiting }; + let since = newer.get(..asked).unwrap_or_default(); + let next = since.iter().rposition(|message| message.role == Role::Human); + let replies = next.map_or(since, |next| since.get(next + 1..).unwrap_or_default()); + let text: Vec<&str> = replies + .iter() + .rev() + .filter(|message| message.role == Role::Assistant) + .map(|message| message.text.as_str()) + .collect(); + Found::Answer { text: text.join("\n\n"), complete: next.is_some() } +} + +#[cfg(test)] +mod tests; diff --git a/crates/plannotator-tui/src/review/ask/watch/tests.rs b/crates/plannotator-tui/src/review/ask/watch/tests.rs new file mode 100644 index 00000000..5818722c --- /dev/null +++ b/crates/plannotator-tui/src/review/ask/watch/tests.rs @@ -0,0 +1,74 @@ +use plannotator_tui_hosts::{Host, Message, Role}; + +use super::{Found, answer}; +use crate::last::Transcript; + +fn prompt(id: &str, text: &str) -> Message { + Message { id: id.to_owned(), role: Role::Human, text: text.to_owned(), at: None } +} + +fn reply(id: &str, text: &str) -> Message { + Message { id: id.to_owned(), role: Role::Assistant, text: text.to_owned(), at: None } +} + +fn said(text: &str, complete: bool) -> Found { + Found::Answer { text: text.to_owned(), complete } +} + +const MARKS: [&str; 2] = ["about `a.rs:9`", "why?"]; + +#[test] +fn the_answer_is_every_reply_after_the_question_oldest_first() { + let newest_first = [ + reply("a3", "and more"), + reply("a2", "first part"), + prompt("q", "about `a.rs:9`: why?"), + reply("a1", "older"), + prompt("mark", "earlier"), + ]; + assert_eq!(answer(&newest_first, Some("mark"), &MARKS), said("first part\n\nand more", false)); +} + +#[test] +fn the_next_prompt_ends_the_answer() { + let newest_first = [ + reply("a3", "to the next"), + prompt("next", "else"), + reply("a2", "answer"), + prompt("q", "about `a.rs:9`: why?"), + ]; + assert_eq!(answer(&newest_first, None, &MARKS), said("answer", true)); +} + +#[test] +fn a_prompt_typed_meanwhile_or_another_waiting_question_is_not_taken_for_the_question() { + let newest_first = [ + reply("a2", "the answer"), + prompt("q", "about `a.rs:9`: why?"), + reply("a1", "to the other"), + prompt("other", "about `a.rs:3`: what?"), + prompt("mark", "earlier"), + ]; + assert_eq!(answer(&newest_first, Some("mark"), &MARKS), said("the answer", false)); +} + +#[test] +fn nothing_answers_until_the_question_is_in_the_transcript() { + let newest_first = + [reply("a1", "about something else"), prompt("other", "a prompt"), prompt("mark", "earlier")]; + assert_eq!(answer(&newest_first, Some("mark"), &MARKS), Found::Waiting); +} + +#[test] +fn a_noted_prompt_out_of_reach_loses_the_question() { + let newest_first = [reply("a2", "answer"), prompt("q", "about `a.rs:9`: why?")]; + assert_eq!(answer(&newest_first, Some("gone"), &MARKS), Found::Lost); +} + +#[test] +fn a_copilot_session_is_watched_by_the_file_it_appends_to() { + let dir = std::path::Path::new("/sessions/abc"); + assert_eq!(Transcript::at(Host::Copilot, dir).file(), dir.join("events.jsonl")); + let file = std::path::Path::new("/projects/x/1.jsonl"); + assert_eq!(Transcript::at(Host::ClaudeCode, file).file(), file); +} diff --git a/crates/plannotator-tui/src/review/compose_at.rs b/crates/plannotator-tui/src/review/compose_at.rs index 2271ecf4..bcb3f029 100644 --- a/crates/plannotator-tui/src/review/compose_at.rs +++ b/crates/plannotator-tui/src/review/compose_at.rs @@ -10,6 +10,9 @@ //! - The whole change (`M`, editing its note), or lines no longer on screen: centred. //! - Editing a note whose box the diff shows (`inline`): over the box, as wide as it. Notes' //! boxes under the lines of a new one count as theirs: the box opens below them. +//! - A question (`ask`): right under the end of the box of questions it goes into, as +//! drawn (`ask` scrolls that end into view first); with no such box, as for lines, below +//! the boxes under them whatever the Notes setting, as Ask boxes always show. //! //! The box only draws over the diff: opening, typing in and closing it never move the view //! or the cursor. It grows with its text on the side it opened on and, out of room there, @@ -30,7 +33,7 @@ pub(super) const MIN_SIDE_WIDTH: u16 = 48; /// One row of text and its borders. const MIN_HEIGHT: u16 = 3; /// The room a side needs for the box to open there: three rows of text to grow into. -const ROOM: u16 = 5; +pub(super) const ROOM: u16 = 5; /// Which side of its rows the box took. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -57,6 +60,8 @@ enum Anchor { Centre, /// A note's box in the diff, as last drawn. Over(Rect), + /// The end of the Ask box a question goes into, as drawn: right under it. + Under(Rect), } impl Screen { @@ -66,7 +71,7 @@ impl Screen { let anchor = self.anchor(draft); // Where the viewer drew the line between a split diff's sides, wherever it was dragged. let middle = self.active_diff().filter(|diff| diff.split()).and_then(super::diff::Diff::split_line); - let boxes = self.notes_inline() && self.whole.is_none(); + let boxes = self.whole.is_none() && (self.notes_inline() || matches!(draft, Draft::Ask(_))); let (x, width) = match &anchor { // Where the notes' boxes are drawn, the box lines up with them. Anchor::Lines(lines) @@ -81,10 +86,15 @@ impl Screen { columns } Anchor::File(_) | Anchor::Centre => (pane.x, pane.width.min(MAX_WIDTH)), - Anchor::Over(rect) => (rect.x, rect.width), + Anchor::Over(rect) | Anchor::Under(rect) => (rect.x, rect.width), }; let wrap = usize::from(width.saturating_sub(compose::CHROME)); let wanted = compose::height(&self.compose, wrap).min(pane.height); + if let Anchor::Under(rect) = anchor { + // Under the box, else (no room left under it) over its last rows. + let y = rect.bottom().min(pane.bottom().saturating_sub(wanted)); + return Rect { x, y, width, height: wanted.min(pane.bottom() - y) }; + } if let Anchor::Over(rect) = anchor { // From the box's top down, else as low as it fits. let y = rect.y.min(pane.bottom().saturating_sub(wanted.max(ROOM.min(pane.height)))); @@ -107,7 +117,7 @@ impl Screen { // No heading on screen: at the top of the pane. None => return Rect { x, y: pane.y, width, height: wanted }, }, - Anchor::Centre | Anchor::Over(_) => None, + Anchor::Centre | Anchor::Over(_) | Anchor::Under(_) => None, }; let Some((first, last, top)) = rows else { let x = pane.x + (pane.width - width) / 2; @@ -128,6 +138,17 @@ impl Screen { Draft::Comment(lines) | Draft::Suggestion(lines) | Draft::Outside(lines, _) => { Anchor::Lines(lines.clone()) } + Draft::Ask(lines) => { + let thread = self.ask.box_for(lines); + let end = thread + .and_then(|thread| self.diff.box_areas().iter().find(|area| area.id == thread.id)) + .filter(|area| area.height == area.clipped_top + area.area.height) + .map(|area| Rect { width: area.area.width.min(MAX_WIDTH), ..area.area }); + match end { + Some(rect) => Anchor::Under(rect), + None => Anchor::Lines(thread.map_or(lines, |thread| &thread.lines).clone()), + } + } Draft::File(path) => Anchor::File(path.clone()), Draft::Change => Anchor::Centre, Draft::Edit(id) if let Some(rect) = self.drawn_box(id) => Anchor::Over(rect), diff --git a/crates/plannotator-tui/src/review/drafts.rs b/crates/plannotator-tui/src/review/drafts.rs index f6b926ca..4eed9e28 100644 --- a/crates/plannotator-tui/src/review/drafts.rs +++ b/crates/plannotator-tui/src/review/drafts.rs @@ -12,7 +12,7 @@ impl Screen { /// The lines a note made now would cover: the selection, else the cursor's line, else /// with the cursor on a note's box the lines it hangs under, so the new note's box /// stacks under it. - fn target_lines(&self) -> Result> { + pub(super) fn target_lines(&self) -> Result> { if let Some(lines) = self.diff.selection() { return Ok(Some(lines)); } @@ -139,6 +139,8 @@ impl Screen { text, &key, )), + // Asked when the box is saved (`ask::save_question`), never kept as a note. + Draft::Ask(_) => return Ok(()), Draft::Edit(id) => { let changed = self.store.edit(id, |note| { let field = match note.kind { diff --git a/crates/plannotator-tui/src/review/draw.rs b/crates/plannotator-tui/src/review/draw.rs index ffafe8e3..10390a9e 100644 --- a/crates/plannotator-tui/src/review/draw.rs +++ b/crates/plannotator-tui/src/review/draw.rs @@ -174,6 +174,7 @@ impl Screen { Draft::Change => "comment on the whole change".to_owned(), Draft::Outside(lines, _) => format!("comment on {} (not in the diff)", lines_label(lines)), Draft::Edit(_) => "edit".to_owned(), + Draft::Ask(lines) => format!("ask about {}", lines_label(lines)), }; let title = self.compose.heading(&verb, self.shift_enter, &self.keys); let (text, first) = compose::draw(frame, rect, &self.compose, &title); @@ -184,7 +185,7 @@ impl Screen { } /// `src/a.rs:12`, `src/a.rs:12-14`, or `src/a.rs:7 old` for lines of the old file. -fn lines_label(lines: &Lines) -> String { +pub(super) fn lines_label(lines: &Lines) -> String { let Lines { path, side, first, last } = lines; let at = if first == last { format!("{path}:{first}") } else { format!("{path}:{first}-{last}") }; if *side == Side::Old { format!("{at} old") } else { at } diff --git a/crates/plannotator-tui/src/review/inline.rs b/crates/plannotator-tui/src/review/inline.rs index 964569ed..a0fb6f0a 100644 --- a/crates/plannotator-tui/src/review/inline.rs +++ b/crates/plannotator-tui/src/review/inline.rs @@ -15,7 +15,9 @@ //! gives that key to something else (`x` marks the file viewed there). //! - `inline` starts with the panel away whatever notes there are; `z` opens it for the //! session. `both` keeps the panel's own rule (`notes_rail`). -//! - `panel`, the default, sets no rows at all: the diff draws as it always has. +//! - `panel`, the default, sets no rows for notes: the diff draws as it always has. +//! - Questions asked with `ask` get a box under their lines whatever the setting, one for +//! each set of lines (`ask`). //! //! A box is laid out once per note revision and width ([`card::Card`]), and only the boxes //! on screen are drawn. @@ -80,9 +82,28 @@ impl Inline { /// The card for `note` at `width`, laid out again only when either changed. fn card(&mut self, id: u64, note: &CodeAnnotation, width: u16) -> &card::Card { - let card = self.cards.entry(id).or_insert_with(|| card::Card::of(note, width)); - if !card.is_for(note, width) { - *card = card::Card::of(note, width); + self.cached(id, |card| card.is_for(note, width), || card::Card::of(note, width)) + } + + /// The card for Ask `thread` at `width`, laid out again only when either changed. + fn thread_card(&mut self, thread: &super::ask::Thread, width: u16) -> &card::Card { + self.cached( + thread.id, + |card| card.is_for_thread(thread, width), + || card::Card::of_thread(thread, width), + ) + } + + /// Box `id`'s card, made again by `make` when `current` says the one kept is not. + fn cached( + &mut self, + id: u64, + current: impl FnOnce(&card::Card) -> bool, + make: impl Fn() -> card::Card, + ) -> &card::Card { + let card = self.cards.entry(id).or_insert_with(&make); + if !current(card) { + *card = make(); } card } @@ -144,10 +165,10 @@ impl Screen { let mut slots = Vec::new(); let mut skipped = 0; let small = self.geometry.diff.height < MIN_PANE_ROWS; + let area = self.geometry.diff; + let split = self.diff.split(); + let mut widths: HashMap<&str, Widths> = HashMap::new(); if self.settings.now.notes != Notes::Panel && !small { - let area = self.geometry.diff; - let split = self.diff.split(); - let mut widths: HashMap<&str, Widths> = HashMap::new(); let mut order: Vec = (0..notes.len()).collect(); order.sort_by_key(|&i| (notes.get(i).map_or(0, |note| note.created_at), i)); for note in order.into_iter().filter_map(|i| notes.get(i)) { @@ -174,6 +195,18 @@ impl Screen { slots.push(Slot { id, path, line, over, height }); } } + for thread in self.ask.threads().iter().filter(|_| !small) { + let Lines { path, side, last, .. } = &thread.lines; + let widths = *widths.entry(path).or_insert_with(|| { + [Some(Side::Old), Some(Side::New), None].map(|over| self.diff.box_width(area, path, over)) + }); + let over = over(Place::Line(*side, *last), split, widths); + let width = width(widths, over).unwrap_or(0).min(MAX_WIDTH); + if width >= MIN_WIDTH { + let height = self.inline.thread_card(thread, width).height(); + slots.push(Slot { id: thread.id, path, line: Some((*side, *last)), over, height }); + } + } self.inline.skipped = skipped; self.inline.small = small; match self.diff.set_boxes(&slots) { diff --git a/crates/plannotator-tui/src/review/inline/card.rs b/crates/plannotator-tui/src/review/inline/card.rs index 3423dc66..221eb581 100644 --- a/crates/plannotator-tui/src/review/inline/card.rs +++ b/crates/plannotator-tui/src/review/inline/card.rs @@ -11,6 +11,7 @@ use plannotator_tui_review::{CodeAnnotation, NoteScope, NoteType, Side}; use ratatui::style::Style; use ratatui::text::Line; +use crate::review::ask::Thread; use crate::theme::palette; use crate::ui::compose::TAB_WIDTH; use crate::wrap::wrap_line; @@ -68,6 +69,21 @@ impl Card { self.made_for == (revision(note), width) } + /// An Ask thread's box at `width`: every question and all of each answer, which is what + /// the box is for, so no [`BODY_LINES`] limit. + pub(super) fn of_thread(thread: &Thread, width: u16) -> Self { + let mut body = thread.body(usize::from(width.saturating_sub(CHROME)).max(1)); + if body.is_empty() { + body.push(Line::default()); + } + Self { made_for: (thread.revision(), width), label: thread.label(), author: None, body, more: false } + } + + /// Whether this is `thread`'s card at `width`, as [`Self::of_thread`] would make it now. + pub(super) fn is_for_thread(&self, thread: &Thread, width: u16) -> bool { + self.made_for == (thread.revision(), width) + } + /// The rows the box takes: its text and two borders. pub(super) fn height(&self) -> u16 { self.body.len() as u16 + 2 diff --git a/crates/plannotator-tui/src/review/inline/paint.rs b/crates/plannotator-tui/src/review/inline/paint.rs index f61cd7b7..36f3438e 100644 --- a/crates/plannotator-tui/src/review/inline/paint.rs +++ b/crates/plannotator-tui/src/review/inline/paint.rs @@ -26,10 +26,13 @@ impl Screen { /// Draw the boxes on screen in the last frame of the diff, and note where for the mouse /// and the comment box. pub(in crate::review) fn draw_boxes(&mut self, frame: &mut Frame) { - if self.whole.is_some() || !self.notes_inline() { + // The rows kept are only for notes while they show inline, and for Ask threads always. + if self.whole.is_some() { return; } let more = self.keys.labelled(Action::Confirm, "for more").unwrap_or_else(|| "more".to_owned()); + let more = format!("\u{2026} {more}"); + let again = self.ask_box_hint(); let areas = self.diff.box_areas().to_vec(); let notes = self.store.annotations(); // The note in the comment box: its box keeps its rows, blank, under the comment box, @@ -39,6 +42,21 @@ impl Screen { _ => None, }; for area in areas { + if let Some(thread) = self.ask.thread(area.id) { + let width = area.area.width.min(MAX_WIDTH); + let rect = Rect { width, ..area.area }; + let card = self.inline.thread_card(thread, width); + paint( + frame.buffer_mut(), + rect, + area.clipped_top, + card, + Look { sent: false, cursor: area.cursor }, + Some(&again), + ); + self.geometry.boxes.push((rect, area.id)); + continue; + } let Some(note) = self.inline.notes.get(&area.id).and_then(|id| notes.iter().find(|n| n.id == *id)) else { @@ -51,7 +69,8 @@ impl Screen { } else { let look = Look { sent: !self.store.is_pending(note), cursor: area.cursor }; let card = self.inline.card(area.id, note, width); - paint(frame.buffer_mut(), rect, area.clipped_top, card, look, &more); + let bottom = card.more.then_some(more.as_str()); + paint(frame.buffer_mut(), rect, area.clipped_top, card, look, bottom); } self.geometry.boxes.push((rect, area.id)); } @@ -71,8 +90,9 @@ fn blank(buf: &mut Buffer, rect: Rect) { } } -/// The box for `card`, its rows from `clipped_top` on, into `rect` of `buf`. -fn paint(buf: &mut Buffer, rect: Rect, clipped_top: u16, card: &Card, look: Look, more: &str) { +/// The box for `card`, its rows from `clipped_top` on, into `rect` of `buf`, with `bottom` on +/// its lower border: what a note cut short says, or the keys of an Ask box. +fn paint(buf: &mut Buffer, rect: Rect, clipped_top: u16, card: &Card, look: Look, bottom: Option<&str>) { let whole = Rect::new(0, 0, rect.width, card.height()); let mut scratch = Buffer::empty(whole); let colour = if look.sent { Color::DarkGray } else { palette().comment }; @@ -90,8 +110,8 @@ fn paint(buf: &mut Buffer, rect: Rect, clipped_top: u16, card: &Card, look: Look .border_type(BorderType::Rounded) .border_style(border) .title(Line::from(title)); - if card.more { - block = block.title_bottom(Span::styled(format!(" \u{2026} {more} "), Style::new().fg(colour))); + if let Some(bottom) = bottom { + block = block.title_bottom(Span::styled(format!(" {bottom} "), Style::new().fg(colour))); } let inner = block.inner(whole); block.render(whole, &mut scratch); diff --git a/crates/plannotator-tui/src/review/input.rs b/crates/plannotator-tui/src/review/input.rs index 5fece190..dd7a0682 100644 --- a/crates/plannotator-tui/src/review/input.rs +++ b/crates/plannotator-tui/src/review/input.rs @@ -9,7 +9,7 @@ use ratatui::layout::{Position, Rect}; use super::diff::Diff; use super::whole::Version; -use super::{Focus, Mode, Screen}; +use super::{Draft, Focus, Mode, Screen}; use crate::keys::{self, Action}; use crate::ui::agent_picker::{AgentPicker, Picked, PickerKey}; use crate::ui::compose::{self, ComposeAction}; @@ -131,6 +131,7 @@ impl Screen { drawn => drawn, }; match self.compose.key(&self.keys, key, wrap) { + ComposeAction::Save if let Draft::Ask(lines) = &draft => self.save_question(lines), ComposeAction::Save => self.save_draft(&draft)?, ComposeAction::Cancel => self.mode = Mode::Browse, ComposeAction::Edited => {} @@ -166,6 +167,7 @@ impl Screen { if self.pick_then.take().is_some() { self.status = Some("nothing sent".into()); } + self.after_ask_picker(false); } PickerKey::Chose(row) => { self.mode = Mode::Browse; @@ -173,11 +175,15 @@ impl Screen { match self.picker.choose(row, &mut self.delivery, &mut self.start_delivery) { Picked::Moved(status) => self.status = Some(status), Picked::Copy => {} - Picked::Nothing => return Ok(()), + Picked::Nothing => { + self.after_ask_picker(false); + return Ok(()); + } } if let Some(then) = then { self.send_picked(then); } + self.after_ask_picker(true); } } Ok(()) @@ -276,7 +282,7 @@ impl Screen { } fn diff_key(&mut self, key: KeyEvent) -> Result<()> { - if self.box_key(&key)? { + if self.ask_box_key(&key) || self.box_key(&key)? { return Ok(()); } match self.keys.action(&key, keys::DIFF) { @@ -323,6 +329,7 @@ impl Screen { Action::Back => Command::Back, Action::Visual | Action::VisualLine => return self.diff.begin_or_end_selection(), Action::Comment => return self.start_comment(), + Action::Ask => return self.start_ask(), Action::Suggest => return self.start_suggestion(), Action::FileComment => { self.start_file_comment(); diff --git a/crates/plannotator-tui/src/review/mod.rs b/crates/plannotator-tui/src/review/mod.rs index b61d8a19..c1189d9e 100644 --- a/crates/plannotator-tui/src/review/mod.rs +++ b/crates/plannotator-tui/src/review/mod.rs @@ -29,6 +29,7 @@ //! person's `gh` login into their clone or a cache repository ([`capture`]), and sends to the //! agent as any review does. Nothing is posted to GitHub. +mod ask; pub(crate) mod cli; mod compose_at; mod diff; @@ -92,6 +93,8 @@ enum Draft { Outside(Lines, String), /// A new body for an existing note, by id. Edit(String), + /// A question for the agent about lines. It is asked, never saved as a note. + Ask(Lines), } #[derive(Debug, Clone, PartialEq, Eq)] @@ -238,6 +241,8 @@ pub(crate) struct Screen { help_room: std::cell::Cell, /// `pick-changes` was pressed: the event loop opens the change picker over the review. pick_request: bool, + /// The questions asked with `ask`, by the lines they are about, and their answers so far. + ask: ask::Ask, /// The other reviews this session showed, for the notes left unsent on them. switched: pick::shown::Switched, quit: bool, @@ -331,6 +336,7 @@ impl Screen { help_scroll: 0, help_room: std::cell::Cell::new(0), pick_request: false, + ask: ask::Ask::default(), switched: pick::shown::Switched::default(), quit: false, }; @@ -451,6 +457,7 @@ impl Screen { changed = true; } changed |= self.reach.poll(); + changed |= self.poll_ask(); changed |= self.step_at_edge(Instant::now())?; let whole_draw = self.whole.as_ref().is_some_and(whole::Whole::needs_draw); Ok(changed || self.diff.needs_draw() || whole_draw) diff --git a/crates/plannotator-tui/src/review/mouse.rs b/crates/plannotator-tui/src/review/mouse.rs index da6f562d..ab9e589f 100644 --- a/crates/plannotator-tui/src/review/mouse.rs +++ b/crates/plannotator-tui/src/review/mouse.rs @@ -125,8 +125,11 @@ pub(super) enum OnRelease { } /// The toolbar's buttons: (glyph, label, action). -const BUTTONS: [(&str, &str, Action); 2] = - [("\u{1f4ac}", "comment", Action::Comment), ("\u{270e}", "suggest", Action::Suggest)]; +const BUTTONS: [(&str, &str, Action); 3] = [ + ("\u{2753}", "ask", Action::Ask), + ("\u{1f4ac}", "comment", Action::Comment), + ("\u{270e}", "suggest", Action::Suggest), +]; /// The drag's gutter mark. Bold tells it from a note's mark when the rows are tinted. pub(super) fn drag_mark() -> Style { @@ -324,6 +327,8 @@ impl Screen { let labels: Vec<(String, Action)> = BUTTONS .iter() .filter(|(_, _, action)| *action != Action::Suggest || lines.side == Side::New) + // Ask is the diff's: the whole-file view has no boxes to answer in. + .filter(|(_, _, action)| *action != Action::Ask || self.whole.is_none()) .map(|(glyph, label, action)| match self.keys.hint(*action) { key if key.is_empty() => (format!(" {glyph} {label} "), *action), key => (format!(" {glyph} {label} ({key}) "), *action), @@ -348,7 +353,7 @@ impl Screen { for (label, action) in labels { let w = label.width() as u16; let chips = crate::ui::chips::chips(); - let fg = if action == Action::Comment { chips.review_comment() } else { chips.review_suggest }; + let fg = if action == Action::Suggest { chips.review_suggest } else { chips.review_comment() }; let style = Style::new().fg(fg).bg(palette().toolbar_bg).add_modifier(Modifier::BOLD); buf.set_span(x, y, &Span::styled(label, style), w); self.geometry.toolbar.push((Rect { x, y, width: w, height: 1 }, action)); diff --git a/crates/plannotator-tui/src/review/overlays.rs b/crates/plannotator-tui/src/review/overlays.rs index 2b8bb276..e7038879 100644 --- a/crates/plannotator-tui/src/review/overlays.rs +++ b/crates/plannotator-tui/src/review/overlays.rs @@ -118,6 +118,7 @@ impl Screen { (key(&[Action::Comment]), "comment on the selection or line"), (key(&[Action::Suggest]), "suggest code for new lines"), (key(&[Action::FileComment]), "comment on the file"), + (key(&[Action::Ask]), "ask the agent about the lines; the answer shows under them"), ] .into_iter() .chain(self.box_help()) diff --git a/crates/plannotator-tui/src/review/tests/ask_flow.rs b/crates/plannotator-tui/src/review/tests/ask_flow.rs new file mode 100644 index 00000000..f172d7ae --- /dev/null +++ b/crates/plannotator-tui/src/review/tests/ask_flow.rs @@ -0,0 +1,303 @@ +//! Asking the agent about lines: the question goes to it as Send goes, the answer is read +//! from its transcript into a box under the lines, and nothing becomes a note. + +use std::io::Write as _; + +use ratatui::crossterm::event::KeyCode; +use serde_json::json; + +use super::*; +use plannotator_tui_hosts::Host; + +use crate::last::Transcript; +use crate::review::Mode; + +fn user(uuid: &str, parent: Option<&str>, text: &str) -> String { + json!({"type": "user", "uuid": uuid, "parentUuid": parent, "message": {"role": "user", "content": text}}) + .to_string() +} + +fn assistant(uuid: &str, parent: Option<&str>, text: &str) -> String { + let content = json!([{"type": "text", "text": text}]); + let message = json!({"role": "assistant", "id": format!("m-{uuid}"), "content": content}); + json!({"type": "assistant", "uuid": uuid, "parentUuid": parent, "message": message}).to_string() +} + +fn append(path: &Path, lines: &[String]) { + let mut file = std::fs::OpenOptions::new().create(true).append(true).open(path).expect("transcript"); + for line in lines { + writeln!(file, "{line}").expect("append"); + } +} + +/// Poll and draw, as the event loop does, until `done` holds for the rows drawn. +fn wait(screen: &mut Screen, what: &str, done: impl Fn(&[String]) -> bool) -> Vec { + let started = Instant::now(); + loop { + screen.tick().expect("tick"); + let rows = frame(screen, 120, 40); + if done(&rows) { + return rows; + } + assert!(started.elapsed() < Duration::from_secs(10), "never: {what}\n{}", rows.join("\n")); + std::thread::sleep(Duration::from_millis(20)); + } +} + +fn wait_for(screen: &mut Screen, text: &str) -> Vec { + wait(screen, text, |rows| rows.iter().any(|row| row.contains(text))) +} + +/// The review on the fixture, answering from a transcript holding one earlier exchange. +fn asking(tag: &str) -> (Fixture, Screen, PathBuf) { + let fixture = Fixture::new(tag); + let transcript = fixture.dir.join("transcript.jsonl"); + append(&transcript, &[user("p1", None, "earlier"), assistant("r1", Some("p1"), "an earlier reply")]); + let mut screen = fixture.open(); + screen.answer_from(Transcript::at(Host::ClaudeCode, &transcript)); + (fixture, screen, transcript) +} + +/// Ask `question` on the lines the cursor or the selection is on, and wait until it is sent. +fn ask(fixture: &Fixture, screen: &mut Screen, question: &str) -> String { + let before = fixture.sent().len(); + keys(screen, "a"); + type_and_save(screen, question); + wait(screen, "the question sent", |_| fixture.sent().len() > before); + fixture.sent().last().cloned().expect("sent") +} + +#[test] +fn a_question_reaches_the_agent_with_its_lines_and_their_code() { + let (fixture, mut screen, _transcript) = asking("ask-prompt"); + at(&mut screen, 9); + keys(&mut screen, "a"); + row_with(&frame(&mut screen, 120, 40), "ask about app.py:9"); + press(&mut screen, KeyCode::Esc); + let question = ask(&fixture, &mut screen, "why a local?"); + assert!(question.starts_with("A question from the code review of Uncommitted changes in "), "{question}"); + assert!(question.contains(", about `app.py:9`:\n\n```\n total = a + b\n```\n"), "{question}"); + assert!(question.ends_with("\nwhy a local?"), "{question}"); + assert_eq!(screen.mode, Mode::Browse); + assert!(screen.store.annotations().is_empty(), "a question is never a note"); +} + +#[test] +fn its_answer_shows_in_a_box_under_the_lines_under_who_wrote_what() { + let (fixture, mut screen, transcript) = asking("ask-answer"); + at(&mut screen, 9); + let question = ask(&fixture, &mut screen, "why a local?"); + let rows = frame(&mut screen, 120, 40); + row_with(&rows, "ask \u{b7} L9"); + row_with(&rows, "waiting for the answer"); + row_with(&rows, "ask again (\u{23ce} Enter) \u{b7} remove (\u{2326} Delete)"); + append( + &transcript, + &[user("p2", Some("r1"), &question), assistant("r2", Some("p2"), "It names the **sum**.")], + ); + let rows = wait_for(&mut screen, "It names the sum."); + assert!(!rows.iter().any(|row| row.contains("an earlier reply")), "only the answer to this question"); + let row = |needle: &str| rows.iter().position(|row| row.contains(needle)).unwrap_or(usize::MAX); + assert!( + row("total = a + b") < row("You") + && row("You") < row("why a local?") + && row("why a local?") < row("claude") + && row("claude") < row("It names the sum.") + && row("It names the sum.") < row("return total"), + "under line 9, each message under who wrote it:\n{}", + rows.join("\n") + ); +} + +#[test] +fn asking_again_from_the_box_goes_into_it_with_the_question_box_at_its_end() { + let (fixture, mut screen, transcript) = asking("ask-again"); + at(&mut screen, 9); + let question = ask(&fixture, &mut screen, "why a local?"); + append( + &transcript, + &[user("p2", Some("r1"), &question), assistant("r2", Some("p2"), "It names the sum.")], + ); + wait_for(&mut screen, "It names the sum."); + keys(&mut screen, "j"); + press(&mut screen, KeyCode::Enter); + let rows = frame(&mut screen, 120, 40); + let end = rows.iter().position(|row| row.contains("ask again")).expect("the answer box's end"); + let asking = rows.iter().position(|row| row.contains("ask about app.py:9")).expect("the question box"); + assert_eq!(asking, end + 1, "the question box opens under the answer box:\n{}", rows.join("\n")); + type_and_save(&mut screen, "and if b is negative?"); + wait(&mut screen, "the follow-up sent", |_| fixture.sent().len() == 2); + let rows = frame(&mut screen, 120, 40); + assert_eq!(rows.iter().filter(|row| row.contains("ask \u{b7} L9")).count(), 1, "one box for the lines"); + row_with(&rows, "and if b is negative?"); +} + +#[test] +fn the_remove_key_removes_a_box_from_the_box_or_from_its_lines() { + let (fixture, mut screen, _transcript) = asking("ask-remove"); + let gone = |screen: &mut Screen| !frame(screen, 120, 40).iter().any(|row| row.contains("ask \u{b7} L9")); + at(&mut screen, 9); + ask(&fixture, &mut screen, "why?"); + keys(&mut screen, "j"); + press(&mut screen, KeyCode::Delete); + assert!(gone(&mut screen), "removed from the box"); + at(&mut screen, 9); + keys(&mut screen, "vjv"); + ask(&fixture, &mut screen, "and these?"); + at(&mut screen, 10); + press(&mut screen, KeyCode::Delete); + assert!(gone(&mut screen), "removed from one of its lines"); +} + +#[test] +fn two_questions_waiting_at_once_each_get_their_own_answer() { + let (fixture, mut screen, transcript) = asking("ask-two"); + at(&mut screen, 9); + let first = ask(&fixture, &mut screen, "why a local?"); + at(&mut screen, 14); + let second = ask(&fixture, &mut screen, "what if argv is empty?"); + // The agent was busy: both questions arrive later, in its own order. + append( + &transcript, + &[ + user("p2", Some("r1"), &second), + assistant("r2", Some("p2"), "Then it raises IndexError."), + user("p3", Some("r2"), &first), + assistant("r3", Some("p3"), "It names the sum."), + ], + ); + let rows = wait(&mut screen, "both answers", |rows| { + rows.iter().any(|row| row.contains("It names the sum.")) + && rows.iter().any(|row| row.contains("IndexError")) + }); + let row = |needle: &str| rows.iter().position(|row| row.contains(needle)).unwrap_or(usize::MAX); + assert!( + row("It names the sum.") < row("greet(sys.argv[1])") && row("greet(sys.argv[1])") < row("IndexError"), + "each answer in its own box:\n{}", + rows.join("\n") + ); +} + +#[test] +fn an_answer_that_ends_without_any_text_says_so() { + let (fixture, mut screen, transcript) = asking("ask-empty"); + at(&mut screen, 9); + let question = ask(&fixture, &mut screen, "why?"); + append(&transcript, &[user("p2", Some("r1"), &question), user("p3", Some("p2"), "something else")]); + wait_for(&mut screen, "no answer"); +} + +#[test] +fn a_question_after_an_answer_longer_than_the_pane_opens_at_its_end() { + let (fixture, mut screen, transcript) = asking("ask-long"); + at(&mut screen, 9); + let question = ask(&fixture, &mut screen, "explain it all"); + let long = (1..=40).map(|n| format!("answer line {n}")).collect::>().join("\n\n"); + append(&transcript, &[user("p2", Some("r1"), &question), assistant("r2", Some("p2"), &long)]); + wait_for(&mut screen, "answer line 1"); + at(&mut screen, 9); + keys(&mut screen, "j"); + press(&mut screen, KeyCode::Enter); + let rows = frame(&mut screen, 120, 40); + let end = rows.iter().position(|row| row.contains("ask again")).expect("the answer box's end on screen"); + let asking = rows.iter().position(|row| row.contains("ask about app.py:9")).expect("the question box"); + assert_eq!(asking, end + 1, "the question box opens under the answer's end:\n{}", rows.join("\n")); +} + +#[test] +fn a_question_on_lines_inside_a_box_goes_into_that_box() { + let (fixture, mut screen, _transcript) = asking("ask-inside"); + at(&mut screen, 9); + keys(&mut screen, "vjv"); + ask(&fixture, &mut screen, "what do these two do?"); + row_with(&frame(&mut screen, 120, 40), "ask \u{b7} L9\u{2013}10"); + at(&mut screen, 10); + let question = ask(&fixture, &mut screen, "and this one?"); + assert!(question.contains("about `app.py:10`"), "the question names its own line: {question}"); + let rows = frame(&mut screen, 120, 40); + assert!(!rows.iter().any(|row| row.contains("ask \u{b7} L10 ")), "no second box:\n{}", rows.join("\n")); + row_with(&rows, "and this one?"); +} + +#[test] +fn a_question_with_no_transcript_to_answer_from_is_not_sent_and_says_why() { + let fixture = Fixture::new("ask-no-transcript"); + let mut screen = fixture.open(); + screen.answer_from(Transcript::at(Host::ClaudeCode, &fixture.dir.join("missing.jsonl"))); + at(&mut screen, 9); + keys(&mut screen, "a"); + type_and_save(&mut screen, "why?"); + wait_for(&mut screen, "not sent: cannot read the agent's"); + assert!(fixture.sent().is_empty(), "no question without a way to read its answer"); + assert!( + screen.status.as_deref().is_some_and(|status| status.starts_with("not asked: ")), + "{:?}", + screen.status + ); +} + +/// A pi transcript line: a message of `role` with `text`, after entry `parent`. +fn pi(id: &str, parent: Option<&str>, role: &str, text: &str) -> String { + let message = json!({"role": role, "content": [{"type": "text", "text": text}]}); + json!({"type": "message", "id": id, "parentId": parent, "message": message}).to_string() +} + +#[test] +fn a_pi_agent_answers_in_the_box_too() { + let fixture = Fixture::new("ask-pi"); + let transcript = fixture.dir.join("pi.jsonl"); + let header = json!({"type": "session", "version": 3, "id": "01a04968-90e4-745a-a8d3-6903d935f391", "cwd": "/work"}); + append( + &transcript, + &[ + header.to_string(), + pi("p1", None, "user", "earlier"), + pi("r1", Some("p1"), "assistant", "an earlier reply"), + ], + ); + let mut screen = fixture.open(); + screen.answer_from(Transcript::at(Host::Pi, &transcript)); + at(&mut screen, 9); + let question = ask(&fixture, &mut screen, "why a local?"); + append( + &transcript, + &[ + pi("p2", Some("r1"), "user", &question), + pi("r2", Some("p2"), "assistant", "Pi says it names the sum."), + ], + ); + let rows = wait_for(&mut screen, "Pi says it names the sum."); + assert!(!rows.iter().any(|row| row.contains("an earlier reply")), "only the answer to this question"); +} + +#[test] +fn a_codex_agent_is_not_asked_as_its_transcript_has_no_prompts_to_find_the_question_by() { + let fixture = Fixture::new("ask-codex"); + let transcript = fixture.dir.join("rollout.jsonl"); + append(&transcript, &[]); + let mut screen = fixture.open(); + screen.answer_from(Transcript::at(Host::Codex, &transcript)); + at(&mut screen, 9); + keys(&mut screen, "a"); + type_and_save(&mut screen, "why?"); + wait_for(&mut screen, "not supported for codex"); + assert!(fixture.sent().is_empty(), "nothing sent to an agent whose answer cannot be read"); +} + +#[test] +fn an_ask_box_and_a_notes_box_on_one_line_both_show() { + let fixture = Fixture::new("ask-beside-note"); + fixture.write_config("[review]\nlayout = \"unified\"\nnotes = \"inline\"\n"); + let transcript = fixture.dir.join("transcript.jsonl"); + append(&transcript, &[user("p1", None, "earlier"), assistant("r1", Some("p1"), "an earlier reply")]); + let mut screen = fixture.open_configured(); + screen.answer_from(Transcript::at(Host::ClaudeCode, &transcript)); + at(&mut screen, 9); + keys(&mut screen, "c"); + type_and_save(&mut screen, "name the total"); + at(&mut screen, 9); + ask(&fixture, &mut screen, "why a local?"); + let rows = frame(&mut screen, 120, 40); + row_with(&rows, "name the total"); + row_with(&rows, "ask \u{b7} L9"); +} diff --git a/crates/plannotator-tui/src/review/tests/mod.rs b/crates/plannotator-tui/src/review/tests/mod.rs index 7a13fc0e..759226f6 100644 --- a/crates/plannotator-tui/src/review/tests/mod.rs +++ b/crates/plannotator-tui/src/review/tests/mod.rs @@ -2,6 +2,7 @@ //! diff viewer, a `TestBackend` frame, and a stand-in for the agent (the one external seam). #![allow(clippy::expect_used, clippy::indexing_slicing, clippy::panic, reason = "tests assert by panicking")] +mod ask_flow; mod auto_layout; #[cfg(unix)] mod big; diff --git a/crates/plannotator-tui/src/review/tests/mouse_flow.rs b/crates/plannotator-tui/src/review/tests/mouse_flow.rs index f10a8f68..a7df66c4 100644 --- a/crates/plannotator-tui/src/review/tests/mouse_flow.rs +++ b/crates/plannotator-tui/src/review/tests/mouse_flow.rs @@ -270,6 +270,19 @@ fn the_toolbar_after_a_drag_comments_on_the_selection() { assert_eq!(screen.mode, Mode::Compose(Draft::Comment(lines(Side::New, 8, 10)))); } +#[test] +fn the_toolbar_after_a_drag_asks_the_agent_about_the_selection() { + let fixture = Fixture::new("mouse-toolbar-ask"); + let mut screen = fixture.open(); + let from = locate(&mut screen, "def add(a, b):", true); + let to = locate(&mut screen, "return total", true); + drag(&mut screen, from, to); + release(&mut screen, to); + let ask = locate(&mut screen, "ask (a)", false); + mouse(&mut screen, MouseEventKind::Down(MouseButton::Left), ask); + assert_eq!(screen.mode, Mode::Compose(Draft::Ask(lines(Side::New, 8, 10)))); +} + #[test] fn a_key_takes_the_toolbar_away_and_keeps_the_selection() { let fixture = Fixture::new("mouse-toolbar-key"); diff --git a/crates/plannotator-tui/src/rex/agent.rs b/crates/plannotator-tui/src/rex/agent.rs index ee079a0f..055d1ca1 100644 --- a/crates/plannotator-tui/src/rex/agent.rs +++ b/crates/plannotator-tui/src/rex/agent.rs @@ -131,6 +131,10 @@ impl Delivery for RexAgent { self.agent.as_deref() } + fn agent_pid(&self) -> Option { + Some(self.pid) + } + fn describe(&self) -> String { let block = short_id(&self.block); let who = self.agent.as_deref().unwrap_or("agent");