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
53 changes: 53 additions & 0 deletions apps/desktop/src/state/reviewViewed.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
95 changes: 95 additions & 0 deletions apps/desktop/src/state/reviewViewed.ts
Original file line number Diff line number Diff line change
@@ -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<string, string>;

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<string, unknown>).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);
}
112 changes: 99 additions & 13 deletions apps/desktop/src/ui/Review.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -38,6 +38,14 @@ import {
setReviewDraft,
useReviewDrafts,
} from "../state/reviewDrafts";
import {
patchHash,
setViewed,
stepFile,
useReviewViewed,
viewedKey,
viewedState,
} from "../state/reviewViewed";
import {
featureMissing,
refreshCheckpoints,
Expand All @@ -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";
Expand Down Expand Up @@ -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<HTMLElement>();
const { mode, wide } = useDiffLayout(diffWidth);
const [collapsed, setCollapsed] = useState(false);
const [collapsed, setCollapsed] = useState<boolean | null>(null);
// A diff for a source already left is dropped, not drawn over the one chosen after it.
const [diff, runLoad] = useOp<ReviewFile[]>();
const files = diff.data ?? null;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -573,6 +626,13 @@ export function Review({ threadId }: { threadId: string }) {
<div className="flex h-9 items-center gap-2 px-2">
<span className="shrink-0 font-semibold text-body">Files</span>
<span className="shrink-0 text-caption text-fg-faint tabular">{files?.length ?? 0}</span>
{files && files.length > 0 && (
<Tooltip label="J and K move between files, V marks one viewed">
<span className="shrink-0 text-caption text-fg-faint tabular">
· {viewedCount} of {files.length} viewed
</span>
</Tooltip>
)}
{base && (
<Tooltip label={base}>
<span className="min-w-0 truncate text-caption text-fg-faint">vs {shortRef(base)}</span>
Expand All @@ -595,15 +655,21 @@ 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 (
<Tooltip key={path} label={f?.oldPath ? `${f.oldPath} → ${path}` : path} side="right">
<Tooltip
key={path}
label={`${f?.oldPath ? `${f.oldPath} → ${path}` : path}${seen === "changed" ? " · changed since you viewed it" : ""}`}
side="right"
>
<button
type="button"
onClick={() => setSelected(path)}
aria-current={selected === path ? "true" : undefined}
className={cx(
"flex w-full items-center gap-1.5 rounded-md px-2 py-[5px] text-left",
selected === path ? "bg-fill" : "hover:bg-fill-subtle",
seen === "viewed" && selected !== path && "text-fg-muted",
)}
>
{f ? <StatusMark status={f.status} /> : <span className="size-4 shrink-0" />}
Expand All @@ -613,7 +679,16 @@ export function Review({ threadId }: { threadId: string }) {
{n > 0 && (
<span className="rounded-full bg-accent/20 px-1.5 text-caption text-accent">{n}</span>
)}
{f && <DiffCount added={f.added} removed={f.removed} />}
{seen === "changed" && (
<span className="size-1.5 shrink-0 rounded-full bg-accent">
<span className="sr-only">Changed since viewed</span>
</span>
)}
{seen === "viewed" ? (
<Check size={12} aria-label="Viewed" className="shrink-0 text-success" />
) : (
f && <DiffCount added={f.added} removed={f.removed} />
)}
</button>
</Tooltip>
);
Expand All @@ -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}`,
}))}
/>
</div>
Expand All @@ -644,12 +719,12 @@ export function Review({ threadId }: { threadId: string }) {
<div className="sticky top-0 z-10 flex items-center gap-2 bg-bg px-4 py-2 text-callout">
<button
type="button"
aria-expanded={!collapsed}
aria-label={collapsed ? `Expand ${file.path}` : `Collapse ${file.path}`}
onClick={() => setCollapsed(!collapsed)}
aria-expanded={!folded}
aria-label={folded ? `Expand ${file.path}` : `Collapse ${file.path}`}
onClick={() => setCollapsed(!folded)}
className="-ml-1.5 flex size-6 shrink-0 items-center justify-center rounded-md text-fg-muted hover:bg-fill hover:text-fg"
>
{collapsed ? (
{folded ? (
<ChevronRight size={13} strokeWidth={2.5} />
) : (
<ChevronDown size={13} strokeWidth={2.5} />
Expand All @@ -661,12 +736,23 @@ export function Review({ threadId }: { threadId: string }) {
</span>
<DiffCount added={file.added} removed={file.removed} />
<span className="flex-1" />
<span className="shrink-0 text-caption text-fg-faint max-[1099px]:hidden">
<span className="shrink-0 text-caption text-fg-faint max-[1300px]:hidden">
Click a line number to comment
</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">
<input
type="checkbox"
className="shrink-0 accent-[var(--rc-accent)]"
checked={viewedOf(file.path) === "viewed"}
onChange={() => toggleViewed(file.path)}
/>
Viewed
</label>
</Tooltip>
</div>
<div className="px-4 pb-4">
{collapsed ? null : file.lines.length ? (
{folded ? null : file.lines.length ? (
<FileDiffView
key={`${sourceKey(source)}|${file.path}`}
file={file}
Expand Down
6 changes: 5 additions & 1 deletion docs/desktop.md
Original file line number Diff line number Diff line change
Expand Up @@ -1636,7 +1636,11 @@ composer's keys stay outside the table.
(`_rustcode/pulls/review`) Drafts belong to the source they were written on and
are kept in app storage per thread and source (`state/reviewDrafts.ts`), so
leaving the screen or reloading keeps them; a source with drafts shows
their count on its segment, and *Discard* offers Undo.
their count on its segment, and *Discard* offers Undo. A file's *Viewed* box
(or V) marks it read, folds it and moves to the next unread file; the file
list says "2 of 5 viewed", J and K step between files, and a mark keeps the
hash of the patch it was read on, so a file the agent changes again drops
its mark and shows a dot (`state/reviewViewed.ts`).
- **Visualizations.** `rustcode-viz` blocks are drawn natively
(`src/ui/Viz.tsx`): bar chart, table (sortable), tree, line chart (hover),
stat list and checklist, with the limits and source fallback of
Expand Down
Loading