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(web): make the coverage tab paginate, sort, and read accurately (#665)
Raghav Chamadiya937e1c4c4b5a
diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsxindex 7c3b3936f..3ed571242 100644--- a/packages/ui/src/health/coverage-view.tsx+++ b/packages/ui/src/health/coverage-view.tsx@@ -22,6 +22,7 @@ import type {import { Skeleton } from "../ui/skeleton";import { EmptyState } from "../shared/empty-state";import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";+import { ResultsFooter } from "../shared/results-footer";import { MetricCard } from "../shared/metric-card";import { CollapsibleSection } from "../shared/collapsible-section";@@ -45,7 +46,7 @@ export function CoverageView({ adapter }: { adapter: CodeHealthAdapter }) {const { data, isLoading, error } = useSWR<HealthCoverageResponse>(`code-health-coverage:${adapter.cacheKey}`,- () => adapter.getCoverage({ limit: 1000 }),+ () => adapter.getCoverage({ limit: 5000 }),{ revalidateOnFocus: false },);@@ -114,6 +115,21 @@ function CoverageBody({}) {const { summary, files, modules } = data;const [search, setSearch] = useState("");+ const [sortField, setSortField] = useState<string>("line_coverage_pct");+ const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");+ const PAGE = 50;+ const [visible, setVisible] = useState(PAGE);++ // Branch coverage is absent for common lcov flows (pytest emits none); only+ // surface the card + column when at least one file actually reports it.+ const hasBranch = summary.branch_coverage_pct != null ||+ files.some((f) => f.branch_coverage_pct != null);++ // A file with zero coverable lines (empty __init__, re-export shim) has no+ // meaningful percentage — treat it as null so it renders "—" and sinks in+ // worst-first sorts instead of masquerading as 0% covered.+ const covOf = (f: CoverageFileRow): number | null =>+ f.total_coverable_lines > 0 ? f.line_coverage_pct : null;const num = (v: unknown): number | null =>typeof v === "number" && Number.isFinite(v) ? v : null;@@ -142,6 +158,7 @@ function CoverageBody({return files.filter((f) =>+ f.total_coverable_lines > 0 &&f.line_coverage_pct != null &&f.line_coverage_pct < 30 &&(f.health_score == null || f.health_score < 6),@@ -176,11 +193,58 @@ function CoverageBody({return files.filter((f) => f.file_path.toLowerCase().includes(s));}, [files, search]);- const columns: ResponsiveColumn<CoverageFileRow>[] = [+ const sortedFiles = useMemo(() => {+ const dir = sortOrder === "asc" ? 1 : -1;+ const val = (f: CoverageFileRow): number | string | null => {+ switch (sortField) {+ case "file_path":+ return f.file_path;+ case "branch_coverage_pct":+ return f.branch_coverage_pct;+ case "total_coverable_lines":+ return f.total_coverable_lines;+ case "health_score":+ return f.health_score ?? null;+ default:+ return covOf(f);+ }+ };+ return [...filteredFiles].sort((a, b) => {+ const av = val(a);+ const bv = val(b);+ // Nulls (no data / no coverable lines) always sink, regardless of order.+ if (av == null && bv == null) return 0;+ if (av == null) return 1;+ if (bv == null) return -1;+ if (typeof av === "string" && typeof bv === "string") {+ return dir * av.localeCompare(bv);+ }+ return dir * ((av as number) - (bv as number));+ });+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [filteredFiles, sortField, sortOrder]);++ const visibleFiles = sortedFiles.slice(0, visible);++ const onSort = (key: string) => {+ if (key === sortField) {+ setSortOrder((o) => (o === "asc" ? "desc" : "asc"));+ } else {+ setSortField(key);+ // Coverage/health default to worst-first (asc); everything else desc.+ setSortOrder(+ key === "line_coverage_pct" || key === "health_score" ? "asc" : "desc",+ );+ }+ setVisible(PAGE);+ };++ const columns: (ResponsiveColumn<CoverageFileRow> | null)[] = [{key: "file_path",header: "File",priority: 1,+ sortable: true,render: (f) => (<span className="inline-flex items-center gap-1.5 font-mono text-xs text-[var(--color-text-primary)]"><span className="truncate max-w-[420px]" title={f.file_path}>@@ -194,27 +258,34 @@ function CoverageBody({key: "line_coverage_pct",header: "Line coverage",priority: 1,- render: (f) => <CoverageBar value={f.line_coverage_pct} size="sm" />,- },- {- key: "branch_coverage_pct",- header: "Branch",- priority: 3,- align: "right",- render: (f) => (- <span className="tabular-nums text-[var(--color-text-secondary)]">- {f.branch_coverage_pct == null ? "—" : `${f.branch_coverage_pct.toFixed(0)}%`}- </span>- ),+ sortable: true,+ render: (f) => <CoverageBar value={covOf(f)} size="sm" />,},+ hasBranch+ ? {+ key: "branch_coverage_pct",+ header: "Branch",+ priority: 3,+ align: "right",+ sortable: true,+ render: (f) => (+ <span className="tabular-nums text-[var(--color-text-secondary)]">+ {f.branch_coverage_pct == null+ ? "—"+ : `${f.branch_coverage_pct.toFixed(0)}%`}+ </span>+ ),+ }+ : null,{key: "total_coverable_lines",header: "Lines",priority: 3,align: "right",+ sortable: true,render: (f) => (<span className="tabular-nums text-[var(--color-text-tertiary)]">- {f.total_coverable_lines}+ {f.total_coverable_lines === 0 ? "—" : f.total_coverable_lines}</span>),},@@ -223,6 +294,7 @@ function CoverageBody({header: "Health",priority: 2,align: "right",+ sortable: true,render: (f) =>f.health_score == null ? (<span className="text-[var(--color-text-tertiary)]">—</span>@@ -264,10 +336,19 @@ function CoverageBody({},];+ const activeColumns = columns.filter(+ (c): c is ResponsiveColumn<CoverageFileRow> => c !== null,+ );+ const uncoveredLines = summary.total_lines - summary.covered_lines;+ const fetchTruncated = summary.file_count > files.length;+return (<div className="space-y-6"><div className="grid grid-cols-1 gap-3 sm:grid-cols-4">- <MetricCard label="Files" value={summary.file_count.toLocaleString()} />+ <MetricCard+ label="Files instrumented"+ value={summary.file_count.toLocaleString()}+ /><MetricCardlabel="Line coverage"value={@@ -282,14 +363,26 @@ function CoverageBody({</span>}/>- <MetricCard- label="Branch coverage"- value={- summary.branch_coverage_pct == null- ? "—"- : `${summary.branch_coverage_pct.toFixed(1)}%`- }- />+ {hasBranch ? (+ <MetricCard+ label="Branch coverage"+ value={+ summary.branch_coverage_pct == null+ ? "—"+ : `${summary.branch_coverage_pct.toFixed(1)}%`+ }+ />+ ) : (+ <MetricCard+ label="Uncovered lines"+ value={uncoveredLines.toLocaleString()}+ distBar={+ <span className="text-xs text-[var(--color-text-tertiary)]">+ lines with no test coverage+ </span>+ }+ />+ )}<MetricCardlabel="Source"value={@@ -307,17 +400,19 @@ function CoverageBody({<RiskCoverageScatter points={scatterPoints} onSelect={(p) => onOpenFile(p.file_path)} />- {untested.length > 0 ? <UntestedHotspotWarning entries={untested} /> : null}+ {untested.length > 0 ? (+ <UntestedHotspotWarning entries={untested} onSelect={onOpenFile} />+ ) : null}<section className="space-y-2"><h2 className="text-sm font-semibold text-[var(--color-text-primary)]">- Module coverage ({modules.length})+ Module coverage</h2><ModuleCoverageList modules={modules} /></section><CollapsibleSection- title={`Files (${filteredFiles.length.toLocaleString()})`}+ title={`Files (${summary.file_count.toLocaleString()})`}defaultOpen={false}><div className="flex items-center gap-2">@@ -326,24 +421,49 @@ function CoverageBody({</span><inputvalue={search}- onChange={(e) => setSearch(e.target.value)}+ onChange={(e) => {+ setSearch(e.target.value);+ setVisible(PAGE);+ }}placeholder="Filter path…"className="text-xs px-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-strong)]"/></div>- <ResponsiveTable- columns={columns}- rows={filteredFiles}- rowKey={(f) => f.file_path}- onRowClick={(f) => onOpenFile(f.file_path)}- stacked="sm"- empty={- <EmptyState- title="No files match"- description="Adjust the path filter to see coverage rows."+ <div className="overflow-hidden rounded-lg border border-[var(--color-border-default)]">+ <ResponsiveTable+ columns={activeColumns}+ rows={visibleFiles}+ rowKey={(f) => f.file_path}+ onRowClick={(f) => onOpenFile(f.file_path)}+ sortField={sortField}+ sortOrder={sortOrder}+ onSort={onSort}+ stacked="sm"+ bare+ empty={+ <EmptyState+ title="No files match"+ description="Adjust the path filter to see coverage rows."+ />+ }+ />+ {sortedFiles.length > 0 ? (+ <ResultsFooter+ shown={visibleFiles.length}+ total={sortedFiles.length}+ hasMore={visible < sortedFiles.length}+ onLoadMore={() => setVisible((v) => v + PAGE)}+ noun="files"/>- }- />+ ) : null}+ </div>+ {fetchTruncated ? (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Showing {files.length.toLocaleString()} of{" "}+ {summary.file_count.toLocaleString()} instrumented files (capped for+ performance).+ </p>+ ) : null}</CollapsibleSection></div>);diff --git a/packages/ui/src/health/module-coverage-list.tsx b/packages/ui/src/health/module-coverage-list.tsxindex a0aa154a8..c1772b994 100644--- a/packages/ui/src/health/module-coverage-list.tsx+++ b/packages/ui/src/health/module-coverage-list.tsx@@ -1,3 +1,7 @@+"use client";++import { useMemo, useState } from "react";+import { ChevronRight, Search } from "lucide-react";import { CoverageBar } from "./coverage-bar";export interface ModuleCoverageRow {@@ -10,9 +14,87 @@ export interface ModuleCoverageRow {export interface ModuleCoverageListProps {modules: ModuleCoverageRow[];+ /** Jump to a directory's files (optional; renders module labels as links). */+ onSelectModule?: ((module: string) => void) | undefined;+}++/**+ * Coverage rolled up into a two-level tree: every directory is grouped under+ * its top-level package (`packages/core`, `tests/unit`, …) so the flat 100++ * row dump becomes navigable. Groups show a weighted rollup bar and expand to+ * their child directories, worst-covered first. A directory with no coverable+ * lines renders "—" rather than a misleading red 0%.+ */+interface ModuleGroup {+ key: string;+ covered: number;+ total: number;+ files: number;+ pct: number | null;+ children: ModuleCoverageRow[];+}++function topKey(module: string): string {+ if (module === "(root)") return module;+ const parts = module.split("/");+ return parts.length > 1 ? parts.slice(0, 2).join("/") : (parts[0] ?? module);+}++function relLabel(module: string, groupKey: string): string {+ if (module === groupKey) return "./";+ return module.startsWith(groupKey + "/") ? module.slice(groupKey.length + 1) : module;}-export function ModuleCoverageList({ modules }: ModuleCoverageListProps) {+export function ModuleCoverageList({ modules, onSelectModule }: ModuleCoverageListProps) {+ const [search, setSearch] = useState("");+ const [open, setOpen] = useState<Set<string>>(new Set());++ const groups = useMemo<ModuleGroup[]>(() => {+ const byKey = new Map<string, ModuleGroup>();+ for (const m of modules) {+ const key = topKey(m.module);+ let g = byKey.get(key);+ if (!g) {+ g = { key, covered: 0, total: 0, files: 0, pct: null, children: [] };+ byKey.set(key, g);+ }+ g.covered += m.covered_lines;+ g.total += m.total_lines;+ g.files += m.files;+ g.children.push(m);+ }+ const out = [...byKey.values()];+ for (const g of out) {+ g.pct = g.total > 0 ? (g.covered / g.total) * 100 : null;+ g.children.sort((a, b) => a.line_coverage_pct - b.line_coverage_pct);+ }+ // Worst-covered groups first; groups with no coverable lines sink to the end.+ out.sort((a, b) => (a.pct ?? 101) - (b.pct ?? 101));+ return out;+ }, [modules]);++ const filtered = useMemo(() => {+ if (!search) return groups;+ const s = search.toLowerCase();+ return groups+ .map((g) => {+ if (g.key.toLowerCase().includes(s)) return g;+ const children = g.children.filter((c) => c.module.toLowerCase().includes(s));+ return children.length ? { ...g, children } : null;+ })+ .filter((g): g is ModuleGroup => g !== null);+ }, [groups, search]);++ // When searching, auto-expand matches so the hits are visible.+ const isOpen = (key: string) => (search ? true : open.has(key));+ const toggle = (key: string) =>+ setOpen((prev) => {+ const next = new Set(prev);+ if (next.has(key)) next.delete(key);+ else next.add(key);+ return next;+ });+if (modules.length === 0) {return (<p className="text-sm text-[var(--color-text-tertiary)]">@@ -20,21 +102,76 @@ export function ModuleCoverageList({ modules }: ModuleCoverageListProps) {</p>);}+return (- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] divide-y divide-[var(--color-border-default)]">- {modules.map((m) => (- <div key={m.module} className="px-4 py-3">- <div className="flex items-center justify-between gap-3 mb-1.5">- <span className="font-mono text-sm text-[var(--color-text-primary)] truncate">- {m.module}- </span>- <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums">- {m.files} files · {m.covered_lines}/{m.total_lines} lines- </span>- </div>- <CoverageBar value={m.line_coverage_pct} />- </div>- ))}+ <div className="space-y-2">+ <div className="relative w-full sm:w-72">+ <Search className="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--color-text-tertiary)]" />+ <input+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Filter modules…"+ className="w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] py-1.5 pl-7 pr-2 text-xs focus:border-[var(--color-border-strong)] focus:outline-none"+ />+ </div>++ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] divide-y divide-[var(--color-border-default)]">+ {filtered.map((g) => {+ const expanded = isOpen(g.key);+ return (+ <div key={g.key}>+ <button+ type="button"+ onClick={() => toggle(g.key)}+ className="flex w-full items-center gap-3 px-4 py-3 text-left hover:bg-[var(--color-bg-elevated)]"+ aria-expanded={expanded}+ >+ <ChevronRight+ className={`h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)] transition-transform ${expanded ? "rotate-90" : ""}`}+ />+ <span className="font-mono text-sm text-[var(--color-text-primary)] truncate">+ {g.key}+ </span>+ <span className="ml-auto shrink-0 text-xs text-[var(--color-text-tertiary)] tabular-nums">+ {g.children.length} dir{g.children.length === 1 ? "" : "s"} ·{" "}+ {g.total > 0 ? `${g.covered.toLocaleString()}/${g.total.toLocaleString()} lines` : "no coverable lines"}+ </span>+ <div className="w-40 shrink-0">+ <CoverageBar value={g.pct} size="sm" />+ </div>+ </button>++ {expanded ? (+ <div className="divide-y divide-[var(--color-table-divider)] border-t border-[var(--color-table-divider)] bg-[var(--color-bg-muted)]/30">+ {g.children.map((c) => {+ const cPct = c.total_lines > 0 ? c.line_coverage_pct : null;+ return (+ <div+ key={c.module}+ className={`flex items-center gap-3 py-2 pl-11 pr-4 ${onSelectModule ? "cursor-pointer hover:bg-[var(--color-bg-elevated)]" : ""}`}+ onClick={onSelectModule ? () => onSelectModule(c.module) : undefined}+ >+ <span+ className="font-mono text-xs text-[var(--color-text-secondary)] truncate"+ title={c.module}+ >+ {relLabel(c.module, g.key)}+ </span>+ <span className="ml-auto shrink-0 text-[11px] text-[var(--color-text-tertiary)] tabular-nums">+ {c.files} file{c.files === 1 ? "" : "s"}+ </span>+ <div className="w-40 shrink-0">+ <CoverageBar value={cPct} size="sm" />+ </div>+ </div>+ );+ })}+ </div>+ ) : null}+ </div>+ );+ })}+ </div></div>);}diff --git a/packages/ui/src/health/untested-hotspot-warning.tsx b/packages/ui/src/health/untested-hotspot-warning.tsxindex 09dd91534..4b6733a16 100644--- a/packages/ui/src/health/untested-hotspot-warning.tsx+++ b/packages/ui/src/health/untested-hotspot-warning.tsx@@ -1,4 +1,4 @@-import { AlertTriangle } from "lucide-react";+import { AlertTriangle, ArrowUpRight } from "lucide-react";export interface UntestedHotspotEntry {file_path: string;@@ -11,11 +11,14 @@ export interface UntestedHotspotEntry {export interface UntestedHotspotWarningProps {entries: UntestedHotspotEntry[];limit?: number;+ /** Open a file's coverage page. When set, rows become clickable. */+ onSelect?: ((filePath: string) => void) | undefined;}export function UntestedHotspotWarning({entries,limit = 5,+ onSelect,}: UntestedHotspotWarningProps) {if (entries.length === 0) return null;const shown = entries.slice(0, limit);@@ -32,15 +35,9 @@ export function UntestedHotspotWarning({</p></div></div>- <ul className="space-y-1.5">- {shown.map((e) => (- <li- key={e.file_path}- className="flex flex-wrap items-baseline gap-x-3 text-sm"- >- <span className="font-mono text-[var(--color-text-primary)] truncate">- {e.file_path}- </span>+ <ul className="space-y-0.5">+ {shown.map((e) => {+ const meta = (<span className="text-xs text-[var(--color-text-tertiary)] tabular-nums">{e.line_coverage_pct == null? "no coverage data"@@ -50,8 +47,36 @@ export function UntestedHotspotWarning({e.commit_count_90d > 0 &&` · ${e.commit_count_90d} commits/90d`}</span>- </li>- ))}+ );+ if (onSelect) {+ return (+ <li key={e.file_path}>+ <button+ type="button"+ onClick={() => onSelect(e.file_path)}+ className="group flex w-full flex-wrap items-baseline gap-x-3 rounded-md px-2 py-1 text-left text-sm hover:bg-[var(--color-warning)]/10"+ >+ <span className="inline-flex items-center gap-1 font-mono text-[var(--color-text-primary)] truncate">+ <span className="truncate">{e.file_path}</span>+ <ArrowUpRight className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)] group-hover:text-[var(--color-warning)]" />+ </span>+ {meta}+ </button>+ </li>+ );+ }+ return (+ <li+ key={e.file_path}+ className="flex flex-wrap items-baseline gap-x-3 px-2 py-1 text-sm"+ >+ <span className="font-mono text-[var(--color-text-primary)] truncate">+ {e.file_path}+ </span>+ {meta}+ </li>+ );+ })}</ul>{entries.length > limit && (<p className="text-xs text-[var(--color-text-tertiary)] mt-2">diff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsxindex 3aadd5cf4..d7e4f2c15 100644--- a/packages/web/src/app/repos/[id]/code-health/page.tsx+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx@@ -14,8 +14,8 @@*/import { useParams, useRouter, useSearchParams } from "next/navigation";-import { useCallback } from "react";-import useSWR from "swr";+import { useCallback, useState } from "react";+import useSWR, { useSWRConfig } from "swr";import { HeartPulse, RotateCw } from "lucide-react";import { PageShell } from "@repowise-dev/ui/shared/page-shell";import { ViewTabs } from "@repowise-dev/ui/shared/view-tabs";@@ -90,13 +90,31 @@ export default function CodeHealthPage() {: "health";// Shares the SWR key with TriageTab — the meta line costs no extra request.- const { data: overview, mutate } = useSWR<HealthOverviewResponse>(+ const { data: overview } = useSWR<HealthOverviewResponse>(`code-health-overview:${repoId}`,() => getHealthOverview(repoId, 25),{ revalidateOnFocus: false },);const meta = overview?.meta;+ // Refresh revalidates every SWR key for this repo (overview + each tab's own+ // keys — coverage, findings, hotspots…), so the button works on whichever+ // tab is active, not just the shared overview.+ const { mutate: mutateAll } = useSWRConfig();+ const [refreshing, setRefreshing] = useState(false);+ const refresh = useCallback(async () => {+ setRefreshing(true);+ try {+ await mutateAll(+ (key) => typeof key === "string" && key.includes(repoId),+ undefined,+ { revalidate: true },+ );+ } finally {+ setRefreshing(false);+ }+ }, [mutateAll, repoId]);+// Trend fetched ONCE here, fed to both the KPI sparklines (Triage) and the// folded Trend section — no second fetch, no second SWR key.const { data: trend, isLoading: trendLoading, error: trendError } =@@ -148,8 +166,11 @@ export default function CodeHealthPage() {description="Per-file health scores from complexity, duplication, coverage, churn, and ownership markers — ranked into a fix-next queue."maxWidth="wide"actions={- <Button size="sm" variant="outline" onClick={() => mutate()}>- <RotateCw className="h-3.5 w-3.5 mr-1.5" /> Refresh+ <Button size="sm" variant="outline" onClick={refresh} disabled={refreshing}>+ <RotateCw+ className={`h-3.5 w-3.5 mr-1.5 ${refreshing ? "animate-spin" : ""}`}+ />{" "}+ {refreshing ? "Refreshing…" : "Refresh"}</Button>}>