Files
stack/packages/webui/src/public/projects.js
T
jason.woltje e12713f68e webui: render the project north star as markdown on the overview (F1, #1873)
The overview's Project direction panel printed north-star.md source as one
paragraph. It now mounts the same DOM-building markdown renderer the
requirements view uses, trims the preview to 500 characters at a word
boundary, and links to the full document in Docs. No raw HTML from the
document reaches the page; the fallback is a text node.

Quick Setup leaving no records was not reproduced on 00ef0bd30: all six
steps report done and the records step writes where the project view
reads. org-quick-live gains a records case that checks the six setup
POSTs, the records repository on disk and the live north-star read with
no button press. The manual records button stays for older projects.

Tests: projects-north-star-browser 1/0 (red before the change),
org-quick-live 4/0 twice on a fresh scratch instance.
2026-11-09 13:02:17 -06:00

340 lines
47 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.
/* Project navigation and presentation. Chat retains ownership of reads and writes. */
(() => {
'use strict';
const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const clean = v => esc(String(v ?? '').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u202a-\u202e\u2066-\u2069]/g, c => `\\u${c.charCodeAt(0).toString(16).padStart(4,'0')}`));
const folder='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 6h7l2 2h9v11H3z"/></svg>';
const icon = path => `<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="${path}"/></svg>`;
const starIcon=icon('m12 3 2.8 5.7 6.2.9-4.5 4.4 1.1 6.2L12 17.3l-5.6 2.9 1.1-6.2L3 9.6l6.2-.9z');
const documentIcon=icon('M6 3h8l4 4v14H6z M14 3v4h4 M9 12h6 M9 16h6');
const settingsIcon=icon('M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8z M19.4 15a8 8 0 0 0 0-6l1.5-1.2-1.5-2.6-1.8.7a8 8 0 0 0-5.2-3l-.4-1.9H9l-.4 1.9a8 8 0 0 0-5.2 3l-1.8-.7L.1 7.8 1.6 9a8 8 0 0 0 0 6L.1 16.2l1.5 2.6 1.8-.7a8 8 0 0 0 5.2 3L9 23h3l.4-1.9a8 8 0 0 0 5.2-3l1.8.7 1.5-2.6z');
const plusIcon=icon('M12 5v14 M5 12h14');
const chatIcon='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 4h18v14H8l-5 3z"/></svg>';
const sections = [['overview','Overview'],['room','Room'],['conversations','Conversations'],['tasks','Tasks'],['requirements','Requirements'],['files','Files']];
const path = (id, key) => key === 'overview' ? `#/projects/${id}` : key === 'room' ? `#/projects/rooms/${id}` : `#/projects/${id}/${key}`;
function header(project, section, threads = [], title = project.name, conversation = false) {
const id=encodeURIComponent(project.id);
const tabs=sections.map(([key,label]) => `<a href="${path(id,key)}"${section === key ? ' aria-current="page"' : ''}>${label}${key==='conversations'?` <span class="project-count">${threads.filter(t=>!t.shared && t.project===project.id).length}</span>`:''}</a>`).join('');
const count=threads.filter(t=>!t.shared && t.project===project.id).length;
return `<header class="project-header" data-project-id="${id}" data-project-name="${clean(project.name)}" data-project-section="${section}" data-project-conversation="${conversation}"><div class="project-heading"><span class="project-header-icon" aria-hidden="true">${conversation?chatIcon:folder}</span><div><h1 tabindex="-1">${clean(title)}</h1>${project.archived?'<span class="project-chip">Archived</span>':''}<p>${conversation ? 'With <span data-project-agent>assistant</span>' : (project.repo ? `Repository: ${clean(project.repo)}` : 'No linked repository') + ` · ${count} ${count===1?'conversation':'conversations'}`}<span data-project-context></span></p></div></div><div class="project-actions">${conversation?'<button type="button" class="btn" data-project-dialog="conversation" aria-label="Details"><span class="project-action-icon" aria-hidden="true"><svg class="i" viewBox="0 0 24 24"><path d="M4 7h9m4 0h3M4 17h3m4 0h9M13 4v6M7 14v6"/></svg></span><span class="project-action-label">Details</span></button>':`<a class="btn project-primary-action" href="${path(id,'requirements')}?section=north-star">${starIcon}North star</a><a class="btn project-primary-action" href="${path(id,'requirements')}?section=prd">${documentIcon}PRD</a><a class="btn project-primary-action" href="#/projects/${id}/settings">${settingsIcon}Settings</a>`}</div></header><nav class="project-tabs" aria-label="Project sections">${tabs}</nav>`;
}
// Bring a tab fully into the strip without moving the page.
function revealTab(nav, tab=nav?.querySelector('[aria-current]')) {
if(!nav || !tab) return;
const n=nav.getBoundingClientRect(), r=tab.getBoundingClientRect();
if(r.left<n.left) nav.scrollLeft-=n.left-r.left;
else if(r.right>n.right) nav.scrollLeft+=Math.min(r.right-n.right,r.left-n.left);
}
document.addEventListener('focusin',e=>{const tab=e.target.closest?.('.project-tabs a'); if(tab) revealTab(tab.parentElement,tab);});
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const storageKey=window.MosaicOrg ? `mosaic-project-tree:${window.MosaicOrg.id}` : 'mosaic-project-tree';
let treeRows=[], treeThreads=[], treeGeneration=0, treeState, treeRead=null, treeReadAt=0;
const treeFocus = new WeakMap();
try { treeState=JSON.parse(localStorage.getItem(storageKey) || '{}'); if (!treeState || Array.isArray(treeState) || typeof treeState !== 'object') treeState={}; } catch { treeState={}; }
async function read(url) {
const response=await fetch(url,{cache:'no-store',redirect:'manual'});
if(response.status===401 || response.type==='opaqueredirect') { document.dispatchEvent(new CustomEvent('mosaic-signed-out',{detail:{signIn:true}})); throw Error('signed-out'); }
if(!response.ok) { const body=await response.json().catch(()=>null); const error=Error('unavailable'); error.status=response.status; error.code=body?.error; throw error; }
return response.json();
}
function currentProject(route) {
const id=route.match(/^\/(?:projects|chat)\/(?:projects\/|rooms\/)?([0-9a-f-]{36})/i)?.[1];
if(id) return id;
const thread=route.match(/^\/(?:projects|chat)\/threads\/([0-9a-f-]{36})/i)?.[1];
return treeThreads.find(t=>t.id===thread)?.project;
}
function drawTree(container, route) {
if(!container?.isConnected || document.body.classList.contains('signed-out')) return;
const current=currentProject(route), threadId=route.match(/\/threads\/([0-9a-f-]{36})/i)?.[1], room=/\/rooms\//.test(route);
const html=`<ul class="project-tree-list">${treeRows.filter(p=>!p.archived && UUID.test(p.id)).map(p=>{
const expanded=Object.hasOwn(treeState,p.id)?treeState[p.id]:p.id===current;
const own=treeThreads.filter(t=>t.project===p.id && !t.shared && UUID.test(t.id)).slice(-5).reverse();
const active=p.id===current && !room && !threadId;
return `<li><div class="project-tree-row${active?' active':''}"><button type="button" data-project-disclosure="${p.id}" aria-expanded="${!!expanded}" aria-controls="project-children-${p.id}" aria-label="${expanded?'Collapse':'Expand'} ${clean(p.name)}">${expanded?'⌄':'›'}</button><a href="${path(p.id,'overview')}" title="${clean(p.name)}"${active?' aria-current="page"':''}>${folder}<span>${clean(p.name)}</span></a></div><ul id="project-children-${p.id}" class="project-tree-children"${expanded?'':' hidden'}><li><a href="${path(p.id,'room')}"${p.id===current && room?' aria-current="page"':''}><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 4h18v14H8l-5 3z"/></svg><span>Project room</span></a></li>${own.map(t=>`<li><a href="#/projects/threads/${t.id}"${t.id===threadId?' aria-current="page"':''} title="${clean(t.name)}"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 4h18v14H8l-5 3z"/></svg><span>${clean(t.name)}</span><small>Private conversation</small></a></li>`).join('')}<li><a href="${path(p.id,'conversations')}"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 6h16M4 12h16M4 18h16"/></svg><span>View conversations</span></a></li></ul></li>`;
}).join('')}</ul>`;
if (container.dataset.treePaint !== html) { container.innerHTML = html; container.dataset.treePaint = html; }
const ancestor=document.querySelector('#sections > li > a[href="#/projects"]'); if(ancestor) { ancestor.classList.toggle('project-tree-ancestor',!!current); if(current) ancestor.removeAttribute('aria-current'); }
}
async function mountTree({container,path:route}) {
if(!container || document.body.classList.contains('signed-out')) return;
const generation=++treeGeneration;
try {
if (!treeRead || Date.now()-treeReadAt>10000) {
treeReadAt=Date.now();
treeRead=Promise.all([read('/api/chat/projects'),read('/api/chat/threads')]);
}
const [projects,threads]=await treeRead;
if(generation!==treeGeneration || !container.isConnected) return;
if(!Array.isArray(projects.rows) || !Array.isArray(threads.rows)) throw Error('invalid tree');
treeRows=projects.rows; treeThreads=threads.rows; drawTree(container,route);
const saved=treeFocus.get(container);
if(saved && (document.activeElement===document.body || container.contains(document.activeElement))) {
const target=[...container.querySelectorAll('a,button[data-project-disclosure]')].find(el=>saved.href ? el.getAttribute('href')===saved.href : el.dataset.projectDisclosure===saved.disclosure);
target?.focus({preventScroll:true});
}
treeFocus.delete(container);
container.onclick=e=>{const button=e.target.closest('[data-project-disclosure]');if(!button)return;const id=button.dataset.projectDisclosure;treeState[id]=button.getAttribute('aria-expanded')!=='true';try{localStorage.setItem(storageKey,JSON.stringify(treeState));}catch{}drawTree(container,route);container.querySelector(`[data-project-disclosure="${id}"]`)?.focus();};
} catch { if(generation===treeGeneration && container.isConnected && !document.body.classList.contains('signed-out')) {
treeRead=null;
const active=document.activeElement;
if(container.contains(active)) treeFocus.set(container, {href:active.getAttribute('href'), disclosure:active.dataset.projectDisclosure});
container.innerHTML='<p role="status">Projects unavailable. Refresh to try again.</p>'; delete container.dataset.treePaint;
} }
}
document.addEventListener('mosaic-signed-out',()=>{treeGeneration++;treeRead=null;treeRows=[];treeThreads=[];document.querySelector('#project-tree')?.replaceChildren();});
const requestId = value => typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/.test(value);
const cache = new Map();
const surfaceData = new Map();
const surfaceRuns = new Map();
let surfaceSequence = 0;
const selectedRequests = new Map();
let epoch=0;
document.addEventListener('click',e=>{if(e.target.closest?.('#refresh, #mobile-refresh')) { cache.clear(); surfaceData.clear(); surfaceRuns.clear(); }});
document.addEventListener('mosaic-project-room-changed',()=>{cache.clear();surfaceData.clear();surfaceRuns.clear();});
document.addEventListener('mosaic-signed-out',()=>{epoch++;cache.clear();surfaceData.clear();surfaceRuns.clear();selectedRequests.clear();});
const ended=s=>['cancelled','delivered','complete'].includes(s?.phase);
const needs=s=>!!s && ((['discovery','prd-review','planning'].includes(s.phase) && s.question?.answer===null) || s.wait?.kind==='decision' || (s.phase==='selection' && s.route==='existing' && s.wait?.kind==='setup'));
const phaseLabels={selection:'Starting',discovery:'Discovery','prd-review':'PRD review',planning:'Planning',implementation:'Building',review:'In review',delivery:'Delivering',complete:'Delivered',delivered:'Delivered',cancelled:'Cancelled'};
const label=s=>!s?'Status unavailable':needs(s)?'Needs your input':phaseLabels[s.phase]||'Status unavailable';
const modeLabel=value=>value ? String(value).replace(/(^|[-_ ])(\w)/g,(_m,sep,c)=>sep.replace(/[-_]/g,' ')+c.toUpperCase()) : 'Unavailable';
const chip=s=>`<span class="project-chip ${needs(s)?'warning':ended(s)&&s?.phase!=='cancelled'?'success':s?.phase==='cancelled'?'danger':''}">${clean(label(s))}</span>`;
const taskRefs=data=>[...new Set(data.requests.flatMap(r=>Array.isArray(r.state?.tasks)?r.state.tasks.filter(v=>typeof v==='string' && /^vikunja:[0-9]+\/[0-9]+$/.test(v)):[]))];
const validState=(s,id)=>s && s.version===1 && s.request===id && Number.isSafeInteger(s.revision) && s.revision>0 && typeof s.phase==='string';
const canonical=v=>Array.isArray(v)?v.map(canonical):v && typeof v==='object'?Object.fromEntries(Object.keys(v).sort().map(k=>[k,canonical(v[k])])):v;
const same=(a,b)=>JSON.stringify(canonical(a))===JSON.stringify(canonical(b));
const material=(d,s)=>d && d.candidate && s?.candidate && same(d.candidate,s.candidate) && d.candidate.request===s.request && d.candidate.project===s.project && d.candidate.mode_revision===s.mode_revision && typeof d.prd==='string' && Array.isArray(d.requirements) && Array.isArray(d.candidate.requirements) && d.requirements.length===d.candidate.requirements.length && d.requirements.every((r,i)=>r && r.id===d.candidate.requirements[i]?.id && r.title===d.candidate.requirements[i]?.title && typeof r.text==='string') && d.snapshot && Number.isSafeInteger(d.snapshot.revision) && d.snapshot.revision>=0 && d.snapshot.id===s.snapshot && (d.snapshot.id===null || requestId(d.snapshot.id) && d.snapshot.revision>0);
const ownThreads=(project,threads)=>threads.filter(t=>t.project===project.id && !t.shared && UUID.test(t.id));
async function gather(project,threads) {
const own=ownThreads(project,threads), key=project.id+':'+String(project.repo)+':'+own.map(t=>t.id).join(',');
const prior=cache.get(key); if(prior && Date.now()-prior.at<10000) return prior.promise;
const started=epoch;
const promise=(async()=>{
let failed=false;
const config=await read('/api/config').catch(()=>null);
const disabled=!config || config.requests!==true;
if(disabled) failed=true;
const pages=await Promise.all((disabled?[]:own).map(async thread=>{
try {
const sessions=await read(`/api/chat/threads/${thread.id}/sessions`).catch(()=>null);
const selected=Array.isArray(sessions?.rows)?sessions.rows.find(s=>s.default===true && UUID.test(s.id)):null;
const page=await read(`/api/chat/threads/${thread.id}/messages?limit=100${selected?'&session='+selected.id:''}`);
if(!Array.isArray(page.rows)) throw Error('invalid');
return {thread, rows:page.rows};
} catch {failed=true;return {thread,rows:[]};}
}));
const ids=new Map();
for(const {thread,rows} of pages) for(const m of rows) if(requestId(m.request)) ids.set(m.request,{id:m.request,thread,at:m.at});
const requests=(await Promise.all([...ids.values()].map(async item=>{
const base='/api/requests/'+encodeURIComponent(item.id);
let state;
try { state=await read(base); }
catch(e) { if(e.status===404 && e.code==='request-not-found') return null; failed=true; return {...item,state:null,draft:null,workspace:null}; }
if(!validState(state,item.id)) {failed=true;return {...item,state:null,draft:null,workspace:null};}
const [draft,workspace]=await Promise.all([read(base+'/draft').catch(()=>null),read(base+'/workspace').catch(()=>null)]);
return {...item,state,draft:material(draft,state)?draft:null,materialFailed:!!state.candidate && !material(draft,state),workspace};
}))).filter(Boolean);
const [tasks,catalog,room]=await Promise.all([read('/api/bus/tasks').catch(()=>null),read('/api/chat/instances').catch(()=>null),readRoomStatus(project)]);
const members=Array.isArray(catalog?.rows)?catalog.rows.filter(m=>typeof m?.instance==='string' && own.some(t=>t.instance===m.instance && t.name===t.instance)).length:null;
let docs=project.repo ? null : {files:[]}, north=null, recordsMissing=false, northMissing=false, northRecordsMissing=false;
if(project.repo && /^[A-Za-z0-9][A-Za-z0-9._/-]{0,200}$/.test(project.repo)) {
const repo=encodeURIComponent(project.repo);
[docs,north]=await Promise.all([read(`/api/project-files?project=${repo}`).catch(e=>{if(e.status===502 && e.code==='project-records-missing') { recordsMissing=true; return {files:[]}; } return null;}),read(`/api/project-file?project=${repo}&path=${encodeURIComponent('spec/north-star.md')}`).catch(e=>{if(e.status===404 && e.code==='project-read-missing') northMissing=true; else if(e.status===502 && e.code==='project-records-missing') northRecordsMissing=true; return null;})]);
}
if(epoch!==started) throw Error('signed-out');
return {requests,threads:own,failed,disabled,docs,north,recordsMissing,northMissing,northRecordsMissing,room,tasks: Array.isArray(tasks?.rows) ? tasks.rows : null,members,at:Date.now()};
})();
cache.set(key,{at:Date.now(),promise}); return promise;
}
async function readRoomStatus(project) {
try {
const response=await fetch(`/api/chat/rooms/${encodeURIComponent(project.id)}/messages?limit=100`,{cache:'no-store',redirect:'manual'});
if(response.status===401 || response.type==='opaqueredirect') { document.dispatchEvent(new CustomEvent('mosaic-signed-out',{detail:{signIn:true}})); return 'Unavailable'; }
const body=await response.json();
if(response.ok && Array.isArray(body?.rows) && typeof body.hasMore==='boolean') return 'Open';
if(response.status===409 && body?.error==='room-not-open') return 'Closed';
} catch {}
return 'Unavailable';
}
function roomControls(project,status,canSend,receipt='') {
return `<div class="project-room-status" data-project-room-status>Room: ${clean(status)} <a href="${path(project.id,'room')}">Read room</a>${window.MosaicOrg ? ' · Room changes unavailable' : status==='Closed' && canSend && !project.archived?` <button type="button" class="btn" data-project-room-open="${clean(project.id)}">Open room</button>`:''}<span data-project-room-receipt role="status">${clean(receipt)}</span></div>`;
}
function workFor(data, thread) {
const rows=data.requests.filter(r=>r.thread.id===thread.id).sort(requestOrder);
return rows.find(r=>r.state && !ended(r.state)) || rows[0];
}
function stepper(s) {
if(!s) return '';
const idx=({selection:0,discovery:0,'prd-review':0,planning:0,implementation:1,review:2,delivery:3,complete:4,delivered:4,cancelled:-1})[s.phase] ?? -1;
return `<div class="project-stepper" aria-label="Request phase">${['Requirements','Build','Review','Deliver'].map((name,i)=>`<span class="${i<idx?'done':i===idx?'current':''}"><i aria-hidden="true">${i<idx?'✓':i===idx?'◉':'○'}</i><b>${name}</b></span>`).join('<svg class="project-step-separator" viewBox="0 0 16 16" aria-hidden="true"><path d="m6 3 5 5-5 5"/></svg>')}</div>`;
}
const conversationLink=t=>`#/projects/threads/${encodeURIComponent(t.id)}`;
const taskLink=(ref,data)=>{const row=data?.tasks?.find(x=>x.task_ref===ref);const f=row?.fields||{};return `<a href="#/tasks/${encodeURIComponent(ref)}">${clean(ref)}${typeof f.title==='string'?' · '+clean(f.title):''}</a>${f.done===true?' · Done':''}`;};
const requestCode = id => `<code title="${clean(id)}">${clean(UUID.test(id) ? id.slice(0,8) : id)}</code>`;
function card(thread,request,failed) {
const file=request && delivery(request);
return `<article class="project-work"><div class="project-work-head"><div><span class="project-conversation-icon" aria-hidden="true">◌</span><a href="${conversationLink(thread)}"><strong>${clean(thread.name)}</strong></a><p>With ${clean(thread.instance)}${request?` · Request ${requestCode(request.id)}${request.state?.mode?' · '+clean(modeLabel(request.state.mode)):''} · Observed just now`:failed?' · Request status unavailable':' · No active request'}</p></div>${request?chip(request.state):''}</div>${stepper(request?.state)}<p class="project-work-wait">${request?.state?.wait?.code?`Waiting: ${clean(request.state.wait.code)}`:''}</p>${file?`<p><code>${clean(file.name)}</code> · Reviewed delivery <a download href="/api/requests/${encodeURIComponent(request.id)}/artifact/${encodeURIComponent(file.id)}">Download</a> <a href="${path(request.thread.project,'files')}">Open files</a></p>`:''}<div class="project-work-bottom">${request?.state?.tasks?.length?`<span>Tasks: ${request.state.tasks.filter(v=>/^vikunja:[0-9]+\/[0-9]+$/.test(v)).map(taskLink).join(', ')}</span>`:''}<a class="btn primary" href="${conversationLink(thread)}">Open conversation</a></div></article>`;
}
const requestOrder=(a,b)=>(Number(needs(b.state))-Number(needs(a.state))) || (Number(!!b.state && !ended(b.state))-Number(!!a.state && !ended(a.state))) || (Date.parse(b.at)||0)-(Date.parse(a.at)||0);
function docsList(data) { return Array.isArray(data.docs?.files)?data.docs.files.filter(f=>typeof f?.path==='string' && /^(spec\/north-star\.md|docs\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.md)$/.test(f.path)).map(f=>f.path):null; }
function delivery(r) {
const s=r.state,d=s?.delivery_evidence,n=d?.artifact?.path?.split('/').at(-1);
return s && requestId(s.delivery) && d?.id===s.delivery && d.request===r.id && d.project===s.project && d.snapshot===s.snapshot && s.phase==='complete' && d.verification && typeof n==='string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(n) ? {name:n,id:d.id} : null;
}
function deliveryPr(r) {
const pr=r.state?.delivery_evidence?.pull_request;
try { const url=new URL(pr?.url); return pr.request===r.id && pr.project===r.state.project && url.protocol==='https:' && !url.username && !url.password ? url.href : null; } catch { return null; }
}
function filesData(data) {
const reviewed=data.requests.map(r=>({r,file:delivery(r)})).filter(x=>x.file);
const drafts=data.requests.flatMap(r=>r.workspace?.available===true && Array.isArray(r.workspace.entries)?r.workspace.entries.slice(0,100).filter(x=>typeof x?.name==='string').map(x=>({r,name:x.name})):[]);
return {reviewed,drafts,docs:docsList(data)};
}
function filesView(data,project) {
const f=filesData(data), docs=f.docs;
return `<h2>Reviewed deliveries <span class="project-count">${f.reviewed.length}</span></h2>${f.reviewed.length?f.reviewed.map(({r,file})=>`<div class="project-panel"><span class="project-delivery-icon" aria-hidden="true">▤</span><strong>${clean(file.name)}</strong> <span class="project-chip success">Reviewed</span><p>Request ${clean(r.id)} · from ${clean(r.thread.name)} · Reviewed delivery. Not landed or deployed.</p><div class="project-delivery-actions"><a class="btn" target="_blank" rel="noopener noreferrer" href="/api/requests/${encodeURIComponent(r.id)}/artifact/${encodeURIComponent(file.id)}/text">Open as text</a> <a class="btn" download href="/api/requests/${encodeURIComponent(r.id)}/artifact/${encodeURIComponent(file.id)}">Download</a>${deliveryPr(r)?` <a class="btn" target="_blank" rel="noopener noreferrer" href="${esc(deliveryPr(r))}">Open pull request</a>`:''}</div><p>Open shows plain text in a new tab. Downloaded HTML can be opened locally after saving.</p></div>`).join(''):`<p>${data.disabled?'Files are unavailable.':data.failed?'Reviewed files are unavailable.':data.requests.length?'No reviewed file is available.':'No request files yet. Files appear when a request in this project produces them.'}</p>`}<h2>Draft workspace <span class="project-count">${f.drafts.length}</span></h2><p>Names only. Draft files may change and are not reviewed deliveries.</p><div class="project-panel project-file-list">${f.drafts.length?f.drafts.map(({r,name})=>`<div><span><span aria-hidden="true">▤</span> <code>${clean(name)}</code></span><span>Request ${clean(r.id)} · <span class="project-chip">Draft</span></span></div>`).join(''):data.failed || data.requests.some(r=>r.workspace?.available!==true || !Array.isArray(r.workspace.entries))?'<p>Could not read draft workspace. Try again later.</p>':'<p>No draft files found.</p>'}${data.requests.some(r=>r.workspace?.truncated)?'<p>The draft list was truncated.</p>':''}</div><h2>Project documents ${docs?`<span class="project-count">${docs.length}</span>`:''}</h2><div class="project-panel project-file-list">${!project.repo?'No linked repository.':data.recordsMissing?window.MosaicRecords.markup(project.repo):!docs?'Project documents unavailable. Docs could not read this project’s repository.':docs.length?docs.map(name=>`<div><span><span aria-hidden="true">▤</span> <code>${clean(name)}</code></span><a href="#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent(name)}">Open in Docs</a></div>`).join(''):'No project documents found.'}</div>`;
}
const expandedPrds = new Set();
function requirementView(data,project,selected) {
const options=data.requests.filter(r=>r.draft), r=options.find(x=>x.id===selected)||options[0], d=r?.draft;
const north=typeof data.north?.content==='string'?data.north.content:null;
const select=options.length>1?`<label>Request <select id="project-request-select">${options.map(x=>`<option value="${clean(x.id)}"${x===r?' selected':''}>${clean(x.id)} · ${clean(x.thread.name)}</option>`).join('')}</select></label>`:'';
const candidate=d?.candidate, expanded=r && expandedPrds.has(project.id+':'+r.id);
const docPath=candidate?.prd_path, docLink=project.repo && typeof docPath==='string' && /^docs\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.md$/.test(docPath) ? `#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent(docPath)}` : null;
const rows=candidate ? [['PRD version',candidate.prd_version],['Approved snapshot',d.snapshot.id || 'None'],['PRD file',docPath],['PRD blob',candidate.prd_blob],['Records commit',candidate.records_commit],['Confirmed intent commit',candidate.spec_commit],['Mode revision',candidate.mode_revision]].map(([label,value])=>`<div class="project-provenance-row"><span>${label}</span>${label==='PRD file' && docLink?`<a href="${docLink}"><code>${clean(value)}</code></a>`:`<code>${clean(value)}</code>`}</div>`).join('') : '<p>Unavailable until a PRD is read.</p>';
return `${r?`<div class="project-panel project-source">${select || `Request <code>${clean(r.id)}</code>`} · ${chip(r.state)} · from ${clean(r.thread.name)} <a href="${conversationLink(r.thread)}">Open conversation</a></div>`:select}<div class="project-columns"><section><h2>Project direction</h2><h3 id="project-north-star">North star</h3>${north!==null?`<div data-north-star></div><a class="project-text-link" href="#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent('spec/north-star.md')}">Open north star in Docs</a>`:data.northRecordsMissing?`<p>${window.MosaicRecords.markup(project.repo)}</p>`:data.northMissing?'<p>No north star yet.</p>':project.repo?'<p>North star unavailable. Docs could not read this project’s repository.</p>':`<p>This project has no linked repository. The north star and project documents live in a repository. Linking one to an existing project isn't available yet.</p>`}<h3 id="project-prd">${candidate?`PRD ${clean(candidate.prd_version)}`:'PRD'} ${candidate?`<span class="project-chip ${d.snapshot.id?'success':''}">${d.snapshot.id?'Approved':'Draft'}</span>`:''}</h3>${d?`<p>${d.snapshot.id?'Approved snapshot '+clean(d.snapshot.id):'This candidate has no active approved snapshot.'}</p><div class="project-panel project-prd-panel"><div class="project-prd-preview${expanded?' expanded':''}" data-prd></div><button type="button" class="btn project-prd-toggle" aria-expanded="${!!expanded}">${expanded?'Show less':'Show full PRD'}</button></div><h3>Requirements <span class="project-count">${d.requirements.length}</span></h3><div class="project-panel">${d.requirements.map((req,i)=>`<details data-restore-key="req:${clean(r.id)}:${clean(req.id)}"><summary>${clean(req.id)} · ${clean(req.title)}</summary><p>${clean(req.text)}</p><p>Requirement identity: <code>${clean(candidate.requirements[i]?.path)}</code> · <code>${clean(candidate.requirements[i]?.blob)}</code></p></details>`).join('')}</div>`:`<p>${(data.failed || data.requests.some(x=>x.materialFailed))?'Request or PRD unavailable. Refresh to try again.':'No current PRD candidate or approved snapshot. Waiting for a PRD submission.'}</p>`}${d && data.requests.some(x=>x.materialFailed)?'<p role="status">Some request PRDs could not be read. Refresh to try again.</p>':''}</section><aside class="project-panel project-provenance"><details data-restore-key="provenance"${matchMedia('(min-width:700px)').matches?' open':''}><summary>Version and provenance</summary>${rows}${candidate?`<p>Approval and revocation live in the conversation's Request details.</p><a href="${conversationLink(r.thread)}">Open conversation</a>`:''}</details></aside></div>`;
}
function overview(data,project,canSend,receipt='') {
const active=data.requests.filter(r=>r.state && !ended(r.state)), waiting=active.filter(r=>needs(r.state)), ordered=[...data.requests].sort(requestOrder), first=ordered[0], threads=[...data.threads];
if(first) threads.sort((a,b)=>Number(b.id===first.thread.id)-Number(a.id===first.thread.id));
const f=filesData(data), filesKnown=!data.failed && !!f.docs && data.requests.every(r=>r.workspace?.available===true && Array.isArray(r.workspace.entries) && r.state), count=filesKnown?f.reviewed.length+f.drafts.length+f.docs.length:'–';
const n=typeof data.north?.content==='string'?data.north.content:null, candidate=ordered.find(r=>r.draft)?.draft;
const metrics=[['Requests in progress',data.failed?'–':active.length,data.failed?'Not available yet':active[0]?label(active[0].state):'No active requests',first?conversationLink(first.thread):path(project.id,'conversations')],['Needs your input',data.failed?'–':waiting.length,data.failed?'Not available yet':waiting.length?label(waiting[0].state):'Nothing waiting',waiting[0]?conversationLink(waiting[0].thread):path(project.id,'conversations')],['Conversations',threads.length,'Project conversations',path(project.id,'conversations')],['Files',count,filesKnown?`${f.reviewed.length} reviewed · ${f.drafts.length} draft · ${f.docs.length} docs`:data.recordsMissing?'No project records yet':'Not available yet',path(project.id,'files')]];
return `${waiting.length?`<div class="project-panel project-decision" role="status">${waiting.length} ${waiting.length===1?'decision needs':'decisions need'} your input. <a class="btn primary" href="${conversationLink(waiting[0].thread)}">Review decision</a></div>`:''}<div class="project-metrics">${metrics.map(([title,value,caption,href])=>`<a href="${href}"><span>${title}</span><strong>${value}</strong><small>${clean(caption)}</small></a>`).join('')}<p>Updated just now · Showing requests from recent messages.</p></div><div class="project-columns"><section><div class="project-section-title"><h2>Current work</h2>${canSend&&!project.archived?`<a class="btn" href="${path(project.id,'conversations')}?new=1">${plusIcon}New conversation</a>`:''}</div>${threads.length?threads.map((t,i)=>i===0?card(t,workFor(data,t),data.failed):`<a class="project-row" href="${conversationLink(t)}"><strong>${clean(t.name)}</strong><small>With ${clean(t.instance)} · ${workFor(data,t) ? label(workFor(data,t).state) : data.failed ? 'Status unavailable' : 'No active request'}</small>${workFor(data,t)?chip(workFor(data,t).state):''}</a>`).join(''):'<p>No conversations yet. Start one to begin work.</p>'}<h2>Tasks <span class="project-count">${taskRefs(data).length}</span></h2><div class="project-panel">${taskRefs(data).length?taskRefs(data).slice(0,2).map(ref=>`<div>${taskLink(ref,data)}</div>`).join(''):data.failed?'<p>Request tasks unavailable. Refresh to try again.</p>':'<p>No request tasks available.</p>'}<a href="${path(project.id,'tasks')}">View all project tasks</a></div></section><aside class="project-panel"><h2>Project direction</h2><h3>North star</h3>${n!==null?`<div data-north-star></div><a class="project-text-link" href="#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent('spec/north-star.md')}">Open north star in Docs</a>`:`<p>${data.northRecordsMissing?window.MosaicRecords.markup(project.repo):data.northMissing?'No north star yet.':project.repo?'North star unavailable. Docs could not read this project’s repository.':"This project has no linked repository. The north star and project documents live in a repository. Linking one to an existing project isn't available yet."}</p>`}<h3>${candidate?'PRD '+clean(candidate.candidate.prd_version):'PRD'} ${candidate?.snapshot.id?'<span class="project-chip success">Approved</span>':''}</h3><p>${candidate?(candidate.snapshot.id?'Approved snapshot '+clean(candidate.snapshot.id):'Draft'):(data.failed || data.requests.some(x=>x.materialFailed)?'PRD unavailable.':'No current PRD available.')}</p>${candidate && data.requests.some(x=>x.materialFailed)?'<p role="status">Some request PRDs could not be read. Refresh to try again.</p>':''}<a href="${path(project.id,'requirements')}">Open PRD and requirements</a><h3>Files ${filesKnown?`<span class="project-count">${count}</span>`:''}</h3>${[...f.reviewed.map(x=>({name:x.file.name,reviewed:true})),...f.drafts.map(x=>({name:x.name,reviewed:false}))].slice(0,3).map(file=>file.reviewed?`<p><a href="${path(project.id,'files')}"><code>${clean(file.name)}</code> · Reviewed</a></p>`:`<p><code>${clean(file.name)}</code> · Draft</p>`).join('')||(data.failed?'<p>Request files unavailable.</p>':'<p>No request files available.</p>')}<a href="${path(project.id,'files')}">All files</a><h3>Project facts</h3><div class="project-provenance-row"><span>Repository</span><span>${project.repo?clean(project.repo):'Not linked'}</span></div>${roomControls(project,data.room,canSend,receipt)}<div class="project-provenance-row"><span>Mode</span><span>${first?.state?.mode?clean(modeLabel(first.state.mode)):data.failed?'Unavailable':'No active request'}</span></div></aside></div>`;
}
function tasksView(data) {
const refs=taskRefs(data);
return `<h2>Tasks <span class="project-count">${refs.length}</span></h2><p>Only tasks referenced by requests are shown.</p>${refs.length?`<div class="project-panel">${refs.map(ref=>{
const request=data.requests.find(r=>r.state?.tasks?.includes(ref)), fields=data.tasks?.find(t=>t.task_ref===ref)?.fields;
const assignees=Array.isArray(fields?.assignees)?fields.assignees.filter(v=>typeof v==='string' || typeof v==='number').map(clean).join(', '):'';
return `<a class="project-file-row" href="#/tasks/${encodeURIComponent(ref)}"><div><strong>${clean(fields?.title || ref)}</strong>${request?`<small>From request ${clean(request.id)} · ${clean(request.thread.name)}</small>`:''}</div><span class="project-chip ${fields?.done===true?'success':''}">${fields?.done===true?'Done':fields?.bucket!==undefined && fields?.bucket!==null?'bucket '+clean(fields.bucket):'Status unavailable'}${assignees?' · '+assignees:''}</span></a>`;
}).join('')}</div>`:`<p>${data.failed?'Request tasks unavailable. Refresh to try again.':'No request tasks available.'}</p>`}`;
}
const contentPaints = new WeakMap(), contentRuns = new WeakMap(), contentModels = new WeakMap();
// Disclosure and focus state is saved by identity (request and requirement id, provenance), so
// a row inserted or moved above it, or another request's requirement with the same local id,
// cannot inherit its state. Keyed disclosures keep a closed state too, so a default-open panel
// the user closed stays closed. Unkeyed details fall back to their position; a key that no
// longer exists is dropped.
const FOCUSABLE='a,button,select,input,textarea,summary,[tabindex]';
const restoreKey=(el,i)=>el.dataset.restoreKey || 'index:'+i;
function captureView(root) {
if(!root) return {disclosures:[],closed:[],projectFocus:null};
const active=document.activeElement, inside=root.contains(active);
const owner=inside && active.matches('summary') ? active.parentElement?.closest('details[data-restore-key]') : null;
return {
disclosures:[...root.querySelectorAll('details')].map((el,i)=>el.open?restoreKey(el,i):null).filter(Boolean),
closed:[...root.querySelectorAll('details[data-restore-key]')].filter(el=>!el.open).map(el=>el.dataset.restoreKey),
projectFocus:inside ? {id:active.id,details:owner?.dataset.restoreKey || null,index:[...root.querySelectorAll(FOCUSABLE)].indexOf(active)} : null
};
}
function restoreView(root,restore) {
const wanted=new Set((restore.disclosures || []).map(String)), closed=new Set((restore.closed || []).map(String));
[...root.querySelectorAll('details')].forEach((el,i)=>{const key=restoreKey(el,i);if(wanted.has(key)) el.open=true;else if(el.dataset.restoreKey && closed.has(key)) el.open=false;});
const f=restore.projectFocus; if(!f) return;
const focus=f.id ? document.getElementById(f.id) : f.details ? [...root.querySelectorAll('details[data-restore-key]')].find(el=>el.dataset.restoreKey===f.details)?.querySelector(':scope > summary') : root.querySelectorAll(FOCUSABLE)[f.index];
focus?.focus({preventScroll:true});
}
async function mountContent({container,project,threads,section,canSend,restore,roomReceipt}) {
if(!container || !project) return;
const generation=epoch, run=(contentRuns.get(container) || 0)+1;
contentRuns.set(container,run);
if (!contentPaints.has(container)) container.textContent='Reading…';
const data=await gather(project,threads).catch(()=>null);
if(!container.isConnected || generation!==epoch || contentRuns.get(container)!==run || document.body.classList.contains('signed-out')) return;
if(!data){contentPaints.delete(container);container.textContent='Project data unavailable. Refresh to try again.';return;}
const selected=selectedRequests.get(project.id);
if(selected && !data.requests.some(r=>r.id===selected && r.draft)) selectedRequests.delete(project.id);
const selection=selectedRequests.get(project.id);
const view = section==='requirements'?requirementView(data,project,selection):section==='files'?filesView(data,project):section==='tasks'?tasksView(data):overview(data,project,canSend,roomReceipt);
const selectedRequest=data.requests.find(r=>r.id===(selection||data.requests.find(x=>x.draft)?.id));
// The generated presentation and separately mounted Markdown determine visible content.
const signature=JSON.stringify([view, section==='requirements' ? selectedRequest?.draft?.prd : null, ['requirements','overview'].includes(section) ? data.north?.content : null, data.failed && ['files','tasks'].includes(section)]);
const header=container.closest('.chat-area')?.querySelector('.project-tabs');
if(header){const tasks=header.querySelector(`a[href="${path(project.id,'tasks')}"]`), files=header.querySelector(`a[href="${path(project.id,'files')}"]`);const f=filesData(data);if(tasks && !tasks.querySelector('.project-count') && !data.failed)tasks.insertAdjacentHTML('beforeend',` <span class="project-count">${taskRefs(data).length}</span>`);if(files && !files.querySelector('.project-count') && !data.failed && f.docs && data.requests.every(r=>r.workspace?.available===true && Array.isArray(r.workspace.entries)))files.insertAdjacentHTML('beforeend',` <span class="project-count">${f.reviewed.length+f.drafts.length+f.docs.length}</span>`);}
revealTab(header);
// Retained controls (the request selector) draw from the newest accepted read, even when
// this read changes nothing visible and the DOM is kept.
contentModels.set(container,{data,project,section,canSend,roomReceipt});
if (contentPaints.get(container) === signature) return;
contentPaints.set(container, signature);
// Capture at commit time: the user may have interacted while the read was pending.
const active=document.activeElement;
const liveRestore=contentPaints.has(container) && container.children.length ? captureView(container) : null;
const draw=selected=>{
const {data,project,section,canSend,roomReceipt}=contentModels.get(container);
container.innerHTML=section==='requirements'?requirementView(data,project,selected):section==='files'?filesView(data,project):section==='tasks'?tasksView(data):overview(data,project,canSend,roomReceipt);
if(data.failed && ['files','tasks'].includes(section)) container.insertAdjacentHTML('afterbegin','<p role="status">Some request data could not be read; this list may be incomplete.</p>');
const selectedRequest=data.requests.find(r=>r.id===(selected||data.requests.find(x=>x.draft)?.id));
const md=container.querySelector('[data-prd]'); if(md && selectedRequest?.draft) { md.replaceChildren(window.MosaicMarkdown?.render(selectedRequest.draft.prd) || document.createTextNode(selectedRequest.draft.prd)); const toggle=container.querySelector('.project-prd-toggle'); toggle.hidden=!md.classList.contains('expanded') && md.scrollHeight<=md.clientHeight; toggle.addEventListener('click',()=>{const key=project.id+':'+selectedRequest.id; if(expandedPrds.has(key)) expandedPrds.delete(key); else expandedPrds.add(key); const open=expandedPrds.has(key); md.classList.toggle('expanded',open); toggle.setAttribute('aria-expanded',String(open));toggle.textContent=open?'Show less':'Show full PRD';}); }
const north=container.querySelector('[data-north-star]'); if(north && typeof data.north?.content==='string') { const text=section==='overview' && data.north.content.length>500 ? data.north.content.slice(0,500).replace(/\s+\S*$/, '')+'…' : data.north.content; north.replaceChildren(window.MosaicMarkdown?.render(text) || document.createTextNode(text)); }
container.querySelector('#project-request-select')?.addEventListener('change',e=>{selectedRequests.set(project.id,e.target.value);draw(e.target.value);container.querySelector('#project-request-select')?.focus({preventScroll:true});});
};
draw(selection);
restore=liveRestore || restore;
if (restore) {
restoreView(container,restore);
}
const sectionTarget=new URLSearchParams(location.hash.split('?')[1] || '').get('section');
if(section==='requirements' && ['prd','north-star'].includes(sectionTarget)) container.querySelector('#project-'+sectionTarget)?.scrollIntoView({block:'start'});
}
async function enhanceList(container,projects,threads) {
for(const project of projects.filter(p=>!p.archived)) {
const slot=container.querySelector(`[data-project-status="${project.id}"]`); if(!slot) continue;
void gather(project,threads).then(data=>{if(!slot.isConnected)return;const current=[...data.requests].sort(requestOrder).find(r=>r.state);const html=`${current?chip(current.state):''}<span class="project-card-status-line">${data.failed?'Status unavailable · ':current?'':'No active requests · '}${ownThreads(project,threads).length} ${ownThreads(project,threads).length === 1 ? 'conversation' : 'conversations'} · Updated just now</span>`;if(slot.innerHTML!==html)slot.innerHTML=html;}).catch(()=>{if(slot.isConnected && slot.textContent!=='Status unavailable')slot.textContent='Status unavailable';});
}
}
async function enhanceSurface(container,project,threads,thread,canSend,receipt) {
const run=++surfaceSequence; surfaceRuns.set(project.id,run);
const data=await gather(project,threads).catch(()=>null); if(!data || !container.isConnected || surfaceRuns.get(project.id)!==run) return;
const f=filesData(data), tabs=container.querySelector('.project-tabs');
const setCount=(key,value)=>{const a=tabs?.querySelector(`a[href="${path(project.id,key)}"]`); if(a && !a.querySelector('.project-count')) a.insertAdjacentHTML('beforeend',` <span class="project-count">${value}</span>`);};
if(!data.failed) { setCount('tasks',taskRefs(data).length); if(f.docs && data.requests.every(r=>r.workspace?.available===true && Array.isArray(r.workspace.entries))) setCount('files',f.reviewed.length+f.drafts.length+f.docs.length); }
revealTab(tabs);
const requestStatus=container.querySelector('[data-conversation-request-status]');
if(requestStatus && thread) { const text=data.failed?'Request status unavailable.':''; if(requestStatus.textContent!==text) requestStatus.textContent=text; }
const selected=thread?workFor(data,thread):[...data.requests].sort(requestOrder).find(r=>r.state);
const agent=container.querySelector('[data-project-agent]'); if(agent && thread && agent.textContent!==thread.instance) agent.textContent=thread.instance;
const context=container.querySelector('[data-project-context]'); if(context) { const text=selected?.state?' · '+label(selected.state)+(selected.state.mode?' · '+modeLabel(selected.state.mode):''):''; if(context.textContent!==text) context.textContent=text; }
for(const row of container.querySelectorAll('[data-conversation-id]')) { const t=data.threads.find(t=>t.id===row.dataset.conversationId), r=t && workFor(data,t), slot=row.querySelector('[data-conversation-status]'); if(slot) { const html=r?chip(r.state):data.failed?'Status unavailable':'No active request'; if(slot.innerHTML!==html) slot.innerHTML=html; } }
surfaceData.set(project.id,data);
enrichRequest(container, project.id);
}
function enrichRequest(container, projectId) {
const data=surfaceData.get(projectId); if(!data) return;
for(const intro of container.querySelectorAll('.project-request-intro')) { const id=intro.querySelector('code')?.title, r=data.requests.find(r=>r.id===id && r.state?.revision===Number(intro.dataset.requestRevision)); if(!r) continue; const files=filesData(data), prd=intro.querySelector('[data-work-prd]'), counts=intro.querySelector('[data-work-files]'); if(prd) { const html=`PRD ${clean(r.draft?.candidate?.prd_version || '–')} ${r.draft ? `<span class="project-chip ${r.draft.snapshot?.id?'success':''}">${r.draft.snapshot?.id?'Approved':'Draft'}</span>` : ''}`; if(prd.innerHTML!==html) prd.innerHTML=html; } if(counts) { const text=`Files · ${!data.failed ? files.reviewed.length : '–'} reviewed, ${!data.failed && data.requests.every(x=>x.workspace?.available===true && Array.isArray(x.workspace.entries) && !x.workspace.truncated) ? files.drafts.length+' draft' : '– draft (Draft files unavailable)'}`; if(counts.textContent!==text) counts.textContent=text; } }
}
document.addEventListener('click',e=>{
const open=e.target.closest?.('[data-project-dialog]');
if(open){const dialog=document.getElementById(`project-${open.dataset.projectDialog}-dialog`);if(dialog && !dialog.open){open.focus({preventScroll:true});dialog.showModal();dialog.querySelector('h2')?.focus();}return;}
const close=e.target.closest?.('[data-dialog-close]');if(close)close.closest('dialog')?.close();
});
window.MosaicProjectTree ??= Object.freeze({mount:mountTree});
function requestIntro(state, projectId, observedAt) {
if(!UUID.test(projectId || '')) return '';
const observed = typeof observedAt === 'string' && Number.isFinite(Date.parse(observedAt)) ? `<time datetime="${clean(observedAt)}">${clean(new Date(observedAt).toLocaleTimeString([], {hour:'numeric',minute:'2-digit'}))}</time>` : 'time unavailable';
return `<div class="project-request-intro" data-request-revision="${clean(state.revision)}"><div class="project-work-head"><strong>Request ${requestCode(state.request)}</strong>${chip(state)}</div><p>${clean(modeLabel(state.mode))} · Observed ${observed}</p>${stepper(state)}<div class="project-work-row"><span data-work-prd>PRD –</span><a href="${path(projectId,'requirements')}">Open requirements</a></div><div class="project-work-row"><span data-work-files>Files · – reviewed, – draft</span><a href="${path(projectId,'files')}">Open files</a></div></div>`;
}
const palette=()=>treeRows.filter(p=>!p.archived && UUID.test(p.id)).flatMap(p=>sections.map(([key,label])=>({href:path(p.id,key),label:key==='overview'?p.name:`${p.name}: ${label}`,group:'project'})));
function breadcrumb(box, view) {
const h=view.querySelector('.project-header'); if(!h)return false;
const id=h.dataset.projectId, name=h.dataset.projectName, section=h.dataset.projectSection, conversation=h.dataset.projectConversation==='true';
const title=sections.find(([key])=>key===section)?.[1] || (section==='settings'?'Settings':'Overview');
const leaf=conversation?view.querySelector('h1')?.textContent:title;
box.innerHTML=`<a href="#/projects">Projects</a><span aria-hidden="true">/</span><a class="project-crumb-name" href="#/projects/${encodeURIComponent(id)}" title="${clean(name)}"><span>${clean(name)}</span></a>${conversation?`<span aria-hidden="true">/</span><a href="${path(id,'conversations')}">Conversations</a>`:''}<span class="project-crumb-current"><span aria-hidden="true">/</span> <span aria-current="page">${clean(leaf)}</span></span>`;
return true;
}
window.MosaicProjects = Object.freeze({ header, revealTab, path, clean, mountContent, captureView, enhanceList, enhanceSurface, enrichRequest, breadcrumb, requestIntro, palette });
})();