diff --git a/dashboard/e2e/learning.spec.ts b/dashboard/e2e/learning.spec.ts index eeee0eb8..e3a413d1 100644 --- a/dashboard/e2e/learning.spec.ts +++ b/dashboard/e2e/learning.spec.ts @@ -1,7 +1,7 @@ import { expect, test, type Page, type Route } from "@playwright/test"; import fs from "node:fs"; import path from "node:path"; -import { learningFixture, learningHealthFixture } from "./wide-data/learning"; +import { learningFixture, learningHealthFixture, outcomeLessonsFixture, reviewerAsksFixture, scorecardFixture } from "./wide-data/learning"; import { pickOption } from "./select"; // The Learning page: what Coderhelm learned from outcomes, the behavior it @@ -24,10 +24,16 @@ interface Backend { calls: { method: string; path: string; body: unknown }[]; /** The health check's answer, or its error status; left out, a gateway without it (404). */ health?: unknown; + /** The scorecard, lessons and reviewer asks: "full", "empty", an error status, or left out for a gateway without them (404). */ + outcomes?: "full" | "empty" | number; + /** Reviewers and asks forgotten so far. */ + forgotten: Set; + /** The guide pull request setting as saved (on unless turned off). */ + guide: { enabled: boolean; repos: Record }; } async function mockApi(page: Page, init: Partial = {}): Promise { - const db: Backend = { role: "admin", canManage: true, empty: false, writeStatus: 200, reverted: new Set(), pinned: "", weights: {}, calls: [], ...init }; + const db: Backend = { role: "admin", canManage: true, empty: false, writeStatus: 200, reverted: new Set(), pinned: "", weights: {}, calls: [], forgotten: new Set(), guide: { enabled: true, repos: {} }, ...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()); @@ -52,9 +58,32 @@ async function mockApi(page: Page, init: Partial = {}): Promise { + const db = await mockApi(page, { outcomes: "full" }); + await page.goto("/learning"); + const card = page.getByTestId("scorecard"); + await expect(card).toBeVisible(); + await expect(page.getByTestId("score-opened")).toContainText("24"); + await expect(page.getByTestId("score-opened")).toContainText("4 still open"); + await expect(page.getByTestId("score-merged")).toContainText("16"); + await expect(page.getByTestId("score-merged")).toContainText("80% of the 20 that finished"); + await expect(page.getByTestId("score-closed")).toContainText("4"); + await expect(page.getByTestId("score-reverted")).toContainText("2"); + await expect(page.getByTestId("score-edited")).toContainText("25% of merged; 12 merged as written"); + await expect(page.getByTestId("score-open-items")).toContainText("3"); + await expect(page.getByTestId("score-rounds")).toContainText("0.6"); + await expect(page.getByTestId("score-rounds")).toContainText("11 of 16 passed with no changes asked"); + await expect(page.getByTestId("score-time")).toContainText("9.5 h"); + await expect(page.getByTestId("score-time")).toContainText("Half merged within 8 h"); + await expect(page.locator("#scorecard")).toContainText("Counting began in January 2026"); + // Each repository, and a rate with nothing behind it is said so, never a zero. + const repos = page.getByRole("table", { name: "Scorecard by repository" }); + await expect(repos.getByRole("row").filter({ hasText: REPO })).toContainText("12 (80%)"); + await expect(repos.getByRole("row").filter({ hasText: REPO_2 })).toContainText("No data yet"); + // Another period asks the gateway again. + await page.getByRole("group", { name: "Scorecard period" }).getByRole("button", { name: "All time" }).click(); + await expect.poll(() => db.calls.some((c) => c.path === "/api/learning/scorecard?months=0")).toBe(true); + // The page's repository filter narrows it, and the per-repository table goes. + await page.getByTestId("repo-filter").click(); + await page.getByTestId("combo-popover").getByRole("option", { name: REPO, exact: true }).first().click(); + await expect.poll(() => db.calls.some((c) => c.path.startsWith("/api/learning/scorecard") && c.path.includes(`repo=${encodeURIComponent(REPO)}`))).toBe(true); + await expect(page.getByTestId("score-opened")).toContainText("18"); + await expect(page.getByRole("table", { name: "Scorecard by repository" })).toHaveCount(0); +}); + +test("lessons say how they are checked, show their evidence, and name the guide pull request", async ({ page }) => { + await mockApi(page, { outcomes: "full" }); + await page.goto("/learning"); + const ready = page.getByTestId("lesson-les_ready"); + await expect(ready).toContainText("Build image addresses with the shared `imageUrl` helper"); + await expect(ready).toContainText("How it is checked: Search the diff under apps/web/src"); + await expect(ready).toContainText("seen on 2 pull requests (#12345, #12399)"); + await expect(ready).toContainText("In use"); + await expect(ready).toContainText("Seen often enough to be proposed for the guide file."); + await ready.getByText("Evidence (3 lines): people edited the pull request before merging").click(); + await expect(ready).toContainText('PR #12345 in people\'s words: "Use the shared image builder"'); + await expect(ready).toContainText("+ const src = imageUrl(p.image)"); + await expect(page.getByTestId("lesson-les_guide")).toContainText("In the guide file"); + const against = page.getByTestId("lesson-les_against"); + await expect(against).toContainText("Contradicted"); + await expect(against).toContainText("contradicted 2 times"); + await expect(against).toContainText("The team declined it for the guide file."); + // A lesson that only records what happened has no check and no evidence list. + await expect(page.getByTestId("lesson-les_area")).not.toContainText("How it is checked"); + const guide = page.getByTestId("guide-prs"); + await expect(guide).toContainText("proposes 1 lesson for AGENTS.md"); + await expect(guide).toContainText("Waiting for review"); + await expect(guide.getByRole("link", { name: `${REPO} #12400` })).toHaveAttribute("href", `https://github.com/${REPO}/pull/12400`); +}); + +test("an admin forgets one ask, then everything kept about a reviewer", async ({ page }) => { + const db = await mockApi(page, { outcomes: "full" }); + await page.goto("/learning"); + const reviewer = page.getByTestId("reviewer-a-reviewer"); + await expect(reviewer.getByTestId("ask-ask_tests")).toContainText("Add a test for the empty state of every new block."); + await expect(reviewer.getByTestId("ask-ask_tests")).toContainText("Tests · on 3 pull requests"); + await expect(reviewer.getByTestId("ask-ask_tests")).toContainText("In use"); + await expect(reviewer.getByTestId("ask-ask_errors")).toContainText("Error handling · on 1 pull request"); + await expect(reviewer.getByTestId("ask-ask_errors")).toContainText("Seen once"); + await expect(page.locator("#reviewers")).toContainText("nothing about the person"); + + await reviewer.getByRole("button", { name: /Forget this ask of a-reviewer: Return typed errors/ }).click(); + await page.getByRole("alertdialog").getByRole("button", { name: "Forget" }).click(); + await expect(page.getByTestId("ask-ask_errors")).toHaveCount(0); + expect(db.calls.find((c) => c.path === "/api/learning/reviewers/forget")?.body).toEqual({ login: "a-reviewer", id: "ask_errors" }); + + await reviewer.getByRole("button", { name: "Forget a-reviewer" }).click(); + await expect(page.getByRole("alertdialog")).toContainText("Every ask kept for a-reviewer is removed"); + await page.getByRole("alertdialog").getByRole("button", { name: "Forget" }).click(); + await expect(page.getByTestId("reviewer-a-reviewer")).toHaveCount(0); + await expect(page.getByTestId("reviewer-another-reviewer")).toBeVisible(); + expect(db.calls.filter((c) => c.path === "/api/learning/reviewers/forget").at(-1)?.body).toEqual({ login: "a-reviewer" }); +}); + +test("a member sees what reviewers ask for and cannot forget it", async ({ page }) => { + const db = await mockApi(page, { role: "member", canManage: false, outcomes: "full" }); + await page.goto("/learning"); + await expect(page.getByTestId("reviewer-a-reviewer")).toContainText("Add a test for the empty state"); + await expect(page.locator("#reviewers").getByRole("button", { name: /Forget/ })).toHaveCount(0); + expect(db.calls.filter((c) => c.method !== "GET")).toHaveLength(0); +}); + +test("a refused forget is said in words and nothing goes", async ({ page }) => { + await mockApi(page, { outcomes: "full", writeStatus: 403 }); + await page.goto("/learning"); + await page.getByTestId("reviewer-a-reviewer").getByRole("button", { name: "Forget a-reviewer" }).click(); + await page.getByRole("alertdialog").getByRole("button", { name: "Forget" }).click(); + await expect(page.locator("#reviewers").getByRole("alert")).toContainText("Only an admin or the owner can forget what was learned (error 403)"); + await expect(page.getByTestId("reviewer-a-reviewer")).toBeVisible(); +}); + +test("before anything is counted or learned, each section says what fills it", async ({ page }) => { + await mockApi(page, { outcomes: "empty" }); + await page.goto("/learning"); + await expect(page.getByTestId("scorecard-empty")).toContainText("The scorecard fills in as pull requests open, merge and close from now on."); + await expect(page.getByTestId("lessons-empty")).toContainText("No lessons yet"); + await expect(page.getByTestId("reviewers-empty")).toContainText("Nothing kept yet"); + await expect(page.getByTestId("guide-prs")).toHaveCount(0); +}); + +test("a gateway without the scorecard shows none of the three sections, and one that fails says so", async ({ page }) => { + await mockApi(page); + await page.goto("/learning"); + await expect(page.getByTestId("tile-events")).toBeVisible(); + for (const name of ["Pull request scorecard", "Lessons from pull requests", "What reviewers ask for"]) { + await expect(page.getByRole("heading", { name })).toHaveCount(0); + } + await mockApi(page, { outcomes: 500 }); + await page.goto("/learning"); + await expect(page.getByText("Couldn't load the scorecard")).toBeVisible(); + await expect(page.getByText("Couldn't load the lessons")).toBeVisible(); + await expect(page.getByText("Couldn't load what reviewers ask for")).toBeVisible(); + // The rest of the page still loads. + await expect(page.getByTestId("tile-events")).toBeVisible(); +}); + +test("the scorecard, lessons and reviewer asks fit a phone at 375 wide", async ({ page }) => { + await page.setViewportSize({ width: 375, height: 844 }); + await mockApi(page, { outcomes: "full" }); + await page.goto("/learning"); + await expect(page.getByTestId("scorecard")).toBeVisible(); + await page.getByTestId("lesson-les_ready").getByText(/Evidence \(3 lines\)/).click(); + await expect(page.getByTestId("reviewer-a-reviewer")).toBeVisible(); + await noSideways(page); + fs.mkdirSync(SHOTS_DIR, { recursive: true }); + for (const id of ["scorecard", "lessons", "reviewers"]) { + await page.locator(`#${id}`).screenshot({ path: path.join(SHOTS_DIR, `learning-${id}-phone.png`) }); + } +}); + +// ── The switch for guide pull requests ───────────────────────────────────── + +const guideSaves = (db: Backend) => db.calls.filter((c) => c.path === "/api/settings/guide-prs" && c.method === "PUT").map((c) => c.body); + +test("an admin turns guide pull requests off for the team, then on for one repository", async ({ page }) => { + const db = await mockApi(page, { outcomes: "full" }); + await page.goto("/learning"); + const team = page.getByTestId("guide-setting-team"); + const toggle = page.getByRole("switch", { name: "Open guide pull requests" }); + // On unless a team turns it off. + await expect(toggle).toBeChecked(); + await expect(team).toContainText("its lessons still go to every run"); + await expect(page.getByTestId("guide-setting-apart")).toContainText("Every repository follows this."); + await expect(team).not.toContainText("Not default"); + + await toggle.click(); + await expect(toggle).not.toBeChecked(); + await expect(team).toContainText("Not default"); + expect(guideSaves(db).at(-1)).toEqual({ enabled: false, repos: {} }); + + // One repository set apart: picked in the page's filter. + await page.getByTestId("repo-filter").click(); + await page.getByTestId("combo-popover").getByRole("option", { name: REPO, exact: true }).first().click(); + const row = page.getByTestId("guide-setting-repo"); + await expect(row).toContainText(`In ${REPO}`); + await expect(row).toContainText("Follows the team's setting: off."); + const choices = page.getByRole("group", { name: `Guide pull requests in ${REPO}` }); + await choices.getByRole("button", { name: "On", exact: true }).click(); + await expect(row).toContainText("guide pull requests are opened here"); + await expect(choices.getByRole("button", { name: "On", exact: true })).toHaveAttribute("aria-pressed", "true"); + expect(guideSaves(db).at(-1)).toEqual({ enabled: false, repos: { [REPO]: true } }); + // Back to the team's setting removes the override. + await choices.getByRole("button", { name: "Follow the team" }).click(); + await expect(row).toContainText("Follows the team's setting: off."); + expect(guideSaves(db).at(-1)).toEqual({ enabled: false, repos: {} }); +}); + +test("repositories set apart are named, and the setting survives a reload", async ({ page }) => { + await mockApi(page, { outcomes: "full", guide: { enabled: true, repos: { [REPO_2]: false } } }); + await page.goto("/learning"); + await expect(page.getByRole("switch", { name: "Open guide pull requests" })).toBeChecked(); + await expect(page.getByTestId("guide-setting-apart")).toContainText(`Set apart from the team: ${REPO_2} (off).`); +}); + +test("a member sees how guide pull requests are set and cannot change it", async ({ page }) => { + const db = await mockApi(page, { role: "member", canManage: false, outcomes: "full" }); + await page.goto("/learning"); + const toggle = page.getByRole("switch", { name: "Open guide pull requests" }); + await expect(toggle).toBeChecked(); + await expect(toggle).toBeDisabled(); + await expect(page.getByTestId("guide-setting-team")).toContainText("Only an admin or the owner can change this."); + await page.getByTestId("repo-filter").click(); + await page.getByTestId("combo-popover").getByRole("option", { name: REPO, exact: true }).first().click(); + await expect(page.getByRole("group", { name: `Guide pull requests in ${REPO}` }).getByRole("button", { name: "Off", exact: true })).toBeDisabled(); + expect(guideSaves(db)).toHaveLength(0); +}); + +test("a refused save of the guide setting is said in words and the switch stays", async ({ page }) => { + const db = await mockApi(page, { outcomes: "full", writeStatus: 403 }); + await page.goto("/learning"); + const toggle = page.getByRole("switch", { name: "Open guide pull requests" }); + await toggle.click(); + await expect(page.getByTestId("guide-setting").getByRole("alert")).toContainText("Only an admin or the owner can change it (error 403)"); + await expect(toggle).toBeChecked(); + expect(db.guide.enabled).toBe(true); +}); + +test("a gateway without the guide setting shows no switch, and the switch fits a phone", async ({ page }) => { + await mockApi(page, { outcomes: "full" }); + await page.route("**/api/settings/guide-prs", (route) => route.fulfill({ status: 404, contentType: "application/json", body: "{}" })); + await page.goto("/learning"); + await expect(page.getByTestId("lesson-les_ready")).toBeVisible(); + await expect(page.getByTestId("guide-setting")).toHaveCount(0); + + // The repository is picked at desktop width (the filter is the page's own, + // tested elsewhere), then the rows are looked at on a phone. + await page.unroute("**/api/settings/guide-prs"); + await page.goto("/learning"); + await page.getByTestId("repo-filter").click(); + await page.getByTestId("combo-popover").getByRole("option", { name: REPO, exact: true }).first().click(); + await expect(page.getByTestId("guide-setting-repo")).toBeVisible(); + await page.setViewportSize({ width: 375, height: 844 }); + await expect(page.getByTestId("guide-setting-repo")).toBeVisible(); + await noSideways(page); + fs.mkdirSync(SHOTS_DIR, { recursive: true }); + await page.getByTestId("guide-setting").screenshot({ path: path.join(SHOTS_DIR, "learning-guide-setting-phone.png") }); +}); diff --git a/dashboard/e2e/wide-data/learning.ts b/dashboard/e2e/wide-data/learning.ts index 4fabcb4e..aecd18c2 100644 --- a/dashboard/e2e/wide-data/learning.ts +++ b/dashboard/e2e/wide-data/learning.ts @@ -198,8 +198,101 @@ export function learningHealthFixture(o: { repo: string; text: string; quiet?: s return { window_days: 7, generated_at: iso(0), state: q.length ? "red" : "ok", quiet: q, loops }; } +/** One scope's numbers on GET /api/learning/scorecard (common::scorecard::row). */ +function scoreRow(opened: number, merged: number, closed: number, extra: Record = {}) { + const finished = merged + closed; + return { + opened, + merged, + closed_unmerged: closed, + open: opened - finished, + reverted: 1, + merge_rate: finished ? Math.round((merged / finished) * 1000) / 1000 : null, + revert_rate: merged ? Math.round((1 / merged) * 1000) / 1000 : null, + human_edited: 4, + human_edited_rate: merged ? Math.round((4 / merged) * 1000) / 1000 : null, + merged_as_written: Math.max(0, merged - 4), + open_items: 3, + open_items_rate: finished ? Math.round((3 / finished) * 1000) / 1000 : null, + reviewed: merged, + first_pass: Math.max(0, merged - 5), + avg_review_rounds: 0.6, + avg_hours_to_merge: 9.5, + median_hours_to_merge_at_most: 8, + median_past_hours: null, + ...extra, + }; +} + +/** GET /api/learning/scorecard: the team's counters and each repository's; `empty` is an install nothing was counted on yet. */ +export function scorecardFixture(o: { repo: string; repo2: string; months?: number; only?: string; empty?: boolean }) { + const none = { ...scoreRow(0, 0, 0), reverted: 0, human_edited: 0, merged_as_written: 0, open_items: 0, reviewed: 0, first_pass: 0, revert_rate: null, human_edited_rate: null, avg_review_rounds: null, avg_hours_to_merge: null, median_hours_to_merge_at_most: null }; + if (o.empty) return { months: o.months ?? 3, repo: o.only ?? "", since: null, team: none, repos: [], trend: [] }; + const a = { repo: o.repo, ...scoreRow(18, 12, 3) }; + const b = { repo: o.repo2, ...scoreRow(6, 4, 1, { avg_review_rounds: null, reviewed: 0, first_pass: 0 }) }; + const repos = o.only ? [a, b].filter((r) => r.repo === o.only) : [a, b]; + const team = o.only ? scoreRow(repos[0]?.opened ?? 0, repos[0]?.merged ?? 0, repos[0]?.closed_unmerged ?? 0) : { ...scoreRow(24, 16, 4), reverted: 2 }; + return { months: o.months ?? 3, repo: o.only ?? "", since: "2026-01", team, repos, trend: [{ month: "2026-01", ...scoreRow(24, 16, 4) }] }; +} + +/** GET /api/learning/lessons: one lesson in each state, and a guide pull request waiting for review. */ +export function outcomeLessonsFixture(o: { repo: string; text: string; file: string; empty?: boolean }) { + if (o.empty) return { lessons: [], guide_prs: [], guide_min_seen: 2 }; + const lesson = (id: string, status: string, extra: Record = {}) => ({ + id, + repo: o.repo, + text: `Build image addresses with the shared \`imageUrl\` helper, never from \`image.asset.url\`. ${o.text}`.trim(), + check: `Search the diff under ${o.file || "apps/web/src"} for \`asset.url\`: there should be none.`, + applies_to: "apps/web", + source: "edited", + seen: 2, + contradicted: 0, + prs: [`${o.repo}#12345`, `${o.repo}#12399`], + evidence: [ + "PR #12345: people edited it before merging (`apps/web/src/blocks/card.tsx`)", + `PR #12345 in people's words: "Use the shared image builder" ${o.text}`.trim(), + "PR #12345 people's change:\napps/web/src/blocks/card.tsx\n- const src = p.image.asset.url\n+ const src = imageUrl(p.image)", + ], + created_at: iso(20 * DAY), + last_seen_at: iso(2 * DAY), + status, + guide_declined: false, + guide_ready: status === "recalled", + ...extra, + }); + return { + lessons: [ + lesson("les_ready", "recalled"), + lesson("les_guide", "in_guide", { text: "Name migration files `NNNN_what.sql`.", check: "The new file under `db/migrations` starts with four digits.", source: "closed", seen: 3 }), + lesson("les_against", "contradicted", { text: "Keep feature flags in `flags.ts`.", contradicted: 2, guide_declined: true }), + lesson("les_area", "recalled", { text: "In `apps/web`: PR #12001 was closed without merging.", check: "", source: "", guide_ready: false, evidence: [] }), + ], + guide_prs: [{ repo: o.repo, pr: 12400, url: `https://github.com/${o.repo}/pull/12400`, state: "open", path: "AGENTS.md", lessons: 1, at: iso(DAY) }], + guide_min_seen: 2, + }; +} + +/** GET /api/learning/reviewers: one reviewer with an ask in use and one seen once, and a second reviewer. */ +export function reviewerAsksFixture(o: { repo: string; text: string; canManage: boolean; forgotten?: Set; empty?: boolean }) { + const gone = o.forgotten ?? new Set(); + if (o.empty) return { min_seen: 2, can_manage: o.canManage, reviewers: [] }; + const ask = (id: string, text: string, category: string, seen: number) => ({ id, text, category, seen, prs: Array.from({ length: seen }, (_, i) => `${o.repo}#${12345 + i}`), last_seen_at: iso(2 * DAY), given: seen >= 2 }); + const reviewers = [ + { login: "a-reviewer", asks: [ask("ask_tests", `Add a test for the empty state of every new block. ${o.text}`.trim(), "tests", 3), ask("ask_errors", "Return typed errors from the client layer", "error_handling", 1)] }, + { login: "another-reviewer", asks: [ask("ask_names", "Name handlers after the route they serve", "naming", 2)] }, + ] + .filter((r) => !gone.has(r.login)) + .map((r) => ({ ...r, asks: r.asks.filter((a) => !gone.has(a.id)) })); + return { min_seen: 2, can_manage: o.canManage, reviewers }; +} + export const learningData: Handler = ({ method, path }) => { if (path === "/api/learning/health" && method === "GET") return learningHealthFixture({ repo: REPO, text: `${SENTENCE} ${TOKEN}` }); + if (path === "/api/learning/scorecard" && method === "GET") return scorecardFixture({ repo: REPO, repo2: REPO_2 }); + if (path === "/api/learning/lessons" && method === "GET") return outcomeLessonsFixture({ repo: REPO, text: `${SENTENCE} ${TOKEN}`, file: FILE }); + if (path === "/api/learning/reviewers" && method === "GET") return reviewerAsksFixture({ repo: REPO, text: `${SENTENCE} ${TOKEN}`, canManage: true }); + if (path === "/api/learning/reviewers/forget" && method === "POST") return { forgotten: 1 }; + if (path === "/api/settings/guide-prs") return { enabled: true, repos: { [REPO_2]: false }, can_manage: true }; if (path === "/api/learning" && method === "GET") { return learningFixture({ repo: REPO, repo2: REPO_2, text: `${TITLE} ${SENTENCE} ${TOKEN}`, file: FILE, canManage: true }); } diff --git a/dashboard/src/app/learning/outcomes.tsx b/dashboard/src/app/learning/outcomes.tsx new file mode 100644 index 00000000..8101cc1f --- /dev/null +++ b/dashboard/src/app/learning/outcomes.tsx @@ -0,0 +1,528 @@ +"use client"; + +import { useCallback, useEffect, useState, type ReactNode } from "react"; +import { + api, + errorStatus, + type GuideSetting, + type OutcomeLesson, + type OutcomeLessons, + type ReviewerAsks, + type Scorecard, + type ScorecardRow, +} from "@/lib/api"; +import { Callout } from "@/components/callout"; +import { useConfirm } from "@/components/confirm-dialog"; +import { DataTable, type Column } from "@/components/data-table"; +import { Disclosure } from "@/components/disclosure"; +import { ListSkeleton, Time } from "@/components/list"; +import { cardClass, Section } from "@/components/page"; +import { Segmented } from "@/components/segmented"; +import { SettingsRow, Switch } from "@/components/settings"; +import { StatGrid, StatTile } from "@/components/stat-tile"; +import { StatusPill } from "@/components/status-pill"; +import { smallSecondaryButton } from "@/components/ui"; + +// What became of the pull requests Coderhelm opened (the scorecard), the +// lessons it took from what people did with them, and what each reviewer +// keeps asking for. Three sections of the Learning page, each loading by +// itself; a gateway from before them has no such routes and they show +// nothing. + +const count = (v: number) => v.toLocaleString(); +const pct = (v: number | null) => (v === null ? "No data yet" : `${Math.round(v * 100)}%`); +const plural = (n: number, one: string, many = `${one}s`) => `${count(n)} ${n === 1 ? one : many}`; +const emptyBox = "rounded-lg border border-zinc-800 bg-zinc-900/50 p-4 text-sm text-zinc-400"; + +/** "2026-11" reads "November 2026". */ +function monthWords(month: string): string { + const d = new Date(`${month}-01T00:00:00Z`); + return Number.isNaN(d.getTime()) ? month : d.toLocaleDateString(undefined, { month: "long", year: "numeric", timeZone: "UTC" }); +} + +function hours(h: number | null): string { + if (h === null) return "No data yet"; + if (h < 1) return `${Math.max(1, Math.round(h * 60))} min`; + if (h < 48) return `${h.toLocaleString(undefined, { maximumFractionDigits: 1 })} h`; + return `${(h / 24).toLocaleString(undefined, { maximumFractionDigits: 1 })} days`; +} + +/** The median as the counters know it: the span it falls in, never an invented number. */ +function medianWords(r: ScorecardRow): string | undefined { + if (r.median_hours_to_merge_at_most !== null) return `Half merged within ${hours(r.median_hours_to_merge_at_most)}`; + if (r.median_past_hours !== null) return `Half took longer than ${hours(r.median_past_hours)}`; + return undefined; +} + +/** A route this gateway doesn't have, or an answer without the fields: the section shows nothing. */ +function useSection(fetcher: () => Promise, ok: (v: T) => boolean) { + const [data, setData] = useState(null); + const [error, setError] = useState(""); + const [gone, setGone] = useState(false); + const [loading, setLoading] = useState(true); + const load = useCallback(async () => { + setError(""); + setLoading(true); + try { + const v = await fetcher(); + if (ok(v)) setData(v); + else setGone(true); + } catch (e) { + if (errorStatus(e) === 404) setGone(true); + else setError(e instanceof Error ? e.message : "The request failed."); + } finally { + setLoading(false); + } + }, [fetcher, ok]); + useEffect(() => { + void load(); + }, [load]); + return { data, error, gone, loading, load }; +} + +function LoadProblem({ title, error, onRetry }: { title: string; error: string; onRetry: () => void }) { + return ( + + Try again + + } + > +

