diff --git a/apps/desktop/src/state/reviewDrafts.test.ts b/apps/desktop/src/state/reviewDrafts.test.ts new file mode 100644 index 000000000..c446797f2 --- /dev/null +++ b/apps/desktop/src/state/reviewDrafts.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, test } from "bun:test"; +import type { ReviewComment } from "./diff"; +import { + draftCounts, + EMPTY_DRAFT, + hasDraft, + MAX_REVIEW_DRAFTS, + parseReviewDrafts, + reviewDraftKey, + withReviewDraft, +} from "./reviewDrafts"; + +const note = (path: string, line = 1): ReviewComment => ({ + path, + line, + side: "RIGHT", + body: `about ${path}`, + code: "let x = 1;", +}); + +describe("review drafts", () => { + test("a draft is kept per thread and source", () => { + const turn = reviewDraftKey("t1", "turn:3"); + const branch = reviewDraftKey("t1", "branch"); + let book = withReviewDraft({}, turn, { comments: [note("a.ts")], note: "" }); + book = withReviewDraft(book, branch, { comments: [], note: "looks fine" }); + book = withReviewDraft(book, reviewDraftKey("t2", "uncommitted"), { comments: [note("b.ts")], note: "" }); + expect(book[turn]?.comments.map((c) => c.path)).toEqual(["a.ts"]); + expect(book[branch]?.comments).toEqual([]); + expect(draftCounts(book, "t1")).toEqual({ "turn:3": 1, branch: 1 }); + expect(draftCounts(book, "t2")).toEqual({ uncommitted: 1 }); + }); + + test("an empty draft forgets its source, and an unchanged book is the same record", () => { + const key = reviewDraftKey("t1", "uncommitted"); + const book = withReviewDraft({}, key, { comments: [note("a.ts")], note: "" }); + expect(withReviewDraft(book, key, EMPTY_DRAFT)).toEqual({}); + expect(withReviewDraft({}, key, { comments: [], note: " " })).toEqual({}); + const empty = {}; + expect(withReviewDraft(empty, key, EMPTY_DRAFT)).toBe(empty); + expect(hasDraft(undefined)).toBe(false); + }); + + test("storage round-trips and drops what is malformed", () => { + const key = reviewDraftKey("t1", "pull:7"); + const book = withReviewDraft({}, key, { comments: [note("a.ts", 4)], note: "n" }); + expect(parseReviewDrafts(JSON.stringify(book))).toEqual(book); + const raw = JSON.stringify({ + [key]: { comments: [{ path: "a.ts", line: "4", side: "RIGHT", body: "x" }, note("b.ts")], note: 3 }, + other: "text", + }); + expect(parseReviewDrafts(raw)).toEqual({ [key]: { comments: [note("b.ts")], note: "" } }); + expect(parseReviewDrafts("not json")).toEqual({}); + expect(parseReviewDrafts(null)).toEqual({}); + }); + + test("only the newest sources are kept", () => { + let book = {}; + for (let i = 0; i <= MAX_REVIEW_DRAFTS; i++) + book = withReviewDraft(book, reviewDraftKey("t", `turn:${i}`), { comments: [], note: "n" }); + const keys = Object.keys(book); + expect(keys).toHaveLength(MAX_REVIEW_DRAFTS); + expect(keys[0]).toBe(reviewDraftKey("t", "turn:1")); + }); +}); diff --git a/apps/desktop/src/state/reviewDrafts.ts b/apps/desktop/src/state/reviewDrafts.ts new file mode 100644 index 000000000..6d644876a --- /dev/null +++ b/apps/desktop/src/state/reviewDrafts.ts @@ -0,0 +1,101 @@ +import { create } from "zustand"; +import { readStorage, writeStorage } from "../lib/storage"; +import type { ReviewComment } from "./diff"; + +/** + * Review drafts: the line comments and note written on the Review screen, per thread and per source + * (the uncommitted changes, the branch, one turn, one pull request), kept in app storage so leaving + * the screen or reloading the app loses none. Drafts written on one source never travel with + * another: their lines belong to that diff. + */ +export const REVIEW_DRAFTS_KEY = "rustcode.reviewDrafts"; +/** At most this many sources keep drafts, the ones written longest ago dropped first. */ +export const MAX_REVIEW_DRAFTS = 100; + +export interface ReviewDraft { + comments: ReviewComment[]; + note: string; +} + +export type ReviewDraftBook = Record; + +export const EMPTY_DRAFT: ReviewDraft = { comments: [], note: "" }; + +/** The key of one source's drafts in one thread. */ +export function reviewDraftKey(threadId: string, source: string): string { + return `${threadId}\n${source}`; +} + +/** Whether a draft holds anything to keep. */ +export function hasDraft(draft: ReviewDraft | undefined): draft is ReviewDraft { + return !!draft && (draft.comments.length > 0 || draft.note.trim().length > 0); +} + +function comment(value: unknown): ReviewComment | null { + if (!value || typeof value !== "object") return null; + const c = value as Record; + if (typeof c.path !== "string" || typeof c.body !== "string") return null; + if (typeof c.line !== "number" || (c.side !== "LEFT" && c.side !== "RIGHT")) return null; + return { + path: c.path, + line: c.line, + side: c.side, + body: c.body, + code: typeof c.code === "string" ? c.code : "", + }; +} + +/** A stored book, with anything malformed left out. */ +export function parseReviewDrafts(raw: string | null): ReviewDraftBook { + if (!raw) return {}; + let value: unknown; + try { + value = JSON.parse(raw); + } catch { + return {}; + } + if (!value || typeof value !== "object" || Array.isArray(value)) return {}; + const out: ReviewDraftBook = {}; + for (const [key, entry] of Object.entries(value as Record)) { + if (!entry || typeof entry !== "object") continue; + const e = entry as Record; + const draft: ReviewDraft = { + comments: Array.isArray(e.comments) + ? e.comments.map(comment).filter((c): c is ReviewComment => c !== null) + : [], + note: typeof e.note === "string" ? e.note : "", + }; + if (hasDraft(draft)) out[key] = draft; + } + return Object.fromEntries(Object.entries(out).slice(-MAX_REVIEW_DRAFTS)); +} + +/** The book with one source's draft written: an empty draft forgets it, a written one moves last. */ +export function withReviewDraft(book: ReviewDraftBook, key: string, draft: ReviewDraft): ReviewDraftBook { + const { [key]: _previous, ...rest } = book; + if (!hasDraft(draft)) return key in book ? rest : book; + return Object.fromEntries(Object.entries({ ...rest, [key]: draft }).slice(-MAX_REVIEW_DRAFTS)); +} + +/** How many comments each source of a thread holds in drafts, by source key. */ +export function draftCounts(book: ReviewDraftBook, threadId: string): Record { + const prefix = reviewDraftKey(threadId, ""); + const out: Record = {}; + for (const [key, draft] of Object.entries(book)) { + if (key.startsWith(prefix)) out[key.slice(prefix.length)] = Math.max(draft.comments.length, 1); + } + return out; +} + +export const useReviewDrafts = create<{ book: ReviewDraftBook }>(() => ({ + book: parseReviewDrafts(readStorage(REVIEW_DRAFTS_KEY)), +})); + +/** Writes one source's draft and keeps the book in app storage. */ +export function setReviewDraft(key: string, draft: ReviewDraft): void { + const before = useReviewDrafts.getState().book; + const book = withReviewDraft(before, key, draft); + if (book === before) return; + useReviewDrafts.setState({ book }); + writeStorage(REVIEW_DRAFTS_KEY, Object.keys(book).length ? JSON.stringify(book) : null); +} diff --git a/apps/desktop/src/ui/Review.tsx b/apps/desktop/src/ui/Review.tsx index 1d25b3596..9002d0048 100644 --- a/apps/desktop/src/ui/Review.tsx +++ b/apps/desktop/src/ui/Review.tsx @@ -10,6 +10,7 @@ import { primaryModifier } from "../lib/platform"; // request as one review with line comments (`_rustcode/pulls/review`). import { memo, useCallback, useEffect, useMemo, useState } from "react"; +import { useShallow } from "zustand/react/shallow"; import type { JsonObject } from "../acp/jsonrpc"; import { type PullRequest, parsePullError, pullErrorTitle, repositoryOf } from "../acp/rustcode"; import { Method } from "../acp/types"; @@ -28,6 +29,14 @@ import { splitRows, } from "../state/diff"; import { loadPullDiff, prefetchPullDiff, usePullList } from "../state/pullQueries"; +import { + draftCounts, + EMPTY_DRAFT, + type ReviewDraft, + reviewDraftKey, + setReviewDraft, + useReviewDrafts, +} from "../state/reviewDrafts"; import { featureMissing, refreshCheckpoints, @@ -334,8 +343,21 @@ export function Review({ threadId }: { threadId: string }) { const error = opError(diff); const loading = opRunning(diff); const [selected, setSelected] = useState(null); - const [comments, setComments] = useState([]); - const [note, setNote] = useState(""); + const draftKey = reviewDraftKey(threadId, sourceKey(source)); + const draft = useReviewDrafts((s) => s.book[draftKey]) ?? EMPTY_DRAFT; + const counts = useReviewDrafts(useShallow((s) => draftCounts(s.book, threadId))); + const { comments, note } = draft; + const writeDraft = (next: Partial) => setReviewDraft(draftKey, { ...draft, ...next }); + const setComments = (update: (all: ReviewComment[]) => ReviewComment[]) => + writeDraft({ comments: update(comments) }); + const setNote = (text: string) => writeDraft({ note: text }); + const discard = () => { + const kept = draft; + setReviewDraft(draftKey, EMPTY_DRAFT); + toast("Review draft discarded", "info", { + action: { label: "Undo", run: () => setReviewDraft(draftKey, kept) }, + }); + }; const [event, setEvent] = useState<"COMMENT" | "APPROVE" | "REQUEST_CHANGES">("COMMENT"); const [post, runPost] = useOp(); const posting = opRunning(post); @@ -423,20 +445,21 @@ export function Review({ threadId }: { threadId: string }) { // The branch's counts compare against the base its worktree was made from; the // other scopes name their comparison themselves (HEAD, a turn, a pull request). const base = source.kind === "branch" ? comparisonBase(wt) : undefined; + const counted = (key: string, label: string) => (counts[key] ? `${label} · ${counts[key]}` : label); const sources: { value: string; label: string }[] = [ - { value: "uncommitted", label: "Uncommitted" }, - ...(wt ? [{ value: "branch", label: "Branch" }] : []), - ...(pull ? [{ value: `pull:${pull.number}`, label: `PR #${pull.number}` }] : []), + { value: "uncommitted", label: counted("uncommitted", "Uncommitted") }, + ...(wt ? [{ value: "branch", label: counted("branch", "Branch") }] : []), + ...(pull + ? [{ value: `pull:${pull.number}`, label: counted(`pull:${pull.number}`, `PR #${pull.number}`) }] + : []), ]; const sendToAgent = () => { if (!comments.length && !note.trim()) return; selectThread(threadId); + const key = draftKey; void submit(reviewMessage(label, comments, note)).then((sent) => { - if (sent) { - setComments([]); - setNote(""); - } + if (sent) setReviewDraft(key, EMPTY_DRAFT); }); }; @@ -444,6 +467,7 @@ export function Review({ threadId }: { threadId: string }) { if (source.kind !== "pull") return; const repository = repositoryOf(source.pull.url); if (!repository) return; + const key = draftKey; await runPost(async () => { try { const r = (await request( @@ -463,8 +487,7 @@ export function Review({ threadId }: { threadId: string }) { if (err) toast(`${pullErrorTitle(err.code)}: ${err.message}`, "error"); else { toast("Review posted", "success"); - setComments([]); - setNote(""); + setReviewDraft(key, EMPTY_DRAFT); } } catch (e) { toast(`Could not post the review: ${e instanceof Error ? e.message : String(e)}`, "error"); @@ -486,7 +509,9 @@ export function Review({ threadId }: { threadId: string }) { // click draws the files instead of waiting for `gh`. onIntent={(v) => v.startsWith("pull:") && prefetchPullDiff(cwd, Number(v.slice(5)))} options={ - source.kind === "turn" ? [...sources, { value: "turn", label: `Turn ${source.turn}` }] : sources + source.kind === "turn" + ? [...sources, { value: "turn", label: counted(`turn:${source.turn}`, `Turn ${source.turn}`) }] + : sources } /> {checkpoints && checkpoints.length > 0 ? ( @@ -500,7 +525,7 @@ export function Review({ threadId }: { threadId: string }) { { value: "", label: "Turn…" }, ...checkpoints.map((c) => ({ value: String(c.turn), - label: `${c.turn}. ${clip(c.prompt, 40)}`, + label: counted(`turn:${c.turn}`, `${c.turn}. ${clip(c.prompt, 40)}`), })), ]} /> @@ -672,7 +697,7 @@ export function Review({ threadId }: { threadId: string }) { className="resize-y rounded-lg bg-fill-subtle px-2 py-1.5 text-callout outline-none hover:bg-fill focus:bg-fill" />
- setComments([])}>Discard + Discard {source.kind === "pull" && ( <>