git clone https://garage44.eu/jeroen/midas.git.. /web/src/components/home.tsx
import m, {MithrilComponent} from '@garage44/mithril'
import {Badge, Button, FieldSelect, FieldText} from '@garage44/mithril/components'
import {confirmButton} from '@/components/confirm'
import {Decided} from '@/components/decisions'
import {icon} from '@/components/icons'
import {NeedsYou, waitingForYou} from '@/components/needs'
import {stuck} from '@/components/nodeline'
import {journeyOf, landedItems, landedToday, landingLane} from '@/components/landing'
import type {LaneItem} from '@/components/landing'
import {placeChip} from '@/components/place'
import {act} from '@/lib/actions'
import {api} from '@/lib/api'
import {age, ahead, now, shortName, span} from '@/lib/format'
import {nameOf} from '@/lib/names'
import {askProjects, inView, projectFilter, projectTag, reposOf, shown} from '@/lib/projects'
import {shipOf, underway} from '@/lib/landing'
import {flipList} from '@/lib/motion'
import {bind, local} from '@/lib/reactive'
import {go} from '@/lib/route'
import {STATUS, awaitsPerson, turnOf} from '@/lib/status'
import {$s} from '@/lib/store'
import {background, cards, connect, hosted, live, todos} from '@/lib/stream'
import type {BoardCard, BoardTodo, Hosted} from '@/lib/stream'
import {focusCard} from '@/components/focus'
/**
* Home: what waits for the person, then every session at work with where it
* stands, then what is left for the next session. It replaces the board's six
* lanes: which node a session builds on and its place in line are midas's
* business, shown only when one has waited long enough to need a hand.
*/
/** The steps a session's bar shows: at work, landing (in line, or its gate running), on main, and live. */
const STEP: Record<BoardCard['stage'], number> = {working: 0, waiting_for_node: 0, on_node: 0, waiting_to_land: 1, landing: 1, landed: 2}
/** Live is a step only where the hub deploys after landings: elsewhere on main is the end. */
const shipped = (c: BoardCard) => !!shipOf($s.deploys?.ships, c.repo ? [c.repo] : [])
const steps = (c: BoardCard) => (shipped(c) ? ['working', 'landing', 'on main', 'live'] : ['working', 'landing', 'on main'])
const stepOf = (c: BoardCard) => (c.stage === 'landed' && c.live ? 3 : STEP[c.stage])
/** A session still at work, as Home counts one: not ended, archived or a record imported. */
const atWork = (h: Hosted) => h.status !== 'stopped' && h.status !== 'failed' && !h.archived && !h.imported
/** The projects a card's work is in: its session's, as midas runs or mirrors it, else as its start said. */
const repoOf = (c: BoardCard, h: Hosted | undefined): string[] => (h && reposOf(h).length ? reposOf(h) : c.repo ? [c.repo] : [])
function open(c: BoardCard, h: Hosted | undefined) {
if (h) {
go(`sessions/${h.id}`)
return
}
// A session midas does not run (a CLI's, a Remote Control one): its conversation, where it has one.
const link = nameOf(c.session).link
if (link) window.open(link, '_blank', 'noopener')
}
/** Where a session is, in a few words: what it is doing, or where it is in line. */
function where(c: BoardCard, h: Hosted | undefined): string {
switch (c.stage) {
case 'waiting_for_node':
return `waiting for ${c.wants === 'any' || !c.wants ? 'a node' : c.wants}${c.position && c.position > 1 ? `, #${c.position} in line` : ''}`
case 'waiting_to_land':
return c.position && c.position > 1 ? `#${c.position} to land` : 'next to land'
case 'landing':
return c.step ?? `landing${c.node ? ` · checks on ${c.node}` : ''}`
case 'landed':
return `${c.live ? 'live' : shipped(c) ? 'on main, in the next deploy' : 'on main'}${c.sha ? ` · ${c.sha.slice(0, 8)}` : ''}`
default: {
const doing = h ? (h.doing ?? (h.status === 'waiting' ? background(h) : null)) : c.busy ? (c.intent ?? c.purpose ?? 'running a command') : null
const on = c.stage === 'on_node' && c.node ? ` · on ${c.node}` : ''
return doing ? `${shortName(doing, 80)}${on}` : h ? `${STATUS[h.status].label.toLowerCase()}${on}` : `working${on}`
}
}
}
/** Its steps as a bar: the ones done in the accent, the one it is in in the brand colour; the last one reached is done. */
export function stepsBar(c: BoardCard, moving = false): m.Children {
const all = steps(c)
const at = Math.min(stepOf(c), all.length - 1)
const end = at === all.length - 1
return (
<div class="run__steps" title={all[at]} aria-label={`${all[at]} (step ${at + 1} of ${all.length})`}>
{all.map((_, i) => (
<i class={i < at || (end && i === at) ? 'is-done' : i === at ? `is-now${moving ? ' is-moving' : ''}` : ''} />
))}
</div>
)
}
/** Moving: busy with something now (a sheen runs along its step), rather than waiting on someone. */
function moving(c: BoardCard, h: Hosted | undefined): boolean {
if (c.stage === 'landing') return true
if (c.stage !== 'working' && c.stage !== 'on_node') return false
return h ? h.status === 'working' || h.status === 'starting' || h.status === 'queued' : !!c.busy
}
/** Idle this long, a session folds out of Running into its "idle" list. */
const IDLE_FOLD_S = 86400
/** It asks the person something: a permission (its own or a thread's in its checkout), or a decision. */
const asksOf = (c: BoardCard, h: Hosted | undefined, others: Hosted[] = []) =>
h?.status === 'needs_permission' || others.some((o) => o.status === 'needs_permission') || c.badges.decisions.length > 0 || (!!h && awaitsPerson(h))
/** Idle: its turn is over, nothing runs for it and it asks nothing. */
const idles = (c: BoardCard, h: Hosted | undefined) => h?.status === 'waiting' && (c.stage === 'working' || c.stage === 'on_node') && !h.doing
/**
* When it last did something: now while it works, else when its last turn
* ended (`turnOf`, which a runner starting again does not move), or for a
* session midas does not run, when its hooks, builds and takes last showed it.
*/
function activeAt(c: BoardCard, h: Hosted | undefined): number {
if (moving(c, h) || h?.status === 'needs_permission') return now()
return h ? now() - turnOf(h).idle_s : (c.active ?? c.since ?? now())
}
/** Idle for more than a day, asking nothing: folded under Running's "idle" list. */
const idleLong = (c: BoardCard, h: Hosted | undefined) =>
!asksOf(c, h) && !moving(c, h) && (c.stage === 'working' || c.stage === 'on_node') && now() - activeAt(c, h) > IDLE_FOLD_S
/** One session at work: its name, where it is, its steps, the open ends it took on; the whole row opens it. */
function row(c: BoardCard, h: Hosted | undefined, others: Hosted[], ends: BoardTodo[]): m.Children {
const asks = asksOf(c, h, others)
const title = h?.title ?? nameOf(c.session).title
const busy = moving(c, h)
const waits = !asks && idles(c, h)
const idle_s = now() - activeAt(c, h)
// Idle is said quietly, however recent: only a session that asks is orange (status.ts `State`).
const tag = shown() ? null : projectTag(repoOf(c, h))
// Its age: how long this turn has run while it works, how long it has been in this step when
// it is in line or landing. An idle one says how long in its meta line.
const turn = h && busy && h.active != null
const ageOf = waits
? {text: null, title: ''}
: c.stage === 'working' || c.stage === 'on_node'
? turn
? {text: age(h.active), title: 'this turn, so far'}
: {text: age(c.active ?? c.since), title: h ? 'since it last did something' : 'since it was last seen at work'}
: {text: age(c.since), title: 'in this step for'}
return (
<li class={`run${asks ? ' run--asks' : ''}`} key={c.session} data-key={c.session} onclick={() => open(c, h)}>
<div class="run__head">
<span class={`run__dot${busy ? ' run__dot--busy' : asks ? ' run__dot--you' : ''}`} aria-hidden="true" />
<span class="run__title">{shortName(title, 90)}</span>
{ageOf.text ? (
<span class="run__age" title={ageOf.title}>
{ageOf.text}
</span>
) : null}
</div>
<div class="run__meta">
{tag}
{h?.local ? placeChip(h) : null}
{asks && h && awaitsPerson(h) && h.status !== 'needs_permission' ? (
<span class="run__pill" title={h.awaits!.text}>
{icon.key()} Waits on you
</span>
) : asks ? (
<span class="run__pill">Asks you</span>
) : h?.wake && !busy ? (
<span class="run__where" title={`what it does then: ${h.wake.text}`}>
{icon.clock()} carries on {ahead(h.wake.at)}
</span>
) : waits ? (
<span class="run__where" title="its last turn ended this long ago, asking nothing">
idle {span(idle_s)}
</span>
) : (
<span class={`run__where${busy ? ' run__where--live' : ''}`}>{where(c, h)}</span>
)}
</div>
{stepsBar(c, busy)}
{others.length ? (
<div class="run__also hint">
also here:{' '}
{others.map((o, i) => [
i ? ', ' : '',
<a
href={`/sessions/${o.id}`}
onclick={(e: Event) => e.stopPropagation()}
>
{shortName(o.title, 40)}
</a>,
])}
</div>
) : null}
{ends.map((t) => (
<div class="run__end" key={t.id} title={t.text}>
<Badge tone="success">left for it</Badge> {shortName(t.text, 120)}
</div>
))}
{stuck(c)}
</li>
)
}
/** An open end: left for the next session on a machine, which is shown it when it starts. */
function todo(t: BoardTodo): m.Children {
return (
<li class={`upnext${t.claimed_by ? ' upnext--picked' : ''}`} key={t.id} data-key={t.id}>
<div class="upnext__text">{shortName(t.text, 200)}</div>
<div class="upnext__foot">
<Badge tone={t.claimed_by ? 'success' : 'info'}>
{t.claimed_by ? `being done by ${shortName(nameOf(t.claimed_by).title, 30)}` : t.for === 'any' ? 'next session' : `next ${t.for} session`}
</Badge>
<span class="run__age" title={`left by ${t.by}`}>
{age(t.at)}
</span>
{$s.hasKey ? confirmButton(`done-${t.id}`, {label: '✓ done', armedLabel: 'Tap again: done', class: 'upnext__done', run: () => act(`${t.id} done`, () => api.doneTodo(t.id))}) : null}
</div>
</li>
)
}
/** Open ends done in the last week, folded: what became of them. */
class DoneTodos extends MithrilComponent {
s = local({open: false})
view() {
const done = $s.todos.filter((t) => t.done_at && now() - t.done_at < 7 * 86400).sort((a, b) => (b.done_at ?? 0) - (a.done_at ?? 0))
if (!done.length) return null
return (
<div class="home__more">
<button class="home__link" type="button" onclick={() => (this.s.open = !this.s.open)}>
{this.s.open ? 'hide done' : `${done.length} done this week`}
</button>
{this.s.open ? (
<ul class="home__list home__list--quiet">
{done.map((t) => (
<li class="upnext upnext--done">
<div class="upnext__text">✓ {shortName(t.text, 160)}</div>
<div class="hint">
{t.done_note ? shortName(t.done_note, 120) : 'done'} · {age(t.done_at)} ago
</div>
</li>
))}
</ul>
) : null}
</div>
)
}
}
/**
* Who an open end can be left for: a caller's name (the machine a session runs
* on). The hub does not list its callers, so these are the usual ones and any
* an open end was already left for.
*/
function targets(): {value: string; label: string}[] {
const known = new Set(['workstation', 'agent', ...$s.todos.map((t) => t.for)])
known.delete('any')
return [...[...known].map((v) => ({value: v, label: `next ${v === 'agent' ? 'agent container' : v} session`})), {value: 'any', label: 'next session anywhere'}]
}
/** Leave something for a next session. */
class AddTodo extends MithrilComponent {
s = local({open: false, text: '', target: 'workstation'})
view() {
if (!$s.hasKey) return null
if (!this.s.open) {
return (
<button class="home__ghost" type="button" onclick={() => (this.s.open = true)}>
+ Leave one for later
</button>
)
}
const add = () => {
const text = this.s.text.trim()
if (!text) return
this.s.text = ''
this.s.open = false
void act(`left for the next ${this.s.target} session`, () => api.addTodo(this.s.target, text))
}
return (
<div class="upnext__add">
<FieldText model={bind(this.s, 'text')} placeholder="what is left to do?" />
<FieldSelect model={bind(this.s, 'target')} options={targets()} />
<span class="upnext__add-actions">
<Button size="sm" variant="primary" disabled={!this.s.text.trim()} onclick={add}>
Leave it
</Button>
<Button size="sm" variant="ghost" onclick={() => (this.s.open = false)}>
Cancel
</Button>
</span>
</div>
)
}
}
type Row = {c: BoardCard; h: Hosted | undefined}
/** Sessions idle for more than a day, folded under their count: still open, nothing asked of the person. */
class Idle extends MithrilComponent<{these: Row[]; row: (r: Row) => m.Children}> {
s = local({open: false})
view({attrs}: m.Vnode<{these: Row[]; row: (r: Row) => m.Children}>) {
const these = attrs.these
if (!these.length) return null
return (
<div class="home__more">
<button class="home__link" type="button" onclick={() => (this.s.open = !this.s.open)}>
{this.s.open ? 'hide the idle ones' : `${these.length} idle`}
</button>
{this.s.open ? <ul class="home__list home__list--quiet">{these.map(attrs.row)}</ul> : null}
</div>
)
}
}
/** The number of something, as a small chip in the calm card: "3 at work". */
const stat = (n: number, what: string) => (
<span class="home__stat">
<b>{n}</b> {what}
</span>
)
/** A check mark: nothing needs the person. */
const check = (
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M5 12.5l4.5 4.5L19 7.5" />
</svg>
)
const plus = (
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true">
<path d="M12 5v14M5 12h14" />
</svg>
)
/** New session, from Home and the list: folds to its + while the page scrolls down, and opens again on the way back up. */
export class NewSessionButton extends MithrilComponent {
folded = local({value: false})
scroller: HTMLElement | null = null
lastY = 0
onscroll = () => {
const y = this.scroller?.scrollTop ?? 0
if (Math.abs(y - this.lastY) < 6) return
this.folded.value = y > 24 && y > this.lastY
this.lastY = y
}
oncreate() {
this.scroller = document.querySelector('.m-shell__content')
this.scroller?.addEventListener('scroll', this.onscroll, {passive: true})
}
onremove() {
this.scroller?.removeEventListener('scroll', this.onscroll)
}
view() {
return (
<a class={`fab${this.folded.value ? ' fab--folded' : ''}`} href="/sessions/new" title="New session" aria-label="New session">
{plus}
<span class="fab__label">New session</span>
</a>
)
}
}
export class Home extends MithrilComponent {
tick = 0
oninit() {
connect()
askProjects()
// The ages ("12m") move with the clock, not only with the hub.
this.tick = window.setInterval(() => m.redraw(), 15000)
}
onremove() {
clearInterval(this.tick)
}
view() {
const all = cards()
// Several sessions can share an owner (an editor's, in one checkout): the row is the latest
// one still at work's, and only when none is, the latest one's.
const byOwner = new Map(
[...hosted()].sort((a, b) => Number(atWork(a)) - Number(atWork(b)) || a.updated - b.updated).map((h) => [h.owner, h]),
)
const others = (owner: string) => hosted().filter((h) => h.owner === owner && h !== byOwner.get(owner) && atWork(h))
const these = all.map((c) => ({c, h: byOwner.get(c.session)})).filter(({c, h}) => inView(repoOf(c, h)))
const asks = ({c, h}: Row) => Number(asksOf(c, h, others(c.session)))
// What asks first, then the furthest along (landing before working), then the most recently
// active: a session that has waited on the person for days sinks below one that just answered.
// On its way to live (in line, checked, on main): the Landing lane's, not Running's.
const onWay: LaneItem[] = these.map(({c, h}) => ({c, h, j: journeyOf(h, c)})).filter((x): x is LaneItem => underway(x.j))
const way = new Set(onWay.map((x) => x.c.session))
const unlanded = these
.filter(({c}) => c.stage !== 'landed' && !way.has(c.session))
.sort((a, b) => asks(b) - asks(a) || stepOf(b.c) - stepOf(a.c) || activeAt(b.c, b.h) - activeAt(a.c, a.h))
// Set to carry on later, its turn over and asking nothing: Scheduled, the soonest first, not Running or idle.
const later = ({c, h}: Row) => !!h?.wake && !asksOf(c, h, others(c.session)) && !moving(c, h)
const scheduled = unlanded.filter(later).sort((a, b) => (a.h?.wake?.at ?? 0) - (b.h?.wake?.at ?? 0))
const running = unlanded.filter(({c, h}) => !later({c, h}) && !idleLong(c, h))
const idle = unlanded.filter(({c, h}) => !later({c, h}) && idleLong(c, h))
const landed = landedItems((repos) => inView(repos))
// An open end a session at work took on is shown on that session's row, not again under Up
// next; one whose session is no longer at work stays there, as being done by it.
const atWorkHere = new Set(all.filter((c) => c.stage !== 'landed').map((c) => c.session))
const taken = (t: BoardTodo) => !!t.claimed_by && atWorkHere.has(t.claimed_by)
const ends = (session: string) => todos().filter((t) => taken(t) && t.claimed_by === session)
const next = todos().filter((t) => !taken(t))
const waiting = waitingForYou().length
return (
<div class="home">
{projectFilter((repo) => all.filter((c) => c.stage !== 'landed' && repoOf(c, byOwner.get(c.session)).includes(repo)).length)}
{!live.loaded ? (
<p class="hint">Connecting to the hub…</p>
) : waiting || $s.admin?.window ? (
NeedsYou()
) : (
<div class="home__calm">
<span class="home__calm-mark">{check}</span>
<span class="home__calm-text">
<b>Nothing needs you</b>
<span class="home__stats">
{running.length ? stat(running.length, 'at work') : <span class="hint">Nothing at work</span>}
{onWay.length ? stat(onWay.length, 'landing') : null}
{scheduled.length ? stat(scheduled.length, 'scheduled') : null}
{landed.length ? stat(landed.length, 'landed today') : null}
</span>
</span>
</div>
)}
{focusCard()}
<Decided />
{landingLane(onWay, ({c, h}) => open(c, h))}
<section class="home__section">
<h3 class="home__head">
Running <span class="home__count">{running.length}</span>
</h3>
{running.length ? (
<ul class="home__list" {...flipList}>
{running.map(({c, h}) => row(c, h, others(c.session), ends(c.session)))}
</ul>
) : (
<p class="hint">{idle.length ? 'Nothing active in the last day.' : 'No session at work. Start one with +.'}</p>
)}
<Idle these={idle} row={({c, h}: Row) => row(c, h, others(c.session), ends(c.session))} />
</section>
{scheduled.length ? (
<section class="home__section">
<h3 class="home__head" title="sessions set to carry on by themselves later: midas tells each what it was to do at its time">
Scheduled <span class="home__count">{scheduled.length}</span>
</h3>
<ul class="home__list" {...flipList}>
{scheduled.map(({c, h}) => row(c, h, others(c.session), ends(c.session)))}
</ul>
</section>
) : null}
{landedToday(landed)}
<section class="home__section">
<h3 class="home__head" title="work left for the next session on a machine: it is shown it when it starts, and does it first">
Up next <span class="home__count">{next.length}</span>
</h3>
{next.length ? (
<ul class="home__list" {...flipList}>
{next.map(todo)}
</ul>
) : null}
<AddTodo />
<DoneTodos />
</section>
<NewSessionButton />
</div>
)
}
}