Files
stack/packages/webui/tests/org-page-fit-browser.test.mjs

330 lines
23 KiB
JavaScript

// SP13 (#1873): the organization page fits its width, and four things seen live.
// 1. At every content width from 360 px up, with and without the agent drawer, nothing in the Settings
// card is cut off by its card and the page does not scroll sideways.
// 2. `#/orgs/<id>?query` is the organization page with the query kept; `?agent=` opens the drawer.
// 3. The drawer never says "not running" before its instances read has answered: while it is open the
// state is being read, after it fails the state was not read, and the Stop note says the same.
// 4. (SP14 removed the Queue card; the organization page now makes no queue read.)
// Plus the test SP12 left out: a repaint while Stop asks its question keeps the question on screen.
// SP14 (#1873): the page has no Queue card and makes no queue read; an instances answer with no runs says
// running was not read wherever a running or working count would show; and the drawer's instances answer
// repaints only the drawer, with no page read made again.
// Every bus is a fake. The real GET /api/workspace and per-organization routes serve the page; only the
// per-organization config, the agent writes and (when a test asks) the drawer's instances read 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();
function fixture({ counts = {} } = {}) {
const LIST = [{ id: 'acme', label: 'Acme Studio', theme: 'cobalt' }];
const d = {
projects: [{ id: 'p-site', repo: 'site', name: 'Website', archived: false, at: at(30) }],
tasks: [], inbox: [], threads: [],
agents: [{ role: 'coder', holder_run: 'run-1', harness: 'claude', state: 'working', at: at(40), working: { since: at(40), messages: 2 } }],
claims: [],
instances: {
coder: { definition: 'coder', running: ['run-1'] },
chief: { definition: 'chief-of-staff', running: [] },
reviewer: { definition: 'reviewer', running: [] },
},
// Long values, so a narrow Settings card has something to cut.
model: { coder: 'claude-opus-5-5', chief: 'claude-sonnet-5-5', reviewer: 'gpt-5.5-codex-high-reasoning' },
};
const value = name => Promise.resolve(d[name] ?? (['usage', 'limits'].includes(name) ? {} : []));
const opts = () => ({
bus: { inbox: () => value('inbox'), agents: () => value('agents'), 'thread.claims': () => value('claims'), tasks: () => value('tasks'), usage: () => value('usage'), limits: () => value('limits'), decisions: () => value('decisions') },
chat: { threads: () => value('threads'), projects: () => value('projects') },
});
const member = org => ({ id: org.id, doc: { appearance: { theme: org.theme } }, status: async () => ({ healthy: true, pid: 4242, boot: null }), options: opts });
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;
return {
busHealthy: true,
reads: {
business: async () => ({ business: { id, human: 'jason', projects: d.projects.map(p => p.repo), appearance: { theme: org.theme }, vars: { 'tracker.kind': 'gitea-issues-and-milestones' }, arbiters: { decisions: 'chief-of-staff', reviews: 'reviewer', merges: 'human-owner-of-the-organization' }, instances: Object.entries(d.model).map(([instance, model]) => ({ instance, vars: { model } })) } }),
settings: async () => ({}),
queue: async () => { counts.queue = (counts.queue ?? 0) + 1; return { 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: structuredClone(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. `window.__inst` set by
// a test holds ('hold', released by window.__release()) or fails ('fail') the first bus instances read,
// which is the drawer's: it starts before the page's own reads. With `window.__heldIdle` the held
// answer says nothing runs.
// Every URL the page fetches, in order, for the tests that count reads.
const URLS = `(() => { const real = window.fetch; window.__urls = []; window.fetch = (url, init) => { window.__urls.push(String(url)); return real(url, init); }; })();`;
// A bus answer the bus did not add runs to (its async read path): no `running` key on any instance.
const STRIP = `(() => { const real = window.fetch; window.fetch = async (url, init) => { const r = await real(url, init); if (!/\\/bus\\/instances$/.test(String(url)) || !r.ok) return r; const v = await r.json(); for (const row of [v, ...(v.rows || [])]) for (const i of Object.values(row?.instances || {})) delete i.running; return new Response(JSON.stringify(v), { status: 200, headers: { 'content-type': 'application/json' } }); }; })();`;
const STUB = `(() => {
const real = window.fetch.bind(window);
window.__posts = []; window.__answers = []; window.__instSeen = 0;
const answer = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
window.fetch = async (url, init = {}) => {
const u = String(url);
if (/\\/api\\/orgs\\/acme\\/bus\\/instances$/.test(u) && window.__instSeen++ === 0 && window.__inst) {
if (window.__inst === 'fail') return answer(502, { error: 'read-failed', message: 'the bus did not answer' });
await new Promise(done => { window.__release = done; });
if (!window.__heldIdle) return real(url, init);
// The held answer, when a test asks, says no instance runs anything.
const v = await (await real(url, init)).json();
for (const row of [v, ...(v.rows || [])]) for (const i of Object.values(row?.instances || {})) i.running = [];
return answer(200, v);
}
const cfg = u.match(/^\\/api\\/orgs\\/([^/]+)\\/config$/);
if (cfg) { const c = await (await real(url, init)).json(); return answer(200, { ...c, chatSend: true, settingsSend: true, decide: true }); }
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 = '#/orgs/acme/organization', inst = null, counts = {}, scripts = [] } = {}) {
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: fixture({ counts }), log: () => {} });
t.after(() => close(server));
const b = await browser({ machine: false }); t.after(() => b.close());
await b.viewport(...viewport);
if (inst) await b.call('Page.addScriptToEvaluateOnNewDocument', { source: `window.__inst = ${JSON.stringify(inst)};` });
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 has = sel => b.evaluate(`!!document.querySelector(${JSON.stringify(sel)})`);
return { b, base, wait: waitFor(b), text, 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 settled = 'document.querySelectorAll("[data-org-settings] [data-org-setting]").length > 10';
// Everything in the Settings card that is cut: a cell whose content is wider than its box, a cell that
// reaches past the card's edge or, from 1200 px, under the drawer, and a page that scrolls sideways.
const CLIPPED = `(() => {
const card = document.querySelector('[data-org-settings]'), r = card.getBoundingClientRect();
// From 1200 px the page keeps clear of the drawer (SP12); below that the drawer covers the page by design.
const d = innerWidth >= 1200 ? document.querySelector('[data-ws-drawer]')?.getBoundingClientRect() : null;
const edge = Math.min(r.right, d && d.left > 0 ? d.left : Infinity);
const out = [];
for (const li of card.querySelectorAll('[data-org-setting]')) {
for (const el of li.querySelectorAll('.k,.v,.src-tag,.go')) {
if (!el.textContent.trim()) continue;
const b = el.getBoundingClientRect();
if (el.scrollWidth > el.clientWidth + 1 || b.right > edge + 1 || b.left < r.left - 1) out.push(li.dataset.orgSetting + ' ' + el.className + ' ' + el.scrollWidth + '/' + el.clientWidth + ' right ' + Math.round(b.right) + '/' + Math.round(edge));
}
}
// The sessions table beside it scrolls only as a last resort; with these rows the columns stack first.
for (const tb of document.querySelectorAll('[data-org-dashboard] .ws-split .ws-tbl')) if (tb.scrollWidth > tb.clientWidth + 1) out.push('sessions table ' + tb.scrollWidth + '/' + tb.clientWidth);
const page = document.documentElement;
if (page.scrollWidth > page.clientWidth) out.push('page ' + page.scrollWidth + '/' + page.clientWidth);
return out;
})()`;
test('the Settings card fits at 1440 with the drawer open, at 735 and 390 without it, and at every width between', async t => {
const { b, base, wait } = await setup(t, { hash: '#/orgs/acme/organization?agent=acme%3Acoder' });
await wait(`${settled} && ${open('acme:coder')}`);
assert.deepEqual(await b.evaluate(CLIPPED), [], 'at 1440 with the drawer open');
// Each Open link keeps its whole word.
assert.ok(await b.evaluate(`[...document.querySelectorAll('[data-org-settings] a.go')].every(a => a.innerText.trim() === 'Open' && a.scrollWidth <= a.clientWidth + 1)`));
// Without the drawer: 735 and 390 wide, and a content width of about 735 (1023 with the sidebar).
for (const [w, h] of [[735, 900], [390, 844], [1023, 900]]) {
await b.viewport(w, h);
await b.navigate(`${base}/#/orgs/acme/organization`);
await wait(`${settled} && ${noDrawer}`);
assert.deepEqual(await b.evaluate(CLIPPED), [], `at ${w} without the drawer`);
}
// Every 40 px from 360 to 1440, with and without the drawer.
for (const hash of ['#/orgs/acme/organization', '#/orgs/acme/organization?agent=acme%3Acoder']) {
await b.navigate(`${base}/${hash}`);
await wait(`${settled} && ${hash.includes('agent') ? open('acme:coder') : noDrawer}`);
for (let w = 360; w <= 1440; w += 40) {
await b.viewport(w, 900);
await b.evaluate('new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))');
assert.deepEqual(await b.evaluate(CLIPPED), [], `at ${w}${hash.includes('agent') ? ' with the drawer' : ''}`);
}
}
// Side by side, both columns' first headings start level (the Workflows card wraps its heading).
await b.navigate(`${base}/#/orgs/acme/organization`);
await wait(`${settled} && ${noDrawer}`);
const tops = await b.evaluate(`[...document.querySelectorAll('#bus-view .ws-dash>.ws-split>section')].map(s => [Math.round(s.getBoundingClientRect().left), Math.round(s.querySelector('h2').getBoundingClientRect().top)])`);
assert.equal(tops.length, 2);
assert.notEqual(tops[0][0], tops[1][0], 'the columns sit side by side at 1440');
assert.equal(tops[0][1], tops[1][1], 'the first headings start level');
});
test('the bare organization address with a query is the organization page, query kept; ?agent= opens the drawer', async t => {
const { b, base, wait, text } = await setup(t, { hash: '#/orgs/acme?agent=acme%3Acoder' });
await wait(`document.querySelector('[data-org-dashboard] h1') && ${open('acme:coder')}`);
assert.equal(await text('[data-org-dashboard] h1'), 'Acme Studio');
assert.equal(await b.evaluate('!!document.querySelector("[data-org-unavailable]")'), false);
assert.equal(await b.evaluate('new URLSearchParams(location.hash.split("?")[1] || "").get("agent")'), 'acme:coder');
assert.match(await b.evaluate('location.hash'), /^#\/orgs\/acme\/organization\?agent=acme%3Acoder$/);
// The reads are scoped to acme, never to "acme?agent=…".
assert.equal(await b.evaluate('window.MosaicOrg?.id'), 'acme');
// Another query, no drawer: the same page with the query kept.
await b.navigate(`${base}/#/orgs/acme?tab=settings`);
await wait(`document.querySelector('[data-org-dashboard] h1')?.innerText === 'Acme Studio'`);
assert.equal(await b.evaluate('location.hash'), '#/orgs/acme/organization?tab=settings');
assert.equal(await b.evaluate('!!document.querySelector("[data-ws-drawer]")'), false);
// Typed into the address bar of a page already open.
await b.evaluate('location.hash = "#/orgs/acme?agent=acme%3Achief"');
await wait(open('acme:chief'));
assert.equal(await text('[data-org-dashboard] h1'), 'Acme Studio');
});
test('while the drawer\'s instances read is open it says the state is being read, never not running, then shows it', async t => {
const { b, wait, text, has } = await setup(t, { hash: '#/orgs/acme/organization?agent=acme%3Acoder', inst: 'hold', scripts: [URLS] });
const d = '[data-ws-drawer="acme:coder"]';
await wait(`${settled} && ${open('acme:coder')}`);
assert.equal(await has(`${d}[data-drawer-pending]`), true);
assert.equal(await text(`${d} [data-drawer-state]`), 'Reading state…');
assert.doesNotMatch(await text(d), /not running/);
// Stop is not offered yet, and its note says why without saying not running.
assert.equal(await has(`${d} [data-drawer-stop]`), false);
assert.match(await text(`${d} [data-drawer-nostop]`), /^Its state is being read\./);
// The page under it painted from its own reads: coder is a running session there.
assert.match(await text('[data-ws-session-agent="acme:coder"]'), /working/);
// When the read answers, the drawer repaints with the state, and Stop. SP14: only the drawer repaints,
// from the reads it already has: the page and its reads are left alone, and focus stays where it was.
await b.evaluate(`document.querySelector('[data-org-dashboard]').dataset.before = '1'; document.querySelector('${d} [data-drawer-close]').focus(); window.__urls.length = 0`);
await b.evaluate('window.__release()');
await wait(`!document.querySelector('${d}[data-drawer-pending]') && document.querySelector('${d} [data-drawer-stop]')`);
assert.match(await text(`${d} [data-drawer-state]`), /(^|\s)working$/);
assert.equal(await has(`${d} [data-drawer-nostop]`), false);
await b.evaluate('new Promise(r => setTimeout(r, 400))');
assert.deepEqual(await b.evaluate(`window.__urls.filter(u => /^\\/api\\/(workspace|orgs\\/)/.test(u))`), [], 'no read is made again after the drawer\'s read answers');
assert.equal(await b.evaluate(`document.querySelector('[data-org-dashboard]').dataset.before`), '1', 'the page under the drawer was not repainted');
assert.equal(await b.evaluate('document.activeElement?.dataset?.focusKey'), 'drawer-close');
});
test('SP14 review: another agent opened while the drawer\'s instances read is open repaints when that read answers', async t => {
const { b, wait, text, has } = await setup(t, { hash: '#/orgs/acme/organization?agent=acme%3Acoder', inst: 'hold' });
await wait(`${settled} && document.querySelector('[data-ws-drawer="acme:coder"][data-drawer-pending]')`);
// Chief opens before the held read answers; its drawer waits on the same read.
await b.evaluate('location.hash = "#/orgs/acme/organization?agent=acme%3Achief"');
const d = '[data-ws-drawer="acme:chief"]';
await wait(`document.querySelector('${d}[data-drawer-pending]')`);
assert.equal(await text(`${d} [data-drawer-state]`), 'Reading state…');
// The read answers. Chief's drawer repaints from it at once, not at the next poll.
await b.evaluate('window.__release()');
await b.evaluate('new Promise(r => setTimeout(r, 1000))');
assert.equal(await has(`${d}[data-drawer-pending]`), false, 'chief\'s drawer still says Reading state… after its read answered');
assert.match(await text(`${d} [data-drawer-state]`), /not running/);
assert.equal(await has('[data-ws-drawer="acme:coder"]'), false);
});
test('a drawer closed before its instances read answers keeps no answer for the next open', async t => {
const idle = 'window.__heldIdle = true;';
const { b, wait, text } = await setup(t, { hash: '#/orgs/acme/organization?agent=acme%3Acoder', inst: 'hold', scripts: [idle] });
const d = '[data-ws-drawer="acme:coder"]';
await wait(`${settled} && document.querySelector('${d}[data-drawer-pending]')`);
await b.evaluate(`document.querySelector('${d} [data-drawer-close]').click()`);
await wait(noDrawer);
// The held read answers after the drawer closed, saying coder runs nothing.
await b.evaluate('window.__release()');
await b.evaluate('new Promise(r => setTimeout(r, 300))');
// Reopened from its row, the drawer reads again and shows coder working, not the closed drawer's answer.
await b.evaluate(`document.querySelector('[data-ws-drawer-open="acme:coder"]').click()`);
await wait(`${open('acme:coder')} && !document.querySelector('${d}[data-drawer-pending]') && document.querySelector('${d} [data-drawer-state]')`);
assert.match(await text(`${d} [data-drawer-state]`), /(^|\s)working$/);
assert.doesNotMatch(await text(d), /not running/);
});
test('after the drawer\'s instances read fails it says the state was not read, and Stop says so too', async t => {
const { b, wait, text, has } = await setup(t, { hash: '#/orgs/acme/organization?agent=acme%3Areviewer', inst: 'fail' });
const d = '[data-ws-drawer="acme:reviewer"]';
await wait(`${settled} && ${open('acme:reviewer')}`);
assert.equal(await has(`${d}[data-drawer-pending]`), false);
assert.match(await text(`${d} [data-drawer-state]`), /^State not read: /);
assert.doesNotMatch(await text(d), /not running/);
assert.equal(await has(`${d} [data-drawer-stop]`), false);
assert.equal(await text(`${d} [data-drawer-nostop]`), 'Its state was not read, so Stop is not offered.');
// A later repaint reads again: reviewer runs nothing, so now it says not running, with that reason.
await b.evaluate('document.dispatchEvent(new CustomEvent("mosaic-workspace-render"))');
await wait(`/not running/.test(document.querySelector('${d} [data-drawer-state]')?.innerText ?? '')`);
assert.equal(await text(`${d} [data-drawer-nostop]`), 'It is not running, so there is nothing to stop.');
});
test('an instances answer that carries no runs says state not read, in the drawer and on the Agents table', async t => {
const { wait, text, has } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', scripts: [STRIP] });
const d = '[data-ws-drawer="acme:coder"]';
await wait(`${open('acme:coder')} && document.querySelector('[data-ws-agent="acme:coder"]')`);
assert.match(await text(`${d} [data-drawer-state]`), /state not read$/);
assert.equal(await text(`${d} [data-drawer-nostop]`), 'Its state was not read, so Stop is not offered.');
assert.match(await text('[data-ws-agent="acme:coder"]'), /state not read/);
assert.doesNotMatch(await text('[data-ws-agent-list]'), /not running/);
assert.equal(await has('[data-ws-astate="not-read"]'), true);
});
test('SP14: the organization page has no Queue card and makes no queue read', async t => {
const counts = {};
const { b, wait, has } = await setup(t, { counts, scripts: [URLS] });
await wait(`${settled} && document.querySelector('[data-ws-session-agent="acme:coder"]')`);
await b.evaluate('new Promise(r => setTimeout(r, 400))');
assert.equal(await has('[data-org-queue]'), false);
assert.equal(await has('[data-org-queue-why]'), false);
const heads = await b.evaluate(`[...document.querySelectorAll('[data-org-dashboard] h2, [data-org-dashboard] h3')].map(h => h.textContent.trim())`);
assert.ok(heads.includes('Active agent sessions'), heads.join(' | '));
assert.ok(!heads.some(h => /^Queue\b/.test(h)), heads.join(' | '));
assert.deepEqual(await b.evaluate('window.__urls.filter(u => /queue/i.test(u))'), []);
assert.equal(counts.queue ?? 0, 0, 'the server read no queue');
});
test('SP14: an instances answer with no runs says running was not read on the organization page and the Dashboard, never 0', async t => {
const { b, base, wait, text, has } = await setup(t, { scripts: [STRIP] });
await wait(`${settled} && document.querySelector('[data-org-dashboard] [data-ws-tile="agents"]')`);
const sec = await b.evaluate(`[...document.querySelectorAll('[data-org-dashboard] .ws-sec-h')].find(h => h.querySelector('h2')?.textContent === 'Active agent sessions')?.innerText.replace(/\\s+/g, ' ').trim()`);
assert.match(sec, /^Active agent sessions running not read /);
assert.doesNotMatch(sec, /none running|\b0 running/);
assert.equal(await text('[data-runs-unread]'), 'Not read: the instance read did not say which agents run.');
assert.equal(await text('[data-org-dashboard] [data-ws-tile="agents"]'), 'Agents working Not read: the instance read did not say which agents run');
assert.equal(await has('[data-org-dashboard] [data-ws-tile="agents"] .ws-big'), false);
assert.equal(await text('[data-org-setting="Agents and roles"] .v'), '3 agents · running not read');
// The Dashboard: the tile counts no organization whose runs were not read and names it; its row says so.
await b.navigate(`${base}/#/dashboard`);
await wait(`document.querySelector('[data-ws-tile="agents"]') && document.querySelector('[data-ws-orgrow="acme"]')`);
const tile = await text('[data-ws-tile="agents"]');
assert.match(tile, /^Agents working Not read Acme Studio \(running not read\)$/);
assert.equal(await has('[data-ws-tile="agents"] .ws-big'), false);
const row = await text('[data-ws-orgrow="acme"]');
assert.match(row, /3 agents \(running not read\)/);
assert.doesNotMatch(row, /\b0 running|0 working/);
});
test('a repaint while Stop asks its question keeps the question on screen and Stop disabled', async t => {
const { b, wait, has } = await setup(t, { hash: '#/orgs/acme/organization?agent=acme%3Acoder' });
const d = '[data-ws-drawer="acme:coder"]';
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-stop]')`);
await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').click()`);
await wait(`document.querySelector('${d} [data-drawer-stop-yes]')`);
// Mark the drawer, so the test knows the repaint replaced it.
await b.evaluate(`document.querySelector('${d}').dataset.before = '1'`);
await b.evaluate('document.dispatchEvent(new CustomEvent("mosaic-workspace-render"))');
await wait(`document.querySelector('${d}') && !document.querySelector('${d}').dataset.before`);
assert.equal(await has(`${d} [data-drawer-stop-confirm]`), true);
assert.equal(await has(`${d} [data-drawer-stop-yes]`), true);
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').disabled`), true);
assert.deepEqual(await b.evaluate('window.__posts'), []);
});