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.

feat(web): add a collapsible code graph tree with per-file imports (#2343)

Nehal K7167f064c885
diff --git a/packages/api-client/src/types/graph.ts b/packages/api-client/src/types/graph.ts
index 5d17e5606..54d3b3575 100644
--- a/packages/api-client/src/types/graph.ts
+++ b/packages/api-client/src/types/graph.ts
@@ -28,6 +28,11 @@ export interface GraphEdgeResponse {
source: string;
target: string;
imported_names: string[];
+ // The server populates this on every edge row and it was simply never
+ // mirrored here, so a consumer wanting to tell an `imports` edge from a
+ // `co_changes` one had to cast. Optional and nullable, matching the
+ // server's own `GraphEdgeResponse`, so an older backend keeps parsing.
+ edge_type?: string | null;
}
/**
diff --git a/packages/types/__tests__/contracts.test.ts b/packages/types/__tests__/contracts.test.ts
index 3c5ed58ba..437833866 100644
--- a/packages/types/__tests__/contracts.test.ts
+++ b/packages/types/__tests__/contracts.test.ts
@@ -97,7 +97,12 @@ describe("GraphLink backwards compatibility", () => {
imported_names: [],
};
expectTypeOf(minimal).toEqualTypeOf<GraphLink>();
- expectTypeOf<GraphLink["edge_type"]>().toEqualTypeOf<string | undefined>();
+ // `| null` is not decoration: the server's `GraphEdgeResponse` declares
+ // `edge_type` as optional-but-nullable, and `types/src/generated/http.ts`
+ // (generated from that schema) says the same. A consumer reading it has to
+ // handle null, and while this type said `string | undefined` that one
+ // compiled only by accident.
+ expectTypeOf<GraphLink["edge_type"]>().toEqualTypeOf<string | null | undefined>();
expectTypeOf<GraphLink["confidence"]>().toEqualTypeOf<number | undefined>();
});
});
diff --git a/packages/types/src/graph.ts b/packages/types/src/graph.ts
index fd777bf50..a6393d013 100644
--- a/packages/types/src/graph.ts
+++ b/packages/types/src/graph.ts
@@ -44,8 +44,10 @@ export interface GraphLink {
source: string;
target: string;
imported_names: string[];
- /** Edge kind from v0.4.0 framework-aware extractors (e.g. "spring.bean", "rails.route"). */
- edge_type?: string;
+ /** Edge kind from v0.4.0 framework-aware extractors (e.g. "spring.bean", "rails.route").
+ * `null` is a real value on the wire — the server's `GraphEdgeResponse` declares
+ * it optional-but-nullable — so a consumer reading it has to handle both. */
+ edge_type?: string | null;
/** Confidence score for resolved symbol-level call edges (v0.4.x). */
confidence?: number;
}
diff --git a/packages/ui/COMPONENT_CONTRACTS.md b/packages/ui/COMPONENT_CONTRACTS.md
index e20ed809f..2bdd9ca2e 100644
--- a/packages/ui/COMPONENT_CONTRACTS.md
+++ b/packages/ui/COMPONENT_CONTRACTS.md
@@ -1422,6 +1422,35 @@ the `useDebounce` presentational hook for autocomplete.
---
+## `graph/code-graph-tree` — `CodeGraphTree`
+
+The dependency graph as a collapsible outline. Presentational: it takes
+one file-level `GraphExport` payload and owns nothing but which rows
+are open. Directories are derived from the node paths, `external:` and
+`framework:` nodes are skipped as rows (no page behind them) but kept as
+import targets, and each file row opens in place to list the types it
+imports and the file each one comes from, read straight off the payload's
+`imported_names`.
+
+Only file-to-file edges count: the module's
+`CODE_GRAPH_DEPENDENCY_EDGE_TYPES` mirrors the engine's
+`FILE_DEPENDENCY_EDGE_TYPES`, so a `co_changes` row (history, not code)
+never appears as an import.
+
+| Prop | Type | Required | Notes |
+|------|------|----------|-------|
+| `graph` | `GraphExport \| null \| undefined` | yes | `undefined` while the first fetch is in flight. |
+| `isLoading` | `boolean` | no | Renders the skeleton instead of the empty state. |
+| `fileHref` | `(path: string) => string` | no | File entity page href. Rows and targets render no link without it. |
+| `LinkComponent` | `ElementType` | no | Router link; defaults to `<a>`. |
+| `className` | `string` | no | |
+
+Also exported: `buildCodeGraphTree(nodes, links)` (the pure builder),
+`collectDirectoryIds`, `summarizeFileImports`, and the
+`CodeGraphTreeItem` / `CodeGraphFile` / `CodeGraphImport` types.
+
+---
+
## `graph/graph-flow` — `GraphFlow`
The full graph canvas. Presentational shell over Sigma that handles
diff --git a/packages/ui/__tests__/graph/code-graph-tree.test.tsx b/packages/ui/__tests__/graph/code-graph-tree.test.tsx
new file mode 100644
index 000000000..0137bb05d
--- /dev/null
+++ b/packages/ui/__tests__/graph/code-graph-tree.test.tsx
@@ -0,0 +1,207 @@
+import { describe, it, expect, vi } from "vitest";
+import { render, screen, fireEvent, within } from "@testing-library/react";
+import {
+ CodeGraphTree,
+ buildCodeGraphTree,
+ collectDirectoryIds,
+ summarizeFileImports,
+} from "../../src/graph/code-graph-tree.js";
+import type { GraphExport, GraphNode, GraphLink } from "@repowise-dev/types/graph";
+
+function node(id: string, overrides: Partial<GraphNode> = {}): GraphNode {
+ return {
+ node_id: id,
+ node_type: "file",
+ language: "typescript",
+ symbol_count: 1,
+ pagerank: 0,
+ betweenness: 0,
+ community_id: 0,
+ is_test: false,
+ is_entry_point: false,
+ has_doc: false,
+ ...overrides,
+ };
+}
+
+function link(
+ source: string,
+ target: string,
+ imported_names: string[],
+ edge_type: string | undefined = "imports",
+): GraphLink {
+ return edge_type === undefined
+ ? { source, target, imported_names }
+ : { source, target, imported_names, edge_type };
+}
+
+// A payload with a directory, a root-level file, an external target, and a
+// co_changes edge that must not be mistaken for an import.
+const payload: GraphExport = {
+ nodes: [
+ node("src/app.ts"),
+ node("src/util/format.ts"),
+ node("src/util/parse.ts", { is_test: true }),
+ node("README.md"),
+ node("external:react", { node_type: "external" }),
+ ],
+ links: [
+ link("src/app.ts", "src/util/format.ts", ["formatNumber", "truncatePath"]),
+ link("src/app.ts", "external:react", ["useState"]),
+ link("src/util/parse.ts", "src/util/format.ts", ["formatNumber"]),
+ link("src/app.ts", "README.md", [], "co_changes"),
+ ],
+};
+
+describe("buildCodeGraphTree", () => {
+ it("nests files under their directories and sorts directories first", () => {
+ const tree = buildCodeGraphTree(payload.nodes, payload.links);
+ expect(tree.map((t) => t.name)).toEqual(["src", "README.md"]);
+ const src = tree[0]!;
+ expect(src.fileCount).toBe(3);
+ // `src/app.ts` is a file; `src/util` is a directory, so the directory leads.
+ expect(src.children.map((c) => c.name)).toEqual(["util", "app.ts"]);
+ expect(src.children[0]!.children.map((c) => c.name)).toEqual(["format.ts", "parse.ts"]);
+ });
+
+ it("drops external nodes as rows but keeps them as import targets", () => {
+ const tree = buildCodeGraphTree(payload.nodes, payload.links);
+ const ids = collectDirectoryIds(tree);
+ expect(ids).toEqual(["src", "src/util"]);
+ const flat = JSON.stringify(tree);
+ expect(flat).not.toContain('"id":"external:react"');
+ expect(flat).toContain("external:react");
+ });
+
+ it("attaches each file's imported names, sorted, and ignores co_changes", () => {
+ const tree = buildCodeGraphTree(payload.nodes, payload.links);
+ const src = tree[0]!;
+ const app = src.children.find((c) => c.name === "app.ts")!;
+ expect(app.file?.imports.map((i) => i.target)).toEqual([
+ "external:react",
+ "src/util/format.ts",
+ ]);
+ const format = app.file!.imports.find((i) => i.target === "src/util/format.ts")!;
+ expect(format.names).toEqual(["formatNumber", "truncatePath"]);
+ // `co_changes` is history, not code: it must not appear as a dependency,
+ // and the file's own list is empty, not a one-row list of README.md.
+ expect(app.file?.imports.some((i) => i.target === "README.md")).toBe(false);
+ });
+
+ it("summarizes counts over distinct names across edges", () => {
+ const tree = buildCodeGraphTree(payload.nodes, payload.links);
+ const src = tree[0]!;
+ const app = src.children.find((c) => c.name === "app.ts")!;
+ expect(summarizeFileImports(app.file!.imports)).toEqual({ fileCount: 2, nameCount: 3 });
+ });
+
+ it("merges parallel edges between the same pair instead of listing the target twice", () => {
+ const graph: GraphExport = {
+ nodes: [node("a.ts"), node("b.ts")],
+ links: [link("a.ts", "b.ts", ["one"]), link("a.ts", "b.ts", ["two"])],
+ };
+ const tree = buildCodeGraphTree(graph.nodes, graph.links);
+ const a = tree.find((t) => t.name === "a.ts")!;
+ expect(a.file?.imports).toHaveLength(1);
+ expect(a.file?.imports[0]!.names).toEqual(["one", "two"]);
+ });
+
+ it("admits an edge with no edge_type and skips an edge whose endpoint is not a node", () => {
+ const graph: GraphExport = {
+ nodes: [node("a.ts"), node("b.ts")],
+ links: [
+ { source: "a.ts", target: "b.ts", imported_names: ["x"] },
+ link("a.ts", "gone.ts", ["y"]),
+ ],
+ };
+ const tree = buildCodeGraphTree(graph.nodes, graph.links);
+ const a = tree.find((t) => t.name === "a.ts")!;
+ expect(a.file?.imports.map((i) => i.target)).toEqual(["b.ts"]);
+ expect(a.file?.imports[0]!.edge_type).toBeNull();
+ });
+});
+
+describe("CodeGraphTree", () => {
+ it("keeps every directory shut until it is opened", () => {
+ render(<CodeGraphTree graph={payload} />);
+ expect(screen.queryByText("format.ts")).toBeNull();
+ fireEvent.click(screen.getByText("src"));
+ expect(screen.queryByText("util")).not.toBeNull();
+ // One rung at a time: opening `src` does not open `src/util`.
+ expect(screen.queryByText("format.ts")).toBeNull();
+ });
+
+ it("shows a file's imported types in place when the file row is opened", () => {
+ render(<CodeGraphTree graph={payload} />);
+ fireEvent.click(screen.getByText("src"));
+ fireEvent.click(screen.getByText("app.ts"));
+ expect(screen.getByText("src/util/format.ts")).toBeTruthy();
+ expect(screen.getByText("formatNumber, truncatePath")).toBeTruthy();
+ // The counts sentence is on the row, before it is opened or not.
+ expect(screen.getByText("useState")).toBeTruthy();
+ });
+
+ it("collapses a row that is already open", () => {
+ render(<CodeGraphTree graph={payload} />);
+ fireEvent.click(screen.getByText("src"));
+ expect(screen.queryByText("app.ts")).not.toBeNull();
+ fireEvent.click(screen.getByText("src"));
+ expect(screen.queryByText("app.ts")).toBeNull();
+ });
+
+ it("keeps imported names off the screen while a file row is shut", () => {
+ render(<CodeGraphTree graph={payload} />);
+ fireEvent.click(screen.getByText("src"));
+ expect(screen.queryByText("formatNumber, truncatePath")).toBeNull();
+ fireEvent.click(screen.getByText("app.ts"));
+ expect(screen.queryByText("formatNumber, truncatePath")).not.toBeNull();
+ fireEvent.click(screen.getByText("app.ts"));
+ expect(screen.queryByText("formatNumber, truncatePath")).toBeNull();
+ });
+
+ it("links a file row and its import targets through fileHref, not external ones", () => {
+ const fileHref = (path: string) => `/repos/1/files/${path}`;
+ render(<CodeGraphTree graph={payload} fileHref={fileHref} />);
+ fireEvent.click(screen.getByText("src"));
+ const row = screen.getByText("app.ts").closest("div")!;
+ const fileLink = within(row).getByLabelText("Open src/app.ts");
+ expect(fileLink.getAttribute("href")).toBe("/repos/1/files/src/app.ts");
+
+ fireEvent.click(screen.getByText("app.ts"));
+ // A real target is linkable; `external:react` has no page behind it.
+ const targetLink = screen.getByLabelText("Open src/util/format.ts");
+ expect(targetLink.getAttribute("href")).toBe("/repos/1/files/src/util/format.ts");
+ expect(screen.queryByLabelText("Open external:react")).toBeNull();
+ });
+
+ it("expands and collapses every directory from the two controls", () => {
+ render(<CodeGraphTree graph={payload} />);
+ fireEvent.click(screen.getByText("Expand all"));
+ expect(screen.queryByText("format.ts")).not.toBeNull();
+ fireEvent.click(screen.getByText("Collapse all"));
+ expect(screen.queryByText("format.ts")).toBeNull();
+ });
+
+ it("says it is loading rather than reporting an empty graph", () => {
+ render(<CodeGraphTree graph={undefined} isLoading />);
+ expect(screen.getByLabelText("Loading the code graph tree")).toBeTruthy();
+ expect(screen.queryByText("No files to outline")).toBeNull();
+ });
+
+ it("reports an empty payload as an empty state, not as a blank panel", () => {
+ render(<CodeGraphTree graph={{ nodes: [], links: [] }} />);
+ expect(screen.getByText("No files to outline")).toBeTruthy();
+ });
+
+ it("says when an edge carries no names rather than printing a bare path", () => {
+ const graph: GraphExport = {
+ nodes: [node("a.ts"), node("b.ts")],
+ links: [link("a.ts", "b.ts", [])],
+ };
+ render(<CodeGraphTree graph={graph} />);
+ fireEvent.click(screen.getByText("a.ts"));
+ expect(
+ screen.getByText(/The edge records no names, so we know these two files are joined/),
+ ).toBeTruthy();
+ });
+});
diff --git a/packages/ui/src/graph/code-graph-tree.tsx b/packages/ui/src/graph/code-graph-tree.tsx
new file mode 100644
index 000000000..593763382
--- /dev/null
+++ b/packages/ui/src/graph/code-graph-tree.tsx
@@ -0,0 +1,614 @@
+"use client";
+
+/**
+ * CodeGraphTree — the dependency graph as a collapsible outline.
+ *
+ * The canvas draws one circle per file and one line per import, and at repo
+ * scale neither the line nor its label can be read: `imported_names` reaches
+ * the client on every edge already, and nothing renders it. This is the same
+ * payload in the other shape a reader knows how to walk. A directory tree, with
+ * every file openable in place to show the names it imports and which file each
+ * name comes from.
+ *
+ * Nothing here is fetched, curated or hardcoded: the outline, the counts and
+ * the type lists are all derived from the payload the canvas is drawing, so the
+ * two surfaces cannot disagree, and a revalidation or a stepped-up node cap
+ * updates this one too.
+ *
+ * Presentational. The component owns only which rows are open; data and links
+ * arrive as props, and `packages/web` hosts the wrapper that fetches them.
+ */
+
+import { useMemo, useState, type ElementType } from "react";
+import {
+ ChevronDown,
+ ChevronRight,
+ FileCode,
+ Folder,
+ FolderOpen,
+ ListTree,
+} from "lucide-react";
+import { cn } from "../lib/cn";
+import { formatNumber, truncatePath } from "../lib/format";
+import { EmptyState } from "../shared/empty-state";
+import { Skeleton } from "../ui/skeleton";
+import { NodeBadges } from "./node-badges";
+import { isExternal } from "@repowise-dev/types";
+import type { GraphExport, GraphLink, GraphNode } from "@repowise-dev/types/graph";
+
+/**
+ * The file -> file edge types that mean "this file references that one", the
+ * TypeScript mirror of the engine's `FILE_DEPENDENCY_EDGE_TYPES`
+ * (`packages/core/src/repowise/core/ingestion/models.py`).
+ *
+ * `co_changes` is the one this deliberately drops, and it is the reason the
+ * list exists at all: it joins files that were committed together, which is
+ * history rather than code, and a tree whose per-file list mixed the two would
+ * report a changelog as an import.
+ */
+export const CODE_GRAPH_DEPENDENCY_EDGE_TYPES: ReadonlySet<string> = new Set([
+ "imports",
+ "type_use",
+ "framework",
+ "dynamic_uses",
+ "dynamic_imports",
+ "dynamic_url_route",
+ "reads",
+]);
+
+/**
+ * Whether an edge belongs in a file's import list.
+ *
+ * An absent `edge_type` is admitted rather than dropped: the field is optional
+ * on the wire for back-compat, and an index predating it carries real import
+ * edges with nothing to classify them. Rendering them unnamed is honest;
+ * hiding them is not.
+ */
+function isDependencyEdge(edgeType: string | null | undefined): boolean {
+ return edgeType === undefined || edgeType === null || CODE_GRAPH_DEPENDENCY_EDGE_TYPES.has(edgeType);
+}
+
+/** Short labels for the edge kinds that are not a plain import. */
+const EDGE_KIND_LABELS: Record<string, string> = {
+ type_use: "type reference",
+ framework: "framework wiring",
+ dynamic_uses: "dynamic reference",
+ dynamic_imports: "dynamic import",
+ dynamic_url_route: "URL route",
+ reads: "member read",
+};
+
+/** One file this file takes names from, with the names themselves. */
+export interface CodeGraphImport {
+ /** The file the names come from; may be an `external:` / `framework:` node. */
+ target: string;
+ edge_type: string | null;
+ /** Sorted and deduped. Empty when the edge carries no names. */
+ names: string[];
+}
+
+/** A file row: the node plus what it imports. */
+export interface CodeGraphFile {
+ node: GraphNode;
+ imports: CodeGraphImport[];
+}
+
+/** One row of the outline: a directory, or a file. */
+export interface CodeGraphTreeItem {
+ /** A directory path, or the file's `node_id`. */
+ id: string;
+ /** Basename, for display. Directories keep their own segment. */
+ name: string;
+ isDir: boolean;
+ children: CodeGraphTreeItem[];
+ /** Files at or below this row (1 for a file row). */
+ fileCount: number;
+ /** Present on file rows only. */
+ file?: CodeGraphFile;
+}
+
+/**
+ * Fold the payload's links into one import list per source file.
+ *
+ * Parallel edges are merged rather than listed twice: the engine already
+ * aggregates `imported_names` onto a single edge per pair, but a payload from
+ * another producer may not, and two rows for one target reads as two separate
+ * dependencies. Both endpoints must be nodes in the payload, so the list never
+ * names a file the tree cannot show. External targets are kept, since
+ * `external:react` is exactly what a lot of files import.
+ */
+function collectImports(
+ nodes: readonly GraphNode[],
+ links: readonly GraphLink[],
+): Map<string, CodeGraphImport[]> {
+ const nodeIds = new Set(nodes.map((n) => n.node_id));
+ const bySource = new Map<string, Map<string, { kind: string | null; names: Set<string> }>>();
+ for (const link of links) {
+ if (link.source === link.target) continue;
+ if (!nodeIds.has(link.source) || !nodeIds.has(link.target)) continue;
+ if (!isDependencyEdge(link.edge_type)) continue;
+ let targets = bySource.get(link.source);
+ if (!targets) {
+ targets = new Map();
+ bySource.set(link.source, targets);
+ }
+ // An edge type is stamped when the edge is created and never rewritten
+ // (a stronger `imports` edge keeps its kind when a `type_use` pass merges
+ // into it), so first-wins for the kind is the engine's own answer.
+ const existing = targets.get(link.target);
+ if (existing) {
+ for (const name of link.imported_names ?? []) existing.names.add(name);
+ } else {
+ targets.set(link.target, {
+ kind: link.edge_type ?? null,
+ names: new Set(link.imported_names ?? []),
+ });
+ }
+ }
+
+ const imports = new Map<string, CodeGraphImport[]>();
+ for (const [source, targets] of bySource) {
+ imports.set(
+ source,
+ [...targets.entries()]
+ .map(([target, { kind, names }]) => ({
+ target,
+ edge_type: kind,
+ names: [...names].sort(),
+ }))
+ .sort((a, b) => a.target.localeCompare(b.target)),
+ );
+ }
+ return imports;
+}
+
+/**
+ * Build the outline from a file-level graph payload.
+ *
+ * Directories are derived from the paths, not from the payload: there is no
+ * directory node to read, and a tree that invented a hierarchy the graph does
+ * not carry would be describing something other than the files that are there.
+ *
+ * `external:` / `framework:` nodes share the node table with real files and are
+ * not files: they have no path, so they would land at the root as a row nobody
+ * can open. They are skipped as rows and kept as import targets.
+ */
+export function buildCodeGraphTree(
+ nodes: readonly GraphNode[],
+ links: readonly GraphLink[],
+): CodeGraphTreeItem[] {
+ const imports = collectImports(nodes, links);
+ const dirs = new Map<string, CodeGraphTreeItem>();
+ const root: CodeGraphTreeItem[] = [];
+
+ function ensureDir(dirPath: string): CodeGraphTreeItem {
+ const existing = dirs.get(dirPath);
+ if (existing) return existing;
+ const parts = dirPath.split("/");
+ const node: CodeGraphTreeItem = {
+ id: dirPath,
+ name: parts[parts.length - 1] ?? dirPath,
+ isDir: true,
+ children: [],
+ fileCount: 0,
+ };
+ dirs.set(dirPath, node);
+ if (parts.length > 1) {
+ const parent = ensureDir(parts.slice(0, -1).join("/"));
+ if (!parent.children.some((child) => child.id === dirPath)) parent.children.push(node);
+ } else {
+ root.push(node);
+ }
+ return node;
+ }
+
+ for (const node of nodes) {
+ if (isExternal(node.node_id)) continue;
+ const parts = node.node_id.split("/");
+ const file: CodeGraphTreeItem = {
+ id: node.node_id,
+ name: parts[parts.length - 1] ?? node.node_id,
+ isDir: false,
+ children: [],
+ fileCount: 1,
+ file: { node, imports: imports.get(node.node_id) ?? [] },
+ };
+ if (parts.length > 1) {
+ ensureDir(parts.slice(0, -1).join("/")).children.push(file);
+ } else {
+ root.push(file);
+ }
+ }
+
+ /** Directories first, then files, each alphabetically, at every level. */
+ function sortAndCount(items: CodeGraphTreeItem[]): number {
+ items.sort((a, b) => {
+ if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
+ return a.name.localeCompare(b.name) || a.id.localeCompare(b.id);
+ });
+ let count = 0;
+ for (const item of items) {
+ item.fileCount = item.isDir ? sortAndCount(item.children) : 1;
+ count += item.fileCount;
+ }
+ return count;
+ }
+ sortAndCount(root);
+ return root;
+}
+
+/** What a file row says about its imports, as figures rather than prose. */
+export interface FileImportSummary {
+ /** Distinct files this file takes names from. */
+ fileCount: number;
+ /** Distinct names across those edges. */
+ nameCount: number;
+}
+
+export function summarizeFileImports(imports: readonly CodeGraphImport[]): FileImportSummary {
+ const names = new Set<string>();
+ for (const entry of imports) for (const name of entry.names) names.add(name);
+ return { fileCount: imports.length, nameCount: names.size };
+}
+
+/** The one-line count for a file row. Says which half is empty rather than
+ * printing a figure that describes nothing. */
+function importSummaryLabel(summary: FileImportSummary): string {
+ const { fileCount, nameCount } = summary;
+ if (fileCount === 0) return "no dependencies";
+ const files = `${fileCount} ${fileCount === 1 ? "file" : "files"}`;
+ if (nameCount === 0) return `${files}, no names recorded`;
+ return `${nameCount} ${nameCount === 1 ? "type" : "types"} from ${files}`;
+}
+
+/** Every directory id in the outline, for expand/collapse-all. */
+export function collectDirectoryIds(items: readonly CodeGraphTreeItem[]): string[] {
+ const ids: string[] = [];
+ const walk = (list: readonly CodeGraphTreeItem[]) => {
+ for (const item of list) {
+ if (!item.isDir) continue;
+ ids.push(item.id);
+ walk(item.children);
+ }
+ };
+ walk(items);
+ return ids;
+}
+
+// ---------------------------------------------------------------------------
+// Rows
+// ---------------------------------------------------------------------------
+
+interface RowChrome {
+ fileHref?: ((path: string) => string) | undefined;
+ LinkComponent: ElementType;
+}
+
+function ImportList({ entry, chrome }: { entry: CodeGraphFile; chrome: RowChrome }) {
+ if (entry.imports.length === 0) {
+ return (
+ <p className="py-1 pl-2 text-xs text-[var(--color-text-tertiary)]">
+ No dependency edges recorded for this file. Files land in the graph once their
+ imports are parsed, so an excluded path or an unsupported language leaves this empty.
+ </p>
+ );
+ }
+ const A = chrome.LinkComponent;
+ return (
+ <ul className="mb-1 space-y-1.5 border-l border-[var(--color-border-default)] pl-4">
+ {entry.imports.map((imp) => {
+ const kindLabel = imp.edge_type ? EDGE_KIND_LABELS[imp.edge_type] : undefined;
+ // An external node has no page behind it, so it gets no link: the same
+ // rule the file page's graph tab follows.
+ const href = isExternal(imp.target) ? undefined : chrome.fileHref?.(imp.target);
+ return (
+ <li key={imp.target}>
+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
+ <span
+ className="font-mono text-[11px] text-[var(--color-text-primary)]"
+ title={imp.target}
+ >
+ {truncatePath(imp.target, 64)}
+ </span>
+ {kindLabel && (
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {kindLabel}
+ </span>
+ )}
+ {href && (
+ <A
+ href={href}
+ className="text-[10px] text-[var(--color-accent-primary)] hover:underline"
+ aria-label={`Open ${imp.target}`}
+ >
+ open <span aria-hidden>→</span>
+ </A>
+ )}
+ </div>
+ {imp.names.length > 0 ? (
+ <p className="font-mono text-[11px] leading-relaxed text-[var(--color-text-secondary)] [overflow-wrap:anywhere]">
+ {imp.names.join(", ")}
+ </p>
+ ) : (
+ <p className="text-[11px] text-[var(--color-text-tertiary)]">
+ The edge records no names, so we know these two files are joined and not what
+ travelled along it.
+ </p>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
+
+function FileRow({
+ item,
+ depth,
+ expanded,
+ toggle,
+ chrome,
+}: {
+ item: CodeGraphTreeItem;
+ depth: number;
+ expanded: ReadonlySet<string>;
+ toggle: (id: string) => void;
+ chrome: RowChrome;
+}) {
+ const file = item.file;
+ if (!file) return null;
+ const isOpen = expanded.has(item.id);
+ const summary = summarizeFileImports(file.imports);
+ const href = chrome.fileHref?.(item.id);
+ const A = chrome.LinkComponent;
+ const listId = `code-graph-tree-imports-${item.id}`;
+
+ return (
+ <li>
+ <div
+ className="flex items-center gap-2 rounded-md pr-2 hover:bg-[var(--color-bg-elevated)]"
+ style={{ paddingLeft: `${depth * 16 + 8}px` }}
+ >
+ <button
+ type="button"
+ onClick={() => toggle(item.id)}
+ aria-expanded={isOpen}
+ aria-controls={listId}
+ className="flex min-w-0 flex-1 items-center gap-1.5 rounded-md py-1.5 text-left text-xs text-[var(--color-text-secondary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {isOpen ? (
+ <ChevronDown className="h-3 w-3 shrink-0 opacity-50" />
+ ) : (
+ <ChevronRight className="h-3 w-3 shrink-0 opacity-50" />
+ )}
+ <FileCode className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)]" />
+ <span
+ className="min-w-0 truncate font-mono text-xs text-[var(--color-text-primary)]"
+ title={item.id}
+ >
+ {item.name}
+ </span>
+ <NodeBadges
+ signals={{ isTest: file.node.is_test, isEntryPoint: file.node.is_entry_point }}
+ only={["isTest", "isEntryPoint"]}
+ />
+ </button>
+ <span className="shrink-0 font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)]">
+ {importSummaryLabel(summary)}
+ </span>
+ {href && (
+ <A
+ href={href}
+ className="shrink-0 text-[10px] text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-primary)] hover:underline"
+ aria-label={`Open ${item.id}`}
+ >
+ file <span aria-hidden>→</span>
+ </A>
+ )}
+ </div>
+ {isOpen && (
+ <div id={listId} style={{ paddingLeft: `${depth * 16 + 24}px` }} className="pb-1">
+ <ImportList entry={file} chrome={chrome} />
+ </div>
+ )}
+ </li>
+ );
+}
+
+function DirRow({
+ item,
+ depth,
+ expanded,
+ toggle,
+ chrome,
+}: {
+ item: CodeGraphTreeItem;
+ depth: number;
+ expanded: ReadonlySet<string>;
+ toggle: (id: string) => void;
+ chrome: RowChrome;
+}) {
+ const isOpen = expanded.has(item.id);
+ return (
+ <li>
+ <button
+ type="button"
+ onClick={() => toggle(item.id)}
+ aria-expanded={isOpen}
+ className={cn(
+ "flex w-full items-center gap-1.5 rounded-md py-1.5 pr-2 text-left text-xs transition-colors hover:bg-[var(--color-bg-elevated)]",
+ depth === 0
+ ? "font-semibold text-[var(--color-text-primary)]"
+ : "text-[var(--color-text-secondary)]",
+ )}
+ style={{ paddingLeft: `${depth * 16 + 8}px` }}
+ >
+ {isOpen ? (
+ <ChevronDown className="h-3 w-3 shrink-0 opacity-50" />
+ ) : (
+ <ChevronRight className="h-3 w-3 shrink-0 opacity-50" />
+ )}
+ {isOpen ? (
+ <FolderOpen className="h-3.5 w-3.5 shrink-0 text-[var(--color-accent-primary)] opacity-70" />
+ ) : (
+ <Folder className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)]" />
+ )}
+ <span className="min-w-0 flex-1 truncate font-mono">{item.name}</span>
+ <span className="shrink-0 font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)]">
+ {formatNumber(item.fileCount)} {item.fileCount === 1 ? "file" : "files"}
+ </span>
+ </button>
+ {isOpen && (
+ <ul>
+ {item.children.map((child) => (
+ <TreeRow
+ key={child.id}
+ item={child}
+ depth={depth + 1}
+ expanded={expanded}
+ toggle={toggle}
+ chrome={chrome}
+ />
+ ))}
+ </ul>
+ )}
+ </li>
+ );
+}
+
+function TreeRow({
+ item,
+ depth,
+ expanded,
+ toggle,
+ chrome,
+}: {
+ item: CodeGraphTreeItem;
+ depth: number;
+ expanded: ReadonlySet<string>;
+ toggle: (id: string) => void;
+ chrome: RowChrome;
+}) {
+ return item.isDir ? (
+ <DirRow item={item} depth={depth} expanded={expanded} toggle={toggle} chrome={chrome} />
+ ) : (
+ <FileRow item={item} depth={depth} expanded={expanded} toggle={toggle} chrome={chrome} />
+ );
+}
+
+// ---------------------------------------------------------------------------
+// The tree
+// ---------------------------------------------------------------------------
+
+export interface CodeGraphTreeProps {
+ /** The file-level graph payload. `undefined` while it is still arriving. */
+ graph: GraphExport | null | undefined;
+ /** Renders the skeleton instead of the empty state while the first fetch runs. */
+ isLoading?: boolean | undefined;
+ /** Builds a file entity page href. Rows render no link when it is omitted. */
+ fileHref?: ((path: string) => string) | undefined;
+ /** Router link; defaults to `<a>` so the package stays framework-neutral. */
+ LinkComponent?: ElementType | undefined;
+ className?: string | undefined;
+}
+
+export function CodeGraphTree({
+ graph,
+ isLoading = false,
+ fileHref,
+ LinkComponent = "a",
+ className,
+}: CodeGraphTreeProps) {
+ const tree = useMemo(
+ () => (graph ? buildCodeGraphTree(graph.nodes, graph.links) : []),
+ [graph],
+ );
+ // Everything starts shut. The top rung on a real repo is dozens of
+ // directories and thousands of files, and a first screen that is already
+ // open to depth three is a wall rather than an outline. `Expand all` is one
+ // click away for the reader who wants the whole shape.
+ const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set());
+ const chrome: RowChrome = { fileHref, LinkComponent };
+
+ const toggle = (id: string) => {
+ setExpanded((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
+ };
+
+ const directoryIds = useMemo(() => collectDirectoryIds(tree), [tree]);
+ const totalFiles = useMemo(
+ () => tree.reduce((sum, item) => sum + item.fileCount, 0),
+ [tree],
+ );
+
+ if (isLoading && !graph) {
+ return (
+ <div className={cn("space-y-2", className)} aria-label="Loading the code graph tree">
+ <Skeleton className="h-4 w-64" />
+ {Array.from({ length: 10 }).map((_, index) => (
+ <Skeleton key={index} className="h-7 w-full" />
+ ))}
+ </div>
+ );
+ }
+
+ if (tree.length === 0) {
+ return (
+ <EmptyState
+ titleAs="h2"
+ icon={<ListTree className="h-8 w-8" />}
+ title="No files to outline"
+ description="Files land in the graph once their imports are parsed. An empty index, or one whose files are all third-party nodes, leaves this with nothing to draw."
+ {...(className ? { className } : {})}
+ />
+ );
+ }
+
+ return (
+ <div className={cn("flex flex-col gap-2", className)}>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-[var(--color-text-secondary)]">
+ <p className="min-w-0 flex-1">
+ <span className="font-medium tabular-nums text-[var(--color-text-primary)]">
+ {formatNumber(totalFiles)}
+ </span>{" "}
+ {totalFiles === 1 ? "file" : "files"} in{" "}
+ <span className="font-medium tabular-nums text-[var(--color-text-primary)]">
+ {formatNumber(directoryIds.length)}
+ </span>{" "}
+ {directoryIds.length === 1 ? "directory" : "directories"}. Open a file to see the types
+ it imports and where each one comes from.
+ </p>
+ <button
+ type="button"
+ onClick={() => setExpanded(new Set(directoryIds))}
+ className="shrink-0 font-medium text-[var(--color-accent-primary)] hover:underline"
+ >
+ Expand all
+ </button>
+ <button
+ type="button"
+ onClick={() => setExpanded(new Set())}
+ className="shrink-0 font-medium text-[var(--color-accent-primary)] hover:underline"
+ >
+ Collapse all
+ </button>
+ </div>
+ <ul className="space-y-0.5">
+ {tree.map((item) => (
+ <TreeRow
+ key={item.id}
+ item={item}
+ depth={0}
+ expanded={expanded}
+ toggle={toggle}
+ chrome={chrome}
+ />
+ ))}
+ </ul>
+ </div>
+ );
+}
diff --git a/packages/ui/src/graph/graph-scope-controls.tsx b/packages/ui/src/graph/graph-scope-controls.tsx
index 6b73ca267..ef4af35b1 100644
--- a/packages/ui/src/graph/graph-scope-controls.tsx
+++ b/packages/ui/src/graph/graph-scope-controls.tsx
@@ -16,7 +16,7 @@ import type { CommunitySummaryItem } from "@repowise-dev/types/graph";
* 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";
+export type GraphScope = "communities" | "files" | "tree";
const SCOPES: { id: GraphScope; label: string; hint: string }[] = [
{
@@ -31,6 +31,14 @@ const SCOPES: { id: GraphScope; label: string; hint: string }[] = [
label: "Files",
hint: "Individual files and how they depend on each other",
},
+ {
+ id: "tree",
+ // The same file graph, read as an outline rather than as a canvas. It is
+ // the same axis as the two above — how the file graph is presented — so it
+ // lives in the same control, not in a tab of its own.
+ label: "Tree",
+ hint: "The same files as an outline, with what each one imports",
+ },
];
export function GraphScopeSwitcher({
diff --git a/packages/ui/src/graph/index.ts b/packages/ui/src/graph/index.ts
index dce92fb22..794417afb 100644
--- a/packages/ui/src/graph/index.ts
+++ b/packages/ui/src/graph/index.ts
@@ -17,6 +17,7 @@ export * from "./edge-provenance";
export * from "./context";
export * from "./elk-layout";
export * from "./graph-scope-controls";
+export * from "./code-graph-tree";
export * from "./graph-population-control";
export * from "./graph-unclustered-panel";
export * from "./use-module-filter";
diff --git a/packages/web/src/app/repos/[id]/architecture/architecture-view-routing.test.tsx b/packages/web/src/app/repos/[id]/architecture/architecture-view-routing.test.tsx
new file mode 100644
index 000000000..43c0d3f97
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/architecture/architecture-view-routing.test.tsx
@@ -0,0 +1,134 @@
+// @vitest-environment jsdom
+
+/**
+ * The Architecture page's routing of the tree scope.
+ *
+ * `?view=tree` has to land on the outline and nothing else: not on the canvas,
+ * not on a table tab. The page resolves `?view=` through an alias table and a
+ * legacy `?viewMode=` translation before it picks a panel, so a regression that
+ * adds the view to `CANONICAL` but forgets the panel (or the reverse) renders
+ * the wrong surface under a correct-looking URL. That is what this pins.
+ *
+ * The two surfaces and the tab row are stubbed: this is about which one the
+ * page mounts, not about what any of them renders.
+ */
+
+import * as React from "react";
+import { Suspense } from "react";
+import { act, cleanup, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ queryValues: {} as Record<string, unknown>,
+ setView: vi.fn(),
+}));
+
+vi.mock("nuqs", () => {
+ const parser = (defaultValue: unknown = null) => ({
+ defaultValue,
+ withDefault(value: unknown) {
+ return parser(value);
+ },
+ withOptions() {
+ return parser();
+ },
+ });
+ return {
+ parseAsString: parser(),
+ parseAsStringLiteral: () => parser(),
+ parseAsInteger: parser(),
+ useQueryState: (name: string, value: { defaultValue?: unknown }) => [
+ name in mocks.queryValues ? mocks.queryValues[name] : value?.defaultValue ?? null,
+ name === "view" ? mocks.setView : vi.fn(),
+ ],
+ };
+});
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ replace: vi.fn() }),
+}));
+
+vi.mock("@/components/architecture/graph-view", () => ({
+ GraphView: (props: { scope: string }) => (
+ <div data-testid="graph-view">canvas:{props.scope}</div>
+ ),
+}));
+
+vi.mock("@/components/architecture/code-graph-tree-view", () => ({
+ CodeGraphTreeView: (props: { scope: string }) => (
+ <div data-testid="tree-view">tree:{props.scope}</div>
+ ),
+}));
+
+vi.mock("@/components/architecture/dependencies-view", () => ({
+ DependenciesView: () => <div data-testid="dependencies-view" />,
+}));
+
+vi.mock("@/components/coupling/coupling-tab", () => ({
+ CouplingTab: () => <div data-testid="coupling-tab" />,
+}));
+
+vi.mock("@/components/symbols/symbol-table-wrapper", () => ({
+ SymbolTableWrapper: () => <div data-testid="symbol-table" />,
+}));
+
+import ArchitecturePage from "./page";
+
+afterEach(cleanup);
+
+// jsdom does not implement scrollIntoView, and the shared ViewTabs calls it on
+// the active tab to keep it in view. A stub here rather than in the component:
+// the component is right, the environment is the one missing the method.
+beforeEach(() => {
+ Element.prototype.scrollIntoView = vi.fn();
+});
+
+describe("Architecture page view routing", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.queryValues = {};
+ });
+
+ // `use(params)` suspends the first render while the route promise resolves,
+ // so every mount is wrapped in a boundary and awaited before assertions.
+ const mount = async (view?: string) => {
+ mocks.queryValues = view === undefined ? {} : { view };
+ await act(async () => {
+ render(
+ <Suspense fallback={<div data-testid="suspended" />}>
+ <ArchitecturePage params={Promise.resolve({ id: "r1" })} />
+ </Suspense>,
+ );
+ });
+ };
+
+ it("mounts the tree for ?view=tree, and not the canvas", async () => {
+ await mount("tree");
+ expect(screen.getByTestId("tree-view").textContent).toBe("tree:tree");
+ expect(screen.queryByTestId("graph-view")).toBeNull();
+ });
+
+ it("still mounts the canvas for the two scopes it draws", async () => {
+ await mount("files");
+ expect(screen.getByTestId("graph-view").textContent).toBe("canvas:files");
+ cleanup();
+ await mount("communities");
+ expect(screen.getByTestId("graph-view").textContent).toBe("canvas:communities");
+ expect(screen.queryByTestId("tree-view")).toBeNull();
+ });
+
+ it("keeps the tree off every non-Map tab", async () => {
+ for (const view of ["coupling", "packages", "symbols"]) {
+ cleanup();
+ await mount(view);
+ expect(screen.queryByTestId("tree-view")).toBeNull();
+ expect(screen.queryByTestId("graph-view")).toBeNull();
+ }
+ });
+
+ it("lands an absent ?view= on the canvas, not on the tree", async () => {
+ await mount();
+ expect(screen.getByTestId("graph-view").textContent).toBe("canvas:communities");
+ expect(screen.queryByTestId("tree-view")).toBeNull();
+ });
+});
diff --git a/packages/web/src/app/repos/[id]/architecture/page.tsx b/packages/web/src/app/repos/[id]/architecture/page.tsx
index 3a8e269c4..fd26c4cbe 100644
--- a/packages/web/src/app/repos/[id]/architecture/page.tsx
+++ b/packages/web/src/app/repos/[id]/architecture/page.tsx
@@ -4,16 +4,19 @@
* Architecture — `/repos/[id]/architecture`.
*
* Tabs are DATASETS, not zoom levels:
- * - Map — the dependency graph, at community or file scope
+ * - Map — the dependency graph, at community or file scope, or as the
+ * outline (`?view=tree`)
* - 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 graph. That control carries the tree scope too, since it is a third way
+ * of presenting the same file graph rather than a dataset of its own. 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
@@ -23,7 +26,7 @@
* ## URL state
*
* One param per axis, no two params saying the same thing:
- * - `?view=` communities | files | coupling | packages | symbols
+ * - `?view=` communities | files | tree | coupling | packages | symbols
* - `?signal=` dead | hot — which overlay is lit on the graph
* - `?module=` a path prefix the file scope is filtered to
* - `?community=` the community the file scope is drilled into. One axis with
@@ -32,6 +35,12 @@
* (`tests,examples,docs`); absent means production only. `external` in
* the same list draws third-party modules in the Files view.
*
+ * `view=tree` is the third reading of the file graph, under the Map tab with
+ * the other two: the same payload as an outline. It is a scope rather than a
+ * tab for the reason above — tabs are datasets and this is the file dataset
+ * again — and it is steered from the same `GraphScopeSwitcher` the canvas uses,
+ * which both views render.
+ *
* `?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
@@ -50,6 +59,7 @@ import { PageFrame } from "@repowise-dev/ui/shared/page-shell";
import { ViewTabs } from "@repowise-dev/ui/shared/view-tabs";
import { ErrorBoundary } from "@repowise-dev/ui/shared";
import { GraphView } from "@/components/architecture/graph-view";
+import { CodeGraphTreeView } from "@/components/architecture/code-graph-tree-view";
import { DependenciesView } from "@/components/architecture/dependencies-view";
import { SymbolTableWrapper as SymbolTable } from "@/components/symbols/symbol-table-wrapper";
import { SymbolIndexHeader } from "@repowise-dev/ui/symbols";
@@ -60,8 +70,8 @@ import { couplingUrlParsers } from "@/components/coupling/coupling-url";
// The curated layered view now lives under the dedicated Knowledge Graph route.
const KNOWLEDGE_GRAPH_VIEWS = new Set(["layers"]);
-/** Canonical `?view=` values. The first two are both the Map tab. */
-const CANONICAL = ["communities", "files", "coupling", "packages", "symbols"] as const;
+/** Canonical `?view=` values. The first three are all the Map tab. */
+const CANONICAL = ["communities", "files", "tree", "coupling", "packages", "symbols"] as const;
type CanonicalView = (typeof CANONICAL)[number];
/** Everything `?view=` accepts, canonical values plus legacy spellings. */
@@ -91,10 +101,11 @@ const LEGACY_VIEW_MODES: Record<string, { view: CanonicalView; signal?: "dead" |
unified: { view: "files", signal: "dead" },
};
-// Which tab a canonical view renders under. Both graph scopes are the Map tab.
+// Which tab a canonical view renders under. All three graph scopes are the Map tab.
const TAB_FOR_VIEW: Record<CanonicalView, string> = {
communities: "map",
files: "map",
+ tree: "map",
coupling: "coupling",
packages: "packages",
symbols: "symbols",
@@ -193,7 +204,7 @@ export default function ArchitecturePage({
);
const handleScopeChange = useCallback(
- (next: "communities" | "files") => {
+ (next: "communities" | "files" | "tree") => {
void setView(next);
},
[setView],
@@ -223,7 +234,14 @@ export default function ArchitecturePage({
tabIndex={0}
className="min-h-0 flex-1 overflow-auto"
>
- {activeTab === "map" && (
+ {activeTab === "map" && view === "tree" && (
+ <CodeGraphTreeView
+ repoId={repoId}
+ scope="tree"
+ onScopeChange={handleScopeChange}
+ />
+ )}
+ {activeTab === "map" && view !== "tree" && (
<GraphView
repoId={repoId}
scope={view === "files" ? "files" : "communities"}
diff --git a/packages/web/src/components/architecture/code-graph-tree-view.test.tsx b/packages/web/src/components/architecture/code-graph-tree-view.test.tsx
new file mode 100644
index 000000000..26080f3e4
--- /dev/null
+++ b/packages/web/src/components/architecture/code-graph-tree-view.test.tsx
@@ -0,0 +1,149 @@
+// @vitest-environment jsdom
+
+/**
+ * The tree tab's wiring: which payload it reads, what it says when the payload
+ * is capped, and that the stepped "load more" reaches the fetch rather than
+ * only the caption.
+ *
+ * Deliberately mounted through the same `useGraph` hook the Map's file scope
+ * uses, so a regression that gives the tree its own endpoint or its own key
+ * fails here rather than quietly doubling the traffic.
+ */
+
+import * as React from "react";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { GraphExportResponse } from "@/lib/api/types";
+
+const mocks = vi.hoisted(() => ({
+ useGraph: vi.fn(),
+ mutate: vi.fn(),
+}));
+
+vi.mock("@/lib/hooks/use-graph", () => ({
+ useGraph: mocks.useGraph,
+}));
+
+vi.mock("next/link", () => ({
+ default: ({ children, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement>) => (
+ <a {...props}>{children}</a>
+ ),
+}));
+
+import { CodeGraphTreeView } from "./code-graph-tree-view";
+import { LOAD_MORE_STEP } from "@repowise-dev/ui/graph/graph-truncation-banner";
+
+afterEach(cleanup);
+
+const node = (id: string) => ({
+ node_id: id,
+ node_type: "file",
+ language: "typescript",
+ symbol_count: 1,
+ pagerank: 0,
+ betweenness: 0,
+ community_id: 0,
+ is_test: false,
+ is_entry_point: false,
+ has_doc: false,
+});
+
+const payload: GraphExportResponse = {
+ nodes: [node("src/app.ts"), node("src/util.ts")],
+ links: [
+ {
+ source: "src/app.ts",
+ target: "src/util.ts",
+ imported_names: ["truncatePath"],
+ edge_type: "imports",
+ },
+ ],
+};
+
+function hookResult(overrides: Partial<Record<string, unknown>> = {}) {
+ return {
+ graph: undefined,
+ error: undefined,
+ isLoading: false,
+ mutate: mocks.mutate,
+ ...overrides,
+ };
+}
+
+describe("CodeGraphTreeView", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.useGraph.mockReturnValue(hookResult());
+ });
+
+ it("reads the same graph hook as the file-scope canvas, with no limit on first load", () => {
+ render(<CodeGraphTreeView repoId="r1" scope="tree" onScopeChange={vi.fn()} />);
+ expect(mocks.useGraph).toHaveBeenCalledWith("r1", undefined);
+ });
+
+ it("shows a skeleton while the first payload is in flight", () => {
+ mocks.useGraph.mockReturnValue(hookResult({ isLoading: true }));
+ render(<CodeGraphTreeView repoId="r1" scope="tree" onScopeChange={vi.fn()} />);
+ expect(screen.getByLabelText("Loading the code graph tree")).toBeTruthy();
+ expect(screen.queryByText("No files to outline")).toBeNull();
+ });
+
+ it("opens a file in place and names the types it imports", () => {
+ mocks.useGraph.mockReturnValue(hookResult({ graph: payload }));
+ render(<CodeGraphTreeView repoId="r1" scope="tree" onScopeChange={vi.fn()} />);
+ fireEvent.click(screen.getByText("src"));
+ fireEvent.click(screen.getByText("app.ts"));
+ expect(screen.getByText("truncatePath")).toBeTruthy();
+ expect(screen.getByText("src/util.ts")).toBeTruthy();
+ });
+
+ it("states the cap and re-fetches with a stepped limit when more is asked for", () => {
+ mocks.useGraph.mockReturnValue(
+ hookResult({
+ graph: {
+ ...payload,
+ truncated: true,
+ total_node_count: 3194,
+ },
+ }),
+ );
+ render(<CodeGraphTreeView repoId="r1" scope="tree" onScopeChange={vi.fn()} />);
+ // The server's own numbers, not a count of what rendered.
+ expect(screen.getByText(/most-connected files of/)).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: /Load .* more/ }));
+ // Before any step has been taken the in-effect cap is read off the payload,
+ // which is the same contract the canvas's banner runs on: `limit` must be
+ // the cap that produced the drawn nodes, not a constant. The fixture is two
+ // nodes, so the next rung is one step above two.
+ expect(mocks.useGraph).toHaveBeenLastCalledWith(
+ "r1",
+ LOAD_MORE_STEP + payload.nodes.length,
+ );
+ });
+
+ it("drops the banner once the payload is whole", () => {
+ mocks.useGraph.mockReturnValue(
+ hookResult({ graph: { ...payload, truncated: false, total_node_count: 2 } }),
+ );
+ render(<CodeGraphTreeView repoId="r1" scope="tree" onScopeChange={vi.fn()} />);
+ expect(screen.queryByText(/most-connected files of/)).toBeNull();
+ });
+
+ it("reports a failed payload with a retry that revalidates", () => {
+ mocks.useGraph.mockReturnValue(hookResult({ error: new Error("boom") }));
+ render(<CodeGraphTreeView repoId="r1" scope="tree" onScopeChange={vi.fn()} />);
+ expect(screen.getByText("Couldn't load the code graph")).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: /Retry/ }));
+ expect(mocks.mutate).toHaveBeenCalledOnce();
+ });
+
+ it("carries the scope switcher so the way back to the canvas is on this tab", () => {
+ const onScopeChange = vi.fn();
+ mocks.useGraph.mockReturnValue(hookResult({ graph: payload }));
+ render(<CodeGraphTreeView repoId="r1" scope="tree" onScopeChange={onScopeChange} />);
+ const tree = screen.getByRole("radio", { name: "Tree" });
+ expect(tree.getAttribute("aria-checked")).toBe("true");
+ fireEvent.click(screen.getByRole("radio", { name: "Files" }));
+ expect(onScopeChange).toHaveBeenCalledWith("files");
+ });
+});
diff --git a/packages/web/src/components/architecture/code-graph-tree-view.tsx b/packages/web/src/components/architecture/code-graph-tree-view.tsx
new file mode 100644
index 000000000..9b4463f57
--- /dev/null
+++ b/packages/web/src/components/architecture/code-graph-tree-view.tsx
@@ -0,0 +1,99 @@
+"use client";
+
+/**
+ * CodeGraphTreeView — the Architecture tab that draws the dependency graph as
+ * an outline instead of a canvas.
+ *
+ * Data comes from the same `/api/graph/{repo_id}` payload the Map tab's file
+ * scope draws (`useGraph`), under the same SWR key, so moving between the two
+ * tabs is a re-render rather than a second fetch, and a revalidation on one is
+ * a revalidation on both. Nothing here resolves imports or builds a graph: the
+ * server already ships each edge's `imported_names`.
+ *
+ * The node cap is real, so it is stated. `/api/graph` returns the most
+ * connected slice of a large repo with `truncated=true`; an outline that showed
+ * 1,500 of 3,194 files without saying so would read as the whole repository.
+ * Same banner and same stepped "load more" as the canvas, for that reason.
+ */
+
+import { useCallback, useState } from "react";
+import Link from "next/link";
+import { ListTree } from "lucide-react";
+import { CodeGraphTree } from "@repowise-dev/ui/graph/code-graph-tree";
+import { GraphTruncationBanner } from "@repowise-dev/ui/graph/graph-truncation-banner";
+import {
+ GraphScopeSwitcher,
+ type GraphScope,
+} from "@repowise-dev/ui/graph/graph-scope-controls";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
+import { ApiError } from "@repowise-dev/ui/shared/api-error";
+import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
+import { useGraph } from "@/lib/hooks/use-graph";
+
+export function CodeGraphTreeView({
+ repoId,
+ scope,
+ onScopeChange,
+}: {
+ repoId: string;
+ /** Controlled by the page, which owns `?view=`, so the one scope control on
+ * this axis carries the way back to the canvas. */
+ scope: GraphScope;
+ onScopeChange: (scope: GraphScope) => void;
+}) {
+ const [graphLimit, setGraphLimit] = useState<number | undefined>(undefined);
+ const { graph, error, isLoading, mutate } = useGraph(repoId, graphLimit);
+
+ const fileHref = useCallback(
+ (path: string) => fileEntityPath(`/repos/${repoId}`, path),
+ [repoId],
+ );
+
+ if (error && !graph) {
+ return (
+ <ApiError
+ title="Couldn't load the code graph"
+ message={toFriendlyMessage(error)}
+ onRetry={() => void mutate()}
+ />
+ );
+ }
+
+ return (
+ <div className="max-w-[1600px] space-y-5 p-4 sm:p-6">
+ <div className="flex flex-col gap-3 border-b border-[var(--color-border-default)] pb-4 sm:flex-row sm:items-start sm:justify-between">
+ <div className="min-w-0">
+ <h1 className="mb-1 flex items-center gap-2 text-xl font-semibold text-[var(--color-text-primary)]">
+ <ListTree className="h-5 w-5 text-[var(--color-accent-primary)]" />
+ Code graph tree
+ </h1>
+ <p className="max-w-3xl text-sm text-[var(--color-text-secondary)]">
+ The same files and dependencies the Map draws, as a tree you can open. Expand a
+ directory to walk it, then a file to see the types it imports and which file each
+ one comes from. Counts are read off this payload, so the tree and the map never
+ disagree about how many files are in it.
+ </p>
+ </div>
+ <div className="shrink-0">
+ <GraphScopeSwitcher scope={scope} onScopeChange={onScopeChange} />
+ </div>
+ </div>
+
+ {graph?.truncated && graph.total_node_count != null && (
+ <GraphTruncationBanner
+ shown={graph.nodes.length}
+ total={graph.total_node_count}
+ limit={graphLimit ?? graph.nodes.length}
+ onLoadMore={(nextLimit) => setGraphLimit(nextLimit)}
+ />
+ )}
+
+ <CodeGraphTree
+ graph={graph}
+ isLoading={isLoading}
+ fileHref={fileHref}
+ LinkComponent={Link}
+ />
+ </div>
+ );
+}
diff --git a/packages/web/src/components/architecture/graph-view.tsx b/packages/web/src/components/architecture/graph-view.tsx
index 800a78056..e25bb865c 100644
--- a/packages/web/src/components/architecture/graph-view.tsx
+++ b/packages/web/src/components/architecture/graph-view.tsx
@@ -10,6 +10,7 @@ import { GraphTruncationBanner } from "@repowise-dev/ui/graph/graph-truncation-b
import {
GraphScopeSwitcher,
GraphNarrowingSelect,
+ type GraphScope,
} 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";
@@ -62,7 +63,9 @@ export function GraphView({
repoId: string;
/** Controlled by the page, which owns `?view=`. */
scope: Scope;
- onScopeChange: (scope: Scope) => void;
+ /** The page owns `?view=`, so a scope the canvas does not draw (the tree)
+ * is handed straight up rather than swallowed here. */
+ onScopeChange: (scope: GraphScope) => void;
}) {
const t = useTranslations("architecture");
const searchParams = useSearchParams();
@@ -198,13 +201,17 @@ export function GraphView({
}, [onScopeChange]);
const handleScopeChange = useCallback(
- (next: Scope) => {
+ (next: GraphScope) => {
// Narrowing is a file-scope concept, so it does not survive a trip to the
// constellation. It does not survive a trip *back* either: a
// `?view=communities&community=3` link (hand-edited, or an old share)
// renders the constellation with the param still set, and without this
// clicking "Files" would drop the reader inside community 3 rather than
// in the file graph they asked for.
+ //
+ // The tree is included: it is not narrowed by `?module=` or `?community=`
+ // either, and a pin left set would be there when the reader came back to
+ // the canvas.
void setActiveModule(null);
void setCommunityParam(null);
// `?node=` forces the file scope for as long as it is set, so leaving it
diff --git a/packages/web/src/components/chat/repository-chat-context.test.ts b/packages/web/src/components/chat/repository-chat-context.test.ts
index 027d05118..891ed0abc 100644
--- a/packages/web/src/components/chat/repository-chat-context.test.ts
+++ b/packages/web/src/components/chat/repository-chat-context.test.ts
@@ -112,6 +112,14 @@ describe("getRepositoryChatContext", () => {
params({ view: "coupling" }),
).label,
).toBe("Architecture · Coupling");
+ // The tree scope is a third reading of the same graph, and names itself so
+ // a chat grounded on it is not labelled as the canvas.
+ expect(
+ getRepositoryChatContext(
+ "/repos/r1/architecture",
+ params({ view: "tree" }),
+ ).label,
+ ).toBe("Architecture · Tree");
expect(
getRepositoryChatContext(
"/repos/r1/code-health",
diff --git a/packages/web/src/components/chat/repository-chat-context.ts b/packages/web/src/components/chat/repository-chat-context.ts
index 21247b25a..1248c1172 100644
--- a/packages/web/src/components/chat/repository-chat-context.ts
+++ b/packages/web/src/components/chat/repository-chat-context.ts
@@ -79,6 +79,7 @@ function decodeSegment(segment: string): string {
const ARCHITECTURE_VIEW_LABELS: Readonly<Record<string, string>> = {
communities: "Map",
files: "Files",
+ tree: "Tree",
coupling: "Coupling",
packages: "Third-party",
symbols: "Symbols",
diff --git a/packages/web/src/components/chat/repository-chat-dock.test.tsx b/packages/web/src/components/chat/repository-chat-dock.test.tsx
index f6018ed6b..3580a66c5 100644
--- a/packages/web/src/components/chat/repository-chat-dock.test.tsx
+++ b/packages/web/src/components/chat/repository-chat-dock.test.tsx
@@ -46,6 +46,9 @@ describe("RepositoryChatDock", () => {
expect(getRepositoryDockCollisionInset("architecture", "packages")).toBeUndefined();
expect(getRepositoryDockCollisionInset("architecture", "symbols")).toBeUndefined();
expect(getRepositoryDockCollisionInset("architecture", "deps")).toBeUndefined();
+ // The tree scope is the same file graph as an outline: no canvas, and so
+ // nothing in the bottom-right corner to clear.
+ expect(getRepositoryDockCollisionInset("architecture", "tree")).toBeUndefined();
});
it("does not mount duplicate chat UI on the full chat route", () => {
diff --git a/packages/web/src/components/chat/repository-chat-dock.tsx b/packages/web/src/components/chat/repository-chat-dock.tsx
index dc0d6ed77..b7056b451 100644
--- a/packages/web/src/components/chat/repository-chat-dock.tsx
+++ b/packages/web/src/components/chat/repository-chat-dock.tsx
@@ -22,12 +22,17 @@ export const REPOSITORY_GRAPH_DOCK_INSET = "12.5rem";
/** Architecture `?view=` values that render a table, not the Sigma canvas.
* `deps` is the legacy spelling of `packages`. Absent or unrecognised means
- * the Map tab, which is the default landing view. */
+ * the Map tab, which is the default landing view.
+ *
+ * `tree` renders no canvas either: it is the same file graph as an outline.
+ * Nothing is anchored in the bottom-right corner there, so lifting the pill
+ * would open the same 200px of dead space this set exists to close. */
const ARCHITECTURE_VIEWS_WITHOUT_CANVAS = new Set([
"coupling",
"packages",
"symbols",
"deps",
+ "tree",
]);
/**
diff --git a/packages/web/src/lib/hooks/use-graph.ts b/packages/web/src/lib/hooks/use-graph.ts
index 50916910f..4eec5655a 100644
--- a/packages/web/src/lib/hooks/use-graph.ts
+++ b/packages/web/src/lib/hooks/use-graph.ts
@@ -57,12 +57,12 @@ export function useZoomMap(
}
export function useGraph(repoId: string | null, limit?: number) {
- const { data, error, isLoading } = useSWR<GraphExportResponse>(
+ const { data, error, isLoading, mutate } = useSWR<GraphExportResponse>(
repoId ? `graph:${repoId}:${limit ?? "default"}` : null,
() => getGraph(repoId!, limit),
SWR_OPTS,
);
- return { graph: data, error, isLoading };
+ return { graph: data, error, isLoading, mutate };
}
/**