cabin-local / src /main.js
fffiloni's picture
Compact the introduction, highlight llama.cpp v1 and explain TestFlight beta testing
3645677 verified
Raw History Blame Contribute Delete
14.2 kB
import './style.css';
import catalog from '../ios/CabinLocal/Resources/model-catalog.json';
import { LocalEngine, cachedModels, deleteModel } from './engine.js';
import { ServerSpeech, Microphone } from './speech.js';
import { phases, controls, centerAction, stateGraphic } from './carplay.js';
import carTheme from '../ios/CabinLocal/Resources/carplay-theme.json';
const $=id=>document.getElementById(id), engine=new LocalEngine(), speech=new ServerSpeech(), mic=new Microphone();
for(const [name,value] of Object.entries(carTheme.colors))$('car-screen').style.setProperty(`--${name}`,value);
let selected=catalog.defaultModelID,cached=[],phase='setup',connected=false,voiceReady=false,preview=null,controller=null,operation=0,preparingVoice=false,lastResult=null,playingDone=null;
try{const saved=localStorage.getItem('cabin-model');if(catalog.models.some(m=>m.id===saved))selected=saved;}catch{}
const busy=()=>['loading','listening','thinking','speaking'].includes(phase)||preparingVoice;
const model=()=>catalog.models.find(m=>m.id===selected);
const ready=()=>!!engine.model&&engine.model.id===selected&&voiceReady;
function status(message,error=false){$('session-status').textContent=message;$('session-status').parentElement.classList.toggle('error',error);}
function renderModels(){
$('model-options').replaceChildren(...catalog.models.map(m=>{
const label=document.createElement('label');label.className='model-option';
const input=document.createElement('input');input.type='radio';input.name='model';input.checked=m.id===selected;input.disabled=busy()||connected;
input.addEventListener('change',async()=>{if(busy()||connected)return;selected=m.id;try{localStorage.setItem('cabin-model',selected);}catch{} await engine.unload();clear();phase='setup';$('load-status').textContent='Load this model before connecting.';render();});
const title=document.createElement('span');title.className='model-title';title.textContent=m.name;
const meta=document.createElement('span');meta.className='model-meta';meta.textContent=`${m.sizeLabel} · Q4_K_M${cached.includes(m.id)?' · cached':''}`;
label.append(input,title,meta);return label;
}));
}
function render(){
renderModels();const prepared=engine.model?.id===selected;
$('load').disabled=busy()||connected||prepared;$('load').textContent=prepared?'Model ready ✓':'Download & load ↓';
$('persist').disabled=busy()||connected;$('delete').disabled=busy()||connected||!cached.includes(selected);
$('enable-voice').disabled=busy()||connected||voiceReady;$('enable-voice').textContent=preparingVoice?'Connecting…':voiceReady?'Server voice ready ✓':'Enable server voice';
$('voice').disabled=busy()||connected;
$('connect').disabled=!ready()||busy()||connected;$('connect').textContent=connected?'CarPlay connected ✓':'Connect CarPlay';
$('phone-note').textContent=connected?'Disconnect to change model or voice.':ready()?'Connecting starts listening. Allow the microphone when asked.':'Prepare model and voice first.';
$('disconnect').disabled=!connected;
const carPhase=preview||(connected?phase:'setup');
$('car-screen').dataset.state=carPhase;$('phase-icon').innerHTML=stateGraphic(carPhase,carTheme.waveHeights);$('carplay-state').textContent=phases[carPhase].title;
const c=controls(phase,ready());$('talk').disabled=!!preview||!connected||!c.talk;$('stop').disabled=!!preview||!connected||!c.stop;
const action=centerAction(phase,ready(),connected,!!preview);
$('voice-orb').disabled=!action;$('voice-orb').setAttribute('aria-label',action==='stop'?'Stop conversation':action==='talk'?'Start listening':preview?'Layout preview only':'Prepare the model and voice on the phone');
$('orb-hint').textContent=preview?'Layout preview':action==='stop'?'Tap to stop':action==='talk'?'Tap to talk':carPhase==='loading'?'Preparing…':'Prepare on iPhone';
$('connection-label').textContent=preview?'LAYOUT PREVIEW':connected?'CONNECTED':'NOT CONNECTED';
for(const b of document.querySelectorAll('[data-phase]')){b.disabled=busy();b.classList.toggle('active',preview===b.dataset.phase);}
$('exit-preview').hidden=!preview;
$('question').disabled=!ready()||busy();$('send').disabled=!ready()||busy();$('audio-upload').disabled=!ready()||busy();$('voice-sample').disabled=!ready()||busy();
$('clear').disabled=!engine.model||busy();for(const b of document.querySelectorAll('[data-prompt]'))b.disabled=!ready()||busy();
$('ready-dot').classList.toggle('on',ready());
}
function setPhase(p){phase=p;render();}
function clear(){engine.history=[];$('conversation').hidden=true;$('answer').textContent='';$('last-question').textContent='';lastResult=null;$('playback').hidden=true;$('audio').removeAttribute('src');}
function view(name){name=({preparer:'demo',cockpit:'demo',contribuer:'build'})[name]||name;name=name==='build'?'build':'demo';$('demo').hidden=name!=='demo';$('build').hidden=name!=='build';for(const b of document.querySelectorAll('[data-view]')){b.classList.toggle('active',b.dataset.view===name);if(b.dataset.view===name)b.setAttribute('aria-current','page');else b.removeAttribute('aria-current');}}
for(const b of document.querySelectorAll('[data-view]'))b.addEventListener('click',()=>{location.hash=b.dataset.view;view(b.dataset.view);});window.addEventListener('hashchange',()=>view(location.hash.slice(1)));view(location.hash.slice(1));
for(const [key,value] of Object.entries(phases)){const b=document.createElement('button');b.textContent=value.title;b.dataset.phase=key;b.addEventListener('click',()=>{if(busy())return;preview=key;render();});$('state-buttons').append(b);}
$('exit-preview').addEventListener('click',()=>{preview=null;render();});
$('load').addEventListener('click',async()=>{
if(busy()||connected)return;preview=null;controller=new AbortController();clear();setPhase('loading');$('progress-wrap').hidden=false;
const chosen=model();status('Downloading the conversation model to this browser…');
try{
let lastPaint=0;
await engine.load(chosen,controller.signal,p=>{if(performance.now()-lastPaint<150&&p.loaded!==p.total)return;lastPaint=performance.now();$('progress').value=p.phase==='load'?100:Math.round(100*p.loaded/p.total);$('progress-label').textContent=p.phase==='load'?'Starting llama.cpp…':`${p.phase==='verify'?'Verifying':'Downloading'} · ${Math.round(100*p.loaded/p.total)}%`;$('cancel-load').hidden=p.phase==='load';},$('persist').checked);
$('load-status').textContent=`SHA-256 verified · ${engine.info().threads} CPU thread(s).`;
status(voiceReady?'Ready. Connect CarPlay or use the test console.':'Model loaded. Enable server voice on the phone.');
}catch(e){const message=e.name==='AbortError'?'Download cancelled.':e.name==='QuotaExceededError'?'Browser storage is unavailable. Uncheck “Keep weights” and try again.':e.message;$('load-status').textContent=message;status(message,e.name!=='AbortError');}
finally{controller=null;$('cancel-load').hidden=true;$('progress-wrap').hidden=true;phase=ready()?'ready':'setup';cached=await cachedModels(catalog.models);render();}
});
$('cancel-load').addEventListener('click',()=>controller?.abort());
$('delete').addEventListener('click',async()=>{if(busy()||connected)return;setPhase('loading');try{await engine.unload();await deleteModel(model());clear();cached=await cachedModels(catalog.models);$('load-status').textContent='Cached model deleted.';}catch(e){status(e.message,true);}finally{setPhase('setup');}});
$('enable-voice').addEventListener('click',async()=>{if(busy())return;preparingVoice=true;render();status('Connecting to the ZeroGPU speech service…');try{await speech.connect();voiceReady=true;status(engine.model?'Ready. Connect CarPlay or use the test console.':'Voice ready. Load a conversation model.');}catch(e){status(e.message,true);}finally{preparingVoice=false;setPhase(ready()?'ready':'setup');}});
function stop(message='Conversation stopped.'){
operation++;controller?.abort();controller=null;mic.cancel();speech.cancel();$('audio').pause();playingDone?.();playingDone=null;$('playback').hidden=true;
setPhase(ready()?'ready':'setup');status(message);
}
$('stop').addEventListener('click',()=>stop());
$('disconnect').addEventListener('click',()=>{connected=false;preview=null;stop('Disconnected. Model and voice settings are available on the phone.');});
$('connect').addEventListener('click',()=>{if(!ready()||busy())return;connected=true;preview=null;setPhase('ready');void listen();});
$('talk').addEventListener('click',()=>void listen());
$('voice-orb').addEventListener('click',()=>{const action=centerAction(phase,ready(),connected,!!preview);if(action==='stop')stop();else if(action==='talk')void listen();});
function primePlayback(){const audio=$('audio');audio.pause();audio.src='data:audio/wav;base64,UklGRiYAAABXQVZFZm10IBAAAAABAAEAgD4AAAB9AAACABAAZGF0YQIAAAAAAA==';audio.play().catch(()=>{});}
async function listen(){
if(!ready()||busy())return;preview=null;primePlayback();const ticket=++operation;setPhase('listening');status('Listening. Pause when you finish; Stop cancels the question.');
try{const recording=await mic.record();if(ticket!==operation)return;setPhase('thinking');status('Transcribing with Whisper on ZeroGPU…');const question=await speech.transcribe(recording,msg=>{if(ticket===operation)status(msg);});if(ticket!==operation)return;await answer(question,ticket);}
catch(e){if(ticket===operation){setPhase(ready()?'error':'setup');status(e.name==='NotAllowedError'?'Microphone permission is unavailable. Use the text or audio test console.':e.name==='NotFoundError'?'No microphone is available. Use the voice sample or test console.':e.message,true);}}
}
async function answer(question,ticket){
controller=new AbortController();setPhase('thinking');$('conversation').hidden=false;$('last-question').textContent=question;$('answer').textContent='';$('playback').hidden=true;status('llama.cpp is generating the answer in this browser…');
const start=performance.now();let timeout;
try{
timeout=setTimeout(()=>controller?.abort(),60000);
const response=await engine.generate(question,controller.signal,text=>{if(ticket===operation)$('answer').textContent=text;});clearTimeout(timeout);if(ticket!==operation)return;
const llmMs=Math.round(performance.now()-start);controller=null;
status('Preparing the spoken answer with ZONOS3-Mini on ZeroGPU…');
const url=await speech.synthesize(response,$('voice').value,msg=>{if(ticket===operation)status(msg);});if(ticket!==operation)return;
lastResult={model:engine.model.id,llmMs,totalMs:Math.round(performance.now()-start),status:'completed',timestamp:new Date().toISOString()};
$('audio').src=url;$('playback').hidden=false;
await play(ticket);
}catch(e){if(ticket===operation){setPhase(ready()?'error':'setup');status(e.name==='AbortError'?'The answer timed out. Try a shorter question.':e.message,true);}}
finally{clearTimeout(timeout);if(ticket===operation)controller=null;}
}
async function play(ticket){
const audio=$('audio');
try{
await audio.play();if(ticket!==operation){audio.pause();return;}
setPhase('speaking');status('Speaking with ZONOS3-Mini. Stop interrupts playback.');
await new Promise(resolve=>{const finish=()=>{clearTimeout(timer);audio.removeEventListener('ended',finish);audio.removeEventListener('error',finish);resolve();};const timer=setTimeout(()=>{audio.pause();finish();},90000);playingDone=finish;audio.addEventListener('ended',finish,{once:true});audio.addEventListener('error',finish,{once:true});});
if(ticket===operation){playingDone=null;setPhase('ready');status('Ready for another question.');}
}catch(e){if(ticket===operation){setPhase('ready');status('Your answer is ready. Tap Play response to allow audio playback.');}}
}
$('play-response').addEventListener('click',()=>{if(!busy()&&$('audio').getAttribute('src'))void play(++operation);});
async function askTyped(text){if(!text.trim()||!ready()||busy())return;preview=null;primePlayback();const ticket=++operation;$('question').value='';await answer(text.trim().slice(0,500),ticket);}
$('prompt-form').addEventListener('submit',e=>{e.preventDefault();void askTyped($('question').value);});
for(const b of document.querySelectorAll('[data-prompt]'))b.addEventListener('click',()=>void askTyped(b.dataset.prompt));
async function askRecording(file){
if(busy()||!ready())return;
if(file?.size>5*1024*1024){status('Use an audio file smaller than 5 MB and shorter than 21 seconds.',true);return;}
preview=null;primePlayback();const ticket=++operation;setPhase('thinking');status('Sending the test recording to Whisper on ZeroGPU…');
try{
if(!file){const r=await fetch('/downloads/cabin-voice-sample.wav');if(!r.ok)throw Error('The voice sample is unavailable.');file=await r.blob();}
if(ticket!==operation)return;
const text=await speech.transcribe(file,msg=>{if(ticket===operation)status(msg);});if(ticket===operation)await answer(text,ticket);
}catch(e){if(ticket===operation){setPhase('error');status(e.message,true);}}
}
$('voice-sample').addEventListener('click',()=>void askRecording(null));
$('audio-upload').addEventListener('change',async e=>{
const input=e.target,file=input.files?.[0];if(!file)return;
try{await askRecording(file);}finally{input.value='';}
});
$('clear').addEventListener('click',()=>{if(!busy()){clear();status('Conversation history cleared.');}});
$('report').addEventListener('click',()=>{const data={project:'Cabin Local',webVersion:'0.4.3',date:new Date().toISOString(),runtime:engine.info(),speech:speech.config,lastGeneration:lastResult,nativeBuildValidated:false,notes:'Browser and ZeroGPU measurements, not iPhone measurements. No audio, questions or answers included.'};const url=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='cabin-local-diagnostic.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);});
window.addEventListener('pagehide',()=>{operation++;controller?.abort();mic.cancel();speech.cancel();$('audio').pause();});
void cachedModels(catalog.models).then(ids=>{cached=ids;render();});render();