import { ApiError, getShellCommand, readShellOutput, type ShellCommand } from './api'; // A canvas view reads an existing human command; it never admits one. Keep // a small live tail, or one page of older output, independently of the chat. const PAGE = 65_536; const KEEP = 400_000; const POLL = 700; const RETRY = 3000; const bytes = (text: string) => new TextEncoder().encode(text).length; export class ShellOutput { command = $state(null); text = $state(''); start = $state(0); end = $state(0); following = $state(true); loading = $state(false); problem = $state(null); #active = false; #initial = true; #timer: ReturnType | undefined; #abort: AbortController | undefined; constructor(readonly sessionId: string, readonly commandId: string) {} #visibility = () => { clearTimeout(this.#timer); if (document.hidden) { this.#abort?.abort(); this.loading = false; } else void this.#read(); }; watch() { if (this.#active) return; this.#active = true; document.addEventListener('visibilitychange', this.#visibility); void this.#read(); } dispose() { this.#active = false; document.removeEventListener('visibilitychange', this.#visibility); clearTimeout(this.#timer); this.#abort?.abort(); } refresh() { void this.#read(); } first() { void this.#read({ page: 0 }); } previous() { void this.#read({ page: Math.max(0, this.start - PAGE), before: this.start }); } next() { void this.#read({ page: this.end }); } latest() { void this.#read({ latest: true }); } // The API requires offsets on codepoint boundaries. An arbitrary tail or // previous-page offset can hit a continuation byte: at most three advances // find the next boundary, without reading the preceding log. async #page(offset: number, abort: AbortController, before?: number) { for (let step = 0; ; step++, offset++) { try { const limit = before === undefined ? PAGE : Math.max(4, Math.min(PAGE, before - offset)); const page = await readShellOutput(this.sessionId, this.commandId, offset, abort.signal, limit); return { start: offset, end: offset + bytes(page.text), text: page.text }; } catch (error) { if (abort.signal.aborted || step === 3 || !(error instanceof ApiError) || error.code !== 'invalid_shell_output_range') throw error; } } } async #read(wanted: { latest?: boolean; page?: number; before?: number } = {}) { if (!this.#active) return; clearTimeout(this.#timer); this.#abort?.abort(); if (document.hidden && wanted.page === undefined && !wanted.latest) { this.loading = false; return; } const abort = (this.#abort = new AbortController()); const current = () => this.#active && this.#abort === abort && !abort.signal.aborted; if (wanted.latest) this.following = true; else if (wanted.page !== undefined) this.following = false; this.loading = true; let retry = false; let missing = false; try { const command = await getShellCommand(this.sessionId, this.commandId, abort.signal); if (!current()) return; this.command = command; this.problem = null; const jump = wanted.latest || this.#initial || command.output_bytes - this.end > KEEP; if (wanted.page !== undefined || (this.following && (jump || command.output_bytes > this.end))) { const offset = wanted.page ?? (jump ? Math.max(0, command.output_bytes - PAGE) : this.end); const page = await this.#page(offset, abort, wanted.before); if (!current()) return; if (wanted.page !== undefined || jump) { this.start = page.start; this.text = page.text; } else { const text = this.text + page.text; let dropped = Math.max(0, text.length - KEEP); if (dropped && /[\uDC00-\uDFFF]/.test(text[dropped])) dropped++; this.start += bytes(text.slice(0, dropped)); this.text = text.slice(dropped); } this.end = page.end; } this.#initial = false; } catch (error) { if (!current()) return; missing = error instanceof ApiError && error.status === 404; this.problem = missing ? 'This command or its session is no longer available.' : String((error as Error).message ?? error); retry = !missing; } finally { if (current()) { this.loading = false; const behind = this.following && !!this.command && this.end < this.command.output_bytes; if (!missing && !document.hidden && (retry || this.#initial || this.command?.status === 'running' || behind)) { this.#timer = setTimeout(() => void this.#read(), retry ? RETRY : behind ? 0 : POLL); } } } } }