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
perf(ui): ELK in a worker with per-level layout cache (#4616)
Raghav Chamadiya38870f588a61
diff --git a/packages/ui/__tests__/c4/elk-runner.test.ts b/packages/ui/__tests__/c4/elk-runner.test.tsnew file mode 100644index 000000000..5361b0eec--- /dev/null+++ b/packages/ui/__tests__/c4/elk-runner.test.ts@@ -0,0 +1,96 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { createRequire } from "node:module";+import { resetElkWorkerForTests, runElkLayout } from "../../src/c4/layout/elk-runner";++// The worker script's in-process twin: the same message protocol the real+// worker speaks, without a thread. jsdom has no Worker, so the tests stub one.+const { Worker: InProcessElk } = createRequire(import.meta.url)("elkjs/lib/elk-worker.min.js") as {+ Worker: new () => { postMessage(msg: unknown): void; onmessage: ((e: { data: unknown }) => void) | null };+};++const graph = () => ({+ id: "root",+ layoutOptions: { "elk.algorithm": "layered" },+ children: [+ { id: "a", width: 10, height: 10 },+ { id: "b", width: 10, height: 10 },+ ],+ edges: [{ id: "e", sources: ["a"], targets: ["b"] }],+});++afterEach(() => {+ resetElkWorkerForTests();+ vi.unstubAllGlobals();+});++describe("runElkLayout", () => {+ it("lays out on the main thread when no Worker exists", async () => {+ const laid = await runElkLayout(graph(), { worker: true });+ expect(laid.children?.map((c) => c.id)).toEqual(["a", "b"]);+ });++ it("sends the layout to one shared worker built from the ELK worker script", async () => {+ const urls: string[] = [];+ const posted: string[] = [];+ class StubWorker extends EventTarget {+ onmessage: ((e: { data: unknown }) => void) | null = null;+ private elk = new InProcessElk();+ constructor(url: URL | string) {+ super();+ urls.push(String(url));+ this.elk.onmessage = (e) => this.onmessage?.(e);+ }+ postMessage(msg: { cmd: string }) {+ posted.push(msg.cmd);+ this.elk.postMessage(msg);+ }+ terminate() {}+ }+ vi.stubGlobal("Worker", StubWorker);+ const first = await runElkLayout(graph(), { worker: true });+ await runElkLayout(graph(), { worker: true });+ expect(urls).toHaveLength(1);+ expect(urls[0]).toContain("elk-worker.min.js");+ expect(posted.filter((c) => c === "layout")).toHaveLength(2);+ expect(first.children?.find((c) => c.id === "b")?.y).toBeGreaterThan(0);+ });++ it("falls back to the main thread when the worker fails to load, and does not retry it", async () => {+ let started = 0;+ class BrokenWorker extends EventTarget {+ onmessage = null;+ constructor() {+ super();+ started += 1;+ setTimeout(() => this.dispatchEvent(new Event("error")), 0);+ }+ postMessage() {}+ terminate() {}+ }+ vi.stubGlobal("Worker", BrokenWorker);+ const laid = await runElkLayout(graph(), { worker: true });+ expect(laid.children).toHaveLength(2);+ await runElkLayout(graph(), { worker: true });+ expect(started).toBe(1);+ });++ it("falls back when the Worker constructor throws", async () => {+ vi.stubGlobal(+ "Worker",+ class {+ constructor() {+ throw new Error("blocked by CSP");+ }+ },+ );+ const laid = await runElkLayout(graph(), { worker: true });+ expect(laid.children).toHaveLength(2);+ });++ it("stays on the main thread unless asked for the worker", async () => {+ const ctor = vi.fn();+ vi.stubGlobal("Worker", ctor);+ await runElkLayout(graph());+ expect(ctor).not.toHaveBeenCalled();+ });+});diff --git a/packages/ui/__tests__/workspace/system-map-level-layout.test.ts b/packages/ui/__tests__/workspace/system-map-level-layout.test.tsnew file mode 100644index 000000000..64bf9d99e--- /dev/null+++ b/packages/ui/__tests__/workspace/system-map-level-layout.test.ts@@ -0,0 +1,204 @@+import { describe, expect, it } from "vitest";+import { renderHook, waitFor } from "@testing-library/react";+import { buildLevelView } from "../../src/workspace/system-map/levels";+import { TRAY_NODE_ID, groupNodeId } from "../../src/workspace/system-map/estate-view";+import { placeFocusColumns } from "../../src/workspace/system-map/focus-columns";+import {+ CONTAINER_PADDING,+ LEVEL_NODE_SIZES,+ ROOT_SCOPE,+ fitContainer,+ orderByPrevious,+ planLevelLayout,+ planSignature,+} from "../../src/workspace/system-map/layout-scopes";+import {+ computeLevelLayout,+ createLayoutCache,+ levelLayoutInput,+ type LayoutCache,+} from "../../src/workspace/system-map/level-layout";+import { useLevelLayout } from "../../src/workspace/system-map/use-level-layout";+import { DEFAULT_EDGE_FAMILIES, type EdgeFamily } from "../../src/workspace/system-map/edge-families";+import type { LevelsEdge, LevelsGraph } from "../../src/workspace/system-map/level-types";+import { ESHOP_GRAPH } from "./fixtures/eshop-system-graph";++function edge(source: string, target: string, kind: LevelsEdge["kind"] = "http"): LevelsEdge {+ return { id: `${source}->${target}:${kind}`, source, target, kind, weight: 1, strategy: null };+}++/** `groups` groups of `size` services; each group is a chain, and group i calls group i+1. */+function groupedEstate(groups: number, size: number): LevelsGraph {+ const nodes = [];+ const edges: LevelsEdge[] = [];+ for (let g = 0; g < groups; g++) {+ for (let s = 0; s < size; s++) {+ nodes.push({ id: `g${g}.s${s}`, name: `g${g}.s${s}`, repo: `g${g}.s${s}`, group: `g${g}` });+ if (s > 0) edges.push(edge(`g${g}.s${s - 1}`, `g${g}.s${s}`));+ }+ if (g + 1 < groups) edges.push(edge(`g${g}.s1`, `g${g + 1}.s0`, "event"));+ }+ // The model draws groups only when the payload lists them.+ return { nodes, edges, groups: Array.from({ length: groups }, (_, g) => ({ id: `g${g}` })) };+}++/** Counts cache traffic, so a test can tell a cache hit from an ELK run. */+function countingCache(): LayoutCache & { hits: number; misses: number } {+ const inner = createLayoutCache();+ const c = {+ hits: 0,+ misses: 0,+ get(key: string) {+ const v = inner.get(key);+ if (v) c.hits += 1;+ else c.misses += 1;+ return v;+ },+ set: inner.set,+ clear: inner.clear,+ };+ return c;+}++const all = new Set<EdgeFamily>(["runtime", "data", "build", "history"]);++describe("planLevelLayout", () => {+ it("lays a flat estate out as one root scope over every drawn card", () => {+ const view = buildLevelView(ESHOP_GRAPH);+ const plan = planLevelLayout(view.nodes, ESHOP_GRAPH.edges);+ expect(plan.interiors).toEqual([]);+ expect(plan.root.id).toBe(ROOT_SCOPE);+ expect(plan.root.nodes.map((n) => n.id)).toEqual(view.nodes.map((n) => n.id));+ // Build links into the closed tray still shape placement, lifted to the tray card.+ expect(plan.root.edges.some((e) => e.target === TRAY_NODE_ID)).toBe(true);+ });++ it("keys on every family but History, so a family toggle changes nothing", () => {+ const g: LevelsGraph = {+ nodes: ["a", "b", "c"].map((id) => ({ id, name: id, repo: id })),+ edges: [edge("a", "b"), edge("b", "c", "package"), edge("a", "c", "co_change")],+ };+ const runtimeOnly = buildLevelView(g);+ const everything = buildLevelView(g, { families: all });+ const plan = planLevelLayout(runtimeOnly.nodes, g.edges);+ expect(planSignature(plan)).toBe(planSignature(planLevelLayout(everything.nodes, g.edges)));+ // c has no runtime link, so it sits in the tray; co-change never shapes placement.+ expect(plan.root.edges.map((e) => e.id)).toEqual(["a>b", `b>${TRAY_NODE_ID}`]);+ });++ it("gives an open group its own scope and lifts cross-group edges to its box", () => {+ const g = groupedEstate(3, 15);+ const view = buildLevelView(g, { open: ["g1"] });+ const plan = planLevelLayout(view.nodes, g.edges);+ expect(plan.interiors.map((s) => s.id)).toEqual([groupNodeId("g1")]);+ const interior = plan.interiors[0]!;+ expect(interior.nodes).toHaveLength(15);+ expect(interior.edges).toHaveLength(14);+ expect(plan.root.nodes.map((n) => n.id).sort()).toEqual([groupNodeId("g0"), groupNodeId("g1"), groupNodeId("g2")]);+ // The open group's box is sized later, from its interior.+ expect(plan.root.nodes.find((n) => n.id === groupNodeId("g1"))!.width).toBe(0);+ expect(plan.root.edges.map((e) => e.id)).toEqual([+ `${groupNodeId("g0")}>${groupNodeId("g1")}`,+ `${groupNodeId("g1")}>${groupNodeId("g2")}`,+ ]);+ });+});++describe("orderByPrevious", () => {+ const n = (id: string) => ({ id, width: 1, height: 1 });+ it("puts known nodes first in reading order, then new ones in drawn order", () => {+ const previous = new Map([+ ["b", { x: 0, y: 100 }],+ ["a", { x: 300, y: 0 }],+ ["c", { x: 0, y: 0 }],+ ]);+ expect(orderByPrevious([n("new2"), n("a"), n("b"), n("new1"), n("c")], previous).map((x) => x.id)).toEqual([+ "c",+ "a",+ "b",+ "new2",+ "new1",+ ]);+ });+});++describe("fitContainer", () => {+ it("shifts children into the padding and sizes the box around them", () => {+ const fitted = fitContainer(+ new Map([+ ["a", { x: 30, y: 30, width: 100, height: 50 }],+ ["b", { x: 230, y: 130, width: 100, height: 50 }],+ ]),+ );+ const pad = CONTAINER_PADDING;+ expect(fitted.children.get("a")).toEqual({ x: pad.left, y: pad.top, width: 100, height: 50 });+ expect(fitted.children.get("b")).toEqual({ x: pad.left + 200, y: pad.top + 100, width: 100, height: 50 });+ expect(fitted.width).toBe(300 + pad.left + pad.right);+ expect(fitted.height).toBe(150 + pad.top + pad.bottom);+ });+});++describe("computeLevelLayout", () => {+ it("places the focus level in fixed columns without ELK", async () => {+ const view = buildLevelView(ESHOP_GRAPH, { focus: "ordering.api" });+ const cache = countingCache();+ const positions = await computeLevelLayout(levelLayoutInput(view, ESHOP_GRAPH.edges), { cache });+ expect(positions).toEqual(placeFocusColumns(view.focus!, { size: LEVEL_NODE_SIZES.service }));+ expect(cache.hits + cache.misses).toBe(0);+ });++ it("positions every drawn card, children relative to their open group", async () => {+ const g = groupedEstate(3, 15);+ const view = buildLevelView(g, { open: ["g1"] });+ const positions = await computeLevelLayout(levelLayoutInput(view, g.edges));+ for (const n of view.nodes) expect(positions.has(n.id), n.id).toBe(true);+ const box = positions.get(groupNodeId("g1"))!;+ for (let s = 0; s < 15; s++) {+ const p = positions.get(`g1.s${s}`)!;+ expect(p.x).toBeGreaterThanOrEqual(CONTAINER_PADDING.left);+ expect(p.y).toBeGreaterThanOrEqual(CONTAINER_PADDING.top);+ expect(p.x + p.width).toBeLessThanOrEqual(box.width);+ expect(p.y + p.height).toBeLessThanOrEqual(box.height);+ }+ // Closed groups keep their card size.+ expect(positions.get(groupNodeId("g0"))!.width).toBe(LEVEL_NODE_SIZES.group.width);+ });++ it("serves a repeated view from the cache and lays out only what an opened group changed", async () => {+ const g = groupedEstate(3, 15);+ const cache = countingCache();+ const run = (open: string[]) => computeLevelLayout(levelLayoutInput(buildLevelView(g, { open }), g.edges), { cache });++ const first = await run(["g1"]);+ expect([cache.hits, cache.misses]).toEqual([0, 2]);+ expect(await run(["g1"])).toEqual(first);+ expect([cache.hits, cache.misses]).toEqual([2, 2]);++ // Opening a second group: g1's interior is reused; g2's and the root are new.+ await run(["g1", "g2"]);+ expect([cache.hits, cache.misses]).toEqual([3, 4]);+ });++ it("lays out the between level over the services on the paths", async () => {+ const view = buildLevelView(ESHOP_GRAPH, { between: { a: "webapp", b: "ordering.api" } });+ expect(view.level).toBe("between");+ const positions = await computeLevelLayout(levelLayoutInput(view, ESHOP_GRAPH.edges));+ expect([...positions.keys()].sort()).toEqual(view.nodes.map((n) => n.id).sort());+ });+});++describe("useLevelLayout", () => {+ it("lays out once and holds still when only the family filter moves", async () => {+ const g = groupedEstate(3, 15);+ const { result, rerender } = renderHook(({ families }) => {+ const view = buildLevelView(g, { open: ["g1"], families: families ?? DEFAULT_EDGE_FAMILIES });+ return useLevelLayout({ graph: g, view });+ }, { initialProps: { families: undefined as ReadonlySet<EdgeFamily> | undefined } });+ await waitFor(() => expect(result.current.loading).toBe(false));+ const first = result.current.positions;+ expect(first?.has("g1.s0")).toBe(true);+ rerender({ families: all });+ expect(result.current.loading).toBe(false);+ expect(result.current.positions).toBe(first);+ });+});diff --git a/packages/ui/__tests__/workspace/system-map-logic.test.ts b/packages/ui/__tests__/workspace/system-map-logic.test.tsindex 4c143a669..8341759be 100644--- a/packages/ui/__tests__/workspace/system-map-logic.test.ts+++ b/packages/ui/__tests__/workspace/system-map-logic.test.ts@@ -6,7 +6,6 @@ import {applyView,computeSystemMapPositions,layoutSignature,- SYSTEM_MAP_MAX_LAYOUT_NODES,} from "../../src/workspace/system-map/layout";import {edgeKindStyle,@@ -573,23 +572,10 @@ describe("layout stability under filtering", () => {});describe("computeSystemMapPositions", () => {- it("lays out a normal graph with ELK and reports it is not simplified", async () => {- const result = await computeSystemMapPositions(+ it("lays out a graph with ELK", async () => {+ const positions = await computeSystemMapPositions(graph([node("api", "api"), node("web", "web")], [edge("web", "api")]),);- expect(result.simplified).toBe(false);- expect(result.positions.size).toBe(2);- });-- it("falls back to a grid above the layout bound and says so", async () => {- const many = Array.from({ length: SYSTEM_MAP_MAX_LAYOUT_NODES + 1 }, (_, i) =>- node(`n${i}`, `r${i}`),- );- const result = await computeSystemMapPositions(graph(many, []));- expect(result.simplified).toBe(true);- expect(result.positions.size).toBe(many.length);- // A grid, not a pile: no two nodes share a position.- const seen = new Set([...result.positions.values()].map((p) => `${p.x},${p.y}`));- expect(seen.size).toBe(many.length);+ expect(positions.size).toBe(2);});});diff --git a/packages/ui/__tests__/workspace/system-map.bench.ts b/packages/ui/__tests__/workspace/system-map.bench.tsindex 6b4219e63..8dcdcfa6b 100644--- a/packages/ui/__tests__/workspace/system-map.bench.ts+++ b/packages/ui/__tests__/workspace/system-map.bench.ts@@ -11,8 +11,14 @@ 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 { neighbourGroups, serviceResolver } from "../../src/workspace/system-map/system-map-model";import { buildLevelView } from "../../src/workspace/system-map/levels";+import {+ orderByPrevious,+ planLevelLayout,+ planSignature,+ scopeSignature,+} from "../../src/workspace/system-map/layout-scopes";+import { neighbourGroups, serviceResolver } from "../../src/workspace/system-map/system-map-model";import { allocateSlots } from "../../src/workspace/system-map/draw-budget";import { servicesBetween } from "../../src/workspace/system-map/between";import type { LevelsGraph } from "../../src/workspace/system-map/level-types";@@ -22,6 +28,8 @@ 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). */+const ELK_MAX_SERVICES = 300;for (const services of SIZES) {const graph = makeSyntheticSystemGraph({@@ -37,6 +45,14 @@ for (const services of SIZES) {const caller = graph.edges.find((e) => e.kind === "http")?.source ?? graph.nodes[0]!.id;const callee = graph.edges.find((e) => e.kind === "http")?.target ?? graph.nodes[1]!.id;const containers = groupIds.map((_, i) => ({ size: 5 + ((i * 7) % 40) }));+ // The drawn view the layout plans from: the estate with its first group open when grouped.+ const firstGroup = graph.nodes.find((n) => n.group)?.group;+ const view = buildLevelView(levels, firstGroup ? { open: [firstGroup] } : {});+ const plan = planLevelLayout(view.nodes, graph.edges);+ // Previous positions in a shuffled-ish reading order, as after a relayout.+ const previous = new Map(+ plan.root.nodes.map((n, i) => [n.id, { x: (i * 7919) % 2000, y: (i * 104729) % 1500 }] as const),+ );describe(`system map, ${services} services / ${graph.edges.length} edges`, () => {bench("applyView (runtime kinds)", () => {@@ -53,6 +69,21 @@ for (const services of SIZES) {neighbourGroups(graph, hub, "in");neighbourGroups(graph, hub, "out");});+ bench("planLevelLayout (drawn view, edges lifted to cards)", () => {+ planLevelLayout(view.nodes, graph.edges);+ });+ bench("planSignature + scopeSignature (layout cache keys)", () => {+ planSignature(plan);+ for (const s of plan.interiors) scopeSignature(s);+ });+ 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 });});@@ -68,8 +99,5 @@ for (const services of SIZES) {bench("servicesBetween (runtime pair)", () => {servicesBetween(levels, caller, callee);});- bench("computeSystemMapPositions (ELK, grid past 500)", async () => {- await computeSystemMapPositions(graph);- }, SLOW);});}diff --git a/packages/ui/src/c4/layout/elk-c4-layout.ts b/packages/ui/src/c4/layout/elk-c4-layout.tsindex 7f5aa2331..cbef58bb9 100644--- a/packages/ui/src/c4/layout/elk-c4-layout.ts+++ b/packages/ui/src/c4/layout/elk-c4-layout.ts@@ -9,8 +9,8 @@* is reusable for SVG/Mermaid export later.*/-import ELK from "elkjs/lib/elk.bundled.js";import type { ElkNode, ElkExtendedEdge } from "elkjs";+import { runElkLayout } from "./elk-runner";export interface C4LayoutNode {id: string;@@ -39,8 +39,6 @@ export const C4_NODE_SIZES = {component: { width: 180, height: 90 },} as const;-const elk = new ELK();-const LAYOUT_OPTIONS: Record<string, string> = {"elk.algorithm": "layered","elk.direction": "DOWN",@@ -52,9 +50,18 @@ const LAYOUT_OPTIONS: Record<string, string> = {"elk.padding": "[top=30,left=30,bottom=30,right=30]",};+export interface C4LayoutOptions {+ /** Run ELK in a Web Worker when one can start (see `elk-runner.ts`). */+ worker?: boolean;+ /** ELK options merged over the C4 defaults. */+ layoutOptions?: Record<string, string>;+}++/** Nodes go to ELK in input order, which it honours when `considerModelOrder` is set. */export async function computeC4Layout(- nodes: C4LayoutNode[],- edges: C4LayoutEdge[],+ nodes: readonly C4LayoutNode[],+ edges: readonly C4LayoutEdge[],+ options: C4LayoutOptions = {},): Promise<Map<string, C4LayoutPosition>> {if (nodes.length === 0) return new Map();@@ -65,7 +72,7 @@ export async function computeC4Layout(const elkGraph: ElkNode = {id: "root",- layoutOptions: LAYOUT_OPTIONS,+ layoutOptions: { ...LAYOUT_OPTIONS, ...options.layoutOptions },children: nodes.map<ElkNode>((n) => ({id: n.id,width: n.width,@@ -78,7 +85,7 @@ export async function computeC4Layout(})),};- const laid = await elk.layout(elkGraph);+ const laid = await runElkLayout(elkGraph, { worker: options.worker ?? false });const positions = new Map<string, C4LayoutPosition>();for (const child of laid.children ?? []) {positions.set(child.id, {diff --git a/packages/ui/src/c4/layout/elk-runner.ts b/packages/ui/src/c4/layout/elk-runner.tsnew file mode 100644index 000000000..4574d131c--- /dev/null+++ b/packages/ui/src/c4/layout/elk-runner.ts@@ -0,0 +1,95 @@+/**+ * Runs an ELK layout off the main thread when it can.+ *+ * `worker: true` sends the graph to one shared Web Worker running+ * `elkjs/lib/elk-worker.min.js`, so a layered layout of a hundred cards no+ * longer blocks input. When a worker cannot start (no `Worker`, as in jsdom or+ * on the server; a blocked or failed script load) the same graph is laid out by+ * the bundled main-thread ELK, which is loaded on first use only. A worker that+ * fails once is not retried for the rest of the session.+ *+ * The worker URL is written as `new Worker(new URL(..., import.meta.url))`,+ * the form webpack 5, Turbopack and Vite all bundle as a worker entry.+ */++import ElkApi, { type ElkNode } from "elkjs/lib/elk-api.js";++interface ElkEngine {+ layout(graph: ElkNode): Promise<ElkNode>;+}++/** Raised when the worker script fails to load or crashes, as opposed to a layout error. */+class WorkerUnavailable extends Error {}++interface WorkerEngine {+ elk: ElkEngine;+ /** Rejects with `WorkerUnavailable` once the worker reports an error event. */+ failed: Promise<never>;+ terminate(): void;+}++/** `undefined`: not tried yet. `null`: this environment cannot run the worker. */+let workerEngine: WorkerEngine | null | undefined;+let mainThreadEngine: Promise<ElkEngine> | null = null;++function mainThreadElk(): Promise<ElkEngine> {+ mainThreadEngine ??= import("elkjs/lib/elk.bundled.js").then((m) => new m.default());+ return mainThreadEngine;+}++function startWorker(): WorkerEngine | null {+ if (workerEngine !== undefined) return workerEngine;+ workerEngine = null;+ if (typeof Worker === "undefined") return null;+ try {+ let fail: (reason: unknown) => void = () => {};+ const failed = new Promise<never>((_, reject) => {+ fail = reject;+ });+ // Observed through `Promise.race` only; never an unhandled rejection.+ failed.catch(() => {});+ let raw: Worker | null = null;+ const elk = new ElkApi({+ workerFactory: () => {+ raw = new Worker(new URL("elkjs/lib/elk-worker.min.js", import.meta.url));+ raw.addEventListener("error", () => fail(new WorkerUnavailable("ELK worker failed")));+ return raw;+ },+ });+ workerEngine = { elk, failed, terminate: () => raw?.terminate() };+ } catch {+ workerEngine = null;+ }+ return workerEngine;+}++/**+ * Lay out an ELK graph, in the worker when `worker` is set and one can run,+ * else on the main thread. A layout error from ELK itself is rethrown either way.+ */+export async function runElkLayout(graph: ElkNode, options: { worker?: boolean } = {}): Promise<ElkNode> {+ const engine = options.worker ? startWorker() : null;+ if (engine) {+ const laid = await layoutInWorker(engine, graph);+ if (laid) return laid;+ }+ return (await mainThreadElk()).layout(graph);+}++/** The worker's layout, or null when the worker failed and has been dropped. */+async function layoutInWorker(engine: WorkerEngine, graph: ElkNode): Promise<ElkNode | null> {+ try {+ return await Promise.race([engine.elk.layout(graph), engine.failed]);+ } catch (err) {+ if (!(err instanceof WorkerUnavailable)) throw err;+ engine.terminate();+ if (workerEngine === engine) workerEngine = null;+ return null;+ }+}++/** Test seam: forget the worker so the next layout tries to start one again. */+export function resetElkWorkerForTests(): void {+ workerEngine?.terminate();+ workerEngine = undefined;+}diff --git a/packages/ui/src/workspace/system-map/index.ts b/packages/ui/src/workspace/system-map/index.tsindex bcf63d740..e9ca17f70 100644--- a/packages/ui/src/workspace/system-map/index.ts+++ b/packages/ui/src/workspace/system-map/index.ts@@ -74,6 +74,8 @@ export {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 type { SystemMapPhase } from "./use-system-map-phases";export {applyView,@@ -81,9 +83,7 @@ export {computeSystemMapPositions,layoutSignature,SYSTEM_MAP_NODE_SIZE,- SYSTEM_MAP_MAX_LAYOUT_NODES,type SystemMapView,- type SystemMapPositions,} from "./layout";export {SystemMapRailPanel,diff --git a/packages/ui/src/workspace/system-map/layout-scopes.ts b/packages/ui/src/workspace/system-map/layout-scopes.tsnew file mode 100644index 000000000..5b9bff627--- /dev/null+++ b/packages/ui/src/workspace/system-map/layout-scopes.ts@@ -0,0 +1,206 @@+/**+ * What the levels layout hands to ELK, as plain data. A drawn view splits into+ * scopes: one per open container (an opened group or the open tray), holding+ * its own cards, and the root, holding everything else with each open+ * container as one box. Each scope is laid out on its own and cached by its+ * signature, so opening a group lays out that group's interior once and+ * re-runs only the root with the group's box at its new size.+ *+ * Placement keys on every edge family but History, whatever the family+ * filter draws, so a filter toggle never moves a card (the drawn node set is+ * filter-independent by construction in `estate-view.ts`). Pure, no React.+ */++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 type { DrawnNode, LevelsEdge } from "./level-types";++interface Size {+ width: number;+ height: number;+}++/** Card footprints per drawn node type. Open containers are sized from their interior. */+export interface LevelNodeSizes {+ service: Size;+ group: Size;+ tray: Size;+ more: Size;+}++export const LEVEL_NODE_SIZES: LevelNodeSizes = {+ service: SYSTEM_MAP_NODE_SIZE,+ group: { width: 240, height: 104 },+ tray: { width: 240, height: 104 },+ more: SYSTEM_MAP_NODE_SIZE,+};++/** Room an open container keeps around its cards; the top holds its title row. */+export const CONTAINER_PADDING = { top: 48, right: 24, bottom: 24, left: 24 } as const;++export const ROOT_SCOPE = "root";++export interface LayoutScope {+ /** `ROOT_SCOPE`, or the drawn id of the open container whose interior this is. */+ id: string;+ /** In drawn order. In the root, an open container has a zero size until its interior is laid out. */+ nodes: C4LayoutNode[];+ /** One per ordered pair of drawn ids, in id order. */+ edges: C4LayoutEdge[];+}++export interface LevelLayoutPlan {+ interiors: LayoutScope[];+ root: LayoutScope;+}++function isOpenContainer(n: DrawnNode): boolean {+ return (n.type === "group" || n.type === "tray") && n.open;+}++function nodeSize(n: DrawnNode, sizes: LevelNodeSizes): Size {+ if (isOpenContainer(n)) return { width: 0, height: 0 };+ return sizes[n.type];+}++/** 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";+}++interface Placement {+ /** Drawn id -> the open container it sits in. */+ parentOf: Map<string, string>;+ /** Service id -> the drawn id it is shown at. */+ drawnAt: Map<string, string>;+}++/** Where each service is drawn: its own card, else the closed group, tray or "+N more" holding it. */+function placement(nodes: readonly DrawnNode[]): Placement {+ const parentOf = new Map<string, string>();+ const drawnAt = new Map<string, string>();+ for (const n of nodes) {+ if ((n.type === "service" || n.type === "more") && n.parentId) parentOf.set(n.id, n.parentId);+ if (n.type === "service") drawnAt.set(n.serviceId, n.id);+ }+ for (const n of nodes) {+ if (n.type === "service" || isOpenContainer(n)) continue;+ for (const id of n.serviceIds) if (!drawnAt.has(id)) drawnAt.set(id, n.id);+ }+ return { parentOf, drawnAt };+}++/**+ * The scope and drawn ends an edge shapes: inside one container when both+ * ends sit in it, else the root between their top-level boxes. Null when+ * the edge joins a box to itself or an end is not drawn.+ */+function liftEdge(e: LevelsEdge, { parentOf, drawnAt }: Placement): [string, string, string] | null {+ const s = drawnAt.get(e.source);+ const t = drawnAt.get(e.target);+ if (s === undefined || t === undefined || s === t) return null;+ const ps = parentOf.get(s);+ const pt = parentOf.get(t);+ if (ps === pt) return [ps ?? ROOT_SCOPE, s, t];+ const [rs, rt] = [ps ?? s, pt ?? t];+ return rs === rt ? null : [ROOT_SCOPE, rs, rt];+}++/**+ * Scopes for an estate, group or between view (focus uses fixed columns).+ * `edges` are the graph's system edges, each lifted to the drawn ids that+ * show its ends.+ */+export function planLevelLayout(+ nodes: readonly DrawnNode[],+ edges: readonly LevelsEdge[],+ sizes: LevelNodeSizes = LEVEL_NODE_SIZES,+): LevelLayoutPlan {+ const placed = placement(nodes);+ const scopes = new Map<string, { nodes: C4LayoutNode[]; edges: Map<string, C4LayoutEdge> }>();+ const scope = (id: string) => {+ let s = scopes.get(id);+ if (!s) scopes.set(id, (s = { nodes: [], edges: new Map() }));+ return s;+ };+ scope(ROOT_SCOPE);+ for (const n of nodes) {+ scope(placed.parentOf.get(n.id) ?? ROOT_SCOPE).nodes.push({ id: n.id, ...nodeSize(n, sizes) });+ }+ for (const e of edges) {+ const lifted = shapesLayout(e) ? liftEdge(e, placed) : null;+ if (!lifted) continue;+ const [scopeId, source, target] = lifted;+ const id = `${source}>${target}`;+ scope(scopeId).edges.set(id, { id, source, target });+ }++ const toScope = (id: string): LayoutScope => {+ const s = scopes.get(id)!;+ return { id, nodes: s.nodes, edges: [...s.edges.values()].sort((a, b) => compareIds(a.id, b.id)) };+ };+ const interiors = [...scopes.keys()].filter((id) => id !== ROOT_SCOPE && scopes.get(id)!.nodes.length > 0);+ return { interiors: interiors.map(toScope), root: toScope(ROOT_SCOPE) };+}++/** Identity of a scope's layout: its node footprints and edges, independent of order. */+export function scopeSignature(scope: LayoutScope): string {+ const nodes = scope.nodes.map((n) => `${n.id}:${n.width}x${n.height}`).sort();+ const edges = scope.edges.map((e) => e.id).sort();+ return `${nodes.join("|")}#${edges.join("|")}`;+}++/** One key for a whole plan; equal keys lay out to equal positions. */+export function planSignature(plan: LevelLayoutPlan): string {+ return [plan.root, ...plan.interiors].map((s) => `${s.id}=${scopeSignature(s)}`).join("\n");+}++/**+ * Nodes that were drawn before go first, in their previous reading order (row,+ * then column), and new ones follow in drawn order. Fed to ELK with+ * `considerModelOrder`, this keeps neighbours in their order when a group opens.+ */+export function orderByPrevious(+ nodes: readonly C4LayoutNode[],+ previous: ReadonlyMap<string, { x: number; y: number }> | undefined,+): C4LayoutNode[] {+ if (!previous || previous.size === 0) return [...nodes];+ const seen = nodes.filter((n) => previous.has(n.id));+ const fresh = nodes.filter((n) => !previous.has(n.id));+ seen.sort((a, b) => {+ const pa = previous.get(a.id)!;+ const pb = previous.get(b.id)!;+ return pa.y - pb.y || pa.x - pb.x || compareIds(a.id, b.id);+ });+ return [...seen, ...fresh];+}++export interface FittedContainer {+ /** Child positions relative to the container's top-left, as React Flow expects for `parentId`. */+ children: Map<string, C4LayoutPosition>;+ width: number;+ height: number;+}++/** Shift an interior layout into its container's padding and size the container to fit. */+export function fitContainer(positions: ReadonlyMap<string, C4LayoutPosition>): FittedContainer {+ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;+ for (const p of positions.values()) {+ minX = Math.min(minX, p.x);+ minY = Math.min(minY, p.y);+ maxX = Math.max(maxX, p.x + p.width);+ maxY = Math.max(maxY, p.y + p.height);+ }+ const pad = CONTAINER_PADDING;+ const children = new Map<string, C4LayoutPosition>();+ if (positions.size === 0) return { children, width: pad.left + pad.right, height: pad.top + pad.bottom };+ for (const [id, p] of positions) {+ children.set(id, { ...p, x: p.x - minX + pad.left, y: p.y - minY + pad.top });+ }+ return { children, width: maxX - minX + pad.left + pad.right, height: maxY - minY + pad.top + pad.bottom };+}diff --git a/packages/ui/src/workspace/system-map/layout.ts b/packages/ui/src/workspace/system-map/layout.tsindex 335be2c92..53f9e0a6c 100644--- a/packages/ui/src/workspace/system-map/layout.ts+++ b/packages/ui/src/workspace/system-map/layout.ts@@ -40,52 +40,17 @@ export function applyCollapse(graph: SystemGraph, collapsed: boolean): SystemGrareturn collapsed ? collapseToRepos(graph) : graph;}-/**- * Above this many nodes ELK's layered layout stops being worth its cost: it runs- * on the main thread, and measured on the real workspace corpus it takes ~1.8s at- * 500 nodes and ~3.4s at 1000, which is a frozen tab rather than a slow one. Past- * the bound we fall back to a deterministic grid, matching the Sigma view's- * `ELK_MAX_NODES` escape hatch. The map says when it has done so (`simplified`),- * because a silently downgraded layout is a lie about the shape of the system.- */-export const SYSTEM_MAP_MAX_LAYOUT_NODES = 500;--export interface SystemMapPositions {- positions: Map<string, C4LayoutPosition>;- /** True when the node count forced the grid fallback instead of ELK. */- simplified: boolean;-}--/** Deterministic grid, used only past `SYSTEM_MAP_MAX_LAYOUT_NODES`. */-function gridPositions(graph: SystemGraph): Map<string, C4LayoutPosition> {- const columns = Math.ceil(Math.sqrt(graph.nodes.length));- const dx = SYSTEM_MAP_NODE_SIZE.width + 55;- const dy = SYSTEM_MAP_NODE_SIZE.height + 90;- const positions = new Map<string, C4LayoutPosition>();- graph.nodes.forEach((n, i) => {- positions.set(n.id, {- x: (i % columns) * dx,- y: Math.floor(i / columns) * dy,- width: SYSTEM_MAP_NODE_SIZE.width,- height: SYSTEM_MAP_NODE_SIZE.height,- });- });- return positions;-}-/*** 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.+ * 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 async function computeSystemMapPositions(graph: SystemGraph): Promise<SystemMapPositions> {- if (graph.nodes.length > SYSTEM_MAP_MAX_LAYOUT_NODES) {- return { positions: gridPositions(graph), simplified: true };- }- const positions = await computeC4Layout(+export function computeSystemMapPositions(graph: SystemGraph): Promise<Map<string, C4LayoutPosition>> {+ return computeC4Layout(graph.nodes.map((n) => ({id: n.id,width: SYSTEM_MAP_NODE_SIZE.width,@@ -96,8 +61,8 @@ export async function computeSystemMapPositions(graph: SystemGraph): Promise<Sysgraph.edges.filter((e) => e.structural).map((e) => ({ id: e.id, source: e.source, target: e.target })),+ { worker: true },);- return { positions, simplified: false };}/**diff --git a/packages/ui/src/workspace/system-map/level-layout.ts b/packages/ui/src/workspace/system-map/level-layout.tsnew file mode 100644index 000000000..988bf1a40--- /dev/null+++ b/packages/ui/src/workspace/system-map/level-layout.ts@@ -0,0 +1,132 @@+/**+ * Positions for a drawn levels view. Focus is a fixed column grid (no ELK).+ * Every other level is laid out per scope (`layout-scopes.ts`): each open+ * container's interior first, then the root with those containers at their+ * fitted size. ELK runs in a worker when one can start, with+ * `considerModelOrder` and nodes in their previous order so a relayout keeps+ * neighbours in place. Scope layouts are cached by signature.+ *+ * Output follows React Flow: a card inside an open container is positioned+ * relative to it, and an open container carries its fitted width and height.+ */++import { computeC4Layout, type C4LayoutPosition } from "../../c4/layout/elk-c4-layout";+import { placeFocusColumns } from "./focus-columns";+import {+ LEVEL_NODE_SIZES,+ fitContainer,+ orderByPrevious,+ planLevelLayout,+ planSignature,+ scopeSignature,+ type FittedContainer,+ type LayoutScope,+ type LevelLayoutPlan,+ type LevelNodeSizes,+} from "./layout-scopes";+import type { LevelView } from "./levels";+import type { LevelsEdge } from "./level-types";++export type LevelPositions = Map<string, C4LayoutPosition>;++/** ELK options added to the C4 defaults for the map: keep the input order where crossings allow. */+export const LEVEL_LAYOUT_OPTIONS: Record<string, string> = {+ "elk.layered.considerModelOrder.strategy": "NODES_AND_EDGES",+};++/** Scope layouts by signature, least recently used dropped first. */+export interface LayoutCache {+ get(key: string): LevelPositions | undefined;+ set(key: string, value: LevelPositions): void;+ clear(): void;+}++export function createLayoutCache(limit = 64): LayoutCache {+ const entries = new Map<string, LevelPositions>();+ return {+ get(key) {+ const hit = entries.get(key);+ if (hit) {+ entries.delete(key);+ entries.set(key, hit);+ }+ return hit;+ },+ set(key, value) {+ entries.delete(key);+ entries.set(key, value);+ if (entries.size > limit) entries.delete(entries.keys().next().value!);+ },+ clear: () => entries.clear(),+ };+}++export type LevelLayoutInput =+ | { kind: "columns"; view: LevelView }+ | { kind: "scopes"; plan: LevelLayoutPlan };++/** What a view needs laid out; pure, so a hook can key on it before any ELK runs. */+export function levelLayoutInput(+ view: LevelView,+ edges: readonly LevelsEdge[],+ sizes: LevelNodeSizes = LEVEL_NODE_SIZES,+): LevelLayoutInput {+ if (view.level === "focus" && view.focus) return { kind: "columns", view };+ return { kind: "scopes", plan: planLevelLayout(view.nodes, edges, sizes) };+}++/** One key per layout: equal keys lay out to equal positions, so a hook can skip ELK on a match. */+export function levelLayoutKey(input: LevelLayoutInput, sizes: LevelNodeSizes = LEVEL_NODE_SIZES): string {+ if (input.kind === "scopes") return planSignature(input.plan);+ const { width, height } = sizes.service;+ return [`columns:${width}x${height}`, ...input.view.nodes.map((n) => n.id)].join("|");+}++export interface LevelLayoutOptions {+ cache?: LayoutCache;+ /** Positions last shown, for input order. */+ previous?: ReadonlyMap<string, { x: number; y: number }> | undefined;+ sizes?: LevelNodeSizes;+ /** Run ELK in a worker when one can start. On by default. */+ worker?: boolean;+}++export async function computeLevelLayout(+ input: LevelLayoutInput,+ options: LevelLayoutOptions = {},+): Promise<LevelPositions> {+ const sizes = options.sizes ?? LEVEL_NODE_SIZES;+ if (input.kind === "columns") return placeFocusColumns(input.view.focus!, { size: sizes.service });++ // The key leaves out input order on purpose: a scope seen before comes back+ // exactly as it was shown, which is the stability the order exists for.+ const run = async (scope: LayoutScope): Promise<LevelPositions> => {+ const key = scopeSignature(scope);+ const hit = options.cache?.get(key);+ if (hit) return hit;+ const positions = await computeC4Layout(orderByPrevious(scope.nodes, options.previous), scope.edges, {+ worker: options.worker ?? true,+ layoutOptions: LEVEL_LAYOUT_OPTIONS,+ });+ options.cache?.set(key, positions);+ return positions;+ };++ const { plan } = input;+ const fitted = new Map<string, FittedContainer>(+ await Promise.all(plan.interiors.map(async (s) => [s.id, fitContainer(await run(s))] as const)),+ );+ // An open container with nothing laid out inside keeps its closed card size.+ const empty = sizes.group;+ const root: LayoutScope = {+ ...plan.root,+ nodes: plan.root.nodes.map((n) => {+ if (n.width > 0) return n;+ const box = fitted.get(n.id) ?? empty;+ return { ...n, width: box.width, height: box.height };+ }),+ };+ const out: LevelPositions = new Map(await run(root));+ for (const box of fitted.values()) for (const [id, p] of box.children) out.set(id, p);+ return out;+}diff --git a/packages/ui/src/workspace/system-map/system-map.tsx b/packages/ui/src/workspace/system-map/system-map.tsxindex 339d8ca57..20ddef078 100644--- a/packages/ui/src/workspace/system-map/system-map.tsx+++ b/packages/ui/src/workspace/system-map/system-map.tsx@@ -39,7 +39,7 @@ 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_MAX_LAYOUT_NODES, SYSTEM_MAP_NODE_SIZE, applyCollapse, type SystemMapView } from "./layout";+import { SYSTEM_MAP_NODE_SIZE, applyCollapse, type SystemMapView } from "./layout";import type { RepoHealth, SystemMapOverlay, SystemMapSelection } from "./types";import { toFriendlyMessage } from "../../lib/errors";@@ -135,7 +135,7 @@ function SystemMapInner({);const view = useMemo<SystemMapView>(() => ({ visibleKinds, collapsed }), [visibleKinds, collapsed]);- const { nodes, edges, loading: layoutLoading, viewGraph, simplified } = useSystemMapLayout({+ const { nodes, edges, loading: layoutLoading, viewGraph } = useSystemMapLayout({graph,view,...(healthByRepo ? { healthByRepo } : {}),@@ -329,7 +329,7 @@ function SystemMapInner({</ReactFlow></div>- {graph && viewGraph && <ScopeCaption graph={graph} viewGraph={viewGraph} collapsed={collapsed} lensed={Boolean(overlay)} hidden={hiddenKinds} kindCounts={kindCounts} simplified={simplified} />}+ {graph && viewGraph && <ScopeCaption graph={graph} viewGraph={viewGraph} collapsed={collapsed} lensed={Boolean(overlay)} hidden={hiddenKinds} kindCounts={kindCounts} />}{graph && viewGraph && (<SystemMapDrawer@@ -451,7 +451,6 @@ function ScopeCaption({lensed,hidden,kindCounts,- simplified,}: {graph: SystemGraph;viewGraph: SystemGraph;@@ -459,7 +458,6 @@ function ScopeCaption({lensed: boolean;hidden: ReadonlySet<SystemEdgeKind>;kindCounts: ReadonlyMap<SystemEdgeKind, number>;- simplified: boolean;}) {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;@@ -479,16 +477,7 @@ function ScopeCaption({"Placement follows structural dependencies; co-change lines do not move services.",];- return (- <div className="flex flex-col gap-1">- <p className="text-xs text-[var(--color-text-tertiary)]">{parts.filter(Boolean).join(" ")}</p>- {simplified && (- <p className="text-xs text-[var(--color-warning)]">- {`Layout simplified: above ${SYSTEM_MAP_MAX_LAYOUT_NODES} services the map falls back to a grid, so placement no longer reflects dependency direction.`}- </p>- )}- </div>- );+ return <p className="text-xs text-[var(--color-text-tertiary)]">{parts.filter(Boolean).join(" ")}</p>;}/**diff --git a/packages/ui/src/workspace/system-map/use-level-layout.ts b/packages/ui/src/workspace/system-map/use-level-layout.tsnew file mode 100644index 000000000..6427c91dd--- /dev/null+++ b/packages/ui/src/workspace/system-map/use-level-layout.ts@@ -0,0 +1,88 @@+"use client";++/**+ * Positions for a drawn levels view (`buildLevelView`), laid out off the main+ * thread and cached per scope for the life of one graph. Keyed on what shapes+ * the layout, so a family toggle or a lens change that leaves the drawn cards+ * alone runs nothing. While a new layout is pending the previous positions+ * stay, so cards already on screen do not jump; ids new to the view have no+ * entry until it lands.+ */++import { useEffect, useMemo, useRef, useState } from "react";+import type { C4LayoutPosition } from "../../c4/layout/elk-c4-layout";+import {+ computeLevelLayout,+ createLayoutCache,+ levelLayoutInput,+ levelLayoutKey,+ type LevelPositions,+} from "./level-layout";+import { LEVEL_NODE_SIZES, type LevelNodeSizes } from "./layout-scopes";+import type { LevelView } from "./levels";+import type { LevelsGraph } from "./level-types";++export interface UseLevelLayoutArgs {+ /** The graph the view was built from; its edges shape placement. */+ graph: LevelsGraph | null;+ view: LevelView | null;+ sizes?: LevelNodeSizes;+}++export interface LevelLayout {+ positions: ReadonlyMap<string, C4LayoutPosition> | null;+ /** True from the render a new layout is asked for until it lands or fails. */+ loading: boolean;+ /** The last layout failed; `positions` are those of the view before it. */+ failed: boolean;+}++export function useLevelLayout({ graph, view, sizes = LEVEL_NODE_SIZES }: UseLevelLayoutArgs): LevelLayout {+ const input = useMemo(+ () => (graph && view ? levelLayoutInput(view, graph.edges, sizes) : null),+ [graph, view, sizes],+ );+ const key = useMemo(() => (input ? levelLayoutKey(input, sizes) : null), [input, sizes]);++ const cache = useRef(createLayoutCache());+ const previous = useRef<LevelPositions | undefined>(undefined);+ const cachedGraph = useRef(graph);+ if (cachedGraph.current !== graph) {+ cachedGraph.current = graph;+ cache.current = createLayoutCache();+ previous.current = undefined;+ }+ // Read by the effect, which runs on `key` alone: equal keys lay out alike.+ const latest = useRef({ input, sizes });+ latest.current = { input, sizes };++ // The key the shown positions belong to; loading is derived, so it is true+ // on the very render the key changes rather than one commit later.+ const [settled, setSettled] = useState<{ key: string | null; positions: LevelPositions | null; failed: boolean }>(+ { key: null, positions: null, failed: false },+ );++ useEffect(() => {+ const { input: current, sizes: currentSizes } = latest.current;+ if (!current || key === null) {+ setSettled({ key, positions: null, failed: false });+ return;+ }+ let cancelled = false;+ computeLevelLayout(current, { cache: cache.current, previous: previous.current, sizes: currentSizes }).then(+ (result) => {+ if (cancelled) return;+ previous.current = result;+ setSettled({ key, positions: result, failed: false });+ },+ () => {+ if (!cancelled) setSettled((s) => ({ key, positions: s.positions, failed: true }));+ },+ );+ return () => {+ cancelled = true;+ };+ }, [key]);++ return { positions: settled.positions, loading: settled.key !== key, failed: settled.failed };+}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.tsindex 7f9c39eb3..05e7d0281 100644--- a/packages/ui/src/workspace/system-map/use-system-map-layout.ts+++ b/packages/ui/src/workspace/system-map/use-system-map-layout.ts@@ -47,8 +47,6 @@ export interface SystemMapLayout {* ids it can be handed only exist here.*/viewGraph: SystemGraph | null;- /** True when the node count forced the grid fallback instead of ELK. */- simplified: boolean;}export function useSystemMapLayout({@@ -62,7 +60,7 @@ export function useSystemMapLayout({// 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 ~23ms main-thread cost is not paid.+ // 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],@@ -72,19 +70,14 @@ export function useSystemMapLayout({[layoutGraph],);- const [layout, setLayout] = useState<{- positions: Map<string, { x: number; y: number }>;- simplified: boolean;- } | null>(null);+ 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, { positions: Map<string, { x: number; y: number }>; simplified: boolean }>(),- );+ const cache = useRef(new Map<string, Map<string, { x: number; y: number }>>());const cachedGraph = useRef(graph);if (cachedGraph.current !== graph) {cachedGraph.current = graph;@@ -94,31 +87,34 @@ export function useSystemMapLayout({useEffect(() => {let cancelled = false;if (!layoutGraph || !signature || layoutGraph.nodes.length === 0) {- setLayout({ positions: new Map(), simplified: false });+ setPositions(new Map());setLoading(false);return;}const cached = cache.current.get(signature);if (cached) {- setLayout(cached);+ setPositions(cached);setLoading(false);return;}setLoading(true);- computeSystemMapPositions(layoutGraph).then((result) => {- cache.current.set(signature, result);- if (!cancelled) {- setLayout(result);- setLoading(false);- }- });+ 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 positions = layout?.positions ?? null;-const nodes = useMemo<Node<SystemMapNodeData>[]>(() => {if (!viewGraph || !positions) return [];return viewGraph.nodes.map((node) => {@@ -152,5 +148,5 @@ export function useSystemMapLayout({}));}, [viewGraph, overlay]);- return { nodes, edges, loading, viewGraph, simplified: layout?.simplified ?? false };+ return { nodes, edges, loading, viewGraph };}