diff --git a/packages/webui/src/public/workspace.js b/packages/webui/src/public/workspace.js index 44fac0663..3f5df5519 100644 --- a/packages/webui/src/public/workspace.js +++ b/packages/webui/src/public/workspace.js @@ -367,12 +367,12 @@ ${orgTiles} ${docrow}
-
+
${secH('Active agent sessions', live ? (noRuns ? 'running not read' : live.length ? `${live.length} running${tileAgents ? `, ${liveWorking} working` : ', working not read'}` : 'none running') : '', `This organization's agents`)} ${sessions} -
-
${window.MosaicWorkflows?.card?.(id, { stopped, label: label(org) }) ?? ''} +
+
${secH('Settings', 'every setting, with where its value comes from')} ${settingsList(org, { business, settings, instances, noRuns, orgCount: list ? list.length : null })}
@@ -638,7 +638,7 @@ const bar = (o, parts, style = '') => ``; const by = (o, parts, fmt = n => n) => `
${parts.map(p => `${av(o.meta(p.id))}${esc(o.name(p.id))}${esc(fmt(p.n))}`).join('')}
`; // Why an organization's instances read gave nothing, in a word or two. - const READ_ERR = { 403: 'refused', 0: 'signed out' }; + const READ_ERR = { 401: 'signed out', 403: 'refused', 0: 'signed out' }; const instWhy = r => READ_ERR[r.err?.status] || r.err?.code || 'no answer'; // SP8 (#1873): one KPI tile, a link to the page that lists what it counts. A tile with no figure // (`big` null) is drawn quiet with `none` in its place; `miss` names the organizations the figure @@ -1141,17 +1141,91 @@ } // SP13 (#1873): the drawer's instances read gives the agent's state. The drawer does not hold the // page for it: once the page's own reads have answered (`opts.page`), a drawer whose instances read - // has not says its state is being read, and repaints when the read answers. That answer is kept for - // the one repaint it asks for; a repaint while the read is still open waits on the same read. + // has not says its state is being read, and repaints when the read answers. A repaint while the read + // is still open waits on the same read; once it answers it is let go, so the next render reads again. let drawerInst = null, drawerReads = 0; // { org, n, done, value, p } + // Repaints whose read answered before their drawer was on screen, keyed by the drawer's + // data-drawer-pending and its agent id. A drawer never painted (closed, or replaced by a later paint) + // leaves its entry; the oldest go first. + const drawerLate = new Map(), DRAWER_LATE_MAX = 8; const drawerInstRead = org => { if (drawerInst?.org === org) return drawerInst; const r = { org, n: ++drawerReads, done: false, value: null }; r.p = data.instances(org).then(v => ({ inst: instancesOf(v), copies: copiesOf(v) }), err => ({ inst: null, copies: {}, err })) .then(v => { r.done = true; r.value = v; return v; }); + r.p.then(() => { if (drawerInst === r) drawerInst = null; }); drawerInst = r; return r; }; + // SP16 (#1873): the template a pack hire was hired from. Only the packs read names it (owner only): + // the pack's hire of this name points at a definition, and that definition at a template. It is read + // only for an organization agent the instances read says a pack hired. The answer is kept per + // organization for DRAWER_PACKS_KEEP ms, and a repaint draws from the kept answer, also while a newer + // read is open, so the line does not change on every poll and a poll does not read packs each time. + // A kept answer that is of no use for this hire is read again at once (SP16 review 3): a refusal or no + // answer on each render, so the line recovers with the route; an answer that does not name this hire + // (a hire made after it was read) once per hire until the keep runs out, so a hire the pack really + // does not name does not read packs on every poll. `p` is given only when the drawer should repaint + // on it: nothing is kept, or the kept answer is of no use for this hire. `value` is then the kept + // refusal, or nothing (the line says being read) rather than a kept answer that does not name it. + // `start` false only looks: the drawer's second look after its race starts no read. + // The pack is the one installed now; the read does not say which version the hire was made from. + // It never rejects: a refusal, no answer or an answer that is not the packs list each give `err`. + const drawerPacksKept = new Map(), DRAWER_PACKS_KEEP = 60000; // org -> { at, value, p, asked } + const drawerPacks = (org, instValue, key, start = true) => { + const item = instValue?.inst?.[key]; + if (!item || !isHired(item) || typeof item.pack?.id !== 'string') return null; + let k = drawerPacksKept.get(org); + if (!k) drawerPacksKept.set(org, (k = { at: 0, value: null, p: null, asked: new Set() })); + const v = k.value, named = !!v && !v.err && !!packTemplate(item, key, v).template; + const expired = !v || Date.now() - k.at >= DRAWER_PACKS_KEEP; + const again = !!v && (!!v.err || (!named && !k.asked.has(key))); + if (start && !k.p && (expired || again)) { + if (expired) k.asked.clear(); + if (v && !v.err && !named) k.asked.add(key); + const kept = k; + kept.p = fetch(`/api/orgs/${enc(org)}/packs`, { cache: 'no-store', redirect: 'manual' }).then(async r => { + if (!r.ok || r.type === 'opaqueredirect') return { err: { status: r.type === 'opaqueredirect' ? 0 : r.status } }; + const v = await r.json().catch(() => null); + return Array.isArray(v?.packs) ? { packs: v.packs } : { err: { code: 'no answer' } }; + }).catch(() => ({ err: { code: 'no answer' } })).then(v => { kept.value = v; kept.at = Date.now(); kept.p = null; return v; }); + } + const wait = k.p && !named ? k.p : null; + return { value: wait && v && !v.err ? null : v, p: wait }; + }; + // The pack's own label and the template its hire of this name is made from, from the packs read. The + // instance names only the pack's id; the installed pack's document carries its label. + const packTemplate = (item, name, read) => { + const pk = item?.pack, doc = arr(read?.packs).find(p => p?.id === pk?.id && (pk?.origin == null || p?.origin === pk.origin))?.pack; + const hire = arr(doc?.hires).find(h => h?.name === name); + const entry = typeof hire?.definition === 'string' && doc?.definitions && typeof doc.definitions === 'object' ? doc.definitions[hire.definition] : null; + const t = entry?.template ?? entry?.from?.template; + return { template: typeof t === 'string' && t ? t : '', label: typeof doc?.label === 'string' && doc.label ? doc.label : '' }; + }; + // Swaps a drawer still on screen for `html`, keeping focus, and runs at once a repaint already waiting + // on the fresh drawer's marker (its packs read answered before this drawer was painted). + const drawerSwap = (node, html) => { + const key = focusKey(node), tpl = document.createElement('template'); + tpl.innerHTML = html; + const fresh = tpl.content.firstElementChild; + if (!fresh) return; + node.replaceWith(fresh); + refocus(fresh, key); + drawerLateRun(fresh); + }; + function drawerLateRun(node) { + const k = `${node.dataset.drawerPending}:${node.dataset.wsDrawer}`, redo = node.dataset.drawerPending ? drawerLate.get(k) : null; + if (redo) { drawerLate.delete(k); redo(node); } + } + // Repaints the drawer that carries `mark` once `p` answers: now if it is on screen, else once it is + // painted. `build(answer)` runs when the read answers and gives what draws the drawer at the swap. + const drawerWhen = (p, mark, id, build) => p.then(v => { + const draw = build(v), redo = node => drawerSwap(node, draw()); + const node = document.querySelector(`#bus-view [data-ws-drawer="${CSS.escape(id)}"][data-drawer-pending="${mark}"]`); + if (node) { redo(node); return; } + drawerLate.set(`${mark}:${id}`, redo); + while (drawerLate.size > DRAWER_LATE_MAX) drawerLate.delete(drawerLate.keys().next().value); + }); async function agentDrawer(q, opts = {}) { const pick = agentPick(q); if (!pick || (opts.only && pick.org !== opts.only)) return ''; @@ -1163,46 +1237,71 @@ typeof opts.configIn === 'function' ? Promise.resolve(opts.configIn(org)).catch(() => null) : null, ensureThemes(), ]); - await Promise.race([ir.p, opts.page ?? ir.p]); - const pending = !ir.done; - // SP14 (#1873): when the read answers, only the drawer repaints, from the reads it already has; the - // page's own reads are not made again. Each open repaints its own drawer if it is still on screen and - // still waits on this read (data-drawer-pending names the read), so a second agent opened while the - // read was open repaints too. A closed drawer repaints nothing, and the answer is not kept for a later open. - if (pending) ir.p.then(() => { - if (drawerInst === ir) drawerInst = null; - const node = document.querySelector(`#bus-view [data-ws-drawer="${CSS.escape(id)}"][data-drawer-pending="${ir.n}"]`); - if (!node) return; - const key = focusKey(node), tpl = document.createElement('template'); - tpl.innerHTML = drawerHtml(pick, { body, business, config, pending: false, instRead: ir.value }); - const fresh = tpl.content.firstElementChild; - if (!fresh) return; - node.replaceWith(fresh); - refocus(fresh, key); - }); - else if (drawerInst === ir) drawerInst = null; - return drawerHtml(pick, { body, business, config, pending: pending && ir.n, instRead: pending ? null : ir.value }); + const page = opts.page ?? null; + const html = (instRead, packs, pending) => drawerHtml(pick, { body, business, config, pending, instRead, packs }); + // Each read the drawer waits on is raced against the page's reads (SP16 review), so neither the + // instances read nor a pack hire's packs read holds the page's paint. + await Promise.race([ir.p, page ?? ir.p]); + // SP14 (#1873): when a read answers, only the drawer repaints, from the reads it already has; the + // page's own reads are not made again. data-drawer-pending names the read it waits on: `` for the + // instances read, `p` for the packs read after it, so each repaint finds only its own drawer. A + // closed drawer repaints nothing. SP16: a read can answer after this HTML is returned and before the + // page that carries it is on screen; then the repaint waits in drawerLate, and afterPaint runs it. + // When the instances read answers, the state is drawn at once, and the template line, if its packs + // read is still open with nothing of use kept, says it is being read (or the kept refusal) and + // repaints when that read answers. + const packsStage = instRead => { + const pk = drawerPacks(org, instRead, pick.key); + if (pk?.p) drawerWhen(pk.p, `${ir.n}p`, id, v => () => html(instRead, v, false)); + return { packs: pk?.value ?? null, pending: pk?.p ? `${ir.n}p` : false }; + }; + if (!ir.done) { + drawerWhen(ir.p, ir.n, id, v => { const s = packsStage(v); return () => html(v, s.packs, s.pending); }); + return html(null, null, ir.n); + } + let pk = drawerPacks(org, ir.value, pick.key); + if (pk?.p) { + await Promise.race([pk.p, page ?? pk.p]); + pk = drawerPacks(org, ir.value, pick.key, false); + } + if (pk?.p) { + drawerWhen(pk.p, `${ir.n}p`, id, v => () => html(ir.value, v, false)); + return html(ir.value, pk.value, `${ir.n}p`); + } + return html(ir.value, pk?.value ?? null, false); } - function drawerHtml(pick, { body, business, config, pending, instRead }) { + function drawerHtml(pick, { body, business, config, pending, instRead, packs = null }) { const { org, key, id } = pick; const o = orgsOf(body), orgName = o.name(org); const close = ``; const shell = (title, inner, attrs = '') => ``; // While the instances read is open, or after it failed, the agent's name is the address's and its - // role, source and state are not known: the state says so, and Stop gives that as its reason. - const unknown = pending ? 'Reading state…' : !instRead?.inst ? `State not read: ${esc(instWhy(instRead || {}))}.` : ''; + // role, source and state are not known: the state says so, and Stop gives that as its reason. A drawer + // can be pending with its instances read answered, while a pack hire's packs read is still open. + const reading = pending && !instRead; + const unknown = reading ? 'Reading state…' : !instRead?.inst ? `State not read: ${esc(instWhy(instRead || {}))}.` : ''; const a = unknown ? { org, key, name: key, level: 'org', keep: false, item: {}, s: arr(body?.sessions).find(x => x?.kind === 'role' && x.org === org && x.role === key) || null } : agentRows([{ id: org, inst: instRead.inst, copies: instRead.copies }], body).find(r => r.key === key); if (!a) return shell(key, `

