garage44.eu/jeroen/midas

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

.. /web/src/components/history.tsx

raw

import m, {MithrilComponent} from '@garage44/mithril'
import {Badge, Card, FieldSegmented, Spinner, Table} from '@garage44/mithril/components'

import {Bars, SERIES} from '@/components/charts'
import {runnersHistory} from '@/components/runners'
import {day, dur, now, shortName, when} from '@/lib/format'
import {machines} from '@/lib/nodes'
import {askProjects, projectFilter, projectName, shown as shownProject} from '@/lib/projects'
import {buckets, buildHoursByDay, commandTable, days, deployTimes, headline, narrow, saidByDay, saidByHour, talkHeadline, timeGoes, topCounts, typical, waitsByDay} from '@/lib/stats'
import type {CommandRow, CountRow, TargetTime} from '@/lib/stats'
import {$s, history, loadHistory} from '@/lib/store'
import type {Session, Tally} from '@/lib/types'

const hours = (v: number) => (v >= 10 ? `${Math.round(v)}h` : v >= 1 ? `${v.toFixed(1)}h` : `${Math.round(v * 60)}m`)

function tile(label: string, value: string, sub?: string) {
    return (
        <div class="tile">
            <div class="tile__label">{label}</div>
            <div class="tile__value">{value}</div>
            {sub ? <div class="tile__sub">{sub}</div> : null}
        </div>
    )
}

const sessionName = (s: Session) => s.label ?? s.branch ?? s.actor

/** One bar of where sessions' time went: what to make faster is the widest part that is not work. */
function timeBar(sessions: Session[], conversations: Tally[]): m.Children {
    const t = timeGoes(sessions, conversations)
    const total = t.working + t.you + t.node + t.landing
    if (!total) return null
    const parts: [string, number, string][] = [
        ['working', t.working, 'time--working'],
        ['waiting on you', t.you, 'time--you'],
        ['waiting for a node', t.node, 'time--node'],
        ['landing', t.landing, 'time--landing'],
    ]
    const pct = (n: number) => Math.round((100 * n) / total)
    return (
        <Card title="Where a session's time goes" subtitle="the sessions here that landed, from their start to their landing, added up: an estimate, from their conversations and the workspace's record">
            <div class="time__bar">
                {parts.map(([label, n, cls]) => (n ? <i class={cls} style={{width: `${(100 * n) / total}%`}} title={`${label}: ${dur(n)}`} /> : null))}
            </div>
            <div class="time__key">
                {parts.map(([label, n, cls]) => (
                    <span>
                        <i class={cls} /> {label} {pct(n)}% <span class="hint">({hours(n / 3600)})</span>
                    </span>
                ))}
            </div>
        </Card>
    )
}

/** One row per target: a bar to its typical deploy, a fainter one on to its slowest in ten. */
function deploySpans(rows: TargetTime[]) {
    const most = Math.max(...rows.map((r) => r.p90))
    const pct = (s: number) => `${(100 * s) / most}%`
    return (
        <div class="spans">
            {rows.map((r) => (
                <div class="spans__row" title={`${r.runs} deploys${r.failed ? `, ${r.failed} failed` : ''}: typical ${dur(r.median)}, slowest in ten ${dur(r.p90)}`}>
                    <span class="spans__name">{r.target}</span>
                    <span class="spans__track">
                        <i class="spans__p90" style={{width: pct(r.p90)}} />
                        <i class="spans__median" style={{width: pct(r.median)}} />
                    </span>
                    <span class="spans__value">
                        {dur(r.median)}
                        {r.p90 > r.median * 1.2 ? <span class="hint"> · {dur(r.p90)}</span> : null}
                    </span>
                </div>
            ))}
        </div>
    )
}

const active = (t: Tally) => dur(t.active_s)

/** A tally's count as a table: what, how many, in how many sessions. */
function counts(title: string, subtitle: string, rows: CountRow[], what: string, code = true) {
    return (
        <Card title={title} subtitle={subtitle} flush>
            {rows.length ? (
                <Table
                    rowKey={(r: CountRow) => r.name}
                    rows={rows}
                    columns={[
                        {key: 'name', label: what, cell: (r: CountRow) => (code ? <code>{shortName(r.name, 56)}</code> : shortName(r.name, 56))},
                        {key: 'count', label: 'times', align: 'end', cell: (r: CountRow) => r.count.toLocaleString()},
                        {key: 'sessions', label: 'sessions', align: 'end', cell: (r: CountRow) => String(r.sessions)},
                    ]}
                />
            ) : (
                <p class="hint">None in this range.</p>
            )}
        </Card>
    )
}

