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]')`);