diff --git a/robot-docs/web.md b/robot-docs/web.md index 9517ae84..cb29c78f 100644 --- a/robot-docs/web.md +++ b/robot-docs/web.md @@ -65,7 +65,7 @@ search (`format.ts`) shares the tui’s matching rules and `test/fixtures/search **Model picker and context meter** (`chat/ModelPicker.svelte`, sharing `ModelChoice.svelte`, `SearchCard.svelte`, and `EffortBar.svelte` with new session and the command palette, maths in `context.ts`): one pill shows the session's model, its reasoning effort as individually rounded capsules along the bottom edge (one capsule per effort step the model supports, stepping progressively in `--accent` lightness and chroma across `low`, `medium`, `high`, `xhigh`), and a multi-segment ring with the share of the window the context fills ("38%", dimming to `--faint` once `cache_fade` expires and turning to the danger colour once the compaction threshold is reached). Hovering the pill opens an interactive context popover (`26px` storage bar) showing the total window fill (`183k / 600k (31%)`), a live cache warmth countdown badge (`cache warm · 3m 50s` vs `cache expired` from `cache_fade`), the hatched compaction reserve zone with its threshold label (`480k`, from `GET /sessions/{id}/context?view=summary`'s `trigger_free_percent`), and the tokens remaining (`297k until compaction`); hovering the bar smoothly expands the 4 category segments (`system`, `messages`, `tool output`, `images`, with a gentle perceptual curve so tiny segments stay easy to target) across 100 % of the bar and shows the hovered category's token count and share underneath. It shows nothing for the context before the session's first usage, and "—" when that usage came from a model other than the session's now. Usage comes from the chat's own session stream (`Transcript.usage`: the reset snapshot's `usage`, then `usage` events), so nothing polls. The window is `GET /sessions/{id}/context-window` (`effective_context_tokens`), read once per model the usage names. The cached count follows `cache_fade` as the terminal footer's does and is redrawn at each step's time. On the canvas the pill sits in the session window's title bar beside the artifacts, agents, background jobs and workspace pills (`nodes/SessionNode.svelte`), and dragging any of those four chips out of the title bar onto the canvas (`Board.undockChip`, `nodes/ChipNode.svelte`) tears it off into a compact tethered window (`context` with the interactive context meter and model selector pill in its body, or `artifacts`, `agents`, `jobs` with their list inline; `sessions.readings` shares the chat's live usage and entries with an undocked `context` window), hiding the chip in the chat's title bar (and routing tethers for open terminals, artifacts, or agents from their row in the undocked chip window via `Tethers.svelte`, falling back to the chat window when docked) until closing (`×`) its window docks it back in; on a phone it floats at the top edge of the chat (`Chat.svelte`) alongside the artifacts and jobs buttons, hiding while the reader scrolls or selects text so the bottom dock stays a clean bare handle above the single-beam composer. Clicking the pill opens a fuzzy-searchable palette of all profiles' models below it (current profile first, matching and highlighting characters across provider names and model ids as in TUI's `/model`, with the effort segmented bar in the footer; clicking a model row or pressing Enter on the first match switches via `PATCH /sessions/{id}?view=configuration` with `If-Match`, or queues the choice while the session is busy and applies it as soon as the turn finishes). Tested by `scripts/context.test.mjs`. -**Slash commands** (`commands.ts`): the chat reads the session's commands from `GET /sessions/{id}/catalog?kind=commands` (only those a human may call; the list is empty until the session's runtime has loaded once). Typing `/` in the composer lists them, filtered as you type (arrows, Tab or Enter to complete, Escape to clear). A line starting with a command runs it: arguments are read the way the terminal reads them (words in order, the last taking the rest, or a JSON object), and one name that is both a read and a change picks the read when nothing follows it. Skills and command inputs are sent as `{kind: "command"}` inputs; reads and changes are the daemon operations the catalogue declares, with path, query, headers and body bound from the session record, the arguments or literals, and their answer shows above the composer until dismissed. +**Slash commands** (`commands.ts`): the chat reads the session's commands from `GET /sessions/{id}/catalog?kind=commands` (only those a human may call; before a runtime has loaded, it uses the catalogue's `native_commands`, as the terminal does, without preparing extensions or booting a kernel). Each chat loads once, then refreshes when slash autocomplete opens or a slash draft regains focus, so a runtime waking or a capability reload does not leave an old menu stuck in the chat. Concurrent refreshes share a request; closing or switching a chat aborts it. Failed reads show an error and retain the previous menu rather than accepting an empty or partial catalogue; opening autocomplete again retries. Loaded commands are authoritative, and pagination rejects a changed loaded revision. Typing `/` in the composer lists them, filtered as you type (arrows, Tab or Enter to complete, Escape to clear). A line starting with a command runs it: arguments are read the way the terminal reads them (words in order, the last taking the rest, or a JSON object), and one name that is both a read and a change picks the read when nothing follows it. Skills and command inputs are sent as `{kind: "command"}` inputs; reads and changes are the daemon operations the catalogue declares, with path, query, headers and body bound from the session record, the arguments or literals, and their answer shows above the composer until dismissed. The (?) between search and settings opens an about pane (`About.svelte`, under it): a one-line description (a placeholder for now), the main contributors with their Bluesky handles (tiles two to a row, an odd one centred under them), thanks to everyone else with a link to the full history on tangled, and the libraries the client is built on with their licences (pills in centred rows), linking `THIRD_PARTY_NOTICES.md`. diff --git a/web/scripts/commands.test.mjs b/web/scripts/commands.test.mjs new file mode 100644 index 00000000..531420d5 --- /dev/null +++ b/web/scripts/commands.test.mjs @@ -0,0 +1,86 @@ +// The daemon E2E suite cannot catch a browser ignoring native_commands or retaining a failed initial read. +// Exercise the real command reader with unloaded/loaded protocol responses and transport failures. +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { stripTypeScriptTypes } from 'node:module'; +import test from 'node:test'; + +async function load(path, prelude = '') { + const source = stripTypeScriptTypes((await readFile(new URL(path, import.meta.url), 'utf8')).replace(/^import .*;$/gm, ''), { mode: 'transform' }); + return import(`data:text/javascript;base64,${Buffer.from(prelude + source).toString('base64')}`); +} +const { ApiError } = await load('../src/lib/api.ts'); +globalThis.__commandsApi = { ApiError }; +const { catalogue, parse } = await load('../src/lib/commands.ts', 'const { ApiError } = globalThis.__commandsApi;\n'); +const command = (name, permissions = ['human']) => ({ id: name, slash_name: name, description: name, arguments: [], caller_permissions: permissions, delivery: 'read' }); +const page = (revision, commands, extra = {}) => ({ loaded: { revision, commands, next: null }, ...extra }); +const json = (body, status = 200) => Response.json(body, { status }); + +test('an unloaded session offers human native commands without preparing its runtime', async (t) => { + const rename = command('/rename'); + const fetch = t.mock.method(globalThis, 'fetch', async () => json(page(null, [], { native_commands: [rename, command('/model-only', ['model'])] }))); + assert.deepEqual(await catalogue('sleeping'), [rename]); + assert.equal(parse(await catalogue('sleeping'), '/rename').command.slash_name, '/rename'); + assert.equal(fetch.mock.calls[0].arguments[0], '/api/sessions/sleeping/catalog?kind=commands&limit=200'); +}); + +test('loaded commands are authoritative, even when discovery failed or the loaded list is empty', async (t) => { + const skill = { ...command('/review'), delivery: 'input', command_id: '/review' }; + const replies = [ + page('loaded', [skill], { native_commands: [command('/disabled')], discovery_failure: { code: 'offline', detail: 'unavailable' } }), + page('loaded-empty', [], { native_commands: [command('/disabled')] }), + ]; + t.mock.method(globalThis, 'fetch', async () => json(replies.shift())); + assert.deepEqual(await catalogue('ready'), [skill]); + assert.deepEqual(await catalogue('ready'), []); +}); + +test('another read replaces the native menu with dynamic commands after the runtime wakes', async (t) => { + let loaded = false; + t.mock.method(globalThis, 'fetch', async () => json(loaded + ? page('awake', [command('/rename'), command('/new-skill')]) + : page(null, [], { native_commands: [command('/rename')] }))); + assert.deepEqual((await catalogue('session')).map(c => c.slash_name), ['/rename']); + loaded = true; + assert.deepEqual((await catalogue('session')).map(c => c.slash_name), ['/rename', '/new-skill']); +}); + +test('paging keeps the same loaded revision and encodes the continuation', async (t) => { + const urls = []; + t.mock.method(globalThis, 'fetch', async (url) => { + urls.push(url); + return json(urls.length === 1 + ? { loaded: { revision: 'same', commands: [command('/first')], next: 'more+/' } } + : page('same', [command('/second')])); + }); + assert.deepEqual((await catalogue('paged')).map(c => c.slash_name), ['/first', '/second']); + assert.equal(urls[1], '/api/sessions/paged/catalog?kind=commands&limit=200&next=more%2B%2F'); +}); + +test('HTTP failures reject instead of becoming a permanently empty or partial command menu', async (t) => { + let calls = 0; + t.mock.method(globalThis, 'fetch', async () => ++calls % 2 === 1 + ? json({ code: 'session_unavailable', detail: 'try again' }, 503) + : json({ loaded: { revision: 'r', commands: [command('/partial')], next: 'later' } })); + await assert.rejects(catalogue('broken'), error => error.status === 503 && error.message === 'try again'); + await assert.rejects(catalogue('broken'), error => error.status === 503); +}); + +test('a changed revision cannot splice commands from two different loaded compositions', async (t) => { + let calls = 0; + t.mock.method(globalThis, 'fetch', async () => json(++calls === 1 + ? { loaded: { revision: 'old', commands: [command('/removed')], next: 'later' } } + : page('new', [command('/replacement')]))); + await assert.rejects(catalogue('changing'), error => error.code === 'catalog_changed'); +}); + +test('a closed chat can abort its catalog request', async (t) => { + const controller = new AbortController(); + t.mock.method(globalThis, 'fetch', (_url, options) => new Promise((_resolve, reject) => { + assert.equal(options.signal, controller.signal); + options.signal.addEventListener('abort', () => reject(options.signal.reason), { once: true }); + })); + const pending = catalogue('closing', controller.signal); + controller.abort(); + await assert.rejects(pending, error => error.name === 'AbortError'); +}); diff --git a/web/src/lib/chat/Chat.svelte b/web/src/lib/chat/Chat.svelte index 4ac2cfa8..354e4b2d 100644 --- a/web/src/lib/chat/Chat.svelte +++ b/web/src/lib/chat/Chat.svelte @@ -275,8 +275,31 @@ // message; reads and changes answer here, above the composer, until dismissed. let commands = $state([]); let answer = $state<{ name: string; text: string; failed: boolean } | null>(null); + let refreshCommands = $state<() => void>(() => {}); $effect(() => { - catalogue(sessionId).then((found) => (commands = found)); + const id = sessionId; + const controller = new AbortController(); + let pending = false; + commands = []; + // Refresh on opening autocomplete, not on every keystroke or a polling timer. + // A slow initial fetch and the first slash share one request. + const refresh = () => { + if (pending || controller.signal.aborted) return; + pending = true; + catalogue(id, controller.signal) + .then((found) => { + if (controller.signal.aborted) return; + commands = found; + if (answer?.name === 'commands') answer = null; + }) + .catch((error) => { + if (!controller.signal.aborted) answer = { name: 'commands', text: String((error as Error).message ?? error), failed: true }; + }) + .finally(() => (pending = false)); + }; + refreshCommands = refresh; + refresh(); + return () => controller.abort(); }); async function command(chosen: Command, rest: string) { @@ -457,7 +480,7 @@ {/if} {/if} - interruptSession(sessionId)} attached={going.length} placeholder={going.length ? 'add a message, or just send the notes…' : undefined} /> + interruptSession(sessionId)} attached={going.length} placeholder={going.length ? 'add a message, or just send the notes…' : undefined} /> diff --git a/web/src/lib/chat/Composer.svelte b/web/src/lib/chat/Composer.svelte index 44b31f2a..dc65857d 100644 --- a/web/src/lib/chat/Composer.svelte +++ b/web/src/lib/chat/Composer.svelte @@ -17,6 +17,7 @@ compact = false, commands = [], oncommand, + oncommands, placeholder = 'message albedo…', attached = 0, }: { @@ -31,6 +32,8 @@ /** The session's slash commands; a line starting with one runs it instead of sending. */ commands?: Command[]; oncommand?: (command: Command, rest: string) => void; + /** Refresh when autocomplete opens or a slash draft regains focus. */ + oncommands?: () => void; placeholder?: string; /** How many notes go with the next message besides the draft; with any, an empty draft can be sent. */ attached?: number; @@ -64,7 +67,11 @@ const marked = $derived(referenced(text, images)); // While the name is being typed, the commands it could be. - const menu = $derived(oncommand && /^\/\S*$/.test(text) ? suggest(commands, text).slice(0, 8) : []); + const completing = $derived(!!oncommand && /^\/\S*$/.test(text)); + const menu = $derived(completing ? suggest(commands, text).slice(0, 8) : []); + $effect(() => { + if (completing) oncommands?.(); + }); let highlighted = $state(0); $effect(() => { menu; @@ -420,6 +427,7 @@ spellcheck="true" tabindex="0" oninput={onInput} + onfocus={() => completing && oncommands?.()} onkeydown={keydown} onpaste={paste} > diff --git a/web/src/lib/commands.ts b/web/src/lib/commands.ts index 97707e1c..5b9f3372 100644 --- a/web/src/lib/commands.ts +++ b/web/src/lib/commands.ts @@ -19,17 +19,28 @@ export interface Outcome { result: unknown; } -/** The commands a person may run in a session; empty until its runtime has loaded once. */ -export async function catalogue(sessionId: string): Promise { +/** Human commands from the loaded composition, or native declarations before its first load. */ +export async function catalogue(sessionId: string, signal?: AbortSignal): Promise { const commands: Command[] = []; let query = 'kind=commands&limit=200'; + let revision: string | null | undefined; for (;;) { - const response = await fetch(`/api/sessions/${sessionId}/catalog?${query}`, { headers: { accept: 'application/json' } }); - if (!response.ok) break; + const response = await fetch(`/api/sessions/${sessionId}/catalog?${query}`, { signal, headers: { accept: 'application/json' } }); + if (!response.ok) { + const body = await response.json().catch(() => null); + const problem = body?.error ?? body ?? {}; + throw new ApiError(response.status, problem.code ?? 'http_error', problem.detail ?? problem.title ?? response.statusText); + } const page: components['schemas']['Catalog'] = await response.json(); const loaded = page.loaded; - commands.push(...(loaded?.commands ?? [])); - if (!loaded?.next) break; + if (revision === undefined) { + revision = loaded.revision; + if (revision === null) commands.push(...(page.native_commands ?? [])); + } else if (loaded.revision !== revision) { + throw new ApiError(409, 'catalog_changed', 'the command catalogue changed; try again'); + } + commands.push(...loaded.commands); + if (!loaded.next) break; query = `kind=commands&limit=200&next=${encodeURIComponent(loaded.next)}`; } return commands.filter((command) => command.caller_permissions.includes('human'));