From 6d8c46fa8054c38395835433db604d0675bc9f85 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 11:52:38 -0500 Subject: [PATCH 1/6] A Pull requests page: every open pull request, grouped by whose turn it is The new top-level page (/prs) lists every open pull request in the team's installed repos, people's and CoderHelm's, grouped by who has the next move (you, CoderHelm, a person, machines, done). Each row says the one state the server decided and the sentence of what it needs and from whom, with the rule it comes from. CoderHelm shows with its own hexagon face, an AI label and the person it works for. The detail opens beside the list on a wide screen and over it otherwise (full screen on a phone): the path to merge, the wait ledger and the timeline with CoderHelm's runs folded. Saved views, the scope trail (org, then repo) and the filters live in the address. j and k move, Enter opens, Esc closes, / searches. Long lists draw only the rows near the screen, the list is read again only while the tab is visible, and a backend without the endpoint gets a plain note instead of an error. The shared list grows what the page needed: shapes for statuses (never colour alone), row attributes and an eyebrow line on ListRow, a windowed list hook, and a generic AvatarGroup that AvatarStack now uses. --- dashboard/e2e/prs-data.ts | 217 ++++++ dashboard/e2e/prs.spec.ts | 384 +++++++++++ dashboard/e2e/shell-menu.spec.ts | 2 +- dashboard/e2e/shell-nav.spec.ts | 2 +- dashboard/e2e/wide-data/addresses.ts | 2 + dashboard/e2e/wide-data/index.ts | 3 +- dashboard/e2e/wide-data/prs.ts | 59 ++ dashboard/src/app/prs/detail.tsx | 470 +++++++++++++ dashboard/src/app/prs/model.ts | 261 ++++++++ dashboard/src/app/prs/page.tsx | 771 ++++++++++++++++++++++ dashboard/src/components/client-shell.tsx | 3 +- dashboard/src/components/icons.tsx | 2 + dashboard/src/components/list/index.ts | 1 + dashboard/src/components/list/list.tsx | 51 +- dashboard/src/components/list/status.tsx | 52 +- dashboard/src/components/list/windowed.ts | 142 ++++ dashboard/src/components/support.tsx | 44 +- dashboard/src/lib/api.ts | 167 +++++ dashboard/src/lib/nav.ts | 7 +- dashboard/src/lib/routes.ts | 1 + 20 files changed, 2624 insertions(+), 17 deletions(-) create mode 100644 dashboard/e2e/prs-data.ts create mode 100644 dashboard/e2e/prs.spec.ts create mode 100644 dashboard/e2e/wide-data/prs.ts create mode 100644 dashboard/src/app/prs/detail.tsx create mode 100644 dashboard/src/app/prs/model.ts create mode 100644 dashboard/src/app/prs/page.tsx create mode 100644 dashboard/src/components/list/windowed.ts diff --git a/dashboard/e2e/prs-data.ts b/dashboard/e2e/prs-data.ts new file mode 100644 index 00000000..2115111c --- /dev/null +++ b/dashboard/e2e/prs-data.ts @@ -0,0 +1,217 @@ +// Invented pull requests for the Pull requests page: the bookstore's repos +// (acme/web, acme/api, acme/checkout) and its people (octocat, mara, theo, +// jun). Every state the server sends appears at least once. + +import type { PrDetail, PrRow, PrsPage } from "../src/lib/api"; + +const now = Date.now(); +export const ago = (mins: number) => new Date(now - mins * 60_000).toISOString(); + +export const VIEWER = "octocat"; + +type Over = Partial & Pick; + +export function pr(over: Over): PrRow { + const repo = over.repo ?? "acme/web"; + return { + key: `${repo}#${over.number}`, + org: repo.split("/")[0], + repo, + url: `https://github.com/${repo}/pull/${over.number}`, + author: { login: "theo" }, + draft: false, + base: "main", + head: `feature/${over.number}`, + created_at: ago(60 * 30), + updated_at: ago(20), + modifiers: [], + people: [{ login: "mara", roles: ["reviewer"] }], + checks: { total: 12, passed: 12, failed: 0, running: 0, required_failed: [], known: true }, + reviews: { approvals: 0, required: 1, changes_requested_by: [], requested: ["mara"], coderhelm_verdict: null }, + conflict: false, + open_threads: 0, + labels: [], + size: { additions: 120, deletions: 14 }, + last_action: { actor: "theo", text: "pushed 1 commit", at: ago(40) }, + coderhelm: null, + links: [], + waiting_since: ago(90), + ...over, + }; +} + +export const ROWS: PrRow[] = [ + pr({ + number: 88, + repo: "acme/checkout", + title: "Add a gift-wrap option at checkout", + state: "needs_review", + turn: "you", + next: { code: "needs_review", text: "Needs your review: 1 approval (repo rule), asked 2 d ago.", from: ["person:octocat"], since: ago(60 * 48), rule: "repo_rule" }, + reviews: { approvals: 0, required: 1, requested: ["octocat"], coderhelm_verdict: "APPROVE" }, + waiting_since: ago(60 * 48), + }), + pr({ + number: 418, + repo: "acme/api", + title: "Store stock counts as whole numbers", + author: { login: "coderhelm[bot]", coderhelm: true }, + for: "octocat", + state: "needs_decision", + turn: "you", + next: { code: "product_decision", text: "CoderHelm stopped: needs you to pick how old stock counts move over.", from: ["person:octocat"], since: ago(25) }, + coderhelm: { run_id: "run-418", round: 1, working: false, what: "Waiting on a decision" }, + modifiers: ["agent_authored", "large"], + size: { additions: 880, deletions: 120 }, + waiting_since: ago(25), + }), + pr({ + number: 212, + title: "Round cart totals per currency", + author: { login: "coderhelm[bot]", coderhelm: true }, + for: "theo", + state: "coderhelm_working", + turn: "coderhelm", + next: { code: "checks_failing", text: "Checks fail on lint: CoderHelm is fixing them, round 2.", from: ["coderhelm"], since: ago(4), rule: "required_check" }, + checks: { total: 12, passed: 10, failed: 1, running: 1, required_failed: ["lint"], known: true }, + reviews: { approvals: 1, required: 1, requested: [], coderhelm_verdict: null }, + coderhelm: { run_id: "run-212", session_id: "session-212", round: 2, working: true, what: "Fixing CI" }, + last_action: { actor: "coderhelm[bot]", text: "pushed a fix to lint", at: ago(4) }, + links: [{ kind: "depends", repo: "acme/api", number: 418, url: "https://github.com/acme/api/pull/418", state: "needs_decision" }], + modifiers: ["agent_authored", "stacked"], + waiting_since: ago(4), + }), + pr({ + number: 204, + title: "Share a wishlist by link", + author: { login: "sam" }, + state: "changes_requested", + turn: "person", + next: { code: "changes_requested", text: "Changes requested by @mara: @sam to answer them.", from: ["person:sam"], since: ago(60 * 50) }, + modifiers: ["stale"], + waiting_since: ago(60 * 50), + }), + pr({ + number: 210, + title: "Show store hours in the header", + author: { login: "jun" }, + state: "needs_review", + turn: "person", + next: { code: "needs_review", text: "Needs 1 approval (repo rule): @mara asked 1 d ago.", from: ["person:mara"], since: ago(60 * 24), rule: "repo_rule" }, + }), + pr({ + number: 215, + title: "Bump the image library", + author: { login: "jun" }, + state: "checks_running", + turn: "machines", + next: { code: "checks_running", text: "Checks running: 9 of 12 done.", from: ["ci"], since: ago(6), rule: "required_check" }, + checks: { total: 12, passed: 9, failed: 0, running: 3, known: true }, + }), + pr({ + number: 219, + title: "Cache book cover images", + author: { login: "mara" }, + state: "ready_to_merge", + turn: "person", + next: { code: "ready_to_merge", text: "Ready to merge: every requirement is met; @mara merges.", from: ["person:mara"], since: ago(180) }, + reviews: { approvals: 2, required: 2, requested: [], coderhelm_verdict: "APPROVE" }, + }), + pr({ + number: 199, + title: "Fix the author search page size", + state: "unknown", + turn: "machines", + next: { code: "unknown", text: "Unknown: GitHub hasn't said yet whether it merges cleanly.", from: [], since: ago(2) }, + checks: { total: 0, passed: 0, failed: 0, running: 0, known: false }, + }), + pr({ + number: 190, + title: "Paginate the order history", + state: "merged", + turn: "done", + next: { code: "merged", text: "Merged by @mara.", from: [], since: ago(120) }, + }), +]; + +export function page(rows: PrRow[] = ROWS, over: Partial = {}): PrsPage { + const turn: Record = {}; + const state: Record = {}; + const repo: Record = {}; + for (const r of rows) { + turn[r.turn] = (turn[r.turn] ?? 0) + 1; + state[r.state] = (state[r.state] ?? 0) + 1; + repo[r.repo] = (repo[r.repo] ?? 0) + 1; + } + return { + prs: rows, + total: rows.length, + next: null, + counts: { + turn, + state, + repo, + org: { acme: rows.length }, + views: { + my_turn: turn.you ?? 0, + coderhelm_working: state.coderhelm_working ?? 0, + needs_decision: state.needs_decision ?? 0, + ready: (state.ready_to_merge ?? 0) + (state.ready_auto_merge ?? 0), + stale: rows.filter((r) => r.modifiers?.includes("stale")).length, + }, + }, + viewer: VIEWER, + synced_at: ago(1), + sources: [{ name: "webhooks", read: "ok" }, { name: "reconcile", read: "ok", detail: "acme: 9 open pull requests read" }], + ...over, + }; +} + +/** A long list, for the windowed list. */ +export function many(n: number): PrRow[] { + return Array.from({ length: n }, (_, i) => + pr({ + number: 1000 + i, + title: `Bookstore change number ${i + 1}`, + state: "needs_review", + turn: "person", + next: { code: "needs_review", text: `Needs 1 approval (repo rule): @mara asked ${i + 1} h ago.`, from: ["person:mara"], since: ago(60 * (i + 1)) }, + }), + ); +} + +export function detail(row: PrRow = ROWS[2]): PrDetail { + return { + pr: row, + checklist: [ + { key: "checks", mark: "blocked", text: "Required checks 10 of 12: lint failed, CoderHelm is on it", source: "required_check" }, + { key: "approvals", mark: "done", text: "Approvals 1 of 1: @mara", source: "repo_rule" }, + { key: "conflicts", mark: "done", text: "No conflicts with main" }, + { key: "threads", mark: "done", text: "Conversations resolved (3 of 3)" }, + { key: "queue", mark: "none", text: "Merge queue: not used in this repo" }, + ], + ledger: { + open_secs: 97_200, + spans: [], + totals: [ + { who: "person:mara", secs: 46_800 }, + { who: "coderhelm", secs: 3_600 }, + { who: "ci", secs: 14_400 }, + { who: "nobody", secs: 28_800 }, + ], + }, + timeline: [ + { at: ago(4), actor: "coderhelm[bot]", coderhelm: true, kind: "pushed", text: "pushed a fix to lint", run_id: "run-212" }, + { at: ago(6), actor: "coderhelm[bot]", coderhelm: true, kind: "run", text: "read the lint log", run_id: "run-212" }, + { at: ago(10), actor: "ci", kind: "check", text: "lint failed on 4c2d1e0" }, + { at: ago(60 * 3), actor: "mara", kind: "review", text: "approved: looks right once CI is green" }, + { at: ago(60 * 26), actor: "coderhelm[bot]", coderhelm: true, kind: "pushed", text: "opened the pull request", run_id: "run-200" }, + { at: ago(60 * 27), actor: "theo", kind: "comment", text: "asked CoderHelm through WEB-42" }, + ], + runs: [ + { run_id: "run-212", title: "Fix CI (lint)", status: "running", started_at: ago(8), url: "/runs/detail?id=run-212" }, + { run_id: "run-200", title: "Write the pull request", status: "completed", started_at: ago(60 * 27), ended_at: ago(60 * 26), url: "/runs/detail?id=run-200" }, + ], + synced_at: ago(1), + }; +} diff --git a/dashboard/e2e/prs.spec.ts b/dashboard/e2e/prs.spec.ts new file mode 100644 index 00000000..a27cbf84 --- /dev/null +++ b/dashboard/e2e/prs.spec.ts @@ -0,0 +1,384 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; +import fs from "node:fs"; +import path from "node:path"; +import type { PrDetail, PrsPage } from "../src/lib/api"; +import { detail, many, page as prsPage, ROWS } from "./prs-data"; + +// The Pull requests page (/prs): every open pull request grouped by whose +// turn it is, the sentence of what each needs and from whom, the detail with +// its path to merge, wait ledger and timeline, saved views, the keyboard, +// the windowed list, polling only while visible, the empty, error and older +// backend states, and the phone layout. Every API call is answered here. + +interface Backend { + calls: string[]; + /** The answer to /api/prs for its query; a number is an error status. Tests swap it mid-way. */ + list: (url: URL) => PrsPage | number; + detail: PrDetail | number; +} + +async function mockApi(page: Page, init: Partial = {}): Promise { + const db: Backend = { calls: [], list: () => prsPage(), detail: detail(), ...init }; + const json = (route: Route, body: unknown, status = 200) => route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); + await page.route((url) => url.hostname !== "localhost", (route) => route.abort()); + await page.route((url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), async (route) => { + const 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: "octocat", email: "octocat@example.com", avatar_url: "", role: "member" }); + 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/security/overview") return json(route, { enabled: false, dry_run: true, counts: { open: 0, p0: 0, p1: 0 } }); + if (p === "/api/setup") return json(route, { repos: [], new_recommendations: [], auto_setup_new_repos: false }); + if (p === "/api/support/badge") return json(route, { waiting: 0, queue_open: null }); + if (p === "/api/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 }, { name: "acme/api", enabled: true }, { name: "acme/checkout", enabled: true }] }); + if (p === "/api/prs") { + const answer = db.list(url); + if (typeof answer === "number") return json(route, { error: "nope" }, answer); + return json(route, answer); + } + if (p === "/api/prs/detail") { + if (typeof db.detail === "number") return json(route, { error: "nope" }, db.detail); + return json(route, db.detail); + } + return json(route, { error: `Not mocked: ${req.method()} ${p}` }, 404); + }); + return db; +} + +const listCalls = (db: Backend) => db.calls.filter((c) => c.startsWith("GET /api/prs?") || c === "GET /api/prs"); + +const SHOTS = process.env.E2E_SHOTS_DIR; +async function shot(page: Page, name: string) { + if (!SHOTS) return; + fs.mkdirSync(SHOTS, { recursive: true }); + await page.addStyleTag({ content: "nextjs-portal{display:none!important}" }); + await page.waitForTimeout(300); + await page.screenshot({ path: path.join(SHOTS, `${name}.png`), fullPage: false }); +} + +test("pull requests are grouped by whose turn it is, each with what it needs and from whom", async ({ page }) => { + await mockApi(page); + await page.goto("/prs"); + await expect(page.getByRole("heading", { name: "Pull requests", level: 1 })).toBeVisible(); + + // Turn groups in order: yours first, done last (and folded). + const headings = page.locator("[data-testid^=list-section-turn-] h2"); + await expect(headings).toHaveText([/^Your turn/, /^CoderHelm working/, /^A person/, /^Machines/, /^Done/]); + await expect(page.getByTestId("list-section-turn-done").getByTestId("pr-row")).toHaveCount(0); + + // Each row says the block, then who, and the rule's source. + const mine = page.getByTestId("list-section-turn-you").getByTestId("pr-row"); + await expect(mine).toHaveCount(2); + await expect(mine.first().getByTestId("pr-needs")).toHaveText("Needs your review: 1 approval (repo rule), asked 2 d ago."); + await expect(mine.first().getByTestId("pr-next")).toContainText("You"); + + // CoderHelm has its own face and an AI label, and says who it works for. + const helm = page.locator("[data-pr-key='acme/web#212']"); + await expect(helm.getByTestId("coderhelm-avatar").first()).toBeVisible(); + await expect(helm.getByTitle("CoderHelm is an AI agent")).toHaveText("AI"); + await expect(helm.getByText("for @theo")).toBeVisible(); + await expect(helm.getByTestId("pr-next")).toContainText("CoderHelm"); + // The columns: checks, approvals, size, last action. + await expect(helm).toContainText("10/12 checks"); + await expect(helm).toContainText("1/1 approvals"); + await expect(helm).toContainText("last: CoderHelm pushed a fix to lint"); + + // Unknown is shown, never dropped. + await expect(page.locator("[data-pr-key='acme/web#199']")).toContainText("Unknown: not synced"); + + // The scope trail is the address. + await expect(page.getByRole("navigation", { name: "Scope" })).toContainText("All orgs"); + await expect(page.getByTestId("prs-synced")).toContainText("Synced"); + await shot(page, "prs-desktop-list"); +}); + +test("every state reads apart without colour, and every row is named by its sentence", async ({ page }) => { + await mockApi(page); + await page.goto("/prs"); + const row = page.locator("[data-pr-key='acme/web#204']"); + await expect(row).toHaveAttribute("aria-label", /acme\/web 204, Share a wishlist by link\. Changes requested\. Changes requested by @mara: @sam to answer them\. Next: @sam, waiting \d+ (h|d)\. Author @sam\./); + await expect(row).toHaveAttribute("aria-posinset", "1"); + await expect(row).toHaveAttribute("aria-setsize", "3"); + // Shapes differ by state, and the state's words are beside them. + const shapeOf = (key: string) => page.locator(`[data-pr-key='${key}'] svg[data-shape]`).first().getAttribute("data-shape"); + const shapes = new Set([await shapeOf("acme/web#204"), await shapeOf("acme/web#215"), await shapeOf("acme/web#212"), await shapeOf("acme/web#219"), await shapeOf("acme/api#418")]); + expect(shapes.size).toBe(5); + await expect(page.locator("[data-pr-key='acme/web#204']")).toContainText("Changes requested"); +}); + +test("the detail shows the path to merge, the wait ledger and the timeline with CoderHelm's runs folded", async ({ page }) => { + const db = await mockApi(page); + await page.goto("/prs"); + await page.locator("[data-pr-key='acme/web#212']").getByRole("link", { name: "Round cart totals per currency" }).click(); + await expect(page).toHaveURL(/pr=acme%2Fweb%23212/); + const panel = page.getByTestId("pr-detail"); + await expect(panel).toBeVisible(); + await expect(panel.getByRole("heading", { name: "Round cart totals per currency" })).toBeFocused(); + expect(db.calls).toContain("GET /api/prs/detail?repo=acme%2Fweb&number=212"); + + await expect(panel.getByTestId("pr-detail-needs")).toHaveText("Checks fail on lint: CoderHelm is fixing them, round 2."); + const checklist = panel.getByTestId("pr-checklist").locator("li"); + await expect(checklist).toHaveCount(5); + await expect(checklist.first()).toContainText("Blocked: Required checks 10 of 12"); + await expect(checklist.first()).toContainText("(required check)"); + + const ledger = panel.getByTestId("pr-ledger"); + await expect(ledger).toContainText("open 1 d 3 h"); + await expect(ledger.getByRole("img")).toHaveAttribute("aria-label", "Who held it: @mara 13 h, Idle 8 h, CI 4 h, CoderHelm 1 h"); + + // Runs fold: the running one is open, the finished one closed. + const runs = panel.getByTestId("pr-run-block"); + await expect(runs).toHaveCount(2); + await expect(runs.first().getByRole("button")).toHaveAttribute("aria-expanded", "true"); + await expect(runs.first()).toContainText("read the lint log"); + const older = runs.nth(1).getByRole("button"); + await expect(older).toHaveAttribute("aria-expanded", "false"); + await expect(runs.nth(1)).not.toContainText("opened the pull request"); + await older.click(); + await expect(runs.nth(1)).toContainText("opened the pull request"); + + // Filters: People only hides CoderHelm's blocks. + await panel.getByRole("group", { name: "Show in the timeline" }).getByRole("button", { name: "People" }).click(); + await expect(runs).toHaveCount(0); + await expect(panel.getByTestId("pr-timeline")).toContainText("approved: looks right once CI is green"); + + await expect(panel).toContainText("Waits on"); + await expect(panel).toContainText("acme/api#418"); + await shot(page, "prs-desktop-detail"); + + // Esc closes and puts focus back on the row. + await page.keyboard.press("Escape"); + await expect(panel).toHaveCount(0); + await expect(page.locator("[data-pr-key='acme/web#212']")).toBeFocused(); +}); + +test("on a wide screen the pull request opens beside the list, and j and k carry it along", async ({ page }) => { + await page.setViewportSize({ width: 1600, height: 900 }); + await mockApi(page); + await page.goto("/prs?pr=acme%2Fweb%23212"); + const panel = page.getByRole("region", { name: "Round cart totals per currency" }); + await expect(panel).toBeVisible(); + await expect(page.getByTestId("pr-row").first()).toBeVisible(); + await shot(page, "prs-desktop-split"); + await page.locator("[data-pr-key='acme/web#212']").focus(); + await page.keyboard.press("j"); + await expect(page).toHaveURL(/pr=acme%2Fweb%23204/); +}); + +test("saved views and turn filters go to the server and live in the address", async ({ page }) => { + const db = await mockApi(page, { + list: (url) => + url.searchParams.get("view") === "my_turn" + ? prsPage(ROWS.filter((r) => r.turn === "you")) + : url.searchParams.get("turn") === "coderhelm" + ? prsPage(ROWS.filter((r) => r.turn === "coderhelm")) + : prsPage(), + }); + await page.goto("/prs"); + const views = page.getByRole("navigation", { name: "Saved views" }); + await expect(views.getByRole("button", { name: /^My turn 2$/ })).toBeVisible(); + await expect(views.getByRole("button", { name: /^Needs decision 1$/ })).toBeVisible(); + await expect(views.getByRole("button", { name: /^Ready 1$/ })).toBeVisible(); + await expect(views.getByRole("button", { name: /^Stale 1$/ })).toBeVisible(); + await views.getByRole("button", { name: /^My turn/ }).click(); + await expect(page).toHaveURL(/view=my_turn/); + await expect.poll(() => listCalls(db).some((c) => c.includes("view=my_turn"))).toBe(true); + await expect(views.getByRole("button", { name: /^My turn/ })).toHaveAttribute("aria-pressed", "true"); + + await page.getByRole("group", { name: "Whose turn" }).getByRole("button", { name: /CoderHelm working/ }).click(); + await expect(page).toHaveURL(/turn=coderhelm/); + await expect.poll(() => listCalls(db).some((c) => c.includes("turn=coderhelm"))).toBe(true); +}); + +test("the scope trail is the address: org, then repo", async ({ page }) => { + const db = await mockApi(page); + await page.goto("/prs?org=acme&repo=acme/web"); + const scope = page.getByRole("navigation", { name: "Scope" }); + await expect(scope.locator("[aria-current=page]")).toHaveText("web"); + await expect.poll(() => listCalls(db).some((c) => c.includes("org=acme") && c.includes("repo=acme%2Fweb"))).toBe(true); + await scope.getByRole("button", { name: "acme" }).click(); + await expect(page).not.toHaveURL(/repo=/); + await expect(page).toHaveURL(/org=acme/); + await scope.getByRole("button", { name: "All orgs" }).click(); + await expect(page).not.toHaveURL(/org=/); +}); + +test("the keyboard: j and k move, Enter opens, Esc closes, / searches", async ({ page }) => { + const db = await mockApi(page); + await page.goto("/prs"); + await expect(page.getByTestId("pr-row").first()).toBeVisible(); + await page.locator("body").click({ position: { x: 5, y: 5 } }); + await page.keyboard.press("j"); + await expect(page.locator("[data-pr-key='acme/checkout#88']")).toBeFocused(); + await page.keyboard.press("j"); + await expect(page.locator("[data-pr-key='acme/api#418']")).toBeFocused(); + await page.keyboard.press("j"); + await expect(page.locator("[data-pr-key='acme/web#212']")).toBeFocused(); + await page.keyboard.press("k"); + await expect(page.locator("[data-pr-key='acme/api#418']")).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(page.getByTestId("pr-detail")).toBeVisible(); + await expect(page).toHaveURL(/pr=acme%2Fapi%23418/); + await page.keyboard.press("Escape"); + await expect(page.getByTestId("pr-detail")).toHaveCount(0); + await expect(page.locator("[data-pr-key='acme/api#418']")).toBeFocused(); + await page.keyboard.press("/"); + const search = page.getByRole("searchbox", { name: "Search pull requests" }); + await expect(search).toBeFocused(); + await search.fill("gift"); + await search.press("Enter"); + await expect.poll(() => listCalls(db).some((c) => c.includes("q=gift"))).toBe(true); +}); + +test("a long list draws only the rows near the screen", async ({ page }) => { + const rows = many(500); + await mockApi(page, { list: () => prsPage(rows) }); + await page.goto("/prs"); + const list = page.locator("#prs-group-person"); + await expect(list).toHaveAttribute("data-windowed", "true"); + await expect(page.getByTestId("pr-row").first()).toBeVisible(); + const drawn = await page.getByTestId("pr-row").count(); + expect(drawn).toBeGreaterThan(5); + expect(drawn).toBeLessThan(80); + // Every row keeps its place in the whole list. + await expect(page.getByTestId("pr-row").first()).toHaveAttribute("aria-setsize", "500"); + // Scrolled to the end, the last rows are drawn. + await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); + await expect(page.locator("[data-pr-key='acme/web#1499']")).toBeVisible(); + expect(await page.getByTestId("pr-row").count()).toBeLessThan(80); + // The keyboard reaches rows that weren't drawn. + await page.evaluate(() => window.scrollTo(0, 0)); + await page.locator("[data-pr-key='acme/web#1000']").focus(); + for (let i = 0; i < 40; i++) await page.keyboard.press("j"); + await expect(page.locator("[data-pr-key='acme/web#1040']")).toBeFocused(); +}); + +test("the list is read again only while the tab is visible", async ({ page }) => { + await page.clock.install(); + const db = await mockApi(page); + await page.goto("/prs"); + await expect(page.getByTestId("pr-row").first()).toBeVisible(); + const first = listCalls(db).length; + await page.clock.runFor(31_000); + await expect.poll(() => listCalls(db).length).toBe(first + 1); + // Hidden: no reads. + await page.evaluate(() => { + Object.defineProperty(document, "visibilityState", { configurable: true, get: () => "hidden" }); + document.dispatchEvent(new Event("visibilitychange")); + }); + const hidden = listCalls(db).length; + await page.clock.runFor(95_000); + expect(listCalls(db).length).toBe(hidden); + // Back: read at once. + await page.evaluate(() => { + Object.defineProperty(document, "visibilityState", { configurable: true, get: () => "visible" }); + document.dispatchEvent(new Event("visibilitychange")); + }); + await expect.poll(() => listCalls(db).length).toBe(hidden + 1); +}); + +test("a change between reads is said once, not row by row", async ({ page }) => { + await page.clock.install(); + const moved = ROWS.map((r) => (r.key === "acme/web#210" ? { ...r, turn: "you", state: "needs_review" } : r)); + const db = await mockApi(page); + await page.goto("/prs"); + await expect(page.getByTestId("pr-row").first()).toBeVisible(); + db.list = () => prsPage(moved); + await page.clock.runFor(31_000); + await expect(page.getByTestId("prs-announce")).toHaveText("1 pull request changed: 1 now needs you."); +}); + +test("empty, error and older-backend states", async ({ page }) => { + // My turn, empty: says what the others are doing. + await mockApi(page, { list: () => prsPage([], { counts: { turn: { coderhelm: 4, person: 7 } } }) }); + await page.goto("/prs?view=my_turn"); + await expect(page.getByTestId("list-empty")).toContainText("Nothing needs you right now"); + await expect(page.getByTestId("list-empty")).toContainText("CoderHelm is working on 4; 7 are waiting on others."); + + // A filter that matches nothing offers to clear it. + await page.goto("/prs?q=zebra"); + await expect(page.getByTestId("list-empty")).toContainText('Nothing matches "zebra"'); + await page.getByTestId("list-empty").getByRole("button", { name: "Clear filters" }).click(); + await expect(page).not.toHaveURL(/q=zebra/); +}); + +test("a failed read shows the problem and tries again", async ({ page }) => { + const db = await mockApi(page, { list: () => 500 }); + await page.goto("/prs"); + await expect(page.getByTestId("list-error")).toContainText("Couldn't read the pull requests"); + db.list = () => prsPage(); + await page.getByTestId("list-error").getByRole("button", { name: /Try again/ }).click(); + await expect(page.getByTestId("pr-row").first()).toBeVisible(); + expect(listCalls(db).length).toBeGreaterThanOrEqual(2); +}); + +test("a backend without the endpoint says when it arrives, and stops asking", async ({ page }) => { + await page.clock.install(); + const db = await mockApi(page, { list: () => 404 }); + await page.goto("/prs"); + await expect(page.getByTestId("list-empty")).toContainText("Pull requests arrive with CoderHelm's next update"); + await expect(page.getByTestId("list-empty").getByRole("link", { name: "Reviewer" })).toHaveAttribute("href", /^\/reviewer\/?$/); + const n = listCalls(db).length; + await page.clock.runFor(95_000); + expect(listCalls(db).length).toBe(n); +}); + +test("a held source is named, and the list still shows", async ({ page }) => { + await mockApi(page, { list: () => prsPage(ROWS, { sources: [{ name: "reconcile", read: "held", detail: "it looks again in about 20 min" }] }) }); + await page.goto("/prs"); + await expect(page.getByTestId("prs-source-problem")).toContainText("GitHub's full list is waiting for GitHub's hourly budget: it looks again in about 20 min."); + await expect(page.getByTestId("pr-row").first()).toBeVisible(); +}); + +test("a pull request that isn't the team's says so", async ({ page }) => { + await mockApi(page, { detail: 404 }); + await page.goto("/prs?pr=acme%2Fweb%23999"); + await expect(page.getByTestId("pr-detail-missing")).toBeVisible(); +}); + +test.describe("on a phone", () => { + test.use({ viewport: { width: 375, height: 760 }, hasTouch: true, isMobile: true }); + + test("rows are three lines, the detail is full screen, targets are 44px, nothing scrolls sideways", async ({ page }) => { + await mockApi(page); + await page.goto("/prs"); + const row = page.locator("[data-pr-key='acme/web#212']"); + await expect(row).toBeVisible(); + // Three lines: state and where, the title, the sentence. Meta and chips stay for wider screens. + await expect(row.getByTestId("pr-next")).toBeHidden(); + await expect(row.getByText("10/12 checks")).toBeHidden(); + const box = await row.boundingBox(); + expect(box!.height).toBeLessThan(110); + + const width = await page.evaluate(() => document.documentElement.scrollWidth); + expect(width).toBeLessThanOrEqual(375); + + for (const target of [ + page.getByRole("navigation", { name: "Saved views" }).getByRole("button").first(), + page.getByTestId("list-section-turn-you").getByRole("button", { name: /Hide/ }), + ]) { + const b = await target.boundingBox(); + expect(b!.height).toBeGreaterThanOrEqual(44); + } + // The turn strip is the groups' headers on a phone. + await expect(page.getByRole("group", { name: "Whose turn" })).toBeHidden(); + await shot(page, "prs-phone-list"); + + await row.getByRole("link").first().click(); + const panel = page.getByRole("dialog", { name: "Round cart totals per currency" }); + await expect(panel).toBeVisible(); + const pb = await panel.boundingBox(); + expect(pb!.width).toBeGreaterThanOrEqual(374); + expect(pb!.height).toBeGreaterThanOrEqual(759); + const close = panel.getByRole("button", { name: "Close the pull request" }); + expect((await close.boundingBox())!.height).toBeGreaterThanOrEqual(44); + expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(375); + await expect(panel.getByTestId("pr-checklist")).toBeVisible(); + await shot(page, "prs-phone-detail"); + await close.click(); + await expect(panel).toHaveCount(0); + }); +}); diff --git a/dashboard/e2e/shell-menu.spec.ts b/dashboard/e2e/shell-menu.spec.ts index 0b39e638..629aa53a 100644 --- a/dashboard/e2e/shell-menu.spec.ts +++ b/dashboard/e2e/shell-menu.spec.ts @@ -24,7 +24,7 @@ test("the main menu is a handful of destinations with one Settings entry, Chat a // Plugins shows only while the team's plugins flag is on (the wide data turns it on). // toHaveText waits for the menu to render; a one-time read can run before it does. // Security carries the count of its open P0 and P1 findings (two in the wide data). - await expect(main.getByRole("link")).toHaveText([/^Setup3 things to set up$/, "Runs", "Plans", "Code review", "Logs", /^Security2 urgent security findings$/, "Chat", "Knowledge", "App map", "Plugins", "Insights", "Settings"]); + await expect(main.getByRole("link")).toHaveText([/^Setup3 things to set up$/, "Runs", "Pull requests", "Plans", "Code review", "Logs", /^Security2 urgent security findings$/, "Chat", "Knowledge", "App map", "Plugins", "Insights", "Settings"]); await expect(main.getByRole("link", { name: "Runs", exact: true })).toHaveAttribute("aria-current", "page"); // "Brain" is never a word people see in the menu. await expect(page.getByRole("navigation", { name: "Main" })).not.toContainText("Brain"); diff --git a/dashboard/e2e/shell-nav.spec.ts b/dashboard/e2e/shell-nav.spec.ts index 0425b800..65fd53ed 100644 --- a/dashboard/e2e/shell-nav.spec.ts +++ b/dashboard/e2e/shell-nav.spec.ts @@ -10,7 +10,7 @@ import { pickOption, expectSelectValue } from "./select"; const SHOTS_DIR = process.env.E2E_SHOTS_DIR || path.join("test-results", "shots"); -const LINKS = ["Runs", "Plans", "Code review", "Logs", "Insights", "Settings", "Admin", "Support queue"]; +const LINKS = ["Runs", "Pull requests", "Plans", "Code review", "Logs", "Insights", "Settings", "Admin", "Support queue"]; async function mockApi(page: Page) { const json = (route: Route, body: unknown, status = 200) => diff --git a/dashboard/e2e/wide-data/addresses.ts b/dashboard/e2e/wide-data/addresses.ts index 648013d9..4d4982fe 100644 --- a/dashboard/e2e/wide-data/addresses.ts +++ b/dashboard/e2e/wide-data/addresses.ts @@ -8,6 +8,8 @@ import { ALERT_ID, DRAFT_ID, PLAN_ID, PLUGIN_ID, PLUGIN_RUN_ID, REVIEW_SK, RUN_I */ export const SAMPLE_QUERY: Record = { "/runs/detail": `?id=${RUN_ID}`, + // Not an item's page, but its fullest view has a pull request open (full screen on a phone). + "/prs": `?pr=${encodeURIComponent(`${REPO}#12346`)}`, "/reviewer/detail": `?sk=${encodeURIComponent(REVIEW_SK)}`, // Not an item's page, but its settings form only shows for one repo. "/reviewer/config": `?repo=${encodeURIComponent(REPO)}`, diff --git a/dashboard/e2e/wide-data/index.ts b/dashboard/e2e/wide-data/index.ts index 01f9dc32..051ea6cb 100644 --- a/dashboard/e2e/wide-data/index.ts +++ b/dashboard/e2e/wide-data/index.ts @@ -13,6 +13,7 @@ import { securityData } from "./security"; import { infraData } from "./infra"; import { setupData } from "./setup"; import { skillRunsData } from "./skill-runs"; +import { prsData } from "./prs"; // An invented backend whose records are full of long, unbroken strings // (long.ts), for the no-sideways-scroll spec. Each file answers one part of @@ -51,7 +52,7 @@ const base: Handler = ({ method, path }) => { }; // Knowledge answers /api/knowledge before the chat's file does. -const HANDLERS: Handler[] = [base, runsData, reviewData, settingsData, logsData, learningData, knowledgeData, brainData, agentsData, pluginsData, securityData, infraData, setupData, skillRunsData]; +const HANDLERS: Handler[] = [base, runsData, reviewData, settingsData, logsData, learningData, knowledgeData, brainData, agentsData, pluginsData, securityData, infraData, setupData, skillRunsData, prsData]; /** Mocks the whole API. Returns the list of GETs no handler answered. */ export async function mockWideApi(page: Page): Promise<{ unanswered: string[] }> { diff --git a/dashboard/e2e/wide-data/prs.ts b/dashboard/e2e/wide-data/prs.ts new file mode 100644 index 00000000..8c0fe87f --- /dev/null +++ b/dashboard/e2e/wide-data/prs.ts @@ -0,0 +1,59 @@ +import type { Handler } from "./index"; +import { BRANCH, ORG, PR_URL, REPO, REPO_2, SENTENCE, TITLE, TOKEN, iso } from "./long"; + +// The Pull requests page: rows and a detail full of long titles, logins, +// branch names, sentences and unbroken tokens. + +const LOGIN = "dana-developer-with-a-long-login"; + +function row(i: number) { + const repo = i % 2 ? REPO_2 : REPO; + const number = 12345 + i; + return { + key: `${repo}#${number}`, org: ORG, repo, number, title: `${TITLE} ${TOKEN}`, url: `${PR_URL}${i}`, + author: i === 1 ? { login: "coderhelm[bot]", coderhelm: true } : { login: LOGIN }, for: i === 1 ? LOGIN : null, + draft: false, base: "main", head: BRANCH, created_at: iso(3000), updated_at: iso(10), + state: ["needs_review", "coderhelm_working", "checks_failing", "unknown", "merged"][i % 5], + turn: ["you", "coderhelm", "person", "machines", "done"][i % 5], + next: { code: "needs_review", text: `${SENTENCE} ${TOKEN}`, from: [`person:${LOGIN}`], since: iso(90), rule: "repo_rule" }, + modifiers: ["stale", "agent_authored", "large", "stacked"], + people: [{ login: LOGIN, roles: ["reviewer", "commenter", "requested"] }, { login: `${TOKEN}-reviewer`, roles: ["reviewer"] }], + checks: { total: 120, passed: 100, failed: 18, running: 2, required_failed: [TOKEN], known: true }, + reviews: { approvals: 1, required: 2, changes_requested_by: [LOGIN], requested: [LOGIN], coderhelm_verdict: "REQUEST_CHANGES" }, + conflict: false, open_threads: 3, labels: [TOKEN], size: { additions: 12000, deletions: 3400 }, + last_action: { actor: LOGIN, text: `pushed ${TOKEN}`, at: iso(30) }, + coderhelm: { run_id: "run_wide", session_id: "session_wide", round: 3, working: true, what: "Fixing CI" }, + links: [{ kind: "depends", repo: REPO_2, number: 67890, url: `${PR_URL}9`, state: "needs_review" }], + waiting_since: iso(90), + }; +} + +export const prsData: Handler = ({ method, path }) => { + if (method !== "GET") return undefined; + if (path === "/api/prs") { + const prs = Array.from({ length: 6 }, (_, i) => row(i)); + return { + prs, total: 6, next: "o:6", + counts: { turn: { you: 2, coderhelm: 1, person: 1, machines: 1, done: 1 }, state: {}, repo: { [REPO]: 3, [REPO_2]: 3 }, org: { [ORG]: 6, [`${ORG}-with-a-second-long-organization-name`]: 1 }, views: { my_turn: 2, coderhelm_working: 1, needs_decision: 0, ready: 0, stale: 6 } }, + viewer: LOGIN, synced_at: iso(1), + sources: [{ name: "reconcile", read: "held", detail: `${SENTENCE} ${TOKEN}` }], + }; + } + if (path === "/api/prs/detail") { + return { + pr: row(1), + checklist: [ + { key: "checks", mark: "blocked", text: `Required checks failing: ${TOKEN}`, source: "required_check" }, + { key: "approvals", mark: "waiting", text: `${SENTENCE} @${LOGIN}`, source: "codeowners" }, + ], + ledger: { open_secs: 400_000, spans: [], totals: [{ who: `person:${LOGIN}`, secs: 200_000 }, { who: "coderhelm", secs: 100_000 }, { who: "nobody", secs: 100_000 }] }, + timeline: [ + { at: iso(5), actor: "coderhelm[bot]", coderhelm: true, kind: "pushed", text: `pushed ${TOKEN}`, run_id: "run_wide" }, + { at: iso(50), actor: `${TOKEN}-reviewer`, kind: "review", text: SENTENCE }, + ], + runs: [{ run_id: "run_wide", title: `${TITLE} ${TOKEN}`, status: "running", started_at: iso(8), url: "/runs/detail?id=run_wide" }], + synced_at: iso(1), + }; + } + return undefined; +}; diff --git a/dashboard/src/app/prs/detail.tsx b/dashboard/src/app/prs/detail.tsx new file mode 100644 index 00000000..e8ebca76 --- /dev/null +++ b/dashboard/src/app/prs/detail.tsx @@ -0,0 +1,470 @@ +"use client"; + +import Link from "next/link"; +import { useEffect, useRef, useState } from "react"; +import { api, ApiError, type PrDetail, type PrRow, type PrTimelineEvent } from "@/lib/api"; +import { Chip, ShapeIcon, StatusText, Time, TONES, type Shape, type Tone } from "@/components/list"; +import { ChevronRightIcon } from "@/components/icons"; +import { CoderHelmAvatar } from "@/components/support"; +import { focusRing, linkButton, secondaryButton } from "@/components/ui"; +import { actorWords, foldTimeline, isCoderHelm, ledgerLook, ledgerShares, longSecs, nextActor, RULE_WORDS, stateLook, type TimelineItem } from "./model"; + +/** How often an open pull request is read again while the tab is visible. */ +const DETAIL_POLL_MS = 15_000; + +const MARK: Record = { + done: { shape: "check", tone: "success", words: "Done" }, + waiting: { shape: "ring", tone: "waiting", words: "Waiting" }, + blocked: { shape: "cross", tone: "danger", words: "Blocked" }, + none: { shape: "square", tone: "muted", words: "Not needed" }, +}; + +type Filter = "all" | "people" | "coderhelm" | "checks"; +const FILTERS: { value: Filter; label: string }[] = [ + { value: "all", label: "All" }, + { value: "people", label: "People" }, + { value: "coderhelm", label: "CoderHelm" }, + { value: "checks", label: "Checks" }, +]; + +function keep(filter: Filter, e: PrTimelineEvent): boolean { + if (filter === "all") return true; + const helm = isCoderHelm(e.actor, e.coderhelm) || !!e.run_id; + if (filter === "coderhelm") return helm; + if (filter === "checks") return e.kind === "check" || e.kind === "queue"; + return !helm && e.kind !== "check" && e.actor !== "ci"; +} + +/** + * One pull request beside the list (wide screens) or over it (a phone, full + * screen): what it needs, its path to merge, who held it and for how long, + * and what happened, with CoderHelm's runs folded. + */ +export function PrDetailPanel({ + row, + prKey, + viewer, + overlay, + onClose, +}: { + /** The list's row, shown at once while the detail loads. */ + row: PrRow | undefined; + prKey: { repo: string; number: number }; + viewer?: string | null; + /** Drawn over the page (a phone or a narrow window): traps focus. */ + overlay: boolean; + onClose: () => void; +}) { + const [detail, setDetail] = useState(null); + const [error, setError] = useState(null); + const [missing, setMissing] = useState(false); + const heading = useRef(null); + const box = useRef(null); + const { repo, number } = prKey; + + useEffect(() => { + let live = true; + setDetail(null); + setError(null); + setMissing(false); + const load = () => + api + .getPr(repo, number) + .then((d) => { + if (!live) return; + setDetail(d); + setError(null); + }) + .catch((e) => { + if (!live) return; + if (e instanceof ApiError && e.status === 404) setMissing(true); + else setError(e instanceof Error ? e.message : String(e)); + }); + load(); + const id = window.setInterval(() => { + if (document.visibilityState === "visible") load(); + }, DETAIL_POLL_MS); + return () => { + live = false; + window.clearInterval(id); + }; + }, [repo, number]); + + // Opening moves focus to the heading. + useEffect(() => { + heading.current?.focus(); + }, [repo, number]); + + // Over the page, Tab stays inside the panel. + useEffect(() => { + if (!overlay) return; + const onKey = (e: KeyboardEvent) => { + if (e.key !== "Tab" || !box.current) return; + const f = Array.from(box.current.querySelectorAll("a[href],button:not([disabled]),[tabindex='0'],h2[tabindex]")); + if (f.length === 0) return; + const first = f[0]; + const last = f[f.length - 1]; + if (e.shiftKey && document.activeElement === first) { + e.preventDefault(); + last.focus(); + } else if (!e.shiftKey && document.activeElement === last) { + e.preventDefault(); + first.focus(); + } + }; + document.addEventListener("keydown", onKey); + const body = document.body.style.overflow; + document.body.style.overflow = "hidden"; + return () => { + document.removeEventListener("keydown", onKey); + document.body.style.overflow = body; + }; + }, [overlay]); + + const pr = detail?.pr ?? row; + const look = stateLook(pr?.state, pr?.state_label); + const headingId = "pr-detail-heading"; + const close = ( + + ); + + return ( +
+
+
+

