From 04de440a6f6128bbb1f9270e3209fad923b8694e Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Thu, 3 Dec 2026 16:20:23 -0500 Subject: [PATCH] The review session page leads with the decision and what blocks the merge The page opened on a verdict pill and a count, never showed a finding, and stacked the step log, the file table and the facts as equal cards. A part of a review read in parts showed "Done" beside "didn't finish", and a failed review said it didn't finish twice. - An opening card for every state: a headline, one sentence on why (the review's own reason, else the counts, else what it is on now), what the change does, what blocks the merge and how the checks went. - What blocks the merge, open, each with file:line at the reviewed commit, why it matters and the fix; the notes folded below, most serious first. - The checks CoderHelm ran: each command with its result and a plain reason; what was left to the pull request's CI; checks turned off. - Status, trigger, commit, time, model cost and links in a side panel; the timeline folded once there is a verdict; the overview folded. - The finding card is shared with the review page. - e2e for approved, changes requested, in progress, failed, a review read in parts, findings that fail to load, and older sessions. --- dashboard/e2e/reviewer-session-data.ts | 325 ++++++++++++++++ dashboard/e2e/reviewer-session-shots.spec.ts | 63 ++++ dashboard/e2e/reviewer-session-states.spec.ts | 334 ++++++++++++++++ dashboard/e2e/reviewer-session.spec.ts | 46 ++- dashboard/src/app/reviewer/detail/page.tsx | 53 +-- dashboard/src/app/reviewer/finding-card.tsx | 93 +++++ dashboard/src/app/reviewer/session/page.tsx | 172 +++++++-- .../src/app/reviewer/session/sections.tsx | 140 +++---- dashboard/src/app/reviewer/session/session.ts | 209 ++++++++++- .../src/app/reviewer/session/summary.tsx | 355 ++++++++++++++++++ dashboard/src/lib/api-contract.ts | 5 +- dashboard/src/lib/api.ts | 30 ++ dashboard/src/lib/openapi-fields.ts | 6 +- 13 files changed, 1651 insertions(+), 180 deletions(-) create mode 100644 dashboard/e2e/reviewer-session-data.ts create mode 100644 dashboard/e2e/reviewer-session-shots.spec.ts create mode 100644 dashboard/e2e/reviewer-session-states.spec.ts create mode 100644 dashboard/src/app/reviewer/finding-card.tsx create mode 100644 dashboard/src/app/reviewer/session/summary.tsx diff --git a/dashboard/e2e/reviewer-session-data.ts b/dashboard/e2e/reviewer-session-data.ts new file mode 100644 index 00000000..0d9d8226 --- /dev/null +++ b/dashboard/e2e/reviewer-session-data.ts @@ -0,0 +1,325 @@ +// Made-up review sessions of a made-up bookstore, for the session page's +// tests and screenshots: one per state the page draws. Every name, path and +// number here is invented. + +export const SESSION_ID = "7c1d2e3f-4a5b-4c6d-8e7f-9a0b1c2d3e4f"; +export const SHA = "4e1a2b0c9d8f7e6a5b4c3d2e1f0a9b8c7d6e5f4a"; +export const REVIEW_SK = "REVIEW#acme/bookstore#000412#2026-11-30T15:04:41Z"; +const REPO = "acme/bookstore"; + +/** Times relative to `now`, so a running review reads as running. */ +export function times(now = Date.now()) { + const iso = (secsAgo: number) => new Date(now - secsAgo * 1000).toISOString(); + return { iso }; +} + +export type Json = Record; + +const overview = { + summary: "Lets a shopper pay part of an order with a gift card and the rest by card.", + changes: [ + "Checkout takes the gift card's balance off the total before charging the card.", + "A new `gift_card_redemptions` table records each use, so a refund can put the balance back.", + ], + files: [ + { path: "src/checkout/giftcard.ts", description: "Reads the card's balance and takes the order's share of it." }, + { path: "src/checkout/total.ts", description: "Subtracts the gift card amount before tax is worked out." }, + { path: "src/checkout/refund.ts", description: "Puts a redeemed amount back on the card when an order is refunded." }, + { path: "db/migrations/0042_gift_card_redemptions.sql", description: "Adds the `gift_card_redemptions` table." }, + { path: "test/checkout/giftcard.test.ts", description: "Covers a partial and a full redemption." }, + ], + files_total: 5, +}; + +function activity(iso: (s: number) => string, done: boolean) { + const list: Json[] = [ + { + kind: "note", + title: "Checking how the balance is taken", + started_at: iso(150), + ended_at: iso(150), + text: "The balance is read, then written back as a separate step. Two orders paying with one card at once could both see the full balance.", + items: [], + }, + { + kind: "search", + title: "Search 3 times", + started_at: iso(146), + ended_at: iso(140), + text: "", + items: [ + { at: iso(146), label: "redeemGiftCard", detail: "", failed: false }, + { at: iso(143), label: "callers of applyBalance", detail: "", failed: false }, + { at: iso(140), label: "FOR UPDATE", detail: "", failed: false }, + ], + }, + { + kind: "view", + title: "View 3 files", + started_at: iso(138), + ended_at: iso(120), + text: "", + items: [ + { at: iso(138), label: "src/checkout/giftcard.ts:60-120", detail: "", failed: false }, + { at: iso(130), label: "src/checkout/refund.ts:1-80", detail: "", failed: false }, + { at: iso(120), label: "src/db/tx.ts:1-40", detail: "", failed: false }, + ], + }, + { + kind: "note", + title: "Checking the rounding of split payments", + started_at: iso(110), + ended_at: iso(110), + text: "The card is charged the total less the gift card amount; both are in cents, so nothing is lost.", + items: [], + }, + { + kind: "view", + title: "View 2 files", + started_at: iso(105), + ended_at: iso(96), + text: "", + items: [ + { at: iso(105), label: "src/checkout/total.ts:1-64", detail: "", failed: false }, + { at: iso(96), label: "test/checkout/giftcard.test.ts:1-90", detail: "", failed: false }, + ], + }, + ]; + if (done) { + list.push({ + kind: "comment", + title: "Keep 3 comments", + started_at: iso(60), + ended_at: iso(60), + text: "", + items: [ + { at: iso(60), label: "src/checkout/giftcard.ts:88", detail: "Two orders can spend the same balance", failed: false }, + { at: iso(60), label: "src/checkout/refund.ts:41", detail: "A refund of a split order puts back the whole order", failed: false }, + { at: iso(60), label: "src/checkout/total.ts:22", detail: "Name the cents variable", failed: false }, + ], + }); + } + return list; +} + +const steps = (iso: (s: number) => string, done: boolean) => [ + { at: iso(180), text: "Started reviewing `4e1a2b0`", detail: "" }, + { at: iso(170), text: "Read the change: 5 files changed", detail: overview.files.map((f) => f.path).join("\n") }, + { at: iso(160), text: "Reviewing the code", detail: "Against the repository's rules, the team's standards and what earlier reviews taught." }, + ...(done + ? [ + { at: iso(70), text: "Checked the findings: kept 3 of 5", detail: "A second pass drops findings it can't back up." }, + { at: iso(20), text: "Posted the review: changes requested", detail: "" }, + ] + : []), +]; + +/** The session of a review that asked for changes, done. */ +export function changesRequested(now = Date.now()): Json { + const { iso } = times(now); + return { + id: SESSION_ID, + repo: REPO, + pr_number: 412, + pr_title: "Apply gift card balance at checkout", + head_sha: SHA, + trigger: "push", + kind: "review", + status: "done", + in_flight: false, + attempt: 0, + started_at: iso(180), + finished_at: iso(15), + reason: "", + verdict: "REQUEST_CHANGES", + findings: 3, + review_url: `https://github.com/${REPO}/pull/412#pullrequestreview-7781`, + check_run_id: 52210001, + steps: steps(iso, true), + activity: activity(iso, true), + activity_dropped: 0, + overview, + review_sk: REVIEW_SK, + cost_usd: 0.84, + verification: { + outcome: "incomplete", + checks: [ + { kind: "install", dir: ".", cmd: "npm ci", result: "passed", why: "" }, + { kind: "check", dir: ".", cmd: "npx tsc --noEmit", result: "passed", why: "" }, + { kind: "test", dir: ".", cmd: "npx vitest run test/checkout/giftcard.test.ts", result: "passed", why: "" }, + { + kind: "check", + dir: "admin", + cmd: "npm run typecheck", + result: "couldnt_run", + why: "the admin package has no typecheck script", + }, + ], + note: "", + left_out: ["`e2e/checkout.spec.ts`: end-to-end tests run against a preview, so the pull request's CI result stands for them"], + }, + }; +} + +const reviewBody = `## Summary +Lets a shopper pay part of an order with a gift card. One change holds the merge: two orders paying with the same card at the same moment can both spend its full balance. + +- [blocking] src/checkout/giftcard.ts:88 — Two orders can spend the same balance + \`redeemGiftCard\` reads the balance, then writes the new one in a second query. Two checkouts that run together both read \`$50\` and both take it, so the card pays out \`$100\`. + + Take the balance in one statement inside the order's transaction: + + \`\`\`ts + await tx.query("UPDATE gift_cards SET balance = balance - $1 WHERE id = $2 AND balance >= $1", [amount, card.id]); + \`\`\` +- [medium] src/checkout/refund.ts:41 — A refund of a split order puts back the whole order + The refund credits the order total to the gift card, not the part the card paid. A \`$80\` order paid \`$30\` by gift card gives the card \`$80\` back. +- [nit] src/checkout/total.ts:22 — Name the cents variable + \`n\` holds cents; \`amountCents\` says so. + +#### 🧪 Verification +✅ Ran \`npm ci\` in the sandbox: passed. +✅ Ran \`npx tsc --noEmit\` in the sandbox: passed. +✅ Ran \`npx vitest run test/checkout/giftcard.test.ts\` in the sandbox: passed. +`; + +/** The review that session posted (`/api/reviewer/review`). */ +export function review(now = Date.now()): Json { + const { iso } = times(now); + return { + sk: REVIEW_SK, + repo: REPO, + pr_number: 412, + head_sha: SHA, + verdict: "REQUEST_CHANGES", + risk: "high", + body: reviewBody, + posted_as: "REQUEST_CHANGES", + trigger: "synchronize", + action_summary: "", + thumbs_up: 0, + thumbs_down: 0, + rating_comments: [], + created_at: iso(15), + pr_title: "Apply gift card balance at checkout", + verdict_reason: "Changes requested for 1 blocking finding: two orders can spend the same gift card balance.", + session_id: SESSION_ID, + applied_standards: [], + findings: [ + { + severity: "blocking", + kind: "defect", + blocks: true, + file: "src/checkout/giftcard.ts", + line: 88, + title: "Two orders can spend the same balance", + body: + "`redeemGiftCard` reads the balance, then writes the new one in a second query. Two checkouts that run together both read `$50` and both take it, so the card pays out `$100`.\n\nTake the balance in one statement inside the order's transaction:\n\n```ts\nawait tx.query(\"UPDATE gift_cards SET balance = balance - $1 WHERE id = $2 AND balance >= $1\", [amount, card.id]);\n```", + }, + { + severity: "medium", + kind: "defect", + blocks: false, + file: "src/checkout/refund.ts", + line: 41, + title: "A refund of a split order puts back the whole order", + body: "The refund credits the order total to the gift card, not the part the card paid. A `$80` order paid `$30` by gift card gives the card `$80` back.", + }, + { + severity: "nit", + kind: "suggestion", + blocks: false, + file: "src/checkout/total.ts", + line: 22, + title: "Name the cents variable", + body: "`n` holds cents; `amountCents` says so.", + }, + ], + }; +} + +/** The same PR approved on a later commit: nothing holds the merge. */ +export function approved(now = Date.now()): Json { + const s = changesRequested(now); + return { + ...s, + verdict: "APPROVE", + findings: 1, + review_url: `https://github.com/${REPO}/pull/412#pullrequestreview-7790`, + steps: (s.steps as Json[]).map((st, i, all) => (i === all.length - 1 ? { ...st, text: "Posted the review: approved" } : st)), + verification: { + outcome: "passed", + checks: (changesRequested(now).verification as { checks: Json[] }).checks.slice(0, 3), + note: "", + left_out: [], + }, + }; +} + +export function approvedReview(now = Date.now()): Json { + const r = review(now); + return { + ...r, + verdict: "APPROVE", + posted_as: "APPROVE", + risk: "medium", + verdict_reason: "Approved: nothing holds the merge. 1 note is worth a look.", + body: "## Summary\nLets a shopper pay part of an order with a gift card. The balance is now taken in one statement, so two orders can't spend it twice.\n", + findings: [(r.findings as Json[])[2]], + }; +} + +/** Still reading: no verdict yet, the newest step running. */ +export function inProgress(now = Date.now()): Json { + const { iso } = times(now); + const s = changesRequested(now); + return { + ...s, + status: "reviewing", + in_flight: true, + finished_at: "", + verdict: "", + findings: null, + review_url: "", + review_sk: null, + overview: null, + verification: null, + cost_usd: null, + steps: steps(iso, false), + activity: activity(iso, false), + }; +} + +/** Ended without a review. */ +export function failed(now = Date.now()): Json { + const s = inProgress(now); + const { iso } = times(now); + return { + ...s, + status: "failed", + in_flight: false, + finished_at: iso(30), + reason: "The model stopped answering partway through the review, twice.", + cost_usd: 0.31, + }; +} + +/** A large PR read in parts: this session read the first part and handed on. */ +export function inParts(now = Date.now()): Json { + const { iso } = times(now); + const s = inProgress(now); + return { + ...s, + status: "done", + in_flight: false, + finished_at: iso(10), + reason: "Reviewing 4e1a2b0 in 3 parts: 1 done, the next one starts now", + goes_on: true, + steps: [ + ...(s.steps as Json[]), + { at: iso(60), text: "Reading part 1 of 3", detail: "38 files (code, tests), the full pass." }, + { at: iso(12), text: "Read this part; the review goes on in its next part: Reviewing 4e1a2b0 in 3 parts: 1 done, the next one starts now", detail: "" }, + ], + cost_usd: 0.52, + }; +} diff --git a/dashboard/e2e/reviewer-session-shots.spec.ts b/dashboard/e2e/reviewer-session-shots.spec.ts new file mode 100644 index 00000000..a125a1e1 --- /dev/null +++ b/dashboard/e2e/reviewer-session-shots.spec.ts @@ -0,0 +1,63 @@ +import { test, type Page, type Route } from "@playwright/test"; +import fs from "node:fs"; +import path from "node:path"; +import { approved, approvedReview, changesRequested, failed, inParts, inProgress, review, SESSION_ID, type Json } from "./reviewer-session-data"; + +// Screenshots of the review session page in each state, at desktop and phone +// width, for a design review. Runs only when E2E_SHOTS_DIR is set; every API +// call is answered here with a made-up bookstore's review. + +const SHOTS_DIR = process.env.E2E_SHOTS_DIR || ""; +const LABEL = process.env.SHOTS_LABEL || "after"; + +async function mock(page: Page, session: Json, rev: Json | null) { + const json = (route: Route, body: unknown, status = 200) => + route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); + await page.route((url) => url.hostname !== "localhost", (route) => route.abort()); + await page.route((url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), async (route) => { + const p = new URL(route.request().url()).pathname; + if (p === "/api/me") return json(route, { user_id: "u_1", team_id: "t_1", github_login: "a-maintainer", email: "someone@example.com", avatar_url: "", role: "member" }); + if (p === "/api/usage") return json(route, { month: "2026-11", total_tokens: 0, tokens_in: 0, tokens_out: 0, total_runs: 0, max_tokens: 0 }); + if (p === "/api/banners") return json(route, { banners: [] }); + if (p === "/api/security/overview") return json(route, { enabled: false, dry_run: true, counts: { open: 0, p0: 0, p1: 0 } }); + if (p === "/api/setup") return json(route, { repos: [], new_recommendations: [], auto_setup_new_repos: false }); + if (p === "/api/support/badge") return json(route, { waiting: 0, queue_open: null }); + if (p === "/api/integrations") return json(route, { can_edit: false, items: [], migrated: 0 }); + if (p === "/api/skills/used") return json(route, { skills: [], agents: [], sources: [], standards: [] }); + if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "acme", status: "active", current: true }] }); + if (p === "/api/repos") return json(route, { repos: [{ name: "acme/bookstore", enabled: true, ticket_source: "github" }] }); + if (p === "/api/aws-connections") return json(route, { connections: [] }); + if (p === "/api/reviewer/session") return json(route, session); + if (p === "/api/reviewer/review") return rev ? json(route, rev) : json(route, { error: "nope" }, 404); + return json(route, { error: `Not mocked: ${p}` }, 404); + }); +} + +async function shot(page: Page, name: string) { + fs.mkdirSync(SHOTS_DIR, { recursive: true }); + await page.addStyleTag({ content: "nextjs-portal{display:none!important}" }); + for (const width of [1440, 390]) { + await page.setViewportSize({ width, height: width < 640 ? 844 : 900 }); + await page.waitForTimeout(300); + await page.screenshot({ path: path.join(SHOTS_DIR, `${LABEL}-${name}-${width}.png`), fullPage: true }); + } +} + +const STATES: [string, () => Json, () => Json | null][] = [ + ["changes-requested", () => changesRequested(), () => review()], + ["approved", () => approved(), () => approvedReview()], + ["in-progress", () => inProgress(), () => null], + ["failed", () => failed(), () => null], + ["in-parts", () => inParts(), () => null], +]; + +for (const [name, session, rev] of STATES) { + test(`session page screenshot: ${name}`, async ({ page }) => { + test.skip(!SHOTS_DIR, "Screenshots only when E2E_SHOTS_DIR is set"); + await mock(page, session(), rev()); + await page.goto(`/reviewer/session?id=${SESSION_ID}`); + await page.getByTestId("review-session").waitFor(); + await page.waitForTimeout(800); + await shot(page, name); + }); +} diff --git a/dashboard/e2e/reviewer-session-states.spec.ts b/dashboard/e2e/reviewer-session-states.spec.ts new file mode 100644 index 00000000..59e2f6bf --- /dev/null +++ b/dashboard/e2e/reviewer-session-states.spec.ts @@ -0,0 +1,334 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; +import { + checkLook, + checksLabel, + costLabel, + countsLabel, + decision, + isPart, + ownReason, + partOf, + verificationFromBody, + verificationLine, +} from "../src/app/reviewer/session/session"; +import { approved, approvedReview, changesRequested, failed, inParts, inProgress, review, REVIEW_SK, SESSION_ID, SHA, type Json } from "./reviewer-session-data"; + +// The review session page in each state a person meets it: approved, changes +// requested, still running, stopped, and one part of a review read in parts. +// Every API call is answered here with a made-up bookstore's review. + +// ---- The words --------------------------------------------------------------- + +test.describe("what the page leads with", () => { + test("the decision reads as a headline and one sentence for every state", () => { + const base = { kind: "review", verdict: "", reason: "" }; + expect(decision({ ...base, status: "reviewing" }, { now: "Checking callers" })).toEqual({ tone: "live", headline: "Reviewing now", why: "Now: Checking callers" }); + expect(decision({ ...base, status: "reviewing", kind: "question" }).headline).toBe("Answering a comment"); + expect(decision({ ...base, status: "failed", reason: "The model timed out." })).toEqual({ + tone: "danger", + headline: "The review didn't finish", + why: "The model timed out. Nothing new was posted on the pull request.", + }); + expect(decision({ ...base, status: "stalled" }).tone).toBe("danger"); + expect(decision({ ...base, status: "retrying", reason: "the model was busy" }).why).toBe( + "This try didn't finish: the model was busy. CoderHelm sent the review again; the new try has its own page.", + ); + expect(decision({ ...base, status: "skipped", reason: "Only lockfile changes." }).why).toBe("Only lockfile changes."); + // A verdict: the review's own reason without the verdict it starts with, else the counts. + const counts = { blocking: 1, notes: 2, unknown: 0 }; + expect(decision({ ...base, status: "done", verdict: "REQUEST_CHANGES" }, { counts, verdictReason: "Changes requested for 1 blocking finding: two orders can spend one balance." })).toEqual({ + tone: "danger", + headline: "Changes requested", + why: "Two orders can spend one balance.", + }); + expect(decision({ ...base, status: "done", verdict: "REQUEST_CHANGES" }, { counts }).why).toBe("1 finding holds the merge."); + expect(decision({ ...base, status: "done", verdict: "APPROVE" }, { counts: { blocking: 0, notes: 0, unknown: 0 } }).why).toBe("Nothing holds the merge."); + expect(decision({ ...base, status: "done", verdict: "APPROVE" }, { counts: { blocking: 0, notes: 2, unknown: 0 } }).why).toBe("Nothing holds the merge. 2 notes are worth a look."); + // One part of a review read in parts never reads as finished. + const part = { ...base, status: "done", reason: "Reviewing 4e1a2b0 in 3 parts: 1 done, the next one starts now" }; + expect(decision(part).headline).toBe("Part 1 of 3 read"); + expect(decision({ ...part, reason: "", goes_on: true }).headline).toBe("One part read"); + expect(isPart(part)).toBe(true); + expect(isPart({ ...part, verdict: "APPROVE" })).toBe(false); + expect(partOf("in 3 parts: 4 done")).toBeNull(); + expect(decision({ ...base, status: "done" }).headline).toBe("Finished"); + }); + + test("a reason that doesn't start with the verdict stays as it is", () => { + expect(ownReason("Approved: nothing holds the merge.")).toBe("Nothing holds the merge."); + expect(ownReason("The lockfile moved.")).toBe("The lockfile moved."); + expect(ownReason(undefined)).toBe(""); + }); + + test("counts, checks and cost read as plain words", () => { + expect(countsLabel({ blocking: 1, notes: 2, unknown: 0 })).toBe("1 blocks the merge · 2 notes"); + expect(countsLabel({ blocking: 2, notes: 1, unknown: 0 })).toBe("2 block the merge · 1 note"); + expect(countsLabel({ blocking: 0, notes: 0, unknown: 3 })).toBe("3 findings"); + expect(countsLabel({ blocking: 0, notes: 0, unknown: 0 })).toBe("No findings"); + expect(checksLabel([{ result: "passed" }, { result: "couldnt_run" }, { result: "failed" }])).toBe("1 of 3 passed · 1 failed · 1 couldn't run"); + expect(checksLabel([])).toBe(""); + expect(checkLook("couldnt_run")).toEqual({ label: "Couldn't run", tone: "waiting" }); + expect(checkLook("skipped").label).toBe("Didn't run"); + expect(checkLook("new_word").label).toBe("New word"); + expect(verificationLine("failed").tone).toBe("danger"); + expect(verificationLine("incomplete").text).toMatch(/CoderHelm's problem, not the change's/); + expect(costLabel(0.84)).toBe("$0.84"); + expect(costLabel(0.004)).toBe("Under $0.01"); + expect(costLabel(null)).toBeNull(); + expect(costLabel(Number.NaN)).toBeNull(); + }); + + test("an older review's checks are read from its text", () => { + const body = "## Summary\nOk.\n\n#### 🧪 Verification\n✅ Ran `npm test` in the sandbox: passed.\n\n## Something else\nNo."; + expect(verificationFromBody(body)).toBe("✅ Ran `npm test` in the sandbox: passed."); + expect(verificationFromBody("## Summary\nOk.")).toBe(""); + }); +}); + +// ---- The page ------------------------------------------------------------------ + +interface Backend { + calls: string[]; + session: Json | number; + review: Json | number; + role: string; +} + +async function mockApi(page: Page, init: Partial): Promise { + const db: Backend = { calls: [], session: changesRequested(), review: review(), role: "member", ...init }; + const json = (route: Route, body: unknown, status = 200) => + route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); + await page.route((url) => url.hostname !== "localhost", (route) => route.abort()); + await page.route((url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), async (route) => { + const url = new URL(route.request().url()); + const p = url.pathname; + db.calls.push(`${p}${url.search}`); + if (p === "/api/me") return json(route, { user_id: "u_1", team_id: "t_1", github_login: "a-maintainer", email: "someone@example.com", avatar_url: "", role: db.role }); + if (p === "/api/usage") return json(route, { month: "2026-11", total_tokens: 0, tokens_in: 0, tokens_out: 0, total_runs: 0, max_tokens: 0 }); + if (p === "/api/banners") return json(route, { banners: [] }); + if (p === "/api/security/overview") return json(route, { enabled: false, dry_run: true, counts: { open: 0, p0: 0, p1: 0 } }); + if (p === "/api/setup") return json(route, { repos: [], new_recommendations: [], auto_setup_new_repos: false }); + if (p === "/api/support/badge") return json(route, { waiting: 0, queue_open: null }); + if (p === "/api/integrations") return json(route, { can_edit: false, items: [], migrated: 0 }); + if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "acme", status: "active", current: true }] }); + if (p === "/api/repos") return json(route, { repos: [{ name: "acme/bookstore", enabled: true, ticket_source: "github" }] }); + if (p === "/api/aws-connections") return json(route, { connections: [] }); + if (p === "/api/reviewer/session") return typeof db.session === "number" ? json(route, { error: "nope" }, db.session) : json(route, db.session); + if (p === "/api/reviewer/review") return typeof db.review === "number" ? json(route, { error: "nope" }, db.review) : json(route, db.review); + return json(route, { error: `Not mocked: ${p}` }, 404); + }); + return db; +} + +function watchConsole(page: Page) { + const errors: string[] = []; + page.on("console", (msg) => { + if (msg.type() !== "error") return; + const text = msg.text(); + if (text.includes("net::ERR_ABORTED") || text.includes("net::ERR_FAILED") || text.startsWith("Failed to load resource")) return; + errors.push(text); + }); + page.on("pageerror", (err) => errors.push(err.message)); + return errors; +} + +/** What a person reads on the page passes the same checks CoderHelm's own text does. */ +async function plainWords(page: Page) { + const text = await page.getByTestId("review-session").innerText(); + for (const bad of [/\(s\)/, /\[[a-z]+(?:_[a-z0-9]+)+\]/, /\bre-review\b/i, /\byourself\b/i, /\bundefined\b/, /\bnull\b/, /\bNaN\b/, /REQUEST_CHANGES|APPROVE\b|couldnt_run|goes_on/, /\bphase\b/i, /\bpass\b/i, /\bjob\b/i]) { + expect(text, `page text matches ${bad}`).not.toMatch(bad); + } +} + +async function noSidewaysScroll(page: Page) { + await page.setViewportSize({ width: 390, height: 844 }); + const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + expect(overflow).toBeLessThanOrEqual(0); +} + +const open = (page: Page) => page.goto(`/reviewer/session?id=${SESSION_ID}`); + +test("changes requested: what blocks comes first, with its place, why and fix", async ({ page }) => { + const errors = watchConsole(page); + const db = await mockApi(page, {}); + await open(page); + const card = page.getByTestId("session-decision"); + await expect(card).toHaveAttribute("data-tone", "danger"); + await expect(card.getByRole("heading", { level: 2 })).toHaveText("Changes requested"); + await expect(page.getByTestId("session-why")).toHaveText("Two orders can spend the same gift card balance."); + await expect(page.getByTestId("session-change")).toContainText("pay part of an order with a gift card"); + await expect(page.getByTestId("session-fact")).toHaveText(["1 blocks the merge · 2 notes", "Checks: 3 of 4 passed · 1 couldn't run"]); + expect(db.calls).toContain(`/api/reviewer/review?sk=${encodeURIComponent(REVIEW_SK)}`); + + // The blocking finding, open, linked to its line at the reviewed commit, with the fix. + const blocking = page.getByTestId("session-blocking"); + await expect(blocking.getByRole("heading", { level: 2 })).toContainText("Blocks the merge"); + const finding = blocking.getByTestId("finding"); + await expect(finding).toHaveCount(1); + await expect(finding.getByRole("heading", { level: 3 })).toHaveText("Two orders can spend the same balance"); + await expect(finding.getByTestId("finding-place")).toHaveAttribute("href", `https://github.com/acme/bookstore/blob/${SHA}/src/checkout/giftcard.ts#L88`); + await expect(finding).toContainText("Take the balance in one statement"); + + // The blocking finding sits above the checks, and both above the notes. + const y = async (id: string) => (await page.getByTestId(id).boundingBox())!.y; + expect(await y("session-blocking")).toBeLessThan(await y("session-checks")); + expect(await y("session-checks")).toBeLessThan(await y("session-notes")); + + // The checks: each command, and a plain reason for the one that couldn't run. + const checks = page.getByTestId("session-checks"); + await expect(checks).toHaveAttribute("data-outcome", "incomplete"); + await expect(checks.getByTestId("check")).toHaveCount(4); + const couldnt = checks.locator('[data-result="couldnt_run"]'); + await expect(couldnt).toContainText("npm run typecheck"); + await expect(couldnt).toContainText("in admin"); + await expect(couldnt).toContainText("The admin package has no typecheck script."); + await expect(couldnt).toContainText("Couldn't run"); + await expect(page.getByTestId("checks-line")).toContainText("doesn't hold the merge"); + await expect(page.getByTestId("checks-left-out")).toContainText("e2e/checkout.spec.ts"); + + // The notes are folded, then one line each, most serious first; a line opens to its reasoning. + const notes = page.getByTestId("session-notes"); + await expect(notes).toContainText("These don't hold the merge. Medium, Nit."); + await expect(notes.getByTestId("note").first()).toBeHidden(); + await notes.getByRole("heading", { name: /Notes/ }).click(); + await expect(notes.getByTestId("note")).toHaveCount(2); + await expect(notes.getByTestId("note").nth(0)).toContainText("A refund of a split order puts back the whole order"); + await expect(notes.getByTestId("note").nth(1)).toContainText("Name the cents variable"); + await notes.getByText("A refund of a split order puts back the whole order").click(); + await expect(notes.getByTestId("note").nth(0)).toContainText("gives the card"); + + // The run's details beside it: the cost, and where to go next. The timeline is folded. + const facts = page.getByTestId("session-facts"); + await expect(page.getByTestId("session-cost")).toContainText("$0.84"); + await expect(facts).toContainText("2m 45s"); + await expect(facts.getByRole("link", { name: /The review on GitHub/ })).toHaveAttribute("href", "https://github.com/acme/bookstore/pull/412#pullrequestreview-7781"); + await expect(page.getByTestId("session-pr-link")).toHaveAttribute("href", /\/reviewer\/pr\/?\?repo=acme%2Fbookstore&pr=412/); + await expect(page.getByTestId("session-timeline")).toBeHidden(); + await plainWords(page); + await noSidewaysScroll(page); + expect(errors).toEqual([]); +}); + +test("approved: nothing holds the merge, and it says so", async ({ page }) => { + const errors = watchConsole(page); + await mockApi(page, { session: approved(), review: approvedReview() }); + await open(page); + const card = page.getByTestId("session-decision"); + await expect(card).toHaveAttribute("data-tone", "success"); + await expect(card.getByRole("heading", { level: 2 })).toHaveText("Approved"); + await expect(page.getByTestId("session-why")).toHaveText("Nothing holds the merge. 1 note is worth a look."); + await expect(page.getByTestId("session-fact")).toHaveText(["1 note", "Checks: 3 of 3 passed"]); + await expect(page.getByTestId("session-blocking")).toHaveCount(0); + await expect(page.getByTestId("checks-line")).toHaveText("Every check passed."); + await expect(page.getByTestId("checks-left-out")).toHaveCount(0); + await expect(page.getByTestId("session-notes")).toContainText("Nit"); + await plainWords(page); + + // An approval with no findings at all. + await mockApi(page, { session: { ...approved(), findings: 0 }, review: { ...approvedReview(), findings: [], verdict_reason: "" } }); + await open(page); + await expect(page.getByTestId("session-why")).toHaveText("Nothing holds the merge."); + await expect(page.getByTestId("session-fact").first()).toHaveText("No findings"); + await expect(page.getByTestId("session-notes")).toHaveCount(0); + expect(errors).toEqual([]); +}); + +test("in progress: what it is on now, the timeline open, no verdict yet", async ({ page }) => { + const errors = watchConsole(page); + const db = await mockApi(page, { session: inProgress() }); + await open(page); + const card = page.getByTestId("session-decision"); + await expect(card).toHaveAttribute("data-tone", "live"); + await expect(card.getByRole("heading", { level: 2 })).toHaveText("Reviewing now"); + await expect(page.getByTestId("session-why")).toHaveText("Now: Checking the rounding of split payments"); + await expect(page.getByTestId("session-status")).toHaveText("Reviewing"); + await expect(page.getByTestId("session-timeline")).toBeVisible(); + await expect(page.getByTestId("session-timeline").locator('[data-state="running"]')).toHaveCount(1); + await expect(page.getByTestId("session-facts")).toContainText("Running for"); + for (const id of ["session-blocking", "session-checks", "session-notes", "session-fact", "session-cost"]) await expect(page.getByTestId(id)).toHaveCount(0); + // No review to read, and no asking again while it runs. + expect(db.calls.some((c) => c.startsWith("/api/reviewer/review"))).toBe(false); + await expect(page.getByRole("button", { name: /again$/ })).toHaveCount(0); + await plainWords(page); + await noSidewaysScroll(page); + expect(errors).toEqual([]); +}); + +test("failed: why it stopped, where, and one way on", async ({ page }) => { + const errors = watchConsole(page); + await mockApi(page, { session: failed() }); + await open(page); + const card = page.getByTestId("session-decision"); + await expect(card).toHaveAttribute("data-tone", "danger"); + await expect(card.getByRole("heading", { level: 2 })).toHaveText("The review didn't finish"); + await expect(page.getByTestId("session-why")).toHaveText("The model stopped answering partway through the review, twice. Nothing new was posted on the pull request."); + // Said once: no second box repeating it. + await expect(page.getByText("Nothing new was posted on the pull request.")).toHaveCount(1); + await expect(page.getByTestId("session-status")).toHaveText("Failed"); + await expect(page.getByTestId("session-timeline")).toBeVisible(); + await expect(page.getByTestId("session-activity").getByRole("heading", { name: "Review stopped" })).toBeVisible(); + await expect(page.getByRole("button", { name: "Review acme/bookstore #412 again" })).toBeVisible(); + await expect(page.getByTestId("session-cost")).toContainText("$0.31"); + await plainWords(page); + + // A viewer reads it but can't ask for a new review. + await mockApi(page, { session: failed(), role: "viewer" }); + await open(page); + await expect(page.getByTestId("session-decision")).toBeVisible(); + await expect(page.getByRole("button", { name: /again$/ })).toHaveCount(0); + expect(errors).toEqual([]); +}); + +test("a review read in parts: this part is done and the review goes on", async ({ page }) => { + const errors = watchConsole(page); + await mockApi(page, { session: inParts() }); + await open(page); + const card = page.getByTestId("session-decision"); + await expect(card.getByRole("heading", { level: 2 })).toHaveText("Part 1 of 3 read"); + await expect(page.getByTestId("session-why")).toContainText("the verdict comes with the last one"); + // Never "Done" or "didn't finish" for a part. + await expect(page.getByTestId("session-status")).toHaveText("Goes on"); + await expect(page.getByTestId("review-session")).not.toContainText("didn't finish"); + await expect(page.getByTestId("session-activity").getByRole("heading", { name: "Read part 1 of 3" })).toBeVisible(); + await expect(page.getByTestId("session-timeline")).toBeVisible(); + await expect(page.getByTestId("session-blocking")).toHaveCount(0); + await expect(page.getByTestId("session-cost")).toContainText("$0.52"); + + // An older part, kept before `goes_on`, reads the same from its reason. + await mockApi(page, { session: { ...inParts(), goes_on: undefined } }); + await open(page); + await expect(page.getByTestId("session-decision").getByRole("heading", { level: 2 })).toHaveText("Part 1 of 3 read"); + await plainWords(page); + await noSidewaysScroll(page); + expect(errors).toEqual([]); +}); + +test("the findings that can't load leave the decision standing and a way to GitHub", async ({ page }) => { + const errors = watchConsole(page); + const db = await mockApi(page, { review: 500 }); + await open(page); + await expect(page.getByTestId("session-decision").getByRole("heading", { level: 2 })).toHaveText("Changes requested"); + await expect(page.getByTestId("session-fact").first()).toHaveText("3 findings"); + const err = page.getByTestId("findings-error"); + await expect(err).toContainText("Couldn't load the findings."); + await expect(err.getByRole("link", { name: /Read them on GitHub/ })).toHaveAttribute("href", /pullrequestreview-7781/); + db.review = review(); + await err.getByRole("button", { name: "Try again" }).click(); + await expect(page.getByTestId("session-blocking").getByTestId("finding")).toHaveCount(1); + await expect(page.getByTestId("findings-error")).toHaveCount(0); + expect(errors).toEqual([]); +}); + +test("a session kept before the checks were data shows them from the review's text, and checks turned off say so", async ({ page }) => { + await mockApi(page, { session: { ...changesRequested(), verification: null, cost_usd: null } }); + await open(page); + const checks = page.getByTestId("session-checks"); + await expect(checks).toHaveAttribute("data-outcome", "text"); + await expect(checks).toContainText("npx tsc --noEmit"); + await expect(page.getByTestId("session-cost")).toHaveCount(0); + + await mockApi(page, { session: { ...changesRequested(), verification: { outcome: "off", checks: [], note: "", left_out: [] } } }); + await open(page); + await expect(page.getByTestId("checks-line")).toContainText("don't run its checks"); + await expect(page.getByTestId("checks-line").getByRole("link", { name: "Reviewer settings" })).toHaveAttribute("href", /\/reviewer\/config/); +}); diff --git a/dashboard/e2e/reviewer-session.spec.ts b/dashboard/e2e/reviewer-session.spec.ts index e2f99a6d..a195d1de 100644 --- a/dashboard/e2e/reviewer-session.spec.ts +++ b/dashboard/e2e/reviewer-session.spec.ts @@ -200,6 +200,11 @@ async function mockApi(page: Page, init: Partial = {}): Promise { }); await page.goto(`/reviewer/session?id=${ID}`); await expect(page.getByTestId("session-status")).toHaveText("Skipped"); - await expect(page.getByTestId("session-notice")).toContainText("Only lockfile changes."); - await expect(page.getByTestId("session-outcome")).toHaveCount(0); + await expect(page.getByTestId("session-decision")).toContainText("No review needed"); + await expect(page.getByTestId("session-why")).toHaveText("Only lockfile changes."); + await expect(page.getByTestId("session-fact")).toHaveCount(0); await mockApi(page, { sessions: [session({ status: "retrying", in_flight: false, finished_at: iso(60), attempt: 1 })] }); await page.goto(`/reviewer/session?id=${ID}`); await expect(page.getByTestId("session-status")).toHaveText("Sent again"); - await expect(page.getByTestId("session-notice")).toContainText("The new try has its own session."); + await expect(page.getByTestId("session-decision")).toContainText("Trying again"); + await expect(page.getByTestId("session-why")).toContainText("the new try has its own page"); await expect(page.getByTestId("session-facts")).toContainText("Review, try 2"); }); @@ -313,7 +325,9 @@ test("a session links back to the review it posted, and a failed one offers a ne await mockApi(page, { sessions: [session({ status: "done", in_flight: false, finished_at: iso(5), verdict: "APPROVE", findings: 0, review_sk: sk })] }); await page.goto(`/reviewer/session?id=${ID}`); await expect(page.getByTestId("session-review-link")).toHaveAttribute("href", /\/reviewer\/detail\/?\?sk=REVIEW%23acme%2Fweb%23000318/); - await expect(page.getByRole("button", { name: /^Review .* again$/ })).toHaveCount(0); + await expect(page.getByTestId("session-review-link")).toHaveText("Rate this review"); + // A finished review can be asked for again; a running one can't. + await expect(page.getByRole("button", { name: "Review acme/web #318 again" })).toBeVisible(); // An older backend leaves review_sk out: no link. await mockApi(page, { sessions: [session({ status: "failed", in_flight: false, finished_at: iso(5), reason: "The model timed out." })] }); @@ -499,7 +513,12 @@ test("the overview says what the PR does, file by file", async ({ page }) => { await mockApi(page, { sessions: [session({ status: "done", in_flight: false, finished_at: iso(5), verdict: "APPROVE", findings: 0, overview: overview(3) })] }); await page.goto(`/reviewer/session?id=${ID}`); const card = page.getByTestId("session-overview"); - await expect(card.getByRole("heading", { name: "PR overview" })).toBeVisible(); + // The opening card says what the change does; the overview is one line until opened. + await expect(page.getByTestId("session-change")).toContainText("Rate-limits the login form by address."); + await expect(card.getByRole("heading", { name: "What the pull request changes" })).toBeVisible(); + await expect(card).toContainText("3 files"); + await expect(page.getByTestId("overview-changes")).toBeHidden(); + await card.getByRole("heading", { name: "What the pull request changes" }).click(); await expect(card).toContainText("Rate-limits the login form by address."); await expect(page.getByTestId("overview-changes").getByRole("listitem")).toHaveText([ "Counts failed logins per address", @@ -548,6 +567,10 @@ test("the file table fits the paths, reads code as code, and stacks on a phone", }); await page.goto(`/reviewer/session?id=${ID}`); const card = page.getByTestId("session-overview"); + await card.getByRole("heading", { name: "What the pull request changes" }).click(); + // A review with a verdict starts with its timeline folded. + await expect(page.getByTestId("session-timeline")).toBeHidden(); + await page.getByTestId("session-activity").getByRole("heading", { name: "Reviewed pull request" }).click(); const table = card.getByRole("table", { name: "Reviewed changes" }); await expect(table.getByRole("columnheader")).toHaveText(["File", "Description"]); await expect(table.getByRole("row")).toHaveCount(4); @@ -594,6 +617,8 @@ test("a large PR's file table starts folded, and nothing scrolls sideways on a p await mockApi(page, { sessions: [session({ status: "done", in_flight: false, finished_at: iso(5), verdict: "APPROVE", overview: big, activity: activity() })] }); await page.goto(`/reviewer/session?id=${ID}`); const card = page.getByTestId("session-overview"); + await expect(card).toContainText("140 files"); + await card.getByRole("heading", { name: "What the pull request changes" }).click(); await expect(card).toContainText("140 changed files"); await expect(card).toContainText("And 120 more files."); const table = card.getByRole("table", { name: "Reviewed changes" }); @@ -603,6 +628,7 @@ test("a large PR's file table starts folded, and nothing scrolls sideways on a p await expect(table.getByRole("row")).toHaveCount(21); await page.setViewportSize({ width: 390, height: 800 }); + await page.getByTestId("session-activity").getByRole("heading", { name: "Reviewed pull request" }).click(); await page.getByTestId("timeline-entry").nth(4).getByText("View 2 files").click(); const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); expect(overflow).toBeLessThanOrEqual(0); diff --git a/dashboard/src/app/reviewer/detail/page.tsx b/dashboard/src/app/reviewer/detail/page.tsx index cd59d38f..ead8d547 100644 --- a/dashboard/src/app/reviewer/detail/page.tsx +++ b/dashboard/src/app/reviewer/detail/page.tsx @@ -9,7 +9,6 @@ import { RoleGuard } from "@/components/role-guard"; import { InlineMarkdown, Markdown } from "@/components/markdown"; import { ChatMarkdown } from "@/components/chat-markdown"; import { MarkdownEditor, clearDraft } from "@/components/markdown-editor"; -import { langFromPath } from "@/lib/highlight"; import { useToast } from "@/components/toast"; import { ReReviewButton } from "@/components/re-review-button"; import { Callout } from "@/components/callout"; @@ -18,10 +17,11 @@ import { Skeleton } from "@/components/skeleton"; import { focusRing, linkButton, primaryButton, secondaryButton } from "@/components/ui"; import { Page, PageHeader, SectionHeading, cardClass } from "@/components/page"; import { ExternalLinkIcon, ThumbsDownIcon, ThumbsUpIcon } from "@/components/icons"; -import { Chip, StatusText, TONES, Time, type Tone } from "@/components/list"; +import { Chip, StatusText, TONES, Time } from "@/components/list"; import { VerdictPill, RiskText } from "../labels"; import { WorkUsedLine } from "@/components/work-used"; -import { bySeverity, fileUrl, reviewParts, type Finding } from "./findings"; +import { bySeverity, reviewParts, type Finding } from "./findings"; +import { FindingCard, SEVERITY_TONE, sentence } from "../finding-card"; import { statusLook } from "../status"; import { isSessionId, sessionForReview, sessionHref } from "../session/session"; import { SessionActivity, SessionOverview } from "../session/sections"; @@ -335,53 +335,6 @@ function Header({ review, title }: { review: Review; title: string }) { ); } -// One severity vocabulary: the same words and colours as the risk on the list. -const SEVERITY_TONE: Record = { - blocking: "danger", - high: "danger", - medium: "waiting", - low: "neutral", - nit: "muted", -}; - -const KIND_WORD: Record = { - defect: "Defect", - concern: "Unverified concern", - question: "Question", - note: "Note", - suggestion: "Suggestion", -}; - -const sentence = (w: string) => (w ? w.charAt(0).toUpperCase() + w.slice(1).replace(/_/g, " ").toLowerCase() : w); - -function FindingCard({ f, repo, sha, id }: { f: Finding; repo: string; sha: string; id: string }) { - const url = fileUrl(repo, sha, f.file, f.line); - const where = f.file ? `${f.file}${f.line > 0 ? `:${f.line}` : ""}` : ""; - return ( -
  • -
    - {sentence(f.severity)} - {f.kind && {KIND_WORD[f.kind] ?? sentence(f.kind)}} -
    -

    {f.title ? {f.title} : "Untitled finding"}

    - {where && - (url ? ( - - {where} - (opens the file on GitHub) - - ) : ( -

    {where}

    - ))} - {f.body && ( -
    - {f.body} -
    - )} -
  • - ); -} - function FindingGroup({ id, title, list, start, repo, sha }: { id: string; title: string; list: Finding[]; start: number; repo: string; sha: string }) { if (list.length === 0) return null; return ( diff --git a/dashboard/src/app/reviewer/finding-card.tsx b/dashboard/src/app/reviewer/finding-card.tsx new file mode 100644 index 00000000..01dd214d --- /dev/null +++ b/dashboard/src/app/reviewer/finding-card.tsx @@ -0,0 +1,93 @@ +"use client"; + +import { InlineMarkdown, Markdown } from "@/components/markdown"; +import { cardClass } from "@/components/page"; +import { Chip, type Tone } from "@/components/list"; +import { focusRing } from "@/components/ui"; +import { langFromPath } from "@/lib/highlight"; +import { fileUrl, type Finding } from "./detail/findings"; + +// One finding as the review page and the session page show it: its severity +// and kind, a title that says what goes wrong, its place linked to the file +// on GitHub at the reviewed commit, and the reasoning with the suggested fix. + +/** One severity vocabulary: the same words and colours as the risk on the list. */ +export const SEVERITY_TONE: Record = { + blocking: "danger", + high: "danger", + medium: "waiting", + low: "neutral", + nit: "muted", +}; + +const KIND_WORD: Record = { + defect: "Defect", + concern: "Unverified concern", + question: "Question", + note: "Note", + suggestion: "Suggestion", +}; + +/** "blocking" → "Blocking"; unknown words still read as words. */ +export const sentence = (w: string) => (w ? w.charAt(0).toUpperCase() + w.slice(1).replace(/_/g, " ").toLowerCase() : w); + +/** "src/a.ts:12", or "" without a file. */ +export function findingPlace(f: Pick): string { + return f.file ? `${f.file}${f.line > 0 ? `:${f.line}` : ""}` : ""; +} + +/** The finding's place, linked to the file at the reviewed commit when it can be. */ +export function FindingPlace({ f, repo, sha }: { f: Finding; repo: string; sha: string }) { + const where = findingPlace(f); + if (!where) return null; + const url = fileUrl(repo, sha, f.file, f.line); + if (!url) return

    {where}

    ; + return ( + + {where} + (opens the file on GitHub) + + ); +} + +export function FindingChips({ f }: { f: Finding }) { + return ( + + {sentence(f.severity)} + {f.kind && {KIND_WORD[f.kind] ?? sentence(f.kind)}} + + ); +} + +export function FindingTitle({ f }: { f: Finding }) { + return f.title ? {f.title} : <>Untitled finding; +} + +/** The finding's reasoning and fix, as the reviewer wrote them. */ +export function FindingBody({ f }: { f: Finding }) { + if (!f.body) return null; + return ( +
    + {f.body} +
    + ); +} + +export function FindingCard({ f, repo, sha, id, accent = false }: { f: Finding; repo: string; sha: string; id?: string; accent?: boolean }) { + return ( +
  • + +

    + +

    + + +
  • + ); +} diff --git a/dashboard/src/app/reviewer/session/page.tsx b/dashboard/src/app/reviewer/session/page.tsx index 7d8a1662..9ba36126 100644 --- a/dashboard/src/app/reviewer/session/page.tsx +++ b/dashboard/src/app/reviewer/session/page.tsx @@ -1,25 +1,40 @@ "use client"; -import { Suspense, useCallback, useEffect, useState } from "react"; +import { Suspense, useCallback, useEffect, useMemo, useState } from "react"; import { useSearchParams } from "next/navigation"; import Link from "next/link"; -import { api, errorStatus, type ReviewSession } from "@/lib/api"; +import { api, errorStatus, type Review, type ReviewSession } from "@/lib/api"; import { RoleGuard } from "@/components/role-guard"; import { Callout } from "@/components/callout"; import { Skeleton } from "@/components/skeleton"; -import { StatusText } from "@/components/list"; import { secondaryButton } from "@/components/ui"; import { ExternalLinkIcon } from "@/components/icons"; import { Page, PageHeader } from "@/components/page"; import { ReReviewButton } from "@/components/re-review-button"; import { useCan } from "@/hooks/use-can"; -import { isSessionId, reviewHref, SESSION_POLL_MS, sessionLook } from "./session"; -import { SessionActivity, SessionFacts, SessionNotice, SessionOutcome, SessionOverview } from "./sections"; +import { ANY_CHANGE } from "@/lib/capabilities"; +import { bySeverity, reviewParts, type Finding } from "../detail/findings"; +import { + checksLabel, + countsLabel, + findingsLabel, + decision, + type FindingCounts, + isPart, + isSessionId, + SESSION_POLL_MS, + partHeading, + timeline, + verificationFromBody, +} from "./session"; +import { SessionActivity, SessionOverview } from "./sections"; +import { BlockingFindings, DecisionCard, DetailsPanel, FindingsError, FindingsLoading, NoteFindings, VerificationCard } from "./summary"; -// One review job, step by step (`?id=`). A PR's "CoderHelm review" -// check links here from its Details link. Each job has its own session, so an -// older check keeps showing its own review. The page refreshes while the -// review runs and the tab is visible. +// One review job (`?id=`): what CoderHelm decided and why, what holds +// the merge, the checks it ran, its notes, and how the review went. A PR's +// "CoderHelm review" check links here from its Details link. Each job has its +// own page, so an older check keeps showing its own review. The page +// refreshes while the review runs and the tab is visible. export default function SessionPageGuarded() { return ( @@ -34,10 +49,10 @@ export default function SessionPageGuarded() { function SessionSkeleton() { return ( -
    +
    - +
    @@ -46,6 +61,53 @@ function SessionSkeleton() { type LoadState = "loading" | "ready" | "missing" | "forbidden" | "error"; +/** The review the session posted, read once it has one: its findings and its own reason. */ +function usePostedReview(sk: string | null | undefined) { + const [review, setReview] = useState(null); + const [state, setState] = useState<"none" | "loading" | "ready" | "error">("none"); + const [attempt, setAttempt] = useState(0); + useEffect(() => { + if (!sk) { + setState("none"); + return; + } + let live = true; + setState("loading"); + api + .getReview(sk) + .then((r) => { + if (!live) return; + setReview(r); + setState("ready"); + }) + .catch(() => live && setState("error")); + return () => { + live = false; + }; + }, [sk, attempt]); + return { review, state, retry: () => setAttempt((n) => n + 1) }; +} + +/** The findings split by whether they hold the merge, most serious first. */ +function splitFindings(review: Review | null) { + if (!review) return null; + const { findings } = reviewParts(review); + const known = findings.every((f) => f.holds !== null); + const blocking: Finding[] = known ? findings.filter((f) => f.holds).sort(bySeverity) : []; + const notes: Finding[] = known ? findings.filter((f) => !f.holds).sort(bySeverity) : []; + const unknown: Finding[] = known ? [] : [...findings].sort(bySeverity); + const counts: FindingCounts = { blocking: blocking.length, notes: notes.length, unknown: unknown.length }; + return { blocking, notes, unknown, counts }; +} + +/** What the reviewer is on now: the newest step, or the newest thing it set out to check. */ +function nowDoing(session: ReviewSession): string { + const all = timeline(session.steps ?? [], session.activity ?? []).filter((e) => e.kind === "step" || e.group.kind === "note"); + const last = all[all.length - 1]; + if (!last) return ""; + return last.kind === "step" ? last.step.text : last.group.title; +} + function SessionPage() { const id = useSearchParams().get("id") || ""; const valid = isSessionId(id); @@ -95,12 +157,54 @@ function SessionPage() { }; }, [inFlight, load]); + const posted = usePostedReview(session?.review_sk); + const split = useMemo(() => splitFindings(posted.review), [posted.review]); + // The timeline starts open while there is no verdict to read (running, + // stopped, read in parts) and folded once there is one. Set once, so it + // never snaps shut while someone is reading it. + const [timelineOpen, setTimelineOpen] = useState(null); + useEffect(() => { + if (session && timelineOpen === null) setTimelineOpen(!(session.status === "done" && !!session.verdict)); + }, [session, timelineOpen]); + if (state === "loading") return ; if (state !== "ready" || !session) return { setState("loading"); load(); }} />; - const look = sessionLook(session.status, session.kind); const prUrl = `https://github.com/${session.repo}/pull/${session.pr_number}`; const name = `${session.repo.split("/").pop()} #${session.pr_number}`; + const sha = posted.review?.head_sha || session.head_sha; + const d = decision(session, { + verdictReason: posted.review?.verdict_reason, + counts: split?.counts ?? null, + now: session.in_flight ? nowDoing(session) : undefined, + }); + const hasVerdict = session.status === "done" && !!session.verdict && !isPart(session); + const bodyChecks = posted.review && !session.verification ? verificationFromBody(posted.review.body) : ""; + const stopped = ["failed", "stalled", "retrying"].includes(session.status); + const mayReview = can("reviews") && !session.in_flight; + // Before the review is read (or on a session that links none), the session's own count stands in. + const counts = !hasVerdict ? "" : split ? countsLabel(split.counts) : (findingsLabel(session.findings) ?? ""); + + const part = isPart(session); + const hasOverview = !!session.overview && (session.overview.files?.length ?? 0) > 0; + const primary = + hasVerdict || hasOverview ? ( + <> + {hasVerdict && posted.state === "loading" && } + {hasVerdict && posted.state === "error" && } + {hasVerdict && split && ( + <> + + {split.unknown.length > 0 && ( + + )} + + )} + {hasVerdict && } + {hasVerdict && split && } + {hasOverview && } + + ) : null; return ( @@ -108,30 +212,42 @@ function SessionPage() { detail crumb={name} title={session.pr_title || `${session.repo} #${session.pr_number}`} - eyebrow="Review session" - status={} + eyebrow="Code review" lead={{session.repo} #{session.pr_number}} actions={ <> - {session.review_sk && ( - - See the findings - - )} - Open on GitHub + Open pull request - (opens in a new tab) + (opens on GitHub in a new tab) - {(session.status === "failed" || session.status === "stalled") && can("reviews") && } + {mayReview && (stopped || hasVerdict) && } } /> - - - - - + + + +
    + {primary &&
    {primary}
    } + +
    + +
    + +
    + {timelineOpen !== null && ( + + )} +
    +
    ); } @@ -141,7 +257,7 @@ function SessionProblem({ state, onRetry }: { state: LoadState; onRetry: () => v return ( -

    Your role can't see reviews. Ask a team admin if you need it.

    +

    Your role can't see reviews. A team admin can change it.

    Back to Runs
    diff --git a/dashboard/src/app/reviewer/session/sections.tsx b/dashboard/src/app/reviewer/session/sections.tsx index 26d4f953..8476883e 100644 --- a/dashboard/src/app/reviewer/session/sections.tsx +++ b/dashboard/src/app/reviewer/session/sections.tsx @@ -1,27 +1,21 @@ "use client"; import type { ReactNode } from "react"; -import type { ActivityGroup, OverviewFile, ReviewSession, SessionStep } from "@/lib/api"; -import { Callout } from "@/components/callout"; +import type { ActivityGroup, OverviewFile, ReviewOverview, ReviewSession, SessionStep } from "@/lib/api"; import { cardClass } from "@/components/page"; -import { formatDate, formatDuration, Time } from "@/components/list"; +import { formatDate, formatDuration } from "@/components/list"; import { FilePath } from "@/components/file-path"; import { Disclosure } from "@/components/disclosure"; import { ChatIcon, CheckIcon, ChevronRightIcon, EyeIcon, ExternalLinkIcon, LayersIcon, PenIcon, SearchIcon, WrenchIcon, XIcon } from "@/components/icons"; import { InlineMarkdown } from "@/components/markdown"; import { focusRing } from "@/components/ui"; -import { VerdictPill } from "../labels"; import { activityHeading, droppedNote, - findingsLabel, - kindLabel, offsetLabel, OVERVIEW_FOLD_AFTER, sessionSeconds, - statusNote, timeline, - triggerLabel, } from "./session"; // The session page's parts. Each takes the session and draws one card, so a @@ -37,7 +31,7 @@ export function SessionCard({ id, title, children, testId }: { id: string; title ); } -function ExternalLink({ href, children }: { href: string; children: ReactNode }) { +export function ExternalLink({ href, children }: { href: string; children: ReactNode }) { return ( {children} @@ -47,79 +41,6 @@ function ExternalLink({ href, children }: { href: string; children: ReactNode }) ); } -function Fact({ label, children }: { label: string; children: ReactNode }) { - return ( -
    -
    {label}
    -
    {children}
    -
    - ); -} - -/** Why it ended without a review, or what its status means. */ -export function SessionNotice({ session }: { session: ReviewSession }) { - const note = statusNote(session.status); - if (!session.reason && !note) return null; - const variant = session.status === "failed" || session.status === "stalled" ? "error" : session.status === "skipped" ? "neutral" : "warning"; - const title = - session.status === "skipped" ? "No review needed" : session.status === "retrying" ? "Sent again" : session.status === "stalled" ? "The review stalled" : "The review didn't finish"; - return ( -
    - - {session.reason &&

    {session.reason}

    } - {note &&

    {note}

    } -
    -
    - ); -} - -/** What asked for it, what kind of job it is, and when it ran. */ -export function SessionFacts({ session, now }: { session: ReviewSession; now: number }) { - const seconds = sessionSeconds(session, now); - const sha = session.head_sha; - return ( - -
    - {triggerLabel(session.trigger)} - {kindLabel(session.kind)}{session.attempt > 0 ? `, try ${session.attempt + 1}` : ""} - {sha && ( - - {sha.slice(0, 7)} - - )} - - {session.started_at ? - - {session.finished_at ? - - {seconds === null ? "Unknown" : formatDuration(seconds)} - -
    -
    - ); -} - -/** The verdict, the findings kept, and the review posted on GitHub. */ -export function SessionOutcome({ session }: { session: ReviewSession }) { - if (session.status !== "done") return null; - const findings = findingsLabel(session.findings); - return ( - -
    - {session.verdict && } - {findings && {findings}} - {session.review_url ? ( - See the review on GitHub - ) : ( - Nothing new was posted on the pull request. - )} -
    -
    - ); -} - // ---- What the reviewer did ------------------------------------------------ const GROUP_ICONS: Record ReactNode> = { @@ -245,7 +166,18 @@ function blocks(session: ReviewSession): { list: Block[]; count: number } { * with what it searched, read and looked up for it as one-line rows, then the * comments it kept and the posting. The newest row pulses while it runs. */ -export function SessionActivity({ session, now, defaultOpen = true }: { session: ReviewSession; now: number; defaultOpen?: boolean }) { +export function SessionActivity({ + session, + now, + defaultOpen = true, + heading, +}: { + session: ReviewSession; + now: number; + defaultOpen?: boolean; + /** The heading in place of the one its status gives. */ + heading?: string; +}) { const { list, count } = blocks(session); const seconds = sessionSeconds(session, now); const live = session.in_flight; @@ -263,7 +195,7 @@ export function SessionActivity({ session, now, defaultOpen = true }: { session:

    - {activityHeading(session.status, session.kind)} + {heading ?? activityHeading(session.status, session.kind)}

    {live ? (