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);