diff --git a/apps/desktop/src/state/reviewViewed.test.ts b/apps/desktop/src/state/reviewViewed.test.ts new file mode 100644 index 000000000..3d5e66a0e --- /dev/null +++ b/apps/desktop/src/state/reviewViewed.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, test } from "bun:test"; +import type { PatchLine } from "./diff"; +import { + MAX_VIEWED, + parseViewed, + patchHash, + stepFile, + viewedKey, + viewedState, + withViewed, +} from "./reviewViewed"; + +const lines = (text: string): PatchLine[] => [{ kind: "add", text, new: 1 }]; + +describe("review viewed marks", () => { + test("a mark holds while the patch is the same and turns to changed when it moves", () => { + const key = viewedKey("t1", "uncommitted", "src/a.ts"); + const read = patchHash(lines("one")); + const book = withViewed({}, key, read); + expect(viewedState(book, key, read)).toBe("viewed"); + expect(viewedState(book, key, patchHash(lines("two")))).toBe("changed"); + expect(viewedState(book, viewedKey("t1", "branch", "src/a.ts"), read)).toBe("unviewed"); + expect(withViewed(book, key, null)).toEqual({}); + }); + + test("the hash tells kinds and texts apart", () => { + expect(patchHash(lines("x"))).toBe(patchHash(lines("x"))); + expect(patchHash(lines("x"))).not.toBe(patchHash([{ kind: "del", text: "x", old: 1 }])); + expect(patchHash([])).not.toBe(patchHash(lines(""))); + }); + + test("storage round-trips, drops what is malformed and keeps the newest", () => { + let book = {}; + for (let i = 0; i <= MAX_VIEWED; i++) book = withViewed(book, `k${i}`, "h"); + expect(Object.keys(book)).toHaveLength(MAX_VIEWED); + expect(parseViewed(JSON.stringify(book))).toEqual(book); + expect(parseViewed(JSON.stringify({ a: "h", b: 3 }))).toEqual({ a: "h" }); + expect(parseViewed("{")).toEqual({}); + }); + + test("stepping moves through the files, wrapping, and can skip viewed ones", () => { + const order = ["a", "b", "c", "d"]; + expect(stepFile(order, "a", 1)).toBe("b"); + expect(stepFile(order, "a", -1)).toBe("d"); + expect(stepFile(order, "d", 1)).toBe("a"); + expect(stepFile(order, null, 1)).toBe("a"); + expect(stepFile(order, null, -1)).toBe("d"); + const viewed = (p: string) => p === "b" || p === "c"; + expect(stepFile(order, "a", 1, viewed, true)).toBe("d"); + expect(stepFile(order, "d", 1, (p) => p !== "d", true)).toBeNull(); + expect(stepFile([], null, 1)).toBeNull(); + }); +}); diff --git a/apps/desktop/src/state/reviewViewed.ts b/apps/desktop/src/state/reviewViewed.ts new file mode 100644 index 000000000..9e40b8f9d --- /dev/null +++ b/apps/desktop/src/state/reviewViewed.ts @@ -0,0 +1,95 @@ +import { create } from "zustand"; +import { readStorage, writeStorage } from "../lib/storage"; +import type { PatchLine } from "./diff"; + +/** + * Files marked viewed on the Review screen, per thread, source and path, each with a hash of the + * patch that was read: when the agent changes the file again the hash no longer matches, the mark + * drops and the file says it changed since it was viewed. Kept in app storage, bounded. + */ +export const REVIEW_VIEWED_KEY = "rustcode.reviewViewed"; +/** At most this many files keep a mark, the ones marked longest ago dropped first. */ +export const MAX_VIEWED = 2000; + +export type ViewedBook = Record; + +export type ViewedState = "viewed" | "changed" | "unviewed"; + +export function viewedKey(threadId: string, source: string, path: string): string { + return `${threadId}\n${source}\n${path}`; +} + +/** A short, stable hash of a file's patch (FNV-1a over each line's kind and text). */ +export function patchHash(lines: readonly PatchLine[]): string { + let hash = 0x811c9dc5; + const mix = (text: string) => { + for (let i = 0; i < text.length; i++) { + hash ^= text.charCodeAt(i); + hash = Math.imul(hash, 0x01000193) >>> 0; + } + }; + for (const line of lines) mix(`${line.kind}\u0000${line.text}\n`); + return `${lines.length.toString(36)}-${hash.toString(36)}`; +} + +export function viewedState(book: ViewedBook, key: string, hash: string): ViewedState { + const seen = book[key]; + if (seen === undefined) return "unviewed"; + return seen === hash ? "viewed" : "changed"; +} + +/** The book with one file marked (with the hash read) or unmarked (`null`). */ +export function withViewed(book: ViewedBook, key: string, hash: string | null): ViewedBook { + const { [key]: previous, ...rest } = book; + if (hash === null) return previous === undefined ? book : rest; + if (previous === hash && Object.keys(book).at(-1) === key) return book; + return Object.fromEntries(Object.entries({ ...rest, [key]: hash }).slice(-MAX_VIEWED)); +} + +export function parseViewed(raw: string | null): ViewedBook { + if (!raw) return {}; + try { + const value: unknown = JSON.parse(raw); + if (!value || typeof value !== "object" || Array.isArray(value)) return {}; + const entries = Object.entries(value as Record).filter( + (entry): entry is [string, string] => typeof entry[1] === "string", + ); + return Object.fromEntries(entries.slice(-MAX_VIEWED)); + } catch { + return {}; + } +} + +/** + * The path `step` files from `current` in `order` (wrapping), or with `unviewedOnly` the next one + * after `current` that is not viewed; null when there is none. + */ +export function stepFile( + order: readonly string[], + current: string | null, + step: 1 | -1, + viewed: (path: string) => boolean = () => false, + unviewedOnly = false, +): string | null { + if (!order.length) return null; + const at = current ? order.indexOf(current) : -1; + const from = at < 0 && step < 0 ? 0 : at; + for (let n = 1; n <= order.length; n++) { + const i = (((from + step * n) % order.length) + order.length) % order.length; + const path = order[i]!; + if (!unviewedOnly || (!viewed(path) && path !== current)) return path; + } + return null; +} + +export const useReviewViewed = create<{ book: ViewedBook }>(() => ({ + book: parseViewed(readStorage(REVIEW_VIEWED_KEY)), +})); + +export function setViewed(key: string, hash: string | null): void { + const before = useReviewViewed.getState().book; + const book = withViewed(before, key, hash); + if (book === before) return; + useReviewViewed.setState({ book }); + writeStorage(REVIEW_VIEWED_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 8b193ff87..b5fee24c8 100644 --- a/apps/desktop/src/ui/Review.tsx +++ b/apps/desktop/src/ui/Review.tsx @@ -9,7 +9,7 @@ import { primaryModifier } from "../lib/platform"; // draft a comment; the drafts go to the agent as one message, or to the pull // request as one review with line comments (`_rustcode/pulls/review`). -import { memo, useCallback, useEffect, useMemo, useState } from "react"; +import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useShallow } from "zustand/react/shallow"; import type { JsonObject } from "../acp/jsonrpc"; import { type PullRequest, parsePullError, pullErrorTitle, repositoryOf } from "../acp/rustcode"; @@ -38,6 +38,14 @@ import { setReviewDraft, useReviewDrafts, } from "../state/reviewDrafts"; +import { + patchHash, + setViewed, + stepFile, + useReviewViewed, + viewedKey, + viewedState, +} from "../state/reviewViewed"; import { featureMissing, refreshCheckpoints, @@ -51,7 +59,17 @@ import { } from "../state/store"; import { StatusMark, splitUnifiedDiff } from "./ChangesPanel"; import { Fragments, useMarkedFragments } from "./DiffView"; -import { ChevronDown, ChevronRight, FileDiff, Folder, MessageSquarePlus, RefreshCw, Send, X } from "./icons"; +import { + Check, + ChevronDown, + ChevronRight, + FileDiff, + Folder, + MessageSquarePlus, + RefreshCw, + Send, + X, +} from "./icons"; import { ViewHeader } from "./MainHeader"; import { cx, noTextHelpers, Pill, Segments, Select, Skeleton, Spinner, Tooltip } from "./primitives"; import { DiffCount } from "./Rows"; @@ -340,7 +358,7 @@ export function Review({ threadId }: { threadId: string }) { // The diff column's own width decides: the file tree takes its share of the window. const [diffRef, diffWidth] = useDiffWidth(); const { mode, wide } = useDiffLayout(diffWidth); - const [collapsed, setCollapsed] = useState(false); + const [collapsed, setCollapsed] = useState(null); // A diff for a source already left is dropped, not drawn over the one chosen after it. const [diff, runLoad] = useOp(); const files = diff.data ?? null; @@ -373,7 +391,7 @@ export function Review({ threadId }: { threadId: string }) { // A folded file opens again for the next one, and for another source. // biome-ignore lint/correctness/useExhaustiveDependencies: a fold belongs to one file of one source useEffect(() => { - setCollapsed(false); + setCollapsed(null); }, [selected, sourceKey(source)]); // The branch's pull request, from the pull store the panel and the sidebar @@ -444,7 +462,42 @@ export function Review({ threadId }: { threadId: string }) { void load(); }, [load]); const tree = useMemo(() => fileTree((files ?? []).map((f) => f.path)), [files]); + const order = useMemo(() => tree.flatMap((group) => group.files), [tree]); + const viewedBook = useReviewViewed((s) => s.book); + const hashes = useMemo(() => new Map((files ?? []).map((f) => [f.path, patchHash(f.lines)])), [files]); + const viewedOf = (path: string) => + viewedState(viewedBook, viewedKey(threadId, sourceKey(source), path), hashes.get(path) ?? ""); + const viewedCount = order.filter((path) => viewedOf(path) === "viewed").length; + const toggleViewed = (path: string) => { + const hash = hashes.get(path); + if (hash === undefined) return; + const marking = viewedOf(path) !== "viewed"; + setViewed(viewedKey(threadId, sourceKey(source), path), marking ? hash : null); + setCollapsed(null); + if (!marking) return; + const next = stepFile(order, path, 1, (p) => p === path || viewedOf(p) === "viewed", true); + if (next) setSelected(next); + }; + const keys = useRef<(e: KeyboardEvent) => void>(() => undefined); + keys.current = (e) => { + if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey || !order.length) return; + const target = e.target as HTMLElement | null; + if (target?.closest("input, textarea, select, [contenteditable='true'], [role='dialog'], [role='menu']")) + return; + if (e.key === "j" || e.key === "k") { + const next = stepFile(order, selected, e.key === "j" ? 1 : -1); + if (next) setSelected(next); + } else if (e.key === "v" && selected) toggleViewed(selected); + else return; + e.preventDefault(); + }; + useEffect(() => { + const onKey = (e: KeyboardEvent) => keys.current(e); + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, []); const file = files?.find((f) => f.path === selected); + const folded = collapsed ?? (file ? viewedOf(file.path) === "viewed" : false); const label = sourceLabel(source, wt?.branch); // 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). @@ -573,6 +626,13 @@ export function Review({ threadId }: { threadId: string }) {
Files {files?.length ?? 0} + {files && files.length > 0 && ( + + + · {viewedCount} of {files.length} viewed + + + )} {base && ( vs {shortRef(base)} @@ -595,8 +655,13 @@ export function Review({ threadId }: { threadId: string }) { {group.files.map((path) => { const f = files?.find((x) => x.path === path); const n = comments.filter((c) => c.path === path).length; + const seen = viewedOf(path); return ( - + ); @@ -632,7 +707,7 @@ export function Review({ threadId }: { threadId: string }) { onChange={setSelected} options={files.map((f) => ({ value: f.path, - label: `${f.path} +${f.added} −${f.removed}`, + label: `${viewedOf(f.path) === "viewed" ? "✓ " : ""}${f.path} +${f.added} −${f.removed}`, }))} />
@@ -644,12 +719,12 @@ export function Review({ threadId }: { threadId: string }) {
- {collapsed ? null : file.lines.length ? ( + {folded ? null : file.lines.length ? (