No agent named ${esc(key)} was read in ${esc(orgName)}.

`); const wsRow = arr(body?.orgs).find(r => r?.org === org) ?? null; const notRead = names => (!body ? 'the read did not answer' : wsRow?.state !== 'ok' ? busWord({ busStopped: wsRow?.state === 'stopped' }) : missOf(wsRow, names)); const field = (attr, term, value) => `
${term}
${value}
`; - // Role and where it came from. A hired agent reads as hired; no read names the template it was hired from. + // Role and where it came from. A hired agent reads as hired; Hired from below names its pack. const item = a.item || {}, def = typeof item.definition === 'string' ? item.definition : ''; const hire = typeof item.hireDecision === 'string' ? item.hireDecision : /^org:hire-(.+)$/.exec(def)?.[1] || ''; const source = a.level === 'org' ? (isHired(item) ? `Hired${hire ? ` by hire decision ${esc(hire)}` : ''}${def ? `, definition ${esc(def)}` : ''}` : `Organization agent${def ? `, definition ${esc(def)}` : ''}`) : `${a.level === 'project' ? `Project agent copy${a.project?.name ? ` for ${esc(a.project.name)}` : ''}` : 'Root agent copy'}${def ? `, definition ${esc(def)}` : ''}${a.id ? `. ${esc(a.id)}` : ''}`; + // SP16: where a hired agent's role came from. A pack hire names its pack and, from the packs read, + // the template; no read names the template of a hire made outside a pack. + let hiredFrom = ''; + if (a.level === 'org' && isHired(item)) { + if (packOf(item)) { + const { template: t, label } = packTemplate(item, key, packs); + hiredFrom = `Pack ${esc(label || packOf(item))}, ${t ? `template ${esc(t)} as the installed pack names it` + : `template ${!packs && pending ? 'being read…' : packs?.err ? `not read: ${esc(instWhy(packs))}` : 'not named in the packs read'}`}`; + } else hiredFrom = 'Template not recorded: no read names the template of a hire made outside a pack.'; + } const model = business?.business?.instances?.find(i => i?.instance === key)?.vars?.model; // Its project and task: the role session's (the task it holds, and that task's project), else the // project of the conversation its live run holds. @@ -1229,10 +1328,18 @@ const acts = []; if (chat && thread?.thread) acts.push(`Message ${esc(a.name)}`); else if (chat && a.level === 'org' && window.MosaicAgents?.isThread?.(def)) acts.push(`Message ${esc(a.name)} Start one from New thread in ${esc(orgName)}.`); + // SP16: where no Message is offered, one line says why. The Console opens a conversation only in an + // Assistant pane, with a conversation agent; a role agent takes messages on the bus, which an + // organizations Console does not send. + else if (chat) acts.push(`

