From a5d7b8b0b3bc158d3c9d24330a5ded98e864750d Mon Sep 17 00:00:00 2001 From: LHaghfoss Date: Wed, 25 Nov 2026 23:36:35 +0100 Subject: [PATCH 1/2] feat(engine): accept line ranges in a pull request review --- rustcode/engine/src/lib.rs | 1 + rustcode/engine/src/pull_requests.rs | 69 +------------ rustcode/engine/src/pull_review.rs | 140 +++++++++++++++++++++++++++ scripts/rust-size-baseline.txt | 2 +- 4 files changed, 143 insertions(+), 69 deletions(-) create mode 100644 rustcode/engine/src/pull_review.rs diff --git a/rustcode/engine/src/lib.rs b/rustcode/engine/src/lib.rs index e1c9745d7..c4059277b 100644 --- a/rustcode/engine/src/lib.rs +++ b/rustcode/engine/src/lib.rs @@ -53,6 +53,7 @@ pub mod preview; pub mod prompt_commands; pub mod provider_auth; pub mod pull_requests; +pub mod pull_review; pub mod pull_watch; pub mod raw_cli; pub mod remote; diff --git a/rustcode/engine/src/pull_requests.rs b/rustcode/engine/src/pull_requests.rs index b14ae812a..11091ddc3 100644 --- a/rustcode/engine/src/pull_requests.rs +++ b/rustcode/engine/src/pull_requests.rs @@ -480,59 +480,12 @@ pub async fn diff(cwd: &Path, number: u64) -> Result { Ok(PullDiff { diff, truncated }) } -/// One line comment of a review: `line` in the file on `side` (`RIGHT` -/// for the pull request's version, `LEFT` for the base). -#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, Serialize)] -pub struct ReviewComment { - pub path: String, - pub line: u64, - pub side: String, - pub body: String, -} - #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct PostedReview { pub url: Option, } -/// The provider's review request: one review at `commit_id`, with its -/// comments, so a review is posted whole or not at all. -pub fn review_payload( - commit_id: &str, - event: &str, - body: &str, - comments: &[ReviewComment], -) -> Result { - let event = match event { - "APPROVE" | "REQUEST_CHANGES" | "COMMENT" => event, - other => { - return Err(PullError { - code: "failed", - message: format!("unknown review event {other}"), - }); - } - }; - if commit_id.is_empty() { - return Err(PullError { - code: "failed", - message: "the review names no commit".to_owned(), - }); - } - for comment in comments { - if !matches!(comment.side.as_str(), "LEFT" | "RIGHT") || comment.line == 0 { - return Err(PullError { - code: "failed", - message: format!("{} has no line to comment on", comment.path), - }); - } - } - Ok(serde_json::json!({ - "commit_id": commit_id, - "event": event, - "body": body, - "comments": comments, - })) -} +pub use crate::pull_review::{ReviewComment, review_payload}; /// Post one review. A review the provider refuses comes back as `failed` /// with its message; one whose answer never arrived as `uncertain`, which @@ -2109,26 +2062,6 @@ mod tests { assert_eq!((other.code, other.message.as_str()), ("failed", "HTTP 502")); } - #[test] - fn a_review_payload_is_one_review_at_one_commit() { - let comments = vec![ReviewComment { - path: "a.rs".into(), - line: 12, - side: "RIGHT".into(), - body: "Why?".into(), - }]; - let payload = review_payload("da4593b", "COMMENT", "Looks fine.", &comments).unwrap(); - assert_eq!(payload["commit_id"], "da4593b"); - assert_eq!(payload["event"], "COMMENT"); - assert_eq!(payload["comments"][0]["line"], 12); - assert_eq!(payload["comments"][0]["side"], "RIGHT"); - assert!(review_payload("da4593b", "MERGE", "", &[]).is_err()); - assert!(review_payload("", "COMMENT", "x", &[]).is_err()); - let mut bad = comments.clone(); - bad[0].side = "MIDDLE".into(); - assert!(review_payload("da4593b", "COMMENT", "", &bad).is_err()); - } - #[test] fn configured_provider_hosts_match_remotes() { let hosts = super::ProviderHosts::from_config("enterprise.example:\n users:\n", None); diff --git a/rustcode/engine/src/pull_review.rs b/rustcode/engine/src/pull_review.rs new file mode 100644 index 000000000..ae1432af5 --- /dev/null +++ b/rustcode/engine/src/pull_review.rs @@ -0,0 +1,140 @@ +//! The review a pull request receives from the app: its line comments, each +//! on one line or a range of lines, checked and shaped into the provider's +//! request so a review is posted whole or not at all. + +use crate::pull_requests::PullError; +use serde::Serialize; +use serde_json::Value; + +/// One line comment of a review: `line` in the file on `side` (`RIGHT` +/// for the pull request's version, `LEFT` for the base), from `start_line` +/// on `start_side` when it covers a range. +#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, Serialize)] +pub struct ReviewComment { + pub path: String, + pub line: u64, + pub side: String, + pub body: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start_line: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start_side: Option, +} + +fn refused(message: String) -> PullError { + PullError { + code: "failed", + message, + } +} + +/// The provider's review request: one review at `commit_id`, with its +/// comments. A range that starts on its own last line is sent as a single +/// line, and one that starts after it is refused. +pub fn review_payload( + commit_id: &str, + event: &str, + body: &str, + comments: &[ReviewComment], +) -> Result { + let event = match event { + "APPROVE" | "REQUEST_CHANGES" | "COMMENT" => event, + other => return Err(refused(format!("unknown review event {other}"))), + }; + if commit_id.is_empty() { + return Err(refused("the review names no commit".to_owned())); + } + let mut shaped = Vec::with_capacity(comments.len()); + for comment in comments { + let side_ok = |side: &str| matches!(side, "LEFT" | "RIGHT"); + if !side_ok(&comment.side) || comment.line == 0 { + return Err(refused(format!( + "{} has no line to comment on", + comment.path + ))); + } + let mut comment = comment.clone(); + match comment.start_line { + Some(start) if start == comment.line => { + comment.start_line = None; + comment.start_side = None; + } + Some(start) if start == 0 || start > comment.line => { + return Err(refused(format!( + "{} has a range that ends before it starts", + comment.path + ))); + } + Some(_) => { + let side = comment + .start_side + .clone() + .unwrap_or_else(|| comment.side.clone()); + if !side_ok(&side) { + return Err(refused(format!( + "{} has no line to comment on", + comment.path + ))); + } + comment.start_side = Some(side); + } + None => comment.start_side = None, + } + shaped.push(comment); + } + Ok(serde_json::json!({ + "commit_id": commit_id, + "event": event, + "body": body, + "comments": shaped, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn comment(line: u64, start_line: Option) -> ReviewComment { + ReviewComment { + path: "a.rs".into(), + line, + side: "RIGHT".into(), + body: "Why?".into(), + start_line, + start_side: None, + } + } + + #[test] + fn a_review_payload_is_one_review_at_one_commit() { + let comments = vec![comment(12, None)]; + let payload = review_payload("da4593b", "COMMENT", "Looks fine.", &comments).unwrap(); + assert_eq!(payload["commit_id"], "da4593b"); + assert_eq!(payload["event"], "COMMENT"); + assert_eq!(payload["comments"][0]["line"], 12); + assert_eq!(payload["comments"][0]["side"], "RIGHT"); + assert!(payload["comments"][0].get("start_line").is_none()); + assert!(review_payload("da4593b", "MERGE", "", &[]).is_err()); + assert!(review_payload("", "COMMENT", "x", &[]).is_err()); + let mut bad = comments.clone(); + bad[0].side = "MIDDLE".into(); + assert!(review_payload("da4593b", "COMMENT", "", &bad).is_err()); + } + + #[test] + fn a_range_comment_names_its_first_line_and_side() { + let payload = review_payload("da4593b", "COMMENT", "", &[comment(18, Some(12))]).unwrap(); + assert_eq!(payload["comments"][0]["start_line"], 12); + assert_eq!(payload["comments"][0]["start_side"], "RIGHT"); + assert_eq!(payload["comments"][0]["line"], 18); + let single = review_payload("da4593b", "COMMENT", "", &[comment(7, Some(7))]).unwrap(); + assert!(single["comments"][0].get("start_line").is_none()); + assert!(single["comments"][0].get("start_side").is_none()); + assert!(review_payload("da4593b", "COMMENT", "", &[comment(7, Some(9))]).is_err()); + let parsed: ReviewComment = serde_json::from_value( + serde_json::json!({"path": "a.rs", "line": 3, "side": "LEFT", "body": "x"}), + ) + .unwrap(); + assert_eq!(parsed.start_line, None); + } +} diff --git a/scripts/rust-size-baseline.txt b/scripts/rust-size-baseline.txt index ad54e9c52..87b9225a3 100644 --- a/scripts/rust-size-baseline.txt +++ b/scripts/rust-size-baseline.txt @@ -30,7 +30,7 @@ 3600 rustcode/engine/src/orchestration/local_threads.rs 2500 rustcode/engine/src/orchestration/mcp_server.rs 2700 rustcode/engine/src/orchestration/outside.rs -2600 rustcode/engine/src/pull_requests.rs +2523 rustcode/engine/src/pull_requests.rs 2200 rustcode/engine/src/pull_watch.rs 2500 rustcode/engine/src/remote/contract.rs 2300 rustcode/engine/src/remote/ops.rs From cb3a628486f878b0985bf1d84b0b1419d139bfaf Mon Sep 17 00:00:00 2001 From: LHaghfoss Date: Wed, 25 Nov 2026 23:39:29 +0100 Subject: [PATCH 2/2] feat(desktop): comment on a range of lines in Review --- apps/desktop/src/state/diff.test.ts | 39 ++++++++++++++++ apps/desktop/src/state/diff.ts | 44 ++++++++++++++++-- apps/desktop/src/state/reviewDrafts.ts | 1 + apps/desktop/src/ui/Review.tsx | 62 +++++++++++++++++++++----- 4 files changed, 131 insertions(+), 15 deletions(-) create mode 100644 apps/desktop/src/state/diff.test.ts diff --git a/apps/desktop/src/state/diff.test.ts b/apps/desktop/src/state/diff.test.ts new file mode 100644 index 000000000..e857409ea --- /dev/null +++ b/apps/desktop/src/state/diff.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, test } from "bun:test"; +import { parsePatch, QUOTED_LINES, rangeLines, reviewMessage } from "./diff"; + +const patch = parsePatch([ + "@@ -1,3 +1,4 @@", + " one", + "-two", + "+TWO", + "+extra", + " three", + "@@ -10,2 +11,2 @@", + " ten", + " eleven", +]); + +describe("review ranges", () => { + test("a range takes the lines of one side, in order, either way round", () => { + expect(rangeLines(patch, "RIGHT", 1, 3)?.map((l) => l.text)).toEqual(["one", "TWO", "extra"]); + expect(rangeLines(patch, "RIGHT", 3, 1)?.map((l) => l.text)).toEqual(["one", "TWO", "extra"]); + expect(rangeLines(patch, "LEFT", 1, 3)?.map((l) => l.text)).toEqual(["one", "two", "three"]); + }); + + test("a range does not cross a hunk or reach a line the diff lacks", () => { + expect(rangeLines(patch, "RIGHT", 3, 11)).toBeNull(); + expect(rangeLines(patch, "RIGHT", 1, 7)).toBeNull(); + }); + + test("the message names a range and quotes its lines, eliding the rest", () => { + const code = Array.from({ length: QUOTED_LINES + 2 }, (_, i) => `line ${i}`).join("\n"); + const message = reviewMessage("branch b", [ + { path: "a.ts", line: 18, startLine: 11, side: "RIGHT", body: "Split this.", code }, + { path: "b.ts", line: 4, side: "LEFT", body: "Keep it.", code: "old();" }, + ]); + expect(message).toContain("- `a.ts:11-18`: Split this.\n > line 0\n"); + expect(message).toContain(` > line ${QUOTED_LINES - 1}\n > …`); + expect(message).not.toContain(`line ${QUOTED_LINES}\n`); + expect(message).toContain("- `b.ts:4` (removed line): Keep it.\n > old();"); + }); +}); diff --git a/apps/desktop/src/state/diff.ts b/apps/desktop/src/state/diff.ts index f0d4a4d71..ec667f0c0 100644 --- a/apps/desktop/src/state/diff.ts +++ b/apps/desktop/src/state/diff.ts @@ -70,18 +70,29 @@ export function splitRows(lines: PatchLine[]): SplitRow[] { export interface ReviewComment { path: string; + /** The last line commented on; with `startLine`, the end of the range. */ line: number; + /** The first line of a range, on the same side. */ + startLine?: number; side: "LEFT" | "RIGHT"; body: string; - /** The line commented on, quoted in the message. */ + /** The lines commented on, quoted in the message. */ code: string; } +/** Lines of a range quoted in a message; the rest is elided. */ +export const QUOTED_LINES = 6; + /** The comments as one message for the agent working on these changes. */ export function reviewMessage(source: string, comments: ReviewComment[], note = ""): string { const items = comments.map((c) => { - const quote = c.code.trim() ? `\n > ${c.code.trim()}` : ""; - return `- \`${c.path}:${c.line}\`${c.side === "LEFT" ? " (removed line)" : ""}: ${c.body.trim()}${quote}`; + const ranged = c.startLine !== undefined && c.startLine !== c.line; + const where = ranged ? `${c.path}:${c.startLine}-${c.line}` : `${c.path}:${c.line}`; + const code = c.code.split("\n"); + const shown = code.slice(0, QUOTED_LINES).map((line) => `\n > ${line.trimEnd()}`); + const quote = c.code.trim() ? shown.join("") + (code.length > QUOTED_LINES ? "\n > …" : "") : ""; + const removed = c.side === "LEFT" ? (ranged ? " (removed lines)" : " (removed line)") : ""; + return `- \`${where}\`${removed}: ${c.body.trim()}${quote}`; }); return [`Review comments on ${source}:`, note.trim(), items.join("\n")].filter(Boolean).join("\n\n"); } @@ -96,3 +107,30 @@ export function fileTree(paths: string[]): { dir: string; files: string[] }[] { } return [...byDir.entries()].map(([dir, files]) => ({ dir, files })); } + +/** + * The lines numbered `from` to `to` on one side of a file's patch, in order, or null when the + * range crosses a hunk header (lines the diff does not show) or a number is missing. + */ +export function rangeLines( + lines: readonly PatchLine[], + side: "LEFT" | "RIGHT", + from: number, + to: number, +): PatchLine[] | null { + const [lo, hi] = from <= to ? [from, to] : [to, from]; + const out: PatchLine[] = []; + let open = false; + for (const line of lines) { + if (line.kind === "hunk") { + if (open) return null; + continue; + } + const n = side === "LEFT" ? line.old : line.new; + if (n === undefined) continue; + if (n === lo) open = true; + if (open) out.push(line); + if (n === hi) return open ? out : null; + } + return null; +} diff --git a/apps/desktop/src/state/reviewDrafts.ts b/apps/desktop/src/state/reviewDrafts.ts index 6d644876a..57d7450a4 100644 --- a/apps/desktop/src/state/reviewDrafts.ts +++ b/apps/desktop/src/state/reviewDrafts.ts @@ -42,6 +42,7 @@ function comment(value: unknown): ReviewComment | null { side: c.side, body: c.body, code: typeof c.code === "string" ? c.code : "", + ...(typeof c.startLine === "number" ? { startLine: c.startLine } : {}), }; } diff --git a/apps/desktop/src/ui/Review.tsx b/apps/desktop/src/ui/Review.tsx index b5fee24c8..ef3c6cb0d 100644 --- a/apps/desktop/src/ui/Review.tsx +++ b/apps/desktop/src/ui/Review.tsx @@ -25,6 +25,7 @@ import { type PatchLine, parsePatch, type ReviewComment, + rangeLines, reviewMessage, splitRows, } from "../state/diff"; @@ -149,21 +150,24 @@ interface LineProps { line: PatchLine; html: string | null | undefined; side: "LEFT" | "RIGHT"; - onComment: () => void; + onComment: (extend: boolean) => void; commented: boolean; + /** Inside the range a comment is being written on. */ + picked?: boolean; } -function Gutter({ line, side, onComment, commented }: Omit) { +function Gutter({ line, side, onComment, commented, picked }: Omit) { const n = side === "LEFT" ? line.old : line.new; return (