/* 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='
Guest chats are saved in this browser. Signed-in chats can sync across devices when durable private storage is configured.
Delete a conversation from the three-dot menu beside it. Deleting removes the saved copy; there is no trash folder.
`; settings?.append(retentionCard);byId('beta-retention').value=retention; const intensityCard=e('div','beta-setting-card');intensityCard.innerHTML='Choose how strong the mode colors feel on your screen.
'; 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=`Checking account availability…
`; settings?.append(accountCard); const privacyCard=e('div','beta-setting-card');privacyCard.innerHTML=`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.
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.
`; settings?.append(privacyCard); const info=e('div','beta-setting-card');info.innerHTML='Artificial Chochma · 1.5.0 Beta V7
Chochma: quick answers · Binah: fuller explanations · Daas: deeper reasoning and sources.
'; settings?.append(info); const feed=e('div','beta-setting-card');feed.innerHTML='Send feedback to the AC team. Only what you choose to submit will be shared.
'; 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=''+(signup?'':''); }); }; 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=`Private user conversations cannot be opened by administrators. Only totals, voluntarily submitted reports, and narrowly detected critical alerts are shown.
Immediately stop AC from answering new student requests until the pause is disabled.
Checking…
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.
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.