git clone https://garage44.eu/jeroen/midas.git.. /web/src/components/sessions.tsx
import m, {MithrilComponent} from '@garage44/mithril'
import {Badge, Button, Card, FieldText, NavGroup, NavItem} from '@garage44/mithril/components'
import {toast} from '@garage44/mithril/components'
import {askConfirm, confirmButton} from '@/components/confirm'
import {foldable} from '@/components/fold'
import {Elapsed} from '@/components/elapsed'
import {activity} from '@/lib/activity'
import {gauge, gaugeOf, journeyOf, milestones, wayButton, wayToLive} from '@/components/landing'
import {nodeFoot, nodeStepLine} from '@/components/nodeline'
import {icon} from '@/components/icons'
import {who} from '@/components/who'
import {nameOf, speaker} from '@/lib/names'
import {act, toastModel} from '@/lib/actions'
import {api} from '@/lib/api'
import {age, ahead, now, shortName, since, span, when} from '@/lib/format'
import {FEED_KINDS, buildFeed, involving} from '@/lib/feed'
import type {Message} from '@/lib/feed'
import {bind, local} from '@/lib/reactive'
import {go, here} from '@/lib/route'
import {placeChip} from '@/components/place'
import {goalLine, originIcon, originPips, themeOf} from '@/components/pips'
import {showTech} from '@/components/research'
import {runnerAwayLine} from '@/components/runners'
import {STATUS, awaitsPerson, turnOf} from '@/lib/status'
import {$s, steers} from '@/lib/store'
import {cards, connect, expect, follow, followedLog, hosted, live, todos} from '@/lib/stream'
import {toolCalls} from '@/lib/tools'
import {nodeStep} from '@/lib/nodeline'
import type {Hosted, LogItem, Mode, PageNote, ResearchOrigin, SearchHit} from '@/lib/stream'
import type {FilesReport} from '@/lib/types'
import {NewSessionButton, stepsBar} from '@/components/home'
import {answersOf, answerTo} from '@/lib/answers'
import {mentions, recommended} from '@/lib/mentions'
import type {Mentions} from '@/lib/mentions'
import {highlight} from '@/lib/highlight'
import {inline, markdown, sessions} from '@/lib/markdown'
import {reduced} from '@/lib/motion'
import {continueList} from '@/lib/lists'
import {checkAvailable, hooks} from '@/lib/discuss'
import {byTech, grouped} from '@/lib/groups'
import type {Group} from '@/lib/groups'
import {deployAt, shortWords} from '@/lib/landing'
import {PILOT, autopilotChip, pilotDeciding, pilotLine, pilotState, pilotWhy, plane} from '@/components/autopilot'
import {startGuard} from '@/components/focus'
import {askProjects, inView, projectName, projectSelect, projects, projectTag, reposOf, several, shown} from '@/lib/projects'
import type {Project} from '@/lib/projects'
/**
* Claude Code's modes through `midas acp`, for a session not started yet (a
* running one offers its agent's own list). Trusted (bypassPermissions) does everything without asking.
*/
const START_MODES: Mode[] = [
{id: 'default', name: 'Manual'},
{id: 'acceptEdits', name: 'Accept edits'},
{id: 'plan', name: 'Plan'},
{id: 'auto', name: 'Auto'},
{id: 'bypassPermissions', name: 'Trusted'},
]
const BYPASS = 'bypassPermissions'
/** The models a session can start on: Claude Code's aliases, each the current model of its kind. */
const START_MODELS: Mode[] = [
{id: 'default', name: 'Default'},
{id: 'fable', name: 'Fable'},
{id: 'opus', name: 'Opus'},
{id: 'opus-fast', name: 'Opus ⚡ fast'},
{id: 'sonnet', name: 'Sonnet'},
{id: 'haiku', name: 'Haiku'},
]
/** The models a session's agent offers, and the one it is on, from its log. */
function modelsOf(items: LogItem[]): {available: Mode[]; current: string | null} {
let available: Mode[] = []
let current: string | null = null
for (const it of items) {
if (it.kind === 'models') available = it.available ?? []
if (it.kind === 'model') current = it.current ?? null
}
return {available, current}
}
/** Its models, for the dropdown: the one it is on; choosing asks it to change. */
function modelModel(s: Hosted) {
const {available, current} = modelsOf(live.following === s.id ? followedLog() : [])
const model = {
get value() {
return current
},
set value(v: string | null) {
if (v && v !== current) void act(`model: ${modeName(available, v)}`, () => api.setModel(s.id, v))
},
}
return {available, model}
}
/** The modes a session's agent offers, and the one it is in, from its log. */
function modesOf(items: LogItem[]): {available: Mode[]; current: string | null} {
let available: Mode[] = []
let current: string | null = null
for (const it of items) {
// Sessions opened before it was renamed still list "Bypass permissions".
if (it.kind === 'modes') available = (it.available ?? []).map((x) => (x.id === BYPASS ? {...x, name: 'Trusted'} : x))
if (it.kind === 'mode') current = it.current ?? null
}
return {available, current}
}
const modeName = (modes: Mode[], id: string | undefined) => modes.find((x) => x.id === id)?.name ?? id ?? '?'
/** A file the agent showed: a picture, a sound or a film, in place; anything else as a link. */
function media(session: string, it: LogItem) {
const src = `/v1/hosted/${session}/media/${encodeURIComponent(it.file ?? '')}`
const mime = it.mime ?? ''
const body = mime.startsWith('image/') ? (
<a href={src} target="_blank" rel="noopener">
<img class="msg__image" src={src} alt={it.caption ?? it.file} loading="lazy" />
</a>
) : mime.startsWith('audio/') ? (
<audio class="msg__audio" src={src} controls preload="metadata" />
) : mime.startsWith('video/') ? (
<video class="msg__video" src={src} controls preload="metadata" playsinline />
) : (
<a href={src} target="_blank" rel="noopener">
{it.file}
</a>
)
return (
<figure class="msg msg--agent msg__media">
{body}
{it.caption ? <figcaption class="hint">{it.caption}</figcaption> : null}
</figure>
)
}
/** The selected session, from the address (`/sessions/s3`). */
function selected(): string {
return here().match(/^sessions\/(s\d+)$/)?.[1] ?? ''
}
/** The address asks for a new session's composer. */
const isNew = () => here() === 'sessions/new'
function select(id: string) {
pinned = true
go(`sessions/${id}`)
}
/** Consecutive text from the agent as one message; tool calls by their id, updated in place. */
/**
* A tool call as one folded line — what it did, in the agent's own words where
* it gave some (a command's `description`) — opening to its command and output.
*/
/** A tool call in a few words: its own description where it gave one, else its title. */
function toolSummary(t: LogItem): string {
const said = typeof t.input?.description === 'string' ? t.input.description : ''
return said || t.title || 'a tool'
}
/**
* Calls made one after another, with nothing said between them, as one folded
* line: how many, and the last one; opening to each as its own folded line.
*/
function toolRun(calls: {t: LogItem; v: m.Children}[]): m.Children {
if (calls.length === 1) return calls[0].v
const last = calls[calls.length - 1].t
const running = calls.some(({t}) => t.status === 'pending' || t.status === 'in_progress')
const failed = calls.filter(({t}) => t.status === 'failed').length
const id = `run:${calls[0].t.id}`
return (
<details class={`msg__tools${failed ? ' msg__tool--failed' : ''}`} open={opened.has(id)} ontoggle={toggled(id)}>
<summary>
<span class="msg__tools-n">{calls.length} steps</span>
<span class="msg__tools-last">{toolSummary(last)}</span>
{running ? <span class="msg__tools-live" aria-label="running" /> : failed ? <span class="msg__tool-state">{failed} failed</span> : null}
</summary>
{opened.has(id) ? <div class="msg__tools-body">{calls.map(({v}) => v)}</div> : null}
</details>
)
}
/**
* The folds the person opened. A fold's insides are drawn only while it is open:
* a long session has hundreds of calls, and highlighting each one's command and
* output on every redraw, folded away, was most of the conversation's cost.
*/
const opened = new Set<string>()
function toggled(id: string) {
return (e: Event) => {
const open = (e.currentTarget as HTMLDetailsElement).open
if (open === opened.has(id)) (e as Event & {redraw?: boolean}).redraw = false
else if (open) opened.add(id)
else opened.delete(id)
}
}
function tool(t: LogItem, inner: LogItem[] = []) {
if (inner.length) return subagent(t, inner)
const input = t.input ?? {}
const said = typeof input.description === 'string' ? input.description : ''
const summary = toolSummary(t)
const command = typeof input.command === 'string' ? input.command : null
const rest = Object.fromEntries(Object.entries(input).filter(([k]) => k !== 'description' && k !== 'command'))
const running = t.status === 'pending' || t.status === 'in_progress'
const failed = t.status === 'failed'
const id = `tool:${t.id}`
return (
<details class={`msg__tool${failed ? ' msg__tool--failed' : ''}`} open={opened.has(id)} ontoggle={toggled(id)}>
<summary>
<span class="msg__tool-title">{summary}</span>
{running ? <span class="hint"> · running</span> : failed ? <span class="msg__tool-state"> · failed</span> : null}
</summary>
{opened.has(id) ? <div class="msg__tool-body">
{said && t.title && !command ? <div class="hint">{t.title}</div> : null}
{command ? (
<pre class="hl">{highlight(command, 'sh')}</pre>
) : Object.keys(rest).length ? (
<pre class="hl">{highlight(JSON.stringify(rest, null, 2), 'json')}</pre>
) : null}
{t.output ? <pre class="msg__tool-out">{t.output}</pre> : <div class="hint">{running ? 'no output yet' : 'no output'}</div>}
</div> : null}
</details>
)
}
/**
* A subagent (an Agent or Task call) as one folded line — what it was sent to
* do and how many calls it made — opening to those calls, each folded as the
* main agent's are, and what it reported back.
*/
function subagent(t: LogItem, inner: LogItem[]) {
const said = typeof t.input?.description === 'string' ? t.input.description : t.title || 'a subagent'
const running = t.status === 'pending' || t.status === 'in_progress'
const failed = t.status === 'failed'
const id = `agent:${t.id}`
return (
<details class={`msg__tool msg__agent${failed ? ' msg__tool--failed' : ''}`} open={opened.has(id)} ontoggle={toggled(id)}>
<summary>
<span class="msg__tool-title">Subagent: {said}</span>
<span class="hint">
{' '}
· {inner.length} tool call{inner.length === 1 ? '' : 's'}
{running ? ' · running' : ''}
</span>
{failed ? <span class="msg__tool-state"> · failed</span> : null}
</summary>
{opened.has(id) ? (
<div class="msg__tool-body">
{inner.map((x) => tool(x))}
{t.output ? <pre class="msg__tool-out">{t.output}</pre> : null}
</div>
) : null}
</details>
)
}
/** The last log item already there when the open session's log was first drawn: what comes after it arrived while watched. */
const seen = {id: '', upto: Infinity}
/** How long a chunk of the agent's text is paced over: the runner's reports come about this far apart (sessions.rs). */
const PACE_MS = 400
/**
* An agent's text; one that arrives while watched is paced in a word at a time,
* each chunk spread evenly over about the time until the next comes. Shown whole
* as it came, a reply moved up a line at a time; typed out to catch up (as it was
* until 2026-10-23), it raced and stopped. Text there before the page was opened,
* and every text under "reduce motion", is drawn whole. It draws its own markdown
* (`m.render` into its element), so a word or a chunk redraws this block and not the page.
*/
class Typed extends MithrilComponent<{text: string; fresh: boolean; n: number}> {
target = ''
/** Characters shown; the reveal runs from `from` at `since` to all of `target` over `over` ms. */
shown = 0
from = 0
since = 0
over = PACE_MS
/** When the last chunk came, to pace the next over the gap between them. */
came = 0
frame = 0
oncreate(v: m.VnodeDOM<{text: string; fresh: boolean; n: number}>) {
this.target = v.attrs.text
this.came = performance.now()
if (!v.attrs.fresh || reduced()) this.shown = this.target.length
this.pace(v.dom as HTMLElement)
}
// Every redraw of the page reached here and parsed the whole text again, changed or not.
onbeforeupdate(v: m.Vnode<{text: string; fresh: boolean; n: number}>, old: m.VnodeDOM<{text: string; fresh: boolean; n: number}>) {
return v.attrs.text !== old.attrs.text || v.attrs.fresh !== old.attrs.fresh || v.attrs.n !== old.attrs.n
}
onupdate(v: m.VnodeDOM<{text: string; fresh: boolean; n: number}>) {
const t = performance.now()
// Replaced rather than grown (another block took its place): drawn whole, never typed back.
const grew = v.attrs.text.startsWith(this.target.slice(0, this.shown))
this.target = v.attrs.text
if (!grew || reduced()) this.shown = this.target.length
this.over = Math.min(700, Math.max(120, t - this.came))
this.came = t
this.pace(v.dom as HTMLElement)
}
onremove() {
cancelAnimationFrame(this.frame)
}
/** From what is shown now to the end of the text, evenly over `over`, redrawn only when a word is added. */
pace(dom: HTMLElement) {
cancelAnimationFrame(this.frame)
this.from = this.shown
this.since = performance.now()
this.draw(dom)
}
draw(dom: HTMLElement) {
m.render(dom, markdown(this.target.slice(0, this.shown)) as m.Children)
following(dom)
if (this.shown >= this.target.length) return
const step = () => {
const f = Math.min(1, (performance.now() - this.since) / this.over)
const want = Math.round(this.from + (this.target.length - this.from) * f)
// To the end of the word it is in: a word comes whole, never a letter at a time.
const space = this.target.slice(want).search(/\s/)
const upto = f >= 1 || space < 0 ? this.target.length : want + space
if (upto > this.shown) {
this.shown = upto
this.draw(dom)
} else this.frame = requestAnimationFrame(step)
}
this.frame = requestAnimationFrame(step)
}
view(v: m.Vnode<{text: string; fresh: boolean; n: number}>) {
return <div class={`msg msg--agent md${v.attrs.fresh ? ' msg--enter' : ''}`} data-n={v.attrs.n} />
}
}
/**
* Answers on their way to the hub, by request: what was pressed. The card stays open until the
* hub's update comes, and with nothing to say the tap was taken, on a slow line the person
* tapped again and got a refusal for the second.
*/
const replying = local({to: {} as Record<string, string>})
/**
* Which ask an answer is for: its session and its place in the log. Not the request id alone,
* which is the agent's own numbering: every session's first ask is "1", and a runner started
* again counts from 1 once more, so keyed by it, one answer left every later "1" on "Sending…".
*/
const askKey = (s: Hosted, it: LogItem) => `${s.id}#${it.n}`
function reply(key: string, what: string, run: () => Promise<unknown>) {
if (replying.to[key]) return
replying.to = {...replying.to, [key]: what}
void act(what, run, {quiet: true}).then((ok) => {
// Answered, the card closes with the hub's update; refused, it can be answered again.
if (!ok) replying.to = Object.fromEntries(Object.entries(replying.to).filter(([k]) => k !== key))
})
}
/** Markdown parsed again only when its text changes, not on every redraw of the page. */
class Md extends MithrilComponent<{text: string}> {
onbeforeupdate(v: m.Vnode<{text: string}>, old: m.VnodeDOM<{text: string}>) {
return v.attrs.text !== old.attrs.text
}
view(v: m.Vnode<{text: string}>) {
return markdown(v.attrs.text) as m.Children
}
}
/** What a note is, on its card. */
const NOTE_KINDS: Record<string, string> = {say: 'note', overlap: 'overlap', landed: 'landed'}
/** `midas:web/src/app.css` → project and path; a path with no project stays whole. */
function splitFile(file: string): [string | null, string] {
const at = file.indexOf(':')
return at > 0 && !file.slice(0, at).includes('/') ? [file.slice(0, at), file.slice(at + 1)] : [null, file]
}
/** One side's places in a file, each that both sides change marked. */
function places(names: string[], both: Set<string>): m.Children {
return names.map((n, i) => <span>{i ? ', ' : ''}{both.has(n) ? <span class="note__same">{n}</span> : n}</span>)
}
/**
* A note midas passed on to the agent (another session's, or its own): a card
* saying who it is from, and for an overlap the files, a line each, with where
* either side changes them. The agent was sent the same as text
* (collab.rs `note_line`).
*/
function noteCard(note: PageNote, at: number): m.Children {
const about = note.about
const kind = note.kind ?? 'say'
const from = about?.with ?? (note.from === 'hub' ? null : note.from)
const label = about ? about.label : note.label
const branch = about ? about.branch : note.branch
const both = new Set((about?.files ?? []).flatMap((f) => f.you.filter((n) => f.them.includes(n))))
// The other side, as the hub names it (`s212`).
const there = about?.with ?? ''
return (
<div class={`note note--${kind}`}>
<div class="note__head">
<span class={`note__kind note__kind--${kind}`}>{NOTE_KINDS[kind] ?? 'midas'}</span>
{from ? <span class="note__from">{sessions(from)}</span> : null}
<span class="note__time">{clock(at)}</span>
{label || branch ? (
<div class="note__about">
{label ? <span class="note__label">{label}</span> : null}
{branch ? <span class="note__branch">{branch}</span> : null}
</div>
) : null}
</div>
{about ? (
<div class="note__body">
<p>
Also changes {about.files.length + (about.more ?? 0)} file{about.files.length + (about.more ?? 0) === 1 ? '' : 's'} changed here:
</p>
<ul class="note__files">
{about.files.map((f) => {
const [project, path] = splitFile(f.file)
return (
<li>
<span class="note__project">{project ?? ''}</span>
<code class="note__path">{path}</code>
{f.you.length || f.them.length ? (
<span class="note__where">
{f.you.length ? [<b>here</b>, ' ', places(f.you, both)] : null}
{f.you.length && f.them.length ? ' · ' : null}
{f.them.length ? [<b>{there}</b>, ' ', places(f.them, both)] : null}
</span>
) : null}
</li>
)
})}
{about.more ? <li class="note__more">and {about.more} more</li> : null}
</ul>
</div>
) : (
<div class="note__body md">{m(Md, {text: note.text ?? ''})}</div>
)}
{kind === 'say' && note.id ? (
<div class="note__foot">
{note.id} · the agent answers with <code>midas say --re {note.id}</code>
</div>
) : both.size ? (
<div class="note__foot">
Both change <span class="note__same">{[...both].join(', ')}</span>
</div>
) : null}
</div>
)
}
/**
* The first message, while the agent is still opening its session: it waits in
* the runner's queue until then, but it is the conversation's start, not a
* message queued behind a turn, so it shows there and not in the queue.
*/
function opening(s: Hosted, items: LogItem[]): NonNullable<Hosted['queue']>[number] | undefined {
const q = s.queue ?? []
return q.length && !items.some((it) => it.kind === 'user') ? q[0] : undefined
}
/**
* Messages sent from this page that the hub has not shown back yet: in the
* conversation at once, faded, rather than gone from the box and nowhere for the
* moment the runner takes to report them. `after` is the log's last line then.
*/
const sending = local({list: [] as {session: string; text: string; after: number; at: number}[]})
/** Whether the hub has shown a sent message back: in the log after it was sent, or in the line. */
function arrived(p: (typeof sending.list)[number], items: LogItem[], s: Hosted): boolean {
const same = (t: string | undefined) => !p.text || (t ?? '').trim() === p.text
return (
Date.now() - p.at > 30000 ||
items.some((it) => it.kind === 'user' && it.n > p.after && same(it.text)) ||
(s.queue ?? []).some((q) => same(q.text))
)
}
/**
* The open conversation's blocks as last drawn, by where each begins, with what
* they showed: a block whose content has not changed is handed to Mithril as the
* same vnode, which it skips. A long session is a thousand blocks, and building
* and comparing every one of them for each chunk the agent sends was most of a
* redraw on a phone. The blocks are keyed, so one that appears in between (a cut
* turn's line) moves the rest rather than diffing each against its neighbour.
*/
const drawn = {session: '', all: '', blocks: new Map<string, {sig: string; v: m.Vnode}>()}
/** A block kept as drawn, or made again when `sig` (all it shows that can change) differs. */
function block(key: string, sig: string, make: () => m.Children): m.Vnode {
const hit = drawn.blocks.get(key)
if (hit && hit.sig === sig) return hit.v
const v = make() as m.Vnode
v.key = key
drawn.blocks.set(key, {sig, v})
return v
}
/** What a tool call's line shows that can change: its state, its output, whether it is open. */
function toolSig(t: LogItem, inner: LogItem[] = []): string {
const one = (x: LogItem, kind: string) => `${x.id}|${x.status}|${x.title}|${x.output?.length ?? 0}|${opened.has(`${kind}:${x.id}`) ? 1 : 0}`
return inner.length ? `${one(t, 'agent')}[${inner.map((x) => one(x, 'tool')).join(',')}]` : one(t, 'tool')
}
/** The blocks drawn of a long conversation, until the person asks for the earlier ones or a search hit is among them. */
const RECENT_BLOCKS = 150
function render(items: LogItem[], s: Hosted) {
if (seen.id !== s.id) Object.assign(seen, {id: s.id, upto: items.length ? items[items.length - 1].n : Infinity})
else if (seen.upto === Infinity && items.length) seen.upto = items[items.length - 1].n
if (drawn.session !== s.id) Object.assign(drawn, {session: s.id, all: '', blocks: new Map()})
const fresh = (n: number) => n > seen.upto
// Each call as it stands now; a subagent's calls go under the call that started it.
const {calls: tools, children} = toolCalls(items)
const nested = new Set([...children.values()].flat().map((t) => t.id))
// Worked out once for the whole log, not once per block that asks.
const answers = answersOf(items)
const lastEnd = items.findLast((it) => it.kind === 'turn_end')
let modes: Mode[] | undefined
const modeList = () => (modes ??= modesOf(items).available)
const may = steers()
let mode: string | undefined
const out: m.Vnode[] = []
// The agent's text since the last other block: its chunks, joined only when its block is made again.
let text: string[] = []
let textAt = 0
let textEnd = 0
const flush = () => {
if (text.length) {
const [chunks, at] = [text, textAt]
out.push(block(`text:${at}`, `${textEnd}|${fresh(at)}`, () => m(Typed, {text: chunks.join(''), fresh: fresh(at), n: at})))
}
text = []
}
// Calls one after another, folded together once something else comes.
let calls: {t: LogItem; inner?: LogItem[]; n: number}[] = []
const flushCalls = () => {
if (calls.length) {
const run = calls
const sig = `${opened.has(`run:${run[0].t.id}`) ? 1 : 0}|${run.map((c) => toolSig(c.t, c.inner)).join(';')}`
out.push(block(`calls:${run[0].n}`, sig, () => {
const vs = run.map(({t, inner, n}) => {
const v = tool(t, inner) as m.Vnode<Record<string, unknown>>
v.attrs['data-n'] = n
if (fresh(n)) v.attrs.className = `${v.attrs.className ?? v.attrs.class ?? ''} msg--enter`.trim()
return {t, v}
})
return toolRun(vs)
}))
}
calls = []
}
const silent = new Set(['permission_answered', 'answered', 'modes', 'usage', 'tool_update', 'background', 'autopilot_deciding', 'autopilot_idle'])
// The autopilot deciding now: said on the request it decides, whose buttons stay.
const deciding = s.autopilot?.on && s.autopilot.state === 'deciding'
for (const it of items) {
if (it.kind === 'agent') {
if (!text.length) {
flushCalls()
textAt = it.n
}
text.push(it.text ?? '')
textEnd = it.n
continue
}
flush()
if (it.kind === 'tool') {
if (nested.has(it.id)) continue
const t = tools.get(it.id ?? '') ?? it
// A `midas take`, `wait` or `release` on its own: a short line of its own, not a raw command in a run.
const step = nodeStep(t)
if (step) {
flushCalls()
const id = `node:${t.id}`
const v = block(`node:${it.n}`, `${toolSig(t)}|${opened.has(id) ? 1 : 0}`, () => nodeStepLine(t, step, opened.has(id), toggled(id))) as m.Vnode<Record<string, unknown>>
v.attrs['data-n'] = it.n
out.push(v)
continue
}
calls.push({t, inner: children.get(it.id ?? ''), n: it.n})
continue
}
if (it.kind === 'mode') {
// Said only when it changes: the runner reports the mode at each turn, and the dropdown
// already shows the current one, so a line per turn was noise.
const was = mode
mode = it.current
if (was === undefined || was === it.current) continue
}
if (!silent.has(it.kind)) flushCalls()
const from = out.length
const key = `${it.kind}:${it.n}`
if (it.kind === 'user') {
// Queued: waiting until the turn running when it was sent has ended.
const waiting = !!it.queued && !(lastEnd && lastEnd.n > it.n)
const note = it.by === 'midas' ? it.note : undefined
if (note) out.push(block(key, '', () => noteCard(note, it.at)))
else if (it.by === PILOT)
out.push(block(key, `${waiting}`, () => (
<div class={`msg msg--pilot md${waiting ? ' msg--queued' : ''}`}>
<div class="pilot__by">{plane(12)} Autopilot</div>
{m(Md, {text: it.text ?? ''})}
{it.why ? <div class="msg__pilot-why">{it.why}</div> : null}
</div>
)))
else out.push(block(key, `${waiting}`, () => (
<div class={`msg msg--user md${it.by === 'midas' ? ' msg--midas' : ''}${waiting ? ' msg--queued' : ''}`}>
{it.images?.length ? (
<div class="msg__images">
{it.images.map((i) => (
<a
class={i.mime?.startsWith('image/') === false ? 'msg__file' : undefined}
href={`/v1/hosted/${s.id}/media/${encodeURIComponent(i.file)}`}
target="_blank"
rel="noopener"
>
{/* A device's log or recording is a file to open, not a picture. */}
{i.mime?.startsWith('image/') === false ? i.file : <img src={`/v1/hosted/${s.id}/media/${encodeURIComponent(i.file)}`} alt={i.file} loading="lazy" />}
</a>
))}
</div>
) : null}
{m(Md, {text: it.text ?? ''})}
{waiting ? <div class="msg__queued">queued · goes when this turn ends</div> : null}
{it.now ? <div class="msg__queued">sent now · the turn before it was stopped</div> : null}
</div>
)))
}
else if (it.kind === 'plan')
out.push(block(key, '', () => (
<ul class="msg__plan">
{(it.entries ?? []).map((e) => (
<li class={`plan--${e.status}`}>{e.content}</li>
))}
</ul>
)))
else if (it.kind === 'permission') {
const answered = answers.get(it)
const open = !answered && s.status === 'needs_permission'
const sending = replying.to[askKey(s, it)]
out.push(block(key, `${open}|${!!answered}|${may}|${sending ?? ''}|${open && deciding}`, () => (
<div class={`msg__permission${open ? '' : ' msg__permission--settled'}${open && deciding ? ' msg__permission--pilot' : ''}`}>
<div>
<b>May it?</b> {typeof it.input?.description === 'string' ? it.input.description : fileAsk(it) ?? it.title}
</div>
{asked(it.input)}
{open && deciding ? pilotDeciding() : null}
{open ? (
<div class="msg__choices">
{(it.options ?? []).map((o) => (
<Button
size="sm"
variant={o.kind.startsWith('allow') ? 'primary' : 'secondary'}
disabled={!may || !!sending}
onclick={() => reply(askKey(s, it), o.name, () => api.permit(s.id, it.request!, o.optionId))}
>
{sending === o.name ? 'Sending…' : o.name}
</Button>
))}
</div>
) : answered?.by === PILOT ? (
pilotWhy(`Autopilot: ${(it.options ?? []).find((o) => o.optionId === answered.option)?.name ?? answered.option}`, answered.why)
) : (
<div class="hint">{answered ? 'answered' : 'no longer asked'}</div>
)}
</div>
)))
} else if (it.kind === 'question') {
const given = answers.get(it)
const open = !given && s.status === 'needs_permission'
// Never kept as drawn: the card has its own state (the choices picked), which only a redraw of it shows.
out.push(m(QuestionCard, {key, s, it, open, answer: given, deciding: open && !!deciding}) as m.Vnode)
} else if (silent.has(it.kind)) {
// Shown on the request (or tool call) itself; the modes are the dropdown's, the usage the ring's,
// what runs in the background the status line's.
} else if (it.kind === 'mode') {
const name = modeName(modeList(), it.current)
out.push(block(key, name, () => (
<div class={`msg__mode${it.current === BYPASS ? ' msg__mode--bypass' : ''}`}>
mode: <b>{name}</b>
</div>
)))
} else if (it.kind === 'autopilot') {
out.push(block(key, '', () => (
<div class={`msg__mode msg__mode--pilot${it.on ? '' : ' msg__mode--pilot-off'}`}>
{plane(12)} {pilotLine(!!it.on, it.by, it.until, it.why)}
</div>
)))
if (it.on && it.goal) out.push(block(`${key}:goal`, '', () => <div class="msg__pilot-goal hint">goal: {it.goal}</div>))
} else if (it.kind === 'autopilot_left') {
out.push(block(key, '', () => <div class="msg__pilot-left">{pilotWhy('The autopilot leaves this to you', it.why, 'left')}</div>))
} else if (it.kind === 'autopilot_done') {
out.push(block(key, '', () => (
<div class="msg__finish hint pilot__done">
{plane(12)} The autopilot has nothing more to say: {it.why}
</div>
)))
} else if (it.kind === 'media') {
out.push(block(key, '', () => media(s.id, it)))
} else if (it.kind === 'turn_end') {
// A turn that ended as turns do says nothing: "· done ·" after every reply read as the
// session being done. One cut short says how, in words; the last one's is the end bar's.
const why = turnCut(it.reason)
if (why && it !== lastEnd) out.push(block(key, '', () => <div class="msg__turn msg__turn--cut">{why}</div>))
}
// Finishing, on the person's answer (sessions.rs `finish`): said where it happened.
else if (it.kind === 'finishing') out.push(block(key, '', () => <div class="msg__finish hint">Landed {String(it.sha ?? '').slice(0, 8)}: the session finishes once that is live.</div>))
// Carrying on later (sessions.rs `wake`): said where it was set, moved, cancelled or reached.
else if (it.kind === 'wake')
out.push(block(key, it.text ?? '', () => (
<div class="msg__finish hint">
{icon.clock()}{' '}
{it.woken
? `Carrying on as planned${it.by && it.by !== 'midas' ? `, at once on ${speaker(it.by).title}'s word` : ''}.`
: it.cancelled
? `No longer set to carry on${it.by ? ` (${speaker(it.by).title})` : ''}.`
: `Set to carry on ${it.when ? ahead(it.when) : 'later'}: ${it.text ?? ''}`}
</div>
)))
// Waiting on the person (sessions.rs `awaits`): said where it was set, put off, and how it ended.
else if (it.kind === 'awaits')
out.push(block(key, it.text ?? '', () => (
<div class="msg__finish hint">
{icon.key()}{' '}
{it.how === 'given'
? `Done by ${speaker(it.by ?? '').title}: ${it.text ?? ''}.`
: it.how === 'declined'
? `${speaker(it.by ?? '').title} won't: ${it.text ?? ''}.`
: it.how === 'done'
? `No longer waits on you: ${it.text ?? ''}.`
: it.snooze
? `Put off until ${ahead(it.snooze)}.`
: `Waits on you: ${it.text ?? ''}`}
</div>
)))
else if (it.kind === 'finished')
out.push(block(key, s.branch ?? '', () => (
<div class="msg__finish">
{it.outcome === 'dropped'
? `Finished: dropped, nothing landed. Its branch ${s.branch} stays.`
: it.outcome === 'done'
? `Finished: done. Its branch ${s.branch} stays; reopen it to go on.`
: `Finished: live${it.live_at ? ` since ${new Date(Number(it.live_at) * 1000).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'})}` : ''}. The session ended and moved to Finished; its branch ${s.branch} stays.`}
</div>
)))
else out.push(block(key, '', () => <div class={`msg__status ${it.kind === 'error' ? 'msg__status--error' : ''}`}>{it.text}</div>))
// Which log item each block is, for a search hit to be found in the conversation.
// What arrived while watched comes in softly; what was there is simply there.
for (const v of out.slice(from)) {
const a = v.attrs as Record<string, unknown> | undefined
if (!a || a['data-n'] !== undefined) continue
a['data-n'] = it.n
// Hyperscript has moved a `class` into `className` already.
if (fresh(it.n)) a.className = `${a.className ?? a.class ?? ''} msg--enter`.trim()
}
}
flush()
flushCalls()
// Its way to live, as short lines where each step happened: before the first block from after it.
const atOf = new Map(items.map((it) => [it.n, it.at]))
for (const mile of milestones(s, items.some((it) => it.kind === 'finishing'))) {
const i = out.findIndex((v) => (atOf.get(Number((v.attrs as Record<string, unknown> | undefined)?.['data-n'])) ?? 0) > mile.at)
out.splice(i < 0 ? out.length : i, 0, mile.view)
}
// Only the latest blocks, until the earlier ones are asked for: a search hit among them asks.
let shown = out
const hidden = drawn.all === s.id ? 0 : out.length - RECENT_BLOCKS
if (hidden > 0) {
const firstShown = Number((out[hidden].attrs as Record<string, unknown> | undefined)?.['data-n'] ?? 0)
if (jump && jump.id === s.id && jump.n < firstShown) {
showAll(s.id)
return render(items, s)
}
shown = [
<div key="earlier" class="msg__earlier">
<Button size="sm" variant="secondary" onclick={() => showAll(s.id)}>
Show {hidden} earlier
</Button>
</div>,
...out.slice(hidden),
]
}
const first = opening(s, items)
if (first) shown.push(<div key="opening" class="msg msg--user md">{markdown(first.text ?? '')}</div>)
sending.list.forEach((p, i) => {
if (p.session === s.id && !arrived(p, items, s)) shown.push(<div key={`sending:${p.at}:${i}`} class="msg msg--user md msg--sending">{markdown(p.text)}</div>)
})
const doing = activity(items, s)
if (doing)
shown.push(
<div key="busy" class="msg__busy">
<span class="typing" aria-hidden="true">
<i />
<i />
<i />
</span>
<span class="msg__doing">{doing.text}…</span>
<Elapsed since={doing.since} typical={doing.typical} />
</div>,
)
else if (!first) {
const end = endBar(s, lastEnd)
if (end) {
end.key = 'end'
shown.push(end)
}
}
// How it gets a node, under it all: in line and who holds them, or the node it is on.
const node = nodeFoot(s)
if (node) shown.push(node)
return shown
}
/**
* Every block of the open conversation from now on. Those kept as drawn are
* made again: one that was drawn and then left the window is no longer in the
* page, and Mithril must not be handed it as though it were.
*/
function showAll(id: string) {
drawn.all = id
drawn.blocks.clear()
}
/** How a turn was cut short, in words; null for one that ended as turns do. */
function turnCut(reason: string | undefined): string | null {
switch (reason) {
case undefined:
case 'end_turn':
return null
case 'cancelled':
return 'Stopped before it finished'
case 'max_tokens':
return 'Cut off: its reply ran too long'
case 'max_turn_requests':
return 'Stopped: too many steps in one turn'
case 'refusal':
return 'It declined to go on'
default:
return `Stopped (${reason})`
}
}
/**
* Idle, at the foot of the conversation once a turn has ended and nothing runs
* for it: since when, how it stopped, and where its branch is. Nothing while it
* works, asks (the card above is the signal) or has finished (its own line says so).
*/
/** When a landed session goes live, as far as the hub has planned it: "live around 12:00". */
function liveWhen(s: Hosted): string {
const j = journeyOf(s)
const at = j ? deployAt(j.deploy) : null
if (j?.deploy.kind === 'deploying') return 'deploying'
if (!at) return 'live with the next deploy'
const time = new Date(at * 1000).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'})
return j?.deploy.kind === 'waits' ? `live by ${time} at the latest` : `live around ${time}`
}
function endBar(s: Hosted, last: LogItem | undefined): m.Vnode | null {
if (s.status !== 'waiting' || s.finished || s.imported) return null
const c = cards().find((x) => x.session === s.owner)
const where =
s.finish ? 'on main · the session finishes once that is live'
: c?.stage === 'waiting_to_land' || c?.stage === 'landing' ? 'landing'
: c?.stage === 'landed' ? (c.live ? 'landed and live' : `on main · ${liveWhen(s)}`)
: null
const cut = turnCut(last?.reason)
return (
<div class="msg__end">
<span class="msg__end-dot" aria-hidden="true" />
<span>
<b>{s.awaits && !((s.awaits.snooze ?? 0) > now()) ? 'Waits on you' : s.wake ? `Carries on ${ahead(s.wake.at)}` : 'Idle'}</b>
{cut ? ` · ${cut.charAt(0).toLowerCase()}${cut.slice(1)}` : ''}
{last ? ` · since ${clock(last.at)}` : ''}
{where ? ` · ${where}` : ''}
</span>
<span class="hint">
{s.awaits
? 'It goes on once you have done what it says below.'
: s.wake
? 'midas wakes it then; reply below to go on sooner.'
: `Reply below to go on${s.finish || c?.stage === 'landed' ? '' : ', or Mark done in About when it is finished'}.`}
</span>
</div>
)
}
/** A span of seconds, short: "40m", "3h", "2d". */
const ago = (secs: number) => (secs < 3600 ? `${Math.max(1, Math.round(secs / 60))}m` : secs < 86400 ? `${Math.round(secs / 3600)}h` : `${Math.round(secs / 86400)}d`)
/** What a permission request would run: the command itself, or what the tool was given. */
function asked(input: LogItem['input']) {
if (!input) return null
if (typeof input.command === 'string') return <pre class="msg__asked hl">{highlight(input.command, 'sh')}</pre>
const file = typeof input.file_path === 'string' ? input.file_path : ''
const ext = file.split('.').pop()?.toLowerCase() ?? ''
// A file it would write: what goes in it, as it will read (Markdown drawn), not as JSON.
if (typeof input.content === 'string')
return ext === 'md' ? (
<div class="msg__asked msg__asked--doc md">{markdown(input.content.replace(/^---\n([\s\S]*?)\n---\n/, '```yaml\n$1\n```\n'))}</div>
) : (
<pre class="msg__asked hl">{highlight(input.content, ext)}</pre>
)
// A change to one: the lines that go, and the lines that come.
if (typeof input.old_string === 'string' && typeof input.new_string === 'string')
return (
<div class="msg__edit">
{input.old_string ? <pre class="msg__asked msg__asked--gone">{input.old_string}</pre> : null}
<pre class="msg__asked msg__asked--new hl">{highlight(input.new_string, ext)}</pre>
</div>
)
const rest = Object.fromEntries(Object.entries(input).filter(([k]) => k !== 'description'))
return Object.keys(rest).length ? <pre class="msg__asked hl">{highlight(JSON.stringify(rest, null, 2), 'json')}</pre> : null
}
/**
* A request to write or change a file, in words: "write docs/x.md", the path
* from its worktree on (where every session's files are; the rest says nothing).
*/
function fileAsk(it: LogItem): string | null {
const path = it.input?.file_path
if (typeof path !== 'string') return null
const verb = typeof it.input?.content === 'string' ? 'write' : typeof it.input?.new_string === 'string' ? 'change' : null
if (!verb) return null
return `${verb} ${path.replace(/^.*\/worktrees\/[^/]+\//, '')}`
}
/** What the person is writing to the open session; kept while they look elsewhere. */
const draft = local({text: ''})
/** Follow the conversation down as it grows, unless the person scrolled up to read. */
let pinned = true
/**
* Until when, just opened, the conversation is put at its end at once as it grows rather
* than glided to: its log comes over the socket after the page is drawn, and pictures
* load after that, so gliding opened a long session at its top and slid all the way
* down. Each growth meanwhile holds it a little longer; the person's own hand ends it.
*/
let landing = 0
const LANDING = 1500
const LANDING_MAX = 8000
let openedAt = 0
const landed = () => (landing = 0)
const HANDS = ['wheel', 'touchstart', 'pointerdown', 'keydown'] as const
/** The Shell's content column scrolls, not the log: that is what follows the conversation down. */
const followDown = {
oncreate: (v: m.VnodeDOM) => {
openedAt = performance.now()
landing = openedAt + LANDING
const el = (v.dom as HTMLElement).closest('.m-shell__content')
for (const h of HANDS) el?.addEventListener(h, landed, {passive: true})
// Opened, it is at its end at once: only what arrives after glides.
stick(v.dom as HTMLElement, true)
// A picture or a film grows the log after it is drawn: follow that too.
const watch = new ResizeObserver(() => stick(v.dom as HTMLElement))
watch.observe(v.dom)
;(v.dom as HTMLElement & {watch?: ResizeObserver}).watch = watch
},
// The observer above sees the log grow, after layout. Measuring here on every redraw (a
// keystroke, a board update) made the browser lay the whole conversation out mid-redraw.
// Only a search hit, which grows nothing, still needs it.
onupdate: (v: m.VnodeDOM) => {
if (jump) stick(v.dom as HTMLElement)
},
onremove: (v: m.VnodeDOM) => {
;(v.dom as HTMLElement & {watch?: ResizeObserver}).watch?.disconnect()
const el = (v.dom as HTMLElement).closest('.m-shell__content')
for (const h of HANDS) el?.removeEventListener(h, landed)
landing = 0
// Its blocks left the page with it: drawn again from nothing when it comes back.
drawn.session = ''
},
}
/** Scrolled up to read while more arrived: a chip says so, and brings the person down to it. */
function showNew(dom: HTMLElement, on: boolean) {
dom.parentElement?.querySelector('.jump-new')?.classList.toggle('is-shown', on)
}
/** To the end of the conversation, gliding. */
function toLatest(e: Event) {
const el = (e.currentTarget as HTMLElement).closest('.m-shell__content')
pinned = true
el?.scrollTo({top: el.scrollHeight, behavior: 'smooth'})
showNew(e.currentTarget as HTMLElement, false)
}
/** The conversation gliding down to its end: the frame it waits on, and where it last put the scroll. */
const glide = {frame: 0, at: 0}
/**
* Down to the end of the conversation, a share of the way each frame. Set in one go, the
* page jumped by a whole message as it came; chasing the end, a reply that streams in
* chunk by chunk keeps sliding up as one movement.
*/
function glideDown(el: HTMLElement) {
if (glide.frame) return
const step = () => {
const gap = el.scrollHeight - el.clientHeight - el.scrollTop
if (!pinned || gap < 1) {
glide.frame = 0
return
}
el.scrollTop += Math.max(1, gap * 0.18)
glide.at = el.scrollTop
glide.frame = requestAnimationFrame(step)
}
glide.frame = requestAnimationFrame(step)
}
/** A block that grew by itself (Typed pacing a reply in), with no redraw of the page: followed down as `stick` would. */
function following(dom: HTMLElement) {
const el = dom.closest('.m-shell__content') as HTMLElement | null
if (!el || !pinned) return
if (reduced() || performance.now() < landing) el.scrollTop = el.scrollHeight
else glideDown(el)
}
function stick(dom: HTMLElement, at = false) {
const el = (dom.closest('.m-shell__content') as HTMLElement | null) ?? dom
el.onscroll = () => {
// The glide's own scrolling, short of the end while it moves: still following.
if (glide.frame && el.scrollTop >= glide.at - 1) return
pinned = el.scrollHeight - el.scrollTop - el.clientHeight < 80
if (pinned) showNew(dom, false)
}
const grew = el.scrollHeight > Number(el.dataset.height ?? 0) + 8
el.dataset.height = String(el.scrollHeight)
if (!pinned && grew) showNew(dom, true)
if (jump && jump.id === live.following && live.logNext >= jump.n) {
// The last block at or before the item: an agent's text is many items in one.
const at = [...dom.querySelectorAll<HTMLElement>('[data-n]')].filter((b) => Number(b.dataset.n) <= jump!.n).pop()
jump = null
if (at) {
pinned = false
at.scrollIntoView({block: 'center'})
at.classList.add('msg--found')
setTimeout(() => at.classList.remove('msg--found'), 2400)
return
}
}
if (!pinned) return
const now = performance.now()
if (now < landing) {
if (grew) landing = Math.min(openedAt + LANDING_MAX, now + LANDING)
at = true
}
if (at || reduced()) el.scrollTop = el.scrollHeight
else glideDown(el)
}
/** The session the address names (`/sessions/s3`), if there is one. */
export function openSession(): Hosted | undefined {
const id = selected()
return hosted().find((h) => h.id === id)
}
const ended = (s: Hosted) => s.status === 'stopped' || s.status === 'failed'
/** Where its imported conversation was had, in words. */
const importedFrom = (s: Hosted) => `${s.imported?.from ?? 'elsewhere'}${s.imported?.cwd ? `, in ${s.imported.cwd}` : ''}`
/** Its modes, and a model for the dropdown: it shows the mode the agent says it is in; choosing asks it to change. */
function modeModel(s: Hosted) {
const {available, current} = modesOf(live.following === s.id ? followedLog() : [])
const model = {
get value() {
return current
},
set value(v: string | null) {
if (!v || v === current) return
const change = () => act(`mode: ${modeName(available, v)}`, () => api.setMode(s.id, v))
if (v !== BYPASS) {
void change()
return
}
void askConfirm({
title: 'Trust it?',
text: 'It will run any command and change any file without asking you first, until you switch it back.',
yes: 'Trust it',
danger: true,
}).then((ok) => {
if (ok) void change()
})
},
}
return {available, current, model}
}
/** Images pasted (or dropped) into the open composer, uploaded at once, sent with the next message. */
const pasted = local({items: [] as {token: string; url: string; name: string}[], uploading: 0})
async function attach(files: File[]) {
for (const f of files.filter((x) => x.type.startsWith('image/'))) {
// A pasted screenshot has no name of its own: one from its type.
const name = f.name && f.name !== 'image' ? f.name : `pasted.${f.type.split('/')[1] ?? 'png'}`
pasted.uploading++
try {
const {token} = await api.upload(f, name)
pasted.items = [...pasted.items, {token, url: URL.createObjectURL(f), name}]
} catch (e) {
toast(toastModel, {tone: 'danger', title: `${name}: not attached`, message: (e as Error).message, timeout: 10000})
} finally {
pasted.uploading--
}
}
}
/**
* The images a clipboard or a drag carries. Some browsers (on phones above all)
* list a pasted image only among its items, not its files: both are read.
*/
function imagesOf(dt: DataTransfer | null | undefined): File[] {
if (!dt) return []
const fromItems = [...(dt.items ?? [])]
.filter((i) => i.kind === 'file' && i.type.startsWith('image/'))
.map((i) => i.getAsFile())
.filter((f): f is File => f != null)
return fromItems.length ? fromItems : [...(dt.files ?? [])].filter((f) => f.type.startsWith('image/'))
}
/** Enter is a new line in every message box (a list goes on); this sends. */
const sends = (e: KeyboardEvent) => e.key === 'Enter' && (e.metaKey || e.ctrlKey) && !e.isComposing
const SEND_KEY = /Mac|iPhone|iPad/.test(navigator.platform) ? '⌘' : 'Ctrl'
/** A box's hint at its keys, where there is a keyboard: a phone sends with its button. */
const keys = (hint: string) => (matchMedia('(pointer: coarse)').matches ? '' : ` — ${hint.replaceAll('Mod', SEND_KEY)}`)
/** Paste or drop onto a message box: images become attachments, text stays text. */
const imageInput = {
onpaste: (e: ClipboardEvent) => {
const files = imagesOf(e.clipboardData)
if (files.length && steers()) {
e.preventDefault()
void attach(files)
}
},
// An Android keyboard's clipboard (Gboard's) pastes an image as input, not as a paste event.
onbeforeinput: (e: InputEvent) => {
// A new line on a list's line starts the next item: asked here, not on keydown, because a
// phone's keyboard says Enter as input and not always as a key.
if (e.inputType === 'insertLineBreak' || e.inputType === 'insertParagraph') {
const box = e.target as HTMLTextAreaElement
const next = continueList(box.value, box.selectionStart, box.selectionEnd)
if (!next) return
e.preventDefault()
box.value = next.text
box.setSelectionRange(next.at, next.at)
// The box's own oninput keeps the draft.
box.dispatchEvent(new Event('input', {bubbles: true}))
return
}
if (e.inputType !== 'insertFromPaste' && e.inputType !== 'insertFromDrop') return
const files = imagesOf(e.dataTransfer)
if (files.length && steers()) {
e.preventDefault()
void attach(files)
}
},
ondragover: (e: DragEvent) => {
if ([...(e.dataTransfer?.items ?? [])].some((i) => i.kind === 'file')) e.preventDefault()
},
ondrop: (e: DragEvent) => {
const files = imagesOf(e.dataTransfer)
if (files.length && steers()) {
e.preventDefault()
void attach(files)
}
},
}
/**
* A + in the composer that opens the picker: on a phone the camera, the
* gallery or files — where pasting an image into a text box may not work.
*/
function attachButton(): m.Children {
return (
<label class={`attach__add${steers() ? '' : ' is-disabled'}`} title="add an image (or paste one into the message)">
<input
type="file"
accept="image/png,image/jpeg,image/gif,image/webp"
multiple
disabled={!steers()}
onchange={(e: Event) => {
const input = e.target as HTMLInputElement
void attach([...(input.files ?? [])])
input.value = ''
}}
/>
{/* Drawn, not typed: the font's + sits above the middle of the ring. */}
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true">
<path d="M12 5v14M5 12h14" />
</svg>
<span class="sr-only">add an image</span>
</label>
)
}
/** The images waiting to go with the message, each with a way to take it back. */
function attachments(): m.Children {
if (!pasted.items.length && !pasted.uploading) return null
return (
<div class="attach">
{pasted.items.map((x) => (
<span class="attach__item" title={x.name}>
<img src={x.url} alt={x.name} />
<button
type="button"
aria-label={`remove ${x.name}`}
onclick={() => {
URL.revokeObjectURL(x.url)
pasted.items = pasted.items.filter((y) => y.token !== x.token)
}}
>
×
</button>
</span>
))}
{pasted.uploading ? <span class="attach__item attach__item--loading hint">…</span> : null}
</div>
)
}
/** The tokens to send, and the composer cleared of them. */
function takeAttachments(): string[] {
const tokens = pasted.items.map((x) => x.token)
for (const x of pasted.items) URL.revokeObjectURL(x.url)
pasted.items = []
return tokens
}
/** What the "carries on" bar keeps between draws: moving it, and to when (a `datetime-local` value). */
const laterUi = local({moving: '', to: ''})
/** A unix time as a `datetime-local` input's value, in the browser's own zone. */
function localInput(t: number): string {
const d = new Date(t * 1000)
const p = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}`
}
/** Tomorrow at nine, the browser's time: the move a person makes most. */
function tomorrowNine(): number {
const d = new Date()
d.setDate(d.getDate() + 1)
d.setHours(9, 0, 0, 0)
return Math.floor(d.getTime() / 1000)
}
/**
* When the session carries on by itself (sessions.rs, `wake`), above the
* message box: when and what, and Now, Move and Cancel. Without it a "the
* rest tomorrow" was a promise nothing kept, and nothing on the page said so.
*/
function laterPanel(s: Hosted): m.Children {
const w = s.wake
if (!w) return null
const moving = laterUi.moving === s.id
const move = (at: number) =>
void act('moved', () => api.moveWake(s.id, at), {quiet: true}).then((ok) => {
if (ok) laterUi.moving = ''
})
return (
<div class="later">
<div class="later__head">
<span class="later__mark" aria-hidden="true">
{icon.clock()}
</span>
<span class="later__when" title={when(w.at)}>
Carries on <b>{ahead(w.at)}</b> <span class="hint">in {span(w.at - now())}</span>
</span>
<span class="later__actions">
<Button size="sm" variant="ghost" disabled={!steers()} onclick={() => void act('carrying on now', () => api.wakeNow(s.id))}>
Now
</Button>
<Button
size="sm"
variant="ghost"
disabled={!steers()}
onclick={() => {
laterUi.moving = moving ? '' : s.id
laterUi.to = localInput(w.at)
}}
>
Move
</Button>
{confirmButton(`wake-${s.id}`, {label: 'Cancel', armedLabel: 'Cancel it?', disabled: !steers(), title: 'it will not carry on by itself', run: () => act('cancelled', () => api.cancelWake(s.id))})}
</span>
</div>
<div class="later__text">{w.text}</div>
{moving ? (
<div class="later__move">
<input
type="datetime-local"
value={laterUi.to}
oninput={(e: Event) => (laterUi.to = (e.target as HTMLInputElement).value)}
/>
<Button size="sm" variant="primary" disabled={!laterUi.to} onclick={() => move(Math.floor(new Date(laterUi.to).getTime() / 1000))}>
Move
</Button>
<Button size="sm" variant="ghost" onclick={() => move(now() + 3600)}>
In an hour
</Button>
<Button size="sm" variant="ghost" onclick={() => move(tomorrowNine())}>
Tomorrow 9:00
</Button>
</div>
) : null}
</div>
)
}
/** What the person types into the field of the secret a session waits for: never kept past it being sent. */
const awaitsUi = local({value: '', sending: ''})
/** Where a secret the session waits for goes, in words: never the conversation. */
function secretGoes(a: NonNullable<Hosted['awaits']>): string {
const s = a.secret
if (!s) return ''
return s.kind === 'remote'
? `It goes to the hub, as the token it signs in to ${s.url ?? s.name} with. The session hears that it is set, never what it is.`
: `It goes to the hub, as the bot secret ${s.name} for ${s.target}. The session hears that it is set, never what it is.`
}
/**
* What the session waits on the person for (sessions.rs, `awaits`), above the
* message box: the steps, a field for a secret, and Tomorrow and Won't. Said
* only in a message, a "paste a token" ended the turn as idle, and once landed
* the session sat under Landed today with the step undone (2026-11-14).
*/
function awaitsPanel(s: Hosted): m.Children {
const a = s.awaits
if (!a) return null
const snoozed = (a.snooze ?? 0) > now()
const give = () => {
const value = awaitsUi.value.trim()
if (!value || awaitsUi.sending) return
awaitsUi.sending = s.id
void act('given', () => api.giveAwaited(s.id, value)).then((ok) => {
awaitsUi.sending = ''
if (ok) awaitsUi.value = ''
})
}
return (
<div class={`awaits${snoozed ? ' awaits--snoozed' : ''}`}>
<div class="awaits__tag">
{icon.key()} {snoozed ? `Waits on you · put off until ${ahead(a.snooze!)}` : 'Waits on you'}
</div>
<b class="awaits__text">{a.text}</b>
{a.steps ? <div class="awaits__steps msg__text">{markdown(a.steps)}</div> : null}
{a.secret ? (
<>
<div class="awaits__field">
<input
type="password"
autocomplete="off"
placeholder="paste it here"
value={awaitsUi.value}
disabled={!steers() || !!awaitsUi.sending}
oninput={(e: Event) => (awaitsUi.value = (e.target as HTMLInputElement).value)}
// A block, not `e.key === 'Enter' && give()`: a handler that returns false
// stops the key, so every other key (a paste, an Android keyboard's) was lost.
onkeydown={(e: KeyboardEvent) => {
if (e.key === 'Enter') give()
}}
/>
<Button size="sm" variant="primary" disabled={!steers() || !awaitsUi.value.trim() || !!awaitsUi.sending} onclick={give}>
Save
</Button>
</div>
<span class="hint">{secretGoes(a)}</span>
</>
) : (
<span class="hint">Done it? Say so below, and the session goes on.</span>
)}
<div class="awaits__actions">
{snoozed ? null : (
<Button size="sm" variant="ghost" disabled={!steers()} onclick={() => void act('put off until tomorrow', () => api.snoozeAwaited(s.id, tomorrowNine()))}>
Tomorrow 9:00
</Button>
)}
{confirmButton(`awaits-${s.id}`, {
label: "Won't do it",
armedLabel: 'Tap again: it goes on without',
disabled: !steers(),
title: 'the session is told, and goes on without it',
run: () => act('declined', () => api.declineAwaited(s.id)),
})}
</div>
</div>
)
}
/** What the queue panel keeps between draws: open or folded, the one being edited, the one dragged. */
const queueUi = local({open: true, editing: 0, text: '', dragging: 0, over: -1})
/**
* Messages waiting for the agent, above the message box: each can be edited,
* dragged to another place, removed or sent now until the agent takes it;
* Clear all empties the line. What the runner has is what shows.
*/
function queuePanel(s: Hosted): m.Children {
// The first message while the session opens is in the conversation already (`opening`).
const skip = opening(s, live.following === s.id ? followedLog() : []) ? 1 : 0
const q = (s.queue ?? []).slice(skip)
// Waiting for the person: what is in the line goes to the agent the moment the runner reads
// it, so a message sent to an idle session flashed up here for a poll before it was taken.
if (!q.length || s.status === 'waiting') return null
// `quiet`: sending says nothing when it went (the conversation shows it); a refusal still does.
const op = (what: string, o: 'remove' | 'edit' | 'move' | 'clear' | 'now', fields: {qid?: number; text?: string; to?: number} = {}, quiet = false) =>
void act(what, () => api.queueOp(s.id, o, fields), {quiet})
return (
<div class="queue">
<div class="queue__head">
<button class="queue__fold" type="button" onclick={() => (queueUi.open = !queueUi.open)}>
{queueUi.open ? '▾' : '▸'} {q.length} queued
</button>
<span class="hint">sent in this order, each when the turn before it ends</span>
<button class="queue__clear" type="button" disabled={!steers()} onclick={() => op('queue cleared', 'clear')}>
Clear all
</button>
</div>
{queueUi.open
? q.map((x, i) => (
<div
class={`queue__row${queueUi.over === i && queueUi.dragging && queueUi.dragging !== x.qid ? ' queue__row--over' : ''}`}
draggable={steers() && queueUi.editing !== x.qid}
ondragstart={(e: DragEvent) => {
queueUi.dragging = x.qid
e.dataTransfer?.setData('text/plain', String(x.qid))
}}
ondragover={(e: DragEvent) => {
e.preventDefault()
queueUi.over = i
}}
ondragend={() => {
queueUi.dragging = 0
queueUi.over = -1
}}
ondrop={(e: DragEvent) => {
e.preventDefault()
const qid = queueUi.dragging
queueUi.dragging = 0
queueUi.over = -1
if (qid && qid !== x.qid) op('moved', 'move', {qid, to: i + skip})
}}
>
<span class="queue__grip" title="drag to another place">⋮⋮</span>
{queueUi.editing === x.qid ? (
<span class="queue__edit">
<textarea
rows={2}
value={queueUi.text}
oninput={(e: Event) => (queueUi.text = (e.target as HTMLTextAreaElement).value)}
onkeydown={(e: KeyboardEvent) => {
if (sends(e)) {
e.preventDefault()
if (queueUi.text.trim()) op('edited', 'edit', {qid: x.qid, text: queueUi.text})
queueUi.editing = 0
} else if (e.key === 'Escape') {
queueUi.editing = 0
}
}}
/>
<Button
size="sm"
variant="primary"
disabled={!queueUi.text.trim()}
onclick={() => {
op('edited', 'edit', {qid: x.qid, text: queueUi.text})
queueUi.editing = 0
}}
>
Save
</Button>
<Button size="sm" variant="ghost" onclick={() => (queueUi.editing = 0)}>
Cancel
</Button>
</span>
) : (
<span class="queue__text">
{x.images?.length ? (
<span class="queue__images">
{x.images.map((i) => (
<img src={`/v1/hosted/${s.id}/media/${encodeURIComponent(i.file)}`} alt={i.file} loading="lazy" />
))}
</span>
) : null}
{x.text}
</span>
)}
{queueUi.editing === x.qid ? null : (
<span class="queue__actions">
<button type="button" title="take it back" aria-label="remove" disabled={!steers()} onclick={() => op('removed', 'remove', {qid: x.qid})}>
{icon.trash()}
</button>
<button
type="button"
title="edit it"
aria-label="edit"
disabled={!steers()}
onclick={() => {
queueUi.editing = x.qid
queueUi.text = x.text
}}
>
{icon.pencil()}
</button>
<button type="button" class="queue__now" disabled={!steers()} title="stop what it is doing and send this first" onclick={() => op('sent now', 'now', {qid: x.qid}, true)}>
Send now
</button>
</span>
)}
</div>
))
: null}
</div>
)
}
/** The question a session waits on, if its log is here and the question has an "Other" box to take a typed answer. */
function openQuestion(s: Hosted): LogItem | undefined {
if (s.status !== 'needs_permission' || live.following !== s.id) return undefined
const log = followedLog()
for (let i = log.length - 1; i >= 0; i--) {
const q = log[i]!
if (q.kind !== 'question') continue
return answerTo(log, q) || !otherBoxes(q).length ? undefined : q
}
return undefined
}
const otherBoxes = (q: LogItem) => Object.keys(q.schema?.properties ?? {}).filter((k) => k.endsWith('_custom'))
/** A typed message as a question's answer: its "Other", for each question it asks. */
const typedAnswer = (q: LogItem, text: string) => Object.fromEntries(otherBoxes(q).map((k) => [k, text]))
/** The message box under the conversation: in the Shell's footer, so it stays while the conversation scrolls. Folded on a phone, it carries the header's buttons (`tools`). */
export function sessionFooter(tools: (m.Vnode | null)[] = []): m.Children {
const s = openSession()
// No session open: a new one's composer; one asked for but not known (yet): nothing.
if (!s) return isNew() ? newComposer(tools) : null
// Imported: a record of a conversation had elsewhere, to read.
if (s.imported)
return (
<div class="session__reopen">
<span class="hint">
Imported from {importedFrom(s)}. Claude Code had this conversation there; midas keeps it to read and search, and cannot reopen it.
</span>
</div>
)
// Ended: its branch keeps its work, and it can be picked up where it left off.
// An editor's: it goes on there, never here.
if (ended(s) && s.local)
return (
<div class="session__reopen">
<span class="hint">
{s.back?.pending
? `Handed back to ${s.local.client} on ${s.local.machine}: open the thread there to go on. Its work is on ${s.back.branch}, and comes into the checkout if that has not changed since.`
: s.gone
? `${s.local.client} on ${s.local.machine} no longer has this thread open, so nothing here reaches it. Open it there again to go on; this page follows it when it does.`
: `This session ran in ${s.local.client} on ${s.local.machine}. Open it there again to go on; this page follows it when it does.`}
</span>
</div>
)
// Ended, but set to carry on: the time is what matters, and midas reopens it then.
if (ended(s) && (s.wake || s.awaits) && !s.finished)
return (
<div class="session__say">
{awaitsPanel(s)}
{laterPanel(s)}
</div>
)
if (ended(s))
return (
<div class="session__reopen">
<span class="hint">
{s.finished ? 'Finished.' : s.status === 'failed' ? 'This session failed.' : 'This session has ended.'} Its branch <code>{s.branch}</code> keeps its work{s.finished ? ': reopen it to go on.' : '.'}
</span>
<Button variant="primary" disabled={!steers()} onclick={() => act(`${s.id} reopened`, () => api.reopen(s.id))}>
Reopen
</Button>
</div>
)
// A question waits: what is typed answers it, rather than stopping the turn (which throws the
// question away) or queueing behind it (which waits for the answer it is).
const asked = pasted.items.length ? undefined : openQuestion(s)
/** Send it; while it works, `now` stops the turn and this goes first, else it is queued. */
const send = (now = false) => {
const text = draft.text.trim()
if ((!text && !pasted.items.length) || pasted.uploading) return
draft.text = ''
if (asked && text) {
const key = askKey(s, asked)
if (replying.to[key]) return
replying.to = {...replying.to, [key]: 'answered'}
void act('answered', () => api.answer(s.id, asked.request!, 'accept', typedAnswer(asked, text)), {quiet: true}).then((ok) => {
if (ok) return
// Refused: it can be answered again, and what was typed is still there.
replying.to = Object.fromEntries(Object.entries(replying.to).filter(([k]) => k !== key))
draft.text ||= text
})
return
}
const images = takeAttachments()
pinned = true
const mine = {session: s.id, text, after: live.following === s.id ? (followedLog().at(-1)?.n ?? 0) : 0, at: Date.now()}
// Those the hub has shown since go; this one shows until it does.
sending.list = [...sending.list.filter((p) => Date.now() - p.at < 30000), mine]
// No word when it went: the conversation, or the queue, shows it.
void act(
busy ? (now ? 'sent now' : 'queued') : 'sent',
async () => {
try {
await api.sayTo(s.id, text, busy && now, images)
} catch (e) {
// Refused: it was never sent, and the toast says why.
sending.list = sending.list.filter((p) => p.at !== mine.at || p.session !== mine.session)
draft.text ||= text
throw e
}
},
{quiet: true},
)
}
const {available, current, model} = modeModel(s)
const models = modelModel(s)
// Working, or waiting on the person mid-turn: the turn can be stopped.
const busy = s.status === 'working' || s.status === 'needs_permission'
const stop = () => {
if (steers()) void act('stopped what it was doing', () => api.cancelTurn(s.id))
}
const bypassing = current === BYPASS
return foldable(
<div class="session__say">
{awaitsPanel(s)}
{laterPanel(s)}
{queuePanel(s)}
{attachments()}
<textarea
{...imageInput}
class="session__prompt session__message"
rows={2}
disabled={!steers()}
placeholder={
!steers()
? 'steering takes the steer role'
: asked
? `pick an answer above, or type your own${keys('Mod+Enter answers')}`
: s.autopilot?.on && !busy
? `say something: your word goes before the autopilot's${keys('Mod+Enter sends')}`
: busy
? `it is working${keys('Mod+Enter queues for after this turn, Mod+Shift+Enter sends now, Esc stops it')}`
: `say something to it${s.local ? ` in ${s.local.client} on ${s.local.machine}` : ''}${keys('Mod+Enter sends')}`
}
value={draft.text}
oninput={(e: InputEvent & {redraw?: boolean}) => {
// draft is reactive state, which redraws what reads it: a whole-page redraw on top made every key two.
e.redraw = false
draft.text = (e.target as HTMLTextAreaElement).value
}}
onkeydown={(e: KeyboardEvent) => {
if (sends(e)) {
// Nothing to send: the key is an open question card's, which answers with what is picked.
if (!draft.text.trim() && !pasted.items.length) return
// While it works: Mod+Enter queues, Mod+Shift+Enter stops the turn and sends now; a question waiting, either answers it.
e.preventDefault()
send(e.shiftKey)
} else if (e.key === 'Escape' && busy) {
// As in a terminal session: Esc stops what it is doing.
e.preventDefault()
stop()
}
}}
/>
<div class="session__send">
{attachButton()}
{models.available.length ? chooser(models.model, models.available, 'the model it thinks with') : null}
{available.length ? chooser(model, available, 'how much it may do without asking', bypassing) : null}
{autopilotChip(s)}
{context(live.following === s.id ? followedLog() : [])}
{sessionWayButton()}
{sessionInfoButton()}
<span class="session__go">
{busy ? (
<button
class="session__stop"
type="button"
disabled={!steers()}
title="Stop what it is doing (Esc). The session stays: say what next."
aria-label="Stop what it is doing"
onclick={stop}
>
<span class="session__stop-icon" />
</button>
) : null}
{/* While it works: queue it for the turn's end, or stop the turn and send it now. A question waiting: answer it. */}
{asked ? (
draft.text.trim() ? (
<Button variant="primary" disabled={!steers() || !!replying.to[askKey(s, asked)]} title={`answer its question with this (${SEND_KEY}+Enter)`} onclick={() => send()}>
Answer
</Button>
) : null
) : busy ? (
draft.text.trim() ? (
[
<Button variant="secondary" disabled={!steers()} title={`send it when this turn ends (${SEND_KEY}+Enter)`} onclick={() => send(false)}>
Queue
</Button>,
<Button variant="primary" disabled={!steers()} title={`stop what it is doing and send this now (${SEND_KEY}+Shift+Enter)`} onclick={() => send(true)}>
Send now
</Button>,
]
) : null
) : (
<button type="button" class="session__arrow" disabled={!steers() || pasted.uploading > 0 || (!draft.text.trim() && !pasted.items.length)} title={`Send (${SEND_KEY}+Enter)`} aria-label="Send" onclick={() => send()}>
{arrowUp}
</button>
)}
</span>
</div>
</div>,
{draft: draft.text, tools: [sessionWayButton(), sessionInfoButton(), ...tools]},
)
}
/**
* A model or mode to choose, as a chip as wide as its name: the platform's own
* picker lies over it, unseen, so a tap opens that. The name is drawn as text,
* not by the select, which a phone with large text sized before it scaled the
* text and cut "Manual" to "Manu".
*/
function chooser(model: {value: string | null}, options: {id: string; name: string; group?: string}[], title: string, bypass = false): m.Children {
const at = options.findIndex((x) => x.id === model.value)
// Options in groups, in their order: the select's index still counts them all, across groups.
const groups = [...new Set(options.map((x) => x.group ?? ''))]
const option = (x: {id: string; name: string}) => <option value={x.id}>{x.name}</option>
return (
<label class={`chooser${bypass ? ' chooser--bypass' : ''}${steers() ? '' : ' is-disabled'}`} title={title}>
<span class="chooser__name">{options[at]?.name ?? '…'}</span>
<svg class="chooser__chev" viewBox="0 0 16 16" width="12" height="12" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
<path d="M4 6l4 4 4-4" />
</svg>
{/* Made again when the options change (the agents arriving): new options reset the browser's
choice to the first, and an unchanged selectedIndex is not set again. Keyed alone in a
fragment, since its siblings are not. */}
{[<select
key={options.map((x) => x.id).join(' ')}
class="chooser__native"
aria-label={title}
disabled={!steers()}
selectedIndex={at}
onchange={(e: Event) => {
const o = options[(e.currentTarget as HTMLSelectElement).selectedIndex]
if (o) model.value = o.id
}}
>
{groups.length > 1 || groups[0]
? groups.map((g) => <optgroup label={g}>{options.filter((x) => (x.group ?? '') === g).map(option)}</optgroup>)
: options.map(option)}
</select>]}
</label>
)
}
/** Send: an arrow, in a round button that pops up once there is something to send. */
const arrowUp = (
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M12 19V5M5 12l7-7 7 7" />
</svg>
)
const kTokens = (n: number) =>
n >= 1e6 ? `${+(n / 1e6).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n)
/** How full its context is, as Zed shows it: a ring and "45k / 200k", the cost in its title. */
function context(items: LogItem[]): m.Children {
const u = items.findLast((i) => i.kind === 'usage')
if (!u?.used || !u.size) return null
const share = Math.min(1, u.used / u.size)
const level = share > 0.85 ? 'bad' : share > 0.6 ? 'warn' : 'ok'
const cost = typeof u.cost === 'number' ? ` · $${u.cost.toFixed(2)} so far` : ''
return (
<span class={`session__context session__context--${level}`} title={`${u.used.toLocaleString()} of ${u.size.toLocaleString()} tokens in its context${cost}`}>
<span class="ring" style={{'--share': `${Math.round(share * 100)}%`}} aria-hidden="true" />
{kTokens(u.used)} / {kTokens(u.size)}
</span>
)
}
/** Sessions waiting for the person: a permission to answer. */
export const needsYou = () => hosted().filter((h) => h.status === 'needs_permission' || awaitsPerson(h)).length
/**
* The sessions in the lists, in their groups: Needs you, Landing, At work,
* Landed today, Idle (lib/groups). The archived and the imported are left to
* the search: sessions end on their own now, so what the lists hold is what is
* still relevant.
*/
function groups(): ReturnType<typeof grouped> {
return grouped(
hosted().filter((h) => inView(reposOf(h))),
(h) => journeyOf(h)?.phase ?? null,
Date.now() / 1000,
)
}
/** The groups folded shut or opened by hand, kept for the next visit; Idle starts folded once it holds more than a few. */
const folds = local({by: (() => {
try {
return (JSON.parse(localStorage.getItem('midas-nav-folds') ?? '{}') ?? {}) as Partial<Record<Group, boolean>>
} catch {
return {}
}
})()})
const folded = (g: Group, n: number) => folds.by[g] ?? (g === 'idle' && n > 4)
function toggleFold(g: Group, n: number) {
folds.by = {...folds.by, [g]: !folded(g, n)}
try {
localStorage.setItem('midas-nav-folds', JSON.stringify(folds.by))
} catch {
// A browser that keeps nothing: folded for this page.
}
}
/** A group's head: its name and count, a tap folding it. */
function groupHead(g: {key: Group; title: string; these: Hosted[]}, cls: string): m.Children {
const shut = folded(g.key, g.these.length)
return (
<button type="button" class={`${cls}${shut ? ` ${cls}--shut` : ''}`} aria-expanded={String(!shut)} onclick={() => toggleFold(g.key, g.these.length)}>
{g.title} <span class="home__count">{g.these.length}</span>
</button>
)
}
/** Where a session is, as its mark in a list: its state's dot, its step on the way to live, or a tick once landed. */
function markOf(h: Hosted, g: Group): m.Children {
if (g === 'landed') return <span class="land-tick" title="landed">✓</span>
const j = g === 'landing' ? journeyOf(h) : null
if (j) return gauge(j, 20)
// Waiting on the person for something only they can do: a key, not an asking dot.
if (h.awaits && (g === 'asks' || g === 'later'))
return (
<span class={`awaits-mark${g === 'later' ? ' awaits-mark--snoozed' : ''}`} title={`waits on you: ${h.awaits.text}`}>
{icon.key()}
</span>
)
return <span class={`dot dot--${h.status}`} title={STATUS[h.status].label} />
}
/** A project's sessions at work, for its filter. */
const atWorkIn = (repo: string) => hosted().filter((h) => reposOf(h).includes(repo) && !h.archived && !h.imported && h.status !== 'stopped' && h.status !== 'failed').length
/** The nav's search: what is typed, and what the hub found for it. */
const find = local({q: '', asked: '', results: [] as SearchHit[], more: false})
let asking: ReturnType<typeof setTimeout> | undefined
/** A search hit to go to once its conversation has loaded: its session and log item. */
let jump: {id: string; n: number} | null = null
const query = {
get value() {
return find.q
},
set value(v: string) {
find.q = v
clearTimeout(asking)
const q = v.trim()
if (q.length < 2) {
find.results = []
find.asked = ''
return
}
asking = setTimeout(() => void ask(q), 250)
},
}
async function ask(q: string) {
try {
const r = await api.searchSessions(q)
// Typed on meanwhile: that search answers.
if (find.q.trim() !== q) return
find.results = r.results
find.more = r.more
find.asked = q
} catch (e) {
toast(toastModel, {tone: 'danger', title: 'search: refused', message: (e as Error).message, timeout: 10000})
}
}
/** The words of the search marked where a snippet says them. */
function marked(text: string, q: string): m.Children {
const words = q.toLowerCase().split(/\s+/).filter(Boolean).map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
if (!words.length) return text
return text.split(new RegExp(`(${words.join('|')})`, 'gi')).map((part, i) => (i % 2 ? <mark>{part}</mark> : part))
}
/** What the search found, in place of the list. */
function found(go: (hash: string) => void, id: string): m.Children {
const q = find.q.trim()
if (find.asked !== q) return <div class="nav-find__note hint">searching…</div>
if (!find.results.length) return <div class="nav-find__note hint">no session says “{q}”</div>
const status = new Map(hosted().map((h) => [h.id, h.status]))
const items = find.results.map((r) => (
<NavItem
key={`found-${r.id}`}
class="nav-find__hit"
active={r.id === id}
onclick={() => {
jump = r.n ? {id: r.id, n: r.n} : null
go(`sessions/${r.id}`)
}}
icon={<span class={`dot dot--${status.get(r.id) ?? 'stopped'}`} />}
>
<span class="nav-find__title">{r.title}</span>
<span class="nav-find__snippet">{marked(r.snippet, q)}</span>
<span class="nav-find__hits hint">
{r.hits} place{r.hits === 1 ? '' : 's'}
</span>
</NavItem>
))
// The hits keyed, in a list of their own: the note after them has no key.
return [m.fragment(null, items), find.more ? <div class="nav-find__note hint">the newest {items.length}; say more to narrow it</div> : null]
}
/** A search field's mark, so it reads as a search and not a place to type a new session. */
const magnifier = () => (
<svg class="nav-find__icon" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
<circle cx="7" cy="7" r="4.5" fill="none" stroke="currentColor" stroke-width="1.6" />
<path d="M10.5 10.5 14 14" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" />
</svg>
)
/** The sessions in the Shell's nav: a dot for each one's state, the open one highlighted. */
export function sessionNav(go: (hash: string) => void): m.Vnode {
askProjects()
const id = selected()
const waiting = needsYou()
return (
<NavGroup title={waiting ? `Sessions · ${waiting} need${waiting === 1 ? 's' : ''} you` : 'Sessions'}>
<div class="nav-top">
<button
class={`nav-new${here() === 'sessions/new' ? ' nav-new--on' : ''}`}
type="button"
onclick={() => go('sessions/new')}
>
<span class="nav-new__plus" aria-hidden="true">
+
</span>
New session
</button>
<div class="nav-find">
<div class="nav-find__row">
<FieldText model={query} type="search" placeholder="Search all sessions" prefix={magnifier()} />
{projectSelect(atWorkIn)}
</div>
</div>
{/* The whole list, a page of its own: the menu no longer has an item for it. */}
<a class={`nav-all${here() === 'sessions' ? ' is-on' : ''}`} href="/sessions">
All sessions →
</a>
</div>
{find.q.trim().length >= 2 ? found(go, id) : sessionList(go, id)}
</NavGroup>
)
}
/** The session a link under the pointer goes to: its row in the nav lights up, so the person sees which it is. */
const pointed = local({id: ''})
document.addEventListener('mouseover', (e) => {
const a = (e.target as Element | null)?.closest?.('a[href^="/sessions/s"]')
// The nav's own rows light up as rows do.
const id = a && !a.closest('.m-nav-item') ? (a.getAttribute('href')?.match(/^\/sessions\/(s\d+)$/)?.[1] ?? '') : ''
if (id !== pointed.id) pointed.id = id
})
// Out of the window: nothing is under the pointer.
document.addEventListener('mouseout', (e) => {
if (!e.relatedTarget && pointed.id) pointed.id = ''
})
/** One session's row in the nav. */
function navRow(h: Hosted, g: Group, id: string): m.Vnode {
return (
<NavItem
key={h.id}
class={h.id === pointed.id ? 'nav-pointed' : undefined}
active={h.id === id}
muted={g === 'landed' || g === 'idle'}
onclick={() => go(`sessions/${h.id}`)}
icon={markOf(h, g)}
>
{/* The title gives way, never the project: the tag stays whole at the row's end. */}
<span class="nav-row__title">{h.title}</span>
{shown() ? null : projectTag(reposOf(h))}
</NavItem>
)
}
/**
* A tech of the research tree over the sessions researching it: its icon in its theme's colour, its
* name, the goal it serves, and its sessions as pips. A tap opens it on the tree.
*/
function techHead(o: ResearchOrigin, cls: string): m.Children {
return (
<button type="button" class={`tech-head ${cls}`} title="Open it on the research tree" onclick={() => showTech(o.tech)}>
{originIcon(o)}
<span class="tech-head__text">
<span class="tech-head__name">{o.name}</span>
{goalLine(o)}
</span>
{originPips(o)}
</button>
)
}
/** The sessions still relevant, in the nav, under their groups' heads. */
function sessionList(go: (hash: string) => void, id: string): m.Children {
const gs = groups().map((g) => (
<div class="nav-group" key={g.key}>
{groupHead(g, 'nav-group__head')}
{folded(g.key, g.these.length)
? null
: m.fragment(
null,
// Keyed, in a list of their own: the head above them has no key.
byTech(g.these).map((r) =>
r.tech ? (
<div class={`nav-tech ${themeOf(r.tech)}`} key={`tech-${r.tech.tech}`}>
{techHead(r.tech, 'nav-tech__head')}
{r.these.map((h) => navRow(h, g.key, id))}
</div>
) : (
navRow(r.h, g.key, id)
),
),
)}
</div>
))
// Keyed like the groups beside it: a list mixes no keyed and unkeyed children.
return m.fragment(null, [m.fragment({key: 'runner-away'}, [runnerAwayLine()]), ...gs])
}
/**
* The agent's question (AskUserQuestion, as a form): each a single choice
* (radio) or several (checkboxes), and an "Other" box beside it; Answer, or
* Skip. Once answered, what was answered.
*/
/** Where a session is now, in words: its lane on the board, and the node it uses. */
function whereNow(owner: string): string | null {
const c = cards().find((x) => x.session === owner.replace(/^gate-/, ''))
if (!c) return null
switch (c.stage) {
case 'on_node':
return `on ${c.node}`
case 'waiting_for_node':
return `waiting for a node (#${c.position})`
case 'waiting_to_land':
return `waiting to land${c.node ? `, still on ${c.node}` : ''}`
case 'landing':
return `landing${c.node ? `, gate on ${c.node}` : ''}`
case 'landed':
return 'landed'
default:
return 'working, no node'
}
}
/** `caller:session` (how open ends record who), as a session's linked name where it is one. */
function byWhom(by: string | null | undefined): m.Children {
if (!by) return '?'
const [caller, owner] = by.includes(':') ? [by.slice(0, by.indexOf(':')), by.slice(by.indexOf(':') + 1)] : ['', by]
return owner && owner !== 'web' && /[-_0-9]/.test(owner) ? [who(owner, {max: 36}), caller ? ` (${caller})` : ''] : by
}
/**
* A question about other work: each session it names — what it is, where it
* is now — and each open end — what it asks, who left it for whom, and how
* far it got — so the person can answer without looking elsewhere.
*/
function aboutOthers(about: Mentions): m.Children {
const rows: m.Children[] = [
...about.sessions.map((o) => {
const where = whereNow(o)
return (
<li>
{who(o, {max: 50})}
<span class="hint"> · {where ?? 'not on the board now'}</span>
</li>
)
}),
...about.todos.map((t) => {
const todo = $s.todos.find((x) => x.id === t)
if (!todo) return <li>open end {t}</li>
const state = todo.done_at
? ['done by ', byWhom(todo.done_by), todo.done_note ? ` — ${todo.done_note}` : '']
: todo.claimed_by
? ['being done by ', byWhom(todo.claimed_by)]
: [`waiting for the next ${todo.for === 'any' ? '' : `${todo.for} `}session`]
return (
<li>
<details class="q__todo">
<summary>
<b>open end {t}</b>
<span class="hint">
{' '}
· {todo.done_at ? 'done' : todo.claimed_by ? 'being done' : 'open'} · left by {byWhom(todo.by)}
</span>
</summary>
<div class="q__todo-text">{sessions(todo.text)}</div>
<div class="hint">
for {todo.for} · {state}
</div>
</details>
</li>
)
}),
]
return (
<div class="q__about" title="this question concerns other sessions' work">
<span class="q__about-mark" aria-hidden="true">⇄</span>
<div>
<b>About other work</b>
{rows.length ? <ul class="q__about-list">{rows}</ul> : <div class="hint">another session, not named</div>}
</div>
</div>
)
}
/** A question longer than this (characters) is folded to its first lines. */
const LONG_QUESTION = 280
export class QuestionCard extends MithrilComponent<{s: Hosted; it: LogItem; open: boolean; answer?: LogItem; deciding?: boolean}> {
picks = local({values: {} as Record<string, string | string[]>})
/** The questions whose "Other" is chosen: its box (`<question>_custom`) is sent only then. */
other = local({on: {} as Record<string, boolean>})
/** A long question, shown whole: folded, its first lines and the choices fit a phone's screen. */
whole = local({open: false})
/** Answer with what is picked, as the Answer button does; set by each view while the question is open. */
submit: (() => void) | null = null
/**
* Mod+Enter answers it too, from anywhere on the page but a box someone is typing other
* words into (the composer gives the key up while it is empty, so it reaches here).
*/
keys = (e: KeyboardEvent) => {
if (!sends(e) || e.defaultPrevented || !this.submit) return
const t = e.target as HTMLElement | null
const typing = t instanceof HTMLTextAreaElement || (t instanceof HTMLInputElement && t.type === 'text')
if (typing && t.value.trim() && !this.dom?.contains(t)) return
e.preventDefault()
this.submit()
}
dom: Element | null = null
oncreate(vnode: m.VnodeDOM<{s: Hosted; it: LogItem; open: boolean; answer?: LogItem; deciding?: boolean}>) {
this.dom = vnode.dom
document.addEventListener('keydown', this.keys)
}
onremove() {
document.removeEventListener('keydown', this.keys)
}
/** The recommended option of each question, chosen already: agreeing is one press. */
oninit(vnode: m.Vnode<{s: Hosted; it: LogItem; open: boolean; answer?: LogItem; deciding?: boolean}>) {
const start: Record<string, string | string[]> = {}
for (const [k, f] of Object.entries(vnode.attrs.it.schema?.properties ?? {})) {
const options = f.oneOf ?? f.items?.anyOf ?? []
const rec = options.filter((o) => recommended(o.title ?? o.const).rec).map((o) => o.const)
if (rec.length) start[k] = f.type === 'array' ? rec : rec[0]
}
this.picks.values = start
}
view(vnode: m.Vnode<{s: Hosted; it: LogItem; open: boolean; answer?: LogItem; deciding?: boolean}>) {
const {s, it, open, answer} = vnode.attrs
const fields = Object.entries(it.schema?.properties ?? {})
// Whether it is about working with other sessions: their names, open ends, or words for them.
const text = [
it.message ?? '',
...fields.flatMap(([, f]) => [
f.title ?? '',
f.description ?? '',
...(f.oneOf ?? f.items?.anyOf ?? []).flatMap((o) => [o.title ?? o.const, o.description ?? '']),
]),
].join('\n')
const about = mentions(text, {
sessions: Object.keys($s.names),
hosted: hosted().map((h) => h.id),
todos: $s.todos.map((t) => t.id),
self: s.owner,
})
const v = this.picks.values
const long = (it.message ?? '').length > LONG_QUESTION || (it.message ?? '').split('\n').length > 6
const set = (k: string, val: string | string[]) => (this.picks.values = {...v, [k]: val})
const toggle = (k: string, opt: string) => {
const now = Array.isArray(v[k]) ? (v[k] as string[]) : []
set(k, now.includes(opt) ? now.filter((x) => x !== opt) : [...now, opt])
}
const said = (k: string) => {
const a = answer?.content?.[k]
return Array.isArray(a) ? a.join(', ') : (a ?? '')
}
const props = it.schema?.properties ?? {}
// A choice's "Other" box (acp.rs `question_form`) is drawn as its last option, not as a field of its own.
const paired = (k: string) => k.endsWith('_custom') && !!(props[k.slice(0, -'_custom'.length)]?.oneOf ?? props[k.slice(0, -'_custom'.length)]?.items?.anyOf)
const on = this.other.on
const pickOther = (k: string, multi: boolean) => {
const now = multi ? !on[k] : true
this.other.on = {...on, [k]: now}
// One choice: Other instead of an option, never beside it.
if (!multi) set(k, '')
if (now) requestAnimationFrame(() => document.getElementById(`q-${it.request}-${k}-other`)?.focus())
}
/** What is sent: an "Other" box only where Other is chosen. */
const content = () => {
const out: Record<string, string | string[]> = {}
for (const [k, val] of Object.entries(v)) {
if (!paired(k) || on[k.slice(0, -'_custom'.length)]) out[k] = val
}
return out
}
/** "Other", the last option: its box takes text only while it is chosen. */
const otherOption = (k: string, multi: boolean) => {
const ck = `${k}_custom`
const chosen = open ? !!on[k] : !!said(ck)
return (
<div class={`q__option q__option--other${chosen ? ' is-chosen' : ''}`}>
<label class="q__other-pick">
<input type={multi ? 'checkbox' : 'radio'} name={`${it.request}-${k}`} checked={chosen} onchange={() => pickOther(k, multi)} />
<span>Other</span>
</label>
{open ? (
<input
id={`q-${it.request}-${k}-other`}
type="text"
class="q__other-text"
disabled={!chosen}
value={(v[ck] as string) ?? ''}
placeholder={multi ? 'your own answer, added to those picked' : 'your own answer'}
oninput={(e: Event) => set(ck, (e.target as HTMLInputElement).value)}
/>
) : chosen ? (
<span class="hint">{said(ck)}</span>
) : null}
</div>
)
}
const answerIt = () => reply(askKey(s, it), 'answered', () => api.answer(s.id, it.request!, 'accept', content()))
this.submit = open && steers() && !replying.to[askKey(s, it)] ? answerIt : null
return (
<div class={`msg__permission msg__question${vnode.attrs.open ? '' : ' msg__permission--settled'}${about.others ? ' msg__question--others' : ''}`}>
{about.others ? aboutOthers(about) : null}
<div class="q__asks">It asks</div>
<div class={`q__text md${long && !this.whole.open ? ' q__text--folded' : ''}`}>
<Md text={it.message ?? ''} />
</div>
{long ? (
<button type="button" class="q__more" onclick={() => (this.whole.open = !this.whole.open)}>
{this.whole.open ? 'Show less' : 'Show all'}
</button>
) : null}
{fields.map(([k, f]) => {
const options = f.oneOf ?? f.items?.anyOf ?? null
const multi = f.type === 'array'
if (paired(k)) return null
if (!options) {
// An "Other" box (or a plain question): free text.
if (!open) return said(k) ? <div class="hint">{f.title ?? 'Other'}: {said(k)}</div> : null
return (
<label class="q__other">
<span class="hint">{f.title ?? 'Answer'}</span>
<input
type="text"
value={(v[k] as string) ?? ''}
placeholder={f.description ?? ''}
oninput={(e: Event) => set(k, (e.target as HTMLInputElement).value)}
/>
</label>
)
}
return (
<fieldset class="q__field" disabled={!open || !steers()}>
{f.title || f.description ? (
<legend>
{f.title ? <b>{f.title}</b> : null} {f.description ? inline(f.description) : null}
</legend>
) : null}
{options.map((o) => {
const chosen = open
? multi
? Array.isArray(v[k]) && (v[k] as string[]).includes(o.const)
: v[k] === o.const
: (Array.isArray(answer?.content?.[k]) ? (answer?.content?.[k] as string[]) : [answer?.content?.[k]]).includes(o.const)
return (
<label class={`q__option${chosen ? ' is-chosen' : ''}`}>
<input
type={multi ? 'checkbox' : 'radio'}
name={`${it.request}-${k}`}
checked={chosen}
onchange={() => {
if (multi) return toggle(k, o.const)
set(k, o.const)
this.other.on = {...on, [k]: false}
}}
/>
<span>
{recommended(o.title ?? o.const).label}
{recommended(o.title ?? o.const).rec ? <span class="q__rec">Recommended</span> : null}
{o.description ? <span class="hint"> — {inline(o.description)}</span> : null}
</span>
</label>
)
})}
{props[`${k}_custom`] ? otherOption(k, multi) : null}
</fieldset>
)
})}
{open && vnode.attrs.deciding ? pilotDeciding() : null}
{open ? (
<div class="msg__choices">
<Button
size="sm"
variant="primary"
disabled={!steers() || !!replying.to[askKey(s, it)]}
title={`answer with what is picked (${SEND_KEY}+Enter)`}
onclick={answerIt}
>
{replying.to[askKey(s, it)] === 'answered' ? 'Sending…' : 'Answer'}
</Button>
<Button
size="sm"
variant="ghost"
disabled={!steers() || !!replying.to[askKey(s, it)]}
onclick={() => reply(askKey(s, it), 'skipped', () => api.answer(s.id, it.request!, 'decline', {}))}
>
{replying.to[askKey(s, it)] === 'skipped' ? 'Sending…' : 'Skip'}
</Button>
<span class="hint q__keys">{SEND_KEY}+Enter answers</span>
</div>
) : answer?.by === PILOT ? (
pilotWhy('The autopilot chose this', answer.why)
) : (
<div class="hint">{answer ? (answer.action === 'accept' ? `answered by ${answer.by ?? '?'}` : answer.action === 'decline' ? 'skipped' : 'cancelled') : 'no longer asked'}</div>
)}
</div>
)
}
}
/**
* The sheet over a session, opened from its name in the header: Files (what its
* branch changes, as its runner last reported it, and the sessions that change
* the same files) and About (where it is and what can be done with it). On a
* phone it rises from the bottom, in the thumb's reach; wider, it is a panel.
*/
const sheet = local({
tab: '' as '' | 'live' | 'files' | 'about',
files: null as FilesReport | null,
filesFor: '',
filesAt: 0,
open: '',
notes: [] as Message[],
loading: false,
renaming: false,
name: '',
})
export function openSheet(tab: 'live' | 'files' | 'about') {
sheet.tab = tab
sheet.open = ''
sheet.renaming = false
const s = openSession()
if (s && shared(s).length) void loadNotes()
}
/** Its files, asked for when it is opened and again when it has moved on (each turn's end reports them). */
function loadFiles(s: Hosted) {
if (sheet.filesFor === s.id && sheet.filesAt >= s.updated) return
if (sheet.filesFor !== s.id) sheet.files = null
sheet.filesFor = s.id
sheet.filesAt = s.updated
api.sessionFiles(s.id)
.then((r) => {
if (sheet.filesFor === s.id) sheet.files = r
})
// A hub from before the reports, or none yet: said as nothing reported, not left asking.
.catch(() => {
if (sheet.filesFor === s.id) sheet.files = {files: [], commits: 0}
})
}
/** The last two days' notes: what two sessions said to each other about the files they share. */
async function loadNotes() {
if (sheet.loading) return
sheet.loading = true
try {
sheet.notes = buildFeed(await api.events(2 * 86400, FEED_KINDS))
} catch {
// Notes are a nicety here: the files are what was asked for.
} finally {
sheet.loading = false
}
}
/** A worktree's notes are its landing gate's too. */
const base = (owner: string) => owner.replace(/^gate-/, '')
/** The session midas runs or mirrors for an owner, when there is one: a link to it stays on this page. */
const hostedFor = (owner: string) => hosted().find((h) => h.owner === owner && !h.archived && !h.imported)
/** A session by its name, linked to its conversation: here when midas runs it, else where it has one. */
function sessionLink(owner: string, max: number): m.Children {
const h = hostedFor(owner)
const n = nameOf(owner)
const title = shortName(h?.title ?? n.title, max)
if (h) return <a href={`/sessions/${h.id}`}>{title}</a>
return n.link ? (
<a href={n.link} target={n.link.startsWith('/') ? undefined : '_blank'} rel="noopener">
{title}
</a>
) : (
<b>{title}</b>
)
}
/** Sessions still at work that change files this one changes. One ended, or quiet a day, keeps its files on record a while: left out. */
function shared(s: Hosted): {with: string; files: string[]}[] {
const atWork = (o: string) => {
const x = $s.names[o]
return !o.startsWith('gate-') && x != null && x.ended == null && (x.last ?? 0) > Date.now() / 1000 - 86400
}
return ($s.names[s.owner]?.overlaps ?? []).filter((o) => atWork(o.with))
}
/** How many files its branch changes: the report's, else what its edits told the hub. */
function fileCount(s: Hosted): number {
if (sheet.filesFor === s.id && sheet.files) return sheet.files.files.length
return $s.names[s.owner]?.changed?.length ?? 0
}
/** The question or permission it waits on, if the conversation is loaded: which of the two it is. */
function waitsOn(s: Hosted): 'question' | 'permission' {
if (live.following !== s.id) return 'permission'
const asked = followedLog().findLast((it) => it.kind === 'question' || it.kind === 'permission')
return asked?.kind === 'question' ? 'question' : 'permission'
}
const clock = (t: number) => new Date(t * 1000).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'})
/**
* What a session is doing, in one sentence a person would say: the line under
* its name. `you` when it waits for the person (in orange), `busy` while it works.
*/
export function stateLine(s: Hosted): {text: string; tone: '' | 'you' | 'busy' | 'done'; wake?: boolean} {
if (s.finished) {
if (s.finished.outcome === 'done') return {text: 'done · finished', tone: 'done'}
return s.finished.outcome === 'dropped'
? {text: 'dropped · finished', tone: ''}
: {text: s.finished.live_at ? `live since ${clock(s.finished.live_at)} · finished` : 'on main · finished', tone: 'done'}
}
if (s.imported) return {text: `imported from ${s.imported.from}`, tone: ''}
// Its runner stopped asking for work: nothing runs, whatever its status last said (runners.rs).
if (s.runner_away) return {text: `paused since ${clock(s.runner_away)}: its runner is away`, tone: ''}
// Waiting on the person for something only they can do: what, in orange, as an ask is.
if (s.awaits && !['working', 'queued', 'starting', 'needs_permission'].includes(s.status))
return (s.awaits.snooze ?? 0) > now()
? {text: `put off until ${ahead(s.awaits.snooze!)}: ${shortName(s.awaits.text, 50)}`, tone: '', wake: true}
: {text: `waits on you: ${shortName(s.awaits.text, 60)}`, tone: 'you'}
// Set to carry on: when, rather than how long it has been quiet or that it ended.
if (s.wake && !['working', 'queued', 'starting', 'needs_permission'].includes(s.status)) return {text: `carries on ${ahead(s.wake.at)}`, tone: '', wake: true}
if (s.status === 'failed') return {text: 'failed', tone: ''}
if (s.status === 'stopped') return {text: s.local ? `goes on in ${s.local.client}` : 'ended', tone: ''}
if (s.finish) return {text: 'on main · finishes when live', tone: ''}
const pilot = pilotState(s)
if (pilot) return {text: pilot.text, tone: pilot.tone === 'you' ? 'you' : 'busy'}
if (s.status === 'needs_permission') return {text: waitsOn(s) === 'question' ? 'waiting for your answer' : 'wants your permission', tone: 'you'}
if (s.status === 'queued' || s.status === 'starting') return {text: 'starting', tone: 'busy'}
if (s.status === 'working') return {text: s.doing ? shortName(s.doing.charAt(0).toLowerCase() + s.doing.slice(1), 60) : 'working', tone: 'busy'}
const c = cards().find((x) => x.session === s.owner)
if (c?.stage === 'waiting_to_land' || c?.stage === 'landing') return {text: 'landing', tone: 'busy'}
if (c?.stage === 'landed') return {text: c.live ? 'live' : `on main · ${liveWhen(s)}`, tone: ''}
// Not "done for now": done is what Mark done and Finished mean.
return {text: `idle ${ago(turnOf(s).idle_s)}`, tone: ''}
}
/**
* An open session's About and Files, as an icon: the name alone was too hidden a way in.
* It sits in the message box on every screen; the header has it only while there is no box.
*/
export function sessionInfoButton(): m.Vnode | null {
if (!openSession()) return null
return (
<button type="button" class="frame__icon session-info" title="About this session and its files" aria-label="About this session and its files" onclick={() => openSheet('about')}>
<svg viewBox="0 0 16 16" width="18" height="18" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round">
<circle cx="8" cy="8" r="6.25" />
<path d="M8 7.25V11.5" />
<circle cx="8" cy="4.9" r="0.4" fill="currentColor" />
</svg>
</button>
)
}
/** An open session's way to live, as its gauge: it sits beside About while the session is on its way, and opens To live. */
export function sessionWayButton(): m.Vnode | null {
return wayButton(openSession(), () => openSheet('live'))
}
/** A session to open at its To live, from a list's gauge. */
let wayFor = ''
/** The header over an open session: its name, and under it what it is doing and its files. The name opens About, the files Files. */
export function sessionHead(): m.Vnode {
const s = openSession()
if (!s) return <h2 class="frame__title">{sessionTitle()}</h2>
loadFiles(s)
const st = stateLine(s)
const n = fileCount(s)
const k = shared(s).length
return (
<button type="button" class="shead" title="About this session" onclick={() => openSheet('about')}>
{s.research ? (
<span
class={`shead__research ${themeOf(s.research)}`}
title="Open its tech on the research tree"
onclick={(e: Event) => {
e.stopPropagation()
showTech(s.research!.tech)
}}
>
{goalLine(s.research, true)}
{s.research.name === s.title ? null : <span class="shead__tech">{s.research.name}</span>}
{originPips(s.research)}
</span>
) : null}
<span class="shead__title">{s.title}</span>
<span class={`shead__line shead__line--${st.tone || 'plain'}`}>
{st.tone === 'busy' ? (
<span class="shead__dot shead__dot--busy" aria-hidden="true" />
) : st.tone ? (
<span class="shead__dot" aria-hidden="true" />
) : null}
<span class="shead__state">
{st.wake ? [icon.clock(), ' '] : null}
{st.text}
</span>
{n ? (
<span
class="shead__files"
onclick={(e: Event) => {
e.stopPropagation()
openSheet('files')
}}
>
{' '}
· {n} file{n === 1 ? '' : 's'}
{k ? `, ${k} shared` : ''} ›
</span>
) : null}
</span>
</button>
)
}
/** A path as its folder (quiet) and its name. */
function pathOf(p: string): m.Children {
const at = p.lastIndexOf('/')
return at < 0 ? p : [<span class="ssheet__dir">{p.slice(0, at + 1)}</span>, p.slice(at + 1)]
}
/** A piece of a diff, its lines coloured. */
function patchOf(text: string): m.Children {
return (
<pre class="ssheet__patch">
{text.split('\n').map((l) => (
<span class={l.startsWith('+') ? 'is-add' : l.startsWith('-') ? 'is-del' : l.startsWith('@@') ? 'is-hunk' : ''}>{l + '\n'}</span>
))}
</pre>
)
}
function filesTab(s: Hosted): m.Children {
const r = sheet.filesFor === s.id ? sheet.files : null
const with_ = shared(s)
const sharedBy = (f: string) => with_.filter((o) => o.files.includes(f))
if (!r) return <p class="hint">Asking the hub…</p>
const add = r.files.reduce((n, f) => n + f.add, 0)
const del = r.files.reduce((n, f) => n + f.del, 0)
return [
r.files.length ? (
<div class="ssheet__sum">
<b>{s.branch}</b>
<span class="hint">
{r.commits} commit{r.commits === 1 ? '' : 's'} off {r.base ?? s.base}
{r.at ? ` · as of ${since(r.at)} ago` : ''}
</span>
<span class="ssheet__nums">
<span class="is-add">+{add.toLocaleString()}</span> <span class="is-del">−{del.toLocaleString()}</span>
</span>
</div>
) : (
<p class="hint">{r.at ? 'Its branch changes nothing yet.' : 'Nothing reported yet: the runner says what its branch changes at the end of each turn.'}</p>
),
r.files.length ? (
<ul class="ssheet__files">
{r.files.map((f) => {
const open = sheet.open === f.path
const also = sharedBy(f.path)
return (
<li key={f.path}>
<button type="button" class={`ssheet__file${open ? ' is-open' : ''}`} disabled={!f.patch} onclick={() => (sheet.open = open ? '' : f.path)}>
<code class="ssheet__path">{pathOf(f.path)}</code>
{f.status === 'A' ? <span class="ssheet__tag">new</span> : f.status === 'D' ? <span class="ssheet__tag ssheet__tag--gone">gone</span> : null}
{f.binary ? (
<span class="hint">binary</span>
) : (
<span class="ssheet__nums">
{f.add ? <span class="is-add">+{f.add}</span> : null} {f.del ? <span class="is-del">−{f.del}</span> : null}
</span>
)}
{also.length ? <span class="ssheet__also">also {also.map((o) => shortName(hostedFor(o.with)?.title ?? nameOf(o.with).title, 18)).join(', ')}</span> : null}
</button>
{open && f.patch ? patchOf(f.patch) : null}
</li>
)
})}
</ul>
) : null,
with_.length ? (
<section class="ssheet__shared">
<h3 class="home__head">Changes the same files</h3>
{with_.map((o) => {
const between = involving(involving(sheet.notes, s.owner), o.with)
return (
<div class="ssheet__with">
<div>
{sessionLink(o.with, 60)}
<span class="hint"> · {o.files.slice(0, 4).join(', ')}{o.files.length > 4 ? ` and ${o.files.length - 4} more` : ''}</span>
</div>
{between.slice(-4).map((x) => (
<div class="ssheet__note">
<span class="hint">
{base(x.from) === s.owner ? 'it said' : 'they said'} · {age(Date.parse(x.ts) / 1000)} ago
</span>
<div>{shortName(x.text, 300)}</div>
</div>
))}
</div>
)
})}
</section>
) : null,
]
}
/** Where it runs, in words. */
function runsOn(s: Hosted): string {
if (s.imported) return `imported from ${importedFrom(s)}`
if (s.local) return `${s.local.client} on ${s.local.machine}`
const node = cards().find((c) => c.session === s.owner)?.node
return `midas runner${node ? ` · holds ${node}` : ''}`
}
/** A session's projects, for its sheet: those it works in, or that it adds them as it needs. */
function projectsOf(s: Hosted): m.Children {
const repos = reposOf(s)
if (repos.length) return repos.map((r) => projectName(r)).join(', ')
return s.layout === 'folder' ? <span class="hint">none yet: it adds the projects the task needs</span> : 'not set'
}
/**
* One of the sheet's actions, confirmed: the sheet closes at once, and when the session
* leaves the list's view (done, deleted) the page goes back to the list, without waiting
* for the hub to say so; the toast says how it went.
*/
function leave(what: string, run: () => Promise<unknown>, toList = false) {
sheet.tab = ''
if (toList) go('sessions')
return act(what, run)
}
function aboutTab(s: Hosted): m.Children {
const c = cards().find((x) => x.session === s.owner)
const row = (k: string, v: m.Children, act?: m.Children) => (
<div class="ssheet__row">
<span class="ssheet__k">{k}</span>
<span class="ssheet__v">{v}</span>
{act ?? <span />}
</div>
)
return [
c ? <div class="ssheet__steps">{stepsBar(c)}</div> : null,
<div class="ssheet__rows">
{row(
'Name',
sheet.renaming ? (
<input
class="ssheet__name"
value={sheet.name}
oncreate={(v: m.VnodeDOM) => (v.dom as HTMLInputElement).focus()}
oninput={(e: Event) => (sheet.name = (e.target as HTMLInputElement).value)}
onkeydown={(e: KeyboardEvent) => {
if (e.key === 'Enter' && sheet.name.trim()) {
sheet.renaming = false
void act('renamed', () => api.renameSession(s.id, sheet.name.trim()))
} else if (e.key === 'Escape') sheet.renaming = false
}}
/>
) : (
s.title
),
steers() && !s.imported ? (
<button
type="button"
class="home__link"
onclick={() => {
sheet.name = s.title
sheet.renaming = !sheet.renaming
}}
>
{sheet.renaming ? 'Cancel' : 'Rename'}
</button>
) : null,
)}
{/* Picked from its first message, not by hand: shown, not chosen. */}
{several() ? row(reposOf(s).length > 1 ? 'Projects' : 'Project', projectsOf(s)) : null}
{/* Named only when it is not Claude Code, which every session ran before there was a choice. */}
{s.agent && s.agent !== CLAUDE ? row('Agent', agentName(s.agent)) : null}
{s.branch ? row('Branch', [s.branch, <div class="hint">off {s.base}{sheet.files && sheet.filesFor === s.id ? ` · ${sheet.files.commits} commit${sheet.files.commits === 1 ? '' : 's'}` : ''}</div>]) : null}
{row('Runs on', runsOn(s))}
{row('Started', [`by ${speaker(s.by).title} · ${since(s.created)} ago`, <div class="hint">{s.id}</div>])}
{s.finished ? row('Finished', s.finished.outcome === 'done' ? `done ${since(s.finished.at)} ago` : s.finished.outcome === 'dropped' ? `dropped ${since(s.finished.at)} ago` : `live ${since(s.finished.live_at ?? s.finished.at)} ago`) : null}
</div>,
<div class="ssheet__acts">
{/* Between the editor and the hub's runner: the conversation and its work go along. */}
{s.local && !ended(s)
? confirmButton(`handoff-${s.id}`, {
label: 'Continue on midas',
armedLabel: 'Tap again to move it',
disabled: !steers(),
run: () => leave(`“${shortName(s.title, 40)}” moving to midas`, () => api.handoff(s.id)),
})
: null}
{s.handed && !s.local && !ended(s)
? confirmButton(`handback-${s.id}`, {
label: `Hand back to ${s.handed.from.client}`,
armedLabel: 'Tap again to hand it back',
disabled: !steers(),
run: () => leave(`“${shortName(s.title, 40)}” handed back to ${s.handed?.from.client}`, () => api.handback(s.id)),
})
: null}
{/* Finished on the person's word; idle ones with nothing to land finish by themselves. */}
{s.finished || s.imported
? null
: confirmButton(`done-${s.id}`, {
label: 'Mark done',
armedLabel: 'Tap again: it ends and moves to Finished',
disabled: !steers(),
run: () => leave(`“${shortName(s.title, 40)}” marked done`, () => api.markDone(s.id), true),
})}
{ended(s)
? null
: confirmButton(`end-${s.id}`, {
label: s.local ? 'Stop following it here' : 'End session',
armedLabel: 'Tap again to end it',
variant: 'danger',
disabled: !steers(),
run: () => leave(`“${shortName(s.title, 40)}” ended`, () => api.stopSession(s.id)),
})}
{ended(s)
? confirmButton(`delete-${s.id}`, {
label: 'Delete',
armedLabel: 'Tap again: its conversation goes',
disabled: !steers(),
run: () => leave(`“${shortName(s.title, 40)}” deleted`, () => api.deleteSession(s.id), true),
})
: null}
</div>,
<p class="hint">
{ended(s)
? `Its branch ${s.branch} keeps its work; the message box reopens it.`
: 'Ending keeps its branch, and it can be reopened. A session finishes on your answer to "Shall it land?", on Mark done, or by itself once idle 15 minutes with nothing to land. Model, mode and context are in the message box.'}
</p>,
]
}
/** The sheet itself, over the conversation while a tab is open. */
function sessionSheet(s: Hosted): m.Children {
if (!sheet.tab) return null
const n = fileCount(s)
// To live while it is on its way; once it is not, the tab it was on falls to About.
const way = !!journeyOf(s)
const tab = sheet.tab === 'live' && !way ? 'about' : sheet.tab
return (
<div class="ssheet" onclick={() => (sheet.tab = '')}>
<div class="ssheet__panel" role="dialog" aria-label={`About ${s.title}`} onclick={(e: Event) => e.stopPropagation()}>
<div class="ssheet__grab" aria-hidden="true" />
<div class="ssheet__tabs" role="tablist">
{way ? (
<button type="button" role="tab" aria-selected={tab === 'live'} class={tab === 'live' ? 'is-on' : ''} onclick={() => (sheet.tab = 'live')}>
To live
</button>
) : null}
<button type="button" role="tab" aria-selected={tab === 'files'} class={tab === 'files' ? 'is-on' : ''} onclick={() => (sheet.tab = 'files')}>
{n ? `${n} file${n === 1 ? '' : 's'}` : 'Files'}
</button>
<button type="button" role="tab" aria-selected={tab === 'about'} class={tab === 'about' ? 'is-on' : ''} onclick={() => (sheet.tab = 'about')}>
About
</button>
<button type="button" class="ssheet__close" aria-label="Close" onclick={() => (sheet.tab = '')}>
✕
</button>
</div>
<div class="ssheet__body">{tab === 'live' ? wayToLive(s) : tab === 'files' ? filesTab(s) : aboutTab(s)}</div>
</div>
</div>
)
}
class SessionView extends MithrilComponent<{s: Hosted}> {
oninit(vnode: m.Vnode<{s: Hosted}>) {
// Opened from a list's gauge: at its To live.
sheet.tab = wayFor === vnode.attrs.s.id ? 'live' : ''
wayFor = ''
// A conversation opens at its latest, wherever the one before it was being read.
pinned = true
}
view(vnode: m.Vnode<{s: Hosted}>) {
const s = vnode.attrs.s
follow(s.id)
return (
<div class="session">
<div class="session__log" {...followDown}>
{live.following === s.id ? render(followedLog(), s) : null}
</div>
<button type="button" class="jump-new" onclick={toLatest}>
<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M12 5v14M6 13l6 6 6-6" />
</svg>
New below
</button>
{sessionSheet(s)}
</div>
)
}
}
/** The choices a new session starts with: the last ones made here, kept in this browser. */
function remembered(key: string, choices: Mode[], fallback: string): string {
try {
const kept = localStorage.getItem(key)
// A choice the list no longer has (a model renamed since) would leave the dropdown blank.
return kept && choices.some((c) => c.id === kept) ? kept : fallback
} catch {
return fallback
}
}
/** Where a choice for the next session is kept. Trusted became the default mode (2026-10-23): a key of its own drops the Manual every page had kept until then. */
const storedAs = (key: 'mode' | 'model' | 'agent') => (key === 'mode' ? 'midas-start-mode' : `midas-new-${key}`)
/** Claude Code's id among the agents (sessions.rs `DEFAULT_AGENT`): the models and modes a new session is offered are its. */
const CLAUDE = 'claude'
/** The agents a new session may run (hub.conf's agents), asked once a page; Claude Code alone until the hub answers. */
const agents = local({list: [{id: CLAUDE, name: 'Claude Code'}] as Mode[], asked: false})
function askAgents() {
if (agents.asked) return
agents.asked = true
api.agents()
.then((list) => {
agents.list = list
// One the hub no longer has, kept from before, would start nothing.
if (!list.some((a) => a.id === fresh.agent)) fresh.agent = CLAUDE
})
.catch(() => (agents.asked = false))
}
/** An agent's name, as the hub has it; its id while the list is asked, or once the hub no longer has it. */
function agentName(id: string): string {
askAgents()
return agents.list.find((a) => a.id === id)?.name ?? id
}
/** The choice kept for the agent, checked against the hub's list once it comes (`askAgents`). */
function keptAgent(): string {
try {
return localStorage.getItem(storedAs('agent')) || CLAUDE
} catch {
return CLAUDE
}
}
const fresh = local({text: '', mode: remembered(storedAs('mode'), START_MODES, BYPASS), model: remembered('midas-new-model', START_MODELS, 'default'), agent: keptAgent()})
/** The project a new session goes in when the page is narrowed to one; else none is chosen here. */
function freshProject(): Project | undefined {
return projects.list.find((p) => p.repo === shown())
}
/** The project to start a session in: the page's, else `auto` — its agent adds the projects the task needs (sessions.rs `add_project`). */
const freshRepo = () => freshProject()?.repo ?? 'auto'
/** A dropdown model that keeps the choice for the next new session too. */
function kept(key: 'mode' | 'model' | 'agent') {
return {
get value() {
return fresh[key]
},
set value(v: string) {
fresh[key] = v
try {
localStorage.setItem(storedAs(key), v)
} catch {
// A browser that keeps nothing: the choice holds for this page.
}
},
}
}
/** How another agent is told from Claude Code's models in the one choice (`thinkers`). */
const AGENT = 'agent:'
/**
* The one choice of what does the work: Claude Code's models, then the other agents
* (Settings ▸ Agents), each in a group of its own once there are any, so a new
* session's form needs no second dropdown for the agent.
*/
function thinkers(): {id: string; name: string; group?: string}[] {
const others = agents.list.filter((a) => a.id !== CLAUDE)
if (!others.length) return START_MODELS
return [
...START_MODELS.map((x) => ({...x, group: 'Claude Code'})),
...others.map((a) => ({id: AGENT + a.id, name: a.name, group: 'Other agents'})),
]
}
/** The choice's model: a model of Claude Code's, or another agent; either is kept for the next session. */
function thinker() {
const agent = kept('agent')
const model = kept('model')
return {
get value() {
return fresh.agent === CLAUDE ? fresh.model : AGENT + fresh.agent
},
set value(v: string) {
if (v.startsWith(AGENT)) {
agent.value = v.slice(AGENT.length)
} else {
agent.value = CLAUDE
model.value = v
}
},
}
}
/**
* What a new session is started on: the agent, and with Claude Code the model and
* mode chosen; another agent starts on its own, whose names for them are not these.
*/
function startChoice(): [mode: string, model: string, agent: string] {
return fresh.agent === CLAUDE ? [fresh.mode, fresh.model, CLAUDE] : ['', 'default', fresh.agent]
}
/**
* A new session's composer, as Claude's own apps have it: what it should do,
* the project, the agent, model and mode last chosen, Ctrl/⌘+Enter to start. It always
* starts from the project's main (the CLI's --base can say otherwise).
*/
function newComposer(tools: (m.Vnode | null)[] = []): m.Children {
askAgents()
/** Start it with what the box says, with the agent, model and mode chosen; a refusal throws. */
const launch = async () => {
const prompt = fresh.text.trim()
fresh.text = ''
const images = takeAttachments()
const {id} = await api.startSession(prompt, freshRepo(), 'main', ...startChoice(), images)
startedAhead(id, prompt)
select(id)
}
const start = async () => {
if ((!fresh.text.trim() && !pasted.items.length) || pasted.uploading || !steers()) return
// At the person's own cap, or as many at work as they wanted (focus.rs): asked first.
if (!(await startGuard())) return
void act('session started', launch, {quiet: true})
}
const claude = fresh.agent === CLAUDE
const bypassing = claude && fresh.mode === BYPASS
return foldable(
<div class="session__say">
{attachments()}
<textarea
class="session__prompt session__message"
rows={2}
disabled={!steers()}
{...imageInput}
placeholder={steers() ? `Describe a task or ask a question; paste an image if it helps${keys('Mod+Enter starts')}` : 'starting sessions takes the steer role'}
value={fresh.text}
oninput={(e: Event) => {
fresh.text = (e.target as HTMLTextAreaElement).value
}}
onkeydown={(e: KeyboardEvent) => {
if (sends(e)) {
e.preventDefault()
void start()
}
}}
/>
<div class="session__send">
{attachButton()}
{chooser(thinker(), thinkers(), claude ? 'the model it thinks with' : 'the agent that does the work')}
{claude ? chooser(kept('mode'), START_MODES, bypassing ? 'it will do everything without asking' : 'how much it may do without asking', bypassing) : null}
<span class="session__go">
<button
type="button"
class="session__arrow"
disabled={!steers() || pasted.uploading > 0 || (!fresh.text.trim() && !pasted.items.length)}
title={`Start the session (${SEND_KEY}+Enter)`}
aria-label="Start the session"
onclick={() => void start()}
>
{arrowUp}
</button>
</span>
</div>
</div>,
{draft: fresh.text, tools, hint: 'Describe a task…'},
)
}
/**
* A session just started, as the page has it until the hub's board names it: its
* first message and "starting". Opening it at once said "No session s3: it may
* have been deleted" for the second or so the board took.
*/
function startedAhead(id: string, prompt: string) {
const t = Math.floor(Date.now() / 1000)
const title = prompt.split('\n').map((l) => l.replace(/^[#>*\-\s]+/, '').trim()).find(Boolean)?.slice(0, 80) ?? 'A picture'
expect(`hosted:${id}`, {
kind: 'hosted', id, title, status: 'queued', branch: `session/${id}`, owner: `session-${id}`, by: '',
created: t, updated: t, active: t, base: 'main', repo: freshProject()?.repo ?? null,
queue: [{qid: 0, text: prompt, by: ''}],
})
}
/** A conversation's design starts from what the composer holds, and starts its session as the composer would. */
hooks.draft = (about) => (about.kind === 'new' ? fresh.text : about.kind === 'session' && about.id === selected() ? draft.text : '')
hooks.startSession = async (brief, images) => {
const {id} = await api.startSession(brief, freshRepo(), 'main', ...startChoice(), images)
if (here().startsWith('sessions') && !selected()) fresh.text = ''
startedAhead(id, brief)
select(id)
return id
}
/** A session in the list: its state, its name, what it is doing or how it ended, its project and age. */
function listRow(h: Hosted, g?: Group): m.Children {
const j = g === 'landing' ? journeyOf(h) : null
const st = j ? null : stateLine(h)
const what = st ? st.text : `landing · ${shortWords(j!)}`
const peeking = !!j && peek.id === h.id
return (
<li key={h.id}>
<a class={`slist__row${ended(h) ? ' slist__row--ended' : ''}`} href={`/sessions/${h.id}`}>
{j ? (
// Its gauge, a thumb's width to tap: where it is on its way, here, without opening it.
<button
type="button"
class={`slist__gauge${peeking ? ' is-on' : ''}`}
aria-expanded={String(peeking)}
aria-label={`${gaugeOf(j).words}: show`}
onclick={(e: Event) => {
e.preventDefault()
e.stopPropagation()
peek.id = peeking ? '' : h.id
}}
>
{gauge(j, 26)}
</button>
) : g ? (
markOf(h, g)
) : (
<span class={`dot dot--${h.status}`} title={STATUS[h.status].label} />
)}
<span class="slist__main">
<span class="slist__title">
{h.autopilot?.on && !ended(h) ? <span class="pilot-mark" title="on autopilot">{plane(12)}</span> : null}
{h.title}
</span>
<span class="slist__sub hint">
{st?.wake ? [icon.clock(), ' '] : null}
{shortName(what, 90)}
</span>
</span>
<span class="slist__end">
{shown() ? null : projectTag(reposOf(h))}
<span class="hint">{age(h.updated)}</span>
</span>
</a>
{peeking ? (
<div class="slist__peek">
{wayToLive(h, () => {
wayFor = h.id
peek.id = ''
go(`sessions/${h.id}`)
})}
</div>
) : null}
</li>
)
}
/** The session whose way to live its gauge in the list has opened, under its row. */
const peek = local({id: ''})
/** The sessions at work in the page's projects: those waiting on the person first, then the busiest, the latest first. */
function atWork(): Hosted[] {
const rank: Record<Hosted['status'], number> = {needs_permission: 0, working: 1, starting: 1, queued: 1, waiting: 2, stopped: 3, failed: 3}
return hosted()
.filter((h) => inView(reposOf(h)) && !h.archived && !h.imported && !ended(h))
.sort((a, b) => rank[a.status] - rank[b.status] || b.updated - a.updated)
}
/**
* Sessions, to get back to one: in the nav's groups (Needs you, Landing, At
* work, Landed today, Idle). Older ones, the archived and the imported are
* found by searching.
*/
class SessionList extends MithrilComponent {
view() {
askProjects()
const gs = groups()
const q = find.q.trim()
return (
<div class="slist">
<div class="slist__find">
<div class="nav-find__row">
<FieldText model={query} type="search" placeholder="Search every session, past and imported" />
{projectSelect(atWorkIn)}
</div>
</div>
{runnerAwayLine()}
{q.length >= 2 ? (
<div class="slist__found">{found(go, '')}</div>
) : gs.length ? (
gs.map((g) => (
<div class="slist__group" key={g.key}>
{groupHead(g, 'slist__head')}
{folded(g.key, g.these.length) ? null : (
<ul class="slist__list">
{byTech(g.these).map((r) =>
r.tech ? (
<li key={`tech-${r.tech.tech}`} class={`slist__tech ${themeOf(r.tech)}`}>
{techHead(r.tech, 'slist__tech-head')}
<ul class="slist__list">{r.these.map((h) => listRow(h, g.key))}</ul>
</li>
) : (
listRow(r.h, g.key)
),
)}
</ul>
)}
</div>
))
) : (
<p class="hint">None at work. Start one with +.</p>
)}
<NewSessionButton />
</div>
)
}
}
/**
* A new session's page: the sessions already at work, a tap from going back to one
* (what was in mind may be one of them), the open ends left for later, each a tap
* from the composer (the session it starts is shown it anyway), and a word on what
* a session is.
*/
class NewSession extends MithrilComponent {
view() {
const later = todos().filter((t) => !t.claimed_by)
const running = atWork()
return (
<div class="session__empty">
{running.length ? (
<div class="session__later">
<h3 class="home__head">
Running <span class="home__count">{running.length}</span>
</h3>
<ul class="slist__list">{running.map((h) => listRow(h))}</ul>
</div>
) : null}
{later.length ? (
<div class="session__later">
<h3 class="home__head">Left for later</h3>
<ul class="slist__list">
{later.map((t) => (
<li>
<button type="button" class="session__pick" title="put it in the message box" onclick={() => (fresh.text = t.text)}>
{shortName(t.text, 160)}
</button>
</li>
))}
</ul>
</div>
) : null}
<p class="hint">{agentName(fresh.agent)} in a folder of its own, a worktree of each project in it, on a branch of its own off {freshProject() ? `${freshProject()!.name}'s main` : several() ? "the main of each project it works in: it adds those the task needs, one or several, or none for a question" : 'main'}.</p>
</div>
)
}
}
/** The page's title for the Sessions page: the open session's, or what is shown instead. */
export function sessionTitle(): string {
const id = selected()
return openSession()?.title ?? (id ? `Session ${id}` : isNew() ? 'New session' : 'Sessions')
}
/** Agent sessions midas runs: the open one, or a new one. The list is in the Shell's nav. */
export class Sessions extends MithrilComponent {
oninit() {
connect()
checkAvailable()
askProjects()
}
view() {
const s = openSession()
if (s) return <SessionView key={s.id} s={s} />
if (isNew()) return <NewSession />
const id = selected()
if (!id) return <SessionList />
// Asked for by its address before the hub has said which sessions there are, or one that is gone.
return (
<div class="session__empty">
<p class="hint">
{live.loaded ? (
<>
No session {id}: it may have been deleted. <a href="/sessions/new">Start a new one</a>
</>
) : (
`Loading session ${id}…`
)}
</p>
</div>
)
}
}