garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /web/src/components/network.tsx

raw

import m from '@garage44/mithril'

import {Measured} from '@/components/measured'
import {since} from '@/lib/format'
import {diskMeter, loadMeter} from '@/lib/meters'
import type {Meter} from '@/lib/meters'
import {STATE_ICON, STATE_LABEL, machines, nodeState} from '@/lib/nodes'
import {nameOf} from '@/lib/names'
import {$s} from '@/lib/store'
import type {Deploys, WorkspaceEvent, WorkspaceState, Node} from '@/lib/types'

/*
 * The workspace as a diagram: the agents, the hub and the deploys across the
 * top; the WireGuard network under them; each machine on a link of its own,
 * its nodes inside. Laid out for the width it is given — machines side by side
 * on a desk, one under another off a trunk on a phone. A node is a button:
 * it opens its details and its controls; so are the deploys.
 */

/** A target's last deploy this week: queued, published or failed. */
export function lastDeploy(d: Deploys, target: string) {
    const evs = d.recent.filter((e) => e.target === target)
    return evs[evs.length - 1] as WorkspaceEvent | undefined
}

const DEPLOY_ICON: Record<string, string> = {deploy_published: '✓', deploy_failed: '✗', deploy_queued: '…'}
const DEPLOY_WORD: Record<string, string> = {deploy_published: 'published', deploy_failed: 'failed', deploy_queued: 'running'}

/**
 * Two lines: one per target when there are two or fewer; else the latest
 * deploy, and how the targets' last deploys went, counted.
 */
function deployLines(d: Deploys | null, narrow: boolean) {
    if (!d) return ['…']
    if (d.targets.length === 0) return ['no targets']
    const line = (target: string) => {
        const e = lastDeploy(d, target)
        if (!e) return `${target} · none this week`
        const icon = DEPLOY_ICON[e.kind] ?? '·'
        return narrow ? `${icon} ${target}` : `${icon} ${target} · ${since(Date.parse(e.ts) / 1000)} ago`
    }
    if (d.targets.length <= 2) return d.targets.map((t) => line(t.target))
    const latest = d.recent[d.recent.length - 1]
    const counts: Record<string, number> = {}
    for (const {target} of d.targets) {
        const kind = lastDeploy(d, target)?.kind ?? ''
        const key = narrow ? (DEPLOY_ICON[kind] ?? '–') : (DEPLOY_WORD[kind] ?? 'idle')
        counts[key] = (counts[key] ?? 0) + 1
    }
    const summary = Object.entries(counts).map(([key, n]) => `${n} ${key}`).join(' · ')
    return [latest ? line(String(latest.target)) : 'none this week', summary]
}

const GAP = 12
const TOP_H = 62
/** The gap between a top box and the hub under it, when they stack. */
const TOP_GAP = 28
const MACHINE_HEAD = 38
const CHIP_H = 72
const CHIP_GAP = 8
/** Where the network runs down the left, and how far the machines stand off it. */
const TRUNK_X = 8
const INDENT = 24
/** Where a machine plugs into the network: level with its name. */
const PORT_DY = 19

function box(x: number, y: number, w: number, h: number, cls: string) {
    return <rect x={x} y={y} width={w} height={h} rx={10} class={cls} />
}

function text(x: number, y: number, s: string, cls: string, anchor = 'start') {
    return (
        <text x={x} y={y} class={cls} text-anchor={anchor}>
            {s}
        </text>
    )
}

/** A link from the network to a machine, ending in a port dot where it leaves the network. */
function link(d: string, px: number, py: number, off: boolean) {
    return (
        <g class="network__branch" data-off={off ? 'true' : undefined}>
            <path d={d} class="network__stub" fill="none" />
            <circle cx={px} cy={py} r={4} class="network__port" />
        </g>
    )
}

/**
 * A meter: its text over a thin bar `w` wide. A node that does not report what
 * to measure against (a midas older than 2026-10-20) gets the text alone.
 */
function meter(x: number, y: number, w: number, mt: Meter | null) {
    if (!mt) return null
    return (
        <g class="network__meter" data-level={mt.level}>
            {text(x, y, fit(mt.text, w, 6), 'network__faint')}
            {mt.fill == null
                ? null
                : [
                      <rect x={x} y={y + 5} width={w} height={5} rx={2.5} class="network__meter-track" />,
                      <rect x={x} y={y + 5} width={Math.max(3, w * mt.fill)} height={5} rx={2.5} class="network__meter-fill" />,
                  ]}
        </g>
    )
}

/** Text cut to fit a width at roughly 7 px a character. */
function fit(s: string, width: number, px = 7) {
    const n = Math.max(3, Math.floor(width / px))
    return s.length > n ? `${s.slice(0, n - 1)}…` : s
}

