Files
stack/packages/webui/src/public/chat.js
T
jason.woltje 3581f7548a Merge E2E round 4 fixes (org-e2e4-fix) into refactor
# Conflicts:
#	packages/webui/src/public/chat.js
#	packages/webui/src/public/projects.js
2026-11-08 23:25:02 -06:00

1245 lines
102 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.
/* Row 129: business chat, isolated from the Board's seat conversations and role composer. */
(() => {
'use strict';
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
// crypto.randomUUID exists only in a secure context; a dev owner Console opened by LAN name
// (http://NAME:PORT/) is not one, so build the same v4 form from getRandomValues there.
const opId = () => {
if (typeof crypto.randomUUID === 'function') return crypto.randomUUID();
const b = crypto.getRandomValues(new Uint8Array(16));
b[6] = (b[6] & 0x0f) | 0x40; b[8] = (b[8] & 0x3f) | 0x80;
const h = [...b].map(x => x.toString(16).padStart(2, '0')).join('');
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
};
const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const inert = value => String(value ?? '').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u202a-\u202e\u2066-\u2069]/g,
c => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'));
const txt = value => esc(inert(value));
const states = new Map(), forms = new Map(), knownRequests = new Map();
const pinnedScrolls = new WeakMap(), settlingPins = new WeakMap();
const pageFlow = log => log.closest('.project-chat') && matchMedia('(max-width: 319px), (max-height: 540px)').matches;
// In page flow the tail is the composer pin. Reaching the newest message's end
// also counts, except on an upward scroll: that is the reader leaving the tail.
const transcriptAtTail = (log, messageEnd = true) => pageFlow(log)
? (pageTailTarget(log)?.getBoundingClientRect().bottom ?? 0) - innerHeight < 40 || messageEnd && Math.abs((log.lastElementChild?.getBoundingClientRect().bottom ?? 0) - innerHeight) < 40
: log.scrollHeight - log.scrollTop - log.clientHeight < 40;
const pageTailTarget = log => {
const form = log.closest('.project-chat')?.querySelector('#chat-send-form, #chat-room-send-form');
const field = form?.querySelector('textarea');
const usable = current && (!field?.disabled && !current.channelDisabled || state(current.key ?? current.id).pending);
return form && field && usable && form.getClientRects().length ? form : log.lastElementChild;
};
const pinTranscript = log => {
const scroller = pageFlow(log) ? document.scrollingElement : log;
const before = scroller.scrollTop;
if (scroller === log) log.scrollTop = log.scrollHeight;
else {
const target = pageTailTarget(log);
if (target) window.scrollBy(0, target.getBoundingClientRect().bottom - innerHeight);
}
if (scroller.scrollTop !== before) pinnedScrolls.set(scroller, scroller.scrollTop);
};
let current = null, controller = null, generation = 0, signedOut = false;
const out = () => signedOut || document.body.classList.contains('signed-out');
const state = id => {
if (!states.has(id)) states.set(id, { rows: [], after: null, more: false, loaded: false, draft: '', receipt: '', pending: false, follow: true, tailRequested: false, receiptId: null });
return states.get(id);
};
const form = key => {
if (!forms.has(key)) forms.set(key, { name: '', repo: '', instance: '', instanceChosen: false, receipt: '', pending: false });
return forms.get(key);
};
// Row 225 (C2-10b, design 7.4): a reply renders through the library's renderReply, the one renderer the
// Discord relay shares. Until it loads, or if it can't, a body shows as its text. Badges, the
// agent-written label and "changed since" come from the bus's stored check (C2-06), never the body.
const SHA = /^[0-9a-f]{40}$/, CODE = /^[a-z][a-z-]{0,63}$/, NAME = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,200}$/;
// The library verbs name the business project, which is the chat project's repository link. These
// codes mean that repository is no library, or this page may not read it: no status line at all.
const NO_LIBRARY = ['project-not-declared', 'project-not-configured', 'not-configured', 'owner-only'];
const libraryOf = (c, t) => { const repo = c?.projects.find(p => p.id === (c.kind === 'room' ? c.id : t?.project))?.repo; return typeof repo === 'string' && NAME.test(repo) ? repo : null; };
let renderReply = null;
import('/render.mjs').then(m => { renderReply = m.renderReply; if (current && !out()) paint(); }, () => {});
const libraries = new Map(), reverts = new Map();
class ChatError extends Error {
constructor(code, status = 0, sent) { super(code); this.code = code; this.status = status; this.sent = sent; }
}
const channelMessage = 'The chat channel is disabled for this business. Ask the person who manages it to enable WebUI chat, then refresh.';
function forget() {
generation++; controller?.abort(); states.clear(); forms.clear(); knownRequests.clear(); libraries.clear(); reverts.clear();
window.MosaicRequests?.forget();
window.MosaicProjectArchive?.forget();
if (current) current.container.replaceChildren();
current = null;
}
function signOut() {
signedOut = true; forget();
document.dispatchEvent(new Event('mosaic-signed-out'));
}
async function request(path, value, signal) {
if (out()) throw new ChatError('signed-out');
let res;
try {
res = await fetch('/api/chat/' + path, {
cache: 'no-store', redirect: 'manual', signal,
...(value === undefined ? {} : { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(value) }),
});
} catch (err) {
if (err.name === 'AbortError') throw err;
window.MosaicIcons?.failed();
throw new ChatError(value === undefined ? 'unreachable' : 'outcome-unknown');
}
if (res.type === 'opaqueredirect' || res.status === 401) { signOut(); throw new ChatError('signed-out'); }
let data;
try { data = await res.json(); }
catch { throw new ChatError(value === undefined ? 'invalid-response' : 'outcome-unknown'); }
if (!res.ok) { window.MosaicIcons?.failed(); throw new ChatError(typeof data?.error === 'string' ? data.error : 'invalid-response', res.status, data?.sent); }
window.MosaicIcons?.succeeded();
if (!data || typeof data !== 'object' || (value === undefined && !path.includes('/operation?') && !Array.isArray(data.rows))) {
throw new ChatError(value === undefined ? 'invalid-response' : 'outcome-unknown');
}
return data;
}
const legacyRoute = () => (window.MosaicOrg?.route() ?? location.hash.slice(1)).startsWith('/chat');
const projectPath = id => legacyRoute() ? `#/chat/projects/${id}` : `#/projects/${id}`;
const threadPath = id => legacyRoute() ? `#/chat/threads/${id}` : `#/projects/threads/${id}`;
const roomPath = id => legacyRoute() ? `#/chat/rooms/${id}` : `#/projects/rooms/${id}`;
const link = (type, id, label) => UUID.test(id) ? `<a href="${type === 'projects' ? projectPath(id) : threadPath(id)}">${txt(label)}</a>` : txt(label);
const heading = text => `<h1 tabindex="-1">${txt(text)}</h1>`;
const selectedInactive = () => { const s = current?.sessions?.find(r => r.id === current.session); return !!s?.state && s.state !== 'active'; };
const disabledSession = pending => disabled(pending || selectedInactive());
const disabled = pending => !current.canSend || current.orgArchived || out() || pending ? ' disabled' : '';
const stamp = at => { const date=new Date(at); const projectSurface=window.MosaicProjects && !current?.user && !current?.tester && (!legacyRoute() || current.path?.startsWith('/projects')); return projectSurface && Number.isFinite(date.getTime()) ? `<time datetime="${esc(at)}">${txt(date.toLocaleTimeString([], {hour:'numeric',minute:'2-digit'}))}</time>` : `<time>${txt(at)}</time>`; };
// Per-grant UI hints; all writes still use the caller's bus principal.
const scopeWrites = (project, instance) => !current.user || current.chatGrants.some(g =>
(g.projects.includes('*') || g.projects.includes(project)) &&
(instance === undefined || g.instances.includes('*') || g.instances.includes(instance)));
const threadAccess = () => !!current.thread && !current.shared && scopeWrites(current.thread?.project, current.thread?.instance);
const threadWrites = () => !current.projectArchived && threadAccess();
function sharing(t) {
if (window.MosaicOrg) return '<p>Thread sharing is unavailable.</p>';
if (!current.canSend || !threadWrites() || current.archiveUnknown || current.tester) return '';
const f = form('share:' + t.id);
return `<section aria-label="Thread sharing"><h2>Share read-only</h2><p>Share with a user (user:id), the business owner's name, or * for everyone granted on this thread.</p><ul>${(current.shares ?? []).map(r => `<li>${txt(r.to)} <button class="btn" type="button" data-unshare="${esc(r.to)}"${disabled(f.pending)}>Unshare</button></li>`).join('')}</ul><form id="chat-share-form"><label>Share with<input id="chat-share-target" value="${esc(f.to ?? '')}" maxlength="200" required></label><button class="btn" type="submit"${disabled(f.pending)}>Share read-only</button></form><p role="status">${txt(f.receipt)}</p></section>`;
}
function creation(kind, key) {
const f = form(key), project = kind === 'project';
if (current.user && (project || !scopeWrites(key))) return '';
const repo = project && current.repos.length ? `<label>Repository (optional)<select id="chat-repo" data-chat-field="repo"><option value="">No repository link</option>${current.repos.map(r => `<option value="${esc(r)}"${r === f.repo ? ' selected' : ''}>${txt(r)}</option>`).join('')}</select></label>` : '';
const choices = (current.instances ?? []).filter(r => scopeWrites(key, r.instance));
const picker = project ? '' : `<label>Conversation with<select id="chat-instance" data-chat-field="instance" required${disabled(f.pending || !!current.instanceError || !choices.length)}><option value="">Choose who this conversation is with</option>${choices.map(row => `<option value="${esc(row.instance)}"${row.instance === f.instance ? ' selected' : ''}>${txt(row.name === row.instance ? row.instance : `${row.name} (${row.instance})`)}</option>`).join('')}</select></label>`;
const unavailable = !project && (!!current.instanceError || !choices.some(row => row.instance === f.instance));
const status = !project && current.instanceError ? current.instanceError : f.receipt || (!project && !choices.length ? (legacyRoute() ? 'No thread instances are configured.' : 'No conversation participants are configured.') : '');
return `<form id="chat-${kind}-form" class="chat-create" data-key="${esc(key)}"><h2>New ${project ? 'project' : 'conversation'}</h2><label>Name<input id="chat-${kind}-name" data-chat-field="name" value="${esc(f.name)}" maxlength="200" required${disabled(f.pending)}></label>${repo}${picker}<button class="btn" type="submit"${disabled(f.pending || unavailable || current.channelDisabled)}>${f.pending ? 'Creating…' : `Create ${project ? 'project' : 'conversation'}`}</button><p role="status">${txt(status)}</p></form>`;
}
function threads(rows) {
return rows.length ? `<ul class="chat-thread-list">${rows.map(t => `<li>${link('threads', t.id, t.name)} <span class="muted">${txt(t.instance)}${t.shared ? ` · Shared by ${txt(t.owner)}` : ''}</span></li>`).join('')}</ul>` : current.readFailed ? '<p>Threads unavailable.</p>' : '<p>No threads yet.</p>';
}
const sessionPath = (thread, session) => `${threadPath(thread)}/sessions/${session}`;
const countLabel = value => !value ? 'unavailable (count collector not installed)' :
value.known === true && Number.isSafeInteger(value.count) && value.count >= 0 ? String(value.count) :
`unknown (${value.reason ?? 'not-collected'})`;
function sessionControls(t) {
if (window.MosaicOrg) return '<p>Session changes are unavailable.</p>';
if (!threadAccess()) return '<p>Read-only thread.</p>';
if (current.legacyDefault) return '<p role="status">Sessions are not available for this account.</p>';
const c = current, selected = c.sessions.find(r => r.id === c.session), f = form('session:' + t.id);
const clear = form('clear:' + c.key);
const reason = !Number.isSafeInteger(selected?.revision) ? 'Safe clear is unavailable until its dependency is installed.' : '';
return `<section class="chat-session-controls" aria-label="Sessions"><label>Session<select id="chat-session">${c.sessions.map(r => `<option value="${esc(r.id)}"${r.id === c.session ? ' selected' : ''}>${txt(r.name)}${r.default ? ' (default)' : ''} — ${txt(r.state ?? 'status unavailable')}</option>`).join('')}</select></label><p id="chat-compactions">Compactions: ${txt(countLabel(selected?.compactions))}</p><p>${txt(selected?.state ?? 'Session status unavailable')}${UUID.test(selected?.successor) ? ` · <a href="${sessionPath(t.id, selected.successor)}">Open fresh successor</a>` : ''}</p><form id="chat-session-form" class="chat-create" data-key="session:${esc(t.id)}"><label>New session name<input id="chat-session-name" data-chat-field="name" value="${esc(f.name)}" maxlength="200" required${disabled(f.pending || c.projectArchived || c.archiveUnknown)}></label><button class="btn" type="submit"${disabled(f.pending || c.projectArchived || c.archiveUnknown || current.channelDisabled)}>New session</button><p role="status">${txt(f.receipt)}</p></form><button class="btn" type="button" id="chat-clear"${disabled(c.projectArchived || clear.pending || !!reason || selected?.state && selected.state !== 'active')}>Clear context</button>${reason ? `<p>${txt(reason)}</p>` : ''}<p id="chat-clear-receipt" role="status">${txt(clear.receipt)}</p><form id="chat-operation-form"><label>Check clear operation<input id="chat-operation" value="${esc(clear.op ?? '')}" maxlength="160"${clear.pending ? ' disabled' : ''}></label><button class="btn" type="submit">Check status</button><button class="btn" type="button" id="chat-cancel"${disabled(c.projectArchived || c.archiveUnknown || clear.pending || !!reason || !clear.op || ['cancelled', 'failed'].includes(clear.record?.state) || clear.record?.start === 'started')}>Cancel clear</button></form></section>`;
}
// A cite is changed when the file's last commit at the served tip (`last`, read with the page) is not
// its last commit at the cited one (`file`, stored with the check). Either one missing marks nothing.
const changedBy = check => (cite, i) => {
const e = Array.isArray(check?.citations) ? check.citations[i] : null;
return SHA.test(e?.file ?? '') && SHA.test(e?.last ?? '') && e.file !== e.last;
};
function cites(list) {
return `<ul class="chat-cites">${list.map(c => `<li>${c.badge ? `<span class="chat-scope chat-scope-${c.badge}">${txt(c.badge)}</span> ` : ''}${c.link ? `<a href="${esc(c.link)}" rel="noopener noreferrer" target="_blank">${txt(c.ref)}</a>` : `<code>${txt(c.ref)}</code>`} <q>${txt(c.quote)}</q>${c.agent ? ` <span class="chat-label chat-agent-written">agent-written: ${txt(c.agent)}</span>` : ''}${c.changed ? ' <span class="chat-label chat-changed">changed since</span>' : ''}</li>`).join('')}</ul>`;
}
function messageBody(m) {
if (m.from_role !== 'human' && typeof m.body === 'string' && m.body.startsWith('The turn failed: ')) return `<div class="chat-body">The assistant couldn't reply. Try again, or check Agents.<div class="small">Details: ${txt(m.body.slice('The turn failed: '.length))}</div></div>`;
const r = renderReply?.(m.body, { check: m.check ?? null, name: m.from_role, changed: changedBy(m.check) });
if (r?.kind === 'reply') return `<div class="chat-body">${txt(r.text)}</div>${r.citations.length ? cites(r.citations) : ''}`;
if (r?.kind === 'notice') {
const v = reverts.get(r.commit) ?? {};
return `<div class="chat-body chat-notice"><span>${txt(r.text)}</span> ${current.archiveUnknown || current.projectArchived || window.MosaicOrg ? '' : `<button class="btn" type="button" data-revert="${esc(r.commit)}"${disabled(v.pending)}>Revert</button>`} <span class="chat-revert-receipt" role="status">${txt(v.receipt ?? '')}</span></div>`;
}
return `<div class="chat-body">${txt(m.body)}</div>`;
}
const ago = iso => {
const minutes = Math.floor((Date.now() - Date.parse(iso)) / 60000);
return !Number.isFinite(minutes) ? 'at an unknown time' : minutes < 1 ? 'just now' : minutes < 60 ? `${minutes} min ago` : minutes < 2880 ? `${Math.floor(minutes / 60)} h ago` : `${Math.floor(minutes / 1440)} days ago`;
};
// library.status (C2-04): the served commit and when it was last fetched, a held divergence, the last
// fetch error, the reply limits in force (C2-06) and the R-problems, listed one click away.
function libraryLine(project) {
const l = libraries.get(project);
if (!l || l.hidden) return '';
if (l.error) return `<div class="chat-library"><p role="status">Library status unavailable (${txt(l.error)}).</p></div>`;
const v = l.value, parts = [];
parts.push(SHA.test(v.served ?? '') ? `Library at <code>${txt(v.served.slice(0, 7))}</code>` : 'Library not served yet');
if (typeof v.lastFetch === 'string') parts.push(`<span data-library-age="${esc(v.lastFetch)}">fetched ${txt(ago(v.lastFetch))}</span>`);
if (SHA.test(v.diverged?.commit ?? '')) parts.push(`<b>library-diverged</b> at <code>${txt(v.diverged.commit.slice(0, 7))}</code>`);
if (CODE.test(v.lastError?.code ?? '')) parts.push(`fetch error <code>${txt(v.lastError.code)}</code>`);
const limits = v.replyLimits;
if (limits && typeof limits === 'object') {
parts.push(`citations ${limits.requireCitation === true ? 'required' : 'optional'}${Number.isSafeInteger(limits.citationsPerReply) ? `, up to ${limits.citationsPerReply} per reply` : ''}`);
const fell = Array.isArray(limits.fallback) ? limits.fallback.filter(k => typeof k === 'string') : [];
if (fell.length) parts.push(`limits fell back: ${fell.map(k => `<code>${txt(k)}</code>`).join(', ')}`);
if (CODE.test(limits.problem ?? '')) parts.push(`<code>${txt(limits.problem)}</code>`);
}
const problems = Array.isArray(v.problems) ? v.problems : [];
if (!problems.length) parts.push('no problems');
const list = problems.length ? `<details class="chat-library-problems"><summary>${problems.length} problem${problems.length === 1 ? '' : 's'}</summary><ul>${problems.map(p => `<li><code>${txt(p?.code)}</code> ${txt(p?.path)}${Number.isSafeInteger(p?.line) ? ':' + p.line : ''} ${txt(p?.message)}</li>`).join('')}</ul></details>` : '';
return `<div class="chat-library"><p role="status">${parts.join(' · ')}</p>${list}</div>`;
}
async function loadLibrary(project, g, signal) {
if (project === null) return;
let entry;
try {
const res = await fetch('/api/library/status?project=' + encodeURIComponent(project), { cache: 'no-store', redirect: 'manual', signal });
if (res.type === 'opaqueredirect' || res.status === 401) { signOut(); return; }
const data = await res.json().catch(() => null);
entry = res.ok && data && typeof data === 'object' && !Array.isArray(data) ? { value: data } : { error: CODE.test(data?.error ?? '') ? data.error : 'invalid-response' };
} catch (err) {
if (err.name === 'AbortError') return;
entry = { error: 'unreachable' };
}
if (g !== generation || out()) return;
libraries.set(project, NO_LIBRARY.includes(entry.error) ? { hidden: true } : entry);
paint(false, true);
}
// design (writes): Revert is library.revert {commit}, her act. A refusal shows its code; before
// C2-02's verb exists that is the bus's refusal of the verb.
async function revert(commit) {
const c = current, t = c?.threads.find(t => t.id === c.id), v = reverts.get(commit) ?? {};
const project = libraryOf(c, t);
if (!c || c.archiveUnknown || c.projectArchived || !c.canSend || out() || v.pending || !SHA.test(commit) || project === null) return;
if (!window.confirm(`Revert ${commit.slice(0, 7)}? This makes a new commit in the library that puts the file back as it was before it.`)) return;
const unknown = 'Outcome unknown. Read the library status before trying again; nothing was retried.';
reverts.set(commit, { pending: true, receipt: 'Reverting…' }); paint();
let receipt;
try {
const res = await fetch('/api/library/revert', { method: 'POST', cache: 'no-store', redirect: 'manual', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ project, commit }) });
if (res.type === 'opaqueredirect' || res.status === 401) { signOut(); return; }
const data = await res.json().catch(() => null);
receipt = res.ok && SHA.test(data?.commit ?? '') ? `Reverted in ${data.commit.slice(0, 7)}.`
: (data?.sent === false || res.status >= 400 && res.status < 500) && typeof data?.error === 'string' ? `Not reverted (${inert(data.error.slice(0, 80))}).` : unknown;
} catch { receipt = unknown; }
if (out()) return;
reverts.set(commit, { pending: false, receipt });
if (current) { paint(); void loadLibrary(project, generation); }
}
// #797 Task 3: the owner's latest few messages that opened a request carry an empty mount that
// requests.js fills with the intake panel. Older rows stay plain, so a long thread reads few requests.
const REQUEST_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/;
const REQUEST_ROWS = 3;
// The request panel, Files and summary each read independently. Share only confirmed
// request-not-found responses while a thread is open, without changing other fetch paths.
const fetchPage = window.fetch.bind(window);
window.fetch = async (url, init) => {
const path = typeof url === 'string' && /^\/api\/requests\/([A-Za-z0-9][A-Za-z0-9._-]{0,159})(?:\/workspace)?$/.exec(url);
const c = current, s = path && (!init?.method || init.method === 'GET') && c?.kind === 'thread' && !out() ? state(c.key) : null;
// An already-aborted read keeps the native AbortError, so it bypasses the remembered miss.
if (!s || init?.signal?.aborted) return fetchPage(url, init);
const id = path[1], epoch = s.requestEpoch ?? 0, seen = s.requestSeen?.get(id) ?? 0;
if (s.missingRequests?.has(id)) return new Response(JSON.stringify({ error: 'request-not-found' }), { status: 404, headers: { 'content-type': 'application/json' } });
const response = await fetchPage(url, init);
// Only the request's own read records a miss. A workspace 404 is about the workspace and must
// not hide a request whose state still reads.
if (response.status === 404 && !path[0].endsWith('/workspace')) {
const body = await response.clone().json().catch(() => null);
if (body?.error === 'request-not-found' && !out() && (s.requestEpoch ?? 0) === epoch && (s.requestSeen?.get(id) ?? 0) === seen) {
(s.missingRequests ??= new Set()).add(id);
}
}
return response;
};
// A request read elsewhere on this page (any requests.js panel) proves the id now exists, so
// every open thread forgets that miss and the next refresh reads it again. The id's own
// generation also advances, so a 404 still in flight from before this observation cannot
// record the miss after it. Only that id moves; other ids' slow misses still settle.
document.addEventListener('mosaic-request-state', event => {
const id = event.detail?.state?.request;
if (typeof id !== 'string' || out()) return;
for (const s of states.values()) {
if (s.missingRequests?.delete(id)) s.requestEpoch = (s.requestEpoch ?? 0) + 1;
if (s.rows?.some(m => m.request === id)) (s.requestSeen ??= new Map()).set(id, (s.requestSeen.get(id) ?? 0) + 1);
}
});
function requestRows(rows) {
const ids = new Set();
if (!window.MosaicRequests || !roomOwner()) return ids;
for (let i = rows.length - 1; i >= 0 && ids.size < REQUEST_ROWS; i--) {
const m = rows[i];
if (m.from_role === 'human' && typeof m.request === 'string' && REQUEST_ID.test(m.request)) ids.add(m.id);
}
return ids;
}
function conversation(t) {
const s = state(current.key);
const withRequest = requestRows(s.rows);
const receipt = s.receipt;
const project = current.projects.find(p => p.id === t.project);
const redesigned = project && roomOwner() && window.MosaicProjects && (!legacyRoute() || current.path?.startsWith('/projects'));
// Keep each request tied to its originating message while placing its card after the first reply.
const mountsAfter = new Map();
if (redesigned) s.rows.forEach((m, i) => {
if (!withRequest.has(m.id)) return;
const next = s.rows[i + 1];
const index = next && next.from_role !== 'human' ? i + 1 : i;
const list = mountsAfter.get(index) || []; list.push(m); mountsAfter.set(index, list);
});
const mount = m => `<div class="request-mount" data-request="${esc(m.request)}" data-origin-message="${esc(m.id)}"></div>`;
const messages = s.rows.map((m, i) => `<li class="${m.from_role === 'human' ? 'chat-message-human' : 'chat-message-agent'}" data-message="${esc(m.id)}"><div class="chat-message-meta"><span class="chat-avatar" aria-hidden="true">${txt(String(m.from_role || '?').slice(0, 1).toUpperCase())}</span><strong>${txt(m.from_role === 'human' ? 'You' : m.from_role)}</strong> ${stamp(m.at)}</div>${messageBody(m)}${!redesigned && withRequest.has(m.id) ? mount(m) : ''}</li>${redesigned ? (mountsAfter.get(i) || []).map(origin => `<li class="project-request-item">${mount(origin)}</li>`).join('') : ''}`).join('');
const frame = redesigned ? window.MosaicProjects.header(project, 'conversations', current.threads, t.name, true) : heading(t.name);
const details = redesigned ? `<dialog class="chat-details project-dialog" id="project-conversation-dialog" aria-labelledby="project-conversation-title"><h2 id="project-conversation-title" tabindex="-1">Conversation details</h2><button class="btn" type="button" data-dialog-close>Close</button>${sessionControls(t)}${sharing(t)}<p>Reading never wakes the assistant. An accepted message is not an answer.</p>${threadWrites() ? `<button class="btn" type="button" id="chat-resume"${disabledSession(s.pending || current.channelDisabled)}>Resume assistant</button>` : ''}</dialog>` : `<details class="chat-details"><summary id="chat-details-toggle">Conversation details</summary>${sessionControls(t)}${sharing(t)}</details><p class="muted">Reading never wakes the assistant. An accepted message is not an answer.</p>${threadWrites() ? `<button class="btn" type="button" id="chat-resume"${disabledSession(s.pending || current.channelDisabled)}>Resume assistant</button>` : ''}`;
return `<section class="chat-conversation${redesigned ? ' project-chat' : ''}" data-project="${esc(t.project)}" data-thread="${esc(t.id)}" data-session="${esc(current.session)}"><p>${link('projects', t.project, current.projects.find(p => p.id === t.project)?.name ?? 'Project')} / ${txt(t.instance)}</p>${frame}${libraryLine(libraryOf(current, t))}${details}${redesigned ? '<p class="small muted" data-conversation-request-status></p>' : ''}<ol class="chat-log" tabindex="0" aria-label="Thread conversation">${messages || (current.readFailed ? '<li class="muted">Messages unavailable.</li>' : '<li class="muted">No messages yet.</li>')}</ol><div class="chat-paging">${current.readFailed ? '<button type="button" class="btn" data-chat-retry>Read again</button>' : s.more ? '<p>Showing earlier history. Read forward to reach the current conversation.</p><button class="btn" type="button" id="chat-next">Read next messages</button>' : '<p class="muted">Caught up to the last read.</p>'}<button class="btn" type="button" id="chat-new"${s.follow ? ' hidden' : ''}>New messages — go to end</button></div>${threadWrites() ? `<form id="chat-send-form"><label for="chat-body">Message ${txt(t.instance)}</label><textarea id="chat-body" rows="4" placeholder="${redesigned ? `Message ${esc(t.instance)}` : 'Write a message…'}"${disabledSession(s.pending)}>${esc(s.draft)}</textarea><p class="chat-audience">To: ${redesigned ? `<span class="room-chip" aria-label="Recipient ${esc(t.instance)}">${txt(t.instance)}</span>` : `${txt(t.instance)} · Private conversation`}</p>${redesigned ? '<p class="project-composer-hint">Enter adds a new line.</p>' : ''}<button class="btn primary" type="submit"${disabledSession(s.pending || current.channelDisabled)}>Send</button></form>` : ''}<p id="chat-receipt" role="status">${txt(receipt)}</p>${redesigned ? '' : '<section class="chat-files"><h2>Files</h2><div data-chat-files>Files unavailable.</div></section><div data-chat-summary></div>'}</section>`;
}
// C2-10c: rooms reuse the same state, renderer and generation fences as threads.
const ROOM_LINES = Object.freeze({
'unknown-addressee': 'Unknown addressee. Choose a room member.',
'addressee-ambiguous': "That addressee is ambiguous. Use a room member's instance name.",
'room-thread-name-taken': 'A room thread name is already in use. Resolve the conflicting thread before opening the room.',
'room-not-open': 'This room is not open. Open the room before sending.',
});
const roomError = err => err.code === 'channel-disabled' ? channelMessage : ROOM_LINES[err.code] ?? (err.sent === false || err.status >= 400 && err.status < 500
? `Room operation refused (${inert(err.code)}).`
: 'Room unavailable. Refresh to read it again; nothing was retried.');
const roomOwner = () => current && !current.user && !current.tester;
// Same leading-token grammar as bus/address.mjs; the UI never resolves/replaces recipients on send.
function roomAddress(input) {
const tags = []; let body = input.trimStart();
while (true) {
const token = /^@(\S+)(?:\s+|$)/u.exec(body);
if (!token) break;
tags.push(token[1]); body = body.slice(token[0].length);
}
return { tags, body };
}
const roomName = instance => current.members?.find(m => m.instance === instance)?.name || instance;
function roomOpenControl(project) {
if (window.MosaicOrg) return '<p>Room changes are unavailable.</p>';
if (!roomOwner()) return '';
if (current.projects.some(p => p.id === project && p.archived)) return `<p><a href="${roomPath(esc(project))}">Read room</a></p>`;
const f = form('room-open:' + project);
return `<section class="chat-room-entry" aria-label="Project room"><button class="btn" type="button" id="chat-room-open"${disabled(f.pending || current.channelDisabled)}>Open room</button> <a href="${roomPath(esc(project))}">Read room</a><p id="chat-room-open-receipt" role="status">${txt(f.receipt)}</p></section>`;
}
function roomConversation() {
const c = current, s = state(c.key), p = c.projects.find(p => p.id === c.id);
const messages = s.rows.map(m => {
const speaker = m.from_role === 'human' ? 'Human' : roomName(m.from_role);
const recipients = m.from_role === 'human' ? ` → ${(m.to ?? []).map(r => txt(roomName(r))).join(', ')}` : '';
return `<li class="${m.from_role === 'human' ? 'chat-message-human' : 'chat-message-agent'}" data-message="${esc(m.id)}"><div class="chat-message-meta"><span class="chat-avatar" aria-hidden="true">${txt(String(speaker || '?').slice(0, 1).toUpperCase())}</span><strong>${txt(m.from_role === 'human' ? 'You' : speaker)}</strong>${recipients} ${stamp(m.at)}</div>${messageBody({ ...m, from_role: m.from_role === 'human' ? m.from_role : speaker })}${m.from_role !== 'human' && c.threads.find(t => t.instance === m.from_role && t.name === t.instance) ? `<a href="${threadPath(esc(c.threads.find(t => t.instance === m.from_role && t.name === t.instance).id))}">Open ${txt(speaker)} conversation</a>` : ''}</li>`;
}).join('');
const off = !!window.MosaicOrg || !c.roomReady || c.channelDisabled || s.pending || !roomOwner();
const redesigned = p && window.MosaicProjects && roomOwner() && (!legacyRoute() || current.path?.startsWith('/projects'));
const frame = redesigned ? window.MosaicProjects.header(p, 'room', c.threads) + `<div class="project-section-title"><h2>Project room</h2><button class="btn" type="button" data-project-dialog="room" aria-label="Room details"><span class="project-action-icon" aria-hidden="true"><svg class="i" viewBox="0 0 24 24"><circle cx="9" cy="8" r="3"/><path d="M3 20v-2a6 6 0 0 1 12 0v2M16 5a3 3 0 0 1 0 6m1 2a5 5 0 0 1 4 5v2"/></svg></span><span class="project-action-label">Room details</span></button></div><dialog class="project-dialog" id="project-room-dialog" aria-labelledby="project-room-title"><h2 id="project-room-title" tabindex="-1">Room details</h2><button class="btn" type="button" data-dialog-close>Close</button>${roomOpenControl(c.id)}<p>Room members: ${(c.members ?? []).map(m => `${txt(m.name)} (@${txt(m.instance)})`).join(', ') || 'unavailable'}</p></dialog>` : heading((p?.name ?? 'Project') + ' room') + roomOpenControl(c.id);
return `<section class="chat-room${redesigned ? ' project-chat' : ''}" data-project="${esc(c.id)}"><p>${link('projects', c.id, p?.name ?? 'Project')}</p>${frame}${redesigned && c.error === ROOM_LINES['room-not-open'] ? `<div class="project-room-warning" role="status">${txt(c.error)} <button type="button" class="btn" data-room-open-inline>Open room</button></div>` : ''}${libraryLine(libraryOf(c))}<p>Messages are copied to the members you choose. Each reply stays in that member's conversation.</p><p>Room members: ${(c.members ?? []).map(m => `${txt(m.name)} (@${txt(m.instance)})`).join(', ') || 'unavailable'}</p><ol class="chat-log chat-room-log" tabindex="0" aria-label="Room conversation">${messages || (c.readFailed ? '<li>Messages unavailable.</li>' : '<li>No messages yet.</li>')}</ol><div class="chat-paging">${c.readFailed ? '' : s.more ? '<button class="btn" type="button" id="chat-next">Read next messages</button>' : '<p class="muted">Caught up to the last read.</p>'}<button class="btn" type="button" id="chat-new"${s.follow ? ' hidden' : ''}>New messages — go to end</button></div>${c.projectArchived ? '<p>This project is archived; its room history stays readable.</p>' : `<form id="chat-room-send-form"><fieldset class="chat-room-picker"${off ? ' disabled' : ''}><legend>To: <span class="sr-only">Recipients</span></legend>${(c.members ?? []).map(m => redesigned ? `<input class="room-chip-input" type="checkbox" id="chat-member-${esc(m.instance)}" data-room-member="${esc(m.instance)}" tabindex="-1" aria-hidden="true"><button type="button" class="room-chip" data-room-chip="${esc(m.instance)}" title="${esc(m.name)}" aria-pressed="true">${txt(m.name)}</button>` : `<label><input type="checkbox" id="chat-member-${esc(m.instance)}" data-room-member="${esc(m.instance)}"> ${txt(m.name)} (@${txt(m.instance)})</label>`).join('')}</fieldset><label for="chat-room-body"${redesigned ? ' class="sr-only"' : ''}>Message the room</label><p id="chat-room-help"${redesigned ? ' class="sr-only"' : ''}>Choose contacts above, or use leading @tags. Without tags, the message goes to all room members. Mentions in the message do not add recipients. The broker checks every address.</p><textarea id="chat-room-body" rows="4" placeholder="Message the room" aria-describedby="chat-room-help" aria-autocomplete="list" aria-controls="chat-room-completion" aria-expanded="false"${disabled(off)}>${esc(s.draft)}</textarea>${redesigned ? '<p class="project-composer-hint">Use @names to choose recipients.</p>' : ''}<div id="chat-room-offer"></div><div id="chat-room-tags"></div><ul id="chat-room-completion" class="chat-room-completion" role="listbox" aria-label="Room members" hidden></ul><button class="btn primary" type="submit"${disabled(off)}>Send to room</button></form>`}<p id="chat-room-receipt" role="status">${txt(s.receipt)}</p></section>`;
}
function drawRoomCompletion() {
const list = document.getElementById('chat-room-completion'), field = document.getElementById('chat-room-body');
if (!list || !field) return;
const c = current.completion, active = !!c?.items.length;
list.hidden = !active; field.setAttribute('aria-expanded', String(active));
if (!active) { list.replaceChildren(); field.removeAttribute('aria-activedescendant'); return; }
list.innerHTML = c.items.map((m, i) => `<li role="presentation"><button type="button" role="option" tabindex="-1" id="chat-room-option-${i}" aria-selected="${i === c.index}" data-room-complete="${esc(m.instance)}">${txt(m.name)} (@${txt(m.instance)})</button></li>`).join('');
field.setAttribute('aria-activedescendant', `chat-room-option-${c.index}`);
}
function updateRoomCompletion() {
if (current?.kind !== 'room') return;
const field = document.getElementById('chat-room-body'), preview = document.getElementById('chat-room-tags');
if (!field || !preview) return;
const { tags, body } = roomAddress(field.value);
const offer = document.getElementById('chat-room-offer');
const mentioned = tags.length ? [...body.matchAll(/@([A-Za-z0-9][A-Za-z0-9_.-]*)/g)].map(m => m[1]).find(name => !tags.includes(name) && current.members.some(m => m.instance === name)) : null;
if (offer) offer.innerHTML = mentioned ? `<button class="btn" type="button" data-room-offer="${esc(mentioned)}">Add ${txt(roomName(mentioned))} to recipients</button>` : '';
preview.innerHTML = tags.length ? 'To: ' + tags.map(tag => `<span data-room-tag="${esc(tag)}">@${txt(tag)}</span>`).join(' ') : 'To: all room members';
for (const box of document.querySelectorAll('[data-room-member]')) { box.checked = tags.length ? tags.includes(box.dataset.roomMember) : true; document.querySelector(`[data-room-chip="${CSS.escape(box.dataset.roomMember)}"]`)?.setAttribute('aria-pressed', String(box.checked)); }
const prefix = field.value.slice(0, field.selectionStart), token = /(?:^|\s)@([^\s@]*)$/u.exec(prefix);
current.completion = null;
if (document.activeElement === field && !field.disabled && token && !roomAddress(prefix.slice(0, token.index)).body.trim()) {
const needle = token[1].toLocaleLowerCase();
const items = (current.members ?? []).filter(m => m.instance.toLocaleLowerCase().startsWith(needle) || m.name.toLocaleLowerCase().startsWith(needle)).slice(0, 10);
current.completion = { items, index: 0, start: prefix.length - token[1].length - 1, end: field.selectionEnd };
}
drawRoomCompletion();
}
function completeRoom(instance) {
const field = document.getElementById('chat-room-body'), c = current?.completion;
if (!field || field.disabled || !c?.items.some(m => m.instance === instance)) return;
const value = field.value.slice(0, c.start) + '@' + instance + ' ' + field.value.slice(c.end);
const caret = c.start + instance.length + 2;
field.value = value; state(current.key).draft = value; field.focus(); field.setSelectionRange(caret, caret);
updateRoomCompletion();
}
async function renderRoom({ path, originalPath = path, container, canSend, user, tester, navigated, next }) {
if (out()) return;
controller?.abort(); controller = new AbortController();
const signal = controller.signal, g = ++generation;
const match = /^\/chat\/rooms\/([0-9a-f-]+)$/i.exec(path), id = match?.[1];
const old = current;
current = { kind: 'room', id, key: 'room:' + id, path: originalPath, container, canSend, user, tester,
projects: old?.kind === 'room' && old.id === id ? old.projects : [], threads: [], members: [], roomReady: false, channelDisabled: old?.channelDisabled ?? false, refused: false, error: '' };
current.projectArchived = current.projects.some(p => p.id === id && p.archived);
if (!UUID.test(id ?? '') || !roomOwner()) {
current.error = UUID.test(id ?? '') ? 'Rooms require the business owner.' : 'Invalid room route.';
current.refused = true; paint(navigated); return;
}
const s = state(current.key);
if (navigated) container.innerHTML = '<p role="status">Reading room…</p>';
try {
const [projects, threads, catalog] = await Promise.all([
request('projects', undefined, signal), request('threads?project=' + id, undefined, signal), request('instances', undefined, signal),
]);
if (g !== generation || out()) return;
if (!projects.rows.some(p => p.id === id) && !user && !tester) {
const resolved = await window.MosaicProjectArchive?.resolve(id, signal);
if (g !== generation || out()) return;
if (resolved) projects.rows.push(resolved);
}
if (!projects.rows.some(p => p.id === id)) throw new ChatError('project-not-found', 404);
current.projects = projects.rows;
current.projectArchived = current.projects.some(p => p.id === id && p.archived);
if (!catalog.rows.every(m => typeof m?.instance === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,159}$/.test(m.instance) && typeof m.name === 'string')) throw new ChatError('invalid-response');
current.threads = threads.rows;
current.members = catalog.rows.filter(m => threads.rows.some(t => t.project === id && t.instance === m.instance && t.name === m.instance));
const after = s.loaded && (!s.more || next) ? s.after : null;
const page = await request(`rooms/${id}/messages?limit=100${after ? '&after=' + after : ''}`, undefined, signal);
if (g !== generation || out()) return;
if (typeof page.hasMore !== 'boolean' || !(page.after === null || UUID.test(page.after)) || page.rows.some(m => !UUID.test(m?.id) || !Array.isArray(m.ids) || !m.ids.every(id => UUID.test(id)) || !Array.isArray(m.to))) throw new ChatError('invalid-response');
const project = current.projects.find(p => p.id === id);
document.dispatchEvent(new CustomEvent('mosaic-project-context', { detail: { projectId: id, repositoryKey: project?.repo ?? null, thread: null, session: null, room: true } }));
current.channelDisabled = false;
s.rows = [...new Map((after ? [...s.rows, ...page.rows] : page.rows).map(m => [m.id, m])).values()].slice(-200);
s.after = page.after ?? s.after; s.more = page.hasMore; s.loaded = true;
current.roomReady = current.members.length > 0;
if (s.receiptIds?.every(id => s.rows.some(m => m.ids.includes(id)))) { s.receipt = 'Message shown in the room.'; s.receiptIds = null; }
} catch (err) {
if (g !== generation || out() || err.name === 'AbortError' || err.code === 'signed-out') return;
current.error = roomError(err);
current.readFailed = true;
if (err.code === 'channel-disabled') current.channelDisabled = true;
if (err.status === 403 || err.status === 404) { s.rows = []; current.members = []; current.projects = []; }
current.projectArchived = current.projects.some(p => p.id === id && p.archived);
}
if (g === generation && !out()) { paint(navigated, true); void loadLibrary(libraryOf(current), g, signal); }
}
async function openRoom(projectId) {
const c = current, id = projectId || c?.id;
const onProject = () => current && (current.id === id || current.kind === 'thread' && current.thread?.project === id);
if (!roomOwner() || c.projectArchived || !c.canSend || c.channelDisabled || out() || !UUID.test(id ?? '')) return;
const f = form('room-open:' + id);
if (f.pending) return;
f.pending = true; f.receipt = ''; paint();
try {
const data = await request(`rooms/${id}/open`, {});
if (out()) return;
if (data.project !== id || !Array.isArray(data.threads) || !data.threads.length || data.threads.some(t => !UUID.test(t?.id) || typeof t.instance !== 'string' || t.name !== t.instance)) throw new ChatError('outcome-unknown');
f.receipt = 'Room opened.';
if (onProject()) {
document.dispatchEvent(new CustomEvent('mosaic-project-room-changed'));
if (current?.kind === 'room' && current.id === id) void refresh();
else location.hash = roomPath(id);
}
} catch (err) {
if (out() || err.code === 'signed-out') return;
f.receipt = err.sent === false ? roomError(err) : `${err.code === 'channel-disabled' ? channelMessage + ' ' : ''}Outcome unknown. Read the room before opening again; nothing was retried.`;
if (err.code === 'channel-disabled' && current?.id === id) current.channelDisabled = true;
} finally { f.pending = false; if (onProject() && !out()) paint(); }
}
async function sendRoom() {
const c = current;
if (!roomOwner() || c.projectArchived || !c.canSend || !c.roomReady || c.channelDisabled || out()) return;
const s = state(c.key), body = s.draft;
if (s.pending) return;
if (!body.trim() || new TextEncoder().encode(JSON.stringify({ body })).length > 16384) {
s.receipt = body.trim() ? 'Message is too long (16 KiB JSON maximum).' : 'Write a message first.'; paint(); return;
}
s.pending = true; s.receipt = ''; paint();
try {
const data = await request(`rooms/${c.id}/messages`, { body });
if (out()) return;
if (!Array.isArray(data.ids) || !data.ids.length || !data.ids.every(id => UUID.test(id)) || !Array.isArray(data.to) || data.to.length !== data.ids.length) throw new ChatError('outcome-unknown');
s.receipt = 'Accepted room message. Waiting for the room to show it.'; s.receiptIds = data.ids;
if (s.draft === body) s.draft = '';
s.follow = true; s.tailRequested = true;
} catch (err) {
if (out() || err.code === 'signed-out') return;
s.receipt = err.sent === false ? roomError(err) : `${err.code === 'channel-disabled' ? channelMessage + ' ' : ''}Outcome unknown. Read the room before trying again. Nothing was retried; your draft is kept.`;
if (err.code === 'channel-disabled' && current?.key === c.key) current.channelDisabled = true;
} finally { s.pending = false; if (current?.key === c.key && !out()) paint(); }
}
document.addEventListener('keydown', event => {
if (current?.kind !== 'room' || event.target.id !== 'chat-room-body' || !current.completion?.items.length) return;
const c = current.completion;
if (['ArrowDown', 'ArrowUp'].includes(event.key)) { event.preventDefault(); c.index = (c.index + (event.key === 'ArrowDown' ? 1 : c.items.length - 1)) % c.items.length; drawRoomCompletion(); }
if (['Enter', 'Tab'].includes(event.key)) { event.preventDefault(); completeRoom(c.items[c.index].instance); }
if (event.key === 'Escape') { event.preventDefault(); current.completion = null; drawRoomCompletion(); }
});
document.addEventListener('mousedown', event => { if (event.target.closest?.('[data-room-complete]')) event.preventDefault(); });
function capture() {
if (!current) return null;
const active = document.activeElement, log = current.container.querySelector('.chat-log');
const field = active?.id?.startsWith('chat-') ? { id: active.id, start: active.selectionStart, end: active.selectionEnd } : null;
const dialog = current.container.querySelector('dialog.project-dialog[open]');
const dialogValues = dialog ? [...dialog.querySelectorAll('input[id],select[id],textarea[id]')].map(e=>({id:e.id,value:e.value,checked:e.checked})) : [];
const dialogFocus = dialog?.contains(active) ? { id:active.id, index:[...dialog.querySelectorAll('button,a,input,select,textarea,[tabindex]')].indexOf(active), value:'value' in active ? active.value : null, start:active.selectionStart, end:active.selectionEnd } : null;
const toggles = [...current.container.querySelectorAll('.project-new-conversation,.project-create')].map(e=>e.open);
const content = current.container.querySelector('[data-project-content]');
const { projectFocus, disclosures, closed } = window.MosaicProjects?.captureView ? window.MosaicProjects.captureView(content) : { projectFocus:null, disclosures:[], closed:[] };
// A repaint can replace a log while its own pin is waiting for layout.
// Carry that intent only while the offset still matches the pending pin.
return { tabScroll: current.container.querySelector('.project-tabs')?.scrollLeft, field, dialog:dialog?.id, dialogValues, dialogFocus, toggles, projectFocus, disclosures, closed, detailsOpen: current.container.querySelector('.chat-details')?.open, top: log ? (pageFlow(log) ? document.scrollingElement.scrollTop : log.scrollTop) : undefined, tail: log ? transcriptAtTail(log) : true, settlingPin: !!log && !pageFlow(log) && (pinnedScrolls.get(log) === log.scrollTop || settlingPins.get(log) === log.scrollTop) };
}
let transcriptObserver = null, transcriptResize = null, lastPaint = null;
const visualKey = html => html.replace(/(<textarea\b[^>]*>)[\s\S]*?(<\/textarea>)/g, '$1$2')
.replace(/<span data-library-age="[^"]*">[^<]*<\/span>/g, '<span data-library-age></span>');
function refreshLibraryAge(c) {
const el = c.container.querySelector('[data-library-age]');
const at = libraries.get(libraryOf(c, c.thread))?.value?.lastFetch;
if (!el || typeof at !== 'string') return;
const text = `fetched ${ago(at)}`;
if (el.textContent !== text) el.textContent = text;
if (el.dataset.libraryAge !== at) el.dataset.libraryAge = at;
}
// Refreshes often read exactly the same view. Remember the generated presentation,
// not the mutable DOM (which also contains independently mounted request controls).
function refreshProjectData(c, redesigned, restore) {
if (c.user || c.tester || !window.MosaicProjects) return;
const project = c.projects.find(p => p.id === c.id);
const projectContent = c.container.querySelector('[data-project-content]');
if (redesigned && (c.kind === 'project' || c.kind === 'thread' || c.kind === 'room')) {
const surfaceProject = c.kind === 'thread' ? c.projects.find(p => p.id === c.thread?.project) : project;
if (surfaceProject) void window.MosaicProjects.enhanceSurface(c.container, surfaceProject, c.threads, c.kind === 'thread' ? c.thread : null, c.canSend, form('room-open:' + surfaceProject.id).receipt);
}
if (projectContent && project) void window.MosaicProjects.mountContent({ container: projectContent, project, threads: c.threads, section: c.section, canSend: c.canSend, restore, roomReceipt: form('room-open:' + project.id).receipt });
if (c.kind === 'list') window.MosaicProjects.enhanceList(c.container, c.projects, c.threads);
}
// Request panels, files and the request summary reread on every refresh, including one whose
// visible view is unchanged: a request's phase moves without a new message. A quiet reread
// keeps the present content until a changed result arrives.
function refreshRequestData(c, quiet) {
window.MosaicRequests?.mount?.(c.container, { archiveUnknown: !!c.archiveUnknown, projectArchived: !!c.projectArchived });
const t = c.kind === 'thread' ? c.thread : null;
const repo = c.kind === 'project' ? c.projects.find(p => p.id === c.id)?.repo : libraryOf(c, t);
const cached = knownRequests.get(c.id);
const remembered = c.kind === 'project' && cached && cached.repo === repo ? cached.ids : [];
const selected = t ? requestRows(state(c.key).rows) : new Set();
const ids = !roomOwner() ? [] : t ? [...new Set(state(c.key).rows.filter(m => selected.has(m.id)).map(m => m.request))] : [...remembered].slice(-REQUEST_ROWS);
const files = c.container.querySelector('[data-chat-files]');
if (files && typeof window.MosaicFiles?.mount === 'function') { if (!quiet) files.replaceChildren(); window.MosaicFiles.mount({ container: files, requestIds: ids, key: `thread:${c.id}`, quiet }); }
const summary = c.container.querySelector('[data-chat-summary]');
if (summary && repo && ids.length) {
if (typeof window.MosaicRequests?.projectSummary === 'function') window.MosaicRequests.projectSummary({ container: summary, requestIds: ids, project: repo, quiet });
else summary.textContent = 'Request summary unavailable.';
}
}
// When only the transcript changed, reconcile its keyed children in the
// existing log. In particular, never detach an unchanged message or composer.
function updateTranscript(c, html, next, keep) {
if (!lastPaint || lastPaint.container !== c.container || lastPaint.path !== c.path) return false;
const previous = document.createElement('template'); previous.innerHTML = lastPaint.html;
const oldLog = previous.content.querySelector('.chat-log'), newLog = next.content.querySelector('.chat-log');
const liveLog = c.container.querySelector('.chat-log');
if (!oldLog || !newLog || !liveLog) return false;
const oldItems = [...oldLog.children], newItems = [...newLog.children], liveItems = [...liveLog.children];
oldLog.replaceChildren(); newLog.replaceChildren();
const outside = template => visualKey(template.innerHTML);
if (outside(previous) !== outside(next)) return false;
const key = el => el.dataset.message ? 'message:' + el.dataset.message : el.querySelector('[data-origin-message]') ? 'request:' + el.querySelector('[data-origin-message]').dataset.originMessage : null;
const oldByKey = new Map(oldItems.map(el => [key(el), el]).filter(([id]) => id));
const liveByKey = new Map(liveItems.map(el => [key(el), el]).filter(([id]) => id));
const desired = newItems.map(el => {
const id = key(el), old = id && oldByKey.get(id), live = id && liveByKey.get(id);
return old && live && old.outerHTML === el.outerHTML ? live : el;
});
for (let i = 0; i < desired.length; i++) if (liveLog.children[i] !== desired[i]) liveLog.insertBefore(desired[i], liveLog.children[i] || null);
while (liveLog.children.length > desired.length) liveLog.lastElementChild.remove();
window.MosaicRequests?.mount?.(c.container, { archiveUnknown: !!c.archiveUnknown, projectArchived: !!c.projectArchived });
const s = state(c.key ?? c.id);
if (s.tailRequested || s.follow && ((keep?.tail ?? true) || keep?.settlingPin)) pinTranscript(liveLog);
else if (keep?.top !== undefined) { if (pageFlow(liveLog)) window.scrollTo(0, keep.top); else liveLog.scrollTop = keep.top; }
s.tailRequested = false;
return true;
}
function updateConversations(c, next) {
if (c.kind !== 'project' || c.section !== 'conversations' || !lastPaint || lastPaint.container !== c.container || lastPaint.path !== c.path) return false;
const previous = document.createElement('template'); previous.innerHTML = lastPaint.html;
const oldList = previous.content.querySelector('[data-project-conversations]'), newList = next.content.querySelector('[data-project-conversations]');
const liveList = c.container.querySelector('[data-project-conversations]');
if (!oldList || !newList || !liveList) return false;
const oldItems = [...oldList.children], newItems = [...newList.children], liveItems = [...liveList.children];
oldList.replaceChildren(); newList.replaceChildren();
const normalize = template => {
const heading = template.content.querySelector('.project-heading p');
for (const node of heading?.childNodes || []) if (node.nodeType === Node.TEXT_NODE) node.data = node.data.replace(/\d+ conversations?/g, '# conversations');
for (const count of template.content.querySelectorAll('.project-tabs .project-count')) count.textContent = '#';
return visualKey(template.innerHTML);
};
if (normalize(previous) !== normalize(next)) return false;
const oldById = new Map(oldItems.filter(el => el.dataset.conversationId).map(el => [el.dataset.conversationId, el]));
const liveById = new Map(liveItems.filter(el => el.dataset.conversationId).map(el => [el.dataset.conversationId, el]));
const desired = newItems.map(el => {
const id = el.dataset.conversationId, old = oldById.get(id), live = liveById.get(id);
return old && live && old.outerHTML === el.outerHTML ? live : el;
});
const focused = liveList.contains(document.activeElement) ? document.activeElement : null;
for (let i = 0; i < desired.length; i++) if (liveList.children[i] !== desired[i]) liveList.insertBefore(desired[i], liveList.children[i] || null);
while (liveList.children.length > desired.length) liveList.lastElementChild.remove();
if (focused?.isConnected && document.activeElement !== focused) focused.focus({preventScroll:true});
const count = c.threads.filter(t => !t.shared && t.project === c.id).length;
const heading = c.container.querySelector('.project-heading p');
for (const node of heading?.childNodes || []) if (node.nodeType === Node.TEXT_NODE) { const value = node.data.replace(/\d+ conversations?/g, `${count} ${count === 1 ? 'conversation' : 'conversations'}`); if (node.data !== value) node.data = value; }
const tab = c.container.querySelector('.project-tabs [href$="/conversations"] .project-count');
if (tab && tab.textContent !== String(count)) tab.textContent = String(count);
return true;
}
function paint(navigated = false, read = false) {
if (!current || out()) return;
const keep = capture(), c = current;
const redesigned = (!legacyRoute() || c.path?.startsWith('/projects')) && !!window.MosaicProjects && !c.user && !c.tester;
let html = '<div class="chat-area"><p><a href="#/projects">Projects</a></p>';
if (c.orgArchived) html += `<p role="status">${c.orgArchived === 'room-not-open' ? 'This room is not open.' : 'This organization is archived.'} Sending is unavailable; your draft is kept.</p>`;
if (c.error && !(c.kind === 'room' && c.error === ROOM_LINES['room-not-open'] && redesigned)) html += `<p class="chat-error banner err" role="alert">${txt(c.error)}</p>`;
if (c.archiveUnknown && !c.loading) html += '<p role="status" data-archive-notice>Archive status unavailable. Some changes are unavailable; sending may be refused; refresh to check.</p>';
else if (c.kind === 'thread' && c.projectArchived) html += '<p role="status">This project is archived; its conversation stays readable.</p>';
if (c.readFailed && (c.kind === 'thread' ? state(c.key).loaded : c.projects.length || c.threads.length)) html += '<p role="status">Showing previously read chat content; it may be out of date.</p>';
if (c.kind === 'room') {
html += c.refused ? heading('Room unavailable') : roomConversation();
} else if (c.kind === 'thread') {
const t = c.thread;
if (t && (c.session || c.legacyDefault) && !c.refused) html += conversation(t);
else if (c.loading) html += '<p role="status">Reading conversation…</p>';
else html += heading('Conversation unavailable') + '<button type="button" class="btn" data-chat-retry>Read again</button>';
} else if (c.kind === 'project') {
const p = c.projects.find(p => p.id === c.id);
html += p && !c.refused && redesigned ? window.MosaicProjects.header(p, c.section, c.threads) : heading(p?.name ?? 'Project unavailable');
if (p && !c.refused) {
if (p.archived && redesigned && !c.canSend) html += '<p class="project-panel" role="status">This project is archived. Its saved conversations and records stay readable.</p>';
if (c.settings) html += `<p><a href="#/projects/${esc(c.id)}">Project overview</a></p><h2>Project information</h2><p>Repository: ${txt(p.repo || 'Not linked')}</p><div data-chat-remote>Repository setting unavailable.</div>`;
else if (c.section === 'conversations' && redesigned) html += `<div class="project-section-title"><h2>Conversations</h2></div><div data-project-conversations>${c.threads.filter(t=>!t.shared && t.project===p.id).map(t=>`<a class="project-conversation-row" href="${threadPath(esc(t.id))}" data-conversation-id="${esc(t.id)}"><span class="project-conversation-icon" aria-hidden="true">◌</span><span><strong>${txt(t.name)}</strong><small>With ${txt(t.instance)}</small></span><span data-conversation-status></span><span aria-hidden="true">›</span></a>`).join('') || '<p>No conversations yet. Start one to begin work.</p>'}</div>${p.archived ? '' : `<details class="project-new-conversation"${location.hash.includes('new=1')?' open':''}><summary class="btn primary">New conversation</summary>${creation('thread', c.id)}</details>`}<h2>Shared with me</h2>${c.threads.some(t=>t.shared && t.project===p.id)?threads(c.threads.filter(t=>t.shared && t.project===p.id)):'<p>Nothing is shared with you yet.</p>'}`;
else if (c.section === 'conversations') html += '<h2>Conversations</h2>' + threads(c.threads.filter(t => !t.shared)) + (p.archived ? '' : creation('thread', c.id));
else if (redesigned) html += '<div data-project-content>Reading…</div>';
else html += `<p><a href="#/projects/${esc(c.id)}/settings">Project information</a></p>${knownRequests.get(c.id)?.repo === p.repo && knownRequests.get(c.id)?.ids.size ? '<p>Request status from conversations opened in this session. Other work may not be shown.</p><div data-chat-summary></div>' : '<p>Request status is not loaded. Open a conversation to see its requests.</p>'}<h2>Conversations</h2>` + roomOpenControl(c.id) + threads(c.threads.filter(t => !t.shared)) + '<h2>Shared with me</h2>' + threads(c.threads.filter(t => t.shared)) + (p.archived ? '' : creation('thread', c.id));
}
} else if (redesigned) {
html += '<div class="project-list-head">' + heading('Projects') + '<p>Projects and their conversations.</p></div>' + (c.canSend ? '<details class="project-create"><summary class="btn primary">New project</summary>' + creation('project', 'projects') + '</details>' : '') + '<div class="chat-projects">' +
c.projects.filter(p => !p.archived).map(p => `<a class="project-card" href="${projectPath(esc(p.id))}"><span class="project-card-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M3 6h7l2 2h9v11H3z"/></svg></span><strong>${txt(p.name)}</strong><span>${p.repo ? `Repository: ${txt(p.repo)}` : 'No linked repository'}</span><span data-project-status="${esc(p.id)}">Reading…</span></a>`).join('') + (c.projects.length ? '' : c.readFailed ? '<p>Projects unavailable.</p>' : '<p>No projects yet.</p>') + '</div><h2>Shared with me</h2>' + (c.threads.some(t => t.shared) ? threads(c.threads.filter(t => t.shared)) : '<p>Nothing is shared with you yet.</p>');
} else {
html += heading('Projects') + '<p>Projects and their conversations.</p><div class="chat-projects">' + c.projects.map(p => `<section class="panel"><h2>${link('projects', p.id, p.name)}</h2>${p.repo ? `<p class="muted">Repository: ${txt(p.repo)}</p>` : ''}${threads(c.threads.filter(t => t.project === p.id && !t.shared))}</section>`).join('') + (c.projects.length ? '' : c.readFailed ? '<p>Projects unavailable.</p>' : '<p>No projects yet.</p>') + '</div><h2>Shared with me</h2>' + threads(c.threads.filter(t => t.shared)) + creation('project', 'projects');
}
if (!c.canSend) html += window.MosaicOrgBusStopped ? '<p class="muted">The bus is stopped. Use Start the bus to send messages.</p>' : '<p class="muted">Creating and sending require signed-in send mode. This Console only reads.</p>';
html += '</div>';
// Drafts already live in the focused textarea; their changing text is not a
// reason for a background read to replace the control.
const fingerprint = visualKey(html);
if (read && !navigated && lastPaint?.container === c.container && lastPaint.path === c.path && lastPaint.fingerprint === fingerprint && c.container.querySelector('.chat-area')) {
lastPaint.html = html;
refreshLibraryAge(c);
refreshProjectData(c, redesigned, keep);
refreshRequestData(c, true);
updateRoomCompletion();
return;
}
const next = document.createElement('template');
next.innerHTML = html;
if (read && !navigated && (updateTranscript(c, html, next, keep) || updateConversations(c, next))) {
lastPaint = { container: c.container, path: c.path, html, fingerprint };
refreshLibraryAge(c);
refreshProjectData(c, redesigned, keep);
refreshRequestData(c, true);
updateRoomCompletion();
return;
}
// updateTranscript empties the template log while comparing the rest.
next.innerHTML = html;
// Keep existing, unchanged message nodes when a later read adds more messages.
if (!navigated && lastPaint?.container === c.container && lastPaint.path === c.path) {
for (const message of next.content.querySelectorAll('[data-message]')) {
const previous = [...c.container.querySelectorAll('[data-message]')].find(el => el.dataset.message === message.dataset.message);
if (previous && previous.outerHTML === message.outerHTML) message.replaceWith(previous);
}
}
lastPaint = { container: c.container, path: c.path, html, fingerprint };
transcriptObserver?.disconnect(); transcriptResize?.disconnect();
c.container.replaceChildren(next.content);
const observedLog = c.container.querySelector('.project-chat .chat-log');
if (observedLog) {
const observedState = state(c.key ?? c.id);
const pin = () => { if (observedLog.isConnected && observedState.follow) pinTranscript(observedLog); };
transcriptObserver = new MutationObserver(pin);
transcriptObserver.observe(observedLog, { childList: true, subtree: true, characterData: true });
// The log's height settles after paint (composer and request card layout); re-pin while following.
if (typeof ResizeObserver === 'function') {
transcriptResize = new ResizeObserver(pin);
transcriptResize.observe(observedLog);
if (pageFlow(observedLog)) transcriptResize.observe(c.container);
}
}
refreshRequestData(c, false);
const remote = c.container.querySelector('[data-chat-remote]');
const project = c.projects.find(p => p.id === c.id);
if (remote && roomOwner() && typeof window.MosaicProjectRemote?.mount === 'function') { remote.replaceChildren(); window.MosaicProjectRemote.mount({ container: remote, projectId: c.id, repositoryKey: project?.repo ?? null, projectArchived: !!c.projectArchived, preserve: true }); }
if (!window.MosaicOrg && (!redesigned || c.kind !== 'project' || c.settings || c.projectArchived)) window.MosaicProjectArchive?.mount(c.container, c);
if (redesigned && c.kind === 'project' && c.projectArchived && !c.settings) {
const controls = c.container.querySelector('.project-archive-control');
if (controls) c.container.querySelector('.project-tabs')?.insertAdjacentElement('afterend', controls);
}
refreshProjectData(c, redesigned, !navigated ? keep : null);
document.title = `${c.container.querySelector('h1')?.textContent ?? 'Chat'} · Mosaic Console`;
if (!navigated && keep?.toggles) [...c.container.querySelectorAll('.project-new-conversation,.project-create')].forEach((e,i)=>{e.open=!!keep.toggles[i];});
const details = c.container.querySelector('.chat-details');
if (details && keep?.detailsOpen && details.tagName === 'DETAILS') details.open = true;
if (!navigated && keep?.dialog) {
const dialog = document.getElementById(keep.dialog), kind = keep.dialog === 'project-room-dialog' ? 'room' : 'conversation';
if (dialog && !dialog.open) {
c.container.querySelector(`[data-project-dialog="${kind}"]`)?.focus({preventScroll:true});
dialog.showModal();
for (const saved of keep.dialogValues || []) { const control=document.getElementById(saved.id); if(control && dialog.contains(control)) { control.value=saved.value; if('checked' in control) control.checked=saved.checked; } }
const focus = keep.dialogFocus && (keep.dialogFocus.id ? document.getElementById(keep.dialogFocus.id) : dialog.querySelectorAll('button,a,input,select,textarea,[tabindex]')[keep.dialogFocus.index]);
if (focus && !focus.disabled) {
if (keep.dialogFocus.value !== null && 'value' in focus) focus.value = keep.dialogFocus.value;
focus.focus({preventScroll:true});
if (keep.dialogFocus.start != null && typeof focus.setSelectionRange === 'function') focus.setSelectionRange(keep.dialogFocus.start,keep.dialogFocus.end);
} else dialog.querySelector('h2')?.focus({preventScroll:true});
}
}
const tabs = c.container.querySelector('.project-tabs');
if (tabs) {
if (navigated) tabs.querySelector('[aria-current]')?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
else {
if (keep?.tabScroll !== undefined) tabs.scrollLeft = keep.tabScroll;
window.MosaicProjects?.revealTab(tabs);
}
}
const log = c.container.querySelector('.chat-log');
if (log) {
const s = state(c.key ?? c.id);
if (navigated) s.follow = true;
if (navigated || s.tailRequested || s.follow && ((keep?.tail ?? true) || keep?.settlingPin)) pinTranscript(log);
else if (keep?.top !== undefined) { if (pageFlow(log)) window.scrollTo(0, keep.top); else log.scrollTop = keep.top; }
s.tailRequested = false;
}
if (!navigated && keep?.field) {
const f = document.getElementById(keep.field.id);
if (f && !f.disabled) {
f.focus({ preventScroll: true });
if (keep.field.start != null && typeof f.setSelectionRange === 'function') f.setSelectionRange(keep.field.start, keep.field.end);
}
} else if (navigated) c.container.querySelector('h1')?.focus({ preventScroll: true });
updateRoomCompletion();
}
function readError(err) {
return err.code === 'channel-disabled' ? channelMessage : err.code === 'thread-not-owned' ? 'This thread is not available to this user.' :
err.code === 'thread-not-found' ? 'Thread not found.' :
err.code === 'session-not-found' ? 'Session not found in this thread.' : 'Chat could not be read. Refresh to try again; your draft is kept.';
}
async function render({ path, container, canSend, user = false, tester = false, navigated = false, next = false }) {
if (out()) return;
const originalPath = path;
const sectionRoute = /^\/projects\/([0-9a-f-]+)\/(settings|conversations|tasks|requirements|files)$/i.exec(path);
const settings = sectionRoute?.[2] === 'settings';
const section = sectionRoute?.[2] ?? 'overview';
if (sectionRoute) path = '/chat/projects/' + sectionRoute[1];
else if (path === '/projects') path = '/chat';
else if (/^\/projects\/(threads|rooms)\//.test(path)) path = '/chat/' + path.slice('/projects/'.length);
else if (/^\/projects\/[0-9a-f-]+$/i.test(path)) path = '/chat/projects/' + path.slice('/projects/'.length);
if (/^\/chat\/rooms(?:\/|$)/.test(path)) return renderRoom({ path, originalPath, container, canSend, user, tester, navigated, next });
const match = /^\/chat(?:\/(projects|threads)\/([0-9a-f-]+)(?:\/sessions\/([0-9a-f-]+))?)?$/.exec(path);
controller?.abort(); controller = new AbortController();
const signal = controller.signal, g = ++generation;
const kind = match?.[1] === 'projects' ? 'project' : match?.[1] === 'threads' ? 'thread' : 'list';
const id = match?.[2];
if (!match || (id && !UUID.test(id)) || match?.[3] && (kind !== 'thread' || !UUID.test(match[3]))) {
current = { container, kind: 'list', canSend, projects: [], threads: [], repos: [], error: 'Invalid chat route.', refused: true };
paint(); return;
}
const old = current;
current = { container, kind, id, orgArchived: old?.orgArchived ?? false, loading: true, archiveUnknown: kind === 'thread' && !user && !tester, settings: !!settings, section, path: originalPath, canSend, user, tester, chatGrants: [], thread: old && old.id === id ? old.thread : null, shared: old && old.id === id ? old.shared : false, projects: old?.projects ?? [], threads: old?.threads ?? [], repos: old?.repos ?? [], instances: old?.instances ?? [], instanceError: kind === 'project' ? 'Reading thread instances…' : '', error: '', readFailed: false, channelDisabled: old?.channelDisabled ?? false, refused: false, legacyDefault: old && old.id === id ? old.legacyDefault : false, sessions: old && old.id === id ? old.sessions ?? [] : [], session: match[3] ?? (old && old.id === id ? old.session : null), key: match[3] ? id + '/' + match[3] : old && old.id === id ? old.key : id };
current.projectArchived = current.projects.some(p => p.id === (kind === 'project' ? id : current.thread?.project) && p.archived);
if (kind === 'thread' && old?.kind === 'thread' && old.id === id && !navigated && old.archiveUnknown === false && old.projects.some(p => p.id === old.thread?.project)) current.archiveUnknown = false;
if (current.projectArchived) current.archiveUnknown = false;
// Keep the previous conversation in place, but immediately withdraw controls whose
// server paths lack archive guards, and the request panel's writes.
const withdraw = () => {
lastPaint = null;
for (const el of container.querySelectorAll('#chat-session-form input, #chat-session-form button, #chat-share-form input, #chat-share-form button, [data-unshare], #chat-cancel, [data-revert]')) el.disabled = true;
window.MosaicRequests?.mount?.(container, { archiveUnknown: !!current.archiveUnknown, projectArchived: !!current.projectArchived });
if (!current.archiveUnknown) return;
if (container.querySelector('[data-archive-notice]')) return;
const notice = document.createElement('p');
notice.dataset.archiveNotice = '';
notice.setAttribute('role', 'status');
notice.textContent = 'Archive status unavailable. Some changes are unavailable; sending may be refused; refresh to check.';
container.querySelector('.chat-area')?.prepend(notice);
};
const withdrawn = !(navigated || !old) && current.archiveUnknown;
if (navigated || !old) container.innerHTML = '<p class="chat-loading" role="status">Reading chat…</p>';
else if (current.archiveUnknown) withdraw(); // archive lookup pending
try {
if (user) {
const config = await fetch('/api/config', { cache: 'no-store', redirect: 'manual', signal });
if (config.type === 'opaqueredirect' || config.status === 401) { signOut(); return; }
if (!config.ok) throw new ChatError('invalid-response');
const hints = await config.json();
if (g !== generation || out()) return;
current.chatGrants = Array.isArray(hints.chatGrants) ? hints.chatGrants : [];
current.canSend = hints.send === true;
}
// Resolve the explicit session before touching history/cursors. Missing selectors never
// silently fall back to a sibling. The saved default is used only for thread-only routes.
const [projects, listed, shared] = await Promise.all([
request('projects', undefined, signal),
request('threads' + (kind === 'project' ? '?project=' + id : ''), undefined, signal),
tester ? { rows: [] } : request('threads?shared=true' + (kind === 'project' ? '&project=' + id : ''), undefined, signal).catch(err => {
if (err.code !== 'access-revoked') err.sharedRead = true;
throw err;
}),
]);
if (g !== generation || out()) return;
current.channelDisabled = false;
current.orgArchived = false;
current.projects = projects.rows;
const own = new Set(listed.rows.map(t => t.id));
current.threads = [...listed.rows, ...shared.rows.filter(t => !own.has(t.id)).map(t => ({ ...t, shared: true }))];
current.thread = current.threads.find(t => t.id === id);
current.shared = current.thread?.shared === true;
const projectId = kind === 'project' ? id : current.thread?.project;
if (projectId && !current.projects.some(p => p.id === projectId) && !user && !tester) {
try {
if (typeof window.MosaicProjectArchive?.resolve !== 'function') throw Error('archive-unavailable');
const resolved = await window.MosaicProjectArchive.resolve(projectId, signal);
if (g !== generation || out()) return;
if (resolved) current.projects = [...current.projects, resolved];
current.archiveUnknown = false;
} catch (err) {
if (kind !== 'thread' || err.name === 'AbortError') throw err;
if (g !== generation || out()) return;
// Unknown is neither live nor archived: history remains readable and the broker
// decides every attempted write. Do not silently claim the project is writable.
current.archiveUnknown = true;
}
}
else if (projectId) current.archiveUnknown = false;
current.projectArchived = current.projects.some(p => p.id === projectId && p.archived);
// A same-thread refresh kept the controls of the last resolved (live) state. If this
// lookup now finds the project archived or unknown, withdraw them before the slower
// session and history reads, not at the next paint.
if (kind === 'thread' && old && !navigated && !withdrawn && (current.archiveUnknown || current.projectArchived)) withdraw();
const catalog = kind === 'thread' && !current.shared ? await request(`threads/${id}/sessions`, undefined, signal).catch(err => {
if (err.code === 'access-refused' && !match[3]) return null;
throw err;
}) : null;
if (g !== generation || out()) return;
if (current.shared && match[3]) throw new ChatError('session-not-found', 404);
current.shares = [];
if (kind === 'thread' && current.canSend && threadWrites() && !tester) {
const shares = await request(`threads/${id}/shares`, undefined, signal).catch(() => ({ rows: [] }));
if (g !== generation || out()) return;
current.shares = shares.rows;
}
let s = null, page = null, after = null;
if (kind === 'thread' && catalog === null) {
current.legacyDefault = true; current.sessions = []; current.session = null;
current.key = id + '/legacy-default';
s = state(current.key);
after = s.loaded && (!s.more || next) ? s.after : null;
page = await request(`threads/${id}/messages?limit=100${after ? '&after=' + after : ''}`, undefined, signal);
if (g !== generation || out()) return;
}
if (catalog) {
if (catalog.rows.some(r => !UUID.test(r.id) || typeof r.name !== 'string')) throw new ChatError('invalid-response');
const selected = match[3] ? catalog.rows.find(r => r.id === match[3]) : catalog.rows.find(r => r.default === true);
if (!selected) throw new ChatError('session-not-found', 404);
current.sessions = catalog.rows; current.session = selected.id; current.key = id + '/' + selected.id;
s = state(current.key);
after = s.loaded && (!s.more || next) ? s.after : null;
page = await request(`threads/${id}/messages?limit=100&session=${selected.id}${after ? '&after=' + after : ''}`, undefined, signal);
if (g !== generation || out()) return;
const clear = form('clear:' + current.key);
if (clear.op && !clear.pending) {
try {
const op = clear.op;
const receipt = await request(`threads/${id}/operation?op=${encodeURIComponent(op)}`, undefined, signal);
if (g !== generation || out()) return;
if (clear.op !== op) return;
clear.record = receipt; clear.receipt = clearText(receipt);
} catch (err) {
if (g !== generation || out() || err.name === 'AbortError') return;
clear.receipt = err.code === 'channel-disabled' ? `${channelMessage} Operation ${clear.op}; no write was retried.` : `Status unavailable (${inert(err.code)}). Operation ${clear.op}; no write was retried.`;
}
}
}
if (s) {
if (typeof page.hasMore !== 'boolean' || !(page.after === null || UUID.test(page.after))) throw new ChatError('invalid-response');
if (catalog) current.legacyDefault = false;
const rows = after ? [...s.rows, ...page.rows] : page.rows;
s.rows = [...new Map(rows.map(m => [m.id, m])).values()].slice(-200);
// Missing requests are retried on an observed thread change, never on a timer: the owner
// opening the thread (navigated), a different newest message on a caught-up thread, or a
// mosaic-request-state for the id. Repaints, the refresh timer and history paging are not.
// The thread page reads only messages, so a request opened with no new message stays hidden
// until one of those happens or the page reloads.
if (navigated) {
s.requestEpoch = (s.requestEpoch ?? 0) + 1;
s.missingRequests?.clear();
}
if (!page.hasMore) {
const tail = s.rows.at(-1)?.id ?? null;
if (s.requestTail !== undefined && s.requestTail !== tail) {
s.requestEpoch = (s.requestEpoch ?? 0) + 1;
s.missingRequests?.clear();
}
s.requestTail = tail;
}
// Keep misses and observation generations only for ids still in the retained rows, so
// memory stays within the row cap.
if (s.missingRequests?.size || s.requestSeen?.size) {
const held = new Set(s.rows.map(m => m.request));
for (const id of s.missingRequests ?? []) if (!held.has(id)) s.missingRequests.delete(id);
for (const id of s.requestSeen?.keys() ?? []) if (!held.has(id)) s.requestSeen.delete(id);
}
s.after = page.after ?? s.after; s.more = page.hasMore; s.loaded = true;
if (s.receiptId && s.rows.some(m => m.id === s.receiptId)) {
s.receipt = 'Message shown in this conversation.'; s.receiptId = null;
}
}
if (kind === 'project') {
try {
const listed = await request('instances', undefined, signal);
if (g !== generation || out()) return;
if (!listed.rows.every(row => typeof row?.instance === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,159}$/.test(row.instance) && typeof row.name === 'string'))
throw new ChatError('invalid-response');
current.instances = listed.rows.filter(r => scopeWrites(id, r.instance)); current.instanceError = '';
const f = form(id);
if (f.instance && !current.instances.some(row => row.instance === f.instance)) {
f.instance = ''; f.instanceChosen = true;
f.receipt = 'The selected instance is no longer available. Choose who this conversation is with.';
}
if (!f.instanceChosen && !f.instance && current.instances.length === 1) f.instance = current.instances[0].instance;
} catch (err) {
if (err.name === 'AbortError' || out() || g !== generation) return;
current.instances = [];
current.instanceError = err.code === 'channel-disabled' ? channelMessage : "Couldn't read the thread instances; reload to try again";
if (err.code === 'channel-disabled') current.channelDisabled = true;
}
}
// Repository choices are optional metadata; an unavailable read must not block unlinked chat.
if (kind === 'list') {
try {
const r = await fetch('/api/business', { cache: 'no-store', redirect: 'manual', signal });
if (r.type === 'opaqueredirect' || r.status === 401) { signOut(); return; }
if (r.ok) {
const business = await r.json();
if (g !== generation || out()) return;
const projects = business.business?.projects ?? business.projects;
current.repos = Array.isArray(projects) ? projects.filter(v => typeof v === 'string') : [];
}
} catch (err) { if (err.name === 'AbortError') return; }
}
if (g === generation) {
current.loading = false;
if ((kind === 'thread' && current.thread || kind === 'project') && !current.refused) {
const projectId = kind === 'thread' ? current.thread.project : id;
const project = current.projects.find(p => p.id === projectId);
if (project && kind === 'thread' && roomOwner() && typeof project.repo === 'string') {
const prior = knownRequests.get(projectId);
const ids = prior?.repo === project.repo ? prior.ids : new Set();
for (const row of state(current.key).rows) if (row.from_role === 'human' && typeof row.request === 'string' && REQUEST_ID.test(row.request)) ids.add(row.request);
knownRequests.set(projectId, { repo: project.repo, ids });
}
if (project) document.dispatchEvent(new CustomEvent('mosaic-project-context', { detail: { projectId, repositoryKey: project.repo ?? null, thread: kind === 'thread' ? id : null, session: kind === 'thread' ? current.session : null } }));
}
paint(navigated, true);
const t = kind === 'thread' ? current.threads.find(t => t.id === id) : null;
if (t) void loadLibrary(libraryOf(current, t), g, signal);
}
} catch (err) {
if (g !== generation || out() || err.name === 'AbortError' || err.code === 'signed-out') return;
current.loading = false;
current.error = readError(err);
if (err.code === 'org-archived' || err.code === 'room-not-open') current.orgArchived = err.code;
current.readFailed = true;
if (err.code === 'channel-disabled') current.channelDisabled = true;
// A bad session selector is local to that read. Only a thread-level refusal
// invalidates all sibling drafts, receipts and recovery operation keys.
if (!err.sharedRead && ['thread-not-owned', 'thread-not-found', 'access-refused'].includes(err.code)) {
knownRequests.clear();
for (const key of states.keys()) if (key === id || key.startsWith(id + '/')) states.delete(key);
for (const key of forms.keys()) if (key.includes(id)) forms.delete(key);
}
if (!err.sharedRead && (err.status === 403 || err.status === 404)) {
current.projects = []; current.threads = []; current.thread = null; current.shared = false; current.refused = true;
}
current.projectArchived = current.projects.some(p => p.id === (kind === 'project' ? id : current.thread?.project) && p.archived);
if (current.projects.some(p => p.id === (kind === 'project' ? id : current.thread?.project))) current.archiveUnknown = false;
else if (kind === 'thread' && !user && !tester) current.archiveUnknown = true;
paint(navigated, true);
}
}
function refresh(next = false) {
if (current) return render({ ...current, path: (window.MosaicOrg?.route() ?? location.hash.slice(1)).split('?')[0], next });
}
function leave(path) {
if (!path.startsWith('/chat') && !path.startsWith('/projects')) { generation++; controller?.abort(); current = null; }
}
document.addEventListener('input', event => {
if (!current || out()) return;
if (event.target.id === 'chat-room-body') { state(current.key).draft = event.target.value; updateRoomCompletion(); return; }
if (event.target.id === 'chat-operation') { const f = form('clear:' + current.key); if (f.pending) return; f.op = event.target.value; f.record = null; const button = document.getElementById('chat-cancel'); if (button) button.disabled = !current.canSend || current.archiveUnknown || current.projectArchived || f.pending || !f.op; }
if (event.target.id === 'chat-share-target') form('share:' + current.id).to = event.target.value;
if (event.target.id === 'chat-body') state(current.key ?? current.id).draft = event.target.value;
const f = event.target.closest('.chat-create');
if (f && event.target.dataset.chatField) {
const draft = form(f.dataset.key), field = event.target.dataset.chatField;
draft[field] = event.target.value;
if (field === 'instance') { draft.instanceChosen = true; draft.receipt = ''; paint(); }
}
});
let pageReaderInput = false, readerMark = 0, settleMark = 0, pageTop = 0;
// User input cancels a pending page pin, including scrollbar dragging.
// Tab counts from any target: it moves focus and can scroll the document.
const readerInput = event => {
if (!['thread', 'room'].includes(current?.kind)) return;
if (event.type === 'keydown' && event.key !== 'Tab' && (!['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '].includes(event.key) || event.target.closest?.('input, textarea, select, button, a, [contenteditable=true]'))) return;
if (event.type === 'pointerdown' && event.target !== document.documentElement && event.target !== document.body && !event.target.matches?.('.chat-log')) return;
const log = current.container.querySelector('.chat-log');
if (!log) return;
if (pageFlow(log)) {
pageReaderInput = true;
pinnedScrolls.delete(document.scrollingElement);
// Input that scrolls nothing must not mark a later layout scroll as the reader's.
const mark = ++readerMark;
requestAnimationFrame(() => requestAnimationFrame(() => { if (mark === readerMark) pageReaderInput = false; }));
}
else if (event.key === 'Tab' || event.target === log || log.contains(event.target)) { pinnedScrolls.delete(log); settlingPins.delete(log); }
};
for (const type of ['wheel', 'touchstart', 'pointerdown', 'keydown']) document.addEventListener(type, readerInput, true);
document.addEventListener('scroll', event => {
if (!['thread', 'room'].includes(current?.kind)) return;
const log = current.container.querySelector('.chat-log');
if (!log) return;
const scroller = pageFlow(log) ? document.scrollingElement : log;
if (event.target !== scroller && !(scroller === document.scrollingElement && event.target === document)) return;
const pinned = pinnedScrolls.get(scroller);
pinnedScrolls.delete(scroller);
const s = state(current.key ?? current.id);
// In page flow the document also moves for layout (scroll anchoring pushes it
// down as content grows) and for focus, find and in-page reveals (usually up).
// While following, only a downward move with no reader input is re-pinned.
if (scroller !== log) {
const top = scroller.scrollTop, down = top > pageTop, reader = pageReaderInput;
pageTop = top;
pageReaderInput = false;
if (pinned !== undefined && top === pinned && !reader) return;
if (!reader && down && s.follow) { pinTranscript(log); pageTop = scroller.scrollTop; return; }
s.follow = transcriptAtTail(log, down);
return;
}
if (pinned !== undefined && scroller.scrollTop === pinned) {
if (transcriptAtTail(log)) return;
// Allow the resize observer to settle a shrinking log before treating an
// old matching offset as a reader scroll away from newly grown content.
// Preserve the pin's provenance if paint replaces this log before settling.
// Reader input may drop that provenance, but the classification still runs:
// input that scrolls nothing gives no later scroll event to decide it.
settlingPins.set(log, pinned);
const mark = ++settleMark;
// Resize delivery can lag the scroll event by several frames. Keep the
// provenance long enough for the observer to restore a following tail.
const settle = frames => frames ? requestAnimationFrame(() => settle(frames - 1)) : (() => {
if (mark !== settleMark) return;
if (settlingPins.get(log) === pinned) settlingPins.delete(log);
if (log.isConnected && scroller.scrollTop === pinned && !transcriptAtTail(log)) s.follow = false;
})();
settle(6);
return;
}
s.follow = transcriptAtTail(log);
}, true);
async function write(action, key, value, path) {
if (!current || !current.canSend || current.orgArchived || out() || current.channelDisabled) return;
const isThread = action === 'send' || action === 'open';
if ((isThread || action === 'createSession') && !threadWrites()) return;
if (action === 'createSession' && current.archiveUnknown) return;
if (action === 'createProject' && current.user || action === 'createThread' && !scopeWrites(value.project, value.instance)) return;
const targetThread = current.id;
const s = isThread ? state(key) : form(key);
if (s.pending || isThread && selectedInactive()) return;
if (action === 'send' && (!value.body.trim() || new TextEncoder().encode(JSON.stringify(value)).length > 16384)) {
s.receipt = value.body.trim() ? 'Message is too long (16 KiB JSON maximum).' : 'Write a message first.';
paint(); return;
}
const startedRoute = location.hash;
s.pending = true; s.receipt = ''; paint();
try {
const result = await request(path, value);
if (out()) return;
if (action === 'open' ? result.opened !== targetThread : !UUID.test(result.id)) throw new ChatError('outcome-unknown');
if (action === 'send') {
s.receipt = `Accepted message ${result.id}. Waiting for the conversation to show it.`;
if (s.draft === value.body) s.draft = '';
s.follow = true; s.tailRequested = true; s.receiptId = result.id;
} else if (action === 'open') s.receipt = 'Assistant resume requested.';
else {
s.name = ''; s.repo = ''; s.op = null; s.payload = null;
if (location.hash === startedRoute) location.hash = action === 'createSession' ? sessionPath(targetThread, result.id) : (action === 'createProject' ? projectPath(result.id) : threadPath(result.id));
}
} catch (err) {
if (out() || err.code === 'signed-out') return;
s.receipt = err.sent === false ? (err.code === 'channel-disabled' ? `Not sent. ${channelMessage} Your draft is kept.` : `Not sent (${inert(err.code)}). Your draft is kept.`) :
`${err.code === 'channel-disabled' ? channelMessage + ' ' : ''}Outcome unknown. Read the current list or conversation before trying again. Nothing was retried; your draft is kept.`;
if (err.code === 'channel-disabled' && current) current.channelDisabled = true;
if (action === 'createSession' && err.sent === false) { s.op = null; s.payload = null; }
if (err.status === 403 && ['thread-not-owned', 'access-refused'].includes(err.code)) {
states.delete(key);
if ((current?.key ?? current?.id) === key) { current.threads = []; current.refused = true; current.error = readError(err); }
}
} finally {
s.pending = false;
if (!out() && current && (isThread ? (current.key ?? current.id) === key : (action === 'createSession' ? current.id === targetThread : key === 'projects' ? current.kind === 'list' : current.id === key))) paint();
}
}
document.addEventListener('submit', event => {
if (!current || !event.target.id.startsWith('chat-')) return;
event.preventDefault();
if (event.target.id === 'chat-room-send-form') {
void sendRoom();
} else if (event.target.id === 'chat-share-form') {
void changeShare('share', form('share:' + current.id).to ?? '');
} else if (event.target.id === 'chat-send-form') {
const id = current.id, session = current.session, key = current.key;
void write('send', key, { body: state(key).draft, ...(session ? { session } : {}) }, `threads/${id}/messages`);
} else if (event.target.id === 'chat-session-form') {
const key = 'session:' + current.id, f = form(key);
// Keep an ambiguous create's key and payload; editing requires a deliberate new attempt.
f.op ??= opId();
f.payload ??= { name: f.name, op: f.op };
void write('createSession', key, f.payload, `threads/${current.id}/sessions`);
} else if (event.target.id === 'chat-operation-form') {
const clear = form('clear:' + current.key);
clear.op = document.getElementById('chat-operation').value;
void checkClear(current.id, current.key, clear);
} else if (event.target.classList.contains('chat-create')) {
const key = event.target.dataset.key, f = form(key), project = key === 'projects';
if (!project && (current.instanceError || !(current.instances ?? []).some(row => row.instance === f.instance))) return;
const value = project ? { name: f.name, ...(f.repo ? { repo: f.repo } : {}) } : { project: key, name: f.name, instance: f.instance };
void write(project ? 'createProject' : 'createThread', key, value, project ? 'projects' : 'threads');
}
});
document.addEventListener('click', event => {
if (!current || out()) return;
if (event.target.id === 'chat-room-open' || event.target.closest?.('[data-room-open-inline]')) void openRoom();
const projectRoomOpen=event.target.closest?.('[data-project-room-open]'); if(projectRoomOpen && UUID.test(projectRoomOpen.dataset.projectRoomOpen)) void openRoom(projectRoomOpen.dataset.projectRoomOpen);
const chip = event.target.closest?.('[data-room-chip]');
if (chip) { const name = chip.dataset.roomChip; document.querySelector(`[data-room-member="${CSS.escape(name)}"]`)?.click(); document.querySelector(`[data-room-chip="${CSS.escape(name)}"]`)?.focus(); }
const offer = event.target.closest?.('[data-room-offer]');
if (offer && current.kind === 'room') {
const field = document.getElementById('chat-room-body'), parsed = roomAddress(field.value), name = offer.dataset.roomOffer;
if (parsed.tags.length && current.members.some(m => m.instance === name) && !parsed.tags.includes(name)) {
state(current.key).draft = [...parsed.tags, name].map(tag => '@' + tag).join(' ') + ' ' + parsed.body;
paint();
}
}
const option = event.target.closest?.('[data-room-complete]');
if (option) completeRoom(option.dataset.roomComplete);
if (event.target.dataset.unshare) void changeShare('unshare', event.target.dataset.unshare);
if (event.target.id === 'chat-resume') void write('open', current.key, current.session ? { session: current.session } : {}, `threads/${current.id}/open`);
if (event.target.id === 'chat-cancel') void cancelClear();
if (event.target.id === 'chat-clear') void clearContext();
if (event.target.id === 'chat-next') void refresh(true);
if (event.target.closest?.('[data-chat-retry]')) void refresh();
const revertButton = event.target.closest?.('[data-revert]');
if (revertButton) void revert(revertButton.dataset.revert);
if (event.target.id === 'chat-new') { state(current.key ?? current.id).tailRequested = true; state(current.key ?? current.id).follow = true; paint(); }
});
document.addEventListener('change', event => {
if (event.target.matches?.('[data-room-member]') && current?.kind === 'room') {
const field = document.getElementById('chat-room-body'), s = state(current.key);
const parsed = roomAddress(field.value);
if (parsed.tags.some(tag => !current.members.some(m => m.instance === tag))) {
s.receipt = 'Repair the unresolved address before changing recipients. Your draft is kept.'; paint(); return;
}
const chosen = [...document.querySelectorAll('[data-room-member]:checked')].map(el => el.dataset.roomMember);
if (!chosen.length) { s.receipt = 'Choose at least one recipient. Your draft is kept.'; paint(); return; }
s.draft = chosen.map(name => '@' + name).join(' ') + (parsed.body ? ' ' + parsed.body : ' ');
s.receipt = ''; paint(); return;
}
if (event.target.id === 'chat-session' && current && UUID.test(event.target.value)) {
location.hash = sessionPath(current.id, event.target.value);
}
});
async function changeShare(op, to) {
if (!current?.canSend || !threadWrites() || current.archiveUnknown || current.tester || out()) return;
const id = current.id, f = form('share:' + id);
if (f.pending || !to.trim()) return;
f.pending = true; f.receipt = ''; paint();
try {
const r = await request(`threads/${id}/${op}`, { to });
if (r.thread !== id || r.to !== to || r.op !== op) throw new ChatError('outcome-unknown');
f.receipt = op === 'share' ? 'Shared read-only.' : 'Share ended.';
if (op === 'share') f.to = '';
} catch (e) {
f.receipt = e.sent === false ? (e.code === 'channel-disabled' ? `Share refused. ${channelMessage}` : `Share refused (${inert(e.code)}).`) : `${e.code === 'channel-disabled' ? channelMessage + ' ' : ''}Outcome unknown. Read shares before trying again; nothing was retried.`;
} finally {
f.pending = false;
if (!out() && current?.id === id) { await refresh(); paint(); }
}
}
const clearText = r => r.state === 'cancelled' ? `Operation ${r.op}: ${r.retired === true ? 'startup cancelled; old session remains retired' : 'replacement cancelled; old session active'}. Cancelled inputs are not replayed.` : `Operation ${r.op}: ${r.state}; successor ${r.successor}; start ${r.start ?? 'pending'}${r.refusal ? '; ' + r.refusal : ''}. No stop is forced.`;
async function checkClear(thread, key, f) {
if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,159}$/.test(f.op ?? '')) { f.receipt = 'Enter a valid operation key.'; paint(); return; }
const op = f.op;
try {
const r = await request(`threads/${thread}/operation?op=${encodeURIComponent(op)}`);
if (out() || f.op !== op) return;
f.record = r; f.receipt = clearText(r);
if (current?.key === key) await refresh();
} catch (e) { if (!out()) f.receipt = e.code === 'channel-disabled' ? `${channelMessage} Operation ${f.op}; no write was retried.` : `Status unavailable (${inert(e.code)}). Operation ${f.op}; no write was retried.`; }
if (current?.key === key) paint();
}
async function cancelClear() {
const c = current, key = c.key, f = form('clear:' + key);
if (!c.canSend || !threadAccess() || c.archiveUnknown || c.projectArchived || out() || f.pending || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,159}$/.test(f.op ?? '')) return;
if (!window.confirm(`Cancel clear operation ${f.op}? Before retirement this restores the old session to active. After retirement it only cancels successor startup. Cancelled messages are never replayed, and nothing is un-retired.`)) return;
const op = f.op;
f.pending = true; paint();
try {
const r = await request(`threads/${c.id}/cancel`, { op, confirm: true });
if (out()) return;
f.record = r; f.receipt = clearText(r);
} catch (e) {
if (out()) return;
f.receipt = e.sent === false ? (e.code === 'channel-disabled' ? `Cancel refused. ${channelMessage}` : `Cancel refused (${inert(e.code)}).`) : `${e.code === 'channel-disabled' ? channelMessage + ' ' : ''}Outcome unknown. Check operation ${op}; cancel was not retried.`;
} finally {
f.pending = false;
if (!out() && current?.key === key) { await refresh(); paint(); }
}
}
async function clearContext() {
const c = current, key = c.key, selected = c.sessions.find(r => r.id === c.session), f = form('clear:' + key);
if (!c.canSend || !threadWrites() || out() || f.pending || selectedInactive() || !Number.isSafeInteger(selected?.revision)) return;
if (!window.confirm(`Clear context for "${selected.name}"? This ends this session after a safe stop and starts fresh context. History and the old checkout (including unpushed work) are retained. The successor uses a fresh approved checkout; old work is not copied. This can wait for safe stop or capacity.`)) return;
// A lost answer retains this key. Only status reads are allowed afterward.
if (f.op && !['cancelled', 'failed'].includes(f.record?.state)) { await checkClear(c.id, key, f); return; }
f.op = opId(); f.pending = true; f.receipt = `Operation ${f.op}: requesting clear.`; paint();
try {
const r = await request(`threads/${c.id}/clear`, { session: selected.id, revision: selected.revision, confirm: true, op: f.op });
if (out()) return;
f.record = r; f.receipt = clearText(r);
} catch (e) {
if (out()) return;
f.receipt = e.sent === false ? (e.code === 'channel-disabled' ? `Clear refused. ${channelMessage}` : `Clear refused (${inert(e.code)}).`) : `${e.code === 'channel-disabled' ? channelMessage + ' ' : ''}Outcome unknown. Check operation ${f.op}; nothing was retried.`;
if (e.sent === false) f.op = null;
} finally {
f.pending = false;
if (!out() && current?.key === key) { await refresh(); paint(); }
}
}
document.addEventListener('mosaic-signed-out', () => { signedOut = true; forget(); });
const hasDraft = () => [...states.values()].some(s => Boolean(s.draft?.trim())) || [...forms.values()].some(f => Boolean(f.name?.trim() || f.repo || f.instanceChosen));
window.MosaicChat = Object.freeze({ render, leave, forget, projectPath, hasDraft });
})();