/** What the sessions' conversations add up to: midas's own and the imported. */
function conversations(ts: Tally[], dayKeys: number[]) {
    if (!ts.length) return <p class="hint">No conversations in this range.</p>
    const head = talkHeadline(ts)
    const said = saidByDay(ts, dayKeys)
    const projectSeries = said.projects.map((p, i) => ({label: p ? (projectName(p) ?? p) : 'no project', color: SERIES[i % SERIES.length]!}))
    const byHour = saidByHour(ts)
    const longest = [...ts].sort((a, b) => b.active_s - a.active_s).slice(0, 10)
    return [
        <h2 class="history__heading">Conversations</h2>,
        <div class="tiles">
            {tile('sessions', String(head.sessions), head.imported ? `${head.imported} imported` : 'none imported')}
            {tile('your messages', head.said.toLocaleString(), `${(head.said / head.sessions).toFixed(1)} a session`)}
            {tile('working', hours(head.activeHours), `median ${dur(head.medianActive)} a session`)}
            {tile('tool calls', head.toolCalls.toLocaleString(), head.failedPct != null ? `${head.failedPct}% failed` : '')}
            {tile('set out to land', String(head.finished), `of ${head.sessions}, ran finish-branch`)}
        </div>,
        <div class="grid2">
            <Card title="Your messages" subtitle="per day, by project">
                <Bars
                    days={dayKeys}
                    series={projectSeries}
                    value={(d) => said.projects.map((p) => said.rows.get(d)?.get(p) ?? 0)}
                    format={(v) => String(Math.round(v))}
                />
            </Card>
            <Card title="When you write" subtitle="your messages by the hour of the day">
                <Bars
                    days={byHour.map((_, h) => h)}
                    series={[{label: 'messages', color: SERIES[0]!}]}
                    value={(h) => [byHour[h]!]}
                    format={(v) => String(Math.round(v))}
                    label={(h) => `${String(h).padStart(2, '0')}:00`}
                />
            </Card>
        </div>,
        <Card title="Longest sessions" subtitle="by time worked: gaps of more than ten minutes count as ten" flush>
            <Table
                rowKey={(t: Tally) => t.id}
                rows={longest}
                columns={[
                    {
                        key: 'title',
                        label: 'session',
                        cell: (t: Tally) => (
                            <span class="who">
                                <a href={`/sessions/${t.id}`}>{shortName(t.title ?? t.id, 48)}</a>
                                <div class="hint">
                                    {t.id} · {when(t.start)}
                                    {t.imported ? ` · imported from ${t.imported}` : ''}
                                </div>
                            </span>
                        ),
                    },
                    {key: 'active', label: 'worked', align: 'end', cell: active},
                    {key: 'said', label: 'messages', align: 'end', cell: (t: Tally) => String(t.said.length)},
                    {key: 'tools', label: 'tool calls', align: 'end', cell: (t: Tally) => t.tool_calls.toLocaleString()},
                ]}
            />
        </Card>,
        <div class="grid2">
            {counts('Tools', 'what the agents called', topCounts(ts, 'tools'), 'tool')}
            {counts('Shell commands', 'the program each Bash call ran', topCounts(ts, 'commands'), 'command')}
        </div>,
        <div class="grid2">
            {counts('Cargo', 'cargo subcommands, wherever a command ran them', topCounts(ts, 'cargo', 10), 'cargo')}
            {counts('Skills', 'skills the agents used', topCounts(ts, 'skills', 10), 'skill')}
        </div>,
        counts('Most changed files', 'edits and writes, per file', topCounts(ts, 'files', 20), 'file'),
    ]
}

/** How long things take: landing, sessions, builds and waiting, over a range of days. */
export class History extends MithrilComponent {
    oninit() {
        askProjects()
        if (history()?.days !== $s.rangeDays) void loadHistory()
    }

    range = {
        get value() {
            return $s.rangeDays
        },
        set value(v: number) {
            $s.rangeDays = v
            void loadHistory()
        },
    }

