The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,940 lines 75 KB
Raw
1 import type {
2 ConnectionRouteKind,
3 EnvironmentConnectionPhase,
4 } from "@t3tools/client-runtime/connection";
5 import { linkBackOffer } from "@t3tools/client-runtime/link-batch";
6 import { peerLinkHealth, type PeerLinkHealth } from "@t3tools/client-runtime/state/peerLinks";
7 import {
8 AuthMcpClientAccess,
9 type EnvironmentId,
10 type EnvironmentMachineKind,
11 type PeerLinkSummary,
12 } from "@t3tools/contracts";
13 import type * as DateTime from "effect/DateTime";
14
15 export const FLEET_CLIENT_NODE_ID = "client";
16
17 /** What this client knows of the links an environment holds to others. */
18 export type FleetOutgoingLinks =
19 | { readonly state: "loaded"; readonly links: ReadonlyArray<PeerLinkSummary> }
20 | { readonly state: "loading" }
21 | { readonly state: "error"; readonly message: string }
22 /** Connected, but linked environments is off or unsupported there. */
23 | { readonly state: "off" }
24 /** Not connected, or not allowed to read: it may hold links this client cannot see. */
25 | { readonly state: "unknown" };
26
27 export interface FleetRouteInput {
28 readonly id: string;
29 readonly kind: ConnectionRouteKind;
30 /** The route's own label when it says more than its kind, such as "Tailscale HTTPS". */
31 readonly label?: string;
32 }
33
34 export interface FleetEnvironmentInput {
35 readonly environmentId: EnvironmentId;
36 readonly label: string;
37 readonly machine: EnvironmentMachineKind | null;
38 readonly phase: EnvironmentConnectionPhase;
39 /** Switched on in this client. A switched-off environment is saved but never dialled. */
40 readonly enabled: boolean;
41 /** Saved routes, preferred first. */
42 readonly routes: ReadonlyArray<FleetRouteInput>;
43 /** The route carrying the connection, when the client is connected and knows it. */
44 readonly activeRouteId: string | null;
45 readonly refusedRouteIds: ReadonlyArray<string>;
46 readonly outgoing: FleetOutgoingLinks;
47 /** Linked environments is supported and switched on there. */
48 readonly offersLinks: boolean;
49 /** This client's session there may create links from it and pairing codes on it. */
50 readonly canWriteAccess: boolean;
51 /** An address another machine can reach it at, so a link to it needs no typed address. */
52 readonly hasLinkAddress: boolean;
53 }
54
55 /** A machine on the user's T3 Connect account that this client has not saved. */
56 export interface FleetConnectMachineInput {
57 readonly environmentId: EnvironmentId;
58 readonly label: string;
59 readonly machine: EnvironmentMachineKind | null;
60 readonly availability: "checking" | "online" | "offline" | "error";
61 }
62
63 /**
64 * How a route is doing, from what the client knows: which one carries the connection, which the
65 * host refused, and the environment's phase. It never probes a route to find out.
66 */
67 export type FleetRouteState =
68 | "in-use"
69 | "standby"
70 | "trying"
71 /** The environment cannot be reached right now, over any route. */
72 | "down"
73 /** Not dialled: the environment is switched off, or needs an update first. */
74 | "idle"
75 | "refused"
76 /** A T3 Connect machine this client could add; no route is saved yet. */
77 | "offered";
78
79 /** Why an environment can or cannot be the source of a new link. */
80 export type FleetLinking = "ready" | "disconnected" | "off" | "forbidden";
81
82 export type FleetNode =
83 | { readonly id: string; readonly kind: "client"; readonly label: string }
84 | {
85 readonly id: string;
86 readonly kind: "environment";
87 readonly environmentId: EnvironmentId;
88 readonly label: string;
89 readonly machine: EnvironmentMachineKind | null;
90 readonly phase: EnvironmentConnectionPhase;
91 readonly enabled: boolean;
92 readonly routeCount: number;
93 readonly outgoing: FleetOutgoingLinks["state"];
94 readonly outgoingError: string | null;
95 readonly linking: FleetLinking;
96 /** The client can mint a pairing code there itself, so linking to it asks for none. */
97 readonly mintable: boolean;
98 readonly canWriteAccess: boolean;
99 readonly hasLinkAddress: boolean;
100 }
101 | {
102 readonly id: string;
103 readonly kind: "connect";
104 readonly environmentId: EnvironmentId;
105 readonly label: string;
106 readonly machine: EnvironmentMachineKind | null;
107 readonly availability: FleetConnectMachineInput["availability"];
108 }
109 /** Seen only as another environment's link target; the client is not connected to it. */
110 | {
111 readonly id: string;
112 readonly kind: "target";
113 readonly environmentId: EnvironmentId;
114 readonly label: string;
115 /** Where the first environment linking to it reaches it. */
116 readonly address: string | null;
117 };
118
119 export type FleetEnvironmentNode = Extract<FleetNode, { kind: "environment" }>;
120
121 export type FleetEdge =
122 | {
123 readonly id: string;
124 readonly kind: "route";
125 readonly from: string;
126 readonly to: string;
127 readonly routeId: string;
128 readonly routeKind: ConnectionRouteKind;
129 readonly routeLabel?: string;
130 readonly state: FleetRouteState;
131 }
132 | {
133 readonly id: string;
134 readonly kind: "link";
135 readonly from: string;
136 readonly to: string;
137 readonly sourceEnvironmentId: EnvironmentId;
138 readonly link: PeerLinkSummary;
139 readonly health: PeerLinkHealth;
140 };
141
142 export type FleetRouteEdge = Extract<FleetEdge, { kind: "route" }>;
143 export type FleetLinkEdge = Extract<FleetEdge, { kind: "link" }>;
144
145 export interface FleetGraph {
146 readonly nodes: ReadonlyArray<FleetNode>;
147 readonly edges: ReadonlyArray<FleetEdge>;
148 }
149
150 export const fleetEnvironmentNodeId = (environmentId: EnvironmentId) => `env:${environmentId}`;
151
152 function routeState(environment: FleetEnvironmentInput, routeId: string): FleetRouteState {
153 if (environment.refusedRouteIds.includes(routeId)) return "refused";
154 if (!environment.enabled) return "idle";
155 switch (environment.phase) {
156 case "connected":
157 return routeId === environment.activeRouteId ? "in-use" : "standby";
158 case "connecting":
159 return "trying";
160 case "unsupported":
161 case "available":
162 return "idle";
163 case "reconnecting":
164 case "error":
165 case "offline":
166 return "down";
167 }
168 }
169
170 function linking(environment: FleetEnvironmentInput): FleetLinking {
171 if (environment.phase !== "connected") return "disconnected";
172 if (!environment.offersLinks) return "off";
173 return environment.canWriteAccess ? "ready" : "forbidden";
174 }
175
176 /**
177 * One node per machine however often it is named: an environment listed twice, a link repeated
178 * in a list, a T3 Connect machine the client also saved, and a link to a machine the client
179 * knows all land on the same node. Each saved route is its own edge from the client.
180 */
181 export function buildFleetGraph(input: {
182 readonly clientLabel: string;
183 readonly environments: ReadonlyArray<FleetEnvironmentInput>;
184 readonly connectMachines?: ReadonlyArray<FleetConnectMachineInput>;
185 readonly now: DateTime.Utc;
186 }): FleetGraph {
187 const nodes = new Map<string, FleetNode>([
188 [FLEET_CLIENT_NODE_ID, { id: FLEET_CLIENT_NODE_ID, kind: "client", label: input.clientLabel }],
189 ]);
190 const edges = new Map<string, FleetEdge>();
191 const environments = input.environments.filter(
192 (environment, index, all) =>
193 all.findIndex((other) => other.environmentId === environment.environmentId) === index,
194 );
195 for (const environment of environments) {
196 const id = fleetEnvironmentNodeId(environment.environmentId);
197 nodes.set(id, {
198 id,
199 kind: "environment",
200 environmentId: environment.environmentId,
201 label: environment.label,
202 machine: environment.machine,
203 phase: environment.phase,
204 enabled: environment.enabled,
205 routeCount: environment.routes.length,
206 outgoing: environment.outgoing.state,
207 outgoingError: environment.outgoing.state === "error" ? environment.outgoing.message : null,
208 linking: linking(environment),
209 mintable:
210 environment.phase === "connected" &&
211 environment.canWriteAccess &&
212 environment.hasLinkAddress,
213 canWriteAccess: environment.canWriteAccess,
214 hasLinkAddress: environment.hasLinkAddress,
215 });
216 for (const route of environment.routes) {
217 const edgeId = `route:${id}:${route.id}`;
218 if (edges.has(edgeId)) continue;
219 edges.set(edgeId, {
220 id: edgeId,
221 kind: "route",
222 from: FLEET_CLIENT_NODE_ID,
223 to: id,
224 routeId: route.id,
225 routeKind: route.kind,
226 ...(route.label === undefined ? {} : { routeLabel: route.label }),
227 state: routeState(environment, route.id),
228 });
229 }
230 }
231 for (const machine of input.connectMachines ?? []) {
232 const id = fleetEnvironmentNodeId(machine.environmentId);
233 if (nodes.has(id)) continue;
234 nodes.set(id, {
235 id,
236 kind: "connect",
237 environmentId: machine.environmentId,
238 label: machine.label,
239 machine: machine.machine,
240 availability: machine.availability,
241 });
242 edges.set(`route:${id}:offer`, {
243 id: `route:${id}:offer`,
244 kind: "route",
245 from: FLEET_CLIENT_NODE_ID,
246 to: id,
247 routeId: "offer",
248 routeKind: "relay",
249 state: "offered",
250 });
251 }
252 for (const environment of environments) {
253 if (environment.outgoing.state !== "loaded") continue;
254 const from = fleetEnvironmentNodeId(environment.environmentId);
255 for (const link of environment.outgoing.links) {
256 const to = fleetEnvironmentNodeId(link.environmentId);
257 const id = `link:${from}>${to}`;
258 if (to === from || edges.has(id)) continue;
259 if (!nodes.has(to)) {
260 nodes.set(to, {
261 id: to,
262 kind: "target",
263 environmentId: link.environmentId,
264 label: link.label,
265 address: link.urls[0] ?? null,
266 });
267 }
268 edges.set(id, {
269 id,
270 kind: "link",
271 from,
272 to,
273 sourceEnvironmentId: environment.environmentId,
274 link,
275 health: peerLinkHealth(link, input.now),
276 });
277 }
278 }
279 return { nodes: [...nodes.values()], edges: [...edges.values()] };
280 }
281
282 export const isLinkEdge = (edge: FleetEdge): edge is FleetLinkEdge => edge.kind === "link";
283 export const isRouteEdge = (edge: FleetEdge): edge is FleetRouteEdge => edge.kind === "route";
284
285 /** Two machines linked to each other at the same access: two links the map draws as one line. */
286 export interface FleetTwoWayLink {
287 /** The one the line is drawn and selected as: from the machine listed first. */
288 readonly forward: FleetLinkEdge;
289 readonly back: FleetLinkEdge;
290 }
291
292 /**
293 * Every two-way link, under the id of each of its two links. Links at different access levels
294 * say different things, so they stay two lines.
295 */
296 export function fleetTwoWayLinks(graph: FleetGraph): ReadonlyMap<string, FleetTwoWayLink> {
297 const links = new Map(graph.edges.filter(isLinkEdge).map((edge) => [edge.id, edge]));
298 const pairs = new Map<string, FleetTwoWayLink>();
299 for (const forward of links.values()) {
300 const back = links.get(`link:${forward.to}>${forward.from}`);
301 if (back === undefined || back.link.access !== forward.link.access || pairs.has(forward.id)) {
302 continue;
303 }
304 const pair = { forward, back };
305 pairs.set(forward.id, pair).set(back.id, pair);
306 }
307 return pairs;
308 }
309
310 /** The link whose line stands for `edge`: itself, or the other half of its two-way link. */
311 export const fleetDrawnLinkId = (pairs: ReadonlyMap<string, FleetTwoWayLink>, edgeId: string) =>
312 pairs.get(edgeId)?.forward.id ?? edgeId;
313
314 /** Worst first: expired, failing, not answering, expiring soon, fine. */
315 export const linkTroubleRank = (health: PeerLinkHealth) =>
316 health.kind === "expired"
317 ? 0
318 : health.kind === "failing"
319 ? 1
320 : health.kind === "unreachable"
321 ? 2
322 : health.expiresInDays === null
323 ? 4
324 : 3;
325
326 /** The health a two-way link's one label wears: that of the direction in more trouble. */
327 export const worseLinkHealth = (left: PeerLinkHealth, right: PeerLinkHealth) =>
328 linkTroubleRank(right) < linkTroubleRank(left) ? right : left;
329
330 /**
331 * Whether the map offers to link a one-way link's target back to its source: the same rule
332 * the link dialogs use, read from what the map knows of the two machines.
333 */
334 export function fleetLinkBackOffered(graph: FleetGraph, edge: FleetLinkEdge): boolean {
335 const source = graph.nodes.find((node) => node.id === edge.from);
336 const target = graph.nodes.find((node) => node.id === edge.to);
337 if (source?.kind !== "environment" || target?.kind !== "environment") return false;
338 const offer = linkBackOffer({
339 source: {
340 environmentId: source.environmentId,
341 connected: source.phase === "connected",
342 writable: source.canWriteAccess,
343 urls: source.hasLinkAddress ? [""] : [],
344 },
345 target: {
346 connected: target.phase === "connected",
347 offersLinks: target.linking !== "off",
348 writable: target.canWriteAccess,
349 links:
350 target.outgoing === "loaded"
351 ? graph.edges
352 .filter(isLinkEdge)
353 .filter((other) => other.from === target.id)
354 .map((other) => other.link)
355 : null,
356 },
357 });
358 return offer.kind === "offered";
359 }
360
361 /**
362 * The setup in two numbers. `links` is null when the total is not known: a list still loading,
363 * none read, or one failed among several. A failed or unread list is not "no links".
364 */
365 export function fleetSummary(graph: FleetGraph): {
366 readonly machines: number;
367 readonly links: number | null;
368 readonly loading: boolean;
369 } {
370 const connected = graph.nodes.filter(
371 (node) => node.kind === "environment" && node.phase === "connected",
372 ) as FleetEnvironmentNode[];
373 const loading = connected.some((node) => node.outgoing === "loading");
374 const known =
375 !loading &&
376 connected.some((node) => node.outgoing === "loaded") &&
377 !connected.some((node) => node.outgoing === "error");
378 return {
379 machines: graph.nodes.length - 1,
380 links: known ? graph.edges.filter(isLinkEdge).length : null,
381 loading,
382 };
383 }
384
385 /** Whether a link wants the user's attention: anything but reachable with time left. */
386 export const linkNeedsAttention = (health: PeerLinkHealth) =>
387 health.kind !== "reachable" || health.expiresInDays !== null;
388
389 const ACCESS_ORDER = AuthMcpClientAccess.literals;
390 /**
391 * How far apart two links enter one card while it has the room: an arrowhead plus the heaviest
392 * line. A card with more links than that fits keeps its size and they close up.
393 */
394 export const FLEET_LANE_PITCH = 12;
395 const labelOrder = new Intl.Collator("en", { numeric: true, sensitivity: "base" });
396
397 /** Why an environment with no links is folded away: what the client knows of it, never a probe. */
398 export type FleetFoldGroup = "offline" | "off" | "update" | "not-added";
399
400 /**
401 * Machines drawn as a single node, each still listed in the details. `targets` are machines
402 * known only through links, all linked from the same environments at the same access levels:
403 * a thousand VMs under two hosts cost one node and two lines. `environments` are ones this app
404 * is not connected to and that take part in no link, grouped by why.
405 */
406 export interface FleetStack {
407 readonly id: string;
408 readonly kind: "targets" | "environments";
409 /** The environments linking to every member, uppermost first. Empty for `environments`. */
410 readonly sources: ReadonlyArray<{
411 readonly sourceId: string;
412 readonly access: AuthMcpClientAccess;
413 }>;
414 readonly group: FleetFoldGroup | null;
415 /** In name order, so the first and last name the range. */
416 readonly memberIds: ReadonlyArray<string>;
417 readonly edgeIds: ReadonlyArray<string>;
418 /** Members every one of whose links answers. */
419 readonly reachable: number;
420 readonly firstLabel: string;
421 readonly lastLabel: string;
422 readonly expanded: boolean;
423 /** The members an open stack draws on the map; the rest are in the details only. */
424 readonly shownIds: ReadonlyArray<string>;
425 }
426
427 /** Below this many machines a group of link targets is clearer drawn one by one. */
428 const FLEET_STACK_MIN = 5;
429 /** Environments fold only once the client knows more than this many. */
430 export const FLEET_FOLD_ENVIRONMENTS_OVER = 12;
431 /** A folded group of environments needs at least this many; fewer stay as cards. */
432 const FLEET_FOLD_MIN = 3;
433 /** An open stack draws this many machines at most, then one card for the rest. */
434 export const FLEET_STACK_SHOWN_MAX = 24;
435
436 export const fleetMoreNodeId = (stackId: string) => `more:${stackId}`;
437
438 function foldGroup(node: FleetNode): FleetFoldGroup | null {
439 if (node.kind === "connect") return "not-added";
440 if (node.kind !== "environment") return null;
441 if (node.phase === "unsupported") return "update";
442 if (!node.enabled) return "off";
443 // One still dialling stays a card: it is about to change, and the user is watching it.
444 return node.phase === "offline" || node.phase === "error" || node.phase === "available"
445 ? "offline"
446 : null;
447 }
448
449 const FOLD_ORDER: ReadonlyArray<FleetFoldGroup> = ["offline", "off", "update", "not-added"];
450
451 export function fleetStacks(graph: FleetGraph, expanded: ReadonlySet<string>): FleetStack[] {
452 const byId = new Map(graph.nodes.map((node) => [node.id, node]));
453 const order = new Map(graph.nodes.map((node, index) => [node.id, index]));
454 const label = (id: string) => byId.get(id)?.label ?? "";
455 const byLabel = (left: string, right: string) =>
456 labelOrder.compare(label(left), label(right)) || (left < right ? -1 : 1);
457 const links = graph.edges.filter(isLinkEdge);
458 const incoming = new Map<string, FleetLinkEdge[]>();
459 for (const link of links) {
460 if (byId.get(link.to)?.kind !== "target") continue;
461 const into = incoming.get(link.to);
462 if (into === undefined) incoming.set(link.to, [link]);
463 else into.push(link);
464 }
465 // Keyed by the exact set of (host, access) links in, so every member is drawn by the same lines.
466 const groups = new Map<string, Array<{ id: string; links: FleetLinkEdge[] }>>();
467 for (const [id, unsorted] of incoming) {
468 const into = unsorted.toSorted((a, b) => order.get(a.from)! - order.get(b.from)!);
469 const key = `stack:${into.map((link) => `${link.from}:${link.link.access}`).join("|")}`;
470 const group = groups.get(key);
471 if (group === undefined) groups.set(key, [{ id, links: into }]);
472 else group.push({ id, links: into });
473 }
474 const make = (
475 id: string,
476 kind: FleetStack["kind"],
477 memberIds: ReadonlyArray<string>,
478 rest: Pick<FleetStack, "sources" | "group" | "edgeIds" | "reachable">,
479 ): FleetStack => ({
480 id,
481 kind,
482 ...rest,
483 memberIds,
484 firstLabel: label(memberIds[0]!),
485 lastLabel: label(memberIds.at(-1)!),
486 expanded: expanded.has(id),
487 shownIds:
488 memberIds.length > FLEET_STACK_SHOWN_MAX
489 ? memberIds.slice(0, FLEET_STACK_SHOWN_MAX)
490 : memberIds,
491 });
492 const stacks: FleetStack[] = [];
493 for (const [id, unsorted] of groups) {
494 if (unsorted.length < FLEET_STACK_MIN) continue;
495 const members = unsorted.toSorted((left, right) => byLabel(left.id, right.id));
496 stacks.push(
497 make(
498 id,
499 "targets",
500 members.map((member) => member.id),
501 {
502 sources: members[0]!.links.map((link) => ({
503 sourceId: link.from,
504 access: link.link.access,
505 })),
506 group: null,
507 edgeIds: members.flatMap((member) => member.links.map((link) => link.id)),
508 reachable: members.filter((member) =>
509 member.links.every((link) => link.health.kind === "reachable"),
510 ).length,
511 },
512 ),
513 );
514 }
515 const hosts = graph.nodes.filter(
516 (node) => node.kind === "environment" || node.kind === "connect",
517 );
518 if (hosts.length <= FLEET_FOLD_ENVIRONMENTS_OVER) return stacks;
519 const linked = new Set(links.flatMap((link) => [link.from, link.to]));
520 const routesOf = new Map<string, string[]>();
521 for (const edge of graph.edges) {
522 if (edge.kind !== "route") continue;
523 const routes = routesOf.get(edge.to);
524 if (routes === undefined) routesOf.set(edge.to, [edge.id]);
525 else routes.push(edge.id);
526 }
527 for (const group of FOLD_ORDER) {
528 const memberIds = hosts
529 .filter((host) => !linked.has(host.id) && foldGroup(host) === group)
530 .map((host) => host.id)
531 .toSorted(byLabel);
532 if (memberIds.length < FLEET_FOLD_MIN) continue;
533 stacks.push(
534 make(`fold:${group}`, "environments", memberIds, {
535 sources: [],
536 group,
537 edgeIds: memberIds.flatMap((id) => routesOf.get(id) ?? []),
538 reachable: 0,
539 }),
540 );
541 }
542 return stacks;
543 }
544
545 export type FleetFocus =
546 | { readonly kind: "node"; readonly id: string }
547 | { readonly kind: "edge"; readonly id: string }
548 | { readonly kind: "stack"; readonly id: string };
549
550 export interface FleetNeighborhood {
551 readonly nodes: ReadonlySet<string>;
552 readonly edges: ReadonlySet<string>;
553 }
554
555 /**
556 * What a node reaches and what reaches it, one hop only, plus how this client gets there. A link
557 * does not chain: A linked to B and B linked to C gives A's agents nothing on C, so following
558 * links further would lie.
559 */
560 export function fleetNeighborhood(
561 graph: FleetGraph,
562 stacks: ReadonlyArray<FleetStack>,
563 focus: FleetFocus,
564 ): FleetNeighborhood {
565 const nodes = new Set<string>();
566 const edges = new Set<string>();
567 const sources = new Set<string>();
568 const stack = focus.kind === "stack" ? stacks.find((entry) => entry.id === focus.id) : undefined;
569 const stackEdges = new Set(stack?.edgeIds);
570 // A two-way link is one line: either of its links brings the other with it.
571 const pair = focus.kind === "edge" ? fleetTwoWayLinks(graph).get(focus.id) : undefined;
572 for (const edge of graph.edges) {
573 const touches =
574 focus.kind === "stack"
575 ? stackEdges.has(edge.id)
576 : focus.kind === "edge"
577 ? edge.id === focus.id || edge.id === pair?.forward.id || edge.id === pair?.back.id
578 : edge.from === focus.id || edge.to === focus.id;
579 if (!touches) continue;
580 edges.add(edge.id);
581 nodes.add(edge.from).add(edge.to);
582 if (edge.kind === "link" && (focus.kind !== "node" || edge.to === focus.id)) {
583 sources.add(edge.from);
584 }
585 }
586 // The client reaches the focus through whichever environment holds the link to it.
587 for (const edge of graph.edges) {
588 if (edge.kind !== "route" || !sources.has(edge.to)) continue;
589 edges.add(edge.id);
590 nodes.add(edge.from);
591 }
592 if (focus.kind === "node" && graph.nodes.some((node) => node.id === focus.id)) {
593 nodes.add(focus.id);
594 }
595 return { nodes, edges };
596 }
597
598 /** What linking `sourceId` to `targetId` would take, or why the map does not offer it. */
599 export type FleetLinkOffer =
600 | {
601 readonly kind: "unavailable";
602 readonly reason:
603 | "not-an-environment"
604 | "same-machine"
605 | "source-disconnected"
606 | "source-off"
607 | "source-forbidden";
608 }
609 | {
610 readonly kind: "link";
611 readonly sourceEnvironmentId: EnvironmentId;
612 /**
613 * `code-less`: the client mints the pairing code on the target with its own session there.
614 * `pairing-code`: the user brings one from the target.
615 */
616 readonly path: "code-less" | "pairing-code";
617 /** The pair is already linked, so linking again renews it. */
618 readonly renews: boolean;
619 readonly target:
620 | { readonly kind: "machine"; readonly environmentId: EnvironmentId }
621 /** A machine the client has no entry for: only an address another host uses. */
622 | { readonly kind: "address"; readonly address: string | null };
623 };
624
625 export function fleetLinkOffer(
626 graph: FleetGraph,
627 sourceId: string,
628 targetId: string,
629 ): FleetLinkOffer {
630 const source = graph.nodes.find((node) => node.id === sourceId);
631 const target = graph.nodes.find((node) => node.id === targetId);
632 if (source?.kind !== "environment" || target === undefined || target.kind === "client") {
633 return { kind: "unavailable", reason: "not-an-environment" };
634 }
635 if (source.id === target.id) return { kind: "unavailable", reason: "same-machine" };
636 if (source.linking !== "ready") {
637 return { kind: "unavailable", reason: `source-${source.linking}` as const };
638 }
639 const renews = graph.edges.some(
640 (edge) =>
641 edge.kind === "link" &&
642 edge.from === source.id &&
643 edge.to === target.id &&
644 edge.health.kind !== "expired",
645 );
646 const base = { kind: "link", sourceEnvironmentId: source.environmentId, renews } as const;
647 if (target.kind === "target") {
648 return {
649 ...base,
650 path: "pairing-code",
651 target: { kind: "address", address: target.address },
652 };
653 }
654 return {
655 ...base,
656 path: target.kind === "environment" && target.mintable ? "code-less" : "pairing-code",
657 target: { kind: "machine", environmentId: target.environmentId },
658 };
659 }
660
661 /** Some of a stack's linked machines do not answer: its card grows a line to say how many do. */
662 export const fleetStackPartial = (stack: FleetStack) =>
663 stack.kind === "targets" && stack.reachable < stack.memberIds.length;
664
665 /** Changes exactly when the layout would: membership, labels, routes, wiring and open stacks. */
666 export function fleetShapeKey(graph: FleetGraph, stacks: ReadonlyArray<FleetStack>): string {
667 return [
668 ...graph.nodes.map((node) => `${node.kind}\u0000${node.id}\u0000${node.label}`),
669 ...graph.edges.map((edge) =>
670 edge.kind === "link" ? `${edge.id}\u0000${edge.link.access}` : edge.id,
671 ),
672 // Which environments fold follows their state, which nothing above carries.
673 ...stacks.map(
674 (stack) =>
675 `${stack.id}\u0000${stack.expanded}\u0000${fleetStackPartial(stack)}\u0000${stack.kind === "environments" ? stack.memberIds.join() : ""}`,
676 ),
677 ].join("\n");
678 }
679
680 export interface FleetRect {
681 readonly x: number;
682 readonly y: number;
683 readonly width: number;
684 readonly height: number;
685 }
686
687 export interface FleetPoint {
688 readonly x: number;
689 readonly y: number;
690 }
691
692 export interface FleetRouteGeometry {
693 readonly d: string;
694 /** Where the route's kind is named, on the wire just before the environment. */
695 readonly pill: FleetRect;
696 }
697
698 /**
699 * Room for a link's access in words. `side` is the way it grows from the lane it sits on.
700 * `onDemand` names one with no clear place: shown only while its link is in focus.
701 */
702 export type FleetLinkBadge = FleetRect & { readonly side: 1 | -1; readonly onDemand: boolean };
703
704 export interface FleetArrow {
705 readonly x: number;
706 readonly y: number;
707 readonly dir: 1 | -1;
708 }
709
710 export interface FleetLinkGeometry {
711 readonly d: string;
712 /** Arrowhead tip and the horizontal direction it points. */
713 readonly arrow: FleetArrow;
714 /**
715 * Set for a two-way link, which is one line with an arrowhead at each end. `arrow` and
716 * `forward` are the half leading into the machine the drawn link reaches; `backArrow` and
717 * `back` the half leading into the one it leaves, which is the other link's.
718 */
719 readonly twoWay: {
720 readonly backArrow: FleetArrow;
721 readonly forward: string;
722 readonly back: string;
723 } | null;
724 /** Where a link between two environments names its access; a target's card shows its own. */
725 readonly badge: FleetLinkBadge | null;
726 }
727
728 /** A line a stack draws for all its machines: one environment's links, or the client's routes. */
729 export interface FleetStackLine {
730 readonly sourceId: string | null;
731 readonly access: AuthMcpClientAccess | null;
732 readonly d: string;
733 readonly arrow: FleetPoint | null;
734 }
735
736 export interface FleetStackGeometry {
737 /** The whole footprint: the sheets of a closed stack, or an open one's card and its tray. */
738 readonly rect: FleetRect;
739 /** The stack's card. Opening the stack leaves it where it is, and the tray grows out below. */
740 readonly face: FleetRect;
741 readonly lines: ReadonlyArray<FleetStackLine>;
742 /** The panel an open stack draws its machines in, below its card. */
743 readonly tray: FleetRect | null;
744 /** In an open stack, the card standing for the machines it does not draw. */
745 readonly more: FleetRect | null;
746 }
747
748 export type FleetColumn = "client" | "environments" | "targets";
749
750 export interface FleetLayout {
751 /** Every machine drawn on its own. Members of a closed stack are not here. */
752 readonly nodes: ReadonlyMap<string, FleetRect>;
753 readonly stacks: ReadonlyMap<string, FleetStackGeometry>;
754 readonly routes: ReadonlyMap<string, FleetRouteGeometry>;
755 /** Links drawn one by one. A stack's links are drawn by the stack. */
756 readonly links: ReadonlyMap<string, FleetLinkGeometry>;
757 /** Where an environment's links leave it and its link handle sits, on its right edge. */
758 readonly handles: ReadonlyMap<string, FleetPoint>;
759 readonly columns: ReadonlyArray<{ readonly id: FleetColumn; readonly x: number }>;
760 readonly width: number;
761 readonly height: number;
762 }
763
764 const HEADER = 28;
765 const CLIENT = { height: 44 };
766 const PILL = { height: 18 };
767 /** How far apart route names sit in their column beside a card. */
768 export const FLEET_ROUTE_PITCH = 22;
769 /** How far that column may reach into the gap above and below its card's place. */
770 const PILL_OVERHANG = 9;
771 /** `nameLine` is the most characters of a name the narrowest card sets on one line. */
772 const CARD = { height: 56, twoLines: 68, nameLine: 13 };
773 /** Routes enter a card as one bundle: this far apart, and never wider than `spread`. */
774 const ROUTE_ENTRY = { pitch: 4, spread: 10 };
775 const OFFER = { height: 44 };
776 const TARGET = { height: 44 };
777 /** `partial` is the room a closed stack adds to say how many of its machines answer. */
778 const STACK = { height: 50, partial: 20, lift: 8 };
779
780 /**
781 * Every horizontal measure the map can give up or take. Heights never change with the width, so
782 * what is drawn where, lane by lane, is the same at every width and only the columns move.
783 */
784 interface FleetMetrics {
785 /** The card for this app, where every route starts. */
786 readonly app: number;
787 /** The run from it to the route names. */
788 readonly wire: number;
789 readonly pill: number;
790 /** The run in which a machine's routes close up from their names to its card. */
791 readonly pillGap: number;
792 readonly card: number;
793 readonly target: number;
794 /** The run from the environments, past their lanes, to the machines they link to. */
795 readonly linkRun: number;
796 readonly laneFirst: number;
797 readonly betweenFirst: number;
798 readonly betweenLast: number;
799 }
800
801 const REGULAR: FleetMetrics = {
802 app: 136,
803 wire: 72,
804 pill: 82,
805 pillGap: 20,
806 card: 164,
807 target: 188,
808 linkRun: 92,
809 laneFirst: 24,
810 betweenFirst: 16,
811 betweenLast: 6,
812 };
813 /** The least each measure can be with its text still whole: a narrow settings column. */
814 const COMPACT: FleetMetrics = {
815 app: 124,
816 wire: 28,
817 pill: 72,
818 pillGap: 14,
819 card: 148,
820 target: 146,
821 linkRun: 36,
822 laneFirst: 18,
823 betweenFirst: 14,
824 betweenLast: 4,
825 };
826 /** Past this the map is enlarged instead: longer wires would only pull the columns apart. */
827 const ROOMY: FleetMetrics = {
828 app: 148,
829 wire: 112,
830 pill: 88,
831 pillGap: 26,
832 card: 180,
833 target: 220,
834 linkRun: 132,
835 laneFirst: 24,
836 betweenFirst: 16,
837 betweenLast: 6,
838 };
839
840 const mixMetrics = (from: FleetMetrics, to: FleetMetrics, t: number): FleetMetrics => {
841 const at = (key: keyof FleetMetrics) => Math.floor(from[key] + (to[key] - from[key]) * t);
842 return {
843 app: at("app"),
844 wire: at("wire"),
845 pill: at("pill"),
846 pillGap: at("pillGap"),
847 card: at("card"),
848 target: at("target"),
849 linkRun: at("linkRun"),
850 laneFirst: at("laneFirst"),
851 betweenFirst: at("betweenFirst"),
852 betweenLast: at("betweenLast"),
853 };
854 };
855 const CHIP = { width: 124, height: 26 };
856 const CHIP_GAP = 6;
857 const FRAME_PAD = 8;
858 /** Between a stack's card and the tray it opens. */
859 const TRAY_GAP = 4;
860 /** Narrower than this a machine's name no longer reads, so a tray gives up a column instead. */
861 const CHIP_MIN_WIDTH = 60;
862 const GROUP_GAP = 28;
863 const BAY_GAP = 12;
864 const LANE_STEP = 14;
865 const LANE_CLEARANCE = 10;
866 const ARROW_LENGTH = 6;
867 /** The least run a link keeps from the last lane to a machine: its turn and its arrowhead. */
868 const LINK_RUN_MIN = 20;
869 /** How far apart two hosts' links enter one machine, so each keeps its own last stretch. */
870 const ENTRY_PITCH = 14;
871 /** The channel left of the cards that links between environments keep to themselves. */
872 const BETWEEN = { step: 14 };
873 /**
874 * Where those links meet a card's left edge: past its routes, the outermost lane innermost,
875 * `margin` short of the corner. The card never grows for them: the pitch gives way instead.
876 */
877 const LINK_PORT = { first: 10, pitch: FLEET_LANE_PITCH, margin: 4 };
878 const CORNER = 8;
879 const BADGE = { width: 120, height: 20, overhang: 5, gap: 4 };
880
881 /** Horizontal, a vertical run at `viaX`, then horizontal again, with rounded turns. */
882 function elbowPath(x0: number, y0: number, viaX: number, x1: number, y1: number): string {
883 const dy = y1 - y0;
884 if (Math.abs(dy) < 1) return `M${x0} ${y0}H${x1}`;
885 const r = Math.min(CORNER, Math.abs(dy) / 2, Math.abs(viaX - x0), Math.abs(x1 - viaX));
886 const sy = Math.sign(dy);
887 const inX = Math.sign(viaX - x0);
888 const outX = Math.sign(x1 - viaX);
889 return [
890 `M${x0} ${y0}`,
891 `H${viaX - inX * r}`,
892 `Q${viaX} ${y0} ${viaX} ${y0 + sy * r}`,
893 `V${y1 - sy * r}`,
894 `Q${viaX} ${y1} ${viaX + outX * r} ${y1}`,
895 `H${x1}`,
896 ].join("");
897 }
898
899 /** `elbowPath` cut halfway along its vertical run: the half it starts with, then the other. */
900 function elbowHalves(x0: number, y0: number, viaX: number, x1: number, y1: number) {
901 const dy = y1 - y0;
902 const mid = (y0 + y1) / 2;
903 const r = Math.min(CORNER, Math.abs(dy) / 2, Math.abs(viaX - x0), Math.abs(x1 - viaX));
904 const sy = Math.sign(dy);
905 const inX = Math.sign(viaX - x0);
906 const outX = Math.sign(x1 - viaX);
907 return [
908 `M${x0} ${y0}H${viaX - inX * r}Q${viaX} ${y0} ${viaX} ${y0 + sy * r}V${mid}`,
909 `M${viaX} ${mid}V${y1 - sy * r}Q${viaX} ${y1} ${viaX + outX * r} ${y1}H${x1}`,
910 ] as const;
911 }
912
913 /** Straight to `fanX`, across any lanes so they only ever meet it square, then a curve. */
914 const sCurve = (x0: number, y0: number, x1: number, y1: number, fanX = x0) => {
915 // A short run bends within itself, so it still arrives level instead of doubling back.
916 const reach = Math.max(Math.min(24, (x1 - fanX) * 0.6), (x1 - fanX) / 2);
917 const lead = fanX > x0 ? `H${fanX}` : "";
918 return `M${x0} ${y0}${lead}C${fanX + reach} ${y0} ${x1 - reach} ${y1} ${x1} ${y1}`;
919 };
920
921 const frameColumns = (count: number) => Math.max(2, Math.min(4, Math.ceil(Math.sqrt(count / 2.2))));
922
923 /** What an open stack draws: its shown machines, and one more card when some are left out. */
924 const frameCells = (stack: FleetStack) =>
925 stack.shownIds.length + Number(stack.memberIds.length > stack.shownIds.length);
926
927 const trayWidth = (columns: number) => FRAME_PAD * 2 + columns * (CHIP.width + CHIP_GAP) - CHIP_GAP;
928
929 /** What an open stack adds below its card. */
930 const trayHeight = (stack: FleetStack, columns: number) =>
931 TRAY_GAP +
932 FRAME_PAD * 2 +
933 Math.ceil(frameCells(stack) / columns) * (CHIP.height + CHIP_GAP) -
934 CHIP_GAP;
935
936 /**
937 * What an open stack of link targets has to stay within, both read off the map with every stack
938 * closed: the width its tray can take without the view shrinking to show it, and where its
939 * column stood, so opening one neither rescales the map nor moves a column.
940 */
941 interface FleetTrayRoom {
942 readonly width: number;
943 readonly bayX: number | null;
944 }
945
946 const closedStacks = (stacks: ReadonlyArray<FleetStack>) =>
947 stacks.some((stack) => stack.expanded)
948 ? stacks.map((stack) => (stack.expanded ? { ...stack, expanded: false } : stack))
949 : stacks;
950
951 /** One line into a machine or a stack, from the environment holding the link. */
952 interface BayEntry {
953 readonly key: string;
954 readonly from: string;
955 }
956
957 type BayItem =
958 | {
959 readonly kind: "target";
960 readonly targetId: string;
961 readonly label: string;
962 readonly access: AuthMcpClientAccess;
963 readonly entries: ReadonlyArray<BayEntry>;
964 }
965 | {
966 readonly kind: "stack";
967 readonly stack: FleetStack;
968 readonly label: string;
969 readonly access: AuthMcpClientAccess;
970 readonly entries: ReadonlyArray<BayEntry>;
971 };
972
973 type ColumnEntry =
974 | { readonly kind: "host"; readonly id: string; readonly host: FleetNode }
975 | { readonly kind: "fold"; readonly id: string; readonly stack: FleetStack };
976
977 interface FleetRow {
978 readonly entries: ColumnEntry[];
979 readonly items: ReadonlyArray<BayItem>;
980 }
981
982 /** One host's vertical run to a row of shared machines, kept to itself for its whole span. */
983 interface FleetLane {
984 readonly id: string;
985 readonly from: number;
986 readonly to: number;
987 /** Where its links turn off towards their machines. */
988 readonly branches: ReadonlyArray<number>;
989 index: number;
990 }
991
992 const stackLineKey = (stackId: string, sourceId: string) => `${stackId}<${sourceId}`;
993
994 const pushTo = <K, V>(into: Map<K, V[]>, key: K, value: V) => {
995 const list = into.get(key);
996 if (list === undefined) into.set(key, [value]);
997 else list.push(value);
998 };
999
1000 /**
1001 * The map at the width it is given. It gives up gutters, wire runs and card width before the fit
1002 * has to shrink it, and takes more of each on a wide canvas, up to a point. With no width it is
1003 * laid out at its regular measures.
1004 */
1005 export function layoutFleetGraph(
1006 graph: FleetGraph,
1007 stacks: ReadonlyArray<FleetStack> = [],
1008 canvasWidth?: number,
1009 ): FleetLayout {
1010 // The measures follow the map with every stack closed, so opening one moves no column.
1011 const closed = closedStacks(stacks);
1012 const { metrics, layout } = fitFleetMetrics(graph, closed, canvasWidth);
1013 if (closed === stacks) return layout;
1014 if (canvasWidth === undefined) {
1015 const bayX = layout.columns.find((column) => column.id === "targets")?.x ?? null;
1016 return layoutFleetGraphAt(graph, stacks, metrics, { width: Infinity, bayX });
1017 }
1018 const bayX = layout.columns.find((column) => column.id === "targets")?.x ?? null;
1019 // How much of the map the closed fit shows across: the room a tray has at that same scale.
1020 const room = canvasWidth - fleetFitPadding(canvasWidth) * 2;
1021 const shown = room / Math.min(FLEET_FIT_MAX_SCALE, room / layout.width);
1022 return layoutFleetGraphAt(graph, stacks, metrics, { width: shown - (bayX ?? 0), bayX });
1023 }
1024
1025 function fitFleetMetrics(
1026 graph: FleetGraph,
1027 stacks: ReadonlyArray<FleetStack>,
1028 canvasWidth: number | undefined,
1029 ): { readonly metrics: FleetMetrics; readonly layout: FleetLayout } {
1030 const regular = layoutFleetGraphAt(graph, stacks, REGULAR);
1031 if (canvasWidth === undefined) return { metrics: REGULAR, layout: regular };
1032 const room = canvasWidth - fleetFitPadding(canvasWidth) * 2;
1033 const narrow = room < regular.width;
1034 // Narrower than regular, the map fits at full size. Wider, it is enlarged first.
1035 const wanted = narrow ? room : room / FLEET_FIT_MAX_SCALE;
1036 if (!narrow && wanted <= regular.width) return { metrics: REGULAR, layout: regular };
1037 const limit = narrow ? COMPACT : ROOMY;
1038 const end = layoutFleetGraphAt(graph, stacks, limit);
1039 if (narrow ? end.width >= wanted : end.width <= wanted) return { metrics: limit, layout: end };
1040 // Width is a maximum of sums of the measures, so it never exceeds this straight-line estimate.
1041 const t = (wanted - regular.width) / (end.width - regular.width);
1042 const metrics = mixMetrics(REGULAR, limit, t);
1043 return { metrics, layout: layoutFleetGraphAt(graph, stacks, metrics) };
1044 }
1045
1046 /**
1047 * Links to machines seen only through a link run right of the environments, links between two
1048 * environments left of them, each on its own lane with its own entry. A stack takes one place
1049 * whatever it holds, so the cost follows what is drawn. Deterministic.
1050 */
1051 function layoutFleetGraphAt(
1052 graph: FleetGraph,
1053 stacks: ReadonlyArray<FleetStack>,
1054 metrics: FleetMetrics,
1055 room: FleetTrayRoom = { width: Infinity, bayX: null },
1056 ): FleetLayout {
1057 const CLIENT_SIZE = { width: metrics.app, height: CLIENT.height };
1058 const PILL_SIZE = { width: metrics.pill, height: PILL.height };
1059 const nodes = new Map<string, FleetRect>();
1060 const stackGeometry = new Map<string, FleetStackGeometry>();
1061 const routes = new Map<string, FleetRouteGeometry>();
1062 const linkGeometry = new Map<string, FleetLinkGeometry>();
1063 const handles = new Map<string, FleetPoint>();
1064 const links = graph.edges.filter(isLinkEdge);
1065 const byId = new Map(graph.nodes.map((node) => [node.id, node]));
1066 const folds = stacks.filter((stack) => stack.kind === "environments");
1067 const folded = new Set(folds.flatMap((stack) => stack.memberIds));
1068 const hosts = graph.nodes.filter(
1069 (node) => (node.kind === "environment" || node.kind === "connect") && !folded.has(node.id),
1070 );
1071 const hostIndex = new Map(hosts.map((host, index) => [host.id, index]));
1072 const indexOf = (hostId: string) => hostIndex.get(hostId) ?? 0;
1073 const routesOf = new Map<string, FleetRouteEdge[]>();
1074 for (const edge of graph.edges) if (edge.kind === "route") pushTo(routesOf, edge.to, edge);
1075 const accessRank = (access: AuthMcpClientAccess) => -ACCESS_ORDER.indexOf(access);
1076 const labelOf = (id: string) => byId.get(id)?.label ?? "";
1077
1078 const stacked = new Set(stacks.flatMap((stack) => stack.edgeIds));
1079 const incomingOf = new Map<string, FleetLinkEdge[]>();
1080 for (const link of links) {
1081 if (byId.get(link.to)?.kind !== "target" || stacked.has(link.id)) continue;
1082 pushTo(incomingOf, link.to, link);
1083 }
1084 const items: BayItem[] = [];
1085 for (const stack of stacks) {
1086 if (stack.kind !== "targets") continue;
1087 items.push({
1088 kind: "stack",
1089 stack,
1090 label: stack.firstLabel,
1091 access: stack.sources[0]!.access,
1092 entries: stack.sources.map((source) => ({
1093 key: stackLineKey(stack.id, source.sourceId),
1094 from: source.sourceId,
1095 })),
1096 });
1097 }
1098 for (const [targetId, unsorted] of incomingOf) {
1099 // Top to bottom in the order of the hosts, so the upper line is the upper host's.
1100 const incoming = unsorted.toSorted((left, right) => indexOf(left.from) - indexOf(right.from));
1101 items.push({
1102 kind: "target",
1103 targetId,
1104 label: labelOf(targetId),
1105 access: incoming[0]!.link.access,
1106 entries: incoming.map((link) => ({ key: link.id, from: link.from })),
1107 });
1108 }
1109 const itemId = (item: BayItem) => (item.kind === "stack" ? item.stack.id : item.targetId);
1110 const byName = (left: BayItem, right: BayItem) =>
1111 labelOrder.compare(left.label, right.label) || (itemId(left) < itemId(right) ? -1 : 1);
1112 const bayOf = new Map<string, BayItem[]>();
1113 const bandOf = new Map<string, BayItem[]>();
1114 for (const item of items
1115 .filter((entry) => entry.entries.length === 1)
1116 .toSorted(
1117 (left, right) =>
1118 Number(right.kind === "stack") - Number(left.kind === "stack") ||
1119 accessRank(left.access) - accessRank(right.access) ||
1120 byName(left, right),
1121 )) {
1122 pushTo(bayOf, item.entries[0]!.from, item);
1123 }
1124 // Below the middle host of those linking to it: the shortest total reach, with ties going up.
1125 const meanSource = (item: BayItem) =>
1126 item.entries.reduce((sum, entry) => sum + indexOf(entry.from), 0) / item.entries.length;
1127 for (const item of items
1128 .filter((entry) => entry.entries.length > 1)
1129 .toSorted((left, right) => meanSource(left) - meanSource(right) || byName(left, right))) {
1130 pushTo(bandOf, item.entries[Math.floor((item.entries.length - 1) / 2)]!.from, item);
1131 }
1132
1133 // A machine with no links rides beside a shared row instead of pushing the hosts further apart.
1134 const linked = new Set(links.flatMap((link) => [link.from, link.to]));
1135 const rows: FleetRow[] = [];
1136 let shared: FleetRow | null = null;
1137 for (const host of hosts) {
1138 const entry: ColumnEntry = { kind: "host", id: host.id, host };
1139 if (shared !== null && !linked.has(host.id)) {
1140 shared.entries.push(entry);
1141 continue;
1142 }
1143 rows.push({ entries: [entry], items: bayOf.get(host.id) ?? [] });
1144 const band = bandOf.get(host.id);
1145 shared = band === undefined ? null : { entries: [], items: band };
1146 if (shared !== null) rows.push(shared);
1147 }
1148 for (const stack of folds) {
1149 const entry: ColumnEntry = { kind: "fold", id: stack.id, stack };
1150 if (shared !== null) shared.entries.push(entry);
1151 else rows.push({ entries: [entry], items: [] });
1152 }
1153
1154 // Links between environments: shorter ones take the lanes nearer the cards, and two share a
1155 // lane when no host lies between both pairs, so a chain of links reads as one line.
1156 const reach = (link: FleetLinkEdge) => Math.abs(indexOf(link.to) - indexOf(link.from));
1157 const low = (link: FleetLinkEdge) => Math.min(indexOf(link.from), indexOf(link.to));
1158 const high = (link: FleetLinkEdge) => Math.max(indexOf(link.from), indexOf(link.to));
1159 // A two-way link is drawn once, as the link from the machine listed first.
1160 const pairs = fleetTwoWayLinks(graph);
1161 const twoWay = (link: FleetLinkEdge) => pairs.has(link.id);
1162 const between = links
1163 .filter(
1164 (link) =>
1165 hostIndex.has(link.from) &&
1166 hostIndex.has(link.to) &&
1167 fleetDrawnLinkId(pairs, link.id) === link.id,
1168 )
1169 .toSorted((left, right) => reach(left) - reach(right) || (left.id < right.id ? -1 : 1));
1170 const betweenLanes: FleetLinkEdge[][] = [];
1171 const betweenLane = new Map<string, number>();
1172 for (const link of between) {
1173 let index = 0;
1174 while (
1175 betweenLanes[index]?.some(
1176 (other) => Math.max(low(other), low(link)) < Math.min(high(other), high(link)),
1177 )
1178 ) {
1179 index += 1;
1180 }
1181 betweenLane.set(link.id, index);
1182 (betweenLanes[index] ??= []).push(link);
1183 }
1184 // Such a link meets a card's left edge above its routes when the other machine is above,
1185 // below them when it is below. Each arrowhead has its own port, the outer lane's nearer the
1186 // middle so two never cross. Links out on a side share one port; a two-way link arrives at
1187 // both its cards.
1188 const leaves = new Set<string>();
1189 const arrivalsOf = new Map<string, FleetLinkEdge[]>();
1190 for (const link of between) {
1191 const down = Math.sign(indexOf(link.to) - indexOf(link.from));
1192 if (twoWay(link)) pushTo(arrivalsOf, `${link.from}:${down}`, link);
1193 else leaves.add(`${link.from}:${down}`);
1194 pushTo(arrivalsOf, `${link.to}:${-down}`, link);
1195 }
1196 for (const ports of arrivalsOf.values()) {
1197 ports.sort((left, right) => betweenLane.get(right.id)! - betweenLane.get(left.id)!);
1198 }
1199 const routesInto = (hostId: string) => routesOf.get(hostId)?.length ?? 0;
1200 // A card's size follows its name alone, so what attaches to it never stretches it. The name
1201 // is measured in characters against the narrowest card, so no height changes with the width.
1202 const cardHeight = (host: FleetNode) =>
1203 host.kind === "connect"
1204 ? OFFER.height
1205 : host.label.length > CARD.nameLine
1206 ? CARD.twoLines
1207 : CARD.height;
1208 const routeEntryPitch = (hostId: string) =>
1209 routesInto(hostId) < 2
1210 ? 0
1211 : Math.min(ROUTE_ENTRY.pitch, ROUTE_ENTRY.spread / (routesInto(hostId) - 1));
1212 const routesExtent = (hostId: string) =>
1213 (Math.max(1, routesInto(hostId)) - 1) * routeEntryPitch(hostId) * 0.5;
1214 const linkPortPitch = (host: FleetNode, side: number) => {
1215 const key = `${host.id}:${side}`;
1216 const ports = Number(leaves.has(key)) + (arrivalsOf.get(key)?.length ?? 0);
1217 const room = cardHeight(host) / 2 - LINK_PORT.margin - routesExtent(host.id) - LINK_PORT.first;
1218 return ports < 2 ? 0 : Math.min(LINK_PORT.pitch, room / (ports - 1));
1219 };
1220 const pillsHeight = (hostId: string) =>
1221 (Math.max(1, routesInto(hostId)) - 1) * FLEET_ROUTE_PITCH + PILL.height;
1222 const foldFace = { width: metrics.card - STACK.lift, height: STACK.height };
1223 const closedWidth = metrics.target + STACK.lift;
1224 /**
1225 * A group of environments opens one machine wide, under its card. Link targets take the
1226 * columns there is room for, and with no room to spare two narrow ones under the closed stack.
1227 */
1228 const trayShape = (stack: FleetStack) => {
1229 if (stack.kind === "environments") return { columns: 1, width: metrics.card };
1230 const wanted = frameColumns(frameCells(stack));
1231 const fitting = Math.floor((room.width - FRAME_PAD * 2 + CHIP_GAP) / (CHIP.width + CHIP_GAP));
1232 if (fitting >= 2) {
1233 const columns = Math.min(wanted, fitting);
1234 return { columns, width: Math.max(closedWidth, trayWidth(columns)) };
1235 }
1236 const width = Math.max(closedWidth, Math.min(room.width, trayWidth(2)));
1237 return {
1238 columns: (width - FRAME_PAD * 2 - CHIP_GAP) / 2 < CHIP_MIN_WIDTH ? 1 : 2,
1239 width,
1240 };
1241 };
1242 /** `open` false is the place an entry takes with its stack closed, which is where it starts. */
1243 const entryHeight = (entry: ColumnEntry, open: boolean) =>
1244 entry.kind === "host"
1245 ? // The place a card takes in the column: its own height, or what its route names need.
1246 Math.max(cardHeight(entry.host), pillsHeight(entry.id) - PILL_OVERHANG * 2)
1247 : STACK.height +
1248 STACK.lift +
1249 (open && entry.stack.expanded
1250 ? trayHeight(entry.stack, trayShape(entry.stack).columns)
1251 : 0);
1252 /** Tall enough that each line in keeps its own entry. */
1253 const faceHeight = (item: BayItem, least: number) =>
1254 Math.max(least, 20 + (item.entries.length - 1) * ENTRY_PITCH);
1255 const itemSize = (item: BayItem, open: boolean) => {
1256 if (item.kind === "target") {
1257 return { width: metrics.target, height: faceHeight(item, TARGET.height) };
1258 }
1259 const closed = {
1260 width: closedWidth,
1261 height:
1262 faceHeight(item, STACK.height + (fleetStackPartial(item.stack) ? STACK.partial : 0)) +
1263 STACK.lift,
1264 };
1265 if (!open || !item.stack.expanded) return closed;
1266 const shape = trayShape(item.stack);
1267 return {
1268 width: shape.width,
1269 height: closed.height + trayHeight(item.stack, shape.columns),
1270 };
1271 };
1272 /** Places an open stack's machines in the tray below its card, and returns the card for the rest. */
1273 const fillTray = (stack: FleetStack, face: FleetRect): FleetRect | null => {
1274 const { columns, width } = trayShape(stack);
1275 const chipWidth = (width - FRAME_PAD * 2 - (columns - 1) * CHIP_GAP) / columns;
1276 const cell = (index: number): FleetRect => ({
1277 x: face.x + FRAME_PAD + (index % columns) * (chipWidth + CHIP_GAP),
1278 y:
1279 face.y +
1280 face.height +
1281 TRAY_GAP +
1282 FRAME_PAD +
1283 Math.floor(index / columns) * (CHIP.height + CHIP_GAP),
1284 width: chipWidth,
1285 height: CHIP.height,
1286 });
1287 stack.shownIds.forEach((memberId, index) => nodes.set(memberId, cell(index)));
1288 return stack.memberIds.length > stack.shownIds.length ? cell(stack.shownIds.length) : null;
1289 };
1290 /** An open stack's footprint, its card and tray, and the tray alone. */
1291 const openRects = (stack: FleetStack, face: FleetRect) => {
1292 const { columns, width } = trayShape(stack);
1293 const height = trayHeight(stack, columns);
1294 return {
1295 rect: { x: face.x, y: face.y, width, height: face.height + height },
1296 tray: {
1297 x: face.x,
1298 y: face.y + face.height + TRAY_GAP,
1299 width,
1300 height: height - TRAY_GAP,
1301 },
1302 };
1303 };
1304
1305 const pillX = metrics.app + metrics.wire;
1306 const cardX =
1307 pillX +
1308 metrics.pill +
1309 metrics.pillGap +
1310 (betweenLanes.length === 0
1311 ? 0
1312 : metrics.betweenLast + (betweenLanes.length - 1) * BETWEEN.step + metrics.betweenFirst);
1313 const cardRight = cardX + metrics.card;
1314
1315 // Heights first: which lanes the channel needs, and so how wide it is, follows from them.
1316 // Rows are spaced as if every stack were closed, so an open one grows down from where its
1317 // card was and moves only what its tray would otherwise cover.
1318 const placed: Array<{
1319 readonly item: BayItem;
1320 readonly y: number;
1321 readonly size: { readonly width: number; readonly height: number };
1322 /** The item's height with its stack closed: where its card ends. */
1323 readonly closedHeight: number;
1324 }> = [];
1325 const column: Array<{ readonly entry: ColumnEntry; readonly center: number }> = [];
1326 /** Where each entry's middle is with every stack closed: this app's card is set by these. */
1327 const restCenters: number[] = [];
1328 /** Where a card's routes arrive and its links leave: its middle. */
1329 const anchors = new Map<string, number>();
1330 let y = HEADER;
1331 let cardFloor = -Infinity;
1332 let bayFloor = -Infinity;
1333 for (const row of rows) {
1334 const heights = row.entries.map((entry) => entryHeight(entry, false));
1335 const cardsHeight = heights.reduce((sum, height) => sum + height + GROUP_GAP, -GROUP_GAP);
1336 const sizes = row.items.map((item) => itemSize(item, false));
1337 const bayHeight = sizes.reduce((sum, size) => sum + size.height + BAY_GAP, -BAY_GAP);
1338 const rowHeight = Math.max(cardsHeight, bayHeight);
1339 let restY = y + (rowHeight - cardsHeight) / 2;
1340 row.entries.forEach((entry, index) => {
1341 const rest = heights[index]!;
1342 const cardY = Math.max(restY, cardFloor);
1343 if (entry.kind === "host") {
1344 const anchor = cardY + rest / 2;
1345 const own = cardHeight(entry.host);
1346 nodes.set(entry.id, { x: cardX, y: anchor - own / 2, width: metrics.card, height: own });
1347 anchors.set(entry.id, anchor);
1348 if (entry.host.kind === "environment") handles.set(entry.id, { x: cardRight, y: anchor });
1349 column.push({ entry, center: anchor });
1350 restCenters.push(restY + rest / 2);
1351 } else {
1352 const face = { x: cardX, y: cardY + STACK.lift, ...foldFace };
1353 stackGeometry.set(entry.id, {
1354 ...(entry.stack.expanded
1355 ? openRects(entry.stack, face)
1356 : { rect: { x: cardX, y: cardY, width: metrics.card, height: rest }, tray: null }),
1357 face,
1358 lines: [],
1359 more: entry.stack.expanded ? fillTray(entry.stack, face) : null,
1360 });
1361 column.push({ entry, center: face.y + face.height / 2 });
1362 restCenters.push(restY + STACK.lift + face.height / 2);
1363 }
1364 cardFloor = cardY + entryHeight(entry, true) + GROUP_GAP;
1365 restY += rest + GROUP_GAP;
1366 });
1367 let restItemY = y + (rowHeight - bayHeight) / 2;
1368 row.items.forEach((item, index) => {
1369 const itemY = Math.max(restItemY, bayFloor);
1370 const size = itemSize(item, true);
1371 placed.push({ item, y: itemY, size, closedHeight: sizes[index]!.height });
1372 bayFloor = itemY + size.height + BAY_GAP;
1373 restItemY += sizes[index]!.height + BAY_GAP;
1374 });
1375 y += rowHeight + GROUP_GAP;
1376 }
1377 let height = Math.max(
1378 HEADER + CLIENT.height,
1379 y - GROUP_GAP,
1380 cardFloor - GROUP_GAP,
1381 bayFloor - BAY_GAP,
1382 );
1383
1384 const centerOf = (id: string) => anchors.get(id)!;
1385
1386 /** What a line into the item points at: the machine, or the stack's card, open or closed. */
1387 const faceOf = (item: BayItem, itemY: number, closedHeight: number) =>
1388 item.kind === "target"
1389 ? { top: itemY, height: closedHeight }
1390 : { top: itemY + STACK.lift, height: closedHeight - STACK.lift };
1391 /** Where each line into the item arrives. */
1392 const entryY = new Map<string, number>();
1393 for (const { item, y: itemY, closedHeight } of placed) {
1394 const face = faceOf(item, itemY, closedHeight);
1395 item.entries.forEach((entry, index) => {
1396 entryY.set(
1397 entry.key,
1398 face.top + face.height / 2 + (index - (item.entries.length - 1) / 2) * ENTRY_PITCH,
1399 );
1400 });
1401 }
1402 const portY = (link: FleetLinkEdge, hostId: string) => {
1403 const side = Math.sign(indexOf(link.from === hostId ? link.to : link.from) - indexOf(hostId));
1404 const key = `${hostId}:${side}`;
1405 const port =
1406 link.from === hostId && !twoWay(link)
1407 ? 0
1408 : Number(leaves.has(key)) + arrivalsOf.get(key)!.indexOf(link);
1409 return (
1410 centerOf(hostId) +
1411 side *
1412 (routesExtent(hostId) + LINK_PORT.first + port * linkPortPitch(byId.get(hostId)!, side))
1413 );
1414 };
1415
1416 // One lane per host for each shared row it reaches.
1417 const trunkOf = new Map<string, FleetLane>();
1418 const lanes: FleetLane[] = [];
1419 for (const [anchor, band] of bandOf) {
1420 const byHost = new Map<string, BayEntry[]>();
1421 for (const item of band) for (const entry of item.entries) pushTo(byHost, entry.from, entry);
1422 for (const [hostId, mine] of byHost) {
1423 const from = centerOf(hostId);
1424 const branches = mine.map((entry) => entryY.get(entry.key)!);
1425 const lane: FleetLane = {
1426 id: `${hostId}>${anchor}`,
1427 from,
1428 to: branches.reduce((far, at) => (Math.abs(at - from) > Math.abs(far - from) ? at : far)),
1429 branches,
1430 index: 0,
1431 };
1432 for (const entry of mine) trunkOf.set(entry.key, lane);
1433 lanes.push(lane);
1434 }
1435 }
1436 const span = (lane: FleetLane) => Math.abs(lane.to - lane.from);
1437 const passes = (lane: FleetLane, at: number) =>
1438 at > Math.min(lane.from, lane.to) && at < Math.max(lane.from, lane.to);
1439 // What `inner` nearer the cards costs: each of its turn-offs that has to cross `outer`, and
1440 // `outer` leaving its host across it. Of two lanes the one that costs less goes inside.
1441 const crossings = (inner: FleetLane, outer: FleetLane) =>
1442 inner.branches.filter((at) => passes(outer, at)).length + Number(passes(inner, outer.from));
1443 const taken: FleetLane[][] = [];
1444 for (const lane of lanes
1445 .toSorted((left, right) => (left.id < right.id ? -1 : 1))
1446 .toSorted(
1447 (left, right) => crossings(left, right) - crossings(right, left) || span(left) - span(right),
1448 )) {
1449 const top = Math.min(lane.from, lane.to) - LANE_CLEARANCE;
1450 const bottom = Math.max(lane.from, lane.to) + LANE_CLEARANCE;
1451 let index = 0;
1452 while (
1453 taken[index]?.some(
1454 (other) => Math.min(other.from, other.to) < bottom && top < Math.max(other.from, other.to),
1455 )
1456 ) {
1457 index += 1;
1458 }
1459 lane.index = index;
1460 (taken[index] ??= []).push(lane);
1461 }
1462 const laneX = (lane: FleetLane) => cardRight + metrics.laneFirst + lane.index * LANE_STEP;
1463 const fanX =
1464 taken.length === 0 ? cardRight : cardRight + metrics.laneFirst + taken.length * LANE_STEP;
1465 // Machines an open stack pushed down can need a lane more. It comes out of the run to their
1466 // column while that has any to give, so the column stays where it stood.
1467 const bayX =
1468 room.bayX === null
1469 ? fanX + metrics.linkRun
1470 : Math.max(room.bayX, fanX + Math.min(metrics.linkRun, LINK_RUN_MIN));
1471 const endX = bayX - ARROW_LENGTH;
1472 const lineInto = (entry: BayEntry) => {
1473 const trunk = trunkOf.get(entry.key);
1474 const targetY = entryY.get(entry.key)!;
1475 return {
1476 d:
1477 trunk === undefined
1478 ? sCurve(cardRight, centerOf(entry.from), endX, targetY, fanX)
1479 : elbowPath(cardRight, trunk.from, laneX(trunk), endX, targetY),
1480 arrow: { x: bayX, y: targetY },
1481 };
1482 };
1483
1484 let width = fanX;
1485 for (const { item, y: itemY, size, closedHeight } of placed) {
1486 width = Math.max(width, bayX + size.width);
1487 if (item.kind === "target") {
1488 nodes.set(item.targetId, { x: bayX, y: itemY, ...size });
1489 for (const entry of item.entries) {
1490 const line = lineInto(entry);
1491 linkGeometry.set(entry.key, {
1492 d: line.d,
1493 arrow: { ...line.arrow, dir: 1 },
1494 twoWay: null,
1495 badge: null,
1496 });
1497 }
1498 continue;
1499 }
1500 const { stack } = item;
1501 const { top, height: faceHeight } = faceOf(item, itemY, closedHeight);
1502 const face = { x: bayX, y: top, width: metrics.target, height: faceHeight };
1503 stackGeometry.set(stack.id, {
1504 ...(stack.expanded
1505 ? openRects(stack, face)
1506 : { rect: { x: bayX, y: itemY, ...size }, tray: null }),
1507 face,
1508 lines: item.entries.map((entry, index) => ({
1509 sourceId: entry.from,
1510 access: stack.sources[index]!.access,
1511 ...lineInto(entry),
1512 })),
1513 more: stack.expanded ? fillTray(stack, face) : null,
1514 });
1515 }
1516
1517 const clientCenterY =
1518 restCenters.length === 0
1519 ? HEADER + CLIENT.height / 2
1520 : (restCenters[0]! + restCenters.at(-1)!) / 2;
1521 nodes.set(FLEET_CLIENT_NODE_ID, {
1522 x: 0,
1523 y: clientCenterY - CLIENT.height / 2,
1524 ...CLIENT_SIZE,
1525 });
1526
1527 // Wires leave the client a little apart, in the order they arrive, so they never cross. A
1528 // folded group of environments gets one wire, whatever its machines' routes are.
1529 // Each route is named in a column beside its card, then closes up into the card's edge.
1530 const wires = column.flatMap(
1531 ({
1532 entry,
1533 center,
1534 }): Array<{
1535 entry: ColumnEntry;
1536 edge: FleetRouteEdge | null;
1537 portY: number;
1538 entryY: number;
1539 }> => {
1540 if (entry.kind === "fold") return [{ entry, edge: null, portY: center, entryY: center }];
1541 const hostRoutes = routesOf.get(entry.id) ?? [];
1542 return hostRoutes.map((edge, index) => {
1543 const offset = index - (hostRoutes.length - 1) / 2;
1544 return {
1545 entry,
1546 edge,
1547 portY: center + offset * FLEET_ROUTE_PITCH,
1548 entryY: center + offset * routeEntryPitch(entry.id),
1549 };
1550 });
1551 },
1552 );
1553 const pillRight = pillX + metrics.pill;
1554 const closeX = pillRight + metrics.pillGap;
1555 const pillColumns: FleetRect[] = [];
1556 const fan = Math.min(CLIENT.height - 20, (wires.length - 1) * 4);
1557 wires.forEach((wire, index) => {
1558 const startY =
1559 clientCenterY + (wires.length < 2 ? 0 : (index / (wires.length - 1) - 0.5) * fan);
1560 const close =
1561 wire.entryY === wire.portY
1562 ? ""
1563 : `H${pillRight}C${pillRight + metrics.pillGap / 2} ${wire.portY} ${closeX - metrics.pillGap / 2} ${wire.entryY} ${closeX} ${wire.entryY}`;
1564 const d = `${sCurve(metrics.app, startY, pillX, wire.portY)}${close}H${cardX}`;
1565 if (wire.edge === null) {
1566 const geometry = stackGeometry.get(wire.entry.id)!;
1567 stackGeometry.set(wire.entry.id, {
1568 ...geometry,
1569 lines: [{ sourceId: null, access: null, d, arrow: null }],
1570 });
1571 return;
1572 }
1573 const pill = { x: pillX, y: wire.portY - PILL.height / 2, ...PILL_SIZE };
1574 routes.set(wire.edge.id, { d, pill });
1575 pillColumns.push(pill);
1576 height = Math.max(height, pill.y + pill.height);
1577 });
1578
1579 // A link between environments names its access on its own lane, in a gap between two cards:
1580 // the one just past the environment it leaves, or the next one free. It grows away from the
1581 // other lanes passing there. Where no place is clear of every lane and every other name, the
1582 // name is shown only while its link is in focus, so it never covers a line that is being read.
1583 const runs = between.map((link) => ({
1584 link,
1585 x: cardX - metrics.betweenFirst - betweenLane.get(link.id)! * BETWEEN.step,
1586 from: portY(link, link.from),
1587 to: portY(link, link.to),
1588 }));
1589 const badges: FleetLinkBadge[] = [];
1590 for (const run of runs) {
1591 const { link, x } = run;
1592 const down = indexOf(link.to) > indexOf(link.from);
1593 const gaps: number[] = [];
1594 for (let index = low(link); index < high(link); index += 1) {
1595 const above = nodes.get(hosts[index]!.id)!;
1596 const below = nodes.get(hosts[index + 1]!.id)!;
1597 gaps.push(above.y + above.height + GROUP_GAP / 2, below.y - GROUP_GAP / 2);
1598 }
1599 if (!down) gaps.reverse();
1600 const place = (at: number, side: 1 | -1): FleetLinkBadge => ({
1601 x: side === 1 ? x - BADGE.overhang : x + BADGE.overhang - BADGE.width,
1602 y: at - BADGE.height / 2,
1603 width: BADGE.width,
1604 height: BADGE.height,
1605 side,
1606 onDemand: false,
1607 });
1608 const clearOfLanes = (badge: FleetLinkBadge) =>
1609 !runs.some(
1610 (other) =>
1611 other !== run &&
1612 other.x > badge.x &&
1613 other.x < badge.x + badge.width &&
1614 Math.min(other.from, other.to) < badge.y + badge.height &&
1615 Math.max(other.from, other.to) > badge.y,
1616 );
1617 const clearOfNames = (badge: FleetLinkBadge) =>
1618 !badges.some(
1619 (other) =>
1620 other.x < badge.x + badge.width + BADGE.gap &&
1621 badge.x < other.x + other.width + BADGE.gap &&
1622 other.y < badge.y + badge.height + BADGE.gap &&
1623 badge.y < other.y + other.height + BADGE.gap,
1624 );
1625 // Route names reach past their card into the gaps a name would take on that side.
1626 const clearOfRoutes = (badge: FleetLinkBadge) =>
1627 !pillColumns.some(
1628 (pill) =>
1629 pill.x < badge.x + badge.width &&
1630 badge.x < pill.x + pill.width &&
1631 pill.y < badge.y + badge.height &&
1632 badge.y < pill.y + pill.height,
1633 );
1634 const options = gaps.flatMap((at) => [place(at, 1), place(at, -1)]);
1635 const clear = options.find(
1636 (option) => clearOfNames(option) && clearOfLanes(option) && clearOfRoutes(option),
1637 );
1638 if (clear !== undefined) badges.push(clear);
1639 const startX = twoWay(link) ? cardX - ARROW_LENGTH : cardX;
1640 const [back, forward] = elbowHalves(startX, run.from, x, cardX - ARROW_LENGTH, run.to);
1641 linkGeometry.set(link.id, {
1642 d: elbowPath(startX, run.from, x, cardX - ARROW_LENGTH, run.to),
1643 arrow: { x: cardX, y: run.to, dir: 1 },
1644 twoWay: twoWay(link) ? { backArrow: { x: cardX, y: run.from, dir: 1 }, forward, back } : null,
1645 badge: clear ?? { ...options[0]!, onDemand: true },
1646 });
1647 }
1648
1649 return {
1650 nodes,
1651 stacks: stackGeometry,
1652 routes,
1653 links: linkGeometry,
1654 handles,
1655 columns: [
1656 { id: "client", x: 0 },
1657 ...(column.length > 0 ? [{ id: "environments" as const, x: cardX }] : []),
1658 ...(placed.length > 0 ? [{ id: "targets" as const, x: bayX }] : []),
1659 ],
1660 width,
1661 height,
1662 };
1663 }
1664
1665 /** What the arrow keys move between: every machine drawn, and each stack's controls. */
1666 export function fleetFocusRects(layout: FleetLayout): ReadonlyMap<string, FleetRect> {
1667 const rects = new Map(layout.nodes);
1668 for (const [id, geometry] of layout.stacks) {
1669 rects.set(id, geometry.face);
1670 if (geometry.more !== null) rects.set(fleetMoreNodeId(id), geometry.more);
1671 }
1672 return rects;
1673 }
1674
1675 /** The machines drawn on their own that a selection box touches. */
1676 export function fleetNodesInBox(layout: FleetLayout, box: FleetRect): string[] {
1677 const inside: string[] = [];
1678 for (const [id, rect] of layout.nodes) {
1679 if (
1680 id !== FLEET_CLIENT_NODE_ID &&
1681 rect.x < box.x + box.width &&
1682 box.x < rect.x + rect.width &&
1683 rect.y < box.y + box.height &&
1684 box.y < rect.y + rect.height
1685 ) {
1686 inside.push(id);
1687 }
1688 }
1689 return inside;
1690 }
1691
1692 /** What pressing or dropping an environment's link handle starts. */
1693 export type FleetLinkAction =
1694 /** The batch flow, opened on these machines. Which of them it can link is its own to say. */
1695 | {
1696 readonly kind: "batch";
1697 readonly sourceEnvironmentId: EnvironmentId;
1698 readonly environmentIds: ReadonlyArray<EnvironmentId>;
1699 }
1700 /**
1701 * None of the machines dropped on can be linked from here in one go: this client has no
1702 * session on any of them, so each needs a pairing code. `machineIds` are the map's nodes.
1703 */
1704 | {
1705 readonly kind: "code-only";
1706 readonly sourceId: string;
1707 readonly sourceEnvironmentId: EnvironmentId;
1708 readonly machineIds: ReadonlyArray<string>;
1709 }
1710 /** The single link flow; `offer` is null when no machine was named. */
1711 | {
1712 readonly kind: "single";
1713 readonly sourceEnvironmentId: EnvironmentId;
1714 readonly offer: Extract<FleetLinkOffer, { kind: "link" }> | null;
1715 };
1716
1717 /**
1718 * A drop on a stack links to its machines; a drop on a selected machine, or a press of the
1719 * handle while others are selected, links to the selection. Anything else is one link.
1720 */
1721 export function fleetLinkAction(
1722 graph: FleetGraph,
1723 stacks: ReadonlyArray<FleetStack>,
1724 selected: ReadonlySet<string>,
1725 sourceId: string,
1726 targetId: string | null,
1727 ): FleetLinkAction | null {
1728 const byId = new Map(graph.nodes.map((node) => [node.id, node]));
1729 const source = byId.get(sourceId);
1730 if (source?.kind !== "environment" || source.linking !== "ready") return null;
1731 const sourceEnvironmentId = source.environmentId;
1732 const batch = (picked: Iterable<string>): FleetLinkAction | null => {
1733 const environmentIds = new Set<EnvironmentId>();
1734 const machineIds: string[] = [];
1735 let known = false;
1736 for (const id of picked) {
1737 const node = byId.get(id);
1738 if (node === undefined || node.kind === "client" || node.id === source.id) continue;
1739 if (!environmentIds.has(node.environmentId)) machineIds.push(node.id);
1740 environmentIds.add(node.environmentId);
1741 known ||= node.kind !== "target";
1742 }
1743 if (environmentIds.size === 0) return null;
1744 if (known) return { kind: "batch", sourceEnvironmentId, environmentIds: [...environmentIds] };
1745 const [only, ...rest] = machineIds;
1746 if (rest.length > 0 || only === undefined) {
1747 return { kind: "code-only", sourceId: source.id, sourceEnvironmentId, machineIds };
1748 }
1749 // One such machine is the single flow's, which asks for its code.
1750 const offer = fleetLinkOffer(graph, sourceId, only);
1751 return offer.kind === "link" ? { kind: "single", sourceEnvironmentId, offer } : null;
1752 };
1753 const stack = targetId === null ? undefined : stacks.find((entry) => entry.id === targetId);
1754 if (stack !== undefined) return batch(stack.memberIds);
1755 if (targetId === null || selected.has(targetId)) {
1756 const picked = batch(selected);
1757 if (picked !== null) return picked;
1758 }
1759 if (targetId === null) return { kind: "single", sourceEnvironmentId, offer: null };
1760 const offer = fleetLinkOffer(graph, sourceId, targetId);
1761 return offer.kind === "link" ? { kind: "single", sourceEnvironmentId, offer } : null;
1762 }
1763
1764 /** Machines whose name holds the query, drawn or folded, in name order. */
1765 export function fleetSearch(graph: FleetGraph, query: string): string[] {
1766 const needle = query.trim().toLocaleLowerCase();
1767 if (needle === "") return [];
1768 return graph.nodes
1769 .filter((node) => node.kind !== "client" && node.label.toLocaleLowerCase().includes(needle))
1770 .toSorted((left, right) => labelOrder.compare(left.label, right.label))
1771 .map((node) => node.id);
1772 }
1773
1774 export type FleetDirection = "up" | "down" | "left" | "right";
1775
1776 /** The nearest item in that direction, for arrow keys. Sideways distance counts double. */
1777 export function nextFleetNode(
1778 rects: ReadonlyMap<string, FleetRect>,
1779 fromId: string,
1780 direction: FleetDirection,
1781 ): string | null {
1782 const from = rects.get(fromId);
1783 if (!from) return null;
1784 const horizontal = direction === "left" || direction === "right";
1785 const sign = direction === "left" || direction === "up" ? -1 : 1;
1786 const center = (rect: FleetRect) => ({
1787 x: rect.x + rect.width / 2,
1788 y: rect.y + rect.height / 2,
1789 });
1790 const origin = center(from);
1791 let best: { readonly id: string; readonly score: number } | null = null;
1792 for (const [id, rect] of rects) {
1793 if (id === fromId) continue;
1794 const point = center(rect);
1795 const along = sign * (horizontal ? point.x - origin.x : point.y - origin.y);
1796 const across = Math.abs(horizontal ? point.y - origin.y : point.x - origin.x);
1797 if (along < 1) continue;
1798 const score = along + across * 2;
1799 if (best === null || score < best.score) best = { id, score };
1800 }
1801 return best?.id ?? null;
1802 }
1803
1804 export interface FleetViewTransform {
1805 readonly x: number;
1806 readonly y: number;
1807 readonly scale: number;
1808 }
1809
1810 const FLEET_MIN_SCALE = 0.3;
1811 const FLEET_MAX_SCALE = 2;
1812 /** A small setup is enlarged to fill the canvas, but not until two machines look like a poster. */
1813 const FLEET_FIT_MAX_SCALE = 1.15;
1814 /** The fit never has to go below this on a map with its stacks closed, down to a 560px canvas. */
1815 export const FLEET_FIT_LEGIBLE_SCALE = 0.85;
1816
1817 /** The canvas width a layout is made for: steps, so dragging a window edge relays it rarely. */
1818 export const fleetLayoutWidth = (canvasWidth: number) => Math.floor(canvasWidth / 16) * 16;
1819
1820 /** The margin the fit leaves around the map: a narrow canvas spends less of itself on it. */
1821 const fleetFitPadding = (canvasWidth: number) => (canvasWidth < 720 ? 16 : 28);
1822
1823 const fitScale = (available: number, extent: number, padding: number) =>
1824 Math.max(0.01, (available - padding * 2) / Math.max(1, extent));
1825
1826 /** Centers the whole map in the viewport at the largest scale that shows all of it. */
1827 export function fitFleetLayout(
1828 layout: Pick<FleetLayout, "width" | "height">,
1829 viewport: { readonly width: number; readonly height: number },
1830 ): FleetViewTransform {
1831 const padding = fleetFitPadding(viewport.width);
1832 const scale = Math.min(
1833 FLEET_FIT_MAX_SCALE,
1834 fitScale(viewport.width, layout.width, padding),
1835 fitScale(viewport.height, layout.height, padding),
1836 );
1837 return {
1838 scale,
1839 x: (viewport.width - layout.width * scale) / 2,
1840 y: (viewport.height - layout.height * scale) / 2,
1841 };
1842 }
1843
1844 /** How tall the canvas wants to be at this width: the fitted map plus padding, within bounds. */
1845 export function fleetCanvasHeight(
1846 layout: Pick<FleetLayout, "width" | "height">,
1847 width: number,
1848 bounds: { readonly min: number; readonly max: number },
1849 ): number {
1850 const padding = fleetFitPadding(width);
1851 const scale = Math.min(FLEET_FIT_MAX_SCALE, fitScale(width, layout.width, padding));
1852 const wanted = Math.ceil(layout.height * scale + padding * 2);
1853 return Math.max(bounds.min, Math.min(bounds.max, wanted));
1854 }
1855
1856 /** Zooms by `factor`, keeping the map point under `anchor` where it is. */
1857 export function zoomFleetView(
1858 view: FleetViewTransform,
1859 factor: number,
1860 anchor: FleetPoint,
1861 fitScale = view.scale,
1862 ): FleetViewTransform {
1863 // A fit of a very large setup sits below the manual minimum: zooming out stops at the fit
1864 // instead of jumping up, and can return to it after zooming in.
1865 const floor = Math.min(FLEET_MIN_SCALE, fitScale, view.scale);
1866 const scale = Math.max(floor, Math.min(FLEET_MAX_SCALE, view.scale * factor));
1867 const ratio = scale / view.scale;
1868 return {
1869 scale,
1870 x: anchor.x - (anchor.x - view.x) * ratio,
1871 y: anchor.y - (anchor.y - view.y) * ratio,
1872 };
1873 }
1874
1875 /** A view that is not the fit: set by hand, or kept in place while a stack opened or closed. */
1876 export interface FleetHeldView {
1877 /** The shape it was set on. It holds while the map keeps that shape. */
1878 readonly key: string;
1879 readonly view: FleetViewTransform;
1880 readonly height: number;
1881 /** Eased into; a drag or pinch tracks the hand instead. */
1882 readonly glide: boolean;
1883 /** What closing the stack again returns to, while nothing else has moved the view since. */
1884 readonly undo: { readonly key: string; readonly held: FleetHeldView | null } | null;
1885 }
1886
1887 /**
1888 * The view after a stack opened or closed. Its card stays where it was on screen and the scale
1889 * holds, so nothing is fitted again. The canvas grows to show what the stack added, up to its
1890 * bound; past that the user pans. Only a stack wider than the canvas at this scale shrinks the
1891 * view, and then just to its width. Toggling it back returns the view it had before.
1892 */
1893 export function anchorFleetView(input: {
1894 readonly key: string;
1895 /** The shape, the view held on it and the canvas before the change. */
1896 readonly from: {
1897 readonly key: string;
1898 readonly held: FleetHeldView | null;
1899 readonly view: FleetViewTransform;
1900 readonly size: { readonly width: number; readonly height: number };
1901 readonly face: FleetPoint;
1902 };
1903 /** The stack and the map after it. */
1904 readonly stack: Pick<FleetStackGeometry, "rect" | "face" | "tray">;
1905 readonly layout: Pick<FleetLayout, "width" | "height">;
1906 readonly bounds: { readonly min: number; readonly max: number };
1907 }): FleetHeldView {
1908 const { from, stack, layout, bounds } = input;
1909 const { size } = from;
1910 if (from.held?.undo?.key === input.key) {
1911 const { held } = from.held.undo;
1912 // With no view held before, a stale entry eases the scene back to the fit.
1913 return held === null
1914 ? { key: "", view: from.view, height: size.height, glide: true, undo: null }
1915 : { ...held, glide: true };
1916 }
1917 const padding = fleetFitPadding(size.width);
1918 const top = from.face.y * from.view.scale + from.view.y;
1919 const scale = Math.min(from.view.scale, fitScale(size.width, stack.rect.width, padding));
1920 const view =
1921 scale < from.view.scale
1922 ? { scale, x: padding - stack.face.x * scale, y: top - stack.face.y * scale }
1923 : {
1924 scale,
1925 x: from.view.x + (from.face.x - stack.face.x) * scale,
1926 y: from.view.y + (from.face.y - stack.face.y) * scale,
1927 };
1928 const wanted = Math.ceil(view.y + layout.height * scale + padding);
1929 const opened = stack.tray !== null;
1930 return {
1931 key: input.key,
1932 view,
1933 height: Math.max(
1934 bounds.min,
1935 Math.min(bounds.max, opened ? Math.max(size.height, wanted) : Math.min(size.height, wanted)),
1936 ),
1937 glide: true,
1938 undo: { key: from.key, held: from.held },
1939 };
1940 }