From 67b1e7e0037771929baaf84a6bd560684b332ec2 Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 21 Nov 2026 13:44:20 -0500 Subject: [PATCH 1/3] feat(changelens): review panel components and dev harness (#397) ReviewBuckets, ChunkInspector, HunkDiff and CommitRail take data through props only. A small unified diff parser, a compressed rail time scale and touch-strip placement are pure and tested. client/panel-harness.html mounts all four on a hand-made sample payload in dev. Co-Authored-By: Claude Opus 5.5 --- client/panel-harness.html | 12 + .../src/changelens/panel/ChunkInspector.tsx | 259 +++++++++ client/src/changelens/panel/CommitRail.tsx | 218 ++++++++ client/src/changelens/panel/HunkDiff.tsx | 164 ++++++ client/src/changelens/panel/ReviewBuckets.tsx | 187 +++++++ client/src/changelens/panel/bits.tsx | 59 +++ client/src/changelens/panel/harness.tsx | 143 +++++ client/src/changelens/panel/index.ts | 5 + client/src/changelens/panel/model.test.ts | 72 +++ client/src/changelens/panel/model.ts | 129 +++++ .../changelens/panel/parseUnifiedDiff.test.ts | 62 +++ .../src/changelens/panel/parseUnifiedDiff.ts | 112 ++++ client/src/changelens/panel/sample.ts | 500 ++++++++++++++++++ 13 files changed, 1922 insertions(+) create mode 100644 client/panel-harness.html create mode 100644 client/src/changelens/panel/ChunkInspector.tsx create mode 100644 client/src/changelens/panel/CommitRail.tsx create mode 100644 client/src/changelens/panel/HunkDiff.tsx create mode 100644 client/src/changelens/panel/ReviewBuckets.tsx create mode 100644 client/src/changelens/panel/bits.tsx create mode 100644 client/src/changelens/panel/harness.tsx create mode 100644 client/src/changelens/panel/index.ts create mode 100644 client/src/changelens/panel/model.test.ts create mode 100644 client/src/changelens/panel/model.ts create mode 100644 client/src/changelens/panel/parseUnifiedDiff.test.ts create mode 100644 client/src/changelens/panel/parseUnifiedDiff.ts create mode 100644 client/src/changelens/panel/sample.ts diff --git a/client/panel-harness.html b/client/panel-harness.html new file mode 100644 index 00000000..05fb2f8d --- /dev/null +++ b/client/panel-harness.html @@ -0,0 +1,12 @@ + + + + + + Change Lens panel harness + + +
+ + + diff --git a/client/src/changelens/panel/ChunkInspector.tsx b/client/src/changelens/panel/ChunkInspector.tsx new file mode 100644 index 00000000..ba6ca800 --- /dev/null +++ b/client/src/changelens/panel/ChunkInspector.tsx @@ -0,0 +1,259 @@ +import { createMemo, For, Show, type JSX } from "solid-js"; +import { Button } from "../../components/ui/Button"; +import { cx } from "../../components/ui/classes"; +import { breakablePath, MagnitudeBar } from "../../compare/bits"; +import { formatDelta, VERDICT_TEXT } from "../../compare/metrics"; +import type { Verdict } from "../../compare/types"; +import { formatMetricValue, metricDef, metricLabel } from "../../utils/metricsStore"; +import type { BeforeAfter, ChangeLensPayload, LensChunk } from "../types"; +import { Empty, LineCounts, MatchBadge, StatusMark } from "./bits"; +import { churn, formatTime, isWorktree, lineRange, net, STATUS_LABEL, touchMarks } from "./model"; + +const KIND_LABEL: Record = { + function: "function", + class: "type", + heading: "section", + file: "file-level lines", + range: "line range", +}; + +function Section(props: { title: string; detail?: JSX.Element; children: JSX.Element }) { + return ( +
+

+ {props.title} + + {props.detail} + +

+ {props.children} +
+ ); +} + +function verdict(id: string, v: BeforeAfter): Verdict { + if (v.before === null || v.after === null || v.before === v.after) return "same"; + const dir = metricDef(id)?.direction; + if (!dir || dir === "neutral") return "neutral"; + const rose = v.after > v.before; + return rose === (dir === "higher-worse") ? "worse" : "better"; +} + +/** A side with no value says why, never 0. */ +function Side(props: { id: string; value: number | null; missing: string }) { + return ( + {props.missing}}> + {formatMetricValue(props.id, props.value)} + + ); +} + +function MetricRow(props: { id: string; value: BeforeAfter; max: number; chunk: LensChunk }) { + const v = () => props.value; + const delta = () => (v().before !== null && v().after !== null ? v().after! - v().before! : null); + const unit = () => metricDef(props.id)?.unit ?? ""; + return ( +
+ + {metricLabel(props.id)} + + + + → + + + + + + {delta() ? formatDelta(props.id, delta()) : ""} + + +
+ ); +} + +/** One mark per commit that touched the chunk, on the window's commit order. */ +function TouchStrip(props: { payload: ChangeLensPayload; chunk: LensChunk; onOpen: (sha: string) => void }) { + const commits = () => props.payload.commits; + const marks = createMemo(() => touchMarks(commits(), props.chunk.touches)); + const n = () => commits().length; + const left = (x: number) => `calc(${x} * (100% - 10px) + 5px)`; + return ( +
+ + + {(c, i) => ( + 1 ? i() / (n() - 1) : 0.5) }} + /> + )} + + + {(m) => { + const c = commits()[m.index]; + const t = props.chunk.touches.find((x) => x.sha === m.sha)!; + return ( + + ); + }} + +
+ ); +} + +/** Everything about one edited chunk: what moved, when it was touched, and how to open it. */ +export function ChunkInspector(props: { + payload: ChangeLensPayload; + chunk: LensChunk | null; + onOpenHunk: (chunkId: string, commit?: string) => void; + onOpenCode: (chunk: LensChunk) => void; +}) { + // Bars scale against the largest |Δ| of each metric across the window. + const maxAbs = createMemo(() => { + const out = new Map(); + for (const c of props.payload.chunks) + for (const [id, v] of Object.entries(c.metrics)) + if (v.before !== null && v.after !== null) out.set(id, Math.max(out.get(id) ?? 1, Math.abs(v.after - v.before))); + return out; + }); + const metricRows = createMemo(() => { + const c = props.chunk; + if (!c) return []; + const order = props.payload.metricIds; + const rank = (id: string) => (order.includes(id) ? order.indexOf(id) : order.length); + return Object.entries(c.metrics).sort((a, b) => rank(a[0]) - rank(b[0])); + }); + const tz = () => props.payload.selection.timezone; + + return ( + Select an edited chunk to see what changed in it and when.}> + {(c) => ( +
+
+
+ + + {STATUS_LABEL[c().status]} + + · {KIND_LABEL[c().kind]} + + + +
+

+ {c().name} +

+

+ {breakablePath(c().path)}:{lineRange(c().startLine, c().endLine)} + + (base {lineRange(c().baseStartLine!, c().baseEndLine!)}) + +

+ +

+ {c().match === "renamed-file" ? "file renamed from " : "moved from "} + {breakablePath(c().oldPath!)} +

+
+ +

+ Paired with the base by a best guess. Check the diff before you trust the before values. +

+
+ +

+ Changed in this window and put back. Base and head are the same. +

+
+ +

+ Deleted. Its lines and values are from the base. +

+
+
+ + +
+
+ +
+ + Not measured. {c().naReason} +

+ } + > + No metrics for this kind of chunk.

} + > + + {([id, v]) => } + +
+ +

{c().naReason}

