diff --git a/hub/client/features/prototype-workspace-header-layout/styles.css b/hub/client/features/prototype-workspace-header-layout/styles.css index 0be8417dc..54d77e513 100644 --- a/hub/client/features/prototype-workspace-header-layout/styles.css +++ b/hub/client/features/prototype-workspace-header-layout/styles.css @@ -167,6 +167,18 @@ div:has(> [data-testid="ActionMenu"] .review-shell__more-trigger[aria-expanded=" display: none; } +.review-shell__more-menu [role="menu"] { + box-sizing: border-box; + width: max-content; + min-width: 13rem; + max-width: calc(100vw - 1rem); +} + +/* Brand only spaces icons in link items, so match that gap for action items. */ +.review-shell__more-action { + column-gap: var(--base-size-8); +} + .review-shell__build-menu [role="menu"] { box-sizing: border-box; width: max-content; diff --git a/hub/client/features/prototype-workspace-header/index.tsx b/hub/client/features/prototype-workspace-header/index.tsx index fb14c5bf3..077c0007b 100644 --- a/hub/client/features/prototype-workspace-header/index.tsx +++ b/hub/client/features/prototype-workspace-header/index.tsx @@ -4,6 +4,7 @@ import { InfoIcon, KebabHorizontalIcon, LinkIcon, + LightBulbIcon, MoonIcon, PencilIcon, RepoForkedIcon, @@ -33,6 +34,7 @@ export function PrototypeWorkspaceHeader({ fork, reviewControls, onControlsToolbarMount, + onShowAgentReportedUse, }: PrototypeWorkspaceHeaderProps) { const { resolvedColorMode, setColorMode } = useHubTheme() const controls = useControlQuery() @@ -222,7 +224,8 @@ export function PrototypeWorkspaceHeader({ ) : null} - {!data.browseReplica && menuLinks.length > 0 ? ( + {!data.browseReplica && + (menuLinks.length > 0 || (data.agentReportedUseLabel && onShowAgentReportedUse)) ? (
@@ -247,6 +250,16 @@ export function PrototypeWorkspaceHeader({ {label} ))} + {data.agentReportedUseLabel && onShowAgentReportedUse ? ( + } + onClick={onShowAgentReportedUse} + > + {data.agentReportedUseLabel} + + ) : null}
diff --git a/hub/client/features/prototype-workspace-header/types.ts b/hub/client/features/prototype-workspace-header/types.ts index 15c72121d..72e1b1f3c 100644 --- a/hub/client/features/prototype-workspace-header/types.ts +++ b/hub/client/features/prototype-workspace-header/types.ts @@ -41,6 +41,7 @@ export interface PrototypeWorkspaceHeaderData extends WorkspaceHeaderData { historyLabel: string historyPath?: string moreActionsLabel: string + agentReportedUseLabel?: string shareLinksLabel?: string shareLinksPath?: string } @@ -57,6 +58,7 @@ export interface PrototypeWorkspaceHeaderProps { onClick: () => void } onControlsToolbarMount?: (toolbar: HTMLSpanElement | null) => void + onShowAgentReportedUse?: () => void fork?: { label: string onClick: () => void diff --git a/hub/client/features/prototype-workspace/index.tsx b/hub/client/features/prototype-workspace/index.tsx index f033889bb..9bc5b86db 100644 --- a/hub/client/features/prototype-workspace/index.tsx +++ b/hub/client/features/prototype-workspace/index.tsx @@ -19,6 +19,7 @@ export function PrototypeWorkspace({ children, data, onShowInfo, + onShowAgentReportedUse, editDetails, fork, preview = false, @@ -27,6 +28,7 @@ export function PrototypeWorkspace({ }: PropsWithChildren<{ data: PrototypeWorkspaceData | ReplicaWorkspaceData onShowInfo?: () => void + onShowAgentReportedUse?: PrototypeWorkspaceHeaderProps["onShowAgentReportedUse"] editDetails?: PrototypeWorkspaceHeaderProps["editDetails"] fork?: PrototypeWorkspaceHeaderProps["fork"] preview?: boolean @@ -39,6 +41,7 @@ export function PrototypeWorkspace({ { + it("can leave every destination unselected without changing the default", () => { + const { rerender } = render( + undefined} + data={prototypeWorkspaceData} + />, + ) + expect(screen.getByRole("link", { name: "Prototypes" })).toHaveAttribute("aria-current", "page") + + rerender( + undefined} + data={{ ...prototypeWorkspaceData, selectedSection: null }} + />, + ) + + expect(screen.queryAllByRole("link", { current: "page" })).toHaveLength(0) + }) + it.each([false, true])( "places Welcome first below the repository selector, collapsed %s", (collapsed) => { diff --git a/hub/client/features/workspace-nav/index.tsx b/hub/client/features/workspace-nav/index.tsx index 031d84a78..309032c5d 100644 --- a/hub/client/features/workspace-nav/index.tsx +++ b/hub/client/features/workspace-nav/index.tsx @@ -173,7 +173,8 @@ export function WorkspaceNav({
    {primaryLinks.map((link) => { if (!link.path || !link.label) return null - const selectedSection = data.selectedSection ?? "prototypes" + const selectedSection = + data.selectedSection === undefined ? "prototypes" : data.selectedSection const item = ( , { wrapper: HubThemeProvider }) +} + +describe("AgentConnectionsPrototype()", () => { + it("copies a repository MCP endpoint without putting a credential in the config", async () => { + const writeText = vi.fn().mockResolvedValue(undefined) + vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } }) + const data: AgentConnectionsPrototypeData = { + repositoryId: "2001", + repositoryName: "github/prototype", + hubUrl: "https://hub.example.com", + signedInAs: "@octocat", + view: "connections", + connections: [], + } + renderPrototype(data) + + const config = screen.getByLabelText("Hub MCP configuration") + expect(config).toHaveTextContent("https://hub.example.com/mcp/repositories/2001") + expect(config).not.toHaveTextContent(/token|secret|password/i) + fireEvent.click(screen.getByRole("button", { name: "Copy: Hub MCP configuration" })) + + expect( + await screen.findByRole("button", { name: "Copied: Hub MCP configuration" }), + ).toBeVisible() + expect(writeText).toHaveBeenCalledWith(config.textContent) + }) + + it("requires confirmation and revokes only the selected agent connection", () => { + const data: AgentConnectionsPrototypeData = { + repositoryId: "2001", + repositoryName: "github/prototype", + hubUrl: "https://hub.example.com", + signedInAs: "@octocat", + view: "connections", + connections: [ + { + id: "agent-vscode", + name: "Visual Studio Code", + connectedAt: "2026-11-18", + lastUsedAt: "2026-11-24", + }, + { + id: "agent-local", + name: "Local MCP client", + connectedAt: "2026-11-12", + lastUsedAt: "2026-11-21", + }, + ], + } + renderPrototype(data) + + fireEvent.click(screen.getByRole("button", { name: "Revoke Visual Studio Code access" })) + const dialog = screen.getByRole("dialog", { name: "Revoke agent access?" }) + expect(dialog).toHaveTextContent("does not sign you out of Hub") + expect(within(dialog).getByRole("button", { name: "Cancel" })).toBeVisible() + + fireEvent.click(within(dialog).getByRole("button", { name: "Revoke access" })) + + expect(screen.queryByText("Visual Studio Code")).not.toBeInTheDocument() + expect(screen.getByText("Local MCP client")).toBeVisible() + expect(screen.getByRole("region", { name: "Notifications" })).toHaveTextContent( + "Visual Studio Code can no longer access Hub.", + ) + expect(document.activeElement).toBe( + screen.getByRole("heading", { name: "Your connected agents" }), + ) + }) + + it("keeps agent access pending until approval and separates screenshot consent", () => { + const data: AgentConnectionsPrototypeData = { + repositoryId: "2001", + repositoryName: "github/prototype", + hubUrl: "https://hub.example.com", + signedInAs: "@octocat", + view: "approval", + requestingAgent: "Visual Studio Code", + connections: [], + } + renderPrototype(data) + + expect(screen.getByText(/does not allow session-message storage/)).toBeVisible() + expect(screen.queryByRole("heading", { name: "Agent connected" })).not.toBeInTheDocument() + fireEvent.click(screen.getByRole("button", { name: "Approve access" })) + + expect(screen.getByRole("heading", { name: "Agent connected" })).toBeVisible() + expect(screen.getByText(/revoke its Hub access at any time/)).toBeVisible() + }) + + it("does not connect the agent when the person cancels approval", () => { + const data: AgentConnectionsPrototypeData = { + repositoryId: "2001", + repositoryName: "github/prototype", + hubUrl: "https://hub.example.com", + signedInAs: "@octocat", + view: "approval", + requestingAgent: "Visual Studio Code", + connections: [], + } + renderPrototype(data) + + fireEvent.click(screen.getByRole("button", { name: "Cancel" })) + + expect(screen.getByRole("heading", { name: "Connection cancelled" })).toBeVisible() + expect(screen.queryByRole("heading", { name: "Agent connected" })).not.toBeInTheDocument() + expect(screen.getByText(/No Hub access was granted/)).toBeVisible() + }) +}) diff --git a/hub/client/pages/agent-connections-prototype/index.tsx b/hub/client/pages/agent-connections-prototype/index.tsx new file mode 100644 index 000000000..8fbc4ea3f --- /dev/null +++ b/hub/client/pages/agent-connections-prototype/index.tsx @@ -0,0 +1,156 @@ +import { useRef, useState } from "react" +import { Button, Heading, Text } from "@primer/react-brand" + +import { CanvasDialog } from "@components/prototype-canvas-dialog" +import { CopyableCodeBlock } from "@components/copyable-code-block" +import { HubToast } from "@components/hub-toast" + +import type { AgentConnectionsPrototypeData } from "./types" +import "./styles.css" + +export function AgentConnectionsPrototype({ data }: { data: AgentConnectionsPrototypeData }) { + const [connections, setConnections] = useState(data.connections) + const [connectionToRevoke, setConnectionToRevoke] = useState(null) + const [notice, setNotice] = useState("") + const [approval, setApproval] = useState<"pending" | "approved" | "cancelled">("pending") + const connectionsHeadingRef = useRef(null) + const endpoint = `${data.hubUrl.replace(/\/$/, "")}/mcp/repositories/${data.repositoryId}` + const configuration = JSON.stringify({ mcpServers: { replica: { url: endpoint } } }, null, 2) + const selectedConnection = connections.find(({ id }) => id === connectionToRevoke) + + function revokeConnection() { + if (!selectedConnection) return + setConnections((current) => current.filter(({ id }) => id !== selectedConnection.id)) + setConnectionToRevoke(null) + setNotice(`${selectedConnection.name} can no longer access Hub.`) + } + + if (data.view === "approval") { + return ( +
    + {approval === "pending" ? ( +
    + + Connect {data.requestingAgent} to Hub? + + + You are signed in as {data.signedInAs}. This agent can read guidance + and report which learnings it applied for repositories you can access. Hub checks + access on every request; only people can accept or change learnings. + + + This does not allow session-message storage, screenshot storage, or automated + screenshot review. Those choices require separate consent. + +
    + + +
    +
    + ) : ( +
    + + {approval === "approved" ? "Agent connected" : "Connection cancelled"} + + + {approval === "approved" + ? `Return to ${data.requestingAgent} to continue. You can revoke its Hub access at any time.` + : `You can close this page and return to ${data.requestingAgent}. No Hub access was granted.`} + +
    + )} +
    + ) + } + + return ( +
    +
    + + Connect an agent + + + Set up an agent to use learning guidance from {data.repositoryName}. + +
    + +
    + + Add Hub to your agent + + + Copy this configuration into your agent. It contains the Hub address for this repository, + not a password or access token. Your agent will open a browser when it needs you to sign + in. + + +
    + +
    + + Your connected agents + + + Connected as {data.signedInAs}. These agents can use your Hub access for any repository + you can access. + + {connections.length ? ( +
      + {connections.map((connection) => ( +
    • +
      + {connection.name} + + Connected{" "} + + {" · "}Last used{" "} + + +
      + +
    • + ))} +
    + ) : ( + No agents are connected to your Hub account. + )} +
    + + {selectedConnection ? ( + setConnectionToRevoke(null)} + > +
    + + {selectedConnection.name} will no longer be able to use your Hub account. This does + not sign you out of Hub or change your repository access. + +
    + + +
    +
    +
    + ) : null} + {notice ? : null} +
    + ) +} diff --git a/hub/client/pages/agent-connections-prototype/stories.tsx b/hub/client/pages/agent-connections-prototype/stories.tsx new file mode 100644 index 000000000..56775d479 --- /dev/null +++ b/hub/client/pages/agent-connections-prototype/stories.tsx @@ -0,0 +1,106 @@ +import type { Meta, StoryObj } from "@storybook/react-vite" + +import { RepositoryWorkspace } from "@features/repository-workspace" +import type { RepositoryWorkspaceData } from "@features/repository-workspace/types" +import { authenticatedHeaderData } from "@/storybook/fixtures/authenticated-header" +import { githubEmpty, githubPrototype } from "@/storybook/fixtures/repositories" + +import { AgentConnectionsPrototype } from "." +import type { AgentConnectionsPrototypeData } from "./types" + +const workspace: RepositoryWorkspaceData = { + ...authenticatedHeaderData, + analyticsLabel: "Analytics", + analyticsPath: "/repositories/2001/analytics", + collapseNavigationLabel: "Collapse sidebar", + expandNavigationLabel: "Expand sidebar", + learningsLabel: "Learnings", + learningsPath: "/repositories/2001/learnings", + navigationLabel: "Repository navigation", + newPrototypeLabel: "Create", + newPrototypePath: "/repositories/2001/new", + prototypesLabel: "Prototypes", + prototypesPath: "/repositories/2001", + repositories: [githubPrototype, githubEmpty], + repositoryMenuLabel: "Repositories", + repositorySelectorLabel: "Choose repository. github/prototype selected", + selectedRepositoryId: "2001", + selectedSection: "learnings", + welcomeLabel: "Welcome", + welcomePath: "/welcome", +} + +const connections: AgentConnectionsPrototypeData = { + repositoryId: "2001", + repositoryName: "github/prototype", + hubUrl: "https://hub.example.com", + signedInAs: "@octocat", + view: "connections", + connections: [ + { + id: "agent-vscode", + name: "Visual Studio Code", + connectedAt: "2026-11-18", + lastUsedAt: "2026-11-24", + }, + { + id: "agent-local", + name: "Local MCP client", + connectedAt: "2026-11-12", + lastUsedAt: "2026-11-21", + }, + ], +} + +const approval: AgentConnectionsPrototypeData = { + ...connections, + view: "approval", + requestingAgent: "Visual Studio Code", +} + +const meta = { + title: "Hub/Pages/Learnings/Agent connections", + component: AgentConnectionsPrototype, + parameters: { layout: "fullscreen" }, + args: { data: connections }, + render: ({ data }) => + data.view === "connections" ? ( + + + + ) : ( + + ), +} satisfies Meta + +export default meta +type Story = StoryObj + +export const ConnectedAgents: Story = {} +export const NoConnectedAgents: Story = { + args: { data: { ...connections, connections: [] } }, +} +export const RevokeConfirmation: Story = { + args: { data: connections }, + play: async ({ canvas, userEvent }) => { + await userEvent.click(canvas.getByRole("button", { name: "Revoke Visual Studio Code access" })) + await canvas.findByRole("dialog", { name: "Revoke agent access?" }) + }, +} +export const ApprovalRequest: Story = { + args: { data: approval }, +} +export const Approved: Story = { + args: { data: approval }, + play: async ({ canvas, userEvent }) => { + await userEvent.click(canvas.getByRole("button", { name: "Approve access" })) + await canvas.findByRole("heading", { name: "Agent connected" }) + }, +} +export const Cancelled: Story = { + args: { data: approval }, + play: async ({ canvas, userEvent }) => { + await userEvent.click(canvas.getByRole("button", { name: "Cancel" })) + await canvas.findByRole("heading", { name: "Connection cancelled" }) + }, +} diff --git a/hub/client/pages/agent-connections-prototype/styles.css b/hub/client/pages/agent-connections-prototype/styles.css new file mode 100644 index 000000000..199e1f760 --- /dev/null +++ b/hub/client/pages/agent-connections-prototype/styles.css @@ -0,0 +1,93 @@ +.agent-connections { + display: grid; + gap: 1.5rem; + max-width: 64rem; + margin-inline: auto; + padding: clamp(1rem, 3vw, 2rem); +} + +.agent-connections h1, +.agent-connections h2, +.agent-connections p { + margin: 0; +} + +.agent-connections__header, +.agent-connections__section, +.agent-connections__approval, +.agent-connections__approval-result { + display: grid; + gap: 0.75rem; +} + +.agent-connections__header > p, +.agent-connections__section > p, +.agent-connections__approval > p, +.agent-connections__approval-result > p { + color: var(--hub-fg-muted); +} + +.agent-connections__section { + padding-block: 1.25rem; + border-top: 1px solid var(--hub-border-default); +} + +.agent-connections__list { + display: grid; + gap: 0.75rem; + margin: 0; + padding: 0; + list-style: none; +} + +.agent-connections__item { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + padding: 1rem; + border: 1px solid var(--hub-border-default); + border-radius: var(--hub-radius-medium); +} + +.agent-connections__item > div { + display: grid; + gap: 0.25rem; +} + +.agent-connections__item span { + color: var(--hub-fg-muted); + font-size: 0.875rem; +} + +.agent-connections__approval { + max-width: 36rem; + margin: 10vh auto; + padding: 1.5rem; + border: 1px solid var(--hub-border-default); + border-radius: var(--hub-radius-medium); + background: var(--hub-canvas-default); +} + +.agent-connections__approval-result { + max-width: 36rem; + margin: 10vh auto; +} + +.agent-connections__actions { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 0.75rem; +} + +.agent-connections__revoke-dialog { + display: grid; + gap: 1.25rem; +} + +@media (max-width: 40rem) { + .agent-connections__item { + align-items: flex-start; + } +} diff --git a/hub/client/pages/agent-connections-prototype/types.ts b/hub/client/pages/agent-connections-prototype/types.ts new file mode 100644 index 000000000..146d4bced --- /dev/null +++ b/hub/client/pages/agent-connections-prototype/types.ts @@ -0,0 +1,24 @@ +export interface AgentConnection { + id: string + name: string + connectedAt: string + lastUsedAt: string +} + +interface AgentConnectionsPrototypeBase { + repositoryId: string + repositoryName: string + hubUrl: string + signedInAs: string +} + +export type AgentConnectionsPrototypeData = + | (AgentConnectionsPrototypeBase & { + view: "connections" + connections: AgentConnection[] + }) + | (AgentConnectionsPrototypeBase & { + view: "approval" + connections: AgentConnection[] + requestingAgent: string + }) diff --git a/hub/client/pages/evaluation-settings-prototype/index.test.tsx b/hub/client/pages/evaluation-settings-prototype/index.test.tsx new file mode 100644 index 000000000..e7cae39b7 --- /dev/null +++ b/hub/client/pages/evaluation-settings-prototype/index.test.tsx @@ -0,0 +1,131 @@ +import { fireEvent, render, screen } from "@testing-library/react" +import { describe, expect, it } from "vitest" + +import { HubThemeProvider } from "@hooks/use-hub-theme" + +import { EvaluationSettingsPrototype } from "." +import type { EvaluationSettingsPrototypeData } from "./types" + +function renderPrototype(data: EvaluationSettingsPrototypeData) { + render(, { wrapper: HubThemeProvider }) +} + +describe("EvaluationSettingsPrototype()", () => { + it("lets a Hub admin set the shared cap without going below spend already used", () => { + const data: EvaluationSettingsPrototypeData = { + repositoryName: "github/prototype", + learningsPath: "/repositories/2001/learnings", + canManageHubBudget: true, + canManageRepositorySettings: true, + budgetLimitCredits: 100, + usedCredits: 42, + repositoryEnabled: false, + } + renderPrototype(data) + + const budget = screen.getByRole("spinbutton", { name: "Shared Hub budget" }) + expect(budget).toHaveAttribute("min", "42") + expect(budget).toHaveAccessibleDescription("42 of 100 credits used") + fireEvent.change(budget, { target: { value: "30" } }) + + expect(budget).toBeInvalid() + fireEvent.blur(budget) + expect(screen.getByRole("alert")).toHaveTextContent("at least 42 credits") + expect(screen.queryByText("Hub evaluation budget saved.")).not.toBeInTheDocument() + + fireEvent.change(budget, { target: { value: "120" } }) + fireEvent.blur(budget) + + expect(screen.getByRole("region", { name: "Notifications" })).toHaveTextContent( + "Hub evaluation budget saved.", + ) + }) + + it("lets a repository administrator opt in without granting Hub budget access", () => { + const data: EvaluationSettingsPrototypeData = { + repositoryName: "github/prototype", + learningsPath: "/repositories/2001/learnings", + canManageHubBudget: false, + canManageRepositorySettings: true, + budgetLimitCredits: 100, + usedCredits: 42, + repositoryEnabled: false, + } + renderPrototype(data) + + const optIn = screen.getByRole("switch", { + name: "Evaluate github/prototype", + }) + expect(screen.queryByRole("spinbutton")).not.toBeInTheDocument() + expect(optIn).toHaveAccessibleDescription( + "Turning this off stops future evaluations and keeps existing results.", + ) + + fireEvent.click(optIn) + + expect(optIn).toBeChecked() + expect(screen.getByRole("region", { name: "Notifications" })).toHaveTextContent( + "Automated evaluations enabled for github/prototype.", + ) + }) + + it("keeps an opted-in repository paused when the Hub budget is used", () => { + const data: EvaluationSettingsPrototypeData = { + repositoryName: "github/prototype", + learningsPath: "/repositories/2001/learnings", + canManageHubBudget: false, + canManageRepositorySettings: true, + budgetLimitCredits: 100, + usedCredits: 100, + repositoryEnabled: true, + } + renderPrototype(data) + + const optIn = screen.getByRole("switch", { + name: "Evaluate github/prototype", + }) + expect(optIn).toBeChecked() + expect(screen.getByRole("alert")).toHaveTextContent(/Evaluations are paused/) + + fireEvent.click(optIn) + + expect(optIn).not.toBeChecked() + expect(optIn).toBeDisabled() + }) + + it("prevents repository opt-in until a Hub administrator sets a budget", () => { + const data: EvaluationSettingsPrototypeData = { + repositoryName: "github/prototype", + learningsPath: "/repositories/2001/learnings", + canManageHubBudget: false, + canManageRepositorySettings: true, + budgetLimitCredits: 0, + usedCredits: 0, + repositoryEnabled: false, + } + renderPrototype(data) + + expect(screen.getByRole("status")).toHaveTextContent( + "A Hub admin must set a budget before evaluations can be enabled.", + ) + expect(screen.getByRole("switch", { name: "Evaluate github/prototype" })).toBeDisabled() + }) + + it("links back to the repository's Learning Library", () => { + const data: EvaluationSettingsPrototypeData = { + repositoryName: "github/empty", + learningsPath: "/repositories/2002/learnings", + canManageHubBudget: false, + canManageRepositorySettings: true, + budgetLimitCredits: 100, + usedCredits: 42, + repositoryEnabled: false, + } + renderPrototype(data) + + expect(screen.getByRole("link", { name: "Back to learnings" })).toHaveAttribute( + "href", + "/repositories/2002/learnings", + ) + }) +}) diff --git a/hub/client/pages/evaluation-settings-prototype/index.tsx b/hub/client/pages/evaluation-settings-prototype/index.tsx new file mode 100644 index 000000000..f58396931 --- /dev/null +++ b/hub/client/pages/evaluation-settings-prototype/index.tsx @@ -0,0 +1,195 @@ +import { useState, type SyntheticEvent } from "react" +import { ArrowLeftIcon } from "@primer/octicons-react" +import { Heading, Text, TextInput, Tooltip } from "@primer/react-brand" + +import { HubAlert } from "@components/hub-alert" +import { HubIconButton } from "@components/hub-icon-button" +import { HubSwitch } from "@components/hub-switch" +import { HubToast } from "@components/hub-toast" +import { HubVisuallyHidden } from "@components/hub-visually-hidden" + +import type { EvaluationSettingsPrototypeData } from "./types" +import "./styles.css" + +const optInHint = "Turning this off stops future evaluations and keeps existing results." + +function credits(value: number) { + return `${value.toLocaleString()} ${value === 1 ? "credit" : "credits"}` +} + +export function EvaluationSettingsPrototype({ data }: { data: EvaluationSettingsPrototypeData }) { + const [budgetLimit, setBudgetLimit] = useState(data.budgetLimitCredits) + const [budgetDraft, setBudgetDraft] = useState(String(data.budgetLimitCredits)) + const [budgetError, setBudgetError] = useState("") + const [repositoryEnabled, setRepositoryEnabled] = useState(data.repositoryEnabled) + const [notice, setNotice] = useState("") + const remaining = Math.max(0, budgetLimit - data.usedCredits) + const budgetReached = budgetLimit > 0 && remaining === 0 + const budgetNotSet = budgetLimit === 0 + const canEnableRepository = !budgetReached && !budgetNotSet + + // A bar shows how much of the shared budget is gone at a glance; the label keeps + // the exact numbers for anyone who needs them. + const usage = budgetNotSet ? ( + + Not set + + ) : ( +
    + + {data.usedCredits.toLocaleString()} of {credits(budgetLimit)} used + + +
    + ) + + // Saving on blur or Enter keeps the row free of a Save button. Unchanged values are + // skipped so tabbing through the page does not show a confirmation. + function saveBudget() { + const nextBudget = Number(budgetDraft) + if (nextBudget === budgetLimit) return + if (budgetDraft === "" || !Number.isFinite(nextBudget) || nextBudget < data.usedCredits) { + setBudgetError(`Set a limit of at least ${credits(data.usedCredits)}, already used.`) + return + } + + setBudgetLimit(nextBudget) + setBudgetError("") + setNotice("Hub evaluation budget saved.") + } + + function setRepositoryOptIn(enabled: boolean) { + if (enabled && !canEnableRepository) return + setRepositoryEnabled(enabled) + setNotice( + enabled + ? `Automated evaluations enabled for ${data.repositoryName}.` + : `Automated evaluations paused for ${data.repositoryName}.`, + ) + } + + return ( +
    +
    + + + Automated evaluations + +
    +
    + + When enabled, Hub checks whether your learnings are helping and suggests updates when + needed. + + +
    + {data.canManageHubBudget ? ( +
    ) => { + event.preventDefault() + saveBudget() + }} + > + + { + setBudgetDraft(event.target.value) + setBudgetError("") + }} + required + size="small" + step="any" + type="number" + value={budgetDraft} + /> + + credits + + {usage} + + ) : ( +
    + + Shared Hub budget + + {usage} +
    + )} + {budgetError ?

    {budgetError}

    : null} +
    + +
    + {budgetReached ? ( + + ) : budgetNotSet ? ( + + ) : null} + {data.canManageRepositorySettings ? ( +
    + + Evaluate {data.repositoryName} + + + + + + + {optInHint} +
    + ) : ( + + Only a repository administrator can change this setting. + + )} +
    + {notice ? : null} +
    +
    + ) +} diff --git a/hub/client/pages/evaluation-settings-prototype/stories.tsx b/hub/client/pages/evaluation-settings-prototype/stories.tsx new file mode 100644 index 000000000..cc502029c --- /dev/null +++ b/hub/client/pages/evaluation-settings-prototype/stories.tsx @@ -0,0 +1,90 @@ +import type { Meta, StoryObj } from "@storybook/react-vite" + +import { RepositoryWorkspace } from "@features/repository-workspace" +import type { RepositoryWorkspaceData } from "@features/repository-workspace/types" +import { authenticatedHeaderData } from "@/storybook/fixtures/authenticated-header" +import { githubEmpty, githubPrototype } from "@/storybook/fixtures/repositories" + +import { EvaluationSettingsPrototype } from "." +import type { EvaluationSettingsPrototypeData } from "./types" + +const workspace: RepositoryWorkspaceData = { + ...authenticatedHeaderData, + analyticsLabel: "Analytics", + analyticsPath: "/repositories/2001/analytics", + collapseNavigationLabel: "Collapse sidebar", + expandNavigationLabel: "Expand sidebar", + learningsLabel: "Learnings", + learningsPath: "/repositories/2001/learnings", + navigationLabel: "Repository navigation", + newPrototypeLabel: "Create", + newPrototypePath: "/repositories/2001/new", + prototypesLabel: "Prototypes", + prototypesPath: "/repositories/2001", + repositories: [githubPrototype, githubEmpty], + repositoryMenuLabel: "Repositories", + repositorySelectorLabel: "Choose repository. github/prototype selected", + selectedRepositoryId: "2001", + selectedSection: "learnings", + welcomeLabel: "Welcome", + welcomePath: "/welcome", +} + +const settings: EvaluationSettingsPrototypeData = { + repositoryName: "github/prototype", + learningsPath: "/iframe.html?id=hub-pages-learnings-library--multiple&viewMode=story", + canManageHubBudget: true, + canManageRepositorySettings: true, + budgetLimitCredits: 100, + usedCredits: 42, + repositoryEnabled: false, +} + +const meta = { + title: "Hub/Pages/Learnings/Evaluation settings", + component: EvaluationSettingsPrototype, + parameters: { layout: "fullscreen" }, + args: { data: settings }, + render: ({ data }) => ( + + + + ), +} satisfies Meta + +export default meta +type Story = StoryObj + +export const HubAndRepositoryAdmin: Story = { + args: { + data: { + ...settings, + learningsPath: "/iframe.html?id=hub-pages-learnings-library--hub-admin&viewMode=story", + }, + }, +} +export const RepositoryAdmin: Story = { + args: { data: { ...settings, canManageHubBudget: false } }, +} +export const BudgetReached: Story = { + args: { + data: { + ...settings, + canManageHubBudget: false, + budgetLimitCredits: 100, + usedCredits: 100, + repositoryEnabled: true, + }, + }, +} +export const BudgetNotSet: Story = { + args: { + data: { + ...settings, + canManageHubBudget: false, + budgetLimitCredits: 0, + usedCredits: 0, + repositoryEnabled: false, + }, + }, +} diff --git a/hub/client/pages/evaluation-settings-prototype/styles.css b/hub/client/pages/evaluation-settings-prototype/styles.css new file mode 100644 index 000000000..8f3c5224f --- /dev/null +++ b/hub/client/pages/evaluation-settings-prototype/styles.css @@ -0,0 +1,99 @@ +.evaluation-settings { + display: grid; + max-width: 64rem; + margin-inline: auto; + padding: clamp(1rem, 3vw, 2rem); +} + +.evaluation-settings p { + margin: 0; +} + +.evaluation-settings__section { + display: grid; + gap: 0.75rem; +} + +.evaluation-settings__intro { + padding-block-end: 1.5rem; + color: var(--hub-fg-muted); +} + +.evaluation-settings__section { + padding-block: 1.25rem; + border-top: 1px solid var(--hub-border-default); +} + +.evaluation-settings__row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.75rem; +} + +/* A shared label width lines up the budget input with the switch below it. */ +.evaluation-settings__label { + min-width: 12rem; + font-weight: 600; +} + +.evaluation-settings__budget-input { + width: 7rem; +} + +/* Shrink-wraps the switch so its tooltip points at the switch, not the whole row. */ +.evaluation-settings__switch { + display: inline-flex; +} + +/* Pushed to the far edge so usage reads as a summary, apart from the editable limit. */ +.evaluation-settings__usage { + display: flex; + align-items: center; + gap: 0.75rem; + margin-inline-start: auto; +} + +.evaluation-settings__meter { + inline-size: 10rem; + block-size: 0.5rem; + border: 0; + border-radius: 999px; + background: var(--hub-border-default); + appearance: none; +} + +.evaluation-settings__meter::-webkit-meter-bar { + block-size: 0.5rem; + border: 0; + border-radius: 999px; + background: var(--hub-border-default); +} + +.evaluation-settings__meter::-webkit-meter-optimum-value { + border-radius: 999px; + background: var(--hub-fg-success); +} + +.evaluation-settings__meter::-moz-meter-bar { + border-radius: 999px; + background: var(--hub-fg-success); +} + +/* A full budget turns red so admins notice evaluations have paused. */ +.evaluation-settings__meter--full::-webkit-meter-optimum-value { + background: var(--hub-fg-danger); +} + +.evaluation-settings__meter--full::-moz-meter-bar { + background: var(--hub-fg-danger); +} +.evaluation-settings-page { + min-height: 100%; +} + +.evaluation-settings__page-header { + display: flex; + align-items: center; + gap: 1rem; +} diff --git a/hub/client/pages/evaluation-settings-prototype/types.ts b/hub/client/pages/evaluation-settings-prototype/types.ts new file mode 100644 index 000000000..8a19961ce --- /dev/null +++ b/hub/client/pages/evaluation-settings-prototype/types.ts @@ -0,0 +1,9 @@ +export interface EvaluationSettingsPrototypeData { + repositoryName: string + learningsPath: string + canManageHubBudget: boolean + canManageRepositorySettings: boolean + budgetLimitCredits: number + usedCredits: number + repositoryEnabled: boolean +} diff --git a/hub/client/pages/learnings-library-prototype/index.test.tsx b/hub/client/pages/learnings-library-prototype/index.test.tsx new file mode 100644 index 000000000..7de6892dd --- /dev/null +++ b/hub/client/pages/learnings-library-prototype/index.test.tsx @@ -0,0 +1,777 @@ +import { fireEvent, render, screen, within } from "@testing-library/react" +import { describe, expect, it, vi } from "vitest" + +import { HubThemeProvider } from "@hooks/use-hub-theme" + +import { LearningsLibraryPrototype } from "." +import type { LearningsLibraryPrototypeData } from "./types" + +function createPrototypeData(canDecide: boolean): LearningsLibraryPrototypeData { + const supportingEvidence = { + id: "evidence-supporting", + body: "The visible label made the form easier to scan.", + authorLogin: "octocat", + prototypeName: "Checkout refresh", + buildNumber: 8, + createdAt: "2026-11-18T16:30:00.000Z", + reviewPath: "https://github.com/github/prototype/pull/42#discussion_r100", + } + const secondSupportingEvidence = { + id: "evidence-second-supporting", + body: "The Save button does not stand out beside Cancel.", + authorLogin: "mona", + prototypeName: "Settings refresh", + buildNumber: 5, + createdAt: "2026-11-17T14:00:00.000Z", + reviewPath: "https://github.com/github/prototype/pull/43#discussion_r101", + } + const placeholderEvidence = { + id: "evidence-placeholder", + body: "The placeholder disappears while I type, so I lose the field name.", + authorLogin: "octocat", + prototypeName: "Signup refresh", + buildNumber: 4, + createdAt: "2026-11-16T10:42:00.000Z", + reviewPath: "https://github.com/github/prototype/pull/44#discussion_r102", + } + + return { + canDecide, + learnings: [ + { + id: "learning-suggested", + title: "Keep form labels visible", + guidance: "Give every field a visible label.", + status: "suggested", + topic: "Accessibility", + updatedAt: "2026-11-18T16:30:00.000Z", + evidence: [supportingEvidence], + }, + { + id: "learning-suggested-rejection", + title: "Rely on placeholder text", + guidance: "Use placeholder text to identify each field.", + status: "suggested", + topic: "Accessibility", + updatedAt: "2026-11-17T14:00:00.000Z", + evidence: [placeholderEvidence], + }, + { + id: "learning-active", + title: "Make actions clear", + guidance: "Use clear labels for primary actions.", + status: "active", + topic: "Content", + updatedAt: "2026-11-18T16:30:00.000Z", + acceptedBy: "mona", + evidence: [supportingEvidence, secondSupportingEvidence], + }, + { + id: "learning-rejected", + title: "Use placeholder text as a label", + guidance: "Rely on placeholder text to identify each field.", + status: "rejected", + topic: "Accessibility", + updatedAt: "2026-11-16T09:00:00.000Z", + rejectionReason: "Placeholder text is not a persistent label.", + evidence: [placeholderEvidence], + }, + ], + activity: [ + { + date: "2026-11-19", + runState: "succeeded", + startedAt: "2026-11-19T15:00:00.000Z", + startedBy: "octocat", + commentsAnalyzed: 12, + commentsTagged: 4, + suggestions: 2, + }, + { + date: "2026-11-18", + runState: "succeeded", + startedAt: "2026-11-18T15:00:00.000Z", + startedBy: "octocat", + commentsAnalyzed: 6, + commentsTagged: 8, + suggestions: 1, + }, + ], + today: "2026-11-20", + agentConnectionPath: "/settings/agents?repositoryId=2001", + } +} + +function renderPrototype(data: LearningsLibraryPrototypeData) { + return render(, { wrapper: HubThemeProvider }) +} + +function getSectionControl(name: string) { + const matcher = new RegExp(`^${name}\\b`, "i") + return ( + screen.queryByRole("tab", { name: matcher }) ?? + screen.queryByRole("button", { name: matcher }) ?? + screen.getByRole("link", { name: matcher }) + ) +} + +function selectSection(name: string) { + fireEvent.click(getSectionControl(name)) +} + +function getLearning(title: string) { + const row = screen.getByRole("button", { name: title }).closest("tr") + if (!row) throw new Error(`Expected "${title}" to be in a learning row`) + return row +} + +describe("LearningsLibraryPrototype()", () => { + it("links only Hub admins to evaluation settings", () => { + const data = { + ...createPrototypeData(true), + evaluationSettingsPath: "/settings/evaluations?repositoryId=2001", + } + const { rerender } = renderPrototype(data) + + expect(screen.queryByRole("link", { name: "Evaluation settings" })).not.toBeInTheDocument() + + rerender() + + expect(screen.getByRole("link", { name: "Evaluation settings" })).toHaveAttribute( + "href", + "/settings/evaluations?repositoryId=2001", + ) + }) + + it("lets a member browse each status without exposing decision controls", () => { + renderPrototype(createPrototypeData(false)) + + expect(screen.getByRole("heading", { name: "Learnings" })).toBeVisible() + expect(screen.queryByRole("button", { name: "Back to learnings" })).not.toBeInTheDocument() + const connectLink = screen.getByRole("link", { name: "Connect an agent" }) + expect(connectLink).toHaveAttribute("href", "/settings/agents?repositoryId=2001") + expect(connectLink.closest("p")).toHaveTextContent( + "Shared guidance from your team’s prototype reviews.", + ) + + for (const [section, title] of [ + ["Suggested", "Keep form labels visible"], + ["Active", "Make actions clear"], + ["Rejected", "Use placeholder text as a label"], + ] as const) { + selectSection(section) + const learning = getLearning(title) + expect(learning).toBeVisible() + expect( + screen.queryByRole("button", { + name: /^(accept|reject|approve|dismiss|restore|retire)(\b|:)/i, + }), + ).not.toBeInTheDocument() + if (section === "Active") { + fireEvent.click(within(learning).getByRole("button", { name: title })) + expect(screen.queryByRole("switch", { name: "Share across Hub" })).not.toBeInTheDocument() + fireEvent.click(screen.getByRole("button", { name: "Back to learnings" })) + } + } + + selectSection("Suggested") + fireEvent.click(screen.getByRole("button", { name: "Keep form labels visible" })) + expect( + screen.queryByRole("button", { name: /accept learning|reject suggestion/i }), + ).not.toBeInTheDocument() + }) + + it("lets a Hub admin share accepted guidance with every repository and stop sharing", () => { + const data = createPrototypeData(true) + data.isHubAdmin = true + data.hubRepositoryCount = 2 + renderPrototype(data) + selectSection("Suggested") + fireEvent.click(screen.getByRole("button", { name: "Keep form labels visible" })) + expect(screen.queryByRole("switch", { name: "Share across Hub" })).not.toBeInTheDocument() + fireEvent.click(screen.getByRole("button", { name: "Back to learnings" })) + + selectSection("Active") + fireEvent.click(screen.getByRole("button", { name: "Make actions clear" })) + const shareSwitch = screen.getByRole("switch", { name: "Share across Hub" }) + expect(shareSwitch).toHaveAccessibleDescription("Read-only in every repository") + expect(shareSwitch).not.toBeChecked() + + fireEvent.click(shareSwitch) + expect(shareSwitch).toBeChecked() + expect(screen.getByRole("region", { name: "Notifications" })).toHaveTextContent( + "Shared across Hub", + ) + + fireEvent.click(shareSwitch) + expect(shareSwitch).not.toBeChecked() + expect(screen.getByRole("region", { name: "Notifications" })).toHaveTextContent( + "Stopped sharing across Hub", + ) + }) + + it("keeps shared guidance live when its source admin edits it", () => { + const data = createPrototypeData(true) + data.isHubAdmin = true + data.hubRepositoryCount = 2 + const sharedLearning = data.learnings.find((learning) => learning.id === "learning-active") + if (!sharedLearning) throw new Error("Expected an active learning") + sharedLearning.sharedAcrossHub = true + renderPrototype(data) + + selectSection("Active") + fireEvent.click(screen.getByRole("button", { name: "Make actions clear" })) + expect(screen.getByRole("switch", { name: "Share across Hub" })).toBeChecked() + fireEvent.click(screen.getByRole("button", { name: "Edit learning" })) + + const dialog = screen.getByRole("dialog", { name: "Edit learning" }) + fireEvent.change(within(dialog).getByRole("textbox", { name: "Title" }), { + target: { value: "Make primary actions clear" }, + }) + fireEvent.change(within(dialog).getByRole("textbox", { name: "Guidance" }), { + target: { value: "Use a clear label for the main action." }, + }) + fireEvent.click(within(dialog).getByRole("button", { name: "Save changes" })) + + expect(screen.getByRole("heading", { name: "Make primary actions clear" })).toBeVisible() + expect(screen.getByText("Use a clear label for the main action.")).toBeVisible() + const shareSwitch = screen.getByRole("switch", { name: "Share across Hub" }) + expect(shareSwitch).toBeChecked() + + fireEvent.click(shareSwitch) + expect(shareSwitch).not.toBeChecked() + expect(screen.getByRole("region", { name: "Notifications" })).toHaveTextContent( + "Stopped sharing across Hub", + ) + }) + + it("hides Hub sharing when Hub has only one repository", () => { + const data = createPrototypeData(true) + data.isHubAdmin = true + data.hubRepositoryCount = 1 + renderPrototype(data) + selectSection("Active") + fireEvent.click(screen.getByRole("button", { name: "Make actions clear" })) + + expect(screen.queryByRole("switch", { name: "Share across Hub" })).not.toBeInTheDocument() + }) + + it("shows shared guidance as read-only and names its source repository", () => { + const data = createPrototypeData(true) + data.isHubAdmin = true + data.hubRepositoryCount = 2 + data.learnings = [ + { + ...data.learnings.find((learning) => learning.id === "learning-active")!, + title: "Make primary actions easier to scan", + guidance: "Use one primary button, with a specific label that explains its result.", + sharedFrom: { repositoryName: "github/prototype" }, + }, + ] + renderPrototype(data) + + selectSection("Active") + fireEvent.click(screen.getByRole("button", { name: "Make primary actions easier to scan" })) + + expect( + screen.getByText("Shared from github/prototype · Read-only in this repository."), + ).toBeVisible() + expect( + screen.getByText("Use one primary button, with a specific label that explains its result."), + ).toBeVisible() + expect( + screen.queryByRole("button", { + name: /^(accept|reject|edit|apply|dismiss|restore|retire)/i, + }), + ).not.toBeInTheDocument() + expect(screen.queryByRole("switch", { name: "Share across Hub" })).not.toBeInTheDocument() + }) + + it("explains when a source stops sharing a learning", () => { + const data = createPrototypeData(false) + data.sharedLearningNotice = + "github/prototype stopped sharing “Make primary actions easier to scan.” It is no longer available here." + data.learnings = data.learnings.filter((learning) => learning.id !== "learning-active") + renderPrototype(data) + + selectSection("Active") + + const notice = screen.getByText(data.sharedLearningNotice) + expect(notice.closest('[role="status"]')).not.toBeNull() + expect(screen.getByRole("heading", { name: "No active learnings" })).toBeVisible() + expect(screen.queryByRole("button", { name: "Make actions clear" })).not.toBeInTheDocument() + }) + + it("keeps the learnings introduction when agent setup is unavailable", () => { + const data = createPrototypeData(false) + data.agentConnectionPath = undefined + renderPrototype(data) + + expect(screen.getByText("Shared guidance from your team’s prototype reviews.")).toBeVisible() + expect(screen.queryByRole("link", { name: "Connect an agent" })).not.toBeInTheDocument() + }) + + it("shows a focus indicator after keyboard activation but not pointer activation", () => { + renderPrototype(createPrototypeData(false)) + selectSection("Active") + + const learningButton = screen.getByRole("button", { name: "Make actions clear" }) + fireEvent.click(learningButton, { detail: 1 }) + const title = screen.getByRole("heading", { name: "Make actions clear" }) + expect(document.activeElement).toBe(title) + expect(title).not.toHaveClass("learning-library__page-title--focus-visible") + + fireEvent.click(screen.getByRole("button", { name: "Back to learnings" }), { detail: 1 }) + fireEvent.click(screen.getByRole("button", { name: "Make actions clear" }), { detail: 0 }) + const reopenedTitle = screen.getByRole("heading", { name: "Make actions clear" }) + expect(document.activeElement).toBe(reopenedTitle) + expect(reopenedTitle).toHaveClass("learning-library__page-title--focus-visible") + }) + + it("accepts suggestions, requires a rejection reason, and lets an admin accept a rejected learning", () => { + const fetch = vi.fn() + vi.stubGlobal("fetch", fetch) + renderPrototype(createPrototypeData(true)) + + selectSection("Suggested") + const suggestion = getLearning("Keep form labels visible") + fireEvent.click(within(suggestion).getByRole("button", { name: "Keep form labels visible" })) + expect(document.activeElement).toBe( + screen.getByRole("heading", { name: "Keep form labels visible" }), + ) + expect(screen.queryByRole("button", { name: "Edit learning" })).not.toBeInTheDocument() + const pageHeader = screen + .getByRole("heading", { name: "Keep form labels visible" }) + .closest("header") + if (!pageHeader) throw new Error("Expected the learning title in the page header") + expect(within(pageHeader).getByRole("button", { name: "Accept learning" })).toBeVisible() + expect(within(pageHeader).getByRole("button", { name: "Reject suggestion" })).toBeVisible() + fireEvent.click(screen.getByRole("button", { name: /accept learning/i })) + + expect(document.activeElement).toBe(getSectionControl("Active")) + selectSection("Active") + const acceptedLearning = getLearning("Keep form labels visible") + expect(acceptedLearning).toBeVisible() + expect(within(acceptedLearning).getByText("November 20, 2026")).toHaveAttribute( + "datetime", + "2026-11-20T12:00:00.000Z", + ) + selectSection("Suggested") + expect( + screen.queryByRole("button", { name: "Keep form labels visible" }), + ).not.toBeInTheDocument() + + const rejectionTitle = "Rely on placeholder text" + selectSection("Suggested") + const suggestionToReject = getLearning(rejectionTitle) + fireEvent.click(within(suggestionToReject).getByRole("button", { name: rejectionTitle })) + fireEvent.click(screen.getByRole("button", { name: /reject suggestion/i })) + + const dialog = screen.getByRole("dialog", { name: "Reject learning" }) + const reason = within(dialog).getByRole("textbox", { name: "Why reject this learning?" }) + expect(reason).toBeRequired() + const rejectionForm = reason.closest("form") + if (!rejectionForm) throw new Error("Expected the rejection reason form") + fireEvent.submit(rejectionForm) + expect(within(dialog).getByRole("alert")).toHaveTextContent( + "Enter a reason to reject this learning.", + ) + + fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" })) + expect(screen.queryByRole("dialog", { name: "Reject learning" })).not.toBeInTheDocument() + expect(screen.getByRole("heading", { name: rejectionTitle })).toBeVisible() + + fireEvent.click(screen.getByRole("button", { name: /reject suggestion/i })) + const reopenedDialog = screen.getByRole("dialog", { name: "Reject learning" }) + const completedReason = within(reopenedDialog).getByRole("textbox", { + name: "Why reject this learning?", + }) + fireEvent.change(completedReason, { + target: { value: "The placeholder disappears while typing." }, + }) + const completedForm = completedReason.closest("form") + if (!completedForm) throw new Error("Expected the rejection reason form") + fireEvent.submit(completedForm) + + const backToLearnings = screen.queryByRole("button", { name: /learnings/i }) + if (backToLearnings) fireEvent.click(backToLearnings) + expect(document.activeElement).toBe(getSectionControl("Rejected")) + const rejectedLearning = getLearning(rejectionTitle) + expect(rejectedLearning).toBeVisible() + expect(within(rejectedLearning).getByText("1 review comment")).toBeVisible() + expect(within(rejectedLearning).getByText("November 20, 2026")).toHaveAttribute( + "datetime", + "2026-11-20T12:00:00.000Z", + ) + fireEvent.click(within(rejectedLearning).getByRole("button", { name: rejectionTitle })) + expect(document.activeElement).toBe(screen.getByRole("heading", { name: rejectionTitle })) + expect(screen.getByText("The placeholder disappears while typing.")).toBeVisible() + expect(screen.getByText("1 review comment")).toBeVisible() + fireEvent.click(screen.getByRole("button", { name: /learnings/i })) + expect(document.activeElement).toBe( + within(getLearning(rejectionTitle)).getByRole("button", { name: rejectionTitle }), + ) + fireEvent.click( + within(getLearning(rejectionTitle)).getByRole("button", { name: rejectionTitle }), + ) + fireEvent.click(screen.getByRole("button", { name: "Accept learning" })) + selectSection("Active") + fireEvent.click( + within(getLearning(rejectionTitle)).getByRole("button", { name: rejectionTitle }), + ) + expect(screen.getByRole("region", { name: "Decision history" })).toHaveTextContent( + "The placeholder disappears while typing.", + ) + expect(screen.getByText("Not evaluated yet.")).toBeVisible() + expect(fetch).not.toHaveBeenCalled() + }) + + it("does not describe insufficient evidence as a negative outcome", () => { + const data = createPrototypeData(true) + const activeLearning = data.learnings.find((learning) => learning.status === "active") + if (!activeLearning) throw new Error("Expected an active learning") + activeLearning.outcomeAssessment = { + version: 1, + status: "insufficient-evidence", + outcomes: [], + } + renderPrototype(data) + selectSection("Active") + fireEvent.click(screen.getByRole("button", { name: "Make actions clear" })) + + const outcomes = screen.getByRole("region", { name: "Observed outcomes" }) + expect( + within(outcomes).getByText("Not enough evidence yet. This is not a negative result."), + ).toBeVisible() + expect(within(outcomes).queryByText("Not evaluated yet.")).not.toBeInTheDocument() + }) + + it("keeps a shared learning and its outcomes when applying a suggested update", () => { + const data = createPrototypeData(true) + data.isHubAdmin = true + data.hubRepositoryCount = 2 + const activeLearning = data.learnings.find((learning) => learning.status === "active") + if (!activeLearning) throw new Error("Expected an active learning") + activeLearning.sharedAcrossHub = true + activeLearning.outcomeAssessment = { + version: 1, + status: "observed", + outcomes: [ + { + id: "outcome-automated", + prototypeName: "Settings", + buildNumber: 7, + buildPath: "/repositories/2001/prototypes/22?build=7", + result: "supports", + source: "automated", + summary: "The primary action stands out beside secondary controls.", + evaluatedAt: "2026-11-17T16:30:00.000Z", + }, + { + id: "outcome-desktop", + prototypeName: "Settings", + buildNumber: 8, + buildPath: "/repositories/2001/prototypes/22?build=8", + result: "supports", + source: "reviewer-confirmed", + summary: "The primary action is easy to identify.", + evaluatedAt: "2026-11-18T16:30:00.000Z", + beforeScreenshotUrl: "/before-settings.png", + afterScreenshotUrl: "/after-settings.png", + }, + ], + } + activeLearning.updateSuggestion = { + title: "Keep one primary action visible", + guidance: "Keep the primary action clear on narrow screens too.", + reason: "A mobile review found the sticky action covered a field.", + } + renderPrototype(data) + selectSection("Active") + + expect(getLearning("Make actions clear")).toHaveTextContent("Update suggested") + fireEvent.click(screen.getByRole("button", { name: "Make actions clear" })) + const suggestedUpdate = screen.getByRole("region", { name: "Suggested update" }) + expect(suggestedUpdate).toHaveTextContent( + "A mobile review found the sticky action covered a field.", + ) + expect(within(suggestedUpdate).getAllByRole("deletion")[0]).toHaveTextContent( + "Removed: Make actions clear", + ) + expect(within(suggestedUpdate).getAllByRole("insertion")[0]).toHaveTextContent( + "Added: Keep one primary action visible", + ) + const observedOutcomes = screen.getByRole("region", { name: "Observed outcomes" }) + expect(within(observedOutcomes).getAllByRole("listitem")).toHaveLength(2) + expect(observedOutcomes).toHaveTextContent("Automated assessment") + expect(observedOutcomes).toHaveTextContent("Reviewer-confirmed") + expect(screen.getByRole("switch", { name: "Share across Hub" })).toBeChecked() + expect(screen.getByRole("link", { name: "Settings, Build 8" })).toHaveAttribute( + "href", + "/repositories/2001/prototypes/22?build=8", + ) + expect( + screen.getByRole("link", { name: "Before screenshot of Settings, Build 8" }), + ).toHaveAttribute("href", "/before-settings.png") + expect( + screen.getByRole("link", { name: "After screenshot of Settings, Build 8" }), + ).toHaveAttribute("href", "/after-settings.png") + fireEvent.click(screen.getByRole("button", { name: "Apply update" })) + + expect(screen.getByRole("heading", { name: "Keep one primary action visible" })).toBeVisible() + expect(screen.getByText("Keep the primary action clear on narrow screens too.")).toBeVisible() + expect(screen.getByText("Not evaluated yet.")).toBeVisible() + expect(screen.getByRole("switch", { name: "Share across Hub" })).toBeChecked() + fireEvent.click(screen.getByText("Earlier guidance")) + expect(screen.getByRole("link", { name: "Settings, Build 8" })).toHaveAttribute( + "href", + "/repositories/2001/prototypes/22?build=8", + ) + expect(screen.queryByRole("region", { name: "Suggested update" })).not.toBeInTheDocument() + expect(screen.getByRole("region", { name: "Observed outcomes" })).toBeVisible() + }) + + it("lets an admin edit and apply a proposed update", () => { + const data = createPrototypeData(true) + const activeLearning = data.learnings.find((learning) => learning.status === "active") + if (!activeLearning) throw new Error("Expected an active learning") + activeLearning.updateSuggestion = { + title: "Use direct action labels", + guidance: "Describe the result on each primary action.", + reason: "Recent evaluations suggest clearer action labels.", + } + renderPrototype(data) + selectSection("Active") + fireEvent.click(screen.getByRole("button", { name: "Make actions clear" })) + fireEvent.click(screen.getByRole("button", { name: "Edit proposed update" })) + const dialog = screen.getByRole("dialog", { name: "Edit proposed update" }) + fireEvent.change(within(dialog).getByRole("textbox", { name: "Proposed title" }), { + target: { value: "Make primary actions clear" }, + }) + fireEvent.change(within(dialog).getByRole("textbox", { name: "Proposed guidance" }), { + target: { value: "Use short labels that describe the result of each action." }, + }) + fireEvent.click(within(dialog).getByRole("button", { name: "Apply edited update" })) + + expect(screen.queryByRole("dialog")).not.toBeInTheDocument() + expect(screen.getByRole("heading", { name: "Make primary actions clear" })).toBeVisible() + expect( + screen.getByText("Use short labels that describe the result of each action."), + ).toBeVisible() + expect(screen.queryByRole("region", { name: "Suggested update" })).not.toBeInTheDocument() + }) + + it("dismisses a proposed update without changing the active learning", () => { + const data = createPrototypeData(true) + const activeLearning = data.learnings.find((learning) => learning.status === "active") + if (!activeLearning) throw new Error("Expected an active learning") + activeLearning.updateSuggestion = { + title: "Use direct action labels", + guidance: "Describe the result on each primary action.", + reason: "Recent evaluations suggest clearer action labels.", + } + renderPrototype(data) + selectSection("Active") + fireEvent.click(screen.getByRole("button", { name: "Make actions clear" })) + fireEvent.click(screen.getByRole("button", { name: "Dismiss update" })) + + expect(screen.getByRole("heading", { name: "Make actions clear" })).toBeVisible() + expect(screen.getByText("Use clear labels for primary actions.")).toBeVisible() + expect(screen.queryByRole("region", { name: "Suggested update" })).not.toBeInTheDocument() + expect(screen.getByRole("status")).toHaveTextContent( + "Suggested learning update dismissed. The active learning is unchanged.", + ) + expect(screen.getByRole("button", { name: "Reject learning" })).toBeVisible() + }) + + it("edits a learning in a modal and discards changes when cancelled", () => { + renderPrototype(createPrototypeData(true)) + selectSection("Active") + const learning = getLearning("Make actions clear") + fireEvent.click(within(learning).getByRole("button", { name: "Make actions clear" })) + fireEvent.click(screen.getByRole("button", { name: /edit learning/i })) + + const cancelledDialog = screen.getByRole("dialog", { name: "Edit learning" }) + fireEvent.change(within(cancelledDialog).getByRole("textbox", { name: "Title" }), { + target: { value: "Discarded title" }, + }) + fireEvent.click(within(cancelledDialog).getByRole("button", { name: "Cancel" })) + expect(screen.queryByRole("dialog", { name: "Edit learning" })).not.toBeInTheDocument() + expect(screen.getByRole("heading", { name: "Make actions clear" })).toBeVisible() + + fireEvent.click(screen.getByRole("button", { name: /edit learning/i })) + const dialog = screen.getByRole("dialog", { name: "Edit learning" }) + fireEvent.change(within(dialog).getByRole("textbox", { name: "Title" }), { + target: { value: "Make primary actions clear" }, + }) + fireEvent.change(within(dialog).getByRole("textbox", { name: "Guidance" }), { + target: { value: "Use short, specific labels for primary actions." }, + }) + fireEvent.click(within(dialog).getByRole("button", { name: /save changes/i })) + + expect(screen.queryByRole("dialog", { name: "Edit learning" })).not.toBeInTheDocument() + expect(screen.getByRole("heading", { name: "Make primary actions clear" })).toBeVisible() + expect(screen.getByText("Use short, specific labels for primary actions.")).toBeVisible() + expect(screen.getByText("November 20, 2026", { selector: "time" })).toHaveAttribute( + "datetime", + "2026-11-20T12:00:00.000Z", + ) + }) + + it("updates the activity measure and exposes the selected run's separate counts and status", () => { + renderPrototype(createPrototypeData(false)) + const activityGrid = screen.getByRole("group", { + name: "Daily learning activity for 2026", + }) + // Every day from Jan 1 to today (November 20) can be inspected. + expect(within(activityGrid).getAllByRole("button")).toHaveLength(324) + const day = within(activityGrid).getByRole("button", { name: /November 19, 2026/i }) + fireEvent.click(day) + const analyzedLabel = day.getAttribute("aria-label") + + const metricControls = screen.getByRole("group", { name: "Activity measure" }) + const analyzedMetric = within(metricControls).getByRole("button", { + name: /comments analyzed/i, + }) + fireEvent.click(analyzedMetric) + expect(analyzedMetric).toHaveAttribute("aria-pressed", "true") + expect( + screen.getByText("Comments analyzed", { selector: "dt" }).parentElement, + ).toHaveTextContent("12") + expect( + screen.getByText("Comments categorized", { selector: "dt" }).parentElement, + ).toHaveTextContent("4") + expect(screen.getByText("Suggestions", { selector: "dt" }).parentElement).toHaveTextContent("2") + expect(screen.getByText(/Run completed/)).toBeVisible() + const analyzedIntensity = day.style.getPropertyValue("--activity-level") + + const categorizedMetric = within(metricControls).getByRole("button", { + name: /comments categorized/i, + }) + fireEvent.click(categorizedMetric) + expect(categorizedMetric).toHaveAttribute("aria-pressed", "true") + const categorizedDay = within(activityGrid).getByRole("button", { + name: /November 19, 2026/i, + }) + expect(categorizedDay.style.getPropertyValue("--activity-level")).not.toBe(analyzedIntensity) + expect(categorizedDay.getAttribute("aria-label")).not.toBe(analyzedLabel) + expect(categorizedDay).toHaveAccessibleName(/4 comments categorized/i) + }) + + it("lays out the calendar and supports keyboard date selection", () => { + renderPrototype(createPrototypeData(false)) + const calendar = screen.getByRole("group", { name: "Daily learning activity for 2026" }) + expect(within(calendar).getAllByRole("button", { name: /^September / })).toHaveLength(30) + expect(within(calendar).getAllByRole("button", { name: /^October / })).toHaveLength(31) + expect(within(calendar).getAllByRole("button", { name: /^November / })).toHaveLength(20) + expect(within(calendar).queryByRole("button", { name: /2025,/ })).not.toBeInTheDocument() + expect(within(calendar).getByText("Jan")).toBeInTheDocument() + expect(within(calendar).getByText("Dec")).toBeInTheDocument() + + const thursday = within(calendar).getByRole("button", { name: /^January 1, 2026,/ }) + const saturday = within(calendar).getByRole("button", { name: /^October 31, 2026,/ }) + const sunday = within(calendar).getByRole("button", { name: /^November 1, 2026,/ }) + const wednesday = within(calendar).getByRole("button", { name: /^November 18, 2026,/ }) + const firstWeek = thursday.parentElement + const octoberWeek = saturday.parentElement + const novemberWeek = sunday.parentElement + const lastWeek = wednesday.parentElement + if (!firstWeek || !octoberWeek || !novemberWeek || !lastWeek) { + throw new Error("Expected calendar weeks") + } + + // Each column has a month label followed by Sunday through Saturday. + expect(firstWeek.children[5]).toBe(thursday) + expect(octoberWeek.children[7]).toBe(saturday) + expect(octoberWeek.nextElementSibling).toBe(novemberWeek) + expect(novemberWeek.children[1]).toBe(sunday) + expect(lastWeek.children[4]).toBe(wednesday) + expect(within(calendar).getByRole("button", { name: /^November 19, 2026,/ })).toHaveAttribute( + "aria-pressed", + "true", + ) + expect( + within(calendar).getByRole("button", { name: /^November 17, 2026,.*no run$/ }), + ).toBeVisible() + + const dateButtons = within(calendar).getAllByRole("button") + expect(dateButtons.filter((button) => button.tabIndex === 0)).toHaveLength(1) + expect(dateButtons.filter((button) => button.tabIndex === -1)).toHaveLength(323) + + fireEvent.click(wednesday) + expect(wednesday).toHaveAttribute("aria-pressed", "true") + fireEvent.keyDown(wednesday, { key: "ArrowDown" }) + const novemberNineteen = within(calendar).getByRole("button", { + name: /^November 19, 2026,/, + }) + expect(novemberNineteen).toHaveAttribute("aria-pressed", "true") + expect(document.activeElement).toBe(novemberNineteen) + fireEvent.keyDown(novemberNineteen, { key: "ArrowRight" }) + expect(document.activeElement).toBe(novemberNineteen) + }) + + it("pages long lists and starts each status on its first page", () => { + const data = createPrototypeData(false) + const [template, , ...otherStatuses] = data.learnings + if (!template) throw new Error("Expected a suggestion to copy") + const suggestions = Array.from({ length: 30 }, (_, index) => ({ + ...template, + id: `learning-page-${index + 1}`, + title: `Paged suggestion ${index + 1}`, + })) + renderPrototype({ ...data, learnings: [...suggestions, ...otherStatuses] }) + + const pages = screen.getByRole("navigation", { name: "Learnings pages" }) + expect(screen.getAllByRole("button", { name: /^Paged suggestion/ })).toHaveLength(25) + expect(screen.queryByRole("button", { name: "Paged suggestion 26" })).not.toBeInTheDocument() + + // Brand marks the last page "Page 2...", so match the start of its name. + fireEvent.click(within(pages).getByRole("button", { name: /^Page 2\b/ })) + expect(screen.getAllByRole("button", { name: /^Paged suggestion/ })).toHaveLength(5) + expect(screen.getByRole("button", { name: "Paged suggestion 26" })).toBeVisible() + expect(within(pages).getByRole("button", { name: /^Page 2\b/ })).toHaveAttribute( + "aria-current", + "page", + ) + + selectSection("Active") + expect(screen.queryByRole("navigation", { name: "Learnings pages" })).not.toBeInTheDocument() + selectSection("Suggested") + expect(screen.getByRole("button", { name: "Paged suggestion 1" })).toBeVisible() + }) + + it("shows review comments in one quiet section and links to their source reviews", () => { + const data = createPrototypeData(false) + const activeLearning = data.learnings.find((learning) => learning.status === "active") + if (!activeLearning) throw new Error("Expected an active learning") + activeLearning.evidence = activeLearning.evidence.map((comment) => ({ + ...comment, + authorLogin: "octocat", + prototypeName: "Checkout refresh", + })) + renderPrototype(data) + selectSection("Active") + const learning = getLearning("Make actions clear") + expect(within(learning).getByText("2 review comments")).toBeVisible() + fireEvent.click(within(learning).getByRole("button", { name: "Make actions clear" })) + + expect(screen.getByText("The visible label made the form easier to scan.")).toBeVisible() + expect(screen.getByText("The Save button does not stand out beside Cancel.")).toBeVisible() + expect(screen.getByRole("region", { name: "Review comments" })).toBeVisible() + expect(screen.getByRole("heading", { name: "Review comments" })).toBeVisible() + expect( + screen.queryByRole("heading", { + name: /Review evidence|Supporting comments|Different views/, + }), + ).not.toBeInTheDocument() + expect(screen.getByText(/Category: Content/)).toBeVisible() + expect(screen.getByText("2 review comments")).toBeVisible() + expect( + screen.getAllByRole("link", { name: /Build [58]/i }).map((link) => link.getAttribute("href")), + ).toEqual([ + "https://github.com/github/prototype/pull/42#discussion_r100", + "https://github.com/github/prototype/pull/43#discussion_r101", + ]) + expect(screen.queryByRole("img")).not.toBeInTheDocument() + }) +}) diff --git a/hub/client/pages/learnings-library-prototype/index.tsx b/hub/client/pages/learnings-library-prototype/index.tsx new file mode 100644 index 000000000..9c014a0da --- /dev/null +++ b/hub/client/pages/learnings-library-prototype/index.tsx @@ -0,0 +1,1303 @@ +import { + useLayoutEffect, + useMemo, + useRef, + useState, + type CSSProperties, + type KeyboardEvent, + type SyntheticEvent, +} from "react" +import { + AlertIcon, + ArrowLeftIcon, + CheckCircleIcon, + CircleIcon, + LightBulbIcon, + PlugIcon, + XCircleIcon, + type Icon, +} from "@primer/octicons-react" +import { + Button, + FormControl, + Heading, + Label, + Pagination, + Text, + TextInput, + Textarea, + Tooltip, +} from "@primer/react-brand" + +import { HubAlert } from "@components/hub-alert" +import { HubCounter } from "@components/hub-counter" +import { HubIconButton } from "@components/hub-icon-button" +import { HubSwitch } from "@components/hub-switch" +import { HubToast } from "@components/hub-toast" +import { HubVisuallyHidden } from "@components/hub-visually-hidden" +import { CanvasDialog } from "@components/prototype-canvas-dialog" +import { diffWords } from "@utils/diff-words" + +import type { + LearningActivityDay, + LearningEvidence, + LearningLifecycle, + LearningOutcome, + LearningRecord, + LearningsLibraryPrototypeData, +} from "./types" +import "./styles.css" + +type ActivityMetric = "commentsAnalyzed" | "commentsTagged" | "suggestions" + +const shareHint = "Read-only in every repository" +// Matches GitHub's pull request list so long lists page the way people expect. +const pageSize = 25 + +const lifecycleLabels: Record = { + suggested: "Suggested", + active: "Active", + rejected: "Rejected", +} + +// Mirrors GitHub's pull request states so people can read status at a glance. +const lifecycleIcons: Record = { + suggested: LightBulbIcon, + active: CheckCircleIcon, + rejected: XCircleIcon, +} + +/** Renders a learning's state icon; Brand labels need an element, not a component. */ +function LifecycleIcon({ status, className }: { status: LearningLifecycle; className?: string }) { + const StatusIcon = lifecycleIcons[status] + return +} + +const lifecycleLabelColors = { + suggested: "default", + active: "green", + rejected: "red", +} as const satisfies Record + +const outcomeResultLabels: Record = { + supports: "Supports the guidance", + concern: "Possible concern", + inconclusive: "Inconclusive", +} + +// A result icon sets outcomes apart from review comments, which lead with an avatar. +const outcomeResultIcons: Record = { + supports: CheckCircleIcon, + concern: AlertIcon, + inconclusive: CircleIcon, +} + +function outcomeSourceLabel(source: LearningOutcome["source"]) { + return source === "automated" ? "Automated assessment" : "Reviewer-confirmed" +} + +const activityMetrics: Array<{ key: ActivityMetric; label: string }> = [ + { key: "commentsAnalyzed", label: "Comments analyzed" }, + { key: "commentsTagged", label: "Comments categorized" }, + { key: "suggestions", label: "Suggestions" }, +] + +function dayLabel(date: string, options: Intl.DateTimeFormatOptions = { dateStyle: "long" }) { + return new Intl.DateTimeFormat("en-US", { ...options, timeZone: "UTC" }).format( + new Date(`${date}T00:00:00.000Z`), + ) +} + +function activityValue(day: LearningActivityDay, metric: ActivityMetric) { + return day[metric] +} + +function activityMetricLabel(metric: ActivityMetric) { + if (metric === "commentsAnalyzed") return "Comments analyzed" + if (metric === "commentsTagged") return "Comments categorized" + return "Suggestions" +} + +function countLabel(value: number, singular: string) { + return `${value} ${singular}${value === 1 ? "" : "s"}` +} + +/** A square in the year grid. Days still ahead have no activity to show yet. */ +type CalendarCell = { date: string; day: LearningActivityDay | null } + +function quietDay(date: string): LearningActivityDay { + return { + date, + runState: "none", + startedAt: null, + startedBy: null, + commentsAnalyzed: 0, + commentsTagged: 0, + suggestions: 0, + } +} + +/** + * Lays out today's UTC calendar year in Sunday-first week columns, like GitHub's + * contribution graph. Past days without a run read as "no run", while days still ahead + * stay blank so nobody mistakes them for quiet days. + */ +function buildCalendarYear(activity: LearningActivityDay[], today: string) { + const year = today.slice(0, 4) + const daysByDate = new Map(activity.map((day) => [day.date, day])) + const cursor = new Date(`${year}-01-01T00:00:00.000Z`) + cursor.setUTCDate(cursor.getUTCDate() - cursor.getUTCDay()) + const end = new Date(`${year}-12-31T00:00:00.000Z`).getTime() + const weeks: Array> = [] + + while (cursor.getTime() <= end) { + weeks.push( + Array.from({ length: 7 }, () => { + const date = cursor.toISOString().slice(0, 10) + cursor.setUTCDate(cursor.getUTCDate() + 1) + if (!date.startsWith(`${year}-`)) return null + if (date > today) return { date, day: null } + return { date, day: daysByDate.get(date) ?? quietDay(date) } + }), + ) + } + return weeks +} + +function firstDateOf(week: Array | undefined) { + return week?.find((cell) => cell !== null)?.date +} + +/** + * Names each month above the first week that starts in it, like GitHub's contribution + * graph. When two months start one week apart, the earlier name is dropped so the + * short labels never overlap. + */ +function monthLabelsByWeek(weeks: Array>) { + const labels = weeks.map((week, index) => { + const firstDate = firstDateOf(week) + const previousDate = firstDateOf(weeks[index - 1]) + if (!firstDate) return "" + if (previousDate && firstDate.slice(0, 7) === previousDate.slice(0, 7)) return "" + return dayLabel(firstDate, { month: "short" }) + }) + return labels.map((label, index) => (label && labels[index + 1] ? "" : label)) +} + +/** + * Shows a suggested edit inline so admins can see what changes without comparing two + * blocks of text. Screen readers hear "Removed" and "Added" because color and + * strikethrough alone are not announced. Spaces at the edges of a change stay outside + * the highlight so it hugs the words. + */ +function diffText(before: string, after: string) { + return diffWords(before, after).map((part, index) => { + const [, leading = "", text = "", trailing = ""] = /^(\s*)(.*?)(\s*)$/su.exec(part.text) ?? [] + if (part.kind === "unchanged" || !text) return {part.text} + + const label = part.kind === "removed" ? "Removed: " : "Added: " + const Mark = part.kind === "removed" ? "del" : "ins" + return ( + + {leading} + + {label} + {text} + + {trailing} + + ) + }) +} + +/** + * Replaces a learning's wording and keeps the old wording, with its outcomes, under + * Earlier guidance. Outcomes describe the wording that builds actually used, so they + * must not carry over to new text. + */ +function reviseGuidance( + learning: LearningRecord, + title: string, + guidance: string, + updatedAt: string, +): LearningRecord { + const version = learning.version ?? 1 + return { + ...learning, + versionHistory: [ + ...(learning.versionHistory ?? []), + { + version, + title: learning.title, + guidance: learning.guidance, + updatedAt: learning.updatedAt, + ...(learning.outcomeAssessment ? { outcomeAssessment: learning.outcomeAssessment } : {}), + }, + ], + version: version + 1, + title, + guidance, + updatedAt, + outcomeAssessment: undefined, + } +} + +function evidenceList(evidence: LearningEvidence[]) { + return ( +
      + {evidence.map((item) => ( +
    • +
      + + @{item.authorLogin} + + + {item.prototypeName} · Build {item.buildNumber} + + + +
      + + {item.body ?? "The author deleted this review comment."} + +
    • + ))} +
    + ) +} + +function ActivityGrid({ activity, today }: { activity: LearningActivityDay[]; today: string }) { + const [metric, setMetric] = useState("commentsAnalyzed") + const weeks = useMemo(() => buildCalendarYear(activity, today), [activity, today]) + const monthLabels = useMemo(() => monthLabelsByWeek(weeks), [weeks]) + const pastDays = weeks.flat().flatMap((cell) => (cell?.day ? [cell.day] : [])) + const maximum = Math.max(1, ...pastDays.map((day) => activityValue(day, metric))) + const [selectedDate, setSelectedDate] = useState( + () => pastDays.findLast((day) => day.runState !== "none")?.date ?? today, + ) + const selectedDay = pastDays.find((day) => day.date === selectedDate) ?? null + const calendarRef = useRef(null) + const scrollerRef = useRef(null) + + function moveSelectedDate(event: KeyboardEvent) { + const offsets: Record = { + ArrowDown: 1, + ArrowLeft: -7, + ArrowRight: 7, + ArrowUp: -1, + } + const offset = offsets[event.key] + if (offset === undefined) return + + event.preventDefault() + const next = new Date(`${selectedDate}T00:00:00.000Z`) + next.setUTCDate(next.getUTCDate() + offset) + const nextDate = next.toISOString().slice(0, 10) + if (!nextDate.startsWith(`${today.slice(0, 4)}-`) || nextDate > today) return + + const nextButton = calendarRef.current?.querySelector( + `[data-date="${nextDate}"]`, + ) + if (!nextButton) return + setSelectedDate(nextDate) + nextButton.focus() + } + + // On a narrow screen recent weeks matter most, so open with the selected day in + // view. + useLayoutEffect(() => { + const scroller = scrollerRef.current + const selectedCell = scroller?.querySelector('[aria-pressed="true"]') + if (!scroller || !selectedCell) return + const overflow = + selectedCell.getBoundingClientRect().right - scroller.getBoundingClientRect().right + if (overflow > 0) { + scroller.scrollLeft += overflow + parseFloat(getComputedStyle(scroller).paddingRight) + } + }, []) + + return ( +
    +
    + + Learning activity + + + Daily runs in {today.slice(0, 4)} · UTC + +
    + +
    + {activityMetrics.map(({ key, label }) => ( + + ))} +
    + +
    +
    +
    + + {weeks.map((week, weekIndex) => ( +
    + + {week.map((cell, dayIndex) => { + if (!cell) { + return ( +
    + ))} +
    +
    + +
    + +
    +
    + + {selectedDay ? ( +
    +
    + + {dayLabel(selectedDay.date)} + + + {selectedDay.runState === "none" + ? "No learning run" + : `${selectedDay.runState === "failed" ? "Run failed" : "Run completed"}${ + selectedDay.startedBy ? ` · Started by ${selectedDay.startedBy}` : "" + }${ + selectedDay.startedAt + ? ` · ${new Intl.DateTimeFormat("en-US", { + hour: "numeric", + minute: "2-digit", + timeZone: "UTC", + timeZoneName: "short", + }).format(new Date(selectedDay.startedAt))}` + : "" + }`} + +
    +
    +
    +
    Comments analyzed
    +
    {selectedDay.commentsAnalyzed}
    +
    +
    +
    Comments categorized
    +
    {selectedDay.commentsTagged}
    +
    +
    +
    Suggestions
    +
    {selectedDay.suggestions}
    +
    +
    +
    + ) : null} +
    + ) +} + +/** + * Lets a repository team browse guidance and gives administrators a local decision + * prototype. + */ +export function LearningsLibraryPrototype({ data }: { data: LearningsLibraryPrototypeData }) { + const [learnings, setLearnings] = useState(data.learnings) + const [lifecycle, setLifecycle] = useState("suggested") + const [query, setQuery] = useState("") + const [page, setPage] = useState(1) + const [selectedId, setSelectedId] = useState(null) + const [editing, setEditing] = useState(false) + const [editingSuggestion, setEditingSuggestion] = useState(false) + const [rejecting, setRejecting] = useState(false) + const [announcement, setAnnouncement] = useState("") + const [shareNotice, setShareNotice] = useState("") + const [formError, setFormError] = useState("") + const [detailFocusVisible, setDetailFocusVisible] = useState(false) + const detailHeadingRef = useRef(null) + const learningListRef = useRef(null) + const statusFiltersRef = useRef(null) + const focusAfterDetailRef = useRef< + { type: "learning"; id: string } | { type: "status"; status: LearningLifecycle } | null + >(null) + const selected = learnings.find((learning) => learning.id === selectedId) ?? null + const canEditSelected = data.canDecide && !selected?.sharedFrom + // Sharing only means something when Hub has another repository to share with. + const canShareSelected = + selected?.status === "active" && + !selected.sharedFrom && + data.isHubAdmin === true && + (data.hubRepositoryCount ?? 0) > 1 + const filtered = learnings.filter( + (learning) => + learning.status === lifecycle && + `${learning.title} ${learning.guidance} ${learning.topic}` + .toLowerCase() + .includes(query.trim().toLowerCase()), + ) + const counts = { + suggested: learnings.filter((learning) => learning.status === "suggested").length, + active: learnings.filter((learning) => learning.status === "active").length, + rejected: learnings.filter((learning) => learning.status === "rejected").length, + } + const pageCount = Math.max(1, Math.ceil(filtered.length / pageSize)) + const currentPage = Math.min(page, pageCount) + const visible = filtered.slice((currentPage - 1) * pageSize, currentPage * pageSize) + + useLayoutEffect(() => { + if (selectedId) { + detailHeadingRef.current?.focus() + return + } + + const focusTarget = focusAfterDetailRef.current + focusAfterDetailRef.current = null + if (!focusTarget) return + + const controls = + focusTarget.type === "learning" + ? learningListRef.current?.querySelectorAll("[data-learning-id]") + : statusFiltersRef.current?.querySelectorAll("[data-lifecycle-status]") + const control = Array.from(controls ?? []).find((item) => + focusTarget.type === "learning" + ? item.dataset.learningId === focusTarget.id + : item.dataset.lifecycleStatus === focusTarget.status, + ) + control?.focus() + }, [selectedId]) + + function decide(status: "active" | "rejected", rejectionReason?: string) { + if (!selected || !canEditSelected) return + focusAfterDetailRef.current = { type: "status", status } + const updatedAt = `${data.today}T12:00:00.000Z` + setLearnings((current) => + current.map((learning) => + learning.id === selected.id + ? { + ...learning, + status, + updatedAt, + ...(status === "rejected" && rejectionReason ? { rejectionReason } : {}), + decisions: [ + ...(learning.decisions ?? + (learning.status === "suggested" + ? [] + : [ + { + status: learning.status, + decidedAt: learning.updatedAt, + ...(learning.status === "rejected" && learning.rejectionReason + ? { reason: learning.rejectionReason } + : {}), + }, + ])), + { + status, + decidedAt: updatedAt, + ...(status === "rejected" && rejectionReason ? { reason: rejectionReason } : {}), + }, + ], + } + : learning, + ), + ) + setLifecycle(status) + setPage(1) + setSelectedId(null) + setRejecting(false) + setFormError("") + setAnnouncement( + status === "active" + ? "Learning accepted and moved to Active." + : "Learning rejected and moved to Rejected.", + ) + } + + function saveLearning(event: SyntheticEvent) { + event.preventDefault() + if (!selected || !canEditSelected) return + const form = new FormData(event.currentTarget) + const titleValue = form.get("title") + const guidanceValue = form.get("guidance") + if (typeof titleValue !== "string" || typeof guidanceValue !== "string") { + setFormError("Enter a title and guidance.") + return + } + const title = titleValue.trim() + const guidance = guidanceValue.trim() + if (!title || !guidance) { + setFormError("Enter a title and guidance.") + return + } + const updatedAt = `${data.today}T12:00:00.000Z` + setLearnings((current) => + current.map((learning) => { + if (learning.id !== selected.id) return learning + const revised = + title !== learning.title || guidance !== learning.guidance + ? reviseGuidance(learning, title, guidance, updatedAt) + : { ...learning, updatedAt } + return editingSuggestion ? { ...revised, updateSuggestion: undefined } : revised + }), + ) + setEditing(false) + setEditingSuggestion(false) + setFormError("") + setAnnouncement(editingSuggestion ? "Suggested learning update applied." : "Learning updated.") + } + + function rejectLearning(event: SyntheticEvent) { + event.preventDefault() + const reason = new FormData(event.currentTarget).get("reason") + if (typeof reason !== "string" || !reason.trim()) { + setFormError("Enter a reason to reject this learning.") + return + } + setFormError("") + decide("rejected", reason.trim()) + } + + function applySuggestedUpdate() { + if (!selected?.updateSuggestion || !canEditSelected) return + const updatedAt = `${data.today}T12:00:00.000Z` + setLearnings((current) => + current.map((learning) => + learning.id === selected.id && learning.updateSuggestion + ? { + ...reviseGuidance( + learning, + learning.updateSuggestion.title, + learning.updateSuggestion.guidance, + updatedAt, + ), + updateSuggestion: undefined, + } + : learning, + ), + ) + setAnnouncement("Suggested learning update applied.") + } + + function dismissSuggestedUpdate() { + if (!selected || !canEditSelected) return + setLearnings((current) => + current.map((learning) => + learning.id === selected.id ? { ...learning, updateSuggestion: undefined } : learning, + ), + ) + setAnnouncement("Suggested learning update dismissed. The active learning is unchanged.") + } + + function setSharedAcrossHub(sharedAcrossHub: boolean) { + if (!selected || !canShareSelected) return + setLearnings((current) => + current.map((learning) => + learning.id === selected.id ? { ...learning, sharedAcrossHub } : learning, + ), + ) + // The live version should show this only after Hub saves the change, so the toast + // confirms sharing really took effect rather than just echoing the click. + setShareNotice(sharedAcrossHub ? "Shared across Hub" : "Stopped sharing across Hub") + } + + function closeEditor() { + setFormError("") + setEditing(false) + setEditingSuggestion(false) + } + + function backToLearnings() { + if (!selected) return + focusAfterDetailRef.current = { type: "learning", id: selected.id } + setSelectedId(null) + setEditing(false) + setEditingSuggestion(false) + setRejecting(false) + setShareNotice("") + setFormError("") + } + + return ( +
    +
    + {selected ? ( + <> + + + {selected.title} + + {canEditSelected ? ( +
    + {selected.status === "suggested" ? ( + <> + + + + ) : selected.status === "active" ? ( + <> + + + + ) : ( + + )} +
    + ) : null} + + ) : ( + <> + + Learnings + + {data.isHubAdmin && data.evaluationSettingsPath ? ( + + ) : null} + + )} +
    +
    +

    + {announcement} +

    + {data.sharedLearningNotice ? ( + + ) : null} + {selected ? ( +
    +
    +
    +
    + +
    + {selected.sharedFrom ? ( + + Shared from {selected.sharedFrom.repositoryName} · Read-only in this repository. + + ) : null} + + {selected.guidance} + +

    + Category: {selected.topic} + + {countLabel(selected.evidence.length, "review comment")} + + + Updated{" "} + + + {selected.acceptedBy ? ( + <> + + Accepted by @{selected.acceptedBy} + + ) : null} +

    +
    + {canShareSelected ? ( + +
    + Share across Hub + + {/* The tooltip is visual, so screen readers get the hint here. */} + {shareHint} +
    +
    + ) : null} +
    + + {selected.status === "rejected" && selected.rejectionReason ? ( +
    + + + Why it was rejected + + {selected.rejectionReason} +
    + ) : null} + + {selected.status === "active" && selected.updateSuggestion ? ( +
    + + Update suggested + +
    + {diffText(selected.title, selected.updateSuggestion.title)} + + {diffText(selected.guidance, selected.updateSuggestion.guidance)} + +
    +

    + Why: {selected.updateSuggestion.reason} +

    + {canEditSelected ? ( +
    + + + +
    + ) : null} +
    + ) : null} + +
    +
    + + Observed outcomes + +

    How later builds did with this guidance.

    +
    + {/* Outcomes of older wording do not apply to the current guidance. */} + {selected.outcomeAssessment?.version !== (selected.version ?? 1) || + selected.outcomeAssessment.status === "not-evaluated" ? ( +

    Not evaluated yet.

    + ) : selected.outcomeAssessment.status === "insufficient-evidence" ? ( +

    + Not enough evidence yet. This is not a negative result. +

    + ) : ( +
      + {selected.outcomeAssessment.outcomes.map((outcome) => { + const ResultIcon = outcomeResultIcons[outcome.result] + return ( +
    • + + + {outcomeResultLabels[outcome.result]} + {" · "} + {outcomeSourceLabel(outcome.source)} + + {outcome.summary} +

      + + {outcome.prototypeName}, Build {outcome.buildNumber} + + {" · "} + +

      + {outcome.beforeScreenshotUrl || outcome.afterScreenshotUrl ? ( +
      + {outcome.beforeScreenshotUrl ? ( +
      +
      Before
      + + {`Before + +
      + ) : null} + {outcome.afterScreenshotUrl ? ( +
      +
      After
      + + {`After + +
      + ) : null} +
      + ) : null} +
    • + ) + })} +
    + )} + {selected.versionHistory?.length ? ( +
    + Earlier guidance + {selected.versionHistory.map((version) => ( +
    + + {version.title} + + {version.guidance} + {version.outcomeAssessment?.outcomes.length ? ( + + ) : null} +
    + ))} +
    + ) : null} +
    + + {selected.status === "active" && selected.decisions?.length ? ( +
    + + Decision history + +
      + {selected.decisions.map((decision, index) => ( +
    • + {lifecycleLabels[decision.status]} + {" · "} + + {decision.reason ?

      {decision.reason}

      : null} +
    • + ))} +
    +
    + ) : null} + + {selected.evidence.length ? ( +
    +
    + + Review comments + +

    The feedback this learning came from.

    +
    + {evidenceList(selected.evidence)} +
    + ) : null} +
    + ) : ( + <> +
    + +

    + Shared guidance from your team’s prototype reviews. + {data.agentConnectionPath ? ( + <> + {" "} + Use these learnings in your agent through MCP.{" "} + Connect an agent + + ) : null} +

    +
    + +
    +
    + + Browse learnings + + {!data.canDecide ? ( + + Browse is open to repository members. Administrators decide what becomes + guidance. + + ) : null} +
    +
    +
    + {(["suggested", "active", "rejected"] as const).map((status) => ( + + ))} +
    + + + Search learnings + + { + setQuery(event.target.value) + setPage(1) + }} + placeholder="Search learnings" + value={query} + /> + +
    +
    + + + + + + + + + + + {visible.map((learning) => ( + + + + + + + ))} + +
    LearningCategoryEvidenceUpdated
    +
    + +
    + + {learning.status === "active" && learning.updateSuggestion ? ( + + Update suggested + + ) : null} +

    {learning.guidance}

    +
    +
    +
    + {learning.topic} + {countLabel(learning.evidence.length, "review comment")} + +
    + {!filtered.length ? ( +
    + + No {lifecycleLabels[lifecycle].toLowerCase()} learnings + + + {query + ? "Try another search." + : "New learnings will appear here as your team reviews prototypes."} + +
    + ) : null} +
    + {pageCount > 1 ? ( + `#learnings-page-${pageNumber}`} + onPageChange={(event, pageNumber) => { + event.preventDefault() + setPage(pageNumber) + }} + pageCount={pageCount} + /> + ) : null} +
    + + )} +
    + {editing && selected ? ( + +

    + {editingSuggestion + ? "Applying this update replaces the current guidance. The current guidance and its outcomes stay under Earlier guidance." + : "Saving replaces the current guidance. Its outcomes stay under Earlier guidance."} +

    +
    + {formError ?

    {formError}

    : null} + + + {editingSuggestion ? "Proposed title" : "Title"} + + + + + + {editingSuggestion ? "Proposed guidance" : "Guidance"} + +