// 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')); });