Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(health): rebuild the Performance tab around interventions (#1985)
Raghav Chamadiya2a8a703b3b56
diff --git a/packages/api-client/src/code-health.ts b/packages/api-client/src/code-health.tsindex 10c67d40b..cb56e860e 100644--- a/packages/api-client/src/code-health.ts+++ b/packages/api-client/src/code-health.ts@@ -14,11 +14,9 @@ import type {HealthFileBreakdownResponse,HealthOverviewResponse,HealthTrendResponse,- PerformanceActionabilityState,- PerformanceExecutionContext,- PerformanceOpportunityConfidence,PerformanceOpportunityDetail,PerformanceOpportunityPage,+ PerformanceOpportunityQuery,HealthWorkQueueQuery,HealthWorkQueueResponse,} from "@repowise-dev/types/health";@@ -57,6 +55,7 @@ export type {PerformanceOpportunityDetail,PerformanceOpportunityEvidence,PerformanceOpportunityPage,+ PerformanceOpportunityQuery,PerformanceOpportunitySummary,RefactoringQuery,RefactoringTarget,@@ -86,26 +85,12 @@ export async function listHealthFindings(return apiGet<HealthFinding[]>(`/api/repos/${repoId}/health/findings`, opts);}-export interface PerformanceOpportunityPageParams {- /**- * Canonical contexts. `production_tooling` is a retired spelling the server- * still answers as Production+Tooling; it is never returned as a context.- */- context?: PerformanceExecutionContext | "all" | "production_tooling";- boundary?: string;- /** Evidence confidence, reported apart from fix safety and actionability. */- confidence?: PerformanceOpportunityConfidence;- actionability?: PerformanceActionabilityState;- /** `summary` drops the explanatory fields and keeps identity and counts. */- view?: "detail" | "summary";- sort?: "rank" | "leverage" | "observations";- limit?: number;- offset?: number;-}+/** The canonical query shape lives with the wire types. */+export type PerformanceOpportunityPageParams = PerformanceOpportunityQuery;export async function getPerformanceOpportunities(repoId: string,- opts: PerformanceOpportunityPageParams = {},+ opts: PerformanceOpportunityQuery = {},): Promise<PerformanceOpportunityPage> {return apiGet<PerformanceOpportunityPage>(`/api/repos/${repoId}/health/performance-opportunities`,diff --git a/packages/api-client/src/hosted.test.ts b/packages/api-client/src/hosted.test.tsindex 69b195049..9786f757f 100644--- a/packages/api-client/src/hosted.test.ts+++ b/packages/api-client/src/hosted.test.ts@@ -333,14 +333,7 @@ describe("request wiring", () => {"/health/performance-opportunities",{...envelope,- summary: {- total: 0,- production_total: 0,- tooling_total: 0,- test_total: 0,- with_plan_total: 0,- without_plan_total: 0,- },+ summary: { status: "current", total: 0, with_plan_total: 0 },},],]);diff --git a/packages/api-client/src/hosted.ts b/packages/api-client/src/hosted.tsindex a8b10328c..417a13d43 100644--- a/packages/api-client/src/hosted.ts+++ b/packages/api-client/src/hosted.ts@@ -31,7 +31,10 @@ import type {HealthWorkQueueResponse,} from "@repowise-dev/types/health";import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";-import type { PerformanceOpportunityPage } from "@repowise-dev/types/health";+import type {+ PerformanceOpportunityPage,+ PerformanceOpportunityQuery,+} from "@repowise-dev/types/health";import type {RefactoringPlan,RefactoringPlanPage,@@ -410,11 +413,7 @@ export interface HostedProvider {getRefactoringPlan(repoId: string, planId: string): Promise<RefactoringPlan>;getPerformanceOpportunities(repoId: string,- opts?: {- context?: "production_tooling" | "test" | "all";- limit?: number;- offset?: number;- },+ opts?: PerformanceOpportunityQuery,): Promise<PerformanceOpportunityPage>;getPerformanceOpportunityFindings(repoId: string,diff --git a/packages/server/src/repowise/server/routers/code_health/performance_routes.py b/packages/server/src/repowise/server/routers/code_health/performance_routes.pyindex 3b9b498f6..9f5401409 100644--- a/packages/server/src/repowise/server/routers/code_health/performance_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/performance_routes.py@@ -41,26 +41,6 @@ def _item(item: dict[str, Any]) -> dict[str, Any]:return {key: value for key, value in item.items() if key != "plan_reference"}-def _summary(summary: dict[str, Any]) -> dict[str, Any]:- """Add the flat counter names the current tab reads.-- A projection of the canonical rollup, not a second count: every value is- read off the fields above it. The flat names retire with the tab.- """- context = summary.get("context", {})- total = summary.get("total", 0)- with_plan = summary.get("with_plan_total", 0)- return {- **summary,- "production_total": context.get("production", 0),- "tooling_total": context.get("tooling", 0),- "test_total": context.get("test", 0),- "unknown_total": context.get("unknown", 0),- "with_plan_total": with_plan,- "without_plan_total": total - with_plan,- }--@router.get("/api/repos/{repo_id}/health/performance-opportunities")async def list_performance_opportunities(repo_id: str,@@ -98,7 +78,7 @@ async def list_performance_opportunities("has_more": page.next_offset is not None,"next_offset": page.next_offset,"facets": page.facets,- "summary": _summary(page.summary),+ "summary": page.summary,**({"ignored_arguments": ignored} if ignored else {}),}diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsindex 39d5624be..258c01ad2 100644--- a/packages/types/src/health.ts+++ b/packages/types/src/health.ts@@ -348,13 +348,55 @@ export type PerformanceOpportunityDetail =detail: string;};-/** Counts per value for one filter, cross-filtered by the other filters. */+/**+ * Counts per value for one filter, computed from the base result rather than+ * the filtered one, so selecting a value never erases its own alternatives.+ * A value with no rows is absent rather than reported as zero.+ */export interface PerformanceFacetCount {value: string;total: number;}-export type PerformanceFacets = Record<string, PerformanceFacetCount[]>;+/**+ * The filters the server owns. Every key except `plan_state` is also a query+ * parameter; plan state is counted per value but is not something the queue+ * narrows by.+ */+export type PerformanceFacetKey =+ | "context"+ | "boundary"+ | "confidence"+ | "actionability"+ | "plan_state";++export type PerformanceFacets = Partial<Record<PerformanceFacetKey, PerformanceFacetCount[]>>;++/** `all` widens the context filter; the four contexts stay separate under it. */+export type PerformanceContextFilter = PerformanceExecutionContext | "all";++/**+ * The query the server answers, shared by the REST client and the views.+ * An alias rather than an interface so a client can hand it to a generic+ * query-parameter helper without restating every field.+ */+export type PerformanceOpportunityQuery = {+ /**+ * Canonical contexts. `production_tooling` is a retired spelling an older+ * server still answers as Production+Tooling. It is never returned as a+ * context, so only a legacy-compatibility path should send it.+ */+ context?: PerformanceContextFilter | "production_tooling";+ boundary?: string;+ /** Evidence confidence, requested apart from fix safety and actionability. */+ confidence?: PerformanceOpportunityConfidence;+ actionability?: PerformanceActionabilityState;+ /** `summary` drops the explanatory fields and keeps identity and counts. */+ view?: "detail" | "summary";+ sort?: "rank" | "leverage" | "observations";+ limit?: number;+ offset?: number;+};export interface PerformanceOpportunitySummary {/** `current` once materialized, `stale_model` after a model bump, or@@ -362,17 +404,16 @@ export interface PerformanceOpportunitySummary {status: "current" | "stale_model" | "unavailable";total: number;performance_model_version?: number;+ /** The model the stored rows were written by, when it trails the current one. */+ materialized_model_version?: number;analyzed_commit?: string | null;actionability?: Partial<Record<PerformanceActionabilityState, number>>;context?: Partial<Record<PerformanceExecutionContext, number>>;boundary?: Record<string, number>;with_plan_total: number;- /** Flat counters the current tab reads, projected from `context` above. */- production_total: number;- tooling_total: number;- test_total: number;- unknown_total: number;- without_plan_total: number;+ /** Why the queue is not current, when it is not. */+ reason?: string;+ detail?: string;}export interface PerformanceOpportunityPage extends Paginated<PerformanceOpportunity> {diff --git a/packages/ui/__tests__/health/fixtures/performance-wire-contract.json b/packages/ui/__tests__/health/fixtures/performance-wire-contract.jsonnew file mode 100644index 000000000..f1f127db8--- /dev/null+++ b/packages/ui/__tests__/health/fixtures/performance-wire-contract.json@@ -0,0 +1,114 @@+{+ "page": [+ "facets",+ "has_more",+ "items",+ "next_offset",+ "summary",+ "total"+ ],+ "summary": [+ "actionability",+ "analyzed_commit",+ "boundary",+ "context",+ "materialized_model_version",+ "performance_model_version",+ "status",+ "total",+ "with_plan_total"+ ],+ "facets": [+ "actionability",+ "boundary",+ "confidence",+ "context",+ "plan_state"+ ],+ "facet_entry": [+ "total",+ "value"+ ],+ "item": [+ "actionability_reason",+ "actionability_state",+ "affected_call_sites_total",+ "affected_files_total",+ "biomarker_type",+ "biomarker_types",+ "boundary_kind",+ "confidence",+ "evidence",+ "evidence_emitted",+ "evidence_total",+ "evidence_truncated",+ "execution_context",+ "facets",+ "file_path",+ "fix",+ "intervention_symbol",+ "observations_total",+ "opportunity_id",+ "performance_model_version",+ "plan_id",+ "plan_reason",+ "plan_status",+ "prerequisites",+ "provenance",+ "rank_factors",+ "rank_position",+ "rank_score",+ "reliable_entry_reachability",+ "resource_fingerprints",+ "shared_path_suffix",+ "terminal_sink",+ "why_ranked"+ ],+ "item_facets": [+ "actionability_confidence",+ "amplification",+ "change_risk",+ "exposure",+ "leverage"+ ],+ "evidence": [+ "biomarker_type",+ "file_path",+ "finding_id",+ "function_name",+ "line_end",+ "line_start",+ "path",+ "provenance",+ "reason"+ ],+ "why_ranked": [+ "factor",+ "points",+ "value"+ ],+ "fix": [+ "rationale",+ "safety",+ "strategy"+ ],+ "detail_extra": [+ "analyzed_commit",+ "lifecycle_status",+ "model_state",+ "resolved"+ ],+ "unresolved_detail": [+ "detail",+ "model_state",+ "opportunity_id",+ "resolved"+ ],+ "model_state": [+ "opportunity_id",+ "performance_model_version",+ "refresh_required",+ "requested_model_version",+ "state"+ ]+}diff --git a/packages/ui/__tests__/health/fixtures/performance.ts b/packages/ui/__tests__/health/fixtures/performance.tsnew file mode 100644index 000000000..9ea2a940d--- /dev/null+++ b/packages/ui/__tests__/health/fixtures/performance.ts@@ -0,0 +1,229 @@+import { vi } from "vitest";+import type {+ PerformanceOpportunity,+ PerformanceOpportunityDetail,+ PerformanceOpportunityPage,+} from "@repowise-dev/types/health";++import type { PerformanceViewAdapter } from "../../../src/health/performance/adapter";++/**+ * Synthetic queue fixtures shaped like the real response.+ *+ * Synthetic on purpose: an edge state such as a stale model, a truncated+ * evidence preview, or a context with no rows has to be reachable on demand,+ * and a live index only offers whatever it happens to hold.+ */++export function opportunity(+ overrides: Partial<PerformanceOpportunity> = {},+): PerformanceOpportunity {+ return {+ opportunity_id: "perf2_aaaaaaaaaaaaaaaaaaaa",+ performance_model_version: 2,+ biomarker_type: "io_in_loop",+ biomarker_types: ["io_in_loop"],+ boundary_kind: "db",+ execution_context: "production",+ terminal_sink: "src/db.py::fetch",+ shared_path_suffix: ["src/shared.py::load", "src/db.py::fetch"],+ intervention_symbol: "src/shared.py::load",+ file_path: "src/shared.py",+ resource_fingerprints: [],+ affected_call_sites_total: 2,+ affected_files_total: 2,+ observations_total: 6,+ evidence: [+ {+ finding_id: "finding_1111",+ file_path: "src/a.py",+ biomarker_type: "io_in_loop",+ function_name: "run",+ line_start: 10,+ line_end: 10,+ reason: "Database work repeats.",+ path: ["src/a.py::run", "src/shared.py::load", "src/db.py::fetch"],+ provenance: "reliable-edge",+ },+ {+ finding_id: "finding_2222",+ file_path: "src/b.py",+ biomarker_type: "io_in_loop",+ function_name: "run",+ line_start: 20,+ line_end: 20,+ reason: "Database work repeats.",+ path: ["src/b.py::run", "src/shared.py::load", "src/db.py::fetch"],+ provenance: "reliable-edge",+ },+ ],+ evidence_truncated: true,+ evidence_total: 6,+ evidence_emitted: 2,+ evidence_next_cursor: 2,+ reliable_entry_reachability: true,+ provenance: "reliable-edge",+ confidence: "medium",+ facets: {+ actionability_confidence: "high",+ exposure: "entry_reachable",+ amplification: "per_iteration",+ leverage: "local",+ change_risk: "moderate",+ },+ actionability_state: "advisory",+ actionability_reason: "strategy_requires_validation",+ prerequisites: ["batch_api_contract"],+ rank_score: 12.5,+ rank_position: 1,+ rank_factors: { boundary_kind: 4 },+ why_ranked: [{ factor: "boundary_kind", value: "db", points: 4 }],+ fix: {+ strategy: "batch_or_prefetch_io",+ safety: "advisory",+ rationale: "Validate result equivalence.",+ },+ plan_id: "plan-1",+ plan_status: "available",+ plan_reason: "A stored performance plan addresses this exact opportunity.",+ ...overrides,+ };+}++/** The five facet groups the server counts, with plausible totals. */+export function facets(): PerformanceOpportunityPage["facets"] {+ return {+ context: [+ { value: "production", total: 4 },+ { value: "test", total: 2 },+ { value: "tooling", total: 1 },+ ],+ boundary: [+ { value: "db", total: 4 },+ { value: "filesystem", total: 2 },+ { value: "none", total: 1 },+ ],+ confidence: [{ value: "high", total: 7 }],+ actionability: [+ { value: "investigate", total: 4 },+ { value: "advisory", total: 2 },+ { value: "plan_ready", total: 1 },+ ],+ plan_state: [+ { value: "no_safe_plan", total: 4 },+ { value: "available", total: 3 },+ ],+ };+}++export function page(overrides: Partial<PerformanceOpportunityPage> = {}): PerformanceOpportunityPage {+ return {+ items: [+ opportunity({+ opportunity_id: "perf2_planready",+ actionability_state: "plan_ready",+ actionability_reason: "proven_strategy",+ rank_position: 1,+ confidence: "high",+ fix: {+ strategy: "parallelize_independent_awaits",+ safety: "proven",+ rationale: "Dataflow proves the iterations carry no dependence.",+ },+ }),+ opportunity({+ opportunity_id: "perf2_advisory",+ actionability_state: "advisory",+ rank_position: 2,+ }),+ opportunity({+ opportunity_id: "perf2_investigate",+ actionability_state: "investigate",+ rank_position: 3,+ boundary_kind: null,+ terminal_sink: null,+ intervention_symbol: null,+ shared_path_suffix: [],+ biomarker_type: "membership_test_against_list_in_loop",+ biomarker_types: ["membership_test_against_list_in_loop"],+ fix: null,+ plan_id: null,+ plan_status: "no_safe_plan",+ plan_reason: "No coherent intervention was proven.",+ }),+ ],+ total: 7,+ has_more: true,+ next_offset: 3,+ facets: facets(),+ summary: {+ status: "current",+ total: 7,+ performance_model_version: 2,+ analyzed_commit: "848a8f180abc",+ actionability: { plan_ready: 1, advisory: 2, investigate: 4 },+ context: { production: 4, test: 2, tooling: 1 },+ boundary: { db: 4, filesystem: 2 },+ with_plan_total: 3,+ },+ ...overrides,+ };+}++/** A server that predates canonical contexts and server-owned facets. */+export function legacyPage(): PerformanceOpportunityPage {+ const base = page();+ return {+ ...base,+ facets: {},+ summary: {+ total: 7,+ with_plan_total: 3,+ } as PerformanceOpportunityPage["summary"],+ };+}++export function resolvedDetail(+ overrides: Partial<Extract<PerformanceOpportunityDetail, { resolved: true }>> = {},+): PerformanceOpportunityDetail {+ return {+ ...opportunity({ opportunity_id: "perf2_planready" }),+ resolved: true,+ lifecycle_status: "open",+ analyzed_commit: "848a8f180abc",+ model_state: {+ state: "current",+ opportunity_id: "perf2_planready",+ requested_model_version: 2,+ performance_model_version: 2,+ refresh_required: false,+ },+ evidence_total: 6,+ evidence_emitted: 2,+ ...overrides,+ };+}++/** `undefined` is a meaningful override here: it is how a host declines one. */+type AdapterOverrides = {+ [K in keyof PerformanceViewAdapter]?: PerformanceViewAdapter[K] | undefined;+};++export function adapter(overrides: AdapterOverrides = {}): PerformanceViewAdapter {+ return {+ cacheKey: `repo-${Math.random()}`,+ listFindings: vi.fn(async () => []),+ getPerformanceOpportunities: vi.fn(async () => page()),+ getPerformanceOpportunityFindings: vi.fn(async () => ({+ items: [],+ total: 0,+ has_more: false,+ next_offset: null,+ })),+ refactoringPlanHref: (planId: string) => `/refactoring?plan=${planId}`,+ fileHref: (path: string) => `/files/${path}`,+ symbolHref: (symbol: string) => `/symbols/${symbol}`,+ navigate: vi.fn(),+ ...overrides,+ } as PerformanceViewAdapter;+}diff --git a/packages/ui/__tests__/health/performance-contract.test.ts b/packages/ui/__tests__/health/performance-contract.test.tsnew file mode 100644index 000000000..26b828e94--- /dev/null+++ b/packages/ui/__tests__/health/performance-contract.test.ts@@ -0,0 +1,136 @@+import { describe, expect, it } from "vitest";+import type {+ PerformanceFacetKey,+ PerformanceOpportunityPage,+} from "@repowise-dev/types/health";++import { capabilitiesOf } from "../../src/health/performance/capabilities";+import { toQuery, INITIAL_FILTERS, withFilter } from "../../src/health/performance/query";+import contract from "./fixtures/performance-wire-contract.json";+import { adapter, facets, legacyPage, page, resolvedDetail } from "./fixtures/performance";++/**+ * The wire contract, pinned.+ *+ * `performance-wire-contract.json` is the key set a live server produced for+ * this repository. The fixtures the view tests run against have to keep+ * matching it, so a field that is renamed or dropped on the server fails here+ * rather than silently rendering as blank in the tab.+ */++const keys = (value: object) => Object.keys(value).sort();++describe("canonical performance wire contract", () => {+ it("keeps the page envelope the server emits", () => {+ expect(keys(page())).toEqual(contract.page);+ });++ it("keeps the canonical summary and carries no retired flat counters", () => {+ expect(contract.summary).not.toContain("production_total");+ expect(contract.summary).not.toContain("without_plan_total");+ for (const field of ["status", "total", "with_plan_total", "actionability", "context"]) {+ expect(contract.summary).toContain(field);+ }+ // The fixture may omit an optional field, but must never add an unknown one.+ expect(contract.summary).toEqual(expect.arrayContaining(keys(page().summary)));+ });++ it("keeps the five facet groups, each counted per value", () => {+ expect(keys(facets())).toEqual(contract.facets);+ expect(keys(facets().context![0]!)).toEqual(contract.facet_entry);+ });++ it("keeps every opportunity field the queue reads", () => {+ // Present only when the preview is bounded, so the sampled row omits it.+ const optional = ["evidence_next_cursor"];+ expect(keys(page().items[0]!).filter((key) => !optional.includes(key))).toEqual(contract.item);+ expect(contract.item.filter((key) => optional.includes(key))).toEqual([]);+ expect(keys(page().items[0]!.facets)).toEqual(contract.item_facets);+ expect(keys(page().items[0]!.evidence[0]!)).toEqual(contract.evidence);+ expect(keys(page().items[0]!.why_ranked[0]!)).toEqual(contract.why_ranked);+ expect(keys(page().items[0]!.fix!)).toEqual(contract.fix);+ });++ it("publishes no value twice across the confidence facets", () => {+ const item = page().items[0]!;+ expect(contract.item).toContain("confidence");+ expect(contract.item_facets).toContain("actionability_confidence");+ expect(contract.fix).toContain("safety");+ // Evidence confidence, actionability confidence, and fix safety are three+ // fields in three places; none of them is a copy of another.+ expect(contract.item_facets).not.toContain("confidence");+ expect(contract.item_facets).not.toContain("safety");+ expect(item.facets.actionability_confidence).toBeDefined();+ });++ it("keeps the detail additions and the unresolved answer", () => {+ const detail = resolvedDetail() as Record<string, unknown>;+ for (const field of contract.detail_extra) expect(detail[field]).toBeDefined();+ expect(contract.unresolved_detail).toEqual([+ "detail",+ "model_state",+ "opportunity_id",+ "resolved",+ ]);+ expect(contract.model_state).toContain("refresh_required");+ });++ it("never emits a plan reference into the browser address space", () => {+ expect(contract.item).not.toContain("plan_reference");+ });+});++describe("legacy adapter compatibility", () => {+ it("detects a server without facets or a canonical summary", () => {+ const modern = capabilitiesOf(adapter(), page());+ expect(modern.serverFacets).toBe(true);+ expect(modern.canonicalContexts).toBe(true);++ const older = capabilitiesOf(adapter(), legacyPage());+ expect(older.serverFacets).toBe(false);+ expect(older.canonicalContexts).toBe(false);+ });++ it("reports a host capability from the adapter rather than a deployment flag", () => {+ const bare = capabilitiesOf(+ adapter({+ getPerformanceOpportunity: undefined,+ getPerformanceOpportunityFindings: undefined,+ getRefactoringPlan: undefined,+ }),+ page(),+ );+ expect(bare.detailById).toBe(false);+ expect(bare.pagedEvidence).toBe(false);+ expect(bare.planById).toBe(false);+ });++ it("sends the retired context pairing only against a server that needs it", () => {+ const production = withFilter(INITIAL_FILTERS, "context", "production");+ const older = capabilitiesOf(adapter(), legacyPage());+ expect(+ toQuery(production, { limit: 20, collapseContexts: !older.canonicalContexts }).context,+ ).toBe("production_tooling");+ const modern = capabilitiesOf(adapter(), page());+ expect(+ toQuery(production, { limit: 20, collapseContexts: !modern.canonicalContexts }).context,+ ).toBe("production");+ });++ it("keeps the facet key union and the emitted facet groups in step", () => {+ const emitted = contract.facets as PerformanceFacetKey[];+ const declared: PerformanceFacetKey[] = [+ "context",+ "boundary",+ "confidence",+ "actionability",+ "plan_state",+ ];+ expect([...emitted].sort()).toEqual([...declared].sort());+ });++ it("treats an absent facet value as absent, never as a zero the server sent", () => {+ const withoutUnknown: PerformanceOpportunityPage = page();+ expect(withoutUnknown.facets.context?.some((entry) => entry.value === "unknown")).toBe(false);+ });+});diff --git a/packages/ui/__tests__/health/performance-presentation.test.ts b/packages/ui/__tests__/health/performance-presentation.test.tsnew file mode 100644index 000000000..beead6de3--- /dev/null+++ b/packages/ui/__tests__/health/performance-presentation.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from "vitest";+import { PERFORMANCE_HOME_BIOMARKERS } from "../../src/health/biomarker-glossary";++import {+ affectedSummary,+ agentHandoffCall,+ boundaryLabel,+ facetValueLabel,+ opportunityEvidenceLine,+ opportunityTitle,+ planPresentation,+ whyRankedLabel,+} from "../../src/health/performance/presentation";+import { contiguousSections } from "../../src/health/performance/queue";+import { opportunity } from "./fixtures/performance";++describe("performance presentation", () => {+ it("titles a cause in words and keeps the sink out of the title", () => {+ const title = opportunityTitle(opportunity());+ expect(title).toBe("Database call inside a loop");+ expect(title).not.toContain("::");+ });++ it("gives every performance marker a non-empty title", () => {+ for (const marker of PERFORMANCE_HOME_BIOMARKERS) {+ const title = opportunityTitle(opportunity({ biomarker_type: marker, boundary_kind: null }));+ expect(title.length, marker).toBeGreaterThan(0);+ expect(title[0], marker).toBe(title[0]!.toUpperCase());+ }+ });++ it("names an absent boundary rather than leaving it blank", () => {+ expect(boundaryLabel(null)).toBe("In-process");+ expect(boundaryLabel("none")).toBe("In-process");+ expect(boundaryLabel("db")).toBe("Database");+ expect(boundaryLabel("something_new")).toBe("Something new");+ });++ it("falls back from sink to intervention symbol to file for the evidence line", () => {+ expect(opportunityEvidenceLine(opportunity())).toBe("src/db.py::fetch");+ expect(opportunityEvidenceLine(opportunity({ terminal_sink: null }))).toBe(+ "src/shared.py::load",+ );+ expect(+ opportunityEvidenceLine(+ opportunity({ terminal_sink: null, intervention_symbol: null }),+ ),+ ).toBe("src/shared.py::run");+ expect(+ opportunityEvidenceLine(+ opportunity({ terminal_sink: null, intervention_symbol: null, evidence: [] }),+ ),+ ).toBe("src/shared.py");+ });++ it("keeps singular and plural counts honest", () => {+ expect(affectedSummary(opportunity())).toBe("2 call sites across 2 files");+ expect(+ affectedSummary(opportunity({ affected_call_sites_total: 1, affected_files_total: 1 })),+ ).toBe("1 call site across 1 file");+ });++ it("reads a rank factor as words with its signed contribution", () => {+ expect(whyRankedLabel({ factor: "boundary_kind", value: "db", points: 4 })).toBe(+ "Boundary kind: Db (+4)",+ );+ expect(whyRankedLabel({ factor: "entry_reachability", value: true, points: 0 })).toBe(+ "Entry reachability (+0)",+ );+ });++ it("labels each facet in its own vocabulary", () => {+ expect(facetValueLabel("context", "unknown")).toBe("Unclassified");+ expect(facetValueLabel("actionability", "investigate")).toBe("Needs investigation");+ expect(facetValueLabel("confidence", "high")).toBe("High");+ expect(facetValueLabel("plan_state", "no_safe_plan")).toBe("No safe plan");+ expect(facetValueLabel("boundary", "none")).toBe("In-process");+ });++ it("separates a plan that exists from one that needs a refresh and from none", () => {+ expect(planPresentation(opportunity()).actionable).toBe(true);+ const refresh = planPresentation(+ opportunity({ plan_id: null, plan_status: "not_persisted" }),+ );+ expect(refresh.actionable).toBe(false);+ expect(refresh.label).toBe("Needs an index refresh");+ const none = planPresentation(opportunity({ plan_id: null, plan_status: "no_safe_plan" }));+ expect(none.label).toBe("No safe plan");+ });++ it("never calls a plan actionable without an id to fetch it with", () => {+ expect(planPresentation(opportunity({ plan_id: null })).actionable).toBe(false);+ });++ it("quotes the opportunity id in the agent drill-down", () => {+ expect(agentHandoffCall("perf2_abc")).toBe('get_health(opportunity_id="perf2_abc")');+ });+});++describe("queue sections", () => {+ it("splits the page into runs without moving a single row", () => {+ const items = [+ opportunity({ opportunity_id: "a", actionability_state: "plan_ready" }),+ opportunity({ opportunity_id: "b", actionability_state: "advisory" }),+ opportunity({ opportunity_id: "c", actionability_state: "advisory" }),+ opportunity({ opportunity_id: "d", actionability_state: "investigate" }),+ ];+ const sections = contiguousSections(items);+ expect(sections.map((s) => s.state)).toEqual(["plan_ready", "advisory", "investigate"]);+ expect(sections.flatMap((s) => s.items.map((i) => i.opportunity_id))).toEqual([+ "a",+ "b",+ "c",+ "d",+ ]);+ });++ it("keeps an interleaved order intact rather than regrouping it", () => {+ const items = [+ opportunity({ opportunity_id: "a", actionability_state: "advisory" }),+ opportunity({ opportunity_id: "b", actionability_state: "investigate" }),+ opportunity({ opportunity_id: "c", actionability_state: "advisory" }),+ ];+ const sections = contiguousSections(items);+ expect(sections).toHaveLength(3);+ expect(sections.flatMap((s) => s.items.map((i) => i.opportunity_id))).toEqual(["a", "b", "c"]);+ });++ it("returns nothing for an empty page", () => {+ expect(contiguousSections([])).toEqual([]);+ });+});diff --git a/packages/ui/__tests__/health/performance-query.test.ts b/packages/ui/__tests__/health/performance-query.test.tsnew file mode 100644index 000000000..b5e5de612--- /dev/null+++ b/packages/ui/__tests__/health/performance-query.test.ts@@ -0,0 +1,77 @@+import { describe, expect, it } from "vitest";++import {+ clearNarrowing,+ INITIAL_FILTERS,+ narrowingCount,+ parseFilters,+ serializeFilters,+ toQuery,+ withFilter,+} from "../../src/health/performance/query";++describe("performance filter state", () => {+ it("serializes only what differs from the default", () => {+ expect(serializeFilters(INITIAL_FILTERS)).toBe("");+ const narrowed = withFilter(+ withFilter(INITIAL_FILTERS, "context", "production"),+ "boundary",+ "db",+ );+ expect(serializeFilters(narrowed)).toBe("context=production&boundary=db");+ });++ it("round trips every field through a query string", () => {+ const state = {+ context: "test" as const,+ boundary: "filesystem",+ confidence: "high" as const,+ actionability: "plan_ready" as const,+ sort: "leverage" as const,+ offset: 40,+ };+ expect(parseFilters(serializeFilters(state))).toEqual(state);+ });++ it("drops a value the vocabulary does not contain instead of forwarding it", () => {+ const parsed = parseFilters("context=production_tooling&actionability=nonsense&offset=-3");+ expect(parsed.context).toBe("all");+ expect(parsed.actionability).toBeNull();+ expect(parsed.offset).toBe(0);+ });++ it("returns to the first page when a filter narrows, and holds it when paging", () => {+ const paged = withFilter(INITIAL_FILTERS, "offset", 20);+ expect(paged.offset).toBe(20);+ expect(withFilter(paged, "boundary", "db").offset).toBe(0);+ expect(withFilter(paged, "offset", 40).offset).toBe(40);+ });++ it("sends canonical contexts, and the retired pairing only when told to collapse", () => {+ const production = withFilter(INITIAL_FILTERS, "context", "production");+ expect(toQuery(production, { limit: 20 }).context).toBe("production");+ expect(toQuery(production, { limit: 20, collapseContexts: true }).context).toBe(+ "production_tooling",+ );+ const test = withFilter(INITIAL_FILTERS, "context", "test");+ expect(toQuery(test, { limit: 20, collapseContexts: true }).context).toBe("test");+ const unknown = withFilter(INITIAL_FILTERS, "context", "unknown");+ expect(toQuery(unknown, { limit: 20 }).context).toBe("unknown");+ });++ it("omits a narrowing parameter that is not set rather than sending an empty one", () => {+ const query = toQuery(INITIAL_FILTERS, { limit: 20 });+ expect(query).toEqual({ context: "all", view: "detail", sort: "rank", limit: 20, offset: 0 });+ expect("boundary" in query).toBe(false);+ });++ it("counts and clears the narrowing filters without touching context", () => {+ let state = withFilter(INITIAL_FILTERS, "context", "test");+ state = withFilter(state, "boundary", "db");+ state = withFilter(state, "actionability", "advisory");+ expect(narrowingCount(state)).toBe(2);+ const cleared = clearNarrowing(state);+ expect(narrowingCount(cleared)).toBe(0);+ expect(cleared.context).toBe("test");+ });+});diff --git a/packages/ui/__tests__/health/performance-view.test.tsx b/packages/ui/__tests__/health/performance-view.test.tsxindex 34f94f5db..82f2a320c 100644--- a/packages/ui/__tests__/health/performance-view.test.tsx+++ b/packages/ui/__tests__/health/performance-view.test.tsx@@ -1,218 +1,374 @@-import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { beforeAll, describe, expect, it, vi } from "vitest";-import type { PerformanceOpportunityPage } from "@repowise-dev/types/health";import type { RefactoringPlan } from "@repowise-dev/types/refactoring";-import { PerformanceView, type PerformanceViewAdapter } from "../../src/health/performance-view";+import { PerformanceView } from "../../src/health/performance-view";+import { adapter, legacyPage, opportunity, page, resolvedDetail } from "./fixtures/performance";beforeAll(() => {Element.prototype.scrollIntoView = vi.fn();});-function page(planId: string | null = "plan-1"): PerformanceOpportunityPage {- return {- items: [- {- opportunity_id: "opp-1",- performance_model_version: 2,- biomarker_type: "io_in_loop",- biomarker_types: ["io_in_loop"],- boundary_kind: "db",- execution_context: "production",- terminal_sink: "src/db.py::fetch",- shared_path_suffix: ["src/shared.py::load", "src/db.py::fetch"],- intervention_symbol: "src/shared.py::load",- file_path: "src/shared.py",- resource_fingerprints: [],- affected_call_sites_total: 2,- affected_files_total: 2,- observations_total: 6,- evidence: [- {- finding_id: "finding-1",- file_path: "src/a.py",- biomarker_type: "io_in_loop",- function_name: "run",- line_start: 10,- line_end: 10,- reason: "Database work repeats.",- path: ["src/a.py::run", "src/shared.py::load", "src/db.py::fetch"],- provenance: "reliable-edge",- },- {- finding_id: "finding-2",- file_path: "src/b.py",- biomarker_type: "io_in_loop",- function_name: "run",- line_start: 20,- line_end: 20,- reason: "Database work repeats.",- path: ["src/b.py::run", "src/shared.py::load", "src/db.py::fetch"],- provenance: "reliable-edge",- },- ],- evidence_truncated: true,- evidence_total: 6,- evidence_emitted: 2,- evidence_next_cursor: 2,- reliable_entry_reachability: true,- provenance: "reliable-edge",- confidence: "medium",- facets: {- actionability_confidence: "medium",- exposure: "entry_reachable",- amplification: "per_iteration",- leverage: "local",- change_risk: "moderate",- },- actionability_state: "advisory",- actionability_reason: "strategy_requires_validation",- prerequisites: ["batch_api_contract"],- rank_score: 12.5,- rank_position: 0,- rank_factors: {},- why_ranked: [{ factor: "boundary_kind", value: "db", points: 4 }],- fix: {- strategy: "batch_or_prefetch_io",- safety: "advisory",- rationale: "Validate result equivalence.",- },- plan_id: planId,- plan_status: planId ? "available" : "no_safe_plan",- plan_reason: planId ? "Exact match." : "No coherent intervention was proven.",- },- ],- total: 1,- has_more: false,- next_offset: null,- facets: {},- summary: {- status: "current",- total: 2,- production_total: 1,- tooling_total: 0,- test_total: 1,- unknown_total: 0,- with_plan_total: planId ? 1 : 0,- without_plan_total: planId ? 1 : 2,- },- };-}--function adapter(load = vi.fn(async () => page())): PerformanceViewAdapter {- return {- cacheKey: `repo-${Math.random()}`,- listFindings: vi.fn(async () => []),- getPerformanceOpportunities: load,- getPerformanceOpportunityFindings: vi.fn(),- refactoringPlanHref: (planId) => `/refactoring?plan=${planId}`,- fileHref: (path) => `/files/${path}`,- symbolHref: (symbol) => `/symbols/${symbol}`,- navigate: vi.fn(),- };-}--describe("PerformanceView", () => {- it("renders causal totals, context, provenance paths, truncation, and an exact plan handoff", async () => {+const rows = () => screen.findAllByRole("listitem");+const openFirstRow = async () => {+ const [first] = await rows();+ fireEvent.click(first!);+ return first!;+};++describe("PerformanceView queue", () => {+ it("leads with the canonical rollup rather than flat context counters", async () => {render(<PerformanceView adapter={adapter()} />);- const row = await screen.findByRole("button", { name: /2 call sites/i });- expect(screen.getByRole("tab", { name: /Production & tooling 1/i })).toBeTruthy();- expect(screen.getByRole("tab", { name: /Test suite 1/i })).toBeTruthy();-- fireEvent.click(row);- expect(await screen.findAllByText("Reliable resolved edge")).toHaveLength(2);- expect(screen.getByText("2 paths shown of 6 recorded observations.")).toBeTruthy();- expect(screen.getByText(/Database · Production · Medium confidence/)).toBeTruthy();- expect(screen.getByRole("link", { name: "Open on Refactoring page" }).getAttribute("href")).toBe(- "/refactoring?plan=plan-1",- );+ expect(await screen.findByText("Causal opportunities")).toBeTruthy();+ expect(screen.getByText("a named safe intervention")).toBeTruthy();+ expect(screen.getByText("read the evidence first")).toBeTruthy();+ expect(screen.getByText("of 7 causes")).toBeTruthy();});- it("switches server-owned context and explains the no-safe-plan state", async () => {- const load = vi.fn(async () => page(null));- render(<PerformanceView adapter={adapter(load)} />);- fireEvent.click(await screen.findByRole("tab", { name: /Test suite 1/i }));+ it("keeps the four canonical contexts separate and counts them from the facets", async () => {+ render(<PerformanceView adapter={adapter()} />);+ await rows();+ expect(screen.getByRole("tab", { name: /Production 4/ })).toBeTruthy();+ expect(screen.getByRole("tab", { name: /Tooling 1/ })).toBeTruthy();+ expect(screen.getByRole("tab", { name: /Test suite 2/ })).toBeTruthy();+ // Absent from the facets, so it counts zero and still gets its own tab.+ expect(screen.getByRole("tab", { name: /Unclassified 0/ })).toBeTruthy();+ });++ it("asks the server for a canonical context and never the retired pairing", async () => {+ const load = vi.fn(async () => page());+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: load })} />);+ fireEvent.click(await screen.findByRole("tab", { name: /Tooling 1/ }));await waitFor(() =>expect(load).toHaveBeenLastCalledWith({- context: "test",- offset: 0,+ context: "tooling",+ view: "detail",+ sort: "rank",limit: 20,+ offset: 0,}),);- expect(load).toHaveBeenCalledTimes(2);+ });- fireEvent.click(screen.getByRole("button", { name: /2 call sites/i }));- expect(await screen.findByText(/No safe structured plan/)).toBeTruthy();- expect(screen.queryByRole("link", { name: "Open on Refactoring page" })).toBeNull();+ it("builds the narrowing filters from the server facets and refetches on change", async () => {+ const load = vi.fn(async () => page());+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: load })} />);+ await rows();+ const boundary = screen.getByLabelText("Boundary");+ expect(within(boundary).getByRole("option", { name: "Database (4)" })).toBeTruthy();+ expect(within(boundary).getByRole("option", { name: "In-process (1)" })).toBeTruthy();++ fireEvent.change(boundary, { target: { value: "db" } });+ await waitFor(() =>+ expect(load).toHaveBeenLastCalledWith(expect.objectContaining({ boundary: "db" })),+ );});- it("distinguishes a safe plan that needs reindexing from no safe plan", async () => {- const result = page(null);- result.items[0] = {- ...result.items[0]!,- plan_status: "not_persisted",- plan_reason: "A matching recommendation can be materialized by reindexing.",- };- render(<PerformanceView adapter={adapter(vi.fn(async () => result))} />);+ it("states a facet with one value instead of offering a control that cannot narrow", async () => {+ render(<PerformanceView adapter={adapter()} />);+ await rows();+ expect(screen.queryByLabelText("Evidence confidence")).toBeNull();+ expect(screen.getByText("on all 7")).toBeTruthy();+ });++ it("states the rendered scope, the filtered total, and the repository total", async () => {+ render(<PerformanceView adapter={adapter()} />);+ // The per-page range belongs to the pagination control; this states what+ // the selection covers and when it was computed, and says each once.+ expect(await screen.findByText(/Showing/)).toBeTruthy();+ const scope = screen+ .getAllByRole("status")+ .map((node) => node.textContent ?? "")+ .find((text) => text.includes("opportunities"));+ expect(scope).toContain("7 opportunities");+ expect(scope).toContain("848a8f1");+ });++ it("groups the page into actionability sections without reordering it", async () => {+ render(<PerformanceView adapter={adapter()} />);+ const items = await rows();+ expect(items).toHaveLength(3);+ expect(screen.getByText(/1 in the repository/)).toBeTruthy();+ const headings = screen.getAllByRole("heading", { level: 3 }).map((h) => h.textContent ?? "");+ expect(headings[0]).toContain("Plan ready");+ expect(headings[1]).toContain("Advisory");+ expect(headings[2]).toContain("Needs investigation");+ });++ it("shows the cause in words with the sink as separate monospace evidence", async () => {+ render(<PerformanceView adapter={adapter()} />);+ const [first] = await rows();+ expect(within(first!).getByText("Database call inside a loop")).toBeTruthy();+ expect(within(first!).getByText("src/db.py::fetch")).toBeTruthy();+ expect(within(first!).getByText(/2 call sites across 2 files/)).toBeTruthy();+ expect(within(first!).getByText(/High evidence confidence/)).toBeTruthy();+ });++ it("pages with the server cursor and never filters the page on the client", async () => {+ const load = vi.fn(async () => page());+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: load })} />);+ await rows();+ fireEvent.click(screen.getByRole("button", { name: /next/i }));+ await waitFor(() =>+ expect(load).toHaveBeenLastCalledWith(expect.objectContaining({ offset: 3 })),+ );+ });+});++describe("PerformanceView states", () => {+ it("says an unanalyzed index is unanalyzed, never clear", async () => {+ const empty = page({+ items: [],+ total: 0,+ has_more: false,+ next_offset: null,+ summary: {+ status: "unavailable",+ total: 0,+ with_plan_total: 0,+ detail: "This index has no performance analysis yet.",+ },+ });+ render(+ <PerformanceView adapter={adapter({ getPerformanceOpportunities: async () => empty })} />,+ );+ expect(+ await screen.findByText("This index has not been analyzed for performance"),+ ).toBeTruthy();+ });++ it("distinguishes an analyzed empty repository from an unanalyzed one", async () => {+ const empty = page({ items: [], total: 0, has_more: false, next_offset: null });+ render(+ <PerformanceView adapter={adapter({ getPerformanceOpportunities: async () => empty })} />,+ );+ expect(await screen.findByText("No supported pattern surfaced")).toBeTruthy();+ expect(screen.getByText(/does not claim the code is fast/)).toBeTruthy();+ });++ it("offers a way back when a filter combination matches nothing", async () => {+ const load = vi.fn(async (query?: { boundary?: string }) =>+ query?.boundary ? page({ items: [], total: 0, has_more: false, next_offset: null }) : page(),+ );+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: load })} />);+ await rows();+ fireEvent.change(screen.getByLabelText("Boundary"), { target: { value: "db" } });+ expect(await screen.findByText("No opportunities match these filters")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Clear filters" }));+ await waitFor(() =>+ expect(load).toHaveBeenLastCalledWith(expect.objectContaining({ context: "all" })),+ );+ });++ it("warns that a stale model can move ids", async () => {+ const stale = page({+ summary: { ...page().summary, status: "stale_model", performance_model_version: 1 },+ });+ render(+ <PerformanceView adapter={adapter({ getPerformanceOpportunities: async () => stale })} />,+ );+ expect(await screen.findByText(/grouped by an earlier analysis model/)).toBeTruthy();+ });++ it("names a filter value the server did not recognize", async () => {+ const ignored = page({ ignored_arguments: { performance_boundary: "bogus" } });+ render(+ <PerformanceView adapter={adapter({ getPerformanceOpportunities: async () => ignored })} />,+ );+ expect(await screen.findByText(/did not recognize/)).toBeTruthy();+ expect(screen.getByText("performance_boundary=bogus")).toBeTruthy();+ });++ it("reports a failed load without implying the repository is clean", async () => {+ const failing = vi.fn(async () => {+ throw new Error("boom");+ });+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: failing })} />);+ expect(await screen.findByText("Could not load performance opportunities")).toBeTruthy();+ expect(screen.getByText(/Nothing here says the code is fast/)).toBeTruthy();+ });+});++describe("PerformanceView drawer", () => {+ it("separates evidence confidence, actionability, and fix safety", async () => {+ render(<PerformanceView adapter={adapter()} />);+ await openFirstRow();+ const panel = await screen.findByRole("dialog");+ expect(within(panel).getByText("Evidence confidence")).toBeTruthy();+ expect(within(panel).getByText("Actionability confidence")).toBeTruthy();+ expect(within(panel).getByText("Fix safety")).toBeTruthy();+ expect(within(panel).getByText("Proven")).toBeTruthy();+ expect(within(panel).getByText(/How reliably the call path resolved/)).toBeTruthy();+ });++ it("carries the exact drill-down an agent should call", async () => {+ render(<PerformanceView adapter={adapter()} />);+ await openFirstRow();+ expect(await screen.findByText('get_health(opportunity_id="perf2_planready")')).toBeTruthy();+ });++ it("reads the detail by id when the host can, and reports the analyzed commit", async () => {+ const getDetail = vi.fn(async () => resolvedDetail());+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunity: getDetail })} />);+ await openFirstRow();+ await waitFor(() =>+ expect(getDetail).toHaveBeenCalledWith("perf2_planready", { evidenceLimit: 8 }),+ );+ const panel = await screen.findByRole("dialog");+ expect(within(panel).getByText(/Analyzed at/)).toBeTruthy();+ });++ it("says a cause is no longer observed instead of showing it as open", async () => {+ const getDetail = vi.fn(async () => resolvedDetail({ lifecycle_status: "resolved" }));+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunity: getDetail })} />);+ await openFirstRow();+ expect(+ await screen.findByText(/No observation supports this cause in the current index/),+ ).toBeTruthy();+ });++ it("reports a stale id as stale rather than as no plan", async () => {+ const getDetail = vi.fn(async () =>+ resolvedDetail({+ model_state: {+ state: "stale_model",+ opportunity_id: "perf2_planready",+ requested_model_version: 1,+ performance_model_version: 2,+ refresh_required: true,+ },+ }),+ );+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunity: getDetail })} />);+ await openFirstRow();+ expect(await screen.findByText(/minted by performance model version 1/)).toBeTruthy();+ });++ it("tells an unresolvable id apart from a stale one and from an empty index", async () => {+ const getDetail = vi.fn(async () => ({+ resolved: false as const,+ opportunity_id: "perf2_planready",+ model_state: {+ state: "unrecognized" as const,+ opportunity_id: "perf2_planready",+ requested_model_version: null,+ performance_model_version: 2,+ refresh_required: false,+ },+ detail: "That is not a performance opportunity id.",+ }));+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunity: getDetail })} />);+ await openFirstRow();+ const panel = await screen.findByRole("dialog");+ expect(within(panel).getByText(/does not recognize that opportunity id/)).toBeTruthy();+ expect(within(panel).getByText("That is not a performance opportunity id.")).toBeTruthy();+ expect(within(panel).queryByText(/minted by performance model version/)).toBeNull();+ expect(within(panel).queryByText(/has not been analyzed/)).toBeNull();+ });++ it("explains why there is no plan rather than leaving the section empty", async () => {+ const noPlan = page({+ items: [+ opportunity({+ opportunity_id: "perf2_noplan",+ plan_id: null,+ plan_status: "no_safe_plan",+ plan_reason: "No coherent intervention was proven.",+ fix: null,+ }),+ ],+ });+ render(+ <PerformanceView adapter={adapter({ getPerformanceOpportunities: async () => noPlan })} />,+ );+ await openFirstRow();+ const panel = await screen.findByRole("dialog");+ expect(within(panel).getByText("No safe plan")).toBeTruthy();+ expect(within(panel).getByText("No coherent intervention was proven.")).toBeTruthy();+ expect(within(panel).queryByRole("link", { name: /Open the plan/ })).toBeNull();+ });- fireEvent.click(await screen.findByRole("button", { name: /2 call sites/i }));- expect(await screen.findByText("Refresh the index to materialize the plan")).toBeTruthy();- expect(screen.queryByText("No safe structured plan")).toBeNull();+ it("distinguishes a plan that needs an index refresh from no safe plan", async () => {+ const refresh = page({+ items: [+ opportunity({+ plan_id: null,+ plan_status: "not_persisted",+ plan_reason: "A matching plan can be materialized by reindexing.",+ }),+ ],+ });+ render(+ <PerformanceView adapter={adapter({ getPerformanceOpportunities: async () => refresh })} />,+ );+ await openFirstRow();+ const panel = await screen.findByRole("dialog");+ expect(within(panel).getByText("Needs an index refresh")).toBeTruthy();+ expect(within(panel).queryByText("No safe plan")).toBeNull();});- it("opens the canonical refactoring drawer and agent handoff for an exact plan", async () => {- const exactPlan: RefactoringPlan = {+ it("offers the plan link only after the stored plan names this opportunity", async () => {+ const exact: RefactoringPlan = {id: "plan-1",refactoring_type: "performance_fix",file_path: "src/shared.py",target_symbol: "src/shared.py::load",line_start: 8,line_end: 12,- plan: {- opportunity_id: "opp-1",- strategy: "batch_or_prefetch_io",- safety: "advisory",- intervention_symbol: "src/shared.py::load",- affected_locations: [],- affected_locations_total: 2,- paths: [["src/a.py::run", "src/shared.py::load"]],- paths_total: 1,- evidence_truncated: false,- },+ plan: { opportunity_id: "perf2_planready", strategy: "batch_or_prefetch_io" },evidence: {},impact_delta: 0,effort_bucket: "M",- blast_radius: { file_count: 2, files: ["src/a.py", "src/b.py"] },+ blast_radius: {},confidence: "medium",source_biomarker: "io_in_loop",rank_score: 12.5,- benefit: 4,- leverage: 3,- cost: 2,- risk: 1,};- const exact = adapter();- exact.getRefactoringPlan = vi.fn(async () => exactPlan);- render(<PerformanceView adapter={exact} />);+ render(<PerformanceView adapter={adapter({ getRefactoringPlan: async () => exact })} />);+ await openFirstRow();+ const link = await screen.findByRole("link", { name: "Open the plan on Refactoring" });+ expect(link.getAttribute("href")).toBe("/refactoring?plan=plan-1");+ });- fireEvent.click(await screen.findByRole("button", { name: /Inspect 2 call sites/i }));- expect(await screen.findByText("The change")).toBeTruthy();- expect(screen.getByText("Causal context")).toBeTruthy();- expect(screen.getByRole("button", { name: /Review raw findings/ })).toBeTruthy();- fireEvent.click(screen.getByRole("button", { name: "Copy prompt for an agent" }));- expect(await screen.findByText("AI performance plan")).toBeTruthy();- expect(exact.getRefactoringPlan).toHaveBeenCalledWith("plan-1");+ it("hands over the stored plan for a verified plan, not a re-derive instruction", async () => {+ const exact: RefactoringPlan = {+ id: "plan-1",+ refactoring_type: "performance_fix",+ file_path: "src/shared.py",+ target_symbol: "src/shared.py::load",+ line_start: 8,+ line_end: 12,+ plan: { opportunity_id: "perf2_planready", strategy: "batch_or_prefetch_io" },+ evidence: {},+ impact_delta: 0,+ effort_bucket: "M",+ blast_radius: {},+ confidence: "medium",+ source_biomarker: "io_in_loop",+ rank_score: 12.5,+ };+ render(<PerformanceView adapter={adapter({ getRefactoringPlan: async () => exact })} />);+ await openFirstRow();+ fireEvent.click(await screen.findByRole("button", { name: "Copy the plan for an agent" }));+ expect(await screen.findByText("Structured plan handoff")).toBeTruthy();+ });++ it("falls back to the evidence handoff when no plan was verified", async () => {+ render(<PerformanceView adapter={adapter()} />);+ await openFirstRow();+ fireEvent.click(await screen.findByRole("button", { name: "Copy an agent handoff" }));+ expect(await screen.findByText("Agent handoff")).toBeTruthy();});- it("rejects a fetched plan whose stable opportunity identity does not match", async () => {- const unrelated: RefactoringPlan = {+ it("rejects a stored plan whose opportunity identity does not match", async () => {+ const mismatched: RefactoringPlan = {id: "plan-1",refactoring_type: "performance_fix",file_path: "src/other.py",target_symbol: "src/other.py::work",line_start: null,line_end: null,- plan: { opportunity_id: "different-opportunity" },+ plan: { opportunity_id: "a-different-opportunity" },evidence: {},impact_delta: 0,effort_bucket: "M",@@ -221,19 +377,91 @@ describe("PerformanceView", () => {source_biomarker: "io_in_loop",rank_score: 1,};- const exact = adapter();- exact.getRefactoringPlan = vi.fn(async () => unrelated);- render(<PerformanceView adapter={exact} />);+ render(<PerformanceView adapter={adapter({ getRefactoringPlan: async () => mismatched })} />);+ await openFirstRow();+ expect(await screen.findByText(/no longer names this opportunity/)).toBeTruthy();+ expect(screen.queryByRole("link", { name: "Open the plan on Refactoring" })).toBeNull();+ });++ it("keeps raw observations behind a click and pages them from the server", async () => {+ const getFindings = vi.fn(async () => ({+ items: [+ {+ id: "finding_1111",+ dimension: "performance" as const,+ biomarker_type: "io_in_loop",+ severity: "medium" as const,+ health_impact: 0,+ file_path: "src/a.py",+ function_name: "run",+ line_start: 10,+ line_end: 10,+ reason: "Database work repeats.",+ details: {},+ status: "open",+ },+ ],+ total: 6,+ has_more: true,+ next_offset: 1,+ }));+ render(+ <PerformanceView adapter={adapter({ getPerformanceOpportunityFindings: getFindings })} />,+ );+ await openFirstRow();+ expect(getFindings).not.toHaveBeenCalled();+ fireEvent.click(await screen.findByRole("button", { name: /Read the raw observations/ }));+ await waitFor(() =>+ expect(getFindings).toHaveBeenCalledWith("perf2_planready", { offset: 0, limit: 50 }),+ );+ });++ it("states the preview bound when the host cannot page observations", async () => {+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunityFindings: undefined })} />);+ await openFirstRow();+ fireEvent.click(await screen.findByRole("button", { name: /Read the raw observations/ }));+ expect(await screen.findByText(/does not page the remaining observations/)).toBeTruthy();+ });+});++describe("PerformanceView compatibility", () => {+ it("collapses production and tooling only when the server predates the vocabulary", async () => {+ const load = vi.fn(async () => legacyPage());+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: load })} />);+ await rows();+ expect(screen.getByRole("tab", { name: /Production & tooling/ })).toBeTruthy();+ expect(screen.queryByRole("tab", { name: /Unclassified/ })).toBeNull();+ expect(screen.queryByLabelText("Boundary")).toBeNull();++ fireEvent.click(screen.getByRole("tab", { name: /Production & tooling/ }));+ await waitFor(() =>+ expect(load).toHaveBeenLastCalledWith(+ expect.objectContaining({ context: "production_tooling" }),+ ),+ );+ });- fireEvent.click(await screen.findByRole("button", { name: /Inspect 2 call sites/i }));- expect(await screen.findByText(/returned plan no longer matches this opportunity/)).toBeTruthy();- expect(screen.queryByRole("button", { name: "Copy prompt for an agent" })).toBeNull();+ it("re-asks with the spelling an older server accepts when a link restored a context", async () => {+ const load = vi.fn(async () => legacyPage());+ render(+ <PerformanceView+ adapter={adapter({ getPerformanceOpportunities: load })}+ initialFilters="context=production"+ />,+ );+ await rows();+ // The first request cannot know the vocabulary, so the correction is a+ // second request rather than a queue left answering the wrong question.+ await waitFor(() =>+ expect(load).toHaveBeenLastCalledWith(+ expect.objectContaining({ context: "production_tooling" }),+ ),+ );});- it("falls back to bounded raw findings when an older server lacks grouping", async () => {- const unavailable = Object.assign(new Error("Not found"), { status: 404 });- const legacy = adapter(vi.fn(async () => Promise.reject(unavailable)));- legacy.listFindings = vi.fn(async () => [+ it("falls back to bounded raw findings when the endpoint is absent", async () => {+ const missing = Object.assign(new Error("Not found"), { status: 404 });+ const listFindings = vi.fn(async () => [{id: "finding-legacy",dimension: "performance" as const,@@ -249,10 +477,64 @@ describe("PerformanceView", () => {status: "open",},]);- render(<PerformanceView adapter={legacy} />);-+ render(+ <PerformanceView+ adapter={adapter({+ getPerformanceOpportunities: async () => {+ throw missing;+ },+ listFindings,+ })}+ />,+ );expect(await screen.findByText("Raw performance findings")).toBeTruthy();- expect(legacy.listFindings).toHaveBeenCalledWith({ dimension: "performance", limit: 100 });- expect(screen.queryByText("No safe structured plan")).toBeNull();+ expect(listFindings).toHaveBeenCalledWith({ dimension: "performance", limit: 100 });+ });++ it("restores a shared filter state and reports every change back to the host", async () => {+ const load = vi.fn(async () => page());+ const onFiltersChange = vi.fn();+ render(+ <PerformanceView+ adapter={adapter({ getPerformanceOpportunities: load })}+ initialFilters="context=test&boundary=db"+ onFiltersChange={onFiltersChange}+ />,+ );+ await waitFor(() =>+ expect(load).toHaveBeenLastCalledWith(+ expect.objectContaining({ context: "test", boundary: "db" }),+ ),+ );+ fireEvent.click(screen.getByRole("tab", { name: /Production 4/ }));+ await waitFor(() =>+ expect(onFiltersChange).toHaveBeenLastCalledWith("context=production&boundary=db"),+ );+ });+});++describe("PerformanceView accessibility", () => {+ it("opens a row from the keyboard and names it", async () => {+ render(<PerformanceView adapter={adapter()} />);+ const [first] = await rows();+ expect(first!.getAttribute("tabindex")).toBe("0");+ expect(first!.getAttribute("aria-label")).toBe("Inspect Database call inside a loop");+ fireEvent.keyDown(first!, { key: "Enter" });+ expect(await screen.findByRole("dialog")).toBeTruthy();+ });++ it("names every filter control and the row overflow", async () => {+ render(<PerformanceView adapter={adapter()} />);+ await rows();+ expect(screen.getByLabelText("Boundary")).toBeTruthy();+ expect(screen.getByLabelText("Actionability")).toBeTruthy();+ expect(screen.getAllByRole("button", { name: /More actions for/ }).length).toBeGreaterThan(0);+ });++ it("announces the rendered scope through a status region", async () => {+ render(<PerformanceView adapter={adapter()} />);+ await rows();+ const statuses = screen.getAllByRole("status").map((node) => node.textContent ?? "");+ expect(statuses.some((text) => text.includes("opportunities"))).toBe(true);});});diff --git a/packages/ui/src/health/code-health-adapter.ts b/packages/ui/src/health/code-health-adapter.tsindex 81e6c8a69..eb85f89b7 100644--- a/packages/ui/src/health/code-health-adapter.ts+++ b/packages/ui/src/health/code-health-adapter.ts@@ -7,7 +7,9 @@ import type {HealthOverviewResponse,HealthWorkQueueQuery,HealthWorkQueueResponse,+ PerformanceOpportunityDetail,PerformanceOpportunityPage,+ PerformanceOpportunityQuery,TestsReachingFile,} from "@repowise-dev/types/health";import type { Paginated } from "@repowise-dev/types";@@ -50,11 +52,18 @@ export interface CodeHealthAdapter {getOverview(limit: number): Promise<HealthOverviewResponse>;listFindings(opts?: CodeHealthFindingsQuery): Promise<HealthFinding[]>;- getPerformanceOpportunities?(opts?: {- context?: "production_tooling" | "test" | "all";- limit?: number;- offset?: number;- }): Promise<PerformanceOpportunityPage>;+ getPerformanceOpportunities?(+ opts?: PerformanceOpportunityQuery,+ ): Promise<PerformanceOpportunityPage>;+ /**+ * One opportunity by its stable id. Optional: a host that has not wired it+ * renders the row it already holds and says so, rather than claiming a+ * lifecycle and analyzed commit it never read.+ */+ getPerformanceOpportunity?(+ opportunityId: string,+ opts?: { evidenceLimit?: number; evidenceOffset?: number },+ ): Promise<PerformanceOpportunityDetail>;getPerformanceOpportunityFindings?(opportunityId: string,opts?: { limit?: number; offset?: number },diff --git a/packages/ui/src/health/performance-view.tsx b/packages/ui/src/health/performance-view.tsxindex 07b8d344f..619435a2b 100644--- a/packages/ui/src/health/performance-view.tsx+++ b/packages/ui/src/health/performance-view.tsx@@ -1,152 +1,141 @@"use client";-import { useState } from "react";+import { useEffect, useMemo, useState } from "react";import useSWR from "swr";-import { Gauge, ChevronRight, Sparkles } from "lucide-react";import type {- HealthFinding,+ PerformanceContextFilter,PerformanceOpportunity,- PerformanceOpportunityEvidence,PerformanceOpportunityPage,} from "@repowise-dev/types/health";import type { RefactoringPlan } from "@repowise-dev/types/refactoring";-import { EmptyState } from "../shared/empty-state";import { PageLede } from "../shared/page-lede";import { PaginationControls } from "../shared/pagination-controls";-import { ProvenancePathList } from "../shared/provenance-path-list";-import { ViewTabs } from "../shared/view-tabs";-import { Sheet, SheetContent, SheetTitle } from "../ui/sheet";import { StatRibbon } from "../stats/stat-ribbon";-import { RefactoringDrawer } from "../refactoring/refactoring-drawer";-import { performancePlanDetail } from "../refactoring/types";-import { PERF_BOUNDARY_LABEL } from "@repowise-dev/types/health";-import { biomarkerLabel } from "./biomarker-glossary";-import { BiomarkerList } from "./biomarker-list";-import type { CodeHealthAdapter } from "./code-health-adapter";import { AiPromptModal } from "./ai-prompt-modal";import {buildPerformanceOpportunityPrompt,buildRefactoringPlanPrompt,} from "./ai-prompt-builder";+import type { PerformanceViewAdapter } from "./performance/adapter";+import { capabilitiesOf } from "./performance/capabilities";+import { OpportunityDrawer } from "./performance/drawer";+import { ContextHint, ContextTabs, QueueFilters, ScopeLine } from "./performance/filters";+import { LegacyPerformanceFindings } from "./performance/legacy";+import { OpportunityQueue } from "./performance/queue";+import {+ clearNarrowing,+ INITIAL_FILTERS,+ narrowingCount,+ parseFilters,+ serializeFilters,+ toQuery,+ withFilter,+ type NarrowingKey,+ type PerformanceFilterState,+} from "./performance/query";+import {+ EmptyQueue,+ FilteredEmpty,+ IgnoredArgumentsNotice,+ QueueError,+ QueueSkeleton,+ StaleModelNotice,+ UnavailableQueue,+} from "./performance/states";-export type PerformanceViewAdapter = Pick<- CodeHealthAdapter,- | "cacheKey"- | "listFindings"- | "getPerformanceOpportunities"- | "getPerformanceOpportunityFindings"- | "getRefactoringPlan"- | "refactoringPlanHref"- | "fileHref"- | "symbolHref"- | "navigate"->;--const PAGE_SIZE = 20;-const RAW_PAGE_SIZE = 50;-type ContextView = "production_tooling" | "test";--const CONTEXT_LABEL: Record<PerformanceOpportunity["execution_context"], string> = {- production: "Production",- tooling: "Tooling",- test: "Test suite",- unknown: "Unclassified",-};+/**+ * The Performance tab: which repeated cost is worth an intervention, why it+ * ranks where it does, and what evidence stands behind it.+ *+ * Composition and state only. Grouping, ranking, filtering, paging, facet+ * counts, and plan linkage are all decided by the server, so this surface and+ * the agent surface cannot disagree about what one opportunity is.+ */-function contextLabel(context: PerformanceOpportunity["execution_context"]): string {- return CONTEXT_LABEL[context] ?? "Unclassified";-}+export type { PerformanceViewAdapter };-function opportunityTitle(opportunity: PerformanceOpportunity): string {- const boundary = opportunity.boundary_kind- ? PERF_BOUNDARY_LABEL[opportunity.boundary_kind].toLowerCase()- : "repeated";- if (opportunity.terminal_sink) {- return `${biomarkerLabel(opportunity.biomarker_type)} reaches ${opportunity.terminal_sink}`;- }- return `${biomarkerLabel(opportunity.biomarker_type)} in ${boundary} work`;-}+const PAGE_SIZE = 20;-export function PerformanceView({ adapter }: { adapter: PerformanceViewAdapter }) {- const [context, setContext] = useState<ContextView>("production_tooling");- const [offset, setOffset] = useState(0);+export function PerformanceView({+ adapter,+ initialFilters,+ onFiltersChange,+}: {+ adapter: PerformanceViewAdapter;+ /** A serialized filter state, so a shared link opens the same queue. */+ initialFilters?: string | undefined;+ /** Called with the serialized state whenever a filter moves. */+ onFiltersChange?: ((search: string) => void) | undefined;+}) {+ const [filters, setFilters] = useState<PerformanceFilterState>(() =>+ initialFilters ? parseFilters(initialFilters) : INITIAL_FILTERS,+ );const [selected, setSelected] = useState<PerformanceOpportunity | null>(null);- const [promptPlan, setPromptPlan] = useState<RefactoringPlan | null>(null);- const [promptOpportunity, setPromptOpportunity] = useState<PerformanceOpportunity | null>(null);+ // The handoff carries the verified plan when the drawer proved one, so a+ // plan-ready row hands over the ready payload rather than an instruction to+ // re-derive it.+ const [promptFor, setPromptFor] = useState<{+ opportunity: PerformanceOpportunity;+ plan: RefactoringPlan | null;+ } | null>(null);++ const apply = (next: PerformanceFilterState) => {+ setFilters(next);+ onFiltersChange?.(serializeFilters(next));+ };const load = adapter.getPerformanceOpportunities;- const { data, error, isLoading } = useSWR<PerformanceOpportunityPage>(- load ? `performance-opportunities:${adapter.cacheKey}:${context}:${offset}` : null,- () => load!({ context, offset, limit: PAGE_SIZE }),+ // What a response proved this server understands. It is part of the cache key+ // so that learning it re-asks with the spelling the server accepts: a shared+ // link can restore a production or tooling context before any response has+ // been seen. It only ever flips for a server that predates the vocabulary, so+ // a current one never pays for the correction.+ const [collapse, setCollapse] = useState(false);+ const key = `${collapse ? "legacy:" : ""}${serializeFilters(filters)}`;+ const { data, error, isLoading, mutate } = useSWR<PerformanceOpportunityPage>(+ load ? `performance-opportunities:${adapter.cacheKey}:${key}` : null,+ () => load!(toQuery(filters, { limit: PAGE_SIZE, collapseContexts: collapse })),{ revalidateOnFocus: false, keepPreviousData: true },);- const selectedPlanId = selected?.plan_id ?? null;- const {- data: selectedPlan,- error: selectedPlanError,- isLoading: selectedPlanLoading,- } = useSWR<RefactoringPlan>(- selectedPlanId && adapter.getRefactoringPlan- ? `performance-plan:${adapter.cacheKey}:${selectedPlanId}`- : null,- () => adapter.getRefactoringPlan!(selectedPlanId!),- { revalidateOnFocus: false },- );- const selectedPlanMatches = Boolean(- selectedPlan &&- selected &&- selectedPlan.id === selected.plan_id &&- selectedPlan.refactoring_type === "performance_fix" &&- performancePlanDetail(selectedPlan).opportunityId === selected.opportunity_id,- );- if (!load) {- return <LegacyPerformanceFindings adapter={adapter} />;- }+ const capabilities = useMemo(() => capabilitiesOf(adapter, data), [adapter, data]);+ useEffect(() => {+ if (data) setCollapse(!capabilitiesOf(adapter, data).canonicalContexts);+ }, [adapter, data]);++ if (!load) return <LegacyPerformanceFindings adapter={adapter} />;if (error && [404, 405].includes(Number((error as { status?: number }).status))) {return <LegacyPerformanceFindings adapter={adapter} />;}- if (error) {- return (- <EmptyState- icon={<Gauge className="h-6 w-6" />}- title="Couldn’t load performance opportunities"- description="The repository may need indexing, or the server may be temporarily unavailable."- />- );- }- if (isLoading && !data) {- return (- <div className="space-y-8">- <div className="h-32 animate-pulse bg-[var(--color-bg-surface)]" />- <div className="h-12 animate-pulse bg-[var(--color-bg-surface)]" />- <div className="h-72 animate-pulse bg-[var(--color-bg-surface)]" />- </div>- );- }+ if (error) return <QueueError onRetry={() => void mutate()} />;+ if (isLoading && !data) return <QueueSkeleton />;if (!data) return null;- const { summary } = data;- const productionToolingTotal = summary.production_total + summary.tooling_total;+ const { summary, facets } = data;+ const narrowed = narrowingCount(filters);+ const filtered = narrowed > 0 || filters.context !== "all";++ if (summary.status === "unavailable") return <UnavailableQueue summary={summary} />;+const stats = [{- label: "Production",- value: summary.production_total.toLocaleString(),- sub: "runtime paths",+ label: "Plan ready",+ value: (summary.actionability?.plan_ready ?? 0).toLocaleString(),+ sub: "a named safe intervention",},{- label: "Tooling",- value: summary.tooling_total.toLocaleString(),- sub: "build and developer paths",+ label: "Advisory",+ value: (summary.actionability?.advisory ?? 0).toLocaleString(),+ sub: "coherent, not proven safe",},{- label: "Test suite",- value: summary.test_total.toLocaleString(),- sub: "test execution cost",+ label: "Needs investigation",+ value: (summary.actionability?.investigate ?? 0).toLocaleString(),+ sub: "read the evidence first",},{- label: "Structured plan",+ label: "With a stored plan",value: summary.with_plan_total.toLocaleString(),sub: `of ${summary.total.toLocaleString()} causes`,},@@ -158,7 +147,7 @@ export function PerformanceView({ adapter }: { adapter: PerformanceViewAdapter }<PageLedelabel="Causal opportunities"value={summary.total.toLocaleString()}- unit="ranked root causes, not duplicated observations"+ unit="ranked causes, not repeated observations"layout="beside"figureFooter={<p className="text-caption text-[var(--color-text-tertiary)]">@@ -167,12 +156,12 @@ export function PerformanceView({ adapter }: { adapter: PerformanceViewAdapter }}><p>- Repeated caller paths are folded into one cause so the first row answers what should- change once, while every raw line finding stays available as evidence.+ Repeated caller paths fold into one cause, so the first row answers what to change+ once while every raw observation stays readable as evidence.</p><p>- Production and tooling stay separate from test-suite cost. A structured plan appears- only when the analysis can name an intervention without guessing.+ Evidence confidence, actionability, and fix safety are three separate judgements. A+ path the analysis resolved well is not automatically a change worth making.</p></PageLede><StatRibbon stats={stats} />@@ -184,423 +173,114 @@ export function PerformanceView({ adapter }: { adapter: PerformanceViewAdapter }Opportunity queue</h2><p className="mt-1 max-w-[72ch] text-sm text-[var(--color-text-secondary)]">- Ordered by the canonical causal score: multiplier shape, boundary, execution context,- entry reachability, affected call sites, and resolution provenance.+ Ranked with the actionable work first. Filters and their counts come from the server,+ so narrowing one never hides the alternatives to it.</p></div>- <ViewTabs- tabs={[- {- id: "production_tooling",- label: "Production & tooling",- badge: productionToolingTotal,- },- { id: "test", label: "Test suite", badge: summary.test_total },- ]}- value={context}- onValueChange={(value) => {- setOffset(0);- setContext(value as ContextView);- }}++ {summary.status === "stale_model" ? <StaleModelNotice summary={summary} /> : null}+ {data.ignored_arguments ? (+ <IgnoredArgumentsNotice ignored={data.ignored_arguments} />+ ) : null}++ <ContextTabs+ value={filters.context}+ facets={facets}+ total={summary.total}+ collapsed={!capabilities.canonicalContexts}+ onChange={(context: PerformanceContextFilter) =>+ apply(withFilter(filters, "context", context))+ }+ />+ <ContextHint context={filters.context} />++ {capabilities.serverFacets ? (+ <QueueFilters+ filters={filters}+ facets={facets}+ onChange={(key: NarrowingKey, value) =>+ apply(withFilter(filters, key, value as never))+ }+ onClear={() => apply(clearNarrowing(filters))}+ />+ ) : null}++ <ScopeLine+ filteredTotal={data.total}+ repositoryTotal={summary.total}+ context={filters.context}+ narrowed={narrowed}+ analyzedCommit={summary.analyzed_commit}/>{data.items.length === 0 ? (- <div className="border-t border-[var(--color-border-default)] py-10 text-center">- <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">- No causal opportunities in this context- </h3>- <p className="mx-auto mt-1.5 max-w-[60ch] text-sm text-[var(--color-text-tertiary)]">- A supported performance detector must find a repeated cost shape before this queue- fills. This does not claim the code is fast.- </p>- </div>+ filtered ? (+ <FilteredEmpty onClear={() => apply({ ...clearNarrowing(filters), context: "all" })} />+ ) : (+ <EmptyQueue />+ )) : (- <div className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">- {data.items.map((opportunity) => (- <OpportunityRow- key={opportunity.opportunity_id}- opportunity={opportunity}- onOpen={() => setSelected(opportunity)}- />- ))}- </div>+ <OpportunityQueue+ items={data.items}+ facets={facets}+ adapter={adapter}+ showSections={filters.actionability === null}+ selectedId={selected?.opportunity_id ?? null}+ onInspect={setSelected}+ />)}<PaginationControls- offset={offset}+ offset={filters.offset}shown={data.items.length}total={data.total}label="opportunities"- onPrevious={offset > 0 ? () => setOffset(Math.max(0, offset - PAGE_SIZE)) : undefined}- onNext={data.next_offset != null ? () => setOffset(data.next_offset!) : undefined}- />- </section>-- {selectedPlanId && adapter.getRefactoringPlan ? (- <RefactoringDrawer- plan={selectedPlanMatches ? (selectedPlan ?? null) : null}- loading={selectedPlanLoading}- error={- selectedPlanError- ? "The exact plan could not be loaded. Close this drawer and retry from the queue."- : selectedPlan && !selectedPlanMatches- ? "The returned plan no longer matches this opportunity. Reindex before handing it to an agent."+ onPrevious={+ filters.offset > 0+ ? () => apply(withFilter(filters, "offset", Math.max(0, filters.offset - PAGE_SIZE))): undefined}- open={selected !== null}- onOpenChange={(open) => {- if (!open) setSelected(null);- }}- onAiPrompt={(plan) => {- if (selectedPlanMatches) setPromptPlan(plan);- }}- contextSlot={- selected ? <OpportunityCausalEvidence opportunity={selected} adapter={adapter} /> : null+ onNext={+ data.next_offset != null+ ? () => apply(withFilter(filters, "offset", data.next_offset!))+ : undefined}- fileHref={(path, line) => {- const href = adapter.fileHref(path);- return line ? `${href}${href.includes("?") ? "&" : "?"}line=${line}` : href;- }}- />- ) : (- <PerformanceOpportunityDrawer- opportunity={selected}- adapter={adapter}- onClose={() => setSelected(null)}- onAiPrompt={setPromptOpportunity}/>- )}+ </section>++ <OpportunityDrawer+ opportunity={selected}+ adapter={adapter}+ detailEnabled={capabilities.detailById}+ planEnabled={capabilities.planById}+ onClose={() => setSelected(null)}+ onAgentHandoff={(opportunity, plan) => setPromptFor({ opportunity, plan })}+ /><AiPromptModal- open={promptPlan !== null || promptOpportunity !== null}+ open={promptFor !== null}onOpenChange={(open) => {- if (!open) {- setPromptPlan(null);- setPromptOpportunity(null);- }+ if (!open) setPromptFor(null);}}getPrompt={- promptPlan- ? (flavor) => buildRefactoringPlanPrompt({ plan: promptPlan, flavor })- : promptOpportunity+ promptFor?.plan+ ? (flavor) => buildRefactoringPlanPrompt({ plan: promptFor.plan!, flavor })+ : promptFor? (flavor) =>- buildPerformanceOpportunityPrompt({ opportunity: promptOpportunity, flavor })+ buildPerformanceOpportunityPrompt({+ opportunity: promptFor.opportunity,+ flavor,+ }): null}- filePath={promptPlan?.file_path ?? promptOpportunity?.evidence[0]?.file_path ?? null}- title={promptPlan ? "AI performance plan" : "AI performance investigation"}+ filePath={promptFor?.plan?.file_path ?? promptFor?.opportunity.file_path ?? null}+ title={promptFor?.plan ? "Structured plan handoff" : "Agent handoff"}description={- promptPlan- ? "A ready-to-paste structured plan with the intervention, affected targets, validation, and completion contract."- : "A ready-to-paste evidence handoff that asks an agent to verify the cause before proposing any edit."+ promptFor?.plan+ ? "The stored plan for this exact opportunity, with its intervention, affected targets, and validation contract."+ : "A ready-to-paste evidence handoff that asks an agent to verify the cause against the source before proposing any edit."}/></div>);}--function LegacyPerformanceFindings({ adapter }: { adapter: PerformanceViewAdapter }) {- const { data, error, isLoading } = useSWR<HealthFinding[]>(- `performance-findings-legacy:${adapter.cacheKey}`,- () => adapter.listFindings({ dimension: "performance", limit: 100 }),- { revalidateOnFocus: false },- );- if (isLoading) return <div className="h-72 animate-pulse bg-[var(--color-bg-surface)]" />;- if (error || !data?.length) {- return (- <EmptyState- icon={<Gauge className="h-6 w-6" />}- title="No performance opportunities"- description="This older server does not provide causal grouping. Reindex with a current server to distinguish an empty result from unsupported grouping."- />- );- }- return (- <div className="space-y-5">- <div>- <h2 className="text-lg font-semibold text-[var(--color-text-primary)]">- Raw performance findings- </h2>- <p className="mt-1 max-w-[72ch] text-sm text-[var(--color-text-secondary)]">- This server predates causal opportunity groups. Up to 100 canonical findings are shown- without inventing plan links or rank semantics.- </p>- </div>- <BiomarkerList- findings={data}- grouped- onSelect={(finding) => adapter.navigate(adapter.fileHref(finding.file_path))}- />- </div>- );-}--function OpportunityRow({- opportunity,- onOpen,-}: {- opportunity: PerformanceOpportunity;- onOpen: () => void;-}) {- const boundary = opportunity.boundary_kind- ? PERF_BOUNDARY_LABEL[opportunity.boundary_kind]- : "Local computation";-- return (- <article data-performance-opportunity={opportunity.opportunity_id}>- <button- type="button"- onClick={onOpen}- aria-label={`Inspect ${opportunity.affected_call_sites_total} call sites for ${opportunityTitle(opportunity)}`}- className="grid w-full grid-cols-[18px_minmax(0,1fr)] gap-3 px-2 py-4 text-left hover:bg-[var(--color-bg-elevated)] sm:grid-cols-[18px_minmax(0,1fr)_auto] sm:items-center"- >- <ChevronRight className="mt-1 h-4 w-4" />- <span className="min-w-0">- <span className="block break-words text-[15px] font-semibold text-[var(--color-text-primary)]">- {opportunityTitle(opportunity)}- </span>- <span className="mt-1 block text-xs text-[var(--color-text-secondary)]">- {boundary} · {contextLabel(opportunity.execution_context)} ·{" "}- {opportunity.confidence[0]!.toUpperCase() + opportunity.confidence.slice(1)} confidence- </span>- </span>- <span className="col-start-2 text-xs tabular-nums text-[var(--color-text-tertiary)] sm:col-auto sm:text-right">- {opportunity.affected_call_sites_total.toLocaleString()} call site- {opportunity.affected_call_sites_total === 1 ? "" : "s"}- <br />- {opportunity.affected_files_total.toLocaleString()} file- {opportunity.affected_files_total === 1 ? "" : "s"}- <span- className={`mt-1 block font-medium ${- opportunity.plan_id- ? "text-[var(--color-success)]"- : "text-[var(--color-text-tertiary)]"- }`}- >- {opportunity.plan_id- ? "Structured plan ready"- : opportunity.plan_status === "not_persisted"- ? "Index refresh needed"- : "Investigation needed"}- </span>- </span>- </button>-- </article>- );-}--function OpportunityCausalEvidence({- opportunity,- adapter,-}: {- opportunity: PerformanceOpportunity;- adapter: PerformanceViewAdapter;-}) {- const paths = opportunity.evidence- .filter((item) => item.path.length > 0)- .map((item) => ({ nodes: item.path, provenance: item.provenance }));- return (- <div className="space-y-6">- <section>- <h4 className="mb-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">- Causal context- </h4>- <p className="text-sm leading-relaxed text-[var(--color-text-secondary)]">- {contextLabel(opportunity.execution_context)} · {opportunity.confidence} confidence ·{" "}- {opportunity.provenance.replaceAll("-", " ")} provenance.{" "}- {opportunity.intervention_symbol ? (- <>- Repeated work converges at{" "}- <span className="break-all font-mono text-xs text-[var(--color-text-primary)]">- {opportunity.intervention_symbol}- </span>- .- </>- ) : (- <>The paths share a costly sink, but no safe common intervention was proven.</>- )}- </p>- </section>- <section>- <h4 className="mb-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">- Caller-to-sink paths- </h4>- <ProvenancePathList- paths={paths}- total={opportunity.observations_total}- fileHref={adapter.fileHref}- symbolHref={adapter.symbolHref}- />- </section>- <RawEvidence opportunity={opportunity} adapter={adapter} />- </div>- );-}--function PerformanceOpportunityDrawer({- opportunity,- adapter,- onClose,- onAiPrompt,-}: {- opportunity: PerformanceOpportunity | null;- adapter: PerformanceViewAdapter;- onClose: () => void;- onAiPrompt: (opportunity: PerformanceOpportunity) => void;-}) {- const planHref = opportunity?.plan_id- ? adapter.refactoringPlanHref?.(opportunity.plan_id, opportunity.opportunity_id)- : undefined;-- return (- <Sheet open={opportunity !== null} onOpenChange={(open) => !open && onClose()}>- <SheetContent- side="right"- closeLabel="Close opportunity"- className="w-full max-w-[680px] sm:w-[92vw]"- >- {opportunity ? (- <>- <div className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12">- <div className="text-[11px] text-[var(--color-text-secondary)]">- Causal performance opportunity- </div>- <SheetTitle className="mt-0.5 break-words text-[15px] font-semibold text-[var(--color-text-primary)]">- {opportunityTitle(opportunity)}- </SheetTitle>- <p className="mt-1 text-[11.5px] text-[var(--color-text-tertiary)]">- {contextLabel(opportunity.execution_context)} · {opportunity.confidence} confidence ·{" "}- {opportunity.affected_call_sites_total} call sites- </p>- </div>-- <div className="flex-1 space-y-6 overflow-y-auto px-5 py-5">- <OpportunityCausalEvidence opportunity={opportunity} adapter={adapter} />-- <section>- <h4 className="mb-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">- Recommended next step- </h4>- <p className="text-sm font-medium text-[var(--color-text-primary)]">- {opportunity.plan_status === "not_persisted"- ? "Refresh the index to materialize the plan"- : opportunity.plan_id- ? "Review the matching structured plan"- : "No safe structured plan — investigate before changing code"}- </p>- <p className="mt-1 text-sm text-[var(--color-text-tertiary)]">- {opportunity.plan_reason}- </p>- {planHref ? (- <a- href={planHref}- className="mt-2 inline-block text-sm font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline"- >- Open on Refactoring page- </a>- ) : null}- </section>- </div>-- <div className="flex items-center gap-3 border-t border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-5 py-3.5">- <button- type="button"- onClick={() => onAiPrompt(opportunity)}- className="inline-flex items-center justify-center gap-2 rounded-lg bg-[var(--color-accent-fill)] px-3.5 py-2 text-sm font-semibold text-[var(--color-text-on-accent)] transition-opacity hover:opacity-90"- >- <Sparkles className="h-4 w-4" />- Copy investigation for an agent- </button>- </div>- </>- ) : (- <SheetTitle className="sr-only">Performance opportunity</SheetTitle>- )}- </SheetContent>- </Sheet>- );-}--function RawEvidence({- opportunity,- adapter,-}: {- opportunity: PerformanceOpportunity;- adapter: PerformanceViewAdapter;-}) {- const [open, setOpen] = useState(false);- const [offset, setOffset] = useState(0);- const load = adapter.getPerformanceOpportunityFindings;- const { data, isLoading } = useSWR(- open && load- ? `performance-raw:${adapter.cacheKey}:${opportunity.opportunity_id}:${offset}`- : null,- () => load!(opportunity.opportunity_id, { offset, limit: RAW_PAGE_SIZE }),- { revalidateOnFocus: false, keepPreviousData: true },- );- const fallback = opportunity.evidence;- const items: Array<HealthFinding | PerformanceOpportunityEvidence> = data?.items ?? fallback;- const total = data?.total ?? opportunity.observations_total;-- return (- <section>- <button- type="button"- onClick={() => setOpen((value) => !value)}- aria-expanded={open}- className="text-sm font-medium text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-text-primary)] hover:underline"- >- {open ? "Hide" : "Review"} raw findings · {total.toLocaleString()} observation- {total === 1 ? "" : "s"}- </button>- {open ? (- <div className="mt-3">- {isLoading && !data ? (- <div className="h-24 animate-pulse bg-[var(--color-bg-surface)]" />- ) : (- <div className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">- {items.map((finding, index) => {- const href = adapter.fileHref(finding.file_path);- return (- <div- key={("id" in finding ? finding.id : finding.finding_id) || index}- className="py-3"- >- <a- href={href}- className="break-all font-mono text-xs text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-accent-primary)] hover:underline"- >- {finding.file_path}- {finding.line_start ? `:${finding.line_start}` : ""}- </a>- <p className="mt-1 text-sm text-[var(--color-text-secondary)]">- {finding.reason}- </p>- </div>- );- })}- </div>- )}- {data ? (- <PaginationControls- offset={offset}- shown={data.items.length}- total={data.total}- label="raw findings"- onPrevious={- offset > 0 ? () => setOffset(Math.max(0, offset - RAW_PAGE_SIZE)) : undefined- }- onNext={data.next_offset != null ? () => setOffset(data.next_offset!) : undefined}- />- ) : opportunity.evidence_truncated ? (- <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">- {fallback.length.toLocaleString()} shown of {total.toLocaleString()}; connect the- paged evidence endpoint to load the rest.- </p>- ) : null}- </div>- ) : null}- </section>- );-}diff --git a/packages/ui/src/health/performance/adapter.ts b/packages/ui/src/health/performance/adapter.tsnew file mode 100644index 000000000..99d98c36b--- /dev/null+++ b/packages/ui/src/health/performance/adapter.ts@@ -0,0 +1,21 @@+import type { CodeHealthAdapter } from "../code-health-adapter";++/**+ * What the Performance tab asks of its host: data and links, nothing about+ * where it is deployed. A host that cannot answer one of the optional members+ * gets an honest fallback, which is why they are narrowed from the canonical+ * adapter rather than redeclared here.+ */+export type PerformanceViewAdapter = Pick<+ CodeHealthAdapter,+ | "cacheKey"+ | "listFindings"+ | "getPerformanceOpportunities"+ | "getPerformanceOpportunity"+ | "getPerformanceOpportunityFindings"+ | "getRefactoringPlan"+ | "refactoringPlanHref"+ | "fileHref"+ | "symbolHref"+ | "navigate"+>;diff --git a/packages/ui/src/health/performance/capabilities.ts b/packages/ui/src/health/performance/capabilities.tsnew file mode 100644index 000000000..b10181c87--- /dev/null+++ b/packages/ui/src/health/performance/capabilities.ts@@ -0,0 +1,41 @@+import type { PerformanceOpportunityPage } from "@repowise-dev/types/health";++import type { PerformanceViewAdapter } from "./adapter";++/**+ * What this server and this host can actually answer.+ *+ * Derived from the response and the adapter, never from a deployment flag. A+ * capability that is missing produces an honest fallback and says so, rather+ * than a control that cannot act.+ */+export interface PerformanceCapabilities {+ /** The server counts the filter vocabulary, so filters can be server-owned. */+ serverFacets: boolean;+ /**+ * The server speaks the four-context vocabulary. When false the tab collapses+ * Production and Tooling into the retired pairing, which is the only case in+ * which that spelling is sent.+ */+ canonicalContexts: boolean;+ /** The host can fetch one opportunity by id, with lifecycle and model state. */+ detailById: boolean;+ /** The host can page raw observations beyond the ones carried on the row. */+ pagedEvidence: boolean;+ /** The host can resolve the exact plan behind a plan id. */+ planById: boolean;+}++export function capabilitiesOf(+ adapter: PerformanceViewAdapter,+ page: PerformanceOpportunityPage | undefined,+): PerformanceCapabilities {+ const facets = page?.facets;+ return {+ serverFacets: Boolean(facets && Object.keys(facets).length > 0),+ canonicalContexts: typeof page?.summary?.status === "string",+ detailById: typeof adapter.getPerformanceOpportunity === "function",+ pagedEvidence: typeof adapter.getPerformanceOpportunityFindings === "function",+ planById: typeof adapter.getRefactoringPlan === "function",+ };+}diff --git a/packages/ui/src/health/performance/drawer.tsx b/packages/ui/src/health/performance/drawer.tsxnew file mode 100644index 000000000..2af38a6d6--- /dev/null+++ b/packages/ui/src/health/performance/drawer.tsx@@ -0,0 +1,374 @@+"use client";++import useSWR from "swr";+import { Sparkles } from "lucide-react";+import type {+ PerformanceOpportunity,+ PerformanceOpportunityDetail,+ PerformanceModelState,+} from "@repowise-dev/types/health";+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";++import { AdaptivePanel } from "../../shared/adaptive-panel";+import { ProvenancePathList } from "../../shared/provenance-path-list";+import { performancePlanDetail } from "../../refactoring/types";+import type { PerformanceViewAdapter } from "./adapter";+import { RawObservations } from "./evidence";+import {+ ACTIONABILITY_LABEL,+ affectedSummary,+ agentHandoffCall,+ boundaryLabel,+ CONFIDENCE_LABEL,+ contextLabel,+ humanizeToken,+ opportunityEvidenceLine,+ opportunityTitle,+ planPresentation,+ whyRankedLabel,+} from "./presentation";++/**+ * One opportunity in depth.+ *+ * The three judgements the analysis makes separately are shown separately:+ * how well the evidence resolved, whether reducing the work is likely valid,+ * and whether one named transformation is safe. Collapsing them would let+ * strong evidence read as a safe fix.+ */++function Field({+ label,+ value,+ detail,+}: {+ label: string;+ value: string;+ detail?: string | undefined;+}) {+ return (+ <div className="min-w-0">+ <dt className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {label}+ </dt>+ <dd className="mt-0.5 text-sm font-medium text-[var(--color-text-primary)]">{value}</dd>+ {detail ? (+ <dd className="mt-0.5 text-xs text-[var(--color-text-tertiary)]">{detail}</dd>+ ) : null}+ </div>+ );+}++function Section({ title, children }: { title: string; children: React.ReactNode }) {+ return (+ <section>+ <h4 className="mb-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {title}+ </h4>+ {children}+ </section>+ );+}++/** A resolved id that came from another model is not the same as a wrong id. */+function ModelStateNotice({ state }: { state: PerformanceModelState }) {+ if (state.state === "current") return null;+ const message =+ state.state === "stale_model"+ ? `This id was minted by performance model version ${state.requested_model_version ?? "an earlier release"}; the index now serves version ${state.performance_model_version}.`+ : "This index does not recognize that opportunity id.";+ return (+ <p+ role="status"+ className="border-l-2 border-[var(--color-warning)] py-1.5 pl-3 text-sm text-[var(--color-text-secondary)]"+ >+ {message}+ {state.refresh_required ? " Update the index to get the current grouping." : ""}+ </p>+ );+}++/**+ * Fetch the stored plan and decide whether it names this exact opportunity.+ * A reindexed or reused row must never be handed over as this one's fix, so+ * both the link and the agent handoff wait on the same verdict.+ */+function useVerifiedPlan(+ opportunity: PerformanceOpportunity | null,+ adapter: PerformanceViewAdapter,+ enabled: boolean,+) {+ const planId =+ opportunity && planPresentation(opportunity).actionable ? opportunity.plan_id : null;+ const { data, error, isLoading } = useSWR<RefactoringPlan>(+ planId && enabled ? `performance-plan:${adapter.cacheKey}:${planId}` : null,+ () => adapter.getRefactoringPlan!(planId!),+ { revalidateOnFocus: false },+ );+ const matches = Boolean(+ data &&+ opportunity &&+ data.id === opportunity.plan_id &&+ data.refactoring_type === "performance_fix" &&+ performancePlanDetail(data).opportunityId === opportunity.opportunity_id,+ );+ return { planId, data, error, isLoading, matches, verified: matches ? data! : null };+}++function PlanSection({+ opportunity,+ adapter,+ enabled,+ plan,+}: {+ opportunity: PerformanceOpportunity;+ adapter: PerformanceViewAdapter;+ enabled: boolean;+ plan: ReturnType<typeof useVerifiedPlan>;+}) {+ const presentation = planPresentation(opportunity);+ const { planId, data, error, isLoading, matches } = plan;+ const href =+ planId && matches+ ? adapter.refactoringPlanHref?.(planId, opportunity.opportunity_id)+ : undefined;++ return (+ <Section title="Plan">+ <p className="text-sm font-medium text-[var(--color-text-primary)]">{presentation.label}</p>+ <p className="mt-1 text-sm text-[var(--color-text-tertiary)]">{presentation.detail}</p>+ {opportunity.fix ? (+ <p className="mt-2 text-sm text-[var(--color-text-secondary)]">+ Proposed intervention: {humanizeToken(opportunity.fix.strategy).toLowerCase()}.{" "}+ {opportunity.fix.rationale}+ </p>+ ) : null}+ {planId && !enabled ? (+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">+ This host cannot open the stored plan. Its id is{" "}+ <span className="break-all font-mono">{planId}</span>.+ </p>+ ) : null}+ {planId && enabled && isLoading ? (+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">Checking the stored plan.</p>+ ) : null}+ {planId && enabled && error ? (+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">+ The stored plan could not be loaded, so it is not offered here.+ </p>+ ) : null}+ {data && !matches ? (+ <p className="mt-2 text-sm text-[var(--color-warning)]">+ The stored plan no longer names this opportunity. Update the index before handing it to+ an agent.+ </p>+ ) : null}+ {href ? (+ <a+ href={href}+ className="mt-2 inline-block rounded text-sm font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ Open the plan on Refactoring+ </a>+ ) : null}+ </Section>+ );+}++export function OpportunityDrawer({+ opportunity,+ adapter,+ detailEnabled,+ planEnabled,+ onClose,+ onAgentHandoff,+}: {+ /** The row that was inspected, held so the panel can render before the fetch. */+ opportunity: PerformanceOpportunity | null;+ adapter: PerformanceViewAdapter;+ detailEnabled: boolean;+ planEnabled: boolean;+ onClose: () => void;+ onAgentHandoff: (opportunity: PerformanceOpportunity, plan: RefactoringPlan | null) => void;+}) {+ const id = opportunity?.opportunity_id ?? null;+ const { data: detail } = useSWR<PerformanceOpportunityDetail>(+ id && detailEnabled ? `performance-opportunity:${adapter.cacheKey}:${id}` : null,+ () => adapter.getPerformanceOpportunity!(id!, { evidenceLimit: 8 }),+ { revalidateOnFocus: false },+ );++ // The row is the fallback body: a host without the detail call still reads+ // every field the queue carried, and simply learns nothing extra.+ const resolved = detail && detail.resolved ? detail : null;+ const unresolved = detail && !detail.resolved ? detail : null;+ const current: PerformanceOpportunity | null = resolved ?? opportunity;+ const plan = useVerifiedPlan(current, adapter, planEnabled);++ return (+ <AdaptivePanel+ open={opportunity !== null}+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ eyebrow="Performance opportunity"+ title={current ? opportunityTitle(current) : "Performance opportunity"}+ widthClassName="md:max-w-[680px]"+ >+ {current ? (+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex-1 space-y-7 overflow-y-auto px-5 py-5">+ <p className="break-all font-mono text-xs text-[var(--color-text-secondary)]">+ {opportunityEvidenceLine(current)}+ </p>++ {unresolved ? <ModelStateNotice state={unresolved.model_state} /> : null}+ {resolved ? <ModelStateNotice state={resolved.model_state} /> : null}+ {unresolved ? (+ <p className="text-sm text-[var(--color-text-tertiary)]">{unresolved.detail}</p>+ ) : null}+ {resolved && resolved.lifecycle_status === "resolved" ? (+ <p+ role="status"+ className="border-l-2 border-[var(--color-warning)] py-1.5 pl-3 text-sm text-[var(--color-text-secondary)]"+ >+ No observation supports this cause in the current index. It is kept so a saved+ link still resolves.+ </p>+ ) : null}++ <Section title="What the evidence shows">+ <dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">+ <Field label="Context" value={contextLabel(current.execution_context)} />+ <Field label="Boundary" value={boundaryLabel(current.boundary_kind)} />+ <Field+ label="Evidence confidence"+ value={CONFIDENCE_LABEL[current.confidence]}+ detail={`How reliably the call path resolved. Provenance: ${humanizeToken(current.provenance).toLowerCase()}.`}+ />+ <Field+ label="Affected"+ value={affectedSummary(current)}+ detail={`${current.observations_total.toLocaleString()} observation${current.observations_total === 1 ? "" : "s"} fold into this cause.`}+ />+ <Field+ label="Amplification"+ value={humanizeToken(current.facets.amplification)}+ />+ <Field label="Exposure" value={humanizeToken(current.facets.exposure)} />+ <Field label="Leverage" value={humanizeToken(current.facets.leverage)} />+ <Field label="Change risk" value={humanizeToken(current.facets.change_risk)} />+ </dl>+ </Section>++ <Section title="Whether it can be changed">+ <dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">+ <Field+ label="Actionability"+ value={ACTIONABILITY_LABEL[current.actionability_state]}+ detail={humanizeToken(current.actionability_reason)}+ />+ <Field+ label="Actionability confidence"+ value={CONFIDENCE_LABEL[current.facets.actionability_confidence]}+ detail="Whether reducing the work is likely valid."+ />+ <Field+ label="Fix safety"+ value={current.fix ? humanizeToken(current.fix.safety) : "No named fix"}+ detail={+ current.fix+ ? "Whether this one transformation is safe to apply."+ : "No transformation was proposed, so none was judged safe."+ }+ />+ </dl>+ {current.prerequisites.length > 0 ? (+ <div className="mt-3">+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Missing before a fix can be named:+ </p>+ <ul className="mt-1 list-inside list-disc text-xs text-[var(--color-text-secondary)]">+ {current.prerequisites.map((item) => (+ <li key={item}>{humanizeToken(item)}</li>+ ))}+ </ul>+ </div>+ ) : null}+ </Section>++ <Section title="Why it ranks here">+ <p className="text-sm text-[var(--color-text-secondary)]">+ Position <span className="tabular-nums">{current.rank_position.toLocaleString()}</span>{" "}+ in the queue.+ </p>+ {current.why_ranked.length > 0 ? (+ <ul className="mt-2 space-y-1 text-sm text-[var(--color-text-secondary)]">+ {current.why_ranked.map((factor) => (+ <li key={factor.factor} className="tabular-nums">+ {whyRankedLabel(factor)}+ </li>+ ))}+ </ul>+ ) : null}+ </Section>++ <PlanSection+ opportunity={current}+ adapter={adapter}+ enabled={planEnabled}+ plan={plan}+ />++ {current.evidence.some((item) => item.path.length > 0) ? (+ <Section title="Caller to sink paths">+ <ProvenancePathList+ paths={current.evidence+ .filter((item) => item.path.length > 0)+ .map((item) => ({ nodes: item.path, provenance: item.provenance }))}+ total={current.observations_total}+ fileHref={adapter.fileHref}+ {...(adapter.symbolHref ? { symbolHref: adapter.symbolHref } : {})}+ />+ </Section>+ ) : null}++ <RawObservations+ opportunityId={current.opportunity_id}+ preview={current.evidence}+ previewTruncated={current.evidence_truncated}+ total={current.observations_total}+ adapter={adapter}+ />++ <Section title="Hand this to an agent">+ <p className="text-sm text-[var(--color-text-secondary)]">+ Ask for the same record by its stable id:+ </p>+ <p className="mt-1 break-all rounded bg-[var(--color-bg-inset)] px-2 py-1.5 font-mono text-xs text-[var(--color-text-primary)]">+ {agentHandoffCall(current.opportunity_id)}+ </p>+ {resolved?.analyzed_commit ? (+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">+ Analyzed at{" "}+ <span className="font-mono">{resolved.analyzed_commit.slice(0, 7)}</span>.+ </p>+ ) : null}+ </Section>+ </div>++ <div className="flex items-center gap-3 border-t border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-5 py-3.5">+ <button+ type="button"+ onClick={() => onAgentHandoff(current, plan.verified)}+ className="inline-flex items-center justify-center gap-2 rounded-lg bg-[var(--color-accent-fill)] px-3.5 py-2 text-sm font-semibold text-[var(--color-text-on-accent)] transition-opacity hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <Sparkles className="h-4 w-4" aria-hidden="true" />+ {plan.verified ? "Copy the plan for an agent" : "Copy an agent handoff"}+ </button>+ </div>+ </div>+ ) : null}+ </AdaptivePanel>+ );+}diff --git a/packages/ui/src/health/performance/evidence.tsx b/packages/ui/src/health/performance/evidence.tsxnew file mode 100644index 000000000..80b5e8510--- /dev/null+++ b/packages/ui/src/health/performance/evidence.tsx@@ -0,0 +1,114 @@+"use client";++import { useState } from "react";+import useSWR from "swr";+import type { HealthFinding, PerformanceOpportunityEvidence } from "@repowise-dev/types/health";++import { PaginationControls } from "../../shared/pagination-controls";+import type { PerformanceViewAdapter } from "./adapter";++/**+ * Raw observations behind one cause, fetched only when asked for.+ *+ * The rows carried on an opportunity are a bounded preview, so paging here+ * asks the server rather than growing the queue payload. A page is never+ * filtered on the client: it is a slice, and narrowing a slice would answer a+ * different question than the total printed beside it.+ */++const RAW_PAGE_SIZE = 50;++type EvidenceRow = HealthFinding | PerformanceOpportunityEvidence;++function rowKey(row: EvidenceRow, index: number): string {+ return ("id" in row ? row.id : row.finding_id) || String(index);+}++export function RawObservations({+ opportunityId,+ preview,+ previewTruncated,+ total,+ adapter,+}: {+ opportunityId: string;+ /** The bounded rows already on the opportunity. */+ preview: PerformanceOpportunityEvidence[];+ previewTruncated: boolean;+ total: number;+ adapter: PerformanceViewAdapter;+}) {+ const [open, setOpen] = useState(false);+ const [offset, setOffset] = useState(0);+ const load = adapter.getPerformanceOpportunityFindings;+ const { data, isLoading, error } = useSWR(+ open && load ? `performance-raw:${adapter.cacheKey}:${opportunityId}:${offset}` : null,+ () => load!(opportunityId, { offset, limit: RAW_PAGE_SIZE }),+ { revalidateOnFocus: false, keepPreviousData: true },+ );++ const rows: EvidenceRow[] = data?.items ?? preview;+ const reportedTotal = data?.total ?? total;++ return (+ <section>+ <button+ type="button"+ onClick={() => setOpen((value) => !value)}+ aria-expanded={open}+ className="rounded text-sm font-medium text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-text-primary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ {open ? "Hide" : "Read"} the raw observations+ <span className="tabular-nums"> ({reportedTotal.toLocaleString()})</span>+ </button>++ {open ? (+ <div className="mt-3">+ {error ? (+ <p className="text-sm text-[var(--color-text-tertiary)]">+ The observations could not be loaded. The preview below is what the queue already+ carried.+ </p>+ ) : null}+ {isLoading && !data ? (+ <div className="h-24 animate-pulse rounded bg-[var(--color-bg-surface)]" />+ ) : (+ <ul className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">+ {rows.map((row, index) => (+ <li key={rowKey(row, index)} className="py-3">+ <a+ href={adapter.fileHref(row.file_path)}+ className="break-all font-mono text-xs text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-accent-primary)] hover:underline"+ >+ {row.file_path}+ {row.line_start ? `:${row.line_start}` : ""}+ </a>+ <p className="mt-1 text-sm text-[var(--color-text-secondary)]">{row.reason}</p>+ </li>+ ))}+ </ul>+ )}++ {data ? (+ <PaginationControls+ offset={offset}+ shown={data.items.length}+ total={data.total}+ label="observations"+ onPrevious={+ offset > 0 ? () => setOffset(Math.max(0, offset - RAW_PAGE_SIZE)) : undefined+ }+ onNext={data.next_offset != null ? () => setOffset(data.next_offset!) : undefined}+ />+ ) : previewTruncated || preview.length < reportedTotal ? (+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">+ Showing <span className="tabular-nums">{preview.length.toLocaleString()}</span> of{" "}+ <span className="tabular-nums">{reportedTotal.toLocaleString()}</span>. This host+ does not page the remaining observations.+ </p>+ ) : null}+ </div>+ ) : null}+ </section>+ );+}diff --git a/packages/ui/src/health/performance/filters.tsx b/packages/ui/src/health/performance/filters.tsxnew file mode 100644index 000000000..b18a01b51--- /dev/null+++ b/packages/ui/src/health/performance/filters.tsx@@ -0,0 +1,208 @@+"use client";++import type {+ PerformanceContextFilter,+ PerformanceExecutionContext,+ PerformanceFacetCount,+ PerformanceFacetKey,+ PerformanceFacets,+} from "@repowise-dev/types/health";++import { FilterSelect } from "../code-health-controls";+import { ViewTabs } from "../../shared/view-tabs";+import {+ CONTEXT_HINT,+ CONTEXT_ORDER,+ FACET_LABEL,+ contextLabel,+ facetValueLabel,+} from "./presentation";+import {+ narrowingCount,+ type NarrowingKey,+ type PerformanceFilterState,+} from "./query";++/**+ * The filter surface. Every option and every count comes from the server's+ * facets, which are counted over the base result, so choosing a value never+ * removes its own alternatives from the list.+ */++function countOf(counts: PerformanceFacetCount[] | undefined, value: string): number {+ return counts?.find((entry) => entry.value === value)?.total ?? 0;+}++/**+ * The four canonical contexts stay separate and always visible, because a+ * context with no rows is a fact about the repository worth reading. When the+ * server predates the vocabulary they collapse to the pairing it understands.+ */+export function ContextTabs({+ value,+ facets,+ total,+ collapsed,+ onChange,+}: {+ value: PerformanceContextFilter;+ facets: PerformanceFacets;+ total: number;+ collapsed: boolean;+ onChange: (context: PerformanceContextFilter) => void;+}) {+ const counts = facets.context;+ const contexts: PerformanceExecutionContext[] = collapsed+ ? ["production", "test"]+ : CONTEXT_ORDER;+ const tabs = [+ { id: "all", label: "All", badge: total },+ ...contexts.map((context) => ({+ id: context,+ label:+ collapsed && context === "production" ? "Production & tooling" : contextLabel(context),+ badge:+ collapsed && context === "production"+ ? countOf(counts, "production") + countOf(counts, "tooling")+ : countOf(counts, context),+ })),+ ];+ return (+ <ViewTabs+ tabs={tabs}+ value={value}+ onValueChange={(next) => onChange(next as PerformanceContextFilter)}+ />+ );+}++interface NarrowingSpec {+ key: NarrowingKey;+ facet: PerformanceFacetKey;+ anyLabel: string;+}++const NARROWING: NarrowingSpec[] = [+ { key: "actionability", facet: "actionability", anyLabel: "Any" },+ { key: "boundary", facet: "boundary", anyLabel: "Any" },+ { key: "confidence", facet: "confidence", anyLabel: "Any" },+];++/**+ * A facet with one value is a fact, not a choice, so it is stated rather than+ * offered as a control that could only ever return the same rows.+ */+function SingleValueFact({ facet, only }: { facet: PerformanceFacetKey; only: PerformanceFacetCount }) {+ return (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ <span className="uppercase tracking-wider">{FACET_LABEL[facet]}</span>{" "}+ <span className="text-[var(--color-text-secondary)]">+ {facetValueLabel(facet, only.value)}+ </span>{" "}+ <span className="tabular-nums">on all {only.total.toLocaleString()}</span>+ </p>+ );+}++export function QueueFilters({+ filters,+ facets,+ onChange,+ onClear,+}: {+ filters: PerformanceFilterState;+ facets: PerformanceFacets;+ onChange: (key: NarrowingKey, value: string | null) => void;+ onClear: () => void;+}) {+ const active = narrowingCount(filters);+ return (+ <div className="flex flex-wrap items-center gap-x-5 gap-y-3">+ {NARROWING.map(({ key, facet, anyLabel }) => {+ const counts = facets[facet] ?? [];+ if (counts.length === 0) return null;+ if (counts.length === 1 && !filters[key]) {+ return <SingleValueFact key={key} facet={facet} only={counts[0]!} />;+ }+ return (+ <FilterSelect+ key={key}+ label={FACET_LABEL[facet]}+ value={filters[key] ?? ""}+ onChange={(next) => onChange(key, next || null)}+ options={[+ { value: "", label: anyLabel },+ ...counts.map((entry) => ({+ value: entry.value,+ label: `${facetValueLabel(facet, entry.value)} (${entry.total.toLocaleString()})`,+ })),+ ]}+ />+ );+ })}+ {active > 0 ? (+ <button+ type="button"+ onClick={onClear}+ className="rounded text-xs font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ Clear {active} filter{active === 1 ? "" : "s"}+ </button>+ ) : null}+ </div>+ );+}++/**+ * What the queue currently describes, and what it was drawn from. The+ * per-page range is the pagination control's job, so this states only what+ * that control cannot: how the selection narrows the repository, and when the+ * answer was computed.+ */+export function ScopeLine({+ filteredTotal,+ repositoryTotal,+ context,+ narrowed,+ analyzedCommit,+}: {+ filteredTotal: number;+ repositoryTotal: number;+ context: PerformanceContextFilter;+ narrowed: number;+ analyzedCommit?: string | null | undefined;+}) {+ const scope =+ context === "all"+ ? "opportunities"+ : `${contextLabel(context as PerformanceExecutionContext).toLowerCase()} opportunities`;+ return (+ <p role="status" className="text-xs text-[var(--color-text-tertiary)]">+ <span className="tabular-nums">{filteredTotal.toLocaleString()}</span> {scope}+ {narrowed > 0 ? ` under ${narrowed} filter${narrowed === 1 ? "" : "s"}` : ""}+ {filteredTotal !== repositoryTotal ? (+ <>+ , from <span className="tabular-nums">{repositoryTotal.toLocaleString()}</span> in the+ repository+ </>+ ) : null}+ .+ {analyzedCommit ? (+ <>+ {" "}+ Analyzed at <span className="font-mono">{analyzedCommit.slice(0, 7)}</span>.+ </>+ ) : null}+ </p>+ );+}++export function ContextHint({ context }: { context: PerformanceContextFilter }) {+ if (context === "all") return null;+ return (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ {CONTEXT_HINT[context as PerformanceExecutionContext]}+ </p>+ );+}+diff --git a/packages/ui/src/health/performance/legacy.tsx b/packages/ui/src/health/performance/legacy.tsxnew file mode 100644index 000000000..d000189ce--- /dev/null+++ b/packages/ui/src/health/performance/legacy.tsx@@ -0,0 +1,52 @@+"use client";++import useSWR from "swr";+import { Gauge } from "lucide-react";+import type { HealthFinding } from "@repowise-dev/types/health";++import { EmptyState } from "../../shared/empty-state";+import { BiomarkerList } from "../biomarker-list";+import type { PerformanceViewAdapter } from "./adapter";++/**+ * The fallback for a server that predates causal grouping.+ *+ * It shows raw findings and says so. Inventing groups, ranks, or plan links+ * from findings alone would put this surface's vocabulary on data that never+ * carried it.+ */+export function LegacyPerformanceFindings({ adapter }: { adapter: PerformanceViewAdapter }) {+ const { data, error, isLoading } = useSWR<HealthFinding[]>(+ `performance-findings-legacy:${adapter.cacheKey}`,+ () => adapter.listFindings({ dimension: "performance", limit: 100 }),+ { revalidateOnFocus: false },+ );+ if (isLoading) return <div className="h-72 animate-pulse rounded bg-[var(--color-bg-surface)]" />;+ if (error || !data?.length) {+ return (+ <EmptyState+ icon={<Gauge className="h-6 w-6" />}+ title="No performance opportunities"+ description="This server does not provide causal grouping. Reindex with a current server to tell an empty result apart from unsupported grouping."+ />+ );+ }+ return (+ <div className="space-y-5">+ <div>+ <h2 className="text-lg font-semibold text-[var(--color-text-primary)]">+ Raw performance findings+ </h2>+ <p className="mt-1 max-w-[72ch] text-sm text-[var(--color-text-secondary)]">+ This server predates causal opportunity groups. Up to 100 canonical findings are shown+ without inventing plan links or rank semantics.+ </p>+ </div>+ <BiomarkerList+ findings={data}+ grouped+ onSelect={(finding) => adapter.navigate(adapter.fileHref(finding.file_path))}+ />+ </div>+ );+}diff --git a/packages/ui/src/health/performance/presentation.ts b/packages/ui/src/health/performance/presentation.tsnew file mode 100644index 000000000..f1bf664b2--- /dev/null+++ b/packages/ui/src/health/performance/presentation.ts@@ -0,0 +1,207 @@+import {+ PERF_BOUNDARY_LABEL,+ type PerformanceActionabilityState,+ type PerformanceExecutionContext,+ type PerformanceFacetKey,+ type PerformanceOpportunity,+ type PerformanceOpportunityConfidence,+ type PerformanceWhyRanked,+} from "@repowise-dev/types/health";+import type { C4IoKind } from "@repowise-dev/types/external-systems";++import { biomarkerLabel } from "../biomarker-glossary";++/**+ * Display derivations for the performance queue. Everything here reads fields+ * the server already decided; nothing re-groups, re-ranks, re-scores, or+ * re-links a plan. If a value needs a rule, the rule belongs on the server.+ */++const CONTEXT_LABEL: Record<PerformanceExecutionContext, string> = {+ production: "Production",+ tooling: "Tooling",+ test: "Test suite",+ unknown: "Unclassified",+};++/** The four canonical contexts, in the order the tab presents them. */+export const CONTEXT_ORDER: PerformanceExecutionContext[] = [+ "production",+ "tooling",+ "test",+ "unknown",+];++export const CONTEXT_HINT: Record<PerformanceExecutionContext, string> = {+ production: "Runtime paths",+ tooling: "Build and developer paths",+ test: "Test execution cost",+ unknown: "No context could be classified",+};++export const ACTIONABILITY_LABEL: Record<PerformanceActionabilityState, string> = {+ plan_ready: "Plan ready",+ advisory: "Advisory",+ investigate: "Needs investigation",+};++export const ACTIONABILITY_HINT: Record<PerformanceActionabilityState, string> = {+ plan_ready: "A named intervention the analysis considers safe to apply.",+ advisory: "A coherent intervention, but the analysis cannot prove it is safe.",+ investigate: "Evidence worth reading before any change is proposed.",+};++export const CONFIDENCE_LABEL: Record<PerformanceOpportunityConfidence, string> = {+ high: "High",+ medium: "Medium",+ low: "Low",+};++export const FACET_LABEL: Record<PerformanceFacetKey, string> = {+ context: "Context",+ boundary: "Boundary",+ confidence: "Evidence confidence",+ actionability: "Actionability",+ plan_state: "Plan",+};++const PLAN_STATE_LABEL: Record<string, string> = {+ available: "Plan ready",+ no_safe_plan: "No safe plan",+ not_persisted: "Needs an index refresh",+};++/** The facet value used when an opportunity crosses no I/O boundary. */+const NO_BOUNDARY = "none";++/** Turn a machine token into readable words without inventing a vocabulary. */+export function humanizeToken(token: string): string {+ const words = token.replaceAll("_", " ").replaceAll("-", " ").trim();+ if (!words) return "Unknown";+ return words[0]!.toUpperCase() + words.slice(1);+}++export function contextLabel(context: PerformanceExecutionContext): string {+ return CONTEXT_LABEL[context] ?? CONTEXT_LABEL.unknown;+}++/** The boundary as a label; `none` is a real answer, not a missing one. */+export function boundaryLabel(boundary: C4IoKind | string | null | undefined): string {+ if (!boundary || boundary === NO_BOUNDARY) return "In-process";+ const known: Partial<Record<string, string>> = PERF_BOUNDARY_LABEL;+ return known[boundary] ?? humanizeToken(boundary);+}++/** The boundary as a noun that reads inside a sentence. */+function boundaryNoun(boundary: C4IoKind | null | undefined): string {+ if (!boundary) return "Repeated";+ const known: Partial<Record<string, string>> = PERF_BOUNDARY_LABEL;+ return known[boundary]?.toLowerCase() ?? "repeated";+}++export function facetValueLabel(facet: PerformanceFacetKey, value: string): string {+ if (facet === "context") return contextLabel(value as PerformanceExecutionContext);+ if (facet === "boundary") return boundaryLabel(value);+ if (facet === "confidence") return CONFIDENCE_LABEL[value as PerformanceOpportunityConfidence] ?? humanizeToken(value);+ if (facet === "actionability")+ return ACTIONABILITY_LABEL[value as PerformanceActionabilityState] ?? humanizeToken(value);+ return PLAN_STATE_LABEL[value] ?? humanizeToken(value);+}++/**+ * Cause phrasings for the markers whose meaning changes with the boundary.+ * Every other marker uses its glossary label, so the taxonomy stays in one+ * place and only genuinely boundary-sensitive sentences are written twice.+ */+const CAUSE_BY_MARKER: Record<string, (boundary: C4IoKind | null) => string> = {+ io_in_loop: (b) => `${b ? boundaryNoun(b) : "I/O"} call inside a loop`,+ nested_loop_with_io: (b) => `${b ? boundaryNoun(b) : "I/O"} call inside a nested loop`,+ hot_path_sync_io: (b) => `Blocking ${b ? boundaryNoun(b) : "I/O"} call on a hot path`,+ serial_await_in_loop: (b) => `${b ? boundaryNoun(b) : "Awaited"} call awaited one at a time in a loop`,+ blocking_io_under_lock: (b) => `${b ? boundaryNoun(b) : "I/O"} call made while a lock is held`,+ resource_construction_in_loop: (b) =>+ `${b ? boundaryNoun(b) : "Resource"} client constructed on every iteration`,+};++/**+ * The cause a reader should act on, in words. The terminal sink is deliberately+ * absent: it is machine evidence and belongs in the monospace line beneath.+ */+export function opportunityTitle(opportunity: PerformanceOpportunity): string {+ const cause = CAUSE_BY_MARKER[opportunity.biomarker_type];+ const phrase = cause+ ? cause(opportunity.boundary_kind)+ : biomarkerLabel(opportunity.biomarker_type);+ return phrase[0]!.toUpperCase() + phrase.slice(1);+}++/**+ * The machine evidence under the title: the sink the paths converge on, or the+ * symbol worth editing, or the file. Whichever exists is monospace.+ */+export function opportunityEvidenceLine(opportunity: PerformanceOpportunity): string {+ const sink = opportunity.terminal_sink?.trim();+ if (sink) return sink;+ const symbol = opportunity.intervention_symbol?.trim();+ if (symbol) return symbol;+ const first = opportunity.evidence[0];+ if (first?.function_name) return `${opportunity.file_path}::${first.function_name}`;+ return opportunity.file_path;+}++/** `12 call sites across 3 files`, with the singulars right. */+export function affectedSummary(opportunity: PerformanceOpportunity): string {+ const sites = opportunity.affected_call_sites_total;+ const files = opportunity.affected_files_total;+ const sitePart = `${sites.toLocaleString()} call site${sites === 1 ? "" : "s"}`;+ const filePart = `${files.toLocaleString()} file${files === 1 ? "" : "s"}`;+ return `${sitePart} across ${filePart}`;+}++/** `Multiplier shape: serial await in loop (+4)`, capped by the server at three. */+export function whyRankedLabel(factor: PerformanceWhyRanked): string {+ const name = humanizeToken(factor.factor);+ const sign = factor.points >= 0 ? "+" : "";+ if (factor.value === null || factor.value === "" || typeof factor.value === "boolean") {+ return `${name} (${sign}${factor.points})`;+ }+ const value = typeof factor.value === "number" ? factor.value.toLocaleString() : humanizeToken(String(factor.value));+ return `${name}: ${value} (${sign}${factor.points})`;+}++export interface PlanPresentation {+ label: string;+ detail: string;+ /** True only for a plan the server says exists and the client verified. */+ actionable: boolean;+}++/**+ * Plan state as the server reported it. The reason is the server's; this only+ * chooses the heading it sits under.+ */+export function planPresentation(opportunity: PerformanceOpportunity): PlanPresentation {+ if (opportunity.plan_status === "available" && opportunity.plan_id) {+ return {+ label: "Structured plan ready",+ detail: opportunity.plan_reason,+ actionable: true,+ };+ }+ if (opportunity.plan_status === "not_persisted") {+ return {+ label: "Needs an index refresh",+ detail: opportunity.plan_reason,+ actionable: false,+ };+ }+ return { label: "No safe plan", detail: opportunity.plan_reason, actionable: false };+}++/**+ * The copy that tells an agent which drill-down to call. Quotes the opportunity+ * id because that is the id the agent surface resolves.+ */+export function agentHandoffCall(opportunityId: string): string {+ return `get_health(opportunity_id="${opportunityId}")`;+}diff --git a/packages/ui/src/health/performance/query.ts b/packages/ui/src/health/performance/query.tsnew file mode 100644index 000000000..65b77680d--- /dev/null+++ b/packages/ui/src/health/performance/query.ts@@ -0,0 +1,136 @@+import type {+ PerformanceActionabilityState,+ PerformanceContextFilter,+ PerformanceOpportunityConfidence,+ PerformanceOpportunityQuery,+} from "@repowise-dev/types/health";++/**+ * The queue's filter state, and its round trip to a query string.+ *+ * Every field here is a parameter the server answers, so narrowing is always a+ * refetch and never a filter over the loaded page. A page can be a slice of a+ * much larger result, so filtering it on the client would answer a different+ * question than the count beside it.+ */++export type PerformanceSort = NonNullable<PerformanceOpportunityQuery["sort"]>;++export interface PerformanceFilterState {+ context: PerformanceContextFilter;+ boundary: string | null;+ confidence: PerformanceOpportunityConfidence | null;+ actionability: PerformanceActionabilityState | null;+ sort: PerformanceSort;+ offset: number;+}++export const INITIAL_FILTERS: PerformanceFilterState = {+ context: "all",+ boundary: null,+ confidence: null,+ actionability: null,+ sort: "rank",+ offset: 0,+};++/** The narrowing filters, apart from context, which is a permanent tab row. */+const NARROWING_KEYS = ["boundary", "confidence", "actionability"] as const;+export type NarrowingKey = (typeof NARROWING_KEYS)[number];++const SORTS: readonly PerformanceSort[] = ["rank", "leverage", "observations"];+const CONFIDENCES: readonly PerformanceOpportunityConfidence[] = ["high", "medium", "low"];+const ACTIONABILITIES: readonly PerformanceActionabilityState[] = [+ "plan_ready",+ "advisory",+ "investigate",+];+const CONTEXTS: readonly PerformanceContextFilter[] = [+ "all",+ "production",+ "tooling",+ "test",+ "unknown",+];++/**+ * Build the server query. `collapseContexts` is set only when the server+ * predates the canonical vocabulary, and is the one place the retired+ * `production_tooling` spelling may be emitted.+ */+export function toQuery(+ state: PerformanceFilterState,+ options: { limit: number; collapseContexts?: boolean },+): PerformanceOpportunityQuery {+ const context =+ options.collapseContexts && (state.context === "production" || state.context === "tooling")+ ? ("production_tooling" as const)+ : state.context;+ const query: PerformanceOpportunityQuery = {+ context,+ view: "detail",+ sort: state.sort,+ limit: options.limit,+ offset: state.offset,+ };+ if (state.boundary) query.boundary = state.boundary;+ if (state.confidence) query.confidence = state.confidence;+ if (state.actionability) query.actionability = state.actionability;+ return query;+}++/**+ * A stable string for the state. Keys are written in a fixed order and+ * defaults are omitted, so an unchanged filter set always produces the same+ * cache key and the same shareable link.+ */+export function serializeFilters(state: PerformanceFilterState): string {+ const params = new URLSearchParams();+ if (state.context !== INITIAL_FILTERS.context) params.set("context", state.context);+ if (state.boundary) params.set("boundary", state.boundary);+ if (state.confidence) params.set("confidence", state.confidence);+ if (state.actionability) params.set("actionability", state.actionability);+ if (state.sort !== INITIAL_FILTERS.sort) params.set("sort", state.sort);+ if (state.offset > 0) params.set("offset", String(state.offset));+ return params.toString();+}++function oneOf<T extends string>(value: string | null, allowed: readonly T[]): T | null {+ return value && (allowed as readonly string[]).includes(value) ? (value as T) : null;+}++/**+ * Read the state back. An unrecognized value falls back to the default rather+ * than being forwarded to the server, so a hand-edited link cannot make the+ * queue look empty.+ */+export function parseFilters(search: string | URLSearchParams): PerformanceFilterState {+ const params = typeof search === "string" ? new URLSearchParams(search) : search;+ const offset = Number.parseInt(params.get("offset") ?? "", 10);+ return {+ context: oneOf(params.get("context"), CONTEXTS) ?? INITIAL_FILTERS.context,+ boundary: params.get("boundary") || null,+ confidence: oneOf(params.get("confidence"), CONFIDENCES),+ actionability: oneOf(params.get("actionability"), ACTIONABILITIES),+ sort: oneOf(params.get("sort"), SORTS) ?? INITIAL_FILTERS.sort,+ offset: Number.isFinite(offset) && offset > 0 ? offset : 0,+ };+}++/** Change one filter. Any narrowing change returns to the first page. */+export function withFilter<K extends keyof PerformanceFilterState>(+ state: PerformanceFilterState,+ key: K,+ value: PerformanceFilterState[K],+): PerformanceFilterState {+ if (key === "offset") return { ...state, offset: value as number };+ return { ...state, [key]: value, offset: 0 };+}++export function clearNarrowing(state: PerformanceFilterState): PerformanceFilterState {+ return { ...state, boundary: null, confidence: null, actionability: null, offset: 0 };+}++export function narrowingCount(state: PerformanceFilterState): number {+ return NARROWING_KEYS.filter((key) => state[key] !== null).length;+}diff --git a/packages/ui/src/health/performance/queue.tsx b/packages/ui/src/health/performance/queue.tsxnew file mode 100644index 000000000..539f41299--- /dev/null+++ b/packages/ui/src/health/performance/queue.tsx@@ -0,0 +1,281 @@+"use client";++import { memo, useState } from "react";+import { Copy, ExternalLink, FileCode, MoreHorizontal } from "lucide-react";+import { toast } from "sonner";+import type {+ PerformanceActionabilityState,+ PerformanceFacets,+ PerformanceOpportunity,+} from "@repowise-dev/types/health";++import { Button } from "../../ui/button";+import { Popover, PopoverContent, PopoverTrigger } from "../../ui/popover";+import { CLICKABLE_ROW_CLS, clickableRowProps } from "../../shared/responsive-table";+import type { PerformanceViewAdapter } from "./adapter";+import {+ ACTIONABILITY_HINT,+ ACTIONABILITY_LABEL,+ affectedSummary,+ agentHandoffCall,+ boundaryLabel,+ contextLabel,+ CONFIDENCE_LABEL,+ opportunityEvidenceLine,+ opportunityTitle,+ planPresentation,+ whyRankedLabel,+} from "./presentation";++/**+ * The queue: full-width rows under section headings, one primary verb each.+ *+ * Sections are contiguous runs of the server's order, never a regrouping. The+ * server ranks actionable work first, so the runs read as tiers; if that order+ * ever changed, the runs would still describe exactly what was returned.+ */++interface Section {+ state: PerformanceActionabilityState;+ items: PerformanceOpportunity[];+}++export function contiguousSections(items: PerformanceOpportunity[]): Section[] {+ const sections: Section[] = [];+ for (const item of items) {+ const last = sections[sections.length - 1];+ if (last && last.state === item.actionability_state) last.items.push(item);+ else sections.push({ state: item.actionability_state, items: [item] });+ }+ return sections;+}++function facetTotal(facets: PerformanceFacets, value: string): number | null {+ const found = facets.actionability?.find((entry) => entry.value === value);+ return found ? found.total : null;+}++export function OpportunityQueue({+ items,+ facets,+ adapter,+ showSections,+ selectedId,+ onInspect,+}: {+ items: PerformanceOpportunity[];+ facets: PerformanceFacets;+ adapter: PerformanceViewAdapter;+ /** Sections are headings over one ranked list, so a narrowed queue drops them. */+ showSections: boolean;+ selectedId: string | null;+ onInspect: (opportunity: PerformanceOpportunity) => void;+}) {+ const sections = showSections+ ? contiguousSections(items)+ : [{ state: items[0]?.actionability_state ?? "investigate", items }];++ return (+ <div className="space-y-8">+ {sections.map((section, index) => (+ <section key={`${section.state}-${index}`} aria-labelledby={`perf-section-${index}`}>+ {showSections ? (+ <div className="mb-1 flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">+ <h3+ id={`perf-section-${index}`}+ className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]"+ >+ {ACTIONABILITY_LABEL[section.state]}+ {facetTotal(facets, section.state) != null ? (+ <span className="ml-2 tabular-nums">+ {facetTotal(facets, section.state)!.toLocaleString()} in the repository+ </span>+ ) : null}+ </h3>+ <p className="text-xs text-[var(--color-text-tertiary)]">+ {ACTIONABILITY_HINT[section.state]}+ </p>+ </div>+ ) : (+ <h3 id={`perf-section-${index}`} className="sr-only">+ Performance opportunities+ </h3>+ )}+ <ul className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">+ {section.items.map((opportunity) => (+ <OpportunityRow+ key={opportunity.opportunity_id}+ opportunity={opportunity}+ adapter={adapter}+ selected={opportunity.opportunity_id === selectedId}+ onInspect={onInspect}+ />+ ))}+ </ul>+ </section>+ ))}+ </div>+ );+}++function StatusMark({ opportunity }: { opportunity: PerformanceOpportunity }) {+ const plan = planPresentation(opportunity);+ const tone = plan.actionable ? "var(--color-success)" : "var(--color-text-tertiary)";+ return (+ <span className="inline-flex items-center gap-1.5 whitespace-nowrap text-xs font-medium text-[var(--color-text-secondary)]">+ <span+ aria-hidden="true"+ className="h-1.5 w-1.5 shrink-0 rounded-full"+ style={{ backgroundColor: tone }}+ />+ {plan.label}+ </span>+ );+}++/**+ * Memoized because a page is twenty of these and the surrounding filter state+ * changes far more often than any single row does. It takes the callback+ * rather than a closure over one opportunity so the props stay comparable.+ */+const OpportunityRow = memo(function OpportunityRow({+ opportunity,+ adapter,+ selected,+ onInspect,+}: {+ opportunity: PerformanceOpportunity;+ adapter: PerformanceViewAdapter;+ selected: boolean;+ onInspect: (opportunity: PerformanceOpportunity) => void;+}) {+ const title = opportunityTitle(opportunity);+ const why = opportunity.why_ranked.slice(0, 3);+ return (+ <li+ data-performance-opportunity={opportunity.opportunity_id}+ aria-current={selected ? "true" : undefined}+ className={`${CLICKABLE_ROW_CLS} flex items-start gap-3 px-1 py-4 sm:gap-4 ${+ selected ? "bg-[var(--color-bg-elevated)]" : "hover:bg-[var(--color-bg-elevated)]"+ }`}+ aria-label={`Inspect ${title}`}+ {...clickableRowProps(() => onInspect(opportunity))}+ >+ <span className="mt-0.5 w-7 shrink-0 text-right font-mono text-xs tabular-nums text-[var(--color-text-tertiary)]">+ {opportunity.rank_position.toLocaleString()}+ </span>++ <div className="min-w-0 flex-1">+ <p className="text-[15px] font-semibold leading-snug text-[var(--color-text-primary)]">+ {title}+ </p>+ <p className="mt-1 break-all font-mono text-xs text-[var(--color-text-secondary)]">+ {opportunityEvidenceLine(opportunity)}+ </p>+ <p className="mt-1.5 text-xs text-[var(--color-text-tertiary)]">+ {contextLabel(opportunity.execution_context)} ·{" "}+ {boundaryLabel(opportunity.boundary_kind)} ·{" "}+ <span className="tabular-nums">{affectedSummary(opportunity)}</span> ·{" "}+ {CONFIDENCE_LABEL[opportunity.confidence]} evidence confidence+ </p>+ {why.length > 0 ? (+ <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">+ Ranked on {why.map(whyRankedLabel).join(", ")}+ </p>+ ) : null}+ <div className="mt-2 sm:hidden">+ <StatusMark opportunity={opportunity} />+ </div>+ </div>++ <div className="flex shrink-0 items-center gap-1 sm:gap-3">+ <span className="hidden sm:inline">+ <StatusMark opportunity={opportunity} />+ </span>+ <RowOverflow opportunity={opportunity} adapter={adapter} title={title} />+ </div>+ </li>+ );+});++async function copy(text: string, what: string) {+ try {+ await navigator.clipboard.writeText(text);+ toast.success(`${what} copied`);+ } catch {+ toast.error(`Could not copy the ${what.toLowerCase()}`);+ }+}++/**+ * Secondary actions. Inspect is the row itself, so nothing here repeats it and+ * each entry names a different kind of destination.+ */+function RowOverflow({+ opportunity,+ adapter,+ title,+}: {+ opportunity: PerformanceOpportunity;+ adapter: PerformanceViewAdapter;+ title: string;+}) {+ const [open, setOpen] = useState(false);+ const plan = planPresentation(opportunity);+ const planHref =+ plan.actionable && opportunity.plan_id+ ? adapter.refactoringPlanHref?.(opportunity.plan_id, opportunity.opportunity_id)+ : undefined;++ const item = (+ label: string,+ Icon: typeof Copy,+ onClick: () => void,+ ) => (+ <button+ type="button"+ onClick={() => {+ setOpen(false);+ onClick();+ }}+ className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <Icon className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />+ {label}+ </button>+ );++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <Button+ size="sm"+ variant="ghost"+ className="h-7 w-7 px-0 text-[var(--color-text-tertiary)]"+ aria-label={`More actions for ${title}`}+ onClick={(event) => event.stopPropagation()}+ >+ <MoreHorizontal className="h-4 w-4" />+ </Button>+ </PopoverTrigger>+ <PopoverContent+ align="end"+ className="w-64 p-1"+ onClick={(event) => event.stopPropagation()}+ >+ {item("Open the file", FileCode, () =>+ adapter.navigate(adapter.fileHref(opportunity.file_path)),+ )}+ {planHref+ ? item("Open the plan on Refactoring", ExternalLink, () => adapter.navigate(planHref))+ : null}+ {item("Copy the agent drill-down", Copy, () =>+ copy(agentHandoffCall(opportunity.opportunity_id), "Drill-down call"),+ )}+ {item("Copy the opportunity id", Copy, () =>+ copy(opportunity.opportunity_id, "Opportunity id"),+ )}+ </PopoverContent>+ </Popover>+ );+}diff --git a/packages/ui/src/health/performance/states.tsx b/packages/ui/src/health/performance/states.tsxnew file mode 100644index 000000000..446bc7eca--- /dev/null+++ b/packages/ui/src/health/performance/states.tsx@@ -0,0 +1,147 @@+"use client";++import { AlertTriangle, Gauge, Info } from "lucide-react";+import type { PerformanceOpportunitySummary } from "@repowise-dev/types/health";++import { EmptyState } from "../../shared/empty-state";++/**+ * Every state the queue can be in other than "here are the rows". They are+ * separated because each says something different: an index that was never+ * analyzed, a model that moved, a filter that matched nothing, and a+ * repository with no supported pattern are four answers, and none of them is+ * "this code is fast".+ */++export function QueueSkeleton() {+ return (+ <div className="space-y-8" aria-busy="true">+ <div className="h-32 animate-pulse rounded bg-[var(--color-bg-surface)]" />+ <div className="h-10 animate-pulse rounded bg-[var(--color-bg-surface)]" />+ <div className="space-y-px">+ {[0, 1, 2, 3, 4].map((row) => (+ <div key={row} className="h-[86px] animate-pulse bg-[var(--color-bg-surface)]" />+ ))}+ </div>+ <span className="sr-only" role="status">+ Loading performance opportunities+ </span>+ </div>+ );+}++export function QueueError({ onRetry }: { onRetry?: (() => void) | undefined }) {+ return (+ <EmptyState+ icon={<Gauge className="h-6 w-6" />}+ title="Could not load performance opportunities"+ description="The repository may need indexing, or the server may be temporarily unavailable. Nothing here says the code is fast."+ {...(onRetry ? { action: { label: "Try again", onClick: onRetry } } : {})}+ />+ );+}++/** The index carries no analysis yet. Distinct from a repository with none. */+export function UnavailableQueue({ summary }: { summary: PerformanceOpportunitySummary }) {+ return (+ <EmptyState+ icon={<Gauge className="h-6 w-6" />}+ title="This index has not been analyzed for performance"+ description={+ summary.detail ??+ summary.reason ??+ "Run an index update to build the causal queue. Until then there is no result to report, which is not the same as a clean one."+ }+ />+ );+}++/** Analyzed, and nothing supported surfaced. Say exactly that. */+export function EmptyQueue() {+ return (+ <div className="border-t border-[var(--color-border-default)] px-1 py-12 text-center">+ <h3 className="text-[15px] font-semibold text-[var(--color-text-primary)]">+ No supported pattern surfaced+ </h3>+ <p className="mx-auto mt-2 max-w-[60ch] text-sm text-[var(--color-text-tertiary)]">+ The detectors are high precision and low recall, so an empty queue means nothing they+ recognize was found. It does not measure latency and does not claim the code is fast.+ </p>+ </div>+ );+}++export function FilteredEmpty({ onClear }: { onClear: () => void }) {+ return (+ <div className="border-t border-[var(--color-border-default)] px-1 py-12 text-center">+ <h3 className="text-[15px] font-semibold text-[var(--color-text-primary)]">+ No opportunities match these filters+ </h3>+ <p className="mx-auto mt-2 max-w-[60ch] text-sm text-[var(--color-text-tertiary)]">+ The counts beside each filter come from the whole repository, so a combination can still+ be empty.+ </p>+ <button+ type="button"+ onClick={onClear}+ className="mt-4 rounded text-sm font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ Clear filters+ </button>+ </div>+ );+}++function Notice({+ tone,+ children,+}: {+ tone: "warning" | "neutral";+ children: React.ReactNode;+}) {+ const Icon = tone === "warning" ? AlertTriangle : Info;+ const ink = tone === "warning" ? "var(--color-warning)" : "var(--color-text-tertiary)";+ return (+ <p+ role="status"+ className="flex items-start gap-2 border-l-2 py-1.5 pl-3 text-sm text-[var(--color-text-secondary)]"+ style={{ borderColor: ink }}+ >+ <Icon className="mt-0.5 h-4 w-4 shrink-0" style={{ color: ink }} aria-hidden="true" />+ <span className="min-w-0">{children}</span>+ </p>+ );+}++/** An id minted by an older model still resolves; it just needs a refresh. */+export function StaleModelNotice({ summary }: { summary: PerformanceOpportunitySummary }) {+ return (+ <Notice tone="warning">+ These opportunities were grouped by an earlier analysis model+ {summary.performance_model_version != null+ ? ` (version ${summary.performance_model_version})`+ : ""}+ . Ids and grouping can move on the next index update, so treat a saved link as approximate.+ </Notice>+ );+}++/** Name the value the server did not recognize instead of showing zero rows. */+export function IgnoredArgumentsNotice({ ignored }: { ignored: Record<string, string> }) {+ const entries = Object.entries(ignored);+ if (entries.length === 0) return null;+ return (+ <Notice tone="warning">+ The server did not recognize{" "}+ {entries.map(([key, value], index) => (+ <span key={key}>+ {index > 0 ? ", " : ""}+ <code className="font-mono text-xs">+ {key}={value}+ </code>+ </span>+ ))}+ , so that filter was not applied. The counts below describe the unfiltered result.+ </Notice>+ );+}diff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsxindex 2117ea6d1..267a4bd39 100644--- a/packages/web/src/app/repos/[id]/code-health/page.tsx+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx@@ -26,7 +26,18 @@import { useParams, useRouter, useSearchParams } from "next/navigation";import { useCallback, useMemo, useState } from "react";import useSWR, { useSWRConfig } from "swr";-import { HeartPulse, RotateCw } from "lucide-react";+import {+ Bug,+ FlaskConical,+ Gauge,+ HeartPulse,+ LayoutDashboard,+ RotateCw,+ Scissors,+ Shield,+ Waypoints,+ type LucideIcon,+} from "lucide-react";import { PageShell } from "@repowise-dev/ui/shared/page-shell";import { ViewTabs } from "@repowise-dev/ui/shared/view-tabs";import { OverviewSection } from "@repowise-dev/ui/overview";@@ -78,6 +89,22 @@ const TAB_LABELS: Record<TabId, string> = {impact: "Blast radius",};+/**+ * One mark per tab, to make the row scannable without reading every word.+ * They are identity, not status: monochrome, inheriting the tab's own color, so+ * no icon can imply a health band. The label still carries the accessible name,+ * which is why `ViewTabs` renders them `aria-hidden`.+ */+const TAB_ICONS: Record<TabId, LucideIcon> = {+ triage: LayoutDashboard,+ performance: Gauge,+ findings: Bug,+ coverage: FlaskConical,+ "dead-code": Scissors,+ security: Shield,+ impact: Waypoints,+};+/*** Legacy tab ids → their new home. `heatmap` was the old churn tab and* `hotspots` its successor; both now land on the map, whose churn lens replaced@@ -292,11 +319,15 @@ export default function CodeHealthPage() {) : null}<ViewTabs- tabs={TABS.map((id) => ({- id,- label: TAB_LABELS[id],- ...(badges[id] !== undefined ? { badge: badges[id] } : {}),- }))}+ tabs={TABS.map((id) => {+ const Icon = TAB_ICONS[id];+ return {+ id,+ label: TAB_LABELS[id],+ icon: <Icon className="h-3.5 w-3.5" />,+ ...(badges[id] !== undefined ? { badge: badges[id] } : {}),+ };+ })}value={activeTab}onValueChange={setTab}>diff --git a/packages/web/src/components/code-health/performance-tab.tsx b/packages/web/src/components/code-health/performance-tab.tsxindex 492ada5b6..8433d761e 100644--- a/packages/web/src/components/code-health/performance-tab.tsx+++ b/packages/web/src/components/code-health/performance-tab.tsx@@ -1,31 +1,62 @@"use client";-import { useRouter } from "next/navigation";+import { useCallback, useMemo } from "react";+import { useRouter, useSearchParams } from "next/navigation";import { PerformanceView, type PerformanceViewAdapter } from "@repowise-dev/ui/health";import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";import {getPerformanceOpportunities,+ getPerformanceOpportunity,getPerformanceOpportunityFindings,listHealthFindings,} from "@/lib/api/code-health";import { getRefactoringPlan } from "@/lib/api/refactoring";+/** The queue's own filter state, kept out of the page's `tab` and `lens`. */+const FILTER_PARAM = "perf";+export function PerformanceTab({ repoId }: { repoId: string }) {const router = useRouter();- const prefix = `/repos/${repoId}`;- const adapter: PerformanceViewAdapter = {- cacheKey: repoId,- listFindings: (options) => listHealthFindings(repoId, options),- getPerformanceOpportunities: (options) => getPerformanceOpportunities(repoId, options),- getPerformanceOpportunityFindings: (opportunityId, options) =>- getPerformanceOpportunityFindings(repoId, opportunityId, options),- getRefactoringPlan: (planId) => getRefactoringPlan(repoId, planId),- refactoringPlanHref: (planId) =>- `/repos/${repoId}/refactoring?type=performance_fix&plan=${encodeURIComponent(planId)}`,- fileHref: (path) => fileEntityPath(prefix, path),- symbolHref: (symbolId) => symbolEntityPath(prefix, symbolId),- navigate: (href) => router.push(href),- };+ const searchParams = useSearchParams();+ // Held stable across renders: the queue memoizes its rows against it, and a+ // fresh object every render would defeat that for twenty rows at a time.+ const adapter: PerformanceViewAdapter = useMemo(() => {+ const prefix = `/repos/${repoId}`;+ return {+ cacheKey: repoId,+ listFindings: (options) => listHealthFindings(repoId, options),+ getPerformanceOpportunities: (options) => getPerformanceOpportunities(repoId, options),+ getPerformanceOpportunity: (opportunityId, options) =>+ getPerformanceOpportunity(repoId, opportunityId, options),+ getPerformanceOpportunityFindings: (opportunityId, options) =>+ getPerformanceOpportunityFindings(repoId, opportunityId, options),+ getRefactoringPlan: (planId) => getRefactoringPlan(repoId, planId),+ refactoringPlanHref: (planId) =>+ `/repos/${repoId}/refactoring?type=performance_fix&plan=${encodeURIComponent(planId)}`,+ fileHref: (path) => fileEntityPath(prefix, path),+ symbolHref: (symbolId) => symbolEntityPath(prefix, symbolId),+ navigate: (href) => router.push(href),+ };+ }, [repoId, router]);++ // A filtered queue is worth sharing and worth surviving a reload, so the+ // serialized state rides in one parameter beside the page's own.+ const onFiltersChange = useCallback(+ (search: string) => {+ const sp = new URLSearchParams(searchParams.toString());+ if (search) sp.set(FILTER_PARAM, search);+ else sp.delete(FILTER_PARAM);+ const qs = sp.toString();+ router.replace(qs ? `?${qs}` : "?", { scroll: false });+ },+ [router, searchParams],+ );- return <PerformanceView adapter={adapter} />;+ return (+ <PerformanceView+ adapter={adapter}+ initialFilters={searchParams.get(FILTER_PARAM) ?? undefined}+ onFiltersChange={onFiltersChange}+ />+ );}