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(ui): synthetic system graphs and a render budget bench (#4597)
Raghav Chamadiya488a3d4bc74a
diff --git a/packages/ui/__tests__/workspace/fixtures/synthetic-system-graph.ts b/packages/ui/__tests__/workspace/fixtures/synthetic-system-graph.tsnew file mode 100644index 000000000..25658f4db--- /dev/null+++ b/packages/ui/__tests__/workspace/fixtures/synthetic-system-graph.ts@@ -0,0 +1,266 @@+/**+ * Seeded synthetic system graphs for the System Map benches and scale tests.+ *+ * Shaped on the eShop reference estate's artifact: every node is a service in+ * its own repo, and edges follow its kind mix (59% package, 20% event, 16%+ * HTTP, 5% gRPC). Package edges fan into a minority of library repos with a+ * Zipf skew, the way eShop's build edges pile onto a few shared libraries;+ * runtime edges join non-library services, mostly inside one group. Edge ids,+ * strategies, confidences and weights follow the core builder's output, so a+ * function that reads a real artifact reads this one the same way.+ */++import type {+ ExtractionDiagnostics,+ LinkStrategy,+ SystemEdge,+ SystemEdgeKind,+ SystemGraph,+ SystemNode,+} from "@repowise-dev/types";++/** A node carrying the optional system group a grouped artifact adds. */+export type SyntheticSystemNode = SystemNode & { group?: string };+export type SyntheticSystemGraph = Omit<SystemGraph, "nodes"> & { nodes: SyntheticSystemNode[] };++export interface SyntheticSystemGraphOptions {+ services: number;+ edges: number;+ /** Groups the services fall into; 1 or fewer leaves `group` off every node. */+ groups?: number;+ seed?: number;+}++/** eShop's measured edge-kind mix: 26, 9, 7 and 2 of its 44 edges. */+export const ESHOP_KIND_MIX: ReadonlyArray<readonly [SystemEdgeKind, number]> = [+ ["package", 26 / 44],+ ["event", 9 / 44],+ ["http", 7 / 44],+ ["grpc", 2 / 44],+];++/** Share of services that are libraries (package-edge targets only). */+const LIBRARY_SHARE = 0.25;+/** Share of runtime edges that stay inside the caller's group. */+const IN_GROUP_SHARE = 0.7;++interface KindShape {+ confidence: readonly number[];+ strategy: readonly LinkStrategy[];+ weight: readonly [number, number];+ contractType: string | null;+ ref: (source: string, target: string, i: number) => string;+}++/** Per-kind values seen in the eShop artifact. */+const KIND_SHAPE: Partial<Record<SystemEdgeKind, KindShape>> = {+ package: {+ confidence: [1],+ strategy: ["manifest"],+ weight: [1, 1],+ contractType: null,+ ref: (source) => `dotnet_project_ref:${source}.csproj`,+ },+ event: {+ confidence: [0.7],+ strategy: ["exact_id"],+ weight: [1, 6],+ contractType: "topic",+ ref: (_s, target, i) => `topic::${target}.event${i}`,+ },+ http: {+ confidence: [0.7, 0.75, 0.85],+ strategy: ["exact_id", "unique_path", "service_mapped", "gateway_route"],+ weight: [2, 6],+ contractType: "http",+ ref: (_s, target, i) => `http::GET::/api/${target}/items${i}`,+ },+ grpc: {+ confidence: [0.65, 0.75],+ strategy: ["exact_id"],+ weight: [1, 2],+ contractType: "grpc",+ ref: (_s, target, i) => `grpc::${target}.Service/Call${i}`,+ },+};++/** mulberry32: small, fast, and identical on every platform for one seed. */+function rng(seed: number): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/** Largest-remainder split of `total` by `mix`, so the counts sum exactly. */+function splitByMix(total: number, mix: ReadonlyArray<readonly [SystemEdgeKind, number]>) {+ const raw = mix.map(([kind, share]) => ({ kind, exact: total * share, n: Math.floor(total * share) }));+ let left = total - raw.reduce((s, r) => s + r.n, 0);+ for (const r of [...raw].sort((a, b) => b.exact - b.n - (a.exact - a.n))) {+ if (left-- <= 0) break;+ r.n += 1;+ }+ return raw.map((r) => [r.kind, r.n] as const);+}++function emptyDiagnostics(totalLinks: number): ExtractionDiagnostics {+ return {+ total_providers: 0,+ total_consumers: 0,+ total_links: totalLinks,+ weak_link_count: 0,+ repo_breakdown: [],+ unmatched_consumers: [],+ unmatched_by_reason: {},+ orphan_providers: [],+ providers_by_layer: {},+ consumers_by_layer: {},+ http_consumers_unresolved: 0,+ http_consumer_coverage: null,+ };+}++interface Estate {+ ids: string[];+ groupOf: Map<string, string>;+ libraries: string[];+ runtime: string[];+ runtimeByGroup: Map<string, string[]>;+}++/** Service ids `g03.svc042`: a dotted family per group gives name-family grouping something to find. */+function estate(services: number, groupCount: number): Estate {+ const libraryCount = Math.max(1, Math.round(services * LIBRARY_SHARE));+ const width = String(services - 1).length;+ const groupWidth = String(groupCount - 1).length;+ const ids: string[] = [];+ const groupOf = new Map<string, string>();+ const runtimeByGroup = new Map<string, string[]>();+ for (let i = 0; i < services; i++) {+ const group = `g${String(i % groupCount).padStart(groupWidth, "0")}`;+ // The first `libraryCount` indices are libraries.+ const library = i < libraryCount;+ const id = `${group}.${library ? "lib" : "svc"}${String(i).padStart(width, "0")}`;+ ids.push(id);+ groupOf.set(id, group);+ if (!library) runtimeByGroup.set(group, [...(runtimeByGroup.get(group) ?? []), id]);+ }+ return { ids, groupOf, libraries: ids.slice(0, libraryCount), runtime: ids.slice(libraryCount), runtimeByGroup };+}++type Random = () => number;++function pickFrom<T>(random: Random, items: readonly T[]): T {+ return items[Math.floor(random() * items.length)] as T;+}++/** Endpoint pickers: package edges to Zipf-ranked library hubs, runtime edges mostly in-group. */+function endpointPicker(e: Estate, random: Random): (kind: SystemEdgeKind) => [string, string] {+ const zipf: number[] = [];+ e.libraries.reduce((sum, _l, r) => {+ zipf.push(sum + 1 / (r + 1));+ return sum + 1 / (r + 1);+ }, 0);+ const zipfTotal = zipf[zipf.length - 1] as number;+ const runtimePool = e.runtime.length > 1 ? e.runtime : e.ids;+ return (kind) => {+ if (kind === "package") {+ const source = pickFrom(random, e.ids);+ const x = random() * zipfTotal;+ return [source, e.libraries[zipf.findIndex((c) => c >= x)] as string];+ }+ const source = pickFrom(random, e.runtime.length > 0 ? e.runtime : e.ids);+ const own = e.runtimeByGroup.get(e.groupOf.get(source) as string) ?? [];+ const pool = own.length > 1 && random() < IN_GROUP_SHARE ? own : runtimePool;+ return [source, pickFrom(random, pool)];+ };+}++function placeEdges(e: Estate, edges: number, random: Random): SystemEdge[] {+ const pickEnds = endpointPicker(e, random);+ const out: SystemEdge[] = [];+ const seen = new Set<string>();+ for (const [kind, count] of splitByMix(edges, ESHOP_KIND_MIX)) {+ const shape = KIND_SHAPE[kind] as KindShape;+ let placed = 0;+ // Edges are unique per (source, target, kind), as the core builder merges+ // them; a bounded retry keeps an over-dense request from looping forever.+ for (let attempt = 0; placed < count && attempt < count * 50; attempt++) {+ const [source, target] = pickEnds(kind);+ const id = `${source}->${target}:${kind}`;+ if (source === target || seen.has(id)) continue;+ seen.add(id);+ const [lo, hi] = shape.weight;+ const weight = lo + Math.floor(random() * (hi - lo + 1));+ out.push({+ id,+ source,+ target,+ kind,+ match_type: "exact",+ confidence: pickFrom(random, shape.confidence),+ weight,+ structural: true,+ contract_refs: Array.from({ length: weight }, (_, i) => shape.ref(source, target, i)),+ strategy: pickFrom(random, shape.strategy),+ });+ placed++;+ }+ if (placed < count) {+ throw new Error(`cannot place ${count} distinct ${kind} edges among ${e.ids.length} services`);+ }+ }+ return out;+}++/** Nodes with counts and contract types derived from their edges, as the core builder derives them. */+function nodesFor(e: Estate, edges: readonly SystemEdge[], grouped: boolean): SyntheticSystemNode[] {+ const provided = new Map<string, number>();+ const consumed = new Map<string, number>();+ const types = new Map<string, Set<string>>();+ for (const edge of edges) {+ const type = KIND_SHAPE[edge.kind]?.contractType;+ if (!type) continue;+ provided.set(edge.target, (provided.get(edge.target) ?? 0) + edge.weight);+ consumed.set(edge.source, (consumed.get(edge.source) ?? 0) + edge.weight);+ for (const end of [edge.source, edge.target]) types.set(end, (types.get(end) ?? new Set()).add(type));+ }+ const linked = new Set(edges.flatMap((edge) => [edge.source, edge.target]));+ return e.ids.map((id) => ({+ id,+ repo: id,+ service_path: null,+ name: id,+ kind: "service",+ provider_count: provided.get(id) ?? 0,+ consumer_count: consumed.get(id) ?? 0,+ contract_types: [...(types.get(id) ?? [])].sort(),+ is_orphan_provider: false,+ is_orphan_consumer: false,+ is_isolated: !linked.has(id),+ ...(grouped ? { group: e.groupOf.get(id) as string } : {}),+ }));+}++export function makeSyntheticSystemGraph({+ services,+ edges,+ groups = 1,+ seed = 1,+}: SyntheticSystemGraphOptions): SyntheticSystemGraph {+ if (services < 2) throw new Error("a synthetic system graph needs at least two services");+ const groupCount = Math.max(1, Math.min(groups, services));+ const e = estate(services, groupCount);+ const out = placeEdges(e, edges, rng(seed));+ return {+ version: 2,+ generated_at: "2026-10-24T00:00:00Z",+ nodes: nodesFor(e, out, groupCount > 1),+ edges: out,+ diagnostics: emptyDiagnostics(out.length),+ };+}diff --git a/packages/ui/__tests__/workspace/synthetic-system-graph.test.ts b/packages/ui/__tests__/workspace/synthetic-system-graph.test.tsnew file mode 100644index 000000000..23d7ed238--- /dev/null+++ b/packages/ui/__tests__/workspace/synthetic-system-graph.test.ts@@ -0,0 +1,51 @@+import { describe, it, expect } from "vitest";+import { collapseToRepos } from "../../src/workspace/system-map/collapse";+import { ESHOP_KIND_MIX, makeSyntheticSystemGraph } from "./fixtures/synthetic-system-graph";++describe("makeSyntheticSystemGraph", () => {+ it("is deterministic for a seed and differs across seeds", () => {+ const a = makeSyntheticSystemGraph({ services: 100, edges: 1000, groups: 10, seed: 7 });+ const b = makeSyntheticSystemGraph({ services: 100, edges: 1000, groups: 10, seed: 7 });+ const c = makeSyntheticSystemGraph({ services: 100, edges: 1000, groups: 10, seed: 8 });+ expect(b).toEqual(a);+ expect(c.edges.map((e) => e.id)).not.toEqual(a.edges.map((e) => e.id));+ });++ it("follows the eShop kind mix exactly, rounded", () => {+ const g = makeSyntheticSystemGraph({ services: 300, edges: 3000, groups: 30 });+ expect(g.edges).toHaveLength(3000);+ const counts = new Map<string, number>();+ for (const e of g.edges) counts.set(e.kind, (counts.get(e.kind) ?? 0) + 1);+ for (const [kind, share] of ESHOP_KIND_MIX) {+ expect(Math.abs((counts.get(kind) ?? 0) - 3000 * share)).toBeLessThanOrEqual(1);+ }+ });++ it("emits a well-formed graph: unique ids, known endpoints, no self loops", () => {+ const g = makeSyntheticSystemGraph({ services: 30, edges: 300, groups: 3, seed: 3 });+ const ids = new Set(g.nodes.map((n) => n.id));+ expect(ids.size).toBe(30);+ expect(new Set(g.edges.map((e) => e.id)).size).toBe(g.edges.length);+ for (const e of g.edges) {+ expect(ids.has(e.source) && ids.has(e.target)).toBe(true);+ expect(e.source).not.toBe(e.target);+ expect(e.id).toBe(`${e.source}->${e.target}:${e.kind}`);+ expect(e.contract_refs).toHaveLength(e.weight);+ }+ // Package edges land only on library repos, which concentrates them in hubs.+ expect(g.edges.filter((e) => e.kind === "package").every((e) => e.target.includes(".lib"))).toBe(true);+ // The collapse path reads it like a real artifact.+ expect(collapseToRepos(g).nodes).toHaveLength(30);+ });++ it("tags groups only when asked for more than one", () => {+ const grouped = makeSyntheticSystemGraph({ services: 40, edges: 200, groups: 4 });+ expect(new Set(grouped.nodes.map((n) => n.group))).toEqual(new Set(["g0", "g1", "g2", "g3"]));+ const flat = makeSyntheticSystemGraph({ services: 18, edges: 44 });+ expect(flat.nodes.every((n) => !("group" in n))).toBe(true);+ });++ it("refuses an edge count the services cannot hold", () => {+ expect(() => makeSyntheticSystemGraph({ services: 4, edges: 400 })).toThrow(/cannot place/);+ });+});diff --git a/packages/ui/__tests__/workspace/system-map.bench.ts b/packages/ui/__tests__/workspace/system-map.bench.tsnew file mode 100644index 000000000..f631e71ee--- /dev/null+++ b/packages/ui/__tests__/workspace/system-map.bench.ts@@ -0,0 +1,50 @@+/**+ * Render-budget bench for the System Map's pure functions, over seeded+ * synthetic estates at four sizes (ten edges per service, a group per ten+ * services). Run with `npm run bench --workspace @repowise-dev/ui`.+ *+ * Add each new pure system-map function to `suite` below; the sizes and the+ * graphs are shared so every row is comparable.+ */++import { bench, describe } from "vitest";+import type { SystemEdgeKind } from "@repowise-dev/types";+import { applyView, computeSystemMapPositions, layoutSignature } from "../../src/workspace/system-map/layout";+import { collapseToRepos } from "../../src/workspace/system-map/collapse";+import { neighbourGroups, serviceResolver } from "../../src/workspace/system-map/system-map-model";+import { makeSyntheticSystemGraph } from "./fixtures/synthetic-system-graph";++const SIZES = [30, 100, 300, 1000] as const;+const RUNTIME_KINDS = new Set<SystemEdgeKind>(["http", "grpc", "socket", "event", "db"]);+/** ELK runs for seconds at the top sizes; a few samples are enough there. */+const SLOW = { iterations: 3, time: 0, warmupIterations: 1 } as const;++for (const services of SIZES) {+ const graph = makeSyntheticSystemGraph({+ services,+ edges: services * 10,+ groups: Math.max(1, Math.round(services / 10)),+ seed: services,+ });+ const hub = graph.edges.find((e) => e.kind === "package")?.target ?? graph.nodes[0]!.id;++ describe(`system map, ${services} services / ${graph.edges.length} edges`, () => {+ bench("applyView (runtime kinds)", () => {+ applyView(graph, { visibleKinds: RUNTIME_KINDS, collapsed: false });+ });+ bench("collapseToRepos", () => {+ collapseToRepos(graph);+ });+ bench("layoutSignature", () => {+ layoutSignature(graph);+ });+ bench("serviceResolver + neighbourGroups (hub, both ways)", () => {+ serviceResolver(graph, false);+ neighbourGroups(graph, hub, "in");+ neighbourGroups(graph, hub, "out");+ });+ bench("computeSystemMapPositions (ELK, grid past 500)", async () => {+ await computeSystemMapPositions(graph);+ }, SLOW);+ });+}diff --git a/packages/ui/__tests__/workspace/system-map.test.tsx b/packages/ui/__tests__/workspace/system-map.test.tsxindex a64855882..d36ad5db2 100644--- a/packages/ui/__tests__/workspace/system-map.test.tsx+++ b/packages/ui/__tests__/workspace/system-map.test.tsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeAll } from "vitest";-import { render, screen, fireEvent, within } from "@testing-library/react";+import { render, screen, fireEvent, within, waitFor } from "@testing-library/react";import type { CrossRepoBlastRadius, GraphEvidence, SystemEdge, SystemGraph, SystemNode } from "@repowise-dev/types";import { SystemMap } from "../../src/workspace/system-map/system-map";import { Segmented, SystemMapFilters } from "../../src/workspace/system-map/system-map-filters";@@ -451,6 +451,31 @@ describe("SystemMap chrome placement", () => {expect(flow.contains(dialog)).toBe(false);});+ it("reports aggregate, layout and paint to onPhase, in order", async () => {+ const onPhase = vi.fn();+ render(<SystemMap graph={g} onPhase={onPhase} />);+ await waitFor(() => expect(onPhase).toHaveBeenLastCalledWith("paint"));+ expect(onPhase.mock.calls.map(([p]) => p)).toEqual(["aggregate", "layout", "paint"]);+ });++ it("reports no phase when there is no graph to lay out", async () => {+ const onPhase = vi.fn();+ render(<SystemMap graph={null} error={new Error("boom")} onPhase={onPhase} />);+ await new Promise((r) => setTimeout(r, 50));+ expect(onPhase).not.toHaveBeenCalled();+ });++ it("reports layout only once the new graph's layout has run", async () => {+ const onPhase = vi.fn();+ const { rerender } = render(<SystemMap graph={g} onPhase={onPhase} />);+ await waitFor(() => expect(onPhase).toHaveBeenLastCalledWith("paint"));+ onPhase.mockClear();+ const next = graph([...g.nodes, node("db")], [...g.edges, edge("api", "db", { kind: "db" })]);+ rerender(<SystemMap graph={next} onPhase={onPhase} />);+ await waitFor(() => expect(onPhase).toHaveBeenLastCalledWith("paint"));+ expect(onPhase.mock.calls.map(([p]) => p)).toEqual(["aggregate", "layout", "paint"]);+ });+it("puts the host's toolbar in the section header, not on the canvas", () => {const { container } = render(<SystemMap graph={g} toolbar={<div>lens bar</div>} />);const flow = container.querySelector(".react-flow")! as HTMLElement;diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 3cc79b080..34c7c7248 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -143,6 +143,7 @@"scripts": {"type-check": "tsc --noEmit","test": "vitest run",+ "bench": "vitest bench --run","gates": "bash ./scripts/ui-gates.sh"},"dependencies": {diff --git a/packages/ui/src/workspace/system-map/index.ts b/packages/ui/src/workspace/system-map/index.tsindex 6231fd98c..8943177b8 100644--- a/packages/ui/src/workspace/system-map/index.ts+++ b/packages/ui/src/workspace/system-map/index.ts@@ -72,6 +72,7 @@ export {type RoleStyle,} from "./architecture";export { useSystemMapLayout, type SystemMapLayout, type UseSystemMapLayoutArgs } from "./use-system-map-layout";+export type { SystemMapPhase } from "./use-system-map-phases";export {applyView,applyCollapse,diff --git a/packages/ui/src/workspace/system-map/system-map.tsx b/packages/ui/src/workspace/system-map/system-map.tsxindex 70fa28c5f..339d8ca57 100644--- a/packages/ui/src/workspace/system-map/system-map.tsx+++ b/packages/ui/src/workspace/system-map/system-map.tsx@@ -37,6 +37,7 @@ import { SystemMapDrawer, type SystemMapDrawerData } from "./system-map-drawer";import { SystemMapFocusContext, createSystemMapFocusStore } from "./system-map-focus";import { edgeKindStyle, isGatewayRouted } from "./edge-kinds";import { useSystemMapLayout } from "./use-system-map-layout";+import { useSystemMapPhases, type SystemMapPhase } from "./use-system-map-phases";import { resolveViewSelection } from "./system-map-model";import { SYSTEM_MAP_MAX_LAYOUT_NODES, SYSTEM_MAP_NODE_SIZE, applyCollapse, type SystemMapView } from "./layout";import type { RepoHealth, SystemMapOverlay, SystemMapSelection } from "./types";@@ -70,6 +71,8 @@ export interface SystemMapProps {/** Controlled selection, so the host can put it in the URL. */selection?: SystemMapSelection;onSelectionChange?: (selection: SystemMapSelection) => void;+ /** Called as each render phase completes, for host-side timing. */+ onPhase?: (phase: SystemMapPhase) => void;}export function SystemMap(props: SystemMapProps) {@@ -95,6 +98,7 @@ function SystemMapInner({drawer,selection: controlledSelection,onSelectionChange,+ onPhase,}: SystemMapProps) {const [hiddenKinds, setHiddenKinds] = useState<Set<SystemEdgeKind>>(() => new Set());const [collapsed, setCollapsed] = useState(false);@@ -140,6 +144,7 @@ function SystemMapInner({...(overlay && !collapsed ? { overlay } : {}),...(roleByNodeId ? { roleByNodeId } : {}),});+ useSystemMapPhases(onPhase, viewGraph, layoutLoading);// Lists and the URL name raw ids; map them onto what is drawn, and show a// hidden kind or the service view when that is the only way to draw them.diff --git a/packages/ui/src/workspace/system-map/use-system-map-phases.ts b/packages/ui/src/workspace/system-map/use-system-map-phases.tsnew file mode 100644index 000000000..2cbf5ad8f--- /dev/null+++ b/packages/ui/src/workspace/system-map/use-system-map-phases.ts@@ -0,0 +1,54 @@+"use client";++/**+ * Reports when the map finishes each render phase, so a host can time them+ * (performance marks, a trace) without this package knowing how. Observes the+ * layout hook's outputs only; it never changes what is drawn.+ */++import { useEffect, useRef } from "react";+import type { SystemGraph } from "@repowise-dev/types";++/**+ * `aggregate`: a new drawn graph is computed (every view change). `layout`: a+ * layout run finished (not reported for a cached layout or a kind toggle,+ * which run none). `paint`: the frame after that layout was painted.+ */+export type SystemMapPhase = "aggregate" | "layout" | "paint";++export function useSystemMapPhases(+ onPhase: ((phase: SystemMapPhase) => void) | undefined,+ viewGraph: SystemGraph | null,+ layoutLoading: boolean,+): void {+ const notify = useRef(onPhase);+ notify.current = onPhase;+ const wasLoading = useRef(layoutLoading);+ const drawn = useRef(viewGraph);+ drawn.current = viewGraph;++ useEffect(() => {+ if (viewGraph) notify.current?.("aggregate");+ }, [viewGraph]);++ // Keyed on the loading flag falling, not on the view graph: the layout hook+ // raises it a commit after a new graph arrives, so the graph alone would+ // report a layout that has not run yet. A null or empty graph clears the+ // flag without a run, so it reports nothing.+ useEffect(() => {+ const settled = wasLoading.current && !layoutLoading && (drawn.current?.nodes.length ?? 0) > 0;+ wasLoading.current = layoutLoading;+ if (!settled || !notify.current) return;+ notify.current("layout");+ if (typeof requestAnimationFrame !== "function") return;+ // The second frame callback runs after the first frame was painted.+ let inner = 0;+ const outer = requestAnimationFrame(() => {+ inner = requestAnimationFrame(() => notify.current?.("paint"));+ });+ return () => {+ cancelAnimationFrame(outer);+ cancelAnimationFrame(inner);+ };+ }, [layoutLoading]);+}diff --git a/packages/web/src/app/workspace/system-map/page.tsx b/packages/web/src/app/workspace/system-map/page.tsxindex eae14f020..c81153c66 100644--- a/packages/web/src/app/workspace/system-map/page.tsx+++ b/packages/web/src/app/workspace/system-map/page.tsx@@ -40,6 +40,7 @@ import {useWorkspaceArchitecture,} from "@/lib/hooks/use-workspace";import { httpLinkedStat } from "@/lib/http-link-coverage";+import { markSystemMap, useSystemMapPerfMarks } from "@/lib/system-map-perf";import { useRepoContracts } from "./use-repo-contracts";const LENSES: readonly SystemMapLens[] = ["none", "blast", "breaking", "conformance", "core"];@@ -72,6 +73,8 @@ export default function SystemMapPage() {const { data: conformance, error: conformanceError } = useWorkspaceConformance();const { data: breaking, error: breakingError } = useWorkspaceBreakingChanges();+ useSystemMapPerfMarks(graph);+// Selection, lens and blast target live in the URL, so a view can be linked to.const selection = useMemo<SystemMapSelection>(() => {const node = searchParams.get("node");@@ -233,6 +236,7 @@ export default function SystemMapPage() {{...(overlay ? { overlay } : {})}selection={selection}onSelectionChange={onSelectionChange}+ onPhase={markSystemMap}drawer={drawer}toolbar={<SystemMapLensControldiff --git a/packages/web/src/lib/system-map-perf.test.ts b/packages/web/src/lib/system-map-perf.test.tsnew file mode 100644index 000000000..4209896ca--- /dev/null+++ b/packages/web/src/lib/system-map-perf.test.ts@@ -0,0 +1,52 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { SYSTEM_MAP_PERF_CAP, markSystemMap, observeLongTasks } from "./system-map-perf";++afterEach(() => {+ vi.unstubAllGlobals();+ performance.clearMarks();+ performance.clearMeasures();+});++describe("system map performance marks", () => {+ it("puts an sm: mark on the timeline", () => {+ markSystemMap("data");+ markSystemMap("paint");+ expect(performance.getEntriesByType("mark").map((m) => m.name)).toEqual(["sm:data", "sm:paint"]);+ });++ it("keeps each mark name under the cap", () => {+ for (let i = 0; i < SYSTEM_MAP_PERF_CAP * 2 + 5; i++) markSystemMap("layout");+ markSystemMap("data");+ expect(performance.getEntriesByName("sm:layout").length).toBeLessThanOrEqual(SYSTEM_MAP_PERF_CAP);+ expect(performance.getEntriesByName("sm:data")).toHaveLength(1);+ });++ it("is a no-op where long tasks cannot be observed", () => {+ vi.stubGlobal("PerformanceObserver", { supportedEntryTypes: ["mark"] });+ const stop = observeLongTasks();+ expect(() => stop()).not.toThrow();+ });++ it("records each long task as an sm:longtask measure until stopped", () => {+ let deliver: (entries: { startTime: number; duration: number }[]) => void = () => {};+ const disconnect = vi.fn();+ class FakeObserver {+ static supportedEntryTypes = ["longtask"];+ constructor(cb: (list: { getEntries: () => unknown[] }) => void) {+ deliver = (entries) => cb({ getEntries: () => entries });+ }+ observe() {}+ disconnect = disconnect;+ }+ vi.stubGlobal("PerformanceObserver", FakeObserver);+ const stop = observeLongTasks();+ deliver([{ startTime: 0, duration: 75 }]);+ const measures = performance.getEntriesByName("sm:longtask");+ expect(measures).toHaveLength(1);+ expect(measures[0]!.duration).toBe(75);+ deliver(Array.from({ length: SYSTEM_MAP_PERF_CAP * 2 }, (_, i) => ({ startTime: i, duration: 60 })));+ expect(performance.getEntriesByName("sm:longtask").length).toBeLessThanOrEqual(SYSTEM_MAP_PERF_CAP);+ stop();+ expect(disconnect).toHaveBeenCalled();+ });+});diff --git a/packages/web/src/lib/system-map-perf.ts b/packages/web/src/lib/system-map-perf.tsnew file mode 100644index 000000000..cf8807ff1--- /dev/null+++ b/packages/web/src/lib/system-map-perf.ts@@ -0,0 +1,56 @@+/**+ * Performance marks for the System Map page: `sm:data` when the graph arrives,+ * then `sm:aggregate`, `sm:layout` and `sm:paint` from the map's phase+ * callback, plus one `sm:longtask` measure per main-thread task over 50 ms+ * while the page is open. Everything stays on the browser's own performance+ * timeline (the Performance panel, or `performance.getEntriesByName`); nothing+ * is sent anywhere. Each name keeps at most `SYSTEM_MAP_PERF_CAP` entries, so a+ * long session does not grow the timeline without bound.+ */++import { useEffect } from "react";+import type { SystemMapPhase } from "@repowise-dev/ui/workspace/system-map";++export type SystemMapMark = "data" | SystemMapPhase;++/** Entries kept per `sm:*` name; reaching it clears that name and starts again. */+export const SYSTEM_MAP_PERF_CAP = 100;++/** Clears a name's entries once it holds the cap, so the next one fits under it. */+function makeRoom(name: string, type: "mark" | "measure"): void {+ if (performance.getEntriesByName(name, type).length < SYSTEM_MAP_PERF_CAP) return;+ if (type === "mark") performance.clearMarks(name);+ else performance.clearMeasures(name);+}++export function markSystemMap(mark: SystemMapMark): void {+ if (typeof performance === "undefined" || typeof performance.mark !== "function") return;+ makeRoom(`sm:${mark}`, "mark");+ performance.mark(`sm:${mark}`);+}++/** Starts recording long tasks; returns the stop function. A no-op where unsupported. */+export function observeLongTasks(): () => void {+ if (+ typeof PerformanceObserver === "undefined" ||+ !PerformanceObserver.supportedEntryTypes?.includes("longtask")+ ) {+ return () => {};+ }+ const observer = new PerformanceObserver((list) => {+ for (const entry of list.getEntries()) {+ makeRoom("sm:longtask", "measure");+ performance.measure("sm:longtask", { start: entry.startTime, duration: entry.duration });+ }+ });+ observer.observe({ type: "longtask" });+ return () => observer.disconnect();+}++/** Marks `sm:data` each time a graph arrives and records long tasks while mounted. */+export function useSystemMapPerfMarks(graph: unknown): void {+ useEffect(() => observeLongTasks(), []);+ useEffect(() => {+ if (graph) markSystemMap("data");+ }, [graph]);+}