diff --git a/robot-docs/web.md b/robot-docs/web.md index 5a9bc6fa0..97626f029 100644 --- a/robot-docs/web.md +++ b/robot-docs/web.md @@ -26,7 +26,7 @@ Background alerts (`attention.ts`, `notifications.svelte.ts`, `sessions.svelte.t Returning to the tab (focus or becoming visible) clears the count and closes its system notifications. The settings switch asks for Notification permission only on a click and saves its opt-in in this browser, off by default. Denial, unavailable APIs and notification construction failures leave tab counts working. System notifications appear only while hidden, once per unread session, contain the session name and event kind (not message contents), and focus the tab and reveal its chat on click, reusing an open board before adding a window. Hidden tabs keep only the collection follow, including SSE fallback; chat/history reads still pause. If that follow is offline, the list is retried every 30 seconds. Browsers may suspend background tabs, so these are best-effort alerts, not push notifications. -A human composer line beginning with `!` submits the trimmed remainder as a command to the daemon shell-command resource; it is not sent as a model prompt. The web client never runs a local subprocess. The shell entry (`chat/ShellCommand.svelte`) is a dedicated, card-free transcript block marked “you · shell”, not a tool call: a quiet left margin mark keeps the command, compact status and output together. Shell outcomes sit after the model turn’s sign-off and do not extend its elapsed time. Its preview is bounded to five logical lines, 4096 characters and five visible rows, so a single minified line cannot fill the chat; expand opens a keyboard-scrollable output area, with explicit UTF-8 byte paging and retention-limit notices. Command and loaded-output copy controls use the shared clipboard helper; partial captures say “Copy loaded” and show loaded versus retained bytes rather than implying the entire capture was copied. An admitted command reveals the latest output like an ordinary send; a failed admission leaves the composer draft and scroll position intact. Before the first request, the client synchronously persists the session, UUIDv7 and immutable command in browser localStorage; a retry, including after a reload, reads that same command id first and only resubmits it after an authoritative 404. The record is removed only after an authoritative result. Corrupt or unavailable storage refuses execution rather than risking a duplicate side effect. Referenced shell history content is hydrated when loading a transcript, so large receipts remain visible after a reload without eagerly fetching the full retained output. Stream/reset records update the transient entry; the committed `shell_command` history entry replaces it by command id, so reconnects do not duplicate entries. Output is rendered as text, never interpreted as terminal escapes or markup. +A human composer line beginning with `!` submits the trimmed remainder as a command to the daemon shell-command resource; it is not sent as a model prompt. The web client never runs a local subprocess. The shell entry (`chat/ShellCommand.svelte`) is a dedicated, card-free transcript block marked “you · shell”, not a tool call: a quiet left margin mark keeps the command, compact status and output together. Shell outcomes sit after the model turn’s sign-off and do not extend its elapsed time. Its preview is bounded to five logical lines, 4096 characters and five visible rows, so a single minified line cannot fill the chat; expand opens a keyboard-scrollable output area, with explicit UTF-8 byte paging and retention-limit notices. Command and loaded-output copy controls use the shared clipboard helper; partial captures say “Copy loaded” and show loaded versus retained bytes rather than implying the entire capture was copied. An admitted command reveals the latest output like an ordinary send; a failed admission leaves the composer draft and scroll position intact. Before the first request, the client synchronously persists the session, UUIDv7 and immutable command in browser localStorage; a retry, including after a reload, reads that same command id first and only resubmits it after an authoritative 404. The record is removed only after an authoritative result. Corrupt or unavailable storage refuses execution rather than risking a duplicate side effect. Referenced shell history content is hydrated when loading a transcript, so large receipts remain visible after a reload without eagerly fetching the full retained output. Stream/reset records update the transient entry; the committed `shell_command` history entry replaces it by command id, so reconnects do not duplicate entries. Output is rendered as text, never interpreted as terminal escapes or markup. “Open command on canvas” keeps the receipt in the transcript and opens a tethered `command` window beside its chat (`nodes/ShellCommandNode.svelte`, `views/ShellCommandView.svelte`, `shell-commands.svelte.ts`). Its saved board record contains only the session/command ids and layout metadata, never output; opening it again focuses the same window. It uses the ordinary layout, focus and browser pop-out/back machinery. The viewer reads the existing resource, follows its latest output every 700 ms while running, and keeps at most 400,000 UTF-16 units; large backlogs jump to the last 64 KiB rather than replaying the entire capture. Read from start, previous/next UTF-8 pages, and follow latest let the reader visit the retained log without loading it all. Arbitrary tail offsets advance at most three bytes to find a codepoint boundary. Copy explicitly means the loaded portion when partial; byte ranges and capture-limit notices say what is missing. Hidden tabs pause requests and timers until visibility resumes. Closing a viewer aborts reads but never stops or executes the command; only Stop requests cancellation. Missing/deleted commands show an error. On a phone it opens in the chat dock, and in zen chat on the desk. Words: a **board** is a named canvas of panels, and the open boards are the tabs along the top (`boards.svelte.ts`). A board holds sessions from any folders. **Workspace** keeps its albedo meaning, a session's folder, and the sidebar shows each session's folder under its name. Its sections are headed as the terminal heads them, the label in the text colour, its count faint, then a thin rule to the edge (the one place lines separate, as `sectionRule` does in the TUI); its rows alternate as the phone's list does, every other row in a section on `--rail-stripe` (the phone's step from its ground, taken from the rail's, about 1.06:1), hover lays a step over a row's own tone, and a session open on the board sits on half of `--open-tint`, the session of the selected window on all of it (the rail with a flat step of the accent, 12% in light, 18% in dark), opaque so the stripes don't show through: a hue over the stripes' tones, under hover's step, and open rows that meet square their corners so a run of them reads as one block. A click on an open session's row selects its window and shows it (its tab, the canvas panned to it, `board.focus`), and the window's frame pulses once. A row's time is the session's `activity_at`; a live `activity` event moves it only while a turn is in hand, since its `observed_at` also moves when nothing but a kernel starting for an opened window happened. `[` (shown on the sidebar's toggle, as search shows ⌘K; those key chips sit a 12% step of ink above their button) hides or shows the sidebar; hidden, it pops out floating over the canvas, without animation, as soon as the pointer is within 20 px of the canvas's edge on its side, or further out the faster it is heading there (15 px more per px/ms, up to 50 px), so a flick toward the edge opens it early (`App.svelte`, watched from the canvas so the edge still pans). It stays while the pointer is on it or within 48 px of it, the top bar above it included, or while its filter has focus, and goes 100 ms after the pointer is clearly elsewhere or leaves the page; `/` brings it out the same way with the filter focused (Escape clears it and puts it away), and only focuses the filter when the sidebar is shown. `+` or B makes a new board; double-click or F2 renames one; closing a tab (⇧W) keeps the board, which the palette reopens (`Open board: `); `Delete board` removes it. The last tab cannot be closed, so there is always a canvas. diff --git a/test.sh b/test.sh index 5e29ff953..cb1ee58ff 100755 --- a/test.sh +++ b/test.sh @@ -99,7 +99,7 @@ changed() { suite "gleam test" gleam test suite "python harness" python3 test/python_test_runner.py --jobs "$ALBEDO_TEST_HARNESS_JOBS" test/harness/*_test.py suite "go test" go -C cli test ./internal/... ./cmd/... -suite "web client" node --test web/scripts/commands.test.mjs web/scripts/transcript.test.mjs web/scripts/context.test.mjs +suite "web client" node --test web/scripts/commands.test.mjs web/scripts/transcript.test.mjs web/scripts/context.test.mjs web/scripts/shell-output.test.mjs # the Go e2e suite builds its own CLI and boots a hermetic daemon, so it must # never reuse a cached run. Bound parallel scenarios while the other suites run. go_parallel="$ALBEDO_TEST_GO_JOBS" diff --git a/web/scripts/shell-output.test.mjs b/web/scripts/shell-output.test.mjs new file mode 100644 index 000000000..4404546f5 --- /dev/null +++ b/web/scripts/shell-output.test.mjs @@ -0,0 +1,186 @@ +// A daemon E2E cannot observe the web client's byte cursor, retry policy, or polling lifetime. +// Compile the real resource and stub only HTTP transport and document visibility. +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { stripTypeScriptTypes } from 'node:module'; +import test from 'node:test'; +import { compileModule } from 'svelte/compiler'; + +const moduleURL = (code) => `data:text/javascript;base64,${Buffer.from(code).toString('base64')}`; +const apiURL = moduleURL(` + const requests = { metadata: [], output: [], metadataQueue: [], outputQueue: [], command: null, bytes: Buffer.alloc(0) }; + export class ApiError extends Error { constructor(code, status = 400) { super(code); this.code = code; this.status = status; } } + export function reset(command, output) { requests.metadata = []; requests.output = []; requests.metadataQueue = []; requests.outputQueue = []; requests.command = command; requests.bytes = Buffer.from(output); } + export async function getShellCommand(session, id, signal) { requests.metadata.push({ session, id, signal }); if (requests.metadataQueue.length) return requests.metadataQueue.shift()(); if (signal.aborted) throw new DOMException('aborted', 'AbortError'); return requests.command; } + export async function readShellOutput(session, id, offset, signal, limit) { + requests.output.push({ session, id, offset, limit, signal }); + if (requests.outputQueue.length) return requests.outputQueue.shift()({ session, id, offset, limit, signal }); + if (signal.aborted) throw new DOMException('aborted', 'AbortError'); + if (offset > requests.bytes.length || (offset < requests.bytes.length && (requests.bytes[offset] & 0xc0) === 0x80)) throw new ApiError('invalid_shell_output_range'); + let end = Math.min(requests.bytes.length, offset + limit); + while (end < requests.bytes.length && (requests.bytes[end] & 0xc0) === 0x80) end--; + const data = requests.bytes.subarray(offset, end); + return { text: data.toString('utf8'), output_bytes: requests.bytes.length }; + } + export { requests }; +`); +const api = await import(apiURL); +const source = await readFile(new URL('../src/lib/shell-commands.svelte.ts', import.meta.url), 'utf8'); +let code = compileModule(stripTypeScriptTypes(source, { mode: 'transform' }), { filename: 'shell-commands.svelte.js', generate: 'client' }).js.code; +code = code.replace(/from (['"])(.*?)\1/g, (_, _quote, path) => `from ${JSON.stringify(path === './api' ? apiURL : import.meta.resolve(path))}`); +const { ShellOutput } = await import(moduleURL(code)); +const visibilityListeners = new Set(); +globalThis.document = { + hidden: false, + addEventListener(type, listener) { if (type === 'visibilitychange') visibilityListeners.add(listener); }, + removeEventListener(type, listener) { if (type === 'visibilitychange') visibilityListeners.delete(listener); }, +}; +function visibility(hidden) { + document.hidden = hidden; + for (const listener of [...visibilityListeners]) listener(); +} + +const timers = new Map(); +let timerId = 0; +const realSetTimeout = globalThis.setTimeout; +const realClearTimeout = globalThis.clearTimeout; +function fakeTimers() { + globalThis.setTimeout = (fn, delay) => { const id = ++timerId; timers.set(id, { fn, delay }); return id; }; + globalThis.clearTimeout = (id) => timers.delete(id); + return () => { globalThis.setTimeout = realSetTimeout; globalThis.clearTimeout = realClearTimeout; timers.clear(); }; +} +async function settle() { for (let i = 0; i < 12; i++) await new Promise((resolve) => setImmediate(resolve)); } +function metadata(output, status = 'completed') { return { id: 'cmd', command: 'printf output', status, output_bytes: Buffer.byteLength(output), exit_code: status === 'completed' ? 0 : null, error: null }; } + +// The assertions need to see requests made with exact offsets, including cursor repairs. +test('initial tail advances off a UTF-8 continuation byte and exposes exact byte range', async () => { + const restore = fakeTimers(); + try { + const output = 'x'.repeat(10) + '🌿' + 't'.repeat(65_533); + api.requests.command = metadata(output); + api.requests.bytes = Buffer.from(output); + const view = new ShellOutput('session', 'cmd'); + view.watch(); await settle(); + assert.equal(view.text, 't'.repeat(65_533)); + assert.equal(view.start, Buffer.byteLength(output) - Buffer.byteLength(view.text)); + assert.equal(view.end, Buffer.byteLength(output)); + assert.equal(timers.size, 0, 'completed command output must not keep polling'); + assert.deepEqual(api.requests.output.map((r) => r.offset), [11, 12, 13, 14]); + view.dispose(); + } finally { restore(); } +}); + +test('first, next, previous and latest use byte cursors without gaps', async () => { + const restore = fakeTimers(); + try { + const output = 'a'.repeat(140_000); + api.reset(metadata(output), output); + const view = new ShellOutput('session', 'cmd'); view.watch(); await settle(); + assert.equal(view.start, 74_464); + view.first(); await settle(); assert.equal(view.start, 0); assert.equal(view.end, 65_536); + view.next(); await settle(); assert.equal(view.start, 65_536); assert.equal(view.end, 131_072); + assert.equal(view.text.length, 65_536); + view.previous(); await settle(); assert.equal(view.start, 0); assert.equal(view.end, 65_536); assert.equal(view.text.length, 65_536); + view.latest(); await settle(); assert.equal(view.text, output.slice(-65_536)); assert.equal(view.end, output.length); + view.dispose(); + } finally { restore(); } +}); + +test('following drains growth beyond one page and caps text without splitting surrogate pairs', async () => { + const restore = fakeTimers(); + try { + let output = 'x'.repeat(70_000); + api.reset(metadata(output, 'running'), output); + const view = new ShellOutput('session', 'cmd'); view.watch(); await settle(); + // Each 320k-byte increment stays below KEEP, so the resource must append + // pages rather than jump straight to the latest tail. + for (let batch = 0; batch < 3; batch++) { + output += '🌿'.repeat(80_000); + api.requests.bytes = Buffer.from(output); api.requests.command = metadata(output, 'running'); + for (let i = 0; i < 8 && view.end < Buffer.byteLength(output); i++) { + const scheduled = [...timers.entries()].find(([, timer]) => timer.delay === 0); + if (scheduled) { timers.delete(scheduled[0]); scheduled[1].fn(); } else view.refresh(); + await settle(); + } + assert.equal(view.end, Buffer.byteLength(output), `batch ${batch} must drain all appended pages`); + } + const suffix = '🌿'.repeat(200_000); + assert.equal(view.text, suffix); + assert.equal(view.text.length, 400_000); + assert.ok(view.start > 0); + assert.equal(view.start, Buffer.byteLength(output) - Buffer.byteLength(suffix)); + assert.ok(!view.text.includes('�')); + assert.ok(!/[\uD800-\uDBFF]$/.test(view.text)); + view.dispose(); + } finally { restore(); } +}); + +test('disposed in-flight reads abort and ignore late transport results', async () => { + const restore = fakeTimers(); + try { + api.reset(metadata('hello'), 'hello'); + let finish; + api.requests.metadataQueue.push(() => new Promise((resolve) => { finish = resolve; })); + const view = new ShellOutput('session', 'cmd'); view.watch(); await settle(); + const signal = api.requests.metadata[0].signal; + view.dispose(); finish(metadata('late')); await settle(); + assert.equal(signal.aborted, true); assert.equal(view.command, null); assert.equal(view.loading, true); + assert.equal(timers.size, 0); + } finally { restore(); } +}); + +test('404 is terminal while transient errors retry after the documented delay', async () => { + const restore = fakeTimers(); + try { + api.reset(metadata(''), ''); + api.requests.metadataQueue.push(() => { throw new api.ApiError('not_found', 404); }); + const missing = new ShellOutput('session', 'cmd'); missing.watch(); await settle(); + assert.match(missing.problem, /no longer available/); assert.equal(timers.size, 0); missing.dispose(); + + api.reset(metadata('ok'), 'ok'); + api.requests.metadataQueue.push(() => { throw new Error('temporary network failure'); }); + const transient = new ShellOutput('session', 'cmd'); transient.watch(); await settle(); + assert.equal(timers.size, 1); assert.equal([...timers.values()][0].delay, 3000); + transient.dispose(); + } finally { restore(); } +}); + + +test('hidden watchers pause, resume on visibility, and detach on dispose', async () => { + const restore = fakeTimers(); + try { + api.reset(metadata('first', 'running'), 'first'); + document.hidden = true; + const view = new ShellOutput('session', 'cmd'); + view.watch(); await settle(); + assert.equal(api.requests.metadata.length, 0, 'initially hidden watcher must not fetch metadata'); + assert.equal(timers.size, 0); + assert.equal(view.loading, false); + + visibility(false); await settle(); + assert.equal(api.requests.metadata.length, 1); + assert.equal(view.text, 'first'); + assert.equal(timers.size, 1); + const reads = api.requests.metadata.length; + + api.requests.command = metadata('first plus later output', 'running'); + api.requests.bytes = Buffer.from('first plus later output'); + visibility(true); + assert.equal(timers.size, 0, 'hide clears scheduled polling'); + assert.equal(view.loading, false); + assert.equal(api.requests.metadata.length, reads, 'hide does not issue metadata requests'); + + visibility(false); await settle(); + assert.equal(api.requests.metadata.length, reads + 1, 'visible resumes with fresh metadata'); + assert.equal(view.text, 'first plus later output'); + assert.equal(view.end, Buffer.byteLength('first plus later output')); + assert.equal(timers.size, 1); + + const beforeDispose = api.requests.metadata.length; + view.dispose(); + assert.equal(visibilityListeners.size, 0, 'dispose removes the visibility listener'); + visibility(true); visibility(false); await settle(); + assert.equal(api.requests.metadata.length, beforeDispose, 'disposed view ignores future visibility events'); + assert.equal(timers.size, 0); + } finally { document.hidden = false; restore(); } +}); diff --git a/web/src/lib/FocusChat.svelte b/web/src/lib/FocusChat.svelte index 09c4ab75c..c69a6b7fe 100644 --- a/web/src/lib/FocusChat.svelte +++ b/web/src/lib/FocusChat.svelte @@ -15,6 +15,7 @@ import PtyView from './views/PtyView.svelte'; import ReviewView from './views/ReviewView.svelte'; import TerminalView from './views/TerminalView.svelte'; + import ShellCommandView from './views/ShellCommandView.svelte'; // A session opened full-screen from the rail: zen mode. The chat is the one // thing fully lit; the header and the composer's chips rest dim until @@ -50,6 +51,7 @@ function keyOf(tab: Panel): string { if (tab.kind === 'artifact') return `artifact:${tab.id}`; if (tab.kind === 'job') return `job:${tab.job}`; + if (tab.kind === 'command') return `command:${tab.commandId}`; if (tab.kind === 'review') return `review:${tab.turnId}`; return 'terminal'; } @@ -81,6 +83,7 @@ function label(tab: Panel): string { if (tab.kind === 'artifact') return tab.title; if (tab.kind === 'job') return commands[tab.job] ? headline(commands[tab.job]) : 'job output'; + if (tab.kind === 'command') return commands[tab.commandId] ? headline(commands[tab.commandId]) : 'shell command'; if (tab.kind === 'review') return 'changes'; return session ? place(session.workspace) : 'shell'; } @@ -188,6 +191,9 @@ {:else if panel.kind === 'job'} {@const job = panel.job} {#key job} (commands[job] = found.command)} />{/key} + {:else if panel.kind === 'command'} + {@const id = panel.commandId} + {#key id} (commands[id] = found.command)} />{/key} {:else if panel.kind === 'review'}
{#key panel.turnId} diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index de811312a..67c061cc0 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -197,16 +197,16 @@ export async function submitShellCommand(sessionId: string, id: string, command: return request<{ shell_command: ShellCommand }>('PUT', `/sessions/${sessionId}/shell-commands/${id}`, { body: { command } }).then((value) => value.shell_command); } -export async function getShellCommand(sessionId: string, id: string): Promise { - return get<{ shell_command: ShellCommand }>(`/sessions/${sessionId}/shell-commands/${id}`).then((value) => value.shell_command); +export async function getShellCommand(sessionId: string, id: string, signal?: AbortSignal): Promise { + return get<{ shell_command: ShellCommand }>(`/sessions/${sessionId}/shell-commands/${id}`, signal).then((value) => value.shell_command); } export async function stopShellCommand(sessionId: string, id: string): Promise { return request<{ shell_command: ShellCommand }>('POST', `/sessions/${sessionId}/shell-commands/${id}/stop`).then((value) => value.shell_command); } -export async function readShellOutput(sessionId: string, id: string, offset: number): Promise<{ text: string; next_offset: number | null }> { - return get(`/sessions/${sessionId}/shell-commands/${id}/output?offset=${offset}&limit=65536`); +export async function readShellOutput(sessionId: string, id: string, offset: number, signal?: AbortSignal, limit = 65536): Promise<{ text: string; next_offset: number | null }> { + return get(`/sessions/${sessionId}/shell-commands/${id}/output?offset=${offset}&limit=${limit}`, signal); } export type Job = components['schemas']['JobRecord']; diff --git a/web/src/lib/board.svelte.ts b/web/src/lib/board.svelte.ts index c172c52e9..7766cd02e 100644 --- a/web/src/lib/board.svelte.ts +++ b/web/src/lib/board.svelte.ts @@ -66,6 +66,8 @@ export type SessionWindow = Of<'session', { sessionId: string; parent?: string; export type ReviewWindow = Of<'review', { sessionId: string; turnId: string; from: number; parent?: string; jump?: { path: string; at: number }; zoom?: number }>; /** A background job's output, following the job; `job` is its id in the session's kernel. */ export type TerminalWindow = Of<'terminal', { sessionId: string; job: string; parent?: string; zoom?: number }>; +/** Read-only output from one shell command, addressed by its session resource id. */ +export type ShellCommandWindow = Of<'command', { sessionId: string; commandId: string; parent?: string; zoom?: number }>; /** An interactive pseudo-terminal window running a live shell session. */ export type PtyWindow = Of<'pty', { terminalId: string; sessionId?: string; cwd?: string; title?: string; parent?: string; zoom?: number }>; /** @@ -104,7 +106,7 @@ export type Target = * its own button. */ export type NoteWindow = Of<'note', { text: string; target?: Target; sent?: boolean; alone?: boolean; zoom?: number }>; -export type Window = SessionWindow | ReviewWindow | TerminalWindow | TraceWindow | AgentsWindow | ArtifactWindow | ChipWindow | NoteWindow | PtyWindow; +export type Window = SessionWindow | ReviewWindow | TerminalWindow | ShellCommandWindow | TraceWindow | AgentsWindow | ArtifactWindow | ChipWindow | NoteWindow | PtyWindow; export type WindowType = Window['type']; type DataOf = Extract['data']; export type Place = 'canvas' | 'float' | 'tab' | 'group' | 'tile'; @@ -646,6 +648,11 @@ export class Board { this.#open({ id: `terminal:${sessionId}:${job}`, type: 'terminal', data: { sessionId, job, parent } }, 640); } + /** Opens one shell command's read-only output beside its originating window. */ + openShellCommand(sessionId: string, commandId: string, parent?: string) { + this.#open({ id: `command:${sessionId}:${commandId}`, type: 'command', data: { sessionId, commandId, parent } }, 640); + } + /** Opens an interactive terminal window with a live shell. */ openPty(options: { terminalId?: string; sessionId?: string; cwd?: string; title?: string; parent?: string } = {}) { const terminalId = options.terminalId ?? uuidv7(); @@ -1057,7 +1064,7 @@ export class Board { /** Opens a window asked for from a popped-out window's page, as the board would open it. */ adopt(window: Exclude) { - const widths: Partial> = { artifact: ARTIFACT.width, trace: TRACE.width, agents: AGENTS.width, review: 640, terminal: 640, pty: 640 }; + const widths: Partial> = { artifact: ARTIFACT.width, trace: TRACE.width, agents: AGENTS.width, review: 640, terminal: 640, command: 640, pty: 640 }; this.#open(window, widths[window.type] ?? sizeOf(window.type).width); } diff --git a/web/src/lib/chat/Chat.svelte b/web/src/lib/chat/Chat.svelte index 67f45a835..4539cd02e 100644 --- a/web/src/lib/chat/Chat.svelte +++ b/web/src/lib/chat/Chat.svelte @@ -62,6 +62,7 @@ import { pendingShell, resolveShell } from './shellAttempts'; import ReviewView from '../views/ReviewView.svelte'; import TerminalView from '../views/TerminalView.svelte'; + import ShellCommandView from '../views/ShellCommandView.svelte'; import ArtifactsButton from '../ArtifactsButton.svelte'; import SkillsButton from '../SkillsButton.svelte'; import JobsButton from '../JobsButton.svelte'; @@ -105,12 +106,19 @@ let shown = $state<{ at: string; turnId: string; from: number; jump?: { path: string; at: number } } | null>(null); /** A job's output opened inside the phone's chat, where there is no canvas to put a window on. */ let terminal = $state<{ job: string; command: string } | null>(null); + /** Human command output opened in the phone's dock; its process outlives the view. */ + let commandPanel = $state(null); + function openShellCommand(commandId: string) { + if (!inline) boards.board?.openShellCommand(sessionId, commandId, windowId); + else if (onopen) onopen({ kind: 'command', commandId }); + else { terminal = null; artifact = null; commandPanel = commandId; } + } /** An artifact opened inside the phone's chat. */ let artifact = $state(null); function openArtifact(made: Made) { if (onopen) onopen({ kind: 'artifact', ...made }); - else if (inline) artifact = made; + else if (inline) { commandPanel = null; artifact = made; } else boards.board?.openArtifact(made.id, sessionId, made.version, windowId); } @@ -488,9 +496,9 @@

{session?.name || 'untitled session'}

{#if session}{/if} - (artifact = { id: found.id, version: found.version, title: found.title })} /> + openArtifact({ id: found.id, version: found.version, title: found.title })} /> - (terminal = { job, command: '' })} /> + { commandPanel = null; terminal = { job, command: '' }; }} /> {/if} @@ -563,7 +571,7 @@
{:else if group.kind === 'shell'} - + openShellCommand(group.command.id)} openLabel={inline ? 'Open command output' : 'Open command on canvas'} /> {:else if group.kind === 'work'} step.kind === 'progress' || step.key.startsWith('live:') || (step.kind === 'tool' && !step.done)))} {transcript} session={view} onreview={(turnId, from, path) => review(group.key, turnId, from, path)} onartifact={openArtifact} /> {:else if group.kind === 'end'} @@ -652,6 +660,12 @@ {/key} {/if} + {#if commandPanel} +
+
shell command output
+ {#key commandPanel}{/key} +
+ {/if} {#if terminal}
diff --git a/web/src/lib/chat/ShellCommand.svelte b/web/src/lib/chat/ShellCommand.svelte index ca019db0a..b9d48ad85 100644 --- a/web/src/lib/chat/ShellCommand.svelte +++ b/web/src/lib/chat/ShellCommand.svelte @@ -1,6 +1,6 @@ + + + (command = found)} /> + diff --git a/web/src/lib/shell-commands.svelte.ts b/web/src/lib/shell-commands.svelte.ts new file mode 100644 index 000000000..9c855ba5f --- /dev/null +++ b/web/src/lib/shell-commands.svelte.ts @@ -0,0 +1,117 @@ +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); + } + } + } + } +} diff --git a/web/src/lib/tiles/WindowSlot.svelte b/web/src/lib/tiles/WindowSlot.svelte index 297ecb42a..8a247cbf1 100644 --- a/web/src/lib/tiles/WindowSlot.svelte +++ b/web/src/lib/tiles/WindowSlot.svelte @@ -8,6 +8,7 @@ import PtyNode from '../nodes/PtyNode.svelte'; import ReviewNode from '../nodes/ReviewNode.svelte'; import SessionNode from '../nodes/SessionNode.svelte'; + import ShellCommandNode from '../nodes/ShellCommandNode.svelte'; import TerminalNode from '../nodes/TerminalNode.svelte'; import TraceNode from '../nodes/TraceNode.svelte'; import { hosted } from './hosts'; @@ -23,6 +24,7 @@ session: SessionNode, review: ReviewNode, terminal: TerminalNode, + command: ShellCommandNode, trace: TraceNode, agents: AgentsNode, artifact: ArtifactNode, diff --git a/web/src/lib/tiles/title.ts b/web/src/lib/tiles/title.ts index 56eb00b32..088390a2e 100644 --- a/web/src/lib/tiles/title.ts +++ b/web/src/lib/tiles/title.ts @@ -17,6 +17,8 @@ export function windowTitle(window: Shown): string { switch (window.type) { case 'session': return name; + case 'command': + return `shell command · ${name}`; case 'artifact': return (typeof data.artifact === 'string' && artifacts.get(data.artifact)?.title) || 'artifact'; case 'pty': { diff --git a/web/src/lib/views/ShellCommandView.svelte b/web/src/lib/views/ShellCommandView.svelte new file mode 100644 index 000000000..b4eabc874 --- /dev/null +++ b/web/src/lib/views/ShellCommandView.svelte @@ -0,0 +1,106 @@ + + +
+ {#if command}
${command.command}
{/if} + {#if command?.truncated}

Capture hit the 16 MiB retention limit; later output wasn’t retained.

{/if} + {#if command?.error}{/if} + {#if output.problem || problem} + + {/if} + +
{#if output.start > 0}… {output.start.toLocaleString()} earlier bytes not shown
+{/if}{output.text}{#if !output.text && !output.problem}{!command || output.loading ? 'Loading output…' : command.status === 'running' ? 'Waiting for output…' : 'No output.'}{/if}
+
+ {status} + {output.start.toLocaleString()}–{output.end.toLocaleString()} of {(command?.output_bytes ?? 0).toLocaleString()} B + {#if output.text}{/if} + {#if command?.status === 'running'}{/if} +
+ +
+ +