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 (
{label}
{value}
{sub ?
{sub}
: null}
)
}
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 (
{parts.map(([label, n, cls]) => (n ? : null))}
{parts.map(([label, n, cls]) => (
{label} {pct(n)}% ({hours(n / 3600)})
))}
)
}
/** 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 (
{rows.map((r) => (
{r.target}
{dur(r.median)}
{r.p90 > r.median * 1.2 ? · {dur(r.p90)} : null}
))}
)
}
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 (
{rows.length ? (
r.name}
rows={rows}
columns={[
{key: 'name', label: what, cell: (r: CountRow) => (code ? {shortName(r.name, 56)} : 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)},
]}
/>
) : (
None in this range.
)}
)
}
/** What the sessions' conversations add up to: midas's own and the imported. */
function conversations(ts: Tally[], dayKeys: number[]) {
if (!ts.length) return No conversations in this range.
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 [
Conversations
,
{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`)}
,
said.projects.map((p) => said.rows.get(d)?.get(p) ?? 0)}
format={(v) => String(Math.round(v))}
/>
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`}
/>
,
t.id}
rows={longest}
columns={[
{
key: 'title',
label: 'session',
cell: (t: Tally) => (
{shortName(t.title ?? t.id, 48)}
{t.id} · {when(t.start)}
{t.imported ? ` · imported from ${t.imported}` : ''}
),
},
{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()},
]}
/>
,
{counts('Tools', 'what the agents called', topCounts(ts, 'tools'), 'tool')}
{counts('Shell commands', 'the program each Bash call ran', topCounts(ts, 'commands'), 'command')}
,
{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')}
,
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 = (
{$s.historyLoading ? : null}
{all ? projectFilter((repo) => all.conversations.filter((t) => t.repo === repo).length) : null}
)
if (!all) return [picker, Loading the history…
]
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 (
{picker}
{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` : '')}
{timeBar(h.sessions, h.conversations)}
{landed.length ? (
[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']
}}
/>
) : (
No landings through the queue in this range: the hub has counted them since the queue began, 2026-10-17.
)}
{turns.length ? (
[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']
}}
/>
) : (
No turns at the gate in this range.
)}
[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']
}}
/>
{shipped.length ? deploySpans(shipped) : No deploys in the last week.
}
shown.map((mm) => built.rows.get(d)?.get(mm) ?? 0)}
format={hours}
/>
[waits.get(d)?.hours ?? 0]}
format={hours}
note={(d) => {
const w = waits.get(d)
return w ? [`${w.waited} of ${w.takes} takes waited`] : []
}}
/>
{/* The runner is every project's: not narrowed to the one shown. */}
{runnersHistory(all.runners ?? null, dayKeys)}
s.actor}
rows={h.sessions}
columns={[
{
key: 'name',
label: 'session',
cell: (s: Session) => (
{s.link ? (
{shortName(sessionName(s), 48)}
) : (
{shortName(sessionName(s), 48)}
)}
{s.label && s.branch ? {s.branch} : null}
{s.start_from === 'hook' ? 'began' : 'first take'} {when(s.start)}
),
},
{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 ? (
✓ {dur(s.time_to_land_s)}
) : s.open ? (
open
) : s.outcome ? (
{s.outcome}
) : (
–
),
},
]}
/>
`${r.shape} ${r.machine}`}
rows={commandTable(h.builds).slice(0, 25)}
columns={[
{key: 'shape', label: 'command', cell: (r: CommandRow) => {r.shape}},
{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)}`,
},
]}
/>
{conversations(h.conversations, dayKeys)}
)
}
}