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
perf(files): stop the file page reading the whole repo to render one file (#1618)
Raghav Chamadiya23bffdcf5d43
diff --git a/packages/api-client/src/files.ts b/packages/api-client/src/files.tsindex d1e621ed1..3ee637994 100644--- a/packages/api-client/src/files.ts+++ b/packages/api-client/src/files.ts@@ -6,15 +6,21 @@ export async function getFilesIndex(repoId: string): Promise<FilesIndexResponse>return apiGet<FilesIndexResponse>(`/api/repos/${repoId}/files`);}-/** Canonical file-detail aggregate for the file entity page. */+/** Canonical file-detail aggregate for the file entity page.+ *+ * `fields: "slim"` drops the four unbounded payloads (wiki body, coverage+ * line array, per-function blame, per-finding `details`) for a caller that+ * only renders the summary numbers. */export async function getFileDetail(repoId: string,filePath: string,+ opts?: { fields?: "full" | "slim" },): Promise<FileDetailResponse> {// Encode each segment but keep the slashes — the server route uses a// catch-all path converter.const encoded = filePath.split("/").map(encodeURIComponent).join("/");- return apiGet<FileDetailResponse>(`/api/repos/${repoId}/files/${encoded}`);+ const qs = opts?.fields ? `?fields=${opts.fields}` : "";+ return apiGet<FileDetailResponse>(`/api/repos/${repoId}/files/${encoded}${qs}`);}/** Raw file content from the repo checkout (plain text, not JSON). */diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.pyindex 0e43d2c1b..74980b89e 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py@@ -29,6 +29,7 @@ from .dead_code import (update_dead_code_status,)from .health import (+ FILE_TREND_SNAPSHOT_WINDOW,HEALTH_SNAPSHOT_RETENTION,HealthSnapshotHeadline,HealthSnapshotScalars,@@ -60,6 +61,7 @@ from .refactoring import ()__all__ = [+ "FILE_TREND_SNAPSHOT_WINDOW","HEALTH_SNAPSHOT_RETENTION","HealthSnapshotHeadline","HealthSnapshotScalars",diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.pyindex d363cbbb0..816d41702 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py@@ -675,6 +675,22 @@ async def update_health_finding_status(# Declining-Health baseline plenty of headroom.HEALTH_SNAPSHOT_RETENTION: int = 50+#: How many snapshots a *single file's* trend line reads. Every snapshot row+#: carries two whole-repo ``{path: float}`` maps, so a route that wants one+#: path's score series pays the entire retention window in TEXT to extract a+#: handful of floats. Twenty points is more than the decline heuristics need+#: (``DECLINE_LOOKBACK`` is 5) and more than the sparkline can usefully draw.+#:+#: One knock-on: ``FileTrend.snapshot_count`` is documented as the size of the+#: whole repo window, and on the two routes that pass this it becomes the size+#: of *this* window instead. Nothing reads that field off a per-file trend+#: today — the dashboard and the trend view read it off the repo-level routes,+#: which are unlimited and unchanged. Projecting one path's series in SQL would+#: keep the count true and drop the bytes further, but no query in this module+#: extracts from a JSON column and doing that portably across SQLite and+#: PostgreSQL is its own change.+FILE_TREND_SNAPSHOT_WINDOW: int = 20+async def save_health_snapshot(session: AsyncSession,@@ -739,17 +755,30 @@ async def list_health_snapshots() -> list[HealthSnapshot]:"""Return snapshots **oldest-first** (the shape ``trends.diff_snapshots``expects). Pass ``limit`` to cap the most recent N (still returned- oldest-first for stable iteration)."""+ oldest-first for stable iteration).++ ``limit`` is pushed into SQL rather than applied to the fetched list. Every+ row carries ``per_file_scores_json`` and ``per_file_deductions_json``, both+ whole-repo ``{path: float}`` maps, and the table keeps+ ``HEALTH_SNAPSHOT_RETENTION`` (50) of them — so trimming in Python read the+ entire history off disk to throw most of it away. Taking the newest N+ descending and reversing gives the same list for a fraction of the bytes.+ """+ if limit is not None:+ newest_first = await session.execute(+ select(HealthSnapshot)+ .where(HealthSnapshot.repository_id == repository_id)+ .order_by(HealthSnapshot.taken_at.desc(), HealthSnapshot.id.desc())+ .limit(limit)+ )+ return list(reversed(newest_first.scalars().all()))q = (select(HealthSnapshot).where(HealthSnapshot.repository_id == repository_id).order_by(HealthSnapshot.taken_at.asc(), HealthSnapshot.id.asc()))result = await session.execute(q)- rows = list(result.scalars().all())- if limit is not None and len(rows) > limit:- rows = rows[-limit:]- return rows+ return list(result.scalars().all())class HealthSnapshotScalars(NamedTuple):diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.pyindex 8d826f06e..ab5a2f882 100644--- a/packages/core/src/repowise/core/persistence/crud/graph.py+++ b/packages/core/src/repowise/core/persistence/crud/graph.py@@ -9,7 +9,7 @@ from __future__ import annotationsimport jsonfrom collections.abc import Sequence-from sqlalchemy import and_, delete, func, or_, select+from sqlalchemy import and_, case, delete, func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom ..models import (@@ -587,8 +587,8 @@ async def get_graph_edges_for_node(on django's 120k-edge index: the hottest node (1,525 inbound edges)goes 10.9 ms to 38.2 ms; a low-degree node is unchanged at ~37 msbecause it was already scanning. The fix is an index on- ``(repository_id, target_node_id)``, which is a migration and is not- this change.+ ``(repository_id, target_node_id)``, which ``GraphEdge`` now declares+ as ``ix_graph_edges_repo_target``."""results: list[GraphEdge] = []@@ -738,6 +738,42 @@ async def get_all_file_metrics(return list(result.scalars().all())+async def get_pagerank_percentile(+ session: AsyncSession,+ repository_id: str,+ pagerank: float,+) -> int:+ """Percentile rank (0-100) of *pagerank* among the repo's file nodes.++ Counted in SQL. The callers that want one file's rank used to load every+ file node through :func:`get_all_file_metrics` and scan the list in Python,+ which is the whole repo graph materialized as ORM objects to produce a+ single integer.++ The arithmetic deliberately matches ``mcp_server._graph_utils.percentile_rank``+ — ``round(100 * below / n)`` over every ``node_type == "file"`` row — so+ swapping a caller over does not move the number it prints. Note this is not+ the same figure the Files *index* shows under ``pagerank_pct``: that one+ drops external and framework nodes first and divides by ``n - 1``.+ Reconciling the two is a behaviour change and not this function's job.+ """+ row = (+ await session.execute(+ select(+ func.count().label("total"),+ func.sum(case((GraphNode.pagerank < pagerank, 1), else_=0)).label("below"),+ ).where(+ GraphNode.repository_id == repository_id,+ GraphNode.node_type == "file",+ )+ )+ ).one()+ total = row.total or 0+ if not total:+ return 0+ return round(100.0 * (row.below or 0) / total)++async def get_cross_community_edges(session: AsyncSession,repository_id: str,diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 505269892..52f2cc093 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -319,6 +319,17 @@ class GraphEdge(Base):"edge_type",name="uq_graph_edge_typed",),+ # The unique constraint above serves every read keyed on+ # ``source_node_id`` and nothing keyed on ``target_node_id``, so the+ # inbound half of every adjacency question — "what depends on this?" —+ # scanned the table. ``get_graph_edges_for_node`` records the measured+ # cost in its own docstring: on django's 120k-edge index the hottest+ # node goes 10.9ms to 38.2ms once the inbound branch has to sort its+ # scan into a temp b-tree for the ranked cut. The file page pays that+ # twice per view, through that function and through+ # ``get_node_degree_counts``. Additive, so ``_reconcile_schema``+ # creates it on existing databases at the next ``init_db``.+ Index("ix_graph_edges_repo_target", "repository_id", "target_node_id"),)@@ -1135,6 +1146,10 @@ class DeadCodeFinding(Base):DateTime(timezone=True), nullable=False, default=_now_utc)+ # The table had no index, so the per-file lookup the file page issues+ # full-scanned every finding in the repo to return the handful on one path.+ __table_args__ = (Index("ix_dead_code_repo_path", "repository_id", "file_path"),)+class HealthFinding(Base):"""One biomarker hit produced by the code-health analyzer."""diff --git a/packages/server/src/repowise/server/routers/code_health/files_routes.py b/packages/server/src/repowise/server/routers/code_health/files_routes.pyindex 8968f2275..34b47a98d 100644--- a/packages/server/src/repowise/server/routers/code_health/files_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/files_routes.py@@ -155,7 +155,9 @@ async def file_score_breakdown(finding_dicts = await _attach_symbol_ids(session, repo_id, [_finding_to_dict(f) for f in findings])- snapshots = await crud.list_health_snapshots(session, repo_id)+ snapshots = await crud.list_health_snapshots(+ session, repo_id, limit=crud.FILE_TREND_SNAPSHOT_WINDOW+ )return {"file_path": file_path,"metric": _metric_to_dict(metric, _primary_and_magnitude(findings)) if metric else None,diff --git a/packages/server/src/repowise/server/routers/files.py b/packages/server/src/repowise/server/routers/files.pyindex ccd65676c..9b42a408c 100644--- a/packages/server/src/repowise/server/routers/files.py+++ b/packages/server/src/repowise/server/routers/files.py@@ -14,7 +14,7 @@ import bisectimport jsonfrom typing import Any-from fastapi import APIRouter, Depends, HTTPException+from fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession@@ -26,7 +26,7 @@ from repowise.core.persistence import crudfrom repowise.core.persistence.decision_graph import get_governing_decisionsfrom repowise.core.persistence.models import DeadCodeFinding, Page, WikiSymbolfrom repowise.server.deps import get_db_session, verify_api_key-from repowise.server.mcp_server._graph_utils import parse_community_meta, percentile_rank+from repowise.server.mcp_server._graph_utils import parse_community_metafrom repowise.server.routers.code_health import (_file_signals_to_dict,_file_trend_to_dict,@@ -68,7 +68,36 @@ def _blame_to_dict(b: Any) -> dict:}-def _symbol_slim(s: WikiSymbol) -> dict:+def _finding_dict(finding: Any, *, slim: bool) -> dict:+ """One health finding, with ``details`` emptied under ``fields=slim``.++ ``details_json`` is an open per-biomarker map and the only unbounded part+ of a finding; everything else is a scalar the summary rows read.+ """+ out = _finding_to_dict(finding)+ if slim:+ out["details"] = {}+ return out+++#: The nine of ``wiki_symbols``' seventeen columns the page renders. Selected+#: by name so the other eight — the doc strings and the decorator/parameter+#: JSON among them — are never read off the table, rather than hydrating whole+#: entities and discarding two thirds of each in :func:`_symbol_slim`.+_SYMBOL_COLUMNS = (+ WikiSymbol.symbol_id,+ WikiSymbol.name,+ WikiSymbol.kind,+ WikiSymbol.signature,+ WikiSymbol.start_line,+ WikiSymbol.end_line,+ WikiSymbol.visibility,+ WikiSymbol.complexity_estimate,+ WikiSymbol.is_async,+)+++def _symbol_slim(s: Any) -> dict:return {"symbol_id": s.symbol_id,"name": s.name,@@ -186,9 +215,24 @@ async def files_index(async def file_detail(repo_id: str,file_path: str,+ fields: str = Query(+ "full",+ description="How much of each block to return. 'full' (the default) is "+ "everything. 'slim' drops the four unbounded payloads — the wiki page "+ "body, the coverage line array, per-function blame, and each finding's "+ "'details' map — for a caller that renders the summary numbers only. "+ "'coverage.covered_line_count' is present in both modes, so the "+ "coverage headline survives the cut.",+ ),session: AsyncSession = Depends(get_db_session),) -> dict:"""Aggregate join over every per-file data source we persist."""+ if fields not in ("full", "slim"):+ raise HTTPException(+ status_code=400,+ detail=f"Unknown fields '{fields}'. Valid: full, slim.",+ )+ slim = fields == "slim"repo = await crud.get_repository(session, repo_id)if repo is None:raise HTTPException(status_code=404, detail="Repository not found")@@ -214,21 +258,20 @@ async def file_detail(raise HTTPException(status_code=404, detail=f"File not indexed: {file_path}")# --- Wiki page ref ----------------------------------------------------- page_row = (- await session.execute(- select(Page).where(- Page.repository_id == repo_id,- Page.page_type == "file_page",- Page.target_path == file_path,- )- )- ).scalar_one_or_none()+ # A primary-key get, not a three-column filter: ``Page.id`` *is*+ # ``"{page_type}:{target_path}"`` (see the model docstring), so the row this+ # predicate described was always reachable by key. The repo check stays+ # because one database can hold several repositories while the page id is+ # unique across the table.+ page_row = await session.get(Page, f"file_page:{file_path}")+ if page_row is not None and page_row.repository_id != repo_id:+ page_row = Nonewiki_page = ({"id": page_row.id,"title": page_row.title,"summary": page_row.summary,- "content": page_row.content,+ "content": "" if slim else page_row.content,"freshness_status": page_row.freshness_status,"confidence": page_row.confidence,"human_notes": page_row.human_notes,@@ -240,11 +283,13 @@ async def file_detail(# --- Health -----------------------------------------------------------findings = await crud.get_health_findings(session, repo_id, file_path=file_path)- snapshots = await crud.list_health_snapshots(session, repo_id)+ snapshots = await crud.list_health_snapshots(+ session, repo_id, limit=crud.FILE_TREND_SNAPSHOT_WINDOW+ )health = {"metric": _metric_to_dict(metric, _primary_and_magnitude(findings)) if metric else None,"breakdown": _score_breakdown_from_findings(findings) if findings else None,- "findings": [_finding_to_dict(f) for f in findings],+ "findings": [_finding_dict(f, slim=slim) for f in findings],"trend": _file_trend_to_dict(file_trend(snapshots, file_path)),"signals": _file_signals_to_dict(file_signals(git_meta, degrees)),}@@ -274,11 +319,15 @@ async def file_detail(coverage: dict | None = Noneif coverage_rows:c = coverage_rows[0]+ covered_lines = _json_or(c.covered_lines_json, [])coverage = {"line_coverage_pct": c.line_coverage_pct,"branch_coverage_pct": c.branch_coverage_pct,"total_coverable_lines": c.total_coverable_lines,- "covered_lines": _json_or(c.covered_lines_json, []),+ # Sent in both modes so "N of M lines hit" never has to count the+ # array client-side, which is what forced the array to travel.+ "covered_line_count": len(covered_lines),+ "covered_lines": [] if slim else covered_lines,"source_format": c.source_format,"ingested_at": c.ingested_at.isoformat() if c.ingested_at else None,"ingested_commit_sha": c.ingested_commit_sha,@@ -287,7 +336,6 @@ async def file_detail(# --- Graph context ------------------------------------------------------graph: dict | None = Noneif node is not None:- all_files = await crud.get_all_file_metrics(session, repo_id)assert degrees is not None # node is not None here, so degrees was loadedmeta = parse_community_meta(node)# Dependencies only. Unfiltered, this served the file's own `defines`@@ -335,8 +383,12 @@ async def file_detail("is_test": node.is_test,"symbol_count": node.symbol_count,"pagerank": round(node.pagerank or 0.0, 6),- "pagerank_percentile": percentile_rank(- node.pagerank or 0.0, [n.pagerank or 0.0 for n in all_files]+ # Counted in SQL. This used to load every file node in the repo+ # through ``get_all_file_metrics`` — a projection-free ``SELECT *``+ # with no limit — and scan the hydrated list in Python, to produce+ # this one integer.+ "pagerank_percentile": await crud.get_pagerank_percentile(+ session, repo_id, node.pagerank or 0.0),"in_degree": degrees["in_degree"],"out_degree": degrees["out_degree"],@@ -348,17 +400,18 @@ async def file_detail(# --- Symbols + per-function blame ---------------------------------------symbol_rows = (- (- await session.execute(- select(WikiSymbol)- .where(WikiSymbol.repository_id == repo_id, WikiSymbol.file_path == file_path)- .order_by(WikiSymbol.start_line)- )+ await session.execute(+ select(*_SYMBOL_COLUMNS)+ .where(WikiSymbol.repository_id == repo_id, WikiSymbol.file_path == file_path)+ .order_by(WikiSymbol.start_line))- .scalars()- .all()+ ).all()+ # Skipped outright under ``fields=slim`` — a query the caller cannot read.+ blame_rows = (+ []+ if slim+ else await crud.get_git_function_blames(session, repo_id, file_path=file_path))- blame_rows = await crud.get_git_function_blames(session, repo_id, file_path=file_path)# --- Governing decisions + dead code -------------------------------------governing = [diff --git a/packages/types/src/files.ts b/packages/types/src/files.tsindex b83e729bf..607ab9a7c 100644--- a/packages/types/src/files.ts+++ b/packages/types/src/files.ts@@ -129,6 +129,14 @@ export interface FileDetailCoverage {line_coverage_pct: number;branch_coverage_pct: number | null;total_coverable_lines: number;+ /**+ * How many lines `covered_lines` names. Always sent, including under+ * `fields=slim` where the array itself is dropped — the coverage headline+ * only ever wanted the count, and counting it client-side is what forced the+ * whole integer array across the wire. Optional so older payloads parse.+ */+ covered_line_count?: number;+ /** Empty under `fields=slim`; read `covered_line_count` for the total. */covered_lines: number[];source_format: string;ingested_at: string | null;diff --git a/packages/ui/src/files/file-coverage-tab.tsx b/packages/ui/src/files/file-coverage-tab.tsxindex 5adebcad0..c15483eed 100644--- a/packages/ui/src/files/file-coverage-tab.tsx+++ b/packages/ui/src/files/file-coverage-tab.tsx@@ -26,7 +26,7 @@ export function FileCoverageTab({ coverage, coverageCodeHtml }: FileCoverageTabP}const pct = coverage.line_coverage_pct;- const coveredCount = coverage.covered_lines.length;+ const coveredCount = coverage.covered_line_count ?? coverage.covered_lines.length;return (<div className="space-y-4">diff --git a/packages/ui/src/files/file-overview-tab.tsx b/packages/ui/src/files/file-overview-tab.tsxindex 49e8970b0..5128eb163 100644--- a/packages/ui/src/files/file-overview-tab.tsx+++ b/packages/ui/src/files/file-overview-tab.tsx@@ -38,6 +38,14 @@ export function FileOverviewTab({ data, symbolHref, fileHref }: FileOverviewTabPconst fixesIn = (symbolId: string) =>perSymbolSignal ? (rawFixCounts[symbolId] ?? 0) : 0;+ // Two full sorts of every symbol in the file to pick eight chips. Left+ // unmemoized deliberately: `useMemo` would make this a client component, and+ // this is one of the five tab bodies that are pure and hookless today —+ // which is what lets the hydration boundary move down to `file-health-tab`+ // alone. Radix mounts only the active tab, and the redundant tab-change+ // effect and the refetch-on-click are both gone, so the sorts now run once+ // per mount rather than on every parent render.+ //// Complexity picks the list, as it always has: biasing the whole sort on a// "was fixed" boolean would evict the file's most complex symbol in favour// of eight trivial helpers that took one fix each.diff --git a/packages/ui/src/files/file-page.tsx b/packages/ui/src/files/file-page.tsxindex d35e89731..a66216f4b 100644--- a/packages/ui/src/files/file-page.tsx+++ b/packages/ui/src/files/file-page.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useEffect, type ReactNode } from "react";+import { useState, type ReactNode } from "react";import { Flame, DoorOpen, Trash2, Users } from "lucide-react";import { Badge } from "../ui/badge";import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";@@ -74,12 +74,12 @@ export function FilePage({const defaultTab: FilePageTab =rawTab === "decisions" && !hasDecisions ? "overview" : rawTab;+ // `defaultTab` seeds the state and nothing more. The effect that re-applied+ // it on every change fired a redundant second state update on top of the one+ // `handleTabChange` had just done, and only ever mattered because the host+ // re-rendered the server tree on a tab click. It no longer does.const [activeTab, setActiveTab] = useState<FilePageTab>(defaultTab);- useEffect(() => {- setActiveTab(defaultTab);- }, [defaultTab]);-const handleTabChange = (tab: FilePageTab) => {setActiveTab(tab);onTabChange?.(tab);diff --git a/packages/web/src/app/repos/[id]/files/[...path]/page.tsx b/packages/web/src/app/repos/[id]/files/[...path]/page.tsxindex 00e9ea78c..b06dd4c61 100644--- a/packages/web/src/app/repos/[id]/files/[...path]/page.tsx+++ b/packages/web/src/app/repos/[id]/files/[...path]/page.tsx@@ -1,12 +1,20 @@import type { Metadata } from "next";import { notFound } from "next/navigation";-import { codeToHtml } from "shiki";+import { bundledLanguages, getSingletonHighlighter, type BundledLanguage } from "shiki";import { getFileContent, getFileDetail } from "@/lib/api/files";import { WikiMarkdown } from "@repowise-dev/ui/wiki/wiki-markdown";import { FilePageHost } from "@/components/files/file-page-host";import { FILE_PAGE_TABS, type FilePageTab } from "@repowise-dev/ui/files";import type { FileDetailResponse } from "@repowise-dev/types/files";+/** Matches the sibling routes (`decisions`, the repo root, the four workspace+ * pages). Reading `searchParams` below keeps the route itself dynamic, so+ * what this buys is the segment's default fetch cache: `apiGet` sets no+ * `cache`/`next` options, so the aggregate and the file content are otherwise+ * re-fetched on every render. Their inputs only move when the index is+ * rebuilt. */+export const revalidate = 30;+interface Props {params: Promise<{ id: string; path: string[] }>;searchParams: Promise<{ tab?: string }>;@@ -18,30 +26,47 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {return { title: filePath.split("/").pop() ?? filePath };}+/** Line-decorated shiki output is held in memory for the whole request and+ * then crosses the client boundary as a string, so the ceiling is on the+ * rendered page rather than on the source. 100KB is ~2.5k lines of code —+ * past that the coverage tab falls back to the summary-only view. */+const MAX_HIGHLIGHTED_BYTES = 100_000;++const THEMES = { light: "github-light", dark: "vesper" } as const;+/** Best-effort shiki render of the file with per-line coverage attributes.* Returns undefined when the source can't be fetched or highlighted —* the Coverage tab falls back to the summary-only view. */async function renderCoverageCode(- repoId: string,- filePath: string,+ content: string | undefined,detail: FileDetailResponse,): Promise<string | undefined> {+ if (!content) return undefined;if (!detail.coverage || detail.coverage.covered_lines.length === 0) return undefined;- let content: string;- try {- content = await getFileContent(repoId, filePath);- } catch {- return undefined;- }- // Guard against pathological files: line-decorated shiki output for very- // large sources costs memory on every request.- if (content.length > 400_000) return undefined;+ if (content.length > MAX_HIGHLIGHTED_BYTES) return undefined;++ // Resolve the grammar before highlighting rather than catching a throw and+ // running a second full pass in "text". An unknown language is a known+ // state, not an exception.+ const declared = detail.graph?.language?.toLowerCase();+ const lang =+ declared && declared in bundledLanguages ? (declared as BundledLanguage) : "text";+const covered = new Set(detail.coverage.covered_lines);- const lang = detail.graph?.language?.toLowerCase() || "text";- const highlight = (language: string) =>- codeToHtml(content, {- lang: language as Parameters<typeof codeToHtml>[1]["lang"],- themes: { light: "github-light", dark: "vesper" },+ try {+ // Singleton: one highlighter and one grammar/theme registry for the+ // process, loaded on demand. The `codeToHtml` shortcut used to build a+ // fresh one per call off the full bundle — every language, both themes.+ const highlighter = await getSingletonHighlighter({+ themes: [THEMES.light, THEMES.dark],+ langs: [],+ });+ if (lang !== "text" && !highlighter.getLoadedLanguages().includes(lang)) {+ await highlighter.loadLanguage(lang);+ }+ return highlighter.codeToHtml(content, {+ lang,+ themes: THEMES,defaultColor: false,transformers: [{@@ -51,14 +76,8 @@ async function renderCoverageCode(},],});- try {- return await highlight(lang);} catch {- try {- return await highlight("text");- } catch {- return undefined;- }+ return undefined;}}@@ -67,18 +86,30 @@ export default async function FileEntityPage({ params, searchParams }: Props) {const { tab } = await searchParams;const filePath = path.map(decodeURIComponent).join("/");+ const initialTab =+ tab && (FILE_PAGE_TABS as readonly string[]).includes(tab)+ ? (tab as FilePageTab)+ : undefined;++ // Only the Coverage tab renders highlighted source, and reading the file off+ // disk costs three DB queries of its own inside `/file-content`. Fetched+ // beside the aggregate rather than after it: the highlight needs `detail`,+ // but the source bytes do not.+ const wantsCoverage = initialTab === "coverage";let detail: FileDetailResponse;+ let source: string | undefined;try {- detail = await getFileDetail(id, filePath);+ [detail, source] = await Promise.all([+ getFileDetail(id, filePath),+ wantsCoverage+ ? getFileContent(id, filePath).catch(() => undefined)+ : Promise.resolve(undefined),+ ]);} catch {notFound();}- const coverageCodeHtml = await renderCoverageCode(id, filePath, detail);- const initialTab =- tab && (FILE_PAGE_TABS as readonly string[]).includes(tab)- ? (tab as FilePageTab)- : undefined;+ const coverageCodeHtml = await renderCoverageCode(source, detail);const docSlot = detail.wiki_page ? (<WikiMarkdown content={detail.wiki_page.content} />@@ -87,11 +118,29 @@ export default async function FileEntityPage({ params, searchParams }: Props) {? `/repos/${id}/docs?page=${encodeURIComponent(detail.wiki_page.id)}`: undefined;+ // `FilePageHost` is a client component taking `data` whole, so everything in+ // it is serialized into the RSC flight payload *and* inlined into the HTML —+ // downloaded twice. These two blocks were consumed above, on the server, and+ // are read by nothing in the client tree: the wiki body became `docSlot`,+ // and the coverage line array became `coverageCodeHtml` plus a count.+ const clientData: FileDetailResponse = {+ ...detail,+ wiki_page: detail.wiki_page ? { ...detail.wiki_page, content: "" } : null,+ coverage: detail.coverage+ ? {+ ...detail.coverage,+ covered_line_count:+ detail.coverage.covered_line_count ?? detail.coverage.covered_lines.length,+ covered_lines: [],+ }+ : null,+ };+return (<div className="p-4 sm:p-6 max-w-[1200px]"><FilePageHostrepoId={id}- data={detail}+ data={clientData}docSlot={docSlot}coverageCodeHtml={coverageCodeHtml}wikiHref={wikiHref}diff --git a/packages/web/src/components/files/file-page-host.tsx b/packages/web/src/components/files/file-page-host.tsxindex 7518b4ef2..42bc0ecd2 100644--- a/packages/web/src/components/files/file-page-host.tsx+++ b/packages/web/src/components/files/file-page-host.tsx@@ -2,7 +2,7 @@import type { ReactNode } from "react";import Link from "next/link";-import { useRouter } from "next/navigation";+import { usePathname, useRouter, useSearchParams } from "next/navigation";import { toast } from "sonner";import { FilePage, type FilePageTab, type FindingStatus } from "@repowise-dev/ui/files";import { updateFindingStatus } from "@/lib/api/code-health";@@ -28,13 +28,40 @@ export function FilePageHost({initialTab,}: FilePageHostProps) {const router = useRouter();+ const pathname = usePathname();+ // Reading `window.location.search` gave the URL the browser happened to be+ // showing rather than the one React rendered, and it is the pattern+ // packages/ui/README.md rules out for the shared components this hosts.+ const searchParams = useSearchParams();++ // Whether a server round trip could produce highlighted source at all. The+ // server declines to highlight when there is no coverage row and when the+ // covered-line set is empty, and both of those are visible from here — so a+ // click on Coverage for an un-ingested file must not pay for the aggregate+ // to be told "no" again. The two cases it cannot see (source over the size+ // cap, `/file-content` failing) are rare and cost one trip.+ const covered = data.coverage;+ const highlightPossible =+ !!covered && (covered.covered_line_count ?? covered.covered_lines.length) > 0;const onTabChange = (tab: FilePageTab) => {- const sp = new URLSearchParams(window.location.search);+ const sp = new URLSearchParams(searchParams.toString());if (tab === "overview") sp.delete("tab");else sp.set("tab", tab);const qs = sp.toString();- router.replace(qs ? `?${qs}` : window.location.pathname, { scroll: false });+ const url = qs ? `${pathname}?${qs}` : pathname;++ // Coverage is the one tab whose body is server-rendered (shiki-highlighted+ // source), so it is the one tab that can still need the round trip. Every+ // other tab reads data already in `data`, and `router.replace` re-ran the+ // whole ~18-query aggregate plus the highlight to hand back a payload+ // identical to the one on screen. A shallow history entry keeps the tab+ // deep-linkable and reloadable without refetching anything.+ if (tab === "coverage" && highlightPossible && !coverageCodeHtml) {+ router.replace(url, { scroll: false });+ return;+ }+ window.history.replaceState(null, "", url);};const onFindingStatusChange = async (findingId: string, status: FindingStatus) => {