From dfd48588893353e0b4e98a3de1b57048814e846d Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 27 Oct 2026 13:50:48 -0400 Subject: [PATCH] Learning: examples as a compact list with a detail panel "Examples in use" printed every example as a card with its whole excerpt, in two tall columns, raw markup included. It is now one list: a row per example (clean title, why it is an example, kind/category/path tags, repo and PR link, reward and use chips), To follow / To avoid toggles with counts, search, repository and kind filters, most used first, ten at a time. A row opens the example in a side panel (full screen on a phone) with the rendered summary, PR and run links, reward, use count, when it was last used and by which runs. Older gateways that send only `text` are read the same way. --- dashboard/e2e/learning.spec.ts | 155 ++++++++- dashboard/e2e/wide-data/learning.ts | 49 ++- dashboard/src/app/learning/examples.tsx | 413 ++++++++++++++++++++++++ dashboard/src/app/learning/page.tsx | 47 +-- dashboard/src/components/drawer.tsx | 15 +- dashboard/src/lib/api.ts | 21 ++ 6 files changed, 648 insertions(+), 52 deletions(-) create mode 100644 dashboard/src/app/learning/examples.tsx diff --git a/dashboard/e2e/learning.spec.ts b/dashboard/e2e/learning.spec.ts index e8e03467..a03ba7d3 100644 --- a/dashboard/e2e/learning.spec.ts +++ b/dashboard/e2e/learning.spec.ts @@ -109,7 +109,7 @@ test("shows rewards, categories, changes with evidence, examples and variants", await expect(style).toContainText("PR #12345"); await expect(page.locator("#exemplars")).toContainText("To follow"); - await expect(page.locator("#exemplars")).toContainText("Ask for a test of the retry path"); + await expect(page.getByTestId("example-ex1")).toContainText("Ask for a test of the retry path"); await expect(page.getByTestId("bandit-reviewer")).toContainText("Gathering outcomes"); // Scoring rules fold away under Advanced. await expect(page.getByRole("table", { name: "Signal weights" })).toBeHidden(); @@ -256,6 +256,8 @@ test("with no outcomes yet it says what it needs", async ({ page }) => { await expect(page.getByText("Nothing learned yet")).toBeVisible(); await expect(page.getByText(/needs 8 outcomes in a repository before anything changes/)).toBeVisible(); await expect(page.getByText(/No changes yet/)).toBeVisible(); + await expect(page.locator("#exemplars").getByText("No examples yet")).toBeVisible(); + await expect(page.getByRole("group", { name: "Show examples" })).toHaveCount(0); await expect(page.getByTestId("reward-chart")).toHaveCount(0); }); @@ -286,3 +288,154 @@ test("fits a phone without sideways scroll, and pictures at both widths", async await page.screenshot({ path: path.join(SHOTS_DIR, `learning-${width > 500 ? "desktop" : "phone"}.png`), fullPage: true }); } }); + +// ── Examples in use ────────────────────────────────────────────────────── + +test("examples are one compact row each, most used first, ten at a time", async ({ page }) => { + await mockApi(page); + await page.goto("/learning"); + const section = page.locator("#exemplars"); + const toggles = section.getByRole("group", { name: "Show examples" }); + await expect(toggles.getByRole("button", { name: /To follow/ })).toHaveAttribute("aria-pressed", "true"); + await expect(toggles.getByRole("button", { name: /To follow/ })).toContainText("13"); + await expect(toggles.getByRole("button", { name: /To avoid/ })).toContainText("2"); + + const list = section.getByRole("list", { name: "Examples to follow" }); + const rows = list.getByRole("listitem"); + await expect(rows).toHaveCount(10); + // Most used first: 6 uses, then 4, then the rest by reward. + await expect(rows.nth(0)).toHaveAttribute("data-testid", "example-ex2"); + await expect(rows.nth(1)).toHaveAttribute("data-testid", "example-ex1"); + await expect(rows.nth(2)).toContainText("step 11"); + + // A row: title, reason, kind and path tags, repo with the PR link, reward and uses. + const ex2 = page.getByTestId("example-ex2"); + await expect(ex2).toContainText("Retry the import once with the same key"); + await expect(ex2.getByTestId("example-reason")).toHaveText("CI passed on the first try, merged without changes"); + await expect(ex2).toContainText("Code change"); + await expect(ex2).toContainText("services/payments"); + await expect(ex2.getByRole("link", { name: /#12340/ })).toHaveAttribute("href", `https://github.com/${REPO_2}/pull/12340`); + await expect(ex2).toContainText("+1.50"); + await expect(ex2).toContainText("6×"); + // The summary waits for the panel: no long text in the list. + await expect(ex2).not.toContainText("idempotency key"); + await expect(section).toContainText("Showing 10 of 13, most used first"); + + await section.getByRole("button", { name: "Show 3 more" }).click(); + await expect(rows).toHaveCount(13); + await expect(section.getByRole("button", { name: /Show \d+ more/ })).toHaveCount(0); + await noSideways(page); +}); + +test("examples to avoid read clean, even ones kept with GitHub markup", async ({ page }) => { + await mockApi(page); + await page.goto("/learning"); + const section = page.locator("#exemplars"); + await section.getByRole("group", { name: "Show examples" }).getByRole("button", { name: /To avoid/ }).click(); + const list = section.getByRole("list", { name: "Examples to avoid" }); + await expect(list.getByRole("listitem")).toHaveCount(2); + const legacy = page.getByTestId("example-ex_legacy"); + await expect(legacy.getByRole("button")).toHaveText("fix(checkout): cache the cart"); + await expect(legacy.getByTestId("example-reason")).toHaveText("Closed, rewritten or reverted"); + for (const raw of ["\n> [!WARNING]\n> **Not yet verified**\n\n\n## Summary\n**Summary** Cache the cart for five minutes.", + reward: -1.8, uses: 1, created_at: iso(9 * DAY), pr: 12301, + }, + ]; + // More to follow than one page holds, so "Show more" has work to do. + const more = Array.from({ length: 11 }, (_, i) => ({ + id: `exm${i}`, repo: i % 2 ? o.repo2 : o.repo, kind: i % 3 ? "finding" : "fix", polarity: "good", category: i % 3 ? "correctness" : "", area: `src/module${i}`, + title: `Check the return value of step ${i + 1}`, summary: `Step ${i + 1} can fail quietly; the comment asked for the error to be returned.`, + reason: i % 3 ? "The author changed the code it pointed at" : "Merged after people changed 20% of it", text: `Check the return value of step ${i + 1}`, + reward: 1 + i / 10, events: 1, uses: i % 4 === 0 ? 0 : 1, created_at: iso((10 + i) * DAY), pr: 12200 + i, + })); + return [...base, ...more]; +} + export const learningData: Handler = ({ method, path }) => { 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/examples.tsx b/dashboard/src/app/learning/examples.tsx new file mode 100644 index 00000000..ff70e9c4 --- /dev/null +++ b/dashboard/src/app/learning/examples.tsx @@ -0,0 +1,413 @@ +"use client"; + +import Link from "next/link"; +import { useMemo, useRef, useState, type ReactNode } from "react"; +import type { LearningExemplar, LearningExemplarUse } from "@/lib/api"; +import { Chip, ListEmpty, ListSkeleton, SearchField, StatusToggles, Time, formatDate, type Tone } from "@/components/list"; +import { Drawer } from "@/components/drawer"; +import { Markdown } from "@/components/markdown"; +import { Code } from "@/components/settings/code"; +import { Section } from "@/components/page"; +import { Select } from "@/components/select"; +import { focusRing, linkButton, secondaryButton } from "@/components/ui"; + +// "Examples in use": the past work the agents read before a review or a +// change. One compact row each (title, why it is an example, tags, chips), +// To follow / To avoid as toggles with counts, and the whole example in a +// side panel (a full-screen sheet on a phone), the way an issue list opens +// an issue beside the list instead of printing every body inline. + +const PAGE = 10; + +type Polarity = "good" | "avoid"; +type KindFilter = "" | "fix" | "finding"; + +const KIND_LABEL: Record = { fix: "Code change", finding: "Review comment" }; +const kindLabel = (k: string) => KIND_LABEL[k] ?? k; + +const signed = (v: number) => `${v > 0 ? "+" : v < 0 ? "−" : ""}${Math.abs(v).toFixed(2)}`; +const times = (n: number) => (n === 0 ? "Not used yet" : n === 1 ? "Used once" : `Used ${n.toLocaleString()} times`); + +/** GitHub-only markup a reader never wants: HTML comments, tags, callout markers. */ +function stripMarkup(md: string): string { + return md + .replace(/[\s\S]*?(|$)/g, "") + .replace(/|$)/g, "") + .replace(/<\/?[A-Za-z][A-Za-z0-9-]*(\s[^<>]*)?\/?>/g, "") + .replace(/^\s*>\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*$/gim, "") + .replace(/^\s*Source ticket:.*$/gim, "") + .replace(/\n{3,}/g, "\n\n") + .trim(); +} + +/** One plain line: no markdown marks. */ +function plainLine(md: string): string { + return stripMarkup(md) + .replace(/^\s*#{1,6}\s+/gm, "") + .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1") + .replace(/(\*\*|__)(.+?)\1/g, "$2") + .replace(/`+([^`]*)`+/g, "$1") + .replace(/\s+/g, " ") + .trim(); +} + +export interface ExampleView { + e: LearningExemplar; + title: string; + summary: string; + reason: string; +} + +/** + * How an example reads. The gateway sends a clean title, summary and reason; + * an older one sends only `text` (`title: body`), read here the same way. + */ +export function viewOf(e: LearningExemplar): ExampleView { + const fallbackReason = + e.kind === "fix" + ? e.polarity === "good" + ? "Merged, with a good outcome" + : "Closed, rewritten or reverted" + : e.polarity === "good" + ? "The team acted on this comment" + : "The team dismissed it or left it open"; + if (e.title) return { e, title: e.title, summary: stripMarkup(e.summary ?? ""), reason: e.reason || fallbackReason }; + // `title: body`, where a commit type ("fix(api): ") is part of the title. + let at = e.text.indexOf(": "); + while (at > 0 && /^[a-z]+(\([^)]*\))?!?$/.test(e.text.slice(0, at).trim())) at = e.text.indexOf(": ", at + 2); + const head = at > 0 && at <= 160 && !e.text.slice(0, at).includes("\n") ? e.text.slice(0, at) : ""; + const body = head ? e.text.slice(at + 2) : e.text; + const title = plainLine(head) || plainLine(body).split(/(?<=[.?!])\s/)[0].slice(0, 120); + const summary = stripMarkup(body) + .replace(/^\s*(#{1,6}\s*)?(\*\*)?(summary|problem|changes?|risk|verification)(\*\*)?\s*:?\s*$/gim, "") + .replace(/^\s*\*\*(summary|problem|changes?|risk|verification)\*\*\s*:?\s*/gim, "") + .trim(); + return { e, title, summary, reason: e.reason || fallbackReason }; +} + +const prUrl = (repo: string, pr: number) => `https://github.com/${repo}/pull/${pr}`; +const runHref = (id: string) => `/runs/detail?id=${encodeURIComponent(id)}`; + +/** Most used first, then the biggest reward either way. */ +function byUse(a: ExampleView, b: ExampleView) { + return b.e.uses - a.e.uses || Math.abs(b.e.reward) - Math.abs(a.e.reward) || a.title.localeCompare(b.title); +} + +const tagClass = "inline-flex min-w-0 max-w-full items-center rounded border border-zinc-700 px-1.5 text-xs leading-5 text-zinc-300"; +const metaLink = `relative z-10 rounded text-zinc-300 underline-offset-2 hover:text-zinc-100 hover:underline ${focusRing}`; + +function ExampleRow({ v, onOpen }: { v: ExampleView; onOpen: (button: HTMLButtonElement) => void }) { + const { e } = v; + const tone: Tone = e.polarity === "good" ? "success" : "danger"; + // Right of the title from sm: up; at the end of the tags on a phone. + const chips = ( + <> + + {signed(e.reward)} + + + {e.uses ? `${e.uses.toLocaleString()}×` : "Unused"} + {times(e.uses)} + + + ); + return ( + // The title's button covers the whole row (its ::after), so the row is + // one click target; the PR link sits above it. +
  • +
    +
    + + {/* One meta line: why it is an example, then its tags and where it came from. */} +
    + + {v.reason} + + + {kindLabel(e.kind)} + {e.category && {e.category}} + {e.area && ( + + {e.area} + + )} + + {e.repo} + {e.pr ? ( + <> + {" "} + + #{e.pr} + (opens in a new tab) + + + ) : null} + + {chips} +
    +
    +
    {chips}
    +
    +
  • + ); +} + +function Fact({ label, children, wide = false }: { label: string; children: ReactNode; wide?: boolean }) { + return ( +
    +
    {label}
    +
    {children}
    +
    + ); +} + +function UseItem({ u, repo }: { u: LearningExemplarUse; repo: string }) { + const what = + u.run_id ? ( + + Coding run {u.run_id.slice(-6)} + + ) : u.pr ? ( + + Review of #{u.pr} + (opens in a new tab) + + ) : ( + {u.agent === "coder" ? "A coding run" : "A review"} + ); + return ( +
  • + {what} +
  • + ); +} + +function ExampleDetail({ v }: { v: ExampleView }) { + const { e } = v; + const uses = [...(e.used_by ?? [])].reverse(); + return ( +
    +
    + {e.polarity === "good" ? "To follow" : "To avoid"} + {kindLabel(e.kind)} + {e.category && {e.category}} +
    + +
    + {e.repo} + + {e.pr ? ( + + #{e.pr} on GitHub + (opens in a new tab) + + ) : ( + "None" + )} + + {e.area && ( + + {e.area} + + )} + {e.run_id && ( + + + The run that wrote it + + + )} + + {signed(e.reward)} + {e.events ? from {e.events} outcome{e.events === 1 ? "" : "s"} : null} + + {times(e.uses)} + {e.last_used_at ? + {formatDate(e.created_at) || "Unknown"} +
    + +
    +

    + {e.kind === "fix" ? "What the change did" : "What the comment said"} +

    + {v.summary ? ( +
    + {v.summary} +
    + ) : ( +

    Nothing more than the title.

    + )} +
    + +
    +

    + Recent uses +

    + {uses.length ? ( +
      + {uses.map((u, i) => ( + + ))} +
    + ) : ( +

    + {e.uses ? "Used before runs were recorded here; new uses will show." : "Not given to an agent yet. It is used when similar work comes up in this repository."} +

    + )} +
    +
    + ); +} + +export function Examples({ list, loading = false }: { list: LearningExemplar[]; /** Reading a new repository or period: rows are stale. */ loading?: boolean }) { + const [polarity, setPolarity] = useState("good"); + const [query, setQuery] = useState(""); + const [repo, setRepo] = useState(""); + const [kind, setKind] = useState(""); + const [shown, setShown] = useState(PAGE); + const [openId, setOpenId] = useState(null); + const opener = useRef(null); + + const views = useMemo(() => list.map(viewOf), [list]); + const repos = useMemo(() => [...new Set(list.map((e) => e.repo))].sort(), [list]); + // Every filter but the toggle: the toggle's counts answer "how many of each, here". + const filtered = useMemo(() => { + const q = query.toLowerCase(); + return views.filter( + (v) => + (!repo || v.e.repo === repo) && + (!kind || v.e.kind === kind) && + (!q || [v.title, v.reason, v.summary, v.e.area, v.e.category, v.e.repo, v.e.pr ? `#${v.e.pr}` : ""].some((s) => s.toLowerCase().includes(q))), + ); + }, [views, query, repo, kind]); + const counts = { good: filtered.filter((v) => v.e.polarity === "good").length, avoid: filtered.filter((v) => v.e.polarity === "avoid").length }; + const rows = useMemo(() => filtered.filter((v) => v.e.polarity === polarity).sort(byUse), [filtered, polarity]); + const open = views.find((v) => v.e.id === openId) ?? null; + const filtering = !!(query || repo || kind); + const reset = (f: () => void) => { + f(); + setShown(PAGE); + }; + const clear = () => reset(() => { + setQuery(""); + setRepo(""); + setKind(""); + }); + + return ( +
    + {list.length === 0 && !loading ? ( + + A review comment the team acts on, or a pull request that merges as written, becomes an example to follow. A dismissed comment or a closed pull request becomes one to avoid. + + ) : ( + <> +
    +
    + reset(() => setQuery(v))} placeholder="Search examples" label="Search examples" /> + reset(() => setPolarity(v as Polarity))} + label="Show examples" + options={[ + { value: "good", label: "To follow", count: counts.good, tone: "success" }, + { value: "avoid", label: "To avoid", count: counts.avoid, tone: "danger" }, + ]} + /> + {/* The page's repository filter (top) reads one repository from the + server; this one narrows the examples already here. */} +
    + {repos.length > 1 && ( + + )} + +
    +
    +
    + {rows.length > 0 &&

    {`Showing ${Math.min(shown, rows.length)} of ${rows.length}, most used first`}

    } + {filtering && ( + + )} +
    +
    +
    + {loading ? ( + + ) : rows.length === 0 ? ( + filtering ? ( + + Try another word, repository or kind. + + ) : ( + + {polarity === "good" + ? "Comments the team acts on and pull requests that merge as written show here." + : "Dismissed comments and closed or reverted pull requests show here."} + + ) + ) : ( + <> +
      + {rows.slice(0, shown).map((v) => ( + { + opener.current = button; + setOpenId(v.e.id); + }} + /> + ))} +
    + {rows.length > shown && ( +
    + +
    + )} + + )} +
    + + )} + !o && setOpenId(null)} + title={open?.title ?? ""} + description={open?.reason} + testId="example-panel" + returnFocusTo={opener} + > + {open && } + +
    + ); +} diff --git a/dashboard/src/app/learning/page.tsx b/dashboard/src/app/learning/page.tsx index 6090777d..d4d2bf0a 100644 --- a/dashboard/src/app/learning/page.tsx +++ b/dashboard/src/app/learning/page.tsx @@ -9,14 +9,14 @@ import { type LearningBandit, type LearningCategory, type LearningChange, - type LearningExemplar, } from "@/lib/api"; import { CardSkeleton, ChartSkeleton } from "@/components/skeleton"; +import { Examples } from "./examples"; import { StatGrid, StatTile } from "@/components/stat-tile"; import { DataTable, type Column } from "@/components/data-table"; import { Problem } from "@/components/problem"; import { Segmented } from "@/components/segmented"; -import { RepoFilter } from "@/components/list"; +import { ListSkeleton, RepoFilter } from "@/components/list"; import { Callout } from "@/components/callout"; import { Disclosure } from "@/components/disclosure"; import { ChevronRightIcon } from "@/components/icons"; @@ -363,46 +363,6 @@ function ChangeItem({ } -function Exemplar({ e }: { e: LearningExemplar }) { - return ( -
  • -

    - {e.kind === "fix" ? "Code change" : "Review comment"} - {e.category ? ` · ${e.category}` : ""} - {e.area ? ` · ${e.area}` : ""} -

    -

    {e.text}

    -

    - {e.repo} - {e.pr ? ` · PR #${e.pr}` : ""} · reward {signed(e.reward)} · {e.uses === 0 ? "not used yet" : `used ${plural(e.uses, "time")}`} -

    -
  • - ); -} - -function Exemplars({ list }: { list: LearningExemplar[] }) { - const good = list.filter((e) => e.polarity === "good"); - const avoid = list.filter((e) => e.polarity === "avoid"); - return ( -
    -
    -
    -

    To follow

    - {good.length ?
      {good.map((e) => )}
    :

    None yet.

    } -
    -
    -

    To avoid

    - {avoid.length ?
      {avoid.map((e) => )}
    :

    None yet.

    } -
    -
    -
    - ); -} - function BanditCard({ b, canManage, busy, minSamples, onPin }: { b: LearningBandit; canManage: boolean; busy: boolean; minSamples: number; onPin: (agent: string, arm: string | null) => void }) { const refusal = canManage ? undefined : "Only an admin or the owner can pin a variant"; return ( @@ -642,6 +602,7 @@ export default function LearningPage() { {Array.from({ length: 4 }).map((_, i) => )} + ) : data ? (
    @@ -740,7 +701,7 @@ export default function LearningPage() { )} - +
    . * * The header (title, `actions`) and `footer` stay put; only the body scrolls. + * + * A drawer opened without a Radix trigger (a row's own button) passes that + * button as `returnFocusTo`, so closing it puts focus back on the row. */ export function Drawer({ open, @@ -20,6 +23,7 @@ export function Drawer({ actions, footer, testId, + returnFocusTo, children, }: { open: boolean; @@ -31,6 +35,8 @@ export function Drawer({ actions?: ReactNode; footer?: ReactNode; testId?: string; + /** Where focus goes on close when nothing else claims it (the row that opened it). */ + returnFocusTo?: RefObject; children?: ReactNode; }) { return ( @@ -39,6 +45,13 @@ export function Drawer({ { + const el = returnFocusTo?.current; + if (el?.isConnected) { + e.preventDefault(); + el.focus(); + } + }} {...(description ? {} : { "aria-describedby": undefined })} className="fixed inset-0 z-[61] flex h-[100dvh] flex-col overflow-hidden bg-zinc-900 shadow-2xl sm:left-auto sm:w-[min(40rem,100vw)] sm:border-l sm:border-zinc-800" > diff --git a/dashboard/src/lib/api.ts b/dashboard/src/lib/api.ts index 4c6dda7d..d854942e 100644 --- a/dashboard/src/lib/api.ts +++ b/dashboard/src/lib/api.ts @@ -3712,6 +3712,14 @@ export interface LearningCategory { reason: string; } +/** One time an example was given to an agent: a coding run, or a review of a pull request. */ +export interface LearningExemplarUse { + at: string; + agent: "reviewer" | "coder" | (string & {}); + run_id?: string; + pr?: number; +} + export interface LearningExemplar { id: string; repo: string; @@ -3719,11 +3727,24 @@ export interface LearningExemplar { polarity: "good" | "avoid"; category: string; area: string; + /** One clean line; older gateways send only `text`. */ + title?: string; + /** Short markdown, markup and boilerplate removed. */ + summary?: string; + /** Why it is an example ("CI passed on the first try, merged without changes"). */ + reason?: string; text: string; reward: number; + /** Outcomes its reward adds up. */ + events?: number; uses: number; created_at: string; pr?: number; + /** The run that made the change (code changes). */ + run_id?: string; + last_used_at?: string; + /** The latest uses, oldest first. */ + used_by?: LearningExemplarUse[]; } export interface LearningArm {