From 22fbebb19827dac7aca7a20d7c7d010a139728a0 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 10 Nov 2026 03:37:32 -0500 Subject: [PATCH] Review and run pages: Copilot-style timeline, status first Review detail - Shows the review's own session inline (from session_id, or the PR's latest session when it ran on the same commit as the review): the grouped activity timeline, the PR overview and the reviewed changes table, then the comments. - Summary card lists every finding as one line that jumps to its card, and says where the PR is now, or that a newer review ran. - "What happened after the review" moves up; the rating is compact. Review session - Notes are bold headings with their tool rows (Search, View, Find) nested under them; step text renders inline code. - Failed or stalled reads "Review stopped"; links back to its review (review_sk) and offers Review again to those who may. Run detail - One status block: what is true now, whether it needs a person, what happens next, one primary action. A held PR never says "Finished"; Retry is secondary; questions show even when the PR is held. - The step pills become a vertical timeline of the run's steps in plain words, with durations, notes folded behind a count, the running step pulsing and a live elapsed time, ending on where the run is now. - Waiting for CI shows the PR's checks (failures first, Required, counts, commit) from the new checks field, with a plain fallback. - Links the reviewer's verdict on the run's PR (pr_review); the run's own button is "Address PR comments". - Tasks are ticked only by the plan itself; files changed on the overview with a link to the diff. Types follow platform #546 (session_id, review_sk, checks, pr_review); openapi-fields regenerated at platform main and held by api-contract. --- dashboard/e2e/audit-reviewer.spec.ts | 113 +++- dashboard/e2e/audit-runs.spec.ts | 129 ++++- dashboard/e2e/reviewer-session.spec.ts | 51 +- dashboard/e2e/run-draft-hold.spec.ts | 42 +- dashboard/src/app/reviewer/detail/page.tsx | 207 ++++++-- dashboard/src/app/reviewer/session/page.tsx | 24 +- .../src/app/reviewer/session/sections.tsx | 253 +++++---- dashboard/src/app/reviewer/session/session.ts | 25 + dashboard/src/app/runs/detail/page.tsx | 501 +++++++++--------- .../src/app/runs/detail/run-timeline.tsx | 311 +++++++++++ dashboard/src/components/run-status.tsx | 24 +- dashboard/src/lib/api-contract.ts | 9 +- dashboard/src/lib/api.ts | 41 ++ dashboard/src/lib/openapi-fields.ts | 12 +- dashboard/src/lib/run-timeline.ts | 246 +++++++++ 15 files changed, 1536 insertions(+), 452 deletions(-) create mode 100644 dashboard/src/app/runs/detail/run-timeline.tsx create mode 100644 dashboard/src/lib/run-timeline.ts diff --git a/dashboard/e2e/audit-reviewer.spec.ts b/dashboard/e2e/audit-reviewer.spec.ts index 54f91f43..2c253e4b 100644 --- a/dashboard/e2e/audit-reviewer.spec.ts +++ b/dashboard/e2e/audit-reviewer.spec.ts @@ -26,6 +26,8 @@ function review(over: Record = {}) { thumbs_down: 0, rating_comments: [{ by: "a-person", text: "Right call on the retry.", rating: "up", at: iso(30) }], created_at: iso(5), + // Set only when the review's session page exists. + session_id: null as string | null, ...over, }; } @@ -183,13 +185,18 @@ interface Backend { used: { skills: unknown[]; agents: unknown[]; sources: unknown[]; standards: unknown[] }; /** What GET /api/releases/pending answers. */ pending: { waiting: unknown[]; blocked: unknown[] }; + /** Merged over GET /api/reviewer/gate's answer; `null` answers 404 (a repo the reviewer isn't on). */ + gate: Record | null; + /** GET /api/reviewer/session answers, by id. */ + sessions: Record>; } async function mockApi(page: Page, init: Partial = {}): Promise { const db: Backend = { calls: [], bodies: [], role: "admin", empty: false, failList: false, failMore: false, failConfig: false, failOrg: false, failDetail: false, missingDetail: false, live: livePrs(), noLive: false, - newReviews: [], pending: { waiting: [], blocked: [] }, used: { skills: [], agents: [], sources: [], standards: [] }, ...init, + newReviews: [], pending: { waiting: [], blocked: [] }, used: { skills: [], agents: [], sources: [], standards: [] }, + gate: {}, sessions: {}, ...init, }; const json = (route: Route, body: unknown, status = 200) => route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); @@ -229,10 +236,19 @@ async function mockApi(page: Page, init: Partial = {}): Promise x.sk === sk); + const r = [...db.newReviews, ...REVIEWS, ...DETAIL_REVIEWS].find((x) => x.sk === sk); return r ? json(route, r) : route.fulfill({ status: 404, body: "" }); } if (p === "/api/reviewer/review/rate") return route.fulfill({ status: 200, body: "" }); + if (p === "/api/reviewer/gate") { + if (!db.gate) return json(route, { error: "not found" }, 404); + const pr = Number(url.searchParams.get("pr")); + return json(route, { repo: url.searchParams.get("repo"), pr_number: pr, pr_title: "", session_id: "", auto_merge: false, status: "reviewed", group: "done", gate: null, ...db.gate }); + } + if (p === "/api/reviewer/session") { + const s = db.sessions[url.searchParams.get("id") ?? ""]; + return s ? json(route, s) : json(route, { error: "not found" }, 404); + } if (p === "/api/reviewer/re-review") return json(route, { status: "queued" }); if (p === "/api/reviewer/org-config") { if (req.method() === "PUT") return route.fulfill({ status: 200, body: "" }); @@ -531,7 +547,7 @@ test("findings read from a review's text become cards, grouped into what to fix await expect(header.getByText("Medium risk")).toBeVisible(); await expect(header.getByText("Triggered by new commits")).toBeVisible(); await expect(page.getByTestId("posted-note")).toHaveText( - "Posted as a comment (GitHub doesn't let Coderhelm approve or request changes on a PR it opened).", + "Posted as a comment: Coderhelm opened this PR, and GitHub doesn't let a PR's author approve it.", ); await expect(page.getByText("COMMENT", { exact: true })).toHaveCount(0); @@ -598,6 +614,97 @@ test("findings kept as data show their kind, and a note can be left without rati expect(errors).toEqual([]); }); +// ── The review's session, inline ────────────────────────────────────── + +const SESSION_ID = "3f2c9a1e-5b7d-4c8e-9a0b-1c2d3e4f5a6b"; +const NEWER_ID = "7a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d"; + +/** The session that posted REVIEWS[0] (commit abcdef1, finished as the review was kept). */ +function sessionOf(over: Record = {}) { + return { + id: SESSION_ID, repo: "your-team/web", pr_number: 101, pr_title: "Faster checkout with a clearer receipt page", + head_sha: "abcdef1234567", trigger: "label", kind: "review", status: "done", in_flight: false, attempt: 0, + started_at: iso(7), finished_at: iso(5), reason: "", verdict: "APPROVE", findings: 1, + review_url: "https://github.com/your-team/web/pull/101#pullrequestreview-1", steps: [ + { at: iso(7), text: "Started reviewing `abcdef1`", detail: "" }, + { at: iso(5), text: "Posted the review on GitHub", detail: "" }, + ], + activity: [ + { kind: "note", title: "Checking the retry loop", started_at: iso(6.5), ended_at: iso(6.5), text: "The loop retries on every error, so a declined card is charged again.", items: [] }, + { kind: "view", title: "View 2 files", started_at: iso(6.4), ended_at: iso(6), text: "", items: [ + { at: iso(6.4), label: "src/checkout/pay.ts:1-80", detail: "", failed: false }, + { at: iso(6.2), label: "src/checkout/pay.test.ts", detail: "", failed: false }, + ] }, + ], + review_sk: null, + overview: { summary: "Shows a receipt page after checkout.", changes: ["Adds the receipt page"], files: [{ path: "src/checkout/receipt.tsx", description: "The new page" }], files_total: 1 }, + ...over, + }; +} + +test("a review with its own session shows how it was done, Copilot style, then the comments", async ({ page }) => { + const errors = watchConsole(page); + const own = { ...REVIEWS[0], sk: "REVIEW#your-team/web#000101#2026-01-04T10:00:00Z", pr_title: "Faster checkout with a clearer receipt page", session_id: SESSION_ID }; + const db = await mockApi(page, { newReviews: [own], sessions: { [SESSION_ID]: sessionOf() }, gate: { status: "merged", session_id: NEWER_ID } }); + await page.goto(`/reviewer/detail?sk=${encodeURIComponent(own.sk)}`); + const activity = page.getByTestId("session-activity"); + await expect(activity.getByRole("heading", { name: "Reviewed pull request" })).toBeVisible(); + await expect(activity.getByRole("heading", { level: 3, name: "Checking the retry loop" })).toBeVisible(); + await activity.getByText("View 2 files").click(); + await expect(activity.getByText("src/checkout/pay.ts:1-80")).toBeVisible(); + await expect(page.getByTestId("session-overview").getByRole("table", { name: "Reviewed changes" })).toContainText("src/checkout/receipt.tsx"); + // The PR has moved on since: said beside the verdict, which stays the review's own. + await expect(page.getByTestId("pr-now")).toContainText("Merged"); + await expect(page.getByTestId("review-header").getByText("Approved")).toBeVisible(); + await expect(page.getByTestId("session-page-link")).toHaveAttribute("href", new RegExp(`/reviewer/session/?\\?id=${SESSION_ID}`)); + // Its own session id wins: the PR's latest session is never asked for. + expect(db.calls.some((c) => c.includes(`id=${NEWER_ID}`))).toBe(false); + // Summary, then the session and its overview, then the rating. + const order = await page.evaluate(() => + ["review-summary", "session-activity-title", "session-overview-title", "rate-review"].map((id) => document.getElementById(id)?.getBoundingClientRect().top ?? -1), + ); + expect(order.every((y, i) => y >= 0 && (i === 0 || y > order[i - 1]))).toBe(true); + await shot(page, "audit-reviewer-detail-session"); + expect(errors).toEqual([]); +}); + +test("an older review finds its session through the PR, and never borrows a newer one", async ({ page }) => { + const errors = watchConsole(page); + // No session_id on the record: the PR's latest session is the review's when it ran on the same commit. + await mockApi(page, { sessions: { [SESSION_ID]: sessionOf() }, gate: { session_id: SESSION_ID } }); + await page.goto(`/reviewer/detail?sk=${encodeURIComponent(REVIEWS[0].sk)}`); + await expect(page.getByTestId("session-activity")).toBeVisible(); + await expect(page.getByTestId("newer-review")).toHaveCount(0); + + // The PR's latest session reviewed another commit: no timeline, a pointer to the newer review instead. + await mockApi(page, { sessions: { [NEWER_ID]: sessionOf({ id: NEWER_ID, head_sha: "4e1a2b0c9d8e", started_at: iso(2), finished_at: iso(1) }) }, gate: { session_id: NEWER_ID, status: "waiting_ci" } }); + await page.goto(`/reviewer/detail?sk=${encodeURIComponent(REVIEWS[0].sk)}`); + await expect(page.getByTestId("newer-review")).toContainText("A newer review ran on 4e1a2b0"); + await expect(page.getByTestId("newer-review").getByRole("link", { name: "See it" })).toHaveAttribute("href", new RegExp(`id=${NEWER_ID}`)); + await expect(page.getByTestId("pr-now")).toContainText("Waiting for CI"); + await expect(page.getByTestId("session-activity")).toHaveCount(0); + + // A repo the reviewer isn't on (no gate): the review alone, nothing broken. + await mockApi(page, { gate: null }); + await page.goto(`/reviewer/detail?sk=${encodeURIComponent(REVIEWS[0].sk)}`); + await expect(page.getByRole("region", { name: "Summary" })).toBeVisible(); + await expect(page.getByTestId("session-activity")).toHaveCount(0); + await expect(page.getByTestId("pr-now")).toHaveCount(0); + expect(errors.filter((e) => !e.startsWith("Failed to load resource"))).toEqual([]); +}); + +test("each finding is one line under the summary that jumps to its card", async ({ page }) => { + await mockApi(page); + await page.goto(`/reviewer/detail?sk=${encodeURIComponent(DETAIL_REVIEWS[0].sk)}`); + const index = page.getByTestId("finding-index"); + await expect(index.getByRole("listitem")).toHaveCount(3); + await expect(index.getByRole("listitem").first()).toContainText("Payment can be sent twice"); + await expect(index.getByRole("listitem").first()).toContainText("src/app/checkout/page.tsx:84"); + await index.getByRole("link").first().click(); + await expect(page).toHaveURL(/#finding-1$/); + await expect(page.locator("#finding-1")).toContainText("Payment can be sent twice"); +}); + test("a review page with no ?sk says the link is wrong instead of loading forever", async ({ page }) => { const errors = watchConsole(page); const db = await mockApi(page); diff --git a/dashboard/e2e/audit-runs.spec.ts b/dashboard/e2e/audit-runs.spec.ts index e9279e87..1d9da2ea 100644 --- a/dashboard/e2e/audit-runs.spec.ts +++ b/dashboard/e2e/audit-runs.spec.ts @@ -52,6 +52,9 @@ function baseRun(over: Record = {}) { { message: "Read src/lib/schedule.ts", timestamp: iso(24) }, { message: "Ran npm test -- --run src/lib/schedule.test.ts and every test passed after the change", timestamp: iso(17) }, ], + // Null when the run has no open pull request or GitHub couldn't be read; null before a review. + checks: null, + pr_review: null, ...over, }; } @@ -227,10 +230,25 @@ test("a finished run shows its pull request, steps, documents and tasks without await expect(page.getByText("Done", { exact: true }).first()).toBeVisible(); // The outcome leads, with the one next step: open the pull request. const outcome = page.getByTestId("run-outcome"); - await expect(outcome).toContainText("Done. The change is ready for review."); + await expect(outcome).toContainText("Pull request #101 is ready for review"); + await expect(page.getByTestId("run-who")).toHaveText("Needs a person"); + await expect(page.getByTestId("run-next")).toContainText("Someone on your team reviews and merges it."); await expect(outcome.getByRole("link", { name: /Open pull request #101/ })).toHaveAttribute("href", "https://github.com/your-team/web/pull/101"); - // Step names are words, not the worker's ids. - await expect(page.getByRole("list", { name: "Steps" })).toContainText("Pull request"); + // The steps read as what Coderhelm did, in words, not the worker's ids, ending on where the run is. + const steps = page.getByRole("list", { name: "Steps" }); + await expect(steps.getByTestId("run-step")).toHaveText([/Read the ticket/, /Planned the change/, /Built the change/, /Ran the tests/, /Opened pull request #101/, /Checked the pull request/, /Handed pull request #101 over for review/]); + await expect(steps.locator('[data-state="done"]')).toHaveCount(7); + // Each step's notes fold behind a count; the build's opens to what it did. + const build = steps.getByTestId("run-step").nth(2); + await expect(build).toContainText("1 note"); + await expect(build).toContainText("7m 0s"); + await build.getByText("Built the change").click(); + await expect(build.getByTestId("step-notes")).toContainText("Read src/lib/schedule.ts"); + // The files the run changed, with the diff on GitHub. + await expect(page.getByTestId("run-files")).toContainText("schedule.ts"); + await expect(page.getByTestId("run-files").getByRole("link", { name: /See the diff on GitHub/ })).toHaveAttribute("href", "https://github.com/your-team/web/pull/101/files"); + // Tasks are ticked only by the plan itself, never guessed from the run's status. + await expect(page.getByText("3 tasks")).toBeVisible(); await expect(page.getByText("Tasks", { exact: true })).toBeVisible(); await expect(page.getByTestId("stat-time")).toContainText("12m 34s"); // Token parts are technical detail: not on the overview. @@ -242,7 +260,8 @@ test("a finished run shows its pull request, steps, documents and tasks without await expect(page.getByText("Linear")).toBeVisible(); await expect(page.getByRole("heading", { name: /Files changed/ })).toBeVisible(); await openTab(page, "Activity"); - await expect(page.getByText("Build started")).toBeVisible(); + // The steps live on the overview; Activity doesn't repeat them. + await expect(page.getByRole("list", { name: "Steps" })).toHaveCount(0); await openTab(page, "Details"); // Trace names read as words too ("CI fix #2", not "ci_fix:2"). await expect(page.getByText("CI fix #2")).toBeVisible(); @@ -326,14 +345,13 @@ test("a run whose fix is outside the code shows what to change there and opens n // The box has its own heading; the report's first line is not repeated as text. await expect(report.getByText("Needs a change outside the code")).toHaveCount(0); await expect(page.getByRole("link", { name: /pull request #/i })).toHaveCount(0); - // Triage and plan are done; nothing after them ran, on purpose. - await expect(page.getByRole("list", { name: "Steps" }).locator("svg")).toHaveCount(2); + // Triage and plan ran; nothing after them ran, on purpose, and the steps end on the report. + const steps = page.getByRole("list", { name: "Steps" }).getByTestId("run-step"); + await expect(steps).toHaveText([/Read the ticket/, /Planned the change/, /Reported the change to make outside the code/]); await shot(page, "runs-detail-outside-code"); await page.getByTestId("page-actions").getByRole("button", { name: "More" }).click(); await expect(page.getByRole("menuitem", { name: /Start over from scratch/ })).toBeVisible(); await page.keyboard.press("Escape"); - await openTab(page, "Activity"); - await expect(page.getByText("Reported the change to make outside the code")).toBeVisible(); expect(errors).toEqual([]); }); @@ -363,9 +381,96 @@ test("a merged run offers no start over, since that would close a merged pull re await expect(page.getByText("Merged", { exact: true }).first()).toBeVisible(); await expect(page.getByTestId("run-outcome")).toContainText("The change was merged"); await expect(page.getByRole("button", { name: "More" })).toHaveCount(0); + await expect(page.getByRole("button", { name: "Address PR comments" })).toHaveCount(0); + await expect(page.getByRole("list", { name: "Steps" }).getByTestId("run-step").last()).toContainText("Pull request #101 merged"); +}); + +// The checks on the run's pull request, as GitHub's merge box says them: +// sorted failed, running, queued, passed, skipped by the server. +const CHECKS = { + sha: "4e1a2b0c9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a", + items: [ + { name: "e2e (chromium)", state: "running", conclusion: null, required: true, started_at: iso(6), completed_at: null, url: "https://github.com/your-team/web/actions/runs/4" }, + { name: "deploy-preview", state: "queued", conclusion: null, required: true, started_at: null, completed_at: null, url: null }, + { name: "build", state: "passed", conclusion: "success", required: true, started_at: iso(9), completed_at: iso(7), url: "https://github.com/your-team/web/actions/runs/1" }, + { name: "lint", state: "passed", conclusion: "success", required: false, started_at: iso(9), completed_at: iso(8), url: "https://github.com/your-team/web/actions/runs/2" }, + ], + counts: { passed: 2, failed: 0, running: 1, queued: 1, skipped: 0 }, +}; + +test("a run waiting for CI says the pull request is open and which checks are still running", async ({ page }) => { + const errors = watchConsole(page); + await mockApi(page, { run: baseRun({ status: "awaiting_ci", duration_s: null, checks: CHECKS }) }); + await page.goto("/runs/detail/?id=01RUNDONE000000000000000A"); + const outcome = page.getByTestId("run-outcome"); + await expect(outcome).toContainText("Pull request #101 is open; waiting for its checks"); + // Never "the change is ready" while checks run. + await expect(outcome).not.toContainText("The change is ready"); + await expect(page.getByTestId("checks-line")).toHaveText("1 running, 1 queued, 2 passed."); + await expect(page.getByTestId("run-who")).toHaveText("Nothing needed from you"); + await expect(page.getByTestId("run-next")).toContainText("If a check fails, Coderhelm fixes it"); + // The steps end on the wait, with the checks: still to finish first, the passed ones folded. + const last = page.getByRole("list", { name: "Steps" }).getByTestId("run-step").last(); + await expect(last).toHaveAttribute("data-state", "waiting"); + await expect(last).toContainText("Waiting for the checks on pull request #101"); + const panel = page.getByTestId("run-checks"); + await expect(panel).toContainText("Some checks haven't finished yet"); + await expect(panel.getByTestId("checks-sentence")).toHaveText("1 running, 1 queued, 2 passed on 4e1a2b0"); + await expect(panel.getByTestId("check").filter({ visible: true })).toHaveText([/e2e \(chromium\)\s*\(running\)\s*Required/, /deploy-preview\s*\(queued\)\s*Required\s*waiting to start/]); + await expect(panel.getByRole("link", { name: /Details for e2e \(chromium\)/ })).toHaveAttribute("href", "https://github.com/your-team/web/actions/runs/4"); + await panel.getByText("2 passed or skipped checks").click(); + await expect(panel.getByTestId("check").filter({ hasText: "build" })).toHaveAttribute("data-group", "passed"); + await shot(page, "runs-detail-awaiting-ci"); + expect(errors).toEqual([]); +}); + +test("a failed check comes first, and an older backend without checks still reads plainly", async ({ page }) => { + const failed = { + ...CHECKS, + items: [{ ...CHECKS.items[0], state: "failed", conclusion: "failure", completed_at: iso(2) }, ...CHECKS.items.slice(2)], + counts: { passed: 2, failed: 1, running: 0, queued: 0, skipped: 0 }, + }; + await mockApi(page, { run: baseRun({ status: "awaiting_ci", duration_s: null, checks: failed }) }); + await page.goto("/runs/detail/?id=01RUNDONE000000000000000A"); + const panel = page.getByTestId("run-checks"); + await expect(panel).toContainText("1 check failed"); + await expect(panel.getByTestId("check").first()).toHaveAttribute("data-group", "failed"); + + // checks: null (no open pull request, or GitHub couldn't be read): a plain line, no panel. + await mockApi(page, { run: baseRun({ status: "awaiting_ci", duration_s: null, checks: null }) }); + await page.goto("/runs/detail/?id=01RUNDONE000000000000000A"); + await expect(page.getByTestId("run-outcome")).toContainText("Coderhelm is watching the checks on GitHub."); + await expect(page.getByTestId("checks-unknown")).toBeVisible(); + await expect(page.getByTestId("run-checks")).toHaveCount(0); +}); + +test("a run links the reviewer's verdict on its own pull request", async ({ page }) => { + await mockApi(page, { + run: baseRun({ pr_review: { verdict: "REQUEST_CHANGES", review_sk: "REVIEW#your-team/web#000101#2026-01-02T10:00:00Z", session_id: null, reviewed_sha: "4e1a2b0c9d8e", at: iso(11) } }), + }); + await page.goto("/runs/detail/?id=01RUNDONE000000000000000A"); + const line = page.getByTestId("run-pr-review"); + await expect(line).toContainText("Changes requested"); + await expect(line).toContainText("on 4e1a2b0"); + await expect(line.getByRole("link", { name: "See the review" })).toHaveAttribute("href", /\/reviewer\/detail\/?\?sk=REVIEW%23your-team%2Fweb%23000101/); + // "Review" means one thing: the reviewer. The run's own button says what it does. + await expect(page.getByRole("button", { name: "Address PR comments" })).toBeVisible(); await expect(page.getByRole("button", { name: "Review again" })).toHaveCount(0); - await openTab(page, "Activity"); - await expect(page.getByText("Pull request merged")).toBeVisible(); +}); + +test("a running run ticks its time, pulses the step it is on and says what is still to come", async ({ page }) => { + await mockApi(page, { + run: baseRun({ status: "running", current_pass: "implement", pr_url: null, pr_number: null, duration_s: null, created_at: iso(5), pass_history: [{ pass: "triage", started_at: iso(5) }, { pass: "implement", started_at: iso(2) }], progress_notes: [{ message: "Edited src/lib/schedule.ts", timestamp: iso(1) }] }), + }); + await page.goto("/runs/detail/?id=01RUNDONE000000000000000A"); + const steps = page.getByRole("list", { name: "Steps" }).getByTestId("run-step"); + await expect(steps.last()).toHaveAttribute("data-state", "running"); + await expect(steps.last()).toContainText("Building the change"); + // The running step is open on what it is doing. + await expect(steps.last().getByTestId("step-notes")).toContainText("Edited src/lib/schedule.ts"); + await expect(page.getByTestId("run-upcoming")).toHaveText("Still to come: tests, a security check, the pull request, its checks"); + const before = await page.getByTestId("run-elapsed").textContent(); + await expect.poll(async () => page.getByTestId("run-elapsed").textContent(), { timeout: 5_000 }).not.toBe(before); }); test("start over asks in the app's own dialog, then calls reset", async ({ page }) => { @@ -432,7 +537,7 @@ test("a viewer sees the run but no buttons the server would refuse", async ({ pa await expect(page.getByRole("link", { name: /Open pull request #101/ }).first()).toBeVisible(); await expect(page.getByRole("button", { name: "Retry" })).toHaveCount(0); await expect(page.getByRole("button", { name: /Start over/ })).toHaveCount(0); - await expect(page.getByRole("button", { name: "Review again" })).toHaveCount(0); + await expect(page.getByRole("button", { name: "Address PR comments" })).toHaveCount(0); }); test("a link without a run id explains itself", async ({ page }) => { @@ -550,7 +655,7 @@ test("eight asks group by step, open one at a time, and say what each step did", test("a finished run with an old error says it's done; the old error waits in Activity", async ({ page }) => { await mockApi(page, { run: baseRun({ status: "completed", error: "TypeError: Cannot read properties of undefined (reading 'times')" }) }); await page.goto("/runs/detail/?id=01RUNDONE000000000000000A"); - await expect(page.getByTestId("run-outcome")).toContainText("Done"); + await expect(page.getByTestId("run-outcome")).toContainText("Pull request #101 is ready for review"); await expect(page.getByText(/TypeError/)).toHaveCount(0); await expect(page.getByText("Coderhelm stopped before it finished")).toHaveCount(0); await openTab(page, "Activity"); diff --git a/dashboard/e2e/reviewer-session.spec.ts b/dashboard/e2e/reviewer-session.spec.ts index 9cdfd99b..7462e1b5 100644 --- a/dashboard/e2e/reviewer-session.spec.ts +++ b/dashboard/e2e/reviewer-session.spec.ts @@ -5,6 +5,8 @@ import { findingsLabel, isSessionId, kindLabel, + reviewHref, + sessionForReview, sessionHref, sessionLook, sessionSeconds, @@ -80,6 +82,24 @@ test.describe("session helpers", () => { }); }); +test.describe("review and session", () => { + test("a review shows a session only when it is that review's", () => { + const sha = "9fceb02d0ae598e95dc970b74767f19372d61af8"; + const review = { head_sha: sha, created_at: "2026-10-22T14:20:05Z" }; + const latest = { id: ID, head_sha: sha, finished_at: "2026-10-22T14:20:01Z", in_flight: false }; + // The review's own session wins whatever the PR's latest is. + expect(sessionForReview({ ...review, session_id: ID }, null)).toBe("own"); + // Same commit, finished as the review was kept: this review's session. + expect(sessionForReview(review, latest)).toBe("latest"); + // Another commit, still running, or hours apart: someone else's session. + expect(sessionForReview(review, { ...latest, head_sha: "4e1a2b0" })).toBeNull(); + expect(sessionForReview(review, { ...latest, in_flight: true, finished_at: "" })).toBeNull(); + expect(sessionForReview(review, { ...latest, finished_at: "2026-10-22T18:00:00Z" })).toBeNull(); + expect(sessionForReview(review, null)).toBeNull(); + expect(reviewHref("REVIEW#acme/web#000318#2026-10-22T14:20:05Z")).toBe("/reviewer/detail?sk=REVIEW%23acme%2Fweb%23000318%232026-10-22T14%3A20%3A05Z"); + }); +}); + test.describe("activity helpers", () => { test("steps and activity groups merge into one timeline by time", () => { const at = (s: number) => `2026-10-22T14:18:${String(s).padStart(2, "0")}.000Z`; @@ -100,7 +120,9 @@ test.describe("activity helpers", () => { expect(activityHeading("reviewing")).toBe("Reviewing pull request"); expect(activityHeading("done")).toBe("Reviewed pull request"); expect(activityHeading("reviewing", "question")).toBe("Reading the comment"); - expect(activityHeading("failed")).toBe("Reviewing pull request"); + // Over without a result reads in the past tense, never "Reviewing" under a red status. + expect(activityHeading("failed")).toBe("Review stopped"); + expect(activityHeading("stalled")).toBe("Review stopped"); expect(droppedNote(0)).toBeNull(); expect(droppedNote(undefined)).toBeNull(); expect(droppedNote(1)).toBe("1 more step wasn't recorded."); @@ -131,6 +153,7 @@ function session(over: Session = {}): Session { findings: null, review_url: "", check_run_id: 31337000, + review_sk: null, 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" }, @@ -281,6 +304,24 @@ test("a skipped or retried review says why", async ({ page }) => { await expect(page.getByTestId("session-facts")).toContainText("Review, try 2"); }); +test("a session links back to the review it posted, and a failed one offers a new review", async ({ page }) => { + const errors = watchConsole(page); + const sk = "REVIEW#acme/web#000318#2026-10-22T14:20:05Z"; + 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); + + // 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." })] }); + await page.goto(`/reviewer/session?id=${ID}`); + await expect(page.getByTestId("session-status")).toHaveText("Failed"); + await expect(page.getByTestId("session-review-link")).toHaveCount(0); + await expect(page.getByTestId("session-activity").getByRole("heading", { name: "Review stopped" })).toBeVisible(); + await expect(page.getByRole("button", { name: "Review acme/web #318 again" })).toBeVisible(); + expect(errors).toEqual([]); +}); + 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] }); @@ -405,6 +446,12 @@ test("the activity timeline shows each step live, grouped like a run log", async await expect(entries.nth(2)).toHaveAttribute("data-kind", "note"); await expect(entries.nth(2)).toContainText("Evaluating rate-limit semantics"); await expect(entries.nth(2)).toContainText("The limiter now counts failed logins per address."); + // A note is a heading over what the reviewer did for it, as on Copilot's session log. + await expect(entries.nth(2).getByRole("heading", { level: 3, name: "Evaluating rate-limit semantics" })).toBeVisible(); + await expect(entries.nth(2).getByTestId("timeline-entry")).toHaveCount(2); + // Step text reads code as code, not backticks. + await expect(entries.nth(0).locator("code", { hasText: "9fceb02" })).toBeVisible(); + await expect(entries.nth(0)).not.toContainText("`"); // Only the newest entry runs. await expect(card.locator('[data-state="running"]')).toHaveCount(1); await expect(entries.nth(4)).toHaveAttribute("data-state", "running"); @@ -449,7 +496,7 @@ 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(); + await expect(card.getByRole("heading", { name: "PR overview" })).toBeVisible(); 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", diff --git a/dashboard/e2e/run-draft-hold.spec.ts b/dashboard/e2e/run-draft-hold.spec.ts index 52f87251..93fb715a 100644 --- a/dashboard/e2e/run-draft-hold.spec.ts +++ b/dashboard/e2e/run-draft-hold.spec.ts @@ -2,9 +2,9 @@ import { expect, test, type Page, type Route } from "@playwright/test"; import fs from "node:fs"; import path from "node:path"; -// A run that finished with its pull request still a draft (`draft_hold`) says -// "Finished, PR held" at the top, with the summary and each reason with what -// to do. A run waiting out GitHub's hourly limit (`github_wait`) says when it +// A run whose pull request is still a draft (`draft_hold`) says so at the +// top, never "Finished": the pull request, how many things hold it, and each +// reason with what to do. A run waiting out GitHub's hourly limit (`github_wait`) says when it // goes on, and that nothing is needed. Every API call is answered here. const SHOTS_DIR = process.env.E2E_SHOTS_DIR || path.join("test-results", "shots"); @@ -46,6 +46,8 @@ function run(over: Partial = {}): Run { { pass: "review", started_at: iso(10) }, ], progress_notes: [], + checks: null, + pr_review: null, waiting_on: { action: "Review pull request #318", detail: "It stays a draft until the items below are dealt with.", url: "https://github.com/your-team/web/pull/318", since: iso(5) }, draft_hold: { kind: "held", @@ -95,19 +97,25 @@ async function shot(page: Page, name: string) { await page.screenshot({ path: path.join(SHOTS_DIR, `${name}.png`), fullPage: true }); } -test("a held run reads Finished, PR held, with each reason and what to do", async ({ page }) => { +test("a held run says its pull request is a draft, with each reason and what to do", async ({ page }) => { await mockApi(page, run()); await page.goto("/runs/detail?id=01RUNHOLD"); const outcome = page.getByTestId("run-outcome"); await expect(outcome).toBeVisible(); await expect(outcome).toHaveAttribute("data-tone", "waiting"); - await expect(outcome.getByText("Finished, PR held", { exact: true })).toBeVisible(); + await expect(outcome).toContainText("Pull request #318 is a draft: 2 things to deal with"); + await expect(page.getByText(/Finished/)).toHaveCount(0); + await expect(page.getByTestId("run-who")).toHaveText("Needs a person"); // The status beside the title says the same, not "Needs your answer". - await expect(page.getByText("Finished, PR held", { exact: true })).toHaveCount(2); + await expect(page.getByTestId("page-header").getByText("PR held", { exact: true })).toBeVisible(); await expect(page.getByText("Needs your answer")).toHaveCount(0); - - await expect(page.getByTestId("draft-hold-summary")).toHaveText(/pull request #318 stays a draft: Security items are open/); + // The summary repeats the first reason word for word: the reasons say it once. + await expect(page.getByTestId("draft-hold-summary")).toHaveCount(0); + // Retry is there, but the pull request is the one primary action. + await expect(outcome.getByRole("button", { name: "Retry" })).toBeVisible(); + // The steps end on the hold, waiting on a person. + await expect(page.getByRole("list", { name: "Steps" }).getByTestId("run-step").last()).toHaveAttribute("data-state", "needs_you"); const reasons = page.getByTestId("draft-hold-reasons"); await expect(reasons.getByRole("listitem").filter({ hasText: SECURITY.what })).toContainText(`What to do: ${SECURITY.todo}`); await expect(reasons.getByRole("listitem").filter({ hasText: SANDBOX.what })).toContainText(`What to do: ${SANDBOX.todo}`); @@ -127,18 +135,26 @@ test("a pull request GitHub refused to mark ready reads as needing attention", a await page.goto("/runs/detail?id=01RUNHOLD"); const outcome = page.getByTestId("run-outcome"); await expect(outcome).toHaveAttribute("data-tone", "attention"); - await expect(outcome).toContainText("Finished, PR held: GitHub refused to mark it ready"); + await expect(outcome).toContainText("Pull request #318 couldn't be marked ready"); await expect(outcome).toContainText("What to do: Mark it ready on GitHub"); await expect(outcome).not.toContainText("Held since"); // Not "Done. The change is ready for review." - await expect(page.getByText("Done. The change is ready for review.")).toHaveCount(0); + await expect(page.getByText("Pull request #318 is ready for review")).toHaveCount(0); +}); + +test("a held run that also asked something shows its questions, not only the hold", async ({ page }) => { + await mockApi(page, run({ questions: [{ id: "q1", question: "Should the limit apply to signed-in people too?", why: "It changes who gets locked out.", suggestions: [] }] })); + await page.goto("/runs/detail?id=01RUNHOLD"); + const outcome = page.getByTestId("run-outcome"); + await expect(outcome).toContainText("Pull request #318 is a draft"); + await expect(outcome.getByTestId("run-question")).toContainText("Should the limit apply to signed-in people too?"); }); test("a run with no hold still reads as before", async ({ page }) => { await mockApi(page, run({ status: "completed", waiting_on: null, draft_hold: null })); await page.goto("/runs/detail?id=01RUNHOLD"); - await expect(page.getByTestId("run-outcome")).toContainText("Done. The change is ready for review."); - await expect(page.getByText("Finished, PR held")).toHaveCount(0); + await expect(page.getByTestId("run-outcome")).toContainText("Pull request #318 is ready for review"); + await expect(page.getByText("PR held")).toHaveCount(0); }); test("a run waiting for GitHub's hourly limit says when it goes on", async ({ page }) => { @@ -160,7 +176,7 @@ test("a run waiting for GitHub's hourly limit says when it goes on", async ({ pa test("a finished run ignores a stale GitHub wait", async ({ page }) => { await mockApi(page, run({ status: "completed", waiting_on: null, draft_hold: null, github_wait: "Waiting for GitHub's hourly limit to reset at 21:05 UTC; continues by itself" })); await page.goto("/runs/detail?id=01RUNHOLD"); - await expect(page.getByTestId("run-outcome")).toContainText("Done. The change is ready for review."); + await expect(page.getByTestId("run-outcome")).toContainText("Pull request #318 is ready for review"); await expect(page.getByTestId("github-wait")).toHaveCount(0); }); diff --git a/dashboard/src/app/reviewer/detail/page.tsx b/dashboard/src/app/reviewer/detail/page.tsx index 48f21527..7deccede 100644 --- a/dashboard/src/app/reviewer/detail/page.tsx +++ b/dashboard/src/app/reviewer/detail/page.tsx @@ -4,7 +4,7 @@ import { ANY_CHANGE } from "@/lib/capabilities"; import { Suspense, useEffect, useState, useCallback, useRef } from "react"; import { useSearchParams } from "next/navigation"; import Link from "next/link"; -import { api, type Review } from "@/lib/api"; +import { api, type GateDetail, type Review, type ReviewSession } from "@/lib/api"; import { RoleGuard } from "@/components/role-guard"; import { InlineMarkdown, Markdown } from "@/components/markdown"; import { ChatMarkdown } from "@/components/chat-markdown"; @@ -18,10 +18,13 @@ 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, TONES, Time, type Tone } from "@/components/list"; +import { Chip, StatusText, TONES, Time, type Tone } from "@/components/list"; import { VerdictPill, RiskText } from "../labels"; import { WorkUsedLine } from "@/components/work-used"; import { bySeverity, fileUrl, reviewParts, type Finding } from "./findings"; +import { statusLook } from "../status"; +import { isSessionId, sessionForReview, sessionHref } from "../session/session"; +import { SessionActivity, SessionOverview } from "../session/sections"; export default function ReviewDetailGuarded() { return ( @@ -76,7 +79,7 @@ function postedNote(verdict: string, postedAs: string): string | null { if (verdict === "QUESTION") return "Answered in a comment on the PR."; if (verdict === "COMMENT") return "Posted as a comment. Reviews from before verdicts were always an approval or a change request."; if (postedAs === "COMMENT" && (verdict === "APPROVE" || verdict === "REQUEST_CHANGES")) { - return "Posted as a comment (GitHub doesn't let Coderhelm approve or request changes on a PR it opened)."; + return "Posted as a comment: Coderhelm opened this PR, and GitHub doesn't let a PR's author approve it."; } if (postedAs === "APPROVE") return "Posted on GitHub as an approval."; if (postedAs === "REQUEST_CHANGES") return "Posted on GitHub as a change request."; @@ -131,6 +134,8 @@ function ReviewDetailPage() { }; }, [repo, prNumber, hasTitle]); + const { gate, session, latest } = useReviewSession(review); + if (state === "loading") return ; if (state === "missing" || (state === "ready" && !review)) { return ( @@ -162,8 +167,28 @@ function ReviewDetailPage() { const created = review.created_at && !isNaN(new Date(review.created_at).getTime()) ? review.created_at : ""; return ( - -
+ +
+ + + + {review.action_summary && ( +
+

What happened after the review

+ {review.action_summary} +
+ )} + + {session && ( + <> + + + + )} + + + + - - - {review.action_summary && ( -
-

What happened after the review

- {review.action_summary} -
- )} - - - -

- - More reviews of {shortRepo(review.repo)} - +

+ + + This PR in the reviewer + + {session && ( + + Open the review session + + )} + + More reviews of {shortRepo(review.repo)} + + Something wrong with this review? @@ -207,6 +230,45 @@ function ReviewDetailPage() { const shortRepo = (repo: string) => repo.split("/").pop() || repo; +const prPageHref = (repo: string, pr: number) => `/reviewer/pr?${new URLSearchParams({ repo, pr: String(pr) })}`; + +/** + * The PR's live state (its gate) and the session that produced this review: + * the review's own `session_id`, or the PR's latest session when that one is + * this review (same commit, finished as the review was kept). `latest` is the + * PR's latest session when it is a different, newer review. + */ +function useReviewSession(review: Review | null) { + const [gate, setGate] = useState(null); + const [session, setSession] = useState(null); + const [latest, setLatest] = useState(null); + const repo = review?.repo ?? ""; + const pr = review?.pr_number ?? 0; + const own = review?.session_id ?? ""; + const sha = review?.head_sha ?? ""; + const made = review?.created_at ?? ""; + useEffect(() => { + if (!repo || !pr) return; + let live = true; + (async () => { + const g = await api.getGate(repo, pr).catch(() => null); + if (!live) return; + setGate(g); + const id = own || g?.session_id || ""; + if (!isSessionId(id)) return; + const s = await api.getReviewSession(id).catch(() => null); + if (!live || !s) return; + const which = sessionForReview({ session_id: own, head_sha: sha, created_at: made }, s); + if (which) setSession(s); + else if (!own && s.id !== own) setLatest(s); + })(); + return () => { + live = false; + }; + }, [repo, pr, own, sha, made]); + return { gate, session, latest }; +} + const externalLink = `rounded hover:underline ${focusRing}`; function Header({ review, title }: { review: Review; title: string }) { @@ -287,11 +349,11 @@ const KIND_WORD: Record = { const sentence = (w: string) => (w ? w.charAt(0).toUpperCase() + w.slice(1).replace(/_/g, " ").toLowerCase() : w); -function FindingCard({ f, repo, sha }: { f: Finding; repo: string; sha: string }) { +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)}} @@ -315,53 +377,112 @@ function FindingCard({ f, repo, sha }: { f: Finding; repo: string; sha: string } ); } -function FindingGroup({ id, title, list, repo, sha }: { id: string; title: string; list: Finding[]; repo: string; sha: string }) { +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 ( -
    +
    {title}
      {list.map((f, i) => ( - + ))}
    ); } -function ReviewBody({ review }: { review: Review }) { +/** "1 to fix · 2 notes", or "3 findings" when the record can't tell which hold the merge. */ +function findingGroups(review: Review) { const { summary, findings, rest } = reviewParts(review); const known = findings.every((f) => f.holds !== null); const toFix = known ? findings.filter((f) => f.holds).sort(bySeverity) : []; const notes = known ? findings.filter((f) => !f.holds).sort(bySeverity) : []; + const all = known ? [...toFix, ...notes] : [...findings].sort(bySeverity); const counts = known ? [toFix.length > 0 && `${toFix.length} to fix`, notes.length > 0 && plural(notes.length, "note", "notes")].filter(Boolean).join(" · ") : plural(findings.length, "finding", "findings"); + return { summary, rest, known, toFix, notes, all, counts }; +} + +const findingId = (i: number) => `finding-${i + 1}`; + +/** + * The verdict's card: the summary, then every finding as one line (its + * severity, title and place) that jumps to the finding below, and where the + * PR is now, since a review is a snapshot of one commit. + */ +function ReviewBody({ review, gate, latest }: { review: Review; gate: GateDetail | null; latest: ReviewSession | null }) { + const { summary, all, counts } = findingGroups(review); + // "Reviewed" says nothing the verdict doesn't; every other state is news. + const now = gate?.status && gate.status !== "reviewed" ? statusLook(gate.status) : null; + const newer = latest && latest.head_sha && latest.head_sha !== review.head_sha ? latest : null; return ( - <> -
    -
    -

    Summary

    - {findings.length > 0 && {counts}} -
    -
    - {summary || (findings.length > 0 ? "_No summary._" : "_The review has no text._")} +
    +
    +

    Summary

    + {all.length > 0 && {counts}} +
    +
    + {summary || (all.length > 0 ? "_No summary._" : "_The review has no text._")} +
    + {all.length > 0 && ( +
      + {all.map((f, i) => ( +
    1. + + {sentence(f.severity)} + {f.title ? {f.title} : "Untitled finding"} + {f.file && ( + + {f.file} + {f.line > 0 ? `:${f.line}` : ""} + + )} + +
    2. + ))} +
    + )} + {(now || newer) && ( +
    + {now && ( +

    + The PR now: + +

    + )} + {newer && ( +

    + {newer.in_flight ? "Coderhelm is reviewing a newer commit" : "A newer review ran"} + {newer.head_sha ? <> on {newer.head_sha.slice(0, 7)} : null}.{" "} + + {newer.in_flight ? "Watch it" : "See it"} + +

    + )}
    -
    + )} +
    + ); +} +/** The comments the review left: what to fix first, then the notes. */ +function Findings({ review }: { review: Review }) { + const { known, toFix, notes, all, rest } = findingGroups(review); + return ( + <> {known ? ( <> - - + + ) : ( - + )} - {rest && ( -
    +
    {rest}
    )} @@ -441,7 +562,7 @@ function Rating({ review, onSaved }: { review: Review; onSaved: () => void }) { const total = review.thumbs_up + review.thumbs_down; return ( -
    +

    Was this review right?

    @@ -492,7 +613,7 @@ function Rating({ review, onSaved }: { review: Review; onSaved: () => void }) {
    )} -

    +

    Coderhelm also learns from your replies on the PR on its own, so there is no need to repeat them here.

    diff --git a/dashboard/src/app/reviewer/session/page.tsx b/dashboard/src/app/reviewer/session/page.tsx index b006bd5a..f35368b2 100644 --- a/dashboard/src/app/reviewer/session/page.tsx +++ b/dashboard/src/app/reviewer/session/page.tsx @@ -11,7 +11,9 @@ 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 { 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"; // One review job, step by step (`?id=`). A PR's "Coderhelm review" @@ -50,6 +52,8 @@ function SessionPage() { const [session, setSession] = useState(null); const [state, setState] = useState(valid ? "loading" : "missing"); const [now, setNow] = useState(() => Date.now()); + // Anyone may read a session; asking for a new review is for those who may. + const { can } = useCan(); const load = useCallback(() => { if (!valid) return; @@ -108,11 +112,19 @@ function SessionPage() { status={} lead={{session.repo} #{session.pr_number}} actions={ - - Open on GitHub - - (opens in a new tab) - + <> + {session.review_sk && ( + + See the findings + + )} + + Open on GitHub + + (opens in a new tab) + + {(session.status === "failed" || session.status === "stalled") && can("reviews") && } + } /> diff --git a/dashboard/src/app/reviewer/session/sections.tsx b/dashboard/src/app/reviewer/session/sections.tsx index 5824e4dd..34ac0c49 100644 --- a/dashboard/src/app/reviewer/session/sections.tsx +++ b/dashboard/src/app/reviewer/session/sections.tsx @@ -8,7 +8,8 @@ import { formatDate, formatDuration, Time } from "@/components/list"; import { DataTable } from "@/components/data-table"; import { Code } from "@/components/settings/code"; import { Disclosure } from "@/components/disclosure"; -import { ChatIcon, ChevronRightIcon, EyeIcon, ExternalLinkIcon, LayersIcon, PenIcon, SearchIcon, WrenchIcon } from "@/components/icons"; +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 { @@ -131,154 +132,188 @@ const GROUP_ICONS: Record ReactNode> = { comment: ChatIcon, }; -/** The dot on the timeline's line: pulsing while the entry is the one running now. */ -function Dot({ running }: { running: boolean }) { - return ( - - ); -} - -/** One row of the timeline, with the line down to the next row. */ -function Row({ kind, running, last, children }: { kind: string; running: boolean; last: boolean; children: ReactNode }) { - return ( -
  • -
  • - ); -} - function Offset({ startedAt, at }: { startedAt: string; at: string }) { const label = offsetLabel(startedAt, at, formatDuration); if (!label) return null; return ( -
    ); @@ -310,7 +345,7 @@ export function SessionOverview({ session }: { session: ReviewSession }) { const more = Math.max(0, (o.files_total ?? files.length) - files.length); const total = o.files_total || files.length; return ( - + {o.summary &&

    {o.summary}

    } {changes.length > 0 && ( <> @@ -324,7 +359,7 @@ export function SessionOverview({ session }: { session: ReviewSession }) { )} {files.length > 0 && ( <> -

    Reviewed Changes

    +

    Reviewed changes

    {total === 1 ? "1 changed file" : `${total} changed files`}

    {files.length > OVERVIEW_FOLD_AFTER ? ( diff --git a/dashboard/src/app/reviewer/session/session.ts b/dashboard/src/app/reviewer/session/session.ts index 7dccdfa0..078a75c5 100644 --- a/dashboard/src/app/reviewer/session/session.ts +++ b/dashboard/src/app/reviewer/session/session.ts @@ -152,9 +152,34 @@ export function activityHeading(status: string, kind = "review"): string { if (status === "reviewing") return answering ? "Reading the comment" : "Reviewing pull request"; if (status === "done") return answering ? "Read the comment" : "Reviewed pull request"; if (status === "skipped") return "Looked at the pull request"; + // Over without a result: past tense, never "Reviewing" under a red status. + if (status === "failed" || status === "stalled" || status === "retrying") return answering ? "Stopped reading the comment" : "Review stopped"; return answering ? "Reading the comment" : "Reviewing pull request"; } +/** The review page's address for a review's key. */ +export function reviewHref(sk: string): string { + return `/reviewer/detail?${new URLSearchParams({ sk })}`; +} + +/** + * The session that produced a review: its own `session_id` when the backend + * keeps one; otherwise the PR's latest session, only when that session is + * this review (same commit, finished within minutes of the review being + * kept). Anything else would show an older review someone else's session. + */ +export function sessionForReview( + review: { session_id?: string | null; head_sha: string; created_at: string }, + latest: { id: string; head_sha: string; finished_at: string; in_flight: boolean } | null, +): "own" | "latest" | null { + if (review.session_id) return "own"; + if (!latest || latest.in_flight || !latest.head_sha || latest.head_sha !== review.head_sha) return null; + const made = ms(review.created_at); + const done = ms(latest.finished_at); + if (made === null || done === null) return null; + return Math.abs(made - done) <= 15 * 60_000 ? "latest" : null; +} + /** "+1m 4s" from the session's start; empty without a time. */ export function offsetLabel(startedAt: string, at: string, format: (s: number) => string): string { const s = stepOffset(startedAt, at); diff --git a/dashboard/src/app/runs/detail/page.tsx b/dashboard/src/app/runs/detail/page.tsx index b66beca4..dbe2c6ea 100644 --- a/dashboard/src/app/runs/detail/page.tsx +++ b/dashboard/src/app/runs/detail/page.tsx @@ -33,6 +33,10 @@ import { CodeBlock } from "@/components/code-block"; import { ChevronRightIcon, ExternalLinkIcon } from "@/components/icons"; import { RunTriggerLine } from "@/components/run-trigger"; import { activePass, PASSES, runSteps } from "@/lib/run-steps"; +import { checksSentence, runTimeline, spanSeconds, stillToCome } from "@/lib/run-timeline"; +import { ChecksPanel, FilesChanged, RunTimeline } from "./run-timeline"; +import { VerdictPill } from "@/app/reviewer/labels"; +import { reviewHref } from "@/app/reviewer/session/session"; /** Words people read for each step name the worker records. */ const PASS_LABEL: Record = { @@ -42,7 +46,9 @@ const PASS_LABEL: Record = { test: "Test", security: "Security", pr: "Pull request", - review: "Review", + // After the pull request: its checks and the run's own look at it. Not the + // Reviewer, and not "Address PR comments". + review: "Checks", feedback: "Feedback", ci_fix: "CI fix", }; @@ -79,56 +85,6 @@ function actionError(e: unknown, what: string): string { return `Couldn't ${what}. Try again in a moment.`; } -function PassProgress({ currentPass, status, passHistory, hasPr }: { currentPass?: string; status: string; passHistory?: { pass: string }[]; hasPr: boolean }) { - const { doneIdx, activeIdx } = runSteps({ currentPass, status, passHistory, hasPr }); - const awaiting = status === "awaiting_ci"; - return ( -
      - {PASSES.map((pass, i) => { - const done = i < doneIdx; - const active = i === activeIdx; - const failed = status === "failed" && i === doneIdx; - return ( -
    1. - {i > 0 && ( -
    2. - ); - })} -
    - ); -} - /** A run's four token parts (missing ones count as 0). */ function usageOf(r: RunDetail) { return { @@ -188,41 +144,25 @@ function parseTaskItems(tasks?: string): TaskItem[] { return items; } -/** Check if a task item is done based on run state and file matching. */ -function isTaskDone( - task: TaskItem, - filesModified: string[], - runStatus: string, - maxPassIdx: number, -): boolean { - const section = task.section.toLowerCase(); - const isPostDeploy = section.includes("post-deploy"); - const isVerification = section.includes("verification") && !isPostDeploy; - const isPrereq = section.includes("prerequisit"); - - // If the openspec itself marks it checked, it's done - if (task.checked) return true; - - // For completed runs: all non-post-deploy tasks are done - if (runStatus === "completed" && !isPostDeploy) return true; - - // Prerequisites done once we're past plan - if (isPrereq && maxPassIdx >= 2) return true; - - // Verification done once review pass completed - if (isVerification && (maxPassIdx >= 4 || runStatus === "completed")) return true; - - // File-path matching for real-time progress during implement - if (task.filePaths.length > 0) { - return task.filePaths.some((tp) => - filesModified.some((fm) => fm.endsWith(tp) || tp.endsWith(fm) || fm.includes(tp.replace(/^.*\//, ""))) - ); - } - - // Implementation tasks without file paths: done if we're past implement - if (maxPassIdx >= 3) return true; +/** + * A task is done only when the plan says so (its own checkbox). The run + * doesn't report tasks one by one, so the page never guesses from file + * names or the run's status. + */ +function isTaskDone(task: TaskItem): boolean { + return task.checked; +} - return false; +/** The time now, once a second while `on`: a live elapsed time. */ +function useNow(on: boolean): number { + const [now, setNow] = useState(() => Date.now()); + useEffect(() => { + if (!on) return; + setNow(Date.now()); + const t = window.setInterval(() => setNow(Date.now()), 1000); + return () => window.clearInterval(t); + }, [on]); + return now; } function AgentLogPassView({ pass }: { pass: AgentLogPass }) { @@ -422,6 +362,8 @@ function RunDetailInner() { // Approvals and sign-ins the run's agents asked for: open ones on the overview, the rest in Activity. const asks = useRunApprovals(runId, !!run && (isActive(run.status) || run.status === "needs_input")); + // The elapsed time ticks while the run works or waits. + const now = useNow(!!run && (isActive(run.status) || run.status === "needs_input")); const taskItems = useMemo(() => parseTaskItems(openspec?.tasks), [openspec?.tasks]); @@ -494,7 +436,7 @@ function RunDetailInner() { const showTaskSidebar = taskItems.length > 0 && implementStarted; const filesModified = run.files_modified ?? []; - const doneCount = taskItems.filter((t) => isTaskDone(t, filesModified, run.status, maxPassIdx)).length; + const doneCount = taskItems.filter(isTaskDone).length; // What each action is allowed for, matching the gateway's own checks. const canRetry = ["failed", "needs_input", "needs_outside_change", "covered_by_pr", "cancelled", "closed"].includes(run.status) && run.current_pass !== "feedback"; @@ -660,6 +602,38 @@ function RunDetailInner() { const hasPr = !!run.pr_number || !!run.pr_url || runPrs.length > 0 || (run.pr_urls?.length ?? 0) > 0; // One answer for the steps and the sentence: they can't disagree. const currentStep = PASS_LABEL[activePass(runSteps({ currentPass: run.current_pass, status: run.status, passHistory: run.pass_history, hasPr }), run.current_pass)] ?? null; + // The timeline, the run's time, and what is still to come. + const prNumber = run.pr_number ?? runPrs[0]?.pr_number ?? null; + const prWords = prNumber ? `Pull request #${prNumber}` : "The pull request"; + const steps = runTimeline({ + status: run.status, + current_pass: run.current_pass, + pass_history: run.pass_history, + progress_notes: run.progress_notes, + updated_at: run.updated_at, + created_at: run.created_at, + pr_number: prNumber, + hasPr, + hold: hold?.kind ?? null, + questions: run.status === "needs_input" ? run.questions?.length ?? 0 : 0, + waitingOn: run.status === "needs_input" ? run.waiting_on?.action ?? null : null, + closedBy: run.closed_by, + }); + const upcoming = stillToCome({ status: run.status, current_pass: run.current_pass, pass_history: run.pass_history, hasPr }); + const ticking = isActive(run.status) || run.status === "needs_input"; + const runSecs = ticking ? spanSeconds(run.created_at, null, now) : run.duration_s ?? null; + const elapsed = runSecs ? (ticking ? `${sharedDuration(runSecs)} so far` : `Took ${sharedDuration(runSecs)}`) : ""; + const checks = run.checks && (run.checks.items?.length || run.checks.counts) ? run.checks : null; + const reviewLine = run.pr_review?.review_sk ? ( +

    + Coderhelm's reviewer: + + {run.pr_review.reviewed_sha && on {run.pr_review.reviewed_sha.slice(0, 7)}} + + See the review + +

    + ) : null; const tab: RunTab = (RUN_TABS as readonly string[]).includes(searchParams.get("tab") ?? "") ? (searchParams.get("tab") as RunTab) : "overview"; const tabHref = (t: RunTab) => `/runs/detail?id=${encodeURIComponent(runId)}${t === "overview" ? "" : `&tab=${t}`}`; const sourceWord = run.ticket_source === "jira" ? "Jira ticket" : run.ticket_source === "alert" ? "Alert" : "Issue"; @@ -674,11 +648,14 @@ function RunDetailInner() { (opens in a new tab) )); - const retryButton = canAct && canRetry && ( - - ); + const retryAs = (variant: "primary" | "secondary") => + canAct && + canRetry && ( + + ); + const retryButton = retryAs("primary"); const reviewButton = canAct && canReview && ( ); const helpLink = ( @@ -899,6 +876,7 @@ function RunDetailInner() { action={ <> {retryButton} + {openPrButtons("secondary")} {helpLink} } @@ -929,21 +907,42 @@ function RunDetailInner() { ); } else { // `body` is one sentence; `content` is a block of its own (a form, a list). - const look: { tone: OutcomeTone; title: string; body: React.ReactNode; content?: React.ReactNode; actions?: React.ReactNode } = + // `who`: whether a person must act now ("you") or nothing is needed ("none"). + const look: { tone: OutcomeTone; title: string; body: React.ReactNode; content?: React.ReactNode; actions?: React.ReactNode; next?: React.ReactNode; who?: "you" | "none" } = hold ? { // Finished, and the pull request stays a draft: why, and what to do about each reason. + // Never "Finished": the work isn't handed over while the pull request is held. tone: hold.kind === "failed" ? "attention" : "waiting", - title: hold.kind === "failed" ? "Finished, PR held: GitHub refused to mark it ready" : hold.kind === "waiting" ? "Finished, PR held until a check settles" : "Finished, PR held", - body: {hold.summary}, - content: hold.reasons.length > 0 && ( + title: + hold.kind === "failed" + ? `${prWords} couldn't be marked ready` + : hold.kind === "waiting" + ? `${prWords} stays a draft until a check finishes` + : hold.reasons.length > 1 + ? `${prWords} is a draft: ${hold.reasons.length} things to deal with` + : `${prWords} is a draft: 1 thing to deal with`, + who: hold.kind === "waiting" ? "none" : "you", + next: + hold.kind === "waiting" + ? "Coderhelm marks it ready for review once the check passes." + : hold.kind === "failed" + ? "Mark it ready on GitHub; nothing else is left." + : "Once each item is dealt with, Coderhelm checks again and marks it ready for review.", + // The summary repeats the first reason word for word; it shows only when there are no reasons. + body: hold.reasons.length === 0 ? {hold.summary} : null, + content: (hold.reasons.length > 0 || (run.status === "needs_input" && !!run.questions?.length)) && ( + <> + {hold.reasons.length > 0 && (
      {hold.reasons.map((r, i) => (
    • -

      {r.what}

      +

      + {r.what} +

      What to do: - {r.todo} + {r.todo}

    • ))} @@ -953,11 +952,19 @@ function RunDetailInner() { )}
    + )} + {/* A held run can also have asked something: the hold never hides the questions. */} + {run.status === "needs_input" && !!run.questions?.length && ( +
    + +
    + )} + ), actions: ( <> {openPrButtons("primary")} - {retryButton} + {retryAs("secondary")} ), } @@ -966,6 +973,7 @@ function RunDetailInner() { // GitHub's limit or an outage: the run goes on by itself at the time given. tone: "waiting", title: "Waiting for GitHub", + who: "none", body: ( {githubWait}. Nothing is needed from you. @@ -974,12 +982,14 @@ function RunDetailInner() { actions: openPrButtons("secondary"), } : run.status === "merged" - ? { tone: "success", title: "Done. The change was merged.", body: "The pull request is merged, so the change is in.", actions: openPrButtons("secondary") } + ? { tone: "success", title: "Done. The change was merged.", body: "The pull request is merged, so the change is in.", who: "none", actions: openPrButtons("secondary") } : done ? { tone: "success", - title: prLinks.length ? "Done. The change is ready for review." : "Done.", - body: prLinks.length ? "Coderhelm opened a pull request. Someone on your team reviews and merges it." : "Coderhelm finished this work.", + title: prLinks.length ? `${prWords} is ready for review` : "Done.", + body: prLinks.length ? "Coderhelm finished its work on it and handed it over." : "Coderhelm finished this work.", + who: prLinks.length ? "you" : "none", + next: prLinks.length ? "Someone on your team reviews and merges it." : undefined, actions: ( <> {openPrButtons("primary")} @@ -988,11 +998,19 @@ function RunDetailInner() { ), } : run.status === "awaiting_ci" - ? { tone: "waiting", title: "Waiting for the automated checks", body: "The change is ready. Coderhelm fixes the checks if they fail, then hands it over for review.", actions: openPrButtons("secondary") } + ? { + tone: "waiting", + title: hasPr ? `${prWords} is open; waiting for its checks` : "Waiting for the checks", + body: checks ? {checksSentence(checks)}. : "Coderhelm is watching the checks on GitHub.", + who: "none", + next: "If a check fails, Coderhelm fixes it and pushes again. When they pass, it hands the pull request over for review.", + actions: openPrButtons("secondary"), + } : run.status === "needs_input" && run.questions?.length ? { tone: "waiting", title: "Coderhelm needs your answer", + who: "you", body: null, content: ( {sanitizeError(run.waiting_on.detail)} : null, actions: ( <> @@ -1036,6 +1055,7 @@ function RunDetailInner() { ? { tone: "waiting", title: "Coderhelm needs more detail", + who: "you", body: run.error ? {sanitizeError(run.error)} : "Add the missing detail to the ticket, then retry.", actions: retryButton, } @@ -1056,6 +1076,7 @@ function RunDetailInner() { tone: "live", title: run.status === "running" ? "Coderhelm is working on this" : "About to start", body: run.status === "running" && currentStep ? `Now on the ${currentStep.toLowerCase()} step. This page updates by itself.` : "This page updates by itself.", + who: "none", actions: canAct && run.status === "running" ? ( - )} - {time && ( - - {new Date(time).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" })} - - )} -
    - {expanded && hasTools && ( -
    - {tools.map((t, i) => ( -
    - {t.label} - - {new Date(t.time).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" })} - -
    - ))} -
    - )} -
    - ); -} diff --git a/dashboard/src/app/runs/detail/run-timeline.tsx b/dashboard/src/app/runs/detail/run-timeline.tsx new file mode 100644 index 00000000..d52f47fd --- /dev/null +++ b/dashboard/src/app/runs/detail/run-timeline.tsx @@ -0,0 +1,311 @@ +"use client"; + +import type { ReactNode } from "react"; +import type { RunCheck, RunChecks } from "@/lib/api"; +import { formatDate, formatDuration, Time } from "@/components/list"; +import { CheckIcon, ChevronRightIcon, ExternalLinkIcon, XIcon } from "@/components/icons"; +import { focusRing } from "@/components/ui"; +import { checkGroup, checksHeadline, checksSentence, sortedChecks, spanSeconds, type StepState, type TimelineStep } from "@/lib/run-timeline"; + +// The run page's timeline in the review session's visual language: one +// line per step in plain words with how long it took, its notes folded +// behind a count, the running step pulsing, the step that needs a person or +// failed open by default. Colour sits only on the small mark at the start of +// a row, always beside a word. + +const STATE_WORD: Record = { + done: "done", + running: "running now", + waiting: "waiting", + needs_you: "needs you", + failed: "failed", + stopped: "stopped", +}; + +/** "14:05": a note's time of day; the full date is the hover text. */ +function clock(iso: string): string { + const d = new Date(iso); + return Number.isNaN(d.getTime()) ? "" : d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); +} + +function Mark({ state }: { state: StepState }) { + const box = "inline-flex h-5 w-4 shrink-0 items-center justify-center"; + if (state === "running") return
  • + {step.notes.length > 0 ? ( +
    + + {head} + + {step.notes.length === 1 ? "1 note" : `${step.notes.length} notes`} + + + + +
      + {step.notes.map((n, i) => ( +
    • + {n.message} + {n.timestamp && ( + + )} +
    • + ))} +
    +
    + ) : ( +
    + {head} + +
    + )} + {children &&
    {children}
    } +
  • + ); +} + +/** + * The run's steps, oldest first, ending on where it is now. `end` is drawn + * under the last entry (the checks, a hold's reasons). `upcoming` names what + * the run still has ahead while it works. + */ +export function RunTimeline({ + steps, + now, + elapsed, + heading, + live, + end, + upcoming, +}: { + steps: TimelineStep[]; + now: number; + /** The whole run's time so far or in all. */ + elapsed: string; + heading: string; + live: boolean; + end?: ReactNode; + upcoming: string[]; +}) { + return ( +
    +
    +

    {heading}

    + {live &&
    +
    + {steps.length > 0 ? ( +
      + {steps.map((s, i) => ( + + {i === steps.length - 1 ? end : null} + + ))} +
    + ) : ( +

    {live ? "Starting. The first step shows here in a moment." : "No steps were recorded."}

    + )} + {upcoming.length > 0 && ( +

    + Still to come: {upcoming.join(", ")} +

    + )} +
    +
    + ); +} + +// ---- Checks --------------------------------------------------------------- + +const GROUP_WORD = { failed: "Failed", running: "Running", queued: "Queued", passed: "Passed", skipped: "Skipped" } as const; + +function CheckMark({ c }: { c: RunCheck }) { + const g = checkGroup(c); + const box = "inline-flex h-5 w-4 shrink-0 items-center justify-center"; + if (g === "failed") return ; + if (g === "passed") return ; + if (g === "running") return