garage44.eu/jeroen/midas

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

.. /web/src/components/autopilot.tsx

raw

import m, {MithrilComponent} from '@garage44/mithril'
import {Alert, Badge, Button, Card, Dialog, FieldText} from '@garage44/mithril/components'

import {journeyOf} from '@/components/landing'
import {act} from '@/lib/actions'
import {api} from '@/lib/api'
import type {Schedule, Template, TemplateRun, TemplatesState} from '@/lib/api'
import {age, ahead, shortName} from '@/lib/format'
import {shortWords, underway} from '@/lib/landing'
import {speaker} from '@/lib/names'
import {askProjects, projectName, projects} from '@/lib/projects'
import {bind, local} from '@/lib/reactive'
import {go, here} from '@/lib/route'
import {steers} from '@/lib/store'
import {hosted} from '@/lib/stream'
import type {Hosted} from '@/lib/stream'

/**
 * The autopilot (autopilot.rs, templates.rs): an agent that answers a
 * session's questions and requests for the person — landing included — and
 * says what next when it stops; turned on per session (the chip under the
 * message box), for many at once (Take over), or for every session a
 * template starts, now or on a schedule. Its colour is its own (`--pilot`),
 * so what it decided never reads as the person's.
 */

/** Who it is in the log. */
export const PILOT = 'autopilot'

/** Its mark: a small plane. */
export const plane = (size = 14) => (
    <svg class="plane" viewBox="0 0 24 24" width={size} height={size} aria-hidden="true">
        <path fill="currentColor" d="M21 15.5v-2l-8-5V3.5a1.5 1.5 0 0 0-3 0V8.5l-8 5v2l8-2.5V18l-2 1.5V21l3.5-1 3.5 1v-1.5L13 18v-5z" />
    </svg>
)

/** What it decided and why, under the request or message it is about. */
export function pilotWhy(label: string, why: string | null | undefined, tone: '' | 'left' = ''): m.Children {
    return (
        <div class={`pilot__why${tone ? ` pilot__why--${tone}` : ''}`}>
            <div class="pilot__by">
                {plane(12)} {label}
            </div>
            {why ? <div class="pilot__reason">{why}</div> : null}
        </div>
    )
}

/** While it decides a request: said on the request, whose buttons stay. */
export function pilotDeciding(): m.Children {
    return (
        <div class="pilot__deciding">
            <div class="pilot__bar">
                <i />
            </div>
            <span>The autopilot is reading the conversation and the code. You can still answer yourself.</span>
        </div>
    )
}

/** Its state, for the session's line in the list and its head: none when it is off. */
export function pilotState(s: Hosted): {text: string; tone: 'pilot' | 'you'} | null {
    const p = s.autopilot
    if (!p?.on || s.finished || s.status === 'stopped' || s.status === 'failed') return null
    if (p.state === 'left') return {text: p.left_urgent === false ? 'autopilot left this for your next block' : 'autopilot leaves this to you', tone: 'you'}
    if (p.state === 'deciding') return {text: 'autopilot · deciding…', tone: 'pilot'}
    return null
}

/** Until when, in words. */
function untilWords(until: number | null | undefined): string {
    if (!until) return 'until you stop it'
    const d = new Date(until * 1000)
    const today = new Date()
    const t = d.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'})
    return d.toDateString() === today.toDateString() || (until - Date.now() / 1000 < 3600 && d.getHours() === 0) ? `until ${t}` : `until ${d.toLocaleDateString([], {weekday: 'short'})} ${t}`
}

/** What a turned-on line says: who, and until when. */
export function pilotLine(on: boolean, by: string | undefined, until: number | null | undefined, why?: string | null): string {
    if (!on) return `autopilot off${why ? ` · ${why}` : by && by !== PILOT ? ` · ${speaker(by).title}` : ''}`
    return `autopilot on · ${speaker(by ?? '?').title} · ${untilWords(until)}`
}

// ── Turning it on ───────────────────────────────────────────────────────────

