garage44.eu/jeroen/midas

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

.. /web/src/components/workspace.tsx

raw

import m, {MithrilComponent} from '@garage44/mithril'
import {Alert, Badge, Button, Card, Dialog, FieldSegmented, FieldText, Progress, Table} from '@garage44/mithril/components'

import {Bars, Lines, SERIES} from '@/components/charts'
import {Network, lastDeploy} from '@/components/network'
import {Services} from '@/components/services'
import {confirmButton} from '@/components/confirm'
import {who} from '@/components/who'
import {api} from '@/lib/api'
import type {Device, Power} from '@/lib/api'
import {act} from '@/lib/actions'
import {age, bytes, day as dayLabel, dur, now, shortName, since, when} from '@/lib/format'
import {diskMeter, loadMeter} from '@/lib/meters'
import type {Level, Meter} from '@/lib/meters'
import {STATE_ICON, STATE_LABEL, nodeState} from '@/lib/nodes'
import {nameOf} from '@/lib/names'
import {projectName} from '@/lib/projects'
import type {NodeState} from '@/lib/nodes'
import {bind, local} from '@/lib/reactive'
import {here} from '@/lib/route'
import {$s} from '@/lib/store'
import {cards} from '@/lib/stream'
import {byNamespace} from '@/lib/together'
import type {WorkspaceState} from '@/lib/types'

const TONE: Record<NodeState, 'success' | 'info' | 'warning' | 'danger' | 'neutral'> = {
    asleep: 'neutral',
    free: 'success',
    busy: 'info',
    bot: 'info',
    drained: 'warning',
    offline: 'danger',
}

const METER_TONE: Record<Level, 'success' | 'warning' | 'danger'> = {ok: 'success', warn: 'warning', bad: 'danger'}

/** A meter as a bar under its text; the text alone when the node gives nothing to measure against. */
function meter(mt: Meter | null, suffix = '') {
    if (!mt) return '–'
    if (mt.fill == null) return mt.text + suffix
    return <Progress value={mt.fill} max={1} tone={METER_TONE[mt.level]} label={mt.text + suffix} />
}

/** A control that needs the caller key says so instead of failing. */
function needsKey() {
    return $s.hasKey ? null : <p class="hint">To change anything here, log in: the mark at the top right on a phone, the foot of the menu wider.</p>
}

/** One node's readings and lease, and what can be done to it. */
class NodeDialog extends MithrilComponent<{workspace: WorkspaceState}> {
    s = local({why: '', confirmRelease: false})

