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) => (
)
/** 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 (
{plane(12)} {label}
{why ?
{why}
: null}
)
}
/** While it decides a request: said on the request, whose buttons stay. */
export function pilotDeciding(): m.Children {
return (
The autopilot is reading the conversation and the code. You can still answer yourself.
)
}
/** 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 (
{options.map((o) => (
))}
)
}
/** 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 (
)
}
}
/** 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 (
)
}
// ── 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, quiet = false): Promise {
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, 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) => (
)
const group = (title: string, list: Hosted[], sub: (h: Hosted) => string) =>
list.length ? [
{t?.proposal ? (
Midas proposes a change, after {t.proposal.session}: {t.proposal.why}
{t.proposal.brief}
) : null}
Who may change it
{seg(EDITORS, editing.editors, (x) => (editing.editors = x))}
{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.'}
)
}
/** 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
{state.error || 'Loading…'}
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 (