/** How long it stays on: an hour, the rest of today, or until turned off. */
const SPANS = [
    {id: 'hour', name: '1 hour'},
    {id: 'today', name: 'today'},
    {id: 'stop', name: 'until I stop it'},
]

function untilOf(span: string): number | null {
    if (span === 'hour') return Math.floor(Date.now() / 1000) + 3600
    if (span === 'today') {
        const d = new Date()
        d.setHours(24, 0, 0, 0)
        return Math.floor(d.getTime() / 1000)
    }
    return null
}

/** A row of choices, one on. */
export function seg(options: {id: string; name: string}[], value: string, set: (id: string) => void, disabled = false): m.Children {
    return (
        <div class="pilot-seg" role="radiogroup">
            {options.map((o) => (
                <button type="button" role="radio" aria-checked={o.id === value} class={o.id === value ? 'is-on' : ''} disabled={disabled} onclick={() => set(o.id)}>
                    {o.name}
                </button>
            ))}
        </div>
    )
}

/** The sheet that turns it on, for one session or several (`ids`). */
const sheet = local({open: false, ids: [] as string[], goal: '', span: 'today', sending: false})

export function openPilotSheet(ids: string[]) {
    Object.assign(sheet, {open: true, ids, goal: '', span: 'today', sending: false})
}

/** Mounted once, in the frame, as the confirm dialog is. */
export class PilotHost extends MithrilComponent {
    view() {
        const n = sheet.ids.length
        const go = async () => {
            sheet.sending = true
            const until = untilOf(sheet.span)
            const ok = await act(n === 1 ? 'autopilot on' : `autopilot on for ${n} sessions`, async () => {
                if (n === 1) await api.setAutopilot(sheet.ids[0]!, true, until, sheet.goal.trim())
                else await api.takeOver(sheet.ids, sheet.goal.trim(), until)
            })
            sheet.sending = false
            if (ok) sheet.open = false
        }
        return (
            <Dialog
                model={bind(sheet, 'open')}
                title="Autopilot on?"
                size="sm"
                footer={[
                    <Button variant="ghost" onclick={() => (sheet.open = false)}>
                        Cancel
                    </Button>,
                    <Button class="pilot-go" variant="primary" disabled={sheet.sending || !steers()} onclick={go}>
                        {sheet.sending ? 'Taking over…' : n === 1 ? 'Take it over' : `Take over ${n}`}
                    </Button>,
                ]}
            >
                <ul class="pilot__list">
                    <li>
                        It answers {n === 1 ? "this session's" : "these sessions'"} questions and requests for you, <b>landing and deploying included</b>.
                    </li>
                    <li>When a session stops, it says what next, or that it is done.</li>
                    <li>Every decision is in the conversation, with why.</li>
                    <li>When it is not sure, or it cannot be undone, it leaves it to you and tells your phone.</li>
                </ul>
                <label class="pilot__field">
                    <span class="hint">Goal (optional)</span>
                    <textarea
                        rows={2}
                        placeholder="e.g. “finish it and land it; nothing new”. Empty: what you asked the session."
                        value={sheet.goal}
                        oninput={(e: Event) => (sheet.goal = (e.target as HTMLTextAreaElement).value)}
                    />
                </label>
                <div class="pilot__field">
                    <span class="hint">Stops by itself</span>
                    {seg(SPANS, sheet.span, (id) => (sheet.span = id))}
                </div>
            </Dialog>
        )
    }
}

/** The chip under the message box: off, a tap opens the sheet; on, a tap turns it off at once. */
export function autopilotChip(s: Hosted): m.Children {
    if (s.local || s.imported) return null
    const on = !!s.autopilot?.on
    return (
        <button
            type="button"
            class={`chooser pilot-chip${on ? ' pilot-chip--on' : ''}${steers() ? '' : ' is-disabled'}`}
            disabled={!steers()}
            title={on ? `The autopilot answers for you ${untilWords(s.autopilot?.until)}. Tap to take back control.` : 'Let the autopilot answer for you'}
            aria-pressed={on}
            onclick={() => (on ? void act('autopilot off', () => api.setAutopilot(s.id, false)) : openPilotSheet([s.id]))}
        >
            {on ? <span class="pilot-chip__dot" /> : plane(13)}
            <span>Autopilot</span>
        </button>
    )
}

