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.

refactor(architecture): give the graph one scope control, and stop it spending 8 seconds arriving (#1150)

Raghav Chamadiyaa0a68d836d8e
diff --git a/packages/server/src/repowise/server/routers/graph/full_graph.py b/packages/server/src/repowise/server/routers/graph/full_graph.py
index 8e78d3651..85d4f2aec 100644
--- a/packages/server/src/repowise/server/routers/graph/full_graph.py
+++ b/packages/server/src/repowise/server/routers/graph/full_graph.py
@@ -47,12 +47,17 @@ def _flow_member_ids(
entry_ids: list[str],
max_depth: int = _FLOW_MAX_DEPTH,
) -> set[str]:
- """Node ids on the primary execution path from each entry point.
+ """Files on the primary execution path from each entry point.
In-memory mirror of ``mcp_server._graph_utils.bfs_trace`` (same rules:
``calls`` edges only, highest-confidence unvisited successor, confidence
>= 0.5, test/demo paths excluded) over the already-fetched edge list, so
the export doesn't re-query edges per hop.
+
+ ``calls`` edges only ever join symbol nodes, so the trace itself is a list
+ of ``path/to/file.py::symbol`` ids. The export carries files, so each step
+ is reduced to its containing file — the reservation is for "the files this
+ flow runs through", which is what the canvas can actually highlight.
"""
adjacency: dict[str, list[GraphEdge]] = {}
for e in edges:
@@ -79,7 +84,7 @@ def _flow_member_ids(
visited.add(best_id)
current = best_id
members |= visited
- return members
+ return {node_id.split("::")[0] for node_id in members}
@router.get("/{repo_id}/nodes/search", response_model=list[NodeSearchResult])
@@ -121,6 +126,15 @@ async def export_graph(
) -> GraphExportResponse:
"""Export the full dependency graph in D3 force-directed format.
+ File nodes only. ``graph_nodes`` also holds a symbol node per extracted
+ symbol — on this repo 28,205 of 31,397 rows — and PageRank ranks the two
+ kinds together, so 450 of the top 1,500 used to be symbols drawn as file
+ circles, labelled ``path/file.py::Symbol`` and carrying a ``fullPath`` that
+ is not a path. Nothing downstream reads ``node_type`` (checked: packages/ui
+ and the VS Code webview), so the client cannot tell them apart. Excluding
+ them buys back those 1,500 slots for real files and makes
+ ``total_node_count`` a count of files, which is what every caller labels it.
+
Large repos are capped with ``truncated=True``. Selection reserves slots
for dead-code files, hotspots, and execution-flow members (up to
``_RESERVED_CLASS_CAP`` each, highest PageRank first within a class) and
@@ -157,7 +171,7 @@ async def export_graph(
GraphNode.community_id,
)
)
- .where(GraphNode.repository_id == repo_id)
+ .where(GraphNode.repository_id == repo_id, GraphNode.node_type == "file")
.order_by(GraphNode.pagerank.desc())
)
all_nodes = node_result.scalars().all()
diff --git a/packages/ui/__tests__/graph/constants.test.ts b/packages/ui/__tests__/graph/constants.test.ts
index 7e1a7ad65..3e3473004 100644
--- a/packages/ui/__tests__/graph/constants.test.ts
+++ b/packages/ui/__tests__/graph/constants.test.ts
@@ -41,14 +41,27 @@ describe("getLayoutDuration", () => {
});
describe("label density", () => {
- it("uses 0.15 / 6px at or below 2000 nodes", () => {
- expect(getLabelDensity(2000)).toBe(0.15);
- expect(getLabelRenderedSizeThreshold(2000)).toBe(6);
+ it("uses 0.15 / 6px at or below 1200 nodes", () => {
+ expect(getLabelDensity(1200)).toBe(0.15);
+ expect(getLabelRenderedSizeThreshold(1200)).toBe(6);
});
- it("uses 0.07 / 8px above 2000 nodes", () => {
- expect(getLabelDensity(2001)).toBe(0.07);
- expect(getLabelRenderedSizeThreshold(2001)).toBe(8);
+ it("thins out above 1200 nodes", () => {
+ expect(getLabelDensity(1201)).toBe(0.07);
+ expect(getLabelRenderedSizeThreshold(1201)).toBe(8);
+ });
+
+ it("thins out again near the load-more ceiling", () => {
+ expect(getLabelDensity(2501)).toBe(0.05);
+ expect(getLabelRenderedSizeThreshold(2501)).toBe(10);
+ });
+
+ // Regression guard: both thresholds used to step at 2,000 while the export
+ // was capped at 1,500, so the "large graph" branch could never be reached on
+ // any repo. Every rung must sit inside what the loader can actually deliver.
+ it("steps below the node cap the loader can reach", () => {
+ expect(getLabelDensity(1500)).toBeLessThan(0.15);
+ expect(getLabelRenderedSizeThreshold(1500)).toBeGreaterThan(6);
});
});
diff --git a/packages/ui/__tests__/graph/graph-flow.test.tsx b/packages/ui/__tests__/graph/graph-flow.test.tsx
index cd26f2445..00bdc0056 100644
--- a/packages/ui/__tests__/graph/graph-flow.test.tsx
+++ b/packages/ui/__tests__/graph/graph-flow.test.tsx
@@ -41,8 +41,6 @@ const fileNode = (id: string, language: string) => ({
// Minimal prop set — no graphs supplied, so the canvas renders its empty state
// while the toolbar (and its color-mode control) still mounts.
const baseProps = {
- moduleGraph: undefined,
- isLoadingModuleGraph: false,
fullGraph: undefined,
isLoadingFullGraph: false,
architectureGraph: undefined,
@@ -143,13 +141,20 @@ describe("GraphFlow shell", () => {
expect(screen.getByText("No dead files in this repo")).toBeTruthy();
});
- it("opens the flow picker on the module overview and jumps to the full graph on selection", () => {
- const onViewModeChange = vi.fn();
+ it("highlights the FILES an execution flow runs through, not its symbols", () => {
+ // `calls` edges only ever join symbol nodes, so a trace is a list of
+ // `file::symbol` ids while this canvas draws files. The trace head focused
+ // must therefore be the containing file, or the picker silently does
+ // nothing on every repo.
+ vi.useFakeTimers();
render(
<GraphFlow
{...baseProps}
- initialViewMode="module"
- onViewModeChange={onViewModeChange}
+ initialViewMode="full"
+ fullGraph={{
+ nodes: [fileNode("app.py", "python"), fileNode("core.py", "python")],
+ links: [],
+ }}
executionFlows={{
total_entry_points: 1,
flows: [
@@ -170,10 +175,11 @@ describe("GraphFlow shell", () => {
fireEvent.click(screen.getByRole("button", { name: "Execution flows" }));
expect(screen.getByText("Execution Flows")).toBeTruthy();
- // Selecting a flow from the module overview switches to the file-level
- // graph so the trace can actually be highlighted.
fireEvent.click(screen.getByText("main"));
- expect(onViewModeChange).toHaveBeenCalledWith("full");
+ act(() => {
+ vi.advanceTimersByTime(900);
+ });
+ expect(focusNodeSpy).toHaveBeenCalledWith("app.py");
});
it("focuses the flow trace head once the graph gains it, exactly once", () => {
@@ -206,8 +212,12 @@ describe("GraphFlow shell", () => {
});
expect(focusNodeSpy).not.toHaveBeenCalled();
- // The full graph lands: the deferred focus fires once for the trace head.
- const nodes = flows.flows[0]!.trace.map((id) => fileNode(id, "python"));
+ // The full graph lands: the deferred focus fires once for the trace head's
+ // containing FILE (the trace itself names symbols, which this canvas has
+ // no nodes for).
+ const nodes = flows.flows[0]!.trace.map((id) =>
+ fileNode(id.split("::")[0]!, "python"),
+ );
rerender(
<GraphFlow
{...baseProps}
@@ -216,7 +226,7 @@ describe("GraphFlow shell", () => {
fullGraph={{ nodes, links: [] }}
/>,
);
- expect(focusNodeSpy).toHaveBeenCalledWith("app.py::main");
+ expect(focusNodeSpy).toHaveBeenCalledWith("app.py");
expect(focusNodeSpy).toHaveBeenCalledTimes(1);
// Later graph changes must not re-steer the camera for the same flow.
@@ -231,7 +241,7 @@ describe("GraphFlow shell", () => {
expect(focusNodeSpy).toHaveBeenCalledTimes(1);
});
- it("refuses hierarchical layout above the ELK cap and explains why", () => {
+ it("shows hierarchical layout as unavailable above the ELK cap, with the reason", () => {
const nodes = Array.from({ length: 501 }, (_, i) =>
fileNode(`f${i}.ts`, "typescript"),
);
@@ -243,14 +253,45 @@ describe("GraphFlow shell", () => {
/>,
);
- fireEvent.click(screen.getByRole("button", { name: "Hierarchical" }));
+ const button = screen.getByRole("button", { name: "Hierarchical" });
- // The mode must not activate — force stays on — and the notice says why.
- expect(
- screen.getByRole("button", { name: "Hierarchical" }).getAttribute("aria-pressed"),
- ).toBe("false");
- expect(screen.getByRole("status").textContent).toContain(
- "Hierarchical layout is limited to 500 nodes",
+ // Unavailable up front rather than live-then-refusing. ELK's 500-node cap
+ // sits below the graph loader's 1,500-node floor, and "load more" only
+ // raises it — so on any repo past the cap this control could never act,
+ // and used to say so only after you pressed it.
+ expect(button.hasAttribute("disabled")).toBe(true);
+ expect(button.getAttribute("title")).toContain(
+ "Hierarchical layout needs 500 nodes or fewer",
+ );
+
+ // The reason must not offer a remedy that cannot work. The module filter,
+ // the community filter and search all dim rather than remove, so none of
+ // them changes `graph.order`, which is the number this cap is measured
+ // against — an earlier version told the reader to use exactly those.
+ expect(button.getAttribute("title")).not.toMatch(
+ /module filter|Modules scope|narrow the view/i,
);
+
+ // Clicking a disabled control changes nothing.
+ fireEvent.click(button);
+ expect(button.getAttribute("aria-pressed")).toBe("false");
+ });
+
+ it("leaves hierarchical layout available when the graph fits under the cap", () => {
+ const nodes = Array.from({ length: 40 }, (_, i) =>
+ fileNode(`f${i}.ts`, "typescript"),
+ );
+ render(
+ <GraphFlow
+ {...baseProps}
+ initialViewMode="full"
+ fullGraph={{ nodes, links: [] }}
+ />,
+ );
+
+ const button = screen.getByRole("button", { name: "Hierarchical" });
+ expect(button.hasAttribute("disabled")).toBe(false);
+ fireEvent.click(button);
+ expect(button.getAttribute("aria-pressed")).toBe("true");
});
});
diff --git a/packages/ui/__tests__/graph/use-module-filter.test.ts b/packages/ui/__tests__/graph/use-module-filter.test.ts
new file mode 100644
index 000000000..895413e71
--- /dev/null
+++ b/packages/ui/__tests__/graph/use-module-filter.test.ts
@@ -0,0 +1,55 @@
+import { describe, it, expect } from "vitest";
+import { moduleGroupFor } from "../../src/graph/use-module-filter.js";
+
+describe("moduleGroupFor", () => {
+ it("groups on two path segments, not the top-level directory", () => {
+ expect(moduleGroupFor("packages/core/src/repowise/core/pipeline/persist.py")).toBe(
+ "packages/core",
+ );
+ expect(moduleGroupFor("packages/ui/src/graph/graph-flow.tsx")).toBe("packages/ui");
+ expect(moduleGroupFor("tests/unit/server/test_graph.py")).toBe("tests/unit");
+ });
+
+ it("takes the second segment only when it is a directory", () => {
+ // Otherwise `tests/conftest.py` invents a one-file module sitting beside
+ // the real `tests/unit`.
+ expect(moduleGroupFor("tests/conftest.py")).toBe("tests");
+ expect(moduleGroupFor("scripts/build.mjs")).toBe("scripts");
+ });
+
+ it("buckets root-level files and every flavour of external", () => {
+ expect(moduleGroupFor("README.md")).toBe("(repo root)");
+ expect(moduleGroupFor("external:next/navigation")).toBe("external");
+ expect(moduleGroupFor("external:@testing-library/react")).toBe("external");
+ // `framework:` ids are third-party too — the same trap `isExternalModuleId`
+ // exists to close.
+ expect(moduleGroupFor("framework:django/db")).toBe("external");
+ });
+
+ it("partitions this repo instead of dimming a sliver of it", () => {
+ // The whole reason the Modules *scope* was replaced by a filter: on the
+ // real export, `packages/` alone holds 92% of the files, so a top-level
+ // grouping would offer a "filter" that dims 8% of the canvas. Two segments
+ // split the same files into groups no single one of which dominates.
+ const paths = [
+ ...Array.from({ length: 575 }, (_, i) => `packages/core/src/a${i}.py`),
+ ...Array.from({ length: 307 }, (_, i) => `packages/ui/src/b${i}.tsx`),
+ ...Array.from({ length: 138 }, (_, i) => `packages/server/src/c${i}.py`),
+ ...Array.from({ length: 127 }, (_, i) => `tests/unit/d${i}.py`),
+ ];
+ const counts = new Map<string, number>();
+ for (const p of paths) {
+ const g = moduleGroupFor(p);
+ counts.set(g, (counts.get(g) ?? 0) + 1);
+ }
+
+ expect([...counts.keys()].sort()).toEqual([
+ "packages/core",
+ "packages/server",
+ "packages/ui",
+ "tests/unit",
+ ]);
+ const largest = Math.max(...counts.values()) / paths.length;
+ expect(largest).toBeLessThan(0.6);
+ });
+});
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 31eea2114..2cdde66f5 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -22,6 +22,7 @@
"./graph/context": "./src/graph/context.ts",
"./graph/elk-layout": "./src/graph/elk-layout.ts",
"./graph/use-elk-layout": "./src/graph/use-elk-layout.ts",
+ "./graph/use-module-filter": "./src/graph/use-module-filter.ts",
"./graph/nodes/*": "./src/graph/nodes/*.tsx",
"./graph/edges/*": "./src/graph/edges/*.tsx",
"./graph/*": "./src/graph/*.tsx",
diff --git a/packages/ui/src/graph/graph-flow-helpers.ts b/packages/ui/src/graph/graph-flow-helpers.ts
index 6c6b4d53d..495a69266 100644
--- a/packages/ui/src/graph/graph-flow-helpers.ts
+++ b/packages/ui/src/graph/graph-flow-helpers.ts
@@ -8,6 +8,26 @@
* result handler — they highlight the same way, so the key construction lives
* here once. Mirrors Sigma's `source→target` edge-key convention.
*/
+/**
+ * Collapse an execution-flow trace onto the files it runs through.
+ *
+ * `calls` edges only ever connect symbol nodes, so a trace is a list of
+ * `path/to/file.py::symbol` ids — but this canvas draws files. Highlighting the
+ * raw trace therefore matched only the handful of symbol nodes that happened to
+ * survive the export's node cap, and matches nothing at all now that the export
+ * is file-only. Mapping each step onto its containing file highlights the route
+ * the reader can actually see, and collapses consecutive steps within one file
+ * so a 6-symbol trace through 2 files reads as 2 hops, not 6.
+ */
+export function traceToFileTrace(trace: readonly string[]): string[] {
+ const files: string[] = [];
+ for (const id of trace) {
+ const file = id.split("::")[0] ?? id;
+ if (files[files.length - 1] !== file) files.push(file);
+ }
+ return files;
+}
+
export function traceToEdgeKeys(nodes: readonly string[]): Set<string> {
const edgeKeys = new Set<string>();
for (let i = 0; i < nodes.length - 1; i++) {
diff --git a/packages/ui/src/graph/graph-flow.tsx b/packages/ui/src/graph/graph-flow.tsx
index 13eed7938..710faf841 100644
--- a/packages/ui/src/graph/graph-flow.tsx
+++ b/packages/ui/src/graph/graph-flow.tsx
@@ -9,11 +9,11 @@ import {
type ReactNode,
} from "react";
import { useTheme } from "next-themes";
-import { ChevronRight, Home, X } from "lucide-react";
+import { X } from "lucide-react";
import { Skeleton } from "../ui/skeleton";
import { EmptyState } from "../shared/empty-state";
import { type Signal } from "./context";
-import { groupNodesAsModules, type FileNodeData, type ModuleNodeData } from "./elk-layout";
+import { type FileNodeData, type ModuleNodeData } from "./elk-layout";
// Resting zoom when easing the camera onto a constellation hub. Looser than the
// default file-node focus (0.15) so the hub *and* its surrounding cluster stay
@@ -22,33 +22,21 @@ const HUB_FOCUS_RATIO = 0.45;
// Below this node count file graphs build synchronously; at or above it we
// build in chunks off the critical path (see sigmaGraph below).
const ASYNC_BUILD_THRESHOLD = 1000;
-// One-time "double-click to expand" hint for the modules scope.
-const MODULE_HINT_KEY = "repowise-graph-module-hint";
-
-/** Deterministic 0–1 value from a string (FNV-1a) — stable layout jitter. */
-function hashUnit(s: string): number {
- let h = 0x811c9dc5;
- for (let i = 0; i < s.length; i++) {
- h ^= s.charCodeAt(i);
- h = Math.imul(h, 0x01000193);
- }
- return (h >>> 0) / 0xffffffff;
-}
-import { useExpandedModules } from "./use-expanded-modules";
+
import { useExpandedHubs } from "./use-expanded-hubs";
-import { traceToEdgeKeys } from "./graph-flow-helpers";
+import { traceToEdgeKeys, traceToFileTrace } from "./graph-flow-helpers";
import { useGraphContextMenu } from "./use-graph-context-menu";
import { useGraphSearch } from "./use-graph-search";
import { useCommunityFilter } from "./use-community-filter";
+import { useModuleFilter } from "./use-module-filter";
import { useGraphKeyboardShortcuts } from "./use-graph-keyboard-shortcuts";
-import { GraphToolbar, type ColorMode, type ViewMode, type LayoutMode, type GraphTheme, type Scope } from "./graph-toolbar";
+import { GraphToolbar, type ColorMode, type ViewMode, type LayoutMode, type GraphTheme } from "./graph-toolbar";
import { GraphLegend } from "./graph-legend";
import { GraphContextMenu } from "./graph-context-menu";
import { GraphInspectionPanel } from "./graph-inspection-panel";
import { GraphShortcutHelp } from "./graph-shortcut-help";
import type {
GraphExport,
- ModuleGraph,
ExecutionFlows,
CommunitySummaryItem,
ArchitectureGraph,
@@ -58,10 +46,6 @@ import { SigmaCanvas, type SigmaCanvasHandle } from "./sigma/sigma-canvas";
import {
fileGraphToGraphology,
fileGraphToGraphologyAsync,
- moduleGraphToGraphology,
- groupFilesAsModules,
- settleGraph,
- isExternalModuleId,
} from "./sigma/graphology-adapter";
import {
architectureToGraphology,
@@ -73,17 +57,8 @@ import { ELK_MAX_NODES, elkSkipReason } from "./sigma/use-elk-sigma-layout";
import type { SigmaNodeAttributes, SigmaEdgeAttributes } from "./sigma/types";
import type GraphologyGraph from "graphology";
import { useEgoFilter } from "./sigma/use-ego-filter";
-import {
- NODE_BASE_SIZES,
- EDGE_COLORS,
- getScaledNodeSize,
- getNodeMass,
- languageColor as sigmaLanguageColor,
-} from "./sigma/constants";
export interface GraphFlowProps {
- moduleGraph: ModuleGraph | undefined;
- isLoadingModuleGraph: boolean;
fullGraph: GraphExport | undefined;
isLoadingFullGraph: boolean;
architectureGraph: GraphExport | undefined;
@@ -106,6 +81,18 @@ export interface GraphFlowProps {
communities?: CommunitySummaryItem[];
executionFlows?: ExecutionFlows;
initialViewMode?: ViewMode;
+ /** Controlled scope. Scope is now steered from the page's section header
+ * (`GraphScopeSwitcher`) rather than from a pill cluster on the canvas, so
+ * the host owns the value and URL-syncs it. Omit to let the component track
+ * its own, seeded by {@link initialViewMode}. */
+ viewMode?: ViewMode;
+ /** The module filter's current selection (a path prefix from
+ * `moduleGroupFor`), or null for "all modules". Controlled by the host so
+ * the control can live in the section header beside the scope switcher. */
+ activeModule?: string | null;
+ /** Fired with the module groups present in the rendered graph, so the host
+ * can populate its filter control. Counts are of nodes actually drawn. */
+ onModuleGroupsChange?: (groups: { id: string; fileCount: number }[]) => void;
/** Initial node color mode (uncontrolled seed). Hosts derive this from their
* URL state instead of the component reading window.location. Ignored when
* {@link colorMode} is supplied. */
@@ -120,8 +107,6 @@ export interface GraphFlowProps {
/** Fired when the node color mode changes (toolbar or 1/2/3 shortcut) so
* hosts can sync it to the URL. */
onColorModeChange?: (mode: ColorMode) => void;
- onModulePathChange?: (path: string[]) => void;
- onExpandedModulesChange?: (expanded: Set<string>) => void;
onNodeClick?: (nodeId: string, nodeType: string) => void | Promise<void>;
onNodeViewDocs?: (nodeId: string) => void;
/** "Symbols" action in the inspection panel — jump to the symbols view
@@ -147,16 +132,10 @@ export interface GraphFlowProps {
* hosting page dismiss any competing right-rail panel (doc panel etc.)
* so the right side is a single sidebar. */
onCommunityPanelOpen?: (communityId: number) => void;
- /** Restricts the toolbar's scope cluster. Explore passes `["modules","full"]`
- * so the constellation scope (now the Knowledge Graph view's Communities
- * lens) is not reachable from here. Defaults to all scopes. */
- availableScopes?: Scope[];
}
export function GraphFlow(props: GraphFlowProps) {
const {
- moduleGraph,
- isLoadingModuleGraph,
fullGraph,
isLoadingFullGraph,
constellationGraph,
@@ -171,13 +150,14 @@ export function GraphFlow(props: GraphFlowProps) {
communities,
executionFlows,
initialViewMode,
+ viewMode: controlledViewMode,
+ activeModule: controlledActiveModule,
+ onModuleGroupsChange,
initialColorMode,
colorMode: controlledColorMode,
initialSelectedNode,
onViewModeChange,
onColorModeChange,
- onModulePathChange,
- onExpandedModulesChange,
onNodeClick,
onNodeViewDocs,
onNodeViewSymbols,
@@ -185,15 +165,19 @@ export function GraphFlow(props: GraphFlowProps) {
renderPathFinder,
renderCommunityPanel,
onCommunityPanelOpen,
- availableScopes,
} = props;
const sigmaRef = useRef<SigmaCanvasHandle>(null);
const focusTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
// ---- Core state ----
- // Default scope is the constellation (radial Knowledge Graph).
- const [viewMode, setViewMode] = useState<ViewMode>(initialViewMode ?? "architecture");
+ // Default scope is the constellation (radial Knowledge Graph). Controlled by
+ // the host when `viewMode` is supplied — the scope switcher lives in the
+ // page's section header now, so the URL is the source of truth.
+ const [viewModeState, setViewModeState] = useState<ViewMode>(
+ initialViewMode ?? "architecture",
+ );
+ const viewMode = controlledViewMode ?? viewModeState;
// Color mode is controlled by the host when `colorMode` is supplied
// (URL-synced); otherwise the component tracks it locally, seeded by
// `initialColorMode`. The wrapped setter routes through the host callback in
@@ -244,42 +228,6 @@ export function GraphFlow(props: GraphFlowProps) {
});
const hideTests = activeSignals.has("hideTests");
- // Expand/collapse modules (replaces drill-down for most use cases)
- const { expandedModules, toggleModule, collapseAll } = useExpandedModules();
- const hasExpandedModules = expandedModules.size > 0;
-
- // External `external:*` dependency modules are hidden by default — they
- // outnumber the repo's own modules and drown the layout. Toggle in toolbar.
- const [showExternals, setShowExternals] = useState(false);
- const externalCount = useMemo(
- () =>
- moduleGraph
- ? moduleGraph.nodes.reduce(
- (n, mod) => n + (isExternalModuleId(mod.module_id) ? 1 : 0),
- 0,
- )
- : 0,
- [moduleGraph],
- );
-
- // One-time "double-click a module to expand it" hint (persists dismissal).
- const [moduleHintDismissed, setModuleHintDismissed] = useState<boolean>(() => {
- if (typeof window === "undefined") return true;
- try {
- return window.localStorage.getItem(MODULE_HINT_KEY) === "1";
- } catch {
- return true;
- }
- });
- const dismissModuleHint = useCallback(() => {
- setModuleHintDismissed(true);
- try {
- window.localStorage.setItem(MODULE_HINT_KEY, "1");
- } catch {
- /* private mode — session-only dismissal */
- }
- }, []);
-
// Expand/collapse constellation hubs (radial blossom). Esc collapses the most
// recently expanded hub; multiple hubs may be open at once.
const { expandedHubs, toggleHub, collapseLast, collapseAll: collapseAllHubs } =
@@ -289,19 +237,6 @@ export function GraphFlow(props: GraphFlowProps) {
onExpandedHubsChange?.(expandedHubs);
}, [expandedHubs, onExpandedHubsChange]);
- // Legacy drill-down (breadcrumb nav, kept for deep-dive via context menu)
- const [modulePath, setModulePath] = useState<string[]>([]);
- const currentPrefix = modulePath.length > 0 ? (modulePath[modulePath.length - 1] ?? "") : "";
- const isDrilledDown = modulePath.length > 0;
-
- useEffect(() => {
- onModulePathChange?.(modulePath);
- }, [modulePath, onModulePathChange]);
-
- useEffect(() => {
- onExpandedModulesChange?.(expandedModules);
- }, [expandedModules, onExpandedModulesChange]);
-
// Context menu (state + dismiss-on-click/Escape lifecycle)
const { ctxMenu, setCtxMenu } = useGraphContextMenu();
@@ -362,7 +297,6 @@ export function GraphFlow(props: GraphFlowProps) {
);
// ---- Derived state ----
- const isModuleView = viewMode === "module";
const isUnified = viewMode === "unified";
// The "architecture" scope renders the radial community constellation.
const isConstellation = viewMode === "architecture";
@@ -433,13 +367,7 @@ export function GraphFlow(props: GraphFlowProps) {
}));
}, [constellationGraph]);
- // Drill-down data
- const drillDownData = useMemo(() => {
- if (!isDrilledDown || !fullGraph) return null;
- return groupNodesAsModules(fullGraph.nodes, fullGraph.links, currentPrefix);
- }, [isDrilledDown, fullGraph, currentPrefix]);
-
- // File-level graph data for non-module views
+ // File-level graph data for each scope
const fileGraphData = useMemo(() => {
switch (viewMode) {
case "full":
@@ -461,8 +389,6 @@ export function GraphFlow(props: GraphFlowProps) {
// Loading state
const isLoading =
- (isModuleView && !isDrilledDown) ? isLoadingModuleGraph :
- isDrilledDown ? isLoadingFullGraph :
viewMode === "full" || viewMode === "unified" ? isLoadingFullGraph :
viewMode === "architecture" ? !!isLoadingConstellationGraph :
viewMode === "dead" ? isLoadingDeadCodeGraph :
@@ -489,167 +415,13 @@ export function GraphFlow(props: GraphFlowProps) {
deadCodeGraph?.dead_total ?? fullGraph?.dead_total ?? null;
const hotTotal = hotFilesGraph?.hot_total ?? fullGraph?.hot_total ?? null;
- // Pre-build indexes for O(1) module expansion lookups (Fix 1.1)
- const fullGraphIndexes = useMemo(() => {
- if (!fullGraph) return null;
- const moduleChildIndex = new Map<string, typeof fullGraph.nodes>();
- const nodeEdgeIndex = new Map<string, typeof fullGraph.links>();
-
- for (const node of fullGraph.nodes) {
- const parts = node.node_id.split("/");
- for (let depth = 1; depth < parts.length; depth++) {
- const prefix = parts.slice(0, depth).join("/");
- let children = moduleChildIndex.get(prefix);
- if (!children) { children = []; moduleChildIndex.set(prefix, children); }
- children.push(node);
- }
- }
- for (const link of fullGraph.links) {
- let srcEdges = nodeEdgeIndex.get(link.source);
- if (!srcEdges) { srcEdges = []; nodeEdgeIndex.set(link.source, srcEdges); }
- srcEdges.push(link);
- let tgtEdges = nodeEdgeIndex.get(link.target);
- if (!tgtEdges) { tgtEdges = []; nodeEdgeIndex.set(link.target, tgtEdges); }
- tgtEdges.push(link);
- }
- return { moduleChildIndex, nodeEdgeIndex };
- }, [fullGraph]);
-
// Build Graphology graph for Sigma rendering.
//
- // Module / drill-down / small file graphs build synchronously here. Large
- // file graphs (>= ASYNC_BUILD_THRESHOLD) are deferred off the critical path:
- // this memo returns null and the effect below constructs them in chunks,
- // keeping the loading state up until the first frame is ready.
+ // Small file graphs build synchronously here. Large ones
+ // (>= ASYNC_BUILD_THRESHOLD) are deferred off the critical path: this memo
+ // returns null and the effect below constructs them in chunks, keeping the
+ // loading state up until the first frame is ready.
const syncSigmaGraph = useMemo(() => {
- if (isModuleView) {
- if (isDrilledDown && fullGraph) {
- return settleGraph(groupFilesAsModules(fullGraph, { prefix: currentPrefix }));
- }
-
- if (!moduleGraph) return null;
-
- const moduleOpts = {
- hideExternals: !showExternals,
- ...(communities ? { communities } : {}),
- };
-
- if (expandedModules.size === 0 || !fullGraph || !fullGraphIndexes) {
- // Settle synchronously so the first painted frame is the final layout
- // (no FA2 convergence animation collapsing the graph into a blob).
- return settleGraph(moduleGraphToGraphology(moduleGraph, moduleOpts));
- }
-
- const graph = moduleGraphToGraphology(moduleGraph, moduleOpts);
-
- for (const moduleId of expandedModules) {
- if (!graph.hasNode(moduleId)) continue;
-
- const childNodes = fullGraphIndexes.moduleChildIndex.get(moduleId) ?? [];
- // No file-level children in the loaded graph (e.g. a docs-only module
- // under a capped node set): keep the module node instead of silently
- // vanishing it.
- if (childNodes.length === 0) continue;
-
- const modAttrs = graph.getNodeAttributes(moduleId);
- const modX = modAttrs.x;
- const modY = modAttrs.y;
-
- graph.dropNode(moduleId);
-
- const nodeCount = fullGraph.nodes.length;
- const jitter = 30;
-
- for (const node of childNodes) {
- if (graph.hasNode(node.node_id)) continue;
- const baseSize = node.is_entry_point
- ? NODE_BASE_SIZES.entryPoint
- : node.is_test ? NODE_BASE_SIZES.test : NODE_BASE_SIZES.file;
- let size = getScaledNodeSize(baseSize, nodeCount);
- size *= Math.min(1 + node.pagerank * 2, 2);
- const color = sigmaLanguageColor(node.language);
-
- graph.addNode(node.node_id, {
- // Deterministic per-node jitter (id hash) so expanding a module
- // always blossoms its files into the same positions.
- x: modX + (hashUnit(node.node_id) - 0.5) * jitter,
- y: modY + (hashUnit(node.node_id + "y") - 0.5) * jitter,
- size,
- color,
- label: node.node_id.split("/").pop() ?? node.node_id,
- nodeType: "file",
- fullPath: node.node_id,
- language: node.language,
- communityId: node.community_id,
- pagerank: node.pagerank,
- betweenness: node.betweenness,
- isTest: node.is_test,
- isEntryPoint: node.is_entry_point,
- hasDoc: node.has_doc,
- symbolCount: node.symbol_count,
- mass: getNodeMass("file", nodeCount),
- originalColor: color,
- });
- }
-
- const childIds = new Set(childNodes.map((n) => n.node_id));
- const seenEdges = new Set<string>();
- for (const childId of childIds) {
- const edges = fullGraphIndexes.nodeEdgeIndex.get(childId) ?? [];
- for (const link of edges) {
- const edgeKey = link.source + "→" + link.target;
- if (seenEdges.has(edgeKey)) continue;
- seenEdges.add(edgeKey);
-
- const srcInModule = childIds.has(link.source);
- const tgtInModule = childIds.has(link.target);
-
- if (srcInModule && tgtInModule) {
- if (!graph.hasEdge(edgeKey) && graph.hasNode(link.source) && graph.hasNode(link.target)) {
- graph.addEdgeWithKey(edgeKey, link.source, link.target, {
- size: 0.4,
- color: EDGE_COLORS.internal,
- type: "curved",
- curvature: 0.15,
- edgeKind: "internal",
- importedNames: link.imported_names,
- edgeCount: 1,
- });
- }
- } else if (srcInModule && graph.hasNode(link.target)) {
- if (!graph.hasEdge(edgeKey)) {
- graph.addEdgeWithKey(edgeKey, link.source, link.target, {
- size: 0.5,
- color: EDGE_COLORS.import,
- type: "curved",
- curvature: 0.15,
- edgeKind: "import",
- importedNames: link.imported_names,
- edgeCount: 1,
- });
- }
- } else if (tgtInModule && graph.hasNode(link.source)) {
- if (!graph.hasEdge(edgeKey)) {
- graph.addEdgeWithKey(edgeKey, link.source, link.target, {
- size: 0.5,
- color: EDGE_COLORS.import,
- type: "curved",
- curvature: 0.15,
- edgeKind: "import",
- importedNames: link.imported_names,
- edgeCount: 1,
- });
- }
- }
- }
- }
- }
-
- // Re-settle from the warm module positions so expanded files land in a
- // readable blossom immediately (no worker restart, no wobble).
- return settleGraph(graph);
- }
-
const graphData = fileGraphData;
if (!graphData) return null;
@@ -664,7 +436,7 @@ export function GraphFlow(props: GraphFlowProps) {
{ nodes: graphData.nodes, links: graphData.links },
{ signals },
);
- }, [isModuleView, isDrilledDown, fullGraph, currentPrefix, moduleGraph, communities, expandedModules, showExternals, fileGraphData, hasHotSignal, hasDeadSignal, isUnified, hotNodeIds, deadNodeIds, fullGraphIndexes]);
+ }, [fileGraphData, hasHotSignal, hasDeadSignal, isUnified, hotNodeIds, deadNodeIds]);
// Async-built file graph for large graphs (built in chunks off the main
// thread critical path). Null while building / when the sync path applies.
@@ -675,9 +447,7 @@ export function GraphFlow(props: GraphFlowProps) {
const [isBuildingGraph, setIsBuildingGraph] = useState(false);
const needsAsyncBuild =
- !isModuleView &&
- !!fileGraphData &&
- fileGraphData.nodes.length >= ASYNC_BUILD_THRESHOLD;
+ !!fileGraphData && fileGraphData.nodes.length >= ASYNC_BUILD_THRESHOLD;
// `isBuildingGraph` is only raised *inside* the effect below, which React
// runs after it has already painted. So on the commit where an async build
@@ -797,7 +567,7 @@ export function GraphFlow(props: GraphFlowProps) {
if (activeFlowIdx === null || !executionFlows || !sigmaGraph) return 0;
const flow = executionFlows.flows[activeFlowIdx];
if (!flow) return 0;
- return flow.trace.filter((id) => !sigmaGraph.hasNode(id)).length;
+ return traceToFileTrace(flow.trace).filter((id) => !sigmaGraph.hasNode(id)).length;
}, [activeFlowIdx, executionFlows, sigmaGraph]);
// Empty-state copy for a dead/hot view that resolved to zero nodes. Two
@@ -842,16 +612,28 @@ export function GraphFlow(props: GraphFlowProps) {
const { activeCommunities, communityDimmedNodes, handleCommunityToggle, handleToggleAllCommunities } =
useCommunityFilter(sigmaGraph);
- // Switch from the module overview into the flat file view. Shared by the
- // execution-flow highlighter and the path-finder result handler, which both
- // need a file-level graph before they can highlight a trace.
- const enterFullViewFromModule = useCallback(() => {
- if (viewMode === "module") {
- setViewMode("full");
- setModulePath([]);
- onViewModeChange?.("full");
- }
- }, [viewMode, onViewModeChange]);
+ // Module filter (path-prefix dimming). Replaces the old Modules *scope*: the
+ // control lives in the section header and the host owns the selection, so
+ // only the dimming derivation happens here.
+ const { moduleGroups, moduleDimmedNodes, handleModuleChange } = useModuleFilter(sigmaGraph);
+ useEffect(() => {
+ handleModuleChange(controlledActiveModule ?? null);
+ }, [controlledActiveModule, handleModuleChange]);
+ useEffect(() => {
+ onModuleGroupsChange?.(moduleGroups);
+ }, [moduleGroups, onModuleGroupsChange]);
+
+ // The module filter and the community filter answer the same question — "is
+ // this node outside what I asked for?" — so they share the one dim channel
+ // and compose as an AND. Two independent dim levels would just muddy the
+ // canvas with three shades of "not this".
+ const filterDimmedNodes = useMemo(() => {
+ if (!communityDimmedNodes) return moduleDimmedNodes;
+ if (!moduleDimmedNodes) return communityDimmedNodes;
+ const union = new Set(communityDimmedNodes);
+ for (const id of moduleDimmedNodes) union.add(id);
+ return union;
+ }, [communityDimmedNodes, moduleDimmedNodes]);
// Flow index whose trace head has already been focused, so the deferred
// re-focus below fires at most once per selection and never re-steers the
@@ -873,15 +655,14 @@ export function GraphFlow(props: GraphFlowProps) {
}
const flow = executionFlows.flows[activeFlowIdx];
if (!flow) return;
- setHighlightedPath(new Set(flow.trace));
- setHighlightedEdges(traceToEdgeKeys(flow.trace));
-
- enterFullViewFromModule();
+ const fileTrace = traceToFileTrace(flow.trace);
+ setHighlightedPath(new Set(fileTrace));
+ setHighlightedEdges(traceToEdgeKeys(fileTrace));
clearTimeout(focusTimerRef.current);
focusTimerRef.current = setTimeout(() => {
focusTimerRef.current = undefined;
- const firstNode = flow.trace[0];
+ const firstNode = fileTrace[0];
if (!firstNode) return;
if (sigmaGraphRef.current?.hasNode(firstNode)) {
flowFocusedRef.current = activeFlowIdx;
@@ -905,7 +686,8 @@ export function GraphFlow(props: GraphFlowProps) {
}
if (flowFocusedRef.current === activeFlowIdx) return;
if (focusTimerRef.current !== undefined) return;
- const firstNode = executionFlows?.flows[activeFlowIdx]?.trace[0];
+ const trace = executionFlows?.flows[activeFlowIdx]?.trace;
+ const firstNode = trace ? traceToFileTrace(trace)[0] : undefined;
if (!firstNode || !sigmaGraph?.hasNode(firstNode)) return;
flowFocusedRef.current = activeFlowIdx;
sigmaRef.current?.focusNode(firstNode);
@@ -914,7 +696,6 @@ export function GraphFlow(props: GraphFlowProps) {
// ---- Handlers ----
// Unified grammar — DOUBLE CLICK = drill deeper (all views):
- // module → expand/collapse the module's children
// hub → toggle the radial blossom (expand eases the camera onto it)
// file/sat. → open the doc panel
// core → no-op (Sigma's default camera zoom is allowed)
@@ -922,11 +703,6 @@ export function GraphFlow(props: GraphFlowProps) {
// double-click zoom; core returns void so the zoom-jump is kept.
const handleSigmaDoubleClick = useCallback(
(nodeId: string, nodeType: string): boolean | void => {
- if (nodeType === "module") {
- toggleModule(nodeId);
- dismissModuleHint();
- return true;
- }
if (nodeType === "hub" && sigmaGraph?.hasNode(nodeId)) {
const cid = sigmaGraph.getNodeAttribute(nodeId, "communityId");
if (typeof cid === "number" && cid >= 0) {
@@ -939,7 +715,7 @@ export function GraphFlow(props: GraphFlowProps) {
onNodeViewDocs?.(nodeId);
return true;
},
- [onNodeViewDocs, toggleModule, dismissModuleHint, sigmaGraph, handleConstellationHubToggle],
+ [onNodeViewDocs, sigmaGraph, handleConstellationHubToggle],
);
// Unified grammar — SINGLE CLICK = select + inspect (never structural):
@@ -1029,7 +805,6 @@ export function GraphFlow(props: GraphFlowProps) {
(pathNodes: string[]) => {
setHighlightedPath(new Set(pathNodes));
setHighlightedEdges(traceToEdgeKeys(pathNodes));
- enterFullViewFromModule();
clearTimeout(focusTimerRef.current);
focusTimerRef.current = setTimeout(() => {
if (pathNodes.length > 0) {
@@ -1037,7 +812,7 @@ export function GraphFlow(props: GraphFlowProps) {
}
}, 800);
},
- [enterFullViewFromModule],
+ [],
);
const handlePathClear = useCallback(() => {
@@ -1050,18 +825,29 @@ export function GraphFlow(props: GraphFlowProps) {
}, []);
const handleViewChange = useCallback((v: ViewMode) => {
- setViewMode(v);
+ setViewModeState(v);
+ onViewModeChange?.(v);
+ }, [onViewModeChange]);
+
+ // Everything a scope change has to clear, in one place. Scope can now arrive
+ // from the host (the section-header switcher, URL-synced) as well as from the
+ // toolbar's overlay buttons, so this reacts to the resolved value rather than
+ // hanging off one of the two call sites — hooking it to the click handler
+ // alone would leave a stale selection and a stale layout mode behind whenever
+ // the host drove the change.
+ const appliedViewModeRef = useRef(viewMode);
+ useEffect(() => {
+ if (appliedViewModeRef.current === viewMode) return;
+ appliedViewModeRef.current = viewMode;
// Constellation is fixed-radial; other scopes default back to FA2.
- setLayoutMode(v === "architecture" ? "radial" : "force");
+ setLayoutMode(viewMode === "architecture" ? "radial" : "force");
setLayoutNotice(null);
- setModulePath([]);
setHighlightedPath(new Set());
setHighlightedEdges(new Set());
setSelectedNodeId(null);
// Leaving the constellation collapses any open blossoms.
- if (v !== "architecture") collapseAllHubs();
- onViewModeChange?.(v);
- }, [onViewModeChange, collapseAllHubs]);
+ if (viewMode !== "architecture") collapseAllHubs();
+ }, [viewMode, collapseAllHubs]);
const handleLayoutModeChange = useCallback((mode: LayoutMode) => {
// Refuse right at the click when ELK can't run: switching the mode anyway
@@ -1129,22 +915,6 @@ export function GraphFlow(props: GraphFlowProps) {
}
}, [selectedNodeId]);
- const handleInspectExpandModule = useCallback(() => {
- if (selectedNodeId) {
- toggleModule(selectedNodeId);
- dismissModuleHint();
- }
- }, [selectedNodeId, toggleModule, dismissModuleHint]);
-
- // 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);
@@ -1152,15 +922,9 @@ export function GraphFlow(props: GraphFlowProps) {
}, [ctxMenu, onNodeViewDocs, setCtxMenu]);
const handleCtxExplore = useCallback(() => {
- if (ctxMenu) {
- if (ctxMenu.nodeType === "moduleGroup" && isModuleView) {
- setModulePath((prev) => [...prev, ctxMenu.nodeId]);
- } else {
- onNodeClick?.(ctxMenu.nodeId, ctxMenu.nodeType);
- }
- }
+ if (ctxMenu) onNodeClick?.(ctxMenu.nodeId, ctxMenu.nodeType);
setCtxMenu(null);
- }, [ctxMenu, isModuleView, onNodeClick, setCtxMenu]);
+ }, [ctxMenu, onNodeClick, setCtxMenu]);
const handleCtxPathFrom = useCallback(() => {
if (ctxMenu) {
@@ -1191,12 +955,7 @@ export function GraphFlow(props: GraphFlowProps) {
const showOverlayCounts =
!!sigmaGraph && sigmaGraph.order > 0 && (isDeadView || isHotView);
const hasCanvasStatus =
- (isEgoActive && !!selectedNodeId) ||
- (isModuleView && isDrilledDown) ||
- (isModuleView && !isDrilledDown && hasExpandedModules) ||
- (isModuleView && hasExpandedModules && !fullGraph && isLoadingFullGraph) ||
- (isModuleView && !isDrilledDown && !hasExpandedModules && !moduleHintDismissed) ||
- (showOverlayCounts && !!overlayStats);
+ (isEgoActive && !!selectedNodeId) || (showOverlayCounts && !!overlayStats);
// The canvas is what the reader came for, so it sits on the page plane
// rather than below it (rule 8). Dark mode used to paint
@@ -1217,15 +976,13 @@ export function GraphFlow(props: GraphFlowProps) {
highlightedPath={highlightedPath}
highlightedEdges={highlightedEdges}
searchDimmedNodes={searchDimmedNodes}
- communityDimmedNodes={communityDimmedNodes}
+ communityDimmedNodes={filterDimmedNodes}
expandDimmedNodes={isConstellation ? expandDimmedNodes : null}
colorMode={colorMode}
activeSignals={activeSignals}
graphTheme={graphTheme}
fileNodes={fileGraphData?.nodes}
fileEdges={fileGraphData?.links}
- moduleNodes={isModuleView ? moduleGraph?.nodes : undefined}
- moduleEdges={isModuleView ? moduleGraph?.edges : undefined}
onNodeClick={handleSigmaNodeClick}
onNodeDoubleClick={handleSigmaDoubleClick}
onNodeContextMenu={handleSigmaNodeContextMenu}
@@ -1270,81 +1027,8 @@ export function GraphFlow(props: GraphFlowProps) {
</button>
</div>
</div>
- ) : isModuleView && isDrilledDown ? (
- <div>
- <div className={canvasRowClass}>
- <button
- onClick={() => handleBreadcrumbClick(-1)}
- className="flex items-center gap-1 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-graph)] transition-colors"
- >
- <Home className="w-3 h-3" />
- <span>Root</span>
- </button>
- {modulePath.map((fullPrefix, i) => {
- const prevPrefix = i > 0 ? modulePath[i - 1] + "/" : "";
- const label = fullPrefix.slice(prevPrefix.length);
- const isLast = i === modulePath.length - 1;
- return (
- <span key={i} className="flex items-center gap-1">
- <ChevronRight className="w-3 h-3 text-[var(--color-text-tertiary)]" />
- <button
- onClick={() => !isLast && handleBreadcrumbClick(i)}
- className={`text-xs font-mono transition-colors ${
- isLast
- ? "text-[var(--color-text-primary)] font-medium cursor-default"
- : "text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-graph)]"
- }`}
- >
- {label}
- </button>
- </span>
- );
- })}
- </div>
- </div>
) : null}
- {/* Expanded-modules chip: count + collapse-all. */}
- {isModuleView && !isDrilledDown && hasExpandedModules && (
- <div className={canvasRowClass}>
- <span className="text-[10px] text-[var(--color-text-secondary)]">
- {expandedModules.size} module{expandedModules.size === 1 ? "" : "s"} expanded
- </span>
- <button
- onClick={collapseAll}
- className="text-[10px] font-medium text-[var(--color-accent-primary)] hover:underline"
- >
- Collapse all
- </button>
- </div>
- )}
-
- {/* Expansion needs the file-level graph — surface the fetch instead of
- letting the double-click look like it silently did nothing. */}
- {isModuleView && hasExpandedModules && !fullGraph && isLoadingFullGraph && (
- <div role="status" aria-live="polite" className={canvasRowClass}>
- <span className="text-[10px] text-[var(--color-text-secondary)]">
- Loading files for expanded module…
- </span>
- </div>
- )}
-
- {/* One-time interaction hint for the modules scope. */}
- {isModuleView && !isDrilledDown && !hasExpandedModules && !moduleHintDismissed && (
- <div className={canvasRowClass}>
- <span className="text-[10px] text-[var(--color-text-secondary)]">
- Tip: double-click a module to see its files
- </span>
- <button
- onClick={dismissModuleHint}
- aria-label="Dismiss hint"
- className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
- >
- <X className="w-3 h-3" />
- </button>
- </div>
- )}
-
{/* Overlay coverage: how many flagged files are actually in view. The
totals come from the backend when it provides them; without totals
we still report the in-view count so the overlay never reads as
@@ -1428,10 +1112,11 @@ export function GraphFlow(props: GraphFlowProps) {
layoutMode={layoutMode}
onLayoutModeChange={handleLayoutModeChange}
onToggleHelp={handleToggleShortcutHelp}
- availableScopes={availableScopes}
- showExternals={showExternals}
- onShowExternalsChange={setShowExternals}
- externalCount={externalCount}
+ hierarchicalDisabledReason={
+ sigmaGraph && sigmaGraph.order > ELK_MAX_NODES
+ ? elkSkipReason(sigmaGraph.order)
+ : undefined
+ }
/>
</div>
@@ -1578,8 +1263,7 @@ export function GraphFlow(props: GraphFlowProps) {
}
filePageHref={fileNd ? fileHrefFor?.(selectedNodeId) : undefined}
onFindPath={handleInspectFindPath}
- onExpandModule={modNd ? handleInspectExpandModule : undefined}
- isModuleExpanded={modNd ? expandedModules.has(selectedNodeId) : false}
+ isModuleExpanded={false}
egoDepth={egoDepth}
onEgoDepthChange={setEgoDepth}
egoVisibleCount={egoVisibleCount}
diff --git a/packages/ui/src/graph/graph-legend.tsx b/packages/ui/src/graph/graph-legend.tsx
index dc15c4c80..a06a142e6 100644
--- a/packages/ui/src/graph/graph-legend.tsx
+++ b/packages/ui/src/graph/graph-legend.tsx
@@ -294,7 +294,7 @@ export const GraphLegend = memo(function GraphLegend({
</>
)}
- {viewMode !== "module" && viewMode !== "full" && (
+ {viewMode !== "full" && (
<p className="px-1.5 pt-1.5 text-[10px] text-[var(--color-text-tertiary)]">
{viewMode === "dead" && "Showing unreachable files"}
{viewMode === "hotfiles" && "Most-committed files (30d)"}
diff --git a/packages/ui/src/graph/graph-scope-controls.tsx b/packages/ui/src/graph/graph-scope-controls.tsx
new file mode 100644
index 000000000..f7bcd313e
--- /dev/null
+++ b/packages/ui/src/graph/graph-scope-controls.tsx
@@ -0,0 +1,148 @@
+"use client";
+
+import type { KeyboardEvent as ReactKeyboardEvent } from "react";
+import { formatNumber } from "../lib/format";
+import type { ModuleGroup } from "./use-module-filter";
+
+/**
+ * How zoomed out the graph is. Exactly one axis, in exactly one control.
+ *
+ * This used to be steered from two places at once — the page's tab strip
+ * (`Communities | Explore | …`) and a floating pill cluster on the canvas
+ * (`Communities | Modules | Full`). "Communities" appeared in both, and
+ * "Explore" was a container name meaning "the graph, but not communities",
+ * which is not a thing a reader thinks about. Tabs are datasets now; this is
+ * the scope, and it follows the `MapLensSwitcher` precedent on Code Health:
+ * labelled, in the section header, not floating over the diagram.
+ */
+export type GraphScope = "communities" | "files";
+
+const SCOPES: { id: GraphScope; label: string; hint: string }[] = [
+ {
+ id: "communities",
+ label: "Communities",
+ hint: "One circle per detected community",
+ },
+ {
+ id: "files",
+ // Not "Full". It draws the most-connected slice of the repo, and the
+ // caption under the tabs says exactly how big that slice is.
+ label: "Files",
+ hint: "Individual files and how they depend on each other",
+ },
+];
+
+export function GraphScopeSwitcher({
+ scope,
+ onScopeChange,
+ className,
+}: {
+ scope: GraphScope;
+ onScopeChange: (scope: GraphScope) => void;
+ className?: string;
+}) {
+ const onKeyDown = (e: ReactKeyboardEvent) => {
+ const i = SCOPES.findIndex((s) => s.id === scope);
+ if (i < 0) return;
+ let next = i;
+ if (e.key === "ArrowRight" || e.key === "ArrowDown") next = (i + 1) % SCOPES.length;
+ else if (e.key === "ArrowLeft" || e.key === "ArrowUp")
+ next = (i - 1 + SCOPES.length) % SCOPES.length;
+ else return;
+ e.preventDefault();
+ const target = SCOPES[next];
+ if (target) onScopeChange(target.id);
+ };
+
+ return (
+ <div
+ role="radiogroup"
+ aria-label="Graph scope"
+ onKeyDown={onKeyDown}
+ className={`inline-flex rounded-md border border-[var(--color-border-default)] p-0.5 ${className ?? ""}`}
+ >
+ {SCOPES.map((s) => {
+ const active = scope === s.id;
+ return (
+ <button
+ key={s.id}
+ type="button"
+ role="radio"
+ aria-checked={active}
+ tabIndex={active ? 0 : -1}
+ title={s.hint}
+ onClick={() => onScopeChange(s.id)}
+ className={`rounded px-2.5 py-1 text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] ${
+ active
+ ? "bg-[var(--color-bg-elevated)] font-semibold text-[var(--color-text-primary)]"
+ : "font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
+ }`}
+ >
+ {s.label}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+/** Below this share of the graph a module is folded into the overflow list —
+ * it is still selectable, just not worth a slot in the front of the menu. */
+const PROMINENT_MODULES = 8;
+
+/**
+ * Module filter for the Files scope: pick a path prefix, everything else dims.
+ *
+ * Deliberately absent from the Communities scope. The constellation payload
+ * carries a community's label, size and one representative file — not its
+ * members' paths — so "does this community contain `packages/ui`?" is a
+ * question that view cannot answer. A control that could only guess is worse
+ * than no control.
+ */
+export function ModuleFilterSelect({
+ groups,
+ activeModule,
+ onModuleChange,
+ className,
+}: {
+ groups: ModuleGroup[];
+ activeModule: string | null;
+ onModuleChange: (next: string | null) => void;
+ className?: string;
+}) {
+ if (groups.length < 2) return null;
+
+ const prominent = groups.slice(0, PROMINENT_MODULES);
+ const rest = groups.slice(PROMINENT_MODULES);
+
+ return (
+ <label
+ className={`inline-flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)] ${className ?? ""}`}
+ >
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Module
+ </span>
+ <select
+ value={activeModule ?? ""}
+ onChange={(e) => onModuleChange(e.target.value || null)}
+ className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-xs text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ <option value="">All modules</option>
+ {prominent.map((g) => (
+ <option key={g.id} value={g.id}>
+ {g.id} · {formatNumber(g.fileCount)}
+ </option>
+ ))}
+ {rest.length > 0 && (
+ <optgroup label="Smaller">
+ {rest.map((g) => (
+ <option key={g.id} value={g.id}>
+ {g.id} · {formatNumber(g.fileCount)}
+ </option>
+ ))}
+ </optgroup>
+ )}
+ </select>
+ </label>
+ );
+}
diff --git a/packages/ui/src/graph/graph-toolbar.tsx b/packages/ui/src/graph/graph-toolbar.tsx
index bf6194322..4ba088162 100644
--- a/packages/ui/src/graph/graph-toolbar.tsx
+++ b/packages/ui/src/graph/graph-toolbar.tsx
@@ -6,11 +6,9 @@ import {
EyeOff,
Maximize,
Route,
- Boxes,
GitFork,
Skull,
Flame,
- LayoutGrid,
Workflow,
Search,
X,
@@ -18,7 +16,6 @@ import {
Waypoints,
SlidersHorizontal,
HelpCircle,
- Package,
} from "lucide-react";
import { memo, useState } from "react";
import { Button } from "../ui/button";
@@ -40,7 +37,7 @@ import { Button } from "../ui/button";
* then this ships two lenses that both encode something true.
*/
export type ColorMode = "language" | "community";
-export type ViewMode = "module" | "full" | "architecture" | "dead" | "hotfiles" | "unified";
+export type ViewMode = "full" | "architecture" | "dead" | "hotfiles" | "unified";
export type LayoutMode = "hierarchical" | "force" | "radial";
export type GraphTheme = "light" | "dark";
@@ -52,8 +49,15 @@ export type GraphTheme = "light" | "dark";
* The legacy ViewMode is preserved as the wire/state format so existing
* callers and query-param routing keep working. The helpers below convert
* freely in both directions.
+ *
+ * There is no "modules" scope. It drew one circle per top-level directory,
+ * and on this repo `packages/` held 69% of the files — a list that skewed is a
+ * bad canvas. It is now a module *filter* over the file graph (see
+ * `use-module-filter`), which cost a scope, an endpoint, a breadcrumb trail,
+ * drill-down state and expand-on-double-click, and gained a control that
+ * partitions the repo instead of pretending to.
*/
-export type Scope = "architecture" | "modules" | "full";
+export type Scope = "architecture" | "full";
export type Overlay = "dead" | "hot";
export function scopeOverlaysToViewMode(scope: Scope, overlays: ReadonlySet<Overlay>): ViewMode {
@@ -62,14 +66,11 @@ export function scopeOverlaysToViewMode(scope: Scope, overlays: ReadonlySet<Over
if (hasDead && hasHot) return "unified";
if (hasDead) return "dead";
if (hasHot) return "hotfiles";
- if (scope === "modules") return "module";
return scope; // "architecture" | "full"
}
export function viewModeToScopeOverlays(view: ViewMode): { scope: Scope; overlays: Set<Overlay> } {
switch (view) {
- case "module":
- return { scope: "modules", overlays: new Set() };
case "architecture":
return { scope: "architecture", overlays: new Set() };
case "dead":
@@ -107,24 +108,19 @@ interface GraphToolbarProps {
onLayoutModeChange: (mode: LayoutMode) => void;
/** Opens the keyboard-shortcut help overlay (also bound to `?`). */
onToggleHelp?: () => void;
- /** Which scopes the scope cluster offers. Defaults to all three; the Explore
- * surface omits the constellation scope (it lives in the Knowledge Graph
- * view) so there is no cross-view jump back through the toolbar. */
- availableScopes?: Scope[] | undefined;
- /** Modules scope: whether `external:*` dependency modules are drawn.
- * Hidden by default because they usually outnumber the repo's own modules. */
- showExternals?: boolean | undefined;
- onShowExternalsChange?: ((v: boolean) => void) | undefined;
- /** How many external modules the toggle controls (0 hides the toggle). */
- externalCount?: number | undefined;
+ /** Why the hierarchical layout cannot run on this graph, if it cannot.
+ * Renders the toggle disabled with the reason as its tooltip instead of
+ * letting it look live and then refuse on click — ELK's 500-node cap sits
+ * BELOW the graph loader's 1,500-node floor, so on any repo bigger than
+ * that the button was unreachable by construction and said so only after
+ * you pressed it. */
+ hierarchicalDisabledReason?: string | undefined;
}
-// Scope = which subset of nodes are drawn. Mutually exclusive.
-const SCOPES: { id: Scope; icon: typeof Boxes; label: string; hint: string }[] = [
- { id: "architecture", icon: GitFork, label: "Communities", hint: "Detected communities" },
- { id: "modules", icon: Boxes, label: "Modules", hint: "Folder / package rollup" },
- { id: "full", icon: LayoutGrid, label: "Full", hint: "All files and symbols" },
-];
+// No scope cluster here. Scope is one axis and it now has one control, in the
+// section header (`GraphScopeSwitcher`), following the Code Health precedent —
+// floating it over the diagram while the page tabs steered the same axis is
+// what made "Communities" appear twice on one screen.
// Node filter = exclusive All / Hot / Dead segmented control. Hot and dead
// files are near-disjoint sets, so the old pair of independent toggles read
@@ -200,14 +196,8 @@ export const GraphToolbar = memo(function GraphToolbar({
layoutMode,
onLayoutModeChange,
onToggleHelp,
- availableScopes,
- showExternals,
- onShowExternalsChange,
- externalCount,
+ hierarchicalDisabledReason,
}: GraphToolbarProps) {
- const scopes = availableScopes
- ? SCOPES.filter((s) => availableScopes.includes(s.id))
- : SCOPES;
// Below sm the full control cluster is too much chrome over the canvas —
// collapse it behind a single toggle, keeping search always reachable.
const [mobileOpen, setMobileOpen] = useState(false);
@@ -222,10 +212,6 @@ export const GraphToolbar = memo(function GraphToolbar({
// hidden here rather than shown in a half-working state.
const isConstellation = activeScope === "architecture";
- const setScope = (next: Scope) => {
- onViewChange(scopeOverlaysToViewMode(next, activeOverlays));
- };
-
// Exclusive node filter. Legacy "unified" URLs parse to both overlays and
// render as Dead here; any click normalizes back to a single filter.
const activeFilter: Overlay | "all" = activeOverlays.has("dead")
@@ -257,30 +243,6 @@ export const GraphToolbar = memo(function GraphToolbar({
</button>
<div className={panelClass}>
- {/* Scope (mutually exclusive). Hidden when only one scope is offered —
- the surface is locked (e.g. the Communities lens). */}
- {scopes.length > 1 && (
- <div className={`${clusterVisibility} ${groupClass}`}>
- {scopes.map((m) => {
- const Icon = m.icon;
- const isActive = activeScope === m.id;
- return (
- <button
- key={m.id}
- onClick={() => setScope(m.id)}
- className={`${itemClass} ${isActive ? itemActiveClass : itemIdleClass}`}
- title={m.hint}
- aria-label={m.label}
- aria-pressed={isActive}
- >
- <Icon className="w-3 h-3" />
- <span className="hidden lg:inline">{m.label}</span>
- </button>
- );
- })}
- </div>
- )}
-
{/* Node filter (exclusive All / Hot / Dead) — not applicable in the constellation */}
{!isConstellation && (
<div
@@ -329,13 +291,19 @@ export const GraphToolbar = memo(function GraphToolbar({
LAYOUT_MODES.map((m) => {
const Icon = m.icon;
const isActive = layoutMode === m.id;
+ const disabledReason =
+ m.id === "hierarchical" ? hierarchicalDisabledReason : undefined;
return (
<button
key={m.id}
onClick={() => onLayoutModeChange(m.id)}
- className={`${itemClass} ${isActive ? itemActiveClass : itemIdleClass}`}
- title={m.label}
+ disabled={!!disabledReason}
+ className={`${itemClass} ${isActive ? itemActiveClass : itemIdleClass} ${
+ disabledReason ? "cursor-not-allowed opacity-40" : ""
+ }`}
+ title={disabledReason ?? m.label}
aria-label={m.label}
+ aria-disabled={!!disabledReason}
aria-pressed={isActive}
>
<Icon className="w-3 h-3" />
@@ -409,27 +377,6 @@ export const GraphToolbar = memo(function GraphToolbar({
<Workflow className="w-3.5 h-3.5" />
</Button>
)}
- {activeScope === "modules" && onShowExternalsChange && (externalCount ?? 0) > 0 && (
- <Button
- size="sm"
- variant="ghost"
- onClick={() => onShowExternalsChange(!showExternals)}
- className={`h-8 w-8 sm:h-7 sm:w-7 p-0 ${showExternals ? "text-[var(--color-accent-primary)]" : "text-[var(--color-text-tertiary)]"}`}
- title={
- showExternals
- ? `Hide ${externalCount} external dependencies`
- : `Show ${externalCount} external dependencies`
- }
- aria-label={
- showExternals
- ? "Hide external dependencies"
- : "Show external dependencies"
- }
- aria-pressed={showExternals}
- >
- <Package className="w-3.5 h-3.5" />
- </Button>
- )}
{!isConstellation && (
<Button
size="sm"
diff --git a/packages/ui/src/graph/graph-truncation-banner.tsx b/packages/ui/src/graph/graph-truncation-banner.tsx
index 0f4e0819c..dd569bb86 100644
--- a/packages/ui/src/graph/graph-truncation-banner.tsx
+++ b/packages/ui/src/graph/graph-truncation-banner.tsx
@@ -18,7 +18,19 @@ import { cn } from "../lib/cn";
import { formatNumber } from "../lib/format";
export const LOAD_MORE_STEP = 1500;
-export const LOAD_MORE_CEILING = 6000;
+
+/**
+ * Highest node cap the "load more" ladder will offer.
+ *
+ * Was 6,000 — a number nothing had rendered, promised while the canvas was
+ * still spending 8-12 seconds in an FA2 worker on every load. The layout is
+ * seeded-and-painted now (no worker), and the largest graph actually measured
+ * end to end is this repo's whole file set: 3,192 nodes / 13,216 edges, which
+ * paints immediately. 3,000 is inside that, and it is exactly two presses of
+ * the 1,500 step. Raising it again is a benchmark, not an edit.
+ */
+export const LOAD_MORE_CEILING = 3000;
+
const SLOW_HINT_THRESHOLD = 3000;
export interface GraphTruncationBannerProps {
diff --git a/packages/ui/src/graph/index.ts b/packages/ui/src/graph/index.ts
index 0e5586722..72b40ffeb 100644
--- a/packages/ui/src/graph/index.ts
+++ b/packages/ui/src/graph/index.ts
@@ -13,7 +13,8 @@ export * from "./graph-canvas-shell";
export * from "./graph-flow";
export * from "./context";
export * from "./elk-layout";
-export * from "./use-expanded-modules";
+export * from "./graph-scope-controls";
+export * from "./use-module-filter";
export * from "./sigma/sigma-canvas";
export * from "./sigma/types";
export * from "./sigma/graphology-adapter";
diff --git a/packages/ui/src/graph/sigma/constants.ts b/packages/ui/src/graph/sigma/constants.ts
index 7334f3b6b..248f3a155 100644
--- a/packages/ui/src/graph/sigma/constants.ts
+++ b/packages/ui/src/graph/sigma/constants.ts
@@ -125,10 +125,27 @@ export function getLayoutDuration(nodeCount: number): number {
return 8000;
}
-// ---- Synchronous pre-settle (small graphs: settle before first paint) ----
+// ---- Community seeding (file graphs) ----
+
+/**
+ * Diameter of a community's seeding disc, per sqrt(member count), in graph
+ * units. Scaling with sqrt keeps node density inside a community roughly
+ * constant: the old fixed `sqrt(nodeCount) * 3` gave a 776-file community and a
+ * 5-file one the same box, which is why 65% of discs overlapped something on
+ * first paint.
+ *
+ * Measured on this repo's real 1,500-node export, at k=20 with a disc
+ * distribution: 20.4% of nodes overlapping (was 65.3%) at cluster separation
+ * 20.8 (was 23.2). A square box scores marginally better on separation at equal
+ * overlap, but draws communities as squares — the whole page reads in circles.
+ */
+export const SEED_JITTER_PER_SQRT_MEMBER = 20;
+
+// ---- Synchronous pre-settle (module graphs: settle before first paint) ----
/** Above this, settling synchronously would risk a main-thread jank — the
- * animated FA2 worker takes over instead. */
+ * animated FA2 worker takes over instead. Applies to module graphs only; file
+ * graphs ship their seed as the final layout (see buildFileGraph). */
export const PRESETTLE_MAX_NODES = 800;
/** Sync FA2 iteration budget, scaled down as graphs grow. ~400 iterations on
@@ -151,7 +168,20 @@ export const NOVERLAP_SETTINGS = {
// ---- Edge rendering thresholds ----
-export const CURVED_EDGE_THRESHOLD = 3000;
+/**
+ * Above this many EDGES, drop the per-edge curvature and draw straight arrows.
+ *
+ * This was compared against the node count, not the edge count, while governing
+ * how edges draw — so with the export capped at 1,500 nodes it could never fire
+ * and every edge drew as a curved arrow. Now measured against what it actually
+ * costs: `curvedArrow` carries a per-edge curvature and a heavier program than
+ * `arrow`.
+ *
+ * The straight variant is "arrow", never "line" — `line` has no arrowhead, and
+ * direction is the whole point of a dependency edge (#1145 added those heads
+ * deliberately).
+ */
+export const CURVED_EDGE_THRESHOLD = 8000;
// ---- Label rendering ----
@@ -161,11 +191,21 @@ export const LABEL_DENSITY = 0.15;
export const LABEL_GRID_CELL_SIZE = 80;
export const LABEL_RENDERED_SIZE_THRESHOLD = 6;
-/** Sparser labels on large graphs to keep repaint cheap. */
+/**
+ * Sparser labels on large graphs to keep repaint cheap.
+ *
+ * Both thresholds used to step at 2,000 nodes while the export was capped at
+ * 1,500 — so neither could ever fire, and the "large graph" branch was dead on
+ * every repo. They step at 1,200 now, which is inside the default page, and the
+ * ladder has a second rung so a "load more" to the 3,000 ceiling still thins
+ * out rather than jumping straight to the densest setting it has.
+ */
export function getLabelDensity(nodeCount: number): number {
- return nodeCount > 2000 ? 0.07 : LABEL_DENSITY;
+ if (nodeCount > 2500) return 0.05;
+ return nodeCount > 1200 ? 0.07 : LABEL_DENSITY;
}
export function getLabelRenderedSizeThreshold(nodeCount: number): number {
- return nodeCount > 2000 ? 8 : LABEL_RENDERED_SIZE_THRESHOLD;
+ if (nodeCount > 2500) return 10;
+ return nodeCount > 1200 ? 8 : LABEL_RENDERED_SIZE_THRESHOLD;
}
diff --git a/packages/ui/src/graph/sigma/graphology-adapter.ts b/packages/ui/src/graph/sigma/graphology-adapter.ts
index 2898b2bbb..6ee5ba753 100644
--- a/packages/ui/src/graph/sigma/graphology-adapter.ts
+++ b/packages/ui/src/graph/sigma/graphology-adapter.ts
@@ -18,6 +18,7 @@ import {
EDGE_SIZE_MULTIPLIERS,
CURVED_EDGE_THRESHOLD,
PRESETTLE_MAX_NODES,
+ SEED_JITTER_PER_SQRT_MEMBER,
getFA2Settings,
getPresettleIterations,
getScaledNodeSize,
@@ -171,7 +172,6 @@ function* buildFileGraph(
(a, b) => a - b,
);
const communityCount = sortedCommunities.length;
- const jitter = Math.sqrt(nodeCount) * 3;
let processed = 0;
for (let i = 0; i < sortedCommunities.length; i++) {
@@ -182,11 +182,18 @@ function* buildFileGraph(
const radius = spread * Math.sqrt((i + 1) / communityCount);
const centroidX = radius * Math.cos(angle);
const centroidY = radius * Math.sin(angle);
+ // Per-community, not per-graph: a community's box grows with its own
+ // membership so density stays even across very unequal communities.
+ const jitter = SEED_JITTER_PER_SQRT_MEMBER * Math.sqrt(members.length);
for (const node of members) {
+ // Deterministic point in the community's disc. sqrt on the radius keeps
+ // the distribution uniform over area rather than bunched at the centre.
const hash = simpleHash(node.node_id);
- const x = centroidX + ((hash % 1000) / 1000 - 0.5) * jitter;
- const y = centroidY + (((hash >> 10) % 1000) / 1000 - 0.5) * jitter;
+ const r = (jitter / 2) * Math.sqrt((hash % 1000) / 1000);
+ const theta = (((hash >> 10) % 1000) / 1000) * 2 * Math.PI;
+ const x = centroidX + r * Math.cos(theta);
+ const y = centroidY + r * Math.sin(theta);
let baseSize: number;
if (node.is_entry_point) {
@@ -271,6 +278,12 @@ function* buildFileGraph(
const maxEdgesPerNode = nodeCount > 1000 ? 25 : Infinity;
const edgesPerSource = new Map<string, number>();
+ // Curvature is an edge-count decision, so decide it on the edge count. The
+ // per-source cap above bounds this, so `orderedLinks.length` is an upper
+ // bound on what actually gets drawn — erring toward curved, which is the
+ // nicer default, on graphs near the threshold.
+ const useCurved = orderedLinks.length <= CURVED_EDGE_THRESHOLD;
+
let edgeProcessed = 0;
for (const link of orderedLinks) {
if (++edgeProcessed % CHUNK_SIZE === 0) yield;
@@ -284,13 +297,12 @@ function* buildFileGraph(
const edgeKind = edgeKindMap.get(link) ?? classifyEdge(link, nodeMap);
- const useCurved = nodeCount <= CURVED_EDGE_THRESHOLD;
const edgeAttrs: SigmaEdgeAttributes = {
size: computeEdgeSize(edgeKind, nodeCount),
color: EDGE_COLORS[edgeKind],
- // Directed arrowheads under the curved threshold; big graphs keep the
- // cheaper line program.
- type: useCurved ? "curvedArrow" : "line",
+ // Dense graphs drop the curvature, never the arrowhead: "line" would
+ // erase the direction encoding that makes a dependency edge readable.
+ type: useCurved ? "curvedArrow" : "arrow",
curvature: useCurved ? computeEdgeCurvature(edgeKey) : 0,
edgeKind,
importedNames: link.imported_names,
@@ -304,6 +316,19 @@ function* buildFileGraph(
result.addEdgeWithKey(edgeKey, link.source, link.target, edgeAttrs);
}
+ // The community seed above IS the layout — mark it settled so use-fa2-layout
+ // skips its auto-run (the toolbar's manual toggle still starts FA2).
+ //
+ // This used to hand off to the animated FA2 worker for 8 seconds. Measured on
+ // this repo's real 1,500-node export, that run does not improve the picture:
+ // cluster separation *falls* monotonically with iterations (23.2 seeded →
+ // 21.6 at 120 → 12.1 at 600 → 7.7 at 1200) as gravity pulls the golden-angle
+ // spiral into one central hairball, while median node drift stays under 4% of
+ // the graph radius for the first ~120. So the eight seconds bought a slower
+ // arrival at a slightly worse layout. Removing it is a removal of known work,
+ // not a speculative optimisation.
+ result.setAttribute("presettled", true);
+
return result;
}
diff --git a/packages/ui/src/graph/sigma/sigma-canvas.tsx b/packages/ui/src/graph/sigma/sigma-canvas.tsx
index c1d70d0a8..d96143a5b 100644
--- a/packages/ui/src/graph/sigma/sigma-canvas.tsx
+++ b/packages/ui/src/graph/sigma/sigma-canvas.tsx
@@ -16,8 +16,6 @@ import type { Signal } from "../context";
import type {
GraphNode as GraphNodeResponse,
GraphLink as GraphEdgeResponse,
- ModuleNode as ModuleNodeResponse,
- ModuleEdge as ModuleEdgeResponse,
} from "@repowise-dev/types/graph";
import { useSigmaRenderer } from "./use-sigma";
import { useFA2Layout } from "./use-fa2-layout";
@@ -42,8 +40,6 @@ export interface SigmaCanvasProps {
graphTheme: "light" | "dark";
fileNodes?: GraphNodeResponse[] | undefined;
fileEdges?: GraphEdgeResponse[] | undefined;
- moduleNodes?: ModuleNodeResponse[] | undefined;
- moduleEdges?: ModuleEdgeResponse[] | undefined;
onNodeClick?: ((nodeId: string, nodeType: string) => void) | undefined;
onNodeContextMenu?:
| ((event: MouseEvent, nodeId: string, nodeType: string) => void)
@@ -106,9 +102,6 @@ export const SigmaCanvas = forwardRef<SigmaCanvasHandle, SigmaCanvasProps>(
enabled: props.layoutMode === "hierarchical",
fileNodes: props.fileNodes,
fileEdges: props.fileEdges,
- moduleNodes: props.moduleNodes,
- moduleEdges: props.moduleEdges,
- viewMode: props.viewMode,
onSkipped: props.onLayoutSkipped,
});
diff --git a/packages/ui/src/graph/sigma/use-elk-sigma-layout.ts b/packages/ui/src/graph/sigma/use-elk-sigma-layout.ts
index 4ad7097a6..a6b3128c0 100644
--- a/packages/ui/src/graph/sigma/use-elk-sigma-layout.ts
+++ b/packages/ui/src/graph/sigma/use-elk-sigma-layout.ts
@@ -6,23 +6,26 @@ import type Graph from "graphology";
import type {
GraphNode as GraphNodeResponse,
GraphLink as GraphEdgeResponse,
- ModuleNode as ModuleNodeResponse,
- ModuleEdge as ModuleEdgeResponse,
} from "@repowise-dev/types/graph";
import type { SigmaNodeAttributes, SigmaEdgeAttributes } from "./types";
-import type { ViewMode } from "../graph-toolbar";
-import {
- computeElkFilePositions,
- computeElkModulePositions,
-} from "../elk-layout";
+import { computeElkFilePositions } from "../elk-layout";
// ELK runs on the main thread (elk.bundled.js, no worker), so a large graph
// would freeze the tab mid-layout. 500 nodes keeps the compute comfortably
// interactive; raising this ceiling means moving ELK into a web worker first.
export const ELK_MAX_NODES = 500;
+/**
+ * States the bound and stops there, deliberately.
+ *
+ * This used to end "Switch to the Modules scope or narrow the view to use it."
+ * Every one of those was a dead end: the Modules scope is gone, and the module
+ * filter, the community filter and search all *dim* rather than remove, so
+ * `graph.order` — the number this cap is measured against — does not move when
+ * you use them. Advice that cannot work is worse than no advice.
+ */
export function elkSkipReason(order: number): string {
- return `Hierarchical layout is limited to ${ELK_MAX_NODES} nodes — this view has ${order.toLocaleString()}. Switch to the Modules scope or narrow the view to use it.`;
+ return `Hierarchical layout needs ${ELK_MAX_NODES} nodes or fewer — this view has ${order.toLocaleString()}.`;
}
/**
@@ -51,9 +54,6 @@ export interface UseElkSigmaLayoutOptions {
enabled: boolean;
fileNodes?: GraphNodeResponse[] | undefined;
fileEdges?: GraphEdgeResponse[] | undefined;
- moduleNodes?: ModuleNodeResponse[] | undefined;
- moduleEdges?: ModuleEdgeResponse[] | undefined;
- viewMode: ViewMode;
onSkipped?: ((reason: string) => void) | undefined;
}
@@ -74,9 +74,6 @@ export function useElkSigmaLayout(
enabled,
fileNodes,
fileEdges,
- moduleNodes,
- moduleEdges,
- viewMode,
} = options;
const compute = useCallback(() => {
@@ -87,14 +84,7 @@ export function useElkSigmaLayout(
const run = async () => {
try {
- if (viewMode === "module" && moduleNodes && moduleEdges) {
- const positions = await computeElkModulePositions(
- moduleNodes,
- moduleEdges,
- );
- if (computeIdRef.current !== computeId) return;
- applyPositions(graph, positions);
- } else if (fileNodes && fileEdges) {
+ if (fileNodes && fileEdges) {
const result = await computeElkFilePositions(fileNodes, fileEdges);
if (computeIdRef.current !== computeId) return;
applyPositions(graph, result.positions);
@@ -109,7 +99,7 @@ export function useElkSigmaLayout(
};
void run();
- }, [graph, sigma, fileNodes, fileEdges, moduleNodes, moduleEdges, viewMode]);
+ }, [graph, sigma, fileNodes, fileEdges]);
useEffect(() => {
if (enabled && graph && graph.order > 0) {
diff --git a/packages/ui/src/graph/use-expanded-modules.ts b/packages/ui/src/graph/use-expanded-modules.ts
deleted file mode 100644
index 59bb46c70..000000000
--- a/packages/ui/src/graph/use-expanded-modules.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-"use client";
-
-import { useState, useCallback } from "react";
-
-export function useExpandedModules() {
- const [expandedModules, setExpandedModules] = useState<Set<string>>(new Set());
-
- const toggleModule = useCallback((moduleId: string) => {
- setExpandedModules((prev) => {
- const next = new Set(prev);
- if (next.has(moduleId)) next.delete(moduleId);
- else next.add(moduleId);
- return next;
- });
- }, []);
-
- const collapseAll = useCallback(() => {
- setExpandedModules(new Set());
- }, []);
-
- const expandAll = useCallback((moduleIds: string[]) => {
- setExpandedModules(new Set(moduleIds));
- }, []);
-
- return { expandedModules, toggleModule, collapseAll, expandAll };
-}
diff --git a/packages/ui/src/graph/use-module-filter.ts b/packages/ui/src/graph/use-module-filter.ts
new file mode 100644
index 000000000..8f20a2828
--- /dev/null
+++ b/packages/ui/src/graph/use-module-filter.ts
@@ -0,0 +1,97 @@
+import { useCallback, useMemo, useState } from "react";
+import type Graph from "graphology";
+import type { SigmaEdgeAttributes, SigmaNodeAttributes } from "./sigma/types";
+
+type SigmaGraph = Graph<SigmaNodeAttributes, SigmaEdgeAttributes>;
+
+/** Bucket every path outside the repo's own tree, however it is spelled. */
+const EXTERNAL_GROUP = "external";
+/** Files that live at the repo root and have no directory to belong to. */
+const ROOT_GROUP = "(repo root)";
+
+/**
+ * The module a file path belongs to, as a *path prefix* rather than a
+ * top-level directory.
+ *
+ * Top-level directories do not partition this kind of repo: on repowise itself
+ * `packages/` holds 92% of the files, so a top-level filter would dim 8% of the
+ * canvas and read as broken. Two segments do partition it — the largest group
+ * becomes 38% and the top five cover 84%.
+ *
+ * The second segment is only taken when it is a directory (path depth 3+).
+ * Otherwise `tests/conftest.py` would invent a one-file module called
+ * "tests/conftest.py" sitting beside the real `tests/unit`.
+ */
+export function moduleGroupFor(nodeId: string): string {
+ if (nodeId.startsWith("external:") || nodeId.startsWith("framework:")) {
+ return EXTERNAL_GROUP;
+ }
+ const parts = nodeId.split("/");
+ if (parts.length === 1) return ROOT_GROUP;
+ if (parts.length === 2) return parts[0]!;
+ return `${parts[0]}/${parts[1]}`;
+}
+
+export interface ModuleGroup {
+ id: string;
+ fileCount: number;
+}
+
+/**
+ * Filter the file graph by module, by dimming everything outside the selected
+ * module rather than removing it — the surrounding structure is the context
+ * that makes "this module" mean anything, and it is the same grammar the
+ * community filter, the ego filter and search already use.
+ *
+ * `activeModule === null` means no filter.
+ *
+ * This replaces a whole separate "Modules" scope, which drew one circle per
+ * top-level directory: a 9-item list where one item held 69% of the files,
+ * with its own endpoint, breadcrumb trail, drill-down state and
+ * expand-on-double-click. A skewed list is a bad canvas and a fine filter.
+ */
+export function useModuleFilter(sigmaGraph: SigmaGraph | null) {
+ const [activeModule, setActiveModule] = useState<string | null>(null);
+
+ const moduleGroups = useMemo<ModuleGroup[]>(() => {
+ if (!sigmaGraph) return [];
+ const counts = new Map<string, number>();
+ sigmaGraph.forEachNode((_nodeId, attrs) => {
+ if (attrs.nodeType !== "file") return;
+ const group = moduleGroupFor(attrs.fullPath);
+ counts.set(group, (counts.get(group) ?? 0) + 1);
+ });
+ return [...counts]
+ .map(([id, fileCount]) => ({ id, fileCount }))
+ .sort((a, b) => b.fileCount - a.fileCount || a.id.localeCompare(b.id));
+ }, [sigmaGraph]);
+
+ const moduleDimmedNodes = useMemo(() => {
+ if (!activeModule || !sigmaGraph) return null;
+ const dimmed = new Set<string>();
+ sigmaGraph.forEachNode((nodeId, attrs) => {
+ if (attrs.nodeType !== "file") return;
+ if (moduleGroupFor(attrs.fullPath) !== activeModule) dimmed.add(nodeId);
+ });
+ return dimmed.size > 0 ? dimmed : null;
+ }, [activeModule, sigmaGraph]);
+
+ /** How many nodes the active module actually matches — the control reports
+ * this, so it can never claim a filter that selected nothing. */
+ const activeModuleCount = useMemo(() => {
+ if (!activeModule) return null;
+ return moduleGroups.find((g) => g.id === activeModule)?.fileCount ?? 0;
+ }, [activeModule, moduleGroups]);
+
+ const handleModuleChange = useCallback((next: string | null) => {
+ setActiveModule(next);
+ }, []);
+
+ return {
+ activeModule,
+ activeModuleCount,
+ moduleGroups,
+ moduleDimmedNodes,
+ handleModuleChange,
+ };
+}
diff --git a/packages/vscode/webview/src/views/graph/App.tsx b/packages/vscode/webview/src/views/graph/App.tsx
index bde1b37b8..322e9c5fc 100644
--- a/packages/vscode/webview/src/views/graph/App.tsx
+++ b/packages/vscode/webview/src/views/graph/App.tsx
@@ -66,8 +66,6 @@ export function App({ host, params, repo, refreshToken }: ViewProps<"graph">) {
</div>
) : (
<GraphFlow
- moduleGraph={data.moduleGraph as ModuleGraph | undefined}
- isLoadingModuleGraph={data.isLoadingModuleGraph}
fullGraph={data.fullGraph as GraphExport | undefined}
isLoadingFullGraph={data.isLoadingFullGraph}
// Legacy file-level architecture graph is unused by the constellation
@@ -89,10 +87,6 @@ export function App({ host, params, repo, refreshToken }: ViewProps<"graph">) {
executionFlows={data.executionFlows as ExecutionFlows | undefined}
initialSelectedNode={params.selectNode ?? null}
onViewModeChange={data.setViewMode}
- onModulePathChange={data.setModulePath}
- onExpandedModulesChange={(expanded) =>
- data.setHasExpandedModules(expanded.size > 0)
- }
onNodeClick={handleNodeClick}
onNodeViewDocs={openIfFile}
renderPathFinder={(p) => (
diff --git a/packages/vscode/webview/src/views/graph/use-graph-data.ts b/packages/vscode/webview/src/views/graph/use-graph-data.ts
index facd65198..38d2c06e3 100644
--- a/packages/vscode/webview/src/views/graph/use-graph-data.ts
+++ b/packages/vscode/webview/src/views/graph/use-graph-data.ts
@@ -19,11 +19,9 @@ import type {
CommunitySummaryItem,
ExecutionFlows,
GraphExport,
- ModuleGraph,
} from "@repowise-dev/types/graph";
export type ViewMode =
- | "module"
| "full"
| "architecture"
| "dead"
@@ -34,8 +32,6 @@ export type ViewMode =
const DEFAULT_VIEW_MODE: ViewMode = "architecture";
export interface GraphData {
- moduleGraph: ModuleGraph | undefined;
- isLoadingModuleGraph: boolean;
fullGraph: GraphExport | undefined;
isLoadingFullGraph: boolean;
constellationGraph: ArchitectureGraph | undefined;
@@ -53,9 +49,6 @@ export interface GraphData {
stats: { nodes: number; edges: number } | null;
viewMode: ViewMode;
setViewMode: (mode: ViewMode) => void;
- /** Legacy breadcrumb drill-down state, owned by the ui shell. */
- setModulePath: (path: string[]) => void;
- setHasExpandedModules: (expanded: boolean) => void;
/** Currently-expanded constellation hubs; drives the incremental slice fetch. */
setExpandedHubs: (ids: number[]) => void;
}
@@ -107,8 +100,6 @@ function useHostSlice<T>(
export function useGraphData(host: WebviewHost, refreshToken: number): GraphData {
const [viewMode, setViewMode] = useState<ViewMode>(DEFAULT_VIEW_MODE);
- const [modulePath, setModulePath] = useState<string[]>([]);
- const [hasExpandedModules, setHasExpandedModules] = useState(false);
const [expandedHubs, setExpandedHubs] = useState<number[]>([]);
const [error, setError] = useState<string | null>(null);
@@ -120,19 +111,13 @@ export function useGraphData(host: WebviewHost, refreshToken: number): GraphData
setError(null);
}, [viewMode, refreshToken]);
- const isDrilledDown = modulePath.length > 0;
- // The full file graph backs the drill-down, the flat file/unified scopes, and
- // module expansion; execution flows only trace a file-level path, so they
- // ride the same gate rather than fetching on the constellation mount.
- const needsFullGraph =
- isDrilledDown ||
- viewMode === "full" ||
- viewMode === "unified" ||
- hasExpandedModules;
+ // The full file graph backs the flat file/unified scopes; execution flows
+ // only trace a file-level path, so they ride the same gate rather than
+ // fetching on the constellation mount.
+ const needsFullGraph = viewMode === "full" || viewMode === "unified";
// Stable fetchers (host is created once at mount) so the slice effects don't
// re-run on every render.
- const fetchModuleGraph = useCallback(() => host.api.moduleGraph(), [host]);
const fetchFullGraph = useCallback(() => host.api.fullGraph(), [host]);
const fetchConstellation = useCallback(
() => host.api.architectureCommunityGraph(),
@@ -143,12 +128,6 @@ export function useGraphData(host: WebviewHost, refreshToken: number): GraphData
const fetchHotFiles = useCallback(() => host.api.hotFilesGraph(), [host]);
const fetchExecutionFlows = useCallback(() => host.api.executionFlows(), [host]);
- const moduleSlice = useHostSlice(
- viewMode === "module",
- refreshToken,
- fetchModuleGraph,
- onError,
- );
const fullSlice = useHostSlice(needsFullGraph, refreshToken, fetchFullGraph, onError);
const constellationSlice = useHostSlice(
viewMode === "architecture",
@@ -210,7 +189,6 @@ export function useGraphData(host: WebviewHost, refreshToken: number): GraphData
setConstellationSlices(new Map());
}, [refreshToken]);
- const moduleGraph = moduleSlice.data as ModuleGraph | undefined;
const fullGraph = fullSlice.data as GraphExport | undefined;
const constellationGraph = constellationSlice.data as
| ArchitectureGraph
@@ -229,10 +207,6 @@ export function useGraphData(host: WebviewHost, refreshToken: number): GraphData
edges: constellationGraph.edges.length,
}
: null;
- case "module":
- return moduleGraph
- ? { nodes: moduleGraph.nodes.length, edges: moduleGraph.edges.length }
- : null;
case "dead":
return deadCodeGraph
? { nodes: deadCodeGraph.nodes.length, edges: deadCodeGraph.links.length }
@@ -246,11 +220,9 @@ export function useGraphData(host: WebviewHost, refreshToken: number): GraphData
? { nodes: fullGraph.nodes.length, edges: fullGraph.links.length }
: null;
}
- }, [viewMode, constellationGraph, moduleGraph, deadCodeGraph, hotFilesGraph, fullGraph]);
+ }, [viewMode, constellationGraph, deadCodeGraph, hotFilesGraph, fullGraph]);
return {
- moduleGraph,
- isLoadingModuleGraph: moduleSlice.isLoading,
fullGraph,
isLoadingFullGraph: fullSlice.isLoading,
constellationGraph,
@@ -266,8 +238,6 @@ export function useGraphData(host: WebviewHost, refreshToken: number): GraphData
stats,
viewMode,
setViewMode,
- setModulePath,
- setHasExpandedModules,
setExpandedHubs,
};
}
diff --git a/packages/web/src/app/repos/[id]/architecture/page.tsx b/packages/web/src/app/repos/[id]/architecture/page.tsx
index 0d78907d7..12b584ab1 100644
--- a/packages/web/src/app/repos/[id]/architecture/page.tsx
+++ b/packages/web/src/app/repos/[id]/architecture/page.tsx
@@ -3,19 +3,38 @@
/**
* Architecture — `/repos/[id]/architecture`.
*
- * The "how the code is wired" destination, with tabs behind `?view=`:
- * - map — the constellation, surfaced as the "Communities" tab
- * - explore — the full / module dependency graph with dead/hot overlays
- * - symbols — the searchable symbol index
- * - deps — the third-party dependency registry
+ * Tabs are DATASETS, not zoom levels:
+ * - Map — the dependency graph, at community or file scope
+ * - Coupling — files that tend to change together
+ * - Packages — the declared third-party dependency registry
+ * - Symbols — the searchable symbol index
+ *
+ * How zoomed out the graph is — communities vs files — is a different axis and
+ * has exactly one control, `GraphScopeSwitcher`, in the section header beside
+ * the graph. It used to be steered from here *and* from a pill cluster floating
+ * on the canvas, which put "Communities" on screen twice and left "Explore" as
+ * a tab meaning "the graph, but not communities".
+ *
+ * The tab named "Packages" was "Dependencies", which collided with the graph
+ * itself: the Map tab *is* the dependency graph, so a sibling tab called
+ * Dependencies read as the same thing at a different zoom. It lists declared
+ * third-party packages, so it says that.
+ *
+ * ## URL state
+ *
+ * One param per axis, no two params saying the same thing:
+ * - `?view=` communities | files | coupling | packages | symbols
+ * - `?signal=` dead | hot — which overlay is lit on the graph
+ * - `?module=` a path prefix the file scope is filtered to
+ *
+ * `?view=` and `?viewMode=` used to encode the same axis twice — `view=explore`
+ * and `viewMode=full` both meant "the file graph", and they could disagree.
+ * Scope now lives in `?view=` and nothing else carries it. Old links keep
+ * working: the legacy spellings are aliased below, and a legacy `?viewMode=` is
+ * translated into `?view=`/`?signal=` on first read.
*
* The curated layered view ("Knowledge Graph") is a separate top-level route
* (`/knowledge-graph`); the legacy `?view=layers` alias redirects there.
- *
- * Communities and Explore are the SAME `GraphFlow` canvas differing only by
- * scope: Communities locks it to the constellation (radial) scope, Explore
- * mounts it at full/module scope. Switching scope inside Explore keeps `?view=`
- * in sync without remounting.
*/
import { use, useCallback, useEffect } from "react";
@@ -33,34 +52,61 @@ import { CouplingTab } from "@/components/coupling/coupling-tab";
// The curated layered view now lives under the dedicated Knowledge Graph route.
const KNOWLEDGE_GRAPH_VIEWS = new Set(["layers"]);
-// Accepted `?view=` values. "graph" and "layers" are legacy aliases that are
-// normalized / redirected below; only the canonical tabs render a tab.
-const VIEWS = [
- "map",
- "explore",
- "deps",
- "symbols",
- "coupling",
- "graph",
- "layers",
-] as const;
+/** Canonical `?view=` values. The first two are both the Map tab. */
+const CANONICAL = ["communities", "files", "coupling", "packages", "symbols"] as const;
+type CanonicalView = (typeof CANONICAL)[number];
+
+/** Everything `?view=` accepts, canonical values plus legacy spellings. */
+const VIEWS = [...CANONICAL, "map", "explore", "deps", "graph", "layers"] as const;
type ArchView = (typeof VIEWS)[number];
-// IA-as-data. Communities first (today's `map`), then the wiring surfaces.
-// Coupling is added here in a later phase — the structure is kept easy to
-// extend (append a `{ id: "coupling", ... }` row + a panel branch).
-const CANONICAL_VIEWS: { id: Extract<ArchView, "map" | "explore" | "deps" | "symbols" | "coupling">; label: string; hint: string }[] = [
- { id: "map", label: "Communities", hint: "Constellation of detected communities" },
- { id: "explore", label: "Explore", hint: "Full dependency graph with dead/hot overlays" },
- { id: "coupling", label: "Coupling", hint: "Files that tend to change together" },
- { id: "deps", label: "Dependencies", hint: "Declared third-party dependencies" },
- { id: "symbols", label: "Symbols", hint: "Every function, class and export" },
+/** Legacy `?view=` spellings → canonical. `graph` predates the tab split and
+ * `explore` was the file-graph half of the old Map/Explore pair. */
+const VIEW_ALIASES: Record<string, CanonicalView> = {
+ map: "communities",
+ graph: "communities",
+ explore: "files",
+ deps: "packages",
+};
+
+/** Legacy `?viewMode=` values → the `?view=` + `?signal=` they now mean. */
+const LEGACY_VIEW_MODES: Record<string, { view: CanonicalView; signal?: "dead" | "hot" }> = {
+ architecture: { view: "communities" },
+ // The modules scope is gone; its nearest honest destination is the file
+ // graph, where "modules" is now a filter rather than a separate canvas.
+ module: { view: "files" },
+ full: { view: "files" },
+ dead: { view: "files", signal: "dead" },
+ hotfiles: { view: "files", signal: "hot" },
+ // "unified" lit dead AND hot at once; the node filter is exclusive now, so
+ // it resolves to the one the old toolbar rendered as active.
+ unified: { view: "files", signal: "dead" },
+};
+
+// Which tab a canonical view renders under. Both graph scopes are the Map tab.
+const TAB_FOR_VIEW: Record<CanonicalView, string> = {
+ communities: "map",
+ files: "map",
+ coupling: "coupling",
+ packages: "packages",
+ symbols: "symbols",
+};
+
+const TABS: { id: string; label: string }[] = [
+ { id: "map", label: "Map" },
+ { id: "coupling", label: "Coupling" },
+ { id: "packages", label: "Packages" },
+ { id: "symbols", label: "Symbols" },
];
-// Legacy ?view=graph deep links carried the graph scope in ?viewMode=. Scopes
-// that render file-level graphs map to Explore; the constellation maps to the
-// Communities tab.
-const EXPLORE_VIEW_MODES = new Set(["module", "full", "dead", "hotfiles", "unified"]);
+/** Landing view when a tab is clicked. Map opens on communities — the whole
+ * repo at a size you can read, rather than 1,500 circles. */
+const DEFAULT_VIEW_FOR_TAB: Record<string, CanonicalView> = {
+ map: "communities",
+ coupling: "coupling",
+ packages: "packages",
+ symbols: "symbols",
+};
export default function ArchitecturePage({
params,
@@ -71,9 +117,11 @@ export default function ArchitecturePage({
const router = useRouter();
const [rawView, setView] = useQueryState(
"view",
- parseAsStringLiteral(VIEWS).withDefault("map"),
+ parseAsStringLiteral(VIEWS).withDefault("communities"),
);
- const [viewModeParam] = useQueryState("viewMode");
+ const [viewModeParam, setViewModeParam] = useQueryState("viewMode");
+ const [, setSignal] = useQueryState("signal");
+ const [, setModule] = useQueryState("module");
const [, setFocus] = useQueryState("focus");
// The curated layers view now lives at /knowledge-graph. `?view=layers`
@@ -85,37 +133,42 @@ export default function ArchitecturePage({
}
}, [redirectsToKnowledgeGraph, repoId, router]);
- // Normalize the remaining legacy alias without a URL rewrite: ?view=graph →
- // map/explore by scope.
- let view: ArchView = rawView;
- if (rawView === "graph") {
- view = EXPLORE_VIEW_MODES.has(viewModeParam ?? "") ? "explore" : "map";
- }
+ // Translate a legacy `?viewMode=` once, then drop it. Doing this as an effect
+ // (rather than reading it every render) means the URL converges on the new
+ // shape instead of carrying both spellings forever.
+ const legacy = viewModeParam ? LEGACY_VIEW_MODES[viewModeParam] : undefined;
+ useEffect(() => {
+ if (!legacy) return;
+ void setView(legacy.view);
+ void setSignal(legacy.signal ?? null);
+ void setViewModeParam(null);
+ }, [legacy, setView, setSignal, setViewModeParam]);
- const handleScopeViewChange = useCallback(
- (next: "map" | "explore") => {
- void setView(next);
- },
- [setView],
- );
+ const view: CanonicalView =
+ legacy?.view ?? VIEW_ALIASES[rawView] ?? (rawView as CanonicalView);
+ const activeTab = TAB_FOR_VIEW[view] ?? "map";
+ // Leaving a tab drops the params that only meant something inside it, so the
+ // URL never carries a `signal=hot` into the Packages table where nothing
+ // reads it and nothing shows it.
const handleTabChange = useCallback(
(id: string) => {
- const next = id as ArchView;
- void setView(next);
- if (next !== "coupling") {
- void setFocus(null);
+ void setView(DEFAULT_VIEW_FOR_TAB[id] ?? "communities");
+ if (id !== "coupling") void setFocus(null);
+ if (id !== "map") {
+ void setSignal(null);
+ void setModule(null);
}
},
- [setView, setFocus],
+ [setView, setFocus, setSignal, setModule],
);
- // The active canonical tab. Map/Explore are the only graph-canvas tabs;
- // everything else resolves to its own panel.
- const activeTab: (typeof CANONICAL_VIEWS)[number]["id"] =
- view === "explore" || view === "deps" || view === "symbols" || view === "coupling"
- ? view
- : "map";
+ const handleScopeChange = useCallback(
+ (next: "communities" | "files") => {
+ void setView(next);
+ },
+ [setView],
+ );
if (redirectsToKnowledgeGraph) {
return null;
@@ -124,29 +177,18 @@ export default function ArchitecturePage({
return (
<div className="flex h-full flex-col">
<div className="shrink-0 px-4 pt-3 sm:px-6">
- <ViewTabs
- tabs={CANONICAL_VIEWS.map((v) => ({ id: v.id, label: v.label }))}
- value={activeTab}
- onValueChange={handleTabChange}
- />
+ <ViewTabs tabs={TABS} value={activeTab} onValueChange={handleTabChange} />
</div>
<div className="min-h-0 flex-1 overflow-auto">
{activeTab === "map" && (
<GraphView
repoId={repoId}
- scope="map"
- onScopeViewChange={handleScopeViewChange}
- />
- )}
- {activeTab === "explore" && (
- <GraphView
- repoId={repoId}
- scope="explore"
- onScopeViewChange={handleScopeViewChange}
+ scope={view === "files" ? "files" : "communities"}
+ onScopeChange={handleScopeChange}
/>
)}
- {activeTab === "deps" && <DependenciesView repoId={repoId} />}
+ {activeTab === "packages" && <DependenciesView repoId={repoId} />}
{activeTab === "symbols" && (
<div className="max-w-[1600px] space-y-6 p-4 sm:p-6">
<SymbolIndexHeader />
diff --git a/packages/web/src/components/architecture/dependencies-view.tsx b/packages/web/src/components/architecture/dependencies-view.tsx
index 9f084f911..afa4b6813 100644
--- a/packages/web/src/components/architecture/dependencies-view.tsx
+++ b/packages/web/src/components/architecture/dependencies-view.tsx
@@ -22,7 +22,10 @@ export function DependenciesView({ repoId }: { repoId: string }) {
<div>
<h1 className="mb-1 flex items-center gap-2 text-xl font-semibold text-[var(--color-text-primary)]">
<Package className="h-5 w-5 text-[var(--color-accent-primary)]" />
- Dependencies
+ {/* Matches the tab. "Dependencies" collided with the Map tab, which
+ IS the dependency graph — this page is the declared package
+ manifest, which is a different thing entirely. */}
+ Packages
</h1>
<p className="text-sm text-[var(--color-text-secondary)]">
Third-party dependencies declared in this repo&apos;s manifests.
diff --git a/packages/web/src/components/architecture/graph-view.tsx b/packages/web/src/components/architecture/graph-view.tsx
index 2aafed3e6..871726491 100644
--- a/packages/web/src/components/architecture/graph-view.tsx
+++ b/packages/web/src/components/architecture/graph-view.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
import useSWR from "swr";
import { useQueryState } from "nuqs";
import { useSearchParams } from "next/navigation";
@@ -8,49 +8,42 @@ import { GraphFlow } from "@/components/graph/graph-flow";
import { GraphDocPanel } from "@/components/graph/graph-doc-panel";
import { GraphCanvasShell } from "@repowise-dev/ui/graph/graph-canvas-shell";
import { GraphTruncationBanner } from "@repowise-dev/ui/graph/graph-truncation-banner";
+import {
+ GraphScopeSwitcher,
+ ModuleFilterSelect,
+} from "@repowise-dev/ui/graph/graph-scope-controls";
+import type { ModuleGroup } from "@repowise-dev/ui/graph/use-module-filter";
import { getGraph } from "@/lib/api/graph";
import type { GraphExportResponse } from "@/lib/api/types";
-type ViewMode = "module" | "full" | "architecture" | "dead" | "hotfiles" | "unified";
+type ViewMode = "full" | "architecture" | "dead" | "hotfiles" | "unified";
type ColorMode = "language" | "community";
+type Scope = "communities" | "files";
// `?colorMode=risk` links predate the removal of that lens; an unlisted value
// falls through to the "community" default rather than erroring.
const VALID_COLOR_MODES = new Set<ColorMode>(["language", "community"]);
-const VALID_VIEW_MODES = new Set<ViewMode>([
- "module",
- "full",
- "architecture",
- "dead",
- "hotfiles",
- "unified",
-]);
-
-// Scopes that render their own dedicated endpoint and therefore never touch the
-// capped full-graph endpoint (`/api/graph`). The constellation ("architecture")
-// and the module browser fetch their own graphs, so the page must NOT eagerly
-// fetch the full graph — nor show its truncation banner — for these scopes.
-const SCOPES_WITHOUT_FULL_GRAPH = new Set<ViewMode>(["architecture", "module"]);
+/** Scope + signal → the canvas's internal ViewMode. The overlay wins, because
+ * dead/hot are only ever drawn on the file graph. */
+function toViewMode(scope: Scope, signal: string | null): ViewMode {
+ if (scope === "communities") return "architecture";
+ if (signal === "dead") return "dead";
+ if (signal === "hot") return "hotfiles";
+ return "full";
+}
export function GraphView({
repoId,
- scope = "map",
- onScopeViewChange,
+ scope,
+ onScopeChange,
}: {
repoId: string;
- /** Which top-level Architecture mode hosts the canvas: Map = constellation,
- * Explore = file/module graphs. One mounted component serves both. */
- scope?: "map" | "explore";
- /** Scope switches inside the canvas (toolbar) re-sync `?view=` upstream. */
- onScopeViewChange?: (view: "map" | "explore") => void;
+ /** Controlled by the page, which owns `?view=`. */
+ scope: Scope;
+ onScopeChange: (scope: Scope) => void;
}) {
const searchParams = useSearchParams();
-
- const viewModeParam = searchParams.get("viewMode");
- const initialViewMode = VALID_VIEW_MODES.has((viewModeParam ?? "") as ViewMode)
- ? (viewModeParam as ViewMode)
- : undefined;
const initialNode = searchParams.get("node");
const colorModeParam = searchParams.get("colorMode");
@@ -60,25 +53,23 @@ export function GraphView({
const [, setSelectedNode] = useQueryState("node");
const [, setColorModeParam] = useQueryState("colorMode");
- const [, setViewModeParam] = useQueryState("viewMode");
+ const [signal, setSignal] = useQueryState("signal");
+ const [activeModule, setActiveModule] = useQueryState("module");
const [docNodeId, setDocNodeId] = useState<string | null>(null);
const [graphLimit, setGraphLimit] = useState<number | undefined>(undefined);
+ const [moduleGroups, setModuleGroups] = useState<ModuleGroup[]>([]);
- // The scope the canvas mounts into: a pinned node forces "full"; an explicit
- // ?viewMode= wins; otherwise the hosting mode decides (Map → constellation,
- // Explore → full graph).
- const mountViewMode: ViewMode = initialNode
- ? "full"
- : initialViewMode ?? (scope === "explore" ? "full" : "architecture");
-
- // Track the live scope so we only fetch the capped full graph (and render
- // its truncation banner) for scopes that actually use it. Remount the canvas
- // (flowKey) when the truncation banner jumps to the constellation — that is
- // a host-initiated scope change, which GraphFlow only reads at mount.
- const [viewMode, setViewMode] = useState<ViewMode>(mountViewMode);
- const [flowKey, setFlowKey] = useState(0);
- const [forcedViewMode, setForcedViewMode] = useState<ViewMode | null>(null);
- const usesFullGraph = !SCOPES_WITHOUT_FULL_GRAPH.has(viewMode);
+ // A pinned node is always a file, so a `?node=` link forces the file scope
+ // however the URL spells the rest.
+ const effectiveScope: Scope = initialNode ? "files" : scope;
+ const viewMode = toViewMode(effectiveScope, signal);
+
+ // Only the unfiltered file scope renders the capped `/api/graph` payload.
+ // The constellation, and each of the dead/hot signals, has its own endpoint —
+ // so neither the fetch nor the truncation banner belongs to them. The banner
+ // used to show under the signals too, announcing "1,500 of 3,194 files" over
+ // a canvas drawing 734 nodes that came from somewhere else entirely.
+ const usesFullGraph = effectiveScope === "files" && !signal;
const { data: graphData } = useSWR<GraphExportResponse>(
usesFullGraph ? `graph:${repoId}:${graphLimit ?? "default"}` : null,
@@ -89,8 +80,6 @@ export function GraphView({
// Click a file node → open doc panel
const handleNodeClick = useCallback(
(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);
@@ -114,19 +103,16 @@ export function GraphView({
setDocNodeId(null);
}, []);
- // In-canvas scope switches keep the URL honest: `?viewMode=` mirrors the
- // graph scope and `?view=` flips between Map and Explore.
+ // The canvas still owns the dead/hot node filter, and reports it as a
+ // ViewMode. Scope changes never arrive this way any more — the switcher in
+ // the header drives those — so this only has to keep `?signal=` honest.
const handleViewModeChange = useCallback(
(mode: ViewMode) => {
- setViewMode(mode);
- void setViewModeParam(mode === "architecture" ? null : mode);
- onScopeViewChange?.(mode === "architecture" ? "map" : "explore");
+ void setSignal(mode === "dead" ? "dead" : mode === "hotfiles" ? "hot" : null);
},
- [onScopeViewChange, setViewModeParam],
+ [setSignal],
);
- // Color-mode changes (toolbar or 1/2/3 keys) sync to the URL so shared
- // links restore the same coloring.
const handleColorModeChange = useCallback(
(mode: ColorMode) => {
void setColorModeParam(mode);
@@ -134,32 +120,57 @@ export function GraphView({
[setColorModeParam],
);
- // "Switch to the Knowledge Graph" from the truncation banner: remount the
- // canvas in the constellation scope. No page reload.
+ // "See all of them grouped" from the truncation banner: the whole repo, at
+ // the scale where all of it fits.
const handleSwitchToArchitecture = useCallback(() => {
- setForcedViewMode("architecture");
- setFlowKey((k) => k + 1);
- handleViewModeChange("architecture");
- }, [handleViewModeChange]);
+ onScopeChange("communities");
+ }, [onScopeChange]);
+
+ const handleScopeChange = useCallback(
+ (next: Scope) => {
+ // The module filter is a file-scope concept; carrying it into the
+ // communities view would leave a control set to something invisible.
+ if (next === "communities") void setActiveModule(null);
+ onScopeChange(next);
+ },
+ [onScopeChange, setActiveModule],
+ );
+
+ const isCommunities = effectiveScope === "communities";
- const isMap = scope === "map" && !initialNode;
+ const headerControls = useMemo(
+ () => (
+ <div className="flex flex-wrap items-center gap-2">
+ {!isCommunities && (
+ <ModuleFilterSelect
+ groups={moduleGroups}
+ activeModule={activeModule}
+ onModuleChange={(next) => void setActiveModule(next)}
+ />
+ )}
+ <GraphScopeSwitcher scope={effectiveScope} onScopeChange={handleScopeChange} />
+ </div>
+ ),
+ [isCommunities, moduleGroups, activeModule, setActiveModule, effectiveScope, handleScopeChange],
+ );
return (
<GraphCanvasShell
- // No title. The tab above already says "Communities" / "Explore", and a
- // heading that repeats the control you just clicked spends a band of
- // chrome saying nothing — this page carried three of them above the
- // canvas. What is left is the one line that adds something the tab
- // cannot: what to do with the thing you are looking at.
+ // No title. The tab above already says "Map", and the scope switcher on
+ // the right says which zoom you are at — a heading that repeats the
+ // control you just clicked spends a band of chrome saying nothing. What
+ // is left is the one line that adds something neither can: what to do
+ // with the thing you are looking at.
description={
- isMap
+ isCommunities
? "Each circle is a detected community, sized by how much code it holds. Double-click one to open it up."
: "Every file and how it depends on the others. Pick two files to trace a path between them."
}
+ titleActions={headerControls}
banner={
- // Shown only when the current scope renders the capped full graph and
- // the server actually capped it. Constellation / module scopes use
- // their own endpoints, so the banner stays hidden.
+ // Shown only when the file scope actually got capped. This line is the
+ // one place the node count is stated, and it only became true when the
+ // export stopped counting symbol nodes as files.
usesFullGraph && graphData?.truncated && graphData.total_node_count != null ? (
<GraphTruncationBanner
shown={graphData.nodes.length}
@@ -171,7 +182,6 @@ export function GraphView({
) : undefined
}
overlay={
- // Doc panel — shows on file click. Single right-rail surface.
docNodeId ? (
<GraphDocPanel
repoId={repoId}
@@ -182,18 +192,17 @@ export function GraphView({
}
>
<GraphFlow
- key={flowKey}
repoId={repoId}
- initialViewMode={forcedViewMode ?? mountViewMode}
- // Color mode is controlled here so the URL (?colorMode=) is the single
- // source of truth — back/forward and shared links restore it. Defaults
- // to community coloring, matching the canvas's own default.
+ // Scope is controlled: `?view=` is the single source of truth, so
+ // back/forward and shared links restore it without a remount.
+ viewMode={viewMode}
+ activeModule={activeModule}
+ // Same value the banner reports, so the caption and the canvas can
+ // never disagree about how many files are drawn.
+ graphLimit={graphLimit}
+ onModuleGroupsChange={setModuleGroups}
colorMode={initialColorMode ?? "community"}
initialSelectedNode={initialNode}
- // Communities locks to the constellation; Explore drops the
- // constellation scope (it lives in the Knowledge Graph view) so the
- // toolbar offers only Modules / Full.
- availableScopes={scope === "explore" ? ["modules", "full"] : undefined}
onNodeClick={handleNodeClick}
onNodeViewDocs={handleNodeViewDocs}
onCommunityPanelOpen={handleCommunityPanelOpen}
diff --git a/packages/web/src/components/graph/graph-flow.tsx b/packages/web/src/components/graph/graph-flow.tsx
index 8c5e52dbb..16b52c449 100644
--- a/packages/web/src/components/graph/graph-flow.tsx
+++ b/packages/web/src/components/graph/graph-flow.tsx
@@ -8,7 +8,6 @@ import {
type GraphFlowProps as GraphFlowShellProps,
} from "@repowise-dev/ui/graph/graph-flow";
import {
- useModuleGraph,
useGraph,
useArchitectureGraph,
useArchitectureCommunityGraph,
@@ -23,19 +22,30 @@ import { PathFinderPanel } from "./path-finder-panel";
import { GraphCommunityPanel } from "./graph-community-panel";
import type {
GraphExport,
- ModuleGraph,
ExecutionFlows,
CommunitySummaryItem,
ArchitectureGraph,
CommunitySlice,
} from "@repowise-dev/types/graph";
-type ViewMode = "module" | "full" | "architecture" | "dead" | "hotfiles" | "unified";
+type ViewMode = "full" | "architecture" | "dead" | "hotfiles" | "unified";
export interface GraphFlowProps {
repoId: string;
repoName?: string;
initialViewMode?: ViewMode;
+ /** Controlled scope — the page owns it via `?view=`. */
+ viewMode?: ViewMode;
+ /** Controlled module filter — the page owns it via `?module=`. */
+ activeModule?: string | null;
+ /** Node cap for the full-graph fetch, stepped up by the truncation banner.
+ * Must be the SAME value the banner is reporting: this and the banner's own
+ * fetch share an SWR key, so a mismatch means the caption describes a
+ * payload the canvas never received. It described one for a while — "Load
+ * more" raised the banner's limit and nothing else, so the sentence said
+ * 3,000 over a canvas still drawing 1,500. */
+ graphLimit?: number | undefined;
+ onModuleGroupsChange?: GraphFlowShellProps["onModuleGroupsChange"];
initialColorMode?: GraphFlowShellProps["initialColorMode"];
/** Controlled node color mode — the page URL-syncs it and passes it down. */
colorMode?: GraphFlowShellProps["colorMode"];
@@ -52,14 +62,16 @@ export interface GraphFlowProps {
onViewModeChange?: (mode: ViewMode) => void;
/** Fired when the node color mode changes so the page can sync the URL. */
onColorModeChange?: GraphFlowShellProps["onColorModeChange"];
- /** Restricts the in-canvas scope cluster (Explore omits the constellation). */
- availableScopes?: GraphFlowShellProps["availableScopes"];
}
export function GraphFlow({
repoId,
repoName,
initialViewMode,
+ viewMode: controlledViewMode,
+ activeModule,
+ graphLimit,
+ onModuleGroupsChange,
initialColorMode,
colorMode,
initialSelectedNode,
@@ -68,25 +80,21 @@ export function GraphFlow({
onCommunityPanelOpen,
onViewModeChange,
onColorModeChange,
- availableScopes,
}: GraphFlowProps) {
const router = useRouter();
// Constellation (Knowledge Graph) is the default scope.
- const [viewMode, setViewMode] = useState<ViewMode>(initialViewMode ?? "architecture");
- const [modulePath, setModulePath] = useState<string[]>([]);
- const [hasExpandedModules, setHasExpandedModules] = useState(false);
+ const [viewModeState, setViewModeState] = useState<ViewMode>(
+ initialViewMode ?? "architecture",
+ );
+ const viewMode = controlledViewMode ?? viewModeState;
// Currently-expanded constellation hubs (community ids). Drives the slice
// fetch; the shell owns the actual expand/collapse interaction state.
const [expandedHubs, setExpandedHubs] = useState<number[]>([]);
- const isDrilledDown = modulePath.length > 0;
- const isModuleView = viewMode === "module";
- const { graph: moduleGraph, isLoading: moduleLoading } = useModuleGraph(
- isModuleView ? repoId : null,
- );
- const needsFullGraph = isDrilledDown || viewMode === "full" || viewMode === "unified" || hasExpandedModules;
+ const needsFullGraph = viewMode === "full" || viewMode === "unified";
const { graph: fullGraph, isLoading: fullLoading } = useGraph(
needsFullGraph ? repoId : null,
+ graphLimit,
);
const { graph: archGraph, isLoading: archLoading } = useArchitectureGraph(null);
// Constellation community super-graph — only fetched for the radial scope.
@@ -107,13 +115,10 @@ export function GraphFlow({
const { repo } = useRepo(repoId);
const resolvedRepoName = repoName ?? repo?.name;
const { communities } = useCommunities(repoId);
- // Flow traces highlight file-level nodes, but the picker must also work from
- // the module overview: selecting a flow there makes the shell jump to the
- // full graph (enterFullViewFromModule) and highlight the trace. Dead/hot
- // scopes render file-level graphs too, so flows work there as well — only
- // the constellation skips the fetch.
+ // Flow traces highlight file-level nodes; the constellation has none, so it
+ // skips the fetch. Dead/hot render file graphs, so flows work there too.
const { flows: executionFlowsData } = useExecutionFlows(
- viewMode !== "architecture" || needsFullGraph ? repoId : null,
+ viewMode !== "architecture" ? repoId : null,
{
top_n: 10,
max_depth: 6,
@@ -122,8 +127,6 @@ export function GraphFlow({
return (
<GraphFlowShell
- moduleGraph={moduleGraph as ModuleGraph | undefined}
- isLoadingModuleGraph={moduleLoading}
fullGraph={fullGraph as GraphExport | undefined}
isLoadingFullGraph={fullLoading}
architectureGraph={archGraph as GraphExport | undefined}
@@ -140,17 +143,17 @@ export function GraphFlow({
communities={communities as CommunitySummaryItem[] | undefined}
executionFlows={executionFlowsData as ExecutionFlows | undefined}
initialViewMode={initialViewMode}
+ viewMode={controlledViewMode}
+ activeModule={activeModule}
+ onModuleGroupsChange={onModuleGroupsChange}
initialColorMode={initialColorMode}
colorMode={colorMode}
initialSelectedNode={initialSelectedNode}
onViewModeChange={(mode) => {
- setViewMode(mode);
+ setViewModeState(mode);
onViewModeChange?.(mode);
}}
onColorModeChange={onColorModeChange}
- availableScopes={availableScopes}
- onModulePathChange={setModulePath}
- onExpandedModulesChange={(expanded) => setHasExpandedModules(expanded.size > 0)}
onNodeClick={onNodeClick}
onNodeViewDocs={onNodeViewDocs}
onNodeViewSymbols={(nodeId) =>
diff --git a/packages/web/src/lib/hooks/use-graph.ts b/packages/web/src/lib/hooks/use-graph.ts
index 01bc4daa3..9d6100f00 100644
--- a/packages/web/src/lib/hooks/use-graph.ts
+++ b/packages/web/src/lib/hooks/use-graph.ts
@@ -14,7 +14,6 @@ import {
getGraph,
getGraphMetrics,
getHotFilesGraph,
- getModuleGraph,
getZoomMap,
} from "@/lib/api/graph";
import type {
@@ -28,7 +27,6 @@ import type {
GraphExportResponse,
GraphMetricsResponse,
HotFilesGraphResponse,
- ModuleGraphResponse,
} from "@/lib/api/types";
const SWR_OPTS = { revalidateOnFocus: false, revalidateOnReconnect: false };
@@ -57,15 +55,6 @@ export function useGraph(repoId: string | null, limit?: number) {
return { graph: data, error, isLoading };
}
-export function useModuleGraph(repoId: string | null) {
- const { data, error, isLoading } = useSWR<ModuleGraphResponse>(
- repoId ? `module-graph:${repoId}` : null,
- () => getModuleGraph(repoId!),
- SWR_OPTS,
- );
- return { graph: data, error, isLoading };
-}
-
/**
* Community super-graph for the constellation (radial Knowledge Graph) scope.
* Conditional SWR: only fetched when a repoId is given (the wrapper gates it
diff --git a/tests/unit/server/test_graph.py b/tests/unit/server/test_graph.py
index 6625ff196..7072699f8 100644
--- a/tests/unit/server/test_graph.py
+++ b/tests/unit/server/test_graph.py
@@ -122,6 +122,46 @@ async def test_export_graph_carries_edge_type(client: AsyncClient, app) -> None:
assert imports["edge_type"] == "imports"
+async def test_export_graph_excludes_symbol_nodes(client: AsyncClient, app) -> None:
+ """Symbol nodes never reach the export, and don't count toward the total.
+
+ `graph_nodes` holds a row per extracted symbol as well as per file, and
+ PageRank ranks both kinds together — so a symbol can outrank a real file and
+ take its slot under the node cap, then render as a file circle with a
+ `node_id` (`path::Symbol`) that is not a path. The client has no way to tell
+ them apart: `node_type` is not serialized.
+ """
+ repo = await create_test_repo(client)
+ session_factory = app.state.session_factory
+ await _populate_graph(session_factory, repo["id"])
+ async with get_session(session_factory) as session:
+ await crud.batch_upsert_graph_nodes(
+ session,
+ repo["id"],
+ [
+ {
+ # Outranks both files, so a pagerank-ordered export without
+ # the filter would put it first.
+ "node_id": "src/main.py::main",
+ "node_type": "symbol",
+ "language": "python",
+ "symbol_count": 1,
+ "pagerank": 0.99,
+ "betweenness": 0.9,
+ "community_id": 0,
+ },
+ ],
+ )
+
+ resp = await client.get(f"/api/graph/{repo['id']}")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert [n["node_id"] for n in data["nodes"]] == ["src/main.py", "src/utils.py"]
+ # The total is a file count too, so "1,500 of N" reads honestly.
+ assert data["total_node_count"] == 2
+
+
@pytest.mark.asyncio
async def test_export_graph_repo_not_found(client: AsyncClient) -> None:
resp = await client.get("/api/graph/nonexistent")
@@ -340,7 +380,12 @@ async def test_export_graph_truncation_reserves_dead_and_hot_nodes(
@pytest.mark.asyncio
async def test_export_graph_truncation_reserves_flow_members(client: AsyncClient, app) -> None:
- """Execution-flow trace members must survive truncation."""
+ """The files an execution-flow trace runs through must survive truncation.
+
+ `calls` edges only join symbol nodes, so the trace is a list of
+ `file.py::symbol` ids while the export carries files — the reservation is
+ for the containing files, which is what the canvas can highlight.
+ """
repo = await create_test_repo(client)
async with get_session(app.state.session_factory) as session:
await crud.batch_upsert_graph_nodes(
@@ -357,6 +402,19 @@ async def test_export_graph_truncation_reserves_flow_members(client: AsyncClient
}
for i in range(3)
]
+ + [
+ # The files the traced symbols live in. Low PageRank, so only
+ # the flow reservation can keep them under a limit of 3.
+ {
+ "node_id": path,
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 1,
+ "pagerank": 0.001,
+ "community_id": 0,
+ }
+ for path in ("src/api.py", "src/service.py")
+ ]
+ [
{
"node_id": "src/api.py::handler",
@@ -402,9 +460,11 @@ async def test_export_graph_truncation_reserves_flow_members(client: AsyncClient
assert data["truncated"] is True
kept = {n["node_id"] for n in data["nodes"]}
- # The entry point and its traced callee are reserved despite low PageRank.
- assert "src/api.py::handler" in kept
- assert "src/service.py::run" in kept
+ # The entry point's file and its traced callee's file are reserved despite
+ # low PageRank; the symbol nodes themselves never enter a file-only export.
+ assert "src/api.py" in kept
+ assert "src/service.py" in kept
+ assert "src/api.py::handler" not in kept
assert "src/core_0.py" in kept