From 6d3fbefd62dc5314db3b8d1c697ec6dda4fff7ed Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Fri, 23 Oct 2026 10:51:03 -0400 Subject: [PATCH] web: a background tab counts sessions that finished or need you, and can send system notifications --- robot-docs/web.md | 6 +- web/scripts/attention.test.mjs | 69 ++++++++++++++++++ web/scripts/stream.test.mjs | 45 ++++++++++++ web/src/lib/Settings.svelte | 33 ++++++++- web/src/lib/attention.ts | 41 +++++++++++ web/src/lib/boards.svelte.ts | 15 ++++ web/src/lib/notifications.svelte.ts | 104 ++++++++++++++++++++++++++++ web/src/lib/sessions.svelte.ts | 26 ++++--- web/src/lib/stream.ts | 63 +++++++++++------ 9 files changed, 369 insertions(+), 33 deletions(-) create mode 100644 web/scripts/attention.test.mjs create mode 100644 web/src/lib/attention.ts create mode 100644 web/src/lib/notifications.svelte.ts diff --git a/robot-docs/web.md b/robot-docs/web.md index 8e2ad8605..383bf5e5d 100644 --- a/robot-docs/web.md +++ b/robot-docs/web.md @@ -4,7 +4,7 @@ `albedo web` (`cli/internal/cli/web.go`) finds or starts the daemon, serves `web/dist` (or `ALBEDO_WEB_DIST`, which the Nix package sets to its `web` build, `.#albedo-web`: `buildNpmPackage` over `web/`, so bump `npmDepsHash` in `default.nix` when `package-lock.json` changes) on `127.0.0.1:4317` (`--port`, 0 for any), prints a launch link and opens it unless `--no-open` or `ALBEDO_NO_BROWSER` is set. `cli/internal/webui` owns the boundary: -- Each browser tab multiplexes its session panels and root-list follow over one WebSocket at `/api/events`, avoiding the HTTP/1.1 six-connection SSE limit across tabs. `stream.ts` sends new follows immediately on an open socket, preserves each session cursor independently, and resubscribes an ended follow. Unsubscribe sends a stop only for a follow actually sent. Hidden tabs close pending and open sockets and reopen on return; stale socket callbacks cannot revive them. Older daemons fall back to the existing SSE routes, retaining their connection budget and visibility cancellation. Both the Go proxy and Vite forward WebSocket upgrades with the daemon bearer token. `npm test` in `web/` exercises the stream lifecycle with mocked browser transport and timers. +- Each browser tab multiplexes its session panels and root-list follow over one WebSocket at `/api/events`, avoiding the HTTP/1.1 six-connection SSE limit across tabs. `stream.ts` sends new follows immediately on an open socket, preserves each session cursor independently, and resubscribes an ended follow. Unsubscribe sends a stop only for a follow actually sent. Hidden tabs stop chat follows but keep one root-list follow for completion alerts; without that background follow they close pending and open sockets and reopen on return. Stale socket callbacks cannot revive them. Older daemons fall back to the existing SSE routes, retaining their connection budget and visibility cancellation. Both the Go proxy and Vite forward WebSocket upgrades with the daemon bearer token. `npm test` in `web/` exercises the stream lifecycle with mocked browser transport and timers. - The daemon token never reaches the browser. The page calls `/api/...` on its own origin; the proxy strips `/api`, drops `Origin`, `Cookie` and `Referer`, and adds `Authorization: Bearer `. Session streams pass through unbuffered. - Each run draws a launch key. `/?key=` sets an `HttpOnly`, `SameSite=Strict` cookie and redirects to `/`; `/api` without that cookie answers `401 web_signed_out`. A restarted `albedo web` signs every tab out. - Requests whose `Host` is not `127.0.0.1` or `localhost` are refused (DNS rebinding), and so is an `Origin` other than the page's own. @@ -16,6 +16,10 @@ In development, `npm run dev` in `web/` proxies `/api` the same way from `$ALBEDO_HOME/daemon.json`, read once at start (only when serving, so a build needs no daemon), dropping `Origin` and `Cookie`. WebSocket upgrades also drop `Referer` and require the page's own origin when an `Origin` header is present. It listens on the local network, open, so other devices at home can try the client; the `Host` it answers is limited to the machine's own name (bare and `.local`) and Tailscale's `*.ts.net`, since the proxy holds the token and a rebound name must not reach it. +Background alerts (`attention.ts`, `notifications.svelte.ts`, `sessions.svelte.ts`): the tab title counts distinct watched sessions that finished a turn, acquired a blocking reason, or received agent mail while the tab was hidden or unfocused; the favicon gets a small dot. A watched session is pinned, on any open board, or the phone's current chat, excluding archived sessions. Root-list activity supplies busy-to-idle transitions; a changed latest-answer id also catches a turn missed while disconnected. Mail marks the watched recipient, not the sender: task dispatch and system event mail do not count. Unwatched child turns stay quiet. The existing roots collection supplies these events; no per-child follows or daemon changes are needed. A closed board alone does not subscribe its sessions. + +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. `npm test` covers counting, duplicate mail, focus clearing, missed transitions and the background transport lifecycle. + 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 `--open-tint`, 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. `[` (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. `+` makes a new board; double-click or F2 renames one; closing a tab 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. A board is an open canvas. **Windows** sit anywhere on it; the view pans freely and zooms out to an overview. Svelte Flow draws, drags and resizes the windows; `board.svelte.ts` places new ones (right of the selected window, top-aligned, stepping past overlaps) and owns the viewport. The wheel is handled in `Canvas.svelte` rather than by Svelte Flow, because windows and canvas share the trackpad: a pinch (ctrl-wheel) zooms around the pointer anywhere, a mouse wheel's notch with ctrl or ⌘ by one 10% step (a notch is a jump of 50 px or more, or any line-mode delta, where a pinch moves a few pixels at a time), an up-down scroll over a window that can scroll scrolls it while the zoom is readable (60% and up), so does a sideways scroll over anything under the pointer that scrolls sideways (a diff's code inside Pierre's shadow root, a wide table; found through `composedPath()`), and every other scroll pans. Dragging empty canvas pans; holding Space (unless a text field has focus) or the middle button drags the canvas from anywhere, over windows too, taking the pointer before Svelte Flow or the window sees it; holding Alt (Option), a drag anywhere on a window or note moves it, not only by its title bar, without selecting text, and the click that ends it is swallowed (Option-click would download a link), and Space with a double-click anywhere glides the view there, centred at 90% (`Board.centreOn`, 300 ms from the middle of the pane up to 500 ms from a corner), where a plain double-click on empty canvas leaves a note. + and − zoom in and out by 5 points (the buttons too), ⇧1 fits all windows, ⇧0 returns to 100%, M shows an overview map, ⌥←/⌥→ moves between windows. The view controls (zoom, fit, map) in the bottom-right corner, under the overview map when it shows (as wide as the controls, measured, and showing and fading with them), and key hints in the bottom-left as the terminal's footer lists them (spc and a grab to pan, ⌥ and a move to move a window, cmd and a scroll to zoom, ⇧1, ⌥←→, spc and two clicks to zoom at a spot, two clicks for a note; the mouse gestures are Lucide's icons, drawn in `Gesture.svelte`, to keep them short; keys in the text colour, what they do muted, each pair on a surface of its own with a small gap between), fade in while the view moves and fade out 4 s after it stops; hovering or focusing them keeps them, and once faded they let clicks through to the windows beneath. What a window shows is a **view**, each framed by `nodes/WindowFrame.svelte`: a session's chat, or a review of one turn's changes; files, terminals and agent-made pages are meant to follow. A view opened from a window names it as its `parent`, opens beside it, and the canvas draws a faint dashed line between them (the board derives Svelte Flow edges from those parents; every window carries invisible handles for them). diff --git a/web/scripts/attention.test.mjs b/web/scripts/attention.test.mjs new file mode 100644 index 000000000..4aed04cbd --- /dev/null +++ b/web/scripts/attention.test.mjs @@ -0,0 +1,69 @@ +// Focus timing, duplicate mail and missed background transitions are browser-only state. +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { stripTypeScriptTypes } from 'node:module'; +import test from 'node:test'; + +const source = stripTypeScriptTypes(await readFile(new URL('../src/lib/attention.ts', import.meta.url), 'utf8')); +const { Attention } = await import(`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`); +const session = (id, phase = 'idle', answer = null, blocking_reason = null) => ({ + id, status: { phase, blocking_reason }, activity: { latest_answer: answer && { message_id: answer } }, +}); +const mail = (mail_id, receiver_session_id = 'parent', kind = 'result') => ({ mail_id, receiver_session_id, sender_session_id: 'child', kind }); + +test('counts sessions once across turns and mail; focus allows the next completion', () => { + const attention = new Attention(); + assert.equal(attention.changed(session('a', 'running'), session('a'), true, true), 'finished'); + assert.equal(attention.changed(session('a', 'generating'), session('a'), true, true), null); + assert.equal(attention.mail(mail('reply', 'a'), true, true), null); + assert.equal(attention.changed(session('b', 'preparing'), session('b'), true, true), 'finished'); + assert.deepEqual([...attention.unread], ['a', 'b']); + attention.clear(); + assert.equal(attention.unread.size, 0); + assert.equal(attention.changed(session('a', 'compacting'), session('a'), true, true), 'finished'); +}); + +test('does not count initial loads, visible changes, unwatched sessions or busy phase changes', () => { + const attention = new Attention(); + assert.equal(attention.changed(undefined, session('a'), true, true), null); + assert.equal(attention.changed(session('a', 'running'), session('a'), false, true), null); + assert.equal(attention.changed(session('a', 'running'), session('a'), true, false), null); + assert.equal(attention.changed(session('a', 'running'), session('a', 'generating'), true, true), null); + assert.equal(attention.unread.size, 0); +}); + +test('a new answer catches a whole turn missed during disconnection, but an idle refresh does not', () => { + const attention = new Attention(); + assert.equal(attention.changed(session('a', 'idle', 'old'), session('a', 'idle', 'new'), true, true), 'finished'); + attention.clear(); + assert.equal(attention.changed(session('a', 'idle', 'new'), session('a', 'idle', 'new'), true, true), null); +}); + +test('new blocking reasons need attention without requiring an idle transition', () => { + const attention = new Attention(); + const blocked = session('a', 'preparing', null, { code: 'quota', detail: 'wait' }); + assert.equal(attention.changed(session('a', 'preparing'), blocked, true, true), 'attention'); + attention.clear(); + assert.equal(attention.changed(blocked, blocked, true, true), null); +}); + +test('mail marks its watched recipient, ignores tasks and system events, and survives focus deduplication', () => { + const attention = new Attention(); + for (const kind of ['task', 'webhook', 'event_tool', 'event_turn']) assert.equal(attention.mail(mail(kind, 'parent', kind), true, true), null); + assert.equal(attention.mail(mail('hidden'), false, true), null); + assert.equal(attention.mail(mail('visible'), true, false), null); + assert.equal(attention.mail({ ...mail('system'), sender_session_id: null }, true, true), null); + assert.equal(attention.mail(mail('reply'), true, true), 'mail'); + assert.deepEqual([...attention.unread], ['parent']); + attention.clear(); + assert.equal(attention.mail(mail('reply'), true, true), null); + assert.equal(attention.mail(mail('next'), true, true), 'mail'); +}); + +test('deleted, archived or no-longer-watched sessions can be pruned', () => { + const attention = new Attention(); + attention.mail(mail('a', 'keep'), true, true); + attention.mail(mail('b', 'removed'), true, true); + attention.prune(new Set(['keep'])); + assert.deepEqual([...attention.unread], ['keep']); +}); diff --git a/web/scripts/stream.test.mjs b/web/scripts/stream.test.mjs index 8cbeb42b4..2f9cfdd40 100644 --- a/web/scripts/stream.test.mjs +++ b/web/scripts/stream.test.mjs @@ -267,3 +267,48 @@ test('an initial WebSocket failure falls back once per follow and SSE pauses and await new Promise(setImmediate); } }); + + +test('background list keeps the socket alive while chat follows stop and resume with their cursors', async (t) => { + const { api, sockets, visibility } = await browser(t); + const chat = follow(api, 'chat'); + const events = []; + const stop = api.followSessions((batch) => events.push(...batch), () => {}, true); + const ws = sockets[0]; + ws.open(); + const [session, list] = ws.sent; + ws.message({ key: session.key, batch: batch(12) }); + visibility(true); + assert.equal(ws.closes, 0); + assert.deepEqual(ws.sent.at(-1), { key: session.key, type: 'stop' }); + ws.message({ key: list.key, batch: { events: [{ type: 'mail', data: { mail_id: 'reply' } }] } }); + assert.equal(events[0].data.mail_id, 'reply'); + visibility(false); + assert.deepEqual(ws.sent.at(-1), { ...session, after_generation: 'saved-generation', after_seq: '12' }); + chat.stop(); + stop(); + assert.equal(ws.closes, 1); +}); + +test('a background list can connect and reconnect while hidden, including SSE fallback', async (t) => { + const { api, sockets, requests, visibility, fireTimeout } = await browser(t); + visibility(true); + const stop = api.followSessions(() => {}, () => {}, true); + const ws = sockets[0]; + ws.open(); + assert.equal(ws.sent[0].type, 'sessions'); + ws.close(); + fireTimeout(500); + assert.equal(sockets.length, 2); + sockets[1].close(); + await new Promise(setImmediate); + assert.equal(requests.length, 1); + assert.equal(requests[0].url, '/api/sessions?scope=roots'); + assert.equal(requests[0].signal.aborted, false); + visibility(false); + visibility(true); + assert.equal(requests[0].signal.aborted, false); + stop(); + assert.equal(requests[0].signal.aborted, true); + await new Promise(setImmediate); +}); diff --git a/web/src/lib/Settings.svelte b/web/src/lib/Settings.svelte index 073446d3e..2c8255700 100644 --- a/web/src/lib/Settings.svelte +++ b/web/src/lib/Settings.svelte @@ -1,5 +1,6 @@