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(ui): focus a service and list every route between two (#4624)

Raghav Chamadiya8918e27dc99a
diff --git a/packages/ui/__tests__/workspace/system-map-activate.test.ts b/packages/ui/__tests__/workspace/system-map-activate.test.ts
new file mode 100644
index 000000000..030930362
--- /dev/null
+++ b/packages/ui/__tests__/workspace/system-map-activate.test.ts
@@ -0,0 +1,44 @@
+import { describe, it, expect } from "vitest";
+import { activateEdge, activateNode } from "../../src/workspace/system-map/activate";
+import type { DrawnNode } from "../../src/workspace/system-map/level-types";
+
+const service: DrawnNode = { type: "service", id: "callers:web", serviceId: "web", parentId: null, column: "callers" };
+const group: DrawnNode = {
+ type: "group",
+ id: "group:tag:a",
+ groupId: "tag:a",
+ label: "A",
+ source: "tag",
+ open: false,
+ serviceIds: ["x", "y"],
+ repoCount: 2,
+ linksIn: 0,
+ linksOut: 0,
+ linksInside: 0,
+};
+
+describe("activateNode", () => {
+ it("selects a service on a single click", () => {
+ expect(activateNode(service, "click")).toEqual({ kind: "select", selection: { type: "node", id: "web" } });
+ });
+
+ it("focuses a service on a double-click or Enter, by its service id", () => {
+ expect(activateNode(service, "double")).toEqual({ kind: "focus", serviceId: "web" });
+ expect(activateNode(service, "key")).toEqual({ kind: "focus", serviceId: "web" });
+ });
+
+ it("still opens a closed group on a double-click and selects it on a click", () => {
+ expect(activateNode(group, "double")).toEqual({ kind: "open", id: "tag:a" });
+ expect(activateNode(group, "click")).toEqual({ kind: "select", selection: { type: "group", id: "tag:a" } });
+ });
+
+ it("does nothing for an unknown id", () => {
+ expect(activateNode(undefined, "key")).toBeNull();
+ expect(activateEdge(undefined)).toBeNull();
+ });
+
+ it("opens a closed tray on a click", () => {
+ const tray: DrawnNode = { type: "tray", id: "tray", open: false, serviceIds: ["z"] };
+ expect(activateNode(tray, "click")).toEqual({ kind: "open", id: "tray" });
+ });
+});
diff --git a/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts b/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts
index 4df75c54b..461323cc9 100644
--- a/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts
+++ b/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts
@@ -8,7 +8,6 @@ import {
buildServiceAiPrompt,
} from "../../src/workspace/system-map/system-map-ai-prompt";
import {
- edgeLinks,
edgeSentence,
serviceDiagnostics,
serviceResolver,
@@ -128,17 +127,6 @@ describe("system map model", () => {
expect(serviceDiagnostics(graph.diagnostics, "api", resolve).unusedProviders).toBe(1);
});
- it("joins an edge to the links it aggregates, consumer to provider", () => {
- const e = graph.edges[0]!;
- const links = edgeLinks(
- e,
- [link({}), link({ consumer_file: "server/r.py" }), link({ contract_type: "code" }), link({})],
- serviceResolver(graph),
- );
- // Wrong service, wrong type and a duplicate are all dropped.
- expect(links).toHaveLength(1);
- });
-
it("names the weight's unit and says the relationship as a sentence", () => {
expect(weightLabel({ kind: "http", weight: 180 })).toBe("180 endpoints called");
expect(weightLabel({ kind: "co_change", weight: 1 })).toBe("1 file pair changed together");
diff --git a/packages/ui/__tests__/workspace/system-map-routes.test.tsx b/packages/ui/__tests__/workspace/system-map-routes.test.tsx
new file mode 100644
index 000000000..7adc7dbd0
--- /dev/null
+++ b/packages/ui/__tests__/workspace/system-map-routes.test.tsx
@@ -0,0 +1,393 @@
+import { describe, it, expect, vi, beforeAll } from "vitest";
+import { render, screen, fireEvent, act, waitFor } from "@testing-library/react";
+import type {
+ ServiceLinkEntry,
+ ServiceLinksBetween,
+ SystemEdge,
+ SystemGraph,
+ SystemNode,
+} from "@repowise-dev/types";
+import { SystemMap } from "../../src/workspace/system-map/system-map";
+import { SystemMapRoutesPanel } from "../../src/workspace/system-map/system-map-routes-panel";
+import { SystemMapBetweenControl } from "../../src/workspace/system-map/system-map-between-control";
+import { servicesBetween } from "../../src/workspace/system-map/between";
+import { matchServices, pickerPath } from "../../src/workspace/system-map/between-picker";
+import { focusColumnLabels } from "../../src/workspace/system-map/focus-labels";
+import { focusColumns, placeFocusColumns } from "../../src/workspace/system-map/focus-columns";
+import { DRAW_BUDGET } from "../../src/workspace/system-map/draw-budget";
+import { DEFAULT_EDGE_FAMILIES, type EdgeFamily } from "../../src/workspace/system-map/edge-families";
+import { planRoutes, routesLede, hiddenRoutesSentence } from "../../src/workspace/system-map/routes-between";
+import { EDGE_FAMILY_COPY } from "../../src/workspace/system-map/edge-families";
+import { buildPairAiPrompt } from "../../src/workspace/system-map/system-map-pair-prompt";
+import { strategyNeedsCheck } from "../../src/workspace/link-provenance";
+import { ESTATE_VIEW } from "../../src/workspace/system-map/view-state";
+
+beforeAll(() => {
+ class RO {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ vi.stubGlobal("ResizeObserver", RO);
+});
+
+function node(id: string): SystemNode {
+ return {
+ id,
+ repo: id,
+ service_path: null,
+ name: id,
+ kind: "service",
+ provider_count: 0,
+ consumer_count: 0,
+ contract_types: [],
+ is_orphan_provider: false,
+ is_orphan_consumer: false,
+ is_isolated: false,
+ };
+}
+
+function edge(source: string, target: string, over: Partial<SystemEdge> = {}): SystemEdge {
+ return {
+ id: `${source}->${target}${over.kind ? `:${over.kind}` : ""}`,
+ source,
+ target,
+ kind: "http",
+ match_type: "exact",
+ confidence: 1,
+ weight: 1,
+ structural: true,
+ contract_refs: [],
+ ...over,
+ };
+}
+
+/** webapp calls ordering twice over HTTP and through an event; ordering pulls a package; hooks reaches catalog through webhooks. */
+const graph: SystemGraph = {
+ version: 1,
+ generated_at: "2026-10-24T00:00:00Z",
+ nodes: ["webapp", "ordering", "shared", "hooks", "webhooks", "catalog"].map(node),
+ edges: [
+ edge("webapp", "ordering", { weight: 2 }),
+ edge("webapp", "ordering", { kind: "event" }),
+ edge("ordering", "shared", { kind: "package" }),
+ edge("hooks", "webhooks"),
+ edge("webhooks", "catalog", { kind: "event" }),
+ ],
+};
+
+function httpRow(i: number, direction: ServiceLinkEntry["direction"] = "a_to_b", strategy = "exact_id"): ServiceLinkEntry {
+ return {
+ kind: "http",
+ direction,
+ evidence: "contract",
+ link: {
+ contract_id: `http::GET::/api/orders/${i}`,
+ contract_type: "http",
+ match_type: "exact",
+ strategy: strategy as never,
+ confidence: 1,
+ provider_repo: "ordering",
+ provider_file: "Apis/OrdersApi.cs",
+ provider_symbol: "Get",
+ consumer_repo: "webapp",
+ consumer_file: "Services/OrderingService.cs",
+ consumer_symbol: "Fetch",
+ provider_service: null,
+ consumer_service: null,
+ provider_symbol_id: null,
+ consumer_symbol_id: null,
+ },
+ };
+}
+
+/** A fake server: 60 HTTP rows, 1 event, 2 package rows, with `kind`, `q` and paging. */
+function fakeServer(over: { stale?: boolean } = {}) {
+ const all: ServiceLinkEntry[] = [
+ ...Array.from({ length: 60 }, (_, i) => httpRow(i, "a_to_b", i === 0 ? "unique_path" : "exact_id")),
+ { ...httpRow(99), kind: "event" },
+ ...[1, 2].map(
+ (i): ServiceLinkEntry => ({
+ kind: "package",
+ direction: "b_to_a",
+ evidence: "package",
+ package_dep: { source_repo: "ordering", source_manifest: "Ordering.csproj", target_repo: "webapp", target_package: `pkg${i}`, kind: "nuget" },
+ }),
+ ),
+ ];
+ return vi.fn(async (a: string, b: string, opts: { kind?: string; q?: string; limit?: number; offset?: number }): Promise<ServiceLinksBetween> => {
+ const filtered = all.filter((r) => !opts.q || JSON.stringify(r).includes(opts.q));
+ const totals = new Map<string, number>();
+ for (const r of filtered) totals.set(`${r.kind}|${r.direction}`, (totals.get(`${r.kind}|${r.direction}`) ?? 0) + 1);
+ const rows = filtered.filter((r) => !opts.kind || r.kind === opts.kind);
+ const offset = opts.offset ?? 0;
+ return {
+ a,
+ b,
+ ...(over.stale ? { stale_graph: true } : {}),
+ links: rows.slice(offset, offset + (opts.limit ?? 50)),
+ total: rows.length,
+ totals: [...totals].map(([k, count]) => {
+ const [kind, direction] = k.split("|") as [string, ServiceLinkEntry["direction"]];
+ return { kind, direction, count };
+ }),
+ };
+ });
+}
+
+const pair = servicesBetween(graph, "webapp", "ordering", { families: DEFAULT_EDGE_FAMILIES })!;
+
+describe("routes between: pure parts", () => {
+ it("keeps kinds in the active families and counts the hidden ones per family", () => {
+ const plan = planRoutes(
+ [
+ { kind: "event", direction: "a_to_b", count: 1 },
+ { kind: "http", direction: "a_to_b", count: 3 },
+ { kind: "http", direction: "b_to_a", count: 1 },
+ { kind: "package", direction: "b_to_a", count: 2 },
+ ],
+ DEFAULT_EDGE_FAMILIES,
+ );
+ expect(plan.sections.map((s) => [s.kind, s.total])).toEqual([["http", 4], ["event", 1]]);
+ expect(plan.sections[0]!.byDirection).toEqual({ a_to_b: 3, b_to_a: 1 });
+ expect(plan.shown).toBe(5);
+ expect(plan.hidden).toEqual([{ family: "build", rows: 2 }]);
+ expect(hiddenRoutesSentence(plan.hidden, EDGE_FAMILY_COPY)).toBe(
+ "Not listed, because the map hides their family: 2 Build rows (package dependencies).",
+ );
+ });
+
+ it("says each direction, or the paths through one service when there is no direct link", () => {
+ const name = (id: string) => id;
+ expect(routesLede(pair, name)).toEqual([
+ "webapp depends on ordering through 3 links (HTTP 2, Event 1).",
+ "Nothing in ordering depends on webapp.",
+ ]);
+ const indirect = servicesBetween(graph, "hooks", "catalog")!;
+ expect(routesLede(indirect, name)).toEqual([
+ "No direct link between hooks and catalog in the links shown.",
+ "hooks reaches catalog through webhooks (HTTP, then Event).",
+ ]);
+ const none = servicesBetween(graph, "shared", "catalog")!;
+ expect(routesLede(none, name)[1]).toBe("No path joins them through one other service either.");
+ });
+
+ it("names only the strategies a reader should check", () => {
+ expect(strategyNeedsCheck("unique_path")).toBe(true);
+ expect(strategyNeedsCheck("prefix_stripped")).toBe(true);
+ expect(strategyNeedsCheck("exact_id")).toBe(false);
+ expect(strategyNeedsCheck(null)).toBe(false);
+ });
+
+ it("builds a pair prompt from the loaded rows and says what was not loaded", () => {
+ const text = buildPairAiPrompt({
+ a: { id: "webapp", name: "webapp" },
+ b: { id: "ordering", name: "ordering" },
+ facts: ["webapp depends on ordering through 3 links (HTTP 2, Event 1)."],
+ rows: [httpRow(1)],
+ total: 4,
+ });
+ expect(text).toContain("## Contract between webapp (`webapp`) and ordering (`ordering`)");
+ expect(text).toContain("`http::GET::/api/orders/1`: consumer `webapp:Services/OrderingService.cs`");
+ expect(text).toContain("3 more routes exist that were not loaded here.");
+ });
+});
+
+describe("SystemMapRoutesPanel", () => {
+ const base = { graph, between: pair, families: DEFAULT_EDGE_FAMILIES, onClose: () => {} };
+
+ it("lists kinds in the active families, paged per kind, and loads more", async () => {
+ const load = fakeServer();
+ render(<SystemMapRoutesPanel {...base} loadLinksBetween={load} contractHref={(r) => `/c?id=${r.contract_id}`} />);
+ expect(await screen.findByText("HTTP · 60")).toBeInTheDocument();
+ expect(await screen.findByText("Showing 50 of 60 routes")).toBeInTheDocument();
+ expect(screen.getByText("Event · 1")).toBeInTheDocument();
+ // Package is in Build, which the map hides: counted, offered, not listed.
+ expect(screen.queryByText(/Package ·/)).toBeNull();
+ expect(screen.getByText(/2 Build rows \(package dependencies\)/)).toBeInTheDocument();
+ // Strategy named only where it needs checking.
+ expect(screen.getAllByText("Matched by path only")).toHaveLength(1);
+ expect(screen.queryByText("Matched by exact name")).toBeNull();
+ expect(screen.getByRole("link", { name: "http::GET::/api/orders/1" })).toHaveAttribute("href", "/c?id=http::GET::/api/orders/1");
+
+ fireEvent.click(screen.getByRole("button", { name: "Load more" }));
+ await waitFor(() => expect(screen.queryByText(/Showing 50 of 60/)).toBeNull());
+ expect(screen.getAllByRole("link", { name: /http::GET::\/api\/orders\// })).toHaveLength(61); // 60 HTTP rows and the event row
+ expect(load).toHaveBeenCalledWith("webapp", "ordering", expect.objectContaining({ kind: "http", offset: 50, limit: 50 }));
+ // No row request for the hidden family.
+ expect(load.mock.calls.some(([, , o]) => o.kind === "package")).toBe(false);
+ });
+
+ it("offers to show a hidden family", async () => {
+ const onShowFamily = vi.fn();
+ render(<SystemMapRoutesPanel {...base} loadLinksBetween={fakeServer()} onShowFamily={onShowFamily} />);
+ fireEvent.click(await screen.findByRole("button", { name: "Show Build" }));
+ expect(onShowFamily).toHaveBeenCalledWith("build" satisfies EdgeFamily);
+ });
+
+ it("passes the filter to the server and says when nothing matches", async () => {
+ const load = fakeServer();
+ render(<SystemMapRoutesPanel {...base} loadLinksBetween={load} />);
+ await screen.findByText("HTTP · 60");
+ fireEvent.change(screen.getByRole("searchbox", { name: "Filter routes" }), { target: { value: "orders/7" } });
+ expect(await screen.findByText("HTTP · 1")).toBeInTheDocument();
+ fireEvent.change(screen.getByRole("searchbox", { name: "Filter routes" }), { target: { value: "nothing-here" } });
+ expect(await screen.findByText('No routes match "nothing-here".')).toBeInTheDocument();
+ expect(load).toHaveBeenCalledWith("webapp", "ordering", expect.objectContaining({ q: "orders/7" }));
+ });
+
+ it("states a stale graph quietly, and an unavailable loader", async () => {
+ const { unmount } = render(<SystemMapRoutesPanel {...base} loadLinksBetween={fakeServer({ stale: true })} />);
+ expect(await screen.findByRole("note")).toHaveTextContent(/read at different commits/);
+ unmount();
+ render(<SystemMapRoutesPanel {...base} />);
+ expect(screen.getByText("Route detail is not available here.")).toBeInTheDocument();
+ });
+
+ it("drops a reply for an earlier filter, and retries a page that failed", async () => {
+ const real = fakeServer();
+ let failNext = true;
+ let releaseStale: (() => void) | null = null;
+ const load = vi.fn(async (a: string, b: string, opts: { kind?: string; q?: string; limit?: number; offset?: number }) => {
+ // The first unfiltered HTTP page is held back until a filter has landed, then answers for the old query.
+ if (opts.kind === "http" && !opts.q && releaseStale === null) {
+ await new Promise<void>((resolve) => (releaseStale = resolve));
+ return real(a, b, opts);
+ }
+ if (opts.kind === "event" && failNext) {
+ failNext = false;
+ throw new Error("down");
+ }
+ return real(a, b, opts);
+ });
+ render(<SystemMapRoutesPanel {...base} loadLinksBetween={load} />);
+ expect(await screen.findByText("This page of routes could not be loaded.")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));
+ expect(await screen.findByText("http::GET::/api/orders/99")).toBeInTheDocument();
+ fireEvent.change(screen.getByRole("searchbox", { name: "Filter routes" }), { target: { value: "orders/7" } });
+ expect(await screen.findByText("HTTP · 1")).toBeInTheDocument();
+ await act(async () => releaseStale?.());
+ // The stale unfiltered page never replaces the filtered rows.
+ expect(screen.queryByText("Showing 50 of 60 routes")).toBeNull();
+ expect(screen.getAllByText(/http::GET::\/api\/orders\/7/).length).toBeGreaterThan(0);
+ });
+
+ it("says when the pair has no routes in the families shown", async () => {
+ const empty = vi.fn(async (a: string, b: string): Promise<ServiceLinksBetween> => ({ a, b, links: [], total: 0, totals: [] }));
+ render(<SystemMapRoutesPanel {...base} loadLinksBetween={empty} />);
+ expect(await screen.findByText("No routes between webapp and ordering in the families shown.")).toBeInTheDocument();
+ });
+});
+
+describe("focus level", () => {
+ it("heads each column with its title and count", () => {
+ const layout = focusColumns(graph, "ordering", { families: new Set(["runtime", "data", "build"]), budget: DRAW_BUDGET })!;
+ const positions = placeFocusColumns(layout, { size: { width: 208, height: 96 } });
+ const labels = focusColumnLabels(layout, positions);
+ expect(labels.map((l) => l.label)).toEqual(["Called by · 1", "Depends on · 1"]);
+ const first = positions.get("callers:webapp")!;
+ expect(labels[0]).toMatchObject({ x: first.x, y: first.y - 28 });
+ });
+
+ it("renders three columns, card links in words, and Escape returns to the estate", async () => {
+ const onViewChange = vi.fn();
+ const { container } = render(
+ <SystemMap graph={graph} view={{ ...ESTATE_VIEW, focus: "ordering" }} onViewChange={onViewChange} />,
+ );
+ expect(await screen.findByText("Called by · 1")).toBeInTheDocument();
+ expect(screen.queryByText(/Depends on/)).toBeNull(); // the package link is in a hidden family
+ expect(await screen.findByText("3 · HTTP 2, Event 1")).toBeInTheDocument();
+ // Columns read left to right, so every focus card joins its connectors at its sides.
+ for (const id of ["callers:webapp", "ordering"]) {
+ const card = container.querySelector(`.react-flow__node[data-id="${id}"]`)!;
+ expect(card.querySelector(".react-flow__handle-left")).not.toBeNull();
+ expect(card.querySelector(".react-flow__handle-right")).not.toBeNull();
+ expect(card.querySelector(".react-flow__handle-top")).toBeNull();
+ }
+ await act(async () => {
+ fireEvent.keyDown(container.querySelector(".react-flow")!, { key: "Escape" });
+ });
+ expect(onViewChange).toHaveBeenCalledWith(expect.objectContaining({ focus: null }));
+ });
+
+ it("focuses a service on double-click", async () => {
+ const onViewChange = vi.fn();
+ const { container } = render(<SystemMap graph={graph} view={ESTATE_VIEW} onViewChange={onViewChange} />);
+ const card = await vi.waitFor(() => {
+ const el = container.querySelector('.react-flow__node[data-id="webapp"]');
+ if (!el) throw new Error("not drawn yet");
+ return el;
+ });
+ // Off the focus level cards keep their top and bottom handles.
+ expect(card.querySelector(".react-flow__handle-top")).not.toBeNull();
+ fireEvent.doubleClick(card);
+ expect(onViewChange).toHaveBeenCalledWith(expect.objectContaining({ focus: "webapp" }));
+ });
+});
+
+describe("Between", () => {
+ it("suggests services by name and finds a route within two hops, either way", () => {
+ expect(matchServices(graph, "web", 5).map((r) => r.node_id)).toEqual(["webapp", "webhooks"]);
+ expect(matchServices(graph, "", 2).map((r) => r.node_id)).toEqual(["ordering", "webapp"]);
+ expect(pickerPath(graph, "hooks", "catalog", DEFAULT_EDGE_FAMILIES).path).toEqual(["hooks", "webhooks", "catalog"]);
+ expect(pickerPath(graph, "ordering", "webapp", DEFAULT_EDGE_FAMILIES).path).toEqual(["ordering", "webapp"]);
+ expect(pickerPath(graph, "shared", "catalog", DEFAULT_EDGE_FAMILIES).path).toEqual([]);
+ expect(() => pickerPath(graph, "nope", "catalog", DEFAULT_EDGE_FAMILIES)).toThrow();
+ });
+
+ it("opens the Between level from the picker", async () => {
+ const onBetween = vi.fn();
+ const onOpenChange = vi.fn();
+ render(
+ <SystemMapBetweenControl graph={graph} families={DEFAULT_EDGE_FAMILIES} open onOpenChange={onOpenChange} from="webapp" onBetween={onBetween} />,
+ );
+ fireEvent.change(screen.getByPlaceholderText("To service..."), { target: { value: "ordering" } });
+ fireEvent.click(screen.getByRole("button", { name: "Show routes" }));
+ await waitFor(() => expect(onBetween).toHaveBeenCalledWith("webapp", "ordering"));
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it("says when no route joins the pair", async () => {
+ const onBetween = vi.fn();
+ render(
+ <SystemMapBetweenControl graph={graph} families={DEFAULT_EDGE_FAMILIES} open onOpenChange={() => {}} from="shared" onBetween={onBetween} />,
+ );
+ fireEvent.change(screen.getByPlaceholderText("To service..."), { target: { value: "catalog" } });
+ fireEvent.click(screen.getByRole("button", { name: "Show routes" }));
+ expect(await screen.findByText(/No route joins these services within two hops/)).toBeInTheDocument();
+ expect(onBetween).not.toHaveBeenCalled();
+ });
+
+ it("shows the routes panel in the rail at the Between level, and the drawer's Focus verb", async () => {
+ const onViewChange = vi.fn();
+ render(
+ <SystemMap
+ graph={graph}
+ view={{ ...ESTATE_VIEW, between: { a: "webapp", b: "ordering" } }}
+ onViewChange={onViewChange}
+ loadLinksBetween={fakeServer()}
+ />,
+ );
+ expect(await screen.findByRole("region", { name: "webapp and ordering" })).toBeInTheDocument();
+ expect(await screen.findByText("HTTP · 60")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Close details" }));
+ expect(onViewChange).toHaveBeenCalledWith(expect.objectContaining({ between: null }));
+ });
+
+ it("lists an edge's routes in its drawer and offers all routes between the pair", async () => {
+ const onViewChange = vi.fn();
+ render(
+ <SystemMap
+ graph={graph}
+ selection={{ type: "edge", id: "webapp->ordering" }}
+ onSelectionChange={() => {}}
+ view={ESTATE_VIEW}
+ onViewChange={onViewChange}
+ loadLinksBetween={fakeServer()}
+ />,
+ );
+ expect(await screen.findByText("Showing 20 of 60 routes.")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "All routes between them" }));
+ expect(onViewChange).toHaveBeenCalledWith(expect.objectContaining({ between: { a: "webapp", b: "ordering" } }));
+ });
+});
diff --git a/packages/ui/__tests__/workspace/system-map.test.tsx b/packages/ui/__tests__/workspace/system-map.test.tsx
index 736da0691..1b0dff922 100644
--- a/packages/ui/__tests__/workspace/system-map.test.tsx
+++ b/packages/ui/__tests__/workspace/system-map.test.tsx
@@ -398,11 +398,10 @@ describe("selectionRepo", () => {
[node("api::svc/a", { repo: "api", service_path: "svc/a" }), node("web")],
[edge("web", "api::svc/a")],
);
- it("names the repository a node or edge lives in, and none for an aggregate", () => {
+ it("names a service's repository, and none for a relationship (its routes come from the loader) or an aggregate", () => {
expect(selectionRepo(g, { type: "node", id: "api::svc/a" })).toBe("api");
expect(selectionRepo(g, { type: "group", id: "tag:api" })).toBeNull();
- expect(selectionRepo(g, { type: "edge", id: "web->api::svc/a" })).toBe("web");
- expect(selectionRepo(g, { type: "edge", id: "web->api::http" })).toBe("web");
+ expect(selectionRepo(g, { type: "edge", id: "web->api::svc/a" })).toBeNull();
expect(selectionRepo(g, null)).toBeNull();
});
});
diff --git a/packages/ui/src/graph/path-finder-panel.tsx b/packages/ui/src/graph/path-finder-panel.tsx
index 765b498f9..065df360d 100644
--- a/packages/ui/src/graph/path-finder-panel.tsx
+++ b/packages/ui/src/graph/path-finder-panel.tsx
@@ -10,6 +10,29 @@ import { FilePath } from "../shared/file-path";
import { isFileNodeId } from "./node-id";
import type { GraphPath, NodeSearchResult } from "@repowise-dev/types/graph";
+/** The panel's words; the defaults name files, a host searching other nodes (services) names those. */
+export interface PathFinderCopy {
+ title: string;
+ fromPlaceholder: string;
+ toPlaceholder: string;
+ /** Heading over the suggestions shown before anything is typed. */
+ topHeading: string;
+ submit: string;
+ noPath: string;
+}
+
+const DEFAULT_COPY: PathFinderCopy = {
+ title: "Find Path",
+ fromPlaceholder: "From file...",
+ toPlaceholder: "To file...",
+ topHeading: "Top files by importance",
+ submit: "Find Path",
+ noPath: "No path found between these nodes.",
+};
+
+/** How a suggestion reads: a label and a short detail on the right. */
+export type PathFinderOptionDescriber = (r: NodeSearchResult) => { label: string; detail: string };
+
export interface PathFinderPanelProps {
/** Inject the autocomplete searcher. Returns the top-N nodes for a query. */
searchNodes: (query: string, limit: number) => Promise<NodeSearchResult[]>;
@@ -24,6 +47,10 @@ export interface PathFinderPanelProps {
/** Pre-fill values driven by the parent's context-menu. */
initialFrom?: string;
initialTo?: string;
+ /** Override any of the panel's words. */
+ copy?: Partial<PathFinderCopy>;
+ /** Label suggestions yourself; by default a file path and its language. */
+ describeOption?: PathFinderOptionDescriber;
}
interface NodeAutocompleteProps {
@@ -31,6 +58,8 @@ interface NodeAutocompleteProps {
value: string;
onChange: (v: string) => void;
placeholder: string;
+ topHeading: string;
+ describeOption?: PathFinderOptionDescriber | undefined;
onSubmit?: () => void;
}
@@ -39,6 +68,8 @@ function NodeAutocomplete({
value,
onChange,
placeholder,
+ topHeading,
+ describeOption,
onSubmit,
}: NodeAutocompleteProps) {
const [results, setResults] = useState<NodeSearchResult[]>([]);
@@ -103,25 +134,32 @@ function NodeAutocomplete({
<div className="absolute top-full left-0 mt-1 w-full max-h-52 overflow-auto z-[var(--z-dropdown)] rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-xl shadow-black/30 py-1">
{results.length === 0 && topNodes.length > 0 && (
<div className="px-3 py-1 text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider">
- Top files by importance
+ {topHeading}
</div>
)}
- {displayResults.map((r) => (
- <button
- key={r.node_id}
- className="w-full px-3 py-1.5 text-left text-xs hover:bg-[var(--color-bg-elevated)] transition-colors flex items-center gap-2"
- onMouseDown={() => handleSelect(r.node_id)}
- >
- {isFileNodeId(r.node_id) ? (
- <FilePath path={r.node_id} fold className="flex-1 text-[var(--color-text-primary)]" />
- ) : (
- <span className="flex-1 truncate font-mono text-[var(--color-text-primary)]">{r.node_id}</span>
- )}
- <span className="text-[10px] text-[var(--color-text-tertiary)] capitalize shrink-0 tabular-nums">
- {r.language}
- </span>
- </button>
- ))}
+ {displayResults.map((r) => {
+ const described = describeOption?.(r);
+ return (
+ <button
+ key={r.node_id}
+ className="w-full px-3 py-1.5 text-left text-xs hover:bg-[var(--color-bg-elevated)] transition-colors flex items-center gap-2"
+ onMouseDown={() => handleSelect(r.node_id)}
+ >
+ {described ? (
+ <span className="flex-1 truncate font-mono text-[var(--color-text-primary)]">{described.label}</span>
+ ) : isFileNodeId(r.node_id) ? (
+ <FilePath path={r.node_id} fold className="flex-1 text-[var(--color-text-primary)]" />
+ ) : (
+ <span className="flex-1 truncate font-mono text-[var(--color-text-primary)]">{r.node_id}</span>
+ )}
+ <span
+ className={`text-[10px] text-[var(--color-text-tertiary)] shrink-0 tabular-nums ${described ? "" : "capitalize"}`}
+ >
+ {described ? described.detail : r.language}
+ </span>
+ </button>
+ );
+ })}
</div>
)}
</div>
@@ -136,7 +174,10 @@ export function PathFinderPanel({
onClose,
initialFrom = "",
initialTo = "",
+ copy: copyOverrides,
+ describeOption,
}: PathFinderPanelProps) {
+ const copy = { ...DEFAULT_COPY, ...copyOverrides };
const [from, setFrom] = useState(initialFrom);
const [to, setTo] = useState(initialTo);
const [loading, setLoading] = useState(false);
@@ -164,14 +205,14 @@ export function PathFinderPanel({
if (res.path && res.path.length > 0) {
onPathFound(res.path);
} else {
- setError("No path found between these nodes.");
+ setError(copy.noPath);
}
} catch {
- setError("No path found between these nodes.");
+ setError(copy.noPath);
} finally {
setLoading(false);
}
- }, [from, to, findPath, onPathFound, onClear]);
+ }, [from, to, findPath, onPathFound, onClear, copy.noPath]);
const handleClear = useCallback(() => {
setFrom("");
@@ -187,7 +228,7 @@ export function PathFinderPanel({
<div className="flex items-center gap-2">
<Route className="w-3.5 h-3.5 text-[var(--color-accent-graph)]" />
<span className="text-xs font-semibold text-[var(--color-text-primary)]">
- Find Path
+ {copy.title}
</span>
<div className="ml-auto flex items-center gap-1">
{(result || error) && (
@@ -221,14 +262,18 @@ export function PathFinderPanel({
searchNodes={searchNodes}
value={from}
onChange={setFrom}
- placeholder="From file..."
+ placeholder={copy.fromPlaceholder}
+ topHeading={copy.topHeading}
+ describeOption={describeOption}
onSubmit={handleFind}
/>
<NodeAutocomplete
searchNodes={searchNodes}
value={to}
onChange={setTo}
- placeholder="To file..."
+ placeholder={copy.toPlaceholder}
+ topHeading={copy.topHeading}
+ describeOption={describeOption}
onSubmit={handleFind}
/>
</div>
@@ -249,7 +294,7 @@ export function PathFinderPanel({
) : (
<Route className="h-3.5 w-3.5" />
)}
- Find Path
+ {copy.submit}
</Button>
{/* Result */}
diff --git a/packages/ui/src/workspace/link-provenance.ts b/packages/ui/src/workspace/link-provenance.ts
index f8d678a77..ff49dd4cb 100644
--- a/packages/ui/src/workspace/link-provenance.ts
+++ b/packages/ui/src/workspace/link-provenance.ts
@@ -140,6 +140,23 @@ export function linkStrategyCopy(strategy: string | null | undefined): Provenanc
);
}
+/**
+ * Strategies a reader should check before relying on the link: the call's
+ * base URL was not read, or the paths matched only after loosening them.
+ * Route rows name only these, so the exception stands out and the stronger
+ * rules stay the quiet default.
+ */
+const WEAK_STRATEGIES: ReadonlySet<string> = new Set<LinkStrategy>([
+ "unique_path",
+ "ambiguous_path",
+ "prefix_stripped",
+ "host_only",
+]);
+
+export function strategyNeedsCheck(strategy: string | null | undefined): boolean {
+ return Boolean(strategy && WEAK_STRATEGIES.has(strategy));
+}
+
/** Describe a contract origin. Null only when the contract carries none. */
export function contractOriginCopy(origin: string | null | undefined): ProvenanceCopy | null {
if (!origin) return null;
diff --git a/packages/ui/src/workspace/system-map/activate.ts b/packages/ui/src/workspace/system-map/activate.ts
index 21a0bbf2f..6d2908fce 100644
--- a/packages/ui/src/workspace/system-map/activate.ts
+++ b/packages/ui/src/workspace/system-map/activate.ts
@@ -1,8 +1,9 @@
/**
* What a click, a double-click or Enter on a drawn card or connector does,
- * as data: select something, open a container, or list what a "+N more"
- * card folded. A single click selects; a double-click or Enter opens an
- * aggregate. Pure, no React.
+ * as data: select something, open a container, focus a service, or list
+ * what a "+N more" card folded. A single click selects; a double-click or
+ * Enter opens an aggregate or focuses a service (its callers and
+ * dependencies). Pure, no React.
*/
import type { DrawnEdge, DrawnNode } from "./level-types";
@@ -14,6 +15,7 @@ export type ActivateTrigger = "click" | "double" | "key";
export type Activation =
| { kind: "select"; selection: SystemMapSelection }
| { kind: "open"; id: string }
+ | { kind: "focus"; serviceId: string }
| { kind: "folded"; serviceIds: readonly string[] }
| null;
@@ -22,7 +24,9 @@ export function activateNode(n: DrawnNode | undefined, trigger: ActivateTrigger)
const opens = trigger !== "click";
switch (n.type) {
case "service":
- return { kind: "select", selection: { type: "node", id: n.serviceId } };
+ return opens
+ ? { kind: "focus", serviceId: n.serviceId }
+ : { kind: "select", selection: { type: "node", id: n.serviceId } };
case "group":
return opens && !n.open
? { kind: "open", id: n.groupId }
diff --git a/packages/ui/src/workspace/system-map/between-picker.ts b/packages/ui/src/workspace/system-map/between-picker.ts
new file mode 100644
index 000000000..c29d8983a
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/between-picker.ts
@@ -0,0 +1,71 @@
+/**
+ * What the Between picker needs from the loaded graph: service suggestions
+ * for a typed name, and whether two services are joined within two hops in
+ * the families shown (`servicesBetween`). Pure, no React, no I/O; the graph
+ * is already in the browser.
+ */
+
+import type { GraphPath, NodeSearchResult } from "@repowise-dev/types/graph";
+import { servicesBetween } from "./between";
+import type { EdgeFamily } from "./edge-families";
+import type { LevelsGraph } from "./level-types";
+
+function degrees(graph: LevelsGraph): Map<string, number> {
+ const out = new Map<string, number>();
+ for (const e of graph.edges) {
+ out.set(e.source, (out.get(e.source) ?? 0) + 1);
+ out.set(e.target, (out.get(e.target) ?? 0) + 1);
+ }
+ return out;
+}
+
+/**
+ * Services whose name or id contains every typed term (case-insensitive),
+ * names starting with the query first, then the most linked. An empty query
+ * lists the most linked services. `language` carries the repository, which
+ * the picker shows beside the name.
+ */
+export function matchServices(graph: LevelsGraph, query: string, limit: number): NodeSearchResult[] {
+ const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
+ const degree = degrees(graph);
+ const head = terms.join(" ");
+ return graph.nodes
+ .filter((n) => {
+ const hay = `${n.name} ${n.id}`.toLowerCase();
+ return terms.every((t) => hay.includes(t));
+ })
+ .map((n) => ({ n, prefix: head !== "" && n.name.toLowerCase().startsWith(head) ? 0 : 1, degree: degree.get(n.id) ?? 0 }))
+ .sort((x, y) => x.prefix - y.prefix || y.degree - x.degree || (x.n.id < y.n.id ? -1 : 1))
+ .slice(0, limit)
+ .map(({ n }) => ({ node_id: n.id, language: n.repo, symbol_count: 0 }));
+}
+
+/** A typed value as a service id: an id, else an exact name (case-insensitive). Null when it names none. */
+export function resolveService(graph: LevelsGraph, value: string): string | null {
+ const v = value.trim();
+ if (graph.nodes.some((n) => n.id === v)) return v;
+ const lower = v.toLowerCase();
+ return graph.nodes.find((n) => n.name.toLowerCase() === lower)?.id ?? null;
+}
+
+/**
+ * The shortest route between two services within two hops, either way, in
+ * the families shown, as the picker's path payload. An empty path when none
+ * joins them; it throws when either value names no service.
+ */
+export function pickerPath(
+ graph: LevelsGraph,
+ from: string,
+ to: string,
+ families: ReadonlySet<EdgeFamily>,
+): GraphPath {
+ const a = resolveService(graph, from);
+ const b = resolveService(graph, to);
+ if (!a || !b) throw new Error("Not a service in this map");
+ const between = servicesBetween(graph, a, b, { families, maxPaths: 1 });
+ const forward = between?.pathsAToB[0];
+ const backward = between?.pathsBToA[0];
+ // Keep the reader's order: a route b -> a still answers "between a and b".
+ const nodes = forward?.nodes ?? (backward ? [...backward.nodes].reverse() : []);
+ return { path: nodes, distance: Math.max(nodes.length - 1, 0), explanation: "" };
+}
diff --git a/packages/ui/src/workspace/system-map/flow-elements.ts b/packages/ui/src/workspace/system-map/flow-elements.ts
index aa7e3fcc6..3425adb9a 100644
--- a/packages/ui/src/workspace/system-map/flow-elements.ts
+++ b/packages/ui/src/workspace/system-map/flow-elements.ts
@@ -9,9 +9,10 @@
import { MarkerType, type Edge, type Node } from "@xyflow/react";
import type { NodeArchitectureRole, SystemEdge, SystemNode } from "@repowise-dev/types";
import type { C4LayoutPosition } from "../../c4/layout/elk-c4-layout";
-import { bandSentence, groupSourceLabel, healthCounts, type HealthCounts } from "./aggregate-facts";
+import { bandSentence, groupSourceLabel, healthCounts, kindMixText, type HealthCounts } from "./aggregate-facts";
import { roleStyle } from "./architecture";
import { edgeLabel } from "./edge-kinds";
+import { focusColumnLabels, type ColumnLabelData } from "./focus-labels";
import type {
DrawnBand,
DrawnGroupNode,
@@ -50,6 +51,8 @@ export interface TrayNodeData {
export interface MoreNodeData {
more: DrawnMoreNode;
+ /** In a focus column: connectors join its sides. */
+ horizontal?: boolean;
[key: string]: unknown;
}
@@ -112,15 +115,28 @@ export function drawnLabel(n: DrawnNode | undefined, nodesById: ReadonlyMap<stri
type Shaped = { type: string; data: Record<string, unknown> } | null;
-function serviceData(n: DrawnServiceNode, { nodesById, healthByRepo, overlay, roleByNodeId }: FlowInputs): Shaped {
+/** A focus-column card's links to its neighbour column: "8 · HTTP 2, Event 6", plus "both ways". */
+function focusLinksText(n: DrawnServiceNode): string | null {
+ if (!n.links) return null;
+ const mix = kindMixText(n.links.kinds);
+ const head = mix ? `${n.links.links.toLocaleString()} · ${mix}` : n.links.links.toLocaleString();
+ return n.bothWays ? `${head} · both ways` : head;
+}
+
+function serviceData(n: DrawnServiceNode, { view, nodesById, healthByRepo, overlay, roleByNodeId }: FlowInputs): Shaped {
const node = nodesById.get(n.serviceId);
if (!node) return null;
const role = roleByNodeId?.get(n.serviceId);
+ const pair = view.between;
const data: SystemMapNodeData = {
node,
health: healthByRepo?.get(node.repo) ?? null,
overlay: resolveNodeOverlay(overlay, n.serviceId),
role: role ? roleStyle(role.role).label : null,
+ // Focus columns read left to right, so their connectors join card sides.
+ horizontal: view.level === "focus",
+ focusLinks: focusLinksText(n),
+ endpoint: pair !== null && (n.serviceId === pair.a || n.serviceId === pair.b),
};
return { type: "systemService", data };
}
@@ -148,8 +164,8 @@ function trayData(n: DrawnTrayNode, { nodesById }: FlowInputs): Shaped {
return { type: "systemTray", data };
}
-function moreData(n: DrawnMoreNode): Shaped {
- const data: MoreNodeData = { more: n };
+function moreData(n: DrawnMoreNode, { view }: FlowInputs): Shaped {
+ const data: MoreNodeData = { more: n, horizontal: view.level === "focus" };
return { type: "systemMore", data };
}
@@ -162,7 +178,7 @@ function nodeData(n: DrawnNode, inputs: FlowInputs): Shaped {
case "tray":
return trayData(n, inputs);
default:
- return moreData(n);
+ return moreData(n, inputs);
}
}
@@ -235,5 +251,22 @@ export function toFlowElements(inputs: FlowInputs): FlowElements {
const flow = e.type === "edge" ? singleEdge(e, inputs, name) : bandEdge(e, inputs, name);
if (flow) edges.push(selectedId === e.id ? { ...flow, selected: true } : flow);
}
+ if (view.focus) nodes.push(...columnLabelNodes(view, positions));
return { nodes, edges };
}
+
+/** The focus level's column headings, as inert nodes above each column. */
+function columnLabelNodes(view: LevelView, positions: ReadonlyMap<string, C4LayoutPosition>): Node[] {
+ return focusColumnLabels(view.focus!, positions).map((l): Node => {
+ const data: ColumnLabelData = { label: l.label };
+ return {
+ id: l.id,
+ type: "systemColumnLabel",
+ position: { x: l.x, y: l.y },
+ data,
+ selectable: false,
+ focusable: false,
+ draggable: false,
+ };
+ });
+}
diff --git a/packages/ui/src/workspace/system-map/focus-labels.ts b/packages/ui/src/workspace/system-map/focus-labels.ts
new file mode 100644
index 000000000..7be697873
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/focus-labels.ts
@@ -0,0 +1,54 @@
+/**
+ * Headings for the focus level's columns ("Called by · 5", "Depends on · 3"),
+ * placed above each column's first card from the positions the column grid
+ * gave it. Pure, no React.
+ */
+
+import type { C4LayoutPosition } from "../../c4/layout/elk-c4-layout";
+import { focusMoreId, focusNodeId, type FocusLayout } from "./focus-columns";
+import type { FocusColumnId } from "./level-types";
+
+/** Room between a heading and the column's first card. */
+const LABEL_GAP = 28;
+
+export const FOCUS_COLUMN_TITLES: Record<FocusColumnId, string> = {
+ callers2: "Callers of callers",
+ callers: "Called by",
+ dependencies: "Depends on",
+ dependencies2: "Their dependencies",
+};
+
+export interface FocusColumnLabel {
+ id: string;
+ label: string;
+ x: number;
+ y: number;
+}
+
+/** React Flow data for one heading node. */
+export interface ColumnLabelData {
+ label: string;
+ [key: string]: unknown;
+}
+
+/** One heading per column with a placed card; an empty column has none. */
+export function focusColumnLabels(
+ layout: FocusLayout,
+ positions: ReadonlyMap<string, C4LayoutPosition>,
+): FocusColumnLabel[] {
+ const out: FocusColumnLabel[] = [];
+ for (const c of layout.columns) {
+ const ids = c.entries.map((e) => focusNodeId(c.id, e.serviceId));
+ if (c.folded.length > 0) ids.push(focusMoreId(c.id));
+ const placed = ids.map((id) => positions.get(id)).filter((p): p is C4LayoutPosition => p !== undefined);
+ if (placed.length === 0) continue;
+ const count = c.entries.length + c.folded.length;
+ out.push({
+ id: `label:${c.id}`,
+ label: `${FOCUS_COLUMN_TITLES[c.id]} · ${count.toLocaleString()}`,
+ x: Math.min(...placed.map((p) => p.x)),
+ y: Math.min(...placed.map((p) => p.y)) - LABEL_GAP,
+ });
+ }
+ return out;
+}
diff --git a/packages/ui/src/workspace/system-map/index.ts b/packages/ui/src/workspace/system-map/index.ts
index b95421264..f7487c563 100644
--- a/packages/ui/src/workspace/system-map/index.ts
+++ b/packages/ui/src/workspace/system-map/index.ts
@@ -89,7 +89,6 @@ export {
serviceResolver,
summarizeServiceContracts,
serviceDiagnostics,
- edgeLinks,
edgeSentence,
weightLabel,
weightShort,
@@ -170,6 +169,22 @@ export {
type PathHop,
type ServicePath,
} from "./between";
+export { matchServices, pickerPath, resolveService } from "./between-picker";
+export { focusColumnLabels, FOCUS_COLUMN_TITLES, type FocusColumnLabel } from "./focus-labels";
+export {
+ ROUTES_PAGE,
+ planRoutes,
+ routesLede,
+ hiddenRoutesSentence,
+ type LinksBetweenOptions,
+ type LoadLinksBetween,
+ type RoutesPlan,
+} from "./routes-between";
+export { SystemMapRoutesPanel, type SystemMapRoutesPanelProps } from "./system-map-routes-panel";
+export { SystemMapBetweenControl, type SystemMapBetweenControlProps } from "./system-map-between-control";
+export { RouteRow } from "./system-map-route-row";
+export { buildPairAiPrompt, type BuildPairPromptOptions } from "./system-map-pair-prompt";
+export { useRoutesBetween, useEdgeRoutes, type RoutesBetweenState, type EdgeRoutes } from "./use-routes-between";
export { connectEdges, summarizeLinks, bandId, compareIds } from "./bands";
export { DRAW_BUDGET, allocateSlots, capEdges, truncationReport, type BudgetContainer } from "./draw-budget";
export {
diff --git a/packages/ui/src/workspace/system-map/routes-between.ts b/packages/ui/src/workspace/system-map/routes-between.ts
new file mode 100644
index 000000000..fff30f836
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/routes-between.ts
@@ -0,0 +1,172 @@
+/**
+ * Routes between two services, as plain data for the rail: which kinds the
+ * map's active families keep (the server's totals count every kind), how many
+ * rows each kind holds per direction, what is left out and why, the lede
+ * sentences, and one line of text per row. Pure, no React, no I/O; the rows
+ * come from the host's `loadLinksBetween`.
+ */
+
+import type {
+ ServiceLinkDirection,
+ ServiceLinkEntry,
+ ServiceLinksBetween,
+ ServiceLinksTotal,
+} from "@repowise-dev/types/workspace";
+import { kindMixText } from "./aggregate-facts";
+import type { BetweenResult, ServicePath } from "./between";
+import { EDGE_FAMILY_ORDER, edgeFamily, type EdgeFamily } from "./edge-families";
+import { EDGE_KIND_ORDER, edgeKindStyle } from "./edge-kinds";
+import type { LinkSummary } from "./level-types";
+import { plural } from "./system-map-model";
+
+/** Options a host's loader takes; mirrors `GET /api/workspace/system-graph/links`. */
+export interface LinksBetweenOptions {
+ kind?: string;
+ q?: string;
+ limit?: number;
+ offset?: number;
+}
+
+/** The host's loader: one page of rows between `a` and `b`. */
+export type LoadLinksBetween = (a: string, b: string, opts: LinksBetweenOptions) => Promise<ServiceLinksBetween>;
+
+/** Rows per request in the routes panel. */
+export const ROUTES_PAGE = 50;
+
+/** Display order of directions inside a kind. */
+export const DIRECTION_ORDER: readonly ServiceLinkDirection[] = ["a_to_b", "b_to_a", "both"];
+
+export interface RouteKindSection {
+ kind: string;
+ /** Rows of this kind, every direction, under the filter. */
+ total: number;
+ byDirection: Partial<Record<ServiceLinkDirection, number>>;
+}
+
+export interface HiddenFamily {
+ family: EdgeFamily;
+ rows: number;
+}
+
+export interface RoutesPlan {
+ /** Kinds the map's families keep, in legend order, each with its rows. */
+ sections: RouteKindSection[];
+ /** Rows the families keep. */
+ shown: number;
+ /** Rows in families the map hides, per family, in chip order. */
+ hidden: HiddenFamily[];
+}
+
+function kindRank(kind: string): number {
+ const i = EDGE_KIND_ORDER.indexOf(kind as never);
+ return i === -1 ? EDGE_KIND_ORDER.length : i;
+}
+
+/** Split the server's totals into the kinds listed (in the active families) and the rows each hidden family holds. */
+export function planRoutes(totals: readonly ServiceLinksTotal[], families: ReadonlySet<EdgeFamily>): RoutesPlan {
+ const byKind = new Map<string, RouteKindSection>();
+ const hidden = new Map<EdgeFamily, number>();
+ for (const t of totals) {
+ if (t.count <= 0) continue;
+ const family = edgeFamily(t.kind);
+ if (!families.has(family)) {
+ hidden.set(family, (hidden.get(family) ?? 0) + t.count);
+ continue;
+ }
+ let s = byKind.get(t.kind);
+ if (!s) byKind.set(t.kind, (s = { kind: t.kind, total: 0, byDirection: {} }));
+ s.total += t.count;
+ s.byDirection[t.direction] = (s.byDirection[t.direction] ?? 0) + t.count;
+ }
+ const sections = [...byKind.values()].sort((x, y) => kindRank(x.kind) - kindRank(y.kind) || (x.kind < y.kind ? -1 : 1));
+ return {
+ sections,
+ shown: sections.reduce((n, s) => n + s.total, 0),
+ hidden: EDGE_FAMILY_ORDER.filter((f) => hidden.has(f)).map((family) => ({ family, rows: hidden.get(family)! })),
+ };
+}
+
+/** Loaded rows of one kind, grouped by direction in display order; empty directions are left out. */
+export function rowsByDirection(rows: readonly ServiceLinkEntry[]): { direction: ServiceLinkDirection; rows: ServiceLinkEntry[] }[] {
+ return DIRECTION_ORDER.map((direction) => ({ direction, rows: rows.filter((r) => r.direction === direction) })).filter(
+ (g) => g.rows.length > 0,
+ );
+}
+
+/** "webapp to ordering.api", "ordering.api to webapp", or "Changed together" for co-change rows. */
+export function directionLabel(direction: ServiceLinkDirection, aName: string, bName: string): string {
+ if (direction === "a_to_b") return `${aName} to ${bName}`;
+ if (direction === "b_to_a") return `${bName} to ${aName}`;
+ return "Changed together";
+}
+
+function oneWay(from: string, to: string, summary: LinkSummary | null): string {
+ if (!summary || summary.links === 0) return `Nothing in ${from} depends on ${to}.`;
+ return `${from} depends on ${to} through ${plural(summary.links, "link", "links")} (${kindMixText(summary.kinds)}).`;
+}
+
+/** "HTTP and Event": a hop's kinds in legend order, without counts. */
+function kindWords(summary: LinkSummary): string {
+ return Object.keys(summary.kinds)
+ .filter((k) => (summary.kinds[k] ?? 0) > 0)
+ .sort((x, y) => kindRank(x) - kindRank(y) || (x < y ? -1 : 1))
+ .map((k) => edgeKindStyle(k).label)
+ .join(" and ");
+}
+
+function pathText(path: ServicePath, name: (id: string) => string): string {
+ const kinds = path.hops.map((h) => kindWords(h.summary)).join(", then ");
+ return `${name(path.nodes[0]!)} reaches ${name(path.nodes[path.nodes.length - 1]!)} through ${path.nodes
+ .slice(1, -1)
+ .map(name)
+ .join(", ")} (${kinds}).`;
+}
+
+/**
+ * The lede, from the graph the map drew (the families shown): each direction
+ * in one sentence, or, with no direct link either way, the shortest paths
+ * through one other service, or that there is none.
+ */
+export function routesLede(between: BetweenResult, name: (id: string) => string): string[] {
+ const a = name(between.a);
+ const b = name(between.b);
+ if (between.aToB || between.bToA) return [oneWay(a, b, between.aToB), oneWay(b, a, between.bToA)];
+ const paths = [...between.pathsAToB, ...between.pathsBToA];
+ const head = `No direct link between ${a} and ${b} in the links shown.`;
+ if (paths.length === 0) return [head, "No path joins them through one other service either."];
+ return [head, ...paths.map((p) => pathText(p, name))];
+}
+
+/** The hidden-family note: "Not listed: 3 Build rows (package dependencies)." Null when nothing is hidden. */
+export function hiddenRoutesSentence(hidden: readonly HiddenFamily[], copy: Record<EdgeFamily, { label: string; meaning: string }>): string | null {
+ if (hidden.length === 0) return null;
+ const parts = hidden.map((h) => `${plural(h.rows, `${copy[h.family].label} row`, `${copy[h.family].label} rows`)} (${copy[h.family].meaning})`);
+ return `Not listed, because the map hides their family: ${parts.join(", ")}.`;
+}
+
+/** A row's one-line name: the route, the package, or the file pair. */
+export function routeTitle(row: ServiceLinkEntry): string {
+ if (row.link) return row.link.contract_id;
+ if (row.package_dep) {
+ const d = row.package_dep;
+ return d.requested_version ? `${d.target_package} ${d.requested_version}` : d.target_package;
+ }
+ if (row.co_change) return `${row.co_change.source_file} with ${row.co_change.target_file}`;
+ return edgeKindStyle(row.kind).label;
+}
+
+/** A stable key for a row: its evidence and both ends. */
+export function routeKey(row: ServiceLinkEntry): string {
+ const l = row.link;
+ if (l) return `c|${row.direction}|${l.contract_id}|${l.provider_repo}/${l.provider_file}|${l.consumer_repo}/${l.consumer_file}`;
+ const d = row.package_dep;
+ if (d) return `p|${row.direction}|${d.source_repo}/${d.source_manifest}|${d.target_package}`;
+ const c = row.co_change;
+ if (c) return `h|${c.source_repo}/${c.source_file}|${c.target_repo}/${c.target_file}`;
+ return `${row.kind}|${row.direction}`;
+}
+
+/** True when a response carries the graph-older-than-contracts flag. */
+export function isStale(page: Pick<ServiceLinksBetween, "stale_graph"> | null | undefined): boolean {
+ return page?.stale_graph === true;
+}
diff --git a/packages/ui/src/workspace/system-map/system-map-ai-prompt.ts b/packages/ui/src/workspace/system-map/system-map-ai-prompt.ts
index 5ac04d47a..e57b0182d 100644
--- a/packages/ui/src/workspace/system-map/system-map-ai-prompt.ts
+++ b/packages/ui/src/workspace/system-map/system-map-ai-prompt.ts
@@ -23,7 +23,7 @@ import { linkStrategyCopy } from "../link-provenance";
/** Evidence rows listed in full before the prompt says how many it left out. */
export const SYSTEM_MAP_PROMPT_MAX_ROWS = 25;
-const PREAMBLE_PARTS: PreambleParts = {
+export const SYSTEM_MAP_PREAMBLE: PreambleParts = {
role: WORKSPACE_ROLE,
source: "The facts below come from repowise's system graph, which is built from code and git history.",
open: "the files behind each relationship in each repository",
@@ -36,7 +36,7 @@ function countsLine(counts: Record<string, number>): string {
return entries.length === 0 ? "none" : entries.map(([t, n]) => `${n} ${t}`).join(", ");
}
-function capped<T>(rows: T[], render: (row: T) => string, noun: string): string {
+export function capped<T>(rows: T[], render: (row: T) => string, noun: string): string {
const shown = rows.slice(0, SYSTEM_MAP_PROMPT_MAX_ROWS).map(render).join("\n");
const hidden = rows.length - SYSTEM_MAP_PROMPT_MAX_ROWS;
return hidden > 0 ? `${shown}\n- ...and ${hidden} more ${noun} not listed here.` : shown;
@@ -114,7 +114,7 @@ export function buildServiceAiPrompt(o: BuildServicePromptOptions): string {
// These prompts keep a blank line between sections, so each section after
// the preamble carries its own leading newline.
return joinSections([
- preamble(flavor, PREAMBLE_PARTS),
+ preamble(flavor, SYSTEM_MAP_PREAMBLE),
`\n## Service: ${s.name} (\`${s.id}\`)`,
`\n${bulletList([
`Location: \`${location}\``,
@@ -196,7 +196,7 @@ export interface BuildEdgePromptOptions {
}
/** `, matched by service name (service_mapped)`, or nothing when the link names no strategy. */
-function matchedBy(strategy: string | null | undefined): string {
+export function matchedBy(strategy: string | null | undefined): string {
const copy = linkStrategyCopy(strategy);
return copy ? `, ${copy.label.toLowerCase()} (\`${strategy}\`)` : "";
}
@@ -226,7 +226,7 @@ export function buildEdgeAiPrompt(o: BuildEdgePromptOptions): string {
: `Check whether this co-change hides a real dependency. Files that change together without a declared contract often share an undocumented format, a copied type or a coordinated release. Decide which it is for the pairs above.`;
return joinSections([
- preamble(flavor, PREAMBLE_PARTS),
+ preamble(flavor, SYSTEM_MAP_PREAMBLE),
`\n## Relationship: ${o.source.name} -> ${o.target.name} (\`${e.id}\`)`,
`\n${bulletList([
o.sentence,
@@ -294,7 +294,7 @@ export function buildCycleAiPrompt(o: BuildCyclePromptOptions): string {
.join("\n");
return joinSections([
- preamble(flavor, PREAMBLE_PARTS),
+ preamble(flavor, SYSTEM_MAP_PREAMBLE),
`\n## Dependency cycle: ${loop}`,
`\n${bulletList([
`Services: ${o.ids.map((id) => `\`${id}\``).join(", ")}`,
@@ -349,7 +349,7 @@ export function buildBlastRadiusAiPrompt(o: BuildBlastRadiusPromptOptions): stri
`- **${n.name}** (\`${n.id}\`, repo ${n.repo}): ${n.distance} ${n.distance === 1 ? "hop" : "hops"}, impact ${n.score.toFixed(2)}, via ${n.edge_kinds.join(", ")}`;
return joinSections([
- preamble(flavor, PREAMBLE_PARTS),
+ preamble(flavor, SYSTEM_MAP_PREAMBLE),
`\n## Blast radius of ${o.target.name} (\`${o.target.id}\`)`,
`\n${bulletList([
`${o.impacted.length} downstream ${o.impacted.length === 1 ? "service is" : "services are"} reachable: ${structural.length} through structural dependencies, ${behavioral.length} only through co-change.`,
diff --git a/packages/ui/src/workspace/system-map/system-map-between-control.tsx b/packages/ui/src/workspace/system-map/system-map-between-control.tsx
new file mode 100644
index 000000000..80d05420b
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-between-control.tsx
@@ -0,0 +1,84 @@
+"use client";
+
+/**
+ * The Between picker in the map's title row: a From and a To service, built
+ * on the shared `PathFinderPanel` with the loaded graph as its search and
+ * path source. A pair joined within two hops in the families shown opens
+ * the Between level; otherwise the panel says no route joins them. The host
+ * may open it pre-filled (the drawer's "Routes to..." verb).
+ */
+
+import { useCallback } from "react";
+import { Route } from "lucide-react";
+import { PathFinderPanel, type PathFinderOptionDescriber } from "../../graph/path-finder-panel";
+import { Popover, PopoverContent, PopoverTrigger } from "../../ui/popover";
+import { matchServices, pickerPath } from "./between-picker";
+import type { EdgeFamily } from "./edge-families";
+import type { LevelsGraph } from "./level-types";
+
+export interface SystemMapBetweenControlProps {
+ graph: LevelsGraph;
+ families: ReadonlySet<EdgeFamily>;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ /** Pre-filled From service id. */
+ from?: string | undefined;
+ onBetween: (a: string, b: string) => void;
+}
+
+const COPY = {
+ title: "Routes between two services",
+ fromPlaceholder: "From service...",
+ toPlaceholder: "To service...",
+ topHeading: "Most linked services",
+ submit: "Show routes",
+ noPath: "No route joins these services within two hops in the links shown.",
+};
+
+export function SystemMapBetweenControl({ graph, families, open, onOpenChange, from, onBetween }: SystemMapBetweenControlProps) {
+ const searchNodes = useCallback(async (query: string, limit: number) => matchServices(graph, query, limit), [graph]);
+ const findPath = useCallback(async (a: string, b: string) => pickerPath(graph, a, b, families), [graph, families]);
+ const describeOption = useCallback<PathFinderOptionDescriber>(
+ (r) => ({ label: graph.nodes.find((n) => n.id === r.node_id)?.name ?? r.node_id, detail: r.language }),
+ [graph],
+ );
+ const onPathFound = useCallback(
+ (path: string[]) => {
+ // The panel shows the reader's order, so the ends are From and To.
+ const a = path[0];
+ const b = path[path.length - 1];
+ if (!a || !b) return;
+ onOpenChange(false);
+ onBetween(a, b);
+ },
+ [onBetween, onOpenChange],
+ );
+
+ return (
+ <Popover open={open} onOpenChange={onOpenChange}>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ aria-expanded={open}
+ className="inline-flex h-8 items-center gap-1.5 rounded-md border border-[var(--color-border-hover)] px-2.5 text-xs font-medium text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ <Route size={14} aria-hidden />
+ Between
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-auto border-0 bg-transparent p-0 shadow-none">
+ <PathFinderPanel
+ key={from ?? ""}
+ searchNodes={searchNodes}
+ findPath={findPath}
+ onPathFound={onPathFound}
+ onClear={() => {}}
+ onClose={() => onOpenChange(false)}
+ initialFrom={from ?? ""}
+ copy={COPY}
+ describeOption={describeOption}
+ />
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/packages/ui/src/workspace/system-map/system-map-canvas.tsx b/packages/ui/src/workspace/system-map/system-map-canvas.tsx
index 3665c08f9..c9b4e7bd6 100644
--- a/packages/ui/src/workspace/system-map/system-map-canvas.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-canvas.tsx
@@ -26,6 +26,7 @@ import {
import "@xyflow/react/dist/style.css";
import type { ActivateTrigger } from "./activate";
import { SystemMapBand } from "./system-map-band";
+import { SystemMapColumnLabel } from "./system-map-column-label";
import { SystemMapEdge } from "./system-map-edge";
import type { SystemMapFocusStore } from "./system-map-focus";
import { SystemMapGroupNode } from "./system-map-group-node";
@@ -40,10 +41,11 @@ const NODE_TYPES = {
systemGroup: SystemMapGroupNode,
systemTray: SystemMapTrayNode,
systemMore: SystemMapMoreNode,
+ systemColumnLabel: SystemMapColumnLabel,
};
const EDGE_TYPES = { systemEdge: SystemMapEdge, systemBand: SystemMapBand };
-const NODE_HELP = "Press Enter to open a group or show a service's details. Escape goes back a level.";
+const NODE_HELP = "Press Space for details. Press Enter to open a group or focus a service. Escape goes back a level.";
const FIT_OPTIONS = { padding: 0.08, maxZoom: 1.2 } as const;
@@ -93,7 +95,8 @@ export function SystemMapCanvas({ nodes, edges, focus, fitKey, settled, onActiva
// Only the focused card or connector itself; a control inside a card keeps its own key handling.
if (!el || !id || el !== target) return;
e.preventDefault();
- onActivate(id, el.classList.contains("react-flow__node") ? "node" : "edge", "key");
+ // Space selects, as a click does; Enter opens a group or focuses a service, as a double-click does.
+ onActivate(id, el.classList.contains("react-flow__node") ? "node" : "edge", e.key === " " ? "click" : "key");
},
[onActivate, onEscape],
);
diff --git a/packages/ui/src/workspace/system-map/system-map-column-label.tsx b/packages/ui/src/workspace/system-map/system-map-column-label.tsx
new file mode 100644
index 000000000..66e4408aa
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-column-label.tsx
@@ -0,0 +1,19 @@
+"use client";
+
+/** A focus column's heading on the canvas: inert text, not a card. */
+
+import { memo } from "react";
+import type { NodeProps } from "@xyflow/react";
+import type { ColumnLabelData } from "./focus-labels";
+import { MICRO_LABEL } from "./system-map-filters";
+
+function SystemMapColumnLabelInner({ data }: NodeProps) {
+ const { label } = data as unknown as ColumnLabelData;
+ return (
+ <div role="heading" aria-level={3} className={`${MICRO_LABEL} pointer-events-none whitespace-nowrap`}>
+ {label}
+ </div>
+ );
+}
+
+export const SystemMapColumnLabel = memo(SystemMapColumnLabelInner);
diff --git a/packages/ui/src/workspace/system-map/system-map-drawer.tsx b/packages/ui/src/workspace/system-map/system-map-drawer.tsx
index 9ff668ab5..db935d13f 100644
--- a/packages/ui/src/workspace/system-map/system-map-drawer.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-drawer.tsx
@@ -9,8 +9,10 @@
* Resolves the selection against the whole graph, so a service or edge the
* current level folds into a group or band still has its details.
*
- * Presentation only. The host fetches the focused repository's contracts and
- * owns every route; the drawer takes href builders, not a router.
+ * Presentation only. The host fetches the selected service's repository
+ * contracts and owns every route; the drawer takes href builders, not a
+ * router. A relationship's evidence comes from the host's links loader, one
+ * kind and one direction, resolved to services on the server.
*/
import { useMemo, useState, type ElementType, type ReactNode } from "react";
@@ -21,7 +23,6 @@ import type {
SystemEdge,
SystemGraph,
SystemNode,
- WorkspaceContractLinkEntry,
} from "@repowise-dev/types/workspace";
import { X } from "lucide-react";
import { FilePath } from "../../shared/file-path";
@@ -40,7 +41,6 @@ import {
coChangePairs,
cyclesThrough,
cyclesWithEdge,
- edgeLinks,
edgeSentence,
neighbourGroups,
nodeLocation,
@@ -59,7 +59,11 @@ import {
buildEdgeAiPrompt,
buildServiceAiPrompt,
} from "./system-map-ai-prompt";
+import type { LoadLinksBetween } from "./routes-between";
+import { RouteRow } from "./system-map-route-row";
+import { routeKey } from "./routes-between";
import type { RepoHealth, SystemMapSelection } from "./types";
+import { useEdgeRoutes, type EdgeRoutes } from "./use-routes-between";
/** Contracts listed in the drawer before it hands off to the Contracts page. */
export const DRAWER_CONTRACT_ROWS = 8;
@@ -96,22 +100,22 @@ export interface SystemMapDrawerProps extends SystemMapDrawerData {
roleByNodeId?: ReadonlyMap<string, NodeArchitectureRole> | undefined;
onClose: () => void;
onSelect: (selection: SystemMapSelection) => void;
+ /** The host's links loader; a relationship lists its routes through it. */
+ loadLinksBetween?: LoadLinksBetween | undefined;
+ /** Map verbs: focus a service, start Between from one, or open Between for a pair. */
+ onFocus?: ((serviceId: string) => void) | undefined;
+ onRoutesFrom?: ((serviceId: string) => void) | undefined;
+ onBetween?: ((a: string, b: string) => void) | undefined;
}
/**
* The repository whose contracts the drawer needs for a selection, so the host
- * can fetch before the drawer asks. Groups and bands name no one repository.
+ * can fetch before the drawer asks: a service's. A relationship reads its
+ * routes through the links loader, and groups and bands name no one repository.
*/
export function selectionRepo(graph: SystemGraph | null, selection: SystemMapSelection): string | null {
- if (!graph || !selection) return null;
- // Groups and bands hold several services, so no one repository.
- if (selection.type === "group" || selection.type === "band") return null;
- const repoOfNode = (id: string) => graph.nodes.find((n) => n.id === id)?.repo ?? null;
- if (selection.type === "node") return repoOfNode(selection.id);
- const edge = graph.edges.find((e) => e.id === selection.id);
- if (edge) return repoOfNode(edge.source);
- const source = selection.id.split("->")[0];
- return source ? repoOfNode(source) : null;
+ if (!graph || selection?.type !== "node") return null;
+ return graph.nodes.find((n) => n.id === selection.id)?.repo ?? null;
}
interface PromptState {
@@ -265,6 +269,33 @@ function SelectButton({ onClick, children, title }: { onClick: () => void; child
);
}
+/** A rail verb: a quiet outlined button. */
+function VerbButton({ onClick, children, title }: { onClick: () => void; children: ReactNode; title?: string }) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ title={title}
+ className="rounded-md border border-[var(--color-border-hover)] px-2.5 py-1 text-xs font-medium text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {children}
+ </button>
+ );
+}
+
+type ServiceVerb = ((serviceId: string) => void) | undefined;
+
+/** A service's map verbs, each offered when the host or the map supports it. */
+function NodeVerbs({ id, onFocus, onRoutesFrom, onShowBlastRadius }: { id: string; onFocus: ServiceVerb; onRoutesFrom: ServiceVerb; onShowBlastRadius: ServiceVerb }) {
+ return (
+ <>
+ {onFocus && <VerbButton onClick={() => onFocus(id)} title="Callers on the left, dependencies on the right">Focus</VerbButton>}
+ {onRoutesFrom && <VerbButton onClick={() => onRoutesFrom(id)}>Routes to…</VerbButton>}
+ {onShowBlastRadius && <VerbButton onClick={() => onShowBlastRadius(id)}>Show blast radius</VerbButton>}
+ </>
+ );
+}
+
function distinct(groups: { edges: SystemEdge[] }[], pick: (e: SystemEdge) => string): number {
return new Set(groups.flatMap((g) => g.edges.map(pick))).size;
}
@@ -293,6 +324,8 @@ function NodeBody({
onShowBlastRadius,
diagnostics,
onSelect,
+ onFocus,
+ onRoutesFrom,
resolve,
onPrompt,
}: BodyProps<{ node: SystemNode }>) {
@@ -396,15 +429,7 @@ function NodeBody({
)}
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
- {onShowBlastRadius && (
- <button
- type="button"
- onClick={() => onShowBlastRadius(node.id)}
- className="rounded-md border border-[var(--color-border-hover)] px-2.5 py-1 text-xs font-medium text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
- >
- Show blast radius
- </button>
- )}
+ <NodeVerbs id={node.id} onFocus={onFocus} onRoutesFrom={onRoutesFrom} onShowBlastRadius={onShowBlastRadius} />
<AiPromptButton label="Map before a change" onClick={openServicePrompt} />
{overview && (
<Anchor href={overview} LinkComponent={LinkComponent} className="text-xs font-medium">
@@ -607,15 +632,14 @@ const MATCH_MEANING: Record<string, string> = {
function EdgeBody({
edge,
graph,
- repoContracts,
- repoContractsLoading,
cycles = [],
contractHref,
contractsHref,
coChangesHref,
LinkComponent,
onSelect,
- resolve,
+ onBetween,
+ loadLinksBetween,
onPrompt,
}: BodyProps<{ edge: SystemEdge }>) {
const style = edgeKindStyle(edge.kind);
@@ -628,10 +652,8 @@ function EdgeBody({
const sentence = edgeSentence(edge, sourceName, targetName);
const strategy = linkStrategyCopy(edge.strategy);
- const links = useMemo<WorkspaceContractLinkEntry[] | null>(
- () => (repoContracts && edge.structural ? edgeLinks(edge, repoContracts.links, resolve) : null),
- [repoContracts, edge, resolve],
- );
+ const routes = useEdgeRoutes(loadLinksBetween, edge.structural ? edge : null, DRAWER_EVIDENCE_ROWS);
+ const links = routes?.rows.flatMap((r) => (r.link ? [r.link] : [])) ?? null;
const refs = uniqueRefs(edge);
const pairs = edge.structural ? [] : coChangePairs(edge);
// The lean map view sends a structural edge's count, not its refs.
@@ -721,6 +743,9 @@ function EdgeBody({
label={edge.structural ? "Verify this dependency" : "Check this co-change"}
onClick={openEdgePrompt}
/>
+ {onBetween && (
+ <VerbButton onClick={() => onBetween(edge.source, edge.target)}>All routes between them</VerbButton>
+ )}
</div>
{myCycles.length > 0 && (
@@ -747,47 +772,8 @@ function EdgeBody({
)
}
>
- {repoContractsLoading && !links ? (
- <p className="text-xs text-[var(--color-text-tertiary)]">Loading the links behind this edge…</p>
- ) : links && links.length > 0 ? (
- <>
- <ul className="m-0 flex list-none flex-col divide-y divide-[var(--color-border-default)] p-0">
- {links.slice(0, DRAWER_EVIDENCE_ROWS).map((l) => (
- <li key={`${l.contract_id}|${l.provider_file}|${l.consumer_file}`} className="flex flex-col gap-0.5 py-2">
- {contractHref ? (
- <Anchor
- href={contractHref({ contract_id: l.contract_id, repo: l.provider_repo, file_path: l.provider_file })}
- LinkComponent={LinkComponent}
- className="font-mono text-xs [overflow-wrap:anywhere]"
- >
- {l.contract_id}
- </Anchor>
- ) : (
- <span className="font-mono text-xs [overflow-wrap:anywhere]">{l.contract_id}</span>
- )}
- <span className="font-mono text-[10px] text-[var(--color-text-tertiary)]">
- provides{" "}
- <FilePath path={`${l.provider_repo}/${l.provider_file}`} mode="full" className="text-[10px]" />
- </span>
- <span className="font-mono text-[10px] text-[var(--color-text-tertiary)]">
- calls from{" "}
- <FilePath path={`${l.consumer_repo}/${l.consumer_file}`} mode="full" className="text-[10px]" />
- </span>
- {l.strategy ? (
- <span
- className="text-[10px] text-[var(--color-text-tertiary)]"
- title={linkStrategyCopy(l.strategy)?.meaning}
- >
- {linkStrategyCopy(l.strategy)?.label}
- </span>
- ) : null}
- </li>
- ))}
- </ul>
- <p className="text-xs text-[var(--color-text-tertiary)]">
- {`Showing ${Math.min(links.length, DRAWER_EVIDENCE_ROWS)} of ${plural(links.length, "matched link", "matched links")}.`}
- </p>
- </>
+ {routes && (routes.loading || routes.rows.length > 0) ? (
+ <EdgeRouteRows routes={routes} contractHref={contractHref} LinkComponent={LinkComponent} />
) : refs.length > 0 ? (
<>
<ul className="m-0 flex list-none flex-col gap-1 p-0">
@@ -861,6 +847,32 @@ function EdgeBody({
);
}
+/** The routes behind a structural edge, from the links loader; the "All routes" verb pages the rest. */
+function EdgeRouteRows({
+ routes,
+ contractHref,
+ LinkComponent,
+}: {
+ routes: EdgeRoutes;
+ contractHref?: ((ref: ContractRef) => string) | undefined;
+ LinkComponent?: ElementType | undefined;
+}) {
+ if (routes.loading) return <p className="text-xs text-[var(--color-text-tertiary)]">Loading the routes behind this edge…</p>;
+ return (
+ <>
+ <ul className="m-0 flex list-none flex-col divide-y divide-[var(--color-border-default)] p-0">
+ {routes.rows.map((r, i) => (
+ <RouteRow key={`${routeKey(r)}#${i}`} row={r} contractHref={contractHref} LinkComponent={LinkComponent} />
+ ))}
+ </ul>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ {`Showing ${routes.rows.length.toLocaleString()} of ${plural(Math.max(routes.total, routes.rows.length), "route", "routes")}.`}
+ {routes.stale && " The map and the contracts were read at different commits, so some may be missing."}
+ </p>
+ </>
+ );
+}
+
/** The cycle prompt, shared by the drawer and the findings below the map. */
export function cyclePrompt(cycle: DependencyCycle, graph: SystemGraph): PromptState {
const name = (id: string) => graph.nodes.find((n) => n.id === id)?.name ?? id;
diff --git a/packages/ui/src/workspace/system-map/system-map-model.ts b/packages/ui/src/workspace/system-map/system-map-model.ts
index 14ea82576..961bd641f 100644
--- a/packages/ui/src/workspace/system-map/system-map-model.ts
+++ b/packages/ui/src/workspace/system-map/system-map-model.ts
@@ -155,44 +155,6 @@ export function serviceDiagnostics(
// An edge's evidence.
// ---------------------------------------------------------------------------
-/** The contract type each structural edge kind is built from. */
-const KIND_CONTRACT_TYPE: Partial<Record<SystemEdgeKind, string>> = {
- http: "http",
- grpc: "grpc",
- socket: "socket",
- event: "topic",
- package: "code",
- db: "data",
-};
-
-/**
- * The matched links an edge aggregates. Edge direction is consumer to
- * provider, so the link's consumer must resolve to the source and its provider
- * to the target. The edge's own refs are capped; the links are not.
- */
-export function edgeLinks(
- edge: SystemEdge,
- links: readonly WorkspaceContractLinkEntry[],
- resolve: ServiceResolver,
-): WorkspaceContractLinkEntry[] {
- if (!edge.structural) return [];
- const type = KIND_CONTRACT_TYPE[edge.kind];
- const refs = new Set(edge.contract_refs ?? []);
- const seen = new Set<string>();
- const out: WorkspaceContractLinkEntry[] = [];
- for (const lk of links) {
- if (type ? lk.contract_type !== type : !refs.has(lk.contract_id)) continue;
- if (resolve(lk.consumer_repo, lk.consumer_file) !== edge.source) continue;
- if (resolve(lk.provider_repo, lk.provider_file) !== edge.target) continue;
- const key = `${linkKey(lk.provider_repo, lk.provider_file, lk.contract_id)}\u0000${lk.consumer_file}`;
- if (seen.has(key)) continue;
- seen.add(key);
- out.push(lk);
- }
- out.sort((a, b) => a.contract_id.localeCompare(b.contract_id));
- return out;
-}
-
/** Co-change refs are `source_file~target_file`. */
export function coChangePairs(edge: SystemEdge): [string, string | null][] {
return (edge.contract_refs ?? []).map((ref) => {
diff --git a/packages/ui/src/workspace/system-map/system-map-node.tsx b/packages/ui/src/workspace/system-map/system-map-node.tsx
index f394643b5..9d05072a3 100644
--- a/packages/ui/src/workspace/system-map/system-map-node.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-node.tsx
@@ -19,10 +19,11 @@ import { SystemMapLensBadge } from "./system-map-lens-badge";
import type { SystemMapNodeData } from "./types";
function SystemMapNodeInner({ data, selected }: NodeProps) {
- const { node, health, overlay, role } = data as unknown as SystemMapNodeData;
+ const { node, health, overlay, role, horizontal, focusLinks, endpoint } = data as unknown as SystemMapNodeData;
// Repo health arrives 0-100; the mark reads 0-10.
const mark = health ? healthMark(health.score / 10) : null;
- const lensed = overlay?.highlighted ?? false;
+ // A compared service is marked like a lensed one: ink, never a hue.
+ const lensed = (overlay?.highlighted ?? false) || Boolean(endpoint);
const dimmed = overlay?.dimmed ?? false;
const where = node.service_path ? `${node.repo} / ${node.service_path}` : `${node.repo} repository`;
@@ -53,7 +54,7 @@ function SystemMapNodeInner({ data, selected }: NodeProps) {
transition: "opacity 120ms, border-color 120ms",
}}
>
- <Handle type="target" position={Position.Top} style={{ opacity: 0, pointerEvents: "none" }} />
+ <Handle type="target" position={horizontal ? Position.Left : Position.Top} style={{ opacity: 0, pointerEvents: "none" }} />
{overlay?.badge && (
<SystemMapLensBadge badge={overlay.badge} style={{ position: "absolute", top: -9, right: 10 }} />
@@ -129,12 +130,13 @@ function SystemMapNodeInner({ data, selected }: NodeProps) {
color: "var(--color-text-secondary)",
}}
>
- {node.is_isolated
- ? "no cross-service edges"
- : `${node.provider_count.toLocaleString()} provided · ${node.consumer_count.toLocaleString()} consumed`}
+ {focusLinks ??
+ (node.is_isolated
+ ? "no cross-service edges"
+ : `${node.provider_count.toLocaleString()} provided · ${node.consumer_count.toLocaleString()} consumed`)}
</span>
- <Handle type="source" position={Position.Bottom} style={{ opacity: 0, pointerEvents: "none" }} />
+ <Handle type="source" position={horizontal ? Position.Right : Position.Bottom} style={{ opacity: 0, pointerEvents: "none" }} />
</div>
);
}
diff --git a/packages/ui/src/workspace/system-map/system-map-pair-prompt.ts b/packages/ui/src/workspace/system-map/system-map-pair-prompt.ts
new file mode 100644
index 000000000..3541aaa21
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-pair-prompt.ts
@@ -0,0 +1,63 @@
+/**
+ * The agent prompt for two services: review every route between them, both
+ * ways, from the rows the routes panel loaded. Same shape and preamble as the
+ * other System Map prompts (`system-map-ai-prompt.ts`). Pure string builder.
+ */
+
+import type { ServiceLinkEntry } from "@repowise-dev/types/workspace";
+import { bulletList, joinSections, numbered, preamble, type AiPromptFlavor } from "../../health/ai-prompts/shared";
+import { SYSTEM_MAP_PREAMBLE, capped, matchedBy } from "./system-map-ai-prompt";
+import { routeTitle } from "./routes-between";
+
+export interface BuildPairPromptOptions {
+ a: { id: string; name: string };
+ b: { id: string; name: string };
+ /** The lede sentences the panel shows, from the graph the map drew. */
+ facts: string[];
+ /** Rows loaded so far, every kind listed. */
+ rows: ServiceLinkEntry[];
+ /** Rows the listed kinds hold on the server; above `rows.length` when not all pages were loaded. */
+ total: number;
+ flavor?: AiPromptFlavor;
+}
+
+function rowLine(row: ServiceLinkEntry, aName: string, bName: string): string {
+ const way = row.direction === "a_to_b" ? `${aName} -> ${bName}` : row.direction === "b_to_a" ? `${bName} -> ${aName}` : "co-change";
+ const l = row.link;
+ if (l) {
+ return `- [${row.kind}, ${way}] \`${l.contract_id}\`: consumer \`${l.consumer_repo}:${l.consumer_file}\`, provider \`${l.provider_repo}:${l.provider_file}\`${matchedBy(l.strategy)}`;
+ }
+ const d = row.package_dep;
+ if (d) return `- [package, ${way}] \`${routeTitle(row)}\` declared in \`${d.source_repo}:${d.source_manifest}\``;
+ const c = row.co_change;
+ if (c) return `- [co-change] \`${c.source_repo}:${c.source_file}\` with \`${c.target_repo}:${c.target_file}\`, ${c.frequency} times`;
+ return `- [${row.kind}, ${way}] ${routeTitle(row)}`;
+}
+
+export function buildPairAiPrompt(o: BuildPairPromptOptions): string {
+ const flavor = o.flavor ?? "generic";
+ const { a, b } = o;
+ const unlisted = o.total - o.rows.length;
+ const routes =
+ o.rows.length === 0
+ ? "No route rows were loaded; list the contracts between the two services before you start."
+ : `${capped(o.rows, (r) => rowLine(r, a.name, b.name), "routes")}${
+ unlisted > 0 ? `\n- ${unlisted} more routes exist that were not loaded here.` : ""
+ }`;
+ return joinSections([
+ preamble(flavor, SYSTEM_MAP_PREAMBLE),
+ `\n## Contract between ${a.name} (\`${a.id}\`) and ${b.name} (\`${b.id}\`)`,
+ `\n${bulletList(o.facts)}`,
+ `\n## Routes\n\n${routes}`,
+ `\n## Task\n\nReview the contract between ${a.name} and ${b.name}. Confirm each route above in code on both sides, flag any that is a false match, and describe what each service expects of the other. Do not edit code.`,
+ `\n## What I expect back\n\n${numbered([
+ "Each confirmed route as consumer file and symbol, provider file and symbol.",
+ "Any route that does not hold, with the file you checked.",
+ "Routes either side uses that are missing above, if you find any.",
+ "What a breaking change on each side would look like, and the tests that would catch it.",
+ ])}`,
+ flavor === "claude-code-mcp"
+ ? `\nUse \`search_codebase\` for each route in both repositories and \`get_context\` on the files above; \`get_blast_radius(target="${b.id}")\` shows what else rides on ${b.name}.`
+ : "\nOpen both sides of each route before you write anything.",
+ ]);
+}
diff --git a/packages/ui/src/workspace/system-map/system-map-rail-content.tsx b/packages/ui/src/workspace/system-map/system-map-rail-content.tsx
index 818a10481..a1be61e38 100644
--- a/packages/ui/src/workspace/system-map/system-map-rail-content.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-rail-content.tsx
@@ -2,17 +2,20 @@
/**
* What the rail shows for a selection: a group, a band, a service or a
- * relationship, else the level's own panel (the routes between two services)
- * when the host gives one. Null when there is nothing to explain, so the
+ * relationship, else the level's own panel (the routes between two services
+ * at the Between level). Null when there is nothing to explain, so the
* canvas takes the full width.
*/
import type { ReactNode } from "react";
import type { NodeArchitectureRole, SystemEdge, SystemGraph, SystemNode } from "@repowise-dev/types";
+import type { EdgeFamily } from "./edge-families";
import { drawnLabel } from "./flow-elements";
import type { LevelView } from "./levels";
import { BandPanel, GroupPanel } from "./system-map-aggregate-panel";
+import type { LoadLinksBetween } from "./routes-between";
import { SystemMapDrawer, drawerHasSubject, type SystemMapDrawerData } from "./system-map-drawer";
+import { SystemMapRoutesPanel } from "./system-map-routes-panel";
import type { RepoHealth, SystemMapSelection } from "./types";
export interface RailContentArgs {
@@ -24,9 +27,38 @@ export interface RailContentArgs {
healthByRepo?: ReadonlyMap<string, RepoHealth> | undefined;
roleByNodeId?: ReadonlyMap<string, NodeArchitectureRole> | undefined;
drawer?: SystemMapDrawerData | undefined;
- levelRail?: ReactNode;
+ loadLinksBetween?: LoadLinksBetween | undefined;
onSelect: (selection: SystemMapSelection) => void;
onOpenGroup: (groupId: string) => void;
+ /** Map verbs the rail offers. */
+ verbs: RailVerbs;
+}
+
+export interface RailVerbs {
+ onFocus: (serviceId: string) => void;
+ onRoutesFrom: (serviceId: string) => void;
+ onBetween: (a: string, b: string) => void;
+ onShowFamily: (family: EdgeFamily) => void;
+ /** Leave the Between level. */
+ onLeaveBetween: () => void;
+}
+
+/** The routes between the two services compared, when the level is Between and nothing is selected. */
+function levelRail({ graph, levelView, drawer, loadLinksBetween, verbs }: RailContentArgs): ReactNode {
+ if (levelView.level !== "between" || !levelView.between) return null;
+ return (
+ <SystemMapRoutesPanel
+ graph={graph}
+ between={levelView.between}
+ families={levelView.families}
+ loadLinksBetween={loadLinksBetween}
+ contractHref={drawer?.contractHref}
+ contractsHref={drawer?.contractsHref}
+ LinkComponent={drawer?.LinkComponent}
+ onShowFamily={verbs.onShowFamily}
+ onClose={verbs.onLeaveBetween}
+ />
+ );
}
function aggregateRail(args: RailContentArgs): ReactNode {
@@ -49,7 +81,7 @@ export function railContent(args: RailContentArgs): ReactNode {
const aggregate = aggregateRail(args);
if (aggregate) return aggregate;
const { graph, selection } = args;
- if (!drawerHasSubject(graph, selection)) return args.levelRail ?? null;
+ if (!drawerHasSubject(graph, selection)) return levelRail(args);
return (
<SystemMapDrawer
{...args.drawer}
@@ -59,6 +91,10 @@ export function railContent(args: RailContentArgs): ReactNode {
roleByNodeId={args.roleByNodeId}
onClose={() => args.onSelect(null)}
onSelect={args.onSelect}
+ loadLinksBetween={args.loadLinksBetween}
+ onFocus={args.verbs.onFocus}
+ onRoutesFrom={args.verbs.onRoutesFrom}
+ onBetween={args.verbs.onBetween}
/>
);
}
diff --git a/packages/ui/src/workspace/system-map/system-map-route-row.tsx b/packages/ui/src/workspace/system-map/system-map-route-row.tsx
new file mode 100644
index 000000000..3ffd033eb
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-route-row.tsx
@@ -0,0 +1,93 @@
+"use client";
+
+/**
+ * One route between two services, as a rail row: the route in mono (linked
+ * to the contract when the host routes there), the calling file and the
+ * serving file, and the matching rule only when it needs checking or a
+ * gateway made it. A package row names its manifest; a co-change row its
+ * file pair. Presentation only.
+ */
+
+import type { ElementType } from "react";
+import type { ServiceLinkEntry } from "@repowise-dev/types/workspace";
+import { FilePath } from "../../shared/file-path";
+import { linkStrategyCopy, strategyNeedsCheck } from "../link-provenance";
+import { routeTitle } from "./routes-between";
+import type { ContractRef } from "./system-map-drawer";
+
+export interface RouteRowProps {
+ row: ServiceLinkEntry;
+ contractHref?: ((ref: ContractRef) => string) | undefined;
+ LinkComponent?: ElementType | undefined;
+}
+
+const MONO_10 = "font-mono text-[10px] text-[var(--color-text-secondary)]";
+
+function Title({ row, contractHref, LinkComponent }: RouteRowProps) {
+ const title = routeTitle(row);
+ const l = row.link;
+ if (!l || !contractHref) return <span className="font-mono text-xs [overflow-wrap:anywhere]">{title}</span>;
+ const A = LinkComponent ?? "a";
+ return (
+ <A
+ href={contractHref({ contract_id: l.contract_id, repo: l.provider_repo, file_path: l.provider_file })}
+ className="font-mono text-xs text-[var(--color-accent-primary)] hover:underline [overflow-wrap:anywhere]"
+ >
+ {title}
+ </A>
+ );
+}
+
+/** The matching rule, named only when the reader should check it or a gateway made the link. */
+function StrategyNote({ strategy }: { strategy: string | null | undefined }) {
+ if (!strategyNeedsCheck(strategy) && strategy !== "gateway_route") return null;
+ const copy = linkStrategyCopy(strategy);
+ return copy ? (
+ <span className="text-[10px] text-[var(--color-text-secondary)]" title={copy.meaning}>
+ {copy.label}
+ </span>
+ ) : null;
+}
+
+function Evidence({ row }: { row: ServiceLinkEntry }) {
+ const l = row.link;
+ if (l) {
+ return (
+ <>
+ <span className={MONO_10}>
+ called from <FilePath path={`${l.consumer_repo}/${l.consumer_file}`} mode="full" className="text-[10px]" />
+ </span>
+ <span className={MONO_10}>
+ served by <FilePath path={`${l.provider_repo}/${l.provider_file}`} mode="full" className="text-[10px]" />
+ </span>
+ <StrategyNote strategy={l.strategy} />
+ </>
+ );
+ }
+ const d = row.package_dep;
+ if (d) {
+ return (
+ <span className={MONO_10}>
+ declared in <FilePath path={`${d.source_repo}/${d.source_manifest}`} mode="full" className="text-[10px]" />
+ </span>
+ );
+ }
+ const c = row.co_change;
+ if (c) {
+ return (
+ <span className="text-[10px] tabular-nums text-[var(--color-text-secondary)]">
+ changed together {c.frequency.toLocaleString()} {c.frequency === 1 ? "time" : "times"}
+ </span>
+ );
+ }
+ return null;
+}
+
+export function RouteRow(props: RouteRowProps) {
+ return (
+ <li className="flex flex-col gap-0.5 py-2">
+ <Title {...props} />
+ <Evidence row={props.row} />
+ </li>
+ );
+}
diff --git a/packages/ui/src/workspace/system-map/system-map-routes-panel.tsx b/packages/ui/src/workspace/system-map/system-map-routes-panel.tsx
new file mode 100644
index 000000000..bf3de5120
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-routes-panel.tsx
@@ -0,0 +1,228 @@
+"use client";
+
+/**
+ * Routes between two services, in the rail at the Between level: a lede from
+ * the graph the map drew, then every route the host's loader returns, grouped
+ * by kind and direction, paged per kind, with a filter box. Kinds follow the
+ * map's active families; rows in a hidden family are counted and offered,
+ * not listed. Verbs: the Contracts page for either repository and a prompt
+ * for an agent to review the pair. Presentation only; the host loads rows.
+ */
+
+import { useMemo, useState, type ElementType } from "react";
+import type { SystemGraph } from "@repowise-dev/types/workspace";
+import { AiPromptButton } from "../../health/ai-prompt-button";
+import { AiPromptModal } from "../../health/ai-prompt-modal";
+import type { AiPromptFlavor } from "../../health/ai-prompt-builder";
+import { useDebounce } from "../../hooks/use-debounce";
+import { Skeleton } from "../../ui/skeleton";
+import type { BetweenResult } from "./between";
+import { EDGE_FAMILY_COPY, type EdgeFamily } from "./edge-families";
+import { edgeKindStyle } from "./edge-kinds";
+import {
+ directionLabel,
+ hiddenRoutesSentence,
+ routeKey,
+ routesLede,
+ rowsByDirection,
+ type LoadLinksBetween,
+ type RouteKindSection,
+} from "./routes-between";
+import { SystemMapRailFrame, type ContractRef } from "./system-map-drawer";
+import { MICRO_LABEL } from "./system-map-filters";
+import { buildPairAiPrompt } from "./system-map-pair-prompt";
+import { RouteRow } from "./system-map-route-row";
+import { plural } from "./system-map-model";
+import { useRoutesBetween, type KindRows, type RoutesBetweenState } from "./use-routes-between";
+
+export interface SystemMapRoutesPanelProps {
+ graph: Pick<SystemGraph, "nodes">;
+ between: BetweenResult;
+ families: ReadonlySet<EdgeFamily>;
+ loadLinksBetween?: LoadLinksBetween | undefined;
+ contractHref?: ((ref: ContractRef) => string) | undefined;
+ /** The Contracts page filtered to one repository. */
+ contractsHref?: ((repo: string) => string) | undefined;
+ LinkComponent?: ElementType | undefined;
+ /** Draw a hidden family, so its rows list here and its links on the canvas. */
+ onShowFamily?: ((family: EdgeFamily) => void) | undefined;
+ onClose: () => void;
+}
+
+const QUIET = "text-xs text-[var(--color-text-secondary)]";
+const BUTTON =
+ "rounded-md border border-[var(--color-border-hover)] px-2.5 py-1 text-xs font-medium text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]";
+
+export function SystemMapRoutesPanel(props: SystemMapRoutesPanelProps) {
+ const { graph, between, families } = props;
+ const [filter, setFilter] = useState("");
+ const q = useDebounce(filter.trim(), 250);
+ const state = useRoutesBetween({ load: props.loadLinksBetween, a: between.a, b: between.b, families, q });
+ const [prompting, setPrompting] = useState(false);
+
+ const nodeOf = (id: string) => graph.nodes.find((n) => n.id === id);
+ const name = (id: string) => nodeOf(id)?.name ?? id;
+ const lede = useMemo(
+ () => routesLede(between, (id) => graph.nodes.find((n) => n.id === id)?.name ?? id),
+ [between, graph],
+ );
+ const a = { id: between.a, name: name(between.a) };
+ const b = { id: between.b, name: name(between.b) };
+ const repos = [...new Set([nodeOf(a.id)?.repo, nodeOf(b.id)?.repo].filter((r): r is string => Boolean(r)))];
+
+ const buildPrompt = () => {
+ const rows = (state.plan?.sections ?? []).flatMap((s) => state.byKind[s.kind]?.rows ?? []);
+ return (flavor: AiPromptFlavor) =>
+ buildPairAiPrompt({ a, b, facts: lede, rows, total: state.plan?.shown ?? rows.length, flavor });
+ };
+
+ return (
+ <>
+ <SystemMapRailFrame eyebrow="Routes between" title={`${a.name} and ${b.name}`} onClose={props.onClose}>
+ <div className="flex flex-col gap-1.5">
+ {lede.map((s) => (
+ <p key={s} className="text-[15px] leading-relaxed text-[var(--color-text-primary)] [text-wrap:pretty]">
+ {s}
+ </p>
+ ))}
+ </div>
+ {state.stale && (
+ <p className={QUIET} role="note">
+ The map and the contracts were read at different commits, so some routes may be missing until the next update.
+ </p>
+ )}
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">
+ <AiPromptButton label="Copy prompt for an agent" onClick={() => setPrompting(true)} />
+ {props.contractsHref &&
+ repos.map((repo) => {
+ const A = props.LinkComponent ?? "a";
+ return (
+ <A key={repo} href={props.contractsHref!(repo)} className="text-xs font-medium text-[var(--color-accent-primary)] hover:underline">
+ Open in Contracts: {repo} →
+ </A>
+ );
+ })}
+ </div>
+ <input
+ type="search"
+ value={filter}
+ onChange={(e) => setFilter(e.target.value)}
+ placeholder="Filter routes, files or packages"
+ aria-label="Filter routes"
+ className="h-8 w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-inset)] px-2.5 text-xs text-[var(--color-text-primary)] placeholder:text-[var(--color-text-secondary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-accent-primary)]"
+ />
+ <RoutesBody state={state} q={q} a={a.name} b={b.name} {...props} />
+ </SystemMapRailFrame>
+ <AiPromptModal
+ open={prompting}
+ onOpenChange={setPrompting}
+ getPrompt={prompting ? buildPrompt() : null}
+ title="Review the contract between two services"
+ description={`A ready-to-paste prompt that has your agent confirm every route between ${a.name} and ${b.name} in code.`}
+ />
+ </>
+ );
+}
+
+type BodyProps = SystemMapRoutesPanelProps & { state: RoutesBetweenState; q: string; a: string; b: string };
+
+function RoutesBody({ state, q, a, b, onShowFamily, ...rest }: BodyProps) {
+ if (state.unavailable) return <p className={QUIET}>Route detail is not available here.</p>;
+ if (state.loading) return <RowSkeletons />;
+ if (state.error || !state.plan) return <p className={QUIET}>The routes could not be loaded.</p>;
+ const { plan } = state;
+ const hidden = hiddenRoutesSentence(plan.hidden, EDGE_FAMILY_COPY);
+ return (
+ <div className="flex flex-col gap-5">
+ {plan.shown === 0 && (
+ <p className={QUIET}>{q ? `No routes match "${q}".` : `No routes between ${a} and ${b} in the families shown.`}</p>
+ )}
+ {plan.sections.map((s) => (
+ <KindSection key={s.kind} section={s} rows={state.byKind[s.kind]} a={a} b={b} onMore={() => state.loadMore(s.kind)} {...rest} />
+ ))}
+ {hidden && (
+ <div className="flex flex-wrap items-center gap-2">
+ <p className={QUIET}>{hidden}</p>
+ {onShowFamily &&
+ plan.hidden.map((h) => (
+ <button key={h.family} type="button" className={BUTTON} onClick={() => onShowFamily(h.family)}>
+ Show {EDGE_FAMILY_COPY[h.family].label}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function RowSkeletons() {
+ return (
+ <div className="flex flex-col gap-3" aria-busy="true" aria-label="Loading routes">
+ {[0, 1, 2].map((i) => (
+ <Skeleton key={i} className="h-[52px] w-full" />
+ ))}
+ </div>
+ );
+}
+
+interface KindSectionProps extends Omit<SystemMapRoutesPanelProps, "graph" | "between" | "families" | "onClose"> {
+ section: RouteKindSection;
+ rows: KindRows | undefined;
+ a: string;
+ b: string;
+ onMore: () => void;
+}
+
+function KindSection({ section, rows, a, b, onMore, contractHref, LinkComponent }: KindSectionProps) {
+ const style = edgeKindStyle(section.kind);
+ const Icon = style.icon;
+ const loaded = rows?.rows ?? [];
+ return (
+ <section className="flex flex-col gap-1" aria-label={`${style.label} routes`}>
+ <h3 className={`${MICRO_LABEL} inline-flex items-center gap-1.5`}>
+ <Icon size={12} aria-hidden />
+ {style.label} · {section.total.toLocaleString()}
+ </h3>
+ {loaded.length === 0 && rows?.loading !== false ? (
+ <RowSkeletons />
+ ) : (
+ rowsByDirection(loaded).map((g) => (
+ <div key={g.direction} className="flex flex-col">
+ <h4 className="text-xs text-[var(--color-text-secondary)]">
+ {directionLabel(g.direction, a, b)} · {(section.byDirection[g.direction] ?? g.rows.length).toLocaleString()}
+ </h4>
+ <ul className="m-0 flex list-none flex-col divide-y divide-[var(--color-border-default)] p-0">
+ {g.rows.map((r, i) => (
+ // The position keeps two rows with the same evidence apart.
+ <RouteRow key={`${routeKey(r)}#${i}`} row={r} contractHref={contractHref} LinkComponent={LinkComponent} />
+ ))}
+ </ul>
+ </div>
+ ))
+ )}
+ <PageFooter shown={loaded.length} total={section.total} rows={rows} onMore={onMore} />
+ </section>
+ );
+}
+
+function PageFooter({ shown, total, rows, onMore }: { shown: number; total: number; rows: KindRows | undefined; onMore: () => void }) {
+ if (rows?.error) {
+ return (
+ <div className="flex items-center justify-between gap-3">
+ <p className={QUIET}>This page of routes could not be loaded.</p>
+ <button type="button" className={BUTTON} onClick={onMore}>
+ Retry
+ </button>
+ </div>
+ );
+ }
+ if (shown === 0 || shown >= total) return null;
+ return (
+ <div className="flex items-center justify-between gap-3">
+ <p className={QUIET}>{`Showing ${shown.toLocaleString()} of ${plural(total, "route", "routes")}`}</p>
+ <button type="button" className={BUTTON} onClick={onMore} disabled={rows?.loading}>
+ {rows?.loading ? "Loading…" : "Load more"}
+ </button>
+ </div>
+ );
+}
diff --git a/packages/ui/src/workspace/system-map/system-map-tray-node.tsx b/packages/ui/src/workspace/system-map/system-map-tray-node.tsx
index 11a6a785e..f9d9bceb3 100644
--- a/packages/ui/src/workspace/system-map/system-map-tray-node.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-tray-node.tsx
@@ -80,13 +80,13 @@ function TrayNodeInner({ data, selected }: NodeProps) {
}
function MoreNodeInner({ data, selected }: NodeProps) {
- const { more } = data as unknown as MoreNodeData;
+ const { more, horizontal } = data as unknown as MoreNodeData;
const { showFolded } = useSystemMapActions();
const { width, height } = LEVEL_NODE_SIZES.more;
const groups = more.groupIds.length;
return (
<div style={{ ...dashed(Boolean(selected)), width, height, display: "flex", flexDirection: "column", gap: 3, padding: "9px 12px" }}>
- <Handle type="target" position={Position.Top} style={HIDDEN_HANDLE} />
+ <Handle type="target" position={horizontal ? Position.Left : Position.Top} style={HIDDEN_HANDLE} />
<span style={{ fontSize: 15, lineHeight: "20px", fontWeight: 600, color: "var(--color-text-primary)", fontVariantNumeric: "tabular-nums" }}>
+{more.serviceIds.length.toLocaleString()} more
</span>
@@ -99,7 +99,7 @@ function MoreNodeInner({ data, selected }: NodeProps) {
<CardAction label="List them" onClick={() => showFolded(more.serviceIds)} />
</div>
)}
- <Handle type="source" position={Position.Bottom} style={HIDDEN_HANDLE} />
+ <Handle type="source" position={horizontal ? Position.Right : Position.Bottom} style={HIDDEN_HANDLE} />
</div>
);
}
diff --git a/packages/ui/src/workspace/system-map/system-map.tsx b/packages/ui/src/workspace/system-map/system-map.tsx
index 74e3a3a5c..7bd43aa8e 100644
--- a/packages/ui/src/workspace/system-map/system-map.tsx
+++ b/packages/ui/src/workspace/system-map/system-map.tsx
@@ -11,11 +11,11 @@
* Built on `GraphCanvasShell`: the lens and extra actions in the title row,
* the family chips and key above the canvas, the caption under it, and the
* details in the rail, a grid peer of the canvas (a bottom sheet on phones).
- * The host supplies data and routes through props only; it may control the
- * level state and the selection to keep them in its URL.
+ * The host supplies data, routes and the links loader through props only; it
+ * may control the level state and the selection to keep them in its URL.
*/
-import { useCallback, useEffect, useMemo, useRef, type ReactNode, type RefObject } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
import { ReactFlowProvider } from "@xyflow/react";
import type { NodeArchitectureRole, SystemGraph } from "@repowise-dev/types";
import { GraphCanvasShell } from "../../graph/graph-canvas-shell";
@@ -31,12 +31,14 @@ import { SystemMapCanvasEmpty } from "./system-map-empty";
import { SystemMapFilters } from "./system-map-filters";
import { SystemMapFocusContext, createSystemMapFocusStore, type SystemMapFocusStore } from "./system-map-focus";
import { SystemMapLegend, legendKeyFor } from "./system-map-legend";
-import { railContent } from "./system-map-rail-content";
+import type { LoadLinksBetween } from "./routes-between";
+import { SystemMapBetweenControl } from "./system-map-between-control";
+import { railContent, type RailVerbs } from "./system-map-rail-content";
import type { RepoHealth, SystemMapOverlay, SystemMapSelection } from "./types";
import { useDropUndrawnAggregate, useMapLevel, type MapLevel } from "./use-map-level";
import type { SystemMapPhase } from "./use-system-map-phases";
import { useSystemMapState, type SystemMapState } from "./use-system-map-state";
-import { backOut, closeContainer, openContainer, toggleFamily, type MapViewState } from "./view-state";
+import { backOut, closeContainer, openContainer, showFamily, toggleFamily, type MapViewState } from "./view-state";
/** The canvas's height, shared with the host's loading placeholder so nothing reflows. */
export const SYSTEM_MAP_CANVAS_HEIGHT = "h-[420px] sm:h-[clamp(460px,calc(100dvh-240px),800px)]";
@@ -65,8 +67,12 @@ export interface SystemMapProps {
/** Controlled level state (`open`, `focus`, `a`/`b`, `kinds` in a URL). */
view?: MapViewState;
onViewChange?: (view: MapViewState) => void;
- /** Rail content for the current level when nothing is selected, e.g. the routes between two services. */
- levelRail?: ReactNode;
+ /**
+ * One page of routes between two services (`GET /api/workspace/system-graph/links`).
+ * The Between level lists them in the rail and a relationship shows its own;
+ * without it both say route detail is not available.
+ */
+ loadLinksBetween?: LoadLinksBetween;
/** Lists what a "+N more" card folded; the card offers it only when present. */
onShowFolded?: (serviceIds: readonly string[]) => void;
/** The breadcrumb's root, e.g. the workspace name. */
@@ -111,9 +117,10 @@ function useMapInput(levelView: LevelView | null, state: SystemMapState, onShowF
(a: Activation) => {
if (a?.kind === "select") setSelection(a.selection);
else if (a?.kind === "open") actions.openContainer(a.id);
+ else if (a?.kind === "focus") setView(focusService(view, a.serviceId));
else if (a?.kind === "folded") actions.showFolded?.(a.serviceIds);
},
- [setSelection, actions],
+ [setSelection, actions, setView, view],
);
const onActivate = useCallback(
(id: string, kind: "node" | "edge", trigger: ActivateTrigger) =>
@@ -132,6 +139,35 @@ function useMapInput(levelView: LevelView | null, state: SystemMapState, onShowF
return { actions, onActivate, onEscape };
}
+/** The focus level around one service; leaves Between, keeps the families and open groups. */
+function focusService(view: MapViewState, id: string): MapViewState {
+ return { ...view, focus: id, between: null };
+}
+
+/** The Between picker's state and the verbs the rail offers (focus, between, show a family). */
+function useRailVerbs(state: SystemMapState) {
+ const { view, setView, setSelection } = state;
+ const [picker, setPicker] = useState<{ open: boolean; from?: string }>({ open: false });
+ const onBetween = useCallback(
+ (a: string, b: string) => {
+ setSelection(null);
+ setView({ ...view, between: { a, b } });
+ },
+ [view, setView, setSelection],
+ );
+ const verbs = useMemo<RailVerbs>(
+ () => ({
+ onFocus: (id) => setView(focusService(view, id)),
+ onRoutesFrom: (id) => setPicker({ open: true, from: id }),
+ onBetween,
+ onShowFamily: (f) => setView(showFamily(view, f)),
+ onLeaveBetween: () => setView({ ...view, between: null }),
+ }),
+ [view, setView, onBetween],
+ );
+ return { verbs, picker, setPicker, onBetween };
+}
+
function SystemMapInner(props: SystemMapProps) {
const { graph, healthByRepo, overlay, roleByNodeId, toolbar, actions: extraActions } = props;
const state = useSystemMapState(props);
@@ -141,6 +177,7 @@ function SystemMapInner(props: SystemMapProps) {
const { nodesById, edgesById, levelView, layout } = level;
const { focus, canvasRef } = useFocusStore(level);
const input = useMapInput(levelView, state, props.onShowFolded);
+ const rail = useRailVerbs(state);
const selectedId = level.resolved?.drawnId ?? null;
const flow = useMemo<FlowElements>(
@@ -155,7 +192,7 @@ function SystemMapInner(props: SystemMapProps) {
const legend = useMemo(() => legendKeyFor(levelView?.edges ?? [], edgesById), [levelView, edgesById]);
const hasGraph = Boolean(graph && graph.nodes.length > 0);
- const rail =
+ const railNode =
graph && levelView
? railContent({
graph,
@@ -166,11 +203,23 @@ function SystemMapInner(props: SystemMapProps) {
healthByRepo,
roleByNodeId,
drawer: props.drawer,
- levelRail: props.levelRail,
+ loadLinksBetween: props.loadLinksBetween,
onSelect: setSelection,
onOpenGroup: input.actions.openContainer,
+ verbs: rail.verbs,
})
: null;
+ const betweenControl =
+ graph && levelView && graph.nodes.length > 1 ? (
+ <SystemMapBetweenControl
+ graph={graph}
+ families={levelView.families}
+ open={rail.picker.open}
+ onOpenChange={(open) => rail.setPicker(open ? { ...rail.picker, open } : { open: false })}
+ from={rail.picker.from}
+ onBetween={rail.onBetween}
+ />
+ ) : null;
const breadcrumb =
graph && levelView && levelView.level !== "estate" ? (
<SystemMapBreadcrumb graph={graph} level={levelView.level} view={view} onViewChange={setView} estateLabel={props.estateLabel} />
@@ -201,9 +250,9 @@ function SystemMapInner(props: SystemMapProps) {
<GraphCanvasShell
variant="section"
breadcrumb={breadcrumb}
- titleActions={toolbar || extraActions ? <>{toolbar}{extraActions}</> : undefined}
+ titleActions={toolbar || extraActions || betweenControl ? <>{toolbar}{extraActions}{betweenControl}</> : undefined}
banner={banner}
- rail={rail}
+ rail={railNode}
footer={hasGraph && caption.length > 0 ? <p className="text-xs text-[var(--color-text-secondary)]">{caption.join(" ")}</p> : undefined}
>
<MapCanvas
diff --git a/packages/ui/src/workspace/system-map/types.ts b/packages/ui/src/workspace/system-map/types.ts
index 908f1660e..fae00ea0a 100644
--- a/packages/ui/src/workspace/system-map/types.ts
+++ b/packages/ui/src/workspace/system-map/types.ts
@@ -21,6 +21,12 @@ export interface SystemMapNodeData {
overlay: NodeOverlayState | null;
/** Architecture role label ("Core", "Shared"...), named in text on the node. */
role: string | null;
+ /** Focus level: connectors join card sides, since its columns read left to right. */
+ horizontal?: boolean;
+ /** Focus level: the links to the neighbour column ("8 · HTTP 2, Event 6"), in place of the contract counts. */
+ focusLinks?: string | null;
+ /** Between level: one of the two services compared. */
+ endpoint?: boolean;
[key: string]: unknown;
}
diff --git a/packages/ui/src/workspace/system-map/use-routes-between.ts b/packages/ui/src/workspace/system-map/use-routes-between.ts
new file mode 100644
index 000000000..47f8543ca
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/use-routes-between.ts
@@ -0,0 +1,188 @@
+"use client";
+
+/**
+ * Pages of routes between two services through the host's loader. The first
+ * request reads the totals per kind and direction under the filter; each
+ * kind the map's families keep then loads its own pages, so paging is exact
+ * per kind and a hidden family costs no row requests. State resets when the
+ * pair or the filter changes; a reply for an earlier pair or filter is
+ * dropped. The edge drawer's smaller read (one kind, one direction, no
+ * paging) lives here too, so both reads share one loader contract.
+ */
+
+import { useCallback, useEffect, useMemo, useState } from "react";
+import type { ServiceLinkEntry, ServiceLinksBetween } from "@repowise-dev/types/workspace";
+import type { EdgeFamily } from "./edge-families";
+import { ROUTES_PAGE, isStale, planRoutes, type LoadLinksBetween, type RoutesPlan } from "./routes-between";
+
+export interface KindRows {
+ rows: ServiceLinkEntry[];
+ loading: boolean;
+ error: boolean;
+}
+
+export interface RoutesBetweenState {
+ /** No loader: the host cannot list routes here. */
+ unavailable: boolean;
+ loading: boolean;
+ error: boolean;
+ plan: RoutesPlan | null;
+ stale: boolean;
+ byKind: Readonly<Record<string, KindRows>>;
+ loadMore: (kind: string) => void;
+}
+
+export interface RoutesBetweenArgs {
+ load: LoadLinksBetween | undefined;
+ a: string;
+ b: string;
+ families: ReadonlySet<EdgeFamily>;
+ q: string;
+}
+
+/** One pair and filter: what every request and every reply is keyed by. */
+interface Query {
+ load: LoadLinksBetween | undefined;
+ a: string;
+ b: string;
+ q: string;
+ key: string;
+}
+
+interface Totals {
+ key: string;
+ page: ServiceLinksBetween | null;
+}
+
+const EMPTY_KIND: KindRows = { rows: [], loading: true, error: false };
+
+const withQ = (q: string) => (q ? { q } : {});
+
+/** The totals request for the current query; null until its reply lands. */
+function useRouteTotals({ load, a, b, q, key }: Query): Totals | null {
+ const [totals, setTotals] = useState<Totals | null>(null);
+ useEffect(() => {
+ if (!load) return;
+ let cancelled = false;
+ load(a, b, { ...withQ(q), limit: 1 }).then(
+ (page) => !cancelled && setTotals({ key, page }),
+ () => !cancelled && setTotals({ key, page: null }),
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [load, a, b, q, key]);
+ return totals?.key === key ? totals : null;
+}
+
+/** Rows per kind for the current query, and a fetch for one page of one kind. */
+function useKindPages({ load, a, b, q, key }: Query) {
+ const [pages, setPages] = useState<{ key: string; byKind: Record<string, KindRows> }>({ key, byKind: {} });
+ const byKind = pages.key === key ? pages.byKind : {};
+
+ const fetchPage = useCallback(
+ (kind: string, offset: number) => {
+ if (!load) return;
+ // A reply for an earlier pair or filter is dropped, never written over the current one.
+ const patch = (next: (prior: KindRows) => KindRows) =>
+ setPages((p) => (p.key !== key ? p : { key, byKind: { ...p.byKind, [kind]: next(p.byKind[kind] ?? EMPTY_KIND) } }));
+ setPages((p) => {
+ const base = p.key === key ? p.byKind : {};
+ return { key, byKind: { ...base, [kind]: { ...(base[kind] ?? EMPTY_KIND), loading: true, error: false } } };
+ });
+ load(a, b, { kind, ...withQ(q), limit: ROUTES_PAGE, offset }).then(
+ (page) => patch((prior) => ({ rows: [...prior.rows.slice(0, offset), ...page.links], loading: false, error: false })),
+ () => patch((prior) => ({ ...prior, loading: false, error: true })),
+ );
+ },
+ [load, a, b, q, key],
+ );
+ return { byKind, fetchPage };
+}
+
+/** The totals and the first page of each kept kind, for one pair and filter. */
+export function useRoutesBetween({ load, a, b, families, q }: RoutesBetweenArgs): RoutesBetweenState {
+ const query: Query = { load, a, b, q, key: `${a}\u0000${b}\u0000${q}` };
+ const totals = useRouteTotals(query);
+ const { byKind, fetchPage } = useKindPages(query);
+ const page = totals?.page ?? null;
+ const plan = useMemo(() => (page ? planRoutes(page.totals, families) : null), [page, families]);
+
+ // First page of every kept kind not asked for yet (a family turned on later loads then).
+ const missingKey = (plan?.sections ?? [])
+ .map((s) => s.kind)
+ .filter((k) => !byKind[k])
+ .join(",");
+ useEffect(() => {
+ if (missingKey) for (const kind of missingKey.split(",")) fetchPage(kind, 0);
+ }, [missingKey, fetchPage]);
+
+ const loadMore = useCallback(
+ (kind: string) => {
+ const prior = byKind[kind];
+ // After an error this retries the page that failed.
+ if (prior && !prior.loading) fetchPage(kind, prior.rows.length);
+ },
+ [byKind, fetchPage],
+ );
+
+ return {
+ unavailable: !load,
+ loading: Boolean(load) && !totals,
+ error: Boolean(totals && !page),
+ plan,
+ stale: isStale(page),
+ byKind,
+ loadMore,
+ };
+}
+
+export interface EdgeRoutes {
+ loading: boolean;
+ error: boolean;
+ /** Rows of the edge's kind running source to target, at most `limit`. */
+ rows: ServiceLinkEntry[];
+ /** Rows of that kind and direction on the server. */
+ total: number;
+ stale: boolean;
+}
+
+const EDGE_LOADING: EdgeRoutes = { loading: true, error: false, rows: [], total: 0, stale: false };
+const EDGE_FAILED: EdgeRoutes = { loading: false, error: true, rows: [], total: 0, stale: false };
+
+/** One edge's rows from a page of its pair: its kind, source to target. */
+function edgeRoutesFrom(page: ServiceLinksBetween, kind: string): EdgeRoutes {
+ const total = page.totals.find((t) => t.kind === kind && t.direction === "a_to_b")?.count ?? 0;
+ return { loading: false, error: false, rows: page.links.filter((r) => r.direction === "a_to_b"), total, stale: isStale(page) };
+}
+
+/**
+ * The routes behind one edge: its kind, from its source (the consumer) to its
+ * target. Rows come ordered by direction, so the first page holds this
+ * direction's rows first. Null without a loader or without an edge to read
+ * (co-change evidence lives on the edge itself).
+ */
+export function useEdgeRoutes(
+ load: LoadLinksBetween | undefined,
+ edge: { source: string; target: string; kind: string } | null,
+ limit: number,
+): EdgeRoutes | null {
+ const [state, setState] = useState<{ key: string; value: EdgeRoutes } | null>(null);
+ const source = edge?.source ?? "";
+ const target = edge?.target ?? "";
+ const kind = edge?.kind ?? "";
+ const key = `${source}\u0000${target}\u0000${kind}`;
+ useEffect(() => {
+ if (!load || !source) return;
+ let cancelled = false;
+ load(source, target, { kind, limit }).then(
+ (page) => !cancelled && setState({ key, value: edgeRoutesFrom(page, kind) }),
+ () => !cancelled && setState({ key, value: EDGE_FAILED }),
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [load, source, target, kind, key, limit]);
+ if (!load || !edge) return null;
+ return state?.key === key ? state.value : EDGE_LOADING;
+}
diff --git a/packages/web/src/app/workspace/system-map/page.tsx b/packages/web/src/app/workspace/system-map/page.tsx
index 9252a0dd8..9da6a7c8d 100644
--- a/packages/web/src/app/workspace/system-map/page.tsx
+++ b/packages/web/src/app/workspace/system-map/page.tsx
@@ -51,6 +51,7 @@ import {
import { httpLinkedStat } from "@/lib/http-link-coverage";
import { markSystemMap, useSystemMapPerfMarks } from "@/lib/system-map-perf";
import { useRepoContracts } from "./use-repo-contracts";
+import { useServiceLinks } from "./use-service-links";
const LENSES: readonly SystemMapLens[] = ["none", "blast", "breaking", "conformance", "core"];
/** URL params a selection is written to, one per selection type. */
@@ -174,6 +175,7 @@ export default function SystemMapPage() {
const focusRepo = useMemo(() => selectionRepo(graph, selection), [graph, selection]);
const { data: repoContracts, isLoading: repoContractsLoading } = useRepoContracts(focusRepo);
+ const loadLinksBetween = useServiceLinks();
const roleByNodeId = useMemo<Map<string, NodeArchitectureRole>>(() => {
const m = new Map<string, NodeArchitectureRole>();
@@ -267,6 +269,7 @@ export default function SystemMapPage() {
estateLabel={t("estate")}
onPhase={markSystemMap}
drawer={drawer}
+ loadLinksBetween={loadLinksBetween}
toolbar={
<SystemMapLensControl
value={lens}
diff --git a/packages/web/src/app/workspace/system-map/use-repo-contracts.ts b/packages/web/src/app/workspace/system-map/use-repo-contracts.ts
index 1bc62e88a..2731008c0 100644
--- a/packages/web/src/app/workspace/system-map/use-repo-contracts.ts
+++ b/packages/web/src/app/workspace/system-map/use-repo-contracts.ts
@@ -16,8 +16,8 @@ const MAX_PAGES = 5;
/**
* Every contract and matched link for one repository, fetched only once the
- * drawer needs it (a service or relationship is selected). Keyed by repo, so
- * the node and edge drawers share one fetch.
+ * drawer needs it (a service is selected) for the service's contract list.
+ * A relationship's routes come from `useServiceLinks` instead.
*/
export function useRepoContracts(repo: string | null) {
const { data, isLoading } = useSWR<SystemMapRepoContracts>(
diff --git a/packages/web/src/app/workspace/system-map/use-service-links.ts b/packages/web/src/app/workspace/system-map/use-service-links.ts
new file mode 100644
index 000000000..12b7d0809
--- /dev/null
+++ b/packages/web/src/app/workspace/system-map/use-service-links.ts
@@ -0,0 +1,28 @@
+"use client";
+
+import { useCallback, useRef } from "react";
+import type { LoadLinksBetween } from "@repowise-dev/ui/workspace/system-map";
+import { getWorkspaceLinksBetween } from "@/lib/api/workspace";
+
+/** Pages kept for the page's lifetime; the oldest goes first past this. */
+const CACHE_LIMIT = 64;
+
+/**
+ * The map's links loader: one page of routes between two services, resolved
+ * server-side. Pages are cached by request, so reselecting an edge or going
+ * back to a pair asks nothing twice; a failed request is not cached.
+ */
+export function useServiceLinks(): LoadLinksBetween {
+ const cache = useRef(new Map<string, ReturnType<LoadLinksBetween>>());
+ return useCallback<LoadLinksBetween>((a, b, opts) => {
+ const key = JSON.stringify([a, b, opts.kind ?? "", opts.q ?? "", opts.limit ?? 0, opts.offset ?? 0]);
+ const pages = cache.current;
+ const hit = pages.get(key);
+ if (hit) return hit;
+ const request = getWorkspaceLinksBetween({ a, b, ...opts });
+ pages.set(key, request);
+ request.catch(() => pages.delete(key));
+ if (pages.size > CACHE_LIMIT) pages.delete(pages.keys().next().value!);
+ return request;
+ }, []);
+}