    view() {
        const all = history()
        const picker = (
            <div class="history__bar">
                <FieldSegmented
                    model={this.range}
                    size="sm"
                    options={[
                        {value: 7, label: '7 days'},
                        {value: 30, label: '30 days'},
                        {value: 90, label: '90 days'},
                        {value: 365, label: 'year'},
                    ]}
                />
                {$s.historyLoading ? <Spinner size="sm" /> : null}
                {all ? projectFilter((repo) => all.conversations.filter((t) => t.repo === repo).length) : null}
            </div>
        )
        if (!all) return [picker, <p class="hint">Loading the history…</p>]
        const project = shownProject()
        const h = project ? narrow(all, (repo) => repo === project) : all

        const to = now()
        const dayKeys = days(to - h.days * 86400 + 86400, to)
        const head = headline(h.sessions, h.builds, h.takes)
        const landed = h.sessions.filter((s) => s.landed_at != null)

        // A machine keeps its colour whatever the range shows: the workspace's order first.
        const order = $s.workspace ? machines($s.workspace).map((x) => x.machine) : []
        const built = buildHoursByDay(h.builds, dayKeys)
        for (const mm of built.machines) if (!order.includes(mm)) order.push(mm)
        const shown = order.filter((mm) => built.machines.includes(mm))
        const machineSeries = shown.map((mm) => ({label: mm, color: SERIES[order.indexOf(mm) % SERIES.length]!}))

        const waits = waitsByDay(h.takes, dayKeys)

        // Typical (median) per day, or per week over a longer range: a dot per session hid the trend.
        const axis = buckets(dayKeys)
        const bucketName = (k: number) => (axis.weekly ? `week of ${day(new Date(k * 1000))}` : day(new Date(k * 1000)))
        const names = (xs: string[]) => [...xs.slice(0, 4).map((n) => `· ${shortName(n, 40)}`), ...(xs.length > 4 ? [`and ${xs.length - 4} more`] : [])]
        const landBy = typical(landed, (s) => s.landed_at!, (s) => s.time_to_land_s! / 3600, axis.keys, axis.of)
        const turns = h.landings.filter((l) => l.held_s != null).map((l) => ({...l, at: Date.parse(l.ts) / 1000}))
        const gateBy = typical(turns, (l) => l.at, (l) => l.held_s! / 60, axis.keys, axis.of)
        const sessionBy = typical(h.sessions, (s) => s.end, (s) => s.span_s / 3600, axis.keys, axis.of)
        const shipped = $s.deploys ? deployTimes($s.deploys).filter((t) => !project || t.repo === project) : []

        return (
            <div class="stack">
                {picker}
                <div class="tiles">
                    {tile('landed', String(head.landed), `of ${head.sessions} sessions`)}
                    {tile('time to land', dur(head.timeToLand), 'median, first take → main')}
                    {tile('landing gate', dur(head.gate), 'median turn at the gate')}
                    {tile('session', dur(head.sessionLength), 'median length')}
                    {tile('building', hours(head.buildHours), 'agents’ cargo time')}
                    {tile('waiting for a node', hours(head.waitHours), head.waitedPct != null ? `${head.waitedPct}% of takes waited` : '')}
                </div>

                {timeBar(h.sessions, h.conversations)}

                <div class="grid2">
                    <Card title="Time to land" subtitle={`typical (median) hours from a session's start to its branch on main, per ${axis.weekly ? 'week' : 'day'}`}>
                        {landed.length ? (
                            <Bars
                                days={axis.keys}
                                series={[{label: 'time to land', color: SERIES[0]!}]}
                                value={(k) => [landBy.get(k)?.median ?? 0]}
                                format={hours}
                                label={bucketName}
                                note={(k) => {
                                    const g = landBy.get(k)?.items ?? []
                                    return g.length ? [`${g.length} landed`, ...names(g.map((s) => `${sessionName(s)} ${dur(s.time_to_land_s)}`))] : ['nothing landed']
                                }}
                            />
                        ) : (
                            <p class="hint">No landings through the queue in this range: the hub has counted them since the queue began, 2026-10-17.</p>
                        )}
                    </Card>
                    <Card title="Landing gate" subtitle={`typical (median) minutes a turn held the landing queue, per ${axis.weekly ? 'week' : 'day'}`}>
                        {turns.length ? (
                            <Bars
                                days={axis.keys}
                                series={[{label: 'at the gate', color: SERIES[0]!}]}
                                value={(k) => [gateBy.get(k)?.median ?? 0]}
                                format={(v) => (v < 1 && v > 0 ? `${Math.round(v * 60)}s` : `${Math.round(v)}m`)}
                                label={bucketName}
                                note={(k) => {
                                    const g = gateBy.get(k)?.items ?? []
                                    const bad = g.filter((l) => l.outcome !== 'landed').length
                                    return g.length ? [`${g.length} turns${bad ? `, ${bad} failed or abandoned` : ''}`, `longest ${dur(Math.max(...g.map((l) => l.held_s!)))}`] : ['no turns']
                                }}
                            />
                        ) : (
                            <p class="hint">No turns at the gate in this range.</p>
                        )}
                    </Card>
                </div>

                <div class="grid2">
                    <Card title="Sessions" subtitle={`typical (median) hours from a session's start to its end, per ${axis.weekly ? 'week' : 'day'} it ended`}>
                        <Bars
                            days={axis.keys}
                            series={[{label: 'session length', color: SERIES[0]!}]}
                            value={(k) => [sessionBy.get(k)?.median ?? 0]}
                            format={hours}
                            label={bucketName}
                            note={(k) => {
                                const g = sessionBy.get(k)?.items ?? []
                                return g.length ? [`${g.length} sessions, ${g.filter((s) => s.landed_at != null).length} landed`, ...names(g.map((s) => `${sessionName(s)} ${dur(s.span_s)}`))] : ['no sessions']
                            }}
                        />
                    </Card>
                    <Card title="Landed to live" subtitle="each target's deploys, from asked for to published: the typical one, and the slowest in ten (the last week)">
                        {shipped.length ? deploySpans(shipped) : <p class="hint">No deploys in the last week.</p>}
                    </Card>
                </div>

                <div class="grid2">
                    <Card title="Building" subtitle="hours of agents' cargo runs per day, by machine">
                        <Bars
                            days={dayKeys}
                            series={machineSeries}
                            value={(d) => shown.map((mm) => built.rows.get(d)?.get(mm) ?? 0)}
                            format={hours}
                        />
                    </Card>
                    <Card title="Waiting for a node" subtitle="hours agents waited in line per day">
                        <Bars
                            days={dayKeys}
                            series={[{label: 'waited', color: SERIES[0]!}]}
                            value={(d) => [waits.get(d)?.hours ?? 0]}
                            format={hours}
                            note={(d) => {
                                const w = waits.get(d)
                                return w ? [`${w.waited} of ${w.takes} takes waited`] : []
                            }}
                        />
                    </Card>
                </div>

                {/* The runner is every project's: not narrowed to the one shown. */}
                {runnersHistory(all.runners ?? null, dayKeys)}

                <Card title="Sessions in this range" subtitle="newest first" flush>
                    <Table
                        rowKey={(s: Session) => s.actor}
                        rows={h.sessions}
                        columns={[
                            {
                                key: 'name',
                                label: 'session',
                                cell: (s: Session) => (
                                    <span title={s.actor} class="who">
                                        {s.link ? (
                                            <a href={s.link} target={s.link.startsWith('/') ? undefined : '_blank'} rel="noopener">
                                                {shortName(sessionName(s), 48)}
                                            </a>
                                        ) : (
                                            <b>{shortName(sessionName(s), 48)}</b>
                                        )}
                                        {s.label && s.branch ? <span class="who__sub">{s.branch}</span> : null}
                                        <div class="hint">
                                            {s.start_from === 'hook' ? 'began' : 'first take'} {when(s.start)}
                                        </div>
                                    </span>
                                ),
                            },
                            {key: 'span', label: 'length', align: 'end', cell: (s: Session) => dur(s.span_s)},
                            {
                                key: 'builds',
                                label: 'builds',
                                align: 'end',
                                cell: (s: Session) => `${s.builds}${s.failed_builds ? ` (${s.failed_builds}✕)` : ''} · ${dur(s.build_s)}`,
                            },
                            {key: 'waited', label: 'waited', align: 'end', cell: (s: Session) => (s.waited_s ? dur(s.waited_s) : '–')},
                            {
                                key: 'outcome',
                                label: 'landed',
                                align: 'end',
                                cell: (s: Session) =>
                                    s.landed_at != null ? (
                                        <span>
                                            <Badge tone="success">✓ {dur(s.time_to_land_s)}</Badge>
                                        </span>
                                    ) : s.open ? (
                                        <Badge tone="info">open</Badge>
                                    ) : s.outcome ? (
                                        <Badge tone="warning">{s.outcome}</Badge>
                                    ) : (
                                        <span class="hint">–</span>
                                    ),
                            },
                        ]}
                    />
                </Card>

                <Card title="Commands" subtitle="the agents' cargo runs per machine, where the time goes first" flush>
                    <Table
                        rowKey={(r: CommandRow) => `${r.shape} ${r.machine}`}
                        rows={commandTable(h.builds).slice(0, 25)}
                        columns={[
                            {key: 'shape', label: 'command', cell: (r: CommandRow) => <code>{r.shape}</code>},
                            {key: 'machine', label: 'machine'},
                            {key: 'runs', label: 'runs', align: 'end', cell: (r: CommandRow) => `${r.runs} · ${r.okPct}% ok`},
                            {key: 'median', label: 'median', align: 'end', cell: (r: CommandRow) => dur(r.median)},
                            {key: 'p90', label: 'p90', align: 'end', cell: (r: CommandRow) => dur(r.p90)},
                            {
                                key: 'cold',
                                label: 'first / later',
                                align: 'end',
                                cell: (r: CommandRow) => `${dur(r.cold)} / ${dur(r.warm)}`,
                            },
                        ]}
                    />
                </Card>

                {conversations(h.conversations, dayKeys)}
            </div>
        )
    }
}