garage44.eu/jeroen/midas

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

.. /web/src/lib/stream.ts

raw

import {local} from '@/lib/reactive'

/** A node it may take, and who holds it (board.rs `node_wait.held`). */
export interface NodeHeld {
    node: string
    offline?: boolean
    by?: string
    since?: number | null
    purpose?: string | null
    intent?: string | null
    intent_until?: number | null
    yielding?: boolean
}

/** Its place in line for a node, what it may take, and who holds those. */
export interface NodeWait {
    position: number
    wants: string
    gate: boolean
    since: number
    held?: NodeHeld[]
}

/** A session's card on the board (board.rs). */
export interface BoardCard {
    kind: 'card'
    session: string
    label: string | null
    branch: string | null
    link: string | null
    /** Its project (`owner/name`), as its session's start said; none for one that did not. */
    repo?: string | null
    stage: 'working' | 'waiting_for_node' | 'on_node' | 'waiting_to_land' | 'landing' | 'landed'
    since: number | null
    /** When it last did something, as its session's hooks, builds and takes show it. */
    active?: number | null
    node: string | null
    position: number | null
    wants?: string
    purpose?: string | null
    intent?: string | null
    last_command?: string | null
    next_turn?: string | null
    gate?: boolean
    /** It holds `node` through its landing gate, not for its own builds. */
    node_gate?: boolean
    /** Its place in line for a node (its own, or its gate's), whatever its lane. */
    node_wait?: NodeWait | null
    /** A command is running on its node now. */
    busy?: boolean
    /** That command has printed nothing and used no CPU for `quiet_s` (five minutes or more); midas stops it at thirty. */
    quiet?: {command: string; quiet_s: number} | null
    step?: string | null
    sha?: string | null
    /** Landed, and every target deployed after landings serves it (ship.rs). */
    live?: boolean
    badges: {overlaps: number; notes: number; decisions: string[]}
}

/** A sessions runner, as the hub last heard it (runners.rs): `away` since when it stopped asking for work. */
export interface BoardRunner {
    kind: 'runner'
    id: string
    name: string
    away: number | null
}

/** A node's slot on the board. */
export interface BoardNode {
    kind: 'node'
    id: string
    machine: string
    renderer: string | null
    online: boolean
    drained: {why: string; by: string; for?: string} | null
    holder: string | null
    service: boolean
    since: number | null
    version: string | null
}

/** What a session waits on the person for (sessions.rs, `awaits`); a `secret` has a field on the page, whose value goes to the hub. */
export interface Awaits {
    text: string
    steps?: string
    secret?: {kind: 'remote'; name: string; url?: string | null} | {kind: 'bot'; target: string; name: string} | null
    by: string
    at: number
    /** Put off until then: out of Needs you meanwhile. */
    snooze?: number | null
}

