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 = {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 (
{all.map((_, i) => ( ))}
) } /** 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 (
  • open(c, h)}>
    {tag} {h?.local ? placeChip(h) : null} {asks && h && awaitsPerson(h) && h.status !== 'needs_permission' ? ( {icon.key()} Waits on you ) : asks ? ( Asks you ) : h?.wake && !busy ? ( {icon.clock()} carries on {ahead(h.wake.at)} ) : waits ? ( idle {span(idle_s)} ) : ( {where(c, h)} )}
    {stepsBar(c, busy)} {others.length ? (
    also here:{' '} {others.map((o, i) => [ i ? ', ' : '', e.stopPropagation()} > {shortName(o.title, 40)} , ])}
    ) : null} {ends.map((t) => (
    left for it {shortName(t.text, 120)}
    ))} {stuck(c)}
  • ) } /** 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 (
  • {shortName(t.text, 200)}
    {t.claimed_by ? `being done by ${shortName(nameOf(t.claimed_by).title, 30)}` : t.for === 'any' ? 'next session' : `next ${t.for} session`} {age(t.at)} {$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}
  • ) } /** 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 (
    {this.s.open ? (
      {done.map((t) => (
    • ✓ {shortName(t.text, 160)}
      {t.done_note ? shortName(t.done_note, 120) : 'done'} · {age(t.done_at)} ago
    • ))}
    ) : null}
    ) } } /** * 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 ( ) } 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 (
    ) } } 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 (
    {this.s.open ?
      {these.map(attrs.row)}
    : null}
    ) } } /** The number of something, as a small chip in the calm card: "3 at work". */ const stat = (n: number, what: string) => ( {n} {what} ) /** A check mark: nothing needs the person. */ const check = ( ) const plus = ( ) /** 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 ( {plus} New session ) } } 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 (
    {projectFilter((repo) => all.filter((c) => c.stage !== 'landed' && repoOf(c, byOwner.get(c.session)).includes(repo)).length)} {!live.loaded ? (

    Connecting to the hub…

    ) : waiting || $s.admin?.window ? ( NeedsYou() ) : (
    {check} Nothing needs you {running.length ? stat(running.length, 'at work') : Nothing at work} {onWay.length ? stat(onWay.length, 'landing') : null} {scheduled.length ? stat(scheduled.length, 'scheduled') : null} {landed.length ? stat(landed.length, 'landed today') : null}
    )} {focusCard()} {landingLane(onWay, ({c, h}) => open(c, h))}

    Running {running.length}

    {running.length ? (
      {running.map(({c, h}) => row(c, h, others(c.session), ends(c.session)))}
    ) : (

    {idle.length ? 'Nothing active in the last day.' : 'No session at work. Start one with +.'}

    )} row(c, h, others(c.session), ends(c.session))} />
    {scheduled.length ? (

    Scheduled {scheduled.length}

      {scheduled.map(({c, h}) => row(c, h, others(c.session), ends(c.session)))}
    ) : null} {landedToday(landed)}

    Up next {next.length}

    {next.length ? (
      {next.map(todo)}
    ) : null}
    ) } }