From d92cdefc1de42f5f7b004a92fb44a3e2f80c1e00 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Mon, 16 Nov 2026 11:28:54 -0600 Subject: [PATCH] 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]')`);