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

669 lines
55 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(() => {
'use strict';
const $ = id => document.getElementById(id);
const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const key = r => `${r.project}/${r.agent}`;
const drafts = new Map(), receipts = new Map(), sending = new Set();
// Delivered replies with no newer answer yet, by row: the board's sentAt. Page memory only.
const awaiting = new Map();
let data = null, project = null, selected = null, returnFocus = null, paused = false, busy = false, writing = false, reading = null, timer;
let board = 'the configured board', failed = false;
// Show machine sessions (#1589): off by default, kept with the page's settings. While it is off the
// page doesn't read /api/board at all; the held roles above come from the bus (bus.js).
let machine = false;
// #1873 SP1: kept per organization, read again when the open organization changes.
const boardKey = () => window.MosaicOrg?.id ? `mosaic-console-board:${window.MosaicOrg.id}` : 'mosaic-console-board';
const readMachine = () => { try { return JSON.parse(localStorage.getItem(boardKey()))?.machine === true; } catch { return false; } };
machine = readMachine();
// Signed out (#1589): a Console fetch answered with a redirect, so the sign-in proxy turned it away.
// The first one sets body.signed-out (the listener below); after that no Console fetch is made.
const out = () => document.body.classList.contains('signed-out');
const signOut = () => { if (!out()) document.dispatchEvent(new Event('mosaic-signed-out')); };
// Q175 phase 1 (#1690): under --sso the Console itself answers a read without a session with 401
// `sign-in required`; that signs the page out too, and the line links to the Console's sign-in.
// Any other 401 stays an error. `sso` comes from /api/config.
let sso = false;
const signInRequired = (res, body) => res.status === 401 && body?.error === 'sign-in required';
const signedOut = () => Object.assign(new Error('the sign-in proxy redirected it, so it never reached the Console'), { signedOut: true });
const labels = { registration: 'registered', 'first-user-message': 'first message', 'tmux-pane': 'tmux pane', 'session-cwd': 'session cwd', 'workspace-git-root': 'git root' };
const source = value => value ? `<span class="source">${esc(labels[value] || value)}</span>` : '';
// Who set a registered task (#1511): null from the scan unless the task shown is the registered one. A caller's claim, not verified; it grants nothing.
const setBy = r => r.taskSetBy ? `<span class="source">set by ${esc(r.taskSetBy)}</span>` : '';
// Status mark: the class adds the glyph (shell.css); the word is the text, so colour is never the only signal.
const badge = state => `<span class="badge st st-${esc(state || 'unknown')} ${ { working: 'badge-ok', waiting: 'badge-attn', error: 'badge-danger' }[state] || 'badge-muted'}">${esc(state || 'unknown')}</span>`;
const connectorStatus = r => r.connector ? `<span class="source">${r.connector.braked === true ? 'braked (STOP)' : r.connector.braked === false ? 'not braked' : 'brake unknown'} · owner ${esc(r.connector.ownerState)}</span>` : '';
const relaunchNotice = r => r.relaunchedAt ? `relaunched at ${r.relaunchedAt}, no messages since` : '';
// Relative age is the board's ageSeconds: time since last activity as of the scan, not session lifetime (#1507).
function age(s) {
if (typeof s !== 'number' || !(s >= 0)) return null;
const m = Math.floor(s / 60), h = Math.floor(m / 60);
return s < 60 ? `${s}s` : m < 60 ? `${m}m` : h < 24 ? `${h}h` : `${Math.floor(h / 24)}d`;
}
const activity = r => r.lastActivity ? (age(r.ageSeconds) ? `${age(r.ageSeconds)} ago` : r.lastActivity) : null;
// A reply is pending until the seat is no longer working and has written after the send.
// If either time is unparsable, the page falls back to the plain label rather than guessing.
function pending(r) {
const sent = awaiting.get(key(r));
if (sent === undefined) return false;
if (r.state === 'working') return true;
const s = Date.parse(sent), a = Date.parse(r.lastActivity);
return Number.isFinite(s) && Number.isFinite(a) && a < s;
}
const canReply = r => !window.MosaicOrg && !r.connector && r.registered && r.registered.alive !== false && r.registered.tmux?.session;
const row = id => data?.sessions.find(r => key(r) === id);
const announce = text => { $('announce').textContent = text; };
// Appearance (stream S4, PLAN C5). Per field: this browser's override for the organization, then the organization's
// saved value (the business file's `appearance`), then the built-in default, Harbor in the dark. Harbor is drawn by
// tokens.css alone, by data-palette and data-mode; System removes data-mode, so the OS setting picks light or dark.
// Any other installed theme adds its validated colours to <html> through the CSSOM: nothing the server sends is
// parsed as CSS or HTML. A theme that cannot be shown renders Harbor with a warning, and no stored value is changed.
const darkPreference = window.matchMedia('(prefers-color-scheme: dark)');
const APPEARANCE_KEY = 'mosaic-console-appearance', LAST_KEY = 'mosaic-console-appearance-last';
const orgKey = id => `${APPEARANCE_KEY}:${id}`;
// #1873 SP2: the system dashboard is no organization's page. It shows the system theme: this browser's
// own choice made there, else the default, never the theme of the organization opened last.
const SYSTEM_KEY = 'mosaic-console-appearance-system';
// SP3: display.js owns which addresses are system pages (the dashboard and #/inbox); the bare address is one before it normalizes.
const onSystem = () => !!window.MosaicOrg && ((!/^#\/orgs\//.test(location.hash) && ['', '/'].includes(location.hash.replace(/^#/, '').split('?')[0])) || window.MosaicOrg.system?.() === true);
const store = {
read(k) { try { const v = JSON.parse(localStorage.getItem(k)); return v && typeof v === 'object' && !Array.isArray(v) ? v : null; } catch { return null; } },
write(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); return true; } catch { return false; } },
remove(k) { try { localStorage.removeItem(k); return true; } catch { return false; } },
};
const orgId = v => typeof v === 'string' && v.length > 0 && v.length <= 64;
// org: null until the Console knows which organization it shows. Then the override lives under that organization's own key;
// before that, and for a Console with no organization, it is the browser-wide record this page has always kept.
let org = null, override = null, themes = null, themesUnavailable = false, current = null, applied = [], system = false;
const shown = () => (system ? null : org);
// Kept in memory too: a choice storage refused still shows until reload, as an organization's does.
let systemOverride = Brand.appearanceOf(store.read(SYSTEM_KEY));
const readOverride = () => {
if (org) return Brand.appearanceOf(store.read(orgKey(org.id)));
const v = store.read(APPEARANCE_KEY);
return v && Brand.appearanceOf({ theme: v.theme ?? v.palette, mode: v.mode });
};
const nameOf = id => (themes || []).find(t => t.id === id)?.displayName || (id === Brand.DEFAULT_THEME ? 'Harbor' : String(id));
function syncThemeSwitch() {
const dark = current.mode === 'dark' || current.mode === 'dim' || (current.mode === 'system' && darkPreference.matches);
$('theme-switch').setAttribute('aria-checked', String(dark));
}
function paintNotices() {
const w = current.warning, banner = $('theme-warning'), cue = $('org-cue'), label = shown()?.label;
banner.hidden = !w;
if (w) {
const asked = String(w.theme).slice(0, 64), kept = w.source === 'browser' ? 'The choice is kept.' : 'The saved value is unchanged.';
banner.querySelector('p').textContent = w.code === 'unavailable'
? `The installed themes could not be read, so Harbor is shown instead of “${asked}”. ${kept}`
: w.source === 'browser'
? `This browser is set to the theme “${asked}”, which is not installed or is not valid. Harbor is shown instead. ${kept}`
: `${label ?? 'The organization'} saves the theme “${asked}”, which is not installed or is not valid. Harbor is shown instead. ${kept}`;
$('theme-clear').hidden = w.source !== 'browser';
$('theme-clear').textContent = label ? `Use ${label}’s theme` : 'Use the default theme';
}
// Colour is never the only cue to which organization this is: whenever the theme is not the built-in one, the name is written out.
cue.hidden = !(shown() && (current.theme !== Brand.DEFAULT_THEME || w));
if (!cue.hidden) cue.textContent = w ? `${label} · Harbor shown instead of “${String(w.theme).slice(0, 64)}”` : `${label} · ${nameOf(current.theme)} theme · ${current.themeSource === 'browser' ? 'your choice in this browser' : 'set by the organization'}`;
}
function paint() {
system = onSystem();
current = Brand.resolveAppearance({ themes, unavailable: themesUnavailable, saved: shown()?.saved ?? null, override: system ? systemOverride : override });
const root = document.documentElement;
root.dataset.palette = current.theme;
if (current.mode === 'system') delete root.dataset.mode; else root.dataset.mode = current.mode;
for (const name of applied) root.style.removeProperty(name);
applied = [];
for (const [name, value] of (current.entry && Brand.themeProperties(current.entry, current.mode, darkPreference.matches)) || []) { root.style.setProperty(name, value); applied.push(name); }
if (!root.getAttribute('style')) root.removeAttribute('style');
const options = [Brand.DEFAULT_THEME, ...(themes || []).map(t => t.id).filter(id => id !== Brand.DEFAULT_THEME)];
if (!options.includes(current.theme)) options.push(current.theme);
$('palette').replaceChildren(...options.map(id => new Option(nameOf(id), id)));
$('palette').value = current.theme; $('mode').value = current.mode;
syncThemeSwitch(); paintNotices();
}
function showAppearance(stored = true) {
paint();
document.dispatchEvent(new CustomEvent('mosaic-theme-change', {detail: {palette: current.theme, mode: current.mode, stored, warning: current.warning, picked: current.warning ? null : current.theme}}));
}
function seedFromLegacy() {
const old = store.read(APPEARANCE_KEY);
if (!old) return;
// The old record goes to the first organization this browser shows, once, and is removed. Another organization starts from its own saved theme.
const seed = Brand.legacySeed(old);
if (seed) { store.write(orgKey(org.id), seed); override = seed; }
store.remove(APPEARANCE_KEY);
}
window.MosaicAppearance = {
// Resolves once /api/themes and /api/business have answered or failed and the page shows the result.
ready: null,
// The installed, valid themes as the server listed them, or null until /api/themes has answered.
themes: () => themes && themes.map(t => ({ id: t.id, displayName: t.displayName, tokens: t.tokens })),
state: () => { const o = shown(), v = system ? systemOverride : override; return { theme: current.theme, mode: current.mode, requested: current.requested, themeSource: current.themeSource, modeSource: current.modeSource, warning: current.warning, provisional: current.provisional, organization: o && { id: o.id, label: o.label }, saved: o?.saved ?? null, override: v && { ...v } }; },
// Writes this browser's override for the organization (a theme, a mode, or both). false when storage refused it; the page still shows it until reload.
set(patch) {
if (onSystem()) { const next = Brand.appearanceOf({ ...(systemOverride || {}), ...patch }), ok = next ? store.write(SYSTEM_KEY, next) : true; systemOverride = next; showAppearance(ok); return ok; }
const next = Brand.appearanceOf({ ...(override || {}), ...patch });
const ok = next ? (org ? store.write(orgKey(org.id), next) : store.write(APPEARANCE_KEY, next)) : true;
override = next; showAppearance(ok); return ok;
},
// Removes the override: the organization's saved value, or else the default, shows again.
clear() { if (onSystem()) { const ok = store.remove(SYSTEM_KEY); systemOverride = null; showAppearance(ok); return ok; } const ok = org ? store.remove(orgKey(org.id)) : store.remove(APPEARANCE_KEY); override = null; showAppearance(ok); return ok; },
// The seam for the organization switcher (stream S5): call it with the organization now shown and its saved appearance.
organization(id, saved, label) {
if (!orgId(id)) return;
const changed = !org || org.id !== id || !org.confirmed;
org = { id, label: orgId(label) ? label : id, saved: Brand.appearanceOf(saved), confirmed: true };
if (changed) { override = readOverride(); if (!override) seedFromLegacy(); }
store.write(LAST_KEY, { org: org.id, label: org.label, saved: org.saved });
showAppearance();
},
};
// First paint from what this browser already knows: the organization it last showed, with that organization's saved value, and this browser's override for it.
const last = store.read(LAST_KEY);
if (last && orgId(last.org)) org = { id: last.org, label: orgId(last.label) ? last.label : last.org, saved: Brand.appearanceOf(last.saved), confirmed: false };
override = readOverride();
paint();
document.dispatchEvent(new CustomEvent('mosaic-theme-change', {detail: {palette: current.theme, mode: current.mode, stored: true, warning: null, picked: current.theme}}));
// The open organization's saved appearance, read again when another organization opens (#1873 SP1).
const readBusiness = async () => {
try {
const { ok, body } = await getJSON('/api/business');
if (ok && orgId(body?.business?.id)) return window.MosaicAppearance.organization(body.business.id, body.business.appearance, body.business.id);
} catch (err) { if (err?.signedOut) return; }
// No fresh answer: keep the organization this browser last showed for its own override, but not its stale saved value.
if (org && !org.confirmed) { org.saved = null; showAppearance(); }
};
document.addEventListener('mosaic-org-switch', () => { readBusiness(); });
// The dashboard and an organization page share the shell: moving between them repaints the theme.
const repaintScope = () => { if (onSystem() !== system) showAppearance(); };
window.addEventListener('hashchange', repaintScope);
window.MosaicOrg?.ready?.then(repaintScope);
window.MosaicAppearance.ready = (async () => {
await Promise.allSettled([
(async () => {
try {
const { ok, body } = await getJSON('/api/themes');
if (!ok || !Array.isArray(body?.themes)) throw new Error('themes');
themes = body.themes.filter(t => Brand.usableTheme(t));
} catch (err) { if (err?.signedOut) return; themes = []; themesUnavailable = true; }
showAppearance();
})(),
readBusiness(),
]);
})();
$('palette').onchange = e => window.MosaicAppearance.set({ theme: e.target.value });
$('mode').onchange = e => window.MosaicAppearance.set({ mode: e.target.value });
$('theme-clear').onclick = () => window.MosaicAppearance.clear();
$('mobile-refresh').onclick = () => $('refresh').click();
$('theme-switch').onclick = () => { $('mode').value = $('theme-switch').getAttribute('aria-checked') === 'true' ? 'light' : 'dark'; $('mode').dispatchEvent(new Event('change', { bubbles: true })); };
// The device's setting only matters under System: re-read the theme's colours for the new side.
darkPreference.addEventListener('change', () => { if (current.mode === 'system') paint(); else syncThemeSwitch(); });
function seenButton(r) {
if (window.MosaicOrg) return '<span class="muted">Seen changes unavailable</span>';
if (!['waiting', 'error'].includes(r.state) || !r.lastActivity) return '';
return `<button type="button" class="btn" data-seen="${esc(key(r))}" data-intent="${r.seen ? 'unsee' : 'seen'}" aria-label="${r.seen ? 'Unsee' : 'Mark seen'} ${esc(r.agent)}">${r.seen ? 'Unsee' : 'Seen'}</button>`;
}
const historyButton = r => `<button type="button" class="btn conv-open" data-history="${esc(key(r))}" aria-label="History for ${esc(r.agent)}">History</button>`;
const openButton = r => `<button type="button" class="session-open" data-open="${esc(key(r))}" aria-controls="inspector" aria-expanded="${selected === key(r)}">${esc(r.agent)}</button>`;
const activityCell = r => relaunchNotice(r) ? esc(relaunchNotice(r)) : activity(r) ? `${esc(activity(r))}${activity(r) === r.lastActivity ? '' : `<span class="source">${esc(r.lastActivity)}</span>`}` : 'unknown';
function cards(rows) {
if (!rows.length) return '<p class="muted">Nothing here.</p>';
return `<ul class="waiting">${rows.map(r => `<li class="wait-item"><div class="wait-head">${openButton(r)} ${badge(r.state)}${connectorStatus(r)}</div><p class="small muted">${esc(r.project)} · ${esc(r.activeProject || 'unknown')}</p><p>${esc(r.task || 'unknown')}${source(r.taskSource)}${setBy(r)}</p><p class="preview">${esc(relaunchNotice(r) || r.lastError || r.lastAssistantText || 'No assistant text yet.')}</p><div class="actions"><span class="small muted" data-board-age="${esc(key(r))}">${esc(relaunchNotice(r) || (activity(r) ? `Last activity ${activity(r)}` : 'No activity'))}</span><span>${historyButton(r)}${seenButton(r)}</span></div></li>`).join('')}</ul>`;
}
function table(rows) {
if (!rows.length) return `<div class="empty"><b>No sessions match these filters.</b><p>${data.sessions.length ? 'Clear Hide offline or Hide seen, or pick All projects, to see the rest.' : 'Sessions appear here when the board scan finds an agent session on this machine.'}</p></div>`;
return `<div class="table-wrap" tabindex="0" role="region" aria-label="Session table, scroll horizontally for all columns"><table class="sessions"><thead><tr>${['Agent', 'State', 'Task', 'Active project', 'Workspace', 'Model', 'Registered', 'Last activity'].map(h => `<th scope="col">${h}</th>`).join('')}</tr></thead><tbody>${rows.map(r => `<tr data-row="${esc(key(r))}"${selected === key(r) ? ' class="is-selected"' : ''}><td>${openButton(r)}<span class="source">${esc(r.project)}</span>${historyButton(r)}</td><td>${badge(r.state)}${connectorStatus(r)}${r.seen ? '<span class="source">seen</span>' : ''}</td><td class="task">${esc(r.task || 'unknown')}${source(r.taskSource)}${setBy(r)}</td><td>${esc(r.activeProject || 'unknown')}${source(r.activeProjectSource)}</td><td>${esc(r.workspace || 'unknown')}${source(r.workspaceSource)}</td><td>${esc(r.model || 'unknown')}<span class="source">${esc(r.provider)}</span></td><td>${r.registered ? r.registered.alive === false ? 'stale' : 'registered' : 'no'}</td><td data-board-activity="${esc(key(r))}">${activityCell(r)}</td></tr>`).join('')}</tbody></table></div>`;
}
function registered(r) {
const reg = r.registered;
if (!reg) return 'No registration';
return `${reg.alive === false ? 'Stale; derived values shown. ' : ''}Started ${reg.startedAt || 'unknown'}; task updated ${reg.updatedAt || 'unknown'}; harness ${reg.harness || 'unknown'}; pid ${reg.pid || 'unknown'}; tmux ${reg.tmux?.session || 'unknown'}${reg.tmux?.socket ? ' on ' + reg.tmux.socket : ''}; layout ${reg.layout || 'unknown'}`;
}
function inspect() {
const r = row(selected);
$('inspector').hidden = !selected;
document.body.classList.toggle('has-inspector', !!selected);
if (!selected) return;
if (!r) { $('inspection').innerHTML = '<p>This session is no longer in the board scan. Its draft is kept until this page closes.</p>'; return; }
$('inspector-title').textContent = r.agent;
const fields = [ ['State', r.state], ['Project', r.project], ['Task', r.task || 'unknown'], ['Task source', labels[r.taskSource] || r.taskSource || 'unknown'], ['Task set by', r.taskSetBy ? `${r.taskSetBy} (as claimed by the caller, not verified)` : 'not applicable (task is not from a registration)'], ['Active project', r.activeProject || 'unknown'], ['Workspace', r.workspace || 'unknown'], ['Model', [r.provider, r.model].filter(Boolean).join('/') || 'unknown'], ['Registered', registered(r)], [r.relaunchedAt ? 'Historical last activity' : 'Last activity', !r.lastActivity ? 'unknown' : activity(r) === r.lastActivity ? r.lastActivity : `${activity(r)} (${r.lastActivity})`] ];
if (r.relaunchedAt) fields.unshift(['Current activity', relaunchNotice(r)]);
if (r.connector) fields.push(['Connector', `${r.connector.braked === true ? 'braked (STOP)' : r.connector.braked === false ? 'not braked' : 'brake unknown'}; owner ${r.connector.ownerState}`]);
const receipt = receipts.get(selected);
$('inspection').innerHTML = `<dl class="kv">${fields.map(([k, v]) => `<dt>${k}</dt><dd>${esc(v)}</dd>`).join('')}${pending(r) ? `<dt>Reply</dt><dd>Waiting for a reply to your message sent ${esc(awaiting.get(selected))}. The page checks every 10 seconds${paused ? ' once you resume' : ''}.</dd><dt>${r.relaunchedAt ? 'Historical assistant text' : 'Previous assistant text'}, before your message</dt>` : `<dt>${r.relaunchedAt ? 'Historical last assistant text' : 'Last assistant text'}</dt>`}<dd><pre class="last-text">${esc(r.lastAssistantText || 'No assistant text yet.')}</pre></dd>${r.lastError ? `<dt>${r.relaunchedAt ? 'Historical last error' : 'Last error'}</dt><dd>${esc(r.lastError)}</dd>` : ''}</dl>${historyButton(r)}${seenButton(r)}${canReply(r) ? `<form class="reply-form"><label for="reply">Reply to ${esc(r.agent)}</label><textarea id="reply" maxlength="2000" rows="3" placeholder="Message this seat">${esc(drafts.get(selected) || '')}</textarea><button class="btn primary" type="submit" ${sending.has(selected) ? 'disabled' : ''}>${sending.has(selected) ? 'Sending…' : 'Send'}</button></form>` : `<p class="muted">${r.connector ? 'Board replies disabled for Discord connectors' : 'reply needs a registered seat'}</p>`}${receipt ? `<p class="receipt ${receipt.delivered ? '' : 'failed'}" role="status">${esc(receipt.delivered ? `delivered ${receipt.sentAt} to tmux ${receipt.session}` : `failed${receipt.exitCode == null ? '' : ' (exit ' + receipt.exitCode + ')'}: ${receipt.stderr || receipt.error || 'no output'}`)}</p>` : ''}`;
}
// Conversation view (#1507, CHAT-02): the full read-only history from the board's
// /api/conversations and /api/conversation routes. Session content is set with
// textContent only, so it never creates an element, handler or navigation.
// Markdown shows as its source text. New entries arrive by polling a follow cursor.
let conv = null, convGen = 0;
const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f]/g, UNSEEN = /[\u0080-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
// C0 controls and DEL show as control pictures. C1 controls and bidi controls and marks have no picture
// and show as [U+XXXX]. Newlines and tabs stay.
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 node = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = inert(text); return e; };
const ROLES = { user: 'User', assistant: 'Assistant', tool: 'Tool', notice: 'Notice', compaction: 'Compaction' };
// The CHAT-01 field that holds each block type's string. Fragments of one block concatenate in order.
const FIELDS = { text: 'text', thinking: 'text', 'tool-call': 'argumentsText', 'tool-result': 'text', compaction: 'summary' };
const convURL = params => '/api/conversation?' + new URLSearchParams(params);
async function getJSON(path) {
if (out()) throw signedOut();
const res = await fetch(path, { cache: 'no-store', redirect: 'manual' });
if (res.type === 'opaqueredirect') { signOut(); throw signedOut(); }
let body; try { body = await res.json(); } catch { body = { error: `HTTP ${res.status}` }; }
if (signInRequired(res, body)) { sso = true; signOut(); throw signedOut(); }
return { ok: res.ok, body };
}
function blockNode(b) {
if (b.type === 'text') return node('div', 'conv-text', b.value);
if (b.type === 'attachment') return node('p', 'small muted', 'Attachment not shown.');
if (!FIELDS[b.type]) return node('p', 'small muted', `A ${b.type} block is not shown.`);
const summary = b.type === 'thinking' ? (b.visibility === 'unavailable' ? 'Thinking (not available)' : 'Thinking')
: b.type === 'tool-call' ? `Tool call: ${b.name}` : b.type === 'tool-result' ? (b.isError ? 'Tool result (error)' : 'Tool result') : 'Earlier context was compacted. Summary';
const d = node('details', `conv-${b.type}`); d.append(node('summary', '', summary), node('pre', 'conv-pre', b.value));
return d;
}
function drawMessage(m) {
const li = node('li', `turn conv-turn conv-${m.role}`), time = node('time', '', m.createdAt);
time.dateTime = m.createdAt; li.append(node('span', 'who', ROLES[m.role] || m.role), time);
const open = m.el ? [...m.el.querySelectorAll('details')].map(d => d.open) : [];
let i = 0;
for (const b of m.blocks) if (b) { const n = blockNode(b); if (n.tagName === 'DETAILS') n.open = open[i++] ?? false; li.append(n); }
if (m.el) m.el.replaceWith(li); else $('conv-log').append(li);
m.el = li;
}
function addEntries(entries) {
const touched = new Set();
for (const e of entries) {
let m = conv.messages.get(e.message);
if (!m) { m = { role: e.role, createdAt: e.createdAt, blocks: [], el: null }; conv.messages.set(e.message, m); }
for (const c of e.content) { const b = m.blocks[c.block] ??= { ...c, value: '' }; if (FIELDS[c.type]) b.value += c[FIELDS[c.type]]; }
touched.add(m);
}
for (const m of touched) drawMessage(m);
return touched.size;
}
function drawMarkers() {
const box = $('conv-markers'); box.replaceChildren();
for (const [kind, m] of conv.markers) {
const d = node('div', 'notice notice-attn conv-marker'); d.dataset.marker = kind; d.append(node('p', '', m.text));
if (m.action) { const b = node('button', 'btn', m.action.label); b.type = 'button'; b.dataset.convAction = m.action.id; d.append(b); }
box.append(d);
}
}
function marker(kind, text, action) { if (conv.markers.get(kind)?.text === text) return; conv.markers.set(kind, { text, action }); drawMarkers(); announce(text); }
function unmark(kind) { if (conv.markers.delete(kind)) drawMarkers(); }
function convStatus(text) {
$('conv-status').textContent = text ?? `${conv.messages.size} messages · ${!conv.follow ? 'not checking for new entries' : paused ? 'checking for new entries paused' : 'checks for new entries every 10 seconds'}`;
}
function apply(body) {
conv.branch = body.page.branch;
const added = addEntries(body.page.entries);
const v = body.view;
if (v.incomplete) marker('incomplete', 'The last line of this session is still being written. It shows here once it is complete.'); else unmark('incomplete');
if (v.defaultBranch !== v.branch) marker('branch', 'This conversation continued on another branch. This view stays on the branch it opened.', { id: 'latest', label: 'Open the latest branch' });
return added;
}
// A refusal with reconcile keeps everything already shown and stops polling. Nothing switches silently.
function refused(res) {
const code = res.body.refusal?.code;
conv.follow = null;
if (res.body.refusal?.reconcile) marker('reconcile', `This view is out of date (${code}): ${res.body.error}. The history below is what was loaded before.`, { id: 'reload', label: 'Reload conversation' }), convStatus();
else convStatus(`History unavailable: ${res.body.error || 'unknown error'}${code ? ` (${code})` : ''}.`);
}
const nearEnd = () => $('conv-log').getBoundingClientRect().bottom <= innerHeight + 300;
// Reads pages from `res` until the snapshot ends. Returns false when the view changed or a page was refused.
async function readPages(c, gen, res, onPage) {
for (;;) {
if (gen !== convGen) return false;
if (!res.ok) { refused(res); return false; }
onPage(apply(res.body));
if (!res.body.cursor) { c.follow = res.body.follow?.id ?? null; return true; }
res = await getJSON(convURL({ id: c.id, branch: c.branch, cursor: res.body.cursor.id }));
}
}
function showConversation(on) {
$('conversation').hidden = !on; $('board-view').hidden = on;
document.body.classList.toggle('has-conversation', on);
}
function convForm() {
if (!conv) return;
const r = row(conv.row), can = !!r && !!canReply(r), receipt = receipts.get(conv.row);
$('conv-form').hidden = !can; $('conv-no-reply').hidden = can;
$('conv-no-reply').textContent = !r ? 'This session is no longer in the board scan.' : r.connector ? 'Board replies disabled for Discord connectors' : 'reply needs a registered seat';
if (r) $('conv-reply-label').textContent = `Reply to ${r.agent}`;
$('conv-send').disabled = sending.has(conv.row); $('conv-send').textContent = sending.has(conv.row) ? 'Sending…' : 'Send';
$('conv-receipt').hidden = !receipt;
if (receipt) { $('conv-receipt').className = `conv-receipt ${receipt.delivered ? '' : 'failed'}`; $('conv-receipt').textContent = receipt.delivered ? `delivered ${receipt.sentAt} to tmux ${receipt.session}` : `failed${receipt.exitCode == null ? '' : ' (exit ' + receipt.exitCode + ')'}: ${receipt.stderr || receipt.error || 'no output'}`; }
// The board's newest file for this seat changed after the view opened: a relaunch. The view keeps its file.
if (conv.sessionId && r?.sessionId && r.sessionId !== conv.sessionId) marker('newer', conv.newerUnread ? 'A newer session started for this seat, but its history is not readable yet. This view stays on the session you opened.' : 'A newer session started for this seat. This view stays on the session you opened.', { id: 'newest', label: 'Open the newest session' });
}
// opts.branch reopens that branch (Reload). opts.from and opts.sessionId come from "Open the newest session".
async function openConversation(rowKey, pick = null, returnTo = conv?.returnFocus, opts = {}) {
const gen = ++convGen, r = row(rowKey), sameRow = conv?.row === rowKey;
conv = { row: rowKey, id: null, branch: null, follow: null, messages: new Map(), markers: new Map(), sessionId: null, loading: true, polling: false, returnFocus: returnTo };
selected = null; render(); showConversation(true);
$('conv-title').textContent = r ? `${r.agent} conversation` : 'Conversation';
$('conv-meta').textContent = ''; $('conv-pick').replaceChildren(); $('conv-log').replaceChildren(); drawMarkers(); convForm();
if (!sameRow) $('conv-reply').value = drafts.get(rowKey) || '';
convStatus('Loading history…');
const slash = rowKey.lastIndexOf('/'), project = r?.project ?? rowKey.slice(0, slash), agent = r?.agent ?? rowKey.slice(slash + 1);
const c = conv;
try {
const cat = await getJSON('/api/conversations');
if (gen !== convGen) return;
if (!cat.ok) { convStatus(`History unavailable: ${cat.body.error || 'the board refused the catalogue'}.`); return; }
const mine = cat.body.conversations.filter(x => x.project === project && x.seat === agent);
const readable = mine.filter(x => x.availability === 'available');
const choice = mine.find(x => x.conversation === pick) ?? readable[0] ?? mine[0];
$('conv-pick').replaceChildren(...mine.map(x => { const o = node('option', '', `${x.title || 'Untitled'} · ${x.lastActivityAt || x.conversationCreatedAt || 'no activity'}${x.availability === 'available' ? '' : ` (${x.unsupportedReason || x.refusal?.code || x.availability})`}`); o.value = x.conversation; return o; }));
$('conv-pick').disabled = mine.length < 2;
if (!choice) { convStatus('No readable history for this seat. Only repository Pi seats have history here.'); return; }
$('conv-pick').value = c.id = choice.conversation;
$('conv-meta').textContent = `${project} · ${choice.title || 'Untitled'} · started ${choice.conversationCreatedAt || 'unknown'}`;
if (choice.availability !== 'available') { convStatus(choice.unsupportedReason === 'unsupported-harness' ? `History for the ${choice.harness} harness is not available yet.` : `History unavailable (${choice.refusal?.code || choice.availability}).`); return; }
// Relaunch detection only makes sense for the newest session, the one the board row shows. If "newest"
// lands on the file already open, the board's newer file is not readable yet: keep the marker.
c.newerUnread = !!opts.from && opts.from === choice.conversation;
if (choice === readable[0]) c.sessionId = c.newerUnread ? opts.sessionId : r?.sessionId ?? null;
let first = await getJSON(convURL(opts.branch ? { id: c.id, branch: opts.branch } : { id: c.id }));
// The branch this view was on is gone: open the default branch and say so.
if (!first.ok && opts.branch && first.body.refusal?.code === 'unknown-branch') {
first = await getJSON(convURL({ id: c.id }));
if (gen !== convGen) return;
if (first.ok) marker('gone', 'The branch this view was on is no longer in the session. This view shows the latest branch.');
}
const done = await readPages(c, gen, first, () => convStatus(`Loading history… ${c.messages.size} messages`));
if (gen !== convGen) return;
if (done) convStatus();
$('conv-log').lastElementChild?.scrollIntoView({ block: 'end' });
convForm();
} catch (err) { if (gen === convGen) convStatus(`History unavailable: ${err.message}.`); }
finally { c.loading = false; }
}
async function pollConversation() {
const c = conv, gen = convGen;
if (!c || c.loading || c.polling || !c.follow) return;
c.polling = true;
try {
const atEnd = nearEnd();
let added = 0;
const done = await readPages(c, gen, await getJSON(convURL({ id: c.id, branch: c.branch, cursor: c.follow })), n => { added += n; });
if (gen !== convGen) return;
if (done) convStatus();
if (added && atEnd) $('conv-log').lastElementChild?.scrollIntoView({ block: 'end' });
} catch (err) { if (gen === convGen) convStatus(`Could not check for new entries: ${err.message}. The view keeps what it has; the next check tries again.`); }
finally { c.polling = false; }
}
function closeConversation() {
const back = conv?.returnFocus; convGen++; conv = null; showConversation(false); render();
if (back) restore(back);
if (document.activeElement === document.body) $('main').focus();
}
$('conv-back').onclick = closeConversation;
$('conv-pick').onchange = e => { if (conv) openConversation(conv.row, e.target.value); };
// Restore by data attribute equality, never interpolate API ids into selectors.
function focusSnapshot() {
const a = document.activeElement;
return { id: a?.id, open: a?.dataset.open, seen: a?.dataset.seen, history: a?.dataset.history, project: a?.dataset.project, container: a?.closest('[id]')?.id, start: a?.selectionStart, end: a?.selectionEnd };
}
function restore(f) {
let el = f.id ? $(f.id) : null;
for (const attr of ['open', 'seen', 'history', 'project']) if (f[attr] !== undefined) {
el = [...document.querySelectorAll(`[data-${attr}]`)].find(e => e.dataset[attr] === f[attr] && e.closest('[id]')?.id === f.container);
}
if (el && !el.closest('[hidden]')) { el.focus({ preventScroll: true }); if (f.start != null) el.setSelectionRange(f.start, f.end); }
}
function render() {
if (!data) return;
const focus = focusSnapshot();
const projects = [...new Set(data.sessions.map(r => r.project))].sort();
if (project && !projects.includes(project)) project = null;
$('projects').innerHTML = `<ul class="tree-list"><li><button type="button" data-project="" aria-pressed="${project === null}">All projects <span class="count">${data.sessions.length}</span></button></li>${projects.map(p => `<li><button type="button" data-project="${esc(p)}" aria-pressed="${project === p}">${esc(p)} <span class="count">${data.sessions.filter(r => r.project === p).length}</span></button></li>`).join('')}</ul>`;
const waiting = data.sessions.filter(r => r.waitingOnYou);
const seen = data.sessions.filter(r => r.seen);
$('waiting-count').textContent = waiting.length; $('waiting').innerHTML = waiting.length ? cards(waiting) : '<div class="empty"><b>Nothing is waiting on you.</b><p>A session shows here when its agent stops on a question or an error and you have not marked it seen.</p></div>';
$('seen-count').textContent = seen.length; $('seen').innerHTML = cards(seen);
const group = data.sessions.filter(r => !project || r.project === project);
const visible = group.filter(r => !($('hide-offline').checked && r.state === 'offline') && !($('hide-seen').checked && r.seen));
$('session-count').textContent = visible.length === group.length ? String(group.length) : `${visible.length} of ${group.length}`;
$('sessions').innerHTML = table(visible);
$('footer').textContent = data.sessions.length ? Object.entries(data.counts || {}).map(([s, n]) => `${s} ${n}`).join(' · ') : 'No machine sessions';
$('status').textContent = `Scanned ${window.MosaicLocalTime(data.generatedAt)} · ${paused ? 'auto-refresh paused' : 'refresh every 10s'}`;
fresh(); inspect(); convForm(); if (conv) convStatus(); restore(focus);
}
// Freshness line in the command bar: when the board last scanned, and warning words when the last refresh failed.
function fresh() {
if (!machine) { $('fresh-board').textContent = 'Machine sessions hidden'; return; }
const at = Date.parse(data?.generatedAt), ago = Number.isFinite(at) ? age(Math.max(0, Math.round((Date.now() - at) / 1000))) : null;
if (!data) { $('fresh-board').innerHTML = failed === 'refused' ? 'Board <span class="warn">not read: refused</span>' : failed ? 'Board <span class="warn">not read: the read failed</span>' : 'Board not read yet'; return; }
const scan = `Board scanned <b>${esc(Number.isFinite(at) ? `${new Date(at).toISOString().slice(11, 19)} UTC` : 'unknown')}</b>${ago ? ` (${ago} ago)` : ''}`;
$('fresh-board').innerHTML = failed ? `${scan} · <span class="warn">stale: the last refresh failed</span>` : scan;
}
setInterval(() => { if (data) fresh(); }, 5000);
async function api(path, value) {
if (out()) throw signedOut();
const res = await fetch(path, value === undefined ? { cache: 'no-store', redirect: 'manual' } : { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(value), redirect: 'manual' });
if (res.type === 'opaqueredirect') { signOut(); throw signedOut(); }
const result = await res.json();
if (signInRequired(res, result)) { sso = true; signOut(); throw signedOut(); }
if (!res.ok) throw Object.assign(new Error(result.error || `HTTP ${res.status}`), { status: res.status });
return result;
}
function accept(value) {
if (out()) return; // a read that was in flight when the page signed out
if (!value || !Array.isArray(value.sessions) || value.sessions.some(r => !r || typeof r.project !== 'string' || typeof r.agent !== 'string')) throw new Error('Invalid board session data');
const canonical = v => Array.isArray(v) ? v.map(canonical) : v && typeof v === 'object'
? Object.fromEntries(Object.keys(v).sort().map(k => [k, canonical(v[k])])) : v;
const material = board => JSON.stringify(canonical({ counts: board.counts, sessions: board.sessions.map(({ageSeconds, scannedAt, ...row}) => row) }));
const unchanged = data && material(data) === material(value);
data = value; failed = false; $('error').hidden = true; $('error').className = 'banner err';
$('board-refused').hidden = true; document.body.classList.remove('board-refused');
for (const id of awaiting.keys()) { const r = row(id); if (r && !pending(r)) awaiting.delete(id); }
if (unchanged) {
for (const r of data.sessions) {
for (const el of document.querySelectorAll('[data-board-age]')) if (el.dataset.boardAge === key(r)) { const text = relaunchNotice(r) || (activity(r) ? `Last activity ${activity(r)}` : 'No activity'); if (el.textContent !== text) el.textContent = text; }
for (const el of document.querySelectorAll('[data-board-activity]')) if (el.dataset.boardActivity === key(r)) { const html = activityCell(r); if (el.innerHTML !== html) el.innerHTML = html; }
}
const selectedRow = row(selected);
const field = [...$('inspection').querySelectorAll('dt')].find(el => /^(Historical )?Last activity$/.test(el.textContent))?.nextElementSibling;
if (selectedRow && field) { const text = !selectedRow.lastActivity ? 'unknown' : activity(selectedRow) === selectedRow.lastActivity ? selectedRow.lastActivity : `${activity(selectedRow)} (${selectedRow.lastActivity})`; if (field.textContent !== text) field.textContent = text; }
$('status').textContent = `Scanned ${window.MosaicLocalTime(data.generatedAt)} · ${paused ? 'auto-refresh paused' : 'refresh every 10s'}`;
fresh();
} else render();
}
// A refusal (403) fails closed: the last data is dropped, not kept or shown as current, and so is
// everything drawn from it: the cards, the table, the inspector, an open conversation and its
// history, the project tree, the counts and the footer. Any other failure keeps the last data with
// its scan time. With no data, from a refusal or before the first scan, the board is drawn empty
// and says why, so a later failure never brings back old rows.
function error(err) {
if (err.signedOut || out()) return;
const refused = err.status === 403, focused = document.activeElement !== document.body;
failed = refused ? 'refused' : true; $('error').hidden = false;
if (refused) { data = null; selected = null; project = null; if (conv) { $('conv-log').replaceChildren(); closeConversation(); } }
if (!data) {
const why = refused ? 'the board refused the read' : 'the read failed';
$('projects').innerHTML = `<p class="muted">Not read: ${why}.</p>`;
for (const id of ['waiting', 'seen', 'sessions']) $(id).replaceChildren();
for (const id of ['waiting-count', 'seen-count', 'session-count']) $(id).textContent = '–';
$('footer').textContent = `Board not read: ${refused ? 'refused' : 'the read failed'}`;
$('status').textContent = `Not read: ${why}`;
inspect();
}
$('error').className = refused ? 'banner ref' : 'banner err';
$('board-refused').hidden = !refused; document.body.classList.toggle('board-refused', refused);
$('error').innerHTML = refused
? `<p><b>The board refused the read.</b> refused: <code>${esc(err.message)}</code> Board: ${esc(board)}. Console shows nothing rather than a guess. Use Refresh to try again.</p>`
: `<p><b>${esc(err.message)}</b> Board: ${esc(board)}. ${data ? `Showing last known data.${data.generatedAt ? ` Scanned ${esc(data.generatedAt)}.` : ''}` : 'No board data loaded.'} Use Refresh to try again.</p>`;
fresh();
// Clearing the board or closing a conversation can remove what had focus: give it to the page.
if (focused && document.activeElement === document.body) $('main').focus();
}
function schedule() { clearTimeout(timer); if (!paused && machine && !out()) timer = setTimeout(refresh, 10000); }
// A board answer that arrives after the toggle went off is dropped, not drawn.
// vikunja:19/302: "bus down: organization file invalid", with the reason, the file and the last
// good load, from the status `mosaic bus start` left. textContent only. Nothing here retries.
async function busDown() {
const box = $('bus-down');
// E2E5 review P2: the organization list is read first and on its own, so a failed bus-status read
// (likely when the bus is down) still refreshes the list, its banner and the Settings Start control.
// #1873 SP1: the dashboard lists every organization's bus on its own rows; this banner is an organization page's.
if (window.MosaicOrg && window.MosaicOrg.route().split('?')[0] === '/dashboard') { box.hidden = true; return; }
// An answer about an organization that is no longer open is dropped: the new one's read draws the banner.
// So is one drawn for a page left while it was read (#1873 SP2: the organization page draws none).
const where = () => window.MosaicOrg?.route().split('?')[0] === '/organization';
const asked = window.MosaicOrg?.id ?? null, onPage = where(), stale = () => (window.MosaicOrg?.id ?? null) !== asked || where() !== onPage;
if (window.MosaicOrg) {
const org = (await window.MosaicOrg.readList()).find(row => row.id === asked);
if (stale()) return;
// #1873 SP2: the organization's own page says it in its down banner, with the restart action: one banner, not two.
if (org?.busHealthy === false && onPage) { box.hidden = true; return; }
if (org?.busHealthy === false) { box.textContent = 'Bus unavailable'; box.hidden = false; window.MosaicConsole?.attachBus(box, 'Restart the bus'); return; }
}
try {
const s = await api('/api/bus-status');
if (stale()) return;
if (!s.down) { box.hidden = true; return; }
const b = s.boot;
box.replaceChildren(node('b', '', 'Bus down: organization file invalid. '), node('span', '', `${b.reason} `), node('span', 'small muted', `File ${b.file}. Refused at ${b.at}. Last good load: ${b.lastGood ?? 'none'}. Fix the file, then restart the bus.`));
box.hidden = false;
window.MosaicConsole?.attachBus(box, 'Restart the bus');
} catch { /* no status to show: leave the banner as it was */ }
}
async function refresh() {
busDown();
if (busy || !machine || out()) return;
busy = true; $('refresh').disabled = true;
reading = (async () => {
try { try { const value = await api('/api/board'); if (machine) accept(value); } catch (err) { if (machine) error(err); } await pollConversation(); }
finally { busy = false; $('refresh').disabled = out(); schedule(); }
})().finally(() => { reading = null; });
await reading;
}
// With the toggle off, nothing from the scan stays on the page: the next time it goes on, the board
// starts from a fresh read rather than showing an old scan as current.
function hideMachine() {
clearTimeout(timer);
if (conv) closeConversation();
data = null; selected = null; project = null; failed = false; inspect();
$('error').hidden = true; $('board-refused').hidden = true; document.body.classList.remove('board-refused');
$('projects').innerHTML = '<p class="muted">Machine sessions hidden.</p>';
for (const id of ['waiting', 'seen', 'sessions']) $(id).replaceChildren();
for (const id of ['waiting-count', 'seen-count', 'session-count']) $(id).textContent = '–';
$('footer').textContent = 'Mosaic Stack';
$('status').textContent = 'Machine sessions hidden. Turn on Show machine sessions to read this machine\'s board scan.';
fresh();
}
function showMachine() { $('show-machine').checked = machine; document.body.classList.toggle('machine-off', !machine); }
$('show-machine').onchange = e => {
machine = e.target.checked; showMachine();
try { localStorage.setItem(boardKey(), JSON.stringify({ machine })); } catch {}
if (machine) { $('status').textContent = 'Loading board…'; fresh(); refresh(); } else hideMachine();
};
showMachine();
if (!machine) hideMachine();
// #1873 SP1: another organization opened in place. Its board setting and bus state are its own.
const onOrgSwitch = () => {
machine = readMachine(); showMachine();
if (machine) { fresh(); refresh(); } else { hideMachine(); busDown(); }
};
document.addEventListener('mosaic-org-switch', onOrgSwitch);
// An address with no organization picks one after the first list read; its own setting applies then.
window.MosaicOrg?.ready?.then(() => { if (readMachine() !== machine) onOrgSwitch(); });
// The banner hides on the system dashboard, gives way to the organization page's own down banner,
// and shows on the organization's other pages, so a move across those lines redraws it. Other moves
// inside one organization read nothing (the switch path reads its own).
let busPlace = null;
window.addEventListener('hashchange', () => {
if (!window.MosaicOrg) return;
const path = window.MosaicOrg.route().split('?')[0], now = ['/dashboard', '/organization'].includes(path) ? path : 'page';
if (now !== busPlace) { busPlace = now; busDown(); }
});
$('refresh').onclick = refresh;
$('mobile-pause').onclick = () => $('pause').click();
$('pause').onclick = () => { paused = !paused; $('pause').querySelector('span').textContent = paused ? 'Resume' : 'Pause'; $('pause').setAttribute('aria-label', paused ? 'Resume' : 'Pause'); $('pause').title = paused ? 'Resume' : 'Pause'; $('mobile-pause').textContent = paused ? 'Resume' : 'Pause'; $('pause').setAttribute('aria-pressed', String(paused)); schedule(); if (data) render(); };
$('hide-offline').onchange = $('hide-seen').onchange = render;
function close() { selected = null; render(); if (returnFocus) restore(returnFocus); }
$('close').onclick = close;
document.addEventListener('click', async e => {
const history = e.target.closest('[data-history]');
if (history) { openConversation(history.dataset.history, null, { history: history.dataset.history, container: history.closest('[id]')?.id }); $('conv-title').focus(); return; }
const action = e.target.closest('[data-conv-action]');
// Reload keeps the open branch; "Open the latest branch" takes the default; "Open the newest session" takes the newest file.
if (action && conv) { const c = conv, a = action.dataset.convAction; openConversation(c.row, a === 'newest' ? null : c.id, undefined, a === 'reload' ? { branch: c.branch } : a === 'newest' ? { from: c.id, sessionId: c.sessionId } : {}); $('conv-title').focus(); return; }
const open = e.target.closest('[data-open]');
if (open) { if (conv) closeConversation(); returnFocus = focusSnapshot(); selected = open.dataset.open; render(); $('inspector-title').focus(); announce(`Inspecting ${row(selected)?.agent}`); return; }
const projectButton = e.target.closest('[data-project]');
if (projectButton) { if (conv) closeConversation(); project = projectButton.dataset.project || null; render(); return; }
const seen = e.target.closest('[data-seen]');
if (!seen || writing) return;
// A Board read in flight (reading) holds busy. The click waits for that read and posts on the row it
// drew; dropping it left the click doing nothing (row 172). A second click while one waits or posts is dropped.
// The click means what the button said when clicked (Seen marks, Unsee returns the row to waiting), read before
// the wait. If the fresh row already holds that, another viewer got there first: nothing is posted (row 173).
const mark = seen.dataset.intent === 'seen';
writing = true; seen.disabled = true;
try {
while (reading) await reading;
const r = row(seen.dataset.seen); if (!r) { seen.disabled = false; return; }
if (r.seen === mark) { seen.disabled = false; announce(`${r.agent} already ${mark ? 'seen' : 'waiting'}`); return; }
busy = true;
try { accept(await api('/api/seen', { project: r.project, agent: r.agent, lastActivity: r.lastActivity, seen: mark })); announce(`${r.agent} ${mark ? 'marked seen' : 'returned to waiting'}`); }
catch (err) { error(err); seen.disabled = false; }
finally { busy = false; schedule(); }
} finally { writing = false; }
});
document.addEventListener('input', e => { if (e.target.id === 'reply') drafts.set(selected, e.target.value); if (e.target.id === 'conv-reply' && conv) drafts.set(conv.row, e.target.value); });
document.addEventListener('submit', async e => {
if (!e.target.matches('.reply-form, #conv-form')) return;
e.preventDefault();
// The inspector form is rebuilt from drafts on render; the conversation form is not rebuilt, so its box is cleared here.
const inView = e.target.id === 'conv-form', id = inView ? conv?.row : selected, box = inView ? $('conv-reply') : $('reply'), text = box.value;
if (!id) return;
if (!text.trim() || sending.has(id)) return;
drafts.set(id, text); sending.add(id); render();
try {
const result = await api('/api/reply', { agent: id, text }); receipts.set(id, result);
if (result.delivered) awaiting.set(id, result.sentAt);
// Do not discard text typed while the request was in flight.
if (result.delivered && drafts.get(id) === text) { drafts.delete(id); if (inView && box.value === text) box.value = ''; }
if (result.delivered && !paused) await refresh();
} catch (err) {
if (err.signedOut) { receipts.set(id, { error: `Signed out: ${err.message}. Not sent.` }); return; }
// A 4xx is a refusal before anything ran (the Console's, or the board's: see replyToRow), so
// nothing was sent. No answer, an unreadable one, a 5xx or a 408 (a proxy can answer it
// after forwarding) leaves delivery unknown.
const refused = err.status >= 400 && err.status < 500 && err.status !== 408;
receipts.set(id, { error: err.message + (refused ? '. Not sent.' : '. Delivery may be unknown; check the seat before sending again.') });
}
finally { sending.delete(id); render(); announce(receipts.get(id)?.delivered ? 'Reply delivered' : 'Reply failed; draft kept'); }
});
document.addEventListener('keydown', e => {
if (e.key === 'Escape' && selected && e.target.closest('#inspector')) { e.preventDefault(); close(); return; }
if (!e.target.matches('table.sessions [data-open]')) return;
const buttons = [...document.querySelectorAll('table.sessions [data-open]')], i = buttons.indexOf(e.target);
const next = { ArrowDown: i + 1, ArrowUp: i - 1, Home: 0, End: buttons.length - 1 }[e.key];
if (next !== undefined) { e.preventDefault(); buttons[next]?.focus(); }
});
// Signed out: everything drawn from a Console read goes, because none of it can be refreshed. The
// line says so once; the send form (bus.js) keeps its draft and receipt. Reload is the way back.
document.addEventListener('mosaic-signed-out', e => {
if (out()) return;
document.body.classList.add('signed-out');
clearTimeout(timer); convGen++;
if (conv) { $('conv-log').replaceChildren(); conv = null; showConversation(false); }
data = null; selected = null; project = null; inspect();
for (const id of ['projects', 'waiting', 'seen', 'sessions']) $(id).replaceChildren();
$('refresh').disabled = $('pause').disabled = $('mobile-pause').disabled = true;
const line = $('signed-out');
line.innerHTML = sso || e.detail?.signIn
? `<p><b>Signed out.</b> <a href="/auth/login?${esc(new URLSearchParams({ return: location.pathname + location.search }))}">Sign in again</a>.</p>`
: '<p><b>Signed out.</b> Reload the page to sign in.</p>';
line.hidden = false; $('sign-out').hidden = true;
// Focus moves to the line only if what had it is gone or disabled, never out of a form being typed in.
setTimeout(() => { const a = document.activeElement; if (!a || a === document.body || a.disabled || !a.getClientRects().length) line.focus(); });
});
// Sign out (sage-1347, F7): a plain same-origin form POST to /auth/logout, shown only under --sso.
api('/api/config').then(config => { board = config.board || 'unknown'; $('board-url').textContent = config.board ? `Board: ${board}` : 'No board'; window.MosaicFederation?.render(config.federation, $('federation')); if (config.sso === true) { sso = true; $('sign-out').hidden = out(); $('local-sign-out').hidden = true; $('avatar-name').textContent = 'Operator'; $('avatar-button').querySelector('.avatar-initial').textContent = 'O'; } }).catch(err => { if (machine) error(err); }).finally(refresh);
})();