{error}

+
+ ); +} + +// ── Scorecard ────────────────────────────────────────────────────────────── + +const WINDOWS = [ + { value: "1", label: "This month" }, + { value: "3", label: "3 months" }, + { value: "12", label: "12 months" }, + { value: "0", label: "All time" }, +] as const; +type Span = (typeof WINDOWS)[number]["value"]; + +const isScorecard = (v: Scorecard) => !!v && typeof v.team === "object" && v.team !== null && Array.isArray(v.repos); + +type RepoRow = ScorecardRow & { repo: string }; + +const REPO_COLUMNS: Column[] = [ + { key: "repo", header: "Repository", width: "grow", cell: (r) => {r.repo} }, + { key: "opened", header: "Opened", width: "fit", align: "right", cell: (r) => count(r.opened) }, + { key: "merged", header: "Merged", width: "fit", align: "right", cell: (r) => `${count(r.merged)}${r.merge_rate === null ? "" : ` (${pct(r.merge_rate)})`}` }, + { key: "closed", header: "Closed", width: "fit", align: "right", cell: (r) => count(r.closed_unmerged) }, + { key: "reverted", header: "Reverted", width: "fit", align: "right", cell: (r) => count(r.reverted) }, + { key: "edited", header: "Needed a commit", width: "fit", align: "right", cell: (r) => count(r.human_edited) }, + { key: "items", header: "Open items", width: "fit", align: "right", cell: (r) => count(r.open_items) }, + { key: "rounds", header: "Review rounds", width: "fit", align: "right", cell: (r) => (r.avg_review_rounds === null ? "No data yet" : r.avg_review_rounds.toLocaleString()) }, + { key: "time", header: "Time to merge", width: "fit", align: "right", cell: (r) => hours(r.avg_hours_to_merge) }, +]; + +/** What became of the pull requests Coderhelm opened, for the team and each repository. */ +export function ScorecardSection({ repo }: { repo: string }) { + const [span, setSpan] = useState("3"); + const fetcher = useCallback(() => api.getScorecard(Number(span), repo || undefined), [span, repo]); + const { data, error, gone, loading, load } = useSection(fetcher, isScorecard); + if (gone) return null; + const t = data?.team; + const period = span === "0" ? "since counting began" : span === "1" ? "opened this month" : `opened in the last ${span} months`; + return ( +
+ What became of the pull requests Coderhelm opened, counted as each one is merged, closed, reviewed or reverted. A pull request counts in the month it was opened. + {data?.since ? ` Counting began in ${monthWords(data.since)}; pull requests opened before that are not included.` : ""} + + } + actions={} + > + {error ? ( + void load()} /> + ) : !data || !t ? ( + + ) : t.opened === 0 ? ( +

+ No pull request from Coderhelm has been counted {period} + {repo ? ` in ${repo}` : ""}. The scorecard fills in as pull requests open, merge and close from now on. +

+ ) : ( +
+ + + + 0 ? "warning" : "neutral"} /> + 0 ? "danger" : "neutral"} + note={t.revert_rate === null ? undefined : `${pct(t.revert_rate)} of merged`} + /> + + + + + + {!repo && data.repos.length > 0 && ( +
+
+ r.repo} /> +
+
+ )} +
+ )} +
+ ); +} + +// ── Lessons from outcomes ────────────────────────────────────────────────── + +const isLessons = (v: OutcomeLessons) => !!v && Array.isArray(v.lessons) && Array.isArray(v.guide_prs); + +const SOURCE: Record = { + edited: "People edited the pull request before merging", + closed: "A pull request was closed without merging", + reverted: "A merged change was reverted", +}; + +const STATUS: Record = { + recalled: { label: "In use", tone: "success", says: "Given to every run in this repository." }, + in_guide: { label: "In the guide file", tone: "success", says: "The team merged it into the repository's guide file, which every run reads." }, + contradicted: { label: "Contradicted", tone: "warning", says: "Later pull requests went against it, so it is no longer given to runs." }, + faded: { label: "Faded", tone: "neutral", says: "Not seen again for a long time, so it is no longer given to runs." }, + off: { label: "Turned off", tone: "neutral", says: "An admin turned it off under What changed and why." }, +}; + +const GUIDE_STATE: Record = { + open: { label: "Waiting for review", tone: "warning" }, + merged: { label: "Merged", tone: "success" }, + declined: { label: "Closed without merging", tone: "neutral" }, +}; + +/** "acme/web#12" reads "#12" inside its own repository's card. */ +const prWords = (key: string, repo: string) => (key.startsWith(`${repo}#`) ? `#${key.slice(repo.length + 1)}` : key); + +function LessonCard({ l }: { l: OutcomeLesson }) { + const status = STATUS[l.status] ?? { label: l.status, tone: "neutral" as const, says: "" }; + return ( +
  • +
    +

    {l.text}

    + {status.label} +
    + {l.check && ( +

    + How it is checked: + {l.check} +

    + )} +

    + {l.repo} + {l.applies_to ? ` · ${l.applies_to}` : ""} · seen on {plural(l.seen, "pull request")} + {l.prs.length > 0 ? ` (${l.prs.map((p) => prWords(p, l.repo)).join(", ")})` : ""} + {l.contradicted > 0 ? ` · contradicted ${plural(l.contradicted, "time")}` : ""} + {l.last_seen_at ? " · last seen " : ""} + {l.last_seen_at &&

    +

    + {status.says} + {l.guide_ready ? " Seen often enough to be proposed for the guide file." : ""} + {l.guide_declined ? " The team declined it for the guide file." : ""} +

    + {l.evidence.length > 0 && ( +
    + +
      + {l.evidence.map((e, i) => ( +
    • + {e} +
    • + ))} +
    +
    +
    + )} +
  • + ); +} + +// ── The switch for guide pull requests ───────────────────────────────────── + +const isGuideSetting = (v: GuideSetting) => !!v && typeof v.enabled === "boolean" && typeof v.repos === "object" && v.repos !== null; + +const REPO_CHOICES = [ + { value: "team", label: "Follow the team" }, + { value: "on", label: "On" }, + { value: "off", label: "Off" }, +] as const; +type RepoChoice = (typeof REPO_CHOICES)[number]["value"]; + +/** + * Whether Coderhelm may open guide pull requests: one switch for the team, + * and, with a repository picked in the page's filter, that repository's own + * setting. Each change is saved at once. Everyone sees how it is set; only + * an admin can change it. + */ +function GuidePrSetting({ repo, canManage }: { repo: string; canManage: boolean }) { + const fetcher = useCallback(() => api.getGuideSetting(), []); + const { data, error, gone, load } = useSection(fetcher, isGuideSetting); + const [saved, setSaved] = useState(null); + const [busy, setBusy] = useState(false); + const [problem, setProblem] = useState(""); + if (gone) return null; + if (error) return void load()} />; + const setting = saved ?? data; + if (!setting) return null; + + const save = async (next: { enabled: boolean; repos: Record }) => { + setBusy(true); + setProblem(""); + try { + setSaved(await api.putGuideSetting(next)); + } catch (e) { + setProblem(errorStatus(e) === 403 ? "Your role does not allow this. Only an admin or the owner can change it (error 403)." : e instanceof Error ? e.message : "The request failed."); + } finally { + setBusy(false); + } + }; + const choice: RepoChoice = repo in setting.repos ? (setting.repos[repo] ? "on" : "off") : "team"; + const setRepo = (c: RepoChoice) => { + const repos = { ...setting.repos }; + if (c === "team") delete repos[repo]; + else repos[repo] = c === "on"; + void save({ enabled: setting.enabled, repos }); + }; + const apart = Object.entries(setting.repos).sort(([a], [b]) => a.localeCompare(b)); + const cannot = canManage ? undefined : "Only an admin or the owner can change this."; + + return ( +
    + + When a lesson has been seen on several pull requests, Coderhelm proposes it for the repository's guide file as a pull request for the team to review. Off, Coderhelm writes nothing to any repository for this; its lessons still go to every run. + {cannot ? ` ${cannot}` : ""} + + } + control={(ids) => ( + void save({ enabled: on, repos: setting.repos })} labelledBy={ids.labelId} describedBy={ids.helpId} testId="guide-switch" /> + )} + /> + {repo ? ( + } + /> + ) : ( +

    + {apart.length === 0 + ? "Every repository follows this. To set one apart, pick it in the repository filter at the top." + : `Set apart from the team: ${apart.map(([r, on]) => `${r} (${on ? "on" : "off"})`).join(", ")}. To change one, pick it in the repository filter at the top.`} +

    + )} + {problem && ( +
    + +

    {problem}

    +
    +
    + )} +
    + ); +} + +/** The coding agent's lessons from what people did with its pull requests, and the guide pull requests that propose them. */ +export function OutcomeLessonsSection({ repo, canManage }: { repo: string; canManage: boolean }) { + const fetcher = useCallback(() => api.getOutcomeLessons(repo || undefined), [repo]); + const { data, error, gone, load } = useSection(fetcher, isLessons); + if (gone) return null; + return ( +
    + {error ? ( + void load()} /> + ) : !data ? ( + + ) : ( +
    + + {data.guide_prs.length > 0 && ( +
      + {data.guide_prs.map((g) => { + const state = GUIDE_STATE[g.state] ?? { label: g.state, tone: "neutral" as const }; + return ( +
    • +

      + Guide pull request{" "} + + {g.repo} #{g.pr} + {" "} + proposes {plural(g.lessons, "lesson")} for {g.path || "the guide file"}. +

      + {state.label} +
    • + ); + })} +
    + )} + {data.lessons.length === 0 ? ( +

    + No lessons yet{repo ? ` in ${repo}` : ""}. One is written when people edit one of Coderhelm's pull requests before merging it, close one with a comment, or revert one and say why. +

    + ) : ( +
      + {data.lessons.map((l) => ( + + ))} +
    + )} +
    + )} +
    + ); +} + +// ── What reviewers ask for ───────────────────────────────────────────────── + +const isAsks = (v: ReviewerAsks) => !!v && Array.isArray(v.reviewers); + +const CATEGORY: Record = { + error_handling: "Error handling", + api: "API", +}; +const categoryWords = (c: string) => CATEGORY[c] ?? `${c.charAt(0).toUpperCase()}${c.slice(1).replace(/_/g, " ")}`; + +/** What each reviewer repeatedly asks for on Coderhelm's pull requests, with a way to forget it. */ +export function ReviewerAsksSection({ canManage }: { canManage: boolean }) { + const fetcher = useCallback(() => api.getReviewerAsks(), []); + const { data, error, gone, load } = useSection(fetcher, isAsks); + const [busy, setBusy] = useState(false); + const [problem, setProblem] = useState(null); + const { confirm } = useConfirm(); + if (gone) return null; + + const forget = async (login: string, id?: string) => { + const ok = await confirm({ + title: id ? "Forget this ask?" : `Forget everything kept about ${login}?`, + message: id + ? "Coderhelm stops applying it. It is kept again only if the reviewer asks for it on later pull requests." + : `Every ask kept for ${login} is removed, and where they reviewed. Coderhelm learns them again only from later pull requests.`, + confirmLabel: "Forget", + destructive: true, + }); + if (ok !== "primary") return; + setBusy(true); + setProblem(null); + try { + await api.forgetReviewer(login, id); + await load(); + } catch (e) { + setProblem(errorStatus(e) === 403 ? "Your role does not allow this. Only an admin or the owner can forget what was learned (error 403)." : e instanceof Error ? e.message : "The request failed."); + } finally { + setBusy(false); + } + }; + + return ( +
    + {error ? ( + void load()} /> + ) : !data ? ( + + ) : data.reviewers.length === 0 ? ( +

    + Nothing kept yet. Asks are learned when people review Coderhelm's pull requests. +

    + ) : ( +
    + {problem && ( + +

    {problem}

    +
    + )} +
      + {data.reviewers.map((r) => ( +
    • +
      +

      {r.login}

      + {canManage && ( + + )} +
      +
        + {r.asks.map((a) => ( +
      • +
        +

        {a.text}

        + {a.given ? "In use" : "Seen once"} +
        +
        +

        + {categoryWords(a.category)} · on {plural(a.seen, "pull request")} + {a.prs.length > 0 ? ` (${a.prs.join(", ")})` : ""} +

        + {canManage && ( + + )} +
        +
      • + ))} +
      +
    • + ))} +
    +
    + )} +
    + ); +} diff --git a/dashboard/src/app/learning/page.tsx b/dashboard/src/app/learning/page.tsx index a894ad10..8eed97ff 100644 --- a/dashboard/src/app/learning/page.tsx +++ b/dashboard/src/app/learning/page.tsx @@ -13,6 +13,7 @@ import { import { CardSkeleton, ChartSkeleton } from "@/components/skeleton"; import { Examples } from "./examples"; import { LearningHealthSection } from "./health"; +import { OutcomeLessonsSection, ReviewerAsksSection, ScorecardSection } from "./outcomes"; import { StatGrid, StatTile } from "@/components/stat-tile"; import { DataTable, type Column } from "@/components/data-table"; import { Problem } from "@/components/problem"; @@ -593,6 +594,8 @@ export default function LearningPage() { + + {error ? (
    void load()} details={error}> @@ -704,6 +707,9 @@ export default function LearningPage() { )} + + +
    ) => request<{ weights: Record }>("/api/learning/weights", { method: "PUT", body: JSON.stringify({ weights }) }), + /** What became of the pull requests Coderhelm opened, per team and per repository. `months` 0 is all time. */ + getScorecard: (months: number, repo?: string) => + request(`/api/learning/scorecard?months=${months}${repo ? `&repo=${encodeURIComponent(repo)}` : ""}`), + /** The coding agent's lessons with their evidence, and each repository's guide pull request. */ + getOutcomeLessons: (repo?: string) => + request(`/api/learning/lessons${repo ? `?repo=${encodeURIComponent(repo)}` : ""}`), + /** What each reviewer repeatedly asks for on Coderhelm's pull requests. */ + getReviewerAsks: () => request("/api/learning/reviewers"), + /** Whether Coderhelm may open guide pull requests: for the team, and per repository set apart. */ + getGuideSetting: () => request("/api/settings/guide-prs"), + /** Save it (admin). The whole setting is sent. */ + putGuideSetting: (setting: { enabled: boolean; repos: Record }) => + request("/api/settings/guide-prs", { method: "PUT", body: JSON.stringify(setting) }), + /** Forget one ask, or everything kept about a reviewer (admin). */ + forgetReviewer: (login: string, id?: string) => + request<{ forgotten: number }>("/api/learning/reviewers/forget", { method: "POST", body: JSON.stringify(id ? { login, id } : { login }) }), // GitHub App installation getInstallationStatus: () => @@ -4815,6 +4831,114 @@ export interface LearningHealth { loops: LearningLoop[]; } +/** One scope's numbers on the scorecard. A rate or an average is `null` when nothing is behind it. */ +export interface ScorecardRow { + opened: number; + merged: number; + closed_unmerged: number; + open: number; + reverted: number; + /** Merged out of merged plus closed. */ + merge_rate: number | null; + revert_rate: number | null; + /** Merged after a person pushed a commit on top. */ + human_edited: number; + human_edited_rate: number | null; + merged_as_written: number; + /** Finished with open or deferred items in the description. */ + open_items: number; + open_items_rate: number | null; + /** Pull requests whose review rounds are known (approved, or merged). */ + reviewed: number; + /** Approved or merged with no request for changes. */ + first_pass: number; + avg_review_rounds: number | null; + avg_hours_to_merge: number | null; + /** The median merge took at most this many hours. */ + median_hours_to_merge_at_most: number | null; + /** Set when the median is past the longest span that is counted. */ + median_past_hours: number | null; +} + +/** GET /api/learning/scorecard. */ +export interface Scorecard { + months: number; + repo: string; + /** The first month anything was counted (`2026-11`), or null when nothing was. */ + since: string | null; + team: ScorecardRow; + repos: (ScorecardRow & { repo: string })[]; + trend: (ScorecardRow & { month: string })[]; +} + +/** A lesson the coding agent learned from what people did with a pull request. */ +export interface OutcomeLesson { + id: string; + repo: string; + text: string; + /** How to check a change against it; empty for a lesson that only records what happened. */ + check: string; + applies_to: string; + /** `edited`, `closed`, `reverted`, or empty. */ + source: string; + seen: number; + contradicted: number; + /** `owner/name#12`. */ + prs: string[]; + evidence: string[]; + created_at: string; + last_seen_at: string; + /** `recalled` (given to runs), `in_guide`, `contradicted`, `faded` or `off`. */ + status: string; + guide_declined: boolean; + guide_ready: boolean; +} + +export interface GuidePr { + repo: string; + pr: number; + url: string; + /** `open`, `merged` or `declined`. */ + state: string; + path: string; + lessons: number; + at: string; +} + +/** GET /api/learning/lessons. */ +export interface OutcomeLessons { + lessons: OutcomeLesson[]; + guide_prs: GuidePr[]; + guide_min_seen: number; +} + +export interface ReviewerAsk { + id: string; + text: string; + category: string; + seen: number; + prs: string[]; + last_seen_at: string; + /** Seen often and recently enough to be given to the agents. */ + given: boolean; +} + +/** GET and PUT /api/settings/guide-prs. On unless turned off. */ +export interface GuideSetting { + /** For every repository that is not set apart. */ + enabled: boolean; + /** `owner/name` to on or off, for the repositories set apart from the team. */ + repos: Record; + can_manage?: boolean; +} + +/** GET /api/learning/reviewers. */ +export interface ReviewerAsks { + min_seen: number; + can_manage?: boolean; + reviewers: { login: string; asks: ReviewerAsk[] }[]; +} + // ── This install (self-hosted) ────────────────────────────────────────── export interface AutoUpdateSettings { diff --git a/dashboard/src/lib/routes.ts b/dashboard/src/lib/routes.ts index 64a7fc25..602c5a6f 100644 --- a/dashboard/src/lib/routes.ts +++ b/dashboard/src/lib/routes.ts @@ -63,7 +63,7 @@ export const ROUTES: Record = { "/data-sources/tools/tool": { label: "Tool", parent: "/data-sources/tools", detail: true, description: "One team tool: what it does, its settings and its recent calls." }, "/analytics": { label: "Analytics", description: "How Coderhelm is doing for your team: runs, merged pull requests, time saved and token use." }, - "/learning": { label: "Learning", description: "How people answered the reviewer's comments, and the changes in its behavior that came from those answers." }, + "/learning": { label: "Learning", description: "What became of Coderhelm's pull requests, how people answered the reviewer's comments, and the lessons and changes in behavior that came from both." }, "/infrastructure": { label: "Infrastructure", description: "The cloud resources Coderhelm can see, and what changed in them." }, "/alerts": { label: "Alerts", description: "Alerts Coderhelm picked up from your monitoring, and what it did about each one." }, "/alerts/detail": { label: "Alert", parent: "/alerts", detail: true, description: "One alert: when it fired, what Coderhelm found and the fix it proposed." },