Spaces:
Running on Zero
Running on Zero
Download beta_ui.js from mendeld/ac: direct link, hf CLI and curl.
- Browser
- Download file 28.1 kB
-
https://huggingface.co/spaces/mendeld/ac/resolve/main/beta_ui.js
- Command line
-
hf download hf://spaces/mendeld/ac/beta_ui.js
-
curl -L -o beta_ui.js https://huggingface.co/spaces/mendeld/ac/resolve/main/beta_ui.js
28.1 kB
| /* AC 1.5.0 Beta V7: functional attachments, feedback, optional accounts, analytics. */ | |
| (() => { | |
| 'use strict'; | |
| const byId = id => document.getElementById(id); | |
| const e = (tag,cls,txt) => {const v=document.createElement(tag);if(cls)v.className=cls;if(txt!==undefined)v.textContent=txt;return v;}; | |
| const safe = str => String(str ?? '').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); | |
| const api = async (url, data, form=false) => { | |
| const r=await fetch(url,{method:data===undefined?'GET':'POST',headers:form?{}:{'Content-Type':'application/json'},body:data===undefined?undefined:(form?data:JSON.stringify(data))}); | |
| const result=await r.json().catch(()=>({}));if(!r.ok)throw Error(result.detail||'Please try again.');return result; | |
| }; | |
| const message = (msg)=>{const node=byId('beta-composer-status');if(node)node.textContent=msg||'';}; | |
| let attached=[]; | |
| let uploadedBefore=[]; | |
| let loggedIn=null; | |
| let accountEnabled=false; | |
| let retention=localStorage.getItem('ac_retention')||'forever'; | |
| let intensity=localStorage.getItem('ac_intensity')||'rich'; | |
| let syncing=null; | |
| let aborter=null; | |
| let busy=false; | |
| const modal=()=>byId('beta-modal'); | |
| const showModal=(title,description,actions=[],more=null)=>{ | |
| byId('beta-modal-title').textContent=title; | |
| byId('beta-modal-description').textContent=description; | |
| const extra=byId('beta-modal-extra');extra.innerHTML='';if(more)more(extra); | |
| const buttons=byId('beta-modal-buttons');buttons.innerHTML=''; | |
| actions.forEach(({label,fn})=>{const btn=e('button','beta-mini-btn',label);btn.onclick=()=>{modal().classList.remove('open');fn?.()};buttons.append(btn)}); | |
| modal().classList.add('open'); | |
| }; | |
| const panel=e('div');panel.id='beta-modal';panel.innerHTML='<div id="beta-modal-panel" role="dialog" aria-modal="true"><h2 id="beta-modal-title"></h2><p id="beta-modal-description"></p><div id="beta-modal-extra"></div><div id="beta-modal-buttons"></div></div>'; | |
| document.body.append(panel); | |
| panel.addEventListener('click',ev=>{if(ev.target===panel)panel.classList.remove('open')}); | |
| // New, clearer product identity; mode-specific accent carries throughout the interface. | |
| const badge=e('span','','1.5.0 Beta');badge.id='beta-version-chip';byId('model-button')?.parentElement?.parentElement?.append(badge); | |
| const applyMode=()=>{ | |
| if(currentMode==='Chachma')currentMode='Chochma'; | |
| if(!['Chochma','Binah','Daas'].includes(currentMode))currentMode='Binah'; | |
| document.body.dataset.mode=currentMode; | |
| localStorage.setItem('ac_mode',currentMode); | |
| byId('model-button').textContent=currentMode+' ▾'; | |
| document.querySelectorAll('.mode-item').forEach(el=>el.classList.toggle('selected',el.dataset.mode===currentMode)); | |
| }; | |
| applyMode(); | |
| document.body.dataset.intensity=intensity; | |
| document.querySelectorAll('.mode-item').forEach(el=>el.addEventListener('click',()=>setTimeout(applyMode,0))); | |
| const warning=byId('page-chat')?.querySelector('.composer-note'); | |
| if(warning)warning.textContent='AC is not a posek. Ask a Rav for practical halachic decisions. AC can make mistakes.'; | |
| // Learning modes removed: retain hidden value for compatibility with v11's chat API. | |
| byId('study-mode')?.closest('.setting-row')?.classList.add('hidden'); | |
| const fileInput=e('input');fileInput.type='file';fileInput.multiple=true;fileInput.accept='.pdf,.docx,.txt,.png,.jpg,.jpeg,.xlsx';fileInput.hidden=true; | |
| byId('page-chat')?.append(fileInput); | |
| const attachmentBox=e('div','beta-attachments'); | |
| byId('page-chat')?.querySelector('.composer')?.parentElement?.prepend(attachmentBox); | |
| const composerStatus=e('div');composerStatus.id='beta-composer-status'; | |
| byId('page-chat')?.querySelector('.composer')?.parentElement?.append(composerStatus); | |
| const repaintAttachments=()=>{ | |
| attachmentBox.innerHTML='';attached.forEach((f,i)=>{const p=e('span','beta-attach-pill',f.filename);const x=e('button','','×');x.title='Remove file';x.onclick=()=>{attached.splice(i,1);repaintAttachments()};p.append(x);attachmentBox.append(p)}); | |
| }; | |
| fileInput.addEventListener('change',async()=>{ | |
| for(const file of Array.from(fileInput.files).slice(0,4)){ | |
| if(file.size>10*1024*1024){message(file.name+' exceeds 10 MB.');continue} | |
| const form=new FormData();form.append('file',file); | |
| message('Reading '+file.name+'…'); | |
| try{const result=await api('/api/upload',form,true);attached.push(result);uploadedBefore.push(result);message(result.notice)} | |
| catch(err){message(err.message)} | |
| } | |
| fileInput.value='';repaintAttachments();byId('upload-menu').classList.remove('open'); | |
| }); | |
| byId('beta-upload').onclick=()=>fileInput.click(); | |
| byId('beta-reuse').onclick=()=>{ | |
| const options=uploadedBefore.filter(f=>!attached.some(x=>x.token===f.token)); | |
| showModal('Previous uploads',options.length?'Choose a file uploaded during this session.':'No reusable files uploaded this session. Upload a document first.',[ | |
| {label:'Close'} | |
| ],box=>options.forEach(file=>{const b=e('button','beta-mini-btn',file.filename);b.style.display='block';b.onclick=()=>{attached.push(file);repaintAttachments();modal().classList.remove('open')};box.append(b)})); | |
| byId('upload-menu').classList.remove('open'); | |
| }; | |
| // Settings: account, retention, privacy, feedback, version metadata. | |
| const settings=byId('page-settings')?.querySelector('.content-page'); | |
| const retentionCard=e('div','beta-setting-card');retentionCard.innerHTML=`<h2>Chat history</h2><p>Guest chats are saved in this browser. Signed-in chats can sync across devices when durable private storage is configured.</p><label for="beta-retention">Keep chats for</label><select id="beta-retention"><option value="forever">Until I delete them</option><option value="30">30 days</option><option value="90">90 days</option></select><p>Delete a conversation from the three-dot menu beside it. Deleting removes the saved copy; there is no trash folder.</p>`; | |
| settings?.append(retentionCard);byId('beta-retention').value=retention; | |
| const intensityCard=e('div','beta-setting-card');intensityCard.innerHTML='<h2>Color intensity</h2><p>Choose how strong the mode colors feel on your screen.</p><select id="beta-intensity"><option value="rich">Rich</option><option value="soft">Soft</option><option value="minimal">Minimal</option></select>'; | |
| settings?.append(intensityCard);byId('beta-intensity').value=intensity; | |
| byId('beta-intensity').onchange=()=>{intensity=byId('beta-intensity').value;localStorage.setItem('ac_intensity',intensity);document.body.dataset.intensity=intensity}; | |
| byId('beta-retention').onchange=()=>{retention=byId('beta-retention').value;localStorage.setItem('ac_retention',retention);pruneLocal();queueSync()}; | |
| const accountCard=e('div','beta-setting-card');accountCard.innerHTML=`<h2>Account (optional)</h2><p id="beta-account-status">Checking account availability…</p><div class="beta-flex"><button class="beta-mini-btn" id="beta-account-login">Log in</button><button class="beta-mini-btn" id="beta-account-signup">Create account</button><button class="beta-mini-btn hidden" id="beta-account-logout">Log out</button></div>`; | |
| settings?.append(accountCard); | |
| const privacyCard=e('div','beta-setting-card');privacyCard.innerHTML=`<h2>Privacy and safety</h2><p>Your chats are private to you and aren't visible in admin analytics. An admin can see only feedback you send or a narrowly detected critical safety message. Routine question counts and categories are collected without the question text. Uploaded file text is used for your request, not displayed to admins. Chat responses may pass through the AI model service.</p><p>Accounts are available only for users aged 13 or older in this beta. Under-13 account registration needs a verified parent/guardian consent flow before it can launch.</p>`; | |
| settings?.append(privacyCard); | |
| const info=e('div','beta-setting-card');info.innerHTML='<h2>About AC</h2><p><strong>Artificial Chochma · 1.5.0 Beta V7</strong></p><p>Chochma: quick answers · Binah: fuller explanations · Daas: deeper reasoning and sources.</p>'; | |
| settings?.append(info); | |
| const feed=e('div','beta-setting-card');feed.innerHTML='<h2>Help improve AC</h2><p>Send feedback to the AC team. Only what you choose to submit will be shared.</p><button class="beta-mini-btn" id="beta-survey">Give feedback</button>'; | |
| settings?.append(feed); | |
| byId('beta-survey').onclick=()=>showModal('Give feedback','What do you like about AC? What should be improved?',[{label:'Cancel'},{label:'Send feedback',fn:async()=>{ | |
| const note=byId('beta-note')?.value.trim();if(!note)return; | |
| try{await api('/api/feedback',{kind:'survey',question:'',answer:'',note});message('Feedback sent. Thank you!')}catch(err){message(err.message)} | |
| }}],extra=>{const t=e('textarea');t.id='beta-note';t.maxLength=1000;t.placeholder='Your feedback';extra.append(t)}); | |
| const pruneLocal=()=>{ | |
| if(retention==='forever')return; | |
| const min=Date.now()-Number(retention)*86400000; | |
| archive=archive.filter(c=>!c.updated||c.updated>=min); | |
| if(currentHistory.length&&!archive.some(c=>c.id===currentChatId)){currentHistory=[];currentChatId=crypto.randomUUID();} | |
| localStorage.setItem('ac_archive',JSON.stringify(archive));localStorage.setItem('ac_current_history',JSON.stringify(currentHistory));renderRecents();renderConversation(); | |
| }; | |
| pruneLocal(); | |
| const queueSync=()=>{ | |
| if(!loggedIn && !(typeof IS_ADMIN!=='undefined' && IS_ADMIN))return; | |
| if(syncing)clearTimeout(syncing); | |
| syncing=setTimeout(async()=>{ | |
| saveCurrentToArchive(); | |
| try { await api((typeof IS_ADMIN!=='undefined'&&IS_ADMIN)?'/api/admin/own-chats':'/api/account/chats',{chats:archive,retention}); } | |
| catch(err){message('Cloud saving failed: '+err.message)} | |
| finally {if(loggedIn){localStorage.removeItem('ac_archive');localStorage.removeItem('ac_current_history')}} | |
| },900); | |
| }; | |
| const basePersist=persistCurrent; | |
| persistCurrent=function(){basePersist();queueSync(); | |
| // Signed-in chats live in authenticated cloud storage, not public guest keys. | |
| if(loggedIn){localStorage.removeItem('ac_archive');localStorage.removeItem('ac_current_history')} | |
| }; | |
| const baseRecents=renderRecents; | |
| renderRecents=function(filter=''){ | |
| const list=byId('recent-list');list.innerHTML='';const q=filter.toLowerCase().trim(); | |
| archive.slice().sort((a,b)=>(b.updated||0)-(a.updated||0)).filter(c=>!q||c.title?.toLowerCase().includes(q)).forEach(item=>{ | |
| const row=e('div','beta-recents-item');const b=e('button','recent-item',item.title||'Chat');b.title=item.title||'Chat'; | |
| b.onclick=()=>{saveCurrentToArchive();currentChatId=item.id;currentHistory=item.history||[];persistCurrent();renderConversation();setPage('chat')}; | |
| const menu=e('button','beta-recents-menu','⋯');menu.title='Chat options';menu.onclick=()=>{ | |
| showModal('Delete conversation?','This permanently deletes the saved conversation from your browser and synced account, if logged in.',[ | |
| {label:'Cancel'}, {label:'Delete chat',fn:()=>{archive=archive.filter(c=>c.id!==item.id);if(currentChatId===item.id){currentChatId=crypto.randomUUID();currentHistory=[]}persistCurrent();renderConversation();}} | |
| ])};row.append(b,menu);list.append(row); | |
| }); | |
| }; | |
| renderRecents(); | |
| const currentQuestion=index=>{for(let i=index-1;i>=0;i--)if(currentHistory[i]?.role==='user')return currentHistory[i].content||'';return ''}; | |
| const reportAnswer=async(kind,index,note='')=>{ | |
| try{await api('/api/feedback',{kind,question:currentQuestion(index),answer:currentHistory[index]?.content||'',note});message(kind==='good'?'Thanks for the feedback.':'Sent to the AC team.')}catch(err){message(err.message)} | |
| }; | |
| const baseRender=renderConversation; | |
| renderConversation=function(){ | |
| baseRender(); | |
| const actionBlocks=document.querySelectorAll('#messages .response-actions'); | |
| const indexes=currentHistory.map((m,i)=>m.role==='assistant'?i:null).filter(x=>x!==null); | |
| actionBlocks.forEach((actions,pos)=>{ | |
| const idx=indexes[pos];if(idx===undefined)return; | |
| actions.innerHTML=''; | |
| const button=(symbol,tip,fn)=>{const b=e('button','response-action',symbol);b.title=tip;b.setAttribute('aria-label',tip);b.onclick=fn;actions.append(b)}; | |
| button('⧉','Copy',()=>navigator.clipboard?.writeText(currentHistory[idx].content||'')); | |
| button('♡','Good response',()=>reportAnswer('good',idx)); | |
| button('♧','Report answer',()=>showModal('Report this answer','Only this question and answer, plus your optional note, will be sent to AC administrators.',[ | |
| {label:'Cancel'}, {label:'Send report',fn:()=>reportAnswer('report',idx,byId('beta-report-reason')?.value||'')} | |
| ],box=>{const t=e('textarea');t.id='beta-report-reason';t.placeholder='What is wrong with this answer?';box.append(t)})); | |
| button('🔊','Read aloud',()=>{speechSynthesis.cancel();speechSynthesis.speak(new SpeechSynthesisUtterance(currentHistory[idx].content||''))}); | |
| button('↻','Regenerate',()=>{ | |
| if(idx!==currentHistory.length-1){message('You can regenerate the most recent answer only.');return;} | |
| const question=currentQuestion(idx);if(!question)return; | |
| currentHistory.splice(idx-1,2);persistCurrent();byId('prompt').value=question;betaSend(); | |
| }); | |
| }); | |
| }; | |
| renderConversation(); | |
| // Stop cancels the browser wait. The underlying ZeroGPU invocation can finish | |
| // on the server; it is not a server-side cancellation primitive. | |
| const stop=e('button','circle-btn send-btn','■');stop.id='stop-button';stop.title='Stop waiting for answer';stop.style.display='none'; | |
| byId('send-button')?.after(stop);stop.onclick=()=>{aborter?.abort();message('Stopped waiting for that answer.');}; | |
| const oldSend=byId('send-button'); | |
| const betaSend=async()=>{ | |
| stopVoiceInput();if(busy)return; | |
| const input=byId('prompt');const text=input.value.trim();if(!text)return; | |
| let announceLocation=false,locationAttempted=false; | |
| if(requestNeedsLocation(text)&&!activeLocation){locationAttempted=true;const detected=await getBrowserLocation();if(detected){activeLocation=detected;announceLocation=true;}} | |
| currentHistory.push({role:'user',content:text});input.value='';resizePrompt();renderConversation();showThinking(); | |
| const submittedUploads=attached.slice();attached=[];repaintAttachments(); | |
| busy=true;oldSend.disabled=true;oldSend.style.display='none';stop.style.display='inline-block';aborter=new AbortController(); | |
| try{ | |
| const r=await fetch('/api/chat',{method:'POST',headers:{'Content-Type':'application/json'},signal:aborter.signal, | |
| body:JSON.stringify({message:text,history:currentHistory.slice(0,-1),mode:currentMode, | |
| answer_length:byId('answer-length').value,study_mode:'Explain', | |
| location:activeLocation||{},announce_location:announceLocation,location_attempted:locationAttempted, | |
| uploads:submittedUploads.map(x=>x.token)})}); | |
| const d=await r.json();if(!r.ok)throw Error(d.detail||'Request failed'); | |
| currentHistory=Array.isArray(d.history)?d.history:currentHistory; | |
| if(d.location?.label)updateLocationDisplay(d.location); | |
| message(''); | |
| }catch(err){ | |
| currentHistory.push({role:'assistant',content:err.name==='AbortError'?'Response canceled. You can try again.':'AC is temporarily unavailable. Please try again.'}); | |
| }finally{ | |
| byId('thinking-row')?.remove();busy=false;oldSend.disabled=false;oldSend.style.display='inline-block';stop.style.display='none';aborter=null;persistCurrent();renderConversation(); | |
| } | |
| }; | |
| sendMessage=betaSend; | |
| oldSend.onclick=betaSend; | |
| // Expose meaningful user-account controls rather than a dead account button. | |
| const checkCapabilities=async()=>{ | |
| try{const c=await api('/api/capabilities');accountEnabled=!!c.accounts_enabled;loggedIn=c.user||null;drawAccount();if(loggedIn)await loadAccountChats()} | |
| catch(err){byId('beta-account-status').textContent='Account service is currently unavailable.'} | |
| }; | |
| function drawAccount(){ | |
| byId('beta-account-status').textContent=loggedIn?`Signed in as ${loggedIn}. Your chats can sync across devices.`:(accountEnabled?'You are using guest mode. Accounts are optional.':'Guest mode. Account signup needs a private persistent storage configuration; no cloud saving yet.'); | |
| byId('beta-account-login').classList.toggle('hidden',!!loggedIn); | |
| byId('beta-account-signup').classList.toggle('hidden',!!loggedIn||!accountEnabled); | |
| byId('beta-account-logout').classList.toggle('hidden',!loggedIn); | |
| byId('beta-account-login').disabled=!accountEnabled; | |
| } | |
| const authDialog=signup=>{ | |
| showModal(signup?'Create account':'Log in',signup?'Accounts are for ages 13 and older. An account is optional.':'Sign in to retrieve your saved chats.',[ | |
| {label:'Cancel'}, {label:signup?'Create account':'Log in',fn:async()=>{ | |
| const username=byId('beta-auth-user')?.value;const password=byId('beta-auth-password')?.value; | |
| const age=!!byId('beta-auth-age')?.checked; | |
| try{const result=await api(signup?'/api/account/signup':'/api/account/login',{username,password,age_13_or_older:age}); | |
| loggedIn=result.user;drawAccount();await loadAccountChats();message('Signed in.')} | |
| catch(err){message(err.message)} | |
| }} | |
| ],box=>{ | |
| box.innerHTML='<label>Username<input id="beta-auth-user" autocomplete="username" maxlength="30"></label><label>Password<input id="beta-auth-password" type="password" autocomplete="'+(signup?'new-password':'current-password')+'" placeholder="'+(signup?'At least 12 characters':'Password')+'"></label>'+(signup?'<label class="beta-muted"><input id="beta-auth-age" type="checkbox" style="width:auto"> I confirm I am at least 13 years old</label>':''); | |
| }); | |
| }; | |
| byId('beta-account-signup').onclick=()=>authDialog(true); | |
| byId('beta-account-login').onclick=()=>authDialog(false); | |
| byId('beta-account-logout').onclick=async()=>{ | |
| if(syncing)clearTimeout(syncing); | |
| await api('/api/account/logout',{});loggedIn=null; | |
| archive=[];currentHistory=[];currentChatId=crypto.randomUUID(); | |
| localStorage.removeItem('ac_archive');localStorage.removeItem('ac_current_history'); | |
| localStorage.setItem('ac_current_chat_id',currentChatId);renderRecents();renderConversation();drawAccount(); | |
| message('Logged out. Synced chats have been cleared from this browser.'); | |
| }; | |
| const loadAccountChats=async()=>{ | |
| const cloud=await api('/api/account/chats'); | |
| if(!localStorage.getItem('ac_merged_user_'+loggedIn)){ | |
| showModal('Merge chats?', 'This is the first time this browser has signed in to this account. Would you like to merge this browser’s saved chats with your account?',[ | |
| {label:'No, use account chats',fn:()=>{archive=cloud.chats||[];localStorage.setItem('ac_merged_user_'+loggedIn,'yes');loadCloudCurrent();}}, | |
| {label:'Yes, merge chats',fn:()=>{const map=new Map((cloud.chats||[]).map(c=>[c.id,c]));archive.forEach(c=>map.set(c.id,c));archive=[...map.values()];localStorage.setItem('ac_merged_user_'+loggedIn,'yes');loadCloudCurrent();queueSync()}} | |
| ]); | |
| }else {archive=cloud.chats||[];loadCloudCurrent()} | |
| }; | |
| function loadCloudCurrent(){ | |
| currentChatId=crypto.randomUUID();currentHistory=[];localStorage.setItem('ac_archive',JSON.stringify(archive)); | |
| localStorage.setItem('ac_current_history','[]');localStorage.setItem('ac_current_chat_id',currentChatId); | |
| if(loggedIn){localStorage.removeItem('ac_archive');localStorage.removeItem('ac_current_history')} | |
| renderRecents();renderConversation();setPage('chat'); | |
| } | |
| checkCapabilities(); | |
| if(typeof IS_ADMIN!=='undefined'&&IS_ADMIN){ | |
| const adm=byId('page-admin-controls')?.querySelector('.content-page'); | |
| if(adm){ | |
| adm.querySelector('.admin-tabs')?.classList.add('hidden'); | |
| adm.querySelectorAll('.admin-pane').forEach(x=>x.classList.add('hidden')); | |
| const area=e('section');area.id='beta-admin';area.innerHTML=` | |
| <p class="beta-muted">Private user conversations cannot be opened by administrators. Only totals, voluntarily submitted reports, and narrowly detected critical alerts are shown.</p> | |
| <div class="beta-kpi-grid" id="beta-stats"></div> | |
| <div class="beta-setting-card"><h2>Emergency pause</h2><p>Immediately stop AC from answering new student requests until the pause is disabled.</p><p id="beta-pause-status">Checking…</p><button class="beta-mini-btn" id="beta-pause-toggle">Change pause status</button></div> | |
| <div class="beta-setting-card"><h2>Bug Tracker</h2><p>Automatic technical errors only. No private questions or answers are collected. Mark a bug as fixed to move it into the archive; if it occurs again, AC reopens it automatically.</p> | |
| <div class="beta-flex"><button class="beta-mini-btn" id="beta-bugs-refresh">Refresh bugs</button><button class="beta-mini-btn" id="beta-bugs-open">Open</button><button class="beta-mini-btn" id="beta-bugs-fixed">Fixed archive</button></div> | |
| <p class="beta-muted" id="beta-bugs-storage"></p><div id="beta-bugs-list" aria-live="polite"></div></div> | |
| <div class="beta-setting-card"><h2>User-submitted feedback</h2><button class="beta-mini-btn" id="beta-reports-refresh">Refresh</button><div id="beta-reports"></div></div> | |
| <div class="beta-setting-card"><h2>Critical safety flags</h2><p>Only messages matching the narrow critical-danger rule are displayed here. False positives and missed dangers are possible; this is not an emergency monitoring service.</p><div id="beta-flags"></div></div> | |
| <div class="beta-setting-card"><h2>Admin</h2><button class="beta-mini-btn" id="beta-admin-logout">Log out of Head Admin</button></div>`; | |
| adm.append(area); | |
| let pauseState=false; | |
| const drawStats=async()=>{ | |
| try{ | |
| const data=await api('/api/admin/dashboard');pauseState=!!data.emergency_pause; | |
| byId('beta-pause-status').textContent=pauseState?'AC is paused':'AC is accepting questions'; | |
| byId('beta-pause-toggle').textContent=pauseState?'Resume AC':'Pause AC'; | |
| const labels={questions:'Total questions',jewish:'Jewish/Torah',secular:'Secular',blocked:'Blocked',security:'Security',news:'News',chochma:'Chochma',binah:'Binah',daas:'Daas',guest:'Guest questions',account:'Account questions',reports:'Reports',critical_flags:'Critical flags'}; | |
| byId('beta-stats').innerHTML='';Object.entries(labels).forEach(([key,name])=>{ | |
| const card=e('div','beta-kpi');card.innerHTML='<strong>'+Number(data.stats[key]||0)+'</strong><small>'+safe(name)+'</small>';byId('beta-stats').append(card) | |
| }); | |
| }catch(err){message(err.message)} | |
| }; | |
| const drawReports=async()=>{ | |
| try{const d=await api('/api/admin/reports'); | |
| const target=byId('beta-reports');target.innerHTML=''; | |
| if(!d.reports.length)target.textContent='No reports yet.'; | |
| d.reports.forEach(r=>{const card=e('div','beta-report');card.innerHTML='<strong>'+safe(r.kind)+'</strong> <span class="beta-muted">'+safe(r.time)+'</span>'; | |
| const q=e('p','','Question: '+(r.question||'(survey)'));const a=e('p','','Answer: '+(r.answer||'(not provided)'));const n=e('p','','Note: '+(r.note||'(none)'));card.append(q,a,n);target.append(card)}); | |
| const flags=byId('beta-flags');flags.innerHTML='';if(!d.critical_flags.length)flags.textContent='No flags.'; | |
| d.critical_flags.forEach(f=>{const card=e('div','beta-report');card.innerHTML='<div class="beta-muted">'+safe(f.time)+'</div>';card.append(e('p','',f.message));flags.append(card)}) | |
| }catch(err){message(err.message)} | |
| }; | |
| let bugView='open'; | |
| const drawBugs=async()=>{ | |
| const target=byId('beta-bugs-list');target.textContent='Loading bugs…'; | |
| try{ | |
| const d=await api('/api/admin/bugs'); | |
| const open=d.open||[], fixed=d.fixed||[], rows=bugView==='fixed'?fixed:open; | |
| byId('beta-bugs-open').textContent='Open ('+open.length+')'; | |
| byId('beta-bugs-fixed').textContent='Fixed archive ('+fixed.length+')'; | |
| byId('beta-bugs-open').setAttribute('aria-pressed',String(bugView==='open')); | |
| byId('beta-bugs-fixed').setAttribute('aria-pressed',String(bugView==='fixed')); | |
| byId('beta-bugs-storage').textContent=d.durable?'Bug records are stored in configured private storage.':'Bug records may reset when the Space restarts until private durable storage is configured.'; | |
| target.innerHTML=''; | |
| if(!rows.length){target.textContent=bugView==='open'?'No open bugs recorded yet.':'No fixed bugs in the archive.';return} | |
| rows.forEach(b=>{ | |
| const card=e('div','beta-bug'); | |
| card.append(e('div','beta-bug-title',b.title||'Unexpected error')); | |
| card.append(e('p','beta-bug-summary',b.summary||'A software error occurred.')); | |
| const details=e('div','beta-bug-technical'); | |
| details.append(e('div','', 'Error code: '+(b.error_code||'Unknown')+(b.reported_cause?' (reported '+b.reported_cause+')':''))); | |
| details.append(e('div','', 'Component: '+(b.component||'Unknown'))); | |
| details.append(e('div','', 'Location: '+(b.location||'Unknown'))); | |
| details.append(e('div','', 'Occurrences: '+Number(b.occurrences||0))); | |
| details.append(e('div','', 'Last seen: '+(b.last_seen||'Unknown'))); | |
| card.append(details); | |
| if(Array.isArray(b.trace)&&b.trace.length){ | |
| const more=e('details','beta-bug-trace');const summary=e('summary','','Technical traceback');more.append(summary); | |
| const pre=e('pre','',b.trace.join('\n'));more.append(pre);card.append(more); | |
| } | |
| const btn=e('button','beta-mini-btn',bugView==='fixed'?'Reopen bug':'Mark as Fixed'); | |
| btn.onclick=async()=>{ | |
| btn.disabled=true; | |
| try{await api('/api/admin/bugs/status',{bug_id:b.id,status:bugView==='fixed'?'open':'fixed'});await drawBugs()} | |
| catch(err){message(err.message);btn.disabled=false} | |
| }; | |
| card.append(btn);target.append(card); | |
| }); | |
| }catch(err){target.textContent='Could not load bugs: '+err.message} | |
| }; | |
| byId('beta-bugs-open').onclick=()=>{bugView='open';drawBugs()}; | |
| byId('beta-bugs-fixed').onclick=()=>{bugView='fixed';drawBugs()}; | |
| byId('beta-bugs-refresh').onclick=drawBugs; | |
| byId('beta-pause-toggle').onclick=async()=>{ | |
| showModal(pauseState?'Resume AC?':'Pause AC?',pauseState?'Users will be able to ask questions again.':'All new student questions will be stopped.',[ | |
| {label:'Cancel'}, {label:pauseState?'Resume AC':'Pause AC',fn:async()=>{ | |
| try{await api('/api/admin/pause',{paused:!pauseState});await drawStats()}catch(err){message(err.message)} | |
| }}]); | |
| }; | |
| byId('beta-reports-refresh').onclick=()=>{drawStats();drawReports()}; | |
| byId('beta-admin-logout').onclick=async()=>{await api('/api/admin/logout',{});location.href='/admin'}; | |
| drawStats();drawReports();drawBugs(); | |
| (async()=>{ | |
| try{ | |
| const d=await api('/api/admin/own-chats');if(!d.available)return; | |
| if(!localStorage.getItem('ac_admin_device_merged')){ | |
| showModal('Merge your admin chats?', 'This browser is new to the Head Admin account. Merge only your own saved chats with the Head Admin archive?', [ | |
| {label:'No, use saved admin chats',fn:()=>{archive=d.chats||[];localStorage.setItem('ac_admin_device_merged','yes');renderRecents()}}, | |
| {label:'Yes, merge chats',fn:()=>{const m=new Map((d.chats||[]).map(c=>[c.id,c]));archive.forEach(c=>m.set(c.id,c));archive=[...m.values()];localStorage.setItem('ac_admin_device_merged','yes');renderRecents();queueSync()}} | |
| ]); | |
| }else{archive=d.chats||[];renderRecents()} | |
| }catch(err){message('Admin chat sync unavailable: '+err.message)} | |
| })(); | |
| } | |
| } | |
| })(); | |