diff --git a/robot-docs/web.md b/robot-docs/web.md index 3e83fc059..d5547feab 100644 --- a/robot-docs/web.md +++ b/robot-docs/web.md @@ -152,7 +152,7 @@ The **web search** section (`settings/WebSearchSettings.svelte`) is the TUI's `/ Extension config (`settings/ConfigurationSettings.svelte`) renders the daemon’s declared `extension_settings` fields, with search across sections and fields; clearing a field resets it to inheritance. A sticky category outline on the right follows the visible groups in page order, highlights the category at the scroll position, and scrolls only the editor when clicked (including on a zoomed canvas). On narrow windows it becomes a compact horizontal strip; jump targets stay below it, and reduced-motion preferences disable smooth scrolling. The editor owns the scroll container and passes it to the configuration form; a cleaned-up listener batches measurements of at most five category headings into one animation frame. These sections load lazily and retain drafts when changing sections. Both explicitly save only changed fields using the group’s observed ETag and `application/merge-patch+json`; 412 retains edits and offers an explicit discard/reload, never retries a stale write. Save errors, warnings and success remain visible, and in-flight saves disable the fields and defer closing until the save settles. MCP sign-ins reuse `McpServers.svelte`. Provider creation and credentials still belong to the CLI. `test/manual/ux/settings_check.py` drives singleton opening/focus, category jumps and scroll tracking, board switching with drafts, saves, resets, conflicts, browser persistence, window closing and the phone fallback through a private daemon and browser. -The **extensions** tab is the same `views/ExtensionsView.svelte` the chat's extensions window shows (above), opened without a session, so by default it is global-only. A session dropdown under the search (`ExtensionsView`'s `below` snippet, passed only by settings, never by the chat window; `none` by default) picks a session, which gives the view that `sessionId` and with it the "this session" column, own-choice tints, follow-all-sessions and the reload; changing the pick reads the choices again and keeps the search and folds, and is disabled while a save runs. With none picked: the shelves, folding, search, memory radios and detail panel are shared, the "this session" column, own-choice tints, follow-all-sessions and the reload are not rendered, and a change is confirmed, then saved to the `extensions` settings group at its observed ETag (a stale write refreshes without retrying; the daemon still refuses a toggle another extension needs, and its reason shows above the list). The view takes an optional `sessionId`; without one `extensionChoices` builds its rows from the global inventory instead of a session catalog. `GET /server?include=extensions` returns the installed global inventory, including disabled extensions, without creating or preparing any session; `http_catalog.global_extensions` encodes the runtime-owned facts. The inventory carries no shelf, summary or tools, so the view borrows that metadata (read-only; it describes the extension, not the session) from the first session's catalog; with no session every row sits on the builtins shelf. Read the validator before the inventory so an intervening global change cannot be overwritten. Older daemons without the inventory field use a read-only catalog solely for global metadata, never for session overrides or mutations. New sessions use global defaults; existing sessions apply them on reload. Settings cannot close during a save (`onbusy`). While this tab is open the section fills the window and the list scrolls inside it, so its shelf headings can stick. `test/manual/ux/extensions_check.py` exercises global-only controls, stale writes and dependency refusal through a private daemon with no sessions. +The **extensions** tab is the same `views/ExtensionsView.svelte` the chat's extensions window shows (above), opened without a session, so by default it is global-only. A session dropdown under the search (`ExtensionsView`'s `below` snippet, passed only by settings, never by the chat window; `none` by default) picks a session, which gives the view that `sessionId` and with it the "this session" column, own-choice tints, follow-all-sessions and the reload; changing the pick reads the choices again and keeps the search and folds, and is disabled while a save runs. With none picked: the shelves, folding, search, memory radios and detail panel are shared, the "this session" column, own-choice tints, follow-all-sessions and the reload are not rendered, and a change is confirmed, then saved to the `extensions` settings group at its observed ETag (a stale write refreshes without retrying; the daemon still refuses a toggle another extension needs, and its reason shows above the list). The view takes an optional `sessionId`; without one `extensionChoices` builds its rows from the global inventory instead of a session catalog. `GET /server?include=extensions` returns the installed global inventory, including disabled extensions, without creating or preparing any session; `http_catalog.global_extensions` encodes the runtime-owned facts. The inventory carries no shelf, summary or tools, so the view borrows that metadata (read-only; it describes the extension, not the session) from the first session's catalog; with no session every row sits on the builtins shelf. Read the validator before the inventory so an intervening global change cannot be overwritten. A reply without that inventory is malformed and surfaces as an error, never as an empty list or a catalog reconstruction. New sessions use global defaults; existing sessions apply them on reload. Settings cannot close during a save (`onbusy`). While this tab is open the section fills the window and the list scrolls inside it, so its shelf headings can stick. `test/manual/ux/extensions_check.py` exercises global-only controls, stale writes and dependency refusal through a private daemon with no sessions. The chat view (`chat/`) reads `GET /sessions/{id}/history` (newest page, then `before=` as the reader scrolls up, and `after=` when the stream says something committed) and sends with `PUT /sessions/{id}/inputs/{uuidv7}`; a page's references are read in one walk of `history/content?entries=` (`hydrateAll`), and the work groups that come into view together expand through one such read. Blocks equal to the ones already drawn keep their objects (`Transcript.#keep`), so a page or a streamed delta redraws only rows that changed, and rows off screen skip layout and paint (`content-visibility: auto`); while the session works, a stop button beside send (or Escape in an empty field) reads the session's `run_id` and `input_order` fresh and posts `/sessions/{id}/interrupt`, so a stop never reaches a later run, `{kind: "message", text}`; images attach by paste, drop or the composer's picture button (`chat/attachments.ts`, the terminal client's scheme: each image leaves an `[Image #n]` marker at the cursor, deleting the marker drops the image, sending renumbers the marked images 1..n in reading order and sends them base64 as `images`, at most 10); a user entry's images show above its bubble from their history references (`/api/sessions/{id}/history/{entry}/image-n`). a send stays on screen as pending until its `input_id` appears in history, and a failed one offers retry with the same id. A turn that failed ends in a quiet row under it, the error's own words (the provider's message out of its JSON body; a click shows all of it): the stream's `error` event says so as it happens, and a chat opened later reads the session's request records since its oldest loaded entry (`context?view=requests`, again whenever the session rests, and for each earlier page it reads), a turn whose last model call failed (`Transcript.failures`); a later call that succeeded clears only a failure a call reported, never one the stream did. There is no retry for a failed turn yet; the daemon has none to call. A stop cancels the messages still queued behind the turn (the daemon never commits them); the interrupt answer's `cancelled_input_ids` name them, and the chat takes those pending bubbles back out of the transcript and appends their text and images to the composer's draft (`Draft.restore`: blank-line separated, in send order, images renumbered after the draft's, focus untouched), so a stop loses no words. Your newest message carries a receipt until a reply follows it, drawn as Signal's (`chat/Receipt.svelte`): a dashed ring while sending, a ring with a check once the daemon has accepted it (sent), two filled ones once its entry is in history (seen), which the daemon commits in the same transaction that takes it into the conversation, so the model has it (a message sent while albedo works stays `sent` until the loop takes it at its next step). Until it is seen the bubble stays faded. A waiting input is not listed anywhere, so after a reload it shows nothing until it commits. `transcript.svelte.ts` turns entries into blocks: user bubbles, assistant markdown, and each run of thinking and tool calls between messages folded into one "Worked" line (open while it is the live run or a thought inside it is expanded). Referenced message text is fetched with the page; tool arguments and output only when their run is opened. Markdown is rendered by `marked` with raw HTML escaped and only http(s)/mailto links (`markdown.ts`), because transcripts carry model and tool text into a page that can reach the daemon. The session list (`sessions.svelte.ts`) follows the collection's stream (`GET /sessions?scope=roots` as server-sent events, `followSessions` in `stream.ts`): each `activity` event patches that session's status and activity in place, so the sidebar, window titles and faces change as the daemon does, and `reset`, `overflow` or `invalidate` reads the list again (once for a burst). While that stream is up the list is also read once a minute in case; while it is down, every 4 s. Both stop while the tab is hidden. Each user message shows its timestamp under the bubble (with the receipt on the newest), and a turn's sign-off row shows its timestamp right before its actions, trace and copy as icons, which appear while the pointer is anywhere over the turn's reply or on the row itself (found from the page when the pointer moves, `hover` in `Chat.svelte`), or always on a screen with no hover. What is typed in a composer is a draft kept by session (`chat/drafts.ts`), outside the composer, which goes with its window when another board is shown, so the draft is there when the board comes back. The text is also written to localStorage (`albedo.draft.v1:`) once typing pauses for 300 ms, and on `pagehide`, so a reload keeps it; sending or emptying the field removes it, and one untouched for 30 days is dropped at the next load. The images it marks are not kept (they are too big for storage), so a reload drops them and their `[Image #n]` markers; switching boards keeps them. diff --git a/web/scripts/extensions-inventory.test.mjs b/web/scripts/extensions-inventory.test.mjs new file mode 100644 index 000000000..6a5d964bf --- /dev/null +++ b/web/scripts/extensions-inventory.test.mjs @@ -0,0 +1,62 @@ +// The global extension page has no session to borrow an inventory from: its +// rows must come from `GET /server?include=extensions` alone. A reply missing +// that inventory is malformed, not an invitation to reconstruct global rows +// from a root session's catalog, which a daemon E2E with a session present +// would not notice. +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { stripTypeScriptTypes } from 'node:module'; +import test from 'node:test'; + +const typeless = async (path) => stripTypeScriptTypes((await readFile(new URL(path, import.meta.url), 'utf8')).replace(/^import type .*;\n/gm, ''), { mode: 'transform' }); +const api = await import(`data:text/javascript;base64,${Buffer.from(await typeless('../src/lib/api.ts')).toString('base64')}`); + +const inventoryItem = { id: 'work', description: 'track work', requires: [], enabled: true, quarantined: false, diagnostic: null }; + +function response(body, { ok = true, status = 200 } = {}) { + return { ok, status, statusText: ok ? 'OK' : 'Bad Request', headers: { get: (name) => (name === 'etag' ? '"settings-1"' : null) }, json: async () => body }; +} + +/** Routes the global choices reads; `server` answers the inventory read. */ +function stub(t, server) { + const asked = []; + t.after(() => delete globalThis.fetch); + globalThis.fetch = async (url) => { + const address = String(url); + asked.push(address); + if (address.startsWith('/api/settings')) return response({}); + if (address.startsWith('/api/server')) return typeof server === 'function' ? server() : response(server); + if (address.startsWith('/api/sessions?')) return response({ items: [], next: null }); + return response({}); + }; + return asked; +} + +test('global choices come from the server inventory when no session exists', async (t) => { + const asked = stub(t, { extension_inventory: [inventoryItem] }); + const choices = await api.extensionChoices(); + assert.deepEqual(choices.candidates.map((candidate) => candidate.id), ['work']); + assert.equal(choices.candidates[0].global_preference, true); + assert.equal(choices.candidates[0].effective_enabled, true); + assert.equal(choices.globalETag, '"settings-1"'); + assert.ok(asked.some((address) => address === '/api/server?include=extensions'), `expected the inventory read, saw ${JSON.stringify(asked)}`); + assert.equal(asked.some((address) => address.includes('/catalog')), false, `must not read a session catalog, saw ${JSON.stringify(asked)}`); +}); + +test('a server reply without the inventory is malformed, not a catalog fallback', async (t) => { + const asked = stub(t, {}); + await assert.rejects(() => api.extensionChoices(), /malformed.*extension inventory/i); + assert.equal(asked.some((address) => address.includes('/catalog')), false, `must not read a session catalog, saw ${JSON.stringify(asked)}`); + assert.equal(asked.some((address) => address.startsWith('/api/sessions?')), false, `must not look for a root session, saw ${JSON.stringify(asked)}`); +}); + +test('a non-array inventory is malformed, not an empty list', async (t) => { + stub(t, { extension_inventory: 'work' }); + await assert.rejects(() => api.extensionChoices(), /malformed.*extension inventory/i); +}); + +test('a failed inventory read surfaces instead of falling back to a catalog', async (t) => { + const asked = stub(t, () => response({ code: 'bad_request', detail: 'unknown include' }, { ok: false, status: 400 })); + await assert.rejects(() => api.extensionChoices(), (error) => error instanceof api.ApiError && error.status === 400); + assert.equal(asked.some((address) => address.includes('/catalog')), false, `must not read a session catalog, saw ${JSON.stringify(asked)}`); +}); diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 4a6aa2378..70b711295 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -137,34 +137,9 @@ export async function changeWebSearchProvider(name: string, change: WebSearchCha /** Installed extensions and resolved global defaults; no session is selected or changed. */ async function listGlobalExtensions(signal?: AbortSignal): Promise { - try { - const server = await get('/server?include=extensions', signal); - if (server.extension_inventory) return server.extension_inventory; - } catch (error) { - if (!(error instanceof ApiError && error.status === 400)) throw error; - } - // Older daemons expose inventory only through the read-only session catalog. - // This compatibility path never reads overrides into the UI or mutates a session. - const [session] = await listSessions(signal); - if (!session) throw new Error('Update the daemon to load the global extension inventory.'); - const sessionId = session.id; - const items: GlobalExtension[] = []; - let next: string | null = null; - let revision: string | undefined; - do { - const query = new URLSearchParams({ kind: 'extensions', limit: '200' }); - if (next) query.set('next', next); - const catalog = await get(`/sessions/${sessionId}/catalog?${query}`, signal); - if (!catalog.discovery) throw new Error(catalog.discovery_failure?.detail ?? 'Extension discovery is unavailable.'); - if (revision !== undefined && revision !== catalog.discovery.revision) throw new Error('The extension catalog changed. Refresh to inspect it again.'); - revision = catalog.discovery.revision; - items.push(...catalog.discovery.candidates.filter((candidate) => candidate.kind === 'extension').map((candidate) => ({ - id: candidate.id, description: candidate.description, requires: candidate.dependencies, enabled: candidate.global_preference ?? true, - quarantined: candidate.quarantined, diagnostic: candidate.diagnostic?.detail ?? null, - }))); - next = catalog.discovery.next; - } while (next); - return items; + const server = await get('/server?include=extensions', signal); + if (!Array.isArray(server.extension_inventory)) throw new Error('The daemon sent a malformed global extension inventory.'); + return server.extension_inventory; } /** The compaction strategy extensions installed on the daemon, with which one is active on the session. */