Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions apps/desktop/src/state/diff.test.ts
Original file line number Diff line number Diff line change
@@ -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();");
});
});
44 changes: 41 additions & 3 deletions apps/desktop/src/state/diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
Expand All @@ -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;
}
1 change: 1 addition & 0 deletions apps/desktop/src/state/reviewDrafts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 } : {}),
};
}

Expand Down
62 changes: 50 additions & 12 deletions apps/desktop/src/ui/Review.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
type PatchLine,
parsePatch,
type ReviewComment,
rangeLines,
reviewMessage,
splitRows,
} from "../state/diff";
Expand Down Expand Up @@ -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<LineProps, "html">) {
function Gutter({ line, side, onComment, commented, picked }: Omit<LineProps, "html">) {
const n = side === "LEFT" ? line.old : line.new;
return (
<button
type="button"
onClick={onComment}
onClick={(e) => onComment(e.shiftKey)}
disabled={n === undefined}
aria-label={n === undefined ? undefined : `Comment on line ${n}`}
className={cx(
"group/g relative w-[6ch] shrink-0 pr-1.5 text-right text-fg-faint tabular enabled:hover:bg-accent/20 enabled:hover:text-accent",
commented && "text-accent",
picked && "bg-accent/20 text-accent",
)}
>
<span className="group-hover/g:invisible">{n ?? ""}</span>
Expand Down Expand Up @@ -214,7 +218,12 @@ const FileDiffView = memo(function FileDiffView({
onAdd: (c: ReviewComment) => void;
onRemove: (c: ReviewComment) => void;
}) {
const [editing, setEditing] = useState<{ side: "LEFT" | "RIGHT"; line: number; code: string } | null>(null);
const [editing, setEditing] = useState<{
side: "LEFT" | "RIGHT";
line: number;
startLine?: number;
code: string;
} | null>(null);
// Every line highlighted once, split around the words that changed on it.
const texts = useMemo(() => file.lines.map((line) => line.text), [file.lines]);
const marks = useMemo(() => runWordMarks(file.lines), [file.lines]);
Expand All @@ -226,10 +235,23 @@ const FileDiffView = memo(function FileDiffView({
};
const at = (side: "LEFT" | "RIGHT", n?: number) =>
n === undefined ? [] : comments.filter((c) => c.side === side && c.line === n);
const start = (line: PatchLine, side: "LEFT" | "RIGHT") => {
const start = (line: PatchLine, side: "LEFT" | "RIGHT", extend = false) => {
const n = side === "LEFT" ? line.old : line.new;
if (n !== undefined) setEditing({ side, line: n, code: line.text });
if (n === undefined) return;
const anchor = editing?.side === side ? (editing.startLine ?? editing.line) : undefined;
const range = extend && anchor !== undefined ? rangeLines(file.lines, side, anchor, n) : null;
if (range && range.length > 1) {
const first = Math.min(anchor!, n);
const last = Math.max(anchor!, n);
setEditing({ side, line: last, startLine: first, code: range.map((l) => l.text).join("\n") });
} else setEditing({ side, line: n, code: line.text });
};
const picked = (side: "LEFT" | "RIGHT", n?: number) =>
n !== undefined &&
editing?.side === side &&
editing.startLine !== undefined &&
n >= editing.startLine &&
n <= editing.line;
const after = (line: PatchLine | undefined, side: "LEFT" | "RIGHT") => {
if (!line) return null;
const n = side === "LEFT" ? line.old : line.new;
Expand All @@ -256,7 +278,14 @@ const FileDiffView = memo(function FileDiffView({
<CommentBox
onCancel={() => setEditing(null)}
onSave={(body) => {
onAdd({ path: file.path, line: editing.line, side, body, code: editing.code });
onAdd({
path: file.path,
line: editing.line,
...(editing.startLine !== undefined ? { startLine: editing.startLine } : {}),
side,
body,
code: editing.code,
});
setEditing(null);
}}
/>
Expand All @@ -279,14 +308,16 @@ const FileDiffView = memo(function FileDiffView({
<Gutter
line={line}
side="LEFT"
onComment={() => start(line, "LEFT")}
onComment={(extend) => start(line, "LEFT", extend)}
commented={at("LEFT", line.old).length > 0}
picked={picked("LEFT", line.old)}
/>
<Gutter
line={line}
side="RIGHT"
onComment={() => start(line, line.kind === "del" ? "LEFT" : "RIGHT")}
onComment={(extend) => start(line, line.kind === "del" ? "LEFT" : "RIGHT", extend)}
commented={at("RIGHT", line.new).length > 0}
picked={picked("RIGHT", line.new)}
/>
<span
className={cx(
Expand Down Expand Up @@ -324,8 +355,9 @@ const FileDiffView = memo(function FileDiffView({
<Gutter
line={shown}
side={side}
onComment={() => start(shown, side)}
onComment={(extend) => start(shown, side, extend)}
commented={at(side, side === "LEFT" ? shown.old : shown.new).length > 0}
picked={picked(side, side === "LEFT" ? shown.old : shown.new)}
/>
{code(shown)}
</>
Expand Down Expand Up @@ -536,7 +568,13 @@ export function Review({ threadId }: { threadId: string }) {
commitId: source.pull.headSha,
event,
body: note,
comments: comments.map((c) => ({ path: c.path, line: c.line, side: c.side, body: c.body })),
comments: comments.map((c) => ({
path: c.path,
line: c.line,
side: c.side,
body: c.body,
...(c.startLine !== undefined ? { start_line: c.startLine, start_side: c.side } : {}),
})),
},
60_000,
)) as JsonObject;
Expand Down Expand Up @@ -737,7 +775,7 @@ export function Review({ threadId }: { threadId: string }) {
<DiffCount added={file.added} removed={file.removed} />
<span className="flex-1" />
<span className="shrink-0 text-caption text-fg-faint max-[1300px]:hidden">
Click a line number to comment
Click a line number to comment, Shift-click another to cover a range
</span>
<Tooltip label="Mark viewed (V)">
<label className="flex shrink-0 cursor-pointer items-center gap-1.5 text-caption text-fg-muted hover:text-fg">
Expand Down
1 change: 1 addition & 0 deletions rustcode/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
69 changes: 1 addition & 68 deletions rustcode/engine/src/pull_requests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -480,59 +480,12 @@ pub async fn diff(cwd: &Path, number: u64) -> Result<PullDiff, PullError> {
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<String>,
}

/// 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<Value, PullError> {
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
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading