Files
stack/packages/webui/src/public/workspace.js
T

1538 lines
147 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// The unified workspace screens in organization mode: the sidebar's Organizations and Projects
// groups (sample 01), the organization dashboard (sample 03) and the Agents levels (sample 08).
// Every read goes through MosaicWorkspaceData (workspace-data.js). Nothing here writes; the bus
// restart button is console-restart.js's own control, with its gating and trail unchanged.
(() => {
'use strict';
if (!document.documentElement.hasAttribute('data-organizations')) return;
const data = window.MosaicWorkspaceData;
const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const enc = encodeURIComponent;
const GROUPING = 'mosaic-workspace-project-grouping-v1', ORGS_OPEN = 'mosaic-workspace-orgs-open-v1', PROJECTS_OPEN = 'mosaic-workspace-projects-open-v1';
const load = key => { try { return localStorage.getItem(key); } catch { return null; } };
const save = (key, value) => { try { localStorage.setItem(key, value); } catch {} };
let grouping = load(GROUPING) === 'flat' ? 'flat' : 'org';
let expanded = load(ORGS_OPEN) !== 'closed';
let projectsOpen = load(PROJECTS_OPEN) !== 'closed';
let orgs = null, orgError = false, themes = null, projects = new Map();
// Icons: the Console sprite where it has one, inline paths from the U0 sample where it does not.
const PATHS = {
folder: '<path d="M3.5 6.5a1 1 0 0 1 1-1h4.5l2 2h8.5a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1h-15a1 1 0 0 1-1-1z"/>',
columns: '<rect x="3.5" y="4.5" width="17" height="15" rx="1.5"/><path d="M12 4.5v15"/>',
chevron: '<path d="m6 9 6 6 6-6"/>',
plus: '<path d="M12 5v14M5 12h14"/>',
restart: '<path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3"/><path d="M19.5 4.5v4h-4"/>',
doc: '<path d="M6.5 3.5h7l4 4v13h-11z"/><path d="M13.5 3.5v4h4M9 12h6M9 15.5h6"/>',
people: '<circle cx="9" cy="8.5" r="3"/><path d="M3.5 19.5a5.5 5.5 0 0 1 11 0M15.5 5.8a3 3 0 0 1 0 5.4M17.5 19.5a5.5 5.5 0 0 0-2.5-4.6"/>',
cube: '<path d="M12 3.5 20 8v8l-8 4.5L4 16V8z"/><path d="m4 8 8 4.5L20 8M12 12.5v8"/>',
};
const icon = (id, cls = '') => `<svg class="i${cls ? ` ${cls}` : ''}"${PATHS[id] ? ' viewBox="0 0 24 24"' : ''} aria-hidden="true" focusable="false">${PATHS[id] || `<use href="/icons.svg#i-${id}"/>`}</svg>`;
const LOGO = '<svg class="mosaic-logo" viewBox="0 0 36 36" aria-hidden="true"><rect x="3" y="12" width="13" height="10" rx="2"/><rect x="18" y="3" width="13" height="12" rx="2"/><rect x="3" y="24" width="13" height="10" rx="2"/><rect x="18" y="17" width="13" height="12" rx="2"/></svg>';
// An organization's colour is its theme's action colour, per mode, with that mode's onAction for
// the initials. The CSS picks the pair for the page's mode (.ws-o in shell.css).
const HEX = /^#[0-9a-f]{6}$/i;
const themeOf = org => (themes || []).find(t => t.id === (org.theme || 'harbor')) || (themes || []).find(t => t.id === 'harbor');
function colours(org) {
const tokens = themeOf(org)?.tokens || {};
const pick = (mode, name, fallback) => (HEX.test(tokens[mode]?.[name] || '') ? tokens[mode][name] : fallback);
const l = [pick('light', '--action', '#2266bf'), pick('light', '--onAction', '#ffffff')];
const d = [pick('dark', '--action', '#74a6e7'), pick('dark', '--onAction', '#10141a')];
const m = [pick('dim', '--action', d[0]), pick('dim', '--onAction', d[1])];
return `--org-l:${l[0]};--org-on-l:${l[1]};--org-d:${d[0]};--org-on-d:${d[1]};--org-m:${m[0]};--org-on-m:${m[1]}`;
}
// Two words give their first letters (Distinctly Digital, DD); one word gives its first letter and
// its last consonant (Forge, FG; Home, HM), as the U0 sample marks them.
function initials(org) {
const words = String(org.label || org.id || '?').trim().split(/[\s_.-]+/).filter(Boolean);
if (words.length > 1) return (words[0][0] + words[1][0]).toUpperCase();
const word = words[0] || '?', rest = word.slice(1).replace(/[^a-z0-9]/gi, ''), consonants = rest.match(/[bcdfghjklmnpqrstvwxz]/gi);
return (word[0] + (consonants ? consonants[consonants.length - 1] : rest[0] || '')).toUpperCase();
}
const av = (org, size = '') => `<span class="ws-av ws-o${size ? ` ${size}` : ''}" style="${colours(org)}" aria-hidden="true">${esc(initials(org))}</span>`;
const label = org => org.label || org.id;
const state = org => (org.invalid ? ['s-error', '▲', 'invalid'] : org.busHealthy ? ['s-working', '●', 'bus running'] : org.busStopped ? ['s-offline', '○', 'bus stopped'] : ['s-offline', '○', 'bus unavailable']);
// A status mark: a glyph plus its word, shown or read aloud only.
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 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.
// An answer without the key (a bus with no copies, or one older than A3) gives an empty map.
const copiesOf = value => { const v = value?.rows?.[0]?.copies ?? value?.copies; return v && typeof v === 'object' && !Array.isArray(v) ? v : {}; };
const running = item => (Array.isArray(item?.running) ? item.running.length : 0);
const rowsOf = v => (Array.isArray(v) ? v : Array.isArray(v?.rows) ? v.rows : null);
// An agent's activity is the state the bus derives for the run holding its role. A live process
// alone says only running, never working or idle.
const ACTIVITY = { working: ['s-working', '●', 'working'], waiting: ['s-waiting', '◐', 'waiting on you'], idle: ['s-idle', '–', 'idle'] };
// SP11 (#1873): the agent counts share two words. Running is an agent row with a live process,
// whatever it is doing; working is a running one whose role session is working.
const LIVE_STATES = new Set(['working', 'waiting', 'idle', 'running']);
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']);
};
// The inline model control: the change itself happens on Settings, Routing, with its own checks.
const modelCell = (agent, model) => (model ? `${esc(model)} <a class="ws-change" href="#/settings/routing" data-focus-key="${esc(`model:${agent}`)}" aria-label="${esc(`Change the model for ${agent}`)}">Change</a>` : '<span class="muted">not reported</span>');
// Focus survives a repaint: the focused control's data-focus-key is found again afterwards.
const focusKey = root => { const a = document.activeElement; return root && a && root.contains(a) ? a.dataset?.focusKey || null : null; };
const refocus = (root, key) => { if (key) root.querySelector(`[data-focus-key="${CSS.escape(key)}"]`)?.focus({ preventScroll: true }); };
// ---------- sidebar (sample 01) ----------
function projectLinks(org, flat) {
const rows = projects.get(org.id);
if (rows === undefined) return flat ? '' : '<p class="ws-line">Reading projects…</p>';
if (rows === null) return `<p class="ws-line">${flat ? `${esc(label(org))}: projects unavailable` : 'Projects unavailable'}</p>`;
const live = rows.filter(p => p && !p.archived);
if (!live.length) return flat ? '' : '<p class="ws-line">No projects yet</p>';
const hash = location.hash;
return live.map(p => {
const href = `${orgHref(org.id)}/projects/${enc(p.id)}`, current = hash === href || hash.startsWith(`${href}/`);
return `<a class="ws-nav ws-proj${flat ? ' flat' : ''}" href="${esc(href)}" data-focus-key="${esc(`proj:${org.id}:${p.id}`)}"${current ? ' aria-current="page"' : ''}>${flat ? av(org, 'xs') : ''}<span class="t">${esc(p.name || p.id)}</span></a>`;
}).join('');
}
function projectGroups(list) {
if (grouping === 'flat') {
const body = list.map(org => projectLinks(org, true)).join('');
if (body) return `<div class="ws-flat">${body}</div>`;
return list.some(org => projects.get(org.id) === undefined) ? '<p class="ws-line">Reading projects…</p>' : '<p class="ws-line">No projects yet</p>';
}
return list.map(org => `<div class="ws-pgroup ws-o" style="${colours(org)}" data-org="${esc(org.id)}"><div class="ws-pgroup-h">${av(org, 'xs')}<span class="t">${esc(label(org))}</span></div><div class="ws-projs">${projectLinks(org, false)}</div></div>`).join('') || '<p class="ws-line">No projects yet</p>';
}
function paint() {
const root = document.getElementById('workspace-nav'); if (!root) return;
const key = focusKey(root);
if (orgError || !orgs) { root.innerHTML = `<hr class="ws-hr"><p class="ws-line">${orgError ? 'Organizations unavailable' : 'Reading organizations…'}</p>`; return; }
// SP1: a system route (the dashboard) marks no organization; an organization route marks its own.
const here = route(), selected = /^#\/orgs\//.test(location.hash) ? window.MosaicOrg?.id : null;
const rows = orgs.map(org => {
const [cls, glyph, word] = state(org), mine = org.id === selected, current = mine && here === '/organization';
return `<li data-workspace-org="${esc(org.id)}"><a class="ws-nav ws-org-row${mine && !current ? ' sel' : ''}" href="${esc(orgHref(org.id))}/organization" data-focus-key="${esc(`org:${org.id}`)}"${current ? ' aria-current="page"' : ''}>${av(org)}<span class="t">${esc(label(org))}</span>${dot(cls, glyph, word, cls !== 's-working')}</a></li>`;
}).join('');
const marks = expanded || !orgs.length ? '' : `<div class="ws-marks" aria-hidden="true">${orgs.map(org => av(org, 'xs')).join('')}</div>`;
root.innerHTML = `<hr class="ws-hr"><div class="ws-grp"><div class="ws-grp-h"><button type="button" class="ws-grp-t" data-org-toggle data-focus-key="org-toggle" aria-expanded="${expanded}" aria-controls="ws-org-list">${icon('chevron', 'chev')}<span class="ws-label">Organizations</span><span class="ws-n">${orgs.length}</span></button><a class="ws-add" href="#/settings/organizations?new=1" data-focus-key="org-new" aria-label="New organization" title="New organization">${icon('plus')}</a></div>${marks}<ul class="ws-orgs" id="ws-org-list" data-org-list${expanded ? '' : ' hidden'}>${rows || '<li class="ws-line">No organizations yet</li>'}</ul></div><hr class="ws-hr"><div class="ws-grp"><div class="ws-grp-h"><button type="button" class="ws-grp-t" data-projects-toggle data-focus-key="projects-toggle" aria-expanded="${projectsOpen}" aria-controls="ws-project-list">${icon('chevron', 'chev')}<span class="ws-label">Projects</span></button><span class="ws-seg xs" role="group" aria-label="Project layout"><button type="button" data-group="org" data-focus-key="group-org" aria-pressed="${grouping === 'org'}">By org</button><button type="button" data-group="flat" data-focus-key="group-flat" aria-pressed="${grouping === 'flat'}">Flat</button></span></div><div class="ws-project-list" id="ws-project-list"${projectsOpen ? '' : ' hidden'}>${projectGroups(orgs.filter(org => !org.invalid))}</div></div>`;
refocus(root, key);
}
let reading = 0;
async function refresh(rows) {
const turn = ++reading;
try {
const [list] = await Promise.all([Array.isArray(rows) ? rows : data.organizations(), ensureThemes()]);
if (turn !== reading) return;
orgs = Array.isArray(list) ? list : []; orgError = false;
} catch { if (turn === reading) { orgError = true; paint(); } return; }
paint();
const results = await Promise.all(orgs.filter(org => !org.invalid).map(org => data.projects(org.id).then(b => [org.id, Array.isArray(b?.rows) ? b.rows : null]).catch(() => [org.id, null])));
if (turn !== reading) return;
projects = new Map(results); paint();
}
document.addEventListener('click', e => {
const toggle = e.target.closest?.('[data-org-toggle]');
if (toggle) { expanded = !expanded; save(ORGS_OPEN, expanded ? 'open' : 'closed'); paint(); document.querySelector('[data-org-toggle]')?.focus(); return; }
if (e.target.closest?.('[data-projects-toggle]')) { projectsOpen = !projectsOpen; save(PROJECTS_OPEN, projectsOpen ? 'open' : 'closed'); paint(); document.querySelector('[data-projects-toggle]')?.focus(); return; }
const group = e.target.closest?.('#workspace-nav [data-group]');
if (group) { grouping = group.dataset.group === 'flat' ? 'flat' : 'org'; save(GROUPING, grouping); paint(); document.querySelector(`#workspace-nav [data-group="${grouping}"]`)?.focus(); if (route().split('?')[0] === '/projects') document.dispatchEvent(new CustomEvent('mosaic-workspace-render')); }
});
window.addEventListener('hashchange', () => { if (orgs) paint(); });
document.addEventListener('mosaic-org-list', e => refresh(e.detail?.rows));
// ---------- organization dashboard (sample 03) ----------
const SAFE = /^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,159}$/;
const DOC_PATH = /^(spec\/north-star\.md|docs\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.md)$/;
const docCache = new Map();
// Docs are read at most once a minute per organization: the dashboard repaints every 10 s.
async function docs(id, names) {
const hit = docCache.get(id);
if (hit && Date.now() - hit.at < 60000) return hit.value;
const list = (Array.isArray(names) ? names : []).filter(p => typeof p === 'string' && SAFE.test(p)).slice(0, 6);
const read = await Promise.allSettled(list.map(p => data.projectFiles(id, p).then(body => (Array.isArray(body?.files) ? body.files : []).filter(f => typeof f?.path === 'string' && DOC_PATH.test(f.path)).map(f => ({ project: p, path: f.path })))));
const value = { rows: read.flatMap(r => (r.status === 'fulfilled' ? r.value : [])), failed: read.length > 0 && read.every(r => r.status === 'rejected') };
docCache.set(id, { at: Date.now(), value });
return value;
}
const docName = path => (path === 'spec/north-star.md' ? 'North star' : path.replace(/^.*\//, '').replace(/\.md$/, '').replace(/[-_]+/g, ' ').replace(/^./, c => c.toUpperCase()));
const titleCase = s => String(s || '').replace(/(^|[-_\s])(\w)/g, (_, sep, c) => `${sep ? ' ' : ''}${c.toUpperCase()}`);
const clock = () => new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
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, noRuns } = ctx;
const b = business?.business, s = settings;
const unread = 'Could not be read';
const names = instances ? Object.keys(instances) : null;
const models = b && Array.isArray(b.instances) ? [...new Set(b.instances.map(i => i?.vars?.model).filter(m => typeof m === 'string' && m))] : null;
const arbiters = b?.arbiters && typeof b.arbiters === 'object' ? Object.entries(b.arbiters).filter(([, v]) => typeof v === 'string').map(([k, v]) => `${v} (${k})`).join(' · ') : null;
const total = s?.launch && !s.launch.refused ? s.launch.limits?.total : undefined;
const notifier = s?.notifier;
const theme = b?.appearance?.theme || org.theme || 'harbor';
const rows = [
['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')} · ${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'],
['talk', 'Channels', !s ? unread : typeof notifier?.binding === 'string' ? `Notifier ${notifier.binding}` : notifier?.refused ? unread : 'No notifier set', 'system', 'about'],
['ledger', 'Launch limits', !s ? unread : s.launch?.refused ? unread : Number.isFinite(total) ? `${plural(total, 'session')} at once` : 'No session limit', 'org file', 'limits'],
['talk', 'Assistant', 'The assistant agent and its seat names', 'org file', 'assistant'],
['ledger', 'Token use', 'Usage and limits per provider and model', 'system', 'tokens'],
['term', 'Model proxy', 'Accounts, priority and client keys', 'system', 'model-proxy'],
['restart', 'Console', 'Console restart', 'system', 'console'],
['business', 'Organizations', orgCount === null ? unread : plural(orgCount, 'organization'), 'system', 'organizations'],
['flag', 'About', typeof s?.release === 'string' ? `Release ${s.release}` : 'Address, release and notifier', 'system', 'about'],
['people', 'Members and invites', 'Not built yet', 'not built', null],
['restart', 'Bus', `${org.busHealthy ? 'Running' : org.busStopped ? 'Stopped' : 'Unavailable'} · restart from this page's header`, 'system', null],
['close', 'Archive or delete', "Archive or delete this organization's file", 'danger', 'organizations'],
];
return `<ul class="ws-cfg one" data-org-settings>${rows.map(([ic, name, value, tag, page]) => {
const href = page === null ? null : page.startsWith('#') ? page : `#/settings/${page}`;
const go = href ? `<a class="go" href="${esc(href)}" data-focus-key="${esc(`set:${name}`)}" aria-label="Open ${esc(name)}">Open</a>` : '<span class="go" aria-hidden="true"></span>';
return `<li${tag === 'danger' ? ' class="danger"' : ''} data-org-setting="${esc(name)}">${icon(ic)}<span class="k">${esc(name)}</span><span class="v" title="${esc(value)}">${esc(value)}</span><span class="src-tag">${esc(tag)}</span>${go}</li>`;
}).join('')}</ul>`;
}
// E2E6 P1-1: a poll repaints the whole page, which would drop an editor's draft and its focus. A
// section marked data-live-key that is being edited (it holds [data-live-hold] or [data-live-dirty])
// or holds focus is kept: holdLive takes it before the repaint and graftLive puts that same node, with
// its typed values, caret and focus, in place of its fresh counterpart. Each editor saves against the
// revision it started from, so a kept node cannot overwrite a change it never saw.
const TYPING = 'input:not([type=button],[type=submit],[type=reset],[type=checkbox],[type=radio]),select,textarea';
function holdLive(root) {
const held = new Map(), a = document.activeElement;
if (!root) return { held, active: null };
// Focus alone holds a section only while it sits in a field being typed in. A focused button or link
// is rebuilt with fresh data and gets its focus back through data-focus-key (review P3), so a section
// never stays stale just because its Apply button kept focus.
const typing = a?.matches?.(TYPING) ?? false;
for (const el of root.querySelectorAll('[data-live-key]')) {
if (el.matches('[data-live-hold]') || el.querySelector('[data-live-hold],[data-live-dirty]') || (typing && el.contains(a))) held.set(el.dataset.liveKey, el);
}
const active = a && [...held.values()].some(el => el.contains(a))
? { el: a, caret: typeof a.selectionStart === 'number' ? [a.selectionStart, a.selectionEnd, a.scrollTop] : null } : null;
return { held, active };
}
function graftLive(root, kept) {
if (!root || !kept?.held?.size) return false;
for (const el of root.querySelectorAll('[data-live-key]')) {
const old = kept.held.get(el.dataset.liveKey);
if (old && old !== el) el.replaceWith(old);
}
const a = kept.active;
if (a && a.el.isConnected) {
a.el.focus({ preventScroll: true });
if (a.caret && typeof a.el.setSelectionRange === 'function') try { a.el.setSelectionRange(a.caret[0], a.caret[1]); a.el.scrollTop = a.caret[2]; } catch { /* not a text field */ }
}
return Boolean(a && a.el.isConnected);
}
// SP1: the reason an organization's bus can't be read, for its pages. `row` is its GET /api/workspace
// status (state, reason, boot), or null when that read gave none.
// A reason that only restates the heading ("the bus is not running", the server's fallback) is not
// repeated; the last start time, when read, still shows.
const restates = reason => /^the bus is not (running|answering)\.?$/i.test(reason.trim());
const downWhy = row => (row && row.state !== 'ok' && typeof row.reason === 'string' && row.reason ? `${row.reason}${row.boot?.at ? `, last start ${when(row.boot.at)}` : ''}` : '');
// #1873 SP2: this is the page's only bus banner (the shell's "Bus unavailable" hides on this page), so
// it carries the restart action where the Console allows it.
function downBanner(org, row) {
const stopped = org.busStopped === true;
const plain = row && row.state !== 'ok' && typeof row.reason === 'string' && row.reason && restates(row.reason);
const why = plain ? '' : downWhy(row);
const tail = plain
? (row.boot?.at ? ` <span class="why">Last start ${esc(when(row.boot.at))}.</span>` : '')
: why ? ` <span class="why">Reason: ${esc(why)}.</span>` : ' <span class="why">No reason was read.</span>';
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, 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()]);
const list = Array.isArray(listRead) ? listRead : null;
const org = list?.find(o => o.id === id && !o.invalid);
if (!org) return `<article class="ws ws-dash" data-org-dashboard data-org-unavailable><div class="ws-vh"><h1 tabindex="-1">Organization unavailable</h1><p class="sub">${list ? 'This organization is not on your list.' : 'The organization list could not be read.'}</p></div></article>`;
// E2E6 P2-8: a stopped bus is not read for the bus-backed editors; each says the bus is stopped.
const stopped = !org.busHealthy && org.busStopped === true;
// SP8 (#1873): the cross-organization read scoped to this one gives the tiles' figures and, SP1,
// 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);
// 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));
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;
const downRow = org.busHealthy ? null : wsRow;
await window.MosaicConsole?.ready;
const name = esc(label(org));
const tracker = business?.business?.vars?.['tracker.kind'];
// Header: the bus restart is console-restart.js's button where the Console allows it, otherwise
// the same control, present and disabled, with the reason. SP7 (#1873): while the bus is down and
// the down banner carries the live restart, the header draws none, so the page has one.
const restart = window.MosaicConsole?.busButton?.('Restart bus', { stop: true, glyph: icon('restart') }) || '';
const offTitle = "Restarting the bus is the owner's trailed action, on a Console started with send and the action trail";
const stopTitle = "Stopping the bus is the owner's trailed action, on a Console started with send and the action trail";
const bus = restart ? (org.busHealthy ? `<span class="ws-busctl" data-dashboard-bus>${restart}</span>` : '') : `<span data-dashboard-bus><button type="button" class="ws-btn" data-bus-restart-off data-focus-key="bus-restart-off" disabled title="${esc(offTitle)}">${icon('restart')}Restart bus</button> <button type="button" class="ws-btn" data-bus-stop-off data-focus-key="bus-stop-off" disabled title="${esc(stopTitle)}">Stop bus</button></span>`;
// SP11 (#1873): the line beside the disabled reload says how a change to the organization file loads.
const reload = `<button type="button" class="ws-btn" data-org-reload data-focus-key="org-reload" disabled aria-describedby="${esc(why)}" title="Reloading without a restart is not available yet">${icon('doc')}Reload organization file</button>`;
const [bcls, bglyph] = state(org);
const meta = `<p class="ws-meta"><span>Kind not recorded</span><span>id <code>${esc(id)}</code></span><span>Tracker: ${tracker ? esc(titleCase(tracker)) : 'not set'}</span><span>${dot(bcls, bglyph, org.busHealthy ? `bus running, read ${clock()}` : org.busStopped ? `bus stopped, read ${clock()}` : `bus unavailable, read ${clock()}`, true)}</span><span id="${esc(why)}">The bus reads the organization file when it starts. To load a change to the file, restart the bus.</span></p>`;
const projectName = pid => projectRows?.find(p => p.id === pid)?.name || pid;
const docChips = !docRead ? '<span class="note">Docs unavailable</span>' : docRead.failed ? '<span class="note">Docs unavailable</span>' : docRead.rows.length ? docRead.rows.slice(0, 6).map(d => `<a class="ws-doc" href="#/docs/${enc(d.project)}/${enc(d.path)}" data-focus-key="${esc(`doc:${d.project}:${d.path}`)}" title="${esc(`${d.project}/${d.path}`)}">${icon('doc')}${esc(docName(d.path))}<small>${esc(projectName(d.project))}</small></a>`).join('') : '<span class="note">No docs yet</span>';
const docrow = `<div class="ws-docrow ws-chips"><span class="ws-label">Docs</span>${docChips}<a class="ws-more" href="#/docs" data-focus-key="docs-all">All docs</a></div>`;
// SP8: the same tiles as the Dashboard, scoped to this organization, each a link to the system page
// filtered to it. A tile whose read gave nothing says why instead of a figure.
const mine = arr(ws?.metrics?.orgs).find(x => x?.org === id) ?? null;
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;
// 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;
const orgTiles = `<div class="ws-tiles" data-org-tiles role="group" aria-label="Key figures">
${orgTile('agents', 'Agents working', `#/agents?${oq}&state=working`, agentsWhy, { big: working, small: `of ${orgAgents?.length ?? 0}`, delta: orgAgents ? agentNote(runningOf(orgAgents), waiting) : '' })}
${orgTile('tasks', 'Open tasks', `#/tasks?${oq}`, whyNot(['tasks']), { big: num(mine?.openTasks) })}
${orgTile('needs', 'Needs you', `#/inbox?${oq}`, whyNot(['inbox']), { big: num(mine?.needsYou), small: num(mine?.needsYou) === 1 ? 'item' : 'items', delta: num(mine?.needsYou) && mine?.oldestNeedsYouAt ? `oldest ${span(mine.oldestNeedsYouAt)}` : 'nothing waiting' })}
${orgTile('done', 'Done this week', `#/tasks?${oq}&done=week`, whyNot(['tasks']), { big: num(mine?.doneThisWeek) })}
</div>`;
const modelOf = inst => business?.business?.instances?.find(i => i?.instance === inst)?.vars?.model;
// SP11: the sessions are the running rows the tile counts: the organization's instances and the
// root and project copies its bus booted with. A copy shows its own name.
const copyLive = Object.entries(copiesOf(value(2))).filter(([, c]) => c && typeof c.name === 'string' && !copyBlocked(c) && running(c)).map(([key, c]) => [key, c, c.name]);
const live = instances ? [...Object.entries(instances).filter(([, item]) => running(item)).map(([key, item]) => [key, item, key]), ...copyLive] : null;
// The sessions heading and rows take their activity from the session list the tile counts, so the
// two never disagree. When the tile shows no figure they use the bus agents read instead; when
// that failed too, the heading says working was not read rather than a figure.
const tileAgents = orgAgents && !agentsWhy ? arr(ws.sessions).filter(x => x?.kind === 'role' && x.org === id && typeof x.role === 'string').map(x => ({ role: x.role, holder_run: x.run, state: x.state })) : agents;
const liveWorking = live ? live.filter(([key, item]) => activity(key, item, tileAgents)[2] === 'working').length : 0;
// A session's project and task is the thread its live run holds a claim on (thread.claims), not
// any older conversation of the same agent. A failed read says unavailable, never "none".
const sessionRows = (live || []).map(([agent, item, shown]) => {
const held = claims ? claims.filter(c => item.running.includes(c?.holder_run)) : null;
const first = held?.[0], thread = first && threads ? threads.find(t => t?.id === first.thread) : null;
const model = modelOf(agent), count = running(item), [acls, aglyph, aword] = activity(agent, item, tileAgents);
const more = held && held.length > 1 ? ` · ${held.length - 1} more` : '';
const where = held === null ? '<span class="muted">Conversation unavailable</span>'
: !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>';
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 && 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>
<nav class="ws-crumb" aria-label="Breadcrumb"><a href="#/dashboard">Dashboard</a><span aria-hidden="true">›</span><span>${name}</span></nav>
<div class="ws-orghead ws-o" style="${colours(org)}">${av(org, 'lg')}<h1 tabindex="-1">${name}</h1><div class="ws-right">${bus}${reload}</div>${meta}</div>
${org.busHealthy ? '' : downBanner(org, downRow)}
${orgTiles}
${docrow}
<div class="ws-split">
<section aria-label="Sessions and workflows">
${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}
${window.MosaicWorkflows?.card?.(id, { stopped, label: label(org) }) ?? ''}
</section>
<section aria-label="Settings">
${secH('Settings', 'every setting, with where its value comes from')}
${settingsList(org, { business, settings, instances, noRuns, orgCount: list ? list.length : null })}
</section>
</div>
<div class="ws-wide">
${stopped ? stoppedPanel('data-autonomy', 'Autonomy') : window.MosaicAutonomy?.section(id) ?? ''}
${stopped ? stoppedPanel('data-packs', 'Starter packs') : window.MosaicPacks?.section(id) ?? ''}
${stopped ? stoppedPanel('data-workflows', 'Workflows') : window.MosaicWorkflows?.section(id) ?? ''}
</div>
${await drawerRead}
</article>`;
}
// ---------- agents levels (sample 08) ----------
// Root and organization agents come from their files through /api/agents/levels (#1873 A1, read
// only). Every status comes from the organization's bus: its instances, and since A3 the root and
// project agent copies it booted with. Nothing here invents a status, a model or a memory.
const NOT_RUNNING = ['s-idle', '–', 'not running'];
// SP1: why a bus-backed read gave nothing, in the membership list's words.
const busWord = org => (org?.busStopped === true ? 'the bus is stopped' : 'the bus is not answering');
// A copy's status: running or not as the bus reports its runs, or why it can't launch.
const CANT = ['s-error', '▲', "can't launch"];
// #1873 CB5: the bus adds `binding` to a copy that needs a credential binding: its status code and
// the owner's next step, fixed text from the bus. A booted copy whose binding is not ready can't
// launch, and says why.
const bindingNext = (c) => (typeof c?.binding?.next === 'string' && c.binding.status !== 'ready' ? c.binding.next : '');
const copyBlocked = (c) => c.state !== 'instance' || Boolean(bindingNext(c));
const copyWhy = (c) => (c.state === 'unbound' ? [`no binding in this organization for ${(c.missing || []).join(', ')}`, bindingNext(c)].filter(Boolean).join('. ')
: c.state === 'instance' ? bindingNext(c) : c.reason || 'refused');
const copyDot = (name, c, agents) => (copyBlocked(c) ? CANT : activity(name, c, agents));
// The bus names each copy's instance. Find an agent's copy by its name and project, never by
// rebuilding the instance name: a collision refuses one entry that lists every claimant.
const copyFor = (copies, name, project = null) => {
const mine = c => c && c.name === name && (c.project ?? null) === project;
const hit = Object.entries(copies || {}).find(([, c]) => mine(c) || (Array.isArray(c?.claims) && c.claims.some(mine)));
return hit ? { key: hit[0], copy: hit[1] } : { key: null, copy: null };
};
const LEVEL_CLS = { root: 'root', org: 'org', project: 'proj' };
// SP5: what an agent is, in words. A hired agent's definition is `org:hire-<decision>`. No read names
// the template it was hired from, so it reads as hired, and from which pack when a pack hired it;
// the definition id stays as secondary text.
const isHired = item => typeof item?.hireDecision === 'string' || /^org:hire-/.test(String(item?.definition ?? ''));
const packOf = item => (typeof item?.pack?.label === 'string' && item.pack.label ? item.pack.label : typeof item?.pack?.id === 'string' ? item.pack.id : '');
const ROLE_WORD = { 'chief-of-staff': 'Chief of staff', assistant: 'Assistant' };
const roleWords = item => {
const d = typeof item?.definition === 'string' ? item.definition : '';
if (isHired(item)) return packOf(item) ? `Hired from pack ${packOf(item)}` : 'Hired';
return ROLE_WORD[d] || d.replace(/^org:/, '') || 'not reported';
};
const projectName = (rows, id) => { const p = Array.isArray(rows) ? rows.find(r => r?.id === id) : null; return p?.name || id; };
let agentsPick = null; // the project chosen in "Available in a project", kept across repaints
// Repaints that section alone when the choice changes, one renderer per organization: a side-by-side
// pane can show another organization's agents next to the page's own.
let agentsAvailable = {};
function levelsTable(ctx, projectId) {
const { selOrg, lv, mine, levels, modelOf, names, others } = ctx;
const union = projectId && lv?.state === 'ok' ? lv.projects[projectId] : null;
if (union && union.state !== 'ok') return `<p class="ws-panel tight note">The agents for ${esc(names(projectId))} could not be resolved. ${esc(union.reason)}</p>`;
const set = union || (lv?.state === 'ok' ? lv.base : null);
const inst = mine?.inst ?? null;
const rows = [];
if (levels?.root?.state === 'ok' && levels.root.assistant) {
// The model the root file sets is shown as configured; the assistant's running state is not reported.
const configured = levels.root.agents.find(a => a.name === levels.root.assistant)?.model ?? null;
rows.push({ name: levels.root.assistant, level: 'root', definition: 'assistant', model: configured, scope: { kind: 'cross-org' }, overrides: [], narrowed: [], assistant: true });
}
if (set) {
rows.push(...set.agents);
// A bus instance the organization file no longer names still shows, as the bus reports it.
const known = new Set([...set.agents.map(a => a.name), ...set.excluded.map(e => e.name)]);
for (const name of Object.keys(inst || {})) if (!known.has(name)) rows.push({ name, level: 'org', definition: inst[name]?.definition, model: null, scope: { kind: 'org' }, overrides: [], narrowed: [] });
} else if (inst) {
rows.push(...Object.entries(inst).map(([name, v]) => ({ name, level: 'org', definition: v?.definition, model: null, scope: { kind: 'org' }, overrides: [], narrowed: [] })));
}
if (!set && inst === null) return `<p class="ws-panel tight note" data-agents-why>${selOrg?.busHealthy === false ? `Agents not read: ${busWord(selOrg)}.` : 'Agents unavailable. The bus did not answer the instance read.'}</p>`;
if (!rows.length) return '<p class="ws-panel tight note">No agents configured</p>';
const where = a => (a.level === 'root' ? 'Your root configuration' : a.level === 'org' ? `${label(selOrg)} file` : `${names(a.project)} project`);
const hired = a => a.level === 'org' && isHired({ ...inst?.[a.name], definition: a.definition });
const sub = a => [hired(a) ? 'hired' : a.definition && a.definition !== a.name ? a.definition : '', a.level === 'org' && typeof inst?.[a.name]?.pack?.id === 'string' ? `from pack ${inst[a.name].pack.id}` : '', hired(a) ? a.definition : '', a.overrides?.length ? `replaces the ${a.overrides.map(o => (o.level === 'org' ? 'organization' : o.level)).join(' and ')} ${a.overrides.length > 1 ? 'definitions' : 'definition'}` : '', a.narrowed?.length ? `narrowed here: ${a.narrowed.join(', ')}` : ''].filter(Boolean).join(' · ');
const status = a => {
if (a.assistant) return dot('s-unknown', '?', 'status not reported', true);
if (a.level !== 'org') {
if (inst === null) return '<span class="muted">status unavailable</span>';
const { key, copy: c } = copyFor(mine?.copies, a.name, a.level === 'project' ? a.project : null);
if (!c) return '<span class="muted">starts with the next bus start</span>';
return `${dot(...copyDot(key, c, mine.agents), true)}${copyBlocked(c) ? `<span class="t2">${esc(copyWhy(c))}</span>` : ''}`;
}
if (inst === null) return '<span class="muted">status unavailable</span>';
return dot(...(inst[a.name] ? activity(a.name, inst[a.name], mine.agents) : NOT_RUNNING), true);
};
const model = a => {
if (a.level === 'org') return modelCell(a.name, modelOf(a.name) ?? a.model);
return a.model ? esc(a.model) : '<span class="muted">not set</span>';
};
const body = rows.map(a => { const s = sub(a); return `<tr data-agent="${esc(a.name)}"><td class="t1">${esc(a.name)}${s ? `<span class="t2">${esc(s)}</span>` : ''}</td><td><span class="ws-lvl ${LEVEL_CLS[a.level]}${a.level === 'org' ? ' ws-o" style="' + colours(selOrg) : ''}">${a.level}</span></td><td class="hide-m">${esc(where(a))}</td><td class="hide-m">${a.scope?.kind === 'cross-org' ? 'Shared across all organizations' : 'This organization only'}</td><td>${status(a)}</td><td class="hide-m mono">${model(a)}</td></tr>`; }).join('');
// What this project does not get: other projects' own agents, its exclusions and other organizations.
const away = [];
if (union) {
const here = new Set(union.agents.map(a => a.name));
for (const [pid, entries] of Object.entries(lv.defined || {})) if (pid !== projectId) for (const e of entries) if (e.form === 'define' && !here.has(e.name)) away.push(`${e.name} (${names(pid)} only)`);
}
if (set) {
for (const e of set.excluded) away.push(`${e.name} (${e.by === 'project' ? 'excluded in this project' : `turned off for ${label(selOrg)}`})`);
}
const otherOrgs = others.map(o => label(o));
const tail = otherOrgs.length ? `every ${otherOrgs.length > 1 ? `${otherOrgs.slice(0, -1).join(', ')} or ${otherOrgs.at(-1)}` : otherOrgs[0]} agent` : '';
const parts = [...away, tail].filter(Boolean);
const note = parts.length ? `<p class="note ws-away">Not available here: ${esc(parts.length > 1 ? `${parts.slice(0, -1).join(', ')} and ${parts.at(-1)}` : parts[0])}.</p>` : '';
return `<div class="ws-tbl"><table><thead><tr><th scope="col">Agent</th><th scope="col">Level</th><th scope="col" class="hide-m">Defined in</th><th scope="col" class="hide-m">Memory</th><th scope="col">Status</th><th scope="col" class="hide-m">Model</th></tr></thead><tbody>${body}</tbody></table></div>${note}`;
}
// SP5: `opts.under` draws it below the scoped Agents table (#/orgs/<id>/agents), which owns the page heading.
async function agentGrid(note = '', selected = window.MosaicOrg?.id, opts = {}) {
const [list, levels] = await Promise.all([data.organizations().catch(() => null), data.agentLevels().catch(() => null), ensureThemes()]);
const head = `<div class="ws-vh">${opts.under ? '<h2>Agents by level</h2>' : '<h1 tabindex="-1">Agents</h1>'}<div class="ws-right"><a class="ws-btn" href="#/settings/agents" data-focus-key="agents-edit">${icon('settings')}Edit agents</a></div><p class="sub">Agents are defined at three levels: root, organization and project. Each organization runs its own copy of a root agent, and a project's agents run only in that project. The copies are made when the organization's bus starts.${note ? ` ${note}` : ''}</p></div>`;
if (!Array.isArray(list)) return `<section class="ws ws-agents" data-org-agents>${head}<p class="ws-panel tight note">Organizations unavailable.</p></section>`;
const valid = list.filter(org => !org.invalid);
const admitted = valid.some(org => org.id === selected);
const [results, business] = await Promise.all([
Promise.all(valid.map(org => Promise.all([
data.instances(org.id).then(v => ({ inst: instancesOf(v), copies: copiesOf(v) })).catch(() => ({ inst: null, copies: null })), data.agents(org.id).then(rowsOf).catch(() => null),
projects.get(org.id) !== undefined ? projects.get(org.id) : data.projects(org.id).then(b => (Array.isArray(b?.rows) ? b.rows : null)).catch(() => null),
]).then(([{ inst, copies }, agents, rows]) => ({ org, inst, copies, agents, rows, lv: levels?.orgs?.find(o => o?.id === org.id) ?? null })))),
admitted ? data.business(selected).catch(() => null) : null,
]);
const band = `<div class="ws-span-band"><span class="ws-av all md" aria-hidden="true">${LOGO}</span><b>assistant</b><span class="ws-lvl root">root</span>${dot('s-unknown', '?', 'status not reported', true)}<span>Works across</span><span class="orgs">${valid.map(org => av(org)).join('')}</span><span class="muted ws-band-note">The assistant talks with you across organizations. Its status is not reported on this page; set it up under Settings, Assistant.</span></div>`;
const n = Math.max(valid.length, 1);
const cell = (org, inner, cls = '') => `<div class="ws-o${cls}" style="${colours(org)}" data-org="${esc(org.id)}"><span class="mlabel">${av(org, 'xs')}${esc(label(org))}</span>${inner}</div>`;
const endc = i => (i === results.length - 1 ? ' endc' : '');
// Ruling 2026-11-14: a card names the pack that hired its agent, and the page's own organization
// offers Fire on every card but the chief's and the assistant's (bus.js draws the control and its confirmation).
const pill = (org, name, item, agents) => {
const cos = item?.definition === 'chief-of-staff' || name === 'chief';
const [acls, aglyph, aword] = activity(name, item, agents);
const from = typeof item?.pack?.id === 'string' ? ` <small data-agent-pack="${esc(item.pack.id)}">from pack ${esc(item.pack.id)}</small>` : '';
// No Fire the bus would refuse: the assistant (and any end-protected instance) is never fired.
const fire = cos || item?.definition === 'assistant' || item?.endProtected === true ? '' : window.MosaicDecide?.fireControl(org.id, name) ?? '';
return `<span class="ws-agent${cos ? ' cos' : ''}" data-agent-card="${esc(name)}">${dot(acls, aglyph, aword)}${esc(name)}${cos && name !== 'chief' ? ' <small>chief</small>' : ''}${from}${fire}</span>`;
};
// A root or project copy in one organization's cell: its status from that organization's bus, and
// why it can't launch when it can't. No answer from the bus reads as unavailable, never as idle.
const copyPill = (copies, agents, name, project, small) => {
const { key, copy: c } = copyFor(copies, name, project);
const mark = copies === null ? ['s-unknown', '?', 'status unavailable'] : !c ? ['s-unknown', '?', 'starts with the next bus start'] : copyDot(key, c, agents);
const why = c && copyBlocked(c) ? `<span class="note ws-off" data-copy-why="${esc(key)}">${esc(name)}: ${esc(copyWhy(c))}</span>` : '';
return `<span class="ws-agent" data-level-agent="${esc(name)}" data-copy-state="${esc(c?.state || 'unknown')}">${dot(...mark)}${esc(name)} <small>${esc(small)}</small></span>${why}`;
};
// Root: one copy per organization, each running inside that organization; an opt-out is said.
const root = levels?.root;
const rootRow = !root ? '<div class="span endc"><span class="muted">Root agents unavailable. The levels read did not answer.</span></div>'
: root.state === 'invalid' ? `<div class="span endc"><span class="muted">Root agents unavailable. ${esc(root.reason)}</span></div>`
: !root.agents.some(a => a.definition !== 'assistant') ? '<div class="span endc"><span class="muted">No root agents. They are defined in agents.json in your configuration directory.</span></div>'
: results.map(({ org, inst, copies, agents }, i) => {
const mineRoot = root.agents.filter(a => a.definition !== 'assistant');
// An organization agent of the same name replaces the root one there, so no copy is made.
const own = a => Boolean(inst && Object.hasOwn(inst, a.name) && !copyFor(copies, a.name).copy);
const kept = mineRoot.filter(a => !a.excludeOrgs.includes(org.id)), off = mineRoot.filter(a => a.excludeOrgs.includes(org.id));
const on = kept.filter(a => !own(a)), replaced = kept.filter(own);
return cell(org, `${on.map(a => copyPill(copies, agents, a.name, null, 'copy')).join('') || '<span class="muted">none</span>'}${replaced.length ? `<span class="note ws-off">${esc(replaced.map(a => a.name).join(', '))} replaced by ${esc(label(org))}'s own</span>` : ''}${off.length ? `<span class="note ws-off">${esc(off.map(a => a.name).join(', '))} turned off for ${esc(label(org))}</span>` : ''}`, endc(i));
}).join('');
const orgRow = results.map(({ org, inst, agents }, i) => cell(org, inst === null ? `<span class="muted" data-agents-why>${org.busHealthy === false ? `Agents not read: ${busWord(org)}` : 'Agents unavailable'}</span>` : Object.keys(inst).length ? Object.entries(inst).map(([k, v]) => pill(org, k, v, agents)).join('') : '<span class="muted">No agents configured</span>', endc(i))).join('');
// Project: the agents a project defines itself. Narrowing and exclusion show in the table.
const projRow = results.map(({ org, lv, rows, copies, agents }, i) => {
if (lv?.state !== 'ok') return cell(org, `<span class="muted">${lv?.state === 'invalid' ? 'Project agents unavailable: the organization file was refused' : 'Project agents unavailable'}</span>`, ` last${endc(i)}`);
const own = Object.entries(lv.defined).flatMap(([pid, entries]) => entries.filter(e => e.form === 'define').map(e => copyPill(copies, agents, e.name, pid, projectName(rows, pid))));
return cell(org, own.join('') || '<span class="muted">none</span>', ` last${endc(i)}`);
}).join('');
const levelsGrid = valid.length ? `<div class="ws-levels" style="grid-template-columns:200px repeat(${n},minmax(0,1fr))">
<div class="lh hide-m"></div>${valid.map((org, i) => `<div class="oh hide-m ws-o${i === valid.length - 1 ? ' endc' : ''}" style="${colours(org)}">${av(org)}${esc(label(org))}</div>`).join('')}
<div class="lh"><span class="ws-lvl root">root</span><small>Your root configuration. Only you change it. Each organization runs its own copy, with memory, files and credentials kept in that organization.</small></div>${rootRow}
<div class="lh"><span class="ws-lvl org">org</span><small>Defined in the organization file. Each organization's agents work only inside it.</small></div>${orgRow}
<div class="lh last"><span class="ws-lvl proj">project</span><small>Defined in one project and available only there.</small></div>${projRow}
</div>` : '<p class="ws-panel tight note">No organizations yet.</p>';
const mine = results.find(r => r.org.id === selected);
const selOrg = list.find(o => o.id === selected) || { id: selected, label: selected };
const modelOf = inst => business?.business?.instances?.find(i => i?.instance === inst)?.vars?.model;
const lv = mine?.lv ?? null;
const projectIds = lv?.state === 'ok' ? Object.keys(lv.projects) : [];
const pick = projectIds.includes(agentsPick?.[selected]) ? agentsPick[selected] : projectIds[0] ?? null;
const ctx = { selOrg, lv, mine, levels, modelOf, names: id => projectName(mine?.rows, id), others: valid.filter(o => o.id !== selected) };
agentsAvailable = { ...agentsAvailable, [selected]: projectId => levelsTable(ctx, projectId) };
const chooser = projectIds.length ? `<label class="ws-psel">${av(selOrg, 'xs')}<span class="ws-sr">Project</span><select data-agents-project="${esc(selected)}" data-focus-key="agents-project">${projectIds.map(id => `<option value="${esc(id)}"${id === pick ? ' selected' : ''}>${esc(ctx.names(id))}</option>`).join('')}</select></label>` : '';
const title = projectIds.length ? 'Available in a project' : `Agents in ${esc(label(selOrg))}`;
const table = !mine ? '<p class="ws-panel tight note">The selected organization is not on the list.</p>' : levelsTable(ctx, pick);
const rules = `<div class="ws-panel tight ws-rules"><p><span class="ws-lvl root">root</span>You define root agents in agents.json in your configuration directory. The chief cannot change them.</p><p><span class="ws-lvl org">org</span>Agents come from the organization file. Add, change or remove them under Settings, Agents.</p><p><span class="ws-lvl proj">project</span>A project in the organization file can add an agent, narrow an inherited agent's limits or exclude one. It never widens them.</p><p><span class="ws-lvl proj">override</span>The most specific level wins. A row says which definition it replaces.</p><p class="muted">An agent's harness, model and thinking are set under Settings, Routing.</p></div>`;
const receipt = selected === window.MosaicOrg?.id ? `<div data-agents-receipt role="status">${window.MosaicDecide?.fireNote() ?? ''}</div>` : '';
return `<section class="ws ws-agents" data-org-agents>${head}${receipt}${band}${levelsGrid}
<div class="ws-split ws-split-agents"><section><div class="ws-sec-h"><h2>${title}</h2>${chooser}</div><div data-agents-available data-agents-org="${esc(selected)}">${table}</div></section><section>${secH('Who changes what')}${rules}</section></div>
</section>`;
}
document.addEventListener('change', e => {
const select = e.target.closest?.('[data-agents-project]');
const org = select?.dataset.agentsProject, draw = org && Object.hasOwn(agentsAvailable, org) ? agentsAvailable[org] : null;
const box = draw && select.closest('[data-org-agents]')?.querySelector('[data-agents-available]');
if (!box) return;
agentsPick = { ...agentsPick, [org]: select.value };
box.innerHTML = draw(select.value);
});
// ---------- across organizations (U3: samples 02, 04 and 05) ----------
// One read, GET /api/workspace (U1), backs the three pages. Each organization carries a state and
// the time it was read: one that is down, starting or slow is named with that state, and the rest
// still render. Filters live in the page's hash query, so a poll repaints the same view and a
// link reproduces it. Numbers come only from the read; a field no read gives is one honest line.
let pollMs = 10000;
const took = body => { const n = Number(body?.pollMs); if (Number.isFinite(n) && n >= 1000) pollMs = n; return body; };
const selHref = path => `#/orgs/${enc(window.MosaicOrg?.id || '')}${path}`;
const ORG_STATE = { ok: ['s-working', '●', 'running'], starting: ['s-waiting', '◐', 'starting'], down: ['s-offline', '○', 'down'], timeout: ['s-error', '▲', 'not answering'], invalid: ['s-error', '▲', 'invalid'] };
const orgState = o => ORG_STATE[o?.state] || ['s-unknown', '?', 'not reported'];
const msOf = iso => { const t = Date.parse(iso || ''); return Number.isFinite(t) ? t : null; };
const hm = iso => { const t = msOf(iso); return t === null ? '' : new Date(t).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); };
// Today's times as HH:MM, older ones as a short date.
const when = iso => { const t = msOf(iso); if (t === null) return ''; const d = new Date(t); return d.toDateString() === new Date().toDateString() ? hm(iso) : d.toLocaleDateString([], { month: 'short', day: 'numeric' }); };
const span = iso => { const t = msOf(iso); if (t === null) return ''; const m = Math.max(0, Math.floor((Date.now() - t) / 60000)); return m < 1 ? 'under a minute' : m < 60 ? `${m} min` : m < 2880 ? `${Math.floor(m / 60)} h` : `${Math.floor(m / 1440)} days`; };
const ago = iso => { const s = span(iso); return !s ? '' : s === 'under a minute' ? 'just now' : `${s} ago`; };
const num = v => (Number.isFinite(v) ? v : 0);
const arr = v => (Array.isArray(v) ? v : []);
// The organizations the read names, with their colours, marks and states.
function orgsOf(body) {
const rows = arr(body?.orgs).filter(o => o && typeof o.org === 'string');
// The read names an organization by id; the sidebar's list carries its display label.
const known = id => (Array.isArray(orgs) ? orgs.find(x => x?.id === id) : null);
const byId = new Map(rows.map(o => [o.org, { id: o.org, label: known(o.org)?.label || o.label || o.org, theme: o.theme ?? known(o.org)?.theme ?? null }]));
const meta = id => byId.get(id) || { id, label: id };
return {
rows, meta, name: id => label(meta(id)), style: id => colours(meta(id)),
ref: (id, cls = '') => `<span class="ws-orgref${cls}">${av(meta(id))}${esc(label(meta(id)))}</span>`,
unread: rows.filter(o => o.state !== 'ok'),
};
}
const stateWords = o => `${esc((Array.isArray(orgs) ? orgs.find(x => x?.id === o.org)?.label : null) || o.label || o.org)} ${orgState(o)[2]}${o.at ? `, read ${hm(o.at)}` : ''}`;
const andList = items => (items.length < 2 ? items.join('') : `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`);
// An organization that answered can still fail one read (errors in GET /api/workspace). The page
// names that organization and the reason rather than count the read as zero.
const READ_WHY = { 'channel-disabled': 'the chat channel is off', 'outcome-unknown': 'no answer', timeout: 'no answer in time' };
const missOf = (r, names) => { const n = r?.state === 'ok' && r.errors ? names.find(x => r.errors[x]) : null; return n ? READ_WHY[r.errors[n]] || String(r.errors[n]) : null; };
const missed = (o, names) => o.rows.filter(r => missOf(r, names)).map(r => `${esc(o.name(r.org))} (${esc(missOf(r, names))})`);
const missLine = (o, names, key, lead = 'Not read in') => { const m = missed(o, names); return m.length ? `<p class="note ws-miss" data-ws-miss="${key}">${lead} ${andList(m)}.</p>` : ''; };
// SP3/SP4: a row's organization and project as chips, and the organizations that did not answer
// named first with the reason their read gave. The Inbox and the system task board share these.
// `mark`, already-escaped markup such as the organization's avatar, takes the dot's place.
const orgChip = (o, id, mark = '<i aria-hidden="true"></i>') => `<span class="ws-chip ws-o ws-ochip" style="${o.style(id)}" data-ws-orgchip>${mark}${esc(o.name(id))}</span>`;
const projChip = name => (name ? `<span class="ws-chip outline ws-pchip" data-ws-projchip>${esc(name)}</span>` : '');
const unreadWhy = r => `${stateWords(r).replace(/, read .*$/, '')}${r.reason ? `: ${esc(r.reason)}` : ''}${r.at ? ` (read ${esc(hm(r.at))})` : ''}`;
const unreadNote = (o, names, key) => (o.unread.length ? `<p class="note ws-unread-note" data-ws-unread>Not read: ${andList(o.unread.map(unreadWhy))}.</p>` : '') + missLine(o, names, key);
// The organizations that answered and made every read a figure is built from. Only these count
// toward it: a failed read reaches the merge as an empty list, so its zero is not a figure.
const readers = (o, names) => new Set(o.rows.filter(r => r.state === 'ok' && !missOf(r, names)).map(r => r.org));
// Some organizations exist, and none of them could make these reads.
const noneRead = (o, names) => o.rows.length > 0 && !readers(o, names).size;
function failedPage(cls, attr, title, err) {
const why = err?.status === 403 ? 'This Console refused the read across organizations.' : err?.status === 0 ? 'You are signed out. Reload the page to sign in again.' : err?.status === 400 ? 'The read refused these filters. Clear them and try again.' : 'The read across organizations did not answer. The page tries again on its next refresh.';
return `<section class="ws ${cls}" ${attr} data-ws-failed><div class="ws-vh"><h1 tabindex="-1">${title}</h1><p class="sub">${why}</p></div></section>`;
}
// The Inbox count in the navigation follows the cross-organization read wherever it was made.
// SP3: the sidebar's Inbox count on a page that reads one organization (the board) comes from the
// workspace read too, so it says what #/inbox lists. A failed read leaves the count as it was.
const inboxCount = () => data.workspace({ sections: ['inbox'] }).then(b => { if (!noneRead(orgsOf(b), ['inbox'])) tellInbox(arr(b.inbox).filter(d => d && typeof d.org === 'string')); }).catch(() => {});
const newest = (a, b) => (b.at ?? '').localeCompare(a.at ?? '');
const tellInbox = rows => { if (Array.isArray(rows)) document.dispatchEvent(new CustomEvent('mosaic-workspace-inbox', { detail: { open: rows.length, blocking: rows.filter(d => d?.blocking).length } })); };
// A stacked bar and its per-organization figures, one segment per organization.
const bar = (o, parts, style = '') => `<div class="ws-bar"${style ? ` style="${style}"` : ''} aria-hidden="true">${parts.filter(p => p.n > 0).map(p => `<i class="ws-o" style="${o.style(p.id)};flex:${p.n}"></i>`).join('')}</div>`;
const by = (o, parts, fmt = n => n) => `<div class="ws-by">${parts.map(p => `<span>${av(o.meta(p.id))}<span class="ws-sr">${esc(o.name(p.id))}</span>${esc(fmt(p.n))}</span>`).join('')}</div>`;
// Why an organization's instances read gave nothing, in a word or two.
const READ_ERR = { 401: 'signed out', 403: 'refused', 0: 'signed out' };
const instWhy = r => READ_ERR[r.err?.status] || r.err?.code || 'no answer';
// SP8 (#1873): one KPI tile, a link to the page that lists what it counts. A tile with no figure
// (`big` null) is drawn quiet with `none` in its place; `miss` names the organizations the figure
// leaves out, already escaped. The figure is never shown as complete while one is missing.
const kpiTile = (o, { key, name, href, big = null, small = '', parts = null, delta = '', miss = [], none = 'Not read', attrs = '' }) => {
const quiet = big == null;
const left = miss.length ? `<span class="ws-delta ws-miss" data-ws-miss="${key}">${quiet ? '' : 'Not read in '}${andList(miss)}</span>` : '';
const head = `<a class="ws-tile${quiet ? ' quiet' : ''}" href="${esc(href)}" data-ws-tile="${key}" data-focus-key="${esc(`tile:${key}`)}"${quiet ? ` data-ws-miss="${key}"` : ''}${attrs}><span class="ws-label">${name}</span>`;
if (quiet) return `${head}<span class="ws-empty-t">${none}</span>${left}</a>`;
return `${head}<span class="ws-big">${big}${small ? ` <small>${small}</small>` : ''}</span>${parts ? bar(o, parts) + by(o, parts) : ''}${delta ? `<span class="ws-delta">${delta}</span>` : ''}${left}</a>`;
};
const CLASS_CHIP = { gated: 'gated', 'within-role': 'within', routine: 'routine', 'cross-role': 'cross' };
// The one map of decision classes to words: the class chips and the Inbox Class filter both read it.
const TYPE_WORD = { gated: 'Gated', 'within-role': 'Within role', 'cross-role': 'Cross-role', routine: 'Routine' };
// SP11: the Inbox's word for a decision class; a class the map does not know shows as it is.
const classWord = c => (Object.hasOwn(TYPE_WORD, c) ? TYPE_WORD[c] : c);
const classChip = c => (c ? `<span class="ws-chip ${CLASS_CHIP[c] || ''}">${esc(classWord(c))}</span>` : '');
const itemKey = d => `${d.org}:${d.id}`;
const roleOf = d => d.session?.role || d.raisedBy || '';
const fromWords = (o, d, withOrg = true) => [withOrg ? o.name(d.org) : '', d.project?.name || 'No project', roleOf(d)].filter(Boolean).map(esc).join(' · ');
// ---- main dashboard (sample 02) ----
async function home() {
let body;
let levels = null, listed = null;
// SP1: the agent counts come from the organization files (GET /api/agents/levels, owner only), so a
// stopped bus still has one; the bus state words come from the membership list. Either read may
// fail or be absent, and its column then shows no figure.
try { [body, levels, listed] = await Promise.all([data.workspace({ sections: ['projects', 'sessions', 'inbox', 'tasks', 'metrics'] }), data.agentLevels().catch(() => null), data.organizations().catch(() => null), ensureThemes()]); took(body); }
catch (err) { return failedPage('ws-home', 'data-ws-home', 'Dashboard', err); }
const o = orgsOf(body), m = body.metrics, t = m?.totals, per = arr(m?.orgs);
const inbox = arr(body.inbox), sessions = arr(body.sessions), projectRows = arr(body.projects), tasks = arr(body.tasks);
if (!noneRead(o, ['inbox'])) tellInbox(body.inbox);
// The reads each tile's figures come from (workspace-read.mjs orgRows).
const SRC = { needs: ['inbox'], sessions: ['agents', 'claims'], tasks: ['tasks'], done: ['tasks'], projects: ['projects'] };
const listRow = id => (Array.isArray(listed) ? listed.find(x => x?.id === id) : null);
// The bus state as the workspace read found it; "stopped" only when the membership list says the owner stopped it.
const ROW_STATE = { ok: ['s-working', '●', 'bus running'], starting: ['s-waiting', '◐', 'bus starting'], timeout: ['s-error', '▲', 'bus not answering'], invalid: ['s-error', '▲', 'invalid'] };
const rowState = (r, fromList) => (r.state === 'down' ? ['s-offline', '○', fromList?.busStopped === true ? 'bus stopped' : 'bus down'] : ROW_STATE[r.state] || orgState(r));
// SP8 (#1873): one row of tiles, each a link to the page that lists what it counts. A figure adds up
// only the organizations whose reads gave it, and its tile names the rest: one that did not answer
// by its bus state, one that answered but failed a read by that read's reason.
const offWord = r => rowState(r, listRow(r.org))[2];
const notIn = names => [...o.unread.map(r => `${esc(o.name(r.org))} (${offWord(r)})`), ...missed(o, names)];
const parts = (key, f) => { const ok = readers(o, SRC[key]); return per.filter(x => ok.has(x.org)).map(x => ({ id: x.org, n: num(f(x)) })); };
const sum = ps => ps.reduce((a, p) => a + p.n, 0);
const fig = (key, ps) => (m && readers(o, SRC[key]).size ? sum(ps) : null);
// A response with no metrics section leaves every figure tile quiet; it says so rather than a bare "Not read".
const noFig = m ? {} : { none: 'Not read: no figures were read' };
const answered = o.rows.filter(r => r.state === 'ok').length;
// Agents working of all agents: the system Agents page's rows, read the way that page reads them.
// 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);
// 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: 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 })}
${kpiTile(o, { key: 'done', name: 'Done this week', href: '#/tasks?done=week', big: fig('done', ps.done), parts: ps.done, miss: notIn(SRC.done), ...noFig })}
${kpiTile(o, { key: 'projects', name: 'Projects', href: selHref('/projects'), big: fig('projects', ps.projects), small: 'active', parts: ps.projects, delta: `${archived} archived`, miss: notIn(SRC.projects), ...noFig })}
</div>`;
// SP1 (sample r2-01): one row per organization. A figure shows only when its read gave it; an
// organization that did not answer shows its state and reason instead of figures.
const projectsRead = readers(o, SRC.projects), inboxRead = readers(o, SRC.needs);
const none = '<span class="muted" title="not read">–</span>';
const orgTable = o.rows.map(r => {
const id = r.org, fromList = listRow(id), x = per.find(p => p.org === id);
const [cls, glyph, word] = rowState(r, fromList);
const lv = levels?.orgs?.find(v => v?.id === id);
// SP11: an organization whose agents were read counts the tile's rows, running and working; one
// 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">(${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.
const reason = r.state !== 'ok' && typeof r.reason === 'string' && r.reason && !restates(r.reason) ? r.reason : '';
const why = r.state === 'ok' || !(reason || r.boot?.at) ? '' : `<span class="why">${esc(reason)}${r.boot?.at ? `${reason ? ' · ' : ''}last start ${esc(when(r.boot.at))}` : ''}</span>`;
return `<tr class="ws-o${r.state === 'ok' ? '' : ' off'}" style="${o.style(id)}" data-ws-orgrow="${esc(id)}" data-state="${esc(r.state)}"><td class="who"><a href="${esc(orgHref(id))}/organization" data-focus-key="${esc(`orgrow:${id}`)}">${av(o.meta(id))}<span class="nm">${esc(o.name(id))}</span></a>${dot(cls, glyph, word, true)}${why}</td><td>${agentsCell}</td><td class="hide-m">${projectsCell}</td><td>${needsCell}</td></tr>`;
}).join('');
const orgList = o.rows.length ? `<div class="ws-tbl"><table class="ws-orgtbl" data-ws-orgs><thead><tr><th scope="col">Organization</th><th scope="col">Agents</th><th scope="col" class="hide-m">Projects</th><th scope="col">Needs you</th></tr></thead><tbody>${orgTable}</tbody></table></div>` : '<p class="ws-panel tight note" data-ws-orgs>No organizations yet. <a class="ws-btn" href="#/settings/organizations?new=1" data-focus-key="home-org-new">New organization</a></p>';
const recent = projectRows.filter(p => p.lastActivity).slice(0, 6);
const STATE_WORD = { working: 'has a session working', waiting: 'is waiting on you', idle: 'has an idle session', none: 'no live session' };
const trail = recent.length ? `<ol class="ws-trail" data-ws-recent>${recent.map(p => `<li class="ws-o" style="${o.style(p.org)}"><time datetime="${esc(p.lastActivity)}">${esc(when(p.lastActivity))}</time>${av(o.meta(p.org))}<span class="what"><a href="${esc(orgHref(p.org))}/projects/${enc(p.id)}" data-focus-key="${esc(`recent:${p.org}:${p.id}`)}"><b>${esc(p.name || p.key || p.id)}</b></a> ${STATE_WORD[p.state] || ''}${p.needsYou ? `, ${plural(p.needsYou, 'item')} for you` : ''} <span class="src">· ${esc(o.name(p.org))}</span></span></li>`).join('')}</ol>` : `<p class="ws-panel tight note" data-ws-recent>${noneRead(o, ['projects']) ? 'Projects not read' : 'No project activity yet'}</p>`;
const open = tasks.filter(x => !x.done);
const buckets = new Map();
for (const x of open) { const b = typeof x.bucket === 'string' && x.bucket ? x.bucket : ''; if (!buckets.has(b)) buckets.set(b, new Map()); const g = buckets.get(b); g.set(x.org, (g.get(x.org) || 0) + 1); }
const srows = [...buckets.entries()].map(([b, g]) => ({ name: b ? titleCase(b) : 'No bucket', g, n: [...g.values()].reduce((a, c) => a + c, 0) })).sort((a, b) => b.n - a.n);
const taskOrgs = readers(o, ['tasks']);
if (t && taskOrgs.size) srows.push({ name: 'Done this week', g: new Map(per.filter(x => taskOrgs.has(x.org)).map(x => [x.org, num(x.doneThisWeek)])), n: num(t.doneThisWeek) });
const max = Math.max(1, ...srows.map(s => s.n));
const states = srows.length ? `<div class="ws-panel tight ws-states" data-ws-states>${srows.map(s => { const ps = [...s.g.entries()].filter(([, n]) => n > 0).map(([id, n]) => ({ id, n })); return `<div class="ws-srow"><span class="sl">${esc(s.name)}</span><span class="sn">${s.n}</span>${bar(o, ps, `width:${Math.max(4, Math.round((s.n / max) * 90))}%`)}${by(o, ps)}</div>`; }).join('')}</div>` : `<p class="ws-panel tight note" data-ws-states>${noneRead(o, ['tasks']) ? 'Tasks not read' : 'No open tasks'}</p>`;
// SP3: the same order as #/inbox, newest first, so these five are the Inbox's top five.
const needs = inbox.slice().sort(newest).slice(0, 5);
const needsList = needs.length ? `<ul class="ws-needs" data-ws-needs>${needs.map(d => `<li class="ws-edge ws-o" style="${o.style(d.org)}">${av(o.meta(d.org), 'md')}<a class="q" href="${esc(`#/inbox?d=${enc(itemKey(d))}`)}" data-focus-key="${esc(`need:${itemKey(d)}`)}">${esc(d.question || `Decision ${d.id}`)}</a><span class="src">${fromWords(o, d)}</span>${classChip(d.class)}</li>`).join('')}</ul>${inbox.length > needs.length ? `<p class="note ws-more-line">${inbox.length - needs.length} more in the inbox</p>` : ''}` : `<p class="ws-panel tight note" data-ws-needs>${noneRead(o, ['inbox']) ? 'Decisions not read' : 'Nothing needs you'}</p>`;
const now = sessions.filter(s => s.kind === 'thread' || s.state === 'working' || s.state === 'waiting');
const idle = sessions.length - now.length;
const who = s => (s.kind === 'thread' ? s.instance || s.thread || 'thread' : s.role || 'agent');
const what = s => s.project?.name || s.task?.title || '';
const st = s => { const [cls, glyph, word] = s.kind === 'thread' ? ['s-working', '●', 'live'] : ACTIVITY[s.state] || ['s-unknown', '?', s.state || 'not reported']; return `${dot(cls, glyph, word === 'waiting on you' ? 'waiting' : word, true)}${s.state === 'waiting' ? ' <span class="muted">on you</span>' : s.since ? ` <span class="muted">${esc(span(s.since))}</span>` : ''}`; };
const sessTable = now.length ? `<div class="ws-tbl"><table class="ws-sess" data-ws-sessions><thead><tr><th scope="col">Agent and project</th><th scope="col">Status</th></tr></thead><tbody>${now.slice(0, 8).map(s => `<tr><td class="who"><span class="ws-orgref">${av(o.meta(s.org), 'xs')}<span class="ws-sr">${esc(o.name(s.org))}: </span>${esc(who(s))}</span>${what(s) ? `<span class="muted"> · ${esc(what(s))}</span>` : ''}</td><td class="ws-st">${st(s)}</td></tr>`).join('')}</tbody></table></div>${now.length > 8 ? `<p class="note ws-more-line">${now.length - 8} more on Agents</p>` : ''}` : `<p class="ws-panel tight note" data-ws-sessions>${noneRead(o, ['agents', 'claims']) ? 'Sessions not read' : `No session working right now${idle ? `; ${plural(idle, 'idle session')}` : ''}`}</p>`;
const total = t ? num(t.projects?.active) + num(t.projects?.archived) : null;
const allRead = !o.unread.length;
const sub = !o.rows.length ? 'You belong to no organization yet.'
: allRead ? `All ${plural(o.rows.length, 'organization')}${missed(o, ['projects']).length ? '' : ` and ${plural(total ?? 0, 'project')}`}. Totals add up every organization you belong to; each tile breaks them down by organization.`
: `${body.summary?.read ?? o.rows.length - o.unread.length} of ${plural(o.rows.length, 'organization')} answered. Totals add up the ones that answered; ${andList(o.unread.map(stateWords))}.`;
return `<article class="ws ws-home" data-ws-home>
<div class="ws-vh"><h1 tabindex="-1">Dashboard</h1><p class="sub">${sub}</p></div>
${tiles}
<div class="ws-split ws-home-split">
<section aria-label="Organizations, projects and tasks">
${secH('Organizations', `read ${esc(hm(body.readAt))}`, '', 'tabindex="-1" data-ws-orgs-h data-focus-key="orgs-h"')}
${orgList}
${secH('Recent project activity', 'latest change per project; there is no activity feed yet', `<a href="${esc(selHref('/projects'))}" data-focus-key="home-projects">All projects</a>`)}
${trail}${missLine(o, ['projects'], 'recent')}
${secH('Tasks by state', 'open tasks, every tracker', '<a href="#/tasks" data-focus-key="home-tasks">Open tasks</a>')}
${states}${missLine(o, ['tasks'], 'states')}
</section>
<section aria-label="Needs you and sessions">
${secH('Needs you', '', '<a href="#/inbox" data-focus-key="home-inbox">Inbox</a>')}
${needsList}${missLine(o, ['inbox'], 'needs')}
${secH('Active agents', 'sessions now', '<a href="#/agents" data-focus-key="home-agents">Agents</a>')}
${sessTable}${missLine(o, ['agents', 'claims'], 'sessions')}
</section>
</div>
</article>`;
}
// ---- projects across organizations (sample 04, REQ-WS-5) ----
const ORG_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
const listParam = (q, key, ok) => { const v = [...new Set(String(q?.get?.(key) || '').split(',').map(s => s.trim()).filter(ok))]; return v.length ? v : null; };
// The hash query, cleaned to what the API accepts, so a hand-edited link never reads as "all".
function projectQuery(q) {
const sort = ['activity', 'name', 'org', 'status'].includes(q?.get?.('sort')) ? q.get('sort') : 'activity';
const order = ['asc', 'desc'].includes(q?.get?.('order')) ? q.get('order') : sort === 'activity' ? 'desc' : 'asc';
const name = String(q?.get?.('name') || '').trim().slice(0, 200);
return {
org: listParam(q, 'org', id => ORG_ID.test(id)), status: listParam(q, 'status', s => ['active', 'archived'].includes(s)) || ['active'],
state: listParam(q, 'state', s => ['working', 'waiting', 'idle', 'none'].includes(s)), name: name || null, sort, order,
};
}
const SORT_WORD = { activity: 'latest activity', name: 'name', org: 'organization', status: 'status' };
const STATUS_OPTS = [['active', 'Active'], ['archived', 'Archived'], ['active,archived', 'Active and archived']];
const STATE_OPTS = [['', 'Any session state'], ['working', 'Working'], ['waiting', 'Waiting on you'], ['idle', 'Idle'], ['none', 'No session']];
function orgChips(o, counts, chosen, total, src = []) {
const all = !chosen;
return `<div class="ws-fchips" role="group" aria-label="Organization"><button type="button" class="f plain" data-ws-org="" data-focus-key="chip:all" aria-pressed="${all}">All <span class="n">${total}</span></button>${o.rows.map(r => `<button type="button" class="f ws-o" style="${o.style(r.org)}" data-ws-org="${esc(r.org)}" data-focus-key="${esc(`chip:${r.org}`)}" aria-pressed="${!!chosen?.includes(r.org)}">${av(o.meta(r.org))}${esc(o.name(r.org))}<span class="n">${r.state === 'ok' && !missOf(r, src) ? counts.get(r.org) || 0 : `<span class="ws-sr">, </span>${r.state === 'ok' ? 'not read' : esc(orgState(r)[2])}`}</span></button>`).join('')}</div>`;
}
async function projectsPage(q) {
const f = projectQuery(q);
const params = { sections: ['projects'], org: f.org, status: f.status, state: f.state, name: f.name, sort: f.sort, order: f.order };
let body, all;
try {
[body, all] = await Promise.all([data.workspace(params), f.org ? data.workspace({ ...params, org: null }) : null, ensureThemes()]);
took(body);
} catch (err) { return failedPage('ws-projects', 'data-ws-projects', 'Projects', err); }
const every = orgsOf(all || body), o = orgsOf(body);
const counts = new Map();
for (const p of arr((all || body).projects)) counts.set(p.org, (counts.get(p.org) || 0) + 1);
const rows = arr(body.projects);
const flat = grouping === 'flat';
const cols = flat ? 8 : 7;
const aria = key => (f.sort === key ? ` aria-sort="${f.order === 'desc' ? 'descending' : 'ascending'}" class="sorted` : ' class="');
const ar = key => (f.sort === key ? `<span class="ar" aria-hidden="true">${f.order === 'desc' ? '↓' : '↑'}</span>` : '');
const head = `<tr>${flat ? `<th scope="col"${aria('org')} hide-m">Organization${ar('org')}</th>` : ''}<th scope="col"${aria('name')}">Project${ar('name')}</th><th scope="col"${aria('status')}">Status${ar('status')}</th><th scope="col" class="hide-m">Sessions</th><th scope="col" class="num hide-m">Open tasks</th><th scope="col" class="num">Needs you</th><th scope="col"${aria('activity')} hide-m">Last activity${ar('activity')}</th><th scope="col" class="hide-m">Git</th></tr>`;
const SESS = [['working', 's-working', '●', 'working'], ['waiting', 's-waiting', '◐', 'waiting'], ['idle', 's-idle', '–', 'idle']];
// A row's figures come from more reads than its project list (workspace-read.mjs orgRows). A
// figure whose reads failed in the row's organization says "not read", never 0 or none.
const DEP = { sessions: ['agents', 'claims', 'threads', 'tasks'], tasks: ['tasks'], needs: ['inbox', 'tasks'], activity: ['tasks', 'inbox', 'agents', 'claims', 'threads'] };
const notRead = (p, key) => missOf(o.rows.find(r => r.org === p.org), DEP[key]);
const nr = why => `<span class="muted" title="${esc(why)}">not read</span>`;
const sessCell = p => { const s = p.sessions || {}, have = SESS.filter(([k]) => num(s[k]) > 0); if (!have.length) return '<span class="muted">none</span>'; const [k, cls, glyph, word] = have[0]; return `${dot(cls, glyph, `${num(s[k])} ${word}`, true)}${have.length > 1 ? `<span class="t2">${have.slice(1).map(([k2, , , w2]) => `${num(s[k2])} ${w2}`).join(' · ')}</span>` : ''}`; };
const row = p => {
const href = `${orgHref(p.org)}/projects/${enc(p.id)}`, active = p.status === 'active';
return `<tr class="ws-edge ws-o" style="${o.style(p.org)}" data-ws-project="${esc(`${p.org}:${p.id}`)}">
${flat ? `<td class="hide-m">${o.ref(p.org)}</td>` : ''}
<td><a class="t1 nm" href="${esc(href)}" data-focus-key="${esc(`prow:${p.org}:${p.id}`)}">${av(o.meta(p.org), 'xs mob')}${esc(p.name || p.key || p.id)}<span class="ws-sr"> in ${esc(o.name(p.org))}</span></a>${p.key ? `<span class="t2 mono hide-m">${esc(p.key)}</span>` : ''}<span class="t2 show-m">${p.lastActivity ? esc(ago(p.lastActivity)) : 'No activity yet'}</span></td>
<td>${active ? dot('s-ok', '●', 'active', true) : dot('s-idle', '–', 'archived', true)}</td>
<td class="hide-m">${notRead(p, 'sessions') ? nr(notRead(p, 'sessions')) : sessCell(p)}</td>
<td class="num hide-m">${notRead(p, 'tasks') ? nr(notRead(p, 'tasks')) : num(p.openTasks)}</td>
<td class="num">${notRead(p, 'needs') ? nr(notRead(p, 'needs')) : p.needsYou ? `<span class="ws-n hot">${num(p.needsYou)}</span>` : '<span class="muted">0</span>'}</td>
<td class="hide-m">${p.lastActivity ? `<time datetime="${esc(p.lastActivity)}">${esc(ago(p.lastActivity))}</time>${notRead(p, 'activity') ? '<span class="t2">some reads missing</span>' : ''}` : notRead(p, 'activity') ? nr(notRead(p, 'activity')) : '<span class="muted">none yet</span>'}</td>
<td class="hide-m">${p.git ? `<span class="ws-chip outline">${esc(p.git)}</span>` : '<span class="muted">none</span>'}</td>
</tr>`;
};
const unreadRow = r => `<tr class="ws-unread"><td colspan="${cols}">${dot(...orgState(r), true)} <span class="muted">Not read${r.at ? ` at ${esc(hm(r.at))}` : ''}${r.reason ? `: ${esc(r.reason)}` : ''}</span></td></tr>`;
let tbody;
if (flat) tbody = rows.length ? rows.map(row).join('') : `<tr><td colspan="${cols}" class="muted">${noneRead(o, ['projects']) ? 'Projects not read' : f.org || f.state || f.name || f.status.join() !== 'active' ? 'No projects match these filters' : 'No projects yet'}</td></tr>`;
else {
const groups = (f.sort === 'org' && f.order === 'desc' ? [...o.rows].reverse() : o.rows);
tbody = groups.map(r => {
const mine = rows.filter(p => p.org === r.org);
const h = `<tr class="ws-grp-row ws-o" style="${o.style(r.org)}" data-ws-group-org="${esc(r.org)}"><th colspan="${cols}" scope="colgroup">${av(o.meta(r.org))}<span>${esc(o.name(r.org))}</span>${r.state === 'ok' && !missOf(r, ['projects']) ? `<span class="ws-n">${mine.length}</span>` : ''}</th></tr>`;
const why = missOf(r, ['projects']);
return h + (r.state !== 'ok' ? unreadRow(r) : why ? `<tr class="ws-unread"><td colspan="${cols}">${dot('s-unknown', '?', 'not read', true)} <span class="muted">Projects not read: ${esc(why)}</span></td></tr>` : mine.length ? mine.map(row).join('') : `<tr><td colspan="${cols}" class="muted">No projects match</td></tr>`);
}).join('') || `<tr><td colspan="${cols}" class="muted">No organizations yet</td></tr>`;
}
const unreadNote = flat && o.unread.length ? `<p class="note ws-unread-note" data-ws-unread>Not in this list: ${andList(o.unread.map(stateWords))}.</p>` : '';
// Projects that were read can still lack figures from the other reads; the cells say "not read".
const missNote = (flat ? missLine(o, ['projects'], 'projects') : '') + missLine({ ...o, rows: o.rows.filter(r => !missOf(r, ['projects'])) }, DEP.activity, 'figures', 'Some figures not read in');
const shown = new Set(rows.map(p => p.org)).size;
const sub = `${plural(rows.length, 'project')} in ${plural(shown, 'organization')}, sorted by ${SORT_WORD[f.sort]}${f.sort === 'activity' ? (f.order === 'desc' ? ', newest first' : ', oldest first') : f.order === 'desc' ? ', descending' : ''}. Each row names its organization by mark and colour edge.`;
const statusVal = f.status.join(',');
const stateVal = f.state?.length === 1 ? f.state[0] : '';
return `<section class="ws ws-projects" data-ws-projects>
<div class="ws-vh"><h1 tabindex="-1">Projects</h1><div class="ws-right"><a class="ws-btn" href="${esc(selHref('/chat'))}" data-focus-key="proj-new">${icon('plus')}New project</a></div><p class="sub">${sub}</p></div>
<div class="ws-toolbar">
<label class="ws-search">${icon('search', 'sm')}<span class="ws-sr">Filter projects by name</span><input type="search" data-ws-name data-focus-key="proj-name" placeholder="Filter by name" maxlength="200" autocomplete="off" value="${esc(String(q?.get?.('name') || '').slice(0, 200))}"></label>
${orgChips(every, counts, f.org, arr((all || body).projects).length, ['projects'])}
<label class="ws-sel"><span class="ws-label">Status</span><select data-ws-status data-focus-key="proj-status">${STATUS_OPTS.map(([v, l]) => `<option value="${v}"${v === statusVal ? ' selected' : ''}>${l}</option>`).join('')}</select></label>
<label class="ws-sel"><span class="ws-label">State</span><select data-ws-state data-focus-key="proj-state">${STATE_OPTS.map(([v, l]) => `<option value="${v}"${v === stateVal ? ' selected' : ''}>${l}</option>`).join('')}</select></label>
<div class="ws-right"><span class="ws-label hide-m" id="ws-sort-l">Sort</span><span class="ws-seg" role="group" aria-labelledby="ws-sort-l">${['activity', 'name', 'org', 'status'].map(s => `<button type="button" data-ws-sort="${s}" data-focus-key="sort:${s}" aria-pressed="${f.sort === s}"${f.sort === s ? ` title="Reverse the order"` : ''}>${titleCase(s === 'org' ? 'org' : s)}${f.sort === s ? `<span class="ws-sr">, ${f.order === 'desc' ? 'descending' : 'ascending'}</span>` : ''}</button>`).join('')}</span>
<span class="ws-seg" role="group" aria-label="Project layout"><button type="button" data-ws-group="org" data-focus-key="pgroup-org" aria-pressed="${!flat}">By org</button><button type="button" data-ws-group="flat" data-focus-key="pgroup-flat" aria-pressed="${flat}">Flat</button></span></div>
</div>
${unreadNote}${missNote}
<div class="ws-tbl"><table class="ws-ptable" data-ws-table data-grouping="${flat ? 'flat' : 'org'}"><caption class="ws-sr">Projects across organizations</caption><thead>${head}</thead><tbody>${tbody}</tbody></table></div>
</section>`;
}
// ---- inbox across organizations (sample 05; SP3 prototype 1114 /inbox) ----
// SP3: #/inbox lists every organization's items from one read (GET /api/workspace), newest first,
// each row with its organization chip and a project chip when it has one. The organization and type
// filters live in the hash query and run on that read, so the chip counts, the sidebar count and the
// dashboard's Needs you agree. `opts.scope` is the organization of #/orgs/<id>/inbox: the same list,
// filtered to it. `opts.answer(d)` returns the answer panel bus.js builds in the row's own
// organization; `opts.answered(key)` keeps its receipt after the row leaves the list. `opts.hire`: a
// function that returns the hire, fire and change form bus.js builds for the current organization
// (D4, P0-1), shown on the scoped list only. It is called after the read so typing or a submit
// result that lands during the read is not painted over with an older draft.
const TYPE_RE = /^[a-z][a-z-]{0,31}$/;
async function inboxPage(q, opts = {}) {
const scope = typeof opts.scope === 'string' && ORG_ID.test(opts.scope) ? opts.scope : null;
const org = scope ? [scope] : listParam(q, 'org', id => ORG_ID.test(id));
const type = TYPE_RE.test(String(q?.get?.('type') || '')) ? q.get('type') : null;
const want = String(q?.get?.('d') || '');
let body;
try { [body] = await Promise.all([data.workspace({ sections: ['inbox'] }), ensureThemes()]); took(body); }
catch (err) { return failedPage('ws-inbox', 'data-ws-inbox', 'Inbox', err); }
const every = orgsOf(body), everyRows = arr(body.inbox).filter(d => d && typeof d.org === 'string');
if (!noneRead(every, ['inbox'])) tellInbox(everyRows);
const counts = new Map();
for (const d of everyRows) counts.set(d.org, (counts.get(d.org) || 0) + 1);
// The organizations in view: every one, or the chosen ones.
const o = org ? { ...every, rows: every.rows.filter(r => org.includes(r.org)), unread: every.unread.filter(r => org.includes(r.org)) } : every;
const inOrg = everyRows.filter(d => !org || org.includes(d.org)).sort(newest);
const rows = inOrg.filter(d => !type || d.class === type);
const picked = want === 'none' ? null : rows.find(d => itemKey(d) === want) || (want ? null : rows[0] || null);
const here = path => (scope ? `${orgHref(scope)}${path}` : `#${path}`);
const qs = d => { const p = new URLSearchParams(); if (org && !scope) p.set('org', org.join(',')); if (type) p.set('type', type); p.set('d', d ? itemKey(d) : 'none'); return here(`/inbox?${p}`); };
const chips = d => `${orgChip(o, d.org)}${projChip(d.project?.name)}`;
const row = d => {
const on = picked && itemKey(d) === itemKey(picked), by = roleOf(d);
return `<tr class="ws-row ws-edge ws-o${on ? ' on' : ''}" style="${o.style(d.org)}" data-ws-item="${esc(itemKey(d))}">
<td><a class="q" href="${esc(qs(d))}" data-ws-select="${esc(itemKey(d))}" data-focus-key="${esc(`item:${itemKey(d)}`)}"${on ? ' aria-current="true"' : ''}>${esc(d.question || `Decision ${d.id}`)}</a><span class="ws-ichips">${chips(d)}<span class="via">${by ? `${esc(by)} · ` : ''}decision <span class="mono">${esc(d.id)}</span>${d.taskRef ? ` · task ${esc(d.taskRef)}` : ''}</span><span class="show-m">${classChip(d.class)}${d.blocking ? ' <span class="ws-chip block">blocking</span>' : ''}</span></span></td>
<td class="hide-m">${classChip(d.class)}${d.blocking ? ' <span class="ws-chip block">blocking</span>' : ''}</td>
<td class="num">${d.at ? `<time datetime="${esc(d.at)}">${esc(span(d.at))}</time>` : '<span class="muted">not reported</span>'}</td>
</tr>`;
};
// An organization that did not answer is named first, with the reason its read gave.
const unread = unreadNote(o, ['inbox'], 'inbox');
const filtered = (org && !scope) || type;
const table = rows.length ? `<div class="ws-tbl"><table class="ws-ibx" data-ws-items><caption class="ws-sr">Items that need you</caption><thead><tr><th scope="col">Needs</th><th scope="col" class="hide-m">Class</th><th scope="col" class="num">Waiting</th></tr></thead><tbody>${rows.map(row).join('')}</tbody></table></div>` : `<p class="ws-panel tight note" data-ws-items>${noneRead(o, ['inbox']) ? 'Decisions not read' : filtered ? 'Nothing matches these filters' : 'Nothing needs you'}</p>`;
// The hire, fire and change form posts to one organization's bus, so the system list links to
// each answering organization's own Inbox, where the form is: only those whose own config says this
// Console decides there, never judged by the organization opened last (its bus may be the stopped one).
// Read before the answer panel: its HTML must be the last thing this render waits for, so a
// confirmation shown while another read was in flight is never painted over with an older panel.
const asks = typeof opts.hireIn === 'function' && !scope ? o.rows.filter(r => r.state === 'ok') : [];
const hiring = (await Promise.all(asks.map(async r => ((await opts.hireIn(r.org)) === true ? r : null)))).filter(Boolean);
let insp = '';
if (picked) {
const d = picked, id = esc(d.id);
const decideHref = `${orgHref(d.org)}/inbox/${enc(d.id)}`;
const answerHtml = (await opts.answer?.(d)) || '';
const choices = arr(d.options);
const optList = choices.length ? `<ul class="ws-opts">${choices.map(x => `<li><div class="row"><span class="k">${esc(x.key)}</span><b>${esc(x.text || '')}</b></div>${answerHtml.includes('data-decide') ? '' : `<div class="row"><a class="ws-btn" href="${esc(decideHref)}" data-focus-key="${esc(`answer:${itemKey(d)}:${x.key}`)}">${d.console ? `Answer ${esc(x.key)}…` : 'Open the decision'}<span class="ws-sr"> on ${esc(o.name(d.org))}'s bus</span></a></div>`}</li>`).join('')}</ul>` : `<p class="note">No options were given. <a href="${esc(decideHref)}" data-focus-key="${esc(`answer:${itemKey(d)}`)}">Open the decision</a></p>`;
const cmds = arr(d.decide).filter(c => typeof c?.command === 'string' && c.command);
const term = cmds.length ? `<div data-ws-cmds><span class="ws-label">Answer from a terminal</span>${cmds.map(c => `<div class="ws-cmd"><code>${esc(c.command)}</code><button type="button" class="ws-btn" data-copy="${esc(c.command)}" data-focus-key="${esc(`copy:${itemKey(d)}:${c.key}`)}" aria-label="Copy the command for option ${esc(c.key)}" title="Copy">${icon('copy')}</button></div>`).join('')}<p class="note">The inbox mixes organizations, so the copied command always names the organization's bus.</p><p class="small muted" id="copy-status" role="status"></p></div>` : '<p class="note" data-ws-cmds>No terminal command for this item: its id or options cannot be passed to a shell safely.</p>';
const by = roleOf(d);
insp = `<aside class="ws-insp ws-o" style="${o.style(d.org)}" aria-label="Decision ${id}" data-ws-insp="${esc(itemKey(d))}">
<header>${av(o.meta(d.org))}<span class="ws-label">Decision <span class="mono">${id}</span></span>${classChip(d.class)}<a class="x" href="${esc(qs(null))}" data-ws-select="none" data-focus-key="insp-close" aria-label="Close the decision">${icon('close')}</a></header>
<div class="body">
<div class="ws-ichips">${chips(d)}</div>
<h3>${esc(d.question || `Decision ${d.id}`)}</h3>
<div class="ws-auth">${esc(o.name(d.org))} · ${esc(d.project?.name || 'No project')}${by ? ` · raised by <b>${esc(by)}</b>` : ''}${d.at ? ` at ${esc(hm(d.at))}` : ''}.${d.class === 'gated' ? ' Only you can answer a gated decision.' : ''}</div>
${d.task?.title || d.taskRef ? `<p class="note">Task ${esc(d.taskRef || '')}${d.task?.title ? ` · ${esc(d.task.title)}` : ''}</p>` : ''}
${optList}
${answerHtml}
<p><a class="ws-btn" href="${esc(decideHref)}" data-ws-open data-focus-key="${esc(`open:${itemKey(d)}`)}">Open in ${esc(o.name(d.org))}</a></p>
${term}
<div><span class="ws-label">History</span><p class="note">Not built yet.</p></div>
</div>
</aside>`;
} else if (want && want !== 'none') {
// The answered row has left the list; its receipt stays until another row is chosen.
const kept = opts.answered?.(want) || '';
if (kept) insp = `<aside class="ws-insp" aria-label="Answered" data-ws-insp="${esc(want)}"><header><span class="ws-label">Answered</span><a class="x" href="${esc(qs(null))}" data-ws-select="none" data-focus-key="insp-close" aria-label="Close">${icon('close')}</a></header><div class="body">${kept}</div></aside>`;
}
// Type chips: the decision classes the read carries, in the organizations in view.
const typeCounts = new Map();
for (const d of inOrg) if (typeof d.class === 'string' && TYPE_RE.test(d.class)) typeCounts.set(d.class, (typeCounts.get(d.class) || 0) + 1);
const types = [...new Set([...typeCounts.keys(), ...(type ? [type] : [])])].sort();
const typeChips = `<div class="ws-fchips" role="group" aria-label="Class"><span class="ws-label">Class</span><button type="button" class="f plain" data-ws-type="" data-focus-key="type:all" aria-pressed="${!type}">All <span class="n">${inOrg.length}</span></button>${types.map(c => `<button type="button" class="f plain" data-ws-type="${esc(c)}" data-focus-key="${esc(`type:${c}`)}" aria-pressed="${type === c}">${esc(TYPE_WORD[c] || c)} <span class="n">${typeCounts.get(c) || 0}</span></button>`).join('')}</div>`;
const hireIn = hiring.length ? `<p class="note" data-ws-hire-in>Hire, fire or change an agent in ${andList(hiring.map(r => `<a href="${esc(`${orgHref(r.org)}/inbox`)}" data-focus-key="${esc(`hire-in:${r.org}`)}">${esc(o.name(r.org))}</a>`))}.</p>` : '';
const orgsWith = new Set(rows.map(d => d.org)).size;
const tally = rows.length ? ` ${plural(rows.length, 'item')}${scope ? '' : ` from ${plural(orgsWith, 'organization')}`}.` : '';
const sub = scope
? `Items from ${esc(o.name(scope))} only.${tally} <a href="#/inbox" data-focus-key="inbox-all">Every organization</a>`
: `Everything waiting on you, from every organization.${tally} An item leaves only when it is answered.`;
return `<section class="ws ws-inbox" data-ws-inbox${scope ? ` data-ws-scope="${esc(scope)}"` : ''}>
<div class="ws-vh"><h1 tabindex="-1">Inbox</h1><p class="sub">${sub}</p></div>
${unread}
<div class="ws-toolbar ws-ibx-filters">
${scope ? '' : `<div class="ws-fgroup"><span class="ws-label">Org</span>${orgChips(every, counts, org, everyRows.length, ['inbox'])}</div>`}
${typeChips}
</div>
<div class="ws-ibx-grid${insp ? ' with-insp' : ''}"><div class="ws-ibx-list">${table}
${typeof opts.hire === 'function' ? opts.hire() : hireIn}</div>
${insp}
</div>
</section>`;
}
// ---- agents across organizations (#1873 SP5, prototype shot 14) ----
// One table of every organization's agents: the organization's own instances and the root and
// project copies its bus booted with, from each organization's instances read; what each one works
// on from the workspace read's role sessions. Filters by organization and state live in the hash.
// `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'], ['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 })),
typeof fireIn === 'function' ? fireIn(id).then(v => v === true, () => false) : false,
]).then(([v, fire]) => ({ id, ...v, fire }))));
// The agent rows of every organization whose instances read answered: its own instances and the root
// and project copies its bus booted with, each in the state the system Agents page shows. SP8: the
// Dashboard and organization tiles count these same rows, so a tile's figure is the page's row count.
function agentRows(reads, body) {
const sessions = arr(body?.sessions).filter(x => x?.kind === 'role' && typeof x.org === 'string' && typeof x.role === 'string');
const projects = arr(body?.projects).filter(x => typeof x?.org === 'string');
const projectRef = (id, p) => { const hit = projects.find(x => x.org === id && (x.id === p || x.key === p)); return hit ? { id: hit.id, name: hit.name || hit.key || hit.id } : { id: p, name: p }; };
const all = [];
for (const r of reads) {
if (!r.inst) continue;
const mine = sessions.filter(x => x.org === r.id);
const agents = mine.map(x => ({ role: x.role, holder_run: x.run, state: x.state }));
const session = name => mine.find(x => x.role === name) || null;
for (const [name, item] of Object.entries(r.inst)) {
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, 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, keep: true, item: c });
}
}
for (const a of all) a.state = AGENT_STATE_KEY[a.dot[2]] || 'not-running';
return all;
}
async function agentsPage(q, opts = {}) {
// SP5 review F11: a scope that is not an organization id is refused, never widened to the system list.
if (opts.scope != null && !(typeof opts.scope === 'string' && ORG_ID.test(opts.scope))) return '<section class="ws ws-agents-all" data-ws-agents data-ws-failed><div class="ws-vh"><h1 tabindex="-1">Agents</h1><p class="sub">That is not an organization address.</p></div></section>';
const scope = opts.scope ?? null;
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); }
const every = orgsOf(body);
const o = org ? { ...every, rows: every.rows.filter(r => org.includes(r.org)), unread: every.unread.filter(r => org.includes(r.org)) } : every;
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);
const inOrg = all.filter(a => !org || org.includes(a.org)).sort((x, y) => x.org.localeCompare(y.org) || x.name.localeCompare(y.name) || x.key.localeCompare(y.key));
const filteredRows = inOrg.filter(a => !stateF || a.state === stateF);
// SP5 review F1/F2: Open addresses one agent (`#/orgs/<id>/agents?agent=<key>`). The scoped page puts
// that agent first and marks it, and draws no Open of its own, which would only link to itself.
const picked = scope ? String(q?.get?.('agent') || '') : '';
const hit = picked ? filteredRows.find(a => a.key === picked) || null : null;
const rows = hit ? [hit, ...filteredRows.filter(a => a !== hit)] : filteredRows;
const akey = a => `${a.org}:${a.key}`;
const orgChip = a => `<span class="ws-chip ws-o ws-ochip" style="${o.style(a.org)}" data-ws-orgchip><i aria-hidden="true"></i>${esc(o.name(a.org))}</span>`;
const projOf = a => a.project || a.s?.project || null;
const projChip = a => (projOf(a)?.name ? `<span class="ws-chip outline ws-pchip" data-ws-projchip>${esc(projOf(a).name)}</span>` : '');
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">${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>
${scope ? '' : `<td class="ws-act"><a class="ws-btn" href="${esc(`${orgHref(a.org)}/agents?agent=${encodeURIComponent(a.key)}`)}" data-ws-open data-focus-key="${esc(`open:${akey(a)}`)}">Open<span class="ws-sr"> ${esc(a.name)} in ${esc(o.name(a.org))}</span></a>${a.fire ? window.MosaicDecide?.fireControl(a.org, a.name, true, o.name(a.org)) ?? '' : ''}</td>`}
</tr>`;
// An organization that did not answer is named first, with the reason its read gave; one that
// answered but whose instances read failed is named too, never counted as having no agents.
const why = r => `${stateWords(r).replace(/, read .*$/, '')}${r.reason ? `: ${esc(r.reason)}` : ''}${r.at ? ` (read ${esc(hm(r.at))})` : ''}`;
const failed = reads.filter(r => !r.inst && (!org || org.includes(r.id)));
const unread = (o.unread.length ? `<p class="note ws-unread-note" data-ws-unread>Not read: ${andList(o.unread.map(why))}.</p>` : '')
+ (failed.length ? `<p class="note ws-miss" data-ws-miss="instances">Agents not read in ${andList(failed.map(r => `${esc(o.name(r.id))} (${esc(instWhy(r))})`))}.</p>` : '')
+ missLine(o, ['agents', 'tasks'], 'agents', 'What agents work on was not read in');
const anyRead = reads.some(r => r.inst && (!org || org.includes(r.id)));
const filtered = (org && !scope) || stateF;
const table = rows.length
? `<div class="ws-tbl"><table class="ws-agt" data-ws-agent-list><caption class="ws-sr">Agents</caption><thead><tr><th scope="col">Agent</th><th scope="col" class="hide-m">Role</th><th scope="col">State</th><th scope="col" class="hide-m">Working on</th>${scope ? '' : '<th scope="col"><span class="ws-sr">Actions</span></th>'}</tr></thead><tbody>${rows.map(row).join('')}</tbody></table></div>`
: `<p class="ws-panel tight note" data-ws-agent-list>${!anyRead && o.rows.length ? 'Agents not read' : filtered ? 'Nothing matches these filters' : 'No agents'}</p>`;
const stateCounts = new Map();
for (const a of inOrg) stateCounts.set(a.state, (stateCounts.get(a.state) || 0) + 1);
const shown = AGENT_STATE.filter(([k]) => stateCounts.has(k) || k === stateF);
const stateChips = `<div class="ws-fchips" role="group" aria-label="State"><span class="ws-label">State</span><button type="button" class="f plain" data-ws-astate="" data-focus-key="astate:all" aria-pressed="${!stateF}">All <span class="n">${inOrg.length}</span></button>${shown.map(([k, w]) => `<button type="button" class="f plain" data-ws-astate="${k}" data-focus-key="${esc(`astate:${k}`)}" aria-pressed="${stateF === k}">${esc(w)} <span class="n">${stateCounts.get(k) || 0}</span></button>`).join('')}</div>`;
// The org chips count each answering organization's agents; an organization whose instances read
// failed shows "not read", as one that did not answer shows its state.
const notRead = new Set(reads.filter(r => !r.inst).map(r => r.id));
const chipOrgs = { ...every, rows: every.rows.map(r => (notRead.has(r.org) ? { ...r, errors: { ...(r.errors || {}), instances: 'not read' } } : r)) };
const orgsWith = new Set(rows.map(a => a.org)).size;
// SP11: running and working in the Dashboard tiles' words, over the rows shown.
const tally = rows.length ? ` ${plural(rows.length, 'agent')}${scope ? '' : ` in ${plural(orgsWith, 'organization')}`}: ${runningOf(rows)} running, ${workingOf(rows)} working.` : '';
const sub = scope
? `Agents in ${esc(o.name(scope))} only.${tally} <a href="#/agents" data-focus-key="agents-all">Every organization</a>`
: `Every agent on the system, by organization.${tally} Open one to see it in its organization.`;
return `<section class="ws ws-agents-all" data-ws-agents${scope ? ` data-ws-scope="${esc(scope)}"` : ''}>
<div class="ws-vh"><h1 tabindex="-1">Agents</h1><p class="sub">${sub}</p></div>
${unread}
<div class="ws-toolbar ws-ibx-filters">
${scope ? '' : `<div class="ws-fgroup"><span class="ws-label">Org</span>${orgChips(chipOrgs, counts, org, all.length, ['instances'])}</div>`}
${stateChips}
</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. A repaint while the read
// is still open waits on the same read; once it answers it is let go, so the next render reads again.
let drawerInst = null, drawerReads = 0; // { org, n, done, value, p }
// Repaints whose read answered before their drawer was on screen, keyed by the drawer's
// data-drawer-pending and its agent id. A drawer never painted (closed, or replaced by a later paint)
// leaves its entry; the oldest go first.
const drawerLate = new Map(), DRAWER_LATE_MAX = 8;
const drawerInstRead = org => {
if (drawerInst?.org === org) return drawerInst;
const r = { org, n: ++drawerReads, done: false, value: null };
r.p = data.instances(org).then(v => ({ inst: instancesOf(v), copies: copiesOf(v) }), err => ({ inst: null, copies: {}, err }))
.then(v => { r.done = true; r.value = v; return v; });
r.p.then(() => { if (drawerInst === r) drawerInst = null; });
drawerInst = r;
return r;
};
// SP16 (#1873): the template a pack hire was hired from. Only the packs read names it (owner only):
// the pack's hire of this name points at a definition, and that definition at a template. It is read
// only for an organization agent the instances read says a pack hired. The answer is kept per
// organization for DRAWER_PACKS_KEEP ms, and a repaint draws from the kept answer, also while a newer
// read is open, so the line does not change on every poll and a poll does not read packs each time.
// A kept answer that is of no use for this hire is read again at once (SP16 review 3): a refusal or no
// answer on each render, so the line recovers with the route; an answer that does not name this hire
// (a hire made after it was read) once per hire until the keep runs out, so a hire the pack really
// does not name does not read packs on every poll. `p` is given only when the drawer should repaint
// on it: nothing is kept, or the kept answer is of no use for this hire. `value` is then the kept
// refusal, or nothing (the line says being read) rather than a kept answer that does not name it.
// `start` false only looks: the drawer's second look after its race starts no read.
// The pack is the one installed now; the read does not say which version the hire was made from.
// It never rejects: a refusal, no answer or an answer that is not the packs list each give `err`.
const drawerPacksKept = new Map(), DRAWER_PACKS_KEEP = 60000; // org -> { at, value, p, asked }
const drawerPacks = (org, instValue, key, start = true) => {
const item = instValue?.inst?.[key];
if (!item || !isHired(item) || typeof item.pack?.id !== 'string') return null;
let k = drawerPacksKept.get(org);
if (!k) drawerPacksKept.set(org, (k = { at: 0, value: null, p: null, asked: new Set() }));
const v = k.value, named = !!v && !v.err && !!packTemplate(item, key, v).template;
const expired = !v || Date.now() - k.at >= DRAWER_PACKS_KEEP;
const again = !!v && (!!v.err || (!named && !k.asked.has(key)));
if (start && !k.p && (expired || again)) {
if (expired) k.asked.clear();
if (v && !v.err && !named) k.asked.add(key);
const kept = k;
kept.p = fetch(`/api/orgs/${enc(org)}/packs`, { cache: 'no-store', redirect: 'manual' }).then(async r => {
if (!r.ok || r.type === 'opaqueredirect') return { err: { status: r.type === 'opaqueredirect' ? 0 : r.status } };
const v = await r.json().catch(() => null);
return Array.isArray(v?.packs) ? { packs: v.packs } : { err: { code: 'no answer' } };
}).catch(() => ({ err: { code: 'no answer' } })).then(v => { kept.value = v; kept.at = Date.now(); kept.p = null; return v; });
}
const wait = k.p && !named ? k.p : null;
return { value: wait && v && !v.err ? null : v, p: wait };
};
// The pack's own label and the template its hire of this name is made from, from the packs read. The
// instance names only the pack's id; the installed pack's document carries its label.
const packTemplate = (item, name, read) => {
const pk = item?.pack, doc = arr(read?.packs).find(p => p?.id === pk?.id && (pk?.origin == null || p?.origin === pk.origin))?.pack;
const hire = arr(doc?.hires).find(h => h?.name === name);
const entry = typeof hire?.definition === 'string' && doc?.definitions && typeof doc.definitions === 'object' ? doc.definitions[hire.definition] : null;
const t = entry?.template ?? entry?.from?.template;
return { template: typeof t === 'string' && t ? t : '', label: typeof doc?.label === 'string' && doc.label ? doc.label : '' };
};
// Swaps a drawer still on screen for `html`, keeping focus, and runs at once a repaint already waiting
// on the fresh drawer's marker (its packs read answered before this drawer was painted).
const drawerSwap = (node, html) => {
const key = focusKey(node), tpl = document.createElement('template');
tpl.innerHTML = html;
const fresh = tpl.content.firstElementChild;
if (!fresh) return;
node.replaceWith(fresh);
refocus(fresh, key);
drawerLateRun(fresh);
};
function drawerLateRun(node) {
const k = `${node.dataset.drawerPending}:${node.dataset.wsDrawer}`, redo = node.dataset.drawerPending ? drawerLate.get(k) : null;
if (redo) { drawerLate.delete(k); redo(node); }
}
// Repaints the drawer that carries `mark` once `p` answers: now if it is on screen, else once it is
// painted. `build(answer)` runs when the read answers and gives what draws the drawer at the swap.
const drawerWhen = (p, mark, id, build) => p.then(v => {
const draw = build(v), redo = node => drawerSwap(node, draw());
const node = document.querySelector(`#bus-view [data-ws-drawer="${CSS.escape(id)}"][data-drawer-pending="${mark}"]`);
if (node) { redo(node); return; }
drawerLate.set(`${mark}:${id}`, redo);
while (drawerLate.size > DRAWER_LATE_MAX) drawerLate.delete(drawerLate.keys().next().value);
});
async function agentDrawer(q, opts = {}) {
const pick = agentPick(q);
if (!pick || (opts.only && pick.org !== opts.only)) return '';
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(),
]);
const page = opts.page ?? null;
const html = (instRead, packs, pending) => drawerHtml(pick, { body, business, config, pending, instRead, packs });
// Each read the drawer waits on is raced against the page's reads (SP16 review), so neither the
// instances read nor a pack hire's packs read holds the page's paint.
await Promise.race([ir.p, page ?? ir.p]);
// SP14 (#1873): when a read answers, only the drawer repaints, from the reads it already has; the
// page's own reads are not made again. data-drawer-pending names the read it waits on: `<n>` for the
// instances read, `<n>p` for the packs read after it, so each repaint finds only its own drawer. A
// closed drawer repaints nothing. SP16: a read can answer after this HTML is returned and before the
// page that carries it is on screen; then the repaint waits in drawerLate, and afterPaint runs it.
// When the instances read answers, the state is drawn at once, and the template line, if its packs
// read is still open with nothing of use kept, says it is being read (or the kept refusal) and
// repaints when that read answers.
const packsStage = instRead => {
const pk = drawerPacks(org, instRead, pick.key);
if (pk?.p) drawerWhen(pk.p, `${ir.n}p`, id, v => () => html(instRead, v, false));
return { packs: pk?.value ?? null, pending: pk?.p ? `${ir.n}p` : false };
};
if (!ir.done) {
drawerWhen(ir.p, ir.n, id, v => { const s = packsStage(v); return () => html(v, s.packs, s.pending); });
return html(null, null, ir.n);
}
let pk = drawerPacks(org, ir.value, pick.key);
if (pk?.p) {
await Promise.race([pk.p, page ?? pk.p]);
pk = drawerPacks(org, ir.value, pick.key, false);
}
if (pk?.p) {
drawerWhen(pk.p, `${ir.n}p`, id, v => () => html(ir.value, v, false));
return html(ir.value, pk.value, `${ir.n}p`);
}
return html(ir.value, pk?.value ?? null, false);
}
function drawerHtml(pick, { body, business, config, pending, instRead, packs = null }) {
const { org, key, id } = pick;
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. A drawer
// can be pending with its instances read answered, while a pack hire's packs read is still open.
const reading = pending && !instRead;
const unknown = reading ? 'Reading state…' : !instRead?.inst ? `State not read: ${esc(instWhy(instRead || {}))}.` : '';
const a = unknown ? { org, key, name: key, level: 'org', keep: false, item: {}, s: arr(body?.sessions).find(x => x?.kind === 'role' && x.org === org && x.role === key) || null }
: agentRows([{ id: org, inst: instRead.inst, copies: instRead.copies }], body).find(r => r.key === key);
if (!a) return shell(key, `<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; Hired from below names its pack.
const item = a.item || {}, def = typeof item.definition === 'string' ? item.definition : '';
const hire = typeof item.hireDecision === 'string' ? item.hireDecision : /^org:hire-(.+)$/.exec(def)?.[1] || '';
const source = a.level === 'org'
? (isHired(item) ? `Hired${hire ? ` by hire decision <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)}` : ''}`;
// SP16: where a hired agent's role came from. A pack hire names its pack and, from the packs read,
// the template; no read names the template of a hire made outside a pack.
let hiredFrom = '';
if (a.level === 'org' && isHired(item)) {
if (packOf(item)) {
const { template: t, label } = packTemplate(item, key, packs);
hiredFrom = `Pack <strong>${esc(label || packOf(item))}</strong>, ${t ? `template <code>${esc(t)}</code> <span class="t2">as the installed pack names it</span>`
: `<span class="muted">template ${!packs && pending ? 'being read…' : packs?.err ? `not read: ${esc(instWhy(packs))}` : 'not named in the packs read'}</span>`}`;
} else hiredFrom = '<span class="muted">Template not recorded: no read names the template of a hire made outside a pack.</span>';
}
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>`);
// SP16: where no Message is offered, one line says why. The Console opens a conversation only in an
// Assistant pane, with a conversation agent; a role agent takes messages on the bus, which an
// organizations Console does not send.
else if (chat) acts.push(`<p class="note" data-drawer-nomessage>${reading ? 'No Message: its state is being read, so it is not known whether it holds a conversation.'
: unknown ? `No Message: its state was not read (${esc(instWhy(instRead || {}))}), so it is not known whether it holds a conversation.`
: a.level !== 'org' ? 'No Message: a copy is not messaged from here.'
: 'No Message: this Console messages only conversation agents, such as the Assistant.'}</p>`);
else if (change) acts.push(`<p class="note" data-drawer-nomessage>No Message: this Console does not send chat in ${esc(orgName)}.</p>`);
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>${reading ? 'Its state is being read. Stop is offered once it is read and the agent is running.'
: unknown || !runsRead(item) ? 'Its state was not read, so Stop is not offered.'
: a.level !== 'org' ? 'A copy is not stopped from here.'
: a.keep ? `${esc(a.name)} is one of ${esc(orgName)}’s protected agents, so it is not stopped from here.`
: '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)),
// A pack hire's pack is named once, in Hired from; the Role row says only that it was hired.
unknown ? '' : field('role', 'Role', `${esc(hiredFrom && packOf(item) ? 'Hired' : a.role)}`),
unknown ? '' : field('source', 'Source', source),
hiredFrom ? field('hired', 'Hired from', hiredFrom) : '',
field('state', 'State', unknown ? `<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>` : ''}`) : '',
// SP16: no read the Console makes carries the time of a role agent's last message or run. The agents
// read's time is when it took the role and `since` is when its present state began, so neither is shown.
// An agent holding a conversation has its messages in that thread's messages read, but that read pages
// from the oldest message, so its last message is a walk of every page away; the drawer does not make it.
field('activity', 'Last activity', `<span class="muted">${thread?.thread ? 'not shown: reading it means reading the whole conversation' : 'not recorded'}</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() {
for (const node of document.querySelectorAll('#bus-view [data-ws-drawer][data-drawer-pending]')) drawerLateRun(node);
const view = document.getElementById('bus-view'), d = view?.querySelector('[data-ws-drawer]');
const now = d?.dataset.wsDrawer || null, was = drawerShown;
drawerShown = now;
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] || '');
function setQuery(change, render = true) {
const q = queryOf();
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).
// 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) {
grouping = g === 'flat' ? 'flat' : 'org'; save(GROUPING, grouping); paint();
if (pathOf() === '/projects') document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
}
document.addEventListener('click', e => {
const page = e.target.closest?.('[data-ws-projects],[data-ws-inbox],[data-ws-agents]');
if (!page) return;
const st = e.target.closest('[data-ws-astate]');
if (st) { setQuery({ state: st.dataset.wsAstate || null }); return; }
const chip = e.target.closest('[data-ws-org]');
if (chip) {
const id = chip.dataset.wsOrg, now = listParam(queryOf(), 'org', x => ORG_ID.test(x)) || [];
const next = !id ? [] : now.includes(id) ? now.filter(x => x !== id) : [...now, id];
setQuery(page.hasAttribute('data-ws-inbox') ? { org: next, d: null } : { org: next });
return;
}
const sort = e.target.closest('[data-ws-sort]');
if (sort) {
const f = projectQuery(queryOf()), s = sort.dataset.wsSort;
setQuery(s === f.sort ? { sort: s, order: f.order === 'desc' ? 'asc' : 'desc' } : { sort: s, order: null });
return;
}
const kind = e.target.closest('[data-ws-type]');
if (kind) { setQuery({ type: kind.dataset.wsType || null, d: null }); return; }
const grp = e.target.closest('[data-ws-group]');
if (grp) { setGrouping(grp.dataset.wsGroup); return; }
const pick = e.target.closest('[data-ws-select]');
if (pick && !e.metaKey && !e.ctrlKey && !e.shiftKey && e.button === 0) { e.preventDefault(); setQuery({ d: pick.dataset.wsSelect }); }
});
// SP8: the Organizations tile counts the Dashboard's own table, so a plain click moves focus there.
document.addEventListener('click', e => {
const jump = e.target.closest?.('[data-ws-jump="orgs"]');
if (!jump || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;
const to = document.querySelector('[data-ws-orgs-h]');
if (to) { e.preventDefault(); to.focus(); }
});
document.addEventListener('change', e => {
if (e.target.matches?.('[data-ws-projects] [data-ws-status]')) setQuery({ status: e.target.value === 'active' ? null : e.target.value });
else if (e.target.matches?.('[data-ws-projects] [data-ws-state]')) setQuery({ state: e.target.value || null });
});
// Typing writes the hash at once, so a poll repaint keeps what was typed; the read waits a beat.
let typing;
document.addEventListener('input', e => {
if (!e.target.matches?.('[data-ws-projects] [data-ws-name]')) return;
setQuery({ name: e.target.value.slice(0, 200) || null }, false);
clearTimeout(typing); typing = setTimeout(() => document.dispatchEvent(new CustomEvent('mosaic-workspace-render')), 250);
});
// 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, 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();
})();