diff --git a/robot-docs/web.md b/robot-docs/web.md index a940bbf70..bba927f72 100644 --- a/robot-docs/web.md +++ b/robot-docs/web.md @@ -37,8 +37,10 @@ live turn produces one (`Transcript.displayed`, `Board.displayShown`). [`notifications.svelte.ts`](../web/src/lib/notifications.svelte.ts) marks pinned sessions and chats on open boards unread when a turn ends, a blocking reason -changes, or agent mail arrives. It uses the session list stream and family reads -for open child-agent chats. Initial loads do not mark old answers unread. +changes, or agent mail arrives. One shared session-summary stream covers roots +and child agents, including chats on inactive boards. Records for chats on all +open boards load independently of their windows. Initial loads do not mark old +answers unread. Dots appear beside chat titles and on their containing tabs and board tabs. A rim light plays once unless the chat's board is visible or the chat is open diff --git a/web/scripts/sessions-attention.test.mjs b/web/scripts/sessions-attention.test.mjs new file mode 100644 index 000000000..120422077 --- /dev/null +++ b/web/scripts/sessions-attention.test.mjs @@ -0,0 +1,238 @@ +// daemon e2e tests cannot see which inactive-board chats the browser keeps observing +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'; +import { flush } from 'svelte/internal/client'; + +const moduleURL = (code) => + `data:text/javascript;base64,${Buffer.from(code).toString('base64')}`; +const imports = new Map(); +async function load(name) { + let code = stripTypeScriptTypes( + await readFile(new URL(`../src/lib/${name}`, import.meta.url), 'utf8'), + { mode: 'transform' }, + ); + if (name.includes('.svelte.')) + code = compileModule(code, { filename: name, generate: 'client' }).js.code; + code = code.replace( + /from (['"])(.*?)\1/g, + (_, _quote, path) => + `from ${JSON.stringify(imports.get(path) ?? import.meta.resolve(path))}`, + ); + const url = moduleURL(code); + imports.set(`./${name.replace(/\.ts$/, '')}`, url); + return import(url); +} +const session = (id, parent_id = null) => ({ + id, + parent_id, + root_id: parent_id ?? id, + status: { phase: 'idle', blocking_reason: null }, + activity: { latest_answer: { message_id: 'old' } }, + preferences: { pinned: false, archived: false }, +}); + +test('inactive-board children and older roots stay observed without mounted chat streams', async (t) => { + const root = session('root'); + const child = session('child', root.id); + const older = session('older'); + const records = new Map([root, child, older].map((s) => [s.id, s])); + const reads = []; + const timers = new Map(); + const listeners = new Map(); + const sent = []; + let socket; + let nextTimer = 0; + const saved = new Map(); + const install = (name, value) => { + saved.set(name, Object.getOwnPropertyDescriptor(globalThis, name)); + Object.defineProperty(globalThis, name, { + configurable: true, + writable: true, + value, + }); + }; + t.after(() => { + for (const [name, descriptor] of saved) { + if (descriptor) Object.defineProperty(globalThis, name, descriptor); + else delete globalThis[name]; + } + }); + install('document', { + title: 'albedo', + hidden: false, + hasFocus: () => true, + querySelector: () => null, + addEventListener(name, fn) { + if (!listeners.has(name)) listeners.set(name, []); + listeners.get(name).push(fn); + }, + }); + install('window', { addEventListener() {} }); + install('localStorage', { getItem: () => null }); + install('location', { protocol: 'http:', host: 'fixture' }); + install('setTimeout', (fn, delay) => { + const id = ++nextTimer; + timers.set(id, { fn, delay }); + return id; + }); + install('clearTimeout', (id) => timers.delete(id)); + install('setInterval', () => ++nextTimer); + install('clearInterval', () => {}); + install( + 'WebSocket', + class { + static OPEN = 1; + readyState = 0; + constructor() { + socket = this; + } + send(value) { + sent.push(JSON.parse(value)); + } + close() { + this.readyState = 3; + this.onclose?.(); + } + }, + ); + const boards = { + tabs: [{ id: 'background' }, { id: 'here' }], + active: 'here', + board: null, + sessionIds: (id) => (id === 'background' ? ['child', 'older'] : []), + hasSession: (id) => ['child', 'older'].includes(id), + }; + install('__sessionAttention', { + boards, + roots: () => [records.get('root')], + read: async (id) => { + reads.push(id); + return records.get(id); + }, + }); + imports.set( + './api', + moduleURL(` + export class ApiError extends Error {} + export const listSessions = async () => globalThis.__sessionAttention.roots(); + export const getSession = (id) => globalThis.__sessionAttention.read(id); + export const configureSession = async () => {}; + `), + ); + imports.set( + './boards.svelte', + moduleURL('export const boards = globalThis.__sessionAttention.boards;'), + ); + imports.set( + './layout.svelte', + moduleURL('export const layout = { phone: false, focus: null };'), + ); + imports.set( + './tiles/tree', + moduleURL('export const paneTrail = () => null;'), + ); + await load('moods.ts'); + await load('live.svelte.ts'); + await load('attention.ts'); + const { notifications } = await load('notifications.svelte.ts'); + await load('stream.ts'); + const { sessions } = await load('sessions.svelte.ts'); + const settle = async () => { + await new Promise((resolve) => setImmediate(resolve)); + flush(); + }; + sessions.start(); + await settle(); + socket.readyState = WebSocket.OPEN; + socket.onopen(); + assert.deepEqual(reads.sort(), ['child', 'older']); + assert.equal(document.title, 'albedo', 'loading old answers is not unread'); + assert.deepEqual( + sessions.list.map((s) => s.id), + ['root'], + 'children stay out of the sidebar', + ); + + const subscription = sent.find((message) => message.type === 'sessions'); + const emit = (events) => { + const visible = events.filter( + (event) => + subscription.scope === 'all' || + !records.get(event.data?.session_id)?.parent_id, + ); + socket.onmessage({ + data: JSON.stringify({ + key: subscription.key, + batch: { events: visible }, + }), + }); + }; + const activity = (id, phase, answer) => ({ + type: 'activity', + data: { + session_id: id, + status: { phase, blocking_reason: null }, + activity: { latest_answer: { message_id: answer } }, + }, + }); + emit([ + activity('child', 'generating', 'old'), + activity('child', 'idle', 'new'), + ]); + assert.ok(notifications.unread.has('child')); + assert.ok(notifications.flashing.has('child')); + assert.equal(sessions.byId.get('child').status.phase, 'idle'); + emit([activity('older', 'idle', 'new')]); + assert.ok( + notifications.unread.has('older'), + 'open roots outside the sidebar page are observed too', + ); + assert.equal(sent.filter((message) => message.type === 'session').length, 0); + + notifications.read('child'); + boards.active = 'background'; + emit([activity('child', 'idle', 'newer')]); + assert.ok(notifications.unread.has('child')); + assert.ok(!notifications.flashing.has('child'), 'visible boards stay quiet'); + notifications.read('child'); + boards.active = 'here'; + emit([ + { + type: 'mail', + data: { + mail_id: 'mail', + sender_session_id: 'root', + receiver_session_id: 'child', + kind: 'message', + }, + }, + ]); + assert.ok( + notifications.unread.has('child'), + 'mail can mark a child as well as a root', + ); + + notifications.read('child'); + records.set('child', { + ...child, + activity: { latest_answer: { message_id: 'after-drop' } }, + }); + emit([{ type: 'reset', data: { reason: 'reconnect' } }]); + const [timerId, timer] = [...timers].find(([, timer]) => timer.delay === 150); + timers.delete(timerId); + timer.fn(); + await settle(); + assert.ok( + notifications.unread.has('child'), + 'a reconnect read recovers a missed completion', + ); + notifications.read('child'); + document.hidden = true; + for (const fn of listeners.get('visibilitychange')) fn(); + emit([activity('child', 'idle', 'while-hidden')]); + assert.ok(notifications.unread.has('child')); + assert.ok(notifications.flashing.has('child')); +}); diff --git a/web/src/lib/sessions.svelte.ts b/web/src/lib/sessions.svelte.ts index 925704ad2..25aa009c2 100644 --- a/web/src/lib/sessions.svelte.ts +++ b/web/src/lib/sessions.svelte.ts @@ -1,3 +1,4 @@ +import { untrack } from 'svelte'; import { SvelteMap } from 'svelte/reactivity'; import { ApiError, @@ -11,6 +12,7 @@ import type { HistoryEntry, Usage } from './context'; import { followSessions, type StreamEvent } from './stream'; import { busy } from './live.svelte'; import { notifications } from './notifications.svelte'; +import { boards } from './boards.svelte'; export type Link = 'connecting' | 'online' | 'offline' | 'unauthorized'; @@ -19,7 +21,7 @@ export type Link = 'connecting' | 'online' | 'offline' | 'unauthorized'; // the list is polled. const POLL_MS = { streaming: 60_000, polling: 4000 }; -// One shared root-list follow stays live for background notifications. +// One shared summary follow stays live for background notifications. // Chat streams and regular list polling still pause while hidden. class Sessions { list = $state.raw([]); @@ -68,6 +70,15 @@ class Sessions { document.hidden ? this.#pause() : this.#resume(), ); notifications.start(); + $effect.root(() => { + $effect(() => { + if (!this.loaded) return; + const ids = boards.tabs.flatMap((tab) => boards.sessionIds(tab.id)); + untrack(() => { + for (const id of new Set(ids)) void this.ensure(id); + }); + }); + }); this.#resume(); } @@ -77,10 +88,27 @@ class Sessions { const controller = (this.#inflight = new AbortController()); try { const next = await listSessions(controller.signal); + const listed = new Set(next.map((session) => session.id)); + const ids = new Set( + boards.tabs.flatMap((tab) => boards.sessionIds(tab.id)), + ); + const agents = ( + await Promise.all( + [...ids] + .filter((id) => !listed.has(id)) + .map((id) => getSession(id, controller.signal).catch(() => null)), + ) + ).filter((session) => session !== null); + if (controller.signal.aborted) return; const previous = this.byId; - for (const session of next) + for (const session of [...next, ...agents]) notifications.changed(previous.get(session.id), session); this.list = next; + if (agents.length) + this.agents = new Map([ + ...this.agents, + ...agents.map((session): [string, Session] => [session.id, session]), + ]); notifications.prune([...next, ...this.agents.values()]); this.link = 'online'; this.loaded = true; @@ -251,15 +279,13 @@ class Sessions { #apply(events: StreamEvent[]) { let patched = this.list; + let agents = this.agents; for (const event of events) { if (event.type === 'activity') { const { session_id: id, status, activity } = event.data ?? {}; const at = patched.findIndex((session) => session.id === id); - if (at < 0) { - this.#later(); - continue; - } - const current = patched[at]; + const current = at < 0 ? agents.get(id) : patched[at]; + if (!current) continue; const next: Session = { ...current, status: status ?? current.status, @@ -271,10 +297,13 @@ class Sessions { if (busy(current) || busy(next)) next.activity_at = activity?.observed_at ?? current.activity_at; notifications.changed(current, next); - patched = patched.map((session, index) => - index === at ? next : session, - ); - } else if (event.type === 'mail') notifications.mail(event.data, patched); + if (at < 0) agents = new Map(agents).set(id, next); + else + patched = patched.map((session, index) => + index === at ? next : session, + ); + } else if (event.type === 'mail') + notifications.mail(event.data, [...patched, ...agents.values()]); else if (event.type === 'invalidate') { const ids: string[] = Array.isArray(event.data?.session_ids) ? event.data.session_ids @@ -292,6 +321,7 @@ class Sessions { this.#later(); } if (patched !== this.list) this.list = patched; + if (agents !== this.agents) this.agents = agents; } } diff --git a/web/src/lib/stream.ts b/web/src/lib/stream.ts index 280a2e09f..2497e7100 100644 --- a/web/src/lib/stream.ts +++ b/web/src/lib/stream.ts @@ -80,7 +80,7 @@ function startFallback(follow: Follow) { if (follow.fallback) return; const path = follow.kind === 'list' - ? '/sessions?scope=roots' + ? '/sessions?scope=all' : `/sessions/${follow.sessionId}?tail=0`; follow.fallback = sseSubscribe( path, @@ -164,7 +164,7 @@ function sendFollow(follow: Follow) { follow.retry = undefined; const value = follow.kind === 'list' - ? { key: follow.key, type: 'sessions', scope: 'roots' } + ? { key: follow.key, type: 'sessions', scope: 'all' } : { key: follow.key, type: 'session', @@ -315,7 +315,7 @@ function release() { * names the query that continues after a handled batch. Returns the stop * function. * - * Chat streams pause while hidden. The root-list follow can stay live + * Chat streams pause while hidden. The summary follow can stay live * for background completion alerts. */ function sseSubscribe(