// ── The Autopilot page ──────────────────────────────────────────────────────

const state = local({data: null as TemplatesState | null, error: '', loading: false})

function load() {
    if (state.loading) return
    state.loading = true
    api.templates()
        .then((d) => (state.data = d))
        .catch((e) => (state.error = (e as Error).message))
        .finally(() => (state.loading = false))
}

async function templateOp(what: string, op: string, fields: Record<string, unknown>, quiet = false): Promise<TemplatesState | null> {
    let out: TemplatesState | null = null
    await act(what, async () => {
        out = await api.templateOp(op, fields)
        state.data = out
    }, {quiet})
    return out
}

const ended = (h: Hosted) => h.status === 'stopped' || h.status === 'failed'

/** How long ago, in words: "just now" rather than "now ago". */
function ago(t: number | null | undefined): string {
    const a = age(t)
    return a === 'now' ? 'just now' : `${a} ago`
}

/**
 * The sessions Take over offers: waiting on the person, quiet and not done, on
 * their way to main, at work; and those on autopilot already. A session whose
 * landing is underway works too, but the lists call it Landing, not At work.
 */
function candidates(): {asks: Hosted[]; quiet: Hosted[]; landing: Hosted[]; busy: Hosted[]; flying: Hosted[]} {
    const open = hosted().filter((h) => !h.finished && !h.archived && !h.imported && !h.local)
    const flying = open.filter((h) => h.autopilot?.on && !ended(h))
    const rest = open.filter((h) => !flying.includes(h))
    const working = rest.filter((h) => ['working', 'queued', 'starting'].includes(h.status))
    const landing = working.filter((h) => underway(journeyOf(h)))
    return {
        flying,
        asks: rest.filter((h) => h.status === 'needs_permission'),
        quiet: rest.filter((h) => h.status === 'waiting' || ended(h)),
        landing,
        busy: working.filter((h) => !landing.includes(h)),
    }
}

/** What Take over tells the autopilot to do with them. */
const ORDERS = [
    {id: 'land', name: 'finish and land', goal: 'Finish what this session was asked to do and land it. Nothing new.'},
    {id: 'keep', name: 'finish, do not land', goal: 'Finish what this session was asked to do, but do not land it: leave "Shall it land?" to me.'},
    {id: 'tidy', name: 'wrap up', goal: 'Wrap this session up: land what is done and verified, drop what is not, and finish it.'},
]

const take = local({picked: {} as Record<string, boolean>, seeded: false, order: 'land', span: 'today', sending: false})

