/* Project navigation and presentation. Chat retains ownership of reads and writes. */ (() => { 'use strict'; const esc = v => String(v ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[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=''; const icon = path => ``; 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=''; 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]) => `${label}${key==='conversations'?` ${threads.filter(t=>!t.shared && t.project===project.id).length}`:''}`).join(''); const count=threads.filter(t=>!t.shared && t.project===project.id).length; return `

${clean(title)}

${project.archived?'Archived':''}

${conversation ? 'With assistant' : (project.repo ? `Repository: ${clean(project.repo)}` : 'No linked repository') + ` · ${count} ${count===1?'conversation':'conversations'}`}

${conversation?'':`${starIcon}North star${documentIcon}PRD${settingsIcon}Settings`}
`; } // 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.leftn.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; // #1873 SP1: the tree and its open/closed state belong to the open organization; a switch drops both. const storageKey=()=>window.MosaicOrg?.id ? `mosaic-project-tree:${window.MosaicOrg.id}` : 'mosaic-project-tree'; let treeRows=[], treeThreads=[], treeGeneration=0, treeState, treeRead=null, treeReadAt=0; const treeFocus = new WeakMap(); const loadTreeState=()=>{ try { treeState=JSON.parse(localStorage.getItem(storageKey()) || '{}'); if (!treeState || Array.isArray(treeState) || typeof treeState !== 'object') treeState={}; } catch { treeState={}; } }; loadTreeState(); window.MosaicOrg?.ready?.then(loadTreeState); document.addEventListener('mosaic-org-switch',()=>{ treeGeneration++; treeRows=[]; treeThreads=[]; treeRead=null; treeReadAt=0; loadTreeState(); }); // A side-by-side pane reads its own organization: its reads name that organization explicitly. const at=(org,url)=>org && url.startsWith('/api/') ? `/api/orgs/${encodeURIComponent(org)}/${url.slice(5)}` : url; 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(); } const readAt=url=>read(url); 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=``; 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='

Projects unavailable. Refresh to try again.

'; 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=>`${clean(label(s))}`; 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,org=null) { const read=url=>readAt(at(org,url)); const own=ownThreads(project,threads), key=(org?org+'|':'')+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,org)]); 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,org=null) { try { const response=await fetch(at(org,'/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 `
Room: ${clean(status)} Read room${window.MosaicOrg ? ' · Room changes unavailable' : status==='Closed' && canSend && !project.archived?` `:''}${clean(receipt)}
`; } 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 `
${['Requirements','Build','Review','Deliver'].map((name,i)=>`