The second review found two paths the first fix round left open.
- The project-file save captures orgEpoch before its POST. When a switch
happened meanwhile, it neither paints nor announces the old file's
outcome on the new organization's page. An opaqueredirect still signs out.
- A live read (reader, get.api), the palette's inbox and tasks reads and
the board poll keep their answer in `last` only while the organization
they were sent for is still open. A later cached render on the new
organization no longer draws the old one's rows.
single-pane test 11 holds acme's file save across a switch to beta and
asserts nothing is announced: red on the previous bus.js ("Saved as commit
cccccccccccc."), green now. The kept-read guard has no browser test.
2130 lines
226 KiB
JavaScript
2130 lines
226 KiB
JavaScript
// Slice 1 S5 (#1522): inbox, tasks, agents and trail, read through /api/bus (src/bus.mjs),
|
||
// which reaches only the four reads of the Q1 module (lead decision 56). Nothing on these
|
||
// pages writes but row 76's message to a role, shown only under `serve --send` behind the
|
||
// proxy (lead decision 95): decisions are answered with `mosaic decide` in a terminal, and
|
||
// Copy only puts that command on the clipboard (Q4). What no Q1 read returns is labelled where it
|
||
// would show (lead decision 63). The control board (app.js) is untouched and stays at #/.
|
||
(() => {
|
||
'use strict';
|
||
const $ = id => document.getElementById(id);
|
||
const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||
// The CHAT-02 rules: C0 controls show as control pictures, C1 and bidi controls as
|
||
// [U+XXXX]. Newlines and tabs stay. Markdown stays as its source.
|
||
const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f]/g, UNSEEN = /[\u0080-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
|
||
const inert = v => String(v ?? '').replace(CONTROL, c => c === '\u007f' ? '␡' : String.fromCharCode(0x2400 + c.charCodeAt(0))).replace(UNSEEN, c => `[U+${c.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0')}]`);
|
||
const txt = v => esc(inert(v)); // every agent-, tracker- or bus-authored string goes through this
|
||
const announce = text => { $('announce').textContent = text; };
|
||
const enc = encodeURIComponent;
|
||
const SAFE = /^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,159}$/; // the broker's identifier rule
|
||
const TASK = /^vikunja:(\d+)\/(\d+)$/;
|
||
const CLOSE = ['resolved', 'withdrawn', 'expired'];
|
||
|
||
// ---------------------------------------------------------------- reads
|
||
// One GET per Q1 read. The last good answer for each read is kept, so a failed read
|
||
// can show what was read before, labelled as such.
|
||
let spriteRetry = false, spriteVersion = 0;
|
||
window.MosaicIcons = {
|
||
failed() { spriteRetry = true; },
|
||
succeeded() {
|
||
if (!spriteRetry) return;
|
||
spriteRetry = false; spriteVersion++;
|
||
for (const use of document.querySelectorAll('use[href^="/icons.svg"]')) {
|
||
const fragment = use.getAttribute('href').split('#')[1];
|
||
if (fragment) use.setAttribute('href', `/icons.svg?retry=${spriteVersion}#${fragment}`);
|
||
}
|
||
},
|
||
};
|
||
const last = new Map();
|
||
class ReadError extends Error { constructor(code, message, status) { super(message); this.code = code; this.status = status; } }
|
||
// Row 95 (#1589): every Console fetch takes `redirect: 'manual'`. A redirect comes only from the
|
||
// sign-in proxy, so the session ended: app.js's listener sets body.signed-out and draws the line,
|
||
// and from then on no read is made. A signed-out read throws code `signed-out`, which no view shows.
|
||
const out = () => document.body.classList.contains('signed-out');
|
||
const signOut = () => { if (!out()) document.dispatchEvent(new Event('mosaic-signed-out')); };
|
||
const signedOut = () => new ReadError('signed-out', 'The sign-in proxy redirected the read.', 0);
|
||
// Q175 phase 1 (#1690, sage-1340 F1): under --sso a read without a session gets 401 `sign-in
|
||
// required` from the Console itself. That signs out the same way; any other 401 stays an error.
|
||
const signInRequired = (res, body) => res.status === 401 && body?.error === 'sign-in required';
|
||
const signOutSso = () => { if (!out()) document.dispatchEvent(new CustomEvent('mosaic-signed-out', { detail: { signIn: true } })); };
|
||
// `replies` takes a message id as `id`; trail takes `subject`.
|
||
async function fetchRead(verb, subject) {
|
||
if (out()) throw signedOut();
|
||
let res, body;
|
||
try { res = await fetch(`/api/bus/${verb}${subject === undefined ? '' : `?${verb === 'replies' ? 'id' : verb === 'messages' ? 'after' : 'subject'}=${enc(subject)}`}`, { cache: 'no-store', redirect: 'manual' }); }
|
||
catch { window.MosaicIcons.failed(); throw new ReadError('unreachable', 'The Console server did not answer.', 0); }
|
||
if (res.type === 'opaqueredirect') { signOut(); throw signedOut(); }
|
||
try { body = await res.json(); } catch { window.MosaicIcons.failed(); throw new ReadError('unreachable', 'The Console server did not answer.', 0); }
|
||
if (signInRequired(res, body)) { signOutSso(); throw signedOut(); }
|
||
if (!res.ok) window.MosaicIcons.failed();
|
||
if (!res.ok || !body || !Array.isArray(body.rows)) throw new ReadError(typeof body?.error === 'string' ? body.error : 'invalid-response', typeof body?.message === 'string' ? body.message : `HTTP ${res.status}`, res.status);
|
||
window.MosaicIcons.succeeded();
|
||
return { ...body, rows: body.rows, at: body.at };
|
||
}
|
||
// Row 54 (#1543): the queue, business and settings reads (src/reads.mjs), GET only. Their
|
||
// error carries the module's own message, which the server has already redacted.
|
||
async function fetchApi(path) {
|
||
if (out()) throw signedOut();
|
||
const unreachable = () => Object.assign(new ReadError('unreachable', 'The Console server did not answer.', 0), { module: true });
|
||
let res, body;
|
||
try { res = await fetch(`/api/${path}`, { cache: 'no-store', redirect: 'manual' }); } catch { window.MosaicIcons.failed(); throw unreachable(); }
|
||
if (res.type === 'opaqueredirect') { signOut(); throw signedOut(); }
|
||
try { body = await res.json(); } catch { throw unreachable(); }
|
||
if (signInRequired(res, body)) { signOutSso(); throw signedOut(); }
|
||
if (!res.ok) window.MosaicIcons.failed();
|
||
if (!res.ok || !body || typeof body !== 'object' || Array.isArray(body)) throw Object.assign(new ReadError(typeof body?.error === 'string' ? body.error : 'invalid-response', typeof body?.message === 'string' ? body.message : `HTTP ${res.status}`, res.status), { module: true });
|
||
window.MosaicIcons.succeeded();
|
||
return body;
|
||
}
|
||
// #1873 SP1: bumped by each in-place organization switch. A write, or a read that keeps its answer,
|
||
// captures it before its await and drops the answer when it changed, so nothing the old organization
|
||
// answered lands on the new page or in its kept answers.
|
||
let orgEpoch = 0;
|
||
// A reader for one render. `live` asks the server; otherwise only kept answers are used.
|
||
function reader(live) {
|
||
const used = [];
|
||
const get = async (verb, subject) => {
|
||
const k = subject === undefined ? verb : `${verb}:${subject}`;
|
||
let r;
|
||
if (live) { const epoch = orgEpoch; r = await fetchRead(verb, subject); if (epoch === orgEpoch) last.set(k, r); }
|
||
else if (!(r = last.get(k))) throw new ReadError('not-read', 'not read before');
|
||
used.push(r.at);
|
||
if (verb === 'messages') { messageCount = r.unread; return r; }
|
||
return r.rows;
|
||
};
|
||
get.api = async path => {
|
||
const k = `api:${path}`;
|
||
let r;
|
||
if (live) { const epoch = orgEpoch; r = await fetchApi(path); if (epoch === orgEpoch) last.set(k, r); }
|
||
else if (!(r = last.get(k))) throw new ReadError('not-read', 'not read before');
|
||
used.push(r.at);
|
||
return r;
|
||
};
|
||
get.note = at => { if (at) used.push(at); }; // a view drawn from its own state names when that state was read
|
||
get.oldest = () => used.filter(Boolean).sort()[0] || null;
|
||
return get;
|
||
}
|
||
const of = (rows, table) => rows.filter(r => r.table === table);
|
||
|
||
// One decision from its trail. An open human decision's inbox row carries the
|
||
// authorization context; otherwise it comes from the trail's decision.raise event,
|
||
// the rule the broker's own decision view uses.
|
||
async function decision(get, id, row = null) {
|
||
const tr = await get('trail', id), d = of(tr, 'decisions').find(x => x.id === id);
|
||
if (!d) return null;
|
||
const ev = of(tr, 'decision_events').filter(x => x.decision === id), closed = ev.filter(x => CLOSE.includes(x.op)).at(-1) || null;
|
||
const raise = of(tr, 'events').find(e => e.kind === 'action.allowed' && e.body?.operation === 'decision.raise' && e.body?.decision === id);
|
||
const mids = new Set(of(tr, 'messages').filter(m => m.decision === id).map(m => m.id));
|
||
const dm = of(tr, 'deliveries').find(x => mids.has(x.message) && x.transport === 'discord-dm' && x.op === 'delivered');
|
||
return {
|
||
id, business:d.business, autonomy:row?.autonomy??null, at: d.at, class: d.class, action: d.action, routeTo: d.route_to, question: d.question,
|
||
options: Array.isArray(d.options) ? d.options : [], recommendation: d.recommendation, taskRef: d.task_ref, requirementRef: d.requirement_ref,
|
||
blocking: !!d.blocking, raisedBy: { role: d.raised_by_role, run: d.raised_by_run },
|
||
authorization: row ? row.authorization : raise ? { action: d.action, target: raise.body.target, approvalChoice: raise.body.approvalChoice } : null,
|
||
seen: ev.filter(x => x.op === 'seen'), closed, dm: dm ? { at: dm.at } : null, supersedes: d.supersedes, trail: tr,
|
||
};
|
||
}
|
||
// Earlier versions through `supersedes`, newest first, one trail read each, at most ten.
|
||
async function chain(get, d) {
|
||
const out = [];
|
||
for (let x = d, n = 0; x?.supersedes && n < 10; n++) { x = await decision(get, x.supersedes); if (x) out.push(x); }
|
||
return out;
|
||
}
|
||
// A task from its task_current row; the trail adds what only events carry.
|
||
function task(row, tr = null) {
|
||
const ref = row.task_ref, f = row.fields || {}, [, project, id] = ref.match(TASK) || [, null, null];
|
||
const evs = tr ? of(tr, 'events').filter(e => e.subject === ref) : [], snaps = tr ? of(tr, 'task_snapshots') : [];
|
||
const shape = f.gone ? snaps.filter(s => !s.fields?.gone).at(-1)?.fields || {} : f;
|
||
const created = evs.find(e => e.kind === 'task.created');
|
||
const ext = evs.filter(e => e.kind === 'task.changed.external').at(-1);
|
||
// task_current already skips stale reads, so a current row from a poll is a change the
|
||
// stack didn't make: to a task the stack wrote ('changed') or to one it never wrote ('foreign').
|
||
const external = !f.gone && row.source === 'poll' ? { kind: tr ? (snaps.some(s => s.source === 'self') ? 'changed' : 'foreign') : null, via: row.via, readAt: row.read_at, changed: Array.isArray(ext?.body?.changed) ? ext.body.changed : [], comments: ext?.body?.comments || 0 } : null;
|
||
const missingEv = evs.filter(e => e.kind === 'task.missing').at(-1);
|
||
return {
|
||
ref, project: project && +project, id: id && +id, title: shape.title ?? null, description: shape.description ?? '',
|
||
bucket: f.gone ? null : f.bucket, done: !!f.done, assignees: Array.isArray(shape.assignees) ? shape.assignees : [],
|
||
// The bus 'tasks' row carries both (row 58). A tombstone's row has no priority, so the detail
|
||
// view falls back to the last snapshot that read the task.
|
||
requirement: row.requirement ?? created?.body?.requirement ?? null, request: created?.body?.request ?? null,
|
||
due: shape.due_date ?? null, priority: row.priority ?? shape.priority ?? null, percent: shape.percent_done ?? 0,
|
||
changedAt: row.at, seq: row.seq, external,
|
||
conflicts: evs.filter(e => e.kind === 'task.conflict').map(e => ({ at: e.at, ...e.body })),
|
||
missing: f.gone ? { reason: f.gone, at: row.at, project: missingEv?.body?.project ?? null } : null,
|
||
decisions: tr ? of(tr, 'decisions').filter(d => d.task_ref === ref) : [],
|
||
// Rows after the current one are reads task_current skipped (lead decision 59).
|
||
snapshots: snaps.map(s => ({ at: s.at, source: s.source, via: s.via, readAt: s.read_at, role: s.role, stale: s.seq > row.seq, fields: s.fields || {} })),
|
||
};
|
||
}
|
||
|
||
// ---------------------------------------------------------------- trail lines
|
||
const group = k => k === 'human.input' ? 'request' : k.startsWith('session.') || k.startsWith('launch.') || k.startsWith('claim.') ? 'launch' : k.startsWith('task.') || k.startsWith('snapshot.') ? 'task' : k.startsWith('review.') ? 'review' : k.startsWith('action.') || k.startsWith('decision.') ? 'decision' : 'other';
|
||
const bucketText = f => f?.gone ? `gone (${f.gone})` : `bucket ${f?.bucket}`;
|
||
const short = id => String(id ?? '').slice(0, 8);
|
||
const plural = (n, one) => `${n} ${one}${n === 1 ? '' : 's'}`;
|
||
function line(r, ctx) {
|
||
const out = { at: r.at, actor: null, by: 'broker', decision: null, note: null };
|
||
if (r.table === 'events') {
|
||
const b = r.body && typeof r.body === 'object' ? r.body : {};
|
||
out.kind = r.kind; out.decision = typeof b.decision === 'string' ? b.decision : null;
|
||
if (r.actor_role) out.actor = { role: r.actor_role, run: r.actor_run }; else if (r.kind === 'human.input' || r.kind.startsWith('launch.')) out.by = 'human';
|
||
const map = {
|
||
'session.launched': () => `Session started: ${r.actor_role} as ${r.actor_run} (${b.harness}${b.address ? `, ${b.address}` : ''})`,
|
||
'session.ended': () => `Session ended: ${r.actor_role} ${r.actor_run}${b.reason ? ` (${b.reason}${b.exit !== undefined ? `, exit ${b.exit}` : ''})` : ''}`,
|
||
'human.input': () => b.kind === 'answer' ? (b.op === 'resolved' ? `The human chose “${b.choice}” from the CLI` : `The human ${b.op === 'seen' ? 'marked it seen' : b.op} from the CLI`)
|
||
: b.kind === 'instruction' ? 'Request from the human, recorded from the CLI' : b.kind === 'admin' ? 'Admin command from the human, CLI' : 'Input from the human',
|
||
'task.created': () => `Created for ${b.requirement}`,
|
||
'task.assigned': () => `Assigned to ${b.role}`,
|
||
'task.state': () => `Moved ${b.previous ? `from ${b.previous} ` : ''}to ${b.state}${b.percent_done !== undefined ? `, ${b.percent_done}% done` : ''}${b.comment ? ', with a comment in Vikunja' : ''}`,
|
||
'task.closed': () => `Closed with verdict ${b.verdict}`,
|
||
'task.changed.external': () => {
|
||
const changed = Array.isArray(b.changed) ? b.changed : [], comments = b.comments ? plural(b.comments, 'new comment') : '';
|
||
if (b.previous === null) return 'Read from Vikunja for the first time: the stack did not create it';
|
||
return changed.length ? `Changed in Vikunja: ${changed.join(', ')}${comments ? `, and ${comments}` : ''}` : comments ? `${comments[0].toUpperCase()}${comments.slice(1)} in Vikunja` : 'Read from Vikunja';
|
||
},
|
||
'task.conflict': () => `Write refused (${b.verb}): Vikunja changed after the stack read it (expected ${short(b.expected)}, found ${short(b.actual)})`,
|
||
'task.missing': () => `No longer readable in Vikunja (${b.reason}${b.project ? `, now in project ${b.project}` : ''})`,
|
||
'review.requested': () => 'Review requested',
|
||
'review.verdict': () => `Review verdict: ${b.verdict ?? 'not recorded'}`,
|
||
'action.refused': () => `Refused: ${b.code}`,
|
||
'action.allowed': () => b.operation === 'decision.raise' ? `Raised with this context: choosing “${b.approvalChoice}” approves ${b.action}${b.target ? ` on ${b.target}` : ''}` : `Allowed ${b.action}${b.target ? ` on ${b.target}` : ''}`,
|
||
'launch.revoked': () => 'Launching revoked from the CLI',
|
||
'launch.restored': () => 'Launching restored from the CLI',
|
||
'credential.expiring': () => `${b.service} credential for ${b.instance} expires ${b.expires ?? 'soon'}`,
|
||
'credential.expired': () => `${b.service} credential for ${b.instance} expired`,
|
||
'credential.changed': () => `${b.service} credential for ${b.instance} changed`,
|
||
};
|
||
out.text = (map[r.kind] || (() => r.kind))();
|
||
if (r.kind === 'human.input' && ctx.asked.has(r.id)) out.note = 'the request task.created names (lead decision 56, Q3)';
|
||
if (r.kind === 'human.input' && b.kind === 'answer') out.groupAs = 'decision'; // an answer, not a request
|
||
} else if (r.table === 'messages') {
|
||
out.kind = `message.${String(r.class).toLowerCase()}`; out.decision = r.decision;
|
||
if (r.from_role === 'human') out.by = 'human'; else out.actor = { role: r.from_role, run: r.from_run };
|
||
out.text = `${r.from_role === 'human' ? 'The human' : r.from_role} to ${r.to_role}: ${r.body}`;
|
||
out.groupAs = r.from_role === 'human' ? 'request' : r.decision ? 'decision' : 'other';
|
||
} else if (r.table === 'deliveries') {
|
||
const m = ctx.messages[r.message];
|
||
out.kind = `delivery.${r.op}`; out.decision = m?.decision || null;
|
||
out.text = `Message ${r.op}${r.holder_run ? ` to ${r.holder_run}` : ''}${r.transport ? ` by ${r.transport}` : ''}${r.transport === 'discord-dm' ? ' (DM to the human)' : ''}`;
|
||
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]}`;
|
||
} 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.
|
||
out.kind = `decision.${r.op}`; out.decision = r.decision; out.by = r.via === 'cli' ? 'human' : r.via === 'console' ? 'human-console' : 'broker';
|
||
out.text = r.op === 'resolved' ? `${r.by} chose “${r.choice}” via ${r.via}` : r.op === 'seen' ? `${r.by} saw it${r.via ? ` via ${r.via}` : ''}` : `${r.op[0].toUpperCase()}${r.op.slice(1)} by ${r.by}${r.note ? `: ${r.note}` : ''}`;
|
||
} else if (r.table === 'task_snapshots') {
|
||
out.kind = `snapshot.${r.source}`;
|
||
if (r.source === 'self') out.actor = { role: r.role, run: r.run };
|
||
out.text = r.source === 'self' ? `Written: ${bucketText(r.fields)}` : `Read from Vikunja (${r.via} read sent ${String(r.read_at).slice(11, 19)}): ${bucketText(r.fields)}`;
|
||
if (ctx.current != null && r.seq > ctx.current) out.note = 'stale read, not current (task_current skips it)';
|
||
} else if (r.table === 'role_claims') {
|
||
out.kind = `claim.${r.op}`; out.actor = { role: r.role, run: r.holder_run };
|
||
out.text = r.op === 'claim' ? `${r.role} claimed by ${r.holder_run} (${r.harness}${r.address ? `, ${r.address}` : ''})` : `${r.role} ${r.op === 'release' ? 'released' : 'revoked'} by ${r.by}${r.reason ? `: ${r.reason}` : ''}`;
|
||
} else { out.kind = String(r.table); out.text = 'A row this page does not know how to show'; }
|
||
out.group = out.groupAs || group(out.kind);
|
||
return out;
|
||
}
|
||
function lines(tr, current = null) {
|
||
const ctx = { current, asked: new Set(of(tr, 'events').filter(e => e.kind === 'task.created').map(e => e.body?.request)), messages: Object.fromEntries(of(tr, 'messages').map(m => [m.id, m])) };
|
||
return tr.map(r => line(r, ctx));
|
||
}
|
||
|
||
// ---------------------------------------------------------------- render helpers
|
||
function ago(iso) {
|
||
const t = Date.parse(iso);
|
||
if (!Number.isFinite(t)) return String(iso ?? 'unknown');
|
||
const s = Math.max(0, Math.round((Date.now() - t) / 1000)), m = Math.floor(s / 60), h = Math.floor(m / 60);
|
||
return s < 60 ? `${s} s ago` : m < 60 ? `${m} min ago` : h < 24 ? `${h} h ${m % 60} min ago` : `${Math.floor(h / 24)} d ago`;
|
||
}
|
||
const when = iso => iso ? `<time datetime="${esc(iso)}" title="${esc(iso)}">${esc(ago(iso))}</time>` : 'never';
|
||
const clock = iso => iso ? `<time datetime="${esc(iso)}" title="${esc(iso)}">${esc(String(iso).slice(11, 16))}</time>` : '';
|
||
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>`;
|
||
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>`;
|
||
// "New organization" everywhere it is offered: the Organizations form with the ID field focused (org-create.js reads ?new=1).
|
||
const NEW_ORG = '#/settings/organizations?new=1';
|
||
const taskLink = ref => ref ? `<a href="#/tasks/${enc(ref)}">#${esc(String(ref).split('/')[1])}</a>` : '';
|
||
// Rows without an actor role come from the human (CLI outside any run, or the signed-in Console)
|
||
// or from the broker itself.
|
||
const actor = (a, by) => `<span class="source">${a ? `${txt(a.role)} · ${txt(a.run)}` : by === 'human' ? 'human, CLI outside any run' : by === 'human-console' ? 'human, signed-in Console' : 'broker'}</span>`;
|
||
const PRIORITY = ['unset', 'low', 'medium', 'high', 'urgent', 'do now'];
|
||
const head = (title, sub) => `<div class="page-head"><div><h1 tabindex="-1">${title}</h1>${sub ? `<p class="small muted" id="bus-status">${sub}</p>` : ''}</div></div>`;
|
||
let readAt = null;
|
||
const readNote = get => `Read from the bus ${when(get.oldest())}.`;
|
||
// Lead decision 63: what no Q1 read returns carries this label where it would show.
|
||
const gap = what => `<span class="feat">${esc(what)}: not in the Q1 module</span>`;
|
||
// Which choice authorizes which action on which target, as the broker recorded it at
|
||
// decision.raise. Never inferred from the recommendation or an option's position.
|
||
const approves = a => a ? `Choosing “${txt(a.approvalChoice)}” approves ${txt(a.action)}${a.target ? ` on ${txt(a.target)}` : ''}.` : 'No approval context was recorded for this decision, so no option is marked as approving.';
|
||
const first = q => String(q ?? '').split('\n')[0];
|
||
const due = d => d ? `<time datetime="${esc(d)}" title="${esc(d)}">${esc(String(d).slice(0, 10))}</time>` : '<span class="muted">none</span>';
|
||
const user = u => `user ${esc(u)}`;
|
||
|
||
// ---------------------------------------------------------------- views
|
||
let inboxCount = null, messageCount = null;
|
||
// Organization mode (sample 01): Dashboard, Inbox, Tasks, Projects, Side by side, Agents and
|
||
// Assistant, with Settings pinned to the foot of the sidebar. Queue opens from the organization
|
||
// dashboard and Docs from its Docs row, so neither is a sidebar item here.
|
||
function orgSections(route) {
|
||
const nav = $('console-nav');
|
||
let foot = $('sections-foot');
|
||
if (!foot) { foot = document.createElement('div'); foot.id = 'sections-foot'; foot.className = 'ws-foot'; nav.append(foot); }
|
||
const active = document.activeElement;
|
||
const focused = $('sections').contains(active) || foot.contains(active) ? active.getAttribute('href') : null;
|
||
const icon = id => window.MosaicWorkspace?.icon?.(id) ?? `<svg class="i" aria-hidden="true"><use href="/icons.svg#i-${id}"/></svg>`;
|
||
const n = (count, what) => count > 0 ? `<span class="ws-n hot" aria-label="${count} ${what}">${count}</span>` : '';
|
||
const items = [['/dashboard', 'Dashboard', '', 'board'], ['/inbox', 'Inbox', n(inboxCount?.open, 'open for you'), 'inbox'], ['/tasks', 'Tasks', '', 'tasks'], ['/projects', 'Projects', '', 'folder'], ['/side-by-side', 'Side by side', '', 'columns'], ['/agents', 'Agents', '', 'agents'], ['/messages', 'Assistant', n(messageCount, 'unread messages'), 'talk']];
|
||
const link = ([h, l, extra, id]) => {
|
||
// #1873 SP1: the Dashboard item is the system dashboard, `#/dashboard`, outside any organization.
|
||
const cur = h === '/dashboard' ? (route === '/dashboard' || route === '/' || route === '/board') : route.startsWith(h) || (h === '/projects' && route.startsWith('/chat')) || (h === '/tasks' && route.startsWith('/trail/task')) || (h === '/inbox' && (route.startsWith('/trail/decision') || route.startsWith('/trail/message')));
|
||
return `<a href="#${h}" class="s1-section ws-nav"${cur ? ' aria-current="page"' : ''}>${icon(id)}<span class="t">${l}</span>${extra}</a>`;
|
||
};
|
||
// No project tree under Projects here: the sidebar's Projects group lists every organization's
|
||
// projects and opens the same project page, which lists its conversations.
|
||
$('sections').innerHTML = items.map(item => `<li>${link(item)}</li>`).join('');
|
||
foot.innerHTML = link(['/settings', 'Settings', '', 'settings']);
|
||
if (focused) [...$('sections').querySelectorAll('a[href]'), ...foot.querySelectorAll('a[href]')].find(a => a.getAttribute('href') === focused)?.focus({ preventScroll: true });
|
||
}
|
||
function sections(route) {
|
||
if (window.MosaicOrg) return orgSections(route);
|
||
const focused = $('sections').contains(document.activeElement) ? document.activeElement.getAttribute('href') : null;
|
||
const items = [['/', 'Dashboard', '', 'board'], ['/projects', 'Projects', '', 'inbox'], ['/inbox', 'Inbox', inboxCount?.open > 0 ? `<span class="count" aria-label="${inboxCount.open} open for you">${inboxCount.open}</span>${inboxCount.blocking ? ` ${blockChip(`${inboxCount.blocking} blocking`)}` : ''}` : '', 'inbox'], ['/messages', 'Assistant', messageCount > 0 ? `<span class="count" aria-label="${messageCount} unread messages">${messageCount}</span>` : '', 'talk'], ['/tasks', 'Tasks', '', 'tasks'], ['/agents', 'Agents', '', 'agents'], ['/queue', 'Queue', '', 'queue'], ['/docs', 'Docs', '', 'library'], ['/settings', 'Settings', '', 'settings']];
|
||
$('sections').innerHTML = items.map(([h, l, extra, icon]) => {
|
||
const cur = h === '/' ? (route === '/' || route === '/board') : route.startsWith(h) || (h === '/projects' && route.startsWith('/chat')) || (h === '/tasks' && route.startsWith('/trail/task')) || (h === '/inbox' && (route.startsWith('/trail/decision') || route.startsWith('/trail/message')));
|
||
return `<li><a href="#${h}" class="s1-section"${cur ? ' aria-current="page"' : ''}><svg class="i" aria-hidden="true">${h === '/projects' ? '<path d="M2 5h6l2 2h8v11H2z"/>' : `<use href="/icons.svg${spriteVersion ? `?retry=${spriteVersion}` : ''}#i-${icon}"/>`}</svg>${l}${extra ? ` ${extra}` : ''}</a>${h === '/projects' ? '<div id="project-tree" aria-label="Project conversations"></div>' : ''}</li>`;
|
||
}).join('');
|
||
window.MosaicProjectTree?.mount?.({ container: $('project-tree'), path: route });
|
||
if (focused) [...$('sections').querySelectorAll('a[href]')].find(a => a.getAttribute('href') === focused)?.focus({ preventScroll: true });
|
||
}
|
||
function countInbox(rows) { inboxCount = { open: rows.length, blocking: rows.filter(d => d.blocking).length }; }
|
||
|
||
// Inbox
|
||
function decisionCard(d) {
|
||
return `<li class="wait-item s1-dec${d.blocking ? ' is-attn' : ''}"><div class="wait-head"><a href="#/inbox/${enc(d.id)}" class="s1-dec-open">${txt(first(d.question))}</a></div>
|
||
<p class="s1-badges">${d.blocking ? blockChip('blocking') : ''}${chip(d.class, d.action)}${d.autonomy?badge(d.autonomy.pending?'Awaiting your confirmation':'Near the loop','attn'):''}${canDecide && d.console ? ` ${badge(['decision','hire'].includes(d.console.kind) ? 'Answer here' : 'Approve or Deny here', 'ok')}` : ''}</p>
|
||
<p class="small s1-auth">${approves(d.authorization)}</p>
|
||
${window.MosaicInbox?.cardMeta?.(d) ?? `<p class="small muted">Raised by ${txt(d.raised_by_role)} ${when(d.at)}</p>`}<p class="small muted">${d.task_ref ? ` · task ${taskLink(d.task_ref)}` : ''}${d.requirement_ref ? ` · ${txt(d.requirement_ref)}` : ''}</p></li>`;
|
||
}
|
||
// Row 76 (#1570, lead decision 95): a human message to a held role, only when the server says
|
||
// a send can pass here (`send` in /api/config). The draft lives in `draft`, not the DOM, so the
|
||
// 10 s refresh redraws the form without losing it. Nothing resends: an unknown outcome stays
|
||
// unknown and the draft stays put.
|
||
// Row 81 (#1575): a sent receipt lists the replies to that message, read with `replies` on each
|
||
// render. That read marks nothing. Row 150 (#1644): since row 142, `mosaic talk` prints only the
|
||
// reply to its own message, so a reply to a Console send stays unread in `mosaic inbox` until
|
||
// the human marks it read with `mosaic inbox --read`.
|
||
let isTester = false, orgSetup = false;
|
||
// Both Docs and project direction use the same owner-only records setup action.
|
||
window.MosaicRecords = {
|
||
markup(project) {
|
||
const org = window.MosaicOrg?.id;
|
||
if (!org) return 'This project has no records yet. Initialize its record repository to add documents.';
|
||
const command = `mosaic project init ${org} ${project}`;
|
||
return `This project has no records yet. ${orgSetup ? `<button type="button" class="btn" data-record-init="${esc(project)}">Initialize project records</button> ` : 'Run '}<code>${txt(command)}</code><span role="status" data-record-receipt></span>`;
|
||
},
|
||
};
|
||
document.addEventListener('click', async e => {
|
||
const button = e.target.closest?.('[data-record-init]');
|
||
if (!button || button.disabled || !orgSetup || !window.MosaicOrg) return;
|
||
button.disabled = true;
|
||
const status = button.parentElement.querySelector('[data-record-receipt]');
|
||
const url = `/api/orgs/${encodeURIComponent(window.MosaicOrg.id)}/setup/records/${encodeURIComponent(button.dataset.recordInit)}`;
|
||
try {
|
||
const response = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
|
||
const body = await response.json();
|
||
if (!response.ok || body.outcome !== 'done' || body.step !== 'records') throw Error(body.message || 'Initialization was refused. Inspect the project before retrying.');
|
||
const readback = await fetch(url, { cache: 'no-store' });
|
||
const checked = await readback.json();
|
||
if (!readback.ok || checked.state !== 'done') throw Error('Read-back failed. Inspect the project before retrying.');
|
||
document.getElementById('refresh')?.click();
|
||
} catch (error) { if (status) status.textContent = ` ${error.message || 'Outcome unknown. Inspect the project before retrying.'}`; }
|
||
});
|
||
|
||
let configRead = Promise.resolve();
|
||
// #1873 SP1: the config read an organization switch started, until the next render has waited for it.
|
||
let switchRead = null;
|
||
let canSend = false, canMessage = false, chatSend = false, sendRoles = null, sending = false, receipt = null, replies = [];
|
||
const REPLIES = 50; // the broker's cap
|
||
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>` : ''}`;
|
||
}
|
||
const draft = { to: '', body: '' };
|
||
function composerHtml() {
|
||
const roles = sendRoles ? [...new Set([...sendRoles, ...(draft.to && !sendRoles.includes(draft.to) ? [draft.to] : [])])] : null;
|
||
const options = roles ? roles.map(r => `<option value="${esc(r)}"${r === draft.to ? ' selected' : ''}>${txt(r)}${sendRoles.includes(r) ? '' : ' (not held now)'}</option>`).join('') : '';
|
||
const r = receipt;
|
||
const said = !r ? '' : r.kind === 'sent'
|
||
? `<p class="receipt">Sent to ${txt(r.to)} ${when(r.at)}, message <code>${txt(short(r.id))}</code>. <a href="#/trail/message/${enc(r.id)}">Its trail</a>.</p>${out() ? '' : repliesHtml()}`
|
||
: r.kind === 'refused'
|
||
? `<p class="receipt failed">Not sent to ${txt(r.to)}: ${txt(r.message)}${r.message.includes(`(${r.code})`) ? '' : ` (<code>${txt(r.code)}</code>)`}. The draft is kept.</p>`
|
||
: `<p class="receipt failed">Outcome unknown: the message to ${txt(r.to)} may have been sent. Nothing was sent again, and the draft is kept. The bus gave no message id, so there is no trail to link: before sending again, look for it on the role's side or in the bus trail from a terminal.</p>`;
|
||
return `<section class="panel s1-send" id="send-section" aria-labelledby="b-send"><h2 id="b-send">Message a role</h2>
|
||
<p class="small muted">Goes to the role as a message from the human, the same way as one sent from the CLI, with class INFO. Replies to it show under the receipt. The Console never marks one read, so each stays unread in <code>mosaic inbox</code> in a terminal until you mark it read with <code>mosaic inbox --read</code>.</p>
|
||
${roles === null ? '<p class="small warn">The held roles could not be read, so there is nothing to pick. Read again to retry.</p>' : !roles.length ? '<p class="small muted">No role is held right now, so there is nothing to pick.</p>' : ''}
|
||
<form id="send-form" class="reply-form" novalidate><label for="send-to">To</label><select id="send-to" data-field="to"><option value="">Choose a held role</option>${options}</select>
|
||
<label for="send-body">Message</label><textarea id="send-body" data-field="body" rows="4" placeholder="What should the role do?">${esc(draft.body)}</textarea>
|
||
<button class="btn primary" type="submit" data-send aria-disabled="${sending}">${sending ? 'Sending…' : 'Send'}</button></form>${said}</section>`;
|
||
}
|
||
async function composer(get) {
|
||
if (!canMessage) return '<p class="small muted">Messaging a role needs a Console started with <code>--send</code> behind the sign-in proxy; this one only reads.</p>';
|
||
try { sendRoles = (await get('agents')).map(c => c.role).filter(r => typeof r === 'string' && SAFE.test(r)); } catch { sendRoles = null; }
|
||
if (receipt?.kind === 'sent') {
|
||
const r = receipt;
|
||
let rows = null;
|
||
try { rows = await get('replies', r.id); } catch {}
|
||
// A send that finished during this read has its own receipt; leave it alone.
|
||
if (receipt === r) replies = Array.isArray(rows) ? rows : null;
|
||
}
|
||
return composerHtml();
|
||
}
|
||
// Redraw only the form, keeping focus, after a send changes its state.
|
||
function paintSend() {
|
||
const el = $('send-section');
|
||
if (!el) return;
|
||
const k = keep();
|
||
el.outerHTML = composerHtml();
|
||
restore(k);
|
||
}
|
||
// #797 / #1839 extends row 252's answer panel to every eligible option, drawn only when
|
||
// the server says this Console answers decisions (`decide` in /api/config: signed in through SSO
|
||
// and started with --send) and the bus marked the inbox row eligible (its `console` field). The
|
||
// first click asks the Console for a one-use confirmation that names what the answer does. Only
|
||
// the second click answers. Nothing here retries: a refusal drops the confirmation, and an
|
||
// unknown outcome says to refresh first. The state lives in `answer`, not the DOM, so the 10 s
|
||
// refresh redraws it. The server and the bus check everything again; this is presentation only.
|
||
let canDecide = false, ssoOn = false, answer = null;
|
||
document.addEventListener('mosaic-signed-out', () => { answer = null; });
|
||
const ACTIONS = { approve: 'Approve', deny: 'Deny' };
|
||
const hireLines = c => c?.kind !== 'hire' ? '' : `<h3>Flagged grants — owner approval required</h3><ul>${c.flagged.map(l=>`<li>${txt(l.field)}: ${txt(l.value)}</li>`).join('')||'<li>None</li>'}</ul><h3>Requested credential scopes — owner approval required</h3><ul>${c.credentialLines.map(l=>`<li>${txt(l.service)}${l.scope?`: ${txt(l.scope)}`:''}</li>`).join('')||'<li>None</li>'}</ul><p>Expires ${txt(c.expiresAt)}</p>${bindingLine(c)}`;
|
||
// #1873 CB5: a copy credential binding decision names its copy and whether it binds or unbinds;
|
||
// the scope lines above are the bus's computed ones. The confirmation says `change`; the inbox
|
||
// row carries the bus's preview, where an unbind is `after: null`.
|
||
const bindingChange = b => b.change === 'unbind' ? 'unbind' : 'bind';
|
||
const bindingLine = c => c?.binding && typeof c.binding === 'object' ? `<h3>Credential binding</h3><p data-binding-change="${bindingChange(c.binding)}">${bindingChange(c.binding) === 'unbind' ? 'Unbind and revoke the credentials of' : 'Bind credentials for'} copy <code>${txt(c.binding.instance)}</code>.</p>` : '';
|
||
const hireAdjustment = c => {
|
||
if(c?.kind!=='hire' || !c.role)return '';
|
||
const list=(key,values)=>(values??[]).map((v,i)=>`<label><input type="checkbox" data-hire-list="${esc(key)}" data-index="${i}" checked> ${txt(v)}</label>`).join(' ');
|
||
return `<details id="hire-adjust"><summary>Adjust before approving</summary><p>Remove grants or credentials below. Additional grants need a new decision.</p>
|
||
<fieldset><legend>Tools</legend>${list('tools',c.role.tools)}</fieldset>
|
||
${['withinRole','crossRole'].map(k=>`<fieldset><legend>${k==='withinRole'?'Within this role':'Across roles'}</legend>${list(k,c.role.authority[k])}</fieldset>`).join('')}
|
||
<label>Network <select id="hire-network">${['none','api-only','open'].filter((_,i)=>i<=['none','api-only','open'].indexOf(c.role.network)).map(n=>`<option${n===c.role.network?' selected':''}>${n}</option>`).join('')}</select></label>
|
||
<fieldset><legend>Skills</legend>${list('skills',c.role.skills)}</fieldset>
|
||
<fieldset><legend>Credentials</legend>${c.credentialLines.map((line,i)=>`<label><input type="checkbox" data-hire-credential="${i}" checked> ${txt(line.service)}${line.scope?`: ${txt(line.scope)}`:''}</label>`).join(' ')||'None'}</fieldset>
|
||
<label>Harness <input id="hire-route-harness" value="${esc(c.route.harness)}" maxlength="200"></label>
|
||
<label>Model <input id="hire-route-model" value="${esc(c.route.model)}" maxlength="200"></label>
|
||
<label>Thinking <input id="hire-route-thinking" value="${esc(c.route.thinking??'')}" maxlength="200"></label></details>`;
|
||
};
|
||
function collectHireAdjustment(c) {
|
||
if(!$('hire-adjust') || !c.role)return undefined;
|
||
const selected=(key,values)=>(values??[]).filter((_,i)=>document.querySelector(`[data-hire-list="${key}"][data-index="${i}"]`)?.checked);
|
||
const kept=new Set([...document.querySelectorAll('[data-hire-credential]:checked')].map(e=>Number(e.dataset.hireCredential)));
|
||
const lines=c.credentialLines.filter((_,i)=>kept.has(i));
|
||
const credentials=c.role.credentials.flatMap(e=>{
|
||
const held=lines.filter(l=>l.service===e.service);if(!held.length)return [];
|
||
if(e.scopes===undefined)return [e];
|
||
const scopes=Array.isArray(e.scopes)?e.scopes.filter(scope=>held.some(l=>l.scope===scope)):
|
||
Object.fromEntries(Object.entries(e.scopes).map(([group,verbs])=>[group,verbs.filter(v=>held.some(l=>l.scope===`${group}.${v}`))]).filter(([,v])=>v.length));
|
||
return [{service:e.service,scopes}];
|
||
});
|
||
const thinking=$('hire-route-thinking').value.trim();
|
||
return {role:{tools:selected('tools',c.role.tools),network:$('hire-network').value,authority:Object.fromEntries(['withinRole','crossRole'].map(k=>[k,selected(k,c.role.authority[k])])),skills:selected('skills',c.role.skills)},credentials,
|
||
route:{harness:$('hire-route-harness').value.trim(),model:$('hire-route-model').value.trim(),...(thinking?{thinking}:{})}};
|
||
}
|
||
const HIRE_START_LABEL='Record and approve';
|
||
let hireDraft={op:'hire',level:'org'},hireTemplates=[],hireBusy=false,hireStatus='',hireCode='';
|
||
// D4 (#1873, P0-1): an org Console shows this form on the workspace inbox. Its posts go to the
|
||
// current organization's bus (display.js), so the organization is that one and is not editable.
|
||
const hireOrg=()=>window.MosaicOrg?.id ?? null;
|
||
function hireStartHtml() {
|
||
if(!canDecide)return '';
|
||
const org=hireOrg(),d=hireDraft,off=hireBusy?' disabled':'';
|
||
const input=(key,label,extra='')=>`<label>${label} <input data-hire-field="${key}" data-focus-key="hire:${key}" value="${esc(d[key]??'')}" maxlength="${key==='reason'?500:200}" ${extra}${off}></label>`;
|
||
const select=(key,label,options)=>`<label>${label} <select data-hire-field="${key}" data-focus-key="hire:${key}"${off}>${options}</select></label>`;
|
||
const business=org?`<label>Organization <input value="${esc(org)}" readonly aria-describedby="hire-start-org"></label><p class="small muted" id="hire-start-org">This hire goes to ${txt(org)}'s bus. Switch organization to hire elsewhere.</p>`:input('business','Organization','required');
|
||
const status=`${txt(hireStatus)}${hireCode?` (<code>${txt(hireCode)}</code>)`:''}`;
|
||
return `<section class="${org?'ws-panel ws-hire':'panel'}" id="hire-start" aria-labelledby="hire-start-h"><h2 id="hire-start-h">Hire, fire or change an agent</h2><form id="hire-start-form">
|
||
${business}<button type="button" class="btn" data-hire-load data-focus-key="hire:load"${off}>Read role templates</button>
|
||
${select('op','Operation',['hire','fire','change'].map(v=>`<option${d.op===v?' selected':''}>${v}</option>`).join(''))}
|
||
${select('level','Level',['org','project','root'].map(v=>`<option${d.level===v?' selected':''}>${v}</option>`).join(''))}
|
||
${input('project','Project (project level only)')}${input('name','Agent name','required')}
|
||
${select('template','Role template',`<option value="">Choose a template</option>${hireTemplates.map(t=>`<option value="${esc(t.name)}"${d.template===t.name?' selected':''}>${txt(t.name)}</option>`).join('')}`)}
|
||
${input('harness','Harness')}${input('model','Model')}${input('thinking','Thinking (optional)')}${input('reason','Reason','required')}
|
||
<p>Submitting raises and approves one decision. Flagged grants and credentials require the owner; root agents require the instance owner.</p>
|
||
<button type="submit" class="btn primary" data-focus-key="hire:submit"${off}>${hireBusy?'Working…':HIRE_START_LABEL}</button><p id="hire-start-status" role="status">${status}</p></form></section>`;
|
||
}
|
||
function paintHireStart() {const e=$('hire-start');if(e)e.outerHTML=hireStartHtml();}
|
||
document.addEventListener('input',e=>{const f=e.target.closest?.('[data-hire-field]');if(f)hireDraft[f.dataset.hireField]=f.value;});
|
||
document.addEventListener('change',e=>{const f=e.target.closest?.('[data-hire-field]');if(f)hireDraft[f.dataset.hireField]=f.value;});
|
||
async function hireSubmit(templatesOnly=false) {
|
||
if(hireBusy || out() || !canDecide)return;
|
||
const d={...hireDraft},template=hireTemplates.find(t=>t.name===d.template);
|
||
if(!templatesOnly && d.op!=='fire' && !template){hireStatus='Read and choose a role template first.';hireCode='';paintHireStart();return;}
|
||
const thinking=d.thinking?.trim(),hire={op:d.op,level:d.level,name:d.name,reason:d.reason,...(d.level==='project'?{project:d.project}:{}),...(d.op==='fire'?{}:{role:{template:template?.name,sha256:template?.sha256},route:{harness:d.harness,model:d.model,...(thinking?{thinking}:{})}})};
|
||
hireBusy=true;hireStatus='';hireCode='';paintHireStart();
|
||
const epoch=orgEpoch;
|
||
const {res,json}=await decidePost(`/api/decisions/hire/${templatesOnly?'templates':'start'}`,{business:hireOrg() ?? d.business,...(templatesOnly?{}:{hire})});
|
||
if(epoch!==orgEpoch){if(res?.type==='opaqueredirect')signOut();return;}
|
||
hireBusy=false;
|
||
if(res?.type==='opaqueredirect'){signOut();return;}
|
||
if(res?.ok && templatesOnly && Array.isArray(json?.templates)){hireTemplates=json.templates;hireStatus=hireTemplates.length?'Templates read.':'No templates available.';}
|
||
else if(res?.ok && !templatesOnly && json?.op==='resolved'){hireStatus=`Recorded decision ${json.id}.`;}
|
||
else {const r=decideRefusal(res,json,templatesOnly?'confirmation-unavailable':'outcome-unknown');hireStatus=r.message;hireCode=r.code;}
|
||
paintHireStart();
|
||
// A hire, fire or change applied: the Agents page and any pane showing this organization draw it now.
|
||
if(res?.ok && !templatesOnly && json?.op==='resolved' && hireOrg())document.dispatchEvent(new CustomEvent('mosaic-org-changed',{detail:{org:hireOrg()}}));
|
||
}
|
||
// Fire from an agent card on the Agents page (ruling 2026-11-14, visibility): the same hire decision the
|
||
// form above raises with op fire, after an inline confirmation. On success the card goes at once, a
|
||
// receipt names the decision, and the page reads the organization again. The confirmation and the
|
||
// receipt live here so a redraw keeps them; workspace.js draws them from MosaicDecide.
|
||
const FIRE_REASON='Fired from the Agents page.';
|
||
let fireAsk=null,fireBusy=false,fireReceipt=null;
|
||
const fireKey=(org,name)=>`${org}\u0000${name}`;
|
||
function fireNote(){const org=hireOrg();const r=fireReceipt&&fireReceipt.org===org?fireReceipt:null;
|
||
return r?`<p class="receipt${r.failed?' failed':''}" data-agents-receipt-text>${txt(r.text)}${r.code?` (<code>${txt(r.code)}</code>)`:''}</p>`:'';}
|
||
function paintFireNote(){for(const e of document.querySelectorAll('[data-agents-receipt]'))e.innerHTML=fireNote();}
|
||
async function fireAgent(name){
|
||
const org=hireOrg();
|
||
if(fireBusy||!org||out()||!canDecide)return;
|
||
fireBusy=true;
|
||
for(const b of document.querySelectorAll('[data-agent-fire-yes],[data-agent-fire-no]'))b.disabled=true;
|
||
const epoch=orgEpoch;
|
||
const {res,json}=await decidePost('/api/decisions/hire/start',{business:org,hire:{op:'fire',level:'org',name,reason:FIRE_REASON}});
|
||
if(epoch!==orgEpoch){if(res?.type==='opaqueredirect')signOut();return;}
|
||
fireBusy=false;fireAsk=null;
|
||
if(res?.type==='opaqueredirect'){signOut();return;}
|
||
if(res?.ok && json?.op==='resolved'){
|
||
for(const c of document.querySelectorAll(`[data-org="${CSS.escape(org)}"] [data-agent-card="${CSS.escape(name)}"]`))c.remove();
|
||
for(const r of document.querySelectorAll(`[data-agents-org="${CSS.escape(org)}"] tr[data-agent="${CSS.escape(name)}"]`))r.remove();
|
||
fireReceipt={org,text:`Fired ${name}. Recorded decision ${json.id}.`};
|
||
paintFireNote();announce(fireReceipt.text);
|
||
document.dispatchEvent(new CustomEvent('mosaic-org-changed',{detail:{org}}));
|
||
} else {
|
||
const r=decideRefusal(res,json,'outcome-unknown');
|
||
fireReceipt={org,failed:true,text:`${name} was not fired: ${r.message}`,code:r.code};
|
||
paintFireNote();
|
||
for(const c of document.querySelectorAll(`[data-agent-fire-confirm="${CSS.escape(name)}"]`))c.outerHTML=fireButton(name);
|
||
}
|
||
}
|
||
const fireButton=name=>`<button type="button" class="btn small" data-agent-fire="${esc(name)}" data-focus-key="${esc(`fire:${name}`)}" aria-label="Fire ${esc(name)}">Fire</button>`;
|
||
const fireConfirm=name=>`<span class="ws-fire-confirm" role="group" aria-label="Fire ${esc(name)}?" data-agent-fire-confirm="${esc(name)}">Fire ${txt(name)}? <button type="button" class="btn small primary" data-agent-fire-yes="${esc(name)}" data-focus-key="${esc(`fire-yes:${name}`)}"${fireBusy?' disabled':''}>Confirm fire</button><button type="button" class="btn small" data-agent-fire-no="${esc(name)}"${fireBusy?' disabled':''}>Cancel</button></span>`;
|
||
// What the agent card shows for one agent: nothing without the decide right or outside the page's own organization.
|
||
function fireControl(org,name){
|
||
if(!canDecide||isTester||org!==hireOrg())return '';
|
||
return fireAsk===fireKey(org,name)?fireConfirm(name):fireButton(name);
|
||
}
|
||
document.addEventListener('click',e=>{
|
||
const t=e.target.closest?.('[data-agent-fire],[data-agent-fire-yes],[data-agent-fire-no]');
|
||
if(!t)return;
|
||
const org=hireOrg();
|
||
if(t.hasAttribute('data-agent-fire')){const name=t.dataset.agentFire;fireAsk=fireKey(org,name);t.outerHTML=fireConfirm(name);document.querySelector(`[data-agent-fire-yes="${CSS.escape(name)}"]`)?.focus();}
|
||
else if(t.hasAttribute('data-agent-fire-no')){const name=t.dataset.agentFireNo;fireAsk=null;t.closest('[data-agent-fire-confirm]').outerHTML=fireButton(name);announce('Cancelled. Nothing was fired.');}
|
||
else void fireAgent(t.dataset.agentFireYes);
|
||
});
|
||
window.MosaicDecide=Object.freeze({fireControl,fireNote});
|
||
document.addEventListener('click',e=>{if(e.target.closest?.('[data-hire-load]'))hireSubmit(true);});
|
||
document.addEventListener('submit',e=>{if(e.target.id==='hire-start-form'){e.preventDefault();hireSubmit();}});
|
||
const answerChoices = c => ['decision','hire'].includes(c.kind)
|
||
? c.options.map((o, i) => ({ ...o, step: `option-${i}`, label: o.text }))
|
||
: Object.entries(ACTIONS).map(([step, label]) => ({ ...c[step], step, label }));
|
||
const grantText = g => [`method ${g.method}`, g.agent && `agent ${g.agent}`, g.host && `host ${g.host}`, Array.isArray(g.projects) && g.projects.length && `projects ${g.projects.join(', ')}`].filter(Boolean).map(s => txt(String(s))).join(' · ');
|
||
function decideHtml() {
|
||
const a = answer;
|
||
if (!a) return '';
|
||
const off = a.pending ? ' disabled' : '';
|
||
let body;
|
||
if (a.result) {
|
||
const r = a.result;
|
||
body = `<p class="receipt" id="decide-status" tabindex="-1">${['decision','hire'].includes(r.kind) ? 'Recorded' : r.action === 'approve' ? 'Approved' : 'Denied'}: you chose “${txt(r.choice)}”, ${txt(r.text)}.${['decision','hire'].includes(r.kind) ? '' : ` ${r.grant === 'started' ? 'The grant executor started.' : r.action === 'approve' ? 'The bus started no grant for it.' : 'Nothing starts for a denial.'}`} History below shows it once the bus is read again.</p>${r.next ? `<p class="receipt" data-binding-next>${txt(r.next)}</p>` : ''}${window.MosaicInbox?.receipt?.(r, a.decision) ?? ''}`;
|
||
} else if (a.confirm) {
|
||
const c = a.confirm, label = `Confirm ${c.action}`;
|
||
body = `<div class="s1-confirm" role="group" aria-labelledby="b-confirm"><h3 id="b-confirm" class="small">${label}</h3>
|
||
${window.MosaicInbox?.detailMeta?.(a.decision) ?? ''}${window.MosaicInbox?.receipt?.(c, a.decision) ?? ''}${hireLines(c)}<dl class="kv"><dt>Id</dt><dd><code>${txt(c.id)}</code></dd><dt>Question</dt><dd class="s1-q">${txt(c.question)}</dd><dt>Answer</dt><dd><b class="s1-key">${txt(c.choice)}</b> ${txt(c.text)}</dd>${['decision','hire'].includes(c.kind) ? '' : `<dt>Grant</dt><dd>${grantText(c.grant)}</dd>`}</dl>
|
||
<p class="small muted">${['decision','hire'].includes(c.kind) ? 'Confirm to record this choice.' : c.action === 'approve' ? 'Approving starts this grant.' : 'Denying starts nothing.'} This confirmation works once and lasts two minutes.</p>
|
||
<div class="s1-cmd"><button type="button" class="btn primary" data-decide="confirm"${off}>${a.pending ? 'Answering…' : label}</button><button type="button" class="btn" data-decide="cancel"${off}>Cancel</button></div></div>`;
|
||
} else {
|
||
const choices = answerChoices(a.console);
|
||
body = `${hireLines(a.console)}${hireAdjustment(a.console)}<ul class="s1-plain">${choices.map(o => `<li>${['decision','hire'].includes(a.console.kind) ? '' : `<b>${txt(o.label)}</b> chooses `}<b class="s1-key">${txt(o.key)}</b> ${txt(o.text)}</li>`).join('')}</ul>
|
||
<p class="small muted">${['decision','hire'].includes(a.console.kind) ? '' : `Grant: ${grantText(a.console.grant)}. `}Each button opens a confirmation first. Nothing is answered until you confirm.</p>
|
||
<div class="s1-cmd">${choices.map(o => `<button type="button" class="btn${o.step === 'approve' ? ' primary' : ''}" data-decide="${o.step}"${off}>${a.pending === o.step ? 'Checking…' : txt(o.label)}</button>`).join('')}</div>`;
|
||
}
|
||
const e = a.error;
|
||
const said = e ? `<p class="receipt failed" id="decide-status" tabindex="-1">Not answered here: ${txt(e.message)} (<code>${txt(e.code)}</code>).${e.code === 'outcome-unknown' ? ' Nothing was sent again.' : ''}</p>` : '';
|
||
return `<section class="panel s1-decide" id="decide-section" aria-labelledby="b-decide"><h2 id="b-decide">Answer in Console</h2>${body}${said}</section>`;
|
||
}
|
||
// Redraw only the answer panel. `focus` names what takes focus after it.
|
||
function paintDecide(focus) {
|
||
const el = $('decide-section');
|
||
if (!el) return;
|
||
el.outerHTML = decideHtml();
|
||
(focus ? $('decide-section')?.querySelector(focus) : null)?.focus();
|
||
}
|
||
async function decidePost(url, body) {
|
||
let res = null, json = null;
|
||
try {
|
||
res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), cache: 'no-store', redirect: 'manual' });
|
||
try { json = await res.json(); } catch { json = null; }
|
||
} catch { res = null; }
|
||
return { res, json };
|
||
}
|
||
// A refusal the Console wrote carries its code and message (design section 4). Anything else, a
|
||
// 408 or no answer included, gets the fallback: at the resolve step that is outcome-unknown.
|
||
const DECIDE_FALLBACK = {
|
||
'confirmation-unavailable': 'Confirmation is unavailable. Try again later.',
|
||
'outcome-unknown': 'The answer may have reached the bus. Refresh before trying again.',
|
||
};
|
||
const decideRefusal = (res, json, fallback) => res && !res.ok && res.status !== 408 && typeof json?.error === 'string' && typeof json?.message === 'string'
|
||
? { code: json.error, message: json.message } : { code: fallback, message: DECIDE_FALLBACK[fallback] };
|
||
async function decide(step) {
|
||
const a = answer;
|
||
if (!a || a.pending || a.result) return;
|
||
if (step === 'cancel') { a.confirm = null; a.error = null; paintDecide('[data-decide]'); announce('Cancelled. Nothing was answered.'); return; }
|
||
if (out()) { a.confirm = null; a.error = { code: 'sign-in-required', message: 'Sign in again before answering.' }; paintDecide('#decide-status'); return; }
|
||
const selected = answerChoices(a.console).find(o => o.step === step);
|
||
if (selected) {
|
||
const choice = selected.key, ordinary = ['decision','hire'].includes(a.console.kind);
|
||
const adjust=choice==='yes'?collectHireAdjustment(a.console):undefined;
|
||
a.pending = step; a.error = null; a.confirm = null; paintDecide();
|
||
const { res, json } = await decidePost(`/api/decisions/${enc(a.id)}/confirmation`, { choice,...(adjust===undefined?{}:{adjust}) });
|
||
a.pending = null;
|
||
// The page moved to another decision meanwhile: its confirmation is dropped, never shown.
|
||
if (answer !== a) { if (res?.type === 'opaqueredirect') signOut(); return; }
|
||
if (res?.type === 'opaqueredirect') { a.error = { code: 'sign-in-required', message: 'Sign in again before answering.' }; paintDecide('#decide-status'); signOut(); return; }
|
||
if (res?.ok && json?.id === a.id && json.action === (ordinary ? 'answer' : step) && json.choice === choice && typeof json.text === 'string' && typeof json.confirmation === 'string' &&
|
||
(ordinary ? ['decision','hire'].includes(json.kind) && !json.grant : json.grant && typeof json.grant.method === 'string')) {
|
||
a.confirm = json; paintDecide('[data-decide="confirm"]'); announce(`Confirm ${json.action}: ${json.text}`);
|
||
} else { a.error = decideRefusal(res, json, 'confirmation-unavailable'); paintDecide('#decide-status'); announce(`Not answered: ${a.error.message}`); }
|
||
return;
|
||
}
|
||
if (step !== 'confirm' || !a.confirm) return;
|
||
const c = a.confirm;
|
||
a.pending = 'confirm'; a.error = null; paintDecide();
|
||
const { res, json } = await decidePost(`/api/decisions/${enc(a.id)}/resolve`, { choice: c.choice, confirmation: c.confirmation });
|
||
// One use, whatever came back.
|
||
a.pending = null; a.confirm = null;
|
||
if (answer !== a) { if (res?.type === 'opaqueredirect') signOut(); else render(false); return; }
|
||
if (res?.type === 'opaqueredirect') { a.error = { code: 'sign-in-required', message: 'Sign in again before answering. The sign-in proxy redirected the answer, so it never reached the Console.' }; paintDecide('#decide-status'); signOut(); return; }
|
||
if (res?.ok && json?.id === a.id && json.op === 'resolved' && json.choice === c.choice) {
|
||
a.result = { kind: c.kind, action: c.action, choice: c.choice, text: c.text, grant: json.grant ?? null, grantDetails: c.grant ?? null, next: typeof json.next === 'string' ? json.next : null };
|
||
paintDecide('#decide-status'); announce(['decision','hire'].includes(c.kind) ? 'Recorded' : c.action === 'approve' ? 'Approved' : 'Denied'); render(false);
|
||
} else { a.error = decideRefusal(res, json, 'outcome-unknown'); paintDecide('#decide-status'); announce(`Not answered: ${a.error.message}`); }
|
||
}
|
||
async function inboxView(get) {
|
||
await configRead;
|
||
if(!hireDraft.business && window.MosaicOrg?.id)hireDraft.business=window.MosaicOrg.id;
|
||
// The broker orders gated first, then oldest; lift blocking ones to the top.
|
||
const rows = (await get('inbox')).slice().sort((a, b) => (b.blocking - a.blocking) || String(a.at).localeCompare(String(b.at)));
|
||
countInbox(rows);
|
||
const body = rows.length ? `<ul class="waiting s1-decs">${rows.map(decisionCard).join('')}</ul>` : empty('Nothing is waiting on you.', 'A decision shows here when an agent raises one routed to you through the bus.');
|
||
const answered = canDecide ? 'Open an eligible decision to answer any of its options here, after a confirmation. Grant requests keep their Approve and Deny confirmation. You can also use <code>mosaic decide</code> in a terminal.'
|
||
: 'Decisions are answered in a terminal with <code>mosaic decide</code>; Console only shows them.';
|
||
return `${head('Inbox', `${readNote(get)} ${answered}`)}
|
||
${await composer(get)}
|
||
${hireStartHtml()}
|
||
<h2 id="b-for-you">Open decisions <span class="count">${rows.length}</span></h2>${body}
|
||
<p class="small muted">Open a decision for its seen, DM and closing history.</p>`;
|
||
}
|
||
const messageText = m => m.from_role !== 'human' && typeof m.body === 'string' && m.body.startsWith('The turn failed: ') ? `The assistant couldn't reply. Try again, or check Agents.<span class="source">Details: ${txt(m.body.slice('The turn failed: '.length))}</span>` : txt(m.body);
|
||
async function messagesView(get, q) {
|
||
const after = q.get('after');
|
||
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>`
|
||
: 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}
|
||
<nav aria-label="Message pages">${after ? '<a href="#/messages">Newest messages</a> · ' : ''}${page.next ? `<a data-older href="#/messages?after=${enc(page.next)}">Older messages</a>` : ''}</nav>`;
|
||
}
|
||
async function decisionView(get, id, current) {
|
||
const open = (await get('inbox')).find(r => r.id === id) || null, d = await decision(get, id, open);
|
||
// Obsolete reads, including kept-data fallback, must not replace the displayed answer state.
|
||
if (!current()) return '';
|
||
if (!d) return notFound(`No decision with id ${txt(id)}.`);
|
||
const c = d.closed;
|
||
const status = c ? (c.op === 'resolved' ? `Resolved: ${txt(c.by)} chose “${txt(c.choice)}”${c.via ? ` via ${txt(c.via)}` : ''} ${when(c.at)}.` : `${esc(c.op[0].toUpperCase() + c.op.slice(1))} by ${txt(c.by)} ${when(c.at)}${c.note ? `: ${txt(c.note)}` : ''}.`) : `Open since ${when(d.at)}.`;
|
||
// A command is offered only for an open decision routed to the human, and only when
|
||
// the id and key pass the broker's identifier rule, so the copied text is safe to paste.
|
||
const answerable = !c && d.routeTo === 'human';
|
||
// Row 252: the answer panel follows this decision. A refresh keeps a confirmation open; a
|
||
// decision no longer eligible (closed elsewhere, say) drops it, unless an answer is in flight
|
||
// or this page just answered it.
|
||
const eligible = canDecide && answerable && open?.console ? open.console : null;
|
||
if (answer?.id !== d.id) answer = eligible ? { id: d.id, console: eligible, pending: null, confirm: null, error: null, result: null } : null;
|
||
else if (eligible && !answer.pending) {
|
||
if (answer.console.digest !== eligible.digest) answer.confirm = null;
|
||
answer.console = eligible;
|
||
}
|
||
else if (!eligible && !answer.pending && !answer.result) answer = null;
|
||
if (answer?.id === d.id) answer.decision = d;
|
||
const options = `<ol class="s1-opts">${d.options.map(o => {
|
||
const cmd = `mosaic decide ${d.id} ${o.key}`, chosen = c?.choice === o.key, approving = d.authorization?.approvalChoice === o.key;
|
||
const copy = !answerable || open?.console?.kind==='hire' ? '' : SAFE.test(String(d.id)) && SAFE.test(String(o.key))
|
||
? `<div class="s1-cmd"><code>${txt(cmd)}</code><button type="button" class="btn" data-copy="${esc(cmd)}" aria-label="Copy the command for option ${txt(o.key)}">Copy</button></div>`
|
||
: '<p class="small muted">This option has no command here: its key is not a plain identifier.</p>';
|
||
return `<li class="s1-opt"><p><b class="s1-key">${txt(o.key)}</b> ${txt(o.text)} ${approving ? badge(`approves ${d.authorization.action}`, 'attn') : ''}${o.key === d.recommendation ? badge('recommended', 'ok') : ''}${chosen ? badge('chosen', 'ok') : ''}</p>${copy}</li>`;
|
||
}).join('')}</ol>`;
|
||
const earlier = await chain(get, d);
|
||
const history = [...d.seen.map(s => `<li>Seen by ${txt(s.by)}${s.via ? ` via ${txt(s.via)}` : ''} ${when(s.at)}</li>`), ...(c ? [`<li>${esc(c.op)} by ${txt(c.by)}${c.via ? ` via ${txt(c.via)}` : ''} ${when(c.at)}</li>`] : [])];
|
||
// Without SSO, or under SSO without --send, the Console says why it has no buttons and never
|
||
// draws a disabled one (design section 5).
|
||
const why = !answerable || isTester || canDecide ? ''
|
||
: ssoOn ? ' This Console is read-only for decisions: it was started without writes enabled (--send), so answers go through a terminal.'
|
||
: ' Answering a decision from the Console needs sign-in (--sso) and writes enabled (--send).';
|
||
const help = open?.console?.kind==='hire' ? '<p class="small muted">Hire, fire and role changes are answered in the Console by a person with org.hire.</p>' : eligible ? '<p class="small muted">Choose an answer in the panel above. You can also run one of these in a terminal. Copy only puts the command on your clipboard.</p>'
|
||
: answerable ? `<p class="small muted">To answer, run one of these in a terminal. Copy only puts the command on your clipboard. Console sends nothing.${why}</p>`
|
||
: !c ? `<p class="small muted">This decision is routed to ${txt(d.routeTo)}, not to you, so Console offers no command for it.</p>` : '';
|
||
return `${head(`Decision ${txt(short(d.id))}`, status)}
|
||
<section aria-labelledby="b-q" class="panel"><h2 id="b-q">Question</h2><p class="s1-q">${txt(d.question)}</p>${window.MosaicInbox?.detailMeta?.(d) ?? ''}
|
||
<dl class="kv"><dt>Class</dt><dd>${chip(d.class, d.action)}${d.blocking ? ` ${blockChip('blocking')}` : ''}</dd><dt>Approval</dt><dd class="s1-auth">${approves(d.authorization)}</dd><dt>Routed to</dt><dd>${txt(d.routeTo)}</dd><dt>Raised by</dt><dd>${txt(d.raisedBy.role)} <span class="source">${txt(d.raisedBy.run)}</span></dd><dt>Raised</dt><dd>${when(d.at)}</dd>${d.taskRef ? `<dt>Task</dt><dd>${taskLink(d.taskRef)} <span class="source">${txt(d.taskRef)}</span></dd>` : ''}${d.requirementRef ? `<dt>Requirement</dt><dd>${txt(d.requirementRef)}</dd>` : ''}<dt>DM</dt><dd>${d.dm ? `sent ${when(d.dm.at)}` : d.blocking ? 'not sent' : 'not needed (not blocking)'}</dd><dt>Id</dt><dd><code>${txt(d.id)}</code></dd></dl></section>
|
||
${answer?.id === d.id ? decideHtml() : ''}
|
||
${canDecide?window.MosaicAutonomy?.notice(d)??'':''}
|
||
<section aria-labelledby="b-o"><h2 id="b-o">Options</h2>${help}${options}<p class="small muted" id="copy-status"></p></section>
|
||
<section aria-labelledby="b-c"><h2 id="b-c">Earlier versions</h2>${earlier.length ? `<ul class="s1-plain">${earlier.map(x => `<li><a href="#/inbox/${enc(x.id)}">${txt(short(x.id))}</a> ${badge(x.closed ? x.closed.op : 'open')} ${txt(first(x.question))}${x.closed?.note ? `<span class="source">${txt(x.closed.note)}</span>` : ''}</li>`).join('')}</ul>` : '<p class="muted">None.</p>'}</section>
|
||
<section aria-labelledby="b-h"><h2 id="b-h">History</h2>${history.length ? `<ul class="s1-plain">${history.join('')}</ul>` : '<p class="muted">Not seen yet.</p>'}<p><a href="#/trail/decision/${enc(d.id)}">Full trail for this decision</a></p></section>`;
|
||
}
|
||
|
||
// Tasks
|
||
function markers(t) {
|
||
const out = [];
|
||
// The list has no trail, so it can only say the current state came from a Vikunja read;
|
||
// the task page tells a change to a task the stack wrote from one it never wrote.
|
||
if (t.external) out.push(t.external.kind === null ? badge(`last read from Vikunja (${t.external.via})`, 'attn') : t.external.kind === 'foreign' ? badge('not created by the stack', 'attn') : badge(`changed in Vikunja${t.external.changed.length ? `: ${t.external.changed.join(', ')}` : ''}`, 'attn'));
|
||
if (t.conflicts.length) out.push(badge(plural(t.conflicts.length, 'refused write'), 'danger'));
|
||
if (t.missing) out.push(badge(`missing: ${t.missing.reason}`, 'danger'));
|
||
return out.join(' ');
|
||
}
|
||
const title = t => `#${esc(t.id)} ${t.title === null ? '<span class="muted">(no title in the current read)</span>' : txt(t.title)}`;
|
||
const priority = p => p === null ? '<span class="muted">none</span>' : esc(PRIORITY[p] || p);
|
||
function taskRow(t) {
|
||
return `<tr><td class="s1-title"><a href="#/tasks/${enc(t.ref)}">${title(t)}</a></td><td>${t.requirement ? txt(t.requirement) : '<span class="muted">none</span>'}</td><td>${t.assignees.map(user).join(', ') || '<span class="muted">none</span>'}</td><td>${due(t.due)}</td><td>${priority(t.priority)}</td><td>${esc(t.percent)}%</td><td>${when(t.changedAt)}</td><td>${markers(t) || '<span class="muted">none</span>'}</td></tr>`;
|
||
}
|
||
const taskTable = (rows, label) => `<div class="table-wrap" tabindex="0" role="region" aria-label="${esc(label)}, scroll for all columns"><table class="s1-table s1-tasks"><thead><tr>${['Task', 'Requirement', 'Assignees', 'Due', 'Priority', 'Done', 'Changed', 'Markers'].map(h => `<th scope="col">${h}</th>`).join('')}</tr></thead><tbody>${rows.map(taskRow).join('')}</tbody></table></div>`;
|
||
function freshness(rows) {
|
||
const reads = rows.filter(r => r.source === 'poll' && r.read_at).map(r => r.read_at).sort();
|
||
return `Newest Vikunja read among these tasks: ${reads.length ? when(reads.at(-1)) : 'none'}.`;
|
||
}
|
||
const byChanged = (x, y) => String(y.changedAt).localeCompare(String(x.changedAt));
|
||
async function tasksView(get) {
|
||
const rows = await get('tasks'), ts = rows.map(r => task(r));
|
||
if (!ts.length) return `${head('Tasks', freshness(rows))}${empty('No tasks in this business yet.', 'Tasks appear after the PM creates them or the poller reads them from Vikunja.')}`;
|
||
const open = ts.filter(t => !t.missing && !t.done), done = ts.filter(t => !t.missing && t.done).sort(byChanged), missing = ts.filter(t => t.missing);
|
||
const buckets = [...new Set(open.map(t => t.bucket))].sort((a, b) => a - b);
|
||
const groups = buckets.map(b => {
|
||
const g = open.filter(t => t.bucket === b).sort(byChanged), id = `b-bucket-${esc(b)}`;
|
||
return `<section aria-labelledby="${id}"><h2 id="${id}">Bucket ${esc(b)} <span class="count">${g.length}</span></h2>${taskTable(g, `Bucket ${b} tasks`)}</section>`;
|
||
}).join('');
|
||
const doneHtml = done.length ? `<details class="s1-done" id="b-done"><summary><h2 id="b-done-title">Done <span class="count">${done.length}</span></h2></summary>${taskTable(done.slice(0, 50), 'Done tasks')}${done.length > 50 ? `<p class="small muted">The 50 most recently changed of ${done.length}.</p>` : ''}</details>` : '';
|
||
const missingHtml = missing.length ? `<section aria-labelledby="b-missing"><h2 id="b-missing">No longer readable <span class="count">${missing.length}</span></h2><ul class="s1-plain">${missing.map(t => `<li><a href="#/tasks/${enc(t.ref)}">${title(t)}</a> ${badge(`missing: ${t.missing.reason}`, 'danger')} <span class="source">since ${clock(t.missing.at)}</span></li>`).join('')}</ul></section>` : '';
|
||
return `${head('Tasks', freshness(rows))}<p class="small muted">Edit tasks in Vikunja; Console only reads them. ${gap('Bucket names, bot names and the Vikunja address')}</p>${groups || empty('No open tasks.', 'Open tasks are read from Vikunja; done and unreadable ones are listed below.')}${doneHtml}${missingHtml}`;
|
||
}
|
||
// Row 61 (#1550, lead decision 113): who may write each field, from the field table
|
||
// (packages/tasks/fields.json, GET /api/task-fields). The table gives the writer each verb
|
||
// checks; whether a write also needs a decision is each role's authority, on Business. A
|
||
// failed read leaves the rest of the task page as it is and says why here.
|
||
const WRITER = { pm: 'pm', assigned: 'the assigned role', any: 'any role' };
|
||
async function writers(get) {
|
||
let doc;
|
||
try { doc = await get.api('task-fields'); } catch (err) { return `<p class="small">${why(err)}</p>`; }
|
||
const fields = Array.isArray(doc.fields) ? doc.fields : [], verbs = doc.verbs && typeof doc.verbs === 'object' ? doc.verbs : {};
|
||
if (!fields.length) return `<p class="small">${why(Object.assign(new ReadError('invalid-response', ''), { module: true }))}</p>`;
|
||
const by = f => (Array.isArray(f.writes) ? f.writes : []).map(w => `${txt(WRITER[verbs[w.verb]] ?? 'unknown')} <span class="source"><code>${txt(w.verb)}</code></span>`).join('<br>');
|
||
const rows = fields.map(f => `<tr><th scope="row">${txt(f.label)}${f.note ? `<span class="source">${txt(f.note)}</span>` : ''}</th><td>${by(f)}</td></tr>`).join('');
|
||
return `<div class="table-wrap" tabindex="0" role="region" aria-label="Who may write each field, scroll for all columns"><table class="s1-table s1-writers"><thead><tr><th scope="col">Field</th><th scope="col">Writer and verb</th></tr></thead><tbody>${rows}</tbody></table></div>`;
|
||
}
|
||
async function taskView(get, ref) {
|
||
const row = (await get('tasks')).find(r => r.task_ref === ref);
|
||
if (!row) return notFound(`No task ${txt(ref)} in this business.`);
|
||
const tr = await get('trail', ref), t = task(row, tr);
|
||
const ext = t.external ? `<dt>Vikunja</dt><dd>${t.external.kind === 'foreign' ? 'Not created by the stack; first read' : 'Changed in Vikunja after the stack wrote it'}${t.external.changed.length ? `: ${txt(t.external.changed.join(', '))}` : ''}${t.external.comments ? `, ${esc(plural(t.external.comments, 'new comment'))}` : ''} <span class="source">${txt(t.external.via)} read sent ${clock(t.external.readAt)}</span></dd>` : '';
|
||
const conflicts = t.conflicts.length ? `<dt>Refused writes</dt><dd>${t.conflicts.map(c => `${txt(c.verb)}: Vikunja changed after the stack read it (expected ${txt(short(c.expected))}, found ${txt(short(c.actual))}) ${when(c.at)}`).join('<br>')}</dd>` : '';
|
||
const decisions = t.decisions.length ? `<dt>Decisions</dt><dd>${t.decisions.map(d => `<a href="#/inbox/${enc(d.id)}">${txt(short(d.id))}</a> ${txt(first(d.question))}`).join('<br>')}</dd>` : '';
|
||
const sub = t.missing ? `No longer readable in Vikunja (${txt(t.missing.reason)}${t.missing.project ? `, now in project ${txt(t.missing.project)}` : ''}) since ${when(t.missing.at)}.` : `${t.done ? 'Done' : `In bucket ${esc(t.bucket)}`}, last changed ${when(t.changedAt)}. ${readNote(get)}`;
|
||
return `${head(title(t), `${sub} ${markers(t)}`)}
|
||
<section class="panel" aria-labelledby="b-t"><h2 id="b-t">Task</h2><dl class="kv"><dt>Ref</dt><dd><code>${txt(t.ref)}</code> ${gap('The Vikunja address')}</dd><dt>Assignees</dt><dd>${t.assignees.map(user).join(', ') || 'none'} ${gap('Bot names')}</dd><dt>Requirement</dt><dd>${txt(t.requirement || 'none')}</dd><dt>Due</dt><dd>${due(t.due)}</dd><dt>Priority</dt><dd>${priority(t.priority)}</dd><dt>Done</dt><dd>${esc(t.percent)}%</dd>${ext}${conflicts}${decisions}</dl>
|
||
${t.description ? `<h3>Description</h3><p class="s1-q">${txt(t.description)}</p>` : ''}
|
||
<details class="s1-snaps" id="b-snaps"><summary>Snapshots <span class="count">${t.snapshots.length}</span></summary><ol class="s1-plain">${t.snapshots.map(s => `<li>${clock(s.at)} ${esc(bucketText(s.fields))} <span class="source">${s.source === 'self' ? `written by ${txt(s.role)}` : `${txt(s.via)} read sent ${esc(String(s.readAt).slice(11, 19))}`}${s.stale ? '; stale read, not shown' : ''}</span></li>`).join('')}</ol></details></section>
|
||
<section class="panel" aria-labelledby="b-w"><h2 id="b-w">Who may write</h2><p class="small muted">The writer each verb checks, from the slice 1 field table. Whether a write also needs a resolved decision comes from the role's authority, on <a href="#/settings/business">Business</a>. Edits made in Vikunja aren't checked against this table.</p>${await writers(get)}</section>
|
||
<section aria-labelledby="b-trail"><h2 id="b-trail">Trail</h2>${trailList(lines(tr, row.seq), 'all')}<p><a href="#/trail/task/${enc(ref)}">Trail with filters</a></p></section>`;
|
||
}
|
||
|
||
// Agents
|
||
// Row 59 (#1548): the state mark is the control board's (shell.css), glyph and word. The
|
||
// broker derives the state from its own records: working while the holder has messages it
|
||
// received and hasn't answered, waiting while a decision the role raised waits for the
|
||
// human, otherwise idle.
|
||
const stateMark = state => `<span class="badge st st-${esc(state || 'unknown')} badge-${{ working: 'ok', waiting: 'attn' }[state] || 'muted'}">${esc(state || 'unknown')}</span>`;
|
||
function attention(c) {
|
||
const asks = Array.isArray(c.inputNeeded) ? c.inputNeeded : [];
|
||
if (!asks.length) return none;
|
||
const d = asks[0];
|
||
return `Input needed: <a href="#/inbox/${enc(d.id)}">${txt(first(d.question))}</a> <span class="source">${txt(short(d.id))}</span>${d.blocking ? ` ${blockChip('blocking')}` : ''}${asks.length > 1 ? ` <a href="#/inbox">+${esc(asks.length - 1)} more</a>` : ''}`;
|
||
}
|
||
// Row 95 (#1589): the Board's first section, the stack's seats: each held role from the bus
|
||
// `agents` read, a claim with no address included. Message opens the send form addressed to the
|
||
// role, so it shows only where a send can pass (`send` in /api/config). A refusal keeps nothing;
|
||
// any other failure keeps the last read, labelled with its time, as the bus pages do.
|
||
let heldErr = null, heldHtml = null, focusSend = false;
|
||
let heldOrganizations = { empty: false, invalid: [], error: null };
|
||
function heldTable(claims) {
|
||
const cols = ['Role', 'State', 'Attention', 'Address', 'Holder', 'Held since'];
|
||
const rows = claims.map(c => `<tr><th scope="row">${txt(c.role)}</th><td>${stateMark(c.state)}${c.working ? `<span class="source">${esc(plural(c.working.messages, 'message'))} since ${when(c.working.since)}</span>` : ''}</td><td>${attention(c)}</td><td>${c.address ? txt(c.address) : '<span class="muted">no address</span>'}</td><td>${txt(c.role || ('a session '+short(c.holder_run)))}${c.harness ? `<span class="source">${txt(c.harness)}</span>` : ''}</td><td>${when(c.at)}</td>${canMessage ? `<td>${typeof c.role === 'string' && SAFE.test(c.role) ? `<button type="button" class="btn" data-message-role="${esc(c.role)}" aria-label="Message ${esc(c.role)}">Message</button>` : ''}</td>` : ''}</tr>`).join('');
|
||
return `<div class="table-wrap" tabindex="0" role="region" aria-label="Held roles on the board, scroll for all columns"><table class="s1-table s1-agents s1-held"><thead><tr>${cols.map(h => `<th scope="col">${h}</th>`).join('')}${canMessage ? '<th scope="col"><span class="sr-only">Message</span></th>' : ''}</tr></thead><tbody>${rows}</tbody></table></div>`;
|
||
}
|
||
function paintHeld(err, noOrganizations, invalidOrganizations, organizationError) {
|
||
heldErr = err;
|
||
if (noOrganizations !== undefined) heldOrganizations = { empty: noOrganizations, invalid: invalidOrganizations, error: organizationError };
|
||
({ empty: noOrganizations, invalid: invalidOrganizations, error: organizationError } = heldOrganizations);
|
||
const box = $('held'), r = last.get('agents');
|
||
let html;
|
||
if (organizationError) html = `<div class="banner err" role="alert"><p>${txt(organizationError)}</p>${retry}</div>`;
|
||
else if (invalidOrganizations.length) html = `<div class="banner err" role="alert">${invalidOrganizations.map(row => `<p>${txt(row.id)}: invalid — ${txt(row.reason)}</p>`).join('')}${retry}</div>`;
|
||
else if (noOrganizations && err?.code === 'org-unavailable') html = `<div class="empty"><b>No organizations yet.</b><p>Create one in <a href="#/settings/organizations">Settings > Organizations</a>.</p><p><a class="btn" href="${NEW_ORG}">New organization</a></p></div>`;
|
||
else if (err && (refusal(err) || !r)) html = `<div class="banner ${refusal(err) ? 'ref' : 'err'}" role="alert"><p>${refusal(err) ? `<b>refused: <code>${txt(err.code)}</code>.</b> ` : ''}${why(err)} Console shows no held roles rather than a guess.</p>${retry}</div>`;
|
||
else if (!r) return; // not read yet: the skeleton stays
|
||
else {
|
||
const claims = r.rows;
|
||
html = `${err ? `<div class="banner err s1-stale" role="alert"><p><b>The last read failed.</b> ${why(err)} These are the roles read before, ${when(r.at)}. Nothing was changed.</p>${retry}</div>` : ''}
|
||
${claims.length ? heldTable(claims) : empty('No role is held on the bus right now.', 'A role shows here while a run holds its claim on the bus. Machine sessions are under Show machine sessions.')}
|
||
<p class="small muted">Read from the bus ${when(r.at)}.</p>`;
|
||
}
|
||
$('held-count').textContent = organizationError || invalidOrganizations.length || (err && (refusal(err) || !r)) || !r ? '–' : String(r.rows.length);
|
||
if (html === heldHtml) return; // unchanged: no repeated alert, focus stays put
|
||
// Keep focus on the same control across the 10 s repaint.
|
||
const a = document.activeElement, k = box.contains(a) ? { role: a.dataset?.messageRole, retry: a.hasAttribute?.('data-retry'), wrap: a.classList?.contains('table-wrap') } : null;
|
||
box.innerHTML = html; heldHtml = html;
|
||
if (k) {
|
||
const el = k.role ? [...box.querySelectorAll('[data-message-role]')].find(b => b.dataset.messageRole === k.role) : k.retry ? box.querySelector('[data-retry]') : k.wrap ? box.querySelector('.table-wrap') : null;
|
||
(el || $('main')).focus({ preventScroll: true });
|
||
}
|
||
}
|
||
// Row 278: a claims refusal belongs to this section. Only sign-out reaches
|
||
// the global handler; a 403 here must not forget the successful role read.
|
||
async function threadClaimsSection(get, holders, threads, runsKnown, running) {
|
||
await configRead;
|
||
if (isTester) return '';
|
||
const title = '<h2 id="b-thread-claims">Thread claims</h2>';
|
||
try {
|
||
const claims = await get('thread.claims');
|
||
if (out()) { last.delete('thread.claims'); throw signedOut(); }
|
||
if (!claims.every(c => c && ['thread', 'holder_run', 'harness', 'at'].every(k => typeof c[k] === 'string'))) throw new ReadError('invalid-response', '');
|
||
const rows = claims.map(c => {
|
||
const name = threads.find(t => t.id === c.thread)?.name;
|
||
const holder = holders.get(c.holder_run);
|
||
const thread = name ? `${txt(name)}<span class="source">${txt(short(c.thread))}</span>` : txt(c.thread);
|
||
const status = !runsKnown ? ', running status unavailable' : running.has(c.holder_run) ? '' : ', not running';
|
||
const run = holder ? `${txt(holder)}<span class="source">run ${txt(c.holder_run)}${status}</span>` : `run ${txt(c.holder_run)}${status}`;
|
||
return `<tr><th scope="row">${thread}</th><td>${run}</td><td>${txt(c.harness)}</td><td>${when(c.at)}</td></tr>`;
|
||
}).join('');
|
||
return `<section aria-labelledby="b-thread-claims">${title}${claims.length ? `<div class="table-wrap" tabindex="0" role="region" aria-label="Thread claims, scroll for all columns"><table class="s1-table s1-thread-claims"><thead><tr>${['Thread', 'Holder run', 'Harness', 'Claimed at'].map(h => `<th scope="col">${h}</th>`).join('')}</tr></thead><tbody>${rows}</tbody></table></div>` : empty('No thread claim is held right now.', 'A thread appears while a run holds its claim on the bus.')}</section>`;
|
||
} catch (err) {
|
||
if (err.code === 'signed-out') throw err;
|
||
last.delete('thread.claims');
|
||
return `<section aria-labelledby="b-thread-claims">${title}<div class="banner err" role="alert"><p>${why(err)}</p>${retry}</div></section>`;
|
||
}
|
||
}
|
||
async function agentsView(get) {
|
||
let claims;
|
||
try { claims = await get('agents'); } catch (err) {
|
||
if (!window.MosaicOrg || err.code === 'signed-out') throw err;
|
||
if (refusal(err)) forget();
|
||
return `${await window.MosaicWorkspace.agentGrid()}<div class="banner err" role="alert">The selected organization's held roles could not be read. ${why(err)}</div>`;
|
||
}
|
||
let instances = null, threads = [];
|
||
if (!isTester) {
|
||
const reads = await Promise.allSettled([get('instances'), get.api('chat/threads')]);
|
||
if (reads.some(r => r.status === 'rejected' && r.reason?.code === 'signed-out')) throw signedOut();
|
||
if (reads[0].status === 'fulfilled') instances = reads[0].value[0]?.instances ?? null;
|
||
if (reads[1].status === 'fulfilled' && Array.isArray(reads[1].value.rows)) threads = reads[1].value.rows;
|
||
}
|
||
const holders = new Map();
|
||
if (instances && typeof instances === 'object') for (const [name, instance] of Object.entries(instances))
|
||
for (const run of [...(Array.isArray(instance.running) ? instance.running : []), ...(Array.isArray(instance.alive) ? instance.alive : [])]) holders.set(run, name);
|
||
const running = new Set(holders.keys());
|
||
for (const claim of claims) if (claim.holder_run && claim.role && !holders.has(claim.holder_run)) holders.set(claim.holder_run, claim.role);
|
||
const threadSection = await threadClaimsSection(get, holders, threads, !!instances, running);
|
||
const rows = claims.map(c => `<tr><th scope="row">${txt(c.role)}</th><td>${stateMark(c.state)}${c.working ? `<span class="source">${esc(plural(c.working.messages, 'message'))} since ${when(c.working.since)}</span>` : ''}</td><td>${attention(c)}</td><td>${txt(holders.get(c.holder_run) || c.role)}<span class="source">run ${txt(c.holder_run)}${!instances ? ', running status unavailable' : running.has(c.holder_run) ? '' : ', not running'}</span></td><td>${txt(c.harness)}${c.address ? `<span class="source">${txt(c.address)}</span>` : ''}</td><td>${when(c.at)}</td></tr>`).join('');
|
||
// Organization mode (sample 08): the levels grid carries the page heading; held roles follow.
|
||
const top = window.MosaicOrg ? await window.MosaicWorkspace.agentGrid(readNote(get)) : head('Agents', readNote(get));
|
||
return `${top}
|
||
<section aria-labelledby="b-claims"><h2 id="b-claims">Held roles <span class="count">${claims.length}</span></h2><p class="small muted">The current holder of each claimed role. A role nobody holds does not appear. Working: the holder has messages it received and hasn't answered yet. Waiting: a decision the role raised is open in your inbox. Otherwise idle.</p>
|
||
${claims.length ? `<div class="table-wrap" tabindex="0" role="region" aria-label="Held roles, scroll for all columns"><table class="s1-table s1-agents"><thead><tr>${['Role', 'State', 'Attention', 'Holder', 'Harness', 'Held since'].map(h => `<th scope="col">${h}</th>`).join('')}</tr></thead><tbody>${rows}</tbody></table></div>` : empty('No role is held right now.', 'A role shows here while a run holds its claim on the bus.')}</section>
|
||
${threadSection}
|
||
<p class="small muted">Board seats stay on the <a href="${window.MosaicOrg ? '#/board' : '#/'}">control board</a>. This view is about roles.</p>`;
|
||
}
|
||
|
||
// ---------------------------------------------------------------- queue, business, settings
|
||
// Row 54 (#1543), read-only. A row moves only with `scripts/mosaic queue move` in a terminal,
|
||
// so its page shows that command and has no button for it. The business file is edited where
|
||
// it lives. On Settings only appearance changes, and only in this browser.
|
||
const readLine = () => readAt ? `Read ${when(readAt)}.` : 'Reading…';
|
||
const none = '<span class="muted">none</span>';
|
||
const QUEUE_STATES = ['queued', 'briefed', 'in-progress', 'in-review', 'waiting-on-jason', 'done', 'blocked', 'parked'];
|
||
const QSTATE = { done: 'ok', blocked: 'danger', 'waiting-on-jason': 'attn', 'in-review': 'attn', 'in-progress': 'attn' };
|
||
const qState = s => badge(s, QSTATE[s] || 'muted');
|
||
const qLink = id => Number.isInteger(id) ? `<a href="#/queue/${esc(id)}">${esc(id)}</a>` : txt(id);
|
||
// An after entry is {id, when}, as QUEUE.md writes it: "53 done".
|
||
const afterRef = a => a && typeof a === 'object' ? `${qLink(a.id)}${a.when ? ` ${txt(a.when)}` : ''}` : qLink(a);
|
||
const names = list => Array.isArray(list) && list.length ? list.map(txt).join(', ') : none;
|
||
// The business file's arbiters are {delivery, technical}, each a role instance: "pm (delivery)".
|
||
const arbiterRefs = a => a && typeof a === 'object' && !Array.isArray(a) ? Object.entries(a).map(([kind, who]) => `${txt(who)} (${txt(kind)})`).join(', ') || none : names(a);
|
||
const issueRefs = list => Array.isArray(list) && list.length ? list.map(n => `#${txt(n)}`).join(', ') : none;
|
||
// Console serves no repository files, so the brief is its path and anchor, as the row names it.
|
||
const briefRef = b => b?.path ? `<code>${txt(b.path)}${b.anchor ? `#${txt(b.anchor)}` : ''}</code>` : none;
|
||
const storeNotes = notes => Array.isArray(notes) && notes.length ? `<section aria-labelledby="q-notes"><h2 id="q-notes">From the store <span class="count">${notes.length}</span></h2><ul class="s1-plain">${notes.map(n => `<li>${txt(n)}</li>`).join('')}</ul></section>` : '';
|
||
const moveHelp = 'Rows move only with <code>scripts/mosaic queue move</code> in a terminal. Console has no button for it.';
|
||
function queueRow(r) {
|
||
return `<tr><td class="s1-title"><a href="#/queue/${esc(r.id)}">${esc(r.id)} ${txt(r.piece)}</a></td><td>${qState(r.state)}</td><td>${txt(r.owner) || none}</td><td>${names(r.reviewers)}</td><td>${briefRef(r.brief)}</td><td>${when(r.updatedAt)}</td></tr>`;
|
||
}
|
||
async function queueView(get, q) {
|
||
const doc = await get.api('queue'), rows = Array.isArray(doc.rows) ? doc.rows : [];
|
||
const filter = QUEUE_STATES.includes(q.get('state')) ? q.get('state') : 'all';
|
||
const shown = filter === 'all' ? rows : rows.filter(r => r.state === filter);
|
||
const chips = `<nav aria-label="Filter the queue by state" class="chips">${['all', ...QUEUE_STATES].map(s => `<a class="chip" href="#/queue${s === 'all' ? '' : `?state=${s}`}"${filter === s ? ' aria-current="true"' : ''}>${s === 'all' ? 'All' : esc(s)} <span class="count">${s === 'all' ? rows.length : rows.filter(r => r.state === s).length}</span></a>`).join('')}</nav>`;
|
||
const table = `<div class="table-wrap" tabindex="0" role="region" aria-label="Queue rows, scroll for all columns"><table class="s1-table s1-queue"><thead><tr>${['Row', 'State', 'Owner', 'Reviewers', 'Brief', 'Updated'].map(h => `<th scope="col">${h}</th>`).join('')}</tr></thead><tbody>${shown.map(queueRow).join('')}</tbody></table></div>`;
|
||
const body = !rows.length ? empty('The queue has no rows.', 'A row shows here after <code>scripts/mosaic queue add</code> records it in <code>docs/plans/queue.json</code>.')
|
||
: shown.length ? table : empty(`No row is ${esc(filter)}.`, 'Choose another state above.');
|
||
return `${head('Queue', `${readLine()} ${moveHelp}`)}${storeNotes(doc.notes)}${rows.length ? chips : ''}${body}`;
|
||
}
|
||
const round = r => {
|
||
const receipts = Array.isArray(r.receipts) ? r.receipts : [];
|
||
return `<li><p><b>Round ${txt(r.n)}</b> requested by ${txt(r.by)} ${when(r.at)}${r.issue ? ` on #${txt(r.issue)}` : ''}${r.candidate ? ` · candidate ${txt(r.candidate.kind)} <code>${txt(String(r.candidate.digest ?? '').slice(0, 12))}</code>` : ''}</p>
|
||
${receipts.length ? `<ul class="s1-plain">${receipts.map(x => `<li>${txt(x.reviewer)}: ${badge(x.verdict ?? 'no verdict', x.verdict === 'approve' ? 'ok' : x.verdict ? 'attn' : 'muted')} ${when(x.at)}${x.comment ? ` <span class="source">comment ${txt(x.comment)}</span>` : ''}</li>`).join('')}</ul>` : '<p class="small muted">No verdict yet.</p>'}</li>`;
|
||
};
|
||
async function queueRowView(get, id) {
|
||
let doc;
|
||
try { doc = await get.api(`queue/${id}`); } catch (err) { if (err.code === 'not-found') return notFound(`No row ${esc(id)} in the queue.`); throw err; }
|
||
const r = doc.row || {}, rounds = Array.isArray(r.review?.rounds) ? r.review.rounds : [];
|
||
// The command names this row; the state, op and seat are the person's to fill in.
|
||
const cmd = `scripts/mosaic queue move ${id} <state> --op <op> --by <seat>`;
|
||
return `${head(`Row ${esc(id)}: ${txt(r.piece)}`, `${qState(r.state)}${r.previousState ? ` <span class="small muted">was ${txt(r.previousState)}</span>` : ''} ${readLine()}`)}
|
||
${storeNotes(doc.notes)}
|
||
<section class="panel" aria-labelledby="q-row"><h2 id="q-row">Row</h2><dl class="kv"><dt>Owner</dt><dd>${txt(r.owner) || none}</dd><dt>Reviewers</dt><dd>${names(r.reviewers)}</dd><dt>Gate</dt><dd>${txt(r.gateOwner) || none}</dd><dt>Issues</dt><dd>${issueRefs(r.issues)}</dd><dt>Closes</dt><dd>${issueRefs(r.closes)}</dd><dt>Brief</dt><dd>${briefRef(r.brief)}${r.brief?.blob ? ` <span class="source">blob ${txt(String(r.brief.blob).slice(0, 12))}</span>` : ''}</dd><dt>After</dt><dd>${Array.isArray(r.after) && r.after.length ? r.after.map(afterRef).join(', ') : none}</dd><dt>Claim</dt><dd>${r.claim ? `${txt(r.claim.seat)} <span class="source">${txt(r.claim.op)}</span>` : none}</dd>${r.required ? `<dt>Required</dt><dd>yes${Number.isFinite(Date.parse(r.requiredSince)) ? ` since ${when(r.requiredSince)}` : ''}</dd>` : ''}${r.blockedReason ? `<dt>Blocked</dt><dd>${txt(r.blockedReason)}</dd>` : ''}${r.note ? `<dt>Note</dt><dd class="s1-q">${txt(r.note)}</dd>` : ''}<dt>Created</dt><dd>${when(r.createdAt)}</dd><dt>Updated</dt><dd>${when(r.updatedAt)}${r.updatedBy ? ` by ${txt(r.updatedBy)}` : ''}</dd></dl></section>
|
||
<section aria-labelledby="q-review"><h2 id="q-review">Review <span class="count">${rounds.length}</span></h2>${rounds.length ? `<ol class="s1-plain">${rounds.map(round).join('')}</ol>` : '<p class="muted">No review round yet.</p>'}</section>
|
||
<section aria-labelledby="q-move"><h2 id="q-move">Moving this row</h2><p class="small muted">${moveHelp} Copy only puts the command on your clipboard; fill in the state, op and seat before you run it.</p>
|
||
<div class="s1-cmd"><code>${txt(cmd)}</code><button type="button" class="btn" data-copy="${esc(cmd)}" aria-label="Copy the move command for row ${esc(id)}">Copy</button></div><p class="small muted" id="copy-status"></p>
|
||
<p><a href="#/queue">Back to the queue</a></p></section>`;
|
||
}
|
||
|
||
const CRED = { valid: 'ok', expiring: 'attn', expired: 'danger', 'rotation-due': 'danger' };
|
||
const AUTH = { within: 'within-role', cross: 'cross-role', gated: 'gated' };
|
||
const kvRows = (vars, label) => {
|
||
const e = Object.entries(vars || {});
|
||
return e.length ? `<dl class="kv">${e.map(([k, v]) => `<dt><code>${txt(k)}</code></dt><dd>${txt(Array.isArray(v) ? v.join(', ') : typeof v === 'object' && v !== null ? JSON.stringify(v) : v)}</dd>`).join('')}</dl>` : `<p class="muted">${label}</p>`;
|
||
};
|
||
async function businessView(get) {
|
||
const b = (await get.api('business')).business || {};
|
||
const orgs = window.MosaicOrg ? await window.MosaicOrg.list : null;
|
||
if (orgs) await configRead; // orgSetup decides the "New organization" link
|
||
const picker = '';
|
||
const instances = Array.isArray(b.instances) ? b.instances : [], creds = Array.isArray(b.credentials) ? b.credentials : [], actions = Array.isArray(b.actions) ? b.actions : [];
|
||
const launch = b.launch || {};
|
||
const authKnown = instances.some(i => i.authority);
|
||
const roleRows = instances.map(i => `<tr><th scope="row">${txt(i.instance)}</th><td>${txt(i.definition)}</td><td>${txt(i.holder) || none}</td><td>${txt(i.vars?.harness) || none}${i.vars?.model ? `<span class="source">${txt(i.vars.model)}</span>` : ''}</td></tr>`).join('');
|
||
const matrix = authKnown ? `<div class="table-wrap" tabindex="0" role="region" aria-label="Authority by action, scroll for all instances"><table class="s1-table s1-authority"><thead><tr><th scope="col">Action</th>${instances.map(i => `<th scope="col">${txt(i.instance)}</th>`).join('')}</tr></thead><tbody>${actions.map(a => `<tr><th scope="row"><code>${txt(a)}</code></th>${instances.map(i => { const c = i.authority?.[a]; return `<td>${c ? `<span class="tag tag-${AUTH[c] || 'gated'}">${txt(c)}</span>` : '<span class="muted">refused</span>'}</td>`; }).join('')}</tr>`).join('')}</tbody></table></div>`
|
||
: '<p class="muted">Authority comes from the system config with the business file. This Console could not read the system config, so it shows none.</p>';
|
||
const refused = instances.filter(i => i.refused).map(i => `<li>${txt(i.instance)}: ${txt(i.refused)}</li>`).join('');
|
||
const credRows = creds.map(c => `<tr><td>${txt(c.service)}</td><td>${txt(c.account) || '<span class="muted">not named in the business file</span>'}</td><td>${txt(c.role)}</td><td>${txt(c.dateKind === 'expires' ? 'expires' : 'rotate by')} <time datetime="${esc(c.date)}">${txt(c.date)}</time></td><td>${badge(c.state, CRED[c.state] || 'muted')}</td></tr>`).join('');
|
||
return settingsShell('business', `${picker}<section class="panel" aria-labelledby="bz-about"><h2 id="bz-about">${orgs ? 'Organization file' : 'Business file'}</h2><dl class="kv"><dt>Human</dt><dd>${txt(b.human) || none}</dd><dt>Arbiters</dt><dd>${arbiterRefs(b.arbiters)}</dd><dt>Projects</dt><dd>${names(b.projects)}</dd><dt>Launcher</dt><dd>${txt(launch.by) || none}</dd><dt>May launch</dt><dd>${names(launch.instances)}</dd><dt>At most</dt><dd>${Object.entries(launch.limits?.models || {}).flatMap(([p, ms]) => Object.entries(ms).map(([m, c]) => `${txt(c)} ${txt(p)} / ${txt(m)}`)).join(', ') || none}</dd></dl>
|
||
<h3>Vars</h3>${kvRows(b.vars, 'No vars Console shows are set.')}</section>
|
||
<section aria-labelledby="bz-roles"><h2 id="bz-roles">Role instances <span class="count">${instances.length}</span></h2>${instances.length ? `<div class="table-wrap" tabindex="0" role="region" aria-label="Role instances, scroll for all columns"><table class="s1-table s1-roles"><thead><tr>${['Instance', 'Definition', 'Holder', 'Harness'].map(h => `<th scope="col">${h}</th>`).join('')}</tr></thead><tbody>${roleRows}</tbody></table></div>` : empty('This business has no role instances.', 'An instance shows here when the business file names one under roles.')}</section>
|
||
${instances.length ? `<section aria-labelledby="bz-auth"><h2 id="bz-auth">Authority</h2><p class="small muted">Within the role, cross-role (needs the other role), or gated (needs the human), as the business package classifies each action.</p>${matrix}${refused ? `<ul class="s1-plain">${refused}</ul>` : ''}</section>` : ''}
|
||
<section aria-labelledby="bz-creds"><h2 id="bz-creds">Credentials <span class="count">${creds.length}</span></h2><p class="small muted">Metadata only: service, account, role and date. Console never reads a token, a token file or a variable.</p>${creds.length ? `<div class="table-wrap" tabindex="0" role="region" aria-label="Credentials, scroll for all columns"><table class="s1-table s1-creds"><thead><tr>${['Service', 'Account', 'Role', 'Date', 'State'].map(h => `<th scope="col">${h}</th>`).join('')}</tr></thead><tbody>${credRows}</tbody></table></div>` : empty('No credentials are named.', 'A credential shows here when a role instance or tracker sync names one.')}</section>`, `${orgs ? 'Organization' : 'Business'} ${txt(b.id)}. The Console only reads this file.`);
|
||
}
|
||
|
||
// Stream S4: the palette tiles are the installed themes (GET /api/themes), Harbor first, which is built in and never needs its module.
|
||
// A saved or chosen theme that is not installed gets a tile of its own, labelled, so the page never shows a choice that is not on the list.
|
||
function appearance() {
|
||
const A = window.MosaicAppearance, s = A.state(), listed = A.themes();
|
||
const segment = (name, options, selected) => `<div class="settings-segments" role="radiogroup" aria-label="${name}">${options.map(([value,label])=>`<label><input type="radio" name="${name.toLowerCase()}" value="${value}"${value===selected?' checked':''}><span>${label}</span></label>`).join('')}</div>`;
|
||
// The ten that ship keep the order this page has always shown; any other installed theme follows, in the server's order (by id).
|
||
const shipped = new Map(Brand.palettes.map((p, i) => [p.id, i])), rank = t => shipped.get(t.id) ?? shipped.size;
|
||
const tiles = [{id: Brand.DEFAULT_THEME, displayName: nameFor(Brand.DEFAULT_THEME)}, ...(listed || []).filter(t => t.id !== Brand.DEFAULT_THEME)].sort((a, b) => rank(a) - rank(b));
|
||
const missing = s.warning && !tiles.some(t => t.id === s.warning.theme) ? String(s.warning.theme).slice(0, 64) : null;
|
||
// The Harbor tile is checked while a missing theme is replaced by it: the radio group shows what the page shows. The missing theme's own tile cannot be picked.
|
||
const tile = (t, gone) => `<label class="palette-tile${gone?' palette-missing':''}"><input type="radio" name="palette" value="${esc(t.id)}"${gone?' disabled':t.id===s.theme?' checked':''}><span class="palette-content"><span class="palette-swatches" data-swatch="${esc(t.id)}"><i></i><i></i><i></i></span><strong>${txt(t.displayName)}</strong>${gone?'<small class="palette-gone">Not installed or not valid</small>':''}<span class="palette-check" aria-hidden="true">✓</span></span></label>`;
|
||
return `<section class="panel"><h3>Theme</h3><p>System follows your device. The switch in the top bar flips between light and dark.</p>${segment('Theme', [['system','System'],['light','Light'],['dim','Dim'],['dark','Dark']],s.mode)}<p class="settings-browser-status" data-status="theme" role="status"></p></section>
|
||
<section class="panel"><h3>Palette</h3><p>Colors for every page. Harbor is the default.</p><div class="palette-grid" role="radiogroup" aria-label="Palette">${tiles.map(t=>tile(t,false)).join('')}${missing?tile({id: missing, displayName: missing}, true):''}</div><p class="settings-browser-status" data-status="palette" role="status"></p>${appearanceNotes(s)}</section>
|
||
<section class="panel"><h3>Sidebar density</h3><p>How much space each sidebar row takes.</p>${segment('Density',[['comfortable','Comfortable'],['compact','Compact']],window.MosaicDisplay.get().density)}<p class="settings-browser-status" data-status="density" role="status"></p></section>`;
|
||
}
|
||
const nameFor = id => (window.MosaicAppearance.themes() || []).find(t => t.id === id)?.displayName || (id === Brand.DEFAULT_THEME ? Brand.palettes.find(p => p.id === Brand.DEFAULT_THEME).name : String(id).slice(0, 64));
|
||
// Where the page's theme and mode come from, in words, and the way back to the organization's choice.
|
||
// Nothing is written while both are the built-in default and nothing is chosen or missing: that page looks as it always has.
|
||
function appearanceNotes(s) {
|
||
if (s.themeSource === 'default' && s.modeSource === 'default' && !s.override && !s.warning) return '';
|
||
const org = s.organization, label = org ? txt(org.label) : 'The organization';
|
||
const saved = [s.saved?.theme && `theme ${txt(nameFor(s.saved.theme))}`, s.saved?.mode && `mode ${txt(s.saved.mode)}`].filter(Boolean).join(', ');
|
||
const source = (what, from) => from === 'browser' ? 'your choice in this browser' : from === 'organization' ? `${label}’s saved ${what}` : 'the built-in default';
|
||
const where = `Showing <strong>${txt(nameFor(s.theme))}</strong> (${source('theme', s.themeSource)}) in <strong>${txt(s.mode)}</strong> mode (${source('mode', s.modeSource)}).${org ? ` ${label} saves ${saved || 'no appearance'}.` : ''}`;
|
||
const clear = s.override ? `<p><button type="button" class="btn" data-theme-clear>${org ? `Use ${label}’s choice` : 'Use the default'}</button></p>` : '';
|
||
return `<div data-notes><p class="settings-source">${where}</p>${clear}</div>`;
|
||
}
|
||
// The tile list and the notes follow the page: themes that arrive after Settings was drawn, a different organization, a cleared override.
|
||
// The tiles are rebuilt only when the list, the organization or a warning changes, so a pick keeps its focus.
|
||
function syncAppearance(drawn = false) {
|
||
const host = document.querySelector('.settings-appearance'); if (!host) return;
|
||
const A = window.MosaicAppearance, s = A.state();
|
||
const sig = JSON.stringify([(A.themes() || []).map(t => t.id), s.warning, s.organization, s.saved]);
|
||
if (drawn) host.dataset.sig = sig;
|
||
else if (host.dataset.sig !== sig) {
|
||
const f = document.activeElement, key = f && host.contains(f) && f.name ? [f.name, f.value] : null;
|
||
const t = document.createElement('template'); t.innerHTML = appearance();
|
||
host.querySelectorAll(':scope > section.panel').forEach(n => n.remove()); host.append(t.content);
|
||
host.dataset.sig = sig;
|
||
if (key) [...host.querySelectorAll('input')].find(i => i.name === key[0] && i.value === key[1])?.focus();
|
||
} else {
|
||
const notes = Object.assign(document.createElement('template'), {innerHTML: appearanceNotes(s)}).content, old = host.querySelector('[data-notes]');
|
||
if (old) old.replaceWith(notes); else host.querySelector('[data-status=palette]')?.after(notes);
|
||
}
|
||
paintSwatches();
|
||
}
|
||
// Tile swatches are drawn from each theme's own tokens for the mode now shown, so an installed theme that tokens.css has never heard of still previews correctly.
|
||
function paintSwatches() {
|
||
const A = window.MosaicAppearance, listed = A.themes(); if (!listed) return;
|
||
const dark = matchMedia('(prefers-color-scheme: dark)').matches, mode = A.state().mode;
|
||
for (const el of document.querySelectorAll('.settings-appearance [data-swatch]')) {
|
||
const t = listed.find(t => t.id === el.dataset.swatch), p = t && Brand.themeProperties(t, mode, dark); if (!p) continue;
|
||
const v = Object.fromEntries(p);
|
||
el.style.setProperty('--swatch-canvas', v['--canvas']); el.style.setProperty('--swatch-action', v['--action']); el.style.setProperty('--swatch-accent', v['--accent']);
|
||
}
|
||
}
|
||
const browserStatusTimers = Object.create(null);
|
||
function browserStatus(name, ok) {
|
||
const el = document.querySelector(`[data-status="${name}"]`); if (!el) return;
|
||
el.textContent = ok ? '✓ Saved in this browser.' : 'Could not save in this browser. The choice applies until you reload.';
|
||
el.classList.toggle('warning', !ok); clearTimeout(browserStatusTimers[name]);
|
||
if (ok) browserStatusTimers[name] = setTimeout(()=>{if(el.isConnected)el.textContent='';},4000);
|
||
}
|
||
document.addEventListener('change', e => {
|
||
if (!e.target.closest?.('.settings-appearance')) return;
|
||
const {name,value}=e.target;
|
||
if (name==='density') browserStatus(name,window.MosaicDisplay.setDensity(value));
|
||
if (name==='theme'||name==='palette') { const src=$(name==='theme'?'mode':'palette'); src.value=value; src.dispatchEvent(new Event('change',{bubbles:true})); }
|
||
});
|
||
document.addEventListener('click', e => { if (e.target.closest?.('.settings-appearance [data-theme-clear]')) window.MosaicAppearance.clear(); });
|
||
document.addEventListener('mosaic-theme-change', e => {
|
||
syncAppearance();
|
||
for (const [name,value] of [['theme',e.detail.mode],['palette',e.detail.palette]]) {
|
||
const input=[...document.querySelectorAll(`.settings-appearance input[name="${name}"]`)].find(i=>i.value===value); if(input)input.checked=true;
|
||
}
|
||
if (document.activeElement?.name==='theme'||document.activeElement?.name==='palette') browserStatus(document.activeElement.name,e.detail.stored);
|
||
});
|
||
// REQ-WEB-1: drafts survive polling/refusals; only an explicit submit writes.
|
||
let settingsSnapshot=null, settingsInputs=null, settingsSaving=false, settingsReceipt='', settingInvalidKey=null;
|
||
const inputKey=parts=>JSON.stringify(parts);
|
||
// Row 167 (#1664): one snapshot for the launch form, the assistant forms and the token limit
|
||
// reset. A read replaces it only while no form has a draft; every save and reset sets it from
|
||
// its answer, so the next submit sends the revision the last write returned.
|
||
const launchDrafts=()=>!!settingsInputs||Object.keys(assistantDrafts).length>0;
|
||
function takeSnapshot(value){if(!settingsSnapshot||!launchDrafts())settingsSnapshot=value;return settingsSnapshot;}
|
||
function launchForm(value){
|
||
if(!value||value.refused)return `<section class="panel"><h2>Agent limits</h2><p>${txt(value?.message||'Launch settings are not configured.')}</p></section>`;
|
||
const v=takeSnapshot(value), modelTable=v.models||{}, limits=v.limits||{}, usage=v.usage||{};
|
||
const val=(parts,fallback)=>settingsInputs&&Object.hasOwn(settingsInputs,inputKey(parts))?settingsInputs[inputKey(parts)]:fallback;
|
||
const disabled=!canSend||out()||settingsSaving?' disabled':'';
|
||
const field=(parts,label,count,current)=>`<tr><th scope="row">${txt(label)}</th><td><label><span class="sr-only">${txt(label)} limit</span><input placeholder="No limit" data-setting="${esc(inputKey(parts))}"${settingInvalidKey===inputKey(parts)?' aria-invalid="true"':''} type="number" min="0" step="1" value="${esc(val(parts,count??''))}"${disabled}></label></td><td class="muted">${txt(current??0)} running</td></tr>`;
|
||
const providers=new Set([...Object.keys(limits.providers||{}),...Object.values(modelTable).map(x=>x.provider)]);
|
||
const pairs=new Map();for(const [provider,models]of Object.entries(limits.models||{}))for(const model of Object.keys(models))pairs.set(inputKey([provider,model]),[provider,model]);for(const m of Object.values(modelTable))pairs.set(inputKey([m.provider,m.model]),[m.provider,m.model]);
|
||
const providerRows=[...providers].map(p=>field(['providers',p],p,limits.providers?.[p],usage.providers?.[p])).join('');
|
||
const modelRows=[...pairs.values()].map(([p,m])=>field(['models',p,m],`${p} / ${m}`,limits.models?.[p]?.[m],usage.models?.[p]?.[m])).join('');
|
||
const table=Object.entries(modelTable).map(([key,m])=>`<tr><th scope="row">${txt(key)}</th><td><label><span class="sr-only">Provider for ${txt(key)}</span><input data-setting="${esc(inputKey(['table',key,'provider']))}" value="${esc(val(['table',key,'provider'],m.provider))}" maxlength="200"${disabled}></label></td><td><label><span class="sr-only">Model for ${txt(key)}</span><input data-setting="${esc(inputKey(['table',key,'model']))}" value="${esc(val(['table',key,'model'],m.model))}" maxlength="200"${disabled}></label></td></tr>`).join('');
|
||
// Row 65 (mos-0840): each instance's model moved to the routing table below.
|
||
return `<form id="launch-settings-form" novalidate><section class="panel" aria-labelledby="launch-settings-title"><h3 id="launch-settings-title">Launch limits</h3><table class="settings-limits-table"><colgroup><col><col><col></colgroup><thead><tr><th>Scope</th><th>Limit</th><th>Running now</th></tr></thead><tbody><tr class="limit-group"><th colspan="3">All sessions</th></tr>${field(['total'],'All sessions',limits.total,usage.total)}<tr class="limit-group"><th colspan="3">Provider</th></tr>${providerRows}<tr class="limit-group"><th colspan="3">Model</th></tr>${modelRows}</tbody></table></section><section class="panel"><h3>Model names</h3><p>Which provider model each short name launches.</p><table class="settings-model-table"><colgroup><col><col><col></colgroup><thead><tr><th>Name</th><th>Provider</th><th>Model</th></tr></thead><tbody>${table}</tbody></table></section><p class="small muted">${canSend?'Changes are checked and logged with your identity.':'Saving requires signed-in send mode.'}</p><div class="settings-actions${settingsInputs?' has-draft':''}"><button type="submit"${disabled}>${settingsSaving?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Save launch settings'}</button> <button type="button" id="launch-settings-reload"${settingsInputs?'':' hidden'}${settingsSaving?' disabled':''}>Discard draft</button><p role="status" id="launch-settings-receipt" class="${settingsReceipt.startsWith('Outcome unknown')?'banner ref':settingsReceipt.includes('Draft kept')||settingsReceipt.startsWith('Limits need')?'banner err':settingsReceipt.includes('saved')?'settings-success':''}">${txt(settingsReceipt)}</p></div></form>`;
|
||
}
|
||
function settingDraft(form){const values={};for(const el of form.querySelectorAll('[data-setting]'))values[el.dataset.setting]=el.value;return values;}
|
||
function settingPayload(){const v=settingsSnapshot, limits={providers:Object.create(null),models:Object.create(null)},models=structuredClone(v.models);for(const [encoded,text]of Object.entries(settingsInputs)){const [kind,p,m]=JSON.parse(encoded);if(kind==='table'){models[p][m]=text;continue;}if(text==='')continue;if(!/^\d+$/.test(text)||!Number.isSafeInteger(Number(text))){settingInvalidKey=encoded;throw Error('Limits need whole numbers of zero or more.');}const n=Number(text);if(kind==='total')limits.total=n;else if(kind==='providers')limits.providers[p]=n;else {limits.models[p]??=Object.create(null);limits.models[p][m]=n;}}
|
||
// Row 125 (#1619): the form doesn't edit token limits; a save keeps them as read.
|
||
if(v.limits?.tokens)limits.tokens=structuredClone(v.limits.tokens);
|
||
return {revision:v.revision,limits,models};
|
||
}
|
||
document.addEventListener('input',e=>{const form=e.target.closest?.('#launch-settings-form');if(form){e.target.removeAttribute('aria-invalid');settingInvalidKey=null;settingsInputs=settingDraft(form);markSettingsDraft('limits',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=$('launch-settings-reload');if(discard)discard.hidden=false;}});
|
||
document.addEventListener('change',e=>{const form=e.target.closest?.('#launch-settings-form');if(form){settingsInputs=settingDraft(form);markSettingsDraft('limits',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=$('launch-settings-reload');if(discard)discard.hidden=false;}});
|
||
document.addEventListener('click',e=>{if(e.target.id!=='launch-settings-reload')return;settingsInputs=null;settingsSnapshot=null;settingsReceipt='';last.delete('api:settings');render(true);});
|
||
document.addEventListener('submit',async e=>{
|
||
if(e.target.id!=='launch-settings-form')return;e.preventDefault();if(!canSend||out()||settingsSaving)return;settingsInputs=settingDraft(e.target);let payload;try{payload=settingPayload();}catch(err){settingsReceipt=err.message+' Draft kept.';render(false);return;}settingsSaving=true;settingsReceipt='';render(false);const epoch=orgEpoch;
|
||
try{const response=await fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(epoch!==orgEpoch){if(response.type==='opaqueredirect')signOut();return;}if(response.type==='opaqueredirect'){settingsReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json();if(epoch!==orgEpoch)return;if(response.ok&&/^[a-f0-9]{64}$/.test(result?.revision??'')){settingsInputs=null;settingsSnapshot=result;const prior=last.get('api:settings');if(prior)last.set('api:settings',{...prior,launch:result});settingsReceipt='Launch settings saved.';}else settingsReceipt=result?.sent==='unknown'?'Outcome unknown. Read current settings before trying again. Draft kept.':`${result?.message||'Settings refused.'} Draft kept.`;}}
|
||
catch{if(epoch!==orgEpoch)return;settingsReceipt='Outcome unknown. Read current settings before trying again. Draft kept.';}finally{if(epoch===orgEpoch){settingsSaving=false;if(!out())render(false);}}
|
||
});
|
||
// Row 125 (#1619, REQ-LIMIT-3, REQ-LIMIT-4): each token limit as the bus's checks report it. A
|
||
// limit no switched-on check counts reads "not enforced". Reset counts it again from now. Row 126
|
||
// (#1620): any daily quota row adds one line saying the count is this stack's own use only.
|
||
let resetReceipt='';
|
||
function tokenLimits(rows, refused) {
|
||
const title = '<h2 id="token-limits-title">Token limits</h2>';
|
||
if (refused) return `<section class="panel" aria-labelledby="token-limits-title">${title}<p>Token limits unavailable. No report was read.</p></section>`;
|
||
if (!rows.length) return `<section class="panel" aria-labelledby="token-limits-title">${title}<p>No token limits are set. This page can reset a limit but cannot set one.</p></section>`;
|
||
const can = canSend && !out() && !settingsSaving && /^[a-f0-9]{64}$/.test(settingsSnapshot?.revision ?? '');
|
||
const state = t => t.status === 'counted'
|
||
? `${txt(t.count)} (input ${txt(t.kinds?.input)}, output ${txt(t.kinds?.output)}, cache write ${txt(t.kinds?.cacheWrite)}, cache read ${txt(t.kinds?.cacheRead)}); unknown turns ${txt(t.unknownTurns)}`
|
||
: t.status === 'not-enforced' ? `not enforced${t.reason ? `: ${txt(t.reason)}` : ''}`
|
||
: `check failed: ${txt(t.code)}${t.check ? ` (${txt(t.check)})` : ''}`;
|
||
const body = rows.map(t => `<tr><th scope="row">${txt((t.path || []).join(' / '))}</th><td>${txt(t.limit)}</td><td>${txt(t.since)}</td><td>${state(t)}</td><td><button type="button" data-limit-reset="${esc(JSON.stringify(t.path || []))}"${can ? '' : ' disabled'}>Reset</button></td></tr>`).join('');
|
||
return `<section class="panel" aria-labelledby="token-limits-title">${title}<p>A count is every token kind since the limit was set or reset. Unknown turns add nothing to it.</p><div class="table-wrap"><table id="token-limits-table"><thead><tr><th scope="col">Subject</th><th scope="col">Limit</th><th scope="col">Since</th><th scope="col">Count</th><th scope="col"><span class="sr-only">Reset</span></th></tr></thead><tbody>${body}</tbody></table></div>${rows.some(t => t.path?.[1] === 'daily') ? '<p class="small muted" id="token-limits-daily">Daily quotas count only this stack\'s own use of the account, not its use anywhere else.</p>' : ''}<p class="small muted">${canSend ? 'A reset is logged with your identity.' : 'Resetting requires signed-in send mode.'}</p><p role="status" id="token-limits-receipt">${txt(resetReceipt)}</p></section>`;
|
||
}
|
||
document.addEventListener('click',async e=>{
|
||
const path=e.target.dataset?.limitReset;if(path===undefined||!canSend||out()||settingsSaving)return;
|
||
const revision=settingsSnapshot?.revision;if(!/^[a-f0-9]{64}$/.test(revision??''))return;
|
||
settingsSaving=true;resetReceipt='';render(false);let reread=false;const epoch=orgEpoch;
|
||
try{const response=await fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision,reset:[JSON.parse(path)]}),cache:'no-store',redirect:'manual'});if(epoch!==orgEpoch){if(response.type==='opaqueredirect')signOut();return;}if(response.type==='opaqueredirect'){resetReceipt='Sign in again.';signOut();}else{const result=await response.json();if(epoch!==orgEpoch)return;if(response.ok&&/^[a-f0-9]{64}$/.test(result?.revision??'')){settingsSnapshot=result;const prior=last.get('api:settings');if(prior)last.set('api:settings',{...prior,launch:result});reread=true;resetReceipt='Limit reset.';}else resetReceipt=result?.sent==='unknown'?'Outcome unknown. Read current settings before trying again.':`${result?.message||'Reset refused.'}`;}}
|
||
catch{if(epoch!==orgEpoch)return;resetReceipt='Outcome unknown. Read current settings before trying again.';}finally{if(epoch===orgEpoch){settingsSaving=false;if(!out())render(reread);}}
|
||
});
|
||
function tokenUsage(value) {
|
||
if (!value?.total) return '<section class="panel" aria-labelledby="token-usage-title"><h2 id="token-usage-title">Token usage</h2><p>Usage unavailable. No count was read.</p></section>';
|
||
const columns = row => ['input', 'output', 'cacheWrite', 'cacheRead', 'unknownTurns'].map(key => `<td>${txt(row[key])}</td>`).join('');
|
||
const rows = [`<tr><th scope="row">Total</th>${columns(value.total)}</tr>`];
|
||
for (const [group, label] of [['byRun', 'Run'], ['byInstance', 'Instance'], ['byModel', 'Model'], ['byProvider', 'Provider'], ['byAccount', 'Account'], ['byKey', 'Key']]) {
|
||
for (const row of value[group] || []) {
|
||
const name = ['run', 'instance', 'provider', 'model', 'account', 'modelKeyId'].filter(key => key in row).map(key => row[key] ?? 'unassigned').join(' / ');
|
||
rows.push(`<tr><th scope="row">${label}: ${txt(name)}</th>${columns(row)}</tr>`);
|
||
}
|
||
}
|
||
// Row 333 R3 (#1831): a daily key quota whose key id no hired agent holds, now or before.
|
||
const orphans = Array.isArray(value.orphanedKeyQuotas) && value.orphanedKeyQuotas.length ? `<ul id="token-usage-orphans" aria-label="Key quotas that match no agent">${value.orphanedKeyQuotas.map(id => `<li>Key quota ${txt(id)} matches no agent, so it limits nothing. A fire and re-hire gives the agent a new key; set the quota on the new key id.</li>`).join('')}</ul>` : '';
|
||
// #778: batches the proxy gave up and the bus did not save, since the bus started. Shown only above 0.
|
||
const lost = Number.isSafeInteger(value.proxy?.droppedBatches) ? value.proxy.droppedBatches : 0;
|
||
const dropped = lost > 0 ? `<p id="token-usage-proxy-dropped" role="status">${txt(lost)} ${lost === 1 ? 'batch' : 'batches'} of proxy usage events could not be saved since the bus started. The events in a dropped batch are lost and are not in these totals.</p>` : '';
|
||
const proxy = value.proxy ? `<section aria-label="Proxy-reported usage"><h3>Proxy-reported usage</h3><p>Optional proxy telemetry never enforces a quota. Status: ${txt(value.proxy.state)}. These counts cover drained events and may be incomplete.</p>${dropped}<div class="table-wrap"><table><thead><tr><th>Proxy account ID</th><th>Input</th><th>Output</th><th>Cache write</th><th>Cache read</th><th>Requests</th><th>Failures</th></tr></thead><tbody>${(value.proxy.byAccount || []).map(row => `<tr><th scope="row">${txt(row.accountId)}</th>${['input','output','cacheWrite','cacheRead','requests','failures'].map(k => `<td>${txt(row[k])}</td>`).join('')}</tr>`).join('')}</tbody></table></div></section>` : '';
|
||
return `<section class="panel" aria-labelledby="token-usage-title"><h2 id="token-usage-title">Token usage</h2><p>Best reading of session-editable transcripts, not proof. Unknown turns may have used more tokens. Account is unassigned until account tracking is configured.</p>${rows.length===1&&['input','output','cacheWrite','cacheRead','unknownTurns'].every(k=>value.total[k]===0)?'<p>No token use counted yet.</p>':`<div class="table-wrap"><table id="token-usage-table"><thead><tr><th scope="col">Subject</th><th scope="col">Input</th><th scope="col">Output</th><th scope="col">Cache write</th><th scope="col">Cache read</th><th scope="col">Unknown turns</th></tr></thead><tbody>${rows.join('')}</tbody></table></div>`}${orphans}${proxy}</section>`;
|
||
}
|
||
// Row 155 (#1649, Q169): each assistant instance's settings, its seat name and a stop. A save
|
||
// sends only the fields that changed, with the read's revision. Drafts survive polling and
|
||
// refusals as in the limits form, and nothing retries.
|
||
let assistantDrafts=Object.create(null), nameDrafts=Object.create(null), assistantBusy=false, assistantReceipts=Object.create(null), assistantReceiptKinds=Object.create(null), assistantCardReceipts=Object.create(null);
|
||
const assistantFormsBusy=new Set(), assistantKey=(instance,kind)=>`${instance}:${kind}`;
|
||
const asShown=(entry,field)=>field==='definition'?entry.definition??'':entry[field]==null?'':JSON.stringify(entry[field],null,2);
|
||
function assistantSection(value,names){
|
||
if(!value||value.refused)return '';
|
||
const v=takeSnapshot(value);if(!v.assistants||!Object.keys(v.assistants).length)return '<p class="empty">This business has no assistant instance.</p>';
|
||
const named=names?Object.fromEntries(names.map(r=>[r.instance,r.name])):null;
|
||
const forms=Object.entries(v.assistants).map(([instance,entry])=>{
|
||
const d=assistantDrafts[instance]||{}, val=f=>Object.hasOwn(d,f)?d[f]:asShown(entry,f), k=esc(instance);
|
||
const name=Object.hasOwn(nameDrafts,instance)?nameDrafts[instance]:named?.[instance]??'';
|
||
const busy=kind=>assistantFormsBusy.has(assistantKey(instance,kind)), disabledFor=kind=>!canSend||out()||busy(kind)?' disabled':'', disabled=disabledFor('settings'), nameDisabled=disabledFor('name'), stopDisabled=disabledFor('stop');
|
||
const status=kind=>{const text=assistantCardReceipts[assistantKey(instance,kind)]||'', current=(assistantReceiptKinds[instance]||'settings')===kind;return `<p role="status" data-assistant-kind="${kind}"${current?` data-assistant-receipt="${k}"`:''} class="${text.startsWith('Outcome unknown')?'banner ref':text.includes('Draft kept')?'banner err':text.includes('saved')||text.startsWith('Seat name set')||text.startsWith('Stopped')?'settings-success':''}">${txt(text)}</p>`;};
|
||
return `<form class="assistant-form" data-instance="${k}"><section class="panel"><h3>Seat name</h3><p>The name people see for this seat.</p><div class="filters"><label>Seat name <input data-assistant-field="name" value="${esc(name)}" maxlength="64" placeholder="No name set"${nameDisabled}></label><button type="button" data-assistant-name="${k}"${nameDisabled}>${busy('name')?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Save name'}</button>${named?'':' <span class="small muted">The current name could not be read.</span>'}</div>${status('name')}</section><section class="panel"><h3>Settings</h3><label>Definition <input data-assistant-field="definition" value="${esc(val('definition'))}" maxlength="64"${disabled}></label><label>Vars as JSON <textarea data-assistant-field="vars" rows="4"${disabled}>${esc(val('vars'))}</textarea></label><p>Harness, model and thinking are set in Routing.</p><label>Tracker as JSON <textarea data-assistant-field="tracker" rows="4"${disabled}>${esc(val('tracker'))}</textarea></label><p>Leave empty to remove the tracker.</p><div class="settings-actions${assistantDrafts[instance]||Object.hasOwn(nameDrafts,instance)?' has-draft':''}"><button type="submit"${disabled}>${busy('settings')?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Save assistant settings'}</button><button type="button" data-assistant-discard="${k}"${assistantDrafts[instance]||Object.hasOwn(nameDrafts,instance)?'':' hidden'}${busy('settings')?' disabled':''}>Discard draft</button>${status('settings')}</div></section><section class="panel"><h3>Runs</h3><p>Stop ends the runs of your threads. The assistant starts again when you next write to it.</p><button type="button" class="agent-danger" data-assistant-stop="${k}"${stopDisabled}>${busy('stop')?'<span class="settings-spinner" aria-hidden="true"></span> Stopping…':'Stop its runs'}</button>${status('stop')}</section></form>`;
|
||
}).join('');
|
||
return `<div aria-labelledby="settings-page-title">${forms}</div>`;
|
||
}
|
||
function assistantPayload(instance,form){
|
||
const entry=settingsSnapshot.assistants[instance], patch={};
|
||
for(const f of ['definition','vars','tracker']){
|
||
const text=form.querySelector(`[data-assistant-field="${f}"]`).value, what=f==='vars'?'Vars':'The tracker';
|
||
if(text===asShown(entry,f))continue;
|
||
if(f==='definition'){patch.definition=text.trim();continue;}
|
||
if(f==='tracker'&&text.trim()===''){patch.tracker=null;continue;}
|
||
let parsed;try{parsed=JSON.parse(text);}catch{throw Error(`${what} must be JSON.`);}
|
||
if(!parsed||typeof parsed!=='object'||Array.isArray(parsed))throw Error(`${what} must be a JSON object.`);
|
||
patch[f]=parsed;
|
||
}
|
||
if(!Object.keys(patch).length)throw Error('Nothing changed.');
|
||
return {revision:settingsSnapshot.revision,assistants:{[instance]:patch}};
|
||
}
|
||
const unknownAssistant='Outcome unknown. Read current settings before trying again. Draft kept.';
|
||
async function assistantPost(url,payload,instance,ok,kind='tester'){
|
||
if(kind==='tester')assistantBusy=true;else assistantFormsBusy.add(assistantKey(instance,kind));assistantReceiptKinds[instance]=kind;assistantReceipts[instance]='';if(kind!=='tester')assistantCardReceipts[assistantKey(instance,kind)]='';render(false);const epoch=orgEpoch;
|
||
try{const response=await fetch(url,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(epoch!==orgEpoch){if(response.type==='opaqueredirect')signOut();return;}if(response.type==='opaqueredirect'){assistantReceipts[instance]='Sign in again. Draft kept.';signOut();}else{const result=await response.json();if(epoch!==orgEpoch)return;assistantReceiptKinds[instance]=kind;assistantReceipts[instance]=response.ok?ok(result):result?.sent==='unknown'?unknownAssistant:`${result?.message||'Refused.'} Draft kept.`;}}
|
||
catch{if(epoch!==orgEpoch)return;assistantReceiptKinds[instance]=kind;assistantReceipts[instance]=unknownAssistant;}finally{if(epoch===orgEpoch){if(kind==='tester')assistantBusy=false;else{assistantCardReceipts[assistantKey(instance,kind)]=assistantReceipts[instance];assistantFormsBusy.delete(assistantKey(instance,kind));}if(!out())render(false);}}
|
||
}
|
||
const assistantForm=el=>el?.closest?.('.assistant-form');
|
||
for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=assistantForm(e.target);if(!form)return;const instance=form.dataset.instance,field=e.target.dataset.assistantField;if(field==='name')nameDrafts[instance]=e.target.value;else if(field)assistantDrafts[instance]={...Object.fromEntries(['definition','vars','tracker'].map(f=>[f,form.querySelector(`[data-assistant-field="${f}"]`).value]))};if(field){markSettingsDraft('assistant',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=form.querySelector('[data-assistant-discard]');if(discard)discard.hidden=false;}});
|
||
document.addEventListener('keydown',e=>{if(e.key==='Enter' && e.target.matches?.('[data-assistant-field=name]')){e.preventDefault();e.target.closest('.assistant-form')?.querySelector('[data-assistant-name]')?.click();}});
|
||
document.addEventListener('submit',async e=>{
|
||
const form=assistantForm(e.target);if(!form||e.target!==form)return;e.preventDefault();if(!canSend||out())return;const instance=form.dataset.instance;if(assistantFormsBusy.has(assistantKey(instance,'settings')))return;let payload;
|
||
try{payload=assistantPayload(instance,form);}catch(err){assistantReceiptKinds[instance]='settings';assistantReceipts[instance]=err.message;assistantCardReceipts[assistantKey(instance,'settings')]=err.message;render(false);return;}
|
||
await assistantPost('/api/settings',payload,instance,result=>{if(!/^[a-f0-9]{64}$/.test(result?.revision??''))return unknownAssistant;delete assistantDrafts[instance];settingsSnapshot=result;const prior=last.get('api:settings');if(prior)last.set('api:settings',{...prior,launch:result});return 'Assistant settings saved.';},'settings');
|
||
});
|
||
document.addEventListener('click',async e=>{
|
||
const form=assistantForm(e.target);if(!form||!canSend||out())return;const instance=form.dataset.instance;
|
||
if(e.target.dataset.assistantDiscard!==undefined){delete assistantDrafts[instance];delete nameDrafts[instance];delete assistantReceipts[instance];delete assistantCardReceipts[assistantKey(instance,'name')];delete assistantCardReceipts[assistantKey(instance,'settings')];settingsSnapshot=null;last.delete('api:settings');render(true);return;}
|
||
if(e.target.dataset.assistantName!==undefined){if(assistantFormsBusy.has(assistantKey(instance,'name')))return;const name=form.querySelector('[data-assistant-field="name"]').value.trim();
|
||
await assistantPost('/api/name',{instance,name},instance,result=>{if(typeof result?.name!=='string')return unknownAssistant;delete nameDrafts[instance];const prior=last.get('names');if(prior)last.set('names',{...prior,rows:[...prior.rows.filter(r=>r.instance!==result.instance),{instance:result.instance,name:result.name,at:result.at}]});return `Seat name set to ${result.name}.`;},'name');}
|
||
else if(e.target.dataset.assistantStop!==undefined&&!assistantFormsBusy.has(assistantKey(instance,'stop')))await assistantPost('/api/assistant-stop',{instance},instance,result=>Array.isArray(result?.stopped)?`Stopped ${plural(result.stopped.length,'run')}.`:unknownAssistant,'stop');
|
||
});
|
||
// Row 165 (#1662, Q171): role instances. Add one, or change one's definition, vars and launch
|
||
// membership, with the read's revision. A definition that declares credentials is named but not
|
||
// offered: binding credentials stays a hand edit. When a change needs a bus restart the receipt
|
||
// says so; the Console never restarts the bus. Drafts survive polling and refusals; nothing retries.
|
||
let instanceView=null, instanceDrafts={add:null,change:null}, instanceBusyOps=new Set(), instanceReceipt='', instanceReceiptOp=null, instanceReceipts=Object.create(null);
|
||
// F3: an organization Console's owner restarts the bus from the receipt (console-restart.js).
|
||
const restartText=()=>window.MosaicConsole?.busRestart?'Restart needed: the running bus keeps the roles it loaded at start. Restart the bus to load the change.':'Restart needed: the running bus keeps the roles it loaded at start. The Console does not restart it.';
|
||
const NO_RESTART_TEXT='No restart: the launcher reads the change at its next launch check.';
|
||
function instancesSection(view){
|
||
const title='<h2 id="instances-title">Role instances</h2>';
|
||
if(!view)return `<section class="panel" aria-labelledby="instances-title">${title}<p class="small warn">The role instances could not be read, so there is nothing to add or change. Read again to retry; they come from the bus host with your identity.</p></section>`;
|
||
if(!instanceDrafts.add&&!instanceDrafts.change)instanceView=view;
|
||
const v=instanceView, disabled=!(canSend || isTester)||out()||instanceBusyOps.size?' disabled':'';
|
||
const defs=Object.entries(v.definitions), accepted=defs.filter(([,d])=>d.accepted).map(([n])=>n);
|
||
const bound=defs.filter(([,d])=>Array.isArray(d.services)&&d.services.length).map(([n,d])=>`${txt(n)} (${d.services.map(txt).join(', ')})`);
|
||
const changeable=Object.entries(v.instances).filter(([,e])=>!e.protected).map(([n])=>n);
|
||
const rows=Object.entries(v.instances).map(([name,e])=>`<tr><th scope="row">${txt(name)}</th><td>${txt(e.definition)}</td><td>${e.launcher?'launcher':e.launched?'yes':'no'}</td><td>${e.vars&&Object.keys(e.vars).length?`<code>${txt(JSON.stringify(e.vars))}</code>`:'<span class="muted">none</span>'}</td></tr>`).join('');
|
||
const opts=(list,sel,keep)=>`${keep?`<option value="">${keep}</option>`:''}${list.map(n=>`<option value="${esc(n)}"${n===sel?' selected':''}>${txt(n)}</option>`).join('')}`;
|
||
const a=instanceDrafts.add||{}, c=instanceDrafts.change||{};
|
||
const addLaunch=v.launch?`<label><input type="checkbox" data-instance-field="launch"${a.launch?' checked':''}${disabled}> Launch it</label>`:'';
|
||
const changeLaunch=v.launch?`<label>Launch <select data-instance-field="launch"${disabled}>${[['','Keep'],['yes','Launch it'],['no','Don\'t launch it']].map(([x,l])=>`<option value="${x}"${(c.launch??'')===x?' selected':''}>${l}</option>`).join('')}</select></label>`:'';
|
||
const addForm=`<form id="instance-add-form" class="instance-form" data-op="add"><fieldset><legend>Add an instance</legend><div class="filters"><label>Instance <input data-instance-field="instance" value="${esc(a.instance??'')}" maxlength="64"${disabled}></label><label>Definition <select data-instance-field="definition"${disabled}>${opts(accepted,a.definition)}</select></label>${addLaunch}</div><label>Vars (JSON, empty for none) <textarea data-instance-field="vars" rows="3"${disabled}>${esc(a.vars??'')}</textarea></label><button type="submit"${disabled}>Add instance</button></fieldset></form>`;
|
||
const changeForm=changeable.length?`<form id="instance-change-form" class="instance-form" data-op="change"><fieldset><legend>Change an instance</legend><div class="filters"><label>Instance <select data-instance-field="instance"${disabled}>${opts(changeable,c.instance)}</select></label><label>Definition <select data-instance-field="definition"${disabled}>${opts(accepted,c.definition,'Keep the definition')}</select></label>${changeLaunch}</div><label>Vars (JSON, replaces them whole; empty keeps them) <textarea data-instance-field="vars" rows="3"${disabled}>${esc(c.vars??'')}</textarea></label><button type="submit"${disabled}>Save instance</button></fieldset></form>`:'';
|
||
return `<section class="panel" aria-labelledby="instances-title">${title}<p>Add an instance or change one's definition, vars and launch membership. Holder, credentials and tracker stay hand edits, and so does an instance of a definition that declares credentials. An assistant changes in the Assistant section.</p><div class="table-wrap" tabindex="0" role="region" aria-label="Role instances, scroll for all columns"><table id="instances-table"><thead><tr><th scope="col">Instance</th><th scope="col">Definition</th><th scope="col">Launched</th><th scope="col">Vars</th></tr></thead><tbody>${rows}</tbody></table></div>${addForm}${changeForm}${bound.length?`<p class="small muted">Definitions that declare credentials, a hand edit: ${bound.join(', ')}.</p>`:''}<p class="small muted">${canSend || isTester?'Changes are checked and logged with your identity.':'Changes require signed-in send mode.'}</p><button type="button" id="instances-reload">Read current instances and discard drafts</button><p role="status" id="instances-receipt">${txt(instanceReceipt)}</p></section>`;
|
||
}
|
||
const instanceFields=form=>Object.fromEntries([...form.querySelectorAll('[data-instance-field]')].map(el=>[el.dataset.instanceField,el.type==='checkbox'?el.checked:el.value]));
|
||
function instancePayload(op,f){
|
||
const payload={revision:instanceView.revision,instance:String(f.instance??'').trim(),op};
|
||
if(!payload.instance)throw Error('Name the instance.');
|
||
if(f.definition)payload.definition=f.definition;
|
||
if(op==='add'&&!payload.definition)throw Error('Choose a definition.');
|
||
if(String(f.vars??'').trim()!==''){let parsed;try{parsed=JSON.parse(f.vars);}catch{throw Error('Vars must be JSON.');}if(!parsed||typeof parsed!=='object'||Array.isArray(parsed))throw Error('Vars must be a JSON object.');payload.vars=parsed;}
|
||
if(op==='add'&&f.launch===true)payload.launch=true;
|
||
if(op==='change'&&(f.launch==='yes'||f.launch==='no'))payload.launch=f.launch==='yes';
|
||
if(op==='change'&&!['definition','vars','launch'].some(k=>Object.hasOwn(payload,k)))throw Error('Nothing changed.');
|
||
return payload;
|
||
}
|
||
const unknownInstance='Outcome unknown. Read the role instances again before trying. Draft kept.';
|
||
// The answer replaces the view the next render draws, so it must have the read's whole shape.
|
||
const instanceAnswer=r=>/^[a-f0-9]{64}$/.test(r?.revision??'')&&typeof r.restart==='boolean'&&[r.instances,r.definitions].every(o=>o&&typeof o==='object'&&!Array.isArray(o));
|
||
// #1873 A2: the level forms keep their own drafts (agents.js); here they only mark the nav.
|
||
for(const kind of ['input','change'])document.addEventListener(kind,e=>{if(e.target?.closest?.('.level-form'))markSettingsDraft('agents',!!window.MosaicAgentLevels?.hasDraft());});
|
||
for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=e.target?.closest?.('.instance-form');if(form){instanceDrafts[form.dataset.op]=instanceFields(form);markSettingsDraft('agents',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=form.querySelector('[data-instance-discard]');if(discard)discard.hidden=false;}});
|
||
document.addEventListener('click',e=>{if(e.target.id!=='instances-reload' && e.target.dataset?.instanceDiscard===undefined)return;instanceDrafts={add:null,change:null};instanceView=null;instanceReceipt='';instanceReceipts=Object.create(null);instanceReceiptOp=null;last.delete('instances');render(true);});
|
||
document.addEventListener('submit',async e=>{
|
||
const form=e.target?.closest?.('.instance-form');if(!form||e.target!==form)return;e.preventDefault();if(!(canSend || isTester)||out()||!instanceView)return;
|
||
const op=form.dataset.op;if(instanceBusyOps.has(op))return;instanceReceiptOp=op;instanceDrafts[op]=instanceFields(form);let payload;
|
||
try{payload=instancePayload(op,instanceDrafts[op]);}catch(err){instanceReceipt=err.message;instanceReceipts[op]=instanceReceipt;render(false);return;}
|
||
instanceBusyOps.add(op);instanceReceipt='';instanceReceipts[op]='';render(false);const epoch=orgEpoch;
|
||
try{const response=await fetch('/api/instances',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(epoch!==orgEpoch){if(response.type==='opaqueredirect')signOut();return;}if(response.type==='opaqueredirect'){instanceReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json();if(epoch!==orgEpoch)return;
|
||
if(response.ok&&instanceAnswer(result)){instanceDrafts[op]=null;instanceView=result;const prior=last.get('instances');if(prior)last.set('instances',{...prior,rows:[result]});instanceReceipt=`${op==='add'?'Added':'Changed'} ${payload.instance}. ${result.restart?restartText():NO_RESTART_TEXT}`;}
|
||
else instanceReceipt=response.ok||result?.sent==='unknown'?unknownInstance:`${result?.message||'Refused.'} Draft kept.`;}}
|
||
catch{if(epoch!==orgEpoch)return;instanceReceipt=unknownInstance;}finally{if(epoch===orgEpoch){instanceBusyOps.delete(op);instanceReceiptOp=op;instanceReceipts[op]=instanceReceipt;if(!out())render(false);}}
|
||
});
|
||
// Row 65 (mos-0840): the routing table. One row per instance: harness, model and thinking, and
|
||
// the fallback's three. Each cell offers the switched-on harnesses, the model table's keys and the
|
||
// levels that harness applies; a value the file holds that isn't offered stays, marked, so a save
|
||
// sends it and the bus says why it refuses. A fallback is set by choosing all three or cleared by
|
||
// choosing none for all three. Save sends the changed rows through routes.set. Drafts survive
|
||
// polling and refusals; nothing retries.
|
||
let routesView=null, routesDraft=null, routesBusy=false, routesReceipt='', routesEditVersion=0;
|
||
// F3: after a save, how the change reaches each saved agent: a session keeps the route it started
|
||
// with, so a running one moves when it ends (a thread when it goes idle) or when the owner
|
||
// restarts it here (agents.js restartMarkup). Read from the instances after the save.
|
||
let routesApply=null;
|
||
async function routesApplyRead(names){
|
||
let view=null;
|
||
try{const res=await fetch('/api/bus/instances',{cache:'no-store',redirect:'manual'});if(res.ok&&res.type!=='opaqueredirect')view=(await res.json())?.rows?.[0]??null;}catch{/* said below */}
|
||
return names.map(name=>{const e=view?.instances?.[name];
|
||
if(!view||!e)return {name,text:'Could not read whether it is running. A running session keeps its old route until it ends.'};
|
||
const running=Array.isArray(e.running)?e.running.length:0, thread=!!window.MosaicAgents?.isThread(e.definition);
|
||
if(e.launcher)return {name,text:'The launcher. It takes the new route at its next start.'};
|
||
if(!running)return {name,text:'Not running. Its next start uses the new route.'};
|
||
return {name,thread,restart:true,text:thread?'Running. Its session keeps the old route until the thread goes idle; the next message after that starts it on the new route. Restart it to move it now.':'Running. Its session keeps the old route until it ends. Restart it to move it now.'};});
|
||
}
|
||
const routesApplyMarkup=()=>routesApply?.length?`<ul class="routes-apply" aria-label="How the change reaches each agent">${routesApply.map(a=>`<li><b>${txt(a.name)}</b>: ${txt(a.text)}${a.restart&&canSend&&!isTester?` ${window.MosaicAgents?.restartMarkup(a.name,a.thread)??''}`:''}</li>`).join('')}</ul>`:'';
|
||
let harnessSettings=null, harnessDraft=null, harnessLoading=false, harnessReceipt='', harnessBusy=false;
|
||
function readHarnesses(){
|
||
if(harnessLoading || harnessSettings !== null || !canSend || isTester)return; harnessLoading=true;const epoch=orgEpoch;
|
||
fetch('/api/proxy/plugins',{cache:'no-store',redirect:'manual'}).then(async r=>{const v=await r.json();if(epoch!==orgEpoch)return;if(!r.ok || !/^[a-f0-9]{64}$/.test(v.revision??'') || !Array.isArray(v.available?.harness) || !v.available.harness.every(n=>typeof n==='string') || !Array.isArray(v.plugins?.harness??[]))throw Error();harnessSettings=v;}).catch(()=>{if(epoch!==orgEpoch)return;harnessSettings=false;harnessReceipt='Harnesses could not be read.';}).finally(()=>{if(epoch!==orgEpoch)return;harnessLoading=false;if(routeOf().split('?')[0]==='/settings/routing')render(false);});
|
||
}
|
||
const ROUTE_CELLS=[['harness','Harness'],['model','Model'],['thinking','Thinking'],['fallback.harness','Fallback harness'],['fallback.model','Fallback model'],['fallback.thinking','Fallback thinking']];
|
||
const routeCells=r=>({harness:r.harness??'',model:r.model??'',thinking:r.thinking??'','fallback.harness':r.fallback?.harness??'','fallback.model':r.fallback?.model??'','fallback.thinking':r.fallback?.thinking??''});
|
||
const sameCells=(a,b)=>ROUTE_CELLS.every(([k])=>a[k]===b[k]);
|
||
function routesSection(view,instanceInfo){
|
||
const title='<h2 id="routes-title">Routing</h2>';
|
||
readHarnesses();
|
||
if(!view)return `<section class="panel" aria-labelledby="routes-title">${title}<p class="small warn">The routes could not be read, so there is nothing to change. Read again to retry; they come from the bus host with your identity.</p></section>`;
|
||
// A harness or catalogue save clears routesView; a draft made while it was in flight keeps its
|
||
// cells over the fresh read.
|
||
if(!routesDraft||!routesView)routesView=view;
|
||
const v=routesView, disabled=!(canSend || isTester)||out()||routesBusy?' disabled':'';
|
||
const cells=name=>routesDraft?.[name]??routeCells(v.instances[name]);
|
||
const select=(name,key,list,current,why,labels={})=>{const offered=current===''||list.includes(current)?list:[...list,current];
|
||
return `<select data-route="${esc(inputKey([name,key]))}" aria-label="${esc(`${name} ${ROUTE_CELLS.find(([k])=>k===key)[1].toLowerCase()}`)}"${disabled}>${key.startsWith('fallback.')||current===''?`<option value=""${current===''?' selected':''}>${key.startsWith('fallback.')?'None':'unset'}</option>`:''}${offered.map(x=>`<option value="${esc(x)}"${x===current?' selected':''}>${txt(labels[x]??x)}${list.includes(x)?'':` (${why})`}</option>`).join('')}</select>`;};
|
||
const levelsOf=h=>Array.isArray(v.levels[h])?v.levels[h]:[];
|
||
const rows=Object.keys(v.instances).map(name=>{const c=cells(name);
|
||
const harness=(key)=>select(name,key,v.harnesses,c[key],'not switched on');
|
||
const model=(key)=>{const h=key.startsWith('fallback.')?c['fallback.harness']:c.harness;
|
||
const entries=Array.isArray(v.catalogue?.models)?v.catalogue.models:[];
|
||
const offered=entries.filter(m=>m.available&&m.harnesses?.includes(h)&&(!v.models.includes(m.key)||v.providerModels?.[m.key]?.module===m.module));
|
||
const enabled=['ready','unavailable'].includes(v.catalogue?.status);
|
||
const legacy=v.models.filter(k=>{if(v.providerModels?.[k])return false;if(!enabled)return true;const mapping=v.catalogue?.legacy?.[k];return mapping&&entries.some(m=>m.module===mapping.module&&m.upstream===mapping.upstream&&m.model===mapping.model&&m.available&&m.harnesses?.includes(h));});
|
||
const labels=Object.fromEntries(offered.map(m=>[m.key,`${m.label}${m.reason==='unverified'?' (unverified)':''}`]));
|
||
return select(name,key,[...new Set([...legacy,...offered.map(m=>m.key)])],c[key],(v.providerModels?.[c[key]]||enabled&&v.models.includes(c[key]))?'unavailable':'not in the model table',labels);};
|
||
const thinking=(key,h)=>select(name,key,levelsOf(c[h]),c[key],c[h]?`not applied by ${c[h]}`:'no harness');
|
||
return `<tr class="route-row${['fallback.harness','fallback.model','fallback.thinking'].some(k=>c[k])?' fallback-open':''}"><th scope="row">${txt(name)}${instanceInfo?.instances?.[name]?.definition?`<small class="route-definition">${txt(instanceInfo.instances[name].definition)}</small>`:''}</th><td data-label="Harness">${harness('harness')}</td><td data-label="Model">${model('model')}</td><td data-label="Thinking">${thinking('thinking','harness')}</td><td class="fallback-cell" data-label="Fallback harness"><button type="button" class="fallback-toggle">Set fallback</button>${harness('fallback.harness')}</td><td class="fallback-cell" data-label="Fallback model">${model('fallback.model')}</td><td class="fallback-cell" data-label="Fallback thinking">${thinking('fallback.thinking','fallback.harness')}</td></tr>`;}).join('');
|
||
// D3 (P0-4): the switch adds or removes the cliproxy module only, so its label follows that
|
||
// module in the organization's model-provider list, not the whole catalogue's status (a
|
||
// fixture-only catalogue is ready with no model proxy). Before the setting is read it falls
|
||
// back to the catalogue status, as before.
|
||
const proxyOn=harnessSettings?(Array.isArray(harnessSettings.plugins?.['model-provider'])?harnessSettings.plugins['model-provider']:[]).includes('cliproxy'):v.catalogue?.status!=='disabled';
|
||
const catalogueInfo=v.catalogue?.status==='ready'?`<p class="small muted">Model catalogue, observed ${txt(window.MosaicLocalTime(v.catalogue.observedAt))}.</p>${(v.catalogue.notices??[]).map(n=>`<p class="small warn">${txt(n)}</p>`).join('')}`:v.catalogue?.status==='unavailable'?`<p class="small warn">Model catalogue unavailable. A change to thinking alone still saves.${proxyOn&&canSend&&!isTester?' A new model needs the catalogue: set up the model proxy, or, when this organization has none, press Disable model proxy catalogue.':''}</p>`:'<p class="small muted">Model catalogue not enabled.</p>';
|
||
const providerControl=canSend&&!isTester?`<button type="button" id="provider-switch" data-enabled="${proxyOn}">${proxyOn?'Disable':'Enable'} model proxy catalogue</button><p role="status" id="provider-switch-status"></p>`:'';
|
||
const harnessControl=canSend&&!isTester?`<fieldset class="harness-control"><legend>Harnesses</legend>${harnessSettings ? [...new Set([...harnessSettings.available.harness,...(harnessSettings.plugins.harness??[])])].map(name=>`<label><input type="checkbox" data-harness="${esc(name)}"${(harnessDraft??harnessSettings.plugins.harness??[]).includes(name)?' checked':''}${harnessBusy?' disabled':''}> ${txt(name)}</label>`).join('')+` <button type="button" id="harness-save"${harnessBusy?' disabled':''}>Save harnesses</button>` : '<p>Harnesses unavailable.</p><button type="button" id="harness-read">Read harnesses again</button>'}<p role="status" id="harness-status">${txt(harnessReceipt)}</p></fieldset>`:'';
|
||
const off=v.harnesses.length?'':'<p class="small warn">No harness is switched on in the business file\'s plugins.harness, so every launch refuses harness-off and a save that changes a harness refuses too. Switch one on under Harnesses.</p>';
|
||
return `<section class="panel routing-panel" aria-labelledby="routes-title"><span class="sr-only">${title}</span>${catalogueInfo}${providerControl}${harnessControl}${off}<form id="routes-form"><div class="table-wrap" tabindex="0" role="region" aria-label="Routes, scroll for all columns"><table id="routes-table"><thead><tr><th scope="col" rowspan="2">Agent</th><th scope="colgroup" colspan="3">Primary</th><th scope="colgroup" colspan="3">Fallback</th></tr><tr>${ROUTE_CELLS.map(([,l])=>`<th scope="col">${l.replace('Fallback ','')}</th>`).join('')}</tr></thead><tbody>${rows}</tbody></table></div><p class="small muted">${canSend || isTester?'Changes are checked and logged with your identity.':'Saving requires signed-in send mode.'}</p><div class="settings-actions route-actions${routesDraft?' has-draft':''}"><button type="submit"${disabled}>${routesBusy?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Save routes'}</button> <button type="button" id="routes-reload"${routesDraft?'':' hidden'}${routesBusy||!routesDraft?' disabled':''}>Discard draft</button><p role="status" id="routes-receipt" class="${routesReceipt.startsWith('Outcome unknown')?'banner ref':routesReceipt.includes('Draft kept')?'banner err':routesReceipt.includes('saved')?'settings-success':''}">${txt(routesReceipt)}</p></div>${routesApplyMarkup()}</form></section>`;
|
||
}
|
||
function routesFields(form){const draft=Object.fromEntries(Object.keys(routesView.instances).map(name=>[name,routeCells(routesView.instances[name])]));for(const el of form.querySelectorAll('[data-route]')){const [name,key]=JSON.parse(el.dataset.route);if(draft[name])draft[name][key]=el.value;}return draft;}
|
||
// The changed rows only. A fallback with all three cells empty is cleared; one with some set goes
|
||
// as it is, and the bus refuses it as partial.
|
||
function routesPayload(draft){
|
||
const routes={};
|
||
for(const [name,c]of Object.entries(draft)){if(sameCells(c,routeCells(routesView.instances[name])))continue;
|
||
const set=['harness','model','thinking'].filter(k=>c[`fallback.${k}`]!=='');
|
||
routes[name]={harness:c.harness,model:c.model,thinking:c.thinking,fallback:set.length===0?null:Object.fromEntries(set.map(k=>[k,c[`fallback.${k}`]]))};}
|
||
if(!Object.keys(routes).length)throw Error('Nothing changed.');
|
||
return {revision:routesView.revision,routes};
|
||
}
|
||
const unknownRoutes='Outcome unknown. Read the routes again before trying. Draft kept.';
|
||
// D3 (P0-4): after a catalogue refusal, Disable is named only when it can make this save apply:
|
||
// cliproxy is listed and every model the change moves to comes from another listed module.
|
||
// A viewer without the switch is sent to the owner.
|
||
function catalogueStep(code,routes){
|
||
if(!['model-catalogue-unavailable','model-provider-unavailable'].includes(code))return '';
|
||
if(!canSend||isTester)return ' Ask the organization\'s owner to set up the model proxy, or to disable the model proxy catalogue when the change needs no proxy.';
|
||
const names=Array.isArray(harnessSettings?.plugins?.['model-provider'])?harnessSettings.plugins['model-provider']:[];
|
||
if(!names.includes('cliproxy'))return '';
|
||
const moved=Object.entries(routes).flatMap(([name,r])=>{const was=routesView?.instances?.[name]??{};
|
||
return [[r.harness,r.model,was.harness,was.model],[r.fallback?.harness,r.fallback?.model,was.fallback?.harness,was.fallback?.model]].filter(([h,m,wh,wm])=>m&&(h!==wh||m!==wm)).map(([,m])=>m);});
|
||
const module=key=>routesView?.providerModels?.[key]?.module;
|
||
return moved.length&&moved.every(key=>module(key)&&module(key)!=='cliproxy'&&names.includes(module(key)))?' This change needs no model proxy: press Disable model proxy catalogue, then save again.':'';
|
||
}
|
||
const routesAnswer=r=>/^[a-f0-9]{64}$/.test(r?.revision??'')&&Array.isArray(r.harnesses)&&Array.isArray(r.models)&&[r.levels,r.instances].every(o=>o&&typeof o==='object'&&!Array.isArray(o));
|
||
for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=e.target?.closest?.('#routes-form');if(!form||!routesView)return;routesDraft=routesFields(form);routesEditVersion++;markSettingsDraft('routing',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=$('routes-reload');if(discard){discard.hidden=false;discard.disabled=false;}
|
||
// A harness change redraws the row so its thinking cell offers that harness's levels.
|
||
if(kind==='change'&&/harness"\]$/.test(e.target.dataset?.route??''))render(false);});
|
||
document.addEventListener('click',e=>{if(e.target.id==='harness-read'){harnessSettings=null;harnessReceipt='';render(false);}});
|
||
document.addEventListener('change',e=>{if(e.target.matches?.('[data-harness]'))harnessDraft=[...document.querySelectorAll('[data-harness]:checked')].map(x=>x.dataset.harness);});
|
||
document.addEventListener('click',async e=>{if(e.target.id!=='harness-save'||!canSend||isTester||harnessBusy||!harnessSettings)return;
|
||
const selected=[...document.querySelectorAll('[data-harness]:checked')].map(x=>x.dataset.harness);
|
||
const old=harnessSettings.plugins.harness??[];
|
||
if(routesDraft){harnessReceipt='Save or discard the route draft first.';render(false);return;}
|
||
if(harnessSettings.revision!==routesView?.revision){harnessReceipt='The business changed. Reload this page before saving harnesses.';render(false);return;}
|
||
const used=old.filter(n=>!selected.includes(n) && Object.values(routesView.instances).some(r=>r.harness===n || r.fallback?.harness===n));
|
||
if(used.length){harnessReceipt=`A saved route uses ${used.join(', ')}. Change the route before switching it off.`;render(false);return;}
|
||
harnessBusy=true;const button=e.target;button.disabled=true;harnessReceipt='';const epoch=orgEpoch;
|
||
try{const response=await fetch('/api/proxy/plugins/set',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision:harnessSettings.revision,plugins:{harness:selected}}),cache:'no-store',redirect:'manual'});const result=await response.json();if(epoch!==orgEpoch)return;if(!response.ok){harnessReceipt=result.message||result.error||'Harness setting was refused.';return;}harnessSettings={...result,available:harnessSettings.available};harnessDraft=null;harnessReceipt='Harnesses saved. The next launch uses the new settings.';routesView=null;last.delete('routes');}
|
||
catch{if(epoch!==orgEpoch)return;harnessReceipt='Outcome unknown. Read the harnesses again before trying.';harnessSettings=false;}
|
||
finally{if(epoch===orgEpoch){harnessBusy=false;if(!out())render(false);}}
|
||
});
|
||
document.addEventListener('click',async e=>{if(e.target.id!=='provider-switch'||!canSend||isTester)return;
|
||
const button=e.target,status=$('provider-switch-status');if(routesDraft){status.textContent='Save or discard the route draft first.';return;}button.disabled=true;const epoch=orgEpoch;
|
||
try {const read=await fetch('/api/proxy/plugins',{cache:'no-store'});const settings=await read.json();if(epoch!==orgEpoch)return;if(!read.ok||!/^[a-f0-9]{64}$/.test(settings.revision??''))throw Error('Could not read provider settings.');
|
||
const names=Array.isArray(settings.plugins?.['model-provider'])?settings.plugins['model-provider']:[];
|
||
// The fresh read decides: a stale label never turns the proxy module on when it meant off.
|
||
const on=names.includes('cliproxy');if(String(on)!==button.dataset.enabled){button.dataset.enabled=String(on);button.textContent=`${on?'Disable':'Enable'} model proxy catalogue`;button.disabled=false;status.textContent='The switch now shows the current setting. Press it again to change it.';return;}
|
||
const next=on?names.filter(n=>n!=='cliproxy'):[...names,'cliproxy'];
|
||
const response=await fetch('/api/proxy/plugins/set',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision:settings.revision,plugins:{'model-provider':next}}),cache:'no-store',redirect:'manual'});
|
||
if(epoch!==orgEpoch)return;if(!response.ok)throw Error('Provider setting was refused.');harnessSettings=null;routesView=null;last.delete('routes');render(true);
|
||
}catch(error){if(epoch!==orgEpoch)return;status.textContent=error.message;button.disabled=false;}
|
||
});
|
||
document.addEventListener('click',e=>{if(e.target.matches?.('.fallback-toggle'))e.target.closest('tr')?.classList.add('fallback-open');});
|
||
document.addEventListener('click',e=>{if(e.target.id!=='routes-reload')return;routesDraft=null;routesView=null;routesReceipt='';routesApply=null;last.delete('routes');render(true);});
|
||
document.addEventListener('submit',async e=>{
|
||
if(e.target.id!=='routes-form')return;e.preventDefault();if(!(canSend || isTester)||out()||routesBusy||!routesView)return;
|
||
routesDraft=routesFields(e.target);let payload;try{payload=routesPayload(routesDraft);}catch(err){routesReceipt=err.message;render(false);return;}
|
||
routesBusy=true;routesReceipt='';routesApply=null;render(false);const epoch=orgEpoch;
|
||
try{const response=await fetch('/api/routes',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(epoch!==orgEpoch){if(response.type==='opaqueredirect')signOut();return;}if(response.type==='opaqueredirect'){routesReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json();if(epoch!==orgEpoch)return;
|
||
if(response.ok&&routesAnswer(result)){routesDraft=null;routesView=result;harnessSettings=null;const prior=last.get('routes');if(prior)last.set('routes',{...prior,rows:[result]});routesReceipt=`Routes saved for ${Object.keys(payload.routes).join(', ')}. The next launch of each uses the new route.`;const applied=await routesApplyRead(Object.keys(payload.routes));if(epoch!==orgEpoch)return;routesApply=applied;}
|
||
else routesReceipt=response.ok||result?.sent==='unknown'?unknownRoutes:`${result?.message||'Refused.'}${catalogueStep(result?.error,payload.routes)} Draft kept.`;}}
|
||
catch{if(epoch!==orgEpoch)return;routesReceipt=unknownRoutes;}finally{if(epoch===orgEpoch){routesBusy=false;if(!out())render(false);}}
|
||
});
|
||
// Row 194 (#1692, D7): the Agents section lives in agents.js (window.MosaicAgents) and draws from
|
||
// the same instances read. A refresh drops that read so the next render asks the bus again.
|
||
const agentsSection=view=>{ if(view&&!instanceDrafts.add&&!instanceDrafts.change)instanceView=view; return window.MosaicAgents?window.MosaicAgents.section(view,{txt,esc,canSend,isTester,out,signOut,instanceDrafts,instanceReceipt,instanceReceiptOp,instanceReceipts,instanceBusyOps:[...instanceBusyOps],render:()=>render(false),refresh:()=>{last.delete('instances');render(false);}}):''; };
|
||
// Tester management is deliberately separate from the human's assistant/settings forms.
|
||
function testerNames(names, instances) {
|
||
if (!instances || !names) return '';
|
||
const current = Object.fromEntries(names.map(row => [row.instance, row.name]));
|
||
return `<section class="panel" aria-labelledby="tester-names-title"><h2 id="tester-names-title">Seat names</h2>${Object.keys(instances.instances).map(instance => `<form class="tester-name-form" data-instance="${esc(instance)}"><label>${txt(instance)} <input name="name" maxlength="64" value="${esc(nameDrafts[instance] ?? current[instance] ?? '')}"${assistantBusy || out() ? ' disabled' : ''}></label><button type="submit"${assistantBusy || out() ? ' disabled' : ''}>Set name</button><p role="status">${txt(assistantReceipts[instance] ?? '')}</p></form>`).join('')}</section>`;
|
||
}
|
||
document.addEventListener('input', event => {
|
||
const form = event.target.closest?.('.tester-name-form');
|
||
if (form) nameDrafts[form.dataset.instance] = event.target.value;
|
||
});
|
||
document.addEventListener('submit', async event => {
|
||
const form = event.target.closest?.('.tester-name-form');
|
||
if (!form || event.target !== form) return;
|
||
event.preventDefault();
|
||
if (!isTester || assistantBusy || out()) return;
|
||
const instance = form.dataset.instance, name = form.elements.name.value.trim();
|
||
await assistantPost('/api/name', { instance, name }, instance, result => {
|
||
if (typeof result?.name !== 'string') return unknownAssistant;
|
||
delete nameDrafts[instance]; last.delete('names');
|
||
return `Seat name set to ${result.name}.`;
|
||
});
|
||
});
|
||
// Organizations is writable when the server allows org setup, which it does in organization mode where send is off.
|
||
const readonlyPage = page => !['appearance','business','console'].includes(page) && !(page === 'organizations' && orgSetup) && !canSend && !isTester;
|
||
const settingsPages = [['appearance','Appearance'],['business',window.MosaicOrg ? 'Organization' : 'Business'],['limits','Launch limits'],['organizations','Organizations'],['routing','Routing'],['agents','Agents'],['assistant','Assistant'],['tokens','Token use'],['model-proxy','Model proxy'],['console','Console'],['about','About']];
|
||
function markSettingsDraft(page,dirty){const link=document.querySelector(`#settings-nav a[href="#/settings/${page}"]`), dot='<span class="settings-dot"><span class="sr-only">unsaved changes</span></span>';if(link && dirty && !link.querySelector('.settings-dot'))link.insertAdjacentHTML('beforeend',dot);const button=$('settings-disclosure');if(dirty && link?.getAttribute('aria-current')==='page' && button && !button.querySelector('.settings-dot'))button.querySelector('strong').insertAdjacentHTML('beforeend',dot);}
|
||
function settingsShell(page, body, helper='') {
|
||
const pages=isTester ? [['appearance','Appearance'],['business','Business'],['routing','Routing'],['agents','Agents'],['names','Seat names']] : settingsPages;
|
||
const label=pages.find(([id])=>id===page)?.[1] || 'Appearance';
|
||
const isDirty=id=>(id==='routing'&&routesDraft)||(id==='limits'&&settingsInputs)||(id==='assistant'&&(Object.keys(assistantDrafts).length||Object.keys(nameDrafts).length))||(id==='agents'&&(instanceDrafts.add||instanceDrafts.change||window.MosaicAgentLevels?.hasDraft()));
|
||
const dot='<span class="settings-dot"><span class="sr-only">unsaved changes</span></span>';
|
||
const links=pages.map(([id,name],i)=>`${i===0?'<div class="settings-group">Your browser</div>':i===1?'<div class="settings-group">This instance</div>':''}<a href="#/settings/${id}"${id===page?' aria-current="page"':''}>${name}${isDirty(id)?dot:''}</a>`).join('') + (!isTester ? '<div class="settings-group">Members and invites <span class="muted">not built</span></div>' : '');
|
||
return `${head('Settings','Your browser and this instance.')}<div class="settings-layout"><div><button type="button" id="settings-disclosure" aria-expanded="false" aria-controls="settings-nav"><small>Section</small><strong>${label}${isDirty(page)?dot:''}</strong><span aria-hidden="true">⌄</span></button><nav id="settings-nav" aria-label="Settings sections">${links}</nav></div><div class="settings-content settings-${page}${readonlyPage(page)?' readonly':''}"><h2 id="settings-page-title" tabindex="-1">${label}</h2><p class="settings-helper">${helper}</p>${readonlyPage(page)?'<p class="settings-readonly">Read only. Saving requires signed-in send mode.</p>':''}${body}</div></div>`;
|
||
}
|
||
async function settingsView(get, page='appearance') {
|
||
if (page==='business') return businessView(get);
|
||
if (page==='appearance') return settingsShell(page,appearance(),'These choices apply in this browser only.');
|
||
if (page==='organizations') { await configRead; return settingsShell(page,window.MosaicOrgCreate.markup,'Create an organization from the template, edit it, and finish its setup. Each step names the command it equals.'); }
|
||
if (page==='model-proxy') { await configRead; return settingsShell(page,window.MosaicProxy.markup,'Accounts used by this instance, their priority, and the client keys assigned to agents.'); }
|
||
// F3: Settings > Console (console-restart.js). The server checks the owner, Origin and trail.
|
||
if (page==='console') { await configRead; await window.MosaicConsole?.ready; return settingsShell(page,window.MosaicConsole?.settingsMarkup()??'<section class="panel"><p class="small warn">The Console controls did not load. Reload the page to try again.</p></section>','Restart this Console on the same address and configuration.'); }
|
||
const s = await get.api('settings'), n = s.notifier || {};
|
||
let usage, names = null, instances = null, routes = null, limitRows = [], limitsRefused = false;
|
||
if (page==='tokens') { try { [usage] = await get('usage'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } try { limitRows = await get('limits'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; limitsRefused = true; } }
|
||
if (page==='assistant'||page==='names') { try { names = await get('names'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } }
|
||
if (page==='agents'||page==='names'||page==='routing') { try { [instances] = await get('instances'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } }
|
||
// #1873 A2: the root and project agent levels (agents.js MosaicAgentLevels), the owner's only.
|
||
let agentLevels='';
|
||
if (page==='agents' && window.MosaicOrg && window.MosaicAgentLevels && !isTester) agentLevels = await window.MosaicAgentLevels.section().catch(()=>'');
|
||
if (page==='routing') { try { [routes] = await get('routes'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } }
|
||
if (page==='tokens' && s.launch && !s.launch.refused) takeSnapshot(s.launch);
|
||
const notify = typeof n.binding==='string' ? `<code>${txt(n.binding)}</code>` : n.refused ? `Could not be read: <code>${txt(n.refused)}</code>` : '<span class="muted">None set</span>';
|
||
const contents={limits:()=>launchForm(s.launch),routing:()=>routesSection(routes,instances),agents:()=>agentsSection(instances)+agentLevels,assistant:()=>assistantSection(s.launch,names),tokens:()=>tokenLimits(limitRows,limitsRefused)+tokenUsage(usage),names:()=>testerNames(names,instances),about:()=>`<section class="panel"><dl class="kv"><dt>Address</dt><dd><code>${txt(s.address)||'unknown'}</code></dd><dt>Release</dt><dd>${txt(s.release)||'unknown'}</dd><dt>Business</dt><dd>${txt(s.business)||none}</dd><dt>Board</dt><dd><code>${txt(s.board)||'unknown'}</code></dd><dt>Notifier binding</dt><dd>${notify}</dd></dl></section>`, 'model-proxy':()=>'<section class="panel"><a href="#/settings/model-proxy">Open model proxy settings</a></section>'};
|
||
const helpers={limits:'Leave a limit blank for no limit. Zero stops new launches. Running sessions keep running when limits or models change.',routing:"Each agent’s harness, model and thinking, and the fallback a launch takes when the primary harness fails its preflight. A fallback sets all three or none. Running sessions keep their route. The next launch reads the change.",agents:'Each agent with its definition, launch membership and runs. A launch refuses until the agent has a route in Routing.',assistant:'The definition stays an assistant one. Holder and credentials stay hand edits.',tokens:'Token limits the bus checks, and token use read from session transcripts.'};
|
||
return settingsShell(page,contents[page](),`${get.oldest()?`Read ${when(get.oldest())}.`: 'Reading…'} ${helpers[page]||''}`);
|
||
}
|
||
let settingsFocusDisclosure=false;
|
||
document.addEventListener('change', e => { if (e.target.id === 'org-picker') window.MosaicOrg?.switchTo(e.target.value); });
|
||
document.addEventListener('click', e=>{const b=e.target.closest?.('#settings-disclosure');if(b){b.setAttribute('aria-expanded',String(b.getAttribute('aria-expanded')!=='true'));return;} if(e.target.closest?.('#settings-nav a')) { const b=$('settings-disclosure'); if(b?.getAttribute('aria-expanded')==='true') {b.setAttribute('aria-expanded','false');settingsFocusDisclosure=true;b.focus();} }});
|
||
document.addEventListener('keydown', e=>{if(e.key==='Escape' && $('settings-disclosure')?.getAttribute('aria-expanded')==='true'){e.preventDefault();$('settings-disclosure').setAttribute('aria-expanded','false');$('settings-disclosure').focus();}});
|
||
|
||
// Trail
|
||
const GROUPS = [['all', 'All'], ['request', 'Requests'], ['decision', 'Decisions'], ['launch', 'Launches'], ['task', 'Task changes'], ['review', 'Review']];
|
||
function trailList(rows, filter) {
|
||
const shown = filter === 'all' ? rows : rows.filter(r => r.group === filter);
|
||
if (!shown.length) return empty('Nothing of this kind in the trail.', 'Every step the stack takes on this subject writes a trail row.');
|
||
return `<ol class="s1-trail">${shown.map(r => `<li class="s1-trow s1-g-${esc(r.group)}"><span class="s1-twhen">${clock(r.at)}</span><span class="s1-tkind">${txt(r.kind)}</span><div class="s1-ttext"><p>${txt(r.text)}${r.decision && !r.kind.startsWith('decision.') && !r.kind.startsWith('delivery.') && SAFE.test(String(r.decision)) ? ` <a href="#/inbox/${enc(r.decision)}">decision ${txt(short(r.decision))}</a>` : ''}</p>${actor(r.actor, r.by)}${r.note ? `<span class="source">${esc(r.note)}</span>` : ''}</div></li>`).join('')}</ol>`;
|
||
}
|
||
async function trailView(get, kind, ref, q) {
|
||
let rows;
|
||
if (kind === 'task') {
|
||
const row = (await get('tasks')).find(r => r.task_ref === ref);
|
||
if (!row) return notFound(`No task ${txt(ref)} in this business.`);
|
||
rows = lines(await get('trail', ref), row.seq);
|
||
} else if (kind === 'message') {
|
||
// Row 76: a sent message's trail, its request event and deliveries. Replies are not in it.
|
||
const tr = await get('trail', ref);
|
||
if (!of(tr, 'messages').some(m => m.id === ref)) return notFound(`No message with id ${txt(ref)}.`);
|
||
rows = lines(tr);
|
||
} else {
|
||
const d = await decision(get, ref);
|
||
if (!d) return notFound(`No decision with id ${txt(ref)}.`);
|
||
// A decision's trail with its earlier versions, merged in the broker's order.
|
||
const all = new Map();
|
||
for (const x of [d, ...await chain(get, d)]) for (const r of x.trail) all.set(`${r.table}:${r.seq}`, r);
|
||
rows = lines([...all.values()].sort((a, b) => String(a.at).localeCompare(String(b.at)) || String(a.table).localeCompare(String(b.table)) || a.seq - b.seq));
|
||
}
|
||
const filter = GROUPS.some(([g]) => g === q.get('kind')) ? q.get('kind') : 'all';
|
||
const base = `#/trail/${kind}/${enc(ref)}`;
|
||
const name = kind === 'task' ? `Trail for task #${esc(String(ref).split('/')[1])}` : `Trail for ${kind} ${txt(short(ref))}`;
|
||
const back = kind === 'task' ? `<a href="#/tasks/${enc(ref)}">Back to the task</a>` : kind === 'message' ? '<a href="#/inbox">Back to the Inbox</a>' : `<a href="#/inbox/${enc(ref)}">Back to the decision</a>`;
|
||
return `${head(name, `${readNote(get)} Oldest first. ${back}`)}
|
||
<nav aria-label="Filter the trail" class="chips">${GROUPS.map(([g, l]) => `<a class="chip" href="${base}${g === 'all' ? '' : `?kind=${g}`}"${filter === g ? ' aria-current="true"' : ''}>${l} <span class="count">${g === 'all' ? rows.length : rows.filter(r => r.group === g).length}</span></a>`).join('')}</nav>
|
||
${trailList(rows, filter)}`;
|
||
}
|
||
|
||
// Row 148 (#1642, ruling sage-0507): the spec and docs editor. A textarea edits the Markdown source and
|
||
// a save writes exactly what is in it. The preview is markdown-preview.js: elements and text nodes,
|
||
// never markup, so nothing in a file runs. A draft lives in `docStates`, not the DOM, so a redraw, a
|
||
// failed save or a visit to another page loses nothing; only Reload discards it, and a file with no
|
||
// unsaved change is read again whenever it is opened. Each save names the commit the editor opened;
|
||
// a newer commit refuses it (`stale-base`) and nothing is written. An unknown outcome is never retried
|
||
// by the page. A textarea reads CRLF as LF, so the draft and the save are LF.
|
||
let canEdit = false, docKey = null;
|
||
const docStates = new Map();
|
||
// Row 154 (#1648, Q168): the visual editor (editor.js, window.MosaicEditor) edits the same draft text.
|
||
// Its view is destroyed whenever the page is redrawn, since it holds a document-level listener.
|
||
// docMode is the view asked for; docShown is the view on screen. They differ when a file opens as Source because
|
||
// the visual editor cannot write it back byte for byte, and a click on a button compares with what is on screen.
|
||
let docMode = 'visual', docShown = 'visual', editor = null;
|
||
function unmountEditor() { if (editor) { try { editor.api.destroy(); } catch { /* the page is being replaced */ } editor = null; } }
|
||
function mountEditor(s, host) {
|
||
unmountEditor();
|
||
try {
|
||
const api = window.MosaicEditor.mount(host, { text: s.text, editable: canEdit && !out(), onChange() { s.text = api.text(); s.status = ''; paintDoc(); } });
|
||
editor = { host, api };
|
||
} catch { host.textContent = 'The visual editor did not start. Use Source to edit this file. The draft is unchanged.'; }
|
||
}
|
||
const dirty = s => s.text !== s.original || s.saving;
|
||
const lf = v => String(v).replace(/\r\n?/g, '\n');
|
||
const DOC_PATH = /^(spec\/north-star\.md|docs\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.md)$/;
|
||
async function docsView(get) {
|
||
const projects = (await get.api('business')).business?.projects, names = Array.isArray(projects) ? projects.filter(p => typeof p === 'string' && SAFE.test(p)) : [];
|
||
const blocks = [];
|
||
for (const p of names) {
|
||
let files = [], code = null;
|
||
try { files = (await get.api(`project-files?project=${enc(p)}`)).files; }
|
||
catch (err) { if (err.code === 'signed-out' || refusal(err)) throw err; code = err.code; }
|
||
files = Array.isArray(files) ? files.filter(f => typeof f?.path === 'string' && DOC_PATH.test(f.path)) : [];
|
||
blocks.push(`<section class="panel" aria-labelledby="doc-p-${esc(p)}"><h2 id="doc-p-${esc(p)}">${txt(p)} <span class="count">${files.length}</span></h2>${code === 'project-records-missing' ? `<p>${window.MosaicRecords.markup(p)}</p>` : code ? `<p class="small warn">These files could not be read. Read again to retry. <code>${txt(code)}</code></p>${retry}` : files.length ? `<ul class="s1-plain">${files.map(f => `<li><a href="#/docs/${enc(p)}/${enc(f.path)}">${txt(f.path)}</a></li>`).join('')}</ul>` : '<p class="muted">No spec or docs files.</p>'}</section>`);
|
||
}
|
||
return `${head('Docs', `${readLine()} The spec and the files under docs/ of each project. ${canEdit ? 'Open one to edit it; a save makes one commit in the project with you as the author.' : 'Saving needs a Console started with <code>--send</code> behind the sign-in proxy; this one only reads.'}`)}
|
||
${blocks.join('') || empty('This business declares no projects.', 'A project shows here when the business file names it.')}`;
|
||
}
|
||
async function docView(get, project, file, { reuseDraft = false } = {}) {
|
||
if (!SAFE.test(project)) return notFound(`${txt(project)} is not a project name.`);
|
||
if (!DOC_PATH.test(file)) return notFound(`${txt(file)} is not a spec or docs file.`);
|
||
docKey = JSON.stringify([project, file]);
|
||
for (const [k, v] of docStates) if (k !== docKey && !dirty(v)) docStates.delete(k);
|
||
let s = docStates.get(docKey);
|
||
// A switch between Visual and Source passes reuseDraft: the draft, clean or not, is already the file as opened.
|
||
if (!s || (!dirty(s) && !reuseDraft)) {
|
||
const r = await get.api(`project-file?project=${enc(project)}&path=${enc(file)}`), now = docStates.get(docKey);
|
||
// Typing during the read wins over what was read.
|
||
s = now && dirty(now) ? now : { project, path: file, commit: r.commit, raw: r.content, original: lf(r.content), text: lf(r.content), status: '', saving: false, at: r.at };
|
||
docStates.set(docKey, s);
|
||
}
|
||
get.note(s.at);
|
||
const unsafe = s.raw.includes('\0'); // a textarea can't hold it, so a save would not write what was read
|
||
const stateNote = unsafe ? 'This file holds a NUL character, which the editor cannot keep. Edit it where it lives.'
|
||
: `${s.raw.includes('\r') ? 'This file uses CRLF line endings; a save writes LF. ' : ''}${canEdit ? '' : 'Saving needs a Console started with <code>--send</code> behind the sign-in proxy; this one only reads.'}`;
|
||
// Row 154 (#1648, Q168): the visual editor is the default view and Source is row 148's textarea. The visual
|
||
// editor opens a file only when it writes the text back byte for byte; otherwise this opens Source.
|
||
let visualOk = false;
|
||
if (docMode === 'visual' && !unsafe && window.MosaicEditor && window.MosaicMarkdown) { try { visualOk = window.MosaicEditor.roundTrip(s.text) === s.text; } catch { /* Source */ } }
|
||
docShown = visualOk ? 'visual' : 'source';
|
||
const modeNote = docMode === 'visual' && !visualOk && !unsafe ?'The visual editor is not available for this file, so it is open as source. ' : '';
|
||
const modes = `<div class="doc-mode" role="group" aria-label="Editor view"><button type="button" class="btn" id="doc-mode-visual" data-field="doc-mode-visual" aria-pressed="${visualOk}">Visual</button> <button type="button" class="btn" id="doc-mode-source" data-field="doc-mode-source" aria-pressed="${!visualOk}">Source</button></div>`;
|
||
const actions = `<button type="submit" id="doc-save" disabled>Save to the project</button> <button type="button" class="btn" id="doc-reload">Reload from the project and discard the draft</button>
|
||
<p role="status" id="doc-status">${txt(s.status)}</p>`;
|
||
const top = `${head(`Edit ${txt(s.path)}`, `Project ${txt(s.project)}, opened at commit <code id="doc-commit">${esc(s.commit.slice(0, 12))}</code>. ${readLine()}`)}
|
||
<p class="small"><a href="#/docs">All documents</a></p>${modes}`;
|
||
if (visualOk) return `${top}
|
||
<div class="doc-edit one"><section class="panel" aria-labelledby="doc-src-title"><h2 id="doc-src-title">Document</h2>
|
||
<p class="small muted">A save writes Markdown. A block you do not touch is saved exactly as it was; a block you edit is rewritten in a standard form. Source the editor does not draw (tables, HTML, front matter) shows as a tinted block you edit as text. A link shows its target when you select it; an image shows its address and is never loaded.</p>
|
||
<div id="doc-visual" class="doc-visual"></div>
|
||
<form id="doc-form"><p class="small muted">${stateNote}</p>
|
||
${actions}</form></section></div>`;
|
||
return `${top}
|
||
<div class="doc-edit"><section class="panel" aria-labelledby="doc-src-title"><h2 id="doc-src-title">Markdown source</h2>
|
||
<form id="doc-form"><label for="doc-text" class="sr-only">Markdown source of ${txt(s.path)}</label>
|
||
<textarea id="doc-text" class="doc-text" data-field="doc-text" rows="26" spellcheck="false" autocomplete="off" aria-describedby="doc-status"${canEdit && !unsafe && !out() ? '' : ' readonly'}>\n${unsafe ? '' : esc(s.text)}</textarea>
|
||
<p class="small muted">${modeNote}${stateNote}</p>
|
||
${actions}</form></section>
|
||
<section class="panel" aria-labelledby="doc-prev-title"><h2 id="doc-prev-title">Preview</h2><p class="small muted">Headings, lists, quotes, code and links are drawn. Raw HTML and anything else shows as text. A link shows where it goes; an image shows its address and is never loaded.</p><div id="doc-preview" class="md-preview"></div></section></div>`;
|
||
}
|
||
// The parts of the editor that follow the draft, set in place so typing never redraws the page.
|
||
function paintDoc() {
|
||
const s = docStates.get(docKey), box = $('doc-preview'), host = $('doc-visual');
|
||
if (!s || !(box || host)) return;
|
||
if (host && editor?.host !== host) mountEditor(s, host);
|
||
// A preview that throws must not skip the lines below, or leave a save stuck on "Saving…".
|
||
if (box) try {
|
||
if (window.MosaicMarkdown) box.replaceChildren(window.MosaicMarkdown.render(s.text));
|
||
else box.textContent = 'The preview did not load. The source is unchanged.';
|
||
} catch { box.textContent = 'The preview failed. The source is unchanged.'; }
|
||
const save = $('doc-save'), status = $('doc-status'), commit = $('doc-commit');
|
||
if (save) save.disabled = !saveable(s);
|
||
if (status) status.textContent = s.saving ? 'Saving…' : s.status;
|
||
if (commit) commit.textContent = s.commit.slice(0, 12);
|
||
}
|
||
const saveable = s => canEdit && !out() && !s.saving && s.text !== s.original && !s.raw.includes('\0');
|
||
document.addEventListener('input', e => { const s = docStates.get(docKey); if (e.target.id !== 'doc-text' || !s) return; s.text = e.target.value; s.status = ''; paintDoc(); });
|
||
document.addEventListener('click', e => {
|
||
const mode = { 'doc-mode-visual': 'visual', 'doc-mode-source': 'source' }[e.target.id], s = docStates.get(docKey);
|
||
if (!mode || !s || s.saving || mode === docShown) return;
|
||
docMode = mode; render(false, { reuseDraft: true });
|
||
});
|
||
document.addEventListener('click', e => { if (e.target.id !== 'doc-reload') return; const s = docStates.get(docKey); if (s?.saving) return; docStates.delete(docKey); render(true); });
|
||
document.addEventListener('submit', async e => {
|
||
if (e.target.id !== 'doc-form') return;
|
||
e.preventDefault();
|
||
const s = docStates.get(docKey);
|
||
if (!s || !saveable(s)) return;
|
||
const sent = { project: s.project, path: s.path, base: s.commit, content: s.text }, unknown = 'Outcome unknown: the save may have gone through. Copy your text, then reload the file to check before saving again. Draft kept.';
|
||
s.saving = true; s.status = '';
|
||
const epoch = orgEpoch;
|
||
let res = null, body = null;
|
||
try {
|
||
paintDoc();
|
||
try { res = await fetch('/api/project-file', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(sent), cache: 'no-store', redirect: 'manual' }); } catch { /* the outcome is unknown */ }
|
||
if (res && res.type !== 'opaqueredirect') { try { body = await res.json(); } catch { /* unknown */ } }
|
||
if (res?.type === 'opaqueredirect') s.status = 'Sign in again. Draft kept.';
|
||
else if (res?.ok && /^[0-9a-f]{40}$/.test(body?.commit ?? '') && body.path === s.path) {
|
||
s.commit = body.commit; s.original = sent.content; s.status = `Saved as commit ${body.commit.slice(0, 12)}.`;
|
||
} else if (body?.sent === false) s.status = `${typeof body.message === 'string' && body.message ? body.message : 'Not saved.'} Draft kept.`;
|
||
else s.status = unknown;
|
||
} finally { s.saving = false; } // a throw above must not leave Save off and Reload refused
|
||
// #1873 SP1: a switch while this was in flight cleared the drafts; the old file's outcome is not
|
||
// painted or announced on the new organization's page.
|
||
if (epoch !== orgEpoch) { if (res?.type === 'opaqueredirect') signOut(); return; }
|
||
paintDoc();
|
||
announce(s.status);
|
||
if (res?.type === 'opaqueredirect') signOut();
|
||
});
|
||
|
||
// Not found and states
|
||
function notFound(why) { return `${head('Not found')}<div class="empty nf"><b>${why || 'No page at this address.'}</b><p>Nothing is at <code>${txt(location.hash || '#/')}</code>. <a href="${window.MosaicOrg ? '#/dashboard' : '#/'}">Go to the ${window.MosaicOrg ? 'Dashboard' : 'Board'}</a> or press <kbd>Ctrl K</kbd> to search.</p></div>`; }
|
||
const loadingView = (source = null) => `${head('Reading…')}<div class="skel-rows" aria-busy="true"><span class="sr-only">${source ? `Reading the ${esc(source.toLowerCase())}.` : 'Reading from the bus.'}</span><span class="skel"></span><span class="skel"></span><span class="skel"></span><span class="skel"></span></div>`;
|
||
const retry = '<div class="actions"><button type="button" class="btn" data-retry>Read again</button></div>';
|
||
// Why a read failed, in words, with the bus code as given. Never a path or a guess.
|
||
function why(err, omitCode = false) {
|
||
if (err.code === 'tester-off' || err.code === 'tester-required') return 'The tester is off or this request did not bind the tester. Nothing was changed.';
|
||
const code = `<code>${txt(err.code)}</code>`;
|
||
// The queue, business and settings reads: the module's own text, redacted by the server.
|
||
if (err.module) {
|
||
const said = {
|
||
'queue-refused': 'The queue refused the read.',
|
||
'not-configured': 'Console could not load what this view reads.',
|
||
'no-bus-host': 'No bus host is running, and the Console was started without <code>--business</code>, so it knows no business. Start one with <code>mosaic bus start <business></code>.',
|
||
'read-failed': 'The read did not finish.',
|
||
'invalid-request': 'The Console server refused this address.',
|
||
unreachable: 'The Console server did not answer.',
|
||
}[err.code] || 'The read answered with something Console cannot use.';
|
||
return `${said}${omitCode ? '' : ` (${code})`}${err.code !== 'unreachable' && err.message ? `<br><span class="source">${txt(err.code === 'queue-refused' ? err.message.replace(/<path>/g, 'This checkout') : err.message)}</span>` : ''}`;
|
||
}
|
||
const say = {
|
||
'human-required': 'The bus answers the Console only when the human started it from their own shell. This Console was started inside an agent session, so the bus refused.',
|
||
unauthenticated: 'The bus did not accept this Console as the human.',
|
||
'unknown-business': 'The bus does not know this business.',
|
||
'read-only': 'The bus refused the read.',
|
||
'not-configured': 'This Console has no bus configured: the system config could not be read when it started. The control board still works.',
|
||
'no-bus-host': 'No bus host is running, and the Console was started without <code>--business</code>. Start one with <code>mosaic bus start <business></code>.',
|
||
'outcome-unknown': 'The bus did not answer in time.',
|
||
'invalid-request': 'The bus refused this address as a request.',
|
||
unreachable: 'The Console server did not answer.',
|
||
}[err.code] || 'The bus answered with something Console cannot use.';
|
||
return `${say}${omitCode ? '' : ` (${code})`}`;
|
||
}
|
||
const failTitle = err => err.code === 'queue-refused' ? 'Queue refused the read' : err.status === 403 ? 'Bus refused the read' : ['not-configured', 'no-bus-host'].includes(err.code) ? (err.module ? 'Nothing to read' : 'No bus to read') : 'The read failed';
|
||
// A refusal fails closed: no kept data, the code in mono. Any other failure keeps the last read, labelled with its time.
|
||
const refusal = err => err.status === 403 || ['not-configured', 'no-bus-host', 'queue-refused'].includes(err.code);
|
||
// After a refusal nothing read before is shown anywhere: not in a view, the palette or the Inbox count.
|
||
function forget() { window.MosaicChat?.forget(); last.clear(); inboxCount = null; messageCount = null; }
|
||
const failedView = (err, path) => `${head(path === '/queue' ? 'Queue' : failTitle(err))}<div class="banner ${refusal(err) ? 'ref' : 'err'}" role="alert"><p>${refusal(err) ? `<b>refused: <code>${txt(err.code)}</code>.</b> ` : ''}${why(err, err.code === 'queue-refused')} Console shows nothing rather than a guess. Nothing was written.</p>${retry}</div>${empty('Nothing to show.', refusal(err) ? 'The view stays empty until the problem above is fixed.' : err.module ? 'Read again.' : 'Read again, or come back when the bus answers.')}`;
|
||
const staleBanner = err => `<div class="banner err s1-stale" role="alert"><p><b>The last read failed.</b> ${why(err)} This is what was read before, ${when(readAt)}. Nothing was changed.</p>${retry}</div>`;
|
||
// Freshness line in the command bar for bus pages.
|
||
const stamp = iso => { const t = Date.parse(iso); return Number.isFinite(t) ? `${new Date(t).toISOString().slice(11, 19)} UTC` : 'unknown'; };
|
||
// The queue, business and settings pages name their own source.
|
||
function freshBus(state, source = 'Bus') {
|
||
$('fresh-bus').innerHTML = state === 'refused' ? `${esc(source)} <span class="warn">not read: refused</span>` : state === 'failed' ? `${esc(source)} <span class="warn">not read: the read failed</span>`
|
||
: `${esc(source)} read <b>${esc(stamp(readAt))}</b>${readAt ? ` (${esc(ago(readAt))})` : ''}${state === 'stale' ? ' · <span class="warn">stale: the last read failed</span>' : ''}`;
|
||
}
|
||
const SOURCES = { queue: 'Queue', business: 'Business', settings: 'Settings', docs: 'Docs' };
|
||
|
||
// ---------------------------------------------------------------- router
|
||
// #/ and anything that is not a #/ route is the control board; the rest is this file's.
|
||
const routeOf = () => window.MosaicOrg?.route() ?? (location.hash.startsWith('#/') ? location.hash.slice(1) : '/');
|
||
function view(get, path, q, opts, current) {
|
||
const parts = path.split('/').filter(Boolean).map(p => { try { return decodeURIComponent(p); } catch { return null; } });
|
||
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();
|
||
if (a === 'projects' && n === 1 && window.MosaicOrg) return window.MosaicWorkspace.projectsPage(q);
|
||
if (a === 'organization' && n === 1 && window.MosaicOrg) return window.MosaicWorkspace.dashboard();
|
||
if (a === 'inbox' && n === 1 && window.MosaicOrg) return configRead.then(() => window.MosaicWorkspace.inboxPage(q, { hire: hireStartHtml }));
|
||
if (a === 'tasks' && n === 1 && window.MosaicOrg) return window.MosaicTasksBoard.view();
|
||
if (a === 'inbox' && n === 1) return inboxView(get);
|
||
if (a === 'inbox' && n === 2) return SAFE.test(b) ? decisionView(get, b, current) : notFound(`${txt(b)} is not a decision id.`);
|
||
if (a === 'messages' && n === 1) return messagesView(get, q);
|
||
if (a === 'tasks' && n === 1) return tasksView(get);
|
||
if (a === 'tasks' && n === 2) return TASK.test(b) ? taskView(get, b) : notFound(`${txt(b)} is not a task reference.`);
|
||
if (a === 'agents' && n === 1) return agentsView(get);
|
||
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');
|
||
if (a === 'docs' && n === 1) return docsView(get);
|
||
if (a === 'docs' && n === 3) return docView(get, b, c, opts);
|
||
if (a === 'trail' && n === 3 && b === 'task') return TASK.test(c) ? trailView(get, b, c, q) : notFound(`${txt(c)} is not a task reference.`);
|
||
if (a === 'trail' && n === 3 && b === 'decision') return SAFE.test(c) ? trailView(get, b, c, q) : notFound(`${txt(c)} is not a decision id.`);
|
||
if (a === 'trail' && n === 3 && b === 'message') return SAFE.test(c) ? trailView(get, b, c, q) : notFound(`${txt(c)} is not a message id.`);
|
||
return notFound();
|
||
}
|
||
let gen = 0, shown = null, timer, proxyCleanup=null, orgCleanup=null;
|
||
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');
|
||
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`).
|
||
function keep() {
|
||
const a = document.activeElement, view = $('bus-view');
|
||
return {
|
||
focusKey: view.contains(a) ? a.dataset?.focusKey || (a.hasAttribute?.('data-bus-restart') ? 'bus-restart' : null) : null,
|
||
href: view.contains(a) ? a.getAttribute('href') : null, copy: view.contains(a) ? a.dataset?.copy : null, retry: view.contains(a) && a.hasAttribute?.('data-retry'), mirror: view.contains(a) ? a.dataset?.mirror : null, h1: view.contains(a) && a.tagName === 'H1',
|
||
settingsChoice: view.contains(a) && a.type==='radio' ? [a.name,a.value] : null,
|
||
settingsField: view.contains(a) && a.closest('.settings-content') && (a.dataset?.instanceField || a.dataset?.assistantField || a.dataset?.route || a.dataset?.setting) ? {form:a.closest('form')?.id || null, instance:a.closest('[data-instance]')?.dataset.instance || null, key:a.dataset.instanceField?'instanceField':a.dataset.assistantField?'assistantField':a.dataset.route?'route':'setting', value:a.dataset.instanceField || a.dataset.assistantField || a.dataset.route || a.dataset.setting} : null,
|
||
fallbacks:[...view.querySelectorAll('.route-row.fallback-open [data-route]')].map(e=>e.dataset.route),
|
||
field: view.contains(a) ? a.dataset?.field : null, caret: view.contains(a) && typeof a.selectionStart === 'number' ? [a.selectionStart, a.selectionEnd, a.scrollTop] : null, send: view.contains(a) && a.hasAttribute?.('data-send'),
|
||
decide: view.contains(a) ? a.dataset?.decide ?? (a.id === 'decide-status' ? 'status' : null) : null,
|
||
open: [...view.querySelectorAll('details[id]')].filter(d => d.open).map(d => d.id), status: $('copy-status')?.textContent || '',
|
||
scroll: [document.scrollingElement?.scrollTop ?? 0, $('main').scrollTop, [...view.querySelectorAll('.ws-tbl, .ws-insp')].map(e => [e.scrollLeft, e.scrollTop])],
|
||
};
|
||
}
|
||
function restore(k) {
|
||
for (const id of k.open) { const d = $(id); if (d) d.open = true; }
|
||
for (const e of $('bus-view').querySelectorAll('.route-row [data-route]')) if(k.fallbacks?.includes(e.dataset.route)) e.closest('.route-row').classList.add('fallback-open');
|
||
if ($('copy-status')) $('copy-status').textContent = k.status;
|
||
const el = [...$('bus-view').querySelectorAll('a[href],[data-copy],[data-retry],[data-mirror],[data-field],[data-send]')].find(e => k.href ? e.getAttribute('href') === k.href : k.copy ? e.dataset.copy === k.copy : k.mirror ? e.dataset.mirror === k.mirror : k.field ? e.dataset.field === k.field : k.send ? e.hasAttribute('data-send') : k.retry && e.hasAttribute('data-retry'));
|
||
// Row 252: the answer panel's buttons and its status line.
|
||
const dec = k.decide ? $('bus-view').querySelector(k.decide === 'status' ? '#decide-status' : `[data-decide="${k.decide}"]`) : null;
|
||
const choice=k.settingsChoice && [...$('bus-view').querySelectorAll('input[type=radio]')].find(x=>x.name===k.settingsChoice[0]&&x.value===k.settingsChoice[1]);
|
||
const setting=k.settingsField && [...$('bus-view').querySelectorAll('[data-instance-field],[data-assistant-field],[data-route],[data-setting]')].find(e=>e.dataset[k.settingsField.key]===k.settingsField.value && (!k.settingsField.form || e.closest('form')?.id===k.settingsField.form) && (!k.settingsField.instance || e.closest('[data-instance]')?.dataset.instance===k.settingsField.instance));
|
||
// The workspace screens mark their controls with data-focus-key: several Open links share an href.
|
||
const keyed = k.focusKey ? $('bus-view').querySelector(k.focusKey === 'bus-restart' ? '[data-bus-restart]' : `[data-focus-key="${CSS.escape(k.focusKey)}"]`) : null;
|
||
if (keyed) { keyed.focus({ preventScroll: true }); if (k.caret && keyed.tagName === 'INPUT' && typeof keyed.setSelectionRange === 'function') try { keyed.setSelectionRange(k.caret[0], k.caret[1]); } catch {} }
|
||
else if (setting) { setting.focus({preventScroll:true}); if(k.caret && typeof setting.setSelectionRange==='function'){setting.setSelectionRange(k.caret[0],k.caret[1]);setting.scrollTop=k.caret[2];} }
|
||
else if (choice) choice.focus({preventScroll:true});
|
||
else if (dec) dec.focus({ preventScroll: true });
|
||
else if (el && (k.href || k.copy || k.retry || k.mirror || k.field || k.send)) {
|
||
el.focus({ preventScroll: true });
|
||
if (k.caret && el.tagName === 'TEXTAREA') { el.setSelectionRange(k.caret[0], k.caret[1]); el.scrollTop = k.caret[2]; }
|
||
}
|
||
else if (k.h1) $('bus-view').querySelector('h1')?.focus({ preventScroll: true });
|
||
// A repaint replaces the tables: put their horizontal scroll and the page's back.
|
||
if (k.scroll) {
|
||
const [top, main, inner] = k.scroll;
|
||
[...$('bus-view').querySelectorAll('.ws-tbl, .ws-insp')].forEach((e, i) => { if (inner[i]) { e.scrollLeft = inner[i][0]; e.scrollTop = inner[i][1]; } });
|
||
if (document.scrollingElement && document.scrollingElement.scrollTop !== top) document.scrollingElement.scrollTop = top;
|
||
if ($('main').scrollTop !== main) $('main').scrollTop = main;
|
||
}
|
||
}
|
||
async function render(navigated, opts = {}) {
|
||
// A refresh due while this render reads would replace it: a navigation would lose its heading focus.
|
||
clearTimeout(timer);
|
||
if (out()) return;
|
||
// #1873 SP1: an address with no organization waits for the first list read to pick one, and a
|
||
// page drawn right after a switch waits for the new organization's config.
|
||
if ((window.MosaicOrg && !window.MosaicOrg.id) || switchRead) {
|
||
const g0 = ++gen, waiting = switchRead;
|
||
await window.MosaicOrg?.ready; await waiting;
|
||
if (waiting && switchRead === waiting) switchRead = null;
|
||
if (g0 !== gen || out()) return;
|
||
}
|
||
const route = routeOf(), [path, query = ''] = route.split('?'), board = window.MosaicOrg ? path === '/board' : path === '/' || path === '' || path === '/board';
|
||
// On the cross-organization pages a filter or selection changes only the query: that is a
|
||
// repaint of the same page, not a navigation (no loading view, focus and scroll kept).
|
||
const samePage = wsPage(path) && typeof shown === 'string' && shown.split('?')[0] === path;
|
||
if (path !== '/settings/model-proxy' && proxyCleanup) {proxyCleanup();proxyCleanup=null;}
|
||
if ((navigated || path !== '/settings/organizations') && orgCleanup) {orgCleanup();orgCleanup=null;}
|
||
// Leaving a decision discards its confirmation immediately, including a preview in flight.
|
||
if (answer && (navigated || path !== `/inbox/${answer.id}`)) answer = null;
|
||
const g = ++gen, routeVersion = routesEditVersion;
|
||
const current = () => g === gen && route === routeOf() && !out();
|
||
// In organization mode #/ is the cross-organization dashboard; the processing controls stay on the board.
|
||
if (window.MosaicOrg) for (const id of ['processing-link', 'mobile-processing-link']) if ($(id) && $(id).getAttribute('href') !== '#/board') $(id).setAttribute('href', '#/board');
|
||
document.body.classList.toggle('on-bus', !board);
|
||
$('bus-view').hidden = board;
|
||
sections(path);
|
||
document.querySelectorAll('.rail a').forEach(a => { const target = a.getAttribute('href').slice(1); const active = target === '/projects' ? /^\/(projects|chat)(\/|$)/.test(path) : target === '/' ? path === '/' : path === target; if (active) a.setAttribute('aria-current', 'page'); else a.removeAttribute('aria-current'); });
|
||
const chatPath = path === '/projects' && !window.MosaicOrg ? '/chat' : /^\/projects\/(threads|rooms)\//.test(path) ? '/chat' + path.slice('/projects'.length) : /^\/projects\/[^/]+$/.test(path) ? '/chat/projects/' + path.slice('/projects/'.length) : path;
|
||
window.MosaicChat?.leave(chatPath);
|
||
if (path === '/business') { location.replace('#/settings/business'); return; }
|
||
if (path === '/settings/display') { location.replace('#/settings/appearance'); return; }
|
||
// U5: Side by side draws its own two panes (panes.js); every other page stops their polling.
|
||
if (path !== '/side-by-side') window.MosaicPanes?.unmount();
|
||
else if (window.MosaicOrg && window.MosaicPanes) {
|
||
const fresh = navigated || shown !== path;
|
||
shown = path;
|
||
if (fresh) { unmountEditor(); await window.MosaicPanes.mount($('bus-view'), query, { navigated }); }
|
||
else window.MosaicPanes.refresh();
|
||
return;
|
||
}
|
||
if (chatPath === '/chat' || chatPath.startsWith('/chat/') || /^\/projects\/[0-9a-f-]+\/(?:settings|conversations|tasks|requirements|files)$/i.test(chatPath)) {
|
||
// Re-read the scoped capability as the Console and bus recover. A failed read
|
||
// withdraws the control; the chat renderer retains the draft across repaint.
|
||
if (window.MosaicOrg && !isTester) {
|
||
try {
|
||
const response = await fetch('/api/config', { cache: 'no-store', redirect: 'manual' });
|
||
if (!current()) return;
|
||
if (response.type === 'opaqueredirect') { signOut(); return; }
|
||
if (response.status === 401) { signOutSso(); return; }
|
||
const config = response.ok ? await response.json() : null;
|
||
if (!current()) return;
|
||
if (response.ok) window.MosaicIcons.succeeded(); else window.MosaicIcons.failed();
|
||
chatSend = config?.chatSend === true;
|
||
window.MosaicOrgBusStopped = config?.devOwner === true && config?.orgSetup === true && config?.chatSend === false;
|
||
} catch {
|
||
if (!current()) return;
|
||
window.MosaicIcons.failed(); chatSend = false; window.MosaicOrgBusStopped = false;
|
||
}
|
||
if (!current()) return;
|
||
}
|
||
// Row 177 (#1675): the tester Console writes to its own threads.
|
||
const focusedHeading = document.activeElement === $('bus-view').querySelector('h1');
|
||
await window.MosaicChat.render({ path: chatPath, container: $('bus-view'), canSend: (window.MosaicOrg ? chatSend : canSend) || isTester, tester: isTester, navigated });
|
||
if ((focusedHeading || shown === null) && document.activeElement === document.body) $('bus-view').querySelector('h1')?.focus({ preventScroll: true });
|
||
if (g !== gen || out()) return;
|
||
if (chatPath === '/chat') { const h = $('bus-view').querySelector('h1'); if (h) { h.textContent = 'Projects'; document.title = 'Projects · Mosaic Console'; } }
|
||
shown = route; schedule(); return;
|
||
}
|
||
if (board) {
|
||
// The board page keeps its own title; the Inbox count still follows the bus.
|
||
if (shown !== null) { shown = null; unmountEditor(); $('bus-view').innerHTML = ''; document.title = 'Dashboard · Mosaic Console'; if (navigated) $('main').focus(); }
|
||
// The held roles (row 95) are read with it. A refusal of either forgets both, as on the bus pages.
|
||
const epoch = orgEpoch;
|
||
const [inbox, agents, messages, tasks, queue, business, projects] = await Promise.allSettled([
|
||
fetchRead('inbox'), fetchRead('agents'), fetchRead('messages'), fetchRead('tasks'), fetchApi('queue'), fetchApi('business'),
|
||
fetch('/api/chat/projects', { cache: 'no-store', redirect: 'manual' }).then(async r => { if (r.type === 'opaqueredirect') { signOut(); throw signedOut(); } const body = await r.json(); if (signInRequired(r, body)) { signOutSso(); throw signedOut(); } if (!r.ok || !Array.isArray(body.rows)) throw new ReadError(body?.error, body?.message, r.status); return body; })
|
||
]);
|
||
const failed = [inbox, agents, messages, tasks].filter(s => s.status === 'rejected').map(s => s.reason);
|
||
if (failed.some(err => err.code === 'signed-out')) return;
|
||
// #1873 SP1: an answer read for an organization that is no longer open is not kept.
|
||
if (epoch !== orgEpoch) return;
|
||
if (inbox.status === 'fulfilled') last.set('inbox', inbox.value);
|
||
if (agents.status === 'fulfilled') last.set('agents', agents.value);
|
||
if (messages.status === 'fulfilled') last.set('messages', messages.value);
|
||
const refused = failed.find(refusal);
|
||
if (refused) forget();
|
||
if (g !== gen) return;
|
||
if (inbox.status === 'fulfilled' && !refused) countInbox(inbox.value.rows);
|
||
if (messages.status === 'fulfilled' && !refused) messageCount = messages.value.unread;
|
||
const good = result => !refused && result.status === 'fulfilled' ? result.value : null;
|
||
const taskRows = good(tasks)?.rows, queueRows = good(queue)?.rows, projectRows = good(projects)?.rows;
|
||
window.MosaicDashboard?.update({
|
||
agents: good(agents)?.rows?.length ?? null, inbox: good(inbox)?.rows ?? null,
|
||
messages: Number.isFinite(good(messages)?.unread) ? good(messages).unread : null,
|
||
tasks: Array.isArray(taskRows) ? taskRows.map(r => task(r)).filter(t => !t.missing && !t.done).length : null,
|
||
queue: Array.isArray(queueRows) ? queueRows.filter(r => r.state !== 'done').length : null,
|
||
projects: Array.isArray(projectRows) ? projectRows.filter(p => !p.archived).length : null,
|
||
business: good(business)?.business?.id ?? null,
|
||
readAt: !refused && [inbox, agents, messages, tasks, queue, business, projects].some(r => r.status === 'fulfilled') ? Date.now() : null
|
||
});
|
||
const initialOrganizations = await window.MosaicInitialOrganizations;
|
||
if (g !== gen) return;
|
||
paintHeld(refused || (agents.status === 'rejected' ? agents.reason : null), !window.MosaicOrg && Array.isArray(initialOrganizations) && initialOrganizations.length === 0, !window.MosaicOrg && Array.isArray(initialOrganizations) ? initialOrganizations.filter(row => row.invalid) : [], !window.MosaicOrg ? window.MosaicOrganizationError : null);
|
||
sections(path); schedule();
|
||
return;
|
||
}
|
||
if (path === '/settings/model-proxy' && shown === route && !navigated) return;
|
||
if (path === '/settings/organizations' && shown?.split('?')[0] === path && !navigated) return;
|
||
if (($('agent-dialog')?.open || document.querySelector('.agent-more[aria-expanded=true]')) && !navigated) { schedule(); return; }
|
||
if (navigated || (shown !== route && !samePage)) { unmountEditor(); $('bus-view').innerHTML = loadingView(SOURCES[path.split('/')[1]]); }
|
||
let html, state = 'fresh';
|
||
const live = reader(true);
|
||
try {
|
||
if (path !== '/organization' && !wsPage(path) && !(path === '/agents' && window.MosaicOrg) && path !== '/messages' && !['/settings','/settings/appearance','/settings/model-proxy','/settings/organizations'].includes(path)) {
|
||
try { await live('messages'); }
|
||
catch (err) { messageCount = null; if (err.status === 403 || err.code === 'signed-out') throw err; }
|
||
}
|
||
html = await view(live, path, new URLSearchParams(query), opts, current); readAt = live.oldest(); }
|
||
catch (err) {
|
||
if (err.code === 'signed-out') return;
|
||
const kept = reader(false);
|
||
try { if (refusal(err)) throw err; html = await view(kept, path, new URLSearchParams(query), opts, current); readAt = kept.oldest(); html = staleBanner(err) + html; state = 'stale'; }
|
||
catch { html = failedView(err, path) + (path === '/settings' ? appearance() : ''); state = refusal(err) ? 'refused' : 'failed'; }
|
||
if (refusal(err)) forget();
|
||
}
|
||
if (!current()) return;
|
||
freshBus(state, SOURCES[path.split('/')[1]]);
|
||
// A route edit after the markup was prepared must win over that pending redraw.
|
||
if(path==='/settings/routing' && routeVersion!==routesEditVersion){render(false);return;}
|
||
const k = !navigated && (shown === route || samePage) ? keep() : null;
|
||
// E2E6 P1-1: an org-page editor in use keeps its node, draft and focus across the repaint.
|
||
const heldLive = k ? window.MosaicWorkspace?.holdLive?.($('bus-view')) : null;
|
||
unmountEditor();
|
||
$('bus-view').innerHTML = html; shown = route;
|
||
if (heldLive) window.MosaicWorkspace.graftLive($('bus-view'), heldLive);
|
||
syncAppearance(true);
|
||
if (path.startsWith('/docs/')) paintDoc();
|
||
if (path === '/organization') window.MosaicConsole?.attachBus(document.querySelector('[data-dashboard-bus]'));
|
||
if (path === '/settings/model-proxy') proxyCleanup=window.MosaicProxy.mount();
|
||
if (path === '/settings/organizations') orgCleanup=window.MosaicOrgCreate.mount();
|
||
sections(path);
|
||
const h1 = $('bus-view').querySelector('h1');
|
||
document.title = path === '/settings/business' && $('settings-page-title') ? `Settings · ${window.MosaicOrg ? 'Organization' : 'Business'} · Mosaic Console` : `${h1 ? h1.textContent : 'Console'} · Mosaic Console`;
|
||
if (k) restore(k);
|
||
// Message on the Board (row 95) lands in the form it opened, addressed to the role.
|
||
else if (focusSend && $('send-body')) { $('send-body').focus(); announce(`Message to ${draft.to}`); }
|
||
else if (navigated && h1) { const target=settingsFocusDisclosure&&path.startsWith('/settings/') ? $('settings-disclosure') : path.startsWith('/settings/') ? ($('settings-page-title')||h1) : h1; settingsFocusDisclosure=false; target.focus(); announce(target.textContent); }
|
||
focusSend = false;
|
||
schedule();
|
||
}
|
||
|
||
// ---------------------------------------------------------------- events
|
||
// Copy puts the command on the clipboard and does nothing else. If the clipboard is
|
||
// unavailable, the command text is selected so the person can copy it themselves.
|
||
document.addEventListener('click', async e => {
|
||
// The skip link moves focus only. Its #main would otherwise reach the hash router.
|
||
if (e.target.closest('.skip')) { e.preventDefault(); $('main').focus(); return; }
|
||
const b = e.target.closest('#bus-view [data-copy]');
|
||
if (b) {
|
||
const text = b.dataset.copy, out = $('copy-status');
|
||
try { await navigator.clipboard.writeText(text); out.textContent = `Copied: ${text}`; toast(out.textContent); }
|
||
catch {
|
||
const r = document.createRange(); r.selectNodeContents(b.previousElementSibling);
|
||
const s = getSelection(); s.removeAllRanges(); s.addRange(r);
|
||
out.textContent = 'The clipboard is unavailable. The command is selected; press Ctrl+C to copy it.';
|
||
toast(out.textContent, true);
|
||
}
|
||
return;
|
||
}
|
||
// Row 252: Approve, Deny, Confirm and Cancel. One click is one step; none repeats itself.
|
||
const dec = e.target.closest('#decide-section [data-decide]');
|
||
if (dec) { if (!dec.disabled) decide(dec.dataset.decide); return; }
|
||
if (e.target.closest('#toast [data-dismiss]')) { toast(null); return; }
|
||
const item = e.target.closest('#cmdk-list [data-href]');
|
||
if (item) { pkGo(item.dataset.href); return; }
|
||
if (e.target.closest('#cmdk')) { pkOpen(); return; }
|
||
const message = e.target.closest('#held [data-message-role]');
|
||
if (message) { draft.to = message.dataset.messageRole; focusSend = true; location.hash = '#/inbox'; return; }
|
||
if (e.target.closest('#bus-view [data-retry], #held [data-retry]')) {
|
||
if (window.MosaicRefreshOrganizations) window.MosaicRefreshOrganizations();
|
||
render(false);
|
||
}
|
||
});
|
||
|
||
// ---------------------------------------------------------------- toast
|
||
// One line in a polite live region. Success goes after 2.6 s; an error stays until dismissed.
|
||
let toastTimer;
|
||
function toast(text, error = false) {
|
||
const t = $('toast'); clearTimeout(toastTimer);
|
||
if (text === null) { t.className = 'toast'; t.textContent = ''; return; }
|
||
t.className = `toast on${error ? ' err' : ''}`;
|
||
t.innerHTML = `<span>${esc(text)}</span>${error ? '<button type="button" data-dismiss>Dismiss</button>' : ''}`;
|
||
if (!error) toastTimer = setTimeout(() => toast(null), 2600);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- command palette
|
||
// Ctrl+K opens it. It lists the views, and the decisions and tasks from the last inbox and
|
||
// tasks reads (opening it reads both again, GET only). Enter goes; Esc closes and puts focus
|
||
// back where it was. It only navigates.
|
||
const VIEWS = [['#/', 'Dashboard'], ['#/projects', 'Projects'], ['#/inbox', 'Inbox'], ['#/messages', 'Assistant'], ['#/tasks', 'Tasks'], ['#/agents', 'Agents'], ['#/queue', 'Queue'], ['#/settings/business', 'Business'], ['#/docs', 'Docs'], ['#/settings', 'Settings'], ['#/settings/display', 'Sidebar display']];
|
||
let pkAll = [], pkShown = [], pkAt = 0, pkBack = null;
|
||
function pkItems() {
|
||
const decisions = (last.get('inbox')?.rows || []).map(d => ({ href: `#/inbox/${enc(d.id)}`, label: first(d.question), group: `decision ${short(d.id)}` }));
|
||
const tasks = (last.get('tasks')?.rows || []).filter(r => TASK.test(String(r.task_ref))).map(r => { const t = task(r); return { href: `#/tasks/${enc(t.ref)}`, label: `#${t.id} ${t.title ?? '(no title in the current read)'}`, group: 'task' }; });
|
||
const rows = (last.get('api:queue')?.rows || []).filter(r => Number.isInteger(r.id)).map(r => ({ href: `#/queue/${r.id}`, label: `${r.id} ${r.piece ?? ''}`, group: `queue row, ${r.state}` }));
|
||
pkAll = [...VIEWS.map(([href, label]) => ({ href, label, group: 'view' })), ...(window.MosaicProjects?.palette?.() || []), ...decisions, ...tasks, ...rows];
|
||
}
|
||
function pkFill() {
|
||
const q = $('cmdk-input').value.trim().toLowerCase();
|
||
pkShown = pkAll.filter(i => !q || `${i.label} ${i.group}`.toLowerCase().includes(q)).slice(0, 50);
|
||
pkAt = Math.min(pkAt, Math.max(0, pkShown.length - 1));
|
||
$('cmdk-list').innerHTML = pkShown.length ? pkShown.map((i, n) => `<li role="option" id="cmdk-opt-${n}" data-href="${esc(i.href)}" aria-selected="${n === pkAt}"><span>${txt(i.label)}</span><span class="g">${txt(i.group)}</span></li>`).join('')
|
||
: '<li class="pk-none" role="option" aria-disabled="true" aria-selected="false">No view, decision or task matches.</li>';
|
||
if (pkShown.length) { $('cmdk-input').setAttribute('aria-activedescendant', `cmdk-opt-${pkAt}`); $(`cmdk-opt-${pkAt}`)?.scrollIntoView({ block: 'nearest' }); }
|
||
else $('cmdk-input').removeAttribute('aria-activedescendant');
|
||
}
|
||
function pkOpen() {
|
||
const d = $('cmdk-dialog');
|
||
if (d.open) return;
|
||
pkBack = document.activeElement; pkAt = 0; $('cmdk-input').value = '';
|
||
pkItems(); pkFill(); d.showModal(); $('cmdk-input').focus();
|
||
const epoch = orgEpoch;
|
||
Promise.allSettled(['inbox', 'tasks'].map(async v => { const r = await fetchRead(v); if (epoch === orgEpoch) last.set(v, r); })).then(rs => {
|
||
if (epoch !== orgEpoch) return;
|
||
if (rs.some(r => r.status === 'rejected' && refusal(r.reason))) { forget(); sections(routeOf().split('?')[0]); }
|
||
if (d.open) { pkItems(); pkFill(); }
|
||
});
|
||
}
|
||
function pkGo(href) {
|
||
pkBack = null; $('cmdk-dialog').close();
|
||
if (location.hash === href || (href === '#/' && !location.hash.startsWith('#/'))) { render(true); return; }
|
||
location.hash = href;
|
||
}
|
||
$('cmdk-dialog').addEventListener('close', () => { const b = pkBack; pkBack = null; if (b && document.contains(b)) b.focus(); });
|
||
$('cmdk-input').addEventListener('input', () => { pkAt = 0; pkFill(); });
|
||
$('cmdk-input').addEventListener('keydown', e => {
|
||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); if (pkShown.length) { pkAt = (pkAt + (e.key === 'ArrowDown' ? 1 : -1) + pkShown.length) % pkShown.length; pkFill(); } }
|
||
else if (e.key === 'Enter') { e.preventDefault(); if (pkShown[pkAt]) pkGo(pkShown[pkAt].href); }
|
||
});
|
||
document.addEventListener('keydown', e => {
|
||
if ((e.ctrlKey || e.metaKey) && !e.altKey && e.key.toLowerCase() === 'k') { e.preventDefault(); pkOpen(); return; }
|
||
// Up and down move between the task links of a table, as on the board's session table.
|
||
const a = e.target.closest?.('#bus-view table.s1-table td.s1-title a');
|
||
if (!a || (e.key !== 'ArrowDown' && e.key !== 'ArrowUp')) return;
|
||
const links = [...a.closest('table').querySelectorAll('td.s1-title a')], i = links.indexOf(a);
|
||
e.preventDefault(); links[i + (e.key === 'ArrowDown' ? 1 : -1)]?.focus();
|
||
});
|
||
// Settings' appearance selects drive the command bar's, and follow them back.
|
||
document.addEventListener('change', e => {
|
||
const m = e.target.closest?.('#bus-view select[data-mirror]');
|
||
if (m) { const src = $(m.dataset.mirror); src.value = m.value; src.dispatchEvent(new Event('change')); return; }
|
||
if (e.target.id === 'palette' || e.target.id === 'mode') for (const s of document.querySelectorAll(`#bus-view select[data-mirror="${e.target.id}"]`)) s.value = e.target.value;
|
||
});
|
||
// The send form (row 76). Values go to `draft` as typed; Send posts once and never again by itself.
|
||
document.addEventListener('input', e => { const f = e.target.closest?.('#send-form [data-field]'); if (f) draft[f.dataset.field] = f.value; });
|
||
document.addEventListener('submit', async e => {
|
||
if (e.target.id !== 'send-form') return;
|
||
e.preventDefault();
|
||
if (sending) return;
|
||
const to = draft.to, text = draft.body;
|
||
if (out()) { receipt = { kind: 'refused', to: to || 'no role', code: 'sign-in', message: 'signed out; reload the page to sign in again' }; paintSend(); announce('Not sent: ' + receipt.message); return; }
|
||
if (!to || !text.trim()) { receipt = { kind: 'refused', to: to || 'no role', code: 'invalid-request', message: to ? 'the message is empty' : 'choose a role first' }; paintSend(); announce('Not sent: ' + receipt.message); return; }
|
||
sending = true; receipt = null; paintSend();
|
||
const epoch = orgEpoch;
|
||
let res = null, body = null;
|
||
try {
|
||
res = await fetch('/api/bus/message', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ to, body: text }), cache: 'no-store', redirect: 'manual' });
|
||
try { body = await res.json(); } catch { body = null; }
|
||
} catch { res = null; }
|
||
if (epoch !== orgEpoch) { if (res?.type === 'opaqueredirect') signOut(); return; }
|
||
// Sent: an id came back. Not sent: a 4xx (refused before the bus wrote), the server's
|
||
// sent:false, or a redirect, which only the sign-in proxy gives (an expired session), so the
|
||
// request never reached the Console. Anything else, no answer included, may have been sent,
|
||
// and so may a 408: a proxy can answer it after forwarding (Envoy's stream_idle_timeout).
|
||
if (res?.type === 'opaqueredirect') {
|
||
receipt = { kind: 'refused', to, code: 'sign-in', message: 'the sign-in proxy redirected it, so it never reached the Console; reload the page to sign in again' };
|
||
} else if (res?.ok && SAFE.test(body?.id ?? '')) {
|
||
receipt = { kind: 'sent', to, id: body.id, at: body.at }; replies = [];
|
||
if (draft.body === text) draft.body = ''; // keep text typed while the send was in flight
|
||
} else if (res && !res.ok && ((res.status >= 400 && res.status < 500 && res.status !== 408) || body?.sent === false)) {
|
||
receipt = { kind: 'refused', to, code: typeof body?.error === 'string' ? body.error : `HTTP ${res.status}`, message: typeof body?.message === 'string' ? body.message.replace(/^not sent: /, '') : 'refused' };
|
||
} else receipt = { kind: 'unknown', to };
|
||
sending = false; paintSend();
|
||
announce(receipt.kind === 'sent' ? `Sent to ${to}` : receipt.kind === 'refused' ? 'Not sent; draft kept' : 'Outcome unknown; it may have been sent; draft kept');
|
||
if (res?.type === 'opaqueredirect') signOut();
|
||
});
|
||
// Signed out: drop every bus read, kept ones included, and the page drawn from them. The send
|
||
// form stays, with its draft and receipt, so nothing typed is lost; it sends nothing more.
|
||
document.addEventListener('mosaic-signed-out', () => {
|
||
window.MosaicDashboard?.update({});
|
||
clearTimeout(timer); gen++; forget();
|
||
for (const el of [...$('bus-view').children]) if (el.id !== 'send-section') el.remove();
|
||
$('held').replaceChildren(); $('held-count').textContent = '–'; heldHtml = null;
|
||
sections(routeOf().split('?')[0]); paintSend();
|
||
});
|
||
// Whether this server takes a send here. The form is drawn on the next Inbox render; the Board's
|
||
// Message buttons are drawn from the roles already read.
|
||
// F3: `settingsSend` lets the owner of an organization Console save Settings on the selected
|
||
// organization's bus; messaging a role still follows `send` (canMessage) and `chatSend`.
|
||
// A bus restart reads the config again and sends it here as a mosaic-config event.
|
||
const applyConfig = (c, opts = {}) => {
|
||
isTester = c?.tester === true;
|
||
canEdit = !isTester && c?.edit === true;
|
||
canSend = !isTester && (c?.send === true || c?.settingsSend === true);
|
||
canMessage = !isTester && c?.send === true;
|
||
chatSend = !isTester && c?.chatSend === true;
|
||
orgSetup = !isTester && c?.orgSetup === true;
|
||
window.MosaicOrgBusStopped = !!window.MosaicOrg && c?.devOwner === true && orgSetup && c?.chatSend === false;
|
||
// The header menu offers "New organization" to the owner of a Console with organizations; nobody else can create one.
|
||
if (orgSetup && !$('org-new-link')) { const a = document.createElement('a'); a.id = 'org-new-link'; a.href = NEW_ORG; a.setAttribute('role', 'menuitem'); a.textContent = 'New organization'; document.querySelector('#avatar-menu > a[href="#/settings"]')?.after(a); }
|
||
ssoOn = c?.sso === true;
|
||
canDecide = !isTester && c?.decide === true;
|
||
if (isTester && !$('tester-banner')) {
|
||
const banner = document.createElement('div'); banner.id = 'tester-banner'; banner.className = 'banner ref';
|
||
banner.setAttribute('role', 'status'); banner.textContent = 'Tester Console. Changes are recorded as tester, never as the human.';
|
||
$('main').prepend(banner);
|
||
}
|
||
if (opts.quiet || (!canSend && !isTester && !ssoOn)) return;
|
||
const path = routeOf().split('?')[0];
|
||
if (path.startsWith('/chat')||path.startsWith('/projects')||path.startsWith('/inbox')||path.startsWith('/settings')||path.startsWith('/docs/')||wsPage(path)) render(false); else if (window.MosaicOrg ? path === '/board' : path === '/' || path === '') paintHeld(heldErr);
|
||
};
|
||
configRead = fetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => { if (r.type === 'opaqueredirect') { signOut(); return null; } return r.json(); }).then(applyConfig).catch(() => {});
|
||
// E1 (P1-5): after Restart bus the organization dashboard draws its bus line now, not at the next poll.
|
||
// E2E6 P2-2: a write on the organization page that changes other sections (a pack apply) asks for a
|
||
// fresh read of the page; editors in progress are kept by holdLive.
|
||
// Ruling 2026-11-14: an apply, hire or fire redraws the Agents page in the same response cycle, not at the next poll.
|
||
document.addEventListener('mosaic-org-changed', e => { if (window.MosaicOrg && e.detail?.org === window.MosaicOrg.id && ['/organization', '/agents'].includes(routeOf().split('?')[0])) render(false); });
|
||
// #1873 SP1: another organization opened in place (display.js, before this file's hashchange
|
||
// render). Nothing read, drafted or confirmed for the old one carries over; the new one's config
|
||
// is read before the next page draws. A write already sent finishes against the old organization,
|
||
// and its answer is not drawn on the new one.
|
||
document.addEventListener('mosaic-org-switch', () => {
|
||
// Writes still in flight keep going to the old organization; their answers are dropped (orgEpoch)
|
||
// and every busy flag and receipt starts clean here.
|
||
orgEpoch++;
|
||
sending = false; receipt = null; replies = [];
|
||
hireBusy = false; fireBusy = false; settingsSaving = false; resetReceipt = '';
|
||
assistantBusy = false; assistantFormsBusy.clear(); instanceBusyOps = new Set();
|
||
routesBusy = false; routesApply = null; harnessBusy = false; harnessLoading = false;
|
||
forget(); clearTimeout(timer);
|
||
answer = null; heldErr = null; heldHtml = null; readAt = null; shown = null; projectContext = null;
|
||
draft.to = ''; draft.body = '';
|
||
hireDraft = { op: 'hire', level: 'org' }; hireTemplates = []; hireStatus = ''; hireCode = '';
|
||
fireAsk = null; fireReceipt = null;
|
||
settingsSnapshot = null; settingsInputs = null; settingsReceipt = ''; settingInvalidKey = null;
|
||
assistantDrafts = Object.create(null); nameDrafts = Object.create(null); assistantReceipts = Object.create(null); assistantReceiptKinds = Object.create(null); assistantCardReceipts = Object.create(null);
|
||
instanceView = null; instanceDrafts = { add: null, change: null }; instanceReceipt = ''; instanceReceiptOp = null; instanceReceipts = Object.create(null);
|
||
routesView = null; routesDraft = null; routesReceipt = ''; routesEditVersion++;
|
||
harnessSettings = null; harnessDraft = null; harnessReceipt = '';
|
||
// A file draft is keyed by project and path only; the page reload that used to drop it is gone.
|
||
docKey = null; docStates.clear(); pkAll = []; pkShown = []; pkAt = 0;
|
||
configRead = switchRead = fetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => { if (r.type === 'opaqueredirect') { signOut(); return null; } return r.json(); }).then(c => applyConfig(c, { quiet: true })).catch(() => {});
|
||
});
|
||
document.addEventListener('mosaic-config', e => { if (e.detail && typeof e.detail === 'object') { applyConfig(e.detail); if (window.MosaicOrg && routeOf().split('?')[0] === '/organization') render(false); } });
|
||
// The cross-organization pages ask for a repaint after a filter, sort or selection change,
|
||
// and report the inbox count across organizations for the sidebar.
|
||
document.addEventListener('mosaic-workspace-render', () => { if (wsPage(routeOf().split('?')[0])) render(false); });
|
||
document.addEventListener('mosaic-workspace-inbox', e => { const d = e.detail; if (d && Number.isFinite(d.open)) { inboxCount = { open: d.open, blocking: Number.isFinite(d.blocking) ? d.blocking : 0 }; sections(routeOf().split('?')[0]); } });
|
||
// This context comes from the conversations renderer after its authorized read.
|
||
let projectContext = null;
|
||
document.addEventListener('mosaic-project-context', event => {
|
||
const detail = event.detail;
|
||
if (detail && typeof detail.projectId === 'string') projectContext = detail;
|
||
});
|
||
document.addEventListener('mosaic-signed-out', () => { projectContext = null; $('project-context').replaceChildren(); });
|
||
// Normalize the renderer's legacy project links without changing the chat API.
|
||
function projectChrome() {
|
||
const path = routeOf().split('?')[0];
|
||
if (!(path === '/chat' || path.startsWith('/chat/') || path === '/projects' || path.startsWith('/projects/'))) { $('project-context').replaceChildren(); $('project-context').dataset.signature = ''; return; }
|
||
const view = $('bus-view');
|
||
const context = $('project-context');
|
||
const conversation = view.querySelector('.chat-conversation, .chat-room');
|
||
const projectLink = conversation?.querySelector('p a[href^="#/chat/projects/"], p a[href^="#/projects/"]');
|
||
const overview = /^\/(?:projects\/|chat\/projects\/)([0-9a-f-]+)$/i.exec(path);
|
||
const isRoom = projectContext?.room === true && conversation?.dataset.project === projectContext.projectId && new RegExp('^/(?:projects|chat)/rooms/' + projectContext.projectId + '$', 'i').test(path);
|
||
const validContext = projectContext && (overview?.[1] === projectContext.projectId || (projectContext.thread && conversation?.dataset.thread === projectContext.thread) || isRoom || path === '/projects/' + projectContext.projectId + '/settings');
|
||
const project = validContext ? (projectLink?.textContent || view.querySelector('.chat-area h1')?.textContent || projectContext.projectId) : '';
|
||
const name = conversation?.querySelector('h1')?.textContent || '';
|
||
const href = validContext ? '#/projects/' + encodeURIComponent(projectContext.projectId) : '';
|
||
const uuid = value => typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
|
||
const threadHref = isRoom ? '#/projects/rooms/' + encodeURIComponent(projectContext.projectId) : validContext && uuid(projectContext.thread) ? '#/projects/threads/' + encodeURIComponent(projectContext.thread) + (uuid(projectContext.session) ? '/sessions/' + encodeURIComponent(projectContext.session) : '') : '';
|
||
const signature = JSON.stringify([project || '', name, href, threadHref]);
|
||
if (context.dataset.signature !== signature) {
|
||
context.dataset.signature = signature; context.replaceChildren();
|
||
if (project && href) { const label = document.createElement('p'); label.className = 'tree-title'; label.textContent = 'Current project'; const link = document.createElement('a'); link.href = href; link.textContent = project; link.className = 'context-project'; context.append(label, link); if (name) { const title = document.createElement(threadHref ? 'a' : 'p'); title.className = 'context-conversation'; title.textContent = name; if (threadHref) title.href = threadHref; context.append(title); } }
|
||
}
|
||
for (const a of view.querySelectorAll('a[href^="#/chat"]')) {
|
||
const h = a.getAttribute('href');
|
||
const canonical = h === '#/chat' ? '#/projects' : h.startsWith('#/chat/projects/') ? '#/projects/' + h.slice('#/chat/projects/'.length) : h.replace(/^#\/chat\/(threads|rooms)\//, '#/projects/$1/');
|
||
if (canonical !== h) a.setAttribute('href', canonical);
|
||
if (a.textContent === 'Chat projects') a.textContent = 'Projects';
|
||
}
|
||
if (path === '/chat' || path === '/projects') {
|
||
const h = view.querySelector('h1');
|
||
if (h && h.textContent === 'Chat') { h.textContent = 'Projects'; document.title = 'Projects · Mosaic Console'; }
|
||
}
|
||
}
|
||
let lastViewFocus = null;
|
||
$('bus-view').addEventListener('focusin', e => { lastViewFocus = e.target; });
|
||
new MutationObserver(() => {
|
||
projectChrome();
|
||
if (lastViewFocus && !lastViewFocus.isConnected && document.activeElement === document.body) {
|
||
const replacement = lastViewFocus.id && document.getElementById(lastViewFocus.id);
|
||
(replacement && !replacement.disabled ? replacement : $('bus-view').querySelector('h1'))?.focus({ preventScroll: true });
|
||
}
|
||
}).observe($('bus-view'), { childList: true, subtree: true });
|
||
// The drawer keeps the background inert and returns focus to its opener.
|
||
const nav = $('console-nav'), opener = $('nav-open'), closer = $('nav-close'), scrim = $('nav-scrim');
|
||
const mobileProcessing = $('processing-mobile');
|
||
let drawerOpen = false;
|
||
const background = [document.querySelector('.cmdbar'), document.querySelector('.rail'), mobileProcessing, $('main'), $('inspector'), document.querySelector('.foot')];
|
||
function drawer(open, restore = true) {
|
||
drawerOpen = open; document.body.classList.toggle('nav-open', open);
|
||
opener.setAttribute('aria-expanded', String(open)); scrim.hidden = !open;
|
||
background.forEach(el => { if (el) el.inert = open; });
|
||
if (open) { $('nav-overflow').hidden = nav.scrollHeight <= nav.clientHeight + 1; closer.focus(); }
|
||
else if (restore) opener.focus();
|
||
}
|
||
opener.addEventListener('click', () => drawer(true));
|
||
closer.addEventListener('click', () => drawer(false));
|
||
scrim.addEventListener('click', () => drawer(false));
|
||
document.addEventListener('keydown', e => {
|
||
if (!drawerOpen) return;
|
||
if (e.key === 'Escape') { e.preventDefault(); drawer(false); return; }
|
||
if (e.key !== 'Tab') return;
|
||
const controls = [...nav.querySelectorAll('a[href],button:not(:disabled),input:not(:disabled),select:not(:disabled),[tabindex="0"]')].filter(el => el.getClientRects().length);
|
||
if (!controls.length) return;
|
||
if (!nav.contains(document.activeElement)) { e.preventDefault(); (e.shiftKey ? controls.at(-1) : controls[0]).focus(); }
|
||
else if (e.shiftKey && document.activeElement === controls[0]) { e.preventDefault(); controls.at(-1).focus(); }
|
||
else if (!e.shiftKey && document.activeElement === controls.at(-1)) { e.preventDefault(); controls[0].focus(); }
|
||
});
|
||
nav.addEventListener('click', e => { if (drawerOpen && e.target.closest('a[href^="#/"]')) drawer(false, false); });
|
||
window.addEventListener('resize', () => { if (drawerOpen && innerWidth >= 760) drawer(false, false); if (drawerOpen) $('nav-overflow').hidden = nav.scrollHeight <= nav.clientHeight + 1; });
|
||
window.addEventListener('hashchange', () => render(true));
|
||
$('refresh').addEventListener('click', () => render(false));
|
||
$('pause').addEventListener('click', () => setTimeout(schedule)); // after app.js flips aria-pressed
|
||
render(false).then(() => { if (!$('bus-view').hidden) { const h1 = $('bus-view').querySelector('h1'); if (h1 && location.hash.startsWith('#/')) h1.focus(); } });
|
||
})();
|