diff --git a/dashboard/e2e/close-runs.spec.ts b/dashboard/e2e/close-runs.spec.ts index 89431298..30007ef3 100644 --- a/dashboard/e2e/close-runs.spec.ts +++ b/dashboard/e2e/close-runs.spec.ts @@ -45,6 +45,14 @@ interface Backend { const OVER = ["closed", "cancelled", "merged", "retried", "archived"]; async function mockApi(page: Page, init: Partial = {}): Promise { + // "/" stays on Runs: the visit has begun (a phone's first visit opens the Inbox). + await page.addInitScript(() => { + try { + sessionStorage.setItem("ch-landed", "1"); + } catch { + /* ignore */ + } + }); const db: Backend = { role: "member", calls: [], diff --git a/dashboard/e2e/inbox-data.ts b/dashboard/e2e/inbox-data.ts new file mode 100644 index 00000000..4c6c9467 --- /dev/null +++ b/dashboard/e2e/inbox-data.ts @@ -0,0 +1,276 @@ +import type { Page, Route } from "@playwright/test"; + +// An invented team for the phone's Inbox: the bookstore's repos (acme/web, +// acme/api, acme/docs), octocat on the team, one of every kind of decision. +// `mockInbox(page, opts)` answers the whole API; what isn't here answers 404, +// as an older backend would. + +const now = Date.now(); +const ago = (mins: number) => new Date(now - mins * 60_000).toISOString(); + +export const QUESTION_RUN = { + run_id: "run_q1", + status: "needs_input", + ticket_source: "github", + ticket_id: "acme/web#41", + title: "Add gift cards to the bookstore checkout", + repo: "acme/web", + pr_number: 818, + pr_url: "https://github.com/acme/web/pull/818", + created_at: ago(95), + updated_at: ago(40), + current_pass: "plan", + questions: [ + { + id: "q1", + question: "Should a gift card pay for shipping too, or only for books?", + why: "The checkout total and the refund rules both change with the answer.", + suggestions: ["Books and shipping", "Books only"], + decision: "gift_card_scope", + }, + ], + waiting_on: { action: "Answer CoderHelm's question", detail: "", since: ago(40) }, + progress_notes: [ + { message: "Read the checkout and the order totals in src/checkout/total.ts.", timestamp: ago(60) }, + { message: "Found two places that add shipping: the cart and the payment step.", timestamp: ago(45) }, + ], +}; + +export const HANDOFF_RUN = { + run_id: "run_h1", + status: "needs_input", + ticket_source: "github", + ticket_id: "acme/docs#12", + title: "Document the new returns policy", + repo: "acme/docs", + pr_number: 44, + pr_url: "https://github.com/acme/docs/pull/44", + created_at: ago(300), + updated_at: ago(200), + draft_hold: { + kind: "held", + summary: "#44 stays a draft until a person signs off the wording", + reasons: [{ what: "the returns policy text needs a person's sign-off", todo: "Read the new page and mark the pull request ready" }], + pr_number: 44, + since: ago(200), + needs_person: true, + }, +}; + +export const MERGE_RUN = { + run_id: "run_m1", + status: "needs_input", + ticket_source: "jira", + ticket_id: "WEB-42", + title: "Fix the flaky retry in the order queue", + repo: "acme/web", + pr_number: 812, + pr_url: "https://github.com/acme/web/pull/812", + prs: [{ repo: "acme/web", pr_number: 812, branch: "coderhelm/shop-212-order-retry", url: "https://github.com/acme/web/pull/812" }], + created_at: ago(500), + updated_at: ago(30), + merge_standing: { code: "auto_merge_off", text: "Checks pass and CoderHelm approved #812; auto-merge is off for this repo", next: "A person merges it", needs_person: true, approvals: null }, + checks: { sha: "a1b2c3d", counts: { passed: 6, failed: 0, running: 0, queued: 0, skipped: 0 }, items: [] }, + pr_review: { verdict: "APPROVE", review_sk: "REVIEW#acme/web#812#1", session_id: null, reviewed_sha: "a1b2c3d", at: ago(35) }, +}; + +export const PR_MERGE = { + key: "acme/web#812", + org: "acme", + repo: "acme/web", + number: 812, + title: "Fix the flaky retry in the order queue", + url: "https://github.com/acme/web/pull/812", + author: { login: "coderhelm[bot]", coderhelm: true }, + for: "octocat", + base: "main", + state: "ready_to_merge", + turn: "you", + next: { code: "merge", text: "Ready to merge: checks pass and CoderHelm approved", from: ["person:octocat"], since: ago(30) }, + checks: { total: 6, passed: 6, failed: 0, running: 0 }, + reviews: { approvals: 1, required: 1, coderhelm_verdict: "APPROVE" }, + size: { additions: 42, deletions: 17 }, + coderhelm: { run_id: "run_m1", session_id: "sess_812", what: "Retries a failed order write once after 2 seconds instead of looping, and logs the order id when it gives up." }, + waiting_since: ago(30), +}; + +export const PR_FAILING = { + key: "acme/api#815", + org: "acme", + repo: "acme/api", + number: 815, + title: "Speed up the book search index", + url: "https://github.com/acme/api/pull/815", + author: { login: "coderhelm[bot]", coderhelm: true }, + base: "main", + state: "checks_failing", + turn: "you", + next: { code: "checks_failing", text: "lint fails; CoderHelm can't fix it without your call", from: ["person:octocat"], since: ago(120) }, + checks: { total: 5, passed: 4, failed: 1, running: 0, required_failed: ["lint"] }, + reviews: { approvals: 0, required: 1, coderhelm_verdict: "APPROVE" }, + size: { additions: 230, deletions: 96 }, + coderhelm: { run_id: "run_f1", session_id: "sess_815", what: "Builds the search index in batches of 500 books, so a full rebuild takes minutes instead of an hour." }, + waiting_since: ago(120), +}; + +export const APPROVAL = { + id: "appr_1", + status: "pending", + agent: "coder", + kind: "command", + tool: "shell", + repo: "acme/web", + command: "npm publish --tag next", + run_id: "run_p1", + args: {}, + args_hash: "h", + why: "Publish the bookstore's checkout widget for the docs site", + asked_because: "rule", + reason: "Publishing needs a person", + created_at: ago(70), + expires_at: ago(-600), +}; + +export const PLANS = [ + { plan_id: "plan_1", title: "Split the billing service", description: "", repo: "acme/api", status: "executing", state: "needs_you", summary: "2 of 6 merged, 1 needs you", needs_count: 1, task_count: 6, created_at: ago(2000), updated_at: ago(150), last_activity_at: ago(150) }, + { plan_id: "plan_2", title: "Move book search to its own service", description: "", repo: "acme/api", status: "draft", state: "drafting", task_count: 4, created_at: ago(400), updated_at: ago(400) }, + { plan_id: "plan_3", title: "Old cleanup", description: "", repo: "acme/web", status: "done", state: "done", task_count: 3, created_at: ago(9000), updated_at: ago(9000) }, +]; + +export const FINDING = { + id: "sec_1", + repo: "acme/web", + manifest: "package-lock.json", + ecosystem: "npm", + package: "bookshelf-parser", + version: "2.1.0", + fixed_version: null, + next_build: null, + advisory: { ids: ["GHSA-xxxx-0000-1111"], primary: "GHSA-xxxx-0000-1111", title: "Prototype pollution in bookshelf-parser", summary: "", cvss: 7.5, cvss_vector: null, epss: null, epss_percentile: null, kev: false, kev_due: null, malware: false, cwe: [], published_at: ago(5000), urls: [], source: "osv" }, + scope: "runtime", + relation: "direct", + path: ["bookshelf-parser"], + verdict: "reachable", + evidence: null, + tier: "P1", + due_at: ago(-5000), + status: "no_fix", + pr: null, + dependabot_alert: null, + dismissed: null, + first_seen_at: ago(3000), + updated_at: ago(100), +}; + +export interface InboxMock { + /** Leave out a source, answer it 404 (an older backend), or fail it. */ + runs?: "ok" | "empty" | "old" | "fail"; + approvals?: "ok" | "empty" | "old" | "fail"; + plans?: "ok" | "empty" | "old" | "fail"; + prs?: "ok" | "empty" | "old" | "fail"; + security?: "ok" | "empty" | "old" | "fail"; + /** Hold every inbox read this long, to see the loading state. */ + delayMs?: number; + /** Requests the page sent, for the checks. */ + sent?: { method: string; path: string; body: string }[]; + /** The auto-merge gate on acme/web#812 was stopped. */ + gateStopped?: boolean; +} + +const json = (route: Route, body: unknown, status = 200) => route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); + +export async function mockInbox(page: Page, opts: InboxMock = {}) { + const o = { runs: "ok", approvals: "ok", plans: "ok", prs: "ok", security: "ok", ...opts } as Required> & InboxMock; + 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; + const m = req.method(); + if (m !== "GET") opts.sent?.push({ method: m, path: p, body: req.postData() ?? "" }); + const state = (s: string, body: () => unknown) => { + if (s === "old") return json(route, { error: "Not found" }, 404); + if (s === "fail") return json(route, { error: "boom" }, 500); + return json(route, body()); + }; + const slow = async () => { + if (opts.delayMs) await new Promise((r) => setTimeout(r, opts.delayMs)); + }; + + if (p === "/api/me") return json(route, { user_id: "u_octocat", team_id: "t_acme", github_login: "octocat", email: "octocat@example.com", avatar_url: "", role: "owner", mfa_enabled: false, platform_admin: false, flags: {} }); + if (p === "/api/usage") return json(route, { month: "2026-01", total_tokens: 0, tokens_in: 0, tokens_out: 0, new_tokens: 0, total_runs: 0, max_tokens: 0, limits_legacy: false, limits: [] }); + if (p === "/api/banners") return json(route, { banners: [] }); + if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_acme", org: "acme", status: "active", current: true }] }); + if (p === "/api/support/badge") return json(route, { waiting: 0, queue_open: null }); + + if (p === "/api/runs" && m === "GET") { + await slow(); + const status = url.searchParams.get("status") ?? ""; + if (status.includes("running")) return json(route, { runs: [{ ...QUESTION_RUN, run_id: "run_w1", status: "running" }, { ...QUESTION_RUN, run_id: "run_w2", status: "running" }], next: null }); + if (status === "needs_input") return state(o.runs, () => ({ runs: o.runs === "empty" ? [] : [QUESTION_RUN, HANDOFF_RUN, MERGE_RUN], next: null })); + // The Runs page. + return json(route, { runs: [{ ...MERGE_RUN, status: "running", current_pass: "implement" }, QUESTION_RUN, HANDOFF_RUN], next: null }); + } + const run = p.match(/^\/api\/runs\/([^/]+)(\/.*)?$/); + if (run) { + const sub = run[2] ?? ""; + if (m === "POST" && sub === "/answer") return json(route, { status: "queued", run_id: "run_q2", posted: true, comment_url: "https://github.com/acme/web/issues/41#issuecomment-1" }); + if (m === "POST" && sub === "/retry") return json(route, { status: "queued" }); + if (m === "GET" && sub === "") { + const r = [QUESTION_RUN, HANDOFF_RUN, MERGE_RUN].find((x) => x.run_id === run[1]) ?? { ...MERGE_RUN, run_id: run[1], status: "running", current_pass: "implement", merge_standing: null }; + return json(route, r); + } + return json(route, { error: "Not mocked" }, 404); + } + if (p === "/api/agents/approvals") { + await slow(); + // The Inbox asks for every pending one; a run's page asks for its own (none here). + const all = o.approvals !== "empty" && !url.searchParams.get("run_id") && !url.searchParams.get("thread_id"); + return state(o.approvals, () => ({ approvals: all ? [APPROVAL] : [], can: { approve: true, always: true } })); + } + if (p === "/api/plans") { + await slow(); + return state(o.plans, () => ({ plans: o.plans === "empty" ? [] : PLANS, next_cursor: null })); + } + if (p === "/api/prs") { + await slow(); + return state(o.prs, () => ({ prs: o.prs === "empty" ? [] : [PR_MERGE, PR_FAILING], total: 2, next: null, counts: { turn: { you: 2 } } })); + } + if (p === "/api/prs/detail") { + const n = Number(url.searchParams.get("number")); + const pr = [PR_MERGE, PR_FAILING].find((x) => x.number === n); + if (o.prs === "old" || !pr) return json(route, { error: "Not found" }, 404); + return json(route, { pr, checklist: [], ledger: { open_secs: 0, spans: [], totals: [] }, timeline: [], runs: [] }); + } + if (p === "/api/reviewer/gate") { + if (m === "POST") return json(route, { status: "rearmed", ok: true, message: "Auto-merge re-armed. CoderHelm checks everything again, then merges." }); + return json(route, { repo: "acme/web", pr_number: 812, auto_merge: true, can_control: true, gate: opts.gateStopped ? { state: "stopped", stopped: { by: "octocat", at: ago(60), reason: "Wanted to read it first" } } : { state: "armed" } }); + } + if (p === "/api/security/findings") { + await slow(); + return state(o.security, () => ({ findings: o.security === "empty" ? [] : [FINDING], next_cursor: null })); + } + return json(route, { error: `Not mocked: ${m} ${p}` }, 404); + }); +} + +/** Mark this visit as begun, so "/" stays on Runs instead of opening the Inbox. */ +export async function skipLanding(page: Page) { + await page.addInitScript(() => { + try { + sessionStorage.setItem("ch-landed", "1"); + } catch { + /* ignore */ + } + }); +} + +export async function hideDevOverlay(page: Page) { + await page.addInitScript(() => { + document.addEventListener("DOMContentLoaded", () => { + const s = document.createElement("style"); + s.textContent = "nextjs-portal{display:none!important}"; + document.head.appendChild(s); + }); + }); +} diff --git a/dashboard/e2e/list-and-palette.spec.ts b/dashboard/e2e/list-and-palette.spec.ts index 0ce9cb88..8cf7f093 100644 --- a/dashboard/e2e/list-and-palette.spec.ts +++ b/dashboard/e2e/list-and-palette.spec.ts @@ -52,6 +52,14 @@ interface Backend { } async function mockApi(page: Page, init: Partial = {}): Promise { + // "/" stays on Runs: the visit has begun (a phone's first visit opens the Inbox). + await page.addInitScript(() => { + try { + sessionStorage.setItem("ch-landed", "1"); + } catch { + /* ignore */ + } + }); const db: Backend = { calls: [], role: "admin", searchStatus: 200, ...init }; const json = (route: Route, body: unknown, status = 200) => route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); diff --git a/dashboard/e2e/phone-inbox-shots.spec.ts b/dashboard/e2e/phone-inbox-shots.spec.ts new file mode 100644 index 00000000..b78625e1 --- /dev/null +++ b/dashboard/e2e/phone-inbox-shots.spec.ts @@ -0,0 +1,63 @@ +import { expect, test, type Page } from "@playwright/test"; +import fs from "node:fs"; +import path from "node:path"; +import { hideDevOverlay, mockInbox, skipLanding } from "./inbox-data"; + +// Screenshots of the phone's Inbox and the flows it opens, at 375 wide, with +// the invented bookstore team, for a pull request. Written only when +// E2E_SHOTS_DIR is set; the checks are in phone-inbox.spec.ts. + +const DIR = process.env.E2E_SHOTS_DIR; +const PREFIX = process.env.E2E_SHOTS_PREFIX ?? "phone2-"; + +async function shot(page: Page, name: string) { + fs.mkdirSync(DIR!, { recursive: true }); + await page.addStyleTag({ content: "nextjs-portal{display:none!important}" }); + await page.waitForTimeout(400); + await page.screenshot({ path: path.join(DIR!, `${PREFIX}${name}.png`) }); +} + +test("phone screenshots: the Inbox, its states and its flows", async ({ page }) => { + test.skip(!DIR, "E2E_SHOTS_DIR is not set"); + test.setTimeout(240_000); + await page.setViewportSize({ width: 375, height: 812 }); + await mockInbox(page); + await hideDevOverlay(page); + await skipLanding(page); + + await page.goto("/inbox"); + await expect(page.getByTestId("inbox-row")).toHaveCount(8); + // The count on the Inbox tab is read a moment after the page. + await expect(page.getByTestId("phone-bar-inbox")).toHaveAccessibleName(/decisions wait on you/); + await shot(page, "inbox"); + + await page.goto("/inbox/answer?run=run_q1"); + await expect(page.getByRole("button", { name: "Books only" })).toBeVisible(); + await page.getByRole("button", { name: "Books only" }).click(); + await page.evaluate(() => window.scrollTo(0, 0)); + await shot(page, "answer"); + + await page.goto("/inbox/pr?repo=acme%2Fweb&number=812&run=run_m1"); + await expect(page.getByTestId("pr-verdict")).toContainText("Approved"); + await page.getByTestId("pr-actions").getByRole("button", { name: "Merge" }).click(); + await expect(page.getByRole("dialog", { name: "Merge #812?" })).toBeVisible(); + await shot(page, "merge-sheet"); + await page.keyboard.press("Escape"); + + await page.goto("/runs/detail?id=run_w1"); + await expect(page.getByRole("heading", { level: 1 })).toBeVisible(); + await shot(page, "run-detail"); + + await page.goto("/inbox"); + await page.getByTestId("phone-bar-menu").click(); + await page.getByRole("searchbox", { name: "Search the menu" }).fill("sec"); + await expect(page.getByTestId("menu-search-results")).toBeVisible(); + await shot(page, "menu-search"); + await page.keyboard.press("Escape"); + + await page.unrouteAll({ behavior: "ignoreErrors" }); + await mockInbox(page, { runs: "empty", approvals: "empty", plans: "empty", prs: "empty", security: "empty" }); + await page.goto("/inbox"); + await expect(page.getByTestId("inbox-empty")).toBeVisible(); + await shot(page, "inbox-empty"); +}); diff --git a/dashboard/e2e/phone-inbox.spec.ts b/dashboard/e2e/phone-inbox.spec.ts new file mode 100644 index 00000000..6ca08954 --- /dev/null +++ b/dashboard/e2e/phone-inbox.spec.ts @@ -0,0 +1,328 @@ +import { expect, test, type Page } from "@playwright/test"; +import AxeBuilder from "@axe-core/playwright"; +import { NAV_SECTIONS } from "../src/lib/nav"; +import { hideDevOverlay, mockInbox, skipLanding, type InboxMock } from "./inbox-data"; + +// The phone's Inbox and the flows it opens, with an invented team (the +// bookstore's acme/* repos, octocat): every kind of row and its order, the +// empty, loading, error and older-backend states, the bar, the Menu sheet's +// search and Back, answering a question, approving and merging, handing a +// failing check to CoderHelm and checking a run, at 375px, with no sideways +// scroll at 320 and 375 and no WCAG 2.2 AA failures (target size included). + +const PHONE = { width: 375, height: 760 }; +/** The Pull requests destination is in this build (its page is its own pull request). */ +const HAS_PRS = NAV_SECTIONS.some((s) => s.key === "prs"); + +async function open(page: Page, path: string, mock: InboxMock = {}, opts: { landed?: boolean } = { landed: true }) { + await mockInbox(page, mock); + await hideDevOverlay(page); + if (opts.landed) await skipLanding(page); + await page.setViewportSize(PHONE); + await page.goto(path); +} + +const rows = (page: Page) => page.getByTestId("inbox-row"); + +async function sideways(page: Page): Promise { + return page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); +} + +async function axe(page: Page, what: string) { + const r = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22a", "wcag22aa"]).exclude("nextjs-portal").analyze(); + const found = r.violations.map((v) => `${v.id}: ${v.nodes.length}x ${v.nodes.slice(0, 3).map((n) => n.target.join(" ")).join(" | ")}`); + expect(found, `${what}: axe WCAG 2.2 AA`).toEqual([]); +} + +test.describe.configure({ mode: "parallel" }); + +test("phone: a visit opens on the Inbox, and the bar is Inbox, Runs, PRs, Chat, then Menu", async ({ page }) => { + await open(page, "/", {}, { landed: false }); + await expect(page).toHaveURL(/\/inbox\/?$/); + const bar = page.getByRole("navigation", { name: "Main" }).filter({ has: page.getByTestId("phone-bar-menu") }); + await expect(bar.getByRole("link")).toHaveText(HAS_PRS ? [/^Inbox/, "Runs", "PRs", "Chat"] : [/^Inbox/, "Runs", "Chat"]); + await expect(bar.getByRole("button")).toHaveText(["Menu"]); + // Inbox is current and carries the only count, said in words. + const inbox = bar.getByRole("link", { name: /^Inbox/ }); + await expect(inbox).toHaveAttribute("aria-current", "page"); + await expect(inbox).toHaveAccessibleName(/Inbox, \d+ decisions wait on you/); + await expect(page.getByTestId("phone-bar-menu")).toHaveAccessibleName("Menu"); + // Security and Code review are in the Menu sheet, not the bar. + await expect(bar.getByRole("link", { name: /Security|Review/ })).toHaveCount(0); + // Runs stays Runs once the visit has begun. + await bar.getByRole("link", { name: "Runs" }).click(); + await expect(page).toHaveURL(/localhost:\d+\/$/); + await expect(bar.getByRole("link", { name: "Runs" })).toHaveAttribute("aria-current", "page"); +}); + +test("phone: the Inbox lists every kind of decision, what blocks work first, each naming its ask and opening its item", async ({ page }) => { + await open(page, "/inbox"); + await expect(rows(page)).toHaveCount(8); + // Questions, then tool approvals, plans, hand-offs, pull requests, security. + const kinds = await rows(page).evaluateAll((els) => els.map((e) => e.getAttribute("data-kind"))); + expect(kinds).toEqual(["question", "approval", "plan", "plan", "handoff", "pr", "pr", "security"]); + // Within a kind, the longest wait first. + const text = (await rows(page).locator("[id^=inbox-]").allInnerTexts()).map((t) => t.replace(/\s+/g, " ").trim()); + expect(text).toEqual([ + "Answer: Should a gift card pay for shipping too, or only for books?", + "Approve: CoderHelm asks to run npm publish --tag next: Publish the bookstore's checkout widget for the docs site", + "Plan needs you: Split the billing service: 1 task waits on you (2 of 6 merged, 1 needs you)", + "Approve plan: Move book search to its own service (4 steps)", + "Decide: #44 stays a draft: the returns policy text needs a person's sign-off. Read the new page and mark the pull request ready.", + "Failing: Speed up the book search index. lint fails; CoderHelm can't fix it without your call", + "Merge: Fix the flaky retry in the order queue. Ready to merge: checks pass and CoderHelm approved", + "Fix or dismiss: P1 bookshelf-parser 2.1.0: Prototype pollution in bookshelf-parser. No fixed version yet", + ]); + // The run behind #812 is the same decision as the pull request: listed once. + await expect(page.getByText("Fix the flaky retry in the order queue")).toHaveCount(1); + const hrefs = await rows(page).getByTestId("inbox-row-open").evaluateAll((els) => els.map((e) => (e.getAttribute("href") ?? "").replace("/?", "?"))); + expect(hrefs).toEqual([ + "/inbox/answer?run=run_q1", + "/runs/detail?id=run_p1", + "/plans/detail?id=plan_1", + "/plans/detail?id=plan_2", + "/runs/detail?id=run_h1", + "/inbox/pr?repo=acme%2Fapi&number=815&run=run_f1", + "/inbox/pr?repo=acme%2Fweb&number=812&run=run_m1", + "/security/detail?id=sec_1", + ]); + // Working now, and when it was read. + await expect(page.getByTestId("inbox-status")).toContainText("CoderHelm is working on 2 runs."); + await expect(page.getByTestId("inbox-status")).toContainText("Updated"); + // A row opens its item. + await rows(page).nth(2).getByTestId("inbox-row-open").click(); + await expect(page).toHaveURL(/\/plans\/detail\/?\?id=plan_1$/); +}); + +test("phone: Snooze puts a row aside on this device, by button or by a swipe to the left", async ({ page }) => { + await open(page, "/inbox"); + await expect(rows(page)).toHaveCount(8); + // Every row has a visible Snooze button: the swipe is never the only way. + await expect(page.getByTestId("inbox-snooze")).toHaveCount(8); + await rows(page).first().getByTestId("inbox-snooze").click(); + await expect(rows(page)).toHaveCount(7); + await expect(page.getByTestId("inbox-snoozed-toggle")).toHaveText("Snoozed (1)"); + // A swipe left on the next row (a touch pointer) does the same. + const box = (await rows(page).first().boundingBox())!; + const target = rows(page).first().locator("div").first(); + const y = box.y + 30; + await target.dispatchEvent("pointerdown", { pointerType: "touch", clientX: box.x + box.width - 20, clientY: y, isPrimary: true }); + await target.dispatchEvent("pointermove", { pointerType: "touch", clientX: box.x + box.width - 80, clientY: y, isPrimary: true }); + await target.dispatchEvent("pointermove", { pointerType: "touch", clientX: box.x + 40, clientY: y, isPrimary: true }); + await target.dispatchEvent("pointerup", { pointerType: "touch", clientX: box.x + 40, clientY: y, isPrimary: true }); + await expect(rows(page)).toHaveCount(6); + await expect(page.getByTestId("inbox-snoozed-toggle")).toHaveText("Snoozed (2)"); + // They stay aside after a reload, and come back on request. + await page.reload(); + await expect(rows(page)).toHaveCount(6); + await page.getByTestId("inbox-snoozed-toggle").click(); + await page.getByRole("list", { name: "Snoozed" }).getByRole("button", { name: "Bring back" }).first().click(); + await expect(page.getByRole("list", { name: "Waiting on you" }).getByTestId("inbox-row")).toHaveCount(7); +}); + +test("phone: the Inbox's empty, loading, error and older-backend states", async ({ page }) => { + // Loading: placeholders while the sources answer. + await open(page, "/inbox", { delayMs: 1500 }); + await expect(page.getByTestId("inbox-loading")).toBeVisible(); + await expect(rows(page)).toHaveCount(8); + await page.unrouteAll({ behavior: "ignoreErrors" }); + + // Empty: nothing waits. + await mockInbox(page, { runs: "empty", approvals: "empty", plans: "empty", prs: "empty", security: "empty" }); + await page.reload(); + await expect(page.getByTestId("inbox-empty")).toContainText("Nothing needs you"); + await page.unrouteAll({ behavior: "ignoreErrors" }); + + // Error: every source failed. + await mockInbox(page, { runs: "fail", approvals: "fail", plans: "fail", prs: "fail", security: "fail" }); + await page.reload(); + await expect(page.getByTestId("inbox-error")).toContainText("Couldn't read what needs you"); + await expect(page.getByTestId("inbox-error").getByRole("button", { name: "Try again" })).toBeVisible(); + await page.unrouteAll({ behavior: "ignoreErrors" }); + + // One source failed: the rest still show, and the failure is named. + await mockInbox(page, { security: "fail" }); + await page.reload(); + await expect(page.getByTestId("inbox-partial")).toContainText("Couldn't read security"); + await expect(rows(page)).toHaveCount(7); + await page.unrouteAll({ behavior: "ignoreErrors" }); + + // An older backend without /api/prs: the run behind #812 shows instead, and the screen says why. + await mockInbox(page, { prs: "old" }); + await page.reload(); + await expect(page.getByTestId("inbox-old-prs")).toBeVisible(); + await expect(rows(page).filter({ hasText: "Fix the flaky retry in the order queue" })).toHaveAttribute("data-kind", "handoff"); + await page.unrouteAll({ behavior: "ignoreErrors" }); + + // A backend with none of the sources. + await mockInbox(page, { runs: "old", approvals: "old", plans: "old", prs: "old", security: "old" }); + await page.reload(); + await expect(page.getByTestId("inbox-old")).toContainText("This install can't list what needs you yet"); +}); + +test("phone: answer CoderHelm's question on one screen", async ({ page }) => { + const sent: InboxMock["sent"] = []; + await open(page, "/inbox", { sent }); + await rows(page).first().getByRole("link", { name: "Answer", exact: true }).click(); + await expect(page).toHaveURL(/\/inbox\/answer\/?\?run=run_q1$/); + // The question, why it matters, what CoderHelm did, and where it belongs. + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Add gift cards to the bookstore checkout"); + await expect(page.getByText("Should a gift card pay for shipping too, or only for books?")).toBeVisible(); + await expect(page.getByText("The checkout total and the refund rules both change with the answer.")).toBeVisible(); + await expect(page.getByText("Found two places that add shipping: the cart and the payment step.")).toBeVisible(); + // A suggested answer is one large button; sending carries the run on. + const choice = page.getByRole("button", { name: "Books only" }); + expect((await choice.boundingBox())!.height).toBeGreaterThanOrEqual(44); + await choice.click(); + await expect(page.getByRole("textbox", { name: "Your answer" })).toHaveValue("Books only"); + await page.getByRole("button", { name: "Send answer and continue" }).click(); + await expect(page.getByTestId("answer-sent")).toContainText("CoderHelm is continuing"); + expect(sent.find((r) => r.path === "/api/runs/run_q1/answer")?.body).toBe(JSON.stringify({ answers: [{ question_id: "q1", answer: "Books only" }] })); + await expect(page).toHaveURL(/\/inbox\/?$/, { timeout: 10_000 }); +}); + +test("phone: approve or merge leads with what it does, its checks and the verdict, and merge asks first in a sheet", async ({ page }) => { + await open(page, "/inbox"); + await rows(page).filter({ hasText: "Fix the flaky retry" }).getByRole("link", { name: "Review and merge" }).click(); + await expect(page).toHaveURL(/\/inbox\/pr\/?\?repo=acme%2Fweb&number=812/); + // The summary, the checks and the verdict come before the diff. + const order = await page.locator("[data-testid^=pr-]").evaluateAll((els) => els.map((e) => e.getAttribute("data-testid"))); + expect(order.slice(0, 4)).toEqual(["pr-summary", "pr-checks", "pr-verdict", "pr-diff"]); + await expect(page.getByTestId("pr-summary")).toContainText("Retries a failed order write once"); + await expect(page.getByTestId("pr-checks")).toContainText("All passing"); + await expect(page.getByTestId("pr-verdict")).toContainText("Approved"); + await expect(page.getByTestId("pr-diff")).toContainText("42 added, 17 removed"); + // Approve and Merge sit in a bar at the bottom, above the phone's own bar. + const actions = page.getByTestId("pr-actions"); + const bar = (await page.getByTestId("phone-bar").boundingBox())!; + const box = (await actions.boundingBox())!; + expect(Math.round(box.y + box.height)).toBeLessThanOrEqual(Math.round(bar.y) + 1); + await expect(actions.getByRole("link", { name: /Approve on GitHub/ })).toHaveAttribute("href", "https://github.com/acme/web/pull/812/files"); + // Merge is confirmed in a bottom sheet naming the branch. + await actions.getByRole("button", { name: "Merge" }).click(); + const sheet = page.getByRole("dialog", { name: "Merge #812?" }); + await expect(sheet).toBeVisible(); + await expect(sheet).toContainText("Into main, in acme/web."); + await expect(sheet.getByTestId("merge-ready")).toBeVisible(); + await expect(sheet.getByRole("link", { name: /Merge on GitHub/ })).toHaveAttribute("href", "https://github.com/acme/web/pull/812"); + const sheetBox = (await sheet.boundingBox())!; + expect(Math.round(sheetBox.y + sheetBox.height)).toBe(PHONE.height); + await sheet.getByRole("button", { name: "Cancel" }).click(); + await expect(sheet).toBeHidden(); +}); + +test("phone: a stopped CoderHelm auto-merge is re-armed from the merge sheet", async ({ page }) => { + const sent: InboxMock["sent"] = []; + await open(page, "/inbox/pr?repo=acme%2Fweb&number=812&run=run_m1", { gateStopped: true, sent }); + await page.getByTestId("pr-actions").getByRole("button", { name: "Merge" }).click(); + const sheet = page.getByRole("dialog", { name: "Merge #812?" }); + await sheet.getByRole("button", { name: "Re-arm auto-merge" }).click(); + await expect(sheet).toBeHidden(); + expect(sent.find((r) => r.path === "/api/reviewer/gate")?.body).toBe(JSON.stringify({ repo: "acme/web", pr: 812, action: "rearm" })); +}); + +test("phone: a failing check goes to CoderHelm in one tap, from the Inbox or the merge sheet", async ({ page }) => { + const sent: InboxMock["sent"] = []; + await open(page, "/inbox", { sent }); + const row = rows(page).filter({ hasText: "Speed up the book search index" }); + await row.getByTestId("inbox-fix").click(); + const fix = page.getByRole("dialog", { name: "Hand the failing checks to CoderHelm" }); + await expect(fix.getByTestId("fix-checks")).toHaveText("lint"); + await fix.getByTestId("fix-start").click(); + await expect(fix).toBeHidden(); + await expect(row).toContainText("CoderHelm is fixing it."); + expect(sent.filter((r) => r.path === "/api/runs/run_f1/retry")).toHaveLength(1); + + // From the pull request: Merge says what blocks it and offers the hand-off. + await page.goto("/inbox/pr?repo=acme%2Fapi&number=815&run=run_f1"); + await expect(page.getByTestId("pr-checks")).toContainText("1 failing"); + await page.getByTestId("pr-actions").getByRole("button", { name: "Merge" }).click(); + const sheet = page.getByRole("dialog", { name: "Merge #815?" }); + await expect(sheet.getByTestId("merge-blocked")).toContainText("1 check fails."); + await sheet.getByTestId("merge-fix").click(); + await page.getByRole("dialog", { name: "Hand the failing checks to CoderHelm" }).getByTestId("fix-start").click(); + await expect(page.getByTestId("pr-checks")).toContainText("CoderHelm is fixing it."); + expect(sent.filter((r) => r.path === "/api/runs/run_f1/retry")).toHaveLength(2); +}); + +test("phone: an older backend's pull request screen reads the run that opened it", async ({ page }) => { + await open(page, "/inbox/pr?repo=acme%2Fweb&number=812&run=run_m1", { prs: "old" }); + await expect(page.getByTestId("pr-summary")).toContainText("auto-merge is off for this repo"); + await expect(page.getByTestId("pr-checks")).toContainText("All passing"); + await expect(page.getByTestId("pr-verdict")).toContainText("Approved"); +}); + +test("phone: check a run from the Runs tab", async ({ page }) => { + await open(page, "/inbox"); + await page.getByRole("navigation", { name: "Main" }).getByRole("link", { name: "Runs" }).click(); + await expect(page).toHaveURL(/localhost:\d+\/$/); + await page.getByRole("link", { name: /Fix the flaky retry in the order queue/ }).first().click(); + await expect(page).toHaveURL(/\/runs\/detail\/?\?id=run_m1/); + await expect(page.getByRole("heading", { level: 1 })).toContainText("Fix the flaky retry in the order queue"); + expect(await sideways(page)).toBeLessThanOrEqual(0); +}); + +test("phone: the Menu sheet searches every page, closes on Back and has no count on its button", async ({ page }) => { + await open(page, "/inbox"); + const menu = page.getByTestId("phone-bar-menu"); + await expect(menu.locator("[aria-hidden=true].rounded-full")).toHaveCount(0); + await menu.click(); + const sheet = page.getByRole("dialog", { name: "Menu" }); + await expect(sheet).toBeVisible(); + // Search is first, above the groups; the groups are the desktop sidebar's. + const search = sheet.getByRole("searchbox", { name: "Search the menu" }); + await expect(search).toBeVisible(); + await expect(sheet.getByTestId("main-nav").getByRole("link")).toHaveText( + NAV_SECTIONS.filter((s) => s.flag !== "plugins").map((s) => new RegExp(`^${s.label}`)), + ); + // Rows are 54px tall. + for (const row of await sheet.getByTestId("main-nav").getByRole("link").all()) expect((await row.boundingBox())!.height).toBeGreaterThanOrEqual(54); + await search.fill("security pol"); + await expect(sheet.getByTestId("menu-search-results").getByRole("link")).toHaveText([/Policy\s*Security/]); + await expect(sheet.getByTestId("main-nav")).toHaveCount(0); + await search.fill("zzz"); + await expect(sheet.getByTestId("menu-search-results")).toContainText("No page matches"); + // Back closes the sheet and stays on the page; another Back leaves it. + await page.goBack(); + await expect(sheet).toBeHidden(); + await expect(page).toHaveURL(/\/inbox\/?$/); + // A search result goes there, and Back from it returns to the page under the sheet. + await menu.click(); + await search.fill("plans"); + await sheet.getByTestId("menu-search-results").getByRole("link", { name: /^Plans/ }).first().click(); + await expect(page).toHaveURL(/\/plans\/?$/); + await expect(sheet).toBeHidden(); + await page.goBack(); + await expect(page).toHaveURL(/\/inbox\/?$/); + // Close is visible and named, and takes the sheet's history entry with it. + await menu.click(); + await sheet.getByRole("button", { name: "Close" }).click(); + await expect(sheet).toBeHidden(); + await expect(page).toHaveURL(/\/inbox\/?$/); +}); + +for (const path of ["/inbox", "/inbox/answer?run=run_q1", "/inbox/pr?repo=acme%2Fapi&number=815&run=run_f1"]) { + test(`phone: ${path} has no sideways scroll at 320 and 375, and passes axe WCAG 2.2 AA`, async ({ page }) => { + await open(page, path); + for (const width of [320, 375]) { + await page.setViewportSize({ width, height: 760 }); + await page.waitForLoadState("networkidle", { timeout: 15_000 }).catch(() => {}); + await page.waitForTimeout(200); + expect(await sideways(page), `${path} at ${width}px`).toBeLessThanOrEqual(0); + } + await axe(page, path); + }); +} + +test("phone: the Menu sheet and the merge sheet pass axe WCAG 2.2 AA", async ({ page }) => { + await open(page, "/inbox"); + await page.getByTestId("phone-bar-menu").click(); + await expect(page.getByRole("dialog", { name: "Menu" })).toBeVisible(); + await page.getByRole("searchbox", { name: "Search the menu" }).fill("set"); + await axe(page, "Menu sheet with search"); + await page.keyboard.press("Escape"); + await page.goto("/inbox/pr?repo=acme%2Fweb&number=812&run=run_m1"); + await page.getByTestId("pr-actions").getByRole("button", { name: "Merge" }).click(); + await expect(page.getByRole("dialog", { name: "Merge #812?" })).toBeVisible(); + await axe(page, "merge sheet"); +}); diff --git a/dashboard/e2e/phone-nav.spec.ts b/dashboard/e2e/phone-nav.spec.ts index 091f4387..1b30f14d 100644 --- a/dashboard/e2e/phone-nav.spec.ts +++ b/dashboard/e2e/phone-nav.spec.ts @@ -1,5 +1,5 @@ import { expect, test, type Locator, type Page } from "@playwright/test"; -import { NAV_SECTIONS, PHONE_BAR_KEYS, phoneBar, type NavSection } from "../src/lib/nav"; +import { NAV_SECTIONS, PHONE_BAR_KEYS, phoneBar, phoneLabel, type NavSection } from "../src/lib/nav"; import { mockWideApi } from "./wide-data"; // The dashboard on a phone. Every page a menu item opens is drawn at 375px @@ -18,6 +18,12 @@ const ROUTES = [...new Set(NAV_SECTIONS.flatMap((s) => s.pages.map((p) => p.href async function hideDevOverlay(page: Page) { await page.addInitScript(() => { + // The visit has begun: "/" stays on Runs (a first visit on a phone opens the Inbox; phone-inbox.spec.ts). + try { + sessionStorage.setItem("ch-landed", "1"); + } catch { + /* ignore */ + } document.addEventListener("DOMContentLoaded", () => { const s = document.createElement("style"); s.textContent = "nextjs-portal{display:none!important}"; @@ -99,20 +105,24 @@ for (const route of ROUTES) { }); } -test("phone: the bottom bar holds Runs, Review, Chat and Security, then Menu; the current page is marked", async ({ page }) => { +test("phone: the bottom bar holds Inbox, Runs, PRs and Chat, then Menu; the current page is marked", async ({ page }) => { await mockWideApi(page); await hideDevOverlay(page); await page.setViewportSize({ width: 375, height: 740 }); - await page.goto("/reviewer/stale"); + await page.goto("/"); const bar = page.getByRole("navigation", { name: "Main" }); - await expect(bar.getByRole("link")).toHaveText(["Runs", "Review", "Chat", /Security/]); - await expect(bar.getByRole("link", { name: "Review" })).toHaveAttribute("aria-current", "page"); - // Security's count is said, not only drawn. - await expect(bar.getByRole("link", { name: /^Security/ })).toHaveAccessibleName(/2 urgent security findings/); - // A page only in the sheet marks Menu. - await page.goto("/analytics"); - await expect(page.getByRole("button", { name: /^Menu/ })).toHaveAttribute("aria-current", "true"); - await expect(bar.locator('[aria-current="page"]')).toHaveCount(0); + const prs = NAV_SECTIONS.some((s) => s.key === "prs"); + await expect(bar.getByRole("link")).toHaveText(prs ? [/^Inbox/, "Runs", "PRs", "Chat"] : [/^Inbox/, "Runs", "Chat"]); + await expect(bar.getByRole("link", { name: "Runs" })).toHaveAttribute("aria-current", "page"); + // Only Inbox carries a count, said in words; Menu never does. + await expect(bar.getByRole("link", { name: /^Inbox/ })).toHaveAccessibleName(/^Inbox, \d+ decisions? waits? on you$/); + await expect(page.getByRole("button", { name: /^Menu/ })).toHaveAccessibleName("Menu"); + // Security and Code review are pages in the sheet: Menu is marked on them. + for (const path of ["/security", "/reviewer/stale", "/analytics"]) { + await page.goto(path); + await expect(page.getByRole("button", { name: /^Menu/ })).toHaveAttribute("aria-current", "true"); + await expect(bar.locator('[aria-current="page"]')).toHaveCount(0); + } // The bar sits at the bottom of the screen. const box = await page.getByTestId("phone-bar").boundingBox(); expect(Math.round((box?.y ?? 0) + (box?.height ?? 0))).toBe(740); @@ -179,14 +189,15 @@ test("phone: the team switcher in the Menu sheet lists every team in rows a thum await expect(sheet.getByRole("button", { name: /example-org$/ })).toHaveAttribute("aria-current", "true"); }); -test("phone: the bar keeps a place for Pull requests", () => { - // The kept place is in the bar's order, second, after Runs. - expect(PHONE_BAR_KEYS[1]).toBe("pull-requests"); +test("phone: the bar is Inbox, Runs, PRs and Chat; without the Pull requests page its place is left out", () => { + expect([...PHONE_BAR_KEYS]).toEqual(["inbox", "runs", "prs", "chat"]); const sec = (key: string, label: string): NavSection => ({ key, label, icon: "reviews", pages: [{ href: `/${key}`, label }] }); - const visible = [...NAV_SECTIONS, sec("pull-requests", "Pull requests")].map((section) => ({ section, href: section.pages[0].href })); - // Once a Pull requests destination exists it is in the bar and Security moves into the Menu sheet. - expect(phoneBar(visible).map((x) => x.section.key)).toEqual(["runs", "pull-requests", "reviews", "chat"]); - // Today: Runs, Code review, Chat and Security. - const today = NAV_SECTIONS.map((section) => ({ section, href: section.pages[0].href })); - expect(phoneBar(today).map((x) => x.section.key)).toEqual(["runs", "reviews", "chat", "security"]); + const base = NAV_SECTIONS.filter((s) => s.key !== "prs"); + const withPrs = [...base, sec("prs", "Pull requests")].map((section) => ({ section, href: section.pages[0].href })); + expect(phoneBar(withPrs).map((x) => x.section.key)).toEqual(["inbox", "runs", "prs", "chat"]); + // "Pull requests" is "PRs" in the bar, where five items share 320px. + expect(phoneLabel(sec("prs", "Pull requests"))).toBe("PRs"); + // An older build without the page: the slot is left out, never filled by Security or Code review. + const without = base.map((section) => ({ section, href: section.pages[0].href })); + expect(phoneBar(without).map((x) => x.section.key)).toEqual(["inbox", "runs", "chat"]); }); diff --git a/dashboard/e2e/select.spec.ts b/dashboard/e2e/select.spec.ts index a8b3d115..78f6f79a 100644 --- a/dashboard/e2e/select.spec.ts +++ b/dashboard/e2e/select.spec.ts @@ -8,6 +8,14 @@ import { expect, test, type Locator, type Page, type Route } from "@playwright/t // phone it is a bottom sheet. Every API call is answered here. async function mockApi(page: Page): Promise { + // "/" stays on Runs: the visit has begun (a phone's first visit opens the Inbox). + await page.addInitScript(() => { + try { + sessionStorage.setItem("ch-landed", "1"); + } catch { + /* ignore */ + } + }); const calls: string[] = []; const json = (route: Route, body: unknown, status = 200) => route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); diff --git a/dashboard/e2e/setup.spec.ts b/dashboard/e2e/setup.spec.ts index a256a64b..ef6595b3 100644 --- a/dashboard/e2e/setup.spec.ts +++ b/dashboard/e2e/setup.spec.ts @@ -13,10 +13,10 @@ const lastDecisions = (db: SetupDb) => calls(db, "PUT /api/setup/runs/run_03/dec const decisionOf = (d: Decisions, repo: string, id: string) => d.items.find((i) => i.repo === repo && i.setting_id === id)?.decision; test.describe("Setup", () => { - test("the menu puts Setup first with a count of new recommendations plus repos not set up or failed", async ({ page }) => { + test("the menu puts Setup first, after the Inbox, with a count of new recommendations plus repos not set up or failed", async ({ page }) => { const db = await mockSetup(page); await page.goto("/setup"); - const link = page.getByTestId("main-nav").getByRole("link").first(); + const link = page.getByTestId("main-nav").getByRole("link").nth(1); // 3 new recommendations + 2 repos not set up + 1 whose setup failed // (listed first on the page, so the badge counts it too). await expect(link).toHaveText(/^Setup6 things to set up$/); diff --git a/dashboard/e2e/shell-menu.spec.ts b/dashboard/e2e/shell-menu.spec.ts index 0b39e638..7f0f10e7 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(["Inbox", /^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", { 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/wide-data/addresses.ts b/dashboard/e2e/wide-data/addresses.ts index 648013d9..f6b779b4 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}`, + "/inbox/answer": `?run=${RUN_ID}`, + "/inbox/pr": `?repo=${encodeURIComponent(REPO)}&number=12345&run=${RUN_ID}`, "/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/inbox.ts b/dashboard/e2e/wide-data/inbox.ts new file mode 100644 index 00000000..e1acd146 --- /dev/null +++ b/dashboard/e2e/wide-data/inbox.ts @@ -0,0 +1,32 @@ +import type { Handler } from "./index"; +import { iso, PR_URL, REPO, TITLE, TOKEN } from "./long"; +import { RUN_ID, SESSION_ID } from "./ids"; + +// The Inbox's pull requests (`GET /api/prs?turn=you`) and the approve or +// merge screen (`GET /api/prs/detail`), with long names and an unbroken check. + +const PR = { + key: `${REPO}#12345`, + org: "your-team", + repo: REPO, + number: 12345, + title: TITLE, + url: PR_URL, + author: { login: "coderhelm[bot]", coderhelm: true }, + base: "main", + state: "checks_failing", + turn: "you", + next: { code: "checks_failing", text: `Needs a fix for ${TOKEN}, then your approval`, from: ["person:dana-developer-with-a-long-login"], since: iso(300) }, + checks: { total: 9, passed: 7, failed: 2, running: 0, required_failed: [TOKEN, "build-and-test-every-package-in-the-monorepo-on-node-22"] }, + reviews: { approvals: 0, required: 2, coderhelm_verdict: "REQUEST_CHANGES" }, + size: { additions: 1204, deletions: 388 }, + coderhelm: { run_id: RUN_ID, session_id: SESSION_ID, what: `${TITLE}. ${TOKEN}` }, + waiting_since: iso(300), +}; + +export const inboxData: Handler = ({ method, path }) => { + if (method !== "GET") return undefined; + if (path === "/api/prs") return { prs: [PR], total: 1, next: null, counts: { turn: { you: 1 } } }; + if (path === "/api/prs/detail") return { pr: PR, checklist: [], ledger: { open_secs: 0, spans: [], totals: [] }, timeline: [], runs: [] }; + return undefined; +}; diff --git a/dashboard/e2e/wide-data/index.ts b/dashboard/e2e/wide-data/index.ts index 01f9dc32..63f188c0 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 { inboxData } from "./inbox"; // 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, inboxData]; /** 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/package-lock.json b/dashboard/package-lock.json index 8d8bfb91..97f03861 100644 --- a/dashboard/package-lock.json +++ b/dashboard/package-lock.json @@ -25,6 +25,7 @@ "shiki": "4.6.0" }, "devDependencies": { + "@axe-core/playwright": "4.14.0", "@fontsource/dejavu-mono": "5.3.0", "@fontsource/dejavu-sans": "5.3.0", "@playwright/test": "^1.65.1", @@ -62,6 +63,22 @@ "url": "https://github.com/sponsors/antfu" } }, + "node_modules/@axe-core/playwright": { + "version": "4.14.0", + "resolved": "https://registry.npmjs.org/@axe-core/playwright/-/playwright-4.14.0.tgz", + "integrity": "sha512-SGUhG5PIHd2eMdpgBF2PyQLOhX+qyDR2PT4cmoS4Qk2ak+jX/rrSvst9l0PGv5WTHolKpUMvVmoHpr4cZgf1RQ==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "axe-core": "~4.14.0" + }, + "engines": { + "node": ">=22.12.0" + }, + "peerDependencies": { + "playwright-core": ">= 1.0.0" + } + }, "node_modules/@braintree/sanitize-url": { "version": "7.1.2", "resolved": "https://registry.npmjs.org/@braintree/sanitize-url/-/sanitize-url-7.1.2.tgz", @@ -2313,6 +2330,16 @@ "node": ">=10" } }, + "node_modules/axe-core": { + "version": "4.14.1", + "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.14.1.tgz", + "integrity": "sha512-FHfa+lmNjQZfJz1q8wKqIDwC6DExcHt/pkjNQb09a3NPjCKg2rhu5qb2S4r76ASyFNNtuFooJpZe37OgudVGtQ==", + "dev": true, + "license": "MPL-2.0", + "engines": { + "node": ">=4" + } + }, "node_modules/bail": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz", diff --git a/dashboard/package.json b/dashboard/package.json index c83dbc5c..375155ce 100644 --- a/dashboard/package.json +++ b/dashboard/package.json @@ -33,6 +33,7 @@ "shiki": "4.6.0" }, "devDependencies": { + "@axe-core/playwright": "4.14.0", "@fontsource/dejavu-mono": "5.3.0", "@fontsource/dejavu-sans": "5.3.0", "@playwright/test": "^1.65.1", diff --git a/dashboard/src/app/inbox/answer/page.tsx b/dashboard/src/app/inbox/answer/page.tsx new file mode 100644 index 00000000..32cc4d4c --- /dev/null +++ b/dashboard/src/app/inbox/answer/page.tsx @@ -0,0 +1,120 @@ +"use client"; + +import Link from "next/link"; +import { useRouter, useSearchParams } from "next/navigation"; +import { Suspense, useCallback, useEffect, useState } from "react"; +import { Page, PageHeader } from "@/components/page"; +import { Problem } from "@/components/problem"; +import { Skeleton } from "@/components/skeleton"; +import { EmptyState } from "@/components/empty-state"; +import { CheckIcon, ExternalLinkIcon } from "@/components/icons"; +import { buttonClass, linkButton } from "@/components/ui"; +import { useCan } from "@/hooks/use-can"; +import { api, ApiError, type RunDetail } from "@/lib/api"; +import { inboxChanged } from "@/lib/inbox"; +import { RunQuestions } from "@/app/runs/detail/run-questions"; + +// Answer CoderHelm's question, on one screen: the question and why it +// matters, the run and pull request it belongs to, what CoderHelm did last, +// its suggested answers as large buttons and a reply box (the run page's own +// form, components shared). Sending carries the run on and goes back to the +// Inbox. + +export default function AnswerPage() { + return ( + + + + ); +} + +function Answer() { + const runId = useSearchParams().get("run") ?? ""; + const router = useRouter(); + const { can } = useCan(); + const [run, setRun] = useState(null); + const [error, setError] = useState<{ title: string; details?: string } | null>(null); + const [sent, setSent] = useState(false); + + const load = useCallback(() => { + if (!runId) { + setError({ title: "No run in this link" }); + return; + } + setError(null); + api.getRun(runId).then(setRun, (e) => + setError(e instanceof ApiError && e.status === 404 ? { title: "This run no longer exists" } : { title: "Couldn't load the question", details: e instanceof Error ? e.message : String(e) }), + ); + }, [runId]); + useEffect(load, [load]); + + const runHref = `/runs/detail?id=${encodeURIComponent(runId)}`; + const questions = run?.questions ?? []; + const waiting = run?.status === "needs_input" && questions.length > 0; + const tried = (run?.progress_notes ?? []).slice(-2).map((n) => n.message.trim()).filter(Boolean); + const pr = run?.pr_url ? { url: run.pr_url, n: run.pr_number } : null; + + return ( + + {run.repo}{run.pr_number ? ` · #${run.pr_number}` : ""} : undefined} + /> +
+ {error ? ( + Back to the Inbox}> + {error.details ? "Nothing was sent. Check your connection and try again." : "It may have been answered or closed already."} + + ) : !run ? ( +
+ + +
+ ) : sent ? ( + } title="CoderHelm is continuing" testId="answer-sent" action={Back to the Inbox}> + Your answer is with it. You hear back here when it needs you again or its pull request is ready. + + ) : !waiting ? ( + } title="Nothing to answer here now" testId="answer-moved-on" action={Open the run}> + This run isn't waiting on a question any more. Someone may have answered it already. + + ) : ( + <> + {(tried.length > 0 || run.waiting_on?.detail) && ( +
+

What CoderHelm did so far

+
    + {(tried.length ? tried : [run.waiting_on!.detail]).map((t) => ( +
  • {t}
  • + ))} +
+
+ )} + { + inboxChanged(); + setSent(true); + window.setTimeout(() => router.push("/inbox"), 2500); + }} + /> +

