diff --git a/hub/client/application/hub/decision-model-contracts/index.test.ts b/hub/client/application/hub/decision-model-contracts/index.test.ts deleted file mode 100644 index 7ad1f6d77..000000000 --- a/hub/client/application/hub/decision-model-contracts/index.test.ts +++ /dev/null @@ -1,209 +0,0 @@ -import { describe, expect, it } from "vitest" - -import { - decisionModelConfigurationResponseSchema, - decisionModelOverviewResponseSchema, - decisionTrainingMutationResponseSchema, -} from "." - -const digest = `sha256:${"a".repeat(64)}` - -function overview() { - return { - preflight: { - state: "ready" as const, - counts: { - prototypes: 2, - builds: 5, - pages: 8, - screenshots: 32, - questions: 7, - samples: 43, - tasks: 43, - train: 27, - dev: 8, - test: 8, - follows: 24, - breaks: 19, - }, - warnings: [], - reasons: [], - digests: { - export: digest, - reviewSnapshot: digest, - buildSet: digest, - questionSet: digest, - taskset: digest, - }, - }, - configuration: { - enabled: true, - generation: 3, - backend: "customer-runtime", - maxUpdates: 8, - maxSeconds: 300, - monthlyBudgetCredits: "10.5", - }, - jobs: [ - { - id: "11111111-2222-4333-8444-555555555555", - state: "succeeded" as const, - tasksetDigest: digest, - runtimeJobId: "runtime-job-1", - candidateRuntimeId: "candidate-1", - failureCode: null, - createdAt: "2026-11-11T18:00:00Z", - finishedAt: "2026-11-11T18:04:30Z", - }, - ], - candidates: [ - { - id: "22222222-3333-4444-8555-666666666666", - runtimeCandidateId: "candidate-1", - backend: "fixture", - tasksetDigest: digest, - productionEligible: true, - baselineMeanReward: "0.61", - candidateMeanReward: "0.79", - meanRewardDelta: "0.18", - baselineCalibrationError: "0.2", - candidateCalibrationError: "0.17", - calibrationErrorDelta: "-0.03", - learningMetrics: [ - { - learningId: "learning-1", - baselineBalancedAccuracy: 0.5, - candidateBalancedAccuracy: 0.75, - delta: 0.25, - direction: "gain" as const, - }, - ], - durationSeconds: 270, - usage: [ - { - connector: "customer-gpu", - kind: "training_credits", - quantity: 3.5, - unit: "credits", - cost: 1.25, - currency: "USD", - source: "runtime", - metadata: {}, - }, - ], - rejection: null, - createdAt: "2026-11-11T18:04:30Z", - }, - ], - promotion: { - candidateId: "22222222-3333-4444-8555-666666666666", - runtimeCandidateId: "candidate-1", - generation: 2, - operation: "promote" as const, - rollbackAvailable: true, - }, - promotionHistory: [], - evaluationBuilds: [ - { - id: "33333333-4444-4555-8666-777777777777", - number: 42, - prototype: { - id: "1", - name: "Settings", - branchName: "settings", - }, - }, - ], - evaluations: [], - deletions: [], - } -} - -describe("Decision-model contracts", () => { - it("accepts only the persisted control-plane overview fields", () => { - const response = overview() - - expect(decisionModelOverviewResponseSchema.parse(response)).toEqual(response) - expect( - decisionModelOverviewResponseSchema.safeParse({ - ...response, - candidates: response.candidates.map((candidate) => ({ - ...candidate, - inventedProof: true, - })), - }).success, - ).toBe(false) - }) - - it("bounds the successful Builds offered for evaluation", () => { - const response = overview() - - expect(decisionModelOverviewResponseSchema.parse(response).evaluationBuilds).toEqual( - response.evaluationBuilds, - ) - expect( - decisionModelOverviewResponseSchema.safeParse({ - ...response, - evaluationBuilds: Array.from({ length: 51 }, (_, index) => ({ - id: `${String(index).padStart(8, "0")}-4444-4555-8666-777777777777`, - number: index + 1, - prototype: { - id: "1", - name: "Settings", - branchName: "settings", - }, - })), - }).success, - ).toBe(false) - }) - - it("keeps repository training settings within the supported bounds", () => { - const configuration = overview().configuration - - expect( - decisionModelConfigurationResponseSchema.parse({ - ...configuration, - maxUpdates: 1, - maxSeconds: 1, - monthlyBudgetCredits: "0", - }), - ).toMatchObject({ maxUpdates: 1, maxSeconds: 1, monthlyBudgetCredits: "0" }) - expect( - decisionModelConfigurationResponseSchema.parse({ - ...configuration, - maxUpdates: 100_000, - maxSeconds: 86_400, - monthlyBudgetCredits: "999.123456789", - }), - ).toMatchObject({ - maxUpdates: 100_000, - maxSeconds: 86_400, - monthlyBudgetCredits: "999.123456789", - }) - - for (const invalid of [ - { ...configuration, maxUpdates: 0 }, - { ...configuration, maxUpdates: 100_001 }, - { ...configuration, maxSeconds: 0 }, - { ...configuration, maxSeconds: 86_401 }, - { ...configuration, monthlyBudgetCredits: "-1" }, - { ...configuration, monthlyBudgetCredits: "1.1234567890" }, - { ...configuration, backend: "Fixture Backend" }, - ]) { - expect(decisionModelConfigurationResponseSchema.safeParse(invalid).success).toBe(false) - } - }) - - it("normalizes the server-shaped uppercase cancellation state", () => { - expect( - decisionTrainingMutationResponseSchema.parse({ - id: "11111111-2222-4333-8444-555555555555", - state: "CANCELLED", - repositoryId: "repository-1", - }), - ).toMatchObject({ - id: "11111111-2222-4333-8444-555555555555", - state: "cancelled", - }) - }) -}) diff --git a/hub/client/application/hub/decision-model-contracts/index.ts b/hub/client/application/hub/decision-model-contracts/index.ts deleted file mode 100644 index 2ce2f997b..000000000 --- a/hub/client/application/hub/decision-model-contracts/index.ts +++ /dev/null @@ -1,292 +0,0 @@ -import { z } from "zod" - -import { recordIdentifierSchema } from "@application/hub/contracts" -import type { - DecisionCandidateRejectionMutationResponse, - DecisionCandidateResponse, - DecisionModelConfigurationResponse, - DecisionModelOverviewResponse, - DecisionPromotionMutationResponse, - DecisionPromotionResponse, - DecisionTrainingJobResponse, - DecisionTrainingMutationResponse, - DecisionTrainingRequestResponse, -} from "./types" - -const identifier = z.uuid() -const count = z.number().int().nonnegative() -const credits = z.string().regex(/^(?:0|[1-9]\d*)(?:\.\d{1,9})?$/) -const signedDecimal = z.string().regex(/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/) -const digest = z.string().regex(/^sha256:[0-9a-f]{64}$/) -const timestamp = z.iso.datetime({ offset: true }) -const trainingState = z.enum([ - "queued", - "submitting", - "cancel_requested", - "submitted", - "running", - "succeeded", - "failed", - "cancelled", -]) - -export const decisionModelConfigurationResponseSchema = z - .object({ - enabled: z.boolean(), - generation: count, - backend: z.string().regex(/^[a-z][a-z0-9-]{0,99}$/), - maxUpdates: z.number().int().min(1).max(100_000), - maxSeconds: z.number().int().min(1).max(86_400), - monthlyBudgetCredits: credits, - }) - .strict() satisfies z.ZodType - -export const decisionTrainingJobResponseSchema = z - .object({ - id: identifier, - state: trainingState, - tasksetDigest: digest, - runtimeJobId: z.string().min(1).nullable(), - candidateRuntimeId: z.string().min(1).nullable(), - failureCode: z.string().min(1).nullable(), - createdAt: timestamp, - finishedAt: timestamp.nullable(), - }) - .strict() satisfies z.ZodType - -const decisionCandidateResponseSchema = z - .object({ - id: identifier, - runtimeCandidateId: z.string().min(1), - backend: z.string().regex(/^[a-z][a-z0-9-]{0,99}$/), - tasksetDigest: digest, - productionEligible: z.boolean(), - baselineMeanReward: signedDecimal.nullable(), - candidateMeanReward: signedDecimal.nullable(), - meanRewardDelta: signedDecimal.nullable(), - baselineCalibrationError: signedDecimal.nullable(), - candidateCalibrationError: signedDecimal.nullable(), - calibrationErrorDelta: signedDecimal.nullable(), - learningMetrics: z.array( - z - .object({ - learningId: z.string().min(1), - baselineBalancedAccuracy: z.number().nullable(), - candidateBalancedAccuracy: z.number().nullable(), - delta: z.number().nullable(), - direction: z.enum(["gain", "regression", "unchanged", "unknown"]), - }) - .strict(), - ), - durationSeconds: z.number().nonnegative().nullable(), - usage: z.array( - z - .object({ - connector: z.string().min(1), - kind: z.string().min(1), - quantity: z.number().nonnegative(), - unit: z.string().min(1), - cost: z.number().nonnegative().nullable(), - currency: z.string().min(1).nullable(), - source: z.string().min(1), - metadata: z.record(z.string(), z.unknown()), - }) - .strict(), - ), - rejection: z - .object({ - rejectedAt: timestamp, - reason: z.string().nullable(), - membershipId: identifier.nullable(), - }) - .strict() - .nullable(), - createdAt: timestamp, - }) - .strict() satisfies z.ZodType - -const decisionPromotionResponseSchema = z - .object({ - candidateId: identifier, - runtimeCandidateId: z.string().min(1), - generation: count, - operation: z.enum(["promote", "rollback"]), - rollbackAvailable: z.boolean(), - }) - .strict() satisfies z.ZodType - -export const decisionModelOverviewResponseSchema = z - .object({ - preflight: z - .object({ - state: z.enum(["ready", "blocked"]), - counts: z - .object({ - prototypes: count, - builds: count, - pages: count, - screenshots: count, - questions: count, - samples: count, - tasks: count, - train: count, - dev: count, - test: count, - follows: count, - breaks: count, - }) - .strict(), - warnings: z.array( - z - .object({ - code: z.string().min(1), - message: z.string().min(1), - count: count.optional(), - }) - .strict(), - ), - reasons: z.array(z.object({ code: z.string().min(1), count }).strict()), - digests: z - .object({ - export: digest.nullable(), - reviewSnapshot: digest, - buildSet: digest, - questionSet: digest.nullable(), - taskset: digest.nullable(), - }) - .strict(), - }) - .strict(), - configuration: decisionModelConfigurationResponseSchema.nullable(), - jobs: z.array(decisionTrainingJobResponseSchema).max(20), - candidates: z.array(decisionCandidateResponseSchema).max(20), - promotion: decisionPromotionResponseSchema.nullable(), - promotionHistory: z.array( - z - .object({ - candidateId: identifier, - runtimeCandidateId: z.string().min(1), - previousCandidateId: identifier.nullable(), - previousRuntimeCandidateId: z.string().min(1).nullable(), - generation: count, - operation: z.enum(["promote", "rollback"]), - membershipId: identifier.nullable(), - createdAt: timestamp, - }) - .strict(), - ), - evaluationBuilds: z - .array( - z - .object({ - id: identifier, - number: z.number().int().positive(), - prototype: z - .object({ - id: recordIdentifierSchema, - name: z.string().nullable(), - branchName: z.string().min(1), - }) - .strict(), - }) - .strict(), - ) - .max(50), - evaluations: z.array( - z - .object({ - id: identifier, - build: z - .object({ - id: identifier, - number: z.number().int().positive(), - prototypeId: recordIdentifierSchema, - }) - .strict(), - model: z - .object({ - id: identifier, - runtimeCandidateId: z.string().min(1), - generation: count, - }) - .strict(), - questionDigest: digest, - screenshotSetDigest: digest, - responseDigest: digest, - findingsAvailable: z.boolean(), - findings: z.array( - z - .object({ - learning: z.object({ id: z.string().min(1), text: z.string().nullable() }).strict(), - route: z.string().min(1), - views: z.array( - z.object({ viewport: z.string().min(1), theme: z.string().min(1) }).strict(), - ), - followsProbability: z.number().min(0).max(1), - breaksProbability: z.number().min(0).max(1), - explanation: z.string().min(1), - }) - .strict(), - ), - createdAt: timestamp, - }) - .strict(), - ), - deletions: z.array( - z - .object({ - id: identifier, - state: z.enum(["pending", "completed", "failed"]), - selectors: z - .object({ - exportId: z.string().nullable(), - grantId: z.string().nullable(), - evidenceDigest: digest.nullable(), - tasksetDigest: digest.nullable(), - }) - .strict(), - pending: count, - failures: count, - revokedAt: timestamp.nullable(), - completedAt: timestamp.nullable(), - failureCode: z.string().nullable(), - }) - .strict(), - ), - }) - .strict() satisfies z.ZodType - -export const decisionTrainingRequestResponseSchema = z - .object({ - created: z.boolean(), - job: decisionTrainingJobResponseSchema, - }) - .strict() satisfies z.ZodType - -export const decisionTrainingMutationResponseSchema = z.preprocess( - (input) => { - if (!input || typeof input !== "object") return input - const record = input as Record - return { - ...record, - state: typeof record.state === "string" ? record.state.toLowerCase() : record.state, - } - }, - z.object({ id: identifier, state: trainingState }).loose(), -) satisfies z.ZodType - -export const decisionBuildEvaluationMutationResponseSchema = z.object({ id: identifier }).loose() - -export const decisionPromotionMutationResponseSchema = z - .object({ - candidateId: identifier, - runtimeCandidateId: z.string().min(1), - previousCandidateId: identifier.nullable(), - previousRuntimeCandidateId: z.string().min(1).nullable(), - generation: count, - }) - .strict() satisfies z.ZodType - -export const decisionCandidateRejectionMutationResponseSchema = z - .object({ candidateId: identifier, rejectedAt: timestamp }) - .loose() satisfies z.ZodType diff --git a/hub/client/application/hub/decision-model-contracts/types.ts b/hub/client/application/hub/decision-model-contracts/types.ts deleted file mode 100644 index 17f5c27f7..000000000 --- a/hub/client/application/hub/decision-model-contracts/types.ts +++ /dev/null @@ -1,186 +0,0 @@ -export interface DecisionModelConfigurationResponse { - enabled: boolean - generation: number - backend: string - maxUpdates: number - maxSeconds: number - monthlyBudgetCredits: string -} - -export interface DecisionTrainingJobResponse { - id: string - state: - | "queued" - | "submitting" - | "cancel_requested" - | "submitted" - | "running" - | "succeeded" - | "failed" - | "cancelled" - tasksetDigest: string - runtimeJobId: string | null - candidateRuntimeId: string | null - failureCode: string | null - createdAt: string - finishedAt: string | null -} - -export interface DecisionCandidateResponse { - id: string - runtimeCandidateId: string - backend: string - tasksetDigest: string - productionEligible: boolean - baselineMeanReward: string | null - candidateMeanReward: string | null - meanRewardDelta: string | null - baselineCalibrationError: string | null - candidateCalibrationError: string | null - calibrationErrorDelta: string | null - learningMetrics: Array<{ - learningId: string - baselineBalancedAccuracy: number | null - candidateBalancedAccuracy: number | null - delta: number | null - direction: "gain" | "regression" | "unchanged" | "unknown" - }> - durationSeconds: number | null - usage: Array<{ - connector: string - kind: string - quantity: number - unit: string - cost: number | null - currency: string | null - source: string - metadata: Record - }> - rejection: { - rejectedAt: string - reason: string | null - membershipId: string | null - } | null - createdAt: string -} - -export interface DecisionPromotionResponse { - candidateId: string - runtimeCandidateId: string - generation: number - operation: "promote" | "rollback" - rollbackAvailable: boolean -} - -export interface DecisionModelOverviewResponse { - preflight: { - state: "ready" | "blocked" - counts: { - prototypes: number - builds: number - pages: number - screenshots: number - questions: number - samples: number - tasks: number - train: number - dev: number - test: number - follows: number - breaks: number - } - warnings: Array<{ code: string; message: string; count?: number }> - reasons: Array<{ code: string; count: number }> - digests: { - export: string | null - reviewSnapshot: string - buildSet: string - questionSet: string | null - taskset: string | null - } - } - configuration: DecisionModelConfigurationResponse | null - jobs: DecisionTrainingJobResponse[] - candidates: DecisionCandidateResponse[] - promotion: DecisionPromotionResponse | null - promotionHistory: Array<{ - candidateId: string - runtimeCandidateId: string - previousCandidateId: string | null - previousRuntimeCandidateId: string | null - generation: number - operation: "promote" | "rollback" - membershipId: string | null - createdAt: string - }> - evaluationBuilds: Array<{ - id: string - number: number - prototype: { id: string; name: string | null; branchName: string } - }> - evaluations: Array<{ - id: string - build: { id: string; number: number; prototypeId: string } - model: { id: string; runtimeCandidateId: string; generation: number } - questionDigest: string - screenshotSetDigest: string - responseDigest: string - findingsAvailable: boolean - findings: Array<{ - learning: { id: string; text: string | null } - route: string - views: Array<{ viewport: string; theme: string }> - followsProbability: number - breaksProbability: number - explanation: string - }> - createdAt: string - }> - deletions: Array<{ - id: string - state: "pending" | "completed" | "failed" - selectors: { - exportId: string | null - grantId: string | null - evidenceDigest: string | null - tasksetDigest: string | null - } - pending: number - failures: number - revokedAt: string | null - completedAt: string | null - failureCode: string | null - }> -} - -export type DecisionModelAvailability = - | { - state: "available" - overview: DecisionModelOverviewResponse - preparationStatus?: string - } - | { state: "not-configured" } - | { state: "unavailable"; error: string } - -export interface DecisionTrainingRequestResponse { - created: boolean - job: DecisionTrainingJobResponse -} - -export interface DecisionTrainingMutationResponse { - id: string - state: DecisionTrainingJobResponse["state"] -} - -export interface DecisionPromotionMutationResponse { - candidateId: string - runtimeCandidateId: string - previousCandidateId: string | null - previousRuntimeCandidateId: string | null - generation: number -} - -export interface DecisionCandidateRejectionMutationResponse { - candidateId: string - rejectedAt: string -} diff --git a/hub/client/application/hub/learnings-contracts/index.test.ts b/hub/client/application/hub/learnings-contracts/index.test.ts index 8464fd4cd..f75c0de30 100644 --- a/hub/client/application/hub/learnings-contracts/index.test.ts +++ b/hub/client/application/hub/learnings-contracts/index.test.ts @@ -16,7 +16,7 @@ const evidence = { } describe("Learnings contracts", () => { - it("accepts the complete repository-administrator review and run history response", () => { + it("accepts Hub responses and Solo activity summaries", () => { const response = { accessDenied: false as const, repository: { @@ -28,6 +28,10 @@ describe("Learnings contracts", () => { permissions: { viewEvidence: true, decide: true, requestRun: true }, copilot: { state: "connected" as const, connectedBy: "hub-admin" }, automaticRunsEnabled: false, + solo: false, + localLearningSetupNeeded: false, + activity: [], + today: "2026-11-10", usageCredits: "0.0735", runAvailable: true, loadError: null, @@ -35,7 +39,8 @@ describe("Learnings contracts", () => { suggestions: [ { id: "mem_suggestion", - content: "Show a visible label above every form field.", + title: "Visible field labels", + content: "a".repeat(3999) + "๐Ÿ™‚", reviewDigest: digest, support: { reviewers: 2, prototypes: 2 }, replaces: [ @@ -51,7 +56,9 @@ describe("Learnings contracts", () => { learnings: [ { id: "mem_accepted", + title: "One primary button", content: "Use one primary button per form.", + digest, acceptedBy: "octocat", acceptedAt: "2026-11-08T20:00:00.000Z", edited: true, @@ -59,13 +66,28 @@ describe("Learnings contracts", () => { }, { id: "mem_damaged", + title: null, content: null, + digest: null, acceptedBy: null, acceptedAt: null, edited: false, status: "damaged" as const, }, ], + rejected: [ + { + id: "mem_rejected", + title: "Hide optional labels", + content: "Hide labels on optional fields.", + digest, + state: "rejected" as const, + replaces: [], + decidedBy: "octocat", + decidedAt: "2026-11-08T20:00:00.000Z", + reason: "Labels help everyone.", + }, + ], recall: { text: "Approved team learnings\n1. Use one primary button per form.", count: 1, @@ -98,6 +120,28 @@ describe("Learnings contracts", () => { } expect(learningsResponseSchema.parse(response)).toEqual(response) + + const soloActivity = { + ...response, + solo: true, + permissions: { ...response.permissions, requestRun: false }, + usageCredits: null, + runAvailable: false, + runs: [], + activity: [ + { + date: "2026-11-10", + runState: "succeeded", + startedAt: "2026-11-10T12:00:00.000Z", + startedBy: { type: "agent" }, + commentsAnalyzed: 4, + commentsTagged: 2, + suggestions: 1, + }, + ], + } + + expect(learningsResponseSchema.parse(soloActivity)).toEqual(soloActivity) }) it.each([false, true])( @@ -133,7 +177,7 @@ describe("Learnings contracts", () => { it.each([ ["accept", { decision: "accept", digest }], - ["edited acceptance", { decision: "accept", digest, content: "Label every field." }], + ["edited acceptance", { decision: "accept", digest, content: "a".repeat(3999) + "๐Ÿ™‚" }], ["reject", { decision: "reject", digest, reason: "The design system already covers this." }], ["retire", { decision: "retire", reason: "This guidance no longer applies." }], ])("accepts the exact %s decision input", (_label, input) => { @@ -146,6 +190,10 @@ describe("Learnings contracts", () => { ["reject without a reason", { decision: "reject", digest }], ["retire with a digest", { decision: "retire", digest, reason: "No longer applies." }], ["a malformed digest", { decision: "accept", digest: "sha256:not-a-digest" }], + [ + "guidance longer than Solo allows", + { decision: "edit", digest, content: "a".repeat(4001), reason: "Clarify the rule." }, + ], ])("rejects %s", (_label, input) => { expect(learningDecisionInputSchema.safeParse(input).success).toBe(false) }) @@ -166,6 +214,10 @@ describe("Learnings contracts", () => { permissions: { viewEvidence: true, decide: true, requestRun: true }, copilot: { state: "not-connected" as const }, automaticRunsEnabled: false, + solo: false, + localLearningSetupNeeded: false, + activity: [], + today: "2026-11-10", usageCredits: "0", runAvailable: false, loadError: null, @@ -173,6 +225,7 @@ describe("Learnings contracts", () => { suggestions: [ { id, + title: null, content: "Use visible labels.", reviewDigest: digest, support: null, @@ -184,6 +237,7 @@ describe("Learnings contracts", () => { }, ], learnings: [], + rejected: [], recall: { text: "", count: 0 }, runs: [], } diff --git a/hub/client/application/hub/learnings-contracts/index.ts b/hub/client/application/hub/learnings-contracts/index.ts index c20db43e2..1759e2be1 100644 --- a/hub/client/application/hub/learnings-contracts/index.ts +++ b/hub/client/application/hub/learnings-contracts/index.ts @@ -1,15 +1,21 @@ import { z } from "zod" import { recordIdentifierSchema, repositorySchema } from "@application/hub/contracts" +import { + fitsLearningGuidanceLimit, + guidanceLimitMessage, +} from "@utils/fits-learning-guidance-limit" import type { AcceptedLearningResponse, LearningDecisionInput, LearningEvidenceResponse, + LearningHistoryResponse, LearningMutationResponse, LearningRunResponse, LearningSuggestionResponse, LearningsResponse, + RejectedLearningResponse, } from "./types" const identifier = z.number().int().positive() @@ -35,15 +41,20 @@ export const learningEvidenceResponseSchema = z }) .strict() satisfies z.ZodType +const title = z.string().trim().min(1).max(120) +const guidance = z.string().trim().min(1).refine(fitsLearningGuidanceLimit, guidanceLimitMessage) +const replaces = z.array( + z.object({ id: learningIdentifier, content: z.string().nullable() }).strict(), +) + export const learningSuggestionResponseSchema = z .object({ id: learningIdentifier, - content: z.string().trim().min(1).max(2000), + title: title.nullable(), + content: guidance, reviewDigest: digest, support: z.object({ reviewers: count, prototypes: count }).strict().nullable(), - replaces: z.array( - z.object({ id: learningIdentifier, content: z.string().nullable() }).strict(), - ), + replaces, evidence: z.array(learningEvidenceResponseSchema), otherEvidenceCount: count, contradictions: z.array(learningEvidenceResponseSchema), @@ -54,7 +65,9 @@ export const learningSuggestionResponseSchema = z export const acceptedLearningResponseSchema = z .object({ id: learningIdentifier, + title: title.nullable(), content: z.string().nullable(), + digest: digest.nullable(), acceptedBy: z.string().nullable(), acceptedAt: timestamp.nullable(), edited: z.boolean(), @@ -62,6 +75,41 @@ export const acceptedLearningResponseSchema = z }) .strict() satisfies z.ZodType +export const rejectedLearningResponseSchema = z + .object({ + id: learningIdentifier, + title: title.nullable(), + content: z.string().nullable(), + digest: digest.nullable(), + state: z.enum(["rejected", "retired"]), + replaces, + decidedBy: z.string().nullable(), + decidedAt: timestamp.nullable(), + reason: z.string().nullable(), + }) + .strict() satisfies z.ZodType + +export const learningHistoryResponseSchema = z + .object({ + decisions: z.array( + z + .object({ + version: identifier, + state: z.enum(["proposed", "accepted", "rejected", "retired"]), + change: z.enum(["proposed", "accepted", "edited", "reinstated", "rejected", "retired"]), + by: z.string().nullable(), + at: timestamp.nullable(), + reason: z.string().nullable(), + }) + .strict(), + ), + evidence: z.array(learningEvidenceResponseSchema), + otherEvidenceCount: count, + contradictions: z.array(learningEvidenceResponseSchema), + otherContradictionsCount: count, + }) + .strict() satisfies z.ZodType + const learningRunResultSchema = z.discriminatedUnion("type", [ z .object({ @@ -91,6 +139,18 @@ export const learningRunResponseSchema = z }) .strict() satisfies z.ZodType +const learningActivityDayResponseSchema = z + .object({ + date: z.iso.date(), + runState: z.enum(["succeeded", "failed"]), + startedAt: timestamp, + startedBy: z.object({ type: z.literal("agent") }).strict(), + commentsAnalyzed: count, + commentsTagged: count, + suggestions: count, + }) + .strict() + export const learningsResponseSchema = z.discriminatedUnion("accessDenied", [ z .object({ @@ -111,7 +171,7 @@ export const learningsResponseSchema = z.discriminatedUnion("accessDenied", [ capabilities: z .object({ administerHub: z.boolean(), - administerRepository: z.literal(true), + administerRepository: z.boolean(), }) .strict(), permissions: z @@ -137,12 +197,17 @@ export const learningsResponseSchema = z.discriminatedUnion("accessDenied", [ .strict(), ]), automaticRunsEnabled: z.boolean(), - usageCredits: credits, + solo: z.boolean(), + localLearningSetupNeeded: z.boolean(), + activity: z.array(learningActivityDayResponseSchema).max(366), + today: z.iso.date(), + usageCredits: credits.nullable(), runAvailable: z.boolean(), loadError: z.string().min(1).nullable(), identityReviewCount: count, suggestions: z.array(learningSuggestionResponseSchema), learnings: z.array(acceptedLearningResponseSchema), + rejected: z.array(rejectedLearningResponseSchema), recall: z.object({ text: z.string(), count }).strict(), runs: z.array(learningRunResponseSchema).max(10), }) @@ -154,7 +219,7 @@ export const learningDecisionInputSchema = z.discriminatedUnion("decision", [ .object({ decision: z.literal("accept"), digest, - content: z.string().trim().min(1).max(2000).optional(), + content: guidance.optional(), }) .strict(), z @@ -170,6 +235,22 @@ export const learningDecisionInputSchema = z.discriminatedUnion("decision", [ reason: z.string().trim().min(1).max(500), }) .strict(), + z + .object({ + decision: z.literal("edit"), + digest, + title: title.optional(), + content: guidance.optional(), + reason: z.string().trim().min(1).max(500), + }) + .strict(), + z + .object({ + decision: z.literal("reinstate"), + digest, + reason: z.string().trim().min(1).max(500), + }) + .strict(), ]) satisfies z.ZodType export const learningMutationResponseSchema = z diff --git a/hub/client/application/hub/learnings-contracts/types.ts b/hub/client/application/hub/learnings-contracts/types.ts index bb79cf7ca..c0e88435e 100644 --- a/hub/client/application/hub/learnings-contracts/types.ts +++ b/hub/client/application/hub/learnings-contracts/types.ts @@ -13,6 +13,7 @@ export interface LearningEvidenceResponse { export interface LearningSuggestionResponse { id: string + title: string | null content: string reviewDigest: string support: { reviewers: number; prototypes: number } | null @@ -25,13 +26,42 @@ export interface LearningSuggestionResponse { export interface AcceptedLearningResponse { id: string + title: string | null content: string | null + digest: string | null acceptedBy: string | null acceptedAt: string | null edited: boolean status: "recalled" | "not-recalled" | "budget-excluded" | "damaged" | "identity-review" } +export interface RejectedLearningResponse { + id: string + title: string | null + content: string | null + digest: string | null + state: "rejected" | "retired" + replaces: Array<{ id: string; content: string | null }> + decidedBy: string | null + decidedAt: string | null + reason: string | null +} + +export interface LearningHistoryResponse { + decisions: Array<{ + version: number + state: "proposed" | "accepted" | "rejected" | "retired" + change: "proposed" | "accepted" | "edited" | "reinstated" | "rejected" | "retired" + by: string | null + at: string | null + reason: string | null + }> + evidence: LearningEvidenceResponse[] + otherEvidenceCount: number + contradictions: LearningEvidenceResponse[] + otherContradictionsCount: number +} + export interface LearningRunResponse { id: number startedAt: string @@ -51,6 +81,16 @@ export interface LearningRunResponse { usage: { credits: string; requests: number } | null } +export interface LearningActivityDayResponse { + date: string + runState: "succeeded" | "failed" + startedAt: string + startedBy: { type: "agent" } + commentsAnalyzed: number + commentsTagged: number + suggestions: number +} + export type LearningsResponse = | { accessDenied: true @@ -60,19 +100,24 @@ export type LearningsResponse = | { accessDenied: false repository: RepositoryRecord - capabilities: { administerHub: boolean; administerRepository: true } + capabilities: { administerHub: boolean; administerRepository: boolean } permissions: { viewEvidence: boolean; decide: boolean; requestRun: boolean } copilot: | { state: "connected"; connectedBy: string | null } | { state: "not-connected" } | { state: "refused"; refusedAt: string | null } automaticRunsEnabled: boolean - usageCredits: string + solo: boolean + localLearningSetupNeeded: boolean + activity: LearningActivityDayResponse[] + today: string + usageCredits: string | null runAvailable: boolean loadError: string | null identityReviewCount: number suggestions: LearningSuggestionResponse[] learnings: AcceptedLearningResponse[] + rejected: RejectedLearningResponse[] recall: { text: string; count: number } runs: LearningRunResponse[] } @@ -81,6 +126,8 @@ export type LearningDecisionInput = | { decision: "accept"; digest: string; content?: string } | { decision: "reject"; digest: string; reason: string } | { decision: "retire"; reason: string } + | { decision: "edit"; digest: string; title?: string; content?: string; reason: string } + | { decision: "reinstate"; digest: string; reason: string } export interface LearningMutationResponse { notice: string 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 d36604f1f..9c8ace521 100644 --- a/hub/client/application/hub/routes/fixtures/empty-learnings/index.ts +++ b/hub/client/application/hub/routes/fixtures/empty-learnings/index.ts @@ -10,12 +10,17 @@ export function emptyLearnings( permissions: { viewEvidence: true, decide: true, requestRun: true }, copilot: { state: "connected", connectedBy: "octocat" }, automaticRunsEnabled: false, + solo: false, + localLearningSetupNeeded: false, + activity: [], + today: new Date().toISOString().slice(0, 10), usageCredits: "0", runAvailable: true, loadError: null, identityReviewCount: 0, suggestions: [], learnings: [], + rejected: [], recall: { text: "", count: 0 }, runs: [], } diff --git a/hub/client/application/hub/routes/learnings-flow.test.tsx b/hub/client/application/hub/routes/learnings-flow.test.tsx index 663499f0a..5e59422e4 100644 --- a/hub/client/application/hub/routes/learnings-flow.test.tsx +++ b/hub/client/application/hub/routes/learnings-flow.test.tsx @@ -1,5 +1,5 @@ -import { fireEvent, screen, waitFor, within } from "@testing-library/react" -import { describe, expect, it, onTestFinished, vi } from "vitest" +import { fireEvent, screen, within } from "@testing-library/react" +import { describe, expect, it, vi } from "vitest" import { http, stubHubFetch } from "@/test/stub-hub-fetch" @@ -30,6 +30,10 @@ function learningsResponse() { permissions: { viewEvidence: true, decide: true, requestRun: true }, copilot: { state: "connected" as const, connectedBy: "hub-admin" }, automaticRunsEnabled: false, + solo: false, + localLearningSetupNeeded: false, + activity: [], + today: "2026-11-10", usageCredits: "0.0945", runAvailable: true, loadError: null, @@ -37,6 +41,7 @@ function learningsResponse() { suggestions: [ { id: "mem_suggestion", + title: null, content: "Show a visible label above every form field.", reviewDigest: digest, support: { reviewers: 2, prototypes: 2 }, @@ -75,7 +80,9 @@ function learningsResponse() { learnings: [ { id: "mem_accepted", + title: null, content: "Use one primary button per form.", + digest, acceptedBy: "octocat", acceptedAt: "2026-11-08T20:00:00.000Z", edited: true, @@ -83,13 +90,16 @@ function learningsResponse() { }, { id: "mem_damaged", + title: null, content: null, + digest: null, acceptedBy: null, acceptedAt: null, edited: false, status: "damaged" as const, }, ], + rejected: [], recall: { text: "Approved team learnings\n1. Use one primary button per form.", count: 1, @@ -122,130 +132,28 @@ function learningsResponse() { } } -function decisionModelOverview(evaluated: boolean) { - const build = { - id: "77777777-8888-4999-8aaa-bbbbbbbbbbbb", - number: 42, - prototypeId: "1", - } - return { - preflight: { - state: "ready" as const, - counts: { - prototypes: 1, - builds: 1, - pages: 1, - screenshots: 4, - questions: 1, - samples: 3, - tasks: 3, - train: 1, - dev: 1, - test: 1, - follows: 2, - breaks: 1, - }, - warnings: [], - reasons: [], - digests: { - export: digest, - reviewSnapshot: digest, - buildSet: digest, - questionSet: digest, - taskset: digest, - }, - }, - configuration: { - enabled: true, - generation: 3, - backend: "fixture", - maxUpdates: 8, - maxSeconds: 300, - monthlyBudgetCredits: "10", - }, - jobs: [], - candidates: [], - promotion: { - candidateId: "33333333-4444-4555-8666-777777777777", - runtimeCandidateId: "fixture-candidate-1", - generation: 2, - operation: "promote" as const, - rollbackAvailable: false, - }, - promotionHistory: [], - evaluationBuilds: evaluated - ? [] - : [ - { - id: build.id, - number: build.number, - prototype: { - id: build.prototypeId, - name: "Settings", - branchName: "settings", - }, - }, - ], - evaluations: evaluated - ? [ - { - id: "44444444-5555-4666-8777-888888888888", - build, - model: { - id: "33333333-4444-4555-8666-777777777777", - runtimeCandidateId: "fixture-candidate-1", - generation: 2, - }, - questionDigest: digest, - screenshotSetDigest: digest, - responseDigest: digest, - findingsAvailable: true, - findings: [ - { - learning: { - id: "learning-1", - text: "Use a visible label above every form field.", - }, - route: "/settings/profile", - views: [{ viewport: "desktop", theme: "dark" }], - followsProbability: 0.82, - breaksProbability: 0.18, - explanation: - "The promoted model found the Build more likely to follow the learning.", - }, - ], - createdAt: "2026-11-20T15:00:00Z", - }, - ] - : [], - deletions: [], - } -} - -function deferred() { - let release!: () => void - const promise = new Promise((resolve) => { - release = resolve - }) - return { promise, release } +function emptyHistory() { + return http.get("/api/repositories/2001/learnings/:learningId/history", () => + Response.json({ + decisions: [], + evidence: [], + otherEvidenceCount: 0, + contradictions: [], + otherContradictionsCount: 0, + }), + ) } -function decisionModelOverviewWithJob(state: "queued" | "running" | "succeeded") { - return { - ...decisionModelOverview(false), - jobs: [ - { - id: "99999999-aaaa-4bbb-8ccc-dddddddddddd", - state, - tasksetDigest: digest, - runtimeJobId: state === "queued" ? null : "runtime-job-1", - candidateRuntimeId: state === "succeeded" ? "fixture-candidate-2" : null, - failureCode: null, - createdAt: "2026-11-20T16:30:00Z", - finishedAt: state === "succeeded" ? "2026-11-20T16:35:00Z" : null, - }, - ], +async function submitDialog(open: string, fields: Record, submit: string) { + fireEvent.click(await screen.findByRole("button", { name: open })) + for (const [name, value] of Object.entries(fields)) { + fireEvent.change(screen.getByRole("textbox", { name }), { target: { value } }) } + const form = within(screen.getByRole("dialog")) + .getByRole("button", { name: submit }) + .closest("form") + if (!form) throw new Error("The learning decision control must belong to a form.") + return form } describe("Learnings frontend integration", () => { @@ -256,42 +164,21 @@ describe("Learnings frontend integration", () => { expect(meta({})).toEqual([{ title: "Replica Hub" }]) }) - it("loads the dedicated contract and presents the complete repository learning history", async () => { + it("lists suggestions first without loading any history", async () => { const server = stubHubFetch(...learningsWorkspace()) server.use( http.get(`/api/repositories/2001/learnings`, () => Response.json(learningsResponse())), ) await renderHubFlow(server, "/repositories/2001/learnings") - expect(await screen.findByText("Raised by 2 reviewers on 2 prototypes")).toBeVisible() - expect(screen.getByText("The email field needs a visible label.")).toBeInTheDocument() - expect( - screen.getByText("The existing visible labels already explain these fields."), - ).toBeInTheDocument() expect( - screen.getByText("2 more opposing comments that Hub cannot show here"), - ).toBeInTheDocument() - expect(screen.getByText("This learning's wording is not available for review.")).toBeVisible() - expect(screen.getByText(/Accepted by @octocat .* with edits/)).toBeVisible() - expect( - within( - screen.getByRole("article", { - name: /wording is unavailable because its stored record failed integrity checks/, - }), - ).getByText(/agents do not get it/), - ).toBeVisible() - const recall = screen - .getAllByRole("region", { name: "What an agent gets" }) - .find((region) => region.textContent?.includes("Approved team learnings")) - if (!recall) throw new Error("The agent recall preview must be available.") - expect(recall).toHaveTextContent("Use one primary button per form.") - expect(screen.getByRole("cell", { name: /4 new comments, 2 labeled/ })).toBeVisible() - expect(screen.getByRole("cell", { name: "0.021 AI credits in 1 request" })).toBeVisible() - expect(screen.getByRole("cell", { name: /Copilot did not return a result/ })).toBeVisible() + await screen.findByRole("link", { name: "Show a visible label above every form field." }), + ).toHaveAttribute( + "href", + "/repositories/2001/learnings?status=suggested&learning=mem_suggestion", + ) + expect(screen.getByRole("link", { name: /Active\s*2/ })).toBeVisible() expect(screen.queryByRole("button", { name: /connect copilot/i })).not.toBeInTheDocument() - expect( - screen.getByText("Hub looks for learnings when you choose Find learnings now."), - ).toBeVisible() expect( server.requests .map(({ method, url }) => `${method} ${new URL(url).pathname}`) @@ -299,320 +186,153 @@ describe("Learnings frontend integration", () => { ).toEqual(["GET /api/repositories/2001/learnings"]) }) - it("reports daily checks only when automatic runs are enabled", async () => { + it("opens a learning with its evidence, replacements, and decision history", async () => { const server = stubHubFetch(...learningsWorkspace()) server.use( - http.get(`/api/repositories/2001/learnings`, () => - Response.json({ ...learningsResponse(), automaticRunsEnabled: true }), + http.get(`/api/repositories/2001/learnings`, () => Response.json(learningsResponse())), + http.get("/api/repositories/2001/learnings/mem_accepted/history", () => + Response.json({ + decisions: [ + { + version: 1, + state: "accepted", + change: "accepted", + by: "octocat", + at: "2026-11-08T20:00:00.000Z", + reason: null, + }, + ], + evidence: [], + otherEvidenceCount: 3, + contradictions: learningsResponse().suggestions[0]!.contradictions, + otherContradictionsCount: 1, + }), ), + emptyHistory(), + ) + const router = await renderHubFlow( + server, + "/repositories/2001/learnings?learning=mem_suggestion", ) - await renderHubFlow(server, "/repositories/2001/learnings") - expect( - await screen.findByText( - "Hub looks for learnings once a day when there are new comments, using the Copilot connection @hub-admin made.", - ), - ).toBeVisible() + expect(await screen.findByText("Raised by 2 reviewers on 2 prototypes")).toBeVisible() + expect(screen.getByText("The email field needs a visible label.")).toBeVisible() + expect(screen.getByRole("region", { name: "Conflicting evidence" })).toHaveTextContent( + "2 more conflicting evidence sources that Hub cannot show here", + ) + expect(screen.getByRole("region", { name: "Accepting this replaces" })).toHaveTextContent( + "This learning's wording is not available for review.", + ) + + await router.settle(() => router.navigate("/repositories/2001/learnings?learning=mem_accepted")) + + expect(await screen.findByText(/Accepted by @octocat .* with edits/)).toBeVisible() + expect(screen.getByRole("heading", { level: 1 })).toHaveFocus() + expect(screen.getByRole("region", { name: "Decision history" })).toHaveTextContent( + "Accepted by @octocat", + ) + expect(screen.getByText("3 more evidence sources that Hub cannot show here")).toBeVisible() + const opposing = screen.getByRole("region", { name: "Conflicting evidence" }) + expect(opposing).toHaveTextContent("The existing visible labels already explain these fields.") + expect(opposing).toHaveTextContent("1 more conflicting evidence source") }) - it("posts a run only to the dedicated repository endpoint", async () => { + it("restores the search field when going back to an earlier search", async () => { const server = stubHubFetch(...learningsWorkspace()) - const runRequests = vi.fn() server.use( http.get(`/api/repositories/2001/learnings`, () => Response.json(learningsResponse())), - http.post(`/api/repositories/2001/learnings/runs`, async ({ request }) => { - runRequests({ - contentType: request.headers.get("content-type"), - text: await request.text(), - }) - return Response.json({ notice: "Hub will look for learnings shortly." }) - }), ) - const router = await renderHubFlow(server, "/repositories/2001/learnings") + const router = await renderHubFlow(server, "/repositories/2001/learnings?q=label") + const search = await screen.findByRole("searchbox", { name: "Search learnings" }) + fireEvent.change(search, { target: { value: "button" } }) + await router.settle(() => router.navigate("/repositories/2001/learnings?q=button")) - await router.settle(() => - fireEvent.click(screen.getByRole("button", { name: "Find learnings now" })), - ) + await router.settle(() => router.navigate(-1)) - expect(runRequests).toHaveBeenCalledWith({ contentType: null, text: "" }) - expect(await screen.findByText("Hub will look for learnings shortly.")).toBeVisible() + expect(screen.getByRole("searchbox", { name: "Search learnings" })).toHaveValue("label") }) - it("evaluates an eligible Build through the route action and shows saved findings", async () => { + it("hides a learning when access to its repository is lost while it opens", async () => { const server = stubHubFetch(...learningsWorkspace()) - const evaluationRequests = vi.fn() - let evaluated = false server.use( - http.get(`/api/repositories/2001/learnings`, () => - Response.json({ - ...learningsResponse(), - capabilities: { administerHub: true, administerRepository: true }, - }), - ), - http.get(`/api/repositories/2001/decision-model`, () => - Response.json(decisionModelOverview(evaluated)), - ), - http.post( - `/api/repositories/2001/decision-model/builds/77777777-8888-4999-8aaa-bbbbbbbbbbbb/evaluation`, - async ({ request }) => { - evaluationRequests({ - contentType: request.headers.get("content-type"), - text: await request.text(), - }) - evaluated = true - return Response.json({ - id: "44444444-5555-4666-8777-888888888888", - runtimeEvaluationId: "fixture-evaluation-1", - candidateId: "fixture-candidate-1", - generation: 2, - responseDigest: digest, - evaluations: [ - { - learningId: "learning-1", - followsProbability: 0.82, - breaksProbability: 0.18, - }, - ], - usage: [], - }) - }, + http.get(`/api/repositories/2001/learnings`, () => Response.json(learningsResponse())), + http.get("/api/repositories/2001/learnings/mem_accepted/history", () => + Response.json( + { code: "repository_not_found", error: "Repository not found." }, + { status: 404 }, + ), ), ) - const router = await renderHubFlow(server, "/repositories/2001/learnings") + await renderHubFlow(server, "/repositories/2001/learnings?learning=mem_accepted") - await router.settle(() => - fireEvent.click(screen.getByRole("button", { name: "Evaluate Settings โ€” Build 42" })), - ) - - expect(evaluationRequests).toHaveBeenCalledWith({ contentType: null, text: "" }) - expect( - await screen.findByText(/promoted model found the Build more likely to follow the learning/), - ).toBeVisible() - expect( - screen.queryByRole("button", { name: "Evaluate Settings โ€” Build 42" }), - ).not.toBeInTheDocument() + expect(await screen.findByRole("heading", { name: "Page or record not found" })).toBeVisible() + expect(screen.queryByText(/Accepted by @octocat/)).not.toBeInTheDocument() }) - it("keeps the decision panel while an accepted training request becomes authoritative", async () => { + it("keeps the first-run consent action available when Hub has daily runs", async () => { const server = stubHubFetch(...learningsWorkspace()) - let trainingAccepted = false - let acceptedOverviewReads = 0 - let failAfterFinished = false - const trainingRequest = deferred() - onTestFinished(trainingRequest.release) - let trainingPostCount = 0 - let trainingJobReads = 0 server.use( http.get(`/api/repositories/2001/learnings`, () => - Response.json({ - ...learningsResponse(), - capabilities: { administerHub: true, administerRepository: true }, - }), - ), - http.get(`/api/repositories/2001/decision-model`, () => { - if (!trainingAccepted) return Response.json(decisionModelOverview(false)) - acceptedOverviewReads += 1 - if (failAfterFinished) { - return Response.json( - { error: "Another learning operation is still running." }, - { status: 409 }, - ) - } - if (acceptedOverviewReads > 1) { - return Response.json(decisionModelOverviewWithJob("succeeded")) - } - return Response.json( - { error: "Another learning operation is still running." }, - { status: 409 }, - ) - }), - http.get( - `/api/repositories/2001/decision-model/training-jobs/99999999-aaaa-4bbb-8ccc-dddddddddddd`, - () => { - trainingJobReads += 1 - return Response.json( - decisionModelOverviewWithJob(trainingJobReads === 1 ? "running" : "succeeded").jobs[0], - ) - }, + Response.json({ ...learningsResponse(), automaticRunsEnabled: true }), ), - http.post(`/api/repositories/2001/decision-model/training-jobs`, async () => { - trainingPostCount += 1 - await trainingRequest.promise - trainingAccepted = true - return Response.json({ - created: true, - job: { - id: "99999999-aaaa-4bbb-8ccc-dddddddddddd", - state: "queued", - tasksetDigest: digest, - runtimeJobId: null, - candidateRuntimeId: null, - failureCode: null, - createdAt: "2026-11-20T16:30:00Z", - finishedAt: null, - }, - }) - }), ) - const router = await renderHubFlow(server, "/repositories/2001/learnings") - - fireEvent.click(await screen.findByRole("button", { name: "Start training" })) - const confirm = screen.getByRole("button", { name: "Queue this training job" }) - fireEvent.click(confirm) - fireEvent.click(confirm) - - await waitFor(() => expect(confirm).toBeDisabled()) - expect(screen.getByRole("button", { name: "Cancel" })).toBeDisabled() - expect(screen.getByText(/submitting.*training request|training request.*prepar/i)).toBeVisible() - - trainingRequest.release() - - expect( - await screen.findByText("Training was queued within the confirmed repository budget."), - ).toBeVisible() - expect(screen.getByRole("checkbox", { name: "Repository training" })).toBeVisible() - expect( - screen.queryByText( - "Decision-model training is temporarily unavailable: Another learning operation is still running.", - ), - ).not.toBeInTheDocument() + await renderHubFlow(server, "/repositories/2001/learnings") expect( - await within( - screen.getByRole("region", { name: "Decision-model training history" }), - ).findByRole("cell", { name: "Queued" }), + await screen.findByRole("link", { name: "Show a visible label above every form field." }), ).toBeVisible() - expect(acceptedOverviewReads).toBeGreaterThanOrEqual(1) - await waitFor(() => expect(trainingJobReads).toBeGreaterThanOrEqual(1)) - expect( - await within( - screen.getByRole("region", { name: "Decision-model training history" }), - ).findByRole("cell", { name: "Running" }), - ).toBeVisible() - expect(trainingPostCount).toBe(1) - await waitFor(() => expect(trainingJobReads).toBeGreaterThanOrEqual(2), { timeout: 4_000 }) - expect(await screen.findByRole("cell", { name: "Finished" }, { timeout: 4_000 })).toBeVisible() - failAfterFinished = true - await router.settle(() => router.revalidate()) - expect(trainingPostCount).toBe(1) - expect( - screen.getByText( - "Decision-model training is temporarily unavailable: Another learning operation is still running.", - ), - ).toBeVisible() - expect(screen.queryByText(/Training was accepted/)).not.toBeInTheDocument() + 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() }) - it("shows an uncorrelated learning lock instead of attributing it to a running job", async () => { + it("shows migration redaction follow-ups to the repository administrator after reload", async () => { const server = stubHubFetch(...learningsWorkspace()) - let overviewReads = 0 + const notice = + "Rebuild learning mem_111111111111111111111111. Follow up on export exp_222222222222222222222222 at private/exports/team.json." + let loads = 0 server.use( - http.get(`/api/repositories/2001/learnings`, () => - Response.json({ + http.get("/api/repositories/2001/learnings", () => { + loads++ + return Response.json({ ...learningsResponse(), - capabilities: { administerHub: true, administerRepository: true }, - }), - ), - http.get(`/api/repositories/2001/decision-model`, () => { - overviewReads += 1 - if (overviewReads === 1) { - return Response.json(decisionModelOverviewWithJob("running")) - } - return Response.json( - { error: "Another learning operation is still running." }, - { status: 409 }, - ) + loadError: notice, + }) }), ) const router = await renderHubFlow(server, "/repositories/2001/learnings") - expect( - screen.getByText("Running: training is using the pinned evidence shown for this job."), - ).toBeVisible() - expect(overviewReads).toBe(1) - + expect(await screen.findByText(notice)).toBeVisible() await router.settle(() => router.revalidate()) - - expect( - screen.getByText( - "Decision-model training is temporarily unavailable: Another learning operation is still running.", - ), - ).toBeVisible() - expect(overviewReads).toBe(2) - expect(screen.queryByRole("region", { name: "Decision-model training history" })).toBeNull() + expect(loads).toBe(2) + expect(screen.getByText(notice)).toBeVisible() }) - it("does not carry a cached training job into another repository", async () => { + it("posts a run only to the dedicated repository endpoint", async () => { const server = stubHubFetch(...learningsWorkspace()) + const runRequests = vi.fn() server.use( - http.get(`/api/repositories/:repositoryId/learnings`, ({ params }) => - Response.json({ - ...learningsResponse(), - repository: { - ...learningsResponse().repository, - id: String(params.repositoryId), - nameWithOwner: params.repositoryId === "2001" ? "github/prototype" : "github/empty", - }, - capabilities: { administerHub: true, administerRepository: true }, - }), - ), - http.get(`/api/repositories/2001/decision-model`, () => - Response.json(decisionModelOverviewWithJob("running")), - ), - http.get(`/api/repositories/2002/decision-model`, () => - Response.json({ error: "Another learning operation is still running." }, { status: 409 }), - ), + http.get(`/api/repositories/2001/learnings`, () => Response.json(learningsResponse())), + http.post(`/api/repositories/2001/learnings/runs`, async ({ request }) => { + runRequests({ + contentType: request.headers.get("content-type"), + text: await request.text(), + }) + return Response.json({ notice: "Hub will look for learnings shortly." }) + }), ) const router = await renderHubFlow(server, "/repositories/2001/learnings") - expect( - await screen.findByText("Running: training is using the pinned evidence shown for this job."), - ).toBeVisible() - - await router.settle(() => router.navigate("/repositories/2002/learnings")) - - expect( - await screen.findByText( - "Decision-model training is temporarily unavailable: Another learning operation is still running.", - ), - ).toBeVisible() - expect( - screen.queryByText("Running: training is using the pinned evidence shown for this job."), - ).not.toBeInTheDocument() - }) - - it("keeps the explicit run action for a queued automatic run", async () => { - const server = stubHubFetch(...learningsWorkspace()) - const response = learningsResponse() - server.use( - http.get(`/api/repositories/2001/learnings`, () => - Response.json({ - ...response, - runAvailable: true, - runs: [ - { - id: 9, - startedAt: "2026-11-11T12:00:00.000Z", - startedBy: { type: "daily" }, - state: "queued", - result: null, - usage: null, - }, - ...response.runs, - ], - }), - ), + await router.settle(() => + fireEvent.click(screen.getByRole("button", { name: "Find learnings now" })), ) - await renderHubFlow(server, "/repositories/2001/learnings") - expect(await screen.findByRole("button", { name: "Find learnings now" })).toBeVisible() - expect(screen.getByText("Hub will look for learnings shortly.")).toHaveAttribute( - "role", - "status", - ) + expect(runRequests).toHaveBeenCalledWith({ contentType: null, text: "" }) + expect(await screen.findByText("Hub will look for learnings shortly.")).toBeVisible() }) - it("accepts a learning through the repository endpoint and refreshes recall", async () => { + it("accepts a suggestion and keeps it open as an active learning", async () => { const original = learningsResponse() const suggestionRecord = original.suggestions[0]! const decision = vi.fn() @@ -628,18 +348,20 @@ describe("Learnings frontend integration", () => { learnings: [ { id: suggestionRecord.id, + title: null, content: suggestionRecord.content, + digest, acceptedBy: "octocat", acceptedAt: "2026-11-10T12:00:00Z", edited: false, status: "recalled", }, ], - recall: { text: `Approved team learnings\n${suggestionRecord.content}`, count: 1 }, } : original, ), ), + emptyHistory(), http.post( `/api/repositories/2001/learnings/${suggestionRecord.id}/decision`, async ({ request }) => { @@ -649,30 +371,22 @@ describe("Learnings frontend integration", () => { }, ), ) - const router = await renderHubFlow(server, "/repositories/2001/learnings") - const suggestion = await screen.findByRole("article", { - name: /Show a visible label above every form field/, - }) - - const accept = within(suggestion).getByRole("button", { name: "Accept" }) - const acceptForm = accept.closest("form") + const router = await renderHubFlow( + server, + `/repositories/2001/learnings?learning=${suggestionRecord.id}`, + ) + const acceptForm = (await screen.findByRole("button", { name: "Accept learning" })).closest( + "form", + ) if (!acceptForm) throw new Error("The acceptance control must belong to a form.") await router.settle(() => fireEvent.submit(acceptForm)) expect(decision).toHaveBeenCalledExactlyOnceWith({ decision: "accept", digest }) - expect( - await screen.findByRole("article", { - name: /Show a visible label above every form field/, - }), - ).toHaveTextContent("Accepted by @octocat") - const recall = screen - .getAllByRole("region", { name: "What an agent gets" }) - .find((region) => region.textContent?.includes("Approved team learnings")) - if (!recall) throw new Error("The accepted learning must enter the agent recall preview.") - expect(recall).toHaveTextContent("Show a visible label above every form field") + expect(await screen.findByText("Agents get this learning.")).toBeVisible() + expect(screen.getByRole("button", { name: "Edit learning" })).toBeVisible() }) - it("refreshes a changed suggestion after a stale-digest response", async () => { + it("shows a changed suggestion's current wording after a stale-digest response", async () => { const server = stubHubFetch(...learningsWorkspace()) const original = learningsResponse() let changed = false @@ -691,6 +405,7 @@ describe("Learnings frontend integration", () => { : original, ), ), + emptyHistory(), http.post(`/api/repositories/2001/learnings/:learningId/decision`, () => { changed = true return Response.json( @@ -699,92 +414,159 @@ describe("Learnings frontend integration", () => { ) }), ) - const router = await renderHubFlow(server, "/repositories/2001/learnings") - const suggestion = await screen.findByRole("article", { - name: "Show a visible label above every form field.", - }) - fireEvent.click(within(suggestion).getByRole("button", { name: "Edit and accept" })) - const wording = within(suggestion).getByRole("textbox", { name: "Wording agents get" }) - fireEvent.change(wording, { target: { value: "My stale draft." } }) - - await router.settle(() => - fireEvent.click(within(suggestion).getByRole("button", { name: "Accept with this wording" })), + const router = await renderHubFlow( + server, + "/repositories/2001/learnings?learning=mem_suggestion", + ) + const form = await submitDialog( + "Reject suggestion", + { "Why reject it?": "My stale reason." }, + "Reject suggestion", ) + await router.settle(() => fireEvent.submit(form)) expect( - await screen.findByRole("article", { + await screen.findByText("This suggestion changed. Review its current wording and evidence."), + ).toBeVisible() + expect( + screen.getByRole("heading", { name: "Show a persistent visible label above every form field.", }), ).toBeVisible() - expect(screen.queryByDisplayValue("My stale draft.")).not.toBeInTheDocument() + expect(screen.queryByDisplayValue("My stale reason.")).not.toBeInTheDocument() }) - it.each([ - { - label: "edited acceptance", - article: "Show a visible label above every form field.", - open: "Edit and accept", - textbox: "Wording agents get", - value: "Use a visible label on every field.", - submit: "Accept with this wording", - expected: { decision: "accept", digest, content: "Use a visible label on every field." }, - error: "This suggestion changed. Review its current wording and evidence.", - status: 409, - }, - { - label: "rejection", - article: "Show a visible label above every form field.", - open: "Reject", - textbox: "Why reject this suggestion?", - value: "The design system already covers this.", - submit: "Reject suggestion", - expected: { - decision: "reject", + it("sends the exact edit and keeps it visible when the save fails", async () => { + const server = stubHubFetch(...learningsWorkspace()) + const guidance = "a".repeat(3999) + "๐Ÿ™‚" + const response = learningsResponse() + response.learnings[0]!.content = guidance + const bodies: unknown[] = [] + server.use( + http.get(`/api/repositories/2001/learnings`, () => Response.json(response)), + emptyHistory(), + http.post(`/api/repositories/2001/learnings/:learningId/decision`, async ({ request }) => { + bodies.push(await request.json()) + return Response.json({ error: "Decisions are temporarily unavailable." }, { status: 503 }) + }), + ) + const router = await renderHubFlow(server, "/repositories/2001/learnings?learning=mem_accepted") + const form = await submitDialog( + "Edit learning", + { + Title: "One primary button", + "Why change it?": "Say what to name it.", + }, + "Save changes", + ) + await router.settle(() => fireEvent.submit(form)) + + const dialog = screen.getByRole("dialog", { name: "Edit learning" }) + expect(await screen.findByText("Decisions are temporarily unavailable.")).toBeVisible() + expect(dialog).toBeVisible() + expect(screen.getByRole("textbox", { name: "Why change it?" })).toHaveValue( + "Say what to name it.", + ) + expect(bodies).toEqual([ + { + decision: "edit", digest, - reason: "The design system already covers this.", + title: "One primary button", + content: guidance, + reason: "Say what to name it.", }, - error: "Decisions are temporarily unavailable.", - status: 503, - }, - { - label: "retirement", - article: "Use one primary button per form.", - open: "Retire", - textbox: "Why retire this learning?", - value: "This guidance no longer applies.", - submit: "Retire learning", - expected: { decision: "retire", reason: "This guidance no longer applies." }, - error: "Decisions are temporarily unavailable.", - status: 503, - }, - ])( - "sends the exact $label input and keeps it visible when the save fails", - async ({ article, open, textbox, value, submit, expected, error, status }) => { - const server = stubHubFetch(...learningsWorkspace()) - const bodies: unknown[] = [] - server.use( - http.get(`/api/repositories/2001/learnings`, () => Response.json(learningsResponse())), - http.post(`/api/repositories/2001/learnings/:learningId/decision`, async ({ request }) => { - bodies.push(await request.json()) - return Response.json({ error }, { status }) + ]) + }) + + it("sends the exact rejection of an active learning without a digest", async () => { + const server = stubHubFetch(...learningsWorkspace()) + const bodies: unknown[] = [] + server.use( + http.get(`/api/repositories/2001/learnings`, () => Response.json(learningsResponse())), + emptyHistory(), + http.post(`/api/repositories/2001/learnings/:learningId/decision`, async ({ request }) => { + bodies.push(await request.json()) + return Response.json({ error: "Decisions are temporarily unavailable." }, { status: 503 }) + }), + ) + const router = await renderHubFlow(server, "/repositories/2001/learnings?learning=mem_accepted") + const form = await submitDialog( + "Reject learning", + { "Why reject it?": "This guidance no longer applies." }, + "Reject learning", + ) + await router.settle(() => fireEvent.submit(form)) + + expect(await screen.findByText("Decisions are temporarily unavailable.")).toBeVisible() + expect(screen.getByRole("dialog", { name: "Reject learning" })).toBeVisible() + expect(bodies).toEqual([{ decision: "retire", reason: "This guidance no longer applies." }]) + }) + + it("accepts a rejected learning again with the digest and a reason", async () => { + const server = stubHubFetch(...learningsWorkspace()) + const bodies: unknown[] = [] + server.use( + http.get(`/api/repositories/2001/learnings`, () => + Response.json({ + ...learningsResponse(), + rejected: [ + { + id: "mem_rejected", + title: "Open links in a new tab", + content: "Open every link in a new tab.", + digest, + state: "rejected", + replaces: [{ id: "mem_links", content: "Open links in the same tab." }], + decidedBy: "hubot", + decidedAt: "2026-11-08T20:00:00.000Z", + reason: "It breaks the back button.", + }, + ], }), - ) - const router = await renderHubFlow(server, "/repositories/2001/learnings") - const card = await screen.findByRole("article", { name: article }) - fireEvent.click(within(card).getByRole("button", { name: open })) - const input = within(card).getByRole("textbox", { name: textbox }) - fireEvent.change(input, { target: { value } }) - - const submitButton = within(card).getByRole("button", { name: submit }) - const form = submitButton.closest("form") - if (!form) throw new Error("The learning decision control must belong to a form.") - await router.settle(() => fireEvent.submit(form)) - - expect(await screen.findByText(error)).toBeVisible() - expect(input).toHaveValue(value) - expect(bodies).toEqual([expected]) - }, - ) + ), + emptyHistory(), + http.post(`/api/repositories/2001/learnings/:learningId/decision`, async ({ request }) => { + bodies.push(await request.json()) + return Response.json({ error: "Decisions are temporarily unavailable." }, { status: 503 }) + }), + ) + const router = await renderHubFlow(server, "/repositories/2001/learnings?learning=mem_rejected") + expect(await screen.findByText("It breaks the back button.")).toBeVisible() + expect(screen.getByRole("region", { name: "Accepting this replaces" })).toHaveTextContent( + "Open links in the same tab.", + ) + const form = await submitDialog( + "Accept learning", + { "Why accept it now?": "External links only." }, + "Accept learning", + ) + await router.settle(() => fireEvent.submit(form)) + + expect(await screen.findByText("Decisions are temporarily unavailable.")).toBeVisible() + expect(screen.getByRole("dialog", { name: "Accept learning" })).toBeVisible() + expect(bodies).toEqual([{ decision: "reinstate", digest, reason: "External links only." }]) + }) + + it("shows a Hub administrator without repository authority a read-only library", async () => { + const server = stubHubFetch( + ...learningsWorkspace(), + http.get("/api/repositories/2001/learnings", () => + Response.json({ + ...learningsResponse(), + capabilities: { administerHub: true, administerRepository: false }, + permissions: { viewEvidence: true, decide: false, requestRun: false }, + usageCredits: null, + runAvailable: false, + runs: [], + }), + ), + ) + 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.queryByRole("button", { name: "Accept" })).not.toBeInTheDocument() + }) it("shows access denied without exposing learning data or decision controls", async () => { const server = stubHubFetch( @@ -802,8 +584,7 @@ describe("Learnings frontend integration", () => { expect( await screen.findByText("You do not have permission to view this repository's learnings."), ).toBeVisible() - expect(screen.queryByRole("article")).not.toBeInTheDocument() - expect(screen.queryByRole("button", { name: "Accept" })).not.toBeInTheDocument() + expect(screen.queryByRole("navigation", { name: "Learning status" })).not.toBeInTheDocument() expect(screen.queryByRole("button", { name: "Find learnings now" })).not.toBeInTheDocument() }) @@ -824,7 +605,9 @@ describe("Learnings frontend integration", () => { expect( await screen.findByText("Learnings stays off until a Hub administrator connects Copilot."), ).toBeVisible() - expect(screen.getByRole("button", { name: "Accept" })).toBeVisible() + expect( + 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("button", { name: /connect copilot/i })).not.toBeInTheDocument() }) diff --git a/hub/client/application/hub/routes/route-naming.test.tsx b/hub/client/application/hub/routes/route-naming.test.tsx index 25ea779d7..d9aa33af0 100644 --- a/hub/client/application/hub/routes/route-naming.test.tsx +++ b/hub/client/application/hub/routes/route-naming.test.tsx @@ -109,6 +109,7 @@ describe("Hub primary route names", () => { const base = { ...emptyLearnings(), repository: second } const suggestion = { id: "mem_second", + title: null, reviewDigest: `sha256:${"a".repeat(64)}`, content: "Use a visible form label.", support: { reviewers: 2, prototypes: 2 }, @@ -131,7 +132,9 @@ describe("Hub primary route names", () => { ? [ { id: suggestion.id, + title: null, content: suggestion.content, + digest: suggestion.reviewDigest, acceptedBy: "octocat", acceptedAt: "2026-11-20T12:00:00Z", edited: false, @@ -141,6 +144,15 @@ describe("Hub primary route names", () => { : [], }), ), + http.get(`/api${path}/:learningId/history`, () => + Response.json({ + decisions: [], + evidence: [], + otherEvidenceCount: 0, + contradictions: [], + otherContradictionsCount: 0, + }), + ), http.post(`/api${path}/runs`, () => { ran = true return Response.json({ notice: "Learning run requested." }) @@ -155,8 +167,10 @@ describe("Hub primary route names", () => { const run = screen.getByRole("button", { name: "Find learnings now" }) expect(new URL(run.closest("form")!.action).pathname).toBe(`${path}/runs`) await router.settle(() => fireEvent.click(run)) - const article = await screen.findByRole("article", { name: suggestion.content }) - const accept = within(article).getByRole("button", { name: "Accept" }) + await router.settle(async () => + fireEvent.click(await screen.findByRole("link", { name: suggestion.content })), + ) + const accept = await screen.findByRole("button", { name: "Accept learning" }) expect(new URL(accept.closest("form")!.action).pathname).toBe( `${path}/${suggestion.id}/decision`, ) @@ -166,7 +180,7 @@ describe("Hub primary route names", () => { decision: "accept", digest: suggestion.reviewDigest, }) - expect(await screen.findByRole("button", { name: "Retire" })).toBeEnabled() + expect(await screen.findByRole("button", { name: "Edit learning" })).toBeEnabled() expect(router.state.location.pathname).toBe(path) }) diff --git a/hub/client/application/hub/routes/settings-learnings/index.test.ts b/hub/client/application/hub/routes/settings-learnings/index.test.ts deleted file mode 100644 index ad7ddd0ba..000000000 --- a/hub/client/application/hub/routes/settings-learnings/index.test.ts +++ /dev/null @@ -1,292 +0,0 @@ -import { describe, expect, it, vi } from "vitest" - -import { emptyLearnings } from "../fixtures/empty-learnings" -import { clientAction, clientLoader } from "." - -const candidateId = "22222222-3333-4444-8555-666666666666" -const jobId = "33333333-4444-4555-8666-777777777777" -const tasksetDigest = `sha256:${"a".repeat(64)}` - -function routeRequest(form: Record) { - const body = new URLSearchParams() - for (const [name, value] of Object.entries(form)) { - if (value !== undefined) body.set(name, value) - } - return new Request(new URL("/repositories/2001/learnings", window.location.origin), { - method: "POST", - body, - }) -} - -describe("settings Learnings route", () => { - it("requests the decision-model overview only for a current Hub administrator", async () => { - const learnings = emptyLearnings() - let canAdministerHub = false - const send = vi.fn((input: RequestInfo | URL) => { - const url = new URL(input instanceof Request ? input.url : input) - if (url.pathname.endsWith("/learnings")) { - return Promise.resolve( - Response.json({ - ...learnings, - capabilities: { administerHub: canAdministerHub, administerRepository: true }, - }), - ) - } - return Promise.resolve( - Response.json({ error: "Decision runtime is not configured." }, { status: 404 }), - ) - }) - - vi.stubGlobal("fetch", send) - const request = new Request(new URL("/repositories/2001/learnings", window.location.origin)) - - const repositoryOnly = await clientLoader({ - request, - params: { repositoryId: "2001" }, - } as unknown as Parameters[0]) - expect(repositoryOnly.decisionModel).toBeNull() - expect(send).toHaveBeenCalledTimes(1) - - send.mockClear() - canAdministerHub = true - const hubAdministrator = await clientLoader({ - request, - params: { repositoryId: "2001" }, - } as unknown as Parameters[0]) - expect(hubAdministrator.decisionModel).toEqual({ state: "not-configured" }) - expect(send).toHaveBeenCalledTimes(2) - }) - - it("keeps repository learnings visible when the configured decision runtime is unavailable", async () => { - const learnings = emptyLearnings() - vi.stubGlobal( - "fetch", - vi.fn((input: RequestInfo | URL) => { - const url = new URL(input instanceof Request ? input.url : input) - return Promise.resolve( - url.pathname.endsWith("/learnings") - ? Response.json({ - ...learnings, - capabilities: { administerHub: true, administerRepository: true }, - }) - : Response.json({ error: "The decision runtime did not respond." }, { status: 503 }), - ) - }), - ) - - const result = await clientLoader({ - request: new Request(new URL("/repositories/2001/learnings", window.location.origin)), - params: { repositoryId: "2001" }, - } as unknown as Parameters[0]) - - expect(result.accessDenied).toBe(false) - expect(result.decisionModel).toEqual({ - state: "unavailable", - error: "The decision runtime did not respond.", - }) - }) - - it.each([ - { - label: "uncorrelated learning-operation conflict", - response: Response.json( - { error: "Another learning operation is still running." }, - { status: 409 }, - ), - expected: "Another learning operation is still running.", - }, - { - label: "invalid overview", - response: Response.json({ configuration: null }), - expected: "The API returned data in an unexpected shape.", - }, - ])("isolates a $label to the optional decision-model panel", async ({ response, expected }) => { - const learnings = emptyLearnings() - vi.stubGlobal( - "fetch", - vi.fn((input: RequestInfo | URL) => { - const url = new URL(input instanceof Request ? input.url : input) - return Promise.resolve( - url.pathname.endsWith("/learnings") - ? Response.json({ - ...learnings, - capabilities: { administerHub: true, administerRepository: true }, - }) - : response.clone(), - ) - }), - ) - - const result = await clientLoader({ - request: new Request(new URL("/repositories/2001/learnings", window.location.origin)), - params: { repositoryId: "2001" }, - } as unknown as Parameters[0]) - - expect(result.accessDenied).toBe(false) - expect(result.decisionModel).toEqual({ state: "unavailable", error: expected }) - }) - - it.each([ - { - label: "bounded settings", - form: { - _action: "/repositories/2001/learnings/decision-model/settings", - enabled: "on", - backend: "customer-runtime", - maxUpdates: "8", - maxSeconds: "300", - monthlyBudgetCredits: "10", - }, - endpoint: "/api/repositories/2001/decision-model", - method: "PATCH", - body: { - enabled: true, - backend: "customer-runtime", - maxUpdates: 8, - maxSeconds: 300, - monthlyBudgetCredits: "10", - }, - response: { - enabled: true, - generation: 4, - backend: "customer-runtime", - maxUpdates: 8, - maxSeconds: 300, - monthlyBudgetCredits: "10", - }, - }, - { - label: "confirmed training", - form: { - _action: "/repositories/2001/learnings/decision-model/training", - idempotencyKey: "hub-ui-request-1", - expectedConfigurationGeneration: "3", - }, - endpoint: "/api/repositories/2001/decision-model/training-jobs", - method: "POST", - body: { idempotencyKey: "hub-ui-request-1", expectedConfigurationGeneration: 3 }, - response: { - created: true, - job: { - id: jobId, - state: "queued", - tasksetDigest, - runtimeJobId: null, - candidateRuntimeId: null, - failureCode: null, - createdAt: "2026-11-18T12:05:00Z", - finishedAt: null, - }, - }, - }, - { - label: "queued or running cancellation", - form: { - _action: `/repositories/2001/learnings/decision-model/training/${jobId}/cancel`, - }, - endpoint: `/api/repositories/2001/decision-model/training-jobs/${jobId}/cancel`, - method: "POST", - body: undefined, - response: { id: jobId, state: "cancelled" }, - }, - { - label: "explicit rejection", - form: { - _action: `/repositories/2001/learnings/decision-model/candidates/${candidateId}/reject`, - reason: "Held-out regressions outweigh the gains.", - }, - endpoint: `/api/repositories/2001/decision-model/candidates/${candidateId}/rejection`, - method: "POST", - body: { reason: "Held-out regressions outweigh the gains." }, - response: { - candidateId, - rejectedAt: "2026-11-18T12:05:00Z", - }, - }, - { - label: "explicit promotion", - form: { - _action: `/repositories/2001/learnings/decision-model/candidates/${candidateId}/promote`, - expectedGeneration: "2", - }, - endpoint: `/api/repositories/2001/decision-model/candidates/${candidateId}/promotion`, - method: "POST", - body: { expectedGeneration: 2 }, - response: { - candidateId, - runtimeCandidateId: "candidate-2", - previousCandidateId: null, - previousRuntimeCandidateId: null, - generation: 3, - }, - }, - { - label: "explicit rollback", - form: { - _action: "/repositories/2001/learnings/decision-model/rollback", - expectedGeneration: "3", - }, - endpoint: "/api/repositories/2001/decision-model/rollback", - method: "POST", - body: { expectedGeneration: 3 }, - response: { - candidateId, - runtimeCandidateId: "candidate-1", - previousCandidateId: candidateId, - previousRuntimeCandidateId: "candidate-2", - generation: 4, - }, - }, - ])( - "sends the exact $label mutation", - async ({ label, form, endpoint, method, body, response }) => { - const send = vi.fn(() => Promise.resolve(Response.json(response))) - vi.stubGlobal("fetch", send) - - const result = await clientAction({ - request: routeRequest(form), - params: { repositoryId: "2001" }, - } as unknown as Parameters[0]) - - expect(result.data.saved).toBe(true) - if (label === "confirmed training") { - expect(result.data).toMatchObject({ trainingJobId: jobId }) - } - expect(send).toHaveBeenCalledOnce() - const [url, init] = send.mock.calls[0]! - expect(new URL(url instanceof Request ? url.url : url).pathname).toBe(endpoint) - expect(init).toMatchObject({ method }) - expect(init?.body == null || typeof init.body === "string").toBe(true) - expect(init?.body == null ? undefined : JSON.parse(init.body as string)).toEqual(body) - }, - ) - - it("marks a stale promotion generation for refresh instead of reporting success", async () => { - vi.stubGlobal( - "fetch", - vi.fn(() => - Promise.resolve( - Response.json( - { error: "The promoted decision model changed. Refresh and try again." }, - { status: 409 }, - ), - ), - ), - ) - - const result = await clientAction({ - request: routeRequest({ - _action: `/repositories/2001/learnings/decision-model/candidates/${candidateId}/promote`, - expectedGeneration: "2", - }), - params: { repositoryId: "2001" }, - } as unknown as Parameters[0]) - - expect(result.init?.status).toBe(409) - expect(result.data).toEqual({ - saved: false, - error: "The promoted decision model changed. Refresh and try again.", - revalidate: true, - }) - }) -}) diff --git a/hub/client/application/hub/routes/settings-learnings/index.tsx b/hub/client/application/hub/routes/settings-learnings/index.tsx index f3fd159b6..057f17f59 100644 --- a/hub/client/application/hub/routes/settings-learnings/index.tsx +++ b/hub/client/application/hub/routes/settings-learnings/index.tsx @@ -1,28 +1,20 @@ -import { useEffect, useRef, useState } from "react" -import { data, useFetcher, useOutletContext, useRevalidator } from "react-router" +import { useEffect, useRef } from "react" +import { data, useFetcher, useLocation, useOutletContext, useRevalidator } from "react-router" import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router" import { LearningsPage } from "@pages/learnings-page" import { recordIdentifierSchema, workspaceResponseSchema } from "@application/hub/contracts" -import { - decisionBuildEvaluationMutationResponseSchema, - decisionCandidateRejectionMutationResponseSchema, - decisionModelConfigurationResponseSchema, - decisionModelOverviewResponseSchema, - decisionPromotionMutationResponseSchema, - decisionTrainingJobResponseSchema, - decisionTrainingMutationResponseSchema, - decisionTrainingRequestResponseSchema, -} from "@application/hub/decision-model-contracts" -import type { DecisionModelAvailability } from "@application/hub/decision-model-contracts/types" -import type { DecisionTrainingJobResponse } from "@application/hub/decision-model-contracts/types" +import type { + LearningHistoryResponse, + LearningsResponse, +} from "@application/hub/learnings-contracts/types" import { learningDecisionInputSchema, + learningHistoryResponseSchema, learningMutationResponseSchema, learningsResponseSchema, } from "@application/hub/learnings-contracts" import type { ProductActionResult } from "@application/hub/product-contracts/types" -import { ApiContractError } from "@application/hub/requests/api-contract-error" import { ApiRequestError } from "@application/hub/requests/api-request-error" import { ProductFormBoundary } from "@application/hub/screens/product-form-boundary" import { settingsLearnings } from "@application/hub/view-models/settings-learnings" @@ -33,11 +25,7 @@ import type { WorkspaceRouteHandle } from "../workspace/types" export const handle = { workspaceSection: "learnings" } satisfies WorkspaceRouteHandle -type LearningActionResult = ProductActionResult & { - revalidate?: boolean - trainingJobId?: string - trainingJob?: DecisionTrainingJobResponse -} +type LearningActionResult = ProductActionResult & { revalidate?: boolean } function repositoryId(params: LoaderFunctionArgs["params"]) { const parsed = recordIdentifierSchema.safeParse(params.repositoryId) @@ -55,31 +43,38 @@ export async function clientLoader({ request, params }: LoaderFunctionArgs) { if (response.repository.id !== id) { throw new Response("This repository is not available.", { status: 404 }) } - let decisionModel: DecisionModelAvailability | null = null - if (!response.accessDenied && response.capabilities.administerHub) { - try { - decisionModel = { - state: "available", - overview: await requestProductJson( - request, - `/api/repositories/${id}/decision-model`, - decisionModelOverviewResponseSchema, - ), - } - } catch (error) { - if (error instanceof ApiRequestError && error.status === 404) { - decisionModel = { state: "not-configured" } - } else if ( - (error instanceof ApiRequestError && ![401, 403].includes(error.status)) || - error instanceof ApiContractError - ) { - decisionModel = { state: "unavailable", error: error.message } - } else { - throw error - } - } + return { ...response, history: await learningHistory(request, response) } +} + +// Only a selected learning needs its history, so the list stays one request. +async function learningHistory( + request: Request, + response: LearningsResponse, +): Promise { + const learningId = new URL(request.url).searchParams.get("learning") + if (response.accessDenied || !learningId) return null + const known = [...response.suggestions, ...response.learnings, ...response.rejected].some( + (entry) => entry.id === learningId, + ) + if (!known) return null + try { + return await requestProductJson( + request, + `/api/repositories/${response.repository.id}/learnings/${encodeURIComponent(learningId)}/history`, + learningHistoryResponseSchema, + ) + } catch (error) { + // A learning can disappear between the two requests; show the list instead. + // A lost repository is a denial, so it still reaches the error boundary. + if (learningNotFound(error)) return null + throw error } - return { ...response, decisionModel } +} + +function learningNotFound(error: unknown) { + if (!(error instanceof ApiRequestError) || error.status !== 404) return false + const body = error.body as { code?: unknown } | undefined + return body?.code !== "repository_not_found" } export async function clientAction({ request, params }: ActionFunctionArgs) { @@ -109,22 +104,14 @@ export async function clientAction({ request, params }: ActionFunctionArgs) { try { const response = source.pathname === `${route}/runs` - ? { - notice: ( - await requestProductJson( - request, - `/api/repositories/${id}/learnings/runs`, - learningMutationResponseSchema, - { method: "POST" }, - ) - ).notice, - } - : source.pathname.startsWith(`${route}/decision-model/`) - ? await submitDecisionModelAction(request, id, route, source, form) - : { - notice: (await submitDecision(request, id, route, source, form)).notice, - } - return data({ saved: true, ...response }) + ? await requestProductJson( + request, + `/api/repositories/${id}/learnings/runs`, + learningMutationResponseSchema, + { method: "POST" }, + ) + : await submitDecision(request, id, route, source, form) + return data({ saved: true, notice: response.notice }) } catch (error) { if (error instanceof Response) { return data( @@ -146,114 +133,6 @@ export async function clientAction({ request, params }: ActionFunctionArgs) { } } -async function submitDecisionModelAction( - request: Request, - repositoryId: string, - route: string, - source: URL, - form: FormData, -) { - const prefix = `${route}/decision-model` - if (source.pathname === `${prefix}/settings`) { - const enabled = form.get("enabled") === "on" - const backend = form.get("backend") - const maxUpdates = Number(form.get("maxUpdates")) - const maxSeconds = Number(form.get("maxSeconds")) - const monthlyBudgetCredits = form.get("monthlyBudgetCredits") - await requestProductJson( - request, - `/api/repositories/${repositoryId}/decision-model`, - decisionModelConfigurationResponseSchema, - { - method: "PATCH", - body: { enabled, backend, maxUpdates, maxSeconds, monthlyBudgetCredits }, - }, - ) - return { - notice: enabled - ? "Decision-model settings were saved and training is enabled." - : "Decision-model settings were saved and training is paused.", - } - } - if (source.pathname === `${prefix}/training`) { - const idempotencyKey = form.get("idempotencyKey") - const expectedConfigurationGeneration = Number(form.get("expectedConfigurationGeneration")) - const parsed = decisionTrainingRequestResponseSchema - const response = await requestProductJson( - request, - `/api/repositories/${repositoryId}/decision-model/training-jobs`, - parsed, - { method: "POST", body: { idempotencyKey, expectedConfigurationGeneration } }, - ) - return { - notice: response.created - ? "Training was queued within the confirmed repository budget." - : "This training request was already queued.", - trainingJob: response.job, - trainingJobId: response.job.id, - } - } - if (source.pathname === `${prefix}/rollback`) { - const expectedGeneration = Number(form.get("expectedGeneration")) - await requestProductJson( - request, - `/api/repositories/${repositoryId}/decision-model/rollback`, - decisionPromotionMutationResponseSchema, - { method: "POST", body: { expectedGeneration } }, - ) - return { notice: "The previous decision model was restored as a new promotion generation." } - } - const evaluation = source.pathname.match( - new RegExp(`^${prefix}/builds/([0-9a-f-]+)/evaluate$`, "i"), - ) - if (evaluation?.[1]) { - await requestProductJson( - request, - `/api/repositories/${repositoryId}/decision-model/builds/${evaluation[1]}/evaluation`, - decisionBuildEvaluationMutationResponseSchema, - { method: "POST" }, - ) - return { notice: "The Build evaluation was saved with the promoted decision model." } - } - const cancel = source.pathname.match(new RegExp(`^${prefix}/training/([0-9a-f-]+)/cancel$`, "i")) - if (cancel?.[1]) { - await requestProductJson( - request, - `/api/repositories/${repositoryId}/decision-model/training-jobs/${cancel[1]}/cancel`, - decisionTrainingMutationResponseSchema, - { method: "POST" }, - ) - return { notice: "Training cancellation was requested." } - } - const promotion = source.pathname.match( - new RegExp(`^${prefix}/candidates/([0-9a-f-]+)/promote$`, "i"), - ) - if (promotion?.[1]) { - const expectedGeneration = Number(form.get("expectedGeneration")) - await requestProductJson( - request, - `/api/repositories/${repositoryId}/decision-model/candidates/${promotion[1]}/promotion`, - decisionPromotionMutationResponseSchema, - { method: "POST", body: { expectedGeneration } }, - ) - return { notice: "The reviewed candidate is now the promoted decision model." } - } - const rejection = source.pathname.match( - new RegExp(`^${prefix}/candidates/([0-9a-f-]+)/reject$`, "i"), - ) - if (rejection?.[1]) { - const reason = form.get("reason") - await requestProductJson( - request, - `/api/repositories/${repositoryId}/decision-model/candidates/${rejection[1]}/rejection`, - decisionCandidateRejectionMutationResponseSchema, - { method: "POST", body: { reason } }, - ) - return { notice: "The candidate was rejected and remains unavailable for promotion." } - } - throw new Response("This decision-model action is not connected.", { status: 400 }) -} - function submitDecision( request: Request, repositoryId: string, @@ -275,7 +154,9 @@ function submitDecision( if (!learningId || learningId.includes("/")) { throw new Response("Invalid learning identifier.", { status: 400 }) } + const path = `/api/repositories/${repositoryId}/learnings/${encodeURIComponent(learningId)}` const decision = form.get("decision") + const title = form.get("title") const input = decision === "accept" ? { @@ -287,17 +168,26 @@ function submitDecision( ? { decision, digest: form.get("digest"), reason: form.get("reason") } : decision === "retire" ? { decision, reason: form.get("reason") } - : { decision } + : decision === "edit" + ? { + decision, + digest: form.get("digest"), + // A blank title keeps the stored one, which may be missing on older learnings. + ...(typeof title === "string" && title.trim() ? { title } : {}), + content: form.get("content"), + reason: form.get("reason"), + } + : decision === "reinstate" + ? { decision, digest: form.get("digest"), 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 }) } - return requestProductJson( - request, - `/api/repositories/${repositoryId}/learnings/${encodeURIComponent(learningId)}/decision`, - learningMutationResponseSchema, - { method: "POST", body: parsed.data }, - ) + return requestProductJson(request, `${path}/decision`, learningMutationResponseSchema, { + method: "POST", + body: parsed.data, + }) } export function meta({ loaderData }: { loaderData?: { repository: { nameWithOwner: string } } }) { @@ -324,129 +214,17 @@ function SettingsLearningsContent({ loaderData: Awaited> }) { const workspace = workspaceResponseSchema.parse(useOutletContext()) + const location = useLocation() const fetcher = useFetcher() const revalidator = useRevalidator() - const revalidateRef = useRef(revalidator.revalidate) const revalidatedResult = useRef(undefined) - const completedResult = useRef(undefined) - const loadedDecisionModel = loaderData.decisionModel - const [previousLoadedDecisionModel, setPreviousLoadedDecisionModel] = - useState(loadedDecisionModel) - const [lastAvailableDecisionModel, setLastAvailableDecisionModel] = useState< - Extract | undefined - >(loadedDecisionModel?.state === "available" ? loadedDecisionModel : undefined) - const [previousActionResult, setPreviousActionResult] = useState(fetcher.data) - const [trackedTrainingJob, setTrackedTrainingJob] = useState< - DecisionTrainingJobResponse | undefined - >(fetcher.data?.saved ? fetcher.data.trainingJob : undefined) - const [decisionModelActionRevision, setDecisionModelActionRevision] = useState(0) const busy = fetcher.state !== "idle" || revalidator.state !== "idle" const result = busy ? undefined : fetcher.data - const action = fetcher.formData?.get("_action") - const trainingSubmitting = - fetcher.state !== "idle" && - typeof action === "string" && - action.endsWith("/decision-model/training") - if (loadedDecisionModel !== previousLoadedDecisionModel) { - setPreviousLoadedDecisionModel(loadedDecisionModel) - if (loadedDecisionModel?.state === "available") { - setLastAvailableDecisionModel(loadedDecisionModel) - } - } - if (fetcher.data !== previousActionResult) { - setPreviousActionResult(fetcher.data) - if (fetcher.data?.saved && fetcher.data.trainingJob) { - setTrackedTrainingJob(fetcher.data.trainingJob) - } - } - const previousDecisionModel = - loadedDecisionModel?.state === "available" ? loadedDecisionModel : lastAvailableDecisionModel - const activeTrackedJob = - trackedTrainingJob && - ["queued", "submitting", "cancel_requested", "submitted", "running"].includes( - trackedTrainingJob.state, - ) - ? trackedTrainingJob - : undefined - const activeTrackedJobId = activeTrackedJob?.id - const transientLearningLock = - loadedDecisionModel?.state === "unavailable" && - loadedDecisionModel.error === "Another learning operation is still running." - const overviewWithTrackedJob = - previousDecisionModel && trackedTrainingJob - ? { - ...previousDecisionModel.overview, - jobs: [ - trackedTrainingJob, - ...previousDecisionModel.overview.jobs.filter( - (job) => job.id !== trackedTrainingJob.id, - ), - ], - } - : previousDecisionModel?.overview - const decisionModel: DecisionModelAvailability | null = - previousDecisionModel && - (trainingSubmitting || (transientLearningLock && activeTrackedJob)) && - (loadedDecisionModel?.state === "available" || transientLearningLock) - ? { - state: "available", - overview: overviewWithTrackedJob!, - preparationStatus: trainingSubmitting - ? "Submitting the confirmed training request. Hub is preparing its private evidence." - : `Status refresh is delayed while Hub prepares evidence. The last confirmed job state is ${activeTrackedJob?.state.replaceAll("_", " ")}.`, - } - : loadedDecisionModel?.state === "available" && overviewWithTrackedJob - ? { ...loadedDecisionModel, overview: overviewWithTrackedJob } - : loadedDecisionModel - useEffect(() => { - revalidateRef.current = revalidator.revalidate - }, [revalidator.revalidate]) useEffect(() => { if (!result?.revalidate || revalidatedResult.current === result) return revalidatedResult.current = result void revalidator.revalidate() }, [result, revalidator]) - useEffect(() => { - if (!result?.saved || completedResult.current === result) return - completedResult.current = result - setDecisionModelActionRevision((revision) => revision + 1) - }, [result]) - useEffect(() => { - if (!activeTrackedJobId) return - const delays = [750, 1_500, 3_000, 5_000] - const controller = new AbortController() - let timer: number | undefined - function schedule(attempt: number) { - timer = window.setTimeout( - () => { - void requestProductJson( - new Request(window.location.href, { signal: controller.signal }), - `/api/repositories/${loaderData.repository.id}/decision-model/training-jobs/${activeTrackedJobId}`, - decisionTrainingJobResponseSchema, - ) - .then((current) => { - setTrackedTrainingJob(current) - if (["succeeded", "failed", "cancelled"].includes(current.state)) { - void revalidateRef.current() - } else { - schedule(0) - } - }) - .catch(() => { - if (!controller.signal.aborted) { - schedule(Math.min(attempt + 1, delays.length - 1)) - } - }) - }, - delays[Math.min(attempt, delays.length - 1)], - ) - } - schedule(0) - return () => { - controller.abort() - if (timer !== undefined) window.clearTimeout(timer) - } - }, [activeTrackedJobId, loaderData.repository.id]) return ( ) 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 new file mode 100644 index 000000000..7f5349602 --- /dev/null +++ b/hub/client/application/hub/view-models/learnings-library/index.test.ts @@ -0,0 +1,160 @@ +import { describe, expect, it } from "vitest" + +import { emptyLearnings } from "@application/hub/routes/fixtures/empty-learnings" + +import { learningsLibrary } from "." + +const pathname = "/repositories/2001/learnings" +const digest = `sha256:${"a".repeat(64)}` + +describe("learningsLibrary()", () => { + it("opens on active learnings once nothing waits for a decision", () => { + const state = emptyLearnings() + state.learnings = [ + { + id: "mem_active", + title: null, + content: "Use one primary button per form.\nLabel it with the action.", + digest, + acceptedBy: "mona", + acceptedAt: "2026-10-06T15:00:00Z", + edited: false, + status: "recalled", + }, + ] + + const result = learningsLibrary(state, { pathname, search: "" }, null) + + expect(result.status).toBe("active") + expect(result.learnings).toEqual([ + expect.objectContaining({ + title: "Use one primary button per form.", + detailPath: `${pathname}?status=active&learning=mem_active`, + }), + ]) + }) + + it("searches titles and guidance and keeps the page within range", () => { + const state = emptyLearnings() + state.learnings = Array.from({ length: 30 }, (_, index) => ({ + id: `mem_${index}`, + title: index === 29 ? "Keep labels visible" : `Learning ${index}`, + content: index === 28 ? "Labels stay above fields." : "Use one primary button.", + digest, + acceptedBy: "mona", + acceptedAt: "2026-10-06T15:00:00Z", + edited: false, + status: "recalled" as const, + })) + + const firstPage = learningsLibrary(state, { pathname, search: "?status=active" }, null) + const pastTheEnd = learningsLibrary(state, { pathname, search: "?status=active&page=9" }, null) + const searched = learningsLibrary(state, { pathname, search: "?status=active&q=LABEL" }, null) + + expect(firstPage.learnings).toHaveLength(25) + expect(firstPage.pageCount).toBe(2) + expect(pastTheEnd.page).toBe(2) + expect(pastTheEnd.learnings).toHaveLength(5) + expect(pastTheEnd.returnPath).toBe(`${pathname}?status=active&page=2`) + expect(searched.learnings.map((learning) => learning.id)).toEqual(["mem_28", "mem_29"]) + expect(searched.statusPaths.rejected).toBe(`${pathname}?status=rejected&q=LABEL`) + }) + + it("shows why a learning was retired, its history, and how to accept it again", () => { + const state = emptyLearnings() + state.rejected = [ + { + id: "mem_retired", + title: "Open links in a new tab", + content: "Open every link in a new tab.", + digest, + state: "retired", + replaces: [], + decidedBy: "hubot", + decidedAt: "2026-10-08T11:00:00Z", + reason: "It breaks the back button.", + }, + ] + + const result = learningsLibrary( + state, + { pathname, search: "?status=rejected&learning=mem_retired" }, + { + decisions: [ + { + version: 1, + state: "proposed", + change: "proposed", + by: "agent:replica-learning", + at: "2026-10-07T04:07:00Z", + reason: null, + }, + { + version: 2, + state: "retired", + change: "retired", + by: "hubot", + at: "2026-10-08T11:00:00Z", + reason: "It breaks the back button.", + }, + ], + evidence: [], + otherEvidenceCount: 2, + contradictions: [], + otherContradictionsCount: 0, + }, + ) + + expect(result.selected).toMatchObject({ + facts: ["Retired by @hubot on October 8, 2026"], + reason: { heading: "Why it was retired", text: "It breaks the back button." }, + otherEvidence: "2 more evidence sources that Hub cannot show here", + history: [ + { label: "Suggested", by: null }, + { label: "Retired", by: "hubot" }, + ], + decision: { + path: `${pathname}/mem_retired/decision`, + digest, + title: "Open links in a new tab", + }, + }) + }) + + it("does not offer to accept unavailable guidance even when its digest is intact", () => { + const state = emptyLearnings() + state.rejected = [ + { + id: "mem_unavailable", + title: null, + content: null, + digest, + state: "rejected", + replaces: [], + decidedBy: null, + decidedAt: null, + reason: null, + }, + ] + const result = learningsLibrary(state, { pathname, search: "?learning=mem_unavailable" }, null) + expect(result.selected?.decision).toBeNull() + }) + + it("does not describe excluded guidance as eligible for another task", () => { + const state = emptyLearnings() + state.learnings = [ + { + id: "mem_excluded", + title: null, + content: "Use the old header.", + digest, + acceptedBy: null, + acceptedAt: null, + edited: false, + status: "not-recalled", + }, + ] + const result = learningsLibrary(state, { pathname, search: "?learning=mem_excluded" }, null) + expect(result.selected?.facts).toContain("Agents do not currently get this learning.") + }) +}) diff --git a/hub/client/application/hub/view-models/learnings-library/index.ts b/hub/client/application/hub/view-models/learnings-library/index.ts new file mode 100644 index 000000000..41decbe32 --- /dev/null +++ b/hub/client/application/hub/view-models/learnings-library/index.ts @@ -0,0 +1,280 @@ +import type { + LearningDetail, + LearningEvidence, + LearningStatus, + LearningsLibraryData, + LibraryLearning, +} from "@features/learnings-library/types" +import type { + LearningEvidenceResponse, + LearningHistoryResponse, + LearningsResponse, +} from "@application/hub/learnings-contracts/types" + +// Matches GitHub's pull request list so long lists page the way people expect. +const pageSize = 25 +const titleLength = 80 + +const changeLabels: Record = { + proposed: "Suggested", + accepted: "Accepted", + edited: "Edited", + reinstated: "Accepted again", + rejected: "Rejected", + retired: "Retired", +} + +type Overview = Extract +type LearningRecord = Omit + +function count(value: number, singular: string, plural = `${singular}s`) { + return `${value} ${value === 1 ? singular : plural}` +} + +function longDate(value: string) { + return new Intl.DateTimeFormat("en-US", { dateStyle: "long" }).format(new Date(value)) +} + +// Older learnings have no title, so the list leads with the start of their guidance. +function titleFrom(title: string | null, guidance: string) { + if (title) return title + const line = guidance.split("\n")[0]?.trim() ?? "" + return line.length > titleLength ? `${line.slice(0, titleLength - 1).trimEnd()}โ€ฆ` : line +} + +function unavailableGuidance(status: Overview["learnings"][number]["status"] | null) { + return status === "damaged" + ? "This learning's wording is unavailable because its stored record failed integrity checks." + : status === "identity-review" + ? "This version's wording is withheld until its reviewer identities are revalidated." + : "This learning's wording is not available for review." +} + +function recallFact(status: Overview["learnings"][number]["status"]) { + return status === "recalled" + ? "Agents get this learning." + : status === "budget-excluded" + ? "Eligible, but the preview's count or text limit leaves it out." + : status === "damaged" + ? "Agents do not get this learning because it failed integrity checks." + : status === "identity-review" + ? "Agents do not get this version until its reviewer identities are revalidated." + : "Agents do not currently get this learning." +} + +function evidence(items: LearningEvidenceResponse[], repositoryId: string): LearningEvidence[] { + return items.map(({ prototypeId, ...item }) => ({ + ...item, + prototypePath: `/repositories/${repositoryId}/prototypes/${prototypeId}`, + })) +} + +function detailEvidence( + source: Omit | null, + repositoryId: string, +) { + return { + evidence: evidence(source?.evidence ?? [], repositoryId), + otherEvidence: + source && source.otherEvidenceCount > 0 + ? `${count(source.otherEvidenceCount, "more evidence source")} that Hub cannot show here` + : null, + contradictions: evidence(source?.contradictions ?? [], repositoryId), + otherContradictions: + source && source.otherContradictionsCount > 0 + ? `${count(source.otherContradictionsCount, "more conflicting evidence source")} that Hub cannot show here` + : null, + } +} + +function replacements(targets: Overview["rejected"][number]["replaces"]) { + return targets.map((target) => ({ + id: target.id, + content: target.content ?? "This learning's wording is not available for review.", + })) +} + +function parseStatus(value: string | null): LearningStatus | null { + return value === "suggested" || value === "active" || value === "rejected" ? value : null +} + +/** + * Turns the Learnings overview and the address bar into one page of the library. The + * status, search and page live in the address so the back button and shared links + * work without extra page state. + */ +export function learningsLibrary( + state: Overview, + location: { pathname: string; search: string }, + history: LearningHistoryResponse | null, +): LearningsLibraryData { + const params = new URLSearchParams(location.search) + const records: LearningRecord[] = [ + ...state.suggestions.map((entry) => ({ + 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, + } + }), + ] + const counts = { + suggested: state.suggestions.length, + active: state.learnings.length, + rejected: state.rejected.length, + } + // Suggestions need a decision, so they lead until there are none. + const status = parseStatus(params.get("status")) ?? (counts.suggested ? "suggested" : "active") + const query = (params.get("q") ?? "").trim() + const needle = query.toLocaleLowerCase() + const matching = records.filter( + (record) => + record.status === status && + (!needle || + record.title.toLocaleLowerCase().includes(needle) || + record.guidance.toLocaleLowerCase().includes(needle)), + ) + const pageCount = Math.max(1, Math.ceil(matching.length / pageSize)) + const requestedPage = Number.parseInt(params.get("page") ?? "1", 10) + const page = Number.isFinite(requestedPage) ? Math.min(Math.max(requestedPage, 1), pageCount) : 1 + + function listPath(target: LearningStatus, targetPage = 1, learningId?: string) { + const next = new URLSearchParams({ status: target }) + if (query) next.set("q", query) + if (targetPage > 1) next.set("page", String(targetPage)) + if (learningId) next.set("learning", learningId) + return `${location.pathname}?${next}` + } + + const selectedId = params.get("learning") + const selected = selectedId ? records.find((record) => record.id === selectedId) : undefined + return { + status, + counts, + statusPaths: { + suggested: listPath("suggested"), + active: listPath("active"), + rejected: listPath("rejected"), + }, + query, + listPath: listPath(status), + returnPath: listPath(status, page), + page, + pageCount, + learnings: matching + .slice((page - 1) * pageSize, page * pageSize) + .map((record) => ({ ...record, detailPath: listPath(status, page, record.id) })), + selected: selected ? detail(state, selected, history) : null, + } +} + +function detail( + state: Overview, + record: LearningRecord, + history: LearningHistoryResponse | null, +): LearningDetail { + const repositoryId = state.repository.id + 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 shared = { + id: record.id, + status: record.status, + title: record.title, + guidance: record.guidance, + reason: null, + replaces: [], + ...detailEvidence(suggestion ?? history, repositoryId), + history: (history?.decisions ?? []).map((entry) => ({ + label: changeLabels[entry.change], + at: entry.at, + // Agents propose suggestions under service identities rather than GitHub logins. + by: entry.by?.includes(":") ? null : entry.by, + reason: entry.reason, + })), + } + if (record.status === "suggested" && suggestion) { + return { + ...shared, + facts: 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: "" } + : null, + } + } + const accepted = state.learnings.find((item) => item.id === record.id) + if (record.status === "active" && accepted) { + return { + ...shared, + facts: [ + ...(accepted.acceptedBy && accepted.acceptedAt + ? [ + `Accepted by @${accepted.acceptedBy} on ${longDate(accepted.acceptedAt)}${ + accepted.edited ? ", with edits" : "" + }`, + ] + : []), + recallFact(accepted.status), + ], + decision: + canDecide && accepted.digest && accepted.content !== null + ? { + path, + digest: accepted.digest, + title: accepted.title ?? "", + content: accepted.content, + } + : null, + } + } + const rejected = state.rejected.find((item) => item.id === record.id) + const verb = rejected?.state === "retired" ? "Retired" : "Rejected" + return { + ...shared, + facts: + rejected?.decidedBy && rejected.decidedAt + ? [`${verb} by @${rejected.decidedBy} on ${longDate(rejected.decidedAt)}`] + : [], + reason: rejected?.reason + ? { heading: `Why it was ${verb.toLowerCase()}`, text: rejected.reason } + : null, + replaces: replacements(rejected?.replaces ?? []), + decision: + canDecide && rejected?.digest && rejected.content !== null + ? { + path, + digest: rejected.digest, + title: rejected.title ?? "", + content: rejected.content, + } + : null, + } +} 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 4d34aba7d..89e29cc41 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 @@ -1,13 +1,12 @@ import { describe, expect, it } from "vitest" import type { WorkspaceResponse } from "@application/hub/contracts/types" -import type { DecisionModelAvailability } from "@application/hub/decision-model-contracts/types" import type { LearningsResponse } from "@application/hub/learnings-contracts/types" import { emptyLearnings } from "@application/hub/routes/fixtures/empty-learnings" import { settingsLearnings } from "." -const tasksetDigest = `sha256:${"b".repeat(64)}` +const location = { pathname: "/repositories/2001/learnings", search: "" } const repository = { id: "2001", nameWithOwner: "github/prototype", @@ -29,175 +28,6 @@ const workspace = { }, } as WorkspaceResponse -function available(): DecisionModelAvailability { - return { - state: "available", - overview: { - preflight: { - state: "ready", - counts: { - prototypes: 2, - builds: 5, - pages: 8, - screenshots: 32, - questions: 7, - samples: 43, - tasks: 43, - train: 27, - dev: 8, - test: 8, - follows: 24, - breaks: 19, - }, - warnings: [ - { - code: "missing_repeatable_reviews", - message: "Three screenshots do not have repeatable review outcomes.", - count: 3, - }, - ], - reasons: [{ code: "event-redacted", count: 2 }], - digests: { - export: `sha256:${"1".repeat(64)}`, - reviewSnapshot: `sha256:${"2".repeat(64)}`, - buildSet: `sha256:${"3".repeat(64)}`, - questionSet: `sha256:${"4".repeat(64)}`, - taskset: tasksetDigest, - }, - }, - configuration: { - enabled: true, - generation: 3, - backend: "fixture", - maxUpdates: 8, - maxSeconds: 300, - monthlyBudgetCredits: "10", - }, - jobs: [ - { - id: "11111111-2222-4333-8444-555555555555", - state: "failed", - tasksetDigest, - runtimeJobId: "runtime-job-1", - candidateRuntimeId: null, - failureCode: "runtime_unavailable", - createdAt: "2026-11-13T16:00:00Z", - finishedAt: "2026-11-13T16:05:00Z", - }, - { - id: "22222222-3333-4444-8555-666666666666", - state: "failed", - tasksetDigest, - runtimeJobId: "runtime-job-2", - candidateRuntimeId: null, - failureCode: "taskset_drift", - createdAt: "2026-11-12T16:00:00Z", - finishedAt: "2026-11-12T16:01:00Z", - }, - ], - candidates: [ - { - id: "33333333-4444-4555-8666-777777777777", - runtimeCandidateId: "fixture-candidate-2", - backend: "fixture", - tasksetDigest, - productionEligible: true, - baselineMeanReward: "0.55", - candidateMeanReward: "0.73", - meanRewardDelta: "0.18", - baselineCalibrationError: "0.20", - candidateCalibrationError: "0.17", - calibrationErrorDelta: "-0.03", - learningMetrics: [ - { - learningId: "learning-gain", - baselineBalancedAccuracy: 0.5, - candidateBalancedAccuracy: 0.75, - delta: 0.25, - direction: "gain", - }, - ], - durationSeconds: 270, - usage: [ - { - connector: "customer-gpu", - kind: "training_credits", - quantity: 3.5, - unit: "credits", - cost: 1.25, - currency: "USD", - source: "runtime", - metadata: {}, - }, - ], - rejection: null, - createdAt: "2026-11-11T18:04:30Z", - }, - ], - promotion: null, - promotionHistory: [], - evaluationBuilds: [ - { - id: "77777777-8888-4999-8aaa-bbbbbbbbbbbb", - number: 42, - prototype: { - id: "1", - name: "Settings", - branchName: "settings", - }, - }, - ], - evaluations: [ - { - id: "44444444-5555-4666-8777-888888888888", - build: { - id: "55555555-6666-4777-8888-999999999999", - number: 3, - prototypeId: "1", - }, - model: { - id: "33333333-4444-4555-8666-777777777777", - runtimeCandidateId: "fixture-candidate-2", - generation: 3, - }, - questionDigest: `sha256:${"4".repeat(64)}`, - screenshotSetDigest: `sha256:${"5".repeat(64)}`, - responseDigest: `sha256:${"6".repeat(64)}`, - findingsAvailable: true, - findings: [ - { - learning: { id: "learning-gain", text: null }, - route: "/settings", - views: [{ viewport: "desktop", theme: "dark" }], - followsProbability: 0.75, - breaksProbability: 0.25, - explanation: "The deleted learning text remains private.", - }, - ], - createdAt: "2026-11-14T16:00:00Z", - }, - ], - deletions: [ - { - id: "66666666-7777-4888-8999-aaaaaaaaaaaa", - state: "pending", - selectors: { - exportId: "export-1", - grantId: "grant-1", - evidenceDigest: `sha256:${"7".repeat(64)}`, - tasksetDigest, - }, - pending: 2, - failures: 0, - revokedAt: "2026-11-14T17:00:00Z", - completedAt: null, - failureCode: null, - }, - ], - }, - } -} - function mockState(administerHub: boolean) { return { workspace, @@ -211,7 +41,7 @@ describe("settingsLearnings()", () => { const message = "Rebuild the learning because its review evidence was removed." const state = { ...administrator.learnings, loadError: message } - const result = settingsLearnings(administrator.workspace, state, null) + const result = settingsLearnings(administrator.workspace, state, location, null) expect(result.accessDenied).toBe(false) if (result.accessDenied) throw new Error("The administrator must receive Learnings.") @@ -226,24 +56,50 @@ describe("settingsLearnings()", () => { permissions: { viewEvidence: true, decide: true, requestRun: true }, copilot: { state: "connected", connectedBy: null }, automaticRunsEnabled: false, + solo: false, + localLearningSetupNeeded: false, + activity: [], + today: "2026-11-10", usageCredits: "0", runAvailable: true, loadError: null, identityReviewCount: 0, suggestions: [], learnings: [], + rejected: [], recall: { text: "", count: 0 }, runs: [], } - const result = settingsLearnings(workspace, state, null) + const result = settingsLearnings(workspace, state, location, null) expect(result.accessDenied).toBe(false) if (result.accessDenied) throw new Error("Expected repository learning access.") - expect(result.canDecide).toBe(true) - expect(result.run.available).toBe(true) + expect(result.run).toEqual({ path: "/repositories/2001/learnings/runs" }) expect(result.administrationLinks).toEqual([]) - expect(result.decisionModel.state).toBe("repository-learning-only") + }) + + it("maps Solo activity to runs started by your agent", () => { + const state = mockState(false) + const activity = { + date: "2026-11-18", + runState: "succeeded" as const, + startedAt: "2026-11-18T16:30:00Z", + startedBy: { type: "agent" as const }, + commentsAnalyzed: 3, + commentsTagged: 2, + suggestions: 1, + } + + const result = settingsLearnings( + state.workspace, + { ...state.learnings, solo: true, activity: [activity] }, + location, + null, + ) + + if (result.accessDenied) throw new Error("Expected repository learning access.") + expect(result.activity).toEqual([{ ...activity, startedBy: "your agent" }]) }) it("keeps Hub administration navigation for a denied repository", () => { @@ -253,76 +109,25 @@ describe("settingsLearnings()", () => { capabilities: { administerHub: true, administerRepository: false }, } - const result = settingsLearnings(workspace, state, null) + const result = settingsLearnings(workspace, state, location, null) expect(result.accessDenied).toBe(true) expect(result.administrationLinks).not.toEqual([]) - expect(result).not.toHaveProperty("canDecide") + expect(result).not.toHaveProperty("library") expect(result).not.toHaveProperty("run") }) - it("keeps repository learning authority separate from Hub administrator authority", () => { - const repositoryAdministrator = mockState(false) - const repositoryData = settingsLearnings( - repositoryAdministrator.workspace, - repositoryAdministrator.learnings, - available(), - ) - - expect(repositoryData.accessDenied).toBe(false) - if (repositoryData.accessDenied) throw new Error("Repository learnings must remain available.") - expect(repositoryData.decisionModel.state).toBe("repository-learning-only") - - const hubAdministrator = mockState(true) - const hubData = settingsLearnings(hubAdministrator.workspace, hubAdministrator.learnings, { - state: "not-configured", - }) - expect(hubData.accessDenied).toBe(false) - if (hubData.accessDenied) throw new Error("The Hub administrator must receive Learnings.") - expect(hubData.decisionModel.state).toBe("not-configured") - }) - - it("maps authoritative evidence, privacy, and deletion state", () => { - const administrator = mockState(true) - const data = settingsLearnings(administrator.workspace, administrator.learnings, available()) + it("keeps an explicit run available when Hub has daily runs", () => { + const state = mockState(false) - expect(data.accessDenied).toBe(false) - if (data.accessDenied || data.decisionModel.state !== "available") { - throw new Error("The configured administrator must receive decision-model controls.") - } - expect(data.decisionModel.readiness.evidence).toMatch( - /2 prototypes, 5 Builds, 8 pages, 32 screenshots, 7 questions, and 43 samples/, - ) - expect(data.decisionModel.readiness.evidence).toMatch( - /reserves 8 development and 8 test tasks from the 27 training tasks/, + const result = settingsLearnings( + state.workspace, + { ...state.learnings, automaticRunsEnabled: true }, + location, + null, ) - expect(data.decisionModel.readiness.blockedReasons).toEqual([]) - expect(data.decisionModel.jobs.map((job) => job.failureKind)).toEqual(["retryable", "terminal"]) - expect(data.decisionModel.candidates[0]).toMatchObject({ - baselineMeanReward: "0.55", - candidateMeanReward: "0.73", - meanRewardChange: "+0.18 (improved)", - duration: "4 minutes 30 seconds", - usage: ["customer-gpu: 3.5 credits, $1.25"], - }) - expect(data.decisionModel.evaluationBuilds).toEqual([ - { - id: "77777777-8888-4999-8aaa-bbbbbbbbbbbb", - number: 42, - label: "Settings โ€” Build 42", - evaluationPath: - "/repositories/2001/learnings/decision-model/builds/77777777-8888-4999-8aaa-bbbbbbbbbbbb/evaluate", - }, - ]) - expect(data.decisionModel.evaluations[0]?.findings[0]).toMatchObject({ - learningId: "learning-gain", - learningText: null, - }) - expect(data.decisionModel.deletions).toEqual([ - expect.objectContaining({ - state: "pending", - summary: "2 pending runtime deletion items; 0 failures.", - }), - ]) + + if (result.accessDenied) throw new Error("Expected repository learning access.") + expect(result.run).toEqual({ path: "/repositories/2001/learnings/runs" }) }) }) 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 7753f42bd..a7060bd8c 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.ts @@ -1,258 +1,19 @@ import type { LearningsPageData } from "@pages/learnings-page/types" -import type { DecisionModelPanelData } from "@features/decision-model-panel/types" import type { WorkspaceResponse } from "@application/hub/contracts/types" -import type { DecisionModelAvailability } from "@application/hub/decision-model-contracts/types" -import type { LearningsResponse } from "@application/hub/learnings-contracts/types" +import type { + LearningHistoryResponse, + LearningsResponse, +} from "@application/hub/learnings-contracts/types" +import type { LearningActivityDay } from "@features/learning-activity-grid/types" +import { learningsLibrary } from "../learnings-library" import { repositoryWorkspace } from "../repository-workspace" -function formatCredits(value: string) { - return `${value} AI ${value === "1" ? "credit" : "credits"}` -} - -function formatCount(value: number, singular: string, plural = `${singular}s`) { - return `${value} ${value === 1 ? singular : plural}` -} - -function formatSignedChange(value: string | null, improvementWhenNegative = false) { - if (value === null) return "Not reported" - const amount = Number(value) - const signed = new Intl.NumberFormat("en-US", { - maximumFractionDigits: 4, - signDisplay: "always", - }).format(amount) - const improved = improvementWhenNegative ? amount < 0 : amount > 0 - const regressed = improvementWhenNegative ? amount > 0 : amount < 0 - return `${signed}${improved ? " (improved)" : regressed ? " (regressed)" : " (unchanged)"}` -} - -function formatMetric(value: string | null) { - return value === null - ? "Not reported" - : new Intl.NumberFormat("en-US", { maximumFractionDigits: 4 }).format(Number(value)) -} - -function formatPercentage(value: number | null) { - return value === null - ? "Not reported" - : new Intl.NumberFormat("en-US", { - style: "percent", - maximumFractionDigits: 1, - }).format(value) -} - -function formatDuration(seconds: number | null) { - if (seconds === null) return "Not reported" - if (seconds < 60) return `${seconds} seconds` - const minutes = Math.floor(seconds / 60) - const remainder = Math.round(seconds % 60) - return remainder ? `${minutes} minutes ${remainder} seconds` : `${minutes} minutes` -} - -function decisionModelData( - repositoryId: string, - state: Extract, - availability: DecisionModelAvailability | null, -): DecisionModelPanelData { - if (!state.capabilities.administerHub) { - return { - state: "repository-learning-only", - message: - "You can manage this repository's accepted learnings, but decision-model training currently requires separate Hub administrator authority.", - } - } - if (!availability || availability.state === "not-configured") { - return { - state: "not-configured", - message: "Decision-model training is not configured for this Hub.", - setupGuidance: - "A Hub operator must configure the customer-run decision runtime, private learning storage, and artifact storage before repository administrators can opt in.", - } - } - if (availability.state === "unavailable") { - return { - state: "unavailable", - message: `Decision-model training is temporarily unavailable: ${availability.error}`, - setupGuidance: - "Check the customer-run decision runtime and private evidence stores, then reload this page. Existing accepted learnings remain available to agents.", - } - } - const overview = availability.overview - const activeJob = - overview.jobs.find((job) => - ["queued", "submitting", "cancel_requested", "submitted", "running"].includes(job.state), - ) ?? null - const jobs = overview.jobs.map((job) => { - const retryableCodes = new Set([ - "polling_deadline_exceeded", - "rate_limited", - "runtime_unavailable", - "timeout", - ]) - const failed = job.state === "failed" - return { - id: job.id, - state: job.state, - stateLabel: - job.state === "queued" - ? "Queued" - : job.state === "submitting" - ? "Submitting" - : job.state === "cancel_requested" - ? "Cancelling" - : job.state === "submitted" - ? "Submitted" - : job.state === "running" - ? "Running" - : job.state === "succeeded" - ? "Finished" - : job.state === "cancelled" - ? "Cancelled" - : "Failed", - createdAt: job.createdAt, - finishedAt: job.finishedAt, - tasksetDigest: job.tasksetDigest, - failure: failed - ? job.failureCode - ? `Training stopped with ${job.failureCode.replaceAll("_", " ")}.` - : "Training stopped without a failure code." - : null, - failureKind: failed - ? job.failureCode && retryableCodes.has(job.failureCode) - ? ("retryable" as const) - : ("terminal" as const) - : null, - cancelPath: `/repositories/${repositoryId}/learnings/decision-model/training/${job.id}/cancel`, - cancellable: ["queued", "submitting", "submitted", "running"].includes(job.state), - } - }) - const promotion = overview.promotion - const counts = overview.preflight.counts - return { - state: "available", - settingsPath: `/repositories/${repositoryId}/learnings/decision-model/settings`, - trainingPath: `/repositories/${repositoryId}/learnings/decision-model/training`, - rollbackPath: `/repositories/${repositoryId}/learnings/decision-model/rollback`, - configuration: overview.configuration, - readiness: { - runtime: - overview.preflight.state === "blocked" - ? "Training is blocked until the listed evidence requirements are resolved." - : overview.configuration?.enabled - ? "Hub can prepare and submit a bounded training job." - : overview.configuration - ? "Training is paused for this repository." - : "Choose bounded settings and opt in before training.", - evidence: `${formatCount(counts.prototypes, "prototype")}, ${formatCount(counts.builds, "Build")}, ${formatCount(counts.pages, "page")}, ${formatCount(counts.screenshots, "screenshot")}, ${formatCount(counts.questions, "question")}, and ${formatCount(counts.samples, "sample")} are covered. The split reserves ${counts.dev} development and ${counts.test} test tasks from the ${counts.train} training tasks, with ${counts.follows} follows and ${counts.breaks} breaks answers.`, - latestTasksetDigest: - overview.preflight.digests.taskset ?? overview.jobs[0]?.tasksetDigest ?? null, - warnings: overview.preflight.warnings.map((warning) => - warning.count === undefined ? warning.message : `${warning.message} (${warning.count})`, - ), - blockedReasons: - overview.preflight.state === "blocked" - ? overview.preflight.reasons.map( - (reason) => `${reason.code.replaceAll("_", " ")} (${reason.count})`, - ) - : [], - }, - trainingAvailable: Boolean( - overview.configuration?.enabled && - overview.preflight.state === "ready" && - !activeJob && - !availability.preparationStatus, - ), - preparationStatus: availability.preparationStatus ?? null, - activeJob: activeJob ? (jobs.find((job) => job.id === activeJob.id) ?? null) : null, - jobs, - candidates: overview.candidates.map((candidate) => ({ - id: candidate.id, - runtimeCandidateId: candidate.runtimeCandidateId, - backend: candidate.backend, - createdAt: candidate.createdAt, - productionEligible: candidate.productionEligible, - tasksetDigest: candidate.tasksetDigest, - baselineMeanReward: formatMetric(candidate.baselineMeanReward), - candidateMeanReward: formatMetric(candidate.candidateMeanReward), - meanRewardChange: formatSignedChange(candidate.meanRewardDelta), - baselineCalibrationError: formatMetric(candidate.baselineCalibrationError), - candidateCalibrationError: formatMetric(candidate.candidateCalibrationError), - calibrationErrorChange: formatSignedChange(candidate.calibrationErrorDelta, true), - learningMetrics: candidate.learningMetrics.map((metric) => ({ - learningId: metric.learningId, - baseline: formatPercentage(metric.baselineBalancedAccuracy), - candidate: formatPercentage(metric.candidateBalancedAccuracy), - change: - metric.delta === null - ? "Not reported" - : new Intl.NumberFormat("en-US", { - style: "percent", - maximumFractionDigits: 1, - signDisplay: "always", - }).format(metric.delta), - direction: metric.direction, - })), - duration: formatDuration(candidate.durationSeconds), - usage: candidate.usage.map((usage) => { - const quantity = `${usage.quantity} ${usage.unit}` - const cost = - usage.cost === null || usage.currency === null - ? "cost not reported" - : new Intl.NumberFormat("en-US", { - style: "currency", - currency: usage.currency, - }).format(usage.cost) - return `${usage.connector}: ${quantity}, ${cost}` - }), - rejection: candidate.rejection - ? { rejectedAt: candidate.rejection.rejectedAt, reason: candidate.rejection.reason } - : null, - promoted: candidate.id === promotion?.candidateId, - promotePath: `/repositories/${repositoryId}/learnings/decision-model/candidates/${candidate.id}/promote`, - rejectPath: `/repositories/${repositoryId}/learnings/decision-model/candidates/${candidate.id}/reject`, - })), - promotion, - evaluationBuilds: overview.evaluationBuilds.map((build) => ({ - id: build.id, - number: build.number, - label: `${build.prototype.name ?? build.prototype.branchName} โ€” Build ${build.number}`, - evaluationPath: `/repositories/${repositoryId}/learnings/decision-model/builds/${build.id}/evaluate`, - })), - evaluations: overview.evaluations.map((evaluation) => ({ - id: evaluation.id, - buildNumber: evaluation.build.number, - prototypePath: `/repositories/${repositoryId}/prototypes/${evaluation.build.prototypeId}?build=${evaluation.build.number}`, - runtimeCandidateId: evaluation.model.runtimeCandidateId, - generation: evaluation.model.generation, - createdAt: evaluation.createdAt, - findingsAvailable: evaluation.findingsAvailable, - findings: evaluation.findings.map((finding) => ({ - learningId: finding.learning.id, - learningText: finding.learning.text, - route: finding.route, - views: finding.views - .map(({ viewport, theme }) => `${viewport} viewport, ${theme} theme`) - .join("; "), - followsProbability: formatPercentage(finding.followsProbability), - breaksProbability: formatPercentage(finding.breaksProbability), - explanation: finding.explanation, - })), - })), - deletions: overview.deletions.map((deletion) => ({ - id: deletion.id, - state: deletion.state, - summary: `${deletion.pending} pending runtime deletion ${deletion.pending === 1 ? "item" : "items"}; ${deletion.failures} ${deletion.failures === 1 ? "failure" : "failures"}.`, - failure: deletion.failureCode - ? `Deletion stopped with ${deletion.failureCode.replaceAll("_", " ")}.` - : null, - })), - } -} - export function settingsLearnings( workspace: WorkspaceResponse, state: LearningsResponse, - decisionModel: DecisionModelAvailability | null, + location: { pathname: string; search: string }, + history: LearningHistoryResponse | null, ): LearningsPageData { const repository = state.repository const repositoryId = state.repository.id @@ -274,9 +35,9 @@ export function settingsLearnings( accessDeniedLabel: "You do not have permission to view this repository's learnings.", } if (state.accessDenied) return { ...shared, accessDenied: true } - const pending = state.runs.find((run) => run.state === "queued" || run.state === "running") - const statusMessage = - state.copilot.state === "not-connected" + const copilotWarning = state.solo + ? null + : state.copilot.state === "not-connected" ? "Learnings stays off until a Hub administrator connects Copilot." : state.copilot.state === "refused" ? `Copilot refused Hub's Copilot token${ @@ -286,180 +47,72 @@ 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.` - : state.automaticRunsEnabled - ? `Hub looks for learnings once a day when there are new comments${ - state.copilot.connectedBy - ? `, using the Copilot connection @${state.copilot.connectedBy} made` - : "" - }.` - : "Hub looks for learnings when you choose Find learnings now." + : null + const activity: LearningActivityDay[] = state.activity.map(({ startedBy, ...day }) => ({ + ...day, + startedBy: startedBy.type === "agent" ? "your agent" : null, + })) return { ...shared, accessDenied: false, - canDecide: state.permissions.decide, - copy: { - heading: "Learnings", - description: - "Hub reads this repository's prototype review comments, asks Copilot which points keep coming up, and suggests learnings. Agents that build prototypes here get the learnings you accept.", - runLabel: "Find learnings now", - suggestionsHeading: "Suggestions", - suggestionsEmpty: - "No suggestions yet. Hub suggests a learning when at least two reviewers raise the same point on two prototypes.", - evidenceHeading: "What reviewers said", - contradictionsHeading: "What reviewers disagreed with", - replacementHeading: "Accepting this replaces the guidance listed below.", - deletedComment: "The author deleted this comment.", - accept: "Accept", - edit: "Edit and accept", - contentLabel: "Wording agents get", - acceptEdited: "Accept with this wording", - reject: "Reject", - rejectReason: "Why reject this suggestion?", - confirmReject: "Reject suggestion", - cancel: "Cancel", - acceptedHeading: "Accepted learnings", - acceptedEmpty: "No accepted learnings yet.", - retire: "Retire", - retireReason: "Why retire this learning?", - confirmRetire: "Retire learning", - recallHeading: "What an agent gets", - recallDescription: - "This preview shows the default learnings within the count and text limits. An agent's task can change their order and which ones fit.", - recallEmpty: "Agents get nothing yet. Accept a suggestion to share it with agents.", - runsHeading: "Recent runs", - runsEmpty: "Hub has not looked for learnings in this repository yet.", - runColumns: { - started: "Started", - startedBy: "Started by", - result: "Result", - usage: "Copilot usage", - }, - }, - status: { - message: statusMessage, - refused: state.copilot.state !== "connected", - activity: - pending?.state === "running" - ? "Hub is looking for learnings now." - : pending - ? "Hub will look for learnings shortly." - : null, - usage: `Copilot used ${formatCredits(state.usageCredits)} for this repository in the last 30 days.`, - }, - run: { - path: `/repositories/${repositoryId}/learnings/runs`, - available: state.permissions.requestRun && state.runAvailable, - }, + copilotWarning, + 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." + : null, + localLearningSetupCommand: state.localLearningSetupNeeded + ? "node /packages/learning/bin/replica-learning.mjs setup" + : null, + activity, + today: state.today, + agentsPath: null, + evaluationsPath: 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, + })), + } + : null, loadError: state.loadError, identityNotice: state.identityReviewCount > 0 - ? "Earlier suggestions or accepted learnings need identity revalidation. Hub keeps their history, but agents cannot use those versions. Find learnings again, then review any rebuilt suggestions." - : null, - suggestions: state.suggestions.map((entry) => ({ - id: entry.id, - content: entry.content, - digest: entry.reviewDigest, - decisionPath: `/repositories/${repositoryId}/learnings/${encodeURIComponent(entry.id)}/decision`, - support: entry.support - ? `Raised by ${formatCount(entry.support.reviewers, "reviewer")} on ${formatCount( - entry.support.prototypes, - "prototype", - )}` + ? "Earlier suggestions or accepted learnings need identity revalidation. Hub keeps their history, but agents cannot use those versions. Review any suggestions Hub rebuilds the next time it looks for learnings." : null, - replaces: entry.replaces.map((target) => ({ - id: target.id, - content: target.content ?? "This learning's wording is not available for review.", - })), - evidence: entry.evidence.map((item) => ({ - ...item, - prototypePath: `/repositories/${repositoryId}/prototypes/${item.prototypeId}`, - })), - otherEvidence: - entry.otherEvidenceCount > 0 - ? `${formatCount(entry.otherEvidenceCount, "more comment")} that Hub cannot show here` - : null, - contradictions: entry.contradictions.map((item) => ({ - ...item, - prototypePath: `/repositories/${repositoryId}/prototypes/${item.prototypeId}`, - })), - otherContradictions: - entry.otherContradictionsCount > 0 - ? `${formatCount(entry.otherContradictionsCount, "more opposing comment")} that Hub cannot show here` - : null, - })), - learnings: state.learnings.map((entry) => ({ - id: entry.id, - content: - entry.content ?? - (entry.status === "damaged" - ? "This learning's wording is unavailable because its stored record failed integrity checks." - : entry.status === "identity-review" - ? "This version's wording is withheld until its reviewer identities are revalidated." - : "This learning's wording is not available for review."), - decisionPath: `/repositories/${repositoryId}/learnings/${encodeURIComponent(entry.id)}/decision`, - accepted: - entry.acceptedBy && entry.acceptedAt - ? `Accepted by @${entry.acceptedBy} on ${new Intl.DateTimeFormat("en-US", { - dateStyle: "long", - }).format(new Date(entry.acceptedAt))}${entry.edited ? ", with edits" : ""}` - : null, - recalled: entry.status === "recalled", - status: - entry.status === "recalled" - ? "This learning is included in the preview below." - : entry.status === "budget-excluded" - ? "This learning is eligible, but the preview's count or text limit leaves it out. An agent's task can change which learnings fit." - : entry.status === "damaged" - ? "This learning failed the store's integrity checks, so agents do not get it. An operator can run replica-learning verify." - : entry.status === "identity-review" - ? "Reviewer identities need revalidation, so agents cannot use this version until its evidence is rebuilt and reviewed." - : "This learning is eligible, but an agent's task can change its order and whether it fits.", - })), - recall: state.recall, - runs: state.runs.map((run) => ({ - id: run.id, - startedAt: run.startedAt, - startedBy: - run.startedBy.type === "daily" - ? "Daily" - : run.startedBy.type === "user" - ? `@${run.startedBy.login}` - : "Someone", - state: run.state, - stateLabel: - run.state === "succeeded" - ? "Finished" - : run.state === "failed" - ? "Failed" - : run.state === "running" - ? "Running" - : "Waiting", - result: - run.result?.type === "failed" - ? run.result.summary - : run.result - ? [ - formatCount(run.result.commentsConsidered, "new comment"), - ...(run.result.commentsConsidered > 0 - ? [formatCount(run.result.commentsLabeled, "labeled", "labeled")] - : []), - formatCount(run.result.suggestions, "new suggestion"), - ...(run.result.commentsRemaining > 0 - ? [ - `${formatCount(run.result.commentsRemaining, "comment")} left for the next run`, - ] - : []), - ...(run.result.suggestionsRemaining > 0 - ? [ - `${formatCount(run.result.suggestionsRemaining, "suggestion")} left for the next run`, - ] - : []), - ].join(", ") - : null, - usage: run.usage - ? `${formatCredits(run.usage.credits)} in ${formatCount(run.usage.requests, "request")}` - : "None", - })), - decisionModel: decisionModelData(repositoryId, state, decisionModel), + library: learningsLibrary(state, location, history), } } diff --git a/hub/client/features/decision-model-panel/index.test.tsx b/hub/client/features/decision-model-panel/index.test.tsx deleted file mode 100644 index 95b6595e8..000000000 --- a/hub/client/features/decision-model-panel/index.test.tsx +++ /dev/null @@ -1,405 +0,0 @@ -import { ThemeProvider } from "@primer/react-brand" -import { fireEvent, render, screen, waitFor, within } from "@testing-library/react" -import { describe, expect, it } from "vitest" - -import { DecisionModelPanel } from "." -import type { DecisionModelPanelData } from "./types" - -const tasksetDigest = `sha256:${"b".repeat(64)}` - -function available(): Extract { - return { - state: "available", - settingsPath: "/repositories/2001/learnings/decision-model/settings", - trainingPath: "/repositories/2001/learnings/decision-model/training", - rollbackPath: "/repositories/2001/learnings/decision-model/rollback", - configuration: { - enabled: true, - generation: 3, - backend: "fixture", - maxUpdates: 8, - maxSeconds: 300, - monthlyBudgetCredits: "10", - }, - readiness: { - runtime: "Hub can prepare and submit a bounded training job.", - evidence: - "3 prototypes, 8 Builds, 12 pages, 48 screenshots, 6 questions, and 96 samples are covered.", - latestTasksetDigest: tasksetDigest, - warnings: [], - blockedReasons: [], - }, - trainingAvailable: true, - activeJob: null, - jobs: [], - candidates: [ - { - id: "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee", - runtimeCandidateId: "fixture-candidate-2", - backend: "fixture", - createdAt: "2026-11-11T18:04:30Z", - productionEligible: true, - tasksetDigest, - baselineMeanReward: "0.55", - candidateMeanReward: "0.73", - meanRewardChange: "+0.18 (improved)", - baselineCalibrationError: "0.2", - candidateCalibrationError: "0.17", - calibrationErrorChange: "-0.03 (improved)", - learningMetrics: [ - { - learningId: "learning-1", - baseline: "50%", - candidate: "75%", - change: "+25%", - direction: "gain", - }, - ], - duration: "4 minutes 30 seconds", - usage: ["fixture-runtime: 3.5 credits, $1.25"], - rejection: null, - promoted: false, - promotePath: - "/repositories/2001/learnings/decision-model/candidates/aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee/promote", - rejectPath: - "/repositories/2001/learnings/decision-model/candidates/aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee/reject", - }, - ], - promotion: { - candidateId: "ffffffff-1111-4222-8333-444444444444", - runtimeCandidateId: "fixture-candidate-1", - generation: 2, - operation: "promote", - rollbackAvailable: true, - }, - evaluationBuilds: [ - { - id: "bbbbbbbb-cccc-4ddd-8eee-ffffffffffff", - number: 42, - label: "Settings โ€” Build 42", - evaluationPath: - "/repositories/2001/learnings/decision-model/builds/bbbbbbbb-cccc-4ddd-8eee-ffffffffffff/evaluate", - }, - ], - evaluations: [ - { - id: "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", - buildNumber: 42, - prototypePath: "/repositories/2001/prototypes/1?build=3", - runtimeCandidateId: "fixture-candidate-1", - generation: 2, - createdAt: "2026-11-12T20:00:00Z", - findingsAvailable: true, - findings: [ - { - learningId: "learning-1", - learningText: null, - route: "/settings/profile", - views: "desktop viewport, dark theme", - followsProbability: "82%", - breaksProbability: "18%", - explanation: "The accepted learning text was removed.", - }, - ], - }, - ], - deletions: [ - { - id: "dddddddd-dddd-4ddd-8ddd-dddddddddddd", - state: "pending", - summary: "2 pending runtime deletion items; 0 failures.", - failure: null, - }, - ], - } -} - -function renderPanel(data: DecisionModelPanelData) { - return render( - - - , - ) -} - -describe("DecisionModelPanel()", () => { - it("explains runtime setup and separate administrator authority without exposing controls", () => { - renderPanel({ - state: "not-configured", - message: "Decision-model training is not configured for this Hub.", - setupGuidance: "Configure the customer-run decision runtime.", - }) - expect(screen.getByText(/not configured for this Hub/)).toBeVisible() - expect(screen.queryByRole("button")).not.toBeInTheDocument() - - renderPanel({ - state: "repository-learning-only", - message: "Decision-model training requires separate Hub administrator authority.", - }) - expect(screen.getByText(/separate Hub administrator authority/)).toBeVisible() - - renderPanel({ - state: "unavailable", - message: "Decision-model training is temporarily unavailable.", - setupGuidance: "Existing accepted learnings remain available to agents.", - }) - expect(screen.getByText(/temporarily unavailable/)).toBeVisible() - }) - - it("exposes bounded settings and confirms the exact observed generation before training", () => { - renderPanel(available()) - expect(screen.getByRole("checkbox", { name: "Repository training" })).toBeChecked() - fireEvent.click(screen.getByRole("button", { name: "Start training" })) - const confirm = screen.getByRole("button", { name: "Queue this training job" }) - const form = confirm.closest("form") - expect( - (form?.querySelector('[name="idempotencyKey"]') as HTMLInputElement | null)?.value, - ).toMatch(/^hub-ui-/) - expect(form?.querySelector('[name="expectedConfigurationGeneration"]')).toHaveValue("3") - expect(confirm).toHaveFocus() - expect(screen.getByText(/capped at 8 updates, 5 minutes, and 10 credits/)).toBeVisible() - expect( - screen.getByText( - "The next click queues this job. It does not promote the resulting candidate.", - ), - ).toBeVisible() - }) - - it.each(["queued", "submitting", "submitted", "running"] as const)( - "allows %s training to be cancelled", - (state) => { - const data = available() - const job = { - id: "11111111-2222-4333-8444-555555555555", - state, - stateLabel: state, - createdAt: "2026-11-12T16:00:00Z", - finishedAt: null, - tasksetDigest, - failure: null, - failureKind: null, - cancelPath: - "/repositories/2001/learnings/decision-model/training/11111111-2222-4333-8444-555555555555/cancel", - cancellable: true, - } - renderPanel({ ...data, trainingAvailable: false, activeJob: job, jobs: [job] }) - expect(screen.getByRole("button", { name: "Cancel training" })).toBeVisible() - }, - ) - - it("labels retryable and terminal failures separately", () => { - const data = available() - renderPanel({ - ...data, - jobs: [ - { - id: "11111111-2222-4333-8444-555555555555", - state: "failed", - stateLabel: "Failed", - createdAt: "2026-11-13T16:00:00Z", - finishedAt: "2026-11-13T16:05:00Z", - tasksetDigest, - failure: "Training stopped with runtime unavailable.", - failureKind: "retryable", - cancelPath: "", - cancellable: false, - }, - { - id: "22222222-3333-4444-8555-666666666666", - state: "failed", - stateLabel: "Failed", - createdAt: "2026-11-12T16:00:00Z", - finishedAt: "2026-11-12T16:01:00Z", - tasksetDigest, - failure: "Training stopped with taskset drift.", - failureKind: "terminal", - cancelPath: "", - cancellable: false, - }, - ], - }) - const history = screen.getByRole("region", { name: "Decision-model training history" }) - expect(within(history).getByText(/runtime unavailable.*Retryable/)).toBeVisible() - expect(within(history).getByText(/taskset drift.*Terminal/)).toBeVisible() - }) - - it("shows blockers only for a blocked preflight", () => { - const data = available() - renderPanel({ - ...data, - trainingAvailable: false, - readiness: { - ...data.readiness, - runtime: "Training is blocked until evidence requirements are resolved.", - blockedReasons: ["insufficient test tasks (4)"], - warnings: ["Three screenshots lack repeatable review outcomes. (3)"], - }, - }) - expect(screen.getByText(/insufficient test tasks/)).toBeVisible() - expect(screen.queryByRole("button", { name: "Start training" })).not.toBeInTheDocument() - }) - - it("shows privacy-safe findings and runtime deletion status", () => { - renderPanel(available()) - const comparison = screen.getByRole("region", { - name: "Held-out comparison for fixture-candidate-2", - }) - expect(within(comparison).getByText("+0.18 (improved)")).toBeVisible() - expect(within(comparison).getByRole("region", { name: "Per-learning gains" })).toHaveAttribute( - "tabindex", - "0", - ) - expect( - screen.getByText("The accepted learning text was removed after this evaluation."), - ).toBeVisible() - expect(screen.getByText("Deletion pending")).toBeVisible() - expect(screen.getByText("2 pending runtime deletion items; 0 failures.")).toBeVisible() - }) - - it("allows explicit fixture promotion without relaxing non-fixture eligibility", () => { - const fixture = available() - const ineligibleCandidate = { ...fixture.candidates[0]!, productionEligible: false } - const { rerender } = renderPanel({ ...fixture, candidates: [ineligibleCandidate] }) - const fixtureCandidate = screen.getByRole("article", { - name: "Candidate fixture-candidate-2", - }) - - expect(within(fixtureCandidate).getByText("Development only")).toBeVisible() - expect( - within(fixtureCandidate).getByRole("button", { name: "Promote candidate" }), - ).toBeVisible() - - rerender( - - - , - ) - const customerRuntimeCandidate = screen.getByRole("article", { - name: "Candidate fixture-candidate-2", - }) - expect(within(customerRuntimeCandidate).getByText("Not eligible")).toBeVisible() - expect( - within(customerRuntimeCandidate).queryByRole("button", { name: "Promote candidate" }), - ).not.toBeInTheDocument() - }) - - it("offers an eligible successful Build for evaluation through a form action", () => { - renderPanel(available()) - - const evaluate = screen.getByRole("button", { name: "Evaluate Settings โ€” Build 42" }) - const form = evaluate.closest("form") - expect(form).toHaveAttribute( - "action", - "/repositories/2001/learnings/decision-model/builds/bbbbbbbb-cccc-4ddd-8eee-ffffffffffff/evaluate", - ) - expect(form).toHaveAttribute("method", "post") - expect(form?.querySelector('[name="authenticity_token"]')).toHaveValue("csrf-token") - }) - - it.each([ - { - label: "no promoted model", - change: (data: ReturnType) => ({ ...data, promotion: null }), - }, - { - label: "no eligible successful Builds", - change: (data: ReturnType) => ({ ...data, evaluationBuilds: [] }), - }, - ])("does not offer Build evaluation with $label", ({ change }) => { - renderPanel(change(available())) - - expect( - screen.queryByRole("button", { name: /^Evaluate .+ โ€” Build \d+$/ }), - ).not.toBeInTheDocument() - }) - - it("restores focus when promotion and rejection confirmations are cancelled", async () => { - renderPanel(available()) - const promote = screen.getByRole("button", { name: "Promote candidate" }) - fireEvent.click(promote) - expect(screen.getByRole("button", { name: "Confirm promotion" })).toHaveFocus() - fireEvent.click(screen.getByRole("button", { name: "Cancel" })) - await waitFor(() => - expect(screen.getByRole("button", { name: "Promote candidate" })).toHaveFocus(), - ) - - const reject = screen.getByRole("button", { name: "Reject candidate" }) - fireEvent.click(reject) - expect(screen.getByRole("textbox", { name: "Why reject this candidate?" })).toHaveFocus() - fireEvent.click(screen.getByRole("button", { name: "Cancel" })) - await waitFor(() => - expect(screen.getByRole("button", { name: "Reject candidate" })).toHaveFocus(), - ) - }) - - it("resets confirmations and idempotency after successful action revalidation", () => { - const data = available() - const { rerender } = render( - - - , - ) - fireEvent.click(screen.getByRole("button", { name: "Start training" })) - const firstKey = ( - screen - .getByRole("button", { name: "Queue this training job" }) - .closest("form") - ?.querySelector('[name="idempotencyKey"]') as HTMLInputElement - ).value - - rerender( - - - , - ) - - expect(screen.queryByRole("button", { name: "Queue this training job" })).toBeNull() - fireEvent.click(screen.getByRole("button", { name: "Start training" })) - const secondKey = ( - screen - .getByRole("button", { name: "Queue this training job" }) - .closest("form") - ?.querySelector('[name="idempotencyKey"]') as HTMLInputElement - ).value - expect(secondKey).not.toBe(firstKey) - }) - - it("shows a persisted rejection without fixing the localized date", () => { - const data = available() - renderPanel({ - ...data, - candidates: data.candidates.map((candidate) => ({ - ...candidate, - rejection: { - rejectedAt: "2026-11-12T20:30:00Z", - reason: "The held-out regression is not acceptable.", - }, - })), - }) - expect(screen.getByText(/Rejected .*held-out regression is not acceptable/)).toBeVisible() - expect(screen.queryByRole("button", { name: "Promote candidate" })).not.toBeInTheDocument() - }) - - it("does not offer rejection or promotion for the current promoted candidate", () => { - const data = available() - const candidate = { ...data.candidates[0]!, promoted: true } - renderPanel({ - ...data, - candidates: [candidate], - promotion: { - ...data.promotion!, - candidateId: candidate.id, - runtimeCandidateId: candidate.runtimeCandidateId, - }, - }) - expect(screen.queryByRole("button", { name: "Promote candidate" })).not.toBeInTheDocument() - expect(screen.queryByRole("button", { name: "Reject candidate" })).not.toBeInTheDocument() - }) -}) diff --git a/hub/client/features/decision-model-panel/index.tsx b/hub/client/features/decision-model-panel/index.tsx deleted file mode 100644 index 4a07e9569..000000000 --- a/hub/client/features/decision-model-panel/index.tsx +++ /dev/null @@ -1,807 +0,0 @@ -import { useRef, useState } from "react" -import { Button, Checkbox, FormControl, Heading, Text, TextInput } from "@primer/react-brand" - -import { HubAlert } from "@components/hub-alert" - -import "./styles.css" -import type { DecisionCandidate, DecisionModelPanelData, DecisionTrainingJob } from "./types" - -/** Repository decision-model settings, training progress, and explicit model decisions. */ -export function DecisionModelPanel({ - data, - authenticityToken, - trainingSubmitting = false, -}: { - data: DecisionModelPanelData - authenticityToken: string - trainingSubmitting?: boolean -}) { - if (data.state === "repository-learning-only") { - return ( -
- - Decision model - - -
- ) - } - if (data.state === "not-configured") { - return ( -
- - Decision model - - - {data.setupGuidance} -
- ) - } - if (data.state === "unavailable") { - return ( -
- - Decision model - - - {data.setupGuidance} -
- ) - } - return ( - - ) -} - -function AvailableDecisionModel({ - data, - authenticityToken, - trainingSubmitting, -}: { - data: Extract - authenticityToken: string - trainingSubmitting: boolean -}) { - const [confirmTraining, setConfirmTraining] = useState(false) - const [promoting, setPromoting] = useState(null) - const [rejecting, setRejecting] = useState(null) - const [confirmRollback, setConfirmRollback] = useState(false) - const [idempotencyKey] = useState(() => `hub-ui-${crypto.randomUUID()}`) - const trainingButton = useRef(null) - const rollbackButton = useRef(null) - const generation = data.promotion?.generation ?? 0 - - return ( -
-
-
- - Decision model - - - A decision model checks Build screenshots against accepted learnings. Training and - promotion always require a person's decision. - -
- - {data.configuration?.enabled ? "Training enabled" : "Training paused"} - -
- -
-
- - Repository settings - - - These limits bound one training job and the repository's monthly training budget. - - -
- -
- - Training readiness - - {data.readiness.runtime} - {data.readiness.evidence} - {data.readiness.blockedReasons.length ? ( - - ) : null} - {data.readiness.warnings.map((warning) => ( - - ))} - {data.readiness.latestTasksetDigest ? ( -

- Latest pinned taskset {data.readiness.latestTasksetDigest} -

- ) : null} -
-
- - {data.configuration?.backend === "fixture" ? ( - - ) : null} - - {data.deletions.length ? ( -
- - Runtime deletions - - - Consent withdrawal can remove private exports, tasksets, and runtime artifacts without - deleting the repository's decision history. - -
    - {data.deletions.map((deletion) => ( -
  • - - {deletion.state === "pending" - ? "Deletion pending" - : deletion.state === "completed" - ? "Deletion completed" - : "Deletion failed"} - - {deletion.summary} - {deletion.failure ? ( - - {deletion.failure} - - ) : null} -
  • - ))} -
-
- ) : null} - -
-
-
- - Training - - - Hub creates a private taskset from permitted review evidence and immutable Build - screenshots, then sends it to the customer-run runtime. - -
- {!confirmTraining && data.trainingAvailable && !data.preparationStatus ? ( - - ) : null} -
- - {confirmTraining && data.configuration ? ( -
- - - - - - The next click queues this job. It does not promote the resulting candidate. - -
- - -
- - ) : null} - - {data.preparationStatus ? ( - - {data.preparationStatus} - - ) : data.activeJob ? ( - - ) : !data.trainingAvailable ? ( - - {data.configuration === null - ? "Save repository settings before starting training." - : !data.configuration.enabled - ? "Enable repository training before starting a job." - : data.readiness.blockedReasons.length - ? "Resolve the evidence blockers before starting training." - : "Wait for the active job to finish before starting another."} - - ) : null} - -
- -
- - Candidate comparison - - - Held-out evidence is data reserved from training so a person can compare a candidate with - the baseline it started from. - - {data.candidates.length ? ( -
- {data.candidates.map((candidate) => ( - setPromoting(candidate.id)} - onCancel={() => setPromoting(null)} - onReject={() => setRejecting(candidate.id)} - onCancelReject={() => setRejecting(null)} - /> - ))} -
- ) : ( - No training candidate has finished yet. - )} -
- -
- - Current promoted model - - {data.promotion ? ( - <> -
-
-
Runtime model
-
{data.promotion.runtimeCandidateId}
-
-
-
Promotion generation
-
{data.promotion.generation}
-
-
-
Last decision
-
{data.promotion.operation === "promote" ? "Promoted" : "Rolled back"}
-
-
- {!data.promotion.rollbackAvailable ? ( - - No eligible previous candidate is available to restore. - - ) : !confirmRollback ? ( - - ) : ( -
- - - -
- - -
- - )} - - ) : ( - No candidate is promoted. Build evaluation remains off. - )} -
- -
- - Evaluate a Build - - - Hub sends the selected Build's captured views and accepted-learning questions to the - currently promoted model, then saves the findings below. - - {!data.promotion ? ( - - Promote a candidate before evaluating a Build. - - ) : data.evaluationBuilds.length ? ( -
    - {data.evaluationBuilds.map((build) => ( -
  • -
    - - -
    -
  • - ))} -
- ) : ( - - No successful Builds with captured screenshots are available. - - )} -
- -
- - Latest Build evaluation - - {data.evaluations.length ? ( - data.evaluations.map((evaluation) => ( -
-
-
- - Build {evaluation.buildNumber} - - - Evaluated {formatDate(evaluation.createdAt)} with{" "} - {evaluation.runtimeCandidateId}, generation {evaluation.generation} - -
- Open accepted Build -
- {evaluation.findingsAvailable ? ( - evaluation.findings.length ? ( -
    - {evaluation.findings.map((finding) => ( -
  • - - {finding.learningText ?? finding.learningId} on{" "} - {finding.route} - - {finding.learningText === null ? ( - - The accepted learning text was removed after this evaluation. - - ) : null} - - {finding.views} - - - Follows {finding.followsProbability}; breaks {finding.breaksProbability}.{" "} - {finding.explanation} - -
  • - ))} -
- ) : ( - The latest evaluation reported no learning findings. - ) - ) : ( - - )} -
- )) - ) : ( - No Build has been evaluated with the promoted model yet. - )} -
-
- ) -} - -function SettingsForm({ - data, - authenticityToken, -}: { - data: Extract - authenticityToken: string -}) { - const configuration = data.configuration - return ( -
- - - Repository training - - - Opt this repository in. Disabling it pauses new jobs without changing the promoted model. - - - - Runtime backend - - - The backend key configured by the customer-run decision runtime. - - -
- - Maximum updates per job - - - - Maximum seconds per job - - - - Monthly training budget (credits) - - -
-
- - {configuration ? ( - - Settings generation {configuration.generation} - - ) : null} -
-
- ) -} - -function TrainingJobs({ - jobs, - authenticityToken, -}: { - jobs: DecisionTrainingJob[] - authenticityToken: string -}) { - if (!jobs.length) return No decision-model training jobs yet. - return ( -
- - - - - - - - - - - {jobs.map((job) => ( - - - - - - - ))} - -
RequestedStatePinned evidenceAction
- - - {job.stateLabel} - {job.failure ? ( - - {" "} - โ€” {job.failure} {job.failureKind === "retryable" ? "Retryable." : "Terminal."} - - ) : null} - - {job.tasksetDigest.slice(0, 18)}โ€ฆ - - {job.cancellable ? ( -
- - -
- ) : ( - "โ€”" - )} -
-
- ) -} - -function CandidateCard({ - candidate, - allowPromotion, - expectedGeneration, - authenticityToken, - confirming, - rejecting, - onConfirm, - onCancel, - onReject, - onCancelReject, -}: { - candidate: DecisionCandidate - allowPromotion: boolean - expectedGeneration: number - authenticityToken: string - confirming: boolean - rejecting: boolean - onConfirm: () => void - onCancel: () => void - onReject: () => void - onCancelReject: () => void -}) { - const promoteButton = useRef(null) - const rejectButton = useRef(null) - - return ( -
-
-
- - Candidate {candidate.runtimeCandidateId} - - - Finished {formatDate(candidate.createdAt)} - -
- - {candidate.promoted - ? "Promoted" - : candidate.productionEligible - ? "Runtime eligible" - : allowPromotion - ? "Development only" - : "Not eligible"} - -
-
-
-
-
Baseline held-out reward
-
{candidate.baselineMeanReward}
-
-
-
Candidate held-out reward
-
{candidate.candidateMeanReward}
-
-
-
Held-out reward change
-
{candidate.meanRewardChange}
-
-
-
Baseline calibration error
-
{candidate.baselineCalibrationError}
-
-
-
Candidate calibration error
-
{candidate.candidateCalibrationError}
-
-
-
Calibration error change
-
{candidate.calibrationErrorChange}
-
-
-
Elapsed time
-
{candidate.duration}
-
-
- {candidate.learningMetrics.length ? ( -
- - - - - - - - - - - {candidate.learningMetrics.map((metric) => ( - - - - - - - ))} - -
LearningBaselineCandidateChange
{metric.learningId}{metric.baseline}{metric.candidate} - {metric.change} ({metric.direction}) -
-
- ) : ( - - Per-learning comparison was not reported. - - )} - {candidate.usage.length ? ( -
    - {candidate.usage.map((usage) => ( -
  • {usage}
  • - ))} -
- ) : ( - - Training usage and cost were not reported. - - )} -
-

- Pinned taskset {candidate.tasksetDigest} -

- {candidate.rejection ? ( - - ) : confirming ? ( -
- - - - - Hub will reject this decision if the promotion generation changed since this page - loaded. - -
- - -
- - ) : rejecting ? ( -
- - - Why reject this candidate? - - -
- - -
-
- ) : ( -
- {!candidate.promoted && allowPromotion ? ( - - ) : null} - {!candidate.promoted ? ( - - ) : null} -
- )} -
- ) -} - -function formatDuration(seconds: number) { - if (seconds < 60) return `${seconds} seconds` - if (seconds % 3600 === 0) return `${seconds / 3600} hours` - if (seconds % 60 === 0) return `${seconds / 60} minutes` - return `${seconds} seconds` -} - -function formatDate(value: string) { - return new Intl.DateTimeFormat("en-US", { - dateStyle: "medium", - timeStyle: "short", - }).format(new Date(value)) -} diff --git a/hub/client/features/decision-model-panel/styles.css b/hub/client/features/decision-model-panel/styles.css deleted file mode 100644 index cd7cde539..000000000 --- a/hub/client/features/decision-model-panel/styles.css +++ /dev/null @@ -1,143 +0,0 @@ -.decision-model-panel { - display: grid; - gap: 1rem; - padding-block-start: 0.5rem; - border-block-start: 1px solid var(--hub-border-default); -} - -.decision-model-panel p { - margin: 0; -} - -.decision-model-panel__heading, -.decision-model-panel__actions { - display: flex; - flex-wrap: wrap; - align-items: flex-start; - justify-content: space-between; - gap: 0.75rem; -} - -.decision-model-panel__heading > div { - display: grid; - gap: 0.5rem; -} - -.decision-model-panel__grid, -.decision-model-panel__candidates { - display: grid; - gap: 1rem; -} - -.decision-model-panel__card, -.decision-model-panel__candidate, -.decision-model-panel__form, -.decision-model-panel__confirm, -.decision-model-panel__comparison { - display: grid; - gap: 1rem; -} - -.decision-model-panel__card, -.decision-model-panel__candidate { - padding: 1.25rem; - border: 1px solid var(--hub-border-default); - border-radius: 0.75rem; - background: var(--hub-canvas-default); -} - -.decision-model-panel__candidate { - background: var(--hub-canvas-subtle); -} - -.decision-model-panel__fields { - display: grid; - gap: 1rem; -} - -.decision-model-panel__badge { - padding: 0.25rem 0.625rem; - border: 1px solid var(--hub-border-default); - border-radius: 999px; - background: var(--hub-canvas-subtle); - color: var(--hub-fg-muted); - font-size: 0.75rem; - font-weight: 600; - white-space: nowrap; -} - -.decision-model-panel__facts { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr)); - gap: 0.75rem; - margin: 0; -} - -.decision-model-panel__facts div { - display: grid; - gap: 0.25rem; -} - -.decision-model-panel__facts dt { - color: var(--hub-fg-muted); - font-size: 0.75rem; -} - -.decision-model-panel__facts dd { - margin: 0; - overflow-wrap: anywhere; - font-weight: 600; -} - -.decision-model-panel__digest { - overflow-wrap: anywhere; - color: var(--hub-fg-muted); - font-size: 0.75rem; -} - -.decision-model-panel__table { - min-width: 0; - overflow-x: auto; -} - -.decision-model-panel__table:focus-visible { - outline: 2px solid var(--hub-focus); - outline-offset: 2px; -} - -.decision-model-panel__table table { - width: 100%; - min-width: 44rem; - border-collapse: collapse; -} - -.decision-model-panel__table th, -.decision-model-panel__table td { - padding: 0.625rem 0.75rem; - border-bottom: 1px solid var(--hub-border-default); - text-align: start; - vertical-align: top; -} - -.decision-model-panel__findings { - display: grid; - gap: 1rem; - margin: 0; - padding-inline-start: 1.25rem; -} - -.decision-model-panel__findings li { - display: grid; - gap: 0.375rem; -} - -@media (min-width: 48rem) { - .decision-model-panel__grid, - .decision-model-panel__fields { - grid-template-columns: repeat(2, minmax(0, 1fr)); - } - - .decision-model-panel__fields > :last-child { - grid-column: 1 / -1; - } -} diff --git a/hub/client/features/decision-model-panel/types.ts b/hub/client/features/decision-model-panel/types.ts deleted file mode 100644 index 38824f732..000000000 --- a/hub/client/features/decision-model-panel/types.ts +++ /dev/null @@ -1,127 +0,0 @@ -export interface DecisionTrainingJob { - id: string - state: - | "queued" - | "submitting" - | "cancel_requested" - | "submitted" - | "running" - | "succeeded" - | "failed" - | "cancelled" - stateLabel: string - createdAt: string - finishedAt: string | null - tasksetDigest: string - failure: string | null - failureKind: "retryable" | "terminal" | null - cancelPath: string - cancellable: boolean -} - -export interface DecisionCandidate { - id: string - runtimeCandidateId: string - backend: string - createdAt: string - productionEligible: boolean - tasksetDigest: string - baselineMeanReward: string - candidateMeanReward: string - meanRewardChange: string - baselineCalibrationError: string - candidateCalibrationError: string - calibrationErrorChange: string - learningMetrics: Array<{ - learningId: string - baseline: string - candidate: string - change: string - direction: "gain" | "regression" | "unchanged" | "unknown" - }> - duration: string - usage: string[] - rejection: { rejectedAt: string; reason: string | null } | null - promoted: boolean - promotePath: string - rejectPath: string -} - -export type DecisionModelPanelData = - | { - state: "repository-learning-only" - message: string - } - | { - state: "not-configured" - message: string - setupGuidance: string - } - | { - state: "unavailable" - message: string - setupGuidance: string - } - | { - state: "available" - settingsPath: string - trainingPath: string - rollbackPath: string - configuration: { - enabled: boolean - generation: number - backend: string - maxUpdates: number - maxSeconds: number - monthlyBudgetCredits: string - } | null - readiness: { - runtime: string - evidence: string - latestTasksetDigest: string | null - warnings: string[] - blockedReasons: string[] - } - trainingAvailable: boolean - preparationStatus?: string | null - activeJob: DecisionTrainingJob | null - jobs: DecisionTrainingJob[] - candidates: DecisionCandidate[] - promotion: { - candidateId: string - runtimeCandidateId: string - generation: number - operation: "promote" | "rollback" - rollbackAvailable: boolean - } | null - evaluationBuilds: Array<{ - id: string - number: number - label: string - evaluationPath: string - }> - evaluations: Array<{ - id: string - buildNumber: number - prototypePath: string - runtimeCandidateId: string - generation: number - createdAt: string - findingsAvailable: boolean - findings: Array<{ - learningId: string - learningText: string | null - route: string - views: string - followsProbability: string - breaksProbability: string - explanation: string - }> - }> - deletions: Array<{ - id: string - state: "pending" | "completed" | "failed" - summary: string - failure: string | null - }> - } diff --git a/hub/client/features/learning-activity-grid/index.test.tsx b/hub/client/features/learning-activity-grid/index.test.tsx new file mode 100644 index 000000000..6f6354ff7 --- /dev/null +++ b/hub/client/features/learning-activity-grid/index.test.tsx @@ -0,0 +1,85 @@ +import { ThemeProvider } from "@primer/react-brand" +import { fireEvent, render, screen, within } from "@testing-library/react" +import { describe, expect, it } from "vitest" + +import { LearningActivityGrid } from "." + +describe("LearningActivityGrid()", () => { + it("shows a day's run and moves between days with the arrow keys", () => { + render( + + + , + ) + 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("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() + + const today = within(calendar).getByRole("button", { name: /^November 20, 2026,/ }) + fireEvent.click(today) + fireEvent.keyDown(today, { key: "ArrowDown" }) + expect(today).toHaveAttribute("aria-pressed", "true") + expect(today).toHaveAccessibleName(/no run$/) + expect(screen.getByText("No learning run")).toBeVisible() + }) + + it("selects today when the grid moves into a new year", () => { + const day = { + runState: "succeeded" as const, + startedAt: "2026-12-30T16:30:00Z", + startedBy: "your agent", + commentsAnalyzed: 5, + commentsTagged: 1, + suggestions: 0, + } + const { rerender } = render( + + + , + ) + expect(screen.getByRole("button", { name: /^December 30, 2026,/ })).toHaveAttribute( + "aria-pressed", + "true", + ) + + rerender( + + + , + ) + expect(screen.getByRole("button", { name: /^January 1, 2027,/ })).toHaveAttribute( + "aria-pressed", + "true", + ) + expect(screen.getByText("No learning run")).toBeVisible() + }) +}) diff --git a/hub/client/features/learning-activity-grid/index.tsx b/hub/client/features/learning-activity-grid/index.tsx new file mode 100644 index 000000000..27913a7d8 --- /dev/null +++ b/hub/client/features/learning-activity-grid/index.tsx @@ -0,0 +1,294 @@ +import { + useLayoutEffect, + useMemo, + useRef, + useState, + type CSSProperties, + type KeyboardEvent, +} from "react" +import { Heading, Text } from "@primer/react-brand" + +import type { LearningActivityDay } from "./types" +import "./styles.css" + +type ActivityMetric = "commentsAnalyzed" | "commentsTagged" | "suggestions" + +const activityMetrics: Array<{ key: ActivityMetric; label: string }> = [ + { key: "commentsAnalyzed", label: "Comments analyzed" }, + { key: "commentsTagged", label: "Comments categorized" }, + { key: "suggestions", label: "Suggestions" }, +] + +function dayLabel(date: string, options: Intl.DateTimeFormatOptions = { dateStyle: "long" }) { + return new Intl.DateTimeFormat("en-US", { ...options, timeZone: "UTC" }).format( + new Date(`${date}T00:00:00.000Z`), + ) +} + +function countLabel(value: number, singular: string) { + return `${value} ${singular}${value === 1 ? "" : "s"}` +} + +type CalendarCell = { date: string; day: LearningActivityDay | null } + +function quietDay(date: string): LearningActivityDay { + return { + date, + runState: "none", + startedAt: null, + startedBy: null, + commentsAnalyzed: 0, + commentsTagged: 0, + suggestions: 0, + } +} + +function buildCalendarYear(activity: LearningActivityDay[], today: string) { + const year = today.slice(0, 4) + const daysByDate = new Map(activity.map((day) => [day.date, day])) + const cursor = new Date(`${year}-01-01T00:00:00.000Z`) + cursor.setUTCDate(cursor.getUTCDate() - cursor.getUTCDay()) + const end = new Date(`${year}-12-31T00:00:00.000Z`).getTime() + const weeks: Array> = [] + + while (cursor.getTime() <= end) { + weeks.push( + Array.from({ length: 7 }, () => { + const date = cursor.toISOString().slice(0, 10) + cursor.setUTCDate(cursor.getUTCDate() + 1) + if (!date.startsWith(`${year}-`)) return null + if (date > today) return { date, day: null } + return { date, day: daysByDate.get(date) ?? quietDay(date) } + }), + ) + } + return weeks +} + +function firstDateOf(week: Array | undefined) { + return week?.find((cell) => cell !== null)?.date +} + +function monthLabelsByWeek(weeks: Array>) { + const labels = weeks.map((week, index) => { + const firstDate = firstDateOf(week) + const previousDate = firstDateOf(weeks[index - 1]) + if (!firstDate) return "" + if (previousDate && firstDate.slice(0, 7) === previousDate.slice(0, 7)) return "" + return dayLabel(firstDate, { month: "short" }) + }) + return labels.map((label, index) => (label && labels[index + 1] ? "" : label)) +} + +/** Shows the year's daily activity and the selected day's run summary. */ +export function LearningActivityGrid({ + activity, + today, +}: { + activity: LearningActivityDay[] + today: string +}) { + return +} + +function CalendarYear({ activity, today }: { activity: LearningActivityDay[]; today: string }) { + const [metric, setMetric] = useState("commentsAnalyzed") + const weeks = useMemo(() => buildCalendarYear(activity, today), [activity, today]) + const monthLabels = useMemo(() => monthLabelsByWeek(weeks), [weeks]) + const pastDays = weeks.flat().flatMap((cell) => (cell?.day ? [cell.day] : [])) + const maximum = Math.max(1, ...pastDays.map((day) => day[metric])) + const metricLabel = activityMetrics.find(({ key }) => key === metric)?.label + const [selectedDate, setSelectedDate] = useState( + () => pastDays.findLast((day) => day.runState !== "none")?.date ?? today, + ) + const selectedDay = pastDays.find((day) => day.date === selectedDate) ?? null + const calendarRef = useRef(null) + const scrollerRef = useRef(null) + + function moveSelectedDate(event: KeyboardEvent) { + const offsets: Record = { + ArrowDown: 1, + ArrowLeft: -7, + ArrowRight: 7, + ArrowUp: -1, + } + const offset = offsets[event.key] + if (offset === undefined) return + + event.preventDefault() + const next = new Date(`${selectedDate}T00:00:00.000Z`) + next.setUTCDate(next.getUTCDate() + offset) + const nextDate = next.toISOString().slice(0, 10) + if (!nextDate.startsWith(`${today.slice(0, 4)}-`) || nextDate > today) return + + const nextButton = calendarRef.current?.querySelector( + `[data-date="${nextDate}"]`, + ) + if (!nextButton) return + setSelectedDate(nextDate) + nextButton.focus() + } + + useLayoutEffect(() => { + const scroller = scrollerRef.current + const selectedCell = scroller?.querySelector('[aria-pressed="true"]') + if (!scroller || !selectedCell) return + const overflow = + selectedCell.getBoundingClientRect().right - scroller.getBoundingClientRect().right + if (overflow > 0) { + scroller.scrollLeft += overflow + parseFloat(getComputedStyle(scroller).paddingRight) + } + }, []) + + return ( +
+
+ + Learning activity + + + Daily runs in {today.slice(0, 4)} ยท UTC + +
+ +
+ {activityMetrics.map(({ key, label }) => ( + + ))} +
+ +
+
+
+ + {weeks.map((week, weekIndex) => ( +
+ + {week.map((cell, dayIndex) => { + if (!cell) { + return ( +
+ ))} +
+
+ +
+ +
+
+ + {selectedDay ? ( +
+
+ + {dayLabel(selectedDay.date)} + + + {selectedDay.runState === "none" + ? "No learning run" + : `${selectedDay.runState === "failed" ? "Run failed" : "Run completed"}${ + selectedDay.startedBy ? ` ยท Started by ${selectedDay.startedBy}` : "" + }${ + selectedDay.startedAt + ? ` ยท ${new Intl.DateTimeFormat("en-US", { + hour: "numeric", + minute: "2-digit", + timeZone: "UTC", + timeZoneName: "short", + }).format(new Date(selectedDay.startedAt))}` + : "" + }`} + +
+
+ {activityMetrics.map(({ key, label }) => ( +
+
{label}
+
{selectedDay[key]}
+
+ ))} +
+
+ ) : null} +
+ ) +} diff --git a/hub/client/features/learning-activity-grid/styles.css b/hub/client/features/learning-activity-grid/styles.css new file mode 100644 index 000000000..78c587f1c --- /dev/null +++ b/hub/client/features/learning-activity-grid/styles.css @@ -0,0 +1,267 @@ +.learning-activity { + --calendar-month-height: 1rem; + --calendar-gap: 0.125rem; + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + grid-template-areas: + "heading ." + "graph measures" + "graph ." + "summary summary"; + align-items: start; + gap: 1rem 2rem; + padding: 1.25rem; + border: 1px solid var(--hub-border-default); + border-radius: var(--hub-radius-medium); + background: var(--hub-canvas-default); +} + +.learning-activity h2, +.learning-activity h3, +.learning-activity p { + margin: 0; +} + +.learning-activity__heading { + display: grid; + grid-area: heading; + gap: 0.375rem; +} + +.learning-activity__graph { + display: grid; + grid-area: graph; + grid-template-rows: subgrid; + gap: 0.75rem; + justify-self: start; + max-width: 100%; +} + +.learning-activity > .learning-activity__run-summary { + grid-area: summary; +} + +.learning-activity__metric-switch { + display: grid; + grid-area: measures; + align-self: center; + gap: 0.25rem; + min-width: 11rem; + translate: 0 calc((var(--calendar-month-height) + var(--calendar-gap)) / 2); +} + +.learning-activity__metric-button { + display: inline-flex; + align-items: center; + gap: 0.5rem; + min-height: 2rem; + padding: 0.375rem 0.75rem; + border: 0; + border-radius: var(--hub-radius-medium); + background: transparent; + color: var(--hub-fg-muted); + cursor: pointer; + font-size: 0.8125rem; + white-space: nowrap; + justify-content: flex-start; + text-align: start; +} + +.learning-activity__metric-button:hover { + background: var(--hub-canvas-subtle); + color: var(--hub-fg-default); +} + +.learning-activity__metric-button[aria-pressed="true"] { + background: var(--hub-primary-bg); + color: var(--hub-primary-fg); +} + +.learning-activity__metric-button:focus-visible, +.learning-activity__day:focus-visible { + outline: 2px solid var(--hub-focus); + outline-offset: 2px; +} + +.learning-activity__calendar-scroll { + overflow-x: auto; + padding: 0.25rem; +} + +.learning-activity__calendar { + --cell-min: 0.625rem; + --cell-max: 0.875rem; + display: grid; + grid-auto-flow: column; + grid-template-columns: auto repeat(var(--weeks), minmax(var(--cell-min), var(--cell-max))); + grid-template-rows: var(--calendar-month-height) repeat(7, auto); + gap: var(--calendar-gap); + justify-content: start; + min-width: min-content; +} + +.learning-activity__weekday-labels, +.learning-activity__week { + display: contents; +} + +.learning-activity__weekday-labels > span { + align-self: center; + padding-inline-end: 0.25rem; + color: var(--hub-fg-muted); + font-size: 0.625rem; + line-height: 1; +} + +.learning-activity__month { + color: var(--hub-fg-muted); + font-size: 0.625rem; + line-height: var(--calendar-month-height); + white-space: nowrap; +} + +.learning-activity__day, +.learning-activity__day-empty, +.learning-activity__day-upcoming { + box-sizing: border-box; + width: 100%; + aspect-ratio: 1; + border-radius: 0.125rem; +} + +.learning-activity__legend-cell { + width: 0.625rem; + height: 0.625rem; + border-radius: 0.125rem; +} + +.learning-activity__day { + padding: 0; + border: 1px solid color-mix(in srgb, var(--hub-border-default) 65%, transparent); + background: color-mix( + in srgb, + var(--hub-success-emphasis) calc(var(--activity-level, 0) * 100%), + var(--hub-canvas-subtle) + ); + cursor: pointer; +} + +.learning-activity__day-upcoming { + border: 1px solid color-mix(in srgb, var(--hub-border-default) 35%, transparent); +} + +.learning-activity__day--failed { + box-shadow: inset 0 0 0 1px var(--hub-fg-danger); +} + +.learning-activity__day:focus-visible, +.learning-activity__day[aria-pressed="true"] { + outline-offset: 0; +} + +.learning-activity__day[aria-pressed="true"] { + outline: 2px solid var(--hub-accent); +} + +.learning-activity__footer { + display: flex; + justify-content: flex-end; + color: var(--hub-fg-muted); +} + +.learning-activity__legend { + display: flex; + align-items: center; + gap: 0.25rem; + font-size: 0.6875rem; +} + +.learning-activity__legend-cell { + display: inline-block; + border: 1px solid var(--hub-border-default); + background: color-mix( + in srgb, + var(--hub-success-emphasis) calc(var(--activity-level, 0) * 100%), + var(--hub-canvas-subtle) + ); +} + +.learning-activity__run-summary { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + padding-top: 1rem; + border-top: 1px solid var(--hub-border-muted); +} + +.learning-activity__run-summary > div:first-child { + display: grid; + gap: 0.25rem; +} + +.learning-activity__run-summary > div:first-child > p { + color: var(--hub-fg-muted); +} + +.learning-activity__run-metrics { + display: grid; + grid-template-columns: repeat(3, auto); + justify-content: start; + gap: 2rem; + margin: 0; +} + +.learning-activity__run-metrics > div { + display: grid; + align-content: start; + gap: 0.25rem; +} + +.learning-activity__run-metrics dt { + color: var(--hub-fg-muted); + font-size: 0.75rem; +} + +.learning-activity__run-metrics dd { + grid-row: 1; + margin: 0; + font-size: var(--brand-text-size-500); + font-weight: 600; + line-height: 1; +} + +@container (max-width: 48rem) { + .learning-activity { + grid-template-columns: minmax(0, 1fr); + grid-template-areas: + "heading" + "measures" + "graph" + "graph" + "summary"; + } + + .learning-activity__run-summary { + align-items: flex-start; + flex-direction: column; + } + + .learning-activity__run-metrics { + gap: 1rem; + align-self: stretch; + } + + .learning-activity__metric-switch { + display: flex; + flex-wrap: wrap; + min-width: 0; + translate: none; + } + + .learning-activity__metric-button { + flex: 1; + justify-content: center; + white-space: normal; + } +} diff --git a/hub/client/features/learning-activity-grid/types.ts b/hub/client/features/learning-activity-grid/types.ts new file mode 100644 index 000000000..7295f1923 --- /dev/null +++ b/hub/client/features/learning-activity-grid/types.ts @@ -0,0 +1,10 @@ +/** One day in the activity grid. Past days without a run use the "none" state. */ +export interface LearningActivityDay { + date: string + runState: "none" | "succeeded" | "failed" + startedAt: string | null + startedBy: string | null + commentsAnalyzed: number + commentsTagged: number + suggestions: number +} diff --git a/hub/client/features/learnings-library/index.tsx b/hub/client/features/learnings-library/index.tsx new file mode 100644 index 000000000..6b45dfc10 --- /dev/null +++ b/hub/client/features/learnings-library/index.tsx @@ -0,0 +1,531 @@ +import { useEffect, useRef, useState, type ReactNode } from "react" +import { + ArrowLeftIcon, + CheckCircleIcon, + LightBulbIcon, + SearchIcon, + XCircleIcon, + type Icon, +} from "@primer/octicons-react" +import { + Button, + FormControl, + Heading, + Label, + Pagination, + Text, + TextInput, + Textarea, +} from "@primer/react-brand" + +import { HubCounter } from "@components/hub-counter" +import { HubEmptyState } from "@components/hub-empty-state" +import { HubUserAvatar } from "@components/hub-user-avatar" +import { CanvasDialog } from "@components/prototype-canvas-dialog" +import { ReviewRelativeTime } from "@features/review-relative-time" +import { + fitsLearningGuidanceLimit, + guidanceLimitMessage, +} from "@utils/fits-learning-guidance-limit" + +import type { + LearningDetail, + LearningEvidence, + LearningStatus, + LearningsLibraryData, +} from "./types" +import "./styles.css" + +const statuses = ["suggested", "active", "rejected"] as const + +const statusLabels: Record = { + suggested: "Suggested", + active: "Active", + rejected: "Rejected", +} + +// Mirrors GitHub's pull request states so people can read status at a glance. +const statusIcons: Record = { + suggested: LightBulbIcon, + active: CheckCircleIcon, + rejected: XCircleIcon, +} + +const statusLabelColors = { + suggested: "default", + active: "green", + rejected: "red", +} as const satisfies Record + +const emptyMessages: Record = { + suggested: "Hub suggests a learning when the same point comes up in at least two review threads.", + active: "Accept a suggestion to share it with agents.", + rejected: "Learnings you reject or stop using stay here so you can accept them again.", +} + +/** Renders a learning's state icon; Brand labels need an element, not a component. */ +function StatusIcon({ status, className }: { status: LearningStatus; className?: string }) { + const Glyph = statusIcons[status] + return +} + +/** + * Lists a repository's learnings by status and shows one in detail. Members browse; + * repository administrators also decide what agents get. + */ +export function LearningsLibrary({ + data, + authenticityToken, +}: { + data: LearningsLibraryData + authenticityToken: string +}) { + const previousSelectedId = useRef(null) + const selectedId = data.selected?.id ?? null + + useEffect(() => { + if (selectedId) { + previousSelectedId.current = selectedId + document.getElementById("learning-detail-heading")?.focus() + return + } + if (previousSelectedId.current) { + document.getElementById(`learning-${previousSelectedId.current}`)?.focus() + previousSelectedId.current = null + } + }, [selectedId]) + + return data.selected ? ( + + ) : ( + + ) +} + +function LearningList({ data }: { data: LearningsLibraryData }) { + const [query, setQuery] = useState(data.query) + + function pageHref(page: number) { + const url = new URL(data.listPath, window.location.origin) + if (page > 1) url.searchParams.set("page", String(page)) + return `${url.pathname}${url.search}` + } + const searchPath = new URL(data.listPath, window.location.origin).pathname + + return ( +
+ + Browse learnings + +
+ +
+ + + Search learnings + } + maxLength={200} + name="q" + onChange={(event) => setQuery(event.target.value)} + placeholder="Search learnings" + type="search" + value={query} + /> + +
+
+ {data.learnings.length ? ( +
+ + + + + + + + + {data.learnings.map((learning) => ( + + + + + ))} + +
LearningUpdated
+
+ +
+ + {learning.title} + +

{learning.guidance}

+
+
+
+ {learning.updatedAt ? : "โ€”"} +
+
+ ) : ( + + )} + {data.pageCount > 1 ? ( + + ) : null} +
+ ) +} + +function LearningDetailView({ + learning, + backPath, + authenticityToken, +}: { + learning: LearningDetail + backPath: string + authenticityToken: string +}) { + const [dialog, setDialog] = useState<"reject" | "edit" | "retire" | "reinstate" | null>(null) + const decision = learning.decision + + return ( +
+ + + Back to learnings + +
+
+ + + {learning.title} + + + {learning.guidance} + + {learning.facts.length ? ( +
    + {learning.facts.map((fact) => ( +
  • {fact}
  • + ))} +
+ ) : null} +
+ {decision ? ( +
+ {learning.status === "suggested" ? ( + <> + + + + + + ) : learning.status === "active" ? ( + <> + + + + ) : ( + + )} +
+ ) : null} +
+ + {learning.reason ? ( +
+ + + {learning.reason.heading} + + {learning.reason.text} +
+ ) : 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.contradictions.length || learning.otherContradictions ? ( + + + + ) : 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 +