/** An agent session midas runs (sessions.rs), as the list shows it. */
export interface Hosted {
    kind: 'hosted'
    id: string
    title: string
    status: 'queued' | 'starting' | 'working' | 'waiting' | 'needs_permission' | 'stopped' | 'failed'
    branch: string
    owner: string
    by: string
    created: number
    /** When its status last changed: a runner starting again moves this too. */
    updated: number
    /** Its runner stopped asking the hub for work at this time: paused, whatever `status` last said (runners.rs). */
    runner_away?: number | null
    /** When it last did something (a turn began or ended, a person reopened it); a restart does not move it. */
    active?: number | null
    base: string
    /** The session it was started from, when one started it (sessions.rs `set_from`). */
    from?: string | null
    /** Its project, as `owner/name`: the repository it works in (none before projects); of several, the first. */
    repo?: string | null
    /** The projects a session in a folder of its own works in, a worktree each, as its agent added them. */
    repos?: string[] | null
    /** The agent it runs, by its id in hub.conf's agents; none for Claude Code. */
    agent?: string | null
    /** `folder`: a session that can span projects; none for one worktree (before, and handed over from an editor). */
    layout?: string | null
    archived?: boolean
    /** A conversation Claude Code had elsewhere (`midas sessions import`): a record to read, never reopened. */
    imported?: {key: string; from: string; cwd: string; complete: boolean; at: number} | null
    /** Messages waiting for the agent, oldest first: editable until it takes one. */
    queue?: {qid: number; text: string; by: string; images?: {file: string; mime: string}[]}[] | null
    /** What it is doing now, in words, while at work (the hub reads it off its log). */
    doing?: string | null
    /** Where it runs when it is an editor's, mirrored here (`midas acp --mirror`): it is
     * followed and steered from here, but its agent and its conversation are there. */
    local?: {client: string; machine: string; cwd: string | null} | null
    /** An editor's session whose mirror stopped asking after it: when the hub noticed. */
    gone?: number | null
    /** Handed over from an editor to the hub's runner: where it came from, by whom. */
    handed?: {from: {client: string; machine: string; cwd: string | null}; by?: string | null; at: number; sha: string} | null
    /** Handed back to that editor: its work's branch, and whether the editor has taken it yet. */
    back?: {branch: string; sha: string; at: number; by?: string | null; pending: boolean} | null
    /** It finishes once this landed commit is live (`land --finish`). */
    finish?: {sha: string; at: number; by: string} | null
    /** Finished on the person's answer: landed and live, or dropped. Ended and filed. */
    finished?: {outcome: 'landed' | 'dropped' | 'done'; at: number; sha?: string; live_at?: number} | null
    /** When it carries on by itself (`midas later`, or set here): midas tells it `text` then, starting it again if it had ended. */
    wake?: {at: number; text: string; by: string; set: number} | null
    /** What it waits on the person for, something only they can do (`midas await`): Needs you until given, put off (`snooze`) or declined. */
    awaits?: Awaits | null
    /** Deploys it asked for that have not ended yet: they go on while its agent waits. */
    deploys?: DeployRun[]
    /** How long the builds it runs now take as a rule, in seconds, by the tool call or background task running each. */
    expect?: Record<string, number> | null
    /** Its autopilot (autopilot.rs): on, by whom, until when, to what end; deciding, or left something to the person. */
    autopilot?: Autopilot | null
    /** The template (and schedule) it was started from (templates.rs). */
    template?: {id: string; name: string; v: number; schedule?: string | null} | null
    /** The research tree's tech it researches (tree.rs `origin_of`). */
    research?: ResearchOrigin | null
}

/** A tech a session researches: its name, icon and size, the goal at the top and the theme under it it serves, the theme's colour slot (-1: none). */
export interface ResearchOrigin {
    tech: string
    name: string
    icon?: string | null
    size?: string | null
    goal?: string | null
    theme?: string | null
    slot: number
}

/** A session's autopilot, as its meta keeps it. Off: `why` when it turned itself off. */
export interface Autopilot {
    on: boolean
    by?: string
    at?: number
    until?: number | null
    goal?: string
    state?: 'idle' | 'deciding' | 'left'
    left_why?: string | null
    /** Left: whether it needs the person now, or can wait for their next decision block (focus.rs). */
    left_urgent?: boolean
    why?: string | null
}

/** One step of a deploy (deploy.rs `pending`): done and what it took, running since when, or to come; each with what it takes as a rule. */
export interface DeployStep {
    name: string
    state: 'done' | 'now' | 'todo'
    seconds?: number | null
    since?: number | null
    typical?: number | null
}

/** A deploy not yet published or failed. `typical`: how long one of its target takes as a rule, asked to published, in seconds. */
export interface DeployRun {
    deploy: string
    target: string
    sha: string
    since: string
    phase: string
    typical?: number | null
    steps?: DeployStep[]
}

/** Where a deploy is, short: "2 of 5: bun run build". */
export function deployStep(d: DeployRun): {text: string; step: DeployStep} | null {
    const steps = d.steps ?? []
    const i = steps.findIndex((s) => s.state === 'now')
    return i < 0 ? null : {text: `${i + 1} of ${steps.length}: ${steps[i].name}`, step: steps[i]}
}

/** What a session started that is still going, in words, while its agent waits on it. */
export function background(h: Hosted): string | null {
    const d = h.deploys?.[0]
    return d ? `${d.target} deploy: ${d.phase}` : null
}

/** A session mode the agent offers (ACP's `availableModes`). */
export interface Mode {
    id: string
    name: string
    description?: string | null
}

/** One line of a session's log: what it said, did, asked and was told. */
/** One field of a question form: a single or multiple choice, or an "Other" text box. */
export interface QuestionField {
    type: 'string' | 'array'
    title?: string
    description?: string
    oneOf?: {const: string; title?: string; description?: string}[]
    items?: {anyOf?: {const: string; title?: string; description?: string}[]}
}

