From 9994f89790d0e63dc7320aa5876c9b1ce8962f8a Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Mon, 16 Nov 2026 11:14:25 -0600 Subject: [PATCH 1/4] feat(webui): sp16 the agent drawer says what it can about an agent and why it can not act: Last activity reads not recorded, since no read the Console makes carries the time of an agent's last message or run (the agents read's time is the role claim, `since` the start of its present state); a pack hire shows Hired from with its pack and the template the installed pack's hire names, from the existing owner-only packs read, made only for a pack hire, and says not read with the reason when that read is refused; where no Message is offered one line says why; a drawer whose instances read answers after its HTML is built and before the page carrying it is on screen repaints once that page is painted, instead of staying on Reading state until the next poll; the organization page's Workflows card moves under Active agent sessions so the left column is not empty below the sessions. No Restart: no route restarts one agent (#1873, lane sp16-drawer-actions) --- packages/webui/src/public/workspace.js | 85 ++++++++++++++++--- .../webui/tests/agent-drawer-browser.test.mjs | 45 ++++++++-- .../webui/tests/org-page-fit-browser.test.mjs | 31 +++++++ .../tests/unified-workspace-browser.test.mjs | 4 +- 4 files changed, 143 insertions(+), 22 deletions(-) diff --git a/packages/webui/src/public/workspace.js b/packages/webui/src/public/workspace.js index 44fac0663..ee5a30a15 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 })}
@@ -1144,6 +1144,9 @@ // 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. let drawerInst = null, drawerReads = 0; // { org, n, done, value, p } + // Repaints whose read answered before their drawer was on screen, keyed `:`. 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 }; @@ -1152,6 +1155,27 @@ 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, once per instances read, so a + // repaint from the same read reads nothing again. The pack is the one installed now; the read does not + // say which version the hire was made from. + const drawerPacks = (org, ir, key) => { + const item = ir?.value?.inst?.[key]; + if (!item || !isHired(item) || typeof item.pack?.id !== 'string') return Promise.resolve(null); + return (ir.packs ??= 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(); + return Array.isArray(v?.packs) ? { packs: v.packs } : { err: { code: 'no answer' } }; + }, () => ({ err: { code: 'no answer' } }))); + }; + 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 typeof t === 'string' && t ? t : ''; + }; async function agentDrawer(q, opts = {}) { const pick = agentPick(q); if (!pick || (opts.only && pick.org !== opts.only)) return ''; @@ -1169,21 +1193,28 @@ // 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(() => { + // SP16: the 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 once that drawer is painted. + if (pending) ir.p.then(() => drawerPacks(org, ir, pick.key)).then(packs => { if (drawerInst === ir) drawerInst = null; + const redo = node => { + const key = focusKey(node), tpl = document.createElement('template'); + tpl.innerHTML = drawerHtml(pick, { body, business, config, pending: false, instRead: ir.value, packs }); + const fresh = tpl.content.firstElementChild; + if (!fresh) return; + node.replaceWith(fresh); + refocus(fresh, key); + }; 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); + if (node) { redo(node); return; } + drawerLate.set(`${ir.n}:${id}`, redo); + while (drawerLate.size > DRAWER_LATE_MAX) drawerLate.delete(drawerLate.keys().next().value); }); else if (drawerInst === ir) drawerInst = null; - return drawerHtml(pick, { body, business, config, pending: pending && ir.n, instRead: pending ? null : ir.value }); + const packs = pending ? null : await drawerPacks(org, ir, pick.key); + return drawerHtml(pick, { body, business, config, pending: pending && ir.n, instRead: pending ? null : ir.value, packs }); } - 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 = ``; @@ -1197,12 +1228,22 @@ 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 t = packTemplate(item, key, packs); + hiredFrom = `Pack ${esc(packOf(item))}, ${t ? `template ${esc(t)} as the installed pack names it` + : `template ${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,6 +1270,14 @@ 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(`

${!unknown && window.MosaicAgents?.isThread?.(def) + ? `No Message: ${esc(a.name)} holds no conversation now.` + : unknown ? 'No Message: its state is not read yet, so it is not known whether it holds a conversation.' + : '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. @@ -1245,10 +1294,14 @@ field('org', 'Organization', orgChip(o, org)), unknown ? '' : field('role', 'Role', `${esc(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 an 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. + field('activity', 'Last activity', 'not recorded'), ].join(''); return shell(a.name, `
${fields}

Open tasks

${tasksBody}${tasksAll}
@@ -1266,6 +1319,10 @@ // 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]')) { + const k = `${node.dataset.drawerPending}:${node.dataset.wsDrawer}`, redo = drawerLate.get(k); + if (redo) { drawerLate.delete(k); redo(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..e30374120 100644 --- a/packages/webui/tests/agent-drawer-browser.test.mjs +++ b/packages/webui/tests/agent-drawer-browser.test.mjs @@ -84,7 +84,7 @@ 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 = []; 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 +94,14 @@ 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. A test may set __packsStatus. + const packs = u.match(/^\\/api\\/orgs\\/([^/]+)\\/packs$/); + if (packs) { + window.__packReads.push(packs[1]); + if (window.__packsStatus) return answer(window.__packsStatus, { error: 'refused' }); + 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', 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(); @@ -171,9 +179,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'`); @@ -192,13 +204,30 @@ test('a hired agent shows where its role came from; a not-running agent says not 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'); + // Read once per instances read (a render makes one), and only for the organization of the pack hire. + const reads = await b.evaluate('window.__packReads'); + assert.ok(reads.length >= 1 && reads.every(o => o === 'beta'), JSON.stringify(reads)); + // 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('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/); @@ -304,6 +333,9 @@ test('Message opens the agent\'s thread in an Assistant pane; Stop asks first an 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.'); + assert.equal(await has('[data-ws-drawer="acme:assistant"] [data-drawer-nomessage]'), 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]')`); @@ -351,6 +383,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 +392,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); -- 2.54.0 From d92cdefc1de42f5f7b004a92fb44a3e2f80c1e00 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Mon, 16 Nov 2026 11:28:54 -0600 Subject: [PATCH 2/4] fix(webui): sp16 review, the packs read never holds the page and never breaks the drawer: a pack hire's packs read is raced against the page's reads as the instances read is, so a slow one shows the template as being read and repaints the drawer when it answers, and the instances read is let go once it answers so a held packs read never keeps a stale state; a packs answer that is not JSON says not read: no answer instead of leaving no drawer; Hired from names the pack by the label the installed pack carries, since the instance names only its id (the test stub now gives the instance the bus's shape); Last activity for an agent holding a conversation says the drawer does not read it, since that thread's messages read pages from the oldest message, and not recorded stays for the rest; where no Message is offered the line says the state is being read, gives the reason a failed read gives, or says a copy is not messaged from here; a 401 reads as signed out (#1873, lane sp16-drawer-actions) --- packages/webui/src/public/workspace.js | 69 ++++++++++++------- .../webui/tests/agent-drawer-browser.test.mjs | 46 +++++++++++-- 2 files changed, 85 insertions(+), 30 deletions(-) diff --git a/packages/webui/src/public/workspace.js b/packages/webui/src/public/workspace.js index ee5a30a15..5f5804be5 100644 --- a/packages/webui/src/public/workspace.js +++ b/packages/webui/src/public/workspace.js @@ -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 @@ -1158,23 +1158,37 @@ // 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, once per instances read, so a - // repaint from the same read reads nothing again. The pack is the one installed now; the read does not - // say which version the hire was made from. + // repaint from the same read reads nothing again (each poll's instances read is new, and so is its packs + // 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 drawerPacks = (org, ir, key) => { const item = ir?.value?.inst?.[key]; if (!item || !isHired(item) || typeof item.pack?.id !== 'string') return Promise.resolve(null); return (ir.packs ??= 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(); + const v = await r.json().catch(() => null); return Array.isArray(v?.packs) ? { packs: v.packs } : { err: { code: 'no answer' } }; - }, () => ({ err: { code: 'no answer' } }))); + }).catch(() => ({ err: { code: 'no answer' } }))); }; + // The reads one agent's drawer waits on: its organization's instances read, then, for a pack hire, the + // packs read. Kept per agent on the instances read, so every open of that agent shares them. + const drawerFull = (org, ir, key) => { + const all = (ir.full ??= new Map()); + if (!all.has(key)) { + const f = { done: false, packs: null }; + f.p = ir.p.then(() => drawerPacks(org, ir, key)).then(packs => { f.done = true; f.packs = packs; return packs; }); + all.set(key, f); + } + return all.get(key); + }; + // 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 typeof t === 'string' && t ? t : ''; + return { template: typeof t === 'string' && t ? t : '', label: typeof doc?.label === 'string' && doc.label ? doc.label : '' }; }; async function agentDrawer(q, opts = {}) { const pick = agentPick(q); @@ -1187,16 +1201,21 @@ 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; + // SP16 review: the packs read is raced against the page's reads as the instances read is, so a slow + // packs read holds only the drawer's template line, never the page's paint. + const full = drawerFull(org, ir, pick.key); + await Promise.race([full.p, opts.page ?? full.p]); + const pending = !full.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. // SP16: the 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 once that drawer is painted. - if (pending) ir.p.then(() => drawerPacks(org, ir, pick.key)).then(packs => { - if (drawerInst === ir) drawerInst = null; + // The instances read is let go once it answers, even while a packs read is open, so a later render + // reads the state again instead of keeping this answer for as long as the packs read takes. + if (pending) ir.p.then(() => { if (drawerInst === ir) drawerInst = null; }); + if (pending) full.p.then(packs => { const redo = node => { const key = focusKey(node), tpl = document.createElement('template'); tpl.innerHTML = drawerHtml(pick, { body, business, config, pending: false, instRead: ir.value, packs }); @@ -1211,8 +1230,7 @@ while (drawerLate.size > DRAWER_LATE_MAX) drawerLate.delete(drawerLate.keys().next().value); }); else if (drawerInst === ir) drawerInst = null; - const packs = pending ? null : await drawerPacks(org, ir, pick.key); - return drawerHtml(pick, { body, business, config, pending: pending && ir.n, instRead: pending ? null : ir.value, packs }); + return drawerHtml(pick, { body, business, config, pending: pending && ir.n, instRead: ir.done ? ir.value : null, packs: full.packs }); } function drawerHtml(pick, { body, business, config, pending, instRead, packs = null }) { const { org, key, id } = pick; @@ -1220,8 +1238,10 @@ 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)}.

`); @@ -1239,9 +1259,9 @@ let hiredFrom = ''; if (a.level === 'org' && isHired(item)) { if (packOf(item)) { - const t = packTemplate(item, key, packs); - hiredFrom = `Pack ${esc(packOf(item))}, ${t ? `template ${esc(t)} as the installed pack names it` - : `template ${packs?.err ? `not read: ${esc(instWhy(packs))}` : 'not named in the packs read'}`}`; + 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; @@ -1273,15 +1293,16 @@ // 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(`

${!unknown && window.MosaicAgents?.isThread?.(def) - ? `No Message: ${esc(a.name)} holds no conversation now.` - : unknown ? 'No Message: its state is not read yet, so it is not known whether it holds a conversation.' + 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.' + : window.MosaicAgents?.isThread?.(def) ? `No Message: ${esc(a.name)} holds no conversation now.` : '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.` @@ -1299,9 +1320,11 @@ 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 an agent's last message or run. The agents + // 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. - field('activity', 'Last activity', 'not recorded'), + // 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 read here: its conversation’s messages read starts at the oldest message' : 'not recorded'}`), ].join(''); return shell(a.name, `

${fields}

Open tasks

${tasksBody}${tasksAll}
diff --git a/packages/webui/tests/agent-drawer-browser.test.mjs b/packages/webui/tests/agent-drawer-browser.test.mjs index e30374120..d181fd431 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: {}, }, }; @@ -85,6 +85,7 @@ function fixture() { const STUB = `(() => { const real = window.fetch.bind(window); window.__posts = []; window.__answers = []; window.__packReads = []; + window.__packsRelease = () => (window.__packsHeld ?? []).splice(0).forEach(r => r()); const answer = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); window.fetch = async (url, init = {}) => { const u = String(url); @@ -95,12 +96,16 @@ const STUB = `(() => { 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. A test may set __packsStatus. + // 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' }); - 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', version: 2, hires: [{ name: 'research-2', definition: 'researcher', reason: 'Research.' }], definitions: { researcher: { template: 'researcher', sha256: '${'a'.repeat(64)}' } } } }] : [] }); + 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 }); @@ -110,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`); @@ -198,7 +204,8 @@ 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/); + // The instance names the pack's id only; the agents list and the Role row show that id. + 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); @@ -218,7 +225,29 @@ test('SP16: a pack hire names its pack and the template the packs read gives; a 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'); + 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'); }); test('a field with no read is left out', async t => { @@ -329,13 +358,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 read here: its conversation’s messages read starts at the oldest message'); // 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.'); - assert.equal(await has('[data-ws-drawer="acme:assistant"] [data-drawer-nomessage]'), 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]')`); -- 2.54.0 From 70af20e29d24f54ebfbbd2d2a06edd9cb4e96d8e Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Mon, 16 Nov 2026 11:46:24 -0600 Subject: [PATCH 3/4] fix(webui): sp16 review 2, the drawer shows the state as soon as it is read and the template line holds still: when the instances read answers after the page, the drawer repaints at once with the state, and a pack hire's template line says being read until its packs read answers and repaints it (data-drawer-pending names `` for the instances read and `p` for the packs read, and a repaint waiting on the fresh drawer runs at the swap); the packs answer is kept per organization for 60 s and a repaint draws from it, also while a newer read is open, so the line no longer goes back to being read on every poll and one read serves the repaints; a drawer whose reads have all answered is no longer marked pending and swapped after paint; the Role row of a pack hire says Hired and the pack is named once, in Hired from; the unreachable holds-no-conversation line is gone; Last activity for a conversation agent reads not shown: reading it means reading the whole conversation; tests pin one packs read across three repaints, the state shown while packs is held, and no pending marker when all reads are in (#1873, lane sp16-drawer-actions) --- packages/webui/src/public/workspace.js | 145 ++++++++++-------- .../webui/tests/agent-drawer-browser.test.mjs | 74 ++++++++- 2 files changed, 151 insertions(+), 68 deletions(-) diff --git a/packages/webui/src/public/workspace.js b/packages/webui/src/public/workspace.js index 5f5804be5..5cdcce423 100644 --- a/packages/webui/src/public/workspace.js +++ b/packages/webui/src/public/workspace.js @@ -1141,45 +1141,44 @@ } // 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 `:`. A - // drawer never painted (closed, or replaced by a later paint) leaves its entry; the oldest go first. + // 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, once per instances read, so a - // repaint from the same read reads nothing again (each poll's instances read is new, and so is its packs - // read). The pack is the one installed now; the read does not say which version the hire was made from. + // 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. + // 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 drawerPacks = (org, ir, key) => { - const item = ir?.value?.inst?.[key]; - if (!item || !isHired(item) || typeof item.pack?.id !== 'string') return Promise.resolve(null); - return (ir.packs ??= 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' } }))); - }; - // The reads one agent's drawer waits on: its organization's instances read, then, for a pack hire, the - // packs read. Kept per agent on the instances read, so every open of that agent shares them. - const drawerFull = (org, ir, key) => { - const all = (ir.full ??= new Map()); - if (!all.has(key)) { - const f = { done: false, packs: null }; - f.p = ir.p.then(() => drawerPacks(org, ir, key)).then(packs => { f.done = true; f.packs = packs; return packs; }); - all.set(key, f); + const drawerPacksKept = new Map(), DRAWER_PACKS_KEEP = 60000; // org -> { at, value, p } + const drawerPacks = (org, instValue, key) => { + 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 })); + if (!k.p && (!k.value || Date.now() - k.at >= DRAWER_PACKS_KEEP)) { + 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; }); } - return all.get(key); + return { value: k.value, p: k.p }; }; // 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. @@ -1190,6 +1189,30 @@ 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 ''; @@ -1201,36 +1224,37 @@ typeof opts.configIn === 'function' ? Promise.resolve(opts.configIn(org)).catch(() => null) : null, ensureThemes(), ]); - // SP16 review: the packs read is raced against the page's reads as the instances read is, so a slow - // packs read holds only the drawer's template line, never the page's paint. - const full = drawerFull(org, ir, pick.key); - await Promise.race([full.p, opts.page ?? full.p]); - const pending = !full.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. - // SP16: the 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 once that drawer is painted. - // The instances read is let go once it answers, even while a packs read is open, so a later render - // reads the state again instead of keeping this answer for as long as the packs read takes. - if (pending) ir.p.then(() => { if (drawerInst === ir) drawerInst = null; }); - if (pending) full.p.then(packs => { - const redo = node => { - const key = focusKey(node), tpl = document.createElement('template'); - tpl.innerHTML = drawerHtml(pick, { body, business, config, pending: false, instRead: ir.value, packs }); - const fresh = tpl.content.firstElementChild; - if (!fresh) return; - node.replaceWith(fresh); - refocus(fresh, key); - }; - const node = document.querySelector(`#bus-view [data-ws-drawer="${CSS.escape(id)}"][data-drawer-pending="${ir.n}"]`); - if (node) { redo(node); return; } - drawerLate.set(`${ir.n}:${id}`, redo); - while (drawerLate.size > DRAWER_LATE_MAX) drawerLate.delete(drawerLate.keys().next().value); - }); - else if (drawerInst === ir) drawerInst = null; - return drawerHtml(pick, { body, business, config, pending: pending && ir.n, instRead: ir.done ? ir.value : null, packs: full.packs }); + 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 kept, says it is being read and repaints when that read answers. + const packsStage = instRead => { + const pk = drawerPacks(org, instRead, pick.key); + if (pk?.p && !pk.value) drawerWhen(pk.p, `${ir.n}p`, id, v => () => html(instRead, v, false)); + return pk?.p && !pk.value ? { packs: null, pending: `${ir.n}p` } : { packs: pk?.value ?? null, pending: 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 && !pk.value) { + await Promise.race([pk.p, page ?? pk.p]); + pk = drawerPacks(org, ir.value, pick.key); + } + if (pk?.p && !pk.value) { + drawerWhen(pk.p, `${ir.n}p`, id, v => () => html(ir.value, v, false)); + return html(ir.value, null, `${ir.n}p`); + } + return html(ir.value, pk?.value ?? null, false); } function drawerHtml(pick, { body, business, config, pending, instRead, packs = null }) { const { org, key, id } = pick; @@ -1296,7 +1320,6 @@ 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.' - : window.MosaicAgents?.isThread?.(def) ? `No Message: ${esc(a.name)} holds no conversation now.` : '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)); @@ -1313,7 +1336,8 @@ : `

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)), @@ -1324,7 +1348,7 @@ // 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 read here: its conversation’s messages read starts at the oldest message' : 'not recorded'}`), + 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}
@@ -1342,10 +1366,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]')) { - const k = `${node.dataset.drawerPending}:${node.dataset.wsDrawer}`, redo = drawerLate.get(k); - if (redo) { drawerLate.delete(k); redo(node); } - } + 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 d181fd431..47325af71 100644 --- a/packages/webui/tests/agent-drawer-browser.test.mjs +++ b/packages/webui/tests/agent-drawer-browser.test.mjs @@ -204,8 +204,8 @@ 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"]'; - // The instance names the pack's id only; the agents list and the Role row show that id. - 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); @@ -217,9 +217,8 @@ test('SP16: a pack hire names its pack and the template the packs read gives; a 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'); - // Read once per instances read (a render makes one), and only for the organization of the pack hire. - const reads = await b.evaluate('window.__packReads'); - assert.ok(reads.length >= 1 && reads.every(o => o === 'beta'), JSON.stringify(reads)); + // 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'); @@ -250,6 +249,69 @@ test('SP16 review: a packs read still open does not hold the page or the state; 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)); +}); + 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' }); @@ -361,7 +423,7 @@ test('Message opens the agent\'s thread in an Assistant pane; Stop asks first an // 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 read here: its conversation’s messages read starts at the oldest message'); + 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]')`); -- 2.54.0 From ff096afa2764565292059191866009a20d000f5e Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Mon, 16 Nov 2026 12:01:02 -0600 Subject: [PATCH 4/4] fix(webui): sp16 review 3, a kept packs answer of no use for this hire is read again at once: a refusal or no answer is read again on each render, at most one read open, so the template line recovers with the route instead of saying not read for 60 s; an answer that does not name this hire (a hire made after it was read) is read again once per hire until the keep runs out, and the line says the template is being read, not that the pack does not name it, until that read answers and repaints the drawer; a hire the pack really does not name says so after one read and makes no read on each repaint; the drawer's second look after its race starts no read, so a render makes at most one packs read; the quiet refresh at 60 s still draws the kept answer with no swap; tests pin a later hire, a hire the pack does not name, a 503 that recovers and the 60 s refresh (#1873, lane sp16-drawer-actions) --- packages/webui/src/public/workspace.js | 38 ++++++--- .../webui/tests/agent-drawer-browser.test.mjs | 79 +++++++++++++++++++ 2 files changed, 105 insertions(+), 12 deletions(-) diff --git a/packages/webui/src/public/workspace.js b/packages/webui/src/public/workspace.js index 5cdcce423..3f5df5519 100644 --- a/packages/webui/src/public/workspace.js +++ b/packages/webui/src/public/workspace.js @@ -1162,15 +1162,27 @@ // 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 } - const drawerPacks = (org, instValue, key) => { + 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 })); - if (!k.p && (!k.value || Date.now() - k.at >= DRAWER_PACKS_KEEP)) { + 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 } }; @@ -1178,7 +1190,8 @@ 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; }); } - return { value: k.value, p: k.p }; + 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. @@ -1235,24 +1248,25 @@ // 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 kept, says it is being read and repaints when that read answers. + // 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 && !pk.value) drawerWhen(pk.p, `${ir.n}p`, id, v => () => html(instRead, v, false)); - return pk?.p && !pk.value ? { packs: null, pending: `${ir.n}p` } : { packs: pk?.value ?? null, pending: false }; + 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 && !pk.value) { + if (pk?.p) { await Promise.race([pk.p, page ?? pk.p]); - pk = drawerPacks(org, ir.value, pick.key); + pk = drawerPacks(org, ir.value, pick.key, false); } - if (pk?.p && !pk.value) { + if (pk?.p) { drawerWhen(pk.p, `${ir.n}p`, id, v => () => html(ir.value, v, false)); - return html(ir.value, null, `${ir.n}p`); + return html(ir.value, pk.value, `${ir.n}p`); } return html(ir.value, pk?.value ?? null, false); } diff --git a/packages/webui/tests/agent-drawer-browser.test.mjs b/packages/webui/tests/agent-drawer-browser.test.mjs index 47325af71..31b6d93c3 100644 --- a/packages/webui/tests/agent-drawer-browser.test.mjs +++ b/packages/webui/tests/agent-drawer-browser.test.mjs @@ -312,6 +312,85 @@ test('SP16 review 2: a drawer whose reads have all answered is not marked pendin 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' }); -- 2.54.0