Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c26879637a | ||
|
|
2fc97a3edb | ||
|
|
68df55130e | ||
|
|
6ad1d33dd1 | ||
|
|
5fba4726dc | ||
|
|
69ce460f91 | ||
|
|
307f88be3e | ||
|
|
bfd3ed6811 |
No files matched your search
@@ -302,14 +302,29 @@
|
||||
// SP11: a pane's unsent message is kept per thread for the life of the browser tab, so leaving the
|
||||
// Assistant page (a Full view link included) and coming back puts it in the composer again.
|
||||
// sessionStorage can be missing or refuse a write; the Map still keeps it while the page lives.
|
||||
// SP14: the kept messages belong to the person who typed them. They are stored with the viewer the
|
||||
// page's /api/config read names (bus.js, window.MosaicViewer), and read back only by a page that
|
||||
// read the same viewer. An entry stored under another viewer, or under none (an older entry, a
|
||||
// failed read), is removed unread, so a tab that never saw a sign-out (another tab signed out, the
|
||||
// session expired) does not hand one person's text to the next. A Console with no sign-in has one
|
||||
// fixed viewer. Until the viewer is read nothing is written; with none, messages live only in the page.
|
||||
const DRAFTS = 'mosaic-assistant-drafts';
|
||||
const kept = (() => {
|
||||
try {
|
||||
const v = JSON.parse(sessionStorage.getItem(DRAFTS) || 'null');
|
||||
return new Map(v && typeof v === 'object' && !Array.isArray(v) ? Object.entries(v).filter(([k, t]) => typeof t === 'string' && t.trim() && parse(`open=${k}`).keys[0] === k) : []);
|
||||
} catch { return new Map(); }
|
||||
})();
|
||||
const saveKept = () => { try { if (kept.size) sessionStorage.setItem(DRAFTS, JSON.stringify(Object.fromEntries(kept))); else sessionStorage.removeItem(DRAFTS); } catch { /* the Map still holds it */ } };
|
||||
const kept = new Map();
|
||||
let viewer = null, known = false, viewerRead = null;
|
||||
const saveKept = () => {
|
||||
if (!known) return;
|
||||
try { if (kept.size && viewer) sessionStorage.setItem(DRAFTS, JSON.stringify({ viewer, drafts: Object.fromEntries(kept) })); else sessionStorage.removeItem(DRAFTS); } catch { /* the Map still holds it */ }
|
||||
};
|
||||
const ready = () => (viewerRead ??= (async () => {
|
||||
let v = null, stored = null;
|
||||
try { v = await window.MosaicViewer; } catch { /* no viewer */ }
|
||||
try { stored = JSON.parse(sessionStorage.getItem(DRAFTS) || 'null'); } catch { /* none kept */ }
|
||||
viewer = typeof v === 'string' && v ? v : null;
|
||||
known = true;
|
||||
const own = !draftsOff && viewer && stored && typeof stored === 'object' && stored.viewer === viewer && stored.drafts && typeof stored.drafts === 'object' && !Array.isArray(stored.drafts);
|
||||
if (own) for (const [k, t] of Object.entries(stored.drafts)) if (!kept.has(k) && typeof t === 'string' && t.trim() && parse(`open=${k}`).keys[0] === k) kept.set(k, t);
|
||||
saveKept();
|
||||
})());
|
||||
const typedIn = p => p.chat?.draft?.() || p.draft || p.el?.querySelector('form textarea')?.value || '';
|
||||
// Signed out, by an expired session or by the Sign out form: the kept drafts go and nothing is kept
|
||||
// again, not even by the pagehide the form's own submit causes, so the next person to sign in on
|
||||
@@ -320,6 +335,7 @@
|
||||
window.addEventListener('pagehide', () => { if (mounted) for (const p of mounted.panes) keep(p); });
|
||||
function forgetDrafts() {
|
||||
draftsOff = true; kept.clear(); saveKept();
|
||||
try { sessionStorage.removeItem(DRAFTS); } catch { /* nothing to remove */ }
|
||||
if (mounted) for (const p of mounted.panes) { p.draft = ''; const t = p.el?.querySelector('form textarea'); if (t) t.value = ''; }
|
||||
}
|
||||
document.addEventListener('mosaic-signed-out', forgetDrafts);
|
||||
@@ -491,7 +507,10 @@
|
||||
// ---------- public ----------
|
||||
async function mount(container, query, { navigated = false } = {}) {
|
||||
unmount();
|
||||
++mountGen;
|
||||
const gen = ++mountGen;
|
||||
// SP14: the kept messages are known only once the viewer is; a page left meanwhile mounts nothing.
|
||||
await ready();
|
||||
if (gen !== mountGen) return;
|
||||
container.innerHTML = frame();
|
||||
const root = container.querySelector('[data-assistant]');
|
||||
mounted = { root, panes: [], show: null, turn: 0, timer: null, list: null, got: null, o: null, form: null, formTurn: 0, notice: '' };
|
||||
@@ -509,10 +528,12 @@
|
||||
else if (navigated) root.querySelector('h1').focus({ preventScroll: true });
|
||||
writeUrl(); paintTabs(); layout();
|
||||
root.querySelector('[data-assist-empty]').hidden = mounted.panes.length > 0;
|
||||
// SP14: a full set offers no fourth from the start, not only once the organization reads answer.
|
||||
root.querySelector('[data-assist-open]').disabled = mounted.panes.length >= MAX;
|
||||
await draw({ navigated: true });
|
||||
}
|
||||
function unmount() {
|
||||
if (!mounted) return;
|
||||
if (!mounted) { mountGen++; return; }
|
||||
clearTimeout(mounted.timer);
|
||||
for (const p of mounted.panes) { keep(p); p.chat?.dispose(); }
|
||||
window.removeEventListener('resize', fit);
|
||||
|
||||
@@ -1695,7 +1695,7 @@
|
||||
// #/ is then the Console's own board.
|
||||
if ((n === 0 && window.MosaicOrg) || (a === 'dashboard' && n === 1 && window.MosaicWorkspace)) return window.MosaicWorkspace.home();
|
||||
if (a === 'projects' && n === 1 && window.MosaicOrg) return window.MosaicWorkspace.projectsPage(q);
|
||||
if (a === 'organization' && n === 1 && window.MosaicOrg) return window.MosaicWorkspace.dashboard();
|
||||
if (a === 'organization' && n === 1 && window.MosaicOrg) return window.MosaicWorkspace.dashboard(undefined, { q, configIn: orgConfig });
|
||||
// SP3: #/inbox is every organization's items; #/orgs/<id>/inbox is that list for one, with its hire form.
|
||||
if (a === 'inbox' && n === 1 && window.MosaicOrg) {
|
||||
const scope = /^#\/orgs\/([^/?]+)/.exec(location.hash)?.[1];
|
||||
@@ -1717,7 +1717,7 @@
|
||||
if (a === 'agents' && n === 1 && window.MosaicOrg) {
|
||||
const scope = /^#\/orgs\/([^/?]+)/.exec(location.hash)?.[1];
|
||||
let org = null; try { org = scope ? decodeURIComponent(scope) : null; } catch { return notFound(); }
|
||||
if (!org) return configRead.then(() => window.MosaicWorkspace.agentsPage(q, { scope: null, fireIn: decidesIn }));
|
||||
if (!org) return configRead.then(() => window.MosaicWorkspace.agentsPage(q, { scope: null, fireIn: decidesIn, configIn: orgConfig }));
|
||||
return agentsView(get, q, org);
|
||||
}
|
||||
if (a === 'agents' && n === 1) return agentsView(get);
|
||||
@@ -1741,6 +1741,14 @@
|
||||
const paused = () => $('pause')?.getAttribute('aria-pressed') === 'true';
|
||||
// A file open in the editor is never refreshed from under its draft; Reload is the person's to press.
|
||||
// The cross-organization pages (U3) poll at the workspace read's pollMs.
|
||||
// SP12: the organization page repaints in place too when only its query changes (the agent drawer).
|
||||
const drawerPage = path => wsPage(path) || (path === '/organization' && !!window.MosaicOrg);
|
||||
// A hash change that only opens, closes or switches the agent drawer is a repaint, not a navigation.
|
||||
const agentOnly = (from, to) => {
|
||||
const split = u => { const h = String(u || '').split('#')[1] ?? ''; const [p, q = ''] = h.split('?'); const n = new URLSearchParams(q); const agent = n.get('agent'); n.delete('agent'); n.sort(); return { p, rest: n.toString(), agent }; };
|
||||
const a = split(from), b = split(to);
|
||||
return a.p === b.p && a.rest === b.rest && a.agent !== b.agent && /^\/(agents|(orgs\/[^/?]+\/)?organization)$/.test(b.p);
|
||||
};
|
||||
const wsPage = path => (path === '/dashboard' && !!window.MosaicWorkspace) || !!window.MosaicOrg && (path === '/' || path === '' || path === '/dashboard' || path === '/projects' || path === '/inbox' || path === '/agents' || path === '/tasks' || /^\/workflows(\/[^/]+)?$/.test(path));
|
||||
function schedule() { clearTimeout(timer); if (!paused() && !out() && !routeOf().startsWith('/docs/')) timer = setTimeout(() => render(false), wsPage(routeOf().split('?')[0]) ? window.MosaicWorkspace?.pollMs || 10000 : 10000); }
|
||||
// Keep focus, open <details> and the copy status across a refresh of the same page.
|
||||
@@ -1802,7 +1810,7 @@
|
||||
const route = routeOf(), [path, query = ''] = route.split('?'), board = window.MosaicOrg ? path === '/board' : path === '/' || path === '' || path === '/board';
|
||||
// On the cross-organization pages a filter or selection changes only the query: that is a
|
||||
// repaint of the same page, not a navigation (no loading view, focus and scroll kept).
|
||||
const samePage = wsPage(path) && typeof shown === 'string' && shown.split('?')[0] === path;
|
||||
const samePage = drawerPage(path) && typeof shown === 'string' && shown.split('?')[0] === path;
|
||||
if (path !== '/settings/model-proxy' && proxyCleanup) {proxyCleanup();proxyCleanup=null;}
|
||||
if ((navigated || path !== '/settings/organizations') && orgCleanup) {orgCleanup();orgCleanup=null;}
|
||||
// Leaving a decision discards its confirmation immediately, including a preview in flight.
|
||||
@@ -1943,6 +1951,7 @@
|
||||
else if (focusSend && $('send-body')) { $('send-body').focus(); announce(`Message to ${draft.to}`); }
|
||||
else if (navigated && h1) { const target=settingsFocusDisclosure&&path.startsWith('/settings/') ? $('settings-disclosure') : path.startsWith('/settings/') ? ($('settings-page-title')||h1) : h1; settingsFocusDisclosure=false; target.focus(); announce(target.textContent); }
|
||||
focusSend = false;
|
||||
window.MosaicWorkspace?.afterPaint?.();
|
||||
schedule();
|
||||
}
|
||||
|
||||
@@ -2116,7 +2125,10 @@
|
||||
const path = routeOf().split('?')[0];
|
||||
if (path.startsWith('/chat')||path.startsWith('/projects')||path.startsWith('/inbox')||path.startsWith('/settings')||path.startsWith('/docs/')||wsPage(path)) render(false); else if (window.MosaicOrg ? path === '/board' : path === '/' || path === '') paintHeld(heldErr);
|
||||
};
|
||||
configRead = fetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => { if (r.type === 'opaqueredirect') { signOut(); return null; } return r.json(); }).then(applyConfig).catch(() => {});
|
||||
configRead = fetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => { if (r.type === 'opaqueredirect') { signOut(); return null; } return r.json(); }).then(c => { applyConfig(c); return c; }).catch(() => null);
|
||||
// SP14 (#1873): who is signed in, from this same read, for what the page keeps per person
|
||||
// (assistant.js's kept pane messages). null when the read failed or named nobody.
|
||||
window.MosaicViewer = configRead.then(c => (typeof c?.viewer === 'string' && c.viewer ? c.viewer : null));
|
||||
// E1 (P1-5): after Restart bus the organization dashboard draws its bus line now, not at the next poll.
|
||||
// E2E6 P2-2: a write on the organization page that changes other sections (a pack apply) asks for a
|
||||
// fresh read of the page; editors in progress are kept by holdLive.
|
||||
@@ -2152,7 +2164,7 @@
|
||||
document.addEventListener('mosaic-config', e => { if (e.detail && typeof e.detail === 'object') { applyConfig(e.detail); if (window.MosaicOrg && routeOf().split('?')[0] === '/organization') render(false); } });
|
||||
// The cross-organization pages ask for a repaint after a filter, sort or selection change,
|
||||
// and report the inbox count across organizations for the sidebar.
|
||||
document.addEventListener('mosaic-workspace-render', () => { if (wsPage(routeOf().split('?')[0])) render(false); });
|
||||
document.addEventListener('mosaic-workspace-render', () => { if (drawerPage(routeOf().split('?')[0])) render(false); });
|
||||
document.addEventListener('mosaic-workspace-inbox', e => { const d = e.detail; if (d && Number.isFinite(d.open)) { inboxCount = { open: d.open, blocking: Number.isFinite(d.blocking) ? d.blocking : 0 }; sections(routeOf().split('?')[0]); } });
|
||||
// This context comes from the conversations renderer after its authorized read.
|
||||
let projectContext = null;
|
||||
@@ -2229,7 +2241,7 @@
|
||||
});
|
||||
nav.addEventListener('click', e => { if (drawerOpen && e.target.closest('a[href^="#/"]')) drawer(false, false); });
|
||||
window.addEventListener('resize', () => { if (drawerOpen && innerWidth >= 760) drawer(false, false); if (drawerOpen) $('nav-overflow').hidden = nav.scrollHeight <= nav.clientHeight + 1; });
|
||||
window.addEventListener('hashchange', () => render(true));
|
||||
window.addEventListener('hashchange', e => render(!agentOnly(e.oldURL, e.newURL)));
|
||||
$('refresh').addEventListener('click', () => render(false));
|
||||
$('pause').addEventListener('click', () => setTimeout(schedule)); // after app.js flips aria-pressed
|
||||
render(false).then(() => { if (!$('bus-view').hidden) { const h1 = $('bus-view').querySelector('h1'); if (h1 && location.hash.startsWith('#/')) h1.focus(); } });
|
||||
|
||||
@@ -5,7 +5,8 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date(
|
||||
// Requests already sent keep the organization they were sent with.
|
||||
(() => {
|
||||
const nativeFetch = window.fetch.bind(window);
|
||||
const orgOf = hash => /^#\/orgs\/([^/]+)/.exec(hash)?.[1] ?? null;
|
||||
// SP13: the organization segment stops at `/` or `?`, so `#/orgs/<id>?agent=…` names <id>.
|
||||
const orgOf = hash => /^#\/orgs\/([^/?]+)/.exec(hash)?.[1] ?? null;
|
||||
const atLoad = orgOf(location.hash);
|
||||
if (!atLoad && !document.documentElement.hasAttribute('data-organizations')) return;
|
||||
// current: the scoping organization as its hash segment. settled: false only while the first
|
||||
@@ -16,7 +17,7 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date(
|
||||
const settle = seg => { current = seg; settled = true; markReady(seg ? decodeURIComponent(seg) : null); };
|
||||
// An address that names its organization is settled at load: anything waiting on ready goes on.
|
||||
if (atLoad) markReady(decodeURIComponent(atLoad));
|
||||
const tail = hash => { const m = /^#\/orgs\/[^/]+(.*)$/.exec(hash); return m ? (m[1] || '/') : hash.startsWith('#/') ? hash.slice(1) : '/'; };
|
||||
const tail = hash => { const m = /^#\/orgs\/[^/?]+(.*)$/.exec(hash); return m ? (!m[1] ? '/' : m[1][0] === '?' ? `/${m[1]}` : m[1]) : hash.startsWith('#/') ? hash.slice(1) : '/'; };
|
||||
const route = () => tail(location.hash);
|
||||
// The bare address and the old per-organization dashboard address are the system dashboard;
|
||||
// an organization page without the prefix gets the current organization's. #1873 SP2: an
|
||||
|
||||
@@ -485,6 +485,13 @@ html[data-organizations] .ws-panel.tight{padding:12px 14px}
|
||||
html[data-organizations] .ws-split{display:grid;grid-template-columns:minmax(0,1.45fr) minmax(0,1fr);gap:16px;align-items:start}
|
||||
html[data-organizations] .ws-split{margin-top:22px}
|
||||
html[data-organizations] .ws-split>section>.ws-sec-h:first-child{margin-top:0}
|
||||
/* SP13: a column whose first child wraps its heading (the Workflows card) starts level with the other. */
|
||||
html[data-organizations] .ws-split>section>:first-child>.ws-sec-h:first-child{margin-top:0}
|
||||
/* SP13 (#1873): the organization page's two columns stack once its content is narrower than both need,
|
||||
with or without the agent drawer beside it: a wrap, not a viewport breakpoint. */
|
||||
html[data-organizations] .ws-dash>.ws-split{display:flex;flex-wrap:wrap;align-items:flex-start}
|
||||
html[data-organizations] .ws-dash>.ws-split>section{flex:1.45 1 480px;min-width:0}
|
||||
html[data-organizations] .ws-dash>.ws-split>section+section{flex:1 1 360px}
|
||||
/* E2E6 P1-3: the long editors (Autonomy, Packs, Workflows) span the page below the split, so neither
|
||||
column runs screens past the other at 1440. */
|
||||
html[data-organizations] .ws-wide{display:grid;grid-template-columns:minmax(0,1fr);gap:16px;margin-top:22px}
|
||||
@@ -522,15 +529,20 @@ html[data-organizations] .ws-tbl tr:last-child td{border-bottom:0}
|
||||
html[data-organizations] .ws-tbl .t1{color:var(--strong)}
|
||||
html[data-organizations] .ws-tbl .t2{display:block;font-size:12px;color:var(--muted)}
|
||||
html[data-organizations] .ws-tbl td.mono{font-family:var(--mono);font-size:12.5px;white-space:nowrap}
|
||||
html[data-organizations] .ws-cfg{display:grid;list-style:none;margin:0;padding:0;border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--surface)}
|
||||
html[data-organizations] .ws-cfg{container-type:inline-size;display:grid;list-style:none;margin:0;padding:0;border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--surface)}
|
||||
html[data-organizations] .ws-cfg li{display:grid;align-items:center;grid-template-columns:18px 132px minmax(0,1fr) auto auto;gap:0 10px;padding:7px 12px;border-bottom:1px solid color-mix(in srgb,var(--line) 60%,transparent)}
|
||||
html[data-organizations] .ws-cfg li:last-child{border-bottom:0}
|
||||
html[data-organizations] .ws-cfg svg.i{width:16px;height:16px;color:var(--muted)}
|
||||
html[data-organizations] .ws-cfg .k{font-size:13px;font-weight:600;color:var(--strong)}
|
||||
html[data-organizations] .ws-cfg .v{font-size:12px;color:var(--muted);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
html[data-organizations] .ws-cfg .v{font-size:12px;color:var(--muted);min-width:0;overflow-wrap:anywhere}
|
||||
html[data-organizations] .ws-cfg .src-tag{font:500 11px var(--mono);color:var(--accent);white-space:nowrap}
|
||||
html[data-organizations] .ws-cfg .go{font-size:12.5px;font-weight:600;color:var(--action);text-decoration:none;min-width:32px;text-align:right}
|
||||
html[data-organizations] .ws-cfg a.go:hover{text-decoration:underline}
|
||||
/* SP13: a Settings card narrower than its five columns need puts each value on its own line. */
|
||||
@container (max-width:560px){
|
||||
html[data-organizations] .ws-cfg li{grid-template-columns:18px minmax(0,1fr) auto auto}
|
||||
html[data-organizations] .ws-cfg .v{grid-column:2/-1;grid-row:2}
|
||||
}
|
||||
html[data-organizations] .ws-cfg li.danger .k,html[data-organizations] .ws-cfg li.danger svg.i,html[data-organizations] .ws-cfg li.danger .go,html[data-organizations] .ws-cfg li.danger .src-tag{color:var(--danger)}
|
||||
|
||||
/* Agents (sample 08). */
|
||||
@@ -726,6 +738,39 @@ html[data-organizations] .ws-cmd{display:flex;gap:6px;align-items:center;min-wid
|
||||
html[data-organizations] .ws-cmd code{flex:1;min-width:0;overflow-x:auto;white-space:nowrap;background:var(--surface);border:1px solid var(--line);border-radius:4px;padding:3px 6px;font-size:12px;color:var(--strong)}
|
||||
html[data-organizations] .ws-cmd .ws-btn{padding:4px 6px}
|
||||
html[data-organizations] #copy-status:empty{display:none}
|
||||
/* SP12 (#1873): the agent drawer, a non-modal region at the right of the page; the page stays under it. */
|
||||
html[data-organizations] .ws-drawer-open{color:inherit;font-weight:inherit;text-decoration:underline;text-decoration-color:color-mix(in srgb,currentColor 35%,transparent);text-underline-offset:3px}
|
||||
html[data-organizations] .ws-drawer-open:hover{text-decoration-color:currentColor}
|
||||
html[data-organizations] .ws-drawer{position:fixed;top:var(--bar-h,52px);right:0;bottom:0;width:min(420px,100vw);z-index:40;display:flex;flex-direction:column;background:var(--surface);border-left:1px solid var(--line);box-shadow:-8px 0 24px color-mix(in srgb,#000 14%,transparent);overflow:auto;overscroll-behavior:contain}
|
||||
html[data-organizations] .ws-drawer .hd{display:flex;align-items:center;gap:8px;padding:12px 14px 12px 17px;border-bottom:1px solid var(--line);background:var(--surface);position:sticky;top:0;z-index:1;box-shadow:inset 4px 0 0 var(--org,var(--action))}
|
||||
html[data-organizations] .ws-drawer h2{margin:0;font-size:18px;font-weight:800;color:var(--strong);overflow-wrap:anywhere;min-width:0}
|
||||
html[data-organizations] .ws-drawer h2:focus{outline:none}
|
||||
html[data-organizations] .ws-drawer h2:focus-visible{outline:2px solid var(--action);outline-offset:2px}
|
||||
html[data-organizations] .ws-drawer .x{margin-left:auto;flex:none;width:32px;height:32px;border:1px solid var(--line);border-radius:6px;background:var(--canvas);color:var(--strong);font-size:20px;line-height:1;cursor:pointer}
|
||||
html[data-organizations] .ws-drawer .body{padding:14px;display:grid;gap:16px;align-content:start}
|
||||
html[data-organizations] .ws-drawer-fields{margin:0;display:grid;gap:8px}
|
||||
html[data-organizations] .ws-drawer-f{display:grid;grid-template-columns:96px minmax(0,1fr);gap:8px;align-items:baseline;font-size:13px}
|
||||
html[data-organizations] .ws-drawer-f dt{color:var(--muted);font-weight:600}
|
||||
html[data-organizations] .ws-drawer-f dd{margin:0;color:var(--strong);overflow-wrap:anywhere;min-width:0}
|
||||
html[data-organizations] .ws-drawer-f code,html[data-organizations] .ws-drawer .mono{font:12px var(--mono)}
|
||||
html[data-organizations] .ws-drawer-sec{display:grid;gap:6px;margin:0}
|
||||
html[data-organizations] .ws-drawer-sec h3{margin:0;font:700 11px/1.3 var(--font);letter-spacing:.06em;text-transform:uppercase;color:var(--muted)}
|
||||
html[data-organizations] .ws-drawer-list{list-style:none;margin:0;padding:0;display:grid;gap:4px;font-size:13px}
|
||||
html[data-organizations] .ws-drawer-list li{border:1px solid var(--line);border-radius:6px;padding:6px 9px;background:var(--canvas);overflow-wrap:anywhere}
|
||||
html[data-organizations] .ws-drawer-list .t2{margin-left:4px;font-size:12px;color:var(--muted)}
|
||||
html[data-organizations] .ws-drawer .ws-more{font-size:13px}
|
||||
html[data-organizations] .ws-drawer .note{margin:0}
|
||||
html[data-organizations] .ws-drawer-acts{display:flex;flex-wrap:wrap;gap:8px;align-items:center;border-top:1px solid var(--line);padding-top:12px}
|
||||
html[data-organizations] .ws-drawer-confirm{display:flex;flex-wrap:wrap;gap:8px;align-items:center;font-size:13px;color:var(--strong);flex-basis:100%}
|
||||
html[data-organizations] .ws-drawer .ws-btn.danger{color:var(--danger)}
|
||||
html[data-organizations] .ws-drawer-status{margin:0;flex-basis:100%;font-size:13px;color:var(--strong)}
|
||||
html[data-organizations] .ws-drawer-status:empty{display:none}
|
||||
html[data-organizations] .ws-drawer-acts .note{flex-basis:100%}
|
||||
/* Wide screens: the page keeps clear of the drawer, so nothing sits under it. */
|
||||
@media (min-width:1200px){html[data-organizations] body:has(.ws-drawer) .content{padding-right:calc(420px + 22px)}}
|
||||
@media (max-width:700px){
|
||||
html[data-organizations] .ws-drawer{top:0;left:0;right:0;width:auto;border-left:0;box-shadow:none}
|
||||
}
|
||||
@media (max-width:1100px){
|
||||
html[data-organizations] .ws-tiles.six{grid-template-columns:repeat(3,minmax(0,1fr))}
|
||||
html[data-organizations] .ws-ibx-grid.with-insp{grid-template-columns:minmax(0,1fr)}
|
||||
@@ -740,8 +785,6 @@ html[data-organizations] #copy-status:empty{display:none}
|
||||
html[data-organizations] .ws-split{grid-template-columns:minmax(0,1fr)}
|
||||
html[data-organizations] .ws-tiles,html[data-organizations] .ws-tiles.six{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
html[data-organizations] .ws-sec-h .note{flex-basis:100%;order:3}
|
||||
html[data-organizations] .ws-cfg li{grid-template-columns:18px minmax(0,1fr) auto auto}
|
||||
html[data-organizations] .ws-cfg .v{grid-column:2/-1;grid-row:2}
|
||||
html[data-organizations] .ws-meta{padding-left:0;margin-top:0}
|
||||
html[data-organizations] .ws-orghead .ws-right{margin-left:0}
|
||||
html[data-organizations] .ws-busctl,html[data-organizations] .ws-busctl .bus-restart{align-items:flex-start}
|
||||
|
||||
@@ -44,6 +44,7 @@
|
||||
// done: 'week' shows the tasks the Dashboard's Done this week tile counts. It stays in the browser:
|
||||
// the rows already carry done and their last change, the same test the tile's count uses.
|
||||
const filter = { org: '', project: '', assignee: '', state: '', label: '', q: '', done: '' };
|
||||
let addrAssignee = '';
|
||||
const WEEK_MS = 7 * 24 * 3600 * 1000;
|
||||
const doneThisWeek = t => t.done && t.changedAt && Date.now() - Date.parse(t.changedAt) <= WEEK_MS;
|
||||
const DONE_NOTE = 'Done this week counts done tasks by their last change; the bus records no time a task was done.';
|
||||
@@ -358,6 +359,11 @@
|
||||
filter.org = scope || (ORG_ID.test(org) ? org : '');
|
||||
filter.project = PROJECT_SELECTOR.test(project) || project === '-' ? project : '';
|
||||
filter.done = q.get('done') === 'week' ? 'week' : '';
|
||||
// SP12: `assignee` in the address (the agent drawer's link) sets the Assignee filter once per new
|
||||
// value; the select changes it after that, and a poll does not put the address's value back.
|
||||
const who = String(q.get('assignee') || '');
|
||||
// When the address drops it, the filter it set goes too, unless the select has changed it since.
|
||||
if (who !== addrAssignee) { const was = addrAssignee; addrAssignee = who; if (ROLE.test(who)) filter.assignee = who; else if (!who && was && filter.assignee === was) filter.assignee = ''; }
|
||||
if (filter.org && filter.project && filter.project !== '-' && !filter.project.startsWith(`${filter.org}:`)) filter.project = '';
|
||||
if (dragging) await Promise.race([dragEnded, new Promise(r => setTimeout(r, 30000))]);
|
||||
// Two renders at once (a first load, a poll during a filter change): the replaced one draws from the newer read.
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
const dot = (cls, glyph, word, shown = false) => `<span class="ws-dot ${cls}" title="${esc(word)}"><b aria-hidden="true">${glyph}</b>${shown ? esc(word) : `<span class="ws-sr">${esc(word)}</span>`}</span>`;
|
||||
const orgHref = id => `#/orgs/${enc(id)}`;
|
||||
// SP3: a system route such as #/inbox has no organization prefix; both forms give the path.
|
||||
const route = () => location.hash.replace(/^#(?:\/orgs\/[^/]+)?/, '') || '/';
|
||||
const route = () => location.hash.replace(/^#(?:\/orgs\/[^/?]+)?/, '') || '/';
|
||||
const ensureThemes = async () => { if (!themes) themes = await data.themes().then(b => (Array.isArray(b?.themes) ? b.themes : [])).catch(() => []); return themes; };
|
||||
const instancesOf = value => { const v = value?.rows?.[0]?.instances ?? value?.instances; return v && typeof v === 'object' && !Array.isArray(v) ? v : null; };
|
||||
// #1873 A3: the root and project agent copies the bus booted with, from the same instances read.
|
||||
@@ -74,7 +74,21 @@
|
||||
const runningOf = rows => rows.filter(a => LIVE_STATES.has(a.state)).length;
|
||||
const workingOf = rows => rows.filter(a => a.state === 'working').length;
|
||||
const agentNote = (run, waiting) => `${run} running${waiting ? `, ${waiting} waiting on you` : ''}`;
|
||||
// SP13 (#1873): an instances answer that carries no runs for an agent (the bus gives `running` on
|
||||
// every answer it enriches) has not said whether the agent runs, so its state reads as not read,
|
||||
// never as not running.
|
||||
const STATE_UNREAD = ['s-unknown', '?', 'state not read'];
|
||||
const runsRead = item => Array.isArray(item?.running);
|
||||
// SP14 (#1873): an instances answer in which no agent carries runs has not said what runs at all, so
|
||||
// a count of running or working agents taken from it says not read, never 0. A copy that cannot
|
||||
// launch has no runs to give and is left out.
|
||||
const RUNS_WHY = 'the instance read did not say which agents run';
|
||||
const runsUnread = (inst, copies = {}) => {
|
||||
const all = [...Object.values(inst || {}), ...Object.values(copies || {}).filter(c => c && typeof c.name === 'string' && !copyBlocked(c))];
|
||||
return all.length > 0 && !all.some(runsRead);
|
||||
};
|
||||
const activity = (name, item, agents) => {
|
||||
if (!runsRead(item)) return STATE_UNREAD;
|
||||
const on = running(item) > 0;
|
||||
const held = on && agents ? agents.find(a => a?.role === name && item.running.includes(a.holder_run)) : null;
|
||||
return ACTIVITY[held?.state] || (on ? ['s-working', '●', 'running'] : ['s-idle', '–', 'not running']);
|
||||
@@ -165,7 +179,7 @@
|
||||
const secH = (title, note = '', link = '', attrs = '') => `<div class="ws-sec-h"><h2${attrs ? ` ${attrs}` : ''}>${title}</h2>${note ? `<span class="note">${note}</span>` : ''}${link}</div>`;
|
||||
|
||||
function settingsList(org, ctx) {
|
||||
const { business, settings, instances, orgCount } = ctx;
|
||||
const { business, settings, instances, orgCount, noRuns } = ctx;
|
||||
const b = business?.business, s = settings;
|
||||
const unread = 'Could not be read';
|
||||
const names = instances ? Object.keys(instances) : null;
|
||||
@@ -178,7 +192,7 @@
|
||||
['business', 'Identity', b ? `${label(org)} · ${org.id} · kind not recorded` : unread, 'org file', 'business'],
|
||||
['flag', 'Appearance', `${titleCase(theme)} theme · ${initials(org)} avatar`, b?.appearance?.theme || org.theme ? 'org file' : 'system', 'appearance'],
|
||||
['folder', 'Projects', b ? (Array.isArray(b.projects) && b.projects.length ? plural(b.projects.length, 'project') : 'No projects') : unread, 'org file', '#/projects'],
|
||||
['people', 'Agents and roles', names ? (names.length ? `${plural(names.length, 'agent')} · ${Object.values(instances).filter(running).length} running` : 'No agents') : unread, 'org file', 'agents'],
|
||||
['people', 'Agents and roles', names ? (names.length ? `${plural(names.length, 'agent')} · ${noRuns ? 'running not read' : `${Object.values(instances).filter(running).length} running`}` : 'No agents') : unread, 'org file', 'agents'],
|
||||
['term', 'Models and routing', models ? (models.length ? models.join(' · ') : 'No models set') : unread, 'org file', 'routing'],
|
||||
['queue', 'Arbiters', b ? arbiters || 'None set' : unread, 'org file', 'business'],
|
||||
['tasks', 'Task tracker', b ? (b.vars?.['tracker.kind'] ? titleCase(b.vars['tracker.kind']) : 'Not set') : unread, 'org file', 'business'],
|
||||
@@ -253,7 +267,7 @@
|
||||
const restart = window.MosaicConsole?.busButton?.('Restart the bus') || '';
|
||||
return `<div class="banner err" role="status" data-org-down><div><b>${stopped ? 'The bus is not running.' : 'The bus is not answering.'}</b> Nothing about ${esc(label(org))}'s agents or packs can be read until it ${stopped ? 'starts' : 'answers'}.${tail}</div>${restart ? `<div class="actions">${restart}</div>` : ''}</div>`;
|
||||
}
|
||||
async function dashboard(id = window.MosaicOrg.id) {
|
||||
async function dashboard(id = window.MosaicOrg.id, opts = {}) {
|
||||
const why = 'ws-reload-why';
|
||||
// Only an organization the membership list names is read; anything else reads nothing more.
|
||||
const [listRead] = await Promise.all([data.organizations().catch(() => null), ensureThemes()]);
|
||||
@@ -266,11 +280,16 @@
|
||||
// while the bus is down, the reason the banner above everything else says. It runs beside the
|
||||
// organization's own reads, not after them.
|
||||
const wsRead = data.workspace({ org: id, sections: ['sessions', 'projects', 'metrics'] }).catch(() => null);
|
||||
const reads = await Promise.allSettled([data.business(id), data.settings(id), data.instances(id), data.threads(id), data.projects(id), data.queue(id), data.agents(id), data.claims(id), ...(stopped ? [] : [window.MosaicAutonomy?.load(id), window.MosaicPacks?.load(id), window.MosaicWorkflows?.load(id)])]);
|
||||
// SP12: an agent row opens its drawer over this page; only an agent of this organization.
|
||||
// SP13: it waits on its own instances read only until this page's reads have answered.
|
||||
let pageRead; const page = new Promise(done => { pageRead = done; });
|
||||
const drawerRead = agentDrawer(opts.q ?? queryOf(), { only: id, configIn: opts.configIn, page }).catch(() => '');
|
||||
const reads = await Promise.allSettled([data.business(id), data.settings(id), data.instances(id), data.threads(id), data.projects(id), data.agents(id), data.claims(id), ...(stopped ? [] : [window.MosaicAutonomy?.load(id), window.MosaicPacks?.load(id), window.MosaicWorkflows?.load(id)])]);
|
||||
pageRead();
|
||||
const value = i => (reads[i].status === 'fulfilled' ? reads[i].value : null);
|
||||
const business = value(0), settings = value(1), instances = instancesOf(value(2));
|
||||
const threads = rowsOf(value(3)), projectRows = rowsOf(value(4)), queue = rowsOf(value(5));
|
||||
const agents = rowsOf(value(6)), claims = rowsOf(value(7));
|
||||
const threads = rowsOf(value(3)), projectRows = rowsOf(value(4));
|
||||
const agents = rowsOf(value(5)), claims = rowsOf(value(6));
|
||||
const docRead = business?.business ? await docs(id, business.business.projects).catch(() => ({ rows: [], failed: true })) : null;
|
||||
const ws = await wsRead;
|
||||
const wsRow = arr(ws?.orgs).find(r => r?.org === id) ?? null;
|
||||
@@ -301,7 +320,9 @@
|
||||
const off = !ws ? 'the read did not answer' : wsRow?.state === 'ok' ? null : wsRow?.state === 'starting' ? 'the bus is starting' : busWord(org);
|
||||
const whyNot = (names, metric = true) => off || missOf(wsRow, names) || (metric && !mine ? 'no figures were read' : null);
|
||||
const orgAgents = instances && ws ? agentRows([{ id, inst: instances, copies: copiesOf(value(2)) }], ws) : null;
|
||||
const agentsWhy = whyNot(['agents'], false) || (orgAgents ? null : 'the agent read did not answer');
|
||||
// SP14: no agent in the instances answer carries runs, so what runs, and so what works, was not read.
|
||||
const noRuns = !!instances && runsUnread(instances, copiesOf(value(2)));
|
||||
const agentsWhy = whyNot(['agents'], false) || (orgAgents ? null : 'the agent read did not answer') || (noRuns ? RUNS_WHY : null);
|
||||
const kpi = orgsOf(ws), oq = `org=${enc(id)}`;
|
||||
const orgTile = (key, title, href, why, fig) => kpiTile(kpi, { key, name: title, href, ...(why ? { none: `Not read: ${esc(why)}` } : fig) });
|
||||
const working = orgAgents ? workingOf(orgAgents) : 0, waiting = orgAgents?.filter(a => a.state === 'waiting').length ?? 0;
|
||||
@@ -332,17 +353,11 @@
|
||||
: !first ? '<span class="muted">No conversation held right now</span>'
|
||||
: thread ? `${esc(projectName(thread.project))}<span class="t2">${esc(thread.name || thread.id)}${more}</span>`
|
||||
: threads ? `<span class="muted">Conversation</span><span class="t2">${esc(first.thread)}${more}</span>` : '<span class="muted">Conversation unavailable</span>';
|
||||
return `<tr><td>${esc(shown)}</td><td>${where}</td><td class="hide-m mono">${modelCell(agent, model)}</td><td>${dot(acls, aglyph, aword, true)}${count > 1 ? ` <span class="muted">${count} sessions</span>` : ''}</td></tr>`;
|
||||
const pick = `${id}:${agent}`, on = new URLSearchParams(opts.q?.toString?.() ?? queryOf().toString());
|
||||
on.set('agent', pick);
|
||||
return `<tr data-ws-session-agent="${esc(pick)}"><td><a class="ws-drawer-open" href="${esc(`${orgHref(id)}/organization?${on.toString()}`)}" data-ws-drawer-open="${esc(pick)}" data-focus-key="${esc(`agent:${pick}`)}">${esc(shown)}</a></td><td>${where}</td><td class="hide-m mono">${modelCell(agent, model)}</td><td>${dot(acls, aglyph, aword, true)}${count > 1 ? ` <span class="muted">${count} sessions</span>` : ''}</td></tr>`;
|
||||
}).join('');
|
||||
const sessions = live === null ? (stopped ? '<p class="ws-panel tight note" data-bus-stopped>Sessions not read: the bus is stopped.</p>' : '<p class="ws-panel tight note">Sessions unavailable. The bus did not answer the instance read.</p>') : live.length ? `<div class="ws-tbl"><table><thead><tr><th scope="col">Agent</th><th scope="col">Project and task</th><th scope="col" class="hide-m">Model</th><th scope="col">Status</th></tr></thead><tbody>${sessionRows}</tbody></table></div>` : '<p class="ws-panel tight note">No active agent sessions</p>';
|
||||
const open = queue ? queue.filter(r => r?.state !== 'done').length : null;
|
||||
const queueNote = queue === null ? 'unavailable' : queue.length ? `${plural(queue.length, 'row')}, ${open} not done` : 'no rows';
|
||||
// E2E6 P2-6: a failed queue read says why, in the words the Queue page uses (server-redacted).
|
||||
const qerr = queue === null && reads[5].status === 'rejected' ? reads[5].reason : null;
|
||||
const queueWhy = queue !== null ? '' : `<p class="ws-panel tight note" data-org-queue-why>${qerr?.code === 'queue-refused' ? `The queue refused the read.${qerr.detail ? ` ${esc(qerr.detail.replace(/<path>/g, 'This checkout'))}` : ''}`
|
||||
: qerr?.status === 0 ? 'You are signed out. Reload the page to sign in again.'
|
||||
: qerr?.code === 'not-configured' ? 'This Console has no queue to read for this organization.'
|
||||
: `The queue read did not answer${qerr?.code ? ` (${esc(qerr.code)})` : ''}.`}</p>`;
|
||||
const sessions = live !== null && noRuns ? `<p class="ws-panel tight note" data-runs-unread>Not read: ${RUNS_WHY}.</p>` : live === null ? (stopped ? '<p class="ws-panel tight note" data-bus-stopped>Sessions not read: the bus is stopped.</p>' : '<p class="ws-panel tight note">Sessions unavailable. The bus did not answer the instance read.</p>') : live.length ? `<div class="ws-tbl"><table><thead><tr><th scope="col">Agent</th><th scope="col">Project and task</th><th scope="col" class="hide-m">Model</th><th scope="col">Status</th></tr></thead><tbody>${sessionRows}</tbody></table></div>` : '<p class="ws-panel tight note">No active agent sessions</p>';
|
||||
const stoppedPanel = (attr, title) => `<section class="panel" ${attr} data-bus-stopped><h3>${title}</h3><p class="note">Not read: the bus is stopped.</p></section>`;
|
||||
|
||||
return `<article class="ws ws-dash" data-org-dashboard>
|
||||
@@ -353,15 +368,13 @@
|
||||
${docrow}
|
||||
<div class="ws-split">
|
||||
<section aria-label="Measures and sessions">
|
||||
${secH('Active agent sessions', live ? (live.length ? `${live.length} running${tileAgents ? `, ${liveWorking} working` : ', working not read'}` : 'none running') : '', `<a href="#/agents?${oq}" data-focus-key="agents-all">This organization's agents</a>`)}
|
||||
${secH('Active agent sessions', live ? (noRuns ? 'running not read' : live.length ? `${live.length} running${tileAgents ? `, ${liveWorking} working` : ', working not read'}` : 'none running') : '', `<a href="#/agents?${oq}" data-focus-key="agents-all">This organization's agents</a>`)}
|
||||
${sessions}
|
||||
${secH('Queue', queueNote, '<a href="#/queue" data-org-queue data-focus-key="queue-open">Open queue</a>')}
|
||||
${queueWhy}
|
||||
</section>
|
||||
<section aria-label="Workflows and settings">
|
||||
${window.MosaicWorkflows?.card?.(id, { stopped, label: label(org) }) ?? ''}
|
||||
${secH('Settings', 'every setting, with where its value comes from')}
|
||||
${settingsList(org, { business, settings, instances, orgCount: list ? list.length : null })}
|
||||
${settingsList(org, { business, settings, instances, noRuns, orgCount: list ? list.length : null })}
|
||||
</section>
|
||||
</div>
|
||||
<div class="ws-wide">
|
||||
@@ -369,6 +382,7 @@
|
||||
${stopped ? stoppedPanel('data-packs', 'Starter packs') : window.MosaicPacks?.section(id) ?? ''}
|
||||
${stopped ? stoppedPanel('data-workflows', 'Workflows') : window.MosaicWorkflows?.section(id) ?? ''}
|
||||
</div>
|
||||
${await drawerRead}
|
||||
</article>`;
|
||||
}
|
||||
|
||||
@@ -680,13 +694,16 @@
|
||||
// An organization whose agent read failed is named, never counted as having none.
|
||||
const agentReads = await readInstances(o.rows.filter(r => r.state === 'ok' && !missOf(r, ['agents'])).map(r => r.org));
|
||||
const agentOk = agentReads.filter(r => r.inst), agentAll = agentRows(agentOk, body);
|
||||
const agentParts = agentOk.map(r => ({ id: r.id, n: agentAll.filter(a => a.org === r.id && a.state === 'working').length }));
|
||||
const waitingOn = agentAll.filter(a => a.state === 'waiting').length;
|
||||
// SP14 (#1873): an organization whose instances answer carries no runs adds nothing to the running
|
||||
// and working figures; the tile names it, and its row says running was not read.
|
||||
const runOk = agentOk.filter(r => !runsUnread(r.inst, r.copies)), runRows = agentAll.filter(a => runOk.some(r => r.id === a.org));
|
||||
const agentParts = runOk.map(r => ({ id: r.id, n: runRows.filter(a => a.org === r.id && a.state === 'working').length }));
|
||||
const waitingOn = runRows.filter(a => a.state === 'waiting').length;
|
||||
const ps = { needs: parts('needs', x => x.needsYou), tasks: parts('tasks', x => x.openTasks), done: parts('done', x => x.doneThisWeek), projects: parts('projects', x => x.projects?.active) };
|
||||
const needsN = fig('needs', ps.needs);
|
||||
const archived = per.filter(x => readers(o, SRC.projects).has(x.org)).reduce((a, x) => a + num(x.projects?.archived), 0);
|
||||
const tiles = !o.rows.length ? '<p class="ws-panel tight note" data-ws-tiles>No organizations yet, so there is nothing to count.</p>' : `<div class="ws-tiles six" data-ws-tiles role="group" aria-label="Key figures">
|
||||
${kpiTile(o, { key: 'agents', name: 'Agents working', href: '#/agents?state=working', big: agentOk.length ? sum(agentParts) : null, small: `of ${agentAll.length}`, parts: agentParts, delta: agentOk.length ? agentNote(runningOf(agentAll), waitingOn) : '', miss: [...notIn(['agents']), ...agentReads.filter(r => !r.inst).map(r => `${esc(o.name(r.id))} (${esc(instWhy(r))})`)] })}
|
||||
${kpiTile(o, { key: 'agents', name: 'Agents working', href: '#/agents?state=working', big: runOk.length ? sum(agentParts) : null, small: `of ${runRows.length}`, parts: agentParts, delta: runOk.length ? agentNote(runningOf(runRows), waitingOn) : '', miss: [...notIn(['agents']), ...agentReads.filter(r => !r.inst).map(r => `${esc(o.name(r.id))} (${esc(instWhy(r))})`), ...agentOk.filter(r => !runOk.includes(r)).map(r => `${esc(o.name(r.id))} (running not read)`)] })}
|
||||
${kpiTile(o, { key: 'orgs', name: 'Organizations', href: '#/dashboard', big: answered, small: `of ${o.rows.length} running`, delta: o.unread.length ? andList(o.unread.map(r => `${esc(o.name(r.org))} ${offWord(r)}`)) : 'every bus answered', attrs: ' data-ws-jump="orgs"' })}
|
||||
${kpiTile(o, { key: 'needs', name: 'Needs you', href: '#/inbox', big: needsN, small: needsN === 1 ? 'item' : 'items', parts: ps.needs, delta: needsN && t?.oldestNeedsYouAt ? `oldest ${span(t.oldestNeedsYouAt)}` : 'nothing waiting', miss: notIn(SRC.needs), ...noFig })}
|
||||
${kpiTile(o, { key: 'tasks', name: 'Open tasks', href: '#/tasks', big: fig('tasks', ps.tasks), parts: ps.tasks, miss: notIn(SRC.tasks), ...noFig })}
|
||||
@@ -706,7 +723,7 @@
|
||||
// that was not (a stopped bus) counts the agents in its file and says nothing of what runs.
|
||||
const mineRows = agentOk.some(a => a.id === id) ? agentAll.filter(a => a.org === id) : null;
|
||||
const count = mineRows ? mineRows.length : lv?.state === 'ok' && Array.isArray(lv.base?.agents) ? lv.base.agents.length : null;
|
||||
const agentsCell = count === null ? none : `${plural(count, 'agent')}${mineRows ? ` <small class="muted">(${runningOf(mineRows)} running, ${workingOf(mineRows)} working)</small>` : ''}`;
|
||||
const agentsCell = count === null ? none : `${plural(count, 'agent')}${mineRows ? ` <small class="muted">(${runOk.some(a => a.id === id) ? `${runningOf(mineRows)} running, ${workingOf(mineRows)} working` : 'running not read'})</small>` : ''}`;
|
||||
const projectsCell = x && projectsRead.has(id) ? plural(num(x.projects?.active), 'project') : none;
|
||||
const needsCell = x && inboxRead.has(id) ? (num(x.needsYou) ? `${num(x.needsYou)} needs you` : 'none waiting') : none;
|
||||
// #1873 SP2: a reason that only restates the state word ("the bus is not running" beside "bus stopped") is said once.
|
||||
@@ -969,8 +986,8 @@
|
||||
// `opts.scope` names one organization (#/orgs/<id>/agents): the same table, that organization only.
|
||||
// `opts.fireIn(org)` says from that organization's own config whether this Console decides there;
|
||||
// Fire is drawn only on the system page and only there, and posts to the row's organization (bus.js).
|
||||
const AGENT_STATE = [['working', 'Working'], ['waiting', 'Waiting on you'], ['idle', 'Idle'], ['running', 'Running, state unknown'], ['not-running', 'Not running'], ['cant-launch', "Can't launch"]];
|
||||
const AGENT_STATE_KEY = { working: 'working', 'waiting on you': 'waiting', idle: 'idle', running: 'running', 'not running': 'not-running', "can't launch": 'cant-launch' };
|
||||
const AGENT_STATE = [['working', 'Working'], ['waiting', 'Waiting on you'], ['idle', 'Idle'], ['running', 'Running, state unknown'], ['not-running', 'Not running'], ['not-read', 'State not read'], ['cant-launch', "Can't launch"]];
|
||||
const AGENT_STATE_KEY = { working: 'working', 'waiting on you': 'waiting', idle: 'idle', running: 'running', 'not running': 'not-running', 'state not read': 'not-read', "can't launch": 'cant-launch' };
|
||||
// Each named organization's instances read, and whether this Console decides there when `fireIn` is given.
|
||||
const readInstances = (ids, fireIn) => Promise.all(ids.map(id => Promise.all([
|
||||
data.instances(id).then(v => ({ inst: instancesOf(v), copies: copiesOf(v) }), err => ({ inst: null, copies: {}, err })),
|
||||
@@ -993,12 +1010,12 @@
|
||||
const d = activity(name, item, agents);
|
||||
// Never Fire the chief, the assistant or an instance the bus would refuse to end.
|
||||
const keep = item?.definition === 'chief-of-staff' || name === 'chief' || item?.definition === 'assistant' || item?.endProtected === true;
|
||||
all.push({ org: r.id, key: name, name, level: 'org', role: roleWords(item), id: isHired(item) ? item.definition : '', dot: d, s: session(name), fire: r.fire && !keep });
|
||||
all.push({ org: r.id, key: name, name, level: 'org', role: roleWords(item), id: isHired(item) ? item.definition : '', dot: d, s: session(name), fire: r.fire && !keep, keep, item });
|
||||
}
|
||||
for (const [key, c] of Object.entries(r.copies || {})) {
|
||||
if (!c || typeof c.name !== 'string') continue;
|
||||
const d = copyDot(key, c, agents);
|
||||
all.push({ org: r.id, key, name: c.name, level: c.level === 'project' ? 'project' : 'root', role: roleWords(c), id: copyBlocked(c) ? copyWhy(c) : '', dot: d, s: session(key), project: c.level === 'project' && c.project ? projectRef(r.id, c.project) : null, fire: false });
|
||||
all.push({ org: r.id, key, name: c.name, level: c.level === 'project' ? 'project' : 'root', role: roleWords(c), id: copyBlocked(c) ? copyWhy(c) : '', dot: d, s: session(key), project: c.level === 'project' && c.project ? projectRef(r.id, c.project) : null, fire: false, keep: true, item: c });
|
||||
}
|
||||
}
|
||||
for (const a of all) a.state = AGENT_STATE_KEY[a.dot[2]] || 'not-running';
|
||||
@@ -1011,6 +1028,10 @@
|
||||
const org = scope ? [scope] : listParam(q, 'org', id => ORG_ID.test(id));
|
||||
const want = String(q?.get?.('state') || '');
|
||||
const stateF = AGENT_STATE.some(([k]) => k === want) ? want : null;
|
||||
// SP12: the system page's agent drawer reads beside the page.
|
||||
// SP13: it waits on its own instances read only until this page's reads have answered.
|
||||
let pageRead = () => {}; const page = new Promise(done => { pageRead = done; });
|
||||
const drawerRead = scope ? Promise.resolve('') : agentDrawer(q, { configIn: opts.configIn, page }).catch(() => '');
|
||||
let body;
|
||||
try { [body] = await Promise.all([data.workspace({ sections: ['sessions', 'projects'] }), ensureThemes()]); took(body); }
|
||||
catch (err) { return failedPage('ws-agents-all', 'data-ws-agents', 'Agents', err); }
|
||||
@@ -1019,6 +1040,7 @@
|
||||
const askable = (scope ? o.rows : every.rows).filter(r => r.state === 'ok');
|
||||
// Each answering organization's instances, and (system page only) whether this Console decides there.
|
||||
const reads = await readInstances(askable.map(r => r.org), scope ? null : opts.fireIn);
|
||||
pageRead();
|
||||
const all = agentRows(reads, body);
|
||||
const counts = new Map();
|
||||
for (const a of all) counts.set(a.org, (counts.get(a.org) || 0) + 1);
|
||||
@@ -1036,7 +1058,7 @@
|
||||
const work = a => (a.s?.task ? `${esc(a.s.task.title || a.s.task.ref)}${a.s.task.title && a.s.task.ref ? `<span class="t2 mono">${esc(a.s.task.ref)}</span>` : ''}` : '<span class="muted">nothing reported</span>');
|
||||
const LEVEL_WORD = { root: 'root agent copy', project: 'project agent' };
|
||||
const row = a => `<tr class="ws-row ws-edge ws-o${a === hit ? ' on' : ''}" style="${o.style(a.org)}" data-ws-agent="${esc(akey(a))}"${a === hit ? ' aria-current="true"' : ''}>
|
||||
<td class="t1">${esc(a.name)}${a.id ? `<span class="t2${a.level === 'org' ? ' mono' : ''}">${esc(a.id)}</span>` : ''}<span class="ws-ichips">${orgChip(a)}${projChip(a)}<span class="show-m ws-arole">${esc(a.role)}</span></span><span class="t2 show-m">${a.s?.task ? `Working on ${esc(a.s.task.title || a.s.task.ref)}` : 'Working on nothing reported'}</span></td>
|
||||
<td class="t1">${scope ? esc(a.name) : drawerLink(q, a)}${a.id ? `<span class="t2${a.level === 'org' ? ' mono' : ''}">${esc(a.id)}</span>` : ''}<span class="ws-ichips">${orgChip(a)}${projChip(a)}<span class="show-m ws-arole">${esc(a.role)}</span></span><span class="t2 show-m">${a.s?.task ? `Working on ${esc(a.s.task.title || a.s.task.ref)}` : 'Working on nothing reported'}</span></td>
|
||||
<td class="hide-m" data-ws-role>${esc(a.role)}${a.level !== 'org' ? `<span class="t2">${esc(LEVEL_WORD[a.level])}</span>` : ''}</td>
|
||||
<td>${dot(...a.dot, true)}</td>
|
||||
<td class="hide-m" data-ws-work>${work(a)}</td>
|
||||
@@ -1077,9 +1099,262 @@
|
||||
</div>
|
||||
${table}
|
||||
${scope ? '' : `<div data-agents-receipt="*" role="status">${window.MosaicDecide?.fireNote('*') ?? ''}</div>`}
|
||||
${await drawerRead}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
// ---- the agent drawer (#1873 SP12) ----
|
||||
// `?agent=<org>:<name>` on #/agents or an organization page opens one agent's details at the right of
|
||||
// the page; the page stays under it. Every field comes from a read the Console already makes: the
|
||||
// workspace read scoped to the agent's organization (its session, project, task, open tasks and the
|
||||
// decisions it raised), that organization's instances read (role, source, state) and its business
|
||||
// read (model). A field no read gives is left out. Actions follow the organization's own config:
|
||||
// Message where it sends chat there, Stop (one agent, /agent/terminate) where it changes agents.
|
||||
const agentPick = q => {
|
||||
const v = String(q?.get?.('agent') || ''), cut = v.indexOf(':');
|
||||
if (cut < 1) return null;
|
||||
const org = v.slice(0, cut), key = v.slice(cut + 1);
|
||||
return ORG_ID.test(org) && key && key.length <= 200 && !/\s/.test(key) ? { org, key, id: v } : null;
|
||||
};
|
||||
const DRAWER_LIMIT = 5, STOP_REASON = 'Stopped from the agent drawer.';
|
||||
const STOP_UNKNOWN = 'Outcome unknown. Read the agents again before trying; nothing was retried.';
|
||||
// The Stop state of the drawer's agent survives repaints: `confirm` while it asks, `busy` while the
|
||||
// request is open, then the result in words beside the button.
|
||||
let stopState = null; // { id, confirm, busy, text }
|
||||
let drawerFocus = false, drawerShown = null;
|
||||
// The drawer holds at most one history entry. A row opened from the page without a drawer pushes one
|
||||
// entry marked in history.state; switching rows replaces it. Close goes Back only from that marked
|
||||
// entry, so a shared link or a reload of an unmarked one never leaves the Console.
|
||||
const DRAWER_MARK = 'mosaicAgentDrawer';
|
||||
const stateOf = () => (history.state && typeof history.state === 'object' ? history.state : null);
|
||||
const unmarked = () => { const st = stateOf(); if (!st || !(DRAWER_MARK in st)) return history.state; const { [DRAWER_MARK]: _, ...rest } = st; return rest; };
|
||||
const drawerHref = (q, id) => { const n = new URLSearchParams(q?.toString?.() || ''); n.set('agent', id); return `#${pathOf()}?${n.toString()}`; };
|
||||
// The address of the page under the drawer: the organization prefix and path, the query without `agent`.
|
||||
const sansAgent = () => { const n = queryOf(); n.delete('agent'); const s = n.toString(); return `${/^#\/orgs\/[^/?]+/.exec(location.hash)?.[0] ?? '#'}${pathOf()}${s ? `?${s}` : ''}`; };
|
||||
// The row's name as a link that opens the drawer: a native link, so Tab reaches it and Enter opens it.
|
||||
const drawerLink = (q, a) => `<a class="ws-drawer-open" href="${esc(drawerHref(q, `${a.org}:${a.key}`))}" data-ws-drawer-open="${esc(`${a.org}:${a.key}`)}" data-focus-key="${esc(`agent:${a.org}:${a.key}`)}">${esc(a.name)}</a>`;
|
||||
const stopConfirm = (name, who) => `<span class="ws-drawer-confirm" data-drawer-stop-confirm>Stop ${esc(who)}? <button type="button" class="ws-btn danger" data-drawer-stop-yes data-focus-key="drawer-stop-yes">Stop ${esc(name)}</button> <button type="button" class="ws-btn" data-drawer-stop-no data-focus-key="drawer-stop-no">Cancel</button></span>`;
|
||||
function stopActions(pick, a, orgName) {
|
||||
const st = stopState?.id === pick.id ? stopState : null;
|
||||
const who = `${a.name} in ${orgName}`;
|
||||
return `<button type="button" class="ws-btn" data-drawer-stop data-focus-key="drawer-stop"${st?.busy || st?.confirm ? ' disabled' : ''}>${st?.busy ? 'Stopping…' : 'Stop'}<span class="ws-sr"> ${esc(who)}</span></button>${st?.confirm ? stopConfirm(a.name, who) : ''}`;
|
||||
}
|
||||
// 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.
|
||||
let drawerInst = null, drawerReads = 0; // { org, n, done, value, p }
|
||||
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; });
|
||||
drawerInst = r;
|
||||
return r;
|
||||
};
|
||||
async function agentDrawer(q, opts = {}) {
|
||||
const pick = agentPick(q);
|
||||
if (!pick || (opts.only && pick.org !== opts.only)) return '';
|
||||
const { org, id } = pick;
|
||||
const ir = drawerInstRead(org);
|
||||
const [body, business, config] = await Promise.all([
|
||||
data.workspace({ org, sections: ['sessions', 'projects', 'inbox', 'tasks'] }).catch(() => null),
|
||||
data.business(org).catch(() => null),
|
||||
typeof opts.configIn === 'function' ? Promise.resolve(opts.configIn(org)).catch(() => null) : null,
|
||||
ensureThemes(),
|
||||
]);
|
||||
await Promise.race([ir.p, opts.page ?? ir.p]);
|
||||
const pending = !ir.done;
|
||||
// SP14 (#1873): when the read answers, only the drawer repaints, from the reads it already has; the
|
||||
// page's own reads are not made again. Each open repaints its own drawer if it is still on screen and
|
||||
// still waits on this read (data-drawer-pending names the read), so a second agent opened while the
|
||||
// read was open repaints too. A closed drawer repaints nothing, and the answer is not kept for a later open.
|
||||
if (pending) ir.p.then(() => {
|
||||
if (drawerInst === ir) drawerInst = null;
|
||||
const node = document.querySelector(`#bus-view [data-ws-drawer="${CSS.escape(id)}"][data-drawer-pending="${ir.n}"]`);
|
||||
if (!node) return;
|
||||
const key = focusKey(node), tpl = document.createElement('template');
|
||||
tpl.innerHTML = drawerHtml(pick, { body, business, config, pending: false, instRead: ir.value });
|
||||
const fresh = tpl.content.firstElementChild;
|
||||
if (!fresh) return;
|
||||
node.replaceWith(fresh);
|
||||
refocus(fresh, key);
|
||||
});
|
||||
else if (drawerInst === ir) drawerInst = null;
|
||||
return drawerHtml(pick, { body, business, config, pending: pending && ir.n, instRead: pending ? null : ir.value });
|
||||
}
|
||||
function drawerHtml(pick, { body, business, config, pending, instRead }) {
|
||||
const { org, key, id } = pick;
|
||||
const o = orgsOf(body), orgName = o.name(org);
|
||||
const close = `<button type="button" class="x" data-drawer-close data-focus-key="drawer-close" aria-label="Close the agent details">×</button>`;
|
||||
const shell = (title, inner, attrs = '') => `<aside class="ws-drawer ws-o" style="${o.style(org)}" role="region" aria-labelledby="ws-drawer-h" data-ws-drawer="${esc(id)}"${attrs}><div class="hd"><h2 id="ws-drawer-h" tabindex="-1" data-focus-key="drawer-h">${esc(title)}</h2>${close}</div><div class="body">${inner}</div></aside>`;
|
||||
// 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 || {}))}.` : '';
|
||||
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, `<p class="note" data-drawer-missing>No agent named ${esc(key)} was read in ${esc(orgName)}.</p>`);
|
||||
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) => `<div class="ws-drawer-f"><dt>${term}</dt><dd data-drawer-${attr}>${value}</dd></div>`;
|
||||
// Role and where it came from. A hired agent reads as hired; no read names the template it was hired from.
|
||||
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 <code>${esc(hire)}</code>` : ''}${def ? `, definition <code>${esc(def)}</code>` : ''}` : `Organization agent${def ? `, definition <code>${esc(def)}</code>` : ''}`)
|
||||
: `${a.level === 'project' ? `Project agent copy${a.project?.name ? ` for ${esc(a.project.name)}` : ''}` : 'Root agent copy'}${def ? `, definition <code>${esc(def)}</code>` : ''}${a.id ? `. ${esc(a.id)}` : ''}`;
|
||||
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.
|
||||
const thread = arr(body?.sessions).find(x => x?.kind === 'thread' && x.org === org && x.instance === key) || null;
|
||||
const project = a.project ? { ...a.project, from: '' } : a.s?.project?.id ? { ...a.s.project, from: a.s.projectFrom === 'task' ? 'from its task' : '' } : thread?.project?.id ? { ...thread.project, from: 'from its conversation' } : null;
|
||||
const task = a.s?.task?.ref ? a.s.task : null;
|
||||
const taskHref = ref => `${orgHref(org)}/tasks?task=${enc(ref)}`;
|
||||
// Open tasks assigned to it, and the decisions it raised that wait on a human, from the same read.
|
||||
const tasksWhy = notRead(['tasks']);
|
||||
const open = arr(body?.tasks).filter(t => t?.org === org && !t.done && t.state !== 'done' && arr(t.assignees).includes(key));
|
||||
const held = Number.isFinite(wsRow?.tasksHeld);
|
||||
const board = `#/tasks?org=${enc(org)}&assignee=${enc(key)}`;
|
||||
const tasksBody = tasksWhy ? `<p class="note">Not read: ${esc(tasksWhy)}.</p>`
|
||||
: open.length ? `<ul class="ws-drawer-list">${open.slice(0, DRAWER_LIMIT).map(t => `<li><a href="${esc(taskHref(t.ref))}">${esc(t.title || t.ref)}</a>${t.state ? ` <span class="t2">${esc(t.state)}</span>` : ''}</li>`).join('')}</ul>`
|
||||
: '<p class="note">No open tasks assigned to it.</p>';
|
||||
const tasksAll = tasksWhy ? '' : `<a class="ws-more" href="${esc(board)}" data-drawer-tasks-all data-focus-key="drawer-tasks-all">${held ? 'Its tasks on the Tasks board' : open.length ? `All ${open.length} on the Tasks board` : 'The Tasks board, filtered to it'}</a>`;
|
||||
const decWhy = notRead(['inbox']);
|
||||
const raised = arr(body?.inbox).filter(d => d?.org === org && d.raisedBy === key && typeof d.id === 'string');
|
||||
const decBody = decWhy ? `<p class="note">Not read: ${esc(decWhy)}.</p>`
|
||||
: raised.length ? `<ul class="ws-drawer-list">${raised.slice(0, DRAWER_LIMIT).map(d => `<li><a href="${esc(`#/inbox?d=${enc(`${org}:${d.id}`)}`)}">${esc(d.question || d.id)}</a></li>`).join('')}</ul>${raised.length > DRAWER_LIMIT ? `<a class="ws-more" href="${esc(`#/inbox?org=${enc(org)}`)}">${raised.length - DRAWER_LIMIT} more in the Inbox</a>` : ''}`
|
||||
: '<p class="note">No decisions it raised are waiting on you.</p>';
|
||||
// Actions, only where this organization's config says this Console writes there.
|
||||
const chat = config?.chatSend === true && config?.tester !== true, change = config?.settingsSend === true && config?.tester !== true;
|
||||
const acts = [];
|
||||
if (chat && thread?.thread) acts.push(`<a class="ws-btn" href="${esc(`#/assistant?add=${enc(`${org}:${thread.thread}`)}`)}" data-drawer-message data-focus-key="drawer-message">Message<span class="ws-sr"> ${esc(a.name)}</span></a>`);
|
||||
else if (chat && a.level === 'org' && window.MosaicAgents?.isThread?.(def)) acts.push(`<a class="ws-btn" href="#/assistant" data-drawer-message data-focus-key="drawer-message">Message<span class="ws-sr"> ${esc(a.name)}</span></a> <span class="note">Start one from New thread in ${esc(orgName)}.</span>`);
|
||||
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(`<p class="note" data-drawer-nostop>${pending ? '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.`
|
||||
: 'It is not running, so there is nothing to stop.'}</p>`);
|
||||
const st = stopState?.id === id ? stopState : null;
|
||||
const actions = chat || change
|
||||
? `<div class="ws-drawer-acts" data-drawer-actions>${acts.join(' ')}<p class="ws-drawer-status" id="ws-drawer-status" role="status" data-drawer-status>${esc(st?.text || '')}</p></div>`
|
||||
: `<p class="note" data-drawer-readonly>This Console only reads ${esc(orgName)}. It can not message or stop its agents.</p>`;
|
||||
const fields = [
|
||||
field('org', 'Organization', orgChip(o, org)),
|
||||
unknown ? '' : field('role', 'Role', `${esc(a.role)}`),
|
||||
unknown ? '' : field('source', 'Source', source),
|
||||
field('state', 'State', unknown ? `<span class="muted">${unknown}</span>` : dot(...a.dot, true)),
|
||||
model ? field('model', 'Model', `<span class="mono">${esc(model)}</span>`) : '',
|
||||
project ? field('project', 'Project', `<a href="${esc(`${orgHref(org)}/projects/${enc(project.id)}`)}">${esc(project.name || project.key || project.id)}</a>${project.from ? ` <span class="t2">${project.from}</span>` : ''}`) : '',
|
||||
task ? field('task', 'Task', `<a href="${esc(taskHref(task.ref))}">${esc(task.title || task.ref)}</a>${task.title ? ` <span class="t2 mono">${esc(task.ref)}</span>` : ''}`) : '',
|
||||
].join('');
|
||||
return shell(a.name, `<dl class="ws-drawer-fields">${fields}</dl>
|
||||
<section class="ws-drawer-sec" data-drawer-tasks aria-label="Open tasks assigned to ${esc(a.name)}"><h3>Open tasks</h3>${tasksBody}${tasksAll}</section>
|
||||
<section class="ws-drawer-sec" data-drawer-decisions aria-label="Decisions ${esc(a.name)} raised"><h3>Decisions waiting on you</h3>${decBody}</section>
|
||||
${actions}`, ` data-drawer-org-id="${esc(org)}" data-drawer-name="${esc(a.name)}" data-drawer-org-name="${esc(orgName)}"${pending ? ` data-drawer-pending="${pending}"` : ''}`);
|
||||
}
|
||||
// Closing goes Back when a row link on this page pushed the current entry; otherwise it drops
|
||||
// `agent` from the address in place. Either way the page repaints without it and focus returns to the row.
|
||||
function closeDrawer() {
|
||||
if (!stopState?.busy) stopState = null;
|
||||
if (stateOf()?.[DRAWER_MARK] && queryOf().has('agent')) { history.back(); return; }
|
||||
history.replaceState(unmarked(), '', sansAgent());
|
||||
document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
|
||||
}
|
||||
// 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() {
|
||||
const view = document.getElementById('bus-view'), d = view?.querySelector('[data-ws-drawer]');
|
||||
const now = d?.dataset.wsDrawer || null, was = drawerShown;
|
||||
drawerShown = now;
|
||||
if (d && drawerFocus) { drawerFocus = false; d.querySelector('h2')?.focus({ preventScroll: true }); return; }
|
||||
drawerFocus = false;
|
||||
if (!now && was) {
|
||||
const a = document.activeElement;
|
||||
if (!a || a === document.body || !view?.contains(a)) view?.querySelector(`[data-focus-key="${CSS.escape(`agent:${was}`)}"]`)?.focus({ preventScroll: true });
|
||||
}
|
||||
}
|
||||
async function stopAgent(d) {
|
||||
const id = d.dataset.wsDrawer, org = d.dataset.drawerOrgId, name = id.slice(org.length + 1), orgName = d.dataset.drawerOrgName;
|
||||
stopState = { id, busy: true, text: `Stopping ${name}…` };
|
||||
const repaint = () => document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
|
||||
const paint = () => { const now = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"]`); if (!now) return; const s = now.querySelector('[data-drawer-status]'); if (s) s.textContent = stopState.text; const b = now.querySelector('[data-drawer-stop]'); if (b) { b.disabled = !!stopState.busy; b.firstChild.textContent = stopState.busy ? 'Stopping…' : 'Stop'; } now.querySelector('[data-drawer-stop-confirm]')?.remove(); };
|
||||
const finish = text => { stopState = { id, text }; paint(); const b = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"] [data-drawer-stop]`); b?.focus({ preventScroll: true }); };
|
||||
paint();
|
||||
let res, body = null;
|
||||
try { res = await fetch(`/api/orgs/${enc(org)}/agent/terminate`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ instance: name, reason: STOP_REASON }), cache: 'no-store', redirect: 'manual' }); }
|
||||
catch { return finish(`Not stopped: ${STOP_UNKNOWN}`); }
|
||||
if (res.type === 'opaqueredirect' || res.status === 401) return finish('Not stopped: sign in again, then read the agents.');
|
||||
try { body = await res.json(); } catch { body = null; }
|
||||
if (!res.ok || body?.sent !== true && !body?.request) {
|
||||
if (body?.sent === false && typeof body.message === 'string' && body.message) return finish(`Not stopped: ${body.message}`);
|
||||
if (res.status === 403 && body?.error === 'read-only') return finish(`Not stopped: this Console only reads agents in ${orgName} (read-only).`);
|
||||
if (body?.sent === false && typeof body.error === 'string') return finish(`Not stopped: the bus refused (${body.error}).`);
|
||||
return finish(`Not stopped: ${STOP_UNKNOWN}`);
|
||||
}
|
||||
const request = typeof body?.request === 'string' ? body.request : '';
|
||||
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(request)) return finish(STOP_UNKNOWN);
|
||||
stopState = { id, busy: true, text: `Stop asked: request ${request} is open.` }; paint();
|
||||
for (let tries = 0; tries < 90; tries++) {
|
||||
await new Promise(r => setTimeout(r, 2000));
|
||||
let r = null;
|
||||
try { const got = await fetch(`/api/orgs/${enc(org)}/agent/request?id=${enc(request)}`, { cache: 'no-store', redirect: 'manual' }); if (got.type === 'opaqueredirect') return finish('Sign in again, then read the agents.'); r = got.ok ? await got.json() : null; } catch { continue; }
|
||||
if (r?.request === request && r.state === 'closed') {
|
||||
if (r.reason) return finish(`Not stopped: ${r.reason}.`);
|
||||
stopState = { id, text: `Stopped ${name}.` }; repaint(); return;
|
||||
}
|
||||
}
|
||||
finish(`Request ${request} is still open. Read the agents again later.`);
|
||||
}
|
||||
document.addEventListener('click', e => {
|
||||
const link = e.target.closest?.('[data-ws-drawer-open]');
|
||||
if (link) {
|
||||
if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;
|
||||
e.preventDefault();
|
||||
const to = new URL(link.href).hash;
|
||||
// The open row again: the address stays, focus goes to the drawer's heading.
|
||||
if (to === location.hash) { document.querySelector('#bus-view [data-ws-drawer] h2')?.focus({ preventScroll: true }); return; }
|
||||
drawerFocus = true;
|
||||
if (queryOf().has('agent')) history.replaceState(history.state, '', to);
|
||||
else history.pushState({ ...(stateOf() || {}), [DRAWER_MARK]: true }, '', to);
|
||||
document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
|
||||
return;
|
||||
}
|
||||
const d = e.target.closest?.('[data-ws-drawer]');
|
||||
if (!d) return;
|
||||
if (e.target.closest('[data-drawer-close]')) { closeDrawer(); return; }
|
||||
const id = d.dataset.wsDrawer;
|
||||
if (e.target.closest('[data-drawer-stop]') && !(stopState?.id === id && stopState.busy)) {
|
||||
const b = d.querySelector('[data-drawer-stop]'), name = d.dataset.drawerName;
|
||||
stopState = { id, confirm: true, text: '' };
|
||||
d.querySelector('[data-drawer-stop-confirm]')?.remove();
|
||||
b.insertAdjacentHTML('afterend', stopConfirm(name, `${name} in ${d.dataset.drawerOrgName}`));
|
||||
b.disabled = true;
|
||||
const s = d.querySelector('[data-drawer-status]'); if (s) s.textContent = '';
|
||||
d.querySelector('[data-drawer-stop-no]')?.focus({ preventScroll: true });
|
||||
return;
|
||||
}
|
||||
if (e.target.closest('[data-drawer-stop-no]')) { cancelStop(d); return; }
|
||||
if (e.target.closest('[data-drawer-stop-yes]')) stopAgent(d);
|
||||
});
|
||||
// Cancel the Stop question: nothing sent, Stop enabled again and focused.
|
||||
function cancelStop(d) {
|
||||
stopState = null;
|
||||
d.querySelector('[data-drawer-stop-confirm]')?.remove();
|
||||
const b = d.querySelector('[data-drawer-stop]'); if (b) { b.disabled = false; b.focus({ preventScroll: true }); }
|
||||
}
|
||||
// Escape cancels the Stop question while it asks, else closes the drawer, unless a dialog is open
|
||||
// or something else took the key.
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.key !== 'Escape' || e.defaultPrevented || document.querySelector('dialog[open]')) return;
|
||||
const d = document.querySelector('#bus-view [data-ws-drawer]');
|
||||
if (!d) return;
|
||||
e.preventDefault();
|
||||
if (d.querySelector('[data-drawer-stop-confirm]')) cancelStop(d); else closeDrawer();
|
||||
});
|
||||
|
||||
// ---- controls: filters write the hash query and repaint in place ----
|
||||
const pathOf = () => route().split('?')[0];
|
||||
const queryOf = () => new URLSearchParams(route().split('?')[1] || '');
|
||||
@@ -1088,7 +1363,8 @@
|
||||
for (const [k, v] of Object.entries(change)) { if (v === null || v === undefined || v === '' || (Array.isArray(v) && !v.length)) q.delete(k); else q.set(k, Array.isArray(v) ? v.join(',') : String(v)); }
|
||||
const s = q.toString();
|
||||
// SP3: the address keeps its own form, an organization's or the system's (#/inbox).
|
||||
history.replaceState(history.state, '', `${/^#\/orgs\/[^/?]+/.exec(location.hash)?.[0] ?? '#'}${pathOf()}${s ? `?${s}` : ''}`);
|
||||
// A filter change makes the entry differ from the one before the drawer, so Close then stays in place.
|
||||
history.replaceState(unmarked(), '', `${/^#\/orgs\/[^/?]+/.exec(location.hash)?.[0] ?? '#'}${pathOf()}${s ? `?${s}` : ''}`);
|
||||
if (render) document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
|
||||
}
|
||||
function setGrouping(g) {
|
||||
@@ -1141,6 +1417,6 @@
|
||||
|
||||
// U4b: the org mark (colour and initials) for the task board (tasks-board.js).
|
||||
const orgMark = Object.freeze({ ready: ensureThemes, av, colours, initials });
|
||||
window.MosaicWorkspace = Object.freeze({ dashboard, holdLive, graftLive, agentGrid, icon, orgMark, refresh: () => refresh(), av, colours, label, state, dot, themes: ensureThemes, home, projectsPage, inboxPage, agentsPage, inboxCount, setGrouping, orgsOf, orgChip, projChip, unreadNote, setQuery, classWord, get pollMs() { return pollMs; } });
|
||||
window.MosaicWorkspace = Object.freeze({ dashboard, afterPaint, holdLive, graftLive, agentGrid, icon, orgMark, refresh: () => refresh(), av, colours, label, state, dot, themes: ensureThemes, home, projectsPage, inboxPage, agentsPage, inboxCount, setGrouping, orgsOf, orgChip, projChip, unreadNote, setQuery, classWord, get pollMs() { return pollMs; } });
|
||||
refresh();
|
||||
})();
|
||||
@@ -4,7 +4,7 @@ import { proxyAdminHTTP } from './proxy-admin.mjs';
|
||||
import { createServer } from 'node:http';
|
||||
import { bindTesterSocket, TESTER_ORIGIN } from './tester-socket.mjs';
|
||||
import { readFileSync, openSync, fstatSync, closeSync, constants } from 'node:fs';
|
||||
import { timingSafeEqual, randomUUID } from 'node:crypto';
|
||||
import { timingSafeEqual, randomUUID, createHash } from 'node:crypto';
|
||||
import { resolve } from 'node:path';
|
||||
import { isIP } from 'node:net';
|
||||
import { BusReadError, busStatus as coreBusStatus, subjectOk, sendOutcome } from './bus.mjs';
|
||||
@@ -251,6 +251,10 @@ const one = (req, name) => (req.headersDistinct[name]?.length === 1 ? req.header
|
||||
// Q175 phase 1 (#1690): under --sso the writer comes from a session the handler already checked,
|
||||
// so it carries `sso: true` and the public origin. The header-preview signer is read-only.
|
||||
const signedIn = (req, p) => p.sso === true || one(req, p.header) === p.user;
|
||||
// SP14 (#1873): who is signed in, as an opaque stable name the page keys what it stores per person by
|
||||
// (the Assistant's kept pane messages). A hash of the session's subject, never the subject itself. A
|
||||
// Console with no sign-in has one fixed local viewer.
|
||||
const viewerOf = session => (typeof session?.sub === 'string' && session.sub ? createHash('sha256').update(JSON.stringify([String(session.provider ?? ''), String(session.iss ?? ''), session.sub])).digest('hex').slice(0, 32) : 'local');
|
||||
const ownOrigin = p => p.origin ?? `https://${p.host}`;
|
||||
async function busSend(req, res, { send, preview, log }) {
|
||||
if (!signedIn(req, preview)) return json(res, 401, { error: 'sign-in required' });
|
||||
@@ -1235,7 +1239,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
// `send`: the page shows the composer only where a send can pass (the public name, --send on).
|
||||
// `edit`: the editor shows Save only where a save can pass, the same test as the route's.
|
||||
// `user` and `federation` (FED R6) only when there is one, so the owner's config is unchanged.
|
||||
if (path === '/api/config') return json(res, 200, { board: upstream, ...(organizations && preselect ? { preselect } : {}), ...(tester ? { tester: true } : {}), ...(sso ? { sso: true } : {}), ...(sso?.devOwner ? { devOwner: true } : {}), ...(granted ? { user: true, chatGrants } : {}), ...(!tester && !granted && named && sso !== null && requestRead ? { requests: true, requestWrites: Boolean(send && requestWrite), workspaceFiles: true, projectRemotes: true, projectRemoteWrites: Boolean(send && requestWrite) } : {}), ...(hub ? { federation: hub } : {}), ...(organizations ? { orgSetup: !tester && !granted && named && sso !== null && owner.send !== null } : {}), ...(proxyAdmin && !tester && !granted && named && sso !== null && currentSession?.rootOwner === true ? { proxyAdmin: true, proxyAdminSend: owner.send !== null } : {}), send: !organizations && !tester && Boolean(send) && named, ...(organizations && orgId ? { chatSend: !tester && Boolean(send) && named && orgBusHealthy, settingsSend: !tester && !granted && Boolean(send) && named && orgBusHealthy } : {}), boot, consoleRestart: !tester && named && currentSession?.instanceRole === 'operator' && owner.send !== null && restart !== null && trail !== null, decide: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(decisionWrite) && named && sso !== null, edit: !organizations && !tester && !granted && Boolean(send) && Boolean(projectSave) && named, northStarApprove: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(projectSave) && Boolean(projectFile) && named });
|
||||
if (path === '/api/config') return json(res, 200, { board: upstream, viewer: viewerOf(currentSession), ...(organizations && preselect ? { preselect } : {}), ...(tester ? { tester: true } : {}), ...(sso ? { sso: true } : {}), ...(sso?.devOwner ? { devOwner: true } : {}), ...(granted ? { user: true, chatGrants } : {}), ...(!tester && !granted && named && sso !== null && requestRead ? { requests: true, requestWrites: Boolean(send && requestWrite), workspaceFiles: true, projectRemotes: true, projectRemoteWrites: Boolean(send && requestWrite) } : {}), ...(hub ? { federation: hub } : {}), ...(organizations ? { orgSetup: !tester && !granted && named && sso !== null && owner.send !== null } : {}), ...(proxyAdmin && !tester && !granted && named && sso !== null && currentSession?.rootOwner === true ? { proxyAdmin: true, proxyAdminSend: owner.send !== null } : {}), send: !organizations && !tester && Boolean(send) && named, ...(organizations && orgId ? { chatSend: !tester && Boolean(send) && named && orgBusHealthy, settingsSend: !tester && !granted && Boolean(send) && named && orgBusHealthy } : {}), boot, consoleRestart: !tester && named && currentSession?.instanceRole === 'operator' && owner.send !== null && restart !== null && trail !== null, decide: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(decisionWrite) && named && sso !== null, edit: !organizations && !tester && !granted && Boolean(send) && Boolean(projectSave) && named, northStarApprove: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(projectSave) && Boolean(projectFile) && named });
|
||||
if (path === '/healthz') return json(res, 200, { ok: true, ...(sso ? { sso: sso.health() } : {}) });
|
||||
if (path === '/favicon.ico') { res.writeHead(204); return res.end(); }
|
||||
const file = files.get(path);
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
// SP12 (#1873): selecting an agent on #/agents or in an organization page's Active agent sessions
|
||||
// table opens a detail drawer at the right of the page; the page under it stays. The address carries
|
||||
// the selection (?agent=<org>:<name>), so a reload reopens it and Back closes it. Escape and Close
|
||||
// close it and put focus back on the row. Every field comes from a read the Console already makes; a
|
||||
// field no read gives is left out. Actions show only where the agent's own organization config says
|
||||
// this Console writes there, and a refused action says why next to its button.
|
||||
// Every bus is a fake: acme and beta answer. The real GET /api/workspace and per-organization routes
|
||||
// serve the page; only the per-organization config and the agent writes are stubbed in the page.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { startServer } from '../src/serve.mjs';
|
||||
import { createDevOwner } from '../src/dev-owner.mjs';
|
||||
import { browser } from './browser.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
|
||||
const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
|
||||
const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString();
|
||||
const HIRE = '0f3c1a2b-4d5e-4f60-8a7b-9c0d1e2f3a4b';
|
||||
const THREAD = '7b1e2c3d-4f50-4a61-8b72-9c83d4e5f6a7';
|
||||
|
||||
function fixture() {
|
||||
const LIST = [
|
||||
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt' },
|
||||
{ id: 'beta', label: 'Beta Works', theme: 'grove' },
|
||||
];
|
||||
const task = (n, title, extra = {}) => ({ task_ref: `store:${n}`, source: 'store', at: at(20 + n), fields: { title, state: 'in-progress', group: 'p-site', assignees: ['coder'], ...extra } });
|
||||
const DATA = {
|
||||
acme: {
|
||||
projects: [{ id: 'p-site', repo: 'site', name: 'Website', archived: false, at: at(30) }],
|
||||
// Seven tasks name coder: six open, one done. The drawer lists five open ones and links the rest.
|
||||
tasks: [task(1, 'Hero copy'), task(2, 'Footer links'), task(3, 'Pricing table'), task(4, 'Contact form'), task(5, 'Blog index'), task(6, 'Search box'), task(7, 'Old banner', { state: 'done', done: true })],
|
||||
agents: [{ role: 'coder', holder_run: 'run-1', harness: 'claude', state: 'working', at: at(40), working: { since: at(40), messages: 2 } }],
|
||||
// Two decisions wait on a human: one coder raised, one chief raised.
|
||||
inbox: [
|
||||
{ id: 'dec-1', question: 'Ship the hero copy?', class: 'DECISION', raised_by_role: 'coder', task_ref: 'store:1', at: at(10) },
|
||||
{ id: 'dec-2', question: 'Hire a designer?', class: 'DECISION', raised_by_role: 'chief', task_ref: 'store:2', at: at(12) },
|
||||
],
|
||||
claims: [{ thread: THREAD, instance: 'assistant', holder_run: 'run-3', harness: 'claude', at: at(5) }],
|
||||
threads: [{ id: THREAD, project: 'p-site', name: 'Launch notes' }],
|
||||
instances: {
|
||||
coder: { definition: 'coder', running: ['run-1'] },
|
||||
chief: { definition: 'chief-of-staff', running: [] },
|
||||
assistant: { definition: 'assistant', running: ['run-3'] },
|
||||
},
|
||||
model: { coder: 'claude-opus-5-5' },
|
||||
},
|
||||
beta: {
|
||||
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' } } },
|
||||
model: {},
|
||||
},
|
||||
};
|
||||
const value = (id, name) => Promise.resolve(DATA[id]?.[name] ?? (['usage', 'limits'].includes(name) ? {} : []));
|
||||
const opts = id => ({
|
||||
bus: { inbox: () => value(id, 'inbox'), agents: () => value(id, 'agents'), 'thread.claims': () => value(id, 'claims'), tasks: () => value(id, 'tasks'), usage: () => value(id, 'usage'), limits: () => value(id, 'limits'), decisions: () => value(id, 'decisions') },
|
||||
chat: { threads: () => value(id, 'threads'), projects: () => value(id, 'projects') },
|
||||
});
|
||||
const member = org => ({ id: org.id, doc: { appearance: { theme: org.theme } }, status: async () => ({ healthy: true, pid: 4242, boot: null }), options: () => opts(org.id) });
|
||||
return {
|
||||
list: async () => LIST.map(o => ({ ...o, busHealthy: true })),
|
||||
members: async () => LIST.map(member),
|
||||
resolve: async id => {
|
||||
const org = LIST.find(o => o.id === id); if (!org) return null;
|
||||
const d = DATA[id];
|
||||
return {
|
||||
busHealthy: true,
|
||||
reads: {
|
||||
business: async () => ({ business: { id, human: 'jason', projects: d.projects.map(p => p.repo), appearance: { theme: org.theme }, instances: Object.entries(d.model).map(([instance, model]) => ({ instance, vars: { model } })) } }),
|
||||
settings: async () => ({}), queue: async () => ({ rows: [] }), busStatus: async () => ({}),
|
||||
},
|
||||
bus: {
|
||||
messages: async () => ({ messages: [], unread: 0 }), agents: async () => d.agents, 'thread.claims': async () => d.claims, inbox: async () => d.inbox, tasks: async () => d.tasks,
|
||||
instances: async () => ({ revision: 'a'.repeat(64), definitions: {}, instances: d.instances }),
|
||||
},
|
||||
chat: { projects: async () => d.projects, threads: async () => d.threads },
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Runs before the page's scripts. Acme's config says this Console sends there (chat and settings);
|
||||
// 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 = [];
|
||||
const answer = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
|
||||
window.fetch = async (url, init = {}) => {
|
||||
const u = String(url);
|
||||
const cfg = u.match(/^\\/api\\/orgs\\/([^/]+)\\/config$/);
|
||||
if (cfg) {
|
||||
const c = await (await real(url, init)).json();
|
||||
const writes = cfg[1] === 'acme';
|
||||
return answer(200, { ...c, chatSend: writes, settingsSend: writes, decide: writes });
|
||||
}
|
||||
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();
|
||||
if (!a) throw new TypeError('no answer queued');
|
||||
return answer(a.status ?? 200, a.body);
|
||||
};
|
||||
})();`;
|
||||
|
||||
async function setup(t, { viewport = [1440, 900], hash = '#/agents', stub = true } = {}) {
|
||||
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 });
|
||||
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`);
|
||||
const attr = (sel, name) => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.getAttribute(${JSON.stringify(name)}) ?? null`);
|
||||
const has = sel => b.evaluate(`!!document.querySelector(${JSON.stringify(sel)})`);
|
||||
return { b, base, wait: waitFor(b), text, attr, has };
|
||||
}
|
||||
const drawer = key => `document.querySelector('[data-ws-drawer="${key}"]')`;
|
||||
const open = key => `!!${drawer(key)} && ${drawer(key)}.querySelector("h2")?.textContent.length > 0`;
|
||||
const noDrawer = '!document.querySelector("[data-ws-drawer]")';
|
||||
const agentParam = 'new URLSearchParams(location.hash.split("?")[1] || "").get("agent")';
|
||||
const rowLink = key => `[data-ws-agent="${key}"] a[data-ws-drawer-open]`;
|
||||
const sessionLink = key => `[data-ws-session-agent="${key}"] a[data-ws-drawer-open]`;
|
||||
|
||||
test('a row on #/agents opens the drawer: a region with a heading, the page stays under it', async t => {
|
||||
const { b, wait, text, attr, has } = await setup(t);
|
||||
await wait(`document.querySelector(${JSON.stringify(rowLink('acme:coder'))})`);
|
||||
assert.equal(await attr(rowLink('acme:coder'), 'href'), '#/agents?agent=acme%3Acoder');
|
||||
await b.evaluate(`document.querySelector(${JSON.stringify(rowLink('acme:coder'))}).click()`);
|
||||
await wait(open('acme:coder'));
|
||||
assert.equal(await b.evaluate(agentParam), 'acme:coder');
|
||||
// A region, not a modal: no dialog role, no aria-modal, labelled by its heading.
|
||||
const d = '[data-ws-drawer="acme:coder"]';
|
||||
assert.equal(await attr(d, 'role'), 'region');
|
||||
assert.equal(await attr(d, 'aria-modal'), null);
|
||||
assert.equal(await b.evaluate(`document.getElementById(document.querySelector('${d}').getAttribute("aria-labelledby"))?.textContent`), 'coder');
|
||||
// The page under it stays: the agents table is still drawn and its heading is the page's.
|
||||
assert.equal(await has('[data-ws-agent-list]'), true);
|
||||
assert.equal(await text('#bus-view h1'), 'Agents');
|
||||
// At the right of the page.
|
||||
const box = await b.evaluate(`(() => { const r = document.querySelector('${d}').getBoundingClientRect(); return [Math.round(r.left), Math.round(r.right), innerWidth]; })()`);
|
||||
assert.ok(box[0] > box[2] / 2, `drawer left edge ${box[0]} should be in the right half of ${box[2]}`);
|
||||
assert.ok(box[1] >= box[2] - 20, `drawer right edge ${box[1]} should reach the right of ${box[2]}`);
|
||||
// At 1440 wide nothing on the page sits under it: the agents table ends left of the drawer.
|
||||
const table = await b.evaluate(`Math.round(document.querySelector('[data-ws-agent-list]').getBoundingClientRect().right)`);
|
||||
assert.ok(table <= box[0], `the agents table right edge ${table} should be left of the drawer at ${box[0]}`);
|
||||
});
|
||||
|
||||
test('the drawer shows each field from its read: name, organization, role and source, state, model, project, task, open tasks and decisions', async t => {
|
||||
const { b, wait, text, attr, has } = await setup(t, { hash: '#/agents?agent=acme%3Acoder' });
|
||||
await wait(open('acme:coder'));
|
||||
const d = '[data-ws-drawer="acme:coder"]';
|
||||
assert.equal(await text(`${d} h2`), 'coder');
|
||||
assert.equal(await text(`${d} [data-ws-orgchip]`), 'Acme Studio');
|
||||
assert.match(await text(`${d} [data-drawer-role]`), /coder/);
|
||||
assert.match(await text(`${d} [data-drawer-source]`), /Organization agent.*definition coder/);
|
||||
assert.match(await text(`${d} [data-drawer-state]`), /(^|\s)working$/);
|
||||
assert.match(await text(`${d} [data-drawer-model]`), /claude-opus-5-5/);
|
||||
// Project and task are links to their pages; the project is the task's, and says so.
|
||||
assert.equal(await attr(`${d} [data-drawer-project] a`, 'href'), '#/orgs/acme/projects/p-site');
|
||||
assert.match(await text(`${d} [data-drawer-project]`), /Website.*from its task/);
|
||||
assert.equal(await attr(`${d} [data-drawer-task] a`, 'href'), '#/orgs/acme/tasks?task=store%3A1');
|
||||
assert.match(await text(`${d} [data-drawer-task]`), /Hero copy/);
|
||||
// Open tasks assigned to it: five of six, newest first is not claimed; the done one is never listed.
|
||||
const tasks = await b.evaluate(`[...document.querySelectorAll('${d} [data-drawer-tasks] li a')].map(a => [a.textContent.trim(), a.getAttribute("href")])`);
|
||||
assert.equal(tasks.length, 5);
|
||||
assert.ok(tasks.every(([, href]) => /^#\/orgs\/acme\/tasks\?task=store%3A[1-6]$/.test(href)), JSON.stringify(tasks));
|
||||
assert.ok(!tasks.some(([title]) => title === 'Old banner'));
|
||||
assert.equal(await attr(`${d} [data-drawer-tasks-all]`, 'href'), '#/tasks?org=acme&assignee=coder');
|
||||
assert.match(await text(`${d} [data-drawer-tasks-all]`), /6/);
|
||||
// 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);
|
||||
// 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'`);
|
||||
// When the address drops the assignee, the board drops the filter it took from the address.
|
||||
await b.evaluate('location.hash = "#/tasks"');
|
||||
await wait(`document.querySelector('[data-tasks-board] select[data-tb-filter="assignee"]')?.value === ''`);
|
||||
});
|
||||
|
||||
test('a hired agent shows where its role came from; a not-running agent says not running', async t => {
|
||||
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/);
|
||||
assert.match(await text(`${d} [data-drawer-source]`), new RegExp(`hire decision ${HIRE}`));
|
||||
assert.match(await text(`${d} [data-drawer-state]`), /(^|\s)not running$/);
|
||||
assert.equal(await has(`${d} [data-drawer-model]`), false);
|
||||
});
|
||||
|
||||
test('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`);
|
||||
// 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/);
|
||||
});
|
||||
|
||||
test('the address round trip: Back closes the drawer, Forward and a reload open it again', async t => {
|
||||
const { b, base, wait } = await setup(t);
|
||||
await wait(`document.querySelector(${JSON.stringify(rowLink('beta:pm'))})`);
|
||||
await b.evaluate(`document.querySelector(${JSON.stringify(rowLink('beta:pm'))}).click()`);
|
||||
await wait(open('beta:pm'));
|
||||
await b.evaluate('history.back()');
|
||||
await wait(`${noDrawer} && location.hash === "#/agents"`);
|
||||
assert.equal(await b.evaluate('!!document.querySelector("[data-ws-agent-list]")'), true);
|
||||
await b.evaluate('history.forward()');
|
||||
await wait(open('beta:pm'));
|
||||
const hash = await b.evaluate('location.hash');
|
||||
await b.navigate(`${base}/${hash}`);
|
||||
await wait(open('beta:pm'));
|
||||
// The other filters stay in the address beside it.
|
||||
await b.navigate(`${base}/#/agents?org=beta&agent=beta%3Apm`);
|
||||
await wait(`${open('beta:pm')} && document.querySelectorAll("[data-ws-agent]").length === 2`);
|
||||
// An agent no read has says so, with Close; a malformed value opens nothing.
|
||||
await b.navigate(`${base}/#/agents?agent=beta%3Anobody`);
|
||||
await wait('document.querySelector("[data-ws-drawer] [data-drawer-missing]")');
|
||||
await b.navigate(`${base}/#/agents?agent=not-an-agent`);
|
||||
await wait(`document.querySelector("[data-ws-agent-list]") && ${noDrawer}`);
|
||||
});
|
||||
|
||||
test('the drawer holds at most one history entry: Close after switching agents, or after a shared link, stays in the Console', async t => {
|
||||
const { b, base, wait } = await setup(t);
|
||||
await wait(`document.querySelector(${JSON.stringify(rowLink('acme:coder'))})`);
|
||||
const before = await b.evaluate('history.length');
|
||||
await b.evaluate(`document.querySelector(${JSON.stringify(rowLink('acme:coder'))}).click()`);
|
||||
await wait(open('acme:coder'));
|
||||
// Another row while the drawer is open switches it in place: no second entry.
|
||||
await b.evaluate(`document.querySelector(${JSON.stringify(rowLink('beta:pm'))}).click()`);
|
||||
await wait(`${open('beta:pm')} && !${drawer('acme:coder')}`);
|
||||
assert.equal(await b.evaluate(agentParam), 'beta:pm');
|
||||
assert.equal(await b.evaluate('history.length'), before + 1);
|
||||
// The open row again does nothing to the address.
|
||||
await b.evaluate(`document.querySelector(${JSON.stringify(rowLink('beta:pm'))}).click()`);
|
||||
assert.equal(await b.evaluate('history.length'), before + 1);
|
||||
// One Close goes back to the page without the drawer.
|
||||
await b.evaluate(`${drawer('beta:pm')}.querySelector("[data-drawer-close]").click()`);
|
||||
await wait(`${noDrawer} && location.hash === "#/agents"`);
|
||||
// A shared link opened after another site: clicking its row and then Close stays here.
|
||||
await b.navigate('about:blank');
|
||||
await b.navigate(`${base}/#/agents?agent=acme%3Acoder`);
|
||||
await wait(open('acme:coder'));
|
||||
await b.evaluate(`document.querySelector(${JSON.stringify(rowLink('acme:coder'))}).click()`);
|
||||
await b.evaluate(`${drawer('acme:coder')}.querySelector("[data-drawer-close]").click()`);
|
||||
await wait(`location.href.startsWith(${JSON.stringify(base)}) && ${noDrawer} && location.hash === "#/agents"`);
|
||||
// Escape on a shared link does the same.
|
||||
await b.navigate(`${base}/#/agents?agent=beta%3Apm`);
|
||||
await wait(open('beta:pm'));
|
||||
await b.key('Escape');
|
||||
await wait(`location.href.startsWith(${JSON.stringify(base)}) && ${noDrawer} && location.hash === "#/agents"`);
|
||||
});
|
||||
|
||||
test('the keyboard path: Tab reaches the row, Enter opens, Escape closes and focus returns to the row', async t => {
|
||||
const { b, wait } = await setup(t);
|
||||
const link = JSON.stringify(rowLink('acme:coder'));
|
||||
await wait(`document.querySelector(${link})`);
|
||||
// Focus the control just before the row's link, then Tab onto it.
|
||||
await b.evaluate(`(() => { const all = [...document.querySelectorAll('a[href],button:not([disabled]),input,select,textarea,[tabindex]:not([tabindex="-1"])')].filter(e => e.getClientRects().length); const i = all.indexOf(document.querySelector(${link})); all[i - 1].focus(); })()`);
|
||||
await b.key('Tab');
|
||||
assert.equal(await b.evaluate(`document.activeElement === document.querySelector(${link})`), true);
|
||||
await b.key('Enter');
|
||||
await wait(open('acme:coder'));
|
||||
// Focus moves into the drawer, onto its heading.
|
||||
await wait(`document.activeElement === ${drawer('acme:coder')}.querySelector("h2")`);
|
||||
await b.key('Escape');
|
||||
await wait(`${noDrawer} && document.activeElement === document.querySelector(${link})`);
|
||||
assert.equal(await b.evaluate(agentParam), null);
|
||||
// Close does the same.
|
||||
await b.key('Enter');
|
||||
await wait(open('acme:coder'));
|
||||
await b.evaluate(`${drawer('acme:coder')}.querySelector("[data-drawer-close]").click()`);
|
||||
await wait(`${noDrawer} && document.activeElement === document.querySelector(${link})`);
|
||||
});
|
||||
|
||||
test('from an organization page\'s Active agent sessions the drawer opens over that page', async t => {
|
||||
const { b, base, wait, text, attr } = await setup(t, { hash: '#/orgs/acme/organization' });
|
||||
await wait(`document.querySelector(${JSON.stringify(sessionLink('acme:coder'))})`);
|
||||
assert.equal(await attr(sessionLink('acme:coder'), 'href'), '#/orgs/acme/organization?agent=acme%3Acoder');
|
||||
await b.evaluate(`document.querySelector(${JSON.stringify(sessionLink('acme:coder'))}).click()`);
|
||||
await wait(open('acme:coder'));
|
||||
// The organization page stays under it.
|
||||
assert.equal(await text('[data-org-dashboard] h1'), 'Acme Studio');
|
||||
assert.match(await text('[data-ws-drawer="acme:coder"] [data-drawer-model]'), /claude-opus-5-5/);
|
||||
await b.evaluate('history.back()');
|
||||
await wait(`${noDrawer} && location.hash === "#/orgs/acme/organization"`);
|
||||
assert.equal(await text('[data-org-dashboard] h1'), 'Acme Studio');
|
||||
await b.navigate(`${base}/#/orgs/acme/organization?agent=acme%3Aassistant`);
|
||||
await wait(open('acme:assistant'));
|
||||
});
|
||||
|
||||
test('Message opens the agent\'s thread in an Assistant pane; Stop asks first and a refusal says why', async t => {
|
||||
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}`);
|
||||
// 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);
|
||||
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]')`);
|
||||
assert.match(await text(`${d} [data-drawer-stop-confirm]`), /Stop coder in Acme Studio\?/);
|
||||
// Cancel: nothing sent, focus back on Stop.
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-stop-no]').click()`);
|
||||
await wait(`document.activeElement === document.querySelector('${d} [data-drawer-stop]')`);
|
||||
assert.deepEqual(await b.evaluate('window.__posts'), []);
|
||||
// Yes: one terminate for this one agent, refused by the bus, in words next to the button.
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').click()`);
|
||||
await wait(`document.querySelector('${d} [data-drawer-stop-yes]')`);
|
||||
await b.evaluate('window.__answers.push({ status: 409, body: { error: "instance-protected", message: "instance-protected: coder is protected from ending. Nothing changed.", sent: false } })');
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-stop-yes]').click()`);
|
||||
await wait(`/coder is protected/.test(document.querySelector('${d} [data-drawer-status]')?.textContent ?? "")`);
|
||||
assert.match(await text(`${d} [data-drawer-status]`), /^Not stopped: instance-protected: coder is protected from ending\. Nothing changed\.$/);
|
||||
const posts = await b.evaluate('window.__posts');
|
||||
assert.deepEqual(posts.map(p => [p.url, p.method]), [['/api/orgs/acme/agent/terminate', 'POST']]);
|
||||
assert.deepEqual(JSON.parse(posts[0].body), { instance: 'coder', reason: 'Stopped from the agent drawer.' });
|
||||
// The status sits beside the Stop button, in the same action group.
|
||||
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-status]').closest('[data-drawer-actions]') === document.querySelector('${d} [data-drawer-stop]').closest('[data-drawer-actions]')`), true);
|
||||
// A read-only refusal with no message from the server still says why.
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').click()`);
|
||||
await wait(`document.querySelector('${d} [data-drawer-stop-yes]')`);
|
||||
await b.evaluate('window.__answers.push({ status: 403, body: { error: "read-only", sent: false } })');
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-stop-yes]').click()`);
|
||||
await wait(`/read-only|only reads/.test(document.querySelector('${d} [data-drawer-status]')?.textContent ?? "")`);
|
||||
assert.match(await text(`${d} [data-drawer-status]`), /^Not stopped: this Console only reads agents in Acme Studio \(read-only\)\.$/);
|
||||
// Escape while it asks cancels only the question: the drawer stays and focus is back on Stop.
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').click()`);
|
||||
await wait(`document.querySelector('${d} [data-drawer-stop-no]') === document.activeElement`);
|
||||
await b.key('Escape');
|
||||
await wait(`!document.querySelector('${d} [data-drawer-stop-confirm]') && document.activeElement === document.querySelector('${d} [data-drawer-stop]')`);
|
||||
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').disabled`), false);
|
||||
assert.equal(await b.evaluate(agentParam), 'acme:coder');
|
||||
assert.equal(await b.evaluate('window.__posts').then(p => p.length), 2);
|
||||
// A Stop the bus takes: the request is followed until it closes, then the drawer says it stopped.
|
||||
const REQ = '0f0e0d0c-0b0a-4908-8706-050403020100';
|
||||
await b.evaluate(`window.__answers.push({ status: 200, body: { sent: true, request: '${REQ}' } }, { status: 200, body: { request: '${REQ}', state: 'closed' } })`);
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').click()`);
|
||||
await wait(`document.querySelector('${d} [data-drawer-stop-yes]')`);
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-stop-yes]').click()`);
|
||||
await wait(`/^Stopped coder\.$/.test(document.querySelector('${d} [data-drawer-status]')?.textContent ?? "")`);
|
||||
assert.deepEqual((await b.evaluate('window.__posts')).slice(2).map(p => [p.url, p.method]), [['/api/orgs/acme/agent/terminate', 'POST'], [`/api/orgs/acme/agent/request?id=${REQ}`, 'GET']]);
|
||||
// A not-running agent has nothing to stop.
|
||||
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);
|
||||
// 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\.$/);
|
||||
});
|
||||
|
||||
test('no action is shown where the Console cannot write for the agent\'s organization', async t => {
|
||||
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`);
|
||||
assert.match(await text(`${d} [data-drawer-readonly]`), /only reads Beta Works/);
|
||||
});
|
||||
|
||||
test('at 390 wide the drawer is a full-width sheet', async t => {
|
||||
const { b, wait } = await setup(t, { viewport: [390, 844], hash: '#/agents?agent=acme%3Acoder' });
|
||||
await wait(open('acme:coder'));
|
||||
const box = await b.evaluate(`(() => { const r = ${drawer('acme:coder')}.getBoundingClientRect(); return [Math.round(r.left), Math.round(r.width), document.documentElement.clientWidth, document.documentElement.scrollWidth]; })()`);
|
||||
assert.equal(box[0], 0);
|
||||
assert.equal(box[1], box[2]);
|
||||
assert.ok(box[3] <= box[2], `no horizontal page scroll: ${box[3]} > ${box[2]}`);
|
||||
});
|
||||
@@ -69,9 +69,9 @@ function orgs(state) {
|
||||
};
|
||||
}
|
||||
|
||||
async function open(t, { width = 1440, height = 900, hash, state = { down: new Set(['home']), sent: [], created: [] } } = {}) {
|
||||
async function open(t, { width = 1440, height = 900, hash, state = { down: new Set(['home']), sent: [], created: [] }, sso = createDevOwner() } = {}) {
|
||||
const organizations = orgs(state);
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), organizations, send: async () => ({}), board: 'http://127.0.0.1:9', log: () => {} });
|
||||
const server = await startServer({ port: 0, sso, organizations, send: async () => ({}), board: 'http://127.0.0.1:9', log: () => {} });
|
||||
t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
await b.viewport(width, height);
|
||||
@@ -462,6 +462,52 @@ test('SP11: the Sign out form drops kept pane messages, and the page it unloads
|
||||
assert.deepEqual(state.sent, []);
|
||||
});
|
||||
|
||||
// SP14 (#1873): kept pane messages belong to the person who typed them. They are stored with who is
|
||||
// signed in, and a load under anyone else, or a store that names no one (the SP11 form), opens empty.
|
||||
// Two people sign in, one after the other, on one tab; the same person keeps theirs across a reload.
|
||||
test('SP14: a kept pane message is shown again only to the person who typed it, on the same tab', async t => {
|
||||
const state = { down: new Set(), sent: [], created: [] };
|
||||
const a1 = `alpha:${T.a1}`, hash = `#/assistant?open=${a1}`;
|
||||
const dev = createDevOwner();
|
||||
const person = sub => ({ ...dev.session(), provider: 'sso', iss: 'https://id.example.test', sub, name: sub });
|
||||
let who = person('person-a');
|
||||
const { b, base, wait } = await open(t, { hash, state, sso: { ...dev, session: () => who } });
|
||||
const stored = () => b.evaluate(`sessionStorage.getItem('mosaic-assistant-drafts') || ''`);
|
||||
const leave = async () => { await b.evaluate(`location.hash = '#/tasks'`); await wait(`!document.querySelector('[data-assist-pane]') && !!document.querySelector('[data-tasks-board]')`); };
|
||||
const load = async () => { await b.navigate(`${base}?n=${Math.random().toString(36).slice(2)}${hash}`); await wait(`${ready(a1)} && !!${field(a1)} && !${field(a1)}.disabled`); };
|
||||
await wait(`${ready(a1)} && !${field(a1)}.disabled`);
|
||||
await type(b, a1, 'note from a');
|
||||
await leave();
|
||||
assert.match(await stored(), /note from a/);
|
||||
// Stored with an opaque name for the person, never their subject.
|
||||
assert.doesNotMatch(await stored(), /person-a/);
|
||||
// Person B signs in on the same tab: the pane opens empty and A's message is gone from the store.
|
||||
who = person('person-b');
|
||||
await load();
|
||||
assert.equal(await b.evaluate(`${field(a1)}.value`), '');
|
||||
assert.doesNotMatch(await stored(), /note from a/);
|
||||
await type(b, a1, 'note from b');
|
||||
await leave();
|
||||
assert.match(await stored(), /note from b/);
|
||||
// A again: B's message is not shown to A either.
|
||||
who = person('person-a');
|
||||
await load();
|
||||
assert.equal(await b.evaluate(`${field(a1)}.value`), '');
|
||||
assert.doesNotMatch(await stored(), /note from b/);
|
||||
// The same person keeps their own message across a load.
|
||||
await type(b, a1, 'a again');
|
||||
await leave();
|
||||
await load();
|
||||
assert.equal(await b.evaluate(`${field(a1)}.value`), 'a again');
|
||||
// A store in the form kept before SP14, which names no one, is dropped.
|
||||
await leave();
|
||||
await b.evaluate(`sessionStorage.setItem('mosaic-assistant-drafts', JSON.stringify({ ${JSON.stringify(a1)}: 'unowned note' })), true`);
|
||||
await load();
|
||||
assert.equal(await b.evaluate(`${field(a1)}.value`), '');
|
||||
assert.doesNotMatch(await stored(), /unowned note/);
|
||||
assert.deepEqual(state.sent, []);
|
||||
});
|
||||
|
||||
// SP11 (#1873): a pane whose message was sent but not yet shown in the conversation is not free: a
|
||||
// fourth thread replaces the first pane that holds nothing, and that pane only once its receipt is in.
|
||||
test('SP11: a pane whose send still waits for its receipt is not replaced by a fourth thread', async t => {
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
// SP13 (#1873): the organization page fits its width, and four things seen live.
|
||||
// 1. At every content width from 360 px up, with and without the agent drawer, nothing in the Settings
|
||||
// card is cut off by its card and the page does not scroll sideways.
|
||||
// 2. `#/orgs/<id>?query` is the organization page with the query kept; `?agent=` opens the drawer.
|
||||
// 3. The drawer never says "not running" before its instances read has answered: while it is open the
|
||||
// state is being read, after it fails the state was not read, and the Stop note says the same.
|
||||
// 4. (SP14 removed the Queue card; the organization page now makes no queue read.)
|
||||
// Plus the test SP12 left out: a repaint while Stop asks its question keeps the question on screen.
|
||||
// SP14 (#1873): the page has no Queue card and makes no queue read; an instances answer with no runs says
|
||||
// running was not read wherever a running or working count would show; and the drawer's instances answer
|
||||
// repaints only the drawer, with no page read made again.
|
||||
// Every bus is a fake. The real GET /api/workspace and per-organization routes serve the page; only the
|
||||
// per-organization config, the agent writes and (when a test asks) the drawer's instances read are
|
||||
// stubbed in the page.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { startServer } from '../src/serve.mjs';
|
||||
import { createDevOwner } from '../src/dev-owner.mjs';
|
||||
import { browser } from './browser.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
|
||||
const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
|
||||
const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString();
|
||||
|
||||
function fixture({ counts = {} } = {}) {
|
||||
const LIST = [{ id: 'acme', label: 'Acme Studio', theme: 'cobalt' }];
|
||||
const d = {
|
||||
projects: [{ id: 'p-site', repo: 'site', name: 'Website', archived: false, at: at(30) }],
|
||||
tasks: [], inbox: [], threads: [],
|
||||
agents: [{ role: 'coder', holder_run: 'run-1', harness: 'claude', state: 'working', at: at(40), working: { since: at(40), messages: 2 } }],
|
||||
claims: [],
|
||||
instances: {
|
||||
coder: { definition: 'coder', running: ['run-1'] },
|
||||
chief: { definition: 'chief-of-staff', running: [] },
|
||||
reviewer: { definition: 'reviewer', running: [] },
|
||||
},
|
||||
// Long values, so a narrow Settings card has something to cut.
|
||||
model: { coder: 'claude-opus-5-5', chief: 'claude-sonnet-5-5', reviewer: 'gpt-5.5-codex-high-reasoning' },
|
||||
};
|
||||
const value = name => Promise.resolve(d[name] ?? (['usage', 'limits'].includes(name) ? {} : []));
|
||||
const opts = () => ({
|
||||
bus: { inbox: () => value('inbox'), agents: () => value('agents'), 'thread.claims': () => value('claims'), tasks: () => value('tasks'), usage: () => value('usage'), limits: () => value('limits'), decisions: () => value('decisions') },
|
||||
chat: { threads: () => value('threads'), projects: () => value('projects') },
|
||||
});
|
||||
const member = org => ({ id: org.id, doc: { appearance: { theme: org.theme } }, status: async () => ({ healthy: true, pid: 4242, boot: null }), options: opts });
|
||||
return {
|
||||
list: async () => LIST.map(o => ({ ...o, busHealthy: true })),
|
||||
members: async () => LIST.map(member),
|
||||
resolve: async id => {
|
||||
const org = LIST.find(o => o.id === id); if (!org) return null;
|
||||
return {
|
||||
busHealthy: true,
|
||||
reads: {
|
||||
business: async () => ({ business: { id, human: 'jason', projects: d.projects.map(p => p.repo), appearance: { theme: org.theme }, vars: { 'tracker.kind': 'gitea-issues-and-milestones' }, arbiters: { decisions: 'chief-of-staff', reviews: 'reviewer', merges: 'human-owner-of-the-organization' }, instances: Object.entries(d.model).map(([instance, model]) => ({ instance, vars: { model } })) } }),
|
||||
settings: async () => ({}),
|
||||
queue: async () => { counts.queue = (counts.queue ?? 0) + 1; return { rows: [] }; },
|
||||
busStatus: async () => ({}),
|
||||
},
|
||||
bus: {
|
||||
messages: async () => ({ messages: [], unread: 0 }), agents: async () => d.agents, 'thread.claims': async () => d.claims, inbox: async () => d.inbox, tasks: async () => d.tasks,
|
||||
instances: async () => ({ revision: 'a'.repeat(64), definitions: {}, instances: structuredClone(d.instances) }),
|
||||
},
|
||||
chat: { projects: async () => d.projects, threads: async () => d.threads },
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Runs before the page's scripts. Acme's config says this Console sends there. `window.__inst` set by
|
||||
// a test holds ('hold', released by window.__release()) or fails ('fail') the first bus instances read,
|
||||
// which is the drawer's: it starts before the page's own reads. With `window.__heldIdle` the held
|
||||
// answer says nothing runs.
|
||||
// Every URL the page fetches, in order, for the tests that count reads.
|
||||
const URLS = `(() => { const real = window.fetch; window.__urls = []; window.fetch = (url, init) => { window.__urls.push(String(url)); return real(url, init); }; })();`;
|
||||
// A bus answer the bus did not add runs to (its async read path): no `running` key on any instance.
|
||||
const STRIP = `(() => { const real = window.fetch; window.fetch = async (url, init) => { const r = await real(url, init); if (!/\\/bus\\/instances$/.test(String(url)) || !r.ok) return r; const v = await r.json(); for (const row of [v, ...(v.rows || [])]) for (const i of Object.values(row?.instances || {})) delete i.running; return new Response(JSON.stringify(v), { status: 200, headers: { 'content-type': 'application/json' } }); }; })();`;
|
||||
|
||||
const STUB = `(() => {
|
||||
const real = window.fetch.bind(window);
|
||||
window.__posts = []; window.__answers = []; window.__instSeen = 0;
|
||||
const answer = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
|
||||
window.fetch = async (url, init = {}) => {
|
||||
const u = String(url);
|
||||
if (/\\/api\\/orgs\\/acme\\/bus\\/instances$/.test(u) && window.__instSeen++ === 0 && window.__inst) {
|
||||
if (window.__inst === 'fail') return answer(502, { error: 'read-failed', message: 'the bus did not answer' });
|
||||
await new Promise(done => { window.__release = done; });
|
||||
if (!window.__heldIdle) return real(url, init);
|
||||
// The held answer, when a test asks, says no instance runs anything.
|
||||
const v = await (await real(url, init)).json();
|
||||
for (const row of [v, ...(v.rows || [])]) for (const i of Object.values(row?.instances || {})) i.running = [];
|
||||
return answer(200, v);
|
||||
}
|
||||
const cfg = u.match(/^\\/api\\/orgs\\/([^/]+)\\/config$/);
|
||||
if (cfg) { const c = await (await real(url, init)).json(); return answer(200, { ...c, chatSend: true, settingsSend: true, decide: true }); }
|
||||
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();
|
||||
if (!a) throw new TypeError('no answer queued');
|
||||
return answer(a.status ?? 200, a.body);
|
||||
};
|
||||
})();`;
|
||||
|
||||
async function setup(t, { viewport = [1440, 900], hash = '#/orgs/acme/organization', inst = null, counts = {}, scripts = [] } = {}) {
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: fixture({ counts }), log: () => {} });
|
||||
t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
await b.viewport(...viewport);
|
||||
if (inst) await b.call('Page.addScriptToEvaluateOnNewDocument', { source: `window.__inst = ${JSON.stringify(inst)};` });
|
||||
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`);
|
||||
const has = sel => b.evaluate(`!!document.querySelector(${JSON.stringify(sel)})`);
|
||||
return { b, base, wait: waitFor(b), text, has };
|
||||
}
|
||||
const drawer = key => `document.querySelector('[data-ws-drawer="${key}"]')`;
|
||||
const open = key => `!!${drawer(key)} && ${drawer(key)}.querySelector("h2")?.textContent.length > 0`;
|
||||
const noDrawer = '!document.querySelector("[data-ws-drawer]")';
|
||||
const settled = 'document.querySelectorAll("[data-org-settings] [data-org-setting]").length > 10';
|
||||
|
||||
// Everything in the Settings card that is cut: a cell whose content is wider than its box, a cell that
|
||||
// reaches past the card's edge or, from 1200 px, under the drawer, and a page that scrolls sideways.
|
||||
const CLIPPED = `(() => {
|
||||
const card = document.querySelector('[data-org-settings]'), r = card.getBoundingClientRect();
|
||||
// From 1200 px the page keeps clear of the drawer (SP12); below that the drawer covers the page by design.
|
||||
const d = innerWidth >= 1200 ? document.querySelector('[data-ws-drawer]')?.getBoundingClientRect() : null;
|
||||
const edge = Math.min(r.right, d && d.left > 0 ? d.left : Infinity);
|
||||
const out = [];
|
||||
for (const li of card.querySelectorAll('[data-org-setting]')) {
|
||||
for (const el of li.querySelectorAll('.k,.v,.src-tag,.go')) {
|
||||
if (!el.textContent.trim()) continue;
|
||||
const b = el.getBoundingClientRect();
|
||||
if (el.scrollWidth > el.clientWidth + 1 || b.right > edge + 1 || b.left < r.left - 1) out.push(li.dataset.orgSetting + ' ' + el.className + ' ' + el.scrollWidth + '/' + el.clientWidth + ' right ' + Math.round(b.right) + '/' + Math.round(edge));
|
||||
}
|
||||
}
|
||||
// The sessions table beside it scrolls only as a last resort; with these rows the columns stack first.
|
||||
for (const tb of document.querySelectorAll('[data-org-dashboard] .ws-split .ws-tbl')) if (tb.scrollWidth > tb.clientWidth + 1) out.push('sessions table ' + tb.scrollWidth + '/' + tb.clientWidth);
|
||||
const page = document.documentElement;
|
||||
if (page.scrollWidth > page.clientWidth) out.push('page ' + page.scrollWidth + '/' + page.clientWidth);
|
||||
return out;
|
||||
})()`;
|
||||
|
||||
test('the Settings card fits at 1440 with the drawer open, at 735 and 390 without it, and at every width between', async t => {
|
||||
const { b, base, wait } = await setup(t, { hash: '#/orgs/acme/organization?agent=acme%3Acoder' });
|
||||
await wait(`${settled} && ${open('acme:coder')}`);
|
||||
assert.deepEqual(await b.evaluate(CLIPPED), [], 'at 1440 with the drawer open');
|
||||
// Each Open link keeps its whole word.
|
||||
assert.ok(await b.evaluate(`[...document.querySelectorAll('[data-org-settings] a.go')].every(a => a.innerText.trim() === 'Open' && a.scrollWidth <= a.clientWidth + 1)`));
|
||||
// Without the drawer: 735 and 390 wide, and a content width of about 735 (1023 with the sidebar).
|
||||
for (const [w, h] of [[735, 900], [390, 844], [1023, 900]]) {
|
||||
await b.viewport(w, h);
|
||||
await b.navigate(`${base}/#/orgs/acme/organization`);
|
||||
await wait(`${settled} && ${noDrawer}`);
|
||||
assert.deepEqual(await b.evaluate(CLIPPED), [], `at ${w} without the drawer`);
|
||||
}
|
||||
// Every 40 px from 360 to 1440, with and without the drawer.
|
||||
for (const hash of ['#/orgs/acme/organization', '#/orgs/acme/organization?agent=acme%3Acoder']) {
|
||||
await b.navigate(`${base}/${hash}`);
|
||||
await wait(`${settled} && ${hash.includes('agent') ? open('acme:coder') : noDrawer}`);
|
||||
for (let w = 360; w <= 1440; w += 40) {
|
||||
await b.viewport(w, 900);
|
||||
await b.evaluate('new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))');
|
||||
assert.deepEqual(await b.evaluate(CLIPPED), [], `at ${w}${hash.includes('agent') ? ' with the drawer' : ''}`);
|
||||
}
|
||||
}
|
||||
// Side by side, both columns' first headings start level (the Workflows card wraps its heading).
|
||||
await b.navigate(`${base}/#/orgs/acme/organization`);
|
||||
await wait(`${settled} && ${noDrawer}`);
|
||||
const tops = await b.evaluate(`[...document.querySelectorAll('#bus-view .ws-dash>.ws-split>section')].map(s => [Math.round(s.getBoundingClientRect().left), Math.round(s.querySelector('h2').getBoundingClientRect().top)])`);
|
||||
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');
|
||||
});
|
||||
|
||||
test('the bare organization address with a query is the organization page, query kept; ?agent= opens the drawer', async t => {
|
||||
const { b, base, wait, text } = await setup(t, { hash: '#/orgs/acme?agent=acme%3Acoder' });
|
||||
await wait(`document.querySelector('[data-org-dashboard] h1') && ${open('acme:coder')}`);
|
||||
assert.equal(await text('[data-org-dashboard] h1'), 'Acme Studio');
|
||||
assert.equal(await b.evaluate('!!document.querySelector("[data-org-unavailable]")'), false);
|
||||
assert.equal(await b.evaluate('new URLSearchParams(location.hash.split("?")[1] || "").get("agent")'), 'acme:coder');
|
||||
assert.match(await b.evaluate('location.hash'), /^#\/orgs\/acme\/organization\?agent=acme%3Acoder$/);
|
||||
// The reads are scoped to acme, never to "acme?agent=…".
|
||||
assert.equal(await b.evaluate('window.MosaicOrg?.id'), 'acme');
|
||||
// Another query, no drawer: the same page with the query kept.
|
||||
await b.navigate(`${base}/#/orgs/acme?tab=settings`);
|
||||
await wait(`document.querySelector('[data-org-dashboard] h1')?.innerText === 'Acme Studio'`);
|
||||
assert.equal(await b.evaluate('location.hash'), '#/orgs/acme/organization?tab=settings');
|
||||
assert.equal(await b.evaluate('!!document.querySelector("[data-ws-drawer]")'), false);
|
||||
// Typed into the address bar of a page already open.
|
||||
await b.evaluate('location.hash = "#/orgs/acme?agent=acme%3Achief"');
|
||||
await wait(open('acme:chief'));
|
||||
assert.equal(await text('[data-org-dashboard] h1'), 'Acme Studio');
|
||||
});
|
||||
|
||||
test('while the drawer\'s instances read is open it says the state is being read, never not running, then shows it', async t => {
|
||||
const { b, wait, text, has } = await setup(t, { hash: '#/orgs/acme/organization?agent=acme%3Acoder', inst: 'hold', scripts: [URLS] });
|
||||
const d = '[data-ws-drawer="acme:coder"]';
|
||||
await wait(`${settled} && ${open('acme:coder')}`);
|
||||
assert.equal(await has(`${d}[data-drawer-pending]`), true);
|
||||
assert.equal(await text(`${d} [data-drawer-state]`), 'Reading state…');
|
||||
assert.doesNotMatch(await text(d), /not running/);
|
||||
// Stop is not offered yet, and its note says why without saying not running.
|
||||
assert.equal(await has(`${d} [data-drawer-stop]`), false);
|
||||
assert.match(await text(`${d} [data-drawer-nostop]`), /^Its state is being read\./);
|
||||
// The page under it painted from its own reads: coder is a running session there.
|
||||
assert.match(await text('[data-ws-session-agent="acme:coder"]'), /working/);
|
||||
// When the read answers, the drawer repaints with the state, and Stop. SP14: only the drawer repaints,
|
||||
// from the reads it already has: the page and its reads are left alone, and focus stays where it was.
|
||||
await b.evaluate(`document.querySelector('[data-org-dashboard]').dataset.before = '1'; document.querySelector('${d} [data-drawer-close]').focus(); window.__urls.length = 0`);
|
||||
await b.evaluate('window.__release()');
|
||||
await wait(`!document.querySelector('${d}[data-drawer-pending]') && document.querySelector('${d} [data-drawer-stop]')`);
|
||||
assert.match(await text(`${d} [data-drawer-state]`), /(^|\s)working$/);
|
||||
assert.equal(await has(`${d} [data-drawer-nostop]`), false);
|
||||
await b.evaluate('new Promise(r => setTimeout(r, 400))');
|
||||
assert.deepEqual(await b.evaluate(`window.__urls.filter(u => /^\\/api\\/(workspace|orgs\\/)/.test(u))`), [], 'no read is made again after the drawer\'s read answers');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-org-dashboard]').dataset.before`), '1', 'the page under the drawer was not repainted');
|
||||
assert.equal(await b.evaluate('document.activeElement?.dataset?.focusKey'), 'drawer-close');
|
||||
});
|
||||
|
||||
test('SP14 review: another agent opened while the drawer\'s instances read is open repaints when that read answers', async t => {
|
||||
const { b, wait, text, has } = await setup(t, { hash: '#/orgs/acme/organization?agent=acme%3Acoder', inst: 'hold' });
|
||||
await wait(`${settled} && document.querySelector('[data-ws-drawer="acme:coder"][data-drawer-pending]')`);
|
||||
// Chief opens before the held read answers; its drawer waits on the same read.
|
||||
await b.evaluate('location.hash = "#/orgs/acme/organization?agent=acme%3Achief"');
|
||||
const d = '[data-ws-drawer="acme:chief"]';
|
||||
await wait(`document.querySelector('${d}[data-drawer-pending]')`);
|
||||
assert.equal(await text(`${d} [data-drawer-state]`), 'Reading state…');
|
||||
// The read answers. Chief's drawer repaints from it at once, not at the next poll.
|
||||
await b.evaluate('window.__release()');
|
||||
await b.evaluate('new Promise(r => setTimeout(r, 1000))');
|
||||
assert.equal(await has(`${d}[data-drawer-pending]`), false, 'chief\'s drawer still says Reading state… after its read answered');
|
||||
assert.match(await text(`${d} [data-drawer-state]`), /not running/);
|
||||
assert.equal(await has('[data-ws-drawer="acme:coder"]'), false);
|
||||
});
|
||||
|
||||
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] });
|
||||
const d = '[data-ws-drawer="acme:coder"]';
|
||||
await wait(`${settled} && document.querySelector('${d}[data-drawer-pending]')`);
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-close]').click()`);
|
||||
await wait(noDrawer);
|
||||
// The held read answers after the drawer closed, saying coder runs nothing.
|
||||
await b.evaluate('window.__release()');
|
||||
await b.evaluate('new Promise(r => setTimeout(r, 300))');
|
||||
// Reopened from its row, the drawer reads again and shows coder working, not the closed drawer's answer.
|
||||
await b.evaluate(`document.querySelector('[data-ws-drawer-open="acme:coder"]').click()`);
|
||||
await wait(`${open('acme:coder')} && !document.querySelector('${d}[data-drawer-pending]') && document.querySelector('${d} [data-drawer-state]')`);
|
||||
assert.match(await text(`${d} [data-drawer-state]`), /(^|\s)working$/);
|
||||
assert.doesNotMatch(await text(d), /not running/);
|
||||
});
|
||||
|
||||
test('after the drawer\'s instances read fails it says the state was not read, and Stop says so too', async t => {
|
||||
const { b, wait, text, has } = await setup(t, { hash: '#/orgs/acme/organization?agent=acme%3Areviewer', inst: 'fail' });
|
||||
const d = '[data-ws-drawer="acme:reviewer"]';
|
||||
await wait(`${settled} && ${open('acme:reviewer')}`);
|
||||
assert.equal(await has(`${d}[data-drawer-pending]`), false);
|
||||
assert.match(await text(`${d} [data-drawer-state]`), /^State not read: /);
|
||||
assert.doesNotMatch(await text(d), /not running/);
|
||||
assert.equal(await has(`${d} [data-drawer-stop]`), false);
|
||||
assert.equal(await text(`${d} [data-drawer-nostop]`), 'Its state was not read, so Stop is not offered.');
|
||||
// A later repaint reads again: reviewer runs nothing, so now it says not running, with that reason.
|
||||
await b.evaluate('document.dispatchEvent(new CustomEvent("mosaic-workspace-render"))');
|
||||
await wait(`/not running/.test(document.querySelector('${d} [data-drawer-state]')?.innerText ?? '')`);
|
||||
assert.equal(await text(`${d} [data-drawer-nostop]`), 'It is not running, so there is nothing to stop.');
|
||||
});
|
||||
|
||||
test('an instances answer that carries no runs says state not read, in the drawer and on the Agents table', async t => {
|
||||
const { wait, text, has } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', scripts: [STRIP] });
|
||||
const d = '[data-ws-drawer="acme:coder"]';
|
||||
await wait(`${open('acme:coder')} && document.querySelector('[data-ws-agent="acme:coder"]')`);
|
||||
assert.match(await text(`${d} [data-drawer-state]`), /state not read$/);
|
||||
assert.equal(await text(`${d} [data-drawer-nostop]`), 'Its state was not read, so Stop is not offered.');
|
||||
assert.match(await text('[data-ws-agent="acme:coder"]'), /state not read/);
|
||||
assert.doesNotMatch(await text('[data-ws-agent-list]'), /not running/);
|
||||
assert.equal(await has('[data-ws-astate="not-read"]'), true);
|
||||
});
|
||||
|
||||
test('SP14: the organization page has no Queue card and makes no queue read', async t => {
|
||||
const counts = {};
|
||||
const { b, wait, has } = await setup(t, { counts, scripts: [URLS] });
|
||||
await wait(`${settled} && document.querySelector('[data-ws-session-agent="acme:coder"]')`);
|
||||
await b.evaluate('new Promise(r => setTimeout(r, 400))');
|
||||
assert.equal(await has('[data-org-queue]'), false);
|
||||
assert.equal(await has('[data-org-queue-why]'), false);
|
||||
const heads = await b.evaluate(`[...document.querySelectorAll('[data-org-dashboard] h2, [data-org-dashboard] h3')].map(h => h.textContent.trim())`);
|
||||
assert.ok(heads.includes('Active agent sessions'), heads.join(' | '));
|
||||
assert.ok(!heads.some(h => /^Queue\b/.test(h)), heads.join(' | '));
|
||||
assert.deepEqual(await b.evaluate('window.__urls.filter(u => /queue/i.test(u))'), []);
|
||||
assert.equal(counts.queue ?? 0, 0, 'the server read no queue');
|
||||
});
|
||||
|
||||
test('SP14: an instances answer with no runs says running was not read on the organization page and the Dashboard, never 0', async t => {
|
||||
const { b, base, wait, text, has } = await setup(t, { scripts: [STRIP] });
|
||||
await wait(`${settled} && document.querySelector('[data-org-dashboard] [data-ws-tile="agents"]')`);
|
||||
const sec = await b.evaluate(`[...document.querySelectorAll('[data-org-dashboard] .ws-sec-h')].find(h => h.querySelector('h2')?.textContent === 'Active agent sessions')?.innerText.replace(/\\s+/g, ' ').trim()`);
|
||||
assert.match(sec, /^Active agent sessions running not read /);
|
||||
assert.doesNotMatch(sec, /none running|\b0 running/);
|
||||
assert.equal(await text('[data-runs-unread]'), 'Not read: the instance read did not say which agents run.');
|
||||
assert.equal(await text('[data-org-dashboard] [data-ws-tile="agents"]'), 'Agents working Not read: the instance read did not say which agents run');
|
||||
assert.equal(await has('[data-org-dashboard] [data-ws-tile="agents"] .ws-big'), false);
|
||||
assert.equal(await text('[data-org-setting="Agents and roles"] .v'), '3 agents · running not read');
|
||||
// The Dashboard: the tile counts no organization whose runs were not read and names it; its row says so.
|
||||
await b.navigate(`${base}/#/dashboard`);
|
||||
await wait(`document.querySelector('[data-ws-tile="agents"]') && document.querySelector('[data-ws-orgrow="acme"]')`);
|
||||
const tile = await text('[data-ws-tile="agents"]');
|
||||
assert.match(tile, /^Agents working Not read Acme Studio \(running not read\)$/);
|
||||
assert.equal(await has('[data-ws-tile="agents"] .ws-big'), false);
|
||||
const row = await text('[data-ws-orgrow="acme"]');
|
||||
assert.match(row, /3 agents \(running not read\)/);
|
||||
assert.doesNotMatch(row, /\b0 running|0 working/);
|
||||
});
|
||||
|
||||
test('a repaint while Stop asks its question keeps the question on screen and Stop disabled', async t => {
|
||||
const { b, wait, has } = await setup(t, { hash: '#/orgs/acme/organization?agent=acme%3Acoder' });
|
||||
const d = '[data-ws-drawer="acme:coder"]';
|
||||
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-stop]')`);
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').click()`);
|
||||
await wait(`document.querySelector('${d} [data-drawer-stop-yes]')`);
|
||||
// Mark the drawer, so the test knows the repaint replaced it.
|
||||
await b.evaluate(`document.querySelector('${d}').dataset.before = '1'`);
|
||||
await b.evaluate('document.dispatchEvent(new CustomEvent("mosaic-workspace-render"))');
|
||||
await wait(`document.querySelector('${d}') && !document.querySelector('${d}').dataset.before`);
|
||||
assert.equal(await has(`${d} [data-drawer-stop-confirm]`), true);
|
||||
assert.equal(await has(`${d} [data-drawer-stop-yes]`), true);
|
||||
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').disabled`), true);
|
||||
assert.deepEqual(await b.evaluate('window.__posts'), []);
|
||||
});
|
||||
@@ -90,7 +90,7 @@ test('workspace navigation exposes all organizations and remembers project group
|
||||
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'),true);
|
||||
});
|
||||
|
||||
test('sidebar follows sample 01 and Queue opens from the organization dashboard, not the sidebar', async t => {
|
||||
test('sidebar follows sample 01; the Queue is in neither the sidebar nor the organization dashboard, and #/queue still opens', async t => {
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: workspaceOrgs(), log: () => {} }); t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
const wait = waitFor(b);
|
||||
@@ -114,9 +114,9 @@ test('sidebar follows sample 01 and Queue opens from the organization dashboard,
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#console-nav a[href]")].filter(a => /\\/(queue|docs)$/.test(a.getAttribute("href"))).length'), 0);
|
||||
// Settings stays pinned to the foot of the sidebar.
|
||||
assert.equal(await b.evaluate('(() => { const nav = document.getElementById("console-nav").getBoundingClientRect(), foot = document.getElementById("sections-foot").getBoundingClientRect(); return foot.bottom >= nav.bottom - 24; })()'), true);
|
||||
const queue = await b.evaluate('document.querySelector("[data-org-dashboard] [data-org-queue]").getAttribute("href")');
|
||||
assert.equal(queue, '#/queue');
|
||||
await b.evaluate('document.querySelector("[data-org-queue]").click()');
|
||||
// SP14 (#1873): the organization dashboard has no Queue card; the Queue page stays at its address.
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-org-dashboard] a[href=\'#/queue\'], [data-org-queue]")'), null);
|
||||
await b.evaluate('location.hash = "#/orgs/ddigital/queue"');
|
||||
await wait('location.hash === "#/orgs/ddigital/queue" && [...document.querySelectorAll("#bus-view h1")].some(h => h.textContent.trim() === "Queue")');
|
||||
// Every sidebar view is built: Inbox (U3, workspace-pages-browser.test.mjs), Tasks (U4b,
|
||||
// tasks-board-browser.test.mjs) and Assistant (SP6, assistant-threads-browser.test.mjs), which
|
||||
@@ -152,7 +152,7 @@ test('organization dashboard renders every section from the per-organization rea
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".ws-tbl a.ws-change")].map(a => [a.getAttribute("href"), a.getAttribute("aria-label")])'),
|
||||
['chief', 'copywriter', 'montage-producer'].map(n => ['#/settings/routing', `Change the model for ${n}`]));
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".ws-tbl thead th")].map(th => th.textContent)'), ['Agent', 'Project and task', 'Model', 'Status']);
|
||||
assert.match(await b.evaluate('document.querySelector("[data-org-dashboard]").innerText'), /Queue\s+3 rows, 2 not done\s+Open queue/);
|
||||
assert.doesNotMatch(await b.evaluate('document.querySelector("[data-org-dashboard]").innerText'), /Open queue|\d+ rows?, \d+ not done/);
|
||||
// Settings: one row per setting, each with an icon, a value, a source tag and, where a page exists, Open.
|
||||
const settings = await b.evaluate(`[...document.querySelectorAll('[data-org-settings] > li')].map(li => ({ name: li.dataset.orgSetting, icon: !!li.querySelector('svg'), value: li.querySelector('.v').textContent, tag: li.querySelector('.src-tag').textContent, href: li.querySelector('a.go')?.getAttribute('href') ?? null, danger: li.classList.contains('danger') }))`);
|
||||
assert.deepEqual(settings.map(s => s.name), SETTINGS);
|
||||
@@ -178,7 +178,7 @@ test('organization dashboard empty states say so in one short line', async t =>
|
||||
await waitFor(b)('document.querySelector("[data-org-dashboard] [data-org-settings]")');
|
||||
const text = await b.evaluate('document.querySelector("[data-org-dashboard]").innerText');
|
||||
// Section labels are uppercased by CSS, so innerText carries the uppercase form.
|
||||
for (const line of [/Docs\s+No docs yet/i, /Agents working\s+Not read/, /Done this week\s+Not read/, /Active agent sessions\s+none running/i, /No active agent sessions/, /Queue\s+no rows/i, /Tracker: not set/])
|
||||
for (const line of [/Docs\s+No docs yet/i, /Agents working\s+Not read/, /Done this week\s+Not read/, /Active agent sessions\s+none running/i, /No active agent sessions/, /Tracker: not set/])
|
||||
assert.match(text, line);
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("[data-org-settings] > li").length'), SETTINGS.length);
|
||||
});
|
||||
@@ -190,7 +190,7 @@ test('organization dashboard presents sections and honest unavailable controls',
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/alpha/organization`);
|
||||
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('[data-org-dashboard]'))return;await new Promise(r=>setTimeout(r,30))}throw Error('dashboard missing')})()`);
|
||||
const text=await b.evaluate('document.querySelector("[data-org-dashboard]").innerText');
|
||||
for(const label of ['Docs','Agents working','Open tasks','Needs you','Done this week','Active agent sessions','Settings','Queue']) assert.match(text,new RegExp(label,'i'));
|
||||
for(const label of ['Docs','Agents working','Open tasks','Needs you','Done this week','Active agent sessions','Settings']) assert.match(text,new RegExp(label,'i'));
|
||||
assert.match(text,/reload organization file/i);
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("[data-org-tiles] .ws-big").length'),0);
|
||||
assert.match(text,/bus unavailable, read \d/);
|
||||
@@ -307,7 +307,7 @@ test('keyboard focus follows visual order and survives a data refresh', async t
|
||||
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);
|
||||
for (const key of ['org:forge', 'proj:ddigital:spring-launch', 'doc:spring-launch:docs/north-star.md', 'docs-all', 'agents-all', 'queue-open', 'wfg-all', 'set:Identity', 'set:Archive or delete']) assert.ok(keys.includes(key), `Tab never reaches ${key}`);
|
||||
for (const key of ['org:forge', 'proj:ddigital:spring-launch', 'doc:spring-launch:docs/north-star.md', 'docs-all', 'agents-all', 'wfg-all', 'set:Identity', 'set:Archive or delete']) assert.ok(keys.includes(key), `Tab never reaches ${key}`);
|
||||
// The disabled reload is not a tab stop; the restart button is, and Stop bus follows it.
|
||||
assert.ok(!keys.includes('org-reload')); assert.ok(keys.includes('Restart bus'));
|
||||
assert.equal(keys.indexOf('Stop bus'), keys.indexOf('Restart bus') + 1);
|
||||
@@ -319,7 +319,7 @@ test('keyboard focus follows visual order and survives a data refresh', async t
|
||||
await b.viewport(1440, 900);
|
||||
|
||||
// A refresh repaints the dashboard, the sidebar and the restart button; focus stays on the same control.
|
||||
for (const key of ['set:Projects', 'queue-open', 'doc:spring-launch:docs/launch-plan.md']) {
|
||||
for (const key of ['set:Projects', 'agents-all', 'doc:spring-launch:docs/launch-plan.md']) {
|
||||
await wait(`document.querySelector('[data-focus-key="${key}"]')`);
|
||||
await b.evaluate(`window.oldDashboard = document.querySelector('[data-org-dashboard]'); document.querySelector('[data-focus-key="${key}"]').focus(); document.getElementById('refresh').click()`);
|
||||
await wait('document.querySelector("[data-org-dashboard]") && document.querySelector("[data-org-dashboard]") !== window.oldDashboard');
|
||||
|
||||
Reference in new issue
Block a user