export class Network extends Measured<{workspace: WorkspaceState}> {
    view({attrs}: m.Vnode<{workspace: WorkspaceState}>) {
        const workspace = attrs.workspace
        const W = this.width
        if (W === 0) return <div class="network" />

        const holding = Object.keys(workspace.leases).length
        const waiting = Object.keys(workspace.waiters).length

        // The machines, in a grid of as many columns as fit.
        const ms = machines(workspace)
        const cols = Math.max(1, Math.min(ms.length, Math.floor((W + GAP) / (220 + GAP))))
        // One column is a phone: agents and deploys side by side over a hub as
        // wide as the diagram, and the network a trunk down the left with a
        // branch to each machine. A line dropped from a bar over one column
        // would run through every machine to reach the next, and read as the
        // later ones being reached through the first.
        const phone = cols === 1 && ms.length > 1

        // The top: agents — hub — deploys in a row, or agents | deploys over the hub.
        const third = Math.min(240, (W - 2 * GAP) / 3)
        const half = (W - GAP) / 2
        const slots = phone
            ? [
                  {x: 0, y: 0, w: half},
                  {x: 0, y: TOP_H + TOP_GAP, w: W},
                  {x: half + GAP, y: 0, w: half},
              ]
            : [
                  {x: 0, y: 0, w: third},
                  {x: (W - third) / 2, y: 0, w: third},
                  {x: W - third, y: 0, w: third},
              ]
        const hub = slots[1]!
        const hubBottom = hub.y + TOP_H
        // A box of less than 180 px says the short form of each line.
        const narrow = (phone ? half : third) < 180
        // Where the hub listens, as the state says; a hub from before it said so shows as "hub".
        const hubAt = $s.workspace?.hub?.listen ?? ''
        const top = [
            {title: 'agents', lines: [`${holding} holding`, `${waiting} waiting`]},
            {title: 'hub', lines: [narrow && !phone ? (hubAt.split(':')[0] || 'hub') : (hubAt || 'hub'), narrow && !phone ? $s.hubVersion : `midas ${$s.hubVersion}`]},
            {title: 'deploys', lines: deployLines($s.deploys, narrow)},
        ]

        // The machines stand off the left edge when a trunk runs down it.
        const rows: (typeof ms)[] = []
        for (let i = 0; i < ms.length; i += cols) rows.push(ms.slice(i, i + cols))
        const indent = rows.length > 1 ? INDENT : 0
        const mw = (W - indent - GAP * (cols - 1)) / cols
        const busY = hubBottom + 34
        let y = phone ? hubBottom + 30 : busY + 30
        const placed = rows.flatMap((row) => {
            const h = Math.max(...row.map((mm) => MACHINE_HEAD + mm.nodes.length * (CHIP_H + CHIP_GAP) + 4))
            const out = row.map((mm, i) => ({...mm, x: indent + i * (mw + GAP), y, h}))
            y += h + 30
            return out
        })
        const height = y - 18
        // A machine all of whose nodes are off the network hangs on a dashed branch.
        const off = (p: (typeof placed)[number]) => p.nodes.every((n) => !n.enabled)

        // The network. On a phone: the trunk from the hub, a branch into each
        // machine's side. Else a bar under the hub with a drop to each machine
        // of the first row; later rows hang off a bar of their own in the gap
        // above them, reached by a trunk down the left.
        const network: m.Children[] = []
        if (phone) {
            const last = placed[placed.length - 1]!
            network.push(<line class="network__trunk" x1={TRUNK_X} y1={hubBottom} x2={TRUNK_X} y2={last.y + PORT_DY} />)
            network.push(text(TRUNK_X + 12, hubBottom + 18, 'WIREGUARD', 'network__label'))
            for (const p of placed) {
                const py = p.y + PORT_DY
                network.push(link(`M${TRUNK_X},${py} H${p.x}`, TRUNK_X, py, off(p)))
            }
        } else {
            const midX = hub.x + hub.w / 2
            network.push(<line class="network__link" x1={midX} y1={hubBottom} x2={midX} y2={busY} />)
            network.push(<line class="network__trunk" x1={indent ? TRUNK_X : 8} y1={busY} x2={W - 8} y2={busY} />)
            network.push(text(indent ? TRUNK_X + 12 : 8, busY - 8, 'WIREGUARD', 'network__label'))
            const rowTops = [...new Set(placed.map((p) => p.y))]
            if (rowTops.length > 1) {
                const lastBar = rowTops[rowTops.length - 1]! - 15
                network.push(<line class="network__trunk" x1={TRUNK_X} y1={busY} x2={TRUNK_X} y2={lastBar} />)
                for (const top of rowTops.slice(1)) {
                    const inRow = placed.filter((p) => p.y === top)
                    const end = inRow[inRow.length - 1]!
                    network.push(<line class="network__trunk" x1={TRUNK_X} y1={top - 15} x2={end.x + mw / 2} y2={top - 15} />)
                }
            }
            for (const p of placed) {
                const cx = p.x + mw / 2
                const barY = p.y === placed[0]!.y ? busY : p.y - 15
                network.push(link(`M${cx},${barY} V${p.y}`, cx, barY, off(p)))
            }
        }

        const chip = (n: Node, x: number, cy: number, w: number) => {
            const lease = workspace.leases[n.id]
            const st = nodeState(n, lease)
            const r = n.reading
            // The holder by its readable name; a bot by what it runs.
            const holder = lease ? (lease.mode === 'bot' && lease.purpose ? lease.purpose : nameOf(lease.owner).title) : ''
            const who = lease
                ? `${since(lease.claimed_at)} · ${lease.yield ? 'yielding · ' : ''}${holder}`
                : n.drained
                  ? n.drained.why
                  : st === 'asleep'
                    ? `idle, shut down ${since(n.asleep!.since)} ago · starts when needed`
                    : (n.renderer ?? '')
            const half = (w - 36) / 2
            return (
                <g
                    class="network__chip"
                    data-state={st}
                    role="button"
                    tabindex={0}
                    aria-label={`${n.id}, ${STATE_LABEL[st]}`}
                    onclick={() => ($s.selected = n.id)}
                    onkeydown={(e: KeyboardEvent) => {
                        if (e.key === 'Enter' || e.key === ' ') $s.selected = n.id
                    }}
                >
                    {box(x, cy, w, CHIP_H, 'network__chip-box')}
                    <rect x={x} y={cy} width={4} height={CHIP_H} rx={2} class="network__chip-bar" />
                    {text(x + 14, cy + 20, n.id, 'network__strong')}
                    <text x={x + w - 10} y={cy + 20} class="network__state" text-anchor="end">
                        <tspan class="network__state-icon">{STATE_ICON[st]}</tspan> {STATE_LABEL[st]}
                    </text>
                    {text(x + 14, cy + 37, fit(who, w - 24), 'network__dim')}
                    {meter(x + 14, cy + 54, half, diskMeter(r))}
                    {meter(x + 14 + half + 12, cy + 54, half, loadMeter(r))}
                </g>
            )
        }

        // The machine's address, in a pill at the right of its name.
        const address = (p: (typeof placed)[number]) => {
            const pw = p.address.length * 6.5 + 18
            const px = p.x + mw - 10 - pw
            return [
                <rect x={px} y={p.y + 9} width={pw} height={20} rx={10} class="network__pill" />,
                text(px + pw / 2, p.y + 23, p.address, 'network__faint', 'middle'),
            ]
        }

        return (
            <div class="network">
                <svg width={W} height={height} role="img" aria-label="The workspace's network">
                    {/* Links into the hub: the agents' API, and the hub publishing main. */}
                    {phone
                        ? [
                              <line class="network__link" x1={half / 2} y1={TOP_H} x2={half / 2} y2={hub.y} />,
                              <line class="network__link" x1={half + GAP + half / 2} y1={TOP_H} x2={half + GAP + half / 2} y2={hub.y} />,
                              text(half / 2 + 8, TOP_H + 18, 'API', 'network__label'),
                              text(half + GAP + half / 2 + 8, TOP_H + 18, 'PUBLISH', 'network__label'),
                          ]
                        : [
                              <line class="network__link" x1={third} y1={TOP_H / 2} x2={hub.x} y2={TOP_H / 2} />,
                              <line class="network__link" x1={hub.x + third} y1={TOP_H / 2} x2={slots[2]!.x} y2={TOP_H / 2} />,
                              hub.x - third > 64 ? text((third + hub.x) / 2, TOP_H / 2 - 6, 'API', 'network__label', 'middle') : null,
                              hub.x - third > 64 ? text((hub.x + third + slots[2]!.x) / 2, TOP_H / 2 - 6, 'PUBLISH', 'network__label', 'middle') : null,
                          ]}

                    {network}

                    {top.map((t, i) => {
                        const s = slots[i]!
                        const inner = [
                            box(s.x, s.y, s.w, TOP_H, i === 1 ? 'network__hub' : 'network__box'),
                            text(s.x + 12, s.y + 20, t.title, 'network__strong'),
                            ...t.lines.map((l, k) => text(s.x + 12, s.y + 37 + k * 15, fit(l, s.w - 20, 6.5), 'network__dim')),
                        ]
                        if (i !== 2) return <g>{inner}</g>
                        return (
                            <g
                                class="network__button"
                                role="button"
                                tabindex={0}
                                aria-label="Deploys"
                                onclick={() => ($s.deploysOpen = true)}
                                onkeydown={(e: KeyboardEvent) => {
                                    if (e.key === 'Enter' || e.key === ' ') $s.deploysOpen = true
                                }}
                            >
                                {inner}
                            </g>
                        )
                    })}

                    {placed.map((p) => (
                        <g>
                            {box(p.x, p.y, mw, p.h, 'network__machine')}
                            {text(p.x + 12, p.y + 23, p.machine, 'network__strong')}
                            {address(p)}
                            {p.nodes.map((n, k) => chip(n, p.x + 8, p.y + MACHINE_HEAD + k * (CHIP_H + CHIP_GAP), mw - 16))}
                        </g>
                    ))}
                </svg>
            </div>
        )
    }
}