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

374 lines
26 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', label: 'Coding' } } },
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 = [];
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 });
}
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 } = {}) {
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 });
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']]);
// No read gives the time of an agent's last activity. The sessions read's `since` is when its
// current state began, which is not the same thing, so the drawer draws no time.
assert.equal(await has(`${d} [data-drawer-activity]`), false);
// 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"]';
assert.match(await text(`${d} [data-drawer-role]`), /Hired from pack Coding/);
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('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', 'activity']) 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}`);
// 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);
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);
// 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', '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]}`);
});