export interface QuestionSchema {
    type: 'object'
    properties: Record<string, QuestionField>
}

/** A note one session sent another, or midas's own (`from: 'hub'`); an overlap says what about. */
export interface PageNote {
    id?: string
    from: string
    kind?: string
    label?: string | null
    branch?: string | null
    text?: string
    about?: {
        with: string
        label?: string | null
        branch?: string | null
        files: {file: string; you: string[]; them: string[]}[]
        more?: number
    }
}

export interface LogItem {
    n: number
    at: number
    kind:
        | 'user'
        | 'agent'
        | 'tool'
        | 'tool_update'
        | 'plan'
        | 'permission'
        | 'permission_answered'
        | 'turn_end'
        | 'status'
        | 'error'
        | 'modes'
        | 'mode'
        | 'media'
        | 'usage'
        | 'question'
        | 'answered'
        | 'models'
        | 'model'
        | 'finishing'
        | 'finished'
        | 'background'
        | 'wake'
        | 'awaits'
        | 'autopilot'
        | 'autopilot_deciding'
        | 'autopilot_left'
        | 'autopilot_done'
        | 'autopilot_idle'
    text?: string
    /** By the autopilot (`user`, `permission_answered`, `answered`), and its own items: why it decided so. */
    why?: string | null
    /** `autopilot`: turned on or off; until when; its goal. `autopilot_deciding`: what about. */
    on?: boolean
    until?: number | null
    goal?: string
    about?: 'permission' | 'question' | 'next'
    /** `wake`: set to carry on at `when`, or `cancelled`, or `woken` (its time came, or a person said now). */
    when?: number
    cancelled?: boolean
    woken?: boolean
    /** `awaits`: set (`text`), put off until `snooze`, or ended `how` — given, declined, or done by the agent. */
    snooze?: number
    how?: 'given' | 'declined' | 'done'
    /** `background`: what runs for it between turns (a command, a subagent, a workflow), and a turn one woke. */
    tasks?: {id: string; kind: string; description: string}[]
    turn?: boolean
    /** `finishing`, `finished`: the landed commit; `finished`: landed or dropped, and when it went live. */
    sha?: string
    outcome?: 'landed' | 'dropped' | 'done'
    live_at?: number
    /** `user`: the images pasted with it, kept with the session. */
    images?: {file: string; mime: string}[]
    /** `user`: it waited for the turn running then (`queued`), or stopped it to go first (`now`). */
    queued?: boolean
    now?: boolean
    /** `user` by midas: the note it sent on, which the page draws as a card (collab.rs `page_note`). */
    note?: PageNote
    /** `question`: the agent's question as a form (ACP form elicitation); `answered`: what came back. */
    message?: string
    schema?: QuestionSchema
    action?: 'accept' | 'decline' | 'cancel'
    content?: Record<string, string | string[]>
    /** `usage`: tokens in its context after a turn, of the model's window, and the cost so far in USD. */
    used?: number
    size?: number
    cost?: number | null
    /** `modes`: what the agent offers; `mode`: the one it is in now. */
    available?: Mode[]
    current?: string
    /** `tool`: what it was given (a command, a file); `tool_update`: what came of it, clipped. */
    input?: Record<string, unknown> | null
    output?: string | null
    /** `tool`, `tool_update`: the subagent call (Agent, Task) this call was made inside, if any. */
    parent?: string | null
    /** `media`: a file the agent showed (`/v1/hosted/<id>/media/<file>`). */
    file?: string
    mime?: string
    caption?: string | null
    by?: string
    id?: string
    title?: string | null
    status?: string | null
    request?: string
    option?: string
    options?: {optionId: string; name: string; kind: string}[]
    entries?: {content: string; status: string}[]
    reason?: string
}

/** What ties two cards: files both change, notes between them, a decision about both (board.rs). */
export interface BoardLink {
    kind: 'link'
    a: string
    b: string
    files: string[]
    notes: number
    last_note?: number
    decisions: string[]
}

/** An open end: work left for the next session on a machine, the board's first lane. */
export interface BoardTodo {
    kind: 'todo'
    id: string
    text: string
    for: string
    by: string
    at: number
    claimed_by?: string | null
}

