Files
stack/packages/webui/tests/agent-drawer-browser.test.mjs

580 lines
42 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SP12 (#1873): selecting an agent on #/agents or in an organization page's Active agent sessions
// table opens a detail drawer at the right of the page; the page under it stays. The address carries
// the selection (?agent=<org>:<name>), so a reload reopens it and Back closes it. Escape and Close
// close it and put focus back on the row. Every field comes from a read the Console already makes; a
// field no read gives is left out. Actions show only where the agent's own organization config says
// this Console writes there, and a refused action says why next to its button.
// Every bus is a fake: acme and beta answer. The real GET /api/workspace and per-organization routes
// serve the page; only the per-organization config and the agent writes are stubbed in the page.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.mjs';
const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString();
const HIRE = '0f3c1a2b-4d5e-4f60-8a7b-9c0d1e2f3a4b';
const THREAD = '7b1e2c3d-4f50-4a61-8b72-9c83d4e5f6a7';
function fixture() {
const LIST = [
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt' },
{ id: 'beta', label: 'Beta Works', theme: 'grove' },
];
const task = (n, title, extra = {}) => ({ task_ref: `store:${n}`, source: 'store', at: at(20 + n), fields: { title, state: 'in-progress', group: 'p-site', assignees: ['coder'], ...extra } });
const DATA = {
acme: {
projects: [{ id: 'p-site', repo: 'site', name: 'Website', archived: false, at: at(30) }],
// Seven tasks name coder: six open, one done. The drawer lists five open ones and links the rest.
tasks: [task(1, 'Hero copy'), task(2, 'Footer links'), task(3, 'Pricing table'), task(4, 'Contact form'), task(5, 'Blog index'), task(6, 'Search box'), task(7, 'Old banner', { state: 'done', done: true })],
agents: [{ role: 'coder', holder_run: 'run-1', harness: 'claude', state: 'working', at: at(40), working: { since: at(40), messages: 2 } }],
// Two decisions wait on a human: one coder raised, one chief raised.
inbox: [
{ id: 'dec-1', question: 'Ship the hero copy?', class: 'DECISION', raised_by_role: 'coder', task_ref: 'store:1', at: at(10) },
{ id: 'dec-2', question: 'Hire a designer?', class: 'DECISION', raised_by_role: 'chief', task_ref: 'store:2', at: at(12) },
],
claims: [{ thread: THREAD, instance: 'assistant', holder_run: 'run-3', harness: 'claude', at: at(5) }],
threads: [{ id: THREAD, project: 'p-site', name: 'Launch notes' }],
instances: {
coder: { definition: 'coder', running: ['run-1'] },
chief: { definition: 'chief-of-staff', running: [] },
assistant: { definition: 'assistant', running: ['run-3'] },
},
model: { coder: 'claude-opus-5-5' },
},
beta: {
projects: [{ id: 'p-shop', repo: 'shop', name: 'Shop', archived: false, at: at(120) }],
tasks: [], inbox: [], claims: [], threads: [],
agents: [{ role: 'pm', holder_run: 'run-9', harness: 'claude', state: 'waiting', at: at(15) }],
instances: { pm: { definition: 'pm', running: ['run-9'] }, 'research-2': { definition: `org:hire-${HIRE}`, hireDecision: HIRE, running: [], pack: { id: 'coding', origin: 'shipped', project: null } } },
model: {},
},
};
const value = (id, name) => Promise.resolve(DATA[id]?.[name] ?? (['usage', 'limits'].includes(name) ? {} : []));
const opts = id => ({
bus: { inbox: () => value(id, 'inbox'), agents: () => value(id, 'agents'), 'thread.claims': () => value(id, 'claims'), tasks: () => value(id, 'tasks'), usage: () => value(id, 'usage'), limits: () => value(id, 'limits'), decisions: () => value(id, 'decisions') },
chat: { threads: () => value(id, 'threads'), projects: () => value(id, 'projects') },
});
const member = org => ({ id: org.id, doc: { appearance: { theme: org.theme } }, status: async () => ({ healthy: true, pid: 4242, boot: null }), options: () => opts(org.id) });
return {
list: async () => LIST.map(o => ({ ...o, busHealthy: true })),
members: async () => LIST.map(member),
resolve: async id => {
const org = LIST.find(o => o.id === id); if (!org) return null;
const d = DATA[id];
return {
busHealthy: true,
reads: {
business: async () => ({ business: { id, human: 'jason', projects: d.projects.map(p => p.repo), appearance: { theme: org.theme }, instances: Object.entries(d.model).map(([instance, model]) => ({ instance, vars: { model } })) } }),
settings: async () => ({}), queue: async () => ({ rows: [] }), busStatus: async () => ({}),
},
bus: {
messages: async () => ({ messages: [], unread: 0 }), agents: async () => d.agents, 'thread.claims': async () => d.claims, inbox: async () => d.inbox, tasks: async () => d.tasks,
instances: async () => ({ revision: 'a'.repeat(64), definitions: {}, instances: d.instances }),
},
chat: { projects: async () => d.projects, threads: async () => d.threads },
};
},
};
}
// Runs before the page's scripts. Acme's config says this Console sends there (chat and settings);
// beta's says it only reads. Agent writes are recorded and answered from a queue; nothing is written.
const STUB = `(() => {
const real = window.fetch.bind(window);
window.__posts = []; window.__answers = []; window.__packReads = [];
window.__packsRelease = () => (window.__packsHeld ?? []).splice(0).forEach(r => r());
const answer = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
window.fetch = async (url, init = {}) => {
const u = String(url);
const cfg = u.match(/^\\/api\\/orgs\\/([^/]+)\\/config$/);
if (cfg) {
const c = await (await real(url, init)).json();
const writes = cfg[1] === 'acme';
return answer(200, { ...c, chatSend: writes, settingsSend: writes, decide: writes });
}
// SP16: the packs read (owner only). Beta installed the Coding pack, whose hire research-2 is made
// from the researcher definition, and that from the researcher template. The instance names only the
// pack's id, as the bus's does; the pack's document carries its label. A test may set __packsStatus,
// __packsBody (a 200 answer that is not JSON) or __packsHold (each read held answers on __packsRelease()).
const packs = u.match(/^\\/api\\/orgs\\/([^/]+)\\/packs$/);
if (packs) {
window.__packReads.push(packs[1]);
if (window.__packsHold) await new Promise(r => (window.__packsHeld ??= []).push(r));
if (window.__packsStatus) return answer(window.__packsStatus, { error: 'refused' });
if (window.__packsBody) return new Response(window.__packsBody, { status: 200, headers: { 'content-type': 'text/html' } });
return answer(200, { writable: false, applied: [{ id: 'coding', origin: 'shipped', project: null, hired: ['research-2'], open: [] }], packs: packs[1] === 'beta' ? [{ id: 'coding', origin: 'shipped', pack: { id: 'coding', label: 'Coding', version: 2, hires: [{ name: 'research-2', definition: 'researcher', reason: 'Research.' }], definitions: { researcher: { template: 'researcher', sha256: '${'a'.repeat(64)}' } } } }] : [] });
}
if (!/\\/agent\\//.test(u) || (init.method || 'GET') === 'GET' && !u.includes('/agent/request')) return real(url, init);
window.__posts.push({ url: u, method: init.method || 'GET', body: init.body ?? null });
const a = window.__answers.shift();
if (!a) throw new TypeError('no answer queued');
return answer(a.status ?? 200, a.body);
};
})();`;
async function setup(t, { viewport = [1440, 900], hash = '#/agents', stub = true, scripts = [] } = {}) {
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: fixture(), log: () => {} });
t.after(() => close(server));
const b = await browser({ machine: false }); t.after(() => b.close());
await b.viewport(...viewport);
if (stub) await b.call('Page.addScriptToEvaluateOnNewDocument', { source: STUB });
for (const source of scripts) await b.call('Page.addScriptToEvaluateOnNewDocument', { source });
const base = `http://127.0.0.1:${server.address().port}`;
await b.navigate(`${base}/${hash}`);
const text = sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.innerText.replace(/\\s+/g, " ").trim() ?? null`);
const attr = (sel, name) => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.getAttribute(${JSON.stringify(name)}) ?? null`);
const has = sel => b.evaluate(`!!document.querySelector(${JSON.stringify(sel)})`);
return { b, base, wait: waitFor(b), text, attr, has };
}
const drawer = key => `document.querySelector('[data-ws-drawer="${key}"]')`;
const open = key => `!!${drawer(key)} && ${drawer(key)}.querySelector("h2")?.textContent.length > 0`;
const noDrawer = '!document.querySelector("[data-ws-drawer]")';
const agentParam = 'new URLSearchParams(location.hash.split("?")[1] || "").get("agent")';
const rowLink = key => `[data-ws-agent="${key}"] a[data-ws-drawer-open]`;
const sessionLink = key => `[data-ws-session-agent="${key}"] a[data-ws-drawer-open]`;
test('a row on #/agents opens the drawer: a region with a heading, the page stays under it', async t => {
const { b, wait, text, attr, has } = await setup(t);
await wait(`document.querySelector(${JSON.stringify(rowLink('acme:coder'))})`);
assert.equal(await attr(rowLink('acme:coder'), 'href'), '#/agents?agent=acme%3Acoder');
await b.evaluate(`document.querySelector(${JSON.stringify(rowLink('acme:coder'))}).click()`);
await wait(open('acme:coder'));
assert.equal(await b.evaluate(agentParam), 'acme:coder');
// A region, not a modal: no dialog role, no aria-modal, labelled by its heading.
const d = '[data-ws-drawer="acme:coder"]';
assert.equal(await attr(d, 'role'), 'region');
assert.equal(await attr(d, 'aria-modal'), null);
assert.equal(await b.evaluate(`document.getElementById(document.querySelector('${d}').getAttribute("aria-labelledby"))?.textContent`), 'coder');
// The page under it stays: the agents table is still drawn and its heading is the page's.
assert.equal(await has('[data-ws-agent-list]'), true);
assert.equal(await text('#bus-view h1'), 'Agents');
// At the right of the page.
const box = await b.evaluate(`(() => { const r = document.querySelector('${d}').getBoundingClientRect(); return [Math.round(r.left), Math.round(r.right), innerWidth]; })()`);
assert.ok(box[0] > box[2] / 2, `drawer left edge ${box[0]} should be in the right half of ${box[2]}`);
assert.ok(box[1] >= box[2] - 20, `drawer right edge ${box[1]} should reach the right of ${box[2]}`);
// At 1440 wide nothing on the page sits under it: the agents table ends left of the drawer.
const table = await b.evaluate(`Math.round(document.querySelector('[data-ws-agent-list]').getBoundingClientRect().right)`);
assert.ok(table <= box[0], `the agents table right edge ${table} should be left of the drawer at ${box[0]}`);
});
test('the drawer shows each field from its read: name, organization, role and source, state, model, project, task, open tasks and decisions', async t => {
const { b, wait, text, attr, has } = await setup(t, { hash: '#/agents?agent=acme%3Acoder' });
await wait(open('acme:coder'));
const d = '[data-ws-drawer="acme:coder"]';
assert.equal(await text(`${d} h2`), 'coder');
assert.equal(await text(`${d} [data-ws-orgchip]`), 'Acme Studio');
assert.match(await text(`${d} [data-drawer-role]`), /coder/);
assert.match(await text(`${d} [data-drawer-source]`), /Organization agent.*definition coder/);
assert.match(await text(`${d} [data-drawer-state]`), /(^|\s)working$/);
assert.match(await text(`${d} [data-drawer-model]`), /claude-opus-5-5/);
// Project and task are links to their pages; the project is the task's, and says so.
assert.equal(await attr(`${d} [data-drawer-project] a`, 'href'), '#/orgs/acme/projects/p-site');
assert.match(await text(`${d} [data-drawer-project]`), /Website.*from its task/);
assert.equal(await attr(`${d} [data-drawer-task] a`, 'href'), '#/orgs/acme/tasks?task=store%3A1');
assert.match(await text(`${d} [data-drawer-task]`), /Hero copy/);
// Open tasks assigned to it: five of six, newest first is not claimed; the done one is never listed.
const tasks = await b.evaluate(`[...document.querySelectorAll('${d} [data-drawer-tasks] li a')].map(a => [a.textContent.trim(), a.getAttribute("href")])`);
assert.equal(tasks.length, 5);
assert.ok(tasks.every(([, href]) => /^#\/orgs\/acme\/tasks\?task=store%3A[1-6]$/.test(href)), JSON.stringify(tasks));
assert.ok(!tasks.some(([title]) => title === 'Old banner'));
assert.equal(await attr(`${d} [data-drawer-tasks-all]`, 'href'), '#/tasks?org=acme&assignee=coder');
assert.match(await text(`${d} [data-drawer-tasks-all]`), /6/);
// Decisions waiting on a human that it raised, each into the Inbox. Chief's is not its own.
const decisions = await b.evaluate(`[...document.querySelectorAll('${d} [data-drawer-decisions] li a')].map(a => [a.textContent.trim(), a.getAttribute("href")])`);
assert.deepEqual(decisions, [['Ship the hero copy?', '#/inbox?d=acme%3Adec-1']]);
// SP16: no read gives the time of an agent's last activity. The agents read's time (when it took the
// role) and `since` (when its present state began) are not that, so the drawer says not recorded.
assert.equal(await text(`${d} [data-drawer-activity]`), 'not recorded');
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-activity]').closest('.ws-drawer-f').querySelector('dt').textContent`), 'Last activity');
// Not a pack hire: no packs read, and no Hired from line.
assert.equal(await has(`${d} [data-drawer-hired]`), false);
assert.deepEqual(await b.evaluate('window.__packReads'), []);
// The Tasks board link opens the board filtered to the agent.
await b.evaluate(`document.querySelector('${d} [data-drawer-tasks-all]').click()`);
await wait(`document.querySelector('[data-tasks-board] select[data-tb-filter="assignee"]')?.value === 'coder'`);
// When the address drops the assignee, the board drops the filter it took from the address.
await b.evaluate('location.hash = "#/tasks"');
await wait(`document.querySelector('[data-tasks-board] select[data-tb-filter="assignee"]')?.value === ''`);
});
test('a hired agent shows where its role came from; a not-running agent says not running', async t => {
const { wait, text, has } = await setup(t, { hash: '#/agents?agent=beta%3Aresearch-2' });
await wait(open('beta:research-2'));
const d = '[data-ws-drawer="beta:research-2"]';
// SP16 review 2: the pack is named once, in Hired from; the Role row says only that it was hired.
assert.equal(await text(`${d} [data-drawer-role]`), 'Hired');
assert.match(await text(`${d} [data-drawer-source]`), new RegExp(`hire decision ${HIRE}`));
assert.match(await text(`${d} [data-drawer-state]`), /(^|\s)not running$/);
assert.equal(await has(`${d} [data-drawer-model]`), false);
});
test('SP16: a pack hire names its pack and the template the packs read gives; a refused read says so', async t => {
const { b, base, wait, text } = await setup(t, { hash: '#/agents?agent=beta%3Aresearch-2' });
const d = '[data-ws-drawer="beta:research-2"]';
await wait(`${open('beta:research-2')} && document.querySelector('${d} [data-drawer-hired]')`);
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-hired]').closest('.ws-drawer-f').querySelector('dt').textContent`), 'Hired from');
assert.equal(await text(`${d} [data-drawer-hired]`), 'Pack Coding, template researcher as the installed pack names it');
// One open makes one packs read, and only for the organization of the pack hire.
assert.deepEqual(await b.evaluate('window.__packReads'), ['beta']);
// The packs read refused (it is the owner's): the pack still shows, and the template says why it is missing.
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: 'window.__packsStatus = 403;' });
await b.navigate('about:blank');
await b.navigate(`${base}/#/agents?agent=beta%3Aresearch-2`);
await wait(`${open('beta:research-2')} && document.querySelector('${d} [data-drawer-hired]')`);
assert.equal(await text(`${d} [data-drawer-hired]`), 'Pack coding, template not read: refused');
});
test('SP16 review: a packs read that answers 200 with no JSON says no answer, and the drawer stays', async t => {
const { b, base, wait, text } = await setup(t, { hash: '#/agents', scripts: ['window.__packsBody = "<html>proxy error</html>";'] });
await b.navigate(`${base}/#/agents?agent=beta%3Aresearch-2`);
const d = '[data-ws-drawer="beta:research-2"]';
await wait(`${open('beta:research-2')} && document.querySelector('${d} [data-drawer-hired]')`);
assert.equal(await text(`${d} [data-drawer-hired]`), 'Pack coding, template not read: no answer');
assert.match(await text(`${d} [data-drawer-state]`), /not running$/);
});
test('SP16 review: a packs read still open does not hold the page or the state; the template line repaints when it answers', async t => {
const { b, wait, text } = await setup(t, { hash: '#/agents?agent=beta%3Aresearch-2', scripts: ['window.__packsHold = true;'] });
const d = '[data-ws-drawer="beta:research-2"]';
await wait(`${open('beta:research-2')} && document.querySelector('${d} [data-drawer-hired]')`);
// The page painted and the state is read while the packs read is held.
assert.equal(await text(`${d} [data-drawer-hired]`), 'Pack coding, template being read…');
assert.match(await text(`${d} [data-drawer-state]`), /not running$/);
assert.ok(await b.evaluate(`!!document.querySelector('${d}[data-drawer-pending]')`));
await b.evaluate('window.__packsHold = false; window.__packsRelease()');
await wait(`document.querySelector('${d} [data-drawer-hired]')?.textContent.includes('template researcher')`);
assert.equal(await text(`${d} [data-drawer-hired]`), 'Pack Coding, template researcher as the installed pack names it');
});
// SP16 review 2 probes. OBS records every agent drawer put on the page; SLOW holds the drawer's own
// workspace read (it names org= and the inbox section) 400 ms, so the page's reads answer first;
// INST_HOLD holds beta's first bus instances read (the drawer's: it is made before the page's) until
// window.__instRelease().
const OBS = `(() => {
window.__ins = [];
new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) {
const list = n.nodeType === 1 ? [n, ...n.querySelectorAll('[data-ws-drawer]')] : [];
for (const e of list) if (e.matches?.('[data-ws-drawer]')) window.__ins.push({ id: e.dataset.wsDrawer, pending: e.dataset.drawerPending || null, hired: e.querySelector('[data-drawer-hired]')?.textContent.trim() ?? null });
} }).observe(document, { childList: true, subtree: true });
})();`;
const SLOW = `(() => { const f = window.fetch; window.fetch = async (u, i) => { if (/\\/api\\/workspace\\?.*org=/.test(String(u)) && /inbox/.test(decodeURIComponent(String(u)))) await new Promise(r => setTimeout(r, 400)); return f(u, i); }; })();`;
const INST_HOLD = `(() => { const f = window.fetch; let n = 0; window.fetch = async (u, i) => { if (/\\/api\\/orgs\\/beta\\/bus\\/instances$/.test(String(u)) && ++n === 1) await new Promise(r => { window.__instRelease = r; }); return f(u, i); }; })();`;
const renders = async (b, wait, count) => {
for (let i = 0; i < count; i++) {
const seen = await b.evaluate('window.__ins.length');
await b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-workspace-render'))`);
await wait(`window.__ins.length > ${seen}`);
await new Promise(r => setTimeout(r, 700));
}
};
test('SP16 review 2: a repaint draws the template from the kept packs answer, so the line does not change and one packs read serves the repaints', async t => {
const { b, wait } = await setup(t, { hash: '#/agents?agent=beta%3Aresearch-2', scripts: [OBS, SLOW] });
const d = '[data-ws-drawer="beta:research-2"]';
const final = 'Pack Coding, template researcher as the installed pack names it';
await wait(`document.querySelector('${d} [data-drawer-hired]')?.textContent.includes('template researcher')`);
const from = await b.evaluate('window.__ins.length');
await renders(b, wait, 3);
const later = JSON.parse(await b.evaluate(`JSON.stringify(window.__ins.slice(${from}))`)).filter(x => x.id === 'beta:research-2');
assert.ok(later.length >= 3, JSON.stringify(later));
for (const x of later) assert.deepEqual([x.hired, x.pending], [final, null], JSON.stringify(later));
assert.deepEqual(await b.evaluate('window.__packReads'), ['beta']);
});
test('SP16 review 2: when the instances read answers after the page, the state shows at once while the packs read is still held', async t => {
const { b, wait, text, has } = await setup(t, { hash: '#/agents?agent=beta%3Aresearch-2', scripts: [INST_HOLD, 'window.__packsHold = true;'] });
const d = '[data-ws-drawer="beta:research-2"]';
await wait(`${open('beta:research-2')} && typeof window.__instRelease === 'function'`);
assert.equal(await text(`${d} [data-drawer-state]`), 'Reading state…');
assert.equal(await has(`${d} [data-drawer-hired]`), false);
await b.evaluate('window.__instRelease()');
await wait(`/not running$/.test(document.querySelector('${d} [data-drawer-state]')?.textContent ?? '')`);
assert.equal(await text(`${d} [data-drawer-hired]`), 'Pack coding, template being read…');
assert.equal(await text(`${d} [data-drawer-role]`), 'Hired');
assert.equal(await has(`${d}[data-drawer-pending]`), true);
await b.evaluate('window.__packsHold = false; window.__packsRelease()');
await wait(`document.querySelector('${d} [data-drawer-hired]')?.textContent.includes('template researcher')`);
assert.equal(await text(`${d} [data-drawer-hired]`), 'Pack Coding, template researcher as the installed pack names it');
assert.match(await text(`${d} [data-drawer-state]`), /not running$/);
assert.equal(await has(`${d}[data-drawer-pending]`), false);
});
test('SP16 review 2: a drawer whose reads have all answered is not marked pending and is not swapped after paint', async t => {
const { b, wait } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', scripts: [OBS, SLOW] });
await wait(`${open('acme:coder')} && /working$/.test(document.querySelector('[data-ws-drawer="acme:coder"] [data-drawer-state]')?.textContent ?? '')`);
const from = await b.evaluate('window.__ins.length');
await renders(b, wait, 2);
const later = JSON.parse(await b.evaluate(`JSON.stringify(window.__ins.slice(${from}))`)).filter(x => x.id === 'acme:coder');
assert.equal(later.length, 2, JSON.stringify(later));
assert.ok(later.every(x => x.pending === null), JSON.stringify(later));
});
// SP16 review 3: HIRE3 adds a later hire of the Coding pack, research-3, to beta's instances read once
// window.__hire3 is set, and to the packs read's Coding hires once window.__packs3 is set. SKEW moves
// Date.now on by window.__skew ms.
const HIRE3 = `(() => {
const f = window.fetch;
const json = (r, v) => new Response(JSON.stringify(v), { status: r.status, headers: { 'content-type': 'application/json' } });
window.fetch = async (u, i) => {
const r = await f(u, i), s = String(u);
if (window.__hire3 && /\\/api\\/orgs\\/beta\\/bus\\/instances$/.test(s) && r.ok) {
const v = await r.clone().json();
(v.rows?.[0]?.instances ?? v.instances)['research-3'] = { definition: 'org:hire-${HIRE.replace('0f3c', '1f3c')}', hireDecision: '${HIRE.replace('0f3c', '1f3c')}', running: [], pack: { id: 'coding', origin: 'shipped', project: null } };
return json(r, v);
}
if (window.__packs3 && /\\/api\\/orgs\\/beta\\/packs$/.test(s) && r.ok) {
const v = await r.clone().json();
v.packs[0].pack.hires.push({ name: 'research-3', definition: 'researcher', reason: 'More research.' });
return json(r, v);
}
return r;
};
})();`;
const SKEW = `(() => { const n = Date.now; Date.now = () => n() + (window.__skew || 0); })();`;
const FINAL = 'Pack Coding, template researcher as the installed pack names it';
const hiredText = key => `(document.querySelector('[data-ws-drawer="${key}"] [data-drawer-hired]')?.textContent ?? '')`;
test('SP16 review 3: a hire made after the packs answer was kept is read again at once, and its drawer never says the pack does not name it', async t => {
const { b, wait, text } = await setup(t, { hash: '#/agents?agent=beta%3Aresearch-2', scripts: [OBS, HIRE3] });
await wait(`${hiredText('beta:research-2')}.includes('template researcher')`);
await b.evaluate('window.__hire3 = true; window.__packs3 = true; location.hash = "#/agents?agent=beta%3Aresearch-3"');
await wait(`${hiredText('beta:research-3')}.includes('template researcher')`);
assert.equal(await text('[data-ws-drawer="beta:research-3"] [data-drawer-hired]'), FINAL);
const seen = JSON.parse(await b.evaluate('JSON.stringify(window.__ins)')).filter(x => x.id === 'beta:research-3');
assert.ok(seen.length >= 1 && seen.every(x => !/not named/.test(x.hired ?? '')), JSON.stringify(seen));
assert.deepEqual(await b.evaluate('window.__packReads'), ['beta', 'beta']);
});
test('SP16 review 3: a hire the pack does not name is read again once, then says so without a packs read on every repaint', async t => {
const { b, wait, text } = await setup(t, { hash: '#/agents?agent=beta%3Aresearch-2', scripts: [OBS, HIRE3] });
await wait(`${hiredText('beta:research-2')}.includes('template researcher')`);
await b.evaluate('window.__hire3 = true; location.hash = "#/agents?agent=beta%3Aresearch-3"');
await wait(`${hiredText('beta:research-3')}.includes('not named')`);
assert.equal(await text('[data-ws-drawer="beta:research-3"] [data-drawer-hired]'), 'Pack Coding, template not named in the packs read');
assert.deepEqual(await b.evaluate('window.__packReads'), ['beta', 'beta']);
await renders(b, wait, 2);
assert.equal(await text('[data-ws-drawer="beta:research-3"] [data-drawer-hired]'), 'Pack Coding, template not named in the packs read');
assert.deepEqual(await b.evaluate('window.__packReads'), ['beta', 'beta']);
});
test('SP16 review 3: a packs read that failed is read again on the next render, so the line recovers with the route', async t => {
const { b, wait, text } = await setup(t, { hash: '#/agents?agent=beta%3Aresearch-2', scripts: [OBS, 'window.__packsStatus = 503;'] });
await wait(`${hiredText('beta:research-2')}.includes('not read')`);
assert.equal(await text('[data-ws-drawer="beta:research-2"] [data-drawer-hired]'), 'Pack coding, template not read: no answer');
// A kept failure is read again on each render (at most one read open), as before the answer was kept.
await new Promise(r => setTimeout(r, 700));
const failed = await b.evaluate('window.__packReads.length');
await b.evaluate(`window.__packsStatus = 0; document.dispatchEvent(new CustomEvent('mosaic-workspace-render'))`);
await wait(`${hiredText('beta:research-2')}.includes('template researcher')`);
assert.equal(await text('[data-ws-drawer="beta:research-2"] [data-drawer-hired]'), FINAL);
assert.equal(await b.evaluate('window.__packReads.length'), failed + 1);
// Recovered, the answer is kept again: a further repaint makes no read.
await renders(b, wait, 1);
assert.equal(await b.evaluate('window.__packReads.length'), failed + 1);
});
test('SP16 review 3: once the kept packs answer is 60 s old a repaint still draws it, with one new read and no swap when that read answers', async t => {
const { b, wait } = await setup(t, { hash: '#/agents?agent=beta%3Aresearch-2', scripts: [OBS, SLOW, SKEW] });
await wait(`${hiredText('beta:research-2')}.includes('template researcher')`);
const from = await b.evaluate('window.__ins.length');
await b.evaluate('window.__skew = 61000; window.__packsHold = true;');
await renders(b, wait, 1);
await wait('window.__packReads.length === 2');
await b.evaluate('window.__packsHold = false; window.__packsRelease()');
await new Promise(r => setTimeout(r, 700));
const later = JSON.parse(await b.evaluate(`JSON.stringify(window.__ins.slice(${from}))`)).filter(x => x.id === 'beta:research-2');
assert.equal(later.length, 1, JSON.stringify(later));
assert.deepEqual([later[0].hired, later[0].pending], [FINAL, null]);
assert.deepEqual(await b.evaluate('window.__packReads'), ['beta', 'beta']);
});
test('a field with no read is left out', async t => {
// beta:pm: beta's business read names no model for it, and it holds no task, so no project either.
const { wait, has, text } = await setup(t, { hash: '#/agents?agent=beta%3Apm' });
await wait(open('beta:pm'));
const d = '[data-ws-drawer="beta:pm"]';
assert.match(await text(`${d} [data-drawer-state]`), /waiting on you/);
for (const field of ['model', 'project', 'task', 'hired']) assert.equal(await has(`${d} [data-drawer-${field}]`), false, `${field} should be absent`);
// An empty list still says so, since the read answered: no open tasks, no decisions.
assert.match(await text(`${d} [data-drawer-tasks]`), /No open tasks/);
assert.match(await text(`${d} [data-drawer-decisions]`), /No decisions/);
});
test('the address round trip: Back closes the drawer, Forward and a reload open it again', async t => {
const { b, base, wait } = await setup(t);
await wait(`document.querySelector(${JSON.stringify(rowLink('beta:pm'))})`);
await b.evaluate(`document.querySelector(${JSON.stringify(rowLink('beta:pm'))}).click()`);
await wait(open('beta:pm'));
await b.evaluate('history.back()');
await wait(`${noDrawer} && location.hash === "#/agents"`);
assert.equal(await b.evaluate('!!document.querySelector("[data-ws-agent-list]")'), true);
await b.evaluate('history.forward()');
await wait(open('beta:pm'));
const hash = await b.evaluate('location.hash');
await b.navigate(`${base}/${hash}`);
await wait(open('beta:pm'));
// The other filters stay in the address beside it.
await b.navigate(`${base}/#/agents?org=beta&agent=beta%3Apm`);
await wait(`${open('beta:pm')} && document.querySelectorAll("[data-ws-agent]").length === 2`);
// An agent no read has says so, with Close; a malformed value opens nothing.
await b.navigate(`${base}/#/agents?agent=beta%3Anobody`);
await wait('document.querySelector("[data-ws-drawer] [data-drawer-missing]")');
await b.navigate(`${base}/#/agents?agent=not-an-agent`);
await wait(`document.querySelector("[data-ws-agent-list]") && ${noDrawer}`);
});
test('the drawer holds at most one history entry: Close after switching agents, or after a shared link, stays in the Console', async t => {
const { b, base, wait } = await setup(t);
await wait(`document.querySelector(${JSON.stringify(rowLink('acme:coder'))})`);
const before = await b.evaluate('history.length');
await b.evaluate(`document.querySelector(${JSON.stringify(rowLink('acme:coder'))}).click()`);
await wait(open('acme:coder'));
// Another row while the drawer is open switches it in place: no second entry.
await b.evaluate(`document.querySelector(${JSON.stringify(rowLink('beta:pm'))}).click()`);
await wait(`${open('beta:pm')} && !${drawer('acme:coder')}`);
assert.equal(await b.evaluate(agentParam), 'beta:pm');
assert.equal(await b.evaluate('history.length'), before + 1);
// The open row again does nothing to the address.
await b.evaluate(`document.querySelector(${JSON.stringify(rowLink('beta:pm'))}).click()`);
assert.equal(await b.evaluate('history.length'), before + 1);
// One Close goes back to the page without the drawer.
await b.evaluate(`${drawer('beta:pm')}.querySelector("[data-drawer-close]").click()`);
await wait(`${noDrawer} && location.hash === "#/agents"`);
// A shared link opened after another site: clicking its row and then Close stays here.
await b.navigate('about:blank');
await b.navigate(`${base}/#/agents?agent=acme%3Acoder`);
await wait(open('acme:coder'));
await b.evaluate(`document.querySelector(${JSON.stringify(rowLink('acme:coder'))}).click()`);
await b.evaluate(`${drawer('acme:coder')}.querySelector("[data-drawer-close]").click()`);
await wait(`location.href.startsWith(${JSON.stringify(base)}) && ${noDrawer} && location.hash === "#/agents"`);
// Escape on a shared link does the same.
await b.navigate(`${base}/#/agents?agent=beta%3Apm`);
await wait(open('beta:pm'));
await b.key('Escape');
await wait(`location.href.startsWith(${JSON.stringify(base)}) && ${noDrawer} && location.hash === "#/agents"`);
});
test('the keyboard path: Tab reaches the row, Enter opens, Escape closes and focus returns to the row', async t => {
const { b, wait } = await setup(t);
const link = JSON.stringify(rowLink('acme:coder'));
await wait(`document.querySelector(${link})`);
// Focus the control just before the row's link, then Tab onto it.
await b.evaluate(`(() => { const all = [...document.querySelectorAll('a[href],button:not([disabled]),input,select,textarea,[tabindex]:not([tabindex="-1"])')].filter(e => e.getClientRects().length); const i = all.indexOf(document.querySelector(${link})); all[i - 1].focus(); })()`);
await b.key('Tab');
assert.equal(await b.evaluate(`document.activeElement === document.querySelector(${link})`), true);
await b.key('Enter');
await wait(open('acme:coder'));
// Focus moves into the drawer, onto its heading.
await wait(`document.activeElement === ${drawer('acme:coder')}.querySelector("h2")`);
await b.key('Escape');
await wait(`${noDrawer} && document.activeElement === document.querySelector(${link})`);
assert.equal(await b.evaluate(agentParam), null);
// Close does the same.
await b.key('Enter');
await wait(open('acme:coder'));
await b.evaluate(`${drawer('acme:coder')}.querySelector("[data-drawer-close]").click()`);
await wait(`${noDrawer} && document.activeElement === document.querySelector(${link})`);
});
test('from an organization page\'s Active agent sessions the drawer opens over that page', async t => {
const { b, base, wait, text, attr } = await setup(t, { hash: '#/orgs/acme/organization' });
await wait(`document.querySelector(${JSON.stringify(sessionLink('acme:coder'))})`);
assert.equal(await attr(sessionLink('acme:coder'), 'href'), '#/orgs/acme/organization?agent=acme%3Acoder');
await b.evaluate(`document.querySelector(${JSON.stringify(sessionLink('acme:coder'))}).click()`);
await wait(open('acme:coder'));
// The organization page stays under it.
assert.equal(await text('[data-org-dashboard] h1'), 'Acme Studio');
assert.match(await text('[data-ws-drawer="acme:coder"] [data-drawer-model]'), /claude-opus-5-5/);
await b.evaluate('history.back()');
await wait(`${noDrawer} && location.hash === "#/orgs/acme/organization"`);
assert.equal(await text('[data-org-dashboard] h1'), 'Acme Studio');
await b.navigate(`${base}/#/orgs/acme/organization?agent=acme%3Aassistant`);
await wait(open('acme:assistant'));
});
test('Message opens the agent\'s thread in an Assistant pane; Stop asks first and a refusal says why', async t => {
const { b, wait, text, attr, has } = await setup(t, { hash: '#/agents?agent=acme%3Aassistant' });
await wait(`${open('acme:assistant')} && document.querySelector('[data-ws-drawer="acme:assistant"] [data-drawer-message]')`);
assert.equal(await attr('[data-ws-drawer="acme:assistant"] [data-drawer-message]', 'href'), `#/assistant?add=acme%3A${THREAD}`);
// SP16: Message is offered, so no line says why it is not.
assert.equal(await has('[data-ws-drawer="acme:assistant"] [data-drawer-nomessage]'), false);
// It holds a conversation, whose messages read pages from the oldest message: the drawer says it does not read it.
assert.equal(await text('[data-ws-drawer="acme:assistant"] [data-drawer-activity]'), 'not shown: reading it means reading the whole conversation');
// A role agent holds no thread to open, so it has no Message; it can still be stopped.
await b.evaluate('location.hash = "#/agents?agent=acme%3Acoder"');
await wait(`${open('acme:coder')} && document.querySelector('[data-ws-drawer="acme:coder"] [data-drawer-stop]')`);
assert.equal(await has('[data-ws-drawer="acme:coder"] [data-drawer-message]'), false);
// SP16: and one line says why there is no Message.
assert.equal(await text('[data-ws-drawer="acme:coder"] [data-drawer-actions] [data-drawer-nomessage]'), 'No Message: this Console messages only conversation agents, such as the Assistant.');
const d = '[data-ws-drawer="acme:coder"]';
await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').click()`);
await wait(`document.querySelector('${d} [data-drawer-stop-yes]')`);
assert.match(await text(`${d} [data-drawer-stop-confirm]`), /Stop coder in Acme Studio\?/);
// Cancel: nothing sent, focus back on Stop.
await b.evaluate(`document.querySelector('${d} [data-drawer-stop-no]').click()`);
await wait(`document.activeElement === document.querySelector('${d} [data-drawer-stop]')`);
assert.deepEqual(await b.evaluate('window.__posts'), []);
// Yes: one terminate for this one agent, refused by the bus, in words next to the button.
await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').click()`);
await wait(`document.querySelector('${d} [data-drawer-stop-yes]')`);
await b.evaluate('window.__answers.push({ status: 409, body: { error: "instance-protected", message: "instance-protected: coder is protected from ending. Nothing changed.", sent: false } })');
await b.evaluate(`document.querySelector('${d} [data-drawer-stop-yes]').click()`);
await wait(`/coder is protected/.test(document.querySelector('${d} [data-drawer-status]')?.textContent ?? "")`);
assert.match(await text(`${d} [data-drawer-status]`), /^Not stopped: instance-protected: coder is protected from ending\. Nothing changed\.$/);
const posts = await b.evaluate('window.__posts');
assert.deepEqual(posts.map(p => [p.url, p.method]), [['/api/orgs/acme/agent/terminate', 'POST']]);
assert.deepEqual(JSON.parse(posts[0].body), { instance: 'coder', reason: 'Stopped from the agent drawer.' });
// The status sits beside the Stop button, in the same action group.
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-status]').closest('[data-drawer-actions]') === document.querySelector('${d} [data-drawer-stop]').closest('[data-drawer-actions]')`), true);
// A read-only refusal with no message from the server still says why.
await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').click()`);
await wait(`document.querySelector('${d} [data-drawer-stop-yes]')`);
await b.evaluate('window.__answers.push({ status: 403, body: { error: "read-only", sent: false } })');
await b.evaluate(`document.querySelector('${d} [data-drawer-stop-yes]').click()`);
await wait(`/read-only|only reads/.test(document.querySelector('${d} [data-drawer-status]')?.textContent ?? "")`);
assert.match(await text(`${d} [data-drawer-status]`), /^Not stopped: this Console only reads agents in Acme Studio \(read-only\)\.$/);
// Escape while it asks cancels only the question: the drawer stays and focus is back on Stop.
await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').click()`);
await wait(`document.querySelector('${d} [data-drawer-stop-no]') === document.activeElement`);
await b.key('Escape');
await wait(`!document.querySelector('${d} [data-drawer-stop-confirm]') && document.activeElement === document.querySelector('${d} [data-drawer-stop]')`);
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').disabled`), false);
assert.equal(await b.evaluate(agentParam), 'acme:coder');
assert.equal(await b.evaluate('window.__posts').then(p => p.length), 2);
// A Stop the bus takes: the request is followed until it closes, then the drawer says it stopped.
const REQ = '0f0e0d0c-0b0a-4908-8706-050403020100';
await b.evaluate(`window.__answers.push({ status: 200, body: { sent: true, request: '${REQ}' } }, { status: 200, body: { request: '${REQ}', state: 'closed' } })`);
await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').click()`);
await wait(`document.querySelector('${d} [data-drawer-stop-yes]')`);
await b.evaluate(`document.querySelector('${d} [data-drawer-stop-yes]').click()`);
await wait(`/^Stopped coder\.$/.test(document.querySelector('${d} [data-drawer-status]')?.textContent ?? "")`);
assert.deepEqual((await b.evaluate('window.__posts')).slice(2).map(p => [p.url, p.method]), [['/api/orgs/acme/agent/terminate', 'POST'], [`/api/orgs/acme/agent/request?id=${REQ}`, 'GET']]);
// A not-running agent has nothing to stop.
await b.evaluate('location.hash = "#/agents?agent=acme%3Achief"');
await wait(open('acme:chief'));
assert.equal(await has('[data-ws-drawer="acme:chief"] [data-drawer-stop]'), false);
assert.match(await text('[data-ws-drawer="acme:chief"] [data-drawer-nomessage]'), /^No Message: this Console messages only conversation agents/);
// Where Stop is not offered, the drawer says why beside the actions.
assert.match(await text('[data-ws-drawer="acme:chief"] [data-drawer-actions] [data-drawer-nostop]'), /^chief is one of Acme Studio’s protected agents, so it is not stopped from here\.$/);
});
test('no action is shown where the Console cannot write for the agent\'s organization', async t => {
const { wait, has, text } = await setup(t, { hash: '#/agents?agent=beta%3Apm' });
await wait(`${open('beta:pm')} && document.querySelector('[data-ws-drawer="beta:pm"] [data-drawer-readonly]')`);
const d = '[data-ws-drawer="beta:pm"]';
for (const action of ['message', 'nomessage', 'stop', 'restart']) assert.equal(await has(`${d} [data-drawer-${action}]`), false, `${action} should be absent`);
assert.match(await text(`${d} [data-drawer-readonly]`), /only reads Beta Works/);
});
test('at 390 wide the drawer is a full-width sheet', async t => {
const { b, wait } = await setup(t, { viewport: [390, 844], hash: '#/agents?agent=acme%3Acoder' });
await wait(open('acme:coder'));
const box = await b.evaluate(`(() => { const r = ${drawer('acme:coder')}.getBoundingClientRect(); return [Math.round(r.left), Math.round(r.width), document.documentElement.clientWidth, document.documentElement.scrollWidth]; })()`);
assert.equal(box[0], 0);
assert.equal(box[1], box[2]);
assert.ok(box[3] <= box[2], `no horizontal page scroll: ${box[3]} > ${box[2]}`);
});