function takeOverCard(): m.Children {
    const c = candidates()
    if (!take.seeded && (c.asks.length || c.quiet.length)) {
        take.seeded = true
        take.picked = Object.fromEntries([...c.asks, ...c.quiet].map((h) => [h.id, true]))
    }
    const ids = [...c.asks, ...c.quiet, ...c.landing, ...c.busy].filter((h) => take.picked[h.id]).map((h) => h.id)
    const row = (h: Hosted, sub: string) => (
        <label class="pilot-row">
            <input type="checkbox" checked={!!take.picked[h.id]} onchange={() => (take.picked = {...take.picked, [h.id]: !take.picked[h.id]})} />
            <span class="pilot-row__main">
                <span class="pilot-row__title">{h.title}</span>
                <span class="hint">{sub}</span>
            </span>
            {projectName(h.repo) ? <Badge tone="neutral">{projectName(h.repo)}</Badge> : null}
        </label>
    )
    const group = (title: string, list: Hosted[], sub: (h: Hosted) => string) =>
        list.length ? [<div class="pilot-group">{title}</div>, ...list.map((h) => row(h, sub(h)))] : null
    const send = async () => {
        take.sending = true
        const goal = ORDERS.find((o) => o.id === take.order)!.goal
        await act(`autopilot on for ${ids.length} session${ids.length === 1 ? '' : 's'}`, () => api.takeOver(ids, goal, untilOf(take.span)))
        take.sending = false
        take.picked = {}
    }
    return (
        <Card title="Take over" subtitle="The open sessions; those waiting on you or quiet and unfinished are ticked.">
            {c.asks.length + c.quiet.length + c.landing.length + c.busy.length === 0 ? <p class="hint">Nothing waits: every open session is at work on autopilot, or there are none.</p> : null}
            <div class="pilot-rows">
                {group('Waiting for you', c.asks, () => 'asks you something')}
                {group('Quiet, not finished', c.quiet, (h) => (ended(h) ? `ended ${ago(h.active ?? h.updated)} · reopened when taken over` : `went quiet ${ago(h.active ?? h.updated)}`))}
                {group('Landing', c.landing, (h) => shortWords(journeyOf(h)!))}
                {group('At work', c.busy, () => 'working')}
            </div>
            {ids.length ? (
                <div class="pilot-take">
                    <div class="pilot__field">
                        <span class="hint">Tell the autopilot to</span>
                        {seg(ORDERS, take.order, (id) => (take.order = id))}
                    </div>
                    <div class="pilot__field">
                        <span class="hint">Stops by itself</span>
                        {seg(SPANS, take.span, (id) => (take.span = id))}
                    </div>
                    <Button class="pilot-go" variant="primary" disabled={!steers() || take.sending} onclick={send}>
                        {plane(14)} {take.sending ? 'Taking over…' : `Take over ${ids.length} session${ids.length === 1 ? '' : 's'}`}
                    </Button>
                </div>
            ) : null}
            {c.flying.length ? (
                <div class="pilot-rows">
                    <div class="pilot-group">On autopilot</div>
                    {c.flying.map((h) => (
                        <div class="pilot-row">
                            <span class="pilot-row__mark">{plane(13)}</span>
                            <a class="pilot-row__main" href={`/sessions/${h.id}`}>
                                <span class="pilot-row__title">{h.title}</span>
                                <span class="hint">{pilotState(h)?.text ?? untilWords(h.autopilot?.until)}</span>
                            </a>
                            <Button size="sm" variant="ghost" disabled={!steers()} onclick={() => act('autopilot off', () => api.setAutopilot(h.id, false))}>
                                Off
                            </Button>
                        </div>
                    ))}
                </div>
            ) : null}
        </Card>
    )
}

/** A run's outcome as a dot: landed filled, anything else hollow. */
function runDots(runs: TemplateRun[]): m.Children {
    const last = runs.filter((r) => r.outcome).slice(-6)
    if (!last.length) return <span class="hint">no runs yet</span>
    const landed = last.filter((r) => r.outcome === 'landed').length
    return (
        <span class="pilot-dots" title={last.map((r) => `${r.session}: ${r.outcome}`).join('\n')}>
            {last.map((r) => (
                <a href={`/sessions/${r.session}`} class={`pilot-dot${r.outcome === 'landed' ? ' is-landed' : ''}`} />
            ))}
            <span class="hint">
                {' '}
                {landed} landed, {last.length - landed} nothing
            </span>
        </span>
    )
}

const DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