type Entity = BoardCard | BoardNode | Hosted | BoardLink | BoardTodo | BoardRunner

/**
 * The board, live from the hub's WebSocket (`/v1/stream`): a snapshot, then
 * patches that set each changed entity whole. A gap in the versions asks for a
 * snapshot again; a dropped connection comes back by itself, slower each time.
 */
export const live = local({
    entities: {} as Record<string, Entity>,
    version: 0,
    connected: false,
    /** The first snapshot has come: until then an empty board is not yet known to be empty. */
    loaded: false,
    /** The followed session, its log's line after the last it has, and a count of its log's changes (`followedLog`). */
    following: '' as string,
    logNext: 0,
    logSeq: 0,
})

/**
 * The followed session's log. Not in `live`: its state makes every object of an
 * array put in it a proxy of its own, so each look at an item's kind went through
 * a trap that recorded it as read, and drawing a long conversation for each chunk
 * the agent sent took a tenth of a second on a fast machine.
 */
let followed: LogItem[] = []

/** The followed session's log, as far as it has come; a view that reads it is drawn again as it grows. */
export function followedLog(): LogItem[] {
    void live.logSeq
    return followed
}

function setLog(items: LogItem[], next: number) {
    followed = items
    live.logNext = next
    live.logSeq++
}

/**
 * Entities the page made itself ahead of the hub: a session it just started, shown
 * at once rather than as "no such session" until the board names it. Each goes
 * the moment the hub sends the real one, or after a minute if it never does.
 */
const expected: Record<string, {e: Entity; until: number}> = {}

export function expect(key: string, e: Entity) {
    expected[key] = {e, until: Date.now() + 60000}
    if (!live.entities[key]) live.entities = {...live.entities, [key]: e}
}

/** `entities`, with what the page expects and the hub (`sent`, this message's) has not sent yet. */
function withExpected(entities: Record<string, Entity>, sent: Record<string, Entity>): Record<string, Entity> {
    const now = Date.now()
    let out = entities
    for (const [k, x] of Object.entries(expected)) {
        if (k in sent || x.until < now) delete expected[k]
        else if (!(k in out)) out = {...out, [k]: x.e}
    }
    return out
}

/**
 * The build of the page the hub served when this one connected first (ws.rs `page`), and
 * whether the hub has served another since. A page left open ran its old code for days
 * across deploys: it reconnected after each and never loaded the new one.
 */
const build = {first: '', stale: false}

function newBuild(page: string) {
    if (!build.first) build.first = page
    else if (page !== build.first) build.stale = true
    reloadIfIdle()
}

/**
 * Load the new build, once nothing would be lost by it: no field holds the cursor and no
 * text area unsent text (a draft lives only in the page). Looked at again when a field lets go of the
 * cursor and when the page comes back into view.
 */
function reloadIfIdle() {
    if (!build.stale) return
    // Text areas only: the messages and briefs are written there, and a settings field shows
    // a value already kept, which would hold the page on the old build for good.
    const busy = document.activeElement?.matches('textarea, input, select, [contenteditable]') ||
        [...document.querySelectorAll('textarea')].some((f) => f.value.trim())
    if (!busy) location.reload()
}

globalThis.document?.addEventListener('focusout', () => setTimeout(reloadIfIdle, 0))

let socket: WebSocket | null = null
let retry = 1000
let timer = 0
let resyncing = false

