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/8] 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/8] 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/8] 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/8] 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("