Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions apps/desktop/e2e/code-review-agent.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,44 @@ const runs = () => h.providerStarts().filter((line) => line.startsWith("claude -
const panel = (p: Page) => tid(p, "cr-agent-panel");
const section = (p: Page) => tid(p, "cr-agent");

test("closing header review and merge panels returns keyboard focus to their own opener", async () => {
h = await launchWithGh(baseWorld());
const page = await openLending();
await tid(page, "code-review-split-toggle").click();
await expect(tid(page, "code-review-workspace")).toHaveAttribute("data-panes", "overview changes");
for (const pane of ["overview", "changes"] as const) {
const root = tid(page, `code-review-pane-${pane}`);
for (const [buttonId, panelId] of [["code-review-review", "cr-agent-panel"], ["code-review-merge", "cr-merge"]] as const) {
const opener = root.getByTestId(buttonId);
await expect(opener).not.toHaveAttribute("aria-disabled", "true");
await opener.focus();
await page.keyboard.press("Enter");
const surface = root.getByTestId(panelId);
await expect(surface).toBeVisible();
const close = surface.getByRole("button", { name: "Close", exact: true });
await close.focus();
await page.keyboard.press("Enter");
await expect(surface).toHaveCount(0);
await expect(opener).toBeFocused();
await page.keyboard.press("Enter");
await expect(surface).toBeVisible();
// The header's instructions popover owns its own Escape; it must not close the underlying panel.
const gear = root.getByTestId("code-review-instructions");
await gear.click();
await expect(page.getByRole("dialog", { name: "Review instructions" })).toBeVisible();
await page.keyboard.press("Escape");
await expect(surface).toBeVisible();
await expect(gear).toBeFocused();
await surface.getByRole("button", { name: "Close", exact: true }).focus();
await page.keyboard.press("Escape");
await expect(surface).toHaveCount(0);
await expect(opener).toBeFocused();
}
}
expect(runs()).toEqual([]);
expect(h.posts()).toEqual([]);
});

test("the instructions popover states its scope, saves a version on this Mac only, survives a reload, and starts nothing", async () => {
h = await launchWithGh(baseWorld());
installClaude("reply");
Expand Down
15 changes: 11 additions & 4 deletions apps/desktop/e2e/code-review-regressions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ test("identity: a read refused because gh's sign-in moved and came back is read
expect(pulls()).toBeGreaterThan(2);
});

test("revision: a head that moves before or during a files page is never served as the current diff", async () => {
for (const heldRead of ["files", "comparison"] as const) test(`revision: a head that moves before or during a ${heldRead} read is never served as the current diff`, async () => {
const world = baseWorld();
h = await launchWithGh(world);
const key = await keyOf("example-org/lending#73");
Expand All @@ -128,11 +128,18 @@ test("revision: a head that moves before or during a files page is never served
const listed = () => h.calls().filter((c) => c.startsWith("repos/example-org/lending/pulls/73/files")).length;
// The moved head was caught by the read before the page: the files list itself was never asked for.
expect(listed()).toBe(0);
h.world((w) => { w.holds = { "repos/example-org/lending/pulls/73/files": "files" }; });
const comparison = `repos/example-org/lending/compare/${sha("b")}...${sha("d")}`;
const heldEndpoint = heldRead === "files" ? "repos/example-org/lending/pulls/73/files" : comparison;
h.world((w) => {
// A comparison names immutable SHAs. It remains readable after the PR moves;
// deriving it from the world's current PR would race the parallel files read.
w.routes[comparison] = { base_commit: { sha: sha("b") }, merge_base_commit: { sha: sha("b") } };
w.holds = { [heldEndpoint]: "revision-read" };
});
const during = invoke({ op: "files", requestId: "f2", key, revision: current, cursor: null });
await expect.poll(listed).toBe(1);
await expect.poll(() => h.calls().filter(c => c.split("?")[0] === heldEndpoint).length).toBe(1);
h.world((w) => { w.routes["repos/example-org/lending/pulls/73"] = ghPull(LENDING, 73, "Moved again", { head: sha("e"), files: 2, additions: 3, deletions: 1 }); });
h.release("files");
h.release("revision-read");
const moved = await during;
expect(moved.scope.revision).toEqual(current);
expect(moved.result).toMatchObject({ state: "stale", reason: "head-changed" });
Expand Down
40 changes: 39 additions & 1 deletion apps/desktop/e2e/markdown-keyboard.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,24 @@ for (const theme of ["graphite", "jev", "coven"] as const) {
const { home } = seedHome();
const { app, page } = await launch(home);
try {
// Observe renderer delivery/cancellation; snapshot native focus on failure.
// DOM focus alone does not explain a missing native scroll action.
await page.evaluate(() => {
const state = window as typeof window & { __markdownKeys?: unknown[] };
const records: unknown[] = state.__markdownKeys = [];
const record = (value: unknown) => { records.push(value); if (records.length > 200) records.shift(); };
const scroll = (el: Element) => ({ tag: el.tagName, className: el.className, left: el.scrollLeft, width: el.clientWidth, scrollWidth: el.scrollWidth });
for (const type of ["keydown", "keyup"] as const) document.addEventListener(type, event => {
if (!["ArrowRight", "ArrowLeft", "Tab"].includes(event.key)) return;
const target = event.target instanceof Element ? scroll(event.target) : null;
// A later task observes cancellation after all capture/bubble listeners.
setTimeout(() => record({ type, key: event.key, at: performance.now(), trusted: event.isTrusted, defaultPrevented: event.defaultPrevented,
documentFocused: document.hasFocus(), visibility: document.visibilityState, target, active: document.activeElement && scroll(document.activeElement) }), 0);
}, true);
document.addEventListener("scroll", event => {
if (event.target instanceof Element && event.target.matches(".md-table, pre.code")) record({ type: "scroll", at: performance.now(), target: scroll(event.target) });
}, true);
});
await resizeWindow(app, page, 900, 600);
await setTheme(page, theme);
await page.emulateMedia({ reducedMotion: "reduce" });
Expand Down Expand Up @@ -86,6 +104,26 @@ for (const theme of ["graphite", "jev", "coven"] as const) {
}))).toEqual([]);
await expect(items(page, "tool")).toHaveCount(0);
await expect(items(page, "approval")).toHaveCount(0);
} finally { await app.close(); }
} catch (error) {
// A stalled renderer must not prevent collecting native state or rethrowing
// the original assertion. Keep both observations inside their own budget.
const observe = async <T>(read: () => Promise<T>) => {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([Promise.resolve().then(read).catch(readError => ({ error: String(readError) })),
new Promise<{ error: string }>(resolve => { timer = setTimeout(() => resolve({ error: "Diagnostic read exceeded 2000ms" }), 2000); })]);
} finally { clearTimeout(timer); }
};
const [renderer, native] = await Promise.all([
observe(() => page.evaluate(() => ({ records: (window as typeof window & { __markdownKeys?: unknown[] }).__markdownKeys,
documentFocused: document.hasFocus(), visibility: document.visibilityState, active: document.activeElement?.outerHTML.slice(0, 800),
scroll: [...document.querySelectorAll(".md-table, pre.code")].map(el => ({ tag: el.tagName, className: el.className, left: el.scrollLeft, width: el.clientWidth, scrollWidth: el.scrollWidth })) }))),
observe(() => app.evaluate(({ BrowserWindow }) => ({ windows: BrowserWindow.getAllWindows().map(w => ({ id: w.id, focused: w.isFocused(), contentsFocused: w.webContents.isFocused(), visible: w.isVisible(), minimized: w.isMinimized(), bounds: w.getBounds() })) }))),
]);
await observe(() => test.info().attach("markdown-keyboard-diagnostics", { body: JSON.stringify({ renderer, native }, null, 2), contentType: "application/json" }));
throw error;
} finally {
await app.close();
}
});
}
21 changes: 18 additions & 3 deletions apps/desktop/src/renderer/code-review/PrPane.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,18 @@ function useScrollMemory(ref: RefObject<HTMLElement | null>, id: string, content
* overview renders #323's read-only content; #324 supplies revision-bound remote diffs and the file tree.
*/
export function PrPane({ pane, changesViews, pr, keyId, changesWidth, treeWidth, busy, pinned, caps, onPin, onRetry, onShowChanges, onActivityPage, contextBusy, onTreeResize, onTreeReset, writes, agent }: Props) {
const paneElement = useRef<HTMLElement>(null);
const body = useRef<HTMLDivElement>(null);
const tree = useRef<HTMLElement>(null);
const [filesShown, setFilesShown] = useState(false);
// At most one panel under the header: Merge, a state change picked from the state menu, or an agent review.
const [panel, setPanel] = useState<"merge" | "agent" | PrStateChange | null>(null);
const closeHeaderPanel = () => {
const opener = panel === "agent" ? "code-review-review" : "code-review-merge";
setPanel(null);
// Each split pane has its own header: return to the button that opened this panel.
paneElement.current?.querySelector<HTMLElement>(`[data-testid="${opener}"]`)?.focus();
};
const overview = pr.overview;
const loaded = overview && overview.state !== "unavailable" ? overview.value : null;
const merge = writes && loaded ? { writes, overview: loaded, open: panel === "merge", onToggle: () => setPanel((v) => v === "merge" ? null : "merge"), onState: (to: PrStateChange) => setPanel(to) } : null;
Expand All @@ -74,10 +81,18 @@ export function PrPane({ pane, changesViews, pr, keyId, changesWidth, treeWidth,
: null;
const status = !overview ? <p className="cr-hint" role="status">{busy ? "Loading the pull request…" : "Not loaded yet."}</p> : notice;
return (
<section id={`cr-pane-${pane}`} role="tabpanel" aria-labelledby={`cr-tab-${pane}`} className={`cr-pane cr-pane-${pane}`} data-pane={pane} data-testid={`code-review-pane-${pane}`}>
<section ref={paneElement} id={`cr-pane-${pane}`} role="tabpanel" aria-labelledby={`cr-tab-${pane}`} className={`cr-pane cr-pane-${pane}`} data-pane={pane} data-testid={`code-review-pane-${pane}`}
onKeyDown={(event) => {
if (event.key === "Escape" && (panel === "agent" || panel === "merge") && event.target instanceof Element
&& event.target.closest('[data-testid="cr-agent-panel"], [data-testid="cr-merge"]')) {
event.preventDefault();
event.stopPropagation();
closeHeaderPanel();
}
}}>
<PrHeader pr={pr} busy={busy} pinned={pinned} caps={caps} onPin={onPin} merge={merge} review={review} filesToggle={pane === "changes" && treeWidth === null ? { shown: filesShown, toggle: () => setFilesShown((v) => !v) } : null} />
{review && panel === "agent" && <AgentPanel key={keyId} agent={review.agent} overview={review.overview} onClose={() => setPanel(null)} onReload={onRetry} />}
{merge && panel === "merge" && <MergePanel key={keyId} writes={merge.writes} overview={merge.overview} onClose={() => setPanel(null)} onMerged={onRetry} />}
{review && panel === "agent" && <AgentPanel key={keyId} agent={review.agent} overview={review.overview} onClose={closeHeaderPanel} onReload={onRetry} />}
{merge && panel === "merge" && <MergePanel key={keyId} writes={merge.writes} overview={merge.overview} onClose={closeHeaderPanel} onMerged={onRetry} />}
{merge && panel && panel !== "merge" && panel !== "agent" && <StatePanel key={`${keyId}:${panel}`} writes={merge.writes} overview={merge.overview} to={panel} onClose={() => setPanel(null)} onDone={onRetry} />}
{pane === "overview" && <div ref={body} className="cr-pane-body" data-testid="code-review-overview-body" tabIndex={-1}>
{status ?? <PrOverview key={keyId} pr={pr} caps={caps} retry={onRetry} onChanges={onShowChanges} onPage={onActivityPage} busy={contextBusy} writes={writes} agent={agent} />}
Expand Down
75 changes: 75 additions & 0 deletions apps/desktop/test/code-review-human-seed.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { ghTransport } from "../src/main/engine/code-review/gh.js";
import { CodeReviewService } from "../src/main/engine/code-review/read-service.js";
import type { CodeReviewRequest, PrActivity, PrCheck, PrFiles, PrKey, PrOverview, PrStack, ReadResult } from "../src/shared/code-review.js";

function ready<T>(result: ReadResult<unknown>): T {
assert.equal(result.state, "ready", JSON.stringify(result));
return (result as { value: T }).value;
}

// Catches the human seed reverting to baseWorld: its overview has no description and its
// activity/checks/stack/second diff reads fail despite the checklist asking a person to use them.
test("the human seed supports populated overview, paged activity, checks, stack and both diffs through real gh reads", async (t) => {
const desktop = fileURLToPath(new URL("../../", import.meta.url));
const root = fs.mkdtempSync(path.join(os.tmpdir(), "modex-cr-human-seed-"));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
execFileSync(process.execPath, [path.resolve(desktop, "../../docs/reviews/2026-10-22-cr8-voiceover/seed.mjs"), root], { cwd: desktop });
const changes = { FAKE_GH_WORLD: path.join(root, "gh-world.json"), FAKE_GH_LOG: path.join(root, "gh-calls.log"), FAKE_GH_HOLDS: path.join(root, "holds"), GH_CONFIG_DIR: path.join(root, "gh-config") };
const original = Object.fromEntries(Object.keys(changes).map(k => [k, process.env[k]]));
Object.assign(process.env, changes);
t.after(() => { for (const [key, value] of Object.entries(original)) { if (value === undefined) delete process.env[key]; else process.env[key] = value; } });
const service = new CodeReviewService({ enabled: true, transport: ghTransport(path.join(root, "bin", "gh")) });
let request = 0;
type Ask = CodeReviewRequest extends infer R ? R extends CodeReviewRequest ? Omit<R, "requestId"> : never : never;
const read = async (ask: Ask) => { const reply = await service.read({ ...ask, requestId: `human-${++request}` }); assert.ok(reply); return reply.result; };
await read({ op: "connection" });
await read({ op: "inbox", query: "" });
const key: PrKey = { account: "1001", host: "github.com", repoId: "7301", number: 73 };
const overview = ready<PrOverview>(await read({ op: "overview", key }));
assert.match(overview.body, /## What changes/);
assert.ok(overview.body.length > 2000, "a long Markdown description for the scrolling journey");
assert.deepEqual(overview.totals, { files: 11, additions: 8912, deletions: 47, commits: 1 });
const first = await read({ op: "activity", key, cursor: null });
const activity = ready<PrActivity[]>(first);
assert.equal(first.state === "ready" && first.coverage?.next, "p2", "Load more activity must be reachable");
const last = await read({ op: "activity", key, cursor: "p2" });
const all = [...activity, ...ready<PrActivity[]>(last)];
assert.equal(last.state === "ready" && last.coverage?.complete, true);
assert.equal(all.filter(a => a.kind === "comment").length, 101);
assert.equal(new Set(all.map(a => a.id)).size, all.length);
assert.ok(all.some(a => a.kind === "deployment" && a.status === "success" && a.url === "https://example.test/preview/73"));
const checks = ready<PrCheck[]>(await read({ op: "checks", key, revision: overview.revision }));
assert.equal(checks.length, 5);
assert.ok(checks.some(c => c.conclusion === "failure"));
assert.ok(checks.some(c => c.status === "running"));
assert.equal(ready<PrStack>(await read({ op: "stack", key })).source, "inferred");
const files = ready<PrFiles>(await read({ op: "files", key, revision: overview.revision, cursor: null })).files;
assert.equal(files.length, 11);
assert.equal(files.reduce((n, f) => n + f.additions, 0), 8912);
assert.equal(files.reduce((n, f) => n + f.deletions, 0), 47);
assert.ok(files.some(f => f.path === "src/holds/move.ts" && f.patch.kind === "text" && /\n /.test(f.patch.patch) && /\n-/.test(f.patch.patch) && /\n\+/.test(f.patch.patch)));
const fieldKey: PrKey = { ...key, repoId: "7302", number: 91 };
const field = ready<PrOverview>(await read({ op: "overview", key: fieldKey }));
const fieldFiles = ready<PrFiles>(await read({ op: "files", key: fieldKey, revision: field.revision, cursor: null })).files;
assert.equal(fieldFiles.length, 4);
assert.deepEqual(fieldFiles.reduce((sum, f) => [sum[0]! + f.additions, sum[1]! + f.deletions], [0, 0]), [11, 4]);
for (const other of [{ ...key, number: 70 }, { ...fieldKey, number: 73 }]) {
const meta = ready<PrOverview>(await read({ op: "overview", key: other }));
const listed = ready<PrFiles>(await read({ op: "files", key: other, revision: meta.revision, cursor: null })).files;
assert.equal(listed.length, meta.totals.files, `listed PR ${other.repoId}#${other.number} must not open an incomplete fixture`);
assert.equal(listed.reduce((n, f) => n + f.additions, 0), meta.totals.additions);
assert.equal(listed.reduce((n, f) => n + f.deletions, 0), meta.totals.deletions);
ready<PrActivity[]>(await read({ op: "activity", key: other, cursor: null }));
ready<PrCheck[]>(await read({ op: "checks", key: other, revision: meta.revision }));
ready<PrStack>(await read({ op: "stack", key: other }));
}
assert.doesNotMatch(fs.readFileSync(path.join(root, "gh-calls.log"), "utf8"), /^(POST|PUT|PATCH|DELETE) /m);
assert.equal(fs.readFileSync(path.join(root, "provider-calls.log"), "utf8"), "");
});
8 changes: 7 additions & 1 deletion apps/desktop/test/fixtures/code-review-gh-world.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,20 @@ const postsFile = process.env.FAKE_GH_POSTS;
const posts = () => postsFile && fs.existsSync(postsFile) ? fs.readFileSync(postsFile, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)) : [];
const reason = { 200: "OK", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 409: "Conflict", 410: "Gone" };
const mergedAs = (pullRoute) => posts().find((p) => p.endpoint === pullRoute + "/merge");
let pagingHeaders = {};
function send(status, body, headers) {
const all = { "Content-Type": "application/json; charset=utf-8", "X-Ratelimit-Remaining": "4999", ...(headers || {}) };
const all = { "Content-Type": "application/json; charset=utf-8", "X-Ratelimit-Remaining": "4999", ...pagingHeaders, ...(headers || {}) };
process.stdout.write("HTTP/2.0 " + status + " " + (reason[status] || "Error") + "\n" + Object.entries(all).map(([k, v]) => k + ": " + v).join("\r\n") + "\r\n\r\n"
+ (typeof body === "string" ? body : JSON.stringify(body)));
if (status >= 300) process.exitCode = 1;
}
function paged(list) {
const per = Number(params.get("per_page") || 30), page = Number(params.get("page") || 1);
if (page * per < list.length) {
const next = new URLSearchParams(params);
next.set("page", String(page + 1));
pagingHeaders = { Link: '<https://api.github.com/' + route + '?' + next + '>; rel="next"' };
}
return list.slice((page - 1) * per, page * per);
}
// Recorded changes to a PR, applied in order to what the world says about it.
Expand Down
Loading
Loading