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 = { asleep: 'neutral', free: 'success', busy: 'info', bot: 'info', drained: 'warning', offline: 'danger', } const METER_TONE: Record = {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 } /** A control that needs the caller key says so instead of failing. */ function needsKey() { return $s.hasKey ? null :

To change anything here, log in: the mark at the top right on a phone, the foot of the menu wider.

} /** 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 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 ? from an older recipe: its owner runs sudo midas setup {n.id} : '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}` : not said], ['last command', {lease.last_command ?? '–'}], ) 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 (

{STATE_ICON[st]} {STATE_LABEL[st]}

{rows.map(([k, v]) => [
{k}
,
{v}
])}
{needsKey()}
{n.drained ? ( ) : (
)} {lease ? ( this.s.confirmRelease ? ( ) : ( ) ) : null}
) } } /** 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 const last = (target: string) => lastDeploy(d, target) return (

The last week. A deploy publishes the tip of main, once the gate passed it.

{needsKey()} t.target} rows={d.targets} columns={[ {key: 'target', label: 'target', cell: (t: {target: string}) => {t.target}}, { key: 'last', label: 'last', cell: (t: {target: string}) => { const e = last(t.target) if (!e) return none this week const tone = e.kind === 'deploy_published' ? 'success' : e.kind === 'deploy_failed' ? 'danger' : 'info' const label = e.kind.replace('deploy_', '') return ( {label} {String(e.sha ?? '').slice(0, 8)} · {when(e.ts)} ) }, }, { key: 'go', label: '', align: 'end', cell: (t: {target: string}) => this.s.confirm === t.target ? ( ) : ( ), }, ]} /> ) } } /** 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 = { 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

Asking the hub…

if (!d.targets.length) return

No deploy targets: the hub's config names none.

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 (
{held ? ( Held by {held.by} {held.why ? `: ${held.why}` : ''} ({since(held.at)} ago). What lands goes on main, not live. ) : null} {ships.map((ship) => { const mine = ship.targets.map((t) => t.target) return (

{ships.length > 1 && ship.repo ? {projectName(ship.repo)}. : 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` : ''}.` : ''}

    {ship.targets.map((t) => (
  • {t.target} {t.state === 'go' ? 'deploying' : t.state} {t.words} {t.published && t.state !== 'live' ? ` · serves ${t.published.slice(0, 8)}` : ''}
  • ))}
{$s.hasKey && held ? (
{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) }), })}
) : null}
) })} {$s.hasKey && ships.length ? (
{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')), })}
) : null}
    {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 (
  • {t.target} {word} {e ? `${String(e.sha ?? '').slice(0, 8)} · ${since(Date.parse(e.ts) / 1000)} ago · by hand` : 'by hand'}
  • ) })}
) } /** 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

Nothing reserved yet.

return (
    {spaces.map((sp) => (
  • {sp.ns} · next free {sp.next} {sp.open.map((h) => (
    #{h.n} {who(h.owner, {max: 32})} {h.why ? ` — ${h.why}` : ''}
    ))}
  • ))}
) } /** 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 | 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

Reading the last day…

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 (
  • {n.id} {n.machine} {pct(busy)} used
  • ) }) return (
      {rows}

    a command ran held but idle · {dur(idle)} held idle in all, the last day

    ) } /** 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>, at: {} as Partial>, 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 = ( ({value: k, label: PERIODS[k].label}))} /> ) if (!w) return
    {pick}

    {power.failed ? 'The hub did not answer; trying again.' : 'Reading the power history…'}

    const names = Object.keys(w.machines).sort() if (!names.length) { return

    No machine reports its power yet. Each machine's owner runs sudo midas setup <node> once more to start it.

    } 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() 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 (
    {pick}
      {names.map((n) => { const mm = w.machines[n]! const total = whSince(n, w.from) return (
    • {n}{' '} {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)})
    • ) })}
    {first > w.from + period.step ?

    Measured since {dayLabel(new Date(first * 1000))}: the period before it is empty.

    : null}

    Watts, {period.step >= 86400 ? 'the average of each day, ' : ''}the last {period.label}

    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} />

    kWh per {unit}, the last {period.label}

    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} />

    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.

    ) } /** * 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 (

    Devices

    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.

    {list == null ? (

    Asking the hub…

    ) : !list.length ? (

    None paired.

    ) : (
      {list.map((d) => (
    • {d.name}{' '} {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
    • ))}
    )}
    ) } } /** * 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

    Asking the hub…

    // Services, a tab of its own (/workspace/services): the deployed targets' health over time (watch.rs). if (here() === 'workspace/services') { return (
    ) } // Deploys, a tab of its own (/workspace/deploys): what reaches users, and the dialog that publishes main. if (here() === 'workspace/deploys') { return (

    Shipping

    {shipping()}
    ) } const wrong = problems(f) return (
    {wrong.length ? ( {wrong.map((w) => (
    {w}
    ))}
    ) : null}

    Tap a node for its details and controls.

    The last day

    {use(f)}

    Power

    {powerCard()}

    Reserved numbers

    Numbers no two branches may share, such as a database migration's; sessions take them with midas reserve.

    {reserved()}
    ) } }