Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b6b39f080 | ||
|
|
2d7d7be5ca | ||
|
|
f73c761ad3 | ||
|
|
8b4a26dd2b | ||
|
|
11d2b43b3a | ||
|
|
8aefc0f7a9 | ||
|
|
9cff3255e6 | ||
|
|
d50d79cddd | ||
|
|
fb3bd16052 | ||
|
|
13615e12b9 | ||
|
|
bd29e756a5 | ||
|
|
6bd9be78ac | ||
|
|
3a84f46b6e | ||
|
|
208439814a | ||
|
|
7c6571768f | ||
|
|
3597e0daf6 | ||
|
|
3116f43e65 | ||
|
|
c66f1ec00c | ||
|
|
9400e0d94d | ||
|
|
a9912983e6 | ||
|
|
626321608f | ||
|
|
5f965cdb30 | ||
|
|
8296d33100 | ||
|
|
69ac78b97e | ||
|
|
a2a7df73df |
No files matched your search
@@ -14,6 +14,7 @@ html[data-organizations] .assist-open:disabled{color:var(--muted);cursor:not-all
|
||||
html[data-organizations] .assist [data-assist-unread]:empty,html[data-organizations] .assist [data-assist-note]:empty{display:none}
|
||||
html[data-organizations] .assist [data-assist-unread] .note{margin:0}
|
||||
html[data-organizations] .assist [data-assist-note]{margin:0;font-size:13px;color:var(--muted)}
|
||||
html[data-organizations] .assist [data-assist-note][data-refused]{color:var(--warning);font-weight:600}
|
||||
|
||||
html[data-organizations] .assist-new{border:1px solid var(--line);border-radius:var(--r);background:var(--surface);padding:12px 14px;display:grid;gap:10px}
|
||||
html[data-organizations] .assist-new[hidden]{display:none}
|
||||
@@ -35,12 +36,21 @@ html[data-organizations] .assist-panes{display:grid;grid-template-columns:repeat
|
||||
html[data-organizations] .assist-panes[hidden]{display:none}
|
||||
html[data-organizations] .assist-pane{display:flex;flex-direction:column;min-width:0;min-height:0;border:1px solid var(--line);border-radius:var(--r);background:var(--surface);overflow:hidden}
|
||||
html[data-organizations] .assist-pane-h{display:flex;align-items:center;gap:8px;padding:10px 12px;border-bottom:1px solid var(--line);box-shadow:inset 0 3px 0 var(--org,var(--line));min-width:0;flex-wrap:wrap}
|
||||
html[data-organizations] .assist-pane-h h2{margin:0;font-size:15px;font-weight:700;color:var(--strong,var(--text));overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1 1 120px}
|
||||
html[data-organizations] .assist-pane-h h2{margin:0;font-size:15px;font-weight:700;color:var(--strong,var(--text));overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:5em;flex:1 1 0}
|
||||
html[data-organizations] .assist-pane-h h2:focus{outline:none}
|
||||
html[data-organizations] .assist-chips{display:inline-flex;gap:6px;flex-wrap:wrap;min-width:0}
|
||||
html[data-organizations] .assist-chips{display:inline-flex;gap:6px;flex-wrap:wrap;min-width:0;order:1;flex:1 0 100%}
|
||||
html[data-organizations] .assist-chips:empty{display:none}
|
||||
/* SP7: a pane's tools (Full view, Messages, close) stay together on the title's row; the chips take the row under it.
|
||||
A pane too narrow for them wraps the tools, never pushes one past the pane's edge. */
|
||||
html[data-organizations] .assist-pane-tools{display:inline-flex;align-items:center;justify-content:flex-end;gap:2px;flex:0 1 auto;flex-wrap:wrap;max-width:100%;margin-left:auto}
|
||||
html[data-organizations] .assist-chips .ws-chip{max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
html[data-organizations] .assist .pane-tool{display:inline-grid;place-items:center;width:28px;height:28px;border-radius:var(--r);color:var(--muted);border:0;background:none;padding:0;min-height:0;cursor:pointer;flex:none}
|
||||
html[data-organizations] .assist .pane-tool:hover{background:var(--raised);color:var(--text)}
|
||||
/* SP7: each pane's own organization's Messages page, a text link among the pane's tools. */
|
||||
html[data-organizations] .assist .pane-tool.assist-msgs{width:auto;padding:0 8px;font-size:12px;font-weight:600;text-decoration:none}
|
||||
/* SP7: "Resume assistant" under a pane's composer is a small secondary control, not a second primary button. */
|
||||
html[data-organizations] .assist-body .btn.pane-resume{align-self:flex-start;min-height:0;padding:2px 8px;margin-top:4px;font-size:12px;font-weight:500;background:none;border-color:transparent;color:var(--muted)}
|
||||
html[data-organizations] .assist-body .btn.pane-resume:hover:not(:disabled){background:var(--raised);color:var(--text)}
|
||||
html[data-organizations] .assist .pane-tool svg.i{width:15px;height:15px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
|
||||
html[data-organizations] .assist-line{margin:0;padding:6px 12px;border-bottom:1px solid var(--line);font-size:13px;color:var(--text);background:color-mix(in srgb,var(--warn,#b7791f) 12%,var(--surface))}
|
||||
html[data-organizations] .assist-line[hidden]{display:none}
|
||||
|
||||
@@ -7,6 +7,11 @@
|
||||
// The open set, its order and the phone's shown pane live in the address
|
||||
// (#/assistant?open=<org>:<thread>,…&show=<org>:<thread>), checked before use and rewritten with
|
||||
// replaceState. A bare #/assistant opens the set this browser had last.
|
||||
//
|
||||
// SP7: a plain click on a thread link anywhere in the Console (a project's conversation rows, the
|
||||
// sidebar's thread links) opens that thread as a pane here, added to the open set; #/assistant?add=<org>:<thread>
|
||||
// carries it across the page change. A link marked data-full-view (a pane's Full view, a requirement's
|
||||
// "Open conversation") and a per-organization chat address typed or pasted open that organization's own chat view.
|
||||
(() => {
|
||||
'use strict';
|
||||
if (!document.documentElement.hasAttribute('data-organizations')) return;
|
||||
@@ -102,7 +107,6 @@
|
||||
<div class="assist-tools">
|
||||
<label class="ws-sr" for="assist-open">Open thread</label>
|
||||
<select id="assist-open" class="assist-open" data-assist-open><option value="">Open thread…</option></select>
|
||||
<a class="ws-btn" data-assist-messages href="#/messages">Messages</a>
|
||||
</div>
|
||||
</div>
|
||||
<div data-assist-unread></div>
|
||||
@@ -128,7 +132,11 @@
|
||||
<div class="assist-pane-h">
|
||||
<h2 id="assist-p${n}-title" data-assist-title>Reading…</h2>
|
||||
<span class="assist-chips" data-assist-chips></span>
|
||||
<button type="button" class="pane-tool" data-assist-close aria-label="Close thread">${CLOSE}</button>
|
||||
<span class="assist-pane-tools">
|
||||
<a class="pane-tool assist-msgs" data-assist-pane-full data-full-view href="#/orgs/${enc(p.org)}/projects/threads/${enc(p.id)}">Full view</a>
|
||||
<a class="pane-tool assist-msgs" data-assist-pane-messages href="#/orgs/${enc(p.org)}/messages" aria-label="Messages in ${esc(p.org)}">Messages</a>
|
||||
<button type="button" class="pane-tool" data-assist-close aria-label="Close thread">${CLOSE}</button>
|
||||
</span>
|
||||
</div>
|
||||
<p class="assist-line" data-assist-line role="status" hidden></p>
|
||||
<div class="assist-body" data-assist-body></div>
|
||||
@@ -136,7 +144,7 @@
|
||||
}
|
||||
const els = p => ({
|
||||
title: p.el.querySelector('[data-assist-title]'), chips: p.el.querySelector('[data-assist-chips]'),
|
||||
close: p.el.querySelector('[data-assist-close]'), line: p.el.querySelector('[data-assist-line]'), body: p.el.querySelector('[data-assist-body]'),
|
||||
close: p.el.querySelector('[data-assist-close]'), full: p.el.querySelector('[data-assist-pane-full]'), messages: p.el.querySelector('[data-assist-pane-messages]'), line: p.el.querySelector('[data-assist-line]'), body: p.el.querySelector('[data-assist-body]'),
|
||||
});
|
||||
|
||||
// The picker: every organization on the list, its threads, and "New thread in …" where this
|
||||
@@ -183,22 +191,21 @@
|
||||
if (paused()) { mounted.timer = setTimeout(tick, POLL); return; }
|
||||
void draw();
|
||||
}
|
||||
// The line under the lead: how many panes are open, or why a thread was not opened (drawn as a warning).
|
||||
function paintNote() {
|
||||
const el = mounted.root.querySelector('[data-assist-note]');
|
||||
setText(el, mounted.notice || (mounted.panes.length ? `${mounted.panes.length} open, up to ${MAX}` : ''));
|
||||
el?.toggleAttribute('data-refused', !!mounted.notice);
|
||||
}
|
||||
function paintTop() {
|
||||
const { root, list, o, panes } = mounted;
|
||||
setHtml(root.querySelector('[data-assist-unread]'), list ? ws().unreadNote(o, [], 'assistant') : '<p class="note ws-unread-note">The organization list could not be read. Open panes only read.</p>');
|
||||
setText(root.querySelector('[data-assist-note]'), panes.length ? `${panes.length} open, up to ${MAX}` : '');
|
||||
paintNote();
|
||||
const pick = root.querySelector('[data-assist-open]');
|
||||
if (document.activeElement !== pick) { setHtml(pick, pickerHtml(list, mounted.got)); pick.value = ''; }
|
||||
const full = panes.length >= MAX;
|
||||
pick.disabled = full;
|
||||
pick.title = full ? `${MAX} threads are open. Close one to open another.` : '';
|
||||
const here = window.MosaicOrg?.id, messages = root.querySelector('[data-assist-messages]');
|
||||
messages.hidden = !here;
|
||||
if (here) {
|
||||
const href = `#/orgs/${enc(here)}/messages`;
|
||||
if (messages.getAttribute('href') !== href) messages.setAttribute('href', href);
|
||||
setText(messages, `Messages in ${window.MosaicOrg.label || here}`);
|
||||
}
|
||||
root.querySelector('[data-assist-empty]').hidden = panes.length > 0;
|
||||
}
|
||||
function drawPane(p) {
|
||||
@@ -211,6 +218,8 @@
|
||||
p.title = title;
|
||||
setText(e.title, title);
|
||||
e.close.setAttribute('aria-label', `Close ${title}, ${name}`);
|
||||
e.full.setAttribute('aria-label', `Full view of ${title}, ${name}`);
|
||||
e.messages.setAttribute('aria-label', `Messages in ${name}`);
|
||||
if (org) p.el.setAttribute('style', ws().colours(org)); else p.el.removeAttribute('style');
|
||||
const project = thread && i.projects?.find(x => x.id === thread.project)?.name;
|
||||
setHtml(e.chips, `${ws().orgChip(o, p.org)}${ws().projChip(project || '')}`);
|
||||
@@ -251,7 +260,8 @@
|
||||
if (seq !== p.seq || p.chat !== chat || !p.el.isConnected) return;
|
||||
const field = p.draft ? e.body.querySelector('form textarea') : null;
|
||||
if (p.draft && !field) {
|
||||
// The thread reads but offers no composer: the held message stays visible here, never silently held.
|
||||
// The thread reads but this render drew no composer (it cannot send now): the held message is
|
||||
// quoted in the pane's status line until a composer is back to take it.
|
||||
p.held = true; const text = withHeld(); setText(e.line, text); e.line.hidden = false;
|
||||
return;
|
||||
}
|
||||
@@ -289,9 +299,34 @@
|
||||
}
|
||||
|
||||
// ---------- panes ----------
|
||||
// SP11: a pane's unsent message is kept per thread for the life of the browser tab, so leaving the
|
||||
// Assistant page (a Full view link included) and coming back puts it in the composer again.
|
||||
// sessionStorage can be missing or refuse a write; the Map still keeps it while the page lives.
|
||||
const DRAFTS = 'mosaic-assistant-drafts';
|
||||
const kept = (() => {
|
||||
try {
|
||||
const v = JSON.parse(sessionStorage.getItem(DRAFTS) || 'null');
|
||||
return new Map(v && typeof v === 'object' && !Array.isArray(v) ? Object.entries(v).filter(([k, t]) => typeof t === 'string' && t.trim() && parse(`open=${k}`).keys[0] === k) : []);
|
||||
} catch { return new Map(); }
|
||||
})();
|
||||
const saveKept = () => { try { if (kept.size) sessionStorage.setItem(DRAFTS, JSON.stringify(Object.fromEntries(kept))); else sessionStorage.removeItem(DRAFTS); } catch { /* the Map still holds it */ } };
|
||||
const typedIn = p => p.chat?.draft?.() || p.draft || p.el?.querySelector('form textarea')?.value || '';
|
||||
// Signed out, by an expired session or by the Sign out form: the kept drafts go and nothing is kept
|
||||
// again, not even by the pagehide the form's own submit causes, so the next person to sign in on
|
||||
// this tab never sees text typed before.
|
||||
let draftsOff = false;
|
||||
function keep(p) { if (draftsOff) return; const text = typedIn(p); if (text.trim()) kept.set(p.key, text); else kept.delete(p.key); saveKept(); }
|
||||
function drop(p) { if (kept.delete(p.key)) saveKept(); }
|
||||
window.addEventListener('pagehide', () => { if (mounted) for (const p of mounted.panes) keep(p); });
|
||||
function forgetDrafts() {
|
||||
draftsOff = true; kept.clear(); saveKept();
|
||||
if (mounted) for (const p of mounted.panes) { p.draft = ''; const t = p.el?.querySelector('form textarea'); if (t) t.value = ''; }
|
||||
}
|
||||
document.addEventListener('mosaic-signed-out', forgetDrafts);
|
||||
document.addEventListener('submit', e => { if (e.target?.id === 'sign-out') forgetDrafts(); }, true);
|
||||
function makePane(key) {
|
||||
const { org, id } = split(key);
|
||||
const p = { key, org, id, n: ++paneSeq, el: null, chat: null, first: true, title: null, draft: '', held: false, seq: 0 };
|
||||
const p = { key, org, id, n: ++paneSeq, el: null, chat: null, first: true, title: null, draft: kept.get(key) || '', held: false, seq: 0 };
|
||||
const box = mounted.root.querySelector('[data-assist-panes]');
|
||||
box.insertAdjacentHTML('beforeend', paneShell(p));
|
||||
p.el = box.lastElementChild;
|
||||
@@ -308,10 +343,58 @@
|
||||
if (mounted.got) { paintTop(); drawPane(p); paintTabs(); layout(); }
|
||||
if (focus) els(p).title.setAttribute('tabindex', '-1'), els(p).title.focus({ preventScroll: true });
|
||||
}
|
||||
// SP7: a thread opened from a link takes a free slot or, with all three taken, the place of the
|
||||
// first pane that holds no unsent message. When every pane holds one, nothing is replaced.
|
||||
// SP11: a pane whose send is in flight, or whose sent message the conversation does not show yet,
|
||||
// is held too, until its receipt is in.
|
||||
const holds = p => !!p.draft.trim() || !!p.chat?.hasDraft() || !!p.chat?.busy?.();
|
||||
function place(key) {
|
||||
const had = mounted.panes.find(p => p.key === key);
|
||||
if (had) return had;
|
||||
if (mounted.panes.length < MAX) { const p = makePane(key); mounted.panes.push(p); return p; }
|
||||
const old = mounted.panes.find(p => !holds(p));
|
||||
if (!old) return null;
|
||||
const p = makePane(key);
|
||||
drop(old); old.chat?.dispose(); old.chat = null; old.el.replaceWith(p.el);
|
||||
mounted.panes[mounted.panes.indexOf(old)] = p;
|
||||
return p;
|
||||
}
|
||||
const REFUSED = `That thread was not opened: all ${MAX} panes hold an unsent message or a message waiting to show. Send or clear one, wait for a sent message to show, or close a pane, then open the thread again.`;
|
||||
function add(key) {
|
||||
if (!mounted) return false;
|
||||
const p = place(key);
|
||||
if (!p) { mounted.notice = REFUSED; paintNote(); return false; }
|
||||
mounted.notice = ''; mounted.show = key;
|
||||
writeUrl();
|
||||
if (mounted.got) { paintTop(); drawPane(p); paintTabs(); layout(); }
|
||||
els(p).title.setAttribute('tabindex', '-1'); els(p).title.focus({ preventScroll: true });
|
||||
return true;
|
||||
}
|
||||
const addOf = query => { const v = new URLSearchParams(query || '').get('add'); return v ? parse(new URLSearchParams({ open: v }).toString()).keys[0] || null : null; };
|
||||
const THREAD_LINK = /^#\/(?:orgs\/([^/?#]+)\/)?(?:projects|chat)\/threads\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
|
||||
document.addEventListener('click', e => {
|
||||
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
||||
const a = e.target.closest?.('a[href]');
|
||||
// A link marked data-full-view (a pane's Full view, a requirement's "Open conversation") goes to the
|
||||
// organization's own thread view, which has Request details, sessions and sharing.
|
||||
if (!a || a.hasAttribute('download') || a.hasAttribute('data-full-view') || (a.target && a.target !== '_self')) return;
|
||||
const m = THREAD_LINK.exec(a.getAttribute('href') || '');
|
||||
const org = m && (m[1] || window.MosaicOrg?.id);
|
||||
if (!m || !org || !ORG.test(org)) return;
|
||||
e.preventDefault();
|
||||
const key = `${org}:${m[2].toLowerCase()}`;
|
||||
if (mounted && /^#\/assistant(?:\?|$)/.test(location.hash)) add(key);
|
||||
else location.hash = `#/assistant?add=${key}`;
|
||||
});
|
||||
|
||||
// SP11: closing a pane that holds unsent text asks first; a close drops the kept text.
|
||||
function closePane(p) {
|
||||
if (!mounted || !p) return;
|
||||
const at = mounted.panes.indexOf(p);
|
||||
if (at < 0) return;
|
||||
if (typedIn(p).trim() && !window.confirm(`Close ${p.title || 'this thread'}? Its unsent message is lost.`)) return;
|
||||
drop(p);
|
||||
mounted.notice = '';
|
||||
p.chat?.dispose(); p.chat = null; p.el.remove();
|
||||
mounted.panes.splice(at, 1);
|
||||
const next = mounted.panes[Math.min(at, mounted.panes.length - 1)];
|
||||
@@ -387,7 +470,7 @@
|
||||
pick.value = '';
|
||||
if (value.startsWith('new:')) { void openForm(value.slice(4)); return; }
|
||||
const want = parse(`open=${value}`).keys[0];
|
||||
if (want) addPane(want);
|
||||
if (want) { mounted.notice = ''; addPane(want); }
|
||||
});
|
||||
root.addEventListener('click', e => {
|
||||
if (!mounted) return;
|
||||
@@ -411,15 +494,19 @@
|
||||
++mountGen;
|
||||
container.innerHTML = frame();
|
||||
const root = container.querySelector('[data-assistant]');
|
||||
mounted = { root, panes: [], show: null, turn: 0, timer: null, list: null, got: null, o: null, form: null, formTurn: 0 };
|
||||
mounted = { root, panes: [], show: null, turn: 0, timer: null, list: null, got: null, o: null, form: null, formTurn: 0, notice: '' };
|
||||
bind(root);
|
||||
window.addEventListener('resize', fit);
|
||||
document.title = 'Assistant · Mosaic Console';
|
||||
if (navigated) root.querySelector('h1').focus({ preventScroll: true });
|
||||
let want = parse(query);
|
||||
if (!want.named) want = parse(`open=${load() || ''}`);
|
||||
for (const key of want.keys) mounted.panes.push(makePane(key));
|
||||
mounted.show = want.show || want.keys[0] || null;
|
||||
// A thread link followed from another page: a fresh set holds no unsent message, so it always lands.
|
||||
const extra = addOf(query), added = extra && place(extra);
|
||||
if (added) mounted.show = extra;
|
||||
if (added) { els(added).title.setAttribute('tabindex', '-1'); els(added).title.focus({ preventScroll: true }); }
|
||||
else if (navigated) root.querySelector('h1').focus({ preventScroll: true });
|
||||
writeUrl(); paintTabs(); layout();
|
||||
root.querySelector('[data-assist-empty]').hidden = mounted.panes.length > 0;
|
||||
await draw({ navigated: true });
|
||||
@@ -427,7 +514,7 @@
|
||||
function unmount() {
|
||||
if (!mounted) return;
|
||||
clearTimeout(mounted.timer);
|
||||
for (const p of mounted.panes) p.chat?.dispose();
|
||||
for (const p of mounted.panes) { keep(p); p.chat?.dispose(); }
|
||||
window.removeEventListener('resize', fit);
|
||||
mounted = null; mountGen++;
|
||||
}
|
||||
@@ -438,7 +525,7 @@
|
||||
if (typeof query === 'string') {
|
||||
const want = parse(query);
|
||||
if (want.named && want.keys.join(',') !== mounted.panes.map(p => p.key).join(',')) {
|
||||
for (const p of [...mounted.panes]) if (!want.keys.includes(p.key)) { p.chat?.dispose(); p.el.remove(); }
|
||||
for (const p of [...mounted.panes]) if (!want.keys.includes(p.key)) { keep(p); p.chat?.dispose(); p.el.remove(); }
|
||||
const kept = new Map(mounted.panes.map(p => [p.key, p]));
|
||||
mounted.panes = want.keys.map(k => kept.get(k) || makePane(k));
|
||||
const box = mounted.root.querySelector('[data-assist-panes]');
|
||||
@@ -446,6 +533,8 @@
|
||||
mounted.show = want.show || want.keys[0] || null;
|
||||
writeUrl();
|
||||
}
|
||||
const extra = addOf(query);
|
||||
if (extra) add(extra);
|
||||
}
|
||||
infos.clear();
|
||||
void draw({ fresh: true });
|
||||
@@ -454,5 +543,5 @@
|
||||
// A write that changed an organization reads it again.
|
||||
document.addEventListener('mosaic-org-changed', e => { if (mounted && mounted.panes.some(p => p.org === e.detail?.org)) { infos.delete(e.detail.org); void draw(); } });
|
||||
|
||||
window.MosaicAssistant = Object.freeze({ mount, unmount, refresh, hasDraft });
|
||||
window.MosaicAssistant = Object.freeze({ mount, unmount, refresh, hasDraft, add });
|
||||
})();
|
||||
@@ -184,8 +184,12 @@
|
||||
draw();
|
||||
// SP1: every page inside an organization says which one, after the dashboard: Dashboard / Acme / ...
|
||||
const box = $('breadcrumbs'), org = /^#\/orgs\/[^/?]+/.test(location.hash) ? window.MosaicOrg : null;
|
||||
if (!box || !org?.id || box.querySelector('[data-crumb-org]') || /^#\/orgs\/[^/?]+\/organization(?:[/?]|$)/.test(location.hash)) return;
|
||||
box.insertAdjacentHTML('afterbegin', `<a href="#/dashboard">Dashboard</a><span aria-hidden="true">/</span><a href="#/orgs/${encodeURIComponent(org.id)}/organization" data-crumb-org>${escape(org.label)}</a><span aria-hidden="true">/</span>`);
|
||||
if (box && org?.id && !box.querySelector('[data-crumb-org]') && !/^#\/orgs\/[^/?]+\/organization(?:[/?]|$)/.test(location.hash)) box.insertAdjacentHTML('afterbegin', `<a href="#/dashboard">Dashboard</a><span aria-hidden="true">/</span><a href="#/orgs/${encodeURIComponent(org.id)}/organization" data-crumb-org>${escape(org.label)}</a><span aria-hidden="true">/</span>`);
|
||||
// SP7: a trail with nothing above the page only repeats the page's heading, so the heading names it once.
|
||||
if (!box) return;
|
||||
const heading = [...$('main').querySelectorAll('h1')].find(h => h.getClientRects().length)?.textContent.trim();
|
||||
const echo = !box.querySelector('a') && !!heading && box.textContent.trim() === heading;
|
||||
if (box.hidden !== echo) box.hidden = echo;
|
||||
}
|
||||
window.MosaicBreadcrumbs = breadcrumbs;
|
||||
function draw() {
|
||||
@@ -197,7 +201,7 @@
|
||||
if (parts[0] === 'board' && /^#\/orgs\//.test(location.hash)) { box.innerHTML = '<span aria-current="page">Control board</span>'; return; }
|
||||
if (!parts.length || parts[0] === 'board' || parts[0] === 'dashboard') { box.innerHTML = '<span aria-current="page">Dashboard</span>'; return; }
|
||||
if (parts[0] === 'organization') { const h = $('bus-view').querySelector('[data-org-dashboard] h1')?.textContent?.trim(); box.innerHTML = `<a href="#/dashboard">Dashboard</a>${h ? `<span aria-hidden="true">/</span><span aria-current="page">${escape(h)}</span>` : ''}`; return; }
|
||||
const names = {projects:'Projects',chat:'Projects',inbox:'Inbox',messages:'Messages',assistant:'Assistant',tasks:'Tasks',agents:'Agents',queue:'Queue',business:'Business',docs:'Docs',settings:'Settings'};
|
||||
const names = {projects:'Projects',chat:'Projects',inbox:'Inbox',messages:'Messages',assistant:'Assistant',tasks:'Tasks',agents:'Agents',workflows:'Workflows',queue:'Queue',business:'Business',docs:'Docs',settings:'Settings'};
|
||||
if (parts[0] === 'settings' && parts[1] === 'business' && $('bus-view').querySelector('#settings-page-title')?.textContent.trim() === 'Business') { box.innerHTML = '<a href="#/settings">Settings</a><span aria-hidden="true">/</span><span aria-current="page">Business</span>'; return; }
|
||||
const name = names[parts[0]] || 'Dashboard', heading = $('bus-view').querySelector('h1')?.textContent?.trim();
|
||||
const project = $('bus-view').querySelector('.chat-conversation > p:first-child a, .chat-room > p:first-child a');
|
||||
|
||||
@@ -208,7 +208,7 @@
|
||||
out.groupAs = m?.from_role === 'human' ? 'request' : m?.decision ? 'decision' : 'other';
|
||||
} else if (r.table === 'decisions') {
|
||||
out.kind = 'decision.raised'; out.decision = r.id; out.actor = { role: r.raised_by_role, run: r.raised_by_run };
|
||||
out.text = `Raised a ${r.class} decision for ${r.route_to}: ${String(r.question).split('\n')[0]}`;
|
||||
out.text = `Raised a ${String(classWord(r.class)).toLowerCase()} decision for ${r.route_to}: ${String(r.question).split('\n')[0]}`;
|
||||
} else if (r.table === 'decision_events') {
|
||||
// The human answers from the CLI (via cli) or, since row 252 (#1753), a grant request from the
|
||||
// signed-in Console (via console); every other row is the broker's.
|
||||
@@ -243,7 +243,9 @@
|
||||
const badge = (text, kind = 'muted') => `<span class="badge badge-${kind}">${txt(text)}</span>`;
|
||||
// Class chip: the decision class, the action in mono. BLOCKING is its own chip (CSS capitalises it; the text stays lowercase).
|
||||
const CLASSES = ['routine', 'within-role', 'cross-role', 'gated'];
|
||||
const chip = (cls, action) => `<span class="tag${CLASSES.includes(cls) ? ` tag-${cls}` : ''}">${txt(cls)} · <code>${txt(action)}</code></span>`;
|
||||
// SP11: the class in the Inbox's words, from workspace.js's map.
|
||||
const classWord = cls => window.MosaicWorkspace?.classWord?.(cls) ?? cls;
|
||||
const chip = (cls, action) => `<span class="tag${CLASSES.includes(cls) ? ` tag-${cls}` : ''}">${txt(classWord(cls))} · <code>${txt(action)}</code></span>`;
|
||||
const blockChip = text => `<span class="tag tag-block">${txt(text)}</span>`;
|
||||
// An empty state says what would appear and where it comes from.
|
||||
const empty = (what, from) => `<div class="empty"><b>${what}</b>${from ? `<p>${from}</p>` : ''}</div>`;
|
||||
@@ -354,7 +356,7 @@
|
||||
function repliesHtml() {
|
||||
if (replies === null) return '<p class="small warn">The replies to it could not be read. Read again to retry; <code>mosaic inbox</code> in a terminal lists them.</p>';
|
||||
if (!replies.length) return '<p class="small muted">No reply yet. One shows here when the role answers, as the page refreshes.</p>';
|
||||
return `<h3 class="small">Replies <span class="count">${replies.length}</span></h3><ol class="s1-plain s1-replies">${replies.map(m => `<li><p class="small muted">${txt(m.from_role)} ${when(m.at)} · ${txt(m.class)} · <a href="#/trail/message/${enc(m.id)}">trail</a></p><p class="s1-q">${txt(m.body)}</p></li>`).join('')}</ol>${replies.length >= REPLIES ? `<p class="small muted">The first ${REPLIES} replies show here.</p>` : ''}`;
|
||||
return `<h3 class="small">Replies <span class="count">${replies.length}</span></h3><ol class="s1-plain s1-replies">${replies.map(m => `<li><p class="small muted">${txt(m.from_role)} ${when(m.at)} · ${txt(classWord(m.class))} · <a href="#/trail/message/${enc(m.id)}">trail</a></p><p class="s1-q">${txt(m.body)}</p></li>`).join('')}</ol>${replies.length >= REPLIES ? `<p class="small muted">The first ${REPLIES} replies show here.</p>` : ''}`;
|
||||
}
|
||||
const draft = { to: '', body: '' };
|
||||
function composerHtml() {
|
||||
@@ -707,7 +709,7 @@
|
||||
if (after !== null && !SAFE.test(after)) return notFound('The message cursor is not a message id.');
|
||||
const page = await get('messages', after === null ? undefined : after);
|
||||
const body = page.rows.length ? `<ul id="message-list" class="waiting s1-replies">${page.rows.map(m =>
|
||||
`<li class="wait-item"><p class="small muted">${txt(m.from_role)} · ${txt(m.class)} · ${when(m.at)} · ${m.read ? 'Read' : 'Unread'} · <a href="#/trail/message/${enc(m.id)}">trail</a></p><p class="s1-message">${messageText(m)}</p></li>`).join('')}</ul>`
|
||||
`<li class="wait-item"><p class="small muted">${txt(m.from_role)} · ${txt(classWord(m.class))} · ${when(m.at)} · ${m.read ? 'Read' : 'Unread'} · <a href="#/trail/message/${enc(m.id)}">trail</a></p><p class="s1-message">${messageText(m)}</p></li>`).join('')}</ul>`
|
||||
: empty('No messages to you.', 'Messages appear here as the bus is read.');
|
||||
return `${head('Messages', `${readNote(get)} Every message to you, newest first. Reading here marks nothing read.`)}
|
||||
<p class="small muted">${page.total} messages · ${page.unread} unread</p>${body}
|
||||
@@ -1689,7 +1691,9 @@
|
||||
if (parts.includes(null)) return notFound();
|
||||
const [a, b, c] = parts, n = parts.length;
|
||||
// #1873 SP1: `#/dashboard` is the system dashboard, every organization on one page.
|
||||
if ((n === 0 || (a === 'dashboard' && n === 1)) && window.MosaicOrg) return window.MosaicWorkspace.home();
|
||||
// SP11: with no organization it is still the Dashboard (it says so and offers New organization);
|
||||
// #/ is then the Console's own board.
|
||||
if ((n === 0 && window.MosaicOrg) || (a === 'dashboard' && n === 1 && window.MosaicWorkspace)) return window.MosaicWorkspace.home();
|
||||
if (a === 'projects' && n === 1 && window.MosaicOrg) return window.MosaicWorkspace.projectsPage(q);
|
||||
if (a === 'organization' && n === 1 && window.MosaicOrg) return window.MosaicWorkspace.dashboard();
|
||||
// SP3: #/inbox is every organization's items; #/orgs/<id>/inbox is that list for one, with its hire form.
|
||||
@@ -1717,6 +1721,12 @@
|
||||
return agentsView(get, q, org);
|
||||
}
|
||||
if (a === 'agents' && n === 1) return agentsView(get);
|
||||
// SP9 (#1873): #/orgs/<id>/workflows lists an organization's workflows; #/orgs/<id>/workflows/<name> draws one, read only.
|
||||
if (a === 'workflows' && (n === 1 || n === 2) && window.MosaicOrg && window.MosaicWorkflows?.page) {
|
||||
const scope = /^#\/orgs\/([^/?]+)/.exec(location.hash)?.[1];
|
||||
let org = null; try { org = scope ? decodeURIComponent(scope) : window.MosaicOrg.id; } catch { return notFound(); }
|
||||
return org ? window.MosaicWorkflows.page(org, n === 2 ? b : null, q) : notFound();
|
||||
}
|
||||
if (a === 'queue' && n === 1) return queueView(get, q);
|
||||
if (a === 'queue' && n === 2) return /^[1-9]\d{0,5}$/.test(b) ? queueRowView(get, b) : notFound(`${txt(b)} is not a queue row id.`);
|
||||
if (a === 'settings' && (n === 1 || (n === 2 && [...settingsPages.map(p=>p[0]),'names'].includes(b)))) return settingsView(get, b || 'appearance');
|
||||
@@ -1731,7 +1741,7 @@
|
||||
const paused = () => $('pause')?.getAttribute('aria-pressed') === 'true';
|
||||
// A file open in the editor is never refreshed from under its draft; Reload is the person's to press.
|
||||
// The cross-organization pages (U3) poll at the workspace read's pollMs.
|
||||
const wsPage = path => !!window.MosaicOrg && (path === '/' || path === '' || path === '/dashboard' || path === '/projects' || path === '/inbox' || path === '/agents' || path === '/tasks');
|
||||
const wsPage = path => (path === '/dashboard' && !!window.MosaicWorkspace) || !!window.MosaicOrg && (path === '/' || path === '' || path === '/dashboard' || path === '/projects' || path === '/inbox' || path === '/agents' || path === '/tasks' || /^\/workflows(\/[^/]+)?$/.test(path));
|
||||
function schedule() { clearTimeout(timer); if (!paused() && !out() && !routeOf().startsWith('/docs/')) timer = setTimeout(() => render(false), wsPage(routeOf().split('?')[0]) ? window.MosaicWorkspace?.pollMs || 10000 : 10000); }
|
||||
// Keep focus, open <details> and the copy status across a refresh of the same page.
|
||||
// In the send form, the focused field and its caret too (its values come from `draft`).
|
||||
|
||||
@@ -90,6 +90,16 @@
|
||||
signedOut = true; forget();
|
||||
document.dispatchEvent(new Event('mosaic-signed-out'));
|
||||
}
|
||||
// SP11: whether the thread's agent runs no process, from the bus instances read the Agents page uses.
|
||||
// true: paused or stopped; false: running; null: the read failed or does not list the agent.
|
||||
async function agentIdle(instance, signal) {
|
||||
try {
|
||||
const res = await fetch(pane ? `/api/orgs/${encodeURIComponent(env.org)}/bus/instances` : '/api/bus/instances', { cache: 'no-store', redirect: 'manual', signal });
|
||||
if (!res.ok || res.type === 'opaqueredirect') return null;
|
||||
const item = (await res.json())?.rows?.[0]?.instances?.[instance];
|
||||
return item && typeof item === 'object' && Array.isArray(item.running) ? item.running.length === 0 : null;
|
||||
} catch (err) { if (err.name === 'AbortError') throw err; return null; }
|
||||
}
|
||||
async function request(path, value, signal) {
|
||||
if (out()) throw new ChatError('signed-out');
|
||||
let res;
|
||||
@@ -317,8 +327,10 @@
|
||||
const messages = s.rows.map((m, i) => `<li class="${m.from_role === 'human' ? 'chat-message-human' : 'chat-message-agent'}" data-message="${esc(m.id)}"><div class="chat-message-meta"><span class="chat-avatar" aria-hidden="true">${txt(String(m.from_role || '?').slice(0, 1).toUpperCase())}</span><strong>${txt(m.from_role === 'human' ? 'You' : m.from_role)}</strong> ${stamp(m.at)}</div>${messageBody(m)}${!redesigned && withRequest.has(m.id) ? mount(m) : ''}</li>${redesigned ? (mountsAfter.get(i) || []).map(origin => `<li class="project-request-item">${mount(origin)}</li>`).join('') : ''}`).join('');
|
||||
const frame = pane ? '' : redesigned ? window.MosaicProjects.header(project, 'conversations', current.threads, t.name, true) : heading(t.name);
|
||||
// A pane leaves out the details: sessions and sharing are unavailable on an organization Console.
|
||||
const resume = threadWrites() ? `<button class="btn" type="button" id="chat-resume"${disabledSession(s.pending || current.channelDisabled)}>Resume assistant</button>` : '';
|
||||
const details = pane ? `<p class="muted small">Reading never wakes the assistant. An accepted message is not an answer.</p>` : redesigned ? `<dialog class="chat-details project-dialog" id="project-conversation-dialog" aria-labelledby="project-conversation-title"><h2 id="project-conversation-title" tabindex="-1">Conversation details</h2><button class="btn" type="button" data-dialog-close>Close</button>${sessionControls(t)}${sharing(t)}<p>Reading never wakes the assistant. An accepted message is not an answer.</p>${threadWrites() ? `<button class="btn" type="button" id="chat-resume"${disabledSession(s.pending || current.channelDisabled)}>Resume assistant</button>` : ''}</dialog>` : `<details class="chat-details"><summary id="chat-details-toggle">Conversation details</summary>${sessionControls(t)}${sharing(t)}</details><p class="muted">Reading never wakes the assistant. An accepted message is not an answer.</p>${threadWrites() ? `<button class="btn" type="button" id="chat-resume"${disabledSession(s.pending || current.channelDisabled)}>Resume assistant</button>` : ''}`;
|
||||
// SP11: Resume shows unless the instances read says the agent is running.
|
||||
const resumable = threadWrites() && current.agentIdle !== false;
|
||||
const resume = resumable ? `<button class="btn${pane ? ' pane-resume' : ''}" type="button" id="chat-resume"${disabledSession(s.pending || current.channelDisabled)}>Resume assistant</button>` : '';
|
||||
const details = pane ? `<p class="muted small">Reading never wakes the assistant. An accepted message is not an answer.</p>` : redesigned ? `<dialog class="chat-details project-dialog" id="project-conversation-dialog" aria-labelledby="project-conversation-title"><h2 id="project-conversation-title" tabindex="-1">Conversation details</h2><button class="btn" type="button" data-dialog-close>Close</button>${sessionControls(t)}${sharing(t)}<p>Reading never wakes the assistant. An accepted message is not an answer.</p>${resumable ? `<button class="btn" type="button" id="chat-resume"${disabledSession(s.pending || current.channelDisabled)}>Resume assistant</button>` : ''}</dialog>` : `<details class="chat-details"><summary id="chat-details-toggle">Conversation details</summary>${sessionControls(t)}${sharing(t)}</details><p class="muted">Reading never wakes the assistant. An accepted message is not an answer.</p>${resumable ? `<button class="btn" type="button" id="chat-resume"${disabledSession(s.pending || current.channelDisabled)}>Resume assistant</button>` : ''}`;
|
||||
return `<section class="chat-conversation${redesigned ? ' project-chat' : ''}" data-project="${esc(t.project)}" data-thread="${esc(t.id)}" data-session="${esc(current.session)}">${pane ? '' : `<p>${link('projects', t.project, current.projects.find(p => p.id === t.project)?.name ?? 'Project')} / ${txt(t.instance)}</p>`}${frame}${libraryLine(libraryOf(current, t))}${details}${redesigned ? '<p class="small muted" data-conversation-request-status></p>' : ''}<ol class="chat-log" tabindex="0" aria-label="Thread conversation">${messages || (current.readFailed ? '<li class="muted">Messages unavailable.</li>' : '<li class="muted">No messages yet.</li>')}</ol><div class="chat-paging">${current.readFailed ? '<button type="button" class="btn" data-chat-retry>Read again</button>' : s.more ? '<p>Showing earlier history. Read forward to reach the current conversation.</p><button class="btn" type="button" id="chat-next">Read next messages</button>' : '<p class="muted">Caught up to the last read.</p>'}<button class="btn" type="button" id="chat-new"${s.follow ? ' hidden' : ''}>New messages — go to end</button></div>${threadWrites() ? `<form id="chat-send-form"><label for="chat-body">Message ${txt(t.instance)}</label><textarea id="chat-body" rows="4" placeholder="${redesigned ? `Message ${esc(t.instance)}` : 'Write a message…'}"${disabledSession(s.pending)}>${esc(s.draft)}</textarea><p class="chat-audience">To: ${redesigned ? `<span class="room-chip" aria-label="Recipient ${esc(t.instance)}">${txt(t.instance)}</span>` : `${txt(t.instance)} · Private conversation`}</p>${redesigned ? '<p class="project-composer-hint">Enter adds a new line.</p>' : ''}<button class="btn primary" type="submit"${disabledSession(s.pending || current.channelDisabled)}>Send</button></form>` : ''}<p id="chat-receipt" role="status">${txt(receipt)}</p>${pane ? resume : ''}${redesigned || pane ? '' : '<section class="chat-files"><h2>Files</h2><div data-chat-files>Files unavailable.</div></section><div data-chat-summary></div>'}</section>`;
|
||||
}
|
||||
// C2-10c: rooms reuse the same state, renderer and generation fences as threads.
|
||||
@@ -789,7 +801,7 @@
|
||||
paint(); return;
|
||||
}
|
||||
const old = current;
|
||||
current = { container, kind, id, orgArchived: old?.orgArchived ?? false, loading: true, archiveUnknown: kind === 'thread' && !user && !tester, settings: !!settings, section, path: originalPath, canSend, user, tester, chatGrants: [], thread: old && old.id === id ? old.thread : null, shared: old && old.id === id ? old.shared : false, projects: old?.projects ?? [], threads: old?.threads ?? [], repos: old?.repos ?? [], instances: old?.instances ?? [], instanceError: kind === 'project' ? 'Reading thread instances…' : '', error: '', readFailed: false, channelDisabled: old?.channelDisabled ?? false, refused: false, legacyDefault: old && old.id === id ? old.legacyDefault : false, sessions: old && old.id === id ? old.sessions ?? [] : [], session: match[3] ?? (old && old.id === id ? old.session : null), key: match[3] ? id + '/' + match[3] : old && old.id === id ? old.key : id };
|
||||
current = { container, kind, id, orgArchived: old?.orgArchived ?? false, loading: true, archiveUnknown: kind === 'thread' && !user && !tester, settings: !!settings, section, path: originalPath, canSend, user, tester, chatGrants: [], thread: old && old.id === id ? old.thread : null, shared: old && old.id === id ? old.shared : false, projects: old?.projects ?? [], threads: old?.threads ?? [], repos: old?.repos ?? [], instances: old?.instances ?? [], instanceError: kind === 'project' ? 'Reading thread instances…' : '', error: '', readFailed: false, channelDisabled: old?.channelDisabled ?? false, refused: false, legacyDefault: old && old.id === id ? old.legacyDefault : false, sessions: old && old.id === id ? old.sessions ?? [] : [], session: match[3] ?? (old && old.id === id ? old.session : null), key: match[3] ? id + '/' + match[3] : old && old.id === id ? old.key : id, agentIdle: old && old.id === id ? old.agentIdle : null };
|
||||
current.projectArchived = current.projects.some(p => p.id === (kind === 'project' ? id : current.thread?.project) && p.archived);
|
||||
if (kind === 'thread' && old?.kind === 'thread' && old.id === id && !navigated && old.archiveUnknown === false && old.projects.some(p => p.id === old.thread?.project)) current.archiveUnknown = false;
|
||||
if (current.projectArchived) current.archiveUnknown = false;
|
||||
@@ -873,6 +885,10 @@
|
||||
if (g !== generation || out()) return;
|
||||
current.shares = shares.rows;
|
||||
}
|
||||
if (kind === 'thread' && current.thread && threadWrites()) {
|
||||
current.agentIdle = await agentIdle(current.thread.instance, signal);
|
||||
if (g !== generation || out()) return;
|
||||
}
|
||||
let s = null, page = null, after = null;
|
||||
if (kind === 'thread' && catalog === null) {
|
||||
current.legacyDefault = true; current.sessions = []; current.session = null;
|
||||
@@ -1274,12 +1290,16 @@
|
||||
}
|
||||
on('mosaic-signed-out', () => { signedOut = true; forget(); });
|
||||
const hasDraft = () => [...states.values()].some(s => Boolean(s.draft?.trim())) || [...forms.values()].some(f => Boolean(f.name?.trim() || f.repo || f.instanceChosen));
|
||||
// SP11: the unsent text of a pane's thread, and whether a write is in flight or a sent message
|
||||
// still waits for the conversation to show it.
|
||||
const draft = () => [...states.values()].find(s => s.draft?.trim())?.draft || '';
|
||||
const busy = () => [...states.values()].some(s => s.pending || !!s.receiptId);
|
||||
// Ends a pane instance: its listeners, reads and observers stop and its container is left as is.
|
||||
function dispose() {
|
||||
life.abort(); generation++; controller?.abort(); transcriptObserver?.disconnect(); transcriptResize?.disconnect();
|
||||
current = null; lastPaint = null;
|
||||
}
|
||||
return { render, leave, forget, refresh, projectPath, hasDraft, dispose };
|
||||
return { render, leave, forget, refresh, projectPath, hasDraft, draft, busy, dispose };
|
||||
}
|
||||
const main = chatInstance();
|
||||
const ORG = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
||||
@@ -1288,7 +1308,7 @@
|
||||
function pane(org) {
|
||||
if (typeof org !== 'string' || !ORG.test(org)) throw new TypeError('pane needs an organization id');
|
||||
const chat = chatInstance({ org, prefix: `chat-p${++panes}-` });
|
||||
return Object.freeze({ render: chat.render, refresh: chat.refresh, dispose: chat.dispose, hasDraft: chat.hasDraft });
|
||||
return Object.freeze({ render: chat.render, refresh: chat.refresh, dispose: chat.dispose, hasDraft: chat.hasDraft, draft: chat.draft, busy: chat.busy });
|
||||
}
|
||||
window.MosaicChat = Object.freeze({ render: main.render, leave: main.leave, forget: main.forget, projectPath: main.projectPath, hasDraft: main.hasDraft, pane });
|
||||
})();
|
||||
@@ -21,7 +21,7 @@
|
||||
.then(r => (r.type === 'opaqueredirect' ? null : r.ok ? r.json() : null));
|
||||
const ready = readConfig().then(c => { config = c; boot = typeof c?.boot === 'string' ? c.boot : null; return c; }).catch(() => null);
|
||||
|
||||
const dirty = () => !!(window.MosaicChat?.hasDraft?.() || window.MosaicAssistant?.hasDraft?.() || window.MosaicOrgCreate?.hasDraft?.()
|
||||
const dirty = () => !!(window.MosaicChat?.hasDraft?.() || window.MosaicAssistant?.hasDraft?.() || window.MosaicOrgCreate?.hasDraft?.() || window.MosaicWorkflows?.hasDraft?.()
|
||||
|| document.querySelector('.settings-dot')
|
||||
|| [...document.querySelectorAll('#reply, #conv-reply, #doc-source, #send-body')].some(el => !!el.value?.trim()));
|
||||
|
||||
|
||||
@@ -118,7 +118,8 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date(
|
||||
return read;
|
||||
};
|
||||
let previous = location.hash, skipGuard = false;
|
||||
const dirty = () => window.MosaicChat?.hasDraft?.() || window.MosaicAssistant?.hasDraft?.() || window.MosaicOrgCreate?.hasDraft?.() || [...document.querySelectorAll('#reply, #conv-reply, #doc-source')].some(el => !!el.value?.trim());
|
||||
// SP11: the Assistant keeps its panes' unsent text per thread, so it is not asked about here.
|
||||
const dirty = () => window.MosaicChat?.hasDraft?.() || window.MosaicOrgCreate?.hasDraft?.() || window.MosaicWorkflows?.hasDraft?.() || [...document.querySelectorAll('#reply, #conv-reply, #doc-source')].some(el => !!el.value?.trim());
|
||||
// A switch scopes later reads to the new organization; listeners drop what they held for the old one.
|
||||
function rescope(seg) {
|
||||
const from = current;
|
||||
@@ -127,6 +128,7 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date(
|
||||
}
|
||||
function discard() {
|
||||
window.MosaicChat?.forget?.();
|
||||
window.MosaicWorkflows?.forget?.();
|
||||
for (const el of document.querySelectorAll('#reply, #conv-reply, #doc-source')) el.value = '';
|
||||
}
|
||||
function confirmSwitch(next) {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<link rel="stylesheet" href="/processing.css"><script src="/processing.js" defer></script>
|
||||
<link rel="stylesheet" href="/org-create.css"><script src="/org-create.js" defer></script>
|
||||
<link rel="stylesheet" href="/onboarding.css"><script src="/onboarding.js" defer></script><link rel="stylesheet" href="/assistant.css">
|
||||
<script src="/workspace-data.js" defer></script><script src="/workspace.js" defer></script><script src="/tasks-board.js" defer></script><script src="/console-restart.js" defer></script><script src="/display.js" defer></script><script src="/inbox.js" defer></script><script src="/files.js" defer></script><script src="/project-remote.js" defer></script><link rel="stylesheet" href="/autonomy.css"><script src="/autonomy.js" defer></script><link rel="stylesheet" href="/packs.css"><script src="/packs.js" defer></script><script src="/workflows.js" defer></script><script src="/federation.js" defer></script><script src="/brand.js" defer></script><script src="/app.js" defer></script><script src="/markdown-preview.js" defer></script><script src="/projects.js" defer></script><script src="/chat.js" defer></script><script src="/project-archive.js" defer></script><script src="/agents.js" defer></script><script src="/assistant.js" defer></script><script src="/bus.js" defer></script><script src="/requests.js" defer></script></head>
|
||||
<script src="/workspace-data.js" defer></script><script src="/workspace.js" defer></script><script src="/tasks-board.js" defer></script><script src="/console-restart.js" defer></script><script src="/display.js" defer></script><script src="/inbox.js" defer></script><script src="/files.js" defer></script><script src="/project-remote.js" defer></script><link rel="stylesheet" href="/autonomy.css"><script src="/autonomy.js" defer></script><link rel="stylesheet" href="/packs.css"><script src="/packs.js" defer></script><link rel="stylesheet" href="/workflows.css"><script src="/workflows.js" defer></script><script src="/federation.js" defer></script><script src="/brand.js" defer></script><script src="/app.js" defer></script><script src="/markdown-preview.js" defer></script><script src="/projects.js" defer></script><script src="/chat.js" defer></script><script src="/project-archive.js" defer></script><script src="/agents.js" defer></script><script src="/assistant.js" defer></script><script src="/bus.js" defer></script><script src="/requests.js" defer></script></head>
|
||||
<body>
|
||||
<div hidden aria-hidden="true"><select id="palette"></select><select id="mode"><option value="system">system</option><option value="light">light</option><option value="dim">dim</option><option value="dark">dark</option></select></div>
|
||||
<a class="skip" href="#main">Skip to content</a>
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
.avatar-wrap{position:relative}.avatar-wrap>button{display:flex;align-items:center;gap:8px;min-height:44px;border:0;background:transparent;color:var(--strong);font:inherit;cursor:pointer}.avatar-initial{display:grid;place-items:center;width:34px;height:34px;border-radius:50%;background:var(--action);color:var(--onAction);font-weight:700}.avatar-menu{position:absolute;right:0;top:calc(100% + 8px);z-index:50;width:240px;background:var(--surface);border:1px solid var(--line);border-radius:var(--r);padding:8px;box-shadow:var(--shadow)}.avatar-menu[hidden]{display:none}.avatar-menu a,.avatar-menu button,.avatar-menu label,.avatar-menu #local-sign-out{display:block;width:100%;padding:9px;color:var(--text);font:inherit;text-align:left}.avatar-menu a{text-decoration:none}.avatar-menu button{background:none;border:0;cursor:pointer}.avatar-menu a:hover,.avatar-menu button:hover{background:var(--raised)}.avatar-menu label{font-size:12px;color:var(--muted)}.avatar-menu select{display:block;width:100%;min-height:44px;margin-top:4px}.avatar-menu small{display:block;color:var(--muted)}.avatar-menu #local-sign-out{opacity:.7}
|
||||
#project-context,#project-tree,#board-tree{display:none!important}
|
||||
.s1-section{font-size:14px;gap:12px}.s1-section[aria-current=page]{background:color-mix(in srgb,var(--action) 30%,var(--surface));color:var(--strong)}
|
||||
.breadcrumbs{display:flex;gap:12px;align-items:center;margin:0 0 18px;color:var(--muted);font-size:13px}.breadcrumbs a{color:var(--action);text-decoration:none}.breadcrumbs [aria-current]{color:var(--strong)}
|
||||
.breadcrumbs[hidden]{display:none}.breadcrumbs{display:flex;gap:12px;align-items:center;margin:0 0 18px;color:var(--muted);font-size:13px}.breadcrumbs a{color:var(--action);text-decoration:none}.breadcrumbs [aria-current]{color:var(--strong)}
|
||||
#board-head h1{margin-bottom:0}#board-head p{margin:2px 0}.machine-off #status{display:none}
|
||||
#dashboard-summary,.dashboard-card{border:1px solid var(--line);border-radius:var(--r-lg);background:var(--surface)}#dashboard-summary{margin:20px 0}.kpi-grid{display:grid;grid-template-columns:repeat(7,minmax(0,1fr));padding:18px 0}.kpi{padding:0 18px;border-right:1px solid var(--line);min-width:0}.kpi:last-child{border-right:0}.kpi div{font-size:12px;color:var(--strong);font-weight:700;min-height:36px}.kpi strong{display:block;font-size:28px;line-height:1.2;color:var(--strong)}.kpi span{display:block;color:var(--muted);font-size:12px;margin-top:4px}.kpi-footer{border-top:1px solid var(--line);padding:8px 18px;margin:0;color:var(--muted);font-size:12px}
|
||||
#dashboard-cards{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px;margin:20px 0}.dashboard-card{padding:16px}.dashboard-card h2{margin:0 0 10px}.dashboard-card .processing-controls{padding:0;border:0}.dashboard-card .processing-controls strong{display:none}.dashboard-card .processing-controls .btn{min-height:44px}.dashboard-card ul{padding-left:20px}.dashboard-card a{color:var(--action)}
|
||||
|
||||
@@ -202,30 +202,22 @@
|
||||
return `<h2>Reviewed deliveries <span class="project-count">${f.reviewed.length}</span></h2>${f.reviewed.length?f.reviewed.map(({r,file})=>`<div class="project-panel"><span class="project-delivery-icon" aria-hidden="true">▤</span><strong>${clean(file.name)}</strong> <span class="project-chip success">Reviewed</span><p>Request ${clean(r.id)} · from ${clean(r.thread.name)} · Reviewed delivery. Not landed or deployed.</p><div class="project-delivery-actions"><a class="btn" target="_blank" rel="noopener noreferrer" href="/api/requests/${encodeURIComponent(r.id)}/artifact/${encodeURIComponent(file.id)}/text">Open as text</a> <a class="btn" download href="/api/requests/${encodeURIComponent(r.id)}/artifact/${encodeURIComponent(file.id)}">Download</a>${deliveryPr(r)?` <a class="btn" target="_blank" rel="noopener noreferrer" href="${esc(deliveryPr(r))}">Open pull request</a>`:''}</div><p>Open shows plain text in a new tab. Downloaded HTML can be opened locally after saving.</p></div>`).join(''):`<p>${data.disabled?'Files are unavailable.':data.failed?'Reviewed files are unavailable.':data.requests.length?'No reviewed file is available.':'No request files yet. Files appear when a request in this project produces them.'}</p>`}<h2>Draft workspace <span class="project-count">${f.drafts.length}</span></h2><p>Names only. Draft files may change and are not reviewed deliveries.</p><div class="project-panel project-file-list">${f.drafts.length?f.drafts.map(({r,name})=>`<div><span><span aria-hidden="true">▤</span> <code>${clean(name)}</code></span><span>Request ${clean(r.id)} · <span class="project-chip">Draft</span></span></div>`).join(''):data.failed || data.requests.some(r=>r.workspace?.available!==true || !Array.isArray(r.workspace.entries))?'<p>Could not read draft workspace. Try again later.</p>':'<p>No draft files found.</p>'}${data.requests.some(r=>r.workspace?.truncated)?'<p>The draft list was truncated.</p>':''}</div><h2>Project documents ${docs?`<span class="project-count">${docs.length}</span>`:''}</h2><div class="project-panel project-file-list">${!project.repo?'No linked repository.':data.recordsMissing?window.MosaicRecords.markup(project.repo):!docs?'Project documents unavailable. Docs could not read this project’s repository.':docs.length?docs.map(name=>`<div><span><span aria-hidden="true">▤</span> <code>${clean(name)}</code></span><a href="#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent(name)}">Open in Docs</a></div>`).join(''):'No project documents found.'}</div>`;
|
||||
}
|
||||
const expandedPrds = new Set();
|
||||
// U5: a project in a Side by side pane keeps its own request choice and PRD disclosure, so two
|
||||
// panes showing the same project (or two organizations' projects with one id) never share them.
|
||||
// The pane passes `views`, kept on the pane per organization, so the state outlives a repaint
|
||||
// that replaces the content element (a new conversation changes the header). Without it, the
|
||||
// state lives as long as the container.
|
||||
const paneViews = new WeakMap();
|
||||
const viewState=(container,pane,views)=>{if(!pane) return {selected:selectedRequests,expanded:expandedPrds}; if(views?.selected instanceof Map && views.expanded instanceof Set) return views; if(!paneViews.has(container)) paneViews.set(container,{selected:new Map(),expanded:new Set()}); return paneViews.get(container);};
|
||||
function requirementView(data,project,selected,expandedSet=expandedPrds,idPrefix='') {
|
||||
const pid=esc(idPrefix);
|
||||
function requirementView(data,project,selected,expandedSet=expandedPrds) {
|
||||
const options=data.requests.filter(r=>r.draft), r=options.find(x=>x.id===selected)||options[0], d=r?.draft;
|
||||
const north=typeof data.north?.content==='string'?data.north.content:null;
|
||||
const select=options.length>1?`<label>Request <select id="${pid}project-request-select">${options.map(x=>`<option value="${clean(x.id)}"${x===r?' selected':''}>${clean(x.id)} · ${clean(x.thread.name)}</option>`).join('')}</select></label>`:'';
|
||||
const select=options.length>1?`<label>Request <select id="project-request-select">${options.map(x=>`<option value="${clean(x.id)}"${x===r?' selected':''}>${clean(x.id)} · ${clean(x.thread.name)}</option>`).join('')}</select></label>`:'';
|
||||
const candidate=d?.candidate, expanded=r && expandedSet.has(project.id+':'+r.id);
|
||||
const docPath=candidate?.prd_path, docLink=project.repo && typeof docPath==='string' && /^docs\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.md$/.test(docPath) ? `#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent(docPath)}` : null;
|
||||
const rows=candidate ? [['PRD version',candidate.prd_version],['Approved snapshot',d.snapshot.id || 'None'],['PRD file',docPath],['PRD blob',candidate.prd_blob],['Records commit',candidate.records_commit],['Confirmed intent commit',candidate.spec_commit],['Mode revision',candidate.mode_revision]].map(([label,value])=>`<div class="project-provenance-row"><span>${label}</span>${label==='PRD file' && docLink?`<a href="${docLink}"><code>${clean(value)}</code></a>`:`<code>${clean(value)}</code>`}</div>`).join('') : '<p>Unavailable until a PRD is read.</p>';
|
||||
return `${r?`<div class="project-panel project-source">${select || `Request <code>${clean(r.id)}</code>`} · ${chip(r.state)} · from ${clean(r.thread.name)} <a href="${conversationLink(r.thread)}">Open conversation</a></div>`:select}<div class="project-columns"><section><h2>Project direction</h2><h3 id="${pid}project-north-star">North star</h3>${north!==null?`<div data-north-star></div><a class="project-text-link" href="#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent('spec/north-star.md')}">Open north star in Docs</a>`:data.northRecordsMissing?`<p>${window.MosaicRecords.markup(project.repo)}</p>`:data.northMissing?'<p>No north star yet.</p>':project.repo?'<p>North star unavailable. Docs could not read this project’s repository.</p>':`<p>This project has no linked repository. The north star and project documents live in a repository. Linking one to an existing project isn't available yet.</p>`}<h3 id="${pid}project-prd">${candidate?`PRD ${clean(candidate.prd_version)}`:'PRD'} ${candidate?`<span class="project-chip ${d.snapshot.id?'success':''}">${d.snapshot.id?'Approved':'Draft'}</span>`:''}</h3>${d?`<p>${d.snapshot.id?'Approved snapshot '+clean(d.snapshot.id):'This candidate has no active approved snapshot.'}</p><div class="project-panel project-prd-panel"><div class="project-prd-preview${expanded?' expanded':''}" data-prd></div><button type="button" class="btn project-prd-toggle" aria-expanded="${!!expanded}">${expanded?'Show less':'Show full PRD'}</button></div><h3>Requirements <span class="project-count">${d.requirements.length}</span></h3><div class="project-panel">${d.requirements.map((req,i)=>`<details data-restore-key="req:${clean(r.id)}:${clean(req.id)}"><summary>${clean(req.id)} · ${clean(req.title)}</summary><p>${clean(req.text)}</p><p>Requirement identity: <code>${clean(candidate.requirements[i]?.path)}</code> · <code>${clean(candidate.requirements[i]?.blob)}</code></p></details>`).join('')}</div>`:`<p>${(data.failed || data.requests.some(x=>x.materialFailed))?'Request or PRD unavailable. Refresh to try again.':'No current PRD candidate or approved snapshot. Waiting for a PRD submission.'}</p>`}${d && data.requests.some(x=>x.materialFailed)?'<p role="status">Some request PRDs could not be read. Refresh to try again.</p>':''}</section><aside class="project-panel project-provenance"><details data-restore-key="provenance"${matchMedia('(min-width:700px)').matches?' open':''}><summary>Version and provenance</summary>${rows}${candidate?`<p>Approval and revocation live in the conversation's Request details.</p><a href="${conversationLink(r.thread)}">Open conversation</a>`:''}</details></aside></div>`;
|
||||
return `${r?`<div class="project-panel project-source">${select || `Request <code>${clean(r.id)}</code>`} · ${chip(r.state)} · from ${clean(r.thread.name)} <a data-full-view href="${conversationLink(r.thread)}">Open conversation</a></div>`:select}<div class="project-columns"><section><h2>Project direction</h2><h3 id="project-north-star">North star</h3>${north!==null?`<div data-north-star></div><a class="project-text-link" href="#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent('spec/north-star.md')}">Open north star in Docs</a>`:data.northRecordsMissing?`<p>${window.MosaicRecords.markup(project.repo)}</p>`:data.northMissing?'<p>No north star yet.</p>':project.repo?'<p>North star unavailable. Docs could not read this project’s repository.</p>':`<p>This project has no linked repository. The north star and project documents live in a repository. Linking one to an existing project isn't available yet.</p>`}<h3 id="project-prd">${candidate?`PRD ${clean(candidate.prd_version)}`:'PRD'} ${candidate?`<span class="project-chip ${d.snapshot.id?'success':''}">${d.snapshot.id?'Approved':'Draft'}</span>`:''}</h3>${d?`<p>${d.snapshot.id?'Approved snapshot '+clean(d.snapshot.id):'This candidate has no active approved snapshot.'}</p><div class="project-panel project-prd-panel"><div class="project-prd-preview${expanded?' expanded':''}" data-prd></div><button type="button" class="btn project-prd-toggle" aria-expanded="${!!expanded}">${expanded?'Show less':'Show full PRD'}</button></div><h3>Requirements <span class="project-count">${d.requirements.length}</span></h3><div class="project-panel">${d.requirements.map((req,i)=>`<details data-restore-key="req:${clean(r.id)}:${clean(req.id)}"><summary>${clean(req.id)} · ${clean(req.title)}</summary><p>${clean(req.text)}</p><p>Requirement identity: <code>${clean(candidate.requirements[i]?.path)}</code> · <code>${clean(candidate.requirements[i]?.blob)}</code></p></details>`).join('')}</div>`:`<p>${(data.failed || data.requests.some(x=>x.materialFailed))?'Request or PRD unavailable. Refresh to try again.':'No current PRD candidate or approved snapshot. Waiting for a PRD submission.'}</p>`}${d && data.requests.some(x=>x.materialFailed)?'<p role="status">Some request PRDs could not be read. Refresh to try again.</p>':''}</section><aside class="project-panel project-provenance"><details data-restore-key="provenance"${matchMedia('(min-width:700px)').matches?' open':''}><summary>Version and provenance</summary>${rows}${candidate?`<p>Approval and revocation live in the conversation's Request details.</p><a data-full-view href="${conversationLink(r.thread)}">Open conversation</a>`:''}</details></aside></div>`;
|
||||
}
|
||||
function overview(data,project,canSend,receipt='') {
|
||||
const active=data.requests.filter(r=>r.state && !ended(r.state)), waiting=active.filter(r=>needs(r.state)), ordered=[...data.requests].sort(requestOrder), first=ordered[0], threads=[...data.threads];
|
||||
if(first) threads.sort((a,b)=>Number(b.id===first.thread.id)-Number(a.id===first.thread.id));
|
||||
const f=filesData(data), filesKnown=!data.failed && !!f.docs && data.requests.every(r=>r.workspace?.available===true && Array.isArray(r.workspace.entries) && r.state), count=filesKnown?f.reviewed.length+f.drafts.length+f.docs.length:'–';
|
||||
const n=typeof data.north?.content==='string'?data.north.content:null, candidate=ordered.find(r=>r.draft)?.draft;
|
||||
const metrics=[['Requests in progress',data.failed?'–':active.length,data.failed?'Not available yet':active[0]?label(active[0].state):'No active requests',first?conversationLink(first.thread):path(project.id,'conversations')],['Needs your input',data.failed?'–':waiting.length,data.failed?'Not available yet':waiting.length?label(waiting[0].state):'Nothing waiting',waiting[0]?conversationLink(waiting[0].thread):path(project.id,'conversations')],['Conversations',threads.length,'Project conversations',path(project.id,'conversations')],['Files',count,filesKnown?`${f.reviewed.length} reviewed · ${f.drafts.length} draft · ${f.docs.length} docs`:data.recordsMissing?'No project records yet':'Not available yet',path(project.id,'files')]];
|
||||
return `${waiting.length?`<div class="project-panel project-decision" role="status">${waiting.length} ${waiting.length===1?'decision needs':'decisions need'} your input. <a class="btn primary" href="${conversationLink(waiting[0].thread)}">Review decision</a></div>`:''}<div class="project-metrics">${metrics.map(([title,value,caption,href])=>`<a href="${href}"><span>${title}</span><strong>${value}</strong><small>${clean(caption)}</small></a>`).join('')}<p>Updated just now · Showing requests from recent messages.</p></div><div class="project-columns"><section><div class="project-section-title"><h2>Current work</h2>${canSend&&!project.archived?`<a class="btn" href="${path(project.id,'conversations')}?new=1">${plusIcon}New conversation</a>`:''}</div>${threads.length?threads.map((t,i)=>i===0?card(t,workFor(data,t),data.failed):`<a class="project-row" href="${conversationLink(t)}"><strong>${clean(t.name)}</strong><small>With ${clean(t.instance)} · ${workFor(data,t) ? label(workFor(data,t).state) : data.failed ? 'Status unavailable' : 'No active request'}</small>${workFor(data,t)?chip(workFor(data,t).state):''}</a>`).join(''):'<p>No conversations yet. Start one to begin work.</p>'}<h2>Tasks <span class="project-count">${taskRefs(data).length}</span></h2><div class="project-panel">${taskRefs(data).length?taskRefs(data).slice(0,2).map(ref=>`<div>${taskLink(ref,data)}</div>`).join(''):data.failed?'<p>Request tasks unavailable. Refresh to try again.</p>':'<p>No request tasks available.</p>'}<a href="${path(project.id,'tasks')}">View all project tasks</a></div></section><aside class="project-panel"><h2>Project direction</h2><h3>North star</h3>${n!==null?`<div data-north-star></div><a class="project-text-link" href="#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent('spec/north-star.md')}">Open north star in Docs</a>`:`<p>${data.northRecordsMissing?window.MosaicRecords.markup(project.repo):data.northMissing?'No north star yet.':project.repo?'North star unavailable. Docs could not read this project’s repository.':"This project has no linked repository. The north star and project documents live in a repository. Linking one to an existing project isn't available yet."}</p>`}<h3>${candidate?'PRD '+clean(candidate.candidate.prd_version):'PRD'} ${candidate?.snapshot.id?'<span class="project-chip success">Approved</span>':''}</h3><p>${candidate?(candidate.snapshot.id?'Approved snapshot '+clean(candidate.snapshot.id):'Draft'):(data.failed || data.requests.some(x=>x.materialFailed)?'PRD unavailable.':'No current PRD available.')}</p>${candidate && data.requests.some(x=>x.materialFailed)?'<p role="status">Some request PRDs could not be read. Refresh to try again.</p>':''}<a href="${path(project.id,'requirements')}">Open PRD and requirements</a><h3>Files ${filesKnown?`<span class="project-count">${count}</span>`:''}</h3>${[...f.reviewed.map(x=>({name:x.file.name,reviewed:true})),...f.drafts.map(x=>({name:x.name,reviewed:false}))].slice(0,3).map(file=>file.reviewed?`<p><a href="${path(project.id,'files')}"><code>${clean(file.name)}</code> · Reviewed</a></p>`:`<p><code>${clean(file.name)}</code> · Draft</p>`).join('')||(data.failed?'<p>Request files unavailable.</p>':'<p>No request files available.</p>')}<a href="${path(project.id,'files')}">All files</a><h3>Project facts</h3><div class="project-provenance-row"><span>Repository</span><span>${project.repo?clean(project.repo):'Not linked'}</span></div>${roomControls(project,data.room,canSend,receipt)}<div class="project-provenance-row"><span>Mode</span><span>${first?.state?.mode?clean(modeLabel(first.state.mode)):data.failed?'Unavailable':'No active request'}</span></div></aside></div>`;
|
||||
const metrics=[['Requests in progress',data.failed?'–':active.length,data.failed?'Not available yet':active[0]?label(active[0].state):'No active requests',first?conversationLink(first.thread):path(project.id,'conversations'),!!first],['Needs your input',data.failed?'–':waiting.length,data.failed?'Not available yet':waiting.length?label(waiting[0].state):'Nothing waiting',waiting[0]?conversationLink(waiting[0].thread):path(project.id,'conversations'),!!waiting[0]],['Conversations',threads.length,'Project conversations',path(project.id,'conversations')],['Files',count,filesKnown?`${f.reviewed.length} reviewed · ${f.drafts.length} draft · ${f.docs.length} docs`:data.recordsMissing?'No project records yet':'Not available yet',path(project.id,'files')]];
|
||||
return `${waiting.length?`<div class="project-panel project-decision" role="status">${waiting.length} ${waiting.length===1?'decision needs':'decisions need'} your input. <a class="btn primary" data-full-view href="${conversationLink(waiting[0].thread)}">Review decision</a></div>`:''}<div class="project-metrics">${metrics.map(([title,value,caption,href,full])=>`<a${full?' data-full-view':''} href="${href}"><span>${title}</span><strong>${value}</strong><small>${clean(caption)}</small></a>`).join('')}<p>Updated just now · Showing requests from recent messages.</p></div><div class="project-columns"><section><div class="project-section-title"><h2>Current work</h2>${canSend&&!project.archived?`<a class="btn" href="${path(project.id,'conversations')}?new=1">${plusIcon}New conversation</a>`:''}</div>${threads.length?threads.map((t,i)=>i===0?card(t,workFor(data,t),data.failed):`<a class="project-row" href="${conversationLink(t)}"><strong>${clean(t.name)}</strong><small>With ${clean(t.instance)} · ${workFor(data,t) ? label(workFor(data,t).state) : data.failed ? 'Status unavailable' : 'No active request'}</small>${workFor(data,t)?chip(workFor(data,t).state):''}</a>`).join(''):'<p>No conversations yet. Start one to begin work.</p>'}<h2>Tasks <span class="project-count">${taskRefs(data).length}</span></h2><div class="project-panel">${taskRefs(data).length?taskRefs(data).slice(0,2).map(ref=>`<div>${taskLink(ref,data)}</div>`).join(''):data.failed?'<p>Request tasks unavailable. Refresh to try again.</p>':'<p>No request tasks available.</p>'}<a href="${path(project.id,'tasks')}">View all project tasks</a></div></section><aside class="project-panel"><h2>Project direction</h2><h3>North star</h3>${n!==null?`<div data-north-star></div><a class="project-text-link" href="#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent('spec/north-star.md')}">Open north star in Docs</a>`:`<p>${data.northRecordsMissing?window.MosaicRecords.markup(project.repo):data.northMissing?'No north star yet.':project.repo?'North star unavailable. Docs could not read this project’s repository.':"This project has no linked repository. The north star and project documents live in a repository. Linking one to an existing project isn't available yet."}</p>`}<h3>${candidate?'PRD '+clean(candidate.candidate.prd_version):'PRD'} ${candidate?.snapshot.id?'<span class="project-chip success">Approved</span>':''}</h3><p>${candidate?(candidate.snapshot.id?'Approved snapshot '+clean(candidate.snapshot.id):'Draft'):(data.failed || data.requests.some(x=>x.materialFailed)?'PRD unavailable.':'No current PRD available.')}</p>${candidate && data.requests.some(x=>x.materialFailed)?'<p role="status">Some request PRDs could not be read. Refresh to try again.</p>':''}<a href="${path(project.id,'requirements')}">Open PRD and requirements</a><h3>Files ${filesKnown?`<span class="project-count">${count}</span>`:''}</h3>${[...f.reviewed.map(x=>({name:x.file.name,reviewed:true})),...f.drafts.map(x=>({name:x.name,reviewed:false}))].slice(0,3).map(file=>file.reviewed?`<p><a href="${path(project.id,'files')}"><code>${clean(file.name)}</code> · Reviewed</a></p>`:`<p><code>${clean(file.name)}</code> · Draft</p>`).join('')||(data.failed?'<p>Request files unavailable.</p>':'<p>No request files available.</p>')}<a href="${path(project.id,'files')}">All files</a><h3>Project facts</h3><div class="project-provenance-row"><span>Repository</span><span>${project.repo?clean(project.repo):'Not linked'}</span></div>${roomControls(project,data.room,canSend,receipt)}<div class="project-provenance-row"><span>Mode</span><span>${first?.state?.mode?clean(modeLabel(first.state.mode)):data.failed?'Unavailable':'No active request'}</span></div></aside></div>`;
|
||||
}
|
||||
function tasksView(data) {
|
||||
const refs=taskRefs(data);
|
||||
@@ -260,9 +252,7 @@
|
||||
const focus=f.id ? root.querySelector('#'+CSS.escape(f.id)) : f.details ? [...root.querySelectorAll('details[data-restore-key]')].find(el=>el.dataset.restoreKey===f.details)?.querySelector(':scope > summary') : root.querySelectorAll(FOCUSABLE)[f.index];
|
||||
focus?.focus({preventScroll:true});
|
||||
}
|
||||
// A Side by side pane passes `idPrefix` (pane-a-, pane-b-), so the same project in both panes
|
||||
// draws distinct ids; the full view passes none and keeps its ids.
|
||||
async function mountContent({container,project,threads,section,canSend,restore,roomReceipt,org=null,pane=false,views:paneState=null,idPrefix=''}) {
|
||||
async function mountContent({container,project,threads,section,canSend,restore,roomReceipt,org=null}) {
|
||||
if(!container || !project) return;
|
||||
const generation=epoch, run=(contentRuns.get(container) || 0)+1;
|
||||
contentRuns.set(container,run);
|
||||
@@ -270,11 +260,10 @@
|
||||
const data=await gather(project,threads,org).catch(()=>null);
|
||||
if(!container.isConnected || generation!==epoch || contentRuns.get(container)!==run || document.body.classList.contains('signed-out')) return;
|
||||
if(!data){contentPaints.delete(container);container.textContent='Project data unavailable. Refresh to try again.';return;}
|
||||
const views=viewState(container,pane,paneState), selectedRequests=views.selected, expandedPrds=views.expanded;
|
||||
const selected=selectedRequests.get(project.id);
|
||||
if(selected && !data.requests.some(r=>r.id===selected && r.draft)) selectedRequests.delete(project.id);
|
||||
const selection=selectedRequests.get(project.id);
|
||||
const view = section==='requirements'?requirementView(data,project,selection,expandedPrds,idPrefix):section==='files'?filesView(data,project):section==='tasks'?tasksView(data):overview(data,project,canSend,roomReceipt);
|
||||
const view = section==='requirements'?requirementView(data,project,selection,expandedPrds):section==='files'?filesView(data,project):section==='tasks'?tasksView(data):overview(data,project,canSend,roomReceipt);
|
||||
const selectedRequest=data.requests.find(r=>r.id===(selection||data.requests.find(x=>x.draft)?.id));
|
||||
// The generated presentation and separately mounted Markdown determine visible content.
|
||||
const signature=JSON.stringify([view, section==='requirements' ? selectedRequest?.draft?.prd : null, ['requirements','overview'].includes(section) ? data.north?.content : null, data.failed && ['files','tasks'].includes(section)]);
|
||||
@@ -284,7 +273,7 @@
|
||||
// Retained controls (the request selector) draw from the newest accepted read, even when
|
||||
// this read changes nothing visible and the DOM is kept.
|
||||
contentModels.set(container,{data,project,section,canSend,roomReceipt});
|
||||
if(!pane) window.MosaicOnboarding?.offer(container,{project,section,north:data.north,docs:data.docs,threads:data.threads,canSend}); // F2: its panel sits before the container, outside draw().
|
||||
window.MosaicOnboarding?.offer(container,{project,section,north:data.north,docs:data.docs,threads:data.threads,canSend}); // F2: its panel sits before the container, outside draw().
|
||||
if (contentPaints.get(container) === signature) return;
|
||||
contentPaints.set(container, signature);
|
||||
// Capture at commit time: the user may have interacted while the read was pending.
|
||||
@@ -292,12 +281,12 @@
|
||||
const liveRestore=contentPaints.has(container) && container.children.length ? captureView(container) : null;
|
||||
const draw=selected=>{
|
||||
const {data,project,section,canSend,roomReceipt}=contentModels.get(container);
|
||||
container.innerHTML=section==='requirements'?requirementView(data,project,selected,expandedPrds,idPrefix):section==='files'?filesView(data,project):section==='tasks'?tasksView(data):overview(data,project,canSend,roomReceipt);
|
||||
container.innerHTML=section==='requirements'?requirementView(data,project,selected,expandedPrds):section==='files'?filesView(data,project):section==='tasks'?tasksView(data):overview(data,project,canSend,roomReceipt);
|
||||
if(data.failed && ['files','tasks'].includes(section)) container.insertAdjacentHTML('afterbegin','<p role="status">Some request data could not be read; this list may be incomplete.</p>');
|
||||
const selectedRequest=data.requests.find(r=>r.id===(selected||data.requests.find(x=>x.draft)?.id));
|
||||
const md=container.querySelector('[data-prd]'); if(md && selectedRequest?.draft) { md.replaceChildren(window.MosaicMarkdown?.render(selectedRequest.draft.prd) || document.createTextNode(selectedRequest.draft.prd)); const toggle=container.querySelector('.project-prd-toggle'); toggle.hidden=!md.classList.contains('expanded') && md.scrollHeight<=md.clientHeight; toggle.addEventListener('click',()=>{const key=project.id+':'+selectedRequest.id; if(expandedPrds.has(key)) expandedPrds.delete(key); else expandedPrds.add(key); const open=expandedPrds.has(key); md.classList.toggle('expanded',open); toggle.setAttribute('aria-expanded',String(open));toggle.textContent=open?'Show less':'Show full PRD';}); }
|
||||
const north=container.querySelector('[data-north-star]'); if(north && typeof data.north?.content==='string') { const text=section==='overview' && data.north.content.length>500 ? previewCut(data.north.content,500) : data.north.content; north.replaceChildren(window.MosaicMarkdown?.render(text) || document.createTextNode(text)); }
|
||||
const requestSelect='#'+CSS.escape(idPrefix+'project-request-select');
|
||||
const requestSelect='#project-request-select';
|
||||
container.querySelector(requestSelect)?.addEventListener('change',e=>{selectedRequests.set(project.id,e.target.value);draw(e.target.value);container.querySelector(requestSelect)?.focus({preventScroll:true});});
|
||||
};
|
||||
draw(selection);
|
||||
@@ -305,8 +294,8 @@
|
||||
if (restore) {
|
||||
restoreView(container,restore);
|
||||
}
|
||||
const sectionTarget=pane ? null : new URLSearchParams(location.hash.split('?')[1] || '').get('section');
|
||||
if(section==='requirements' && ['prd','north-star'].includes(sectionTarget)) container.querySelector('#'+CSS.escape(idPrefix+'project-'+sectionTarget))?.scrollIntoView({block:'start'});
|
||||
const sectionTarget=new URLSearchParams(location.hash.split('?')[1] || '').get('section');
|
||||
if(section==='requirements' && ['prd','north-star'].includes(sectionTarget)) container.querySelector('#project-'+sectionTarget)?.scrollIntoView({block:'start'});
|
||||
}
|
||||
// Cut at a word boundary, unless that would leave only a markdown marker (a long heading).
|
||||
function previewCut(content,max) {
|
||||
|
||||
@@ -462,7 +462,7 @@ html[data-organizations] .ws-chips{display:flex;flex-wrap:wrap;align-items:cente
|
||||
|
||||
/* Page frame (sample main column). */
|
||||
html[data-organizations] .content:has(.ws){padding-top:18px;padding-inline:24px}
|
||||
body:has([data-org-dashboard]) #breadcrumbs,body:has([data-org-agents]) #breadcrumbs{display:none}
|
||||
body:has([data-org-dashboard]) #breadcrumbs{display:none}
|
||||
html[data-organizations] .ws{font-size:14px;line-height:1.5;color:var(--text);min-width:0}
|
||||
html[data-organizations] .ws h1{margin:0;font-size:28px;font-weight:800;letter-spacing:-.02em;line-height:1.15;color:var(--strong)}
|
||||
html[data-organizations] .ws h1:focus,html[data-organizations] .ws h1:focus-visible{outline:none}
|
||||
@@ -506,9 +506,13 @@ html[data-organizations] .ws-doc:hover{background:var(--raised)}
|
||||
html[data-organizations] .ws-doc svg.i{width:14px;height:14px;color:var(--muted)}
|
||||
html[data-organizations] .ws-doc small{font-weight:500;color:var(--muted);font-size:11px}
|
||||
html[data-organizations] .ws-more{font-size:13px;font-weight:600;margin-left:4px;color:var(--action);text-decoration:none}
|
||||
html[data-organizations] .ws-tiles{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px}
|
||||
html[data-organizations] .ws-tile{background:var(--surface);border:1px solid var(--line);border-radius:8px;padding:12px 14px;display:grid;gap:6px;align-content:start}
|
||||
html[data-organizations] .ws-tile.is-empty{grid-column:1/-1;border-style:dashed;background:transparent}
|
||||
/* SP8 (#1873): one row of figure tiles under the page heading, each a link to the page that lists what it counts. */
|
||||
html[data-organizations] .ws-tiles{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px;margin:0 0 16px}
|
||||
html[data-organizations] .ws-tiles.six{grid-template-columns:repeat(6,minmax(0,1fr))}
|
||||
html[data-organizations] .ws-tile{background:var(--surface);border:1px solid var(--line);border-radius:8px;padding:12px 14px;display:grid;gap:6px;align-content:start;min-width:0;color:inherit;text-decoration:none}
|
||||
html[data-organizations] a.ws-tile:hover{border-color:color-mix(in srgb,var(--action) 45%,var(--line))}
|
||||
html[data-organizations] a.ws-tile:focus-visible{outline:2px solid var(--action);outline-offset:2px}
|
||||
html[data-organizations] .ws-tile>.ws-label{font-size:12.5px;font-weight:600;letter-spacing:0;text-transform:none}
|
||||
html[data-organizations] .ws-empty-t{font-size:13.5px;font-weight:600;color:var(--strong)}
|
||||
html[data-organizations] .ws-tbl{overflow-x:auto;border:1px solid var(--line);border-radius:8px;background:var(--surface)}
|
||||
html[data-organizations] .ws-tbl table{width:100%;border-collapse:collapse;font-size:13px;margin:0}
|
||||
@@ -567,7 +571,7 @@ html[data-organizations] .ws-rules .ws-lvl{margin-right:0}
|
||||
html[data-organizations] .ws-scope{margin:-8px 0 14px}
|
||||
|
||||
/* Across organizations (U3): the main dashboard, projects and inbox, samples 02, 04 and 05. */
|
||||
body:has([data-ws-home]) #breadcrumbs,body:has([data-ws-projects]) #breadcrumbs,body:has([data-ws-inbox]) #breadcrumbs{display:none}
|
||||
body:has([data-ws-home]) #breadcrumbs{display:none}
|
||||
html[data-organizations] .ws-edge{box-shadow:inset 3px 0 0 var(--org)}
|
||||
html[data-organizations] .ws-orgref{display:inline-flex;align-items:center;gap:6px;white-space:nowrap;color:var(--strong);font-weight:600}
|
||||
html[data-organizations] .ws-chip{display:inline-flex;align-items:center;gap:5px;font-size:12px;font-weight:600;padding:1px 7px;border-radius:4px;background:var(--raised);color:var(--strong);white-space:nowrap;line-height:1.5}
|
||||
@@ -580,9 +584,8 @@ html[data-organizations] .ws-tbl .ws-dot.s-working b,html[data-organizations] .w
|
||||
html[data-organizations] .ws-tbl .ws-dot.s-waiting b{color:var(--warning)}
|
||||
html[data-organizations] .ws-tbl .ws-dot.s-error b{color:var(--danger)}
|
||||
html[data-organizations] .ws-tbl .ws-dot.s-idle b,html[data-organizations] .ws-tbl .ws-dot.s-offline b{color:var(--muted)}
|
||||
html[data-organizations] .ws-g5{display:grid;gap:10px;grid-template-columns:repeat(5,minmax(0,1fr))}
|
||||
html[data-organizations] .ws-tile .ws-big{font-size:24px;font-weight:800;color:var(--strong);letter-spacing:-.02em;font-variant-numeric:tabular-nums;line-height:1.1}
|
||||
html[data-organizations] .ws-tile .ws-big small{font-size:13px;font-weight:600;color:var(--muted);letter-spacing:0;margin-left:4px}
|
||||
html[data-organizations] .ws-tile .ws-big small{font-size:13px;font-weight:600;color:var(--muted);letter-spacing:0}
|
||||
html[data-organizations] .ws-tile .ws-delta{font-size:12px;color:var(--muted)}
|
||||
html[data-organizations] .ws-tile .ws-delta b{color:var(--success);font-weight:600}
|
||||
html[data-organizations] .ws-tile.quiet{border-style:dashed;background:transparent}
|
||||
@@ -724,7 +727,7 @@ html[data-organizations] .ws-cmd code{flex:1;min-width:0;overflow-x:auto;white-s
|
||||
html[data-organizations] .ws-cmd .ws-btn{padding:4px 6px}
|
||||
html[data-organizations] #copy-status:empty{display:none}
|
||||
@media (max-width:1100px){
|
||||
html[data-organizations] .ws-g5{grid-template-columns:repeat(3,minmax(0,1fr))}
|
||||
html[data-organizations] .ws-tiles.six{grid-template-columns:repeat(3,minmax(0,1fr))}
|
||||
html[data-organizations] .ws-ibx-grid.with-insp{grid-template-columns:minmax(0,1fr)}
|
||||
html[data-organizations] .ws-insp{position:static;max-height:none}
|
||||
}
|
||||
@@ -734,8 +737,8 @@ html[data-organizations] #copy-status:empty{display:none}
|
||||
html[data-organizations] .content:has(.ws){padding:14px 16px 24px}
|
||||
html[data-organizations] .tree{padding:10px 12px 20px}
|
||||
html[data-organizations] .ws h1{font-size:24px}
|
||||
html[data-organizations] .ws-split,html[data-organizations] .ws-tiles{grid-template-columns:minmax(0,1fr)}
|
||||
html[data-organizations] .ws-tile.is-empty{grid-column:auto}
|
||||
html[data-organizations] .ws-split{grid-template-columns:minmax(0,1fr)}
|
||||
html[data-organizations] .ws-tiles,html[data-organizations] .ws-tiles.six{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
html[data-organizations] .ws-sec-h .note{flex-basis:100%;order:3}
|
||||
html[data-organizations] .ws-cfg li{grid-template-columns:18px minmax(0,1fr) auto auto}
|
||||
html[data-organizations] .ws-cfg .v{grid-column:2/-1;grid-row:2}
|
||||
@@ -751,9 +754,6 @@ html[data-organizations] #copy-status:empty{display:none}
|
||||
html[data-organizations] .ws-levels>.span{grid-column:auto}
|
||||
html[data-organizations] .ws-levels>.last.lh{border-bottom:1px solid color-mix(in srgb,var(--line) 60%,transparent)}
|
||||
html[data-organizations] .ws-levels .mlabel{display:flex}
|
||||
html[data-organizations] .ws-g5{grid-template-columns:minmax(0,1fr)}
|
||||
html[data-organizations] .ws-g5.keep2{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
html[data-organizations] .ws-g5.keep2>:last-child:nth-child(odd){grid-column:1/-1}
|
||||
html[data-organizations] .ws-orgcards{grid-template-columns:minmax(0,1fr)}
|
||||
html[data-organizations] .ws-srow{grid-template-columns:92px 20px minmax(0,1fr)}
|
||||
html[data-organizations] .ws-srow .ws-by{grid-column:1/-1}
|
||||
|
||||
@@ -41,7 +41,12 @@
|
||||
// The layout is remembered per viewer and per width: a phone opens on List until its viewer picks
|
||||
// Kanban, a wide screen on Kanban until its viewer picks List.
|
||||
const layouts = (() => { try { const v = JSON.parse(load(LAYOUT) || '{}'); return v && typeof v === 'object' ? v : {}; } catch { return {}; } })();
|
||||
const filter = { org: '', project: '', assignee: '', state: '', label: '', q: '' };
|
||||
// done: 'week' shows the tasks the Dashboard's Done this week tile counts. It stays in the browser:
|
||||
// the rows already carry done and their last change, the same test the tile's count uses.
|
||||
const filter = { org: '', project: '', assignee: '', state: '', label: '', q: '', done: '' };
|
||||
const WEEK_MS = 7 * 24 * 3600 * 1000;
|
||||
const doneThisWeek = t => t.done && t.changedAt && Date.now() - Date.parse(t.changedAt) <= WEEK_MS;
|
||||
const DONE_NOTE = 'Done this week counts done tasks by their last change; the bus records no time a task was done.';
|
||||
// The board style in force: the filtered project's when it has one, else the one organization's the
|
||||
// view is narrowed to (by the org chip or by a project of that org), else none.
|
||||
function activeBoard() {
|
||||
@@ -167,6 +172,7 @@
|
||||
&& (!filter.assignee || (filter.assignee === '-' ? !t.assignees.length : t.assignees.includes(filter.assignee)))
|
||||
&& (!filter.state || stateOf(t) === filter.state)
|
||||
&& (!filter.label || t.labels.map(String).includes(filter.label))
|
||||
&& (!filter.done || doneThisWeek(t))
|
||||
&& (!q || !needle || `${t.title ?? ''} ${shortId(t.ref)} ${projectName(t) ?? ''}`.toLowerCase().includes(needle)));
|
||||
}
|
||||
const select = (name, label, options, focus) => `<label class="tb-sel"><span class="ws-label">${esc(label)}</span><select data-tb-filter="${name}" data-focus-key="${focus}">${options}</select></label>`;
|
||||
@@ -189,6 +195,7 @@
|
||||
const labelSel = labels.length ? select('label', 'Label', opt('', 'Any', filter.label) + labels.map(l => opt(l, l, filter.label)).join(''), 'tb-label') : '';
|
||||
return `<div class="tb-toolbar">
|
||||
${scope ? '' : `<div class="tb-chips" role="group" aria-label="Organization">${chips}</div>`}
|
||||
${filter.done ? '<button type="button" class="tb-f plain" data-tb-done aria-pressed="true" aria-label="Clear Done this week: done tasks last changed in the past 7 days" data-focus-key="tb-done">Done this week <span aria-hidden="true">×</span></button>' : ''}
|
||||
${select('project', 'Project', projectOpts, 'tb-project')}${select('assignee', 'Assignee', assigneeOpts, 'tb-assignee')}${select('state', 'State', stateOpts, 'tb-state')}${labelSel}
|
||||
<div class="tb-right"><label class="tb-search">${icon('search')}<input type="search" placeholder="Find a task" aria-label="Find a task" data-tb-q data-focus-key="tb-q" value="${esc(filter.q)}" autocomplete="off"></label></div>
|
||||
</div>`;
|
||||
@@ -244,8 +251,9 @@
|
||||
// total; with one of those on, the line says how many match rather than inventing an "of N".
|
||||
// The scope's org= is where the board reads, not a filter.
|
||||
const onServer = new URLSearchParams(readQuery()).size > (scope ? 2 : 1), n = rows.length;
|
||||
const line = onServer ? `<p class="tb-count">Showing ${n} ${n === 1 ? 'task that matches' : 'tasks that match'} the filters.</p>`
|
||||
: n !== all ? `<p class="tb-count">Showing ${n} of ${all} tasks.</p>` : '';
|
||||
const note = filter.done ? ` ${DONE_NOTE}` : '';
|
||||
const line = onServer ? `<p class="tb-count">Showing ${n} ${n === 1 ? 'task that matches' : 'tasks that match'} the filters.${note}</p>`
|
||||
: n !== all ? `<p class="tb-count">Showing ${n} of ${all} tasks.${note}</p>` : note ? `<p class="tb-count">${note.trim()}</p>` : '';
|
||||
// An empty result is only exhaustive when every organization's tasks were read.
|
||||
const unread = snap.orgs.filter(o => !tasksRead(o));
|
||||
const none = what => (unread.length ? `${what} in the organizations that answered. Tasks from ${unread.map(o => o.label).join(', ')} could not be read.` : `${what}.`);
|
||||
@@ -349,6 +357,7 @@
|
||||
const org = String(q.get('org') || ''), project = String(q.get('project') || '');
|
||||
filter.org = scope || (ORG_ID.test(org) ? org : '');
|
||||
filter.project = PROJECT_SELECTOR.test(project) || project === '-' ? project : '';
|
||||
filter.done = q.get('done') === 'week' ? 'week' : '';
|
||||
if (filter.org && filter.project && filter.project !== '-' && !filter.project.startsWith(`${filter.org}:`)) filter.project = '';
|
||||
if (dragging) await Promise.race([dragEnded, new Promise(r => setTimeout(r, 30000))]);
|
||||
// Two renders at once (a first load, a poll during a filter change): the replaced one draws from the newer read.
|
||||
@@ -592,6 +601,7 @@
|
||||
ws()?.setQuery?.({ org: org || null, ...(clear ? { project: null } : {}) }, true);
|
||||
return;
|
||||
}
|
||||
if (e.target.closest('[data-tb-done]')) { filter.done = ''; paint(); ws()?.setQuery?.({ done: null }, true); return; }
|
||||
const open = e.target.closest('[data-tb-open]');
|
||||
if (open) { const t = find(open.dataset.tbOpen); if (t) openDialog(editForm(t), open.dataset.focusKey, t); return; }
|
||||
const add = e.target.closest('[data-tb-new]');
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/* SP9 (#1873): the read-only workflow pages (#/orgs/<id>/workflows[/<name>]) and the organization
|
||||
page's Workflows card. Colours come from the theme tokens, so light and dark both follow the theme. */
|
||||
.wfg{min-width:0}
|
||||
.wfg h2{font-size:15px;margin:22px 0 8px}
|
||||
.wfg-scope:first-of-type h2{margin-top:6px}
|
||||
.wfg-list{list-style:none;margin:0;padding:0;background:var(--surface);border:1px solid var(--line);border-radius:10px}
|
||||
.wfg-item{padding:12px 14px;border-top:1px solid var(--line-soft,var(--line));overflow-wrap:anywhere}
|
||||
.wfg-item:first-child{border-top:0}
|
||||
.wfg-item-h{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 10px}
|
||||
.wfg-item-h a{font-weight:600;color:var(--action,var(--accent));text-decoration:none}
|
||||
.wfg-item-h a:hover{text-decoration:underline}
|
||||
.wfg-desc{margin:4px 0 0;color:var(--muted);font-size:13.5px}
|
||||
.wfg-chain{list-style:none;display:flex;flex-wrap:wrap;gap:4px 0;margin:8px 0 0;padding:0;font-size:13px;color:var(--text)}
|
||||
.wfg-chain li{display:inline-flex;align-items:center}
|
||||
.wfg-chain li+li::before{content:"\2192";color:var(--muted);padding:0 8px}
|
||||
:is(.wfg,.wfg-card) a:focus-visible{outline:2px solid var(--focus);outline-offset:2px;border-radius:4px}
|
||||
|
||||
/* The graph scrolls inside its own frame when it is wider than the frame; the page never does. */
|
||||
.wfg-frame{max-width:100%;overflow-x:auto;background:var(--surface);border:1px solid var(--line);border-radius:10px;padding:8px}
|
||||
.wfg-graph{display:block}
|
||||
.wfg-graph.is-vertical{width:100%;max-width:340px;height:auto;margin:0 auto}
|
||||
.wfg-node{cursor:pointer;text-decoration:none}
|
||||
.wfg-node rect{fill:var(--canvas);stroke:var(--line);stroke-width:1.5}
|
||||
.wfg-node:hover rect{stroke:var(--muted)}
|
||||
.wfg-node.is-sel rect{stroke:var(--accent);stroke-width:2.5;fill:var(--raised)}
|
||||
.wfg-node:focus{outline:none}
|
||||
.wfg-node:focus-visible rect{stroke:var(--focus);stroke-width:3}
|
||||
.wfg-node text{font-family:var(--font);fill:var(--text)}
|
||||
.wfg-meta{font-size:12px;fill:var(--muted)!important;letter-spacing:.02em}
|
||||
.wfg-title{font-size:15px;font-weight:600;fill:var(--strong,var(--text))!important}
|
||||
.wfg-roles{font-size:13px;font-family:var(--mono)!important;fill:var(--text)}
|
||||
.wfg-miss{font-size:12px;fill:var(--danger)!important}
|
||||
.wfg-node .wfg-none{fill:var(--muted);font-family:var(--font)}
|
||||
.wfg-edge{fill:none;stroke:var(--muted);stroke-width:1.5}
|
||||
.wfg-arrow{fill:var(--muted)}
|
||||
|
||||
.wfg-detail{margin-top:16px;overflow-wrap:anywhere}
|
||||
.wfg-detail h2{margin:0 0 10px}
|
||||
.wfg-dl{display:grid;grid-template-columns:max-content minmax(0,1fr);align-items:baseline;gap:8px 16px;margin:0 0 12px}
|
||||
.wfg-dl dt{color:var(--muted);font-size:13px}
|
||||
.wfg-dl dd{margin:0}
|
||||
@media (max-width:700px){
|
||||
.wfg-dl{grid-template-columns:minmax(0,1fr);gap:2px}
|
||||
.wfg-dl dd{margin-bottom:8px}
|
||||
}
|
||||
|
||||
/* The organization page's card, above Settings in the right column. */
|
||||
.wfg-card>.ws-sec-h{margin-top:0}
|
||||
.wfg-card+.ws-sec-h{margin-top:22px}
|
||||
.wfg-cardlist{list-style:none;margin:0}
|
||||
.wfg-cardlist li+li{border-top:1px solid var(--line-soft,var(--line))}
|
||||
.wfg-cardlist a{display:block;padding:8px 0;color:var(--text);text-decoration:none;overflow-wrap:anywhere}
|
||||
.wfg-cardlist a:hover strong{text-decoration:underline}
|
||||
.wfg-cardlist strong{color:var(--action,var(--accent))}
|
||||
.wfg-card [data-wfg-none]{margin:0 0 8px}
|
||||
.wfg-card p:last-child{margin-bottom:0}
|
||||
|
||||
/* SP10 (#1873): editing a workflow in its graph. The bar above the graph holds Unsaved, Discard, Save and
|
||||
Delete workflow; the step panel holds the step actions and the step form; the list page holds New workflow. */
|
||||
html[data-organizations] :is(.wfg-bar,.wfg-step-acts,.wfg-form,.wfg-new) .ws-btn{min-height:32px}
|
||||
html[data-organizations] :is(.wfg-bar,.wfg-form) .ws-btn.primary{background:var(--action);color:var(--onAction);border-color:var(--action)}
|
||||
html[data-organizations] :is(.wfg-bar,.wfg-form) .ws-btn.primary:hover:not(:disabled){background:color-mix(in srgb,var(--action) 88%,var(--strong))}
|
||||
html[data-organizations] :is(.wfg-bar,.wfg-step-acts) .ws-btn.danger{color:var(--danger)}
|
||||
html[data-organizations] :is(.wfg-bar,.wfg-step-acts,.wfg-form,.wfg-new) .ws-btn:focus-visible{outline:2px solid var(--focus);outline-offset:2px}
|
||||
.wfg-bar{display:flex;flex-wrap:wrap;align-items:center;gap:8px 12px;margin:0 0 10px}
|
||||
.wfg-acts{display:inline-flex;flex-wrap:wrap;align-items:center;gap:8px;margin-left:auto}
|
||||
.wfg-bar:not(.is-dirty) .wfg-acts:empty{display:none}
|
||||
.wfg-badge{display:inline-block;padding:2px 8px;border-radius:999px;font-size:12px;font-weight:600;color:var(--strong,var(--text));background:color-mix(in srgb,var(--accent) 18%,var(--surface));border:1px solid color-mix(in srgb,var(--accent) 45%,var(--line))}
|
||||
.wfg-confirm{display:inline-flex;flex-wrap:wrap;align-items:center;gap:8px;font-size:13.5px}
|
||||
.wfg-status,.wfg-stale{flex-basis:100%;margin:0;font-size:13.5px;overflow-wrap:anywhere}
|
||||
.wfg-stale{color:var(--danger)}
|
||||
.wfg-ro{margin:0 0 10px}
|
||||
.wfg-step-acts{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 12px}
|
||||
.wfg-form{display:grid;gap:10px;min-width:0}
|
||||
.wfg-form h2{margin:0}
|
||||
.wfg-form h3{font-size:14px;margin:6px 0 0}
|
||||
.wfg-form>label,.wfg-form label:has(>select){display:grid;gap:4px;font-size:13px;color:var(--muted)}
|
||||
.wfg-form input:not([type=checkbox]),.wfg-form select{font:14px/1.4 var(--font);color:var(--text);background:var(--canvas);border:1px solid var(--line);border-radius:6px;padding:6px 8px;min-width:0;max-width:100%}
|
||||
.wfg-form :is(input,select):focus-visible{outline:2px solid var(--focus);outline-offset:1px}
|
||||
.wfg-form .note{margin:0}
|
||||
.wfg-roles-pick{border:1px solid var(--line);border-radius:8px;padding:8px 12px 10px;margin:0;min-width:0;display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:4px 12px}
|
||||
.wfg-roles-pick legend{font-size:13px;color:var(--muted);padding:0 4px}
|
||||
.wfg-pick-h{grid-column:1/-1;margin:6px 0 0;font-size:12px;color:var(--muted)}
|
||||
.wfg-pick{display:flex;align-items:baseline;gap:6px;font-size:13.5px;color:var(--text);overflow-wrap:anywhere;min-width:0}
|
||||
.wfg-pick input{margin:0;flex:none}
|
||||
.wfg-why{margin:0;color:var(--danger);font-size:13.5px}
|
||||
.wfg-why:empty{display:none}
|
||||
.wfg-form-acts{display:flex;flex-wrap:wrap;gap:8px;margin:0}
|
||||
.wfg-new{margin:0 0 12px}
|
||||
.wfg-newform{margin:0 0 16px}
|
||||
@media (max-width:700px){
|
||||
.wfg-acts{margin-left:0}
|
||||
.wfg-roles-pick{grid-template-columns:minmax(0,1fr)}
|
||||
}
|
||||
@@ -33,7 +33,8 @@
|
||||
const r = await fetch(url, method === 'GET' ? { cache: 'no-store' } : { method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
|
||||
let value = null;
|
||||
try { value = await r.json(); } catch { value = null; }
|
||||
if (!r.ok) throw Error(guidance[value?.error] ?? `The bus refused: ${value?.error ?? 'outcome unknown'}.`);
|
||||
// The refusal code rides on the error, so a caller with its own words for one (the graph editor) can use them.
|
||||
if (!r.ok) throw Object.assign(Error(guidance[value?.error] ?? `The bus refused: ${value?.error ?? 'outcome unknown'}.`), { code: value?.error ?? null });
|
||||
return value;
|
||||
}
|
||||
const plain = v => v !== null && typeof v === 'object' && !Array.isArray(v);
|
||||
@@ -122,6 +123,40 @@
|
||||
}
|
||||
const flowsIn = (s, scope) => scope ? s.data.projects[scope] : s.data.workflows;
|
||||
const target = (s, scope) => scope ? { project: scope } : {};
|
||||
// SP10: the one check, body and write both editors use, the organization page's form and the graph.
|
||||
// A step is {title, state, roles: [names]}. The order of the checks is the form's: the name, a name the
|
||||
// scope already holds, a role that names no current role, then the shape the bus checks (organization-config
|
||||
// checkWorkflows: 1 to 20 steps, each with a title and 1 to 8 distinct roles), named here before the bus
|
||||
// refuses it in general words.
|
||||
const rolesIn = text => String(text ?? '').split(',').map(r => r.trim()).filter(Boolean);
|
||||
function stepRefusal(st, n) {
|
||||
if (!String(st.title ?? '').trim()) return `Step ${n} needs a title.`;
|
||||
if (!st.roles.length) return `Step ${n} needs at least one role.`;
|
||||
if (st.roles.length > 8) return `Step ${n} names ${st.roles.length} roles. A step takes at most eight.`;
|
||||
if (new Set(st.roles).size !== st.roles.length) return `Step ${n} names the same role twice.`;
|
||||
return '';
|
||||
}
|
||||
function refusal(s, { isNew, scope, name, steps }) {
|
||||
if (!NAME.test(name)) return NAME_RULE;
|
||||
// A save is a set: a new workflow under a name the scope already holds would replace it without a word.
|
||||
if (isNew && Object.hasOwn(flowsIn(s, scope) ?? {}, name)) return `A workflow named ${name} already exists here. Edit it instead.`;
|
||||
// E2E6 P2-1: a step role that names no current role is named before the bus refuses it generically.
|
||||
const unknown = steps.flatMap((st, i) => st.roles.filter(r => !s.known.has(r)).map(r => [i + 1, r]));
|
||||
if (unknown.length) return `${unknown.map(([i, r]) => `Step ${i}: ${r}`).join('; ')} ${unknown.length === 1 ? 'names' : 'name'} no current role. Use an organization role, a role template or human.`;
|
||||
if (!steps.length) return 'A workflow needs at least one step.';
|
||||
if (steps.length > 20) return 'A workflow has at most 20 steps.';
|
||||
for (const [i, st] of steps.entries()) { const why = stepRefusal(st, i + 1); if (why) return why; }
|
||||
return '';
|
||||
}
|
||||
const shape = ({ title = '', description = '', steps }) => ({
|
||||
...(title.trim() ? { title: title.trim() } : {}),
|
||||
...(description.trim() ? { description: description.trim() } : {}),
|
||||
steps: steps.map(st => ({ title: st.title.trim(), state: st.state, roles: [...st.roles] })),
|
||||
});
|
||||
const flowUrl = (org, name) => `${base(org)}/workflows/${encodeURIComponent(name)}`;
|
||||
// The revision is the one the editor opened on: a change made since then is a revision-conflict, not overwritten.
|
||||
const saveFlow = (org, s, { scope, name, revision, workflow }) => call(flowUrl(org, name), 'POST', { revision, workflow, ...target(s, scope) });
|
||||
const removeFlow = (org, s, { scope, name, revision }) => call(flowUrl(org, name), 'DELETE', { revision, ...target(s, scope) });
|
||||
async function reload(org, s, status) {
|
||||
try { await read(org, s); s.status = status; } catch (error) { s.status = `${status} ${error.message}`; }
|
||||
}
|
||||
@@ -149,7 +184,7 @@
|
||||
} else if (button.hasAttribute('data-wf-delete-yes')) {
|
||||
button.disabled = true;
|
||||
try {
|
||||
await call(`${base(org)}/workflows/${encodeURIComponent(name)}`, 'DELETE', { revision: s.data.revision, ...target(s, scope) });
|
||||
await removeFlow(org, s, { scope, name, revision: s.data.revision });
|
||||
s.confirm = null;
|
||||
await reload(org, s, `Deleted ${name}.`);
|
||||
} catch (error) { s.status = error.message; }
|
||||
@@ -176,26 +211,550 @@
|
||||
if (!s?.editing) return;
|
||||
capture(root, s);
|
||||
const e = s.editing;
|
||||
if (!NAME.test(e.name)) { s.status = NAME_RULE; redraw(org); return; }
|
||||
// A save is a set: a new workflow under a name the scope already holds would replace it without a word.
|
||||
if (e.isNew && Object.hasOwn(flowsIn(s, e.scope) ?? {}, e.name)) { s.status = `A workflow named ${e.name} already exists here. Edit it instead.`; redraw(org); return; }
|
||||
// E2E6 P2-1: a step role that names no current role is named before the bus refuses it generically.
|
||||
const unknown = e.draft.steps.flatMap((st, i) => st.roles.split(',').map(r => r.trim()).filter(r => r && !s.known.has(r)).map(r => [i + 1, r]));
|
||||
if (unknown.length) { s.status = `${unknown.map(([i, r]) => `Step ${i}: ${r}`).join('; ')} ${unknown.length === 1 ? 'names' : 'name'} no current role. Use an organization role, a role template or human.`; redraw(org); return; }
|
||||
const workflow = {
|
||||
...(e.draft.title.trim() ? { title: e.draft.title.trim() } : {}),
|
||||
...(e.draft.description.trim() ? { description: e.draft.description.trim() } : {}),
|
||||
steps: e.draft.steps.map(st => ({ title: st.title.trim(), state: st.state, roles: st.roles.split(',').map(r => r.trim()).filter(Boolean) })),
|
||||
};
|
||||
const draft = { ...e.draft, steps: e.draft.steps.map(st => ({ ...st, roles: rolesIn(st.roles) })) };
|
||||
const why = refusal(s, { isNew: e.isNew, scope: e.scope, name: e.name, steps: draft.steps });
|
||||
if (why) { s.status = why; redraw(org); return; }
|
||||
const workflow = shape(draft);
|
||||
const button = ev.target.querySelector('button[type="submit"]');
|
||||
button.disabled = true;
|
||||
try {
|
||||
// The revision the editor opened on: a change made since then is a revision-conflict, not overwritten.
|
||||
await call(`${base(org)}/workflows/${encodeURIComponent(e.name)}`, 'POST', { revision: e.revision ?? s.data.revision, workflow, ...target(s, e.scope) });
|
||||
await saveFlow(org, s, { scope: e.scope, name: e.name, revision: e.revision ?? s.data.revision, workflow });
|
||||
s.editing = null;
|
||||
await reload(org, s, `Saved ${e.name}.`);
|
||||
} catch (error) { s.status = error.message; }
|
||||
redraw(org);
|
||||
});
|
||||
window.MosaicWorkflows = { load, section };
|
||||
|
||||
// ---------- SP9 (#1873): the read-only view ----------
|
||||
// #/orgs/<id>/workflows lists the organization's workflows; #/orgs/<id>/workflows/<name>[?project=<p>]
|
||||
// draws one as an inline-SVG graph. The data is the same read as the editor above: each step's title,
|
||||
// state and roles, in file order. A workflow has no edges or branches in the file, so a step hands on to
|
||||
// the next one. Nothing else is drawn: no gate, no inputs and no running mark, because no read gives them.
|
||||
const WS = () => window.MosaicWorkspace;
|
||||
const orgHash = org => `#/orgs/${encodeURIComponent(org)}`;
|
||||
const flowHref = (org, scope, name, step) => {
|
||||
const q = new URLSearchParams();
|
||||
if (scope) q.set('project', scope);
|
||||
if (step) q.set('step', String(step));
|
||||
return `${orgHash(org)}/workflows/${encodeURIComponent(name)}${q.size ? `?${q}` : ''}`;
|
||||
};
|
||||
const stepsOf = w => (Array.isArray(w?.steps) ? w.steps.filter(st => st && typeof st === 'object') : []);
|
||||
const rolesOf = st => (Array.isArray(st?.roles) ? st.roles.filter(r => typeof r === 'string') : []);
|
||||
const count = n => `${n} step${n === 1 ? '' : 's'}`;
|
||||
const stateLabel = st => STATE_LABEL[st?.state] ?? String(st?.state ?? '');
|
||||
const scopeLabel = scope => (scope ? `Project ${scope}` : 'Organization');
|
||||
// Each scope that holds a workflow, the organization first. Names are own keys only.
|
||||
const listed = s => scopes(s).map(([scope, label, flows]) => [scope, label, Object.keys(plain(flows) ? flows : {}).sort().map(n => [n, flows[n]])]);
|
||||
const total = s => listed(s).reduce((n, [, , rows]) => n + rows.length, 0);
|
||||
// The organization's bus state from the membership list, and for one that is down the workspace read's
|
||||
// reason in the Inbox's words (orgsOf + unreadNote, the data-ws-unread note).
|
||||
async function orgOf(org) {
|
||||
const list = await window.MosaicWorkspaceData.organizations().catch(() => null);
|
||||
const row = Array.isArray(list) ? list.find(o => o?.id === org && !o.invalid) : null;
|
||||
if (!row) return { row: null, list: Array.isArray(list) };
|
||||
let unread = '';
|
||||
if (!row.busHealthy) {
|
||||
const body = await window.MosaicWorkspaceData.workspace({ org, sections: 'projects' }).catch(() => null);
|
||||
const o = body ? WS().orgsOf({ orgs: (Array.isArray(body.orgs) ? body.orgs : []).filter(r => r?.org === org) }) : null;
|
||||
unread = o?.unread.length ? WS().unreadNote(o, [], 'workflows')
|
||||
: `<p class="note ws-unread-note" data-ws-unread>Not read: ${esc(row.label || org)} ${row.busStopped ? 'bus stopped' : 'bus not answering'}. No reason was read.</p>`;
|
||||
}
|
||||
return { row, unread, stopped: !row.busHealthy && row.busStopped === true, label: row.label || org };
|
||||
}
|
||||
const head = (title, sub) => `<div class="ws-vh"><h1 tabindex="-1">${title}</h1><p class="sub">${sub}</p></div>`;
|
||||
const applyLink = (org, s) => (s?.data?.writable
|
||||
? `<p><a class="ws-btn" href="${esc(`${orgHash(org)}/organization`)}" data-wfg-apply data-focus-key="wfg-apply">Apply a pack</a></p>`
|
||||
: '<p class="note">A starter pack brings workflows. Only the owner, on a Console started with send, can apply one.</p>');
|
||||
const none = (org, s, label) => `<p class="note" data-wfg-none>No workflows in ${esc(label)} yet.</p>${applyLink(org, s)}`;
|
||||
|
||||
// Layout: left to right on a wide screen, top to bottom on a narrow one. The graph scrolls inside its
|
||||
// own frame when it is wider than the frame; the page never does.
|
||||
const NARROW = '(max-width: 700px)';
|
||||
const narrow = () => window.matchMedia(NARROW).matches;
|
||||
// SP10 (sp9 follow-up): box text is fitted by its measured width in the font it is drawn in, not by a
|
||||
// character count, so a line ends inside its box with an ellipsis and a short name shows whole. The clip
|
||||
// path stays as a backstop. Without a canvas the old per-character estimate is used.
|
||||
let ctx;
|
||||
function measure(text, font, per) {
|
||||
if (ctx === undefined) { try { ctx = document.createElement('canvas').getContext('2d'); } catch { ctx = null; } }
|
||||
if (!ctx) return text.length * per;
|
||||
ctx.font = font;
|
||||
return ctx.measureText(text).width;
|
||||
}
|
||||
const token = (name, fallback) => getComputedStyle(document.documentElement).getPropertyValue(name).trim() || fallback;
|
||||
const fonts = () => ({
|
||||
title: [`600 15px ${token('--font', 'sans-serif')}`, 8.6],
|
||||
roles: [`13px ${token('--mono', 'monospace')}`, 7.9],
|
||||
miss: [`12px ${token('--font', 'sans-serif')}`, 6.8],
|
||||
});
|
||||
function fit(text, [font, per], max) {
|
||||
if (measure(text, font, per) <= max) return text;
|
||||
let lo = 0, hi = text.length;
|
||||
while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (measure(`${text.slice(0, mid)}…`, font, per) <= max) lo = mid; else hi = mid - 1; }
|
||||
return `${text.slice(0, lo)}…`;
|
||||
}
|
||||
// Up to two lines broken at spaces; the second ends in … when the title is longer.
|
||||
function wrap(text, f, max) {
|
||||
const words = String(text ?? '').split(/\s+/).filter(Boolean), lines = [''];
|
||||
let over = false;
|
||||
for (const w of words) {
|
||||
const cur = lines[lines.length - 1], next = cur ? `${cur} ${w}` : w;
|
||||
if (!cur || measure(next, f[0], f[1]) <= max) lines[lines.length - 1] = next;
|
||||
else if (lines.length < 2) lines.push(w);
|
||||
else { lines[1] = `${lines[1]} ${w}`; over = true; }
|
||||
}
|
||||
if (measure(lines[0], f[0], f[1]) > max) return [fit(lines[0], f, max)];
|
||||
if (lines[1] && (over || measure(lines[1], f[0], f[1]) > max)) lines[1] = fit(lines[1], f, max);
|
||||
return lines;
|
||||
}
|
||||
function graph(org, s, scope, name, steps, sel) {
|
||||
const vertical = narrow(), f = fonts();
|
||||
const W = vertical ? 300 : 188, GAP = vertical ? 32 : 36, PAD = 14;
|
||||
// Text runs from x+12 and ends 12px before the box edge; 2px more absorbs a font that loads after the measure.
|
||||
const room = W - 26;
|
||||
// One role a line, at most three lines: with four or more, two roles and "+N more". Every role is in the label and the detail panel.
|
||||
const roleLines = st => { const r = rolesOf(st); return !r.length ? [] : r.length <= 3 ? r : [...r.slice(0, 2), `+${r.length - 2} more`]; };
|
||||
// A role that names no current role: "No current role:" and then each such role on its own line, at most
|
||||
// two lines, so the whole name shows (a name longer than the box ends in …).
|
||||
const missing = st => rolesOf(st).filter(r => !s.known.has(r));
|
||||
const missLines = st => { const m = missing(st); return m.length <= 2 ? m : [m[0], `+${m.length - 1} more`]; };
|
||||
const titleEnd = st => 46 + (wrap(st.title, f.title, room).length - 1) * 19;
|
||||
const rolesY = st => titleEnd(st) + 24;
|
||||
const missY = st => rolesY(st) + (Math.max(roleLines(st).length, 1) - 1) * 17 + 18;
|
||||
// Each box is as tall as the tallest step needs: meta, one or two title lines, its role lines, and the missing-role lines if any.
|
||||
const bottom = st => (missing(st).length ? missY(st) + missLines(st).length * 15 : missY(st) - 18);
|
||||
const H = Math.max(...steps.map(st => bottom(st) + 16));
|
||||
const pos = i => (vertical ? [PAD, PAD + i * (H + GAP)] : [PAD + i * (W + GAP), PAD]);
|
||||
const width = vertical ? W + 2 * PAD : PAD * 2 + steps.length * W + (steps.length - 1) * GAP;
|
||||
const height = vertical ? PAD * 2 + steps.length * H + (steps.length - 1) * GAP : H + 2 * PAD;
|
||||
const edges = steps.slice(1).map((_, i) => {
|
||||
const [x, y] = pos(i), [x2, y2] = pos(i + 1);
|
||||
const d = vertical ? `M${x + W / 2} ${y + H} V${y2 - 3}` : `M${x + W} ${y + H / 2} H${x2 - 3}`;
|
||||
return `<path class="wfg-edge" d="${d}" data-wfg-edge="${i + 1}-${i + 2}" marker-end="url(#wfg-arrow)"/>`;
|
||||
}).join('');
|
||||
const nodes = steps.map((st, i) => {
|
||||
const [x, y] = pos(i), n = i + 1, roles = rolesOf(st), miss = missing(st);
|
||||
const lines = wrap(st.title, f.title, room), on = sel === n;
|
||||
const label = `Step ${n} of ${steps.length}: ${st.title ?? ''}. ${stateLabel(st)}. Roles ${roles.join(', ')}${miss.length ? `; ${miss.join(', ')} ${MISSING}` : ''}.`;
|
||||
const rl = roleLines(st), more = roles.length > 3;
|
||||
const roleText = rl.length
|
||||
? rl.map((r, j) => `<tspan x="${x + 12}" dy="${j ? 17 : 0}"${more && j === rl.length - 1 ? ' data-wfg-more' : ''}>${esc(more && j === rl.length - 1 ? r : fit(r, f.roles, room))}</tspan>`).join('')
|
||||
: '<tspan class="wfg-none">No roles recorded</tspan>';
|
||||
const missText = miss.length
|
||||
? `<text class="wfg-miss" data-wfg-missing x="${x + 12}" y="${y + missY(st)}"><tspan x="${x + 12}" dy="0">No current role:</tspan>${missLines(st).map((r, j) => `<tspan x="${x + 12}" dy="15"${miss.length > 2 && j === 1 ? ' data-wfg-more' : ''}>${esc(miss.length > 2 && j === 1 ? r : fit(r, f.miss, room))}</tspan>`).join('')}</text>`
|
||||
: '';
|
||||
return `<a class="wfg-node${on ? ' is-sel' : ''}" href="${esc(flowHref(org, scope, name, n))}" data-wfg-step="${n}" data-focus-key="${esc(`wfg-step:${n}`)}" aria-label="${esc(label)}"${on ? ' aria-current="step"' : ''}>
|
||||
<title>${esc(`${st.title ?? ''}${roles.length ? ` (${roles.join(', ')})` : ''}`)}</title><rect x="${x}" y="${y}" width="${W}" height="${H}" rx="10"/>
|
||||
<clipPath id="wfg-clip-${n}"><rect x="${x + 2}" y="${y}" width="${W - 10}" height="${H}"/></clipPath>
|
||||
<g clip-path="url(#wfg-clip-${n})">
|
||||
<text class="wfg-meta" x="${x + 12}" y="${y + 22}">${esc(fit(`Step ${n} · ${stateLabel(st)}`, f.miss, room))}</text>
|
||||
<text class="wfg-title" data-wfg-title x="${x + 12}" y="${y + 46}">${lines.map((l, j) => `<tspan x="${x + 12}" dy="${j ? 19 : 0}">${esc(l)}${j < lines.length - 1 ? ' ' : ''}</tspan>`).join('')}</text>
|
||||
<text class="wfg-roles" data-wfg-roles x="${x + 12}" y="${y + rolesY(st)}">${roleText}</text>
|
||||
${missText}</g></a>`;
|
||||
}).join('');
|
||||
return `<svg class="wfg-graph${vertical ? ' is-vertical' : ''}" data-wfg-graph role="group" aria-label="${esc(`${count(steps.length)}, in order`)}" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs><marker id="wfg-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto"><path class="wfg-arrow" d="M0 0L10 5L0 10z"/></marker></defs>${edges}${nodes}</svg>`;
|
||||
}
|
||||
|
||||
// ---------- SP10 (#1873): editing a workflow in its graph ----------
|
||||
// A change is held in the page, not written, until Save: the graph draws the pending workflow, the bar says
|
||||
// Unsaved, and Save sends one POST with the revision the page read (saveFlow, the form's write). A refusal is
|
||||
// shown in words and the pending change kept. The poll redraws from the pending workflow, never over it.
|
||||
// When the file changes while a change is pending: if this workflow is as the page read it, the new revision
|
||||
// is taken (a workflow write sets only this workflow, so nothing else is overwritten); if this workflow
|
||||
// changed, the bar says so and offers Discard. Drafts live per organization until saved or discarded, and
|
||||
// the organization-switch and restart guards ask before dropping one (hasDraft).
|
||||
const drafts = new Map(), notes = new Map(), newForms = new Map();
|
||||
const dkey = (org, scope, name) => JSON.stringify([org, scope, name]);
|
||||
const norm = w => ({
|
||||
title: typeof w?.title === 'string' ? w.title : '', description: typeof w?.description === 'string' ? w.description : '',
|
||||
steps: stepsOf(w).map(st => ({ title: String(st.title ?? ''), state: st.state, roles: rolesOf(st) })),
|
||||
});
|
||||
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
||||
const changed = d => d.isNew || !same(d.flow, d.base);
|
||||
const editDirty = e => !!e && !same({ title: e.title, state: e.state, roles: e.roles }, e.orig);
|
||||
const READ_ONLY = 'Only the owner, on a Console started with send, can change workflows.';
|
||||
// The graph's own words for a refusal where the form's would mislead: the change is kept, not lost.
|
||||
const kept = {
|
||||
'revision-conflict': 'Not saved: the organization file changed since this page read it. Your change is kept. Discard to load the current version.',
|
||||
'organization-busy': 'Not saved: the organization is busy with another write. Your change is kept. Try Save again shortly.',
|
||||
'no-bus-host': 'Not saved: the organization bus is not running. Your change is kept. Save again once it runs.',
|
||||
'invalid-request': 'Not saved: the bus refused the workflow. Check each step has a title, a state and one to eight distinct roles. Your change is kept.',
|
||||
};
|
||||
const say = text => { const live = document.getElementById('announce'); if (live) { live.textContent = ''; live.textContent = text; } };
|
||||
|
||||
// A pending change measured against the fresh read; drops one with nothing left to keep.
|
||||
function settle(org, s, scope, name, fresh) {
|
||||
const key = dkey(org, scope, name), d = drafts.get(key);
|
||||
if (!d) return null;
|
||||
if (d.busy) return d;
|
||||
const now = fresh ? norm(fresh) : null;
|
||||
if (d.isNew) { d.stale = !!fresh; if (!fresh) d.revision = s.data.revision; }
|
||||
else if (now && same(now, d.base)) { d.revision = s.data.revision; d.stale = false; }
|
||||
else if (now && !changed(d)) {
|
||||
Object.assign(d, { base: now, flow: structuredClone(now), revision: s.data.revision, stale: false });
|
||||
if (d.edit?.mode === 'edit' && d.edit.i >= now.steps.length) d.edit = null;
|
||||
} else d.stale = true;
|
||||
if (!changed(d) && !d.edit && !d.confirm && !d.status) { drafts.delete(key); return null; }
|
||||
return d;
|
||||
}
|
||||
function draftFor(org, s, scope, name) {
|
||||
const key = dkey(org, scope, name);
|
||||
if (drafts.has(key)) return drafts.get(key);
|
||||
const fresh = flowsIn(s, scope)?.[name];
|
||||
if (!fresh) return null;
|
||||
const base = norm(fresh), d = { isNew: false, base, flow: structuredClone(base), revision: s.data.revision, edit: null, confirm: false, status: '', busy: false, stale: false };
|
||||
drafts.set(key, d);
|
||||
notes.delete(key);
|
||||
return d;
|
||||
}
|
||||
// The role picker: human, the organization's roles, the role templates, and first any role the step names
|
||||
// that resolves to none of those (checked and marked, so leaving it in is a choice the save check names).
|
||||
function rolePick(s, chosen, prefix) {
|
||||
const defs = [...(s.data.roles.definitions || [])].sort(), tpl = [...(s.data.roles.templates || [])].filter(r => !defs.includes(r)).sort();
|
||||
const odd = chosen.filter(r => !s.known.has(r));
|
||||
const box = (r, mark = '') => `<label class="wfg-pick"><input type="checkbox" name="role" value="${esc(r)}"${chosen.includes(r) ? ' checked' : ''} data-focus-key="${esc(`${prefix}:role:${r}`)}"> <code>${esc(r)}</code>${mark}</label>`;
|
||||
const group = (title, list, mark) => (list.length ? `<p class="wfg-pick-h">${title}</p>${list.map(r => box(r, mark)).join('')}` : '');
|
||||
return `<fieldset class="wfg-roles-pick" data-wfg-roles-pick><legend>Roles, one to eight</legend>
|
||||
${group('Named in this step', odd, ` <span class="wf-missing" data-wfg-pick-missing>${MISSING}</span>`)}${box('human', ' <span class="muted">a person</span>')}
|
||||
${group('This organization\'s roles', defs.filter(r => r !== 'human'), '')}${group('Role templates', tpl.filter(r => r !== 'human'), '')}</fieldset>`;
|
||||
}
|
||||
const stateSelect = (value, key) => `<label>State<select name="state" data-focus-key="${esc(key)}">${STATES.map(([v, l]) => `<option value="${v}"${value === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label>`;
|
||||
function stepForm(org, s, scope, name, d) {
|
||||
const e = d.edit, n = e.i + 1;
|
||||
return `<form class="wfg-form" data-wfg-form data-live-key="${esc(`wfg-form:${org}:${scope}:${name}:${e.mode}:${e.i}`)}" data-live-hold novalidate>
|
||||
<h2 data-wfg-form-title>${e.mode === 'add' ? `New step ${n}` : `Edit step ${n}`}</h2>
|
||||
<label>Title<input name="title" maxlength="120" value="${esc(e.title)}" autocomplete="off" data-focus-key="wfg-f-title"></label>
|
||||
${stateSelect(e.state, 'wfg-f-state')}${rolePick(s, e.roles, 'wfg-f')}
|
||||
<p class="wfg-why" data-wfg-why>${esc(e.why ?? '')}</p>
|
||||
<p class="wfg-form-acts"><button type="submit" class="ws-btn primary" data-wfg-apply data-focus-key="wfg-f-apply">${e.mode === 'add' ? 'Add step' : 'Apply'}</button> <button type="button" class="ws-btn" data-wfg-cancel data-focus-key="wfg-f-cancel">Cancel</button></p>
|
||||
<p class="note">Apply changes the graph on this page. Save writes it to the organization file.</p></form>`;
|
||||
}
|
||||
function bar(org, s, scope, name, d) {
|
||||
if (!s.data.writable) return `<p class="note wfg-ro" data-wfg-readonly>${READ_ONLY}</p>`;
|
||||
const dirty = !!d && changed(d), busy = d?.busy ? ' disabled' : '';
|
||||
const status = d?.status || notes.get(dkey(org, scope, name)) || '';
|
||||
const stale = d?.stale ? `<p class="wfg-stale" data-wfg-stale>${d.isNew ? `A workflow named ${esc(name)} now exists here. Save will be refused. Discard to drop this one.` : 'The organization file changed this workflow since the page read it. Save will be refused. Discard to load the current version.'}</p>` : '';
|
||||
const acts = d?.confirm
|
||||
? `<span class="wfg-confirm" data-wfg-confirm>Delete ${esc(name)} from the organization file? <button type="button" class="ws-btn danger" data-wfg-delete-yes data-focus-key="wfg-delete-yes"${busy}>Delete workflow</button> <button type="button" class="ws-btn" data-wfg-delete-no data-focus-key="wfg-delete-no"${busy}>Keep</button></span>`
|
||||
: `${dirty ? `<button type="button" class="ws-btn" data-wfg-discard data-focus-key="wfg-discard"${busy}>Discard</button> <button type="button" class="ws-btn primary" data-wfg-save data-focus-key="wfg-save"${busy}>${d.busy ? 'Saving…' : 'Save'}</button>` : ''}${d?.isNew ? '' : ` <button type="button" class="ws-btn danger" data-wfg-delete data-focus-key="wfg-delete"${busy}>Delete workflow</button>`}`;
|
||||
return `<div class="wfg-bar${dirty ? ' is-dirty' : ''}" data-wfg-bar>${dirty ? `<span class="wfg-badge" data-wfg-unsaved>Unsaved${d.isNew ? ', not in the file yet' : ''}</span>` : ''}<span class="wfg-acts">${acts}</span>
|
||||
${status ? `<p class="wfg-status" data-wfg-status>${esc(status)}</p>` : ''}${stale}</div>`;
|
||||
}
|
||||
const stepRef = (org, scope, name, steps, n) => `<a href="${esc(flowHref(org, scope, name, n))}" data-wfg-go="${n}">Step ${n}, ${esc(steps[n - 1].title)}</a>`;
|
||||
function actions(steps, sel, d) {
|
||||
const busy = d?.busy ? ' disabled' : '';
|
||||
if (!sel) return `<p class="wfg-step-acts" data-wfg-actions><button type="button" class="ws-btn" data-wfg-add data-focus-key="wfg-add"${busy}>Add a step at the end</button></p>`;
|
||||
const dis = c => (c || d?.busy ? ' disabled' : '');
|
||||
return `<p class="wfg-step-acts" data-wfg-actions><button type="button" class="ws-btn" data-wfg-edit data-focus-key="wfg-edit"${busy}>Edit step</button>
|
||||
<button type="button" class="ws-btn" data-wfg-add data-focus-key="wfg-add"${dis(steps.length >= 20)}>Add a step after</button>
|
||||
<button type="button" class="ws-btn" data-wfg-up data-focus-key="wfg-up"${dis(sel === 1)}>Move earlier</button>
|
||||
<button type="button" class="ws-btn" data-wfg-down data-focus-key="wfg-down"${dis(sel === steps.length)}>Move later</button>
|
||||
<button type="button" class="ws-btn danger" data-wfg-remove data-focus-key="wfg-remove"${dis(steps.length === 1)}>Remove step</button></p>`;
|
||||
}
|
||||
function detail(org, s, scope, name, steps, sel, d) {
|
||||
const writable = !!s.data.writable;
|
||||
if (writable && d?.edit) return `<section class="panel wfg-detail" data-wfg-detail>${stepForm(org, s, scope, name, d)}</section>`;
|
||||
if (!sel) return `<section class="panel wfg-detail" data-wfg-detail><h2>Step details</h2><p class="note">Select a step to see its roles, the state it puts a task in and the step it hands on to.</p>${writable ? actions(steps, 0, d) : ''}</section>`;
|
||||
const st = steps[sel - 1], roles = rolesOf(st);
|
||||
const roleList = roles.map(r => r === 'human' ? '<code>human</code> (a person)' : s.known.has(r) ? `<code>${esc(r)}</code>` : `<code>${esc(r)}</code> <span class="wf-missing" data-wfg-missing>${MISSING}</span>`).join(', ');
|
||||
return `<section class="panel wfg-detail" data-wfg-detail><h2 data-wfg-detail-title>${esc(st.title)}</h2><dl class="wfg-dl">
|
||||
<dt>Position</dt><dd data-wfg-field="position">Step ${sel} of ${steps.length}</dd>
|
||||
<dt>Roles</dt><dd data-wfg-field="roles">${roleList || '<span class="muted">None recorded</span>'}</dd>
|
||||
<dt>Puts the task in</dt><dd data-wfg-field="state">${esc(stateLabel(st))}</dd>
|
||||
<dt>Comes after</dt><dd data-wfg-field="after">${sel > 1 ? stepRef(org, scope, name, steps, sel - 1) : 'Nothing: this is the first step'}</dd>
|
||||
<dt>Hands on to</dt><dd data-wfg-field="next">${sel < steps.length ? stepRef(org, scope, name, steps, sel + 1) : 'Nothing: this is the last step'}</dd>
|
||||
</dl>${writable ? actions(steps, sel, d) : ''}<p class="note">The workflow file records no gate or inputs for a step, and no read says which step a task is on now.</p></section>`;
|
||||
}
|
||||
function graphBody(org, s, name, q) {
|
||||
const scope = q.get('project') || '';
|
||||
if (scope && !Object.hasOwn(s.data.projects, scope)) return { title: esc(name), sub: '', body: `<p class="note" data-wfg-unknown>No code project named ${esc(scope)} in the organization file.</p>` };
|
||||
const flows = flowsIn(s, scope), fresh = plain(flows) && Object.hasOwn(flows, name) ? flows[name] : null;
|
||||
const d = s.data.writable ? settle(org, s, scope, name, fresh) : null;
|
||||
const note = notes.get(dkey(org, scope, name));
|
||||
if (!fresh && !d) return { title: esc(name), sub: '', body: `${note ? `<p class="wfg-status" data-wfg-status>${esc(note)}</p>` : ''}<p class="note" data-wfg-unknown>No workflow named ${esc(name)} in ${scope ? `project ${esc(scope)}` : 'the organization'}.</p>` };
|
||||
const w = d ? d.flow : norm(fresh), steps = w.steps;
|
||||
const raw = Number(q.get('step')), sel = Number.isInteger(raw) && raw >= 1 && raw <= steps.length ? raw : 0;
|
||||
const sub = `${esc(scopeLabel(scope))}, <code>${esc(name)}</code>, ${count(steps.length)}.${w.description ? ` ${esc(w.description)}` : ''}`;
|
||||
const body = steps.length
|
||||
? `${bar(org, s, scope, name, d)}<div class="wfg-frame" data-wfg-frame>${graph(org, s, scope, name, steps, sel)}</div>${detail(org, s, scope, name, steps, sel, d)}`
|
||||
: `${bar(org, s, scope, name, d)}<p class="note">This workflow has no steps.</p>`;
|
||||
return { title: esc(w.title || name), sub, body };
|
||||
}
|
||||
|
||||
// The list page's New workflow form: where, a name, and the first step. Create opens it in the graph, unsaved.
|
||||
function newForm(org, s) {
|
||||
const f = newForms.get(org);
|
||||
if (!f) return `<p class="wfg-new"><button type="button" class="ws-btn" data-wfg-new data-focus-key="wfg-new">New workflow</button></p>`;
|
||||
return `<form class="wfg-form wfg-newform panel" data-wfg-form data-wfg-newform data-live-key="${esc(`wfg-new:${org}`)}" data-live-hold novalidate>
|
||||
<h2>New workflow</h2>
|
||||
<label>Where<select name="scope" data-focus-key="wfg-n-scope">${scopes(s).map(([v, l]) => `<option value="${esc(v)}"${f.scope === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label>
|
||||
<label>Name<input name="name" maxlength="64" value="${esc(f.name)}" autocomplete="off" placeholder="lowercase letters, digits, dashes" data-focus-key="wfg-n-name"></label>
|
||||
<p class="note">${NAME_RULE}</p>
|
||||
<h3>First step</h3>
|
||||
<label>Title<input name="title" maxlength="120" value="${esc(f.title)}" autocomplete="off" data-focus-key="wfg-n-title"></label>
|
||||
${stateSelect(f.state, 'wfg-n-state')}${rolePick(s, f.roles, 'wfg-n')}
|
||||
<p class="wfg-why" data-wfg-why>${esc(f.why ?? '')}</p>
|
||||
<p class="wfg-form-acts"><button type="submit" class="ws-btn primary" data-wfg-create data-focus-key="wfg-n-create">Create</button> <button type="button" class="ws-btn" data-wfg-new-cancel data-focus-key="wfg-n-cancel">Cancel</button></p>
|
||||
<p class="note">Create opens it in its graph. It is written to the organization file when you save it there.</p></form>`;
|
||||
}
|
||||
// The rows each scope lists: the file's workflows, and any new one not saved yet.
|
||||
function rowsWithDrafts(org, s) {
|
||||
return listed(s).map(([scope, label, rows]) => {
|
||||
const names = new Set(rows.map(([n]) => n));
|
||||
const fresh = [...drafts.entries()].map(([k, d]) => [JSON.parse(k), d]).filter(([[o, sc, n], d]) => o === org && sc === scope && d.isNew && !names.has(n)).map(([[, , n], d]) => [n, d.flow]);
|
||||
return [scope, label, [...rows, ...fresh].sort(([p], [q]) => (p < q ? -1 : p > q ? 1 : 0))];
|
||||
});
|
||||
}
|
||||
function listBody(org, s, label) {
|
||||
const writable = !!s.data.writable, rows = writable ? rowsWithDrafts(org, s) : listed(s);
|
||||
const top = `${notes.has(dkey(org, '', '')) ? `<p class="wfg-status" data-wfg-status>${esc(notes.get(dkey(org, '', '')))}</p>` : ''}${writable ? newForm(org, s) : `<p class="note wfg-ro" data-wfg-readonly>${READ_ONLY}</p>`}`;
|
||||
if (!rows.some(([, , r]) => r.length)) return `${top}${none(org, s, label)}`;
|
||||
return top + rows.filter(([scope, , r]) => !scope || r.length).map(([scope, label2, r]) => `<section class="wfg-scope" data-wfg-scope-list="${esc(scope)}"><h2>${esc(label2)}</h2>${r.length ? `<ul class="wfg-list">${r.map(([name, w]) => {
|
||||
const steps = stepsOf(w), d = drafts.get(dkey(org, scope, name)), pending = d && changed(d);
|
||||
return `<li class="wfg-item" data-wfg-item="${esc(name)}" data-wfg-scope="${esc(scope)}"><div class="wfg-item-h"><a href="${esc(flowHref(org, scope, name))}" data-wfg-open data-focus-key="${esc(`wfg-open:${scope}:${name}`)}">${esc(w?.title || name)}</a>${w?.title ? ` <code>${esc(name)}</code>` : ''} <span class="muted">${count(steps.length)}</span>${pending ? ` <span class="wfg-badge" data-wfg-unsaved>Unsaved${d.isNew ? ', not in the file yet' : ''}</span>` : ''}</div>
|
||||
${w?.description ? `<p class="wfg-desc">${esc(w.description)}</p>` : ''}<ol class="wfg-chain" data-wfg-chain aria-label="Steps in order">${steps.map(st => `<li>${esc(st.title)}</li>`).join('')}</ol></li>`;
|
||||
}).join('')}</ul>` : '<p class="note">None at the organization level.</p>'}</section>`).join('');
|
||||
}
|
||||
|
||||
// The page for #/orgs/<org>/workflows (name null) or #/orgs/<org>/workflows/<name>. page() reads; compose()
|
||||
// draws from what was read, so an edit on the page redraws at once (paint) without waiting for a read.
|
||||
const shown = { org: null, name: null, info: null };
|
||||
function compose(org, name, q, info) {
|
||||
const attr = name === null ? 'data-wfg-list' : 'data-wfg-page';
|
||||
const wrapIt = (title, sub, body) => `<article class="ws wfg" ${attr} data-wfg-org="${esc(org)}"${name === null ? '' : ` data-wfg-name="${esc(name)}"`}>${head(title, sub)}${info.unread}${body}</article>`;
|
||||
// Review P3: a change held for this organization that the page cannot draw now is said to be kept.
|
||||
const held = [...drafts].filter(([k, d]) => JSON.parse(k)[0] === org && (changed(d) || editDirty(d.edit))).map(([k]) => JSON.parse(k)[2]);
|
||||
const keptNote = held.length ? `<p class="note" data-wfg-held>Unsaved change to ${held.map(n => esc(n)).join(', ')} is kept on this page. It comes back when the workflows can be read.</p>` : '';
|
||||
// E2E6 P2-8: a stopped bus is not read; the note above says why.
|
||||
if (info.stopped) return wrapIt(name === null ? 'Workflows' : esc(name), `Workflows in ${esc(info.label)}.`, keptNote);
|
||||
const s = states.get(org);
|
||||
if (!s?.data) return wrapIt(name === null ? 'Workflows' : esc(name), `Workflows in ${esc(info.label)}.`, `<p class="note" data-wfg-error>${esc(s?.error ?? 'Workflows could not be read.')}</p>${keptNote}`);
|
||||
if (name === null) return wrapIt('Workflows', `The steps a task goes through in ${esc(info.label)}, in order, with the roles that do each.${s.data.writable ? ' Open one to change it.' : ''}`, listBody(org, s, info.label));
|
||||
const g = graphBody(org, s, name, q);
|
||||
return wrapIt(g.title, g.sub, g.body);
|
||||
}
|
||||
async function page(org, name, q) {
|
||||
const info = await orgOf(org);
|
||||
if (!info.row) return `<article class="ws wfg" ${name === null ? 'data-wfg-list' : 'data-wfg-page'} data-wfg-org="${esc(org)}">${head('Organization unavailable', info.list ? 'This organization is not on your list.' : 'The organization list could not be read.')}</article>`;
|
||||
if (!info.stopped) await load(org);
|
||||
Object.assign(shown, { org, name, info });
|
||||
return compose(org, name, q, info);
|
||||
}
|
||||
const query = () => new URLSearchParams(location.hash.split('?')[1] || '');
|
||||
// Redraw the open workflow page from the page's state, then put focus on `focus` (a data-focus-key).
|
||||
function paint(focus) {
|
||||
const el = document.querySelector('#bus-view [data-wfg-list], #bus-view [data-wfg-page]');
|
||||
if (!el || !shown.info || el.dataset.wfgOrg !== shown.org || (el.dataset.wfgName ?? null) !== shown.name) return;
|
||||
el.outerHTML = compose(shown.org, shown.name, query(), shown.info);
|
||||
const el2 = focus && document.querySelector(`#bus-view [data-focus-key="${CSS.escape(focus)}"]`);
|
||||
if (!el2) return;
|
||||
el2.focus();
|
||||
// A text field takes focus with the caret after its text, ready to change it.
|
||||
if (el2.matches('input:not([type=checkbox])')) el2.setSelectionRange(el2.value.length, el2.value.length);
|
||||
}
|
||||
// The open graph page: its organization, scope, name, read and pending change.
|
||||
function here(el) {
|
||||
const root = el.closest('[data-wfg-page]');
|
||||
if (!root || root.dataset.wfgOrg !== shown.org) return null;
|
||||
const org = shown.org, name = shown.name, scope = query().get('project') || '', s = states.get(org);
|
||||
if (!s?.data?.writable) return null;
|
||||
return { org, name, scope, s, key: dkey(org, scope, name) };
|
||||
}
|
||||
const selected = () => { const n = Number(query().get('step')); return Number.isInteger(n) && n > 0 ? n : 0; };
|
||||
const select = step => WS()?.setQuery?.({ step: step || null }, false);
|
||||
function openForm(d, mode, i, st) {
|
||||
const roles = st ? [...st.roles] : [];
|
||||
d.edit = { mode, i, title: st?.title ?? '', state: st?.state ?? 'todo', roles, why: '', orig: { title: st?.title ?? '', state: st?.state ?? 'todo', roles: [...roles] } };
|
||||
}
|
||||
function readForm(form, into) {
|
||||
into.title = form.elements.title.value;
|
||||
into.state = form.elements.state.value;
|
||||
into.roles = [...form.querySelectorAll('input[name="role"]:checked')].map(i => i.value);
|
||||
if (form.elements.scope) into.scope = form.elements.scope.value;
|
||||
if (form.elements.name) into.name = form.elements.name.value.trim();
|
||||
}
|
||||
function why(form, into, text) {
|
||||
into.why = text;
|
||||
// Direct text: the form may be the held node a repaint grafted back.
|
||||
const p = form.querySelector('[data-wfg-why]');
|
||||
if (p) p.textContent = text;
|
||||
say(text);
|
||||
}
|
||||
|
||||
document.addEventListener('click', async ev => {
|
||||
const btn = ev.target.closest('[data-wfg-new],[data-wfg-new-cancel],[data-wfg-edit],[data-wfg-add],[data-wfg-up],[data-wfg-down],[data-wfg-remove],[data-wfg-cancel],[data-wfg-discard],[data-wfg-save],[data-wfg-delete],[data-wfg-delete-no],[data-wfg-delete-yes]');
|
||||
if (!btn || btn.disabled) return;
|
||||
if (btn.matches('[data-wfg-new],[data-wfg-new-cancel]')) {
|
||||
const org = btn.closest('[data-wfg-list]')?.dataset.wfgOrg;
|
||||
if (!org || org !== shown.org) return;
|
||||
if (btn.hasAttribute('data-wfg-new')) { newForms.set(org, { scope: '', name: '', title: '', state: 'todo', roles: [], why: '' }); notes.delete(dkey(org, '', '')); paint('wfg-n-name'); }
|
||||
else { newForms.delete(org); paint('wfg-new'); }
|
||||
return;
|
||||
}
|
||||
const at = here(btn);
|
||||
if (!at) return;
|
||||
const { org, name, scope, s, key } = at;
|
||||
const sel = selected();
|
||||
if (btn.hasAttribute('data-wfg-discard')) {
|
||||
const d = drafts.get(key);
|
||||
drafts.delete(key);
|
||||
if (d?.isNew) { location.hash = `${orgHash(org)}/workflows`; return; }
|
||||
say(`Discarded the change to ${name}.`);
|
||||
return paint('wfg-delete');
|
||||
}
|
||||
if (btn.hasAttribute('data-wfg-save')) return save(at, btn);
|
||||
if (btn.matches('[data-wfg-delete-yes]')) return remove(at);
|
||||
const d = draftFor(org, s, scope, name) ?? drafts.get(key);
|
||||
if (!d) return;
|
||||
d.status = '';
|
||||
const steps = d.flow.steps;
|
||||
if (btn.hasAttribute('data-wfg-edit') && steps[sel - 1]) { openForm(d, 'edit', sel - 1, steps[sel - 1]); return paint('wfg-f-title'); }
|
||||
if (btn.hasAttribute('data-wfg-add')) { openForm(d, 'add', sel ? sel : steps.length, null); return paint('wfg-f-title'); }
|
||||
if (btn.hasAttribute('data-wfg-cancel')) { const back = d.edit?.mode === 'edit' ? d.edit.i + 1 : sel; d.edit = null; select(back); return paint(back ? `wfg-step:${back}` : 'wfg-add'); }
|
||||
if (btn.matches('[data-wfg-up],[data-wfg-down]') && steps[sel - 1]) {
|
||||
const to = btn.hasAttribute('data-wfg-up') ? sel - 1 : sel + 1;
|
||||
if (to < 1 || to > steps.length) return;
|
||||
[steps[sel - 1], steps[to - 1]] = [steps[to - 1], steps[sel - 1]];
|
||||
select(to);
|
||||
say(`Moved step ${sel} to position ${to}.`);
|
||||
const key2 = btn.hasAttribute('data-wfg-up') ? (to > 1 ? 'wfg-up' : 'wfg-down') : (to < steps.length ? 'wfg-down' : 'wfg-up');
|
||||
return paint(key2);
|
||||
}
|
||||
if (btn.hasAttribute('data-wfg-remove') && steps[sel - 1] && steps.length > 1) {
|
||||
const [gone] = steps.splice(sel - 1, 1);
|
||||
const next = Math.min(sel, steps.length);
|
||||
select(next);
|
||||
say(`Removed step ${sel}, ${gone.title}.`);
|
||||
return paint(`wfg-step:${next}`);
|
||||
}
|
||||
if (btn.hasAttribute('data-wfg-delete')) { d.confirm = true; return paint('wfg-delete-no'); }
|
||||
if (btn.hasAttribute('data-wfg-delete-no')) { d.confirm = false; return paint('wfg-delete'); }
|
||||
});
|
||||
async function save({ org, name, scope, s, key }) {
|
||||
const d = drafts.get(key);
|
||||
if (!d || d.busy) return;
|
||||
// Review P2: the open step form's edits are not in the workflow yet; saving now would drop them unsaid.
|
||||
const refused = (editDirty(d.edit) ? `Not saved: step ${d.edit.i + 1} has edits not applied. Apply or cancel the step first.` : '')
|
||||
|| refusal(s, { isNew: d.isNew, scope, name, steps: d.flow.steps });
|
||||
if (refused) { d.status = refused; say(refused); return paint('wfg-save'); }
|
||||
d.busy = true; d.status = 'Saving…'; paint();
|
||||
try {
|
||||
await saveFlow(org, s, { scope, name, revision: d.revision, workflow: shape(d.flow) });
|
||||
drafts.delete(key);
|
||||
notes.set(key, `Saved ${name}.`);
|
||||
try { await read(org, states.get(org) ?? s); } catch { /* the next poll reads it */ }
|
||||
say(`Saved ${name}.`);
|
||||
paint(selected() ? `wfg-step:${selected()}` : 'wfg-delete');
|
||||
} catch (error) {
|
||||
d.busy = false;
|
||||
d.status = kept[error.code] ?? `Not saved: ${error.message} Your change is kept.`;
|
||||
say(d.status);
|
||||
paint('wfg-save');
|
||||
}
|
||||
}
|
||||
async function remove({ org, name, scope, s, key }) {
|
||||
const d = drafts.get(key);
|
||||
if (!d || d.busy) return;
|
||||
d.busy = true; paint();
|
||||
try {
|
||||
// The revision of the workflow the page shows (settle moves it on only while this workflow is unchanged):
|
||||
// a change made to it since is refused, not deleted over.
|
||||
await removeFlow(org, s, { scope, name, revision: d.revision });
|
||||
drafts.delete(key);
|
||||
notes.set(dkey(org, '', ''), `Deleted ${name}.`);
|
||||
say(`Deleted ${name}.`);
|
||||
try { await read(org, s); } catch { /* the next poll reads it */ }
|
||||
location.hash = `${orgHash(org)}/workflows`;
|
||||
} catch (error) {
|
||||
d.busy = false; d.confirm = false;
|
||||
// Recheck B: Discard shows only with a pending change; without one the next read draws the current version.
|
||||
d.status = error.code === 'revision-conflict' ? `Not deleted: the organization file changed this workflow since the page read it. ${changed(d) ? 'Discard to load the current version.' : 'The page shows the current version at its next read.'}` : `Not deleted: ${error.message}`;
|
||||
say(d.status);
|
||||
paint('wfg-delete');
|
||||
}
|
||||
}
|
||||
// Every change in a form goes into the page's state at once, so any repaint draws what was entered.
|
||||
document.addEventListener('input', ev => {
|
||||
const form = ev.target.closest('[data-wfg-form]');
|
||||
if (!form) return;
|
||||
if (form.matches('[data-wfg-newform]')) { const f = newForms.get(shown.org); if (f) readForm(form, f); return; }
|
||||
const at = here(form), d = at && drafts.get(at.key);
|
||||
if (d?.edit) readForm(form, d.edit);
|
||||
});
|
||||
document.addEventListener('submit', ev => {
|
||||
const form = ev.target.closest?.('[data-wfg-form]');
|
||||
if (!form) return;
|
||||
ev.preventDefault();
|
||||
if (form.matches('[data-wfg-newform]')) {
|
||||
const org = shown.org, s = states.get(org), f = newForms.get(org);
|
||||
if (!f || !s?.data?.writable) return;
|
||||
readForm(form, f);
|
||||
const step = { title: f.title, state: f.state, roles: f.roles };
|
||||
const refused = refusal(s, { isNew: true, scope: f.scope, name: f.name, steps: [step] })
|
||||
|| (drafts.get(dkey(org, f.scope, f.name))?.isNew ? `A new workflow named ${f.name} is already open here, not saved yet.` : '');
|
||||
if (refused) return why(form, f, refused);
|
||||
drafts.set(dkey(org, f.scope, f.name), { isNew: true, base: null, flow: { title: '', description: '', steps: [{ ...step, title: step.title.trim() }] }, revision: s.data.revision, edit: null, confirm: false, status: '', busy: false, stale: false });
|
||||
newForms.delete(org);
|
||||
notes.delete(dkey(org, f.scope, f.name));
|
||||
location.hash = flowHref(org, f.scope, f.name, 1);
|
||||
return;
|
||||
}
|
||||
const at = here(form), d = at && drafts.get(at.key);
|
||||
if (!d?.edit) return;
|
||||
readForm(form, d.edit);
|
||||
const e = d.edit, st = { title: e.title.trim(), state: e.state, roles: e.roles };
|
||||
const refused = stepRefusal(st, e.i + 1);
|
||||
if (refused) return why(form, e, refused);
|
||||
if (e.mode === 'add') d.flow.steps.splice(e.i, 0, st); else d.flow.steps[e.i] = st;
|
||||
d.edit = null; d.status = '';
|
||||
select(e.i + 1);
|
||||
say(`${e.mode === 'add' ? 'Added' : 'Changed'} step ${e.i + 1}. Not saved yet.`);
|
||||
paint('wfg-save');
|
||||
});
|
||||
// Escape in a step form is Cancel.
|
||||
document.addEventListener('keydown', ev => {
|
||||
if (ev.key !== 'Escape') return;
|
||||
const form = ev.target.closest?.('[data-wfg-form]:not([data-wfg-newform])');
|
||||
form?.querySelector('[data-wfg-cancel]')?.click();
|
||||
});
|
||||
// The organization-switch and restart guards (display.js, console-restart.js) ask before these are lost.
|
||||
function hasDraft() {
|
||||
return [...drafts.values()].some(d => changed(d) || editDirty(d.edit))
|
||||
|| [...newForms.values()].some(f => f.name || f.title.trim() || f.roles.length);
|
||||
}
|
||||
function forget() { drafts.clear(); newForms.clear(); }
|
||||
// The organization page's card: each workflow as a link to its graph, from the page's one workflow read.
|
||||
function card(org, { stopped = false, label = org } = {}) {
|
||||
const all = `<a href="${esc(`${orgHash(org)}/workflows`)}" data-wfg-all data-focus-key="wfg-all">All workflows</a>`;
|
||||
const h = note => `<div class="ws-sec-h"><h2>Workflows</h2>${note ? `<span class="note">${note}</span>` : ''}${all}</div>`;
|
||||
if (stopped) return `<div class="wfg-card" data-wfg-card data-bus-stopped>${h('')}<p class="ws-panel tight note">Not read: the bus is stopped.</p></div>`;
|
||||
const s = states.get(org);
|
||||
if (!s?.data) return `<div class="wfg-card" data-wfg-card>${h('')}<p class="ws-panel tight note" data-wfg-error>${esc(s?.error ?? 'Workflows could not be read.')}</p></div>`;
|
||||
const rows = listed(s).flatMap(([scope, , list]) => list.map(([name, w]) => [scope, name, w]));
|
||||
if (!rows.length) return `<div class="wfg-card" data-wfg-card>${h('none')}<div class="ws-panel tight">${none(org, s, label)}</div></div>`;
|
||||
return `<div class="wfg-card" data-wfg-card>${h(String(rows.length))}<ul class="ws-panel tight wfg-cardlist">${rows.map(([scope, name, w]) => `<li><a href="${esc(flowHref(org, scope, name))}" data-wfg-card-item data-focus-key="${esc(`wfg-card:${scope}:${name}`)}"><strong>${esc(w?.title || name)}</strong> <span class="muted">${count(stepsOf(w).length)}${scope ? `, project ${esc(scope)}` : ''}</span></a></li>`).join('')}</ul></div>`;
|
||||
}
|
||||
// A step box or a step link in the details selects that step in the address (setQuery repaints).
|
||||
document.addEventListener('click', ev => {
|
||||
const link = ev.target.closest('[data-wfg-step],[data-wfg-go]');
|
||||
if (link && WS()?.setQuery && ev.button === 0 && !ev.metaKey && !ev.ctrlKey && !ev.shiftKey && !ev.altKey) {
|
||||
ev.preventDefault();
|
||||
WS().setQuery({ step: link.dataset.wfgStep ?? link.dataset.wfgGo });
|
||||
return;
|
||||
}
|
||||
// Apply a pack: the pack picker on the organization page, scrolled into view.
|
||||
const apply = ev.target.closest('[data-wfg-apply]');
|
||||
if (!apply || ev.button !== 0 || ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return;
|
||||
const show = () => { const p = document.querySelector('[data-packs]'); if (!p) return false; p.scrollIntoView({ block: 'start' }); return true; };
|
||||
if (location.hash === apply.getAttribute('href') && show()) { ev.preventDefault(); return; }
|
||||
const until = Date.now() + 8000;
|
||||
const wait = () => { if (location.hash === apply.getAttribute('href') && document.querySelector('[data-org-dashboard] [data-packs]')) setTimeout(show, 0); else if (Date.now() < until) setTimeout(wait, 60); };
|
||||
setTimeout(wait, 60);
|
||||
});
|
||||
// Crossing the narrow breakpoint redraws the graph in the other direction.
|
||||
window.matchMedia(NARROW).addEventListener('change', () => {
|
||||
if (document.querySelector('[data-wfg-graph]')) document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
|
||||
});
|
||||
window.MosaicWorkflows = { load, section, page, card, hasDraft, forget };
|
||||
})();
|
||||
@@ -68,6 +68,12 @@
|
||||
// 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` : ''}`;
|
||||
const activity = (name, item, agents) => {
|
||||
const on = running(item) > 0;
|
||||
const held = on && agents ? agents.find(a => a?.role === name && item.running.includes(a.holder_run)) : null;
|
||||
@@ -156,7 +162,7 @@
|
||||
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 = '') => `<div class="ws-sec-h"><h2>${title}</h2>${note ? `<span class="note">${note}</span>` : ''}${link}</div>`;
|
||||
const secH = (title, note = '', link = '', attrs = '') => `<div class="ws-sec-h"><h2${attrs ? ` ${attrs}` : ''}>${title}</h2>${note ? `<span class="note">${note}</span>` : ''}${link}</div>`;
|
||||
|
||||
function settingsList(org, ctx) {
|
||||
const { business, settings, instances, orgCount } = ctx;
|
||||
@@ -236,21 +242,19 @@
|
||||
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. A side-by-side pane has no restart.
|
||||
function downBanner(org, row, pane = false) {
|
||||
// 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 = pane ? '' : window.MosaicConsole?.busButton?.('Restart the bus') || '';
|
||||
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>`;
|
||||
}
|
||||
// A side-by-side pane passes its own organization and { pane: true, idPrefix }: the pane has no bus
|
||||
// restart (that stays in the organization's full view) and its ids carry the pane's prefix.
|
||||
async function dashboard(id = window.MosaicOrg.id, opts = {}) {
|
||||
const pane = opts.pane === true, why = `${opts.idPrefix || ''}ws-reload-why`;
|
||||
async function dashboard(id = window.MosaicOrg.id) {
|
||||
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;
|
||||
@@ -258,47 +262,77 @@
|
||||
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);
|
||||
const reads = await Promise.allSettled([data.business(id), data.settings(id), data.instances(id), data.threads(id), data.projects(id), data.queue(id), data.agents(id), data.claims(id), ...(stopped ? [] : [window.MosaicAutonomy?.load(id), window.MosaicPacks?.load(id), window.MosaicWorkflows?.load(id)])]);
|
||||
const value = i => (reads[i].status === 'fulfilled' ? reads[i].value : null);
|
||||
const business = value(0), settings = value(1), instances = instancesOf(value(2));
|
||||
const threads = rowsOf(value(3)), projectRows = rowsOf(value(4)), queue = rowsOf(value(5));
|
||||
const agents = rowsOf(value(6)), claims = rowsOf(value(7));
|
||||
const docRead = business?.business ? await docs(id, business.business.projects).catch(() => ({ rows: [], failed: true })) : null;
|
||||
// SP1: a bus that is down says so above everything else, with the reason the workspace read gives.
|
||||
const downRow = org.busHealthy ? null : await data.workspace({ org: id, sections: 'projects' }).then(b => arr(b?.orgs).find(r => r?.org === id) ?? null).catch(() => 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.
|
||||
const restart = pane ? '' : window.MosaicConsole?.busButton?.('Restart bus', { stop: true, glyph: icon('restart') }) || '';
|
||||
const offTitle = pane ? "Restart the bus from this organization's full view" : "Restarting the bus is the owner's trailed action, on a Console started with send and the action trail";
|
||||
const stopTitle = pane ? "Stop the bus from this organization's full view" : "Stopping the bus is the owner's trailed action, on a Console started with send and the action trail";
|
||||
const bus = restart ? `<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>`;
|
||||
const reload = `<button type="button" class="ws-btn" data-org-reload data-focus-key="org-reload" disabled aria-describedby="${esc(why)}" title="Reload arrives with the cross-org update">${icon('doc')}Reload organization file</button>`;
|
||||
// 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)}">Restart is a trailed human action; reload arrives with the cross-org update.</span></p>`;
|
||||
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>`;
|
||||
|
||||
const tiles = (title, note, empty) => `${secH(title, note)}<div class="ws-tiles"><div class="ws-tile is-empty"><span class="ws-empty-t">${empty}</span></div></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;
|
||||
const agentsWhy = whyNot(['agents'], false) || (orgAgents ? null : 'the agent read did not answer');
|
||||
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;
|
||||
const live = instances ? Object.entries(instances).filter(([, item]) => running(item)) : null;
|
||||
// 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]) => {
|
||||
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, agents);
|
||||
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>';
|
||||
return `<tr><td>${esc(agent)}</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>`;
|
||||
return `<tr><td>${esc(shown)}</td><td>${where}</td><td class="hide-m mono">${modelCell(agent, model)}</td><td>${dot(acls, aglyph, aword, true)}${count > 1 ? ` <span class="muted">${count} sessions</span>` : ''}</td></tr>`;
|
||||
}).join('');
|
||||
const sessions = live === null ? (stopped ? '<p class="ws-panel tight note" data-bus-stopped>Sessions not read: the bus is stopped.</p>' : '<p class="ws-panel tight note">Sessions unavailable. The bus did not answer the instance read.</p>') : live.length ? `<div class="ws-tbl"><table><thead><tr><th scope="col">Agent</th><th scope="col">Project and task</th><th scope="col" class="hide-m">Model</th><th scope="col">Status</th></tr></thead><tbody>${sessionRows}</tbody></table></div>` : '<p class="ws-panel tight note">No active agent sessions</p>';
|
||||
const open = queue ? queue.filter(r => r?.state !== 'done').length : null;
|
||||
@@ -314,18 +348,18 @@
|
||||
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, pane)}
|
||||
${org.busHealthy ? '' : downBanner(org, downRow)}
|
||||
${orgTiles}
|
||||
${docrow}
|
||||
<div class="ws-split">
|
||||
<section aria-label="Measures and sessions">
|
||||
${tiles('KPIs', 'defined in the organization file', 'No KPIs defined in the organization file')}
|
||||
${tiles('Metrics', 'measured by the bus', 'No metrics recorded yet')}
|
||||
${secH('Active agent sessions', live ? (live.length ? `${live.length} running` : 'none running') : '', '<a href="#/agents" data-focus-key="agents-all">All agents</a>')}
|
||||
${secH('Active agent sessions', live ? (live.length ? `${live.length} running${tileAgents ? `, ${liveWorking} working` : ', working not read'}` : 'none running') : '', `<a href="#/agents?${oq}" data-focus-key="agents-all">This organization's agents</a>`)}
|
||||
${sessions}
|
||||
${secH('Queue', queueNote, '<a href="#/queue" data-org-queue data-focus-key="queue-open">Open queue</a>')}
|
||||
${queueWhy}
|
||||
</section>
|
||||
<section aria-label="Settings">
|
||||
<section aria-label="Workflows and settings">
|
||||
${window.MosaicWorkflows?.card?.(id, { stopped, label: label(org) }) ?? ''}
|
||||
${secH('Settings', 'every setting, with where its value comes from')}
|
||||
${settingsList(org, { business, settings, instances, orgCount: list ? list.length : null })}
|
||||
</section>
|
||||
@@ -589,8 +623,25 @@
|
||||
// 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 = { 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' };
|
||||
const classChip = c => (c ? `<span class="ws-chip ${CLASS_CHIP[c] || ''}">${esc(c)}</span>` : '');
|
||||
// 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(' · ');
|
||||
@@ -607,40 +658,55 @@
|
||||
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);
|
||||
const sessN = s => num(s?.working) + num(s?.waiting) + num(s?.idle) + num(s?.live);
|
||||
// The reads each tile's figures come from (workspace-read.mjs orgRows).
|
||||
const SRC = { needs: ['inbox'], sessions: ['agents', 'claims'], tasks: ['tasks'], projects: ['projects'] };
|
||||
// Per-organization figures name only the organizations that made the tile's reads.
|
||||
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 answered = o.rows.filter(r => r.state === 'ok').length;
|
||||
const tile = (key, name, big, small, ps, delta) => {
|
||||
const m = missed(o, SRC[key]);
|
||||
if (!readers(o, SRC[key]).size) return `<div class="ws-tile quiet" data-ws-tile="${key}" data-ws-miss="${key}"><span class="ws-label">${name}</span><span class="ws-empty-t">Not read</span><span class="ws-delta">${andList(m)}</span></div>`;
|
||||
return `<div class="ws-tile" data-ws-tile="${key}"><span class="ws-label">${name}</span><span class="ws-big">${big}${small ? `<small>${small}</small>` : ''}</span>${ps ? bar(o, ps) + by(o, ps) : ''}<span class="ws-delta">${delta}</span>${m.length ? `<span class="ws-delta ws-miss" data-ws-miss="${key}">Not read in ${andList(m)}</span>` : ''}</div>`;
|
||||
};
|
||||
const tiles = t && answered ? `<div class="ws-g5 keep2" data-ws-tiles>
|
||||
${tile('needs', 'Needs you', num(t.needsYou), t.needsYou === 1 ? 'item' : 'items', parts('needs', x => x.needsYou), t.oldestNeedsYouAt ? `oldest ${span(t.oldestNeedsYouAt)}` : 'nothing waiting')}
|
||||
${tile('sessions', 'Sessions', sessN(t.sessions), `${num(t.sessions?.working)} working`, parts('sessions', x => sessN(x.sessions)), `${num(t.sessions?.waiting)} waiting on you · ${num(t.sessions?.idle)} idle${num(t.sessions?.live) ? ` · ${num(t.sessions.live)} live ${t.sessions.live === 1 ? 'thread' : 'threads'}` : ''}`)}
|
||||
${tile('tasks', 'Open tasks', num(t.openTasks), '', parts('tasks', x => x.openTasks), `<b>${num(t.doneThisWeek)}</b> done this week`)}
|
||||
${tile('projects', 'Projects', num(t.projects?.active) + num(t.projects?.archived), `${num(t.projects?.active)} active`, parts('projects', x => num(x.projects?.active) + num(x.projects?.archived)), `${num(t.projects?.archived)} archived`)}
|
||||
<div class="ws-tile quiet" data-ws-tile="spend"><span class="ws-label">Model spend</span><span class="ws-empty-t">No spend figures yet</span><span class="ws-delta">No model prices are read yet, so today's use has no cost figure.</span></div>
|
||||
</div>` : '<p class="ws-panel tight note" data-ws-tiles>No organization answered, so there are no totals yet.</p>';
|
||||
|
||||
// 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 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);
|
||||
const projectsRead = readers(o, SRC.projects), inboxRead = readers(o, SRC.needs), sessionsRead = readers(o, SRC.sessions);
|
||||
const none = '<span class="muted" title="not read">–</span>';
|
||||
// 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);
|
||||
const agentParts = agentOk.map(r => ({ id: r.id, n: agentAll.filter(a => a.org === r.id && a.state === 'working').length }));
|
||||
const waitingOn = agentAll.filter(a => a.state === 'waiting').length;
|
||||
const ps = { needs: parts('needs', x => x.needsYou), tasks: parts('tasks', x => x.openTasks), done: parts('done', x => x.doneThisWeek), projects: parts('projects', x => x.projects?.active) };
|
||||
const needsN = fig('needs', ps.needs);
|
||||
const archived = per.filter(x => readers(o, SRC.projects).has(x.org)).reduce((a, x) => a + num(x.projects?.archived), 0);
|
||||
const tiles = !o.rows.length ? '<p class="ws-panel tight note" data-ws-tiles>No organizations yet, so there is nothing to count.</p>' : `<div class="ws-tiles six" data-ws-tiles role="group" aria-label="Key figures">
|
||||
${kpiTile(o, { key: 'agents', name: 'Agents working', href: '#/agents?state=working', big: agentOk.length ? sum(agentParts) : null, small: `of ${agentAll.length}`, parts: agentParts, delta: agentOk.length ? agentNote(runningOf(agentAll), waitingOn) : '', miss: [...notIn(['agents']), ...agentReads.filter(r => !r.inst).map(r => `${esc(o.name(r.id))} (${esc(instWhy(r))})`)] })}
|
||||
${kpiTile(o, { key: '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);
|
||||
const count = lv?.state === 'ok' && Array.isArray(lv.base?.agents) ? lv.base.agents.length : null;
|
||||
const working = x && sessionsRead.has(id) ? num(x.sessions?.working) : null;
|
||||
const agentsCell = count === null ? none : `${plural(count, 'agent')}${working === null ? '' : ` <small class="muted">(${working} working)</small>`}`;
|
||||
// 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">(${runningOf(mineRows)} running, ${workingOf(mineRows)} working)</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.
|
||||
@@ -648,7 +714,7 @@
|
||||
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</p>';
|
||||
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' };
|
||||
@@ -684,11 +750,11 @@
|
||||
${tiles}
|
||||
<div class="ws-split ws-home-split">
|
||||
<section aria-label="Organizations, projects and tasks">
|
||||
${secH('Organizations', `read ${esc(hm(body.readAt))}`)}
|
||||
${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="${esc(selHref('/tasks'))}" data-focus-key="home-tasks">Open tasks</a>`)}
|
||||
${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">
|
||||
@@ -802,7 +868,6 @@
|
||||
// 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_WORD = { gated: 'Gated', 'within-role': 'Within role', 'cross-role': 'Cross-role', routine: 'Routine' };
|
||||
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;
|
||||
@@ -904,28 +969,19 @@
|
||||
// `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'], ['not-running', 'Not running'], ['cant-launch', "Can't launch"]];
|
||||
const AGENT_STATE = [['working', 'Working'], ['waiting', 'Waiting on you'], ['idle', 'Idle'], ['running', 'Running, state unknown'], ['not-running', 'Not running'], ['cant-launch', "Can't launch"]];
|
||||
const AGENT_STATE_KEY = { working: 'working', 'waiting on you': 'waiting', idle: 'idle', running: 'running', 'not running': 'not-running', "can't launch": 'cant-launch' };
|
||||
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;
|
||||
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 Promise.all(askable.map(r => Promise.all([
|
||||
data.instances(r.org).then(v => ({ inst: instancesOf(v), copies: copiesOf(v) }), err => ({ inst: null, copies: {}, err })),
|
||||
!scope && typeof opts.fireIn === 'function' ? opts.fireIn(r.org).then(v => v === true, () => false) : false,
|
||||
]).then(([v, fire]) => ({ id: r.org, ...v, fire }))));
|
||||
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');
|
||||
// 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) {
|
||||
@@ -946,6 +1002,24 @@
|
||||
}
|
||||
}
|
||||
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;
|
||||
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);
|
||||
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));
|
||||
@@ -972,9 +1046,8 @@
|
||||
// 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 READ_ERR = { 403: 'refused', 0: 'signed out' };
|
||||
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(READ_ERR[r.err?.status] || r.err?.code || 'no answer')})`))}.</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;
|
||||
@@ -990,7 +1063,8 @@
|
||||
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;
|
||||
const tally = rows.length ? ` ${plural(rows.length, 'agent')}${scope ? '' : ` in ${plural(orgsWith, 'organization')}`}.` : '';
|
||||
// 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.`;
|
||||
@@ -1046,6 +1120,13 @@
|
||||
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 });
|
||||
@@ -1060,6 +1141,6 @@
|
||||
|
||||
// U4b: the org mark (colour and initials) for the task board (tasks-board.js).
|
||||
const orgMark = Object.freeze({ ready: ensureThemes, av, colours, initials });
|
||||
window.MosaicWorkspace = Object.freeze({ dashboard, holdLive, graftLive, agentGrid, icon, orgMark, refresh: () => refresh(), av, colours, label, state, dot, themes: ensureThemes, home, projectsPage, inboxPage, agentsPage, inboxCount, setGrouping, orgsOf, orgChip, projChip, unreadNote, setQuery, get pollMs() { return pollMs; } });
|
||||
window.MosaicWorkspace = Object.freeze({ dashboard, holdLive, graftLive, agentGrid, icon, orgMark, refresh: () => refresh(), av, colours, label, state, dot, themes: ensureThemes, home, projectsPage, inboxPage, agentsPage, inboxCount, setGrouping, orgsOf, orgChip, projChip, unreadNote, setQuery, classWord, get pollMs() { return pollMs; } });
|
||||
refresh();
|
||||
})();
|
||||
@@ -86,6 +86,7 @@ const files = new Map([
|
||||
['/packs.js', ['packs.js', 'text/javascript; charset=utf-8']],
|
||||
['/workflows.js', ['workflows.js', 'text/javascript; charset=utf-8']],
|
||||
['/packs.css', ['packs.css', 'text/css; charset=utf-8']],
|
||||
['/workflows.css', ['workflows.css', 'text/css; charset=utf-8']],
|
||||
...[400, 500, 600, 700].map(w => [`/assets/fonts/manrope-${w}.woff2`, [`assets/fonts/manrope-${w}.woff2`, 'font/woff2']]),
|
||||
...[400, 500, 700].map(w => [`/assets/fonts/jetbrains-mono-${w}.woff2`, [`assets/fonts/jetbrains-mono-${w}.woff2`, 'font/woff2']]),
|
||||
]);
|
||||
@@ -1085,7 +1086,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
return templatesHTTP(req, res, { path, owner, read: requestRead, write: send ? templatesWrite : null,
|
||||
session: ssoSession, live: () => { const live = sso.session(req); return live?.rootOwner === true ? live : null; }, origin: localOrigin ?? sso?.publicOrigin });
|
||||
}
|
||||
if (tester && ['/project-remote.js', '/project-remote.css', '/files.js', '/files.css', '/packs.js', '/packs.css', '/workflows.js'].includes(path)) return json(res, 403, { error: 'owner-only' });
|
||||
if (tester && ['/project-remote.js', '/project-remote.css', '/files.js', '/files.css', '/packs.js', '/packs.css', '/workflows.js', '/workflows.css'].includes(path)) return json(res, 403, { error: 'owner-only' });
|
||||
// Row 194 (#1692, D4.1): the tester also launches and terminates.
|
||||
if (tester && !['GET', 'HEAD'].includes(req.method) && !['/api/instances', '/api/routes', '/api/name', '/api/agent/launch', '/api/agent/terminate'].includes(path) && !TESTER_CHAT_WRITE.test(path))
|
||||
return json(res, 403, { error: 'read-only', sent: false });
|
||||
|
||||
@@ -42,7 +42,7 @@ function orgs(state) {
|
||||
reads: { business: async () => ({ business: { id } }), settings: async () => ({}), busStatus: async () => ({ live: true, down: false }), queue: async () => ({ rows: [] }) },
|
||||
bus: {
|
||||
inbox: async () => [], agents: async () => [], tasks: async () => [], 'thread.claims': async () => [], messages: async () => ({ messages: [], unread: 0 }),
|
||||
instances: async () => ({ business: id, revision: 'a'.repeat(64), definitions: {}, instances: { assistant: { definition: 'assistant', vars: {} } } }),
|
||||
instances: async () => ({ business: id, revision: 'a'.repeat(64), definitions: {}, instances: { assistant: { definition: 'assistant', vars: {}, ...(state.run?.[id] ? { running: state.run[id] } : {}) } } }),
|
||||
},
|
||||
chat: {
|
||||
projects: async () => PROJECTS[id],
|
||||
@@ -51,7 +51,7 @@ function orgs(state) {
|
||||
shares: async () => [],
|
||||
messages: async ({ thread }) => [
|
||||
...(MESSAGES[thread] ? [{ id: thread.replace(/^2/, '3'), from_role: 'assistant', body: MESSAGES[thread], at: '2026-11-15T10:00:00.000Z' }] : []),
|
||||
...state.sent.filter(s => s.org === id && s.thread === thread).map(s => ({ id: s.id, from_role: 'human', body: s.body, at: '2026-11-15T10:01:00.000Z' })),
|
||||
...(state.hideSent ? [] : state.sent).filter(s => s.org === id && s.thread === thread).map(s => ({ id: s.id, from_role: 'human', body: s.body, at: '2026-11-15T10:01:00.000Z' })),
|
||||
...(state.replies || []).filter(r => r.org === id && r.thread === thread).map((r, n) => ({ id: `50000000-0000-4000-8000-${String(n + 1).padStart(12, '0')}`, from_role: 'assistant', body: r.body, at: '2026-11-15T10:02:00.000Z' })),
|
||||
],
|
||||
send: async ({ thread, body }) => {
|
||||
@@ -86,6 +86,7 @@ const panes = `[...document.querySelectorAll('[data-assist-pane]')].map(p => p.d
|
||||
const shown = `[...document.querySelectorAll('[data-assist-pane]')].filter(p => p.getClientRects().length).map(p => p.dataset.assistPane)`;
|
||||
const query = `new URLSearchParams(location.hash.split('?')[1] || '').get('open')`;
|
||||
const ready = sel => `!!${PANE(sel)}?.querySelector('.chat-log li') && !!${PANE(sel)}?.querySelector('[data-ws-orgchip]')`;
|
||||
const trail = '(document.getElementById("breadcrumbs").getClientRects().length ? document.getElementById("breadcrumbs").innerText.replace(/\\s+/g, " ").trim() : null)';
|
||||
const SENT = '/Accepted message|Message shown in this conversation/';
|
||||
const pick = (b, value) => b.evaluate(`(() => { const s = document.querySelector('[data-assist-open]'); s.value = ${JSON.stringify(value)}; if (s.value !== ${JSON.stringify(value)}) throw Error('no option ' + ${JSON.stringify(value)}); s.dispatchEvent(new Event('change', { bubbles: true })); })()`);
|
||||
|
||||
@@ -96,6 +97,8 @@ test('the sidebar Assistant opens one system page, and two threads from two orga
|
||||
await b.evaluate(`document.querySelector('#sections a[href="#/assistant"]').click()`);
|
||||
await wait(`location.hash.startsWith('#/assistant') && document.querySelector('#bus-view h1')?.textContent === 'Assistant'`);
|
||||
assert.equal(await b.evaluate('document.querySelector(\'#sections a[href="#/assistant"]\').getAttribute("aria-current")'), 'page');
|
||||
// SP7: the page name shows once, as the heading.
|
||||
assert.equal(await b.evaluate(trail), null);
|
||||
await wait(`!!document.querySelector('[data-assist-open] optgroup[label^="Beta"] option[value="beta:${T.b1}"]')`);
|
||||
await pick(b, `alpha:${T.a1}`);
|
||||
await pick(b, `beta:${T.b1}`);
|
||||
@@ -279,3 +282,252 @@ test('"Open thread" starts a new thread in a chosen organization through that or
|
||||
assert.deepEqual(state.created.map(({ org, project, name, instance }) => ({ org, project, name, instance })), [{ org: 'beta', project: P.beta, name: 'Rate limits', instance: 'assistant' }]);
|
||||
assert.equal(await b.evaluate(query), `beta:${NEW}`);
|
||||
});
|
||||
|
||||
// SP7: a thread link anywhere opens that thread as a pane here; a typed per-organization address
|
||||
// still opens that organization's own chat view.
|
||||
const follow = (b, href) => b.evaluate(`(() => { const a = document.createElement('a'); a.href = ${JSON.stringify(href)}; a.textContent = 'thread'; document.body.append(a); a.click(); a.remove(); })()`);
|
||||
const type = (b, sel, text) => b.evaluate(`(() => { const el = ${PANE(sel)}.querySelector('form textarea'); el.value = ${JSON.stringify(text)}; el.dispatchEvent(new Event('input', { bubbles: true })); })()`);
|
||||
const field = sel => `${PANE(sel)}?.querySelector('form textarea')`;
|
||||
|
||||
test('SP7: a thread link on a project page opens the thread as a pane on the Assistant page, added to the open set', async t => {
|
||||
const { b, wait } = await open(t, { hash: `#/assistant?open=beta:${T.b1}` });
|
||||
await wait(ready(`beta:${T.b1}`));
|
||||
await b.evaluate(`location.hash = '#/orgs/alpha/projects/${P.alpha}'`);
|
||||
await wait(`!!document.querySelector('#bus-view a[href$="/threads/${T.a1}"]')`);
|
||||
await b.evaluate(`document.querySelector('#bus-view a[href$="/threads/${T.a1}"]').click()`);
|
||||
await wait(`location.hash.startsWith('#/assistant') && ${ready(`alpha:${T.a1}`)}`);
|
||||
assert.deepEqual(await b.evaluate(panes), [`beta:${T.b1}`, `alpha:${T.a1}`]);
|
||||
assert.equal(await b.evaluate(query), `beta:${T.b1},alpha:${T.a1}`);
|
||||
// A per-organization chat address typed or pasted still opens that organization's chat view.
|
||||
await b.evaluate(`location.hash = '#/orgs/beta/projects/threads/${T.b1}'`);
|
||||
await wait(`!document.querySelector('[data-assistant]') && /Beta tokens rotate nightly/.test(document.getElementById('bus-view').innerText)`);
|
||||
assert.equal(await b.evaluate('location.hash'), `#/orgs/beta/projects/threads/${T.b1}`);
|
||||
});
|
||||
|
||||
// SP11 (#1873): Resume assistant shows only when the organization's instances read says the thread's
|
||||
// agent runs no process (paused or stopped). An agent the read does not say about keeps the control.
|
||||
test('Resume assistant shows only in a pane whose agent the instances read says is not running', async t => {
|
||||
const state = { down: new Set(), sent: [], created: [], run: { alpha: ['run-1'], beta: [] } };
|
||||
const { b, wait } = await open(t, { hash: `#/assistant?open=alpha:${T.a1},beta:${T.b1},home:${T.h1}`, state });
|
||||
const resume = sel => `!!${PANE(sel)}.querySelector('button.pane-resume')`;
|
||||
await wait(`${ready(`alpha:${T.a1}`)} && ${ready(`beta:${T.b1}`)} && ${ready(`home:${T.h1}`)}`);
|
||||
await wait(resume(`beta:${T.b1}`));
|
||||
assert.equal(await b.evaluate(resume(`alpha:${T.a1}`)), false, 'a running assistant offers no resume');
|
||||
assert.equal(await b.evaluate(resume(`home:${T.h1}`)), true, 'a read that does not say keeps the control');
|
||||
// Alpha's assistant stops: the next read shows the control.
|
||||
state.run.alpha = [];
|
||||
await b.evaluate('window.MosaicAssistant.refresh()');
|
||||
await wait(resume(`alpha:${T.a1}`));
|
||||
// Beta's starts again: its control goes.
|
||||
state.run.beta = ['run-2'];
|
||||
await b.evaluate('window.MosaicAssistant.refresh()');
|
||||
await wait(`!${resume(`beta:${T.b1}`)}`);
|
||||
});
|
||||
|
||||
test('SP7: with three open, a fourth thread replaces the first pane with no unsent message; when all three hold one, nothing is replaced and the page says why', async t => {
|
||||
const state = { down: new Set(), sent: [], created: [] };
|
||||
const { b, wait } = await open(t, { hash: `#/assistant?open=alpha:${T.a1},beta:${T.b1}`, state });
|
||||
await wait(`${ready(`alpha:${T.a1}`)} && ${ready(`beta:${T.b1}`)} && !${field(`alpha:${T.a1}`)}.disabled`);
|
||||
await type(b, `alpha:${T.a1}`, 'alpha draft');
|
||||
// On the Assistant page a thread link adds a pane in place: the typed message stays.
|
||||
await follow(b, `#/orgs/alpha/projects/threads/${T.a2}`);
|
||||
await wait(ready(`alpha:${T.a2}`));
|
||||
assert.deepEqual(await b.evaluate(panes), [`alpha:${T.a1}`, `beta:${T.b1}`, `alpha:${T.a2}`]);
|
||||
assert.equal(await b.evaluate(`${field(`alpha:${T.a1}`)}.value`), 'alpha draft');
|
||||
// A fourth: Alpha's first pane holds a message, so Beta's pane, the first without one, gives way.
|
||||
await follow(b, `#/orgs/home/projects/threads/${T.h1}`);
|
||||
await wait(ready(`home:${T.h1}`));
|
||||
assert.deepEqual(await b.evaluate(panes), [`alpha:${T.a1}`, `home:${T.h1}`, `alpha:${T.a2}`]);
|
||||
assert.equal(await b.evaluate(query), `alpha:${T.a1},home:${T.h1},alpha:${T.a2}`);
|
||||
assert.equal(await b.evaluate(`${field(`alpha:${T.a1}`)}.value`), 'alpha draft');
|
||||
// All three hold a message: nothing is replaced and the page says why.
|
||||
await wait(`!${field(`home:${T.h1}`)}.disabled && !${field(`alpha:${T.a2}`)}.disabled`);
|
||||
await type(b, `home:${T.h1}`, 'home draft');
|
||||
await type(b, `alpha:${T.a2}`, 'kickoff draft');
|
||||
await follow(b, `#/orgs/beta/projects/threads/${T.b1}`);
|
||||
await wait(`/not opened/.test(document.querySelector('[data-assist-note]').textContent)`);
|
||||
assert.match(await b.evaluate(`document.querySelector('[data-assist-note]').textContent`), /all 3 panes hold an unsent message/);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-assist-note]').hasAttribute('data-refused')`), true);
|
||||
assert.deepEqual(await b.evaluate(panes), [`alpha:${T.a1}`, `home:${T.h1}`, `alpha:${T.a2}`]);
|
||||
assert.deepEqual(await b.evaluate(`[${field(`alpha:${T.a1}`)}.value, ${field(`home:${T.h1}`)}.value, ${field(`alpha:${T.a2}`)}.value]`), ['alpha draft', 'home draft', 'kickoff draft']);
|
||||
assert.equal(await b.evaluate(query), `alpha:${T.a1},home:${T.h1},alpha:${T.a2}`);
|
||||
// Closing a pane clears the reason; the thread then opens. SP11: the pane holds a message, so the
|
||||
// close asks first.
|
||||
await b.evaluate(`window.__asked = []; window.confirm = m => (window.__asked.push(m), true)`);
|
||||
await b.evaluate(`${PANE(`home:${T.h1}`)}.querySelector('button[data-assist-close]').click()`);
|
||||
assert.equal(await b.evaluate('window.__asked.length'), 1);
|
||||
await wait(`!/not opened/.test(document.querySelector('[data-assist-note]').textContent)`);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-assist-note]').hasAttribute('data-refused')`), false);
|
||||
await follow(b, `#/orgs/beta/projects/threads/${T.b1}`);
|
||||
await wait(ready(`beta:${T.b1}`));
|
||||
assert.deepEqual(await b.evaluate(panes), [`alpha:${T.a1}`, `alpha:${T.a2}`, `beta:${T.b1}`]);
|
||||
assert.deepEqual(state.sent, []);
|
||||
});
|
||||
|
||||
test('SP7: each pane names its own organization\'s Messages page, and the bar no longer names the organization opened last', async t => {
|
||||
const { b, wait } = await open(t, { hash: '#/orgs/beta/tasks' });
|
||||
await wait(`window.MosaicOrg?.id === 'beta'`);
|
||||
await b.evaluate(`location.hash = '#/assistant?open=alpha:${T.a1},beta:${T.b1}'`);
|
||||
await wait(`${ready(`alpha:${T.a1}`)} && ${ready(`beta:${T.b1}`)}`);
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-assist-pane]')].map(p => { const a = p.querySelector('.assist-pane-h a[data-assist-pane-messages]'); return a && [a.getAttribute('href'), a.getAttribute('aria-label'), a.textContent.trim()]; })`),
|
||||
[['#/orgs/alpha/messages', 'Messages in Alpha', 'Messages'], ['#/orgs/beta/messages', 'Messages in Beta', 'Messages']]);
|
||||
assert.doesNotMatch(await b.evaluate(`document.querySelector('.assist-bar').innerText`), /Messages/);
|
||||
});
|
||||
|
||||
// SP11 (#1873): a pane's unsent message is kept per thread while the tab is open. Leaving the
|
||||
// Assistant page, by the sidebar or by a pane's Full view into another organization, keeps it, and the
|
||||
// pane shows it again when it opens. Closing a pane that holds one asks first.
|
||||
test('SP11: an unsent pane message survives leaving the Assistant page, through Full view too, and closing a pane with one asks first', async t => {
|
||||
const state = { down: new Set(), sent: [], created: [] };
|
||||
const a1 = `alpha:${T.a1}`, b1 = `beta:${T.b1}`, both = `#/assistant?open=${a1},${b1}`;
|
||||
const { b, wait } = await open(t, { hash: both, state });
|
||||
await wait(`${ready(a1)} && ${ready(b1)} && !${field(a1)}.disabled && !${field(b1)}.disabled`);
|
||||
await type(b, a1, 'alpha keep');
|
||||
await type(b, b1, 'beta keep');
|
||||
// Away to Tasks and back.
|
||||
await b.evaluate(`location.hash = '#/tasks'`);
|
||||
await wait(`!document.querySelector('[data-assist-pane]') && !!document.querySelector('[data-tasks-board]')`);
|
||||
await b.evaluate(`location.hash = ${JSON.stringify(both)}`);
|
||||
await wait(`${field(a1)}?.value === 'alpha keep' && ${field(b1)}?.value === 'beta keep'`);
|
||||
// Away through Beta's Full view: no discard question, and the message is still there after.
|
||||
await b.evaluate(`${PANE(b1)}.querySelector('a[data-assist-pane-full]').click()`);
|
||||
await wait(`location.hash.startsWith('#/orgs/beta/') && !document.querySelector('[data-assist-pane]')`);
|
||||
assert.equal(await b.evaluate(`!!document.querySelector('dialog[open]')`), false, 'leaving asks nothing: the message is kept');
|
||||
await b.evaluate(`location.hash = ${JSON.stringify(both)}`);
|
||||
await wait(`${field(a1)}?.value === 'alpha keep' && ${field(b1)}?.value === 'beta keep'`);
|
||||
// Closing a pane with an unsent message asks; saying no keeps the pane.
|
||||
await b.evaluate(`window.__asked = []; window.confirm = m => (window.__asked.push(m), false)`);
|
||||
await b.evaluate(`${PANE(a1)}.querySelector('button[data-assist-close]').click()`);
|
||||
assert.deepEqual(await b.evaluate('window.__asked'), ['Close Launch email? Its unsent message is lost.']);
|
||||
assert.deepEqual(await b.evaluate(panes), [a1, b1]);
|
||||
// Saying yes closes it and drops the message: the thread opens again empty.
|
||||
await b.evaluate(`window.confirm = m => (window.__asked.push(m), true)`);
|
||||
await b.evaluate(`${PANE(a1)}.querySelector('button[data-assist-close]').click()`);
|
||||
await wait(`document.querySelectorAll('[data-assist-pane]').length === 1`);
|
||||
await follow(b, `#/orgs/alpha/projects/threads/${T.a1}`);
|
||||
await wait(`${ready(a1)} && !!${field(a1)} && !${field(a1)}.disabled`);
|
||||
assert.equal(await b.evaluate(`${field(a1)}.value`), '');
|
||||
// A pane with nothing typed closes with no question.
|
||||
await b.evaluate(`${PANE(a1)}.querySelector('button[data-assist-close]').click()`);
|
||||
await wait(`document.querySelectorAll('[data-assist-pane]').length === 1`);
|
||||
assert.equal(await b.evaluate('window.__asked.length'), 2);
|
||||
assert.deepEqual(state.sent, []);
|
||||
});
|
||||
|
||||
// SP11 review: signing out drops every kept pane message, so the next person to sign in on this tab
|
||||
// never sees text typed before, after a reload too.
|
||||
test('SP11: signing out drops kept pane messages, and a reload after it opens the pane empty', async t => {
|
||||
const state = { down: new Set(), sent: [], created: [] };
|
||||
const a1 = `alpha:${T.a1}`, hash = `#/assistant?open=${a1}`;
|
||||
const { b, base, wait } = await open(t, { hash, state });
|
||||
await wait(`${ready(a1)} && !${field(a1)}.disabled`);
|
||||
await type(b, a1, 'private note');
|
||||
await b.evaluate(`location.hash = '#/tasks'`);
|
||||
await wait(`!document.querySelector('[data-assist-pane]')`);
|
||||
assert.match(await b.evaluate(`sessionStorage.getItem('mosaic-assistant-drafts') || ''`), /private note/);
|
||||
await b.evaluate(`location.hash = ${JSON.stringify(hash)}`);
|
||||
await wait(`${field(a1)}?.value === 'private note'`);
|
||||
await b.evaluate(`document.dispatchEvent(new Event('mosaic-signed-out')), true`);
|
||||
await wait(`document.body.classList.contains('signed-out')`);
|
||||
assert.equal(await b.evaluate(`sessionStorage.getItem('mosaic-assistant-drafts')`), null);
|
||||
// A query string makes it a real load; the same address with only a hash would not reload.
|
||||
await b.navigate(base + '?again=1' + hash);
|
||||
await wait(`!document.body.classList.contains('signed-out') && ${ready(a1)} && !!${field(a1)} && !${field(a1)}.disabled`);
|
||||
assert.equal(await b.evaluate(`${field(a1)}.value`), '');
|
||||
assert.equal(await b.evaluate(`sessionStorage.getItem('mosaic-assistant-drafts')`), null);
|
||||
assert.deepEqual(state.sent, []);
|
||||
});
|
||||
|
||||
// SP11 review: the Sign out form is a plain POST that unloads the page; its submit drops the kept
|
||||
// messages and the pagehide it causes keeps nothing, so a sign-in after it opens the pane empty.
|
||||
test('SP11: the Sign out form drops kept pane messages, and the page it unloads keeps none', async t => {
|
||||
const state = { down: new Set(), sent: [], created: [] };
|
||||
const a1 = `alpha:${T.a1}`, hash = `#/assistant?open=${a1}`;
|
||||
const { b, base, wait } = await open(t, { hash, state });
|
||||
await wait(`${ready(a1)} && !${field(a1)}.disabled`);
|
||||
await type(b, a1, 'private note');
|
||||
await b.evaluate(`location.hash = '#/tasks'`);
|
||||
await wait(`!document.querySelector('[data-assist-pane]')`);
|
||||
await b.evaluate(`location.hash = ${JSON.stringify(hash)}`);
|
||||
await wait(`${field(a1)}?.value === 'private note'`);
|
||||
await b.evaluate(`document.getElementById('sign-out').requestSubmit(), true`);
|
||||
// The POST unloads the page; poll from here, since the old page's context goes away under it.
|
||||
let left = false;
|
||||
for (let i = 0; i < 200 && !left; i++) { try { left = await b.evaluate(`location.pathname === '/auth/logout'`); } catch { /* navigating */ } if (!left) await new Promise(r => setTimeout(r, 30)); }
|
||||
assert.equal(left, true, 'the Sign out form posted');
|
||||
await b.navigate(base + '?again=1' + hash);
|
||||
await wait(`${ready(a1)} && !!${field(a1)} && !${field(a1)}.disabled`);
|
||||
assert.equal(await b.evaluate(`${field(a1)}.value`), '');
|
||||
assert.equal(await b.evaluate(`sessionStorage.getItem('mosaic-assistant-drafts')`), null);
|
||||
assert.deepEqual(state.sent, []);
|
||||
});
|
||||
|
||||
// SP11 (#1873): a pane whose message was sent but not yet shown in the conversation is not free: a
|
||||
// fourth thread replaces the first pane that holds nothing, and that pane only once its receipt is in.
|
||||
test('SP11: a pane whose send still waits for its receipt is not replaced by a fourth thread', async t => {
|
||||
const state = { down: new Set(), sent: [], created: [], hideSent: true };
|
||||
const a1 = `alpha:${T.a1}`, b1 = `beta:${T.b1}`, a2 = `alpha:${T.a2}`, h1 = `home:${T.h1}`;
|
||||
const { b, wait } = await open(t, { hash: `#/assistant?open=${a1},${b1},${a2}`, state });
|
||||
await wait(`${ready(a1)} && ${ready(b1)} && ${ready(a2)} && !${field(a1)}.disabled`);
|
||||
await b.evaluate(`(() => { const el = ${field(a1)}; el.value = 'in flight'; el.dispatchEvent(new Event('input', { bubbles: true })); el.form.requestSubmit(); })()`);
|
||||
await wait(`/Accepted message/.test(${PANE(a1)}.innerText) && ${field(a1)}.value === ''`);
|
||||
await follow(b, `#/orgs/home/projects/threads/${T.h1}`);
|
||||
await wait(ready(h1));
|
||||
assert.deepEqual(await b.evaluate(panes), [a1, h1, a2], 'the waiting pane stays; the first free one gives way');
|
||||
// The message shows: the receipt is in and the pane is free again.
|
||||
state.hideSent = false;
|
||||
await b.evaluate('window.MosaicAssistant.refresh()');
|
||||
await wait(`/Message shown in this conversation/.test(${PANE(a1)}.innerText)`);
|
||||
await follow(b, `#/orgs/beta/projects/threads/${T.b1}`);
|
||||
await wait(ready(b1));
|
||||
assert.deepEqual(await b.evaluate(panes), [b1, h1, a2]);
|
||||
});
|
||||
|
||||
// SP7 review: a pane has no Request details, sessions or sharing, so each pane links its thread's full
|
||||
// view, and a link marked data-full-view is not turned into a pane.
|
||||
test('SP7: each pane links its thread\'s full view, and one plain click reaches it', async t => {
|
||||
const { b, wait } = await open(t, { hash: `#/assistant?open=alpha:${T.a1},beta:${T.b1}` });
|
||||
await wait(`${ready(`alpha:${T.a1}`)} && ${ready(`beta:${T.b1}`)}`);
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-assist-pane]')].map(p => { const a = p.querySelector('.assist-pane-h a[data-assist-pane-full]'); return a && [a.getAttribute('href'), a.textContent.trim(), a.hasAttribute('data-full-view')]; })`),
|
||||
[[`#/orgs/alpha/projects/threads/${T.a1}`, 'Full view', true], [`#/orgs/beta/projects/threads/${T.b1}`, 'Full view', true]]);
|
||||
// Each pane's Full view names its thread and organization, so a screen reader can tell three apart.
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-assist-pane-full]')].map(a => a.getAttribute('aria-label'))`),
|
||||
['Full view of Launch email, Alpha', 'Full view of Gateway auth, Beta']);
|
||||
await b.evaluate(`${PANE(`beta:${T.b1}`)}.querySelector('a[data-assist-pane-full]').click()`);
|
||||
await wait(`!document.querySelector('[data-assistant]') && /Beta tokens rotate nightly/.test(document.getElementById('bus-view').innerText)`);
|
||||
assert.equal(await b.evaluate('location.hash'), `#/orgs/beta/projects/threads/${T.b1}`);
|
||||
});
|
||||
|
||||
test('SP7: a link marked as the full view stays in the organization\'s own view, from any page', async t => {
|
||||
const { b, wait } = await open(t, { hash: `#/assistant?open=alpha:${T.a1}` });
|
||||
await wait(ready(`alpha:${T.a1}`));
|
||||
// On the Assistant page itself: no pane is added, the browser follows the link.
|
||||
await b.evaluate(`(() => { const a = document.createElement('a'); a.href = '#/orgs/beta/projects/threads/${T.b1}'; a.setAttribute('data-full-view', ''); a.textContent = 'thread'; document.body.append(a); a.click(); a.remove(); })()`);
|
||||
await wait(`location.hash === '#/orgs/beta/projects/threads/${T.b1}'`);
|
||||
await wait(`!document.querySelector('[data-assistant]') && /Beta tokens rotate nightly/.test(document.getElementById('bus-view').innerText)`);
|
||||
// From another page: the same.
|
||||
await b.evaluate(`(() => { const a = document.createElement('a'); a.href = '#/orgs/alpha/projects/threads/${T.a1}'; a.setAttribute('data-full-view', ''); a.textContent = 'thread'; document.body.append(a); a.click(); a.remove(); })()`);
|
||||
await wait(`location.hash === '#/orgs/alpha/projects/threads/${T.a1}' && !document.querySelector('[data-assistant]')`);
|
||||
});
|
||||
|
||||
// SP7 review shots: the title and the pane's tools (Full view, Messages, close) share the header's
|
||||
// first row, the organization and project chips sit under it, and nothing spills out of the pane.
|
||||
const headerRows = `[...document.querySelectorAll('[data-assist-pane]')].map(p => {
|
||||
const h = p.querySelector('.assist-pane-h').getBoundingClientRect();
|
||||
const r = s => p.querySelector(s).getBoundingClientRect();
|
||||
const mid = q => Math.round(q.top + q.height / 2);
|
||||
const row = ['[data-assist-title]', '[data-assist-pane-full]', '[data-assist-pane-messages]', '[data-assist-close]'].map(s => mid(r(s)));
|
||||
const inside = [...p.querySelectorAll('.assist-pane-h > *, .assist-pane-h a, .assist-pane-h button')].every(e => { const q = e.getBoundingClientRect(); return q.left >= h.left - 1 && q.right <= h.right + 1; });
|
||||
return { oneRow: Math.max(...row) - Math.min(...row) <= 4, chipsBelow: r('[data-assist-chips]').top >= r('[data-assist-title]').bottom - 1, inside };
|
||||
})`;
|
||||
// At 800 three panes are too narrow for one row: the tools wrap, and none of them leaves the pane.
|
||||
const THREE = [`alpha:${T.a1}`, `alpha:${T.a2}`, `beta:${T.b1}`];
|
||||
for (const [width, height, keys, oneRow] of [[1440, 900, THREE, true], [800, 900, THREE, null], [761, 900, THREE, null], [390, 844, [`beta:${T.b1}`], true]]) {
|
||||
test(`SP7: a pane header keeps its tools inside the pane${oneRow ? ', title and tools on one row with the chips below' : ''}, at ${width}`, async t => {
|
||||
const { b, wait } = await open(t, { width, height, hash: `#/assistant?open=${keys.join(',')}` });
|
||||
await wait(keys.map(k => ready(k)).join(' && '));
|
||||
await wait(`[...document.querySelectorAll('[data-assist-pane] [data-ws-orgchip]')].length === ${keys.length}`);
|
||||
const rows = await b.evaluate(headerRows);
|
||||
assert.deepEqual(rows.map(r => (oneRow ? r : { ...r, oneRow: null })), keys.map(() => ({ oneRow, chipsBelow: true, inside: true })));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
// SP8 (#1873, single pane slice 8): the Dashboard leads with one row of KPI tiles, each built from a
|
||||
// number an existing read returns and each a link to the page that lists what it counts, with the
|
||||
// filter in the address where that page has one. A tile whose number some organization could not give
|
||||
// names that organization; it never shows a lower number as if it were complete. An organization's
|
||||
// page leads with the same tiles scoped to it, each linking to the system page filtered to it.
|
||||
// Every bus is a fake: acme and beta answer, gamma's bus is stopped. The real GET /api/workspace and
|
||||
// the real per-organization routes serve the pages.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { startServer } from '../src/serve.mjs';
|
||||
import { createDevOwner } from '../src/dev-owner.mjs';
|
||||
import { browser } from './browser.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
|
||||
const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
|
||||
const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString();
|
||||
|
||||
// fail: { org: [read names] } makes those reads refuse; `none` empties the organization list.
|
||||
// split: { org: agents } is what that organization's own bus agents read answers, while the
|
||||
// cross-organization sessions read still answers the fixture's agents.
|
||||
function fixture({ fail = {}, none = false, split = {} } = {}) {
|
||||
const LIST = none ? [] : [
|
||||
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true },
|
||||
{ id: 'beta', label: 'Beta Works', theme: 'grove', busHealthy: true },
|
||||
{ id: 'gamma', label: 'Gamma Home', theme: 'rosewood', busHealthy: false, busStopped: true },
|
||||
];
|
||||
const decision = (id, question, role, minutes) => ({ id, question, class: 'within-role', blocking: false, raised_by_role: role, at: at(minutes), options: [{ key: 'yes', text: 'Yes' }] });
|
||||
const DATA = {
|
||||
acme: {
|
||||
projects: [{ id: 'p-site', repo: 'site', name: 'Website', archived: false, at: at(30) }, { id: 'p-old', repo: 'old', name: 'Old', archived: true, at: at(9000) }],
|
||||
tasks: [{ task_ref: 'local:1', project_key: 'site', at: at(20), fields: { title: 'Hero copy', done: false } }],
|
||||
agents: [{ role: 'coder', holder_run: 'run-1', harness: 'claude', state: 'working', at: at(40), working: { since: at(40) } }],
|
||||
inbox: [decision('dec-acme-1', 'Ship the hero?', 'coder', 10)],
|
||||
instances: { coder: { definition: 'coder', running: ['run-1'] }, chief: { definition: 'chief-of-staff', running: [] } },
|
||||
},
|
||||
beta: {
|
||||
projects: [{ id: 'p-shop', repo: 'shop', name: 'Shop', archived: false, at: at(120) }],
|
||||
tasks: [
|
||||
{ task_ref: 'local:7', project_key: 'shop', at: at(50), fields: { title: 'Price list', done: false } },
|
||||
{ task_ref: 'local:8', project_key: 'shop', at: at(70), fields: { title: 'Cart copy', done: false } },
|
||||
{ task_ref: 'local:9', project_key: 'shop', at: at(60 * 24), fields: { title: 'Logo', done: true } },
|
||||
],
|
||||
agents: [{ role: 'pm', holder_run: 'run-9', harness: 'claude', state: 'waiting', at: at(15) }],
|
||||
inbox: [decision('dec-beta-1', 'Pick a launch price', 'pm', 5), decision('dec-beta-2', 'Name the shop', 'pm', 90)],
|
||||
instances: { pm: { definition: 'pm', running: ['run-9'] }, writer: { definition: 'writer', running: [] } },
|
||||
},
|
||||
};
|
||||
const value = (id, name) => (fail[id]?.includes(name) ? Promise.reject(Object.assign(new Error('off'), { code: 'channel-disabled' })) : Promise.resolve(DATA[id]?.[name] ?? (['usage', 'limits'].includes(name) ? {} : [])));
|
||||
const opts = id => ({
|
||||
bus: { inbox: () => value(id, 'inbox'), agents: () => value(id, 'agents'), 'thread.claims': () => value(id, 'claims'), tasks: () => value(id, 'tasks'), usage: () => value(id, 'usage'), limits: () => value(id, 'limits'), decisions: () => value(id, 'decisions') },
|
||||
chat: { threads: () => value(id, 'threads'), projects: () => value(id, 'projects') },
|
||||
});
|
||||
const member = org => ({
|
||||
id: org.id, doc: { appearance: { theme: org.theme } },
|
||||
status: async () => (org.busHealthy ? { healthy: true, pid: 4242, boot: null } : { healthy: false, boot: { ok: false, at: at(90), lastGood: null, reason: 'stopped by the owner' } }),
|
||||
options: () => opts(org.id),
|
||||
});
|
||||
return {
|
||||
list: async () => LIST,
|
||||
members: async () => LIST.map(member),
|
||||
resolve: async id => {
|
||||
const org = LIST.find(o => o.id === id); if (!org) return null;
|
||||
if (!org.busHealthy) return { busHealthy: false, reads: null, bus: {}, chat: { projects: async () => [], threads: async () => [] } };
|
||||
return {
|
||||
busHealthy: true,
|
||||
reads: { business: async () => ({ business: { id, human: 'jason', projects: DATA[id].projects.map(p => p.repo), appearance: { theme: org.theme } } }), settings: async () => ({}), queue: async () => ({ rows: [] }), busStatus: async () => ({}) },
|
||||
bus: {
|
||||
messages: async () => ({ messages: [], unread: 0 }), agents: async () => { if (fail[id]?.includes('agents')) throw Object.assign(new Error('off'), { code: 'channel-disabled' }); return split[id] ?? DATA[id].agents; }, 'thread.claims': async () => [], inbox: async () => [], tasks: async () => [],
|
||||
instances: () => (fail[id]?.includes('instances') ? Promise.reject(Object.assign(new Error('off'), { code: 'bus-unavailable' })) : Promise.resolve({ revision: 'a'.repeat(64), definitions: {}, instances: DATA[id].instances })),
|
||||
},
|
||||
chat: { projects: async () => DATA[id].projects, threads: async () => [] },
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function setup(t, { viewport = [1440, 900], hash = '#/dashboard', fail, none, split } = {}) {
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: fixture({ fail, none, split }), log: () => {} });
|
||||
t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
await b.viewport(...viewport);
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
await b.navigate(`${base}/${hash}`);
|
||||
return { b, base, wait: waitFor(b), text: sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.innerText ?? null`) };
|
||||
}
|
||||
const tileKeys = scope => `[...document.querySelectorAll(${JSON.stringify(`${scope} [data-ws-tile]`)})].map(e => e.dataset.wsTile)`;
|
||||
const hrefs = scope => `Object.fromEntries([...document.querySelectorAll(${JSON.stringify(`${scope} [data-ws-tile]`)})].map(e => [e.dataset.wsTile, e.tagName === 'A' ? e.getAttribute('href') : null]))`;
|
||||
const big = (scope, key) => `document.querySelector(${JSON.stringify(`${scope} [data-ws-tile=${key}] .ws-big`)})?.textContent.replace(/\\s+/g, ' ').trim() ?? null`;
|
||||
const homeReady = 'document.querySelector("[data-ws-home] [data-ws-tiles] [data-ws-tile=agents] .ws-big")';
|
||||
|
||||
test('The Dashboard tiles add both answering organizations\' numbers, one row, each tile a link to the page that lists it', async t => {
|
||||
const { b, wait, text } = await setup(t);
|
||||
await wait(homeReady);
|
||||
// One row: no second tile group anywhere on the page, and the row leads the page under its heading.
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("[data-ws-home] [data-ws-tiles]").length'), 1);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-ws-home] .ws-vh").nextElementSibling.hasAttribute("data-ws-tiles")'), true);
|
||||
assert.deepEqual(await b.evaluate(tileKeys('[data-ws-home]')), ['agents', 'orgs', 'needs', 'tasks', 'done', 'projects']);
|
||||
// Agents working of total: acme's coder works; beta's pm waits; chief and writer run nothing.
|
||||
assert.equal(await b.evaluate(big('[data-ws-home]', 'agents')), '1 of 4');
|
||||
assert.equal(await b.evaluate(big('[data-ws-home]', 'orgs')), '2 of 3 running');
|
||||
assert.equal(await b.evaluate(big('[data-ws-home]', 'needs')), '3 items');
|
||||
assert.equal(await b.evaluate(big('[data-ws-home]', 'tasks')), '3');
|
||||
assert.equal(await b.evaluate(big('[data-ws-home]', 'done')), '1');
|
||||
assert.equal(await b.evaluate(big('[data-ws-home]', 'projects')), '2 active');
|
||||
// Each organization's share, named for a screen reader.
|
||||
assert.match(await text('[data-ws-tile=needs] .ws-by'), /Acme Studio\s*1[\s\S]*Beta Works\s*2/);
|
||||
assert.match(await text('[data-ws-tile=tasks] .ws-by'), /Acme Studio\s*1[\s\S]*Beta Works\s*2/);
|
||||
assert.match(await text('[data-ws-tile=agents] .ws-by'), /Acme Studio\s*1[\s\S]*Beta Works\s*0/);
|
||||
// Every tile is a link, with the filter in the address where the page has one.
|
||||
const links = await b.evaluate(hrefs('[data-ws-home]'));
|
||||
assert.equal(links.agents, '#/agents?state=working');
|
||||
assert.equal(links.orgs, '#/dashboard');
|
||||
assert.equal(links.needs, '#/inbox');
|
||||
assert.equal(links.tasks, '#/tasks');
|
||||
assert.equal(links.done, '#/tasks?done=week');
|
||||
assert.match(links.projects, /^#\/orgs\/[a-z0-9._-]+\/projects$/);
|
||||
// No sample numbers and no trend line: no tile draws an svg sparkline.
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("[data-ws-tiles] svg:not(.i)").length'), 0);
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("[data-ws-tile=spend],[data-ws-tile=sessions]").length'), 0);
|
||||
// The Open tasks link under Tasks by state goes to the system board too.
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-focus-key=home-tasks]").getAttribute("href")'), '#/tasks');
|
||||
});
|
||||
|
||||
test('A stopped organization is named on every tile its numbers would have joined, and on none it counted', async t => {
|
||||
const { b, wait, text } = await setup(t);
|
||||
await wait(homeReady);
|
||||
for (const key of ['agents', 'needs', 'tasks', 'done', 'projects']) {
|
||||
assert.match(await text(`[data-ws-tile=${key}] [data-ws-miss=${key}]`) ?? '', /Not read in Gamma Home \(bus stopped\)/, key);
|
||||
}
|
||||
// The Organizations tile counts it as not running and says which one.
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-ws-tile=orgs] [data-ws-miss]")'), null);
|
||||
assert.match(await text('[data-ws-tile=orgs]'), /Gamma Home bus stopped/);
|
||||
});
|
||||
|
||||
test('Following a tile lands on its page showing what the tile counted', async t => {
|
||||
const { b, wait, text } = await setup(t);
|
||||
await wait(homeReady);
|
||||
await b.evaluate('document.querySelector("[data-ws-tile=agents]").click()');
|
||||
await wait('location.hash === "#/agents?state=working" && document.querySelector("[data-ws-agent]")');
|
||||
await wait('JSON.stringify([...document.querySelectorAll("[data-ws-agent]")].map(r => r.dataset.wsAgent)) === JSON.stringify(["acme:coder"])');
|
||||
assert.match(await text('[data-ws-astate=""] .n'), /^4$/);
|
||||
await b.evaluate('location.hash = "#/dashboard"');
|
||||
await wait(homeReady);
|
||||
await b.evaluate('document.querySelector("[data-ws-tile=needs]").click()');
|
||||
await wait('location.hash === "#/inbox" && document.querySelectorAll("[data-ws-item]").length === 3');
|
||||
await b.evaluate('location.hash = "#/dashboard"');
|
||||
await wait(homeReady);
|
||||
// SP11: Done this week lands on the board showing the one task it counted, beta's Logo.
|
||||
await b.evaluate('document.querySelector("[data-ws-tile=done]").click()');
|
||||
await wait('location.hash === "#/tasks?done=week" && JSON.stringify([...document.querySelectorAll("[data-tasks-board] [data-tb-task]")].map(e => e.dataset.tbTask)) === JSON.stringify(["beta|local:9"])');
|
||||
await b.evaluate('location.hash = "#/dashboard"');
|
||||
await wait(homeReady);
|
||||
// The Organizations tile's list is this page's own table: following it keeps the page and moves focus there.
|
||||
await b.evaluate('document.querySelector("[data-ws-tile=orgs]").click()');
|
||||
await wait('document.activeElement?.closest?.("[data-ws-orgs-h]")');
|
||||
assert.equal(await b.evaluate('location.hash'), '#/dashboard');
|
||||
});
|
||||
|
||||
test('An answering organization whose agent read failed is named on the Agents tile, never counted as none', async t => {
|
||||
const { b, wait, text } = await setup(t, { fail: { beta: ['instances'] } });
|
||||
await wait(homeReady);
|
||||
assert.equal(await b.evaluate(big('[data-ws-home]', 'agents')), '1 of 2');
|
||||
assert.match(await text('[data-ws-tile=agents] [data-ws-miss=agents]'), /Beta Works/);
|
||||
assert.doesNotMatch(await text('[data-ws-tile=agents] .ws-by') ?? '', /Beta Works/);
|
||||
});
|
||||
|
||||
test('When no answering organization could read its agents, the Agents tile says Not read instead of a number', async t => {
|
||||
const { b, wait, text } = await setup(t, { fail: { acme: ['instances'], beta: ['instances'] } });
|
||||
await wait('document.querySelector("[data-ws-tile=agents]")');
|
||||
assert.equal(await b.evaluate(big('[data-ws-home]', 'agents')), null);
|
||||
assert.match(await text('[data-ws-tile=agents]'), /Not read/);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-ws-tile=agents]").getAttribute("href")'), '#/agents?state=working');
|
||||
});
|
||||
|
||||
// SP11 (#1873): with no organizations, #/dashboard is the Dashboard, not Not found. It says there is
|
||||
// nothing to count and offers New organization, which opens the Organizations form at its ID field.
|
||||
// #/ stays the Console's own board, with its dashes.
|
||||
test('With no organizations the Dashboard says so, shows no tile, and offers New organization', async t => {
|
||||
const { b, wait, text } = await setup(t, { none: true });
|
||||
await wait('document.querySelector("[data-ws-home] h1")');
|
||||
assert.equal(await text('#bus-view h1'), 'Dashboard');
|
||||
assert.doesNotMatch(await text('#bus-view'), /Not found/);
|
||||
assert.equal(await b.evaluate('document.querySelectorAll(".ws-tile, .ws-big").length'), 0);
|
||||
assert.match(await text('[data-ws-home] [data-ws-tiles]'), /^No organizations yet, so there is nothing to count\./);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-ws-home] [data-ws-orgs] a")?.getAttribute("href") ?? null'), '#/settings/organizations?new=1');
|
||||
assert.equal(await text('[data-ws-home] [data-ws-orgs] a'), 'New organization');
|
||||
await b.evaluate('document.querySelector("[data-ws-home] [data-ws-orgs] a").click()');
|
||||
await wait('document.activeElement?.id === "org-new-id"');
|
||||
await b.evaluate('location.hash = "#/"');
|
||||
await wait('document.querySelector("#dashboard-kpis .kpi strong") && !document.querySelector("[data-ws-home]")');
|
||||
assert.equal(await b.evaluate('document.querySelectorAll(".ws-tile, .ws-big").length'), 0);
|
||||
assert.deepEqual(await b.evaluate('[...new Set([...document.querySelectorAll("#dashboard-kpis .kpi strong")].map(e => e.textContent.trim()))]'), ['–']);
|
||||
});
|
||||
|
||||
test('An organization page leads with its own tiles, each linking to the system page filtered to it', async t => {
|
||||
const { b, wait, text } = await setup(t, { hash: '#/orgs/beta' });
|
||||
await wait('document.querySelector("[data-org-dashboard] [data-org-tiles] [data-ws-tile=agents] .ws-big")');
|
||||
// The tiles come straight after the header, before the docs row.
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-org-dashboard] .ws-orghead").nextElementSibling.hasAttribute("data-org-tiles")'), true);
|
||||
assert.deepEqual(await b.evaluate(tileKeys('[data-org-tiles]')), ['agents', 'tasks', 'needs', 'done']);
|
||||
assert.equal(await b.evaluate(big('[data-org-tiles]', 'agents')), '0 of 2');
|
||||
assert.equal(await b.evaluate(big('[data-org-tiles]', 'tasks')), '2');
|
||||
assert.equal(await b.evaluate(big('[data-org-tiles]', 'needs')), '2 items');
|
||||
assert.equal(await b.evaluate(big('[data-org-tiles]', 'done')), '1');
|
||||
assert.deepEqual(await b.evaluate(hrefs('[data-org-tiles]')), { agents: '#/agents?org=beta&state=working', tasks: '#/tasks?org=beta', needs: '#/inbox?org=beta', done: '#/tasks?org=beta&done=week' });
|
||||
// The empty KPI and metric placeholders are gone; there is one tile row.
|
||||
assert.doesNotMatch(await text('[data-org-dashboard]'), /No KPIs defined|No metrics recorded yet/);
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("[data-org-dashboard] .ws-tiles, [data-org-dashboard] [data-org-tiles]").length'), 1);
|
||||
// Following Needs you shows beta's two items on the system Inbox.
|
||||
await b.evaluate('document.querySelector("[data-org-tiles] [data-ws-tile=needs]").click()');
|
||||
await wait('location.hash === "#/inbox?org=beta" && document.querySelectorAll("[data-ws-item]").length === 2');
|
||||
// Acme's own page counts only acme.
|
||||
await b.evaluate('location.hash = "#/orgs/acme"');
|
||||
await wait('document.querySelector("[data-org-dashboard] [data-org-tiles] [data-ws-tile=agents] .ws-big") && location.hash.startsWith("#/orgs/acme")');
|
||||
await wait(`${big('[data-org-tiles]', 'agents')} === "1 of 2"`);
|
||||
assert.equal(await b.evaluate(big('[data-org-tiles]', 'needs')), '1 item');
|
||||
assert.equal(await b.evaluate(big('[data-org-tiles]', 'done')), '0');
|
||||
await b.evaluate('document.querySelector("[data-org-tiles] [data-ws-tile=agents]").click()');
|
||||
await wait('location.hash === "#/agents?org=acme&state=working" && JSON.stringify([...document.querySelectorAll("[data-ws-agent]")].map(r => r.dataset.wsAgent)) === JSON.stringify(["acme:coder"])');
|
||||
});
|
||||
|
||||
// SP11 (#1873): "working" and "running" each name what they count. Running is an agent with a live
|
||||
// process, whatever it is doing; working is a running agent whose role session is working. The tile,
|
||||
// the Dashboard organization rows and the sessions heading count the same agent rows.
|
||||
const delta = (scope, key) => `document.querySelector(${JSON.stringify(`${scope} [data-ws-tile=${key}] .ws-delta:not(.ws-miss)`)})?.textContent.trim() ?? null`;
|
||||
const rowAgents = org => `document.querySelector("[data-ws-orgrow=${org}] td:nth-child(2)")?.innerText.replace(/\\s+/g, " ").trim() ?? null`;
|
||||
test('Agent counts say running and working, and count the same agents on the tiles, the organization rows and the sessions heading', async t => {
|
||||
const { b, wait, text } = await setup(t);
|
||||
await wait(homeReady);
|
||||
// acme's coder runs and works; beta's pm runs and waits on you; chief and writer run nothing.
|
||||
assert.equal(await b.evaluate(big('[data-ws-home]', 'agents')), '1 of 4');
|
||||
assert.equal(await b.evaluate(delta('[data-ws-home]', 'agents')), '2 running, 1 waiting on you');
|
||||
assert.equal(await b.evaluate(rowAgents('acme')), '2 agents (1 running, 1 working)');
|
||||
assert.equal(await b.evaluate(rowAgents('beta')), '2 agents (1 running, 0 working)');
|
||||
await b.evaluate('location.hash = "#/orgs/beta"');
|
||||
await wait('document.querySelector("[data-org-dashboard] [data-org-tiles] [data-ws-tile=agents] .ws-big")');
|
||||
assert.equal(await b.evaluate(big('[data-org-tiles]', 'agents')), '0 of 2');
|
||||
assert.equal(await b.evaluate(delta('[data-org-tiles]', 'agents')), '1 running, 1 waiting on you');
|
||||
assert.match(await text('[data-org-dashboard] .ws-split'), /Active agent sessions\s*1 running, 0 working/);
|
||||
await b.evaluate('location.hash = "#/orgs/acme"');
|
||||
await wait(`location.hash.startsWith("#/orgs/acme") && (${big('[data-org-tiles]', 'agents')}) === "1 of 2"`);
|
||||
assert.equal(await b.evaluate(delta('[data-org-tiles]', 'agents')), '1 running');
|
||||
assert.match(await text('[data-org-dashboard] .ws-split'), /Active agent sessions\s*1 running, 1 working/);
|
||||
});
|
||||
|
||||
test('An organization page counts working from one read: the sessions heading and rows follow the tile when the two bus reads disagree', async t => {
|
||||
// acme's own agents read says the coder is idle; the sessions read the tile counts says working.
|
||||
const split = { acme: [{ role: 'coder', holder_run: 'run-1', harness: 'claude', state: 'idle', at: at(40) }] };
|
||||
const { b, wait, text } = await setup(t, { hash: '#/orgs/acme', split });
|
||||
await wait(`document.querySelector("[data-org-dashboard]") && (${big('[data-org-tiles]', 'agents')}) === "1 of 2"`);
|
||||
assert.match(await text('[data-org-dashboard] .ws-split'), /Active agent sessions\s*1 running, 1 working/);
|
||||
assert.match(await text('[data-org-dashboard] .ws-split tbody'), /coder[\s\S]*working/);
|
||||
});
|
||||
|
||||
test('When neither bus read gives agent activity, the sessions heading says working was not read, never a figure', async t => {
|
||||
const { b, wait, text } = await setup(t, { hash: '#/orgs/acme', fail: { acme: ['agents'] } });
|
||||
await wait('document.querySelector("[data-org-dashboard] [data-org-tiles] [data-ws-tile=agents]")');
|
||||
assert.match(await text('[data-org-tiles] [data-ws-tile=agents]'), /Not read/);
|
||||
assert.match(await text('[data-org-dashboard] .ws-split'), /Active agent sessions\s*1 running, working not read/);
|
||||
assert.doesNotMatch(await text('[data-org-dashboard] .ws-split'), /\d+ working/);
|
||||
});
|
||||
|
||||
test('A stopped organization\'s page shows its tiles as not read, still linking to its filtered pages', async t => {
|
||||
const { b, wait, text } = await setup(t, { hash: '#/orgs/gamma' });
|
||||
await wait('document.querySelector("[data-org-dashboard] [data-org-tiles]")');
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("[data-org-tiles] .ws-big").length'), 0);
|
||||
for (const key of ['agents', 'tasks', 'needs', 'done']) assert.match(await text(`[data-org-tiles] [data-ws-tile=${key}]`), /Not read: the bus is stopped/, key);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-org-tiles] [data-ws-tile=needs]").getAttribute("href")'), '#/inbox?org=gamma');
|
||||
});
|
||||
|
||||
test('At 390 wide the tiles sit two to a row with no sideways scroll, on the Dashboard and an organization page', async t => {
|
||||
const { b, wait } = await setup(t, { viewport: [390, 844] });
|
||||
await wait(homeReady);
|
||||
const cols = scope => b.evaluate(`new Set([...document.querySelectorAll(${JSON.stringify(`${scope} [data-ws-tile]`)})].map(e => Math.round(e.getBoundingClientRect().left))).size`);
|
||||
assert.equal(await cols('[data-ws-home]'), 2);
|
||||
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, 'dashboard');
|
||||
await b.evaluate('location.hash = "#/orgs/acme"');
|
||||
await wait('document.querySelector("[data-org-tiles] [data-ws-tile=agents] .ws-big")');
|
||||
assert.equal(await cols('[data-org-tiles]'), 2);
|
||||
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, 'organization page');
|
||||
});
|
||||
@@ -165,3 +165,9 @@ test('S4 fix stale project gather cannot enrich a newer request revision', async
|
||||
const x=await b.evaluate(`({revision:document.querySelector('.project-request-intro').dataset.requestRevision,prd:document.querySelector('[data-work-prd]').textContent,files:document.querySelector('[data-work-files]').textContent})`);
|
||||
assert.equal(x.revision,'2');assert.doesNotMatch(x.prd,/v3|Approved/);assert.doesNotMatch(x.files,/4 draft/);
|
||||
});
|
||||
// SP7 review: the requirement view sends the person to the conversation's Request details, which a pane
|
||||
// does not have, so both of its "Open conversation" links are marked as the full view.
|
||||
test('SP7 requirement view links the conversation\'s full view, not a pane',async t=>{const {b,wait}=await setup(t,'/projects/'+P+'/requirements');await wait(`document.querySelector('[data-prd]')`);const links=await b.evaluate(`[...document.querySelectorAll('[data-project-content] a')].filter(a=>a.textContent.trim()==='Open conversation').map(a=>a.hasAttribute('data-full-view'))`);assert.deepEqual(links,[true,true]);});
|
||||
// SP7 re-check: the overview's "Review decision" and its two request counts lead to a request, which only
|
||||
// the conversation's full view shows, so each link that names a conversation is marked as the full view.
|
||||
test('SP7 overview decision and request links go to the conversation\'s full view',async t=>{const {b,wait}=await setup(t,'/projects');await b.evaluate(`reviewStates['request-1'].wait={kind:'decision'};document.querySelector('#refresh').click();location.hash='#/projects/${P}'`);await wait(`document.querySelector('.project-decision a')`);const got=await b.evaluate(`({decision:[...document.querySelectorAll('.project-decision a')].map(a=>[a.textContent.trim(),a.hasAttribute('data-full-view'),/\\/threads\\//.test(a.getAttribute('href'))]),metrics:[...document.querySelectorAll('.project-metrics a')].map(a=>[a.querySelector('span').textContent,/\\/threads\\//.test(a.getAttribute('href')),a.hasAttribute('data-full-view')])})`);assert.deepEqual(got,{decision:[['Review decision',true,true]],metrics:[['Requests in progress',true,true],['Needs your input',true,true],['Conversations',false,false],['Files',false,false]]});});
|
||||
@@ -371,6 +371,10 @@ test('a stopped organization\'s page shows one bus banner, with the restart acti
|
||||
assert.match(shown[0], /The bus is not running\. Nothing about Gamma Home's agents or packs can be read until it starts\./);
|
||||
assert.match(shown[0], /Restart the bus/);
|
||||
assert.equal(await b.evaluate('document.getElementById("bus-down").hidden'), true);
|
||||
// SP7 item 7: one restart control on the page, the banner's; the header draws no second one.
|
||||
const restarts = 'Array.from(document.querySelectorAll("[data-bus-restart], [data-bus-restart-off]")).filter(e => e.getClientRects().length).map(e => e.closest("[data-org-down]") ? "banner" : "header")';
|
||||
assert.deepEqual(await b.evaluate(restarts), ['banner']);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-org-dashboard] .ws-orghead [data-dashboard-bus]")'), null);
|
||||
// The organization's other pages keep the shell's banner, with its restart.
|
||||
await b.evaluate('location.hash = "#/orgs/gamma/agents"');
|
||||
await wait('!document.getElementById("bus-down").hidden && /Bus unavailable/.test(document.getElementById("bus-down").textContent)');
|
||||
|
||||
@@ -17,7 +17,7 @@ const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++)
|
||||
const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString();
|
||||
|
||||
const HIRE = '0f3c1a2b-4d5e-4f60-8a7b-9c0d1e2f3a4b';
|
||||
function fixture({ empty = false } = {}) {
|
||||
function fixture({ empty = false, unheld = false } = {}) {
|
||||
const LIST = [
|
||||
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true },
|
||||
{ id: 'beta', label: 'Beta Works', theme: 'grove', busHealthy: true },
|
||||
@@ -38,6 +38,8 @@ function fixture({ empty = false } = {}) {
|
||||
},
|
||||
};
|
||||
if (empty) for (const d of Object.values(DATA)) { d.instances = {}; d.agents = []; }
|
||||
// `unheld`: a live designer run that holds no role session, so the bus reports no state for it.
|
||||
if (unheld) DATA.acme.instances.designer = { definition: 'designer', running: ['run-5'] };
|
||||
const value = (id, name) => Promise.resolve(DATA[id]?.[name] ?? (['usage', 'limits'].includes(name) ? {} : []));
|
||||
const opts = id => ({
|
||||
bus: { inbox: () => value(id, 'inbox'), agents: () => value(id, 'agents'), 'thread.claims': () => value(id, 'claims'), tasks: () => value(id, 'tasks'), usage: () => value(id, 'usage'), limits: () => value(id, 'limits'), decisions: () => value(id, 'decisions') },
|
||||
@@ -90,8 +92,8 @@ const STUB = `(() => {
|
||||
};
|
||||
})();`;
|
||||
|
||||
async function setup(t, { viewport = [1440, 900], hash = '#/agents', empty = false, stub = false, noDecide = [] } = {}) {
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: fixture({ empty }), log: () => {} });
|
||||
async function setup(t, { viewport = [1440, 900], hash = '#/agents', empty = false, unheld = false, stub = false, noDecide = [] } = {}) {
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: fixture({ empty, unheld }), log: () => {} });
|
||||
t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
await b.viewport(...viewport);
|
||||
@@ -102,6 +104,7 @@ async function setup(t, { viewport = [1440, 900], hash = '#/agents', empty = fal
|
||||
}
|
||||
const rows = 'JSON.stringify([...document.querySelectorAll("[data-ws-agent]")].map(r => r.dataset.wsAgent))';
|
||||
const are = list => `${rows} === ${JSON.stringify(JSON.stringify(list))}`;
|
||||
const trail = '(document.getElementById("breadcrumbs").getClientRects().length ? document.getElementById("breadcrumbs").innerText.replace(/\\s+/g, " ").trim() : null)';
|
||||
const ALL = ['acme:chief', 'acme:coder', 'beta:pm', 'beta:research-2'];
|
||||
|
||||
test('#/agents lists both organizations\' agents in one table, each row with its organization chip', async t => {
|
||||
@@ -111,6 +114,8 @@ test('#/agents lists both organizations\' agents in one table, each row with its
|
||||
assert.equal(await b.evaluate('location.hash.split("?")[0]'), '#/agents');
|
||||
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]")?.getAttribute("href")'), '#/agents');
|
||||
assert.equal(await text('#bus-view h1'), 'Agents');
|
||||
// SP7: the page name shows once, as the heading; a trail with nothing above it is not drawn.
|
||||
assert.equal(await b.evaluate(trail), null);
|
||||
assert.equal(await text('[data-ws-agent="acme:coder"] [data-ws-orgchip]'), 'Acme Studio');
|
||||
assert.equal(await text('[data-ws-agent="beta:pm"] [data-ws-orgchip]'), 'Beta Works');
|
||||
// State from the bus, and what the agent works on: its task, with the task's project chip.
|
||||
@@ -129,6 +134,19 @@ test('#/agents lists both organizations\' agents in one table, each row with its
|
||||
assert.equal(await b.evaluate('document.querySelector(\'[data-ws-agent="beta:pm"] a[data-ws-open]\')?.getAttribute("href")'), '#/orgs/beta/agents?agent=pm');
|
||||
});
|
||||
|
||||
// SP11 (#1873): the page says how many of its rows run and how many work, in the words the Dashboard
|
||||
// tiles use. A live agent with no reported state is "Running, state unknown", not a bare "Running"
|
||||
// that reads as every running agent.
|
||||
test('#/agents counts its running and working agents, and names a running agent with no reported state', async t => {
|
||||
const { b, wait, text } = await setup(t, { unheld: true });
|
||||
await wait(are(['acme:chief', 'acme:coder', 'acme:designer', 'beta:pm', 'beta:research-2']));
|
||||
assert.match(await text('[data-ws-agents] .sub'), /^Every agent on the system, by organization\. 5 agents in 2 organizations: 3 running, 1 working\./);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-ws-astate=running]")?.innerText.replace(/\\s+/g, " ").trim()'), 'Running, state unknown 1');
|
||||
await b.evaluate('document.querySelector("[data-ws-astate=working]").click()');
|
||||
await wait(are(['acme:coder']));
|
||||
assert.match(await text('[data-ws-agents] .sub'), /1 agent in 1 organization: 1 running, 1 working\./);
|
||||
});
|
||||
|
||||
test('the organization and state filters live in the hash and survive a reload', async t => {
|
||||
const { b, base, wait } = await setup(t);
|
||||
await wait(are(ALL));
|
||||
@@ -206,6 +224,8 @@ test('#/orgs/<id>/agents shows that organization\'s rows only, with a link to ev
|
||||
assert.match(await text('[data-ws-agents] .sub'), /Beta Works/);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-ws-agents] a[href=\'#/agents\']") !== null'), true);
|
||||
assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/agents');
|
||||
// SP7: a drill-in keeps its trail back to the dashboard and the organization.
|
||||
await wait(`${trail} === 'Dashboard / Beta Works / Agents'`);
|
||||
// The organization's own levels grid and held roles still follow, under the one page heading.
|
||||
await wait('document.querySelector("[data-org-agents]")');
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("#bus-view h1").length'), 1);
|
||||
|
||||
@@ -99,6 +99,7 @@ async function setup(t, { viewport = [1440, 900], hash = '#/inbox', empty = fals
|
||||
await b.navigate(`${base}/${hash}`);
|
||||
return { b, base, wait: waitFor(b), text: sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.innerText ?? null`) };
|
||||
}
|
||||
const trail = '(document.getElementById("breadcrumbs").getClientRects().length ? document.getElementById("breadcrumbs").innerText.replace(/\\s+/g, " ").trim() : null)';
|
||||
const items = 'JSON.stringify([...document.querySelectorAll("[data-ws-item]")].map(r => r.dataset.wsItem))';
|
||||
|
||||
test('#/inbox lists both organizations in one list, newest first, each row with its organization and project chips', async t => {
|
||||
@@ -108,11 +109,15 @@ test('#/inbox lists both organizations in one list, newest first, each row with
|
||||
assert.equal(await b.evaluate('location.hash.split("?")[0]'), '#/inbox');
|
||||
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]")?.getAttribute("href")'), '#/inbox');
|
||||
assert.equal(await text('#bus-view h1'), 'Inbox');
|
||||
// SP7: the page name shows once, as the heading.
|
||||
assert.equal(await b.evaluate(trail), null);
|
||||
// Organization chips on every row; the project chip only where the item has a project.
|
||||
assert.equal(await text(`[data-ws-item="acme:${ACME_DECISION}"] [data-ws-orgchip]`), 'Acme Studio');
|
||||
assert.equal(await text(`[data-ws-item="beta:${BETA_DECISION}"] [data-ws-orgchip]`), 'Beta Works');
|
||||
assert.equal(await text(`[data-ws-item="acme:${ACME_DECISION}"] [data-ws-projchip]`), 'Website');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-ws-item="beta:${BETA_DECISION}"] [data-ws-projchip]')`), null);
|
||||
// SP7: the class chip says the decision class in words, from the one map of class words.
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-ws-item]')].map(r => r.querySelector('td.hide-m .ws-chip')?.textContent)`), ['Within role', 'Gated']);
|
||||
// The stopped organization is named at the top, before the list, with its reason.
|
||||
const note = await text('[data-ws-unread]');
|
||||
assert.match(note, /Gamma Home/);
|
||||
@@ -157,6 +162,7 @@ test('answering beta\'s row from the list while acme was opened last reaches bet
|
||||
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'acme');
|
||||
await b.evaluate(`document.querySelector('[data-ws-select="beta:${BETA_DECISION}"]').click()`);
|
||||
await wait(`document.querySelector("[data-ws-insp]")?.dataset.wsInsp === "beta:${BETA_DECISION}" && document.querySelector("#decide-section [data-decide]")`);
|
||||
assert.equal(await text('[data-ws-insp] header .ws-chip'), 'Within role');
|
||||
// The item also opens in its own organization.
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-ws-insp] [data-ws-open]")?.getAttribute("href")'), `#/orgs/beta/inbox/${BETA_DECISION}`);
|
||||
await b.evaluate(`window.__answers.push({ body: { id: '${BETA_DECISION}', action: 'answer', choice: 'high', text: 'High', confirmation: 'c-1', kind: 'decision' } }, { body: { id: '${BETA_DECISION}', op: 'resolved', choice: 'high' } })`);
|
||||
@@ -183,6 +189,8 @@ test('#/orgs/<id>/inbox is the same list filtered to that organization', async t
|
||||
await wait(`${items} === ${JSON.stringify(JSON.stringify([`beta:${BETA_DECISION}`]))}`);
|
||||
assert.match(await text('[data-ws-inbox] .sub'), /Beta Works/);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-ws-inbox] a[href=\'#/inbox\']") !== null'), true);
|
||||
// SP7: a drill-in keeps its trail.
|
||||
await wait(`${trail} === 'Dashboard / Beta Works / Inbox'`);
|
||||
// Selecting a row keeps the organization address.
|
||||
await b.evaluate(`document.querySelector('[data-ws-select="beta:${BETA_DECISION}"]').click()`);
|
||||
await wait(`location.hash.startsWith("#/orgs/beta/inbox?") && document.querySelector("[data-ws-insp]")?.dataset.wsInsp === "beta:${BETA_DECISION}"`);
|
||||
|
||||
@@ -18,7 +18,7 @@ const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++)
|
||||
const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString();
|
||||
const D = n => String(n).repeat(64);
|
||||
|
||||
function fixture({ empty = false, archived = [] } = {}) {
|
||||
function fixture({ empty = false, archived = [], done = false } = {}) {
|
||||
const LIST = [
|
||||
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true },
|
||||
{ id: 'beta', label: 'Beta Works', theme: 'grove', busHealthy: true },
|
||||
@@ -33,9 +33,11 @@ function fixture({ empty = false, archived = [] } = {}) {
|
||||
beta: [{ n: 2, title: 'Price page', state: 'in-progress', group: 'shop', assignees: [] }, { n: 3, title: 'Spring banner', state: 'todo', group: 'ads', assignees: [] }],
|
||||
};
|
||||
if (empty) { STORE.acme = []; STORE.beta = []; }
|
||||
// `done`: one task finished two days ago and one ten days ago; only the first is done this week.
|
||||
if (done) { STORE.acme.push({ n: 4, title: 'Old logo', state: 'done', group: 'site', assignees: [], ago: 60 * 24 * 10 }); STORE.beta.push({ n: 5, title: 'Launch email', state: 'done', group: 'shop', assignees: [], ago: 60 * 24 * 2 }); }
|
||||
for (const [org, list] of Object.entries(PROJECTS)) for (const p of list) p.archived = archived.includes(`${org}:${p.id}`);
|
||||
const tasks = id => (STORE[id] || []).map(t => ({ source: 'store', task_ref: `task:${t.n}`, at: at(10), priority: 0, digest: D(t.n), requirement: 'REQ-WEB-1',
|
||||
fields: { title: t.title, state: t.state, group: t.group, assignees: t.assignees, due_date: null } }));
|
||||
const tasks = id => (STORE[id] || []).map(t => ({ source: 'store', task_ref: `task:${t.n}`, at: at(t.ago ?? 10), priority: 0, digest: D(t.n), requirement: 'REQ-WEB-1',
|
||||
fields: { title: t.title, state: t.state, group: t.group, assignees: t.assignees, due_date: null, ...(t.state === 'done' ? { done: true } : {}) } }));
|
||||
const writes = [];
|
||||
const taskWrite = org => async (verb, args) => { writes.push([org, verb, args]); return { task_ref: args.task_ref, digest: D(9) }; };
|
||||
const opts = id => ({
|
||||
@@ -81,8 +83,8 @@ const STUB = noWrite => `window.__noWrite = ${JSON.stringify(noWrite)};
|
||||
};
|
||||
})();`;
|
||||
|
||||
async function setup(t, { viewport = [1440, 900], hash = '#/tasks', empty = false, noWrite = [], archived = [] } = {}) {
|
||||
const orgs = fixture({ empty, archived });
|
||||
async function setup(t, { viewport = [1440, 900], hash = '#/tasks', empty = false, noWrite = [], archived = [], done = false } = {}) {
|
||||
const orgs = fixture({ empty, archived, done });
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: orgs, send: async () => ({}), log: () => {} });
|
||||
t.after(() => close(server));
|
||||
const b = await browser({ machine: false, args: ['--disable-extensions'] }); t.after(() => b.close());
|
||||
@@ -92,6 +94,7 @@ async function setup(t, { viewport = [1440, 900], hash = '#/tasks', empty = fals
|
||||
await b.navigate(`${base}/${hash}`);
|
||||
return { b, base, orgs, wait: waitFor(b), text: sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.innerText ?? null`) };
|
||||
}
|
||||
const trail = '(document.getElementById("breadcrumbs").getClientRects().length ? document.getElementById("breadcrumbs").innerText.replace(/\\s+/g, " ").trim() : null)';
|
||||
const cards = 'JSON.stringify([...document.querySelectorAll("[data-tasks-board] [data-tb-task]")].map(e => e.dataset.tbTask).sort())';
|
||||
const ALL = JSON.stringify(JSON.stringify(['acme|task:1', 'beta|task:2', 'beta|task:3']));
|
||||
const BETA = JSON.stringify(JSON.stringify(['beta|task:2', 'beta|task:3']));
|
||||
@@ -103,6 +106,8 @@ test('#/tasks shows both organizations\' tasks on one board, each card with its
|
||||
assert.equal(await b.evaluate('location.hash'), '#/tasks');
|
||||
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]")?.getAttribute("href")'), '#/tasks');
|
||||
assert.equal(await text('#bus-view h1'), 'Tasks');
|
||||
// SP7: the page name shows once, as the heading.
|
||||
assert.equal(await b.evaluate(trail), null);
|
||||
// The per-organization page's columns.
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".tb-col h3")].map(h => h.textContent)'), ['To do', 'In progress', 'Review', 'Blocked', 'Done']);
|
||||
// One chip names the organization, with its avatar in place of the dot.
|
||||
@@ -115,6 +120,26 @@ test('#/tasks shows both organizations\' tasks on one board, each card with its
|
||||
assert.equal(await b.evaluate('document.querySelector("#bus-view .s1-stale")'), null);
|
||||
});
|
||||
|
||||
// SP11 (#1873): the Dashboard's Done this week tile opens the board on the tasks it counted: done, and
|
||||
// changed in the last seven days. The bus keeps no time a task was done, so the filter says it reads
|
||||
// the last change, the time the tile counts by. The filter lives in the address and clears.
|
||||
test('#/tasks?done=week shows only the tasks Done this week counted, says what it counts, and clears', async t => {
|
||||
const { b, base, wait, text } = await setup(t, { hash: '#/tasks?done=week', done: true });
|
||||
await wait(`${cards} === ${JSON.stringify(JSON.stringify(['beta|task:5']))}`);
|
||||
assert.match(await text('[data-tb-done]'), /^Done this week\s+×$/);
|
||||
assert.match(await b.evaluate('document.querySelector("[data-tb-done]").getAttribute("aria-label")'), /^Clear Done this week: done tasks last changed in the past 7 days$/);
|
||||
assert.match(await text('[data-tasks-board] .tb-count'), /^Showing 1 of 5 tasks\. Done this week counts done tasks by their last change; the bus records no time a task was done\.$/);
|
||||
// It survives a reload and joins the organization filter.
|
||||
await b.navigate(`${base}/#/tasks?org=acme&done=week`);
|
||||
await wait('document.querySelector("[data-tb-done]") && document.querySelector("[data-tasks-board] .ws-panel")?.textContent.includes("No tasks match these filters")');
|
||||
await b.evaluate('location.hash = "#/tasks?done=week"');
|
||||
await wait(`${cards} === ${JSON.stringify(JSON.stringify(['beta|task:5']))}`);
|
||||
// Clearing it drops it from the address and shows every task again.
|
||||
await b.evaluate('document.querySelector("[data-tb-done]").click()');
|
||||
await wait(`location.hash === "#/tasks" && ${cards} === ${JSON.stringify(JSON.stringify(['acme|task:1', 'acme|task:4', 'beta|task:2', 'beta|task:3', 'beta|task:5']))}`);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-tb-done]")'), null);
|
||||
});
|
||||
|
||||
test('the organization and project filters live in the address and survive a reload', async t => {
|
||||
const { b, base, wait } = await setup(t);
|
||||
await wait(`${cards} === ${ALL}`);
|
||||
@@ -172,6 +197,8 @@ test('#/orgs/beta/tasks shows beta\'s tasks only, with a link to every organizat
|
||||
await wait(`${cards} === ${BETA}`);
|
||||
assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/tasks');
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-tasks-board]").dataset.tbScope'), 'beta');
|
||||
// SP7: a drill-in keeps its trail.
|
||||
await wait(`${trail} === 'Dashboard / Beta Works / Tasks'`);
|
||||
// No filter is on, so no "match the filters" line: the scope is not a filter.
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-tasks-board] .tb-count")'), null);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-tb-org]")'), null);
|
||||
|
||||
@@ -136,9 +136,10 @@ test('organization dashboard renders every section from the per-organization rea
|
||||
assert.match(head.colour, /^#[0-9a-f]{6}$/i);
|
||||
// Docs come from the project files reads: only documents, named by project.
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".ws-doc")].map(a => a.innerText.replace(/\\s+/g, " ").trim())'), ['North star Spring launch', 'Launch plan Spring launch', 'Brand voice guide Brand refresh']);
|
||||
// KPIs and metrics: one honest empty tile each, with no invented number.
|
||||
const tiles = await b.evaluate('[...document.querySelectorAll(".ws-tiles")].map(t => [t.querySelectorAll(".ws-tile").length, t.querySelector(".ws-tile").classList.contains("is-empty"), t.innerText.replace(/\\s+/g, " ").trim()])');
|
||||
assert.deepEqual(tiles, [[1, true, 'No KPIs defined in the organization file'], [1, true, 'No metrics recorded yet']]);
|
||||
// SP8 (#1873): one row of figure tiles. This fixture gives no cross-organization read (no members),
|
||||
// so each tile says it was not read and shows no number.
|
||||
const tiles = await b.evaluate('[...document.querySelectorAll(".ws-tiles")].map(t => [[...t.querySelectorAll("[data-ws-tile]")].map(e => e.dataset.wsTile), t.querySelectorAll(".ws-big").length, t.innerText.match(/Not read: the read did not answer/g)?.length ?? 0])');
|
||||
assert.deepEqual(tiles, [[['agents', 'tasks', 'needs', 'done'], 0, 4]]);
|
||||
// Active agent sessions: the running instances, the thread their live run holds (chief's older
|
||||
// Kickoff notes is not it), the model with its Change link, and the state the bus reports. With no
|
||||
// reported state (montage-producer) the row says only running.
|
||||
@@ -177,7 +178,7 @@ test('organization dashboard empty states say so in one short line', async t =>
|
||||
await waitFor(b)('document.querySelector("[data-org-dashboard] [data-org-settings]")');
|
||||
const text = await b.evaluate('document.querySelector("[data-org-dashboard]").innerText');
|
||||
// Section labels are uppercased by CSS, so innerText carries the uppercase form.
|
||||
for (const line of [/Docs\s+No docs yet/i, /No KPIs defined in the organization file/, /No metrics recorded yet/, /Active agent sessions\s+none running/i, /No active agent sessions/, /Queue\s+no rows/i, /Tracker: not set/])
|
||||
for (const line of [/Docs\s+No docs yet/i, /Agents working\s+Not read/, /Done this week\s+Not read/, /Active agent sessions\s+none running/i, /No active agent sessions/, /Queue\s+no rows/i, /Tracker: not set/])
|
||||
assert.match(text, line);
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("[data-org-settings] > li").length'), SETTINGS.length);
|
||||
});
|
||||
@@ -189,9 +190,9 @@ test('organization dashboard presents sections and honest unavailable controls',
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/alpha/organization`);
|
||||
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('[data-org-dashboard]'))return;await new Promise(r=>setTimeout(r,30))}throw Error('dashboard missing')})()`);
|
||||
const text=await b.evaluate('document.querySelector("[data-org-dashboard]").innerText');
|
||||
for(const label of ['Docs','KPIs','Metrics','Active agent sessions','Settings','Queue']) assert.match(text,new RegExp(label,'i'));
|
||||
for(const label of ['Docs','Agents working','Open tasks','Needs you','Done this week','Active agent sessions','Settings','Queue']) assert.match(text,new RegExp(label,'i'));
|
||||
assert.match(text,/reload organization file/i);
|
||||
assert.match(text,/no metrics recorded yet/i);
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("[data-org-tiles] .ws-big").length'),0);
|
||||
assert.match(text,/bus unavailable, read \d/);
|
||||
assert.match(text,/Sessions unavailable/);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-org-reload]").disabled'),true);
|
||||
@@ -210,7 +211,8 @@ test('each header control is present, reload is disabled, and restart and stop a
|
||||
stop: stop ? [stop.textContent, stop.disabled, stop.closest('.bus-restart') === live.closest('.bus-restart')] : null, stopOff: stopOff ? [stopOff.textContent, stopOff.disabled, !!stopOff.title] : null,
|
||||
reload: [reload.textContent, reload.disabled, reload.title, document.getElementById(reload.getAttribute('aria-describedby'))?.textContent] };
|
||||
})()`));
|
||||
const RELOAD = ['Reload organization file', true, 'Reload arrives with the cross-org update', 'Restart is a trailed human action; reload arrives with the cross-org update.'];
|
||||
// SP11 (#1873): the line beside the disabled reload says in plain words how a change to the file loads.
|
||||
const RELOAD = ['Reload organization file', true, 'Reloading without a restart is not available yet', 'The bus reads the organization file when it starts. To load a change to the file, restart the bus.'];
|
||||
// The owner on a Console started with --send gets console-restart.js's restart button.
|
||||
// Stop bus sits beside it, in the same control, and is one press like Restart bus.
|
||||
assert.deepEqual(await header(owner), { live: ['Restart bus', false], off: null, stop: ['Stop bus', false, true], stopOff: null, reload: RELOAD });
|
||||
@@ -300,11 +302,12 @@ test('keyboard focus follows visual order and survives a data refresh', async t
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/ddigital/organization`);
|
||||
await wait('document.querySelectorAll("[data-org-dashboard] .ws-doc").length > 0 && document.querySelectorAll("#workspace-nav .ws-proj").length === 3');
|
||||
const wide = await tabStops(b, 'document.querySelector("#sections a")');
|
||||
const regions = ['nav', 'head', 'Measures and sessions', 'Settings'];
|
||||
// The right column holds the Workflows card (SP9) above Settings.
|
||||
const regions = ['nav', 'head', 'Measures and sessions', 'Workflows and settings'];
|
||||
assert.deepEqual([...new Set(wide.map(s => s.region))].filter(r => r !== 'other'), regions);
|
||||
assertVisualOrder(wide.filter(s => s.region !== 'other'), regions, '1440');
|
||||
const keys = wide.map(s => s.key);
|
||||
for (const key of ['org:forge', 'proj:ddigital:spring-launch', 'doc:spring-launch:docs/north-star.md', 'docs-all', 'agents-all', 'queue-open', 'set:Identity', 'set:Archive or delete']) assert.ok(keys.includes(key), `Tab never reaches ${key}`);
|
||||
for (const key of ['org:forge', 'proj:ddigital:spring-launch', 'doc:spring-launch:docs/north-star.md', 'docs-all', 'agents-all', 'queue-open', 'wfg-all', 'set:Identity', 'set:Archive or delete']) assert.ok(keys.includes(key), `Tab never reaches ${key}`);
|
||||
// The disabled reload is not a tab stop; the restart button is, and Stop bus follows it.
|
||||
assert.ok(!keys.includes('org-reload')); assert.ok(keys.includes('Restart bus'));
|
||||
assert.equal(keys.indexOf('Stop bus'), keys.indexOf('Restart bus') + 1);
|
||||
|
||||
@@ -45,7 +45,7 @@ export async function w15Fixture(t, { scenario = {}, slice = 'shell' } = {}) {
|
||||
if(/^\\/api\\/chat\\/threads\\/[^/]+\\/sessions$/.test(path)) return data({rows:[{id:ids.session,name:'Default',default:true}]});
|
||||
if(/^\\/api\\/chat\\/threads\\/[^/]+\\/messages(?:\\?.*)?$/.test(path)) return data({rows:[],after:null,hasMore:false});
|
||||
if(path==='/api/chat/threads' || /^\\/api\\/chat\\/threads\\?(shared=true|project=)/.test(path)) return data({rows:[{id:ids.thread,project:ids.project,name:'Project conversation',instance:'assistant'}]});
|
||||
if(/^\\/api\\/bus\\/(inbox|messages|agents|tasks|queue|trail)(\\?|$)/.test(path)) return data({rows:[],unread:0});
|
||||
if(/^\\/api\\/bus\\/(inbox|messages|agents|instances|tasks|queue|trail)(\\?|$)/.test(path)) return data({rows:[],unread:0});
|
||||
__unexpected.push(method+' '+path); return new Response(JSON.stringify({error:'fixture-unexpected-api'}),{status:403,headers:{'content-type':'application/json'}});
|
||||
};
|
||||
})();` });
|
||||
|
||||
@@ -0,0 +1,669 @@
|
||||
// Single pane SP9 (#1873): an organization's workflows, read only. #/orgs/<id>/workflows lists them,
|
||||
// #/orgs/<id>/workflows/<name> draws one as an inline-SVG graph (one box per step, an arrowed line per
|
||||
// hand-off), and the organization page carries a small card. The data is what GET /api/orgs/<id>/workflows
|
||||
// returns from the organization file: steps in order, each with a title, a state and its roles. Nothing
|
||||
// else is drawn. A stopped organization is not read and says why.
|
||||
// SP10 (#1873): the graph page edits the workflow. The change is held in the page until Save, which sends one
|
||||
// POST with the revision the page read; a refusal is shown in words and the change kept; the poll never draws
|
||||
// over a pending change. The fixture's write stub keeps the organization file and its revision, as the bus does.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { startServer } from '../src/serve.mjs';
|
||||
import { createDevOwner } from '../src/dev-owner.mjs';
|
||||
import { browser } from './browser.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
|
||||
const XSS = '<img src=x onerror=window.__sp9pwn=1>';
|
||||
const at = minutes => new Date(Date.now() - minutes * 60000).toISOString();
|
||||
const waitFor = b => (expression, what = expression) => b.evaluate(`(async()=>{for(let i=0;i<300;i++){if(${expression})return true;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(what)}+': '+document.body.innerText.slice(0,1500))})()`);
|
||||
|
||||
// The coding starter pack's workflow as pack.apply writes it (the pack's step ids are not kept).
|
||||
const CHANGE = {
|
||||
description: 'One change from task to merge.',
|
||||
steps: [
|
||||
{ title: 'Write the task', roles: ['pm'], state: 'todo' },
|
||||
{ title: 'Implement the change', roles: ['coder'], state: 'in-progress' },
|
||||
{ title: 'Review the change', roles: ['reviewer'], state: 'in-review' },
|
||||
{ title: 'Approve the merge', roles: ['human', 'merge-gate'], state: 'done' },
|
||||
],
|
||||
};
|
||||
const DOCS = {
|
||||
acme: {
|
||||
definitions: { pm: {}, coder: {}, reviewer: {} },
|
||||
workflows: { change: CHANGE, intake: { title: `Intake ${XSS}`, steps: [{ title: `Sort ${XSS}`, state: 'todo', roles: ['human'] }] } },
|
||||
projects: { site: { workflows: { change: { title: 'Site release', steps: [{ title: 'Build', state: 'in-progress', roles: ['coder'] }, { title: 'Ship', state: 'done', roles: ['human'] }] } } }, notes: { kind: 'library', workflows: { hidden: { steps: [{ title: 'x', state: 'todo', roles: ['human'] }] } } } },
|
||||
},
|
||||
bare: { definitions: {}, projects: {} },
|
||||
};
|
||||
const LIST = [
|
||||
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true },
|
||||
{ id: 'bare', label: 'Bare Works', theme: 'grove', busHealthy: true },
|
||||
{ id: 'gamma', label: 'Gamma Home', theme: 'rosewood', busHealthy: false, busStopped: true },
|
||||
];
|
||||
|
||||
// The organization files as the bus holds them: each organization's document and revision, the writes the
|
||||
// page sent, and a refusal to give the next write. A write with another revision is a revision-conflict.
|
||||
const hex = n => n.toString(16).padStart(64, '0');
|
||||
function store(writable) {
|
||||
const st = { writable, docs: structuredClone(DOCS), revs: { acme: 'a'.repeat(64), bare: 'b'.repeat(64), gamma: 'c'.repeat(64) }, writes: [], refuse: null, n: 0 };
|
||||
const fail = code => Object.assign(new Error(code), { code });
|
||||
st.write = (id, verb, args) => {
|
||||
st.writes.push({ id, verb, args: structuredClone(args) });
|
||||
if (verb !== 'workflow.set.console') throw fail('not-configured');
|
||||
if (st.refuse) { const code = st.refuse; st.refuse = null; throw fail(code); }
|
||||
if (args.revision !== st.revs[id]) throw fail('revision-conflict');
|
||||
const doc = st.docs[id], scope = args.project ? doc.projects[args.project] : doc;
|
||||
scope.workflows ??= {};
|
||||
if (args.workflow === null) delete scope.workflows[args.name]; else scope.workflows[args.name] = structuredClone(args.workflow);
|
||||
st.revs[id] = hex(++st.n);
|
||||
return { revision: st.revs[id], added: [] };
|
||||
};
|
||||
// Another writer changes the file outside the page.
|
||||
st.change = (id, fn) => { fn(st.docs[id]); st.revs[id] = hex(1000 + ++st.n); };
|
||||
return st;
|
||||
}
|
||||
function organizations(reads, st) {
|
||||
const member = org => ({
|
||||
id: org.id, doc: { appearance: { theme: org.theme }, roles: {}, projects: {} },
|
||||
status: async () => (org.busHealthy ? { healthy: true, pid: 4242, boot: null } : { healthy: false, boot: { ok: false, at: at(90), lastGood: null, reason: 'stopped by the owner' } }),
|
||||
options: () => ({ bus: { inbox: async () => [], agents: async () => [], 'thread.claims': async () => [], tasks: async () => [] }, chat: { threads: async () => [], projects: async () => [] } }),
|
||||
});
|
||||
return {
|
||||
list: async () => LIST,
|
||||
members: async () => LIST.map(member),
|
||||
resolve: async id => {
|
||||
const org = LIST.find(o => o.id === id); if (!org) return null;
|
||||
const workflowsRead = async () => { reads.push(id); if (st.failRead) throw Object.assign(new Error('org-unavailable'), { code: 'org-unavailable' }); return { revision: st.revs[id], document: structuredClone(st.docs[id] ?? {}), templates: ['writer'] }; };
|
||||
if (!org.busHealthy) return { busHealthy: false, reads: null, bus: {}, workflowsRead, chat: { projects: async () => [], threads: async () => [] } };
|
||||
return {
|
||||
busHealthy: true, workflowsRead, packsWrite: st.writable ? async (verb, args) => st.write(id, verb, args) : null, decisionWrite: async () => ({}), send: async () => ({}),
|
||||
requestRead: async verb => { if (verb === 'packs.console') return { packs: [] }; if (verb === 'autonomy.get.console') return { revision: 'e'.repeat(64), autonomy: {}, levels: {} }; throw Object.assign(new Error('not-configured'), { code: 'not-configured' }); },
|
||||
reads: { business: async () => ({ business: { id, projects: [], instances: [] } }), settings: async () => ({}), queue: async () => ({ rows: [] }) },
|
||||
bus: { instances: async () => ({ instances: {} }), agents: async () => [], 'thread.claims': async () => [], tasks: async () => [], inbox: async () => [], messages: async () => ({ messages: [] }) },
|
||||
chat: { projects: async () => [], threads: async () => [] },
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function setup(t, { path, viewport = [1440, 900], mode = null, writable = true } = {}) {
|
||||
const reads = [], st = store(writable);
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), send: async () => ({}), log: () => {}, organizations: organizations(reads, st) });
|
||||
t.after(() => close(server));
|
||||
const b = await browser({ machine: false, args: ['--disable-extensions'] });
|
||||
t.after(() => b.close());
|
||||
await b.viewport(...viewport);
|
||||
// The Console's own mode wins over the OS setting (Harbor in the dark by default), so a theme test sets it per organization.
|
||||
if (mode) await b.call('Page.addScriptToEvaluateOnNewDocument', { source: `try { for (const o of ['acme','bare','gamma']) localStorage.setItem('mosaic-console-appearance:' + o, JSON.stringify({ theme: 'harbor', mode: ${JSON.stringify(mode)} })); } catch {}` });
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/${path}`);
|
||||
return { b, reads, st, wait: waitFor(b) };
|
||||
}
|
||||
|
||||
const boxes = `[...document.querySelectorAll('[data-wfg-graph] [data-wfg-step]')]`;
|
||||
|
||||
test('the list names each workflow by scope with its steps in order, links to its graph, and keeps titles as text', { timeout: 60000 }, async t => {
|
||||
const { b, wait } = await setup(t, { path: '#/orgs/acme/workflows' });
|
||||
await wait(`document.querySelector('[data-wfg-list] [data-wfg-item="change"]')`, 'workflow list');
|
||||
assert.equal(await b.evaluate(`document.querySelector('#bus-view h1').textContent`), 'Workflows');
|
||||
// Organization first, then each code project; a library project has no workflows.
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wfg-scope-list]')].map(n=>[n.dataset.wfgScopeList,n.querySelector('h2').textContent])`), [['', 'Organization'], ['site', 'Project site']]);
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wfg-scope-list=""] [data-wfg-item]')].map(n=>n.dataset.wfgItem)`), ['change', 'intake']);
|
||||
const change = `[data-wfg-scope-list=""] [data-wfg-item="change"]`;
|
||||
assert.equal(await b.evaluate(`document.querySelector('${change} a[data-wfg-open]').getAttribute('href')`), '#/orgs/acme/workflows/change');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-scope-list="site"] [data-wfg-item="change"] a[data-wfg-open]').getAttribute('href')`), '#/orgs/acme/workflows/change?project=site');
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('${change} [data-wfg-chain] li')].map(l=>l.textContent)`), ['Write the task', 'Implement the change', 'Review the change', 'Approve the merge']);
|
||||
assert.match(await b.evaluate(`document.querySelector('${change}').textContent`), /4 steps/);
|
||||
assert.match(await b.evaluate(`document.querySelector('${change}').textContent`), /One change from task to merge\./);
|
||||
// The title is shown as written.
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-item="intake"] a[data-wfg-open]').textContent`), `Intake ${XSS}`);
|
||||
assert.equal(await b.evaluate(`document.querySelectorAll('#bus-view img').length`), 0);
|
||||
assert.equal(await b.evaluate(`window.__sp9pwn===undefined`), true);
|
||||
assert.equal(await b.evaluate(`document.querySelector('#bus-view [data-ws-unread]')`), null, 'a running bus has no unread note');
|
||||
// The trail names the organization and the page.
|
||||
await wait(`document.querySelector('#breadcrumbs [data-crumb-org]')?.textContent === 'Acme Studio'`, 'org crumb');
|
||||
// A click opens the graph.
|
||||
await b.evaluate(`document.querySelector('${change} a[data-wfg-open]').click();true`);
|
||||
await wait(`location.hash === '#/orgs/acme/workflows/change' && document.querySelectorAll('[data-wfg-graph] [data-wfg-step]').length === 4`, 'graph after click');
|
||||
});
|
||||
|
||||
test('the graph draws one box per step in order with its roles and one arrowed edge per hand-off', { timeout: 60000 }, async t => {
|
||||
const { b, wait } = await setup(t, { path: '#/orgs/acme/workflows/change' });
|
||||
await wait(`${boxes}.length === 4`, 'four boxes');
|
||||
assert.equal(await b.evaluate(`document.querySelector('#bus-view h1').textContent`), 'change');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-graph]').tagName.toLowerCase()`), 'svg');
|
||||
assert.deepEqual(await b.evaluate(`${boxes}.map(g=>g.dataset.wfgStep)`), ['1', '2', '3', '4']);
|
||||
assert.deepEqual(await b.evaluate(`${boxes}.map(g=>g.querySelector('[data-wfg-title]').textContent)`), ['Write the task', 'Implement the change', 'Review the change', 'Approve the merge']);
|
||||
// One role per line.
|
||||
assert.deepEqual(await b.evaluate(`${boxes}.map(g=>[...g.querySelectorAll('[data-wfg-roles] tspan')].map(t=>t.textContent))`), [['pm'], ['coder'], ['reviewer'], ['human', 'merge-gate']]);
|
||||
// A role that resolves to no definition or template (and is not human) is marked on its box.
|
||||
assert.deepEqual(await b.evaluate(`${boxes}.map(g=>g.querySelectorAll('[data-wfg-missing]').length)`), [0, 0, 0, 1]);
|
||||
// sp9 follow-up: the missing role's whole name shows at 1440, on its own line under "No current role:".
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wfg-step="4"] [data-wfg-missing] tspan')].map(t=>t.textContent)`), ['No current role:', 'merge-gate']);
|
||||
// At 1440 the steps run left to right.
|
||||
const xs = await b.evaluate(`${boxes}.map(g=>g.querySelector('rect').getBoundingClientRect().left)`);
|
||||
assert.deepEqual([...xs].sort((p, q) => p - q), xs);
|
||||
assert.equal(new Set(xs).size, 4);
|
||||
// One edge per hand-off, from each box to the next, with an arrowhead.
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wfg-graph] [data-wfg-edge]')].map(e=>e.dataset.wfgEdge)`), ['1-2', '2-3', '3-4']);
|
||||
const touches = await b.evaluate(`[...document.querySelectorAll('[data-wfg-graph] [data-wfg-edge]')].map(e=>{
|
||||
const [f,t]=e.dataset.wfgEdge.split('-'), box=n=>document.querySelector('[data-wfg-graph] [data-wfg-step="'+n+'"] rect').getBBox();
|
||||
const p=e.getPointAtLength(0), q=e.getPointAtLength(e.getTotalLength()), a=box(f), z=box(t), near=(pt,r)=>pt.x>=r.x-14&&pt.x<=r.x+r.width+14&&pt.y>=r.y-14&&pt.y<=r.y+r.height+14;
|
||||
return near(p,a)&&near(q,z)&&!!e.getAttribute('marker-end');})`);
|
||||
assert.deepEqual(touches, [true, true, true]);
|
||||
// The graph scrolls inside its own box, never the page.
|
||||
assert.equal(await b.evaluate(`document.documentElement.scrollWidth<=innerWidth`), true);
|
||||
// Nothing running is drawn: no read links a task to a step.
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-running]')`), null);
|
||||
});
|
||||
|
||||
test('selecting a step shows what the data holds for it and survives a repaint', { timeout: 60000 }, async t => {
|
||||
const { b, wait, reads } = await setup(t, { path: '#/orgs/acme/workflows/change' });
|
||||
await wait(`${boxes}.length === 4`, 'four boxes');
|
||||
assert.match(await b.evaluate(`document.querySelector('[data-wfg-detail]').textContent`), /Select a step/);
|
||||
await b.evaluate(`document.querySelector('[data-wfg-step="2"]').dispatchEvent(new MouseEvent('click',{bubbles:true,cancelable:true}));true`);
|
||||
await wait(`/[?&]step=2/.test(location.hash) && document.querySelector('[data-wfg-detail] [data-wfg-detail-title]')?.textContent === 'Implement the change'`, 'detail for step 2');
|
||||
assert.equal(await b.evaluate(`location.hash`), '#/orgs/acme/workflows/change?step=2');
|
||||
const field = name => b.evaluate(`document.querySelector('[data-wfg-detail] [data-wfg-field="${name}"]')?.textContent.replace(/\\s+/g,' ').trim() ?? null`);
|
||||
assert.equal(await field('position'), 'Step 2 of 4');
|
||||
assert.equal(await field('roles'), 'coder');
|
||||
assert.equal(await field('state'), 'In progress');
|
||||
assert.equal(await field('after'), 'Step 1, Write the task');
|
||||
assert.equal(await field('next'), 'Step 3, Review the change');
|
||||
// The workflow file holds no gate or inputs for a step; the panel says so once instead of inventing them.
|
||||
assert.match(await b.evaluate(`document.querySelector('[data-wfg-detail]').textContent`), /records no gate or inputs/);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-step="2"]').getAttribute('aria-current')`), 'step');
|
||||
assert.equal(await b.evaluate(`document.querySelectorAll('[data-wfg-graph] [aria-current]').length`), 1);
|
||||
// The last step hands on to nothing; an unknown role is named in the panel too.
|
||||
await b.evaluate(`document.querySelector('[data-wfg-step="4"]').dispatchEvent(new MouseEvent('click',{bubbles:true,cancelable:true}));true`);
|
||||
await wait(`document.querySelector('[data-wfg-detail] [data-wfg-detail-title]')?.textContent === 'Approve the merge'`, 'detail for step 4');
|
||||
assert.equal(await field('next'), 'Nothing: this is the last step');
|
||||
assert.match(await field('roles'), /human \(a person\)/);
|
||||
assert.match(await field('roles'), /merge-gate names no current role/);
|
||||
// Keyboard: a step box takes focus and opens on Enter, and keeps focus through the repaint.
|
||||
await b.evaluate(`document.querySelector('[data-wfg-step="1"]').focus();true`);
|
||||
assert.equal(await b.evaluate(`document.activeElement.dataset.focusKey`), 'wfg-step:1');
|
||||
await b.key('Enter');
|
||||
await wait(`document.querySelector('[data-wfg-detail] [data-wfg-detail-title]')?.textContent === 'Write the task' && document.activeElement?.dataset.focusKey === 'wfg-step:1'`, 'Enter opens step 1 and keeps focus');
|
||||
assert.equal(await b.evaluate(`location.hash`), '#/orgs/acme/workflows/change?step=1');
|
||||
await b.evaluate(`document.querySelector('[data-wfg-step="4"]').focus();true`);
|
||||
await b.key('Enter');
|
||||
await wait(`document.querySelector('[data-wfg-detail] [data-wfg-detail-title]')?.textContent === 'Approve the merge'`, 'Enter opens step 4');
|
||||
// A repaint (the poll) keeps the selection.
|
||||
const before = reads.length;
|
||||
await b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));true`);
|
||||
await wait(`document.querySelector('[data-wfg-detail] [data-wfg-detail-title]')?.textContent === 'Approve the merge'`, 'kept after repaint');
|
||||
assert.ok(reads.length >= before);
|
||||
// A project's workflow of the same name is its own graph.
|
||||
await b.evaluate(`location.hash = '#/orgs/acme/workflows/change?project=site'`);
|
||||
await wait(`${boxes}.length === 2`, 'project graph');
|
||||
assert.match(await b.evaluate(`document.querySelector('#bus-view').textContent`), /Project site/);
|
||||
// A name the scope does not hold says so.
|
||||
await b.evaluate(`location.hash = '#/orgs/acme/workflows/nope'`);
|
||||
await wait(`/No workflow named nope/.test(document.querySelector('#bus-view').textContent)`, 'unknown workflow');
|
||||
});
|
||||
|
||||
test('a step with more roles than fit shows three lines, the last counting the rest, all inside its box', { timeout: 60000 }, async t => {
|
||||
// The business-management pack's first step names four long roles.
|
||||
const roles = ['chief-executive-officer', 'chief-financial-officer', 'chief-information-officer', 'chief-information-security-officer'];
|
||||
DOCS.acme.workflows.brief = { steps: [{ title: 'Draft the brief', state: 'todo', roles }, { title: 'WWWWWWWWWWWWWWWWWWWWWWWW WWWWWWWWWWWWWWWWWWWWWWWW WWWWWWWWWWWWWWWWWWWW', state: 'done', roles: ['human'] }] };
|
||||
t.after(() => { delete DOCS.acme.workflows.brief; });
|
||||
for (const viewport of [[1440, 900], [390, 844]]) {
|
||||
await t.test(String(viewport[0]), async t2 => {
|
||||
const { b, wait } = await setup(t2, { path: '#/orgs/acme/workflows/brief', viewport });
|
||||
await wait(`${boxes}.length === 2`, 'two boxes');
|
||||
const one = `document.querySelector('[data-wfg-step="1"]')`;
|
||||
// A role longer than the box is shortened with an ellipsis (the full name is in the box's title and the step panel).
|
||||
const lines = await b.evaluate(`[...${one}.querySelectorAll('[data-wfg-roles] tspan')].map(t=>t.textContent)`);
|
||||
assert.equal(lines.length, 3);
|
||||
assert.equal(lines[2], '+2 more');
|
||||
lines.slice(0, 2).forEach((line, i) => assert.ok(line === roles[i] || (line.endsWith('…') && roles[i].startsWith(line.slice(0, -1))), line));
|
||||
if (viewport[0] === 390) assert.deepEqual(lines.slice(0, 2), roles.slice(0, 2), 'the 390 column is wide enough for the whole name');
|
||||
assert.equal(await b.evaluate(`${one}.querySelector('[data-wfg-roles] [data-wfg-more]').textContent`), '+2 more');
|
||||
// The box names every role for a pointer or a screen reader.
|
||||
const named = await b.evaluate(`${one}.querySelector('title').textContent + ' ' + (${one}.getAttribute('aria-label') ?? '')`);
|
||||
for (const r of roles) assert.ok(named.includes(r), r);
|
||||
// Every text line ends inside its own box: its drawn extent, not what the clip path lets show, ends left
|
||||
// of the clip edge (8px inside the box) and above the box bottom.
|
||||
const out = await b.evaluate(`${boxes}.flatMap(g=>{const r=g.querySelector('rect'),right=r.x.baseVal.value+r.width.baseVal.value-8,bottom=r.y.baseVal.value+r.height.baseVal.value;
|
||||
return [...g.querySelectorAll('text')].flatMap(t=>{const spans=[...t.querySelectorAll('tspan')];return (spans.length?spans:[t]).filter(e=>e.getNumberOfChars()>0).filter(e=>{let n=e.getNumberOfChars();while(n>1&&/\\s/.test(e.textContent[n-1]))n--;const z=e.getExtentOfChar(n-1),a=e.getExtentOfChar(0);return z.x+z.width>right+0.5||z.y+z.height>bottom+0.5||a.x<r.x.baseVal.value}).map(e=>e.textContent)})})`);
|
||||
assert.deepEqual(out, []);
|
||||
assert.equal(await b.evaluate(`document.documentElement.scrollWidth<=innerWidth`), true);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('an organization with no workflows says so on its page and its card, and links to apply a pack', { timeout: 60000 }, async t => {
|
||||
const { b, wait } = await setup(t, { path: '#/orgs/bare/workflows' });
|
||||
await wait(`document.querySelector('[data-wfg-list] [data-wfg-none]')`, 'none note');
|
||||
assert.match(await b.evaluate(`document.querySelector('[data-wfg-none]').textContent`), /No workflows in Bare Works yet/);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-list] [data-wfg-apply]').getAttribute('href')`), '#/orgs/bare/organization');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-list] [data-wfg-item]')`), null);
|
||||
// The organization page's card says the same and links the list.
|
||||
await b.evaluate(`location.hash = '#/orgs/bare/organization'`);
|
||||
await wait(`document.querySelector('[data-org-dashboard] [data-wfg-card] [data-wfg-none]')`, 'card none');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-card] [data-wfg-all]').getAttribute('href')`), '#/orgs/bare/workflows');
|
||||
// Apply a pack takes the person to the pack picker on the same page.
|
||||
await wait(`document.querySelector('[data-packs]')`, 'packs section');
|
||||
await b.evaluate(`document.querySelector('[data-wfg-card] [data-wfg-apply]').click();true`);
|
||||
await wait(`(()=>{const r=document.querySelector('[data-packs]').getBoundingClientRect();return r.top>=0&&r.top<innerHeight})()`, 'packs in view');
|
||||
assert.equal(await b.evaluate(`location.hash`), '#/orgs/bare/organization');
|
||||
});
|
||||
|
||||
test('the organization page card lists each workflow as a link to its graph', { timeout: 60000 }, async t => {
|
||||
const { b, wait, reads } = await setup(t, { path: '#/orgs/acme/organization' });
|
||||
await wait(`document.querySelectorAll('[data-org-dashboard] [data-wfg-card] [data-wfg-card-item]').length === 3`, 'card items');
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wfg-card] [data-wfg-card-item]')].map(a=>[a.getAttribute('href'),a.textContent.replace(/\\s+/g,' ').trim()])`), [
|
||||
['#/orgs/acme/workflows/change', 'change 4 steps'],
|
||||
['#/orgs/acme/workflows/intake', `Intake ${XSS} 1 step`],
|
||||
['#/orgs/acme/workflows/change?project=site', 'Site release 2 steps, project site'],
|
||||
]);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-card] [data-wfg-all]').getAttribute('href')`), '#/orgs/acme/workflows');
|
||||
assert.equal(await b.evaluate(`document.querySelectorAll('[data-org-dashboard] img').length`), 0);
|
||||
assert.equal(await b.evaluate(`window.__sp9pwn===undefined`), true);
|
||||
// The card reuses the page's one workflow read; it sends no second one.
|
||||
assert.equal(reads.filter(id => id === 'acme').length, 1);
|
||||
await b.evaluate(`document.querySelector('[data-wfg-card] [data-wfg-card-item]').click();true`);
|
||||
await wait(`location.hash === '#/orgs/acme/workflows/change' && document.querySelectorAll('[data-wfg-graph] [data-wfg-step]').length === 4`, 'graph from card');
|
||||
});
|
||||
|
||||
test('a stopped organization is not read: the page and card say the bus is stopped with the reason, never "no workflows"', { timeout: 60000 }, async t => {
|
||||
const { b, wait, reads } = await setup(t, { path: '#/orgs/gamma/workflows' });
|
||||
await wait(`document.querySelector('[data-wfg-list] [data-ws-unread]')`, 'unread note');
|
||||
const note = await b.evaluate(`document.querySelector('[data-wfg-list] [data-ws-unread]').textContent`);
|
||||
assert.match(note, /^Not read: Gamma Home/);
|
||||
assert.match(note, /stopped by the owner/);
|
||||
assert.doesNotMatch(await b.evaluate(`document.querySelector('#bus-view').textContent`), /No workflows/);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-none],[data-wfg-item]')`), null);
|
||||
// The graph address says the same.
|
||||
await b.evaluate(`location.hash = '#/orgs/gamma/workflows/change'`);
|
||||
await wait(`document.querySelector('[data-wfg-page] [data-ws-unread]')`, 'graph unread note');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-graph]')`), null);
|
||||
assert.doesNotMatch(await b.evaluate(`document.querySelector('#bus-view').textContent`), /No workflow/);
|
||||
// The organization page card.
|
||||
await b.evaluate(`location.hash = '#/orgs/gamma/organization'`);
|
||||
await wait(`document.querySelector('[data-org-dashboard] [data-wfg-card][data-bus-stopped]')`, 'stopped card');
|
||||
assert.match(await b.evaluate(`document.querySelector('[data-wfg-card]').textContent`), /Not read: the bus is stopped\./);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-card] [data-wfg-none]')`), null);
|
||||
assert.equal(reads.filter(id => id === 'gamma').length, 0, 'a stopped organization is not read');
|
||||
});
|
||||
|
||||
test('at 390 the graph runs top to bottom inside its box and the page does not scroll sideways', { timeout: 60000 }, async t => {
|
||||
for (const mode of ['light', 'dark']) {
|
||||
const dark = mode === 'dark';
|
||||
await t.test(mode, async t2 => {
|
||||
const { b, wait } = await setup(t2, { path: '#/orgs/acme/workflows/change?step=3', viewport: [390, 844], mode });
|
||||
await wait(`${boxes}.length === 4 && document.querySelector('[data-wfg-detail-title]')`, 'graph at 390');
|
||||
assert.equal(await b.evaluate(`document.documentElement.dataset.mode`), mode, 'the page shows the mode under test');
|
||||
const ys = await b.evaluate(`${boxes}.map(g=>g.querySelector('rect').getBoundingClientRect().top)`);
|
||||
assert.deepEqual([...ys].sort((p, q) => p - q), ys);
|
||||
assert.equal(new Set(ys).size, 4);
|
||||
assert.equal(await b.evaluate(`document.documentElement.scrollWidth<=innerWidth`), true, 'no sideways page scroll');
|
||||
// Every box fits the width of its own box.
|
||||
assert.equal(await b.evaluate(`(()=>{const w=document.querySelector('[data-wfg-graph]').closest('[data-wfg-frame]').getBoundingClientRect();return ${boxes}.every(g=>{const r=g.querySelector('rect').getBoundingClientRect();return r.left>=w.left-1&&r.right<=w.right+1})})()`), true);
|
||||
// The box text and the edges read in the theme's colours, not the browser default black on dark.
|
||||
const fill = await b.evaluate(`getComputedStyle(document.querySelector('[data-wfg-step="1"] [data-wfg-title]')).fill`);
|
||||
const bg = await b.evaluate(`getComputedStyle(document.body).backgroundColor`);
|
||||
assert.notEqual(fill, bg);
|
||||
assert.notEqual(fill, dark ? 'rgb(0, 0, 0)' : 'rgb(255, 255, 255)');
|
||||
// An SVG rect with no theme fill is drawn black.
|
||||
assert.notEqual(await b.evaluate(`getComputedStyle(document.querySelector('[data-wfg-step="1"] rect')).fill`), 'rgb(0, 0, 0)');
|
||||
// The list and the card fit too.
|
||||
await b.evaluate(`location.hash = '#/orgs/acme/workflows'`);
|
||||
await wait(`document.querySelector('[data-wfg-list] [data-wfg-item]')`, 'list at 390');
|
||||
assert.equal(await b.evaluate(`document.documentElement.scrollWidth<=innerWidth`), true, 'list: no sideways page scroll');
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ---------- SP10: editing a workflow in its graph ----------
|
||||
const REV_A = 'a'.repeat(64);
|
||||
const titles = `${boxes}.map(g=>g.querySelector('[data-wfg-title]').textContent)`;
|
||||
const press = sel => `(()=>{const e=document.querySelector(${JSON.stringify(sel)});if(!e)throw Error('no '+${JSON.stringify(sel)});if(e.disabled)throw Error('disabled '+${JSON.stringify(sel)});e.click();return true})()`;
|
||||
const pick = step => `document.querySelector('[data-wfg-step="${step}"]').dispatchEvent(new MouseEvent('click',{bubbles:true,cancelable:true}))`;
|
||||
// Sets a form field as typing would: the value, then the input event the page listens for.
|
||||
const fill = (sel, value) => `(()=>{const e=document.querySelector(${JSON.stringify(sel)});e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('input',{bubbles:true}));return true})()`;
|
||||
const role = (form, name) => `${form} input[name="role"][value="${name}"]`;
|
||||
const text = sel => `(document.querySelector(${JSON.stringify(sel)})?.textContent ?? '').replace(/\\s+/g,' ').trim()`;
|
||||
|
||||
test('editing a step changes the graph on the page, and Save sends one POST with the revision the page read', { timeout: 60000 }, async t => {
|
||||
const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?step=4' });
|
||||
await wait(`document.querySelector('[data-wfg-detail-title]')?.textContent === 'Approve the merge' && document.querySelector('[data-wfg-edit]')`, 'step 4 with Edit');
|
||||
// Nothing pending: no Unsaved, no Save.
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-unsaved],[data-wfg-save],[data-wfg-discard]')`), null);
|
||||
await b.evaluate(press('[data-wfg-edit]'));
|
||||
await wait(`document.querySelector('[data-wfg-form] [data-wfg-form-title]')?.textContent === 'Edit step 4'`, 'step form');
|
||||
assert.equal(await b.evaluate(`document.activeElement.dataset.focusKey`), 'wfg-f-title');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-form] input[name="title"]').value`), 'Approve the merge');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-form] select[name="state"]').value`), 'done');
|
||||
// The picker offers human, the organization's roles and the templates; the step's unknown role is first, checked and marked.
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wfg-form] input[name="role"]')].map(i=>[i.value,i.checked])`), [['merge-gate', true], ['human', true], ['coder', false], ['pm', false], ['reviewer', false], ['writer', false]]);
|
||||
assert.ok(await b.evaluate(`!!document.querySelector('[data-wfg-form] [data-wfg-pick-missing]')`));
|
||||
await b.evaluate(fill('[data-wfg-form] input[name="title"]', 'Approve and merge'));
|
||||
await b.evaluate(press(role('[data-wfg-form]', 'merge-gate')));
|
||||
await b.evaluate(press(role('[data-wfg-form]', 'reviewer')));
|
||||
await b.evaluate(press('[data-wfg-apply]'));
|
||||
await wait(`${titles}[3] === 'Approve and merge' && document.querySelector('[data-wfg-unsaved]')`, 'pending change drawn');
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wfg-step="4"] [data-wfg-roles] tspan')].map(t=>t.textContent)`), ['human', 'reviewer']);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-step="4"] [data-wfg-missing]')`), null);
|
||||
assert.equal(await b.evaluate(text('[data-wfg-unsaved]')), 'Unsaved');
|
||||
assert.equal(await b.evaluate(`document.activeElement.dataset.focusKey`), 'wfg-save');
|
||||
assert.equal(st.writes.length, 0, 'Apply writes nothing');
|
||||
await b.evaluate(press('[data-wfg-save]'));
|
||||
await wait(`/Saved change\\./.test(${text('[data-wfg-status]')}) && !document.querySelector('[data-wfg-unsaved]')`, 'saved');
|
||||
assert.equal(st.writes.length, 1);
|
||||
assert.deepEqual(st.writes[0], { id: 'acme', verb: 'workflow.set.console', args: { revision: REV_A, name: 'change', workflow: {
|
||||
description: 'One change from task to merge.',
|
||||
steps: [
|
||||
{ title: 'Write the task', state: 'todo', roles: ['pm'] },
|
||||
{ title: 'Implement the change', state: 'in-progress', roles: ['coder'] },
|
||||
{ title: 'Review the change', state: 'in-review', roles: ['reviewer'] },
|
||||
{ title: 'Approve and merge', state: 'done', roles: ['human', 'reviewer'] },
|
||||
] } } });
|
||||
// The page now draws the file as saved, read again.
|
||||
await wait(`document.querySelector('[data-wfg-detail-title]')?.textContent === 'Approve and merge'`, 'detail after save');
|
||||
assert.deepEqual(st.docs.acme.workflows.change.steps[3], { title: 'Approve and merge', state: 'done', roles: ['human', 'reviewer'] });
|
||||
});
|
||||
|
||||
test('add, move, remove and discard change only the page until Save', { timeout: 60000 }, async t => {
|
||||
const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?step=2' });
|
||||
await wait(`document.querySelector('[data-wfg-detail-title]')?.textContent === 'Implement the change'`, 'step 2');
|
||||
// Add after the selected step.
|
||||
await b.evaluate(press('[data-wfg-add]'));
|
||||
await wait(`document.querySelector('[data-wfg-form-title]')?.textContent === 'New step 3'`, 'add form');
|
||||
await b.evaluate(fill('[data-wfg-form] input[name="title"]', 'Test the change'));
|
||||
await b.evaluate(`(()=>{const e=document.querySelector('[data-wfg-form] select[name="state"]');e.value='in-review';e.dispatchEvent(new Event('input',{bubbles:true}));return true})()`);
|
||||
// Apply with no role is refused in words, and the form stays.
|
||||
await b.evaluate(press('[data-wfg-apply]'));
|
||||
await wait(`${text('[data-wfg-why]')} === 'Step 3 needs at least one role.'`, 'no role refused');
|
||||
await b.evaluate(press(role('[data-wfg-form]', 'coder')));
|
||||
await b.evaluate(press('[data-wfg-apply]'));
|
||||
await wait(`${boxes}.length === 5 && ${titles}[2] === 'Test the change'`, 'step added');
|
||||
assert.equal(await b.evaluate(`location.hash`), '#/orgs/acme/workflows/change?step=3');
|
||||
assert.equal(await b.evaluate(text('[data-wfg-field="state"]')), 'Review');
|
||||
assert.ok(await b.evaluate(`!!document.querySelector('[data-wfg-unsaved]')`));
|
||||
// Move earlier and later.
|
||||
await b.evaluate(press('[data-wfg-up]'));
|
||||
await wait(`${titles}[1] === 'Test the change' && /step=2/.test(location.hash)`, 'moved earlier');
|
||||
assert.equal(await b.evaluate(`document.activeElement.dataset.focusKey`), 'wfg-up');
|
||||
await b.evaluate(press('[data-wfg-down]'));
|
||||
await wait(`${titles}[2] === 'Test the change' && /step=3/.test(location.hash)`, 'moved later');
|
||||
// Selecting another step goes through a full render (a read); the pending change stays.
|
||||
await b.evaluate(pick(1));
|
||||
await wait(`document.querySelector('[data-wfg-detail-title]')?.textContent === 'Write the task' && ${boxes}.length === 5`, 'step 1, change kept');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-up]').disabled`), true, 'the first step cannot move earlier');
|
||||
await b.evaluate(press('[data-wfg-remove]'));
|
||||
await wait(`${boxes}.length === 4`, 'step removed');
|
||||
assert.deepEqual(await b.evaluate(titles), ['Implement the change', 'Test the change', 'Review the change', 'Approve the merge']);
|
||||
// With no step selected, Add puts a step at the end.
|
||||
await b.evaluate(`location.hash = '#/orgs/acme/workflows/change'`);
|
||||
await wait(`${text('[data-wfg-add]')} === 'Add a step at the end'`, 'add at end');
|
||||
await b.evaluate(press('[data-wfg-add]'));
|
||||
await wait(`document.querySelector('[data-wfg-form-title]')?.textContent === 'New step 5'`, 'add-at-end form');
|
||||
await b.evaluate(fill('[data-wfg-form] input[name="title"]', 'Announce it'));
|
||||
await b.evaluate(press(role('[data-wfg-form]', 'pm')));
|
||||
await b.evaluate(press('[data-wfg-apply]'));
|
||||
await wait(`${boxes}.length === 5 && ${titles}[4] === 'Announce it' && /step=5/.test(location.hash)`, 'added at end');
|
||||
// Discard drops all of it; nothing was written.
|
||||
await b.evaluate(press('[data-wfg-discard]'));
|
||||
await wait(`${boxes}.length === 4 && !document.querySelector('[data-wfg-unsaved]')`, 'discarded');
|
||||
assert.deepEqual(await b.evaluate(titles), ['Write the task', 'Implement the change', 'Review the change', 'Approve the merge']);
|
||||
assert.equal(st.writes.length, 0);
|
||||
});
|
||||
|
||||
test('a refused save says why next to Save and keeps the pending change', { timeout: 60000 }, async t => {
|
||||
const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?step=1' });
|
||||
await wait(`document.querySelector('[data-wfg-edit]')`, 'step 1');
|
||||
await b.evaluate(press('[data-wfg-edit]'));
|
||||
await wait(`document.querySelector('[data-wfg-form]')`, 'form');
|
||||
await b.evaluate(fill('[data-wfg-form] input[name="title"]', 'Write the brief'));
|
||||
await b.evaluate(press('[data-wfg-apply]'));
|
||||
await wait(`${titles}[0] === 'Write the brief'`, 'pending');
|
||||
// Step 4 still names merge-gate: the page refuses before sending, in the same words as the form editor.
|
||||
await b.evaluate(press('[data-wfg-save]'));
|
||||
await wait(`${text('[data-wfg-status]')} === 'Step 4: merge-gate names no current role. Use an organization role, a role template or human.'`, 'unknown role refused');
|
||||
assert.equal(st.writes.length, 0);
|
||||
assert.ok(await b.evaluate(`${titles}[0] === 'Write the brief' && !!document.querySelector('[data-wfg-unsaved]')`));
|
||||
// Fix step 4, then the bus is down.
|
||||
await b.evaluate(pick(4));
|
||||
await wait(`document.querySelector('[data-wfg-detail-title]')?.textContent === 'Approve the merge'`, 'step 4');
|
||||
await b.evaluate(press('[data-wfg-edit]'));
|
||||
await wait(`document.querySelector('[data-wfg-form-title]')?.textContent === 'Edit step 4'`, 'form 4');
|
||||
await b.evaluate(press(role('[data-wfg-form]', 'merge-gate')));
|
||||
await b.evaluate(press('[data-wfg-apply]'));
|
||||
await wait(`!document.querySelector('[data-wfg-step="4"] [data-wfg-missing]')`, 'step 4 fixed');
|
||||
st.refuse = 'no-bus-host';
|
||||
await b.evaluate(press('[data-wfg-save]'));
|
||||
await wait(`/bus is not running/.test(${text('[data-wfg-status]')})`, 'bus down refused');
|
||||
assert.match(await b.evaluate(text('[data-wfg-status]')), /Your change is kept/);
|
||||
assert.equal(st.writes.length, 1);
|
||||
assert.equal(st.writes[0].args.revision, REV_A);
|
||||
assert.ok(await b.evaluate(`${titles}[0] === 'Write the brief' && !!document.querySelector('[data-wfg-unsaved]') && !!document.querySelector('[data-wfg-save]')`));
|
||||
assert.equal(st.docs.acme.workflows.change.steps[0].title, 'Write the task', 'nothing written');
|
||||
// The status sits in the bar with Save.
|
||||
assert.ok(await b.evaluate(`!!document.querySelector('[data-wfg-bar] [data-wfg-status]') && !!document.querySelector('[data-wfg-bar] [data-wfg-save]')`));
|
||||
// Another writer changes this workflow: the save is refused as stale, the change kept.
|
||||
st.change('acme', doc => { doc.workflows.change.description = 'Changed elsewhere.'; });
|
||||
await b.evaluate(press('[data-wfg-save]'));
|
||||
await wait(`/changed since this page read it/.test(${text('[data-wfg-status]')})`, 'stale refused');
|
||||
assert.match(await b.evaluate(text('[data-wfg-status]')), /Your change is kept\. Discard to load the current version\./);
|
||||
assert.ok(await b.evaluate(`${titles}[0] === 'Write the brief' && !!document.querySelector('[data-wfg-unsaved]')`));
|
||||
assert.equal(st.writes.length, 2);
|
||||
});
|
||||
|
||||
test('the poll does not draw over a pending change, takes a new revision when only other workflows changed, and says when this one changed', { timeout: 60000 }, async t => {
|
||||
const { b, wait, st, reads } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=2' });
|
||||
// The site project's workflow names only current roles, so a save goes to the bus.
|
||||
await wait(`document.querySelector('[data-wfg-edit]')`, 'step 2');
|
||||
const repaint = async () => { const n = reads.length; await b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));true`); await wait(`true`); for (let i = 0; i < 100 && reads.length === n; i++) await new Promise(r => setTimeout(r, 30)); await new Promise(r => setTimeout(r, 150)); };
|
||||
// A form being typed in survives a repaint as typed.
|
||||
await b.evaluate(press('[data-wfg-edit]'));
|
||||
await wait(`document.querySelector('[data-wfg-form]')`, 'form');
|
||||
await b.evaluate(fill('[data-wfg-form] input[name="title"]', 'Ship the release'));
|
||||
await repaint();
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-form] input[name="title"]')?.value`), 'Ship the release');
|
||||
await b.evaluate(press('[data-wfg-apply]'));
|
||||
await wait(`${titles}[1] === 'Ship the release' && document.querySelector('[data-wfg-unsaved]')`, 'pending');
|
||||
await repaint();
|
||||
assert.equal(await b.evaluate(`${titles}[1]`), 'Ship the release', 'the poll keeps the pending change');
|
||||
assert.ok(await b.evaluate(`!!document.querySelector('[data-wfg-unsaved]')`));
|
||||
// Another workflow changes in the file: this one is as read, so the page takes the new revision and no warning shows.
|
||||
st.change('acme', doc => { doc.workflows.intake.title = 'Intake, renamed'; });
|
||||
const fresh = st.revs.acme;
|
||||
await repaint();
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-stale]')`), null);
|
||||
assert.equal(await b.evaluate(`${titles}[1]`), 'Ship the release');
|
||||
await b.evaluate(press('[data-wfg-save]'));
|
||||
await wait(`/Saved change\\./.test(${text('[data-wfg-status]')})`, 'saved on the new revision');
|
||||
assert.equal(st.writes.at(-1).args.revision, fresh);
|
||||
assert.equal(st.docs.acme.workflows.intake.title, 'Intake, renamed', 'the other workflow is untouched');
|
||||
// Now this workflow changes underneath a pending change: the page says so and offers Discard.
|
||||
await b.evaluate(press('[data-wfg-edit]'));
|
||||
await wait(`document.querySelector('[data-wfg-form]')`, 'form again');
|
||||
await b.evaluate(fill('[data-wfg-form] input[name="title"]', 'Build it'));
|
||||
await b.evaluate(press('[data-wfg-apply]'));
|
||||
await wait(`${titles}[1] === 'Build it'`, 'pending again');
|
||||
st.change('acme', doc => { doc.projects.site.workflows.change.description = 'Changed elsewhere.'; });
|
||||
await repaint();
|
||||
await wait(`!!document.querySelector('[data-wfg-stale]')`, 'stale note');
|
||||
assert.match(await b.evaluate(text('[data-wfg-stale]')), /changed this workflow since the page read it.*Discard to load the current version/);
|
||||
assert.equal(await b.evaluate(`${titles}[1]`), 'Build it');
|
||||
assert.ok(await b.evaluate(`!!document.querySelector('[data-wfg-discard]')`));
|
||||
await b.evaluate(press('[data-wfg-discard]'));
|
||||
await wait(`${titles}[1] === 'Ship the release' && !document.querySelector('[data-wfg-stale],[data-wfg-unsaved]')`, 'discarded to current');
|
||||
assert.match(await b.evaluate(`document.querySelector('#bus-view .sub').textContent`), /Changed elsewhere\./);
|
||||
});
|
||||
|
||||
test('a reader who cannot write sees no edit controls and one line saying who can', { timeout: 60000 }, async t => {
|
||||
const { b, wait } = await setup(t, { path: '#/orgs/acme/workflows/change?step=2', writable: false });
|
||||
await wait(`document.querySelector('[data-wfg-detail-title]')?.textContent === 'Implement the change'`, 'step 2');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-bar],[data-wfg-actions],[data-wfg-edit],[data-wfg-add],[data-wfg-save],[data-wfg-delete],[data-wfg-form]')`), null);
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('#bus-view [data-wfg-readonly]')].map(n=>n.textContent)`), ['Only the owner, on a Console started with send, can change workflows.']);
|
||||
assert.equal(await b.evaluate(`document.querySelectorAll('#bus-view button').length`), 0);
|
||||
await b.evaluate(`location.hash = '#/orgs/acme/workflows'`);
|
||||
await wait(`document.querySelector('[data-wfg-list] [data-wfg-item]')`, 'list');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-new]')`), null);
|
||||
assert.ok(await b.evaluate(`!!document.querySelector('[data-wfg-list] [data-wfg-readonly]')`));
|
||||
});
|
||||
|
||||
test('a new workflow starts on the list page, opens in its graph unsaved, saves, and deletes after a confirm', { timeout: 60000 }, async t => {
|
||||
const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows' });
|
||||
await wait(`document.querySelector('[data-wfg-new]')`, 'New workflow');
|
||||
await b.evaluate(press('[data-wfg-new]'));
|
||||
await wait(`document.querySelector('[data-wfg-newform]')`, 'new form');
|
||||
assert.equal(await b.evaluate(`document.activeElement.dataset.focusKey`), 'wfg-n-name');
|
||||
const create = async () => b.evaluate(press('[data-wfg-create]'));
|
||||
await b.evaluate(fill('[data-wfg-newform] input[name="name"]', 'Release Plan'));
|
||||
await create();
|
||||
await wait(`${text('[data-wfg-newform] [data-wfg-why]')} === 'A workflow name is 1 to 64 lowercase letters, digits or dashes, starting with a letter.'`, 'name refused');
|
||||
await b.evaluate(fill('[data-wfg-newform] input[name="name"]', 'change'));
|
||||
await create();
|
||||
await wait(`${text('[data-wfg-newform] [data-wfg-why]')} === 'A workflow named change already exists here. Edit it instead.'`, 'taken refused');
|
||||
await b.evaluate(fill('[data-wfg-newform] input[name="name"]', 'release'));
|
||||
await b.evaluate(fill('[data-wfg-newform] input[name="title"]', 'Cut the release'));
|
||||
await create();
|
||||
await wait(`${text('[data-wfg-newform] [data-wfg-why]')} === 'Step 1 needs at least one role.'`, 'role refused');
|
||||
await b.evaluate(press(role('[data-wfg-newform]', 'human')));
|
||||
await create();
|
||||
await wait(`location.hash === '#/orgs/acme/workflows/release?step=1' && ${boxes}.length === 1`, 'opens in the graph');
|
||||
assert.equal(await b.evaluate(text('[data-wfg-unsaved]')), 'Unsaved, not in the file yet');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-delete]')`), null, 'nothing to delete yet');
|
||||
assert.equal(st.writes.length, 0);
|
||||
// The list shows it, marked.
|
||||
await b.evaluate(`location.hash = '#/orgs/acme/workflows'`);
|
||||
await wait(`document.querySelector('[data-wfg-item="release"] [data-wfg-unsaved]')`, 'listed unsaved');
|
||||
await b.evaluate(press('[data-wfg-item="release"] a[data-wfg-open]'));
|
||||
await wait(`${boxes}.length === 1 && document.querySelector('[data-wfg-save]')`, 'back in the graph');
|
||||
await b.evaluate(press('[data-wfg-save]'));
|
||||
await wait(`/Saved release\\./.test(${text('[data-wfg-status]')}) && document.querySelector('[data-wfg-delete]')`, 'saved');
|
||||
assert.deepEqual(st.writes[0].args, { revision: REV_A, name: 'release', workflow: { steps: [{ title: 'Cut the release', state: 'todo', roles: ['human'] }] } });
|
||||
// Delete asks first; Keep keeps it.
|
||||
await b.evaluate(press('[data-wfg-delete]'));
|
||||
await wait(`document.querySelector('[data-wfg-confirm]')`, 'confirm');
|
||||
assert.match(await b.evaluate(text('[data-wfg-confirm]')), /Delete release from the organization file\?/);
|
||||
assert.equal(await b.evaluate(`document.activeElement.dataset.focusKey`), 'wfg-delete-no');
|
||||
await b.evaluate(press('[data-wfg-delete-no]'));
|
||||
await wait(`!document.querySelector('[data-wfg-confirm]') && document.activeElement?.dataset.focusKey === 'wfg-delete'`, 'kept');
|
||||
assert.equal(st.writes.length, 1);
|
||||
const saved = st.revs.acme;
|
||||
await b.evaluate(press('[data-wfg-delete]'));
|
||||
await wait(`document.querySelector('[data-wfg-delete-yes]')`, 'confirm again');
|
||||
await b.evaluate(press('[data-wfg-delete-yes]'));
|
||||
await wait(`location.hash === '#/orgs/acme/workflows' && /Deleted release\\./.test(${text('[data-wfg-list] [data-wfg-status]')}) && !document.querySelector('[data-wfg-item="release"]')`, 'deleted');
|
||||
assert.deepEqual(st.writes[1].args, { revision: saved, name: 'release', workflow: null });
|
||||
assert.equal(Object.hasOwn(st.docs.acme.workflows, 'release'), false);
|
||||
});
|
||||
|
||||
test('the keyboard alone opens a step, edits it and saves', { timeout: 60000 }, async t => {
|
||||
const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site' });
|
||||
await wait(`${boxes}.length === 2`, 'graph');
|
||||
await b.evaluate(`document.querySelector('[data-wfg-step="1"]').focus();true`);
|
||||
await b.key('Enter');
|
||||
await wait(`document.querySelector('[data-wfg-detail-title]')?.textContent === 'Build' && document.activeElement?.dataset.focusKey === 'wfg-step:1'`, 'Enter opens step 1');
|
||||
const tabTo = async (sel, what) => {
|
||||
for (let i = 0; i < 20; i++) { if (await b.evaluate(`document.activeElement?.matches(${JSON.stringify(sel)}) ?? false`)) return; await b.key('Tab'); }
|
||||
throw new Error(`Tab never reached ${what}`);
|
||||
};
|
||||
await tabTo('[data-wfg-edit]', 'Edit step');
|
||||
await b.key('Enter');
|
||||
await wait(`document.querySelector('[data-wfg-form-title]')?.textContent === 'Edit step 1' && document.activeElement?.dataset.focusKey === 'wfg-f-title'`, 'form with focus on the title');
|
||||
await b.call('Input.insertText', { text: ' now' });
|
||||
await tabTo(`[data-wfg-form] input[name="role"][value="reviewer"]`, 'the reviewer box');
|
||||
await b.key(' ', 'Space');
|
||||
await tabTo('[data-wfg-apply]', 'Apply');
|
||||
await b.key('Enter');
|
||||
await wait(`${titles}[0] === 'Build now' && document.activeElement?.dataset.focusKey === 'wfg-save'`, 'applied, focus on Save');
|
||||
await b.key('Enter');
|
||||
await wait(`/Saved change\\./.test(${text('[data-wfg-status]')})`, 'saved');
|
||||
assert.deepEqual(st.writes[0].args, { revision: REV_A, name: 'change', project: 'site', workflow: { title: 'Site release', steps: [
|
||||
{ title: 'Build now', state: 'in-progress', roles: ['coder', 'reviewer'] }, { title: 'Ship', state: 'done', roles: ['human'] }] } });
|
||||
});
|
||||
|
||||
test('switching organization with a pending workflow change asks first, through the existing draft guard', { timeout: 60000 }, async t => {
|
||||
const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=1' });
|
||||
await wait(`document.querySelector('[data-wfg-edit]') && document.querySelector('#breadcrumbs [data-crumb-org]')`, 'step 1');
|
||||
await b.evaluate(press('[data-wfg-remove]'));
|
||||
await wait(`${boxes}.length === 1 && document.querySelector('[data-wfg-unsaved]')`, 'pending removal');
|
||||
assert.equal(await b.evaluate(`window.MosaicWorkflows.hasDraft()`), true);
|
||||
await b.evaluate(`location.hash = '#/orgs/bare/workflows'`);
|
||||
await wait(`document.querySelector('dialog[aria-label="Unsaved draft"][open]')`, 'guard dialog');
|
||||
await b.evaluate(press('dialog [data-stay]'));
|
||||
await wait(`!document.querySelector('dialog[open]') && /#\\/orgs\\/acme\\/workflows\\/change/.test(location.hash) && ${boxes}.length === 1`, 'stayed with the change');
|
||||
await b.evaluate(`location.hash = '#/orgs/bare/workflows'`);
|
||||
await wait(`document.querySelector('dialog[aria-label="Unsaved draft"][open]')`, 'guard dialog again');
|
||||
await b.evaluate(press('dialog [data-discard]'));
|
||||
await wait(`location.hash === '#/orgs/bare/workflows' && document.querySelector('[data-wfg-list][data-wfg-org="bare"]')`, 'switched');
|
||||
assert.equal(await b.evaluate(`window.MosaicWorkflows.hasDraft()`), false);
|
||||
assert.equal(st.writes.length, 0);
|
||||
});
|
||||
|
||||
test('Save with a step form holding edits not applied refuses in words and sends nothing; after Apply it sends them', { timeout: 60000 }, async t => {
|
||||
const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=2' });
|
||||
await wait(`document.querySelector('[data-wfg-up]')`, 'step 2');
|
||||
// One change pending, so Save shows; then a step form is opened and typed in, not applied.
|
||||
await b.evaluate(press('[data-wfg-up]'));
|
||||
await wait(`${titles}[0] === 'Ship' && document.querySelector('[data-wfg-save]')`, 'moved');
|
||||
await b.evaluate(press('[data-wfg-edit]'));
|
||||
await wait(`document.querySelector('[data-wfg-form]')`, 'form');
|
||||
await b.evaluate(fill('[data-wfg-form] input[name="title"]', 'Ship the release'));
|
||||
await b.evaluate(press('[data-wfg-save]'));
|
||||
await wait(`/Apply or cancel the step first/.test(${text('[data-wfg-status]')})`, 'save refused');
|
||||
assert.equal(await b.evaluate(text('[data-wfg-status]')), 'Not saved: step 1 has edits not applied. Apply or cancel the step first.');
|
||||
assert.equal(st.writes.length, 0);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-form] input[name="title"]')?.value`), 'Ship the release', 'the typed title stays');
|
||||
await b.evaluate(press('[data-wfg-apply]'));
|
||||
await wait(`${titles}[0] === 'Ship the release'`, 'applied');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-status]')`), null, 'Apply clears the refusal');
|
||||
await b.evaluate(press('[data-wfg-save]'));
|
||||
await wait(`/Saved change\\./.test(${text('[data-wfg-status]')})`, 'saved');
|
||||
assert.equal(st.writes.length, 1);
|
||||
assert.deepEqual(st.writes[0].args.workflow.steps.map(s => s.title), ['Ship the release', 'Build']);
|
||||
});
|
||||
|
||||
test('Delete on a view another writer has changed is refused, not deleted over', { timeout: 60000 }, async t => {
|
||||
const { b, wait, st, reads } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=1' });
|
||||
await wait(`document.querySelector('[data-wfg-remove]')`, 'step 1');
|
||||
await b.evaluate(press('[data-wfg-remove]'));
|
||||
await wait(`${boxes}.length === 1 && document.querySelector('[data-wfg-unsaved]')`, 'pending removal');
|
||||
st.change('acme', doc => { doc.projects.site.workflows.change.description = 'Changed elsewhere.'; });
|
||||
const n = reads.length;
|
||||
await b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));true`);
|
||||
await wait(`!!document.querySelector('[data-wfg-stale]')`, 'stale note');
|
||||
assert.ok(reads.length > n);
|
||||
await b.evaluate(press('[data-wfg-delete]'));
|
||||
await wait(`document.querySelector('[data-wfg-delete-yes]')`, 'confirm');
|
||||
await b.evaluate(press('[data-wfg-delete-yes]'));
|
||||
await wait(`/^Not deleted/.test(${text('[data-wfg-status]')})`, 'delete refused');
|
||||
assert.equal(await b.evaluate(text('[data-wfg-status]')), 'Not deleted: the organization file changed this workflow since the page read it. Discard to load the current version.');
|
||||
assert.equal(st.writes.length, 1);
|
||||
assert.equal(st.writes[0].args.revision, REV_A);
|
||||
assert.equal(st.writes[0].args.workflow, null);
|
||||
assert.equal(st.docs.acme.projects.site.workflows.change.description, 'Changed elsewhere.', 'the newer workflow is still in the file');
|
||||
assert.ok(await b.evaluate(`${boxes}.length === 1 && !!document.querySelector('[data-wfg-unsaved]')`), 'the pending change stays');
|
||||
// With no pending change there is no Discard, so the refusal does not point at one.
|
||||
await b.evaluate(press('[data-wfg-discard]'));
|
||||
await wait(`${boxes}.length === 2 && !document.querySelector('[data-wfg-unsaved]')`, 'discarded');
|
||||
await b.evaluate(press('[data-wfg-delete]'));
|
||||
await wait(`document.querySelector('[data-wfg-delete-yes]')`, 'confirm again');
|
||||
st.change('acme', doc => { doc.projects.site.workflows.change.description = 'Changed again.'; });
|
||||
await b.evaluate(press('[data-wfg-delete-yes]'));
|
||||
await wait(`/^Not deleted/.test(${text('[data-wfg-status]')})`, 'second delete refused');
|
||||
assert.equal(await b.evaluate(text('[data-wfg-status]')), 'Not deleted: the organization file changed this workflow since the page read it. The page shows the current version at its next read.');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-discard]')`), null);
|
||||
assert.equal(st.docs.acme.projects.site.workflows.change.description, 'Changed again.');
|
||||
});
|
||||
|
||||
test('a failed read says a pending change is kept, and it comes back when the read works', { timeout: 60000 }, async t => {
|
||||
const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=1' });
|
||||
await wait(`document.querySelector('[data-wfg-remove]')`, 'step 1');
|
||||
await b.evaluate(press('[data-wfg-remove]'));
|
||||
await wait(`${boxes}.length === 1 && document.querySelector('[data-wfg-unsaved]')`, 'pending removal');
|
||||
st.failRead = true;
|
||||
await b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));true`);
|
||||
await wait(`!!document.querySelector('[data-wfg-error]') && !!document.querySelector('[data-wfg-held]')`, 'error with kept note');
|
||||
assert.equal(await b.evaluate(text('[data-wfg-held]')), 'Unsaved change to change is kept on this page. It comes back when the workflows can be read.');
|
||||
assert.equal(await b.evaluate(`window.MosaicWorkflows.hasDraft()`), true);
|
||||
st.failRead = false;
|
||||
await b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));true`);
|
||||
await wait(`${boxes}.length === 1 && !!document.querySelector('[data-wfg-unsaved]') && !document.querySelector('[data-wfg-held]')`, 'back');
|
||||
assert.equal(st.writes.length, 0);
|
||||
});
|
||||
@@ -14,7 +14,8 @@ const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString()
|
||||
// acme and beta answer; gamma's bus is stopped. Decision ids are long so a shortened id would show.
|
||||
const ACME_DECISION = 'dec-acme-7f3c9a21-5b8e-4d1f-9c2a-0e6b7d8f9a10';
|
||||
const BETA_DECISION = 'dec-beta-1a2b3c4d-5e6f-4a1b-8c9d-0e1f2a3b4c5d';
|
||||
function fixture({ pollMs, fail = {}, down = [] } = {}) {
|
||||
// messages: { org: rows } is what that organization's bus messages read answers.
|
||||
function fixture({ pollMs, fail = {}, down = [], messages = {} } = {}) {
|
||||
const LIST = [
|
||||
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true },
|
||||
{ id: 'beta', label: 'Beta Works', theme: 'grove', busHealthy: true },
|
||||
@@ -61,7 +62,9 @@ function fixture({ pollMs, fail = {}, down = [] } = {}) {
|
||||
return {
|
||||
busHealthy: true,
|
||||
reads: { business: async () => ({ business: { id, human: 'jason', projects: DATA[id].projects.map(p => p.repo) } }), settings: async () => ({}), queue: async () => ({ rows: [] }), busStatus: async () => ({}) },
|
||||
bus: { messages: async () => ({ messages: [], unread: 0 }), agents: async () => [], 'thread.claims': async () => [], inbox: async () => DATA[id].inbox.map(d => ({ ...d, business: id, raised_by_run: 'run', routed_to: 'human' })), tasks: async () => [], instances: async () => ({ business: id, instances: {} }) },
|
||||
bus: { messages: async () => ({ messages: messages[id] ?? [], unread: 0 }), agents: async () => [], 'thread.claims': async () => [], inbox: async () => DATA[id].inbox.map(d => ({ ...d, business: id, raised_by_run: 'run', routed_to: 'human' })), tasks: async () => [], instances: async () => ({ business: id, instances: {} }),
|
||||
// SP11: a decision's own page reads its trail.
|
||||
trail: async subject => DATA[id].inbox.filter(d => d.id === subject).map((d, i) => ({ table: 'decisions', seq: i + 1, ...d, business: id, raised_by_run: 'run', route_to: 'human', action: 'price.set', recommendation: null })) },
|
||||
chat: { projects: async () => DATA[id].projects, threads: async () => [] },
|
||||
};
|
||||
},
|
||||
@@ -69,8 +72,8 @@ function fixture({ pollMs, fail = {}, down = [] } = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
async function setup(t, { viewport = [1440, 900], hash = '/', workspaceTimeoutMs, fail, down } = {}) {
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: fixture({ fail, down }), log: () => {}, ...(workspaceTimeoutMs ? { workspaceTimeoutMs } : {}) });
|
||||
async function setup(t, { viewport = [1440, 900], hash = '/', workspaceTimeoutMs, fail, down, messages } = {}) {
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: fixture({ fail, down, messages }), log: () => {}, ...(workspaceTimeoutMs ? { workspaceTimeoutMs } : {}) });
|
||||
t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
await b.viewport(...viewport);
|
||||
@@ -87,12 +90,11 @@ test('Dashboard renders every section across organizations, and a stopped one sh
|
||||
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page] .t")?.textContent'), 'Dashboard');
|
||||
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]").getAttribute("href")'), '#/dashboard');
|
||||
assert.equal(await text('#bus-view h1'), 'Dashboard');
|
||||
// Tiles: needs you, sessions, open tasks, projects, and an honest line for spend.
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-tile]")].map(e => e.dataset.wsTile)'), ['needs', 'sessions', 'tasks', 'projects', 'spend']);
|
||||
// SP8 (#1873): one row of figure tiles, none for spend or any figure no read returns.
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-tile]")].map(e => e.dataset.wsTile)'), ['agents', 'orgs', 'needs', 'tasks', 'done', 'projects']);
|
||||
assert.match(await text('[data-ws-tile=needs]'), /Needs you\s*2\s*items/i);
|
||||
assert.match(await text('[data-ws-tile=projects]'), /Projects\s*4\s*3 active/i);
|
||||
assert.match(await text('[data-ws-tile=spend]'), /No spend figures yet/);
|
||||
assert.doesNotMatch(await text('[data-ws-tile=spend]'), /\$|\d/);
|
||||
assert.match(await text('[data-ws-tile=projects]'), /Projects\s*3 active[\s\S]*1 archived/i);
|
||||
assert.doesNotMatch(await text('[data-ws-tiles]'), /spend|\$/i);
|
||||
// SP1: one organization row each: two running, the stopped one with its state and reason.
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-orgrow]")].map(e => [e.dataset.wsOrgrow, e.dataset.state])'), [['acme', 'ok'], ['beta', 'ok'], ['gamma', 'down']]);
|
||||
assert.match(await text('[data-ws-orgrow=gamma]'), /Gamma Home/);
|
||||
@@ -188,7 +190,7 @@ test('Inbox lists both organizations, copies a command with --org and the full i
|
||||
assert.deepEqual(items.map(([k]) => k).sort(), [`acme:${ACME_DECISION}`, `beta:${BETA_DECISION}`]);
|
||||
// Each row names its organization, project and session.
|
||||
const acme = items.find(([k]) => k.startsWith('acme'))[1];
|
||||
assert.match(acme, /Acme Studio/); assert.match(acme, /Website/); assert.match(acme, /coder/); assert.match(acme, /gated/);
|
||||
assert.match(acme, /Acme Studio/); assert.match(acme, /Website/); assert.match(acme, /coder/); assert.match(acme, /Gated/);
|
||||
const beta = items.find(([k]) => k.startsWith('beta'))[1];
|
||||
assert.match(beta, /Beta Works/); assert.match(beta, /pm/);
|
||||
// SP3: a project chip only where the item has a project.
|
||||
@@ -225,6 +227,36 @@ test('Inbox lists both organizations, copies a command with --org and the full i
|
||||
await wait(`document.querySelectorAll("[data-ws-item]").length === 1 && document.querySelector("[data-ws-item]").dataset.wsItem === ${JSON.stringify(`beta:${BETA_DECISION}`)}`);
|
||||
});
|
||||
|
||||
// SP11 (#1873): an organization's own decision page names the class in the words the Inbox uses,
|
||||
// from the same map, not the raw class.
|
||||
test('SP11: the per-organization decision page names the class as the Inbox does', async t => {
|
||||
const { b, base, wait } = await setup(t, { hash: '#/inbox' });
|
||||
const item = `[data-ws-item="beta:${BETA_DECISION}"]`;
|
||||
await wait(`!!document.querySelector(${JSON.stringify(`${item} .ws-chip.within`)})`);
|
||||
const word = await b.evaluate(`document.querySelector(${JSON.stringify(`${item} .ws-chip.within`)}).textContent`);
|
||||
assert.equal(word, 'Within role');
|
||||
await b.navigate(`${base}/#/orgs/beta/inbox/${BETA_DECISION}`);
|
||||
await wait('!!document.querySelector("#bus-view .tag.tag-within-role")');
|
||||
const chip = await b.evaluate('document.querySelector("#bus-view .tag.tag-within-role").textContent');
|
||||
assert.match(chip, new RegExp(`^${word} · `), chip);
|
||||
assert.doesNotMatch(await b.evaluate('document.getElementById("bus-view").innerText'), /within-role/);
|
||||
});
|
||||
|
||||
test('SP11: the per-organization Messages page names a known class as the Inbox does and shows an unknown one as it is', async t => {
|
||||
const at = '2026-11-15T10:00:00.000Z';
|
||||
const messages = { beta: [
|
||||
{ id: 'msg-beta-1a2b3c4d-0001', from_role: 'pm', class: 'within-role', body: 'Price list is ready.', at, read: false },
|
||||
{ id: 'msg-beta-1a2b3c4d-0002', from_role: 'pm', class: 'NOTE', body: 'Logo is in.', at, read: true },
|
||||
] };
|
||||
const { b, base, wait } = await setup(t, { hash: '#/inbox', messages });
|
||||
await b.navigate(`${base}/#/orgs/beta/messages`);
|
||||
await wait('document.querySelectorAll("#message-list li").length === 2');
|
||||
const lines = await b.evaluate('JSON.stringify([...document.querySelectorAll("#message-list li p.small")].map(p => p.textContent))');
|
||||
const [known, unknown] = JSON.parse(lines);
|
||||
assert.match(known, /^pm · Within role · /, known);
|
||||
assert.match(unknown, /^pm · NOTE · /, unknown);
|
||||
});
|
||||
|
||||
test('A poll repaints in place: focus, caret and scroll stay where they were', async t => {
|
||||
const { b, wait } = await setup(t, { hash: '/projects', viewport: [1000, 420] });
|
||||
await wait('document.querySelector("[data-ws-table]") && document.querySelectorAll("[data-ws-project]").length === 3');
|
||||
@@ -284,8 +316,9 @@ test('A read that an answering organization could not make says not read, never
|
||||
// beta answers, but its project and inbox reads refuse.
|
||||
const { b, wait, text } = await setup(t, { fail: { beta: ['projects', 'inbox'] } });
|
||||
await wait('document.querySelector("[data-ws-tiles]")');
|
||||
assert.match(await text('[data-ws-tile=projects] [data-ws-miss=projects]'), /Not read in Beta Works \(the chat channel is off\)/);
|
||||
assert.match(await text('[data-ws-tile=needs] [data-ws-miss=needs]'), /Not read in Beta Works/);
|
||||
// The tiles also name Gamma Home, whose bus is down.
|
||||
assert.match(await text('[data-ws-tile=projects] [data-ws-miss=projects]'), /Not read in Gamma Home \(bus down\) and Beta Works \(the chat channel is off\)/);
|
||||
assert.match(await text('[data-ws-tile=needs] [data-ws-miss=needs]'), /Not read in .*Beta Works/);
|
||||
assert.match(await text('[data-ws-miss=recent]'), /Not read in Beta Works/);
|
||||
assert.match(await text('[data-ws-miss=needs]:not([data-ws-tile] *)'), /Not read in Beta Works/);
|
||||
assert.doesNotMatch(await text('.ws-home .sub'), /and \d+ projects?/, 'no project total when a project read failed');
|
||||
@@ -329,10 +362,10 @@ test('Project rows and per-organization figures say not read when the reads behi
|
||||
// Dashboard: the per-organization figures leave Beta out instead of showing its 0.
|
||||
await b.evaluate('location.hash = "#/orgs/acme/"');
|
||||
await wait('document.querySelector("[data-ws-tiles]")');
|
||||
for (const tile of ['needs', 'sessions', 'tasks']) {
|
||||
for (const tile of ['needs', 'agents', 'tasks', 'done']) {
|
||||
const by = await b.evaluate(`document.querySelector('[data-ws-tile=${tile}] .ws-by')?.textContent ?? ''`);
|
||||
assert.doesNotMatch(by, /Beta Works/, tile);
|
||||
assert.match(await text(`[data-ws-tile=${tile}] [data-ws-miss=${tile}]`), /Not read in Beta Works/, tile);
|
||||
assert.match(await text(`[data-ws-tile=${tile}] [data-ws-miss=${tile}]`), /Beta Works \(the chat channel is off\)/, tile);
|
||||
}
|
||||
assert.doesNotMatch(await b.evaluate(`[...document.querySelectorAll('[data-ws-states] .ws-srow')].find(r => /Done this week/.test(r.textContent))?.querySelector('.ws-by')?.textContent ?? ''`), /Beta Works/);
|
||||
});
|
||||
@@ -340,8 +373,10 @@ test('Project rows and per-organization figures say not read when the reads behi
|
||||
test('With every organization down the dashboard and inbox show no totals and no empty-list claims', async t => {
|
||||
const { b, wait, text } = await setup(t, { down: ['acme', 'beta'] });
|
||||
await wait('document.querySelector("[data-ws-tiles]")');
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("[data-ws-home] .ws-big").length'), 0);
|
||||
assert.match(await text('[data-ws-tiles]'), /No organization answered/);
|
||||
// Only the Organizations tile has a figure, and it is complete: none of the three runs.
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-home] .ws-big")].map(e => e.closest("[data-ws-tile]").dataset.wsTile)'), ['orgs']);
|
||||
assert.match(await text('[data-ws-tile=orgs] .ws-big'), /^0 of 3 running$/);
|
||||
for (const tile of ['agents', 'needs', 'tasks', 'done', 'projects']) assert.match(await text(`[data-ws-tile=${tile}]`), /Not read[\s\S]*Acme Studio \(bus down\), Beta Works \(bus down\) and Gamma Home \(bus /, tile);
|
||||
assert.equal(await text('[data-ws-needs]'), 'Decisions not read');
|
||||
assert.equal(await text('[data-ws-states]'), 'Tasks not read');
|
||||
assert.equal(await text('[data-ws-recent]'), 'Projects not read');
|
||||
|
||||
Reference in new issue
Block a user