${reading ? 'No Message: its state is being read, so it is not known whether it holds a conversation.' + : unknown ? `No Message: its state was not read (${esc(instWhy(instRead || {}))}), so it is not known whether it holds a conversation.` + : a.level !== 'org' ? 'No Message: a copy is not messaged from here.' + : 'No Message: this Console messages only conversation agents, such as the Assistant.'}

`); + else if (change) acts.push(`

No Message: this Console does not send chat in ${esc(orgName)}.

`); if (change && a.level === 'org' && !a.keep && running(item) > 0) acts.push(stopActions(pick, a, orgName)); // Why Stop is not offered, in words, where this Console could otherwise change the organization's agents. // SP13: "not running" is a reason only once the instances read has given the agent's runs. - else if (change) acts.push(`

${pending ? 'Its state is being read. Stop is offered once it is read and the agent is running.' + else if (change) acts.push(`

${reading ? 'Its state is being read. Stop is offered once it is read and the agent is running.' : unknown || !runsRead(item) ? 'Its state was not read, so Stop is not offered.' : a.level !== 'org' ? 'A copy is not stopped from here.' : a.keep ? `${esc(a.name)} is one of ${esc(orgName)}’s protected agents, so it is not stopped from here.` @@ -1243,12 +1350,19 @@ : `

This Console only reads ${esc(orgName)}. It can not message or stop its agents.

`; const fields = [ field('org', 'Organization', orgChip(o, org)), - unknown ? '' : field('role', 'Role', `${esc(a.role)}`), + // A pack hire's pack is named once, in Hired from; the Role row says only that it was hired. + unknown ? '' : field('role', 'Role', `${esc(hiredFrom && packOf(item) ? 'Hired' : a.role)}`), unknown ? '' : field('source', 'Source', source), + hiredFrom ? field('hired', 'Hired from', hiredFrom) : '', field('state', 'State', unknown ? `${unknown}` : dot(...a.dot, true)), model ? field('model', 'Model', `${esc(model)}`) : '', project ? field('project', 'Project', `${esc(project.name || project.key || project.id)}${project.from ? ` ${project.from}` : ''}`) : '', task ? field('task', 'Task', `${esc(task.title || task.ref)}${task.title ? ` ${esc(task.ref)}` : ''}`) : '', + // SP16: no read the Console makes carries the time of a role agent's last message or run. The agents + // read's time is when it took the role and `since` is when its present state began, so neither is shown. + // An agent holding a conversation has its messages in that thread's messages read, but that read pages + // from the oldest message, so its last message is a walk of every page away; the drawer does not make it. + field('activity', 'Last activity', `${thread?.thread ? 'not shown: reading it means reading the whole conversation' : 'not recorded'}`), ].join(''); return shell(a.name, `
${fields}

Open tasks

${tasksBody}${tasksAll}
@@ -1266,6 +1380,7 @@ // bus.js calls this after each paint: focus moves into a drawer a row opened, and back to the row // when the drawer has closed and focus was left nowhere. function afterPaint() { + for (const node of document.querySelectorAll('#bus-view [data-ws-drawer][data-drawer-pending]')) drawerLateRun(node); const view = document.getElementById('bus-view'), d = view?.querySelector('[data-ws-drawer]'); const now = d?.dataset.wsDrawer || null, was = drawerShown; drawerShown = now; diff --git a/packages/webui/tests/agent-drawer-browser.test.mjs b/packages/webui/tests/agent-drawer-browser.test.mjs index 6e2a8cb08..31b6d93c3 100644 --- a/packages/webui/tests/agent-drawer-browser.test.mjs +++ b/packages/webui/tests/agent-drawer-browser.test.mjs @@ -48,7 +48,7 @@ function fixture() { 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' } } }, + instances: { pm: { definition: 'pm', running: ['run-9'] }, 'research-2': { definition: `org:hire-${HIRE}`, hireDecision: HIRE, running: [], pack: { id: 'coding', origin: 'shipped', project: null } } }, model: {}, }, }; @@ -84,7 +84,8 @@ function fixture() { // 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.__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); @@ -94,6 +95,18 @@ const STUB = `(() => { 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(); @@ -102,12 +115,13 @@ const STUB = `(() => { }; })();`; -async function setup(t, { viewport = [1440, 900], hash = '#/agents', stub = true } = {}) { +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`); @@ -171,9 +185,13 @@ test('the drawer shows each field from its read: name, organization, role and so // 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); + // 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'`); @@ -186,19 +204,200 @@ test('a hired agent shows where its role came from; a not-running agent says not 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/); + // 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 = "proxy error";'] }); + 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', 'activity']) assert.equal(await has(`${d} [data-drawer-${field}]`), false, `${field} should be absent`); + 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/); @@ -300,10 +499,16 @@ test('Message opens the agent\'s thread in an Assistant pane; Stop asks first an 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]')`); @@ -351,6 +556,7 @@ test('Message opens the agent\'s thread in an Assistant pane; Stop asks first an 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\.$/); }); @@ -359,7 +565,7 @@ test('no action is shown where the Console cannot write for the agent\'s organiz 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`); + 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/); }); diff --git a/packages/webui/tests/org-page-fit-browser.test.mjs b/packages/webui/tests/org-page-fit-browser.test.mjs index c8c9fdb7b..c0756e952 100644 --- a/packages/webui/tests/org-page-fit-browser.test.mjs +++ b/packages/webui/tests/org-page-fit-browser.test.mjs @@ -171,6 +171,15 @@ test('the Settings card fits at 1440 with the drawer open, at 735 and 390 withou 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'); + // SP16: the Workflows card sits under Active agent sessions, so the left column is not empty below + // the sessions and the Settings column holds Settings alone. How near level the two end depends on + // how many agents the sessions list has; the Settings card is the taller with three. + const cols = await b.evaluate(`[...document.querySelectorAll('#bus-view .ws-dash>.ws-split>section')].map(s => ({ wf: !!s.querySelector('[data-wfg-card]'), heads: [...s.querySelectorAll('h2')].map(h => h.textContent.trim()) }))`); + assert.deepEqual(cols.map(c => c.wf), [true, false], `the Workflows card is in the left column: ${JSON.stringify(cols)}`); + assert.equal(cols[0].heads[0], 'Active agent sessions'); + assert.deepEqual(cols[1].heads, ['Settings']); + const gap = await b.evaluate(`(() => { const left = document.querySelector('#bus-view .ws-dash>.ws-split>section'), card = left.querySelector('[data-wfg-card]'), above = card.previousElementSibling; return Math.round(card.getBoundingClientRect().top - above.getBoundingClientRect().bottom); })()`); + assert.ok(gap >= 0 && gap <= 40, `the Workflows card follows the sessions directly: ${gap}px`); }); test('the bare organization address with a query is the organization page, query kept; ?agent= opens the drawer', async t => { @@ -234,6 +243,28 @@ test('SP14 review: another agent opened while the drawer\'s instances read is op assert.equal(await has('[data-ws-drawer="acme:coder"]'), false); }); +// SP16 (#1873): the page's own metrics read, held when a test asks, so the drawer's instances read can +// answer after the drawer's HTML is built and before the page that carries it is on screen. +const HOLD_WS = `(() => { const real = window.fetch; let held = false; window.fetch = async (url, init) => { const u = String(url); if (!held && /^\\/api\\/workspace\\?/.test(u) && /metrics/.test(u)) { held = true; await new Promise(done => { window.__releaseWs = done; }); } return real(url, init); }; })();`; + +test('SP16: a drawer whose instances read answers after its HTML is built, before it is on screen, still repaints', async t => { + const { b, wait, text, has } = await setup(t, { hash: '#/orgs/acme/organization?agent=acme%3Acoder', inst: 'hold', scripts: [HOLD_WS] }); + const d = '[data-ws-drawer="acme:coder"]'; + // The page's metrics read is held; the page's other reads answer, so the drawer builds its pending HTML. + await wait('typeof window.__releaseWs === "function" && typeof window.__release === "function"'); + await b.evaluate('new Promise(r => setTimeout(r, 600))'); + assert.equal(await has(d), false, 'the page is not on screen yet'); + // The instances read answers in the gap, then the page paints. + await b.evaluate('window.__release()'); + await b.evaluate('new Promise(r => setTimeout(r, 200))'); + await b.evaluate('window.__releaseWs()'); + await wait(`${settled} && ${open('acme:coder')}`); + await b.evaluate('new Promise(r => setTimeout(r, 1000))'); + assert.equal(await has(`${d}[data-drawer-pending]`), false, 'the drawer still says Reading state… after its read answered'); + assert.match(await text(`${d} [data-drawer-state]`), /(^|\s)working$/); + assert.equal(await has(`${d} [data-drawer-stop]`), true); +}); + 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] }); diff --git a/packages/webui/tests/unified-workspace-browser.test.mjs b/packages/webui/tests/unified-workspace-browser.test.mjs index 01911e0b5..29171de71 100644 --- a/packages/webui/tests/unified-workspace-browser.test.mjs +++ b/packages/webui/tests/unified-workspace-browser.test.mjs @@ -302,8 +302,8 @@ test('keyboard focus follows visual order and survives a data refresh', async t await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/ddigital/organization`); await wait('document.querySelectorAll("[data-org-dashboard] .ws-doc").length > 0 && document.querySelectorAll("#workspace-nav .ws-proj").length === 3'); const wide = await tabStops(b, 'document.querySelector("#sections a")'); - // The right column holds the Workflows card (SP9) above Settings. - const regions = ['nav', 'head', 'Measures and sessions', 'Workflows and settings']; + // The left column holds the sessions and, below them, the Workflows card (SP16); the right holds Settings. + const regions = ['nav', 'head', 'Sessions and workflows', 'Settings']; assert.deepEqual([...new Set(wide.map(s => s.region))].filter(r => r !== 'other'), regions); assertVisualOrder(wide.filter(s => s.region !== 'other'), regions, '1440'); const keys = wide.map(s => s.key);