+
+
+
+ +
+ Net mode compares base and head only.

} + > + props.onOpenHunk(c().id, sha)} /> +
+
+ + {churn(c()).toLocaleString("en-US")} lines + churned / {net(c()).toLocaleString("en-US")}{" "} + net + + +
+
+
First touched
+
+ {c().firstTouched ? formatTime(c().firstTouched, tz()) : "Working tree only"} +
+
Last touched
+
+ {c().touches.some((t) => isWorktree(t.sha)) ? "Working tree" : formatTime(c().lastTouched, tz())} +
+
+
+
+ )} +
+ ); +} diff --git a/client/src/changelens/panel/CommitRail.tsx b/client/src/changelens/panel/CommitRail.tsx new file mode 100644 index 00000000..b25c71c7 --- /dev/null +++ b/client/src/changelens/panel/CommitRail.tsx @@ -0,0 +1,218 @@ +import { createMemo, createSignal, For, onCleanup, onMount, Show } from "solid-js"; +import { cx } from "../../components/ui/classes"; +import type { LensCommit } from "../types"; +import { LineCounts } from "./bits"; +import { formatDay, formatTime, isWorktree, railPositions } from "./model"; + +/** Width kept for the working-tree mark at the right end. */ +const NOW_SLOT = 52; +const MARK = 8; +/** Room a day label needs before the next one may show. */ +const LABEL_GAP = 52; + +/** + * The window's commits on a compressed time axis, oldest at the left, sized by + * lines changed. Uncommitted work sits apart at the right as "Now". Click picks a + * commit, a second click or "All" clears it; ← → step. + */ +export function CommitRail(props: { + commits: LensCommit[]; + selected: string | null; + onSelect: (sha: string | null) => void; + highlightChunk?: string | null; + /** IANA zone for dates; defaults to the browser's. */ + timeZone?: string; +}) { + const [hover, setHover] = createSignal(null); + const [width, setWidth] = createSignal(0); + const tz = () => props.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone; + const dated = createMemo(() => props.commits.filter((c) => !isWorktree(c.sha))); + const now = createMemo(() => props.commits.find((c) => isWorktree(c.sha)) ?? null); + const xs = createMemo(() => railPositions(dated().map((c) => c.date!))); + const maxLines = createMemo(() => Math.max(1, ...props.commits.map((c) => c.added + c.deleted))); + const height = (c: LensCommit) => Math.round(4 + Math.sqrt((c.added + c.deleted) / maxLines()) * 22); + const left = (x: number) => `calc(${x} * (100% - ${MARK}px))`; + const touches = (c: LensCommit) => Boolean(props.highlightChunk && c.chunkIds.includes(props.highlightChunk)); + + /** Day labels where the day changes, skipped when they would crowd the one before. */ + const days = createMemo(() => { + const out: { x: number; label: string }[] = []; + const span = Math.max(1, width() - (now() ? NOW_SLOT : 0) - MARK); + let last = -Infinity; + let prev = ""; + dated().forEach((c, i) => { + const day = formatDay(c.date!, tz()); + if (day === prev) return; + prev = day; + const px = xs()[i] * span; + if (px - last < LABEL_GAP) return; + last = px; + out.push({ x: xs()[i], label: day }); + }); + return out; + }); + + const shown = () => { + const sha = hover() ?? props.selected; + return props.commits.find((c) => c.sha === sha) ?? null; + }; + + let rail: HTMLDivElement | undefined; + onMount(() => { + const ro = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width)); + if (rail) ro.observe(rail); + onCleanup(() => ro.disconnect()); + }); + + const step = (delta: number) => { + const list = props.commits; + if (!list.length) return; + const at = list.findIndex((c) => c.sha === props.selected); + const next = at < 0 ? (delta > 0 ? 0 : list.length - 1) : Math.max(0, Math.min(list.length - 1, at + delta)); + const sha = list[next].sha; + props.onSelect(sha); + rail?.querySelector(`[data-commit="${sha}"]`)?.focus(); + }; + const onKeyDown = (e: KeyboardEvent) => { + if (e.key === "ArrowLeft" || e.key === "ArrowRight") { + e.preventDefault(); + step(e.key === "ArrowRight" ? 1 : -1); + } + }; + const tone = (c: LensCommit) => + props.selected === c.sha + ? "var(--plc-accent)" + : touches(c) + ? "var(--plc-chart-6)" + : props.highlightChunk + ? "var(--plc-border-strong)" + : "var(--plc-tertiary)"; + const pick = (sha: string) => props.onSelect(props.selected === sha ? null : sha); + + const Mark = (p: { c: LensCommit; x?: number }) => { + const selected = () => props.selected === p.c.sha; + return ( + + ); + }; + + return ( +
+
+ + + {dated().length} {dated().length === 1 ? "commit" : "commits"} + +
+ + {props.commits.length ? "Every commit in the window. Click one to see only its edits." : "No commits in this window."} + + } + > + {(c) => ( + <> + + {isWorktree(c().sha) ? "Working tree" : c().short} + + + {c().subject} + + + {c().date ? formatTime(c().date, tz()) : "Now"} · {c().files} {c().files === 1 ? "file" : "files"} + + + + + + )} + +
+
+ +
+
+ + {(d) => ( + 0.8 ? `translateX(calc(-100% + ${MARK}px))` : undefined }} + > + {d.label} + + )} + +
+ + + Now + + +
+
+ ); +} diff --git a/client/src/changelens/panel/HunkDiff.tsx b/client/src/changelens/panel/HunkDiff.tsx new file mode 100644 index 00000000..be9c6ab4 --- /dev/null +++ b/client/src/changelens/panel/HunkDiff.tsx @@ -0,0 +1,164 @@ +import { X } from "lucide-solid"; +import { createMemo, For, Match, onCleanup, onMount, Show, Switch } from "solid-js"; +import { IconButton } from "../../components/ui/IconButton"; +import type { LensHunkDiff } from "../types"; +import { breakablePath } from "../../compare/bits"; +import { parseUnifiedDiff, type DiffLine } from "./parseUnifiedDiff"; + +const ROW_BG: Record = { + add: "var(--plc-success-subtle)", + del: "var(--plc-error-subtle)", + ctx: "transparent", + note: "transparent", +}; +const HIT_BG: Record<"add" | "del", string> = { add: "#c6f0d4", del: "#fbd0d0" }; +const SIGN: Record = { add: "+", del: "−", ctx: " ", note: "" }; + +function Line(props: { line: DiffLine }) { + const l = props.line; + return ( +
+ {l.old ?? ""} + {l.new ?? ""} + + {SIGN[l.kind]} + + {l.text}} + > + + + {(spans) => ( + + {(s) => + s.hit ? ( + + {s.text} + + ) : ( + s.text + ) + } + + )} + + + +
+ ); +} + +/** The diff text behind one chunk, with line numbers and word highlights. Esc closes it. */ +export function HunkDiff(props: { diff: LensHunkDiff | null; loading: boolean; error?: string; onClose: () => void }) { + const hunks = createMemo(() => (props.diff ? parseUnifiedDiff(props.diff.diff) : [])); + const counts = createMemo(() => { + let added = 0; + let deleted = 0; + for (const h of hunks()) + for (const l of h.lines) { + if (l.kind === "add") added++; + else if (l.kind === "del") deleted++; + } + return { added, deleted }; + }); + + onMount(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape" && !e.defaultPrevented) props.onClose(); + }; + window.addEventListener("keydown", onKey); + onCleanup(() => window.removeEventListener("keydown", onKey)); + }); + + return ( +
+
+
+ Diff

}> + {(d) => ( +

+ {breakablePath(d().path)} +

+ )} +
+

+  }> + {(d) => ( + <> + + {d().from} → {d().to} + + + + from {d().oldPath} + + + + clipped + + + +{counts().added}{" "} + −{counts().deleted} + + + )} + +

+
+ props.onClose()}> + +
+
+ + +

+ Couldn't load the diff: {props.error} +

+
+ +
+ + {(w) =>
} + +
+ + +

Open a chunk's diff to see its lines here.

+
+ +

+ No line differs between these two sides. +

+
+ +
+ + {(h) => ( +
+
+ + @@ −{h.oldStart},{h.oldLines} +{h.newStart},{h.newLines} @@ + + {h.section} +
+ {(l) => } +
+ )} +
+ +

+ The diff is clipped here. Open the code to read the rest. +

