Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(graph): fix module-view blob, hide externals by default, layered node info (#754)
Raghav Chamadiyaa571e1dcc5b8
diff --git a/packages/ui/__tests__/graph/use-sigma-focus.test.tsx b/packages/ui/__tests__/graph/use-sigma-focus.test.tsxindex 40eb72ce4..357fa2c52 100644--- a/packages/ui/__tests__/graph/use-sigma-focus.test.tsx+++ b/packages/ui/__tests__/graph/use-sigma-focus.test.tsx@@ -35,9 +35,13 @@ class FakeSigma {}vi.mock("sigma", () => ({ default: FakeSigma }));-vi.mock("@sigma/edge-curve", () => ({ default: class {} }));+vi.mock("@sigma/edge-curve", () => ({+ default: class {},+ EdgeCurvedArrowProgram: class {},+}));vi.mock("sigma/rendering", () => ({EdgeLineProgram: class {},+ EdgeArrowProgram: class {},drawDiscNodeLabel: () => {},}));diff --git a/packages/ui/src/graph/elk-layout.ts b/packages/ui/src/graph/elk-layout.tsindex 0e9171199..ed8d6c019 100644--- a/packages/ui/src/graph/elk-layout.ts+++ b/packages/ui/src/graph/elk-layout.ts@@ -58,6 +58,11 @@ export interface ModuleNodeData {isEntryPoint?: boolean;isTest?: boolean;dominantCommunityId?: number | undefined;+ /** Health rollups from the module API (0 / false / null when absent). */+ hotspotCount?: number;+ deadCount?: number;+ hasDecision?: boolean;+ primaryOwner?: string | null;[key: string]: unknown;}diff --git a/packages/ui/src/graph/graph-flow.tsx b/packages/ui/src/graph/graph-flow.tsxindex 5bd9929de..a6ab54d77 100644--- a/packages/ui/src/graph/graph-flow.tsx+++ b/packages/ui/src/graph/graph-flow.tsx@@ -23,6 +23,8 @@ const HUB_FOCUS_RATIO = 0.45;// Below this node count file graphs build synchronously; at or above it we// build in chunks off the critical path (see sigmaGraph below).const ASYNC_BUILD_THRESHOLD = 1000;+// One-time "double-click to expand" hint for the modules scope.+const MODULE_HINT_KEY = "repowise-graph-module-hint";/** Deterministic 0–1 value from a string (FNV-1a) — stable layout jitter. */function hashUnit(s: string): number {@@ -59,6 +61,8 @@ import {fileGraphToGraphologyAsync,moduleGraphToGraphology,groupFilesAsModules,+ settleGraph,+ isExternalModuleId,} from "./sigma/graphology-adapter";import {architectureToGraphology,@@ -243,6 +247,38 @@ export function GraphFlow(props: GraphFlowProps) {const { expandedModules, toggleModule, collapseAll } = useExpandedModules();const hasExpandedModules = expandedModules.size > 0;+ // External `external:*` dependency modules are hidden by default — they+ // outnumber the repo's own modules and drown the layout. Toggle in toolbar.+ const [showExternals, setShowExternals] = useState(false);+ const externalCount = useMemo(+ () =>+ moduleGraph+ ? moduleGraph.nodes.reduce(+ (n, mod) => n + (isExternalModuleId(mod.module_id) ? 1 : 0),+ 0,+ )+ : 0,+ [moduleGraph],+ );++ // One-time "double-click a module to expand it" hint (persists dismissal).+ const [moduleHintDismissed, setModuleHintDismissed] = useState<boolean>(() => {+ if (typeof window === "undefined") return true;+ try {+ return window.localStorage.getItem(MODULE_HINT_KEY) === "1";+ } catch {+ return true;+ }+ });+ const dismissModuleHint = useCallback(() => {+ setModuleHintDismissed(true);+ try {+ window.localStorage.setItem(MODULE_HINT_KEY, "1");+ } catch {+ /* private mode — session-only dismissal */+ }+ }, []);+// Expand/collapse constellation hubs (radial blossom). Esc collapses the most// recently expanded hub; multiple hubs may be open at once.const { expandedHubs, toggleHub, collapseLast, collapseAll: collapseAllHubs } =@@ -486,28 +522,39 @@ export function GraphFlow(props: GraphFlowProps) {const syncSigmaGraph = useMemo(() => {if (isModuleView) {if (isDrilledDown && fullGraph) {- return groupFilesAsModules(fullGraph, { prefix: currentPrefix });+ return settleGraph(groupFilesAsModules(fullGraph, { prefix: currentPrefix }));}if (!moduleGraph) return null;+ const moduleOpts = {+ hideExternals: !showExternals,+ ...(communities ? { communities } : {}),+ };+if (expandedModules.size === 0 || !fullGraph || !fullGraphIndexes) {- return moduleGraphToGraphology(moduleGraph, communities ? { communities } : {});+ // Settle synchronously so the first painted frame is the final layout+ // (no FA2 convergence animation collapsing the graph into a blob).+ return settleGraph(moduleGraphToGraphology(moduleGraph, moduleOpts));}- const graph = moduleGraphToGraphology(moduleGraph, communities ? { communities } : {});+ const graph = moduleGraphToGraphology(moduleGraph, moduleOpts);for (const moduleId of expandedModules) {if (!graph.hasNode(moduleId)) continue;+ const childNodes = fullGraphIndexes.moduleChildIndex.get(moduleId) ?? [];+ // No file-level children in the loaded graph (e.g. a docs-only module+ // under a capped node set): keep the module node instead of silently+ // vanishing it.+ if (childNodes.length === 0) continue;+const modAttrs = graph.getNodeAttributes(moduleId);const modX = modAttrs.x;const modY = modAttrs.y;graph.dropNode(moduleId);- const childNodes = fullGraphIndexes.moduleChildIndex.get(moduleId) ?? [];-const nodeCount = fullGraph.nodes.length;const jitter = 30;@@ -596,7 +643,9 @@ export function GraphFlow(props: GraphFlowProps) {}}- return graph;+ // Re-settle from the warm module positions so expanded files land in a+ // readable blossom immediately (no worker restart, no wobble).+ return settleGraph(graph);}const graphData = fileGraphData;@@ -613,7 +662,7 @@ export function GraphFlow(props: GraphFlowProps) {{ nodes: graphData.nodes, links: graphData.links },{ signals },);- }, [isModuleView, isDrilledDown, fullGraph, currentPrefix, moduleGraph, communities, expandedModules, fileGraphData, hasHotSignal, hasDeadSignal, isUnified, hotNodeIds, deadNodeIds, fullGraphIndexes]);+ }, [isModuleView, isDrilledDown, fullGraph, currentPrefix, moduleGraph, communities, expandedModules, showExternals, fileGraphData, hasHotSignal, hasDeadSignal, isUnified, hotNodeIds, deadNodeIds, fullGraphIndexes]);// Async-built file graph for large graphs (built in chunks off the main// thread critical path). Null while building / when the sync path applies.@@ -700,6 +749,10 @@ export function GraphFlow(props: GraphFlowProps) {symbolCount: attrs.symbolCount,avgPagerank: attrs.avgPagerank ?? 0,docCoveragePct: attrs.docCoveragePct ?? 0,+ hotspotCount: attrs.hotspotCount ?? 0,+ deadCount: attrs.deadCount ?? 0,+ hasDecision: attrs.hasDecision ?? false,+ primaryOwner: attrs.primaryOwner ?? null,dominantCommunityId: attrs.dominantCommunityId,});}@@ -852,6 +905,7 @@ export function GraphFlow(props: GraphFlowProps) {(nodeId: string, nodeType: string): boolean | void => {if (nodeType === "module") {toggleModule(nodeId);+ dismissModuleHint();return true;}if (nodeType === "hub" && sigmaGraph?.hasNode(nodeId)) {@@ -866,7 +920,7 @@ export function GraphFlow(props: GraphFlowProps) {onNodeViewDocs?.(nodeId);return true;},- [onNodeViewDocs, toggleModule, sigmaGraph, handleConstellationHubToggle],+ [onNodeViewDocs, toggleModule, dismissModuleHint, sigmaGraph, handleConstellationHubToggle],);// Unified grammar — SINGLE CLICK = select + inspect (never structural):@@ -1024,6 +1078,14 @@ export function GraphFlow(props: GraphFlowProps) {});}, []);+ // A rebuild can drop the selected node (module expanded into files) — clear+ // the selection then, or the reducer dims the whole canvas around a ghost.+ useEffect(() => {+ if (selectedNodeId && sigmaGraph && !sigmaGraph.hasNode(selectedNodeId)) {+ setSelectedNodeId(null);+ }+ }, [sigmaGraph, selectedNodeId]);+const initialNodeApplied = useRef(false);useEffect(() => {if (initialNodeApplied.current || !initialSelectedNode || !sigmaGraph) return;@@ -1051,8 +1113,9 @@ export function GraphFlow(props: GraphFlowProps) {const handleInspectExpandModule = useCallback(() => {if (selectedNodeId) {toggleModule(selectedNodeId);+ dismissModuleHint();}- }, [selectedNodeId, toggleModule]);+ }, [selectedNodeId, toggleModule, dismissModuleHint]);// Breadcrumbconst handleBreadcrumbClick = useCallback((index: number) => {@@ -1199,6 +1262,49 @@ export function GraphFlow(props: GraphFlowProps) {</div>) : null}+ {/* Expanded-modules chip: count + collapse-all. */}+ {isModuleView && !isDrilledDown && hasExpandedModules && (+ <div className="flex items-center gap-2 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2.5 py-1.5 shadow-sm">+ <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-graph)] hover:underline"+ >+ 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="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2.5 py-1.5 shadow-sm text-[10px] text-[var(--color-text-secondary)]"+ >+ Loading files for expanded module…+ </div>+ )}++ {/* One-time interaction hint for the modules scope. */}+ {isModuleView && !isDrilledDown && !hasExpandedModules && !moduleHintDismissed && (+ <div className="flex items-center gap-2 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2.5 py-1.5 shadow-sm">+ <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. Thetotals come from the backend when it provides them; without totalswe still report the in-view count so the overlay never reads as@@ -1284,6 +1390,9 @@ export function GraphFlow(props: GraphFlowProps) {onGraphThemeChange={handleGraphThemeChange}onToggleHelp={handleToggleShortcutHelp}availableScopes={availableScopes}+ showExternals={showExternals}+ onShowExternalsChange={setShowExternals}+ externalCount={externalCount}/></div>@@ -1359,8 +1468,9 @@ export function GraphFlow(props: GraphFlowProps) {</div>)}- {/* Legend */}- <div className="absolute bottom-3 left-3 z-10">+ {/* 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" : ""}`}><GraphLegendnodeCount={sigmaGraph?.order ?? 0}edgeCount={sigmaGraph?.size ?? 0}@@ -1430,6 +1540,7 @@ export function GraphFlow(props: GraphFlowProps) {filePageHref={fileNd ? fileHrefFor?.(selectedNodeId) : undefined}onFindPath={handleInspectFindPath}onExpandModule={modNd ? handleInspectExpandModule : undefined}+ isModuleExpanded={modNd ? expandedModules.has(selectedNodeId) : false}egoDepth={egoDepth}onEgoDepthChange={setEgoDepth}egoVisibleCount={egoVisibleCount}diff --git a/packages/ui/src/graph/graph-inspection-panel.tsx b/packages/ui/src/graph/graph-inspection-panel.tsxindex 07add52f4..00af5a680 100644--- a/packages/ui/src/graph/graph-inspection-panel.tsx+++ b/packages/ui/src/graph/graph-inspection-panel.tsx@@ -13,6 +13,9 @@ import {Route,Network,Code2,+ Flame,+ Skull,+ Lightbulb,} from "lucide-react";import { ScrollArea } from "../ui/scroll-area";import { languageColor } from "../lib/confidence";@@ -27,6 +30,8 @@ interface NeighborInfo {label: string;communityId: number;direction: "importer" | "import";+ /** Aggregated import count on the connecting edge (modules roll up many). */+ edgeCount: number;}export interface GraphInspectionPanelProps {@@ -44,6 +49,8 @@ export interface GraphInspectionPanelProps {onFindPath?: (() => void) | undefined;onShowEgoGraph?: (() => void) | undefined;onExpandModule?: (() => void) | undefined;+ /** Whether the module is currently expanded (the action becomes Collapse). */+ isModuleExpanded?: boolean | undefined;egoDepth?: number | undefined;onEgoDepthChange?: ((depth: number) => void) | undefined;egoVisibleCount?: number | undefined;@@ -77,6 +84,7 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({onFindPath,onShowEgoGraph,onExpandModule,+ isModuleExpanded,egoDepth,onEgoDepthChange,egoVisibleCount,@@ -87,7 +95,7 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({if (!graph || !graph.hasNode(nodeId)) return [];const result: NeighborInfo[] = [];const seen = new Set<string>();- graph.forEachOutEdge(nodeId, (_edge, _attrs, _source, target) => {+ graph.forEachOutEdge(nodeId, (_edge, attrs, _source, target) => {if (seen.has(target)) return;seen.add(target);const nd = allNodes.get(target);@@ -96,9 +104,10 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({label: target.split("/").pop() ?? target,communityId: nd?.communityId ?? 0,direction: "import",+ edgeCount: attrs.edgeCount ?? 1,});});- graph.forEachInEdge(nodeId, (_edge, _attrs, source) => {+ graph.forEachInEdge(nodeId, (_edge, attrs, source) => {if (seen.has(source)) return;seen.add(source);const nd = allNodes.get(source);@@ -107,6 +116,7 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({label: source.split("/").pop() ?? source,communityId: nd?.communityId ?? 0,direction: "importer",+ edgeCount: attrs.edgeCount ?? 1,});});return result;@@ -212,6 +222,9 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({</div><span className="text-caption text-[var(--color-text-tertiary)] shrink-0">{n.direction === "importer" ? "imports this" : "imported"}+ {n.edgeCount > 1 && (+ <span className="tabular-nums"> · {n.edgeCount}</span>+ )}</span></button>))}@@ -271,7 +284,8 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({onClick={onExpandModule}className="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 py-1.5 text-caption font-medium text-[var(--color-accent-graph)] transition-colors col-span-2">- <Network className="w-3 h-3" /> Expand Module+ <Network className="w-3 h-3" />+ {isModuleExpanded ? "Collapse Module" : "Expand Module"}</button>)}{onViewDocs && (@@ -463,6 +477,36 @@ function ModuleMetadata({</span></span></div>++ {data.primaryOwner && (+ <div className="flex items-center justify-between text-xs">+ <span className="text-[var(--color-text-tertiary)]">Owner</span>+ <span className="font-medium text-[var(--color-text-primary)] truncate max-w-[60%]" title={data.primaryOwner}>+ {data.primaryOwner}+ </span>+ </div>+ )}++ {/* Health badges — only rendered when there is something to say. */}+ {((data.hotspotCount ?? 0) > 0 || (data.deadCount ?? 0) > 0 || data.hasDecision) && (+ <div className="flex items-center gap-1.5 pt-1 flex-wrap">+ {(data.hotspotCount ?? 0) > 0 && (+ <span className="inline-flex items-center gap-1 rounded-md bg-[var(--color-warning)]/10 text-[var(--color-warning)] px-1.5 py-0.5 text-caption font-medium">+ <Flame className="w-2.5 h-2.5" /> {data.hotspotCount} hotspot{data.hotspotCount === 1 ? "" : "s"}+ </span>+ )}+ {(data.deadCount ?? 0) > 0 && (+ <span className="inline-flex items-center gap-1 rounded-md bg-[var(--color-error)]/10 text-[var(--color-error)] px-1.5 py-0.5 text-caption font-medium">+ <Skull className="w-2.5 h-2.5" /> {data.deadCount} dead+ </span>+ )}+ {data.hasDecision && (+ <span className="inline-flex items-center gap-1 rounded-md bg-[var(--color-accent-secondary)]/10 text-[var(--color-accent-secondary)] px-1.5 py-0.5 text-caption font-medium">+ <Lightbulb className="w-2.5 h-2.5" /> Decision+ </span>+ )}+ </div>+ )}</div>);}diff --git a/packages/ui/src/graph/graph-legend.tsx b/packages/ui/src/graph/graph-legend.tsxindex c4b81e8a1..f16b10f43 100644--- a/packages/ui/src/graph/graph-legend.tsx+++ b/packages/ui/src/graph/graph-legend.tsx@@ -187,7 +187,7 @@ export const GraphLegend = memo(function GraphLegend({{onCommunityToggle && (<buttononClick={(e) => { e.stopPropagation(); onCommunityToggle(cid); }}- className="shrink-0 w-[10px] h-[10px] rounded-sm border"+ className="shrink-0 w-4 h-4 sm:w-[10px] sm:h-[10px] rounded-sm border"style={{borderColor: color,background: checked ? color : "transparent",@@ -257,7 +257,7 @@ export const GraphLegend = memo(function GraphLegend({<div key={et.type} className="flex items-center gap-2 text-[var(--color-text-tertiary)]"><buttononClick={() => onEdgeTypeToggle(et.type)}- className="shrink-0 w-[10px] h-[10px] rounded-sm border"+ className="shrink-0 w-4 h-4 sm:w-[10px] sm:h-[10px] rounded-sm border"style={{borderColor: et.color,background: checked ? et.color : "transparent",diff --git a/packages/ui/src/graph/graph-toolbar.tsx b/packages/ui/src/graph/graph-toolbar.tsxindex 31b91b2a1..51301beac 100644--- a/packages/ui/src/graph/graph-toolbar.tsx+++ b/packages/ui/src/graph/graph-toolbar.tsx@@ -21,6 +21,7 @@ import {Moon,SlidersHorizontal,HelpCircle,+ Package,} from "lucide-react";import { memo, useState } from "react";import { Button } from "../ui/button";@@ -99,6 +100,12 @@ interface GraphToolbarProps {* surface omits the constellation scope (it lives in the Knowledge Graph* view) so there is no cross-view jump back through the toolbar. */availableScopes?: Scope[] | undefined;+ /** Modules scope: whether `external:*` dependency modules are drawn.+ * Hidden by default because they usually outnumber the repo's own modules. */+ showExternals?: boolean | undefined;+ onShowExternalsChange?: ((v: boolean) => void) | undefined;+ /** How many external modules the toggle controls (0 hides the toggle). */+ externalCount?: number | undefined;}// Scope = which subset of nodes are drawn. Mutually exclusive.@@ -161,6 +168,9 @@ export const GraphToolbar = memo(function GraphToolbar({onGraphThemeChange,onToggleHelp,availableScopes,+ showExternals,+ onShowExternalsChange,+ externalCount,}: GraphToolbarProps) {const scopes = availableScopes? SCOPES.filter((s) => availableScopes.includes(s.id))@@ -224,7 +234,7 @@ export const GraphToolbar = memo(function GraphToolbar({<buttonkey={m.id}onClick={() => setScope(m.id)}- className={`flex items-center gap-1.5 px-2 py-1.5 rounded-md text-[10px] font-medium transition-all ${+ className={`flex items-center gap-1.5 px-2 py-2 sm:py-1.5 rounded-md text-[10px] font-medium transition-all ${isActive? "bg-[var(--color-accent-primary)]/15 text-[var(--color-accent-primary)]": "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-overlay)]"@@ -255,7 +265,7 @@ export const GraphToolbar = memo(function GraphToolbar({<buttonkey={f.id}onClick={() => setNodeFilter(f.id)}- className={`flex items-center gap-1 px-2 py-1 rounded-md text-[10px] font-medium transition-all ${+ className={`flex items-center gap-1 px-2 py-2 sm:py-1 rounded-md text-[10px] font-medium transition-all ${isActive? "bg-[var(--color-accent-graph)]/15 text-[var(--color-accent-graph)]": "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-overlay)]"@@ -298,7 +308,7 @@ export const GraphToolbar = memo(function GraphToolbar({<buttonkey={m.id}onClick={() => onLayoutModeChange(m.id)}- className={`flex items-center gap-1 px-2 py-1 rounded-md text-[10px] font-medium transition-all ${+ className={`flex items-center gap-1 px-2 py-2 sm:py-1 rounded-md text-[10px] font-medium transition-all ${isActive? "bg-[var(--color-accent-graph)]/15 text-[var(--color-accent-graph)]": "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-overlay)]"@@ -322,7 +332,7 @@ export const GraphToolbar = memo(function GraphToolbar({<buttonkey={m.id}onClick={() => onColorModeChange(m.id)}- className={`flex items-center gap-1 px-2 py-1 rounded-md text-[10px] font-medium transition-all ${+ className={`flex items-center gap-1 px-2 py-2 sm:py-1 rounded-md text-[10px] font-medium transition-all ${isActive? "bg-[var(--color-accent-graph)]/15 text-[var(--color-accent-graph)]": "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-overlay)]"@@ -342,7 +352,7 @@ export const GraphToolbar = memo(function GraphToolbar({size="sm"variant="ghost"onClick={() => onGraphThemeChange(graphTheme === "light" ? "dark" : "light")}- className={`h-7 w-7 p-0 ${graphTheme === "dark" ? "text-[var(--color-accent-graph)]" : "text-[var(--color-text-tertiary)]"}`}+ className={`h-8 w-8 sm:h-7 sm:w-7 p-0 ${graphTheme === "dark" ? "text-[var(--color-accent-graph)]" : "text-[var(--color-text-tertiary)]"}`}title={graphTheme === "dark" ? "Light graph theme" : "Dark graph theme"}aria-label={graphTheme === "dark" ? "Light graph theme" : "Dark graph theme"}aria-pressed={graphTheme === "dark"}@@ -356,7 +366,7 @@ export const GraphToolbar = memo(function GraphToolbar({size="sm"variant="ghost"onClick={onTogglePathFinder}- className={`h-7 w-7 p-0 ${showPathFinder ? "text-[var(--color-accent-graph)]" : "text-[var(--color-text-tertiary)]"}`}+ className={`h-8 w-8 sm:h-7 sm:w-7 p-0 ${showPathFinder ? "text-[var(--color-accent-graph)]" : "text-[var(--color-text-tertiary)]"}`}title="Find dependency path"aria-label="Find dependency path"aria-pressed={showPathFinder}@@ -369,7 +379,7 @@ export const GraphToolbar = memo(function GraphToolbar({size="sm"variant="ghost"onClick={onToggleFlows}- className={`h-7 w-7 p-0 ${showFlows ? "text-[var(--color-accent-graph)]" : "text-[var(--color-text-tertiary)]"}`}+ className={`h-8 w-8 sm:h-7 sm:w-7 p-0 ${showFlows ? "text-[var(--color-accent-graph)]" : "text-[var(--color-text-tertiary)]"}`}title="Execution flows"aria-label="Execution flows"aria-pressed={showFlows}@@ -377,12 +387,33 @@ export const GraphToolbar = memo(function GraphToolbar({<Workflow className="w-3.5 h-3.5" /></Button>)}+ {activeScope === "modules" && onShowExternalsChange && (externalCount ?? 0) > 0 && (+ <Button+ size="sm"+ variant="ghost"+ onClick={() => onShowExternalsChange(!showExternals)}+ className={`h-8 w-8 sm:h-7 sm:w-7 p-0 ${showExternals ? "text-[var(--color-accent-graph)]" : "text-[var(--color-text-tertiary)]"}`}+ title={+ showExternals+ ? `Hide ${externalCount} external dependencies`+ : `Show ${externalCount} external dependencies`+ }+ aria-label={+ showExternals+ ? "Hide external dependencies"+ : "Show external dependencies"+ }+ aria-pressed={showExternals}+ >+ <Package className="w-3.5 h-3.5" />+ </Button>+ )}{!isConstellation && (<Buttonsize="sm"variant="ghost"onClick={() => onHideTestsChange(!hideTests)}- className={`h-7 w-7 p-0 ${hideTests ? "text-[var(--color-accent-graph)]" : "text-[var(--color-text-tertiary)]"}`}+ className={`h-8 w-8 sm:h-7 sm:w-7 p-0 ${hideTests ? "text-[var(--color-accent-graph)]" : "text-[var(--color-text-tertiary)]"}`}title={hideTests ? "Show test files" : "Hide test files"}aria-label={hideTests ? "Show test files" : "Hide test files"}aria-pressed={hideTests}@@ -394,7 +425,7 @@ export const GraphToolbar = memo(function GraphToolbar({size="sm"variant="ghost"onClick={onFitView}- className="h-7 w-7 p-0 text-[var(--color-text-tertiary)]"+ className="h-8 w-8 sm:h-7 sm:w-7 p-0 text-[var(--color-text-tertiary)]"title="Fit view"aria-label="Fit view">@@ -405,7 +436,7 @@ export const GraphToolbar = memo(function GraphToolbar({size="sm"variant="ghost"onClick={onToggleHelp}- className="h-7 w-7 p-0 text-[var(--color-text-tertiary)]"+ className="h-8 w-8 sm:h-7 sm:w-7 p-0 text-[var(--color-text-tertiary)]"title="Keyboard shortcuts (?)"aria-label="Keyboard shortcuts">diff --git a/packages/ui/src/graph/sigma/constants.ts b/packages/ui/src/graph/sigma/constants.tsindex 3dc717292..7334f3b6b 100644--- a/packages/ui/src/graph/sigma/constants.ts+++ b/packages/ui/src/graph/sigma/constants.ts@@ -125,6 +125,21 @@ export function getLayoutDuration(nodeCount: number): number {return 8000;}+// ---- Synchronous pre-settle (small graphs: settle before first paint) ----++/** Above this, settling synchronously would risk a main-thread jank — the+ * animated FA2 worker takes over instead. */+export const PRESETTLE_MAX_NODES = 800;++/** Sync FA2 iteration budget, scaled down as graphs grow. ~400 iterations on+ * a 100-node module graph runs in a few ms; 120 on an 800-node expansion+ * stays well under a frame budget with Barnes-Hut on. */+export function getPresettleIterations(nodeCount: number): number {+ if (nodeCount <= 150) return 400;+ if (nodeCount <= 400) return 250;+ return 120;+}+// ---- Noverlap post-layout settings ----export const NOVERLAP_SETTINGS = {diff --git a/packages/ui/src/graph/sigma/graphology-adapter.ts b/packages/ui/src/graph/sigma/graphology-adapter.tsindex def7ec450..4d3da1a71 100644--- a/packages/ui/src/graph/sigma/graphology-adapter.ts+++ b/packages/ui/src/graph/sigma/graphology-adapter.ts@@ -8,12 +8,17 @@ import type {ModuleEdge,CommunitySummaryItem,} from "@repowise-dev/types/graph";+import forceAtlas2 from "graphology-layout-forceatlas2";+import noverlap from "graphology-layout-noverlap";import type { SigmaNodeAttributes, SigmaEdgeAttributes } from "./types";import {NODE_BASE_SIZES,EDGE_COLORS,EDGE_SIZE_MULTIPLIERS,CURVED_EDGE_THRESHOLD,+ PRESETTLE_MAX_NODES,+ getFA2Settings,+ getPresettleIterations,getScaledNodeSize,getNodeMass,languageColor,@@ -282,7 +287,9 @@ function* buildFileGraph(const edgeAttrs: SigmaEdgeAttributes = {size: computeEdgeSize(edgeKind, nodeCount),color: EDGE_COLORS[edgeKind],- type: useCurved ? "curved" : "line",+ // Directed arrowheads under the curved threshold; big graphs keep the+ // cheaper line program.+ type: useCurved ? "curvedArrow" : "line",curvature: useCurved ? computeEdgeCurvature(edgeKey) : 0,edgeKind,importedNames: link.imported_names,@@ -299,30 +306,45 @@ function* buildFileGraph(return result;}+/** External-dependency module ids share the platform-wide `external:` prefix. */+export function isExternalModuleId(id: string): boolean {+ return id.startsWith("external:");+}+export function moduleGraphToGraphology(graph: ModuleGraph,options?: {communities?: CommunitySummaryItem[];nodeCount?: number;+ /** Drop `external:*` dependency modules (and their edges) so the repo's+ * own structure defines the layout extent. */+ hideExternals?: boolean;},): Graph<SigmaNodeAttributes, SigmaEdgeAttributes> {const result = new Graph<SigmaNodeAttributes, SigmaEdgeAttributes>();- const nodeCount = options?.nodeCount ?? graph.nodes.length;-- // Build community lookup: map module_id to community_id+ const nodes = options?.hideExternals+ ? graph.nodes.filter((n) => !isExternalModuleId(n.module_id))+ : graph.nodes;+ const nodeCount = options?.nodeCount ?? nodes.length;++ // Build community lookup: map module_id to community_id. For each community,+ // check each path-prefix of its top_file against the module-id set —+ // O(C × depth) instead of the old O(C × M) nested scan.const moduleCommunity = new Map<string, number>();if (options?.communities) {+ const moduleIds = new Set(nodes.map((n) => n.module_id));for (const community of options.communities) {- for (const mod of graph.nodes) {- if (community.top_file === mod.module_id ||- community.top_file.startsWith(mod.module_id + "/")) {- moduleCommunity.set(mod.module_id, community.community_id);+ const parts = community.top_file.split("/");+ for (let depth = 1; depth <= parts.length; depth++) {+ const prefix = parts.slice(0, depth).join("/");+ if (moduleIds.has(prefix)) {+ moduleCommunity.set(prefix, community.community_id);}}}}// Fill in missing modules with deterministic hash- for (const mod of graph.nodes) {+ for (const mod of nodes) {if (!moduleCommunity.has(mod.module_id)) {moduleCommunity.set(mod.module_id, simpleHash(mod.module_id) % 24);}@@ -330,7 +352,7 @@ export function moduleGraphToGraphology(// Group modules by community for warm-start positioningconst communityModules = new Map<number, ModuleNode[]>();- for (const mod of graph.nodes) {+ for (const mod of nodes) {const cid = moduleCommunity.get(mod.module_id) ?? 0;const list = communityModules.get(cid) ?? [];list.push(mod);@@ -356,8 +378,11 @@ export function moduleGraphToGraphology(const centroidY = (row - (Math.ceil(communityCount / cols) - 1) / 2) * cellSize;for (const mod of members) {- const x = centroidX + (Math.random() - 0.5) * jitter;- const y = centroidY + (Math.random() - 0.5) * jitter;+ // Deterministic per-module jitter (id hash) so the layout is stable+ // across mounts and rebuilds — no Math.random layout churn.+ const hash = simpleHash(mod.module_id);+ const x = centroidX + ((hash % 1000) / 1000 - 0.5) * jitter;+ const y = centroidY + (((hash >> 10) % 1000) / 1000 - 0.5) * jitter;const baseSize = getScaledNodeSize(NODE_BASE_SIZES.module, nodeCount);const size = baseSize * (0.5 + Math.min(Math.log2(Math.max(mod.file_count, 1)) * 0.3, 1.5));@@ -384,6 +409,10 @@ export function moduleGraphToGraphology(fileCount: mod.file_count,avgPagerank: mod.avg_pagerank,docCoveragePct: mod.doc_coverage_pct,+ hotspotCount: mod.hotspot_count ?? 0,+ deadCount: mod.dead_count ?? 0,+ hasDecision: mod.has_decision ?? false,+ primaryOwner: mod.primary_owner ?? null,dominantCommunityId: communityId,mass: getNodeMass("module", nodeCount),originalColor: color,@@ -411,7 +440,9 @@ export function moduleGraphToGraphology(EDGE_SIZE_MULTIPLIERS[edgeKind] *(1 + Math.log2(edge.edge_count)),color: EDGE_COLORS[edgeKind],- type: "curved",+ // Arrowhead points at the imported module — direction is the whole+ // point of a dependency edge.+ type: "curvedArrow",curvature: computeEdgeCurvature(edgeKey),edgeKind,importedNames: [],@@ -422,6 +453,35 @@ export function moduleGraphToGraphology(return result;}+/**+ * Synchronously settle a small graph with FA2 + noverlap so the FIRST painted+ * frame is the final layout — no visible "expand then collapse into a blob"+ * convergence animation, no FA2 worker spin-up. Marks the graph `presettled`+ * so use-fa2-layout skips its auto-run (the manual layout toggle still works).+ *+ * No-ops above PRESETTLE_MAX_NODES: large graphs keep the animated worker+ * layout, which stays off the main thread.+ */+export function settleGraph(+ graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes>,+): Graph<SigmaNodeAttributes, SigmaEdgeAttributes> {+ if (graph.order === 0 || graph.order > PRESETTLE_MAX_NODES) return graph;+ const settings = {+ ...forceAtlas2.inferSettings(graph),+ ...getFA2Settings(graph.order),+ };+ forceAtlas2.assign(graph, {+ iterations: getPresettleIterations(graph.order),+ settings,+ });+ noverlap.assign(graph, {+ maxIterations: 60,+ settings: { ratio: 1.1, margin: 6, expansion: 1.1 },+ });+ graph.setAttribute("presettled", true);+ return graph;+}+export function groupFilesAsModules(graph: GraphExport,options?: { prefix?: string },diff --git a/packages/ui/src/graph/sigma/types.ts b/packages/ui/src/graph/sigma/types.tsindex 72db32f66..234cda375 100644--- a/packages/ui/src/graph/sigma/types.ts+++ b/packages/ui/src/graph/sigma/types.ts@@ -74,8 +74,10 @@ export interface SigmaEdgeAttributes {size: number;color: string;- // Sigma edge program type ("curved" for small graphs, "line" for large)- type: "curved" | "line";+ // Sigma edge program type: directed "curvedArrow" for small dependency+ // graphs, plain "line" for large ones; "curved"/"arrow" kept for surfaces+ // where arrowheads are meaningless (constellation) or curves too costly.+ type: "curved" | "curvedArrow" | "arrow" | "line";// Random curvature for visual variety (0.12-0.20)curvature: number;diff --git a/packages/ui/src/graph/sigma/use-fa2-layout.ts b/packages/ui/src/graph/sigma/use-fa2-layout.tsindex 6d1d08519..3c7b88770 100644--- a/packages/ui/src/graph/sigma/use-fa2-layout.ts+++ b/packages/ui/src/graph/sigma/use-fa2-layout.ts@@ -32,9 +32,12 @@ export function useFA2Layout(const [isRunning, setIsRunning] = useState(false);const convergenceIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);+ const releaseCameraTrackingRef = useRef<(() => void) | null>(null);const killLayout = useCallback(() => {cancelledRef.current = true;+ releaseCameraTrackingRef.current?.();+ releaseCameraTrackingRef.current = null;if (layoutTimeoutRef.current) {clearTimeout(layoutTimeoutRef.current);layoutTimeoutRef.current = null;@@ -54,6 +57,25 @@ export function useFA2Layout(killLayout();cancelledRef.current = false;+ // Track whether the user touches the camera while the layout runs — if+ // they haven't, re-fit the view when it finishes so the converged graph+ // never ends up as a small cluster under a stale wide framing.+ let userMovedCamera = false;+ const markMoved = () => {+ userMovedCamera = true;+ };+ const layoutContainer = options.sigma?.getContainer();+ layoutContainer?.addEventListener("pointerdown", markMoved);+ layoutContainer?.addEventListener("wheel", markMoved, { passive: true });+ const releaseCameraTracking = () => {+ layoutContainer?.removeEventListener("pointerdown", markMoved);+ layoutContainer?.removeEventListener("wheel", markMoved);+ if (releaseCameraTrackingRef.current === releaseCameraTracking) {+ releaseCameraTrackingRef.current = null;+ }+ };+ releaseCameraTrackingRef.current = releaseCameraTracking;+(async () => {const [{ default: FA2Layout }, { default: forceAtlas2 }] =await Promise.all([@@ -89,6 +111,12 @@ export function useFA2Layout();noverlap.assign(graph, NOVERLAP_SETTINGS);options.sigma?.refresh();+ // Re-frame the converged layout — but never yank a camera the user+ // has already panned or zoomed.+ if (!userMovedCamera) {+ options.sigma?.getCamera().animatedReset({ duration: 300 });+ }+ releaseCameraTracking();setIsRunning(false);};@@ -141,9 +169,16 @@ export function useFA2Layout([killLayout, options.sigma],);- // Start layout when enabled and graph is ready+ // Start layout when enabled and graph is ready. Graphs the adapter already+ // settled synchronously (see settleGraph) skip the auto-run — their first+ // frame IS the final layout; the manual toggle below can still start FA2.useEffect(() => {- if (options.enabled && options.graph && options.graph.order > 0) {+ if (+ options.enabled &&+ options.graph &&+ options.graph.order > 0 &&+ !options.graph.getAttribute("presettled")+ ) {runLayout(options.graph);} else {killLayout();diff --git a/packages/ui/src/graph/sigma/use-sigma.ts b/packages/ui/src/graph/sigma/use-sigma.tsindex c56599d75..a6ed3d477 100644--- a/packages/ui/src/graph/sigma/use-sigma.ts+++ b/packages/ui/src/graph/sigma/use-sigma.ts@@ -102,16 +102,27 @@ function makeDrawNodeHover(graphTheme: "light" | "dark"): NodeLabelDrawingFuncticonst extra = data as Record<string, unknown>;const fullPath = (extra.fullPath as string) ?? undefined;- // Hub tooltip: a small surface card with member count, doc %, langs.- if (extra.nodeType === "hub") {+ // Hub/module tooltip: a small surface card. First disclosure layer —+ // headline stats only; the full detail lives in the inspection panel.+ if (extra.nodeType === "hub" || extra.nodeType === "module") {const font = settings.labelFont || "JetBrains Mono, monospace";- const members = (extra.memberCount as number) ?? 0;const docPct = Math.round(((extra.docCoveragePct as number) ?? 0) * 100);- const langs = ((extra.languages as string[]) ?? []).slice(0, 3).join(", ");- const lines: string[] = [- `${members} file${members === 1 ? "" : "s"} · ${docPct}% documented`,- ];- if (langs) lines.push(langs);+ const lines: string[] = [];+ if (extra.nodeType === "hub") {+ const members = (extra.memberCount as number) ?? 0;+ lines.push(`${members} file${members === 1 ? "" : "s"} · ${docPct}% documented`);+ const langs = ((extra.languages as string[]) ?? []).slice(0, 3).join(", ");+ if (langs) lines.push(langs);+ } else {+ const files = (extra.fileCount as number) ?? 0;+ lines.push(`${files} file${files === 1 ? "" : "s"} · ${docPct}% documented`);+ const hot = (extra.hotspotCount as number) ?? 0;+ const dead = (extra.deadCount as number) ?? 0;+ const issues: string[] = [];+ if (hot > 0) issues.push(`${hot} hotspot${hot === 1 ? "" : "s"}`);+ if (dead > 0) issues.push(`${dead} dead file${dead === 1 ? "" : "s"}`);+ if (issues.length > 0) lines.push(issues.join(" · "));+ }const titleSize = (settings.labelSize || 11) + 1;const lineSize = 9;@@ -430,7 +441,12 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {return { ...attrs, color };}if (cm === "language") {- color = languageColor(attrs.language || "other");+ // 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+ : languageColor(attrs.language || "other");} else if (cm === "community") {// Modules (centroids) get the hub hue; files use the softer satellite// tint so leaves recede behind their community's anchor.@@ -497,14 +513,17 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {let sigmaInstance: Sigma | null = null;(async () => {- const [{ default: SigmaConstructor }, { default: EdgeCurveProgram }, sigmaRendering, graphologyModule] =+ const [{ default: SigmaConstructor }, edgeCurveModule, sigmaRendering, graphologyModule] =await Promise.all([import("sigma"),import("@sigma/edge-curve"),import("sigma/rendering"),import("graphology"),]);+ const EdgeCurveProgram = edgeCurveModule.default;+ const EdgeCurvedArrowProgram = edgeCurveModule.EdgeCurvedArrowProgram;const EdgeLineProgram = sigmaRendering.EdgeLineProgram;+ const EdgeArrowProgram = sigmaRendering.EdgeArrowProgram;const drawDiscNodeLabel = sigmaRendering.drawDiscNodeLabel;drawDiscRef.current = drawDiscNodeLabel;@@ -527,6 +546,8 @@ export function useSigmaRenderer(options: UseSigmaOptions): UseSigmaReturn {defaultEdgeType: "curved",edgeProgramClasses: {curved: EdgeCurveProgram,+ curvedArrow: EdgeCurvedArrowProgram,+ arrow: EdgeArrowProgram,line: EdgeLineProgram,},minCameraRatio: 0.002,