From c370a785704ef57365d3809592ba8e1e2baa93b0 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 3 Nov 2026 08:48:51 -0500 Subject: [PATCH] Review session page: follow one review step by step Adds /reviewer/session?id=, the page a PR's Coderhelm review check links to. It shows the PR, what asked for the review, its status, start and finish times, every step as a timeline (details on demand), and once done the verdict, finding count and a link to the posted review. It refreshes every 4s while the review runs and the tab is visible. The PR page links to its latest session. Docs explain the check. --- dashboard/e2e/reviewer-session.spec.ts | 285 ++++++++++++++++++ dashboard/e2e/wide-data/addresses.ts | 3 +- dashboard/e2e/wide-data/ids.ts | 1 + dashboard/e2e/wide-data/review.ts | 17 +- dashboard/src/app/reviewer/pr/page.tsx | 18 +- dashboard/src/app/reviewer/session/page.tsx | 158 ++++++++++ .../src/app/reviewer/session/sections.tsx | 153 ++++++++++ dashboard/src/app/reviewer/session/session.ts | 114 +++++++ dashboard/src/lib/api-contract.ts | 8 +- dashboard/src/lib/api.ts | 52 ++++ dashboard/src/lib/openapi-fields.ts | 4 +- dashboard/src/lib/routes.ts | 1 + .../content/docs/getting-started/reviewer.mdx | 6 + 13 files changed, 809 insertions(+), 11 deletions(-) create mode 100644 dashboard/e2e/reviewer-session.spec.ts create mode 100644 dashboard/src/app/reviewer/session/page.tsx create mode 100644 dashboard/src/app/reviewer/session/sections.tsx create mode 100644 dashboard/src/app/reviewer/session/session.ts diff --git a/dashboard/e2e/reviewer-session.spec.ts b/dashboard/e2e/reviewer-session.spec.ts new file mode 100644 index 00000000..42429718 --- /dev/null +++ b/dashboard/e2e/reviewer-session.spec.ts @@ -0,0 +1,285 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; +import { + findingsLabel, + isSessionId, + kindLabel, + sessionHref, + sessionLook, + sessionSeconds, + statusNote, + stepOffset, + triggerLabel, +} from "../src/app/reviewer/session/session"; + +// A review's session page: where a PR's "Coderhelm review" check links. Every +// API call is answered here; nothing reaches a real backend. + +const ID = "3f2c9a1e-5b7d-4c8e-9a0b-1c2d3e4f5a6b"; +const now = Date.now(); +const iso = (secsAgo: number) => new Date(now - secsAgo * 1000).toISOString(); + +// ---- The helpers ------------------------------------------------------------ + +test.describe("session helpers", () => { + test("only a job id (a UUID) is a session id", () => { + expect(isSessionId(ID)).toBe(true); + expect(isSessionId(ID.toUpperCase())).toBe(true); + for (const bad of ["", "abc", `${ID}x`, "../REVIEW#acme/web", "3f2c9a1e_5b7d_4c8e_9a0b_1c2d3e4f5a6b"]) { + expect(isSessionId(bad), bad).toBe(false); + } + expect(sessionHref(ID)).toBe(`/reviewer/session?id=${ID}`); + }); + + test("every status reads as words with its tone", () => { + expect(sessionLook("reviewing")).toEqual({ label: "Reviewing", tone: "live", live: true }); + expect(sessionLook("reviewing", "question").label).toBe("Answering"); + expect(sessionLook("done")).toEqual({ label: "Done", tone: "success" }); + expect(sessionLook("skipped").tone).toBe("muted"); + expect(sessionLook("retrying").label).toBe("Sent again"); + expect(sessionLook("failed").tone).toBe("danger"); + expect(sessionLook("stalled")).toEqual({ label: "Stalled", tone: "danger" }); + expect(sessionLook("some_new_state")).toEqual({ label: "Some new state", tone: "muted" }); + expect(statusNote("retrying")).toMatch(/own session/); + expect(statusNote("done")).toBeNull(); + }); + + test("trigger, kind and findings read as plain words", () => { + expect(triggerLabel("label")).toBe("The review label"); + expect(triggerLabel("push")).toBe("New commits"); + expect(triggerLabel("rerequest")).toBe("Asked for again"); + expect(triggerLabel("reply")).toBe("A reply to the reviewer"); + expect(triggerLabel("new_kind")).toBe("New kind"); + expect(triggerLabel("")).toBe("Unknown"); + expect(kindLabel("question")).toBe("Answer to a comment"); + expect(kindLabel("review")).toBe("Review"); + expect(findingsLabel(undefined)).toBeNull(); + expect(findingsLabel(null)).toBeNull(); + expect(findingsLabel(0)).toBe("No findings"); + expect(findingsLabel(1)).toBe("1 finding"); + expect(findingsLabel(3)).toBe("3 findings"); + }); + + test("duration runs to now while in flight and to the finish after", () => { + const start = "2026-10-22T14:18:00+00:00"; + const end = "2026-10-22T14:20:05+00:00"; + expect(sessionSeconds({ started_at: start, finished_at: end, in_flight: false })).toBe(125); + const t = new Date(start).getTime() + 42_000; + expect(sessionSeconds({ started_at: start, finished_at: "", in_flight: true }, t)).toBe(42); + expect(sessionSeconds({ started_at: start, finished_at: "", in_flight: false })).toBeNull(); + expect(sessionSeconds({ started_at: "", finished_at: end, in_flight: false })).toBeNull(); + expect(stepOffset(start, "2026-10-22T14:18:12+00:00")).toBe(12); + expect(stepOffset(start, "not a time")).toBeNull(); + }); +}); + +// ---- The page --------------------------------------------------------------- + +type Session = Record; + +function session(over: Session = {}): Session { + return { + id: ID, + repo: "acme/web", + pr_number: 318, + pr_title: "Rate-limit the login form", + head_sha: "9fceb02d0ae598e95dc970b74767f19372d61af8", + trigger: "push", + kind: "review", + status: "reviewing", + in_flight: true, + attempt: 0, + started_at: iso(90), + finished_at: "", + reason: "", + verdict: "", + findings: null, + review_url: "", + check_run_id: 31337000, + steps: [ + { at: iso(90), text: "Started reviewing `9fceb02`", detail: "" }, + { at: iso(80), text: "Read the change: 2 files changed", detail: "src/auth/login.ts\nsrc/auth/limits.ts" }, + ], + ...over, + }; +} + +interface Backend { + calls: string[]; + /** Answers to /api/reviewer/session, in turn; the last one repeats. */ + sessions: (Session | number)[]; + role: string; + gate?: Record; +} + +async function mockApi(page: Page, init: Partial = {}): Promise { + const db: Backend = { calls: [], sessions: [session()], role: "member", ...init }; + let served = 0; + 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 req = route.request(); + const url = new URL(req.url()); + const p = url.pathname; + db.calls.push(`${req.method()} ${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-01", 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/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/web", enabled: true, ticket_source: "github" }] }); + if (p === "/api/aws-connections") return json(route, { connections: [] }); + if (p === "/api/reviewer/session") { + const answer = db.sessions[Math.min(served, db.sessions.length - 1)]; + served += 1; + if (typeof answer === "number") return json(route, { error: "nope" }, answer); + return json(route, answer); + } + if (p === "/api/reviewer/gate" && db.gate) return json(route, db.gate); + return json(route, { error: `Not mocked: ${req.method()} ${p}` }, 404); + }); + return db; +} + +function watchConsole(page: Page, allowFailedLoads = false) { + 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")) return; + if (allowFailedLoads && text.startsWith("Failed to load resource")) return; + errors.push(text); + }); + page.on("pageerror", (err) => errors.push(err.message)); + return errors; +} + +const sessionCalls = (db: Backend) => db.calls.filter((c) => c.startsWith("GET /api/reviewer/session")); + +test("a running review shows its steps live, then its verdict and the posted review", async ({ page }) => { + const errors = watchConsole(page); + const done = session({ + status: "done", + in_flight: false, + finished_at: iso(5), + verdict: "REQUEST_CHANGES", + findings: 2, + review_url: "https://github.com/acme/web/pull/318#pullrequestreview-2201", + steps: [ + ...(session().steps as unknown[]), + { at: iso(5), text: "Posted the review: 2 findings", detail: "" }, + ], + }); + const db = await mockApi(page, { sessions: [session(), done] }); + await page.goto(`/reviewer/session?id=${ID}`); + await expect(page.getByRole("heading", { level: 1, name: "Rate-limit the login form" })).toBeVisible(); + await expect(page.getByTestId("session-status")).toHaveText("Reviewing"); + await expect(page.getByRole("link", { name: /Open on GitHub/ })).toHaveAttribute("href", "https://github.com/acme/web/pull/318"); + await expect(page.getByTestId("session-facts")).toContainText("New commits"); + await expect(page.getByTestId("session-facts")).toContainText("Still running"); + await expect(page.getByRole("link", { name: /9fceb02/ })).toHaveAttribute("href", "https://github.com/acme/web/commit/9fceb02d0ae598e95dc970b74767f19372d61af8"); + const steps = page.getByTestId("session-steps").getByRole("listitem"); + await expect(steps).toHaveCount(2); + await expect(steps.nth(1)).toContainText("Read the change: 2 files changed"); + // A step's detail opens on demand. + await expect(page.getByText("src/auth/limits.ts")).toBeHidden(); + await steps.nth(1).getByText("More").click(); + await expect(page.getByText(/src\/auth\/limits\.ts/)).toBeVisible(); + await expect(page.getByTestId("session-outcome")).toHaveCount(0); + + // The page refreshes on its own while the review runs, and stops when it ends. + await expect(page.getByTestId("session-status")).toHaveText("Done", { timeout: 10_000 }); + await expect(steps).toHaveCount(3); + const outcome = page.getByTestId("session-outcome"); + await expect(outcome).toContainText("Changes requested"); + await expect(page.getByTestId("session-findings")).toHaveText("2 findings"); + await expect(outcome.getByRole("link", { name: /See the review on GitHub/ })).toHaveAttribute( + "href", + "https://github.com/acme/web/pull/318#pullrequestreview-2201", + ); + await expect(page.getByTestId("session-duration")).toHaveText("1m 25s"); + const calls = sessionCalls(db).length; + await page.waitForTimeout(5_000); + expect(sessionCalls(db).length).toBe(calls); + + // Phone width: nothing scrolls sideways. + await page.setViewportSize({ width: 390, height: 800 }); + const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + expect(overflow).toBeLessThanOrEqual(0); + expect(errors).toEqual([]); +}); + +test("a hidden tab stops refreshing until it is visible again", async ({ page }) => { + const db = await mockApi(page); + await page.goto(`/reviewer/session?id=${ID}`); + await expect(page.getByTestId("session-status")).toHaveText("Reviewing"); + await page.evaluate(() => { + Object.defineProperty(document, "visibilityState", { configurable: true, get: () => "hidden" }); + document.dispatchEvent(new Event("visibilitychange")); + }); + const calls = sessionCalls(db).length; + await page.waitForTimeout(9_000); + expect(sessionCalls(db).length).toBe(calls); + await page.evaluate(() => { + Object.defineProperty(document, "visibilityState", { configurable: true, get: () => "visible" }); + document.dispatchEvent(new Event("visibilitychange")); + }); + await expect.poll(() => sessionCalls(db).length).toBeGreaterThan(calls); +}); + +test("a skipped or retried review says why", async ({ page }) => { + await mockApi(page, { + sessions: [session({ status: "skipped", in_flight: false, finished_at: iso(60), reason: "Only lockfile changes." })], + }); + 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 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-facts")).toContainText("Review, try 2"); +}); + +test("a missing, malformed or forbidden session shows nothing to read", async ({ page }) => { + const errors = watchConsole(page, true); + const db = await mockApi(page, { sessions: [404] }); + await page.goto(`/reviewer/session?id=${ID}`); + await expect(page.getByText("Review not found")).toBeVisible(); + // A malformed id never reaches the API. + const before = sessionCalls(db).length; + await page.goto("/reviewer/session?id=../REVIEW%23acme"); + await expect(page.getByText("Review not found")).toBeVisible(); + expect(sessionCalls(db).length).toBe(before); + + await mockApi(page, { sessions: [403] }); + await page.goto(`/reviewer/session?id=${ID}`); + await expect(page.getByText("You can't open this review")).toBeVisible(); + + await mockApi(page, { sessions: [500, session()] }); + await page.goto(`/reviewer/session?id=${ID}`); + await expect(page.getByText("Could not load the review")).toBeVisible(); + await page.getByRole("button", { name: "Try again" }).click(); + await expect(page.getByTestId("session-status")).toHaveText("Reviewing"); + expect(errors).toEqual([]); +}); + +test("the PR page links to its latest review session", async ({ page }) => { + const gate = { repo: "acme/web", pr_number: 318, pr_title: "Rate-limit the login form", auto_merge: false, status: "reviewing", group: "active", can_control: true, gate: null }; + await mockApi(page, { gate: { ...gate, session_id: ID } }); + await page.goto("/reviewer/pr?repo=acme/web&pr=318"); + const link = page.getByRole("link", { name: "View session" }); + await expect(link).toHaveAttribute("href", new RegExp(`/reviewer/session/?\\?id=${ID}`)); + await link.click(); + await expect(page.getByTestId("session-status")).toHaveText("Reviewing"); + + // No session yet: no link. + await mockApi(page, { gate: { ...gate, session_id: "" } }); + await page.goto("/reviewer/pr?repo=acme/web&pr=318"); + await expect(page.getByRole("heading", { level: 1, name: "Rate-limit the login form" })).toBeVisible(); + await expect(page.getByRole("link", { name: "View session" })).toHaveCount(0); +}); diff --git a/dashboard/e2e/wide-data/addresses.ts b/dashboard/e2e/wide-data/addresses.ts index 0ef4fb3a..01ae35c8 100644 --- a/dashboard/e2e/wide-data/addresses.ts +++ b/dashboard/e2e/wide-data/addresses.ts @@ -1,5 +1,5 @@ import { REPO } from "./long"; -import { ALERT_ID, DRAFT_ID, PLAN_ID, PLUGIN_ID, PLUGIN_RUN_ID, REVIEW_SK, RUN_ID, SUPPORT_TICKET_ID, TEST_ID, TEST_RUN_KEY, TOOL_NAME } from "./ids"; +import { ALERT_ID, DRAFT_ID, PLAN_ID, PLUGIN_ID, PLUGIN_RUN_ID, REVIEW_SK, RUN_ID, SESSION_ID, SUPPORT_TICKET_ID, TEST_ID, TEST_RUN_KEY, TOOL_NAME } from "./ids"; /** * The query an item's page (`detail: true` in lib/routes.ts) is opened with, @@ -12,6 +12,7 @@ export const SAMPLE_QUERY: Record = { // Not an item's page, but its settings form only shows for one repo. "/reviewer/config": `?repo=${encodeURIComponent(REPO)}`, "/reviewer/pr": `?repo=${encodeURIComponent(REPO)}&pr=12345`, + "/reviewer/session": `?id=${SESSION_ID}`, "/tests/run": `?key=${encodeURIComponent(TEST_RUN_KEY)}`, "/tests/test": `?id=${encodeURIComponent(TEST_ID)}`, "/plans/detail": `?id=${PLAN_ID}`, diff --git a/dashboard/e2e/wide-data/ids.ts b/dashboard/e2e/wide-data/ids.ts index ea2b45d9..5708a7cd 100644 --- a/dashboard/e2e/wide-data/ids.ts +++ b/dashboard/e2e/wide-data/ids.ts @@ -2,6 +2,7 @@ import { REPO } from "./long"; // The ids the sample addresses point at; the fixtures answer for these. export const RUN_ID = "01RUNWIDE00000000000000001"; +export const SESSION_ID = "3f2c9a1e-5b7d-4c8e-9a0b-1c2d3e4f5a6b"; export const REVIEW_SK = `REVIEW#${REPO}#012345#2026-01-03T10:00:00Z`; export const TEST_RUN_KEY = "testrun-01WIDE0000000000000001"; export const TEST_ID = "test-01WIDE0000000000000001"; diff --git a/dashboard/e2e/wide-data/review.ts b/dashboard/e2e/wide-data/review.ts index e13543c5..1fa3bdb6 100644 --- a/dashboard/e2e/wide-data/review.ts +++ b/dashboard/e2e/wide-data/review.ts @@ -1,5 +1,5 @@ import type { Handler } from "./index"; -import { ALERT_ID, REVIEW_SK, SUPPORT_TICKET_ID, TEST_ID, TEST_RUN_KEY } from "./ids"; +import { ALERT_ID, REVIEW_SK, SESSION_ID, SUPPORT_TICKET_ID, TEST_ID, TEST_RUN_KEY } from "./ids"; import { ARN, BRANCH, EMAIL, FILE, FILE_2, iso, LOG_GROUP, LONG_URL, MARKDOWN, NOTES, ORG, PR_URL, REPO, REPO_2, SENTENCE, SHA, TICKET, TITLE, TOKEN, } from "./long"; @@ -308,7 +308,20 @@ export const reviewData: Handler = ({ method, path, url }) => { if (path === "/api/reviewer/gate") { return { repo: url.searchParams.get("repo") ?? REPO, pr_number: Number(url.searchParams.get("pr") ?? 12345), pr_title: TITLE, - auto_merge: true, status: "stopped", group: "waiting", can_control: true, gate: GATE, + session_id: SESSION_ID, auto_merge: true, status: "stopped", group: "waiting", can_control: true, gate: GATE, + }; + } + if (path === "/api/reviewer/session") { + return { + id: url.searchParams.get("id") ?? SESSION_ID, repo: REPO, pr_number: 12345, pr_title: TITLE, head_sha: SHA, + trigger: "a_trigger_word_the_dashboard_does_not_know_yet_with_a_long_name", kind: "review", status: "done", in_flight: false, + attempt: 2, started_at: iso(30), finished_at: iso(20), reason: `${SENTENCE} ${TOKEN}`, verdict: "REQUEST_CHANGES", findings: 12, + review_url: `${PR_URL}#pullrequestreview-2201`, check_run_id: 31337000, + steps: [ + { at: iso(30), text: `Started reviewing \`${SHA.slice(0, 7)}\``, detail: "" }, + { at: iso(28), text: `${TITLE} ${TOKEN}`, detail: [FILE, FILE_2, LONG_URL, TOKEN].join("\n") }, + { at: iso(20), text: "Posted the review: 12 findings", detail: SENTENCE }, + ], }; } if (path === "/api/reviewer/org-config") return { instructions: NOTES, web_domains: ["staging.web-platform-frontend-monorepo.example.com", LONG_URL] }; diff --git a/dashboard/src/app/reviewer/pr/page.tsx b/dashboard/src/app/reviewer/pr/page.tsx index 58ccafa6..b904e701 100644 --- a/dashboard/src/app/reviewer/pr/page.tsx +++ b/dashboard/src/app/reviewer/pr/page.tsx @@ -15,6 +15,7 @@ import { Problem } from "@/components/problem"; import { Page, PageHeader, cardClass } from "@/components/page"; import { statusLook, stopperName } from "../status"; import { GATE_ACTION_LABEL } from "../gate-control"; +import { isSessionId, sessionHref } from "../session/session"; // One PR's auto-merge: what it waits on, who stopped it, every stop and // re-arm, and one button to stop or re-arm it. The PR's status comment links @@ -154,11 +155,18 @@ function GatePage() { status={!stopped && (gateState || gate.status) ? : undefined} lead={{gate.repo} #{gate.pr_number}} actions={ - - Open on GitHub - - (opens in a new tab) - + <> + {gate.session_id && isSessionId(gate.session_id) && ( + + View session + + )} + + Open on GitHub + + (opens in a new tab) + + } /> diff --git a/dashboard/src/app/reviewer/session/page.tsx b/dashboard/src/app/reviewer/session/page.tsx new file mode 100644 index 00000000..e0f1b9fb --- /dev/null +++ b/dashboard/src/app/reviewer/session/page.tsx @@ -0,0 +1,158 @@ +"use client"; + +import { Suspense, useCallback, useEffect, useState } from "react"; +import { useSearchParams } from "next/navigation"; +import Link from "next/link"; +import { api, errorStatus, 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 { isSessionId, SESSION_POLL_MS, sessionLook } from "./session"; +import { SessionFacts, SessionNotice, SessionOutcome, SessionTimeline } from "./sections"; + +// 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. + +export default function SessionPageGuarded() { + return ( + + }> + + + + ); +} + +function SessionSkeleton() { + return ( + +
+ + + + +
+
+ ); +} + +type LoadState = "loading" | "ready" | "missing" | "forbidden" | "error"; + +function SessionPage() { + const id = useSearchParams().get("id") || ""; + const valid = isSessionId(id); + const [session, setSession] = useState(null); + const [state, setState] = useState(valid ? "loading" : "missing"); + const [now, setNow] = useState(() => Date.now()); + + const load = useCallback(() => { + if (!valid) return; + api + .getReviewSession(id) + .then((s) => { + setSession(s); + setNow(Date.now()); + setState("ready"); + }) + .catch((e: unknown) => { + const code = errorStatus(e); + // A failed refresh keeps the session on screen; the next one retries. + setState((prev) => + code === 400 || code === 404 ? "missing" : code === 403 ? "forbidden" : prev === "ready" ? "ready" : "error", + ); + }); + }, [id, valid]); + + useEffect(() => { + load(); + }, [load]); + + // Refresh while the review runs, only while the tab is visible; coming + // back to the tab refreshes at once. + const inFlight = !!session?.in_flight; + useEffect(() => { + if (!inFlight) return; + const tick = window.setInterval(() => { + if (document.visibilityState === "visible") load(); + }, SESSION_POLL_MS); + const onVisible = () => { + if (document.visibilityState === "visible") load(); + }; + document.addEventListener("visibilitychange", onVisible); + return () => { + window.clearInterval(tick); + document.removeEventListener("visibilitychange", onVisible); + }; + }, [inFlight, load]); + + 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}`; + + return ( + + } + lead={{session.repo} #{session.pr_number}} + actions={ + + Open on GitHub + + (opens in a new tab) + + } + /> + + + + + + ); +} + +function SessionProblem({ state, onRetry }: { state: LoadState; onRetry: () => void }) { + if (state === "forbidden") { + return ( + + +

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

+ Back to Runs +
+
+ ); + } + if (state === "error") { + return ( + + +

Check your connection and try again.

+ +
+
+ ); + } + return ( + + +

+ This link doesn't point to a review of your team. If you belong to more than one team, switch to the team + that owns the repo and open the link again. Older reviews are kept for a while, then removed. +

+ See the Reviewer +
+
+ ); +} diff --git a/dashboard/src/app/reviewer/session/sections.tsx b/dashboard/src/app/reviewer/session/sections.tsx new file mode 100644 index 00000000..16ecdb9d --- /dev/null +++ b/dashboard/src/app/reviewer/session/sections.tsx @@ -0,0 +1,153 @@ +"use client"; + +import type { ReactNode } from "react"; +import type { ReviewSession, SessionStep } from "@/lib/api"; +import { Callout } from "@/components/callout"; +import { cardClass } from "@/components/page"; +import { formatDate, formatDuration, Time } from "@/components/list"; +import { ExternalLinkIcon } from "@/components/icons"; +import { focusRing } from "@/components/ui"; +import { VerdictPill } from "../labels"; +import { findingsLabel, kindLabel, sessionSeconds, statusNote, stepOffset, triggerLabel } from "./session"; + +// The session page's parts. Each takes the session and draws one card, so a +// new kind of detail is one more section on the page. + +/** A card with a heading; the page stacks these. */ +export function SessionCard({ id, title, children, testId }: { id: string; title: string; children: ReactNode; testId?: string }) { + return ( +
+

{title}

+ {children} +
+ ); +} + +function ExternalLink({ href, children }: { href: string; children: ReactNode }) { + return ( + + {children} + + (opens in a new tab) + + ); +} + +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. + )} +
+
+ ); +} + +function StepRow({ step, startedAt, last, live }: { step: SessionStep; startedAt: string; last: boolean; live: boolean }) { + const offset = stepOffset(startedAt, step.at); + return ( +
  • +
  • + ); +} + +/** Every step so far, oldest first; the last one pulses while it runs. */ +export function SessionTimeline({ session }: { session: ReviewSession }) { + const steps = session.steps ?? []; + return ( + + {steps.length ? ( +
      + {steps.map((s, i) => ( + + ))} +
    + ) : ( +

    No steps yet.

    + )} +
    + ); +} diff --git a/dashboard/src/app/reviewer/session/session.ts b/dashboard/src/app/reviewer/session/session.ts new file mode 100644 index 00000000..ce0be215 --- /dev/null +++ b/dashboard/src/app/reviewer/session/session.ts @@ -0,0 +1,114 @@ +import type { StatusLook } from "@/components/list/status"; + +// Plain words for a review session (`/api/reviewer/session`): its status, what +// asked for it, and how long it took. Pure, so the e2e suite checks them +// directly. + +/** How often an open session page refreshes while the review runs. */ +export const SESSION_POLL_MS = 4_000; + +/** A job id the worker makes (a UUID). Anything else never reaches the API. */ +export function isSessionId(id: string): boolean { + return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id); +} + +const LOOKS: Record = { + reviewing: { label: "Reviewing", tone: "live", live: true }, + done: { label: "Done", tone: "success" }, + skipped: { label: "Skipped", tone: "muted" }, + retrying: { label: "Sent again", tone: "waiting" }, + failed: { label: "Failed", tone: "danger" }, + stalled: { label: "Stalled", tone: "danger" }, +}; + +/** The session's status as a dot and a word. Unknown codes still read as words. */ +export function sessionLook(status: string, kind = "review"): StatusLook { + if (status === "reviewing" && kind === "question") return { label: "Answering", tone: "live", live: true }; + const look = LOOKS[status]; + if (look) return look; + const words = (status || "unknown").replace(/_/g, " ").toLowerCase(); + return { label: words.charAt(0).toUpperCase() + words.slice(1), tone: "muted" }; +} + +/** What a status means, in one sentence, when the status word alone doesn't say. */ +export function statusNote(status: string): string | null { + switch (status) { + case "retrying": + return "This try didn't finish, so Coderhelm sent the review again. The new try has its own session."; + case "stalled": + return "The review stopped without saying how it ended. Ask for a review again on the pull request to start a new one."; + case "failed": + return "The review didn't finish. Nothing new was posted on the pull request."; + default: + return null; + } +} + +const TRIGGERS: Record = { + label: "The review label", + labeled: "The review label", + push: "New commits", + synchronize: "New commits", + opened: "The pull request was opened", + reopened: "The pull request was reopened", + ready_for_review: "The pull request was marked ready", + rerequest: "Asked for again", + reply: "A reply to the reviewer", + sweep: "The reviewer's catch-up check", + reconcile: "The reviewer's catch-up check", +}; + +/** What asked for the review, in words. */ +export function triggerLabel(trigger: string): string { + if (!trigger) return "Unknown"; + const known = TRIGGERS[trigger]; + if (known) return known; + const words = trigger.replace(/_/g, " "); + return words.charAt(0).toUpperCase() + words.slice(1); +} + +/** "Review" or "Answer to a comment". */ +export function kindLabel(kind: string): string { + return kind === "question" ? "Answer to a comment" : "Review"; +} + +function ms(iso: string | null | undefined): number | null { + if (!iso) return null; + const t = new Date(iso).getTime(); + return Number.isNaN(t) ? null : t; +} + +/** + * Seconds from start to finish, or to `now` while it still runs. `null` when + * there is no start, or no finish for a session that is over. + */ +export function sessionSeconds( + s: { started_at: string; finished_at: string; in_flight: boolean }, + now = Date.now(), +): number | null { + const start = ms(s.started_at); + if (start === null) return null; + const end = ms(s.finished_at) ?? (s.in_flight ? now : null); + if (end === null) return null; + return Math.max(0, Math.round((end - start) / 1000)); +} + +/** Seconds from the session's start to one step: "+12s" on the timeline. */ +export function stepOffset(startedAt: string, at: string): number | null { + const start = ms(startedAt); + const t = ms(at); + if (start === null || t === null) return null; + return Math.max(0, Math.round((t - start) / 1000)); +} + +/** "No findings", "1 finding", "3 findings"; `null` before there is a count. */ +export function findingsLabel(n: number | null | undefined): string | null { + if (n === null || n === undefined) return null; + if (n === 0) return "No findings"; + return `${n} finding${n === 1 ? "" : "s"}`; +} + +/** The session page's address for a job id. */ +export function sessionHref(id: string): string { + return `/reviewer/session?${new URLSearchParams({ id })}`; +} diff --git a/dashboard/src/lib/api-contract.ts b/dashboard/src/lib/api-contract.ts index 9a3630f1..0cff90c9 100644 --- a/dashboard/src/lib/api-contract.ts +++ b/dashboard/src/lib/api-contract.ts @@ -1,4 +1,4 @@ -// The dashboard reads runs and plans through the public API, whose schemas +// The dashboard reads runs, plans and review sessions through the public API, whose schemas // are generated from the gateway's code (src/lib/openapi-fields.ts lists their // fields). Each line below fails `npm run typecheck` when the dashboard's type // reads a field the gateway's schema does not have, naming the field, so a @@ -6,7 +6,7 @@ // Nothing here runs; it is checked by the compiler only. import type { OpenApiFields } from "./openapi-fields"; -import type { AnswerRunResult, Plan, Run, RunAnswer, RunDetail, RunQuestion, RunTrigger, Task, api } from "./api"; +import type { AnswerRunResult, Plan, ReviewSession, Run, RunAnswer, RunDetail, RunQuestion, RunTrigger, SessionStep, Task, api } from "./api"; type Answer = Awaited>; @@ -32,3 +32,7 @@ export type PlansPageContract = None, "PlansPag export type PlanContract = None, "PlanWithTasks">>; export type PlanListContract = None, "Plan">>; export type TaskContract = None>; + +// A review's session (the page a PR's "Coderhelm review" check links to). +export type ReviewSessionContract = None>; +export type SessionStepContract = None>; diff --git a/dashboard/src/lib/api.ts b/dashboard/src/lib/api.ts index 032c705b..eff95083 100644 --- a/dashboard/src/lib/api.ts +++ b/dashboard/src/lib/api.ts @@ -1136,6 +1136,9 @@ export const api = { method: "POST", body: JSON.stringify({ sk, rating, comment }), }), + /** One review job step by step: where a PR's "Coderhelm review" check links. */ + getReviewSession: (id: string) => + request(`/api/reviewer/session?id=${encodeURIComponent(id)}`), /** One PR's auto-merge gate: state, checklist, who stopped it, every stop and re-arm. */ getGate: (repo: string, pr: number) => request(`/api/reviewer/gate?${new URLSearchParams({ repo, pr: String(pr) })}`), @@ -1794,6 +1797,8 @@ export interface GateDetail { repo: string; pr_number: number; pr_title?: string; + /** The latest review job's session (`getReviewSession`); empty before any. */ + session_id?: string; auto_merge: boolean; status?: string; group?: string; @@ -1811,6 +1816,53 @@ export interface GateDetail { } | null; } +/** One step a review went through. */ +export interface SessionStep { + /** RFC 3339. */ + at: string; + /** What happened, in one line. */ + text: string; + /** More about it; empty when there is nothing more. */ + detail: string; +} + +/** + * GET /api/reviewer/session: one review job, step by step. Each job has its + * own session, so an older check on a PR keeps showing its own review. + */ +export interface ReviewSession { + id: string; + /** owner/name */ + repo: string; + pr_number: number; + pr_title: string; + head_sha: string; + /** label · push · rerequest · reply · … */ + trigger: string; + /** review · question */ + kind: string; + /** reviewing · done · skipped · retrying · failed · stalled */ + status: string; + /** True while the review is still running. */ + in_flight: boolean; + /** Which try this job is, from 0. */ + attempt: number; + started_at: string; + /** Empty while it runs. */ + finished_at: string; + /** Why it ended without a review; empty otherwise. */ + reason: string; + /** APPROVE · REQUEST_CHANGES; empty until there is one. */ + verdict: string; + /** How many findings the review kept, once there is a verdict. */ + findings?: number | null; + /** The review posted on GitHub; empty when nothing new was posted. */ + review_url: string; + check_run_id?: number | null; + /** Oldest first. */ + steps: SessionStep[]; +} + export interface GateControlResult { /** stopped · already_stopped · rearmed · rechecking · finished · off */ status: string; diff --git a/dashboard/src/lib/openapi-fields.ts b/dashboard/src/lib/openapi-fields.ts index 37c93b7d..4e39e12f 100644 --- a/dashboard/src/lib/openapi-fields.ts +++ b/dashboard/src/lib/openapi-fields.ts @@ -2,7 +2,7 @@ // docs/api/openapi.json. Do not edit; run `npm run openapi:fields` instead. /** The platform commit this was generated from. */ -export const OPENAPI_REF = "9fba0fd6d5b1c2307e776586f5e5c57e40058628"; +export const OPENAPI_REF = "4af300bd05abf7db9f07f0cfe4e7046098aa0bea"; /** The fields each public API schema has. */ export interface OpenApiFields { @@ -56,6 +56,7 @@ export interface OpenApiFields { ReposList: "repos"; Review: "action_summary" | "applied_standards" | "body" | "created_at" | "findings" | "head_sha" | "posted_as" | "pr_number" | "pr_title" | "rating_comments" | "repo" | "risk" | "sk" | "thumbs_down" | "thumbs_up" | "trigger" | "verdict"; ReviewFinding: "blocks" | "body" | "category" | "end_line" | "evidence" | "file" | "line" | "lookups" | "severity" | "suggestion" | "title"; + ReviewSession: "attempt" | "check_run_id" | "findings" | "finished_at" | "head_sha" | "id" | "in_flight" | "kind" | "pr_number" | "pr_title" | "reason" | "repo" | "review_url" | "started_at" | "status" | "steps" | "trigger" | "verdict"; ReviewsPage: "next" | "reviews"; RotateBody: "overlap_hours"; RotatedSecret: "previous_secret_expires_at" | "secret"; @@ -72,6 +73,7 @@ export interface OpenApiFields { RunTrigger: "by" | "kind" | "label" | "ref" | "ref_url"; RunsPage: "next" | "runs" | "scanned"; SecretView: "previous_secret_expires_at" | "secret"; + SessionStep: "at" | "detail" | "text"; SnsEnvelope: "Message" | "MessageId" | "Signature" | "SignatureVersion" | "SigningCertURL" | "Subject" | "SubscribeURL" | "Timestamp" | "TopicArn" | "Type"; SourceRow: "deliveries" | "direction" | "failed" | "failed_series" | "ok" | "p50_ms" | "p95_ms" | "previous_deliveries" | "previous_success_rate" | "series" | "source" | "success_rate"; Totals: "deliveries" | "failed" | "handled" | "ignored" | "p50_ms" | "p95_ms" | "p99_ms" | "retried" | "retried_ok" | "retries" | "success_rate"; diff --git a/dashboard/src/lib/routes.ts b/dashboard/src/lib/routes.ts index f665bcee..a374cc4a 100644 --- a/dashboard/src/lib/routes.ts +++ b/dashboard/src/lib/routes.ts @@ -25,6 +25,7 @@ export const ROUTES: Record = { "/reviewer": { label: "Reviewer" }, "/reviewer/detail": { label: "Review", parent: "/reviewer", detail: true }, "/reviewer/pr": { label: "Pull request", parent: "/reviewer", detail: true }, + "/reviewer/session": { label: "Review session", parent: "/reviewer", detail: true }, "/reviewer/config": { label: "Settings", parent: "/reviewer", tab: "Reviewer settings" }, "/tests": { label: "Tests" }, diff --git a/docs/content/docs/getting-started/reviewer.mdx b/docs/content/docs/getting-started/reviewer.mdx index 4d87db64..98f4410e 100644 --- a/docs/content/docs/getting-started/reviewer.mdx +++ b/docs/content/docs/getting-started/reviewer.mdx @@ -13,6 +13,12 @@ The reviewer reviews pull requests written by people (and by CoderHelm). It post Add the label to a pull request to get a review. Once a pull request has the label, every new push is reviewed again. Draft pull requests are skipped until they are marked ready. +## Follow a review while it runs + +While a review runs, the pull request shows a **CoderHelm review** check. Its **Details** link opens the review's session in CoderHelm: the steps so far, live while it runs, and the verdict with a link to the posted review once it is done. Each review has its own session, so an older check keeps showing its own review. + +When the review is done, the check ends as neutral if the review has findings, and as success when it found nothing. The check needs the **Checks** permission on the GitHub App. Without it, reviews work as before, just with no check on the pull request. + ## Talk to it on a pull request | Comment | What happens |