+ + {repo}#{number} + + {pr?.head && pr.base && ( + + {pr.head} into {pr.base} + + )} + {detail?.synced_at && ( + + synced + )} +

+

+ {pr?.title || `${repo}#${number}`} +

+
+ {close} +
+ + {missing ? ( +

+ This pull request isn't open in your team's repos any more, or it was never one of them. +

+ ) : ( + <> + {pr && ( +
+ +

+ {pr.next?.text} +

+

+ Next: {nextActor(pr, viewer)} + {pr.next?.rule && <> · {RULE_WORDS[pr.next.rule] ?? pr.next.rule}} + {pr.next?.since && ( + <> + {" "} + · since

+
+ {pr.url && ( + + Open on GitHub (opens in a new tab) + + )} + {pr.coderhelm?.run_id && ( + + CoderHelm's run + + )} + {pr.coderhelm?.session_id && ( + + CoderHelm's review + + )} +
+
+ )} + + {error && ( +

+ Couldn't read this pull request: {error} +

+ )} + + {!detail && !error && ( +

+ Reading the pull request… +

+ )} + + {detail && ( + <> + + + + + + + )} + + )} +
+ ); +} + +function SectionTitle({ children }: { children: React.ReactNode }) { + return

{children}

; +} + +function Checklist({ detail }: { detail: PrDetail }) { + if (!detail.checklist?.length) return null; + return ( +
+ Path to merge +
    + {detail.checklist.map((c) => { + const m = MARK[c.mark] ?? MARK.none; + return ( +
  • + + {m.words}: + + {c.text} + {c.source && ({RULE_WORDS[c.source] ?? c.source})} + +
  • + ); + })} +
+
+ ); +} + +const BAR: Record = { + live: "bg-sky-400", + queued: "bg-sky-400/60", + waiting: "bg-amber-400", + attention: "bg-orange-400", + success: "bg-emerald-400", + merged: "bg-violet-400", + danger: "bg-red-400", + info: "bg-blue-400", + neutral: "bg-zinc-400", + muted: "bg-zinc-600", +}; + +/** Who held the turn, for how long: one bar, and the same in words under it. */ +function Ledger({ detail }: { detail: PrDetail }) { + const shares = ledgerShares(detail); + if (shares.length === 0) return null; + const words = shares.map((s) => `${ledgerLook(s.who).label} ${longSecs(s.secs)}`).join(", "); + return ( +
+ Wait ledger · open {longSecs(detail.ledger.open_secs)} +
+ {shares.map((s, i) => ( + + ))} +
+
    + {shares.map((s) => { + const l = ledgerLook(s.who); + return ( +
  • +
  • + ); + })} +
+
+ ); +} + +function EventLine({ e }: { e: PrTimelineEvent }) { + const helm = isCoderHelm(e.actor, e.coderhelm); + return ( +
  • + {helm ? :
  • + ); +} + +function RunBlock({ item }: { item: Extract }) { + const [open, setOpen] = useState(item.status === "running"); + const id = `run-${item.runId}`; + return ( +
  • + + {open && ( +
    +
      + {item.events.map((e, i) => ( + + ))} +
    + {item.url && ( + + The whole run + + )} +
    + )} +
  • + ); +} + +function Timeline({ detail }: { detail: PrDetail }) { + const [filter, setFilter] = useState("all"); + const items = foldTimeline({ + runs: detail.runs, + timeline: (detail.timeline ?? []).filter((e) => keep(filter, e)), + }).filter((i) => i.kind === "event" || filter === "all" || filter === "coderhelm"); + return ( +
    + Timeline +
    + {FILTERS.map((f) => ( + + ))} +
    + {items.length === 0 ? ( +

    Nothing of this kind happened on it yet.

    + ) : ( +
      + {items.map((it, i) => + it.kind === "run" ? : , + )} +
    + )} +
    + ); +} + +function Links({ pr }: { pr: PrRow }) { + if (!pr.links?.length) return null; + const words: Record = { stack_base: "Stacked on", stack_child: "Stacked under it", plan: "Same plan", depends: "Waits on" }; + return ( +
    + Links + +
    + ); +} + +function People({ pr }: { pr: PrRow }) { + const people = pr.people ?? []; + const helmAuthor = isCoderHelm(pr.author?.login, pr.author?.coderhelm); + return ( +
    + People +
      +
    • + Author + {helmAuthor ? ( + + CoderHelm AI + {pr.for && for @{pr.for}} + + ) : ( + @{pr.author?.login} + )} +
    • + {people + .filter((p) => p.login !== pr.author?.login) + .map((p) => ( +
    • + {isCoderHelm(p.login, p.coderhelm) ? "CoderHelm" : `@${p.login}`} + {p.roles.join(", ")} +
    • + ))} +
    • + Turn: {(pr.next?.from ?? []).map((w) => actorWords(w)).join(", ") || "nobody"} +
    • +
    +
    + ); +} diff --git a/dashboard/src/app/prs/model.ts b/dashboard/src/app/prs/model.ts new file mode 100644 index 00000000..1a50c02f --- /dev/null +++ b/dashboard/src/app/prs/model.ts @@ -0,0 +1,261 @@ +// The Pull requests page's words and pure helpers: one look per state (a +// label, a tone and a shape, never colour alone), the turn groups in their +// order, the saved views, the sentence each row is named by, the wait +// ledger's totals and the timeline folded into CoderHelm's runs. The server +// decides each pull request's one state and what it needs next; nothing here +// second-guesses it, it only says it. + +import type { PrDetail, PrRow, PrState, PrTimelineEvent, PrTurn, PrView } from "@/lib/api"; +import type { Shape, StatusLook, Tone } from "@/components/list/status"; +import { statusWords } from "@/components/list/status"; + +export interface StateLook extends StatusLook { + shape: Shape; +} + +/** Every state the server sends, with its words, tone and shape. */ +export const STATE_LOOK: Record = { + merged: { label: "Merged", tone: "merged", shape: "check" }, + closed: { label: "Closed", tone: "muted", shape: "cross" }, + in_queue: { label: "In merge queue", tone: "neutral", shape: "bars" }, + left_queue: { label: "Left the queue", tone: "danger", shape: "triangle" }, + coderhelm_working: { label: "CoderHelm working", tone: "live", shape: "hexagon", live: true }, + needs_decision: { label: "Needs a decision", tone: "attention", shape: "flag" }, + draft: { label: "Draft", tone: "muted", shape: "ring" }, + waiting_on_pr: { label: "Waiting on another PR", tone: "waiting", shape: "link" }, + conflicts: { label: "Conflicts", tone: "danger", shape: "triangle" }, + checks_failing: { label: "Checks failing", tone: "danger", shape: "cross" }, + changes_requested: { label: "Changes requested", tone: "attention", shape: "return" }, + re_review: { label: "Re-review needed", tone: "waiting", shape: "diamond" }, + needs_reviewer: { label: "Needs a reviewer", tone: "waiting", shape: "diamond" }, + needs_review: { label: "Needs review", tone: "waiting", shape: "diamond" }, + needs_code_owner: { label: "Needs a code owner", tone: "waiting", shape: "diamond" }, + open_threads: { label: "Open threads", tone: "waiting", shape: "square" }, + checks_running: { label: "Checks running", tone: "queued", shape: "ring", live: true }, + ready_auto_merge: { label: "Ready, auto-merge on", tone: "success", shape: "check" }, + ready_to_merge: { label: "Ready to merge", tone: "success", shape: "check" }, + unknown: { label: "Unknown: not synced", tone: "neutral", shape: "square" }, +}; + +/** A state's look; a code this page doesn't know yet still reads as words. */ +export function stateLook(state: string | null | undefined, label?: string): StateLook { + const known = STATE_LOOK[(state ?? "unknown") as PrState]; + if (known) return label ? { ...known, label } : known; + return { label: label || statusWords(state), tone: "neutral", shape: "square" }; +} + +export const TURNS: { turn: PrTurn; label: string; tone: Tone; empty: string }[] = [ + { turn: "you", label: "Your turn", tone: "attention", empty: "Nothing needs you right now." }, + { turn: "coderhelm", label: "CoderHelm working", tone: "live", empty: "CoderHelm isn't working on any of these." }, + { turn: "person", label: "A person", tone: "waiting", empty: "Nobody else is holding one." }, + { turn: "machines", label: "Machines", tone: "neutral", empty: "Nothing waits on CI or the queue." }, + { turn: "done", label: "Done", tone: "merged", empty: "Nothing merged or closed lately." }, +]; + +export function turnOf(row: PrRow): PrTurn { + const t = row.turn as PrTurn; + return TURNS.some((x) => x.turn === t) ? t : "machines"; +} + +export const VIEWS: { view: PrView; label: string; key: string }[] = [ + { view: "my_turn", label: "My turn", key: "m" }, + { view: "coderhelm_working", label: "CoderHelm working", key: "c" }, + { view: "needs_decision", label: "Needs decision", key: "d" }, + { view: "ready", label: "Ready", key: "r" }, + { view: "stale", label: "Stale", key: "s" }, +]; + +export function isView(v: string): v is PrView { + return VIEWS.some((x) => x.view === v); +} + +/** The rule behind a next step, in words: "repo rule", "CODEOWNERS", "required check". */ +export const RULE_WORDS: Record = { + repo_rule: "repo rule", + codeowners: "CODEOWNERS", + required_check: "required check", + team_rule: "team rule", + branch_rule: "branch rule", +}; + +/** CoderHelm's GitHub login looks like this; the server also marks it. */ +export function isCoderHelm(login: string | null | undefined, flag?: boolean): boolean { + if (flag) return true; + return !!login && /^coderhelm(\[bot\])?$/i.test(login); +} + +/** "person:octocat" → "@octocat"; "coderhelm" → "CoderHelm"; "ci" → "CI". */ +export function actorWords(who: string, viewer?: string | null): string { + if (who === "coderhelm") return "CoderHelm"; + if (who === "ci") return "CI"; + if (who === "queue") return "the queue"; + if (who === "nobody") return "nobody"; + if (who === "author") return "the author"; + if (who.startsWith("person:")) { + const login = who.slice(7); + return viewer && login.toLowerCase() === viewer.toLowerCase() ? "You" : `@${login}`; + } + if (who.startsWith("team:")) return `@${who.slice(5)}`; + return who; +} + +/** The first actor in `next.from`, as the Next column says it. */ +export function nextActor(row: PrRow, viewer?: string | null): string { + const from = row.next?.from ?? []; + if (from.length === 0) return turnOf(row) === "done" ? "Nobody" : "Unassigned"; + const first = actorWords(from[0], viewer); + return from.length > 1 ? `${first} +${from.length - 1}` : first; +} + +export function nextIsCoderHelm(row: PrRow): boolean { + return (row.next?.from ?? [])[0] === "coderhelm"; +} + +/** "3 min", "2 h", "4 d": a compact wait for a column. */ +export function shortWait(iso: string | null | undefined, now = Date.now()): string { + if (!iso) return ""; + const t = new Date(iso).getTime(); + if (Number.isNaN(t)) return ""; + return shortSecs(Math.max(0, Math.floor((now - t) / 1000))); +} + +export function shortSecs(secs: number): string { + if (secs < 60) return "now"; + const m = Math.floor(secs / 60); + if (m < 60) return `${m} min`; + const h = Math.floor(m / 60); + if (h < 48) return `${h} h`; + return `${Math.floor(h / 24)} d`; +} + +/** "1 d 4 h", "47 min": a ledger total. */ +export function longSecs(secs: number): string { + if (secs < 60) return "under a minute"; + const m = Math.floor(secs / 60); + if (m < 60) return `${m} min`; + const h = Math.floor(m / 60); + const rm = m % 60; + if (h < 24) return rm ? `${h} h ${rm} min` : `${h} h`; + const d = Math.floor(h / 24); + const rh = h % 24; + return rh ? `${d} d ${rh} h` : `${d} d`; +} + +/** XS to XL from the lines changed. */ +export function sizeBucket(size: PrRow["size"]): string { + if (!size) return ""; + const n = (size.additions ?? 0) + (size.deletions ?? 0); + if (n < 10) return "XS"; + if (n < 100) return "S"; + if (n < 500) return "M"; + if (n < 1000) return "L"; + return "XL"; +} + +/** + * The sentence a row is named by for a screen reader: where, what, the + * needs sentence, who has it and for how long, and who wrote it. + */ +export function rowSentence(row: PrRow, viewer?: string | null, now = Date.now()): string { + const look = stateLook(row.state, row.state_label); + const wait = shortWait(row.waiting_since ?? row.next?.since, now); + const author = isCoderHelm(row.author?.login, row.author?.coderhelm) + ? `Written by CoderHelm${row.for ? ` for @${row.for}` : ""}` + : `Author @${row.author?.login ?? "unknown"}`; + const parts = [ + `${row.repo} ${row.number}, ${row.title}`, + look.label, + row.next?.text, + `Next: ${nextActor(row, viewer)}${wait ? `, waiting ${wait}` : ""}`, + author, + ]; + return parts.filter(Boolean).map((p) => String(p).replace(/[.\s]+$/, "")).join(". ") + "."; +} + +/** Rows grouped by turn, in the page's order; empty turns are left out. */ +export function groupByTurn(rows: PrRow[]): { turn: PrTurn; rows: PrRow[] }[] { + const by = new Map(); + for (const r of rows) { + const t = turnOf(r); + if (!by.has(t)) by.set(t, []); + by.get(t)!.push(r); + } + return TURNS.filter((t) => by.has(t.turn)).map((t) => ({ turn: t.turn, rows: by.get(t.turn)! })); +} + +/** The oldest wait in a group, for its header ("oldest 2 d"). */ +export function oldestWait(rows: PrRow[], now = Date.now()): string { + let oldest = Infinity; + for (const r of rows) { + const t = new Date(r.waiting_since ?? r.next?.since ?? "").getTime(); + if (!Number.isNaN(t) && t < oldest) oldest = t; + } + return oldest === Infinity ? "" : shortWait(new Date(oldest).toISOString(), now); +} + +/** A ledger actor's words and tone. */ +export function ledgerLook(who: string): { label: string; tone: Tone } { + if (who === "coderhelm") return { label: "CoderHelm", tone: "live" }; + if (who === "ci") return { label: "CI", tone: "neutral" }; + if (who === "queue") return { label: "Queue", tone: "info" }; + if (who === "nobody") return { label: "Idle", tone: "muted" }; + return { label: actorWords(who), tone: "waiting" }; +} + +/** The ledger's totals, largest first, with each one's share of the time open. */ +export function ledgerShares(detail: Pick): { who: string; secs: number; pct: number }[] { + const totals = detail.ledger?.totals?.length + ? detail.ledger.totals + : Object.entries( + (detail.ledger?.spans ?? []).reduce>((acc, s) => { + acc[s.who] = (acc[s.who] ?? 0) + (s.secs ?? 0); + return acc; + }, {}), + ).map(([who, secs]) => ({ who, secs })); + const sum = totals.reduce((a, t) => a + t.secs, 0) || 1; + return [...totals] + .filter((t) => t.secs > 0) + .sort((a, b) => b.secs - a.secs) + .map((t) => ({ ...t, pct: (t.secs / sum) * 100 })); +} + +export type TimelineItem = + | { kind: "event"; event: PrTimelineEvent } + | { kind: "run"; runId: string; title: string; status: string; at: string; events: PrTimelineEvent[]; url?: string }; + +/** + * The timeline, newest first, with every event of one CoderHelm run folded + * into that run's block (placed at the run's newest event). + */ +export function foldTimeline(detail: Pick): TimelineItem[] { + const events = [...(detail.timeline ?? [])].sort((a, b) => b.at.localeCompare(a.at)); + const runs = new Map((detail.runs ?? []).map((r) => [r.run_id, r])); + const out: TimelineItem[] = []; + const blocks = new Map>(); + for (const e of events) { + if (!e.run_id) { + out.push({ kind: "event", event: e }); + continue; + } + let block = blocks.get(e.run_id); + if (!block) { + const run = runs.get(e.run_id); + block = { kind: "run", runId: e.run_id, title: run?.title || "CoderHelm run", status: run?.status ?? "", at: e.at, events: [], url: run?.url }; + blocks.set(e.run_id, block); + out.push(block); + } + block.events.push(e); + } + // A run with no events yet still shows as a block. + for (const r of detail.runs ?? []) { + if (blocks.has(r.run_id)) continue; + out.push({ kind: "run", runId: r.run_id, title: r.title, status: r.status, at: r.started_at ?? "", events: [], url: r.url }); + } + return out; +} + +/** "acme/web#318" parsed; null when it isn't one. */ +export function parseKey(key: string | null | undefined): { repo: string; number: number } | null { + const m = /^([^/\s#]+\/[^/\s#]+)#(\d+)$/.exec(key ?? ""); + return m ? { repo: m[1], number: Number(m[2]) } : null; +} diff --git a/dashboard/src/app/prs/page.tsx b/dashboard/src/app/prs/page.tsx new file mode 100644 index 00000000..23b0738f --- /dev/null +++ b/dashboard/src/app/prs/page.tsx @@ -0,0 +1,771 @@ +"use client"; + +import Link from "next/link"; +import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { api, ApiError, type PrRow, type PrsPage, type PrsQuery, type PrTurn } from "@/lib/api"; +import { RoleGuard } from "@/components/role-guard"; +import { Page, PageHeader } from "@/components/page"; +import { + Chip, + List, + ListEmpty, + ListError, + ListRow, + ListSection, + ListSkeleton, + ListToolbar, + ShapeIcon, + StatusText, + Time, + useListParams, + useWindowedList, +} from "@/components/list"; +import { ChevronRightIcon } from "@/components/icons"; +import { AvatarGroup, CoderHelmAvatar } from "@/components/support"; +import { focusRing, linkButton, secondaryButton } from "@/components/ui"; +import { usePhone } from "@/hooks/use-phone"; +import { PrDetailPanel } from "./detail"; +import { + groupByTurn, + isCoderHelm, + isView, + nextActor, + nextIsCoderHelm, + oldestWait, + parseKey, + rowSentence, + shortWait, + sizeBucket, + stateLook, + TURNS, + VIEWS, +} from "./model"; + +export default function PrsPageGuarded() { + return ( + + + +
    + +
    + + } + > + +
    +
    + ); +} + +/** How often the list is read again while the tab is visible. */ +const POLL_MS = 30_000; +/** Rows a page asks for. */ +const PAGE_SIZE = 100; +/** The split pane needs this much room; narrower, the pull request opens over the list. */ +const SPLIT_QUERY = "(min-width: 1440px)"; + +function useSplit(): boolean { + const [split, setSplit] = useState(false); + useEffect(() => { + const q = window.matchMedia(SPLIT_QUERY); + const on = () => setSplit(q.matches); + on(); + q.addEventListener("change", on); + return () => q.removeEventListener("change", on); + }, []); + return split; +} + +/** True when the key press should go to the page, not to a field being typed in. */ +function typing(e: KeyboardEvent): boolean { + const t = e.target as HTMLElement | null; + return !!t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)); +} + +const rowId = (key: string) => `pr-row-${key.replace(/[^A-Za-z0-9_-]/g, "-")}`; + +function PrsPage() { + const [params, setParams] = useListParams({ org: "", repo: "", turn: "", state: "", person: "", q: "", view: "", pr: "" }); + const phone = usePhone(); + const split = useSplit(); + const [page, setPage] = useState(null); + const [more, setMore] = useState([]); + const [next, setNext] = useState(null); + const [loading, setLoading] = useState(true); + const [loadingMore, setLoadingMore] = useState(false); + const [error, setError] = useState(null); + // An older backend: the page explains instead of failing. + const [notServed, setNotServed] = useState(false); + const [collapsed, setCollapsed] = useState>(new Set(["done"])); + const [announce, setAnnounce] = useState(""); + const [focusKey, setFocusKey] = useState(null); + // The row the keyboard is on, set at once (focus lands a frame later). + const cursor = useRef(null); + const lastStates = useRef | null>(null); + const scrollers = useRef(new Map void>()); + + const query = useMemo( + (): PrsQuery => ({ + org: params.org, + repo: params.repo, + turn: params.turn as PrTurn | "", + state: params.state, + person: params.person, + q: params.q, + view: isView(params.view) ? params.view : "", + limit: PAGE_SIZE, + }), + [params.org, params.repo, params.turn, params.state, params.person, params.q, params.view], + ); + + const gen = useRef(0); + const load = useCallback( + (quiet = false) => { + const g = ++gen.current; + if (!quiet) setLoading(true); + return api + .listPrs(query) + .then((d) => { + if (g !== gen.current) return; + // Say what changed since the last read, once, never row by row. + const states = new Map(d.prs.map((r) => [r.key, `${r.state}|${r.turn}`])); + if (quiet && lastStates.current) { + const changed = d.prs.filter((r) => lastStates.current!.get(r.key) !== states.get(r.key)); + if (changed.length) { + const mine = changed.filter((r) => r.turn === "you").length; + setAnnounce( + `${changed.length} pull request${changed.length === 1 ? "" : "s"} changed${mine ? `: ${mine} now need${mine === 1 ? "s" : ""} you` : ""}.`, + ); + } + } + lastStates.current = states; + setPage(d); + setMore([]); + setNext(d.next ?? null); + setError(null); + setNotServed(false); + }) + .catch((e) => { + if (g !== gen.current) return; + if (e instanceof ApiError && (e.status === 404 || e.status === 405)) setNotServed(true); + else if (!quiet || !page) setError(e instanceof Error ? e.message : String(e)); + }) + .finally(() => { + if (g === gen.current) setLoading(false); + }); + }, + // `page` is read only to keep a good list on a passing error. + // eslint-disable-next-line react-hooks/exhaustive-deps + [query], + ); + + useEffect(() => { + load(); + }, [load]); + + // Read again while the tab is visible, and at once when it comes back. + useEffect(() => { + if (notServed) return; + const id = window.setInterval(() => { + if (document.visibilityState === "visible") load(true); + }, POLL_MS); + const onVis = () => { + if (document.visibilityState === "visible") load(true); + }; + document.addEventListener("visibilitychange", onVis); + return () => { + window.clearInterval(id); + document.removeEventListener("visibilitychange", onVis); + }; + }, [load, notServed]); + + const loadMore = () => { + if (!next) return; + setLoadingMore(true); + api + .listPrs({ ...query, cursor: next }) + .then((d) => { + setMore((m) => [...m, ...d.prs]); + setNext(d.next ?? null); + }) + .catch(() => {}) + .finally(() => setLoadingMore(false)); + }; + + const rows = useMemo(() => [...(page?.prs ?? []), ...more], [page, more]); + const groups = useMemo(() => groupByTurn(rows), [rows]); + const viewer = page?.viewer ?? null; + const counts = page?.counts ?? {}; + const open = parseKey(params.pr); + const openRow = open ? rows.find((r) => r.repo === open.repo && r.number === open.number) : undefined; + + // The rows the keyboard walks, in the order on screen. + const order = useMemo(() => groups.filter((g) => !collapsed.has(g.turn)).flatMap((g) => g.rows.map((r, i) => ({ key: r.key, turn: g.turn, i }))), [groups, collapsed]); + + const focusRow = useCallback( + (key: string) => { + cursor.current = key; + setFocusKey(key); + const at = order.find((o) => o.key === key); + if (at) scrollers.current.get(at.turn)?.(at.i); + let tries = 0; + const tryFocus = () => { + const el = document.getElementById(rowId(key)); + if (el) el.focus({ preventScroll: false }); + else if (tries++ < 10) window.requestAnimationFrame(tryFocus); + }; + window.requestAnimationFrame(tryFocus); + }, + [order], + ); + + const openPr = useCallback((key: string) => setParams({ pr: key }), [setParams]); + const closePr = useCallback(() => { + const key = params.pr; + setParams({ pr: "" }); + if (key) focusRow(key); + }, [params.pr, setParams, focusRow]); + + // j/k (and the arrows) move between rows, Enter opens, Esc closes. + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.metaKey || e.ctrlKey || e.altKey) return; + if (e.key === "Escape" && params.pr) { + e.preventDefault(); + closePr(); + return; + } + if (typing(e)) return; + const down = e.key === "j" || e.key === "ArrowDown"; + const up = e.key === "k" || e.key === "ArrowUp"; + if (down || up) { + if (order.length === 0) return; + // Arrows scroll the page unless a row has focus. + const onRow = (document.activeElement as HTMLElement | null)?.dataset?.prKey; + if ((e.key === "ArrowDown" || e.key === "ArrowUp") && !onRow) return; + e.preventDefault(); + const cur = order.findIndex((o) => o.key === (cursor.current ?? onRow ?? focusKey)); + const to = cur < 0 ? 0 : Math.min(order.length - 1, Math.max(0, cur + (down ? 1 : -1))); + focusRow(order[to].key); + // With the pull request open beside the list, it follows. + if (params.pr && split) openPr(order[to].key); + } else if (e.key === "Enter") { + const onRow = (document.activeElement as HTMLElement | null)?.dataset?.prKey; + if (onRow) { + e.preventDefault(); + openPr(onRow); + } + } + }; + document.addEventListener("keydown", onKey); + return () => document.removeEventListener("keydown", onKey); + }, [order, focusKey, focusRow, openPr, closePr, params.pr, split]); + + const filtered = !!(params.turn || params.state || params.person || params.q || params.view); + const clear = () => setParams({ turn: "", state: "", person: "", q: "", view: "" }); + const scopeLabel = params.repo || params.org || "every repo"; + const detailOpen = !!open; + const overlay = detailOpen && !split; + const problems = (page?.sources ?? []).filter((s) => s.read !== "ok"); + const repoChoices = useMemo( + () => Object.keys(counts.repo ?? {}).filter((r) => !params.org || r.startsWith(`${params.org}/`)).sort((a, b) => a.localeCompare(b)), + [counts.repo, params.org], + ); + + return ( + + + Synced + ); +} + +/** The scope as a trail that is also the address: All orgs, then the org, then the repo. */ +function Scope({ org, repo, orgs, onPick }: { org: string; repo: string; orgs: string[]; onPick: (org: string, repo: string) => void }) { + const crumb = `inline-flex min-h-11 items-center rounded-md px-1.5 text-sm sm:min-h-8 ${focusRing}`; + const repoName = repo.split("/")[1]; + const orgOf = org || repo.split("/")[0] || ""; + return ( + + ); +} + +function ViewButton({ label, count, on, onClick }: { label: string; count?: number; on: boolean; onClick: () => void }) { + return ( + + ); +} + +/** Counts per turn, each a filter: the board's overview without a board. */ +function TurnStrip({ counts, value, onPick }: { counts: Partial>; value: string; onPick: (t: PrTurn) => void }) { + return ( +
    + {TURNS.map((t) => { + const on = value === t.turn; + return ( + + ); + })} +
    + ); +} + +function Empty({ + page, + filtered, + view, + query, + onClear, + onView, +}: { + page: PrsPage | null; + filtered: boolean; + view: string; + query: string; + onClear: () => void; + onView: (v: string) => void; +}) { + const t = page?.counts?.turn ?? {}; + if (view === "my_turn") { + return ( + + CoderHelm is working on {t.coderhelm ?? 0}; {t.person ?? 0} are waiting on others.{" "} + + + ); + } + if (filtered) { + return ( + + {query ? `Nothing matches "${query}" with these filters.` : "Nothing matches these filters."} + + ); + } + return ( + + The repos CoderHelm is installed on have no open pull requests. A pull request someone opens shows here within a minute, and CoderHelm opens its own from + a ticket or a{" "} + + plan + + . + + ); +} + +/** Row heights before measuring: three short lines on a phone, two plus the sentence wider. */ +const EST_PHONE = 92; +const EST_WIDE = 96; + +function TurnGroup({ + turn, + rows, + count, + collapsed, + onToggle, + viewer, + phone, + openKey, + focusKey, + hrefFor, + onFocusRow, + registerScroll, +}: { + turn: PrTurn; + rows: PrRow[]; + count: number; + collapsed: boolean; + onToggle: () => void; + viewer: string | null; + phone: boolean; + openKey: string; + focusKey: string | null; + hrefFor: (key: string) => string; + onFocusRow: (key: string) => void; + registerScroll: (fn: (i: number) => void) => void; +}) { + const info = TURNS.find((t) => t.turn === turn)!; + const keys = useMemo(() => (collapsed ? [] : rows.map((r) => r.key)), [rows, collapsed]); + const w = useWindowedList({ keys, estimate: phone ? EST_PHONE : EST_WIDE }); + useEffect(() => { + registerScroll(w.scrollToIndex); + }, [registerScroll, w.scrollToIndex]); + const oldest = oldestWait(rows); + const listId = `prs-group-${turn}`; + // The row the keyboard enters the list on: the focused one, else the first. + const tabKey = focusKey && rows.some((r) => r.key === focusKey) ? focusKey : null; + return ( + + {collapsed ? "Show" : "Hide"} + {info.label} + + } + > + {!collapsed && ( + + {w.padTop > 0 &&