    view({attrs}: m.Vnode<{workspace: WorkspaceState}>) {
        const id = $s.selected
        const n = attrs.workspace.nodes.find((x) => x.id === id)
        const s = this.s
        const open = {
            get value() {
                return n != null
            },
            set value(v: boolean) {
                if (!v) {
                    $s.selected = null
                    s.confirmRelease = false
                }
            },
        }
        if (!n) return <Dialog model={open} title="" />
        const lease = attrs.workspace.leases[n.id]
        const st = nodeState(n, lease)
        const r = n.reading
        const rows: [string, m.Children][] = [
            ['machine', `${n.machine} · ${n.address}`],
            ['renders on', n.renderer ?? (n.gpu ? 'GPU' : 'CPU')],
            ['midas', r?.version ? `${r.version}${r.version !== $s.hubVersion ? ` (takes the hub's ${$s.hubVersion} when free)` : ''}` : '–'],
            ['set up', !r ? '–' : !r.recipe || r.recipe !== $s.hubRecipe ? <span class="hint">from an older recipe: its owner runs sudo midas setup {n.id}</span> : 'current'],
            ['checkout', r?.head ? r.head.slice(0, 8) : '–'],
            ['warmed', r?.warm ? `${r.warm.slice(0, 8)}, ${dur(r.warm_age_s)} ago` : '–'],
            ['load', meter(loadMeter(r))],
            ['memory', r?.mem_used != null ? `${bytes(r.mem_used)} of ${bytes(r.mem_max)}` : '–'],
            ['target/', bytes(r?.target_bytes)],
            ['disk', meter(diskMeter(r), r?.disk_total ? ` of ${bytes(r.disk_total)}` : '')],
            ['ssh sessions', String(r?.sessions ?? '–')],
            ['last heard', r ? `${since(r.at)} ago` : 'never'],
        ]
        if (lease) {
            const left = lease.intent_until != null ? `, about ${dur(Math.max(0, lease.intent_until - now()))} more` : ''
            rows.push(
                ['held by', who(lease.owner, {sub: true})],
                ['branch', lease.branch ?? '–'],
                ['for', `${lease.purpose ? `${lease.purpose}, ` : ''}${since(lease.claimed_at)}`],
                ['doing', lease.intent ? `${lease.intent}${left}` : <span class="hint">not said</span>],
                ['last command', <code>{lease.last_command ?? '–'}</code>],
            )
            if (lease.yield) rows.push(['yield', 'goes back when its current session ends'])
        }
        if (n.drained) rows.push(['drained', `${n.drained.why} (by ${n.drained.by}, ${when(n.drained.at)})`])
        if (n.asleep)
            rows.push(['asleep', `its VM was shut down ${since(n.asleep.since)} ago, after an hour nobody used it; it starts when somebody waits for a node (a minute or two)`])
        return (
            <Dialog model={open} title={n.id}>
                <p>
                    <Badge tone={TONE[st]} dot>
                        {STATE_ICON[st]} {STATE_LABEL[st]}
                    </Badge>
                </p>
                <dl class="facts">
                    {rows.map(([k, v]) => [<dt>{k}</dt>, <dd>{v}</dd>])}
                </dl>
                {needsKey()}
                <div class="actions">
                    {n.drained ? (
                        <Button disabled={!$s.hasKey} onclick={() => act(`${n.id} undrained`, () => api.undrain(n.id))}>
                            Put back in the pool
                        </Button>
                    ) : (
                        <div class="drain">
                            <FieldText model={bind(this.s, 'why')} placeholder="why (shown to everyone)" />
                            <Button
                                variant="secondary"
                                disabled={!$s.hasKey || !this.s.why.trim()}
                                onclick={() => act(`${n.id} drained`, () => api.drain(n.id, this.s.why.trim()))}
                            >
                                Drain
                            </Button>
                        </div>
                    )}
                    {lease ? (
                        this.s.confirmRelease ? (
                            <Button
                                variant="danger"
                                disabled={!$s.hasKey}
                                onclick={() => {
                                    this.s.confirmRelease = false
                                    void act(`${n.id} taken from ${lease.owner}`, () => api.release(n.id))
                                }}
                            >
                                Take it from {shortName(nameOf(lease.owner).title, 30)}
                            </Button>
                        ) : (
                            <Button variant="ghost" disabled={!$s.hasKey} onclick={() => (this.s.confirmRelease = true)}>
                                Release the lease…
                            </Button>
                        )
                    ) : null}
                </div>
            </Dialog>
        )
    }
}

/** Each deploy target with how its last deploy went, and a button to publish main. */
class DeployDialog extends MithrilComponent {
    s = local({confirm: '' as string})

    view() {
        const d = $s.deploys
        const s = this.s
        const open = {
            get value() {
                return $s.deploysOpen
            },
            set value(v: boolean) {
                $s.deploysOpen = v
                if (!v) s.confirm = ''
            },
        }
        if (!d) return <Dialog model={open} title="Deploys" />
        const last = (target: string) => lastDeploy(d, target)
        return (
            <Dialog model={open} title="Deploys">
                <p class="hint">The last week. A deploy publishes the tip of main, once the gate passed it.</p>
                {needsKey()}
                <Table
                    rowKey={(t: {target: string}) => t.target}
                    rows={d.targets}
                    columns={[
                        {key: 'target', label: 'target', cell: (t: {target: string}) => <b>{t.target}</b>},
                        {
                            key: 'last',
                            label: 'last',
                            cell: (t: {target: string}) => {
                                const e = last(t.target)
                                if (!e) return <span class="hint">none this week</span>
                                const tone = e.kind === 'deploy_published' ? 'success' : e.kind === 'deploy_failed' ? 'danger' : 'info'
                                const label = e.kind.replace('deploy_', '')
                                return (
                                    <span title={String(e.what ?? '')}>
                                        <Badge tone={tone}>{label}</Badge> {String(e.sha ?? '').slice(0, 8)} · {when(e.ts)}
                                    </span>
                                )
                            },
                        },
                        {
                            key: 'go',
                            label: '',
                            align: 'end',
                            cell: (t: {target: string}) =>
                                this.s.confirm === t.target ? (
                                    <Button
                                        size="sm"
                                        variant="danger"
                                        onclick={() => {
                                            this.s.confirm = ''
                                            void act(`deploy of ${t.target} queued`, () => api.deploy(t.target))
                                        }}
                                    >
                                        Publish main to {t.target}
                                    </Button>
                                ) : (
                                    <Button size="sm" variant="ghost" disabled={!$s.hasKey} onclick={() => (this.s.confirm = t.target)}>
                                        Deploy…
                                    </Button>
                                ),
                        },
                    ]}
                />
            </Dialog>
        )
    }
}

/** Something wrong with the machines, in a line each: what the person may want to act on first. */
function problems(ws: WorkspaceState): string[] {
    const out: string[] = []
    // Its state, git mirrors and sessions share one disk: full, every take and every write fails (check.rs's HUB_LOW_DISK).
    const hubFree = ws.hub?.disk_free
    if (hubFree != null && hubFree < 10e9) out.push(`the hub is short of disk: ${Math.floor(hubFree / 1e9)} GB free where its state is`)
    for (const n of ws.nodes) {
        const lease = ws.leases[n.id]
        const st = nodeState(n, lease)
        if (st === 'offline') out.push(`${n.id} is not reporting${n.reading ? `: last heard ${since(n.reading.at)} ago` : ''}`)
        else if (st === 'drained' && n.drained) out.push(`${n.id} is out of the pool: ${n.drained.why}`)
        if (st === 'offline') continue
        const load = loadMeter(n.reading)
        if (load?.level === 'bad') out.push(`${n.id} is overloaded: ${load.text}`)
        const disk = diskMeter(n.reading)
        if (disk?.level === 'bad') out.push(`${n.id} is short of disk: ${disk.text}`)
    }
    // Waiting long for a node: the pool is too small for the work, or a node is held and idle.
    for (const [owner, w] of Object.entries(ws.waiters)) {
        const waited = now() - w.since
        if (waited > 15 * 60) out.push(`${shortName(nameOf(owner).title, 50)} has waited ${dur(waited)} for ${w.node ?? w.machine ?? 'a node'}`)
    }
    return out
}

const SHIP_TONE: Record<string, 'success' | 'info' | 'warning' | 'danger' | 'neutral'> = {
    live: 'success', deploying: 'info', go: 'info', waiting: 'neutral', held: 'warning', ungated: 'warning', failed: 'danger',
}

/**
 * What reaches users: the targets the hub deploys after landings, each with
 * what its next deploy waits for (the landings in line, a hold, the gate), and
 * a hold to keep what lands on main without going live; then every other
 * target's last deploy. The dialog publishes main to one by hand.
 */
function shipping(): m.Children {
    const d = $s.deploys
    if (!d) return <p class="hint">Asking the hub…</p>
    if (!d.targets.length) return <p class="hint">No deploy targets: the hub's config names none.</p>
    const ships = (d.ships ?? []).filter((s) => s.targets.length)
    const auto = new Set(ships.flatMap((s) => s.targets.map((t) => t.target)))
    // A hold is the workspace's, not a project's: every plan carries the same one.
    const held = ships[0]?.held
    return (
        <div class="stack">
            {held ? (
                <Alert tone="warning">
                    Held by {held.by}
                    {held.why ? `: ${held.why}` : ''} ({since(held.at)} ago). What lands goes on main, not live.
                </Alert>
            ) : null}
            {ships.map((ship) => {
                const mine = ship.targets.map((t) => t.target)
                return (
                    <div class="ship__auto">
                        <p class="hint">
                            {ships.length > 1 && ship.repo ? <b>{projectName(ship.repo)}. </b> : null}
                            After each landing the hub deploys {mine.join(', ')} itself, once no other landing is in line (at most {Math.round((ship.max_wait_s ?? 1800) / 60)} minutes later), so one deploy carries them all.
                            {ship.tip ? ` Main is at ${ship.tip.slice(0, 8)}${ship.landed_at ? `, landed ${since(ship.landed_at)} ago` : ''}.` : ''}
                        </p>
                        <ul class="ship">
                            {ship.targets.map((t) => (
                                <li class="ship__row">
                                    <span class="ship__target">{t.target}</span>
                                    <Badge tone={SHIP_TONE[t.state] ?? 'neutral'}>{t.state === 'go' ? 'deploying' : t.state}</Badge>
                                    <span class="hint ship__when">
                                        {t.words}
                                        {t.published && t.state !== 'live' ? ` · serves ${t.published.slice(0, 8)}` : ''}
                                    </span>
                                </li>
                            ))}
                        </ul>
                        {$s.hasKey && held ? (
                            <div class="actions">
                                {confirmButton(`ship-now-${ship.repo ?? ''}`, {
                                    label: 'Deploy now',
                                    armedLabel: `Tap again: deploy ${mine.join(', ')}`,
                                    variant: 'primary',
                                    run: () => act('deploying main', async () => {
                                        for (const t of mine) await api.deploy(t)
                                    }),
                                })}
                            </div>
                        ) : null}
                    </div>
                )
            })}
            {$s.hasKey && ships.length ? (
                <div class="actions">
                    {held
                        ? confirmButton('ship-release', {
                              label: 'Release the hold',
                              armedLabel: 'Tap again to release',
                              run: () => act('deploys after landings resume', () => api.releaseDeploys()),
                          })
                        : confirmButton('ship-hold', {
                              label: 'Hold deploys',
                              armedLabel: 'Tap again to hold',
                              title: 'what lands goes on main, and nothing goes live until you deploy or release',
                              run: () => act('deploys after landings held', () => api.holdDeploys('held on the page')),
                          })}
                </div>
            ) : null}
            <ul class="ship">
                {d.targets
                    .filter((t) => !auto.has(t.target))
                    .map((t) => {
                        const e = lastDeploy(d, t.target)
                        const tone = !e ? 'neutral' : e.kind === 'deploy_published' ? 'success' : e.kind === 'deploy_failed' ? 'danger' : 'info'
                        const word = !e ? 'none this week' : e.kind === 'deploy_published' ? 'live' : e.kind === 'deploy_failed' ? 'failed' : 'deploying'
                        return (
                            <li class="ship__row">
                                <span class="ship__target">{t.target}</span>
                                <Badge tone={tone}>{word}</Badge>
                                <span class="hint ship__when">{e ? `${String(e.sha ?? '').slice(0, 8)} · ${since(Date.parse(e.ts) / 1000)} ago · by hand` : 'by hand'}</span>
                            </li>
                        )
                    })}
            </ul>
            <div>
                <Button size="sm" variant="ghost" onclick={() => ($s.deploysOpen = true)}>
                    Deploy one by hand…
                </Button>
            </div>
        </div>
    )
}

/** The numbers sessions have reserved (`midas reserve`): the next free one of each kind, and who holds one. */
function reserved(): m.Children {
    const atWork = new Set(cards().filter((c) => c.stage !== 'landed').map((c) => c.session))
    const spaces = byNamespace($s.reservations, atWork)
    if (!spaces.length) return <p class="hint">Nothing reserved yet.</p>
    return (
        <ul class="reserved">
            {spaces.map((sp) => (
                <li>
                    <b>{sp.ns}</b> <span class="hint">· next free {sp.next}</span>
                    {sp.open.map((h) => (
                        <div class="hint">
                            #{h.n} {who(h.owner, {max: 32})}
                            {h.why ? ` — ${h.why}` : ''}
                        </div>
                    ))}
                </li>
            ))}
        </ul>
    )
}

/** Each node's last day, asked for when the page opens and every few minutes: held, and how much of it was used. */
const day = local({use: null as Record<string, {held_s: number; busy_s: number}> | null, at: 0})

function loadUse() {
    if (Date.now() - day.at < 120_000) return
    day.at = Date.now()
    api.nodeUse(86400)
        .then((r) => (day.use = r.use ?? {}))
        .catch(() => (day.at = 0))
}

/**
 * The last day per node, as one bar: building (a command ran), held but idle
 * (a session kept it and nobody else could take it: the waste), and free.
 */
function use(ws: WorkspaceState): m.Children {
    loadUse()
    if (!day.use) return <p class="hint">Reading the last day…</p>
    const pct = (s: number) => `${Math.round((100 * s) / 86400)}%`
    let idle = 0
    const rows = ws.nodes.map((n) => {
        const u = day.use![n.id] ?? {held_s: 0, busy_s: 0}
        const held = Math.min(u.held_s, 86400)
        const busy = Math.min(u.busy_s, held)
        idle += held - busy
        return (
            <li class="use__row">
                <span class="use__node">
                    <b>{n.id}</b> <span class="hint">{n.machine}</span>
                </span>
                <span class="use__bar" title={`built on ${dur(busy)}, held but idle ${dur(held - busy)}, free ${dur(86400 - held)}`}>
                    <i class="use__busy" style={{width: pct(busy)}} />
                    <i class="use__idle" style={{width: pct(held - busy)}} />
                </span>
                <span class="hint use__pct">{pct(busy)} used</span>
            </li>
        )
    })
    return (
        <div class="use">
            <ul class="use__list">{rows}</ul>
            <p class="hint">
                <span class="use__key use__key--busy" /> a command ran <span class="use__key use__key--idle" /> held but idle · {dur(idle)} held idle in all, the last day
            </p>
        </div>
    )
}

/** The periods the power card shows: how far back, the line's step, and what each bar is. */
const PERIODS = {
    day: {label: 'day', span: 86400, step: 300, bar: 'hour'},
    week: {label: 'week', span: 7 * 86400, step: 3600, bar: 'day'},
    month: {label: '30 days', span: 30 * 86400, step: 3600, bar: 'day'},
    year: {label: 'year', span: 365 * 86400, step: 86400, bar: 'month'},
} as const
type Period = keyof typeof PERIODS

/** The power history of each period, asked for when it is shown and every few minutes. */
const power = local({period: 'day' as Period, data: {} as Partial<Record<Period, Power>>, at: {} as Partial<Record<Period, number>>, failed: false})

function loadPower() {
    const p = power.period
    if (Date.now() - (power.at[p] ?? 0) < 120_000) return
    power.at[p] = Date.now()
    api.power(PERIODS[p].span, PERIODS[p].step)
        .then((d) => {
            power.data[p] = d
            power.failed = false
        })
        .catch(() => {
            power.at[p] = 0
            power.failed = true
        })
}

/** The start of the local hour, day or month a time falls in, in seconds. */
function startOf(t: number, unit: 'hour' | 'day' | 'month'): number {
    const d = new Date(t * 1000)
    if (unit === 'month') d.setDate(1)
    if (unit === 'hour') d.setMinutes(0, 0, 0)
    else d.setHours(0, 0, 0, 0)
    return d.getTime() / 1000
}

/** The `n` hours, days or months up to the one `t` falls in, oldest first. */
function lastUnits(t: number, unit: 'hour' | 'day' | 'month', n: number): number[] {
    const out = [startOf(t, unit)]
    while (out.length < n) {
        const d = new Date(out[0]! * 1000)
        if (unit === 'hour') d.setHours(d.getHours() - 1)
        else if (unit === 'day') d.setDate(d.getDate() - 1)
        else d.setMonth(d.getMonth() - 1)
        out.unshift(d.getTime() / 1000)
    }
    return out
}

const clock = (t: number) => new Date(t * 1000).toLocaleTimeString(undefined, {hour: '2-digit', minute: '2-digit'})
const dateTime = (t: number) => `${dayLabel(new Date(t * 1000))}, ${clock(t)}`
const monthName = (t: number) => new Date(t * 1000).toLocaleDateString(undefined, {month: 'short', year: '2-digit'})
const watts = (v: number) => `${v.toFixed(v < 10 ? 1 : 0)} W`
const kwh = (v: number) => `${v.toFixed(2)} kWh`

/**
 * What each machine draws (power.rs): now, and over a day, a week, 30 days or
 * a year, as a line of watts and bars of kWh. The chip's power as the machine
 * measures it, not the socket's.
 */
function powerCard(): m.Children {
    loadPower()
    const period = PERIODS[power.period]
    const w = power.data[power.period]
    const pick = (
        <FieldSegmented
            model={bind(power, 'period')}
            size="sm"
            options={(Object.keys(PERIODS) as Period[]).map((k) => ({value: k, label: PERIODS[k].label}))}
        />
    )
    if (!w) return <div class="stack">{pick}<p class="hint">{power.failed ? 'The hub did not answer; trying again.' : 'Reading the power history…'}</p></div>
    const names = Object.keys(w.machines).sort()
    if (!names.length) {
        return <p class="hint">No machine reports its power yet. Each machine's owner runs <code>sudo midas setup &lt;node&gt;</code> once more to start it.</p>
    }
    const series = names.map((n, i) => ({label: n, color: SERIES[i % SERIES.length]!}))
    const pts = (n: string) => w.machines[n]?.points ?? []
    const whSince = (n: string, t: number) => pts(n).filter((p) => p[0] >= t).reduce((a, p) => a + p[2], 0)
    // Measured since: the first point of any machine, when that is later than the period's start.
    const first = Math.min(...names.map((n) => pts(n)[0]?.[0] ?? w.to))
    const counted = Math.max(1, w.to - Math.max(w.from, first))
    // Each step's watt-hours to the hour, day or month it began in.
    const unit = period.bar
    const keys = lastUnits(w.to, unit, unit === 'hour' ? 24 : unit === 'month' ? 12 : Math.round(period.span / 86400))
    const perUnit = names.map((n) => {
        const out = new Map<number, number>()
        for (const p of pts(n)) out.set(startOf(p[0], unit), (out.get(startOf(p[0], unit)) ?? 0) + p[2] / 1000)
        return out
    })
    const long = period.span > 86400
    return (
        <div class="stack">
            {pick}
            <ul class="power">
                {names.map((n) => {
                    const mm = w.machines[n]!
                    const total = whSince(n, w.from)
                    return (
                        <li>
                            <b>{n}</b>{' '}
                            <span class="hint">
                                {mm.now ? `${watts(mm.now.w)} now` : 'not reporting'} · {kwh(whSince(n, w.to - 86400) / 1000)} the last day
                                {long ? ` · ${kwh(total / 1000)} the last ${period.label}` : ''} (on average {watts((total * 3600) / counted)})
                            </span>
                        </li>
                    )
                })}
            </ul>
            {first > w.from + period.step ? <p class="hint">Measured since {dayLabel(new Date(first * 1000))}: the period before it is empty.</p> : null}
            <p class="hint">Watts, {period.step >= 86400 ? 'the average of each day, ' : ''}the last {period.label}</p>
            <Lines
                series={series}
                points={names.map((n) => pts(n).map((p) => [p[0], p[1]] as [number, number]))}
                from={w.from}
                to={w.to}
                step={w.step}
                format={watts}
                label={period.step >= 86400 ? (t) => dayLabel(new Date(t * 1000)) : long ? dateTime : clock}
                tick={long ? (t) => dayLabel(new Date(t * 1000)) : clock}
            />
            <p class="hint">kWh per {unit}, the last {period.label}</p>
            <Bars
                days={keys}
                series={series}
                value={(k) => perUnit.map((byUnit) => byUnit.get(k) ?? 0)}
                format={kwh}
                axis={(v) => String(Math.round(v * 100) / 100)}
                label={unit === 'hour' ? clock : unit === 'month' ? monthName : undefined}
            />
            <p class="hint">
                What each machine's chip draws (CPU and GPU, from {[...new Set(names.map((n) => w.machines[n]!.source).filter(Boolean))].join(', ')}), measured on the machine once a minute. The wall socket's is a few watts more: memory, disk, fans, the power supply. A gap is a machine asleep, off or not reporting.
            </p>
        </div>
    )
}

/**
 * The paired devices (device.rs): not nodes, which build, nor the runner, which
 * runs the agents, but apps on a phone whose tools sessions call through the
 * hub while the app is open. Pairing and forgetting stay in Settings.
 */
class Devices extends MithrilComponent {
    s = local({list: null as Device[] | null})
    timer = 0

    oninit() {
        void this.load()
        // Online or not changes as the app opens and closes.
        this.timer = window.setInterval(() => void this.load(), 10000)
    }

    onremove() {
        window.clearInterval(this.timer)
    }

    async load() {
        try {
            this.s.list = (await api.devices()).devices
        } catch {
            // Kept as last read; the next tick tries again.
        }
    }

    view() {
        const list = this.s.list
        return (
            <Card>
                <h3 class="card__title">Devices</h3>
                <p class="hint">Apps on a phone whose tools sessions call while the app is open: a screenshot, the camera, the sensors. They build nothing. Pair one in Settings ▸ This device.</p>
                {list == null ? (
                    <p class="hint">Asking the hub…</p>
                ) : !list.length ? (
                    <p class="hint">None paired.</p>
                ) : (
                    <ul class="devices">
                        {list.map((d) => (
                            <li class="devices__row">
                                <span class={`devices__dot${d.online ? ' devices__dot--on' : ''}`} />
                                <span class="devices__name">
                                    <b>{d.name}</b>{' '}
                                    <span class="hint">
                                        {d.app} {d.build?.version ?? d.version} · {d.account} · {d.online ? 'online' : d.seen ? `seen ${age(d.seen)} ago` : 'never linked'} ·{' '}
                                        {d.tools.length} tools
                                    </span>
                                </span>
                            </li>
                        ))}
                    </ul>
                )}
            </Card>
        )
    }
}

/**
 * The machines and what reaches users: what is wrong first, then the network
 * and its nodes (tap one for its controls), the paired devices, the deploys, and the numbers
 * sessions reserved. Who waits for a node is shown here only when it is long.
 */
export class Workspace extends MithrilComponent {
    view() {
        const f = $s.workspace
        if (!f) return <p class="hint">Asking the hub…</p>
        // Services, a tab of its own (/workspace/services): the deployed targets' health over time (watch.rs).
        if (here() === 'workspace/services') {
            return (
                <div class="stack workspace">
                    <Services />
                </div>
            )
        }
        // Deploys, a tab of its own (/workspace/deploys): what reaches users, and the dialog that publishes main.
        if (here() === 'workspace/deploys') {
            return (
                <div class="stack workspace">
                    <Card>
                        <h3 class="card__title">Shipping</h3>
                        {shipping()}
                    </Card>
                    <DeployDialog />
                </div>
            )
        }
        const wrong = problems(f)
        return (
            <div class="stack workspace">
                {wrong.length ? (
                    <Alert tone="warning">
                        {wrong.map((w) => (
                            <div>{w}</div>
                        ))}
                    </Alert>
                ) : null}
                <Card>
                    <p class="hint">Tap a node for its details and controls.</p>
                    <Network workspace={f} />
                </Card>
                <Devices />
                <Card>
                    <h3 class="card__title">The last day</h3>
                    {use(f)}
                </Card>
                <Card>
                    <h3 class="card__title">Power</h3>
                    {powerCard()}
                </Card>
                <Card>
                    <h3 class="card__title">Reserved numbers</h3>
                    <p class="hint">Numbers no two branches may share, such as a database migration's; sessions take them with <code>midas reserve</code>.</p>
                    {reserved()}
                </Card>
                <NodeDialog workspace={f} />
                <DeployDialog />
            </div>
        )
    }
}