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(coupling): make the change-coupling page interactive and surface it on Overview (#986)

Raghav Chamadiyab701f1fe00dd
diff --git a/packages/ui/COMPONENT_CONTRACTS.md b/packages/ui/COMPONENT_CONTRACTS.md
index 9c0c33e6a..8ec922d7a 100644
--- a/packages/ui/COMPONENT_CONTRACTS.md
+++ b/packages/ui/COMPONENT_CONTRACTS.md
@@ -375,32 +375,68 @@ the caller. Co-change is a temporal hint, not a verified dependency, and
Hierarchical edge-bundling diagram (`d3-hierarchy` radial cluster +
`d3-shape` `curveBundle`). Files sit on a ring grouped by their directory
hierarchy; bundled arcs link files that change together. Dots are colored by
-health band and sized by lines + coupling degree. Hovering a file lifts its
-couplings (colored by the partner's health band) and dims the rest. Focus is
-controllable (`focusedPath`/`onFocusChange`) for cross-highlight with a table,
-or falls back to internal hover state.
+health band and sized by lines + coupling degree. Hovering a file peeks its
+couplings (colored by the partner's health band) and dims the rest; clicking a
+file pins a sticky selection (persistent accent ring) and clicking empty canvas
+clears it. The effective focus (`focusedPath` = hover ?? pinned) is controlled
+for cross-highlight with a table, and falls back to internal hover/pin state.
| Prop | Type | Required |
|------|------|----------|
| `nodes` | `CouplingNode[]` (`@repowise-dev/types/coupling`) | yes |
| `edges` | `CouplingEdge[]` (`@repowise-dev/types/coupling`) | yes |
| `totalEdges` | `number` (pre-cap count, for the "showing N of M" line) | no |
-| `focusedPath` | `string \| null` (controlled focus) | no |
-| `onFocusChange` | `(path: string \| null) => void` | no |
+| `focusedPath` | `string \| null` (effective focus: hover ?? pinned) | no |
+| `pinnedPath` | `string \| null` (sticky selection; draws the ring) | no |
+| `onHover` | `(path: string \| null) => void` (transient peek) | no |
+| `onPinToggle` | `(path: string \| null) => void` (click a dot / empty canvas) | no |
| `size` | `number` (square viewBox edge, default 760) | no |
### `coupling/coupling-table` — `CouplingTable`
-The precise, ranked companion to the diagram: one row per coupling
-(strongest first) with a strength bar and last-shared-commit date. Clicking a
-row toggles focus on that file; rows incident to the focused file are
-emphasised. Uses `shared/responsive-table`.
+The precise, ranked companion to the diagram: one row per coupling with a
+strength bar and last-shared-commit date, sortable by Strength or Last. File
+names are links (when `linkForPath` is set); clicking a row pins its source
+file, and hovering a row (or a name) peeks that file. Uses
+`shared/responsive-table`.
| Prop | Type | Required |
|------|------|----------|
| `edges` | `CouplingEdge[]` (`@repowise-dev/types/coupling`) | yes |
-| `focusedPath` | `string \| null` | no |
-| `onFocusChange` | `(path: string \| null) => void` | no |
+| `focusedPath` | `string \| null` (effective focus) | no |
+| `pinnedPath` | `string \| null` (drives the selected-row style) | no |
+| `onHover` | `(path: string \| null) => void` | no |
+| `onPinToggle` | `(path: string \| null) => void` | no |
+| `onGeneratePrompt` | `(edge: CouplingEdge) => void` (shows the AI decouple action) | no |
+| `linkForPath` | `(path: string) => string` (makes file names links) | no |
+| `LinkComponent` | link component for file links (defaults to `<a>`) | no |
+
+### `coupling/coupling-explorer` — `CouplingExplorer`
+
+The full change-coupling surface: the diagram over a sortable/filterable table,
+sharing one focus model, plus the AI-decouple modal and a default pin on the
+most-coupled hub. Lives in the shared package so OSS and hosted share the
+interaction; the host supplies only the link prefix and optional URL sync.
+
+| Prop | Type | Required |
+|------|------|----------|
+| `data` | `CouplingGraphResponse` (`@repowise-dev/types/coupling`) | yes |
+| `repoLinkPrefix` | `string` (e.g. `/repos/abc`; makes file names links) | no |
+| `LinkComponent` | link component for file links (defaults to `<a>`) | no |
+| `initialFocus` | `string \| null` (seed pin, e.g. from a `?focus=` deep link) | no |
+| `onFocusChange` | `(path: string \| null) => void` (reflect the pin to the URL) | no |
+
+### `dashboard/coupling-mini-card` — `CouplingMiniCard`
+
+Overview front-door for the (sidebar-less) change-coupling view: previews the
+top few coupled pairs with strength bars and links to the full page. Fully
+presentational.
+
+| Prop | Type | Required |
+|------|------|----------|
+| `edges` | `CouplingEdge[]` (top couplings, strongest-first) | yes |
+| `href` | `string` (link to the full coupling view) | yes |
+| `LinkComponent` | link component (defaults to `<a>`) | no |
---
diff --git a/packages/ui/__tests__/coupling/coupling-graph.test.tsx b/packages/ui/__tests__/coupling/coupling-graph.test.tsx
index 1ac8e2be7..26c263a53 100644
--- a/packages/ui/__tests__/coupling/coupling-graph.test.tsx
+++ b/packages/ui/__tests__/coupling/coupling-graph.test.tsx
@@ -1,4 +1,4 @@
-import { describe, it, expect } from "vitest";
+import { describe, it, expect, vi } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import type { CouplingEdge, CouplingNode } from "@repowise-dev/types/coupling";
import { CouplingGraph } from "../../src/coupling/coupling-graph.js";
@@ -27,22 +27,35 @@ describe("CouplingGraph", () => {
expect(screen.getByText(/showing 2 of 9 couplings/i)).toBeInTheDocument();
});
- it("emphasizes a file's couplings on hover (focus changes)", () => {
+ it("peeks a file's couplings on hover (onHover fires)", () => {
const nodes = [node("api/a.py"), node("core/b.py")];
const edges = [edge("api/a.py", "core/b.py")];
- let focus: string | null = null;
+ const onHover = vi.fn();
+ const { container } = render(
+ <CouplingGraph nodes={nodes} edges={edges} focusedPath={null} onHover={onHover} />,
+ );
+ const circle = container.querySelector("circle");
+ expect(circle).not.toBeNull();
+ fireEvent.mouseEnter(circle!.parentElement!);
+ expect(onHover).toHaveBeenCalledWith(expect.any(String));
+ });
+
+ it("pins a file on click (onPinToggle fires with the path)", () => {
+ const nodes = [node("api/a.py"), node("core/b.py")];
+ const edges = [edge("api/a.py", "core/b.py")];
+ const onPinToggle = vi.fn();
const { container } = render(
<CouplingGraph
nodes={nodes}
edges={edges}
- focusedPath={focus}
- onFocusChange={(p) => (focus = p)}
+ focusedPath={null}
+ pinnedPath={null}
+ onPinToggle={onPinToggle}
/>,
);
const circle = container.querySelector("circle");
- expect(circle).not.toBeNull();
- fireEvent.mouseEnter(circle!.parentElement!);
- expect(focus).not.toBeNull();
+ fireEvent.click(circle!.parentElement!);
+ expect(onPinToggle).toHaveBeenCalledWith(expect.any(String));
});
});
@@ -54,12 +67,11 @@ describe("CouplingTable", () => {
expect(screen.getByText("↔ b.py")).toBeInTheDocument();
});
- it("toggles focus on row click", () => {
- const edges = [edge("a.py", "b.py", 4)];
- let focus: string | null = null;
- render(<CouplingTable edges={edges} focusedPath={focus} onFocusChange={(p) => (focus = p)} />);
+ it("toggles the pin on row click", () => {
+ const onPinToggle = vi.fn();
+ render(<CouplingTable edges={[edge("a.py", "b.py", 4)]} pinnedPath={null} onPinToggle={onPinToggle} />);
fireEvent.click(screen.getByText("a.py"));
- expect(focus).toBe("a.py");
+ expect(onPinToggle).toHaveBeenCalledWith("a.py");
});
it("shows the empty state with no couplings", () => {
diff --git a/packages/ui/__tests__/coupling/coupling-table.test.tsx b/packages/ui/__tests__/coupling/coupling-table.test.tsx
index fa91e715b..43a363e1d 100644
--- a/packages/ui/__tests__/coupling/coupling-table.test.tsx
+++ b/packages/ui/__tests__/coupling/coupling-table.test.tsx
@@ -27,17 +27,35 @@ describe("CouplingTable (virtualized)", () => {
expect(screen.getByText("7")).toBeInTheDocument();
});
- it("toggles focus on row click", () => {
- let focus: string | null = null;
+ it("toggles the pin on row click", () => {
+ const onPinToggle = vi.fn();
+ render(
+ <CouplingTable edges={[edge("a.py", "b.py", 4)]} pinnedPath={null} onPinToggle={onPinToggle} />,
+ );
+ fireEvent.click(screen.getByText("a.py"));
+ expect(onPinToggle).toHaveBeenCalledWith("a.py");
+ });
+
+ it("renders file names as links when linkForPath is provided", () => {
render(
<CouplingTable
- edges={[edge("a.py", "b.py", 4)]}
- focusedPath={focus}
- onFocusChange={(p) => (focus = p)}
+ edges={[edge("api/a.py", "core/b.py", 4)]}
+ linkForPath={(p) => `/repos/r/files/${p}`}
/>,
);
- fireEvent.click(screen.getByText("a.py"));
- expect(focus).toBe("a.py");
+ const link = screen.getByText("a.py").closest("a");
+ expect(link).not.toBeNull();
+ expect(link).toHaveAttribute("href", "/repos/r/files/api/a.py");
+ });
+
+ it("sorts by strength ascending when the Strength header is toggled", () => {
+ const edges = [edge("a.py", "b.py", 9), edge("c.py", "d.py", 1)];
+ render(<CouplingTable edges={edges} />);
+ // Default is strength desc → strongest (9) first. Toggle to ascending.
+ fireEvent.click(screen.getByRole("button", { name: /strength/i }));
+ const rows = screen.getAllByRole("row").filter((r) => r.querySelector("td"));
+ // First data row should now be the weakest pair (c.py ↔ d.py).
+ expect(rows[0]).toHaveTextContent("c.py");
});
it("shows the empty state when there are no couplings", () => {
diff --git a/packages/ui/src/coupling/coupling-explorer.tsx b/packages/ui/src/coupling/coupling-explorer.tsx
new file mode 100644
index 000000000..c368bd80f
--- /dev/null
+++ b/packages/ui/src/coupling/coupling-explorer.tsx
@@ -0,0 +1,206 @@
+"use client";
+
+import * as React from "react";
+import { useEffect, useMemo, useState } from "react";
+import { Search, X } from "lucide-react";
+import { CouplingGraph } from "./coupling-graph";
+import { CouplingTable } from "./coupling-table";
+import { GraphCanvasShell } from "../graph/graph-canvas-shell";
+import { AiPromptModal, buildCouplingAiPrompt } from "../health";
+import { fileEntityPath } from "../shared/entity/routes";
+import { cn } from "../lib/cn";
+import type { CouplingEdge, CouplingGraphResponse } from "@repowise-dev/types/coupling";
+
+/** Injected link component (e.g. Next's Link); defaults to a plain anchor. */
+type LinkLike = React.ElementType<{
+ href: string;
+ className?: string;
+ children: React.ReactNode;
+}>;
+
+export interface CouplingExplorerProps {
+ data: CouplingGraphResponse;
+ /**
+ * Repo link prefix (e.g. `/repos/abc123`). File names in the table become
+ * links under `${prefix}/files/...`. Omit to render plain (non-link) names.
+ */
+ repoLinkPrefix?: string;
+ /** Link component for file links (defaults to a plain anchor). */
+ LinkComponent?: LinkLike;
+ /**
+ * Initial pinned file (e.g. from a `?focus=` deep link). When omitted the
+ * explorer opens with the most-coupled hub pinned so the diagram lands with a
+ * story already told rather than a flat ring.
+ */
+ initialFocus?: string | null;
+ /** Called when the user pins/clears a file — reflect it to the URL if wanted. */
+ onFocusChange?: (path: string | null) => void;
+}
+
+/** The file with the most couplings — the most useful default story to open on. */
+function topHub(edges: CouplingEdge[]): string | null {
+ const degree = new Map<string, number>();
+ for (const e of edges) {
+ degree.set(e.source, (degree.get(e.source) ?? 0) + 1);
+ degree.set(e.target, (degree.get(e.target) ?? 0) + 1);
+ }
+ let best: string | null = null;
+ let bestN = 0;
+ for (const [path, n] of degree) {
+ if (n > bestN) {
+ best = path;
+ bestN = n;
+ }
+ }
+ return best;
+}
+
+function shortName(path: string): string {
+ return path.split("/").pop() ?? path;
+}
+
+/**
+ * The full change-coupling surface: the edge-bundling diagram (centerpiece)
+ * over a precise, sortable, filterable table, sharing one focus model. A
+ * transient `hover` peeks over a sticky `pinned` selection so the picture never
+ * goes blank — hover a file (in either the ring or the table) to trace what it
+ * changes with, click to pin, click empty canvas to clear.
+ *
+ * This composition lives in the shared package (not the app) so both the OSS
+ * and hosted apps get the same interaction from a single source; the app only
+ * supplies the link prefix and, optionally, URL sync for the pinned file.
+ */
+export function CouplingExplorer({
+ data,
+ repoLinkPrefix,
+ LinkComponent,
+ initialFocus,
+ onFocusChange,
+}: CouplingExplorerProps) {
+ const defaultPin = useMemo(
+ () => (initialFocus !== undefined ? initialFocus : topHub(data.edges)),
+ // Only seed once from the initial data/prop; user actions drive it after.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [],
+ );
+ const [pinned, setPinned] = useState<string | null>(defaultPin);
+ const [hover, setHover] = useState<string | null>(null);
+ const [query, setQuery] = useState("");
+ const [promptEdge, setPromptEdge] = useState<CouplingEdge | null>(null);
+
+ // Drop a stale pin if a background revalidation returns an edge set that no
+ // longer contains it, so the guidance never claims to trace a vanished file.
+ const nodePaths = useMemo(
+ () => new Set(data.nodes.map((n) => n.file_path)),
+ [data.nodes],
+ );
+ useEffect(() => {
+ if (pinned && !nodePaths.has(pinned)) setPinned(null);
+ }, [pinned, nodePaths]);
+
+ // Transient hover peeks over the sticky pin: what the ring and table light up.
+ const focus = hover ?? pinned;
+
+ const changePin = (path: string | null) => {
+ setPinned(path);
+ onFocusChange?.(path);
+ };
+
+ const filtered = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ if (!q) return data.edges;
+ return data.edges.filter(
+ (e) => e.source.toLowerCase().includes(q) || e.target.toLowerCase().includes(q),
+ );
+ }, [data.edges, query]);
+
+ const linkForPath = repoLinkPrefix
+ ? (path: string) => fileEntityPath(repoLinkPrefix, path)
+ : undefined;
+
+ return (
+ <div className="space-y-5">
+ <GraphCanvasShell className="block h-auto">
+ <div className="mx-auto w-full max-w-[820px]">
+ {/* Guidance line so the diagram is not a mystery until you touch it.
+ Echoes the pinned file so the sticky selection is always named. */}
+ <p className="mb-2 text-xs text-[var(--color-text-tertiary)]">
+ {pinned ? (
+ <>
+ Tracing{" "}
+ <span className="font-mono text-[var(--color-text-secondary)]" title={pinned}>
+ {shortName(pinned)}
+ </span>
+ . Hover any file to peek, click to pin, or click empty space to clear.
+ </>
+ ) : (
+ <>Hover a file to trace what changes with it; click to pin the view.</>
+ )}
+ </p>
+ <CouplingGraph
+ nodes={data.nodes}
+ edges={data.edges}
+ totalEdges={data.total_edges}
+ focusedPath={focus}
+ pinnedPath={pinned}
+ onHover={setHover}
+ onPinToggle={changePin}
+ />
+ </div>
+ </GraphCanvasShell>
+
+ <div className="space-y-3 border-t border-[var(--color-border-default)] pt-4">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="relative min-w-0 flex-1 sm:max-w-xs">
+ <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--color-text-tertiary)]" />
+ <input
+ type="text"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Filter table by file path…"
+ aria-label="Filter the coupled-files table by path"
+ className="h-8 w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] pl-8 pr-3 text-xs text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--color-accent-primary)]"
+ />
+ </div>
+ {pinned && (
+ <button
+ type="button"
+ onClick={() => changePin(null)}
+ className={cn(
+ "inline-flex h-8 shrink-0 items-center gap-1 rounded-md border border-[var(--color-border-default)] px-2.5 text-xs text-[var(--color-text-secondary)]",
+ "hover:bg-[var(--color-bg-elevated)]",
+ )}
+ >
+ <X className="h-3.5 w-3.5" />
+ Clear selection
+ </button>
+ )}
+ </div>
+
+ <CouplingTable
+ edges={filtered}
+ focusedPath={focus}
+ pinnedPath={pinned}
+ onHover={setHover}
+ onPinToggle={changePin}
+ onGeneratePrompt={setPromptEdge}
+ linkForPath={linkForPath}
+ LinkComponent={LinkComponent}
+ />
+ </div>
+
+ <AiPromptModal
+ open={promptEdge !== null}
+ onOpenChange={(o) => !o && setPromptEdge(null)}
+ getPrompt={
+ promptEdge
+ ? (flavor) => buildCouplingAiPrompt({ edge: promptEdge, flavor })
+ : null
+ }
+ filePath={promptEdge ? `${promptEdge.source} ↔ ${promptEdge.target}` : null}
+ title="AI decouple prompt"
+ description="A ready-to-paste prompt that has your AI agent diagnose why these two files change together and propose how to decouple them."
+ />
+ </div>
+ );
+}
diff --git a/packages/ui/src/coupling/coupling-graph.tsx b/packages/ui/src/coupling/coupling-graph.tsx
index a074e6bed..f6642c468 100644
--- a/packages/ui/src/coupling/coupling-graph.tsx
+++ b/packages/ui/src/coupling/coupling-graph.tsx
@@ -15,9 +15,18 @@ export interface CouplingGraphProps {
edges: CouplingEdge[];
/** Pre-cap edge count, for the honest "showing N of M" line. */
totalEdges?: number;
- /** Controlled focus (sync with the table); falls back to internal hover. */
+ /**
+ * Effective focus — the file whose couplings are lit and whose neighbors stay
+ * bright. The host passes `hover ?? pinned` so a transient hover peeks over a
+ * sticky pin. Falls back to internal hover/pin when uncontrolled.
+ */
focusedPath?: string | null;
- onFocusChange?: (path: string | null) => void;
+ /** The sticky selection (persistent ring). Falls back to internal pin. */
+ pinnedPath?: string | null;
+ /** Transient hover peek — mouse enters a dot, or leaves the canvas (null). */
+ onHover?: (path: string | null) => void;
+ /** Sticky selection changed — click a dot toggles it, click empty space clears it. */
+ onPinToggle?: (path: string | null) => void;
/** Square render size in px (viewBox edge). */
size?: number;
}
@@ -104,7 +113,8 @@ function project(angle: number, radius: number): [number, number] {
* frequently committed together. Edges are bundled through the folder tree so
* the picture reads as module-to-module flow rather than a hairball. Dots are
* colored by health band; hovering a file lifts its couplings (colored by the
- * partner's health) and dims the rest.
+ * partner's health) and dims the rest, and clicking a file pins that view so it
+ * survives the mouse leaving the canvas.
*
* Co-change is a temporal hint, not a verified dependency; edge thickness/
* opacity encode the decay-weighted strength, never a fabricated trend.
@@ -114,14 +124,28 @@ export function CouplingGraph({
edges,
totalEdges,
focusedPath,
- onFocusChange,
+ pinnedPath,
+ onHover,
+ onPinToggle,
size = 760,
}: CouplingGraphProps) {
- const [internalFocus, setInternalFocus] = useState<string | null>(null);
- const focus = focusedPath !== undefined ? focusedPath : internalFocus;
- const setFocus = (p: string | null) => {
- if (onFocusChange) onFocusChange(p);
- else setInternalFocus(p);
+ // Internal fallback for uncontrolled use (tests, standalone). When the host
+ // wires onHover/onPinToggle + focusedPath/pinnedPath these stay unused.
+ const [internalHover, setInternalHover] = useState<string | null>(null);
+ const [internalPin, setInternalPin] = useState<string | null>(null);
+
+ const pinned = pinnedPath !== undefined ? pinnedPath : internalPin;
+ const focus =
+ focusedPath !== undefined ? focusedPath : (internalHover ?? internalPin);
+
+ const hover = (p: string | null) => {
+ if (onHover) onHover(p);
+ else setInternalHover(p);
+ };
+ const togglePin = (p: string | null) => {
+ const next = p == null || p === pinned ? null : p;
+ if (onPinToggle) onPinToggle(next);
+ else setInternalPin(next);
};
const layout = useMemo(() => {
@@ -254,8 +278,20 @@ export function CouplingGraph({
width="100%"
role="img"
aria-label="Change-coupling diagram: files arranged in a ring, arcs link files that change together"
- onMouseLeave={() => setFocus(null)}
+ onMouseLeave={() => hover(null)}
>
+ {/* Background target: entering empty canvas drops the hover peek so the
+ lit edges clear immediately, and clicking it clears the pin. Kept
+ transparent and behind everything; dot clicks stopPropagation. */}
+ <rect
+ x={0}
+ y={0}
+ width={size}
+ height={size}
+ fill="transparent"
+ onMouseEnter={() => hover(null)}
+ onClick={() => togglePin(null)}
+ />
<g transform={`translate(${c},${c})`}>
{/* Module arc bands + labels around the perimeter. Tiny (≈single
file) arcs are left unlabelled so their names don't pile up near
@@ -323,6 +359,7 @@ export function CouplingGraph({
if (!n) return null;
const [x, y] = project(leaf.x!, leaf.y!);
const isFocus = focus === n.file_path;
+ const isPinned = pinned === n.file_path;
const isNeighbor = neighbors.has(n.file_path);
const dim = focus != null && !isFocus && !isNeighbor;
const isHub = hubPaths.has(n.file_path);
@@ -334,17 +371,35 @@ export function CouplingGraph({
// left half so the text never renders upside-down.
const onLeft = leaf.x! >= Math.PI;
const labelRot = (leaf.x! * 180) / Math.PI - 90;
+ const r = dotR(n);
return (
<g
key={n.file_path}
style={{ transition: "opacity 160ms ease", opacity: dim ? 0.18 : 1 }}
- onMouseEnter={() => setFocus(n.file_path)}
+ onMouseEnter={() => hover(n.file_path)}
+ onClick={(e) => {
+ e.stopPropagation();
+ togglePin(n.file_path);
+ }}
className="cursor-pointer"
>
+ {/* Persistent ring on the pinned file so the sticky selection
+ stays readable even while hovering elsewhere. */}
+ {isPinned && (
+ <circle
+ cx={x}
+ cy={y}
+ r={r * 1.5 + 3}
+ fill="none"
+ stroke="var(--color-accent-primary)"
+ strokeWidth={1.5}
+ strokeOpacity={0.9}
+ />
+ )}
<circle
cx={x}
cy={y}
- r={dotR(n) * (isFocus ? 1.5 : 1)}
+ r={r * (isFocus ? 1.5 : 1)}
fill={inkFor(n.score)}
fillOpacity={0.92}
stroke="var(--color-bg-surface)"
diff --git a/packages/ui/src/coupling/coupling-table.tsx b/packages/ui/src/coupling/coupling-table.tsx
index 4a78534f4..9ebbcf6fe 100644
--- a/packages/ui/src/coupling/coupling-table.tsx
+++ b/packages/ui/src/coupling/coupling-table.tsx
@@ -1,6 +1,8 @@
"use client";
-import { useMemo } from "react";
+import * as React from "react";
+import { useMemo, useState } from "react";
+import { ArrowDown, ArrowUp } from "lucide-react";
import { EmptyState } from "../shared/empty-state";
import { VirtualizedTable } from "../shared/virtualized-table";
import { clickableRowProps, CLICKABLE_ROW_CLS } from "../shared/responsive-table";
@@ -8,19 +10,79 @@ import { AiPromptButton } from "../health/ai-prompt-button";
import { cn } from "../lib/cn";
import type { CouplingEdge } from "@repowise-dev/types/coupling";
+/**
+ * Injected link component (e.g. Next's Link); defaults to a plain anchor. Kept
+ * to the minimal href/className/children shape so Next's `Link` assigns cleanly
+ * (event handlers ride on a wrapper, never on the injected element).
+ */
+type LinkLike = React.ElementType<{
+ href: string;
+ className?: string;
+ children: React.ReactNode;
+}>;
+
interface CouplingTableProps {
edges: CouplingEdge[];
/** Focused file (emphasizes rows incident to it; synced with the diagram). */
focusedPath?: string | null;
- onFocusChange?: (path: string | null) => void;
+ /** Sticky selection (drives the selected-row style; synced with the diagram). */
+ pinnedPath?: string | null;
+ /** Transient hover peek — row/filename enter, or table leave (null). */
+ onHover?: (path: string | null) => void;
+ /** Sticky selection toggle — clicking a row pins/unpins its source file. */
+ onPinToggle?: (path: string | null) => void;
/** When set, each row shows an "AI decouple prompt" action. */
onGeneratePrompt?: (edge: CouplingEdge) => void;
+ /** Resolve a file's detail-page href; when set, file names become links. */
+ linkForPath?: ((path: string) => string) | undefined;
+ /** Link component used for file links (defaults to a plain anchor). */
+ LinkComponent?: LinkLike | undefined;
}
+type SortKey = "strength" | "last";
+type SortDir = "asc" | "desc";
+
function basename(path: string): string {
return path.split("/").pop() ?? path;
}
+/** A clickable column header that toggles/shows the active sort direction. */
+function SortHeader({
+ label,
+ columnKey,
+ sortKey,
+ sortDir,
+ onToggle,
+}: {
+ label: React.ReactNode;
+ columnKey: SortKey;
+ sortKey: SortKey;
+ sortDir: SortDir;
+ onToggle: (key: SortKey) => void;
+}) {
+ const active = sortKey === columnKey;
+ return (
+ <button
+ type="button"
+ onClick={() => onToggle(columnKey)}
+ aria-sort={active ? (sortDir === "asc" ? "ascending" : "descending") : "none"}
+ className="inline-flex items-center gap-1 font-medium uppercase tracking-wider hover:text-[var(--color-text-secondary)]"
+ >
+ {label}
+ {active ? (
+ sortDir === "asc" ? (
+ <ArrowUp className="h-3 w-3" />
+ ) : (
+ <ArrowDown className="h-3 w-3" />
+ )
+ ) : (
+ // Reserve the arrow slot so the label doesn't shift when it activates.
+ <span className="inline-block h-3 w-3" />
+ )}
+ </button>
+ );
+}
+
// Column-priority hide classes, mirroring the shared ResponsiveTable scale:
// priority 2 hides below md (768px), priority 3 hides below lg (1024px). The
// "pair" identity column (priority 1) is always visible.
@@ -29,30 +91,85 @@ const HIDE_BELOW_LG = "max-lg:hidden";
/**
* The precise, sortable companion to the coupling diagram: one row per
- * coupling, strongest first. Clicking a row focuses that file in the ring;
- * rows touching the focused file are emphasized.
+ * coupling. Clicking a row pins its source file in the ring; the two file
+ * names are links to their detail pages, and hovering a row (or a name) peeks
+ * that file's couplings in the diagram. Rows touching the focused file are
+ * emphasized.
*
* The body is virtualized (windowed `<tbody>`) so long coupling lists stay
* cheap to render; below the wrapper's threshold every row renders, so the
* common short list behaves exactly as a plain table.
*/
-export function CouplingTable({ edges, focusedPath, onFocusChange, onGeneratePrompt }: CouplingTableProps) {
+export function CouplingTable({
+ edges,
+ focusedPath,
+ pinnedPath,
+ onHover,
+ onPinToggle,
+ onGeneratePrompt,
+ linkForPath,
+ LinkComponent,
+}: CouplingTableProps) {
+ const [sortKey, setSortKey] = useState<SortKey>("strength");
+ const [sortDir, setSortDir] = useState<SortDir>("desc");
+
// The strength bars are normalized to the strongest coupling; recompute only
// when the edge list changes rather than on every render.
const maxStrength = useMemo(() => Math.max(...edges.map((e) => e.strength), 1), [edges]);
+ const sorted = useMemo(() => {
+ const dir = sortDir === "asc" ? 1 : -1;
+ const val = (e: CouplingEdge) =>
+ sortKey === "strength" ? e.strength : e.last_co_change ? Date.parse(e.last_co_change) : 0;
+ // Copy before sorting: never mutate the caller's edge array in place.
+ return [...edges].sort((a, b) => (val(a) - val(b)) * dir);
+ }, [edges, sortKey, sortDir]);
+
+ const toggleSort = (key: SortKey) => {
+ if (key === sortKey) {
+ setSortDir((d) => (d === "asc" ? "desc" : "asc"));
+ } else {
+ setSortKey(key);
+ setSortDir("desc");
+ }
+ };
+
const incident = (e: CouplingEdge) =>
focusedPath != null && (e.source === focusedPath || e.target === focusedPath);
+ const Anchor: LinkLike = LinkComponent ?? "a";
+
const fileCell = (path: string, e: CouplingEdge, prefix = "") => {
const hot = incident(e) && path === focusedPath;
+ const cls = cn(
+ "block truncate font-mono text-xs",
+ hot
+ ? "text-[var(--color-text-primary)] font-medium"
+ : "text-[var(--color-text-secondary)]",
+ );
+ if (linkForPath) {
+ // Handlers ride on the wrapper (not the injected Link): navigate without
+ // toggling the row's pin, and peek this exact file (source or target) in
+ // the ring on hover.
+ return (
+ <span
+ className="block min-w-0"
+ title={path}
+ onClick={(ev) => ev.stopPropagation()}
+ onMouseEnter={() => onHover?.(path)}
+ >
+ <Anchor
+ href={linkForPath(path)}
+ className={cn(cls, "hover:text-[var(--color-accent-primary)] hover:underline")}
+ >
+ {prefix}
+ {basename(path)}
+ </Anchor>
+ </span>
+ );
+ }
return (
- <span
- className={`block truncate font-mono text-xs ${
- hot ? "text-[var(--color-text-primary)] font-medium" : "text-[var(--color-text-secondary)]"
- }`}
- title={path}
- >
+ <span className={cls} title={path}>
{prefix}
{basename(path)}
</span>
@@ -74,14 +191,30 @@ export function CouplingTable({ edges, focusedPath, onFocusChange, onGeneratePro
Coupled files
</th>
<th className={`px-3 py-2 text-left font-medium whitespace-nowrap w-36 ${HIDE_BELOW_MD}`}>
- <span
- title="Recency-weighted count of commits that touched both files. Higher means more or more-recent shared changes. It is not a percentage or a verified dependency."
- className="cursor-help underline decoration-dotted underline-offset-2"
- >
- Strength
- </span>
+ <SortHeader
+ columnKey="strength"
+ sortKey={sortKey}
+ sortDir={sortDir}
+ onToggle={toggleSort}
+ label={
+ <span
+ title="Recency-weighted count of commits that touched both files. Higher means more or more-recent shared changes. It is not a percentage or a verified dependency."
+ className="cursor-help underline decoration-dotted underline-offset-2"
+ >
+ Strength
+ </span>
+ }
+ />
+ </th>
+ <th className={`px-3 py-2 text-left font-medium whitespace-nowrap ${HIDE_BELOW_LG}`}>
+ <SortHeader
+ columnKey="last"
+ sortKey={sortKey}
+ sortDir={sortDir}
+ onToggle={toggleSort}
+ label="Last"
+ />
</th>
- <th className={`px-3 py-2 text-left font-medium whitespace-nowrap ${HIDE_BELOW_LG}`}>Last</th>
{onGeneratePrompt ? (
<th className={`px-3 py-2 text-left font-medium whitespace-nowrap w-10 ${HIDE_BELOW_LG}`} />
) : null}
@@ -89,10 +222,10 @@ export function CouplingTable({ edges, focusedPath, onFocusChange, onGeneratePro
);
const renderRow = (e: CouplingEdge) => {
- const onClick = onFocusChange
- ? () => onFocusChange(focusedPath === e.source ? null : e.source)
+ const onClick = onPinToggle
+ ? () => onPinToggle(pinnedPath === e.source ? null : e.source)
: undefined;
- const isSelected = focusedPath != null && focusedPath === e.source;
+ const isSelected = pinnedPath != null && pinnedPath === e.source;
return (
<tr
className={cn(
@@ -100,6 +233,7 @@ export function CouplingTable({ edges, focusedPath, onFocusChange, onGeneratePro
isSelected && "bg-[var(--color-accent-muted)]/30",
onClick && CLICKABLE_ROW_CLS,
)}
+ onMouseEnter={onHover ? () => onHover(e.source) : undefined}
{...(onClick ? clickableRowProps(onClick) : {})}
>
<td className="px-3 py-2 text-left min-w-[200px]">
@@ -140,12 +274,14 @@ export function CouplingTable({ edges, focusedPath, onFocusChange, onGeneratePro
};
return (
- <VirtualizedTable<CouplingEdge>
- rows={edges}
- rowKey={(e) => `${e.source}|${e.target}`}
- header={header}
- renderRow={renderRow}
- aria-label="Change-coupling pairs"
- />
+ <div onMouseLeave={onHover ? () => onHover(null) : undefined}>
+ <VirtualizedTable<CouplingEdge>
+ rows={sorted}
+ rowKey={(e) => `${e.source}|${e.target}`}
+ header={header}
+ renderRow={renderRow}
+ aria-label="Change-coupling pairs"
+ />
+ </div>
);
}
diff --git a/packages/ui/src/coupling/index.ts b/packages/ui/src/coupling/index.ts
index 16c2707ba..a8bcf9116 100644
--- a/packages/ui/src/coupling/index.ts
+++ b/packages/ui/src/coupling/index.ts
@@ -1,5 +1,6 @@
export { CouplingGraph, type CouplingGraphProps } from "./coupling-graph";
export { CouplingTable } from "./coupling-table";
+export { CouplingExplorer, type CouplingExplorerProps } from "./coupling-explorer";
/**
* The single canonical disclaimer for every change-coupling surface. Co-change
diff --git a/packages/ui/src/dashboard/coupling-mini-card.tsx b/packages/ui/src/dashboard/coupling-mini-card.tsx
new file mode 100644
index 000000000..1b82aa5da
--- /dev/null
+++ b/packages/ui/src/dashboard/coupling-mini-card.tsx
@@ -0,0 +1,89 @@
+"use client";
+
+import * as React from "react";
+import { ArrowRight, GitMerge } from "lucide-react";
+import { Card } from "../ui/card";
+import type { CouplingEdge } from "@repowise-dev/types/coupling";
+
+/** Injected link component (e.g. Next's Link); defaults to a plain anchor. */
+type LinkLike = React.ElementType<{
+ href: string;
+ className?: string;
+ children: React.ReactNode;
+}>;
+
+export interface CouplingMiniCardProps {
+ /** Top couplings (already ranked strongest-first, small N). */
+ edges: CouplingEdge[];
+ /** Link to the full change-coupling view. */
+ href: string;
+ /** Link component (defaults to a plain anchor). */
+ LinkComponent?: LinkLike;
+}
+
+function basename(path: string): string {
+ return path.split("/").pop() ?? path;
+}
+
+/**
+ * Overview front-door for the change-coupling view. The full diagram lives as
+ * an Architecture tab (off the sidebar), so this card gives it a landing-page
+ * presence and previews the strongest few file pairs that tend to change
+ * together — enough to make the hidden page discoverable and worth a click.
+ *
+ * Fully presentational: the host fetches the top edges and passes them in.
+ */
+export function CouplingMiniCard({ edges, href, LinkComponent }: CouplingMiniCardProps) {
+ const Link: LinkLike = LinkComponent ?? "a";
+ const top = edges.slice(0, 3);
+ const maxStrength = Math.max(...top.map((e) => e.strength), 1);
+
+ return (
+ <Card className="overflow-hidden">
+ <Link
+ href={href}
+ className="group block h-full p-4 transition-colors hover:bg-[var(--color-bg-elevated)]"
+ >
+ <div className="flex items-center justify-between">
+ <span className="flex items-center gap-2 text-sm font-semibold text-[var(--color-text-primary)]">
+ <GitMerge className="h-4 w-4 text-[var(--color-accent-primary)]" />
+ Change coupling
+ </span>
+ <ArrowRight className="h-4 w-4 text-[var(--color-text-tertiary)] transition-transform group-hover:translate-x-0.5" />
+ </div>
+
+ {top.length > 0 ? (
+ <ul className="mt-3 space-y-2">
+ {top.map((e) => (
+ <li key={`${e.source}|${e.target}`} className="space-y-1">
+ <div
+ className="truncate font-mono text-xs text-[var(--color-text-secondary)]"
+ title={`${e.source} ↔ ${e.target}`}
+ >
+ {basename(e.source)}
+ <span className="text-[var(--color-text-tertiary)]"> ↔ </span>
+ {basename(e.target)}
+ </div>
+ <div className="h-1 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">
+ <div
+ className="h-full rounded-full bg-[var(--color-accent-primary)]"
+ style={{ width: `${Math.max(8, Math.round((e.strength / maxStrength) * 100))}%` }}
+ />
+ </div>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="mt-3 text-sm text-[var(--color-text-secondary)]">
+ Files that tend to change together, drawn from git history. A hint at
+ hidden relationships the imports don't show.
+ </p>
+ )}
+
+ <p className="mt-3 text-xs font-medium text-[var(--color-accent-primary)]">
+ {top.length > 0 ? "See the coupling map" : "Explore coupling"}
+ </p>
+ </Link>
+ </Card>
+ );
+}
diff --git a/packages/ui/src/dashboard/index.ts b/packages/ui/src/dashboard/index.ts
index 9a26649e1..6b9c4da1c 100644
--- a/packages/ui/src/dashboard/index.ts
+++ b/packages/ui/src/dashboard/index.ts
@@ -18,3 +18,4 @@ export * from "./active-job-banner";
export * from "./quick-actions";
export * from "./community-summary-grid";
export * from "./explore-cards";
+export * from "./coupling-mini-card";
diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsx
index d35816b8a..cd9df463b 100644
--- a/packages/web/src/app/repos/[id]/overview/page.tsx
+++ b/packages/web/src/app/repos/[id]/overview/page.tsx
@@ -5,6 +5,7 @@ import Link from "next/link";
import { getOverviewSummary } from "@/lib/api/overview";
import { getProviders } from "@/lib/api/providers";
import { getStatsHighlights } from "@/lib/api/stats";
+import { getCoupling } from "@/lib/api/coupling";
import { StatsTeaserCard } from "@/components/overview/stats-teaser-card";
import { Badge } from "@repowise-dev/ui/ui/badge";
import { PageShell } from "@repowise-dev/ui/shared";
@@ -17,6 +18,7 @@ import { SavingsMini } from "@repowise-dev/ui/dashboard/savings-mini";
import { IndexStorageMini } from "@repowise-dev/ui/dashboard/index-storage-mini";
import { LanguageDonut } from "@repowise-dev/ui/dashboard/language-donut";
import { KnowledgeGraphCard } from "@repowise-dev/ui/dashboard/explore-cards";
+import { CouplingMiniCard } from "@repowise-dev/ui/dashboard/coupling-mini-card";
import { AskAnythingCardWrapper } from "@/components/overview/ask-anything-card-wrapper";
import { QuickActionsWrapper as QuickActions } from "@/components/dashboard/quick-actions-wrapper";
import { OverviewTabs } from "@/components/overview/overview-tabs";
@@ -40,10 +42,11 @@ async function safeFetch<T>(fn: () => Promise<T>): Promise<T | null> {
export default async function OverviewPage({ params }: Props) {
const { id } = await params;
- const [summary, providers, statsHighlights] = await Promise.all([
+ const [summary, providers, statsHighlights, coupling] = await Promise.all([
safeFetch(() => getOverviewSummary(id)),
safeFetch(() => getProviders()),
safeFetch(() => getStatsHighlights(id)),
+ safeFetch(() => getCoupling(id, { limit: 3 })),
]);
if (!summary) notFound();
@@ -193,8 +196,10 @@ export default async function OverviewPage({ params }: Props) {
decisions={summary.recent_decisions}
/>
- {/* ── Languages + explore: donut alongside the graph and chat front-doors ── */}
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
+ {/* ── Languages + explore: donut alongside the graph, coupling, and
+ chat front-doors. Coupling has no sidebar entry, so this card is
+ its discoverable landing-page door. ── */}
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
{summary.languages.length > 0 && (
<LanguageDonut
distribution={langDistribution}
@@ -202,6 +207,11 @@ export default async function OverviewPage({ params }: Props) {
/>
)}
<KnowledgeGraphCard href={`/repos/${id}/knowledge-graph`} />
+ <CouplingMiniCard
+ edges={coupling?.edges ?? []}
+ href={`/repos/${id}/architecture?view=coupling`}
+ LinkComponent={Link}
+ />
<AskAnythingCardWrapper repoId={id} />
</div>
</>
diff --git a/packages/web/src/components/coupling/coupling-tab.tsx b/packages/web/src/components/coupling/coupling-tab.tsx
index d69de53da..a860f9c07 100644
--- a/packages/web/src/components/coupling/coupling-tab.tsx
+++ b/packages/web/src/components/coupling/coupling-tab.tsx
@@ -1,17 +1,21 @@
"use client";
import useSWR from "swr";
+import Link from "next/link";
+import { useQueryState } from "nuqs";
import { ApiError } from "@repowise-dev/ui/shared/api-error";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+import { CouplingExplorer } from "@repowise-dev/ui/coupling";
import { getCoupling } from "@/lib/api/coupling";
-import { CouplingView } from "@/components/coupling/coupling-view";
import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
/**
* Self-fetching host for the change-coupling Architecture tab. The Architecture
* page is a client component, so coupling data is fetched here via SWR (mirrors
- * how the impact analyzer self-fetches) rather than on the server. The diagram
- * and table stay in `@repowise-dev/ui/coupling` so package bumps propagate them.
+ * how the impact analyzer self-fetches) rather than on the server. The whole
+ * diagram + table interaction lives in `@repowise-dev/ui/coupling` so package
+ * bumps propagate it to hosted; this host only supplies the repo link prefix,
+ * Next's Link, and `?focus=` URL sync for the pinned file.
*/
export function CouplingTab({ repoId }: { repoId: string }) {
const { data, error, isLoading, mutate } = useSWR(
@@ -19,6 +23,7 @@ export function CouplingTab({ repoId }: { repoId: string }) {
() => getCoupling(repoId, { limit: 200 }),
{ revalidateOnFocus: false },
);
+ const [focus, setFocus] = useQueryState("focus");
return (
<div className="space-y-6">
@@ -38,7 +43,14 @@ export function CouplingTab({ repoId }: { repoId: string }) {
</div>
</div>
) : (
- <CouplingView data={data} />
+ <CouplingExplorer
+ data={data}
+ repoLinkPrefix={`/repos/${repoId}`}
+ LinkComponent={Link}
+ // Absent `?focus=` → let the explorer open on the most-coupled hub.
+ initialFocus={focus ?? undefined}
+ onFocusChange={(path) => void setFocus(path)}
+ />
)}
</div>
);
diff --git a/packages/web/src/components/coupling/coupling-view.tsx b/packages/web/src/components/coupling/coupling-view.tsx
deleted file mode 100644
index e082eefde..000000000
--- a/packages/web/src/components/coupling/coupling-view.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { CouplingGraph, CouplingTable } from "@repowise-dev/ui/coupling";
-import { GraphCanvasShell } from "@repowise-dev/ui/graph/graph-canvas-shell";
-import { AiPromptModal, buildCouplingAiPrompt } from "@repowise-dev/ui/health";
-import type { CouplingEdge, CouplingGraphResponse } from "@repowise-dev/types/coupling";
-
-interface CouplingViewProps {
- data: CouplingGraphResponse;
-}
-
-/**
- * Hosts the coupling diagram (centerpiece) and the precise ranked table below
- * it, sharing a single `focusedPath` so hovering the ring emphasizes the table
- * rows and clicking a row lifts the ring — one focus model across both.
- *
- * One airy column: an un-boxed diagram on the page background → thin divider →
- * borderless table. No card chrome, no in-diagram header (the surrounding tab
- * hint supplies the one-liner).
- */
-export function CouplingView({ data }: CouplingViewProps) {
- const [focusedPath, setFocusedPath] = useState<string | null>(null);
- const [promptEdge, setPromptEdge] = useState<CouplingEdge | null>(null);
-
- return (
- <div className="space-y-5">
- <GraphCanvasShell className="block h-auto">
- <div className="mx-auto w-full max-w-[820px]">
- <CouplingGraph
- nodes={data.nodes}
- edges={data.edges}
- totalEdges={data.total_edges}
- focusedPath={focusedPath}
- onFocusChange={setFocusedPath}
- />
- </div>
- </GraphCanvasShell>
-
- <div className="border-t border-[var(--color-border-default)] pt-4">
- <CouplingTable
- edges={data.edges}
- focusedPath={focusedPath}
- onFocusChange={setFocusedPath}
- onGeneratePrompt={setPromptEdge}
- />
- </div>
-
- <AiPromptModal
- open={promptEdge !== null}
- onOpenChange={(o) => !o && setPromptEdge(null)}
- getPrompt={
- promptEdge
- ? (flavor) => buildCouplingAiPrompt({ edge: promptEdge, flavor })
- : null
- }
- filePath={promptEdge ? `${promptEdge.source} ↔ ${promptEdge.target}` : null}
- title="AI decouple prompt"
- description="A ready-to-paste prompt that has your AI agent diagnose why these two files change together and propose how to decouple them."
- />
- </div>
- );
-}