diff --git a/hub/client/application/hub-application/index.tsx b/hub/client/application/hub-application/index.tsx index 5e67638e3..ff0cca245 100644 --- a/hub/client/application/hub-application/index.tsx +++ b/hub/client/application/hub-application/index.tsx @@ -197,9 +197,11 @@ export function HubApplication({ canvasReturnTo }: { canvasReturnTo?: string } = : null, badge: "Collaborative prototyping", badgeAlternate: "Built for feedback", - description: canvasReturnTo - ? "Sign in to continue to your Replica canvas connection." - : "Sign in with an active Replica Hub membership.", + description: canvasReturnTo?.startsWith("/agents/") + ? "Sign in to connect your coding agent to Replica Hub." + : canvasReturnTo + ? "Sign in to continue to your Replica canvas connection." + : "Sign in with an active Replica Hub membership.", footerNote: "\u00a9 2026 GitHub, Inc.", heading: "Build and review prototypes with your team.", notice: null, diff --git a/hub/client/application/hub/agent-connections/contract.ts b/hub/client/application/hub/agent-connections/contract.ts new file mode 100644 index 000000000..024922930 --- /dev/null +++ b/hub/client/application/hub/agent-connections/contract.ts @@ -0,0 +1,29 @@ +import { z } from "zod" + +export const agentAuthorizationSchema = z + .object({ + agent: z.string().min(1), + redirectUri: z.url(), + session: z.string().min(1).max(255), + signedInAs: z.string().min(1), + expiresAt: z.iso.datetime(), + }) + .strict() + +export const agentDecisionSchema = z.object({ redirectUrl: z.url() }).strict() + +export const agentConnectionsSchema = z + .object({ + connections: z.array( + z + .object({ + id: z.uuid(), + agent: z.string().min(1), + createdAt: z.iso.datetime(), + lastUsedAt: z.iso.datetime().nullable(), + inactiveAt: z.iso.datetime(), + }) + .strict(), + ), + }) + .strict() diff --git a/hub/client/application/hub/learnings-contracts/index.test.ts b/hub/client/application/hub/learnings-contracts/index.test.ts index f75c0de30..456f07877 100644 --- a/hub/client/application/hub/learnings-contracts/index.test.ts +++ b/hub/client/application/hub/learnings-contracts/index.test.ts @@ -30,10 +30,24 @@ describe("Learnings contracts", () => { automaticRunsEnabled: false, solo: false, localLearningSetupNeeded: false, - activity: [], + activity: [ + { + date: "2026-11-10", + runs: 2, + commentsAnalyzed: 4, + commentsTagged: 2, + suggestions: 1, + lastRun: { + state: "failed", + startedAt: "2026-11-10T12:00:00.000Z", + startedBy: { type: "user", login: "mona" }, + }, + }, + ], today: "2026-11-10", usageCredits: "0.0735", runAvailable: true, + firstRunNeeded: false, loadError: null, identityReviewCount: 1, suggestions: [ @@ -120,6 +134,12 @@ describe("Learnings contracts", () => { } expect(learningsResponseSchema.parse(response)).toEqual(response) + expect( + learningsResponseSchema.safeParse({ + ...response, + capabilities: { administerHub: true, administerRepository: false }, + }).success, + ).toBe(false) const soloActivity = { ...response, @@ -142,6 +162,7 @@ describe("Learnings contracts", () => { } expect(learningsResponseSchema.parse(soloActivity)).toEqual(soloActivity) + expect(learningsResponseSchema.safeParse({ ...soloActivity, solo: false }).success).toBe(false) }) it.each([false, true])( @@ -221,6 +242,7 @@ describe("Learnings contracts", () => { usageCredits: "0", runAvailable: false, loadError: null, + firstRunNeeded: false, identityReviewCount: 0, suggestions: [ { diff --git a/hub/client/application/hub/learnings-contracts/index.ts b/hub/client/application/hub/learnings-contracts/index.ts index 1759e2be1..c0a5120f9 100644 --- a/hub/client/application/hub/learnings-contracts/index.ts +++ b/hub/client/application/hub/learnings-contracts/index.ts @@ -1,3 +1,4 @@ +import type { AppliedLearningsResponse, EvaluationSettingsResponse } from "./types" import { z } from "zod" import { recordIdentifierSchema, repositorySchema } from "@application/hub/contracts" @@ -13,9 +14,13 @@ import type { LearningHistoryResponse, LearningMutationResponse, LearningRunResponse, + LearningShareInput, + LearningSettingsInput, + LearningSettingsResponse, LearningSuggestionResponse, LearningsResponse, RejectedLearningResponse, + SharedLearningResponse, } from "./types" const identifier = z.number().int().positive() @@ -47,12 +52,15 @@ const replaces = z.array( z.object({ id: learningIdentifier, content: z.string().nullable() }).strict(), ) +const sessions = z.object({ supporting: count, opposing: count }).strict().optional() + export const learningSuggestionResponseSchema = z .object({ id: learningIdentifier, title: title.nullable(), content: guidance, reviewDigest: digest, + sessions, support: z.object({ reviewers: count, prototypes: count }).strict().nullable(), replaces, evidence: z.array(learningEvidenceResponseSchema), @@ -70,17 +78,32 @@ export const acceptedLearningResponseSchema = z digest: digest.nullable(), acceptedBy: z.string().nullable(), acceptedAt: timestamp.nullable(), + shared: z.boolean().optional(), edited: z.boolean(), + shareable: z.boolean().optional(), status: z.enum(["recalled", "not-recalled", "budget-excluded", "damaged", "identity-review"]), }) .strict() satisfies z.ZodType +export const sharedLearningResponseSchema = z + .object({ + id: learningIdentifier, + title: title.nullable(), + content: z.string().nullable(), + source: z.string().min(1), + sharedBy: z.string().nullable(), + sharedAt: timestamp, + status: z.enum(["recalled", "budget-excluded"]), + }) + .strict() satisfies z.ZodType + export const rejectedLearningResponseSchema = z .object({ id: learningIdentifier, title: title.nullable(), content: z.string().nullable(), digest: digest.nullable(), + shared: z.boolean().optional(), state: z.enum(["rejected", "retired"]), replaces, decidedBy: z.string().nullable(), @@ -89,6 +112,35 @@ export const rejectedLearningResponseSchema = z }) .strict() satisfies z.ZodType +const historyScreenshotSchema = z + .object({ sha256: z.string().regex(/^[0-9a-f]{64}$/), route: z.string() }) + .strict() + +const buildSchema = z + .object({ + prototypeId: recordIdentifierSchema, + prototypeName: z.string().min(1), + number: identifier, + }) + .strict() + +const learningOutcomeResponseSchema = z + .object({ + id: z.string().min(1), + source: z.enum(["automated", "reviewer_confirmed"]), + efficiency: z.number().int().min(1).max(4), + followed: z.enum(["followed", "not_followed", "unclear"]), + reasoning: z.string(), + issue: z.string().nullable(), + scoredAt: timestamp, + build: buildSchema, + before: historyScreenshotSchema.optional(), + after: historyScreenshotSchema.optional(), + }) + .strict() + +const proposalId = z.string().regex(/^[a-z][a-z0-9]{1,15}_[A-Za-z0-9_-]{8,128}$/) + export const learningHistoryResponseSchema = z .object({ decisions: z.array( @@ -107,6 +159,31 @@ export const learningHistoryResponseSchema = z otherEvidenceCount: count, contradictions: z.array(learningEvidenceResponseSchema), otherContradictionsCount: count, + updateNeedsMoreEvidence: z.boolean().optional(), + sessions, + outcomes: z.array(learningOutcomeResponseSchema), + earlierGuidance: z.array( + z + .object({ + version: identifier, + title: z.string().nullable(), + content: z.string(), + outcomes: z.array(learningOutcomeResponseSchema), + }) + .strict(), + ), + updates: z.array( + z + .object({ + id: proposalId, + issue: z.string(), + title: z.string().nullable(), + content: z.string(), + reasoning: z.string(), + support: z.array(buildSchema), + }) + .strict(), + ), }) .strict() satisfies z.ZodType @@ -124,32 +201,48 @@ const learningRunResultSchema = z.discriminatedUnion("type", [ z.object({ type: z.literal("failed"), summary: z.string().min(1) }).strict(), ]) +const runStarter = z.discriminatedUnion("type", [ + z.strictObject({ type: z.literal("daily") }), + z.strictObject({ type: z.literal("user"), login: z.string().min(1) }), + z.strictObject({ type: z.literal("unknown") }), +]) + export const learningRunResponseSchema = z .object({ id: identifier, startedAt: timestamp, - startedBy: z.discriminatedUnion("type", [ - z.object({ type: z.literal("daily") }).strict(), - z.object({ type: z.literal("user"), login: z.string().min(1) }).strict(), - z.object({ type: z.literal("unknown") }).strict(), - ]), + startedBy: runStarter, state: z.enum(["queued", "running", "succeeded", "failed"]), result: learningRunResultSchema.nullable(), usage: z.object({ credits, requests: identifier }).strict().nullable(), }) .strict() satisfies z.ZodType -const learningActivityDayResponseSchema = z - .object({ - date: z.iso.date(), +const activityCounts = { + date: z.iso.date(), + commentsAnalyzed: count, + commentsTagged: count, + suggestions: count, +} +const learningActivityDayResponseSchema = z.union([ + z.strictObject({ + ...activityCounts, + runs: z.number().int().positive(), + lastRun: z + .strictObject({ + state: z.enum(["succeeded", "failed"]), + startedAt: timestamp, + startedBy: runStarter, + }) + .optional(), + }), + z.strictObject({ + ...activityCounts, runState: z.enum(["succeeded", "failed"]), startedAt: timestamp, - startedBy: z.object({ type: z.literal("agent") }).strict(), - commentsAnalyzed: count, - commentsTagged: count, - suggestions: count, - }) - .strict() + startedBy: z.strictObject({ type: z.literal("agent") }), + }), +]) export const learningsResponseSchema = z.discriminatedUnion("accessDenied", [ z @@ -179,6 +272,7 @@ export const learningsResponseSchema = z.discriminatedUnion("accessDenied", [ viewEvidence: z.boolean(), decide: z.boolean(), requestRun: z.boolean(), + share: z.boolean().optional(), }) .strict(), copilot: z.discriminatedUnion("state", [ @@ -203,15 +297,24 @@ export const learningsResponseSchema = z.discriminatedUnion("accessDenied", [ today: z.iso.date(), usageCredits: credits.nullable(), runAvailable: z.boolean(), + firstRunNeeded: z.boolean(), loadError: z.string().min(1).nullable(), identityReviewCount: count, suggestions: z.array(learningSuggestionResponseSchema), learnings: z.array(acceptedLearningResponseSchema), rejected: z.array(rejectedLearningResponseSchema), + shared: z.array(sharedLearningResponseSchema).optional(), recall: z.object({ text: z.string(), count }).strict(), runs: z.array(learningRunResponseSchema).max(10), }) - .strict(), + .strict() + .refine( + ({ solo, activity, capabilities }) => + activity.every((day) => + "runs" in day ? !solo && (!day.lastRun || capabilities.administerRepository) : solo, + ), + { message: "The activity details do not match this repository access.", path: ["activity"] }, + ), ]) satisfies z.ZodType export const learningDecisionInputSchema = z.discriminatedUnion("decision", [ @@ -251,8 +354,104 @@ export const learningDecisionInputSchema = z.discriminatedUnion("decision", [ reason: z.string().trim().min(1).max(500), }) .strict(), + z + .object({ + decision: z.literal("apply_update"), + proposalId, + title: title.optional(), + content: guidance.optional(), + reason: z.string().trim().min(1).max(500), + }) + .strict(), + z + .object({ + decision: z.literal("dismiss_update"), + proposalId, + reason: z.string().trim().min(1).max(500), + }) + .strict(), ]) satisfies z.ZodType +export const learningShareInputSchema = z.discriminatedUnion("shared", [ + z.object({ shared: z.literal(true), digest }).strict(), + z.object({ shared: z.literal(false) }).strict(), +]) satisfies z.ZodType + export const learningMutationResponseSchema = z .object({ notice: z.string().min(1) }) .strict() satisfies z.ZodType + +const learningSettingsRecordSchema = z + .object({ + allowed: z.boolean(), + changedBy: z.string().min(1).nullable(), + changedAt: timestamp.nullable(), + }) + .strict() + +export const learningSettingsResponseSchema = z + .object({ + repository: repositorySchema, + notes: learningSettingsRecordSchema, + reviewComments: learningSettingsRecordSchema, + }) + .strict() satisfies z.ZodType + +export const learningSettingsInputSchema = z + .object({ + notes: z.boolean().optional(), + reviewComments: z.boolean().optional(), + }) + .strict() + .refine((value) => Object.keys(value).length > 0) satisfies z.ZodType + +const appliedScreenshotSchema = z + .object({ sha256: z.string().regex(/^[0-9a-f]{64}$/), route: z.string() }) + .strict() + +export const appliedLearningsResponseSchema = z + .object({ + learnings: z.array( + z + .object({ + id: z.string().min(1), + title: z.string().nullable(), + version: identifier.nullable(), + before: appliedScreenshotSchema.optional(), + after: appliedScreenshotSchema.optional(), + }) + .strict(), + ), + }) + .strict() satisfies z.ZodType + +const evaluationBudgetSchema = z + .object({ + repository: z + .object({ + id: recordIdentifierSchema, + nameWithOwner: z.string().min(1), + defaultBranch: z.string().min(1), + }) + .strict(), + monthlyBudgetCredits: credits, + usedCredits: credits, + }) + .strict() + +export const evaluationSettingsResponseSchema = z.union([ + evaluationBudgetSchema.extend({ + permissions: z + .object({ changeBudget: z.literal(true), changeRepository: z.literal(false) }) + .strict(), + }), + evaluationBudgetSchema.extend({ + permissions: z + .object({ changeBudget: z.boolean(), changeRepository: z.literal(true) }) + .strict(), + enabled: z.boolean(), + screenshots: learningSettingsRecordSchema, + notes: learningSettingsRecordSchema, + reviewComments: learningSettingsRecordSchema, + }), +]) satisfies z.ZodType diff --git a/hub/client/application/hub/learnings-contracts/types.ts b/hub/client/application/hub/learnings-contracts/types.ts index c0e88435e..06c8dd681 100644 --- a/hub/client/application/hub/learnings-contracts/types.ts +++ b/hub/client/application/hub/learnings-contracts/types.ts @@ -12,6 +12,7 @@ export interface LearningEvidenceResponse { } export interface LearningSuggestionResponse { + sessions?: { supporting: number; opposing: number } id: string title: string | null content: string @@ -31,6 +32,8 @@ export interface AcceptedLearningResponse { digest: string | null acceptedBy: string | null acceptedAt: string | null + shareable?: boolean + shared?: boolean edited: boolean status: "recalled" | "not-recalled" | "budget-excluded" | "damaged" | "identity-review" } @@ -40,6 +43,7 @@ export interface RejectedLearningResponse { title: string | null content: string | null digest: string | null + shared?: boolean state: "rejected" | "retired" replaces: Array<{ id: string; content: string | null }> decidedBy: string | null @@ -47,7 +51,18 @@ export interface RejectedLearningResponse { reason: string | null } +export interface SharedLearningResponse { + id: string + title: string | null + content: string | null + source: string + sharedBy: string | null + sharedAt: string + status: "recalled" | "budget-excluded" +} + export interface LearningHistoryResponse { + sessions?: { supporting: number; opposing: number } decisions: Array<{ version: number state: "proposed" | "accepted" | "rejected" | "retired" @@ -60,6 +75,44 @@ export interface LearningHistoryResponse { otherEvidenceCount: number contradictions: LearningEvidenceResponse[] otherContradictionsCount: number + outcomes: LearningOutcomeResponse[] + /** Wording agents were given before the current version, newest first. */ + earlierGuidance: Array<{ + version: number + title: string | null + content: string + outcomes: LearningOutcomeResponse[] + }> + /** Suggested new wording waiting for an administrator. */ + updateNeedsMoreEvidence?: boolean + updates: LearningUpdateResponse[] +} + +/** Suggested new wording, drafted because scored uses kept showing the same issue. */ +export interface LearningUpdateResponse { + id: string + issue: string + title: string | null + content: string + reasoning: string + /** The Builds whose scores showed the issue. */ + support: LearningOutcomeResponse["build"][] +} + +/** How one use of a learning was scored, with the Build it judged. */ +export interface LearningOutcomeResponse { + id: string + /** Whether a reviewer confirmed the work before it was scored. */ + source: "automated" | "reviewer_confirmed" + /** 4 is best. 1 and 2 come with an issue. */ + efficiency: number + followed: "followed" | "not_followed" | "unclear" + reasoning: string + issue: string | null + scoredAt: string + build: { prototypeId: string; prototypeName: string; number: number } + before?: { sha256: string; route: string } + after?: { sha256: string; route: string } } export interface LearningRunResponse { @@ -81,15 +134,22 @@ export interface LearningRunResponse { usage: { credits: string; requests: number } | null } -export interface LearningActivityDayResponse { +export type LearningActivityDayResponse = { date: string - runState: "succeeded" | "failed" - startedAt: string - startedBy: { type: "agent" } commentsAnalyzed: number commentsTagged: number suggestions: number -} +} & ( + | { + runs: number + lastRun?: { + state: "succeeded" | "failed" + startedAt: string + startedBy: LearningRunResponse["startedBy"] + } + } + | { runState: "succeeded" | "failed"; startedAt: string; startedBy: { type: "agent" } } +) export type LearningsResponse = | { @@ -101,7 +161,7 @@ export type LearningsResponse = accessDenied: false repository: RepositoryRecord capabilities: { administerHub: boolean; administerRepository: boolean } - permissions: { viewEvidence: boolean; decide: boolean; requestRun: boolean } + permissions: { viewEvidence: boolean; decide: boolean; requestRun: boolean; share?: boolean } copilot: | { state: "connected"; connectedBy: string | null } | { state: "not-connected" } @@ -113,11 +173,13 @@ export type LearningsResponse = today: string usageCredits: string | null runAvailable: boolean + firstRunNeeded: boolean loadError: string | null identityReviewCount: number suggestions: LearningSuggestionResponse[] learnings: AcceptedLearningResponse[] rejected: RejectedLearningResponse[] + shared?: SharedLearningResponse[] recall: { text: string; count: number } runs: LearningRunResponse[] } @@ -128,7 +190,64 @@ export type LearningDecisionInput = | { decision: "retire"; reason: string } | { decision: "edit"; digest: string; title?: string; content?: string; reason: string } | { decision: "reinstate"; digest: string; reason: string } + | { + decision: "apply_update" + proposalId: string + title?: string + content?: string + reason: string + } + | { decision: "dismiss_update"; proposalId: string; reason: string } + +export type LearningShareInput = { shared: true; digest: string } | { shared: false } export interface LearningMutationResponse { notice: string } + +export interface LearningSettingsRecord { + allowed: boolean + changedBy: string | null + changedAt: string | null +} + +export interface LearningSettingsResponse { + repository: RepositoryRecord + notes: LearningSettingsRecord + reviewComments: LearningSettingsRecord +} + +export interface LearningSettingsInput { + notes?: boolean + reviewComments?: boolean +} + +export interface AppliedLearningResponse { + id: string + title: string | null + version: number | null + before?: { sha256: string; route: string } + after?: { sha256: string; route: string } +} + +export interface AppliedLearningsResponse { + learnings: AppliedLearningResponse[] +} + +interface EvaluationBudgetResponse { + repository: { id: string; nameWithOwner: string; defaultBranch: string } + monthlyBudgetCredits: string + usedCredits: string +} + +export type EvaluationSettingsResponse = EvaluationBudgetResponse & + ( + | { permissions: { changeBudget: true; changeRepository: false } } + | { + permissions: { changeBudget: boolean; changeRepository: true } + enabled: boolean + screenshots: LearningSettingsResponse["notes"] + notes: LearningSettingsResponse["notes"] + reviewComments: LearningSettingsResponse["reviewComments"] + } + ) diff --git a/hub/client/application/hub/requests/get-applied-learnings/index.ts b/hub/client/application/hub/requests/get-applied-learnings/index.ts new file mode 100644 index 000000000..412330f2a --- /dev/null +++ b/hub/client/application/hub/requests/get-applied-learnings/index.ts @@ -0,0 +1,16 @@ +import { appliedLearningsResponseSchema } from "@application/hub/learnings-contracts" + +import { requestJson } from "../request-json" + +/** Reads what agents said they applied in the commit a Build was made from. */ +export function getAppliedLearnings( + request: Request, + repositoryId: string, + prototypeId: string, + commitSha: string, +) { + const url = new URL(`/api/repositories/${repositoryId}/learnings/applied`, request.url) + url.searchParams.set("prototype", prototypeId) + url.searchParams.set("commit", commitSha) + return requestJson(url, appliedLearningsResponseSchema, { signal: request.signal }) +} diff --git a/hub/client/application/hub/routes.ts b/hub/client/application/hub/routes.ts index 57fb007ab..4818cc8ae 100644 --- a/hub/client/application/hub/routes.ts +++ b/hub/client/application/hub/routes.ts @@ -8,6 +8,7 @@ export default [ route("signed-in/no-access", "routes/no-repository-access/index.tsx"), route("sign-in", "routes/sign-in/index.tsx"), route("canvas/pair/:userCode", "routes/canvas-pairing/index.tsx"), + route("agents/approve/:authorizationId", "routes/agent-approval/index.tsx"), route("shared/:shareId", "routes/product-public/index.tsx"), ...standaloneSetupRoutes, layout("routes/workspace/index.tsx", [ diff --git a/hub/client/application/hub/routes/administrator-flow.test.tsx b/hub/client/application/hub/routes/administrator-flow.test.tsx index 9f2118f10..bc06fb896 100644 --- a/hub/client/application/hub/routes/administrator-flow.test.tsx +++ b/hub/client/application/hub/routes/administrator-flow.test.tsx @@ -663,7 +663,7 @@ describe("administrator frontend integration", () => { fireEvent.click( await screen.findByRole("checkbox", { - name: /confirm connecting Copilot for this Hub/i, + name: /confirm connecting or checking Copilot for this Hub/i, }), ) fireEvent.click(screen.getByRole("button", { name: "Connect Copilot" })) diff --git a/hub/client/application/hub/routes/agent-approval-flow.test.tsx b/hub/client/application/hub/routes/agent-approval-flow.test.tsx new file mode 100644 index 000000000..b4a811187 --- /dev/null +++ b/hub/client/application/hub/routes/agent-approval-flow.test.tsx @@ -0,0 +1,44 @@ +import { fireEvent, screen } from "@testing-library/react" +import { describe, expect, it } from "vitest" + +import { http, stubHubFetch } from "@/test/stub-hub-fetch" + +import { renderHubFlow } from "./fixtures/render-hub-flow" + +describe("Agent approval", () => { + it("shows the current account and requires a new decision after an account switch", async () => { + const id = "7c9e6679-7425-40de-944b-e07fc1f90ae7" + const authorization = `/api/agent-connections/authorizations/${id}` + let account = { signedInAs: "octocat", session: "original-session" } + const decisions: unknown[] = [] + const api = stubHubFetch( + http.get(authorization, () => + Response.json({ + agent: "Local MCP client", + redirectUri: "http://127.0.0.1:8123/callback", + expiresAt: "2026-11-30T12:05:00Z", + ...account, + }), + ), + http.post(`${authorization}/approve`, async ({ request }) => { + decisions.push(await request.json()) + return Response.json({ error: "The signed-in account changed." }, { status: 409 }) + }), + ) + const router = await renderHubFlow(api, `/agents/approve/${id}`) + expect(screen.getByText("@octocat")).toBeVisible() + + account = { signedInAs: "mona", session: "current-session" } + await router.settle(() => + fireEvent.click(screen.getByRole("button", { name: "Approve access" })), + ) + + expect(decisions).toEqual([{ session: "original-session" }]) + expect(screen.getByText("@mona")).toBeVisible() + expect(screen.getByText(/submit Pick & Polish notes/i)).toHaveTextContent( + /only for repositories where an administrator has allowed note storage/i, + ) + const approve = screen.getByRole("button", { name: "Approve access" }) + expect(new FormData(approve.form!).get("session")).toBe("current-session") + }) +}) diff --git a/hub/client/application/hub/routes/agent-approval/index.tsx b/hub/client/application/hub/routes/agent-approval/index.tsx new file mode 100644 index 000000000..cdbf0f624 --- /dev/null +++ b/hub/client/application/hub/routes/agent-approval/index.tsx @@ -0,0 +1,97 @@ +import { redirect, useFetcher, useLocation } from "react-router" +import { z } from "zod" + +import { HubApplication } from "@application/hub-application" +import { + agentAuthorizationSchema, + agentDecisionSchema, +} from "@application/hub/agent-connections/contract" +import { canvasActionError } from "@application/hub/canvas-connections/contract" +import { FormBoundary } from "@application/hub/form-boundary" +import { ApiRequestError } from "@application/hub/requests/api-request-error" +import { requestJson } from "@application/hub/requests/request-json" +import { AgentConnectionsPage } from "@pages/agent-connections-page" +import type { AgentConnectionsPageData } from "@pages/agent-connections-page/types" + +import type { Route } from "./+types/index" + +function authorizationPath(value: string | undefined) { + const id = z.uuid().safeParse(value) + if (!id.success) throw new Response("This agent request is invalid.", { status: 404 }) + return { id: id.data, browserPath: `/agents/approve/${id.data}` } +} + +export async function clientLoader({ request, params }: Route.ClientLoaderArgs) { + const { id, browserPath } = authorizationPath(params.authorizationId) + try { + const authorization = await requestJson( + new URL(`/api/agent-connections/authorizations/${id}`, request.url), + agentAuthorizationSchema, + { signal: request.signal }, + ) + const destination = new URL(authorization.redirectUri) + const page: AgentConnectionsPageData = { + view: "approval", + requestingAgent: authorization.agent, + destination: destination.host, + localDestination: ["localhost", "127.0.0.1", "[::1]"].includes(destination.hostname), + session: authorization.session, + signedInAs: authorization.signedInAs, + expiresLabel: `This request expires at ${new Date(authorization.expiresAt).toLocaleTimeString()}.`, + decisionPath: browserPath, + } + return { page, browserPath } + } catch (error) { + if (error instanceof ApiRequestError && error.status === 401) return { page: null, browserPath } + if (error instanceof ApiRequestError && error.status === 410) + throw new Response(error.message, { status: 410 }) + throw error + } +} + +export async function clientAction({ request, params }: Route.ClientActionArgs) { + const { id, browserPath } = authorizationPath(params.authorizationId) + if (request.method !== "POST") throw new Response("Method not allowed.", { status: 405 }) + const form = await request.formData() + const decision = form.get("decision") + if (decision !== "approve" && decision !== "cancel") + throw new Response("Choose whether to approve this agent.", { status: 422 }) + try { + const { redirectUrl } = await requestJson( + new URL(`/api/agent-connections/authorizations/${id}/${decision}`, request.url), + agentDecisionSchema, + { + method: "POST", + body: JSON.stringify({ session: form.get("session") }), + signal: request.signal, + }, + ) + // The agent listens on its own address, so the browser leaves Hub to finish. + return redirect(redirectUrl) + } catch (error) { + if (error instanceof ApiRequestError && [401, 409].includes(error.status)) { + return redirect(browserPath) + } + return canvasActionError(error) + } +} + +export function meta() { + return [{ title: "Connect an agent - Replica Hub" }] +} + +export default function AgentApproval({ loaderData }: Route.ComponentProps) { + const fetcher = useFetcher<{ error?: string }>() + const { pathname } = useLocation() + if (!loaderData.page) return + const busy = fetcher.state !== "idle" + return ( + void fetcher.submit(form, { method: "post", action: pathname })} + > + + + ) +} diff --git a/hub/client/application/hub/routes/fixtures/empty-learnings/index.ts b/hub/client/application/hub/routes/fixtures/empty-learnings/index.ts index 9c8ace521..bcbb67679 100644 --- a/hub/client/application/hub/routes/fixtures/empty-learnings/index.ts +++ b/hub/client/application/hub/routes/fixtures/empty-learnings/index.ts @@ -16,6 +16,7 @@ export function emptyLearnings( today: new Date().toISOString().slice(0, 10), usageCredits: "0", runAvailable: true, + firstRunNeeded: false, loadError: null, identityReviewCount: 0, suggestions: [], diff --git a/hub/client/application/hub/routes/fixtures/preview-handlers/index.ts b/hub/client/application/hub/routes/fixtures/preview-handlers/index.ts index 8cd71bac2..2e8c179d5 100644 --- a/hub/client/application/hub/routes/fixtures/preview-handlers/index.ts +++ b/hub/client/application/hub/routes/fixtures/preview-handlers/index.ts @@ -27,6 +27,9 @@ export function previewHandlers(data: ReturnType) { canBranch, }) }), + http.get(`/api/repositories/${repository.id}/learnings/applied`, () => + Response.json({ learnings: [] }), + ), http.get(`/api${path}/builds`, () => Response.json({ repository, diff --git a/hub/client/application/hub/routes/learning-agents/index.tsx b/hub/client/application/hub/routes/learning-agents/index.tsx new file mode 100644 index 000000000..f0a022ebf --- /dev/null +++ b/hub/client/application/hub/routes/learning-agents/index.tsx @@ -0,0 +1,104 @@ +import { useFetcher, useLocation, useOutletContext } from "react-router" +import { z } from "zod" + +import { agentConnectionsSchema } from "@application/hub/agent-connections/contract" +import { + canvasActionError, + canvasFormDestination, +} from "@application/hub/canvas-connections/contract" +import { recordIdentifierSchema } from "@application/hub/contracts" +import type { WorkspaceResponse } from "@application/hub/contracts/types" +import { FormBoundary } from "@application/hub/form-boundary" +import { requestJson } from "@application/hub/requests/request-json" +import { AgentConnectionsPage } from "@pages/agent-connections-page" + +import type { Route } from "./+types/index" +import type { WorkspaceRouteHandle } from "../workspace/types" + +export const handle = { workspaceSection: "learnings" } satisfies WorkspaceRouteHandle + +function repositoryId(value: string | undefined) { + const parsed = recordIdentifierSchema.safeParse(value) + if (!parsed.success) throw new Response("Invalid repository identifier.", { status: 400 }) + return parsed.data +} + +function dateLabel(value: string) { + return new Date(value).toLocaleDateString() +} + +export async function clientLoader({ request, params }: Route.ClientLoaderArgs) { + const id = repositoryId(params.repositoryId) + const { connections } = await requestJson( + new URL("/api/agent-connections", request.url), + agentConnectionsSchema, + { signal: request.signal }, + ) + return { + mcpUrl: new URL(`/mcp/repositories/${id}`, request.url).href, + connections: connections.map((connection) => ({ + id: connection.id, + name: connection.agent, + connectedLabel: `Connected ${dateLabel(connection.createdAt)}`, + lastUsedLabel: connection.lastUsedAt + ? `Last used ${dateLabel(connection.lastUsedAt)}` + : "Not used yet", + revokePath: `/repositories/${id}/learnings/agents/${connection.id}`, + })), + } +} + +export async function clientAction({ request, params }: Route.ClientActionArgs) { + const id = repositoryId(params.repositoryId) + if (request.method !== "POST") throw new Response("Method not allowed.", { status: 405 }) + const form = await request.formData() + const destination = canvasFormDestination(form, request.url) + const connectionId = destination?.pathname.startsWith(`/repositories/${id}/learnings/agents/`) + ? z.uuid().safeParse(destination.pathname.split("/").at(-1)) + : null + if (!connectionId?.success || form.get("_method") !== "delete") { + throw new Response("This agent connection could not be revoked.", { status: 422 }) + } + try { + await requestJson( + new URL(`/api/agent-connections/${connectionId.data}`, request.url), + z.undefined(), + { method: "DELETE", signal: request.signal }, + ) + } catch (error) { + return canvasActionError(error) + } + return { notice: "Agent access revoked." } +} + +export function meta() { + return [{ title: "Connect an agent - Replica Hub" }] +} + +export default function LearningAgents({ loaderData, params }: Route.ComponentProps) { + const workspace = useOutletContext() + const fetcher = useFetcher<{ error?: string; notice?: string }>() + const { pathname } = useLocation() + const busy = fetcher.state !== "idle" + const repository = workspace?.repositories.find(({ id }) => id === params.repositoryId) + return ( + void fetcher.submit(form, { method: "post", action: pathname })} + > + + + ) +} diff --git a/hub/client/application/hub/routes/learning-evaluations/index.tsx b/hub/client/application/hub/routes/learning-evaluations/index.tsx new file mode 100644 index 000000000..c022c5b81 --- /dev/null +++ b/hub/client/application/hub/routes/learning-evaluations/index.tsx @@ -0,0 +1,10 @@ +import { redirect } from "react-router" +import type { LoaderFunctionArgs } from "react-router" + +import { readRecordIdentifier } from "@application/hub/read-record-identifier" + +/** Keep existing evaluation links pointing at the combined Learning settings. */ +export function clientLoader({ params }: LoaderFunctionArgs) { + const id = readRecordIdentifier(params.repositoryId, "repository") + return redirect(`/repositories/${id}/learnings/settings`) +} diff --git a/hub/client/application/hub/routes/learning-settings-flow.test.tsx b/hub/client/application/hub/routes/learning-settings-flow.test.tsx new file mode 100644 index 000000000..a4c253f34 --- /dev/null +++ b/hub/client/application/hub/routes/learning-settings-flow.test.tsx @@ -0,0 +1,172 @@ +import { fireEvent, screen, waitFor, within } from "@testing-library/react" +import { describe, expect, it, onTestFinished } from "vitest" + +import type { LearningSettingsInput } from "@application/hub/learnings-contracts/types" +import { deferred } from "@/test/deferred" +import { http, stubHubFetch } from "@/test/stub-hub-fetch" + +import { authenticatedWorkspace } from "./fixtures/authenticated-workspace" +import { renderHubFlow } from "./fixtures/render-hub-flow" + +const repository = { id: "2001", nameWithOwner: "github/prototype", defaultBranch: "main" } +const settings = `/repositories/${repository.id}/learnings/settings` + +function response(notes: boolean, reviewComments: boolean, reading = false) { + return Response.json({ + repository, + ...(reading + ? { + enabled: false, + monthlyBudgetCredits: "100", + usedCredits: "4", + screenshots: { allowed: false, changedBy: null, changedAt: null }, + permissions: { changeRepository: true, changeBudget: true }, + } + : {}), + notes: { allowed: notes, changedBy: null, changedAt: null }, + reviewComments: { allowed: reviewComments, changedBy: null, changedAt: null }, + }) +} + +describe("Learning settings", () => { + it("saves each consent choice separately and shows the refreshed settings", async () => { + let notesAllowed = false + let commentsAllowed = true + const changes: unknown[] = [] + const api = stubHubFetch( + ...authenticatedWorkspace([repository]), + http.get(`/api/repositories/${repository.id}/learnings/evaluations`, () => + response(notesAllowed, commentsAllowed, true), + ), + http.patch(`/api${settings}`, async ({ request }) => { + const change = (await request.json()) as LearningSettingsInput + changes.push(change) + notesAllowed = change.notes ?? notesAllowed + commentsAllowed = change.reviewComments ?? commentsAllowed + return response(notesAllowed, commentsAllowed) + }), + ) + const router = await renderHubFlow(api, settings) + const header = screen + .getByRole("heading", { name: "Learning settings", level: 1 }) + .closest("header")! + expect(header).toHaveClass("repository-page-header") + expect(within(header).getByRole("link", { name: "Back to learnings" })).toHaveAttribute( + "href", + `/repositories/${repository.id}/learnings`, + ) + const notes = screen.getByRole("switch", { name: "Learn from Pick & Polish notes" }) + const comments = screen.getByRole("switch", { name: "Learn from review comments" }) + + await router.settle(() => fireEvent.click(notes)) + expect(changes).toEqual([{ notes: true }]) + expect(notes).toBeChecked() + expect(comments).toBeChecked() + + await router.settle(() => fireEvent.click(comments)) + expect(changes).toEqual([{ notes: true }, { reviewComments: false }]) + expect(notes).toBeChecked() + expect(comments).not.toBeChecked() + }) + + it("saves a Hub budget without allowing that administrator to change repository consent", async () => { + const changes: unknown[] = [] + let budget = "100" + const api = stubHubFetch( + ...authenticatedWorkspace([repository]), + http.get(`/api/repositories/${repository.id}/learnings/evaluations`, () => + Response.json({ + repository, + monthlyBudgetCredits: budget, + usedCredits: "4", + permissions: { changeRepository: false, changeBudget: true }, + }), + ), + http.patch("/api/learnings/evaluation-budget", async ({ request }) => { + const change = (await request.json()) as { monthlyBudgetCredits: string } + changes.push(change) + budget = change.monthlyBudgetCredits + return Response.json({ notice: "Budget saved." }) + }), + ) + const router = await renderHubFlow(api, `/repositories/${repository.id}/learnings/evaluations`) + expect(screen.queryByRole("switch")).not.toBeInTheDocument() + expect(screen.queryByRole("heading", { name: "Review comments" })).not.toBeInTheDocument() + expect(screen.queryByRole("heading", { name: "Pick & Polish notes" })).not.toBeInTheDocument() + fireEvent.change(screen.getByLabelText("Shared Hub budget", { selector: "input" }), { + target: { value: "0.000000001" }, + }) + await router.settle(() => fireEvent.click(screen.getByRole("button", { name: "Save" }))) + expect(changes).toEqual([{ monthlyBudgetCredits: "0.000000001" }]) + expect(screen.getByText("Budget saved.")).toBeInTheDocument() + }) + + it("lets a repository administrator enable evaluations before allowing screenshots", async () => { + let enabled = false + let screenshots = false + const endpoint = `/api/repositories/${repository.id}/learnings/evaluations` + const changes: unknown[] = [] + const router = await renderHubFlow( + stubHubFetch( + ...authenticatedWorkspace([repository]), + http.get(endpoint, async () => + Response.json({ + ...(await response(false, false, true).json()), + enabled, + screenshots: { allowed: screenshots, changedBy: null, changedAt: null }, + permissions: { changeRepository: true, changeBudget: false }, + }), + ), + http.patch(endpoint, async ({ request }) => { + const change = (await request.json()) as { enabled?: boolean; screenshots?: boolean } + changes.push(change) + enabled = change.enabled ?? enabled + screenshots = enabled && (change.screenshots ?? screenshots) + return Response.json({ notice: "Learning settings saved." }) + }), + ), + settings, + ) + const evaluate = screen.getByRole("switch", { name: `Evaluate ${repository.nameWithOwner}` }) + const images = screen.getByRole("switch", { name: "Allow screenshots" }) + expect(screen.queryByRole("textbox", { name: "Shared Hub budget" })).not.toBeInTheDocument() + expect(images).toBeDisabled() + await router.settle(() => fireEvent.click(evaluate)) + await router.settle(() => fireEvent.click(images)) + expect(images).toBeChecked() + await router.settle(() => fireEvent.click(evaluate)) + expect(images).toBeDisabled() + expect(images).not.toBeChecked() + expect(changes).toEqual([{ enabled: true }, { screenshots: true }, { enabled: false }]) + }) + + it("blocks both switches during a save and restores the saved choices after failure", async () => { + const pending = deferred() + onTestFinished(() => pending.resolve()) + const api = stubHubFetch( + ...authenticatedWorkspace([repository]), + http.get(`/api/repositories/${repository.id}/learnings/evaluations`, () => + response(false, true, true), + ), + http.patch(`/api${settings}`, async () => { + await pending.promise + return Response.json({ error: "Hub could not save this setting." }, { status: 503 }) + }), + ) + const router = await renderHubFlow(api, settings) + const notes = screen.getByRole("switch", { name: "Learn from Pick & Polish notes" }) + const comments = screen.getByRole("switch", { name: "Learn from review comments" }) + + fireEvent.click(notes) + await waitFor(() => expect(notes).toBeDisabled()) + expect(comments).toBeDisabled() + await router.settle(() => pending.resolve()) + + const page = within(screen.getByRole("region", { name: "Learning settings" })) + expect(page.getByRole("alert")).toHaveTextContent("Hub could not save this setting.") + expect(notes).not.toBeChecked() + expect(comments).toBeChecked() + expect(notes).toBeEnabled() + expect(comments).toBeEnabled() + }) +}) diff --git a/hub/client/application/hub/routes/learning-settings/index.tsx b/hub/client/application/hub/routes/learning-settings/index.tsx new file mode 100644 index 000000000..a0c584c13 --- /dev/null +++ b/hub/client/application/hub/routes/learning-settings/index.tsx @@ -0,0 +1,153 @@ +import { data, useFetcher, useOutletContext } from "react-router" +import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router" + +import { recordIdentifierSchema, workspaceResponseSchema } from "@application/hub/contracts" +import { + evaluationSettingsResponseSchema, + learningMutationResponseSchema, + learningSettingsInputSchema, + learningSettingsResponseSchema, +} from "@application/hub/learnings-contracts" +import type { LearningSettingsInput } from "@application/hub/learnings-contracts/types" +import { RepositoryWorkspace } from "@features/repository-workspace" +import { ApiRequestError } from "@application/hub/requests/api-request-error" +import { repositoryWorkspace } from "@application/hub/view-models/repository-workspace" +import { LearningSettingsPage } from "@pages/learning-settings-page" +import type { LearningSettingsChange } from "@pages/learning-settings-page/types" + +import { productActionError } from "../product-action-error" +import { requestProductJson } from "../request-product-json" +import type { WorkspaceRouteHandle } from "../workspace/types" + +export const handle = { workspaceSection: "learnings" } satisfies WorkspaceRouteHandle + +function repositoryId(params: LoaderFunctionArgs["params"]) { + const parsed = recordIdentifierSchema.safeParse(params.repositoryId) + if (!parsed.success) throw new Response("Invalid repository identifier.", { status: 400 }) + return parsed.data +} + +export async function clientLoader({ request, params }: LoaderFunctionArgs) { + const id = repositoryId(params) + const response = await requestProductJson( + request, + `/api/repositories/${id}/learnings/evaluations`, + evaluationSettingsResponseSchema, + ) + if (response.repository.id !== id) { + throw new Response("This repository is not available.", { status: 404 }) + } + return response +} + +export async function clientAction({ request, params }: ActionFunctionArgs) { + if (request.method.toUpperCase() !== "POST") { + return data({ saved: false, error: "Method not allowed." }, { status: 405 }) + } + const id = repositoryId(params) + const form = await request.formData() + const setting = form.get("setting") + const allowed = form.get("allowed") + try { + if (setting === "monthlyBudgetCredits" || setting === "enabled" || setting === "screenshots") { + const budget = setting === "monthlyBudgetCredits" + if (typeof allowed !== "string" || (!budget && allowed !== "true" && allowed !== "false")) { + return data({ saved: false, error: "Choose a valid evaluation setting." }, { status: 422 }) + } + const result = await requestProductJson( + request, + budget + ? "/api/learnings/evaluation-budget" + : `/api/repositories/${id}/learnings/evaluations`, + learningMutationResponseSchema, + { method: "PATCH", body: { [setting]: budget ? allowed.trim() : allowed === "true" } }, + ) + return data({ saved: true, notice: result.notice }) + } + const input: LearningSettingsInput = + setting === "notes" && (allowed === "true" || allowed === "false") + ? { notes: allowed === "true" } + : setting === "reviewComments" && (allowed === "true" || allowed === "false") + ? { reviewComments: allowed === "true" } + : {} + const parsed = learningSettingsInputSchema.safeParse(input) + if (!parsed.success) { + return data( + { saved: false, error: "Choose a Learning setting and try again." }, + { status: 422 }, + ) + } + await requestProductJson( + request, + `/api/repositories/${id}/learnings/settings`, + learningSettingsResponseSchema, + { method: "PATCH", body: parsed.data }, + ) + return data({ saved: true, notice: "Learning settings saved." }) + } catch (error) { + if (error instanceof Response) { + return data({ saved: false, error: await error.text() }, { status: error.status }) + } + if (error instanceof ApiRequestError && [403, 404, 409, 422, 502, 503].includes(error.status)) { + return data({ saved: false, error: error.message }, { status: error.status }) + } + return productActionError(error) + } +} + +export function meta({ loaderData }: { loaderData?: { repository: { nameWithOwner: string } } }) { + return [ + { + title: loaderData + ? `Learning settings - ${loaderData.repository.nameWithOwner} - Replica Hub` + : "Replica Hub", + }, + ] +} + +export default function LearningSettings({ + loaderData, +}: { + loaderData: Awaited> +}) { + const workspace = workspaceResponseSchema.parse(useOutletContext()) + const fetcher = useFetcher<{ saved: boolean; error?: string; notice?: string }>() + const busy = fetcher.state !== "idle" + const pageWorkspace = { + ...repositoryWorkspace(workspace, loaderData.repository), + learningsPath: `/repositories/${loaderData.repository.id}/learnings`, + selectedSection: "learnings" as const, + } + const data = { + ...pageWorkspace, + repositoryName: loaderData.repository.nameWithOwner, + learningsPath: `/repositories/${loaderData.repository.id}/learnings`, + monthlyBudgetCredits: loaderData.monthlyBudgetCredits, + usedCredits: loaderData.usedCredits, + changeBudget: loaderData.permissions.changeBudget, + repositorySettings: + "enabled" in loaderData + ? { + enabled: loaderData.enabled, + screenshots: loaderData.screenshots, + notes: loaderData.notes, + reviewComments: loaderData.reviewComments, + } + : null, + } + + return ( + + { + const [setting, value] = Object.entries(change)[0]! + void fetcher.submit({ setting, allowed: String(value) }, { method: "post" }) + }} + /> + + ) +} diff --git a/hub/client/application/hub/routes/learnings-flow.test.tsx b/hub/client/application/hub/routes/learnings-flow.test.tsx index 5e59422e4..368a2c529 100644 --- a/hub/client/application/hub/routes/learnings-flow.test.tsx +++ b/hub/client/application/hub/routes/learnings-flow.test.tsx @@ -36,6 +36,7 @@ function learningsResponse() { today: "2026-11-10", usageCredits: "0.0945", runAvailable: true, + firstRunNeeded: false, loadError: null, identityReviewCount: 1, suggestions: [ @@ -87,6 +88,7 @@ function learningsResponse() { acceptedAt: "2026-11-08T20:00:00.000Z", edited: true, status: "recalled" as const, + shareable: true, }, { id: "mem_damaged", @@ -135,6 +137,9 @@ function learningsResponse() { function emptyHistory() { return http.get("/api/repositories/2001/learnings/:learningId/history", () => Response.json({ + outcomes: [], + earlierGuidance: [], + updates: [], decisions: [], evidence: [], otherEvidenceCount: 0, @@ -192,6 +197,9 @@ describe("Learnings frontend integration", () => { http.get(`/api/repositories/2001/learnings`, () => Response.json(learningsResponse())), http.get("/api/repositories/2001/learnings/mem_accepted/history", () => Response.json({ + outcomes: [], + earlierGuidance: [], + updates: [], decisions: [ { version: 1, @@ -282,9 +290,7 @@ describe("Learnings frontend integration", () => { await screen.findByRole("link", { name: "Show a visible label above every form field." }), ).toBeVisible() expect(await screen.findByRole("button", { name: "Find learnings now" })).toBeVisible() - fireEvent.click(screen.getByText("Recent runs ยท Finished")) - expect(screen.getByText("Copilot usage: 0.0945 AI credits")).toBeVisible() - expect(screen.getByText("Copilot did not return a result.")).toBeVisible() + expect(screen.queryByText(/Recent runs/)).not.toBeInTheDocument() }) it("shows migration redaction follow-ups to the repository administrator after reload", async () => { @@ -309,7 +315,7 @@ describe("Learnings frontend integration", () => { expect(screen.getByText(notice)).toBeVisible() }) - it("posts a run only to the dedicated repository endpoint", async () => { + it("asks before allowing current and future review-comment imports", async () => { const server = stubHubFetch(...learningsWorkspace()) const runRequests = vi.fn() server.use( @@ -324,11 +330,24 @@ describe("Learnings frontend integration", () => { ) const router = await renderHubFlow(server, "/repositories/2001/learnings") + const run = screen.getByRole("button", { name: "Find learnings now" }) + fireEvent.click(run) + const confirmation = screen.getByRole("dialog") + expect(confirmation).toHaveTextContent("github/prototype") + expect(confirmation).toHaveTextContent(/review comments.*this run and future runs/i) + fireEvent.click(within(confirmation).getByRole("button", { name: "Cancel" })) + await router.settle() + expect(runRequests).not.toHaveBeenCalled() + expect(screen.queryByRole("dialog")).not.toBeInTheDocument() + + fireEvent.click(run) await router.settle(() => - fireEvent.click(screen.getByRole("button", { name: "Find learnings now" })), + fireEvent.click( + within(screen.getByRole("dialog")).getByRole("button", { name: "Confirm and run" }), + ), ) - expect(runRequests).toHaveBeenCalledWith({ contentType: null, text: "" }) + expect(runRequests).toHaveBeenCalledExactlyOnceWith({ contentType: null, text: "" }) expect(await screen.findByText("Hub will look for learnings shortly.")).toBeVisible() }) @@ -386,6 +405,213 @@ describe("Learnings frontend integration", () => { expect(screen.getByRole("button", { name: "Edit learning" })).toBeVisible() }) + it("applies edited wording from a suggested update and shows it in the history", async () => { + const original = learningsResponse() + const learning = { + ...original.learnings[0]!, + title: "One primary button", + content: "Use one primary button per form.", + } + const build = { prototypeId: "1", prototypeName: "Checkout", number: 4 } + const score = { + id: "score_12345678", + source: "automated", + efficiency: 2, + followed: "followed", + reasoning: "The button was placed inconsistently.", + issue: "The guidance does not say where the button goes.", + scoredAt: "2026-11-09T20:00:00.000Z", + build, + } + const update = { + id: "update_1234567890abcdef", + issue: score.issue, + title: "Place the primary button", + content: "Put one primary button at the bottom of each form.", + reasoning: "Naming the position removes the guess.", + support: [build, build], + } + const decision = vi.fn() + let applied = false + const server = stubHubFetch( + ...learningsWorkspace(), + http.get("/api/repositories/2001/learnings", () => + Response.json({ + ...original, + learnings: [ + applied + ? { + ...learning, + title: "Place the main button", + content: "Put the primary button below each form.", + digest: `sha256:${"b".repeat(64)}`, + acceptedBy: "octocat", + acceptedAt: "2026-11-10T12:00:00.000Z", + } + : learning, + ], + }), + ), + http.get("/api/repositories/2001/learnings/mem_accepted/history", () => + Response.json({ + decisions: [ + { + version: 2, + state: "accepted", + change: "accepted", + by: "octocat", + at: "2026-11-08T20:00:00.000Z", + reason: null, + }, + ...(applied + ? [ + { + version: 3, + state: "accepted", + change: "edited", + by: "octocat", + at: "2026-11-10T12:00:00.000Z", + reason: "Make the placement clear.", + }, + ] + : []), + ], + evidence: [], + otherEvidenceCount: 0, + contradictions: [], + otherContradictionsCount: 0, + outcomes: applied ? [] : [score], + earlierGuidance: applied + ? [{ version: 2, title: learning.title, content: learning.content, outcomes: [score] }] + : [], + updates: applied ? [] : [update], + updateNeedsMoreEvidence: false, + }), + ), + http.post("/api/repositories/2001/learnings/mem_accepted/decision", async ({ request }) => { + decision(await request.json()) + applied = true + return Response.json({ notice: "Learning updated." }) + }), + ) + const router = await renderHubFlow(server, "/repositories/2001/learnings?learning=mem_accepted") + const suggestion = await screen.findByRole("region", { name: "Suggested update" }) + + expect(suggestion.querySelector("del")).toBeInTheDocument() + expect(suggestion.querySelector("ins")).toBeInTheDocument() + expect(within(suggestion).getAllByRole("link", { name: "Checkout, Build 4" })).toHaveLength(1) + expect(within(suggestion).getByRole("link", { name: "Checkout, Build 4" })).toHaveAttribute( + "href", + "/repositories/2001/prototypes/1?build=4", + ) + + const form = await submitDialog( + "Apply update", + { + Title: "Place the main button", + Guidance: "Put the primary button below each form.", + "Why apply it?": "Make the placement clear.", + }, + "Apply update", + ) + await router.settle(() => fireEvent.submit(form)) + + expect(decision).toHaveBeenCalledExactlyOnceWith({ + decision: "apply_update", + proposalId: update.id, + title: "Place the main button", + content: "Put the primary button below each form.", + reason: "Make the placement clear.", + }) + expect(screen.getByRole("heading", { name: "Place the main button" })).toBeVisible() + expect(screen.getByText("Put the primary button below each form.")).toBeVisible() + expect(screen.getByRole("region", { name: "Decision history" })).toHaveTextContent( + "Edited by @octocat", + ) + expect(screen.getByRole("region", { name: "Decision history" })).toHaveTextContent( + "Make the placement clear.", + ) + expect(screen.getByRole("region", { name: "Earlier guidance" })).toHaveTextContent( + learning.content, + ) + expect(screen.queryByRole("region", { name: "Suggested update" })).not.toBeInTheDocument() + expect(screen.queryByRole("dialog")).not.toBeInTheDocument() + }) + + it("keeps a failed dismissal for retry and removes it without changing the learning", async () => { + const original = learningsResponse() + const learning = original.learnings[0]! + const update = { + id: "update_1234567890abcdef", + issue: "The guidance does not say where the button goes.", + title: null, + content: "Put one primary button at the bottom of each form.", + reasoning: "Naming the position removes the guess.", + support: [{ prototypeId: "1", prototypeName: "Checkout", number: 4 }], + } + const bodies: unknown[] = [] + let dismissed = false + const server = stubHubFetch( + ...learningsWorkspace(), + http.get("/api/repositories/2001/learnings", () => Response.json(original)), + http.get("/api/repositories/2001/learnings/mem_accepted/history", () => + Response.json({ + decisions: [], + evidence: [], + otherEvidenceCount: 0, + contradictions: [], + otherContradictionsCount: 0, + outcomes: [], + earlierGuidance: [], + updates: dismissed ? [] : [update], + updateNeedsMoreEvidence: false, + }), + ), + http.post("/api/repositories/2001/learnings/mem_accepted/decision", async ({ request }) => { + bodies.push(await request.json()) + if (bodies.length === 1) { + return Response.json({ error: "Decisions are temporarily unavailable." }, { status: 503 }) + } + dismissed = true + return Response.json({ notice: "Suggested update dismissed." }) + }), + ) + const router = await renderHubFlow(server, "/repositories/2001/learnings?learning=mem_accepted") + const form = await submitDialog( + "Dismiss", + { "Why dismiss it?": "The position depends on the form." }, + "Dismiss", + ) + await router.settle(() => fireEvent.submit(form)) + + const dialog = screen.getByRole("dialog", { name: "Dismiss suggested update" }) + expect(within(dialog).getByRole("alert")).toHaveTextContent( + "Decisions are temporarily unavailable.", + ) + expect(within(dialog).getByRole("textbox", { name: "Why dismiss it?" })).toHaveValue( + "The position depends on the form.", + ) + const retry = within(dialog).getByRole("button", { name: "Dismiss" }).closest("form") + if (!retry) throw new Error("The dismissal control must belong to a form.") + await router.settle(() => fireEvent.submit(retry)) + + expect(bodies).toEqual([ + { + decision: "dismiss_update", + proposalId: update.id, + reason: "The position depends on the form.", + }, + { + decision: "dismiss_update", + proposalId: update.id, + reason: "The position depends on the form.", + }, + ]) + expect(screen.getByText(learning.content!, { selector: "p" })).toBeVisible() + expect(screen.queryByRole("region", { name: "Suggested update" })).not.toBeInTheDocument() + expect(screen.queryByRole("dialog")).not.toBeInTheDocument() + }) + it("shows a changed suggestion's current wording after a stale-digest response", async () => { const server = stubHubFetch(...learningsWorkspace()) const original = learningsResponse() @@ -547,6 +773,116 @@ describe("Learnings frontend integration", () => { expect(bodies).toEqual([{ decision: "reinstate", digest, reason: "External links only." }]) }) + it("asks to share a learning and shows why Hub could not save it", async () => { + const server = stubHubFetch(...learningsWorkspace()) + const bodies: unknown[] = [] + server.use( + http.get(`/api/repositories/2001/learnings`, () => + Response.json({ + ...learningsResponse(), + permissions: { viewEvidence: true, decide: true, requestRun: true, share: true }, + }), + ), + emptyHistory(), + http.post(`/api/repositories/2001/learnings/mem_accepted/share`, async ({ request }) => { + bodies.push(await request.json()) + return Response.json({ error: "Sharing is temporarily unavailable." }, { status: 503 }) + }), + ) + const router = await renderHubFlow(server, "/repositories/2001/learnings?learning=mem_accepted") + const toggle = await screen.findByRole("switch", { name: "Share across Hub" }) + await router.settle(() => fireEvent.click(toggle)) + + expect(await screen.findByText("Sharing is temporarily unavailable.")).toBeVisible() + expect(bodies).toEqual([{ shared: true, digest }]) + }) + + it("withdraws a saved share without reinstating or revealing a retired learning", async () => { + let shared = true + const bodies: unknown[] = [] + const server = stubHubFetch( + ...learningsWorkspace(), + http.get("/api/repositories/2001/learnings", () => + Response.json({ + ...learningsResponse(), + permissions: { viewEvidence: true, decide: true, requestRun: true, share: true }, + rejected: [ + { + id: "mem_old", + state: "retired", + shared, + content: null, + title: null, + digest: null, + replaces: [], + reason: null, + decidedBy: null, + decidedAt: null, + }, + ], + }), + ), + emptyHistory(), + http.post("/api/repositories/2001/learnings/mem_old/share", async ({ request }) => { + bodies.push(await request.json()) + shared = false + return Response.json({ notice: "Stopped sharing across Hub." }) + }), + ) + const router = await renderHubFlow( + server, + "/repositories/2001/learnings?status=rejected&learning=mem_old", + ) + const remove = await screen.findByRole("button", { name: "Remove saved share" }) + expect(screen.queryByRole("button", { name: "Accept learning" })).not.toBeInTheDocument() + await router.settle(() => fireEvent.click(remove)) + expect(bodies).toEqual([{ shared: false }]) + expect(screen.queryByRole("button", { name: "Remove saved share" })).not.toBeInTheDocument() + expect( + screen.getByText("This learning's wording is not available for review.", { selector: "p" }), + ).toBeVisible() + }) + + it("shows a learning another repository shared as read-only", async () => { + const historyRequests = vi.fn() + const server = stubHubFetch( + ...learningsWorkspace(), + http.get("/api/repositories/2001/learnings", () => + Response.json({ + ...learningsResponse(), + shared: [ + { + id: "mem_shared", + title: "Keep labels visible", + content: "Show a label above every field.", + source: "github/design-guidelines", + sharedBy: "mona", + sharedAt: "2026-11-07T20:00:00.000Z", + status: "recalled", + }, + ], + }), + ), + http.get("/api/repositories/2001/learnings/:learningId/history", historyRequests), + ) + await renderHubFlow( + server, + "/repositories/2001/learnings?learning=shared%3Agithub%2Fdesign-guidelines%3Amem_shared", + ) + + expect( + await screen.findByText( + "Shared from github/design-guidelines ยท Read-only in this repository.", + ), + ).toBeVisible() + expect( + screen.getByText("Agents in this repository don't get shared learnings yet."), + ).toBeVisible() + expect(screen.queryByRole("button", { name: "Edit learning" })).not.toBeInTheDocument() + expect(screen.queryByRole("switch", { name: "Share across Hub" })).not.toBeInTheDocument() + expect(historyRequests).not.toHaveBeenCalled() + }) + it("shows a Hub administrator without repository authority a read-only library", async () => { const server = stubHubFetch( ...learningsWorkspace(), @@ -564,7 +900,8 @@ describe("Learnings frontend integration", () => { await renderHubFlow(server, "/repositories/2001/learnings") expect(await screen.findByRole("heading", { name: "Browse learnings" })).toBeVisible() - expect(screen.queryByRole("heading", { name: "Recent runs" })).not.toBeInTheDocument() + expect(screen.getByRole("group", { name: "Daily learning activity for 2026" })).toBeVisible() + expect(screen.queryByRole("button", { name: "Find learnings now" })).not.toBeInTheDocument() expect(screen.queryByRole("button", { name: "Accept" })).not.toBeInTheDocument() }) @@ -588,7 +925,7 @@ describe("Learnings frontend integration", () => { expect(screen.queryByRole("button", { name: "Find learnings now" })).not.toBeInTheDocument() }) - it("keeps Copilot connection management outside repository Learnings", async () => { + it("warns a repository administrator who cannot connect Copilot without offering that action", async () => { const server = stubHubFetch(...learningsWorkspace()) const response = learningsResponse() server.use( @@ -609,6 +946,7 @@ describe("Learnings frontend integration", () => { screen.getByRole("link", { name: "Show a visible label above every form field." }), ).toBeVisible() expect(screen.queryByRole("button", { name: "Find learnings now" })).not.toBeInTheDocument() + expect(screen.queryByRole("link", { name: /connect copilot/i })).not.toBeInTheDocument() expect(screen.queryByRole("button", { name: /connect copilot/i })).not.toBeInTheDocument() }) diff --git a/hub/client/application/hub/routes/product-routes.ts b/hub/client/application/hub/routes/product-routes.ts index 0d0b79f60..e1ecaf826 100644 --- a/hub/client/application/hub/routes/product-routes.ts +++ b/hub/client/application/hub/routes/product-routes.ts @@ -11,6 +11,9 @@ export const repositoryProductRoutes: RouteConfigEntry[] = [ route("prototypes/:prototypeId/share-links", "routes/product-share-links/index.tsx"), route("analytics", "routes/settings-analytics/index.tsx"), route("learnings", "routes/settings-learnings/index.tsx"), + route("learnings/agents", "routes/learning-agents/index.tsx"), + route("learnings/settings", "routes/learning-settings/index.tsx"), + route("learnings/evaluations", "routes/learning-evaluations/index.tsx"), ] export const workspaceProductRoutes: RouteConfigEntry[] = [ diff --git a/hub/client/application/hub/routes/prototype/index.tsx b/hub/client/application/hub/routes/prototype/index.tsx index ee33992d4..90be850f7 100644 --- a/hub/client/application/hub/routes/prototype/index.tsx +++ b/hub/client/application/hub/routes/prototype/index.tsx @@ -1,3 +1,4 @@ +import { useEffect, useState } from "react" import { data, useFetcher, useOutletContext } from "react-router" import { prototypeEditSchema } from "@application/hub/contracts" @@ -9,7 +10,9 @@ import type { import { readRecordIdentifier } from "@application/hub/read-record-identifier" import { ApiContractError } from "@application/hub/requests/api-contract-error" import { ApiRequestError } from "@application/hub/requests/api-request-error" +import { getAppliedLearnings } from "@application/hub/requests/get-applied-learnings" import { getPrototype } from "@application/hub/requests/get-prototype" +import type { AppliedLearningResponse } from "@application/hub/learnings-contracts/types" import { updatePrototype } from "@application/hub/requests/update-prototype" import { PrototypeScreen } from "@application/hub/screens/prototype-screen" @@ -34,6 +37,34 @@ export async function clientLoader({ ) } +/** + * Reads what agents applied in the selected Build after the page shows. Learnings are + * optional, so a slow or failed read never holds up or breaks the prototype page. + */ +function useAppliedLearnings(prototype: PrototypeResponse) { + const repositoryId = prototype.repository.id + const prototypeId = prototype.prototype.id + const commitSha = prototype.selectedBuild?.commitSha?.toLowerCase() + const key = `${repositoryId}/${prototypeId}/${commitSha}` + const [loaded, setLoaded] = useState<{ key: string; learnings: AppliedLearningResponse[] }>() + useEffect(() => { + if (!commitSha || !/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(commitSha)) return + const controller = new AbortController() + getAppliedLearnings( + new Request(window.location.href, { signal: controller.signal }), + repositoryId, + prototypeId, + commitSha, + ).then( + (response) => setLoaded({ key, learnings: response.learnings }), + () => undefined, + ) + return () => controller.abort() + }, [commitSha, key, prototypeId, repositoryId]) + // Learnings from a previously selected Build must not show beside this one. + return loaded?.key === key ? loaded.learnings : [] +} + export async function clientAction({ request, params, @@ -94,11 +125,13 @@ export default function Prototype({ loaderData }: Pick { void fetcher.submit( { diff --git a/hub/client/application/hub/routes/real-build-history.test.tsx b/hub/client/application/hub/routes/real-build-history.test.tsx index a847d3a84..1261228be 100644 --- a/hub/client/application/hub/routes/real-build-history.test.tsx +++ b/hub/client/application/hub/routes/real-build-history.test.tsx @@ -125,7 +125,10 @@ describe("real Build history", () => { { build: "3" }, ]) expect(screen.queryByRole("link", { name: "Analytics" })).not.toBeInTheDocument() - expect(screen.queryByRole("link", { name: "Learnings" })).not.toBeInTheDocument() + expect(screen.getByRole("link", { name: "Learnings" })).toHaveAttribute( + "href", + `/repositories/${repositoryId}/learnings`, + ) expect(document.querySelector('form[action="/api/auth/session/sign-out"]')).not.toBeNull() expect(document.querySelector('form[action="/session"]')).toBeNull() const history = screen.getByRole("list", { name: "History" }) diff --git a/hub/client/application/hub/routes/real-workspace-navigation.test.tsx b/hub/client/application/hub/routes/real-workspace-navigation.test.tsx index 761f0a9cd..83feabcf7 100644 --- a/hub/client/application/hub/routes/real-workspace-navigation.test.tsx +++ b/hub/client/application/hub/routes/real-workspace-navigation.test.tsx @@ -1336,6 +1336,26 @@ describe("real workspace navigation", () => { expect(screen.queryByRole("link", { name: "Prototypes" })).not.toBeInTheDocument() }) + it("returns to an agent's approval request after sign-in", async () => { + const path = "/agents/approve/7c9e6679-7425-40de-944b-e07fc1f90ae7" + await renderApplication(path, [ + json("/api/auth/providers", { providers: ["github"] }), + ...[ + "/api/auth/session", + "/api/agent-connections/authorizations/7c9e6679-7425-40de-944b-e07fc1f90ae7", + ].map((endpoint) => + http.get(`${window.location.origin}${endpoint}`, () => + Response.json({ error: "Sign in to continue." }, { status: 401 }), + ), + ), + ]) + + const signIn = await screen.findByRole("button", { + name: "Sign in with GitHub", + }) + expect(new FormData(signIn.form ?? undefined).get("return_to")).toBe(path) + }) + it("shows a disabled picker and Prototypes without Create on a repository-free landing", async () => { await renderApplication("/repositories", workspaceApi([])) diff --git a/hub/client/application/hub/routes/route-naming.test.tsx b/hub/client/application/hub/routes/route-naming.test.tsx index d9aa33af0..17b8bbd5c 100644 --- a/hub/client/application/hub/routes/route-naming.test.tsx +++ b/hub/client/application/hub/routes/route-naming.test.tsx @@ -147,6 +147,9 @@ describe("Hub primary route names", () => { http.get(`/api${path}/:learningId/history`, () => Response.json({ decisions: [], + outcomes: [], + earlierGuidance: [], + updates: [], evidence: [], otherEvidenceCount: 0, contradictions: [], @@ -164,7 +167,8 @@ describe("Hub primary route names", () => { }), ) const router = await renderHubFlow(api, `${path}?repositoryId=${first.id}`) - const run = screen.getByRole("button", { name: "Find learnings now" }) + fireEvent.click(screen.getByRole("button", { name: "Find learnings now" })) + const run = within(screen.getByRole("dialog")).getByRole("button", { name: "Confirm and run" }) expect(new URL(run.closest("form")!.action).pathname).toBe(`${path}/runs`) await router.settle(() => fireEvent.click(run)) await router.settle(async () => diff --git a/hub/client/application/hub/routes/settings-learnings/index.tsx b/hub/client/application/hub/routes/settings-learnings/index.tsx index 057f17f59..9c18bdd52 100644 --- a/hub/client/application/hub/routes/settings-learnings/index.tsx +++ b/hub/client/application/hub/routes/settings-learnings/index.tsx @@ -12,6 +12,7 @@ import { learningDecisionInputSchema, learningHistoryResponseSchema, learningMutationResponseSchema, + learningShareInputSchema, learningsResponseSchema, } from "@application/hub/learnings-contracts" import type { ProductActionResult } from "@application/hub/product-contracts/types" @@ -141,7 +142,7 @@ function submitDecision( form: FormData, ) { const prefix = `${route}/` - const suffix = "/decision" + const suffix = source.pathname.endsWith("/share") ? "/share" : "/decision" if (!source.pathname.startsWith(prefix) || !source.pathname.endsWith(suffix)) { throw new Response("This learning action is not connected.", { status: 400 }) } @@ -155,6 +156,20 @@ function submitDecision( throw new Response("Invalid learning identifier.", { status: 400 }) } const path = `/api/repositories/${repositoryId}/learnings/${encodeURIComponent(learningId)}` + if (suffix === "/share") { + const shared = form.get("shared") + const parsed = learningShareInputSchema.safeParse({ + shared: shared === "true" ? true : shared === "false" ? false : shared, + ...(shared === "true" ? { digest: form.get("digest") } : {}), + }) + if (!parsed.success) { + throw new Response("Choose whether to share this learning.", { status: 422 }) + } + return requestProductJson(request, `${path}/share`, learningMutationResponseSchema, { + method: "POST", + body: parsed.data, + }) + } const decision = form.get("decision") const title = form.get("title") const input = @@ -179,7 +194,17 @@ function submitDecision( } : decision === "reinstate" ? { decision, digest: form.get("digest"), reason: form.get("reason") } - : { decision } + : decision === "apply_update" + ? { + decision, + proposalId: form.get("proposalId"), + ...(typeof title === "string" && title.trim() ? { title } : {}), + content: form.get("content"), + reason: form.get("reason"), + } + : decision === "dismiss_update" + ? { decision, proposalId: form.get("proposalId"), reason: form.get("reason") } + : { decision } const parsed = learningDecisionInputSchema.safeParse(input) if (!parsed.success) { throw new Response(parsed.error.issues.map(({ message }) => message).join(" "), { status: 422 }) @@ -220,6 +245,8 @@ function SettingsLearningsContent({ const revalidatedResult = useRef(undefined) const busy = fetcher.state !== "idle" || revalidator.state !== "idle" const result = busy ? undefined : fetcher.data + const page = settingsLearnings(workspace, loaderData, location, loaderData.history) + const detail = !page.accessDenied && page.library.selected !== null useEffect(() => { if (!result?.revalidate || revalidatedResult.current === result) return revalidatedResult.current = result @@ -228,15 +255,13 @@ function SettingsLearningsContent({ return ( { void fetcher.submit(input, { method: "post" }) }} > - + ) } diff --git a/hub/client/application/hub/screens/product-form-boundary/styles.css b/hub/client/application/hub/screens/product-form-boundary/styles.css index c9542bbe5..aae75890b 100644 --- a/hub/client/application/hub/screens/product-form-boundary/styles.css +++ b/hub/client/application/hub/screens/product-form-boundary/styles.css @@ -29,6 +29,7 @@ .hub-product-flow__workspace { position: relative; min-block-size: 0; + overflow: auto; flex: 1; contain: layout; } diff --git a/hub/client/application/hub/screens/prototype-screen/index.tsx b/hub/client/application/hub/screens/prototype-screen/index.tsx index 979d86ddd..df0ffbf57 100644 --- a/hub/client/application/hub/screens/prototype-screen/index.tsx +++ b/hub/client/application/hub/screens/prototype-screen/index.tsx @@ -8,6 +8,7 @@ import { MentionProvider } from "@components/mention-provider" import { PrototypesShowPage } from "@pages/prototypes-show-page" import type { PrototypeDetailsInput } from "@pages/prototypes-show-page/types" import type { PrototypeResponse, WorkspaceResponse } from "@application/hub/contracts/types" +import type { AppliedLearningResponse } from "@application/hub/learnings-contracts/types" import { prototypeShowData } from "@application/hub/view-models/prototype-show-data" import { createReviewTransport } from "@application/hub/create-review-transport" import { readReviewQuery } from "@application/hub/read-review-query" @@ -23,6 +24,7 @@ import { readPreviewReturnPath } from "@utils/read-preview-return-path" export function PrototypeScreen({ workspace, data, + appliedLearnings, onSaveDetails, savingDetails, detailsError, @@ -30,6 +32,7 @@ export function PrototypeScreen({ }: { workspace: WorkspaceResponse data: PrototypeResponse + appliedLearnings?: AppliedLearningResponse[] onSaveDetails: (details: PrototypeDetailsInput) => void savingDetails: boolean detailsError: string | null @@ -43,7 +46,12 @@ export function PrototypeScreen({ const repositoryCapabilities = workspace.repositories.find( ({ id }) => id === data.repository.id, )?.capabilities - const pageData = prototypeShowData(workspace, data, new URLSearchParams(location.search)) + const pageData = prototypeShowData( + workspace, + data, + new URLSearchParams(location.search), + appliedLearnings, + ) pageData.reviewReadOnly = !repositoryCapabilities?.reviewPrototypes if (pageData.reviewReadOnly) { pageData.reviewComments = { diff --git a/hub/client/application/hub/view-models/copilot-connection-page-data/index.test.ts b/hub/client/application/hub/view-models/copilot-connection-page-data/index.test.ts index 86f083c33..4892a9740 100644 --- a/hub/client/application/hub/view-models/copilot-connection-page-data/index.test.ts +++ b/hub/client/application/hub/view-models/copilot-connection-page-data/index.test.ts @@ -51,6 +51,8 @@ describe("copilotConnectionPageData()", () => { if (data.accessDenied) throw new Error("The administrator must receive connection controls.") expect(data.credentialLabel).toBeNull() expect(data.connect?.label).toBe("Connect Copilot") + expect(data.connect?.consequence).toMatch(/deployment-wide review-comment consent is enabled/) + expect(data.connect?.confirmLabel).toMatch(/connecting or checking Copilot/) expect([data.description, data.connect?.consequence].join(" ")).not.toMatch( /operator-provided token|configured token/i, ) diff --git a/hub/client/application/hub/view-models/copilot-connection-page-data/index.ts b/hub/client/application/hub/view-models/copilot-connection-page-data/index.ts index 6bf64d73a..7fa703040 100644 --- a/hub/client/application/hub/view-models/copilot-connection-page-data/index.ts +++ b/hub/client/application/hub/view-models/copilot-connection-page-data/index.ts @@ -8,6 +8,8 @@ export function copilotConnectionPageData( ): CopilotConnectionPageData { const verification = "Hub checks your live administrator session again after Copilot answers, before saving the change." + const reviewCommentConsent = + "If deployment-wide review-comment consent is enabled, connecting or checking Copilot records your consent to learn from comments in every repository. Repository administrators can turn this off for their repository." return { administrationWorkspace: workspace, heading: "Copilot", @@ -51,9 +53,10 @@ export function copilotConnectionPageData( ? "Check and connect Copilot" : "Connect Copilot", consequence: status.credentialIdentity - ? `Hub asks Copilot to verify a fresh credential for the ${status.credentialIdentity.organization} organization through GitHub App ${status.credentialIdentity.appId}. Later learning runs may send review comment text without reviewer identity. The organization's Copilot model policy, budget, and App installation revocation continue to apply.` - : "Hub asks Copilot to verify the configured credential. Later learning runs may send review comment text without reviewer identity. The available local providers attribute usage to the signed-in account or user-token identity.", - confirmLabel: "I understand and confirm connecting Copilot for this Hub.", + ? `Hub asks Copilot to verify a fresh credential for the ${status.credentialIdentity.organization} organization through GitHub App ${status.credentialIdentity.appId}. Later learning runs may send review comment text without reviewer identity. The organization's Copilot model policy, budget, and App installation revocation continue to apply. ${reviewCommentConsent}` + : `Hub asks Copilot to verify the configured credential. Later learning runs may send review comment text without reviewer identity. The available local providers attribute usage to the signed-in account or user-token identity. ${reviewCommentConsent}`, + confirmLabel: + "I understand this review-comment consent behavior and confirm connecting or checking Copilot for this Hub.", verification, }, disconnect: status.savedConnection diff --git a/hub/client/application/hub/view-models/learnings-library/index.test.ts b/hub/client/application/hub/view-models/learnings-library/index.test.ts index 7f5349602..cb9e472d9 100644 --- a/hub/client/application/hub/view-models/learnings-library/index.test.ts +++ b/hub/client/application/hub/view-models/learnings-library/index.test.ts @@ -80,6 +80,9 @@ describe("learningsLibrary()", () => { state, { pathname, search: "?status=rejected&learning=mem_retired" }, { + updates: [], + outcomes: [], + earlierGuidance: [], decisions: [ { version: 1, @@ -157,4 +160,36 @@ describe("learningsLibrary()", () => { const result = learningsLibrary(state, { pathname, search: "?learning=mem_excluded" }, null) expect(result.selected?.facts).toContain("Agents do not currently get this learning.") }) + it("counts the agent sessions a local suggestion came from instead of reviewers", () => { + const state = emptyLearnings() + state.solo = true + state.suggestions = [ + { + id: "mem_local", + title: "Visible field labels", + content: "Show a visible label above every form field.", + reviewDigest: digest, + support: { reviewers: 1, prototypes: 0 }, + replaces: [], + evidence: [], + sessions: { supporting: 2, opposing: 1 }, + otherEvidenceCount: 0, + contradictions: [], + otherContradictionsCount: 0, + }, + ] + + const result = learningsLibrary( + state, + { pathname, search: "?status=suggested&learning=mem_local" }, + null, + ) + + expect(result.selected?.facts).toEqual([ + "Found in 2 agent sessions", + "Questioned in 1 agent session", + ]) + expect(result.selected?.otherEvidence).toBeNull() + expect(result.selected?.otherContradictions).toBeNull() + }) }) diff --git a/hub/client/application/hub/view-models/learnings-library/index.ts b/hub/client/application/hub/view-models/learnings-library/index.ts index 41decbe32..ced57895f 100644 --- a/hub/client/application/hub/view-models/learnings-library/index.ts +++ b/hub/client/application/hub/view-models/learnings-library/index.ts @@ -2,12 +2,14 @@ import type { LearningDetail, LearningEvidence, LearningStatus, + LearningOutcome, LearningsLibraryData, LibraryLearning, } from "@features/learnings-library/types" import type { LearningEvidenceResponse, LearningHistoryResponse, + LearningOutcomeResponse, LearningsResponse, } from "@application/hub/learnings-contracts/types" @@ -69,8 +71,47 @@ function evidence(items: LearningEvidenceResponse[], repositoryId: string): Lear })) } +function buildLink(build: LearningOutcomeResponse["build"], repositoryId: string) { + return { + label: `${build.prototypeName}, Build ${build.number}`, + path: `/repositories/${repositoryId}/prototypes/${build.prototypeId}?build=${build.number}`, + } +} + +/** + * Reads each score as a plain result. A score only says something about the guidance + * when the agent followed it, and 3 or 4 means the work went well. + */ +function outcomes(items: LearningOutcomeResponse[], repositoryId: string): LearningOutcome[] { + function screenshot(value?: { sha256: string }) { + return value ? `/api/repositories/${repositoryId}/learnings/screenshots/${value.sha256}` : null + } + return items.toReversed().map((item) => { + const build = buildLink(item.build, repositoryId) + return { + id: item.id, + result: + item.followed !== "followed" + ? "inconclusive" + : item.efficiency >= 3 + ? "supports" + : "concern", + reviewerConfirmed: item.source === "reviewer_confirmed", + summary: item.issue ?? item.reasoning, + buildLabel: build.label, + buildPath: build.path, + evaluatedAt: item.scoredAt, + beforeScreenshotUrl: screenshot(item.before), + afterScreenshotUrl: screenshot(item.after), + } + }) +} + function detailEvidence( - source: Omit | null, + source: Pick< + LearningHistoryResponse, + "evidence" | "otherEvidenceCount" | "contradictions" | "otherContradictionsCount" + > | null, repositoryId: string, ) { return { @@ -109,38 +150,43 @@ export function learningsLibrary( history: LearningHistoryResponse | null, ): LearningsLibraryData { const params = new URLSearchParams(location.search) - const records: LearningRecord[] = [ - ...state.suggestions.map((entry) => ({ + function record( + entry: { id: string; title: string | null }, + status: LearningStatus, + guidance: string, + updatedAt: string | null, + source: LearningRecord["source"] = null, + ): LearningRecord { + return { id: entry.id, - status: "suggested" as const, - title: titleFrom(entry.title, entry.content), - guidance: entry.content, - updatedAt: null, - })), - ...state.learnings.map((entry) => { - const guidance = entry.content ?? unavailableGuidance(entry.status) - return { - id: entry.id, - status: "active" as const, - title: titleFrom(entry.title, guidance), - guidance, - updatedAt: entry.acceptedAt, - } - }), - ...state.rejected.map((entry) => { - const guidance = entry.content ?? unavailableGuidance(null) - return { - id: entry.id, - status: "rejected" as const, - title: titleFrom(entry.title, guidance), - guidance, - updatedAt: entry.decidedAt, - } - }), + status, + title: titleFrom(entry.title, guidance), + guidance, + updatedAt, + source, + } + } + const records = [ + ...state.suggestions.map((entry) => record(entry, "suggested", entry.content, null)), + ...state.learnings.map((entry) => + record(entry, "active", entry.content ?? unavailableGuidance(entry.status), entry.acceptedAt), + ), + ...(state.solo ? [] : (state.shared ?? [])).map((entry) => + record( + { ...entry, id: `shared:${entry.source}:${entry.id}` }, + "active", + entry.content ?? unavailableGuidance(null), + entry.sharedAt, + entry.source, + ), + ), + ...state.rejected.map((entry) => + record(entry, "rejected", entry.content ?? unavailableGuidance(null), entry.decidedAt), + ), ] const counts = { suggested: state.suggestions.length, - active: state.learnings.length, + active: state.learnings.length + (state.solo ? 0 : (state.shared?.length ?? 0)), rejected: state.rejected.length, } // Suggestions need a decision, so they lead until there are none. @@ -197,7 +243,30 @@ function detail( const path = `/repositories/${repositoryId}/learnings/${encodeURIComponent(record.id)}/decision` const canDecide = state.permissions.decide const suggestion = state.suggestions.find((item) => item.id === record.id) + const sessions = (suggestion ?? history)?.sessions + const sessionFacts = + sessions && state.solo + ? [ + ...(sessions.supporting + ? [`Found in ${count(sessions.supporting, "agent session")}`] + : []), + ...(sessions.opposing + ? [`Questioned in ${count(sessions.opposing, "agent session")}`] + : []), + ] + : [] const shared = { + source: record.source, + share: null, + updates: [], + updateNeedsMoreEvidence: false, + outcomes: null, + earlierGuidance: (history?.earlierGuidance ?? []).map((entry) => ({ + version: entry.version, + title: entry.title, + guidance: entry.content, + outcomes: outcomes(entry.outcomes, repositoryId), + })), id: record.id, status: record.status, title: record.title, @@ -213,17 +282,34 @@ function detail( reason: entry.reason, })), } + if (record.source) { + const received = state.shared?.find((item) => `shared:${item.source}:${item.id}` === record.id) + return { + ...shared, + facts: [ + ...(received + ? [ + `Shared${received.sharedBy ? ` by @${received.sharedBy}` : ""} on ${longDate(received.sharedAt)}`, + ] + : []), + "Agents in this repository don't get shared learnings yet.", + ], + decision: null, + } + } if (record.status === "suggested" && suggestion) { return { ...shared, - facts: suggestion.support - ? [ - `Raised by ${count(suggestion.support.reviewers, "reviewer")} on ${count( - suggestion.support.prototypes, - "prototype", - )}`, - ] - : [], + facts: state.solo + ? sessionFacts + : suggestion.support + ? [ + `Raised by ${count(suggestion.support.reviewers, "reviewer")} on ${count( + suggestion.support.prototypes, + "prototype", + )}`, + ] + : [], replaces: replacements(suggestion.replaces), decision: canDecide ? { path, digest: suggestion.reviewDigest, title: "", content: "" } @@ -232,17 +318,64 @@ function detail( } const accepted = state.learnings.find((item) => item.id === record.id) if (record.status === "active" && accepted) { + const receipt = history?.decisions.at(-1) + const verb = + receipt?.change === "edited" + ? "Edited" + : receipt?.change === "reinstated" + ? "Reinstated" + : "Accepted" return { ...shared, + outcomes: accepted.content !== null ? outcomes(history?.outcomes ?? [], repositoryId) : null, + updates: (accepted.content !== null ? (history?.updates ?? []) : []).map((update) => ({ + id: update.id, + issue: update.issue, + title: update.title, + content: update.content, + reasoning: update.reasoning, + // Both scores of one Build can support a suggestion, so each Build is linked once. + support: [ + ...new Map( + update.support.map((build) => { + const link = buildLink(build, repositoryId) + return [link.path, link] + }), + ).values(), + ], + })), + updateNeedsMoreEvidence: history?.updateNeedsMoreEvidence ?? false, + share: + !state.solo && + state.permissions.share && + (accepted.shared || + (accepted.shareable && + accepted.content !== null && + accepted.digest && + ["recalled", "budget-excluded"].includes(accepted.status))) + ? { + path: path.replace(/decision$/, "share"), + shared: accepted.shared ?? false, + digest: accepted.digest, + } + : null, facts: [ ...(accepted.acceptedBy && accepted.acceptedAt ? [ - `Accepted by @${accepted.acceptedBy} on ${longDate(accepted.acceptedAt)}${ - accepted.edited ? ", with edits" : "" + `${verb} by @${accepted.acceptedBy} on ${longDate(accepted.acceptedAt)}${ + verb === "Accepted" && accepted.edited ? ", with edits" : "" }`, ] : []), recallFact(accepted.status), + ...sessionFacts, + ...(accepted.shared + ? [ + accepted.shareable + ? "Shared across Hub" + : "Sharing is paused because this version is no longer eligible.", + ] + : []), ], decision: canDecide && accepted.digest && accepted.content !== null @@ -257,12 +390,24 @@ function detail( } const rejected = state.rejected.find((item) => item.id === record.id) const verb = rejected?.state === "retired" ? "Retired" : "Rejected" + const savedShare = !state.solo && rejected?.shared return { ...shared, - facts: - rejected?.decidedBy && rejected.decidedAt + share: + savedShare && state.permissions.share + ? { path: path.replace(/decision$/, "share"), shared: true } + : null, + facts: [ + ...(rejected?.decidedBy && rejected.decidedAt ? [`${verb} by @${rejected.decidedBy} on ${longDate(rejected.decidedAt)}`] - : [], + : []), + ...sessionFacts, + ...(savedShare + ? [ + "Other repositories cannot see this learning. A share from an earlier version is still saved.", + ] + : []), + ], reason: rejected?.reason ? { heading: `Why it was ${verb.toLowerCase()}`, text: rejected.reason } : null, diff --git a/hub/client/application/hub/view-models/prototype-show-data/index.test.ts b/hub/client/application/hub/view-models/prototype-show-data/index.test.ts index af14b80cc..caff703ef 100644 --- a/hub/client/application/hub/view-models/prototype-show-data/index.test.ts +++ b/hub/client/application/hub/view-models/prototype-show-data/index.test.ts @@ -143,3 +143,61 @@ it("plays a private Build inline only when it has no legacy review viewer", () = copyPrivatePreviewLinkLabel: "Copy private Hub link", }) }) + +it("lists the learnings agents applied in the selected Build", () => { + const repository = { id: "2001", nameWithOwner: "example/repository", defaultBranch: "main" } + const workspace: WorkspaceResponse = { + viewer: { id: "123", login: "octocat", name: null, provider: "github", avatarUrl: null }, + repositories: [repository], + } + const build = { + number: 3, + repositoryId: repository.id, + prototypeId: "1", + state: "successful", + commitSha: "a".repeat(40), + commitAuthorLogin: null, + createdAt: "2026-12-20T12:00:00Z", + startedAt: null, + finishedAt: null, + previewUrl: null, + desktopScreenshotUrl: null, + narrowScreenshotUrl: null, + failureSummary: null, + } + const response = prototypeResponseSchema.parse({ + repository, + prototype: { + id: "1", + repositoryId: repository.id, + name: "Prototype", + branchName: "prototype/welcome", + authorLogin: null, + canEdit: false, + description: null, + builds: [build], + }, + selectedBuild: build, + }) + const sha256 = "b".repeat(64) + + const result = prototypeShowData(workspace, response, new URLSearchParams("build=3"), [ + { id: "mem_1", title: "Label every field", version: 2, after: { sha256, route: "/" } }, + ]) + + expect(result.agentReportedUseLabel).toBe("Applied learnings") + expect(result.agentReportedUse).toMatchObject({ + buildNumber: 3, + learnings: [ + { + id: "mem_1", + label: "Label every field ยท v2", + afterScreenshot: { + url: `/api/repositories/2001/learnings/screenshots/${sha256}`, + label: "View after screenshot for Label every field", + }, + }, + ], + }) + expect(result.agentReportedUse?.learnings[0]?.beforeScreenshot).toBeUndefined() +}) diff --git a/hub/client/application/hub/view-models/prototype-show-data/index.ts b/hub/client/application/hub/view-models/prototype-show-data/index.ts index f95428bd8..30f4beb98 100644 --- a/hub/client/application/hub/view-models/prototype-show-data/index.ts +++ b/hub/client/application/hub/view-models/prototype-show-data/index.ts @@ -1,6 +1,7 @@ import type { PrototypesShowPageData } from "@pages/prototypes-show-page/types" import { reviewCommentsCopy } from "@utils/review-comment/en" import type { PrototypeResponse, WorkspaceResponse } from "@application/hub/contracts/types" +import type { AppliedLearningResponse } from "@application/hub/learnings-contracts/types" import { buildStateLabel } from "../build-state-label" import { productContinuation } from "../product-continuation" @@ -10,6 +11,7 @@ export function prototypeShowData( workspace: WorkspaceResponse, data: PrototypeResponse, search: URLSearchParams, + appliedLearnings: AppliedLearningResponse[] = [], ): PrototypesShowPageData { const selectedBuild = data.selectedBuild const previewBuild = @@ -117,6 +119,16 @@ export function prototypeShowData( selectedBuild && !previewBuild ? `Build ${selectedBuild.number} ยท ${buildStateLabel(selectedBuild.state)}` : "Choose build", + ...(selectedBuild?.state === "successful" && appliedLearnings.length > 0 + ? { + agentReportedUseLabel: "Applied learnings", + agentReportedUse: agentReportedUse( + data.repository.id, + selectedBuild.number, + appliedLearnings, + ), + } + : {}), selectedBuild: previewBuild?.previewUrl ? { number: previewBuild.number, @@ -126,3 +138,45 @@ export function prototypeShowData( : undefined, } } + +/** + * Shows what agents said they applied in a Build. Screenshots are served by Hub, which + * stops serving them once the repository withdraws screenshot consent. + */ +function agentReportedUse( + repositoryId: string, + buildNumber: number, + learnings: AppliedLearningResponse[], +): NonNullable { + function screenshot(name: string, kind: string, value?: { sha256: string }) { + return value + ? { + url: `/api/repositories/${repositoryId}/learnings/screenshots/${value.sha256}`, + label: `View ${kind} screenshot for ${name}`, + } + : undefined + } + return { + buildNumber, + copy: { + heading: `Applied learnings for Build ${buildNumber}`, + caption: "Reported by the agent; not independently verified.", + learningLabel: "Learning", + beforeLabel: "Before", + afterLabel: "After", + viewLabel: "View", + notAttachedLabel: "Not attached", + }, + learnings: learnings.map((learning) => { + const name = learning.title ?? "Untitled learning" + const beforeScreenshot = screenshot(name, "before", learning.before) + const afterScreenshot = screenshot(name, "after", learning.after) + return { + id: learning.id, + label: learning.version === null ? name : `${name} ยท v${learning.version}`, + ...(beforeScreenshot ? { beforeScreenshot } : {}), + ...(afterScreenshot ? { afterScreenshot } : {}), + } + }), + } +} diff --git a/hub/client/application/hub/view-models/repository-workspace/index.ts b/hub/client/application/hub/view-models/repository-workspace/index.ts index 19d2fe4da..c25b484ec 100644 --- a/hub/client/application/hub/view-models/repository-workspace/index.ts +++ b/hub/client/application/hub/view-models/repository-workspace/index.ts @@ -15,7 +15,7 @@ export function repositoryWorkspace(workspace: WorkspaceResponse, repository: Re analyticsLabel: "Analytics", analyticsPath: canManageAnalytics ? `/repositories/${repository.id}/analytics` : null, learningsLabel: "Learnings", - learningsPath: null, + learningsPath: `/repositories/${repository.id}/learnings`, newPrototypeLabel: "Create", newPrototypePath: browseTemplates ? `/repositories/${repository.id}/new` : null, prototypesLabel: "Prototypes", diff --git a/hub/client/application/hub/view-models/settings-learnings/index.test.ts b/hub/client/application/hub/view-models/settings-learnings/index.test.ts index 89e29cc41..86a7a4859 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.test.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.test.ts @@ -58,10 +58,25 @@ describe("settingsLearnings()", () => { automaticRunsEnabled: false, solo: false, localLearningSetupNeeded: false, - activity: [], + activity: [ + { date: "2026-11-09", runs: 2, commentsAnalyzed: 3, commentsTagged: 1, suggestions: 1 }, + { + date: "2026-11-10", + runs: 3, + commentsAnalyzed: 6, + commentsTagged: 2, + suggestions: 1, + lastRun: { + state: "failed", + startedAt: "2026-11-10T12:00:00Z", + startedBy: { type: "user", login: "mona" }, + }, + }, + ], today: "2026-11-10", usageCredits: "0", runAvailable: true, + firstRunNeeded: false, loadError: null, identityReviewCount: 0, suggestions: [], @@ -75,7 +90,20 @@ describe("settingsLearnings()", () => { expect(result.accessDenied).toBe(false) if (result.accessDenied) throw new Error("Expected repository learning access.") - expect(result.run).toEqual({ path: "/repositories/2001/learnings/runs" }) + expect(result.run?.path).toBe("/repositories/2001/learnings/runs") + expect(result.activity).toEqual([ + { ...state.activity[0], runState: "aggregate", startedAt: null, startedBy: null }, + { + date: "2026-11-10", + runs: 3, + commentsAnalyzed: 6, + commentsTagged: 2, + suggestions: 1, + runState: "failed", + startedAt: "2026-11-10T12:00:00Z", + startedBy: "@mona", + }, + ]) expect(result.administrationLinks).toEqual([]) }) @@ -117,17 +145,54 @@ describe("settingsLearnings()", () => { expect(result).not.toHaveProperty("run") }) - it("keeps an explicit run available when Hub has daily runs", () => { - const state = mockState(false) - + it("links a Hub administrator to Copilot setup without granting a repository run", () => { const result = settingsLearnings( + workspace, + { + ...emptyLearnings(true), + capabilities: { administerHub: true, administerRepository: false }, + permissions: { viewEvidence: true, decide: false, requestRun: false }, + copilot: { state: "not-connected" }, + runAvailable: false, + usageCredits: null, + }, + location, + null, + ) + + expect(result).toMatchObject({ copilotPath: "/settings/copilot", run: null }) + }) + + it("offers a run regardless of daily runs but asks for consent only when needed", () => { + const state = mockState(false) + const daily = { ...state.learnings, automaticRunsEnabled: true } + const withoutHistory = settingsLearnings(state.workspace, daily, location, null) + const needsConsent = settingsLearnings( state.workspace, - { ...state.learnings, automaticRunsEnabled: true }, + { + ...daily, + firstRunNeeded: true, + runs: [ + { + id: 1, + startedBy: { type: "daily" }, + startedAt: "2026-11-09T12:00:00Z", + state: "failed", + result: { type: "failed", summary: "Review consent is missing." }, + usage: null, + }, + ], + }, location, null, ) - if (result.accessDenied) throw new Error("Expected repository learning access.") - expect(result.run).toEqual({ path: "/repositories/2001/learnings/runs" }) + expect(withoutHistory).toMatchObject({ + run: { path: "/repositories/2001/learnings/runs" }, + firstRunNotice: null, + }) + if (needsConsent.accessDenied) throw new Error("Expected repository learning access.") + expect(needsConsent.run?.path).toBe("/repositories/2001/learnings/runs") + expect(needsConsent.firstRunNotice).toMatch(/allow Hub to learn from .*review comments/i) }) }) diff --git a/hub/client/application/hub/view-models/settings-learnings/index.ts b/hub/client/application/hub/view-models/settings-learnings/index.ts index a7060bd8c..a486f9c3a 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.ts @@ -48,64 +48,54 @@ export function settingsLearnings( : "" }, so Hub stopped looking for learnings until the token is replaced or checked again on the Copilot page. You can still decide on suggestions, and agents still get accepted learnings.` : null - const activity: LearningActivityDay[] = state.activity.map(({ startedBy, ...day }) => ({ - ...day, - startedBy: startedBy.type === "agent" ? "your agent" : null, - })) + const activity: LearningActivityDay[] = state.activity.map((day) => { + if (!("runs" in day)) return { ...day, startedBy: "your agent" } + const { lastRun, ...counts } = day + if (!lastRun) return { ...counts, runState: "aggregate", startedAt: null, startedBy: null } + return { + ...counts, + runState: lastRun.state, + startedAt: lastRun.startedAt, + startedBy: + lastRun.startedBy.type === "daily" + ? "the daily schedule" + : lastRun.startedBy.type === "user" + ? `@${lastRun.startedBy.login}` + : null, + } + }) return { ...shared, accessDenied: false, copilotWarning, + copilotPath: copilotWarning && state.capabilities.administerHub ? "/settings/copilot" : null, + firstRunNotice: + state.firstRunNeeded && state.permissions.requestRun && !state.solo + ? "Choose Find learnings now to allow Hub to learn from this repository's review comments. You can review what this enables before confirming." + : null, soloNotice: state.solo && !state.localLearningSetupNeeded - ? "These learnings come from Solo in this checkout. Solo looks for new ones after each agent session, and agents here get the ones you accept." + ? "This checkout uses local learning mode. Your agent looks for new learnings after each session, and agents here get the ones you accept." : null, localLearningSetupCommand: state.localLearningSetupNeeded ? "node /packages/learning/bin/replica-learning.mjs setup" : null, activity, today: state.today, - agentsPath: null, - evaluationsPath: null, + // Hub serves agents only for GitHub repositories, so local ones offer no setup. + agentsPath: workspace.repositories.find(({ id }) => id === repositoryId)?.capabilities?.local + ? null + : `/repositories/${repositoryId}/learnings/agents`, + settingsPath: + !state.solo && (state.capabilities.administerRepository || state.capabilities.administerHub) + ? `/repositories/${repositoryId}/learnings/settings` + : null, // Keep an explicit run available so repository admins can establish first-run consent. run: !state.solo && state.permissions.requestRun && state.runAvailable - ? { path: `/repositories/${repositoryId}/learnings/runs` } - : null, - runHistory: - !state.solo && state.capabilities.administerRepository && state.runs.length > 0 ? { - credits: state.usageCredits, - runs: state.runs.map((run) => ({ - id: run.id, - state: { - queued: "Queued", - running: "Running", - succeeded: "Finished", - failed: "Failed", - }[run.state], - started: [ - new Intl.DateTimeFormat("en-US", { dateStyle: "medium", timeZone: "UTC" }).format( - new Date(run.startedAt), - ), - run.startedBy.type === "user" - ? `@${run.startedBy.login}` - : run.startedBy.type === "daily" - ? "Daily run" - : null, - ] - .filter(Boolean) - .join(" ยท "), - result: - run.result?.type === "failed" - ? run.result.summary - : run.result - ? `Comments analyzed: ${run.result.commentsConsidered}. Labeled: ${run.result.commentsLabeled}. Suggestions: ${run.result.suggestions}.` - : null, - usage: run.usage - ? `${run.usage.credits} AI credits (${run.usage.requests} ${run.usage.requests === 1 ? "request" : "requests"})` - : null, - })), + path: `/repositories/${repositoryId}/learnings/runs`, + repositoryName: repository.nameWithOwner, } : null, loadError: state.loadError, diff --git a/hub/client/features/learning-activity-grid/index.test.tsx b/hub/client/features/learning-activity-grid/index.test.tsx index 6f6354ff7..ab6967fad 100644 --- a/hub/client/features/learning-activity-grid/index.test.tsx +++ b/hub/client/features/learning-activity-grid/index.test.tsx @@ -13,6 +13,7 @@ describe("LearningActivityGrid()", () => { activity={[ { date: "2026-11-18", + runs: 2, runState: "failed", startedAt: "2026-11-18T16:30:00Z", startedBy: "@mona", @@ -22,6 +23,7 @@ describe("LearningActivityGrid()", () => { }, { date: "2026-11-19", + runs: 1, runState: "succeeded", startedAt: "2026-11-19T16:30:00Z", startedBy: "the daily schedule", @@ -36,13 +38,15 @@ describe("LearningActivityGrid()", () => { const calendar = screen.getByRole("group", { name: "Daily learning activity for 2026" }) expect(within(calendar).getAllByRole("button")).toHaveLength(324) - expect(screen.getByText(/Run completed ยท Started by the daily schedule/)).toBeVisible() + expect( + screen.getByText(/1 learning run ยท Last run completed ยท Started by the daily schedule/), + ).toBeVisible() expect(screen.getByText("Suggestions", { selector: "dt" }).parentElement).toHaveTextContent("2") const latest = within(calendar).getByRole("button", { name: /^November 19, 2026,/ }) fireEvent.keyDown(latest, { key: "ArrowUp" }) expect(document.activeElement).toHaveAccessibleName(/^November 18, 2026,.*run failed$/) - expect(screen.getByText(/Run failed ยท Started by @mona/)).toBeVisible() + expect(screen.getByText(/2 learning runs ยท Last run failed ยท Started by @mona/)).toBeVisible() const today = within(calendar).getByRole("button", { name: /^November 20, 2026,/ }) fireEvent.click(today) diff --git a/hub/client/features/learning-activity-grid/index.tsx b/hub/client/features/learning-activity-grid/index.tsx index 27913a7d8..eab5f3522 100644 --- a/hub/client/features/learning-activity-grid/index.tsx +++ b/hub/client/features/learning-activity-grid/index.tsx @@ -31,6 +31,27 @@ function countLabel(value: number, singular: string) { type CalendarCell = { date: string; day: LearningActivityDay | null } +function runSummary(day: LearningActivityDay) { + if (day.runState === "none") return "No learning run" + if (day.runState === "aggregate") return countLabel(day.runs, "learning run") + const status = day.runState === "failed" ? "failed" : "completed" + const parts = [ + day.runs ? `${countLabel(day.runs, "learning run")} ยท Last run ${status}` : `Run ${status}`, + ] + if (day.startedBy) parts.push(`Started by ${day.startedBy}`) + if (day.startedAt) { + parts.push( + new Intl.DateTimeFormat("en-US", { + hour: "numeric", + minute: "2-digit", + timeZone: "UTC", + timeZoneName: "short", + }).format(new Date(day.startedAt)), + ) + } + return parts.join(" ยท ") +} + function quietDay(date: string): LearningActivityDay { return { date, @@ -212,11 +233,11 @@ function CalendarYear({ activity, today }: { activity: LearningActivityDay[]; to const value = day[metric] const level = value === 0 ? 0 : Math.min(4, Math.ceil((value / maximum) * 4)) const runLabel = - day.runState === "none" - ? "no run" - : day.runState === "failed" - ? "run failed" - : "run succeeded" + day.runState === "aggregate" + ? countLabel(day.runs, "run") + : day.runState === "none" + ? "no run" + : `${day.runs ? `${countLabel(day.runs, "run")}; last ` : ""}run ${day.runState}` const accessibleLabel = `${dayLabel(day.date)}, ${metricLabel}: ${value}; ${countLabel(day.commentsAnalyzed, "comment")} analyzed, ${countLabel(day.commentsTagged, "comment")} categorized, ${countLabel(day.suggestions, "suggestion")}, ${runLabel}` return ( + + + + ) : learning.status === "active" ? ( + <> + - - + + ) : ( + - - ) : learning.status === "active" ? ( - <> - + ) : ( + +
+ Share across Hub + shareForm.current?.requestSubmit()} + size="small" + /> + {/* The tooltip is visual, so screen readers get the hint here. */} + {shareHint} +
+
+ )} + + ) : null} + + + {learning.updates.map((update) => ( + +
+ + Issue: {update.issue} + +
+
+
Title
+
+ {diffText(learning.title, update.title ?? learning.title)} +
+
+
+
Guidance
+
+ + {diffText(learning.guidance, update.content)} + +
+
+
+
+
+ + Why: {update.reasoning} + + {update.support.length ? ( +
+ Seen in + {update.support.map((build) => ( + + {build.label} + + ))} +
+ ) : null} +
+ {decision ? ( +
+ - - - ) : ( - - )} +
+ ) : null} +
+ ))} + + {learning.reason ? ( +
+ + + {learning.reason.heading} + + {learning.reason.text}
) : null} - - - {learning.reason ? ( -
- - - {learning.reason.heading} - - {learning.reason.text} -
- ) : null} - {learning.replaces.length ? ( - -
    - {learning.replaces.map((target) => ( -
  • - - {target.content} - -
  • - ))} -
-
- ) : null} + {learning.replaces.length ? ( + +
    + {learning.replaces.map((target) => ( +
  • + + {target.content} + +
  • + ))} +
+
+ ) : null} - {learning.history.length ? ( - -
    - {learning.history.map((entry, index) => ( -
  • - - {entry.label} - {entry.by ? ` by @${entry.by}` : null} - {entry.at ? ( - <> - {" ยท "} - - - ) : null} - - {entry.reason ?

    {entry.reason}

    : null} -
  • - ))} -
-
- ) : null} + {learning.evidence.length || learning.otherEvidence ? ( + + + + ) : null} - {learning.evidence.length || learning.otherEvidence ? ( - - - - ) : null} + {learning.contradictions.length || learning.otherContradictions ? ( + + + + ) : null} - {learning.contradictions.length || learning.otherContradictions ? ( - - - - ) : null} + {learning.outcomes ? ( + + + {learning.updateNeedsMoreEvidence ? ( + + Not enough Builds show the same issue to suggest new wording yet. + + ) : null} + + ) : null} - {decision && dialog ? ( - setDialog(null)} - > -

- {dialog === "edit" - ? "This updates the stored guidance. The decision history keeps your reason." - : dialog === "reinstate" - ? "This moves the learning back to Active. The decision history keeps your reason." - : "Agents do not get rejected learnings. You can accept it later."} -

- - {dialog === "edit" ? ( - <> - - Title - - - - Guidance -