+
+
+
+ +
+
+ ); +} diff --git a/client/src/changelens/panel/ReviewBuckets.tsx b/client/src/changelens/panel/ReviewBuckets.tsx new file mode 100644 index 00000000..9e42b600 --- /dev/null +++ b/client/src/changelens/panel/ReviewBuckets.tsx @@ -0,0 +1,187 @@ +import { createMemo, createSignal, For, Show, type JSX } from "solid-js"; +import { cx } from "../../components/ui/classes"; +import type { ChangeLensPayload, ChunkStatus, LensChunk } from "../types"; +import { Empty, LineCounts, StatusMark } from "./bits"; +import { bucketList, countBy, editsByChurn, HOTSPOT_COMPLEXITY, lineRange, STATUS_LABEL, STATUS_ORDER } from "./model"; + +function Section(props: { title: string; count: number; rule?: string; children: JSX.Element; tools?: JSX.Element }) { + return ( +
+

+ {props.title} + {props.count} +

+ +

{props.rule}

+
+ {props.tools} + {props.children} +
+ ); +} + +/** `12 → 17` for complexity, colored by direction; says so when a chunk is not measured. */ +function Complexity(props: { chunk: LensChunk }) { + const value = () => props.chunk.metrics.complexity; + const tone = () => { + const v = value(); + if (!v || v.before === null || v.after === null || v.before === v.after) return "text-[var(--plc-on-muted)]"; + return v.after > v.before ? "text-[var(--plc-error)]" : "text-[var(--plc-success)]"; + }; + return ( + not measured} + > + —}> + {(v) => ( + + {v().before ?? "—"} + → + {v().after ?? "—"} + + )} + + + ); +} + +function Row(props: { chunk: LensChunk; selected: boolean; onSelect: (id: string) => void }) { + const c = () => props.chunk; + const where = () => `${c().path}:${lineRange(c().startLine, c().endLine)}`; + return ( + + ); +} + +const selectClass = + "h-6 min-w-0 flex-1 cursor-pointer rounded border border-[var(--plc-border)] bg-[var(--plc-surface)] px-1.5 text-[12px] text-[var(--plc-on-muted)] outline-none transition-colors duration-150 hover:border-[var(--plc-border-strong)] focus-visible:border-[var(--plc-border-focus)] focus-visible:ring-2 focus-visible:ring-[var(--plc-accent-border)]"; + +/** + * The review order: two rule-based buckets, then every edit by churn. + * ↑ ↓ move between rows, Enter selects. + */ +export function ReviewBuckets(props: { payload: ChangeLensPayload; selected: string | null; onSelect: (chunkId: string) => void }) { + const [status, setStatus] = createSignal(""); + const [fileClass, setFileClass] = createSignal(""); + const chunks = () => props.payload.chunks; + const complex = createMemo(() => bucketList(chunks(), "complex-and-changed")); + const hotspots = createMemo(() => bucketList(chunks(), "new-hotspot")); + const edits = createMemo(() => editsByChurn(chunks(), status(), fileClass())); + const statusCounts = createMemo(() => { + const counts = new Map(countBy(chunks(), (c) => c.status)); + return STATUS_ORDER.filter((s) => counts.has(s)).map((s) => [s, counts.get(s)!] as const); + }); + const classCounts = createMemo(() => countBy(chunks(), (c) => c.fileClass).sort((a, b) => b[1] - a[1])); + + let root: HTMLDivElement | undefined; + const onKeyDown = (e: KeyboardEvent) => { + if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(e.key) || !root) return; + if ((e.target as HTMLElement).closest("select")) return; + const rows = [...root.querySelectorAll("[data-chunk-row]")]; + if (!rows.length) return; + e.preventDefault(); + const at = rows.indexOf(document.activeElement as HTMLElement); + const next = + e.key === "Home" ? 0 : e.key === "End" ? rows.length - 1 : at < 0 ? 0 : at + (e.key === "ArrowDown" ? 1 : -1); + rows[Math.max(0, Math.min(rows.length - 1, next))].focus(); + }; + + const list = (items: LensChunk[], empty: string) => ( + {empty}}> + {(c) => } + + ); + + return ( +
+ No code changed in this window. Pick a wider window or include the working tree.} + > +
+ {list(complex(), "No complex chunk changed.")} +
+
+ {list(hotspots(), "No new hotspot.")} +
+

+ Tests, docs, generated and vendor files get no bucket. +

+
+ + +
+ } + > + {list(edits(), "No edits match these filters.")} + + +
+ ); +} diff --git a/client/src/changelens/panel/bits.tsx b/client/src/changelens/panel/bits.tsx new file mode 100644 index 00000000..0611b5d7 --- /dev/null +++ b/client/src/changelens/panel/bits.tsx @@ -0,0 +1,59 @@ +// Small shared pieces for the Change Lens panel. + +import { ArrowRight, Circle, Minus, Plus, RotateCcw } from "lucide-solid"; +import { Show, type JSX } from "solid-js"; +import type { ChunkMatch, ChunkStatus } from "../types"; +import { MATCH_LABEL, STATUS_COLOR, STATUS_LABEL } from "./model"; + +const STATUS_ICON = { modified: Circle, added: Plus, deleted: Minus, moved: ArrowRight, reverted: RotateCcw } as const; + +export function StatusMark(props: { status: ChunkStatus }) { + const Icon = STATUS_ICON[props.status]; + const dot = () => props.status === "modified"; + return ( + + + + ); +} + +/** A labeled pill for a match the reader should know about; nothing for `exact` and `none`. */ +export function MatchBadge(props: { match: ChunkMatch }) { + const uncertain = () => props.match === "uncertain"; + return ( + + {(label) => ( + + {label()} + + )} + + ); +} + +/** `+12 −3` in diff colors. */ +export function LineCounts(props: { added: number; deleted: number }) { + return ( + + +{props.added.toLocaleString("en-US")} + −{props.deleted.toLocaleString("en-US")} + + ); +} + +export function Empty(props: { children: JSX.Element }) { + return

{props.children}

