Spaces:
Running
Running
Update live.html
Browse files
live.html
CHANGED
|
@@ -4,8 +4,9 @@
|
|
| 4 |
<meta charset="utf-8">
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
| 6 |
<title>Gemini Live</title>
|
| 7 |
-
<script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script>
|
| 8 |
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Devanagari:wght@300;400;500&family=Sora:wght@300;500&display=swap" rel="stylesheet">
|
|
|
|
|
|
|
| 9 |
<style>
|
| 10 |
:root{--c1:#5ef2d6;--c2:#8b7bff;--ink:#eef1ff;--dim:#8d96c4;--lv:0}
|
| 11 |
*{box-sizing:border-box;margin:0;-webkit-tap-highlight-color:transparent}
|
|
@@ -158,42 +159,25 @@ const TXT={idle:'Start a conversation anytime',listening:'Listening…',thinking
|
|
| 158 |
nofl:'This camera has no flashlight. Try the back camera.',nocam:'Could not start the camera. Check permission.',
|
| 159 |
nomic:'No sound from your mic. Pick the right one in Settings.',mutedT:'Mic muted',unmutedT:'Mic on',
|
| 160 |
lang:'AI speaks',mode:'Voice input',mic:'Microphone',brow:'Browser',nat:'Native',err:'Connecting… send again in a moment'};
|
| 161 |
-
let LANG='hi';
|
| 162 |
try{LANG=localStorage.getItem('ailang')||'hi'}catch{}
|
| 163 |
const T=k=>TXT[k]||'';
|
| 164 |
const SR=window.SpeechRecognition||window.webkitSpeechRecognition;
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
const STATES={idle:{c:['#5ef2d6','#8b7bff','#4285f4']},listening:{c:['#5ef2d6','#4aa8ff','#8b7bff']},thinking:{c:['#ffc46b','#ff7ab8','#8b7bff']},speaking:{c:['#8b7bff','#ff7ab8','#5ef2d6']}};
|
| 167 |
const rgb=h=>[1,3,5].map(i=>parseInt(h.substr(i,2),16));
|
| 168 |
const cur=STATES.idle.c.map(rgb);
|
| 169 |
let state='',ws,micCtx,outCtx,stream,node,analyser,micAn,active=false,starting=false,muted=false,chunks=0,heard=0,rst='-',maxLevel=0;
|
| 170 |
let micLevel=0,spokeAt=0,userSpeaking=false,floor=.003,nextT=0,sources=[],rec=null,liveUser=null,botEl=null,userEl=null,typing=null,botActive=false,userBuf='';
|
| 171 |
-
let currentSessionId = Date.now();
|
| 172 |
-
let sessionInteractions = [];
|
| 173 |
|
| 174 |
-
function saveLiveSessionToHistory() {
|
| 175 |
-
if (sessionInteractions.length === 0) return;
|
| 176 |
-
let sessionData = {
|
| 177 |
-
id: currentSessionId,
|
| 178 |
-
type: 'live',
|
| 179 |
-
title: sessionInteractions[0].question || "Gemini Live Session",
|
| 180 |
-
interactions: sessionInteractions,
|
| 181 |
-
timestamp: currentSessionId
|
| 182 |
-
};
|
| 183 |
-
if (typeof localforage !== 'undefined') {
|
| 184 |
-
localforage.config({ name: 'AI_Pro_Suite', storeName: 'massive_chat_history' });
|
| 185 |
-
localforage.getItem('aiHistory').then(existing => {
|
| 186 |
-
let history = existing || [];
|
| 187 |
-
let index = history.findIndex(item => String(item.id) === String(currentSessionId));
|
| 188 |
-
if (index !== -1) {
|
| 189 |
-
history[index] = sessionData;
|
| 190 |
-
} else {
|
| 191 |
-
history.unshift(sessionData);
|
| 192 |
-
}
|
| 193 |
-
localforage.setItem('aiHistory', history);
|
| 194 |
-
}).catch(err => console.error("Error saving live session to localforage:", err));
|
| 195 |
-
}
|
| 196 |
-
}
|
| 197 |
function toast(m,ms){const e=$('toast');e.textContent=m;e.classList.add('on');clearTimeout(window.tt);window.tt=setTimeout(()=>e.classList.remove('on'),ms||3500)}
|
| 198 |
function applyLang(){
|
| 199 |
document.querySelectorAll('[data-t]').forEach(e=>e.textContent=T(e.dataset.t));
|
|
@@ -203,12 +187,55 @@ function applyLang(){
|
|
| 203 |
document.querySelectorAll('#modeseg button').forEach(b=>b.classList.toggle('on',b.dataset.m===MODE));
|
| 204 |
$('modeh').style.display=$('modeseg').style.display=SR?'':'none';refreshStatus();
|
| 205 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
/* ---------- captions ---------- */
|
| 207 |
const caps=()=>[$('cap'),$('camcap')];
|
| 208 |
function statusText(){if(!active)return T('idle');if(muted&&(state==='listening'||state==='idle'))return T('muted');return T(state)||''}
|
| 209 |
function capSet(text,cls){caps().forEach(e=>{e.className=cls;e.textContent=text})}
|
| 210 |
-
function capAdd(text){
|
| 211 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
function refreshStatus(){if(!botActive)capSet(statusText(),'status')}
|
| 213 |
function ucapSet(t){$('ucap').textContent=t;$('camucap').textContent=t}
|
| 214 |
function newUserTurn(){botActive=false;refreshStatus()}
|
|
@@ -219,36 +246,92 @@ function setState(s){
|
|
| 219 |
refreshStatus();
|
| 220 |
if(MODE==='stt'&&active){if(s==='speaking')stopRec();else if(s==='listening')startRec()}
|
| 221 |
}
|
|
|
|
| 222 |
/* ---------- written conversation ---------- */
|
| 223 |
const chat=$('chat');
|
| 224 |
function newLine(cls){const m=document.createElement('div');m.className='msg '+cls;
|
| 225 |
m.innerHTML='<div class="who">'+(cls==='you'?'You':'Gemini')+'</div><div class="txt"></div>';chat.appendChild(m);chat.scrollTop=1e9;return m}
|
| 226 |
-
function addWords(m,text){
|
| 227 |
-
|
| 228 |
-
m.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
function showTyping(){if(typing||botEl)return;typing=newLine('bot');typing.lastChild.innerHTML='<span class="dots"><i></i><i></i><i></i></span>'}
|
| 230 |
function hideTyping(){if(typing){typing.remove();typing=null}}
|
| 231 |
-
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
function addUser(text){
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
}
|
| 238 |
function onUserText(t){
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
}
|
| 248 |
function onBotText(t){
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
|
| 253 |
/* ---------- browser speech recognition ---------- */
|
| 254 |
function startRec(){
|
|
@@ -259,8 +342,17 @@ function startRec(){
|
|
| 259 |
for(let i=e.resultIndex;i<e.results.length;i++){const x=e.results[i];if(x.isFinal)fin+=x[0].transcript;else interim+=x[0].transcript}
|
| 260 |
const txt=(fin||interim).trim();if(!txt)return;rst='heard you';
|
| 261 |
if(state!=='speaking')setState('listening');
|
| 262 |
-
hideTyping();endTurn();
|
| 263 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
if(fin.trim()){liveUser=null;heard++;sendText(fin.trim())}
|
| 265 |
};
|
| 266 |
r.onstart=()=>{rst='recognizer on'};r.onsoundstart=()=>{rst='sound detected'};r.onspeechstart=()=>{rst='speech detected'};
|
|
@@ -390,13 +482,10 @@ function sendFrame(){
|
|
| 390 |
}
|
| 391 |
|
| 392 |
/* ---------- wiring ---------- */
|
| 393 |
-
$('pill').onclick=()=>{if(!active)start();else if(state==='speaking'){stopPlayback();setState('listening')}};
|
| 394 |
-
$('bend').onclick=()=>{if(active){saveLiveSessionToHistory();stop()}};
|
| 395 |
-
window.addEventListener('beforeunload',()=>{saveLiveSessionToHistory()});
|
| 396 |
-
$('bend').onclick=()=>{if(active)stop()};
|
| 397 |
$('bmute').onclick=$('cmute').onclick=toggleMute;
|
| 398 |
$('bcam').onclick=openCam;$('coff').onclick=closeCam;$('cflip').onclick=async()=>{facing=facing==='user'?'environment':'user';await startCamStream()};$('cflash').onclick=toggleTorch;
|
| 399 |
-
$('btext').onclick=()=>{$('textview').classList.add('on');if(!active)start();setTimeout(()=>$('typed').focus(),450)};
|
| 400 |
$('tclose').onclick=()=>$('textview').classList.remove('on');
|
| 401 |
function submitText(){const v=$('typed').value.trim();if(!v)return;if(!active){toast(T('err'));start();return}$('typed').value='';addUser(v);sendText(v)}
|
| 402 |
$('tsend').onclick=submitText;$('typed').addEventListener('keydown',e=>{if(e.key==='Enter')submitText()});
|
|
@@ -408,7 +497,7 @@ applyLang();
|
|
| 408 |
|
| 409 |
/* ---------- background animation ---------- */
|
| 410 |
const fx=$('fx'),f=fx.getContext('2d'),BARS=[...document.querySelectorAll('#bars i')];
|
| 411 |
-
let FW,FH,smooth=0,ripples=[],lastState='';
|
| 412 |
const buf=new Uint8Array(128),micBuf=new Uint8Array(64),DPR=()=>devicePixelRatio||1,avg=a=>a.reduce((x,y)=>x+y,0)/a.length;
|
| 413 |
function fit(){const d=DPR();FW=fx.width=innerWidth*d;FH=fx.height=innerHeight*d}addEventListener('resize',fit);fit();
|
| 414 |
const PT=Array.from({length:70},()=>({x:Math.random(),y:Math.random(),s:.2+Math.random(),z:Math.random()}));
|
|
@@ -437,7 +526,7 @@ function frame(){
|
|
| 437 |
}
|
| 438 |
PT.forEach((p,i)=>{p.y-=p.s*.0004*(1+smooth*4);if(p.y<0){p.y=1;p.x=Math.random()}
|
| 439 |
f.fillStyle=rgba(cur[i%3],.1+.45*p.z*(.3+smooth));f.beginPath();f.arc(p.x*FW+Math.sin(t+i)*12*d,p.y*FH,(1+p.z*2.2)*d,0,7);f.fill()});
|
| 440 |
-
if(!document.body.classList.contains('camopen')){
|
| 441 |
const rc=$('pill').getBoundingClientRect(),ox=(rc.left+rc.width/2)*d,oy=(rc.top+rc.height/2)*d;
|
| 442 |
ripples.forEach(q=>{q.r+=.011;f.beginPath();f.arc(ox,oy,(40+q.r*260)*d,0,7);f.lineWidth=2*d;f.strokeStyle=rgba(cur[0],q.a*(1-q.r));f.stroke()});
|
| 443 |
}
|
|
@@ -445,6 +534,40 @@ function frame(){
|
|
| 445 |
requestAnimationFrame(frame);
|
| 446 |
}
|
| 447 |
frame();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 448 |
</script>
|
| 449 |
<script src="nav-sidebar.js" data-pos="none"></script>
|
| 450 |
</body>
|
|
|
|
| 4 |
<meta charset="utf-8">
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
| 6 |
<title>Gemini Live</title>
|
|
|
|
| 7 |
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Devanagari:wght@300;400;500&family=Sora:wght@300;500&display=swap" rel="stylesheet">
|
| 8 |
+
<!-- Added localForage for History Vault compatibility -->
|
| 9 |
+
<script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script>
|
| 10 |
<style>
|
| 11 |
:root{--c1:#5ef2d6;--c2:#8b7bff;--ink:#eef1ff;--dim:#8d96c4;--lv:0}
|
| 12 |
*{box-sizing:border-box;margin:0;-webkit-tap-highlight-color:transparent}
|
|
|
|
| 159 |
nofl:'This camera has no flashlight. Try the back camera.',nocam:'Could not start the camera. Check permission.',
|
| 160 |
nomic:'No sound from your mic. Pick the right one in Settings.',mutedT:'Mic muted',unmutedT:'Mic on',
|
| 161 |
lang:'AI speaks',mode:'Voice input',mic:'Microphone',brow:'Browser',nat:'Native',err:'Connecting… send again in a moment'};
|
| 162 |
+
let LANG='hi';
|
| 163 |
try{LANG=localStorage.getItem('ailang')||'hi'}catch{}
|
| 164 |
const T=k=>TXT[k]||'';
|
| 165 |
const SR=window.SpeechRecognition||window.webkitSpeechRecognition;
|
| 166 |
+
|
| 167 |
+
// 1. DEFAULT MIC INPUT IS NOW NATIVE (DEVICE)
|
| 168 |
+
let MODE='native';
|
| 169 |
+
|
| 170 |
+
// HISTORY TRACKING VARS
|
| 171 |
+
let liveSessionId = Date.now().toString();
|
| 172 |
+
let currentInteractions = [];
|
| 173 |
+
let interactionCount = 0;
|
| 174 |
+
|
| 175 |
const STATES={idle:{c:['#5ef2d6','#8b7bff','#4285f4']},listening:{c:['#5ef2d6','#4aa8ff','#8b7bff']},thinking:{c:['#ffc46b','#ff7ab8','#8b7bff']},speaking:{c:['#8b7bff','#ff7ab8','#5ef2d6']}};
|
| 176 |
const rgb=h=>[1,3,5].map(i=>parseInt(h.substr(i,2),16));
|
| 177 |
const cur=STATES.idle.c.map(rgb);
|
| 178 |
let state='',ws,micCtx,outCtx,stream,node,analyser,micAn,active=false,starting=false,muted=false,chunks=0,heard=0,rst='-',maxLevel=0;
|
| 179 |
let micLevel=0,spokeAt=0,userSpeaking=false,floor=.003,nextT=0,sources=[],rec=null,liveUser=null,botEl=null,userEl=null,typing=null,botActive=false,userBuf='';
|
|
|
|
|
|
|
| 180 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
function toast(m,ms){const e=$('toast');e.textContent=m;e.classList.add('on');clearTimeout(window.tt);window.tt=setTimeout(()=>e.classList.remove('on'),ms||3500)}
|
| 182 |
function applyLang(){
|
| 183 |
document.querySelectorAll('[data-t]').forEach(e=>e.textContent=T(e.dataset.t));
|
|
|
|
| 187 |
document.querySelectorAll('#modeseg button').forEach(b=>b.classList.toggle('on',b.dataset.m===MODE));
|
| 188 |
$('modeh').style.display=$('modeseg').style.display=SR?'':'none';refreshStatus();
|
| 189 |
}
|
| 190 |
+
|
| 191 |
+
// 2. SAVING HISTORY CORE LOGIC
|
| 192 |
+
async function saveToHistory() {
|
| 193 |
+
if (interactionCount < 2) return;
|
| 194 |
+
try {
|
| 195 |
+
let history = await localforage.getItem('aiHistory') || [];
|
| 196 |
+
let existingIdx = history.findIndex(h => String(h.id) === String(liveSessionId));
|
| 197 |
+
|
| 198 |
+
let title = "Live Conversation";
|
| 199 |
+
if (currentInteractions.length > 0 && currentInteractions[0].question) {
|
| 200 |
+
title = currentInteractions[0].question.substring(0, 50);
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
let sessionObj = {
|
| 204 |
+
id: liveSessionId,
|
| 205 |
+
type: 'live',
|
| 206 |
+
title: title,
|
| 207 |
+
interactions: currentInteractions,
|
| 208 |
+
timestamp: Date.now()
|
| 209 |
+
};
|
| 210 |
+
if (existingIdx >= 0) {
|
| 211 |
+
history[existingIdx] = sessionObj;
|
| 212 |
+
} else {
|
| 213 |
+
history.unshift(sessionObj);
|
| 214 |
+
}
|
| 215 |
+
await localforage.setItem('aiHistory', history);
|
| 216 |
+
} catch (e) { console.error("History save error", e); }
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
/* ---------- captions ---------- */
|
| 220 |
const caps=()=>[$('cap'),$('camcap')];
|
| 221 |
function statusText(){if(!active)return T('idle');if(muted&&(state==='listening'||state==='idle'))return T('muted');return T(state)||''}
|
| 222 |
function capSet(text,cls){caps().forEach(e=>{e.className=cls;e.textContent=text})}
|
| 223 |
+
function capAdd(text){
|
| 224 |
+
caps().forEach(e=>{
|
| 225 |
+
if(e.className!=='bot'){e.className='bot';e.textContent=''}
|
| 226 |
+
text.split(/(\s+)/).filter(Boolean).forEach(w=>{
|
| 227 |
+
const s=document.createElement('span');
|
| 228 |
+
s.className='w';
|
| 229 |
+
s.textContent=w;
|
| 230 |
+
e.appendChild(s);
|
| 231 |
+
});
|
| 232 |
+
// DOM OPTIMIZATION: Cap maximum visible words in the live caption to prevent lag over long periods
|
| 233 |
+
while(e.childNodes.length > 60) {
|
| 234 |
+
e.removeChild(e.firstChild);
|
| 235 |
+
}
|
| 236 |
+
e.scrollTop=1e9;
|
| 237 |
+
});
|
| 238 |
+
}
|
| 239 |
function refreshStatus(){if(!botActive)capSet(statusText(),'status')}
|
| 240 |
function ucapSet(t){$('ucap').textContent=t;$('camucap').textContent=t}
|
| 241 |
function newUserTurn(){botActive=false;refreshStatus()}
|
|
|
|
| 246 |
refreshStatus();
|
| 247 |
if(MODE==='stt'&&active){if(s==='speaking')stopRec();else if(s==='listening')startRec()}
|
| 248 |
}
|
| 249 |
+
|
| 250 |
/* ---------- written conversation ---------- */
|
| 251 |
const chat=$('chat');
|
| 252 |
function newLine(cls){const m=document.createElement('div');m.className='msg '+cls;
|
| 253 |
m.innerHTML='<div class="who">'+(cls==='you'?'You':'Gemini')+'</div><div class="txt"></div>';chat.appendChild(m);chat.scrollTop=1e9;return m}
|
| 254 |
+
function addWords(m,text){
|
| 255 |
+
m.classList.remove('cursor');
|
| 256 |
+
const box=m.lastChild;
|
| 257 |
+
text.split(/(\s+)/).filter(Boolean).forEach(w=>{
|
| 258 |
+
const s=document.createElement('span');
|
| 259 |
+
s.className='w';
|
| 260 |
+
s.textContent=w;
|
| 261 |
+
box.appendChild(s);
|
| 262 |
+
});
|
| 263 |
+
m.classList.add('cursor');
|
| 264 |
+
chat.scrollTop=1e9;
|
| 265 |
+
}
|
| 266 |
function showTyping(){if(typing||botEl)return;typing=newLine('bot');typing.lastChild.innerHTML='<span class="dots"><i></i><i></i><i></i></span>'}
|
| 267 |
function hideTyping(){if(typing){typing.remove();typing=null}}
|
| 268 |
+
|
| 269 |
+
// 3. DOM LEAK LAG FIX: Squash spans at turn end
|
| 270 |
+
function endTurn(){
|
| 271 |
+
if(botEl){
|
| 272 |
+
botEl.classList.remove('cursor');
|
| 273 |
+
// Converts thousands of heavy span elements into one single lightweight text node
|
| 274 |
+
if(botEl.lastChild) botEl.lastChild.innerHTML = botEl.lastChild.textContent;
|
| 275 |
+
}
|
| 276 |
+
botEl=null;
|
| 277 |
+
if(interactionCount >= 2) saveToHistory();
|
| 278 |
+
}
|
| 279 |
+
function closeUserEl(){
|
| 280 |
+
if(userEl){
|
| 281 |
+
userEl.classList.remove('cursor');
|
| 282 |
+
// Squash user node spans too
|
| 283 |
+
if(userEl.lastChild) userEl.lastChild.innerHTML = userEl.lastChild.textContent;
|
| 284 |
+
userEl=null;
|
| 285 |
+
}
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
function addUser(text){
|
| 289 |
+
hideTyping();
|
| 290 |
+
endTurn();
|
| 291 |
+
closeUserEl();
|
| 292 |
+
const m=newLine('you');
|
| 293 |
+
m.lastChild.textContent=text;
|
| 294 |
+
userBuf='';
|
| 295 |
+
ucapSet(text);
|
| 296 |
+
|
| 297 |
+
// Track History Interaction
|
| 298 |
+
currentInteractions.push({ question: text, answer: '', timestamp: Date.now() });
|
| 299 |
+
interactionCount++;
|
| 300 |
+
|
| 301 |
+
newUserTurn();
|
| 302 |
}
|
| 303 |
function onUserText(t){
|
| 304 |
+
hideTyping();
|
| 305 |
+
endTurn();
|
| 306 |
+
if(!userEl) {
|
| 307 |
+
userEl=newLine('you');
|
| 308 |
+
currentInteractions.push({ question: '', answer: '', timestamp: Date.now() });
|
| 309 |
+
interactionCount++;
|
| 310 |
+
}
|
| 311 |
+
addWords(userEl,t);
|
| 312 |
+
userBuf+=t;
|
| 313 |
+
ucapSet(userBuf);
|
| 314 |
+
|
| 315 |
+
// Update History Interaction
|
| 316 |
+
if(currentInteractions.length > 0) currentInteractions[currentInteractions.length - 1].question += t;
|
| 317 |
+
|
| 318 |
+
newUserTurn();
|
| 319 |
}
|
| 320 |
function onBotText(t){
|
| 321 |
+
hideTyping();
|
| 322 |
+
closeUserEl();
|
| 323 |
+
userBuf='';
|
| 324 |
+
if(state==='listening'||state==='idle')setState('thinking');
|
| 325 |
+
hideTyping();
|
| 326 |
+
if(!botEl){botEl=newLine('bot');capSet('','bot')}
|
| 327 |
+
addWords(botEl,t);
|
| 328 |
+
botActive=true;
|
| 329 |
+
capAdd(t);
|
| 330 |
+
|
| 331 |
+
// Update History Interaction
|
| 332 |
+
if(currentInteractions.length > 0) currentInteractions[currentInteractions.length - 1].answer += t;
|
| 333 |
+
}
|
| 334 |
+
function sendText(text){if(ws&&ws.readyState===1){sendFrame();ws.send(JSON.stringify({t:'text',text}));setState('thinking')}}
|
| 335 |
|
| 336 |
/* ---------- browser speech recognition ---------- */
|
| 337 |
function startRec(){
|
|
|
|
| 342 |
for(let i=e.resultIndex;i<e.results.length;i++){const x=e.results[i];if(x.isFinal)fin+=x[0].transcript;else interim+=x[0].transcript}
|
| 343 |
const txt=(fin||interim).trim();if(!txt)return;rst='heard you';
|
| 344 |
if(state!=='speaking')setState('listening');
|
| 345 |
+
hideTyping();endTurn();
|
| 346 |
+
if(!liveUser) {
|
| 347 |
+
liveUser=newLine('you');
|
| 348 |
+
currentInteractions.push({ question: '', answer: '', timestamp: Date.now() });
|
| 349 |
+
interactionCount++;
|
| 350 |
+
}
|
| 351 |
+
liveUser.lastChild.textContent=txt;
|
| 352 |
+
chat.scrollTop=1e9;ucapSet(txt);newUserTurn();
|
| 353 |
+
|
| 354 |
+
if (currentInteractions.length > 0) currentInteractions[currentInteractions.length - 1].question = txt;
|
| 355 |
+
|
| 356 |
if(fin.trim()){liveUser=null;heard++;sendText(fin.trim())}
|
| 357 |
};
|
| 358 |
r.onstart=()=>{rst='recognizer on'};r.onsoundstart=()=>{rst='sound detected'};r.onspeechstart=()=>{rst='speech detected'};
|
|
|
|
| 482 |
}
|
| 483 |
|
| 484 |
/* ---------- wiring ---------- */
|
| 485 |
+
$('pill').onclick=()=>{if(!active)start();else if(state==='speaking'){stopPlayback();setState('listening')}};$('bend').onclick=()=>{if(active)stop()};
|
|
|
|
|
|
|
|
|
|
| 486 |
$('bmute').onclick=$('cmute').onclick=toggleMute;
|
| 487 |
$('bcam').onclick=openCam;$('coff').onclick=closeCam;$('cflip').onclick=async()=>{facing=facing==='user'?'environment':'user';await startCamStream()};$('cflash').onclick=toggleTorch;
|
| 488 |
+
$('btext').onclick=()=>{$('textview').classList.add('on');if(!active&&!$('textview').dataset.restored)start();setTimeout(()=>$('typed').focus(),450)};
|
| 489 |
$('tclose').onclick=()=>$('textview').classList.remove('on');
|
| 490 |
function submitText(){const v=$('typed').value.trim();if(!v)return;if(!active){toast(T('err'));start();return}$('typed').value='';addUser(v);sendText(v)}
|
| 491 |
$('tsend').onclick=submitText;$('typed').addEventListener('keydown',e=>{if(e.key==='Enter')submitText()});
|
|
|
|
| 497 |
|
| 498 |
/* ---------- background animation ---------- */
|
| 499 |
const fx=$('fx'),f=fx.getContext('2d'),BARS=[...document.querySelectorAll('#bars i')];
|
| 500 |
+
let FW,FH,t=0,smooth=0,ripples=[],lastState='';
|
| 501 |
const buf=new Uint8Array(128),micBuf=new Uint8Array(64),DPR=()=>devicePixelRatio||1,avg=a=>a.reduce((x,y)=>x+y,0)/a.length;
|
| 502 |
function fit(){const d=DPR();FW=fx.width=innerWidth*d;FH=fx.height=innerHeight*d}addEventListener('resize',fit);fit();
|
| 503 |
const PT=Array.from({length:70},()=>({x:Math.random(),y:Math.random(),s:.2+Math.random(),z:Math.random()}));
|
|
|
|
| 526 |
}
|
| 527 |
PT.forEach((p,i)=>{p.y-=p.s*.0004*(1+smooth*4);if(p.y<0){p.y=1;p.x=Math.random()}
|
| 528 |
f.fillStyle=rgba(cur[i%3],.1+.45*p.z*(.3+smooth));f.beginPath();f.arc(p.x*FW+Math.sin(t+i)*12*d,p.y*FH,(1+p.z*2.2)*d,0,7);f.fill()});
|
| 529 |
+
if(!document.body.classList.contains('camopen')){
|
| 530 |
const rc=$('pill').getBoundingClientRect(),ox=(rc.left+rc.width/2)*d,oy=(rc.top+rc.height/2)*d;
|
| 531 |
ripples.forEach(q=>{q.r+=.011;f.beginPath();f.arc(ox,oy,(40+q.r*260)*d,0,7);f.lineWidth=2*d;f.strokeStyle=rgba(cur[0],q.a*(1-q.r));f.stroke()});
|
| 532 |
}
|
|
|
|
| 534 |
requestAnimationFrame(frame);
|
| 535 |
}
|
| 536 |
frame();
|
| 537 |
+
|
| 538 |
+
// 4. RESTORE OFFLINE SESSION LOGIC
|
| 539 |
+
document.addEventListener("DOMContentLoaded", () => {
|
| 540 |
+
const urlParams = new URLSearchParams(window.location.search);
|
| 541 |
+
const restoreId = urlParams.get('restore');
|
| 542 |
+
if (restoreId) {
|
| 543 |
+
$('textview').classList.add('on');$('textview').dataset.restored = "true"; // Prevents auto-connect until manual action
|
| 544 |
+
|
| 545 |
+
localforage.getItem('aiHistory').then(history => {
|
| 546 |
+
if (history) {
|
| 547 |
+
const session = history.find(h => String(h.id) === String(restoreId));
|
| 548 |
+
if (session && session.interactions) {
|
| 549 |
+
liveSessionId = session.id;
|
| 550 |
+
currentInteractions = session.interactions;
|
| 551 |
+
interactionCount = currentInteractions.length;
|
| 552 |
+
|
| 553 |
+
session.interactions.forEach(inter => {
|
| 554 |
+
if (inter.question) {
|
| 555 |
+
const u = newLine('you');
|
| 556 |
+
u.classList.remove('cursor');
|
| 557 |
+
u.lastChild.textContent = inter.question;
|
| 558 |
+
}
|
| 559 |
+
if (inter.answer) {
|
| 560 |
+
const b = newLine('bot');
|
| 561 |
+
b.classList.remove('cursor');
|
| 562 |
+
b.lastChild.textContent = inter.answer;
|
| 563 |
+
}
|
| 564 |
+
});
|
| 565 |
+
chat.scrollTop = 1e9;
|
| 566 |
+
}
|
| 567 |
+
}
|
| 568 |
+
}).catch(e => console.error("Restore Error:", e));
|
| 569 |
+
}
|
| 570 |
+
});
|
| 571 |
</script>
|
| 572 |
<script src="nav-sidebar.js" data-pos="none"></script>
|
| 573 |
</body>
|