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.

fix(graph): keep dead/hot/flow nodes visible on capped graphs; explain layout and overlay states (#714)

Swati Ahuja958869000c3a
diff --git a/packages/api-client/src/types/graph.ts b/packages/api-client/src/types/graph.ts
index ab31aab51..ef20c9f67 100644
--- a/packages/api-client/src/types/graph.ts
+++ b/packages/api-client/src/types/graph.ts
@@ -41,9 +41,15 @@ export interface GraphLike<N> {
}
export interface GraphExportResponse extends GraphLike<GraphNodeResponse> {
- /** Server set this true when the response was capped to top-N by PageRank. */
+ /** Server set this true when the response was capped (PageRank fill +
+ * reserved dead/hot/flow slots). */
truncated?: boolean;
total_node_count?: number;
+ /** Repo-wide signal totals vs how many nodes are in this response. */
+ dead_total?: number | null;
+ dead_in_view?: number | null;
+ hot_total?: number | null;
+ hot_in_view?: number | null;
}
// Community slice (Phase G4 — constellation blossom)
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 2c0c070cf..343720d9f 100644
--- a/packages/server/src/repowise/server/routers/graph/full_graph.py
+++ b/packages/server/src/repowise/server/routers/graph/full_graph.py
@@ -2,12 +2,14 @@
from __future__ import annotations
-from fastapi import APIRouter, Depends, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from fastapi import APIRouter, Depends, Query
+from repowise.core.persistence import crud
from repowise.core.persistence.models import GraphEdge, GraphNode
from repowise.server.deps import get_db_session
+from repowise.server.mcp_server._graph_utils import _node_id_is_excluded
from repowise.server.routers.graph._common import _escape_like, with_repo
from repowise.server.schemas import GraphExportResponse, NodeSearchResult
from repowise.server.services.graph_views import edge_response
@@ -17,14 +19,67 @@ from repowise.server.services.node_signals import (
to_graph_node,
)
-# Cap on full-graph export; above this we return top-N by PageRank with truncated=True.
-# Sized to keep the client-side force layout responsive; clients can step the
-# limit up via the truncation banner.
+# Cap on full-graph export; above this we return a capped selection with
+# truncated=True. Sized to keep the client-side force layout responsive;
+# clients can step the limit up via the truncation banner.
_FULL_GRAPH_NODE_CAP = 1500
+# When truncating, reserve up to this many slots per signal class (dead-code
+# files, hotspots, execution-flow members) so flagged nodes survive selection
+# even though their PageRank is low — dead code in particular is
+# anti-correlated with PageRank, so a pure top-N cut would drop nearly all of
+# it and overlays would silently render nothing. The remaining budget fills
+# by PageRank as before.
+_RESERVED_CLASS_CAP = 150
+
+# Mirror the /execution-flows defaults the web client requests, so the
+# reserved flow members match the traces the flows panel highlights.
+_FLOW_ENTRY_POINTS = 10
+_FLOW_MAX_DEPTH = 6
+
router = APIRouter()
+def _flow_member_ids(
+ edges: list[GraphEdge],
+ entry_ids: list[str],
+ max_depth: int = _FLOW_MAX_DEPTH,
+) -> set[str]:
+ """Node ids 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.
+ """
+ adjacency: dict[str, list[GraphEdge]] = {}
+ for e in edges:
+ if e.edge_type == "calls":
+ adjacency.setdefault(e.source_node_id, []).append(e)
+
+ members: set[str] = set()
+ for entry_id in entry_ids:
+ visited: set[str] = {entry_id}
+ current = entry_id
+ for _ in range(max_depth):
+ best_id: str | None = None
+ best_conf = -1.0
+ for e in adjacency.get(current, ()):
+ tid = e.target_node_id
+ conf = e.confidence if e.confidence is not None else 0.0
+ if tid in visited or conf < 0.5 or _node_id_is_excluded(tid):
+ continue
+ if conf > best_conf:
+ best_conf = conf
+ best_id = tid
+ if best_id is None:
+ break
+ visited.add(best_id)
+ current = best_id
+ members |= visited
+ return members
+
+
@router.get("/{repo_id}/nodes/search", response_model=list[NodeSearchResult])
async def search_nodes(
repo_id: str,
@@ -57,15 +112,19 @@ async def export_graph(
_FULL_GRAPH_NODE_CAP,
ge=1,
le=6000,
- description="Maximum nodes to return (top-N by PageRank). Stepped up by the client.",
+ description="Maximum nodes to return. Stepped up by the client.",
),
session: AsyncSession = Depends(get_db_session), # noqa: B008
_repo: object = Depends(with_repo),
) -> GraphExportResponse:
"""Export the full dependency graph in D3 force-directed format.
- Large repos are capped to top-N nodes by PageRank with ``truncated=True``;
- clients should surface a banner and let the user request unrestricted load.
+ 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
+ fills the rest by PageRank, so signal overlays always have their nodes in
+ view. ``dead_total``/``hot_total`` vs ``*_in_view`` let clients say
+ "showing 12 of 37" instead of rendering silently-empty overlays.
"""
node_result = await session.execute(
select(GraphNode)
@@ -75,15 +134,50 @@ async def export_graph(
all_nodes = node_result.scalars().all()
total_node_count = len(all_nodes)
truncated = total_node_count > limit
- nodes = all_nodes[:limit] if truncated else all_nodes
- kept_ids = {n.node_id for n in nodes}
edge_result = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id))
- edges = edge_result.scalars().all()
+ edges = list(edge_result.scalars().all())
+
+ # Repo-wide signals: needed for the *_total counts and, when truncating,
+ # for reserved-slot selection (flagged nodes are known before the cut).
+ signals = await collect_node_signals(session, repo_id, None)
+
+ def _sig(n: GraphNode):
+ return signals.get(n.node_id, EMPTY_SIGNALS)
+
+ dead_total = sum(1 for n in all_nodes if _sig(n).is_dead)
+ hot_total = sum(1 for n in all_nodes if _sig(n).is_hotspot)
- signals = await collect_node_signals(session, repo_id, list(kept_ids) if truncated else None)
+ if truncated:
+ entry_nodes = await crud.get_top_entry_points(
+ session, repo_id, min_score=0.0, limit=_FLOW_ENTRY_POINTS
+ )
+ flow_ids = _flow_member_ids(edges, [n.node_id for n in entry_nodes])
+
+ kept_ids: set[str] = set()
+ flagged_classes = (
+ lambda n: _sig(n).is_dead,
+ lambda n: _sig(n).is_hotspot,
+ lambda n: n.node_id in flow_ids,
+ )
+ for flagged in flagged_classes:
+ picked = 0
+ for n in all_nodes: # PageRank order → best flagged nodes first
+ if picked >= _RESERVED_CLASS_CAP or len(kept_ids) >= limit:
+ break
+ if n.node_id not in kept_ids and flagged(n):
+ kept_ids.add(n.node_id)
+ picked += 1
+ for n in all_nodes:
+ if len(kept_ids) >= limit:
+ break
+ kept_ids.add(n.node_id)
+ nodes = [n for n in all_nodes if n.node_id in kept_ids]
+ else:
+ nodes = list(all_nodes)
+ kept_ids = {n.node_id for n in nodes}
- node_responses = [to_graph_node(n, signals.get(n.node_id, EMPTY_SIGNALS)) for n in nodes]
+ node_responses = [to_graph_node(n, _sig(n)) for n in nodes]
link_responses = [
edge_response(e)
@@ -96,4 +190,8 @@ async def export_graph(
links=link_responses,
truncated=truncated,
total_node_count=total_node_count,
+ dead_total=dead_total,
+ dead_in_view=sum(1 for n in nodes if _sig(n).is_dead),
+ hot_total=hot_total,
+ hot_in_view=sum(1 for n in nodes if _sig(n).is_hotspot),
)
diff --git a/packages/server/src/repowise/server/schemas/graph.py b/packages/server/src/repowise/server/schemas/graph.py
index ed95e7f91..150260535 100644
--- a/packages/server/src/repowise/server/schemas/graph.py
+++ b/packages/server/src/repowise/server/schemas/graph.py
@@ -38,9 +38,18 @@ class GraphExportResponse(BaseModel):
nodes: list[GraphNodeResponse]
links: list[GraphEdgeResponse]
# When the graph is too large to return in full, the server caps the response
- # to top-N nodes by PageRank. Clients should surface a banner.
+ # (PageRank fill + reserved slots for dead/hot/flow nodes). Clients should
+ # surface a banner.
truncated: bool = False
total_node_count: int | None = None
+ # Signal-overlay counts: repo-wide totals vs how many made it into this
+ # response. Lets clients render "12 of 37 dead files in view" and
+ # distinguish "none in repo" from "none in view". None on endpoints that
+ # don't compute them.
+ dead_total: int | None = None
+ dead_in_view: int | None = None
+ hot_total: int | None = None
+ hot_in_view: int | None = None
# Architecture / community super-node graph
diff --git a/packages/types/src/graph.ts b/packages/types/src/graph.ts
index 7821ff80a..98d6c6b2f 100644
--- a/packages/types/src/graph.ts
+++ b/packages/types/src/graph.ts
@@ -49,9 +49,18 @@ export interface GraphLink {
export interface GraphExport {
nodes: GraphNode[];
links: GraphLink[];
- /** Server flagged response as capped (top-N by PageRank). UI should banner. */
+ /** Server flagged response as capped (PageRank fill + reserved dead/hot/flow
+ * slots). UI should banner. */
truncated?: boolean;
total_node_count?: number;
+ /** Signal-overlay counts: repo-wide totals vs how many nodes are in this
+ * response. Lets the UI say "12 of 37 dead files in view" and distinguish
+ * "none in the repo" from "none in the loaded view". Optional — older
+ * backends and endpoints that don't compute them omit these. */
+ dead_total?: number | null;
+ dead_in_view?: number | null;
+ hot_total?: number | null;
+ hot_in_view?: number | null;
}
// ---------------------------------------------------------------------------
diff --git a/packages/ui/__tests__/graph/graph-flow.test.tsx b/packages/ui/__tests__/graph/graph-flow.test.tsx
index db4a7d62c..0f7f5c7d3 100644
--- a/packages/ui/__tests__/graph/graph-flow.test.tsx
+++ b/packages/ui/__tests__/graph/graph-flow.test.tsx
@@ -62,4 +62,44 @@ describe("GraphFlow shell", () => {
screen.getByRole("button", { name: "Language" }).getAttribute("aria-pressed"),
).toBe("false");
});
+
+ it("offers an exclusive All / Hot / Dead node filter", () => {
+ render(<GraphFlow {...baseProps} initialViewMode="full" />);
+
+ expect(screen.getByRole("radio", { name: "All" }).getAttribute("aria-checked")).toBe("true");
+
+ fireEvent.click(screen.getByRole("radio", { name: "Dead" }));
+ expect(screen.getByRole("radio", { name: "Dead" }).getAttribute("aria-checked")).toBe("true");
+ expect(screen.getByRole("radio", { name: "Hot" }).getAttribute("aria-checked")).toBe("false");
+ expect(screen.getByRole("radio", { name: "All" }).getAttribute("aria-checked")).toBe("false");
+
+ // Selecting Hot replaces Dead — the two can never be active together.
+ fireEvent.click(screen.getByRole("radio", { name: "Hot" }));
+ expect(screen.getByRole("radio", { name: "Hot" }).getAttribute("aria-checked")).toBe("true");
+ expect(screen.getByRole("radio", { name: "Dead" }).getAttribute("aria-checked")).toBe("false");
+ });
+
+ it("says when dead files exist but fell outside the loaded view", () => {
+ render(
+ <GraphFlow
+ {...baseProps}
+ initialViewMode="full"
+ fullGraph={{ nodes: [], links: [], truncated: true, dead_total: 3 }}
+ />,
+ );
+ fireEvent.click(screen.getByRole("radio", { name: "Dead" }));
+ expect(screen.getByText("Dead files are outside the loaded view")).toBeTruthy();
+ });
+
+ it("says when the repo simply has no dead files", () => {
+ render(
+ <GraphFlow
+ {...baseProps}
+ initialViewMode="full"
+ fullGraph={{ nodes: [], links: [], dead_total: 0 }}
+ />,
+ );
+ fireEvent.click(screen.getByRole("radio", { name: "Dead" }));
+ expect(screen.getByText("No dead files in this repo")).toBeTruthy();
+ });
});
diff --git a/packages/ui/src/graph/graph-flow.tsx b/packages/ui/src/graph/graph-flow.tsx
index 7ed243b2b..5bd9929de 100644
--- a/packages/ui/src/graph/graph-flow.tsx
+++ b/packages/ui/src/graph/graph-flow.tsx
@@ -9,7 +9,7 @@ import {
type ReactNode,
} from "react";
import { useTheme } from "next-themes";
-import { ChevronRight, Home } from "lucide-react";
+import { ChevronRight, Home, X } from "lucide-react";
import { Skeleton } from "../ui/skeleton";
import { EmptyState } from "../shared/empty-state";
import { GraphProvider, type GraphContextValue, type Signal } from "./context";
@@ -209,6 +209,9 @@ export function GraphFlow(props: GraphFlowProps) {
const [highlightedEdges, setHighlightedEdges] = useState<Set<string>>(new Set());
const [showPathFinder, setShowPathFinder] = useState(false);
const [showShortcutHelp, setShowShortcutHelp] = useState(false);
+ // Explanation surfaced when the hierarchical layout refuses to run (too
+ // many nodes) — otherwise the toggle looks active but does nothing.
+ const [layoutNotice, setLayoutNotice] = useState<string | null>(null);
// Constellation is the default scope → its fixed radial layout.
const [layoutMode, setLayoutMode] = useState<LayoutMode>(
(initialViewMode ?? "architecture") === "architecture" ? "radial" : "force",
@@ -441,6 +444,13 @@ export function GraphFlow(props: GraphFlowProps) {
const hasDeadSignal = activeSignals.has("dead");
const hasHotSignal = activeSignals.has("hot");
+ // Repo-wide signal totals, when the backend provides them (the overlay's
+ // own payload wins over the capped full graph). Distinguishes "the repo has
+ // none" from "none survived the node cap" in the empty states below.
+ const deadTotal =
+ 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;
@@ -701,6 +711,61 @@ export function GraphFlow(props: GraphFlowProps) {
const effectiveNodeDataMap = sigmaNodeMaps?.fileMap ?? new Map<string, FileNodeData>();
const effectiveModuleDataMap = sigmaNodeMaps?.modMap ?? new Map<string, ModuleNodeData>();
+ // How many flagged nodes actually made it into the rendered graph — paired
+ // with the repo-wide totals to caption the dead/hot views honestly.
+ const overlayStats = useMemo(() => {
+ if (!sigmaGraph) return null;
+ let deadInView = 0;
+ let hotInView = 0;
+ sigmaGraph.forEachNode((_, attrs) => {
+ if (attrs.isDead) deadInView++;
+ if (attrs.isHotspot) hotInView++;
+ });
+ return { deadInView, hotInView };
+ }, [sigmaGraph]);
+
+ const isDeadView = viewMode === "dead" || viewMode === "unified";
+ const isHotView = viewMode === "hotfiles" || viewMode === "unified";
+
+ // Trace nodes of the selected execution flow that fell outside the loaded
+ // node set — highlighting/focus silently no-op for them, so tell the user.
+ const activeFlowMissingCount = useMemo(() => {
+ 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;
+ }, [activeFlowIdx, executionFlows, sigmaGraph]);
+
+ // Empty-state copy for a dead/hot view that resolved to zero nodes. Two
+ // different failure modes deserve two different messages: the repo really
+ // has no flagged files, vs the flagged files exist but fell outside the
+ // capped node selection.
+ const overlayEmptyState = (() => {
+ if (!isDeadView && !isHotView) return null;
+ const kind = isDeadView && isHotView ? "dead or hot" : isDeadView ? "dead" : "hot";
+ const total = isDeadView && isHotView ? null : isDeadView ? deadTotal : hotTotal;
+ if (total === 0) {
+ return {
+ title: `No ${kind} files in this repo`,
+ description:
+ kind === "dead"
+ ? "No open dead-code findings — nothing to overlay."
+ : "No files are flagged as hotspots — nothing to overlay.",
+ };
+ }
+ if (total != null && total > 0) {
+ return {
+ title: `${kind === "dead" ? "Dead" : "Hot"} files are outside the loaded view`,
+ description: `None of the ${total} ${kind} files are in the loaded node set. Load more nodes from the banner, or narrow the scope to bring them in.`,
+ };
+ }
+ return {
+ title: `No ${kind} files in this view`,
+ description:
+ "The repo may have none, or they may fall outside the loaded node set.",
+ };
+ })();
+
const panToNode = useCallback((nodeId: string) => {
sigmaRef.current?.focusNode(nodeId);
}, []);
@@ -852,6 +917,11 @@ export function GraphFlow(props: GraphFlowProps) {
setShowShortcutHelp(false);
return true;
}
+ if (showFlows) {
+ setShowFlows(false);
+ setActiveFlowIdx(null);
+ return true;
+ }
if (selectedNodeId !== null || communityPanelId !== null) {
setSelectedNodeId(null);
setCommunityPanelId(null);
@@ -910,6 +980,7 @@ export function GraphFlow(props: GraphFlowProps) {
setViewMode(v);
// Constellation is fixed-radial; other scopes default back to FA2.
setLayoutMode(v === "architecture" ? "radial" : "force");
+ setLayoutNotice(null);
setModulePath([]);
setHighlightedPath(new Set());
setHighlightedEdges(new Set());
@@ -921,6 +992,7 @@ export function GraphFlow(props: GraphFlowProps) {
const handleLayoutModeChange = useCallback((mode: LayoutMode) => {
setLayoutMode(mode);
+ setLayoutNotice(null);
}, []);
const handleGraphThemeChange = useCallback(
@@ -1034,7 +1106,7 @@ export function GraphFlow(props: GraphFlowProps) {
return (
<GraphProvider value={ctxValue}>
<div className="relative w-full h-full" style={{ touchAction: "none", ...(graphTheme === "dark" ? { background: "var(--color-bg-inset)" } : {}) }} aria-label="Dependency graph">
- {sigmaGraph ? (
+ {sigmaGraph && sigmaGraph.order > 0 ? (
<SigmaCanvas
ref={sigmaRef}
graph={sigmaGraph}
@@ -1059,6 +1131,7 @@ export function GraphFlow(props: GraphFlowProps) {
onNodeHover={setHoveredNodeId}
onNodeContextMenu={handleSigmaNodeContextMenu}
onStageClick={() => setSelectedNodeId(null)}
+ onLayoutSkipped={setLayoutNotice}
hiddenNodes={isEgoActive ? hiddenNodes : undefined}
visibleEdgeTypes={visibleEdgeTypes}
depthRingRadii={isConstellation ? constellationRingRadii : null}
@@ -1066,15 +1139,19 @@ export function GraphFlow(props: GraphFlowProps) {
) : !isLoading ? (
<div className="flex items-center justify-center h-full">
<EmptyState
- title="No graph data"
- description="Check that the backend is running and this repo has been indexed."
+ title={overlayEmptyState?.title ?? "No graph data"}
+ description={
+ overlayEmptyState?.description ??
+ "Check that the backend is running and this repo has been indexed."
+ }
/>
</div>
) : null}
- {/* Ego indicator or breadcrumb */}
+ {/* Ego indicator / breadcrumb / overlay counts (stacked top-left) */}
+ <div className="absolute top-3 left-3 z-10 flex flex-col items-start gap-1.5">
{isEgoActive && selectedNodeId ? (
- <div className="absolute top-3 left-3 z-10">
+ <div>
<div className="flex items-center gap-2 rounded-lg border border-[var(--color-accent-graph)]/30 bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2.5 py-1.5 shadow-lg shadow-black/20">
<span className="text-[10px] text-[var(--color-accent-graph)]">
Showing {egoVisibleCount} nodes within {egoDepth} hop{egoDepth === 1 ? "" : "s"} of{" "}
@@ -1089,7 +1166,7 @@ export function GraphFlow(props: GraphFlowProps) {
</div>
</div>
) : isModuleView && isDrilledDown ? (
- <div className="absolute top-3 left-3 z-10">
+ <div>
<div className="flex items-center gap-1 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2.5 py-1.5 shadow-lg shadow-black/20">
<button
onClick={() => handleBreadcrumbClick(-1)}
@@ -1122,6 +1199,49 @@ export function GraphFlow(props: GraphFlowProps) {
</div>
) : null}
+ {/* Overlay coverage: how many flagged files are actually in view. The
+ totals come from the backend when it provides them; without totals
+ we still report the in-view count so the overlay never reads as
+ silently doing nothing. */}
+ {sigmaGraph && sigmaGraph.order > 0 && overlayStats && (isDeadView || isHotView) && (
+ <div className="flex flex-col items-start gap-1">
+ {isDeadView && (
+ <OverlayCountChip
+ kind="dead"
+ inView={overlayStats.deadInView}
+ total={deadTotal}
+ />
+ )}
+ {isHotView && (
+ <OverlayCountChip
+ kind="hot"
+ inView={overlayStats.hotInView}
+ total={hotTotal}
+ />
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Layout-skipped notice: the hierarchical toggle must never look
+ active while silently doing nothing. */}
+ {layoutNotice && (
+ <div
+ role="status"
+ aria-live="polite"
+ className="absolute top-3 left-1/2 -translate-x-1/2 z-10 flex max-w-[min(28rem,calc(100vw-6rem))] items-center gap-2 rounded-lg border border-[var(--color-warning)]/40 bg-[var(--color-bg-elevated)]/95 backdrop-blur-sm px-3 py-1.5 shadow-sm"
+ >
+ <span className="text-[11px] text-[var(--color-text-primary)]">{layoutNotice}</span>
+ <button
+ onClick={() => setLayoutNotice(null)}
+ aria-label="Dismiss layout notice"
+ className="shrink-0 text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
+ >
+ <X className="w-3 h-3" />
+ </button>
+ </div>
+ )}
+
{/* Toolbar */}
<div className="absolute top-3 right-3 z-10">
<GraphToolbar
@@ -1188,9 +1308,23 @@ export function GraphFlow(props: GraphFlowProps) {
<span className="text-xs font-medium text-[var(--color-text-primary)]">
Execution Flows
</span>
- <span className="text-[10px] text-[var(--color-text-tertiary)]">
- {executionFlows.flows.length} entry points
- </span>
+ <div className="flex items-center gap-1.5">
+ <span className="text-[10px] text-[var(--color-text-tertiary)]">
+ {executionFlows.flows.length} entry points
+ </span>
+ {/* Same close affordance as the Path Finder panel above. */}
+ <button
+ onClick={() => {
+ setShowFlows(false);
+ setActiveFlowIdx(null);
+ }}
+ aria-label="Close"
+ title="Close"
+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
+ >
+ <X className="w-3 h-3" />
+ </button>
+ </div>
</div>
<div className="space-y-1 max-h-60 overflow-y-auto">
{executionFlows.flows.map((flow, idx) => (
@@ -1214,6 +1348,13 @@ export function GraphFlow(props: GraphFlowProps) {
</button>
))}
</div>
+ {activeFlowMissingCount > 0 && (
+ <p className="mt-2 text-[10px] leading-snug text-[var(--color-warning)]">
+ This flow includes {activeFlowMissingCount} node
+ {activeFlowMissingCount === 1 ? "" : "s"} not in the loaded
+ view — load more nodes to see the full trace.
+ </p>
+ )}
</div>
</div>
)}
@@ -1299,3 +1440,34 @@ export function GraphFlow(props: GraphFlowProps) {
</GraphProvider>
);
}
+
+/** Small status chip captioning a dead/hot view: "12 of 37 dead files in
+ * view" when the backend supplies repo-wide totals, or just the in-view
+ * count when it doesn't. */
+function OverlayCountChip({
+ kind,
+ inView,
+ total,
+}: {
+ kind: "dead" | "hot";
+ inView: number;
+ total: number | null;
+}) {
+ const noun = kind === "dead" ? "dead files" : "hot files";
+ let text: string;
+ if (total != null && inView < total) {
+ text = `${inView} of ${total} ${noun} in view — the rest are outside the loaded node set`;
+ } else if (total != null) {
+ text = `Showing all ${total} ${noun}`;
+ } else {
+ text = `${inView} ${noun} in view`;
+ }
+ return (
+ <div
+ role="status"
+ className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2.5 py-1.5 shadow-sm text-[10px] text-[var(--color-text-secondary)]"
+ >
+ {text}
+ </div>
+ );
+}
diff --git a/packages/ui/src/graph/graph-toolbar.tsx b/packages/ui/src/graph/graph-toolbar.tsx
index c6c058415..31b91b2a1 100644
--- a/packages/ui/src/graph/graph-toolbar.tsx
+++ b/packages/ui/src/graph/graph-toolbar.tsx
@@ -108,10 +108,14 @@ const SCOPES: { id: Scope; icon: typeof Boxes; label: string; hint: string }[] =
{ id: "full", icon: LayoutGrid, label: "Full", hint: "All files and symbols" },
];
-// Overlays = additive signal highlights that compose with any scope.
-const OVERLAYS: { id: Overlay; icon: typeof Skull; label: string }[] = [
- { id: "dead", icon: Skull, label: "Dead" },
- { id: "hot", icon: Flame, label: "Hot" },
+// Node filter = exclusive All / Hot / Dead segmented control. Hot and dead
+// files are near-disjoint sets, so the old pair of independent toggles read
+// as an AND filter and mostly produced an empty view when both were lit; a
+// single exclusive control matches how the affordance is read.
+const NODE_FILTERS: { id: Overlay | "all"; icon?: typeof Skull; label: string; hint: string }[] = [
+ { id: "all", label: "All", hint: "Show every node" },
+ { id: "hot", icon: Flame, label: "Hot", hint: "High-churn files" },
+ { id: "dead", icon: Skull, label: "Dead", hint: "Dead-code files" },
];
const COLOR_MODES: { id: ColorMode; icon: typeof Palette; label: string }[] = [
@@ -179,10 +183,16 @@ export const GraphToolbar = memo(function GraphToolbar({
onViewChange(scopeOverlaysToViewMode(next, activeOverlays));
};
- const toggleOverlay = (id: Overlay) => {
- const next = new Set(activeOverlays);
- if (next.has(id)) next.delete(id);
- else next.add(id);
+ // 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")
+ ? "dead"
+ : activeOverlays.has("hot")
+ ? "hot"
+ : "all";
+
+ const setNodeFilter = (id: Overlay | "all") => {
+ const next = new Set<Overlay>(id === "all" ? [] : [id]);
onViewChange(scopeOverlaysToViewMode(activeScope, next));
};
@@ -231,27 +241,32 @@ export const GraphToolbar = memo(function GraphToolbar({
</div>
)}
- {/* Overlays (additive signal chips) — not applicable in the constellation */}
+ {/* Node filter (exclusive All / Hot / Dead) — not applicable in the constellation */}
{!isConstellation && (
- <div className={`${clusterVisibility} gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-sm`}>
- {OVERLAYS.map((o) => {
- const Icon = o.icon;
- const isActive = activeOverlays.has(o.id);
+ <div
+ role="radiogroup"
+ aria-label="Node filter"
+ className={`${clusterVisibility} gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-sm`}
+ >
+ {NODE_FILTERS.map((f) => {
+ const Icon = f.icon;
+ const isActive = activeFilter === f.id;
return (
<button
- key={o.id}
- onClick={() => toggleOverlay(o.id)}
+ key={f.id}
+ onClick={() => setNodeFilter(f.id)}
className={`flex items-center gap-1 px-2 py-1 rounded-md text-[10px] font-medium transition-all ${
isActive
? "bg-[var(--color-accent-graph)]/15 text-[var(--color-accent-graph)]"
: "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-overlay)]"
}`}
- title={`Overlay: ${o.label}`}
- aria-label={`Overlay: ${o.label}`}
- aria-pressed={isActive}
+ title={f.hint}
+ aria-label={f.label}
+ role="radio"
+ aria-checked={isActive}
>
- <Icon className="w-3 h-3" />
- <span className="hidden lg:inline">{o.label}</span>
+ {Icon && <Icon className="w-3 h-3" />}
+ <span className={Icon ? "hidden lg:inline" : undefined}>{f.label}</span>
</button>
);
})}
diff --git a/packages/ui/src/graph/sigma/sigma-canvas.tsx b/packages/ui/src/graph/sigma/sigma-canvas.tsx
index d8443be18..6e238a484 100644
--- a/packages/ui/src/graph/sigma/sigma-canvas.tsx
+++ b/packages/ui/src/graph/sigma/sigma-canvas.tsx
@@ -58,6 +58,9 @@ export interface SigmaCanvasProps {
| ((nodeId: string, nodeType: string) => boolean | void)
| undefined;
onStageClick?: (() => void) | undefined;
+ /** Fired when the hierarchical (ELK) layout refuses to run (too many
+ * nodes) so the host can explain the dead-looking toggle to the user. */
+ onLayoutSkipped?: ((reason: string) => void) | undefined;
hiddenNodes?: Set<string> | undefined;
visibleEdgeTypes?: Set<string> | undefined;
/** Concentric depth-ring radii (graph coords) for the constellation underlay. */
@@ -110,6 +113,7 @@ export const SigmaCanvas = forwardRef<SigmaCanvasHandle, SigmaCanvasProps>(
moduleNodes: props.moduleNodes,
moduleEdges: props.moduleEdges,
viewMode: props.viewMode,
+ onSkipped: props.onLayoutSkipped,
});
// Keep callback refs up to date so Sigma event handlers always use latest props
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 de66ebbae..d8c9d78ac 100644
--- a/packages/ui/src/graph/sigma/use-elk-sigma-layout.ts
+++ b/packages/ui/src/graph/sigma/use-elk-sigma-layout.ts
@@ -16,6 +16,11 @@ import {
computeElkModulePositions,
} 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;
+
export interface UseElkSigmaLayoutOptions {
graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes> | null;
sigma: Sigma | null;
@@ -25,7 +30,7 @@ export interface UseElkSigmaLayoutOptions {
moduleNodes?: ModuleNodeResponse[] | undefined;
moduleEdges?: ModuleEdgeResponse[] | undefined;
viewMode: ViewMode;
- onSkipped?: (reason: string) => void;
+ onSkipped?: ((reason: string) => void) | undefined;
}
export interface UseElkSigmaLayoutReturn {
@@ -96,8 +101,10 @@ export function useElkSigmaLayout(
useEffect(() => {
if (enabled && graph && graph.order > 0) {
- if (graph.order > 500) {
- options.onSkipped?.("Graph too large for hierarchical layout (>500 nodes)");
+ if (graph.order > ELK_MAX_NODES) {
+ options.onSkipped?.(
+ `Hierarchical layout is limited to ${ELK_MAX_NODES} nodes — this view has ${graph.order.toLocaleString()}. Switch to the Modules scope or narrow the view to use it.`,
+ );
return;
}
compute();
diff --git a/tests/unit/server/test_graph.py b/tests/unit/server/test_graph.py
index 508b946da..46aeeb821 100644
--- a/tests/unit/server/test_graph.py
+++ b/tests/unit/server/test_graph.py
@@ -186,6 +186,12 @@ async def test_export_graph_carries_cross_link_signals(client: AsyncClient, app)
assert utils["is_hotspot"] is False
assert utils["has_decision"] is False
+ # Overlay counts: untruncated response has everything in view.
+ assert data["dead_total"] == 1
+ assert data["dead_in_view"] == 1
+ assert data["hot_total"] == 1
+ assert data["hot_in_view"] == 1
+
@pytest.mark.asyncio
async def test_export_graph_truncation(client: AsyncClient, app) -> None:
@@ -204,6 +210,160 @@ async def test_export_graph_truncation(client: AsyncClient, app) -> None:
assert data["links"] == []
+async def _populate_ranked_graph_with_flags(session_factory, repo_id: str) -> None:
+ """Three high-PageRank files + one dead file and one hotspot that both
+ rank BELOW the PageRank cutoff — the shape that used to silently drop
+ every overlay node."""
+ async with get_session(session_factory) as session:
+ await crud.batch_upsert_graph_nodes(
+ session,
+ repo_id,
+ [
+ {
+ "node_id": f"src/core_{i}.py",
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 1,
+ "pagerank": 0.9 - i * 0.1,
+ "community_id": 0,
+ }
+ for i in range(3)
+ ]
+ + [
+ {
+ "node_id": "src/orphan.py",
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 1,
+ "pagerank": 0.01,
+ "community_id": 0,
+ },
+ {
+ "node_id": "src/churny.py",
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 1,
+ "pagerank": 0.02,
+ "community_id": 0,
+ },
+ ],
+ )
+ session.add(
+ DeadCodeFinding(
+ repository_id=repo_id,
+ file_path="src/orphan.py",
+ kind="unreachable_file",
+ status="open",
+ confidence=0.9,
+ )
+ )
+ await crud.upsert_git_metadata(
+ session,
+ repository_id=repo_id,
+ file_path="src/churny.py",
+ is_hotspot=True,
+ churn_percentile=0.99,
+ commit_count_30d=40,
+ commit_count_90d=90,
+ )
+ await session.flush()
+
+
+async def test_export_graph_truncation_reserves_dead_and_hot_nodes(
+ client: AsyncClient, app
+) -> None:
+ """Dead/hot files must survive truncation even with rock-bottom PageRank."""
+ repo = await create_test_repo(client)
+ await _populate_ranked_graph_with_flags(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/graph/{repo['id']}", params={"limit": 3})
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["truncated"] is True
+ assert data["total_node_count"] == 5
+
+ kept = {n["node_id"] for n in data["nodes"]}
+ # Reserved slots: the dead file and the hotspot are kept; the remaining
+ # budget fills by PageRank (core_0 only).
+ assert kept == {"src/orphan.py", "src/churny.py", "src/core_0.py"}
+
+ assert data["dead_total"] == 1
+ assert data["dead_in_view"] == 1
+ assert data["hot_total"] == 1
+ assert data["hot_in_view"] == 1
+
+
+async def test_export_graph_truncation_reserves_flow_members(client: AsyncClient, app) -> None:
+ """Execution-flow trace members must survive truncation."""
+ repo = await create_test_repo(client)
+ async with get_session(app.state.session_factory) as session:
+ await crud.batch_upsert_graph_nodes(
+ session,
+ repo["id"],
+ [
+ {
+ "node_id": f"src/core_{i}.py",
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 1,
+ "pagerank": 0.9 - i * 0.1,
+ "community_id": 0,
+ }
+ for i in range(3)
+ ]
+ + [
+ {
+ "node_id": "src/api.py::handler",
+ "node_type": "symbol",
+ "language": "python",
+ "symbol_count": 0,
+ "pagerank": 0.03,
+ "community_id": 0,
+ "name": "handler",
+ "kind": "function",
+ "file_path": "src/api.py",
+ "community_meta_json": json.dumps({"entry_point_score": 0.9}),
+ },
+ {
+ "node_id": "src/service.py::run",
+ "node_type": "symbol",
+ "language": "python",
+ "symbol_count": 0,
+ "pagerank": 0.01,
+ "community_id": 0,
+ "name": "run",
+ "kind": "function",
+ "file_path": "src/service.py",
+ },
+ ],
+ )
+ await crud.batch_upsert_graph_edges(
+ session,
+ repo["id"],
+ [
+ {
+ "source_node_id": "src/api.py::handler",
+ "target_node_id": "src/service.py::run",
+ "edge_type": "calls",
+ "confidence": 0.95,
+ },
+ ],
+ )
+
+ resp = await client.get(f"/api/graph/{repo['id']}", params={"limit": 3})
+ assert resp.status_code == 200
+ data = resp.json()
+ 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
+ assert "src/core_0.py" in kept
+
+
@pytest.mark.asyncio
async def test_architecture_graph(client: AsyncClient, app) -> None:
repo = await create_test_repo(client)