; +} diff --git a/client/src/changelens/panel/harness.tsx b/client/src/changelens/panel/harness.tsx new file mode 100644 index 00000000..cece1c91 --- /dev/null +++ b/client/src/changelens/panel/harness.tsx @@ -0,0 +1,143 @@ +/* @refresh reload */ +// Dev-only page (client/panel-harness.html): the four panel components on sample data. +import { render } from "solid-js/web"; +import { createMemo, createSignal, For, type JSX } from "solid-js"; +import "../../index.css"; +import catalog from "../../../../server/tests/snapshots/metric-catalog.json"; +import { setMetricCatalog, type MetricCatalog } from "../../utils/metricsStore"; +import type { LensHunkDiff } from "../types"; +import { ChunkInspector, CommitRail, HunkDiff, ReviewBuckets } from "./index"; +import { bigHunkDiff, emptyPayload, sampleHunkDiff, samplePayload } from "./sample"; + +setMetricCatalog(catalog as MetricCatalog); + +type DiffState = "none" | "loaded" | "loading" | "error" | "same" | "big"; + +function Pick(props: { label: string; value: T; options: T[]; onChange: (v: T) => void }) { + return ( + + ); +} + +function Panel(props: { title: string; width?: number; children: JSX.Element; class?: string }) { + return ( +
+
+ {props.title} +
+
{props.children}
+
+ ); +} + +function Harness() { + const params = new URLSearchParams(location.search); + const [data, setData] = createSignal<"sample" | "empty">(params.get("data") === "empty" ? "empty" : "sample"); + const [width, setWidth] = createSignal(Number(params.get("w") ?? 340)); + const [chunkId, setChunkId] = createSignal(params.get("chunk")); + const [commit, setCommit] = createSignal(null); + const [diffState, setDiffState] = createSignal((params.get("diff") as DiffState) ?? "loaded"); + const [diffCommit, setDiffCommit] = createSignal(); + const [log, setLog] = createSignal("—"); + + const payload = () => (data() === "sample" ? samplePayload : emptyPayload); + const chunk = createMemo(() => payload().chunks.find((c) => c.id === chunkId()) ?? null); + const diff = createMemo((): LensHunkDiff | null => { + const s = diffState(); + if (s === "none" || s === "loading" || s === "error") return null; + if (s === "big") return bigHunkDiff(2000); + const c = chunk(); + const base = { + ...sampleHunkDiff, + ...(c ? { chunkId: c.id, path: c.path, oldPath: c.oldPath } : {}), + ...(diffCommit() ? { from: "parent", to: diffCommit()!.slice(0, 7) } : {}), + }; + return s === "same" ? { ...base, diff: "" } : base; + }); + + return ( +
+
+ Change Lens panel + { setData(v); setChunkId(null); setCommit(null); }} /> + + + + last call: {log()} + +
+ +
+ { + setCommit(sha); + setLog(`CommitRail.onSelect(${sha})`); + }} + highlightChunk={chunkId()} + timeZone={payload().selection.timezone} + /> +
+
+
+ + { + setChunkId(id); + setLog(`ReviewBuckets.onSelect(${id})`); + }} + /> + + + { + setDiffCommit(sha); + setDiffState("loaded"); + setLog(`onOpenHunk(${id}${sha ? `, ${sha.slice(0, 8)}` : ""})`); + }} + onOpenCode={(c) => setLog(`onOpenCode(${c.path}:${c.startLine})`)} + /> + + + { + setDiffState("none"); + setLog("HunkDiff.onClose()"); + }} + /> + +
+
+ ); +} + +render(() => , document.getElementById("root")!); diff --git a/client/src/changelens/panel/index.ts b/client/src/changelens/panel/index.ts new file mode 100644 index 00000000..1fb91ad9 --- /dev/null +++ b/client/src/changelens/panel/index.ts @@ -0,0 +1,5 @@ +// Change Lens review panel. Props only: no fetching, no navigation store. +export { ReviewBuckets } from "./ReviewBuckets"; +export { ChunkInspector } from "./ChunkInspector"; +export { HunkDiff } from "./HunkDiff"; +export { CommitRail } from "./CommitRail"; diff --git a/client/src/changelens/panel/model.test.ts b/client/src/changelens/panel/model.test.ts new file mode 100644 index 00000000..cc8d101f --- /dev/null +++ b/client/src/changelens/panel/model.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from "vitest"; +import { WORKTREE } from "../types"; +import { bucketList, editsByChurn, railPositions, touchMarks } from "./model"; +import { samplePayload } from "./sample"; + +describe("review order", () => { + const { chunks } = samplePayload; + + it("puts only bucketed chunks in each bucket, highest complexity first", () => { + const complex = bucketList(chunks, "complex-and-changed"); + expect(complex.every((c) => c.buckets.includes("complex-and-changed"))).toBe(true); + const before = complex.map((c) => c.metrics.complexity.before!); + expect(before).toEqual([...before].sort((a, b) => b - a)); + + const hot = bucketList(chunks, "new-hotspot"); + const after = hot.map((c) => c.metrics.complexity.after!); + expect(after).toEqual([...after].sort((a, b) => b - a)); + expect(hot.some((c) => c.status === "added")).toBe(true); + }); + + it("lists every edit by churn and filters by status and file class", () => { + const all = editsByChurn(chunks, "", ""); + expect(all).toHaveLength(chunks.length); + const churns = all.map((c) => c.added + c.deleted); + expect(churns).toEqual([...churns].sort((a, b) => b - a)); + expect(editsByChurn(chunks, "deleted", "").every((c) => c.status === "deleted")).toBe(true); + expect(editsByChurn(chunks, "", "test").every((c) => c.fileClass === "test")).toBe(true); + expect(editsByChurn(chunks, "reverted", "docs")).toEqual([]); + }); +}); + +describe("railPositions", () => { + it("keeps a burst readable next to a long gap", () => { + const x = railPositions([ + "2026-11-17T09:00:00Z", + "2026-11-18T10:00:00Z", // a day later + "2026-11-18T10:04:00Z", // burst + "2026-11-18T10:08:00Z", + ]); + expect(x[0]).toBe(0); + expect(x.at(-1)).toBe(1); + const dayGap = x[1] - x[0]; + const burstGap = x[2] - x[1]; + // A linear scale would make the day gap ~370x the burst gap. + expect(dayGap / burstGap).toBeLessThan(5); + expect(burstGap).toBeGreaterThan(0.1); + }); + + it("places one commit in the middle and same-time commits apart", () => { + expect(railPositions(["2026-11-17T09:00:00Z"])).toEqual([0.5]); + const same = railPositions(["2026-11-17T09:00:00Z", "2026-11-17T09:00:00Z", "2026-11-17T09:00:00Z"]); + expect(same).toEqual([0, 0.5, 1]); + }); +}); + +describe("touchMarks", () => { + const commits = samplePayload.commits; + + it("places touches on the window's commit order and sizes them by lines", () => { + const marks = touchMarks(commits, [ + { sha: commits[0].sha, added: 4, deleted: 0 }, + { sha: WORKTREE, added: 30, deleted: 6 }, + { sha: "not-in-window", added: 9, deleted: 9 }, + ]); + expect(marks.map((m) => [m.index, m.x])).toEqual([ + [0, 0], + [commits.length - 1, 1], + ]); + expect(marks[1].size).toBe(1); + expect(marks[0].size).toBeCloseTo(Math.sqrt(4 / 36)); + }); +}); diff --git a/client/src/changelens/panel/model.ts b/client/src/changelens/panel/model.ts new file mode 100644 index 00000000..3fc6de88 --- /dev/null +++ b/client/src/changelens/panel/model.ts @@ -0,0 +1,129 @@ +// Pure helpers behind the Change Lens panel: review order, rail scale, touch placement, labels. + +import type { ChunkMatch, ChunkStatus, LensChunk, LensCommit, LensTouch } from "../types"; +import { WORKTREE } from "../types"; + +/** Display copy of the server's bucket threshold (server/app/services/changelens). */ +export const HOTSPOT_COMPLEXITY = 10; + +export const STATUS_LABEL: Record = { + modified: "Modified", + added: "Added", + deleted: "Deleted", + moved: "Moved", + reverted: "Reverted", +}; + +export const STATUS_COLOR: Record = { + modified: "var(--plc-warning)", + added: "var(--plc-success)", + deleted: "var(--plc-error)", + moved: "var(--plc-accent)", + reverted: "var(--plc-on-disabled)", +}; + +export const STATUS_ORDER: ChunkStatus[] = ["modified", "added", "deleted", "moved", "reverted"]; + +/** Matches the UI names; `exact` and `none` need no badge. */ +export const MATCH_LABEL: Partial> = { + uncertain: "Uncertain match", + moved: "Moved", + "renamed-file": "File renamed", +}; + +export const churn = (c: { added: number; deleted: number }) => c.added + c.deleted; +export const net = (c: LensChunk) => c.netAdded + c.netDeleted; + +const complexity = (c: LensChunk) => c.metrics.complexity ?? { before: null, after: null }; + +/** Chunks in a bucket, in review order: highest complexity first, then most churn. */ +export function bucketList(chunks: LensChunk[], bucket: "complex-and-changed" | "new-hotspot"): LensChunk[] { + const side = bucket === "complex-and-changed" ? "before" : "after"; + return chunks + .filter((c) => c.buckets.includes(bucket)) + .sort((a, b) => (complexity(b)[side] ?? 0) - (complexity(a)[side] ?? 0) || churn(b) - churn(a)); +} + +/** Every chunk, most churn first; ties by path and line so the order is stable. */ +export function editsByChurn(chunks: LensChunk[], status: ChunkStatus | "", fileClass: string): LensChunk[] { + return chunks + .filter((c) => (!status || c.status === status) && (!fileClass || c.fileClass === fileClass)) + .sort((a, b) => churn(b) - churn(a) || a.path.localeCompare(b.path) || a.startLine - b.startLine); +} + +/** Count of each value, in first-seen order. */ +export function countBy(items: T[], key: (item: T) => string): [string, number][] { + const out = new Map(); + for (const item of items) out.set(key(item), (out.get(key(item)) ?? 0) + 1); + return [...out]; +} + +/** + * Commit positions in [0, 1], oldest at 0. Each gap counts as `1 + ln(1 + minutes)`, + * so three commits five minutes apart stay apart and a quiet weekend doesn't + * push them into one pixel. One commit sits in the middle. + */ +export function railPositions(dates: string[]): number[] { + if (dates.length === 0) return []; + if (dates.length === 1) return [0.5]; + const times = dates.map((d) => Date.parse(d)); + const steps = [0]; + for (let i = 1; i < times.length; i++) { + const minutes = Math.max(0, (times[i] - times[i - 1]) / 60000); + steps.push(steps[i - 1] + 1 + Math.log1p(minutes)); + } + const total = steps[steps.length - 1]; + return steps.map((s) => s / total); +} + +export interface TouchMark { + sha: string; + /** Index in the window's commits. */ + index: number; + /** 0..1 along the window's commit order. */ + x: number; + lines: number; + /** 0..1 against the chunk's largest touch (square root, so small touches stay visible). */ + size: number; +} + +/** Place a chunk's touches on the window's commit order. Touches of unknown commits are dropped. */ +export function touchMarks(commits: LensCommit[], touches: LensTouch[]): TouchMark[] { + const at = new Map(commits.map((c, i) => [c.sha, i])); + const n = commits.length; + const max = Math.max(1, ...touches.map(churn)); + return touches.flatMap((t) => { + const index = at.get(t.sha); + if (index === undefined) return []; + const lines = churn(t); + return [{ sha: t.sha, index, x: n > 1 ? index / (n - 1) : 0.5, lines, size: Math.sqrt(lines / max) }]; + }); +} + +export const isWorktree = (sha: string | null | undefined) => sha === WORKTREE; + +/** "Nov 18, 10:05" in the payload's time zone. */ +export function formatTime(iso: string | null, timeZone: string, withYear = false): string { + if (!iso) return "Working tree"; + return new Intl.DateTimeFormat("en-US", { + timeZone, + month: "short", + day: "numeric", + ...(withYear ? { year: "numeric" } : {}), + hour: "2-digit", + minute: "2-digit", + hourCycle: "h23", + }).format(new Date(iso)); +} + +/** "Nov 18" in the payload's time zone. */ +export function formatDay(iso: string, timeZone: string): string { + return new Intl.DateTimeFormat("en-US", { timeZone, month: "short", day: "numeric" }).format(new Date(iso)); +} + +export function lineRange(start: number, end: number): string { + return start === end ? `${start}` : `${start}–${end}`; +} + +/** Last path segment, for compact rows. */ +export const baseName = (path: string) => path.slice(path.lastIndexOf("/") + 1); diff --git a/client/src/changelens/panel/parseUnifiedDiff.test.ts b/client/src/changelens/panel/parseUnifiedDiff.test.ts new file mode 100644 index 00000000..dbf0ac6f --- /dev/null +++ b/client/src/changelens/panel/parseUnifiedDiff.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from "vitest"; +import { parseUnifiedDiff } from "./parseUnifiedDiff"; +import { bigHunkDiff } from "./sample"; + +const DIFF = `diff --git a/src/a.ts b/src/a.ts +index 3f9a21c..9e0b7d4 100644 +--- a/src/a.ts ++++ b/src/a.ts +@@ -10,4 +10,5 @@ export function retryJob(job: Job) { + const max = job.maxAttempts; +- for (let i = 0; i < max; i++) { ++ for (let i = 1; i <= max; i++) { ++ log(i); + run(job); + +@@ -40 +41,2 @@ +- return null; ++ return result; ++} +\\ No newline at end of file +`; + +describe("parseUnifiedDiff", () => { + const hunks = parseUnifiedDiff(DIFF); + + it("reads hunk headers, including the one-line short form", () => { + expect(hunks.map((h) => [h.oldStart, h.oldLines, h.newStart, h.newLines])).toEqual([ + [10, 4, 10, 5], + [40, 1, 41, 2], + ]); + expect(hunks[0].section).toBe("export function retryJob(job: Job) {"); + }); + + it("numbers old and new lines separately and keeps a stripped empty context line", () => { + const rows = hunks[0].lines.map((l) => [l.kind, l.old, l.new]); + expect(rows).toEqual([ + ["ctx", 10, 10], + ["del", 11, null], + ["add", null, 11], + ["add", null, 12], + ["ctx", 12, 13], + ["ctx", 13, 14], + ]); + expect(hunks[1].lines.at(-1)).toMatchObject({ kind: "note", text: "No newline at end of file" }); + }); + + it("highlights only the changed words of a paired line", () => { + const [del, add] = hunks[0].lines.slice(1, 3); + expect(del.spans?.filter((s) => s.hit).map((s) => s.text)).toEqual(["0; i <"]); + expect(add.spans?.filter((s) => s.hit).map((s) => s.text)).toEqual(["1; i <="]); + // The unpaired added line gets no highlight. + expect(hunks[0].lines[3].spans).toBeUndefined(); + }); + + it("parses a 2,000-line diff quickly", () => { + const text = bigHunkDiff(2000).diff; + const start = performance.now(); + const big = parseUnifiedDiff(text); + expect(big.reduce((n, h) => n + h.lines.length, 0)).toBeGreaterThanOrEqual(2000); + expect(performance.now() - start).toBeLessThan(100); + }); +}); diff --git a/client/src/changelens/panel/parseUnifiedDiff.ts b/client/src/changelens/panel/parseUnifiedDiff.ts new file mode 100644 index 00000000..65d45b0e --- /dev/null +++ b/client/src/changelens/panel/parseUnifiedDiff.ts @@ -0,0 +1,112 @@ +// A small unified diff parser for the hunk view: hunks, line numbers, and word highlights. + +export type DiffLineKind = "add" | "del" | "ctx" | "note"; + +export interface DiffSpan { + text: string; + /** True for the part of a paired line that changed. */ + hit: boolean; +} + +export interface DiffLine { + kind: DiffLineKind; + old: number | null; + new: number | null; + text: string; + /** Word highlights, only on a removed line paired with an added line. */ + spans?: DiffSpan[]; +} + +export interface DiffHunk { + header: string; + oldStart: number; + oldLines: number; + newStart: number; + newLines: number; + /** Text after the second `@@`, usually the enclosing function. */ + section: string; + lines: DiffLine[]; +} + +const HUNK = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@ ?(.*)$/; +const FILE_HEADER = /^(diff --git |index |--- |\+\+\+ |new file mode|deleted file mode|similarity index|rename (from|to) |old mode|new mode|Binary files )/; +/** Lines longer than this skip word highlights; the diff must stay fast. */ +const MAX_HIGHLIGHT = 400; + +export function parseUnifiedDiff(text: string): DiffHunk[] { + const hunks: DiffHunk[] = []; + let hunk: DiffHunk | null = null; + let oldNo = 0; + let newNo = 0; + const lines = text.split("\n"); + if (lines[lines.length - 1] === "") lines.pop(); + + for (const raw of lines) { + const head = HUNK.exec(raw); + if (head) { + hunk = { + header: raw, + oldStart: Number(head[1]), + oldLines: head[2] === undefined ? 1 : Number(head[2]), + newStart: Number(head[3]), + newLines: head[4] === undefined ? 1 : Number(head[4]), + section: head[5].trim(), + lines: [], + }; + hunks.push(hunk); + oldNo = hunk.oldStart; + newNo = hunk.newStart; + continue; + } + if (!hunk || FILE_HEADER.test(raw)) continue; + const sign = raw[0]; + const body = raw.slice(1); + if (sign === "+") hunk.lines.push({ kind: "add", old: null, new: newNo++, text: body }); + else if (sign === "-") hunk.lines.push({ kind: "del", old: oldNo++, new: null, text: body }); + else if (sign === "\\") hunk.lines.push({ kind: "note", old: null, new: null, text: raw.slice(2) }); + // Some tools strip the space from an empty context line. + else hunk.lines.push({ kind: "ctx", old: oldNo++, new: newNo++, text: sign === " " ? body : raw }); + } + for (const h of hunks) pairWords(h.lines); + return hunks; +} + +/** Pair each run of removed lines with the added run after it, line by line, and mark the changed words. */ +function pairWords(lines: DiffLine[]) { + let i = 0; + while (i < lines.length) { + if (lines[i].kind !== "del") { + i++; + continue; + } + const delStart = i; + while (i < lines.length && lines[i].kind === "del") i++; + const addStart = i; + while (i < lines.length && lines[i].kind === "add") i++; + const pairs = Math.min(addStart - delStart, i - addStart); + for (let k = 0; k < pairs; k++) markWords(lines[delStart + k], lines[addStart + k]); + } +} + +const TOKEN = /\w+|\s+|[^\w\s]/g; + +/** Common prefix and suffix tokens stay plain; the middle is the change. */ +export function markWords(del: DiffLine, add: DiffLine) { + if (del.text.length > MAX_HIGHLIGHT || add.text.length > MAX_HIGHLIGHT) return; + const a = del.text.match(TOKEN) ?? []; + const b = add.text.match(TOKEN) ?? []; + let pre = 0; + while (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++; + let suf = 0; + while (suf < a.length - pre && suf < b.length - pre && a[a.length - 1 - suf] === b[b.length - 1 - suf]) suf++; + // Nothing in common: the whole line changed, and a highlight would only add noise. + if (pre + suf === 0) return; + const split = (tokens: string[]): DiffSpan[] => + [ + { text: tokens.slice(0, pre).join(""), hit: false }, + { text: tokens.slice(pre, tokens.length - suf).join(""), hit: true }, + { text: tokens.slice(tokens.length - suf).join(""), hit: false }, + ].filter((s) => s.text); + del.spans = split(a); + add.spans = split(b); +} diff --git a/client/src/changelens/panel/sample.ts b/client/src/changelens/panel/sample.ts new file mode 100644 index 00000000..3a053cc7 --- /dev/null +++ b/client/src/changelens/panel/sample.ts @@ -0,0 +1,500 @@ +// A hand-made Change Lens payload for the panel tests and the dev harness. +// It covers every status, kind and match, a not-measured chunk, a reverted +// chunk, a burst of commits, and uncommitted work. + +import type { ChangeLensPayload, LensChunk, LensCommit, LensFile, LensHunkDiff, LensTouch } from "../types"; +import { WORKTREE } from "../types"; + +const sha = (seed: string) => (seed.repeat(40) + "0".repeat(40)).slice(0, 40); + +function commit(seed: string, date: string, subject: string, files: number, added: number, deleted: number): LensCommit { + const full = sha(seed); + return { sha: full, short: full.slice(0, 7), subject, author: "Byron Wall", date, files, added, deleted, chunkIds: [] }; +} + +const C = { + config: commit("a1f3", "2026-11-17T15:12:00Z", "Add backoff settings to job config", 2, 24, 3), + extract: commit("b27c", "2026-11-17T21:40:00Z", "Extract retry policy from the queue runner", 3, 88, 61), + backoff: commit("c3d9", "2026-11-18T16:05:00Z", "Retry failed jobs with exponential backoff", 4, 112, 14), + offByOne: commit("d4e1", "2026-11-18T16:09:00Z", "Fix off-by-one in the attempt count", 1, 3, 3), + logRetry: commit("e5a0", "2026-11-18T16:14:00Z", "Log each retry attempt with its delay", 2, 19, 2), + jitter: commit("f6b8", "2026-11-18T16:22:00Z", "Try a jittered delay between attempts", 2, 16, 5), + revert: commit("07c2", "2026-11-19T19:30:00Z", 'Revert "Try a jittered delay between attempts"', 2, 5, 16), + rename: commit("18d5", "2026-11-19T22:02:00Z", "Rename queue/worker.ts to queue/runner.ts", 1, 4, 3), + legacy: commit("29e7", "2026-11-20T17:47:00Z", "Drop the legacy schedule parser and update the docs", 4, 31, 74), +}; + +const worktree: LensCommit = { + sha: WORKTREE, + short: "WORKTREE", + subject: "Uncommitted changes", + author: "", + date: null, + files: 3, + added: 21, + deleted: 6, + chunkIds: [], +}; + +const touch = (c: LensCommit | typeof WORKTREE, added: number, deleted: number): LensTouch => ({ + sha: typeof c === "string" ? c : c.sha, + added, + deleted, +}); + +type ChunkSeed = Omit & { + qualified?: string; +}; + +const dateOf = (s: string) => Object.values(C).find((c) => c.sha === s)?.date ?? null; + +function chunk(seed: ChunkSeed): LensChunk { + const { qualified, ...rest } = seed; + const dated = seed.touches.map((t) => dateOf(t.sha)).filter((d): d is string => d !== null); + return { + ...rest, + id: qualified === undefined ? seed.path : `${seed.path}::${qualified}`, + added: seed.touches.reduce((n, t) => n + t.added, 0), + deleted: seed.touches.reduce((n, t) => n + t.deleted, 0), + firstTouched: dated[0] ?? null, + lastTouched: dated.at(-1) ?? null, + hunks: [{ sha: null, oldStart: seed.baseStartLine ?? seed.startLine, oldLines: seed.netDeleted, newStart: seed.startLine, newLines: seed.netAdded }], + }; +} + +const m = (before: number | null, after: number | null) => ({ before, after }); + +const chunks: LensChunk[] = [ + chunk({ + path: "src/jobs/retry.ts", + qualified: "retryJob", + kind: "function", + name: "retryJob", + startLine: 42, + endLine: 118, + baseStartLine: 30, + baseEndLine: 84, + status: "modified", + match: "exact", + netAdded: 41, + netDeleted: 17, + touches: [touch(C.backoff, 38, 9), touch(C.offByOne, 2, 2), touch(C.logRetry, 11, 1), touch(C.jitter, 6, 3), touch(C.revert, 3, 6), touch(WORKTREE, 8, 2)], + metrics: { + complexity: m(12, 17), + cognitive_complexity: m(18, 26), + loc: m(55, 77), + max_nesting_depth: m(3, 4), + parameter_count: m(2, 3), + }, + measured: true, + buckets: ["complex-and-changed", "new-hotspot"], + fileClass: "code", + }), + chunk({ + path: "src/jobs/retry.ts", + qualified: "backoffDelay", + kind: "function", + name: "backoffDelay", + startLine: 120, + endLine: 168, + status: "added", + match: "none", + netAdded: 49, + netDeleted: 0, + touches: [touch(C.backoff, 44, 0), touch(C.jitter, 7, 2), touch(C.revert, 2, 7)], + metrics: { complexity: m(null, 11), cognitive_complexity: m(null, 15), loc: m(null, 49), max_nesting_depth: m(null, 3), parameter_count: m(null, 2) }, + measured: true, + buckets: ["new-hotspot"], + fileClass: "code", + }), + chunk({ + path: "src/jobs/policy.ts", + oldPath: "src/queue/retry-utils.ts", + qualified: "RetryPolicy", + kind: "class", + name: "RetryPolicy", + startLine: 8, + endLine: 61, + baseStartLine: 112, + baseEndLine: 160, + status: "moved", + match: "moved", + netAdded: 9, + netDeleted: 3, + touches: [touch(C.extract, 54, 48)], + metrics: { complexity: m(4, 5), loc: m(49, 54), max_nesting_depth: m(2, 2) }, + measured: true, + buckets: [], + fileClass: "code", + }), + chunk({ + path: "src/jobs/retry.ts", + qualified: "nextAttemptAt", + kind: "function", + name: "nextAttemptAt", + startLine: 170, + endLine: 181, + baseStartLine: 86, + baseEndLine: 97, + status: "reverted", + match: "exact", + netAdded: 0, + netDeleted: 0, + touches: [touch(C.jitter, 3, 0), touch(C.revert, 0, 3)], + metrics: { complexity: m(3, 3), cognitive_complexity: m(2, 2), loc: m(12, 12), max_nesting_depth: m(1, 1), parameter_count: m(1, 1) }, + measured: true, + buckets: [], + fileClass: "code", + }), + chunk({ + path: "src/queue/runner.ts", + oldPath: "src/queue/worker.ts", + qualified: "drainQueue", + kind: "function", + name: "drainQueue", + startLine: 64, + endLine: 131, + baseStartLine: 64, + baseEndLine: 129, + status: "modified", + match: "renamed-file", + netAdded: 9, + netDeleted: 7, + touches: [touch(C.extract, 6, 9), touch(C.rename, 4, 3)], + metrics: { complexity: m(14, 15), cognitive_complexity: m(21, 22), loc: m(66, 68), max_nesting_depth: m(4, 4), parameter_count: m(2, 2) }, + measured: true, + buckets: ["complex-and-changed", "new-hotspot"], + fileClass: "code", + }), + chunk({ + path: "src/queue/runner.ts", + oldPath: "src/queue/worker.ts", + qualified: "QueueRunner", + kind: "class", + name: "QueueRunner", + startLine: 12, + endLine: 60, + baseStartLine: 12, + baseEndLine: 60, + status: "moved", + match: "renamed-file", + netAdded: 0, + netDeleted: 0, + touches: [touch(C.rename, 0, 0)], + metrics: { complexity: m(6, 6), loc: m(49, 49), max_nesting_depth: m(2, 2) }, + measured: true, + buckets: [], + fileClass: "code", + }), + chunk({ + path: "src/jobs/schedule.ts", + qualified: "parseLegacySchedule", + kind: "function", + name: "parseLegacySchedule", + startLine: 88, + endLine: 151, + baseStartLine: 88, + baseEndLine: 151, + status: "deleted", + match: "none", + netAdded: 0, + netDeleted: 64, + touches: [touch(C.legacy, 0, 64)], + metrics: { complexity: m(19, null), cognitive_complexity: m(31, null), loc: m(64, null), max_nesting_depth: m(5, null), parameter_count: m(2, null) }, + measured: true, + buckets: [], + fileClass: "code", + }), + chunk({ + path: "src/jobs/schedule.ts", + qualified: "parseSchedule", + kind: "function", + name: "parseSchedule", + startLine: 20, + endLine: 52, + baseStartLine: 20, + baseEndLine: 48, + status: "modified", + match: "uncertain", + netAdded: 9, + netDeleted: 5, + touches: [touch(C.legacy, 9, 5)], + metrics: { complexity: m(8, 9), cognitive_complexity: m(9, 11), loc: m(29, 33), max_nesting_depth: m(2, 3), parameter_count: m(1, 1) }, + measured: true, + buckets: [], + fileClass: "code", + }), + chunk({ + path: "src/jobs/settings.ts", + kind: "file", + name: "settings.ts", + startLine: 1, + endLine: 52, + baseStartLine: 1, + baseEndLine: 40, + status: "modified", + match: "exact", + netAdded: 14, + netDeleted: 2, + touches: [touch(C.config, 14, 2)], + metrics: { loc: m(40, 52) }, + measured: true, + buckets: [], + fileClass: "code", + }), + chunk({ + path: "config/jobs.toml", + kind: "file", + name: "jobs.toml", + startLine: 1, + endLine: 34, + baseStartLine: 1, + baseEndLine: 25, + status: "modified", + match: "exact", + netAdded: 13, + netDeleted: 2, + touches: [touch(C.config, 10, 1), touch(WORKTREE, 3, 1)], + metrics: {}, + measured: false, + naReason: "No analyzer reads TOML files.", + buckets: [], + fileClass: "config", + }), + chunk({ + path: "docs/jobs.md", + qualified: "## Retries", + kind: "heading", + name: "## Retries", + startLine: 58, + endLine: 91, + baseStartLine: 58, + baseEndLine: 70, + status: "modified", + match: "exact", + netAdded: 22, + netDeleted: 1, + touches: [touch(C.legacy, 22, 1)], + metrics: {}, + measured: true, + buckets: [], + fileClass: "docs", + }), + chunk({ + path: "scripts/requeue-dead-jobs.sh", + qualified: "L40-62", + kind: "range", + name: "lines 40–62", + startLine: 40, + endLine: 62, + baseStartLine: 40, + baseEndLine: 57, + status: "modified", + match: "exact", + netAdded: 8, + netDeleted: 3, + touches: [touch(C.logRetry, 8, 1), touch(C.legacy, 0, 4)], + metrics: {}, + measured: false, + naReason: "No analyzer reads shell scripts.", + buckets: [], + fileClass: "code", + }), + chunk({ + path: "src/jobs/retry.test.ts", + qualified: "retries with backoff", + kind: "function", + name: "retries with backoff", + startLine: 14, + endLine: 58, + status: "added", + match: "none", + netAdded: 36, + netDeleted: 0, + touches: [touch(C.backoff, 30, 0), touch(C.offByOne, 1, 1), touch(WORKTREE, 6, 0)], + metrics: { complexity: m(null, 2), loc: m(null, 36), max_nesting_depth: m(null, 2) }, + measured: true, + buckets: [], + fileClass: "test", + }), + chunk({ + path: "src/ui/JobRow.tsx", + qualified: "JobRow", + kind: "function", + name: "JobRow", + startLine: 18, + endLine: 74, + baseStartLine: 18, + baseEndLine: 70, + status: "modified", + match: "exact", + netAdded: 4, + netDeleted: 3, + touches: [touch(WORKTREE, 4, 3)], + metrics: { + complexity: m(6, 7), + loc: m(53, 57), + component_hook_count: m(2, 3), + component_jsx_depth: m(6, 6), + component_prop_count: m(4, 5), + }, + measured: true, + buckets: [], + fileClass: "code", + }), + chunk({ + path: "src/features/notifications/delivery/handlers/createExponentialBackoffNotificationDeliveryHandler.ts", + qualified: "createExponentialBackoffNotificationDeliveryHandlerWithJitterAndCircuitBreaker", + kind: "function", + name: "createExponentialBackoffNotificationDeliveryHandlerWithJitterAndCircuitBreaker", + startLine: 210, + endLine: 344, + baseStartLine: 204, + baseEndLine: 331, + status: "modified", + match: "exact", + netAdded: 22, + netDeleted: 9, + touches: [touch(C.extract, 28, 4)], + metrics: { complexity: m(10, 13), cognitive_complexity: m(16, 21), loc: m(128, 135), max_nesting_depth: m(4, 5), parameter_count: m(4, 4) }, + measured: true, + buckets: ["complex-and-changed", "new-hotspot"], + fileClass: "code", + }), +]; + +const commits = [...Object.values(C), worktree]; +for (const c of chunks) for (const t of c.touches) commits.find((x) => x.sha === t.sha)?.chunkIds.push(c.id); + +const files: LensFile[] = Object.values( + chunks.reduce>((out, c) => { + const f = (out[c.path] ??= { + path: c.path, + ...(c.oldPath && c.match === "renamed-file" ? { oldPath: c.oldPath } : {}), + status: c.match === "renamed-file" ? "renamed" : c.status === "added" ? "added" : "modified", + added: 0, + deleted: 0, + loc: 120, + fileClass: c.fileClass, + chunkIds: [], + outOfScope: false, + }); + f.added += c.added; + f.deleted += c.deleted; + f.chunkIds.push(c.id); + return out; + }, {}) +); + +export const samplePayload: ChangeLensPayload = { + selection: { + window: "branch", + mode: "touched", + ref: "HEAD", + base: { ref: "merge-base(main, HEAD)", sha: sha("3f9a"), label: "main @ 3f9a3f9", date: "2026-11-17T14:02:00Z" }, + head: { ref: WORKTREE, sha: null, label: "Working tree", date: null }, + since: null, + until: null, + timezone: "America/Chicago", + includesWorktree: true, + notes: [], + }, + commits, + chunks, + files, + summary: { + filesEdited: files.length, + filesTotal: 214, + chunks: chunks.length, + churnLines: chunks.reduce((n, c) => n + c.added + c.deleted, 0), + netLines: chunks.reduce((n, c) => n + c.netAdded + c.netDeleted, 0), + reverted: chunks.filter((c) => c.status === "reverted").length, + }, + metricIds: ["complexity", "cognitive_complexity", "loc", "max_nesting_depth", "parameter_count", "component_hook_count", "component_jsx_depth", "component_prop_count"], +}; + +/** A window with no edits. */ +export const emptyPayload: ChangeLensPayload = { + ...samplePayload, + selection: { ...samplePayload.selection, notes: ["No commits on this branch since main, and no uncommitted edits."] }, + commits: [], + chunks: [], + files: [], + summary: { filesEdited: 0, filesTotal: 214, chunks: 0, churnLines: 0, netLines: 0, reverted: 0 }, + metricIds: [], +}; + +export const sampleHunkDiff: LensHunkDiff = { + chunkId: "src/jobs/retry.ts::retryJob", + path: "src/jobs/retry.ts", + from: "main @ 3f9a3f9", + to: "Working tree", + truncated: false, + diff: `diff --git a/src/jobs/retry.ts b/src/jobs/retry.ts +index 3f9a3f9..8c1e2d0 100644 +--- a/src/jobs/retry.ts ++++ b/src/jobs/retry.ts +@@ -30,24 +42,38 @@ import { RetryPolicy } from "./policy"; + +-export async function retryJob(job: Job, queue: Queue): Promise { +- const max = job.maxAttempts ?? 3; +- for (let attempt = 0; attempt < max; attempt++) { ++export async function retryJob(job: Job, queue: Queue, policy = RetryPolicy.default()): Promise { ++ const max = job.maxAttempts ?? policy.maxAttempts; ++ for (let attempt = 1; attempt <= max; attempt++) { + try { + const result = await queue.run(job); +- return result; ++ if (result.ok) return result; ++ if (!policy.shouldRetry(result.error)) return result; + } catch (error) { +- if (attempt === max - 1) throw error; ++ if (attempt === max || !policy.shouldRetry(error)) throw error; + } +- await sleep(1000); ++ const delay = backoffDelay(attempt, policy); ++ logger.info("retrying job", { id: job.id, attempt, delay }); ++ await sleep(delay); + } +- return { ok: false, error: new Error("retries exhausted") }; ++ return { ok: false, error: new RetryExhaustedError(job.id, max) }; + } +@@ -71,14 +97,22 @@ export async function retryJob(job: Job, queue: Queue): Promise { + export function retryAll(jobs: Job[], queue: Queue) { +- return Promise.all(jobs.map((job) => retryJob(job, queue))); ++ const policy = RetryPolicy.fromSettings(settings.jobs.retry); ++ return Promise.all(jobs.map((job) => retryJob(job, queue, policy))); + } + + function isTransient(error: unknown): boolean { + if (error instanceof TimeoutError) return true; + if (error instanceof NetworkError) return error.status !== 401; ++ if (error instanceof RateLimitError) return true; + return false; + } +`, +}; + +/** A long generated diff for checking speed and truncation. */ +export function bigHunkDiff(lines: number): LensHunkDiff { + const out = ["--- a/src/generated/routes.ts", "+++ b/src/generated/routes.ts"]; + let written = 0; + for (let h = 0; written < lines; h++) { + const start = h * 60 + 1; + out.push(`@@ -${start},36 +${start},36 @@ export const routes = {`); + for (let i = 0; i < 40 && written < lines; i++, written++) { + const n = start + i; + if (i % 10 === 4) out.push(`- route${n}: { path: "/v1/items/${n}", method: "GET", auth: false },`); + else if (i % 10 === 5) out.push(`+ route${n - 1}: { path: "/v2/items/${n - 1}", method: "GET", auth: true },`); + else out.push(` route${n}: { path: "/v1/items/${n}", method: "GET", auth: false },`); + } + } + return { + chunkId: "src/generated/routes.ts", + path: "src/generated/routes.ts", + from: "main @ 3f9a3f9", + to: "29e7029", + diff: out.join("\n"), + truncated: true, + }; +} From 6e7d09f717a4c2e83afd98223fe263d15c23ca4d Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 21 Nov 2026 13:45:29 -0500 Subject: [PATCH 2/3] fix(changelens): precise word highlights in the hunk diff (#397) Paired lines mark changed words with a token LCS instead of a prefix and suffix trim. Lines that share less than half their text get no marks, since they were rewritten. Co-Authored-By: Claude Opus 5.5 --- .../changelens/panel/parseUnifiedDiff.test.ts | 4 +- .../src/changelens/panel/parseUnifiedDiff.ts | 59 +++++++++++++++---- 2 files changed, 50 insertions(+), 13 deletions(-) diff --git a/client/src/changelens/panel/parseUnifiedDiff.test.ts b/client/src/changelens/panel/parseUnifiedDiff.test.ts index dbf0ac6f..2b3a16f8 100644 --- a/client/src/changelens/panel/parseUnifiedDiff.test.ts +++ b/client/src/changelens/panel/parseUnifiedDiff.test.ts @@ -46,8 +46,8 @@ describe("parseUnifiedDiff", () => { it("highlights only the changed words of a paired line", () => { const [del, add] = hunks[0].lines.slice(1, 3); - expect(del.spans?.filter((s) => s.hit).map((s) => s.text)).toEqual(["0; i <"]); - expect(add.spans?.filter((s) => s.hit).map((s) => s.text)).toEqual(["1; i <="]); + expect(del.spans?.filter((s) => s.hit).map((s) => s.text)).toEqual(["0"]); + expect(add.spans?.filter((s) => s.hit).map((s) => s.text)).toEqual(["1", "="]); // The unpaired added line gets no highlight. expect(hunks[0].lines[3].spans).toBeUndefined(); }); diff --git a/client/src/changelens/panel/parseUnifiedDiff.ts b/client/src/changelens/panel/parseUnifiedDiff.ts index 65d45b0e..7d6ab0a9 100644 --- a/client/src/changelens/panel/parseUnifiedDiff.ts +++ b/client/src/changelens/panel/parseUnifiedDiff.ts @@ -90,23 +90,60 @@ function pairWords(lines: DiffLine[]) { const TOKEN = /\w+|\s+|[^\w\s]/g; -/** Common prefix and suffix tokens stay plain; the middle is the change. */ +/** Most token pairs compared by the LCS; longer pairs fall back to prefix and suffix. */ +const MAX_LCS = 20000; + +/** Tokens both lines share (a token LCS) stay plain; the rest is the change. */ export function markWords(del: DiffLine, add: DiffLine) { if (del.text.length > MAX_HIGHLIGHT || add.text.length > MAX_HIGHLIGHT) return; const a = del.text.match(TOKEN) ?? []; const b = add.text.match(TOKEN) ?? []; + const [keepA, keepB] = a.length * b.length <= MAX_LCS ? lcs(a, b) : prefixSuffix(a, b); + // Lines that share less than half their text were rewritten; scattered highlights would only add noise. + const solid = (tokens: string[], keep?: boolean[]) => + tokens.reduce((n, t, i) => n + (keep && !keep[i] ? 0 : t.replace(/\s/g, "").length), 0); + if (solid(a, keepA) < 0.5 * Math.min(solid(a), solid(b))) return; + del.spans = spans(a, keepA); + add.spans = spans(b, keepB); +} + +function spans(tokens: string[], keep: boolean[]): DiffSpan[] { + const out: DiffSpan[] = []; + tokens.forEach((text, i) => { + const hit = !keep[i]; + const last = out[out.length - 1]; + if (last && last.hit === hit) last.text += text; + else out.push({ text, hit }); + }); + return out; +} + +function lcs(a: string[], b: string[]): [boolean[], boolean[]] { + const n = a.length; + const m = b.length; + const table = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1)); + for (let i = n - 1; i >= 0; i--) + for (let j = m - 1; j >= 0; j--) + table[i][j] = a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]); + const keepA = new Array(n).fill(false); + const keepB = new Array(m).fill(false); + let i = 0; + let j = 0; + while (i < n && j < m) { + if (a[i] === b[j]) { + keepA[i++] = true; + keepB[j++] = true; + } else if (table[i + 1][j] >= table[i][j + 1]) i++; + else j++; + } + return [keepA, keepB]; +} + +function prefixSuffix(a: string[], b: string[]): [boolean[], boolean[]] { let pre = 0; while (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++; let suf = 0; while (suf < a.length - pre && suf < b.length - pre && a[a.length - 1 - suf] === b[b.length - 1 - suf]) suf++; - // Nothing in common: the whole line changed, and a highlight would only add noise. - if (pre + suf === 0) return; - const split = (tokens: string[]): DiffSpan[] => - [ - { text: tokens.slice(0, pre).join(""), hit: false }, - { text: tokens.slice(pre, tokens.length - suf).join(""), hit: true }, - { text: tokens.slice(tokens.length - suf).join(""), hit: false }, - ].filter((s) => s.text); - del.spans = split(a); - add.spans = split(b); + const keep = (len: number) => Array.from({ length: len }, (_, i) => i < pre || i >= len - suf); + return [keep(a.length), keep(b.length)]; } From 71bf249ec917170c81b9d961b540368ac2fa98e1 Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 21 Nov 2026 19:13:00 -0500 Subject: [PATCH 3/3] fix(changelens): the panel sample names its repo root (#397) Co-Authored-By: Claude Fable 5.2 --- client/src/changelens/panel/sample.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/client/src/changelens/panel/sample.ts b/client/src/changelens/panel/sample.ts index 3a053cc7..9cad9324 100644 --- a/client/src/changelens/panel/sample.ts +++ b/client/src/changelens/panel/sample.ts @@ -391,6 +391,7 @@ export const samplePayload: ChangeLensPayload = { window: "branch", mode: "touched", ref: "HEAD", + repoRoot: "/repo/jobs-service", base: { ref: "merge-base(main, HEAD)", sha: sha("3f9a"), label: "main @ 3f9a3f9", date: "2026-11-17T14:02:00Z" }, head: { ref: WORKTREE, sha: null, label: "Working tree", date: null }, since: null,