Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(ui): system map v2 canvas (group cards, bands, breadcrumb, rail) (#4621)
Raghav Chamadiya94074087b9a1
diff --git a/packages/ui/__tests__/workspace/synthetic-system-graph.test.ts b/packages/ui/__tests__/workspace/synthetic-system-graph.test.tsindex 23d7ed238..8222de4ad 100644--- a/packages/ui/__tests__/workspace/synthetic-system-graph.test.ts+++ b/packages/ui/__tests__/workspace/synthetic-system-graph.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from "vitest";-import { collapseToRepos } from "../../src/workspace/system-map/collapse";+import { buildLevelView } from "../../src/workspace/system-map/levels";import { ESHOP_KIND_MIX, makeSyntheticSystemGraph } from "./fixtures/synthetic-system-graph";describe("makeSyntheticSystemGraph", () => {@@ -34,8 +34,8 @@ describe("makeSyntheticSystemGraph", () => {}// Package edges land only on library repos, which concentrates them in hubs.expect(g.edges.filter((e) => e.kind === "package").every((e) => e.target.includes(".lib"))).toBe(true);- // The collapse path reads it like a real artifact.- expect(collapseToRepos(g).nodes).toHaveLength(30);+ // The levels model reads it like a real artifact.+ expect(buildLevelView(g).nodes.length).toBeGreaterThan(0);});it("tags groups only when asked for more than one", () => {diff --git a/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts b/packages/ui/__tests__/workspace/system-map-ai-prompt.test.tsindex 63d401867..4df75c54b 100644--- a/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts+++ b/packages/ui/__tests__/workspace/system-map-ai-prompt.test.ts@@ -92,11 +92,10 @@ const graph: SystemGraph = {};describe("system map model", () => {- it("puts a file in its deepest service, else the repo root, and in its repo when collapsed", () => {- const resolve = serviceResolver(graph, false);+ it("puts a file in its deepest service, else the repo root", () => {+ const resolve = serviceResolver(graph);expect(resolve("mono", "packages/web/src/x.ts")).toBe("mono::packages/web");expect(resolve("mono", "packages/website/x.ts")).toBe("mono");- expect(serviceResolver(graph, true)("mono", "packages/web/x.ts")).toBe("mono");});it("counts a service's contracts by role and type, most linked first", () => {@@ -112,7 +111,7 @@ describe("system map model", () => {total: 4,},"mono::packages/web",- serviceResolver(graph, false),+ serviceResolver(graph),);expect(summary.consumes).toEqual({ http: 2 });expect(summary.provides).toEqual({ code: 1 });@@ -120,7 +119,7 @@ describe("system map model", () => {});it("attributes unmatched consumers and unused providers to the owning service", () => {- const resolve = serviceResolver(graph, false);+ const resolve = serviceResolver(graph);expect(serviceDiagnostics(graph.diagnostics, "mono::packages/web", resolve)).toEqual({unmatched: 1,unmatchedByReason: { no_provider: 1 },@@ -134,7 +133,7 @@ describe("system map model", () => {const links = edgeLinks(e,[link({}), link({ consumer_file: "server/r.py" }), link({ contract_type: "code" }), link({})],- serviceResolver(graph, false),+ serviceResolver(graph),);// Wrong service, wrong type and a duplicate are all dropped.expect(links).toHaveLength(1);diff --git a/packages/ui/__tests__/workspace/system-map-canvas-v2.test.tsx b/packages/ui/__tests__/workspace/system-map-canvas-v2.test.tsxnew file mode 100644index 000000000..7f7542dda--- /dev/null+++ b/packages/ui/__tests__/workspace/system-map-canvas-v2.test.tsx@@ -0,0 +1,298 @@+import type React from "react";+import { describe, it, expect, vi, beforeAll } from "vitest";+import { render, screen, fireEvent, act } from "@testing-library/react";+import type { SystemEdge, SystemGraph, SystemNode } from "@repowise-dev/types";+import { SystemMap } from "../../src/workspace/system-map/system-map";+import { SystemMapGroupNode } from "../../src/workspace/system-map/system-map-group-node";+import { SystemMapLensBadge } from "../../src/workspace/system-map/system-map-lens-badge";+import { bandPairs, BandPanel } from "../../src/workspace/system-map/system-map-aggregate-panel";+import { breadcrumbTrail } from "../../src/workspace/system-map/system-map-breadcrumb";+import { buildLevelView } from "../../src/workspace/system-map/levels";+import { scopeCaption, truncationSentence, hiddenFamiliesSentence } from "../../src/workspace/system-map/scope-caption";+import { resolveSelection } from "../../src/workspace/system-map/selection-fix";+import { toFlowElements } from "../../src/workspace/system-map/flow-elements";+import { bandSentence, groupSourceLabel, healthCounts, healthSummaryText } from "../../src/workspace/system-map/aggregate-facts";+import { ESTATE_VIEW, openContainer } from "../../src/workspace/system-map/view-state";+import { ReactFlowProvider } from "@xyflow/react";++beforeAll(() => {+ class RO {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ vi.stubGlobal("ResizeObserver", RO);+});++function node(id: string, group?: 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,+ ...(group ? { group } : {}),+ };+}++function edge(source: string, target: string, over: Partial<SystemEdge> = {}): SystemEdge {+ return {+ id: `${source}->${target}`,+ source,+ target,+ kind: "http",+ match_type: "exact",+ confidence: 1,+ weight: 1,+ structural: true,+ contract_refs: [],+ ...over,+ };+}++/**+ * Two declared groups and a library only packages reach: storefront calls+ * ordering three times, ordering calls itself inside, and the library sits+ * in the tray at the estate.+ */+const grouped: SystemGraph = {+ version: 1,+ generated_at: "2026-10-24T00:00:00Z",+ nodes: [+ node("webapp", "tag:storefront"),+ node("mobile", "tag:storefront"),+ node("ordering.api", "tag:ordering"),+ node("ordering.worker", "tag:ordering"),+ node("shared.lib"),+ ],+ edges: [+ edge("webapp", "ordering.api", { weight: 2 }),+ edge("mobile", "ordering.api", { kind: "event", strategy: "gateway_route" }),+ edge("ordering.worker", "ordering.api", { kind: "event" }),+ edge("ordering.api", "shared.lib", { id: "ordering.api->shared.lib:pkg", kind: "package" }),+ ],+ groups: [+ { id: "tag:storefront", label: "Storefront", source: "tag", member_count: 2 },+ { id: "tag:ordering", label: "Ordering", source: "tag", member_count: 2 },+ ],+};++describe("estate -> open group -> back", () => {+ it("draws group cards and a band at the estate, opens a group in place, and Escape backs out", async () => {+ const { container } = render(<SystemMap graph={grouped} estateLabel="eShop" />);+ expect(await screen.findByText(/drawing 2 groups and a tray of 1 service/i)).toBeInTheDocument();+ expect(screen.getByText(/1 band carrying 3 links/i)).toBeInTheDocument();+ // No breadcrumb at the estate: it appears once the map is somewhere narrower.+ expect(screen.queryByRole("navigation", { name: "Graph location" })).toBeNull();++ // Storefront's card offers Open; the band prints its count.+ const opens = await screen.findAllByText("Open ›");+ expect(opens.length).toBeGreaterThanOrEqual(2);+ fireEvent.click(container.querySelector('[data-id="group:tag:ordering"] button')!);++ expect(await screen.findByText(/drawing 1 group, 2 services and a tray/i)).toBeInTheDocument();+ const crumbs = screen.getByRole("navigation", { name: "Graph location" });+ expect(crumbs).toHaveTextContent("eShop");+ expect(crumbs).toHaveTextContent("Ordering");++ await act(async () => {+ fireEvent.keyDown(container.querySelector(".react-flow")!, { key: "Escape" });+ });+ expect(await screen.findByText(/drawing 2 groups and a tray/i)).toBeInTheDocument();+ expect(screen.queryByRole("navigation", { name: "Graph location" })).toBeNull();+ });++ it("opens a group with Enter on its focused card, and reports the level to a controlling host", async () => {+ const onViewChange = vi.fn();+ const { container } = render(<SystemMap graph={grouped} view={ESTATE_VIEW} onViewChange={onViewChange} />);+ await screen.findByText(/drawing 2 groups/i);+ const card = await vi.waitFor(() => {+ const el = container.querySelector('.react-flow__node[data-id="group:tag:storefront"]');+ if (!el) throw new Error("not drawn yet");+ return el;+ });+ fireEvent.keyDown(card, { key: "Enter" });+ expect(onViewChange).toHaveBeenCalledWith({ ...ESTATE_VIEW, open: ["tag:storefront"] });+ });++ it("shows a hidden family when the edge filter chip is pressed, and names it in the caption until then", async () => {+ render(<SystemMap graph={grouped} />);+ expect(await screen.findByText(/hidden by the edge filter: 1 build relationship \(package dependencies\)/i)).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: /build/i }));+ expect(screen.queryByText(/hidden by the edge filter/i)).toBeNull();+ });++ it("opens the group holding a service selected from outside the map", async () => {+ const onViewChange = vi.fn();+ render(+ <SystemMap+ graph={grouped}+ view={ESTATE_VIEW}+ onViewChange={onViewChange}+ selection={{ type: "node", id: "webapp" }}+ onSelectionChange={() => {}}+ />,+ );+ await screen.findByRole("region", { name: "webapp" });+ expect(onViewChange).toHaveBeenCalledWith({ ...ESTATE_VIEW, open: ["tag:storefront"] });+ });++ it("opens the group again when the same hidden service is selected a second time", async () => {+ const onViewChange = vi.fn();+ const props = { graph: grouped, view: ESTATE_VIEW, onViewChange, onSelectionChange: () => {} };+ const { rerender } = render(<SystemMap {...props} selection={{ type: "node", id: "webapp" }} />);+ await screen.findByRole("region", { name: "webapp" });+ rerender(<SystemMap {...props} selection={null} />);+ rerender(<SystemMap {...props} selection={{ type: "node", id: "webapp" }} />);+ await screen.findByRole("region", { name: "webapp" });+ expect(onViewChange).toHaveBeenCalledTimes(2);+ });+});++describe("caption", () => {+ it("states the draw budget's truncation in words", () => {+ const many: SystemGraph = {+ ...grouped,+ groups: [],+ nodes: Array.from({ length: 12 }, (_, i) => node(`s${i}`)),+ edges: Array.from({ length: 11 }, (_, i) => edge(`s${i}`, `s${i + 1}`)),+ };+ const view = buildLevelView(many, {}, { nodes: 5, edges: 3 });+ const sentence = truncationSentence(view)!;+ expect(sentence).toMatch(/^Over the draw budget of 5 cards and 3 lines: /);+ expect(sentence).toMatch(/services are folded into "\+N more" cards/);+ expect(sentence).toMatch(/weakest lines \(\d+ links\) are not drawn/);+ expect(scopeCaption(view, (id) => id)).toContain(sentence);+ expect(truncationSentence(buildLevelView(many))).toBeNull();+ });++ it("names every hidden family with its count, and nothing when all present are drawn", () => {+ const g: SystemGraph = { ...grouped, edges: [...grouped.edges, edge("webapp", "mobile", { id: "co", kind: "co_change", structural: false })] };+ expect(hiddenFamiliesSentence(buildLevelView(g))).toBe(+ "Hidden by the edge filter: 1 Build relationship (package dependencies) and 1 History relationship (files changed together).",+ );+ expect(hiddenFamiliesSentence(buildLevelView(g, { families: new Set(["runtime", "build", "history"]) }))).toBeNull();+ });+});++describe("selection against the drawn level", () => {+ const edgesById = new Map(grouped.edges.map((e) => [e.id, e]));++ it("maps a service onto its card, or opens the group that holds it", () => {+ const estate = buildLevelView(grouped);+ expect(resolveSelection({ type: "node", id: "webapp" }, estate, edgesById, ESTATE_VIEW).fix).toEqual({+ ...ESTATE_VIEW,+ open: ["tag:storefront"],+ });+ const opened = openContainer(ESTATE_VIEW, "tag:storefront");+ const view = buildLevelView(grouped, { open: ["tag:storefront"] });+ expect(resolveSelection({ type: "node", id: "webapp" }, view, edgesById, opened)).toEqual({+ drawnId: "webapp",+ drawnKind: "node",+ fix: null,+ });+ });++ it("asks for a hidden family to be shown for an edge of it", () => {+ const fix = resolveSelection({ type: "edge", id: "ordering.api->shared.lib:pkg" }, buildLevelView(grouped), edgesById, ESTATE_VIEW).fix;+ expect(fix?.families).toEqual(["runtime", "data", "build"]);+ });+});++describe("aggregate facts", () => {+ it("names where a group came from", () => {+ expect(groupSourceLabel("tag:storefront", "tag", 4)).toBe("tag: storefront");+ expect(groupSourceLabel("name:ordering", "name", 3)).toBe("name: ordering.*");+ expect(groupSourceLabel("linked:a", "linked", 6)).toBe("linked: 6 services");+ expect(groupSourceLabel("x", null, 2)).toBeNull();+ });++ it("marks health exceptions and keeps healthy quiet", () => {+ expect(healthSummaryText(healthCounts([9.5, 9.1]))).toBe("All healthy");+ expect(healthSummaryText(healthCounts([9.5, 2, 5, 6]))).toBe("1 Alert, 2 Warning");+ expect(healthSummaryText(healthCounts([null]))).toBe("No health scores");+ });++ it("puts a band in one sentence with its kind mix and gateway share", () => {+ const view = buildLevelView(grouped);+ const band = view.edges.find((e) => e.type === "band")!;+ expect(band.type === "band" && bandSentence("Storefront", "Ordering", band.summary)).toBe(+ "Storefront depends on Ordering: 3 links. HTTP 2, Event 1, 1 of them through a gateway.",+ );+ });+});++describe("cards and rail", () => {+ it("renders a group card with its source, counts, health exception and Open", () => {+ const view = buildLevelView(grouped);+ const health = new Map([["webapp", { score: 30 }], ["mobile", { score: 95 }]]);+ const flow = toFlowElements({+ view,+ positions: new Map(view.nodes.map((n) => [n.id, { x: 0, y: 0, width: 240, height: 104 }])),+ nodesById: new Map(grouped.nodes.map((n) => [n.id, n])),+ edgesById: new Map(grouped.edges.map((e) => [e.id, e])),+ healthByRepo: health,+ });+ const card = flow.nodes.find((n) => n.id === "group:tag:storefront")!;+ const Node = SystemMapGroupNode as unknown as (p: { data: unknown; selected: boolean }) => React.ReactElement;+ render(+ <ReactFlowProvider>+ <Node data={card.data} selected={false} />+ </ReactFlowProvider>,+ );+ expect(screen.getByText("Storefront")).toBeInTheDocument();+ expect(screen.getByText("tag: storefront")).toBeInTheDocument();+ expect(screen.getByText(/2 services · 2 repos/)).toBeInTheDocument();+ expect(screen.getByText("Alert")).toBeInTheDocument();+ expect(screen.getByText(/in 0 · out 3/)).toBeInTheDocument();+ expect(screen.getByText("Open ›")).toBeInTheDocument();+ // The band joining the two groups carries the count the card states.+ expect(flow.edges.find((e) => e.type === "systemBand")?.ariaLabel).toMatch(/3 links/);+ });++ it("lists a band's service pairs, strongest first, and selects one", () => {+ const view = buildLevelView(grouped);+ const band = view.edges.find((e) => e.type === "band")!;+ if (band.type !== "band") throw new Error("expected a band");+ const edgesById = new Map(grouped.edges.map((e) => [e.id, e]));+ expect(bandPairs(band, edgesById).map((p) => `${p.source}>${p.target}:${p.summary.links}`)).toEqual([+ "webapp>ordering.api:2",+ "mobile>ordering.api:1",+ ]);+ const onSelect = vi.fn();+ render(+ <BandPanel+ band={band}+ sourceLabel="Storefront"+ targetLabel="Ordering"+ nodesById={new Map(grouped.nodes.map((n) => [n.id, n]))}+ edgesById={edgesById}+ onSelect={onSelect}+ onClose={() => {}}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: /webapp → ordering.api/ }));+ expect(onSelect).toHaveBeenCalledWith({ type: "edge", id: "webapp->ordering.api" });+ });++ it("draws a lens badge in ink with a word, never in a health hue", () => {+ const { container } = render(<SystemMapLensBadge badge={{ label: "3 breaking", tone: "danger" }} />);+ const badge = container.firstElementChild as HTMLElement;+ expect(badge).toHaveTextContent("3 breaking");+ expect(badge.style.color).toBe("var(--color-text-primary)");+ expect(badge.outerHTML).not.toMatch(/color-error|color-warning/);+ });++ it("builds the breadcrumb chain Estate / Group / Service", () => {+ const focus = { ...ESTATE_VIEW, focus: "ordering.api" };+ expect(breadcrumbTrail(grouped, "focus", focus).map((c) => c.label)).toEqual(["Ordering", "ordering.api"]);+ expect(breadcrumbTrail(grouped, "focus", focus)[0]!.target).toEqual({ ...ESTATE_VIEW, open: ["tag:ordering"] });+ expect(breadcrumbTrail(grouped, "estate", ESTATE_VIEW)).toEqual([]);+ });+});diff --git a/packages/ui/__tests__/workspace/system-map-logic.test.ts b/packages/ui/__tests__/workspace/system-map-logic.test.tsindex 8341759be..8090f28e8 100644--- a/packages/ui/__tests__/workspace/system-map-logic.test.ts+++ b/packages/ui/__tests__/workspace/system-map-logic.test.ts@@ -1,12 +1,5 @@import { describe, it, expect } from "vitest";import type { SystemEdge, SystemGraph, SystemNode } from "@repowise-dev/types";-import { collapseToRepos } from "../../src/workspace/system-map/collapse";-import {- applyCollapse,- applyView,- computeSystemMapPositions,- layoutSignature,-} from "../../src/workspace/system-map/layout";import {edgeKindStyle,edgeLabel,@@ -67,129 +60,6 @@ function graph(nodes: SystemNode[], edges: SystemEdge[]): SystemGraph {return { version: 1, generated_at: "2026-06-19T00:00:00Z", nodes, edges, diagnostics: {} as never };}-describe("collapseToRepos", () => {- it("merges services of a repo into one node and sums their counts", () => {- const g = graph(- [- node("api::svc/a", "api", { provider_count: 2, contract_types: ["http"] }),- node("api::svc/b", "api", { consumer_count: 3, contract_types: ["grpc"] }),- node("web", "web", { kind: "frontend" }),- ],- [edge("web", "api::svc/a")],- );- const collapsed = collapseToRepos(g);- expect(collapsed.nodes.map((n) => n.id).sort()).toEqual(["api", "web"]);- const api = collapsed.nodes.find((n) => n.id === "api")!;- expect(api.provider_count).toBe(2);- expect(api.consumer_count).toBe(3);- expect(api.contract_types).toEqual(["grpc", "http"]);- expect(api.service_path).toBeNull();- });-- it("drops intra-repo edges and merges parallel cross-repo edges", () => {- const g = graph(- [node("api::a", "api"), node("api::b", "api"), node("web", "web")],- [- edge("api::a", "api::b"), // intra-repo → dropped- edge("web", "api::a", { weight: 1, confidence: 0.6, match_type: "candidate" }),- edge("web", "api::b", { weight: 2, confidence: 0.9, match_type: "exact" }),- ],- );- const collapsed = collapseToRepos(g);- expect(collapsed.edges).toHaveLength(1);- const e = collapsed.edges[0]!;- expect(e.source).toBe("web");- expect(e.target).toBe("api");- expect(e.weight).toBe(3); // 1 + 2- expect(e.confidence).toBe(0.9); // max- expect(e.match_type).toBe("exact"); // strongest- });-- it("merges the lean map view's counts where it has no refs to merge", () => {- const { contract_refs: _a, ...a } = edge("web", "api::a", { ref_count: 2 });- const { contract_refs: _b, ...b } = edge("web", "api::b", { ref_count: 3 });- const { diagnostics: _d, ...lean } = graph([node("api::a", "api"), node("api::b", "api"), node("web", "web")], [a, b]);- const collapsed = collapseToRepos(lean);- expect(collapsed.edges[0]!.ref_count).toBe(5);- expect(collapsed.edges[0]!.contract_refs).toBeUndefined();- expect(collapsed.diagnostics).toBeUndefined();- });-- it("keeps different edge kinds between the same repos distinct", () => {- const g = graph(- [node("web", "web"), node("api", "api")],- [edge("web", "api", { kind: "http" }), edge("web", "api", { kind: "co_change", structural: false })],- );- const collapsed = collapseToRepos(g);- expect(collapsed.edges).toHaveLength(2);- expect(new Set(collapsed.edges.map((e) => e.kind))).toEqual(new Set(["http", "co_change"]));- });-- it("flags a repo with no surviving edges as isolated", () => {- const g = graph([node("api::a", "api"), node("api::b", "api"), node("lonely", "lonely")], [edge("api::a", "api::b")]);- const collapsed = collapseToRepos(g);- expect(collapsed.nodes.find((n) => n.id === "lonely")!.is_isolated).toBe(true);- // api had only an intra-repo edge → also isolated after collapse- expect(collapsed.nodes.find((n) => n.id === "api")!.is_isolated).toBe(true);- });-- it("preserves a single-kind repo's kind, neutralizes a mixed one", () => {- const g = graph(- [node("libs::x", "libs", { kind: "library" }), node("libs::y", "libs", { kind: "library" })],- [],- );- expect(collapseToRepos(g).nodes[0]!.kind).toBe("library");- const mixed = graph(- [node("app::x", "app", { kind: "frontend" }), node("app::y", "app", { kind: "worker" })],- [],- );- expect(collapseToRepos(mixed).nodes[0]!.kind).toBe("service");- });-- it("keeps the strategy of the strongest merged link, as the core builder does", () => {- const g = graph(- [node("api::a", "api"), node("api::b", "api"), node("gw", "gw")],- [- edge("gw", "api::a", { confidence: 0.6, strategy: "prefix_stripped" }),- edge("gw", "api::b", { confidence: 1, strategy: "gateway_route" }),- ],- );- expect(collapseToRepos(g).edges[0]!.strategy).toBe("gateway_route");- const weakerSecond = graph(g.nodes, [g.edges[1]!, { ...g.edges[0]!, id: "x" }]);- expect(collapseToRepos(weakerSecond).edges[0]!.strategy).toBe("gateway_route");- });-});--describe("applyView", () => {- const g = graph(- [node("a", "a"), node("b", "b")],- [edge("a", "b", { kind: "http" }), edge("a", "b", { id: "cc", kind: "co_change", structural: false })],- );-- it("filters edges to the visible kinds, keeping all nodes", () => {- const view = { visibleKinds: new Set(["http"] as const), collapsed: false };- const out = applyView(g, view);- expect(out.edges).toHaveLength(1);- expect(out.edges[0]!.kind).toBe("http");- expect(out.nodes).toHaveLength(2);- });-- it("hides everything when no kinds are visible", () => {- const out = applyView(g, { visibleKinds: new Set(), collapsed: false });- expect(out.edges).toHaveLength(0);- });-- it("collapses before filtering", () => {- const multi = graph(- [node("api::a", "api"), node("web", "web")],- [edge("web", "api::a", { kind: "http" })],- );- const out = applyView(multi, { visibleKinds: new Set(["http"] as const), collapsed: true });- expect(out.nodes.map((n) => n.id).sort()).toEqual(["api", "web"]);- expect(out.edges[0]!.target).toBe("api");- });-});-describe("edge-kind registry", () => {it("covers every kind in the union and display order", () => {expect(EDGE_KIND_ORDER).toHaveLength(7);@@ -529,53 +399,3 @@ describe("buildDsm", () => {});});-describe("layout stability under filtering", () => {- const g = graph(- [node("api", "api"), node("web", "web")],- [- edge("web", "api"),- edge("api", "web", { id: "api->web:co", kind: "co_change", structural: false }),- ],- );-- it("lays out the whole shape while drawing only the filtered edges", () => {- const all = new Set(["http", "co_change"] as const);- const httpOnly = new Set(["http"] as const);-- // What we lay out keeps every edge, so a filter cannot move a node…- expect(applyCollapse(g, false).edges).toHaveLength(2);-- // …while the drawn graph really does lose the filtered edge.- expect(applyView(g, { visibleKinds: httpOnly, collapsed: false }).edges.map((e) => e.id)).toEqual([- "web->api",- ]);- expect(applyView(g, { visibleKinds: all, collapsed: false }).edges).toHaveLength(2);-- // The property that matters: the layout input is filter-independent.- expect(layoutSignature(applyView(g, { visibleKinds: all, collapsed: false }))).toBe(- layoutSignature(applyCollapse(g, false)),- );- expect(layoutSignature(applyView(g, { visibleKinds: httpOnly, collapsed: false }))).not.toBe(- layoutSignature(applyCollapse(g, false)),- );- });-- it("changes the layout signature when collapse changes the node set", () => {- const withServices = graph(- [node("api::svc/a", "api"), node("api::svc/b", "api"), node("web", "web")],- [edge("web", "api::svc/a")],- );- expect(layoutSignature(applyCollapse(withServices, false))).not.toBe(- layoutSignature(applyCollapse(withServices, true)),- );- });-});--describe("computeSystemMapPositions", () => {- it("lays out a graph with ELK", async () => {- const positions = await computeSystemMapPositions(- graph([node("api", "api"), node("web", "web")], [edge("web", "api")]),- );- expect(positions.size).toBe(2);- });-});diff --git a/packages/ui/__tests__/workspace/system-map-relayout.test.tsx b/packages/ui/__tests__/workspace/system-map-relayout.test.tsxindex 787ea68a9..8747cec60 100644--- a/packages/ui/__tests__/workspace/system-map-relayout.test.tsx+++ b/packages/ui/__tests__/workspace/system-map-relayout.test.tsx@@ -1,30 +1,27 @@/**- * Guards how often the System Map runs ELK. The layered layout is synchronous- * main-thread work with a fixed ~23ms floor even on the real 7-node workspace- * graph, so paying it for a filter toggle is both a stall and a layout jump.+ * Guards how often the System Map runs ELK. A family toggle changes only the+ * connectors, so it must never pay a layout or move a card; opening the tray+ * changes the drawn cards, so it earns one, and going back reuses the cache.*- * Lives in its own file because it wraps the layout module to count calls,+ * Lives in its own file because it wraps the ELK helper to count calls,* which the other system-map tests import unmocked.*/import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest";-import { render, screen, fireEvent } from "@testing-library/react";+import { render, screen, fireEvent, act, waitFor } from "@testing-library/react";import type { SystemEdge, SystemGraph, SystemNode } from "@repowise-dev/types";-const computePositions = vi.hoisted(() => vi.fn());+const layoutCalls = vi.hoisted(() => vi.fn());-vi.mock("../../src/workspace/system-map/layout", async (importOriginal) => {- const actual =- await importOriginal<- typeof import("../../src/workspace/system-map/layout")- >();+vi.mock("../../src/c4/layout/elk-c4-layout", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../../src/c4/layout/elk-c4-layout")>();return {...actual,// Wraps, rather than replaces, the real layout: the assertions are about// how often it runs and on what, not about what ELK returns.- computeSystemMapPositions: (graph: SystemGraph) => {- computePositions(graph);- return actual.computeSystemMapPositions(graph);+ computeC4Layout: (...args: Parameters<typeof actual.computeC4Layout>) => {+ layoutCalls(...args);+ return actual.computeC4Layout(args[0], args[1], { ...args[2], worker: false });},};});@@ -40,13 +37,13 @@ beforeAll(() => {vi.stubGlobal("ResizeObserver", RO);});-beforeEach(() => computePositions.mockClear());+beforeEach(() => layoutCalls.mockClear());-function node(id: string, repo: string): SystemNode {+function node(id: string): SystemNode {return {id,- repo,- service_path: id.includes("::") ? (id.split("::")[1] ?? null) : null,+ repo: id,+ service_path: null,name: id,kind: "service",provider_count: 0,@@ -58,11 +55,7 @@ function node(id: string, repo: string): SystemNode {};}-function edge(- source: string,- target: string,- over: Partial<SystemEdge> = {},-): SystemEdge {+function edge(source: string, target: string, over: Partial<SystemEdge> = {}): SystemEdge {return {id: `${source}->${target}`,source,@@ -77,68 +70,55 @@ function edge(};}+// web calls api; lib is reached only by a package edge, so it sits in the tray.const graph: SystemGraph = {version: 1,generated_at: "2026-06-19T00:00:00Z",- nodes: [- node("api::svc/a", "api"),- node("api::svc/b", "api"),- node("web", "web"),- ],- edges: [- edge("web", "api::svc/a"),- edge("api::svc/b", "web", {- id: "api::svc/b->web:co",- kind: "co_change",- structural: false,- }),- ],- diagnostics: {} as never,+ nodes: [node("api"), node("web"), node("lib")],+ edges: [edge("web", "api"), edge("api", "lib", { id: "api->lib:pkg", kind: "package" })],};describe("System Map relayout", () => {- it("does not re-run ELK when an edge-kind filter is toggled", async () => {+ it("does not re-run ELK when an edge family is toggled", async () => {render(<SystemMap graph={graph} />);- await screen.findByTitle(/toggle http edges/i);- expect(computePositions).toHaveBeenCalledTimes(1);+ await screen.findByText(/drawing 2 services/i);+ const runs = layoutCalls.mock.calls.length;+ expect(runs).toBeGreaterThan(0);- fireEvent.click(screen.getByTitle(/toggle co-change edges/i));- await screen.findByTitle(/toggle http edges/i);- fireEvent.click(screen.getByTitle(/toggle http edges/i));- await screen.findByTitle(/toggle http edges/i);+ fireEvent.click(screen.getByRole("button", { name: /build/i }));+ await screen.findByRole("button", { name: /build/i, pressed: true });+ fireEvent.click(screen.getByRole("button", { name: /runtime/i }));+ await screen.findByRole("button", { name: /runtime/i, pressed: false });- // Two filter toggles, still one layout: node placement describes the- // system, not the current lens.- expect(computePositions).toHaveBeenCalledTimes(1);+ // Two toggles, no new layout: placement describes the system, not the filter.+ expect(layoutCalls.mock.calls.length).toBe(runs);});- it("re-runs ELK when collapse changes the node set, then reuses the result", async () => {- render(<SystemMap graph={graph} />);- await screen.findByText(/drawing 3 services/i);- expect(computePositions).toHaveBeenCalledTimes(1);-- fireEvent.click(screen.getByRole("radio", { name: "Repositories" }));- await screen.findByText(/drawing 2 repositories/i);- // Collapsing genuinely changes the shape, so it earns a layout.- expect(computePositions).toHaveBeenCalledTimes(2);+ it("lays out again when the tray opens, and reuses the estate layout on the way back", async () => {+ const { container } = render(<SystemMap graph={graph} />);+ await screen.findByText(/drawing 2 services/i);+ const estateRuns = layoutCalls.mock.calls.length;- fireEvent.click(screen.getByRole("radio", { name: "Services" }));+ fireEvent.click(await screen.findByText("Open ›"));await screen.findByText(/drawing 3 services/i);- fireEvent.click(screen.getByRole("radio", { name: "Repositories" }));- await screen.findByText(/drawing 2 repositories/i);- // Both shapes are already cached for this mount.- expect(computePositions).toHaveBeenCalledTimes(2);+ // The tray's interior, then the root with the tray at its new size.+ await waitFor(() => expect(layoutCalls.mock.calls.length).toBe(estateRuns + 2));+ const openRuns = layoutCalls.mock.calls.length;++ // Escape backs out a level: the tray closes, and the cached estate comes back.+ await act(async () => {+ fireEvent.keyDown(container.querySelector(".react-flow")!, { key: "Escape" });+ });+ await screen.findByText(/drawing 2 services/i);+ await new Promise((r) => setTimeout(r, 50));+ expect(layoutCalls.mock.calls.length).toBe(openRuns);});- it("lays out from every edge, not only the visible ones", async () => {+ it("places cards from every family but History, whatever is drawn", async () => {render(<SystemMap graph={graph} />);- await screen.findByTitle(/toggle http edges/i);- fireEvent.click(screen.getByTitle(/toggle co-change edges/i));- await screen.findByTitle(/toggle http edges/i);-- const laidOut = computePositions.mock.calls[0]?.[0] as SystemGraph;- expect(laidOut.edges.map((e) => e.id).sort()).toEqual(- ["api::svc/b->web:co", "web->api::svc/a"].sort(),- );+ await screen.findByText(/drawing 2 services/i);+ const edges = layoutCalls.mock.calls.flatMap((c) => (c[1] as { id: string }[]).map((e) => e.id));+ // The package edge into the tray shapes the root even though Build is hidden.+ expect(edges.some((id) => id.includes("tray:"))).toBe(true);});});diff --git a/packages/ui/__tests__/workspace/system-map-view-state.test.ts b/packages/ui/__tests__/workspace/system-map-view-state.test.tsnew file mode 100644index 000000000..adff6de44--- /dev/null+++ b/packages/ui/__tests__/workspace/system-map-view-state.test.ts@@ -0,0 +1,103 @@+import { describe, it, expect } from "vitest";+import {+ ESTATE_VIEW,+ TRAY_OPEN_TOKEN,+ backOut,+ closeContainer,+ openContainer,+ parseMapView,+ toEstate,+ toLevelViewState,+ toggleFamily,+ writeMapView,+ type MapViewState,+} from "../../src/workspace/system-map/view-state";++const parse = (query: string) => {+ const p = new URLSearchParams(query);+ return parseMapView((k) => p.get(k));+};++describe("map view state in the URL", () => {+ it("reads open, focus, a, b and kinds", () => {+ expect(parse("open=tag:ordering,tray&focus=ordering.api&a=webapp&b=ordering.api&kinds=build,runtime")).toEqual({+ open: ["tag:ordering", "tray"],+ focus: "ordering.api",+ between: { a: "webapp", b: "ordering.api" },+ // Family order is fixed, whatever order the URL lists them in.+ families: ["runtime", "build"],+ });+ });++ it("reads an empty query as the estate, and ignores what names nothing", () => {+ expect(parse("")).toEqual(ESTATE_VIEW);+ // Unknown families read as the default, not as "draw nothing"; a lone `a` or a == b is no comparison.+ expect(parse("kinds=telepathy&a=x").families).toBeNull();+ expect(parse("a=x&b=x").between).toBeNull();+ expect(parse("open=g1,,g1").open).toEqual(["g1"]);+ });++ it("writes only what differs from the estate, and round-trips", () => {+ const state: MapViewState = {+ open: ["tag:ordering"],+ focus: null,+ between: { a: "webapp", b: "ordering.api" },+ families: ["runtime", "data", "build"],+ };+ const params = new URLSearchParams("lens=core&open=stale");+ writeMapView(params, state);+ expect(params.get("lens")).toBe("core");+ expect(params.toString()).toContain("open=tag%3Aordering");+ expect(params.get("kinds")).toBe("runtime,data,build");+ expect(parseMapView((k) => params.get(k))).toEqual(state);++ const estate = new URLSearchParams("open=g&kinds=runtime,data&focus=x");+ writeMapView(estate, { ...ESTATE_VIEW, families: ["runtime", "data"] });+ // The default families need no param.+ expect(estate.toString()).toBe("");+ });+});++describe("level transitions", () => {+ it("opens a group, focuses, compares, then backs out one level at a time", () => {+ let s = openContainer(ESTATE_VIEW, "g1");+ s = openContainer(s, "g2");+ s = { ...s, focus: "svc" };+ s = { ...s, between: { a: "svc", b: "other" } };+ const steps: MapViewState[] = [];+ for (let up = backOut(s); up; up = backOut(up)) steps.push(up);+ expect(steps.map((v) => [v.between ? "between" : "", v.focus ?? "", v.open.join(",")])).toEqual([+ ["", "svc", "g1,g2"],+ ["", "", "g1,g2"],+ ["", "", "g1"],+ ["", "", ""],+ ]);+ expect(backOut(ESTATE_VIEW)).toBeNull();+ });++ it("reopening a group moves it last, so Escape closes it first", () => {+ const s = openContainer(openContainer(openContainer(ESTATE_VIEW, "g1"), "g2"), "g1");+ expect(s.open).toEqual(["g2", "g1"]);+ expect(closeContainer(s, "g2").open).toEqual(["g1"]);+ });++ it("keeps the families when going back to the estate", () => {+ const s = toggleFamily(openContainer(ESTATE_VIEW, "g1"), "build");+ expect(s.families).toEqual(["runtime", "data", "build"]);+ expect(toEstate(s)).toEqual({ ...ESTATE_VIEW, families: ["runtime", "data", "build"] });+ expect(toggleFamily(s, "runtime").families).toEqual(["data", "build"]);+ });++ it("keeps the last drawn family, so the filter never empties the map", () => {+ const one = toggleFamily(ESTATE_VIEW, "data");+ expect(one.families).toEqual(["runtime"]);+ expect(toggleFamily(one, "runtime")).toBe(one);+ });++ it("hands the tray to the levels model separately from groups", () => {+ const level = toLevelViewState(openContainer(openContainer(ESTATE_VIEW, "g1"), TRAY_OPEN_TOKEN));+ expect([...(level.open ?? [])]).toEqual(["g1"]);+ expect(level.openTray).toBe(true);+ expect([...level.families!].sort()).toEqual(["data", "runtime"]);+ });+});diff --git a/packages/ui/__tests__/workspace/system-map.bench.ts b/packages/ui/__tests__/workspace/system-map.bench.tsindex 8dcdcfa6b..bb4cbb47e 100644--- a/packages/ui/__tests__/workspace/system-map.bench.ts+++ b/packages/ui/__tests__/workspace/system-map.bench.ts@@ -8,10 +8,11 @@*/import { bench, describe } from "vitest";-import type { SystemEdgeKind } from "@repowise-dev/types";-import { applyView, computeSystemMapPositions, layoutSignature } from "../../src/workspace/system-map/layout";-import { collapseToRepos } from "../../src/workspace/system-map/collapse";+import type { SystemEdge, SystemNode } from "@repowise-dev/types";import { buildLevelView } from "../../src/workspace/system-map/levels";+import { computeLevelLayout, levelLayoutInput } from "../../src/workspace/system-map/level-layout";+import { toFlowElements } from "../../src/workspace/system-map/flow-elements";+import { scopeCaption } from "../../src/workspace/system-map/scope-caption";import {orderByPrevious,planLevelLayout,@@ -25,10 +26,9 @@ import type { LevelsGraph } from "../../src/workspace/system-map/level-types";import { makeSyntheticSystemGraph } from "./fixtures/synthetic-system-graph";const SIZES = [30, 100, 300, 1000] as const;-const RUNTIME_KINDS = new Set<SystemEdgeKind>(["http", "grpc", "socket", "event", "db"]);/** ELK runs for seconds at the top sizes; a few samples are enough there. */const SLOW = { iterations: 3, time: 0, warmupIterations: 1 } as const;-/** ELK over the whole estate is skipped above this: the map only ever lays out drawn views (at most ~120 cards). */+/** ELK rows stop here: past it a cold layout of the drawn estate takes minutes in Node without a worker. */const ELK_MAX_SERVICES = 300;for (const services of SIZES) {@@ -53,19 +53,18 @@ for (const services of SIZES) {const previous = new Map(plan.root.nodes.map((n, i) => [n.id, { x: (i * 7919) % 2000, y: (i * 104729) % 1500 }] as const),);+ // What the canvas draws first: the estate (L0), its layout and its React Flow elements.+ const estate = buildLevelView(levels);+ // A grid stands in for ELK's positions: toFlowElements reads them, it does not depend on their values.+ const estatePositions = new Map(+ estate.nodes.map((n, i) => [n.id, { x: (i % 12) * 260, y: Math.floor(i / 12) * 140, width: 240, height: 104 }] as const),+ );+ const nodesById = new Map<string, SystemNode>(graph.nodes.map((n) => [n.id, n]));+ const edgesById = new Map<string, SystemEdge>(graph.edges.map((e) => [e.id, e]));describe(`system map, ${services} services / ${graph.edges.length} edges`, () => {- bench("applyView (runtime kinds)", () => {- applyView(graph, { visibleKinds: RUNTIME_KINDS, collapsed: false });- });- bench("collapseToRepos", () => {- collapseToRepos(graph);- });- bench("layoutSignature", () => {- layoutSignature(graph);- });bench("serviceResolver + neighbourGroups (hub, both ways)", () => {- serviceResolver(graph, false);+ serviceResolver(graph);neighbourGroups(graph, hub, "in");neighbourGroups(graph, hub, "out");});@@ -79,11 +78,6 @@ for (const services of SIZES) {bench("orderByPrevious (root scope)", () => {orderByPrevious(plan.root.nodes, previous);});- if (services <= ELK_MAX_SERVICES) {- bench("computeSystemMapPositions (ELK, whole estate)", async () => {- await computeSystemMapPositions(graph);- }, SLOW);- }bench("buildLevelView estate (cold payload, normalizes)", () => {buildLevelView({ ...levels });});@@ -99,5 +93,19 @@ for (const services of SIZES) {bench("servicesBetween (runtime pair)", () => {servicesBetween(levels, caller, callee);});+ if (services <= ELK_MAX_SERVICES) {+ bench("L0 layout: computeLevelLayout estate (ELK over the drawn view, cold cache)", async () => {+ await computeLevelLayout(levelLayoutInput(buildLevelView(levels), graph.edges), { worker: false });+ }, SLOW);+ bench("open group layout: computeLevelLayout with one group open (cold cache)", async () => {+ await computeLevelLayout(levelLayoutInput(view, graph.edges), { worker: false });+ }, SLOW);+ }+ bench("toFlowElements estate (cards, bands, health join)", () => {+ toFlowElements({ view: estate, positions: estatePositions, nodesById, edgesById });+ });+ bench("scopeCaption estate", () => {+ scopeCaption(estate, (id) => id);+ });});}diff --git a/packages/ui/__tests__/workspace/system-map.test.tsx b/packages/ui/__tests__/workspace/system-map.test.tsxindex b6da4c6e6..736da0691 100644--- a/packages/ui/__tests__/workspace/system-map.test.tsx+++ b/packages/ui/__tests__/workspace/system-map.test.tsx@@ -7,8 +7,6 @@ import { SystemMapLegend } from "../../src/workspace/system-map/system-map-legenimport { SystemMapEvidenceNotice } from "../../src/workspace/system-map/system-map-evidence-notice";import { SystemMapDrawer, selectionRepo } from "../../src/workspace/system-map/system-map-drawer";import { SystemMapFindings } from "../../src/workspace/system-map/system-map-findings";-import { resolveViewSelection } from "../../src/workspace/system-map/system-map-model";-import { collapseToRepos } from "../../src/workspace/system-map/collapse";import { SystemMapBlastPanel } from "../../src/workspace/system-map/system-map-blast-panel";import { SystemMapBreakingPanel } from "../../src/workspace/system-map/system-map-breaking-panel";import type { BreakingChange, BreakingChangeReport } from "@repowise-dev/types";@@ -79,51 +77,27 @@ describe("SystemMap empty states", () => {});describe("SystemMapFilters", () => {- it("only offers edge kinds present in the graph, with counts, and toggles them", () => {- const onToggleKind = vi.fn();+ it("offers one chip per family present, with counts, Build off, and toggles a family", () => {+ const onToggleFamily = vi.fn();render(<SystemMapFilters- kindCounts={new Map([["http", 3], ["co_change", 10]])}- visibleKinds={new Set(["http", "co_change"])}- onToggleKind={onToggleKind}- canCollapse- collapsed={false}- onCollapsedChange={() => {}}+ familyCounts={{ runtime: { edges: 18, links: 40 }, build: { edges: 26, links: 26 } }}+ kindCounts={{ runtime: { http: 7, event: 9, grpc: 2 }, build: { package: 26 } }}+ families={new Set(["runtime", "data"])}+ onToggleFamily={onToggleFamily}/>,);- expect(screen.getByTitle("Toggle HTTP edges")).toHaveTextContent("3");- expect(screen.getByTitle("Toggle Co-change edges")).toHaveTextContent("10");- expect(screen.queryByTitle("Toggle gRPC edges")).not.toBeInTheDocument();- fireEvent.click(screen.getByTitle("Toggle HTTP edges"));- expect(onToggleKind).toHaveBeenCalledWith("http");- });-- it("switches between services and repositories, and hides the switch when it would change nothing", () => {- const onCollapsedChange = vi.fn();- const { rerender } = render(- <SystemMapFilters- kindCounts={new Map([["http", 1]])}- visibleKinds={new Set(["http"])}- onToggleKind={() => {}}- canCollapse- collapsed={false}- onCollapsedChange={onCollapsedChange}- />,- );- fireEvent.click(screen.getByRole("radio", { name: "Repositories" }));- expect(onCollapsedChange).toHaveBeenCalledWith(true);-- rerender(- <SystemMapFilters- kindCounts={new Map([["http", 1]])}- visibleKinds={new Set(["http"])}- onToggleKind={() => {}}- canCollapse={false}- collapsed={false}- onCollapsedChange={onCollapsedChange}- />,- );- expect(screen.queryByRole("radio", { name: "Repositories" })).not.toBeInTheDocument();+ const runtime = screen.getByRole("button", { name: /runtime/i });+ expect(runtime).toHaveAttribute("aria-pressed", "true");+ expect(runtime).toHaveTextContent("18");+ expect(runtime.getAttribute("title")).toMatch(/HTTP 7, gRPC 2, Event 9/);+ const build = screen.getByRole("button", { name: /build/i });+ expect(build).toHaveAttribute("aria-pressed", "false");+ expect(build).toHaveTextContent("26");+ // Data is drawn by default but absent here, so it gets no dead chip.+ expect(screen.queryByRole("button", { name: /data/i })).not.toBeInTheDocument();+ fireEvent.click(build);+ expect(onToggleFamily).toHaveBeenCalledWith("build");});});@@ -233,35 +207,6 @@ describe("SystemMapFindings", () => {});});-describe("resolveViewSelection", () => {- const raw = graph(- [node("api::svc/a", { repo: "api", service_path: "svc/a" }), node("api::svc/b", { repo: "api", service_path: "svc/b" }), node("web")],- [edge("web", "api::svc/a", { id: "web->api::svc/a:http" }), edge("api::svc/a", "api::svc/b", { id: "a->b:package", kind: "package" })],- );-- it("maps a service onto its repository node in repo view", () => {- const view = collapseToRepos(raw);- expect(resolveViewSelection({ type: "node", id: "api::svc/a" }, raw, view, true).selection).toEqual({ type: "node", id: "api" });- });-- it("maps a cross-repo edge onto the merged edge, and asks for services for an edge inside one repo", () => {- const view = collapseToRepos(raw);- expect(resolveViewSelection({ type: "edge", id: "web->api::svc/a:http" }, raw, view, true).selection).toEqual({- type: "edge",- id: "web->api::http",- });- expect(resolveViewSelection({ type: "edge", id: "a->b:package" }, raw, view, true).fix).toEqual({ kind: "expand" });- });-- it("asks for a hidden edge kind to be shown", () => {- const view = { ...raw, edges: raw.edges.filter((e) => e.kind !== "package") };- expect(resolveViewSelection({ type: "edge", id: "a->b:package" }, raw, view, false).fix).toEqual({- kind: "show-edge-kind",- edgeKind: "package",- });- });-});-describe("SystemMapLegend", () => {it("keys only the line styles drawn, plus the three health bands", () => {render(<SystemMapLegend matchTypes={new Set(["exact", "inferred"])} />);@@ -323,7 +268,7 @@ describe("SystemMapDrawer", () => {],[edge("web", "api", { weight: 2, contract_refs: ["http::GET::/v1/users", "http::GET::/v1/users"] })],);- const base = { graph: g, rawGraph: g, collapsed: false, onClose: () => {} };+ const base = { graph: g, onClose: () => {} };it("renders a service with its role, neighbours and contracts, and selects a neighbour", () => {const onSelect = vi.fn();@@ -402,8 +347,6 @@ describe("SystemMapDrawer", () => {render(<SystemMapDrawergraph={behavioral}- rawGraph={behavioral}- collapsed={false}onClose={() => {}}onSelect={() => {}}selection={{ type: "edge", id: "web->api" }}@@ -419,7 +362,7 @@ describe("SystemMapDrawer", () => {const { contract_refs: _refs, ...lean } = edge("web", "api", { weight: 2, ref_count: 2 });const g2 = graph([node("web"), node("api")], [lean]);render(- <SystemMapDrawer graph={g2} rawGraph={g2} collapsed={false} onClose={() => {}} onSelect={() => {}} selection={{ type: "edge", id: "web->api" }} />,+ <SystemMapDrawer graph={g2} onClose={() => {}} onSelect={() => {}} selection={{ type: "edge", id: "web->api" }} />,);expect(screen.getByText("2 references")).toBeInTheDocument();expect(screen.getByText(/The graph kept 2 contract ids for this edge/)).toBeInTheDocument();@@ -432,7 +375,6 @@ describe("SystemMapDrawer", () => {<SystemMapDrawer{...base}graph={lean}- rawGraph={lean}selection={{ type: "node", id: "web" }}onSelect={() => {}}diagnostics={{@@ -456,9 +398,9 @@ 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, edge or collapsed id lives in", () => {+ it("names the repository a node or edge lives in, and none for an aggregate", () => {expect(selectionRepo(g, { type: "node", id: "api::svc/a" })).toBe("api");- expect(selectionRepo(g, { type: "node", id: "api" })).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, null)).toBeNull();@@ -471,11 +413,12 @@ describe("SystemMap chrome placement", () => {[edge("web", "api", { contract_refs: ["http:GET /v1/users"] })],);- it("opens the drawer outside the canvas for a selection", async () => {+ it("opens the details in the rail, beside the canvas, for a selection", async () => {const { container } = render(<SystemMap graph={g} selection={{ type: "node", id: "api" }} onSelectionChange={() => {}} />,);- const dialog = await screen.findByRole("dialog");+ const dialog = await screen.findByRole("region", { name: "api" });+ expect(dialog.closest("aside")).not.toBeNull();expect(within(dialog).getByText(/api provides 2 contracts/i)).toBeInTheDocument();const flow = container.querySelector(".react-flow")!;expect(flow.contains(dialog)).toBe(false);@@ -519,70 +462,28 @@ describe("SystemMap chrome placement", () => {const { rerender } = render(<SystemMap graph={g} selection={{ type: "node", id: "api" }} onSelectionChange={stale} />,);- await screen.findByRole("dialog");+ await screen.findByRole("region", { name: "api" });rerender(<SystemMap graph={g} selection={{ type: "node", id: "api" }} onSelectionChange={fresh} />);// "Depended on by" lists web; selecting it goes through a lifetime-memoised handler.- fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: /^web/ }));+ fireEvent.click(within(screen.getByRole("region", { name: "api" })).getByRole("button", { name: /^web/ }));expect(fresh).toHaveBeenCalledWith({ type: "node", id: "web" });expect(stale).not.toHaveBeenCalled();});- it("closing the drawer clears the selection the host holds", async () => {+ it("closing the rail clears the selection the host holds", async () => {const onSelectionChange = vi.fn();render(<SystemMap graph={g} selection={{ type: "node", id: "api" }} onSelectionChange={onSelectionChange} />);- await screen.findByRole("dialog");- fireEvent.click(screen.getByLabelText("Close panel"));+ await screen.findByRole("region", { name: "api" });+ fireEvent.click(screen.getByLabelText("Close details"));expect(onSelectionChange).toHaveBeenCalledWith(null);});it("states what it draws", async () => {render(<SystemMap graph={g} />);- expect(await screen.findByText(/drawing 2 services and 1 relationship\./i)).toBeInTheDocument();- });-- it("resolves a collapsed-view selection against the graph actually drawn", async () => {- const withServices = graph(- [- node("api::svc/a", { repo: "api", service_path: "svc/a", provider_count: 2 }),- node("api::svc/b", { repo: "api", service_path: "svc/b", provider_count: 3 }),- node("web", { repo: "web", kind: "frontend" }),- ],- [edge("web", "api::svc/a")],- );- render(- <SystemMap- graph={withServices}- // A collapsed edge id: it exists only once services are merged.- selection={{ type: "edge", id: "web->api::http" }}- onSelectionChange={() => {}}- />,- );- expect(screen.queryByText(/web calls api over HTTP/i)).not.toBeInTheDocument();-- fireEvent.click(await screen.findByRole("radio", { name: "Repositories" }));-- expect(await screen.findByText(/web calls api over HTTP/i)).toBeInTheDocument();- });-- it("shows the merged counts in repo view rather than a same-named service's", async () => {- const withServices = graph(- [- node("api", { repo: "api", provider_count: 2 }),- node("api::svc/b", { repo: "api", service_path: "svc/b", provider_count: 3 }),- node("web", { repo: "web", kind: "frontend" }),- ],- [edge("web", "api")],- );- render(<SystemMap graph={withServices} selection={{ type: "node", id: "api" }} onSelectionChange={() => {}} />);- expect(await screen.findByText(/api provides 2 contracts/i)).toBeInTheDocument();-- fireEvent.click(screen.getByRole("radio", { name: "Repositories" }));-- // 2 + 3, not 2: the repo node is the merge, not the same-named service.- expect(await screen.findByText(/api provides 5 contracts/i)).toBeInTheDocument();+ expect(await screen.findByText(/drawing 2 services, joined by 1 line between services\./i)).toBeInTheDocument();});});diff --git a/packages/ui/src/graph/graph-canvas-shell.tsx b/packages/ui/src/graph/graph-canvas-shell.tsxindex 254082f33..81094a3cb 100644--- a/packages/ui/src/graph/graph-canvas-shell.tsx+++ b/packages/ui/src/graph/graph-canvas-shell.tsx@@ -33,9 +33,21 @@ export interface GraphCanvasShellProps {* `footer` or `rail`.*/overlay?: React.ReactNode | undefined;+ /**+ * `page` (default) fills a full-bleed page and pads its rows. `section` sits+ * inside a padded page section: rows align with the section's text, and the+ * canvas and rail share one hairline frame.+ */+ variant?: "page" | "section" | undefined;className?: string | undefined;}+/** Row padding and canvas frame per variant. */+const VARIANT = {+ page: { pad: "px-4 sm:px-6", frame: "" },+ section: { pad: "", frame: "overflow-hidden rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-root)]" },+} as const;+/*** The single canvas container for every graph surface.*@@ -54,12 +66,14 @@ export function GraphCanvasShell({rail,footer,overlay,+ variant = "page",className,}: GraphCanvasShellProps) {+ const { pad, frame } = VARIANT[variant];return (<div className={cn("flex h-full flex-col", className)}>{(breadcrumb || title || description || titleActions) && (- <div className="flex shrink-0 flex-wrap items-start justify-between gap-2 px-4 pt-3 sm:px-6">+ <div className={cn("flex shrink-0 flex-wrap items-start justify-between gap-2 pt-3", pad)}><div className="min-w-0 max-w-2xl">{breadcrumb && <div className="mb-1 min-w-0">{breadcrumb}</div>}{title && (@@ -80,12 +94,13 @@ export function GraphCanvasShell({)}</div>)}- {banner && <div className="shrink-0 px-4 pt-3 sm:px-6">{banner}</div>}+ {banner && <div className={cn("shrink-0 pt-3", pad)}>{banner}</div>}<divclassName={cn("relative mt-3 grid min-h-0 flex-1",rail ? "lg:grid-cols-[minmax(0,1fr)_340px]" : "grid-cols-1",+ frame,)}>{/* A floor, so a tall header or key row cannot squeeze the subject to@@ -138,7 +153,7 @@ export function GraphCanvasShell({)}</div>- {footer && <div className="shrink-0 px-4 pb-3 pt-2 sm:px-6">{footer}</div>}+ {footer && <div className={cn("shrink-0 pb-3 pt-2", pad)}>{footer}</div>}</div>);}diff --git a/packages/ui/src/graph/graph-scope-breadcrumb.tsx b/packages/ui/src/graph/graph-scope-breadcrumb.tsxindex 6fd9776d7..c3d48332e 100644--- a/packages/ui/src/graph/graph-scope-breadcrumb.tsx+++ b/packages/ui/src/graph/graph-scope-breadcrumb.tsx@@ -10,19 +10,28 @@ import { ChevronRight, Home } from "lucide-react";* a keyboard shortcut nothing documents. Follows `ZoomBreadcrumb` on the* Knowledge Graph: a home crumb that returns to the overview, then the trail.*- * Two levels is the whole depth the Map has, so this takes a single leaf rather- * than a chain it would never fill.+ * The Map has two levels and passes a root and a leaf. A deeper surface (the+ * System Map's Estate / Group / Service) passes the crumbs between them as+ * `trail`, each one a way back to that level.*/+export interface GraphScopeCrumb {+ label: string;+ onClick: () => void;+}+export function GraphScopeBreadcrumb({rootLabel,leafLabel,onRoot,+ trail = [],}: {/** The whole-repo crumb, e.g. the repo name. */rootLabel: string;/** Where you are now. */leafLabel: string;onRoot: () => void;+ /** Levels between the root and the leaf, outermost first. */+ trail?: readonly GraphScopeCrumb[];}) {return (<nav@@ -38,8 +47,21 @@ export function GraphScopeBreadcrumb({<Home className="h-3.5 w-3.5" /><span className="max-w-[10rem] truncate">{rootLabel}</span></button>+ {trail.map((crumb, i) => (+ <span key={`${i}:${crumb.label}`} className="flex min-w-0 items-center gap-1">+ <ChevronRight className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)]" />+ <button+ type="button"+ onClick={crumb.onClick}+ title={`Back to ${crumb.label}`}+ className="max-w-[12rem] truncate rounded px-1.5 py-1 hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ {crumb.label}+ </button>+ </span>+ ))}<ChevronRight className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)]" />- <span className="max-w-[16rem] truncate px-1 py-1 font-medium text-[var(--color-text-primary)]">+ <span aria-current="location" className="max-w-[16rem] truncate px-1 py-1 font-medium text-[var(--color-text-primary)]">{leafLabel}</span></nav>diff --git a/packages/ui/src/workspace/system-map/activate.ts b/packages/ui/src/workspace/system-map/activate.tsnew file mode 100644index 000000000..21a0bbf2f--- /dev/null+++ b/packages/ui/src/workspace/system-map/activate.ts@@ -0,0 +1,40 @@+/**+ * 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.+ */++import type { DrawnEdge, DrawnNode } from "./level-types";+import type { SystemMapSelection } from "./types";+import { TRAY_OPEN_TOKEN } from "./view-state";++export type ActivateTrigger = "click" | "double" | "key";++export type Activation =+ | { kind: "select"; selection: SystemMapSelection }+ | { kind: "open"; id: string }+ | { kind: "folded"; serviceIds: readonly string[] }+ | null;++export function activateNode(n: DrawnNode | undefined, trigger: ActivateTrigger): Activation {+ if (!n) return null;+ const opens = trigger !== "click";+ switch (n.type) {+ case "service":+ return { kind: "select", selection: { type: "node", id: n.serviceId } };+ case "group":+ return opens && !n.open+ ? { kind: "open", id: n.groupId }+ : { kind: "select", selection: { type: "group", id: n.groupId } };+ case "tray":+ return n.open ? null : { kind: "open", id: TRAY_OPEN_TOKEN };+ default:+ return opens ? { kind: "folded", serviceIds: n.serviceIds } : null;+ }+}++export function activateEdge(e: DrawnEdge | undefined): Activation {+ if (!e) return null;+ return { kind: "select", selection: e.type === "edge" ? { type: "edge", id: e.edgeId } : { type: "band", id: e.id } };+}diff --git a/packages/ui/src/workspace/system-map/aggregate-facts.ts b/packages/ui/src/workspace/system-map/aggregate-facts.tsnew file mode 100644index 000000000..e3507442d--- /dev/null+++ b/packages/ui/src/workspace/system-map/aggregate-facts.ts@@ -0,0 +1,80 @@+/**+ * The words and figures an aggregate carries: where a group came from, how+ * healthy its services are, what a band's links are made of. Shared by the+ * cards, the bands, their accessible names and the rail, so a figure reads+ * the same everywhere it appears. Pure, no React.+ */++import { HEALTH_MARK_BANDS, healthMark, type HealthMarkBand } from "../../health/tokens";+import { EDGE_KIND_ORDER, edgeKindStyle } from "./edge-kinds";+import type { LinkSummary } from "./level-types";+import { plural } from "./system-map-model";++/**+ * Where a group came from, as a reader can check it: `tag: storefront`,+ * `name: ordering.*`, `linked: 6 services`. Null for an unknown source, so+ * nothing is invented.+ */+export function groupSourceLabel(groupId: string, source: string | null | undefined, members: number): string | null {+ const name = groupId.includes(":") ? groupId.slice(groupId.indexOf(":") + 1) : groupId;+ if (source === "tag") return `tag: ${name}`;+ if (source === "name") return `name: ${name}.*`;+ if (source === "linked") return `linked: ${plural(members, "service", "services")}`;+ return null;+}++export type HealthCounts = Record<HealthMarkBand, number> & { unscored: number };++/** Services per canonical health band; `score10` is null for a service with no score. */+export function healthCounts(scores: Iterable<number | null>): HealthCounts {+ const out: HealthCounts = { healthy: 0, warning: 0, alert: 0, unscored: 0 };+ for (const s of scores) {+ if (s == null) out.unscored += 1;+ else out[healthMark(s).band] += 1;+ }+ return out;+}++export interface HealthException {+ band: HealthMarkBand;+ count: number;+ label: string;+ color: string;+}++/** The bands worth marking on a group: Alert, then Warning. Healthy is the quiet default. */+export function healthExceptions(counts: HealthCounts): HealthException[] {+ return HEALTH_MARK_BANDS.filter((b) => b.band !== "healthy" && counts[b.band] > 0)+ .map((b) => ({ band: b.band, count: counts[b.band], label: b.label, color: b.color }))+ .reverse();+}++/** "All healthy", "1 Alert, 2 Warning", or "No health scores" when none of the services has one. */+export function healthSummaryText(counts: HealthCounts): string {+ const exceptions = healthExceptions(counts);+ if (exceptions.length > 0) return exceptions.map((e) => `${e.count} ${e.label}`).join(", ");+ if (counts.healthy > 0) return counts.unscored > 0 ? `${counts.healthy} Healthy, ${counts.unscored} unscored` : "All healthy";+ return "No health scores";+}++/** "HTTP 17, Event 6": links per kind, in the legend's kind order. */+export function kindMixText(kinds: Readonly<Record<string, number>>): string {+ const known = EDGE_KIND_ORDER.filter((k) => (kinds[k] ?? 0) > 0);+ const unknown = Object.keys(kinds).filter((k) => !known.includes(k as never) && (kinds[k] ?? 0) > 0).sort();+ return [...known, ...unknown].map((k) => `${edgeKindStyle(k).label} ${kinds[k]}`).join(", ");+}++/**+ * A band in one sentence: "storefront depends on catalog: 17 links. HTTP 17,+ * 2 of them through a gateway." The arrow runs consumer to provider, so the+ * verb is "depends on" whatever the kinds are.+ */+export function bandSentence(source: string, target: string, summary: LinkSummary): string {+ const head = `${source} depends on ${target}: ${plural(summary.links, "link", "links")}.`;+ const mix = kindMixText(summary.kinds);+ const gateway =+ summary.gatewayLinks > 0+ ? `, ${summary.gatewayLinks === summary.links ? "all" : summary.gatewayLinks} of them through a gateway`+ : "";+ return mix ? `${head} ${mix}${gateway}.` : head;+}diff --git a/packages/ui/src/workspace/system-map/collapse.ts b/packages/ui/src/workspace/system-map/collapse.tsdeleted file mode 100644index c8419ad09..000000000--- a/packages/ui/src/workspace/system-map/collapse.ts+++ /dev/null@@ -1,120 +0,0 @@-/**- * Pure transform: collapse the service-granular system graph into a- * repo-granular one. Services in the same repo merge into a single repo node;- * intra-repo edges drop out; cross-repo edges sharing a (source, target, kind)- * merge with summed weight and the strongest match type. Used by the map's- * "collapse to repos" toggle. Side-effect free and cheap to test.- */--import type { SystemEdge, SystemEdgeMatchType, SystemGraph, SystemNode } from "@repowise-dev/types";--/** Confidence ordering for picking the strongest match type when merging. */-const MATCH_RANK: Record<SystemEdgeMatchType, number> = {- exact: 3,- manual: 2,- candidate: 1,- inferred: 0,-};--/** Cap on retained drill-down refs per merged edge (mirrors the core bound). */-const MAX_REFS = 50;--function strongerMatch(a: SystemEdgeMatchType, b: SystemEdgeMatchType): SystemEdgeMatchType {- return MATCH_RANK[a] >= MATCH_RANK[b] ? a : b;-}--function repoNode(repo: string, members: SystemNode[]): SystemNode {- const contractTypes = new Set<string>();- let providerCount = 0;- let consumerCount = 0;- let orphanProvider = false;- let orphanConsumer = false;- for (const m of members) {- providerCount += m.provider_count;- consumerCount += m.consumer_count;- m.contract_types.forEach((t) => contractTypes.add(t));- orphanProvider = orphanProvider || m.is_orphan_provider;- orphanConsumer = orphanConsumer || m.is_orphan_consumer;- }- // A repo node's kind: keep a single service kind unless every member is a- // library or external (then surface that), so the collapsed view stays honest.- const kinds = new Set(members.map((m) => m.kind));- const kind: SystemNode["kind"] =- kinds.size === 1 ? (members[0]?.kind ?? "service") : "service";- return {- id: repo,- repo,- service_path: null,- name: repo,- kind,- provider_count: providerCount,- consumer_count: consumerCount,- contract_types: [...contractTypes].sort(),- is_orphan_provider: orphanProvider,- is_orphan_consumer: orphanConsumer,- is_isolated: false, // recomputed below from the collapsed edge set- };-}--export function collapseToRepos(graph: SystemGraph): SystemGraph {- const repoOf = new Map<string, string>();- const membersByRepo = new Map<string, SystemNode[]>();- for (const node of graph.nodes) {- repoOf.set(node.id, node.repo);- const list = membersByRepo.get(node.repo) ?? [];- list.push(node);- membersByRepo.set(node.repo, list);- }-- const nodes = [...membersByRepo.entries()]- .map(([repo, members]) => repoNode(repo, members))- .sort((a, b) => a.id.localeCompare(b.id));-- const merged = new Map<string, SystemEdge>();- for (const edge of graph.edges) {- const source = repoOf.get(edge.source) ?? edge.source;- const target = repoOf.get(edge.target) ?? edge.target;- if (source === target) continue; // intra-repo edge disappears on collapse- const key = `${source}->${target}::${edge.kind}`;- const existing = merged.get(key);- if (!existing) {- merged.set(key, {- ...edge,- id: key,- source,- target,- ...(edge.contract_refs ? { contract_refs: edge.contract_refs.slice(0, MAX_REFS) } : {}),- });- continue;- }- existing.weight += edge.weight;- // The strategy names the strongest link, as the core graph builder keeps it.- if (edge.confidence > existing.confidence) existing.strategy = edge.strategy ?? null;- existing.confidence = Math.max(existing.confidence, edge.confidence);- existing.match_type = strongerMatch(existing.match_type, edge.match_type);- if (existing.contract_refs && existing.contract_refs.length < MAX_REFS) {- existing.contract_refs = [...existing.contract_refs, ...(edge.contract_refs ?? [])].slice(0, MAX_REFS);- }- // A lean edge carries only its count; the sum can repeat an id two- // services share, as the merged ref list above can.- if (existing.ref_count != null) {- existing.ref_count = Math.min(existing.ref_count + (edge.ref_count ?? 0), MAX_REFS);- }- }-- const edges = [...merged.values()].sort((a, b) => a.id.localeCompare(b.id));- const connected = new Set<string>();- for (const e of edges) {- connected.add(e.source);- connected.add(e.target);- }- for (const n of nodes) n.is_isolated = !connected.has(n.id);-- return {- version: graph.version,- generated_at: graph.generated_at,- nodes,- edges,- ...(graph.diagnostics ? { diagnostics: graph.diagnostics } : {}),- };-}diff --git a/packages/ui/src/workspace/system-map/edge-families.ts b/packages/ui/src/workspace/system-map/edge-families.tsindex 7946aba7a..aef0b40d9 100644--- a/packages/ui/src/workspace/system-map/edge-families.ts+++ b/packages/ui/src/workspace/system-map/edge-families.ts@@ -64,3 +64,23 @@ export function familyCounts(export function linkWeight(edge: { weight: number }): number {return edge.weight > 1 ? edge.weight : 1;}++/** How a family is named on its chip, in the caption and in the legend. */+export const EDGE_FAMILY_COPY: Record<EdgeFamily, { label: string; meaning: string }> = {+ runtime: { label: "Runtime", meaning: "calls and events" },+ data: { label: "Data", meaning: "shared databases" },+ build: { label: "Build", meaning: "package dependencies" },+ history: { label: "History", meaning: "files changed together" },+};++/** Edges per kind inside each family, for a chip's hover ("HTTP 7, Event 9"). */+export function kindCountsByFamily(+ edges: Iterable<{ kind: string; family?: string | null | undefined }>,+): Partial<Record<EdgeFamily, Record<string, number>>> {+ const out: Partial<Record<EdgeFamily, Record<string, number>>> = {};+ for (const e of edges) {+ const row = (out[edgeFamilyOf(e)] ??= {});+ row[e.kind] = (row[e.kind] ?? 0) + 1;+ }+ return out;+}diff --git a/packages/ui/src/workspace/system-map/flow-elements.ts b/packages/ui/src/workspace/system-map/flow-elements.tsnew file mode 100644index 000000000..aa7e3fcc6--- /dev/null+++ b/packages/ui/src/workspace/system-map/flow-elements.ts@@ -0,0 +1,239 @@+/**+ * A drawn levels view plus its positions, as React Flow nodes and edges.+ * Joins what each card shows (service record, repo health, role, lens marks,+ * group health and source) onto the drawn ids. Cards with no position yet+ * (new to the view while its layout runs) are left out, with their children+ * and lines, so nothing flashes at the origin. Pure, no React rendering.+ */++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 { roleStyle } from "./architecture";+import { edgeLabel } from "./edge-kinds";+import type {+ DrawnBand,+ DrawnGroupNode,+ DrawnMoreNode,+ DrawnNode,+ DrawnServiceNode,+ DrawnSingleEdge,+ DrawnTrayNode,+} from "./level-types";+import type { LevelView } from "./levels";+import {+ resolveEdgeOverlay,+ resolveNodeOverlay,+ type NodeOverlayState,+ type RepoHealth,+ type SystemMapEdgeData,+ type SystemMapNodeData,+ type SystemMapOverlay,+} from "./types";++export interface GroupNodeData {+ group: DrawnGroupNode;+ sourceLabel: string | null;+ health: HealthCounts;+ /** Lens marks folded up from the members: highlighted when any is, dimmed when all are. */+ overlay: NodeOverlayState | null;+ [key: string]: unknown;+}++export interface TrayNodeData {+ tray: DrawnTrayNode;+ /** Names of the first services, for the closed card. */+ names: string[];+ [key: string]: unknown;+}++export interface MoreNodeData {+ more: DrawnMoreNode;+ [key: string]: unknown;+}++export interface BandEdgeData {+ band: DrawnBand;+ sentence: string;+ overlay: { highlighted: boolean; dimmed: boolean } | null;+ [key: string]: unknown;+}++export interface FlowInputs {+ view: LevelView;+ positions: ReadonlyMap<string, C4LayoutPosition> | null;+ nodesById: ReadonlyMap<string, SystemNode>;+ edgesById: ReadonlyMap<string, SystemEdge>;+ healthByRepo?: ReadonlyMap<string, RepoHealth> | undefined;+ overlay?: SystemMapOverlay | undefined;+ roleByNodeId?: ReadonlyMap<string, NodeArchitectureRole> | undefined;+ /** Drawn id to mark selected. */+ selectedId?: string | null | undefined;+}++export interface FlowElements {+ nodes: Node[];+ edges: Edge[];+}++/** Names on the tray's closed card before "+N more". */+const TRAY_NAMES = 3;++const ARROW = { type: MarkerType.ArrowClosed, width: 14, height: 14, color: "var(--color-diagram-edge)" } as const;+/** Bands are wide; an arrow in user units keeps one head size whatever the band's width. */+const BAND_ARROW = { ...ARROW, width: 16, height: 16, markerUnits: "userSpaceOnUse" } as const;++/** Members' lens marks on their group card, so a lens still reads at the estate. */+function groupOverlay(overlay: SystemMapOverlay | undefined, ids: readonly string[]): NodeOverlayState | null {+ if (!overlay) return null;+ const marks = ids.map((id) => resolveNodeOverlay(overlay, id));+ const highlighted = marks.some((m) => m?.highlighted);+ const dimmed = marks.length > 0 && marks.every((m) => m?.dimmed);+ return highlighted || dimmed ? { highlighted, dimmed } : null;+}++function bandOverlay(overlay: SystemMapOverlay | undefined, edgeIds: readonly string[]): BandEdgeData["overlay"] {+ if (!overlay) return null;+ const marks = edgeIds.map((id) => resolveEdgeOverlay(overlay, id));+ const highlighted = marks.some((m) => m?.highlighted);+ const dimmed = marks.length > 0 && marks.every((m) => m?.dimmed);+ return highlighted || dimmed ? { highlighted, dimmed } : null;+}++/** A drawn id's display name: a service's name, a group's label, or the aggregate's own words. */+export function drawnLabel(n: DrawnNode | undefined, nodesById: ReadonlyMap<string, SystemNode>): string {+ if (!n) return "";+ if (n.type === "service") return nodesById.get(n.serviceId)?.name ?? n.serviceId;+ if (n.type === "group") return n.label;+ if (n.type === "tray") return "Not linked at runtime";+ return `${n.serviceIds.length} more`;+}++type Shaped = { type: string; data: Record<string, unknown> } | null;++function serviceData(n: DrawnServiceNode, { nodesById, healthByRepo, overlay, roleByNodeId }: FlowInputs): Shaped {+ const node = nodesById.get(n.serviceId);+ if (!node) return null;+ const role = roleByNodeId?.get(n.serviceId);+ const data: SystemMapNodeData = {+ node,+ health: healthByRepo?.get(node.repo) ?? null,+ overlay: resolveNodeOverlay(overlay, n.serviceId),+ role: role ? roleStyle(role.role).label : null,+ };+ return { type: "systemService", data };+}++/** A service's repo health on the canonical 0-10 scale (repo health arrives 0-100); null when unscored. */+function score10(id: string, { nodesById, healthByRepo }: FlowInputs): number | null {+ const repo = nodesById.get(id)?.repo;+ const h = repo ? healthByRepo?.get(repo) : undefined;+ return h ? h.score / 10 : null;+}++function groupData(n: DrawnGroupNode, inputs: FlowInputs): Shaped {+ const data: GroupNodeData = {+ group: n,+ sourceLabel: groupSourceLabel(n.groupId, n.source, n.serviceIds.length),+ health: healthCounts(n.serviceIds.map((id) => score10(id, inputs))),+ overlay: groupOverlay(inputs.overlay, n.serviceIds),+ };+ return { type: "systemGroup", data };+}++function trayData(n: DrawnTrayNode, { nodesById }: FlowInputs): Shaped {+ const names = n.serviceIds.slice(0, TRAY_NAMES).map((id) => nodesById.get(id)?.name ?? id);+ const data: TrayNodeData = { tray: n, names };+ return { type: "systemTray", data };+}++function moreData(n: DrawnMoreNode): Shaped {+ const data: MoreNodeData = { more: n };+ return { type: "systemMore", data };+}++function nodeData(n: DrawnNode, inputs: FlowInputs): Shaped {+ switch (n.type) {+ case "service":+ return serviceData(n, inputs);+ case "group":+ return groupData(n, inputs);+ case "tray":+ return trayData(n, inputs);+ default:+ return moreData(n);+ }+}++function parentOf(n: DrawnNode): string | null {+ return n.type === "service" || n.type === "more" ? n.parentId : null;+}++function isOpenContainer(n: DrawnNode): boolean {+ return (n.type === "group" || n.type === "tray") && n.open;+}++/** One React Flow node, or null when it has no position yet or its container is not drawn. */+function flowNode(n: DrawnNode, inputs: FlowInputs, placed: ReadonlySet<string>): Node | null {+ const pos = inputs.positions?.get(n.id);+ const parentId = parentOf(n);+ if (!pos || (parentId && !placed.has(parentId))) return null;+ const shaped = nodeData(n, inputs);+ if (!shaped) return null;+ return {+ id: n.id,+ type: shaped.type,+ position: { x: pos.x, y: pos.y },+ data: shaped.data,+ ...(parentId ? { parentId } : {}),+ // An open container sits under its cards and lines.+ ...(isOpenContainer(n) ? { width: pos.width, height: pos.height, zIndex: -1 } : {}),+ ...(inputs.selectedId === n.id ? { selected: true } : {}),+ ariaLabel: drawnLabel(n, inputs.nodesById),+ };+}++function singleEdge(e: DrawnSingleEdge, inputs: FlowInputs, name: (id: string) => string): Edge | null {+ const edge = inputs.edgesById.get(e.edgeId);+ if (!edge) return null;+ const data: SystemMapEdgeData = { edge, overlay: resolveEdgeOverlay(inputs.overlay, edge.id) };+ return {+ id: e.id,+ source: e.source,+ target: e.target,+ type: "systemEdge",+ markerEnd: ARROW,+ data,+ ariaLabel: `${name(e.source)} to ${name(e.target)}, ${edgeLabel(edge)}`,+ };+}++function bandEdge(e: DrawnBand, inputs: FlowInputs, name: (id: string) => string): Edge {+ const sentence = bandSentence(name(e.source), name(e.target), e.summary);+ const data: BandEdgeData = { band: e, sentence, overlay: bandOverlay(inputs.overlay, e.summary.edgeIds) };+ return { id: e.id, source: e.source, target: e.target, type: "systemBand", markerEnd: BAND_ARROW, data, ariaLabel: sentence };+}++export function toFlowElements(inputs: FlowInputs): FlowElements {+ const { view, positions, nodesById, selectedId } = inputs;+ if (!positions) return { nodes: [], edges: [] };+ const placed = new Set<string>();+ const nodes: Node[] = [];+ for (const n of view.nodes) {+ const flow = flowNode(n, inputs, placed);+ if (!flow) continue;+ placed.add(n.id);+ nodes.push(flow);+ }++ const drawnById = new Map(view.nodes.map((n) => [n.id, n]));+ const name = (id: string) => drawnLabel(drawnById.get(id), nodesById);+ const edges: Edge[] = [];+ for (const e of view.edges) {+ if (!placed.has(e.source) || !placed.has(e.target)) continue;+ const flow = e.type === "edge" ? singleEdge(e, inputs, name) : bandEdge(e, inputs, name);+ if (flow) edges.push(selectedId === e.id ? { ...flow, selected: true } : flow);+ }+ return { nodes, edges };+}diff --git a/packages/ui/src/workspace/system-map/index.ts b/packages/ui/src/workspace/system-map/index.tsindex e9ca17f70..b95421264 100644--- a/packages/ui/src/workspace/system-map/index.ts+++ b/packages/ui/src/workspace/system-map/index.ts@@ -7,12 +7,55 @@* still use them.*/-export {- SystemMap,- SYSTEM_MAP_CANVAS_HEIGHT,- SYSTEM_MAP_MINIMAP_MIN_NODES,- type SystemMapProps,-} from "./system-map";+export { SystemMap, SYSTEM_MAP_CANVAS_HEIGHT, type SystemMapProps } from "./system-map";+export { SystemMapCanvas, SYSTEM_MAP_MINIMAP_MIN_NODES, type SystemMapCanvasProps } from "./system-map-canvas";+export { SystemMapGroupNode } from "./system-map-group-node";+export { SystemMapTrayNode, SystemMapMoreNode } from "./system-map-tray-node";+export { SystemMapBand, BAND_STROKE, bandWidth } from "./system-map-band";+export { SystemMapLensBadge } from "./system-map-lens-badge";+export { SystemMapBreadcrumb, breadcrumbTrail, type SystemMapBreadcrumbProps } from "./system-map-breadcrumb";+export { GroupPanel, BandPanel, bandPairs } from "./system-map-aggregate-panel";+export { SystemMapActionsContext, useSystemMapActions, type SystemMapActions } from "./system-map-actions";+export { useSystemMapState, type SystemMapState, type SystemMapStateArgs } from "./use-system-map-state";+export {+ ESTATE_VIEW,+ MAP_VIEW_PARAMS,+ TRAY_OPEN_TOKEN,+ parseMapView,+ writeMapView,+ drawnFamilies,+ toLevelViewState,+ openContainer,+ closeContainer,+ toggleFamily,+ showFamily,+ backOut,+ toEstate,+ sameMapView,+ type MapViewState,+} from "./view-state";+export { resolveSelection, type ResolvedSelection } from "./selection-fix";+export { scopeCaption, hiddenFamiliesSentence, truncationSentence } from "./scope-caption";+export {+ toFlowElements,+ drawnLabel,+ type FlowInputs,+ type FlowElements,+ type GroupNodeData,+ type TrayNodeData,+ type MoreNodeData,+ type BandEdgeData,+} from "./flow-elements";+export {+ groupSourceLabel,+ healthCounts,+ healthExceptions,+ healthSummaryText,+ kindMixText,+ bandSentence,+ type HealthCounts,+ type HealthException,+} from "./aggregate-facts";export { SystemMapLegend, type SystemMapLegendProps } from "./system-map-legend";export { SystemMapEvidenceNotice, type SystemMapEvidenceNoticeProps } from "./system-map-evidence-notice";export {@@ -24,6 +67,8 @@ export {export { SystemMapLensControl, type SystemMapLens, type SystemMapLensControlProps } from "./system-map-lens";export {SystemMapDrawer,+ SystemMapRailFrame,+ drawerHasSubject,selectionRepo,cyclePrompt,type ContractRef,@@ -50,7 +95,6 @@ export {weightShort,plural,unmatchedReasonList,- resolveViewSelection,type SystemMapContract,type SystemMapRepoContracts,} from "./system-map-model";@@ -73,25 +117,15 @@ export {ROLE_ORDER,type RoleStyle,} from "./architecture";-export { useSystemMapLayout, type SystemMapLayout, type UseSystemMapLayoutArgs } from "./use-system-map-layout";export { useLevelLayout, type LevelLayout, type UseLevelLayoutArgs } from "./use-level-layout";-export { LEVEL_NODE_SIZES, CONTAINER_PADDING, type LevelNodeSizes } from "./layout-scopes";+export { LEVEL_NODE_SIZES, CONTAINER_PADDING, SYSTEM_MAP_NODE_SIZE, type LevelNodeSizes } from "./layout-scopes";export type { SystemMapPhase } from "./use-system-map-phases";-export {- applyView,- applyCollapse,- computeSystemMapPositions,- layoutSignature,- SYSTEM_MAP_NODE_SIZE,- type SystemMapView,-} from "./layout";export {SystemMapRailPanel,RailChip,RailEyebrow,type SystemMapRailPanelProps,} from "./system-map-rail";-export { collapseToRepos } from "./collapse";export {SYSTEM_EDGE_KINDS,EDGE_KIND_ORDER,@@ -140,6 +174,8 @@ export { connectEdges, summarizeLinks, bandId, compareIds } from "./bands";export { DRAW_BUDGET, allocateSlots, capEdges, truncationReport, type BudgetContainer } from "./draw-budget";export {EDGE_FAMILY_ORDER,+ EDGE_FAMILY_COPY,+ kindCountsByFamily,DEFAULT_EDGE_FAMILIES,LINKED_FAMILIES,edgeFamily,diff --git a/packages/ui/src/workspace/system-map/layout-scopes.ts b/packages/ui/src/workspace/system-map/layout-scopes.tsindex 5b9bff627..d3be34645 100644--- a/packages/ui/src/workspace/system-map/layout-scopes.ts+++ b/packages/ui/src/workspace/system-map/layout-scopes.ts@@ -13,8 +13,7 @@import type { C4LayoutEdge, C4LayoutNode, C4LayoutPosition } from "../../c4/layout/elk-c4-layout";import { compareIds } from "./bands";-import { edgeFamily } from "./edge-families";-import { SYSTEM_MAP_NODE_SIZE } from "./layout";+import { edgeFamilyOf } from "./edge-families";import type { DrawnNode, LevelsEdge } from "./level-types";interface Size {@@ -22,6 +21,9 @@ interface Size {height: number;}+/** A service card's footprint on the map. */+export const SYSTEM_MAP_NODE_SIZE = { width: 208, height: 96 } as const;+/** Card footprints per drawn node type. Open containers are sized from their interior. */export interface LevelNodeSizes {service: Size;@@ -67,7 +69,7 @@ function nodeSize(n: DrawnNode, sizes: LevelNodeSizes): Size {/** Every family but History shapes placement; co-change is undirected and would add layers. */function shapesLayout(e: LevelsEdge): boolean {- return e.source !== e.target && edgeFamily(e.kind) !== "history";+ return e.source !== e.target && edgeFamilyOf(e) !== "history";}interface Placement {diff --git a/packages/ui/src/workspace/system-map/layout.ts b/packages/ui/src/workspace/system-map/layout.tsdeleted file mode 100644index 53f9e0a6c..000000000--- a/packages/ui/src/workspace/system-map/layout.ts+++ /dev/null@@ -1,77 +0,0 @@-/**- * Pure layout + filtering for the Live System Map. Filters the system graph to- * the visible edge kinds, optionally collapses to repos, then positions the- * nodes with the shared ELK helper (reused from the C4 view — one layout- * engine, no bespoke positioning). Returns plain data; the hook turns it into- * React Flow nodes/edges.- */--import { computeC4Layout, type C4LayoutPosition } from "../../c4/layout/elk-c4-layout";-import type { SystemEdgeKind, SystemGraph } from "@repowise-dev/types";-import { collapseToRepos } from "./collapse";--/** Uniform service-node footprint on the map. */-export const SYSTEM_MAP_NODE_SIZE = { width: 208, height: 96 } as const;--export interface SystemMapView {- /** Edge kinds to keep; an edge survives only if its kind is in the set. */- visibleKinds: ReadonlySet<SystemEdgeKind>;- /** Collapse services into one node per repo. */- collapsed: boolean;-}--/**- * Apply the view's filters to a raw system graph. Pure: returns a new graph;- * nodes are retained even when filtering leaves them edgeless (honest — an- * isolated service is real signal, not noise to hide).- */-export function applyView(graph: SystemGraph, view: SystemMapView): SystemGraph {- const base = applyCollapse(graph, view.collapsed);- const edges = base.edges.filter((e) => view.visibleKinds.has(e.kind));- return { ...base, edges };-}--/**- * The collapse half of the view, without the edge-kind filter. This is what the- * layout is computed from: collapsing genuinely changes the system's shape, but- * hiding an edge kind is a lens on the same shape and must not move nodes.- */-export function applyCollapse(graph: SystemGraph, collapsed: boolean): SystemGraph {- return collapsed ? collapseToRepos(graph) : graph;-}--/**- * Position every node via the shared ELK layered layout.- *- * Takes the *unfiltered* edge set on purpose. Node positions describe the system,- * not the current filter, so hiding an edge kind no longer rearranges the map- * underneath the reader — and no longer pays ELK's ~23ms floor on every toggle.- * The filtered edges are still the only ones drawn. ELK runs in a worker- * when one can start, so a large estate is slow to appear, never a frozen tab.- */-export function computeSystemMapPositions(graph: SystemGraph): Promise<Map<string, C4LayoutPosition>> {- return computeC4Layout(- graph.nodes.map((n) => ({- id: n.id,- width: SYSTEM_MAP_NODE_SIZE.width,- height: SYSTEM_MAP_NODE_SIZE.height,- })),- // Structural edges only: placement should read as dependency direction,- // and co-change pairs are undirected history that would add layers.- graph.edges- .filter((e) => e.structural)- .map((e) => ({ id: e.id, source: e.source, target: e.target })),- { worker: true },- );-}--/**- * Identity of a layout: the node set plus the edges that shape it. Two views with- * the same signature must get the same positions, which is what lets the hook- * skip ELK when only the edge-kind filter moved.- */-export function layoutSignature(graph: SystemGraph): string {- const nodes = graph.nodes.map((n) => n.id).sort();- const edges = graph.edges.map((e) => `${e.source}>${e.target}`).sort();- return `${nodes.join("|")}#${edges.join("|")}`;-}diff --git a/packages/ui/src/workspace/system-map/scope-caption.ts b/packages/ui/src/workspace/system-map/scope-caption.tsnew file mode 100644index 000000000..014ea6306--- /dev/null+++ b/packages/ui/src/workspace/system-map/scope-caption.ts@@ -0,0 +1,125 @@+/**+ * The caption under the map: what is drawn, what the family filter hides,+ * and what the draw budget left out. Read off the drawn view itself, so the+ * words and the canvas always come from the same data. Pure, no React.+ */++import { EDGE_FAMILY_COPY, EDGE_FAMILY_ORDER } from "./edge-families";+import type { DrawnTrayNode } from "./level-types";+import type { LevelView } from "./levels";+import { plural } from "./system-map-model";++function joinWords(parts: readonly string[]): string {+ if (parts.length <= 1) return parts[0] ?? "";+ return `${parts.slice(0, -1).join(", ")} and ${parts[parts.length - 1]}`;+}++function present(parts: readonly (string | null)[]): string[] {+ return parts.filter((p): p is string => p !== null);+}++/** "2 groups, 3 services and a tray of 4 services ...": the cards drawn. */+function cardWords(view: LevelView): string[] {+ const groups = view.nodes.filter((n) => n.type === "group" && !n.open).length;+ const services = view.nodes.filter((n) => n.type === "service").length;+ const tray = view.nodes.find((n): n is DrawnTrayNode => n.type === "tray" && !n.open);+ return present([+ groups > 0 ? plural(groups, "group", "groups") : null,+ services > 0 ? plural(services, "service", "services") : null,+ tray ? `a tray of ${plural(tray.serviceIds.length, "service", "services")} with no runtime or data link` : null,+ ]);+}++/** "3 lines between services and 2 bands carrying 17 links": the connectors drawn. */+function lineWords(view: LevelView): string[] {+ const singles = view.edges.filter((e) => e.type === "edge").length;+ let bands = 0;+ let bandLinks = 0;+ for (const e of view.edges) {+ if (e.type !== "band") continue;+ bands += 1;+ bandLinks += e.summary.links;+ }+ return present([+ singles > 0 ? `${plural(singles, "line", "lines")} between services` : null,+ bands > 0 ? `${plural(bands, "band", "bands")} carrying ${plural(bandLinks, "link", "links")}` : null,+ ]);+}++function drawnSentence(view: LevelView): string {+ const cards = cardWords(view);+ if (cards.length === 0) return "Nothing to draw at this level.";+ const lines = lineWords(view);+ return `Drawing ${joinWords(cards)}${lines.length > 0 ? `, joined by ${joinWords(lines)}` : ""}.`;+}++function focusSentence(view: LevelView, name: (id: string) => string): string | null {+ const focus = view.focus;+ if (!focus) return null;+ const count = (ids: readonly string[]) =>+ focus.columns+ .filter((c) => ids.includes(c.id))+ .reduce((sum, c) => sum + c.entries.length + c.folded.length, 0);+ const callers = count(["callers"]);+ const deps = count(["dependencies"]);+ return `Focused on ${name(focus.focus)}, ${focus.hops === 2 ? "two hops" : "one hop"}: ${plural(callers, "service depends", "services depend")} on it, and it depends on ${plural(deps, "service", "services")}.`;+}++function betweenSentence(view: LevelView, name: (id: string) => string): string | null {+ const between = view.between;+ if (!between) return null;+ const a = name(between.a);+ const b = name(between.b);+ const direct = present([+ between.aToB ? `${plural(between.aToB.links, "link", "links")} from ${a} to ${b}` : null,+ between.bToA ? `${plural(between.bToA.links, "link", "links")} from ${b} to ${a}` : null,+ ]);+ if (direct.length > 0) return `Between ${a} and ${b}: ${joinWords(direct)}.`;+ const through = new Set<string>();+ for (const p of [...between.pathsAToB, ...between.pathsBToA]) p.nodes.slice(1, -1).forEach((id) => through.add(id));+ return through.size > 0+ ? `No direct link between ${a} and ${b}; they connect through ${joinWords([...through].sort().map(name))}.`+ : `No link or two-step path between ${a} and ${b} in the families drawn.`;+}++/** "Hidden by the edge filter: 26 Build relationships (package dependencies)." Null when every family present is drawn. */+export function hiddenFamiliesSentence(view: LevelView): string | null {+ const hidden = EDGE_FAMILY_ORDER.filter((f) => !view.families.has(f) && (view.familyCounts[f]?.edges ?? 0) > 0);+ if (hidden.length === 0) return null;+ const parts = hidden.map((f) => {+ const copy = EDGE_FAMILY_COPY[f];+ return `${plural(view.familyCounts[f]!.edges, `${copy.label} relationship`, `${copy.label} relationships`)} (${copy.meaning})`;+ });+ return `Hidden by the edge filter: ${joinWords(parts)}.`;+}++/** What the draw budget folded or dropped. Null when everything fit. */+export function truncationSentence(view: LevelView): string | null {+ const t = view.truncation;+ if (!t) return null;+ const folded = [+ t.foldedServices > 0 ? plural(t.foldedServices, "service", "services") : null,+ t.foldedGroups > 0 ? plural(t.foldedGroups, "group", "groups") : null,+ ].filter((p): p is string => p !== null);+ const single = t.foldedServices + t.foldedGroups === 1;+ const parts = [+ folded.length > 0 ? `${joinWords(folded)} ${single ? "is" : "are"} folded into "+N more" cards` : null,+ t.droppedEdges > 0+ ? `the ${plural(t.droppedEdges, "weakest line", "weakest lines")} (${plural(t.droppedLinks, "link", "links")}) ${t.droppedEdges === 1 ? "is" : "are"} not drawn`+ : null,+ ].filter((p): p is string => p !== null);+ return `Over the draw budget of ${t.budget.nodes} cards and ${t.budget.edges} lines: ${joinWords(parts)}.`;+}++/** Every caption sentence for a view, in reading order. */+export function scopeCaption(view: LevelView, name: (id: string) => string): string[] {+ const level =+ view.level === "focus" ? focusSentence(view, name) : view.level === "between" ? betweenSentence(view, name) : null;+ return [+ level,+ drawnSentence(view),+ hiddenFamiliesSentence(view),+ truncationSentence(view),+ "Placement follows runtime, data and build dependencies, so changing the edge filter never moves a card.",+ ].filter((p): p is string => p !== null);+}diff --git a/packages/ui/src/workspace/system-map/selection-fix.ts b/packages/ui/src/workspace/system-map/selection-fix.tsnew file mode 100644index 000000000..4e78cabae--- /dev/null+++ b/packages/ui/src/workspace/system-map/selection-fix.ts@@ -0,0 +1,110 @@+/**+ * A selection names a service, a system edge, a group or a band; the canvas+ * draws cards and connectors. This maps the one onto the other, and when a+ * selection from the URL or a list below the map is hidden at the current+ * level, names the smallest view change that draws it: open the group (or+ * tray) holding a service, or show the family an edge belongs to. It never+ * changes the level (focus, between) for a selection. Pure, no React.+ */++import type { SystemEdge } from "@repowise-dev/types";+import { edgeFamilyOf } from "./edge-families";+import type { DrawnNode } from "./level-types";+import type { LevelView } from "./levels";+import type { SystemMapSelection } from "./types";+import { TRAY_OPEN_TOKEN, openContainer, showFamily, type MapViewState } from "./view-state";++export interface ResolvedSelection {+ /** The drawn node or connector id to mark selected; null when nothing drawn stands for it. */+ drawnId: string | null;+ drawnKind: "node" | "edge" | null;+ /** A view that would draw the selection, or null when it is drawn or cannot be. */+ fix: MapViewState | null;+}++const NONE: ResolvedSelection = { drawnId: null, drawnKind: null, fix: null };++/** The closed container a service is folded into: a group id, the tray, or nothing. */+function containerOf(nodes: readonly DrawnNode[], serviceId: string): string | null {+ for (const n of nodes) {+ if (n.type === "group" && !n.open && n.serviceIds.includes(serviceId)) return n.groupId;+ if (n.type === "tray" && !n.open && n.serviceIds.includes(serviceId)) return TRAY_OPEN_TOKEN;+ }+ return null;+}++/** The card drawn for a service: the focus card first, then any column copy. */+function serviceCard(nodes: readonly DrawnNode[], serviceId: string): string | null {+ let first: string | null = null;+ for (const n of nodes) {+ if (n.type !== "service" || n.serviceId !== serviceId) continue;+ if (n.column === "focus" || n.column === undefined) return n.id;+ first ??= n.id;+ }+ return first;+}++function atEstate(view: LevelView): boolean {+ return view.level === "estate" || view.level === "group";+}++function resolveService(id: string, view: LevelView, state: MapViewState): ResolvedSelection {+ const card = serviceCard(view.nodes, id);+ if (card) return { drawnId: card, drawnKind: "node", fix: null };+ const holder = atEstate(view) ? containerOf(view.nodes, id) : null;+ return { ...NONE, fix: holder ? openContainer(state, holder) : null };+}++function resolveGroup(id: string, view: LevelView): ResolvedSelection {+ const group = view.nodes.find((n) => n.type === "group" && n.groupId === id);+ return group ? { drawnId: group.id, drawnKind: "node", fix: null } : NONE;+}++function resolveBand(id: string, view: LevelView): ResolvedSelection {+ return view.edges.some((e) => e.id === id) ? { drawnId: id, drawnKind: "edge", fix: null } : NONE;+}++/** Open what folds an edge's two ends, so it gets its own line. */+function openEnds(edge: SystemEdge, view: LevelView, state: MapViewState): MapViewState | null {+ let fix: MapViewState | null = null;+ for (const end of [edge.source, edge.target]) {+ const holder = containerOf(view.nodes, end);+ if (holder) fix = openContainer(fix ?? state, holder);+ }+ return fix;+}++function resolveEdge(+ id: string,+ view: LevelView,+ edgesById: ReadonlyMap<string, SystemEdge>,+ state: MapViewState,+): ResolvedSelection {+ const edge = edgesById.get(id);+ if (!edge) return NONE;+ const drawn = view.edges.find((e) => e.type === "edge" && e.edgeId === edge.id);+ if (drawn) return { drawnId: drawn.id, drawnKind: "edge", fix: null };+ const family = edgeFamilyOf(edge);+ if (!view.families.has(family)) return { ...NONE, fix: showFamily(state, family) };+ return { ...NONE, fix: atEstate(view) ? openEnds(edge, view, state) : null };+}++export function resolveSelection(+ selection: SystemMapSelection,+ view: LevelView,+ edgesById: ReadonlyMap<string, SystemEdge>,+ state: MapViewState,+): ResolvedSelection {+ switch (selection?.type) {+ case "node":+ return resolveService(selection.id, view, state);+ case "group":+ return resolveGroup(selection.id, view);+ case "band":+ return resolveBand(selection.id, view);+ case "edge":+ return resolveEdge(selection.id, view, edgesById, state);+ default:+ return NONE;+ }+}diff --git a/packages/ui/src/workspace/system-map/system-map-actions.ts b/packages/ui/src/workspace/system-map/system-map-actions.tsnew file mode 100644index 000000000..024a9616b--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-actions.ts@@ -0,0 +1,23 @@+/**+ * Verbs a card offers on the canvas (open or close a group or the tray, show+ * what a "+N more" card holds), handed down by context rather than through+ * node data, so a new callback never re-renders every card.+ */++import { createContext, useContext } from "react";++export interface SystemMapActions {+ /** Open a group id, or `TRAY_OPEN_TOKEN` for the tray, in place. */+ openContainer: (id: string) => void;+ closeContainer: (id: string) => void;+ /** Present when the host can list folded services (the list view). */+ showFolded?: ((serviceIds: readonly string[]) => void) | undefined;+}++const NOOP: SystemMapActions = { openContainer: () => {}, closeContainer: () => {} };++export const SystemMapActionsContext = createContext<SystemMapActions>(NOOP);++export function useSystemMapActions(): SystemMapActions {+ return useContext(SystemMapActionsContext);+}diff --git a/packages/ui/src/workspace/system-map/system-map-aggregate-panel.tsx b/packages/ui/src/workspace/system-map/system-map-aggregate-panel.tsxnew file mode 100644index 000000000..ddf3ff501--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-aggregate-panel.tsx@@ -0,0 +1,152 @@+"use client";++/**+ * The rail for an aggregate: a group (where it came from, its services with+ * their health, its links, and the verb to open it) or a band (its sentence+ * and the service pairs behind it, each one a way to that pair's strongest+ * relationship). Presentation only; the map passes the drawn data.+ */++import type { SystemEdge, SystemNode } from "@repowise-dev/types";+import { healthMark } from "../../health/tokens";+import { bandSentence, groupSourceLabel, healthCounts, healthSummaryText, kindMixText } from "./aggregate-facts";+import { summarizeLinks } from "./bands";+import type { DrawnBand, DrawnGroupNode, LinkSummary } from "./level-types";+import { SystemMapRailFrame } from "./system-map-drawer";+import { MICRO_LABEL } from "./system-map-filters";+import { plural } from "./system-map-model";+import type { RepoHealth, SystemMapSelection } from "./types";++const ROW =+ "flex w-full min-w-0 items-baseline justify-between gap-3 rounded px-2 py-1.5 text-left hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]";++interface Lookups {+ nodesById: ReadonlyMap<string, SystemNode>;+ edgesById: ReadonlyMap<string, SystemEdge>;+ healthByRepo?: ReadonlyMap<string, RepoHealth> | undefined;+ onSelect: (selection: SystemMapSelection) => void;+ onClose: () => void;+}++export function GroupPanel({+ group,+ onOpen,+ nodesById,+ healthByRepo,+ onSelect,+ onClose,+}: Lookups & { group: DrawnGroupNode; onOpen: () => void }) {+ const score = (id: string) => {+ const repo = nodesById.get(id)?.repo;+ const h = repo ? healthByRepo?.get(repo) : undefined;+ return h ? h.score / 10 : null;+ };+ const source = groupSourceLabel(group.groupId, group.source, group.serviceIds.length);+ return (+ <SystemMapRailFrame eyebrow="Group" title={group.label} onClose={onClose}>+ <p className="text-xs text-[var(--color-text-secondary)]">+ {plural(group.serviceIds.length, "service", "services")} in {plural(group.repoCount, "repository", "repositories")}+ {source ? `, grouped by ${source}` : ""}. {healthSummaryText(healthCounts(group.serviceIds.map(score)))}.{" "}+ <span className="font-mono tabular-nums">+ in {group.linksIn} · out {group.linksOut} · {group.linksInside} inside+ </span>{" "}+ links in the families drawn.+ </p>+ {!group.open && (+ <button+ type="button"+ onClick={onOpen}+ className="self-start text-xs font-medium text-[var(--color-accent-primary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ Open this group on the map+ </button>+ )}+ <section className="flex flex-col gap-1">+ <h3 className={MICRO_LABEL}>Services</h3>+ <ul className="flex flex-col">+ {group.serviceIds.map((id) => {+ const s = score(id);+ const mark = s == null ? null : healthMark(s);+ return (+ <li key={id}>+ <button type="button" className={ROW} onClick={() => onSelect({ type: "node", id })}>+ <span className="min-w-0 truncate text-xs text-[var(--color-text-primary)]">{nodesById.get(id)?.name ?? id}</span>+ {mark ? (+ <span className="inline-flex shrink-0 items-center gap-1.5 text-xs">+ <span aria-hidden className="h-1.5 w-1.5 rounded-full" style={{ background: mark.color }} />+ <span className="tabular-nums text-[var(--color-text-primary)]">{mark.value}</span>+ <span className="text-[var(--color-text-secondary)]">{mark.label}</span>+ </span>+ ) : (+ <span className="shrink-0 text-xs text-[var(--color-text-secondary)]">No score</span>+ )}+ </button>+ </li>+ );+ })}+ </ul>+ </section>+ </SystemMapRailFrame>+ );+}++interface Pair {+ source: string;+ target: string;+ summary: LinkSummary;+ strongest: string;+}++/** The service pairs behind a band, most links first. */+export function bandPairs(band: DrawnBand, edgesById: ReadonlyMap<string, SystemEdge>): Pair[] {+ const byPair = new Map<string, SystemEdge[]>();+ for (const id of band.summary.edgeIds) {+ const e = edgesById.get(id);+ if (!e) continue;+ const key = `${e.source}>${e.target}`;+ const list = byPair.get(key);+ if (list) list.push(e);+ else byPair.set(key, [e]);+ }+ return [...byPair.values()]+ .map((edges) => {+ const strongest = [...edges].sort((a, b) => b.weight - a.weight || (a.id < b.id ? -1 : 1))[0]!;+ return { source: strongest.source, target: strongest.target, summary: summarizeLinks(edges), strongest: strongest.id };+ })+ .sort((a, b) => b.summary.links - a.summary.links || (a.source + a.target < b.source + b.target ? -1 : 1));+}++export function BandPanel({+ band,+ sourceLabel,+ targetLabel,+ nodesById,+ edgesById,+ onSelect,+ onClose,+}: Lookups & { band: DrawnBand; sourceLabel: string; targetLabel: string }) {+ const pairs = bandPairs(band, edgesById);+ const name = (id: string) => nodesById.get(id)?.name ?? id;+ return (+ <SystemMapRailFrame eyebrow="Band" title={`${sourceLabel} → ${targetLabel}`} onClose={onClose}>+ <p className="text-xs text-[var(--color-text-secondary)]">{bandSentence(sourceLabel, targetLabel, band.summary)}</p>+ <section className="flex flex-col gap-1">+ <h3 className={MICRO_LABEL}>{plural(pairs.length, "service pair", "service pairs")}</h3>+ <ul className="flex flex-col">+ {pairs.map((p) => (+ <li key={`${p.source}>${p.target}`}>+ <button type="button" className={ROW} onClick={() => onSelect({ type: "edge", id: p.strongest })}>+ <span className="min-w-0 text-xs text-[var(--color-text-primary)] [overflow-wrap:anywhere]">+ {name(p.source)} → {name(p.target)}+ </span>+ <span className="shrink-0 font-mono text-[10px] tabular-nums text-[var(--color-text-secondary)]">+ {p.summary.links} · {kindMixText(p.summary.kinds)}+ </span>+ </button>+ </li>+ ))}+ </ul>+ </section>+ </SystemMapRailFrame>+ );+}diff --git a/packages/ui/src/workspace/system-map/system-map-band.tsx b/packages/ui/src/workspace/system-map/system-map-band.tsxnew file mode 100644index 000000000..9942571c6--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-band.tsx@@ -0,0 +1,113 @@+"use client";++/**+ * A band: every link between two drawn nodes where at least one end is an+ * aggregate (a group, the tray, a "+N more" card, a focus column), as one+ * stroke per direction. Width is the link count on a log scale and the count+ * is printed on the band, because width alone does not name a number. The+ * kind mix is a sentence on hover or selection; kind is never a hue.+ */++import { memo, type CSSProperties } from "react";+import { BaseEdge, EdgeLabelRenderer, getBezierPath, type EdgeProps } from "@xyflow/react";+import type { BandEdgeData } from "./flow-elements";+import { useEdgeActive, useEdgeFocused } from "./system-map-focus";++/** One source for the band's look, read by the legend too. */+export const BAND_STROKE = { min: 2, max: 10, opacity: 0.55 } as const;++/** Stroke width for a band of `links` links: 2 px for one link, 10 px from about 150. */+export function bandWidth(links: number): number {+ return Math.min(BAND_STROKE.max, BAND_STROKE.min + Math.log2(Math.max(1, links)) * 1.6);+}++const LABEL_BASE = {+ position: "absolute",+ pointerEvents: "none",+ borderRadius: 4,+ background: "var(--color-bg-root)",+ fontFamily: "var(--font-mono, ui-monospace, monospace)",+ fontSize: 10,+ lineHeight: "14px",+} as const;++/** The band's stroke: accent when it or a card it touches is hovered or selected, ink when a lens marks it. */+function bandStyle(links: number, active: boolean, lensed: boolean, dimmed: boolean): CSSProperties {+ const stroke = active ? "var(--color-accent-primary)" : lensed ? "var(--color-text-primary)" : "var(--color-diagram-edge)";+ return {+ stroke,+ strokeWidth: bandWidth(links),+ strokeOpacity: active ? 0.9 : BAND_STROKE.opacity,+ strokeLinecap: "butt",+ opacity: dimmed ? 0.12 : 1,+ transition: "opacity 120ms, stroke 120ms, stroke-opacity 120ms",+ };+}++/** The printed count, always; the sentence under it only while the band itself is hovered or selected. */+function BandLabels({ x, y, links, sentence, active, focused }: { x: number; y: number; links: number; sentence: string; active: boolean; focused: boolean }) {+ return (+ <EdgeLabelRenderer>+ <div+ className="nodrag nopan"+ style={{+ ...LABEL_BASE,+ transform: `translate(-50%, -50%) translate(${x}px, ${y}px)`,+ padding: "0 5px",+ border: `1px solid ${active ? "var(--color-accent-primary)" : "var(--color-border-hover)"}`,+ color: "var(--color-text-primary)",+ fontWeight: 500,+ fontVariantNumeric: "tabular-nums",+ zIndex: focused ? 3 : 1,+ }}+ >+ {links.toLocaleString()}+ </div>+ {focused && (+ <div+ role="tooltip"+ style={{+ ...LABEL_BASE,+ transform: `translate(-50%, 12px) translate(${x}px, ${y}px)`,+ maxWidth: 280,+ padding: "6px 8px",+ border: "1px solid var(--color-border-hover)",+ background: "var(--color-bg-overlay)",+ color: "var(--color-text-primary)",+ fontFamily: "var(--font-sans)",+ fontSize: 12,+ lineHeight: "16px",+ zIndex: 4,+ }}+ >+ {sentence}+ </div>+ )}+ </EdgeLabelRenderer>+ );+}++function SystemMapBandInner(props: EdgeProps) {+ const { id, source, target, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, markerEnd, data } = props;+ const { band, sentence, overlay } = data as unknown as BandEdgeData;+ const active = useEdgeActive(id, source, target);+ const focused = useEdgeFocused(id);+ const [path, labelX, labelY] = getBezierPath({ sourceX, sourceY, sourcePosition, targetX, targetY, targetPosition });+ const dimmed = Boolean(overlay?.dimmed) && !active;+ const links = band.summary.links;++ return (+ <g className="sm-edge" data-active={active || overlay?.highlighted ? "" : undefined}>+ <BaseEdge+ id={id}+ path={path}+ {...(markerEnd ? { markerEnd } : {})}+ interactionWidth={Math.max(16, bandWidth(links) + 8)}+ style={bandStyle(links, active, Boolean(overlay?.highlighted), dimmed)}+ />+ {!dimmed && <BandLabels x={labelX} y={labelY} links={links} sentence={sentence} active={active} focused={focused} />}+ </g>+ );+}++export const SystemMapBand = memo(SystemMapBandInner);diff --git a/packages/ui/src/workspace/system-map/system-map-breadcrumb.tsx b/packages/ui/src/workspace/system-map/system-map-breadcrumb.tsxnew file mode 100644index 000000000..3aa3a53c0--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-breadcrumb.tsx@@ -0,0 +1,61 @@+"use client";++/**+ * Where the map is, as Estate / Group / Service, once it is anywhere but the+ * estate. Each crumb returns to its level. Built on the shared+ * `GraphScopeBreadcrumb` so every graph surface says "you are here" the same way.+ */++import type { SystemGraph } from "@repowise-dev/types";+import { GraphScopeBreadcrumb, type GraphScopeCrumb } from "../../graph/graph-scope-breadcrumb";+import type { MapLevel } from "./level-types";+import { TRAY_OPEN_TOKEN, openContainer, toEstate, type MapViewState } from "./view-state";++export interface SystemMapBreadcrumbProps {+ graph: SystemGraph;+ level: MapLevel;+ view: MapViewState;+ onViewChange: (view: MapViewState) => void;+ estateLabel?: string | undefined;+}++/** The crumbs below the estate for a view, as plain labels and target views. Exported for tests. */+export function breadcrumbTrail(+ graph: SystemGraph,+ level: MapLevel,+ view: MapViewState,+): { label: string; target: MapViewState | null }[] {+ const name = (id: string) => graph.nodes.find((n) => n.id === id)?.name ?? id;+ const groupLabel = (id: string) =>+ id === TRAY_OPEN_TOKEN ? "Not linked at runtime" : (graph.groups?.find((g) => g.id === id)?.label ?? id);+ const estate = toEstate(view);++ if (level === "between" && view.between) {+ return [{ label: `${name(view.between.a)} and ${name(view.between.b)}`, target: null }];+ }+ if (level === "focus" && view.focus) {+ const group = graph.nodes.find((n) => n.id === view.focus)?.group;+ const known = group && graph.groups?.some((g) => g.id === group);+ return [+ ...(known ? [{ label: groupLabel(group!), target: openContainer(estate, group!) }] : []),+ { label: name(view.focus), target: null },+ ];+ }+ if (level === "group" && view.open.length > 0) {+ return [{ label: groupLabel(view.open[view.open.length - 1]!), target: null }];+ }+ return [];+}++export function SystemMapBreadcrumb({ graph, level, view, onViewChange, estateLabel = "Estate" }: SystemMapBreadcrumbProps) {+ const crumbs = breadcrumbTrail(graph, level, view);+ if (crumbs.length === 0) return null;+ const leaf = crumbs[crumbs.length - 1]!;+ const trail: GraphScopeCrumb[] = crumbs.slice(0, -1).map((c) => ({+ label: c.label,+ onClick: () => c.target && onViewChange(c.target),+ }));+ return (+ <GraphScopeBreadcrumb rootLabel={estateLabel} leafLabel={leaf.label} onRoot={() => onViewChange(toEstate(view))} trail={trail} />+ );+}diff --git a/packages/ui/src/workspace/system-map/system-map-canvas.tsx b/packages/ui/src/workspace/system-map/system-map-canvas.tsxnew file mode 100644index 000000000..3665c08f9--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-canvas.tsx@@ -0,0 +1,182 @@+"use client";++/**+ * The drawing plane: React Flow over the drawn cards and connectors, with+ * pointer and keyboard input reported as one `onActivate` call so a click,+ * a double-click and Enter on a focused card reach the same handler. Cards+ * and connectors are in the tab order; Escape asks the map to back out a+ * level. Fits the drawing whenever the level's layout changes or the canvas+ * resizes, without animating when the reader prefers reduced motion.+ */++import { useCallback, useEffect, useMemo, type FocusEvent, type KeyboardEvent, type ReactNode } from "react";+import {+ Background,+ BackgroundVariant,+ Controls,+ MiniMap,+ ReactFlow,+ useReactFlow,+ useStore,+ type Edge,+ type EdgeMouseHandler,+ type Node,+ type NodeMouseHandler,+} from "@xyflow/react";+import "@xyflow/react/dist/style.css";+import type { ActivateTrigger } from "./activate";+import { SystemMapBand } from "./system-map-band";+import { SystemMapEdge } from "./system-map-edge";+import type { SystemMapFocusStore } from "./system-map-focus";+import { SystemMapGroupNode } from "./system-map-group-node";+import { SystemMapNode } from "./system-map-node";+import { SystemMapMoreNode, SystemMapTrayNode } from "./system-map-tray-node";++/** Below this many cards the whole map fits on screen and a minimap is noise. */+export const SYSTEM_MAP_MINIMAP_MIN_NODES = 40;++const NODE_TYPES = {+ systemService: SystemMapNode,+ systemGroup: SystemMapGroupNode,+ systemTray: SystemMapTrayNode,+ systemMore: SystemMapMoreNode,+};+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 FIT_OPTIONS = { padding: 0.08, maxZoom: 1.2 } as const;+++export interface SystemMapCanvasProps {+ nodes: Node[];+ edges: Edge[];+ focus: SystemMapFocusStore;+ /** Changes when the drawing should be refitted (a new level). */+ fitKey: string;+ /** False while the level's layout is still running; the fit waits for it. */+ settled: boolean;+ onActivate: (id: string, kind: "node" | "edge", trigger: ActivateTrigger) => void;+ onPaneClick: () => void;+ onEscape: () => void;+ /** Drawn over the plane when there is nothing to draw (empty or error state). */+ empty?: ReactNode;+}++function prefersReducedMotion(): boolean {+ return typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true;+}++export function SystemMapCanvas({ nodes, edges, focus, fitKey, settled, onActivate, onPaneClick, onEscape, empty }: SystemMapCanvasProps) {+ const onNodeClick = useCallback<NodeMouseHandler>((_, n) => onActivate(n.id, "node", "click"), [onActivate]);+ const onNodeDoubleClick = useCallback<NodeMouseHandler>((_, n) => onActivate(n.id, "node", "double"), [onActivate]);+ const onEdgeClick = useCallback<EdgeMouseHandler>((_, e) => onActivate(e.id, "edge", "click"), [onActivate]);+ const onNodeMouseEnter = useCallback<NodeMouseHandler>((_, n) => focus.setHover({ node: n.id }), [focus]);+ const onNodeMouseLeave = useCallback<NodeMouseHandler>(() => focus.setHover({ node: null }), [focus]);+ const onEdgeMouseEnter = useCallback<EdgeMouseHandler>((_, e) => focus.setHover({ edge: e.id }), [focus]);+ const onEdgeMouseLeave = useCallback<EdgeMouseHandler>(() => focus.setHover({ edge: null }), [focus]);++ // Keyboard: React Flow's own selection is off, so Enter and Space on a+ // focused card or connector land here and do what a click (or, on an+ // aggregate, a double-click) does.+ const onKeyDown = useCallback(+ (e: KeyboardEvent<HTMLDivElement>) => {+ if (e.key === "Escape") {+ e.preventDefault();+ onEscape();+ return;+ }+ if (e.key !== "Enter" && e.key !== " ") return;+ const target = e.target as HTMLElement;+ const el = target.closest?.(".react-flow__node, .react-flow__edge");+ const id = el?.getAttribute("data-id");+ // 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");+ },+ [onActivate, onEscape],+ );+ // A focused connector shows what hovering it shows.+ const onFocusCapture = useCallback(+ (e: FocusEvent<HTMLDivElement>) => {+ const el = (e.target as HTMLElement).closest?.(".react-flow__edge");+ focus.setHover({ edge: el?.getAttribute("data-id") ?? null });+ },+ [focus],+ );+ const onBlurCapture = useCallback(() => focus.setHover({ edge: null }), [focus]);++ const ariaLabelConfig = useMemo(+ () => ({+ "node.a11yDescription.default": NODE_HELP,+ "node.a11yDescription.keyboardDisabled": NODE_HELP,+ "edge.a11yDescription.default": "Press Enter to show this line's or band's details. Escape goes back a level.",+ }),+ [],+ );++ return (+ <div className="h-full w-full" onKeyDown={onKeyDown} onFocusCapture={onFocusCapture} onBlurCapture={onBlurCapture}>+ {empty}+ <ReactFlow+ nodes={nodes}+ edges={edges}+ nodeTypes={NODE_TYPES}+ edgeTypes={EDGE_TYPES}+ onNodeClick={onNodeClick}+ onNodeDoubleClick={onNodeDoubleClick}+ onEdgeClick={onEdgeClick}+ onPaneClick={onPaneClick}+ onNodeMouseEnter={onNodeMouseEnter}+ onNodeMouseLeave={onNodeMouseLeave}+ onEdgeMouseEnter={onEdgeMouseEnter}+ onEdgeMouseLeave={onEdgeMouseLeave}+ elementsSelectable={false}+ nodesDraggable={false}+ nodesConnectable={false}+ zoomOnDoubleClick={false}+ fitView+ fitViewOptions={FIT_OPTIONS}+ minZoom={0.15}+ maxZoom={2}+ proOptions={{ hideAttribution: true }}+ ariaLabelConfig={ariaLabelConfig}+ >+ <Background variant={BackgroundVariant.Dots} gap={20} size={1} color="var(--color-border-hover)" />+ <Controls showInteractive={false} style={{ marginBottom: "var(--canvas-chrome-bottom, 15px)" }} />+ {nodes.length >= SYSTEM_MAP_MINIMAP_MIN_NODES && (+ <MiniMap+ pannable+ zoomable+ bgColor="var(--color-bg-surface)"+ maskColor="color-mix(in srgb, var(--color-bg-root) 70%, transparent)"+ nodeColor="var(--color-border-hover)"+ nodeStrokeColor="var(--color-text-tertiary)"+ style={{ border: "1px solid var(--color-border-default)", marginBottom: "var(--canvas-chrome-bottom, 15px)" }}+ />+ )}+ <FitOnChange fitKey={fitKey} ready={settled && nodes.length > 0} />+ </ReactFlow>+ </div>+ );+}++/**+ * Fits once a level's layout lands and when the canvas resizes. `fitView` on+ * mount alone would fit an empty field, because the async layout places+ * cards after React Flow's first pass.+ */+function FitOnChange({ fitKey, ready }: { fitKey: string; ready: boolean }) {+ const rf = useReactFlow();+ const width = useStore((s) => s.width);+ const height = useStore((s) => s.height);+ useEffect(() => {+ if (!ready || width === 0 || height === 0) return;+ const id = requestAnimationFrame(() => {+ void rf.fitView({ ...FIT_OPTIONS, duration: prefersReducedMotion() ? 0 : 200 });+ });+ return () => cancelAnimationFrame(id);+ }, [rf, ready, fitKey, width, height]);+ return null;+}diff --git a/packages/ui/src/workspace/system-map/system-map-card-action.tsx b/packages/ui/src/workspace/system-map/system-map-card-action.tsxnew file mode 100644index 000000000..332208f84--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-card-action.tsx@@ -0,0 +1,40 @@+"use client";++/**+ * Shared bits of the aggregate cards (group, tray, "+N more"): the card's one+ * verb as a quiet accent link, and the invisible handles connectors attach to.+ */++import type { CSSProperties } from "react";++/** Connectors attach here; the handle itself is never shown or grabbed. */+export const HIDDEN_HANDLE: CSSProperties = { opacity: 0, pointerEvents: "none" };++/** The card's one verb. Out of the tab order: Enter on the card does the same. */+export function CardAction({ label, onClick }: { label: string; onClick: () => void }) {+ return (+ <button+ type="button"+ tabIndex={-1}+ className="nodrag nopan"+ onClick={(e) => {+ e.stopPropagation();+ onClick();+ }}+ onDoubleClick={(e) => e.stopPropagation()}+ style={{+ flexShrink: 0,+ border: 0,+ background: "transparent",+ padding: 0,+ cursor: "pointer",+ fontSize: 12,+ lineHeight: "16px",+ fontWeight: 500,+ color: "var(--color-accent-primary)",+ }}+ >+ {label}+ </button>+ );+}diff --git a/packages/ui/src/workspace/system-map/system-map-drawer.tsx b/packages/ui/src/workspace/system-map/system-map-drawer.tsxindex 8dab9c7f4..9ff668ab5 100644--- a/packages/ui/src/workspace/system-map/system-map-drawer.tsx+++ b/packages/ui/src/workspace/system-map/system-map-drawer.tsx@@ -1,13 +1,13 @@"use client";/**- * The System Map's detail drawer: one service or one relationship, with- * everything needed to act on it. It is the shared `AdaptivePanel`, non-modal,- * so the map stays interactive behind it and a click on another node swaps the- * subject without closing and reopening.+ * The System Map's detail rail: one service or one relationship, with+ * everything needed to act on it. It renders in the canvas shell's rail slot,+ * a grid peer of the canvas from `lg` and a bottom sheet below, so it never+ * covers what it describes and a click on another card swaps the subject.*- * Resolves the selection against the *drawn* graph. In repo view the ids the- * map hands back are collapsed ones that only exist there.+ * 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.@@ -23,7 +23,7 @@ import type {SystemNode,WorkspaceContractLinkEntry,} from "@repowise-dev/types/workspace";-import { AdaptivePanel } from "../../shared/adaptive-panel";+import { X } from "lucide-react";import { FilePath } from "../../shared/file-path";import { AiPromptButton } from "../../health/ai-prompt-button";import { AiPromptModal } from "../../health/ai-prompt-modal";@@ -91,11 +91,7 @@ export interface SystemMapDrawerData {export interface SystemMapDrawerProps extends SystemMapDrawerData {selection: SystemMapSelection;- /** The drawn graph (collapse + filters applied). */graph: SystemGraph;- /** The raw graph, for diagnostics and service boundaries. */- rawGraph: SystemGraph;- collapsed: boolean;healthByRepo?: ReadonlyMap<string, RepoHealth> | undefined;roleByNodeId?: ReadonlyMap<string, NodeArchitectureRole> | undefined;onClose: () => void;@@ -104,12 +100,13 @@ export interface SystemMapDrawerProps extends SystemMapDrawerData {/*** The repository whose contracts the drawer needs for a selection, so the host- * can fetch before the drawer asks. Accepts raw and collapsed ids.+ * can fetch before the drawer asks. Groups and bands name no one repository.*/export function selectionRepo(graph: SystemGraph | null, selection: SystemMapSelection): string | null {if (!graph || !selection) return null;- const repoOfNode = (id: string) =>- graph.nodes.find((n) => n.id === id)?.repo ?? (graph.nodes.some((n) => n.repo === id) ? id : 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);@@ -123,34 +120,68 @@ interface PromptState {build: (flavor: AiPromptFlavor) => string;}+/** Whether the rail has anything to say about a selection; the map shows no rail otherwise. */+export function drawerHasSubject(graph: SystemGraph, selection: SystemMapSelection): boolean {+ if (selection?.type === "node") return graph.nodes.some((n) => n.id === selection.id);+ if (selection?.type === "edge") return graph.edges.some((e) => e.id === selection.id);+ return false;+}++/** Eyebrow, title and a close button over a scrolling body: the rail's one frame. */+export function SystemMapRailFrame({+ eyebrow,+ title,+ onClose,+ children,+}: {+ eyebrow: string;+ title: string;+ onClose: () => void;+ children: ReactNode;+}) {+ return (+ <div className="flex min-h-0 flex-1 flex-col" role="region" aria-label={title}>+ <div className="flex shrink-0 items-start justify-between gap-3 border-b border-[var(--color-border-default)] px-4 py-3">+ <div className="min-w-0">+ <div className={MICRO_LABEL}>{eyebrow}</div>+ <h2 className="mt-0.5 text-[15px] font-semibold text-[var(--color-text-primary)] [overflow-wrap:anywhere]">+ {title}+ </h2>+ </div>+ <button+ type="button"+ onClick={onClose}+ aria-label="Close details"+ className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <X size={14} aria-hidden />+ </button>+ </div>+ <div className="flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto px-4 py-4">{children}</div>+ </div>+ );+}+export function SystemMapDrawer(props: SystemMapDrawerProps) {- const { selection, graph, rawGraph, collapsed, onClose } = props;+ const { selection, graph, onClose } = props;const [prompt, setPrompt] = useState<PromptState | null>(null);- const resolve = useMemo(() => serviceResolver(rawGraph, collapsed), [rawGraph, collapsed]);+ const resolve = useMemo(() => serviceResolver(graph), [graph]);const node = selection?.type === "node" ? graph.nodes.find((n) => n.id === selection.id) ?? null : null;const edge = selection?.type === "edge" ? graph.edges.find((e) => e.id === selection.id) ?? null : null;- const open = Boolean(node || edge);const name = (id: string) => graph.nodes.find((n) => n.id === id)?.name ?? id;+ if (!node && !edge) return null;return (<>- <AdaptivePanel- open={open}- onOpenChange={(next) => {- if (!next) onClose();- }}- modal={false}- // The map, the rows below it and the drawer are one workspace: a click- // elsewhere selects something else or does nothing, never closes this.- onInteractOutside={(e) => e.preventDefault()}+ <SystemMapRailFrameeyebrow={node ? nodeKindStyle(node.kind).label : "Relationship"}title={node ? node.name : edge ? `${name(edge.source)} → ${name(edge.target)}` : ""}- widthClassName="md:max-w-[480px]"+ onClose={onClose}>{node && <NodeBody {...props} node={node} resolve={resolve} onPrompt={setPrompt} />}{edge && <EdgeBody {...props} edge={edge} resolve={resolve} onPrompt={setPrompt} />}- </AdaptivePanel>+ </SystemMapRailFrame><AiPromptModalopen={prompt !== null}onOpenChange={(o) => !o && setPrompt(null)}@@ -250,8 +281,6 @@ type BodyProps<T> = SystemMapDrawerProps & {function NodeBody({node,graph,- rawGraph,- collapsed,healthByRepo,roleByNodeId,repoContracts,@@ -270,16 +299,15 @@ function NodeBody({const health = healthByRepo?.get(node.repo);// Repo health arrives 0-100; the mark reads 0-10.const mark = health ? healthMark(health.score / 10) : null;- // Roles are computed per service, so a merged repo node has none.- const role = collapsed ? undefined : roleByNodeId?.get(node.id);+ const role = roleByNodeId?.get(node.id);const style = role ? roleStyle(role.role) : null;const reaches = role ? Math.max(role.visibility_fan_out - 1, 0) : 0;const reachedBy = role ? Math.max(role.visibility_fan_in - 1, 0) : 0;const out = neighbourGroups(graph, node.id, "out");const incoming = neighbourGroups(graph, node.id, "in");- const myCycles = collapsed ? [] : cyclesThrough(cycles, node.id);- const diag = serviceDiagnostics(diagnostics ?? rawGraph.diagnostics, node.id, resolve);+ const myCycles = cyclesThrough(cycles, node.id);+ const diag = serviceDiagnostics(diagnostics ?? graph.diagnostics, node.id, resolve);const summary = useMemo(() => (repoContracts ? summarizeServiceContracts(repoContracts, node.id, resolve) : null),[repoContracts, node.id, resolve],@@ -352,7 +380,7 @@ function NodeBody({},{label: "Architecture role",- value: style ? style.label : <span className="text-xs text-[var(--color-text-tertiary)]">{collapsed ? "Per service only" : "Not computed"}</span>,+ value: style ? style.label : <span className="text-xs text-[var(--color-text-tertiary)]">Not computed</span>,},{ label: "Outgoing to", value: <span className="tabular-nums">{plural(distinct(out, (e) => e.target), "service", "services")}</span> },{ label: "Incoming from", value: <span className="tabular-nums">{plural(distinct(incoming, (e) => e.source), "service", "services")}</span> },@@ -407,7 +435,7 @@ function NodeBody({<AiPromptButtonvariant="icon"label="Break this cycle with AI"- onClick={() => onPrompt(cyclePrompt(c, rawGraph))}+ onClick={() => onPrompt(cyclePrompt(c, graph))}/></li>))}@@ -579,11 +607,9 @@ const MATCH_MEANING: Record<string, string> = {function EdgeBody({edge,graph,- rawGraph,repoContracts,repoContractsLoading,cycles = [],- collapsed,contractHref,contractsHref,coChangesHref,@@ -610,7 +636,7 @@ function EdgeBody({const pairs = edge.structural ? [] : coChangePairs(edge);// The lean map view sends a structural edge's count, not its refs.const keptRefs = edge.contract_refs ? refs.length : (edge.ref_count ?? 0);- const myCycles = collapsed ? [] : cyclesWithEdge(cycles, edge.id);+ const myCycles = cyclesWithEdge(cycles, edge.id);const name = (id: string) => nodeOf(id)?.name ?? id;const openEdgePrompt = () =>@@ -703,7 +729,7 @@ function EdgeBody({<div key={c.edge_ids.join("|")} className="flex flex-wrap items-center gap-2 text-xs text-[var(--color-text-secondary)]"><span aria-hidden className="h-1.5 w-1.5 rounded-full bg-[var(--color-warning)]" />This edge closes a cycle: {c.nodes.map(name).join(" → ")} → {name(c.nodes[0] ?? "")}.- <AiPromptButton label="Break the cycle" onClick={() => onPrompt(cyclePrompt(c, rawGraph))} />+ <AiPromptButton label="Break the cycle" onClick={() => onPrompt(cyclePrompt(c, graph))} /></div>))}</Section>diff --git a/packages/ui/src/workspace/system-map/system-map-edge.tsx b/packages/ui/src/workspace/system-map/system-map-edge.tsxindex 83776a0f0..fe1400452 100644--- a/packages/ui/src/workspace/system-map/system-map-edge.tsx+++ b/packages/ui/src/workspace/system-map/system-map-edge.tsx@@ -15,6 +15,7 @@ import { memo } from "react";import { BaseEdge, EdgeLabelRenderer, getSmoothStepPath, type EdgeProps } from "@xyflow/react";import { edgeKindStyle, edgeLabel, matchTypeDash } from "./edge-kinds";import { useEdgeActive } from "./system-map-focus";+import { SystemMapLensBadge } from "./system-map-lens-badge";import { weightShort } from "./system-map-model";import type { SystemMapEdgeData } from "./types";@@ -22,12 +23,6 @@ function strokeWidth(weight: number): number {return Math.min(1 + Math.log2(weight + 1) * 0.4, 3.2);}-function badgeColor(tone: "danger" | "warning" | "info"): string {- if (tone === "danger") return "var(--color-error)";- if (tone === "warning") return "var(--color-warning)";- return "var(--color-text-secondary)";-}-function SystemMapEdgeInner(props: EdgeProps) {const { id, source, target, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, markerEnd, data } =props;@@ -98,11 +93,7 @@ function SystemMapEdgeInner(props: EdgeProps) {><Icon size={10} aria-hidden style={{ flexShrink: 0 }} />{edgeLabel(edge)} · {weightShort(edge)}- {overlay?.badge && (- <span style={{ color: badgeColor(overlay.badge.tone), fontWeight: 600 }}>- · {overlay.badge.label}- </span>- )}+ {overlay?.badge && <SystemMapLensBadge badge={overlay.badge} style={{ marginLeft: 2 }} />}</div></EdgeLabelRenderer>)}diff --git a/packages/ui/src/workspace/system-map/system-map-empty.tsx b/packages/ui/src/workspace/system-map/system-map-empty.tsxnew file mode 100644index 000000000..3e3f12ad6--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-empty.tsx@@ -0,0 +1,46 @@+"use client";++/**+ * The canvas's own "nothing to draw" copy, centred over the canvas box: an+ * error, no services yet, or services with no relationships. Null while+ * loading or when there is something to draw.+ */++import { EmptyState } from "../../shared/empty-state";+import { toFriendlyMessage } from "../../lib/errors";++export interface CanvasEmptyProps {+ error?: Error | null | undefined;+ loading: boolean;+ hasGraph: boolean;+ hasEdges: boolean;+}++function message({ error, loading, hasGraph, hasEdges }: CanvasEmptyProps): { title: string; description: string } | null {+ if (error) return { title: "Couldn't load the system map", description: toFriendlyMessage(error) };+ if (loading) return null;+ if (!hasGraph) {+ return {+ title: "No services to map yet",+ description:+ "The system map appears once the workspace has at least two indexed repositories with detected cross-repo relationships.",+ };+ }+ if (!hasEdges) {+ return {+ title: "No cross-repo relationships detected",+ description: "Services are indexed, but no HTTP, gRPC, event, package, database or co-change links were found between them yet.",+ };+ }+ return null;+}++export function SystemMapCanvasEmpty(props: CanvasEmptyProps) {+ const m = message(props);+ if (!m) return null;+ return (+ <div className="pointer-events-none absolute inset-0 z-[3] flex items-center justify-center">+ <EmptyState title={m.title} description={m.description} />+ </div>+ );+}diff --git a/packages/ui/src/workspace/system-map/system-map-filters.tsx b/packages/ui/src/workspace/system-map/system-map-filters.tsxindex 387b4f8e0..89dae1fbd 100644--- a/packages/ui/src/workspace/system-map/system-map-filters.tsx+++ b/packages/ui/src/workspace/system-map/system-map-filters.tsx@@ -1,86 +1,74 @@"use client";/**- * The map's section-header controls: which edge kinds are drawn, and whether- * services or whole repositories are the nodes. Only kinds present in the- * graph are offered, each with its count, so the row never shows a dead- * filter. Pure controlled components; state lives in the map.+ * The map's edge filter: one chip per edge family present in the graph+ * (Runtime, Data, Build, History), each with its relationship count. Runtime+ * and Data are drawn by default; Build and History are opt-in, and the+ * caption names what is hidden. Hovering a chip names the kinds inside it.+ * Controlled; the state lives with the map's level state.*/-import type { SystemEdgeKind } from "@repowise-dev/types";-import { Segmented } from "../../shared/segmented";-import { EDGE_KIND_ORDER, SYSTEM_EDGE_KINDS } from "./edge-kinds";+import { ArrowRight, Boxes, Database, Link2, type LucideIcon } from "lucide-react";+import { EDGE_FAMILY_COPY, EDGE_FAMILY_ORDER, type EdgeFamily, type FamilyCount } from "./edge-families";+import { kindMixText } from "./aggregate-facts";// Re-exported for the lens switch and existing imports; the control lives in shared.export { Segmented, type SegmentOption } from "../../shared/segmented";export const MICRO_LABEL =- "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";+ "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-secondary)]";++const FAMILY_ICON: Record<EdgeFamily, LucideIcon> = {+ runtime: ArrowRight,+ data: Database,+ build: Boxes,+ history: Link2,+};export interface SystemMapFiltersProps {- /** Edges per kind in the drawn shape (before the kind filter); only these kinds are offered. */- kindCounts: ReadonlyMap<SystemEdgeKind, number>;- visibleKinds: ReadonlySet<SystemEdgeKind>;- onToggleKind: (kind: SystemEdgeKind) => void;- /** Whether the repo view would differ from the service view; the switch hides otherwise. */- canCollapse: boolean;- collapsed: boolean;- onCollapsedChange: (collapsed: boolean) => void;+ /** Relationships per family in the whole graph; only families present get a chip. */+ familyCounts: Partial<Record<EdgeFamily, FamilyCount>>;+ /** Relationships per kind inside each family, named on the chip's hover. */+ kindCounts?: Partial<Record<EdgeFamily, Record<string, number>>> | undefined;+ families: ReadonlySet<EdgeFamily>;+ onToggleFamily: (family: EdgeFamily) => void;}-export function SystemMapFilters({- kindCounts,- visibleKinds,- onToggleKind,- canCollapse,- collapsed,- onCollapsedChange,-}: SystemMapFiltersProps) {- const kinds = EDGE_KIND_ORDER.filter((k) => (kindCounts.get(k) ?? 0) > 0);+export function SystemMapFilters({ familyCounts, kindCounts, families, onToggleFamily }: SystemMapFiltersProps) {+ const present = EDGE_FAMILY_ORDER.filter((f) => (familyCounts[f]?.edges ?? 0) > 0);+ if (present.length === 0) return null;return (- <div className="flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2">- {kinds.length > 0 && (- <div className="flex min-w-0 flex-wrap items-center gap-1.5" role="group" aria-label="Edge kinds drawn">- <span className={`${MICRO_LABEL} mr-1`}>Edges</span>- {kinds.map((kind) => {- const s = SYSTEM_EDGE_KINDS[kind];- const Icon = s.icon;- const active = visibleKinds.has(kind);- return (- <button- key={kind}- type="button"- onClick={() => onToggleKind(kind)}- aria-pressed={active}- title={`Toggle ${s.label} edges`}- className={`inline-flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] ${- active- ? "border-[var(--color-border-hover)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)]"- : "border-dashed border-[var(--color-border-default)] text-[var(--color-text-tertiary)] line-through"- }`}- >- <Icon size={12} aria-hidden />- {s.label}- <span className="font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)] no-underline">- {kindCounts.get(kind)}- </span>- </button>- );- })}- </div>- )}- {canCollapse && (- <Segmented- label="Nodes"- value={collapsed ? "repos" : "services"}- options={[- { value: "services", label: "Services", hint: "One node per detected service" },- { value: "repos", label: "Repositories", hint: "Group services into one node per repository" },- ]}- onChange={(v) => onCollapsedChange(v === "repos")}- />- )}+ <div className="flex min-w-0 flex-wrap items-center gap-1.5" role="group" aria-label="Edge families drawn">+ <span className={`${MICRO_LABEL} mr-1`}>Edges</span>+ {present.map((family) => {+ const copy = EDGE_FAMILY_COPY[family];+ const Icon = FAMILY_ICON[family];+ const active = families.has(family);+ const count = familyCounts[family]!.edges;+ const kinds = kindCounts?.[family];+ const mix = kinds ? kindMixText(kinds) : "";+ return (+ <button+ key={family}+ type="button"+ onClick={() => onToggleFamily(family)}+ aria-pressed={active}+ title={`${copy.label}: ${copy.meaning}${mix ? ` (${mix})` : ""}. ${active ? "Click to hide." : "Click to show."}`}+ className={`inline-flex min-h-[28px] items-center gap-1.5 rounded-md border px-2 py-1 text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] ${+ active+ ? "border-[var(--color-border-hover)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)]"+ : "border-dashed border-[var(--color-border-default)] text-[var(--color-text-secondary)]"+ }`}+ >+ <Icon size={12} aria-hidden />+ <span className={active ? undefined : "line-through"}>{copy.label}</span>+ <span className="font-mono text-[10px] tabular-nums text-[var(--color-text-secondary)]">+ {count.toLocaleString()}+ </span>+ </button>+ );+ })}</div>);}diff --git a/packages/ui/src/workspace/system-map/system-map-focus.ts b/packages/ui/src/workspace/system-map/system-map-focus.tsindex f41dc18fa..e1475f060 100644--- a/packages/ui/src/workspace/system-map/system-map-focus.ts+++ b/packages/ui/src/workspace/system-map/system-map-focus.ts@@ -22,6 +22,8 @@ export interface SystemMapFocusStore {/** True when anything is hovered or selected. */focused: () => boolean;edgeActive: (id: string, source: string, target: string) => boolean;+ /** True when this connector itself is hovered or selected, not merely touching a hovered card. */+ edgeFocused: (id: string) => boolean;}export function createSystemMapFocusStore(): SystemMapFocusStore {@@ -54,6 +56,7 @@ export function createSystemMapFocusStore(): SystemMapFocusStore {}return false;},+ edgeFocused: (id) => id === hover.edge || id === selected.edge,};}@@ -70,3 +73,13 @@ export function useEdgeActive(id: string, source: string, target: string): boole() => false,);}++/** Whether this connector itself is hovered or selected (a band's kind mix shows only then). */+export function useEdgeFocused(id: string): boolean {+ const store = useContext(SystemMapFocusContext);+ return useSyncExternalStore(+ store ? store.subscribe : never,+ () => (store ? store.edgeFocused(id) : false),+ () => false,+ );+}diff --git a/packages/ui/src/workspace/system-map/system-map-group-node.tsx b/packages/ui/src/workspace/system-map/system-map-group-node.tsxnew file mode 100644index 000000000..cd275aefa--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-group-node.tsx@@ -0,0 +1,150 @@+"use client";++/**+ * A group of services on the map. Closed, it is a card: the group's name and+ * where it came from, how many services and repositories it holds, its+ * health exceptions on the canonical three bands (healthy is quiet), and its+ * links in, out and inside. Open, it is the container its service cards sit+ * in, with a title row and a way to close it.+ *+ * No hue per group: containment and the name identify it, and the health+ * mark keeps the only colour on the card.+ */++import { memo, type CSSProperties } from "react";+import { Handle, Position, type NodeProps } from "@xyflow/react";+import { healthExceptions, healthSummaryText } from "./aggregate-facts";+import type { GroupNodeData } from "./flow-elements";+import { LEVEL_NODE_SIZES } from "./layout-scopes";+import { useSystemMapActions } from "./system-map-actions";+import { CardAction, HIDDEN_HANDLE } from "./system-map-card-action";+import { plural } from "./system-map-model";++const MONO: CSSProperties = {+ fontFamily: "var(--font-mono, ui-monospace, monospace)",+ fontSize: 10,+ lineHeight: "14px",+ fontVariantNumeric: "tabular-nums",+ color: "var(--color-text-secondary)",+};++const TITLE: CSSProperties = {+ minWidth: 0,+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ fontSize: 15,+ lineHeight: "20px",+ fontWeight: 600,+ color: "var(--color-text-primary)",+};++function frame(selected: boolean, highlighted: boolean): CSSProperties {+ return {+ border: `${highlighted && !selected ? 1.5 : 1}px solid ${+ selected ? "var(--color-accent-primary)" : highlighted ? "var(--color-text-primary)" : "var(--color-border-hover)"+ }`,+ boxShadow: selected ? "0 0 0 2px color-mix(in srgb, var(--color-accent-primary) 35%, transparent)" : undefined,+ };+}++function GroupNodeInner({ data, selected }: NodeProps) {+ const { group, sourceLabel, health, overlay } = data as unknown as GroupNodeData;+ const actions = useSystemMapActions();+ const services = plural(group.serviceIds.length, "service", "services");+ const links = [+ `in ${group.linksIn.toLocaleString()}`,+ `out ${group.linksOut.toLocaleString()}`,+ ...(group.linksInside > 0 ? [`${group.linksInside.toLocaleString()} inside`] : []),+ ].join(" · ");+ const lensed = overlay?.highlighted ?? false;+ const dimmed = overlay?.dimmed ?? false;++ if (group.open) {+ return (+ <div+ className="sm-group"+ style={{+ width: "100%",+ height: "100%",+ boxSizing: "border-box",+ borderRadius: 10,+ background: "color-mix(in srgb, var(--color-bg-surface) 55%, transparent)",+ padding: "10px 14px",+ opacity: dimmed ? 0.35 : 1,+ ...frame(Boolean(selected), lensed),+ }}+ >+ <Handle type="target" position={Position.Top} style={HIDDEN_HANDLE} />+ <div style={{ display: "flex", alignItems: "baseline", gap: 10, minWidth: 0 }}>+ <span style={TITLE}>{group.label}</span>+ {sourceLabel && <span style={{ ...MONO, flexShrink: 0 }}>{sourceLabel}</span>}+ <span style={{ ...MONO, flexShrink: 0 }}>{services}</span>+ <span style={{ flex: 1 }} />+ <CardAction label="Close" onClick={() => actions.closeContainer(group.groupId)} />+ </div>+ <Handle type="source" position={Position.Bottom} style={HIDDEN_HANDLE} />+ </div>+ );+ }++ const exceptions = healthExceptions(health);+ const { width, height } = LEVEL_NODE_SIZES.group;+ return (+ <div+ className="sm-group"+ style={{+ position: "relative",+ width,+ height,+ boxSizing: "border-box",+ display: "flex",+ flexDirection: "column",+ gap: 3,+ padding: "9px 12px",+ borderRadius: 8,+ background: "var(--color-bg-surface)",+ boxShadow: "var(--shadow-sm)",+ opacity: dimmed ? 0.35 : 1,+ cursor: "pointer",+ transition: "opacity 120ms, border-color 120ms",+ ...frame(Boolean(selected), lensed),+ }}+ >+ <Handle type="target" position={Position.Top} style={HIDDEN_HANDLE} />+ <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 8, minWidth: 0 }}>+ <span title={group.label} style={TITLE}>+ {group.label}+ </span>+ {sourceLabel && (+ <span title={sourceLabel} style={{ ...MONO, flexShrink: 1, minWidth: 0, maxWidth: "50%", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>+ {sourceLabel}+ </span>+ )}+ </div>+ <span style={MONO}>+ {services} · {plural(group.repoCount, "repo", "repos")}+ </span>+ <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, lineHeight: "16px", minWidth: 0 }}>+ {exceptions.length > 0 ? (+ exceptions.map((e) => (+ <span key={e.band} style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>+ <span aria-hidden style={{ width: 6, height: 6, borderRadius: 999, background: e.color, flexShrink: 0 }} />+ <span style={{ fontVariantNumeric: "tabular-nums", color: "var(--color-text-primary)", fontWeight: 600 }}>{e.count}</span>+ <span style={{ color: "var(--color-text-secondary)" }}>{e.label}</span>+ </span>+ ))+ ) : (+ <span style={{ color: "var(--color-text-secondary)" }}>{healthSummaryText(health)}</span>+ )}+ </div>+ <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 8, marginTop: "auto" }}>+ <span style={MONO}>{links}</span>+ <CardAction label="Open ›" onClick={() => actions.openContainer(group.groupId)} />+ </div>+ <Handle type="source" position={Position.Bottom} style={HIDDEN_HANDLE} />+ </div>+ );+}++export const SystemMapGroupNode = memo(GroupNodeInner);diff --git a/packages/ui/src/workspace/system-map/system-map-legend.tsx b/packages/ui/src/workspace/system-map/system-map-legend.tsxindex 7af3a9567..19353dba1 100644--- a/packages/ui/src/workspace/system-map/system-map-legend.tsx+++ b/packages/ui/src/workspace/system-map/system-map-legend.tsx@@ -2,15 +2,17 @@/*** Key for the Live System Map, as one caption row between the controls and- * the canvas: the line styles actually drawn (structural ink, co-change- * dotted, candidate dashed), the health mark's three bands, and how to get- * more. Reads the same registries the map renders from, so the two cannot- * drift, and lists only what the graph contains.+ * the canvas: bands when any are drawn, the line styles actually drawn+ * (structural ink, co-change dotted, candidate dashed), the health mark's+ * three bands, and how to get more. Reads the same constants the map renders+ * from, so the two cannot drift, and lists only what is drawn.*/-import type { SystemEdgeMatchType } from "@repowise-dev/types";+import type { SystemEdge, SystemEdgeMatchType } from "@repowise-dev/types";+import type { DrawnEdge } from "./level-types";import { HEALTH_MARK_BANDS } from "../../health/tokens";-import { matchTypeDash } from "./edge-kinds";+import { isGatewayRouted, matchTypeDash } from "./edge-kinds";+import { BAND_STROKE, bandWidth } from "./system-map-band";function Item({ swatch, label }: { swatch: React.ReactNode; label: string }) {return (@@ -54,9 +56,43 @@ export interface SystemMapLegendProps {matchTypes?: ReadonlySet<SystemEdgeMatchType>;/** Drawn lines a gateway route made; they share the HTTP line, so the key names them in words. */gatewayRouted?: number;+ /** Whether any band is drawn; only then does the key explain one. */+ bands?: boolean;}-export function SystemMapLegend({ matchTypes, gatewayRouted = 0 }: SystemMapLegendProps) {+function BandSwatch() {+ return (+ <svg width={26} height={10} aria-hidden>+ <line+ x1={0}+ y1={5}+ x2={26}+ y2={5}+ stroke="var(--color-diagram-edge)"+ strokeOpacity={BAND_STROKE.opacity}+ strokeWidth={bandWidth(17)}+ />+ </svg>+ );+}++/** What the key lists for the connectors drawn: their match types, gateway-made lines, and whether any band is drawn. */+export function legendKeyFor(+ edges: readonly DrawnEdge[],+ edgesById: ReadonlyMap<string, SystemEdge>,+): Required<SystemMapLegendProps> {+ const matchTypes = new Set<SystemEdgeMatchType>();+ let gatewayRouted = 0;+ for (const e of edges) {+ const edge = e.type === "edge" ? edgesById.get(e.edgeId) : undefined;+ if (!edge) continue;+ matchTypes.add(edge.match_type);+ if (isGatewayRouted(edge)) gatewayRouted += 1;+ }+ return { matchTypes, gatewayRouted, bands: edges.some((e) => e.type === "band") };+}++export function SystemMapLegend({ matchTypes, gatewayRouted = 0, bands = false }: SystemMapLegendProps) {const order: SystemEdgeMatchType[] = ["exact", "manual", "candidate", "inferred"];const shown = order.filter((m) => !matchTypes || matchTypes.has(m));// Exact and manual draw the same solid line; one key covers both.@@ -64,6 +100,7 @@ export function SystemMapLegend({ matchTypes, gatewayRouted = 0 }: SystemMapLegereturn (<div className="flex flex-wrap items-center gap-x-5 gap-y-1.5">+ {bands && <Item swatch={<BandSwatch />} label="Band: every link between two cards, width and number are the count" />}{lines.map((m) => (<Itemkey={m}@@ -89,7 +126,9 @@ export function SystemMapLegend({ matchTypes, gatewayRouted = 0 }: SystemMapLege))}</span><span className="text-xs text-[var(--color-text-tertiary)]">- Hover a line for its kind and weight. Click a service or line for details.+ {bands+ ? "Hover a band for its kinds. Open a group to see its services. Click anything for details."+ : "Hover a line for its kind and weight. Click a service or line for details."}</span></div>);diff --git a/packages/ui/src/workspace/system-map/system-map-lens-badge.tsx b/packages/ui/src/workspace/system-map/system-map-lens-badge.tsxnew file mode 100644index 000000000..c99178606--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-lens-badge.tsx@@ -0,0 +1,53 @@+"use client";++/**+ * A lens mark on a card or a line: ink on the surface plane, an icon and a+ * word ("3 breaking", "cycle", "core"). Never red or amber: health owns those+ * hues on a card, and a second mark in the same vocabulary would read as a+ * second health reading. The icon's shape carries the severity the tone used+ * to, and the lens's results below the map explain it.+ */++import { CircleDot, OctagonAlert, TriangleAlert, type LucideIcon } from "lucide-react";+import type { BadgeTone, SystemMapBadge } from "./types";++const TONE_ICON: Record<BadgeTone, LucideIcon> = {+ danger: OctagonAlert,+ warning: TriangleAlert,+ info: CircleDot,+};++/** Words a screen reader hears before the label, so the icon's meaning is not shape alone. */+const TONE_WORD: Record<BadgeTone, string> = {+ danger: "Lens, high:",+ warning: "Lens, medium:",+ info: "Lens:",+};++export function SystemMapLensBadge({ badge, style }: { badge: SystemMapBadge; style?: React.CSSProperties }) {+ const Icon = TONE_ICON[badge.tone];+ return (+ <span+ style={{+ display: "inline-flex",+ alignItems: "center",+ gap: 3,+ padding: "0 5px",+ borderRadius: 4,+ background: "var(--color-bg-surface)",+ border: "1px solid var(--color-text-secondary)",+ color: "var(--color-text-primary)",+ fontFamily: "var(--font-mono, ui-monospace, monospace)",+ fontSize: 10,+ lineHeight: "16px",+ fontWeight: 600,+ whiteSpace: "nowrap",+ ...style,+ }}+ >+ <Icon size={10} aria-hidden style={{ flexShrink: 0 }} />+ <span className="sr-only">{TONE_WORD[badge.tone]} </span>+ {badge.label}+ </span>+ );+}diff --git a/packages/ui/src/workspace/system-map/system-map-model.ts b/packages/ui/src/workspace/system-map/system-map-model.tsindex 8b24939ef..14ea82576 100644--- a/packages/ui/src/workspace/system-map/system-map-model.ts+++ b/packages/ui/src/workspace/system-map/system-map-model.ts@@ -39,14 +39,12 @@ export interface SystemMapRepoContracts {// ---------------------------------------------------------------------------/**- * Resolves `(repo, file)` to the node that owns it on the drawn graph. A file- * belongs to the deepest declared service path containing it, else to the- * repo-root node; in repo view every file belongs to its repo.+ * Resolves `(repo, file)` to the service that owns it. A file belongs to the+ * deepest declared service path containing it, else to the repo-root node.*/export type ServiceResolver = (repo: string, file: string) => string;-export function serviceResolver(graph: SystemGraph, collapsed: boolean): ServiceResolver {- if (collapsed) return (repo) => repo;+export function serviceResolver(graph: SystemGraph): ServiceResolver {const paths = new Map<string, string[]>();for (const n of graph.nodes) {if (!n.service_path) continue;@@ -345,52 +343,3 @@ export function unmatchedReasonList(byReason: Record<string, number>): string {.map(([r, n]) => `${n.toLocaleString()} ${UNMATCHED_REASON[r] ?? r}`).join(", ");}--// ----------------------------------------------------------------------------// Selections against the drawn graph.-// -----------------------------------------------------------------------------export type ViewSelectionFix = { kind: "show-edge-kind"; edgeKind: SystemEdgeKind } | { kind: "expand" } | null;--/**- * Lists below the map, and the URL, name raw service and edge ids. The drawn- * graph may be collapsed to repositories or missing a hidden edge kind. Maps- * the selection onto what is drawn, or says what the map must change to draw- * it: show a hidden kind, or return to the service view for an edge inside- * one repository.- */-export function resolveViewSelection(- selection: { type: "node" | "edge"; id: string } | null,- raw: SystemGraph,- view: SystemGraph,- collapsed: boolean,-): { selection: { type: "node" | "edge"; id: string } | null; fix: ViewSelectionFix } {- if (!selection) return { selection: null, fix: null };- const drawn =- selection.type === "node"- ? view.nodes.some((n) => n.id === selection.id)- : view.edges.some((e) => e.id === selection.id);- if (drawn) return { selection, fix: null };-- const repoOf = (id: string) => raw.nodes.find((n) => n.id === id)?.repo;- if (selection.type === "node") {- const repo = collapsed ? repoOf(selection.id) : undefined;- return { selection: repo ? { type: "node", id: repo } : null, fix: null };- }-- const edge = raw.edges.find((e) => e.id === selection.id);- if (!edge) {- // A collapsed id whose kind is hidden.- const kind = selection.id.split("::").pop() as SystemEdgeKind | undefined;- const known = kind && raw.edges.some((e) => e.kind === kind);- return { selection: null, fix: collapsed && known ? { kind: "show-edge-kind", edgeKind: kind } : null };- }- if (!collapsed) return { selection: null, fix: { kind: "show-edge-kind", edgeKind: edge.kind } };- const src = repoOf(edge.source);- const tgt = repoOf(edge.target);- if (!src || !tgt || src === tgt) return { selection: null, fix: { kind: "expand" } };- const merged = `${src}->${tgt}::${edge.kind}`;- return view.edges.some((e) => e.id === merged)- ? { selection: { type: "edge", id: merged }, fix: null }- : { selection: null, fix: { kind: "show-edge-kind", edgeKind: edge.kind } };-}diff --git a/packages/ui/src/workspace/system-map/system-map-node.tsx b/packages/ui/src/workspace/system-map/system-map-node.tsxindex 452f342f9..f394643b5 100644--- a/packages/ui/src/workspace/system-map/system-map-node.tsx+++ b/packages/ui/src/workspace/system-map/system-map-node.tsx@@ -7,21 +7,17 @@** The architecture role is a word, not a colour: the health mark already owns* green, amber and red on this object, and a second mark in the same- * vocabulary would read as a second health reading.+ * vocabulary would read as a second health reading. Lens marks are ink+ * badges for the same reason (`system-map-lens-badge.tsx`).*/import { memo } from "react";import { Handle, Position, type NodeProps } from "@xyflow/react";import { healthMark } from "../../health/tokens";-import { SYSTEM_MAP_NODE_SIZE } from "./layout";+import { SYSTEM_MAP_NODE_SIZE } from "./layout-scopes";+import { SystemMapLensBadge } from "./system-map-lens-badge";import type { SystemMapNodeData } from "./types";-function badgeColor(tone: "danger" | "warning" | "info"): string {- if (tone === "danger") return "var(--color-error)";- if (tone === "warning") return "var(--color-warning)";- return "var(--color-text-secondary)";-}-function SystemMapNodeInner({ data, selected }: NodeProps) {const { node, health, overlay, role } = data as unknown as SystemMapNodeData;// Repo health arrives 0-100; the mark reads 0-10.@@ -60,24 +56,7 @@ function SystemMapNodeInner({ data, selected }: NodeProps) {<Handle type="target" position={Position.Top} style={{ opacity: 0, pointerEvents: "none" }} />{overlay?.badge && (- <span- style={{- position: "absolute",- top: -9,- right: 10,- padding: "0 6px",- borderRadius: 4,- background: "var(--color-bg-surface)",- border: `1px solid ${badgeColor(overlay.badge.tone)}`,- color: badgeColor(overlay.badge.tone),- fontFamily: "var(--font-mono, ui-monospace, monospace)",- fontSize: 10,- lineHeight: "16px",- fontWeight: 600,- }}- >- {overlay.badge.label}- </span>+ <SystemMapLensBadge badge={overlay.badge} style={{ position: "absolute", top: -9, right: 10 }} />)}<div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 8, minWidth: 0 }}>@@ -104,7 +83,7 @@ function SystemMapNodeInner({ data, selected }: NodeProps) {fontSize: 10,letterSpacing: "0.08em",textTransform: "uppercase",- color: "var(--color-text-tertiary)",+ color: "var(--color-text-secondary)",}}>{role}@@ -121,7 +100,7 @@ function SystemMapNodeInner({ data, selected }: NodeProps) {fontFamily: "var(--font-mono, ui-monospace, monospace)",fontSize: 10,lineHeight: "14px",- color: "var(--color-text-tertiary)",+ color: "var(--color-text-secondary)",}}>{where}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.tsxnew file mode 100644index 000000000..818a10481--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-rail-content.tsx@@ -0,0 +1,64 @@+"use client";++/**+ * 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+ * canvas takes the full width.+ */++import type { ReactNode } from "react";+import type { NodeArchitectureRole, SystemEdge, SystemGraph, SystemNode } from "@repowise-dev/types";+import { drawnLabel } from "./flow-elements";+import type { LevelView } from "./levels";+import { BandPanel, GroupPanel } from "./system-map-aggregate-panel";+import { SystemMapDrawer, drawerHasSubject, type SystemMapDrawerData } from "./system-map-drawer";+import type { RepoHealth, SystemMapSelection } from "./types";++export interface RailContentArgs {+ graph: SystemGraph;+ levelView: LevelView;+ selection: SystemMapSelection;+ nodesById: ReadonlyMap<string, SystemNode>;+ edgesById: ReadonlyMap<string, SystemEdge>;+ healthByRepo?: ReadonlyMap<string, RepoHealth> | undefined;+ roleByNodeId?: ReadonlyMap<string, NodeArchitectureRole> | undefined;+ drawer?: SystemMapDrawerData | undefined;+ levelRail?: ReactNode;+ onSelect: (selection: SystemMapSelection) => void;+ onOpenGroup: (groupId: string) => void;+}++function aggregateRail(args: RailContentArgs): ReactNode {+ const { levelView, selection, nodesById } = args;+ const lookups = { ...args, onClose: () => args.onSelect(null) };+ if (selection?.type === "group") {+ const g = levelView.nodes.find((n) => n.type === "group" && n.groupId === selection.id);+ return g?.type === "group" ? <GroupPanel {...lookups} group={g} onOpen={() => args.onOpenGroup(g.groupId)} /> : null;+ }+ if (selection?.type === "band") {+ const b = levelView.edges.find((e) => e.id === selection.id);+ if (b?.type !== "band") return null;+ const label = (id: string) => drawnLabel(levelView.nodes.find((n) => n.id === id), nodesById);+ return <BandPanel {...lookups} band={b} sourceLabel={label(b.source)} targetLabel={label(b.target)} />;+ }+ return null;+}++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;+ return (+ <SystemMapDrawer+ {...args.drawer}+ selection={selection}+ graph={graph}+ healthByRepo={args.healthByRepo}+ roleByNodeId={args.roleByNodeId}+ onClose={() => args.onSelect(null)}+ onSelect={args.onSelect}+ />+ );+}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.tsxnew file mode 100644index 000000000..11a6a785e--- /dev/null+++ b/packages/ui/src/workspace/system-map/system-map-tray-node.tsx@@ -0,0 +1,108 @@+"use client";++/**+ * The two aggregates that are not systems. The tray holds the services with+ * no Runtime or Data link at all, as one card or (open) the container of+ * their cards. A "+N more" card stands for what the draw budget folded. Both+ * are dashed: they collect services by what the map can say about them, not+ * by anything the services share.+ */++import { memo, type CSSProperties } from "react";+import { Handle, Position, type NodeProps } from "@xyflow/react";+import type { MoreNodeData, TrayNodeData } from "./flow-elements";+import { LEVEL_NODE_SIZES } from "./layout-scopes";+import { useSystemMapActions } from "./system-map-actions";+import { CardAction, HIDDEN_HANDLE } from "./system-map-card-action";+import { plural } from "./system-map-model";+import { TRAY_OPEN_TOKEN } from "./view-state";++const MONO: CSSProperties = {+ fontFamily: "var(--font-mono, ui-monospace, monospace)",+ fontSize: 10,+ lineHeight: "14px",+ color: "var(--color-text-secondary)",+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+};++function dashed(selected: boolean): CSSProperties {+ return {+ boxSizing: "border-box",+ borderRadius: 8,+ border: `1px dashed ${selected ? "var(--color-accent-primary)" : "var(--color-border-hover)"}`,+ background: "transparent",+ };+}++function TrayNodeInner({ data, selected }: NodeProps) {+ const { tray, names } = data as unknown as TrayNodeData;+ const actions = useSystemMapActions();+ const count = tray.serviceIds.length;++ if (tray.open) {+ return (+ <div style={{ ...dashed(Boolean(selected)), width: "100%", height: "100%", padding: "10px 14px", borderRadius: 10 }}>+ <Handle type="target" position={Position.Top} style={HIDDEN_HANDLE} />+ <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>+ <span style={{ fontSize: 12, fontWeight: 600, color: "var(--color-text-primary)" }}>Not linked at runtime</span>+ <span style={{ ...MONO, flexShrink: 0 }}>{plural(count, "service", "services")}</span>+ <span style={{ flex: 1 }} />+ <CardAction label="Close" onClick={() => actions.closeContainer(TRAY_OPEN_TOKEN)} />+ </div>+ <Handle type="source" position={Position.Bottom} style={HIDDEN_HANDLE} />+ </div>+ );+ }++ const { width, height } = LEVEL_NODE_SIZES.tray;+ const rest = count - names.length;+ return (+ <div+ style={{ ...dashed(Boolean(selected)), width, height, display: "flex", flexDirection: "column", gap: 2, padding: "9px 12px", cursor: "pointer" }}+ >+ <Handle type="target" position={Position.Top} style={HIDDEN_HANDLE} />+ <span style={{ fontSize: 12, lineHeight: "16px", fontWeight: 600, color: "var(--color-text-primary)" }}>+ Not linked at runtime · <span style={{ fontVariantNumeric: "tabular-nums" }}>{count.toLocaleString()}</span>+ </span>+ <span style={MONO} title={names.join(", ")}>+ {names.join(", ")}+ {rest > 0 ? `, +${rest.toLocaleString()} more` : ""}+ </span>+ <span style={{ fontSize: 12, lineHeight: "16px", color: "var(--color-text-secondary)" }}>No runtime or data link.</span>+ <div style={{ display: "flex", justifyContent: "flex-end", marginTop: "auto" }}>+ <CardAction label="Open ›" onClick={() => actions.openContainer(TRAY_OPEN_TOKEN)} />+ </div>+ <Handle type="source" position={Position.Bottom} style={HIDDEN_HANDLE} />+ </div>+ );+}++function MoreNodeInner({ data, selected }: NodeProps) {+ const { more } = 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} />+ <span style={{ fontSize: 15, lineHeight: "20px", fontWeight: 600, color: "var(--color-text-primary)", fontVariantNumeric: "tabular-nums" }}>+ +{more.serviceIds.length.toLocaleString()} more+ </span>+ <span style={{ fontSize: 12, lineHeight: "16px", color: "var(--color-text-secondary)" }}>+ {groups > 0 ? `${plural(groups, "group", "groups")} and their services, ` : "Services "}+ folded to keep the map within its draw budget.+ </span>+ {showFolded && (+ <div style={{ marginTop: "auto" }}>+ <CardAction label="List them" onClick={() => showFolded(more.serviceIds)} />+ </div>+ )}+ <Handle type="source" position={Position.Bottom} style={HIDDEN_HANDLE} />+ </div>+ );+}++export const SystemMapTrayNode = memo(TrayNodeInner);+export const SystemMapMoreNode = memo(MoreNodeInner);diff --git a/packages/ui/src/workspace/system-map/system-map.tsx b/packages/ui/src/workspace/system-map/system-map.tsxindex 20ddef078..74e3a3a5c 100644--- a/packages/ui/src/workspace/system-map/system-map.tsx+++ b/packages/ui/src/workspace/system-map/system-map.tsx@@ -1,76 +1,76 @@"use client";/**- * The Live System Map: a code-derived diagram of the workspace's services- * (nodes) and their typed relationships (edges), laid out with the shared ELK- * stack and explored through a detail drawer.+ * The Live System Map: the workspace's services and the typed relationships+ * between them, drawn a level at a time within a fixed draw budget. The+ * estate shows group cards joined by bands (or services, below the grouping+ * threshold); a group opens in place into its services; focus and between+ * levels come from the level state. Whatever does not fit is folded into a+ * "+N more" card and stated in the caption.*- * A canvas surface: the controls sit in the section header, the key in one- * row under them, and the canvas takes the width. The host supplies the graph,- * the lens control (`toolbar`) and the drawer's data; this component owns the- * edge-kind filter, the service/repository switch, hover and selection.+ * 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.*/-import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";-import {- Background,- BackgroundVariant,- Controls,- MiniMap,- ReactFlow,- ReactFlowProvider,- useReactFlow,- useStore,- type EdgeChange,- type EdgeMouseHandler,- type NodeChange,- type NodeMouseHandler,-} from "@xyflow/react";-import "@xyflow/react/dist/style.css";-import type { NodeArchitectureRole, SystemEdgeKind, SystemEdgeMatchType, SystemGraph } from "@repowise-dev/types";-import { EmptyState } from "../../shared/empty-state";-import { systemMapNodeTypes } from "./system-map-node";-import { systemMapEdgeTypes } from "./system-map-edge";-import { SystemMapLegend } from "./system-map-legend";+import { useCallback, useEffect, useMemo, useRef, 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";+import { activateEdge, activateNode, type Activation, type ActivateTrigger } from "./activate";+import { toFlowElements, type FlowElements } from "./flow-elements";+import type { LevelView } from "./levels";+import { scopeCaption } from "./scope-caption";+import { SystemMapActionsContext, type SystemMapActions } from "./system-map-actions";+import { SystemMapBreadcrumb } from "./system-map-breadcrumb";+import { SystemMapCanvas } from "./system-map-canvas";+import type { SystemMapDrawerData } from "./system-map-drawer";+import { SystemMapCanvasEmpty } from "./system-map-empty";import { SystemMapFilters } from "./system-map-filters";-import { SystemMapDrawer, type SystemMapDrawerData } from "./system-map-drawer";-import { SystemMapFocusContext, createSystemMapFocusStore } from "./system-map-focus";-import { edgeKindStyle, isGatewayRouted } from "./edge-kinds";-import { useSystemMapLayout } from "./use-system-map-layout";-import { useSystemMapPhases, type SystemMapPhase } from "./use-system-map-phases";-import { resolveViewSelection } from "./system-map-model";-import { SYSTEM_MAP_NODE_SIZE, applyCollapse, type SystemMapView } from "./layout";+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 { RepoHealth, SystemMapOverlay, SystemMapSelection } from "./types";-import { toFriendlyMessage } from "../../lib/errors";--/** Below this many nodes the whole map fits on screen and a minimap is noise. */-export const SYSTEM_MAP_MINIMAP_MIN_NODES = 40;+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";/** 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)]";-/** Width the drawer takes on desktop; selections are kept clear of it. */-const DRAWER_WIDTH = 480;--const FIT_OPTIONS = { padding: 0.08, maxZoom: 1.2 } as const;+const FADE_CSS = ".sm-canvas[data-focused] .sm-edge:not([data-active]){opacity:.22}.sm-canvas .sm-edge{transition:opacity 120ms}";export interface SystemMapProps {graph: SystemGraph | null;loading?: boolean;error?: Error | null;- /** Repo health by repo alias, joined onto service nodes (optional). */+ /** Repo health by repo alias, joined onto service and group cards (optional). */healthByRepo?: ReadonlyMap<string, RepoHealth>;/** Additive decoration from the active lens (ripple, badges, violations). */overlay?: SystemMapOverlay;- /** Per-service architecture role, named on nodes and in the drawer (optional). */+ /** Per-service architecture role, named on cards and in the rail (optional). */roleByNodeId?: ReadonlyMap<string, NodeArchitectureRole>;- /** The lens control, placed at the head of the section header. */+ /** The lens control, in the title row. */toolbar?: ReactNode;- /** Data and routes for the detail drawer. */+ /** More title-row controls after the lens (search, a between picker). */+ actions?: ReactNode;+ /** Data and routes for the rail's service and relationship details. */drawer?: SystemMapDrawerData;/** Controlled selection, so the host can put it in the URL. */selection?: SystemMapSelection;onSelectionChange?: (selection: SystemMapSelection) => void;+ /** 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;+ /** 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. */+ estateLabel?: string;/** Called as each render phase completes, for host-side timing. */onPhase?: (phase: SystemMapPhase) => void;}@@ -83,411 +83,174 @@ export function SystemMap(props: SystemMapProps) {);}-function sameSelection(a: SystemMapSelection, b: SystemMapSelection): boolean {- return a?.type === b?.type && a?.id === b?.id;-}--function SystemMapInner({- graph,- loading,- error,- healthByRepo,- overlay,- roleByNodeId,- toolbar,- drawer,- selection: controlledSelection,- onSelectionChange,- onPhase,-}: SystemMapProps) {- const [hiddenKinds, setHiddenKinds] = useState<Set<SystemEdgeKind>>(() => new Set());- const [collapsed, setCollapsed] = useState(false);- const [uncontrolledSelection, setUncontrolledSelection] = useState<SystemMapSelection>(null);- const isControlled = onSelectionChange !== undefined;- const selection = isControlled ? (controlledSelection ?? null) : uncontrolledSelection;-- // Handlers below are memoised for the component's lifetime, so they read the- // live props through a ref. A click also fires React Flow's own selection- // change; `last` drops the duplicate so the host sees one update.- const latest = useRef({ selection, onSelectionChange });- latest.current = { selection, onSelectionChange };- const last = useRef<SystemMapSelection>(selection);- last.current = selection;-- const setSelection = useCallback((next: SystemMapSelection) => {- if (sameSelection(last.current, next)) return;- last.current = next;- const notify = latest.current.onSelectionChange;- if (notify) notify(next);- else setUncontrolledSelection(next);- }, []);-- // The collapse-applied shape, before the kind filter: what the filter offers.- const shaped = useMemo(() => (graph ? applyCollapse(graph, collapsed) : null), [graph, collapsed]);- const kindCounts = useMemo(() => {- const m = new Map<SystemEdgeKind, number>();- for (const e of shaped?.edges ?? []) m.set(e.kind, (m.get(e.kind) ?? 0) + 1);- return m;- }, [shaped]);- const visibleKinds = useMemo<Set<SystemEdgeKind>>(- () => new Set([...kindCounts.keys()].filter((k) => !hiddenKinds.has(k))),- [kindCounts, hiddenKinds],- );- const view = useMemo<SystemMapView>(() => ({ visibleKinds, collapsed }), [visibleKinds, collapsed]);-- const { nodes, edges, loading: layoutLoading, viewGraph } = useSystemMapLayout({- graph,- view,- ...(healthByRepo ? { healthByRepo } : {}),- // Overlays are keyed by service; on merged repo nodes only the repo roots- // would match, which marks some repositories and not others. Off instead.- ...(overlay && !collapsed ? { overlay } : {}),- ...(roleByNodeId ? { roleByNodeId } : {}),- });- useSystemMapPhases(onPhase, viewGraph, layoutLoading);-- // Lists and the URL name raw ids; map them onto what is drawn, and show a- // hidden kind or the service view when that is the only way to draw them.- const resolved = useMemo(- () =>- graph && viewGraph- ? resolveViewSelection(selection, graph, viewGraph, collapsed)- : { selection: null, fix: null },- [selection, graph, viewGraph, collapsed],- );- const drawnSelection = resolved.selection;- const fixKey = resolved.fix ? `${resolved.fix.kind}:${"edgeKind" in resolved.fix ? resolved.fix.edgeKind : ""}` : "";- useEffect(() => {- const fix = resolved.fix;- if (!fix) return;- if (fix.kind === "expand") setCollapsed(false);- else- setHiddenKinds((prev) => {- if (!prev.has(fix.edgeKind)) return prev;- const next = new Set(prev);- next.delete(fix.edgeKind);- return next;- });- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [fixKey]);-- // Only the selected node gets a new object, so React Flow re-renders one node.- const selectedNode = drawnSelection?.type === "node" ? drawnSelection.id : null;- const drawnNodes = useMemo(- () => (selectedNode ? nodes.map((n) => (n.id === selectedNode ? { ...n, selected: true } : n)) : nodes),- [nodes, selectedNode],- );-- const matchTypes = useMemo(- () => new Set<SystemEdgeMatchType>((viewGraph?.edges ?? []).map((e) => e.match_type)),- [viewGraph],- );- const gatewayRouted = useMemo(() => (viewGraph?.edges ?? []).filter(isGatewayRouted).length, [viewGraph]);-- // Hover and selection for edges live outside React state (see system-map-focus).+/** The connector store, with the canvas's fade attribute and the selection kept in step with it. */+function useFocusStore(level: MapLevel) {const focus = useMemo(() => createSystemMapFocusStore(), []);const canvasRef = useRef<HTMLDivElement>(null);- useEffect(- () =>- focus.subscribe(() => {- canvasRef.current?.toggleAttribute("data-focused", focus.focused());- }),- [focus],- );+ useEffect(() => focus.subscribe(() => canvasRef.current?.toggleAttribute("data-focused", focus.focused())), [focus]);+ const drawnId = level.resolved?.drawnId ?? null;+ const kind = level.resolved?.drawnKind ?? null;useEffect(() => {- focus.setSelected({- node: drawnSelection?.type === "node" ? drawnSelection.id : null,- edge: drawnSelection?.type === "edge" ? drawnSelection.id : null,- });- }, [focus, drawnSelection]);-- const toggleKind = useCallback((kind: SystemEdgeKind) => {- setHiddenKinds((prev) => {- const next = new Set(prev);- if (next.has(kind)) next.delete(kind);- else next.add(kind);- return next;- });- }, []);+ focus.setSelected({ node: kind === "node" ? drawnId : null, edge: kind === "edge" ? drawnId : null });+ }, [focus, kind, drawnId]);+ return { focus, canvasRef };+}- const onNodeClick = useCallback<NodeMouseHandler>((_, node) => setSelection({ type: "node", id: node.id }), [setSelection]);- const onEdgeClick = useCallback<EdgeMouseHandler>((_, edge) => setSelection({ type: "edge", id: edge.id }), [setSelection]);- // Keyboard selection (Enter or Space on a focused node or edge) arrives as a- // React Flow selection change, and lands on the same object a click would.- const onNodesChange = useCallback(- (changes: NodeChange[]) => {- for (const c of changes) if (c.type === "select" && c.selected) setSelection({ type: "node", id: c.id });- },- [setSelection],+/** Card verbs and the canvas's activate and Escape handlers, over the level state and the selection. */+function useMapInput(levelView: LevelView | null, state: SystemMapState, onShowFolded: SystemMapProps["onShowFolded"]) {+ const { view, setView, selection, setSelection } = state;+ const actions = useMemo<SystemMapActions>(+ () => ({+ openContainer: (id) => setView(openContainer(view, id)),+ closeContainer: (id) => setView(closeContainer(view, id)),+ showFolded: onShowFolded,+ }),+ [setView, view, onShowFolded],);- const onEdgesChange = useCallback(- (changes: EdgeChange[]) => {- for (const c of changes) if (c.type === "select" && c.selected) setSelection({ type: "edge", id: c.id });+ const apply = useCallback(+ (a: Activation) => {+ if (a?.kind === "select") setSelection(a.selection);+ else if (a?.kind === "open") actions.openContainer(a.id);+ else if (a?.kind === "folded") actions.showFolded?.(a.serviceIds);},- [setSelection],+ [setSelection, actions],);- const onPaneClick = useCallback(() => setSelection(null), [setSelection]);- const onNodeMouseEnter = useCallback<NodeMouseHandler>((_, n) => focus.setHover({ node: n.id }), [focus]);- const onNodeMouseLeave = useCallback<NodeMouseHandler>(() => focus.setHover({ node: null }), [focus]);- const onEdgeMouseEnter = useCallback<EdgeMouseHandler>((_, e) => focus.setHover({ edge: e.id }), [focus]);- const onEdgeMouseLeave = useCallback<EdgeMouseHandler>(() => focus.setHover({ edge: null }), [focus]);+ const onActivate = useCallback(+ (id: string, kind: "node" | "edge", trigger: ActivateTrigger) =>+ apply(+ kind === "edge"+ ? activateEdge(levelView?.edges.find((e) => e.id === id))+ : activateNode(levelView?.nodes.find((n) => n.id === id), trigger),+ ),+ [apply, levelView],+ );+ const onEscape = useCallback(() => {+ if (selection) return setSelection(null);+ const up = backOut(view);+ if (up) setView(up);+ }, [selection, setSelection, view, setView]);+ return { actions, onActivate, onEscape };+}- // Collapsing changes node ids, so a selection cannot survive it.- const onCollapsedChange = useCallback(- (next: boolean) => {- setCollapsed(next);- setSelection(null);- },- [setSelection],+function SystemMapInner(props: SystemMapProps) {+ const { graph, healthByRepo, overlay, roleByNodeId, toolbar, actions: extraActions } = props;+ const state = useSystemMapState(props);+ const { view, setView, selection, setSelection } = state;+ const level = useMapLevel(graph, view, selection, setView, props.onPhase);+ useDropUndrawnAggregate(selection, level, setSelection);+ const { nodesById, edgesById, levelView, layout } = level;+ const { focus, canvasRef } = useFocusStore(level);+ const input = useMapInput(levelView, state, props.onShowFolded);+ const selectedId = level.resolved?.drawnId ?? null;++ const flow = useMemo<FlowElements>(+ () =>+ levelView+ ? toFlowElements({ view: levelView, positions: layout.positions, nodesById, edgesById, healthByRepo, overlay, roleByNodeId, selectedId })+ : { nodes: [], edges: [] },+ [levelView, layout.positions, nodesById, edgesById, healthByRepo, overlay, roleByNodeId, selectedId],);+ const name = useCallback((id: string) => nodesById.get(id)?.name ?? id, [nodesById]);+ const caption = useMemo(() => (levelView ? scopeCaption(levelView, name) : []), [levelView, name]);+ const legend = useMemo(() => legendKeyFor(levelView?.edges ?? [], edgesById), [levelView, edgesById]);- const isLoading = loading || layoutLoading;const hasGraph = Boolean(graph && graph.nodes.length > 0);- const hasEdges = (graph?.edges.length ?? 0) > 0;- const canCollapse = Boolean(graph?.nodes.some((n) => n.service_path));+ const rail =+ graph && levelView+ ? railContent({+ graph,+ levelView,+ selection,+ nodesById,+ edgesById,+ healthByRepo,+ roleByNodeId,+ drawer: props.drawer,+ levelRail: props.levelRail,+ onSelect: setSelection,+ onOpenGroup: input.actions.openContainer,+ })+ : null;+ const breadcrumb =+ graph && levelView && levelView.level !== "estate" ? (+ <SystemMapBreadcrumb graph={graph} level={levelView.level} view={view} onViewChange={setView} estateLabel={props.estateLabel} />+ ) : undefined;+ const banner = levelView ? (+ <div className="flex min-w-0 flex-col gap-2">+ <SystemMapFilters+ familyCounts={levelView.familyCounts}+ kindCounts={level.kindCounts}+ families={levelView.families}+ onToggleFamily={(f) => setView(toggleFamily(view, f))}+ />+ <SystemMapLegend {...legend} />+ </div>+ ) : undefined;+ const empty = (+ <SystemMapCanvasEmpty+ error={props.error}+ loading={Boolean(props.loading) || (hasGraph && layout.loading && flow.nodes.length === 0)}+ hasGraph={hasGraph}+ hasEdges={(graph?.edges.length ?? 0) > 0}+ />+ );return (<SystemMapFocusContext.Provider value={focus}>- <div className="flex min-w-0 flex-col gap-3">- {/* Section header: the lens, then what is drawn. Nothing sits on the canvas. */}- <div className="flex min-w-0 flex-wrap items-center justify-between gap-x-6 gap-y-3">- {toolbar}- <SystemMapFilters- kindCounts={kindCounts}- visibleKinds={visibleKinds}- onToggleKind={toggleKind}- canCollapse={canCollapse}- collapsed={collapsed}- onCollapsedChange={onCollapsedChange}- />- </div>-- <SystemMapLegend matchTypes={matchTypes} gatewayRouted={gatewayRouted} />-- <div- ref={canvasRef}- className={`sm-canvas relative min-w-0 overflow-hidden rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-root)] ${SYSTEM_MAP_CANVAS_HEIGHT}`}+ <SystemMapActionsContext.Provider value={input.actions}>+ <GraphCanvasShell+ variant="section"+ breadcrumb={breadcrumb}+ titleActions={toolbar || extraActions ? <>{toolbar}{extraActions}</> : undefined}+ banner={banner}+ rail={rail}+ footer={hasGraph && caption.length > 0 ? <p className="text-xs text-[var(--color-text-secondary)]">{caption.join(" ")}</p> : undefined}>- <style>{".sm-canvas[data-focused] .sm-edge:not([data-active]){opacity:.22}.sm-canvas .sm-edge{transition:opacity 120ms}"}</style>- {error ? (- <Centered>- <EmptyState title="Couldn't load the system map" description={toFriendlyMessage(error)} />- </Centered>- ) : !isLoading && !hasGraph ? (- <Centered>- <EmptyState- title="No services to map yet"- description="The system map appears once the workspace has at least two indexed repositories with detected cross-repo relationships."- />- </Centered>- ) : !isLoading && !hasEdges ? (- <Centered>- <EmptyState- title="No cross-repo relationships detected"- description="Services are indexed, but no HTTP, gRPC, event, package, database or co-change links were found between them yet."- />- </Centered>- ) : null}-- <ReactFlow- nodes={drawnNodes}- edges={edges}- nodeTypes={systemMapNodeTypes}- edgeTypes={systemMapEdgeTypes}- onNodeClick={onNodeClick}- onEdgeClick={onEdgeClick}- onNodesChange={onNodesChange}- onEdgesChange={onEdgesChange}- onPaneClick={onPaneClick}- onNodeMouseEnter={onNodeMouseEnter}- onNodeMouseLeave={onNodeMouseLeave}- onEdgeMouseEnter={onEdgeMouseEnter}- onEdgeMouseLeave={onEdgeMouseLeave}- fitView- fitViewOptions={FIT_OPTIONS}- minZoom={0.15}- maxZoom={2}- proOptions={{ hideAttribution: true }}- nodesDraggable={false}- nodesConnectable={false}- ariaLabelConfig={{ "node.a11yDescription.default": "Press Enter to open this service's details." }}- >- <Background variant={BackgroundVariant.Dots} gap={20} size={1} color="var(--color-border-hover)" />- <Controls showInteractive={false} />- {nodes.length >= SYSTEM_MAP_MINIMAP_MIN_NODES && (- <MiniMap- pannable- zoomable- bgColor="var(--color-bg-surface)"- maskColor="color-mix(in srgb, var(--color-bg-root) 70%, transparent)"- nodeColor="var(--color-border-hover)"- nodeStrokeColor="var(--color-text-tertiary)"- style={{ border: "1px solid var(--color-border-default)" }}- />- )}- <Viewport fitKey={`${collapsed}:${nodes.length}`} ready={nodes.length > 0} selection={drawnSelection} canvas={canvasRef} />- </ReactFlow>- </div>-- {graph && viewGraph && <ScopeCaption graph={graph} viewGraph={viewGraph} collapsed={collapsed} lensed={Boolean(overlay)} hidden={hiddenKinds} kindCounts={kindCounts} />}-- {graph && viewGraph && (- <SystemMapDrawer- {...drawer}- selection={drawnSelection}- graph={viewGraph}- rawGraph={graph}- collapsed={collapsed}- healthByRepo={healthByRepo}- roleByNodeId={roleByNodeId}- onClose={() => setSelection(null)}- onSelect={setSelection}+ <MapCanvas+ canvasRef={canvasRef}+ focus={focus}+ flow={flow}+ fitKey={[levelView?.level, view.open.join(","), view.focus, view.between?.a, view.between?.b].join("|")}+ settled={!layout.loading}+ onActivate={input.onActivate}+ onEscape={input.onEscape}+ onPaneClick={() => setSelection(null)}+ empty={empty}/>- )}- </div>+ </GraphCanvasShell>+ </SystemMapActionsContext.Provider></SystemMapFocusContext.Provider>);}-/**- * Owns the viewport. Fits the drawing once the layout lands and when the canvas- * resizes (`fitView` on mount alone fit an empty field, because the async- * layout places nodes after React Flow's first pass). Then, on desktop, where- * the drawer covers the canvas's right edge, pans the selection into the- * uncovered part without changing the zoom. A selection from a list below the- * map, or from the URL, would otherwise open a drawer about something hidden.- */-function Viewport({- fitKey,- ready,- selection,- canvas,-}: {+interface MapCanvasProps {+ canvasRef: RefObject<HTMLDivElement | null>;+ focus: SystemMapFocusStore;+ flow: FlowElements;+ /** Changes with the level; the canvas refits once its layout has landed. */fitKey: string;- ready: boolean;- selection: SystemMapSelection;- canvas: React.RefObject<HTMLDivElement | null>;-}) {- const rf = useReactFlow();- // Not useNodesInitialized: controlled nodes that ignore dimension changes- // never report it. The layout's node count is the signal instead.- const initialized = ready;- const width = useStore((s) => s.width);- const height = useStore((s) => s.height);- const latestSelection = useRef(selection);- latestSelection.current = selection;-- const reveal = useCallback(- (sel: SystemMapSelection) => {- if (!sel || typeof window === "undefined" || window.innerWidth < 768) return;- const el = canvas.current;- if (!el) return;- const ids =- sel.type === "node" ? [sel.id] : (() => {- const e = rf.getEdge(sel.id);- return e ? [e.source, e.target] : [];- })();- const points = ids- .map((id) => rf.getInternalNode(id))- .filter((n): n is NonNullable<typeof n> => Boolean(n))- .map((n) => ({- x: n.internals.positionAbsolute.x + SYSTEM_MAP_NODE_SIZE.width / 2,- y: n.internals.positionAbsolute.y + SYSTEM_MAP_NODE_SIZE.height / 2,- }));- if (points.length === 0) return;- const center = {- x: points.reduce((a, p) => a + p.x, 0) / points.length,- y: points.reduce((a, p) => a + p.y, 0) / points.length,- };- const rect = el.getBoundingClientRect();- const visibleRight = Math.max(Math.min(rect.right, window.innerWidth - DRAWER_WIDTH), rect.left + 240);- const screen = rf.flowToScreenPosition(center);- const margin = SYSTEM_MAP_NODE_SIZE.width / 2;- const inView =- screen.x > rect.left + margin &&- screen.x < visibleRight - margin &&- screen.y > rect.top + 40 &&- screen.y < rect.bottom - 40;- if (inView) return;- const { zoom } = rf.getViewport();- // Only move on the axis that hides it, so the map shifts as little as possible.- const xInView = screen.x > rect.left + margin && screen.x < visibleRight - margin;- const targetX = xInView ? screen.x - rect.left : (visibleRight - rect.left) / 2;- const yInView = screen.y > rect.top + 40 && screen.y < rect.bottom - 40;- const targetY = yInView ? screen.y - rect.top : rect.height / 2;- void rf.setViewport({ x: targetX - center.x * zoom, y: targetY - center.y * zoom, zoom }, { duration: 250 });- },- [rf, canvas],- );-- useEffect(() => {- if (!initialized || width === 0 || height === 0) return;- // fitView is queued inside React Flow, so the reveal waits a beat for the- // fitted viewport rather than reading the one it replaces.- let reveal2 = 0;- const id = requestAnimationFrame(() => {- void rf.fitView(FIT_OPTIONS);- reveal2 = window.setTimeout(() => reveal(latestSelection.current), 80);- });- return () => {- cancelAnimationFrame(id);- window.clearTimeout(reveal2);- };- }, [rf, initialized, fitKey, width, height, reveal]);-- const selKey = selection ? `${selection.type}:${selection.id}` : "";- useEffect(() => {- if (initialized) reveal(latestSelection.current);- }, [selKey, initialized, reveal]);-- return null;+ settled: boolean;+ onActivate: (id: string, kind: "node" | "edge", trigger: ActivateTrigger) => void;+ onEscape: () => void;+ onPaneClick: () => void;+ empty: ReactNode;}-/** What is drawn and what is not, stated beside the canvas. */-function ScopeCaption({- graph,- viewGraph,- collapsed,- lensed,- hidden,- kindCounts,-}: {- graph: SystemGraph;- viewGraph: SystemGraph;- collapsed: boolean;- lensed: boolean;- hidden: ReadonlySet<SystemEdgeKind>;- kindCounts: ReadonlyMap<SystemEdgeKind, number>;-}) {- const repoOf = new Map(graph.nodes.map((n) => [n.id, n.repo]));- const intraRepo = graph.edges.filter((e) => repoOf.get(e.source) === repoOf.get(e.target)).length;- const hiddenParts = [...hidden]- .filter((k) => (kindCounts.get(k) ?? 0) > 0)- .map((k) => `${kindCounts.get(k)} ${edgeKindStyle(k).label}`);- const nodes = viewGraph.nodes.length;- const edges = viewGraph.edges.length;-- const parts = [- collapsed- ? `Drawing ${nodes} ${nodes === 1 ? "repository" : "repositories"} and ${edges} ${edges === 1 ? "relationship" : "relationships"}. Edges of one kind between the same two repositories are merged, and ${intraRepo} ${intraRepo === 1 ? "relationship" : "relationships"} inside a repository ${intraRepo === 1 ? "is" : "are"} not drawn.`- : `Drawing ${nodes} ${nodes === 1 ? "service" : "services"} and ${edges} ${edges === 1 ? "relationship" : "relationships"}.`,- hiddenParts.length > 0 ? `Hidden by the edge filter: ${hiddenParts.join(", ")}.` : null,- // Lens results name services, and a merged node is several of them.- collapsed && lensed ? "Lens marks are drawn per service, so they are off in this view; switch to Services to see them." : null,- "Placement follows structural dependencies; co-change lines do not move services.",- ];-- return <p className="text-xs text-[var(--color-text-tertiary)]">{parts.filter(Boolean).join(" ")}</p>;-}--/**- * Empty/error state centred over the canvas box. Deliberately absolute: it is- * the canvas's own "nothing to draw" copy, not chrome competing with a diagram.- */-function Centered({ children }: { children: React.ReactNode }) {+function MapCanvas({ canvasRef, focus, flow, fitKey, settled, onActivate, onEscape, onPaneClick, empty }: MapCanvasProps) {return (- <div className="pointer-events-none absolute inset-0 z-[3] flex items-center justify-center">- {children}+ <div ref={canvasRef} className={`sm-canvas relative min-w-0 ${SYSTEM_MAP_CANVAS_HEIGHT}`}>+ <style>{FADE_CSS}</style>+ <SystemMapCanvas+ nodes={flow.nodes}+ edges={flow.edges}+ focus={focus}+ fitKey={fitKey}+ settled={settled}+ onActivate={onActivate}+ onPaneClick={onPaneClick}+ onEscape={onEscape}+ empty={empty}+ /></div>);}diff --git a/packages/ui/src/workspace/system-map/types.ts b/packages/ui/src/workspace/system-map/types.tsindex 4750f173a..908f1660e 100644--- a/packages/ui/src/workspace/system-map/types.ts+++ b/packages/ui/src/workspace/system-map/types.ts@@ -101,8 +101,14 @@ export function resolveEdgeOverlay(return { highlighted, dimmed, ...(badge ? { badge } : {}) };}-/** Either a node or an edge selected in the map (drives the inspector). */+/**+ * What the map has selected (drives the rail). `node` is a service id and+ * `edge` a system edge id, so a host can put either in its URL; `group` is a+ * group id and `band` the id of a band drawn at the current level.+ */export type SystemMapSelection =| { type: "node"; id: string }| { type: "edge"; id: string }+ | { type: "group"; id: string }+ | { type: "band"; id: string }| null;diff --git a/packages/ui/src/workspace/system-map/use-map-level.ts b/packages/ui/src/workspace/system-map/use-map-level.tsnew file mode 100644index 000000000..350b089ff--- /dev/null+++ b/packages/ui/src/workspace/system-map/use-map-level.ts@@ -0,0 +1,82 @@+"use client";++/**+ * From graph and level state to what the canvas draws: the drawn levels+ * view, its positions (off the main thread, cached per scope), and the+ * selection mapped onto it. When a selection from the URL or a list below+ * the map is hidden at the current level, opens what holds it, once per+ * selection.+ */++import { useEffect, useMemo, useRef } from "react";+import type { SystemEdge, SystemGraph, SystemNode } from "@repowise-dev/types";+import { kindCountsByFamily } from "./edge-families";+import { buildLevelView, type LevelView } from "./levels";+import { resolveSelection, type ResolvedSelection } from "./selection-fix";+import type { SystemMapSelection } from "./types";+import { useLevelLayout, type LevelLayout } from "./use-level-layout";+import { useSystemMapPhases, type SystemMapPhase } from "./use-system-map-phases";+import { sameMapView, toLevelViewState, type MapViewState } from "./view-state";++export interface MapLevel {+ nodesById: ReadonlyMap<string, SystemNode>;+ edgesById: ReadonlyMap<string, SystemEdge>;+ kindCounts: ReturnType<typeof kindCountsByFamily>;+ levelView: LevelView | null;+ layout: LevelLayout;+ resolved: ResolvedSelection | null;+}++export function useMapLevel(+ graph: SystemGraph | null,+ view: MapViewState,+ selection: SystemMapSelection,+ setView: (next: MapViewState) => void,+ onPhase?: (phase: SystemMapPhase) => void,+): MapLevel {+ const nodesById = useMemo(() => new Map<string, SystemNode>((graph?.nodes ?? []).map((n) => [n.id, n])), [graph]);+ const edgesById = useMemo(() => new Map<string, SystemEdge>((graph?.edges ?? []).map((e) => [e.id, e])), [graph]);+ const kindCounts = useMemo(() => kindCountsByFamily(graph?.edges ?? []), [graph]);++ const levelState = useMemo(() => toLevelViewState(view), [view]);+ const levelView = useMemo(() => (graph ? buildLevelView(graph, levelState) : null), [graph, levelState]);+ const layout = useLevelLayout({ graph, view: levelView });+ useSystemMapPhases(onPhase, levelView, layout.loading);++ const resolved = useMemo(+ () => (levelView ? resolveSelection(selection, levelView, edgesById, view) : null),+ [selection, levelView, edgesById, view],+ );+ const fix = resolved?.fix ?? null;+ const fixedFor = useRef<string | null>(null);+ useEffect(() => {+ const key = selection ? `${selection.type}:${selection.id}` : null;+ // Nothing to fix: forget the last fix, so reselecting a hidden service opens it again.+ if (!fix) {+ fixedFor.current = null;+ return;+ }+ if (fixedFor.current === key) return;+ fixedFor.current = key;+ if (!sameMapView(fix, view)) setView(fix);+ }, [selection, fix, view, setView]);++ return { nodesById, edgesById, kindCounts, levelView, layout, resolved };+}++/**+ * A group or band selection names something drawn at one level only. Once+ * the level changes and it is no longer drawn, it is dropped, so the rail+ * and Escape never act on a selection the reader cannot see.+ */+export function useDropUndrawnAggregate(+ selection: SystemMapSelection,+ level: MapLevel,+ setSelection: (next: SystemMapSelection) => void,+): void {+ const stale =+ (selection?.type === "group" || selection?.type === "band") && level.levelView !== null && !level.resolved?.drawnId;+ useEffect(() => {+ if (stale) setSelection(null);+ }, [stale, setSelection]);+}diff --git a/packages/ui/src/workspace/system-map/use-system-map-layout.ts b/packages/ui/src/workspace/system-map/use-system-map-layout.tsdeleted file mode 100644index 05e7d0281..000000000--- a/packages/ui/src/workspace/system-map/use-system-map-layout.ts+++ /dev/null@@ -1,152 +0,0 @@-"use client";--/**- * Computes the React Flow node/edge arrays for the Live System Map: applies the- * view filters, runs the async ELK layout, then joins health + overlay onto- * each element. Mirrors the C4 view's `use-c4-layout` pattern (async layout,- * loading flag, cancel-on-unmount). Pure inputs in, render-ready arrays out.- */--import { useEffect, useMemo, useRef, useState } from "react";-import { MarkerType, type Edge, type Node } from "@xyflow/react";-import type { NodeArchitectureRole, SystemGraph } from "@repowise-dev/types";-import { roleStyle } from "./architecture";-import {- applyCollapse,- applyView,- computeSystemMapPositions,- layoutSignature,- type SystemMapView,-} from "./layout";-import {- resolveEdgeOverlay,- resolveNodeOverlay,- type RepoHealth,- type SystemMapEdgeData,- type SystemMapNodeData,- type SystemMapOverlay,-} from "./types";--export interface UseSystemMapLayoutArgs {- graph: SystemGraph | null;- view: SystemMapView;- /** Repo health by repo alias, joined onto service nodes (optional). */- healthByRepo?: ReadonlyMap<string, RepoHealth>;- overlay?: SystemMapOverlay;- /** Per-service role, named on the node. Service ids only, so not in repo view. */- roleByNodeId?: ReadonlyMap<string, NodeArchitectureRole>;-}--export interface SystemMapLayout {- nodes: Node<SystemMapNodeData>[];- edges: Edge<SystemMapEdgeData>[];- loading: boolean;- /**- * The graph actually on screen (collapse + filters applied). The inspector- * must resolve selections against this, not the raw graph: in repo view the- * ids it can be handed only exist here.- */- viewGraph: SystemGraph | null;-}--export function useSystemMapLayout({- graph,- view,- healthByRepo,- overlay,- roleByNodeId,-}: UseSystemMapLayoutArgs): SystemMapLayout {- const viewGraph = useMemo(() => (graph ? applyView(graph, view) : null), [graph, view]);-- // Laid out from the collapse state only. Toggling an edge-kind filter leaves- // this identical, so the effect below sees the same signature and never- // re-runs ELK — the map holds still and the layout is not paid again.- const layoutGraph = useMemo(- () => (graph ? applyCollapse(graph, view.collapsed) : null),- [graph, view.collapsed],- );- const signature = useMemo(- () => (layoutGraph ? layoutSignature(layoutGraph) : null),- [layoutGraph],- );-- const [positions, setPositions] = useState<Map<string, { x: number; y: number }> | null>(null);- const [loading, setLoading] = useState(true);-- // Positions keyed by layout signature, so collapsing and un-collapsing is free- // after the first pass in each direction. Dropped whenever a new graph arrives:- // one graph has only the two collapse shapes, so holding entries for superseded- // graphs would grow the map for refetches it can never serve again.- const cache = useRef(new Map<string, Map<string, { x: number; y: number }>>());- const cachedGraph = useRef(graph);- if (cachedGraph.current !== graph) {- cachedGraph.current = graph;- cache.current.clear();- }-- useEffect(() => {- let cancelled = false;- if (!layoutGraph || !signature || layoutGraph.nodes.length === 0) {- setPositions(new Map());- setLoading(false);- return;- }- const cached = cache.current.get(signature);- if (cached) {- setPositions(cached);- setLoading(false);- return;- }- setLoading(true);- computeSystemMapPositions(layoutGraph).then(- (result) => {- cache.current.set(signature, result);- if (!cancelled) {- setPositions(result);- setLoading(false);- }- },- () => {- if (!cancelled) setLoading(false);- },- );- return () => {- cancelled = true;- };- }, [layoutGraph, signature]);-- const nodes = useMemo<Node<SystemMapNodeData>[]>(() => {- if (!viewGraph || !positions) return [];- return viewGraph.nodes.map((node) => {- const pos = positions.get(node.id);- return {- id: node.id,- type: "systemService",- position: { x: pos?.x ?? 0, y: pos?.y ?? 0 },- data: {- node,- health: healthByRepo?.get(node.repo) ?? null,- overlay: resolveNodeOverlay(overlay, node.id),- role: (() => {- const r = view.collapsed ? undefined : roleByNodeId?.get(node.id);- return r ? roleStyle(r.role).label : null;- })(),- },- };- });- }, [viewGraph, positions, healthByRepo, overlay, roleByNodeId, view.collapsed]);-- const edges = useMemo<Edge<SystemMapEdgeData>[]>(() => {- if (!viewGraph) return [];- return viewGraph.edges.map((edge) => ({- id: edge.id,- source: edge.source,- target: edge.target,- type: "systemEdge",- markerEnd: { type: MarkerType.ArrowClosed, width: 14, height: 14, color: "var(--color-diagram-edge)" },- data: { edge, overlay: resolveEdgeOverlay(overlay, edge.id) },- }));- }, [viewGraph, overlay]);-- return { nodes, edges, loading, viewGraph };-}diff --git a/packages/ui/src/workspace/system-map/use-system-map-phases.ts b/packages/ui/src/workspace/system-map/use-system-map-phases.tsindex 2cbf5ad8f..71c3db114 100644--- a/packages/ui/src/workspace/system-map/use-system-map-phases.ts+++ b/packages/ui/src/workspace/system-map/use-system-map-phases.ts@@ -7,7 +7,6 @@*/import { useEffect, useRef } from "react";-import type { SystemGraph } from "@repowise-dev/types";/*** `aggregate`: a new drawn graph is computed (every view change). `layout`: a@@ -18,7 +17,7 @@ export type SystemMapPhase = "aggregate" | "layout" | "paint";export function useSystemMapPhases(onPhase: ((phase: SystemMapPhase) => void) | undefined,- viewGraph: SystemGraph | null,+ viewGraph: { nodes: readonly unknown[] } | null,layoutLoading: boolean,): void {const notify = useRef(onPhase);diff --git a/packages/ui/src/workspace/system-map/use-system-map-state.ts b/packages/ui/src/workspace/system-map/use-system-map-state.tsnew file mode 100644index 000000000..88a99e8d8--- /dev/null+++ b/packages/ui/src/workspace/system-map/use-system-map-state.ts@@ -0,0 +1,59 @@+"use client";++/**+ * The map's two pieces of reader state, each controlled when the host passes+ * a change handler (so it can live in the URL) and held here otherwise: the+ * level state (open groups, focus, between, families) and the selection.+ * Setters are stable for the component's lifetime and read the live props+ * through a ref, so handlers built on them never go stale.+ */++import { useCallback, useRef, useState } from "react";+import type { SystemMapSelection } from "./types";+import { ESTATE_VIEW, sameMapView, type MapViewState } from "./view-state";++function sameSelection(a: SystemMapSelection, b: SystemMapSelection): boolean {+ return a?.type === b?.type && a?.id === b?.id;+}++export interface SystemMapStateArgs {+ view?: MapViewState | undefined;+ onViewChange?: ((view: MapViewState) => void) | undefined;+ selection?: SystemMapSelection | undefined;+ onSelectionChange?: ((selection: SystemMapSelection) => void) | undefined;+}++export interface SystemMapState {+ view: MapViewState;+ setView: (next: MapViewState) => void;+ selection: SystemMapSelection;+ setSelection: (next: SystemMapSelection) => void;+}++export function useSystemMapState({ view, onViewChange, selection, onSelectionChange }: SystemMapStateArgs): SystemMapState {+ const [ownView, setOwnView] = useState<MapViewState>(ESTATE_VIEW);+ const [ownSelection, setOwnSelection] = useState<SystemMapSelection>(null);+ const currentView = onViewChange ? (view ?? ESTATE_VIEW) : ownView;+ const currentSelection = onSelectionChange ? (selection ?? null) : ownSelection;++ const live = useRef({ currentView, currentSelection, onViewChange, onSelectionChange });+ live.current = { currentView, currentSelection, onViewChange, onSelectionChange };++ const setView = useCallback((next: MapViewState) => {+ const l = live.current;+ if (sameMapView(l.currentView, next)) return;+ l.currentView = next;+ if (l.onViewChange) l.onViewChange(next);+ else setOwnView(next);+ }, []);++ const setSelection = useCallback((next: SystemMapSelection) => {+ const l = live.current;+ if (sameSelection(l.currentSelection, next)) return;+ l.currentSelection = next;+ if (l.onSelectionChange) l.onSelectionChange(next);+ else setOwnSelection(next);+ }, []);++ return { view: currentView, setView, selection: currentSelection, setSelection };+}diff --git a/packages/ui/src/workspace/system-map/view-state.ts b/packages/ui/src/workspace/system-map/view-state.tsnew file mode 100644index 000000000..b81a56bdc--- /dev/null+++ b/packages/ui/src/workspace/system-map/view-state.ts@@ -0,0 +1,138 @@+/**+ * The map's level state as plain data: which groups are open, which service+ * is focused, which two services are compared, and which edge families are+ * drawn. A host keeps it in its URL (`open`, `focus`, `a`, `b`, `kinds`);+ * this module reads and writes those params and steps between levels, so+ * every host walks the levels the same way. Pure, no React.+ */++import { DEFAULT_EDGE_FAMILIES, EDGE_FAMILY_ORDER, type EdgeFamily } from "./edge-families";+import type { LevelViewState } from "./level-types";++/** The token `open` uses for the "Not linked at runtime" tray. Group ids carry a `source:` prefix, so it cannot clash. */+export const TRAY_OPEN_TOKEN = "tray";++export interface MapViewState {+ /** Opened group ids in the order they were opened, plus `TRAY_OPEN_TOKEN` when the tray is open. */+ open: readonly string[];+ /** Service id at the centre of the focus level. */+ focus: string | null;+ /** Two service ids compared at the between level. */+ between: { a: string; b: string } | null;+ /** Families drawn; null is the default (Runtime and Data). */+ families: readonly EdgeFamily[] | null;+}++export const ESTATE_VIEW: MapViewState = { open: [], focus: null, between: null, families: null };++/** The URL params the map state owns. */+export const MAP_VIEW_PARAMS = ["open", "focus", "a", "b", "kinds"] as const;++const KNOWN_FAMILIES: ReadonlySet<string> = new Set(EDGE_FAMILY_ORDER);++function list(value: string | null): string[] {+ if (!value) return [];+ // A Set keeps first-seen order and drops repeats.+ return [...new Set(value.split(",").map((v) => v.trim()).filter(Boolean))];+}++/**+ * State from URL params. Unknown family names are dropped; a `kinds` that+ * names none we know reads as the default rather than as "draw nothing".+ * `a` without `b` (or the same id twice) is no comparison.+ */+export function parseMapView(get: (key: string) => string | null): MapViewState {+ const families = list(get("kinds")).filter((f): f is EdgeFamily => KNOWN_FAMILIES.has(f));+ const a = get("a");+ const b = get("b");+ return {+ open: list(get("open")),+ focus: get("focus") || null,+ between: a && b && a !== b ? { a, b } : null,+ families: families.length > 0 ? EDGE_FAMILY_ORDER.filter((f) => families.includes(f)) : null,+ };+}++function sameFamilies(families: readonly EdgeFamily[], defaults: ReadonlySet<EdgeFamily>): boolean {+ return families.length === defaults.size && families.every((f) => defaults.has(f));+}++/** Write `state` into `params`, removing every map param it does not set, so the URL stays short at the estate. */+export function writeMapView(params: URLSearchParams, state: MapViewState): void {+ for (const key of MAP_VIEW_PARAMS) params.delete(key);+ if (state.open.length > 0) params.set("open", state.open.join(","));+ if (state.focus) params.set("focus", state.focus);+ if (state.between) {+ params.set("a", state.between.a);+ params.set("b", state.between.b);+ }+ if (state.families && !sameFamilies(state.families, DEFAULT_EDGE_FAMILIES)) {+ params.set("kinds", EDGE_FAMILY_ORDER.filter((f) => state.families!.includes(f)).join(","));+ }+}++/** The families a state draws, as the levels model takes them. */+export function drawnFamilies(state: MapViewState): ReadonlySet<EdgeFamily> {+ return state.families ? new Set(state.families) : DEFAULT_EDGE_FAMILIES;+}++/** What the levels model needs from the state. */+export function toLevelViewState(state: MapViewState): LevelViewState {+ return {+ open: state.open.filter((id) => id !== TRAY_OPEN_TOKEN),+ openTray: state.open.includes(TRAY_OPEN_TOKEN),+ focus: state.focus,+ between: state.between,+ families: drawnFamilies(state),+ };+}++/** Open a group (or the tray) in place; reopening one moves it to the end, so Escape closes it first. */+export function openContainer(state: MapViewState, id: string): MapViewState {+ return { ...state, open: [...state.open.filter((o) => o !== id), id] };+}++export function closeContainer(state: MapViewState, id: string): MapViewState {+ if (!state.open.includes(id)) return state;+ return { ...state, open: state.open.filter((o) => o !== id) };+}++/** Show or hide one family. The last drawn family stays: a map with no edges drawn is not a view anyone asks for. */+export function toggleFamily(state: MapViewState, family: EdgeFamily): MapViewState {+ const current = drawnFamilies(state);+ if (current.has(family) && current.size === 1) return state;+ const next = current.has(family) ? [...current].filter((f) => f !== family) : [...current, family];+ return { ...state, families: EDGE_FAMILY_ORDER.filter((f) => next.includes(f)) };+}++/** Draw `family` if it is hidden; the state itself when it is already drawn. */+export function showFamily(state: MapViewState, family: EdgeFamily): MapViewState {+ return drawnFamilies(state).has(family) ? state : toggleFamily(state, family);+}++/**+ * One level up, for Escape and the breadcrumb: leave Between, then Focus,+ * then close the last opened group. Null at the estate, where there is+ * nothing left to back out of.+ */+export function backOut(state: MapViewState): MapViewState | null {+ if (state.between) return { ...state, between: null };+ if (state.focus) return { ...state, focus: null };+ if (state.open.length > 0) return { ...state, open: state.open.slice(0, -1) };+ return null;+}++/** The estate with the same families drawn: the breadcrumb's root. */+export function toEstate(state: MapViewState): MapViewState {+ return { ...ESTATE_VIEW, families: state.families };+}++export function sameMapView(x: MapViewState, y: MapViewState): boolean {+ return (+ x.open.join(",") === y.open.join(",") &&+ x.focus === y.focus &&+ x.between?.a === y.between?.a &&+ x.between?.b === y.between?.b &&+ [...drawnFamilies(x)].sort().join(",") === [...drawnFamilies(y)].sort().join(",")+ );+}diff --git a/packages/web/messages/en.json b/packages/web/messages/en.jsonindex 3661cd1ee..d0a8c1fbe 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -1983,6 +1983,7 @@}},"systemMap": {+ "estate": "Estate","title": "System map","description": "Services and the typed relationships between them, rebuilt from code and git history on every workspace update.","section": {diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex 183ee67b4..be832928c 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -1983,6 +1983,7 @@}},"systemMap": {+ "estate": "服务全景","title": "系统地图","description": "服务及它们之间的带类型关系,每次工作区更新都会从代码与 git 历史重建。","section": {diff --git a/packages/web/src/app/workspace/system-map/page.tsx b/packages/web/src/app/workspace/system-map/page.tsxindex d371148a0..9252a0dd8 100644--- a/packages/web/src/app/workspace/system-map/page.tsx+++ b/packages/web/src/app/workspace/system-map/page.tsx@@ -1,6 +1,6 @@"use client";-import { useCallback, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import Link from "next/link";import { useRouter, useSearchParams } from "next/navigation";import { useTranslations } from "next-intl";@@ -16,7 +16,10 @@ import {buildBlastRadiusOverlay,buildBreakingChangeOverlay,buildConformanceOverlay,+ parseMapView,selectionRepo,+ writeMapView,+ type MapViewState,type ContractRef,type RepoHealth,type SegmentOption,@@ -50,6 +53,8 @@ import { markSystemMap, useSystemMapPerfMarks } from "@/lib/system-map-perf";import { useRepoContracts } from "./use-repo-contracts";const LENSES: readonly SystemMapLens[] = ["none", "blast", "breaking", "conformance", "core"];+/** URL params a selection is written to, one per selection type. */+const SELECTION_PARAMS = ["node", "edge", "group", "band"] as const;/** The minimal translator shape the copy helpers below need; next-intl's `t` fits. */type Translator = (key: string, values?: Record<string, string | number>) => string;@@ -84,14 +89,15 @@ export default function SystemMapPage() {useSystemMapPerfMarks(graph);- // Selection, lens and blast target live in the URL, so a view can be linked to.+ // Selection, level, lens and blast target live in the URL, so a view can be linked to.const selection = useMemo<SystemMapSelection>(() => {- const node = searchParams.get("node");- if (node) return { type: "node", id: node };- const edge = searchParams.get("edge");- if (edge) return { type: "edge", id: edge };+ for (const type of SELECTION_PARAMS) {+ const id = searchParams.get(type);+ if (id) return { type, id };+ }return null;}, [searchParams]);+ const mapView = useMemo(() => parseMapView((key) => searchParams.get(key)), [searchParams]);const lensOptions = useMemo(() =>lensOptionsFor(t, graph, breaking, conformance, architecture, {@@ -119,11 +125,18 @@ export default function SystemMapPage() {: "none";const blastTarget = lens === "blast" ? searchParams.get("from") : null;+ // The query last written but not yet rendered: a second edit in the same+ // tick builds on it, so neither edit is lost.+ const pendingQuery = useRef<string | null>(null);+ useEffect(() => {+ pendingQuery.current = null;+ }, [searchParams]);const replaceParams = useCallback((edit: (p: URLSearchParams) => void) => {- const params = new URLSearchParams(searchParams.toString());+ const params = new URLSearchParams(pendingQuery.current ?? searchParams.toString());edit(params);const query = params.toString();+ pendingQuery.current = query;// `replace`, not `push`: exploring a diagram should not fill the back button.router.replace(query ? `?${query}` : "/workspace/system-map", { scroll: false });},@@ -133,12 +146,15 @@ export default function SystemMapPage() {const onSelectionChange = useCallback((next: SystemMapSelection) =>replaceParams((p) => {- p.delete("node");- p.delete("edge");+ for (const key of SELECTION_PARAMS) p.delete(key);if (next) p.set(next.type, next.id);}),[replaceParams],);+ const onViewChange = useCallback(+ (next: MapViewState) => replaceParams((p) => writeMapView(p, next)),+ [replaceParams],+ );const setLens = useCallback((next: SystemMapLens, from?: string | null) =>@@ -246,6 +262,9 @@ export default function SystemMapPage() {{...(overlay ? { overlay } : {})}selection={selection}onSelectionChange={onSelectionChange}+ view={mapView}+ onViewChange={onViewChange}+ estateLabel={t("estate")}onPhase={markSystemMap}drawer={drawer}toolbar={