+ Open the whole run + {pr && ( + + {pr.n ? `Pull request #${pr.n} on GitHub` : "The pull request on GitHub"} + + (opens in a new tab) + + )} +

+ + )} +
+
+ ); +} diff --git a/dashboard/src/app/inbox/fix-sheet.tsx b/dashboard/src/app/inbox/fix-sheet.tsx new file mode 100644 index 00000000..7621040a --- /dev/null +++ b/dashboard/src/app/inbox/fix-sheet.tsx @@ -0,0 +1,106 @@ +"use client"; + +import { useState } from "react"; +import { Modal } from "@/components/modal"; +import { buttonClass } from "@/components/ui"; +import { useToast } from "@/components/toast"; +import { api, ApiError } from "@/lib/api"; +import { inboxChanged } from "@/lib/inbox"; + +/** Words for a hand-off the server refused. Its own sentence when it sent one. */ +export function fixError(e: unknown): string { + if (e instanceof ApiError) { + if (e.status === 403) return "Only members can hand work to CoderHelm. Ask an admin for member access."; + if (e.status === 429) return "The monthly token limit is reached, so no new work can start."; + if (e.status === 400 || e.status === 409) return e.message && !/error \d+/.test(e.message) ? e.message : "This run can't start again in its current state. Open it to see where it is now."; + } + return "CoderHelm didn't get it. Try again in a moment."; +} + +/** + * "Fix with CoderHelm": a short sheet naming the failing checks, then one + * tap. It picks the run up again on its own pull request (the run's Retry, + * the same as on the run page), so CoderHelm works on what failed. + */ +export function FixSheet({ + open, + onOpenChange, + runId, + checks, + where, + onStarted, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; + runId: string; + /** The failing checks' names, when known. */ + checks: string[]; + /** "acme/web · #812". */ + where: string; + onStarted: () => void; +}) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const { toast } = useToast(); + const start = async () => { + setBusy(true); + setError(null); + try { + await api.retryRun(runId); + toast("CoderHelm is fixing it. The result shows here when the checks run again."); + inboxChanged(); + onOpenChange(false); + onStarted(); + } catch (e) { + setError(fixError(e)); + } finally { + setBusy(false); + } + }; + return ( + { + if (!o) setError(null); + onOpenChange(o); + }} + sheet + title="Hand the failing checks to CoderHelm" + description={where} + testId="fix-sheet" + footer={ + <> + + + + } + > +
+ {checks.length > 0 ? ( + <> +

{checks.length === 1 ? "This check fails:" : `These ${checks.length} checks fail:`}

+
    + {checks.map((c) => ( +
  • + {c} +
  • + ))} +
+ + ) : ( +

A check fails on this pull request.

+ )} +