export function connect() {
    if (socket) return
    const ws = new WebSocket(`${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/v1/stream`)
    socket = ws
    resyncing = false
    ws.onopen = () => {
        live.connected = true
        if (live.following) ws.send(JSON.stringify({type: 'follow', session: live.following, after: live.logNext}))
    }
    ws.onmessage = (e) => {
        const m = JSON.parse(e.data as string)
        if (m.type === 'snapshot') {
            resyncing = false
            // Connected for real: a hub that takes the connection and drops it is not retried every second.
            retry = 1000
            if (typeof m.page === 'string') newBuild(m.page)
            live.entities = withExpected(m.entities, m.entities)
            live.version = m.version
            live.loaded = true
        } else if (m.type === 'log') {
            if (m.session !== live.following) return
            // Only what is new: following a session again before its first answer came asks the
            // hub for it from the start twice, and the log drew its opening twice ("mode: Manual"
            // between two "mode: Trusted").
            const last = followed.at(-1)?.n ?? 0
            setLog(followed.concat((m.items as LogItem[]).filter((it) => it.n > last)), m.next)
        } else if (m.type === 'patch') {
            // One gap asks for one snapshot: the patches already on their way miss too, and each
            // asking again had the hub send the whole board once per patch.
            if (resyncing) return
            if (m.version !== live.version + 1) {
                resyncing = true
                ws.send(JSON.stringify({type: 'resync'}))
                return
            }
            const next = {...live.entities, ...m.upsert}
            for (const k of m.remove as string[]) delete next[k]
            live.entities = withExpected(next, m.upsert)
            live.version = m.version
        }
    }
    ws.onclose = () => {
        // One replaced already (reconnect, or back from sleep): its close is not the new one's.
        if (socket !== ws) return
        socket = null
        live.connected = false
        clearTimeout(timer)
        timer = window.setTimeout(connect, retry)
        retry = Math.min(retry * 2, 30000)
    }
}

// A phone brought back to the page: its stream was cut while it slept, and the retry may be
// half a minute off by now. Try again at once.
globalThis.document?.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'visible') reloadIfIdle()
    if (document.visibilityState !== 'visible' ||socket?.readyState === WebSocket.OPEN || socket?.readyState === WebSocket.CONNECTING) return
    if (!socket && !timer) return // never connected: not this page's to start
    retry = 1000
    clearTimeout(timer)
    socket = null
    connect()
})

/** Start again now, e.g. right after logging in. */
export function reconnect() {
    retry = 1000
    clearTimeout(timer)
    socket?.close()
    socket = null
    connect()
}

/**
 * The logs of the sessions followed last, as far as they had come: going back to
 * one goes on from there instead of fetching the whole log again (a megabyte for a
 * long session, on a phone). A log only grows, so what was read stays true.
 */
const recent = new Map<string, {log: LogItem[]; next: number}>()
const RECENT_LOGS = 3

/** Follow one session's log (one at a time): from where it was left, if it was followed lately. */
export function follow(id: string) {
    if (live.following === id) return
    if (live.following) {
        recent.delete(live.following)
        recent.set(live.following, {log: followed, next: live.logNext})
        while (recent.size > RECENT_LOGS) recent.delete(recent.keys().next().value!)
    }
    const kept = recent.get(id)
    live.following = id
    setLog(kept?.log ?? [], kept?.next ?? 0)
    if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({type: 'follow', session: id, after: live.logNext}))
}

/**
 * One list of the board's entities, worked out again only when the board changes: a
 * redraw of the session page asked for the sorted sessions ten or fifteen times, and
 * Home's sort asked inside its comparator. Every message replaces `live.entities`.
 */
function ofBoard<T>(make: (entities: Record<string, Entity>) => T): () => T {
    let src: Record<string, Entity> | null = null
    let v: T
    return () => {
        if (live.entities !== src) {
            src = live.entities
            v = make(src)
        }
        return v
    }
}

export const hosted: () => readonly Hosted[] = ofBoard((all) =>
    Object.values(all)
        .filter((e): e is Hosted => e.kind === 'hosted')
        .sort((a, b) => b.created - a.created),
)

export const links: () => readonly BoardLink[] = ofBoard((all) => Object.values(all).filter((e): e is BoardLink => e.kind === 'link'))
export const todos: () => readonly BoardTodo[] = ofBoard((all) =>
    Object.values(all)
        .filter((e): e is BoardTodo => e.kind === 'todo')
        .sort((a, b) => a.at - b.at),
)

export const cards: () => readonly BoardCard[] = ofBoard((all) => Object.values(all).filter((e): e is BoardCard => e.kind === 'card'))
export const nodes: () => readonly BoardNode[] = ofBoard((all) => Object.values(all).filter((e): e is BoardNode => e.kind === 'node'))
/** The sessions runners the hub has heard since it started. */
export const runners: () => readonly BoardRunner[] = ofBoard((all) => Object.values(all).filter((e): e is BoardRunner => e.kind === 'runner'))

/** A session the hub's search found (`/v1/hosted/search`): the place that says it first, `n` 0 for its title. */
export interface SearchHit {
    id: string
    title: string
    hits: number
    n: number
    snippet: string
}