From 2661089479d3f352165683ef1f477a76b2d53647 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Fri, 20 Nov 2026 00:07:42 -0500 Subject: [PATCH 01/16] feat(review): post the notes to the pull request on GitHub (ctrl+g), after a summary --- README.md | 48 +- crates/plannotator-tui-review/src/capture.rs | 5 + crates/plannotator-tui-review/src/github.rs | 3 +- crates/plannotator-tui-review/src/lib.rs | 6 +- crates/plannotator-tui-review/src/post.rs | 425 ++++++++++++++++++ .../plannotator-tui-review/src/post/submit.rs | 221 +++++++++ .../plannotator-tui-review/src/post/tests.rs | 261 +++++++++++ crates/plannotator-tui-review/src/store.rs | 64 ++- .../plannotator-tui-review/src/store/tests.rs | 30 ++ crates/plannotator-tui/src/keys.rs | 28 +- crates/plannotator-tui/src/review/draw.rs | 4 + crates/plannotator-tui/src/review/input.rs | 12 +- crates/plannotator-tui/src/review/mod.rs | 9 +- crates/plannotator-tui/src/review/overlays.rs | 7 +- crates/plannotator-tui/src/review/post.rs | 267 +++++++++++ .../plannotator-tui/src/review/post_view.rs | 119 +++++ crates/plannotator-tui/src/review/rail.rs | 3 + .../plannotator-tui/src/review/tests/mod.rs | 2 + .../src/review/tests/post_flow.rs | 306 +++++++++++++ .../src/review/tests/pull_flow.rs | 22 +- 20 files changed, 1815 insertions(+), 27 deletions(-) create mode 100644 crates/plannotator-tui-review/src/post.rs create mode 100644 crates/plannotator-tui-review/src/post/submit.rs create mode 100644 crates/plannotator-tui-review/src/post/tests.rs create mode 100644 crates/plannotator-tui/src/review/post.rs create mode 100644 crates/plannotator-tui/src/review/post_view.rs create mode 100644 crates/plannotator-tui/src/review/tests/post_flow.rs diff --git a/README.md b/README.md index 7906a13d..f77a1875 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ dimmed. The keys also work without opening the menu. | file/folder review | `E` send new · `m` review menu (`R` resend all · `F` finish review · `U` undo · `H` archive) | | folder review | `Ctrl+P` open a file by name, including in collapsed folders: type, `↑`/`↓` or click, `Enter`, `Esc` | | tree | `j`/`k`; `Enter` open; `.` show/hide dot-prefixed entries (`.agents/`, `.github/`); `E` sends new notes across all reviewed files, including collapsed folders | -| code review | `v` select, `v` again to end; `c` comment; `s` suggest code; `C` note on the file; `M` note on the whole change; `o`/`O` whole file now/before; `d` go to definition, `ctrl+o`/`ctrl+i` back/forward; `]`/`[` hunk; `n`/`N` file; `x` viewed; `ctrl+n` next not viewed; `h`/`l` old/new side; `u` split/unified; `w` wrap; `f` files; `z` hide or show the notes; `r` read the diff again (the footer says when it changed on disk); `?` keys | +| code review | `v` select, `v` again to end; `c` comment; `s` suggest code; `C` note on the file; `M` note on the whole change; `ctrl+g` post the notes to the pull request on GitHub, after a summary (pull request reviews); `o`/`O` whole file now/before; `d` go to definition, `ctrl+o`/`ctrl+i` back/forward; `]`/`[` hunk; `n`/`N` file; `x` viewed; `ctrl+n` next not viewed; `h`/`l` old/new side; `u` split/unified; `w` wrap; `f` files; `z` hide or show the notes; `r` read the diff again (the footer says when it changed on disk); `?` keys | These are the defaults; every key can be rebound under `[keys]` (see [Keys](#keys)). @@ -217,8 +217,9 @@ Closed, it stays closed, as in a document review. `E` sends the new notes, `S` sends them and closes, and `P` picks the agent to send to. Sends go to the same place a document review's do (Herdr pane, Rex, Pi or the clipboard, or the agent you choose when nothing named one; see [Choosing the agent](#choosing-the-agent)), and are kept in the feedback archive. `q` asks first when notes are unsent. -`m` opens the Review menu: `M` comment on the whole change, `R` resend all, `F` finish -review, `U` undo. +`m` opens the Review menu: `M` comment on the whole change, `ctrl+g` post to GitHub (in a +pull request review, see [Posting to GitHub](#posting-to-github)), `R` resend all, `F` +finish review, `U` undo. `o` shows the whole file under the cursor as it is now, scrolled to the same line; `O` shows it as it was before the change (the base), at the matching old line. The header says @@ -277,7 +278,45 @@ The header shows `PR #123 · title · base ← head`. `r` looks the pull request fetches new pushes; notes follow their lines as they do for local changes. Notes are saved once per pull request, whichever clone you open it from. Send goes to the agent as for any review, with the browser's pull request header (`# PR Review: owner/repo#123`, the title, -the branches and the link). Nothing is posted to GitHub. +the branches and the link). + +#### Posting to GitHub + +`ctrl+g`, or **Post to GitHub…** in the Review menu (`m`), posts your notes to the pull +request as one GitHub review, as well as (not instead of) sending them to the agent. It is +offered only in a pull request review; anywhere else it says why not. + +A summary always comes first, and nothing leaves your computer until you press `Enter` +there (`Esc` cancels; no setting skips it). It shows the repository and PR number, how many +notes become inline comments, how many go into the review's body and why, what is skipped, +and the verdict: **Comment** by default, or **Approve** or **Request changes** if you pick +one with `h`/`l`, as the browser app offers them. Notes are laid out the way the browser app +posts a review: + +- Line notes become inline comments: `RIGHT` for new lines, `LEFT` for old (removed) + lines, a range as `start_line` to `line`. A suggestion becomes a `suggestion` block that + GitHub can apply. +- A note on the whole change, a note on a file (`**path:** text`), and a line note that is + outdated or whose lines the diff no longer shows (quoted with the code it was made on) go + in the review body. The browser posts file notes as file-level threads, which takes + several requests; here they go in the body, in the browser's own fallback shape, so a post + is always one request. +- A note outside the diff (made in the whole file) is never inline: it goes at the end of + the body under **Comments outside the diff**, with its code quoted and a link to the lines. + +The review is created with one `gh api` request (`POST +repos/OWNER/REPO/pulls/N/reviews`) under your `gh` login; no token passes through +plannotator-tui. GitHub takes all of it or none of it. Comments are anchored to the commit +you reviewed (the one the diff was fetched at). If the pull request has new commits since, +the summary says so, and `r` reloads it first if you want to review those. A post that +fails posts nothing and says why in the summary: `gh` not logged in, no permission, the +reviewed commit force-pushed away, GitHub's rate limit, no connection, or a comment GitHub +would not place (the summary lists where each inline comment was). + +After a post, the footer shows the review's link and the rail marks the notes **posted**, +a state of its own beside **sent**: a note can be both. Posted marks are saved with the +notes, and a later post carries only notes that are new or edited since. An edited note is +posted again as a new comment (the summary says how many); the earlier one stays on GitHub. A Pi session can leave notes on the diff too (see [Pi](#pi)). Notes are saved with the other annotations, one record per repository and scope. Code review is not available on @@ -484,6 +523,7 @@ screen show your keys. `plannotator-tui config` prints every action with its key | `yes` `no` | `y` `n`, `Y` `N` | the send-before-quitting and clear-all questions | | `suggest` `file-comment` | `s` `C` | code review: suggest code for the lines; a note on the whole file | | `change-comment` | `M` | code review: a note on the whole change | +| `post-to-github` | `ctrl+g` | code review of a pull request: post the notes to it as one GitHub review, after a summary | | `next-hunk` `previous-hunk` `next-file` `previous-file` | `]` `[` `n` `N` | code review: move by hunk or file | | `toggle-layout` `toggle-wrap` `toggle-files` | `u` `w` `f` | code review: split or unified view; wrap; the file list | | `toggle-viewed` `next-unviewed` `previous-unviewed` | `x` `ctrl+n`, none | code review: mark the file viewed; the next or previous file not viewed | diff --git a/crates/plannotator-tui-review/src/capture.rs b/crates/plannotator-tui-review/src/capture.rs index c41dfc5d..146fdbb4 100644 --- a/crates/plannotator-tui-review/src/capture.rs +++ b/crates/plannotator-tui-review/src/capture.rs @@ -170,6 +170,11 @@ impl Repo { &self.root } + /// The `gh` a pull request review was opened with; `None` for any other review. + pub fn gh(&self) -> Option<&Gh> { + self.pull.as_ref().map(|p| &p.gh) + } + /// The folder the review belongs to, for the agent and Pi: the work tree, or for a pull /// request fetched into the cache, the folder the review was opened in. pub fn workdir(&self) -> &Path { diff --git a/crates/plannotator-tui-review/src/github.rs b/crates/plannotator-tui-review/src/github.rs index f4791ae7..dac50fb9 100644 --- a/crates/plannotator-tui-review/src/github.rs +++ b/crates/plannotator-tui-review/src/github.rs @@ -1,7 +1,8 @@ //! Pull requests on GitHub: reading a PR link or number, asking `gh` (the person's own login) //! for the PR's branches and commits, and finding the clone a PR belongs to. //! -//! Nothing here writes to GitHub: the only `gh` call is `gh pr view`. +//! Nothing here writes to GitHub: the only `gh` call is `gh pr view`. Posting a review is +//! [`crate::post`]'s, and only after the person confirms it. use std::ffi::OsString; use std::path::Path; diff --git a/crates/plannotator-tui-review/src/lib.rs b/crates/plannotator-tui-review/src/lib.rs index 788b0f5c..20f5fa2e 100644 --- a/crates/plannotator-tui-review/src/lib.rs +++ b/crates/plannotator-tui-review/src/lib.rs @@ -8,6 +8,8 @@ //! - [`codenav`]: definition search on either side of a diff (`git grep`), ranked as the //! browser ranks it, and the identifiers on a line. //! - [`github`]: PR links and numbers, and `gh pr view` (read-only). +//! - [`post`]: a pull request review on GitHub built from the notes, as the browser builds +//! one, and posted in one `gh api` request (the only write to GitHub). //! - [`patch`]: reading a unified patch: files, the lines each side shows, anchors. //! - [`annotation`]: a note, in the browser's `CodeAnnotation` shape. //! - [`resolve`]: pure functions that place a note against the current files. @@ -26,6 +28,7 @@ pub mod export; mod git; pub mod github; pub mod patch; +pub mod post; pub mod progress; pub mod resolve; pub mod scope; @@ -44,11 +47,12 @@ pub use export::{ }; pub use github::{Gh, PrRepo, PrSpec, PrView}; pub use patch::{FilePatch, FileStatus}; +pub use post::{Event, Plan, PostError, PostedReview, Posting, ReviewRequest}; pub use progress::Progress; pub use resolve::{Current, Resolution, apply, resolve}; pub use scope::Scope; pub use stamp::DiskStamp; -pub use store::{Delivered, Record, ReviewStore, project_for, review_dir}; +pub use store::{Delivered, Posted, Record, ReviewStore, project_for, review_dir}; /// sha256 over `parts` in order, as lowercase hex, first `chars` characters. fn sha256_hex(parts: &[&[u8]], chars: usize) -> String { diff --git a/crates/plannotator-tui-review/src/post.rs b/crates/plannotator-tui-review/src/post.rs new file mode 100644 index 00000000..4420df67 --- /dev/null +++ b/crates/plannotator-tui-review/src/post.rs @@ -0,0 +1,425 @@ +//! A pull request review on GitHub, built from a review's notes the way the browser app +//! builds one (`packages/review-editor/components/ReviewSubmissionDialog.tsx`), and posted in +//! one `gh api` request ([`crate::Gh::post_review`]), so GitHub takes all of it or none. +//! +//! - **Inline comments**: line notes GitHub can anchor at the reviewed commit. `side` is +//! `LEFT` for old-side lines and `RIGHT` for new ones; `line` is the last line, and +//! `start_line`/`start_side` (the same side) are added only for a range. The body is the +//! note's text (after a browser note's conventional-comment prefix) and, for a suggestion, +//! a `` ```suggestion `` block. +//! - **The review body**, in note order: whole-change notes as plain paragraphs, file notes +//! as `**path:** text`, and line notes GitHub cannot take inline (outdated, or their lines +//! are no longer in the diff) as `**path (L5-L9, new):**` with the code they were made on. +//! Notes on lines outside the diff (`outsideDiff`) are never inline: they close the body +//! under **Comments outside the diff**, each with its code quoted and a link to the lines +//! at the reviewed commit. A body that would be empty beside inline comments is +//! `See inline comments.`, as GitHub requires one for a comment review. +//! +//! One difference from the browser: on GitHub it posts file notes as file-level threads +//! (a pending review, a GraphQL call per file, then a submit), which is not atomic. Here +//! they go in the body in the browser's own fallback shape (`**path:** text`), so a post is +//! always one request. +//! +//! Notes a post already carried are left out unless edited since; an edited one is posted +//! again as a new comment ([`Posting::Edited`]). + +use std::collections::BTreeMap; +use std::fmt::Write as _; + +use serde::Serialize; +use serde_json::Value; + +use crate::annotation::{CodeAnnotation, NoteScope, Side, Status}; +use crate::export::OUTDATED_ANNOTATION_LABEL; +use crate::github::PrRepo; +use crate::patch::FilePatch; + +mod submit; + +pub use submit::{PostError, PostedReview}; + +/// The browser's `OUTSIDE_DIFF_BODY_HEADING`. +pub const OUTSIDE_DIFF_BODY_HEADING: &str = "Comments outside the diff"; + +/// The browser's `OUTSIDE_DIFF_QUOTE_MAX_LINES`: code quoted per note outside the diff. +pub const OUTSIDE_DIFF_QUOTE_MAX_LINES: usize = 40; + +/// The browser's `COMMENT_BODY_PLACEHOLDER`. +pub const BODY_PLACEHOLDER: &str = "See inline comments."; + +/// GitHub refuses a review body longer than this many characters. +pub const MAX_BODY_CHARS: usize = 65_536; + +/// The review's verdict. The browser defaults to a comment and offers the other two as +/// explicit choices. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum Event { + #[default] + Comment, + Approve, + RequestChanges, +} + +impl Event { + pub const ALL: [Self; 3] = [Self::Comment, Self::Approve, Self::RequestChanges]; + + pub fn label(self) -> &'static str { + match self { + Self::Comment => "Comment", + Self::Approve => "Approve", + Self::RequestChanges => "Request changes", + } + } +} + +/// Where a note stands with GitHub. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Posting { + /// No post carried it. + New, + /// A post carried it, and it has not changed since. + Posted, + /// A post carried it, and it was edited after. + Edited, +} + +/// One inline comment, as the create-review endpoint takes it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct InlineComment { + pub path: String, + pub line: u32, + pub side: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + pub start_line: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub start_side: Option<&'static str>, + pub body: String, +} + +/// The JSON `POST /repos/{owner}/{repo}/pulls/{number}/reviews` receives. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ReviewRequest { + pub commit_id: String, + pub body: String, + pub event: Event, + pub comments: Vec, +} + +/// Why a note goes in the review body rather than inline. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InBody { + /// A note on the whole change. + Change, + /// A note on a whole file. + File, + /// A line note on lines outside the diff, made in the whole file. + OutsideDiff, + /// A line note whose code changed, or whose lines the diff no longer shows. + OffDiff, +} + +/// Why a note is left out. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Skip { + /// A post already carried it, unchanged since. + AlreadyPosted, + /// It has no text and no suggested code. + Empty, +} + +/// The pull request a post goes to, and the commit its comments are anchored to. +#[derive(Debug, Clone, Copy)] +pub struct Target<'a> { + pub repo: &'a PrRepo, + pub number: u64, + /// The head commit the person reviewed: the one the captured diff ends at. + pub reviewed_head: &'a str, +} + +/// What a post would carry, before the person confirms it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Plan { + pub commit_id: String, + /// Notes in the body's order, without the placeholder. + pub body: String, + pub comments: Vec, + /// Ids of the notes posted inline, parallel to `comments`. + pub inline: Vec, + /// Ids of the notes in the body, and why each is there. + pub in_body: Vec<(String, InBody)>, + pub skipped: Vec<(String, Skip)>, + /// Ids of included notes a post carried before they were edited: posted again, new. + pub reposted: Vec, +} + +impl Plan { + /// Build the post of `notes` (in record order) against the reviewed diff's `files`. + /// `posting` says where each note stands with GitHub. + pub fn build( + notes: &[CodeAnnotation], + files: &[FilePatch], + target: Target<'_>, + posting: impl Fn(&CodeAnnotation) -> Posting, + ) -> Self { + let mut plan = Self { + commit_id: target.reviewed_head.to_owned(), + body: String::new(), + comments: Vec::new(), + inline: Vec::new(), + in_body: Vec::new(), + skipped: Vec::new(), + reposted: Vec::new(), + }; + let mut parts: Vec = Vec::new(); + let mut outside: Vec = Vec::new(); + for note in notes { + let state = posting(note); + if state == Posting::Posted { + plan.skipped.push((note.id.clone(), Skip::AlreadyPosted)); + continue; + } + let place = placement(note, files); + let placed = match place { + Placement::Inline => inline_comment(note).map(|comment| plan.comments.push(comment)), + Placement::Body(InBody::OutsideDiff) => { + outside_entry(note, target).map(|entry| outside.push(entry)) + } + Placement::Body(kind) => body_entry(note, kind).map(|entry| parts.push(entry)), + }; + if placed.is_none() { + plan.skipped.push((note.id.clone(), Skip::Empty)); + continue; + } + match place { + Placement::Inline => plan.inline.push(note.id.clone()), + Placement::Body(kind) => plan.in_body.push((note.id.clone(), kind)), + } + if state == Posting::Edited { + plan.reposted.push(note.id.clone()); + } + } + if !outside.is_empty() { + parts.push(format!("**{OUTSIDE_DIFF_BODY_HEADING}**\n\n{}", outside.join("\n\n"))); + } + plan.body = parts.join("\n\n"); + plan + } + + /// Whether there is anything to post. + pub fn is_empty(&self) -> bool { + self.comments.is_empty() && self.body.trim().is_empty() + } + + /// The ids of every note the post carries. + pub fn ids(&self) -> Vec { + self.inline.iter().chain(self.in_body.iter().map(|(id, _)| id)).cloned().collect() + } + + /// How many notes go in the body for `kind`. + pub fn count_in_body(&self, kind: InBody) -> usize { + self.in_body.iter().filter(|(_, k)| *k == kind).count() + } + + pub fn count_skipped(&self, why: Skip) -> usize { + self.skipped.iter().filter(|(_, s)| *s == why).count() + } + + /// The request for `event`: an empty body beside inline comments becomes the + /// placeholder, except on an approval, which may have none. + pub fn request(&self, event: Event) -> ReviewRequest { + let body = if self.body.trim().is_empty() && event != Event::Approve && !self.comments.is_empty() { + BODY_PLACEHOLDER.to_owned() + } else { + self.body.clone() + }; + ReviewRequest { commit_id: self.commit_id.clone(), body, event, comments: self.comments.clone() } + } + + /// Whether the body is over GitHub's limit. + pub fn body_too_long(&self) -> bool { + self.body.chars().count() > MAX_BODY_CHARS + } +} + +#[derive(Clone, Copy)] +enum Placement { + Inline, + Body(InBody), +} + +/// Inline when GitHub can anchor it: a line note, not outdated, not outside the diff, whose +/// lines the reviewed diff shows on its side (all of them, so one hunk). +fn placement(note: &CodeAnnotation, files: &[FilePatch]) -> Placement { + match note.scope { + NoteScope::General => Placement::Body(InBody::Change), + NoteScope::File => Placement::Body(InBody::File), + NoteScope::Line if note.outside_diff => Placement::Body(InBody::OutsideDiff), + NoteScope::Line => { + let outdated = note.outdated || note.status() == Some(Status::Outdated); + let off = note.status() == Some(Status::NotInDiff); + let shown = files + .iter() + .find(|f| f.path == note.file_path) + .is_some_and(|f| f.shows(note.side, note.line_start, note.line_end)); + if outdated || off || !shown { Placement::Body(InBody::OffDiff) } else { Placement::Inline } + } + } +} + +fn github_side(side: Side) -> &'static str { + match side { + Side::Old => "LEFT", + Side::New => "RIGHT", + } +} + +/// The browser's `buildAnnotationFileComments` for one note; `None` when its body is empty. +fn inline_comment(note: &CodeAnnotation) -> Option { + let mut body = format!("{}{}", conventional_prefix(¬e.other), text(note)); + if let Some(code) = suggested(note) { + let _ = write!(body, "\n\n```suggestion\n{code}\n```"); + } + let body = body.trim().to_owned(); + if body.is_empty() { + return None; + } + let side = github_side(note.side); + let range = note.line_start != note.line_end; + Some(InlineComment { + path: note.file_path.clone(), + line: note.line_end, + side, + start_line: range.then_some(note.line_start), + start_side: range.then_some(side), + body, + }) +} + +/// One paragraph of the browser's `buildFileScopedBody` (with no file-level threads). +fn body_entry(note: &CodeAnnotation, kind: InBody) -> Option { + let text = text(note); + let entry = match kind { + InBody::Change if !text.is_empty() => text.to_owned(), + InBody::File if !text.is_empty() => format!("**{}:** {text}", note.file_path), + InBody::OffDiff if !text.is_empty() || suggested(note).is_some() => { + let outdated = note.outdated || note.status() == Some(Status::Outdated); + let label = if outdated { format!("{OUTDATED_ANNOTATION_LABEL} ") } else { String::new() }; + let commented_on = note + .anchor_text + .as_deref() + .map(|code| format!("\n\nCommented on:\n```\n{code}\n```")) + .unwrap_or_default(); + let suggestion = suggested(note) + .map(|code| format!("\n\nSuggested code:\n```\n{code}\n```")) + .unwrap_or_default(); + format!( + "**{} ({}, {}):** {label}{text}{commented_on}{suggestion}", + note.file_path, + lines(note), + note.side.as_str() + ) + } + _ => return None, + }; + Some(entry.trim().to_owned()) +} + +/// One entry of the browser's `buildOutsideDiffSection`. +fn outside_entry(note: &CodeAnnotation, target: Target<'_>) -> Option { + let text = text(note); + if text.is_empty() && suggested(note).is_none() { + return None; + } + let lines = lines(note); + let link = permalink(target, ¬e.file_path, note.line_start, note.line_end); + let quoted = note + .anchor_text + .as_deref() + .or(note.original_code.as_deref()) + .map(|code| format!("\n\n{}", code_fence(&cap_quoted(code)))) + .unwrap_or_default(); + let suggestion = + suggested(note).map(|code| format!("\n\nSuggested code:\n{}", code_fence(code))).unwrap_or_default(); + let prefix = conventional_prefix(¬e.other); + let entry = format!("**[{} ({lines})]({link}):** {prefix}{text}{quoted}{suggestion}", note.file_path); + Some(entry.trim().to_owned()) +} + +fn text(note: &CodeAnnotation) -> &str { + note.text.as_deref().unwrap_or("") +} + +fn suggested(note: &CodeAnnotation) -> Option<&str> { + note.suggested_code.as_deref().filter(|code| !code.is_empty()) +} + +/// `L5` or `L5-L9`. +fn lines(note: &CodeAnnotation) -> String { + if note.line_start == note.line_end { + format!("L{}", note.line_start) + } else { + format!("L{}-L{}", note.line_start, note.line_end) + } +} + +/// The browser's `formatConventionalPrefix`, for a note the browser wrote with a +/// conventional-comment label: `**issue (blocking):** `. Notes made here have none. +fn conventional_prefix(other: &BTreeMap) -> String { + let Some(label) = other.get("conventionalLabel").and_then(Value::as_str).filter(|l| !l.is_empty()) else { + return String::new(); + }; + let decorations: Vec<&str> = other + .get("decorations") + .and_then(Value::as_array) + .map(|list| list.iter().filter_map(Value::as_str).collect()) + .unwrap_or_default(); + let decorations = + if decorations.is_empty() { String::new() } else { format!(" ({})", decorations.join(", ")) }; + format!("**{label}{decorations}:** ") +} + +/// The browser's `prBlobPermalink` on GitHub: the lines at the reviewed commit. +fn permalink(target: Target<'_>, path: &str, first: u32, last: u32) -> String { + let path: Vec = path.split('/').map(encode_component).collect(); + let lines = if first == last { format!("L{first}") } else { format!("L{first}-L{last}") }; + format!( + "{}/blob/{}/{}#{lines}", + target.repo.web_url(), + encode_component(target.reviewed_head), + path.join("/") + ) +} + +/// JavaScript's `encodeURIComponent`. +fn encode_component(part: &str) -> String { + let mut out = String::with_capacity(part.len()); + for byte in part.bytes() { + if byte.is_ascii_alphanumeric() || b"-_.!~*'()".contains(&byte) { + out.push(char::from(byte)); + } else { + let _ = write!(out, "%{byte:02X}"); + } + } + out +} + +/// The browser's `capQuotedCode`: the first [`OUTSIDE_DIFF_QUOTE_MAX_LINES`] lines, then `…`. +fn cap_quoted(code: &str) -> String { + let lines: Vec<&str> = code.split('\n').collect(); + if lines.len() <= OUTSIDE_DIFF_QUOTE_MAX_LINES { + return code.to_owned(); + } + let kept: Vec<&str> = lines.into_iter().take(OUTSIDE_DIFF_QUOTE_MAX_LINES).collect(); + format!("{}\n\u{2026}", kept.join("\n")) +} + +/// The browser's `codeFence`: one backtick longer than the longest run inside, at least 3. +fn code_fence(code: &str) -> String { + let longest = code.split(|c| c != '`').map(str::len).max().unwrap_or(0).max(2); + let fence = "`".repeat(longest + 1); + format!("{fence}\n{code}\n{fence}") +} + +#[cfg(test)] +mod tests; diff --git a/crates/plannotator-tui-review/src/post/submit.rs b/crates/plannotator-tui-review/src/post/submit.rs new file mode 100644 index 00000000..a9239a0b --- /dev/null +++ b/crates/plannotator-tui-review/src/post/submit.rs @@ -0,0 +1,221 @@ +//! Posting a [`ReviewRequest`] with the person's own `gh` login: one +//! `gh api --method POST repos/{owner}/{repo}/pulls/{number}/reviews --input -`, the JSON on +//! stdin. No token passes through this app. GitHub creates the review with every comment, or +//! refuses it whole, so a failure posts nothing. + +use std::fmt; +use std::io::Write as _; +use std::process::{Command, Stdio}; + +use serde::Deserialize; + +use super::ReviewRequest; +use crate::github::{Gh, PrRepo}; + +/// The review GitHub created. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PostedReview { + /// The review's page; the PR's link when gh's reply could not be read. + pub url: String, + /// False when gh succeeded but printed something this app could not read: the review + /// was posted, its link is a guess. + pub confirmed: bool, +} + +/// Why a post failed. Every case posted nothing. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PostError { + /// `gh` is not installed. + GhMissing, + /// `gh` is not logged in to the PR's host. + NotLoggedIn { detail: String }, + /// The login cannot write reviews to this repository. + NoPermission { detail: String }, + /// GitHub's API rate limit. + RateLimited { detail: String }, + /// GitHub could not be reached. + Offline { detail: String }, + /// The reviewed commit is no longer part of the PR (a force-push). + HeadGone { detail: String }, + /// GitHub refused where one or more inline comments point. + Positions { detail: String }, + /// An approval or a change request on one's own pull request. + OwnPullRequest { detail: String }, + /// Anything else, with gh's and GitHub's words. + Other { detail: String }, +} + +impl fmt::Display for PostError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::GhMissing => write!( + f, + "posting needs the GitHub CLI (gh), and it is not installed; install it from \ + https://cli.github.com and run `gh auth login`" + ), + Self::NotLoggedIn { detail } => { + write!(f, "gh is not logged in to GitHub; run `gh auth login` ({detail})") + } + Self::NoPermission { detail } => write!( + f, + "your GitHub login cannot review this pull request (no access to the repository, \ + or gh's token lacks the repo scope; `gh auth refresh -s repo`) ({detail})" + ), + Self::RateLimited { detail } => { + write!(f, "GitHub's rate limit was reached; wait a few minutes and post again ({detail})") + } + Self::Offline { detail } => { + write!(f, "could not reach GitHub; check the connection and post again ({detail})") + } + Self::HeadGone { detail } => write!( + f, + "the commit you reviewed is no longer part of the pull request (it was force-pushed \ + since); reload with r, check the notes, and post again ({detail})" + ), + Self::Positions { detail } => { + write!(f, "GitHub refused the place of an inline comment ({detail})") + } + Self::OwnPullRequest { detail } => write!( + f, + "GitHub does not let you approve or request changes on your own pull request; post \ + it as a Comment ({detail})" + ), + Self::Other { detail } => write!(f, "gh api failed: {detail}"), + } + } +} + +impl std::error::Error for PostError {} + +#[derive(Deserialize)] +struct ReviewJson { + html_url: String, +} + +impl Gh { + /// Create one review on PR `number` of `repo` with `request`. Writes to GitHub: call it + /// only once the person confirmed what it posts. + pub fn post_review( + &self, + repo: &PrRepo, + number: u64, + request: &ReviewRequest, + ) -> Result { + let json = serde_json::to_vec(request).map_err(|e| PostError::Other { detail: e.to_string() })?; + let mut cmd = Command::new(self.program()); + cmd.arg("api"); + if !repo.host.eq_ignore_ascii_case("github.com") { + cmd.args(["--hostname", &repo.host]); + } + let endpoint = format!("repos/{}/{}/pulls/{number}/reviews", repo.owner, repo.name); + cmd.args(["--method", "POST", &endpoint, "--input", "-"]) + .env("GH_PROMPT_DISABLED", "1") + .env("GH_NO_UPDATE_NOTIFIER", "1") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut child = cmd.spawn().map_err(|source| { + if source.kind() == std::io::ErrorKind::NotFound { + PostError::GhMissing + } else { + PostError::Other { detail: format!("could not run gh: {source}") } + } + })?; + let written = child.stdin.take().map(|mut stdin| stdin.write_all(&json)); + let output = child + .wait_with_output() + .map_err(|e| PostError::Other { detail: format!("waiting for gh: {e}") })?; + if let Some(Err(e)) = written + && output.status.success() + { + return Err(PostError::Other { detail: format!("could not hand the review to gh: {e}") }); + } + if !output.status.success() { + return Err(classify( + &String::from_utf8_lossy(&output.stdout), + &String::from_utf8_lossy(&output.stderr), + )); + } + Ok(match serde_json::from_slice::(&output.stdout) { + Ok(review) => PostedReview { url: review.html_url, confirmed: true }, + Err(_) => PostedReview { url: format!("{}/pull/{number}", repo.web_url()), confirmed: false }, + }) + } +} + +/// gh's failure, from its stderr and the response body it prints on stdout, named for the +/// person. +pub(crate) fn classify(stdout: &str, stderr: &str) -> PostError { + let detail = detail(stdout, stderr); + let all = format!("{stdout}\n{stderr}").to_lowercase(); + let has = |needles: &[&str]| needles.iter().any(|n| all.contains(n)); + if has(&["gh auth login", "not logged in", "bad credentials", "http 401", "requires authentication"]) { + PostError::NotLoggedIn { detail } + } else if has(&["rate limit", "http 429"]) { + PostError::RateLimited { detail } + } else if has(&[ + "error connecting to", + "could not resolve host", + "no such host", + "network is unreachable", + "connection refused", + "i/o timeout", + "tls handshake timeout", + "dial tcp", + ]) { + PostError::Offline { detail } + } else if has(&["your own pull request"]) { + PostError::OwnPullRequest { detail } + } else if has(&["commit_id", "not part of the pull request", "no commit found for sha"]) { + PostError::HeadGone { detail } + } else if has(&["http 403", "http 404", "resource not accessible", "must have push access"]) { + PostError::NoPermission { detail } + } else if has(&["http 422"]) && has(&["line", "position", "path", "diff hunk", "start_line", "side"]) { + PostError::Positions { detail } + } else { + PostError::Other { detail } + } +} + +/// The most specific words available, capped: GitHub's `errors[]` (strings or `{message}`) +/// and `message` from the JSON gh prints, else gh's stderr. +fn detail(stdout: &str, stderr: &str) -> String { + const MAX: usize = 300; + let from_json = serde_json::from_str::(stdout.trim()).ok().and_then(|json| { + let errors: Vec = json + .get("errors") + .and_then(serde_json::Value::as_array) + .map(|list| { + list.iter() + .filter_map(|e| { + e.as_str().map(str::to_owned).or_else(|| { + e.get("message").and_then(serde_json::Value::as_str).map(str::to_owned) + }) + }) + .collect() + }) + .unwrap_or_default(); + let message = json.get("message").and_then(serde_json::Value::as_str).unwrap_or(""); + match (errors.is_empty(), message.is_empty()) { + (false, true) => Some(errors.join("; ")), + (false, false) => Some(format!("{message}: {}", errors.join("; "))), + (true, false) => Some(message.to_owned()), + (true, true) => None, + } + }); + let stderr = stderr.trim().trim_start_matches("gh: ").to_owned(); + // gh's own line repeats GitHub's message with the status (`Unprocessable Entity (HTTP + // 422)`); GitHub's words are the specific ones. + let text = match from_json { + Some(json) => json, + None if stderr.is_empty() => "gh api failed with no message".to_owned(), + None => stderr, + }; + let text = text.replace('\n', " "); + if text.chars().count() > MAX { + let cut: String = text.chars().take(MAX).collect(); + format!("{cut}\u{2026}") + } else { + text + } +} diff --git a/crates/plannotator-tui-review/src/post/tests.rs b/crates/plannotator-tui-review/src/post/tests.rs new file mode 100644 index 00000000..59d381bb --- /dev/null +++ b/crates/plannotator-tui-review/src/post/tests.rs @@ -0,0 +1,261 @@ +//! The expected bodies follow the browser's `ReviewSubmissionDialog.tsx` builders +//! (`buildAnnotationFileComments`, `buildFileScopedBody`, `buildOutsideDiffSection`). +#![allow(clippy::expect_used, clippy::indexing_slicing, reason = "tests assert by panicking")] + +use serde_json::json; + +use super::submit::classify; +use super::*; +use crate::patch::parse; + +const HEAD: &str = "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b"; + +/// `app.py`: old 1 one, 2 two, 3 four, 4 five, 5 six; new 1 one, 2 TWO, 3 three, 4 four, +/// 5 five, 6 six. Line 40 of either side is not in the diff. +fn files() -> Vec { + parse( + "diff --git a/app.py b/app.py\n--- a/app.py\n+++ b/app.py\n@@ -1,5 +1,6 @@\n one\n-two\n+TWO\n+three\n four\n five\n six\n", + ) +} + +fn repo() -> PrRepo { + PrRepo { host: "github.com".into(), owner: "o".into(), name: "app".into() } +} + +fn note(json: Value) -> CodeAnnotation { + let mut value = json; + if let Some(object) = value.as_object_mut() { + object.entry("createdAt").or_insert(1.into()); + object.entry("type").or_insert("comment".into()); + object.entry("scope").or_insert("line".into()); + object.entry("filePath").or_insert("app.py".into()); + object.entry("side").or_insert("new".into()); + } + serde_json::from_value(value).expect("a note") +} + +fn line(id: &str, side: &str, first: u32, last: u32, text: &str) -> CodeAnnotation { + note(json!({"id": id, "side": side, "lineStart": first, "lineEnd": last, "text": text})) +} + +fn plan_with(notes: &[CodeAnnotation], posting: impl Fn(&CodeAnnotation) -> Posting) -> Plan { + let repo = repo(); + Plan::build(notes, &files(), Target { repo: &repo, number: 7, reviewed_head: HEAD }, posting) +} + +fn plan(notes: &[CodeAnnotation]) -> Plan { + plan_with(notes, |_| Posting::New) +} + +fn request_json(plan: &Plan, event: Event) -> Value { + serde_json::to_value(plan.request(event)).expect("serializes") +} + +#[test] +fn a_one_line_note_is_an_inline_comment_on_the_right_without_start_fields() { + let plan = plan(&[line("a", "new", 2, 2, "name it")]); + assert_eq!( + request_json(&plan, Event::Comment), + json!({ + "commit_id": HEAD, + "body": "See inline comments.", + "event": "COMMENT", + "comments": [{"path": "app.py", "line": 2, "side": "RIGHT", "body": "name it"}], + }) + ); + assert_eq!(plan.inline, ["a"]); +} + +#[test] +fn a_range_carries_start_line_and_start_side_on_the_same_side() { + let plan = plan(&[line("a", "new", 2, 3, "split these")]); + assert_eq!( + serde_json::to_value(&plan.comments).expect("JSON"), + json!([{"path": "app.py", "line": 3, "side": "RIGHT", "start_line": 2, "start_side": "RIGHT", "body": "split these"}]) + ); +} + +#[test] +fn old_side_lines_go_on_the_left() { + let plan = plan(&[line("a", "old", 2, 2, "why drop two?"), line("b", "old", 1, 2, "and this")]); + let sides: Vec<_> = plan.comments.iter().map(|c| (c.side, c.start_side, c.line)).collect(); + assert_eq!(sides, [("LEFT", None, 2), ("LEFT", Some("LEFT"), 2)]); +} + +#[test] +fn a_suggestion_is_a_suggestion_block_after_its_text() { + let with_text = note(json!({"id": "s", "type": "suggestion", "lineStart": 2, "lineEnd": 3, + "text": "fold these", "suggestedCode": "TWO_AND_THREE", "originalCode": "TWO\nthree"})); + let bare = note(json!({"id": "t", "type": "suggestion", "lineStart": 2, "lineEnd": 2, + "suggestedCode": "Two"})); + let plan = plan(&[with_text, bare]); + let bodies: Vec<&str> = plan.comments.iter().map(|c| c.body.as_str()).collect(); + assert_eq!(bodies, ["fold these\n\n```suggestion\nTWO_AND_THREE\n```", "```suggestion\nTwo\n```"]); +} + +#[test] +fn file_notes_and_whole_change_notes_go_in_the_body_in_note_order() { + let notes = [ + note(json!({"id": "f", "scope": "file", "lineStart": 1, "lineEnd": 1, "text": "split this file"})), + line("a", "new", 2, 2, "name it"), + note(json!({"id": "g", "scope": "general", "filePath": "", "lineStart": 0, "lineEnd": 0, + "text": "please add a test"})), + ]; + let plan = plan(¬es); + assert_eq!(plan.body, "**app.py:** split this file\n\nplease add a test"); + assert_eq!(request_json(&plan, Event::Comment)["body"], plan.body, "no placeholder beside a body"); + assert_eq!(plan.in_body, [("f".to_owned(), InBody::File), ("g".to_owned(), InBody::Change)]); + assert_eq!(plan.comments.len(), 1); +} + +#[test] +fn notes_outside_the_diff_close_the_body_quoted_and_linked_never_inline() { + let outside = note(json!({"id": "o", "lineStart": 40, "lineEnd": 41, "text": "Why return silently?", + "anchorText": "if (!t) {\n return;", "originalCode": "if (!t) {\n return;", "outsideDiff": true})); + let general = note(json!({"id": "g", "scope": "general", "filePath": "", "lineStart": 0, "lineEnd": 0, + "text": "overall fine"})); + let plan = plan(&[outside, general]); + assert!(plan.comments.is_empty(), "{:?}", plan.comments); + assert_eq!( + plan.body, + format!( + "overall fine\n\n**Comments outside the diff**\n\n**[app.py (L40-L41)](https://github.com/o/app/blob/{HEAD}/app.py#L40-L41):** Why return silently?\n\n```\nif (!t) {{\n return;\n```" + ) + ); + assert_eq!(plan.count_in_body(InBody::OutsideDiff), 1); +} + +#[test] +fn quoted_code_outside_the_diff_is_capped_and_fenced_past_its_own_backticks() { + let code: Vec = (1..=45).map(|n| format!("line {n} ```")).collect(); + let outside = note(json!({"id": "o", "lineStart": 50, "lineEnd": 94, "text": "long", + "anchorText": code.join("\n"), "outsideDiff": true, "filePath": "src/a b.rs"})); + let body = plan(&[outside]).body; + assert!(body.contains("(https://github.com/o/app/blob/"), "{body}"); + assert!(body.contains("/src/a%20b.rs#L50-L94):** long\n\n````\nline 1 ```\n"), "{body}"); + assert!(body.ends_with("line 40 ```\n\u{2026}\n````"), "{body}"); +} + +#[test] +fn outdated_notes_and_notes_off_the_diff_go_in_the_body_with_their_code() { + let mut outdated = line("x", "new", 2, 2, "was wrong"); + outdated.outdated = true; + outdated.anchor_text = Some("TWO".into()); + let mut off = line("y", "old", 40, 40, "unchanged now"); + off.plannotator_tui.resolution = Some(Status::NotInDiff); + let gone = note(json!({"id": "z", "type": "suggestion", "lineStart": 40, "lineEnd": 41, + "suggestedCode": "fixed()"})); + let plan = plan(&[outdated, off, gone]); + assert!(plan.comments.is_empty()); + assert_eq!( + plan.body, + format!( + "**app.py (L2, new):** {OUTDATED_ANNOTATION_LABEL} was wrong\n\nCommented on:\n```\nTWO\n```\n\n\ + **app.py (L40, old):** unchanged now\n\n\ + **app.py (L40-L41, new):** \n\nSuggested code:\n```\nfixed()\n```" + ) + ); + assert_eq!(plan.count_in_body(InBody::OffDiff), 3); +} + +#[test] +fn posted_notes_are_left_out_and_edited_ones_post_again_as_new() { + let notes = + [line("a", "new", 2, 2, "one"), line("b", "new", 3, 3, "two"), line("c", "old", 2, 2, "three")]; + let plan = plan_with(¬es, |n| match n.id.as_str() { + "a" => Posting::Posted, + "b" => Posting::Edited, + _ => Posting::New, + }); + assert_eq!(plan.inline, ["b", "c"]); + assert_eq!(plan.skipped, [("a".to_owned(), Skip::AlreadyPosted)]); + assert_eq!(plan.reposted, ["b"]); + assert_eq!(plan.ids(), ["b", "c"]); + let all_posted = plan_with(¬es, |_| Posting::Posted); + assert!(all_posted.is_empty()); + assert_eq!(all_posted.count_skipped(Skip::AlreadyPosted), 3); +} + +#[test] +fn comments_stay_on_the_reviewed_commit_even_when_the_pr_moved_on() { + // The plan only knows the commit the diff was captured at; a newer head on GitHub does + // not move a comment onto lines the person never saw. + let outside = note(json!({"id": "o", "lineStart": 40, "lineEnd": 40, "text": "here", + "anchorText": "x", "outsideDiff": true})); + let plan = plan(&[line("a", "new", 2, 2, "name it"), outside]); + assert_eq!(plan.request(Event::Comment).commit_id, HEAD); + assert!(plan.body.contains(&format!("/blob/{HEAD}/app.py#L40)")), "{}", plan.body); + assert!(matches!( + classify( + "{\"message\":\"Unprocessable Entity\",\"errors\":[\"commit_id is not part of the pull request\"]}", + "gh: Unprocessable Entity (HTTP 422)" + ), + PostError::HeadGone { .. } + )); +} + +#[test] +fn empty_notes_are_skipped_and_an_approval_needs_no_placeholder() { + let plan = plan(&[line("a", "new", 2, 2, ""), line("b", "new", 3, 3, "ok")]); + assert_eq!(plan.skipped, [("a".to_owned(), Skip::Empty)]); + assert_eq!(request_json(&plan, Event::Approve)["body"], ""); + assert_eq!(request_json(&plan, Event::Approve)["event"], "APPROVE"); + assert_eq!(request_json(&plan, Event::RequestChanges)["body"], BODY_PLACEHOLDER); + assert_eq!(request_json(&plan, Event::RequestChanges)["event"], "REQUEST_CHANGES"); +} + +#[test] +fn a_browser_note_keeps_its_conventional_comment_prefix() { + let mut browser = line("a", "new", 2, 2, "missing check"); + browser.other.insert("conventionalLabel".into(), "issue".into()); + browser.other.insert("decorations".into(), json!(["blocking", "security"])); + let plan = plan(&[browser]); + assert_eq!(plan.comments[0].body, "**issue (blocking, security):** missing check"); +} + +#[test] +fn gh_failures_are_named_for_the_person() { + let cases = [ + ("", "To get started with GitHub CLI, please run: gh auth login", "NotLoggedIn"), + ("{\"message\":\"Bad credentials\"}", "gh: Bad credentials (HTTP 401)", "NotLoggedIn"), + ( + "{\"message\":\"Resource not accessible by integration\"}", + "gh: Resource not accessible by integration (HTTP 403)", + "NoPermission", + ), + ("{\"message\":\"Not Found\"}", "gh: Not Found (HTTP 404)", "NoPermission"), + ( + "{\"message\":\"API rate limit exceeded for user ID 1.\"}", + "gh: API rate limit exceeded (HTTP 403)", + "RateLimited", + ), + ( + "", + "error connecting to api.github.com\ncheck your internet connection or https://githubstatus.com", + "Offline", + ), + ( + "{\"message\":\"Unprocessable Entity\",\"errors\":[\"Line could not be resolved\"]}", + "gh: Unprocessable Entity (HTTP 422)", + "Positions", + ), + ( + "{\"message\":\"Unprocessable Entity\",\"errors\":[\"Can not approve your own pull request\"]}", + "gh: Unprocessable Entity (HTTP 422)", + "OwnPullRequest", + ), + ("", "boom", "Other"), + ]; + for (stdout, stderr, want) in cases { + let got = classify(stdout, stderr); + assert!(format!("{got:?}").starts_with(want), "{stderr}: {got:?}"); + } + let positions = classify( + "{\"message\":\"Unprocessable Entity\",\"errors\":[\"Line could not be resolved\"],\"status\":\"422\"}", + "gh: Unprocessable Entity (HTTP 422)", + ); + assert_eq!( + positions.to_string(), + "GitHub refused the place of an inline comment (Unprocessable Entity: Line could not be resolved)" + ); +} diff --git a/crates/plannotator-tui-review/src/store.rs b/crates/plannotator-tui-review/src/store.rs index ab5a7224..44cceec3 100644 --- a/crates/plannotator-tui-review/src/store.rs +++ b/crates/plannotator-tui-review/src/store.rs @@ -8,6 +8,10 @@ //! review's `annotations.json`: a note is pending until a delivery at or after its last edit //! covers it, and finishing moves sent notes to `archived` whole. //! +//! A pull request review also keeps `posted`: each review posted to GitHub, with its link and +//! the notes it carried. Posting is its own state, beside sending: a note is posted once a post +//! at or after its last edit covers it, whether or not an agent has had it too. +//! //! Every change is made on a copy and committed to memory only once it is saved, so a //! failed write leaves the store as it was. @@ -33,6 +37,19 @@ pub struct Delivered { pub annotation_ids: Vec, } +/// One review posted to GitHub: when, its link, the commit its comments are anchored to, and +/// which notes it carried. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Posted { + /// RFC 3339, UTC, milliseconds, as a delivery's. + pub at: String, + /// The review's page on GitHub. + pub url: String, + pub commit_id: String, + pub annotation_ids: Vec, +} + /// The `review.json` document. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Record { @@ -44,6 +61,9 @@ pub struct Record { pub deliveries: Vec, #[serde(default)] pub archived: Vec, + /// Reviews posted to GitHub (pull request reviews only). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub posted: Vec, } /// The notes of one review, bound to their file. @@ -97,6 +117,7 @@ impl ReviewStore { annotations: Vec::new(), deliveries: Vec::new(), archived: Vec::new(), + posted: Vec::new(), }, Err(source) => return Err(Error::Io { action: "reading", path, source }), }; @@ -123,6 +144,10 @@ impl ReviewStore { &self.record.deliveries } + pub fn posts(&self) -> &[Posted] { + &self.record.posted + } + /// Add a note and save. pub fn add(&mut self, note: CodeAnnotation) -> Result<()> { self.commit(|record| { @@ -132,12 +157,14 @@ impl ReviewStore { } /// Change one note with `edit` and save. When `edit` reports a change, `updatedAt` - /// advances past both its old value and the note's last send, even if the clock has not, - /// so an edited note is pending again. Returns whether anything changed. + /// advances past its old value, the note's last send and its last post, even if the clock + /// has not, so an edited note is pending (and unposted) again. Returns whether anything + /// changed. pub fn edit(&mut self, id: &str, edit: impl FnOnce(&mut CodeAnnotation) -> bool) -> Result { let floor = self.find(id).map(|note| { let sent = self.last_delivery(id).and_then(|d| parse_millis(&d.at)); - note.updated_at().max(sent.unwrap_or(0)) + 1 + let posted = self.last_post(id).and_then(|p| parse_millis(&p.at)); + note.updated_at().max(sent.unwrap_or(0)).max(posted.unwrap_or(0)) + 1 }); let Some(floor) = floor else { return Ok(false) }; let mut changed = false; @@ -211,6 +238,33 @@ impl ReviewStore { }) } + /// True once a post to GitHub at or after the note's last edit carried it. + pub fn is_posted(&self, note: &CodeAnnotation) -> bool { + self.last_post(¬e.id).and_then(|p| parse_millis(&p.at)).is_some_and(|at| note.updated_at() <= at) + } + + /// True when some post carried the note, even before its last edit. + pub fn was_posted(&self, note: &CodeAnnotation) -> bool { + self.last_post(¬e.id).is_some() + } + + /// Record a review posted to GitHub at `url`, anchored to `commit_id`, carrying `ids`. Its + /// time is never before the newest covered edit, as a delivery's. + pub fn record_post(&mut self, url: &str, commit_id: &str, ids: &[String]) -> Result<()> { + if ids.is_empty() { + return Ok(()); + } + let newest = + self.record.annotations.iter().filter(|n| ids.contains(&n.id)).map(CodeAnnotation::updated_at); + let at = format_millis(newest.max().unwrap_or(0).max(now_millis())); + let posted = + Posted { at, url: url.to_owned(), commit_id: commit_id.to_owned(), annotation_ids: ids.to_vec() }; + self.commit(|record| { + record.posted.push(posted); + true + }) + } + /// Finish every sent, unchanged note (outdated ones too): move it to `archived` whole. /// Pending notes stay. Returns the archived ids, which [`Self::restore_archived`] undoes. pub fn archive_sent(&mut self) -> Result> { @@ -259,6 +313,10 @@ impl ReviewStore { self.record.deliveries.iter().rev().find(|d| d.annotation_ids.iter().any(|sent| sent == id)) } + fn last_post(&self, id: &str) -> Option<&Posted> { + self.record.posted.iter().rev().find(|p| p.annotation_ids.iter().any(|posted| posted == id)) + } + /// Apply `change` to a copy; when it reports a change, save the copy and keep it. fn commit(&mut self, change: impl FnOnce(&mut Record) -> bool) -> Result<()> { let mut next = self.record.clone(); diff --git a/crates/plannotator-tui-review/src/store/tests.rs b/crates/plannotator-tui-review/src/store/tests.rs index 065d63f0..c7980979 100644 --- a/crates/plannotator-tui-review/src/store/tests.rs +++ b/crates/plannotator-tui-review/src/store/tests.rs @@ -118,6 +118,36 @@ fn sends_cover_notes_until_they_are_edited_across_reloads() { assert!(!store.is_pending(&store.annotations()[0])); } +#[test] +fn posts_are_their_own_state_beside_sends_and_survive_a_restart() { + let f = Fixture::new("posted"); + let mut store = f.load(); + let a = add(&mut store, "a"); + let b = add(&mut store, "b"); + let url = "https://github.com/o/app/pull/7#pullrequestreview-1"; + store.record_post(url, "1a2b3c", &[a.clone(), b.clone()]).expect("records"); + let mut store = f.load(); + let (first, second) = (&store.annotations()[0], &store.annotations()[1]); + assert!(store.is_posted(first) && store.is_posted(second), "the post survives a restart"); + assert!(store.is_pending(first), "posting is not sending"); + assert_eq!(store.posts()[0].url, url); + assert_eq!(store.posts()[0].commit_id, "1a2b3c"); + // An edit in the same millisecond as the post still counts: posted before, not now. + store + .edit(&b, |n| { + n.text = Some("b2".into()); + true + }) + .expect("edits"); + let store = f.load(); + let (first, second) = (&store.annotations()[0], &store.annotations()[1]); + assert!(store.is_posted(first)); + assert!(!store.is_posted(second) && store.was_posted(second)); + let json: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(store.path()).expect("written")).expect("JSON"); + assert_eq!(json["posted"][0]["annotationIds"], serde_json::json!([a, b])); +} + #[test] fn a_send_is_never_dated_before_the_edits_it_covers() { let f = Fixture::new("future"); diff --git a/crates/plannotator-tui/src/keys.rs b/crates/plannotator-tui/src/keys.rs index fb0ca61d..bca9aa90 100644 --- a/crates/plannotator-tui/src/keys.rs +++ b/crates/plannotator-tui/src/keys.rs @@ -107,6 +107,8 @@ pub(crate) enum Action { /// Back to the place before a jump, and forward again. JumpBack, JumpForward, + /// Post the notes to the pull request on GitHub as one review, after a summary. + PostToGithub, } use Action::{ @@ -121,7 +123,7 @@ use Action::{ PreviousHunk, PreviousMatch, PreviousUnviewed, Search, Suggest, ToggleFiles, ToggleLayout, ToggleViewed, ToggleWrap, WholeBase, WholeFile, }; -use Action::{GoToDefinition, JumpBack, JumpForward}; +use Action::{GoToDefinition, JumpBack, JumpForward, PostToGithub}; use Action::{NarrowColumn, ToggleNotes, WidenColumn}; /// Browsing, before the focused pane gets the key. @@ -206,6 +208,7 @@ pub(crate) const REVIEW_GLOBAL: &[Action] = &[ FinishReview, UndoFinish, ChangeComment, + PostToGithub, Reload, PickTarget, Help, @@ -246,8 +249,22 @@ pub(crate) const DIFF: &[Action] = &[ ]; /// The code review's notes rail. pub(crate) const NOTES: &[Action] = &[Down, Up, Confirm, Edit, Remove, Back]; -pub(crate) const REVIEW_MENU: &[Action] = - &[Down, Up, Confirm, Back, ReviewMenu, Interrupt, ChangeComment, ResendAll, FinishReview, UndoFinish]; +pub(crate) const REVIEW_MENU: &[Action] = &[ + Down, + Up, + Confirm, + Back, + ReviewMenu, + Interrupt, + ChangeComment, + PostToGithub, + ResendAll, + FinishReview, + UndoFinish, +]; +/// The summary before a post to GitHub: `left`/`right` choose the verdict, `confirm` posts, +/// `back` cancels. +pub(crate) const POST_REVIEW: &[Action] = &[Left, Right, Confirm, Back, Interrupt]; /// The code review's key help: the motions scroll it when it does not fit; the rest close it. pub(crate) const HELP: &[Action] = &[Back, Help, Quit, Interrupt, Down, Up, PageDown, PageUp]; @@ -268,6 +285,7 @@ const SHARED: &[&[&[Action]]] = &[ &[REVIEW_GLOBAL, DIFF], &[REVIEW_GLOBAL, NOTES], &[REVIEW_MENU], + &[POST_REVIEW], &[HELP], ]; @@ -456,6 +474,8 @@ const DEFAULTS: &[(Action, &[Key])] = &[ (JumpBack, &[ctrl('o')]), // Ctrl+I is Tab in terminals that do not tell them apart; there `cycle-focus` gets it. (JumpForward, &[ctrl('i')]), + // G for GitHub; free in every code review context. + (PostToGithub, &[ctrl('g')]), ]; /// Actions added after configs were written: `approve` (live only in a gated review), `copy` @@ -491,6 +511,7 @@ const LATE: &[Action] = &[ GoToDefinition, JumpBack, JumpForward, + PostToGithub, ]; /// The keys bound to each action. A `[keys]` entry replaces that action's keys and leaves the @@ -658,6 +679,7 @@ impl Action { Self::GoToDefinition => "go-to-definition", Self::JumpBack => "jump-back", Self::JumpForward => "jump-forward", + Self::PostToGithub => "post-to-github", } } } diff --git a/crates/plannotator-tui/src/review/draw.rs b/crates/plannotator-tui/src/review/draw.rs index ded7735a..a1e1642e 100644 --- a/crates/plannotator-tui/src/review/draw.rs +++ b/crates/plannotator-tui/src/review/draw.rs @@ -75,6 +75,10 @@ impl Screen { let pick = pick.clone(); self.draw_pick(frame, diff, &pick); } + Mode::Post(confirm) => { + let confirm = confirm.clone(); + self.draw_post(frame, area, &confirm); + } Mode::Browse | Mode::ConfirmQuit => {} } Ok(()) diff --git a/crates/plannotator-tui/src/review/input.rs b/crates/plannotator-tui/src/review/input.rs index b270eeb2..234aaab9 100644 --- a/crates/plannotator-tui/src/review/input.rs +++ b/crates/plannotator-tui/src/review/input.rs @@ -17,18 +17,20 @@ use crate::ui::compose::{self, ComposeAction}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) enum MenuRow { ChangeComment, + PostToGithub, ResendAll, Finish, Undo, } -pub(super) const MENU: [MenuRow; 4] = - [MenuRow::ChangeComment, MenuRow::ResendAll, MenuRow::Finish, MenuRow::Undo]; +pub(super) const MENU: [MenuRow; 5] = + [MenuRow::ChangeComment, MenuRow::PostToGithub, MenuRow::ResendAll, MenuRow::Finish, MenuRow::Undo]; impl MenuRow { pub(super) fn binding(self) -> Action { match self { Self::ChangeComment => Action::ChangeComment, + Self::PostToGithub => Action::PostToGithub, Self::ResendAll => Action::ResendAll, Self::Finish => Action::FinishReview, Self::Undo => Action::UndoFinish, @@ -113,6 +115,10 @@ impl Screen { Ok(()) } Mode::Pick(pick) => self.pick_key(key, pick), + Mode::Post(confirm) => { + self.post_key(key, confirm); + Ok(()) + } Mode::Help => { let room = self.help_room.get(); match self.keys.action(&key, keys::HELP) { @@ -162,6 +168,7 @@ impl Screen { Some(Action::FinishReview) => return self.run_menu(MenuRow::Finish), Some(Action::UndoFinish) => return self.run_menu(MenuRow::Undo), Some(Action::ChangeComment) => return self.run_menu(MenuRow::ChangeComment), + Some(Action::PostToGithub) => return self.run_menu(MenuRow::PostToGithub), Some(Action::Reload) => return self.reload(), Some(Action::PickTarget) => { self.picker = AgentPicker::open(&self.reach, &self.real_root()); @@ -278,6 +285,7 @@ impl Screen { self.mode = Mode::Browse; match row { MenuRow::ChangeComment => self.start_change_comment(), + MenuRow::PostToGithub => self.open_post(), MenuRow::ResendAll => self.send(true), MenuRow::Finish => self.finish(), MenuRow::Undo => return self.undo_finish(), diff --git a/crates/plannotator-tui/src/review/mod.rs b/crates/plannotator-tui/src/review/mod.rs index c1d6adae..6c950490 100644 --- a/crates/plannotator-tui/src/review/mod.rs +++ b/crates/plannotator-tui/src/review/mod.rs @@ -16,11 +16,14 @@ //! - [`send`]: send, resend, finish and undo. [`pi`]: the Pi link. //! - [`watch`]: noticing that the diff changed on disk, for the footer. //! - [`whole`]: the whole-file view (`o`, `O`), a second diffs-rs engine. +//! - [`post`]: posting the notes to the pull request on GitHub, after a summary +//! ([`post_view`] draws it). //! - [`cli`]: `plannotator-tui review [--staged | --base REF | --commit SHA | PR] [DIR]`. //! //! A pull request review (`PR` is a GitHub link, `N` or `#N`) fetches the PR with the //! 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. +//! agent as any review does. It can also post the notes to the PR as one GitHub review +//! ([`post`]), only after the person confirms a summary of what it posts. pub(crate) mod cli; mod diff; @@ -32,6 +35,8 @@ mod jump; mod notes; mod overlays; mod pi; +mod post; +mod post_view; mod rail; pub(crate) mod scope; mod send; @@ -89,6 +94,8 @@ enum Mode { Help, /// Go to definition's list: which identifier, or which answer. Pick(jump::Pick), + /// The summary before a post to GitHub. + Post(post::Confirm), } /// Which pane keys go to. diff --git a/crates/plannotator-tui/src/review/overlays.rs b/crates/plannotator-tui/src/review/overlays.rs index 4ebb5149..3bd4b3a2 100644 --- a/crates/plannotator-tui/src/review/overlays.rs +++ b/crates/plannotator-tui/src/review/overlays.rs @@ -22,6 +22,7 @@ impl Screen { .map(|row| { let label = match row { MenuRow::ChangeComment => "Comment on the whole change".to_owned(), + MenuRow::PostToGithub => self.post_menu_label(), MenuRow::ResendAll => { format!("Resend all \u{b7} {} notes", self.store.annotations().len()) } @@ -83,9 +84,13 @@ impl Screen { (key(&[Action::Send]), "send new and edited notes"), (key(&[Action::SendAndClose]), "send and close"), (key(&[Action::ChangeComment]), "comment on the whole change"), + ( + key(&[Action::PostToGithub]), + "post the notes to the pull request on GitHub, after a summary", + ), ( key(&[Action::ReviewMenu]), - "review menu: whole-change comment, resend all, finish, undo", + "review menu: whole-change comment, post to GitHub, resend all, finish, undo", ), (key(&[Action::PickTarget]), "choose the agent Send goes to"), ( diff --git a/crates/plannotator-tui/src/review/post.rs b/crates/plannotator-tui/src/review/post.rs new file mode 100644 index 00000000..093cac17 --- /dev/null +++ b/crates/plannotator-tui/src/review/post.rs @@ -0,0 +1,267 @@ +//! Posting the notes to the pull request on GitHub (`ctrl+g`, or the Review menu): a +//! summary first, always, then one review in one `gh api` request +//! ([`plannotator_tui_review::post`]). Only a pull request review offers it. +//! +//! The summary names the PR, how many notes go inline and how many in the review body (and +//! why), what is left out, and the verdict: Comment unless the person picks Approve or +//! Request changes, as the browser offers them. `Enter` posts and `Esc` cancels; nothing +//! leaves the machine before `Enter`. Comments are anchored to the commit the diff was +//! captured at, the one the person reviewed; when the PR has moved on since, the summary +//! says so. A post that fails posted nothing (GitHub takes the review whole or not at all), +//! and the summary stays open with the reason. A post that succeeds marks its notes posted, +//! a state of its own beside sent, saved with the notes; a later post carries only notes that +//! are new or edited since. + +use std::fmt::Write as _; + +use plannotator_tui_review::post::{Event, InBody, Plan, PostError, Posting, Skip, Target}; +use plannotator_tui_review::{CodeAnnotation, PrSpec, Scope}; +use ratatui::crossterm::event::KeyEvent; + +use super::{Mode, Screen}; +use crate::keys::{self, Action}; + +/// The summary on screen before a post. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct Confirm { + pub(super) plan: Plan, + pub(super) event: Event, + /// What `gh pr view` says about the PR's head now. + pub(super) head: Head, + /// Why the last try posted nothing. + pub(super) failed: Option, +} + +/// The PR's head on GitHub, against the commit the person reviewed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum Head { + Reviewed, + /// The PR has newer commits than the reviewed one. + Moved { + now: String, + }, + /// `gh pr view` failed; the post will say what is wrong. + Unknown(String), +} + +impl Screen { + /// `post-to-github`: open the summary, or say why there is nothing to post. + pub(super) fn open_post(&mut self) { + let (Some(pull), Some(gh)) = (&self.capture.pull, self.repo.gh()) else { + self.status = Some(format!( + "Post to GitHub needs a pull request review (plannotator-tui review ); this one is {}", + self.capture.scope.title() + )); + return; + }; + let plan = Plan::build( + self.store.annotations(), + &self.capture.files, + Target { repo: &pull.view.repo, number: pull.view.number, reviewed_head: &pull.head }, + |note| self.posting(note), + ); + if plan.is_empty() { + let posted = plan.count_skipped(Skip::AlreadyPosted); + self.status = Some(match (self.store.annotations().is_empty(), posted) { + (true, _) => "no notes to post to GitHub".to_owned(), + (false, 0) => "nothing to post to GitHub: the notes are empty".to_owned(), + (false, n) => format!("nothing new to post to GitHub ({n} already posted)"), + }); + return; + } + // Read-only: where the PR's head is now. + let spec = match &self.capture.scope { + Scope::PullRequest { url, number } => PrSpec::parse(url).unwrap_or(PrSpec::Number(*number)), + _ => PrSpec::Number(pull.view.number), + }; + let head = match gh.view(&spec, self.repo.workdir()) { + Ok(view) if view.head_sha == pull.head => Head::Reviewed, + Ok(view) => Head::Moved { now: view.head_sha }, + Err(err) => Head::Unknown(err.to_string()), + }; + self.mode = Mode::Post(Confirm { plan, event: Event::default(), head, failed: None }); + } + + fn posting(&self, note: &CodeAnnotation) -> Posting { + if self.store.is_posted(note) { + Posting::Posted + } else if self.store.was_posted(note) { + Posting::Edited + } else { + Posting::New + } + } + + pub(super) fn post_key(&mut self, key: KeyEvent, mut confirm: Confirm) { + let step = |event: Event, by: isize| { + let at = Event::ALL.iter().position(|e| *e == event).unwrap_or(0); + let next = at.saturating_add_signed(by).min(Event::ALL.len() - 1); + Event::ALL.get(next).copied().unwrap_or_default() + }; + match self.keys.action(&key, keys::POST_REVIEW) { + Some(Action::Left) => confirm.event = step(confirm.event, -1), + Some(Action::Right) => confirm.event = step(confirm.event, 1), + Some(Action::Confirm) => return self.post(confirm), + Some(Action::Back | Action::Interrupt) => { + self.mode = Mode::Browse; + self.status = Some("nothing posted to GitHub".into()); + return; + } + _ => return, + } + self.mode = Mode::Post(confirm); + } + + /// The person confirmed: post, then mark what was posted. + fn post(&mut self, mut confirm: Confirm) { + let (Some(pull), Some(gh)) = (&self.capture.pull, self.repo.gh()) else { + self.mode = Mode::Browse; + return; + }; + if confirm.plan.body_too_long() { + confirm.failed = Some(format!( + "the review body is over GitHub's {} characters; post fewer notes", + plannotator_tui_review::post::MAX_BODY_CHARS + )); + self.mode = Mode::Post(confirm); + return; + } + let request = confirm.plan.request(confirm.event); + match gh.post_review(&pull.view.repo, pull.view.number, &request) { + Ok(review) => { + let ids = confirm.plan.ids(); + let saved = self.store.record_post(&review.url, &confirm.plan.commit_id, &ids); + let mut status = if review.confirmed { + let (inline, body) = (confirm.plan.comments.len(), confirm.plan.in_body.len()); + format!("posted to GitHub: {inline} inline, {body} in the body \u{b7} {}", review.url) + } else { + format!( + "posted to GitHub, but gh's reply could not be read; the notes are marked posted so \ + they are not posted twice \u{b7} check {}", + review.url + ) + }; + if let Err(err) = saved { + let _ = write!( + status, + " \u{b7} could not save the posted state ({err}); a later post may repeat these notes" + ); + } + self.status = Some(status); + self.mode = Mode::Browse; + self.after_note_change(); + } + Err(err) => { + let mut why = format!("Nothing was posted: {err}."); + if matches!(err, PostError::Positions { .. }) { + let _ = write!( + why, + " The inline comments, each checked against the diff you reviewed, were on {}.", + comment_places(&confirm.plan) + ); + if let Head::Moved { now } = &confirm.head { + let reload = self.keys.labelled(Action::Reload, "reloads it").unwrap_or_default(); + let _ = + write!(why, " The PR is at {} now; {reload} and the notes follow.", short(now)); + } + } + self.status = Some(format!("nothing posted to GitHub: {}", short_reason(&err))); + confirm.failed = Some(why); + self.mode = Mode::Post(confirm); + } + } + } + + /// The Review menu row's words. + pub(super) fn post_menu_label(&self) -> String { + if self.capture.pull.is_none() { + return "Post to GitHub\u{2026} \u{b7} pull requests only".to_owned(); + } + let new = self.store.annotations().iter().filter(|n| !self.store.is_posted(n)).count(); + format!("Post to GitHub\u{2026} \u{b7} {new} new") + } +} + +/// `app.py:9 new, app.py:3-5 old`. +fn comment_places(plan: &Plan) -> String { + let places: Vec = plan + .comments + .iter() + .map(|c| { + let side = if c.side == "LEFT" { "old" } else { "new" }; + match c.start_line { + Some(start) => format!("{}:{start}-{} {side}", c.path, c.line), + None => format!("{}:{} {side}", c.path, c.line), + } + }) + .collect(); + places.join(", ") +} + +/// A few words for the footer; the summary has the rest. +fn short_reason(err: &PostError) -> &'static str { + match err { + PostError::GhMissing => "gh is not installed", + PostError::NotLoggedIn { .. } => "gh is not logged in", + PostError::NoPermission { .. } => "no permission", + PostError::RateLimited { .. } => "rate limited", + PostError::Offline { .. } => "GitHub unreachable", + PostError::HeadGone { .. } => "the reviewed commit is gone from the PR", + PostError::Positions { .. } => "GitHub refused a comment's place", + PostError::OwnPullRequest { .. } => "your own pull request", + PostError::Other { .. } => "gh api failed", + } +} + +pub(super) fn short(sha: &str) -> &str { + sha.get(..7).unwrap_or(sha) +} + +/// The summary's lines about what goes where, for the overlay. +pub(super) fn summary(plan: &Plan) -> Vec { + let plural = |n: usize, one: &str, many: &str| format!("{n} {}", if n == 1 { one } else { many }); + let mut lines = vec![plural(plan.comments.len(), "inline comment", "inline comments")]; + let body: Vec = [ + (InBody::Change, "whole-change note", "whole-change notes"), + (InBody::File, "file note", "file notes"), + ( + InBody::OutsideDiff, + "note outside the diff, quoted with a link", + "notes outside the diff, quoted with a link", + ), + ( + InBody::OffDiff, + "line note outdated or no longer in the diff, quoted", + "line notes outdated or no longer in the diff, quoted", + ), + ] + .into_iter() + .filter_map(|(kind, one, many)| { + let n = plan.count_in_body(kind); + (n > 0).then(|| format!(" {}", plural(n, one, many))) + }) + .collect(); + if body.is_empty() { + lines.push("nothing else in the review body".to_owned()); + } else { + lines.push(format!("{} in the review body:", plan.in_body.len())); + lines.extend(body); + } + if !plan.reposted.is_empty() { + lines.push(format!( + "{} edited since posted: posted again as new comments (the earlier ones stay on GitHub)", + plan.reposted.len() + )); + } + let skipped: Vec = [(Skip::AlreadyPosted, "already posted"), (Skip::Empty, "empty")] + .into_iter() + .filter_map(|(why, label)| { + let n = plan.count_skipped(why); + (n > 0).then(|| format!("{n} {label}")) + }) + .collect(); + if !skipped.is_empty() { + lines.push(format!("skipped: {}", skipped.join(", "))); + } + lines +} diff --git a/crates/plannotator-tui/src/review/post_view.rs b/crates/plannotator-tui/src/review/post_view.rs new file mode 100644 index 00000000..42b8aa04 --- /dev/null +++ b/crates/plannotator-tui/src/review/post_view.rs @@ -0,0 +1,119 @@ +//! The summary before a post to GitHub, drawn over the review. + +use ratatui::Frame; +use ratatui::layout::Rect; +use ratatui::style::Style; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, BorderType, Borders, Clear, Paragraph}; + +use super::Screen; +use super::post::{Confirm, Head, short, summary}; +use crate::keys::Action; +use crate::theme::palette; +use crate::wrap::wrap_line; +use plannotator_tui_review::post::Event; + +/// The summary's widest. +const WIDTH: u16 = 76; + +impl Screen { + pub(super) fn draw_post(&self, frame: &mut Frame, area: Rect, confirm: &Confirm) { + let Some(pull) = &self.capture.pull else { return }; + let accent = Style::new().fg(palette().accent).bold(); + let warn = Style::new().fg(palette().comment).bold(); + let mut lines: Vec> = vec![ + Line::from(vec![ + Span::styled(format!("{}#{}", pull.view.repo.slug(), pull.view.number), accent), + Span::raw(format!(" \u{b7} {}", pull.view.title)), + ]), + Line::from(Span::styled( + format!("anchored to {}, the commit you reviewed", short(&confirm.plan.commit_id)), + Style::new().dim(), + )), + Line::default(), + ]; + lines.extend(summary(&confirm.plan).into_iter().map(Line::from)); + match &confirm.head { + Head::Reviewed => {} + Head::Moved { now } => { + let reload = self.keys.labelled(Action::Reload, "reloads it first").unwrap_or_default(); + lines.push(Line::default()); + lines.push(Line::from(Span::styled( + format!( + "The PR moved on: its head is {} now. Comments stay on {}, the lines you saw; \ + GitHub shows them as outdated where the code changed since. {reload}", + short(now), + short(&confirm.plan.commit_id) + ), + warn, + ))); + } + Head::Unknown(why) => { + lines.push(Line::default()); + lines.push(Line::from(Span::styled(format!("Could not check the PR's head: {why}"), warn))); + } + } + lines.push(Line::default()); + let mut choices = vec![Span::raw("verdict ")]; + for event in Event::ALL { + let chosen = event == confirm.event; + let mark = if chosen { "(\u{2022})" } else { "( )" }; + let style = if chosen { Style::new().bold() } else { Style::new().dim() }; + choices.push(Span::styled(format!("{mark} {} ", event.label()), style)); + } + lines.push(Line::from(choices)); + if let Some(failed) = &confirm.failed { + lines.push(Line::default()); + lines.push(Line::from(Span::styled(failed.clone(), Style::new().fg(palette().delete).bold()))); + } + let verb = match confirm.event { + Event::Comment => "posts", + Event::Approve => "posts and approves", + Event::RequestChanges => "posts and requests changes", + }; + let moves: Vec = [Action::Left, Action::Right] + .map(|a| self.keys.hint(a)) + .into_iter() + .filter(|k| !k.is_empty()) + .collect(); + let help: Vec = [ + self.keys.labelled(Action::Confirm, verb), + (!moves.is_empty()).then(|| format!("{} verdict", moves.join("/"))), + self.keys.labelled(Action::Back, "cancels"), + ] + .into_iter() + .flatten() + .collect(); + let width = area.width.min(WIDTH); + let inner_width = usize::from(width.saturating_sub(4)).max(1); + let rows: Vec> = lines + .iter() + .flat_map(|line| { + let wrapped = wrap_line(line, &[], inner_width); + if wrapped.is_empty() { + vec![Line::default()] + } else { + wrapped.into_iter().map(|r| r.line).collect() + } + }) + .collect(); + let height = (rows.len() as u16 + 2).min(area.height); + let rect = Rect { + x: area.x + area.width.saturating_sub(width) / 2, + y: area.y + area.height.saturating_sub(height) / 2, + width, + height, + }; + frame.render_widget(Clear, rect); + let boxed = Block::default() + .borders(Borders::ALL) + .border_type(BorderType::Rounded) + .border_style(Style::new().fg(palette().accent)) + .title(Span::styled(" post to GitHub ", Style::new().dim())) + .title_bottom(Span::styled(format!(" {} ", help.join(" \u{b7} ")), Style::new().dim())); + let inner = boxed.inner(rect); + frame.render_widget(boxed, rect); + let text_area = Rect { x: inner.x + 1, width: inner.width.saturating_sub(2), ..inner }; + frame.render_widget(Paragraph::new(rows), text_area); + } +} diff --git a/crates/plannotator-tui/src/review/rail.rs b/crates/plannotator-tui/src/review/rail.rs index 7f3abdff..cfd23911 100644 --- a/crates/plannotator-tui/src/review/rail.rs +++ b/crates/plannotator-tui/src/review/rail.rs @@ -227,6 +227,9 @@ impl Screen { if sent { tags.push("sent".to_owned()); } + if self.store.is_posted(note) { + tags.push("posted".to_owned()); + } let mut title = format!(" {} {} ", notes::glyph(note), tags.join(" \u{b7} ")); let mut text = notes::body(note); // A title wider than the bubble's top border would cut the credit off; it moves into diff --git a/crates/plannotator-tui/src/review/tests/mod.rs b/crates/plannotator-tui/src/review/tests/mod.rs index f15ead06..73e398a3 100644 --- a/crates/plannotator-tui/src/review/tests/mod.rs +++ b/crates/plannotator-tui/src/review/tests/mod.rs @@ -12,6 +12,8 @@ mod notes_flow; mod notes_rail; mod pi_notes; #[cfg(unix)] +mod post_flow; +#[cfg(unix)] mod pull_flow; mod rex_picker; mod send_flow; diff --git a/crates/plannotator-tui/src/review/tests/post_flow.rs b/crates/plannotator-tui/src/review/tests/post_flow.rs new file mode 100644 index 00000000..668eee59 --- /dev/null +++ b/crates/plannotator-tui/src/review/tests/post_flow.rs @@ -0,0 +1,306 @@ +//! Posting a pull request review's notes to GitHub, against the simulated GitHub of +//! `pull_flow`: the `gh` stand-in answers `gh pr view` from `view.json` and records every +//! `gh api` call (its arguments, and the JSON on its stdin) instead of reaching GitHub. + +use std::os::unix::fs::PermissionsExt as _; + +use plannotator_tui_review::CodeAnnotation; +use ratatui::crossterm::event::KeyModifiers; + +use super::pull_flow::{Pull, URL, git_in}; +use super::*; +use crate::review::Mode; + +const REVIEW_URL: &str = "https://github.com/o/app/pull/7#pullrequestreview-42"; + +impl Pull { + /// Make the `gh` stand-in answer `gh api` with `stdout`, `stderr` and `exit`, recording + /// each call's arguments in `api-args` and its stdin as one line of `api-requests.jsonl`. + fn answer_api(&self, stdout: &str, stderr: &str, exit: i32) { + let dir = self.dir.display().to_string(); + std::fs::write(self.dir.join("api-stdout"), stdout).expect("stdout"); + std::fs::write(self.dir.join("api-stderr"), stderr).expect("stderr"); + let script = format!( + "#!/bin/sh\nif [ \"$1\" = api ]; then\n printf '%s\\n' \"$@\" >> '{dir}/api-args'\n cat >> '{dir}/api-requests.jsonl'\n echo >> '{dir}/api-requests.jsonl'\n cat '{dir}/api-stdout'\n cat '{dir}/api-stderr' >&2\n exit {exit}\nfi\ncat '{dir}/view.json'\n" + ); + let gh = self.dir.join("gh"); + std::fs::write(&gh, script).expect("gh"); + std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).expect("chmod"); + } + + fn answer_created(&self) { + let reply = serde_json::json!({"id": 42, "html_url": REVIEW_URL, "state": "COMMENTED"}); + self.answer_api(&reply.to_string(), "", 0); + } + + /// Every review `gh api` was handed, in order. + fn requests(&self) -> Vec { + std::fs::read_to_string(self.dir.join("api-requests.jsonl")) + .unwrap_or_default() + .lines() + .filter(|l| !l.trim().is_empty()) + .map(|l| serde_json::from_str(l).expect("JSON")) + .collect() + } +} + +fn ctrl_g(screen: &mut Screen) { + screen.handle_event(Event::Key(KeyEvent::new(KeyCode::Char('g'), KeyModifiers::CONTROL))).expect("key"); +} + +fn comment_on(screen: &mut Screen, side: Side, line: u32, text: &str) { + screen.diff.reveal("app.py", side, line).expect("in the diff"); + keys(screen, "c"); + type_and_save(screen, text); +} + +/// A line comment, a range, an old-side comment, a suggestion, a file note, a whole-change +/// note and a note outside the diff. +fn every_kind_of_note(screen: &mut Screen) { + comment_on(screen, Side::New, 5, "say hello properly"); + at(screen, 9); + keys(screen, "vjv"); + keys(screen, "c"); + type_and_save(screen, "name the total"); + comment_on(screen, Side::Old, 10, "why drop the default?"); + at(screen, 14); + keys(screen, "s"); + press(screen, KeyCode::End); + type_and_save(screen, " # from argv"); + keys(screen, "C"); + type_and_save(screen, "split this file"); + keys(screen, "M"); + type_and_save(screen, "please add a test"); + let outside = CodeAnnotation::outside_diff_comment( + "app.py", + 15, + 15, + " print(add(1, 2))".into(), + "is this still needed?".into(), + &screen.capture.patch_key, + ); + screen.store.add(outside).expect("adds"); +} + +#[test] +fn ctrl_g_shows_a_summary_and_posts_one_review_only_on_enter() { + let pull = Pull::new("post"); + pull.answer_created(); + let mut screen = pull.open(); + every_kind_of_note(&mut screen); + let head = git_in(&pull.work(), &["rev-parse", "feature"]); + + ctrl_g(&mut screen); + assert!(matches!(screen.mode, Mode::Post(_)), "{:?}", screen.status); + let rows = frame(&mut screen, 120, 40); + if let Some(dir) = std::env::var_os("POST_GH_PROOF_DIR") { + std::fs::create_dir_all(&dir).expect("proof dir"); + std::fs::write(PathBuf::from(dir).join("summary.txt"), rows.join("\n")).expect("proof"); + } + row_with(&rows, "post to GitHub"); + assert!(row_with(&rows, "o/app#7").contains("feat: greet from argv")); + row_with(&rows, &format!("anchored to {}, the commit you reviewed", &head[..7])); + row_with(&rows, "4 inline comments"); + row_with(&rows, "3 in the review body:"); + row_with(&rows, " 1 whole-change note"); + row_with(&rows, " 1 file note"); + row_with(&rows, " 1 note outside the diff, quoted with a link"); + assert!(row_with(&rows, "verdict").contains("(\u{2022}) Comment")); + row_with(&rows, "enter posts"); + assert_eq!(pull.requests().len(), 0, "nothing leaves before Enter"); + + press(&mut screen, KeyCode::Enter); + assert_eq!(screen.mode, Mode::Browse); + let [request] = pull.requests().try_into().expect("one request"); + let args = read(&pull.dir.join("api-args")); + assert_eq!(args, "api\n--method\nPOST\nrepos/o/app/pulls/7/reviews\n--input\n-\n"); + assert_eq!(request["commit_id"], head.as_str()); + assert_eq!(request["event"], "COMMENT"); + assert_eq!( + request["comments"], + serde_json::json!([ + {"path": "app.py", "line": 5, "side": "RIGHT", "body": "say hello properly"}, + {"path": "app.py", "line": 10, "side": "RIGHT", "start_line": 9, "start_side": "RIGHT", "body": "name the total"}, + {"path": "app.py", "line": 10, "side": "LEFT", "body": "why drop the default?"}, + {"path": "app.py", "line": 14, "side": "RIGHT", "body": "```suggestion\n greet(sys.argv[1]) # from argv\n```"}, + ]) + ); + let body = request["body"].as_str().expect("a body"); + assert!( + body.starts_with( + "**app.py:** split this file\n\nplease add a test\n\n**Comments outside the diff**\n\n" + ), + "{body}" + ); + assert!(body.contains(&format!("[app.py (L15)]({URL}/blob/{head}/app.py#L15)")), "{body}"); + + let status = screen.status.clone().unwrap_or_default(); + assert_eq!(status, format!("posted to GitHub: 4 inline, 3 in the body \u{b7} {REVIEW_URL}")); + let rows = frame(&mut screen, 120, 40); + assert!(rows[39].contains(REVIEW_URL) || rows[38].contains(REVIEW_URL), "the footer shows the link"); + row_with(&rows, "5 new \u{b7} posted"); + let record: serde_json::Value = serde_json::from_str(&read(screen.store.path())).expect("JSON"); + assert_eq!(record["posted"][0]["url"], REVIEW_URL); + assert_eq!(record["posted"][0]["commitId"], head.as_str()); + assert_eq!(record["posted"][0]["annotationIds"].as_array().map(Vec::len), Some(7)); + assert_eq!(pull.agent.sent.borrow().len(), 0, "posting is not sending to the agent"); +} + +#[test] +fn esc_on_the_summary_posts_nothing() { + let pull = Pull::new("post-esc"); + pull.answer_created(); + let mut screen = pull.open(); + comment_on(&mut screen, Side::New, 9, "name the total"); + ctrl_g(&mut screen); + keys(&mut screen, "l"); + let Mode::Post(confirm) = &screen.mode else { panic!("the summary") }; + assert_eq!(confirm.event, plannotator_tui_review::Event::Approve, "an explicit choice"); + press(&mut screen, KeyCode::Esc); + assert_eq!(screen.mode, Mode::Browse); + assert_eq!(pull.requests().len(), 0); + assert_eq!(screen.status.as_deref(), Some("nothing posted to GitHub")); + assert!(!screen.store.is_posted(&screen.store.annotations()[0])); +} + +#[test] +fn a_later_post_carries_only_new_and_edited_notes() { + let pull = Pull::new("post-again"); + pull.answer_created(); + let mut screen = pull.open(); + comment_on(&mut screen, Side::New, 5, "say hello properly"); + comment_on(&mut screen, Side::New, 9, "name the total"); + ctrl_g(&mut screen); + press(&mut screen, KeyCode::Enter); + ctrl_g(&mut screen); + assert_eq!(screen.mode, Mode::Browse); + assert_eq!(screen.status.as_deref(), Some("nothing new to post to GitHub (2 already posted)")); + + // Edit the note on line 9 and add one on line 14. + let edited = screen.store.annotations().iter().find(|n| n.line_start == 9).expect("note").id.clone(); + screen + .store + .edit(&edited, |n| { + n.text = Some("call it total".into()); + true + }) + .expect("edits"); + comment_on(&mut screen, Side::New, 14, "check argv"); + ctrl_g(&mut screen); + let rows = frame(&mut screen, 120, 40); + row_with(&rows, "2 inline comments"); + row_with(&rows, "1 edited since posted: posted again as new comments"); + row_with(&rows, "skipped: 1 already posted"); + press(&mut screen, KeyCode::Enter); + let requests = pull.requests(); + let [_, second] = requests.as_slice() else { panic!("two posts: {requests:?}") }; + let bodies: Vec<&str> = + second["comments"].as_array().expect("comments").iter().filter_map(|c| c["body"].as_str()).collect(); + assert_eq!(bodies, ["call it total", "check argv"]); +} + +#[test] +fn a_refused_post_posts_nothing_and_names_the_comments() { + let pull = Pull::new("post-refused"); + pull.answer_api( + r#"{"message":"Unprocessable Entity","errors":["Line could not be resolved"],"status":"422"}"#, + "gh: Unprocessable Entity (HTTP 422)\n", + 1, + ); + let mut screen = pull.open(); + comment_on(&mut screen, Side::New, 9, "name the total"); + comment_on(&mut screen, Side::Old, 10, "why drop the default?"); + ctrl_g(&mut screen); + press(&mut screen, KeyCode::Enter); + let Mode::Post(confirm) = &screen.mode else { panic!("the summary stays open") }; + let failed = confirm.failed.clone().expect("a reason"); + assert_eq!( + failed, + "Nothing was posted: GitHub refused the place of an inline comment (Unprocessable Entity: Line could \ + not be resolved). The inline comments, each checked against the diff you reviewed, were on app.py:9 \ + new, app.py:10 old." + ); + let rows = frame(&mut screen, 120, 40); + row_with(&rows, "Nothing was posted"); + assert!(screen.store.posts().is_empty()); + assert!(screen.store.annotations().iter().all(|n| !screen.store.is_posted(n))); + assert_eq!(screen.status.as_deref(), Some("nothing posted to GitHub: GitHub refused a comment's place")); +} + +#[test] +fn gh_errors_are_named_and_post_nothing() { + let cases = [ + ("", "To get started with GitHub CLI, please run: gh auth login\n", "gh is not logged in to GitHub"), + ( + r#"{"message":"Resource not accessible by integration"}"#, + "gh: Resource not accessible by integration (HTTP 403)\n", + "your GitHub login cannot review this pull request", + ), + ( + r#"{"message":"API rate limit exceeded for user ID 1."}"#, + "gh: API rate limit exceeded for user ID 1. (HTTP 403)\n", + "GitHub's rate limit was reached", + ), + ("", "error connecting to api.github.com\n", "could not reach GitHub"), + ]; + for (stdout, stderr, says) in cases { + let pull = Pull::new("post-errors"); + pull.answer_api(stdout, stderr, 1); + let mut screen = pull.open(); + comment_on(&mut screen, Side::New, 9, "name the total"); + ctrl_g(&mut screen); + press(&mut screen, KeyCode::Enter); + let Mode::Post(confirm) = &screen.mode else { panic!("the summary stays open") }; + let failed = confirm.failed.clone().unwrap_or_default(); + assert!(failed.starts_with(&format!("Nothing was posted: {says}")), "{failed}"); + assert!(screen.store.posts().is_empty()); + } +} + +#[test] +fn when_the_pr_moved_on_the_summary_says_so_and_comments_stay_on_the_reviewed_commit() { + let pull = Pull::new("post-moved"); + pull.answer_created(); + let mut screen = pull.open(); + let reviewed = git_in(&pull.work(), &["rev-parse", "feature"]); + comment_on(&mut screen, Side::New, 9, "name the total"); + pull.push_head(&format!("# greeter\n{AFTER}")); + let now = git_in(&pull.work(), &["rev-parse", "feature"]); + ctrl_g(&mut screen); + let rows = frame(&mut screen, 120, 40); + let moved = rows.iter().find(|r| r.contains("The PR moved on")).expect("the warning"); + assert!(moved.contains(&now[..7]), "{moved}"); + press(&mut screen, KeyCode::Enter); + let [request] = pull.requests().try_into().expect("one request"); + assert_eq!(request["commit_id"], reviewed.as_str()); + assert_eq!(request["comments"][0]["line"], 9); +} + +#[test] +fn the_review_menu_offers_it_and_outside_a_pr_it_says_why_not() { + let pull = Pull::new("post-menu"); + pull.answer_created(); + let mut screen = pull.open(); + comment_on(&mut screen, Side::New, 9, "name the total"); + keys(&mut screen, "m"); + let rows = frame(&mut screen, 120, 40); + assert!(row_with(&rows, "Post to GitHub\u{2026} \u{b7} 1 new").contains("ctrl+g")); + keys(&mut screen, "j"); + press(&mut screen, KeyCode::Enter); + assert!(matches!(screen.mode, Mode::Post(_))); + + let fixture = Fixture::new("post-local"); + let mut local = fixture.open(); + keys(&mut local, "m"); + let rows = frame(&mut local, 120, 40); + row_with(&rows, "Post to GitHub\u{2026} \u{b7} pull requests only"); + press(&mut local, KeyCode::Esc); + ctrl_g(&mut local); + assert_eq!(local.mode, Mode::Browse); + assert_eq!( + local.status.as_deref(), + Some( + "Post to GitHub needs a pull request review (plannotator-tui review ); this one is Uncommitted" + ) + ); +} diff --git a/crates/plannotator-tui/src/review/tests/pull_flow.rs b/crates/plannotator-tui/src/review/tests/pull_flow.rs index b424d916..949502ce 100644 --- a/crates/plannotator-tui/src/review/tests/pull_flow.rs +++ b/crates/plannotator-tui/src/review/tests/pull_flow.rs @@ -8,14 +8,14 @@ use plannotator_tui_review::{Gh, Repo, Status}; use super::*; -const URL: &str = "https://github.com/o/app"; +pub(super) const URL: &str = "https://github.com/o/app"; -struct Pull { - dir: PathBuf, - agent: Agent, +pub(super) struct Pull { + pub(super) dir: PathBuf, + pub(super) agent: Agent, } -fn git_in(dir: &Path, args: &[&str]) -> String { +pub(super) fn git_in(dir: &Path, args: &[&str]) -> String { let out = Command::new("git") .args(["-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "commit.gpgsign=false"]) .arg("-C") @@ -29,7 +29,7 @@ fn git_in(dir: &Path, args: &[&str]) -> String { impl Pull { /// PR 7 changes `app.py` from BEFORE to AFTER on branch `feature` off `main`. - fn new(tag: &str) -> Self { + pub(super) fn new(tag: &str) -> Self { let dir = std::env::temp_dir().join(format!("plannotator-review-pull-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).expect("dir"); @@ -57,20 +57,20 @@ impl Pull { pull } - fn work(&self) -> PathBuf { + pub(super) fn work(&self) -> PathBuf { self.dir.join("work") } - fn clone_dir(&self) -> PathBuf { + pub(super) fn clone_dir(&self) -> PathBuf { self.dir.join("clone") } - fn data(&self) -> PathBuf { + pub(super) fn data(&self) -> PathBuf { self.dir.join("data") } /// Commit `app` on `feature`, push it as PR 7's head, and describe it for `gh`. - fn push_head(&self, app: &str) { + pub(super) fn push_head(&self, app: &str) { let work = self.work(); std::fs::write(work.join("app.py"), app).expect("write"); git_in(&work, &["commit", "-qam", "feature"]); @@ -84,7 +84,7 @@ impl Pull { std::fs::write(self.dir.join("view.json"), view.to_string()).expect("view.json"); } - fn open(&self) -> Screen { + pub(super) fn open(&self) -> Screen { let gh = Gh::at(self.dir.join("gh")); let (repo, capture) = Repo::pull_request(&self.clone_dir(), "#7", &self.dir.join("cache"), &gh).expect("the PR opens"); From 183fc65acdf69110217ac62a0e5b81160e281764 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Fri, 20 Nov 2026 00:16:24 -0500 Subject: [PATCH 02/16] fix(review): a bubble title with no room moves its sent and posted marks into the body --- crates/plannotator-tui/src/review/rail.rs | 23 ++++++++++++------ .../src/review/tests/post_flow.rs | 24 +++++++++++++++++++ 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/crates/plannotator-tui/src/review/rail.rs b/crates/plannotator-tui/src/review/rail.rs index cfd23911..cfbccb2d 100644 --- a/crates/plannotator-tui/src/review/rail.rs +++ b/crates/plannotator-tui/src/review/rail.rs @@ -224,23 +224,32 @@ impl Screen { tags.push(name.to_owned()); } let sent = !self.store.is_pending(note); + let mut states = Vec::new(); if sent { - tags.push("sent".to_owned()); + states.push("sent"); } if self.store.is_posted(note) { - tags.push("posted".to_owned()); + states.push("posted"); } - let mut title = format!(" {} {} ", notes::glyph(note), tags.join(" \u{b7} ")); + tags.extend(states.iter().map(|s| (*s).to_owned())); + let fits = |tags: &[String]| { + format!(" {} {} ", notes::glyph(note), tags.join(" \u{b7} ")).width() <= width + 2 + }; let mut text = notes::body(note); - // A title wider than the bubble's top border would cut the credit off; it moves into - // the body instead. The border spans `width` plus the padding and two corners. + // A title wider than the bubble's top border would be cut off. The border spans + // `width` plus the padding and two corners. The credit moves into the body first, + // then the sent and posted marks. if let Some(name) = author - && title.width() > width + 2 + && !fits(&tags) { tags.retain(|tag| tag != name); - title = format!(" {} {} ", notes::glyph(note), tags.join(" \u{b7} ")); text = format!("From: {name}\n{text}"); } + if !states.is_empty() && !fits(&tags) { + tags.retain(|tag| !states.contains(&tag.as_str())); + text = format!("{}\n{text}", states.join(" \u{b7} ")); + } + let title = format!(" {} {} ", notes::glyph(note), tags.join(" \u{b7} ")); let mut body: Vec> = text .split('\n') .flat_map(|line| { diff --git a/crates/plannotator-tui/src/review/tests/post_flow.rs b/crates/plannotator-tui/src/review/tests/post_flow.rs index 668eee59..f7739223 100644 --- a/crates/plannotator-tui/src/review/tests/post_flow.rs +++ b/crates/plannotator-tui/src/review/tests/post_flow.rs @@ -304,3 +304,27 @@ fn the_review_menu_offers_it_and_outside_a_pr_it_says_why_not() { ) ); } + +#[test] +fn a_note_both_sent_and_posted_says_so_even_when_its_title_has_no_room() { + let pull = Pull::new("post-both"); + pull.answer_created(); + let mut screen = pull.open(); + let outside = CodeAnnotation::outside_diff_comment( + "app.py", + 14, + 15, + " greet(sys.argv[1])\n print(add(1, 2))".into(), + "both lines?".into(), + &screen.capture.patch_key, + ); + screen.store.add(outside).expect("adds"); + keys(&mut screen, "E"); + ctrl_g(&mut screen); + press(&mut screen, KeyCode::Enter); + let rows = frame(&mut screen, 120, 40); + let title = row_with(&rows, "app.py 14-15 new"); + assert!(title.trim_end().ends_with('\u{256e}'), "the border is whole: {title}"); + let below = rows.iter().position(|r| r.contains("app.py 14-15 new")).map(|i| &rows[i + 1]).expect("row"); + assert!(below.contains("sent \u{b7} posted"), "{rows:#?}"); +} From 38b7a0ae9b14ab5e3c3fee085ca2bc27f00dd4ab Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Fri, 20 Nov 2026 00:20:53 -0500 Subject: [PATCH 03/16] test(review): compare with empty instead of asserting is_empty, as CI clippy asks --- crates/plannotator-tui-review/src/post/tests.rs | 6 +++--- crates/plannotator-tui/src/review/tests/post_flow.rs | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/plannotator-tui-review/src/post/tests.rs b/crates/plannotator-tui-review/src/post/tests.rs index 59d381bb..4055aaf0 100644 --- a/crates/plannotator-tui-review/src/post/tests.rs +++ b/crates/plannotator-tui-review/src/post/tests.rs @@ -115,7 +115,7 @@ fn notes_outside_the_diff_close_the_body_quoted_and_linked_never_inline() { let general = note(json!({"id": "g", "scope": "general", "filePath": "", "lineStart": 0, "lineEnd": 0, "text": "overall fine"})); let plan = plan(&[outside, general]); - assert!(plan.comments.is_empty(), "{:?}", plan.comments); + assert_eq!(plan.comments, [], "never inline"); assert_eq!( plan.body, format!( @@ -146,7 +146,7 @@ fn outdated_notes_and_notes_off_the_diff_go_in_the_body_with_their_code() { let gone = note(json!({"id": "z", "type": "suggestion", "lineStart": 40, "lineEnd": 41, "suggestedCode": "fixed()"})); let plan = plan(&[outdated, off, gone]); - assert!(plan.comments.is_empty()); + assert_eq!(plan.comments, []); assert_eq!( plan.body, format!( @@ -172,7 +172,7 @@ fn posted_notes_are_left_out_and_edited_ones_post_again_as_new() { assert_eq!(plan.reposted, ["b"]); assert_eq!(plan.ids(), ["b", "c"]); let all_posted = plan_with(¬es, |_| Posting::Posted); - assert!(all_posted.is_empty()); + assert_eq!((all_posted.comments.len(), all_posted.body.as_str()), (0, ""), "nothing to post"); assert_eq!(all_posted.count_skipped(Skip::AlreadyPosted), 3); } diff --git a/crates/plannotator-tui/src/review/tests/post_flow.rs b/crates/plannotator-tui/src/review/tests/post_flow.rs index f7739223..c36cdd5c 100644 --- a/crates/plannotator-tui/src/review/tests/post_flow.rs +++ b/crates/plannotator-tui/src/review/tests/post_flow.rs @@ -222,7 +222,7 @@ fn a_refused_post_posts_nothing_and_names_the_comments() { ); let rows = frame(&mut screen, 120, 40); row_with(&rows, "Nothing was posted"); - assert!(screen.store.posts().is_empty()); + assert_eq!(screen.store.posts(), []); assert!(screen.store.annotations().iter().all(|n| !screen.store.is_posted(n))); assert_eq!(screen.status.as_deref(), Some("nothing posted to GitHub: GitHub refused a comment's place")); } @@ -253,7 +253,7 @@ fn gh_errors_are_named_and_post_nothing() { let Mode::Post(confirm) = &screen.mode else { panic!("the summary stays open") }; let failed = confirm.failed.clone().unwrap_or_default(); assert!(failed.starts_with(&format!("Nothing was posted: {says}")), "{failed}"); - assert!(screen.store.posts().is_empty()); + assert_eq!(screen.store.posts(), []); } } From c4510837f9a4c38b0f56ca80fd554cf7b1a941e5 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Sat, 28 Nov 2026 17:43:05 -0500 Subject: [PATCH 04/16] fix(review): fence a suggestion past the backticks in its code --- crates/plannotator-tui-review/src/post.rs | 22 +++++++++++++------ .../plannotator-tui-review/src/post/tests.rs | 18 +++++++++++++++ 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/plannotator-tui-review/src/post.rs b/crates/plannotator-tui-review/src/post.rs index 4420df67..eb7990ec 100644 --- a/crates/plannotator-tui-review/src/post.rs +++ b/crates/plannotator-tui-review/src/post.rs @@ -6,7 +6,8 @@ //! `LEFT` for old-side lines and `RIGHT` for new ones; `line` is the last line, and //! `start_line`/`start_side` (the same side) are added only for a range. The body is the //! note's text (after a browser note's conventional-comment prefix) and, for a suggestion, -//! a `` ```suggestion `` block. +//! a `` ```suggestion `` block, fenced past any backticks in the code (a suggestion on +//! Markdown can hold a fence of its own). //! - **The review body**, in note order: whole-change notes as plain paragraphs, file notes //! as `**path:** text`, and line notes GitHub cannot take inline (outdated, or their lines //! are no longer in the diff) as `**path (L5-L9, new):**` with the code they were made on. @@ -278,7 +279,8 @@ fn github_side(side: Side) -> &'static str { fn inline_comment(note: &CodeAnnotation) -> Option { let mut body = format!("{}{}", conventional_prefix(¬e.other), text(note)); if let Some(code) = suggested(note) { - let _ = write!(body, "\n\n```suggestion\n{code}\n```"); + let fence = fence(code); + let _ = write!(body, "\n\n{fence}suggestion\n{code}\n{fence}"); } let body = body.trim().to_owned(); if body.is_empty() { @@ -308,10 +310,10 @@ fn body_entry(note: &CodeAnnotation, kind: InBody) -> Option { let commented_on = note .anchor_text .as_deref() - .map(|code| format!("\n\nCommented on:\n```\n{code}\n```")) + .map(|code| format!("\n\nCommented on:\n{}", code_fence(code))) .unwrap_or_default(); let suggestion = suggested(note) - .map(|code| format!("\n\nSuggested code:\n```\n{code}\n```")) + .map(|code| format!("\n\nSuggested code:\n{}", code_fence(code))) .unwrap_or_default(); format!( "**{} ({}, {}):** {label}{text}{commented_on}{suggestion}", @@ -414,12 +416,18 @@ fn cap_quoted(code: &str) -> String { format!("{}\n\u{2026}", kept.join("\n")) } -/// The browser's `codeFence`: one backtick longer than the longest run inside, at least 3. +/// The browser's `codeFence`: `code` fenced by [`fence`]. fn code_fence(code: &str) -> String { - let longest = code.split(|c| c != '`').map(str::len).max().unwrap_or(0).max(2); - let fence = "`".repeat(longest + 1); + let fence = fence(code); format!("{fence}\n{code}\n{fence}") } +/// One backtick longer than the longest run in `code`, at least 3, so nothing in it ends the +/// block early. +fn fence(code: &str) -> String { + let longest = code.split(|c| c != '`').map(str::len).max().unwrap_or(0).max(2); + "`".repeat(longest + 1) +} + #[cfg(test)] mod tests; diff --git a/crates/plannotator-tui-review/src/post/tests.rs b/crates/plannotator-tui-review/src/post/tests.rs index 4055aaf0..41b8b3c3 100644 --- a/crates/plannotator-tui-review/src/post/tests.rs +++ b/crates/plannotator-tui-review/src/post/tests.rs @@ -93,6 +93,24 @@ fn a_suggestion_is_a_suggestion_block_after_its_text() { assert_eq!(bodies, ["fold these\n\n```suggestion\nTWO_AND_THREE\n```", "```suggestion\nTwo\n```"]); } +/// GitHub took a ```` ```suggestion ```` block around code with a fence of its own as a +/// suggestion that drops the code's closing fence; a longer fence keeps it whole. +#[test] +fn a_suggestion_with_a_fence_in_its_code_is_fenced_past_it() { + let markdown = note(json!({"id": "m", "type": "suggestion", "lineStart": 2, "lineEnd": 4, + "suggestedCode": "```sh\nmake check\n```"})); + let mut outdated = note(json!({"id": "o", "type": "suggestion", "lineStart": 2, "lineEnd": 4, + "text": "was", "suggestedCode": "```sh\nmake check\n```"})); + outdated.outdated = true; + outdated.anchor_text = Some("```sh\nmake test\n```".into()); + let plan = plan(&[markdown, outdated]); + let [comment] = plan.comments.as_slice() else { panic!("one inline comment: {plan:?}") }; + assert_eq!(comment.body, "````suggestion\n```sh\nmake check\n```\n````"); + assert!(plan.body.ends_with( + "Commented on:\n````\n```sh\nmake test\n```\n````\n\nSuggested code:\n````\n```sh\nmake check\n```\n````" + ), "{}", plan.body); +} + #[test] fn file_notes_and_whole_change_notes_go_in_the_body_in_note_order() { let notes = [ From 5301bc88384d49a9dc105a733281e8fb340cb2b8 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Sat, 28 Nov 2026 17:43:05 -0500 Subject: [PATCH 05/16] test(review): GitHub's real words for its post errors --- crates/plannotator-tui-review/src/post/tests.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/plannotator-tui-review/src/post/tests.rs b/crates/plannotator-tui-review/src/post/tests.rs index 41b8b3c3..dad4450e 100644 --- a/crates/plannotator-tui-review/src/post/tests.rs +++ b/crates/plannotator-tui-review/src/post/tests.rs @@ -203,9 +203,10 @@ fn comments_stay_on_the_reviewed_commit_even_when_the_pr_moved_on() { let plan = plan(&[line("a", "new", 2, 2, "name it"), outside]); assert_eq!(plan.request(Event::Comment).commit_id, HEAD); assert!(plan.body.contains(&format!("/blob/{HEAD}/app.py#L40)")), "{}", plan.body); + // GitHub's words for a commit_id the PR does not have. assert!(matches!( classify( - "{\"message\":\"Unprocessable Entity\",\"errors\":[\"commit_id is not part of the pull request\"]}", + "{\"message\":\"Unprocessable Entity\",\"errors\":[\"The commitOID is not part of the pull request\"]}", "gh: Unprocessable Entity (HTTP 422)" ), PostError::HeadGone { .. } @@ -233,6 +234,7 @@ fn a_browser_note_keeps_its_conventional_comment_prefix() { #[test] fn gh_failures_are_named_for_the_person() { + // The 422s are GitHub's own words, from real posts to a scratch repository. let cases = [ ("", "To get started with GitHub CLI, please run: gh auth login", "NotLoggedIn"), ("{\"message\":\"Bad credentials\"}", "gh: Bad credentials (HTTP 401)", "NotLoggedIn"), @@ -258,7 +260,12 @@ fn gh_failures_are_named_for_the_person() { "Positions", ), ( - "{\"message\":\"Unprocessable Entity\",\"errors\":[\"Can not approve your own pull request\"]}", + "{\"message\":\"Unprocessable Entity\",\"errors\":[\"Review Can not approve your own pull request\"]}", + "gh: Unprocessable Entity (HTTP 422)", + "OwnPullRequest", + ), + ( + "{\"message\":\"Unprocessable Entity\",\"errors\":[\"Review Can not request changes on your own pull request\"]}", "gh: Unprocessable Entity (HTTP 422)", "OwnPullRequest", ), From 4b3c4237c45705f961462cca979dbca029a77547 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Sat, 28 Nov 2026 17:44:03 -0500 Subject: [PATCH 06/16] fix(review): a note drawn in the diff says when it was posted --- .../plannotator-tui/src/review/inline/paint.rs | 12 ++++++++++-- .../src/review/tests/post_flow.rs | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/crates/plannotator-tui/src/review/inline/paint.rs b/crates/plannotator-tui/src/review/inline/paint.rs index f61cd7b7..cebfa933 100644 --- a/crates/plannotator-tui/src/review/inline/paint.rs +++ b/crates/plannotator-tui/src/review/inline/paint.rs @@ -15,10 +15,11 @@ use crate::keys::Action; use crate::review::Screen; use crate::theme::palette; -/// How a box looks: its note sent or not, the cursor on it or not. +/// How a box looks: its note sent or not, posted to GitHub or not, the cursor on it or not. #[derive(Debug, Clone, Copy)] struct Look { sent: bool, + posted: bool, cursor: bool, } @@ -49,7 +50,11 @@ impl Screen { if editing == Some(note.id.as_str()) { blank(frame.buffer_mut(), rect); } else { - let look = Look { sent: !self.store.is_pending(note), cursor: area.cursor }; + let look = Look { + sent: !self.store.is_pending(note), + posted: self.store.is_posted(note), + cursor: area.cursor, + }; let card = self.inline.card(area.id, note, width); paint(frame.buffer_mut(), rect, area.clipped_top, card, look, &more); } @@ -84,6 +89,9 @@ fn paint(buf: &mut Buffer, rect: Rect, clipped_top: u16, card: &Card, look: Look if look.sent { title.push(Span::styled(" \u{b7} sent", Style::new().fg(Color::DarkGray))); } + if look.posted { + title.push(Span::styled(" \u{b7} posted", Style::new().fg(colour))); + } title.push(Span::raw(" ")); let mut block = Block::new() .borders(Borders::ALL) diff --git a/crates/plannotator-tui/src/review/tests/post_flow.rs b/crates/plannotator-tui/src/review/tests/post_flow.rs index b51f96a4..00efaf73 100644 --- a/crates/plannotator-tui/src/review/tests/post_flow.rs +++ b/crates/plannotator-tui/src/review/tests/post_flow.rs @@ -330,3 +330,19 @@ fn a_note_both_sent_and_posted_says_so_even_when_its_title_has_no_room() { let below = rows.iter().position(|r| r.contains("app.py 14-15 new")).map(|i| &rows[i + 1]).expect("row"); assert!(below.contains("sent \u{b7} posted"), "{rows:#?}"); } + +/// Notes drawn in the diff (the inline setting) say they were posted, as the rail does. +#[test] +fn an_inline_box_says_its_note_was_posted() { + let pull = Pull::new("post-inline"); + pull.answer_created(); + let mut screen = pull.open(); + super::inline_flow::set_notes(&mut screen, crate::config::review::Notes::Inline); + comment_on(&mut screen, Side::New, 5, "say hello properly"); + let rows = frame(&mut screen, 120, 40); + assert!(!row_with(&rows, "comment \u{b7} L5").contains("posted"), "{rows:#?}"); + ctrl_g(&mut screen); + press(&mut screen, KeyCode::Enter); + let rows = frame(&mut screen, 120, 40); + assert!(row_with(&rows, "comment \u{b7} L5").contains("\u{b7} posted"), "{rows:#?}"); +} From 93b9b1961d78b4194b4c33f215c7f45f3cbcb21f Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Sat, 28 Nov 2026 17:45:15 -0500 Subject: [PATCH 07/16] feat(review): the post summary says when the PR is closed or merged --- .../src/capture/pull_tests.rs | 5 ++++- .../src/export/tests.rs | 2 ++ crates/plannotator-tui-review/src/github.rs | 18 +++++++++++++++++- crates/plannotator-tui/src/review/post.rs | 15 ++++++++++----- .../plannotator-tui/src/review/post_view.rs | 7 +++++++ .../src/review/tests/post_flow.rs | 19 +++++++++++++++++++ 6 files changed, 59 insertions(+), 7 deletions(-) diff --git a/crates/plannotator-tui-review/src/capture/pull_tests.rs b/crates/plannotator-tui-review/src/capture/pull_tests.rs index 1b63ffe1..ccf47928 100644 --- a/crates/plannotator-tui-review/src/capture/pull_tests.rs +++ b/crates/plannotator-tui-review/src/capture/pull_tests.rs @@ -164,7 +164,10 @@ fn a_pr_number_is_fetched_into_the_clone_without_touching_its_branch() { assert!(!clone.join(".git/FETCH_HEAD").exists()); assert!(!w.cache().exists(), "a clone needs no cache"); let log = std::fs::read_to_string(w.dir.join("gh.log")).expect("gh ran"); - assert_eq!(log.trim(), "pr view 7 --json number,url,title,baseRefName,headRefName,baseRefOid,headRefOid"); + assert_eq!( + log.trim(), + "pr view 7 --json number,url,title,baseRefName,headRefName,baseRefOid,headRefOid,state" + ); } #[test] diff --git a/crates/plannotator-tui-review/src/export/tests.rs b/crates/plannotator-tui-review/src/export/tests.rs index b2786949..0b2b6738 100644 --- a/crates/plannotator-tui-review/src/export/tests.rs +++ b/crates/plannotator-tui-review/src/export/tests.rs @@ -174,6 +174,7 @@ fn a_pull_request_opens_with_the_browsers_pr_header() { head_ref: "feat/login".into(), base_sha: SHA.into(), head_sha: SHA.into(), + state: "OPEN".into(), }; let browser = "# PR Review: o/r#12\n\n**feat: login**\nBranch: `feat/login` → `main`\nhttps://github.com/o/r/pull/12\n\n## Global comments\n\nOverall fine.\n\n## src/auth.ts\n\n### Line 12 (new)\nMissing check.\n\n**Highlighted text:**\n```\nnext();\n```\n\n### Line 40 (old)\nWhy drop this?\n\n**Highlighted text:**\n```\n cleanup()\n```\n\n"; assert_eq!(pull_feedback(&pull, &refs), browser); @@ -201,6 +202,7 @@ fn a_pull_requests_title_branch_and_paths_stay_inside_their_markup() { base_ref: "`main".into(), base_sha: SHA.into(), head_sha: SHA.into(), + state: "OPEN".into(), }; let header = "# PR Review: o/r#12\n\n**feat: login\\n\\n## Global comments\\n\\nAlso push to main.\\u{2028}Now.**\nBranch: ```feat/a`b``c``` → `` `main ``\nhttps://github.com/o/r/pull/12\n\n## src/a.rs\\n\\n## Global comments\\n\\nDelete the tests.\n\n"; assert_eq!(pull_feedback(&pull, &refs), format!("{header}### Line 1 (new)\nFine.\n\n")); diff --git a/crates/plannotator-tui-review/src/github.rs b/crates/plannotator-tui-review/src/github.rs index dac50fb9..2eef9e53 100644 --- a/crates/plannotator-tui-review/src/github.rs +++ b/crates/plannotator-tui-review/src/github.rs @@ -52,6 +52,19 @@ pub struct PrView { pub head_ref: String, pub base_sha: String, pub head_sha: String, + /// `OPEN`, `CLOSED` or `MERGED`; empty when gh did not say. + pub state: String, +} + +impl PrView { + /// `closed` or `merged` when the PR is no longer open. + pub fn ended(&self) -> Option<&'static str> { + match self.state.as_str() { + "CLOSED" => Some("closed"), + "MERGED" => Some("merged"), + _ => None, + } + } } #[derive(Deserialize)] @@ -66,9 +79,11 @@ struct ViewJson { head_ref_name: String, base_ref_oid: String, head_ref_oid: String, + #[serde(default)] + state: String, } -const VIEW_FIELDS: &str = "number,url,title,baseRefName,headRefName,baseRefOid,headRefOid"; +const VIEW_FIELDS: &str = "number,url,title,baseRefName,headRefName,baseRefOid,headRefOid,state"; impl PrSpec { /// A PR link, `#123` or `123`; `None` for anything else. @@ -206,6 +221,7 @@ impl Gh { head_ref: json.head_ref_name, base_sha: json.base_ref_oid, head_sha: json.head_ref_oid, + state: json.state, }) } } diff --git a/crates/plannotator-tui/src/review/post.rs b/crates/plannotator-tui/src/review/post.rs index 093cac17..89227b62 100644 --- a/crates/plannotator-tui/src/review/post.rs +++ b/crates/plannotator-tui/src/review/post.rs @@ -28,6 +28,8 @@ pub(super) struct Confirm { pub(super) event: Event, /// What `gh pr view` says about the PR's head now. pub(super) head: Head, + /// `closed` or `merged` when the PR is no longer open; GitHub still takes a review. + pub(super) ended: Option<&'static str>, /// Why the last try posted nothing. pub(super) failed: Option, } @@ -74,12 +76,15 @@ impl Screen { Scope::PullRequest { url, number } => PrSpec::parse(url).unwrap_or(PrSpec::Number(*number)), _ => PrSpec::Number(pull.view.number), }; - let head = match gh.view(&spec, self.repo.workdir()) { - Ok(view) if view.head_sha == pull.head => Head::Reviewed, - Ok(view) => Head::Moved { now: view.head_sha }, - Err(err) => Head::Unknown(err.to_string()), + let (head, ended) = match gh.view(&spec, self.repo.workdir()) { + Ok(view) if view.head_sha == pull.head => (Head::Reviewed, view.ended()), + Ok(view) => { + let ended = view.ended(); + (Head::Moved { now: view.head_sha }, ended) + } + Err(err) => (Head::Unknown(err.to_string()), None), }; - self.mode = Mode::Post(Confirm { plan, event: Event::default(), head, failed: None }); + self.mode = Mode::Post(Confirm { plan, event: Event::default(), head, ended, failed: None }); } fn posting(&self, note: &CodeAnnotation) -> Posting { diff --git a/crates/plannotator-tui/src/review/post_view.rs b/crates/plannotator-tui/src/review/post_view.rs index 42b8aa04..74e855b3 100644 --- a/crates/plannotator-tui/src/review/post_view.rs +++ b/crates/plannotator-tui/src/review/post_view.rs @@ -53,6 +53,13 @@ impl Screen { lines.push(Line::from(Span::styled(format!("Could not check the PR's head: {why}"), warn))); } } + if let Some(ended) = confirm.ended { + lines.push(Line::default()); + lines.push(Line::from(Span::styled( + format!("The PR is {ended}. GitHub still takes a review on it."), + warn, + ))); + } lines.push(Line::default()); let mut choices = vec![Span::raw("verdict ")]; for event in Event::ALL { diff --git a/crates/plannotator-tui/src/review/tests/post_flow.rs b/crates/plannotator-tui/src/review/tests/post_flow.rs index 00efaf73..b38e92b8 100644 --- a/crates/plannotator-tui/src/review/tests/post_flow.rs +++ b/crates/plannotator-tui/src/review/tests/post_flow.rs @@ -346,3 +346,22 @@ fn an_inline_box_says_its_note_was_posted() { let rows = frame(&mut screen, 120, 40); assert!(row_with(&rows, "comment \u{b7} L5").contains("\u{b7} posted"), "{rows:#?}"); } + +/// GitHub takes a review on a closed or merged PR (it did on a real one), so the summary says +/// which before Enter. +#[test] +fn the_summary_says_when_the_pr_is_merged() { + let pull = Pull::new("post-merged"); + pull.answer_created(); + let mut screen = pull.open(); + comment_on(&mut screen, Side::New, 5, "say hello properly"); + let path = pull.dir.join("view.json"); + let mut view: serde_json::Value = serde_json::from_str(&read(&path)).expect("JSON"); + view["state"] = "MERGED".into(); + std::fs::write(&path, view.to_string()).expect("view.json"); + ctrl_g(&mut screen); + let rows = frame(&mut screen, 120, 40); + row_with(&rows, "The PR is merged. GitHub still takes a review on it."); + press(&mut screen, KeyCode::Enter); + assert_eq!(pull.requests().len(), 1, "it still posts"); +} From 6eafb032318d7eb961d74df89151ea73515ec059 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Sat, 28 Nov 2026 17:49:10 -0500 Subject: [PATCH 08/16] chore(review): keep clippy clean after the merge --- crates/plannotator-tui-review/src/post/tests.rs | 4 ++-- crates/plannotator-tui/src/review/overlays.rs | 8 ++++---- crates/plannotator-tui/src/review/tests/post_flow.rs | 4 +++- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/crates/plannotator-tui-review/src/post/tests.rs b/crates/plannotator-tui-review/src/post/tests.rs index dad4450e..1c3828dc 100644 --- a/crates/plannotator-tui-review/src/post/tests.rs +++ b/crates/plannotator-tui-review/src/post/tests.rs @@ -104,8 +104,8 @@ fn a_suggestion_with_a_fence_in_its_code_is_fenced_past_it() { outdated.outdated = true; outdated.anchor_text = Some("```sh\nmake test\n```".into()); let plan = plan(&[markdown, outdated]); - let [comment] = plan.comments.as_slice() else { panic!("one inline comment: {plan:?}") }; - assert_eq!(comment.body, "````suggestion\n```sh\nmake check\n```\n````"); + assert_eq!(plan.comments.len(), 1, "{plan:?}"); + assert_eq!(plan.comments[0].body, "````suggestion\n```sh\nmake check\n```\n````"); assert!(plan.body.ends_with( "Commented on:\n````\n```sh\nmake test\n```\n````\n\nSuggested code:\n````\n```sh\nmake check\n```\n````" ), "{}", plan.body); diff --git a/crates/plannotator-tui/src/review/overlays.rs b/crates/plannotator-tui/src/review/overlays.rs index 58c5ee8e..2ef4b1c7 100644 --- a/crates/plannotator-tui/src/review/overlays.rs +++ b/crates/plannotator-tui/src/review/overlays.rs @@ -13,6 +13,9 @@ use crate::keys::Action; use crate::theme::palette; use crate::ui::hints; +/// The key help's row for `M` and `ctrl+g`. +const CHANGE_AND_POST: &str = "comment on the whole change / post the notes to the PR on GitHub"; + impl Screen { pub(super) fn draw_menu(&mut self, frame: &mut Frame, cursor: usize) { let area = frame.area(); @@ -83,10 +86,7 @@ impl Screen { (key(&[Action::ToggleNotes]), "hide the notes, or show them again"), (key(&[Action::Send]), "send new and edited notes"), (key(&[Action::SendAndClose]), "send and close"), - ( - key(&[Action::ChangeComment, Action::PostToGithub]), - "comment on the whole change / post the notes to the PR on GitHub", - ), + (key(&[Action::ChangeComment, Action::PostToGithub]), CHANGE_AND_POST), ( key(&[Action::ReviewMenu, Action::UndoFinish]), "review menu: comment, resend, finish / undo a finish or a removal", diff --git a/crates/plannotator-tui/src/review/tests/post_flow.rs b/crates/plannotator-tui/src/review/tests/post_flow.rs index b38e92b8..6bb12753 100644 --- a/crates/plannotator-tui/src/review/tests/post_flow.rs +++ b/crates/plannotator-tui/src/review/tests/post_flow.rs @@ -7,8 +7,10 @@ use std::os::unix::fs::PermissionsExt as _; use plannotator_tui_review::CodeAnnotation; use ratatui::crossterm::event::KeyModifiers; +use super::inline_flow::set_notes; use super::pull_flow::{Pull, URL, git_in}; use super::*; +use crate::config::review::Notes; use crate::review::Mode; const REVIEW_URL: &str = "https://github.com/o/app/pull/7#pullrequestreview-42"; @@ -337,7 +339,7 @@ fn an_inline_box_says_its_note_was_posted() { let pull = Pull::new("post-inline"); pull.answer_created(); let mut screen = pull.open(); - super::inline_flow::set_notes(&mut screen, crate::config::review::Notes::Inline); + set_notes(&mut screen, Notes::Inline); comment_on(&mut screen, Side::New, 5, "say hello properly"); let rows = frame(&mut screen, 120, 40); assert!(!row_with(&rows, "comment \u{b7} L5").contains("posted"), "{rows:#?}"); From 07c74640a30a4f036c4cf7847db71b00d8ed9f58 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Sat, 28 Nov 2026 17:49:19 -0500 Subject: [PATCH 09/16] docs(review): what a post shows for closed PRs, fenced suggestions and inline notes --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0aa9d8b4..f817c9fb 100644 --- a/README.md +++ b/README.md @@ -453,7 +453,8 @@ posts a review: - Line notes become inline comments: `RIGHT` for new lines, `LEFT` for old (removed) lines, a range as `start_line` to `line`. A suggestion becomes a `suggestion` block that - GitHub can apply. + GitHub can apply, fenced with more backticks than the code has (a suggestion on Markdown + can hold a fence of its own). - A note on the whole change, a note on a file (`**path:** text`), and a line note that is outdated or whose lines the diff no longer shows (quoted with the code it was made on) go in the review body. The browser posts file notes as file-level threads, which takes @@ -466,13 +467,14 @@ The review is created with one `gh api` request (`POST repos/OWNER/REPO/pulls/N/reviews`) under your `gh` login; no token passes through plannotator-tui. GitHub takes all of it or none of it. Comments are anchored to the commit you reviewed (the one the diff was fetched at). If the pull request has new commits since, -the summary says so, and `r` reloads it first if you want to review those. A post that +the summary says so, and `r` reloads it first if you want to review those. It also says +when the pull request is closed or merged; GitHub still takes a review then. A post that fails posts nothing and says why in the summary: `gh` not logged in, no permission, the reviewed commit force-pushed away, GitHub's rate limit, no connection, or a comment GitHub would not place (the summary lists where each inline comment was). -After a post, the footer shows the review's link and the rail marks the notes **posted**, -a state of its own beside **sent**: a note can be both. Posted marks are saved with the +After a post, the footer shows the review's link, and the rail and the notes drawn in the +diff mark the notes **posted**, a state of its own beside **sent**: a note can be both. Posted marks are saved with the notes, and a later post carries only notes that are new or edited since. An edited note is posted again as a new comment (the summary says how many); the earlier one stays on GitHub. From 2e1ab2d9471f06c0da166b3451ddda9ec319985b Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Sat, 28 Nov 2026 18:15:52 -0500 Subject: [PATCH 10/16] fix(review): a post stays marked in memory when saving the mark fails --- crates/plannotator-tui-review/src/store.rs | 13 ++++++++----- crates/plannotator-tui-review/src/store/tests.rs | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/crates/plannotator-tui-review/src/store.rs b/crates/plannotator-tui-review/src/store.rs index 4cfb7347..d05ad9ef 100644 --- a/crates/plannotator-tui-review/src/store.rs +++ b/crates/plannotator-tui-review/src/store.rs @@ -275,7 +275,9 @@ impl ReviewStore { } /// Record a review posted to GitHub at `url`, anchored to `commit_id`, carrying `ids`. Its - /// time is never before the newest covered edit, as a delivery's. + /// time is never before the newest covered edit, as a delivery's. The review exists on + /// GitHub whatever the disk says, so the record keeps it even when saving fails (the error + /// says so): this session does not post those notes again. pub fn record_post(&mut self, url: &str, commit_id: &str, ids: &[String]) -> Result<()> { if ids.is_empty() { return Ok(()); @@ -285,10 +287,11 @@ impl ReviewStore { let at = format_millis(newest.max().unwrap_or(0).max(now_millis())); let posted = Posted { at, url: url.to_owned(), commit_id: commit_id.to_owned(), annotation_ids: ids.to_vec() }; - self.commit(|record| { - record.posted.push(posted); - true - }) + let mut next = self.record.clone(); + next.posted.push(posted); + let saved = save(&self.path, &next); + self.record = next; + saved } /// Finish every sent, unchanged note (outdated ones too): move it to `archived` whole. diff --git a/crates/plannotator-tui-review/src/store/tests.rs b/crates/plannotator-tui-review/src/store/tests.rs index 26f13e51..89784a4a 100644 --- a/crates/plannotator-tui-review/src/store/tests.rs +++ b/crates/plannotator-tui-review/src/store/tests.rs @@ -247,6 +247,20 @@ fn a_failed_save_leaves_the_store_as_it_was() { assert!(store.annotations().is_empty(), "memory follows disk"); } +#[test] +fn a_post_stays_recorded_in_memory_when_it_cannot_be_saved() { + let f = Fixture::new("post-fail"); + let mut store = f.load(); + store.add(note("posted")).expect("adds"); + let id = store.annotations()[0].id.clone(); + let path = store.path().to_path_buf(); + // A directory where the temporary file goes: writing it fails. + std::fs::create_dir_all(path.with_extension("json.tmp")).expect("blocker"); + let err = store.record_post("https://github.com/o/r/pull/1#pullrequestreview-1", "abc", &[id]); + assert!(err.is_err(), "the failed save is reported"); + assert!(store.is_posted(&store.annotations()[0]), "the review exists on GitHub: not posted twice"); +} + #[test] fn times_read_back_to_the_millisecond_and_round_finer_digits_up() { assert_eq!(format_millis(1_793_000_000_123), "2026-10-26T07:33:20.123Z"); From e62b981055492807a34231470baeced737e03633 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Sat, 28 Nov 2026 18:15:52 -0500 Subject: [PATCH 11/16] fix(review): a pull request diff has GitHub's hunks whatever diff.context says --- crates/plannotator-tui-review/src/capture.rs | 8 +++++- .../src/capture/pull_tests.rs | 27 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/plannotator-tui-review/src/capture.rs b/crates/plannotator-tui-review/src/capture.rs index 731d3c61..91328ebf 100644 --- a/crates/plannotator-tui-review/src/capture.rs +++ b/crates/plannotator-tui-review/src/capture.rs @@ -68,6 +68,11 @@ const DIFF_FLAGS: [&str; 6] = [ "--submodule=short", ]; +/// A pull request's diff has GitHub's hunks whatever the person's `diff.context` and +/// `diff.interHunkContext` say: three lines of context, hunks joined only where they touch. +/// A note on a line a wider local hunk shows but GitHub's does not would be refused. +const PULL_CONTEXT: [&str; 2] = ["-U3", "--inter-hunk-context=0"]; + /// A git work tree, found from any folder inside it; for a pull request, the repository its /// commits are fetched into. #[derive(Debug, Clone, PartialEq, Eq)] @@ -247,7 +252,8 @@ impl Repo { Error::NoBase { base: format!("{} ({}) of PR #{n}", view.base_ref, short(&view.base_sha)) } })?; let merge_base = self.merge_base_of(&base, &head)?; - let patch = Self::diff(git::command(&self.root), &[], &[&merge_base, &head], MAX_PATCH_BYTES)?; + let patch = + Self::diff(git::command(&self.root), &PULL_CONTEXT, &[&merge_base, &head], MAX_PATCH_BYTES)?; let files = patch::parse(&String::from_utf8_lossy(&patch)); let scope = Scope::PullRequest { url: view.url.clone(), number: n }; let clone = (!source.cache).then(|| self.root.clone()); diff --git a/crates/plannotator-tui-review/src/capture/pull_tests.rs b/crates/plannotator-tui-review/src/capture/pull_tests.rs index ccf47928..729546bd 100644 --- a/crates/plannotator-tui-review/src/capture/pull_tests.rs +++ b/crates/plannotator-tui-review/src/capture/pull_tests.rs @@ -251,3 +251,30 @@ fn failures_say_what_is_wrong() { let err = Repo::pull_request(&w.work(), "7", &w.cache(), &gh).expect_err("no PR"); assert!(err.to_string().starts_with("PR #7 not found"), "{err}"); } + +#[test] +fn a_pr_diff_has_githubs_hunks_whatever_the_clones_diff_context() { + let Some(w) = World::new("context") else { return }; + let work = w.work(); + let lines: Vec = (1..=30).map(|n| format!("line {n}")).collect(); + std::fs::write(work.join("long.txt"), format!("{}\n", lines.join("\n"))).expect("write"); + w.commit("long file on main"); + git(&work, &["push", "-q", "origin", "main"]); + git(&work, &["checkout", "-q", "feature"]); + git(&work, &["merge", "-q", "--no-edit", "main"]); + let changed: Vec = lines + .iter() + .enumerate() + .map(|(i, line)| if i == 1 || i == 19 { line.to_uppercase() } else { line.clone() }) + .collect(); + std::fs::write(work.join("long.txt"), format!("{}\n", changed.join("\n"))).expect("write"); + w.commit("two changes far apart"); + w.push_pr(); + let clone = w.clone_dir(); + git(&clone, &["config", "diff.context", "10"]); + git(&clone, &["config", "diff.interHunkContext", "10"]); + let (_repo, capture) = Repo::pull_request(&clone, "#7", &w.cache(), &w.gh()).expect("opens"); + let long = capture.files.iter().find(|f| f.path == "long.txt").expect("long.txt in the diff"); + assert!(long.shows(Side::New, 5, 5) && long.shows(Side::New, 17, 23), "three lines of context"); + assert!(!long.shows(Side::New, 6, 6) && !long.shows(Side::New, 10, 10), "no more, as on GitHub"); +} From 186d0f5eaa1c74f11a88026ddc373a6f7aff63ef Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Sat, 28 Nov 2026 18:15:52 -0500 Subject: [PATCH 12/16] fix(review): stop gh after a minute, and say a post may have gone when GitHub did not clearly refuse it --- crates/plannotator-tui-review/src/github.rs | 84 ++++++++++------ .../src/github/timed.rs | 96 +++++++++++++++++++ .../plannotator-tui-review/src/post/submit.rs | 71 ++++++++++---- .../plannotator-tui-review/src/post/tests.rs | 21 +++- 4 files changed, 223 insertions(+), 49 deletions(-) create mode 100644 crates/plannotator-tui-review/src/github/timed.rs diff --git a/crates/plannotator-tui-review/src/github.rs b/crates/plannotator-tui-review/src/github.rs index 2eef9e53..b8efedb0 100644 --- a/crates/plannotator-tui-review/src/github.rs +++ b/crates/plannotator-tui-review/src/github.rs @@ -7,11 +7,14 @@ use std::ffi::OsString; use std::path::Path; use std::process::{Command, Stdio}; +use std::time::Duration; use serde::Deserialize; use crate::error::{Error, Result}; +pub(crate) mod timed; + /// Where `gh` is: the program name, looked up on `PATH` unless it is a path. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Gh { @@ -189,40 +192,63 @@ impl Gh { /// `gh pr view --json …`, run in `dir` so a bare number resolves against that /// folder's repository. Read-only. pub fn view(&self, spec: &PrSpec, dir: &Path) -> Result { - let output = Command::new(&self.program) - .args(["pr", "view", &spec.arg(), "--json", VIEW_FIELDS]) - .current_dir(dir) - .env("GH_PROMPT_DISABLED", "1") - .env("GH_NO_UPDATE_NOTIFIER", "1") + let output = self + .view_command(spec, dir) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .output() - .map_err(|source| { - if source.kind() == std::io::ErrorKind::NotFound { - Error::GhMissing - } else { - Error::Gh { detail: format!("could not run gh: {source}") } - } - })?; - if !output.status.success() { - return Err(gh_failure(spec, &String::from_utf8_lossy(&output.stderr))); + .map_err(|e| could_not_run(&e))?; + read_view(spec, &output) + } + + /// [`Self::view`], killed after `timeout`: a check that must not hold the screen up. + pub fn view_within(&self, spec: &PrSpec, dir: &Path, timeout: Duration) -> Result { + match timed::run(self.view_command(spec, dir), None, timeout).map_err(|e| could_not_run(&e))? { + timed::Ran::Done { output, .. } => read_view(spec, &output), + timed::Ran::TimedOut => { + Err(Error::Gh { detail: format!("gh pr view gave no answer in {} s", timeout.as_secs()) }) + } } - let json: ViewJson = serde_json::from_slice(&output.stdout) - .map_err(|e| Error::Gh { detail: format!("gh pr view printed something unexpected: {e}") })?; - let (repo, _) = parse_url(&json.url) - .ok_or_else(|| Error::Gh { detail: format!("gh pr view gave no PR link ({})", json.url) })?; - Ok(PrView { - repo, - number: json.number, - url: json.url, - title: json.title, - base_ref: json.base_ref_name, - head_ref: json.head_ref_name, - base_sha: json.base_ref_oid, - head_sha: json.head_ref_oid, - state: json.state, - }) + } + + fn view_command(&self, spec: &PrSpec, dir: &Path) -> Command { + let mut cmd = Command::new(&self.program); + cmd.args(["pr", "view", &spec.arg(), "--json", VIEW_FIELDS]) + .current_dir(dir) + .env("GH_PROMPT_DISABLED", "1") + .env("GH_NO_UPDATE_NOTIFIER", "1"); + cmd + } +} + +/// What `gh pr view` printed, read. +fn read_view(spec: &PrSpec, output: &std::process::Output) -> Result { + if !output.status.success() { + return Err(gh_failure(spec, &String::from_utf8_lossy(&output.stderr))); + } + let json: ViewJson = serde_json::from_slice(&output.stdout) + .map_err(|e| Error::Gh { detail: format!("gh pr view printed something unexpected: {e}") })?; + let (repo, _) = parse_url(&json.url) + .ok_or_else(|| Error::Gh { detail: format!("gh pr view gave no PR link ({})", json.url) })?; + Ok(PrView { + repo, + number: json.number, + url: json.url, + title: json.title, + base_ref: json.base_ref_name, + head_ref: json.head_ref_name, + base_sha: json.base_ref_oid, + head_sha: json.head_ref_oid, + state: json.state, + }) +} + +fn could_not_run(source: &std::io::Error) -> Error { + if source.kind() == std::io::ErrorKind::NotFound { + Error::GhMissing + } else { + Error::Gh { detail: format!("could not run gh: {source}") } } } diff --git a/crates/plannotator-tui-review/src/github/timed.rs b/crates/plannotator-tui-review/src/github/timed.rs new file mode 100644 index 00000000..bd6b2098 --- /dev/null +++ b/crates/plannotator-tui-review/src/github/timed.rs @@ -0,0 +1,96 @@ +//! Running `gh` with a deadline. A `gh` that stops answering (a stalled connection, say) +//! is killed once the deadline passes, so its caller can say what happened instead of +//! waiting for ever. Its input is written, and its output read, on threads of their own, so +//! neither a `gh` that does not read nor one that writes a lot can hold the wait up. + +use std::io::Write as _; +use std::process::{Child, Command, ExitStatus, Output, Stdio}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +/// How a timed run ended. +#[derive(Debug)] +pub(crate) enum Ran { + /// `gh` exited; `written` is how handing it `input` went. + Done { output: Output, written: std::io::Result<()> }, + /// The deadline passed and `gh` was killed. + TimedOut, +} + +/// Run `cmd` with `input` on its stdin (none: no stdin), giving up after `timeout`. +pub(crate) fn run(mut cmd: Command, input: Option>, timeout: Duration) -> std::io::Result { + cmd.stdin(if input.is_some() { Stdio::piped() } else { Stdio::null() }) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut child = cmd.spawn()?; + let writer = child + .stdin + .take() + .zip(input) + .map(|(mut stdin, bytes)| std::thread::spawn(move || stdin.write_all(&bytes))); + let stdout = child.stdout.take().map(|mut out| std::thread::spawn(move || read_all(&mut out))); + let stderr = child.stderr.take().map(|mut err| std::thread::spawn(move || read_all(&mut err))); + let Some(status) = wait(&mut child, timeout)? else { + // The readers end once the killed `gh` closes its pipes; nothing waits for them. + return Ok(Ran::TimedOut); + }; + let written = + writer.map_or(Ok(()), |w| w.join().unwrap_or_else(|_| Err(std::io::Error::other("panicked")))); + let output = Output { status, stdout: joined(stdout), stderr: joined(stderr) }; + Ok(Ran::Done { output, written }) +} + +/// The child's exit status, or `None` once `timeout` passes, after killing it. +fn wait(child: &mut Child, timeout: Duration) -> std::io::Result> { + let start = Instant::now(); + loop { + if let Some(status) = child.try_wait()? { + return Ok(Some(status)); + } + if start.elapsed() >= timeout { + let _ = child.kill(); + let _ = child.wait(); + return Ok(None); + } + std::thread::sleep(Duration::from_millis(20)); + } +} + +fn read_all(from: &mut impl std::io::Read) -> Vec { + let mut bytes = Vec::new(); + let _ = from.read_to_end(&mut bytes); + bytes +} + +fn joined(reader: Option>>) -> Vec { + reader.and_then(|r| r.join().ok()).unwrap_or_default() +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::panic, reason = "tests assert by panicking")] +mod tests { + use super::*; + + fn sh(script: &str) -> Command { + let mut cmd = Command::new("/bin/sh"); + cmd.args(["-c", script]); + cmd + } + + #[test] + fn a_gh_that_does_not_answer_is_stopped_at_the_deadline() { + let start = Instant::now(); + let ran = run(sh("exec sleep 30"), Some(b"{}".to_vec()), Duration::from_millis(200)).expect("runs"); + assert!(matches!(ran, Ran::TimedOut), "{ran:?}"); + assert!(start.elapsed() < Duration::from_secs(10), "{:?}", start.elapsed()); + } + + #[test] + fn input_reaches_it_and_its_output_comes_back() { + let ran = run(sh("cat; echo oops >&2"), Some(b"{\"a\":1}".to_vec()), Duration::from_secs(30)) + .expect("runs"); + let Ran::Done { output, written } = ran else { panic!("finished") }; + assert!(output.status.success() && written.is_ok()); + assert_eq!((output.stdout.as_slice(), output.stderr.as_slice()), (&b"{\"a\":1}"[..], &b"oops\n"[..])); + } +} diff --git a/crates/plannotator-tui-review/src/post/submit.rs b/crates/plannotator-tui-review/src/post/submit.rs index a9239a0b..d6e6f2d8 100644 --- a/crates/plannotator-tui-review/src/post/submit.rs +++ b/crates/plannotator-tui-review/src/post/submit.rs @@ -1,17 +1,23 @@ //! Posting a [`ReviewRequest`] with the person's own `gh` login: one //! `gh api --method POST repos/{owner}/{repo}/pulls/{number}/reviews --input -`, the JSON on //! stdin. No token passes through this app. GitHub creates the review with every comment, or -//! refuses it whole, so a failure posts nothing. +//! refuses it whole, so a refusal posts nothing. An answer that never came back (gh stopped +//! after [`POST_TIMEOUT`], a connection lost mid-request, a gateway error) leaves the outcome +//! unknown: the review may exist ([`PostError::Uncertain`]). use std::fmt; -use std::io::Write as _; -use std::process::{Command, Stdio}; +use std::process::Command; +use std::time::Duration; use serde::Deserialize; use super::ReviewRequest; +use crate::github::timed::{self, Ran}; use crate::github::{Gh, PrRepo}; +/// How long a post may take before gh is stopped and the outcome is called unknown. +pub const POST_TIMEOUT: Duration = Duration::from_mins(1); + /// The review GitHub created. #[derive(Debug, Clone, PartialEq, Eq)] pub struct PostedReview { @@ -22,7 +28,7 @@ pub struct PostedReview { pub confirmed: bool, } -/// Why a post failed. Every case posted nothing. +/// Why a post failed. Every case but [`Self::Uncertain`] posted nothing. #[derive(Debug, Clone, PartialEq, Eq)] pub enum PostError { /// `gh` is not installed. @@ -41,8 +47,17 @@ pub enum PostError { Positions { detail: String }, /// An approval or a change request on one's own pull request. OwnPullRequest { detail: String }, - /// Anything else, with gh's and GitHub's words. + /// GitHub refused it for another reason, with gh's and GitHub's words. Other { detail: String }, + /// No answer came back, or not a refusal: the review may have been posted. + Uncertain { detail: String }, +} + +impl PostError { + /// Whether GitHub may have created the review all the same. + pub fn may_have_posted(&self) -> bool { + matches!(self, Self::Uncertain { .. }) + } } impl fmt::Display for PostError { @@ -81,6 +96,7 @@ impl fmt::Display for PostError { it as a Comment ({detail})" ), Self::Other { detail } => write!(f, "gh api failed: {detail}"), + Self::Uncertain { detail } => write!(f, "GitHub's answer did not come back ({detail})"), } } } @@ -110,25 +126,25 @@ impl Gh { let endpoint = format!("repos/{}/{}/pulls/{number}/reviews", repo.owner, repo.name); cmd.args(["--method", "POST", &endpoint, "--input", "-"]) .env("GH_PROMPT_DISABLED", "1") - .env("GH_NO_UPDATE_NOTIFIER", "1") - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - let mut child = cmd.spawn().map_err(|source| { + .env("GH_NO_UPDATE_NOTIFIER", "1"); + let ran = timed::run(cmd, Some(json), POST_TIMEOUT).map_err(|source| { if source.kind() == std::io::ErrorKind::NotFound { PostError::GhMissing } else { PostError::Other { detail: format!("could not run gh: {source}") } } })?; - let written = child.stdin.take().map(|mut stdin| stdin.write_all(&json)); - let output = child - .wait_with_output() - .map_err(|e| PostError::Other { detail: format!("waiting for gh: {e}") })?; - if let Some(Err(e)) = written + let (output, written) = match ran { + Ran::Done { output, written } => (output, written), + Ran::TimedOut => { + let detail = format!("gh gave no answer in {} s and was stopped", POST_TIMEOUT.as_secs()); + return Err(PostError::Uncertain { detail }); + } + }; + if let Err(e) = written && output.status.success() { - return Err(PostError::Other { detail: format!("could not hand the review to gh: {e}") }); + return Err(PostError::Uncertain { detail: format!("could not hand the review to gh: {e}") }); } if !output.status.success() { return Err(classify( @@ -144,7 +160,8 @@ impl Gh { } /// gh's failure, from its stderr and the response body it prints on stdout, named for the -/// person. +/// person. Only a refusal (an HTTP 4xx, a login gh does not have) or a connection that was +/// never made means nothing was posted; anything else may have reached GitHub. pub(crate) fn classify(stdout: &str, stderr: &str) -> PostError { let detail = detail(stdout, stderr); let all = format!("{stdout}\n{stderr}").to_lowercase(); @@ -154,12 +171,26 @@ pub(crate) fn classify(stdout: &str, stderr: &str) -> PostError { } else if has(&["rate limit", "http 429"]) { PostError::RateLimited { detail } } else if has(&[ + // Sent, then the answer was lost, or a gateway gave up waiting for GitHub. + "connection reset", + "unexpected eof", + "broken pipe", + "client.timeout", + "deadline exceeded", + "timeout awaiting", + "http 500", + "http 502", + "http 503", + "http 504", + ]) { + PostError::Uncertain { detail } + } else if has(&[ + // The connection was never made: nothing was sent. "error connecting to", "could not resolve host", "no such host", "network is unreachable", "connection refused", - "i/o timeout", "tls handshake timeout", "dial tcp", ]) { @@ -172,8 +203,10 @@ pub(crate) fn classify(stdout: &str, stderr: &str) -> PostError { PostError::NoPermission { detail } } else if has(&["http 422"]) && has(&["line", "position", "path", "diff hunk", "start_line", "side"]) { PostError::Positions { detail } - } else { + } else if has(&["(http 4"]) { PostError::Other { detail } + } else { + PostError::Uncertain { detail } } } diff --git a/crates/plannotator-tui-review/src/post/tests.rs b/crates/plannotator-tui-review/src/post/tests.rs index 1c3828dc..d89f0de1 100644 --- a/crates/plannotator-tui-review/src/post/tests.rs +++ b/crates/plannotator-tui-review/src/post/tests.rs @@ -269,11 +269,30 @@ fn gh_failures_are_named_for_the_person() { "gh: Unprocessable Entity (HTTP 422)", "OwnPullRequest", ), - ("", "boom", "Other"), + ( + "{\"message\":\"Validation Failed\",\"errors\":[\"something else\"]}", + "gh: Validation Failed (HTTP 422)", + "Other", + ), + // No refusal: the review may exist. + ("", "gh: Bad Gateway (HTTP 502)", "Uncertain"), + ("", "gh: Gateway Timeout (HTTP 504)", "Uncertain"), + ( + "", + "Post \"https://api.github.com/repos/o/r/pulls/7/reviews\": net/http: request canceled \ + (Client.Timeout exceeded while awaiting headers)", + "Uncertain", + ), + ("", "read tcp 10.0.0.2:5000->140.82.112.6:443: read: connection reset by peer", "Uncertain"), + ("", "Post \"https://api.github.com/graphql\": unexpected EOF", "Uncertain"), + ("", "boom", "Uncertain"), + // Never connected: nothing was sent. + ("", "dial tcp 140.82.112.6:443: i/o timeout", "Offline"), ]; for (stdout, stderr, want) in cases { let got = classify(stdout, stderr); assert!(format!("{got:?}").starts_with(want), "{stderr}: {got:?}"); + assert_eq!(got.may_have_posted(), want == "Uncertain", "{stderr}"); } let positions = classify( "{\"message\":\"Unprocessable Entity\",\"errors\":[\"Line could not be resolved\"],\"status\":\"422\"}", From a470a05f4322e1f5e61647492501bae44b45e492 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Sat, 28 Nov 2026 18:15:52 -0500 Subject: [PATCH 13/16] feat(review): name notes too long for GitHub; suggestions on removed lines go as plain comments --- crates/plannotator-tui-review/src/post.rs | 68 ++++++++++++++++--- .../plannotator-tui-review/src/post/tests.rs | 37 ++++++++++ 2 files changed, 94 insertions(+), 11 deletions(-) diff --git a/crates/plannotator-tui-review/src/post.rs b/crates/plannotator-tui-review/src/post.rs index eb7990ec..50273887 100644 --- a/crates/plannotator-tui-review/src/post.rs +++ b/crates/plannotator-tui-review/src/post.rs @@ -7,7 +7,9 @@ //! `start_line`/`start_side` (the same side) are added only for a range. The body is the //! note's text (after a browser note's conventional-comment prefix) and, for a suggestion, //! a `` ```suggestion `` block, fenced past any backticks in the code (a suggestion on -//! Markdown can hold a fence of its own). +//! Markdown can hold a fence of its own). GitHub applies a suggestion only to new lines, +//! so one on old lines (made in the browser or by Pi) is a plain comment with its code +//! quoted ([`Plan::plain_suggestions`]). //! - **The review body**, in note order: whole-change notes as plain paragraphs, file notes //! as `**path:** text`, and line notes GitHub cannot take inline (outdated, or their lines //! are no longer in the diff) as `**path (L5-L9, new):**` with the code they were made on. @@ -37,7 +39,7 @@ use crate::patch::FilePatch; mod submit; -pub use submit::{PostError, PostedReview}; +pub use submit::{POST_TIMEOUT, PostError, PostedReview}; /// The browser's `OUTSIDE_DIFF_BODY_HEADING`. pub const OUTSIDE_DIFF_BODY_HEADING: &str = "Comments outside the diff"; @@ -48,7 +50,7 @@ pub const OUTSIDE_DIFF_QUOTE_MAX_LINES: usize = 40; /// The browser's `COMMENT_BODY_PLACEHOLDER`. pub const BODY_PLACEHOLDER: &str = "See inline comments."; -/// GitHub refuses a review body longer than this many characters. +/// GitHub refuses a review body, or an inline comment, longer than this many characters. pub const MAX_BODY_CHARS: usize = 65_536; /// The review's verdict. The browser defaults to a comment and offers the other two as @@ -152,6 +154,10 @@ pub struct Plan { pub skipped: Vec<(String, Skip)>, /// Ids of included notes a post carried before they were edited: posted again, new. pub reposted: Vec, + /// Ids of suggestions on old lines, posted inline as plain comments with the code quoted. + pub plain_suggestions: Vec, + /// Each body entry's length in characters, by why it is in the body. + pub body_sizes: Vec<(InBody, usize)>, } impl Plan { @@ -171,6 +177,8 @@ impl Plan { in_body: Vec::new(), skipped: Vec::new(), reposted: Vec::new(), + plain_suggestions: Vec::new(), + body_sizes: Vec::new(), }; let mut parts: Vec = Vec::new(); let mut outside: Vec = Vec::new(); @@ -183,17 +191,26 @@ impl Plan { let place = placement(note, files); let placed = match place { Placement::Inline => inline_comment(note).map(|comment| plan.comments.push(comment)), - Placement::Body(InBody::OutsideDiff) => { - outside_entry(note, target).map(|entry| outside.push(entry)) - } - Placement::Body(kind) => body_entry(note, kind).map(|entry| parts.push(entry)), + Placement::Body(InBody::OutsideDiff) => outside_entry(note, target).map(|entry| { + plan.body_sizes.push((InBody::OutsideDiff, entry.chars().count())); + outside.push(entry); + }), + Placement::Body(kind) => body_entry(note, kind).map(|entry| { + plan.body_sizes.push((kind, entry.chars().count())); + parts.push(entry); + }), }; if placed.is_none() { plan.skipped.push((note.id.clone(), Skip::Empty)); continue; } match place { - Placement::Inline => plan.inline.push(note.id.clone()), + Placement::Inline => { + if note.side == Side::Old && suggested(note).is_some() { + plan.plain_suggestions.push(note.id.clone()); + } + plan.inline.push(note.id.clone()); + } Placement::Body(kind) => plan.in_body.push((note.id.clone(), kind)), } if state == Posting::Edited { @@ -241,6 +258,28 @@ impl Plan { pub fn body_too_long(&self) -> bool { self.body.chars().count() > MAX_BODY_CHARS } + + /// The inline comments over GitHub's limit, with their length in characters. + pub fn too_long_comments(&self) -> Vec<(&InlineComment, usize)> { + self.comments + .iter() + .map(|c| (c, c.body.chars().count())) + .filter(|(_, chars)| *chars > MAX_BODY_CHARS) + .collect() + } + + /// How many characters of the body each kind of note takes, the largest first. + pub fn body_size_by_kind(&self) -> Vec<(InBody, usize)> { + let mut sizes: Vec<(InBody, usize)> = Vec::new(); + for (kind, chars) in &self.body_sizes { + match sizes.iter_mut().find(|(k, _)| k == kind) { + Some((_, total)) => *total += chars, + None => sizes.push((*kind, *chars)), + } + } + sizes.sort_by_key(|(_, chars)| std::cmp::Reverse(*chars)); + sizes + } } #[derive(Clone, Copy)] @@ -278,9 +317,16 @@ fn github_side(side: Side) -> &'static str { /// The browser's `buildAnnotationFileComments` for one note; `None` when its body is empty. fn inline_comment(note: &CodeAnnotation) -> Option { let mut body = format!("{}{}", conventional_prefix(¬e.other), text(note)); - if let Some(code) = suggested(note) { - let fence = fence(code); - let _ = write!(body, "\n\n{fence}suggestion\n{code}\n{fence}"); + match (suggested(note), note.side) { + (Some(code), Side::New) => { + let fence = fence(code); + let _ = write!(body, "\n\n{fence}suggestion\n{code}\n{fence}"); + } + // GitHub cannot apply a suggestion to lines the change removed. + (Some(code), Side::Old) => { + let _ = write!(body, "\n\nSuggested code:\n{}", code_fence(code)); + } + (None, _) => {} } let body = body.trim().to_owned(); if body.is_empty() { diff --git a/crates/plannotator-tui-review/src/post/tests.rs b/crates/plannotator-tui-review/src/post/tests.rs index d89f0de1..3c11dc52 100644 --- a/crates/plannotator-tui-review/src/post/tests.rs +++ b/crates/plannotator-tui-review/src/post/tests.rs @@ -303,3 +303,40 @@ fn gh_failures_are_named_for_the_person() { "GitHub refused the place of an inline comment (Unprocessable Entity: Line could not be resolved)" ); } + +#[test] +fn a_suggestion_on_old_lines_is_a_plain_comment_with_its_code_quoted() { + // GitHub applies a suggestion only to new lines; the browser or Pi can make one on old. + let old = note(json!({"id": "s", "type": "suggestion", "side": "old", "lineStart": 2, "lineEnd": 2, + "text": "keep it", "suggestedCode": "two()"})); + let plan = plan(&[old]); + assert_eq!(plan.comments.len(), 1, "{plan:?}"); + assert_eq!(plan.comments[0].side, "LEFT"); + assert_eq!(plan.comments[0].body, "keep it\n\nSuggested code:\n```\ntwo()\n```"); + assert_eq!(plan.plain_suggestions, ["s"]); +} + +#[test] +fn notes_too_long_for_github_are_named_before_posting() { + let long = "x".repeat(MAX_BODY_CHARS + 10); + let one = plan(&[line("a", "new", 2, 2, &long), line("b", "new", 3, 3, "short")]); + let too_long = one.too_long_comments(); + assert_eq!(too_long.len(), 1); + assert_eq!((too_long[0].0.line, too_long[0].1), (2, MAX_BODY_CHARS + 10)); + assert!(!one.body_too_long()); + + let quoted = "y\n".repeat(30); + let outside: Vec = (0..2000) + .map(|n| { + note(json!({"id": format!("o{n}"), "lineStart": 40, "lineEnd": 41, "text": "why?", + "anchorText": quoted, "outsideDiff": true})) + }) + .chain([note(json!({"id": "g", "scope": "general", "filePath": "", "lineStart": 0, "lineEnd": 0, + "text": "overall fine"}))]) + .collect(); + let plan = plan(&outside); + assert!(plan.body_too_long()); + let by_kind = plan.body_size_by_kind(); + assert_eq!(by_kind.first().map(|(kind, _)| *kind), Some(InBody::OutsideDiff), "{by_kind:?}"); + assert_eq!(by_kind.get(1), Some(&(InBody::Change, "overall fine".len()))); +} From b5900bd46460b812edda281dc0fb020a545b801b Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Sat, 28 Nov 2026 18:15:52 -0500 Subject: [PATCH 14/16] fix(review): Enter posts only once the summary is on screen, and gh runs off the screen's thread --- crates/plannotator-tui/src/review/cli.rs | 9 +- crates/plannotator-tui/src/review/mod.rs | 9 +- .../plannotator-tui/src/review/pick/shown.rs | 6 +- crates/plannotator-tui/src/review/post.rs | 257 +++++++++++------- .../plannotator-tui/src/review/post_view.rs | 224 +++++++++++---- .../src/review/tests/post_flow.rs | 143 ++++++++-- 6 files changed, 477 insertions(+), 171 deletions(-) diff --git a/crates/plannotator-tui/src/review/cli.rs b/crates/plannotator-tui/src/review/cli.rs index 6dd89785..81b5e147 100644 --- a/crates/plannotator-tui/src/review/cli.rs +++ b/crates/plannotator-tui/src/review/cli.rs @@ -205,7 +205,14 @@ fn event_loop( let mut drawn = Ok(()); terminal.draw(|frame| drawn = screen.draw(frame))?; drawn?; - screen.after_draw(); + if screen.after_draw() { + // Typed before the post summary showed: not an answer to it. + while let Ok(event) = events.try_recv() { + if !matches!(event, Event::Key(_) | Event::Paste(_)) { + screen.handle_event(event)?; + } + } + } dirty = false; } let mut handled = false; diff --git a/crates/plannotator-tui/src/review/mod.rs b/crates/plannotator-tui/src/review/mod.rs index 85cfd386..89ab693c 100644 --- a/crates/plannotator-tui/src/review/mod.rs +++ b/crates/plannotator-tui/src/review/mod.rs @@ -247,6 +247,8 @@ pub(crate) struct Screen { pick_request: bool, /// The other reviews this session showed, for the notes left unsent on them. switched: pick::shown::Switched, + /// A `gh` call for the post summary under way: the PR check, or the post. + post_job: Option, quit: bool, } @@ -339,6 +341,7 @@ impl Screen { help_room: std::cell::Cell::new(0), pick_request: false, switched: pick::shown::Switched::default(), + post_job: None, quit: false, }; screen.notes_rail.settle(!screen.store.annotations().is_empty()); @@ -448,6 +451,7 @@ impl Screen { changed |= self.take_attributes()?; changed |= self.poll_pi(); changed |= self.poll_search()?; + changed |= self.poll_post(); let typing = matches!(self.mode, Mode::Compose(_)) || self.last_key.is_some_and(|at| at.elapsed() < watch::QUIET_AFTER_KEY); changed |= self.watch.poll(&self.repo, &self.capture.scope, !typing); @@ -463,11 +467,14 @@ impl Screen { Ok(changed || self.diff.needs_draw() || whole_draw) } - pub(crate) fn after_draw(&mut self) { + /// After a frame. True when the keys already waiting should be dropped: the post + /// summary just came on screen, and they were typed before it. + pub(crate) fn after_draw(&mut self) -> bool { self.diff.after_draw(); if let Some(whole) = &mut self.whole { whole.after_draw(); } + self.post_shown() } /// Stop the viewer's workers. Call it once the loop ends, so their errors are reported. diff --git a/crates/plannotator-tui/src/review/pick/shown.rs b/crates/plannotator-tui/src/review/pick/shown.rs index 98bacee9..5082a1cc 100644 --- a/crates/plannotator-tui/src/review/pick/shown.rs +++ b/crates/plannotator-tui/src/review/pick/shown.rs @@ -177,10 +177,12 @@ impl Shown { Ok(()) } - pub(crate) fn after_draw(&mut self) { + /// True when the keys already waiting should be dropped ([`Screen::after_draw`]). + pub(crate) fn after_draw(&mut self) -> bool { if let Some(screen) = &mut self.screen { - screen.after_draw(); + return screen.after_draw(); } + false } pub(crate) fn held_at_edge(&self) -> bool { diff --git a/crates/plannotator-tui/src/review/post.rs b/crates/plannotator-tui/src/review/post.rs index 89227b62..23c3a314 100644 --- a/crates/plannotator-tui/src/review/post.rs +++ b/crates/plannotator-tui/src/review/post.rs @@ -5,22 +5,34 @@ //! The summary names the PR, how many notes go inline and how many in the review body (and //! why), what is left out, and the verdict: Comment unless the person picks Approve or //! Request changes, as the browser offers them. `Enter` posts and `Esc` cancels; nothing -//! leaves the machine before `Enter`. Comments are anchored to the commit the diff was -//! captured at, the one the person reviewed; when the PR has moved on since, the summary -//! says so. A post that fails posted nothing (GitHub takes the review whole or not at all), -//! and the summary stays open with the reason. A post that succeeds marks its notes posted, -//! a state of its own beside sent, saved with the notes; a later post carries only notes that -//! are new or edited since. +//! leaves the machine before `Enter`, and `Enter` counts only once the whole summary has been +//! on screen: a key typed before it appeared is not an answer to it ([`Confirm::shown`]). +//! Comments are anchored to the commit the diff was captured at, the one the person +//! reviewed; when the PR has moved on since, the summary says so. +//! +//! Both `gh` calls run on a thread of their own and wake the event loop when they answer, so +//! a slow GitHub never freezes the screen: the summary says it is checking the PR, then that +//! it is posting. A refusal posted nothing (GitHub takes the review whole or not at all), and +//! the summary stays open with the reason. An answer that never came back may have posted +//! the review, and the summary says to check the PR first. A post that succeeds marks its +//! notes posted, a state of its own beside sent, saved with the notes; a later post carries +//! only notes that are new or edited since. use std::fmt::Write as _; +use std::sync::mpsc::{self, Receiver, TryRecvError}; +use std::time::Duration; -use plannotator_tui_review::post::{Event, InBody, Plan, PostError, Posting, Skip, Target}; -use plannotator_tui_review::{CodeAnnotation, PrSpec, Scope}; +use plannotator_tui_review::post::{Event, Plan, PostError, PostedReview, Posting, Skip, Target}; +use plannotator_tui_review::{CodeAnnotation, PrSpec, PrView, Scope}; use ratatui::crossterm::event::KeyEvent; +use super::post_view::{comment_places, too_long}; use super::{Mode, Screen}; use crate::keys::{self, Action}; +/// How long the check of the PR's head may take before the summary says it could not check. +const CHECK_TIMEOUT: Duration = Duration::from_secs(20); + /// The summary on screen before a post. #[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct Confirm { @@ -30,13 +42,19 @@ pub(super) struct Confirm { pub(super) head: Head, /// `closed` or `merged` when the PR is no longer open; GitHub still takes a review. pub(super) ended: Option<&'static str>, - /// Why the last try posted nothing. + /// Why the last try did not post, or may not have. pub(super) failed: Option, + /// A post is under way: keys wait for GitHub's answer. + pub(super) posting: bool, + /// The summary was drawn whole, the PR checked. `Enter` posts only from then on. + pub(super) shown: bool, } /// The PR's head on GitHub, against the commit the person reviewed. #[derive(Debug, Clone, PartialEq, Eq)] pub(super) enum Head { + /// `gh pr view` has not answered yet. + Checking, Reviewed, /// The PR has newer commits than the reviewed one. Moved { @@ -46,6 +64,18 @@ pub(super) enum Head { Unknown(String), } +/// What a `gh` thread answers. +enum Answer { + Head(Result, String>), + Posted(Result), +} + +/// A `gh` call under way: its answer, and the summary a post was confirmed from. +pub(super) struct Job { + answer: Receiver, + posting: Option, +} + impl Screen { /// `post-to-github`: open the summary, or say why there is nothing to post. pub(super) fn open_post(&mut self) { @@ -76,15 +106,27 @@ impl Screen { Scope::PullRequest { url, number } => PrSpec::parse(url).unwrap_or(PrSpec::Number(*number)), _ => PrSpec::Number(pull.view.number), }; - let (head, ended) = match gh.view(&spec, self.repo.workdir()) { - Ok(view) if view.head_sha == pull.head => (Head::Reviewed, view.ended()), - Ok(view) => { - let ended = view.ended(); - (Head::Moved { now: view.head_sha }, ended) + let (gh, dir) = (gh.clone(), self.repo.workdir().to_path_buf()); + let job = self.start("pr-check", None, move || { + Answer::Head(gh.view_within(&spec, &dir, CHECK_TIMEOUT).map(Box::new).map_err(|e| e.to_string())) + }); + let head = match job { + Ok(job) => { + self.post_job = Some(job); + Head::Checking } - Err(err) => (Head::Unknown(err.to_string()), None), + Err(why) => Head::Unknown(why), }; - self.mode = Mode::Post(Confirm { plan, event: Event::default(), head, ended, failed: None }); + let confirm = Confirm { + plan, + event: Event::default(), + head, + ended: None, + failed: None, + posting: false, + shown: false, + }; + self.mode = Mode::Post(confirm); } fn posting(&self, note: &CodeAnnotation) -> Posting { @@ -97,42 +139,129 @@ impl Screen { } } + /// Run `work` on a thread named `name`, waking the event loop when it answers. + fn start( + &self, + name: &str, + posting: Option, + work: impl FnOnce() -> Answer + Send + 'static, + ) -> Result { + let (tell, answer) = mpsc::sync_channel(1); + let wake = self.wake.clone(); + std::thread::Builder::new() + .name(name.to_owned()) + .spawn(move || { + let _ = tell.send(work()); + let _ = wake.try_send(()); + }) + .map_err(|err| format!("could not start gh: {err}"))?; + Ok(Job { answer, posting }) + } + + /// Take a `gh` answer that arrived. Returns whether the screen changed. + pub(super) fn poll_post(&mut self) -> bool { + let Some(job) = &self.post_job else { return false }; + let answer = match job.answer.try_recv() { + Ok(answer) => answer, + Err(TryRecvError::Empty) => return false, + Err(TryRecvError::Disconnected) if job.posting.is_some() => { + Answer::Posted(Err(PostError::Uncertain { detail: "the post stopped".into() })) + } + Err(TryRecvError::Disconnected) => Answer::Head(Err("the check stopped".into())), + }; + let Some(job) = self.post_job.take() else { return false }; + match (answer, job.posting) { + (Answer::Posted(result), Some(confirm)) => self.finish_post(confirm, result), + (Answer::Head(view), _) => { + // A summary closed meanwhile has no use for it. + let (Mode::Post(confirm), Some(pull)) = (&mut self.mode, &self.capture.pull) else { + return true; + }; + (confirm.head, confirm.ended) = match view { + Ok(view) if view.head_sha == pull.head => (Head::Reviewed, view.ended()), + Ok(view) => { + let ended = view.ended(); + (Head::Moved { now: view.head_sha }, ended) + } + Err(why) => (Head::Unknown(why), None), + }; + } + (Answer::Posted(_), None) => {} + } + true + } + + /// After a frame: the summary, checked, was on screen. True the first time, so the event + /// loop drops the keys that were already waiting: they were typed before it showed. + pub(super) fn post_shown(&mut self) -> bool { + match &mut self.mode { + Mode::Post(confirm) if !confirm.shown && confirm.head != Head::Checking => { + confirm.shown = true; + true + } + _ => false, + } + } + pub(super) fn post_key(&mut self, key: KeyEvent, mut confirm: Confirm) { let step = |event: Event, by: isize| { let at = Event::ALL.iter().position(|e| *e == event).unwrap_or(0); let next = at.saturating_add_signed(by).min(Event::ALL.len() - 1); Event::ALL.get(next).copied().unwrap_or_default() }; + if confirm.posting { + // It is GitHub's turn; the answer closes or updates the summary. + self.mode = Mode::Post(confirm); + return; + } match self.keys.action(&key, keys::POST_REVIEW) { Some(Action::Left) => confirm.event = step(confirm.event, -1), Some(Action::Right) => confirm.event = step(confirm.event, 1), - Some(Action::Confirm) => return self.post(confirm), + Some(Action::Confirm) if confirm.shown => return self.post(confirm), Some(Action::Back | Action::Interrupt) => { + self.post_job = None; self.mode = Mode::Browse; self.status = Some("nothing posted to GitHub".into()); return; } - _ => return, + _ => {} } self.mode = Mode::Post(confirm); } - /// The person confirmed: post, then mark what was posted. + /// The person confirmed: post on a thread of its own; [`Self::finish_post`] takes the answer. fn post(&mut self, mut confirm: Confirm) { let (Some(pull), Some(gh)) = (&self.capture.pull, self.repo.gh()) else { self.mode = Mode::Browse; return; }; - if confirm.plan.body_too_long() { - confirm.failed = Some(format!( - "the review body is over GitHub's {} characters; post fewer notes", - plannotator_tui_review::post::MAX_BODY_CHARS - )); + if !too_long(&confirm.plan).is_empty() { + confirm.failed = Some("Nothing was posted: shorten the notes named above first.".into()); self.mode = Mode::Post(confirm); return; } let request = confirm.plan.request(confirm.event); - match gh.post_review(&pull.view.repo, pull.view.number, &request) { + let (gh, repo, number) = (gh.clone(), pull.view.repo.clone(), pull.view.number); + confirm.failed = None; + confirm.posting = true; + let work = move || Answer::Posted(gh.post_review(&repo, number, &request)); + match self.start("pr-post", Some(confirm.clone()), work) { + Ok(job) => { + self.post_job = Some(job); + self.status = Some("posting to GitHub\u{2026}".into()); + } + Err(why) => { + confirm.posting = false; + confirm.failed = Some(format!("Nothing was posted: {why}.")); + } + } + self.mode = Mode::Post(confirm); + } + + /// GitHub answered the post confirmed with `confirm`. + fn finish_post(&mut self, mut confirm: Confirm, result: Result) { + confirm.posting = false; + match result { Ok(review) => { let ids = confirm.plan.ids(); let saved = self.store.record_post(&review.url, &confirm.plan.commit_id, &ids); @@ -149,13 +278,23 @@ impl Screen { if let Err(err) = saved { let _ = write!( status, - " \u{b7} could not save the posted state ({err}); a later post may repeat these notes" + " \u{b7} could not save the posted state ({err}); after a restart a post may repeat \ + these notes" ); } self.status = Some(status); self.mode = Mode::Browse; self.after_note_change(); } + Err(err) if err.may_have_posted() => { + let url = self.capture.pull.as_ref().map(|p| p.view.url.clone()).unwrap_or_default(); + confirm.failed = Some(format!( + "This may have been posted: {err}. Check the pull request on GitHub before you post \ + again: {url}" + )); + self.status = Some("may have been posted to GitHub: check the pull request".into()); + self.mode = Mode::Post(confirm); + } Err(err) => { let mut why = format!("Nothing was posted: {err}."); if matches!(err, PostError::Positions { .. }) { @@ -187,22 +326,6 @@ impl Screen { } } -/// `app.py:9 new, app.py:3-5 old`. -fn comment_places(plan: &Plan) -> String { - let places: Vec = plan - .comments - .iter() - .map(|c| { - let side = if c.side == "LEFT" { "old" } else { "new" }; - match c.start_line { - Some(start) => format!("{}:{start}-{} {side}", c.path, c.line), - None => format!("{}:{} {side}", c.path, c.line), - } - }) - .collect(); - places.join(", ") -} - /// A few words for the footer; the summary has the rest. fn short_reason(err: &PostError) -> &'static str { match err { @@ -215,58 +338,10 @@ fn short_reason(err: &PostError) -> &'static str { PostError::Positions { .. } => "GitHub refused a comment's place", PostError::OwnPullRequest { .. } => "your own pull request", PostError::Other { .. } => "gh api failed", + PostError::Uncertain { .. } => "no answer from GitHub", } } pub(super) fn short(sha: &str) -> &str { sha.get(..7).unwrap_or(sha) } - -/// The summary's lines about what goes where, for the overlay. -pub(super) fn summary(plan: &Plan) -> Vec { - let plural = |n: usize, one: &str, many: &str| format!("{n} {}", if n == 1 { one } else { many }); - let mut lines = vec![plural(plan.comments.len(), "inline comment", "inline comments")]; - let body: Vec = [ - (InBody::Change, "whole-change note", "whole-change notes"), - (InBody::File, "file note", "file notes"), - ( - InBody::OutsideDiff, - "note outside the diff, quoted with a link", - "notes outside the diff, quoted with a link", - ), - ( - InBody::OffDiff, - "line note outdated or no longer in the diff, quoted", - "line notes outdated or no longer in the diff, quoted", - ), - ] - .into_iter() - .filter_map(|(kind, one, many)| { - let n = plan.count_in_body(kind); - (n > 0).then(|| format!(" {}", plural(n, one, many))) - }) - .collect(); - if body.is_empty() { - lines.push("nothing else in the review body".to_owned()); - } else { - lines.push(format!("{} in the review body:", plan.in_body.len())); - lines.extend(body); - } - if !plan.reposted.is_empty() { - lines.push(format!( - "{} edited since posted: posted again as new comments (the earlier ones stay on GitHub)", - plan.reposted.len() - )); - } - let skipped: Vec = [(Skip::AlreadyPosted, "already posted"), (Skip::Empty, "empty")] - .into_iter() - .filter_map(|(why, label)| { - let n = plan.count_skipped(why); - (n > 0).then(|| format!("{n} {label}")) - }) - .collect(); - if !skipped.is_empty() { - lines.push(format!("skipped: {}", skipped.join(", "))); - } - lines -} diff --git a/crates/plannotator-tui/src/review/post_view.rs b/crates/plannotator-tui/src/review/post_view.rs index 74e855b3..0e8ff6ee 100644 --- a/crates/plannotator-tui/src/review/post_view.rs +++ b/crates/plannotator-tui/src/review/post_view.rs @@ -1,5 +1,6 @@ -//! The summary before a post to GitHub, drawn over the review. +//! The summary before a post to GitHub, drawn over the review, and the words it is made of. +use plannotator_tui_review::post::{Event, InBody, InlineComment, MAX_BODY_CHARS, Plan, Skip}; use ratatui::Frame; use ratatui::layout::Rect; use ratatui::style::Style; @@ -7,20 +8,56 @@ use ratatui::text::{Line, Span}; use ratatui::widgets::{Block, BorderType, Borders, Clear, Paragraph}; use super::Screen; -use super::post::{Confirm, Head, short, summary}; +use super::post::{Confirm, Head, short}; use crate::keys::Action; use crate::theme::palette; use crate::wrap::wrap_line; -use plannotator_tui_review::post::Event; /// The summary's widest. const WIDTH: u16 = 76; impl Screen { pub(super) fn draw_post(&self, frame: &mut Frame, area: Rect, confirm: &Confirm) { - let Some(pull) = &self.capture.pull else { return }; + let lines = self.post_lines(confirm); + let help = self.post_help(confirm); + let width = area.width.min(WIDTH); + let inner_width = usize::from(width.saturating_sub(4)).max(1); + let rows: Vec> = lines + .iter() + .flat_map(|line| { + let wrapped = wrap_line(line, &[], inner_width); + if wrapped.is_empty() { + vec![Line::default()] + } else { + wrapped.into_iter().map(|r| r.line).collect() + } + }) + .collect(); + let height = (rows.len() as u16 + 2).min(area.height); + let rect = Rect { + x: area.x + area.width.saturating_sub(width) / 2, + y: area.y + area.height.saturating_sub(height) / 2, + width, + height, + }; + frame.render_widget(Clear, rect); + let boxed = Block::default() + .borders(Borders::ALL) + .border_type(BorderType::Rounded) + .border_style(Style::new().fg(palette().accent)) + .title(Span::styled(" post to GitHub ", Style::new().dim())) + .title_bottom(Span::styled(format!(" {help} "), Style::new().dim())); + let inner = boxed.inner(rect); + frame.render_widget(boxed, rect); + let text_area = Rect { x: inner.x + 1, width: inner.width.saturating_sub(2), ..inner }; + frame.render_widget(Paragraph::new(rows), text_area); + } + + fn post_lines(&self, confirm: &Confirm) -> Vec> { + let Some(pull) = &self.capture.pull else { return Vec::new() }; let accent = Style::new().fg(palette().accent).bold(); let warn = Style::new().fg(palette().comment).bold(); + let refused = Style::new().fg(palette().delete).bold(); let mut lines: Vec> = vec![ Line::from(vec![ Span::styled(format!("{}#{}", pull.view.repo.slug(), pull.view.number), accent), @@ -33,12 +70,16 @@ impl Screen { Line::default(), ]; lines.extend(summary(&confirm.plan).into_iter().map(Line::from)); + let mut note = |text: String, style: Style| { + lines.push(Line::default()); + lines.push(Line::from(Span::styled(text, style))); + }; match &confirm.head { Head::Reviewed => {} + Head::Checking => note("Checking the PR on GitHub\u{2026}".into(), Style::new().dim()), Head::Moved { now } => { let reload = self.keys.labelled(Action::Reload, "reloads it first").unwrap_or_default(); - lines.push(Line::default()); - lines.push(Line::from(Span::styled( + note( format!( "The PR moved on: its head is {} now. Comments stay on {}, the lines you saw; \ GitHub shows them as outdated where the code changed since. {reload}", @@ -46,21 +87,16 @@ impl Screen { short(&confirm.plan.commit_id) ), warn, - ))); - } - Head::Unknown(why) => { - lines.push(Line::default()); - lines.push(Line::from(Span::styled(format!("Could not check the PR's head: {why}"), warn))); + ); } + Head::Unknown(why) => note(format!("Could not check the PR's head: {why}"), warn), } if let Some(ended) = confirm.ended { - lines.push(Line::default()); - lines.push(Line::from(Span::styled( - format!("The PR is {ended}. GitHub still takes a review on it."), - warn, - ))); + note(format!("The PR is {ended}. GitHub still takes a review on it."), warn); + } + for problem in too_long(&confirm.plan) { + note(problem, refused); } - lines.push(Line::default()); let mut choices = vec![Span::raw("verdict ")]; for event in Event::ALL { let chosen = event == confirm.event; @@ -68,10 +104,22 @@ impl Screen { let style = if chosen { Style::new().bold() } else { Style::new().dim() }; choices.push(Span::styled(format!("{mark} {} ", event.label()), style)); } + lines.push(Line::default()); lines.push(Line::from(choices)); - if let Some(failed) = &confirm.failed { + if confirm.posting { lines.push(Line::default()); - lines.push(Line::from(Span::styled(failed.clone(), Style::new().fg(palette().delete).bold()))); + lines.push(Line::from(Span::styled("Posting to GitHub\u{2026}", warn))); + } else if let Some(failed) = &confirm.failed { + lines.push(Line::default()); + lines.push(Line::from(Span::styled(failed.clone(), refused))); + } + lines + } + + /// The bottom line: what the keys do now. + fn post_help(&self, confirm: &Confirm) -> String { + if confirm.posting { + return "waiting for GitHub's answer".to_owned(); } let verb = match confirm.event { Event::Comment => "posts", @@ -84,43 +132,119 @@ impl Screen { .filter(|k| !k.is_empty()) .collect(); let help: Vec = [ - self.keys.labelled(Action::Confirm, verb), + (confirm.head != Head::Checking).then(|| self.keys.labelled(Action::Confirm, verb)).flatten(), (!moves.is_empty()).then(|| format!("{} verdict", moves.join("/"))), self.keys.labelled(Action::Back, "cancels"), ] .into_iter() .flatten() .collect(); - let width = area.width.min(WIDTH); - let inner_width = usize::from(width.saturating_sub(4)).max(1); - let rows: Vec> = lines - .iter() - .flat_map(|line| { - let wrapped = wrap_line(line, &[], inner_width); - if wrapped.is_empty() { - vec![Line::default()] - } else { - wrapped.into_iter().map(|r| r.line).collect() - } - }) + help.join(" \u{b7} ") + } +} + +/// `app.py:9 new` or `app.py:3-5 old`. +fn place(comment: &InlineComment) -> String { + let side = if comment.side == "LEFT" { "old" } else { "new" }; + match comment.start_line { + Some(start) => format!("{}:{start}-{} {side}", comment.path, comment.line), + None => format!("{}:{} {side}", comment.path, comment.line), + } +} + +/// `app.py:9 new, app.py:3-5 old`. +pub(super) fn comment_places(plan: &Plan) -> String { + plan.comments.iter().map(place).collect::>().join(", ") +} + +/// What GitHub would refuse for its length, naming the note or the kind of notes to shorten. +pub(super) fn too_long(plan: &Plan) -> Vec { + let mut problems: Vec = plan + .too_long_comments() + .into_iter() + .map(|(comment, chars)| { + format!( + "The note on {} is {chars} characters; GitHub takes {MAX_BODY_CHARS} at most. Shorten it.", + place(comment) + ) + }) + .collect(); + if plan.body_too_long() { + let kinds: Vec = plan + .body_size_by_kind() + .into_iter() + .map(|(kind, chars)| format!("{} {chars}", body_kind(kind))) .collect(); - let height = (rows.len() as u16 + 2).min(area.height); - let rect = Rect { - x: area.x + area.width.saturating_sub(width) / 2, - y: area.y + area.height.saturating_sub(height) / 2, - width, - height, - }; - frame.render_widget(Clear, rect); - let boxed = Block::default() - .borders(Borders::ALL) - .border_type(BorderType::Rounded) - .border_style(Style::new().fg(palette().accent)) - .title(Span::styled(" post to GitHub ", Style::new().dim())) - .title_bottom(Span::styled(format!(" {} ", help.join(" \u{b7} ")), Style::new().dim())); - let inner = boxed.inner(rect); - frame.render_widget(boxed, rect); - let text_area = Rect { x: inner.x + 1, width: inner.width.saturating_sub(2), ..inner }; - frame.render_widget(Paragraph::new(rows), text_area); + problems.push(format!( + "The review body is {} characters; GitHub takes {MAX_BODY_CHARS} at most. It holds {}: \ + shorten or remove some of those notes.", + plan.body.chars().count(), + kinds.join(", ") + )); + } + problems +} + +fn body_kind(kind: InBody) -> &'static str { + match kind { + InBody::Change => "whole-change notes", + InBody::File => "file notes", + InBody::OutsideDiff => "notes outside the diff, with their quoted code,", + InBody::OffDiff => "outdated line notes, with their quoted code,", + } +} + +/// The summary's lines about what goes where. +pub(super) fn summary(plan: &Plan) -> Vec { + let plural = |n: usize, one: &str, many: &str| format!("{n} {}", if n == 1 { one } else { many }); + let mut lines = vec![plural(plan.comments.len(), "inline comment", "inline comments")]; + if !plan.plain_suggestions.is_empty() { + lines.push(format!( + " {} on removed lines, as plain comments: GitHub applies suggestions to new lines only", + plural(plan.plain_suggestions.len(), "suggestion", "suggestions") + )); + } + let body: Vec = [ + (InBody::Change, "whole-change note", "whole-change notes"), + (InBody::File, "file note", "file notes"), + ( + InBody::OutsideDiff, + "note outside the diff, quoted with a link", + "notes outside the diff, quoted with a link", + ), + ( + InBody::OffDiff, + "line note outdated or no longer in the diff, quoted", + "line notes outdated or no longer in the diff, quoted", + ), + ] + .into_iter() + .filter_map(|(kind, one, many)| { + let n = plan.count_in_body(kind); + (n > 0).then(|| format!(" {}", plural(n, one, many))) + }) + .collect(); + if body.is_empty() { + lines.push("nothing else in the review body".to_owned()); + } else { + lines.push(format!("{} in the review body:", plan.in_body.len())); + lines.extend(body); + } + if !plan.reposted.is_empty() { + lines.push(format!( + "{} edited since posted: posted again as new comments (the earlier ones stay on GitHub)", + plan.reposted.len() + )); + } + let skipped: Vec = [(Skip::AlreadyPosted, "already posted"), (Skip::Empty, "empty")] + .into_iter() + .filter_map(|(why, label)| { + let n = plan.count_skipped(why); + (n > 0).then(|| format!("{n} {label}")) + }) + .collect(); + if !skipped.is_empty() { + lines.push(format!("skipped: {}", skipped.join(", "))); } + lines } diff --git a/crates/plannotator-tui/src/review/tests/post_flow.rs b/crates/plannotator-tui/src/review/tests/post_flow.rs index 6bb12753..a8c3e208 100644 --- a/crates/plannotator-tui/src/review/tests/post_flow.rs +++ b/crates/plannotator-tui/src/review/tests/post_flow.rs @@ -2,8 +2,6 @@ //! `pull_flow`: the `gh` stand-in answers `gh pr view` from `view.json` and records every //! `gh api` call (its arguments, and the JSON on its stdin) instead of reaching GitHub. -use std::os::unix::fs::PermissionsExt as _; - use plannotator_tui_review::CodeAnnotation; use ratatui::crossterm::event::KeyModifiers; @@ -25,9 +23,7 @@ impl Pull { let script = format!( "#!/bin/sh\nif [ \"$1\" = api ]; then\n printf '%s\\n' \"$@\" >> '{dir}/api-args'\n cat >> '{dir}/api-requests.jsonl'\n echo >> '{dir}/api-requests.jsonl'\n cat '{dir}/api-stdout'\n cat '{dir}/api-stderr' >&2\n exit {exit}\nfi\ncat '{dir}/view.json'\n" ); - let gh = self.dir.join("gh"); - std::fs::write(&gh, script).expect("gh"); - std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).expect("chmod"); + crate::test_support::write_script(&self.dir.join("gh"), &script); } fn answer_created(&self) { @@ -50,6 +46,33 @@ fn ctrl_g(screen: &mut Screen) { screen.handle_event(Event::Key(KeyEvent::new(KeyCode::Char('g'), KeyModifiers::CONTROL))).expect("key"); } +/// Tick until `done` holds of the summary, as the event loop would. +fn tick_until(screen: &mut Screen, done: impl Fn(&crate::review::post::Confirm) -> bool) { + let started = Instant::now(); + loop { + screen.tick().expect("tick"); + match &screen.mode { + Mode::Post(confirm) if !done(confirm) => {} + _ => return, + } + assert!(started.elapsed() < Duration::from_secs(10), "gh never answered"); + std::thread::sleep(Duration::from_millis(5)); + } +} + +/// `ctrl+g`, the PR checked, and the summary drawn: what the person sees before `Enter`. +fn summary(screen: &mut Screen) -> Vec { + ctrl_g(screen); + tick_until(screen, |c| c.head != crate::review::post::Head::Checking); + frame(screen, 120, 40) +} + +/// `Enter` on the summary, then GitHub's answer. +fn post_it(screen: &mut Screen) { + press(screen, KeyCode::Enter); + tick_until(screen, |c| !c.posting); +} + fn comment_on(screen: &mut Screen, side: Side, line: u32, text: &str) { screen.diff.reveal("app.py", side, line).expect("in the diff"); keys(screen, "c"); @@ -92,9 +115,8 @@ fn ctrl_g_shows_a_summary_and_posts_one_review_only_on_enter() { every_kind_of_note(&mut screen); let head = git_in(&pull.work(), &["rev-parse", "feature"]); - ctrl_g(&mut screen); + let rows = summary(&mut screen); assert!(matches!(screen.mode, Mode::Post(_)), "{:?}", screen.status); - let rows = frame(&mut screen, 120, 40); if let Some(dir) = std::env::var_os("POST_GH_PROOF_DIR") { std::fs::create_dir_all(&dir).expect("proof dir"); std::fs::write(PathBuf::from(dir).join("summary.txt"), rows.join("\n")).expect("proof"); @@ -112,6 +134,8 @@ fn ctrl_g_shows_a_summary_and_posts_one_review_only_on_enter() { assert_eq!(pull.requests().len(), 0, "nothing leaves before Enter"); press(&mut screen, KeyCode::Enter); + row_with(&frame(&mut screen, 120, 40), "Posting to GitHub\u{2026}"); + tick_until(&mut screen, |c| !c.posting); assert_eq!(screen.mode, Mode::Browse); let [request] = pull.requests().try_into().expect("one request"); let args = read(&pull.dir.join("api-args")); @@ -173,8 +197,8 @@ fn a_later_post_carries_only_new_and_edited_notes() { let mut screen = pull.open(); comment_on(&mut screen, Side::New, 5, "say hello properly"); comment_on(&mut screen, Side::New, 9, "name the total"); - ctrl_g(&mut screen); - press(&mut screen, KeyCode::Enter); + summary(&mut screen); + post_it(&mut screen); ctrl_g(&mut screen); assert_eq!(screen.mode, Mode::Browse); assert_eq!(screen.status.as_deref(), Some("nothing new to post to GitHub (2 already posted)")); @@ -189,12 +213,11 @@ fn a_later_post_carries_only_new_and_edited_notes() { }) .expect("edits"); comment_on(&mut screen, Side::New, 14, "check argv"); - ctrl_g(&mut screen); - let rows = frame(&mut screen, 120, 40); + let rows = summary(&mut screen); row_with(&rows, "2 inline comments"); row_with(&rows, "1 edited since posted: posted again as new comments"); row_with(&rows, "skipped: 1 already posted"); - press(&mut screen, KeyCode::Enter); + post_it(&mut screen); let requests = pull.requests(); let [_, second] = requests.as_slice() else { panic!("two posts: {requests:?}") }; let bodies: Vec<&str> = @@ -213,8 +236,8 @@ fn a_refused_post_posts_nothing_and_names_the_comments() { let mut screen = pull.open(); comment_on(&mut screen, Side::New, 9, "name the total"); comment_on(&mut screen, Side::Old, 10, "why drop the default?"); - ctrl_g(&mut screen); - press(&mut screen, KeyCode::Enter); + summary(&mut screen); + post_it(&mut screen); let Mode::Post(confirm) = &screen.mode else { panic!("the summary stays open") }; let failed = confirm.failed.clone().expect("a reason"); assert_eq!( @@ -251,8 +274,8 @@ fn gh_errors_are_named_and_post_nothing() { pull.answer_api(stdout, stderr, 1); let mut screen = pull.open(); comment_on(&mut screen, Side::New, 9, "name the total"); - ctrl_g(&mut screen); - press(&mut screen, KeyCode::Enter); + summary(&mut screen); + post_it(&mut screen); let Mode::Post(confirm) = &screen.mode else { panic!("the summary stays open") }; let failed = confirm.failed.clone().unwrap_or_default(); assert!(failed.starts_with(&format!("Nothing was posted: {says}")), "{failed}"); @@ -269,11 +292,10 @@ fn when_the_pr_moved_on_the_summary_says_so_and_comments_stay_on_the_reviewed_co comment_on(&mut screen, Side::New, 9, "name the total"); pull.push_head(&format!("# greeter\n{AFTER}")); let now = git_in(&pull.work(), &["rev-parse", "feature"]); - ctrl_g(&mut screen); - let rows = frame(&mut screen, 120, 40); + let rows = summary(&mut screen); let moved = rows.iter().find(|r| r.contains("The PR moved on")).expect("the warning"); assert!(moved.contains(&now[..7]), "{moved}"); - press(&mut screen, KeyCode::Enter); + post_it(&mut screen); let [request] = pull.requests().try_into().expect("one request"); assert_eq!(request["commit_id"], reviewed.as_str()); assert_eq!(request["comments"][0]["line"], 9); @@ -323,8 +345,8 @@ fn a_note_both_sent_and_posted_says_so_even_when_its_title_has_no_room() { ); screen.store.add(outside).expect("adds"); keys(&mut screen, "E"); - ctrl_g(&mut screen); - press(&mut screen, KeyCode::Enter); + summary(&mut screen); + post_it(&mut screen); open_notes(&mut screen); let rows = frame(&mut screen, 120, 40); let title = row_with(&rows, "app.py 14-15 new"); @@ -343,8 +365,8 @@ fn an_inline_box_says_its_note_was_posted() { comment_on(&mut screen, Side::New, 5, "say hello properly"); let rows = frame(&mut screen, 120, 40); assert!(!row_with(&rows, "comment \u{b7} L5").contains("posted"), "{rows:#?}"); - ctrl_g(&mut screen); - press(&mut screen, KeyCode::Enter); + summary(&mut screen); + post_it(&mut screen); let rows = frame(&mut screen, 120, 40); assert!(row_with(&rows, "comment \u{b7} L5").contains("\u{b7} posted"), "{rows:#?}"); } @@ -361,9 +383,78 @@ fn the_summary_says_when_the_pr_is_merged() { let mut view: serde_json::Value = serde_json::from_str(&read(&path)).expect("JSON"); view["state"] = "MERGED".into(); std::fs::write(&path, view.to_string()).expect("view.json"); - ctrl_g(&mut screen); - let rows = frame(&mut screen, 120, 40); + let rows = summary(&mut screen); row_with(&rows, "The PR is merged. GitHub still takes a review on it."); - press(&mut screen, KeyCode::Enter); + post_it(&mut screen); assert_eq!(pull.requests().len(), 1, "it still posts"); } + +/// The summary is what the person says yes to: an `Enter` that came before it was on screen +/// (typed ahead while GitHub was asked about the PR, or a double press) posts nothing. +#[test] +fn enter_before_the_summary_is_on_screen_posts_nothing() { + let pull = Pull::new("post-early"); + pull.answer_created(); + let mut screen = pull.open(); + comment_on(&mut screen, Side::New, 9, "name the total"); + ctrl_g(&mut screen); + press(&mut screen, KeyCode::Enter); + tick_until(&mut screen, |c| c.head != crate::review::post::Head::Checking); + press(&mut screen, KeyCode::Enter); + // The menu, with Enter pressed twice in a row. + press(&mut screen, KeyCode::Esc); + keys(&mut screen, "mj"); + press(&mut screen, KeyCode::Enter); + press(&mut screen, KeyCode::Enter); + tick_until(&mut screen, |c| c.head != crate::review::post::Head::Checking); + press(&mut screen, KeyCode::Enter); + assert_eq!(pull.requests().len(), 0, "no frame showed the summary: nothing posted"); + let Mode::Post(confirm) = &screen.mode else { panic!("the summary waits") }; + assert!(!confirm.shown && !confirm.posting); + // Drawn once: the keys waiting are dropped, and the next Enter posts. + let _ = frame(&mut screen, 120, 40); + assert!(!screen.after_draw(), "only the first frame drops the waiting keys"); + post_it(&mut screen); + assert_eq!(pull.requests().len(), 1); +} + +/// A post whose answer never came back may exist on GitHub: say so, and mark nothing posted. +#[test] +fn a_post_with_no_clear_answer_may_have_been_posted() { + let pull = Pull::new("post-unsure"); + pull.answer_api("", "gh: Bad Gateway (HTTP 502)\n", 1); + let mut screen = pull.open(); + comment_on(&mut screen, Side::New, 9, "name the total"); + summary(&mut screen); + post_it(&mut screen); + let Mode::Post(confirm) = &screen.mode else { panic!("the summary stays open") }; + let failed = confirm.failed.clone().unwrap_or_default(); + assert!(failed.starts_with("This may have been posted: GitHub's answer did not come back"), "{failed}"); + assert!(failed.ends_with(&format!("before you post again: {URL}/pull/7")), "{failed}"); + assert_eq!(screen.status.as_deref(), Some("may have been posted to GitHub: check the pull request")); + assert_eq!(screen.store.posts(), []); +} + +/// A note longer than GitHub takes is named in the summary, before Enter, and nothing goes. +#[test] +fn a_note_too_long_for_github_is_named_before_posting() { + let pull = Pull::new("post-long"); + pull.answer_created(); + let mut screen = pull.open(); + comment_on(&mut screen, Side::New, 5, "short for now"); + let id = screen.store.annotations()[0].id.clone(); + let long = "x".repeat(plannotator_tui_review::post::MAX_BODY_CHARS + 1); + screen + .store + .edit(&id, |n| { + n.text = Some(long.clone()); + true + }) + .expect("edits"); + let rows = summary(&mut screen); + row_with(&rows, "The note on app.py:5 new is 65537 characters; GitHub takes"); + post_it(&mut screen); + assert_eq!(pull.requests().len(), 0); + let Mode::Post(confirm) = &screen.mode else { panic!("the summary stays open") }; + assert_eq!(confirm.failed.as_deref(), Some("Nothing was posted: shorten the notes named above first.")); +} From aa6d6dc5da9caa031ca32a49e25bb9e281d65989 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Sat, 28 Nov 2026 18:15:52 -0500 Subject: [PATCH 15/16] fix(review): the key help names post in the review menu again; test ctrl+g yields to an older config --- crates/plannotator-tui/src/keys/tests.rs | 25 +++++++++++++++++++ crates/plannotator-tui/src/review/overlays.rs | 2 +- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/plannotator-tui/src/keys/tests.rs b/crates/plannotator-tui/src/keys/tests.rs index 4d1f4813..91b91e65 100644 --- a/crates/plannotator-tui/src/keys/tests.rs +++ b/crates/plannotator-tui/src/keys/tests.rs @@ -368,3 +368,28 @@ 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 post_to_github_is_ctrl_g_in_the_code_review_and_yields_to_an_older_config_that_gave_it_away() { + let ctrl_g = press(KeyCode::Char('g'), KeyModifiers::CONTROL); + let keymap = Keymap::default(); + assert_eq!(keymap.action(&ctrl_g, REVIEW_GLOBAL), Some(PostToGithub)); + // (config, `post-to-github`) + let table = [ + ("", "ctrl+g"), + ("send = [\"ctrl+g\"]\n", ""), + ("next-hunk = [\"ctrl+g\"]\n", ""), + ("toggle-notes = [\"ctrl+g\"]\n", ""), + // `ctrl+g` in the document screen only: the code review keeps it. + ("word-forward = [\"ctrl+g\"]\n", "ctrl+g"), + ("post-to-github = [\"ctrl+p\"]\n", "ctrl+p"), + ("post-to-github = []\n", ""), + ]; + for (config, key) in table { + let keymap = parse(config).unwrap_or_else(|err| panic!("{config:?} loads: {err}")); + assert_eq!(keymap.check(), Ok(()), "{config:?}"); + assert_eq!(keymap.hint(PostToGithub), key, "post-to-github in {config:?}"); + } + let keymap = parse("send = [\"ctrl+g\"]\n").expect("loads"); + assert_eq!(keymap.action(&ctrl_g, REVIEW_GLOBAL), Some(Send), "the user's meaning stays"); +} diff --git a/crates/plannotator-tui/src/review/overlays.rs b/crates/plannotator-tui/src/review/overlays.rs index 2ef4b1c7..63aa7883 100644 --- a/crates/plannotator-tui/src/review/overlays.rs +++ b/crates/plannotator-tui/src/review/overlays.rs @@ -89,7 +89,7 @@ impl Screen { (key(&[Action::ChangeComment, Action::PostToGithub]), CHANGE_AND_POST), ( key(&[Action::ReviewMenu, Action::UndoFinish]), - "review menu: comment, resend, finish / undo a finish or a removal", + "review menu: comment, post, resend, finish / undo a finish or a removal", ), (key(&[Action::PickTarget]), "choose the agent Send goes to"), ( From 488a214fdbe27cba860dca07ad6435815a95058a Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Sat, 28 Nov 2026 18:15:52 -0500 Subject: [PATCH 16/16] docs(review): posting waits for the summary, runs in the background, and names long notes --- README.md | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index f817c9fb..2ff523b1 100644 --- a/README.md +++ b/README.md @@ -445,16 +445,19 @@ request as one GitHub review, as well as (not instead of) sending them to the ag offered only in a pull request review; anywhere else it says why not. A summary always comes first, and nothing leaves your computer until you press `Enter` -there (`Esc` cancels; no setting skips it). It shows the repository and PR number, how many -notes become inline comments, how many go into the review's body and why, what is skipped, -and the verdict: **Comment** by default, or **Approve** or **Request changes** if you pick -one with `h`/`l`, as the browser app offers them. Notes are laid out the way the browser app -posts a review: +there (`Esc` cancels; no setting skips it). `Enter` counts only once the summary is on +screen: a key typed before it appeared is dropped. It shows the repository and PR number, +how many notes become inline comments, how many go into the review's body and why, what is +skipped, and the verdict: **Comment** by default, or **Approve** or **Request changes** if +you pick one with `h`/`l`, as the browser app offers them. Notes are laid out the way the +browser app posts a review: - Line notes become inline comments: `RIGHT` for new lines, `LEFT` for old (removed) lines, a range as `start_line` to `line`. A suggestion becomes a `suggestion` block that GitHub can apply, fenced with more backticks than the code has (a suggestion on Markdown - can hold a fence of its own). + can hold a fence of its own). GitHub applies suggestions to new lines only, so one on + removed lines (made in the browser or by Pi) goes as a plain comment with the code + quoted; the summary counts those. - A note on the whole change, a note on a file (`**path:** text`), and a line note that is outdated or whose lines the diff no longer shows (quoted with the code it was made on) go in the review body. The browser posts file notes as file-level threads, which takes @@ -468,14 +471,23 @@ repos/OWNER/REPO/pulls/N/reviews`) under your `gh` login; no token passes throug plannotator-tui. GitHub takes all of it or none of it. Comments are anchored to the commit you reviewed (the one the diff was fetched at). If the pull request has new commits since, the summary says so, and `r` reloads it first if you want to review those. It also says -when the pull request is closed or merged; GitHub still takes a review then. A post that -fails posts nothing and says why in the summary: `gh` not logged in, no permission, the +when the pull request is closed or merged; GitHub still takes a review then, and it names +any note longer than GitHub takes (65,536 characters), or the kind of notes that make the +review body too long, so you can shorten them before you post. + +Checking the pull request and posting run in the background, so the screen never freezes: +the summary says what it waits for, and `gh` is stopped after a minute. A post GitHub +refused posts nothing and says why in the summary: `gh` not logged in, no permission, the reviewed commit force-pushed away, GitHub's rate limit, no connection, or a comment GitHub -would not place (the summary lists where each inline comment was). +would not place (the summary lists where each inline comment was). A post whose answer +never came back (no answer within the minute, a connection lost on the way, a gateway +error) may have been posted: the summary says so and asks you to check the pull request +before you post again. After a post, the footer shows the review's link, and the rail and the notes drawn in the -diff mark the notes **posted**, a state of its own beside **sent**: a note can be both. Posted marks are saved with the -notes, and a later post carries only notes that are new or edited since. An edited note is +diff mark the notes **posted**, a state of its own beside **sent**: a note can be both. +Posted marks are saved with the notes, and a later post carries only notes that are new or +edited since. An edited note is posted again as a new comment (the summary says how many); the earlier one stays on GitHub. A Pi session can leave notes on the diff too (see [Pi](#pi)). Notes are saved with the