CoderHelm picks its run up again on the same pull request, reads why each check failed and pushes a fix.

+ {error && ( +

+ {error} +

+ )} +
+
+ ); +} diff --git a/dashboard/src/app/inbox/page.tsx b/dashboard/src/app/inbox/page.tsx new file mode 100644 index 00000000..443239ce --- /dev/null +++ b/dashboard/src/app/inbox/page.tsx @@ -0,0 +1,317 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useRef, useState } from "react"; +import { Page, PageHeader } from "@/components/page"; +import { EmptyState } from "@/components/empty-state"; +import { Problem } from "@/components/problem"; +import { Skeleton } from "@/components/skeleton"; +import { Time } from "@/components/list"; +import { CheckIcon, InboxIcon } from "@/components/icons"; +import { buttonClass, focusRing, linkButton } from "@/components/ui"; +import { useToast } from "@/components/toast"; +import { loadInbox, readSnoozed, rememberInboxCount, SNOOZE_HOURS, writeSnoozed, type InboxKind, type InboxResult, type InboxRow } from "@/lib/inbox"; +import { FixSheet } from "./fix-sheet"; + +// The phone's home: every decision waiting on this person, one row each, +// what blocks work first (lib/inbox.ts). Each row names the ask and opens the +// exact item. A swipe to the left snoozes a row; the Snooze button on every +// row does the same, so nothing needs the gesture. + +const KIND_LABEL: Record = { + question: "Question", + approval: "Approval", + plan: "Plan", + handoff: "Handed to you", + pr: "Pull request", + security: "Security", +}; + +const KIND_TONE: Record = { + question: "border-amber-400/40 bg-amber-400/10 text-amber-200", + approval: "border-amber-400/40 bg-amber-400/10 text-amber-200", + plan: "border-sky-400/40 bg-sky-400/10 text-sky-200", + handoff: "border-amber-400/40 bg-amber-400/10 text-amber-200", + pr: "border-violet-400/40 bg-violet-400/10 text-violet-200", + security: "border-red-400/40 bg-red-400/10 text-red-200", +}; + +/** How far a finger moves left before a release snoozes the row. */ +const SWIPE_PX = 96; + +export default function InboxPage() { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(true); + const [readAt, setReadAt] = useState(null); + const [snoozed, setSnoozed] = useState>({}); + const [showSnoozed, setShowSnoozed] = useState(false); + const [fixing, setFixing] = useState>(new Set()); + const [fixRow, setFixRow] = useState(null); + const { toast } = useToast(); + + const load = useCallback(async () => { + setLoading(true); + setError(null); + try { + const r = await loadInbox(); + setData(r); + setReadAt(new Date().toISOString()); + setSnoozed(readSnoozed()); + if (r.sources.some((s) => s.read === "ok")) rememberInboxCount(r.rows.length); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setLoading(false); + } + }, []); + + useEffect(() => { + void load(); + }, [load]); + + const snooze = (row: InboxRow) => { + const next = { ...readSnoozed(), [row.key]: Date.now() + SNOOZE_HOURS * 3_600_000 }; + writeSnoozed(next); + setSnoozed(next); + toast(`Snoozed for ${SNOOZE_HOURS} hours. It comes back by itself.`); + }; + const unsnooze = (row: InboxRow) => { + const next = { ...readSnoozed() }; + delete next[row.key]; + writeSnoozed(next); + setSnoozed(next); + }; + + const sources = data?.sources ?? []; + const anyRead = sources.some((s) => s.read === "ok"); + const failed = sources.filter((s) => s.read === "failed"); + const allOld = sources.length > 0 && sources.every((s) => s.read === "old"); + const rows = data?.rows ?? []; + const active = rows.filter((r) => !snoozed[r.key]); + const asleep = rows.filter((r) => snoozed[r.key]); + + return ( + + void load()} disabled={loading} className={buttonClass("secondary", "sm")} data-testid="inbox-refresh"> + {loading && data ? "Refreshing…" : "Refresh"} + + } + /> + +

