diff --git a/dashboard/e2e/audit-alerts.spec.ts b/dashboard/e2e/audit-alerts.spec.ts index defb5e31..02293acd 100644 --- a/dashboard/e2e/audit-alerts.spec.ts +++ b/dashboard/e2e/audit-alerts.spec.ts @@ -1,3 +1,4 @@ +import { quietForYou } from "./foryou-data"; import { expect, test, type Page, type Route } from "@playwright/test"; import fs from "node:fs"; import path from "node:path"; @@ -54,6 +55,8 @@ async function mockApi(page: Page, init: Partial = {}): Promise = {}): Promise = {}): Promise = {}): Promise s.kind === "review"); b.suggestion_summary = { count: 1, kinds: [b.suggestion_summary.kinds[1]], top: [], batch: null }; b.stats.waiting_on_you = { count: 4, oldest: b.stats.waiting_on_you.oldest }; @@ -194,6 +194,31 @@ export function stateBody(state: ForYouState): ForYou { b.viewer.github = null b.stats = { waiting_on_you: { count: 0, oldest: null }, waiting_on_others: { count: 0, longest: null }, review_turnaround: null } } + // One repo, a couple of pull requests, Jira not linked, no history. + if (state === "sparse") { + b.needs = { reviews: b.needs.reviews.filter((r) => r.where.startsWith("acme/web")).slice(0, 1), suggested_reviews: [], returned: [], asks: [] }; + b.header = { needs: b.needs.reviews.length, working: 0, waiting: 1 }; + b.sprint = { state: "not_linked", detail: "your Jira account isn't linked to CoderHelm yet", meta: null, tickets: [] }; + b.working = []; + b.waiting = b.waiting.filter((w) => w.where.startsWith("acme/web")).slice(0, 1); + b.later = []; + b.suggestions = []; + b.suggestion_summary = { count: 0, kinds: [], top: [], batch: null }; + b.withdrawn = []; + b.accounts.jira = { state: "not_linked", name: null, suggestion: null }; + b.stats = { waiting_on_you: { count: b.needs.reviews.length, oldest: b.needs.reviews[0] ? { where: b.needs.reviews[0].where, since: b.needs.reviews[0].since ?? ago(60) } : null }, waiting_on_others: { count: b.waiting.length, longest: b.waiting[0] ? { where: b.waiting[0].where, since: b.waiting[0].since ?? ago(60) } : null }, review_turnaround: null }; + } + // A busy week: many of each. + if (state === "big") { + const more = (list: T[], n: number) => + Array.from({ length: n }, (_, i) => list.map((x) => ({ ...x, key: `${x.key}-${i}`, where: i ? x.where.replace(/#(\d+)/, (_m, d) => `#${Number(d) + i * 7}`) : x.where }))).flat(); + b.needs.reviews = more(b.needs.reviews, 4); + b.needs.returned = more(b.needs.returned, 3); + b.waiting = more(b.waiting, 4).map((w) => (w.nudge ? { ...w, nudge: { to: w.nudge.to, sent: null } } : w)); + b.header = { needs: b.needs.reviews.length + b.needs.returned.length + b.needs.asks.length, working: b.working.length, waiting: b.waiting.length }; + b.stats.waiting_on_you.count = b.header.needs; + b.stats.waiting_on_others.count = b.waiting.length; + } if (state === "empty_sprint") b.sprint.tickets = []; if (state === "app_old") b.sprint = { state: "app_old", detail: "Your Jira site runs an older CoderHelm app that can't read a sprint. An admin updates it in Atlassian Administration.", meta: null, tickets: [] }; return b; @@ -208,14 +233,95 @@ export interface Sent { const json = (route: Route, body: unknown, status = 200) => route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); /** The whole API for For you in `state`, recording what the page sends. */ -export async function mockForYou(page: Page, state: ForYouState = "busy", sent: Sent[] = [], opts: { giveStarting?: boolean; decisions?: boolean } = {}) { +/** A "Draft a plan first" run's plan, as the planner wrote it, waiting for Dana's OK. */ +export const PLAN_112 = { + run_id: "run_112p", + ticket: "BOOK-112", + status: "needs_input", + ready: true, + awaiting_ok: { question_id: "q1", approve: "Approve the plan and start coding", change: "Change the plan first (say how)" }, + plan: { + repos: [ + { + repo: "acme/web", + steps: [ + { text: "Show an empty state in `web/src/carts/SavedCartsList.tsx` when there are no carts", done: false, test: false, files: ["web/src/carts/SavedCartsList.tsx"] }, + { text: "Link Browse books to the catalog page", done: false, test: false, files: [] }, + { text: "Add tests for zero carts and one cart in `web/src/carts/__tests__/SavedCartsList.test.tsx`", done: false, test: true, files: ["web/src/carts/__tests__/SavedCartsList.test.tsx"] }, + ], + }, + ], + files: ["web/src/carts/SavedCartsList.tsx", "web/src/carts/__tests__/SavedCartsList.test.tsx"], + tests: ["Add tests for zero carts and one cart in `web/src/carts/__tests__/SavedCartsList.test.tsx`"], + done: 0, + total: 3, + }, +}; + +/** A run at work: two of its four steps done. */ +export const PLAN_097 = { + run_id: "run_097a", + ticket: "BOOK-097", + status: "running", + ready: true, + awaiting_ok: null, + plan: { + repos: [ + { + repo: "acme/web", + steps: [ + { text: "Add the gift-wrap note field to the order", done: true, test: false, files: [] }, + { text: "Show the note in the confirmation email", done: true, test: false, files: [] }, + { text: "Update the confirmation snapshot test", done: false, test: true, files: [] }, + { text: "Note the field in the order API docs", done: false, test: false, files: [] }, + ], + }, + ], + files: [], + tests: ["Update the confirmation snapshot test"], + done: 2, + total: 4, + }, +}; + +export async function mockForYou(page: Page, state: ForYouState = "busy", sent: Sent[] = [], opts: { giveStarting?: boolean; decisions?: boolean; planAsk?: boolean; planWritten?: boolean; linkFlips?: boolean; staleAndAlike?: boolean } = {}) { // Plans and security findings waiting on Dana come from their own // endpoints; empty unless a test asks for them. - await mockInbox(page, state === "old" ? {} : opts.decisions ? {} : { plans: "empty", security: "empty" }); + await mockNeedSources(page, state === "old" ? {} : opts.decisions ? {} : { plans: "empty", security: "empty" }); await page.route((url) => url.hostname === "localhost" && url.pathname === "/api/me", (route) => json(route, { user_id: "u_dana", team_id: "t_acme", github_login: state === "nc" ? null : "dana-ortiz", email: "dana@example.com", name: "Dana Ortiz", avatar_url: "", role: "member", mfa_enabled: false, platform_admin: false, flags: {} }), ); let body = stateBody(state); + if (opts.staleAndAlike) { + // Three copies of one template's plan, one finding idle for 245 days, + // and a row whose text holds code. + const plan = (n: number, mins: number) => ({ + key: `plan:tpl-${n}`, group: "asks" as const, kind: "plan", label: "Plan", where: `acme/web · copy ${n}`, title: "Save the weekly stock report", why: "A plan waits for your OK.", + since: ago(mins), who: null, by_coderhelm: true, action: { label: "Open", href: `/plans/detail?id=tpl-${n}` }, href: `/plans/detail?id=tpl-${n}`, + }); + body.needs.asks.push(plan(1, 90), plan(2, 80), plan(3, 70)); + body.needs.asks.push({ + key: "plan:old-1", group: "asks", kind: "plan", label: "Plan", where: "acme/api", title: "Move the nightly export to the new queue", why: "A plan waits for your OK.", + since: ago(245 * 24 * 60), who: null, by_coderhelm: true, action: { label: "Open", href: "/plans/detail?id=old-1" }, href: "/plans/detail?id=old-1", + }); + body.needs.asks.push({ + key: "run:run_code", group: "asks", kind: "question", label: "Question", where: "BOOK-130 · acme/web", title: "Fix CI after `cd381bd`", why: "CoderHelm asks: reply `@coderhelm fix ci` or pick a fix.", + since: ago(15), who: null, by_coderhelm: true, action: { label: "Answer", href: "/foryou/answer?run=run_code" }, href: "/runs/detail?id=run_code", run_id: "run_code", + }); + } + if (opts.planAsk) { + body.needs.asks.unshift({ + key: "run:run_112p", group: "asks", kind: "plan", label: "Plan", where: "BOOK-112 · acme/web", title: "Add an empty state to the saved carts list", + why: "CoderHelm wrote the plan and waits for your OK before coding.", since: ago(4), who: null, by_coderhelm: true, + action: { label: "Review plan", href: "/foryou/answer?run=run_112p" }, href: "/runs/detail?id=run_112p", run_id: "run_112p", ticket: "BOOK-112", + }); + body.header.needs += 1; + } + await page.route((url) => url.hostname === "localhost" && /^\/api\/runs\/[^/]+\/answer$/.test(url.pathname), (route) => { + const req = route.request(); + sent.push({ method: req.method(), path: new URL(req.url()).pathname, body: req.postData() ?? "" }); + return json(route, { status: "queued", run_id: "run_112q", continued_run_id: "run_112q" }, 202); + }); let given = false; await page.route((url) => url.hostname === "localhost" && url.pathname.startsWith("/api/foryou"), async (route) => { const req = route.request(); @@ -241,6 +347,23 @@ export async function mockForYou(page: Page, state: ForYouState = "busy", sent: } return json(route, body); } + if (p === "/api/foryou/plan") { + const run = new URL(req.url()).searchParams.get("run"); + return json(route, run === "run_112p" ? PLAN_112 : run === "run_097a" ? PLAN_097 : { run_id: run, ticket: null, status: "running", ready: false, awaiting_ok: null, plan: { repos: [], files: [], tests: [], done: 0, total: 0 } }); + } + if (p === "/api/foryou/nudge") { + const b = JSON.parse(req.postData() || "{}"); + const w = body.waiting.find((x) => x.pr?.repo === b.repo && x.pr?.number === b.number); + if (m === "POST" && w?.nudge) { + w.nudge.sent = { to: w.nudge.to ?? "", by: "dana-ortiz", at: Math.floor(Date.now() / 1000), mine: true, comment_url: `https://github.com/${b.repo}/pull/${b.number}#issuecomment-2`, until: Math.floor(Date.now() / 1000) + 86_400 }; + return json(route, { nudged: true, to: w.nudge.to, comment_url: w.nudge.sent.comment_url, until: w.nudge.sent.until, effect: `Reminded @${w.nudge.to} on GitHub. Undo takes the comment back.` }); + } + if (m === "DELETE" && w?.nudge) { + w.nudge.sent = null; + return json(route, { undone: true, effect: "The reminder is taken back." }); + } + return json(route, { error: "There's no nudge to undo." }, 404); + } if (p === "/api/foryou/prefs") { const b = JSON.parse(req.postData() || "{}"); if (b.layout) body.prefs.layout = b.layout; @@ -271,7 +394,9 @@ export async function mockForYou(page: Page, state: ForYouState = "busy", sent: fit: body.sprint.tickets.find((t) => t.key === "BOOK-112")?.fit ?? fitGood([], "UI changes"), repos: ["acme/web"], repo_source: "label", files: ["web/src/carts/SavedCartsList.tsx", "web/src/carts/__tests__/"], criteria: ["The saved carts list says it is empty when there are none", "Browse books links to the catalog page", "Zero carts and one cart are both tested"], - plan: { available: false, text: 'CoderHelm writes its plan first, from the ticket and the code, before any change. With "Pause after the plan" it waits for your OK on the run page before it codes.' }, + plan: opts.planWritten + ? { available: true, run_id: "run_112p", text: "The plan CoderHelm's planner wrote for this ticket, before any code.", view: PLAN_112.plan } + : { available: false, text: 'CoderHelm writes its plan from the ticket and the code before any change. With "Pause after the plan" it plans only, then shows you every step, file and test for your OK before it codes.' }, plan_first_default: false, owner: "you", delegate: "CoderHelm", effect: "The ticket stays assigned to you in Jira. CoderHelm opens one pull request on its own branch, and someone other than you approves it. You can stop it at any time.", }); @@ -282,17 +407,27 @@ export async function mockForYou(page: Page, state: ForYouState = "busy", sent: } if (p === "/api/foryou/link/jira") { if (m === "DELETE") return json(route, { unlinked: true }); - return json(route, { code: "K7QF-2MXA-9RTB-HC4D", expires_at: ahead(0.01), steps: ["Open any issue in Jira.", "Open the issue's ••• menu and choose Link my CoderHelm account.", "Paste this code and choose Link my account."] }); + // Jira sends the code a moment later: the page then reads the link. + if (opts.linkFlips) { + body = JSON.parse(JSON.stringify(body)); + body.accounts.jira = { state: "linked", name: "Dana Ortiz", suggestion: null }; + } + return json(route, { code: "K7QF-2MXA-9RTB-HC4D", expires_at: new Date(Date.now() + 15 * 60_000).toISOString(), steps: ["Open any issue in Jira.", "Open the issue's ••• menu and choose Link my CoderHelm account.", "Paste this code and choose Link my account."] }); } if (p === "/api/foryou/link/jira/not-me") return json(route, { ok: true }); return json(route, { error: "Not mocked" }, 404); }); } -export async function openForYou(page: Page, state: ForYouState = "busy", viewport = { width: 1440, height: 900 }, sent: Sent[] = [], opts: { giveStarting?: boolean; decisions?: boolean } = {}) { +export async function openForYou(page: Page, state: ForYouState = "busy", viewport = { width: 1440, height: 900 }, sent: Sent[] = [], opts: { giveStarting?: boolean; decisions?: boolean; planAsk?: boolean; planWritten?: boolean; linkFlips?: boolean; staleAndAlike?: boolean } = {}) { await mockForYou(page, state, sent, opts); await hideDevOverlay(page); await skipLanding(page); await page.setViewportSize(viewport); await page.goto("/foryou"); } + +/** For you with nothing waiting, for pages whose own mocks only need the menu's count read answered. */ +export function quietForYou(): ForYou { + return stateBody("quiet"); +} diff --git a/dashboard/e2e/foryou-polish.spec.ts b/dashboard/e2e/foryou-polish.spec.ts new file mode 100644 index 00000000..39112d12 --- /dev/null +++ b/dashboard/e2e/foryou-polish.spec.ts @@ -0,0 +1,48 @@ +import { expect, test, type Page } from "@playwright/test"; +import path from "node:path"; +import { openForYou } from "./foryou-data"; + +// For you at every data size (sparse: one repo, a couple of pull requests, +// Jira not linked, no history; medium; big) and width. Each is checked for +// what makes a page look broken: a popover or tooltip open at rest, +// sideways scroll, an empty frame or a row of zeros. Screenshots are saved +// when E2E_SHOTS_DIR is set (foryou-polish--.png). + +const DIR = process.env.E2E_SHOTS_DIR; +const WIDTHS = [1440, 1280, 1024, 375]; +const SIZES = [ + ["sparse", "sparse"], + ["medium", "busy"], + ["big", "big"], +] as const; + +async function atRest(page: Page) { + const open = await page.locator('[role=tooltip], [data-radix-popper-content-wrapper], [role=dialog], [role=menu]').evaluateAll((els) => + els.filter((e) => { + const r = e.getBoundingClientRect(); + const s = getComputedStyle(e); + return r.width > 0 && r.height > 0 && s.visibility !== "hidden" && s.display !== "none" && Number(s.opacity) > 0; + }).length, + ); + expect(open, "nothing pops up at rest").toBe(0); + const sideways = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + expect(sideways, "no sideways scroll").toBe(0); + // Never a row of zero tiles: a number shown on the rail is a real count. + const zeros = await page.getByTestId("fy-stats").locator("dd").evaluateAll((els) => els.filter((e) => /^\s*0\s*$/.test(e.textContent ?? "")).length); + expect(zeros, "no zero tiles on the rail").toBe(0); +} + +test.describe.configure({ mode: "parallel" }); + +for (const [size, state] of SIZES) { + for (const width of WIDTHS) { + test(`For you, ${size}, ${width} wide: designed, nothing open at rest`, async ({ page }) => { + await openForYou(page, state, { width, height: 900 }); + await expect(page.getByTestId("fy-status")).toBeVisible(); + await page.mouse.move(0, 0); + await page.waitForTimeout(250); + await atRest(page); + if (DIR) await page.screenshot({ path: path.join(DIR, `foryou-polish-${size}-${width}.png`), fullPage: true }); + }); + } +} diff --git a/dashboard/e2e/foryou-polish2.spec.ts b/dashboard/e2e/foryou-polish2.spec.ts new file mode 100644 index 00000000..45d196a3 --- /dev/null +++ b/dashboard/e2e/foryou-polish2.spec.ts @@ -0,0 +1,113 @@ +import { expect, test, type Page } from "@playwright/test"; +import path from "node:path"; +import { openForYou, type Sent } from "./foryou-data"; + +// For you's type and content, round two: one small label style for group +// headers, one primary button (the top row), code shown as code, old rows +// folded away, copies of one thing under one row, the accounts card with one +// plain status per account, the Jira link sheet, and an older backend that +// offers no button it can't serve. Screenshots: foryou-polish2-*.png when +// E2E_SHOTS_DIR is set. + +const DIR = process.env.E2E_SHOTS_DIR; +const DESKTOP = { width: 1440, height: 900 }; + +async function shot(page: Page, name: string, full = true) { + if (DIR) await page.screenshot({ path: path.join(DIR, `foryou-polish2-${name}.png`), fullPage: full }); +} + +test.describe.configure({ mode: "parallel" }); + +test("one primary button, on the top row only; group headers in one small label style", async ({ page }) => { + await openForYou(page); + await expect(page.getByTestId("fy-need").first()).toBeVisible(); + const primaries = await page.locator("[data-testid=fy-need-action]").evaluateAll((els) => els.filter((e) => e.className.includes("bg-inverse")).length); + expect(primaries).toBe(1); + const head = page.getByTestId("fy-needs").getByText("Reviews requested of you", { exact: true }); + const style = await head.evaluate((e) => { + const s = getComputedStyle(e.parentElement as HTMLElement); + return { size: s.fontSize, transform: s.textTransform, weight: s.fontWeight }; + }); + expect(style).toEqual({ size: "15px", transform: "none", weight: "600" }); + const title = page.getByTestId("fy-need").first().locator("div.text-sm.font-medium").first(); + expect(await title.evaluate((e) => getComputedStyle(e).fontSize)).toBe("15px"); +}); + +test("old rows fold into one group with Dismiss all; copies sit under one row; code shows as code", async ({ page }) => { + const sent: Sent[] = []; + await openForYou(page, "busy", DESKTOP, sent, { staleAndAlike: true }); + const stale = page.getByTestId("fy-stale"); + await expect(stale).toContainText("Old, probably abandoned"); + await expect(stale).not.toHaveAttribute("open", ""); + const alike = page.getByTestId("fy-need").filter({ hasText: "Save the weekly stock report" }); + await expect(alike).toHaveCount(1); + await expect(alike.getByTestId("fy-alike")).toContainText("2 more like it"); + const coded = page.getByTestId("fy-need").filter({ hasText: "Fix CI after" }); + await expect(coded.locator("code").first()).toHaveText("cd381bd"); + await expect(coded).not.toContainText("`"); + await shot(page, "stale-alike-1440"); + await stale.locator("summary").click(); + await stale.getByTestId("fy-stale-dismiss").click(); + await expect(page.getByText("1 old item dismissed.")).toBeVisible(); + expect(sent.filter((s) => s.path === "/api/foryou/items").map((s) => JSON.parse(s.body).key)).toEqual(["plan:old-1"]); +}); + +test("the accounts card: one plain status per account, never a badge beside a contradicting word", async ({ page }) => { + for (const [state, gh, jira, name] of [ + ["busy", "Linked as @dana-ortiz", "Linked as Dana Ortiz", "accounts-linked"], + ["nc", "Not linked", "Not linked", "accounts-not-linked"], + ["partial", "Linked as @dana-ortiz", "Not linked", "accounts-mixed"], + ] as const) { + await openForYou(page, state, DESKTOP); + const card = page.getByTestId("fy-accounts"); + await expect(page.getByTestId("fy-acct-github-status")).toHaveText(gh); + await expect(page.getByTestId("fy-acct-jira-status")).toHaveText(jira); + await expect(card).not.toContainText(/\bOn\b/); + await expect(card.locator(".bg-inverse")).toHaveCount(0); + for (const id of ["fy-acct-github-status", "fy-acct-jira-status"]) { + const h = await page.getByTestId(id).evaluate((e) => e.getBoundingClientRect().height); + expect(h, `${id} on one line`).toBeLessThan(20); + } + if (DIR) await card.screenshot({ path: path.join(DIR, `foryou-polish2-${name}.png`) }); + } +}); + +test("Link Jira: three steps, the code with Copy, and Waiting for Jira turns into Linked as", async ({ page, context }) => { + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await openForYou(page, "partial", DESKTOP, [], { linkFlips: true }); + await page.getByTestId("fy-connect-jira-rail").click(); + const sheet = page.getByTestId("fy-link-code"); + await expect(sheet).toContainText("Open any Jira issue."); + await expect(sheet).toContainText("Link my CoderHelm account"); + await expect(sheet.getByTestId("fy-link-wait")).toHaveText("Waiting for Jira…"); + await sheet.getByTestId("fy-code-copy").click(); + await expect(sheet.getByTestId("fy-code-copy")).toHaveText("Copied"); + await shot(page, "link-sheet", false); + await expect(sheet.getByTestId("fy-link-wait")).toHaveText("Linked as Dana Ortiz", { timeout: 15_000 }); +}); + +test("an older backend offers no Jira button and never raises a 404 toast", async ({ page }) => { + await openForYou(page, "old", DESKTOP); + await expect(page.getByTestId("fy-fallback")).toBeVisible(); + await expect(page.getByTestId("fy-acct-jira-status")).toHaveText("Arrives with the next update"); + await expect(page.getByTestId("fy-connect-jira-rail")).toHaveCount(0); + await expect(page.getByTestId("fy-connect-jira")).toHaveCount(0); + await expect(page.getByText(/error 404|Not found/i)).toHaveCount(0); +}); + +for (const [size, state] of [ + ["fallback", "old"], + ["busy", "busy"], + ["sparse", "sparse"], +] as const) { + for (const width of [1440, 1280, 1024, 375]) { + test(`shots: ${size} at ${width}`, async ({ page }) => { + test.skip(!DIR, "E2E_SHOTS_DIR is not set"); + await openForYou(page, state, { width, height: 900 }); + await expect(page.getByTestId("fy-status")).toBeVisible(); + await page.mouse.move(0, 0); + await page.waitForTimeout(250); + await shot(page, `${size}-${width}`); + }); + } +} diff --git a/dashboard/e2e/foryou-real.spec.ts b/dashboard/e2e/foryou-real.spec.ts new file mode 100644 index 00000000..c2366a5a --- /dev/null +++ b/dashboard/e2e/foryou-real.spec.ts @@ -0,0 +1,112 @@ +import { expect, test, type Page } from "@playwright/test"; +import AxeBuilder from "@axe-core/playwright"; +import { mockForYou, openForYou, type Sent } from "./foryou-data"; +import { hideDevOverlay } from "./needs-data"; + +// For you's real plan, step checklist, nudge and desktop count, with the +// same invented team (acme/*, Dana Ortiz, @mara, @theo, @jun, BOOK tickets). + +const DESKTOP = { width: 1440, height: 900 }; +const PHONE = { width: 375, height: 760 }; + +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([]); +} + +const sideways = (page: Page) => page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + +test.describe.configure({ mode: "parallel" }); + +test("a plan waiting for your OK opens as written: steps, repositories, files and tests; Approve answers the run", async ({ page }) => { + const sent: Sent[] = []; + await openForYou(page, "busy", DESKTOP, sent, { planAsk: true }); + const row = page.getByTestId("fy-need").filter({ hasText: "Add an empty state to the saved carts list" }); + await expect(row).toContainText("CoderHelm wrote the plan and waits for your OK before coding."); + await row.getByTestId("fy-need-action").click(); + const sheet = page.getByTestId("fy-plan-sheet"); + await expect(sheet).toContainText("The plan, for your OK"); + await expect(sheet.getByTestId("fy-plan-step")).toHaveCount(3); + await expect(sheet.getByTestId("fy-plan-repos")).toHaveText("acme/web"); + await expect(sheet.getByTestId("fy-plan-files")).toContainText("web/src/carts/__tests__/SavedCartsList.test.tsx"); + await expect(sheet.getByTestId("fy-plan-tests")).toContainText("Add tests for zero carts and one cart"); + await axe(page, "plan sheet"); + await sheet.getByTestId("fy-plan-approve").click(); + await expect(page.getByText("Approved. CoderHelm codes from this plan now.")).toBeVisible(); + const answer = sent.find((s) => s.path === "/api/runs/run_112p/answer"); + expect(JSON.parse(answer?.body ?? "{}")).toEqual({ answers: [{ question_id: "q1", answer: "Approve the plan and start coding" }] }); +}); + +test("changing the plan sends the words and asks for another OK", async ({ page }) => { + const sent: Sent[] = []; + await openForYou(page, "busy", DESKTOP, sent, { planAsk: true }); + await page.getByTestId("fy-need").filter({ hasText: "Add an empty state" }).getByTestId("fy-need-action").click(); + const sheet = page.getByTestId("fy-plan-sheet"); + await sheet.getByTestId("fy-plan-change").click(); + await expect(sheet.getByTestId("fy-plan-send-change")).toBeDisabled(); + await sheet.getByTestId("fy-plan-change-words").fill("Keep the old empty text for the mobile app"); + await sheet.getByTestId("fy-plan-send-change").click(); + await expect(page.getByText("Sent. CoderHelm plans again and asks for your OK again.")).toBeVisible(); + const answer = sent.find((s) => s.path === "/api/runs/run_112p/answer"); + expect(JSON.parse(answer?.body ?? "{}").answers[0].answer).toBe("Change the plan first (say how): Keep the old empty text for the mobile app"); +}); + +test("a run at work shows its plan's real steps, ticked as it goes", async ({ page }) => { + await openForYou(page); + const work = page.getByTestId("fy-work").filter({ hasText: "Add a gift-wrap note" }); + await work.getByTestId("fy-steps-toggle").click(); + await expect(work.getByTestId("fy-steps-count")).toHaveText("2 of 4 steps done"); + await expect(work.getByTestId("fy-plan-step")).toHaveCount(4); + await expect(work.locator("[data-testid=fy-plan-step][data-done]")).toHaveCount(2); + await axe(page, "steps open"); +}); + +test("Give shows the plan the ticket's run already wrote", async ({ page }) => { + await openForYou(page, "busy", DESKTOP, [], { planWritten: true }); + await page.getByTestId("fy-ticket").filter({ hasText: "BOOK-112" }).getByTestId("fy-sug-accept").click(); + const sheet = page.getByTestId("fy-give-sheet"); + await expect(sheet.getByTestId("fy-give-plan").getByTestId("fy-plan-step")).toHaveCount(3); + await expect(sheet.getByTestId("fy-give-plan")).toContainText("Tests: Add tests for zero carts"); +}); + +test("Nudge reminds the one person on GitHub, says it was sent, and can be undone", async ({ page }) => { + const sent: Sent[] = []; + await openForYou(page, "busy", DESKTOP, sent); + const row = page.getByTestId("fy-waiting").filter({ hasText: "Paginate the orders export" }); + await row.getByTestId("fy-nudge").click(); + await expect(page.getByText("Reminded @mara on GitHub. Undo takes the comment back.")).toBeVisible(); + expect(sent.filter((s) => s.path === "/api/foryou/nudge" && s.method === "POST").map((s) => JSON.parse(s.body))).toEqual([{ repo: "acme/api", number: 477 }]); + await expect(row.getByTestId("fy-nudged")).toContainText("You nudged @mara just now"); + await row.getByTestId("fy-unnudge").click(); + await expect(page.getByText("The reminder is taken back.")).toBeVisible(); + expect(sent.filter((s) => s.path === "/api/foryou/nudge" && s.method === "DELETE").map((s) => JSON.parse(s.body))).toEqual([{ repo: "acme/api", number: 477 }]); + await expect(row.getByTestId("fy-nudge")).toBeVisible(); +}); + +test("a nudge sent today shows instead of the button, at most one a day", async ({ page }) => { + await openForYou(page); + const row = page.getByTestId("fy-waiting").filter({ hasText: "Show proration when a plan changes" }); + await expect(row.getByTestId("fy-nudged")).toContainText(/You nudged @theo \d+ min ago · one a day/); + await expect(row.getByTestId("fy-nudge")).toHaveCount(0); + await axe(page, "nudged row"); +}); + +test("on a phone the plan sheet and nudges fit without sideways scroll", async ({ page }) => { + await openForYou(page, "busy", PHONE, [], { planAsk: true }); + await expect(page.getByTestId("fy-waiting").first()).toBeVisible(); + expect(await sideways(page)).toBe(0); + await page.getByTestId("fy-need").filter({ hasText: "Add an empty state" }).getByTestId("fy-need-action").click(); + await expect(page.getByTestId("fy-plan-sheet").getByTestId("fy-plan-step")).toHaveCount(3); + expect(await sideways(page)).toBe(0); +}); + +test("a wide screen shows the For you count with the menu, before For you is opened", async ({ page }) => { + await mockForYou(page); + await hideDevOverlay(page); + await page.setViewportSize(DESKTOP); + await page.goto("/plans/"); + const link = page.getByTestId("main-nav").first().getByRole("link").first(); + await expect(link).toHaveText(/^For you/); + await expect(link.getByTestId("count-badge")).toContainText("6"); +}); diff --git a/dashboard/e2e/foryou-shots.spec.ts b/dashboard/e2e/foryou-shots.spec.ts index 210ccc16..147e65e8 100644 --- a/dashboard/e2e/foryou-shots.spec.ts +++ b/dashboard/e2e/foryou-shots.spec.ts @@ -56,6 +56,23 @@ test("desktop screenshots: For you and its states", async ({ page }) => { await expect(page.getByTestId("fy-customize")).toBeVisible(); await shot(page, "desktop-customize"); + // The plan a "Draft a plan first" run waits on, as written. + await openForYou(page, "busy", DESKTOP, [], { planAsk: true }); + await page.getByTestId("fy-need").filter({ hasText: "Add an empty state" }).getByTestId("fy-need-action").click(); + await expect(page.getByTestId("fy-plan-step")).toHaveCount(3); + await shot(page, "desktop-plan-sheet"); + await page.keyboard.press("Escape"); + + // A run's steps, and a nudge sent. + await openForYou(page, "busy", DESKTOP); + const work = page.getByTestId("fy-work").filter({ hasText: "Add a gift-wrap note" }); + await work.getByTestId("fy-steps-toggle").click(); + await expect(work.getByTestId("fy-steps-count")).toBeVisible(); + await work.scrollIntoViewIfNeeded(); + await shot(page, "desktop-steps"); + await page.getByTestId("fy-waiting").first().scrollIntoViewIfNeeded(); + await shot(page, "desktop-waiting-nudge"); + for (const st of ["quiet", "partial", "nc"] as const) { await openForYou(page, st, DESKTOP); await expect(page.getByTestId("fy-status")).toBeVisible(); diff --git a/dashboard/e2e/foryou.spec.ts b/dashboard/e2e/foryou.spec.ts index f3428ad7..b3215eb7 100644 --- a/dashboard/e2e/foryou.spec.ts +++ b/dashboard/e2e/foryou.spec.ts @@ -35,9 +35,9 @@ test("needs you now is grouped by whose turn it is, with the counts and the stat const review = page.getByTestId("fy-need").first(); await expect(review).toContainText("@theo asked for your review. The repo needs 1 approval."); await expect(review).toContainText("waiting 1d 4h"); - await expect(review.getByTestId("fy-need-action")).toHaveAttribute("href", /^\/inbox\/pr\/?\?repo=acme%2Fweb\&number=482$/); + await expect(review.getByTestId("fy-need-action")).toHaveAttribute("href", /^\/foryou\/pr\/?\?repo=acme%2Fweb\&number=482$/); await expect(page.getByTestId("fy-need").filter({ hasText: "Checks failing" }).getByTestId("fy-need-action")).toHaveText("Open checks"); - await expect(page.getByTestId("fy-need").filter({ hasText: "Question" }).getByTestId("fy-need-action")).toHaveAttribute("href", /^\/inbox\/answer\/?\?run=run_101a$/); + await expect(page.getByTestId("fy-need").filter({ hasText: "Question" }).getByTestId("fy-need-action")).toHaveAttribute("href", /^\/foryou\/answer\/?\?run=run_101a$/); // The private rail: three numbers, and nothing that ranks or counts output. const stats = page.getByTestId("fy-stats"); await expect(stats.getByTestId("fy-stat-you")).toContainText("6"); @@ -48,7 +48,7 @@ test("needs you now is grouped by whose turn it is, with the counts and the stat await expect(stats).toContainText("No streaks, commit counts, lines of code or rankings."); // Waiting on others, CoderHelm's work, Later collapsed. await expect(page.getByTestId("fy-waiting")).toHaveCount(3); - await expect(page.getByTestId("fy-waiting").first()).toContainText("Next:M@mara· review requested"); + await expect(page.getByTestId("fy-waiting").first()).toContainText("Next: @mara, review requested"); await expect(page.getByTestId("fy-work")).toHaveCount(2); await expect(page.getByTestId("fy-work").first()).toContainText("you stay the owner, CoderHelm is the delegate"); await expect(page.getByTestId("fy-later-item")).toHaveCount(0); @@ -87,7 +87,7 @@ test("Give to CoderHelm: a preview first, then the run starts with you as the ow await page.getByTestId("fy-ticket").filter({ hasText: "BOOK-112" }).getByTestId("fy-sug-accept").click(); const sheet = page.getByTestId("fy-give-sheet"); await expect(sheet).toContainText("BOOK-112 · Add an empty state to the saved carts list"); - await expect(sheet.getByTestId("fy-plan-text")).toContainText("CoderHelm writes its plan first"); + await expect(sheet.getByTestId("fy-plan-text")).toContainText("CoderHelm writes its plan from the ticket and the code before any change"); await expect(sheet).toContainText("acme/web"); await expect(sheet).toContainText("You stay the owner. CoderHelm is the delegate."); await expect(sheet.getByTestId("fy-plan-first-check")).not.toBeChecked(); @@ -311,13 +311,15 @@ test("GitHub on, Jira not: link Jira by a code, never by email; Is this you? onl const link = page.getByTestId("fy-link-jira"); await expect(link).toContainText("It never links you by matching emails"); await expect(link.getByTestId("fy-is-this-you")).toContainText("Is this you? Dana Ortiz (Jira)"); - await expect(page.getByTestId("fy-accounts")).toContainText("Jira · not linked"); + await expect(link.getByTestId("fy-seen-on")).toHaveText("Seen on BOOK-112, BOOK-115"); + await expect(page.getByTestId("fy-acct-jira-status")).toHaveText("Not linked"); await axe(page, "partial"); await link.getByTestId("fy-yes-me").click(); const code = page.getByTestId("fy-link-code"); await expect(code.getByTestId("fy-code")).toHaveText("K7QF-2MXA-9RTB-HC4D"); await expect(code).toContainText("Link my CoderHelm account"); - await expect(code).toContainText("works once, for 15 minutes"); + await expect(code).toContainText(/it works once, for 1[45] min/); + await expect(code).toContainText("Your admin’s Jira connection, and what CoderHelm can read, don’t change."); expect(sent.filter((s) => s.path === "/api/foryou/link/jira" && s.method === "POST")).toHaveLength(1); await page.keyboard.press("Escape"); await link.getByTestId("fy-not-me").click(); @@ -353,7 +355,7 @@ test("loading, error and an older backend", async ({ page }) => { // An older backend: the Inbox's rows stand in as what needs you. await openForYou(page, "old"); - await expect(page.getByTestId("fy-fallback")).toContainText("This CoderHelm serves an older version"); + await expect(page.getByTestId("fy-fallback")).toContainText("This CoderHelm is an older version"); await expect(page.getByTestId("fy-need").first()).toBeVisible(); await expect(page.getByTestId("fy-sprint-problem")).toContainText("This CoderHelm doesn't serve your sprint yet."); }); diff --git a/dashboard/e2e/inbox-redirects.spec.ts b/dashboard/e2e/inbox-redirects.spec.ts new file mode 100644 index 00000000..f4474f00 --- /dev/null +++ b/dashboard/e2e/inbox-redirects.spec.ts @@ -0,0 +1,41 @@ +import { expect, test } from "@playwright/test"; +import { mockForYou } from "./foryou-data"; +import { hideDevOverlay } from "./needs-data"; + +// The Inbox is retired: For you holds what needs you. Every old /inbox +// address still lands somewhere real, with its query kept where the page +// moved, so old links and bookmarks keep working. + +test.describe.configure({ mode: "parallel" }); + +const CASES: [string, RegExp][] = [ + ["/inbox", /\/foryou\/?$/], + ["/inbox/", /\/foryou\/?$/], + ["/inbox/answer?run=run_101a", /\/foryou\/answer\/?\?run=run_101a$/], + ["/inbox/pr?repo=acme%2Fweb&number=482", /\/foryou\/pr\/?\?repo=acme%2Fweb&number=482$/], + ["/inbox/settings", /\/foryou\/?$/], + ["/inbox/some/old/page", /\/foryou\/?$/], +]; + +for (const [from, to] of CASES) { + test(`${from} redirects to For you`, async ({ page }) => { + await mockForYou(page); + await hideDevOverlay(page); + await page.goto(from); + await expect(page).toHaveURL(to); + }); +} + +test("the menu has no Inbox, and the phone bar is For you, Runs, PRs, Chat, Menu", async ({ page }) => { + await mockForYou(page); + await hideDevOverlay(page); + await page.setViewportSize({ width: 1440, height: 900 }); + await page.goto("/foryou"); + const nav = page.getByTestId("main-nav").first(); + await expect(nav.getByRole("link", { name: /^Inbox/ })).toHaveCount(0); + await page.setViewportSize({ width: 375, height: 760 }); + const bar = page.getByTestId("phone-bar"); + await expect(bar).toBeVisible(); + const labels = (await bar.locator("a, button").allInnerTexts()).map((t) => t.replace(/\d+/g, "").trim()).filter(Boolean); + expect(labels).toEqual(["For you", "Runs", "PRs", "Chat", "Menu"]); +}); diff --git a/dashboard/e2e/inbox-data.ts b/dashboard/e2e/needs-data.ts similarity index 96% rename from dashboard/e2e/inbox-data.ts rename to dashboard/e2e/needs-data.ts index 4c6c9467..58f03d22 100644 --- a/dashboard/e2e/inbox-data.ts +++ b/dashboard/e2e/needs-data.ts @@ -2,7 +2,7 @@ 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, +// `mockNeedSources(page, opts)` answers the whole API; what isn't here answers 404, // as an older backend would. const now = Date.now(); @@ -162,14 +162,14 @@ export const FINDING = { updated_at: ago(100), }; -export interface InboxMock { +export interface NeedSourcesMock { /** 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. */ + /** Hold every read of these sources this long, to see the loading state. */ delayMs?: number; /** Requests the page sent, for the checks. */ sent?: { method: string; path: string; body: string }[]; @@ -179,8 +179,8 @@ export interface InboxMock { 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; +export async function mockNeedSources(page: Page, opts: NeedSourcesMock = {}) { + const o = { runs: "ok", approvals: "ok", plans: "ok", prs: "ok", security: "ok", ...opts } as Required> & NeedSourcesMock; 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(); diff --git a/dashboard/e2e/phone-inbox-shots.spec.ts b/dashboard/e2e/phone-foryou-shots.spec.ts similarity index 82% rename from dashboard/e2e/phone-inbox-shots.spec.ts rename to dashboard/e2e/phone-foryou-shots.spec.ts index 933e5bb5..574056f7 100644 --- a/dashboard/e2e/phone-inbox-shots.spec.ts +++ b/dashboard/e2e/phone-foryou-shots.spec.ts @@ -1,11 +1,11 @@ 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"; +import { hideDevOverlay, mockNeedSources, skipLanding } from "./needs-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. +// E2E_SHOTS_DIR is set; the checks are in phone-foryou.spec.ts. const DIR = process.env.E2E_SHOTS_DIR; const PREFIX = process.env.E2E_SHOTS_PREFIX ?? "phone2-"; @@ -21,22 +21,22 @@ 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 mockNeedSources(page); await hideDevOverlay(page); await skipLanding(page); // An older backend: For you lists the Inbox's decisions. await page.goto("/foryou"); await expect(page.getByTestId("fy-need")).toHaveCount(8); - await shot(page, "inbox"); + await shot(page, "foryou"); - await page.goto("/inbox/answer?run=run_q1"); + await page.goto("/foryou/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 page.goto("/foryou/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(); @@ -55,8 +55,8 @@ test("phone screenshots: the Inbox, its states and its flows", async ({ page }) await page.keyboard.press("Escape"); await page.unrouteAll({ behavior: "ignoreErrors" }); - await mockInbox(page, { runs: "empty", approvals: "empty", plans: "empty", prs: "empty", security: "empty" }); + await mockNeedSources(page, { runs: "empty", approvals: "empty", plans: "empty", prs: "empty", security: "empty" }); await page.goto("/foryou"); await expect(page.getByTestId("fy-quiet")).toBeVisible(); - await shot(page, "inbox-empty"); + await shot(page, "foryou-empty"); }); diff --git a/dashboard/e2e/phone-inbox.spec.ts b/dashboard/e2e/phone-foryou.spec.ts similarity index 92% rename from dashboard/e2e/phone-inbox.spec.ts rename to dashboard/e2e/phone-foryou.spec.ts index d420be45..482de63d 100644 --- a/dashboard/e2e/phone-inbox.spec.ts +++ b/dashboard/e2e/phone-foryou.spec.ts @@ -1,7 +1,7 @@ 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"; +import { hideDevOverlay, mockNeedSources, skipLanding, type NeedSourcesMock } from "./needs-data"; // The phone's For you (the Inbox folded into it) and the flows it opens, with an invented team (the // bookstore's acme/* repos, octocat): every kind of row and its order, the @@ -14,8 +14,8 @@ 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); +async function open(page: Page, path: string, mock: NeedSourcesMock = {}, opts: { landed?: boolean } = { landed: true }) { + await mockNeedSources(page, mock); await hideDevOverlay(page); if (opts.landed) await skipLanding(page); await page.setViewportSize(PHONE); @@ -58,15 +58,15 @@ test("phone: on an older backend For you lists the Inbox's decisions, what block await open(page, "/foryou"); await expect(page.getByTestId("fy-fallback")).toBeVisible(); await expect(page.getByTestId("fy-need")).toHaveCount(8); - await expect(page.getByTestId("fy-need").filter({ hasText: "Should a gift card pay for shipping too" }).getByTestId("fy-need-action")).toHaveAttribute("href", /^\/inbox\/answer\/?\?run=run_q1$/); + await expect(page.getByTestId("fy-need").filter({ hasText: "Should a gift card pay for shipping too" }).getByTestId("fy-need-action")).toHaveAttribute("href", /^\/foryou\/answer\/?\?run=run_q1$/); expect(await sideways(page)).toBeLessThanOrEqual(0); }); test("phone: answer CoderHelm's question on one screen", async ({ page }) => { - const sent: InboxMock["sent"] = []; + const sent: NeedSourcesMock["sent"] = []; await open(page, "/foryou", { sent }); await page.getByTestId("fy-need").filter({ hasText: "Should a gift card pay for shipping too" }).getByTestId("fy-need-action").click(); - await expect(page).toHaveURL(/\/inbox\/answer\/?\?run=run_q1$/); + await expect(page).toHaveURL(/\/foryou\/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(); @@ -86,7 +86,7 @@ test("phone: answer CoderHelm's question on one screen", async ({ page }) => { 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, "/foryou"); await page.getByTestId("fy-need").filter({ hasText: "Fix the flaky retry" }).getByTestId("fy-need-action").click(); - await expect(page).toHaveURL(/\/inbox\/pr\/?\?repo=acme%2Fweb&number=812/); + await expect(page).toHaveURL(/\/foryou\/pr\/?\?repo=acme%2Fweb&number=812/); // The summary, the checks and the verdict come before the diff. await expect(page.getByTestId("pr-summary")).toBeVisible(); const order = await page.locator("[data-testid^=pr-]").evaluateAll((els) => els.map((e) => e.getAttribute("data-testid"))); @@ -115,8 +115,8 @@ test("phone: approve or merge leads with what it does, its checks and the verdic }); 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 }); + const sent: NeedSourcesMock["sent"] = []; + await open(page, "/foryou/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(); @@ -125,8 +125,8 @@ test("phone: a stopped CoderHelm auto-merge is re-armed from the merge sheet", a }); test("phone: a failing check goes to CoderHelm in one tap from the merge sheet", async ({ page }) => { - const sent: InboxMock["sent"] = []; - await open(page, "/inbox/pr?repo=acme%2Fapi&number=815&run=run_f1", { sent }); + const sent: NeedSourcesMock["sent"] = []; + await open(page, "/foryou/pr?repo=acme%2Fapi&number=815&run=run_f1", { sent }); // From the pull request: Merge says what blocks it and offers the hand-off. await expect(page.getByTestId("pr-checks")).toContainText("1 failing"); await page.getByTestId("pr-actions").getByRole("button", { name: "Merge" }).click(); @@ -139,7 +139,7 @@ test("phone: a failing check goes to CoderHelm in one tap from the merge sheet", }); 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 open(page, "/foryou/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"); @@ -194,7 +194,7 @@ test("phone: the Menu sheet searches every page, closes on Back and has no count await expect(page).toHaveURL(/\/foryou\/?$/); }); -for (const path of ["/foryou", "/inbox/answer?run=run_q1", "/inbox/pr?repo=acme%2Fapi&number=815&run=run_f1"]) { +for (const path of ["/foryou", "/foryou/answer?run=run_q1", "/foryou/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]) { @@ -214,7 +214,7 @@ test("phone: the Menu sheet and the merge sheet pass axe WCAG 2.2 AA", async ({ 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.goto("/foryou/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/prs-scope.spec.ts b/dashboard/e2e/prs-scope.spec.ts new file mode 100644 index 00000000..766b9d38 --- /dev/null +++ b/dashboard/e2e/prs-scope.spec.ts @@ -0,0 +1,345 @@ +import AxeBuilder from "@axe-core/playwright"; +import { expect, test, type Page, type Route } from "@playwright/test"; +import fs from "node:fs"; +import path from "node:path"; +import type { PrRow, PrsOverview, PrsPage } from "../src/lib/api"; +import { many, page as prsPage, ROWS } from "./prs-data"; +import { overview } from "./prs-overview-data"; + +// The Pull requests scope on both tabs (List /prs and Overview /prs/overview): +// one repo picker, "All repos" first, then every repo the installation can +// see (from /api/repos, not from the pull requests read so far); old +// `?org=` links; the menu anchored to its trigger; the older-backend and +// being-set-up states; and the List tab at three data sizes and four widths +// with nothing floating at rest and no sideways scroll. Every API call is +// answered here. + +const ONE_OWNER = ["acme/web", "acme/api", "acme/checkout"]; +const TWO_OWNERS = ["acme/web", "acme/api", "acme/checkout", "acme-labs/search", "acme-labs/recs"]; + +interface Backend { + calls: string[]; + repos: string[]; + list: (url: URL) => PrsPage | number; + overview: (url: URL) => PrsOverview | number; +} + +async function mockApi(page: Page, init: Partial = {}): Promise { + const db: Backend = { calls: [], repos: ONE_OWNER, list: () => prsPage(), overview: (u) => overview("normal", u.searchParams.get("repo") ?? undefined), ...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: db.repos.map((name) => ({ name, enabled: true, ticket_source: "github" })) }); + if (p === "/api/prs") { + const a = db.list(url); + return typeof a === "number" ? json(route, { error: "nope" }, a) : json(route, a); + } + if (p === "/api/prs/overview") { + const a = db.overview(url); + return typeof a === "number" ? json(route, { error: "nope" }, a) : json(route, a); + } + return json(route, { error: `Not mocked: ${req.method()} ${p}` }, 404); + }); + return db; +} + +const calls = (db: Backend, path: string) => db.calls.filter((c) => c.startsWith(`GET ${path}?`) || c === `GET ${path}`); + +/** No pull request read anywhere yet, but synced and done: the plain empty list. */ +const nothing = () => prsPage([], { counts: { turn: {}, state: {}, repo: {}, org: {}, views: {} } }); + +const SHOTS = process.env.E2E_SHOTS_DIR; +async function shot(page: Page, name: string, fullPage = false) { + 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 }); +} + +async function axe(page: Page) { + const r = await new AxeBuilder({ page }).include("main").withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"]).analyze(); + expect(r.violations.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).join(", ")}`)).toEqual([]); +} + +const sideways = (page: Page) => page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + +/** Every repo the picker offers, by its full name (the option's title). */ +async function offered(page: Page): Promise { + return page.getByTestId("combo-option").evaluateAll((els) => els.map((el) => el.getAttribute("data-option") ?? "")); +} + +test.describe("the repo picker", () => { + test("lists the installed repos even with no pull requests, and a pick filters the List", async ({ page }) => { + const db = await mockApi(page, { list: nothing }); + await page.goto("/prs"); + const picker = page.getByTestId("prs-scope-picker"); + await expect(picker).toHaveText(/All repos$/); + await picker.click(); + // All repos first, then every installed repo; one owner: no org anywhere. + await expect.poll(() => offered(page)).toEqual(["*", "acme/api", "acme/checkout", "acme/web"]); + await expect(page.getByTestId("combo-popover")).not.toContainText("acme "); + await page.getByRole("option", { name: "acme/checkout" }).click(); + await expect(page).toHaveURL(/[?&]repo=acme%2Fcheckout/); + await expect.poll(() => calls(db, "/api/prs").some((c) => /[?&]repo=acme%2Fcheckout/.test(c))).toBe(true); + await expect(picker).toHaveText(/Repos: checkout$/); + // The search narrows a long list. + await picker.click(); + await page.getByTestId("combo-search").fill("web"); + await expect.poll(() => offered(page)).toEqual(["acme/web"]); + }); + + test("a pick filters the Overview the same way", async ({ page }) => { + const db = await mockApi(page); + await page.goto("/prs/overview"); + await expect(page.getByTestId("overview-summary")).toBeVisible(); + const picker = page.getByTestId("prs-scope-picker"); + await expect(picker).toHaveText(/All repos$/); + await picker.click(); + await expect.poll(() => offered(page)).toEqual(["*", "acme/api", "acme/checkout", "acme/web"]); + await page.getByRole("option", { name: "acme/web" }).click(); + await expect(page).toHaveURL(/[?&]repo=acme%2Fweb/); + await expect.poll(() => calls(db, "/api/prs/overview").some((c) => /[?&]repo=acme%2Fweb/.test(c))).toBe(true); + await expect(picker).toHaveText(/Repos: web$/); + }); + + test("more than one owner: repos grouped by owner, the owner as context, and an old ?org= link opens every repo under it", async ({ page }) => { + const db = await mockApi(page, { repos: TWO_OWNERS }); + await page.goto("/prs?org=acme-labs"); + const picker = page.getByTestId("prs-scope-picker"); + await expect(picker).toHaveText(/acme-labs \/ All repos$/); + await expect(page.getByTestId("prs-scope")).toHaveAttribute("data-scope", "owner"); + await expect.poll(() => calls(db, "/api/prs").some((c) => /[?&]org=acme-labs/.test(c))).toBe(true); + await picker.click(); + const groups = page.getByTestId("combo-popover").getByTestId("combo-group"); + await expect(groups).toHaveCount(3); + await expect(page.locator("[cmdk-group-heading]")).toHaveText(["acme", "acme-labs"]); + await expect(page.getByRole("option", { name: "Every repo under acme-labs" })).toHaveAttribute("aria-selected", "true"); + await page.getByRole("option", { name: "acme-labs/search" }).click(); + await expect(page).toHaveURL(/[?&]repo=acme-labs%2Fsearch/); + await expect(page).not.toHaveURL(/[?&]org=/); + await expect(picker).toHaveText(/acme-labs \/ search$/); + + // The same old link on the Overview. + await page.goto("/prs/overview?org=acme"); + await expect(page.getByTestId("prs-scope-picker")).toHaveText(/acme \/ All repos$/); + await expect.poll(() => calls(db, "/api/prs/overview").some((c) => /[?&]org=acme(&|$)/.test(c))).toBe(true); + }); + + test("?org= with one owner is all repos, and the org is never shown", async ({ page }) => { + const db = await mockApi(page); + await page.goto("/prs?org=acme"); + await expect(page.getByTestId("prs-scope-picker")).toHaveText(/Repos: All repos$/); + await expect(page.getByTestId("prs-scope")).toHaveAttribute("data-scope", "all"); + await expect.poll(() => calls(db, "/api/prs").length).toBeGreaterThan(0); + }); + + test("one repo only: All repos is still the default and no org is shown", async ({ page }) => { + await mockApi(page, { repos: ["acme/web"], list: () => prsPage(ROWS.filter((r) => r.repo === "acme/web")) }); + await page.goto("/prs"); + const picker = page.getByTestId("prs-scope-picker"); + await expect(picker).toHaveText(/Repos: All repos$/); + await picker.click(); + await expect.poll(() => offered(page)).toEqual(["*", "acme/web"]); + await expect(page.locator("[cmdk-group-heading]")).toHaveText(["Repositories"]); + }); + + for (const [where, url] of [ + ["List", "/prs"], + ["Overview", "/prs/overview"], + ] as const) { + for (const width of [1440, 1024]) { + test(`the menu is anchored to its trigger on the ${where} at ${width}`, async ({ page }) => { + await page.setViewportSize({ width, height: 900 }); + await mockApi(page, { repos: TWO_OWNERS }); + await page.goto(url); + const picker = page.getByTestId("prs-scope-picker"); + await expect(picker).toBeVisible(); + await page.waitForTimeout(200); + await picker.click(); + const menu = page.getByTestId("combo-popover"); + await expect(menu).toBeVisible(); + const t = (await picker.boundingBox())!; + const m = (await menu.boundingBox())!; + expect(Math.abs(m.x - t.x)).toBeLessThanOrEqual(2); + expect(m.width).toBeGreaterThanOrEqual(t.width - 0.5); + expect(m.y).toBeGreaterThanOrEqual(t.y + t.height); + if (where === "List") await shot(page, `list-picker-after-${width}`); + }); + } + } + + test("on a phone the picker is a sheet with the search first", async ({ page }) => { + await page.setViewportSize({ width: 375, height: 800 }); + await mockApi(page, { repos: TWO_OWNERS }); + await page.goto("/prs"); + await expect(page.getByTestId("pr-row").first()).toBeVisible(); + const picker = page.getByTestId("prs-scope-picker"); + expect((await picker.boundingBox())!.height).toBeGreaterThanOrEqual(44); + await picker.click(); + await expect(page.getByTestId("combo-sheet")).toBeVisible(); + await expect(page.getByTestId("combo-search")).toBeFocused(); + await shot(page, "list-picker-after-375"); + }); +}); + +test.describe("states with nothing to show", () => { + test("List, older backend: not available on this version yet, no controls and no zeros", async ({ page }) => { + await mockApi(page, { list: () => 404 }); + await page.goto("/prs"); + const state = page.getByTestId("prs-not-available"); + await expect(state).toContainText("Pull requests is not available on this version yet"); + await expect(state).toContainText("An admin updates CoderHelm"); + await expect(state.getByRole("link", { name: "Open System settings" })).toHaveAttribute("href", /^\/settings\/system\/?$/); + await expect(page.getByTestId("prs-turns")).toHaveCount(0); + await expect(page.getByTestId("prs-views")).toHaveCount(0); + await expect(page.getByTestId("prs-scope")).toHaveCount(0); + await axe(page); + await shot(page, "list-state-not-available"); + }); + + test("List, being set up: says how far CoderHelm has read, with no zeros", async ({ page }) => { + const backfill = [{ owner: "acme", months_read: 3, months_total: 12, done: false, repos: {} }]; + await mockApi(page, { list: () => ({ ...nothing(), synced_at: null, backfill }) }); + await page.goto("/prs"); + const state = page.getByTestId("prs-setting-up"); + await expect(state).toContainText("Pull requests is being set up"); + await expect(state).toContainText("CoderHelm is reading your repos (3 of 12 months of history)."); + await expect(state.getByRole("progressbar")).toHaveAttribute("aria-valuenow", "25"); + await expect(page.getByTestId("prs-turns")).toHaveCount(0); + await expect(page.getByTestId("list-toolbar")).toHaveCount(0); + // The picker still lists the installed repos. + await expect(page.getByTestId("prs-scope-picker")).toBeVisible(); + await axe(page); + await shot(page, "list-state-setting-up"); + }); + + test("List, being set up without numbers: says it is reading the team's repos", async ({ page }) => { + await mockApi(page, { list: () => ({ ...nothing(), synced_at: null }) }); + await page.goto("/prs"); + await expect(page.getByTestId("prs-setting-up-text")).toContainText("CoderHelm is reading your team's repos."); + await expect(page.getByTestId("prs-setting-up").getByRole("progressbar")).not.toHaveAttribute("aria-valuenow", /.*/); + }); + + test("List, read and empty: no open pull requests, and no zero counts", async ({ page }) => { + await mockApi(page, { list: nothing }); + await page.goto("/prs"); + await expect(page.getByTestId("list-empty")).toContainText("No open pull requests"); + await expect(page.getByTestId("prs-turns")).toHaveCount(0); + await axe(page); + }); + + test("Overview, older backend: not available on this version yet", async ({ page }) => { + await mockApi(page, { overview: () => 404 }); + await page.goto("/prs/overview"); + const state = page.getByTestId("overview-not-served"); + await expect(state).toContainText("The Pull requests overview is not available on this version yet"); + await expect(state).toContainText("An admin updates CoderHelm"); + await expect(state.getByRole("link", { name: "list" })).toHaveAttribute("href", /^\/prs\/?$/); + await axe(page); + await shot(page, "overview-state-not-available"); + }); + + test("Overview, being set up: n of m repos read, never zero tiles or empty charts", async ({ page }) => { + await mockApi(page, { + overview: () => { + const o = overview("empty"); + return { ...o, history: { ...o.history, backfill: { repos: 14, repos_read: 5, done: false, days: 0 } } }; + }, + }); + await page.goto("/prs/overview"); + const state = page.getByTestId("overview-setting-up"); + await expect(state).toContainText("Pull requests is being set up"); + await expect(state).toContainText("CoderHelm is reading your repos (5 of 14)."); + await expect(page.getByTestId("summary-tile")).toHaveCount(0); + await expect(page.getByTestId("overview-summary")).toHaveCount(0); + await axe(page); + await shot(page, "overview-state-setting-up"); + }); + + for (const width of [320, 375]) { + test(`the states have no sideways scroll at ${width}`, async ({ page }) => { + await page.setViewportSize({ width, height: 800 }); + const db = await mockApi(page, { list: () => 404, overview: () => 404 }); + for (const url of ["/prs", "/prs/overview"]) { + await page.goto(url); + await expect(page.getByTestId(url === "/prs" ? "prs-not-available" : "overview-not-served")).toBeVisible(); + expect(await sideways(page)).toBeLessThanOrEqual(0); + } + db.list = () => ({ ...nothing(), synced_at: null }); + db.overview = () => overview("empty"); + await page.goto("/prs"); + await expect(page.getByTestId("prs-setting-up")).toBeVisible(); + expect(await sideways(page)).toBeLessThanOrEqual(0); + await page.goto("/prs/overview"); + await expect(page.getByTestId("overview-empty")).toBeVisible(); + expect(await sideways(page)).toBeLessThanOrEqual(0); + }); + } +}); + +const BIG_REPOS = [...TWO_OWNERS, "acme/admin", "acme/mobile", "acme/docs"]; + +/** Sparse: one repo, three pull requests. Medium: the usual nine over three repos. Big: 400 more over eight repos. */ +const SIZES: Record = { + sparse: { repos: ["acme/web"], rows: ROWS.filter((r) => r.repo === "acme/web").slice(0, 3) }, + medium: { repos: ONE_OWNER, rows: ROWS }, + big: { + repos: BIG_REPOS, + rows: [ + ...ROWS, + ...many(400).map((r, i): PrRow => { + const repo = BIG_REPOS[i % BIG_REPOS.length]; + return { ...r, repo, org: repo.split("/")[0], key: `${repo}#${r.number}`, url: `https://github.com/${repo}/pull/${r.number}`, turn: (["you", "coderhelm", "person", "machines"] as const)[i % 4] }; + }), + ], + }, +}; + +/** Anything floating that nobody opened: a tooltip, a popper or a dialog. */ +async function floating(page: Page): Promise { + return page.evaluate(() => + Array.from(document.querySelectorAll('[role="tooltip"], [data-radix-popper-content-wrapper], [role="dialog"], [data-popover]')) + .filter((el) => { + const r = el.getBoundingClientRect(); + const cs = getComputedStyle(el); + return r.width > 0 && r.height > 0 && cs.visibility !== "hidden" && cs.display !== "none" && Number(cs.opacity) > 0; + }) + .map((el) => el.outerHTML.slice(0, 120)), + ); +} + +for (const [size, data] of Object.entries(SIZES)) { + for (const width of [1440, 1280, 1024, 375]) { + test(`List polish, ${size} data at ${width}: nothing floats at rest, nothing scrolls sideways, labels stay whole`, async ({ page }) => { + await page.setViewportSize({ width, height: 900 }); + await mockApi(page, { repos: data.repos, list: () => prsPage(data.rows) }); + await page.goto("/prs"); + await expect(page.getByTestId("pr-row").first()).toBeVisible(); + await page.mouse.move(0, 0); + await page.waitForTimeout(250); + expect(await floating(page)).toEqual([]); + expect(await sideways(page)).toBeLessThanOrEqual(0); + if (width > 640) { + // The turn strip fits on one line from 1024 up. + const tops = await page.getByTestId("prs-turns").locator("button").evaluateAll((els) => new Set(els.map((el) => Math.round(el.getBoundingClientRect().top))).size); + expect(tops).toBe(1); + } + // The picker is no taller than the other controls and no label is cut. + const cut = await page.getByTestId("prs-scope-picker").evaluate((el) => el.scrollWidth > el.clientWidth + 1); + expect(cut).toBe(false); + await shot(page, `list-polish-${size}-${width}`); + }); + } +} diff --git a/dashboard/e2e/prs.spec.ts b/dashboard/e2e/prs.spec.ts index 93eacb7a..3041a2d3 100644 --- a/dashboard/e2e/prs.spec.ts +++ b/dashboard/e2e/prs.spec.ts @@ -48,7 +48,9 @@ async function mockApi(page: Page, init: Partial = {}): Promise db.calls.filter((c) => c.startsWith("GET /api/prs?") || c === "GET /api/prs"); +// The list's own reads: not the menu count's "your turn" read (the shell reads +// it on an older backend without For you). +const listCalls = (db: Backend) => db.calls.filter((c) => (c.startsWith("GET /api/prs?") || c === "GET /api/prs") && !c.includes("turn=you")); const SHOTS = process.env.E2E_SHOTS_DIR; async function shot(page: Page, name: string) { @@ -96,8 +98,8 @@ test("pull requests are grouped by whose turn it is, each with what it needs and // 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"); + // The scope is one repo picker, on all repos by default. + await expect(page.getByTestId("prs-scope-picker")).toContainText("All repos"); await expect(page.getByTestId("prs-synced")).toContainText("Synced"); await shot(page, "prs-desktop-list"); }); @@ -220,22 +222,17 @@ test("saved views and turn filters go to the server and live in the address", as 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 }) => { +test("the scope picker is the address: a repo, then back to all repos", 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); - // Each step is a switcher: a bordered button that opens its level's choices. - const allOrgs = scope.getByRole("button", { name: /^All orgs/ }); - expect(await allOrgs.evaluate((el) => getComputedStyle(el).borderTopWidth)).not.toBe("0px"); - await scope.getByRole("button", { name: /^acme/ }).click(); - await page.getByRole("menuitem", { name: "All repos in acme" }).click(); + await page.goto("/prs?repo=acme/web"); + const picker = page.getByTestId("prs-scope-picker"); + // One owner: the trigger names the repo alone, without the org. + await expect(picker).toHaveText(/Repos: web$/); + await expect.poll(() => listCalls(db).some((c) => c.includes("repo=acme%2Fweb"))).toBe(true); + await picker.click(); + await page.getByRole("option", { name: "All repos" }).click(); await expect(page).not.toHaveURL(/repo=/); - await expect(page).toHaveURL(/org=acme/); - await allOrgs.click(); - await page.getByRole("menuitem", { name: "All orgs" }).click(); - await expect(page).not.toHaveURL(/org=/); + await expect(picker).toHaveText(/Repos: All repos$/); }); test("the keyboard: j and k move, Enter opens, Esc closes, / searches", async ({ page }) => { @@ -351,8 +348,8 @@ test("a backend without the endpoint says when it arrives, and stops asking", as 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\/?$/); + await expect(page.getByTestId("prs-not-available")).toContainText("Pull requests is not available on this version yet"); + await expect(page.getByTestId("prs-not-available").getByRole("link", { name: "Reviewer" })).toHaveAttribute("href", /^\/reviewer\/?$/); const n = listCalls(db).length; await page.clock.runFor(95_000); expect(listCalls(db).length).toBe(n); diff --git a/dashboard/e2e/reviewer-session.spec.ts b/dashboard/e2e/reviewer-session.spec.ts index a195d1de..66bb9afa 100644 --- a/dashboard/e2e/reviewer-session.spec.ts +++ b/dashboard/e2e/reviewer-session.spec.ts @@ -1,3 +1,4 @@ +import { quietForYou } from "./foryou-data"; import { expect, test, type Page, type Route } from "@playwright/test"; import { activityHeading, @@ -180,6 +181,8 @@ async function mockApi(page: Page, init: Partial = {}): Promise = { "/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`)}`, + "/foryou/answer": `?run=${RUN_ID}`, "/inbox/answer": `?run=${RUN_ID}`, + "/foryou/pr": `?repo=${encodeURIComponent(REPO)}&number=12345&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. diff --git a/dashboard/e2e/wide-data/index.ts b/dashboard/e2e/wide-data/index.ts index 3c590c37..1e9cab1d 100644 --- a/dashboard/e2e/wide-data/index.ts +++ b/dashboard/e2e/wide-data/index.ts @@ -15,7 +15,7 @@ import { setupData } from "./setup"; import { skillRunsData } from "./skill-runs"; import { prsData } from "./prs"; import { prsOverviewData } from "./prs-overview"; -import { inboxData } from "./inbox"; +import { needSourcesData } from "./needs"; import { foryouData } from "./foryou"; // An invented backend whose records are full of long, unbroken strings @@ -55,7 +55,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, foryouData, inboxData, prsData, prsOverviewData]; +const HANDLERS: Handler[] = [base, runsData, reviewData, settingsData, logsData, learningData, knowledgeData, brainData, agentsData, pluginsData, securityData, infraData, setupData, skillRunsData, foryouData, needSourcesData, prsData, prsOverviewData]; /** 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/inbox.ts b/dashboard/e2e/wide-data/needs.ts similarity index 95% rename from dashboard/e2e/wide-data/inbox.ts rename to dashboard/e2e/wide-data/needs.ts index e1acd146..97c575ed 100644 --- a/dashboard/e2e/wide-data/inbox.ts +++ b/dashboard/e2e/wide-data/needs.ts @@ -24,7 +24,7 @@ const PR = { waiting_since: iso(300), }; -export const inboxData: Handler = ({ method, path }) => { +export const needSourcesData: 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: [] }; diff --git a/dashboard/scripts/ui-lint-allow.json b/dashboard/scripts/ui-lint-allow.json index 8134ef9d..f0a368e7 100644 --- a/dashboard/scripts/ui-lint-allow.json +++ b/dashboard/scripts/ui-lint-allow.json @@ -32,13 +32,13 @@ { "rule": "dashed-box", "file": "src/app/foryou/parts.tsx", - "text": "border-l-2 border-dashed border-info-line", + "text": "border-l-2 border-dashed border-accent-line", "why": "A suggestion's dashed left edge marks CoderHelm's proposal as not yet real (the approved For you design, from the suggestions research): it is one edge on a solid tinted block with real content, never an empty placeholder box." }, { "rule": "dashed-box", "file": "src/app/foryou/page.tsx", - "text": "border-l-2 border-dashed border-info-line", + "text": "border-l-2 border-dashed border-accent-line", "why": "A suggestion's dashed left edge marks CoderHelm's proposal as not yet real (the approved For you design, from the suggestions research): it is one edge on a solid tinted block with real content, never an empty placeholder box." } ] diff --git a/dashboard/src/app/foryou/accounts.tsx b/dashboard/src/app/foryou/accounts.tsx new file mode 100644 index 00000000..1f086640 --- /dev/null +++ b/dashboard/src/app/foryou/accounts.tsx @@ -0,0 +1,169 @@ +"use client"; + +// Connected accounts on For you: one row per account, one plain status +// ("Linked as @login", "Not linked"), one small secondary action, never a +// badge beside a contradicting word. And the Jira link sheet: what Connect +// does, in three steps, with the code and a live "Waiting for Jira…" that +// turns into "Linked as …" once Jira has sent it. + +import { useEffect, useState } from "react"; +import { AtlassianIcon, CheckIcon, GitHubIcon } from "@/components/icons"; +import { Modal } from "@/components/modal"; +import { buttonClass } from "@/components/ui"; +import { apiBase } from "@/lib/runtime-config"; +import { loadForYou, type ForYou } from "@/lib/foryou"; + +type Accounts = ForYou["accounts"]; + +function Row({ icon, name, hint, action, testId }: { icon: React.ReactNode; name: string; hint: string; action?: React.ReactNode; testId: string }) { + return ( +
  • + + + {name} + + {hint} + + + {action} +
  • + ); +} + +/** The card. `fallback`: an older backend that serves no link routes, so no button that would fail. */ +export function AccountsCard({ accounts, fallback, onLinkJira, onUnlinkJira }: { accounts: Accounts; fallback: boolean; onLinkJira: () => void; onUnlinkJira: () => void }) { + const gh = accounts.github; + const jira = accounts.jira; + const ghLinked = gh.state === "linked" && !!gh.login; + const jiraHint = + jira.state === "linked" ? `Linked as ${jira.name || "your Atlassian account"}` : fallback ? "Arrives with the next update" : jira.state === "not_connected" ? "Your team's Jira isn't connected" : "Not linked"; + return ( +
    +

    Connected accounts

    +
      + } + name="GitHub" + hint={ghLinked ? `Linked as @${gh.login}` : "Not linked"} + testId="fy-acct-github" + action={ + ghLinked ? undefined : ( + + Link + + ) + } + /> + } + name="Jira" + hint={jiraHint} + testId="fy-acct-jira" + action={ + jira.state === "linked" ? ( + + ) : jira.state === "not_linked" && !fallback ? ( + + ) : undefined + } + /> +
    +
    + ); +} + +/** What Connect does, the code, and whether Jira has sent it yet. */ +export function LinkSheet({ code, onClose, onLinked }: { code: { code: string; expires_at?: string } | null; onClose: () => void; onLinked: (name: string) => void }) { + const [copied, setCopied] = useState(false); + const [linked, setLinked] = useState(null); + useEffect(() => { + setCopied(false); + setLinked(null); + if (!code) return; + let live = true; + // Waiting for Jira: the page is read again every few seconds until the + // link shows (or the sheet closes). + const t = window.setInterval(() => { + loadForYou().then( + (r) => { + if (!live || r.accounts.jira.state !== "linked") return; + const name = r.accounts.jira.name || "your Atlassian account"; + setLinked(name); + window.clearInterval(t); + onLinked(name); + }, + () => {}, + ); + }, 4000); + return () => { + live = false; + window.clearInterval(t); + }; + }, [code, onLinked]); + const minutes = code?.expires_at ? Math.max(1, Math.round((Date.parse(code.expires_at) - Date.now()) / 60_000)) : 15; + const copy = async () => { + if (!code) return; + try { + await navigator.clipboard.writeText(code.code); + setCopied(true); + } catch { + setCopied(false); + } + }; + return ( + !o && onClose()} title="Link your Jira account" description="Three steps in Jira. CoderHelm never links you by matching emails." testId="fy-link-code"> + {code && ( +
    +
      + {[ + <>Open any Jira issue., + <> + Choose ••• and then Link my CoderHelm account. + , + <> + Paste this code (it works once, for {minutes} min): + + + {code.code} + + + + , + ].map((step, i) => ( +
    1. + + {step} +
    2. + ))} +
    +

    + {linked ? ( + <> + + Linked as {linked} + + ) : ( + <> +

    +

    This only tells CoderHelm which Jira person is you. Your admin’s Jira connection, and what CoderHelm can read, don’t change.

    +
    + )} +
    + ); +} diff --git a/dashboard/src/app/foryou/answer/page.tsx b/dashboard/src/app/foryou/answer/page.tsx new file mode 100644 index 00000000..ea3bf6b3 --- /dev/null +++ b/dashboard/src/app/foryou/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 { forYouChanged } from "@/lib/foryou"; +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 +// For you. + +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 For you}> + {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 For you}> + 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}
    • + ))} +
    +
    + )} + { + forYouChanged(); + setSent(true); + window.setTimeout(() => router.push("/foryou"), 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/foryou/customize.tsx b/dashboard/src/app/foryou/customize.tsx index b9759d94..2511427c 100644 --- a/dashboard/src/app/foryou/customize.tsx +++ b/dashboard/src/app/foryou/customize.tsx @@ -32,7 +32,7 @@ function Rows({ list, labels, layout, onChange, group }: { lis onChange={(e) => onChange(list, e.target.checked ? layout.hidden.filter((h) => h !== k) : [...layout.hidden, k])} className={`h-4 w-4 ${focusRing}`} /> - {label} + {label} - @@ -122,6 +124,12 @@ export function GiveSheet({

    {preview.plan.text}

    + {preview.plan.available && preview.plan.view && ( +
    + + {preview.plan.view.tests.length > 0 &&

    Tests: {preview.plan.view.tests.join("; ")}

    } +
    + )} {preview.criteria.length > 0 && ( <>

    What the ticket asks for:

    @@ -186,7 +194,7 @@ export function GiveSheet({ data-testid="fy-batch-check" /> - {k} {t?.title} + {k} {t?.title}
    {[t?.points != null ? `${t.points} pt` : "", ...(t?.repos ?? [])].filter(Boolean).join(" · ")}
    @@ -197,12 +205,12 @@ export function GiveSheet({ )} {target && ( -
    +

    - You stay the owner. CoderHelm is the delegate. The ticket stays assigned to you in Jira. CoderHelm opens one pull request on its own branch, and someone other than you approves it. You can stop it at any time. + You stay the owner. CoderHelm is the delegate. The ticket stays assigned to you in Jira. CoderHelm opens one pull request on its own branch, and someone other than you approves it. You can stop it at any time.

    )} diff --git a/dashboard/src/app/foryou/page.tsx b/dashboard/src/app/foryou/page.tsx index 74bc6078..7f773193 100644 --- a/dashboard/src/app/foryou/page.tsx +++ b/dashboard/src/app/foryou/page.tsx @@ -17,7 +17,7 @@ import { Page, PageHeader } from "@/components/page"; import { EmptyState } from "@/components/empty-state"; import { Problem } from "@/components/problem"; import { Skeleton } from "@/components/skeleton"; -import { CheckIcon, ChevronRightIcon, GitHubIcon, LockIcon, MoreIcon, SlidersIcon } from "@/components/icons"; +import { CheckIcon, ChevronRightIcon, GitHubIcon, InfoIcon, LockIcon, MoreIcon, SlidersIcon } from "@/components/icons"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/popover"; import { AtlassianIcon } from "@/components/icons"; import { Modal } from "@/components/modal"; @@ -39,11 +39,14 @@ import { type NeedItem, type SectionKey, type Suggestion, + type WaitingItem, type Withdrawn, } from "@/lib/foryou"; import { Card, GroupHead, Mark, NeedRow, Section, SuggestionBlock, TicketRow, WaitingRow, WithdrawnRow, WorkCard } from "./parts"; import { Customize } from "./customize"; +import { AccountsCard, LinkSheet } from "./accounts"; import { GiveSheet, type GiveTarget } from "./give-sheet"; +import { PlanSheet } from "./plan"; type Local = { state: "reasons" } | { state: "said"; msg: string; undo?: () => void }; @@ -64,7 +67,7 @@ export default function ForYouPage() { const [laterOpen, setLaterOpen] = useState(false); const [sumOpen, setSumOpen] = useState(false); const [focus, setFocus] = useState(-1); - const [code, setCode] = useState<{ code: string; steps: string[] } | null>(null); + const [code, setCode] = useState<{ code: string; expires_at?: string } | null>(null); const { toast } = useToast(); const root = useRef(null); @@ -198,6 +201,41 @@ export default function ForYouPage() { } }; + // ── Plans and nudges ──────────────────────────────────────────────── + const [planRun, setPlanRun] = useState(null); + const onPlanAnswered = (approved: boolean) => { + setPlanRun(null); + toast(approved ? "Approved. CoderHelm codes from this plan now." : "Sent. CoderHelm plans again and asks for your OK again."); + forYouChanged(); + void load(true); + }; + const nudge = async (w: WaitingItem) => { + if (!w.pr) return; + const pr = w.pr; + try { + const r = await foryouApi.nudge(pr.repo, pr.number); + toast(r.effect, "success", { + action: { + label: "Undo", + onClick: () => void unnudge(w), + }, + }); + void load(true); + } catch (e) { + toast(e instanceof ApiError ? e.message : "The nudge couldn't be sent.", "error"); + } + }; + const unnudge = async (w: WaitingItem) => { + if (!w.pr) return; + try { + const r = await foryouApi.unnudge(w.pr.repo, w.pr.number); + toast(r.effect); + void load(true); + } catch (e) { + toast(e instanceof ApiError ? e.message : "That couldn't be undone.", "error"); + } + }; + const onGiven = (keys: string[], planFirst: boolean, message: string) => { setGive(null); toast(planFirst ? `${message} It writes the plan first and waits for your OK.` : message); @@ -209,11 +247,15 @@ export default function ForYouPage() { const connectJira = async () => { try { const r = await foryouApi.linkCode(); - setCode({ code: r.code, steps: r.steps }); + setCode({ code: r.code, expires_at: r.expires_at }); } catch (e) { toast(e instanceof ApiError ? e.message : "A code couldn't be made.", "error"); } }; + const onJiraLinked = useCallback((name: string) => { + toast(`Jira linked as ${name}. Your sprint shows here now.`); + void load(true); + }, [toast, load]); const unlinkJira = async () => { try { await foryouApi.unlink(); @@ -241,11 +283,26 @@ export default function ForYouPage() { const withdrawn = seenWithdrawn; const needs = data?.needs; const visible = (i: { key: string }) => !hidden.has(i.key); - const reviews = (needs?.reviews ?? []).filter(visible); + // Anything idle past STALE_DAYS is probably abandoned: it leaves the top + // for a folded group of its own, with Dismiss all. + const fresh = (i: NeedItem) => !isStale(i.since); + const allReviews = (needs?.reviews ?? []).filter(visible); + const allReturned = (needs?.returned ?? []).filter(visible); + const allAsks = (needs?.asks ?? []).filter(visible); + const reviews = allReviews.filter(fresh); const suggestedReviews = (needs?.suggested_reviews ?? []).filter(visible); - const returned = (needs?.returned ?? []).filter(visible); - const asks = (needs?.asks ?? []).filter(visible); - const needCount = reviews.length + returned.length + asks.length; + const returned = allReturned.filter(fresh); + // Copies of one thing (a template's plans, say) under one row with a count. + const asks = groupAlike(allAsks.filter(fresh)); + const stale = [...allReviews, ...allReturned, ...allAsks].filter((i) => !fresh(i)); + const needCount = reviews.length + returned.length + asks.reduce((n, a) => n + 1 + a.more.length, 0); + const oldestNeed = (() => { + const all = [...reviews, ...returned, ...asks.flatMap((a) => [a.item, ...a.more])].filter((i) => i.since); + if (!all.length) return data?.stats.waiting_on_you.oldest ?? null; + const o = all.reduce((a, b) => (Date.parse(a.since as string) <= Date.parse(b.since as string) ? a : b)); + return { where: o.where, since: o.since as string }; + })(); + const topKey = reviews[0]?.key ?? returned[0]?.key ?? asks[0]?.item.key ?? null; const notConnected = !!data && !data.fallback && data.accounts.github.state !== "linked" && data.accounts.jira.state !== "linked"; // Rows in reading order, for j/k. @@ -296,12 +353,12 @@ export default function ForYouPage() { const parts: { tone: string; text: React.ReactNode }[] = []; parts.push( needCount - ? { tone: "bg-warn-solid", text: <>{needCount} {needCount === 1 ? "thing needs" : "things need"} you } + ? { tone: "bg-warn-solid", text: <>{needCount} {needCount === 1 ? "thing needs" : "things need"} you } : { tone: "bg-good-solid", text: <>Nothing needs you right now }, ); - if (data.working.length) parts.push({ tone: "bg-info-solid", text: <>CoderHelm is working on {data.working.length} of your tickets }); + if (data.working.length) parts.push({ tone: "bg-accent-solid", text: <>CoderHelm is working on {data.working.length} of your tickets }); if (data.accounts.jira.state !== "linked" && !data.fallback) parts.push({ tone: "bg-neutral-solid", text: <>Link Jira to see your sprint }); - else if (!needCount && data.waiting.length) parts.push({ tone: "bg-neutral-solid", text: <>{data.waiting.length} of your PRs wait on others }); + else if (!needCount && data.waiting.length) parts.push({ tone: "bg-neutral-solid", text: <>{data.waiting.length} of your PRs wait on others }); return parts; })(); @@ -310,8 +367,8 @@ export default function ForYouPage() { if (!s) return; const el = document.getElementById(`sg-${s.key.replace(/[^a-zA-Z0-9-]/g, "-")}`); el?.scrollIntoView({ behavior: "smooth", block: "center" }); - el?.classList.add("ring-2", "ring-info-line"); - window.setTimeout(() => el?.classList.remove("ring-2", "ring-info-line"), 2000); + el?.classList.add("ring-2", "ring-accent-line"); + window.setTimeout(() => el?.classList.remove("ring-2", "ring-accent-line"), 2000); }; const renderSuggestion = (target: string) => { @@ -334,30 +391,62 @@ export default function ForYouPage() { .filter((w) => w.kind === kind) .map((w) => setSeenWithdrawn((l) => l.filter((x) => x.key !== w.key))} />); - const needRow = (item: NeedItem) => ( - void mark(item, "snooze")} onDone={() => void mark(item, "done")}> + const needRow = (item: NeedItem, extra?: React.ReactNode) => ( + void mark(item, "snooze")} onDone={() => void mark(item, "done")} onOpenPlan={setPlanRun}> {renderSuggestion(item.key)} + {extra} ); + const askRow = (a: { item: NeedItem; more: NeedItem[] }) => + needRow( + a.item, + a.more.length > 0 ? ( +
    + + {a.more.length} more like it + +
      + {a.more.map((m) => ( +
    • + {m.where} + {m.since && waiting {waited(m.since)}} + {m.action && ( + + {m.action.label} + + )} +
    • + ))} +
    +
    + ) : undefined, + ); + const dismissStale = async () => { + const keys = stale.map((i) => i.key); + setHidden((h) => new Set([...h, ...keys])); + await Promise.allSettled(stale.map((i) => foryouApi.mark({ key: i.key, action: "done", since: i.since ?? null }))); + toast(`${keys.length} old ${keys.length === 1 ? "item" : "items"} dismissed. Each comes back if it changes.`); + forYouChanged(); + }; const sections: Record = data ? { needs: (
    - {needCount === 0 && suggestedReviews.length === 0 ? ( + {needCount === 0 && suggestedReviews.length === 0 && stale.length === 0 ? (
    -

    Nothing is waiting on you

    +

    Nothing is waiting on you

    No review requests, no pull requests sent back, no questions from CoderHelm.

      {data.stats.waiting_on_others.longest && (
    • - Your oldest PR waiting: {data.stats.waiting_on_others.longest.where} for {waited(data.stats.waiting_on_others.longest.since)} + Your oldest PR waiting: {data.stats.waiting_on_others.longest.where} for {waited(data.stats.waiting_on_others.longest.since)}
    • )} @@ -386,15 +475,15 @@ export default function ForYouPage() { {(reviews.length > 0 || suggestedReviews.length > 0 || withdrawn.some((w) => w.kind === "review")) && ( <> - {reviews.map(needRow)} - {suggestedReviews.map(needRow)} + {reviews.map((r) => needRow(r))} + {suggestedReviews.map((r) => needRow(r))} {withdrawnFor("review")} )} {returned.length > 0 && ( <> - {returned.map(needRow)} + {returned.map((r) => needRow(r))} )} {asks.length > 0 && ( @@ -405,12 +494,27 @@ export default function ForYouPage() { CoderHelm asks you } - count={asks.length} - oldest={asks[0]?.since} + count={asks.reduce((n, a) => n + 1 + a.more.length, 0)} + oldest={asks[0]?.item.since} /> - {asks.map(needRow)} + {asks.map(askRow)} )} + {stale.length > 0 && ( +
      + + Old, probably abandoned {stale.length} + idle over {STALE_DAYS} days + +
      + Nothing has moved on these for a month or more. + +
      + {stale.map((r) => needRow(r))} +
      + )} )}
    @@ -455,8 +559,12 @@ export default function ForYouPage() { ) ) : data.sprint.state === "not_linked" ? ( void connectJira()} onNo={(id) => void notMe(id)} /> + ) : data.sprint.state === "unavailable" ? ( +

    + {data.sprint.detail} It arrives with the next update. +

    ) : ( - + {data.sprint.detail} )} @@ -477,18 +585,18 @@ export default function ForYouPage() {
    {data.waiting.filter(visible).map((w) => ( - + void nudge(x)} onUnnudge={(x) => void unnudge(x)} /> ))}
    ) : null, - later: ( + later: data.later.length ? (
    @@ -500,11 +608,11 @@ export default function ForYouPage() { {l.later === "snoozed" ? "Snoozed" : l.later === "fyi" ? "FYI" : "Not in this sprint"} {l.where} {l.href ? ( - + {l.title} ) : ( - {l.title} + {l.title} )} {l.snoozed_until && back {new Date(l.snoozed_until).toLocaleString([], { weekday: "short", hour: "numeric", minute: "2-digit" })}} {l.later === "snoozed" && ( @@ -521,7 +629,7 @@ export default function ForYouPage() { )}
    - ), + ) : null, } : { needs: null, sprint: null, working: null, waiting: null, later: null }; @@ -533,7 +641,7 @@ export default function ForYouPage() { .map((r) => r === "stats" ? (
    -

    +

    Just for you

    Only you can see this. Admins can’t open it.

    @@ -541,11 +649,11 @@ export default function ForYouPage() {

    Your private numbers show here once GitHub is connected: what waits on you, what waits on others, and how quickly you review.

    ) : (
    - - + + @@ -554,50 +662,7 @@ export default function ForYouPage() {

    No streaks, commit counts, lines of code or rankings. Nothing here compares you with anyone.

    ) : ( -
    -

    Connected accounts

    -
      -
    • - - - GitHub{data.accounts.github.login ? ` · @${data.accounts.github.login}` : " · not linked"} -
      - {data.accounts.github.login ? "Linked by your GitHub account" : "Sign in once with GitHub"} -
      - {data.accounts.github.state === "linked" ? ( - On - ) : ( - - Connect - - )} -
    • -
    • - - - Jira · {data.accounts.jira.state === "linked" ? data.accounts.jira.name || "linked" : "not linked"} -
      - {data.accounts.jira.state === "linked" ? "Linked by your Atlassian account" : data.accounts.jira.state === "not_connected" ? "Your team's Jira isn't connected" : "Link by your Atlassian account"} -
      - {data.accounts.jira.state === "linked" ? ( - <> - On - - - ) : data.accounts.jira.state === "not_linked" ? ( - - ) : null} -
    • -
    -
    + void connectJira()} onUnlinkJira={() => void unlinkJira()} /> ), )} @@ -649,13 +714,13 @@ export default function ForYouPage() {

    - Suggested + Suggested {summary.kinds.map((k) => ( {" "} {" "} - @@ -664,16 +729,16 @@ export default function ForYouPage() { {" "} {" "} -

    {sumOpen && ( -
      +
        {(data?.suggestions ?? []).slice(0, 3).map((x) => (
      • - + {x.text} {x.reason}
      • @@ -703,12 +768,15 @@ export default function ForYouPage() {
    )} {data?.fallback && ( -

    - This CoderHelm serves an older version: what needs you is listed from the Inbox. Your sprint, CoderHelm’s work and your numbers show once it is updated. +

    + + This CoderHelm is an older version: what needs you is read from its other pages. Your sprint, CoderHelm’s work and your numbers arrive with the next update.

    )} {data && data.sources.filter((x) => x.read === "failed").length > 0 && ( -

    +

    Not everything could be read: {data.sources.filter((x) => x.read === "failed").map((x) => `${x.name} (${x.detail})`).join("; ")}.

    )} @@ -718,7 +786,7 @@ export default function ForYouPage() {
    void connectJira()} />
    -

    After you connect

    +

    After you connect

    Needs you now, grouped by whose turn it is · Your sprint, with a CoderHelm fit on each ticket · CoderHelm’s live work for you · Your PRs waiting on others

    @@ -736,6 +804,7 @@ export default function ForYouPage() { )}
    + setPlanRun(null)} onAnswered={onPlanAnswered} /> setGive(null)} onGiven={onGiven} /> - !o && setCode(null)} title="Link your Jira account" description="CoderHelm never links you by email: you prove the account from Jira." testId="fy-link-code"> - {code && ( -
    -

    - {code.code} -

    -
      - {code.steps.map((s) => ( -
    1. {s}
    2. - ))} -
    -

    The code works once, for 15 minutes. This page shows your sprint as soon as it is linked.

    -
    - )} -
    + setCode(null)} onLinked={onJiraLinked} /> ); } -function Stat({ label, value, sub, testId }: { label: string; value: string; sub: string; testId: string }) { +/** One private number. With nothing to count it says so in words, quietly, never a big zero. */ +function Stat({ label, value, sub, testId }: { label: string; value: string | null; sub: string; testId: string }) { return (
    {label}
    -
    {value}
    -
    {sub}
    + {value ?
    {value}
    :
    None
    } + {sub &&
    {sub}
    }
    ); } @@ -810,16 +866,21 @@ function Loading() { function LinkJira({ suggestion, onConnect, onNo }: { suggestion: ForYou["accounts"]["jira"]["suggestion"]; onConnect: () => void; onNo: (id: string) => void }) { return (
    -

    +

    Link Jira to see your sprint

    CoderHelm finds your tickets by your Atlassian account. It never links you by matching emails, because emails can be hidden or differ between tools.

    {suggestion ? ( -
    +
    - Is this you? {suggestion.name} (Jira) + Is this you? {suggestion.name} (Jira)
    {suggestion.why} + {suggestion.seen_on && suggestion.seen_on.length > 0 && ( + + Seen on {suggestion.seen_on.join(", ")} + + )}
    + ) : external ? ( {item.action.label} ) : ( - + {item.action.label} ))} @@ -163,7 +199,7 @@ export function NeedRow({ const BAND_TONE: Record = { good: "border-good-line bg-good-soft text-good", - maybe: "border-done-line bg-done-soft text-done-strong", + maybe: "border-done-line bg-done-soft text-done", not: "border-line-strong bg-hover text-fg-secondary", }; @@ -179,12 +215,12 @@ export function FitBadge({ ticket, fit }: { ticket: string; fit: Fit }) { -

    +

    {fit.label} {ticket}

    {fit.why.length > 0 && ( <> -

    Why

    +

    Why

    ); } /** One of your pull requests where someone else has the turn. */ -export function WaitingRow({ w }: { w: WaitingItem }) { +export function WaitingRow({ w, onNudge, onUnnudge }: { w: WaitingItem; onNudge?: (w: WaitingItem) => void; onUnnudge?: (w: WaitingItem) => void }) { + const sent = w.nudge?.sent ?? null; + const to = w.nudge ? w.nudge.to : w.next.who; return (
    {w.where} {w.by_coderhelm && ( - + by CoderHelm for you )}
    -
    + {w.title} -
    - Next: - {w.next.who ? ( - <> - - @{w.next.who} - - ) : ( - {w.next.turn === "coderhelm" ? "CoderHelm" : w.next.turn === "machines" ? "checks" : "someone"} - )} - · {w.next.what} - {w.since && · {waited(w.since)}} +
    + {w.next.who && } +

    + Next: {w.next.who ? `@${w.next.who}` : w.next.turn === "coderhelm" ? "CoderHelm" : w.next.turn === "machines" ? "checks" : "someone"} + {", "} + {w.next.what} + {w.since && {`, waiting ${waited(w.since)}`}} +

    - {w.next.who && ( - - Nudge - + {sent ? ( +
    + + {sent.mine ? "You nudged" : `@${sent.by} nudged`}{" "} + + @{sent.to} + {" "} + {(() => { + const ago = waited(new Date(sent.at * 1000).toISOString()); + return ago === "just now" ? ago : `${ago} ago`; + })()}{" "} + · one a day + + {sent.mine && onUnnudge && ( + + )} +
    + ) : ( + to && + w.pr && + onNudge && ( + + ) )}
    ); @@ -430,7 +488,7 @@ export function SuggestionBlock({ onUndo: () => void; }) { const [why, setWhy] = useState(false); - const box = "mt-3 rounded-r-lg border-l-2 border-dashed border-info-line bg-info-soft px-4 py-3"; + const box = "mt-3 rounded-r-lg border-l-2 border-dashed border-accent-line bg-accent-soft px-4 py-3"; if (local?.state === "reasons") { return (
    @@ -474,9 +532,9 @@ export function SuggestionBlock({ Suggested - {s.text} + {s.text}

    - {s.back_because &&

    {s.back_because}

    } + {s.back_because &&

    {s.back_because}

    }

    {s.reason}

    @@ -487,7 +545,7 @@ export function SuggestionBlock({
    - ))} @@ -516,9 +574,9 @@ export function SuggestionBlock({
    {why && ( -
    +

    - Why CoderHelm suggested this + Why CoderHelm suggested this as of {new Date(s.as_of).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}

      @@ -571,7 +629,7 @@ export function WithdrawnRow({ w, onOk }: { w: Withdrawn; onOk: () => void }) { export function SourceProblem({ name, detail }: { name: string; detail: string }) { return ( -

      +

      diff --git a/dashboard/src/app/foryou/plan.tsx b/dashboard/src/app/foryou/plan.tsx new file mode 100644 index 00000000..ad85fe72 --- /dev/null +++ b/dashboard/src/app/foryou/plan.tsx @@ -0,0 +1,234 @@ +"use client"; + +// A run's real plan, as its planner wrote it (GET /api/foryou/plan): the +// steps per repository with what is done, the files it names and its test +// steps. Two places use it: the plan a "Draft a plan first" run waits on +// (PlanSheet, with Approve and Change), and the step checklist under a run +// CoderHelm is doing for you (PlanSteps). + +import { useEffect, useState } from "react"; +import { Drawer } from "@/components/drawer"; +import { CheckIcon } from "@/components/icons"; +import { Problem } from "@/components/problem"; +import { Skeleton } from "@/components/skeleton"; +import { buttonClass, focusRing } from "@/components/ui"; +import { api, ApiError } from "@/lib/api"; +import { foryouApi, type RunPlan } from "@/lib/foryou"; +import { Mark } from "./parts"; + +function usePlan(run: string | null) { + const [plan, setPlan] = useState(null); + const [error, setError] = useState(null); + useEffect(() => { + setPlan(null); + setError(null); + if (!run) return; + let live = true; + foryouApi.plan(run).then( + (p) => live && setPlan(p), + (e) => live && setError(e instanceof ApiError && e.status === 404 ? "This run's plan can't be read here yet." : e instanceof ApiError ? e.message : String(e)), + ); + return () => { + live = false; + }; + }, [run]); + return { plan, error }; +} + +/** The steps, per repository, each ticked when done. */ +export function StepList({ plan, compact = false }: { plan: RunPlan["plan"]; compact?: boolean }) { + return ( +

      + {plan.repos.map((r) => ( +
      + {r.repo &&

      {r.repo}

      } +
        + {r.steps.map((s, i) => ( +
      1. + + + {s.done ? "Done: " : "To do: "} + {s.text} + {s.test && !compact && test} + +
      2. + ))} +
      +
      + ))} +
      + ); +} + +/** Under a run at work: "Steps 3 of 7", opened to the checklist. */ +export function PlanSteps({ run }: { run: string }) { + const [open, setOpen] = useState(false); + const { plan, error } = usePlan(open ? run : null); + return ( +
      + + {open && ( +
      + {!plan && !error && } + {error &&

      {error}

      } + {plan && !plan.ready &&

      CoderHelm is still writing the plan. Its steps show here once it is saved.

      } + {plan?.ready && ( + <> +

      + {plan.plan.done} of {plan.plan.total} steps done +

      + + + )} +
      + )} +
      + ); +} + +/** The plan a run waits on: read it, then approve it or say what to change. */ +export function PlanSheet({ run, onClose, onAnswered }: { run: string | null; onClose: () => void; onAnswered: (approved: boolean) => void }) { + const { plan, error } = usePlan(run); + const [changing, setChanging] = useState(false); + const [words, setWords] = useState(""); + const [busy, setBusy] = useState(false); + const [sendError, setSendError] = useState(null); + useEffect(() => { + setChanging(false); + setWords(""); + setSendError(null); + }, [run]); + + const send = async (approve: boolean) => { + if (!run || !plan?.awaiting_ok) return; + setBusy(true); + setSendError(null); + try { + const answer = approve ? plan.awaiting_ok.approve : `${plan.awaiting_ok.change}: ${words.trim()}`; + await api.answerRun(run, [{ question_id: plan.awaiting_ok.question_id, answer }]); + onAnswered(approve); + } catch (e) { + setSendError(e instanceof ApiError ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + + const waits = !!plan?.awaiting_ok; + return ( + !o && onClose()} + title={ + + {waits ? "The plan, for your OK" : "The plan"} + + } + description={plan?.ticket ? `${plan.ticket} · written by CoderHelm's planner, before any code` : "Written by CoderHelm's planner, before any code"} + testId="fy-plan-sheet" + footer={ + waits ? ( +
      + + {changing ? ( + + ) : ( + + )} +
      + ) : ( +
      + +
      + ) + } + > +
      + {!plan && !error && ( +
      + + + +
      + )} + {error && {error}} + {plan && !plan.ready &&

      CoderHelm is still writing the plan. It shows here once it is saved.

      } + {plan?.ready && ( + <> +
      +

      + Steps ({plan.plan.total}) +

      +
      + +
      +
      +
      +

      Repositories

      +

      + {plan.plan.repos.filter((r) => r.repo).map((r) => ( + + {r.repo} + + ))} +

      +
      + {plan.plan.files.length > 0 && ( +
      +

      Files it names

      +
        + {plan.plan.files.map((f) => ( +
      • + {f} +
      • + ))} +
      +
      + )} +
      +

      Tests

      + {plan.plan.tests.length ? ( +
        + {plan.plan.tests.map((t) => ( +
      • + {t} +
      • + ))} +
      + ) : ( +

      No step writes or runs tests.

      + )} +
      + {changing && ( +