Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

Replace D3 canvas graph with React Flow + ELK.js

RaghavChamadiyaf957dac6c3cc
diff --git a/package-lock.json b/package-lock.json
index dc262abd4..c6d7e3043 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -3759,6 +3759,38 @@
"d3-transition": "^3.0.1"
}
},
+ "node_modules/@xyflow/react": {
+ "version": "12.10.2",
+ "resolved": "https://registry.npmjs.org/@xyflow/react/-/react-12.10.2.tgz",
+ "integrity": "sha512-CgIi6HwlcHXwlkTpr0fxLv/0sRVNZ8IdwKLzzeCscaYBwpvfcH1QFOCeaTCuEn1FQEs/B8CjnTSjhs8udgmBgQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@xyflow/system": "0.0.76",
+ "classcat": "^5.0.3",
+ "zustand": "^4.4.0"
+ },
+ "peerDependencies": {
+ "react": ">=17",
+ "react-dom": ">=17"
+ }
+ },
+ "node_modules/@xyflow/system": {
+ "version": "0.0.76",
+ "resolved": "https://registry.npmjs.org/@xyflow/system/-/system-0.0.76.tgz",
+ "integrity": "sha512-hvwvnRS1B3REwVDlWexsq7YQaPZeG3/mKo1jv38UmnpWmxihp14bW6VtEOuHEwJX2FvzFw8k77LyKSk/wiZVNA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-drag": "^3.0.7",
+ "@types/d3-interpolate": "^3.0.4",
+ "@types/d3-selection": "^3.0.10",
+ "@types/d3-transition": "^3.0.8",
+ "@types/d3-zoom": "^3.0.8",
+ "d3-drag": "^3.0.0",
+ "d3-interpolate": "^3.0.1",
+ "d3-selection": "^3.0.0",
+ "d3-zoom": "^3.0.0"
+ }
+ },
"node_modules/acorn": {
"version": "8.16.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
@@ -4290,6 +4322,12 @@
"url": "https://polar.sh/cva"
}
},
+ "node_modules/classcat": {
+ "version": "5.0.5",
+ "resolved": "https://registry.npmjs.org/classcat/-/classcat-5.0.5.tgz",
+ "integrity": "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==",
+ "license": "MIT"
+ },
"node_modules/client-only": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz",
@@ -5165,6 +5203,12 @@
"node": ">= 0.4"
}
},
+ "node_modules/elkjs": {
+ "version": "0.11.1",
+ "resolved": "https://registry.npmjs.org/elkjs/-/elkjs-0.11.1.tgz",
+ "integrity": "sha512-zxxR9k+rx5ktMwT/FwyLdPCrq7xN6e4VGGHH8hA01vVYKjTFik7nHOxBnAYtrgYUB1RpAiLvA1/U2YraWxyKKg==",
+ "license": "EPL-2.0"
+ },
"node_modules/emoji-regex": {
"version": "9.2.2",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
@@ -11422,6 +11466,34 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/zustand": {
+ "version": "4.5.7",
+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",
+ "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",
+ "license": "MIT",
+ "dependencies": {
+ "use-sync-external-store": "^1.2.2"
+ },
+ "engines": {
+ "node": ">=12.7.0"
+ },
+ "peerDependencies": {
+ "@types/react": ">=16.8",
+ "immer": ">=9.0.6",
+ "react": ">=16.8"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "immer": {
+ "optional": true
+ },
+ "react": {
+ "optional": true
+ }
+ }
+ },
"node_modules/zwitch": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",
@@ -11452,12 +11524,14 @@
"@radix-ui/react-toggle": "^1.1.0",
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.0",
+ "@xyflow/react": "^12.10.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"d3": "^7.9.0",
"d3-force": "^3.0.0",
"d3-hierarchy": "^3.1.2",
+ "elkjs": "^0.11.1",
"framer-motion": "^11.11.0",
"fuse.js": "^7.0.0",
"geist": "^1.3.0",
diff --git a/packages/server/src/repowise/server/routers/graph.py b/packages/server/src/repowise/server/routers/graph.py
index a594a178f..b68f14ec5 100644
--- a/packages/server/src/repowise/server/routers/graph.py
+++ b/packages/server/src/repowise/server/routers/graph.py
@@ -50,6 +50,14 @@ def _parse_imported_names(raw: str | None) -> list[str]:
return []
+async def _get_documented_paths(session: AsyncSession, repo_id: str) -> set[str]:
+ """Return the set of node_ids (file paths) that have a wiki page."""
+ result = await session.execute(
+ select(Page.target_path).where(Page.repository_id == repo_id)
+ )
+ return {row.target_path for row in result.all() if row.target_path}
+
+
# ---------------------------------------------------------------------------
# Module graph
# ---------------------------------------------------------------------------
@@ -204,6 +212,8 @@ async def ego_graph(
git_row = git_result.scalar_one_or_none()
git_meta = GitMetadataResponse.from_orm(git_row) if git_row else None
+ documented = await _get_documented_paths(session, repo_id)
+
node_responses = [
GraphNodeResponse(
node_id=n.node_id,
@@ -215,6 +225,7 @@ async def ego_graph(
community_id=n.community_id,
is_test=n.is_test,
is_entry_point=n.is_entry_point,
+ has_doc=n.node_id in documented,
)
for n in node_rows
]
@@ -284,6 +295,8 @@ async def entry_points_graph(
)
nodes = node_result.scalars().all()
+ documented = await _get_documented_paths(session, repo_id)
+
node_responses = [
GraphNodeResponse(
node_id=n.node_id,
@@ -295,6 +308,7 @@ async def entry_points_graph(
community_id=n.community_id,
is_test=n.is_test,
is_entry_point=n.is_entry_point,
+ has_doc=n.node_id in documented,
)
for n in nodes
]
@@ -383,6 +397,7 @@ async def dead_code_graph(
neighbor_nodes = []
all_node_ids = dead_node_ids | neighbor_ids
+ documented = await _get_documented_paths(session, repo_id)
def _to_dead_node(n: GraphNode, confidence_group: str) -> DeadCodeGraphNodeResponse:
return DeadCodeGraphNodeResponse(
@@ -395,6 +410,7 @@ async def dead_code_graph(
community_id=n.community_id,
is_test=n.is_test,
is_entry_point=n.is_entry_point,
+ has_doc=n.node_id in documented,
confidence_group=confidence_group,
)
@@ -493,6 +509,7 @@ async def hot_files_graph(
neighbor_nodes = []
all_node_ids = hot_node_ids | neighbor_ids
+ documented = await _get_documented_paths(session, repo_id)
def _to_hot_node(n: GraphNode, commit_count: int) -> HotFilesNodeResponse:
return HotFilesNodeResponse(
@@ -505,6 +522,7 @@ async def hot_files_graph(
community_id=n.community_id,
is_test=n.is_test,
is_entry_point=n.is_entry_point,
+ has_doc=n.node_id in documented,
commit_count=commit_count,
)
@@ -581,6 +599,8 @@ async def export_graph(
)
edges = edge_result.scalars().all()
+ documented = await _get_documented_paths(session, repo_id)
+
node_responses = [
GraphNodeResponse(
node_id=n.node_id,
@@ -592,6 +612,7 @@ async def export_graph(
community_id=n.community_id,
is_test=n.is_test,
is_entry_point=n.is_entry_point,
+ has_doc=n.node_id in documented,
)
for n in nodes
]
diff --git a/packages/server/src/repowise/server/schemas.py b/packages/server/src/repowise/server/schemas.py
index 8b85f268c..b925102c0 100644
--- a/packages/server/src/repowise/server/schemas.py
+++ b/packages/server/src/repowise/server/schemas.py
@@ -263,6 +263,7 @@ class GraphNodeResponse(BaseModel):
community_id: int
is_test: bool = False
is_entry_point: bool = False
+ has_doc: bool = False
class GraphEdgeResponse(BaseModel):
@@ -478,6 +479,7 @@ class DeadCodeGraphNodeResponse(BaseModel):
community_id: int
is_test: bool = False
is_entry_point: bool = False
+ has_doc: bool = False
confidence_group: str # "certain" | "likely"
@@ -501,6 +503,7 @@ class HotFilesNodeResponse(BaseModel):
community_id: int
is_test: bool = False
is_entry_point: bool = False
+ has_doc: bool = False
commit_count: int
diff --git a/packages/web/package.json b/packages/web/package.json
index d5ea35850..e7a4974f8 100644
--- a/packages/web/package.json
+++ b/packages/web/package.json
@@ -27,12 +27,14 @@
"@radix-ui/react-toggle": "^1.1.0",
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.0",
+ "@xyflow/react": "^12.10.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"d3": "^7.9.0",
"d3-force": "^3.0.0",
"d3-hierarchy": "^3.1.2",
+ "elkjs": "^0.11.1",
"framer-motion": "^11.11.0",
"fuse.js": "^7.0.0",
"geist": "^1.3.0",
diff --git a/packages/web/src/app/repos/[id]/graph/page.tsx b/packages/web/src/app/repos/[id]/graph/page.tsx
index bd9c62533..7e66a6bfb 100644
--- a/packages/web/src/app/repos/[id]/graph/page.tsx
+++ b/packages/web/src/app/repos/[id]/graph/page.tsx
@@ -1,13 +1,9 @@
"use client";
import { use, useCallback, useState } from "react";
-import { useQueryState, parseAsString, parseAsInteger } from "nuqs";
-import { GraphCanvas, type ViewMode } from "@/components/graph/graph-canvas";
-import { GraphViewSwitcher } from "@/components/graph/graph-view-switcher";
-import { GraphEgoSidebar } from "@/components/graph/graph-ego-sidebar";
+import { useQueryState } from "nuqs";
+import { GraphFlow } from "@/components/graph/graph-flow";
import { GraphDocPanel } from "@/components/graph/graph-doc-panel";
-import { useEgoGraph } from "@/lib/hooks/use-graph";
-import { searchNodes } from "@/lib/api/graph";
export default function GraphPage({
params,
@@ -16,57 +12,30 @@ export default function GraphPage({
}) {
const { id: repoId } = use(params);
- const [view, setView] = useQueryState("view", parseAsString.withDefault("module"));
- const [node, setNode] = useQueryState("node");
- const [hops, setHops] = useQueryState("hops", parseAsInteger.withDefault(2));
- const [days, setDays] = useQueryState("days", parseAsInteger.withDefault(30));
+ const [, setSelectedNode] = useQueryState("node");
const [docNodeId, setDocNodeId] = useState<string | null>(null);
- const viewMode = view as ViewMode;
-
- // Fetch ego graph data so we can show the sidebar
- const { graph: egoGraph } = useEgoGraph(
- viewMode === "ego" ? repoId : null,
- viewMode === "ego" ? node : null,
- hops,
- );
-
+ // Click a file node → open doc panel
const handleNodeClick = useCallback(
- async (nodeId: string) => {
- if (viewMode === "module") {
- try {
- // Fetch many candidates so we can pick the most representative code file
- const results = await searchNodes(repoId, nodeId + "/", 40);
- // Exclude config/doc files that have no symbols; prefer actual code
- const NON_CODE = new Set(["markdown", "json", "yaml", "toml", "text", "plaintext", "xml", "ini", ""]);
- const codeFiles = results.filter(
- (r) => !NON_CODE.has(r.language.toLowerCase()) && r.symbol_count > 0,
- );
- // Fall back to any non-doc file, then any file if nothing else
- const candidates = codeFiles.length > 0
- ? codeFiles
- : results.filter((r) => !NON_CODE.has(r.language.toLowerCase()));
- const pool = candidates.length > 0 ? candidates : results;
- // Pick the file with the most symbols (most substantive)
- const best = pool.sort((a, b) => b.symbol_count - a.symbol_count)[0];
- const targetNode = best?.node_id ?? nodeId;
- await setView("ego");
- await setNode(targetNode);
- } catch {
- await setView("ego");
- await setNode(nodeId);
- }
- } else {
- await setView("ego");
- await setNode(nodeId);
+ (nodeId: string, nodeType: string) => {
+ // Module clicks are handled inside GraphFlow (drill-down)
+ // File clicks open the doc panel
+ if (nodeType !== "moduleGroup") {
+ setDocNodeId((prev) => (prev === nodeId ? null : nodeId));
+ void setSelectedNode(nodeId);
}
},
- [viewMode, repoId, setView, setNode],
+ [setSelectedNode],
);
- const handleNodeViewDocs = useCallback((nodeId: string) => {
- setDocNodeId((prev) => (prev === nodeId ? null : nodeId));
- }, []);
+ // Double click or context menu "View Docs"
+ const handleNodeViewDocs = useCallback(
+ (nodeId: string) => {
+ setDocNodeId((prev) => (prev === nodeId ? null : nodeId));
+ void setSelectedNode(nodeId);
+ },
+ [setSelectedNode],
+ );
return (
<div className="flex flex-col h-screen">
@@ -76,51 +45,20 @@ export default function GraphPage({
Dependency Graph
</h1>
<p className="text-xs text-[var(--color-text-secondary)] mt-0.5">
- {viewMode === "module" && "Module overview — click a node to explore its neighborhood"}
- {viewMode === "ego" && `Neighborhood of ${node ?? "…"}`}
- {viewMode === "architecture" && "Entry-point reachable subgraph (3 hops)"}
- {viewMode === "dead" && "Dead code — unreachable files and unused exports"}
- {viewMode === "hotfiles" && `Most-committed files (${days}d)`}
- {viewMode === "full" && "Full dependency graph — scroll to zoom, drag to pan"}
+ Explore dependencies and trace paths between files
</p>
</div>
- {/* View switcher */}
- <GraphViewSwitcher
- repoId={repoId}
- view={viewMode}
- hops={hops}
- days={days}
- onViewChange={(v) => void setView(v)}
- onNodeSelect={(nodeId) => void handleNodeClick(nodeId)}
- onHopsChange={(h) => void setHops(h)}
- onDaysChange={(d) => void setDays(d)}
- />
-
- {/* Canvas area */}
+ {/* Graph area */}
<div className="flex-1 overflow-hidden p-3">
<div className="h-full w-full rounded-lg border border-[var(--color-border-default)] overflow-hidden relative">
- <GraphCanvas
+ <GraphFlow
repoId={repoId}
- viewMode={viewMode}
- centerNodeId={node}
- hops={hops}
- days={days}
- onNodeClick={(nodeId) => void handleNodeClick(nodeId)}
+ onNodeClick={handleNodeClick}
onNodeViewDocs={handleNodeViewDocs}
- onViewChange={(v) => void setView(v)}
/>
- {/* Ego sidebar */}
- {viewMode === "ego" && egoGraph && !docNodeId && (
- <GraphEgoSidebar
- graph={egoGraph}
- onClose={() => void setView("module")}
- onNavigateToNode={(nodeId) => void setNode(nodeId)}
- />
- )}
-
- {/* Doc panel */}
+ {/* Doc panel — shows on file click */}
{docNodeId && (
<GraphDocPanel
repoId={repoId}
diff --git a/packages/web/src/components/graph/edges/dependency-edge.tsx b/packages/web/src/components/graph/edges/dependency-edge.tsx
new file mode 100644
index 000000000..44c1d7ca9
--- /dev/null
+++ b/packages/web/src/components/graph/edges/dependency-edge.tsx
@@ -0,0 +1,94 @@
+"use client";
+
+import { memo, useContext } from "react";
+import {
+ getSmoothStepPath,
+ EdgeLabelRenderer,
+ type EdgeProps,
+} from "@xyflow/react";
+import { GraphContext } from "../graph-flow";
+import type { DependencyEdgeData } from "../elk-layout";
+
+function DependencyEdgeInner({
+ id,
+ sourceX,
+ sourceY,
+ targetX,
+ targetY,
+ sourcePosition,
+ targetPosition,
+ data,
+}: EdgeProps) {
+ const d = (data ?? { importedNames: [], edgeCount: 1 }) as DependencyEdgeData;
+ const ctx = useContext(GraphContext);
+
+ const edgeKey = id;
+ const isOnPath = ctx.highlightedEdges.has(edgeKey);
+ const hasActivePath = ctx.highlightedPath.size > 0;
+ const isDimmed = hasActivePath && !isOnPath;
+ const isDynamic = d.importedNames.length === 0;
+
+ const [edgePath, labelX, labelY] = getSmoothStepPath({
+ sourceX,
+ sourceY,
+ targetX,
+ targetY,
+ sourcePosition,
+ targetPosition,
+ borderRadius: 12,
+ });
+
+ const strokeWidth = Math.max(1, Math.min(4, 1 + Math.sqrt(d.edgeCount) * 0.5));
+
+ let stroke: string;
+ let opacity: number;
+ let dashArray: string | undefined;
+ let animation: string | undefined;
+
+ if (isOnPath) {
+ stroke = "var(--color-accent-graph)";
+ opacity = 1;
+ dashArray = "6 4";
+ animation = "graph-marching-ants 0.6s linear infinite";
+ } else if (isDimmed) {
+ stroke = "rgba(91, 156, 246, 0.15)";
+ opacity = 0.3;
+ } else if (isDynamic) {
+ stroke = "rgba(150, 150, 150, 0.5)";
+ opacity = 0.4;
+ dashArray = "4 4";
+ } else {
+ stroke = "rgba(91, 156, 246, 0.35)";
+ opacity = 0.6;
+ }
+
+ return (
+ <>
+ <path
+ d={edgePath}
+ fill="none"
+ stroke={stroke}
+ strokeWidth={strokeWidth}
+ strokeOpacity={opacity}
+ strokeDasharray={dashArray}
+ style={{ animation }}
+ className="transition-all duration-300"
+ />
+ {d.edgeCount > 1 && !isDimmed && (
+ <EdgeLabelRenderer>
+ <div
+ className="nodrag nopan pointer-events-none absolute rounded-full bg-[var(--color-bg-elevated)] border border-[var(--color-border-default)] px-1.5 py-0.5 text-[9px] font-medium text-[var(--color-text-tertiary)] tabular-nums"
+ style={{
+ transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)`,
+ opacity: isDimmed ? 0.15 : 0.8,
+ }}
+ >
+ {d.edgeCount}
+ </div>
+ </EdgeLabelRenderer>
+ )}
+ </>
+ );
+}
+
+export const DependencyEdge = memo(DependencyEdgeInner);
diff --git a/packages/web/src/components/graph/elk-layout.ts b/packages/web/src/components/graph/elk-layout.ts
new file mode 100644
index 000000000..3f48c0eda
--- /dev/null
+++ b/packages/web/src/components/graph/elk-layout.ts
@@ -0,0 +1,491 @@
+/**
+ * ELK layout engine — transforms graph API data into React Flow nodes/edges.
+ *
+ * Uses elkjs for deterministic hierarchical layout with compound nodes
+ * representing directories.
+ */
+
+import ELK from "elkjs/lib/elk.bundled.js";
+import type { ElkNode, ElkExtendedEdge } from "elkjs";
+import type { Node, Edge } from "@xyflow/react";
+import type {
+ GraphNodeResponse,
+ GraphEdgeResponse,
+ ModuleNodeResponse,
+ ModuleEdgeResponse,
+} from "@/lib/api/types";
+
+// ---- Constants ----
+
+const MODULE_NODE_WIDTH = 200;
+const MODULE_NODE_HEIGHT = 60;
+const FILE_NODE_WIDTH = 160;
+const FILE_NODE_HEIGHT = 40;
+
+const elk = new ELK();
+
+// ---- Types ----
+
+export interface FileNodeData {
+ label: string;
+ fullPath: string;
+ language: string;
+ symbolCount: number;
+ pagerank: number;
+ betweenness: number;
+ communityId: number;
+ isTest: boolean;
+ isEntryPoint: boolean;
+ hasDoc: boolean;
+ [key: string]: unknown;
+}
+
+export interface ModuleNodeData {
+ label: string;
+ fullPath: string;
+ fileCount: number;
+ symbolCount: number;
+ avgPagerank: number;
+ docCoveragePct: number;
+ /** True when this entry represents a single file, not a directory */
+ isFile?: boolean;
+ /** File-level fields (only set when isFile=true) */
+ language?: string;
+ hasDoc?: boolean;
+ isEntryPoint?: boolean;
+ isTest?: boolean;
+ [key: string]: unknown;
+}
+
+export interface DependencyEdgeData {
+ importedNames: string[];
+ edgeCount: number;
+ [key: string]: unknown;
+}
+
+// ---- Helpers ----
+
+/** Extract directory path from a file node_id (everything before the last /). */
+function dirOf(nodeId: string): string {
+ const idx = nodeId.lastIndexOf("/");
+ return idx > 0 ? nodeId.slice(0, idx) : "";
+}
+
+/** Build all ancestor directories for grouping (e.g. "src/auth/middleware" → ["src", "src/auth", "src/auth/middleware"]). */
+function ancestorDirs(dir: string): string[] {
+ if (!dir) return [];
+ const parts = dir.split("/");
+ const result: string[] = [];
+ for (let i = 0; i < parts.length; i++) {
+ result.push(parts.slice(0, i + 1).join("/"));
+ }
+ return result;
+}
+
+/** Deduplicate edges: group by (source, target) pair, merge imported_names, sum count. */
+function deduplicateEdges(
+ edges: GraphEdgeResponse[],
+): { source: string; target: string; importedNames: string[]; edgeCount: number }[] {
+ const map = new Map<
+ string,
+ { source: string; target: string; importedNames: string[]; edgeCount: number }
+ >();
+ for (const e of edges) {
+ const key = `${e.source}→${e.target}`;
+ const existing = map.get(key);
+ if (existing) {
+ existing.importedNames.push(...e.imported_names);
+ existing.edgeCount++;
+ } else {
+ map.set(key, {
+ source: e.source,
+ target: e.target,
+ importedNames: [...e.imported_names],
+ edgeCount: 1,
+ });
+ }
+ }
+ return Array.from(map.values());
+}
+
+// ---- Client-side module grouping (for drill-down) ----
+
+/**
+ * Groups file-level graph nodes into modules at the next directory level
+ * below `prefix`. Mirrors what the backend `/modules` endpoint does but
+ * scoped to a sub-tree.
+ *
+ * @param nodes All file-level nodes (from the full graph)
+ * @param edges All file-level edges
+ * @param prefix The current drill-down prefix, e.g. "packages" or "packages/web".
+ * Pass "" for the top level.
+ * @returns Module nodes and inter-module edges, ready for `layoutModuleGraph`.
+ */
+export function groupNodesAsModules(
+ nodes: GraphNodeResponse[],
+ edges: GraphEdgeResponse[],
+ prefix: string,
+): { moduleNodes: ModuleNodeResponse[]; moduleEdges: ModuleEdgeResponse[]; fileEntries: Map<string, GraphNodeResponse> } {
+ const slash = prefix ? prefix + "/" : "";
+
+ // Filter nodes under this prefix
+ const scopedNodes = prefix
+ ? nodes.filter((n) => n.node_id.startsWith(slash))
+ : nodes;
+
+ if (scopedNodes.length === 0) {
+ return { moduleNodes: [], moduleEdges: [], fileEntries: new Map() };
+ }
+
+ // Group by next path segment after the prefix
+ const modules = new Map<string, GraphNodeResponse[]>();
+ const nodeToModule = new Map<string, string>();
+
+ for (const n of scopedNodes) {
+ const rest = prefix ? n.node_id.slice(slash.length) : n.node_id;
+ const slashIdx = rest.indexOf("/");
+ const moduleId = slashIdx >= 0
+ ? (prefix ? slash + rest.slice(0, slashIdx) : rest.slice(0, slashIdx))
+ : (prefix ? slash + rest : rest); // file at this level
+
+ const list = modules.get(moduleId) ?? [];
+ list.push(n);
+ modules.set(moduleId, list);
+ nodeToModule.set(n.node_id, moduleId);
+ }
+
+ // Build module node responses
+ const moduleNodes: ModuleNodeResponse[] = [];
+ // Track which entries are single files vs directories
+ const fileEntries = new Map<string, GraphNodeResponse>();
+ for (const [moduleId, groupedNodes] of modules) {
+ const fileCount = groupedNodes.length;
+ const symbolCount = groupedNodes.reduce((s, n) => s + n.symbol_count, 0);
+ const avgPagerank =
+ groupedNodes.reduce((s, n) => s + n.pagerank, 0) / Math.max(fileCount, 1);
+ const docCount = groupedNodes.filter((n) => n.has_doc).length;
+ const docCoveragePct = docCount / Math.max(fileCount, 1);
+
+ // A "file entry" is when the module_id equals a single node's full path
+ // (i.e., it's a direct file at this level, not a subdirectory)
+ const isSingleFile = fileCount === 1 && groupedNodes[0].node_id === moduleId;
+ if (isSingleFile) {
+ fileEntries.set(moduleId, groupedNodes[0]);
+ }
+
+ moduleNodes.push({
+ module_id: moduleId,
+ file_count: fileCount,
+ symbol_count: symbolCount,
+ avg_pagerank: avgPagerank,
+ doc_coverage_pct: docCoveragePct,
+ });
+ }
+
+ // Build inter-module edges
+ const scopedNodeSet = new Set(scopedNodes.map((n) => n.node_id));
+ const edgeCounts = new Map<string, number>();
+ for (const e of edges) {
+ if (!scopedNodeSet.has(e.source) || !scopedNodeSet.has(e.target)) continue;
+ const srcModule = nodeToModule.get(e.source);
+ const tgtModule = nodeToModule.get(e.target);
+ if (srcModule && tgtModule && srcModule !== tgtModule) {
+ const key = `${srcModule}→${tgtModule}`;
+ edgeCounts.set(key, (edgeCounts.get(key) ?? 0) + 1);
+ }
+ }
+
+ const moduleEdges: ModuleEdgeResponse[] = Array.from(edgeCounts.entries()).map(
+ ([key, count]) => {
+ const [source, target] = key.split("→");
+ return { source, target, edge_count: count };
+ },
+ );
+
+ return { moduleNodes, moduleEdges, fileEntries };
+}
+
+// ---- Layout for file-level graph ----
+
+export async function layoutFileGraph(
+ nodes: GraphNodeResponse[],
+ edges: GraphEdgeResponse[],
+): Promise<{ nodes: Node[]; edges: Edge[] }> {
+ if (nodes.length === 0) return { nodes: [], edges: [] };
+
+ const nodeSet = new Set(nodes.map((n) => n.node_id));
+ const validEdges = edges.filter((e) => nodeSet.has(e.source) && nodeSet.has(e.target));
+ const dedupedEdges = deduplicateEdges(validEdges);
+
+ // Build directory hierarchy
+ const dirSet = new Set<string>();
+ for (const n of nodes) {
+ const dir = dirOf(n.node_id);
+ if (dir) {
+ for (const ancestor of ancestorDirs(dir)) {
+ dirSet.add(ancestor);
+ }
+ }
+ }
+
+ // Sort dirs so parents come before children
+ const dirs = Array.from(dirSet).sort();
+
+ // Build ELK compound graph
+ const elkGraph: ElkNode = {
+ id: "root",
+ layoutOptions: {
+ "elk.algorithm": "layered",
+ "elk.direction": "DOWN",
+ "elk.layered.spacing.nodeNodeBetweenLayers": "60",
+ "elk.layered.spacing.edgeNodeBetweenLayers": "30",
+ "elk.spacing.nodeNode": "30",
+ "elk.spacing.componentComponent": "50",
+ "elk.hierarchyHandling": "INCLUDE_CHILDREN",
+ "elk.layered.crossingMinimization.strategy": "LAYER_SWEEP",
+ "elk.padding": "[top=45,left=15,bottom=15,right=15]",
+ },
+ children: [],
+ edges: [],
+ };
+
+ // Create dir nodes as groups
+ const dirElkNodes = new Map<string, ElkNode>();
+ for (const dir of dirs) {
+ const parts = dir.split("/");
+ const label = parts[parts.length - 1];
+ const elkNode: ElkNode = {
+ id: `dir:${dir}`,
+ labels: [{ text: label }],
+ layoutOptions: {
+ "elk.padding": "[top=40,left=12,bottom=12,right=12]",
+ },
+ children: [],
+ };
+ dirElkNodes.set(dir, elkNode);
+ }
+
+ // Nest dir nodes into their parents
+ for (const dir of dirs) {
+ const parentDir = dirOf(dir);
+ const parentElk = parentDir ? dirElkNodes.get(parentDir) : null;
+ const elkNode = dirElkNodes.get(dir)!;
+ if (parentElk) {
+ parentElk.children!.push(elkNode);
+ } else {
+ elkGraph.children!.push(elkNode);
+ }
+ }
+
+ // Add file nodes
+ for (const n of nodes) {
+ const elkFileNode: ElkNode = {
+ id: n.node_id,
+ width: FILE_NODE_WIDTH,
+ height: FILE_NODE_HEIGHT,
+ labels: [{ text: n.node_id.split("/").pop() ?? n.node_id }],
+ };
+ const dir = dirOf(n.node_id);
+ const parentElk = dir ? dirElkNodes.get(dir) : null;
+ if (parentElk) {
+ parentElk.children!.push(elkFileNode);
+ } else {
+ elkGraph.children!.push(elkFileNode);
+ }
+ }
+
+ // Add edges — ELK needs hierarchical edge format
+ const elkEdges: ElkExtendedEdge[] = dedupedEdges.map((e, i) => ({
+ id: `e${i}`,
+ sources: [e.source],
+ targets: [e.target],
+ }));
+ elkGraph.edges = elkEdges;
+
+ // Compute layout
+ const layout = await elk.layout(elkGraph);
+
+ // Flatten layout into React Flow nodes
+ const rfNodes: Node[] = [];
+ const rfEdges: Edge[] = [];
+
+ function extractNodes(
+ elkNode: ElkNode,
+ parentId?: string,
+ offsetX = 0,
+ offsetY = 0,
+ ) {
+ if (!elkNode.children) return;
+ for (const child of elkNode.children) {
+ const x = (child.x ?? 0) + offsetX;
+ const y = (child.y ?? 0) + offsetY;
+ const isDir = child.id.startsWith("dir:");
+
+ if (isDir) {
+ const dirPath = child.id.slice(4);
+ const label = child.labels?.[0]?.text ?? dirPath;
+ rfNodes.push({
+ id: child.id,
+ type: "moduleGroup",
+ position: { x: child.x ?? 0, y: child.y ?? 0 },
+ ...(parentId ? { parentId, extent: "parent" as const } : {}),
+ style: {
+ width: child.width,
+ height: child.height,
+ },
+ data: {
+ label,
+ fullPath: dirPath,
+ fileCount: child.children?.filter((c) => !c.id.startsWith("dir:")).length ?? 0,
+ } satisfies Record<string, unknown>,
+ });
+ // Recurse into children
+ extractNodes(child, child.id);
+ } else {
+ const apiNode = nodes.find((n) => n.node_id === child.id);
+ if (apiNode) {
+ rfNodes.push({
+ id: child.id,
+ type: "fileNode",
+ position: { x: child.x ?? 0, y: child.y ?? 0 },
+ ...(parentId ? { parentId, extent: "parent" as const } : {}),
+ data: {
+ label: child.labels?.[0]?.text ?? apiNode.node_id,
+ fullPath: apiNode.node_id,
+ language: apiNode.language,
+ symbolCount: apiNode.symbol_count,
+ pagerank: apiNode.pagerank,
+ betweenness: apiNode.betweenness,
+ communityId: apiNode.community_id,
+ isTest: apiNode.is_test,
+ isEntryPoint: apiNode.is_entry_point,
+ hasDoc: apiNode.has_doc,
+ } satisfies FileNodeData,
+ });
+ }
+ }
+ }
+ }
+
+ extractNodes(layout);
+
+ // Build React Flow edges
+ for (const e of dedupedEdges) {
+ rfEdges.push({
+ id: `${e.source}→${e.target}`,
+ source: e.source,
+ target: e.target,
+ type: "dependency",
+ data: {
+ importedNames: e.importedNames,
+ edgeCount: e.edgeCount,
+ } satisfies DependencyEdgeData,
+ });
+ }
+
+ return { nodes: rfNodes, edges: rfEdges };
+}
+
+// ---- Layout for module-level graph ----
+
+export async function layoutModuleGraph(
+ moduleNodes: ModuleNodeResponse[],
+ moduleEdges: ModuleEdgeResponse[],
+ fileEntries?: Map<string, GraphNodeResponse>,
+): Promise<{ nodes: Node[]; edges: Edge[] }> {
+ if (moduleNodes.length === 0) return { nodes: [], edges: [] };
+
+ const elkGraph: ElkNode = {
+ id: "root",
+ layoutOptions: {
+ "elk.algorithm": "layered",
+ "elk.direction": "DOWN",
+ "elk.layered.spacing.nodeNodeBetweenLayers": "80",
+ "elk.layered.spacing.edgeNodeBetweenLayers": "40",
+ "elk.spacing.nodeNode": "40",
+ "elk.spacing.componentComponent": "60",
+ "elk.layered.crossingMinimization.strategy": "LAYER_SWEEP",
+ },
+ children: moduleNodes.map((m) => {
+ const isFile = fileEntries?.has(m.module_id) ?? false;
+ return {
+ id: m.module_id,
+ width: isFile ? FILE_NODE_WIDTH : MODULE_NODE_WIDTH,
+ height: isFile ? FILE_NODE_HEIGHT : MODULE_NODE_HEIGHT,
+ labels: [{ text: m.module_id }],
+ };
+ }),
+ edges: moduleEdges.map((e, i) => ({
+ id: `me${i}`,
+ sources: [e.source],
+ targets: [e.target],
+ })),
+ };
+
+ const layout = await elk.layout(elkGraph);
+
+ const rfNodes: Node[] = (layout.children ?? []).map((child) => {
+ const apiNode = moduleNodes.find((m) => m.module_id === child.id)!;
+ const fileEntry = fileEntries?.get(child.id);
+ const isFile = !!fileEntry;
+ const label = child.id.split("/").pop() ?? child.id;
+
+ if (isFile) {
+ // Render as a FileNode
+ return {
+ id: child.id,
+ type: "fileNode",
+ position: { x: child.x ?? 0, y: child.y ?? 0 },
+ data: {
+ label,
+ fullPath: child.id,
+ language: fileEntry.language,
+ symbolCount: fileEntry.symbol_count,
+ pagerank: fileEntry.pagerank,
+ betweenness: fileEntry.betweenness,
+ communityId: fileEntry.community_id,
+ isTest: fileEntry.is_test,
+ isEntryPoint: fileEntry.is_entry_point,
+ hasDoc: fileEntry.has_doc,
+ } satisfies FileNodeData,
+ };
+ }
+
+ return {
+ id: child.id,
+ type: "moduleGroup",
+ position: { x: child.x ?? 0, y: child.y ?? 0 },
+ data: {
+ label,
+ fullPath: child.id,
+ fileCount: apiNode.file_count,
+ symbolCount: apiNode.symbol_count,
+ avgPagerank: apiNode.avg_pagerank,
+ docCoveragePct: apiNode.doc_coverage_pct,
+ } satisfies ModuleNodeData,
+ };
+ });
+
+ // Deduplicate module edges
+ const edgeMap = new Map<string, number>();
+ for (const e of moduleEdges) {
+ const key = `${e.source}→${e.target}`;
+ edgeMap.set(key, (edgeMap.get(key) ?? 0) + e.edge_count);
+ }
+
+ const rfEdges: Edge[] = Array.from(edgeMap.entries()).map(([key, count]) => {
+ const [source, target] = key.split("→");
+ return {
+ id: key,
+ source,
+ target,
+ type: "dependency",
+ data: {
+ importedNames: [],
+ edgeCount: count,
+ } satisfies DependencyEdgeData,
+ };
+ });
+
+ return { nodes: rfNodes, edges: rfEdges };
+}
diff --git a/packages/web/src/components/graph/graph-canvas.tsx b/packages/web/src/components/graph/graph-canvas.tsx
deleted file mode 100644
index 0891f4fc8..000000000
--- a/packages/web/src/components/graph/graph-canvas.tsx
+++ /dev/null
@@ -1,806 +0,0 @@
-"use client";
-
-import { useEffect, useRef, useState, useCallback, useMemo } from "react";
-import { useRouter } from "next/navigation";
-import * as d3 from "d3";
-import type { SimulationNodeDatum, SimulationLinkDatum } from "d3-force";
-import { SlidersHorizontal, Download, Route, AlertTriangle } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { Skeleton } from "@/components/ui/skeleton";
-import { EmptyState } from "@/components/shared/empty-state";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { GraphTooltip } from "./graph-tooltip";
-import { GraphFilterPanel, type GraphFilters } from "./graph-filter-panel";
-import { GraphMinimap } from "./graph-minimap";
-import { PathFinder } from "./path-finder";
-import {
- useGraph,
- useModuleGraph,
- useEgoGraph,
- useArchitectureGraph,
- useDeadCodeGraph,
- useHotFilesGraph,
-} from "@/lib/hooks/use-graph";
-import { languageColor } from "@/lib/utils/confidence";
-import type { GraphNodeResponse } from "@/lib/api/types";
-
-export type ViewMode = "module" | "ego" | "architecture" | "dead" | "hotfiles" | "full";
-
-// Community colors palette (24 distinct colors)
-const COMMUNITY_COLORS = [
- "#6366f1","#ec4899","#10b981","#f59e0b","#3b82f6","#a855f7",
- "#14b8a6","#f97316","#84cc16","#06b6d4","#e11d48","#8b5cf6",
- "#22c55e","#eab308","#0ea5e9","#d946ef","#ef4444","#78716c",
- "#64748b","#0891b2","#059669","#b45309","#7c3aed","#db2777",
-];
-
-// Normalized node — superset of all view-specific node types
-interface NormalizedNode {
- node_id: string;
- node_type: string;
- language: string;
- symbol_count: number;
- pagerank: number;
- betweenness: number;
- community_id: number;
- is_test: boolean;
- is_entry_point: boolean;
- file_count?: number;
- doc_coverage_pct?: number;
- confidence_group?: string;
- commit_count?: number;
-}
-
-type SimNode = NormalizedNode & SimulationNodeDatum;
-type SimLink = SimulationLinkDatum<SimNode> & {
- imported_names: string[];
- edge_count?: number;
-};
-
-interface HoverState {
- node: SimNode;
- x: number;
- y: number;
-}
-
-const MINIMAP_W = 160;
-const MINIMAP_H = 120;
-
-function nodeRadius(node: SimNode, viewMode: ViewMode, sizeBy: GraphFilters["sizeBy"]): number {
- if (viewMode === "module" && node.file_count !== undefined) {
- return 6 + Math.sqrt(node.file_count) * 2.5;
- }
- if (viewMode === "hotfiles" && node.commit_count !== undefined && node.commit_count > 0) {
- return 4 + Math.min(10, Math.sqrt(node.commit_count) * 1.5);
- }
- switch (sizeBy) {
- case "symbol_count":
- return 4 + Math.min(8, node.symbol_count / 10);
- case "pagerank":
- return 4 + Math.min(8, node.pagerank * 1000);
- case "betweenness":
- return 4 + Math.min(8, node.betweenness * 50);
- }
-}
-
-function nodeColor(node: SimNode, viewMode: ViewMode, colorBy: GraphFilters["colorBy"]): string {
- if (viewMode === "module" && node.doc_coverage_pct !== undefined) {
- return d3.interpolateRgb("#dc2626", "#22c55e")(node.doc_coverage_pct);
- }
- if (viewMode === "dead") {
- if (node.confidence_group === "certain") return "#dc2626";
- if (node.confidence_group === "likely") return "rgba(220,38,38,0.6)";
- return "#64748b"; // neighbor
- }
- if (node.node_id.startsWith("external:")) return "#78716c";
- switch (colorBy) {
- case "language":
- return languageColor(node.language);
- case "community":
- return COMMUNITY_COLORS[node.community_id % COMMUNITY_COLORS.length];
- case "entry_point":
- return node.is_entry_point ? "#f59e0b" : languageColor(node.language);
- }
-}
-
-export interface GraphCanvasProps {
- repoId: string;
- viewMode?: ViewMode;
- centerNodeId?: string | null;
- hops?: number;
- days?: number;
- onNodeClick?: (nodeId: string) => void;
- onNodeViewDocs?: (nodeId: string) => void;
- onViewChange?: (view: ViewMode) => void;
-}
-
-export function GraphCanvas({
- repoId,
- viewMode = "module",
- centerNodeId,
- hops = 2,
- days = 30,
- onNodeClick,
- onNodeViewDocs,
- onViewChange,
-}: GraphCanvasProps) {
- const router = useRouter();
-
- // All hooks called unconditionally; null key = no fetch
- const { graph: fullGraph, isLoading: fullLoading, error: fullError } = useGraph(
- viewMode === "full" ? repoId : null,
- );
- const { graph: moduleGraph, isLoading: moduleLoading } = useModuleGraph(
- viewMode === "module" ? repoId : null,
- );
- const { graph: egoGraph, isLoading: egoLoading } = useEgoGraph(
- viewMode === "ego" ? repoId : null,
- viewMode === "ego" ? (centerNodeId ?? null) : null,
- hops,
- );
- const { graph: archGraph, isLoading: archLoading } = useArchitectureGraph(
- viewMode === "architecture" ? repoId : null,
- );
- const { graph: deadGraph, isLoading: deadLoading } = useDeadCodeGraph(
- viewMode === "dead" ? repoId : null,
- );
- const { graph: hotGraph, isLoading: hotLoading } = useHotFilesGraph(
- viewMode === "hotfiles" ? repoId : null,
- days,
- );
-
- const canvasRef = useRef<HTMLCanvasElement>(null);
- const minimapRef = useRef<HTMLCanvasElement>(null);
- const containerRef = useRef<HTMLDivElement>(null);
- const transformRef = useRef<d3.ZoomTransform>(d3.zoomIdentity);
- const simNodesRef = useRef<SimNode[]>([]);
- const simLinksRef = useRef<SimLink[]>([]);
- const animFrameRef = useRef<number | null>(null);
- const adjacencyRef = useRef<Map<string, Set<string>>>(new Map());
- const neighborhoodRef = useRef<Set<string> | null>(null);
-
- const [hoveredNode, setHoveredNode] = useState<HoverState | null>(null);
- const [canvasSize, setCanvasSize] = useState({ w: 800, h: 600 });
- const [showFilter, setShowFilter] = useState(false);
- const [showPathFinder, setShowPathFinder] = useState(false);
- const [highlightedPath, setHighlightedPath] = useState<Set<string>>(new Set());
- const [showFullGraphWarning, setShowFullGraphWarning] = useState(false);
- const [filters, setFilters] = useState<GraphFilters>({
- hiddenLangs: new Set(),
- hideTests: false,
- colorBy: "language",
- sizeBy: "symbol_count",
- nodeSearch: "",
- });
-
- // Normalize graph data to a common shape for all views
- const normalizedData = useMemo<{
- nodes: NormalizedNode[];
- links: { source: string; target: string; imported_names: string[]; edge_count?: number }[];
- } | null>(() => {
- switch (viewMode) {
- case "full":
- if (!fullGraph) return null;
- return { nodes: fullGraph.nodes, links: fullGraph.links };
- case "module":
- if (!moduleGraph) return null;
- return {
- nodes: moduleGraph.nodes.map((m) => ({
- node_id: m.module_id,
- node_type: "module",
- language: "",
- symbol_count: m.symbol_count,
- pagerank: m.avg_pagerank,
- betweenness: 0,
- community_id: 0,
- is_test: false,
- is_entry_point: false,
- file_count: m.file_count,
- doc_coverage_pct: m.doc_coverage_pct,
- })),
- links: moduleGraph.edges.map((e) => ({
- source: e.source,
- target: e.target,
- imported_names: [],
- edge_count: e.edge_count,
- })),
- };
- case "ego":
- if (!egoGraph) return null;
- return { nodes: egoGraph.nodes, links: egoGraph.links };
- case "architecture":
- if (!archGraph) return null;
- return { nodes: archGraph.nodes, links: archGraph.links };
- case "dead":
- if (!deadGraph) return null;
- return { nodes: deadGraph.nodes, links: deadGraph.links };
- case "hotfiles":
- if (!hotGraph) return null;
- return { nodes: hotGraph.nodes, links: hotGraph.links };
- default:
- return null;
- }
- }, [viewMode, fullGraph, moduleGraph, egoGraph, archGraph, deadGraph, hotGraph]);
-
- // Full graph warning gate
- useEffect(() => {
- if (viewMode === "full" && fullGraph && fullGraph.nodes.length > 2000) {
- const confirmed =
- typeof window !== "undefined" &&
- sessionStorage.getItem("full-graph-confirmed") === "1";
- if (!confirmed) setShowFullGraphWarning(true);
- }
- }, [viewMode, fullGraph]);
-
- // Resize observer
- useEffect(() => {
- const el = containerRef.current;
- if (!el) return;
- const ro = new ResizeObserver((entries) => {
- const { width, height } = entries[0]!.contentRect;
- setCanvasSize({ w: Math.floor(width), h: Math.floor(height) });
- });
- ro.observe(el);
- return () => ro.disconnect();
- }, []);
-
- // Update hover neighborhood for dimming
- useEffect(() => {
- if (!hoveredNode) {
- neighborhoodRef.current = null;
- return;
- }
- const visited = new Set<string>([hoveredNode.node.node_id]);
- let frontier = [hoveredNode.node.node_id];
- for (let hop = 0; hop < 2; hop++) {
- const next: string[] = [];
- for (const id of frontier) {
- for (const nbr of adjacencyRef.current.get(id) ?? []) {
- if (!visited.has(nbr)) {
- visited.add(nbr);
- next.push(nbr);
- }
- }
- }
- frontier = next;
- }
- neighborhoodRef.current = visited;
- }, [hoveredNode]);
-
- const drawFrame = useCallback(() => {
- const canvas = canvasRef.current;
- if (!canvas) return;
- const ctx = canvas.getContext("2d");
- if (!ctx) return;
-
- const { w, h } = canvasSize;
- const t = transformRef.current;
- const search = filters.nodeSearch.toLowerCase();
- const neighborhood = neighborhoodRef.current;
- const hasPathFilter = highlightedPath.size > 0;
-
- ctx.clearRect(0, 0, w, h);
- ctx.save();
- ctx.translate(t.x, t.y);
- ctx.scale(t.k, t.k);
-
- // Draw edges
- for (const link of simLinksRef.current) {
- const src = link.source as SimNode;
- const tgt = link.target as SimNode;
- if (src.x == null || src.y == null || tgt.x == null || tgt.y == null) continue;
- if (filters.hiddenLangs.has(src.language) || filters.hiddenLangs.has(tgt.language)) continue;
-
- const inNeighborhood =
- !neighborhood ||
- (neighborhood.has(src.node_id) && neighborhood.has(tgt.node_id));
- const isOnPath =
- hasPathFilter &&
- (highlightedPath.has(src.node_id) || highlightedPath.has(tgt.node_id));
- const isDynamic = link.imported_names.length === 0 && viewMode !== "module";
-
- ctx.beginPath();
- ctx.moveTo(src.x, src.y);
- ctx.lineTo(tgt.x, tgt.y);
- ctx.strokeStyle = isDynamic ? "rgba(150,150,150,1)" : "rgba(91,156,246,1)";
- ctx.globalAlpha = !inNeighborhood
- ? 0.05
- : hasPathFilter && !isOnPath
- ? 0.05
- : isDynamic
- ? 0.25
- : 0.4;
- ctx.lineWidth =
- viewMode === "module"
- ? (1 + Math.min(3, Math.sqrt(link.edge_count ?? 1) * 0.5)) / t.k
- : (1 + Math.min(3, link.imported_names.length * 0.4)) / t.k;
- if (isDynamic) {
- ctx.setLineDash([4 / t.k, 4 / t.k]);
- } else {
- ctx.setLineDash([]);
- }
- ctx.stroke();
- ctx.setLineDash([]);
- }
-
- // Draw nodes
- for (const node of simNodesRef.current) {
- if (node.x == null || node.y == null) continue;
- if (filters.hiddenLangs.has(node.language)) continue;
- if (filters.hideTests && node.is_test) continue;
-
- const r = nodeRadius(node, viewMode, filters.sizeBy);
- const color = nodeColor(node, viewMode, filters.colorBy);
- const isMatch = search ? node.node_id.toLowerCase().includes(search) : false;
- const isOnPath = hasPathFilter && highlightedPath.has(node.node_id);
- const inNbr = !neighborhood || neighborhood.has(node.node_id);
- const dimmed = (hasPathFilter && !isOnPath) || (neighborhood !== null && !inNbr);
-
- ctx.globalAlpha = dimmed ? 0.15 : 1.0;
-
- ctx.beginPath();
- ctx.arc(node.x, node.y, r, 0, Math.PI * 2);
- ctx.fillStyle = isOnPath ? "#f97316" : color;
- ctx.fill();
-
- // Entry point / architecture ring
- if (node.is_entry_point && !isOnPath) {
- ctx.strokeStyle = "#ffffff";
- ctx.lineWidth = (viewMode === "architecture" ? 2.5 : 2) / t.k;
- ctx.stroke();
- }
- if (viewMode === "architecture" && node.is_entry_point && !isOnPath) {
- ctx.beginPath();
- ctx.arc(node.x, node.y, r + 4 / t.k, 0, Math.PI * 2);
- ctx.strokeStyle = "#ffffff";
- ctx.lineWidth = 1.5 / t.k;
- ctx.stroke();
- }
-
- // Path highlight ring
- if (isOnPath) {
- ctx.globalAlpha = 1;
- ctx.beginPath();
- ctx.arc(node.x, node.y, r + 4 / t.k, 0, Math.PI * 2);
- ctx.strokeStyle = "#f97316";
- ctx.lineWidth = 2.5 / t.k;
- ctx.stroke();
- }
-
- // Search highlight
- if (isMatch && !isOnPath) {
- ctx.globalAlpha = 1;
- ctx.beginPath();
- ctx.arc(node.x, node.y, r + 3 / t.k, 0, Math.PI * 2);
- ctx.strokeStyle = "#eab308";
- ctx.lineWidth = 2 / t.k;
- ctx.stroke();
- }
-
- // Module label for large nodes
- if (viewMode === "module" && r > 14) {
- ctx.globalAlpha = dimmed ? 0.15 : 0.9;
- ctx.fillStyle = "#ffffff";
- ctx.font = `bold ${Math.min(12, r * 0.7) / t.k}px sans-serif`;
- ctx.textAlign = "center";
- ctx.textBaseline = "middle";
- const label = node.node_id.length > 10 ? node.node_id.slice(0, 9) + "…" : node.node_id;
- ctx.fillText(label, node.x, node.y);
- }
- }
-
- ctx.globalAlpha = 1;
- ctx.restore();
-
- // Minimap
- const mc = minimapRef.current;
- if (mc && simNodesRef.current.length > 0) {
- const mctx = mc.getContext("2d");
- if (mctx) {
- mctx.clearRect(0, 0, MINIMAP_W, MINIMAP_H);
- let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
- for (const n of simNodesRef.current) {
- if (n.x == null || n.y == null) continue;
- if (n.x < minX) minX = n.x;
- if (n.x > maxX) maxX = n.x;
- if (n.y < minY) minY = n.y;
- if (n.y > maxY) maxY = n.y;
- }
- if (!isFinite(minX)) return;
- const pad = 20;
- minX -= pad; maxX += pad; minY -= pad; maxY += pad;
- const worldW = maxX - minX;
- const worldH = maxY - minY;
- const scale = Math.min(MINIMAP_W / worldW, MINIMAP_H / worldH);
- const offX = (MINIMAP_W - worldW * scale) / 2 - minX * scale;
- const offY = (MINIMAP_H - worldH * scale) / 2 - minY * scale;
- for (const node of simNodesRef.current) {
- if (node.x == null || node.y == null) continue;
- mctx.beginPath();
- mctx.arc(node.x * scale + offX, node.y * scale + offY, 1.5, 0, Math.PI * 2);
- mctx.fillStyle = nodeColor(node, viewMode, filters.colorBy);
- mctx.globalAlpha = 0.7;
- mctx.fill();
- }
- mctx.globalAlpha = 1;
- const { w: cw, h: ch } = canvasSize;
- const vtx = (-t.x / t.k) * scale + offX;
- const vty = (-t.y / t.k) * scale + offY;
- const vtw = (cw / t.k) * scale;
- const vth = (ch / t.k) * scale;
- mctx.strokeStyle = "rgba(255,255,255,0.6)";
- mctx.lineWidth = 1;
- mctx.strokeRect(vtx, vty, vtw, vth);
- }
- }
- }, [canvasSize, filters, highlightedPath, viewMode]);
-
- // D3 simulation
- useEffect(() => {
- if (!normalizedData || !canvasRef.current) return;
- const canvas = canvasRef.current;
- const { w, h } = canvasSize;
-
- simNodesRef.current = normalizedData.nodes.map((n) => ({ ...n }));
- simLinksRef.current = normalizedData.links.map((l) => ({
- ...l,
- source: l.source as string,
- target: l.target as string,
- })) as SimLink[];
-
- // Build undirected adjacency for hover dimming
- const adj = new Map<string, Set<string>>();
- for (const link of normalizedData.links) {
- const s = link.source;
- const tgt = link.target;
- if (!adj.has(s)) adj.set(s, new Set());
- if (!adj.has(tgt)) adj.set(tgt, new Set());
- adj.get(s)!.add(tgt);
- adj.get(tgt)!.add(s);
- }
- adjacencyRef.current = adj;
-
- // Clustering gravity (pull same-directory nodes together)
- function clusterForce(alpha: number) {
- const centroids = new Map<string, { x: number; y: number; count: number }>();
- for (const n of simNodesRef.current) {
- if (n.x == null || n.y == null) continue;
- const dir = n.node_id.split("/")[0] ?? n.node_id;
- const c = centroids.get(dir) ?? { x: 0, y: 0, count: 0 };
- c.x += n.x;
- c.y += n.y;
- c.count++;
- centroids.set(dir, c);
- }
- for (const n of simNodesRef.current) {
- if (n.x == null || n.y == null) continue;
- const dir = n.node_id.split("/")[0] ?? n.node_id;
- const c = centroids.get(dir);
- if (!c || c.count === 0) continue;
- n.vx! += (c.x / c.count - n.x) * alpha * 0.04;
- n.vy! += (c.y / c.count - n.y) * alpha * 0.04;
- }
- }
-
- const isFileLevelView = viewMode === "full" || viewMode === "ego";
- const isModuleView = viewMode === "module";
-
- const simulation = d3
- .forceSimulation<SimNode>(simNodesRef.current)
- .force(
- "link",
- d3
- .forceLink<SimNode, SimLink>(simLinksRef.current)
- .id((d) => d.node_id)
- .distance(isModuleView ? 120 : 60),
- )
- .force("charge", d3.forceManyBody<SimNode>().strength(isModuleView ? -500 : -150))
- .force("center", d3.forceCenter(w / 2, h / 2))
- .force("collide", d3.forceCollide<SimNode>(isModuleView ? 35 : 12))
- .alphaDecay(0.02)
- .on("tick", () => {
- if (animFrameRef.current) cancelAnimationFrame(animFrameRef.current);
- animFrameRef.current = requestAnimationFrame(drawFrame);
- });
-
- if (isFileLevelView) {
- simulation.force("cluster", clusterForce);
- }
-
- const zoom = d3
- .zoom<HTMLCanvasElement, unknown>()
- .scaleExtent([0.05, 20])
- .on("zoom", (event) => {
- transformRef.current = event.transform;
- if (animFrameRef.current) cancelAnimationFrame(animFrameRef.current);
- animFrameRef.current = requestAnimationFrame(drawFrame);
- });
-
- d3.select(canvas).call(zoom);
-
- return () => {
- simulation.stop();
- d3.select(canvas).on(".zoom", null);
- if (animFrameRef.current) cancelAnimationFrame(animFrameRef.current);
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [normalizedData, canvasSize]);
-
- // Redraw when filters/path/hover change
- useEffect(() => { drawFrame(); }, [filters, highlightedPath, drawFrame]);
- useEffect(() => { drawFrame(); }, [hoveredNode, drawFrame]);
-
- const handleExportPng = useCallback(() => {
- const canvas = canvasRef.current;
- if (!canvas) return;
- const link = document.createElement("a");
- link.download = "dependency-graph.png";
- link.href = canvas.toDataURL("image/png");
- link.click();
- }, []);
-
- const handleMouseMove = useCallback(
- (e: React.MouseEvent<HTMLCanvasElement>) => {
- const canvas = canvasRef.current;
- if (!canvas) return;
- const rect = canvas.getBoundingClientRect();
- // Scale from CSS pixels to canvas pixels (accounts for any CSS/intrinsic size mismatch)
- const scaleX = canvas.width / rect.width;
- const scaleY = canvas.height / rect.height;
- const mxCSS = e.clientX - rect.left;
- const myCSS = e.clientY - rect.top;
- const mx = mxCSS * scaleX;
- const my = myCSS * scaleY;
- const t = transformRef.current;
- const wx = (mx - t.x) / t.k;
- const wy = (my - t.y) / t.k;
-
- let closest: SimNode | null = null;
- let minDist = Infinity;
-
- for (const node of simNodesRef.current) {
- if (node.x == null || node.y == null) continue;
- if (filters.hiddenLangs.has(node.language)) continue;
- if (filters.hideTests && node.is_test) continue;
- const r = nodeRadius(node, viewMode, filters.sizeBy);
- const dx = node.x - wx;
- const dy = node.y - wy;
- const dist = Math.sqrt(dx * dx + dy * dy);
- // Hit threshold: node radius + 4 CSS pixels of margin (4/t.k converts to world space)
- if (dist < r + 4 / t.k && dist < minDist) {
- closest = node;
- minDist = dist;
- }
- }
-
- // Store CSS pixel coords for tooltip positioning
- setHoveredNode(closest ? { node: closest, x: mxCSS, y: myCSS } : null);
- },
- [filters, viewMode],
- );
-
- const handleClick = useCallback(
- (e: React.MouseEvent<HTMLCanvasElement>) => {
- const canvas = canvasRef.current;
- if (!canvas) return;
- const rect = canvas.getBoundingClientRect();
- const scaleX = canvas.width / rect.width;
- const scaleY = canvas.height / rect.height;
- const mx = (e.clientX - rect.left) * scaleX;
- const my = (e.clientY - rect.top) * scaleY;
- const t = transformRef.current;
- const wx = (mx - t.x) / t.k;
- const wy = (my - t.y) / t.k;
-
- // Find the closest node within threshold (same logic as hover)
- let closest: SimNode | null = null;
- let minDist = Infinity;
- for (const node of simNodesRef.current) {
- if (node.x == null || node.y == null) continue;
- const r = nodeRadius(node, viewMode, filters.sizeBy);
- const dx = node.x - wx;
- const dy = node.y - wy;
- const dist = Math.sqrt(dx * dx + dy * dy);
- if (dist < r + 4 / t.k && dist < minDist) {
- closest = node;
- minDist = dist;
- }
- }
-
- if (closest) {
- if (viewMode === "module") {
- onNodeClick?.(closest.node_id);
- } else {
- // Open doc panel for the clicked node
- onNodeViewDocs?.(closest.node_id);
- }
- }
- },
- [filters, viewMode, onNodeClick, onNodeViewDocs],
- );
-
- const isLoading =
- viewMode === "full" ? fullLoading :
- viewMode === "module" ? moduleLoading :
- viewMode === "ego" ? egoLoading :
- viewMode === "architecture" ? archLoading :
- viewMode === "dead" ? deadLoading :
- viewMode === "hotfiles" ? hotLoading : false;
-
- const error = viewMode === "full" ? fullError : null;
-
- const availableLangs = Array.from(
- new Set((normalizedData?.nodes ?? []).map((n) => n.language).filter(Boolean)),
- ).sort();
-
- const nodeCount = normalizedData?.nodes.length ?? 0;
- const linkCount = normalizedData?.links.length ?? 0;
-
- if (isLoading) {
- return <Skeleton className="h-full w-full rounded-lg" />;
- }
-
- if ((!normalizedData || error) && !showFullGraphWarning) {
- return (
- <EmptyState
- title={viewMode === "ego" && !centerNodeId ? "Select a node" : "No data"}
- description={
- viewMode === "ego" && !centerNodeId
- ? "Search for a file above or click a module node to explore its neighborhood."
- : "Check that the backend is running and this repo has been indexed."
- }
- />
- );
- }
-
- return (
- <div ref={containerRef} className="relative w-full h-full">
- <canvas
- ref={canvasRef}
- width={canvasSize.w}
- height={canvasSize.h}
- onMouseMove={handleMouseMove}
- onMouseLeave={() => setHoveredNode(null)}
- onClick={handleClick}
- className="w-full h-full cursor-crosshair"
- />
-
- {hoveredNode && (
- <GraphTooltip
- node={hoveredNode.node as GraphNodeResponse}
- x={hoveredNode.x}
- y={hoveredNode.y}
- canvasWidth={canvasSize.w}
- canvasHeight={canvasSize.h}
- />
- )}
-
- {/* Toolbar */}
- <div className="absolute top-3 right-3 flex flex-wrap gap-2 justify-end">
- {viewMode === "full" && (
- <Button
- size="sm"
- variant="secondary"
- onClick={() => { setShowPathFinder((s) => !s); setShowFilter(false); }}
- className="h-8 gap-1.5"
- >
- <Route className="h-3.5 w-3.5" />
- <span className="hidden sm:inline">Path</span>
- </Button>
- )}
- <Button
- size="sm"
- variant="secondary"
- onClick={() => { setShowFilter((s) => !s); setShowPathFinder(false); }}
- className="h-8 gap-1.5"
- >
- <SlidersHorizontal className="h-3.5 w-3.5" />
- <span className="hidden sm:inline">Filter</span>
- </Button>
- <Button size="sm" variant="secondary" onClick={handleExportPng} className="h-8 gap-1.5">
- <Download className="h-3.5 w-3.5" />
- <span className="hidden sm:inline">Export</span>
- </Button>
- </div>
-
- {showPathFinder && viewMode === "full" && (
- <div className="absolute top-12 right-3">
- <PathFinder
- repoId={repoId}
- onPathFound={(nodes) => setHighlightedPath(new Set(nodes))}
- onClear={() => setHighlightedPath(new Set())}
- />
- </div>
- )}
-
- {showFilter && (
- <div className="absolute top-12 right-3">
- <GraphFilterPanel
- filters={filters}
- onChange={setFilters}
- availableLangs={availableLangs}
- />
- </div>
- )}
-
- <div className="absolute bottom-3 right-3">
- <GraphMinimap ref={minimapRef} />
- </div>
-
- {/* Legend */}
- <div className="absolute bottom-3 left-3 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)]/80 backdrop-blur-sm p-2 text-xs text-[var(--color-text-tertiary)] space-y-1">
- <div className="font-medium text-[var(--color-text-secondary)] mb-1">
- {nodeCount} nodes · {linkCount} edges
- </div>
- {viewMode === "module" ? (
- <>
- <div className="flex items-center gap-1.5"><span className="h-2 w-2 rounded-full bg-green-500" />High doc coverage</div>
- <div className="flex items-center gap-1.5"><span className="h-2 w-2 rounded-full bg-red-500" />Low doc coverage</div>
- </>
- ) : viewMode === "dead" ? (
- <>
- <div className="flex items-center gap-1.5"><span className="h-2 w-2 rounded-full bg-red-600" />Certain dead</div>
- <div className="flex items-center gap-1.5"><span className="h-2 w-2 rounded-full bg-red-400" />Likely dead</div>
- </>
- ) : (
- <>
- <div className="flex items-center gap-1.5"><span className="h-2 w-2 rounded-full bg-white border border-gray-400" />Entry point</div>
- <div className="flex items-center gap-1.5"><span className="h-2 w-2 rounded-full border-2 border-yellow-400 bg-transparent" />Search match</div>
- </>
- )}
- </div>
-
- {/* Full graph warning dialog */}
- <Dialog
- open={showFullGraphWarning}
- onOpenChange={(open) => {
- if (!open) {
- setShowFullGraphWarning(false);
- onViewChange?.("module");
- }
- }}
- >
- <DialogContent>
- <DialogHeader>
- <DialogTitle className="flex items-center gap-2">
- <AlertTriangle className="h-5 w-5 text-amber-400" />
- Large Graph Warning
- </DialogTitle>
- <DialogDescription>
- Rendering {nodeCount} nodes may be slow. This view works best for small repos.
- Continue anyway?
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button
- variant="secondary"
- onClick={() => {
- setShowFullGraphWarning(false);
- onViewChange?.("module");
- }}
- >
- Cancel
- </Button>
- <Button
- onClick={() => {
- if (typeof window !== "undefined") {
- sessionStorage.setItem("full-graph-confirmed", "1");
- }
- setShowFullGraphWarning(false);
- }}
- >
- Continue
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </div>
- );
-}
diff --git a/packages/web/src/components/graph/graph-context-menu.tsx b/packages/web/src/components/graph/graph-context-menu.tsx
new file mode 100644
index 000000000..6e5721888
--- /dev/null
+++ b/packages/web/src/components/graph/graph-context-menu.tsx
@@ -0,0 +1,73 @@
+"use client";
+
+import { FileText, Search, Route, ArrowRightFromLine, ArrowLeftToLine } from "lucide-react";
+
+interface GraphContextMenuProps {
+ x: number;
+ y: number;
+ nodeId: string;
+ isModule: boolean;
+ onViewDocs: () => void;
+ onExplore: () => void;
+ onPathFrom: () => void;
+ onPathTo: () => void;
+}
+
+export function GraphContextMenu({
+ x,
+ y,
+ nodeId,
+ isModule,
+ onViewDocs,
+ onExplore,
+ onPathFrom,
+ onPathTo,
+}: GraphContextMenuProps) {
+ const shortName = nodeId.split("/").pop() ?? nodeId;
+
+ return (
+ <div
+ className="fixed z-50 min-w-[200px] rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-xl shadow-black/40 backdrop-blur-md py-1 text-xs"
+ style={{ left: x, top: y }}
+ >
+ {/* Node name header */}
+ <div className="px-3 py-1.5 text-[10px] text-[var(--color-text-tertiary)] font-mono truncate border-b border-[var(--color-border-default)] mb-1">
+ {shortName}
+ </div>
+
+ <button
+ onClick={onViewDocs}
+ className="w-full flex items-center gap-2.5 px-3 py-2 text-left text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] transition-colors"
+ >
+ <FileText className="w-3.5 h-3.5 text-[var(--color-accent-primary)]" />
+ View Documentation
+ </button>
+
+ <button
+ onClick={onExplore}
+ className="w-full flex items-center gap-2.5 px-3 py-2 text-left text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] transition-colors"
+ >
+ <Search className="w-3.5 h-3.5 text-[var(--color-accent-primary)]" />
+ {isModule ? "Explore Module" : "Explore Neighborhood"}
+ </button>
+
+ <div className="border-t border-[var(--color-border-default)] my-1" />
+
+ <button
+ onClick={onPathFrom}
+ className="w-full flex items-center gap-2.5 px-3 py-2 text-left text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] transition-colors"
+ >
+ <ArrowRightFromLine className="w-3.5 h-3.5 text-[var(--color-accent-graph)]" />
+ Find paths from here
+ </button>
+
+ <button
+ onClick={onPathTo}
+ className="w-full flex items-center gap-2.5 px-3 py-2 text-left text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] transition-colors"
+ >
+ <ArrowLeftToLine className="w-3.5 h-3.5 text-[var(--color-accent-graph)]" />
+ Find paths to here
+ </button>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/graph/graph-filter-panel.tsx b/packages/web/src/components/graph/graph-filter-panel.tsx
deleted file mode 100644
index d7b5244a6..000000000
--- a/packages/web/src/components/graph/graph-filter-panel.tsx
+++ /dev/null
@@ -1,132 +0,0 @@
-"use client";
-
-import { Input } from "@/components/ui/input";
-import { cn } from "@/lib/utils/cn";
-import { LANGUAGE_COLORS } from "@/lib/utils/confidence";
-
-export type ColorBy = "language" | "community" | "entry_point";
-export type SizeBy = "symbol_count" | "pagerank" | "betweenness";
-
-export interface GraphFilters {
- hiddenLangs: Set<string>;
- hideTests: boolean;
- colorBy: ColorBy;
- sizeBy: SizeBy;
- nodeSearch: string;
-}
-
-interface GraphFilterPanelProps {
- filters: GraphFilters;
- onChange: (filters: GraphFilters) => void;
- availableLangs: string[];
-}
-
-export function GraphFilterPanel({ filters, onChange, availableLangs }: GraphFilterPanelProps) {
- const update = (patch: Partial<GraphFilters>) => onChange({ ...filters, ...patch });
-
- const toggleLang = (lang: string) => {
- const next = new Set(filters.hiddenLangs);
- if (next.has(lang)) next.delete(lang);
- else next.add(lang);
- update({ hiddenLangs: next });
- };
-
- return (
- <div className="w-52 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] p-3 shadow-lg space-y-4 text-xs">
- <div>
- <p className="font-semibold text-[var(--color-text-primary)] mb-2 uppercase tracking-wider text-[10px]">
- Node Search
- </p>
- <Input
- value={filters.nodeSearch}
- onChange={(e) => update({ nodeSearch: e.target.value })}
- placeholder="Highlight nodes…"
- className="h-7 text-xs"
- />
- </div>
-
- <div>
- <p className="font-semibold text-[var(--color-text-primary)] mb-2 uppercase tracking-wider text-[10px]">
- Languages
- </p>
- <div className="space-y-1">
- {availableLangs.map((lang) => {
- const hidden = filters.hiddenLangs.has(lang);
- return (
- <label key={lang} className="flex items-center gap-2 cursor-pointer select-none">
- <input
- type="checkbox"
- checked={!hidden}
- onChange={() => toggleLang(lang)}
- className="rounded border-[var(--color-border-default)]"
- />
- <span
- className="h-2 w-2 rounded-full shrink-0"
- style={{
- background:
- LANGUAGE_COLORS[lang.toLowerCase()] ?? LANGUAGE_COLORS.other,
- }}
- />
- <span className="text-[var(--color-text-secondary)] capitalize">{lang}</span>
- </label>
- );
- })}
- </div>
- </div>
-
- <label className="flex items-center gap-2 cursor-pointer select-none">
- <input
- type="checkbox"
- checked={filters.hideTests}
- onChange={(e) => update({ hideTests: e.target.checked })}
- className="rounded border-[var(--color-border-default)]"
- />
- <span className="text-[var(--color-text-secondary)]">Hide test files</span>
- </label>
-
- <div>
- <p className="font-semibold text-[var(--color-text-primary)] mb-2 uppercase tracking-wider text-[10px]">
- Color By
- </p>
- <div className="space-y-1">
- {(["language", "community", "entry_point"] as ColorBy[]).map((v) => (
- <label key={v} className="flex items-center gap-2 cursor-pointer select-none">
- <input
- type="radio"
- checked={filters.colorBy === v}
- onChange={() => update({ colorBy: v })}
- name="colorBy"
- className="border-[var(--color-border-default)]"
- />
- <span className="text-[var(--color-text-secondary)] capitalize">
- {v.replace(/_/g, " ")}
- </span>
- </label>
- ))}
- </div>
- </div>
-
- <div>
- <p className="font-semibold text-[var(--color-text-primary)] mb-2 uppercase tracking-wider text-[10px]">
- Size By
- </p>
- <div className="space-y-1">
- {(["symbol_count", "pagerank", "betweenness"] as SizeBy[]).map((v) => (
- <label key={v} className="flex items-center gap-2 cursor-pointer select-none">
- <input
- type="radio"
- checked={filters.sizeBy === v}
- onChange={() => update({ sizeBy: v })}
- name="sizeBy"
- className="border-[var(--color-border-default)]"
- />
- <span className="text-[var(--color-text-secondary)] capitalize">
- {v.replace(/_/g, " ")}
- </span>
- </label>
- ))}
- </div>
- </div>
- </div>
- );
-}
diff --git a/packages/web/src/components/graph/graph-flow.tsx b/packages/web/src/components/graph/graph-flow.tsx
new file mode 100644
index 000000000..b218c8a2e
--- /dev/null
+++ b/packages/web/src/components/graph/graph-flow.tsx
@@ -0,0 +1,515 @@
+"use client";
+
+import {
+ createContext,
+ useCallback,
+ useMemo,
+ useState,
+ useEffect,
+} from "react";
+import {
+ ReactFlow,
+ MiniMap,
+ Controls,
+ Background,
+ BackgroundVariant,
+ ReactFlowProvider,
+ useReactFlow,
+ type NodeMouseHandler,
+ type Node,
+} from "@xyflow/react";
+import "@xyflow/react/dist/style.css";
+import { Loader2, ChevronRight, Home } from "lucide-react";
+import { Skeleton } from "@/components/ui/skeleton";
+import { EmptyState } from "@/components/shared/empty-state";
+import {
+ useModuleGraph,
+ useGraph,
+ useArchitectureGraph,
+ useDeadCodeGraph,
+ useHotFilesGraph,
+} from "@/lib/hooks/use-graph";
+import { ModuleGroupNode } from "./nodes/module-group-node";
+import { FileNode } from "./nodes/file-node";
+import { DependencyEdge } from "./edges/dependency-edge";
+import { groupNodesAsModules } from "./elk-layout";
+import { useModuleElkLayout, useFileElkLayout } from "./use-elk-layout";
+import { PathFinderPanel } from "./path-finder-panel";
+import { GraphToolbar, type ColorMode, type ViewMode } from "./graph-toolbar";
+import { GraphLegend } from "./graph-legend";
+import { GraphContextMenu } from "./graph-context-menu";
+import { languageColor } from "@/lib/utils/confidence";
+
+// ---- Context ----
+
+export interface GraphContextValue {
+ highlightedPath: Set<string>;
+ highlightedEdges: Set<string>;
+ colorMode: ColorMode;
+ riskScores: Map<string, number>;
+}
+
+export const GraphContext = createContext<GraphContextValue>({
+ highlightedPath: new Set(),
+ highlightedEdges: new Set(),
+ colorMode: "language",
+ riskScores: new Map(),
+});
+
+// ---- Node/Edge types ----
+
+const nodeTypes = {
+ moduleGroup: ModuleGroupNode,
+ fileNode: FileNode,
+};
+
+const edgeTypes = {
+ dependency: DependencyEdge,
+};
+
+// ---- Inner component (needs ReactFlowProvider) ----
+
+interface GraphFlowInnerProps {
+ repoId: string;
+ onNodeClick?: (nodeId: string, nodeType: string) => void | Promise<void>;
+ onNodeViewDocs?: (nodeId: string) => void;
+}
+
+function GraphFlowInner({
+ repoId,
+ onNodeClick,
+ onNodeViewDocs,
+}: GraphFlowInnerProps) {
+ const reactFlow = useReactFlow();
+
+ // State
+ const [viewMode, setViewMode] = useState<ViewMode>("module");
+ const [colorMode, setColorMode] = useState<ColorMode>("language");
+ const [hideTests, setHideTests] = useState(false);
+ const [highlightedPath, setHighlightedPath] = useState<Set<string>>(new Set());
+ const [highlightedEdges, setHighlightedEdges] = useState<Set<string>>(new Set());
+ const [showPathFinder, setShowPathFinder] = useState(false);
+
+ // Drill-down: stack of module prefixes. e.g. ["packages", "packages/web"]
+ const [modulePath, setModulePath] = useState<string[]>([]);
+ const currentPrefix = modulePath.length > 0 ? modulePath[modulePath.length - 1] : "";
+ const isDrilledDown = modulePath.length > 0;
+
+ // Context menu
+ const [ctxMenu, setCtxMenu] = useState<{
+ x: number; y: number; nodeId: string; nodeType: string;
+ } | null>(null);
+
+ // Path finder pre-fill
+ const [pathFrom, setPathFrom] = useState("");
+ const [pathTo, setPathTo] = useState("");
+
+ // ---- Data fetching ----
+ const isModuleView = viewMode === "module";
+
+ // Top-level module graph (only when at root of module view)
+ const { graph: moduleGraph, isLoading: moduleLoading } = useModuleGraph(
+ isModuleView && !isDrilledDown ? repoId : null,
+ );
+
+ // Full graph — needed for drill-down and other views
+ const needsFullGraph = isDrilledDown || viewMode === "full";
+ const { graph: fullGraph, isLoading: fullLoading } = useGraph(
+ needsFullGraph ? repoId : null,
+ );
+
+ const { graph: archGraph, isLoading: archLoading } = useArchitectureGraph(
+ viewMode === "architecture" ? repoId : null,
+ );
+ const { graph: deadGraph, isLoading: deadLoading } = useDeadCodeGraph(
+ viewMode === "dead" ? repoId : null,
+ );
+ const { graph: hotGraph, isLoading: hotLoading } = useHotFilesGraph(
+ viewMode === "hotfiles" ? repoId : null,
+ );
+
+ // ---- Derived data ----
+
+ // When drilled down, re-group nodes as sub-modules at the current prefix
+ const drillDownData = useMemo(() => {
+ if (!isDrilledDown || !fullGraph) return null;
+ return groupNodesAsModules(fullGraph.nodes, fullGraph.links, currentPrefix);
+ }, [isDrilledDown, fullGraph, currentPrefix]);
+
+ // File-level graph data — only for non-module views
+ const fileGraphData = useMemo(() => {
+ switch (viewMode) {
+ case "full":
+ return fullGraph ? { nodes: fullGraph.nodes, links: fullGraph.links } : undefined;
+ case "architecture":
+ return archGraph ? { nodes: archGraph.nodes, links: archGraph.links } : undefined;
+ case "dead":
+ return deadGraph ? { nodes: deadGraph.nodes, links: deadGraph.links } : undefined;
+ case "hotfiles":
+ return hotGraph ? { nodes: hotGraph.nodes, links: hotGraph.links } : undefined;
+ default:
+ return undefined;
+ }
+ }, [viewMode, fullGraph, archGraph, deadGraph, hotGraph]);
+
+ // ---- Layout selection ----
+ // Module view (including drill-down) always uses module layout
+ // Other views use file layout
+
+ const moduleLayoutInput = useMemo(() => {
+ if (!isModuleView) return { nodes: undefined, edges: undefined, fileEntries: undefined };
+ if (!isDrilledDown) {
+ return { nodes: moduleGraph?.nodes, edges: moduleGraph?.edges, fileEntries: undefined };
+ }
+ return {
+ nodes: drillDownData?.moduleNodes,
+ edges: drillDownData?.moduleEdges,
+ fileEntries: drillDownData?.fileEntries,
+ };
+ }, [isModuleView, isDrilledDown, moduleGraph, drillDownData]);
+
+ const {
+ nodes: moduleNodes,
+ edges: moduleEdges,
+ isLayouting: moduleLayouting,
+ } = useModuleElkLayout(moduleLayoutInput.nodes, moduleLayoutInput.edges, moduleLayoutInput.fileEntries);
+
+ const {
+ nodes: fileNodes,
+ edges: fileEdges,
+ isLayouting: fileLayouting,
+ } = useFileElkLayout(
+ !isModuleView ? fileGraphData?.nodes : undefined,
+ !isModuleView ? fileGraphData?.links : undefined,
+ );
+
+ const currentNodes = isModuleView ? moduleNodes : fileNodes;
+ const currentEdges = isModuleView ? moduleEdges : fileEdges;
+
+ // Filter hidden tests
+ const filteredNodes = useMemo(() => {
+ if (!hideTests) return currentNodes;
+ return currentNodes.filter((n) => {
+ if (n.type === "fileNode") {
+ return !(n.data as { isTest?: boolean }).isTest;
+ }
+ return true;
+ });
+ }, [currentNodes, hideTests]);
+
+ const isLoading =
+ (isModuleView && !isDrilledDown) ? moduleLoading :
+ isDrilledDown ? fullLoading :
+ viewMode === "full" ? fullLoading :
+ viewMode === "architecture" ? archLoading :
+ viewMode === "dead" ? deadLoading :
+ viewMode === "hotfiles" ? hotLoading : false;
+ const isLayouting = isModuleView ? moduleLayouting : fileLayouting;
+
+ // Context value
+ const ctxValue = useMemo<GraphContextValue>(
+ () => ({
+ highlightedPath,
+ highlightedEdges,
+ colorMode,
+ riskScores: new Map(),
+ }),
+ [highlightedPath, highlightedEdges, colorMode],
+ );
+
+ // ---- Handlers ----
+
+ const handleNodeClick: NodeMouseHandler = useCallback(
+ (_event, node) => {
+ if (node.type === "moduleGroup" && isModuleView) {
+ // Drill into this module — the node ID is the full module path
+ setModulePath((prev) => [...prev, node.id]);
+ return;
+ }
+ // File node or dir group in file view — pass to parent (opens docs)
+ onNodeClick?.(node.id, node.type ?? "fileNode");
+ },
+ [isModuleView, onNodeClick],
+ );
+
+ const handleNodeDoubleClick: NodeMouseHandler = useCallback(
+ (_event, node) => {
+ if (node.type !== "moduleGroup") {
+ onNodeViewDocs?.(node.id);
+ }
+ },
+ [onNodeViewDocs],
+ );
+
+ const handleNodeContextMenu: NodeMouseHandler = useCallback(
+ (event, node) => {
+ event.preventDefault();
+ setCtxMenu({
+ x: (event as unknown as React.MouseEvent).clientX,
+ y: (event as unknown as React.MouseEvent).clientY,
+ nodeId: node.id,
+ nodeType: node.type ?? "fileNode",
+ });
+ },
+ [],
+ );
+
+ useEffect(() => {
+ if (!ctxMenu) return;
+ const close = () => setCtxMenu(null);
+ window.addEventListener("click", close);
+ return () => window.removeEventListener("click", close);
+ }, [ctxMenu]);
+
+ const handlePathFound = useCallback(
+ (pathNodes: string[]) => {
+ setHighlightedPath(new Set(pathNodes));
+ const edgeKeys = new Set<string>();
+ for (let i = 0; i < pathNodes.length - 1; i++) {
+ edgeKeys.add(`${pathNodes[i]}→${pathNodes[i + 1]}`);
+ edgeKeys.add(`${pathNodes[i + 1]}→${pathNodes[i]}`);
+ }
+ setHighlightedEdges(edgeKeys);
+ if (viewMode === "module") {
+ setViewMode("full");
+ setModulePath([]);
+ }
+ setTimeout(() => {
+ const pathRfNodes = pathNodes
+ .map((id) => reactFlow.getNode(id))
+ .filter(Boolean) as Node[];
+ if (pathRfNodes.length > 0) {
+ reactFlow.fitView({ nodes: pathRfNodes, padding: 0.3, duration: 600 });
+ }
+ }, 800);
+ },
+ [viewMode, reactFlow],
+ );
+
+ const handlePathClear = useCallback(() => {
+ setHighlightedPath(new Set());
+ setHighlightedEdges(new Set());
+ }, []);
+
+ const handleFitView = useCallback(() => {
+ reactFlow.fitView({ padding: 0.15, duration: 400 });
+ }, [reactFlow]);
+
+ const handleViewChange = useCallback((v: ViewMode) => {
+ setViewMode(v);
+ setModulePath([]);
+ setHighlightedPath(new Set());
+ setHighlightedEdges(new Set());
+ }, []);
+
+ // Breadcrumb
+ const handleBreadcrumbClick = useCallback((index: number) => {
+ if (index < 0) {
+ setModulePath([]);
+ } else {
+ setModulePath((prev) => prev.slice(0, index + 1));
+ }
+ }, []);
+
+ // Context menu actions
+ const handleCtxViewDocs = useCallback(() => {
+ if (ctxMenu) onNodeViewDocs?.(ctxMenu.nodeId);
+ setCtxMenu(null);
+ }, [ctxMenu, onNodeViewDocs]);
+
+ const handleCtxExplore = useCallback(() => {
+ if (ctxMenu) {
+ if (ctxMenu.nodeType === "moduleGroup" && isModuleView) {
+ setModulePath((prev) => [...prev, ctxMenu.nodeId]);
+ } else {
+ onNodeClick?.(ctxMenu.nodeId, ctxMenu.nodeType);
+ }
+ }
+ setCtxMenu(null);
+ }, [ctxMenu, isModuleView, onNodeClick]);
+
+ const handleCtxPathFrom = useCallback(() => {
+ if (ctxMenu) { setPathFrom(ctxMenu.nodeId); setShowPathFinder(true); }
+ setCtxMenu(null);
+ }, [ctxMenu]);
+
+ const handleCtxPathTo = useCallback(() => {
+ if (ctxMenu) { setPathTo(ctxMenu.nodeId); setShowPathFinder(true); }
+ setCtxMenu(null);
+ }, [ctxMenu]);
+
+ const minimapNodeColor = useCallback(
+ (node: Node) => {
+ if (node.type === "moduleGroup") {
+ const pct = (node.data as { docCoveragePct?: number }).docCoveragePct;
+ if (pct != null) return pct >= 0.7 ? "#22c55e" : pct >= 0.3 ? "#f59520" : "#ef4444";
+ return "#3b82f6";
+ }
+ const lang = (node.data as { language?: string }).language;
+ return lang ? languageColor(lang) : "#8b5cf6";
+ },
+ [],
+ );
+
+ if (isLoading) return <Skeleton className="h-full w-full rounded-lg" />;
+
+ if (filteredNodes.length === 0 && !isLayouting) {
+ return (
+ <EmptyState
+ title="No graph data"
+ description="Check that the backend is running and this repo has been indexed."
+ />
+ );
+ }
+
+ return (
+ <GraphContext.Provider value={ctxValue}>
+ <div className="relative w-full h-full">
+ {isLayouting && (
+ <div className="absolute inset-0 z-50 flex items-center justify-center bg-[var(--color-bg-root)]/60 backdrop-blur-sm rounded-lg">
+ <div className="flex items-center gap-3 text-sm text-[var(--color-text-secondary)]">
+ <Loader2 className="w-5 h-5 animate-spin text-[var(--color-accent-graph)]" />
+ Computing layout...
+ </div>
+ </div>
+ )}
+
+ <ReactFlow
+ nodes={filteredNodes}
+ edges={currentEdges}
+ nodeTypes={nodeTypes}
+ edgeTypes={edgeTypes}
+ onNodeClick={handleNodeClick}
+ onNodeDoubleClick={handleNodeDoubleClick}
+ onNodeContextMenu={handleNodeContextMenu}
+ fitView
+ fitViewOptions={{ padding: 0.15 }}
+ minZoom={0.02}
+ maxZoom={4}
+ proOptions={{ hideAttribution: true }}
+ className="!bg-transparent"
+ nodesDraggable={false}
+ defaultEdgeOptions={{ type: "dependency" }}
+ >
+ <Background variant={BackgroundVariant.Dots} gap={20} size={1} color="rgba(255,255,255,0.04)" />
+ <Controls
+ showInteractive={false}
+ className="!border-[var(--color-border-default)] !bg-[var(--color-bg-elevated)] !shadow-lg !shadow-black/20 [&>button]:!border-[var(--color-border-default)] [&>button]:!bg-[var(--color-bg-elevated)] [&>button]:!text-[var(--color-text-secondary)] [&>button:hover]:!bg-[var(--color-bg-overlay)] [&>button:hover]:!text-[var(--color-text-primary)]"
+ />
+ <MiniMap
+ nodeColor={minimapNodeColor}
+ maskColor="rgba(0, 0, 0, 0.6)"
+ className="!bg-[var(--color-bg-surface)] !border-[var(--color-border-default)] !shadow-lg !shadow-black/20 !rounded-lg"
+ pannable
+ zoomable
+ />
+ </ReactFlow>
+
+ {/* Breadcrumb — shown when drilled into a module */}
+ {isModuleView && isDrilledDown && (
+ <div className="absolute top-3 left-3 z-10">
+ <div className="flex items-center gap-1 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2.5 py-1.5 shadow-lg shadow-black/20">
+ <button
+ onClick={() => handleBreadcrumbClick(-1)}
+ className="flex items-center gap-1 text-[11px] 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) => {
+ // Show only the segment added at this level
+ 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-[11px] 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>
+ )}
+
+ {/* Toolbar */}
+ <div className="absolute top-3 right-3 z-10">
+ <GraphToolbar
+ viewMode={viewMode}
+ onViewChange={handleViewChange}
+ colorMode={colorMode}
+ onColorModeChange={setColorMode}
+ hideTests={hideTests}
+ onHideTestsChange={setHideTests}
+ onFitView={handleFitView}
+ showPathFinder={showPathFinder}
+ onTogglePathFinder={() => setShowPathFinder((s) => !s)}
+ />
+ </div>
+
+ {/* Path Finder */}
+ {showPathFinder && (
+ <div className="absolute top-14 right-3 z-10">
+ <PathFinderPanel
+ repoId={repoId}
+ onPathFound={handlePathFound}
+ onClear={handlePathClear}
+ onClose={() => setShowPathFinder(false)}
+ initialFrom={pathFrom}
+ initialTo={pathTo}
+ />
+ </div>
+ )}
+
+ {/* Legend */}
+ <div className="absolute bottom-3 left-3 z-10">
+ <GraphLegend
+ nodeCount={filteredNodes.length}
+ edgeCount={currentEdges.length}
+ colorMode={colorMode}
+ viewMode={viewMode}
+ />
+ </div>
+
+ {/* 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}
+ />
+ )}
+ </div>
+ </GraphContext.Provider>
+ );
+}
+
+// ---- Public component ----
+
+export interface GraphFlowProps {
+ repoId: string;
+ onNodeClick?: (nodeId: string, nodeType: string) => void | Promise<void>;
+ onNodeViewDocs?: (nodeId: string) => void;
+}
+
+export function GraphFlow(props: GraphFlowProps) {
+ return (
+ <ReactFlowProvider>
+ <GraphFlowInner {...props} />
+ </ReactFlowProvider>
+ );
+}
diff --git a/packages/web/src/components/graph/graph-legend.tsx b/packages/web/src/components/graph/graph-legend.tsx
new file mode 100644
index 000000000..35149fa9e
--- /dev/null
+++ b/packages/web/src/components/graph/graph-legend.tsx
@@ -0,0 +1,124 @@
+"use client";
+
+import { LANGUAGE_COLORS } from "@/lib/utils/confidence";
+import type { ColorMode, ViewMode } from "./graph-toolbar";
+
+const COMMUNITY_SAMPLE = [
+ { color: "#6366f1", label: "Community 1" },
+ { color: "#ec4899", label: "Community 2" },
+ { color: "#10b981", label: "Community 3" },
+ { color: "#f59e0b", label: "Community 4" },
+ { color: "#3b82f6", label: "Community 5" },
+ { color: "#a855f7", label: "Community 6" },
+];
+
+const LANGUAGE_LEGEND = [
+ { lang: "python", color: LANGUAGE_COLORS.python, label: "Python" },
+ { lang: "typescript", color: LANGUAGE_COLORS.typescript, label: "TypeScript" },
+ { lang: "go", color: LANGUAGE_COLORS.go, label: "Go" },
+ { lang: "rust", color: LANGUAGE_COLORS.rust, label: "Rust" },
+ { lang: "java", color: LANGUAGE_COLORS.java, label: "Java" },
+ { lang: "config", color: LANGUAGE_COLORS.config, label: "Config" },
+ { lang: "other", color: LANGUAGE_COLORS.other, label: "Other" },
+];
+
+interface GraphLegendProps {
+ nodeCount: number;
+ edgeCount: number;
+ colorMode: ColorMode;
+ viewMode: ViewMode;
+}
+
+export function GraphLegend({
+ nodeCount,
+ edgeCount,
+ colorMode,
+ viewMode,
+}: GraphLegendProps) {
+ return (
+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)]/80 backdrop-blur-sm p-2.5 text-xs space-y-1.5 min-w-[130px] max-w-[160px] shadow-lg shadow-black/20">
+ <div className="font-medium text-[var(--color-text-secondary)] tabular-nums">
+ {nodeCount} nodes &middot; {edgeCount} edges
+ </div>
+
+ <div className="border-t border-[var(--color-border-default)] pt-1.5 space-y-1">
+ {/* Doc status — always shown */}
+ <div className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
+ <span
+ className="w-2 h-2 rounded-full shrink-0"
+ style={{ background: "var(--color-node-documented)" }}
+ />
+ <span>Has docs</span>
+ </div>
+ <div className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
+ <span
+ className="w-2 h-2 rounded-full shrink-0"
+ style={{ background: "var(--color-node-undocumented)" }}
+ />
+ <span>No docs</span>
+ </div>
+ </div>
+
+ {/* Color mode legend */}
+ <div className="border-t border-[var(--color-border-default)] pt-1.5 space-y-1">
+ <p className="text-[9px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium mb-1">
+ {colorMode === "language" ? "Language" : colorMode === "community" ? "Community" : "Risk"}
+ </p>
+
+ {colorMode === "language" &&
+ LANGUAGE_LEGEND.map((l) => (
+ <div key={l.lang} className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
+ <span
+ className="w-2 h-2 rounded-full shrink-0"
+ style={{ background: l.color }}
+ />
+ <span>{l.label}</span>
+ </div>
+ ))}
+
+ {colorMode === "community" &&
+ COMMUNITY_SAMPLE.map((c, i) => (
+ <div key={i} className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
+ <span
+ className="w-2 h-2 rounded-full shrink-0"
+ style={{ background: c.color }}
+ />
+ <span>{c.label}</span>
+ </div>
+ ))}
+
+ {colorMode === "risk" && (
+ <>
+ <div className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
+ <span className="w-2 h-2 rounded-full shrink-0 bg-[#22c55e]" />
+ <span>Low risk</span>
+ </div>
+ <div className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
+ <span className="w-2 h-2 rounded-full shrink-0 bg-[#f59520]" />
+ <span>Medium risk</span>
+ </div>
+ <div className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
+ <span className="w-2 h-2 rounded-full shrink-0 bg-[#ef4444]" />
+ <span>High risk</span>
+ </div>
+ </>
+ )}
+ </div>
+
+ {/* View-specific info */}
+ {viewMode !== "module" && viewMode !== "full" && (
+ <div className="border-t border-[var(--color-border-default)] pt-1.5">
+ <p className="text-[9px] text-[var(--color-text-tertiary)]">
+ {viewMode === "dead" && "Showing unreachable files"}
+ {viewMode === "hotfiles" && "Most-committed files (30d)"}
+ {viewMode === "architecture" && "Entry-point reachable (3 hops)"}
+ </p>
+ </div>
+ )}
+
+ <p className="text-[9px] text-[var(--color-text-tertiary)] pt-1 border-t border-[var(--color-border-default)]">
+ Click &middot; Double-click &middot; Right-click
+ </p>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/graph/graph-minimap.tsx b/packages/web/src/components/graph/graph-minimap.tsx
deleted file mode 100644
index 8357fe0e6..000000000
--- a/packages/web/src/components/graph/graph-minimap.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-"use client";
-
-import { forwardRef } from "react";
-import { cn } from "@/lib/utils/cn";
-
-interface GraphMinimapProps {
- className?: string;
-}
-
-export const GraphMinimap = forwardRef<HTMLCanvasElement, GraphMinimapProps>(
- ({ className }, ref) => {
- return (
- <canvas
- ref={ref}
- width={160}
- height={120}
- className={cn(
- "rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]",
- className,
- )}
- />
- );
- },
-);
-GraphMinimap.displayName = "GraphMinimap";
diff --git a/packages/web/src/components/graph/graph-toolbar.tsx b/packages/web/src/components/graph/graph-toolbar.tsx
new file mode 100644
index 000000000..e9a4acc16
--- /dev/null
+++ b/packages/web/src/components/graph/graph-toolbar.tsx
@@ -0,0 +1,140 @@
+"use client";
+
+import {
+ Palette,
+ Network,
+ Shield,
+ EyeOff,
+ Maximize,
+ Route,
+ Boxes,
+ GitFork,
+ Skull,
+ Flame,
+ LayoutGrid,
+} from "lucide-react";
+import { Button } from "@/components/ui/button";
+
+export type ColorMode = "language" | "community" | "risk";
+export type ViewMode = "module" | "full" | "architecture" | "dead" | "hotfiles";
+
+interface GraphToolbarProps {
+ viewMode: ViewMode;
+ onViewChange: (mode: ViewMode) => void;
+ colorMode: ColorMode;
+ onColorModeChange: (mode: ColorMode) => void;
+ hideTests: boolean;
+ onHideTestsChange: (v: boolean) => void;
+ onFitView: () => void;
+ showPathFinder: boolean;
+ onTogglePathFinder: () => void;
+}
+
+const VIEW_MODES: { id: ViewMode; icon: typeof Boxes; label: string }[] = [
+ { id: "module", icon: Boxes, label: "Modules" },
+ { id: "full", icon: LayoutGrid, label: "Full Graph" },
+ { id: "architecture", icon: GitFork, label: "Architecture" },
+ { id: "dead", icon: Skull, label: "Dead Code" },
+ { id: "hotfiles", icon: Flame, label: "Hot Files" },
+];
+
+const COLOR_MODES: { id: ColorMode; icon: typeof Palette; label: string }[] = [
+ { id: "language", icon: Palette, label: "Language" },
+ { id: "community", icon: Network, label: "Community" },
+ { id: "risk", icon: Shield, label: "Risk" },
+];
+
+export function GraphToolbar({
+ viewMode,
+ onViewChange,
+ colorMode,
+ onColorModeChange,
+ hideTests,
+ onHideTestsChange,
+ onFitView,
+ showPathFinder,
+ onTogglePathFinder,
+}: GraphToolbarProps) {
+ return (
+ <div className="flex flex-col gap-1.5 items-end">
+ {/* View modes */}
+ <div className="flex gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-lg shadow-black/20">
+ {VIEW_MODES.map((m) => {
+ const Icon = m.icon;
+ const isActive = viewMode === m.id;
+ return (
+ <button
+ key={m.id}
+ onClick={() => onViewChange(m.id)}
+ className={`flex items-center gap-1.5 px-2 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)]"
+ }`}
+ title={m.label}
+ >
+ <Icon className="w-3 h-3" />
+ <span className="hidden lg:inline">{m.label}</span>
+ </button>
+ );
+ })}
+ </div>
+
+ {/* Color mode + actions row */}
+ <div className="flex gap-1.5 items-center">
+ {/* Color modes */}
+ <div className="flex gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-lg shadow-black/20">
+ {COLOR_MODES.map((m) => {
+ const Icon = m.icon;
+ const isActive = colorMode === m.id;
+ return (
+ <button
+ key={m.id}
+ onClick={() => onColorModeChange(m.id)}
+ className={`flex items-center gap-1 px-2 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)]"
+ }`}
+ title={m.label}
+ >
+ <Icon className="w-3 h-3" />
+ </button>
+ );
+ })}
+ </div>
+
+ {/* Action buttons */}
+ <div className="flex gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-lg shadow-black/20">
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={onTogglePathFinder}
+ className={`h-7 w-7 p-0 ${showPathFinder ? "text-[var(--color-accent-graph)]" : "text-[var(--color-text-tertiary)]"}`}
+ title="Find dependency path"
+ >
+ <Route className="w-3.5 h-3.5" />
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => onHideTestsChange(!hideTests)}
+ className={`h-7 w-7 p-0 ${hideTests ? "text-[var(--color-accent-graph)]" : "text-[var(--color-text-tertiary)]"}`}
+ title={hideTests ? "Show test files" : "Hide test files"}
+ >
+ <EyeOff className="w-3.5 h-3.5" />
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={onFitView}
+ className="h-7 w-7 p-0 text-[var(--color-text-tertiary)]"
+ title="Fit view"
+ >
+ <Maximize className="w-3.5 h-3.5" />
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/graph/graph-view-switcher.tsx b/packages/web/src/components/graph/graph-view-switcher.tsx
deleted file mode 100644
index 52a5d5f8b..000000000
--- a/packages/web/src/components/graph/graph-view-switcher.tsx
+++ /dev/null
@@ -1,172 +0,0 @@
-"use client";
-
-import { useState, useCallback, useEffect } from "react";
-import { Search, RotateCcw, AlertTriangle } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import { useDebounce } from "@/lib/hooks/use-debounce";
-import { searchNodes } from "@/lib/api/graph";
-import type { NodeSearchResult } from "@/lib/api/types";
-
-export type ViewMode = "module" | "ego" | "architecture" | "dead" | "hotfiles" | "full";
-
-const VIEWS: { id: ViewMode; label: string; warn?: boolean }[] = [
- { id: "module", label: "Module" },
- { id: "ego", label: "Neighborhood" },
- { id: "architecture", label: "Architecture" },
- { id: "dead", label: "Dead Code" },
- { id: "hotfiles", label: "Hot Files" },
- { id: "full", label: "Full Graph", warn: true },
-];
-
-interface GraphViewSwitcherProps {
- repoId: string;
- view: ViewMode;
- hops: number;
- days: number;
- onViewChange: (view: ViewMode) => void;
- onNodeSelect: (nodeId: string) => void;
- onHopsChange: (hops: number) => void;
- onDaysChange: (days: number) => void;
-}
-
-export function GraphViewSwitcher({
- repoId,
- view,
- hops,
- days,
- onViewChange,
- onNodeSelect,
- onHopsChange,
- onDaysChange,
-}: GraphViewSwitcherProps) {
- const [searchQuery, setSearchQuery] = useState("");
- const [searchResults, setSearchResults] = useState<NodeSearchResult[]>([]);
- const [showResults, setShowResults] = useState(false);
-
- const debouncedSearch = useDebounce(searchQuery, 300);
-
- useEffect(() => {
- if (!debouncedSearch.trim()) {
- setSearchResults([]);
- setShowResults(false);
- return;
- }
- searchNodes(repoId, debouncedSearch, 10)
- .then((results) => {
- setSearchResults(results);
- setShowResults(results.length > 0);
- })
- .catch(() => setSearchResults([]));
- }, [debouncedSearch, repoId]);
-
- const handleSelectNode = useCallback(
- (nodeId: string) => {
- onNodeSelect(nodeId);
- setSearchQuery("");
- setShowResults(false);
- },
- [onNodeSelect],
- );
-
- const showSearch = view === "ego" || view === "module";
-
- return (
- <div className="shrink-0 flex items-center gap-2 px-4 py-2 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)] flex-wrap">
- {/* View tabs */}
- <div className="flex items-center gap-1">
- {VIEWS.map((v) => (
- <Button
- key={v.id}
- size="sm"
- variant={view === v.id ? "default" : "ghost"}
- onClick={() => onViewChange(v.id)}
- className="h-7 px-2.5 text-xs gap-1"
- >
- {v.warn && <AlertTriangle className="h-3 w-3 text-amber-400" />}
- {v.label}
- </Button>
- ))}
- </div>
-
- <div className="h-4 w-px bg-[var(--color-border-default)]" />
-
- {/* File search */}
- {showSearch && (
- <div className="relative">
- <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
- <Input
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- onFocus={() => searchResults.length > 0 && setShowResults(true)}
- onBlur={() => setTimeout(() => setShowResults(false), 150)}
- placeholder="Search file…"
- className="h-7 pl-7 pr-3 w-48 text-xs"
- />
- {showResults && (
- <div className="absolute top-full left-0 mt-1 z-50 w-72 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-lg py-1">
- {searchResults.map((r) => (
- <button
- key={r.node_id}
- className="w-full px-3 py-1.5 text-left text-xs hover:bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]"
- onMouseDown={() => handleSelectNode(r.node_id)}
- >
- <span className="font-mono">{r.node_id}</span>
- <span className="ml-2 text-[var(--color-text-tertiary)]">{r.language}</span>
- </button>
- ))}
- </div>
- )}
- </div>
- )}
-
- {/* Hop depth (ego view) */}
- {view === "ego" && (
- <Select value={String(hops)} onValueChange={(v) => onHopsChange(Number(v))}>
- <SelectTrigger className="h-7 w-20 text-xs">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="1">1 hop</SelectItem>
- <SelectItem value="2">2 hops</SelectItem>
- <SelectItem value="3">3 hops</SelectItem>
- </SelectContent>
- </Select>
- )}
-
- {/* Days selector (hot files) */}
- {view === "hotfiles" && (
- <Select value={String(days)} onValueChange={(v) => onDaysChange(Number(v))}>
- <SelectTrigger className="h-7 w-20 text-xs">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="7">7 days</SelectItem>
- <SelectItem value="30">30 days</SelectItem>
- <SelectItem value="90">90 days</SelectItem>
- </SelectContent>
- </Select>
- )}
-
- <div className="ml-auto">
- <Button
- size="sm"
- variant="ghost"
- onClick={() => onViewChange("module")}
- className="h-7 px-2 text-xs gap-1"
- title="Reset to module view"
- >
- <RotateCcw className="h-3.5 w-3.5" />
- Reset
- </Button>
- </div>
- </div>
- );
-}
diff --git a/packages/web/src/components/graph/nodes/file-node.tsx b/packages/web/src/components/graph/nodes/file-node.tsx
new file mode 100644
index 000000000..4c2c73b91
--- /dev/null
+++ b/packages/web/src/components/graph/nodes/file-node.tsx
@@ -0,0 +1,107 @@
+"use client";
+
+import { memo, useContext } from "react";
+import { Handle, Position, type NodeProps } from "@xyflow/react";
+import { GraphContext } from "../graph-flow";
+import { languageColor } from "@/lib/utils/confidence";
+import type { FileNodeData } from "../elk-layout";
+
+const COMMUNITY_COLORS = [
+ "#6366f1", "#ec4899", "#10b981", "#f59e0b", "#3b82f6", "#a855f7",
+ "#14b8a6", "#f97316", "#84cc16", "#06b6d4", "#e11d48", "#8b5cf6",
+ "#22c55e", "#eab308", "#0ea5e9", "#d946ef", "#ef4444", "#78716c",
+ "#64748b", "#0891b2", "#059669", "#b45309", "#7c3aed", "#db2777",
+];
+
+function riskColor(score: number): string {
+ if (score <= 0.3) return "#22c55e";
+ if (score <= 0.7) return "#f59520";
+ return "#ef4444";
+}
+
+function FileNodeInner({ id, data }: NodeProps) {
+ const d = data as FileNodeData;
+ const ctx = useContext(GraphContext);
+
+ const isOnPath = ctx.highlightedPath.has(id);
+ const hasActivePath = ctx.highlightedPath.size > 0;
+ const isDimmed = hasActivePath && !isOnPath;
+
+ // Determine node accent color based on color mode
+ let accentColor: string;
+ switch (ctx.colorMode) {
+ case "risk": {
+ const score = ctx.riskScores.get(d.fullPath) ?? (d.pagerank * 3); // use pagerank as fallback proxy
+ accentColor = riskColor(Math.min(1, score));
+ break;
+ }
+ case "community":
+ accentColor = COMMUNITY_COLORS[d.communityId % COMMUNITY_COLORS.length];
+ break;
+ case "language":
+ default:
+ accentColor = languageColor(d.language);
+ break;
+ }
+
+ return (
+ <div
+ className="group relative rounded-lg border transition-all duration-200 cursor-pointer"
+ style={{
+ borderColor: isOnPath ? "var(--color-accent-graph)" : `${accentColor}60`,
+ background: `linear-gradient(135deg, ${accentColor}12 0%, var(--color-bg-surface) 70%)`,
+ opacity: isDimmed ? 0.15 : 1,
+ animation: isOnPath ? "graph-path-pulse 2s ease-in-out infinite" : undefined,
+ borderStyle: d.isTest ? "dashed" : "solid",
+ boxShadow: isOnPath
+ ? `0 0 16px ${accentColor}40`
+ : `0 2px 8px rgba(0,0,0,0.2)`,
+ }}
+ >
+ <Handle
+ type="target"
+ position={Position.Top}
+ className="!w-1.5 !h-1.5 !bg-[var(--color-border-subtle)] !border-none"
+ />
+
+ {/* Left accent bar */}
+ <div
+ className="absolute left-0 top-0 bottom-0 w-[3px] rounded-l-lg"
+ style={{ background: accentColor }}
+ />
+
+ <div className="flex items-center gap-2 px-3 py-2 pl-3.5">
+ {/* Doc status dot */}
+ <div
+ className="w-2 h-2 rounded-full shrink-0 ring-1 ring-black/10"
+ style={{
+ background: d.hasDoc
+ ? "var(--color-node-documented)"
+ : "var(--color-node-undocumented)",
+ }}
+ title={d.hasDoc ? "Has documentation" : "No documentation"}
+ />
+
+ {/* Label */}
+ <span className="text-xs font-mono text-[var(--color-text-primary)] truncate max-w-[110px]">
+ {d.label}
+ </span>
+
+ {/* Entry point badge */}
+ {d.isEntryPoint && (
+ <span className="shrink-0 text-[8px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-[var(--color-accent-graph)]/15 text-[var(--color-accent-graph)]">
+ EP
+ </span>
+ )}
+ </div>
+
+ <Handle
+ type="source"
+ position={Position.Bottom}
+ className="!w-1.5 !h-1.5 !bg-[var(--color-border-subtle)] !border-none"
+ />
+ </div>
+ );
+}
+
+export const FileNode = memo(FileNodeInner);
diff --git a/packages/web/src/components/graph/nodes/module-group-node.tsx b/packages/web/src/components/graph/nodes/module-group-node.tsx
new file mode 100644
index 000000000..dfc658b4c
--- /dev/null
+++ b/packages/web/src/components/graph/nodes/module-group-node.tsx
@@ -0,0 +1,118 @@
+"use client";
+
+import { memo, useContext } from "react";
+import { Handle, Position, type NodeProps } from "@xyflow/react";
+import { Folder, FileText } from "lucide-react";
+import { GraphContext } from "../graph-flow";
+import type { ModuleNodeData } from "../elk-layout";
+
+const COMMUNITY_COLORS = [
+ "#6366f1", "#ec4899", "#10b981", "#f59e0b", "#3b82f6", "#a855f7",
+ "#14b8a6", "#f97316", "#84cc16", "#06b6d4", "#e11d48", "#8b5cf6",
+ "#22c55e", "#eab308", "#0ea5e9", "#d946ef", "#ef4444", "#78716c",
+ "#64748b", "#0891b2", "#059669", "#b45309", "#7c3aed", "#db2777",
+];
+
+function docCoverageColor(pct: number): string {
+ if (pct >= 0.7) return "var(--color-node-documented)";
+ if (pct >= 0.3) return "var(--color-risk-medium)";
+ return "var(--color-risk-high)";
+}
+
+function ModuleGroupNodeInner({ id, data }: NodeProps) {
+ const d = data as ModuleNodeData;
+ const ctx = useContext(GraphContext);
+ const docPct = d.docCoveragePct ?? 0;
+
+ // Color mode determines the accent/border color
+ let accentColor: string;
+ switch (ctx.colorMode) {
+ case "risk":
+ accentColor = docCoverageColor(docPct); // use doc coverage as proxy for module risk
+ break;
+ case "community": {
+ // Use a hash of the module name to pick a community color
+ let hash = 0;
+ for (let i = 0; i < id.length; i++) hash = (hash * 31 + id.charCodeAt(i)) | 0;
+ accentColor = COMMUNITY_COLORS[Math.abs(hash) % COMMUNITY_COLORS.length];
+ break;
+ }
+ case "language":
+ default:
+ accentColor = "var(--color-accent-graph)";
+ break;
+ }
+
+ const isOnPath = ctx.highlightedPath.has(id);
+ const hasActivePath = ctx.highlightedPath.size > 0;
+ const isDimmed = hasActivePath && !isOnPath;
+
+ return (
+ <div
+ className="rounded-xl border-2 bg-[var(--color-bg-elevated)]/80 backdrop-blur-sm px-4 py-3 min-w-[180px] shadow-lg shadow-black/20 transition-all duration-200 cursor-pointer hover:shadow-[0_0_20px_rgba(245,149,32,0.12)]"
+ style={{
+ borderColor: isOnPath ? "var(--color-accent-graph)" : accentColor,
+ borderLeftWidth: 4,
+ opacity: isDimmed ? 0.15 : 1,
+ animation: isOnPath ? "graph-path-pulse 2s ease-in-out infinite" : undefined,
+ }}
+ >
+ <Handle
+ type="target"
+ position={Position.Top}
+ className="!w-2 !h-2 !bg-[var(--color-border-subtle)] !border-none"
+ />
+
+ {/* Header */}
+ <div className="flex items-center gap-2 mb-2">
+ <div
+ className="flex items-center justify-center w-6 h-6 rounded-md"
+ style={{ background: `${accentColor}22` }}
+ >
+ <Folder className="w-3.5 h-3.5" style={{ color: accentColor }} />
+ </div>
+ <span className="text-sm font-semibold text-[var(--color-text-primary)] truncate max-w-[140px]">
+ {d.label}
+ </span>
+ </div>
+
+ {/* Stats row */}
+ <div className="flex items-center gap-3 text-[10px] text-[var(--color-text-tertiary)]">
+ <span className="flex items-center gap-1">
+ <FileText className="w-3 h-3" />
+ {d.fileCount ?? 0} files
+ </span>
+ {d.symbolCount != null && d.symbolCount > 0 && (
+ <span>{d.symbolCount} sym</span>
+ )}
+ </div>
+
+ {/* Doc coverage bar */}
+ {d.docCoveragePct != null && (
+ <div className="mt-2">
+ <div className="flex items-center justify-between text-[9px] text-[var(--color-text-tertiary)] mb-0.5">
+ <span>Docs</span>
+ <span>{Math.round(docPct * 100)}%</span>
+ </div>
+ <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-500"
+ style={{
+ width: `${Math.max(2, Math.round(docPct * 100))}%`,
+ background: docCoverageColor(docPct),
+ }}
+ />
+ </div>
+ </div>
+ )}
+
+ <Handle
+ type="source"
+ position={Position.Bottom}
+ className="!w-2 !h-2 !bg-[var(--color-border-subtle)] !border-none"
+ />
+ </div>
+ );
+}
+
+export const ModuleGroupNode = memo(ModuleGroupNodeInner);
diff --git a/packages/web/src/components/graph/path-finder-panel.tsx b/packages/web/src/components/graph/path-finder-panel.tsx
new file mode 100644
index 000000000..095c184e5
--- /dev/null
+++ b/packages/web/src/components/graph/path-finder-panel.tsx
@@ -0,0 +1,271 @@
+"use client";
+
+import { useState, useEffect, useRef, useCallback } from "react";
+import { Route, Loader2, X, ArrowRight, Search, ChevronDown } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { getGraphPath, searchNodes } from "@/lib/api/graph";
+import { useDebounce } from "@/lib/hooks/use-debounce";
+import type { GraphPathResponse, NodeSearchResult } from "@/lib/api/types";
+
+interface PathFinderPanelProps {
+ repoId: string;
+ onPathFound: (pathNodes: string[]) => void;
+ onClear: () => void;
+ onClose: () => void;
+ initialFrom?: string;
+ initialTo?: string;
+}
+
+function NodeAutocomplete({
+ repoId,
+ value,
+ onChange,
+ placeholder,
+ onSubmit,
+}: {
+ repoId: string;
+ value: string;
+ onChange: (v: string) => void;
+ placeholder: string;
+ onSubmit?: () => void;
+}) {
+ const [results, setResults] = useState<NodeSearchResult[]>([]);
+ const [topNodes, setTopNodes] = useState<NodeSearchResult[]>([]);
+ const [showDropdown, setShowDropdown] = useState(false);
+ const debounced = useDebounce(value, 250);
+ const topLoaded = useRef(false);
+
+ // Load top nodes by pagerank once for the dropdown
+ useEffect(() => {
+ if (topLoaded.current) return;
+ topLoaded.current = true;
+ searchNodes(repoId, "", 20)
+ .then(setTopNodes)
+ .catch(() => {});
+ }, [repoId]);
+
+ // Search as user types
+ useEffect(() => {
+ if (!debounced.trim() || debounced.length < 2) {
+ setResults([]);
+ return;
+ }
+ searchNodes(repoId, debounced, 12)
+ .then((r) => {
+ setResults(r);
+ setShowDropdown(r.length > 0);
+ })
+ .catch(() => setResults([]));
+ }, [debounced, repoId]);
+
+ const displayResults = results.length > 0 ? results : topNodes;
+
+ const handleSelect = useCallback(
+ (nodeId: string) => {
+ onChange(nodeId);
+ setShowDropdown(false);
+ },
+ [onChange],
+ );
+
+ return (
+ <div className="relative">
+ <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-[var(--color-text-tertiary)]" />
+ <input
+ type="text"
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ onFocus={() => setShowDropdown(true)}
+ onBlur={() => setTimeout(() => setShowDropdown(false), 150)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ setShowDropdown(false);
+ onSubmit?.();
+ }
+ }}
+ placeholder={placeholder}
+ className="w-full h-8 pl-8 pr-8 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-inset)] text-xs font-mono text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] focus:outline-none focus:border-[var(--color-accent-graph)] focus:ring-1 focus:ring-[var(--color-accent-graph)]/30 transition-all"
+ />
+ <ChevronDown className="absolute right-2.5 top-1/2 -translate-y-1/2 w-3 h-3 text-[var(--color-text-tertiary)]" />
+ {showDropdown && displayResults.length > 0 && (
+ <div className="absolute top-full left-0 mt-1 w-full max-h-52 overflow-auto z-50 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-xl shadow-black/30 py-1">
+ {results.length === 0 && topNodes.length > 0 && (
+ <div className="px-3 py-1 text-[9px] text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ Top files by importance
+ </div>
+ )}
+ {displayResults.map((r) => (
+ <button
+ key={r.node_id}
+ className="w-full px-3 py-1.5 text-left text-xs hover:bg-[var(--color-bg-elevated)] transition-colors flex items-center gap-2"
+ onMouseDown={() => handleSelect(r.node_id)}
+ >
+ <span className="font-mono text-[var(--color-text-primary)] truncate flex-1">
+ {r.node_id}
+ </span>
+ <span className="text-[10px] text-[var(--color-text-tertiary)] capitalize shrink-0 tabular-nums">
+ {r.language}
+ </span>
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function PathFinderPanel({
+ repoId,
+ onPathFound,
+ onClear,
+ onClose,
+ initialFrom = "",
+ initialTo = "",
+}: PathFinderPanelProps) {
+ const [from, setFrom] = useState(initialFrom);
+ const [to, setTo] = useState(initialTo);
+ const [loading, setLoading] = useState(false);
+ const [result, setResult] = useState<GraphPathResponse | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ // Sync initial values when they change from context menu
+ useEffect(() => {
+ if (initialFrom) setFrom(initialFrom);
+ }, [initialFrom]);
+ useEffect(() => {
+ if (initialTo) setTo(initialTo);
+ }, [initialTo]);
+
+ const handleFind = useCallback(async () => {
+ if (!from.trim() || !to.trim()) return;
+ setLoading(true);
+ setError(null);
+ setResult(null);
+ onClear();
+ try {
+ const res = await getGraphPath(repoId, from.trim(), to.trim());
+ setResult(res);
+ if (res.path && res.path.length > 0) {
+ onPathFound(res.path);
+ } else {
+ setError("No path found between these nodes.");
+ }
+ } catch {
+ setError("No path found between these nodes.");
+ } finally {
+ setLoading(false);
+ }
+ }, [from, to, repoId, onPathFound, onClear]);
+
+ const handleClear = useCallback(() => {
+ setFrom("");
+ setTo("");
+ setResult(null);
+ setError(null);
+ onClear();
+ }, [onClear]);
+
+ return (
+ <div className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)]/90 backdrop-blur-md shadow-xl shadow-black/30 p-3 w-[280px] space-y-2">
+ {/* Header */}
+ <div className="flex items-center gap-2">
+ <Route className="w-3.5 h-3.5 text-[var(--color-accent-graph)]" />
+ <span className="text-xs font-semibold text-[var(--color-text-primary)]">
+ Find Path
+ </span>
+ <div className="ml-auto flex items-center gap-1">
+ {(result || error) && (
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={handleClear}
+ className="h-5 w-5 p-0"
+ aria-label="Clear results"
+ title="Clear results"
+ >
+ <X className="h-3 w-3" />
+ </Button>
+ )}
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={onClose}
+ className="h-5 w-5 p-0 text-[var(--color-text-tertiary)]"
+ aria-label="Close"
+ title="Close"
+ >
+ <X className="h-3 w-3" />
+ </Button>
+ </div>
+ </div>
+
+ {/* Inputs stacked */}
+ <div className="space-y-1.5">
+ <NodeAutocomplete
+ repoId={repoId}
+ value={from}
+ onChange={setFrom}
+ placeholder="From file..."
+ onSubmit={handleFind}
+ />
+ <NodeAutocomplete
+ repoId={repoId}
+ value={to}
+ onChange={setTo}
+ placeholder="To file..."
+ onSubmit={handleFind}
+ />
+ </div>
+
+ {/* Find button */}
+ <Button
+ size="sm"
+ onClick={handleFind}
+ disabled={!from.trim() || !to.trim() || loading}
+ className="w-full h-7 text-xs font-medium gap-1.5"
+ style={{
+ background: "var(--color-accent-graph)",
+ color: "#000",
+ }}
+ >
+ {loading ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Route className="h-3.5 w-3.5" />
+ )}
+ Find Path
+ </Button>
+
+ {/* Result */}
+ {result && result.path && result.path.length > 0 && (
+ <div className="rounded-lg bg-[var(--color-bg-inset)] border border-[var(--color-border-default)] p-2 space-y-1">
+ <p className="text-[10px] font-medium text-[var(--color-accent-graph)] uppercase tracking-wider">
+ {result.distance} {result.distance === 1 ? "hop" : "hops"}
+ </p>
+ <div className="space-y-0.5 max-h-28 overflow-auto">
+ {result.path.map((nodeName, i) => {
+ const shortName = nodeName.split("/").pop() ?? nodeName;
+ return (
+ <div key={i} className="flex items-center gap-1">
+ {i > 0 && (
+ <ArrowRight className="w-2.5 h-2.5 text-[var(--color-accent-graph)] shrink-0" />
+ )}
+ <span
+ className="text-[10px] font-mono text-[var(--color-text-secondary)] truncate"
+ title={nodeName}
+ >
+ {shortName}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ )}
+
+ {error && (
+ <p className="text-[10px] text-[var(--color-risk-high)]">{error}</p>
+ )}
+ </div>
+ );
+}
diff --git a/packages/web/src/components/graph/path-finder.tsx b/packages/web/src/components/graph/path-finder.tsx
deleted file mode 100644
index bf505e044..000000000
--- a/packages/web/src/components/graph/path-finder.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { Route, Loader2, X } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { getGraphPath } from "@/lib/api/graph";
-import type { GraphPathResponse } from "@/lib/api/types";
-
-interface PathFinderProps {
- repoId: string;
- onPathFound: (path: string[]) => void;
- onClear: () => void;
-}
-
-export function PathFinder({ repoId, onPathFound, onClear }: PathFinderProps) {
- const [from, setFrom] = useState("");
- const [to, setTo] = useState("");
- const [loading, setLoading] = useState(false);
- const [result, setResult] = useState<GraphPathResponse | null>(null);
- const [error, setError] = useState<string | null>(null);
-
- async function handleFind() {
- if (!from.trim() || !to.trim()) return;
- setLoading(true);
- setError(null);
- setResult(null);
- onClear();
- try {
- const res = await getGraphPath(repoId, from.trim(), to.trim());
- setResult(res);
- onPathFound(res.path.map((step) => step.node));
- } catch {
- setError("No path found between these nodes.");
- } finally {
- setLoading(false);
- }
- }
-
- function handleClear() {
- setFrom("");
- setTo("");
- setResult(null);
- setError(null);
- onClear();
- }
-
- return (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)]/90 backdrop-blur-sm p-3 space-y-2 w-64">
- <div className="flex items-center gap-1.5">
- <Route className="h-3.5 w-3.5 text-[var(--color-accent-primary)] shrink-0" />
- <span className="text-xs font-medium text-[var(--color-text-primary)]">Path Finder</span>
- </div>
-
- <div className="space-y-1.5">
- <Input
- value={from}
- onChange={(e) => setFrom(e.target.value)}
- placeholder="From node (file path)"
- className="h-7 text-xs font-mono"
- onKeyDown={(e) => e.key === "Enter" && handleFind()}
- />
- <Input
- value={to}
- onChange={(e) => setTo(e.target.value)}
- placeholder="To node (file path)"
- className="h-7 text-xs font-mono"
- onKeyDown={(e) => e.key === "Enter" && handleFind()}
- />
- </div>
-
- <div className="flex gap-1.5">
- <Button
- size="sm"
- onClick={handleFind}
- disabled={!from.trim() || !to.trim() || loading}
- className="flex-1 h-7 text-xs gap-1"
- >
- {loading ? (
- <Loader2 className="h-3 w-3 animate-spin" />
- ) : (
- <Route className="h-3 w-3" />
- )}
- Find
- </Button>
- {(result || error) && (
- <Button size="sm" variant="ghost" onClick={handleClear} className="h-7 w-7 p-0" aria-label="Clear path">
- <X className="h-3 w-3" />
- </Button>
- )}
- </div>
-
- {result && (
- <div className="text-xs text-[var(--color-text-secondary)] space-y-1">
- <p className="font-medium text-[var(--color-confidence-fresh)]">
- Path found — {result.distance} hops
- </p>
- <div className="max-h-24 overflow-auto space-y-0.5">
- {result.path.map((step, i) => (
- <div key={i} className="font-mono truncate text-[var(--color-text-tertiary)]">
- {i > 0 && <span className="text-[var(--color-accent-primary)] mr-1">→</span>}
- {step.node}
- </div>
- ))}
- </div>
- </div>
- )}
-
- {error && (
- <p className="text-xs text-[var(--color-confidence-outdated)]">{error}</p>
- )}
- </div>
- );
-}
diff --git a/packages/web/src/components/graph/use-elk-layout.ts b/packages/web/src/components/graph/use-elk-layout.ts
new file mode 100644
index 000000000..eb3c2a986
--- /dev/null
+++ b/packages/web/src/components/graph/use-elk-layout.ts
@@ -0,0 +1,128 @@
+"use client";
+
+import { useState, useEffect, useRef } from "react";
+import type { Node, Edge } from "@xyflow/react";
+import type {
+ GraphNodeResponse,
+ GraphEdgeResponse,
+ ModuleNodeResponse,
+ ModuleEdgeResponse,
+} from "@/lib/api/types";
+import { layoutFileGraph, layoutModuleGraph } from "./elk-layout";
+
+interface ElkLayoutResult {
+ nodes: Node[];
+ edges: Edge[];
+ isLayouting: boolean;
+}
+
+/** Compute ELK layout for a file-level graph (ego, architecture, full, dead, hot). */
+export function useFileElkLayout(
+ graphNodes: GraphNodeResponse[] | undefined,
+ graphEdges: GraphEdgeResponse[] | undefined,
+): ElkLayoutResult {
+ const [nodes, setNodes] = useState<Node[]>([]);
+ const [edges, setEdges] = useState<Edge[]>([]);
+ const [isLayouting, setIsLayouting] = useState(false);
+ const cacheKey = useRef("");
+
+ useEffect(() => {
+ if (!graphNodes || !graphEdges || graphNodes.length === 0) {
+ setNodes([]);
+ setEdges([]);
+ cacheKey.current = "";
+ return;
+ }
+
+ const key = `${graphNodes.length}:${graphEdges.length}:${graphNodes[0]?.node_id}`;
+ if (key === cacheKey.current) return;
+ cacheKey.current = key;
+
+ setIsLayouting(true);
+ layoutFileGraph(graphNodes, graphEdges)
+ .then(({ nodes: n, edges: e }) => {
+ setNodes(n);
+ setEdges(e);
+ })
+ .catch(() => {
+ const cols = Math.ceil(Math.sqrt(graphNodes.length));
+ setNodes(
+ graphNodes.map((node, i) => ({
+ id: node.node_id,
+ type: "fileNode",
+ position: { x: (i % cols) * 200, y: Math.floor(i / cols) * 80 },
+ data: {
+ label: node.node_id.split("/").pop() ?? node.node_id,
+ fullPath: node.node_id,
+ language: node.language,
+ symbolCount: node.symbol_count,
+ pagerank: node.pagerank,
+ betweenness: node.betweenness,
+ communityId: node.community_id,
+ isTest: node.is_test,
+ isEntryPoint: node.is_entry_point,
+ hasDoc: node.has_doc,
+ },
+ })),
+ );
+ setEdges([]);
+ })
+ .finally(() => setIsLayouting(false));
+ }, [graphNodes, graphEdges]);
+
+ return { nodes, edges, isLayouting };
+}
+
+/** Compute ELK layout for a module-level graph. Supports mixed modules + files via fileEntries. */
+export function useModuleElkLayout(
+ moduleNodes: ModuleNodeResponse[] | undefined,
+ moduleEdges: ModuleEdgeResponse[] | undefined,
+ fileEntries?: Map<string, GraphNodeResponse>,
+): ElkLayoutResult {
+ const [nodes, setNodes] = useState<Node[]>([]);
+ const [edges, setEdges] = useState<Edge[]>([]);
+ const [isLayouting, setIsLayouting] = useState(false);
+ const cacheKey = useRef("");
+
+ useEffect(() => {
+ if (!moduleNodes || !moduleEdges || moduleNodes.length === 0) {
+ setNodes([]);
+ setEdges([]);
+ cacheKey.current = "";
+ return;
+ }
+
+ const key = `mod:${moduleNodes.length}:${moduleEdges.length}:${moduleNodes[0]?.module_id}`;
+ if (key === cacheKey.current) return;
+ cacheKey.current = key;
+
+ setIsLayouting(true);
+ layoutModuleGraph(moduleNodes, moduleEdges, fileEntries)
+ .then(({ nodes: n, edges: e }) => {
+ setNodes(n);
+ setEdges(e);
+ })
+ .catch(() => {
+ const cols = Math.ceil(Math.sqrt(moduleNodes.length));
+ setNodes(
+ moduleNodes.map((m, i) => ({
+ id: m.module_id,
+ type: "moduleGroup",
+ position: { x: (i % cols) * 240, y: Math.floor(i / cols) * 100 },
+ data: {
+ label: m.module_id.split("/").pop() ?? m.module_id,
+ fullPath: m.module_id,
+ fileCount: m.file_count,
+ symbolCount: m.symbol_count,
+ avgPagerank: m.avg_pagerank,
+ docCoveragePct: m.doc_coverage_pct,
+ },
+ })),
+ );
+ setEdges([]);
+ })
+ .finally(() => setIsLayouting(false));
+ }, [moduleNodes, moduleEdges, fileEntries]);
+
+ return { nodes, edges, isLayouting };
+}
diff --git a/packages/web/src/lib/api/types.ts b/packages/web/src/lib/api/types.ts
index 3716ee11e..2f125b596 100644
--- a/packages/web/src/lib/api/types.ts
+++ b/packages/web/src/lib/api/types.ts
@@ -176,6 +176,7 @@ export interface GraphNodeResponse {
community_id: number;
is_test: boolean;
is_entry_point: boolean;
+ has_doc: boolean;
}
export interface GraphEdgeResponse {
@@ -190,9 +191,10 @@ export interface GraphExportResponse {
}
export interface GraphPathResponse {
- path: Array<{ node: string; relationship: string; edge_type: string }>;
+ path: string[];
distance: number;
explanation: string;
+ visual_context?: unknown;
}
export interface ModuleNodeResponse {
@@ -239,6 +241,7 @@ export interface DeadCodeGraphNodeResponse {
community_id: number;
is_test: boolean;
is_entry_point: boolean;
+ has_doc: boolean;
confidence_group: string;
}
@@ -257,6 +260,7 @@ export interface HotFilesNodeResponse {
community_id: number;
is_test: boolean;
is_entry_point: boolean;
+ has_doc: boolean;
commit_count: number;
}
diff --git a/packages/web/src/styles/globals.css b/packages/web/src/styles/globals.css
index f5db4b054..54a1bca15 100644
--- a/packages/web/src/styles/globals.css
+++ b/packages/web/src/styles/globals.css
@@ -54,6 +54,16 @@
--color-error: #ef4444;
--color-info: #5b9cf6;
+ /* ------------------------------------------------------------------ */
+ /* Graph — React Flow */
+ /* ------------------------------------------------------------------ */
+ --color-accent-graph: #f59520;
+ --color-risk-low: #22c55e;
+ --color-risk-medium: #f59520;
+ --color-risk-high: #ef4444;
+ --color-node-documented: #22c55e;
+ --color-node-undocumented: #64748b;
+
/* ------------------------------------------------------------------ */
/* Language Colors (graph nodes) */
/* ------------------------------------------------------------------ */
@@ -265,3 +275,31 @@ body {
.tabular-nums {
font-variant-numeric: tabular-nums;
}
+
+/* -------------------------------------------------------------------- */
+/* React Flow Dark Theme */
+/* -------------------------------------------------------------------- */
+
+.react-flow {
+ --xy-background-color: transparent;
+ --xy-minimap-background-color: var(--color-bg-surface);
+ --xy-minimap-mask-background: rgba(0, 0, 0, 0.6);
+ --xy-minimap-mask-stroke: none;
+ --xy-controls-button-background-color: var(--color-bg-elevated);
+ --xy-controls-button-background-color-hover: var(--color-bg-overlay);
+ --xy-controls-button-border-color: var(--color-border-default);
+ --xy-controls-button-color: var(--color-text-secondary);
+ --xy-controls-button-color-hover: var(--color-text-primary);
+ --xy-edge-stroke: rgba(91, 156, 246, 0.3);
+ --xy-edge-stroke-selected: var(--color-accent-graph);
+ --xy-node-border-radius: var(--radius-lg);
+}
+
+@keyframes graph-path-pulse {
+ 0%, 100% { box-shadow: 0 0 0 0 rgba(245, 149, 32, 0.4); }
+ 50% { box-shadow: 0 0 12px 4px rgba(245, 149, 32, 0.2); }
+}
+
+@keyframes graph-marching-ants {
+ to { stroke-dashoffset: -20; }
+}