/** A schedule's time in the person's own: from minutes past midnight UTC (and a UTC weekday). */
function localOf(minute: number, weekday: number): {time: string; weekday: number} {
    // 2024-01-01 was a Monday.
    const d = new Date(Date.UTC(2024, 0, 1 + weekday, Math.floor(minute / 60), minute % 60))
    return {time: d.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'}), weekday: (d.getDay() + 6) % 7}
}

/** And back: a local time (and local weekday) as minutes past midnight UTC and a UTC weekday. */
function utcOf(time: string, weekday: number): {minute: number; weekday: number} {
    const [h, mi] = time.split(':').map(Number)
    const d = new Date(2024, 0, 1 + weekday, h || 0, mi || 0)
    return {minute: d.getUTCHours() * 60 + d.getUTCMinutes(), weekday: (d.getUTCDay() + 6) % 7}
}

function repeatWords(s: Schedule): string {
    const l = localOf(s.minute, s.weekday)
    if (s.repeat === 'weekly') return `every ${DAYS[l.weekday]} at ${l.time}`
    return `${s.repeat === 'weekdays' ? 'weekdays' : 'every night'} at ${l.time}`
}

function schedulesCard(d: TemplatesState): m.Children {
    const tpl = (id: string) => d.templates.find((t) => t.id === id)
    return (
        <Card title="Schedules" subtitle="A template on a clock. It starts only when its last run has finished, and pauses after two runs in a row that land nothing.">
            {d.schedules.length ? null : <p class="hint">No schedules yet: start a template and choose how often it repeats.</p>}
            <div class="pilot-cards">
                {d.schedules.map((s) => {
                    const t = tpl(s.template)
                    const runs = (t?.runs ?? []).filter((r) => r.schedule === s.id)
                    const open = runs.some((r) => !r.outcome)
                    return (
                        <div class={`pilot-card${s.paused ? ' pilot-card--paused' : s.on ? '' : ' pilot-card--off'}`}>
                            <div class="pilot-card__head">
                                <b>
                                    {t?.icon} {t?.name ?? s.template}
                                </b>
                                {s.repos.map((r) => (
                                    <Badge tone="neutral">{projectName(r)}</Badge>
                                ))}
                                <button
                                    type="button"
                                    class={`chooser pilot-chip${s.on && !s.paused ? ' pilot-chip--on' : ''}`}
                                    disabled={!steers()}
                                    onclick={() => templateOp(s.on && !s.paused ? 'schedule off' : 'schedule on', 'schedule_on', {id: s.id, on: !(s.on && !s.paused)})}
                                >
                                    {s.on && !s.paused ? <span class="pilot-chip__dot" /> : null}
                                    <span>{s.paused ? 'paused' : s.on ? 'on' : 'off'}</span>
                                </button>
                            </div>
                            <div class="hint">
                                {repeatWords(s)}
                                {s.on && !s.paused ? ` · next ${ahead(s.next)}` : ''}
                                {open ? ' · a run is going on' : ''}
                            </div>
                            {s.extra ? <div class="hint">also: {s.extra}</div> : null}
                            <div>{runDots(runs)}</div>
                            {s.paused ? <div class="pilot-card__why">Paused: {s.paused}. Tap “paused” to resume it.</div> : null}
                            <div class="pilot-card__tools">
                                <button type="button" class="home__link" disabled={!steers()} onclick={() => templateOp('schedule removed', 'schedule_delete', {id: s.id})}>
                                    remove
                                </button>
                            </div>
                        </div>
                    )
                })}
            </div>
        </Card>
    )
}

const EDITORS = [
    {id: 'me', name: 'only me'},
    {id: 'propose', name: 'midas proposes'},
    {id: 'midas', name: 'midas changes it'},
]

function templatesCard(d: TemplatesState): m.Children {
    return (
        <Card title="Templates" subtitle="Briefs to start sessions from, each saying what counts as done.">
            <div class="pilot-cards">
                {d.templates.map((t) => (
                    <a class="pilot-card pilot-card--link" href={`/autopilot/t/${t.id}`}>
                        <div class="pilot-card__head">
                            <b>
                                {t.icon} {t.name}
                            </b>
                            <span class="hint">v{t.versions.at(-1)?.v ?? 1}</span>
                            {t.proposal ? <Badge tone="accent">midas proposes a change</Badge> : null}
                        </div>
                        <div class="hint pilot-card__brief">{shortName(t.brief.split('\n')[0] ?? '', 140)}</div>
                        <div class="hint">
                            {EDITORS.find((e) => e.id === t.editors)?.name} · {runDots(t.runs)}
                        </div>
                    </a>
                ))}
            </div>
            <div class="pilot-card__tools">
                <Button variant="primary" disabled={!steers()} onclick={() => go('autopilot/new')}>
                    Start from a template
                </Button>
                <Button variant="ghost" disabled={!steers()} onclick={() => go('autopilot/t/new')}>
                    New template
                </Button>
            </div>
        </Card>
    )
}

// ── Starting from a template ────────────────────────────────────────────────

const REPEATS = [
    {id: 'once', name: 'once'},
    {id: 'daily', name: 'every night'},
    {id: 'weekdays', name: 'weekdays'},
    {id: 'weekly', name: 'weekly'},
]

const MODES = [
    {id: 'bypassPermissions', name: 'Trusted'},
    {id: 'auto', name: 'Auto'},
    {id: 'default', name: 'Manual'},
]

const MODELS = [
    {id: 'default', name: 'Default'},
    {id: 'fable', name: 'Fable'},
    {id: 'opus', name: 'Opus'},
    {id: 'opus-fast', name: 'Opus ⚡ fast'},
    {id: 'sonnet', name: 'Sonnet'},
]

const starting = local({template: '', repos: {} as Record<string, boolean>, extra: '', repeat: 'once', time: '02:00', weekday: 0, mode: 'bypassPermissions', model: 'default', pilot: true, sending: false})

/** Start a template: chosen here, or the one the address names (`autopilot/new/t3`). */
function startPage(d: TemplatesState): m.Children {
    const named = here().match(/^autopilot\/new\/(t\d+)$/)?.[1]
    if (named && starting.template !== named && !starting.sending) starting.template = named
    if (!starting.template && d.templates[0]) starting.template = d.templates[0].id
    const t = d.templates.find((x) => x.id === starting.template)
    const repos = projects.list.filter((p) => starting.repos[p.repo]).map((p) => p.repo)
    const repeat = starting.repeat
    const send = async () => {
        starting.sending = true
        const at = utcOf(starting.time, starting.weekday)
        const out = await templateOp(repeat === 'once' ? 'started' : 'started, and scheduled', 'start', {
            template: starting.template, repos, extra: starting.extra.trim(), mode: starting.mode, model: starting.model === 'default' ? '' : starting.model,
            autopilot: starting.pilot, repeat, minute: at.minute, weekday: at.weekday,
        })
        starting.sending = false
        const first = (out as (TemplatesState & {started?: string[]}) | null)?.started?.[0]
        if (first) go(`sessions/${first}`)
    }
    const label = repeat === 'once' ? 'Start' : `Start now and ${REPEATS.find((r) => r.id === repeat)!.name}`
    return (
        <div class="stack">
            <p class="hint">
                <a href="/autopilot" class="home__link">
                    ← Autopilot
                </a>
            </p>
            <Card title="New session from a template" subtitle="The template is the brief: what to do and what counts as done. One session per project.">
                <div class="pilot-cards">
                    {d.templates.map((x) => (
                        <button type="button" class={`pilot-card pilot-card--pick${x.id === starting.template ? ' is-on' : ''}`} onclick={() => (starting.template = x.id)}>
                            <b>
                                {x.icon} {x.name}
                            </b>
                            <span class="hint pilot-card__brief">{shortName(x.brief.split('\n')[0] ?? '', 140)}</span>
                        </button>
                    ))}
                </div>
                {t ? (
                    <details class="pilot-brief">
                        <summary class="hint">the whole brief (v{t.versions.at(-1)?.v ?? 1})</summary>
                        <pre>{t.brief}</pre>
                    </details>
                ) : null}
                <div class="pilot__field">
                    <span class="hint">Project(s)</span>
                    <div class="pilot-chips">
                        {projects.list.map((p) => (
                            <button type="button" class={`chooser pilot-chip${starting.repos[p.repo] ? ' pilot-chip--on' : ''}`} onclick={() => (starting.repos = {...starting.repos, [p.repo]: !starting.repos[p.repo]})}>
                                <span>{p.name}</span>
                            </button>
                        ))}
                    </div>
                </div>
                <label class="pilot__field">
                    <span class="hint">Also (optional)</span>
                    <input type="text" class="pilot__input" placeholder="e.g. “only the web client”" value={starting.extra} oninput={(e: Event) => (starting.extra = (e.target as HTMLInputElement).value)} />
                </label>
                <div class="pilot__field">
                    <span class="hint">Repeat</span>
                    {seg(REPEATS, repeat, (id) => (starting.repeat = id))}
                    {repeat !== 'once' ? (
                        <div class="pilot-when">
                            {repeat === 'weekly' ? (
                                <select value={String(starting.weekday)} onchange={(e: Event) => (starting.weekday = Number((e.target as HTMLSelectElement).value))}>
                                    {DAYS.map((name, i) => (
                                        <option value={String(i)}>{name}</option>
                                    ))}
                                </select>
                            ) : null}
                            <input type="time" value={starting.time} oninput={(e: Event) => (starting.time = (e.target as HTMLInputElement).value)} />
                            <span class="hint">your time · only when its last run has finished</span>
                        </div>
                    ) : null}
                </div>
                <div class="pilot__field">
                    <span class="hint">Mode, model and the autopilot</span>
                    <div class="pilot-chips">
                        {seg(MODES, starting.mode, (id) => (starting.mode = id))}
                        {seg(MODELS, starting.model, (id) => (starting.model = id))}
                        <button type="button" class={`chooser pilot-chip${starting.pilot ? ' pilot-chip--on' : ''}`} aria-pressed={starting.pilot} onclick={() => (starting.pilot = !starting.pilot)}>
                            {starting.pilot ? <span class="pilot-chip__dot" /> : plane(13)}
                            <span>Autopilot</span>
                        </button>
                    </div>
                </div>
                <Button variant="primary" disabled={!steers() || !t || !repos.length || starting.sending} onclick={send}>
                    {starting.sending ? 'Starting…' : repos.length > 1 ? `${label} (${repos.length} sessions)` : label}
                </Button>
            </Card>
        </div>
    )
}

// ── A template's own page ───────────────────────────────────────────────────

const editing = local({id: '', name: '', icon: '', brief: '', editors: 'propose', why: '', shown: 0, sending: false})

function editPage(d: TemplatesState, id: string): m.Children {
    const t: Template | undefined = d.templates.find((x) => x.id === id)
    if (editing.id !== id) {
        Object.assign(editing, {id, name: t?.name ?? '', icon: t?.icon ?? '', brief: t?.brief ?? '', editors: t?.editors ?? 'propose', why: '', shown: 0})
    }
    if (id !== 'new' && !t) return <p class="hint">No template {id}.</p>
    const changed = !t || editing.brief.trim() !== t.brief || editing.name.trim() !== t.name || editing.icon.trim() !== t.icon || editing.editors !== t.editors
    const save = async () => {
        editing.sending = true
        const out = await templateOp('template saved', 'save', {id: t?.id ?? '', name: editing.name, icon: editing.icon, brief: editing.brief, editors: editing.editors, why: editing.why})
        editing.sending = false
        if (out && !t) {
            const made = out.templates.at(-1)
            if (made) go(`autopilot/t/${made.id}`)
        }
        editing.why = ''
    }
    const versions = [...(t?.versions ?? [])].reverse()
    const current = versions[0]?.v
    return (
        <div class="stack">
            <p class="hint">
                <a href="/autopilot" class="home__link">
                    ← Autopilot
                </a>
            </p>
            {t?.proposal ? (
                <Alert tone="info">
                    <b>Midas proposes a change</b>, after {t.proposal.session}: {t.proposal.why}
                    <pre class="pilot-brief__text">{t.proposal.brief}</pre>
                    <div class="pilot-card__tools">
                        <Button size="sm" variant="primary" disabled={!steers()} onclick={() => templateOp('change taken', 'accept', {id: t.id})}>
                            Take it
                        </Button>
                        <Button size="sm" variant="ghost" disabled={!steers()} onclick={() => templateOp('change turned down', 'reject', {id: t.id})}>
                            Turn it down
                        </Button>
                    </div>
                </Alert>
            ) : null}
            <Card title={t ? `${t.icon} ${t.name}` : 'New template'} subtitle={t && t.editors === 'midas' ? `midas keeps this up · version ${current}` : t ? `version ${current}` : 'a brief to start sessions from'}>
                <div class="pilot-name">
                    <FieldText model={bind(editing, 'icon')} label="icon" placeholder="⚡" />
                    <FieldText model={bind(editing, 'name')} label="name" placeholder="Performance" />
                </div>
                <label class="pilot__field">
                    <span class="hint">The brief: what to do, and what counts as done</span>
                    <textarea class="pilot__brief" rows={10} value={editing.brief} oninput={(e: Event) => (editing.brief = (e.target as HTMLTextAreaElement).value)} />
                </label>
                <div class="pilot__field">
                    <span class="hint">Who may change it</span>
                    {seg(EDITORS, editing.editors, (x) => (editing.editors = x))}
                    <span class="hint">
                        {editing.editors === 'midas'
                            ? 'After each run, midas reads how it went and changes the brief when the run shows it should; every change is a version you can put back.'
                            : editing.editors === 'propose'
                              ? 'After each run, midas may propose a change; it waits here for your yes.'
                              : 'Only you change it.'}
                    </span>
                </div>
                {t && editing.brief.trim() !== t.brief ? <FieldText model={bind(editing, 'why')} label="why (optional)" placeholder="what this change is for" /> : null}
                <div class="pilot-card__tools">
                    <Button variant="primary" disabled={!steers() || !changed || editing.sending || !editing.name.trim() || !editing.brief.trim()} onclick={save}>
                        {editing.sending ? 'Saving…' : 'Save'}
                    </Button>
                    {t ? (
                        <Button variant="ghost" disabled={!steers()} onclick={() => go(`autopilot/new/${t.id}`)}>
                            Try it now
                        </Button>
                    ) : null}
                    {t ? (
                        <button type="button" class="home__link" disabled={!steers()} onclick={() => templateOp('template removed', 'delete', {id: t.id}).then(() => go('autopilot'))}>
                            remove
                        </button>
                    ) : null}
                </div>
            </Card>
            {versions.length ? (
                <Card title="Versions" subtitle="Who changed it, and why.">
                    <div class="pilot-versions">
                        {versions.map((v) => (
                            <div class={`pilot-version${v.by === 'midas' ? ' pilot-version--midas' : ''}`}>
                                <div class="pilot__by">
                                    {v.by === 'midas' ? plane(12) : null} v{v.v} · {v.by === 'midas' ? 'midas' : speaker(v.by).title} · {ago(v.at)}
                                    {v.session ? (
                                        <a class="home__link" href={`/sessions/${v.session}`}>
                                            {' '}
                                            after {v.session}
                                        </a>
                                    ) : null}
                                </div>
                                <div class="pilot__reason">{v.why}</div>
                                <div class="pilot-card__tools">
                                    <button type="button" class="home__link" onclick={() => (editing.shown = editing.shown === v.v ? 0 : v.v)}>
                                        {editing.shown === v.v ? 'hide' : 'show'}
                                    </button>
                                    {v.v !== current ? (
                                        <button type="button" class="home__link" disabled={!steers()} onclick={() => templateOp(`back to version ${v.v}`, 'revert', {id: t!.id, v: v.v})}>
                                            back to this one
                                        </button>
                                    ) : null}
                                </div>
                                {editing.shown === v.v ? <pre class="pilot-brief__text">{v.brief}</pre> : null}
                            </div>
                        ))}
                    </div>
                </Card>
            ) : null}
        </div>
    )
}

/** The page: Take over, the schedules and the templates; a template's start and its own page. */
export class AutopilotPage extends MithrilComponent {
    oninit() {
        askProjects()
        load()
    }

    view() {
        const d = state.data
        if (!d) return <p class="hint">{state.error || 'Loading…'}</p>
        const h = here()
        if (h === 'autopilot/new' || h.startsWith('autopilot/new/')) return startPage(d)
        const t = h.match(/^autopilot\/t\/(t\d+|new)$/)?.[1]
        if (t) return editPage(d, t)
        return (
            <div class="stack">
                {takeOverCard()}
                {schedulesCard(d)}
                {templatesCard(d)}
            </div>
        )
    }
}

/** Fresh when the page is looked at again. */
export function reloadTemplates() {
    load()
}