Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876import { getShellCommand, readContentBatch, readEntryContent, readHistory, readRequests, sendContinue, sendMessage, uuidv7, type ContentPart, type HistoryEntry, type Phase, type SkillLoad, type ShellCommand } from './api';import type { Trace } from './burst';import type { Attached } from './chat/attachments';import type { Usage } from './context';import { follow, type Batch } from './stream';import { formatGap, outcome, type Mood } from './moods';
// One session's transcript as the chat shows it. Entries arrive as history// pages; blocks are what the chat draws. Content a page only referenced is// fetched when needed: messages and shell receipts at once, tool output on opening.
/** Why a turn failed: the error's own words, and all it said. */type Failure = { text: string; detail: string };
export type Block = | { kind: 'user'; key: string; text: string; images: Picture[]; from: string | null; gap: string | null; at: number; state: 'sending' | 'sent' | 'seen' | 'failed'; error?: string; skill?: string } | { kind: 'assistant'; key: string; text: string; plate: boolean; phase: HistoryEntry['phase'] } | { kind: 'thinking'; key: string; text: string; ms: number | null } | { kind: 'tool'; key: string; name: string; entry: HistoryEntry; done: boolean; trace?: Trace; failed: boolean } | { kind: 'note'; key: string; text: string } | { kind: 'compaction'; key: string; text: string } | ({ kind: 'failure'; key: string } & Failure) | { kind: 'end'; key: string; turnId: string | null; from: number; mood: Mood; seed: number; elapsedMs: number; tools: number; text: string; changed: { files: number; added: number; removed: number } } | { kind: 'progress'; key: string; name: string; title?: string | null; preview: string } | { kind: 'shell'; key: string; command: ShellCommand };
/** An artifact a cell made or revised: its id, the version, and its title. */export interface Made { id: string; version: number; title: string;}
/** The artifacts a trace says its cell made or revised. */export function madeIn(trace: Trace | undefined): Made[] { return (trace?.activities ?? []).flatMap((activity) => activity.kind === 'artifact' && activity.artifact ? [{ id: activity.artifact.id, version: activity.artifact.version, title: activity.target }] : [], );}
/** The skills a trace says its cell loaded, by name. */export function loadedIn(trace: Trace | undefined): string[] { return (trace?.activities ?? []).flatMap((activity) => (activity.kind === 'skill' ? [activity.target] : []));}
/** Output the session is writing now, before it commits: one message of thinking or reply. */interface Live { id: string; kind: 'text' | 'thinking'; text: string;}
/** A tool call running now, as its progress reports it. */interface Progress { id: string; /** The model's id for the call, which its tool_call entry carries too. */ call: string; name: string; title?: string | null; preview: string;}
interface Turn { id: string | null; /** The turn's first history position, where a review starts reading. */ from: number; start: number; last: number; tools: number; answered: boolean; files: Set<string>; added: number; removed: number; /** The turn's last reply, which its copy action copies. */ text: string;}
/** What `#read` hands `#tail`: history's blocks, its still-open turn and speaker, and the calls and shell commands it shows. */interface Read { blocks: Block[]; turn: Turn | null; speaker: string; called: Set<string>; durable: Set<string>;}
/** * Whether two blocks hold the same values, two levels down: deeper values * (an entry's content, a trace's steps) count as the same only when they are * the same objects, which they are until the entry is replaced. */function alike(a: unknown, b: unknown, depth = 2): boolean { if (Object.is(a, b)) return true; if (depth === 0 || !a || !b || typeof a !== 'object' || typeof b !== 'object' || Array.isArray(a) !== Array.isArray(b)) return false; const keys = Object.keys(a); return keys.length === Object.keys(b).length && keys.every((key) => alike((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], depth - 1));}
/** * A value worked out once per entry: entries are replaced, never changed, so * `#read`, which walks every entry on each change, reads it from here. */function perEntry<K extends object, V>(compute: (key: K) => V): (key: K) => V { const known = new WeakMap<K, V>(); return (key) => { if (known.has(key)) return known.get(key)!; const value = compute(key); known.set(key, value); return value; };}
/** The pause before your message that earns a "later" note, as in the TUI. */const AWAY_MS = 30 * 60_000;
/** A turn's run of thinking and tool use, drawn as one collapsible step list. */export type Group = { kind: 'work'; key: string; steps: Block[] } | Block;
/** An image in a message: where to load it, and its size when known. */export interface Picture { src: string; width?: number; height?: number;}
interface Pending { id: string; text: string; images: Attached[]; at: number; continuation?: boolean; /** The daemon has it, waiting for the loop to take it into the conversation. */ accepted?: boolean; error?: string;}
/** The images a user entry carries; the daemon serves each under its reference. */const picturesOf = perEntry((entry: HistoryEntry): Picture[] => entry.content.flatMap((part) => (part.kind === 'image' && part.image.reference ? [{ src: `/api${part.image.reference.url}`, width: part.image.width, height: part.image.height }] : [])),);
const textOf = perEntry((content: ContentPart[]): string => content.map((part) => (part.kind === 'text' ? part.text : '')).join(''));
/** The value of a JSON field of an entry, if the page carried it inline. */export function jsonField(entry: HistoryEntry, field: string): unknown { for (const part of entry.content) if (part.kind === 'json' && part.field === field) return part.value; return undefined;}
function traceOf(entry: HistoryEntry): Trace | undefined { for (const part of entry.content) if (part.kind === 'trace') return part.trace; return undefined;}
/** A python cell that raised, read from its result envelope. */export const failedTool = perEntry((entry: HistoryEntry): boolean => { const result = jsonField(entry, 'result'); if (typeof result !== 'string') return false; try { return JSON.parse(result)?.status === 'error'; } catch { return false; }});
function progressOf(progress: any): Progress { return { id: progress?.call_id ?? '', call: progress?.tool_call_id ?? '', name: progress?.name ?? 'tool', title: progress?.title ?? undefined, preview: progress?.preview?.text ?? '' };}
/** An error as one line: the message inside the provider's JSON body when it carries one. */function failureLine(detail: string): string { const body = detail.slice(detail.indexOf('{'), detail.lastIndexOf('}') + 1); // The stream's error quotes the body inside the transport's own words. for (const candidate of [body, body.replaceAll('\\"', '"')]) { try { const parsed = JSON.parse(candidate); const message = parsed?.error?.message ?? parsed?.message; if (typeof message === 'string' && message.trim()) return message.trim(); } catch {} } return detail.trim().split('\n')[0];}
const failureOf = (detail: string): Failure => ({ text: failureLine(detail), detail: detail.trim() });
/** Entries whose text the chat shows as soon as it opens, so their references are read with their page. */const TEXT_KINDS = new Set(['user', 'assistant', 'thinking', 'note', 'compaction', 'shell_command']);
const byPosition = (a: HistoryEntry, b: HistoryEntry) => a.position - b.position;
/** * `added`, sorted and new, joined to `entries` in history order. A page is * older or newer than everything loaded; only a read that raced another lands * in between and needs the whole list sorted. */function joined(entries: HistoryEntry[], added: HistoryEntry[]): HistoryEntry[] { if (!entries.length || added[0].position > entries.at(-1)!.position) return [...entries, ...added]; if (added.at(-1)!.position < entries[0].position) return [...added, ...entries]; return [...entries, ...added].sort(byPosition);}
const at = perEntry((entry: HistoryEntry) => (entry.created_at ? Date.parse(entry.created_at) : 0));
function shellCommandOf(value: unknown): ShellCommand | null { if (!value || typeof value !== 'object') return null; const command = value as Record<string, unknown>; if ( typeof command.id !== 'string' || typeof command.command !== 'string' || !['running', 'completed', 'cancelled', 'interrupted', 'failed'].includes(String(command.status)) || (command.exit_code !== null && typeof command.exit_code !== 'number') || typeof command.output !== 'string' || typeof command.output_bytes !== 'number' || typeof command.truncated !== 'boolean' || (command.error !== null && typeof command.error !== 'string') || (command.history_seq !== null && typeof command.history_seq !== 'number') || (command.delivery !== undefined && !['unknown', 'pending', 'delivered', 'detached'].includes(String(command.delivery))) ) return null; return { ...value as ShellCommand, delivery: command.delivery as ShellCommand['delivery'] ?? 'unknown' };}
/** HTTP admission replies can lag behind completion/ACK events. Neither may undo an acknowledgment. */function mergeShell(previous: ShellCommand, next: ShellCommand): ShellCommand { const stale = next.delivery !== 'detached' && ( previous.delivery === 'detached' || (previous.delivery === 'delivered' && next.delivery !== 'delivered') || (previous.status !== 'running' && next.status === 'running') || (previous.history_seq !== null && next.history_seq === null) || previous.output_bytes > next.output_bytes ); const latest = stale ? previous : next; // Reset/events carry a smaller head than hydrated history; keep the richer preview. const output = previous.output.length > next.output.length ? previous.output : next.output; return latest.output === output ? latest : { ...latest, output };}
function referenced(entry: HistoryEntry): boolean { return entry.content.some((part) => part.kind === 'reference' && !part.reference.field.startsWith('image-'));}
/** What tool results that just arrived made, reading the traces their page only referenced. */async function madeBy(entries: HistoryEntry[]): Promise<Made[]> { const results = entries.filter((entry) => entry.kind === 'tool_result'); const referencing = results.filter((entry) => entry.content.some((part) => part.kind === 'reference' && part.reference.field === 'trace')); const traced = new Map((await hydrateAll(referencing)).map((entry) => [entry.id, entry])); return results.flatMap((entry) => madeIn(traceOf(traced.get(entry.id) ?? entry)));}
/** Replaces an entry's references with the content they name. */export async function hydrate(entry: HistoryEntry): Promise<HistoryEntry> { return (await hydrateAll([entry]))[0];}
/** The batch content route takes at most this many entries a read. */const BATCH = 200;const named = /^\/sessions\/([^/]+)\/history\/([^/?]+)$/;
/** * `hydrate` for many entries, in order: every reference is read through the * batch content route, one walk per session and 200 entries, rather than one * request per entry. A reference the route cannot name is read on its own. */export async function hydrateAll(entries: HistoryEntry[]): Promise<HistoryEntry[]> { const urls = new Set(entries.flatMap((entry) => (referenced(entry) ? entry.content.flatMap((part) => (part.kind === 'reference' && !part.reference.field.startsWith('image-') ? [part.reference.url] : [])) : []))); const bySession = new Map<string, string[]>(); const alone: string[] = []; for (const url of urls) { const match = named.exec(url); if (!match) alone.push(url); else if (bySession.has(match[1])) bySession.get(match[1])!.push(match[2]); else bySession.set(match[1], [match[2]]); } const loaded = new Map<string, Record<string, string>>(); const reads: Promise<void>[] = alone.map(async (url) => void loaded.set(url, await readEntryContent(url))); for (const [session, ids] of bySession) { for (let start = 0; start < ids.length; start += BATCH) { const chunk = ids.slice(start, start + BATCH); reads.push(readContentBatch(session, chunk).then((fields) => { for (const id of chunk) loaded.set(`/sessions/${session}/history/${id}`, fields.get(id) ?? {}); })); } } await Promise.all(reads); return entries.map((entry) => { if (!referenced(entry)) return { ...entry, content_complete: true }; const content = entry.content.map((part): ContentPart => { if (part.kind !== 'reference' || part.reference.field.startsWith('image-')) return part; const { url, field } = part.reference; const raw = loaded.get(url)?.[field] ?? ''; if (field === 'text') return { kind: 'text', text: raw }; if (field === 'trace') return { kind: 'trace', trace: JSON.parse(raw) }; return { kind: 'json', field, value: JSON.parse(raw) }; }); return { ...entry, content, content_complete: true }; });}
export class Transcript { entries = $state.raw<HistoryEntry[]>([]); pending = $state.raw<Pending[]>([]); loading = $state(true); /** Whether the session is busy, so its newest turn is not signed off yet. */ running = $state(false); /** The phase the stream last reported, fresher than the session list's. */ phase = $state<Phase | null>(null); streaming = $state(false); live = $state.raw<Live[]>([]); progress = $state.raw<Progress[]>([]); shellCommands = $state.raw<ShellCommand[]>([]); #stop: (() => void) | null = null; #settle: ReturnType<typeof setTimeout> | undefined; /** Live output ids history has committed, kept until a read that began after their commit succeeds. */ #replacing = new Set<string>(); more = $state(false); error = $state<string | null>(null); /** * Artifacts made or revised since the chat opened, oldest first, so the * chat can open them as they arrive; history read on opening never adds. */ made = $state.raw<Made[]>([]);
/** Why turns failed, by run id: the stream's error, then the failed model call's own record. */ failures = $state.raw<Record<string, Failure>>({}); /** * Whether each run's last model call read so far failed. A later call * clears only a failure a call set: one the stream reported after a call * that succeeded stays. */ #calls = new Map<string, boolean>(); /** The first and last model calls read. */ #requestsFrom = Infinity; #requestsAfter = 0;
/** The newest request's usage, from the stream's snapshot and its usage events; null before the first. */ usage = $state.raw<Usage | null>(null);
#history = $derived(this.#read()); blocks = $derived(this.#keep([...this.#history.blocks, ...this.#tail(this.#history)])); /** Whether mid-turn prose folds into the work around it. */ #collapse = () => false; groups = $derived(this.#keepGroups(group(this.blocks, this.#collapse()))); /** Last time's blocks and groups by key, which `#keep` and `#keepGroups` reuse. */ #shown = new Map<string, Block>(); #shownGroups = new Map<string, Group>(); /** Your newest message, until a reply follows it, so the chat can say whether the model has it. */ receipt = $derived(this.#receipt());
#expanding = new Set<string>(); /** Entries asked to expand since the last read began, and the read that will take them. */ #asked = new Map<string, HistoryEntry>(); #expansion: Promise<void> | null = null; /** The ids `entries` holds, so a page is checked against them without a pass over all of it. */ #ids = new Set<string>(); /** The history read in flight, which a poll during it shares, and whether one asked while it ran. */ #reading: Promise<void> | null = null; #again = false; #shellRefresh: AbortController | undefined;
constructor( readonly sessionId: string, collapse: () => boolean = () => false, ) { this.#collapse = collapse; }
trackShell(command: ShellCommand) { const previous = this.shellCommands.find((item) => item.id === command.id); this.shellCommands = [...this.shellCommands.filter((item) => item.id !== command.id), previous ? mergeShell(previous, command) : command]; }
/** The first page's read, which a poll that starts during it waits for rather than reading the same page. */ #opening: Promise<void> | null = null;
load(): Promise<void> { return (this.#opening ??= this.#load()); }
async #load() { try { const page = await readHistory(this.sessionId); this.#merge(await this.#hydrateText(page.items)); this.more = page.older !== null; this.error = null; } catch (error) { this.error = String((error as Error).message ?? error); } finally { this.loading = false; } this.#readFailures().catch(() => {}); }
async loadOlder() { const first = this.entries[0]; if (!first || !this.more) return; const page = await readHistory(this.sessionId, { before: first.position }); this.#merge(await this.#hydrateText(page.items.filter((entry) => !this.#ids.has(entry.id)))); this.more = page.older !== null; this.#readFailures(true).catch(() => {}); }
/** * Adds the entries the chat does not have yet, in history order, and * returns them. Reads overlap (a poll racing the first load, or a load * after a reconnect), so an entry may arrive twice; a duplicate key would * stop the whole chat from updating. */ #merge(arrived: HistoryEntry[]): HistoryEntry[] { const added = arrived.filter((entry) => !this.#ids.has(entry.id)).sort(byPosition); for (const entry of added) this.#ids.add(entry.id); if (added.length) this.entries = joined(this.entries, added); // Initial hydration may finish after a reset that had no loaded rows yet. if (this.#stop && added.some((entry) => entry.kind === 'shell_command')) void this.#refreshShells(); return added; }
/** * Reads everything after the newest entry, then drops the live output that * committed before the read began. A poll while one runs shares it, and it * reads once more, since what that caller was told committed may have * landed after its request went out. */ poll(): Promise<void> { if (this.#reading) { this.#again = true; return this.#reading; } return (this.#reading = this.#readNewer().finally(() => (this.#reading = null))); }
async #readNewer() { // A read racing the first load may return history from before the chat // opened; only what follows that load counts as arriving. const opened = !this.loading; await this.#opening; do { this.#again = false; const committed = new Set(this.#replacing); for (;;) { const last = this.entries.at(-1); const page = await readHistory(this.sessionId, last ? { after: last.position } : {}); const fresh = page.items.filter((entry) => !this.#ids.has(entry.id)); if (fresh.length) { const hydrated = await this.#hydrateText(fresh); const made = opened ? await madeBy(hydrated) : []; const arrived = this.#merge(hydrated); if (made.length) this.made = [...this.made, ...made]; const answered = new Set(arrived.map((entry) => entry.input_id)); this.pending = this.pending.filter((send) => !answered.has(send.id)); } if (!page.newer || !fresh.length) break; } this.#dropLive(committed); } while (this.#again); }
/** Follows the session's stream: live output as it is written, and history as it commits. */ attach() { this.#stop ??= follow(this.sessionId, (batch) => this.#apply(batch), (connected) => (this.streaming = connected)); }
detach() { this.#stop?.(); this.#stop = null; clearTimeout(this.#settle); this.#shellRefresh?.abort(); }
/** A reset may have missed an ACK for an older, already loaded history row. */ async #refreshShells() { this.#shellRefresh?.abort(); const abort = (this.#shellRefresh = new AbortController()); const pending = new Set(this.entries.flatMap((entry) => { if (entry.kind !== 'shell_command') return []; const part = entry.content.find((part) => part.kind === 'json' && part.field === 'shell_command'); const command = part?.kind === 'json' ? shellCommandOf(part.value) : null; return command?.delivery === 'pending' ? [command.id] : []; })); // Serial reads bound in-flight work even when many idle receipts were loaded. for (const id of pending) { if (abort.signal.aborted) return; try { const command = await getShellCommand(this.sessionId, id, abort.signal); if (abort.signal.aborted) return; this.trackShell(command); } catch { /* Preserve the last observation; the next reconnect or event can refresh it. */ } } }
#apply(batch: Batch) { for (const event of batch.events) { const data = event.data ?? {}; switch (event.type) { case 'reset': { const snapshot = batch.snapshot ?? {}; this.phase = snapshot.status?.phase ?? null; if (snapshot.usage) this.usage = snapshot.usage.observed_at ? snapshot.usage : null; this.live = (snapshot.active_output ?? []).flatMap((output: any) => output.kind === 'text' || output.kind === 'thinking' ? [{ id: output.message_id, kind: output.kind, text: output.text ?? '…' }] : [], ); this.progress = (snapshot.current_progress ?? []).map(progressOf); this.shellCommands = (snapshot.shell_commands ?? []).flatMap((command: unknown) => { const checked = shellCommandOf(command); return checked ? [checked] : []; }); void this.#refreshShells(); this.#commit(null); break; } case 'status': this.phase = data.phase ?? null; if (this.phase === 'idle') this.#commit(null); break; case 'usage': this.usage = data; break; case 'error': if (data.run_id) this.failures = { ...this.failures, [data.run_id]: failureOf(data.message ?? '') }; break; case 'text': case 'thinking': { const at = this.live.findIndex((item) => item.id === data.message_id); if (at < 0) this.live = [...this.live, { id: data.message_id, kind: event.type, text: data.text }]; else this.live = this.live.map((item, index) => (index === at ? { ...item, text: item.text + data.text } : item)); break; } case 'shell_command': { const shell = shellCommandOf(data.shell_command); if (shell) this.trackShell(shell); break; } case 'tool_progress': { const next = progressOf(data.progress); this.progress = [...this.progress.filter((item) => item.id !== next.id), next]; break; } case 'tool': this.progress = this.progress.filter((item) => item.id !== data.progress_call_id); this.#commit(null); break; case 'committed': this.#commit(data.replaces_all_live ? 'all' : (data.replaces_live_ids ?? [])); break; case 'message': case 'note': this.#commit(null); break; } } }
/** * Reads what committed, then drops the live output it replaces, so a reply * never blinks out between its last delta and its history entry. */ #commit(replaces: 'all' | string[] | null) { // Events arrive in bursts (a commit, then its tool, then a status), so // one read serves them all; what each burst replaces adds up. A model // commit retires everything streamed so far and a resting session has // nothing left streaming, but output that starts later is not theirs. const retired = replaces === 'all' || this.phase === 'idle' ? this.live.map((item) => item.id) : (replaces ?? []); for (const id of retired) this.#replacing.add(id); clearTimeout(this.#settle); this.#settle = setTimeout(async () => { // A failed read keeps the live output; the next poll drops it once history has it. try { await this.poll(); } catch { // Idle cleanup is independent of whether durable history is reachable. } if (this.phase === 'idle') { this.progress = []; await this.#readFailures().catch(() => {}); } }, 60); }
/** * Reads which turns failed from the session's model calls since the oldest * loaded entry: a turn whose last call failed. The stream says so as it * happens; this is what a chat opened later has. Reads on from the last * call read, or, for an `older` page, the calls before the first one read. */ async #readFailures(older = false) { const since = this.entries[0]?.created_at; if (this.loading || !since) return; const last = new Map<string, string | null>(); const until = this.#requestsFrom; let after = older ? 0 : this.#requestsAfter; reading: for (;;) { const page = await readRequests(this.sessionId, after, 200, undefined, after ? undefined : Date.parse(since)); for (const request of page.items) { if (older && request.sequence >= until) break reading; if (request.run_id) last.set(request.run_id, request.outcome === 'failed' ? (request.failure?.detail ?? '') : null); this.#requestsFrom = Math.min(this.#requestsFrom, request.sequence); after = request.sequence; } if (!page.next || !page.items.length) break; } if (!older) this.#requestsAfter = Math.max(this.#requestsAfter, after); if (!last.size) return; const failures = { ...this.failures }; for (const [run, detail] of last) { // A later page already read how an older run ended. if (older && this.#calls.has(run)) continue; if (detail !== null) failures[run] = failureOf(detail); else if (this.#calls.get(run)) delete failures[run]; this.#calls.set(run, detail !== null); } this.failures = failures; }
#dropLive(committed: Set<string>) { if (!committed.size) return; for (const id of committed) this.#replacing.delete(id); this.live = this.live.filter((item) => !committed.has(item.id)); }
async send(text: string, images: Attached[] = []) { const continuation = text.trim() === '.' && !images.length; const send: Pending = { id: uuidv7(), text: continuation ? '.' : text, images, at: Date.now(), continuation }; this.pending = [...this.pending, send]; await this.#deliver(send); }
async retry(id: string) { const send = this.pending.find((candidate) => candidate.id === id); if (!send) return; this.pending = this.pending.map((candidate) => (candidate.id === id ? { ...send, error: undefined } : candidate)); await this.#deliver(send); }
discard(id: string) { this.pending = this.pending.filter((send) => send.id !== id); }
/** Removes the sends the daemon cancelled and returns them in the order they were sent. */ take(ids: string[]): { text: string; images: Attached[] }[] { const taken = this.pending.filter((send) => ids.includes(send.id) && !send.continuation); this.pending = this.pending.filter((send) => !ids.includes(send.id)); return taken; }
#receipt(): string | null { for (const block of this.blocks.toReversed()) { if (block.kind === 'assistant' || block.kind === 'failure') return null; if (block.kind === 'user' && !block.from) return block.key; } return null; }
/** Where a turn starts among the loaded entries, for a review of it. */ turnStart(turnId: string): number | null { return this.entries.find((entry) => entry.turn_id === turnId)?.position ?? null; }
/** * Puts tool entries' full arguments and output in place of their * references. Asks made in the same moment, as every work group a page * brings into view makes, share one batched read and one replacement. */ expand(...entries: HistoryEntry[]): Promise<void> { for (const entry of entries) if (!entry.content_complete && !this.#expanding.has(entry.id) && referenced(entry)) this.#asked.set(entry.id, entry); if (!this.#asked.size) return Promise.resolve(); return (this.#expansion ??= new Promise((done) => setTimeout(done)).then(() => this.#expandAsked())); }
async #expandAsked() { const waiting = [...this.#asked.values()]; this.#asked.clear(); this.#expansion = null; for (const entry of waiting) this.#expanding.add(entry.id); try { const full = new Map((await hydrateAll(waiting)).map((entry) => [entry.id, entry])); this.entries = this.entries.map((candidate) => full.get(candidate.id) ?? candidate); } finally { for (const entry of waiting) this.#expanding.delete(entry.id); } }
async #deliver(send: Pending) { try { if (send.continuation) await sendContinue(this.sessionId, send.id); else await sendMessage(this.sessionId, send.id, send.text, send.images.map(({ mime_type, data }) => ({ mime_type, data }))); this.pending = this.pending.map((candidate) => (candidate.id === send.id ? { ...candidate, accepted: true } : candidate)); } catch (error) { const message = String((error as Error).message ?? error); this.pending = this.pending.map((candidate) => (candidate.id === send.id ? { ...candidate, error: message } : candidate)); } }
// Fetch visible messages and bounded shell receipts up front; tool content waits. async #hydrateText(entries: HistoryEntry[]) { const shown = entries.filter((entry) => TEXT_KINDS.has(entry.kind)); const full = new Map((await hydrateAll(shown)).map((entry) => [entry.id, entry])); return entries.map((entry) => full.get(entry.id) ?? entry); }
/** * The blocks history makes, and what the tail after it needs: the turn still * open at its end, who spoke last, and which calls and shell commands * history already shows. Live output changes with every delta, so it stays * out of here: `#tail` adds it without another pass over history. */ #read(): Read { const results = new Set(this.entries.flatMap((entry) => (entry.kind === 'tool_result' && entry.tool ? [entry.tool.tool_call_id] : []))); const blocks: Block[] = []; let turn = null as Turn | null; let previous = 0; let speaker = '';
const liveShells = new Map(this.shellCommands.map((command) => [command.id, command])); for (const entry of this.entries) { // Mid-turn receipts belong to the surrounding turn. Loose idle receipts // still sign it off before shell time starts. if (entry.kind === 'shell_command') { if (!turn || entry.turn_id === null || entry.turn_id !== turn.id) { blocks.push(...this.#ending(turn)); turn = null; } speaker = 'you'; const part = entry.content.find((item) => item.kind === 'json' && item.field === 'shell_command'); const recorded = part?.kind === 'json' ? shellCommandOf(part.value) : null; const live = recorded ? liveShells.get(recorded.id) : undefined; const command = recorded && live ? mergeShell(recorded, live) : recorded; if (command) blocks.push({ kind: 'shell', key: `shell:${command.id}`, command }); if (at(entry)) previous = at(entry); continue; } const text = textOf(entry.content); // An entry outside any turn (a system or scheduled note) shows where it landed but // does not end the turn around it; that turn would sign off twice. const loose = entry.turn_id === null && entry.kind !== 'user'; if (!turn || (entry.turn_id !== turn.id && !loose)) { blocks.push(...this.#ending(turn)); turn = { id: entry.turn_id, from: entry.position, start: at(entry), last: at(entry), tools: 0, answered: false, files: new Set(), added: 0, removed: 0, text: '' }; } turn.last = Math.max(turn.last, at(entry)); switch (entry.kind) { case 'user': { const gap = previous && at(entry) - previous >= AWAY_MS ? formatGap(at(entry) - previous) : null; const from = entry.mail?.sender_label?.toLowerCase() ?? (entry.turn_type && !['user', 'chat'].includes(entry.turn_type) ? entry.turn_type : null); const skill = jsonField(entry, 'skill') as SkillLoad | undefined; blocks.push({ kind: 'user', key: entry.id, text, images: picturesOf(entry), from, gap, at: at(entry), state: 'seen', skill: skill?.name }); speaker = 'you'; break; } case 'assistant': if (!text.trim()) break; blocks.push({ kind: 'assistant', key: entry.id, text, plate: speaker !== 'albedo', phase: entry.phase ?? null }); speaker = 'albedo'; turn.answered = true; turn.text = text; break; case 'thinking': if (text.trim()) blocks.push({ kind: 'thinking', key: entry.id, text, ms: entry.thinking_duration_ms ?? null }); break; case 'tool_call': // A call shows until its result replaces it. if (entry.tool && !results.has(entry.tool.tool_call_id)) blocks.push({ kind: 'tool', key: entry.id, name: entry.tool.name, entry, done: false, failed: false }); break; case 'tool_result': if (!entry.tool) break; turn.tools++; for (const change of traceOf(entry)?.changes ?? []) { turn.files.add(change.path); if (change.kind === 'diff') { turn.added += change.added; turn.removed += change.removed; } } blocks.push({ kind: 'tool', key: entry.id, name: entry.tool.name, entry, done: true, trace: traceOf(entry), failed: failedTool(entry) }); break; case 'note': case 'image_fit': if (text.trim()) blocks.push({ kind: 'note', key: entry.id, text }); break; case 'compaction': blocks.push({ kind: 'compaction', key: entry.id, text }); break; } if (at(entry)) previous = at(entry); } const called = new Set(this.entries.flatMap((entry) => (entry.kind === 'tool_call' && entry.tool ? [entry.tool.tool_call_id] : []))); const durable = new Set(blocks.flatMap((block) => (block.kind === 'shell' ? [block.command.id] : []))); return { blocks, turn, speaker, called, durable }; }
/** A turn's sign-off, once the next one starts or the session rests: its failure, then a face. */ #ending(turn: Turn | null): Block[] { const id = turn?.id; const failed = id ? this.failures[id] : undefined; const ending: Block[] = failed ? [{ kind: 'failure', key: `failure:${id}`, ...failed }] : []; if (!turn || (!turn.answered && !turn.tools)) return ending; const elapsedMs = Math.max(0, turn.last - turn.start); const changed = { files: turn.files.size, added: turn.added, removed: turn.removed }; ending.push({ kind: 'end', key: `end:${turn.id}:${turn.from}`, turnId: turn.id, from: turn.from, mood: outcome(false, false, elapsedMs), seed: turn.last, elapsedMs, tools: turn.tools, text: turn.text, changed }); return ending; }
/** What follows history: the open turn's sign-off, live output, running calls and shell commands, and your sends. */ #tail({ turn, speaker, called, durable }: Read): Block[] { const blocks: Block[] = []; // Text still live has not committed yet: signing off now would put the // sign-off above the answer, timed without it. if (!this.running && !this.live.some((item) => item.text.trim())) blocks.push(...this.#ending(turn)); for (const item of this.live) { if (!item.text.trim()) continue; if (item.kind === 'thinking') blocks.push({ kind: 'thinking', key: `live:${item.id}`, text: item.text, ms: null }); else blocks.push({ kind: 'assistant', key: `live:${item.id}`, text: item.text, plate: speaker !== 'albedo', phase: null }); } // A call whose entry has committed already shows as that entry. for (const item of this.progress) { if (!called.has(item.call)) blocks.push({ kind: 'progress', key: `progress:${item.id}`, name: item.name, title: item.title, preview: item.preview }); } for (const command of this.shellCommands) if (!durable.has(command.id)) blocks.push({ kind: 'shell', key: `shell:${command.id}`, command }); for (const send of this.pending) { if (send.continuation && !send.error) continue; const images = send.images.map((image) => ({ src: image.preview })); blocks.push({ kind: 'user', key: `pending:${send.id}`, text: send.text, images, from: null, gap: null, at: send.at, state: send.error ? 'failed' : send.accepted ? 'sent' : 'sending', error: send.error }); } return blocks; }
/** * `blocks` with every one equal to last time's block of its key replaced by * that block, so the chat's keyed rows see the same object and redraw * nothing: a fresh object would re-run each row's template, timestamps and * Markdown included, on every page and every delta. */ #keep(blocks: Block[]): Block[] { const shown = new Map<string, Block>(); const kept = blocks.map((block) => { const earlier = this.#shown.get(block.key); const same = earlier && alike(earlier, block) ? earlier : block; shown.set(block.key, same); return same; }); this.#shown = shown; return kept; }
/** `#keep` for groups: a work group whose steps are all the same objects stays the same group. */ #keepGroups(groups: Group[]): Group[] { const shown = new Map<string, Group>(); const kept = groups.map((group) => { const earlier = this.#shownGroups.get(group.key); const same = group.kind === 'work' && earlier?.kind === 'work' && earlier.steps.length === group.steps.length && earlier.steps.every((step, index) => step === group.steps[index]) ? earlier : group; shown.set(group.key, same); return same; }); this.#shownGroups = shown; return kept; }}
function group(blocks: Block[], collapse: boolean): Group[] { const answers = new Set<string>(); if (collapse) { // A row the daemon labelled final stays out of its work stretch and one // labelled commentary folds. An unlabelled row (older, or still streaming) // stays out when it is a turn's last prose: its answer, or what a running // turn is writing now, until thinking or a tool call follows it. let ended = true; for (const block of blocks.toReversed()) { if (block.kind === 'end') ended = true; else if (block.kind === 'assistant') { if (block.phase === 'final' || (block.phase === null && ended)) answers.add(block.key); ended = false; } else if (block.kind === 'user' || block.kind === 'thinking' || block.kind === 'tool' || block.kind === 'progress') ended = false; } } const groups: Group[] = []; for (const block of blocks) { const last = groups.at(-1); if (block.kind === 'thinking' || block.kind === 'tool' || block.kind === 'progress' || (collapse && block.kind === 'assistant' && !answers.has(block.key))) { if (last?.kind === 'work') last.steps.push(block); else groups.push({ kind: 'work', key: last ? `work:${last.key}` : 'work:root', steps: [block] }); } else groups.push(block); } return groups;}