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(architecture-graph): stop the canvas doing per-node and per-frame work, and fix what dimming blends toward (#1149)
Raghav Chamadiyaf4a20ea131f6
diff --git a/packages/server/src/repowise/server/routers/graph/full_graph.py b/packages/server/src/repowise/server/routers/graph/full_graph.pyindex 3e0295bc0..8e78d3651 100644--- a/packages/server/src/repowise/server/routers/graph/full_graph.py+++ b/packages/server/src/repowise/server/routers/graph/full_graph.py@@ -4,6 +4,7 @@ from __future__ import annotationsfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.orm import load_onlyfrom fastapi import APIRouter, Depends, Queryfrom repowise.core.persistence import crud@@ -127,8 +128,35 @@ async def export_graph(view. ``dead_total``/``hot_total`` vs ``*_in_view`` let clients say"showing 12 of 37" instead of rendering silently-empty overlays."""+ # Load only the columns this endpoint actually serializes. The row carries+ # several large text columns (signature, qualified_name, file_path,+ # community_meta_json) that nothing here reads, and this query hydrates+ # EVERY node in the repo before capping — on a 31k-node repo that is several+ # MB of text fetched and discarded per request. The list below must stay a+ # superset of what `node_to_response` reads plus `node_id`: a deferred+ # column accessed under asyncio raises MissingGreenlet rather than lazily+ # loading, so adding a field there means adding it here.+ #+ # Caveat worth knowing before trusting the saving: on the truncated path+ # `crud.get_top_entry_points` runs its own unnarrowed query over every+ # symbol node to read `community_meta_json`. Those rows are already in the+ # identity map, so SQLAlchemy back-fills their deferred columns and the+ # saving applies only to file nodes there. Correctness is unaffected.node_result = await session.execute(select(GraphNode)+ .options(+ load_only(+ GraphNode.node_id,+ GraphNode.node_type,+ GraphNode.language,+ GraphNode.symbol_count,+ GraphNode.is_test,+ GraphNode.is_entry_point,+ GraphNode.pagerank,+ GraphNode.betweenness,+ GraphNode.community_id,+ )+ ).where(GraphNode.repository_id == repo_id).order_by(GraphNode.pagerank.desc()))diff --git a/packages/server/src/repowise/server/schemas/graph.py b/packages/server/src/repowise/server/schemas/graph.pyindex 150260535..61bc07147 100644--- a/packages/server/src/repowise/server/schemas/graph.py+++ b/packages/server/src/repowise/server/schemas/graph.py@@ -32,6 +32,13 @@ class GraphEdgeResponse(BaseModel):source: strtarget: strimported_names: list[str]+ # Both already exist and are fully populated on GraphEdge; they were simply+ # never serialized. Without edge_type the client can only infer edge kind+ # from `imported_names` being empty, which lumps every `defines` / `calls` /+ # `co_changes` / `has_method` row into one "dynamic" bucket. Optional so+ # every other consumer of this model gains them additively.+ edge_type: str | None = None+ confidence: float | None = Noneclass GraphExportResponse(BaseModel):diff --git a/packages/server/src/repowise/server/services/graph_views.py b/packages/server/src/repowise/server/services/graph_views.pyindex 6ba95bfd7..5fba4bea4 100644--- a/packages/server/src/repowise/server/services/graph_views.py+++ b/packages/server/src/repowise/server/services/graph_views.py@@ -61,6 +61,8 @@ def edge_response(e: GraphEdge) -> GraphEdgeResponse:source=e.source_node_id,target=e.target_node_id,imported_names=_parse_imported_names(e.imported_names_json),+ edge_type=e.edge_type,+ confidence=e.confidence,)diff --git a/packages/ui/COMPONENT_CONTRACTS.md b/packages/ui/COMPONENT_CONTRACTS.mdindex 7336d9500..0245dd2da 100644--- a/packages/ui/COMPONENT_CONTRACTS.md+++ b/packages/ui/COMPONENT_CONTRACTS.md@@ -720,10 +720,8 @@ Returns `null` when fewer than two headings are found.## `graph/*` — Graph layout, presentation, and chromePresentational graph pieces — chrome (toolbar/legend/sidebar/menu),-ELK layout primitives, `@xyflow/react` node/edge components, and the-floating `GraphTooltip`. The `GraphContext` provider also lives here-so node/edge components can be consumed independently of the-`graph-flow` data-fetching host.+ELK layout primitives, and `@xyflow/react` node/edge components.+State reaches the canvas as props; there is no graph context.`graph-flow` and the panels (`graph-doc-panel`, `graph-community-panel`,`path-finder-panel`) live HERE as presentational shells; `packages/web`@@ -732,19 +730,18 @@ the datasets in. The canvas renders via Sigma (`graph/sigma/`), not`@xyflow/react` (the xyflow node/edge components remain for the modulebrowser and embedded views).-### `graph/context` — `GraphContext`, `GraphProvider`, `useGraphContext`, `GraphContextValue`+### `graph/context` — `Signal`-Standalone context module. Node and edge components consume it to-read selection / hover / highlight state without depending on the-`graph-flow` host implementation. Hosts wrap their tree in-`<GraphProvider value={...}>`.+Shared graph vocabulary. `Signal` is the overlay-toggle union+(`"dead" | "hot" | "architecture" | "hideTests"`).-| Export | Type | Notes |-|--------|------|-------|-| `GraphContext` | `React.Context<GraphContextValue>` | Default value renders inert. |-| `GraphProvider` | `React.Provider<GraphContextValue>` | Alias of `GraphContext.Provider`. |-| `useGraphContext` | `() => GraphContextValue` | Sugar for `useContext(GraphContext)`. |-| `GraphContextValue` | interface | `highlightedPath`, `highlightedEdges`, `colorMode`, `riskScores`, `hoveredNodeId`, `connectedNodeIds`, `connectedEdgeIds`, `selectedNodeId`, `searchDimmedNodes`. |+This module used to export a `GraphContext` / `GraphProvider` /+`useGraphContext` / `GraphContextValue` trio mirroring ~18 fields of+`graph-flow`'s state. It had no consumers — every field already reaches+the canvas as a prop, and Sigma owns hover and highlight itself — so the+provider only re-rendered the shell and rebuilt an 18-key object on every+interaction. Removed rather than kept "just in case": a second path to+the same state would only drift from the props.### `graph/elk-layout` and `graph/use-elk-layout`@@ -758,24 +755,13 @@ Pure layout primitives. Functions: `layoutFileGraph`,### `graph/nodes/*`, `graph/edges/*``FileNode`, `ModuleGroupNode`, `DependencyEdge` — `@xyflow/react`-node/edge renderers. Consume `GraphContext` for selection / hover /-path-highlight state. Wear `FileNodeData` / `ModuleNodeData` /-`DependencyEdgeData` types from `graph/elk-layout`.+node/edge renderers. Receive selection / path-highlight state as props.+Wear `FileNodeData` / `ModuleNodeData` / `DependencyEdgeData` types from+`graph/elk-layout`.-### `graph/graph-tooltip` — `GraphTooltip`--Floating tooltip over a focused node, smart-positioned against the-viewport edges. Renders file or module metadata depending on-`nodeType`.--| Prop | Type | Required |-|------|------|----------|-| `nodeId` | `string` | yes |-| `nodeType` | `string` (`fileNode` / `moduleGroup`) | yes |-| `data` | `Record<string, unknown>` (cast to `FileNodeData` or `ModuleNodeData`) | yes |-| `x`, `y` | `number` | yes |-| `onClose` / `onViewDocs` | `() => void` | yes |-| `onExplore` | `() => void` | no — when omitted, the action button is hidden |+There is no React tooltip component. The hover card users see on the+Sigma canvas is painted by `defaultDrawNodeHover` in+`graph/sigma/use-sigma.ts`, not rendered as DOM.### `graph/graph-context-menu` — `GraphContextMenu`diff --git a/packages/ui/__tests__/graph/graph-tooltip.test.tsx b/packages/ui/__tests__/graph/graph-tooltip.test.tsxdeleted file mode 100644index e05e5d3f3..000000000--- a/packages/ui/__tests__/graph/graph-tooltip.test.tsx+++ /dev/null@@ -1,55 +0,0 @@-import { describe, it, expect, vi } from "vitest";-import { render, screen } from "@testing-library/react";-import { GraphTooltip } from "../../src/graph/graph-tooltip.js";--describe("GraphTooltip", () => {- it("renders file metadata for a file node", () => {- render(- <GraphTooltip- nodeId="src/foo/bar.ts"- nodeType="fileNode"- data={{- label: "bar.ts",- fullPath: "src/foo/bar.ts",- language: "typescript",- symbolCount: 3,- pagerank: 0.005,- betweenness: 0.002,- communityId: 1,- isTest: false,- isEntryPoint: false,- hasDoc: false,- }}- x={100}- y={100}- onClose={vi.fn()}- onViewDocs={vi.fn()}- />,- );- expect(screen.getByText("bar.ts")).toBeTruthy();- expect(screen.getByText("typescript")).toBeTruthy();- });-- it("renders module metadata for a moduleGroup node", () => {- render(- <GraphTooltip- nodeId="src/foo"- nodeType="moduleGroup"- data={{- label: "foo",- fullPath: "src/foo",- fileCount: 5,- symbolCount: 12,- avgPagerank: 0.001,- docCoveragePct: 0.6,- }}- x={50}- y={50}- onClose={vi.fn()}- onViewDocs={vi.fn()}- />,- );- expect(screen.getByText("Doc coverage")).toBeTruthy();- expect(screen.getByText("60%")).toBeTruthy();- });-});diff --git a/packages/ui/__tests__/graph/use-sigma-focus.test.tsx b/packages/ui/__tests__/graph/use-sigma-focus.test.tsxindex 357fa2c52..671b02c36 100644--- a/packages/ui/__tests__/graph/use-sigma-focus.test.tsx+++ b/packages/ui/__tests__/graph/use-sigma-focus.test.tsx@@ -88,7 +88,6 @@ describe("useSigmaRenderer.focusNode coordinate contract", () => {container,graph,selectedNodeId: null,- hoveredNodeId: null,highlightedPath: new Set(),highlightedEdges: new Set(),searchDimmedNodes: null,@@ -126,7 +125,6 @@ describe("useSigmaRenderer.focusNode coordinate contract", () => {container,graph,selectedNodeId: null,- hoveredNodeId: null,highlightedPath: new Set(),highlightedEdges: new Set(),searchDimmedNodes: null,diff --git a/packages/ui/__tests__/graph/use-sigma-style-reads.test.ts b/packages/ui/__tests__/graph/use-sigma-style-reads.test.tsnew file mode 100644index 000000000..bda703ffa--- /dev/null+++ b/packages/ui/__tests__/graph/use-sigma-style-reads.test.ts@@ -0,0 +1,118 @@+/**+ * Guards the cost of the Sigma color pass.+ *+ * `getComputedStyle` is a synchronous style read: doing one per node inside a+ * loop is the difference between a constant and a linear cost on every graph+ * load, colorMode toggle and theme flip. This pass regressed exactly that way+ * once — the node loop called the raw `getCommunityFamily` (two reads a node,+ * ~3,000 for a 1,500-node graph) while the hook that pre-resolves the 12+ * families once already existed — and the palette resolver was passed as the+ * argument to `useRef`, re-running on every render for a result React discards.+ *+ * The assertions are deliberately loose: they only pin the *shape* of the cost+ * (constant, not per-node), so palette work can be added without churn here.+ */+import { describe, it, expect, vi } from "vitest";+import { renderHook } from "@testing-library/react";+import Graph from "graphology";+import { useSigmaRenderer } from "../../src/graph/sigma/use-sigma.js";+import type {+ SigmaNodeAttributes,+ SigmaEdgeAttributes,+} from "../../src/graph/sigma/types.js";++const NODE_COUNT = 1500;++function makeGraph() {+ const graph = new Graph<SigmaNodeAttributes, SigmaEdgeAttributes>();+ for (let i = 0; i < NODE_COUNT; i++) {+ graph.addNode(`n${i}`, {+ x: i,+ y: i,+ size: 5,+ color: "#000000",+ label: `n${i}`,+ // Mix in hubs: they take a different branch of the color pass, and both+ // branches used to resolve community tokens per node.+ nodeType: i < 12 ? "hub" : "file",+ fullPath: `src/f${i}.ts`,+ language: "typescript",+ communityId: i % 12,+ pagerank: 0.001,+ betweenness: 0,+ isTest: false,+ isEntryPoint: false,+ hasDoc: false,+ symbolCount: 1,+ });+ }+ return graph;+}++function options(graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes>) {+ return {+ container: null,+ graph,+ selectedNodeId: null,+ highlightedPath: new Set<string>(),+ highlightedEdges: new Set<string>(),+ searchDimmedNodes: null,+ communityDimmedNodes: null,+ colorMode: "community" as const,+ activeSignals: new Set<never>(),+ graphTheme: "dark" as "light" | "dark",+ };+}++describe("hub disc label ink", () => {+ it("is resolved from the base fill, so dimming never brightens a label", () => {+ const graph = makeGraph();+ renderHook(() => useSigmaRenderer(options(graph)));++ // The colour pass must stamp the ink onto the node. If it did not, the+ // drawer would fall back to deriving ink from `data.color` — which Sigma+ // hands over POST-reducer, i.e. already dimmed. In dark mode every dimmed+ // fill lands near-black, so the luminance pick would flip to the light ink+ // and a dimmed hub's label would render brighter than an undimmed one:+ // the exact inverse of what dimming is for.+ const hubs = graph.filterNodes((_id, attrs) => attrs.nodeType === "hub");+ expect(hubs.length).toBeGreaterThan(0);++ for (const id of hubs) {+ const attrs = graph.getNodeAttributes(id);+ expect(attrs.labelInk, `hub ${id} has no labelInk`).toBeTruthy();+ // Ink must contrast with the node's own undimmed fill.+ expect(attrs.labelInk).not.toBe(attrs.color);+ }+ });+});++describe("useSigmaRenderer style reads", () => {+ it("resolves tokens a constant number of times, not once per node", () => {+ const graph = makeGraph();+ const spy = vi.spyOn(window, "getComputedStyle");++ const { rerender } = renderHook(+ (props: { theme: "light" | "dark" }) =>+ useSigmaRenderer({ ...options(graph), graphTheme: props.theme }),+ { initialProps: { theme: "dark" as "light" | "dark" } },+ );++ // Well under NODE_COUNT: the 12 community families plus the palette, once.+ expect(spy.mock.calls.length).toBeLessThan(100);++ // A re-render with unchanged props must resolve nothing at all — the+ // palette is memoized, not recomputed and thrown away.+ spy.mockClear();+ rerender({ theme: "dark" });+ expect(spy.mock.calls.length).toBe(0);++ // A theme flip re-resolves, but still at constant cost.+ spy.mockClear();+ rerender({ theme: "light" });+ expect(spy.mock.calls.length).toBeGreaterThan(0);+ expect(spy.mock.calls.length).toBeLessThan(100);++ spy.mockRestore();+ });+});diff --git a/packages/ui/src/graph/context.ts b/packages/ui/src/graph/context.tsindex f15c23090..f64a4de52 100644--- a/packages/ui/src/graph/context.ts+++ b/packages/ui/src/graph/context.ts@@ -1,56 +1,12 @@-"use client";--import { createContext, useContext } from "react";-import type { ColorMode, ViewMode, LayoutMode, GraphTheme } from "./graph-toolbar";+/**+ * Shared graph vocabulary.+ *+ * This file used to also export a `GraphContext` / `GraphProvider` /+ * `useGraphContext` trio mirroring ~18 fields of GraphFlow's state. It had zero+ * consumers — every one of those fields reaches the canvas as a prop, and Sigma+ * owns hover and highlight itself — so the provider only re-rendered the shell+ * and rebuilt an 18-key object on every interaction. Removed rather than kept+ * "just in case": props already carry this, and a second path would drift.+ */export type Signal = "dead" | "hot" | "architecture" | "hideTests";--export interface GraphContextValue {- highlightedPath: Set<string>;- highlightedEdges: Set<string>;- colorMode: ColorMode;- viewMode: ViewMode;- hoveredNodeId: string | null;- connectedNodeIds: Set<string>;- connectedEdgeIds: Set<string>;- selectedNodeId: string | null;- searchDimmedNodes: Set<string> | null;- communityDimmedNodes: Set<string> | null;- layoutMode: LayoutMode;- graphTheme: GraphTheme;- maxPagerank: number;- medianPagerank: number;- expandedModules: Set<string>;- activeSignals: Set<Signal>;- egoDepth: number;- visibleEdgeTypes: Set<string>;-}--const defaultValue: GraphContextValue = {- highlightedPath: new Set(),- highlightedEdges: new Set(),- colorMode: "language",- viewMode: "module",- hoveredNodeId: null,- connectedNodeIds: new Set(),- connectedEdgeIds: new Set(),- selectedNodeId: null,- searchDimmedNodes: null,- communityDimmedNodes: null,- layoutMode: "force",- graphTheme: "light",- maxPagerank: 0,- medianPagerank: 0,- expandedModules: new Set(),- activeSignals: new Set(),- egoDepth: 0,- visibleEdgeTypes: new Set(["import", "crossCommunity", "internal", "dynamic", "lowConfidence"]),-};--export const GraphContext = createContext<GraphContextValue>(defaultValue);--export const GraphProvider = GraphContext.Provider;--export function useGraphContext(): GraphContextValue {- return useContext(GraphContext);-}diff --git a/packages/ui/src/graph/graph-flow.tsx b/packages/ui/src/graph/graph-flow.tsxindex 1e1400fe7..13eed7938 100644--- a/packages/ui/src/graph/graph-flow.tsx+++ b/packages/ui/src/graph/graph-flow.tsx@@ -12,10 +12,9 @@ import { useTheme } from "next-themes";import { ChevronRight, Home, X } from "lucide-react";import { Skeleton } from "../ui/skeleton";import { EmptyState } from "../shared/empty-state";-import { GraphProvider, type GraphContextValue, type Signal } from "./context";+import { type Signal } from "./context";import { groupNodesAsModules, type FileNodeData, type ModuleNodeData } from "./elk-layout";-const EMPTY_STRING_SET = new Set<string>();// Resting zoom when easing the camera onto a constellation hub. Looser than the// default file-node focus (0.15) so the hub *and* its surrounding cluster stay// visible instead of the disc filling the whole viewport.@@ -310,8 +309,9 @@ export function GraphFlow(props: GraphFlowProps) {const [pathFrom, setPathFrom] = useState("");const [pathTo, setPathTo] = useState("");- // Hover & selection- const [hoveredNodeId, setHoveredNodeId] = useState<string | null>(null);+ // Selection. There is deliberately no hover state: Sigma draws its own hover+ // highlight on the canvas, so mirroring it into React only re-rendered this+ // whole shell on every hover transition for nothing.const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);// Execution flows@@ -911,31 +911,6 @@ export function GraphFlow(props: GraphFlowProps) {sigmaRef.current?.focusNode(firstNode);}, [activeFlowIdx, executionFlows, sigmaGraph]);- // Context value (hover fields use static empty sets — highlighting handled by Sigma reducers)- const ctxValue = useMemo<GraphContextValue>(- () => ({- highlightedPath,- highlightedEdges,- colorMode,- viewMode,- hoveredNodeId,- connectedNodeIds: EMPTY_STRING_SET,- connectedEdgeIds: EMPTY_STRING_SET,- selectedNodeId,- searchDimmedNodes,- communityDimmedNodes,- layoutMode,- graphTheme,- maxPagerank: 0,- medianPagerank: 0,- expandedModules,- activeSignals,- egoDepth,- visibleEdgeTypes,- }),- [highlightedPath, highlightedEdges, colorMode, viewMode, hoveredNodeId, selectedNodeId, searchDimmedNodes, communityDimmedNodes, layoutMode, graphTheme, expandedModules, activeSignals, egoDepth, visibleEdgeTypes],- );-// ---- Handlers ----// Unified grammar — DOUBLE CLICK = drill deeper (all views):@@ -1223,399 +1198,395 @@ export function GraphFlow(props: GraphFlowProps) {(isModuleView && !isDrilledDown && !hasExpandedModules && !moduleHintDismissed) ||(showOverlayCounts && !!overlayStats);+ // The canvas is what the reader came for, so it sits on the page plane+ // rather than below it (rule 8). Dark mode used to paint+ // `--color-bg-inset`, which the July ramp move took a full step darker than+ // the `--color-bg-root` page around it, so the graph read as a hole cut in+ // the app. Light mode never painted anything and has always looked right;+ // this makes dark do what light already did. Same call the knowledge-graph+ // canvas made in `zoom/theme.ts`.return (- <GraphProvider value={ctxValue}>- {/* The canvas is what the reader came for, so it sits on the page plane- rather than below it (rule 8). Dark mode used to paint- `--color-bg-inset`, which the July ramp move dropped to #0a0a0b — a- full step darker than the #0e0e0f page around it, so the graph read- as a hole cut in the app. Light mode never painted anything and has- always looked right; this makes dark do what light already did. Same- call the knowledge-graph canvas made in `zoom/theme.ts`. */}- <div className="relative w-full h-full" style={{ touchAction: "none", ...(graphTheme === "dark" ? { background: "var(--color-bg-root)" } : {}) }} aria-label="Dependency graph">- {sigmaGraph && sigmaGraph.order > 0 ? (- <SigmaCanvas- ref={sigmaRef}- graph={sigmaGraph}- layoutMode={layoutMode}- viewMode={viewMode}- selectedNodeId={selectedNodeId}- hoveredNodeId={hoveredNodeId}- highlightedPath={highlightedPath}- highlightedEdges={highlightedEdges}- searchDimmedNodes={searchDimmedNodes}- communityDimmedNodes={communityDimmedNodes}- expandDimmedNodes={isConstellation ? expandDimmedNodes : null}- colorMode={colorMode}- activeSignals={activeSignals}- graphTheme={graphTheme}- fileNodes={fileGraphData?.nodes}- fileEdges={fileGraphData?.links}- moduleNodes={isModuleView ? moduleGraph?.nodes : undefined}- moduleEdges={isModuleView ? moduleGraph?.edges : undefined}- onNodeClick={handleSigmaNodeClick}- onNodeDoubleClick={handleSigmaDoubleClick}- onNodeHover={setHoveredNodeId}- onNodeContextMenu={handleSigmaNodeContextMenu}- onStageClick={() => setSelectedNodeId(null)}- onLayoutSkipped={setLayoutNotice}- hiddenNodes={isEgoActive ? hiddenNodes : undefined}- visibleEdgeTypes={visibleEdgeTypes}- depthRingRadii={isConstellation ? constellationRingRadii : null}+ <div className="relative w-full h-full" style={{ touchAction: "none", ...(graphTheme === "dark" ? { background: "var(--color-bg-root)" } : {}) }} aria-label="Dependency graph">+ {sigmaGraph && sigmaGraph.order > 0 ? (+ <SigmaCanvas+ ref={sigmaRef}+ graph={sigmaGraph}+ layoutMode={layoutMode}+ viewMode={viewMode}+ selectedNodeId={selectedNodeId}+ highlightedPath={highlightedPath}+ highlightedEdges={highlightedEdges}+ searchDimmedNodes={searchDimmedNodes}+ communityDimmedNodes={communityDimmedNodes}+ expandDimmedNodes={isConstellation ? expandDimmedNodes : null}+ colorMode={colorMode}+ activeSignals={activeSignals}+ graphTheme={graphTheme}+ fileNodes={fileGraphData?.nodes}+ fileEdges={fileGraphData?.links}+ moduleNodes={isModuleView ? moduleGraph?.nodes : undefined}+ moduleEdges={isModuleView ? moduleGraph?.edges : undefined}+ onNodeClick={handleSigmaNodeClick}+ onNodeDoubleClick={handleSigmaDoubleClick}+ onNodeContextMenu={handleSigmaNodeContextMenu}+ onStageClick={() => setSelectedNodeId(null)}+ onLayoutSkipped={setLayoutNotice}+ hiddenNodes={isEgoActive ? hiddenNodes : undefined}+ visibleEdgeTypes={visibleEdgeTypes}+ depthRingRadii={isConstellation ? constellationRingRadii : null}+ />+ ) : !isLoading ? (+ <div className="flex items-center justify-center h-full">+ <EmptyState+ title={overlayEmptyState?.title ?? "No graph data"}+ description={+ overlayEmptyState?.description ??+ "This scope came back with nothing to draw. Try another scope, or re-index the repo if it was added recently."+ }/>- ) : !isLoading ? (- <div className="flex items-center justify-center h-full">- <EmptyState- title={overlayEmptyState?.title ?? "No graph data"}- description={- overlayEmptyState?.description ??- "This scope came back with nothing to draw. Try another scope, or re-index the repo if it was added recently."- }- />- </div>- ) : null}-- {/* Canvas status, top-left. One panel with hairline rows, matching the- toolbar, the legend and the zoom controls — this corner could- otherwise stack four independently-bordered, independently-shadowed- chips (breadcrumb, expanded-modules, loading, tip, overlay counts)- over the diagram at once. Rendered only when it has something to- say, so an idle canvas carries no chrome here at all (rule 10). */}- {hasCanvasStatus && (- <div className={`absolute top-3 left-3 z-10 flex flex-col items-stretch overflow-hidden ${canvasPanelClass}`}>- {isEgoActive && selectedNodeId ? (- <div>- <div className={canvasRowClass}>- <span className="text-[10px] text-[var(--color-accent-primary)]">- Showing {egoVisibleCount} nodes within {egoDepth} hop{egoDepth === 1 ? "" : "s"} of{" "}- <span className="font-mono font-medium">{selectedNodeId.split("/").pop()}</span>- </span>- <button- onClick={() => setEgoDepth(0)}- className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] text-[10px]"- >- Clear- </button>- </div>- </div>- ) : isModuleView && isDrilledDown ? (- <div>- <div className={canvasRowClass}>- <button- onClick={() => handleBreadcrumbClick(-1)}- className="flex items-center gap-1 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-graph)] transition-colors"- >- <Home className="w-3 h-3" />- <span>Root</span>- </button>- {modulePath.map((fullPrefix, i) => {- const prevPrefix = i > 0 ? modulePath[i - 1] + "/" : "";- const label = fullPrefix.slice(prevPrefix.length);- const isLast = i === modulePath.length - 1;- return (- <span key={i} className="flex items-center gap-1">- <ChevronRight className="w-3 h-3 text-[var(--color-text-tertiary)]" />- <button- onClick={() => !isLast && handleBreadcrumbClick(i)}- className={`text-xs font-mono transition-colors ${- isLast- ? "text-[var(--color-text-primary)] font-medium cursor-default"- : "text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-graph)]"- }`}- >- {label}- </button>- </span>- );- })}- </div>- </div>- ) : null}-- {/* Expanded-modules chip: count + collapse-all. */}- {isModuleView && !isDrilledDown && hasExpandedModules && (+ </div>+ ) : null}++ {/* Canvas status, top-left. One panel with hairline rows, matching the+ toolbar, the legend and the zoom controls — this corner could+ otherwise stack four independently-bordered, independently-shadowed+ chips (breadcrumb, expanded-modules, loading, tip, overlay counts)+ over the diagram at once. Rendered only when it has something to+ say, so an idle canvas carries no chrome here at all (rule 10). */}+ {hasCanvasStatus && (+ <div className={`absolute top-3 left-3 z-10 flex flex-col items-stretch overflow-hidden ${canvasPanelClass}`}>+ {isEgoActive && selectedNodeId ? (+ <div><div className={canvasRowClass}>- <span className="text-[10px] text-[var(--color-text-secondary)]">- {expandedModules.size} module{expandedModules.size === 1 ? "" : "s"} expanded+ <span className="text-[10px] text-[var(--color-accent-primary)]">+ Showing {egoVisibleCount} nodes within {egoDepth} hop{egoDepth === 1 ? "" : "s"} of{" "}+ <span className="font-mono font-medium">{selectedNodeId.split("/").pop()}</span></span><button- onClick={collapseAll}- className="text-[10px] font-medium text-[var(--color-accent-primary)] hover:underline"+ onClick={() => setEgoDepth(0)}+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] text-[10px]">- Collapse all+ Clear</button></div>- )}-- {/* Expansion needs the file-level graph — surface the fetch instead of- letting the double-click look like it silently did nothing. */}- {isModuleView && hasExpandedModules && !fullGraph && isLoadingFullGraph && (- <div role="status" aria-live="polite" className={canvasRowClass}>- <span className="text-[10px] text-[var(--color-text-secondary)]">- Loading files for expanded module…- </span>- </div>- )}-- {/* One-time interaction hint for the modules scope. */}- {isModuleView && !isDrilledDown && !hasExpandedModules && !moduleHintDismissed && (+ </div>+ ) : isModuleView && isDrilledDown ? (+ <div><div className={canvasRowClass}>- <span className="text-[10px] text-[var(--color-text-secondary)]">- Tip: double-click a module to see its files- </span><button- onClick={dismissModuleHint}- aria-label="Dismiss hint"- className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"+ onClick={() => handleBreadcrumbClick(-1)}+ className="flex items-center gap-1 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-graph)] transition-colors">- <X className="w-3 h-3" />+ <Home className="w-3 h-3" />+ <span>Root</span></button>+ {modulePath.map((fullPrefix, i) => {+ const prevPrefix = i > 0 ? modulePath[i - 1] + "/" : "";+ const label = fullPrefix.slice(prevPrefix.length);+ const isLast = i === modulePath.length - 1;+ return (+ <span key={i} className="flex items-center gap-1">+ <ChevronRight className="w-3 h-3 text-[var(--color-text-tertiary)]" />+ <button+ onClick={() => !isLast && handleBreadcrumbClick(i)}+ className={`text-xs font-mono transition-colors ${+ isLast+ ? "text-[var(--color-text-primary)] font-medium cursor-default"+ : "text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-graph)]"+ }`}+ >+ {label}+ </button>+ </span>+ );+ })}</div>- )}-- {/* Overlay coverage: how many flagged files are actually in view. The- totals come from the backend when it provides them; without totals- we still report the in-view count so the overlay never reads as- silently doing nothing. */}- {showOverlayCounts && overlayStats && (- <>- {isDeadView && (- <OverlayCountChip- kind="dead"- inView={overlayStats.deadInView}- total={deadTotal}- />- )}- {isHotView && (- <OverlayCountChip- kind="hot"- inView={overlayStats.hotInView}- total={hotTotal}- />- )}- </>- )}</div>- )}-- {/* Layout-skipped notice: the hierarchical toggle must never look- active while silently doing nothing. */}- {layoutNotice && (- <div- role="status"- aria-live="polite"- className="absolute top-3 left-1/2 -translate-x-1/2 z-10 flex max-w-[min(28rem,calc(100vw-6rem))] items-center gap-2 rounded-lg border border-[var(--color-warning)]/40 bg-[var(--color-bg-elevated)]/95 backdrop-blur-sm px-3 py-1.5 shadow-sm"+ ) : null}++ {/* Expanded-modules chip: count + collapse-all. */}+ {isModuleView && !isDrilledDown && hasExpandedModules && (+ <div className={canvasRowClass}>+ <span className="text-[10px] text-[var(--color-text-secondary)]">+ {expandedModules.size} module{expandedModules.size === 1 ? "" : "s"} expanded+ </span>+ <button+ onClick={collapseAll}+ className="text-[10px] font-medium text-[var(--color-accent-primary)] hover:underline">- <span className="text-[11px] text-[var(--color-text-primary)]">{layoutNotice}</span>- <button- onClick={() => setLayoutNotice(null)}- aria-label="Dismiss layout notice"- className="shrink-0 text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"- >- <X className="w-3 h-3" />- </button>- </div>- )}-- {/* Toolbar */}- <div className="absolute top-3 right-3 z-10">- <GraphToolbar- viewMode={viewMode}- onViewChange={handleViewChange}- colorMode={colorMode}- onColorModeChange={setColorMode}- hideTests={hideTests}- onHideTestsChange={(v) => {- setActiveSignals(prev => {- const next = new Set(prev);- v ? next.add("hideTests") : next.delete("hideTests");- return next;- });- }}- onFitView={handleFitView}- showPathFinder={showPathFinder}- pathFinderAvailable={Boolean(renderPathFinder)}- onTogglePathFinder={() => {- // Path finder and flows share the same overlay slot — opening- // one always closes the other.- setShowPathFinder((s) => !s);- setShowFlows(false);- setActiveFlowIdx(null);- }}- showFlows={showFlows}- onToggleFlows={() => {- setShowFlows((s) => !s);- setActiveFlowIdx(null);- setShowPathFinder(false);- }}- searchQuery={searchQuery}- onSearchChange={setSearchQuery}- searchMatchCount={searchResults.length}- searchTotalCount={sigmaGraph?.order ?? 0}- onSearchKeyDown={handleSearchKeyDown}- layoutMode={layoutMode}- onLayoutModeChange={handleLayoutModeChange}- onToggleHelp={handleToggleShortcutHelp}- availableScopes={availableScopes}- showExternals={showExternals}- onShowExternalsChange={setShowExternals}- externalCount={externalCount}- />+ Collapse all+ </button>+ </div>+ )}++ {/* Expansion needs the file-level graph — surface the fetch instead of+ letting the double-click look like it silently did nothing. */}+ {isModuleView && hasExpandedModules && !fullGraph && isLoadingFullGraph && (+ <div role="status" aria-live="polite" className={canvasRowClass}>+ <span className="text-[10px] text-[var(--color-text-secondary)]">+ Loading files for expanded module…+ </span></div>+ )}++ {/* One-time interaction hint for the modules scope. */}+ {isModuleView && !isDrilledDown && !hasExpandedModules && !moduleHintDismissed && (+ <div className={canvasRowClass}>+ <span className="text-[10px] text-[var(--color-text-secondary)]">+ Tip: double-click a module to see its files+ </span>+ <button+ onClick={dismissModuleHint}+ aria-label="Dismiss hint"+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"+ >+ <X className="w-3 h-3" />+ </button>+ </div>+ )}++ {/* Overlay coverage: how many flagged files are actually in view. The+ totals come from the backend when it provides them; without totals+ we still report the in-view count so the overlay never reads as+ silently doing nothing. */}+ {showOverlayCounts && overlayStats && (+ <>+ {isDeadView && (+ <OverlayCountChip+ kind="dead"+ inView={overlayStats.deadInView}+ total={deadTotal}+ />+ )}+ {isHotView && (+ <OverlayCountChip+ kind="hot"+ inView={overlayStats.hotInView}+ total={hotTotal}+ />+ )}+ </>+ )}+ </div>+ )}++ {/* Layout-skipped notice: the hierarchical toggle must never look+ active while silently doing nothing. */}+ {layoutNotice && (+ <div+ role="status"+ aria-live="polite"+ className="absolute top-3 left-1/2 -translate-x-1/2 z-10 flex max-w-[min(28rem,calc(100vw-6rem))] items-center gap-2 rounded-lg border border-[var(--color-warning)]/40 bg-[var(--color-bg-elevated)]/95 backdrop-blur-sm px-3 py-1.5 shadow-sm"+ >+ <span className="text-[11px] text-[var(--color-text-primary)]">{layoutNotice}</span>+ <button+ onClick={() => setLayoutNotice(null)}+ aria-label="Dismiss layout notice"+ className="shrink-0 text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"+ >+ <X className="w-3 h-3" />+ </button>+ </div>+ )}++ {/* Toolbar */}+ <div className="absolute top-3 right-3 z-10">+ <GraphToolbar+ viewMode={viewMode}+ onViewChange={handleViewChange}+ colorMode={colorMode}+ onColorModeChange={setColorMode}+ hideTests={hideTests}+ onHideTestsChange={(v) => {+ setActiveSignals(prev => {+ const next = new Set(prev);+ v ? next.add("hideTests") : next.delete("hideTests");+ return next;+ });+ }}+ onFitView={handleFitView}+ showPathFinder={showPathFinder}+ pathFinderAvailable={Boolean(renderPathFinder)}+ onTogglePathFinder={() => {+ // Path finder and flows share the same overlay slot — opening+ // one always closes the other.+ setShowPathFinder((s) => !s);+ setShowFlows(false);+ setActiveFlowIdx(null);+ }}+ showFlows={showFlows}+ onToggleFlows={() => {+ setShowFlows((s) => !s);+ setActiveFlowIdx(null);+ setShowPathFinder(false);+ }}+ searchQuery={searchQuery}+ onSearchChange={setSearchQuery}+ searchMatchCount={searchResults.length}+ searchTotalCount={sigmaGraph?.order ?? 0}+ onSearchKeyDown={handleSearchKeyDown}+ layoutMode={layoutMode}+ onLayoutModeChange={handleLayoutModeChange}+ onToggleHelp={handleToggleShortcutHelp}+ availableScopes={availableScopes}+ showExternals={showExternals}+ onShowExternalsChange={setShowExternals}+ externalCount={externalCount}+ />+ </div>- {/* Path Finder */}- {showPathFinder && renderPathFinder && (- <div className="absolute top-14 right-3 z-10">- {renderPathFinder({- initialFrom: pathFrom,- initialTo: pathTo,- onPathFound: handlePathFound,- onClear: handlePathClear,- onClose: () => setShowPathFinder(false),- })}- </div>- )}-- {/* Execution Flows Panel */}- {showFlows && executionFlows && executionFlows.flows.length > 0 && (- <div className="absolute top-14 right-3 z-10 w-[min(16rem,calc(100vw-1.5rem))]">- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/95 backdrop-blur-sm shadow-lg shadow-black/20 p-3">- <div className="flex items-center justify-between mb-2">- <span className="text-xs font-medium text-[var(--color-text-primary)]">- Execution Flows+ {/* Path Finder */}+ {showPathFinder && renderPathFinder && (+ <div className="absolute top-14 right-3 z-10">+ {renderPathFinder({+ initialFrom: pathFrom,+ initialTo: pathTo,+ onPathFound: handlePathFound,+ onClear: handlePathClear,+ onClose: () => setShowPathFinder(false),+ })}+ </div>+ )}++ {/* Execution Flows Panel */}+ {showFlows && executionFlows && executionFlows.flows.length > 0 && (+ <div className="absolute top-14 right-3 z-10 w-[min(16rem,calc(100vw-1.5rem))]">+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/95 backdrop-blur-sm shadow-lg shadow-black/20 p-3">+ <div className="flex items-center justify-between mb-2">+ <span className="text-xs font-medium text-[var(--color-text-primary)]">+ Execution Flows+ </span>+ <div className="flex items-center gap-1.5">+ <span className="text-[10px] text-[var(--color-text-tertiary)]">+ {executionFlows.flows.length} entry points</span>- <div className="flex items-center gap-1.5">- <span className="text-[10px] text-[var(--color-text-tertiary)]">- {executionFlows.flows.length} entry points- </span>- {/* Same close affordance as the Path Finder panel above. */}- <button- onClick={() => {- setShowFlows(false);- setActiveFlowIdx(null);- }}- aria-label="Close"- title="Close"- className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"- >- <X className="w-3 h-3" />- </button>- </div>+ {/* Same close affordance as the Path Finder panel above. */}+ <button+ onClick={() => {+ setShowFlows(false);+ setActiveFlowIdx(null);+ }}+ aria-label="Close"+ title="Close"+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"+ >+ <X className="w-3 h-3" />+ </button></div>- <div className="space-y-1 max-h-60 overflow-y-auto">- {executionFlows.flows.map((flow, idx) => (- <button- key={flow.entry_point}- onClick={() => setActiveFlowIdx(activeFlowIdx === idx ? null : idx)}- className={`w-full text-left px-2 py-1.5 rounded-md text-xs transition-colors ${- activeFlowIdx === idx- ? "bg-[var(--color-accent-primary)]/15 text-[var(--color-accent-primary)]"- : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-overlay)] hover:text-[var(--color-text-primary)]"- }`}- >- <div className="font-mono truncate">{flow.entry_point_name}</div>- <div className="flex items-center gap-2 mt-0.5 text-[10px] text-[var(--color-text-tertiary)]">- <span>depth {flow.depth}</span>- <span>{flow.trace.length} nodes</span>- {flow.crosses_community && (- <span className="text-yellow-500">cross-community</span>- )}- </div>- </button>- ))}- </div>- {activeFlowMissingCount > 0 && (- <p className="mt-2 text-[10px] leading-snug text-[var(--color-warning)]">- This flow includes {activeFlowMissingCount} node- {activeFlowMissingCount === 1 ? "" : "s"} not in the loaded- view — load more nodes to see the full trace.- </p>- )}</div>+ <div className="space-y-1 max-h-60 overflow-y-auto">+ {executionFlows.flows.map((flow, idx) => (+ <button+ key={flow.entry_point}+ onClick={() => setActiveFlowIdx(activeFlowIdx === idx ? null : idx)}+ className={`w-full text-left px-2 py-1.5 rounded-md text-xs transition-colors ${+ activeFlowIdx === idx+ ? "bg-[var(--color-accent-primary)]/15 text-[var(--color-accent-primary)]"+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-overlay)] hover:text-[var(--color-text-primary)]"+ }`}+ >+ <div className="font-mono truncate">{flow.entry_point_name}</div>+ <div className="flex items-center gap-2 mt-0.5 text-[10px] text-[var(--color-text-tertiary)]">+ <span>depth {flow.depth}</span>+ <span>{flow.trace.length} nodes</span>+ {flow.crosses_community && (+ <span className="text-yellow-500">cross-community</span>+ )}+ </div>+ </button>+ ))}+ </div>+ {activeFlowMissingCount > 0 && (+ <p className="mt-2 text-[10px] leading-snug text-[var(--color-warning)]">+ This flow includes {activeFlowMissingCount} node+ {activeFlowMissingCount === 1 ? "" : "s"} not in the loaded+ view — load more nodes to see the full trace.+ </p>+ )}</div>- )}-- {/* Legend — on phones the inspection bottom sheet covers this corner,- so yield to it instead of stacking underneath. */}- <div className={`absolute bottom-3 left-3 z-10 ${selectedNodeId ? "hidden sm:block" : ""}`}>- <GraphLegend- nodeCount={sigmaGraph?.order ?? 0}- edgeCount={sigmaGraph?.size ?? 0}- colorMode={colorMode}- viewMode={viewMode}- {...(communityLabels ? { communityLabels } : {})}- onCommunityClick={openCommunityPanel}- activeCommunities={activeCommunities ?? undefined}- onCommunityToggle={handleCommunityToggle}- onToggleAllCommunities={handleToggleAllCommunities}- visibleEdgeTypes={isConstellation ? undefined : visibleEdgeTypes}- onEdgeTypeToggle={isConstellation ? undefined : handleEdgeTypeToggle}- graphTheme={graphTheme}- constellationEntries={isConstellation ? constellationLegend : undefined}- onConstellationHubClick={handleConstellationHubClick}- /></div>+ )}++ {/* Legend — on phones the inspection bottom sheet covers this corner,+ so yield to it instead of stacking underneath. */}+ <div className={`absolute bottom-3 left-3 z-10 ${selectedNodeId ? "hidden sm:block" : ""}`}>+ <GraphLegend+ nodeCount={sigmaGraph?.order ?? 0}+ edgeCount={sigmaGraph?.size ?? 0}+ colorMode={colorMode}+ viewMode={viewMode}+ {...(communityLabels ? { communityLabels } : {})}+ onCommunityClick={openCommunityPanel}+ activeCommunities={activeCommunities ?? undefined}+ onCommunityToggle={handleCommunityToggle}+ onToggleAllCommunities={handleToggleAllCommunities}+ visibleEdgeTypes={isConstellation ? undefined : visibleEdgeTypes}+ onEdgeTypeToggle={isConstellation ? undefined : handleEdgeTypeToggle}+ graphTheme={graphTheme}+ constellationEntries={isConstellation ? constellationLegend : undefined}+ onConstellationHubClick={handleConstellationHubClick}+ />+ </div>- {/* Keyboard shortcut help (toggled with ?) */}- {showShortcutHelp && (- <GraphShortcutHelp onClose={() => setShowShortcutHelp(false)} />- )}-- {/* Context menu */}- {ctxMenu && (- <GraphContextMenu- x={ctxMenu.x}- y={ctxMenu.y}- nodeId={ctxMenu.nodeId}- isModule={ctxMenu.nodeType === "moduleGroup"}- onViewDocs={handleCtxViewDocs}- onExplore={handleCtxExplore}- onPathFrom={handleCtxPathFrom}- onPathTo={handleCtxPathTo}+ {/* Keyboard shortcut help (toggled with ?) */}+ {showShortcutHelp && (+ <GraphShortcutHelp onClose={() => setShowShortcutHelp(false)} />+ )}++ {/* Context menu */}+ {ctxMenu && (+ <GraphContextMenu+ x={ctxMenu.x}+ y={ctxMenu.y}+ nodeId={ctxMenu.nodeId}+ isModule={ctxMenu.nodeType === "moduleGroup"}+ onViewDocs={handleCtxViewDocs}+ onExplore={handleCtxExplore}+ onPathFrom={handleCtxPathFrom}+ onPathTo={handleCtxPathTo}+ />+ )}++ {/* Community detail panel */}+ {communityPanelId !== null && renderCommunityPanel &&+ renderCommunityPanel({+ communityId: communityPanelId,+ onClose: () => setCommunityPanelId(null),+ onExpandOnCanvas: () => handleConstellationHubToggle(communityPanelId),+ })}++ {/* Inspection panel — works for both file and module nodes */}+ {selectedNodeId && (() => {+ const fileNd = effectiveNodeDataMap.get(selectedNodeId);+ const modNd = effectiveModuleDataMap.get(selectedNodeId);+ const nd = fileNd ?? modNd;+ if (!nd) return null;+ return (+ <GraphInspectionPanel+ nodeId={selectedNodeId}+ data={nd}+ graph={sigmaGraph}+ allNodes={effectiveNodeDataMap}+ communityLabel={fileNd ? communityLabels?.get(fileNd.communityId) : undefined}+ onClose={() => { setSelectedNodeId(null); }}+ onNavigateToNode={handleInspectNavigate}+ onViewDocs={() => { onNodeViewDocs?.(selectedNodeId); }}+ onViewSymbols={+ fileNd && onNodeViewSymbols+ ? () => { onNodeViewSymbols(selectedNodeId); }+ : undefined+ }+ filePageHref={fileNd ? fileHrefFor?.(selectedNodeId) : undefined}+ onFindPath={handleInspectFindPath}+ onExpandModule={modNd ? handleInspectExpandModule : undefined}+ isModuleExpanded={modNd ? expandedModules.has(selectedNodeId) : false}+ egoDepth={egoDepth}+ onEgoDepthChange={setEgoDepth}+ egoVisibleCount={egoVisibleCount}/>- )}-- {/* Community detail panel */}- {communityPanelId !== null && renderCommunityPanel &&- renderCommunityPanel({- communityId: communityPanelId,- onClose: () => setCommunityPanelId(null),- onExpandOnCanvas: () => handleConstellationHubToggle(communityPanelId),- })}-- {/* Inspection panel — works for both file and module nodes */}- {selectedNodeId && (() => {- const fileNd = effectiveNodeDataMap.get(selectedNodeId);- const modNd = effectiveModuleDataMap.get(selectedNodeId);- const nd = fileNd ?? modNd;- if (!nd) return null;- return (- <GraphInspectionPanel- nodeId={selectedNodeId}- data={nd}- graph={sigmaGraph}- allNodes={effectiveNodeDataMap}- communityLabel={fileNd ? communityLabels?.get(fileNd.communityId) : undefined}- onClose={() => { setSelectedNodeId(null); }}- onNavigateToNode={handleInspectNavigate}- onViewDocs={() => { onNodeViewDocs?.(selectedNodeId); }}- onViewSymbols={- fileNd && onNodeViewSymbols- ? () => { onNodeViewSymbols(selectedNodeId); }- : undefined- }- filePageHref={fileNd ? fileHrefFor?.(selectedNodeId) : undefined}- onFindPath={handleInspectFindPath}- onExpandModule={modNd ? handleInspectExpandModule : undefined}- isModuleExpanded={modNd ? expandedModules.has(selectedNodeId) : false}- egoDepth={egoDepth}- onEgoDepthChange={setEgoDepth}- egoVisibleCount={egoVisibleCount}- />- );- })()}- </div>- </GraphProvider>+ );+ })()}+ </div>);}diff --git a/packages/ui/src/graph/graph-tooltip.tsx b/packages/ui/src/graph/graph-tooltip.tsxdeleted file mode 100644index 7054ec293..000000000--- a/packages/ui/src/graph/graph-tooltip.tsx+++ /dev/null@@ -1,258 +0,0 @@-/** @deprecated Use GraphInspectionPanel instead — this tooltip is no longer mounted by GraphFlow. */-"use client";--import { useEffect, useRef } from "react";-import { FileText, Folder, ArrowRight, X, BookOpen, Code2 } from "lucide-react";-import { formatNumber } from "../lib/format";-import { languageColor } from "../lib/confidence";-import type { FileNodeData, ModuleNodeData } from "./elk-layout";-import { NodeBadges } from "./node-badges";--interface GraphTooltipProps {- nodeId: string;- nodeType: string;- data: Record<string, unknown>;- x: number;- y: number;- onClose: () => void;- onViewDocs: () => void;- onViewSymbol?: () => void;- onExplore?: () => void;-}--function importanceLabel(pagerank: number): { label: string; color: string } {- if (pagerank >= 0.01) return { label: "High", color: "var(--color-risk-high)" };- if (pagerank >= 0.003) return { label: "Medium", color: "var(--color-risk-medium)" };- return { label: "Low", color: "var(--color-risk-low)" };-}--export function GraphTooltip({- nodeId,- nodeType,- data,- x,- y,- onClose,- onViewDocs,- onViewSymbol,- onExplore,-}: GraphTooltipProps) {- const ref = useRef<HTMLDivElement>(null);-- // Dismiss on Escape- useEffect(() => {- const handler = (e: KeyboardEvent) => {- if (e.key === "Escape") onClose();- };- window.addEventListener("keydown", handler);- return () => window.removeEventListener("keydown", handler);- }, [onClose]);-- // Smart positioning: prefer below-right, flip if near edges- const tooltipW = 260;- const tooltipH = 280;- const pad = 12;- const vw = typeof window !== "undefined" ? window.innerWidth : 1200;- const vh = typeof window !== "undefined" ? window.innerHeight : 800;-- let left = x + pad;- let top = y + pad;- if (left + tooltipW > vw - pad) left = x - tooltipW - pad;- if (top + tooltipH > vh - pad) top = y - tooltipH - pad;- if (left < pad) left = pad;- if (top < pad) top = pad;-- const isFile = nodeType === "fileNode";- const isModule = nodeType === "moduleGroup";-- return (- <div- ref={ref}- className="fixed z-50 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-2xl shadow-black/30 backdrop-blur-md text-xs animate-in fade-in slide-in-from-bottom-1 duration-150"- style={{ left, top, width: tooltipW }}- >- {/* Header */}- <div className="flex items-start gap-2 p-3 pb-2 border-b border-[var(--color-border-default)]/50">- <div className="mt-0.5 shrink-0">- {isModule ? (- <Folder className="w-4 h-4 text-[var(--color-accent-graph)]" />- ) : (- <FileText className="w-4 h-4 text-[var(--color-text-secondary)]" />- )}- </div>- <div className="min-w-0 flex-1">- <p className="font-mono font-semibold text-[var(--color-text-primary)] text-xs leading-tight break-all">- {nodeId.split("/").pop()}- </p>- <p className="text-[10px] text-[var(--color-text-tertiary)] mt-0.5 truncate">- {nodeId}- </p>- </div>- <button- onClick={onClose}- className="shrink-0 p-0.5 rounded hover:bg-[var(--color-bg-inset)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] transition-colors"- >- <X className="w-3.5 h-3.5" />- </button>- </div>-- {/* Details */}- <div className="p-3 space-y-2">- {isFile && (() => {- const d = data as unknown as FileNodeData;- const imp = importanceLabel(d.pagerank);- return (- <>- {/* Language */}- <div className="flex items-center justify-between">- <span className="text-[var(--color-text-tertiary)]">Language</span>- <span className="flex items-center gap-1.5">- <span- className="w-2 h-2 rounded-full"- style={{ background: languageColor(d.language) }}- />- <span className="font-medium text-[var(--color-text-primary)] capitalize">- {d.language}- </span>- </span>- </div>-- {/* Symbols */}- <div className="flex items-center justify-between">- <span className="text-[var(--color-text-tertiary)]">Symbols</span>- <span className="font-medium text-[var(--color-text-primary)] tabular-nums">- {formatNumber(d.symbolCount)}- </span>- </div>-- {/* Importance */}- <div className="flex items-center justify-between">- <span className="text-[var(--color-text-tertiary)]">Importance</span>- <span className="font-medium tabular-nums" style={{ color: imp.color }}>- {imp.label}- </span>- </div>-- {/* Community */}- <div className="flex items-center justify-between">- <span className="text-[var(--color-text-tertiary)]">Community</span>- <span className="font-medium text-[var(--color-text-primary)] tabular-nums">- #{d.communityId}- </span>- </div>-- {/* Betweenness centrality */}- <div className="flex items-center justify-between">- <span className="text-[var(--color-text-tertiary)]">Betweenness</span>- <span className="font-medium text-[var(--color-text-primary)] tabular-nums">- {d.betweenness < 0.001 ? "<0.1%" : `${(d.betweenness * 100).toFixed(1)}%`}- </span>- </div>-- {/* Dead code view: confidence group */}- {typeof d.confidenceGroup === "string" && (- <div className="flex items-center justify-between">- <span className="text-[var(--color-text-tertiary)]">Confidence</span>- <span className="font-medium text-[var(--color-text-primary)] capitalize">- {(d.confidenceGroup as string)}- </span>- </div>- )}-- {/* Hot files view: commit count */}- {typeof d.commitCount === "number" && (- <div className="flex items-center justify-between">- <span className="text-[var(--color-text-tertiary)]">Commits (30d)</span>- <span className="font-medium text-[var(--color-text-primary)] tabular-nums">- {formatNumber(d.commitCount as number)}- </span>- </div>- )}-- {/* Badges row — single shared component used by tooltip + drawer */}- <NodeBadges- className="pt-1"- signals={{- isEntryPoint: d.isEntryPoint,- isTest: d.isTest,- hasDoc: d.hasDoc,- isHotspot: (d as { isHotspot?: boolean }).isHotspot,- isDead: (d as { isDead?: boolean }).isDead,- hasDecision: (d as { hasDecision?: boolean }).hasDecision,- }}- />- </>- );- })()}-- {isModule && (() => {- const d = data as unknown as ModuleNodeData;- const docPct = d.docCoveragePct ?? 0;- return (- <>- <div className="flex items-center justify-between">- <span className="text-[var(--color-text-tertiary)]">Files</span>- <span className="font-medium text-[var(--color-text-primary)] tabular-nums">- {formatNumber(d.fileCount ?? 0)}- </span>- </div>- {d.symbolCount != null && d.symbolCount > 0 && (- <div className="flex items-center justify-between">- <span className="text-[var(--color-text-tertiary)]">Symbols</span>- <span className="font-medium text-[var(--color-text-primary)] tabular-nums">- {formatNumber(d.symbolCount)}- </span>- </div>- )}- <div className="flex items-center justify-between">- <span className="text-[var(--color-text-tertiary)]">Doc coverage</span>- <span className="font-medium text-[var(--color-text-primary)] tabular-nums">- {Math.round(docPct * 100)}%- </span>- </div>- {/* Mini doc coverage bar */}- <div className="h-1.5 w-full rounded-full bg-[var(--color-bg-inset)] overflow-hidden">- <div- className="h-full rounded-full transition-all duration-300"- style={{- width: `${Math.max(2, Math.round(docPct * 100))}%`,- background: docPct >= 0.7 ? "var(--color-success)" : docPct >= 0.3 ? "var(--color-warning)" : "var(--color-error)",- }}- />- </div>- </>- );- })()}- </div>-- {/* Actions */}- <div className="flex items-center gap-2 p-3 pt-0">- <button- onClick={onViewDocs}- className="flex-1 flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-bg-inset)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] px-2.5 py-1.5 text-xs font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"- >- <BookOpen className="w-3 h-3" />- View Docs- </button>- {isFile && onViewSymbol && (- <button- onClick={onViewSymbol}- className="flex-1 flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-bg-inset)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] px-2.5 py-1.5 text-xs font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"- >- <Code2 className="w-3 h-3" />- View Symbol- </button>- )}- {onExplore && (- <button- onClick={onExplore}- className="flex-1 flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-accent-graph)]/10 hover:bg-[var(--color-accent-graph)]/20 border border-[var(--color-accent-graph)]/30 px-2.5 py-1.5 text-xs font-medium text-[var(--color-accent-graph)] transition-colors"- >- <ArrowRight className="w-3 h-3" />- Explore- </button>- )}- </div>- </div>- );-}diff --git a/packages/ui/src/graph/sigma/sigma-canvas.tsx b/packages/ui/src/graph/sigma/sigma-canvas.tsxindex 63be0295c..c1d70d0a8 100644--- a/packages/ui/src/graph/sigma/sigma-canvas.tsx+++ b/packages/ui/src/graph/sigma/sigma-canvas.tsx@@ -23,7 +23,6 @@ import { useSigmaRenderer } from "./use-sigma";import { useFA2Layout } from "./use-fa2-layout";import { useElkSigmaLayout } from "./use-elk-sigma-layout";import { SigmaControls } from "./sigma-controls";-import { SigmaMinimap } from "./sigma-minimap";import { DepthRings } from "./depth-rings";export interface SigmaCanvasProps {@@ -32,7 +31,6 @@ export interface SigmaCanvasProps {layoutMode: "force" | "hierarchical" | "radial";viewMode: ViewMode;selectedNodeId: string | null;- hoveredNodeId: string | null;highlightedPath: Set<string>;highlightedEdges: Set<string>;searchDimmedNodes: Set<string> | null;@@ -47,7 +45,6 @@ export interface SigmaCanvasProps {moduleNodes?: ModuleNodeResponse[] | undefined;moduleEdges?: ModuleEdgeResponse[] | undefined;onNodeClick?: ((nodeId: string, nodeType: string) => void) | undefined;- onNodeHover?: ((nodeId: string | null) => void) | undefined;onNodeContextMenu?:| ((event: MouseEvent, nodeId: string, nodeType: string) => void)| undefined;@@ -85,7 +82,6 @@ export const SigmaCanvas = forwardRef<SigmaCanvasHandle, SigmaCanvasProps>(container,graph: props.graph,selectedNodeId: props.selectedNodeId,- hoveredNodeId: props.hoveredNodeId,highlightedPath: props.highlightedPath,highlightedEdges: props.highlightedEdges,searchDimmedNodes: props.searchDimmedNodes,@@ -119,13 +115,11 @@ export const SigmaCanvas = forwardRef<SigmaCanvasHandle, SigmaCanvasProps>(// Keep callback refs up to date so Sigma event handlers always use latest propsconst onNodeClickRef = useRef(props.onNodeClick);const onStageClickRef = useRef(props.onStageClick);- const onNodeHoverRef = useRef(props.onNodeHover);const onNodeContextMenuRef = useRef(props.onNodeContextMenu);const onNodeDoubleClickRef = useRef(props.onNodeDoubleClick);useEffect(() => {onNodeClickRef.current = props.onNodeClick;onStageClickRef.current = props.onStageClick;- onNodeHoverRef.current = props.onNodeHover;onNodeContextMenuRef.current = props.onNodeContextMenu;onNodeDoubleClickRef.current = props.onNodeDoubleClick;});@@ -144,14 +138,15 @@ export const SigmaCanvas = forwardRef<SigmaCanvasHandle, SigmaCanvasProps>(onStageClickRef.current?.();};- const handleEnterNode = ({ node }: { node: string }) => {- onNodeHoverRef.current?.(node);- if (container)- container.style.cursor = "pointer";+ // Cursor affordance only. Sigma draws its own hover highlight, so hover+ // never needs to reach React — an `onNodeHover` callback used to publish+ // it into shell state that nothing read, re-rendering the whole shell on+ // every hover transition.+ const handleEnterNode = () => {+ if (container) container.style.cursor = "pointer";};const handleLeaveNode = () => {- onNodeHoverRef.current?.(null);if (container) container.style.cursor = "grab";};@@ -248,7 +243,6 @@ export const SigmaCanvas = forwardRef<SigmaCanvasHandle, SigmaCanvasProps>(isLayoutRunning={props.layoutMode === "force" ? isLayoutRunning : isElkComputing}onToggleLayout={props.layoutMode === "force" ? toggleLayout : undefined}/>- <SigmaMinimap sigma={sigma} graphTheme={props.graphTheme} /></div>);},diff --git a/packages/ui/src/graph/sigma/sigma-minimap.tsx b/packages/ui/src/graph/sigma/sigma-minimap.tsxdeleted file mode 100644index 454c4ff01..000000000--- a/packages/ui/src/graph/sigma/sigma-minimap.tsx+++ /dev/null@@ -1,92 +0,0 @@-"use client";--import { useRef, useEffect } from "react";-import type Sigma from "sigma";--interface SigmaMinimapProps {- sigma: Sigma | null;- graphTheme: "light" | "dark";-}--export function SigmaMinimap({ sigma, graphTheme }: SigmaMinimapProps) {- const canvasRef = useRef<HTMLCanvasElement>(null);-- useEffect(() => {- if (!sigma) return;-- const canvas = canvasRef.current;- if (!canvas) return;- const ctx = canvas.getContext("2d");- if (!ctx) return;-- const draw = () => {- const width = canvas.width;- const height = canvas.height;- const graph = sigma.getGraph();-- ctx.clearRect(0, 0, width, height);-- if (graph.order === 0) return;-- let minX = Infinity;- let maxX = -Infinity;- let minY = Infinity;- let maxY = -Infinity;-- graph.forEachNode((_node, attrs) => {- if (attrs.x < minX) minX = attrs.x;- if (attrs.x > maxX) maxX = attrs.x;- if (attrs.y < minY) minY = attrs.y;- if (attrs.y > maxY) maxY = attrs.y;- });-- const rangeX = maxX - minX || 1;- const rangeY = maxY - minY || 1;- const padding = 8;- const drawW = width - padding * 2;- const drawH = height - padding * 2;-- graph.forEachNode((_node, attrs) => {- const px = padding + ((attrs.x - minX) / rangeX) * drawW;- const py = padding + ((attrs.y - minY) / rangeY) * drawH;- ctx.fillStyle = (attrs.color as string) || "#6b7280";- ctx.beginPath();- ctx.arc(px, py, 1.5, 0, Math.PI * 2);- ctx.fill();- });-- const camera = sigma.getCamera();- const state = camera.getState();- const vw = (1 / (state.ratio || 1)) * 0.3;- const vh = (1 / (state.ratio || 1)) * 0.3;- const vx = padding + ((state.x - minX) / rangeX) * drawW - (vw * drawW) / 2;- const vy = padding + ((state.y - minY) / rangeY) * drawH - (vh * drawH) / 2;-- ctx.strokeStyle = graphTheme === "dark" ? "rgba(255,255,255,0.3)" : "rgba(0,0,0,0.3)";- ctx.lineWidth = 1;- ctx.strokeRect(vx, vy, vw * drawW, vh * drawH);- };-- sigma.on("afterRender", draw);- draw();-- return () => {- sigma.off("afterRender", draw);- };- }, [sigma, graphTheme]);-- const isDark = graphTheme === "dark";-- return (- <canvas- ref={canvasRef}- width={120}- height={80}- className={`absolute bottom-3 left-3 z-10 rounded-lg border hidden sm:block ${- isDark- ? "bg-[#1a1a2e] border-white/10 shadow-lg shadow-black/40"- : "bg-[var(--color-bg-surface)] border-[var(--color-border-default)] shadow-lg shadow-black/20"- }`}- />- );-}diff --git a/packages/ui/src/graph/sigma/types.ts b/packages/ui/src/graph/sigma/types.tsindex 234cda375..f0050ab9a 100644--- a/packages/ui/src/graph/sigma/types.ts+++ b/packages/ui/src/graph/sigma/types.ts@@ -44,6 +44,11 @@ export interface SigmaNodeAttributes {languages?: string[] | undefined;/** Family hub hue for the soft halo ring drawn around hub discs. */haloColor?: string | undefined;+ /** Ink for the label drawn *inside* a hub/core disc, resolved from the node's+ * BASE fill. Must not be derived in the drawer: by then the reducers have+ * already dimmed `color`, and picking against a dimmed fill inverts the ink+ * so dimmed labels come out brighter than undimmed ones. */+ labelInk?: string | undefined;/** Render the label even when density culling would hide it (hubs/core). */forceLabel?: boolean | undefined;diff --git a/packages/ui/src/graph/sigma/use-elk-sigma-layout.ts b/packages/ui/src/graph/sigma/use-elk-sigma-layout.tsindex badfd434e..4ad7097a6 100644--- a/packages/ui/src/graph/sigma/use-elk-sigma-layout.ts+++ b/packages/ui/src/graph/sigma/use-elk-sigma-layout.ts@@ -25,6 +25,26 @@ export function elkSkipReason(order: number): string {return `Hierarchical layout is limited to ${ELK_MAX_NODES} nodes — this view has ${order.toLocaleString()}. Switch to the Modules scope or narrow the view to use it.`;}+/**+ * Write computed positions onto the graph in ONE pass. Graphology emits an+ * event per `setNodeAttribute`, so the obvious `forEachNode` + two setters+ * fired 2 events per node — 3,000 for a 500-node ELK run's worth of listeners+ * to walk. `updateEachNodeAttributes` with an explicit attribute hint emits a+ * single `eachNodeAttributesUpdated` instead.+ */+function applyPositions(+ graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes>,+ positions: Map<string, { x: number; y: number }>,+): void {+ graph.updateEachNodeAttributes(+ (nodeId, attrs) => {+ const pos = positions.get(nodeId);+ return pos ? { ...attrs, x: pos.x, y: pos.y } : attrs;+ },+ { attributes: ["x", "y"] },+ );+}+export interface UseElkSigmaLayoutOptions {graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes> | null;sigma: Sigma | null;@@ -73,23 +93,11 @@ export function useElkSigmaLayout(moduleEdges,);if (computeIdRef.current !== computeId) return;- graph.forEachNode((nodeId) => {- const pos = positions.get(nodeId);- if (pos) {- graph.setNodeAttribute(nodeId, "x", pos.x);- graph.setNodeAttribute(nodeId, "y", pos.y);- }- });+ applyPositions(graph, positions);} else if (fileNodes && fileEdges) {const result = await computeElkFilePositions(fileNodes, fileEdges);if (computeIdRef.current !== computeId) return;- graph.forEachNode((nodeId) => {- const pos = result.positions.get(nodeId);- if (pos) {- graph.setNodeAttribute(nodeId, "x", pos.x);- graph.setNodeAttribute(nodeId, "y", pos.y);- }- });+ applyPositions(graph, result.positions);}sigma.refresh();sigma.getCamera().animatedReset({ duration: 500 });diff --git a/packages/ui/src/graph/sigma/use-sigma.ts b/packages/ui/src/graph/sigma/use-sigma.tsindex 6764dab1a..3acaed3f9 100644--- a/packages/ui/src/graph/sigma/use-sigma.ts+++ b/packages/ui/src/graph/sigma/use-sigma.ts@@ -1,4 +1,4 @@-import { useRef, useEffect, useCallback, useState } from "react";+import { useRef, useEffect, useCallback, useState, useMemo } from "react";import type Sigma from "sigma";import type Graph from "graphology";import type { NodeLabelDrawingFunction, drawDiscNodeLabel } from "sigma/rendering";@@ -15,7 +15,7 @@ import {type EdgeKind,languageColor,} from "./constants";-import { getCommunityFamily, resolveToken, useThemeVersion } from "../../shared/use-theme-tokens";+import { resolveToken, useCommunityFamilies, useThemeVersion } from "../../shared/use-theme-tokens";// ---- Color helpers (kept minimal — avoid regex in hot paths) ----@@ -28,21 +28,85 @@ function rgbToHex(r: number, g: number, b: number): string {return "#" + ((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1);}-const THEME_COLORS = {- dark: { bg: [18, 18, 28] as const, text: "#f5f5f7", subtitle: "#888888", tooltip: "#12121c" },- light: { bg: [250, 250, 252] as const, text: "#1a1a2e", subtitle: "#666666", tooltip: "#ffffff" },-};+/**+ * Parse a resolved token into RGB. Custom properties come back as authored, so+ * in practice this only ever sees `#rrggbb` — but a token that later becomes+ * `#rgb` or an `rgb()` string must not silently yield NaN, which would poison+ * `dimColor` for every node on the canvas. Runs once per theme flip, never in+ * a hot path, so the regex is affordable here.+ */+function parseColorToRgb(+ value: string,+ fallback: [number, number, number],+): [number, number, number] {+ const v = value.trim();+ if (/^#[0-9a-f]{6}$/i.test(v)) return hexToRgb(v);+ if (/^#[0-9a-f]{3}$/i.test(v)) {+ return [+ parseInt(v[1]! + v[1]!, 16),+ parseInt(v[2]! + v[2]!, 16),+ parseInt(v[3]! + v[3]!, 16),+ ];+ }+ const m = v.match(/^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/i);+ if (m) return [Number(m[1]), Number(m[2]), Number(m[3])];+ return fallback;+}++/** WCAG relative luminance. */+function relativeLuminance([r, g, b]: [number, number, number]): number {+ const channel = (c: number) => {+ const s = c / 255;+ return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);+ };+ return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);+}++function contrastRatio(a: number, b: number): number {+ return a > b ? (a + 0.05) / (b + 0.05) : (b + 0.05) / (a + 0.05);+}++// Ink for labels painted *inside* a colored disc. Deliberately theme-independent:+// the disc fill is a community hue that does not track light/dark the way body+// text does, so the ink is picked from the fill's own luminance instead of the+// theme. This used to be a single hardcoded dark ink, which measured 5.23-8.86:1+// across all 12 hues in dark mode but failed 4.5:1 on 10 of 12 in LIGHT, where+// the community hues are deep and saturated.+//+// The pair is deliberately a shade wider than the page's text tokens. Picking by+// luminance alone against the softer #1a1320/#faf7f4 pair left four mid-luminance+// hues stranded at 4.32-4.40:1 — close, but short. These clear 4.5:1 on all 12+// hues in BOTH themes (worst pair 4.54:1) while staying warm, where pure+// black/white would read as a foreign element on this palette.+const DISC_INK_DARK = "#0d0910";+const DISC_INK_LIGHT = "#fffdfb";+const DISC_INK_DARK_LUM = relativeLuminance(hexToRgb(DISC_INK_DARK));+const DISC_INK_LIGHT_LUM = relativeLuminance(hexToRgb(DISC_INK_LIGHT));+const discInkCache = new Map<string, string>();++/** Pick whichever ink contrasts better against the disc fill. */+function discInkFor(fill: string): string {+ const cached = discInkCache.get(fill);+ if (cached) return cached;+ const lum = relativeLuminance(parseColorToRgb(fill, [128, 128, 128]));+ const ink =+ contrastRatio(lum, DISC_INK_DARK_LUM) >= contrastRatio(lum, DISC_INK_LIGHT_LUM)+ ? DISC_INK_DARK+ : DISC_INK_LIGHT;+ discInkCache.set(fill, ink);+ return ink;+}/**- * Hub/core disc-label drawer, built per theme. Hub/core labels render centered- * *inside* the disc (ROBOTICS-style) with a soft halo ring in the family hue;- * everything else falls through to Sigma's stock side-label drawer. Factored out- * of the init effect so the theme effect can re-set it on light/dark toggle- * (the closure must NOT capture stale theme colors). Closes over only its args +- * the stable THEME_COLORS import.+ * Hub/core disc-label drawer. Hub/core labels render centered *inside* the disc+ * (ROBOTICS-style) with a soft halo ring in the family hue; everything else+ * falls through to Sigma's stock side-label drawer.+ *+ * Takes no palette: every colour it paints comes off the node itself (the halo+ * from `haloColor`, the ink from `labelInk`), both resolved by the colour pass.+ * That is what lets it survive a theme flip without being rebuilt.*/function makeDrawNodeLabel(- graphTheme: "light" | "dark",drawDisc: typeof drawDiscNodeLabel,): NodeLabelDrawingFunction {return (context, data, settings) => {@@ -53,7 +117,6 @@ function makeDrawNodeLabel(return;}- const theme = THEME_COLORS[graphTheme] ?? THEME_COLORS.dark;const size = data.size || 20;// Soft 2px halo ring in the family hue (emulated — NodeCircleProgram@@ -81,24 +144,28 @@ function makeDrawNodeLabel(}context.textAlign = "center";context.textBaseline = "middle";- // Core is dark → light text; hubs are warm → dark text for contrast.- context.fillStyle = kind === "core" ? theme.text : "#1a1320";+ // Pre-resolved from the node's BASE fill by the color pass. Deriving it+ // here from `data.color` would be wrong: `data` is post-reducer, so a+ // dimmed hub would pick ink against its dimmed fill and come out brighter+ // than an undimmed one — dimming would make labels louder, not quieter.+ // The fallback only covers a node the color pass has not reached yet,+ // whose color is therefore still an undimmed placeholder.+ context.fillStyle = (extra.labelInk as string) || discInkFor(data.color);context.fillText(label, data.x, data.y);};}/**- * Hover tooltip drawer, built per theme. Hubs get a small surface card (member+ * Hover tooltip drawer, built per palette. Hubs get a small surface card (member* count, doc %, langs); other nodes get a label/path pill. Factored out of the* init effect alongside makeDrawNodeLabel so the theme effect can re-set it on- * light/dark toggle. Closes over only its arg + the stable THEME_COLORS import.+ * light/dark toggle (the closure must NOT capture a stale palette).*/-function makeDrawNodeHover(graphTheme: "light" | "dark"): NodeLabelDrawingFunction {+function makeDrawNodeHover(theme: VizPalette): NodeLabelDrawingFunction {return (context, data, settings) => {const label = data.label;if (!label) return;- const theme = THEME_COLORS[graphTheme] ?? THEME_COLORS.dark;const extra = data as Record<string, unknown>;const fullPath = (extra.fullPath as string) ?? undefined;@@ -246,9 +313,15 @@ interface VizPalette {label: string;pathHighlight: string;edge: Record<EdgeKind, string>;+ /** The canvas plane, as RGB. `dimColor` blends toward this. */+ bg: [number, number, number];+ text: string;+ subtitle: string;+ tooltip: string;}function resolveVizPalette(theme: "light" | "dark"): VizPalette {+ const dark = theme === "dark";return {risk: {high: resolveToken("--color-risk-high", "#b23a2e"),@@ -257,13 +330,31 @@ function resolveVizPalette(theme: "light" | "dark"): VizPalette {},hotspot: resolveToken("--color-warning", "#9a6614"),decision: resolveToken("--color-warning", "#9a6614"),- label: resolveToken("--color-text-secondary", theme === "dark" ? "#a79db3" : "#5e5360"),+ label: resolveToken("--color-text-secondary", dark ? "#a79db3" : "#5e5360"),pathHighlight: resolveToken("--color-accent-fill", "#f59520"),edge: edgeColorsForTheme(theme),+ // The canvas plane. sigma-canvas paints `--color-bg-root` explicitly in+ // dark and stays transparent in light over a body painted the same token,+ // so this one value is the correct blend target in BOTH themes. It used to+ // be a hardcoded mirror that had drifted: #12121c (blue-black) against a+ // real #0e0e0f, and a cool white against warm #fbf6f1 paper. dimColor+ // blends toward it, so every dimmed node settled lighter and bluer than+ // the canvas and never fully receded — and dimming is how this canvas+ // expresses focus.+ bg: parseColorToRgb(+ resolveToken("--color-bg-root", dark ? "#0e0e0f" : "#fbf6f1"),+ dark ? [14, 14, 15] : [251, 246, 241],+ ),+ text: resolveToken("--color-text-primary", dark ? "#f2f2f3" : "#241b2c"),+ subtitle: resolveToken("--color-text-secondary", dark ? "#b4b4b9" : "#5e5360"),+ tooltip: resolveToken("--color-bg-surface", dark ? "#141416" : "#ffffff"),};}-let activeBg: readonly [number, number, number] = THEME_COLORS.dark.bg;+// Read by `dimColor`, which runs inside Sigma's node reducer — outside React,+// so it cannot take the palette as an argument. Kept in sync by the theme+// effect, which also drops the color caches keyed to the previous plane.+let activeBg: readonly [number, number, number] = [14, 14, 15];const dimColorCache = new Map<string, string>();const brightenColorCache = new Map<string, string>();@@ -325,7 +416,6 @@ export interface UseSigmaOptions {container: HTMLDivElement | null;graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes> | null;selectedNodeId: string | null;- hoveredNodeId: string | null;highlightedPath: Set<string>;highlightedEdges: Set<string>;searchDimmedNodes: Set<string> | null;@@ -352,21 +442,37 @@ export interface UseSigmaReturn {}export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {- const newBg = (THEME_COLORS[options.graphTheme] ?? THEME_COLORS.dark).bg;- if (newBg !== activeBg) {- activeBg = newBg;+ // Re-resolve theme tokens (risk / hotspot / edge / label / plane) when the+ // theme flips so the canvas repaints in the active palette. Memoized, not+ // recomputed per render: this was previously the argument to `useRef(...)`,+ // which evaluates on every render and discards all but the first result —+ // seven getComputedStyle reads per render for nothing.+ const themeVersion = useThemeVersion();+ const viz = useMemo(+ () => resolveVizPalette(options.graphTheme),+ [options.graphTheme, themeVersion],+ );+ // Pre-resolves the 12 community families once per theme version. The color+ // pass below used to call the raw `getCommunityFamily` per node, which is two+ // getComputedStyle reads each — ~3,000 synchronous style reads for a+ // 1,500-node load, repeated on every colorMode toggle and theme flip.+ const communityFamilies = useCommunityFamilies();++ // Mirror of `viz` readable from Sigma's reducers, which run outside React.+ const vizRef = useRef<VizPalette>(viz);++ // Point `dimColor` at the new canvas plane during render, not in the effect+ // below. Sigma renders on its own schedule, so a frame driven by mouse or+ // camera motion can land between commit and passive-effect flush; doing this+ // in the effect would let that frame blend toward the previous theme's plane+ // using caches keyed to it. `viz` is memoized, so this fires once per theme+ // change rather than once per render.+ if (activeBg !== viz.bg) {+ activeBg = viz.bg;clearColorCaches();}- // Re-resolve theme tokens (risk / hotspot / community / edge / label) when the- // theme flips so the canvas repaints in the active palette.- const themeVersion = useThemeVersion();- const vizRef = useRef<VizPalette>(resolveVizPalette(options.graphTheme));-const sigmaRef = useRef<Sigma | null>(null);- // Sigma's stock disc-label drawer, captured from the dynamic import in the- // init effect so the theme effect can rebuild the label drawer factory.- const drawDiscRef = useRef<typeof drawDiscNodeLabel | null>(null);const [sigmaReady, setSigmaReady] = useState<Sigma | null>(null);const selectedRef = useRef<string | null>(null);const highlightedPathRef = useRef<Set<string>>(new Set());@@ -419,7 +525,6 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {useEffect(() => {const graph = options.graph;if (!graph || graph.order === 0) return;- const viz = (vizRef.current = resolveVizPalette(options.graphTheme));const cm = options.colorMode;const coreColor = resolveToken("--color-bg-inset", "#141415");graph.updateEachNodeAttributes(@@ -429,23 +534,31 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {// the active colorMode — the radial view *is* the community view. The// repo-core is a dark plum disc; its halo borrows the soft canvas dot.if (attrs.nodeType === "hub") {- const family = getCommunityFamily(attrs.communityId);+ const family = communityFamilies(attrs.communityId);color = family.hub;- const next = { ...attrs, color, haloColor: family.satellite || family.hub };- if (attrs.color === color && attrs.haloColor === next.haloColor) return attrs;- return next;+ const haloColor = family.satellite || family.hub;+ const labelInk = discInkFor(color);+ if (+ attrs.color === color &&+ attrs.haloColor === haloColor &&+ attrs.labelInk === labelInk+ ) {+ return attrs;+ }+ return { ...attrs, color, haloColor, labelInk };}if (attrs.nodeType === "core") {color = coreColor;- if (attrs.color === color) return attrs;- return { ...attrs, color };+ const labelInk = discInkFor(color);+ if (attrs.color === color && attrs.labelInk === labelInk) return attrs;+ return { ...attrs, color, labelInk };}if (cm === "language") {// Modules aggregate many languages and carry none themselves — fall// back to the community hue instead of a meaningless "other" gray.color =attrs.nodeType === "module"- ? getCommunityFamily(attrs.communityId).hub+ ? communityFamilies(attrs.communityId).hub: languageColor(attrs.language || "other");} else {// Community. Modules (centroids) get the hub hue; files use the@@ -456,7 +569,7 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {// graph, so those thresholds are unreachable on any real repo and// the lens rendered entirely green. See the `ColorMode` docstring in// `graph-toolbar.tsx` for why it is gone rather than re-tuned.- const family = getCommunityFamily(attrs.communityId);+ const family = communityFamilies(attrs.communityId);color = attrs.nodeType === "module" ? family.hub : family.satellite;}if (attrs.isDead) color = desaturateColor(color, 0.6);@@ -467,16 +580,16 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {if (attrs.color === color) return attrs;return { ...attrs, color };},- { attributes: ["color"] },+ { attributes: ["color", "haloColor", "labelInk"] },);- }, [options.colorMode, options.graph, options.graphTheme, themeVersion]);+ }, [options.colorMode, options.graph, viz, communityFamilies]);// Re-color edges by semantic kind for the active theme (canvas can't resolve// var()). Build-time colors are placeholders; this is the source of truth.useEffect(() => {const graph = options.graph;if (!graph || graph.size === 0) return;- const edge = (vizRef.current = resolveVizPalette(options.graphTheme)).edge;+ const edge = viz.edge;graph.updateEachEdgeAttributes((_edgeKey, attrs) => {const color = edge[attrs.edgeKind] ?? edge.import;@@ -485,27 +598,24 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {},{ attributes: ["color"] },);- }, [options.graph, options.graphTheme, themeVersion]);+ }, [options.graph, viz]);- // Keep the label color in the active text token when the theme flips, and- // rebuild the hub/core disc-label + hover drawers so their theme-dependent- // text/tooltip colors track the toggle (the init-effect closures would- // otherwise stay pinned to the mount-time theme until remount).+ // Theme flip: publish the new palette to the reducers, re-point the canvas+ // plane that `dimColor` blends toward (dropping the color caches keyed to the+ // old plane), and rebuild the disc-label + hover drawers, whose closures+ // capture palette colors and would otherwise stay pinned to the mount-time+ // theme until remount.useEffect(() => {+ vizRef.current = viz;const sigma = sigmaRef.current;if (!sigma) return;- const label = (vizRef.current = resolveVizPalette(options.graphTheme)).label;- sigma.setSetting("labelColor", { color: label });- const drawDisc = drawDiscRef.current;- if (drawDisc) {- sigma.setSetting(- "defaultDrawNodeLabel",- makeDrawNodeLabel(options.graphTheme, drawDisc),- );- }- sigma.setSetting("defaultDrawNodeHover", makeDrawNodeHover(options.graphTheme));+ sigma.setSetting("labelColor", { color: viz.label });+ // Only the hover drawer needs rebuilding: it paints the tooltip card from+ // the palette. The disc-label drawer takes its colours off the node and is+ // theme-independent, so it is built once at init.+ sigma.setSetting("defaultDrawNodeHover", makeDrawNodeHover(viz));sigma.refresh();- }, [options.graphTheme, themeVersion]);+ }, [viz]);// Initialize Sigma (dynamic import to avoid SSR WebGL crash)useEffect(() => {@@ -528,7 +638,6 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {const EdgeLineProgram = sigmaRendering.EdgeLineProgram;const EdgeArrowProgram = sigmaRendering.EdgeArrowProgram;const drawDiscNodeLabel = sigmaRendering.drawDiscNodeLabel;- drawDiscRef.current = drawDiscNodeLabel;if (cancelled) return;@@ -556,13 +665,24 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {minCameraRatio: 0.002,maxCameraRatio: 50,hideEdgesOnMove: true,+ // Labels are a canvas2d pass that Sigma re-runs on every camera frame,+ // and at this graph size it is the dominant cost of a pan or a zoom —+ // WebGL draws the nodes almost for free by comparison. With this set,+ // dragging and zooming skip renderLabels/renderEdgeLabels/+ // renderHighlightedNodes entirely and paint nodes only; everything+ // comes back on the first settled frame. Pairs with hideEdgesOnMove+ // above, which already does the same for the edge programs.+ hideLabelsOnMove: true,zIndex: true,- // Hub/core disc labels + hover tooltips. Built per theme via module-level- // factories so the theme effect can re-set them on light/dark toggle- // without remount (single source of truth — no duplicated drawer logic).- defaultDrawNodeLabel: makeDrawNodeLabel(options.graphTheme, drawDiscNodeLabel),- defaultDrawNodeHover: makeDrawNodeHover(options.graphTheme),+ // Hub/core disc labels + hover tooltips. The label drawer is+ // theme-independent (it reads colours off the node) and is built once.+ // The hover drawer paints from the palette, so the theme effect re-sets+ // it on light/dark toggle without a remount; it is read through the ref+ // here because this effect depends only on the container, which would+ // otherwise leave its `viz` closure stale.+ defaultDrawNodeLabel: makeDrawNodeLabel(drawDiscNodeLabel),+ defaultDrawNodeHover: makeDrawNodeHover(vizRef.current),// --- nodeReducer: ONLY handles interaction state (selection, search, path) ---// Colors and sizes are pre-set on the graphology graph by the effect above.@@ -691,6 +811,25 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {sigma.getCamera().animatedReset({ duration: 500 });}, [options.graph]);+ // Label culling is a function of graph size, but the init effect above depends+ // only on the container — so a scope switch or a "load more" step to a much+ // larger graph would otherwise keep the mount-time values and label-spam the+ // canvas. `sigmaReady` is in the deps so this also applies once the async init+ // resolves. `setSetting` has no equality check of its own — it revalidates and+ // schedules a refresh on every call — but this only fires when the graph+ // identity actually changes, and the graph-swap effect above already refreshes+ // and resets the camera, so the extra schedule coalesces into that frame.+ useEffect(() => {+ const sigma = sigmaRef.current;+ const graph = options.graph;+ if (!sigma || !graph) return;+ sigma.setSetting("labelDensity", getLabelDensity(graph.order));+ sigma.setSetting(+ "labelRenderedSizeThreshold",+ getLabelRenderedSizeThreshold(graph.order),+ );+ }, [options.graph, sigmaReady]);+const focusNode = useCallback((nodeId: string, ratio = 0.15) => {const sigma = sigmaRef.current;const graph = graphRef.current;diff --git a/packages/web/README.md b/packages/web/README.mdindex 6e4d6d838..82ee05d8d 100644--- a/packages/web/README.md+++ b/packages/web/README.md@@ -58,7 +58,7 @@ Interactive React Flow graph with ELK layout engine. Supports five view modes:Three color modes: **Language** (per-language coloring), **Community** (Leiden community clusters with real labels from analysis), **Risk** (churn-based).-Features pan/zoom, minimap, path finder for dependency chains, community detail panel (click any node in community mode to see members, cohesion, and neighboring communities with cross-edge counts), and URL param support for deep-linking color modes.+Features pan/zoom, path finder for dependency chains, community detail panel (click any node in community mode to see members, cohesion, and neighboring communities with cross-edge counts), and URL param support for deep-linking color modes.### Search (`/repos/[id]/search`)diff --git a/tests/unit/server/test_graph.py b/tests/unit/server/test_graph.pyindex 73e9acbb8..6625ff196 100644--- a/tests/unit/server/test_graph.py+++ b/tests/unit/server/test_graph.py@@ -81,6 +81,47 @@ async def test_export_graph_with_data(client: AsyncClient, app) -> None:assert data["nodes"][1]["symbol_count"] == 5+async def test_export_graph_carries_edge_type(client: AsyncClient, app) -> None:+ """Edges carry their semantic type, not just imported_names.++ Without this the client can only infer edge kind from `imported_names`+ being empty, which collapses every `defines`/`calls`/`co_changes` row into+ one bucket. Both columns are populated on the row; they were simply never+ serialized.+ """+ repo = await create_test_repo(client)+ session_factory = app.state.session_factory+ await _populate_graph(session_factory, repo["id"])+ async with get_session(session_factory) as session:+ await crud.batch_upsert_graph_edges(+ session,+ repo["id"],+ [+ {+ "source_node_id": "src/utils.py",+ "target_node_id": "src/main.py",+ "imported_names_json": "[]",+ "edge_type": "calls",+ "confidence": 0.5,+ },+ ],+ )++ resp = await client.get(f"/api/graph/{repo['id']}")+ assert resp.status_code == 200+ links = {(link["source"], link["target"]): link for link in resp.json()["links"]}++ calls = links[("src/utils.py", "src/main.py")]+ assert calls["edge_type"] == "calls"+ assert calls["confidence"] == 0.5++ # The default edge_type still round-trips, so a client can always branch on+ # it rather than falling back to the empty-imported_names heuristic.+ imports = links[("src/main.py", "src/utils.py")]+ assert imports["edge_type"] == "imports"++@pytest.mark.asyncioasync def test_export_graph_repo_not_found(client: AsyncClient) -> None:resp = await client.get("/api/graph/nonexistent")