Open History to see the last commit
1import { EnvironmentId, type PeerLinkSummary } from "@t3tools/contracts";
2import * as DateTime from "effect/DateTime";
3import { describe, expect, it } from "vite-plus/test";
4
5import {
6 anchorFleetView,
7 buildFleetGraph,
8 FLEET_FIT_LEGIBLE_SCALE,
9 fitFleetLayout,
10 fleetCanvasHeight,
11 fleetStackPartial,
12 FLEET_CLIENT_NODE_ID,
13 fleetEnvironmentNodeId,
14 FLEET_FOLD_ENVIRONMENTS_OVER,
15 FLEET_LANE_PITCH,
16 FLEET_ROUTE_PITCH,
17 FLEET_STACK_SHOWN_MAX,
18 fleetFocusRects,
19 fleetDrawnLinkId,
20 fleetLinkAction,
21 fleetLinkBackOffered,
22 fleetLinkOffer,
23 fleetMoreNodeId,
24 fleetNeighborhood,
25 fleetNodesInBox,
26 fleetSearch,
27 fleetShapeKey,
28 fleetStacks,
29 fleetSummary,
30 fleetTwoWayLinks,
31 isLinkEdge,
32 isRouteEdge,
33 layoutFleetGraph,
34 nextFleetNode,
35 zoomFleetView,
36 type FleetConnectMachineInput,
37 type FleetEnvironmentInput,
38 type FleetLayout,
39 type FleetRect,
40} from "./environmentsMap.logic";
41
42const now = DateTime.makeUnsafe("2026-11-19T12:00:00.000Z");
43const id = (value: string) => EnvironmentId.make(value);
44const node = (value: string) => fleetEnvironmentNodeId(id(value));
45
46const link = (target: string, overrides: Partial<PeerLinkSummary> = {}): PeerLinkSummary => ({
47 environmentId: id(target),
48 label: target,
49 urls: [`https://${target}.example.ts.net`],
50 access: "approval-required",
51 linkedAt: DateTime.makeUnsafe("2026-11-01T00:00:00.000Z"),
52 expiresAt: DateTime.makeUnsafe("2027-01-01T00:00:00.000Z"),
53 lastReachedAt: null,
54 lastError: null,
55 status: "reachable",
56 ...overrides,
57});
58
59const environment = (
60 name: string,
61 links: ReadonlyArray<PeerLinkSummary> | FleetEnvironmentInput["outgoing"]["state"] = [],
62 overrides: Partial<FleetEnvironmentInput> = {},
63): FleetEnvironmentInput => ({
64 environmentId: id(name),
65 label: name,
66 machine: "server",
67 phase: "connected",
68 enabled: true,
69 routes: [{ id: "tailnet", kind: "tailnet" }],
70 activeRouteId: "tailnet",
71 refusedRouteIds: [],
72 offersLinks: true,
73 canWriteAccess: true,
74 hasLinkAddress: true,
75 outgoing:
76 typeof links !== "string"
77 ? { state: "loaded", links }
78 : links === "error"
79 ? { state: "error", message: "boom" }
80 : links === "loaded"
81 ? { state: "loaded", links: [] }
82 : { state: links },
83 ...overrides,
84});
85
86const connectMachine = (name: string): FleetConnectMachineInput => ({
87 environmentId: id(name),
88 label: name,
89 machine: "server",
90 availability: "online",
91});
92
93const build = (
94 environments: ReadonlyArray<FleetEnvironmentInput>,
95 connectMachines: ReadonlyArray<FleetConnectMachineInput> = [],
96) => buildFleetGraph({ clientLabel: "This browser", environments, connectMachines, now });
97
98const vms = (count: number, prefix = "vm", overrides: Partial<PeerLinkSummary> = {}) =>
99 Array.from({ length: count }, (_, index) => link(`${prefix}-${index + 1}`, overrides));
100
101const routeStates = (graph: ReturnType<typeof build>, name: string) =>
102 Object.fromEntries(
103 graph.edges
104 .filter(isRouteEdge)
105 .filter((edge) => edge.to === node(name))
106 .map((edge) => [edge.routeId, edge.state]),
107 );
108
109/** Six environments in every state, 45 link targets, 40 of them under one host. */
110const largeSetup = () =>
111 build(
112 [
113 environment(
114 "nucbox",
115 [...vms(40, "fs", { access: "full-access" }), link("ci"), link("cups", { access: "auto" })],
116 {
117 routes: [
118 { id: "tailnet", kind: "tailnet" },
119 { id: "lan", kind: "lan" },
120 { id: "relay", kind: "relay" },
121 ],
122 },
123 ),
124 environment("cups", [link("nucbox"), link("staging", { access: "read-only" }), link("ci")]),
125 environment("mbp", "unknown", { phase: "offline" }),
126 environment("win", "unknown", { phase: "error" }),
127 environment("vps", [
128 link("db-1"),
129 link("db-2"),
130 link("db-3"),
131 link("ci", { access: "read-only" }),
132 link("staging", { access: "auto" }),
133 link("cups", { access: "full-access" }),
134 ]),
135 environment("old", "unknown", { enabled: false, phase: "available" }),
136 ],
137 [connectMachine("gpu")],
138 );
139
140/** The brief's setup: two hosts share three machines, one has three more and links to the other. */
141const sharedSetup = () =>
142 build([
143 environment("nucbox", [
144 link("fs-1", { access: "full-access" }),
145 link("fs-2", { access: "auto" }),
146 link("fs-3", { access: "read-only" }),
147 ]),
148 environment("mbp", "unknown", { phase: "reconnecting" }),
149 environment("cups", [
150 link("fs-1", { access: "full-access" }),
151 link("fs-2", { access: "full-access" }),
152 link("fs-3", { access: "auto" }),
153 link("fs-4", { access: "auto-accept-edits" }),
154 link("fs-5"),
155 link("fs-6", { access: "read-only" }),
156 link("nucbox", { access: "auto" }),
157 ]),
158 ]);
159
160/** Twenty environments, five of them folding by state, and 1000 machines two hosts both link to. */
161const hugeSetup = () =>
162 build([
163 environment("nucbox", [...vms(1000, "vm", { access: "full-access" }), link("cups")]),
164 environment("cups", vms(1000, "vm", { access: "full-access" })),
165 environment("mbp", [link("nucbox", { access: "auto" })]),
166 ...Array.from({ length: 5 }, (_, index) => environment(`gpu-${index + 1}`)),
167 ...Array.from({ length: 6 }, (_, index) =>
168 environment(`lab-${index + 1}`, "unknown", { phase: "offline" }),
169 ),
170 ...Array.from({ length: 4 }, (_, index) =>
171 environment(`old-${index + 1}`, "unknown", { enabled: false, phase: "available" }),
172 ),
173 ...Array.from({ length: 2 }, (_, index) =>
174 environment(`legacy-${index + 1}`, "unknown", { phase: "unsupported" }),
175 ),
176 ]);
177
178/** Points along a path the layout wrote: absolute M, H, V, Q and C only. */
179function samplePath(d: string): Array<{ x: number; y: number }> {
180 const points: Array<{ x: number; y: number }> = [];
181 let x = 0;
182 let y = 0;
183 const curve = (controls: ReadonlyArray<number>) => {
184 const xs = [x, ...controls.filter((_, index) => index % 2 === 0)];
185 const ys = [y, ...controls.filter((_, index) => index % 2 === 1)];
186 const at = (values: ReadonlyArray<number>, t: number): number =>
187 values.length === 1
188 ? values[0]!
189 : at(
190 values.slice(1).map((value, index) => values[index]! * (1 - t) + value * t),
191 t,
192 );
193 for (let step = 1; step <= 24; step += 1) {
194 points.push({ x: at(xs, step / 24), y: at(ys, step / 24) });
195 }
196 x = xs.at(-1)!;
197 y = ys.at(-1)!;
198 };
199 for (const [, command, rest] of d.matchAll(/([MHVQC])([^MHVQC]*)/g)) {
200 const values = rest!.trim().split(/[ ,]+/).map(Number);
201 if (command === "M") points.push({ x: (x = values[0]!), y: (y = values[1]!) });
202 else if (command === "H") curve([values[0]!, y]);
203 else if (command === "V") curve([x, values[0]!]);
204 else curve(values);
205 }
206 return points;
207}
208
209const overlaps = (a: FleetRect, b: FleetRect) =>
210 a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height;
211
212/** Every box the layout draws that must not sit on another. */
213const solidRects = (layout: FleetLayout) => [
214 ...[...layout.nodes].map(([key, rect]) => ({ key, rect, within: null as string | null })),
215 ...[...layout.routes].map(([key, geometry]) => ({ key, rect: geometry.pill, within: null })),
216 ...[...layout.stacks].map(([key, geometry]) => ({ key, rect: geometry.rect, within: key })),
217];
218
219function expectNoOverlap(layout: FleetLayout, members: ReadonlyMap<string, string>) {
220 const rects = solidRects(layout);
221 for (const [index, left] of rects.entries()) {
222 for (const right of rects.slice(index + 1)) {
223 // An open stack's frame holds its own machines.
224 if (members.get(left.key) === right.within || members.get(right.key) === left.within) {
225 if (left.within !== null || right.within !== null) continue;
226 }
227 expect(overlaps(left.rect, right.rect), `${left.key} overlaps ${right.key}`).toBe(false);
228 }
229 expect(left.rect.x).toBeGreaterThanOrEqual(0);
230 expect(left.rect.y).toBeGreaterThanOrEqual(0);
231 expect(left.rect.x + left.rect.width).toBeLessThanOrEqual(layout.width);
232 expect(left.rect.y + left.rect.height).toBeLessThanOrEqual(layout.height);
233 }
234}
235
236describe("buildFleetGraph", () => {
237 it("draws each saved route as its own edge and reads its state from what the client knows", () => {
238 const routes = [
239 { id: "tailnet", kind: "tailnet" as const },
240 { id: "lan", kind: "lan" as const },
241 { id: "relay", kind: "relay" as const },
242 ];
243 const graph = build([
244 environment("up", [], { routes, activeRouteId: "lan", refusedRouteIds: ["relay"] }),
245 environment("dialling", "unknown", { routes, phase: "connecting", activeRouteId: null }),
246 environment("gone", "unknown", { routes, phase: "error", activeRouteId: null }),
247 environment("off", "unknown", { routes, enabled: false, phase: "available" }),
248 environment("old", "unknown", { routes, phase: "unsupported" }),
249 ]);
250 expect(routeStates(graph, "up")).toEqual({
251 tailnet: "standby",
252 lan: "in-use",
253 relay: "refused",
254 });
255 expect(routeStates(graph, "dialling")).toEqual({
256 tailnet: "trying",
257 lan: "trying",
258 relay: "trying",
259 });
260 expect(routeStates(graph, "gone")).toEqual({ tailnet: "down", lan: "down", relay: "down" });
261 expect(routeStates(graph, "off")).toEqual({ tailnet: "idle", lan: "idle", relay: "idle" });
262 expect(routeStates(graph, "old")).toEqual({ tailnet: "idle", lan: "idle", relay: "idle" });
263 });
264
265 it("adds T3 Connect machines the client has not saved, and only those", () => {
266 const graph = build([environment("cups")], [connectMachine("cups"), connectMachine("gpu")]);
267 expect(graph.nodes.map((entry) => `${entry.kind}:${entry.label}`)).toEqual([
268 "client:This browser",
269 "environment:cups",
270 "connect:gpu",
271 ]);
272 expect(routeStates(graph, "gpu")).toEqual({ offer: "offered" });
273 });
274
275 it("keeps one node per machine and one edge per link, whatever names it twice", () => {
276 const graph = build(
277 [
278 environment("cups", [link("vps"), link("vps"), link("cups"), link("gpu"), link("nucbox")]),
279 environment("cups", [link("other")]),
280 environment("nucbox"),
281 ],
282 [connectMachine("gpu")],
283 );
284 expect(graph.nodes.map((entry) => `${entry.kind}:${entry.label}`)).toEqual([
285 "client:This browser",
286 "environment:cups",
287 "environment:nucbox",
288 "connect:gpu",
289 "target:vps",
290 ]);
291 expect(graph.edges.filter((edge) => edge.kind === "link").map((edge) => edge.id)).toEqual([
292 `link:${node("cups")}>${node("vps")}`,
293 `link:${node("cups")}>${node("gpu")}`,
294 `link:${node("cups")}>${node("nucbox")}`,
295 ]);
296 });
297
298 it("keeps unknown, off, loading and failed link lists apart from an empty one", () => {
299 const graph = build([
300 environment("a", "loaded"),
301 environment("b", "loading"),
302 environment("c", "error"),
303 environment("d", "off", { offersLinks: false }),
304 environment("e", "unknown", { phase: "offline" }),
305 environment("f", [], { canWriteAccess: false }),
306 ]);
307 const states = graph.nodes.flatMap((entry) =>
308 entry.kind === "environment"
309 ? [[entry.label, entry.outgoing, entry.linking, entry.outgoingError]]
310 : [],
311 );
312 expect(states).toEqual([
313 ["a", "loaded", "ready", null],
314 ["b", "loading", "ready", null],
315 ["c", "error", "ready", "boom"],
316 ["d", "off", "off", null],
317 ["e", "unknown", "disconnected", null],
318 ["f", "loaded", "forbidden", null],
319 ]);
320 });
321
322 it("reads a link's health at the given time", () => {
323 const graph = build([
324 environment("cups", [
325 link("soon", { expiresAt: DateTime.makeUnsafe("2026-11-21T12:00:00.000Z") }),
326 link("gone", { status: "expired" }),
327 ]),
328 ]);
329 expect(graph.edges.flatMap((edge) => (edge.kind === "link" ? [edge.health] : []))).toEqual([
330 { kind: "reachable", expiresInDays: 2 },
331 { kind: "expired" },
332 ]);
333 });
334});
335
336describe("fleetSummary", () => {
337 it("counts links only when every connected environment's list was read", () => {
338 const summary = (...environments: FleetEnvironmentInput[]) => fleetSummary(build(environments));
339 expect(summary(environment("a", [link("x")]), environment("b"))).toEqual({
340 machines: 3,
341 links: 1,
342 loading: false,
343 });
344 expect(summary(environment("a"), environment("b"))).toMatchObject({ links: 0 });
345 // One failed list among several leaves the total unknown, not zero.
346 expect(summary(environment("a"), environment("b", "error"))).toMatchObject({ links: null });
347 expect(summary(environment("a", "unknown"))).toMatchObject({ links: null });
348 expect(summary(environment("a"), environment("b", "loading"))).toMatchObject({
349 links: null,
350 loading: true,
351 });
352 // A machine that is not connected says nothing either way.
353 expect(
354 summary(environment("a", [link("x")]), environment("b", "unknown", { phase: "offline" })),
355 ).toMatchObject({ links: 1 });
356 });
357});
358
359describe("fleetStacks", () => {
360 it("collapses many machines under one host and one access level, and nothing smaller", () => {
361 const graph = build([
362 environment("nucbox", [
363 ...vms(40, "fs", { access: "full-access" }),
364 ...vms(4, "few"),
365 link("fs-41", { access: "full-access", status: "unreachable" }),
366 ]),
367 ]);
368 const stacks = fleetStacks(graph, new Set());
369 expect(
370 stacks.map((stack) => [
371 stack.id,
372 stack.memberIds.length,
373 stack.reachable,
374 stack.firstLabel,
375 stack.lastLabel,
376 stack.expanded,
377 ]),
378 ).toEqual([[`stack:${node("nucbox")}:full-access`, 41, 40, "fs-1", "fs-41", false]]);
379 const [open] = fleetStacks(graph, new Set([stacks[0]!.id]));
380 expect(open!.expanded).toBe(true);
381 // An open stack draws its first machines; the rest stay in the details.
382 expect(open!.shownIds).toEqual(open!.memberIds.slice(0, FLEET_STACK_SHOWN_MAX));
383 });
384
385 it("folds machines that share the exact set of links in, and keeps other sets apart", () => {
386 const graph = build([
387 environment("nucbox", [
388 ...vms(8, "vm", { access: "full-access" }),
389 ...vms(6, "ro", { access: "read-only" }),
390 ...vms(5, "solo"),
391 ]),
392 environment("cups", [
393 link("vm-1", { access: "full-access", status: "unreachable" }),
394 ...vms(8, "vm", { access: "full-access" }).slice(1),
395 // The same two hosts, but one at another access level: a set of its own.
396 ...vms(6, "ro", { access: "full-access" }),
397 ]),
398 ]);
399 const stacks = fleetStacks(graph, new Set());
400 expect(
401 stacks.map((stack) => [
402 stack.sources.map((source) => `${source.sourceId}:${source.access}`),
403 stack.memberIds.length,
404 stack.edgeIds.length,
405 stack.reachable,
406 ]),
407 ).toEqual([
408 [[`${node("nucbox")}:full-access`, `${node("cups")}:full-access`], 8, 16, 7],
409 [[`${node("nucbox")}:read-only`, `${node("cups")}:full-access`], 6, 12, 6],
410 [[`${node("nucbox")}:approval-required`], 5, 5, 5],
411 ]);
412 });
413
414 it("folds unlinked environments by state once there are many, and never a linked or connected one", () => {
415 const few = build(
416 Array.from({ length: FLEET_FOLD_ENVIRONMENTS_OVER }, (_, index) =>
417 environment(`lab-${index}`, "unknown", { phase: "offline" }),
418 ),
419 );
420 expect(fleetStacks(few, new Set())).toEqual([]);
421 const graph = build(
422 [
423 environment("nucbox", [link("linked-offline")]),
424 environment("linked-offline", "unknown", { phase: "offline" }),
425 environment("idle"),
426 environment("dialling", "unknown", { phase: "connecting" }),
427 ...Array.from({ length: 4 }, (_, index) =>
428 environment(`lab-${index + 1}`, "unknown", { phase: index === 0 ? "error" : "offline" }),
429 ),
430 ...Array.from({ length: 3 }, (_, index) =>
431 environment(`old-${index + 1}`, "unknown", { enabled: false, phase: "available" }),
432 ),
433 // Two is too few to be worth a stack.
434 environment("legacy-1", "unknown", { phase: "unsupported" }),
435 environment("legacy-2", "unknown", { phase: "unsupported" }),
436 ],
437 ["gpu-1", "gpu-2", "gpu-3"].map(connectMachine),
438 );
439 expect(
440 fleetStacks(graph, new Set()).map((stack) => [stack.kind, stack.group, stack.memberIds]),
441 ).toEqual([
442 ["environments", "offline", ["lab-1", "lab-2", "lab-3", "lab-4"].map(node)],
443 ["environments", "off", ["old-1", "old-2", "old-3"].map(node)],
444 ["environments", "not-added", ["gpu-1", "gpu-2", "gpu-3"].map(node)],
445 ]);
446 });
447
448 it("leaves out a machine a second host links to, and a machine the client knows", () => {
449 const graph = build([
450 environment("nucbox", [...vms(6, "fs"), link("cups")]),
451 environment("cups", [link("fs-1")]),
452 ]);
453 const [stack] = fleetStacks(graph, new Set());
454 expect(stack!.memberIds).toEqual(["fs-2", "fs-3", "fs-4", "fs-5", "fs-6"].map(node));
455 });
456});
457
458describe("fleetLinkOffer", () => {
459 const graph = build(
460 [
461 environment("cups", [link("vm"), link("old", { status: "expired" }), link("nucbox")]),
462 environment("nucbox"),
463 environment("guest", [], { canWriteAccess: false }),
464 environment("nolabs", "off", { offersLinks: false }),
465 environment("ssh-only", [], { hasLinkAddress: false }),
466 environment("asleep", "unknown", { phase: "offline" }),
467 ],
468 [connectMachine("gpu")],
469 );
470 const offer = (source: string, target: string) =>
471 fleetLinkOffer(graph, node(source), target === "client" ? FLEET_CLIENT_NODE_ID : node(target));
472
473 it("links without a code only where the client can mint one on the target", () => {
474 expect(offer("nucbox", "cups")).toEqual({
475 kind: "link",
476 sourceEnvironmentId: id("nucbox"),
477 path: "code-less",
478 renews: false,
479 target: { kind: "machine", environmentId: id("cups") },
480 });
481 expect(offer("cups", "nucbox")).toMatchObject({ path: "code-less", renews: true });
482 for (const target of ["guest", "ssh-only", "asleep", "gpu"]) {
483 expect(offer("cups", target), target).toMatchObject({
484 path: "pairing-code",
485 target: { kind: "machine", environmentId: id(target) },
486 });
487 }
488 });
489
490 it("links to a machine known only through a link by its address, with a code", () => {
491 expect(offer("nucbox", "vm")).toMatchObject({
492 path: "pairing-code",
493 renews: false,
494 target: { kind: "address", address: "https://vm.example.ts.net" },
495 });
496 expect(offer("cups", "vm")).toMatchObject({ renews: true });
497 expect(offer("cups", "old")).toMatchObject({ renews: false });
498 });
499
500 it("links through a machine that holds a full-access link there and whose access the client manages", () => {
501 const through = (hosts: ReadonlyArray<FleetEnvironmentInput>) => {
502 const result = fleetLinkOffer(build(hosts), node("mbp"), node("vm"));
503 return result.kind === "link" ? [result.path, result.target] : result.kind;
504 };
505 const full = link("vm", { access: "full-access" });
506 expect(through([environment("mbp"), environment("nucbox", [full])])).toEqual([
507 "through-link",
508 {
509 kind: "address",
510 address: "https://vm.example.ts.net",
511 through: { viaEnvironmentId: id("nucbox"), environmentId: id("vm"), label: "vm" },
512 },
513 ]);
514 for (const [why, nucbox] of [
515 ["a lower link", environment("nucbox", [link("vm")])],
516 ["an expired link", environment("nucbox", [{ ...full, status: "expired" }])],
517 ["a link that does not answer", environment("nucbox", [{ ...full, status: "unreachable" }])],
518 ["no access management", environment("nucbox", [full], { canWriteAccess: false })],
519 ] as const) {
520 expect(through([environment("mbp"), nucbox]), why).toMatchObject(["pairing-code", {}]);
521 }
522 // Its own link is not a way to a new one.
523 expect(through([environment("mbp", [full])])).toMatchObject(["pairing-code", {}]);
524 });
525
526 it("offers nothing from a machine that cannot link, or to itself or the client", () => {
527 const reason = (source: string, target: string) => {
528 const result = offer(source, target);
529 return result.kind === "unavailable" ? result.reason : result.kind;
530 };
531 expect(reason("cups", "cups")).toBe("same-machine");
532 expect(reason("cups", "client")).toBe("not-an-environment");
533 expect(reason("gpu", "cups")).toBe("not-an-environment");
534 expect(reason("vm", "cups")).toBe("not-an-environment");
535 expect(reason("asleep", "cups")).toBe("source-disconnected");
536 expect(reason("nolabs", "cups")).toBe("source-off");
537 expect(reason("guest", "cups")).toBe("source-forbidden");
538 });
539});
540
541describe("fleetLinkAction", () => {
542 const graph = build([
543 environment("nucbox", [...vms(6, "fs")]),
544 environment("cups"),
545 environment("mbp", "unknown", { phase: "offline" }),
546 environment("vps", [], { canWriteAccess: false }),
547 ]);
548 const stacks = fleetStacks(graph, new Set());
549 const batch = (environmentIds: ReadonlyArray<string>) => ({
550 kind: "batch",
551 sourceEnvironmentId: id("nucbox"),
552 environmentIds: environmentIds.map(id),
553 });
554
555 it("links to the selection when the drop lands on it, or the handle is pressed with one", () => {
556 const selected = new Set([node("cups"), node("mbp"), node("nucbox"), FLEET_CLIENT_NODE_ID]);
557 // The source and the client are never among the machines to link.
558 expect(fleetLinkAction(graph, stacks, selected, node("nucbox"), node("cups"))).toEqual(
559 batch(["cups", "mbp"]),
560 );
561 expect(fleetLinkAction(graph, stacks, selected, node("nucbox"), null)).toEqual(
562 batch(["cups", "mbp"]),
563 );
564 });
565
566 it("links one machine when the drop lands outside the selection, or nothing is selected", () => {
567 const selected = new Set([node("mbp")]);
568 expect(fleetLinkAction(graph, stacks, selected, node("nucbox"), node("cups"))).toMatchObject({
569 kind: "single",
570 offer: { path: "code-less", target: { environmentId: id("cups") } },
571 });
572 expect(fleetLinkAction(graph, stacks, new Set(), node("nucbox"), null)).toEqual({
573 kind: "single",
574 sourceEnvironmentId: id("nucbox"),
575 offer: null,
576 });
577 // A selection of only the source is no batch.
578 expect(
579 fleetLinkAction(graph, stacks, new Set([node("nucbox")]), node("nucbox"), null),
580 ).toMatchObject({ kind: "single" });
581 });
582
583 it("opens no batch for machines the client has no session on, and offers nothing from a host that cannot link", () => {
584 const members = ["fs-1", "fs-2", "fs-3", "fs-4", "fs-5", "fs-6"].map(node);
585 // A stack of machines known only through links: each needs a code, so no batch can link one.
586 expect(fleetLinkAction(graph, stacks, new Set(), node("cups"), stacks[0]!.id)).toEqual({
587 kind: "code-only",
588 sourceId: node("cups"),
589 sourceEnvironmentId: id("cups"),
590 machineIds: members,
591 });
592 // One such machine alone, ticked and dropped on, is asked for its code like any other.
593 expect(
594 fleetLinkAction(graph, stacks, new Set([node("fs-1")]), node("cups"), node("fs-1")),
595 ).toMatchObject({
596 kind: "single",
597 sourceEnvironmentId: id("cups"),
598 offer: { path: "pairing-code", target: { kind: "address" } },
599 });
600 // One the client is connected to among them makes it a batch, which says why for the rest.
601 const mixed = new Set([node("fs-1"), node("fs-2"), node("mbp")]);
602 expect(fleetLinkAction(graph, stacks, mixed, node("cups"), node("mbp"))).toEqual({
603 ...batch(["fs-1", "fs-2", "mbp"]),
604 sourceEnvironmentId: id("cups"),
605 });
606 for (const source of ["mbp", "vps"]) {
607 expect(fleetLinkAction(graph, stacks, new Set(), node(source), stacks[0]!.id)).toBeNull();
608 expect(fleetLinkAction(graph, stacks, new Set(), node(source), null)).toBeNull();
609 }
610 expect(fleetLinkAction(graph, stacks, new Set(), node("nucbox"), node("nucbox"))).toBeNull();
611 });
612});
613
614describe("fleetTwoWayLinks", () => {
615 const graph = build([
616 environment("a", [link("b"), link("c", { access: "full-access" }), link("d")]),
617 environment("b", [link("a", { status: "unreachable" })]),
618 environment("c", [link("a", { access: "auto" })]),
619 environment("d"),
620 ]);
621 const pairs = fleetTwoWayLinks(graph);
622 const edge = (from: string, to: string) => `link:${node(from)}>${node(to)}`;
623
624 it("merges two links between the same machines only at the same access", () => {
625 expect([...pairs.keys()].toSorted()).toEqual([edge("a", "b"), edge("b", "a")]);
626 // Both links select the one line, drawn as the link from the machine listed first.
627 expect(fleetDrawnLinkId(pairs, edge("b", "a"))).toBe(edge("a", "b"));
628 expect(fleetDrawnLinkId(pairs, edge("a", "b"))).toBe(edge("a", "b"));
629 // Different access says two different things, and a one-way link has no other half.
630 expect(fleetDrawnLinkId(pairs, edge("c", "a"))).toBe(edge("c", "a"));
631 expect(fleetDrawnLinkId(pairs, edge("a", "d"))).toBe(edge("a", "d"));
632 });
633
634 it("keeps each direction's own health, and counts both links", () => {
635 const pair = pairs.get(edge("a", "b"))!;
636 expect(pair.forward.health.kind).toBe("reachable");
637 expect(pair.back.health.kind).toBe("unreachable");
638 expect(fleetSummary(graph).links).toBe(5);
639 });
640
641 it("lights both links and both machines' routes from either one", () => {
642 const lit = fleetNeighborhood(graph, [], { kind: "edge", id: edge("a", "b") });
643 expect(lit.edges.has(edge("a", "b")) && lit.edges.has(edge("b", "a"))).toBe(true);
644 expect(lit.edges.has(`route:${node("a")}:tailnet`)).toBe(true);
645 expect(lit.edges.has(`route:${node("b")}:tailnet`)).toBe(true);
646 expect(lit.edges.has(edge("a", "d"))).toBe(false);
647 });
648
649 it("offers the link back on a one-way link only where the client can make it", () => {
650 const linkEdge = (from: ReturnType<typeof build>, source: string, target: string) =>
651 from.edges.filter(isLinkEdge).find((entry) => entry.id === edge(source, target))!;
652 expect(fleetLinkBackOffered(graph, linkEdge(graph, "a", "d"))).toBe(true);
653 // Already linked back, at whatever access.
654 expect(fleetLinkBackOffered(graph, linkEdge(graph, "a", "c"))).toBe(false);
655 for (const target of [
656 environment("d", "unknown", { phase: "offline" }),
657 environment("d", "off", { offersLinks: false }),
658 environment("d", [], { canWriteAccess: false }),
659 environment("d", "loading"),
660 ]) {
661 const other = build([environment("a", [link("d")]), target]);
662 expect(fleetLinkBackOffered(other, linkEdge(other, "a", "d"))).toBe(false);
663 }
664 for (const source of [{ canWriteAccess: false }, { hasLinkAddress: false }]) {
665 const other = build([environment("a", [link("d")], source), environment("d")]);
666 expect(fleetLinkBackOffered(other, linkEdge(other, "a", "d"))).toBe(false);
667 }
668 // A machine known only through the link is not one the client can link from.
669 const unknown = build([environment("a", [link("x")])]);
670 expect(fleetLinkBackOffered(unknown, linkEdge(unknown, "a", "x"))).toBe(false);
671 });
672});
673
674describe("selecting and finding machines", () => {
675 it("selects the machines a box touches, and never the client or a stack", () => {
676 const graph = largeSetup();
677 const layout = layoutFleetGraph(graph, fleetStacks(graph, new Set()));
678 const everything = { x: 0, y: 0, width: layout.width, height: layout.height };
679 expect(fleetNodesInBox(layout, everything).toSorted()).toEqual(
680 [...layout.nodes.keys()].filter((key) => key !== FLEET_CLIENT_NODE_ID).toSorted(),
681 );
682 const cups = layout.nodes.get(node("cups"))!;
683 expect(fleetNodesInBox(layout, { x: cups.x + 4, y: cups.y + 4, width: 2, height: 2 })).toEqual([
684 node("cups"),
685 ]);
686 });
687
688 it("finds machines by name wherever they are drawn, in name order", () => {
689 const graph = largeSetup();
690 expect(fleetSearch(graph, " FS-1 ").slice(0, 3)).toEqual(["fs-1", "fs-10", "fs-11"].map(node));
691 expect(fleetSearch(graph, "")).toEqual([]);
692 expect(fleetSearch(graph, "this browser")).toEqual([]);
693 });
694});
695
696describe("fleetNeighborhood", () => {
697 const graph = build([
698 environment("a", [link("b"), ...vms(5)]),
699 environment("b", [link("c")]),
700 environment("c"),
701 ]);
702 const stacks = fleetStacks(graph, new Set());
703
704 it("lights one hop from a machine and its routes, and does not follow a link through", () => {
705 const lit = fleetNeighborhood(graph, stacks, { kind: "node", id: node("b") });
706 expect([...lit.nodes].toSorted()).toEqual(
707 [FLEET_CLIENT_NODE_ID, node("a"), node("b"), node("c")].toSorted(),
708 );
709 expect(lit.edges.has(`link:${node("a")}>${node("vm-1")}`)).toBe(false);
710 expect(lit.edges.has(`route:${node("b")}:tailnet`)).toBe(true);
711 expect(lit.edges.has(`route:${node("a")}:tailnet`)).toBe(true);
712 expect(lit.edges.has(`route:${node("c")}:tailnet`)).toBe(false);
713 });
714
715 it("lights a stack's machines, their host and the route to it", () => {
716 const lit = fleetNeighborhood(graph, stacks, { kind: "stack", id: stacks[0]!.id });
717 expect(lit.nodes.has(node("vm-3"))).toBe(true);
718 expect(lit.nodes.has(node("b"))).toBe(false);
719 expect(lit.edges.has(`route:${node("a")}:tailnet`)).toBe(true);
720 });
721});
722
723describe("layoutFleetGraph", () => {
724 const membersOf = (stacks: ReturnType<typeof fleetStacks>) =>
725 new Map(stacks.flatMap((stack) => stack.memberIds.map((member) => [member, stack.id])));
726
727 it("places one environment, and a large setup, with nothing overlapping or out of bounds", () => {
728 const one = build([environment("cups")]);
729 expectNoOverlap(layoutFleetGraph(one), new Map());
730 const large = largeSetup();
731 const closed = fleetStacks(large, new Set());
732 const layout = layoutFleetGraph(large, closed);
733 expectNoOverlap(layout, membersOf(closed));
734 // Forty machines cost one node: 6 environments, the client, the Connect machine, 5 targets.
735 expect(layout.nodes.size).toBe(13);
736 expect(layout.stacks.size).toBe(1);
737 expect(layout.routes.size).toBe(9);
738 expect(layout.columns.map((column) => column.id)).toEqual([
739 "client",
740 "environments",
741 "targets",
742 ]);
743 });
744
745 it("opens a stack where its card is, each machine in the tray below it", () => {
746 const large = largeSetup();
747 const closed = fleetStacks(large, new Set());
748 const stackId = closed[0]!.id;
749 const open = fleetStacks(large, new Set([stackId]));
750 for (const width of [undefined, 560, 900, 1400]) {
751 const before = layoutFleetGraph(large, closed, width);
752 const layout = layoutFleetGraph(large, open, width);
753 expectNoOverlap(layout, membersOf(open));
754 // Forty machines open to the first 24 and one card for the other 16, never forty cards.
755 expect(layout.nodes.size).toBe(13 + FLEET_STACK_SHOWN_MAX);
756 const { face, tray } = layout.stacks.get(stackId)!;
757 const more = fleetFocusRects(layout).get(fleetMoreNodeId(stackId))!;
758 expect(layout.nodes.has(open[0]!.memberIds[FLEET_STACK_SHOWN_MAX]!)).toBe(false);
759 for (const rect of [more, ...open[0]!.shownIds.map((member) => layout.nodes.get(member)!)]) {
760 expect(rect.x).toBeGreaterThanOrEqual(tray!.x);
761 expect(rect.y).toBeGreaterThanOrEqual(tray!.y);
762 expect(rect.x + rect.width).toBeLessThanOrEqual(tray!.x + tray!.width);
763 expect(rect.y + rect.height).toBeLessThanOrEqual(tray!.y + tray!.height);
764 }
765 // The card, its lines, every route and every column stay put: the width's measures are
766 // those of the closed map, so opening never closes the columns up.
767 expect(face).toEqual(before.stacks.get(stackId)!.face);
768 expect(layout.stacks.get(stackId)!.lines.map((line) => line.arrow)).toEqual(
769 before.stacks.get(stackId)!.lines.map((line) => line.arrow),
770 );
771 expect(layout.routes).toEqual(before.routes);
772 expect(layout.columns).toEqual(before.columns);
773 expect(tray!.y).toBeGreaterThanOrEqual(face.y + face.height);
774 // Only machines the tray would cover move, and only down.
775 for (const [nodeId, rect] of before.nodes) {
776 const now = layout.nodes.get(nodeId)!;
777 if (rect.x === face.x && rect.y > face.y) {
778 expect(now.y, nodeId).toBeGreaterThanOrEqual(tray!.y + tray!.height);
779 expect({ ...now, y: rect.y }, nodeId).toEqual(rect);
780 } else {
781 expect(now, nodeId).toEqual(rect);
782 }
783 }
784 }
785 });
786
787 it("opens a group of environments where its card is, moving only the cards below it", () => {
788 const graph = hugeSetup();
789 const closed = fleetStacks(graph, new Set());
790 const fold = closed.find((stack) => stack.kind === "environments")!;
791 const open = fleetStacks(graph, new Set([fold.id]));
792 for (const width of [560, 1400]) {
793 const before = layoutFleetGraph(graph, closed, width);
794 const layout = layoutFleetGraph(graph, open, width);
795 expectNoOverlap(layout, membersOf(open));
796 const { face } = layout.stacks.get(fold.id)!;
797 expect(face).toEqual(before.stacks.get(fold.id)!.face);
798 for (const [nodeId, rect] of before.nodes) {
799 const now = layout.nodes.get(nodeId)!;
800 if (rect.y < face.y) expect(now, nodeId).toEqual(rect);
801 else expect({ ...now, y: rect.y }, nodeId).toEqual(rect);
802 }
803 }
804 });
805
806 it("draws the same map whatever order links arrive in", () => {
807 const forward = build([environment("a", [...vms(7), link("x"), link("y")])]);
808 const backward = build([environment("a", [link("y"), link("x"), ...vms(7).toReversed()])]);
809 const lay = (graph: ReturnType<typeof build>) => {
810 const layout = layoutFleetGraph(graph, fleetStacks(graph, new Set()));
811 return [...layout.nodes].toSorted(([left], [right]) => (left < right ? -1 : 1));
812 };
813 expect(lay(backward)).toEqual(lay(forward));
814 });
815
816 it("names the access of links between environments on their own lane, clear of everything", () => {
817 const graph = build([
818 environment("a", [link("b"), link("c"), link("x")]),
819 // At another access than the links back, so each of the four is its own line.
820 environment("b", [link("a", { access: "auto" }), link("x")]),
821 environment("c", [link("a", { access: "auto" })]),
822 ]);
823 const layout = layoutFleetGraph(graph);
824 const geometry = (from: string, to: string) =>
825 layout.links.get(`link:${node(from)}>${node(to)}`)!;
826 expect(geometry("a", "x").badge).toBeNull();
827 expect(geometry("b", "x").badge).toBeNull();
828 const badges = [
829 ["a", "b"],
830 ["a", "c"],
831 ["b", "a"],
832 ["c", "a"],
833 ].map(([from, to]) => {
834 const { badge, d } = geometry(from!, to!);
835 // On the link's own vertical run, between the two machines it joins.
836 const run = samplePath(d).filter(
837 (point) => point.y > badge!.y && point.y < badge!.y + badge!.height,
838 );
839 expect(run.length).toBeGreaterThan(0);
840 for (const point of run) {
841 expect(point.x).toBeGreaterThan(badge!.x);
842 expect(point.x).toBeLessThan(badge!.x + badge!.width);
843 }
844 const ends = [layout.nodes.get(node(from!))!, layout.nodes.get(node(to!))!];
845 expect(badge!.y).toBeGreaterThan(Math.min(...ends.map((rect) => rect.y)));
846 expect(badge!.y).toBeLessThan(Math.max(...ends.map((rect) => rect.y + rect.height)));
847 expect(badge!.x).toBeGreaterThanOrEqual(0);
848 expect(badge!.x + badge!.width).toBeLessThanOrEqual(layout.width);
849 return badge!;
850 });
851 const boxes = [...badges, ...solidRects(layout).map((box) => box.rect)];
852 for (const [index, badge] of badges.entries()) {
853 for (const other of boxes) {
854 if (other !== badge && boxes.indexOf(other) > index) {
855 expect(overlaps(badge, other)).toBe(false);
856 }
857 }
858 }
859 });
860
861 it("runs links between environments left of them and links to other machines right", () => {
862 const graph = largeSetup();
863 const layout = layoutFleetGraph(graph, fleetStacks(graph, new Set()));
864 const card = layout.nodes.get(node("nucbox"))!;
865 for (const edge of graph.edges) {
866 const geometry = edge.kind === "link" ? layout.links.get(edge.id) : undefined;
867 if (geometry === undefined) continue;
868 const between = layout.nodes.get(edge.to)!.x === card.x;
869 for (const point of samplePath(geometry.d)) {
870 if (between) expect(point.x, edge.id).toBeLessThanOrEqual(card.x);
871 else expect(point.x, edge.id).toBeGreaterThanOrEqual(card.x + card.width);
872 }
873 }
874 });
875
876 it("keeps two hosts' links into one machine apart, and every link clear of other boxes", () => {
877 for (const graph of [sharedSetup(), largeSetup(), hugeSetup()]) {
878 for (const expanded of [false, true]) {
879 const closed = fleetStacks(graph, new Set());
880 const stacks = expanded
881 ? fleetStacks(graph, new Set(closed.map((stack) => stack.id)))
882 : closed;
883 const layout = layoutFleetGraph(graph, stacks);
884 expectNoOverlap(layout, membersOf(stacks));
885 const boxes = solidRects(layout);
886 const drawn = [
887 ...[...layout.links].map(([key, geometry]) => ({ key, d: geometry.d })),
888 ...[...layout.stacks].flatMap(([key, geometry]) =>
889 geometry.lines.map((line) => ({ key, d: line.d })),
890 ),
891 ];
892 for (const { key, d } of drawn) {
893 for (const point of samplePath(d)) {
894 const hit = boxes.find(
895 ({ rect }) =>
896 point.x > rect.x + 0.5 &&
897 point.x < rect.x + rect.width - 0.5 &&
898 point.y > rect.y + 0.5 &&
899 point.y < rect.y + rect.height - 0.5,
900 );
901 expect(hit?.key, `${key} passes through ${hit?.key}`).toBeUndefined();
902 }
903 }
904 // The last stretch into a machine is level, so two that differ in height never share it.
905 const arrivals = new Map<string, number[]>();
906 for (const edge of graph.edges) {
907 const geometry = edge.kind === "link" ? layout.links.get(edge.id) : undefined;
908 if (geometry === undefined) continue;
909 const [before, last] = samplePath(geometry.d).slice(-2);
910 // A machine an open stack pushed far down is reached by a steeper curve.
911 expect(Math.abs(before!.y - geometry.arrow.y)).toBeLessThan(1);
912 expect(last!.y).toBe(geometry.arrow.y);
913 arrivals.set(edge.to, [...(arrivals.get(edge.to) ?? []), geometry.arrow.y]);
914 }
915 // A stack several hosts link to takes one line from each, each with its own entry.
916 for (const [stackId, geometry] of layout.stacks) {
917 for (const line of geometry.lines) {
918 if (line.arrow === null) continue;
919 if (geometry.lines.length > 1) {
920 expect(samplePath(line.d).at(-2)!.y).toBeCloseTo(line.arrow.y, 0);
921 }
922 arrivals.set(stackId, [...(arrivals.get(stackId) ?? []), line.arrow.y]);
923 }
924 }
925 for (const [target, heights] of arrivals) {
926 const sorted = heights.toSorted((left, right) => left - right);
927 for (const [index, height] of sorted.entries()) {
928 if (index > 0) {
929 expect(height - sorted[index - 1]!, `into ${target}`).toBeGreaterThanOrEqual(6);
930 }
931 }
932 }
933 }
934 }
935 });
936
937 it("draws 1000 shared machines and 20 environments as a few stacks, open or closed", () => {
938 const graph = hugeSetup();
939 const closed = fleetStacks(graph, new Set());
940 expect(closed.map((stack) => [stack.kind, stack.memberIds.length])).toEqual([
941 ["targets", 1000],
942 ["environments", 6],
943 ["environments", 4],
944 ]);
945 const layout = layoutFleetGraph(graph, closed);
946 expectNoOverlap(layout, membersOf(closed));
947 // The client and the ten environments that stay cards: nothing per folded machine.
948 expect(layout.nodes.size).toBe(11);
949 expect(layout.links.size).toBe(2);
950 expect(layout.routes.size).toBe(10);
951 expect(layout.stacks.get(closed[0]!.id)!.lines.map((line) => line.sourceId)).toEqual([
952 node("nucbox"),
953 node("cups"),
954 ]);
955 const open = fleetStacks(graph, new Set(closed.map((stack) => stack.id)));
956 const opened = layoutFleetGraph(graph, open);
957 expectNoOverlap(opened, membersOf(open));
958 expect(opened.nodes.size).toBe(11 + FLEET_STACK_SHOWN_MAX + 6 + 4);
959 expect(layoutFleetGraph(graph, open)).toEqual(opened);
960 });
961
962 it("sizes a card by its name alone, whatever routes and links attach to it", () => {
963 const routes = (count: number) =>
964 Array.from({ length: count }, (_, index) => ({ id: `r${index}`, kind: "tailnet" as const }));
965 const names = ["a", "b", "c", "d", "e"];
966 const mesh = build(
967 names.map((name, index) =>
968 environment(
969 name,
970 names.filter((other) => other !== name).map((other) => link(other)),
971 { routes: routes(index * 2 + 1) },
972 ),
973 ),
974 );
975 const layout = layoutFleetGraph(mesh);
976 expectNoOverlap(layout, new Map());
977 const plain = layoutFleetGraph(build([environment("a")])).nodes.get(node("a"))!;
978 const cards = names.map((name) => layout.nodes.get(node(name))!);
979 // Nine routes and eight links leave a card the size of one with a single route.
980 expect(cards.map((card) => card.height)).toEqual(names.map(() => plain.height));
981 expect(plain.height).toBeLessThanOrEqual(64);
982 const long = layoutFleetGraph(build([environment("Julius's MacBook Pro")]));
983 const wrapped = long.nodes.get(node("Julius's MacBook Pro"))!.height;
984 expect(wrapped).toBeGreaterThan(plain.height);
985 expect(wrapped).toBeLessThanOrEqual(72);
986 for (const [index, name] of names.entries()) {
987 const card = cards[index]!;
988 const pills = mesh.edges
989 .filter(isRouteEdge)
990 .filter((edge) => edge.to === node(name))
991 .map((edge) => layout.routes.get(edge.id)!);
992 const centers = pills.map(({ pill }) => pill.y + pill.height / 2);
993 // The route names keep their own pitch, centred on the card, and may reach past it.
994 expect((centers[0]! + centers.at(-1)!) / 2).toBeCloseTo(card.y + card.height / 2, 5);
995 for (const [at, center] of centers.entries()) {
996 if (at > 0) expect(center - centers[at - 1]!).toBe(FLEET_ROUTE_PITCH);
997 }
998 // Their wires close up and enter the card as one bundle, each at its own height.
999 const entries = pills.map(({ d }) => samplePath(d).at(-1)!.y);
1000 expect(new Set(entries).size).toBe(entries.length);
1001 expect(Math.max(...entries) - Math.min(...entries)).toBeLessThanOrEqual(10);
1002 for (const entry of entries) {
1003 expect(entry).toBeGreaterThan(card.y);
1004 expect(entry).toBeLessThan(card.y + card.height);
1005 }
1006 }
1007 // The gap between two cards grows only by what the taller column of route names needs.
1008 const gap = (upper: number) => cards[upper + 1]!.y - cards[upper]!.y - cards[upper]!.height;
1009 const two = layoutFleetGraph(build([environment("a"), environment("b")]));
1010 expect(gap(0)).toBe(two.nodes.get(node("b"))!.y - plain.y - plain.height);
1011 expect(gap(3)).toBeGreaterThan(gap(0));
1012 });
1013
1014 it("gives every link into a card its own arrowhead on the edge the card already has", () => {
1015 const fan = build([
1016 ...["a", "b", "c", "d"].map((name) => environment(name, [link("e")])),
1017 environment("e"),
1018 ]);
1019 const pair = build([
1020 environment("a", [link("b"), link("c")]),
1021 environment("b"),
1022 environment("c", [link("b")]),
1023 ]);
1024 const names = ["a", "b", "c", "d", "e"];
1025 const mesh = build(
1026 names.map((name) =>
1027 environment(
1028 name,
1029 names.filter((other) => other !== name).map((other) => link(other)),
1030 ),
1031 ),
1032 );
1033 for (const [graph, roomy] of [
1034 [pair, true],
1035 [fan, false],
1036 [mesh, false],
1037 ] as const) {
1038 const layout = layoutFleetGraph(graph);
1039 expectNoOverlap(layout, new Map());
1040 const arrivals = new Map<string, number[]>();
1041 for (const edge of graph.edges) {
1042 const geometry = edge.kind === "link" ? layout.links.get(edge.id) : undefined;
1043 if (edge.kind !== "link" || geometry === undefined) continue;
1044 const from = layout.nodes.get(edge.from)!;
1045 const leaves = samplePath(geometry.d)[0]!.y;
1046 expect(leaves).toBeGreaterThan(from.y);
1047 expect(leaves).toBeLessThan(from.y + from.height);
1048 arrivals.set(edge.to, [...(arrivals.get(edge.to) ?? []), geometry.arrow.y]);
1049 if (geometry.twoWay !== null) {
1050 const into = arrivals.get(edge.from) ?? [];
1051 arrivals.set(edge.from, [...into, geometry.twoWay.backArrow.y]);
1052 }
1053 }
1054 for (const [id, heights] of arrivals) {
1055 const card = layout.nodes.get(id)!;
1056 const sorted = heights.toSorted((left, right) => left - right);
1057 expect(sorted[0]!).toBeGreaterThan(card.y);
1058 expect(sorted.at(-1)!).toBeLessThan(card.y + card.height);
1059 for (const [index, height] of sorted.entries()) {
1060 if (index === 0) continue;
1061 // With room they are a full lane apart; a crowded edge closes them up, never onto
1062 // one another.
1063 expect(height - sorted[index - 1]!, `at ${id}`).toBeGreaterThanOrEqual(
1064 roomy ? FLEET_LANE_PITCH : 3,
1065 );
1066 }
1067 }
1068 }
1069 });
1070
1071 it("draws a two-way link once, on one lane, with an arrowhead into each card", () => {
1072 const setup = (back: Partial<PeerLinkSummary>) =>
1073 build([environment("a", [link("b")]), environment("b", [link("a", back)])]);
1074 const merged = setup({});
1075 const apart = setup({ access: "auto" });
1076 const forward = `link:${node("a")}>${node("b")}`;
1077 const reverse = `link:${node("b")}>${node("a")}`;
1078 const layout = layoutFleetGraph(merged);
1079 const two = layoutFleetGraph(apart);
1080 expect([...layout.links.keys()]).toEqual([forward]);
1081 expect([...two.links.keys()].toSorted()).toEqual([forward, reverse]);
1082 // Two lines need two lanes left of the cards; the merged one needs a single lane.
1083 expect(two.nodes.get(node("a"))!.x - layout.nodes.get(node("a"))!.x).toBeGreaterThan(0);
1084 expect(two.links.get(forward)!.twoWay).toBeNull();
1085 const geometry = layout.links.get(forward)!;
1086 const { twoWay } = geometry;
1087 expect(twoWay).not.toBeNull();
1088 for (const [arrow, cardId] of [
1089 [geometry.arrow, "b"],
1090 [twoWay!.backArrow, "a"],
1091 ] as const) {
1092 const card = layout.nodes.get(node(cardId))!;
1093 expect(arrow.x).toBe(card.x);
1094 expect(arrow.y).toBeGreaterThan(card.y);
1095 expect(arrow.y).toBeLessThan(card.y + card.height);
1096 }
1097 // Each half ends at its own arrowhead and the two meet, so one direction's state shows at
1098 // its end without a gap in the line.
1099 const forwardHalf = samplePath(twoWay!.forward);
1100 const backHalf = samplePath(twoWay!.back);
1101 expect(forwardHalf.at(-1)!.y).toBe(geometry.arrow.y);
1102 expect(backHalf[0]!.y).toBe(twoWay!.backArrow.y);
1103 expect(backHalf.at(-1)).toEqual(forwardHalf[0]);
1104 expect(geometry.badge?.onDemand).toBe(false);
1105 // Health is no part of the shape: one direction failing redraws nothing.
1106 expect(fleetShapeKey(setup({ status: "unreachable" }), [])).toBe(fleetShapeKey(merged, []));
1107 });
1108
1109 it("shows a link's name only on demand where it has no clear place", () => {
1110 const names = ["a", "b", "c", "d", "e"];
1111 const graph = build(
1112 names.map((name) =>
1113 environment(
1114 name,
1115 names.filter((other) => other !== name).map((other) => link(other)),
1116 ),
1117 ),
1118 );
1119 const layout = layoutFleetGraph(graph);
1120 const between = [...layout.links.values()];
1121 const always = between.flatMap(({ badge }) => (badge && !badge.onDemand ? [badge] : []));
1122 // Every link keeps a name; the ones always drawn sit on no other link's lane and no other name.
1123 expect(between.every(({ badge }) => badge !== null)).toBe(true);
1124 expect(always.length).toBeGreaterThan(0);
1125 expect(always.length).toBeLessThan(between.length);
1126 for (const [index, badge] of always.entries()) {
1127 for (const other of always.slice(index + 1)) expect(overlaps(badge, other)).toBe(false);
1128 const crossing = between.filter(({ badge: own, d }) => {
1129 if (own === badge) return false;
1130 return samplePath(d).some(
1131 (point) =>
1132 point.x > badge.x + 0.5 &&
1133 point.x < badge.x + badge.width - 0.5 &&
1134 point.y > badge.y + 0.5 &&
1135 point.y < badge.y + badge.height - 0.5,
1136 );
1137 });
1138 expect(crossing).toEqual([]);
1139 }
1140 });
1141
1142 it("puts a machine several hosts link to between them, and one host's machines beside it", () => {
1143 const layout = layoutFleetGraph(sharedSetup());
1144 const center = (name: string) => {
1145 const rect = layout.nodes.get(node(name))!;
1146 return rect.y + rect.height / 2;
1147 };
1148 for (const name of ["fs-1", "fs-2", "fs-3"]) {
1149 expect(center(name)).toBeGreaterThan(center("nucbox"));
1150 expect(center(name)).toBeLessThan(center("cups"));
1151 }
1152 expect(center("fs-5")).toBe(center("cups"));
1153 // The upper host's link arrives above the lower host's.
1154 const arrival = (from: string) => layout.links.get(`link:${node(from)}>${node("fs-2")}`)!.arrow;
1155 expect(arrival("nucbox").y).toBeLessThan(arrival("cups").y);
1156 });
1157
1158 it("gives up gutters before scale: a real setup stays legible from 560 to 1400 wide", () => {
1159 const routes = (...kinds: ReadonlyArray<"lan" | "tailnet" | "relay">) =>
1160 kinds.map((kind, index) => ({ id: `${kind}-${index}`, kind }));
1161 const graph = build([
1162 environment("cups", "unknown", {
1163 phase: "offline",
1164 routes: routes("tailnet", "tailnet", "relay"),
1165 }),
1166 environment(
1167 "nucbox-1",
1168 [
1169 link("Julius's MacBook Pro", { access: "full-access" }),
1170 ...vms(7, "fs", { access: "full-access" }),
1171 ...vms(37, "gs", { access: "full-access", status: "unreachable" }),
1172 ],
1173 { routes: routes("lan", "tailnet", "tailnet", "relay"), activeRouteId: "lan-0" },
1174 ),
1175 environment("Julius's MacBook Pro"),
1176 ]);
1177 const stacks = fleetStacks(graph, new Set());
1178 expect(stacks.map((stack) => [stack.memberIds.length, stack.reachable])).toEqual([[44, 7]]);
1179 const regular = layoutFleetGraph(graph, stacks);
1180 const widths = [560, 900, 1400].map((width) => {
1181 const layout = layoutFleetGraph(graph, stacks, width);
1182 expectNoOverlap(layout, membersOf(stacks));
1183 const height = fleetCanvasHeight(layout, width, { min: 0, max: 840 });
1184 expect(fitFleetLayout(layout, { width, height }).scale, `at ${width}`).toBeGreaterThanOrEqual(
1185 FLEET_FIT_LEGIBLE_SCALE,
1186 );
1187 // Only the columns move: every height, and so every lane and entry, is the regular one.
1188 expect(layout.height).toBe(regular.height);
1189 // Each route enters its machine at its own height, and a link's arrowhead stands clear
1190 // of all of them.
1191 const arrivals = new Map<string, { routes: number[]; links: number[] }>();
1192 const into = (id: string) =>
1193 arrivals.get(id) ?? arrivals.set(id, { routes: [], links: [] }).get(id)!;
1194 for (const edge of graph.edges) {
1195 if (edge.kind === "route") {
1196 into(edge.to).routes.push(samplePath(layout.routes.get(edge.id)!.d).at(-1)!.y);
1197 } else if (layout.links.has(edge.id)) {
1198 into(edge.to).links.push(layout.links.get(edge.id)!.arrow.y);
1199 }
1200 }
1201 for (const [id, { routes: entries, links: arrows }] of arrivals) {
1202 expect(new Set(entries).size, `into ${id}`).toBe(entries.length);
1203 for (const arrow of arrows) {
1204 for (const entry of entries) {
1205 expect(Math.abs(arrow - entry), `into ${id}`).toBeGreaterThanOrEqual(8);
1206 }
1207 }
1208 }
1209 // Every wire and link still ends level, however short its run became.
1210 for (const { d } of [...layout.routes.values(), ...layout.links.values()]) {
1211 const [before, last] = samplePath(d).slice(-2);
1212 expect(before!.y).toBe(last!.y);
1213 }
1214 return layout.width;
1215 });
1216 expect(widths[0]).toBeLessThan(regular.width);
1217 expect(widths[2]).toBeGreaterThan(regular.width);
1218 });
1219
1220 it("gives a stack room to say how many machines answer only when some do not", () => {
1221 const face = (links: ReadonlyArray<PeerLinkSummary>) => {
1222 const graph = build([environment("host", links)]);
1223 const stacks = fleetStacks(graph, new Set());
1224 expect(fleetStackPartial(stacks[0]!)).toBe(
1225 links.some((entry) => entry.status !== "reachable"),
1226 );
1227 return {
1228 key: fleetShapeKey(graph, stacks),
1229 height: layoutFleetGraph(graph, stacks).stacks.get(stacks[0]!.id)!.face.height,
1230 };
1231 };
1232 const whole = face(vms(6));
1233 const partial = face([...vms(5), link("vm-6", { status: "unreachable" })]);
1234 expect(partial.height).toBeGreaterThan(whole.height);
1235 // The card changes size, so the layout has to be made again.
1236 expect(partial.key).not.toBe(whole.key);
1237 });
1238
1239 it("keeps the shape key when only health, route state or status changes", () => {
1240 const key = (graph: ReturnType<typeof build>) =>
1241 fleetShapeKey(graph, fleetStacks(graph, new Set()));
1242 // One machine already not answering: how many more go quiet does not resize the card.
1243 const before = build([environment("a", [...vms(5), link("vm-6", { status: "unreachable" })])]);
1244 const after = build([
1245 environment("a", [...vms(6, "vm", { status: "unreachable" })], {
1246 activeRouteId: null,
1247 phase: "connected",
1248 }),
1249 ]);
1250 expect(key(after)).toBe(key(before));
1251 const moved = build([environment("a", [...vms(6, "vm", { access: "read-only" })])]);
1252 expect(key(moved)).not.toBe(key(before));
1253 const stacks = fleetStacks(before, new Set());
1254 expect(fleetShapeKey(before, fleetStacks(before, new Set([stacks[0]!.id])))).not.toBe(
1255 key(before),
1256 );
1257 // An environment that comes back leaves its folded group, with the group's id unchanged.
1258 const labs = (firstPhase: FleetEnvironmentInput["phase"]) =>
1259 build(
1260 Array.from({ length: 14 }, (_, index) =>
1261 environment(`lab-${index}`, "unknown", { phase: index === 0 ? firstPhase : "offline" }),
1262 ),
1263 );
1264 expect(key(labs("connecting"))).not.toBe(key(labs("offline")));
1265 });
1266});
1267
1268describe("nextFleetNode", () => {
1269 it("steps between columns and down a column, stacks included", () => {
1270 const graph = build([
1271 environment("a", [...vms(5), link("x", { access: "read-only" })]),
1272 environment("b"),
1273 ]);
1274 const stacks = fleetStacks(graph, new Set());
1275 const rects = fleetFocusRects(layoutFleetGraph(graph, stacks));
1276 expect(nextFleetNode(rects, FLEET_CLIENT_NODE_ID, "right")).toBe(node("a"));
1277 expect(nextFleetNode(rects, node("a"), "down")).toBe(node("b"));
1278 expect(nextFleetNode(rects, node("a"), "right")).toBe(stacks[0]!.id);
1279 expect(nextFleetNode(rects, stacks[0]!.id, "down")).toBe(node("x"));
1280 expect(nextFleetNode(rects, FLEET_CLIENT_NODE_ID, "left")).toBeNull();
1281 });
1282});
1283
1284describe("fitting the view", () => {
1285 it("fills the canvas but caps the zoom for a small map", () => {
1286 const view = fitFleetLayout({ width: 300, height: 60 }, { width: 900, height: 400 });
1287 expect(view.scale).toBe(1.15);
1288 expect(view.x).toBeCloseTo((900 - 300 * 1.15) / 2);
1289 });
1290
1291 it("fits a map taller than the manual minimum allows, and zooming out does not jump back", () => {
1292 const view = fitFleetLayout({ width: 700, height: 1572 }, { width: 800, height: 360 });
1293 expect(view.scale).toBeLessThan(0.3);
1294 expect(1572 * view.scale).toBeLessThanOrEqual(360);
1295 expect(zoomFleetView(view, 0.8, { x: 0, y: 0 }).scale).toBe(view.scale);
1296 const closer = zoomFleetView(view, 1.25, { x: 0, y: 0 }, view.scale);
1297 expect(closer.scale).toBeGreaterThan(view.scale);
1298 expect(zoomFleetView(closer, 0.8, { x: 0, y: 0 }, view.scale).scale).toBeCloseTo(view.scale);
1299 });
1300
1301 it("sizes the canvas to the fitted map within its bounds", () => {
1302 const bounds = { min: 240, max: 640 };
1303 expect(fleetCanvasHeight({ width: 400, height: 60 }, 900, bounds)).toBe(240);
1304 expect(fleetCanvasHeight({ width: 800, height: 2000 }, 900, bounds)).toBe(640);
1305 expect(fleetCanvasHeight({ width: 800, height: 300 }, 900, bounds)).toBe(
1306 Math.ceil(300 * ((900 - 56) / 800) + 56),
1307 );
1308 });
1309
1310 it("keeps a stack where it is on screen when it opens, and returns when it closes", () => {
1311 const graph = largeSetup();
1312 const closed = fleetStacks(graph, new Set());
1313 const stackId = closed[0]!.id;
1314 const open = fleetStacks(graph, new Set([stackId]));
1315 const bounds = { min: 180, max: 840 };
1316 const onScreen = (view: { x: number; y: number; scale: number }, rect: FleetRect) => ({
1317 x: rect.x * view.scale + view.x,
1318 y: rect.y * view.scale + view.y,
1319 });
1320 for (const width of [560, 640, 1400]) {
1321 const before = layoutFleetGraph(graph, closed, width);
1322 const after = layoutFleetGraph(graph, open, width);
1323 const size = { width, height: fleetCanvasHeight(before, width, bounds) };
1324 const fit = fitFleetLayout(before, size);
1325 const face = before.stacks.get(stackId)!.face;
1326 const opened = anchorFleetView({
1327 key: "open",
1328 from: { key: "closed", held: null, view: fit, size, face },
1329 stack: after.stacks.get(stackId)!,
1330 layout: after,
1331 bounds,
1332 });
1333 expect(opened.key).toBe("open");
1334 expect(opened.glide).toBe(true);
1335 // The canvas only grows, to show what opened, and never past its bound.
1336 expect(opened.height).toBeGreaterThanOrEqual(size.height);
1337 expect(opened.height).toBeLessThanOrEqual(bounds.max);
1338 // The scale holds, and the card and every machine beside it stay where they were.
1339 expect(opened.view).toEqual(fit);
1340 expect(onScreen(opened.view, after.nodes.get(node("nucbox"))!)).toEqual(
1341 onScreen(fit, before.nodes.get(node("nucbox"))!),
1342 );
1343 const tray = after.stacks.get(stackId)!.rect;
1344 expect(onScreen(opened.view, tray).x + tray.width * opened.view.scale).toBeLessThanOrEqual(
1345 width,
1346 );
1347
1348 // Zoomed in until the stack is wider than the canvas, the view shrinks to its width, once.
1349 const close = { x: fit.x - 600, y: fit.y, scale: 6 };
1350 const shrunk = anchorFleetView({
1351 key: "open",
1352 from: { key: "closed", held: null, view: close, size, face },
1353 stack: after.stacks.get(stackId)!,
1354 layout: after,
1355 bounds,
1356 });
1357 expect(shrunk.view.scale).toBeLessThan(6);
1358 expect(onScreen(shrunk.view, tray).x).toBeGreaterThanOrEqual(0);
1359 expect(onScreen(shrunk.view, tray).x + tray.width * shrunk.view.scale).toBeLessThanOrEqual(
1360 width,
1361 );
1362 expect(onScreen(shrunk.view, face).y).toBeCloseTo(onScreen(close, face).y);
1363
1364 // Closing it again goes back to the fit it came from.
1365 const back = anchorFleetView({
1366 key: "closed",
1367 from: { key: "open", held: opened, view: opened.view, size, face },
1368 stack: before.stacks.get(stackId)!,
1369 layout: before,
1370 bounds,
1371 });
1372 expect(back.key).toBe("");
1373 expect(back.glide).toBe(true);
1374
1375 // After a pan the view is the user's: closing keeps the card under the pointer instead.
1376 const panned = { ...opened, view: { ...opened.view, x: opened.view.x - 40 }, undo: null };
1377 const closedAgain = anchorFleetView({
1378 key: "closed",
1379 from: { key: "open", held: panned, view: panned.view, size, face },
1380 stack: before.stacks.get(stackId)!,
1381 layout: before,
1382 bounds,
1383 });
1384 expect(closedAgain.key).toBe("closed");
1385 expect(closedAgain.view.scale).toBe(panned.view.scale);
1386 expect(onScreen(closedAgain.view, face)).toEqual(onScreen(panned.view, face));
1387 expect(closedAgain.height).toBeLessThanOrEqual(size.height);
1388 // The canvas that grew for the tray gives that room back, not just the pre-open size.
1389 const grown = { width, height: opened.height };
1390 const givenBack = anchorFleetView({
1391 key: "closed",
1392 from: { key: "open", held: panned, view: panned.view, size: grown, face },
1393 stack: before.stacks.get(stackId)!,
1394 layout: before,
1395 bounds,
1396 });
1397 expect(givenBack.height).toBeLessThan(opened.height);
1398 }
1399 });
1400
1401 it("returns to a view set by hand before the stack opened", () => {
1402 const graph = largeSetup();
1403 const closed = fleetStacks(graph, new Set());
1404 const stackId = closed[0]!.id;
1405 const before = layoutFleetGraph(graph, closed, 1400);
1406 const after = layoutFleetGraph(graph, fleetStacks(graph, new Set([stackId])), 1400);
1407 const bounds = { min: 180, max: 840 };
1408 const size = { width: 1400, height: 500 };
1409 const held = {
1410 key: "closed",
1411 view: { x: -120, y: 30, scale: 1.4 },
1412 height: 500,
1413 glide: false,
1414 undo: null,
1415 };
1416 const face = before.stacks.get(stackId)!.face;
1417 const opened = anchorFleetView({
1418 key: "open",
1419 from: { key: "closed", held, view: held.view, size, face },
1420 stack: after.stacks.get(stackId)!,
1421 layout: after,
1422 bounds,
1423 });
1424 expect(opened.view.scale).toBe(1.4);
1425 const back = anchorFleetView({
1426 key: "closed",
1427 from: { key: "open", held: opened, view: opened.view, size, face },
1428 stack: before.stacks.get(stackId)!,
1429 layout: before,
1430 bounds,
1431 });
1432 expect(back).toEqual({ ...held, glide: true });
1433 });
1434
1435 it("zooms around the anchor", () => {
1436 const view = zoomFleetView({ x: 10, y: 20, scale: 1 }, 2, { x: 100, y: 100 });
1437 expect(view).toEqual({ scale: 2, x: -80, y: -60 });
1438 });
1439});