From e595bace62529c5a58cad0729ae2b8a02e3bee53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Val=20Alexander=20=F0=9F=91=91?= Date: Thu, 12 Nov 2026 00:49:03 -0600 Subject: [PATCH 1/9] Add a local Viewed toggle to remote diffs and remove the new-tab control Decision 5 (C65): a file can be marked viewed. The mark is kept on this Mac per account and belongs to one revision; a new head or base shows none. Marking folds the file; the tree and a count show progress. Nothing is read from or sent to GitHub. Decision 6 (C07): the unavailable new-tab button is removed. Co-Authored-By: Claude Fable 5.2 --- apps/desktop/e2e/code-review-diff.spec.ts | 32 ++++++++++ .../e2e/code-review-navigation.spec.ts | 3 +- .../e2e/code-review-regressions.spec.ts | 11 +--- .../renderer/code-review/CodeReviewView.tsx | 3 - .../src/renderer/code-review/PrChanges.tsx | 17 ++++-- .../src/renderer/code-review/code-review.css | 5 +- .../src/renderer/code-review/viewed.ts | 58 +++++++++++++++++++ .../test/code-review-workspace.test.ts | 31 ++++++++++ 8 files changed, 142 insertions(+), 18 deletions(-) create mode 100644 apps/desktop/src/renderer/code-review/viewed.ts diff --git a/apps/desktop/e2e/code-review-diff.spec.ts b/apps/desktop/e2e/code-review-diff.spec.ts index 94a13687..fe1bbbe0 100644 --- a/apps/desktop/e2e/code-review-diff.spec.ts +++ b/apps/desktop/e2e/code-review-diff.spec.ts @@ -73,6 +73,38 @@ test("grouped diffs, both gutters, hierarchy, filter and keyboard selection use expect((await log()).filter((r: any) => r.op === "files")).toHaveLength(1); }); +test("Viewed marks a file on this Mac for one revision, folds it, survives a reload and asks GitHub nothing (C65)", async () => { + await open(); + const first = tid(page, "cr-file-section").first(); + const viewed = page.getByRole("checkbox", { name: "Viewed src/holds/move.ts", exact: true }); + await expect(tid(page, "cr-viewed-count")).toHaveText("0 of 4 viewed"); + await expect(first.getByTestId("diff").first()).toBeVisible(); + const asked = (await log()).length; + await viewed.focus(); + await page.keyboard.press("Space"); + await expect(viewed).toBeChecked(); + await expect(first.getByTestId("diff")).toHaveCount(0); + await expect(tid(page, "cr-viewed-count")).toHaveText("1 of 4 viewed"); + await expect(page.getByRole("button", { name: "View remote diff for src/holds/move.ts, viewed", exact: true })).toBeVisible(); + // The file can still be opened, and unmarking it does not reopen or lose anything. + await page.getByRole("button", { name: "Expand src/holds/move.ts", exact: true }).click(); + await expect(first.getByTestId("diff").first()).toBeVisible(); + expect((await log()).length, "a mark is local: no read, and there is no write channel call").toBe(asked); + await page.reload(); + await tid(page, "rail-code-review").click(); + await page.locator('[data-testid="code-review-row"][data-pr="example-org/field-guide#91"]').click(); + await tid(page, "code-review-tab-changes").click(); + await expect(page.getByRole("checkbox", { name: "Viewed src/holds/move.ts", exact: true })).toBeChecked(); + await expect(tid(page, "cr-viewed-count")).toHaveText("1 of 4 viewed"); + // A new head may have changed the file: its marks are not carried over. + await app.evaluate(() => { const s = (globalThis as any).__diff; s.revision = { ...s.revision, headSha: "f".repeat(40) }; }); + await refreshOverview(); + await expect(tid(page, "cr-file-section").first()).toHaveAttribute("data-head-sha", "f".repeat(40)); + await expect(tid(page, "cr-viewed-count")).toHaveText("0 of 4 viewed"); + await expect(page.getByRole("checkbox", { name: "Viewed src/holds/move.ts", exact: true })).not.toBeChecked(); + expect(await app.evaluate(() => (globalThis as any).__diff.local)).toEqual([]); +}); + test("expanding context asks the exact remote revision and never a local file", async () => { await open(); const section = tid(page, "cr-file-section").first(); diff --git a/apps/desktop/e2e/code-review-navigation.spec.ts b/apps/desktop/e2e/code-review-navigation.spec.ts index 3c471c81..a61d1fe4 100644 --- a/apps/desktop/e2e/code-review-navigation.spec.ts +++ b/apps/desktop/e2e/code-review-navigation.spec.ts @@ -387,7 +387,8 @@ test("pin, copy and Open in GitHub use the canonical link, a pasted link opens i await settle(page); expect((await log(app)).filter((r) => r.requestId !== "settle").length).toBe(asked); await expect(tid(page, "code-review-review").first()).toHaveAttribute("aria-disabled", "true"); - await expect(tid(page, "code-review-new-tab").first()).toHaveAttribute("aria-disabled", "true"); + // C07 (decision 6, 2026-11-04): this surface has no new-tab control. + await expect(tid(page, "code-review-new-tab")).toHaveCount(0); // Pins outlive a reload, per account, and open their PR. await page.reload(); await tid(page, "rail-code-review").click(); diff --git a/apps/desktop/e2e/code-review-regressions.spec.ts b/apps/desktop/e2e/code-review-regressions.spec.ts index b49c2a16..2c121627 100644 --- a/apps/desktop/e2e/code-review-regressions.spec.ts +++ b/apps/desktop/e2e/code-review-regressions.spec.ts @@ -240,15 +240,8 @@ for (const delayed of [false, true]) test(`dispatch: unavailable actions start n await page.keyboard.press("Escape"); await expect(page.getByRole("dialog", { name: "Review instructions" })).toHaveCount(0); // Merge is CR-7's now (e2e/code-review-actions.spec.ts): opening it reads, and only an explicit preview and confirm writes. - for (const id of ["code-review-new-tab"]) { - const control = tid(page, id).first(); - await expect(control, id).toHaveAttribute("aria-disabled", "true"); - // aria-disabled, not disabled: it stays focusable, so force the pointer through to prove it does nothing. - await control.dblclick({ force: true }); - await control.focus(); - await page.keyboard.press("Enter"); - await page.keyboard.press("Space"); - } + // C07 (decision 6, 2026-11-04): the new-tab control is gone from this surface. + await expect(tid(page, "code-review-new-tab")).toHaveCount(0); await expect(tid(page, "code-review-pr-id").first()).toHaveText("lending #73"); await settle(page); // The settle reads are connection checks; nothing else reached gh, and no provider CLI started. diff --git a/apps/desktop/src/renderer/code-review/CodeReviewView.tsx b/apps/desktop/src/renderer/code-review/CodeReviewView.tsx index 0e49e7c3..861e63fd 100644 --- a/apps/desktop/src/renderer/code-review/CodeReviewView.tsx +++ b/apps/desktop/src/renderer/code-review/CodeReviewView.tsx @@ -6,7 +6,6 @@ import type { Layout } from "../../shared/layout"; import { PanelResizeHandle } from "../components/PanelResizeHandle"; import { Icon } from "../components/ui/Icon"; import { IconButton } from "../components/ui/IconButton"; -import { Tooltip } from "../components/ui/Tooltip"; import { refreshingRead, retainRead } from "../../shared/code-review-overview.js"; import { Reader, type Ask, type Outcome } from "./reader.js"; import { back, canBack, canForward, closeChanges, current, DEFAULT_VIEW, EMPTY_HISTORY, fitSplit, fitTree, forward, panesFor, showTab, SPLIT, toggleSplit, visit, type History, type Pane, type PrView } from "./navigation.js"; @@ -298,8 +297,6 @@ export default function CodeReviewView({ active, inboxOpen, layout, setLayout, o ; })} - {/* C07: what a new tab opens here is an open decision; until then it is shown and unavailable. */} - {(!split || !group.includes("overview")) && } ); const singleGroup: Pane[] = view.changes ? ["overview", "changes"] : ["overview"]; diff --git a/apps/desktop/src/renderer/code-review/PrChanges.tsx b/apps/desktop/src/renderer/code-review/PrChanges.tsx index 7e781f65..8ff1db5c 100644 --- a/apps/desktop/src/renderer/code-review/PrChanges.tsx +++ b/apps/desktop/src/renderer/code-review/PrChanges.tsx @@ -11,6 +11,7 @@ import { Reader } from "./reader.js"; import { prUrl } from "./model.js"; import { anchorFor, anchorState, parsePatch, hunkBounds, contextWindow, type LineAnchor, type PatchRow } from "./patch.js"; import { unavailableText } from "./text.js"; +import { loadViewed, setViewed } from "./viewed.js"; import { highlightRows, REMOTE_TEXT_LIMITS } from "./remote-highlight.js"; let sessionSequence = 0; @@ -55,6 +56,12 @@ function ChangesSession({ overview, views, stale, bodyRef, treeRef, treeWidth, c const [filter, setFilter] = useState(saved?.filter ?? ""); const [wrap, setWrap] = useState(saved?.wrap ?? true); const [highlight, setHighlight] = useState(saved?.highlight ?? true); + // C65: local marks for exactly this revision (this component is keyed by it); nothing is sent to GitHub. + const [viewed, setViewedPaths] = useState(() => loadViewed(localStorage, overview.key, overview.revision)); + const mark = (path: string, on: boolean) => { + setViewedPaths(setViewed(localStorage, overview.key, overview.revision, path, on)); + if (on) setExpanded(paths => paths.filter(p => p !== path)); + }; const sections = useRef(new Map()); const alive = useRef(true); const lastPage = pages.at(-1); @@ -105,6 +112,7 @@ function ChangesSession({ overview, views, stale, bodyRef, treeRef, treeWidth, c
{files.length} of {total} files loaded{incomplete ? " · Incomplete file list" : ""} + {files.filter(f => viewed.includes(f.path)).length} of {files.length} viewed
@@ -121,6 +129,7 @@ function ChangesSession({ overview, views, stale, bodyRef, treeRef, treeWidth, c {file.patch.kind === "omitted" && {file.patch.reason === "binary" ? "No text diff" : "Patch unavailable"}} +{file.additions}−{file.deletions} +
⋯
{prUrl(overview.locator) && Open in GitHub}
{file.previousPath &&

Renamed from {file.previousPath}

} @@ -136,14 +145,14 @@ function ChangesSession({ overview, views, stale, bodyRef, treeRef, treeWidth, c ; } interface TreeNode { folders: Map; files: PrFile[] } -function FileTree({ files, selected, onSelect }: { files: PrFile[]; selected: string | null; onSelect: (path: string) => void }) { +function FileTree({ files, selected, viewed, onSelect }: { files: PrFile[]; selected: string | null; viewed: string[]; onSelect: (path: string) => void }) { const root: TreeNode = { folders: new Map(), files: [] }; for (const file of files) { let node = root; @@ -155,8 +164,8 @@ function FileTree({ files, selected, onSelect }: { files: PrFile[]; selected: st } const render = (node: TreeNode, prefix = "") => <> {[...node.folders].map(([folder, child]) =>
{folder}
{render(child, `${prefix}${folder}/`)}
)} - {node.files.map(file => )} ; return
{ diff --git a/apps/desktop/src/renderer/code-review/code-review.css b/apps/desktop/src/renderer/code-review/code-review.css index 25200fb2..17ba26dc 100644 --- a/apps/desktop/src/renderer/code-review/code-review.css +++ b/apps/desktop/src/renderer/code-review/code-review.css @@ -17,7 +17,6 @@ .cr-totals { flex: none; font-variant-numeric: tabular-nums; } .cr-add { color: var(--add); } .cr-del { color: var(--del); } -.cr-new-tab[aria-disabled="true"] { opacity: .5; cursor: default; } /* Inbox: R1 x 55–335, an 8 px scrollbar gutter included; search y 100–136; rows about 73 tall. */ .cr-inbox { width: var(--sidebar-w); flex: none; display: flex; flex-direction: column; min-width: 0; min-height: 0; background: var(--bg-sidebar); border-right: 1px solid var(--border-pane); } @@ -162,6 +161,10 @@ .cr-file-heading > button { display: flex; align-items: center; gap: 6px; min-width: 0; flex: 1; text-align: left; font-size: 11px; color: var(--text-2); background: transparent; border: 0; padding: 3px 0; cursor: pointer; } .cr-file-heading bdi { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .cr-file-heading .stat { flex-shrink: 0; font-size: 10px; } +.cr-viewed { display: inline-flex; align-items: center; gap: 4px; font-size: 11px; color: var(--text-3); white-space: nowrap; cursor: pointer; } +.cr-viewed:has(input:checked) { color: var(--text-1); } +.cr-tree-file[data-viewed="true"] bdi { color: var(--text-3); } +.cr-tree-viewed { font-size: 10px; color: var(--text-3); flex-shrink: 0; } .cr-file-menu { position: relative; } .cr-file-menu summary { list-style: none; cursor: pointer; padding: 0 4px; } .cr-file-menu > div { position: absolute; z-index: 4; top: 22px; right: 0; display: grid; gap: 6px; width: 150px; padding: 8px; background: var(--bg-2); border: 1px solid var(--border-pane); border-radius: 6px; } diff --git a/apps/desktop/src/renderer/code-review/viewed.ts b/apps/desktop/src/renderer/code-review/viewed.ts new file mode 100644 index 00000000..7b88e688 --- /dev/null +++ b/apps/desktop/src/renderer/code-review/viewed.ts @@ -0,0 +1,58 @@ +import type { PrKey, PrRevision } from "../../shared/code-review.js"; + +/** + * Viewed files (C65, decision 5): a local mark per signed-in account, never GitHub's viewed state and never + * a write. A mark belongs to the revision it was made at: when the head or the base moves, the files may + * have changed, so the marks for the earlier revision are not shown and the next mark replaces them. + */ +export const VIEWED_KEY = "modex.codeReview.viewed"; +const PRS = 200, PATHS = 3000; + +type Storage = { getItem(key: string): string | null; setItem(key: string, value: string): void }; +interface Entry { baseSha: string; headSha: string; paths: string[] } + +const ACCOUNT = /^[1-9][0-9]{0,19}$/; +const SHA = /^[0-9a-f]{40}$/; +const id = (key: PrKey) => `${key.repoId}#${key.number}`; + +function read(storage: Storage): Record { + try { + const value: unknown = JSON.parse(storage.getItem(VIEWED_KEY) ?? "null"); + return value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + } catch { + return {}; + } +} + +function entries(storage: Storage, account: string): Record { + const mine = ACCOUNT.test(account) ? read(storage)[account] : null; + return mine && typeof mine === "object" && !Array.isArray(mine) ? mine as Record : {}; +} + +function valid(value: unknown, revision: PrRevision): string[] { + if (!value || typeof value !== "object") return []; + const { baseSha, headSha, paths } = value as Partial; + if (typeof baseSha !== "string" || typeof headSha !== "string" || !SHA.test(baseSha) || !SHA.test(headSha) || !Array.isArray(paths)) return []; + if (baseSha !== revision.baseSha || headSha !== revision.headSha) return []; + return [...new Set(paths.filter((path): path is string => typeof path === "string" && path.length > 0 && path.length <= 4096))].slice(0, PATHS); +} + +/** The paths marked viewed at exactly this revision; none for any other. */ +export function loadViewed(storage: Storage, key: PrKey, revision: PrRevision): string[] { + return valid(entries(storage, key.account)[id(key)], revision); +} + +/** Marks or unmarks one path at this revision and returns the paths as saved. */ +export function setViewed(storage: Storage, key: PrKey, revision: PrRevision, path: string, viewed: boolean): string[] { + if (!ACCOUNT.test(key.account) || !SHA.test(revision.baseSha) || !SHA.test(revision.headSha)) return []; + const mine = entries(storage, key.account); + const current = valid(mine[id(key)], revision).filter((p) => p !== path); + const paths = viewed ? [...current, path].slice(-PATHS) : current; + // Newest last; the oldest pull requests' marks go first when the list is full. + const rest = Object.entries(mine).filter(([other]) => other !== id(key)).slice(-(PRS - 1)); + const next = paths.length ? [...rest, [id(key), { baseSha: revision.baseSha, headSha: revision.headSha, paths } satisfies Entry]] : rest; + try { + storage.setItem(VIEWED_KEY, JSON.stringify({ ...read(storage), [key.account]: Object.fromEntries(next) })); + } catch { /* A full or blocked store keeps the mark for this session only. */ } + return paths; +} diff --git a/apps/desktop/test/code-review-workspace.test.ts b/apps/desktop/test/code-review-workspace.test.ts index 24f91181..9c27a3e7 100644 --- a/apps/desktop/test/code-review-workspace.test.ts +++ b/apps/desktop/test/code-review-workspace.test.ts @@ -4,6 +4,7 @@ import { prKeyId, scopeOf, SIGN_IN_CHANGED, type CodeReviewReply, type CodeRevie import { Reader } from "../src/renderer/code-review/reader.js"; import { back, canBack, canForward, closeChanges, current, DEFAULT_VIEW, fitSplit, fitTree, forward, panesFor, showTab, SPLIT, toggleSplit, visit, type History } from "../src/renderer/code-review/navigation.js"; import { isPinned, loadPins, PINS_KEY, togglePin } from "../src/renderer/code-review/pins.js"; +import { loadViewed, setViewed, VIEWED_KEY } from "../src/renderer/code-review/viewed.js"; import { LAYOUT_KEY, LEGACY_CODE_REVIEW_SWITCH, loadLayout, saveLayout } from "../src/shared/layout.js"; import { ACCOUNT_A, ACCOUNT_B, FIELD_GUIDE, key, LENDING, locator, R1, R4 } from "./fixtures/code-review.js"; @@ -241,6 +242,36 @@ test("pins are local, per account, validated on load and capped", () => { assert.equal(loadPins(storage, ACCOUNT_A.id).length, 50); }); +test("viewed marks are local, per account and belong to one revision (C65)", () => { + const store = new Map(); + const storage = { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => void store.set(k, v) }; + const pr = key(ACCOUNT_A, LENDING, 73); + const at = (head: string, base = "a") => ({ baseRef: "main", baseSha: base.repeat(40), headSha: head.repeat(40) }); + assert.deepEqual(loadViewed(storage, pr, at("b")), []); + assert.deepEqual(setViewed(storage, pr, at("b"), "src/a.ts", true), ["src/a.ts"]); + assert.deepEqual(setViewed(storage, pr, at("b"), "src/b.ts", true), ["src/a.ts", "src/b.ts"]); + assert.deepEqual(setViewed(storage, pr, at("b"), "src/a.ts", true), ["src/b.ts", "src/a.ts"], "marking twice keeps one mark"); + assert.deepEqual(loadViewed(storage, pr, at("b")), ["src/b.ts", "src/a.ts"]); + assert.deepEqual(loadViewed(storage, pr, at("c")), [], "a new head shows no marks: the files may have changed"); + assert.deepEqual(loadViewed(storage, pr, at("b", "d")), [], "so does a moved base"); + assert.deepEqual(loadViewed(storage, key(ACCOUNT_B, LENDING, 73), at("b")), [], "another account sees none of them"); + assert.deepEqual(loadViewed(storage, key(ACCOUNT_A, LENDING, 74), at("b")), [], "nor does another pull request"); + assert.deepEqual(setViewed(storage, pr, at("b"), "src/b.ts", false), ["src/a.ts"]); + assert.deepEqual(setViewed(storage, pr, at("c"), "src/c.ts", true), ["src/c.ts"], "a mark at a new head replaces the earlier revision's"); + assert.deepEqual(loadViewed(storage, pr, at("b")), []); + assert.deepEqual(setViewed(storage, pr, at("c"), "src/c.ts", false), []); + assert.deepEqual(JSON.parse(store.get(VIEWED_KEY)!)[ACCOUNT_A.id], {}, "an unmarked pull request leaves no entry"); + store.set(VIEWED_KEY, JSON.stringify({ [ACCOUNT_A.id]: { [`${pr.repoId}#73`]: { baseSha: "a".repeat(40), headSha: "b".repeat(40), paths: ["ok.ts", 7, "", "ok.ts"] }, [`${pr.repoId}#74`]: { baseSha: "zz", headSha: "b".repeat(40), paths: ["x"] } } })); + assert.deepEqual(loadViewed(storage, pr, at("b")), ["ok.ts"], "malformed paths are dropped"); + assert.deepEqual(loadViewed(storage, key(ACCOUNT_A, LENDING, 74), at("b")), [], "a malformed revision holds no marks"); + store.set(VIEWED_KEY, "{not json"); + assert.deepEqual(loadViewed(storage, pr, at("b")), []); + for (let n = 1; n <= 210; n++) setViewed(storage, key(ACCOUNT_A, LENDING, n), at("b"), "f.ts", true); + assert.equal(Object.keys(JSON.parse(store.get(VIEWED_KEY)!)[ACCOUNT_A.id]).length, 200, "the oldest pull requests' marks go first"); + assert.deepEqual(loadViewed(storage, key(ACCOUNT_A, LENDING, 210), at("b")), ["f.ts"]); + assert.deepEqual(loadViewed(storage, key(ACCOUNT_A, LENDING, 1), at("b")), []); +}); + test("the destination defaults on, keeps an explicit old off, and the saved choice wins over the old switch", () => { const storage = (value: string | null, saved?: object) => ({ getItem: (k: string) => k === LEGACY_CODE_REVIEW_SWITCH ? value : k === LAYOUT_KEY && saved ? JSON.stringify(saved) : null, setItem: () => {} }); assert.equal(loadLayout(storage(null)).codeReview, false); From 453d97f533ac9b89a6a1bdf72337d12b142c3067 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Val=20Alexander=20=F0=9F=91=91?= Date: Thu, 12 Nov 2026 01:19:05 -0600 Subject: [PATCH 2/9] Move between Code Review's areas and files with the keyboard Measured on real pull requests, every control was reachable with Tab but only through 34 to 124 presses between areas, and 147 arrows to the last of 151 files. F6 and Shift+F6 now move between the inbox, the pane tabs, the pane and the file list; [ and ] move to the previous and next file. Keys typed in a text field stay text. Co-Authored-By: Claude Fable 5.2 --- apps/desktop/e2e/code-review-diff.spec.ts | 33 ++++++++++++ .../renderer/code-review/CodeReviewView.tsx | 15 ++++++ .../src/renderer/code-review/PrChanges.tsx | 14 ++++- apps/desktop/src/renderer/code-review/keys.ts | 51 +++++++++++++++++++ .../test/code-review-workspace.test.ts | 20 ++++++++ 5 files changed, 131 insertions(+), 2 deletions(-) create mode 100644 apps/desktop/src/renderer/code-review/keys.ts diff --git a/apps/desktop/e2e/code-review-diff.spec.ts b/apps/desktop/e2e/code-review-diff.spec.ts index fe1bbbe0..4322e6bf 100644 --- a/apps/desktop/e2e/code-review-diff.spec.ts +++ b/apps/desktop/e2e/code-review-diff.spec.ts @@ -105,6 +105,39 @@ test("Viewed marks a file on this Mac for one revision, folds it, survives a rel expect(await app.evaluate(() => (globalThis as any).__diff.local)).toEqual([]); }); +test("keyboard: F6 moves between the areas and [ ] between files, and typing a bracket in the filter types it (F6)", async () => { + await open(); + await expect(tid(page, "cr-file-section")).toHaveCount(4); + await expect(tid(page, "cr-key-hint")).toContainText("F6"); + const paths = await tid(page, "cr-file-section").evaluateAll((sections) => sections.map((s) => (s as HTMLElement).dataset.path!)); + await tid(page, "code-review-search").focus(); + const focused = () => page.evaluate(() => { const a = document.activeElement as HTMLElement | null; return a?.dataset.testid ?? a?.getAttribute("role") ?? a?.tagName ?? null; }); + // Forward: inbox search, the selected tab, the diff, the file list, and round again. Four presses, not dozens of Tabs. + const seen: (string | null)[] = []; + for (let i = 0; i < 4; i++) { await page.keyboard.press("F6"); seen.push(await focused()); } + expect(seen).toEqual(["code-review-tab-changes", "code-review-diff", "cr-tree-file", "code-review-search"]); + await page.keyboard.press("Shift+F6"); + expect(await focused()).toBe("cr-tree-file"); + // ] and [ step through the files from anywhere in the pane, and stop at the ends. + const current = () => page.locator('[data-testid="cr-tree-file"][aria-current="true"]').getAttribute("title"); + expect(await current()).toBe(paths[0]); + await page.keyboard.press("]"); + await expect.poll(current).toBe(paths[1]); + await expect(page.locator(`[data-testid="cr-file-section"][data-path="${paths[1]}"]`)).toBeFocused(); + await page.keyboard.press("]"); await page.keyboard.press("]"); await page.keyboard.press("]"); + await expect.poll(current).toBe(paths[3]); + await page.keyboard.press("["); + await expect.poll(current).toBe(paths[2]); + // In a text field the keys are text. + const filter = page.getByRole("textbox", { name: "Filter remote files" }); + await filter.focus(); + await page.keyboard.type("[x]"); + await expect(filter).toHaveValue("[x]"); + await filter.fill(""); + await expect.poll(current, "typing brackets moved to no other file").toBe(paths[2]); + expect(await app.evaluate(() => (globalThis as any).__diff.local)).toEqual([]); +}); + test("expanding context asks the exact remote revision and never a local file", async () => { await open(); const section = tid(page, "cr-file-section").first(); diff --git a/apps/desktop/src/renderer/code-review/CodeReviewView.tsx b/apps/desktop/src/renderer/code-review/CodeReviewView.tsx index 861e63fd..e6ef7f98 100644 --- a/apps/desktop/src/renderer/code-review/CodeReviewView.tsx +++ b/apps/desktop/src/renderer/code-review/CodeReviewView.tsx @@ -10,6 +10,7 @@ import { refreshingRead, retainRead } from "../../shared/code-review-overview.js import { Reader, type Ask, type Outcome } from "./reader.js"; import { back, canBack, canForward, closeChanges, current, DEFAULT_VIEW, EMPTY_HISTORY, fitSplit, fitTree, forward, panesFor, showTab, SPLIT, toggleSplit, visit, type History, type Pane, type PrView } from "./navigation.js"; import { isPinned, loadPins, togglePin, type Pin } from "./pins.js"; +import { cycleArea } from "./keys.js"; import { additions, deletions, unavailableText } from "./text.js"; import { InboxPane } from "./Inbox"; import { rowsOf, titleOf, type GroupPages, type OpenPr } from "./model.js"; @@ -261,6 +262,20 @@ export default function CodeReviewView({ active, inboxOpen, layout, setLayout, o const connectionValue: CodeReviewConnection = connection && connection.state !== "unavailable" ? connection.value : { state: "unavailable", detail: connection?.state === "unavailable" ? unavailableText(connection) : "" }; const caps = capabilities(connectionValue); + // F6 and Shift+F6 move between the areas (keys.ts). The pane tabs sit in the title bar, outside this section, + // so the key is heard on the document while Code Review is the destination shown, and only when focus is in + // one of its areas or nowhere: a dialog or another destination keeps the key. + useEffect(() => { + if (!active) return; + const onKey = (event: globalThis.KeyboardEvent) => { + if (event.key !== "F6" || event.altKey || event.ctrlKey || event.metaKey || event.defaultPrevented) return; + const at = document.activeElement; + const mine = !at || at === document.body || !!at.closest('[data-testid="code-review"], [data-testid="code-review-tabbar"]'); + if (mine && !document.querySelector('[role="dialog"], dialog[open]') && cycleArea(document.body, event.shiftKey)) event.preventDefault(); + }; + document.addEventListener("keydown", onKey); + return () => document.removeEventListener("keydown", onKey); + }, [active]); const pinned = selected ? isPinned(pins, selected.key) : false; const pin = () => { if (!selected || !account) return; diff --git a/apps/desktop/src/renderer/code-review/PrChanges.tsx b/apps/desktop/src/renderer/code-review/PrChanges.tsx index 8ff1db5c..259a452a 100644 --- a/apps/desktop/src/renderer/code-review/PrChanges.tsx +++ b/apps/desktop/src/renderer/code-review/PrChanges.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef, useState, type RefObject } from "react"; +import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type RefObject } from "react"; import { prKeyId, sameKey, sameRevision, type PrFile, type PrOverview, type ReadResult, type PrFiles } from "../../shared/code-review.js"; import { LineComment } from "./ReviewComposer"; import type { Writes } from "./writes.js"; @@ -12,6 +12,7 @@ import { prUrl } from "./model.js"; import { anchorFor, anchorState, parsePatch, hunkBounds, contextWindow, type LineAnchor, type PatchRow } from "./patch.js"; import { unavailableText } from "./text.js"; import { loadViewed, setViewed } from "./viewed.js"; +import { stepFile, typing } from "./keys.js"; import { highlightRows, REMOTE_TEXT_LIMITS } from "./remote-highlight.js"; let sessionSequence = 0; @@ -107,7 +108,15 @@ function ChangesSession({ overview, views, stale, bodyRef, treeRef, treeWidth, c const incomplete = pages.some(p => p.result.state !== "ready") || !!next || files.length < total || (lastData && lastData.state !== "unavailable" && lastData.coverage?.complete === false); const missing = files.filter(f => f.patch.kind === "omitted" && f.patch.reason !== "binary").length; const matching = files.filter(f => `${f.path}\n${f.previousPath ?? ""}`.toLocaleLowerCase().includes(filter.toLocaleLowerCase())); - return
+ // `[` and `]` go to the previous and next file, wherever focus is in the pane, unless text is being typed. + const fileKeys = (event: KeyboardEvent) => { + if ((event.key !== "[" && event.key !== "]") || event.altKey || event.ctrlKey || event.metaKey || typing(event.target)) return; + const to = stepFile(matching.map(f => f.path), selected, event.key === "["); + if (to === null) return; + event.preventDefault(); + select(to); + }; + return
@@ -139,6 +148,7 @@ function ChangesSession({ overview, views, stale, bodyRef, treeRef, treeWidth, c {!busy && next && !stopped && last?.state === "ready" && files.length < DISPLAY.files && } {stopped &&

{stopped} Open in GitHub

} {files.length >= DISPLAY.files && (next || files.length < total) &&

Display limited to {DISPLAY.files} files. Open remaining files in GitHub

} +

Keys: F6 moves between the inbox, the tabs, the diff and the file list; [ and ] move between files.

Text patches may be incomplete. Each open file reports its patch coverage. Up to {DISPLAY.open} file bodies are open at once.

{treeWidth !== null && } diff --git a/apps/desktop/src/renderer/code-review/keys.ts b/apps/desktop/src/renderer/code-review/keys.ts new file mode 100644 index 00000000..e326cee6 --- /dev/null +++ b/apps/desktop/src/renderer/code-review/keys.ts @@ -0,0 +1,51 @@ +/** + * Keyboard movement between Code Review's areas (real-use benchmark, F6). Every control was reachable with + * Tab, but only through 34 to 124 presses between areas. F6 goes to the next area and Shift+F6 to the + * previous, as desktop apps use it; `[` and `]` go to the previous and next changed file. + */ +export const AREAS: readonly { within: string; focus: string }[] = [ + { within: '[data-testid="code-review-inbox"]', focus: '[data-testid="code-review-search"]' }, + { within: '[data-testid="code-review-tabbar"]', focus: '[role="tab"][aria-selected="true"]' }, + { within: '[data-testid="code-review-overview-body"]', focus: ":scope" }, + { within: '[data-testid="code-review-diff"]', focus: ":scope" }, + { within: '[data-testid="code-review-tree"]', focus: '[data-testid="cr-tree-file"][aria-current="true"], [data-testid="cr-tree-file"]' }, +]; + +/** The area to focus after `current` (an index into `present`, or -1 when focus is in none). */ +export function nextArea(present: number[], current: number, back: boolean): number | null { + if (!present.length) return null; + const at = present.indexOf(current); + if (at < 0) return back ? present[present.length - 1]! : present[0]!; + return present[(at + (back ? present.length - 1 : 1)) % present.length]!; +} + +/** The file `[` or `]` goes to from `selected`; it stops at either end rather than wrapping. */ +export function stepFile(paths: string[], selected: string | null, back: boolean): string | null { + if (!paths.length) return null; + const at = selected === null ? -1 : paths.indexOf(selected); + if (at < 0) return back ? paths[paths.length - 1]! : paths[0]!; + return paths[Math.max(0, Math.min(paths.length - 1, at + (back ? -1 : 1)))]!; +} + +/** True when a plain key press belongs to what is focused: text being typed, or a control that uses the key. */ +export function typing(target: EventTarget | null): boolean { + if (!(target instanceof HTMLElement)) return false; + return target.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName); +} + +/** Moves focus to the next or previous area that is on screen. Returns whether it moved. */ +export function cycleArea(root: HTMLElement, back: boolean): boolean { + const active = document.activeElement; + const targets: (HTMLElement | null)[] = []; + let current = -1; + AREAS.forEach((area, i) => { + const within = [...root.querySelectorAll(area.within)].find((el) => el.checkVisibility()) ?? null; + const target = within && (area.focus === ":scope" ? within : [...within.querySelectorAll(area.focus)].find((el) => el.checkVisibility()) ?? null); + targets.push(target); + if (within && active && within.contains(active)) current = i; + }); + const to = nextArea(targets.flatMap((el, i) => (el ? [i] : [])), current, back); + if (to === null) return false; + targets[to]!.focus(); + return document.activeElement === targets[to]; +} diff --git a/apps/desktop/test/code-review-workspace.test.ts b/apps/desktop/test/code-review-workspace.test.ts index 9c27a3e7..9bd9ae2e 100644 --- a/apps/desktop/test/code-review-workspace.test.ts +++ b/apps/desktop/test/code-review-workspace.test.ts @@ -302,3 +302,23 @@ test("fixture keys used here carry the account they were read under", () => { const k: PrKey = key(ACCOUNT_B, FIELD_GUIDE, 73); assert.equal(k.account, ACCOUNT_B.id); }); + +test("real use: F6 walks the areas on screen in order and [ ] step through files without wrapping", async () => { + const { nextArea, stepFile } = await import("../src/renderer/code-review/keys.js"); + // Areas: 0 inbox, 1 tabs, 2 overview, 3 diff, 4 file list. Only those on screen take part. + assert.equal(nextArea([0, 1, 2], -1, false), 0, "from outside, forward enters the first area"); + assert.equal(nextArea([0, 1, 2], -1, true), 2, "and backward the last"); + assert.equal(nextArea([0, 1, 3, 4], 1, false), 3, "an area that is not shown is skipped"); + assert.equal(nextArea([0, 1, 3, 4], 4, false), 0, "forward wraps to the first"); + assert.equal(nextArea([0, 1, 3, 4], 0, true), 4, "backward wraps to the last"); + assert.equal(nextArea([0, 1, 3, 4], 2, false), 0, "an area that has gone counts as outside"); + assert.equal(nextArea([], 0, false), null); + const paths = ["a.ts", "b.ts", "c.ts"]; + assert.equal(stepFile(paths, "a.ts", false), "b.ts"); + assert.equal(stepFile(paths, "c.ts", false), "c.ts", "the last file stays the last"); + assert.equal(stepFile(paths, "a.ts", true), "a.ts", "the first file stays the first"); + assert.equal(stepFile(paths, "c.ts", true), "b.ts"); + assert.equal(stepFile(paths, null, false), "a.ts"); + assert.equal(stepFile(paths, "filtered-out.ts", true), "c.ts"); + assert.equal(stepFile([], "a.ts", false), null); +}); From 39d2c539346035f25385b11507c473d82547bc16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Val=20Alexander=20=F0=9F=91=91?= Date: Thu, 12 Nov 2026 01:13:47 -0600 Subject: [PATCH 3/9] Open a pull request faster in Code Review Measured on 10 real pull requests, opening one took 2 to 5 s to its title and 6 to 7 s to its checks. Three causes are addressed: - Reads for an opened pull request go ahead of inbox lookups that have not started; a running read is never interrupted. - The overview uses resolve's read of the pull request once, within 2 s, under the same account, and only if nothing newer read it. - The merge base and the file page are read together between the two guarding reads. Checks and activity keep their order: a failed first read still costs GitHub nothing further. Co-Authored-By: Claude Fable 5.2 --- .../main/engine/code-review/read-service.ts | 124 ++++++++++++------ .../test/code-review-read-service.test.ts | 75 +++++++++++ 2 files changed, 162 insertions(+), 37 deletions(-) diff --git a/apps/desktop/src/main/engine/code-review/read-service.ts b/apps/desktop/src/main/engine/code-review/read-service.ts index ff474255..55c379e0 100644 --- a/apps/desktop/src/main/engine/code-review/read-service.ts +++ b/apps/desktop/src/main/engine/code-review/read-service.ts @@ -32,6 +32,8 @@ const JSON_TYPE: Accept = "application/vnd.github+json"; const RAW: Accept = "application/vnd.github.raw"; const KB = 1024, MB = 1024 * KB; const TIMEOUT_MS = 15_000, LONG_TIMEOUT_MS = 30_000; +/** How long `resolve`'s read of a pull request may stand in for the overview read that follows it. */ +const HANDOFF_MS = 2_000; const INBOX_PAGE = 30, PAGE = 100; /** GitHub's own limits: search serves 1,000 results, the files list 3,000 files. */ const SEARCH_CAP = 1000, FILES_CAP = 3000; @@ -116,18 +118,23 @@ class Lru { } } -/** At most `max` gh processes; a released slot passes straight to the next waiter. */ +/** + * At most `max` gh processes; a released slot passes straight to the next waiter. A read for the pull request + * the person opened goes ahead of the inbox's background lookups that have not started yet: it never + * interrupts one that has, and background reads still run whenever no such read is waiting. + */ class Slots { private active = 0; private readonly waiting: (() => void)[] = []; + private readonly background: (() => void)[] = []; constructor(private readonly max: number) {} - async run(work: () => Promise): Promise { + async run(work: () => Promise, background = false): Promise { if (this.active < this.max) this.active++; - else await new Promise((resolve) => this.waiting.push(resolve)); + else await new Promise((resolve) => (background ? this.background : this.waiting).push(resolve)); try { return await work(); } finally { - const next = this.waiting.shift(); + const next = this.waiting.shift() ?? this.background.shift(); if (next) next(); else this.active--; } @@ -135,7 +142,9 @@ class Slots { } /** `stamp`: gh's login state the account was confirmed under when the read began. */ -interface Context { account: string; generation: number; stamp: string | null; signal: AbortSignal; repositories: Set; resources: Set; deniedResources: Set; invalidated: boolean } +interface Context { account: string; generation: number; stamp: string | null; signal: AbortSignal; repositories: Set; resources: Set; deniedResources: Set; invalidated: boolean; + /** An inbox read: its gh calls wait behind those for an opened pull request. */ + background: boolean; } interface Fetched { body: Buffer; headers: Record } const enc = encodeURIComponent; @@ -165,6 +174,8 @@ export class CodeReviewService { private readonly names = new Lru(2048); private readonly hints = new Lru(4096); private readonly revisions = new Lru(1024); + /** The pull request `resolve` just read, for the one overview read the renderer sends next. Used once, then gone. */ + private readonly handoff = new Lru(8); private readonly kept = new Lru }>(256, 32 * MB, (entry) => size(entry.value) + [...entry.resources].reduce((bytes, key) => bytes + key.length * 2 + 32, 0)); constructor(options: CodeReviewOptions = {}) { @@ -215,7 +226,8 @@ export class CodeReviewService { return this.reply(request, null, this.unavailable(failure)); } if ("key" in request && request.key.account !== account.id) return this.reply(request, account.id, this.unavailable(new ReadFailure("signed-out", DETAIL.otherAccount))); - const context: Context = { account: account.id, generation: this.generation, stamp: this.identity!.stamp, signal: entry.controller.signal, repositories: new Set(), resources: new Set(), deniedResources: new Set(), invalidated: false }; + const context: Context = { account: account.id, generation: this.generation, stamp: this.identity!.stamp, signal: entry.controller.signal, repositories: new Set(), resources: new Set(), deniedResources: new Set(), invalidated: false, + background: request.op === "inbox" || request.op === "inbox-page" }; entry.generation = context.generation; this.contexts.add(context); try { @@ -407,7 +419,7 @@ export class CodeReviewService { private switchAccount(): void { this.generation++; for (const entry of this.inflight.values()) if (entry.generation !== null) entry.controller.abort(); - for (const store of [this.cache, this.repos, this.names, this.hints, this.revisions, this.kept]) store.clear(); + for (const store of [this.cache, this.repos, this.names, this.hints, this.revisions, this.kept, this.handoff]) store.clear(); this.blocked.clear(); this.searches = []; } @@ -451,7 +463,7 @@ export class CodeReviewService { const cached = this.cache.get(key); // A read cancelled while it waited for a slot never starts gh. const answer = await this.slots.run(() => context.signal.aborted ? Promise.resolve({ kind: "cancelled" }) - : this.transport({ endpoint, accept, etag: cached?.etag ?? null, maxBytes: options.maxBytes ?? MB, timeoutMs: options.timeoutMs ?? TIMEOUT_MS, signal: context.signal })); + : this.transport({ endpoint, accept, etag: cached?.etag ?? null, maxBytes: options.maxBytes ?? MB, timeoutMs: options.timeoutMs ?? TIMEOUT_MS, signal: context.signal }), context.background); if (answer.kind !== "http") { if ((answer.kind === "no-cli" || answer.kind === "signed-out") && context.generation === this.generation) this.forget(); throw this.transportFailure(answer.kind); @@ -558,6 +570,7 @@ export class CodeReviewService { }); this.revisions.delete(prId(repo.id, number)); this.hints.delete(prId(repo.id, number)); + this.handoff.delete(prId(repo.id, number)); // Commit and contents URLs are shared by PRs. Revalidate the repository's transport // representations next time, while preserving unrelated repositories' caches. this.cache.deleteWhere((key) => key.includes(`\u0000${repoPath(repo)}/`) || key.startsWith(`${JSON_TYPE}\u0000search/`)); @@ -565,6 +578,8 @@ export class CodeReviewService { private async pull(context: Context, repoId: string, number: number): Promise { const repo = this.repoFor({ account: context.account, host: "github.com", repoId, number }); + // Any newer read of this pull request supersedes what `resolve` left for the overview. + this.handoff.delete(prId(repoId, number)); let fetched: Fetched; try { fetched = await this.get(context, `${repoPath(repo)}/pulls/${number}`, { maxBytes: 4 * MB }); @@ -595,19 +610,40 @@ export class CodeReviewService { return found; } + /** + * Opening a link is two requests from the renderer, `resolve` then `overview`, and each read the same pull + * request a moment apart. The overview may use `resolve`'s read once, within HANDOFF_MS and under the same + * account generation; it then depends on that resource like any read of its own. Every other read, and + * every read that guards a revision, still asks GitHub itself. + */ + private handedOff(context: Context, key: PrKey): Pull | null { + const id = prId(key.repoId, key.number); + const entry = this.handoff.get(id); + if (!entry) return null; + this.handoff.delete(id); + const age = this.now() - entry.at; + if (entry.generation !== context.generation || entry.account !== context.account || age < 0 || age > HANDOFF_MS || context.invalidated) return null; + const path = repoPath(entry.pull.base); + context.repositories.add(path.toLowerCase()); + context.resources.add(`${JSON_TYPE}\u0000${path}/pulls/${key.number}`); + return entry.pull; + } + private async resolve(context: Context, input: string): Promise> { const locator = parsePrLocator(input); if (!locator) throw new ReadFailure("invalid", DETAIL.badLink); let repo = await this.repoByName(context, locator.owner, locator.repo); + let found: Pull; try { - await this.pull(context, repo.id, locator.number); + found = await this.pull(context, repo.id, locator.number); } catch (error) { if (!(error instanceof Moved)) throw error; // The name main knew now leads elsewhere: read it again for the repository it names today. repo = await this.repoByName(context, locator.owner, locator.repo); - await this.pull(context, repo.id, locator.number); + found = await this.pull(context, repo.id, locator.number); } const current = this.repos.get(repo.id) ?? repo; + if (context.generation === this.generation) this.handoff.set(prId(repo.id, locator.number), { pull: found, at: this.now(), generation: context.generation, account: context.account }); return { state: "ready", fetchedAt: this.at(), value: { locator: { host: "github.com", owner: current.owner, repo: current.name, number: locator.number }, key: { account: context.account, host: "github.com", repoId: repo.id, number: locator.number }, @@ -615,7 +651,7 @@ export class CodeReviewService { } private async overview(context: Context, key: PrKey): Promise> { - const pr = await this.pull(context, key.repoId, key.number); + const pr = this.handedOff(context, key) ?? await this.pull(context, key.repoId, key.number); return { state: "ready", fetchedAt: this.at(), value: { key, locator: { host: "github.com", owner: pr.base.owner, repo: pr.base.name, number: key.number }, revision: pr.revision, title: pr.title, body: pr.body, state: pr.state, author: pr.author, createdAt: pr.createdAt, updatedAt: pr.updatedAt, headRef: pr.headRef, @@ -757,29 +793,10 @@ export class CodeReviewService { let deploymentFailure: Unavailable | "capped" | null = null; if (pr) { activity.unshift({ kind: "opened", id: `pr-${pr.id}`, at: pr.createdAt, actor: pr.author }); - // A bounded current-head preview read, independent of arbitrary links in bot comments. - // Endpoint strings are built from main's repository and numeric provider IDs only. - try { - const base = repoPath(this.repoFor(key)); - const fetchedDeployments = await this.get(context, `${base}/deployments?sha=${pr.revision.headSha}&per_page=20&page=1`, { maxBytes: 2 * MB }); - const records: unknown = json(fetchedDeployments.body); - if (!Array.isArray(records)) throw new ReadFailure("failed", DETAIL.failed); - if (hasNext(fetchedDeployments.headers.link)) deploymentFailure = "capped"; - for (const record of records.slice(0, 20)) { - const mapped = deployment(record, null); - if (!mapped || mapped.commit !== pr.revision.headSha) { deploymentFailure = "failed"; continue; } - const deploymentId = mapped.id.slice("deployment-".length); - const statuses = json((await this.get(context, `${base}/deployments/${deploymentId}/statuses?per_page=1&page=1`, { maxBytes: MB })).body); - if (!Array.isArray(statuses)) throw new ReadFailure("failed", DETAIL.failed); - activity.push(deployment(record, statuses[0])!); - } - const after = await this.pull(context, key.repoId, key.number); - if (!sameRevision(pr.revision, after.revision)) deploymentFailure = "head-changed"; - } catch (error) { - const failure = this.failure(error); - if (failure.cancelled || failure.reason === "signed-out") throw error; - deploymentFailure = failure.reason; - } + // Asked only once the timeline has arrived: a failed timeline costs GitHub no further request. + const read = await this.deployments(context, key, pr); + activity.push(...read.records); + deploymentFailure = read.failure; } const more = hasNext(fetched.headers.link); const next = more && number < TIMELINE_PAGES ? `p${number + 1}` : null; @@ -792,6 +809,38 @@ export class CodeReviewService { return { state: "ready", value: activity, fetchedAt, coverage }; } + /** + * A bounded current-head preview read, independent of arbitrary links in bot comments. Endpoint strings are + * built from main's repository and numeric provider IDs only. A failure is reported, not thrown, unless the + * read was cancelled or the account is gone. + */ + private async deployments(context: Context, key: PrKey, pr: Pull): Promise<{ records: PrActivity[]; failure: Unavailable | "capped" | null }> { + const records: PrActivity[] = []; + let failure: Unavailable | "capped" | null = null; + try { + const base = repoPath(this.repoFor(key)); + const fetchedDeployments = await this.get(context, `${base}/deployments?sha=${pr.revision.headSha}&per_page=20&page=1`, { maxBytes: 2 * MB }); + const listed: unknown = json(fetchedDeployments.body); + if (!Array.isArray(listed)) throw new ReadFailure("failed", DETAIL.failed); + if (hasNext(fetchedDeployments.headers.link)) failure = "capped"; + for (const record of listed.slice(0, 20)) { + const mapped = deployment(record, null); + if (!mapped || mapped.commit !== pr.revision.headSha) { failure = "failed"; continue; } + const deploymentId = mapped.id.slice("deployment-".length); + const statuses = json((await this.get(context, `${base}/deployments/${deploymentId}/statuses?per_page=1&page=1`, { maxBytes: MB })).body); + if (!Array.isArray(statuses)) throw new ReadFailure("failed", DETAIL.failed); + records.push(deployment(record, statuses[0])!); + } + const after = await this.pull(context, key.repoId, key.number); + if (!sameRevision(pr.revision, after.revision)) failure = "head-changed"; + } catch (error) { + const caught = this.failure(error); + if (caught.cancelled || caught.reason === "signed-out") throw error; + failure = caught.reason; + } + return { records, failure }; + } + /** Every page of a check list, up to CHECK_PAGES. `limited`: main stopped at its own page limit, not at GitHub's last page. */ private async pages(context: Context, endpoint: string, list: string, map: (item: unknown) => T | null): Promise<{ items: T[]; total: number; complete: boolean; limited: boolean }> { const items: T[] = []; @@ -843,9 +892,10 @@ export class CodeReviewService { const number = page(cursor, FILES_CAP / PAGE); const before = await this.pull(context, key.repoId, key.number); if (!sameRevision(before.revision, revision)) throw new ReadFailure("head-changed", DETAIL.headChanged); - const diffBaseSha = await this.diffBase(context, key, revision); - const listed = json((await this.get(context, `${repoPath(this.repoFor(key))}/pulls/${key.number}/files?per_page=${PAGE}&page=${number}`, - { maxBytes: 24 * MB, timeoutMs: LONG_TIMEOUT_MS })).body); + // The merge base and the page of files do not depend on each other: both are read between the two reads of the PR. + const [diffBaseSha, filesPage] = await Promise.all([this.diffBase(context, key, revision), + this.get(context, `${repoPath(this.repoFor(key))}/pulls/${key.number}/files?per_page=${PAGE}&page=${number}`, { maxBytes: 24 * MB, timeoutMs: LONG_TIMEOUT_MS })]); + const listed = json(filesPage.body); if (!Array.isArray(listed)) throw new ReadFailure("failed", DETAIL.failed); const files = listed.map(changedFile); if (files.some((file) => file === null)) throw new ReadFailure("failed", DETAIL.failed); diff --git a/apps/desktop/test/code-review-read-service.test.ts b/apps/desktop/test/code-review-read-service.test.ts index b42e32d2..4b33c842 100644 --- a/apps/desktop/test/code-review-read-service.test.ts +++ b/apps/desktop/test/code-review-read-service.test.ts @@ -1087,3 +1087,78 @@ test("CR-4 denied deployment enrichment leaves timeline useful and explicitly pa assert.equal(reply.result.coverage.complete, false); assert(value(reply).some(r => r.kind === "opened")); }); + +// --- Real-use benchmark, 2026-11-12: opening a pull request was slow (F1, F2) -------------------- + +test("real use: a read for an opened pull request goes ahead of inbox reads that have not started", async () => { + const { github, read, prime } = setup({ concurrency: 1 }); + await prime(); + const releaseSearch = github.hold(/^search\/issues\?/); + const before = github.calls.length; + const inbox = read({ op: "inbox", query: "" }); + // One search holds the only slot; the other waits behind it. + await until(() => github.calls.length === before + 1); + const overview = read({ op: "overview", key: keyOf(LENDING, 73) }); + for (let i = 0; i < 50; i++) await new Promise((resolve) => setImmediate(resolve)); + assert.equal(github.calls.length, before + 1, "nothing interrupts the read that is running"); + releaseSearch(); + assert.equal(value<{ title: string }>(await overview).title, "Lend a hold to another branch"); + await inbox; + const order = github.calls.slice(before).map((c) => c.endpoint.replace(/\?.*/, "")); + assert.deepEqual(order.slice(0, 3), ["search/issues", "repos/example-org/lending/pulls/73", "search/issues"], "the pull request's read ran before the waiting inbox search"); + assert.equal(github.peak, 1, "still one gh at a time"); +}); + +test("real use: the overview uses resolve's read once, and only while nothing newer was read", async () => { + const { github, read, prime, tick } = setup(); + await prime(); + const key = keyOf(LENDING, 73); + const link = `https://github.com/${LENDING.full_name}/pull/73`; + const pulls = () => github.calls.filter((c) => c.endpoint === "repos/example-org/lending/pulls/73").length; + let seen = pulls(); + const step = async (request: Ask, cost: number, why: string) => { const reply = await read(request); assert.equal(pulls() - seen, cost, why); seen = pulls(); return reply; }; + + await step({ op: "resolve", input: link }, 1, "resolve reads the pull request"); + const overview = await step({ op: "overview", key }, 0, "the overview that follows uses that read"); + assert.equal(value<{ title: string }>(overview).title, "Lend a hold to another branch"); + await step({ op: "overview", key }, 1, "a second overview reads for itself: the hand-off is used once"); + + await step({ op: "resolve", input: link }, 1, "resolve"); + tick(2_001); + await step({ op: "overview", key }, 1, "an overview that comes late reads for itself"); + + const revision = revisionOf(github.pulls.get("7301#73")!); + await step({ op: "resolve", input: link }, 1, "resolve"); + await step({ op: "checks", key, revision }, 2, "checks is bracketed by its own two reads"); + await step({ op: "overview", key }, 1, "a newer read of the pull request supersedes the hand-off"); + + // A pull request that became unreadable after resolve is not shown from the hand-off. + await step({ op: "resolve", input: link }, 1, "resolve"); + github.overrides = [{ pattern: /repos\/example-org\/lending\/pulls\/73$/, answer: { kind: "http", status: 404, headers: {}, body: Buffer.from("{}") } }]; + assert.equal((await read({ op: "activity", key, cursor: null })).result.state, "unavailable"); + assert.equal((await read({ op: "overview", key })).result.state, "unavailable"); +}); + +test("real use: the merge base and the file page are read together between the two reads of the pull request", async () => { + const { github, read, prime } = setup(); + await prime(); + const key = keyOf(LENDING, 73); + const revision = revisionOf(github.pulls.get("7301#73")!); + const together = async (request: Ask, held: RegExp, other: RegExp, what: string) => { + const release = github.hold(held); + const before = github.calls.length; + const pending = read(request); + const started = () => github.calls.slice(before).some((c) => other.test(c.endpoint)); + for (let i = 0; i < 2000 && !started(); i++) await new Promise((resolve) => setImmediate(resolve)); + const ran = started(); + release(); + const reply = await pending; + github.gates = []; + assert.ok(ran, what); + assert.notEqual(reply.result.state, "unavailable", what); + const mine = github.calls.slice(before).map((c) => c.endpoint); + assert.equal(mine[0], "repos/example-org/lending/pulls/73", "the first read is the pull request"); + assert.equal(mine.at(-1), "repos/example-org/lending/pulls/73", "and so is the last"); + }; + await together({ op: "files", key, revision, cursor: null }, /\/compare\//, /\/pulls\/73\/files\?/, "the file page is asked for while the merge base is still being read"); +}); From f151380d0b987d372ea5707bbd1d9f46dbc7ed04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Val=20Alexander=20=F0=9F=91=91?= Date: Thu, 12 Nov 2026 03:16:28 -0600 Subject: [PATCH 4/9] Show comment HTML as readable text and the pull request number in inbox rows GitHub comment bodies often carry HTML (details, sup, img, links). The overview showed the tags as raw text. Known tags outside code are now dropped, and an image becomes "Image: alt". Inbox rows show repo #number. Co-Authored-By: Claude Fable 5.2 --- .../e2e/code-review-navigation.spec.ts | 6 ++ apps/desktop/e2e/code-review-overview.spec.ts | 8 ++- .../src/renderer/code-review/Inbox.tsx | 5 +- .../src/renderer/code-review/PrOverview.tsx | 5 +- .../src/renderer/code-review/remote-text.ts | 67 +++++++++++++++++++ .../test/code-review-render-bounds.test.ts | 24 +++++++ 6 files changed, 110 insertions(+), 5 deletions(-) create mode 100644 apps/desktop/src/renderer/code-review/remote-text.ts diff --git a/apps/desktop/e2e/code-review-navigation.spec.ts b/apps/desktop/e2e/code-review-navigation.spec.ts index a61d1fe4..fa0663e7 100644 --- a/apps/desktop/e2e/code-review-navigation.spec.ts +++ b/apps/desktop/e2e/code-review-navigation.spec.ts @@ -143,6 +143,12 @@ test("the rail opens the inbox, and a row opens its PR with the PR and Changes t await expect(inbox.getByRole("group", { name: "Authored by me" })).toBeVisible(); await expect(inbox.getByRole("group", { name: "Needs my review" })).toBeVisible(); await expect(row(page, "example-org", "lending", 73)).toContainText(R1.overview.title); + // The repository and number are drawn on the row, not kept for screen readers only: pull requests from many + // repositories share one list (real-use benchmark, F5). The owner completes the accessible name. + const rowId = row(page, "example-org", "lending", 73).getByTestId("code-review-row-id"); + await expect(rowId).toHaveText("lending #73"); + expect((await rowId.boundingBox())!.width, "drawn at its own width, not clipped to a pixel").toBeGreaterThan(40); + await expect(row(page, "example-org", "lending", 73)).toHaveAccessibleName(/example-org\/ ?lending #73 · /); await row(page, "example-org", "lending", 73).click(); await expect(row(page, "example-org", "lending", 73)).toHaveAttribute("aria-current", "true"); const prTab = tid(page, "code-review-tab-overview"); diff --git a/apps/desktop/e2e/code-review-overview.spec.ts b/apps/desktop/e2e/code-review-overview.spec.ts index 4987fb8f..00b3cd40 100644 --- a/apps/desktop/e2e/code-review-overview.spec.ts +++ b/apps/desktop/e2e/code-review-overview.spec.ts @@ -19,7 +19,7 @@ async function open(hostile = false, mode = "normal") { const failed = { state: "unavailable", reason: "offline", fetchedAt: NOW }; const overview = structuredClone(req.key?.number === 91 ? R4.overview : R1.overview); if (g.__overviewMode === "renamed") overview.locator = { ...overview.locator, owner: "current-org", repo: "lending-renamed" }; - if (hostile) overview.body = '# Hostile fixture\n\n\n\n[bad](javascript:alert(1))\n\n![remote](https://invalid.example/tracker.svg)\n\n[Safe](https://example.com/path)'; + if (hostile) overview.body = '# Hostile fixture\n\n\n\n[bad](javascript:alert(1))\n\n![remote](https://invalid.example/tracker.svg)\n\n[Safe](https://example.com/path)\n\nMedium severity Contrast gate\n\nvisible words and `kept in code`'; let result: unknown = failed; if (req.op === "connection") result = R1.connection; if (req.op === "inbox") result = R1.inbox; @@ -136,6 +136,12 @@ test("hostile Markdown is inert and narrow content remains reachable", async () await expect(description).toContainText("", path: "src/holds/move.ts", line: 41, side: "RIGHT" }, + { id: 802, user: who, created_at: "2026-10-18T20:32:00Z", body: "It does; see the closure test.", path: "src/holds/move.ts", line: 41, side: "RIGHT", in_reply_to_id: 801 }, + { id: 803, user: who, created_at: "2026-10-18T20:33:00Z", body: "This helper is gone now.", path: "src/holds/queue.ts", line: null, side: "LEFT" }, + ]; + h = await launchWithGh(world); + const { page } = h; + await tid(page, "rail-code-review").click(); + await prRow(page, "example-org/lending#73").click(); + const activity = tid(page, "cr-activity"); + const item = (id: number) => activity.locator(`[data-activity-id="line-comment:${id}"]`); + await expect(item(801)).toContainText("commented on src/holds/move.ts · line 41"); + await expect(item(801)).toContainText("Should this keep the position when the branch is closed?"); + await expect(item(802)).toContainText("replied on src/holds/move.ts · line 41"); + await expect(item(803)).toContainText("commented on src/holds/queue.ts · line no longer in the diff"); + await page.getByLabel("Activity filter").selectOption("comment"); + await expect(activity.locator('[data-activity-id^="line-comment:"]')).toHaveCount(3); + await expect(activity.locator('[data-activity-id^="commit:"]')).toHaveCount(0); + expect(await page.evaluate(() => (window as unknown as { __pwned?: boolean }).__pwned)).toBeUndefined(); + expect(h.calls().filter((c) => c.startsWith("repos/example-org/lending/pulls/73/comments"))).toEqual(["repos/example-org/lending/pulls/73/comments?per_page=100&page=1"]); + expect(h.calls().filter((c) => !READ_ENDPOINT.test(c) && !c.startsWith("repos/example-org/lending/deployments?"))).toEqual([]); +}); diff --git a/apps/desktop/e2e/code-review-support.ts b/apps/desktop/e2e/code-review-support.ts index 03ae5039..3d9bb5cd 100644 --- a/apps/desktop/e2e/code-review-support.ts +++ b/apps/desktop/e2e/code-review-support.ts @@ -120,7 +120,7 @@ export const prRow = (p: Page, slug: string) => p.locator(`[data-testid="code-re export const settle = (p: Page) => p.evaluate(() => window.modex!.invoke("code-review:read", { op: "connection", requestId: `settle-${Date.now()}` })); /** Every endpoint the read service may ask for (docs/design/code-review.md, Read operations). */ -export const READ_ENDPOINT = /^(user|search\/issues\?[^/]+|repos\/[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+(\/(pulls(\/\d+(\/files)?)?|compare\/[0-9a-f]{40}\.\.\.[0-9a-f]{40}|issues\/\d+\/timeline|commits\/[0-9a-f]{40}\/(check-runs|status)|contents\/[^?]+))?(\?[^/]*)?)$/; +export const READ_ENDPOINT = /^(user|search\/issues\?[^/]+|repos\/[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+(\/(pulls(\/\d+(\/(files|comments))?)?|compare\/[0-9a-f]{40}\.\.\.[0-9a-f]{40}|issues\/\d+\/timeline|commits\/[0-9a-f]{40}\/(check-runs|status)|contents\/[^?]+))?(\?[^/]*)?)$/; /** * resizeWindow, but within the display. These launches can't set MODEX_E2E (it disables the read service), so diff --git a/apps/desktop/src/main/engine/code-review/github.ts b/apps/desktop/src/main/engine/code-review/github.ts index 4cb420f5..5bc46855 100644 --- a/apps/desktop/src/main/engine/code-review/github.ts +++ b/apps/desktop/src/main/engine/code-review/github.ts @@ -191,6 +191,16 @@ export function hasNext(header: string | undefined): boolean { return typeof header === "string" && /<[^>]+>;\s*rel="next"/.test(header); } +/** One comment on a line of the diff, from `pulls/{n}/comments`. Null when malformed. */ +export function lineComment(value: unknown): Extract | null { + const item = object(value); + const commentId = id(item?.id), at = time(item?.created_at), who = actor(item?.user); + if (!item || !commentId || !at || !who || typeof item.path !== "string" || !item.path || item.path.length > 4096) return null; + const line = count(item.line) || null; + return { kind: "line-comment", id: commentId, at, actor: who, body: text(item.body, 262_144), path: item.path, line, + side: item.side === "LEFT" ? "LEFT" : "RIGHT", replyTo: id(item.in_reply_to_id) }; +} + /** Provider deployment + its latest status; a comment URL never enters this mapping. */ export function deployment(value: unknown, latest: unknown): Extract | null { const record = object(value), status = object(latest); diff --git a/apps/desktop/src/main/engine/code-review/read-service.ts b/apps/desktop/src/main/engine/code-review/read-service.ts index 55c379e0..804e13d7 100644 --- a/apps/desktop/src/main/engine/code-review/read-service.ts +++ b/apps/desktop/src/main/engine/code-review/read-service.ts @@ -4,7 +4,7 @@ import { type PrStack, type PrActivity, type PrCheck, type PrContext, type PrFiles, type PrKey, type PrOverview, type PrRevision, type PrSummary, type ReadResult, type ResolvedPr, type Unavailable, } from "../../../shared/code-review.js"; import { ghHostsStamp, ghTransport, type GhAnswer, type GhCall, type GhTransport } from "./gh.js"; -import { deployment, changedFile, checkRun, commitStatus, hasNext, json, pull, repository, searchRow, timeline, type Pull, type Repository } from "./github.js"; +import { deployment, lineComment, changedFile, checkRun, commitStatus, hasNext, json, pull, repository, searchRow, timeline, type Pull, type Repository } from "./github.js"; /** * Main's Code Review reads (#321): narrow GETs through the person's `gh` login, each bound to the @@ -794,9 +794,10 @@ export class CodeReviewService { if (pr) { activity.unshift({ kind: "opened", id: `pr-${pr.id}`, at: pr.createdAt, actor: pr.author }); // Asked only once the timeline has arrived: a failed timeline costs GitHub no further request. - const read = await this.deployments(context, key, pr); - activity.push(...read.records); - deploymentFailure = read.failure; + // Line comments are not in the timeline; they are their own list. Both reads run together. + const [read, comments] = await Promise.all([this.deployments(context, key, pr), this.lineComments(context, key)]); + activity.push(...read.records, ...comments.records); + deploymentFailure = read.failure ?? comments.failure; } const more = hasNext(fetched.headers.link); const next = more && number < TIMELINE_PAGES ? `p${number + 1}` : null; @@ -809,6 +810,30 @@ export class CodeReviewService { return { state: "ready", value: activity, fetchedAt, coverage }; } + /** + * The first page of comments on lines of the diff (100, oldest first). A failure is reported, not thrown, + * unless the read was cancelled or the account is gone; more than one page is reported as capped. + */ + private async lineComments(context: Context, key: PrKey): Promise<{ records: PrActivity[]; failure: Unavailable | "capped" | null }> { + const records: PrActivity[] = []; + let failure: Unavailable | "capped" | null = null; + try { + const fetched = await this.get(context, `${repoPath(this.repoFor(key))}/pulls/${key.number}/comments?per_page=${PAGE}&page=1`, { maxBytes: 8 * MB }); + const listed: unknown = json(fetched.body); + if (!Array.isArray(listed)) throw new ReadFailure("failed", DETAIL.failed); + if (hasNext(fetched.headers.link)) failure = "capped"; + for (const item of listed.slice(0, PAGE)) { + const mapped = lineComment(item); + if (mapped) records.push(mapped); else failure = "failed"; + } + } catch (error) { + const caught = this.failure(error); + if (caught.cancelled || caught.reason === "signed-out") throw error; + failure = caught.reason; + } + return { records, failure }; + } + /** * A bounded current-head preview read, independent of arbitrary links in bot comments. Endpoint strings are * built from main's repository and numeric provider IDs only. A failure is reported, not thrown, unless the diff --git a/apps/desktop/src/renderer/code-review/PrOverview.tsx b/apps/desktop/src/renderer/code-review/PrOverview.tsx index e05c1b87..568425c7 100644 --- a/apps/desktop/src/renderer/code-review/PrOverview.tsx +++ b/apps/desktop/src/renderer/code-review/PrOverview.tsx @@ -67,7 +67,7 @@ export function PrOverview({ pr, caps, retry, onChanges, onPage, busy, actions = } const activity = activityPages(pages); const pageFailed = pages.at(-1)?.state === "unavailable"; - const rows = activity.rows.filter(row => filter === "all" || row.kind === filter); + const rows = activity.rows.filter(row => filter === "all" || row.kind === filter || (filter === "comment" && row.kind === "line-comment")); const grouped: PrActivity[][] = []; for (const row of rows) { const last = grouped.at(-1); @@ -110,8 +110,9 @@ export function PrOverview({ pr, caps, retry, onChanges, onPage, busy, actions = } function Activity({ row, locator, currentHead, onAsk }: { row: PrActivity; locator?: PrLocator; currentHead?: string; onAsk?: (text: string) => void }) { return
-
{row.kind === "comment" && locator && }{row.kind === "deployment" ? row.environment : row.kind === "commit" ? row.author?.login ?? "Git author" : row.actor?.login ?? "GitHub"}{row.kind === "commit" ? "committed" : row.kind === "opened" ? "opened this pull request" : row.kind === "review" ? `reviewed · ${row.verdict}` : row.kind === "event" ? row.event : row.kind === "deployment" ? `provider deployment · ${row.status}` : "issue comment"}
+
{row.kind === "comment" && locator && }{row.kind === "deployment" ? row.environment : row.kind === "commit" ? row.author?.login ?? "Git author" : row.actor?.login ?? "GitHub"}{row.kind === "commit" ? "committed" : row.kind === "opened" ? "opened this pull request" : row.kind === "line-comment" ? `${row.replyTo ? "replied" : "commented"} on ${row.path}${row.line ? ` · line ${row.line}${row.side === "LEFT" ? " (before)" : ""}` : " · line no longer in the diff"}` : row.kind === "review" ? `reviewed · ${row.verdict}` : row.kind === "event" ? row.event : row.kind === "deployment" ? `provider deployment · ${row.status}` : "issue comment"}
{row.kind === "commit" &&

{row.sha.slice(0, 8)} {row.headline}

} + {row.kind === "line-comment" && <>

Comment on a line · Whether its thread is resolved is not shown.

} {(row.kind === "comment" || row.kind === "review") && <>

{row.kind === "comment" ? "Comment content · Links and status claims are supplied by the commenter, not verified deployment evidence." : `Submitted review · revision ${row.commit?.slice(0, 8) ?? "unknown"}`}

} {row.kind === "deployment" &&

Provider record · revision {row.commit.slice(0, 8)}{currentHead && row.commit !== currentHead ? " · Old revision" : ""} · Open deployment

}
; diff --git a/apps/desktop/src/shared/code-review.ts b/apps/desktop/src/shared/code-review.ts index aa9631a2..7bcd4983 100644 --- a/apps/desktop/src/shared/code-review.ts +++ b/apps/desktop/src/shared/code-review.ts @@ -115,6 +115,8 @@ export type PrActivity = | { kind: "commit"; id: string; at: string; sha: string; headline: string; author: PrActor | null } | { kind: "opened"; id: string; at: string; actor: PrActor } | { kind: "comment"; id: string; at: string; actor: PrActor; /** Untrusted Markdown, like `PrOverview.body`. */ body: string } + /** A comment on a line of the diff (GitHub's review comment). `line` is null once the line is no longer in the diff. `replyTo` is the comment it answers. Whether its thread is resolved is not read. */ + | { kind: "line-comment"; id: string; at: string; actor: PrActor; body: string; path: string; line: number | null; side: "LEFT" | "RIGHT"; replyTo: string | null } | { kind: "review"; id: string; at: string; actor: PrActor; verdict: "approved" | "changes-requested" | "commented" | "dismissed"; body: string; commit: string | null } | { kind: "event"; id: string; at: string; actor: PrActor | null; event: string } | { kind: "deployment"; id: string; at: string; environment: string; status: "success" | "pending" | "failure" | "inactive" | "unknown"; url: string | null; commit: string }; diff --git a/apps/desktop/test/code-review-read-service.test.ts b/apps/desktop/test/code-review-read-service.test.ts index 4b33c842..02378fbc 100644 --- a/apps/desktop/test/code-review-read-service.test.ts +++ b/apps/desktop/test/code-review-read-service.test.ts @@ -53,6 +53,7 @@ class FakeGitHub { ["7301#74", pull(LENDING, 74, { base: "topic-73", baseSha: sha("c"), head: sha("e") })], ]); timeline = new Map(); + lineComments = new Map(); files = new Map(); checkRuns = new Map(); statuses = new Map(); @@ -146,6 +147,10 @@ class FakeGitHub { } const id = `${repo.id}#${parts[4]}`; if (parts[3] === "pulls" && parts.length === 5) return this.pulls.has(id) ? this.json(call, this.pulls.get(id)) : this.missing(); + if (parts[3] === "pulls" && parts[5] === "comments") { + const { slice, link } = this.page(this.lineComments.get(id) ?? [], query, path!); + return this.json(call, slice, link); + } if (parts[3] === "pulls" && parts[5] === "files") { const { slice, link } = this.page(this.files.get(id) ?? [], query, path!); return this.json(call, slice, link); @@ -1162,3 +1167,56 @@ test("real use: the merge base and the file page are read together between the t }; await together({ op: "files", key, revision, cursor: null }, /\/compare\//, /\/pulls\/73\/files\?/, "the file page is asked for while the merge base is still being read"); }); + +// --- Real-use benchmark, 2026-11-12: comments on lines of the diff were not shown (F3) ----------- + +const lineCommentRow = (id: number, extra: Record = {}) => ({ id, user: { id: 5, login: "bea-fixture", type: "User" }, created_at: "2026-10-19T09:00:00Z", + body: "Should this be `>=`?", path: "policy/schema.ts", line: 41, side: "RIGHT", ...extra }); + +test("real use: comments on lines of the diff arrive with the first activity page, with their file, line and reply", async () => { + const { github, read, prime } = setup(); + await prime(); + github.lineComments.set("7301#73", [lineCommentRow(801), lineCommentRow(802, { in_reply_to_id: 801, body: "Yes.", created_at: "2026-10-19T09:05:00Z" }), lineCommentRow(803, { line: null, side: "LEFT" })]); + const reply = await read({ op: "activity", key: keyOf(LENDING, 73), cursor: null }); + assert.equal(reply.result.state, "ready"); + const rows = value(reply).filter(r => r.kind === "line-comment"); + assert.deepEqual(rows.map(r => r.kind === "line-comment" && [r.id, r.path, r.line, r.side, r.replyTo, r.body, r.actor.login]), [ + ["801", "policy/schema.ts", 41, "RIGHT", null, "Should this be `>=`?", "bea-fixture"], + ["802", "policy/schema.ts", 41, "RIGHT", "801", "Yes.", "bea-fixture"], + ["803", "policy/schema.ts", null, "LEFT", null, "Should this be `>=`?", "bea-fixture"], + ]); + const asked = github.calls.filter(c => c.endpoint.includes("/pulls/73/comments")); + assert.deepEqual(asked.map(c => c.endpoint.split("/pulls/")[1]), ["73/comments?per_page=100&page=1"]); +}); + +test("real use: a refused or malformed line-comment read leaves the timeline usable and says the page is partial", async () => { + const { github, read, prime } = setup(); + await prime(); + github.overrides.push({ pattern: /\/pulls\/73\/comments\?/, answer: { kind: "http", status: 403, headers: {}, body: Buffer.from("{}") } }); + const refused = await read({ op: "activity", key: keyOf(LENDING, 73), cursor: null }); + assert(refused.result.state === "partial"); + assert.equal(refused.result.reason, "denied"); + assert.equal(refused.result.coverage.complete, false); + assert(value(refused).some(r => r.kind === "opened")); + + github.overrides.length = 0; + github.lineComments.set("7301#73", [lineCommentRow(801), { id: 802, body: "no author, file or date" }]); + const malformed = await read({ op: "activity", key: keyOf(LENDING, 73), cursor: null }); + assert(malformed.result.state === "partial"); + assert.equal(malformed.result.reason, "failed"); + assert.deepEqual(value(malformed).filter(r => r.kind === "line-comment").map(r => r.id), ["801"]); +}); + +test("real use: more than one page of line comments is reported as capped, and later activity pages do not ask again", async () => { + const { github, read, prime } = setup(); + await prime(); + github.lineComments.set("7301#73", Array.from({ length: 101 }, (_, i) => lineCommentRow(1000 + i))); + const first = await read({ op: "activity", key: keyOf(LENDING, 73), cursor: null }); + assert(first.result.state === "partial"); + assert.equal(first.result.reason, "capped"); + assert.equal(value(first).filter(r => r.kind === "line-comment").length, 100); + github.timeline.set("7301#73", Array.from({ length: 150 }, (_, i) => ({ event: "labeled", id: 5000 + i, created_at: "2026-10-19T10:00:00Z", actor: { id: 5, login: "bea-fixture", type: "User" } }))); + const before = github.calls.filter(c => c.endpoint.includes("/pulls/73/comments")).length; + await read({ op: "activity", key: keyOf(LENDING, 73), cursor: "p2" }); + assert.equal(github.calls.filter(c => c.endpoint.includes("/pulls/73/comments")).length, before); +}); diff --git a/apps/desktop/test/fixtures/code-review-gh-world.ts b/apps/desktop/test/fixtures/code-review-gh-world.ts index 3d9d8ab1..23cf60c8 100644 --- a/apps/desktop/test/fixtures/code-review-gh-world.ts +++ b/apps/desktop/test/fixtures/code-review-gh-world.ts @@ -138,6 +138,8 @@ if (method === "PATCH" || (method === "POST" && (route === "graphql" || /\/reque && value && value.base && value.head && value.base.sha === comparison[2] && value.head.sha === comparison[3]); if (declared) found = { base_commit: { sha: comparison[2] }, merge_base_commit: { sha: comparison[2] } }; } + // A declared pull request with no line comments listed has none. + if (found === undefined && /\/pulls\/\d+\/comments$/.test(route) && world.routes[route.replace(/\/comments$/, "")]) found = []; if (found && /\/pulls\/\d+$/.test(route)) found = changed(route, found); if (found && /\/pulls\/\d+$/.test(route) && mergedAs(route)) { found = { ...found, state: "closed", merged: true, merged_at: "2026-10-18T20:40:00Z", merged_by: { ...world.user, type: "User" }, diff --git a/docs/design/code-review.md b/docs/design/code-review.md index e1515479..3ff54981 100644 --- a/docs/design/code-review.md +++ b/docs/design/code-review.md @@ -171,7 +171,7 @@ Every call is `gh api --method GET` with validated, encoded segment | `inbox-page` | `group`, `query`, `cursor` | `PrSummary[]` | the same search, next page; GitHub serves 1,000 results, so `p34` is the last | | `resolve` | `input` (a pasted link) | `{ locator, key }` | `parsePrLocator`, then `repos/{owner}/{repo}` for the stable id and `pulls/{n}` to check the PR exists | | `overview` | `key` | `PrOverview` with its `revision` | `repos/{owner}/{repo}/pulls/{n}` | -| `activity` | `key`, `cursor` | `PrActivity[]` | `repos/{owner}/{repo}/issues/{n}/timeline`, 100 a page; the first page adds the opening from `pulls/{n}` and up to 20 current-head provider deployments from `deployments?sha={headSha}`, each with its latest status | +| `activity` | `key`, `cursor` | `PrActivity[]` | `repos/{owner}/{repo}/issues/{n}/timeline`, 100 a page; the first page adds the opening from `pulls/{n}` up to 20 current-head provider deployments from `deployments?sha={headSha}`, each with its latest status, and the first 100 comments on lines of the diff from `pulls/{n}/comments` (more is reported as capped). Whether a comment's thread is resolved is not read: GitHub gives that only over GraphQL | | `checks` | `key`, `revision` | `PrCheck[]` for that head | `commits/{headSha}/check-runs` and `commits/{headSha}/status`, 100 a page, up to 10 pages each; `reporter` is a run's `app.slug` or a status's `creator.login` | | `stack` | `key` | `PrStack`, labelled `inferred` | CR-4 reads up to 1,000 open PRs with `repos/{owner}/{repo}/pulls?state=open`; equal base/head branch refs within the same stable repository form the inferred relationship. Branching, cycles, a capped read, forks or an unresolved root yield unavailable ordering. | | `files` | `key`, `revision`, `cursor` | `PrFiles` | `repos/{owner}/{repo}/pulls/{n}/files`, 100 a page (GitHub stops at 3,000 files, so `p30` is the last) | diff --git a/docs/status.md b/docs/status.md index 66db75a9..e88fd433 100644 --- a/docs/status.md +++ b/docs/status.md @@ -145,7 +145,7 @@ before relying on a tick. - **Companion command recovery (COMP-CMD-2).** #497 is on main as `85143ee`; its tree exactly matches reviewed `d3d2eee`. It keeps timed-out command reads in the picker with explicit retry, retained search/drafts and keyboard Done actions. The required protected queue check passed 505 desktop cases (four skips) and seven site cases; iPhone was skipped for that merge-group event. The independent three-cycle context regression passes without #496's reset, so #496 is closed as superseded; its branch and checkout are preserved. Two fresh-install closeout integration suites each passed 44 executions (43 ordinary passes and one intentional expected failure, zero actual failures/skips), with source hashes unchanged. Human and physical-device acceptance on #276/#281 remains open. [Current integration qualification](reviews/2026-11-11-native-closeout-delivery.md); [historical producer review](reviews/2026-11-08-companion-recovery-pr.md). - **v0.4.2 release.** #492 (`4297235`) prepared it with Code Review hidden by default. Its tag exists, and the GitHub release remains a draft; it is not published. [Review](reviews/2026-11-03-v0.4.2-release-review.md). -- **Code Review acceptance** (#319). Every slice's code is on `main` (design and history: [design page](design/code-review.md), [CR-8 matrix](reviews/2026-11-01-cr8-acceptance-matrix.md)). Built apps hide it by default (#492); Settings → General can show it. #490 added that setting, C76 accessibility coverage, performance budgets as gates and the CR-7 sign-out and CF-3 question-card regressions; it also carries #481, #484, #485 and #491. No live provider run, live GitHub write, VoiceOver pass or reference comparison has happened. Those are listed in [Val's one session](reviews/2026-11-02-v0.5.0-val-session.md), which predates the 2026-11-04 answers and still asks for them. On 2026-11-04 Val answered decisions 1, 5, 6 and 7 ([record](design/code-review.md#open-decisions)): logins only, a local revision-bound Viewed toggle, the new-tab control removed, no access indicator; C58 and C59 effort are approved omissions; the reference comparison is retired for a benchmark on real pull requests; real reads and one CR-6 smoke may run on this repository. The Viewed toggle is built and C07 is removed. A benchmark on ten real pull requests of this repository ranked the friction; its first fixes are in: a pull request opens in about two seconds instead of four, comment HTML reads as text, inbox rows show the pull request number, and F6 and `[` / `]` move between areas and files. Review comments made on diff lines are still not shown. The benchmark has not been re-run on the fixed build. +- **Code Review acceptance** (#319). Every slice's code is on `main` (design and history: [design page](design/code-review.md), [CR-8 matrix](reviews/2026-11-01-cr8-acceptance-matrix.md)). Built apps hide it by default (#492); Settings → General can show it. #490 added that setting, C76 accessibility coverage, performance budgets as gates and the CR-7 sign-out and CF-3 question-card regressions; it also carries #481, #484, #485 and #491. No live provider run, live GitHub write, VoiceOver pass or reference comparison has happened. Those are listed in [Val's one session](reviews/2026-11-02-v0.5.0-val-session.md), which predates the 2026-11-04 answers and still asks for them. On 2026-11-04 Val answered decisions 1, 5, 6 and 7 ([record](design/code-review.md#open-decisions)): logins only, a local revision-bound Viewed toggle, the new-tab control removed, no access indicator; C58 and C59 effort are approved omissions; the reference comparison is retired for a benchmark on real pull requests; real reads and one CR-6 smoke may run on this repository. The Viewed toggle is built and C07 is removed. A benchmark on ten real pull requests of this repository ranked the friction; its first fixes are in: a pull request opens in about two seconds instead of four, comment HTML reads as text, inbox rows show the pull request number, and F6 and `[` / `]` move between areas and files. Comments made on diff lines are listed in Activity with their file and line (the first 100; whether a thread is resolved is not read, and they are not yet shown beside the line in Changes). The benchmark has not been re-run on the fixed build. - **Conversation fidelity** ([tracker #273](https://github.com/TypeSafeAI/modex/issues/273)). CF-3, CF-7 and CF-8 stay open; their code is on `main`. The #489 question-focus repair and Approve/Deny/Stop/withdrawal draft coverage are integrated by #495. The human gates are under [Open acceptance gates](#open-acceptance-gates). - **Protected delivery diagnostics** (#498). Earlier #497 queue shutdown failures and #498's hosted iOS 26.4.1 post-relaunch TLS stall remain unexplained. The closeout candidate adds bounded test-only native stack sampling and DEBUG-only opt-in TLS callback phases, preserving close outcomes, certificate APIs, exact pins, redirects and deadlines. Fresh build/typecheck, 2,412 units (35 skips), 508 desktop E2E cases (11 explicit skips), seven site cases, 65 native units and the fresh 44-execution traced paired suite passed. Actual iOS logs show five callbacks across two app processes; macOS security controls preserve matching/mismatched-pin and redirect behavior, with default/Release logging silent. The additional canonical export regression passed within eight token-record cases after compilation. The published `be5a4c8` head subsequently passed required macOS, iPhone and Linux/Windows checks; those checks do not validate the later private-workspace trust repair. These remain candidate results, not a TLS/shutdown repair or protected delivery. [Current evidence and limits](reviews/2026-11-11-native-closeout-delivery.md); [shutdown observer](reviews/2026-11-11-electron-shutdown-diagnostics.md). - **Private local workspace continuation** (#379/#380, #498). A network-denied real Codex 0.167.0/Ollama 0.40.16 read reproduced refusal on the next turn after the child persisted its own workspace trust mark. The strict repair admits only that one main-bound private workspace entry, keeps other settings and managed/project overrides refused, and checks captured realpaths before setup and after configuration reads. These spot checks do not establish race-free filesystem identity. All 45 focused tests, root build/typechecks and full units (2,420 passes, 35 skips) passed on the frozen candidate; full E2E passed with 508 desktop passes, 11 explicit skips and seven site passes, with no failures or observed retries. The unchanged 500 ms cold-open gate measured 73.2 ms; all four affected real-model Electron lifecycle cases separately passed with zero skips or retries. Native continuation and completed compaction were observed, but independent session audit found two repeated reads after compaction, so action-safe compaction and production admission remain unqualified. [New qualification and limits](reviews/2026-11-11-native-private-workspace-trust.md). From 4ed8ba0453204a092b801983fe1b920d02a0217d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Val=20Alexander=20=F0=9F=91=91?= Date: Thu, 12 Nov 2026 10:01:14 -0600 Subject: [PATCH 8/9] Code Review: remove fallback buttons that could never act The overview always receives the write service, so the plain Comment, Edit pull request and Request reviewers fallbacks ("This action isn't connected yet.") were unreachable. The service is now required. Co-Authored-By: Claude Fable 5.2 --- .../src/renderer/code-review/PrOverview.tsx | 17 +++++------------ .../desktop/src/renderer/code-review/PrPane.tsx | 2 +- 2 files changed, 6 insertions(+), 13 deletions(-) diff --git a/apps/desktop/src/renderer/code-review/PrOverview.tsx b/apps/desktop/src/renderer/code-review/PrOverview.tsx index 568425c7..d8334daa 100644 --- a/apps/desktop/src/renderer/code-review/PrOverview.tsx +++ b/apps/desktop/src/renderer/code-review/PrOverview.tsx @@ -1,5 +1,5 @@ import { useState, useRef, useLayoutEffect, type ReactNode } from "react"; -import { prKeyId, summarizeChecks, type Capabilities, type Capability, type PrActivity, type PrLocator, type ReadResult } from "../../shared/code-review.js"; +import { prKeyId, summarizeChecks, type Capabilities, type PrActivity, type PrLocator, type ReadResult } from "../../shared/code-review.js"; import { activityPages, externalDestination, stackOrder } from "../../shared/code-review-overview.js"; import { bridge } from "../bridge"; import { Menu, MenuItem } from "../components/ui/Menu"; @@ -15,12 +15,6 @@ import { EditPullRequest, RequestReviewers } from "./PrActions"; import type { Agent } from "./agent.js"; import { AgentReview } from "./AgentReview"; -/** Explicit action boundary for CR-7. No draft or successful submission is invented here. */ -export interface OverviewActions { edit?: () => void; requestReviewers?: () => void; comment?: () => void } -function Action({ label, capability, action }: { label: string; capability: Capability; action?: () => void }) { - const available = capability.available && !!action; - return ; -} function Evidence({ result, label, retry }: { result: ReadResult | undefined; label: string; retry: () => void }) { if (!result) return

Loading {label}…

; if (result.state === "unavailable") return ; @@ -44,7 +38,7 @@ function usePosition(id: string) { }, [id]); return ref; } -export function PrOverview({ pr, caps, retry, onChanges, onPage, busy, actions = {}, writes, agent }: { pr: OpenPr; caps: Capabilities; retry: () => void; onChanges: () => void; onPage: (cursor: string | null) => void; busy: ReadonlySet; actions?: OverviewActions; writes?: Writes; agent?: Agent }) { +export function PrOverview({ pr, caps, retry, onChanges, onPage, busy, writes, agent }: { pr: OpenPr; caps: Capabilities; retry: () => void; onChanges: () => void; onPage: (cursor: string | null) => void; busy: ReadonlySet; writes: Writes; agent?: Agent }) { const main = usePosition(`${prKeyId(pr.key)}:content`); const sidebar = usePosition(`${prKeyId(pr.key)}:details`); const read = pr.overview; @@ -83,7 +77,7 @@ export function PrOverview({ pr, caps, retry, onChanges, onPage, busy, actions =

{overview.title}

-
{overview.author.login} opened
{overview.headRepo ? `${overview.headRepo}:` : ""}{overview.headRef} → {overview.revision.baseRef}{writes ? : }
+
{overview.author.login} opened
{overview.headRepo ? `${overview.headRepo}:` : ""}{overview.headRef} → {overview.revision.baseRef}
{agent && writes && } @@ -95,14 +89,13 @@ export function PrOverview({ pr, caps, retry, onChanges, onPage, busy, actions = {pr.activityRefreshing &&

Refreshing activity · Earlier pages remain provisional.

} {activity.complete && !pr.activityRefreshing ?

{activity.rows.length ? "All activity loaded" : "No activity"}{filter !== "all" && rows.length === 0 ? " · No matching activity" : ""}

:

{activity.rows.length} activity items loaded · More activity may be missing.

} {activity.next && } - {writes ? - :

Comment on this pull request

{!caps.comment.available && caps.comment.reason}

} +
diff --git a/apps/desktop/src/renderer/code-review/PrPane.tsx b/apps/desktop/src/renderer/code-review/PrPane.tsx index 66ea0cb9..47a09a79 100644 --- a/apps/desktop/src/renderer/code-review/PrPane.tsx +++ b/apps/desktop/src/renderer/code-review/PrPane.tsx @@ -34,7 +34,7 @@ interface Props { contextBusy: ReadonlySet; onTreeResize: (width: number) => void; onTreeReset: () => void; - writes?: Writes; + writes: Writes; agent?: Agent; } From 35b52b07c8932aa3e82cef2d80378e06bafd9afc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Val=20Alexander=20=F0=9F=91=91?= Date: Thu, 12 Nov 2026 12:05:11 -0600 Subject: [PATCH 9/9] test(code-review): wait for the file focus before typing in the filter The bracket key focuses its file on the next animation frame. The keyboard test went on to focus the filter and type at once, so on a slow runner that focus arrived mid-typing and the filter kept only the first character. This failed the merge queue run for #506. Co-Authored-By: Claude Fable 5.2 --- apps/desktop/e2e/code-review-diff.spec.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/desktop/e2e/code-review-diff.spec.ts b/apps/desktop/e2e/code-review-diff.spec.ts index 4322e6bf..cde9c9d5 100644 --- a/apps/desktop/e2e/code-review-diff.spec.ts +++ b/apps/desktop/e2e/code-review-diff.spec.ts @@ -128,6 +128,8 @@ test("keyboard: F6 moves between the areas and [ ] between files, and typing a b await expect.poll(current).toBe(paths[3]); await page.keyboard.press("["); await expect.poll(current).toBe(paths[2]); + // The move focuses its file on the next frame; wait for it, or that focus lands in the middle of the typing below. + await expect(page.locator(`[data-testid="cr-file-section"][data-path="${paths[2]}"]`)).toBeFocused(); // In a text field the keys are text. const filter = page.getByRole("textbox", { name: "Filter remote files" }); await filter.focus();