+ {data?.working != null && ( + + {data.working === 0 ? "CoderHelm has nothing running." : data.working === 1 ? "CoderHelm is working on 1 run." : `CoderHelm is working on ${data.working} runs.`}{" "} + + See runs + + + )} + {readAt && !loading && ( + + Updated + )} +

+ +
+ {loading && !data ? ( +
+ {[0, 1, 2].map((i) => ( +
+ + + +
+ ))} +
+ ) : error || (data && !anyRead && failed.length > 0) ? ( + void load()} details={error ?? failed.map((f) => f.name).join(", ")} testId="inbox-error"> + Nothing was changed. Check your connection and try again. + + ) : allOld ? ( + } + title="This install can't list what needs you yet" + testId="inbox-old" + action={ + <> + + Runs + + + Plans + + + } + > + Update CoderHelm to see questions, approvals and pull requests in one place. Until then, runs waiting on you are under Runs. + + ) : ( + <> + {failed.length > 0 && ( + f.name.toLowerCase()).join(" and ")}`} onRetry={() => void load()} testId="inbox-partial"> + What else needs you is below; this list may be missing some. + + )} + {active.length === 0 ? ( + } title="Nothing needs you" testId="inbox-empty"> + When CoderHelm asks a question, a plan waits for your approval or a pull request is your turn, it shows here. + + ) : ( +
    + {active.map((row) => ( + snooze(row)} onFix={() => setFixRow(row)} /> + ))} +
+ )} + {sources.some((s) => s.read === "old" && s.name === "Pull requests") && anyRead && ( +

+ Pull requests waiting on your review show here once this install is updated. +

+ )} + {asleep.length > 0 && ( +
+ + {showSnoozed && ( +
    + {asleep.map((row) => ( + unsnooze(row)} onFix={() => setFixRow(row)} /> + ))} +
+ )} +
+ )} + + )} +
+ + {fixRow?.fix && ( + !o && setFixRow(null)} + runId={fixRow.fix.runId} + checks={fixRow.fix.checks} + where={fixRow.where} + onStarted={() => setFixing((s) => new Set(s).add(fixRow.key))} + /> + )} +
+ ); +} + +/** The button that does the row's ask: answer, open the pull request, open the item. */ +function primaryLabel(row: InboxRow): string { + switch (row.kind) { + case "question": + return "Answer"; + case "pr": + return row.verb === "Merge" ? "Review and merge" : "Open"; + case "handoff": + return row.pr && row.href.startsWith("/inbox/pr") ? "Open" : "Open run"; + case "plan": + return "Open plan"; + case "security": + return "Open finding"; + default: + return "Open"; + } +} + +function InboxItem({ + row, + snoozed = false, + fixing, + onSnooze, + onFix, +}: { + row: InboxRow; + snoozed?: boolean; + fixing: boolean; + onSnooze: () => void; + onFix: () => void; +}) { + // Swipe left to snooze, on touch only; the Snooze button does the same. + const start = useRef<{ x: number; y: number } | null>(null); + const [dx, setDx] = useState(0); + const onPointerDown = (e: React.PointerEvent) => { + if (e.pointerType !== "touch" || snoozed) return; + start.current = { x: e.clientX, y: e.clientY }; + }; + const onPointerMove = (e: React.PointerEvent) => { + const s = start.current; + if (!s) return; + const x = e.clientX - s.x; + if (Math.abs(e.clientY - s.y) > Math.abs(x)) { + start.current = null; + setDx(0); + return; + } + setDx(Math.min(0, x)); + }; + const onPointerUp = () => { + if (start.current && dx <= -SWIPE_PX) onSnooze(); + start.current = null; + setDx(0); + }; + const titleId = `inbox-${row.key.replace(/[^a-zA-Z0-9_-]/g, "-")}`; + + return ( +
  • + {dx < 0 && ( + + )} +
    + + + {KIND_LABEL[row.kind]} + {row.since && + + {row.verb}: {row.ask} + + {row.where} + {fixing && ( + + CoderHelm is fixing it. + + )} + +
    + + {primaryLabel(row)} + + {row.fix && !fixing && ( + + )} + +
    +
    +
  • + ); +} diff --git a/dashboard/src/app/inbox/pr/page.tsx b/dashboard/src/app/inbox/pr/page.tsx new file mode 100644 index 00000000..88f9df46 --- /dev/null +++ b/dashboard/src/app/inbox/pr/page.tsx @@ -0,0 +1,417 @@ +"use client"; + +import Link from "next/link"; +import { useSearchParams } from "next/navigation"; +import { Suspense, useCallback, useEffect, useState } from "react"; +import { Page, PageHeader } from "@/components/page"; +import { Problem } from "@/components/problem"; +import { Skeleton } from "@/components/skeleton"; +import { Modal } from "@/components/modal"; +import { ExternalLinkIcon } from "@/components/icons"; +import { buttonClass, linkButton } from "@/components/ui"; +import { useToast } from "@/components/toast"; +import { api, ApiError, request, type GateDetail, type RunDetail } from "@/lib/api"; +import { inboxChanged } from "@/lib/inbox"; +import { FixSheet } from "../fix-sheet"; + +// Approve or merge a pull request, on one screen. What it is and why, its +// checks and CoderHelm's review verdict come first; the diff after them, one +// tap away. Approve and Merge sit in a bar at the bottom, in the thumb's +// reach. Merge asks first, in a sheet that names the target branch and what +// still blocks it; a red check offers the hand-off to CoderHelm instead. +// +// Read from `GET /api/prs/detail` (newer backends), else from the run that +// opened the pull request. The dashboard has no approve or merge endpoint of +// its own: both are done on GitHub from here, except re-arming a stopped +// CoderHelm auto-merge, which is. + +interface Check { + name: string; + url?: string | null; +} + +interface PrView { + repo: string; + number: number; + title: string; + url: string | null; + base: string | null; + author: string | null; + /** What changed and why, in CoderHelm's words or the needs sentence. */ + summary: string | null; + next: string | null; + checks: { passed: number; failed: number; running: number; failing: Check[] } | null; + verdict: string | null; + reviewHref: string | null; + approvals: { have: number; need: number } | null; + size: { additions: number; deletions: number } | null; + conflict: boolean; + runId: string | null; +} + +/** The parts of `GET /api/prs/detail` this screen reads. */ +interface PrDetailReply { + pr: { + repo: string; + number: number; + title: string; + url?: string; + base?: string; + author?: { login: string }; + next?: { text?: string } | null; + checks?: { passed: number; failed: number; running: number; required_failed?: string[] } | null; + reviews?: { approvals: number; required: number; coderhelm_verdict?: string | null } | null; + conflict?: boolean | null; + size?: { additions: number; deletions: number } | null; + coderhelm?: { run_id?: string | null; session_id?: string | null; what?: string } | null; + }; +} + +function fromPrs(d: PrDetailReply): PrView { + const p = d.pr; + return { + repo: p.repo, + number: p.number, + title: p.title, + url: p.url ?? null, + base: p.base ?? null, + author: p.author?.login ?? null, + summary: p.coderhelm?.what?.trim() || null, + next: p.next?.text?.trim() || null, + checks: p.checks ? { passed: p.checks.passed, failed: p.checks.failed, running: p.checks.running, failing: (p.checks.required_failed ?? []).map((name) => ({ name })) } : null, + verdict: p.reviews?.coderhelm_verdict ?? null, + reviewHref: p.coderhelm?.session_id ? `/reviewer/session?id=${encodeURIComponent(p.coderhelm.session_id)}` : null, + approvals: p.reviews ? { have: p.reviews.approvals, need: p.reviews.required } : null, + size: p.size ?? null, + conflict: !!p.conflict, + runId: p.coderhelm?.run_id ?? null, + }; +} + +function fromRun(r: RunDetail, repo: string, number: number): PrView { + const c = r.checks; + const s = r.merge_standing; + const pr = (r.prs ?? []).find((p) => p.repo === repo && p.pr_number === number); + return { + repo, + number, + title: r.title, + url: pr?.url ?? r.pr_url ?? null, + base: null, + author: "CoderHelm", + summary: s?.text?.trim() || null, + next: r.waiting_line?.trim() || s?.next?.trim() || null, + checks: c ? { passed: c.counts.passed, failed: c.counts.failed, running: c.counts.running + c.counts.queued, failing: c.items.filter((i) => i.state === "failed").map((i) => ({ name: i.name, url: i.url })) } : null, + verdict: r.pr_review?.verdict ?? null, + reviewHref: r.pr_review?.review_sk ? `/reviewer/detail?sk=${encodeURIComponent(r.pr_review.review_sk)}` : null, + approvals: s?.approvals ? { have: 0, need: s.approvals } : null, + size: null, + conflict: s?.code === "conflict", + runId: r.run_id, + }; +} + +/** What still stands between the pull request and a merge, in plain words. */ +function blockers(v: PrView): string[] { + const out: string[] = []; + if (v.conflict) out.push("It conflicts with its base branch."); + if (v.checks && v.checks.failed > 0) out.push(v.checks.failed === 1 ? "1 check fails." : `${v.checks.failed} checks fail.`); + if (v.checks && v.checks.running > 0) out.push(v.checks.running === 1 ? "1 check is still running." : `${v.checks.running} checks are still running.`); + if (v.approvals && v.approvals.have < v.approvals.need) { + const n = v.approvals.need - v.approvals.have; + out.push(n === 1 ? "It needs 1 more approval." : `It needs ${n} more approvals.`); + } + if (v.verdict === "REQUEST_CHANGES") out.push("CoderHelm's review asked for changes."); + return out; +} + +const VERDICT: Record = { + APPROVE: { words: "Approved", tone: "text-emerald-300" }, + approve: { words: "Approved", tone: "text-emerald-300" }, + REQUEST_CHANGES: { words: "Changes requested", tone: "text-red-300" }, + request_changes: { words: "Changes requested", tone: "text-red-300" }, + comment: { words: "Commented", tone: "text-zinc-200" }, +}; + +export default function PrDecisionPage() { + return ( + + + + ); +} + +function PrDecision() { + const params = useSearchParams(); + const repo = params.get("repo") ?? ""; + const number = Number(params.get("number") ?? 0); + const runParam = params.get("run"); + const [view, setView] = useState(null); + const [error, setError] = useState(null); + const [mergeOpen, setMergeOpen] = useState(false); + const [fixOpen, setFixOpen] = useState(false); + const [fixing, setFixing] = useState(false); + + const load = useCallback(async () => { + setError(null); + if (!repo || !number) { + setError("This link names no pull request."); + return; + } + try { + const d = await request(`/api/prs/detail?repo=${encodeURIComponent(repo)}&number=${number}`); + setView(fromPrs(d)); + return; + } catch (e) { + const old = e instanceof ApiError && (e.status === 404 || e.status === 405); + if (!old || !runParam) { + setError(e instanceof Error ? e.message : String(e)); + return; + } + } + try { + setView(fromRun(await api.getRun(runParam), repo, number)); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } + }, [repo, number, runParam]); + useEffect(() => { + void load(); + }, [load]); + + const block = view ? blockers(view) : []; + const failing = view?.checks?.failing ?? []; + const canFix = !!view?.runId && (view.checks?.failed ?? 0) > 0 && !fixing; + const where = `${repo} · #${number}`; + + return ( + + {where}} title={view?.title ?? `Pull request #${number || ""}`} crumb={`#${number}`} /> + {error ? ( +
    + void load()} action={Back to the Inbox}> + Nothing was changed. + +
    + ) : !view ? ( +
    + + +
    + ) : ( + // Room at the bottom for the action bar, above the phone's own bar. +
    + +

    {view.summary ?? view.title}

    + {view.next &&

    {view.next}

    } + {view.author &&

    By {view.author}{view.base ? `, into ${view.base}` : ""}

    } +
    + + + {view.checks ? ( + <> +

    + {view.checks.failed ? `${view.checks.failed} failing` : view.checks.running ? `${view.checks.running} running` : "All passing"} + + {" "} + · {view.checks.passed} passed + +

    + {failing.length > 0 && ( + + )} + {canFix && ( + + )} + {fixing &&

    CoderHelm is fixing it.

    } + + ) : ( +

    No checks reported yet.

    + )} +
    + + + {view.verdict ? ( +

    + {VERDICT[view.verdict]?.words ?? view.verdict} + {view.reviewHref && ( + <> + {" · "} + + Read the review + + + )} +

    + ) : ( +

    Not reviewed yet.

    + )} + {view.approvals && view.approvals.need > 0 && ( +

    + {view.approvals.have} of {view.approvals.need} {view.approvals.need === 1 ? "approval" : "approvals"} from people +

    + )} +
    + + + {view.size && ( +

    + {view.size.additions} added, {view.size.deletions} removed +

    + )} + {view.url ? ( + + Read the diff on GitHub + + (opens in a new tab) + + ) : ( +

    The diff is on GitHub.

    + )} +
    + + {/* The decision: at the bottom of the screen on a phone, in the page from md up. */} +
    + {view.url ? ( + + Approve on GitHub (opens in a new tab) + + ) : null} + +
    +
    + )} + + {view && ( + { setMergeOpen(false); setFixOpen(true); } : undefined} + /> + )} + {view?.runId && ( + c.name)} where={where} onStarted={() => setFixing(true)} /> + )} +
    + ); +} + +function Block({ title, testId, children }: { title: string; testId: string; children: React.ReactNode }) { + return ( +
    +

    {title}

    + {children} +
    + ); +} + +/** + * The merge, confirmed: the target branch, how it merges, and what still + * blocks it. A stopped CoderHelm auto-merge is re-armed here (it checks every + * condition again before merging); any other merge is done on GitHub. + */ +function MergeSheet({ open, onOpenChange, view, blocks, onFix }: { open: boolean; onOpenChange: (o: boolean) => void; view: PrView; blocks: string[]; onFix?: () => void }) { + const [gate, setGate] = useState(null); + const [busy, setBusy] = useState(false); + const { toast } = useToast(); + useEffect(() => { + if (!open || !view.runId) return; + let live = true; + api.getGate(view.repo, view.number).then( + (g) => live && setGate(g), + () => live && setGate(null), + ); + return () => { + live = false; + }; + }, [open, view.repo, view.number, view.runId]); + const rearm = !!gate?.can_control && !!gate.gate?.stopped; + const doRearm = async () => { + setBusy(true); + try { + const r = await api.controlGate(view.repo, view.number, "rearm"); + toast(r.message, r.ok ? undefined : "error"); + if (r.ok) { + inboxChanged(); + onOpenChange(false); + } + } catch { + toast("Couldn't re-arm auto-merge. Try again, or merge it on GitHub.", "error"); + } finally { + setBusy(false); + } + }; + const blocked = blocks.length > 0; + return ( + + + {blocked && onFix ? ( + + ) : rearm && !blocked ? ( + + ) : view.url ? ( + onOpenChange(false)}> + Merge on GitHub (opens in a new tab) + + ) : null} + + } + > +
    + {blocked ? ( +
    +

    Not ready to merge:

    +
      + {blocks.map((b) => ( +
    • {b}
    • + ))} +
    +
    + ) : ( +

    + Checks pass and nothing blocks it. +

    + )} +

    + {rearm && !blocked + ? "Its auto-merge was stopped. Re-arming checks every condition again, then CoderHelm merges it." + : "GitHub merges it with this repository's default merge method. Merging can't be undone from here."} +

    +
    +
    + ); +} diff --git a/dashboard/src/components/client-shell.tsx b/dashboard/src/components/client-shell.tsx index 8ead2eb1..d9a1afe8 100644 --- a/dashboard/src/components/client-shell.tsx +++ b/dashboard/src/components/client-shell.tsx @@ -18,8 +18,10 @@ import { Logo, TopBar, TopBarProvider } from "./top-bar"; import { tabTitle as routeTabTitle } from "@/lib/routes"; import { focusRing } from "./ui"; import { helpHref, helpTargetFromUrl } from "@/lib/support"; -import { BookIcon, ChatIcon, GearIcon, LifeBuoyIcon, MapIcon, PlanIcon, PlayIcon, ReviewerIcon, ShieldCheckIcon, ShieldIcon, SlidersIcon, TemplateIcon, TrendingUpIcon } from "./icons"; -import { ADMIN_SECTIONS, NAV_SECTIONS, phoneBar, sectionFor, visiblePages, type NavIconKey, type NavSection } from "@/lib/nav"; +import { BookIcon, ChatIcon, GearIcon, InboxIcon, LifeBuoyIcon, MapIcon, PlanIcon, PlayIcon, ReviewerIcon, ShieldCheckIcon, ShieldIcon, SlidersIcon, TemplateIcon, TrendingUpIcon } from "./icons"; +import { ADMIN_SECTIONS, NAV_SECTIONS, phoneBar, phoneLabel, sectionFor, visiblePages, type NavIconKey, type NavSection } from "@/lib/nav"; +import { inboxCount, INBOX_CHANGED } from "@/lib/inbox"; +import { MenuSearch } from "./menu-search"; import { PhoneBar, type PhoneBarItem } from "./phone-bar"; import { SETTINGS_ITEMS, offered } from "./settings-items"; import { isSelfHosted } from "@/lib/runtime-config"; @@ -80,6 +82,7 @@ function isPlatformAdmin(user: User | null): boolean { } const NAV_ICONS: Record = { + inbox: , runs: , plans: , reviews: , @@ -144,6 +147,27 @@ export function ClientShell({ children }: { children: React.ReactNode }) { useEffect(() => { document.documentElement.setAttribute("data-ch-mounted", ""); }, []); + // A phone opens on the Inbox: the first page of a visit, when it is the + // app's root. The loading screen stays up until it is there, so Runs is + // never drawn first and nothing tapped meanwhile is lost; later taps on + // Runs stay on Runs. + const landingRouter = useRouter(); + const [landing, setLanding] = useState(false); + useEffect(() => { + try { + if (sessionStorage.getItem("ch-landed")) return; + sessionStorage.setItem("ch-landed", "1"); + } catch { + return; + } + if (window.location.pathname === "/" && !window.location.search && window.matchMedia("(max-width: 767px)").matches) { + setLanding(true); + landingRouter.replace("/inbox"); + } + }, [landingRouter]); + useEffect(() => { + if (landing && pathname.startsWith("/inbox")) setLanding(false); + }, [landing, pathname]); // A dismissed banner stays dismissed: by its id, never reset by the month // (a banner that matters again is posted with a new id). useEffect(() => { @@ -220,20 +244,69 @@ export function ClientShell({ children }: { children: React.ReactNode }) { const [menuOpen, setMenuOpen] = useState(false); const menuButtonRef = useRef(null); const drawerRef = useRef(null); + const router = useRouter(); + // The browser's Back closes the sheet, as on any phone screen: opening it + // adds a history entry at the same address (the app router keeps its own + // state in it), and Back takes it off again. Every other way of closing + // (Close, Escape, the backdrop) takes the entry off too, so Back after a + // closed sheet goes to the page before, not to the same page twice. + const menuEntry = useRef(false); + const openMenu = () => { + try { + window.history.pushState({ ...(window.history.state ?? {}), chMenu: true }, ""); + menuEntry.current = true; + } catch { + /* no history: Close and Escape still close it */ + } + setMenuOpen(true); + }; + const closeMenu = () => { + if (menuEntry.current) { + menuEntry.current = false; + window.history.back(); + } + setMenuOpen(false); + }; + useEffect(() => { + const onPop = () => { + menuEntry.current = false; + setMenuOpen(false); + }; + window.addEventListener("popstate", onPop); + return () => window.removeEventListener("popstate", onPop); + }, []); // A link to the page you are already on does not change the path, so close on any link click too. // A native listener: links rendered into the menu through a portal (the chat list) don't - // bubble through this element in React's tree. + // bubble through this element in React's tree. A row opening a page first takes the sheet's + // history entry off, then goes there, so the history holds the page, not the sheet. useEffect(() => { const el = drawerRef.current; if (!el) return; const onClick = (e: MouseEvent) => { - if ((e.target as HTMLElement | null)?.closest("a")) setMenuOpen(false); + const a = (e.target as HTMLElement | null)?.closest("a"); + if (!a) return; + const href = a.getAttribute("href") ?? ""; + const plain = e.button === 0 && !e.metaKey && !e.ctrlKey && !e.shiftKey && !e.altKey && !a.target && href.startsWith("/") && !href.startsWith("//"); + if (plain && menuEntry.current) { + e.preventDefault(); + menuEntry.current = false; + const go = () => { + window.removeEventListener("popstate", go); + window.setTimeout(() => router.push(href), 0); + }; + window.addEventListener("popstate", go); + window.history.back(); + } + setMenuOpen(false); }; el.addEventListener("click", onClick); return () => el.removeEventListener("click", onClick); // Attached when the menu opens: the element exists only once signed in. - }, [menuOpen]); + }, [menuOpen, router]); const menuWasOpen = useRef(false); + const closeRef = useRef(closeMenu); + closeRef.current = closeMenu; + // Close on navigation. useEffect(() => { setMenuOpen(false); }, [pathname]); @@ -258,7 +331,7 @@ export function ClientShell({ children }: { children: React.ReactNode }) { const onKeyDown = (e: KeyboardEvent) => { if (e.key === "Escape") { e.preventDefault(); - setMenuOpen(false); + closeRef.current(); return; } if (e.key !== "Tab") return; @@ -280,7 +353,7 @@ export function ClientShell({ children }: { children: React.ReactNode }) { // The drawer only exists below md. If the window grows, close it. const wide = window.matchMedia("(min-width: 768px)"); - const onWide = () => { if (wide.matches) setMenuOpen(false); }; + const onWide = () => { if (wide.matches) closeRef.current(); }; wide.addEventListener("change", onWide); return () => { @@ -347,7 +420,7 @@ export function ClientShell({ children }: { children: React.ReactNode }) { ); } - if (!authChecked) { + if (!authChecked || landing) { return ( // Styled by the inline BOOT_STYLE, not Tailwind: this markup is in the // static HTML and must look right even when the stylesheet failed. @@ -468,7 +541,8 @@ export function ClientShell({ children }: { children: React.ReactNode }) { teams={teams} pluginsOn={pluginsOn} menuOpen={menuOpen} - setMenuOpen={setMenuOpen} + onOpenMenu={openMenu} + onCloseMenu={closeMenu} drawerRef={drawerRef} menuButtonRef={menuButtonRef} /> @@ -526,7 +600,8 @@ function ShellNav({ teams, pluginsOn, menuOpen, - setMenuOpen, + onOpenMenu, + onCloseMenu, drawerRef, menuButtonRef, }: { @@ -535,7 +610,8 @@ function ShellNav({ teams: TeamInfo[]; pluginsOn: boolean; menuOpen: boolean; - setMenuOpen: (open: boolean) => void; + onOpenMenu: () => void; + onCloseMenu: () => void; drawerRef: React.RefObject; menuButtonRef: React.RefObject; }) { @@ -545,7 +621,7 @@ function ShellNav({ return ( <> {menuOpen && ( -