tz-voice-chat 1.1.2 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +647 -148
  3. package/bin/tz-voice-chat.js +57 -0
  4. package/dist/assets/llmWorker-CmV-b4uq.js +1 -0
  5. package/dist/assets/whisperWorker-rOnua0b5.js +1 -0
  6. package/dist/index.cjs +2 -2
  7. package/dist/index.js +1557 -699
  8. package/dist/style.css +1 -1
  9. package/dist-app/assets/index-Bcmhe9G_.css +1 -0
  10. package/dist-app/assets/index-Wcfqx97N.js +41 -0
  11. package/dist-app/assets/llmWorker-CmV-b4uq.js +1 -0
  12. package/dist-app/assets/whisperWorker-rOnua0b5.js +1 -0
  13. package/dist-app/index.html +27 -0
  14. package/package.json +45 -11
  15. package/server/chat.js +91 -0
  16. package/server/elevenlabs.js +40 -0
  17. package/server/index.js +173 -92
  18. package/server/openai-stt.js +21 -0
  19. package/server/run.js +56 -0
  20. package/server/settings.js +102 -0
  21. package/server/tts.js +26 -3
  22. package/server/vendor.js +57 -0
  23. package/shared/settingsSchema.js +212 -0
  24. package/vendor/kokoro/kokoro.web.js +1 -0
  25. package/vendor/ort/ort-wasm-simd-threaded.jsep.mjs +125 -0
  26. package/vendor/ort/ort-wasm-simd-threaded.jsep.wasm +0 -0
  27. package/vendor/ort/ort-wasm-simd-threaded.mjs +70 -0
  28. package/vendor/ort/ort-wasm-simd-threaded.wasm +0 -0
  29. package/vendor/ort/ort.wasm.min.js +8 -0
  30. package/vendor/transformers/ort-wasm-simd-threaded.jsep.mjs +125 -0
  31. package/vendor/transformers/ort-wasm-simd-threaded.jsep.wasm +0 -0
  32. package/vendor/transformers/transformers.min.js +2 -0
  33. package/vendor/transformers/transformers.node.min.mjs +2 -0
  34. package/vendor/transformers/transformers.node.mjs +36472 -0
  35. package/vendor/vad/bundle.min.js +2 -0
  36. package/vendor/vad/silero_vad_legacy.onnx +0 -0
  37. package/vendor/vad/vad.worklet.bundle.min.js +1 -0
  38. package/dist/assets/llmWorker-CVEGn6yI.js +0 -1
  39. package/dist/assets/whisperWorker-BJuP9cl9.js +0 -1
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ import { startServer } from '../server/run.js';
3
+
4
+ const HELP = `tz-voice-chat — voice assistant server + web app
5
+
6
+ Usage: tz-voice-chat [options]
7
+
8
+ -p, --port <n> Port to listen on (default: $PORT or 3000)
9
+ --host <addr> Address to bind to (default: 127.0.0.1)
10
+ --settings <file> Settings file to read/write (default: ~/.tz-voice-chat/settings.json,
11
+ or $TZ_VOICE_CHAT_SETTINGS)
12
+ --cert <file> PEM certificate } serve HTTPS — browsers only allow the microphone
13
+ --key <file> PEM private key } on https:// pages and localhost (phones need this)
14
+ -h, --help Show this help
15
+
16
+ Open the printed URL and finish setup on the Settings page (chat provider and key).
17
+ Speech-to-text and text-to-speech work out of the box. Settings can also be
18
+ pre-seeded with environment variables (OPENAI_PROVIDER, OPENROUTER_API_KEY, ...).
19
+ `;
20
+
21
+ const args = process.argv.slice(2);
22
+ const opts = { port: Number(process.env.PORT) || 3000, host: '127.0.0.1' };
23
+ for (let i = 0; i < args.length; i++) {
24
+ const a = args[i];
25
+ const next = () => args[++i];
26
+ if (a === '-h' || a === '--help') { console.log(HELP); process.exit(0); }
27
+ else if (a === '-p' || a === '--port') opts.port = Number(next());
28
+ else if (a === '--host') opts.host = next();
29
+ else if (a === '--settings') opts.settingsFile = next();
30
+ else if (a === '--cert') opts.cert = next();
31
+ else if (a === '--key') opts.key = next();
32
+ else { console.error(`Unknown option: ${a}\n\n${HELP}`); process.exit(1); }
33
+ }
34
+ if (!Number.isInteger(opts.port) || opts.port < 0 || opts.port > 65535) {
35
+ console.error('Invalid --port'); process.exit(1);
36
+ }
37
+
38
+ if (Boolean(opts.cert) !== Boolean(opts.key)) { console.error('--cert and --key must be used together'); process.exit(1); }
39
+
40
+ try {
41
+ const { url, network, secure, settings, host } = await startServer(opts);
42
+ console.log(`tz-voice-chat running at ${url}`);
43
+ console.log(`Settings file: ${settings.file}`);
44
+ if (network.length) console.log(`On your network: ${network.join(' ')}`);
45
+ if (!['127.0.0.1', 'localhost', '::1'].includes(host)) {
46
+ console.warn('Warning: listening on a non-loopback address — anyone who can reach this port can read/change the saved API keys.');
47
+ if (!secure) {
48
+ console.warn('Note: other devices (phones!) load this page over plain http, and browsers then block the microphone and WebGPU.\n' +
49
+ ' The page will load and typed chat works. For voice use HTTPS: --cert/--key (e.g. made with mkcert) or a private tunnel.');
50
+ }
51
+ }
52
+ const { missing } = settings.getPublic();
53
+ if (missing.length) console.log(`Needs setup: ${missing.map(m => m.message).join(' ')} Open ${url} and use Settings.`);
54
+ } catch (err) {
55
+ console.error(err.code === 'EADDRINUSE' ? `Port ${opts.port} is already in use (try --port).` : err.message);
56
+ process.exit(1);
57
+ }
@@ -0,0 +1 @@
1
+ (function(){"use strict";const M=/\.(onnx|onnx_data|safetensors|bin|ort)$/i;function x(n,{minBytes:o=1e6,cap:t=.99}={}){const s=new Map,i=(e,a)=>a>=o&&(M.test(e)||a>=5e6);let r=0;return(e={})=>{const a=e.file||e.name;if(a&&i(a,e.total)){const c=e.status==="done"?e.total:e.loaded??(typeof e.progress=="number"?e.total*e.progress/100:0),p=s.get(a);s.set(a,{loaded:Math.max((p==null?void 0:p.loaded)??0,c),total:e.total})}else if(a&&e.status==="done"&&s.has(a)){const c=s.get(a);c.loaded=c.total}let l=0,d=0;for(const c of s.values())l+=c.loaded,d+=c.total;if(d<=0)return;const u=Math.min(t,l/d);u>r&&(r=u,n(r))}}const _="tz-voice-chat-model-cache",S=4*1024*1024;let g=null;function C(){return g||(g=new Promise((n,o)=>{const t=indexedDB.open(_,1);t.onupgradeneeded=()=>{t.result.createObjectStore("meta"),t.result.createObjectStore("chunks")},t.onsuccess=()=>n(t.result),t.onerror=()=>o(t.error)})),g}async function f(n,o,t){const s=await C();return new Promise((i,r)=>{const e=s.transaction(n,o),a=t(e.objectStore(n));e.oncomplete=()=>i(a==null?void 0:a.result),e.onerror=e.onabort=()=>r(e.error)})}const b=n=>typeof n=="string"?n:n.url,y=(n,o)=>`${n}\0${o}`;async function k(n){const o=await f("meta","readonly",t=>t.get(n));if(o)for(let t=0;t<o.chunks;t++)await f("chunks","readwrite",s=>s.delete(y(n,t)));await f("meta","readwrite",t=>t.delete(n))}function B(){return{async match(n){try{const o=b(n),t=await f("meta","readonly",r=>r.get(o));if(!t||!t.complete)return;let s=0;const i=new ReadableStream({async pull(r){if(s>=t.chunks){r.close();return}const e=await f("chunks","readonly",a=>a.get(y(o,s)));if(!e){r.error(new Error("model cache entry is incomplete"));return}r.enqueue(new Uint8Array(e)),s++}});return new Response(i,{status:200,headers:new Headers(t.headers)})}catch(o){console.warn("[tz-voice-chat] model cache read failed:",o);return}},async put(n,o){const t=b(n);try{await k(t);const s=o.body.getReader();let i=[],r=0,e=0,a=0;const l=async u=>{if(!r||!u&&r<S)return;const c=new Uint8Array(r);let p=0;for(const m of i)c.set(m,p),p+=m.length;i=[],r=0,await f("chunks","readwrite",m=>m.put(c.buffer,y(t,e))),e++};for(;;){const{done:u,value:c}=await s.read();if(u)break;i.push(c),r+=c.length,a+=c.length,await l(!1)}await l(!0);const d=[];o.headers.forEach((u,c)=>{c!=="content-encoding"&&c!=="content-length"&&d.push([c,u])}),d.push(["content-length",String(a)]),await f("meta","readwrite",u=>u.put({complete:!0,chunks:e,size:a,headers:d},t))}catch(s){console.warn("[tz-voice-chat] could not cache a model file (continuing without):",s);try{await k(t)}catch{}}}}}function H(n){return typeof caches<"u"||typeof indexedDB>"u"?!1:(n.useBrowserCache=!1,n.useCustomCache=!0,n.customCache=B(),!0)}let h=null,w=null;self.onmessage=async n=>{var i,r;const{type:o,messages:t,modelProxyUrl:s}=n.data;if(o==="init"){try{const{pipeline:e,TextStreamer:a,env:l}=await import("/vendor/transformers/transformers.min.js");l.remoteHost=s||"/api/models/",H(l),(r=(i=l==null?void 0:l.backends)==null?void 0:i.onnx)!=null&&r.wasm&&(l.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),w=a,h=await e("text-generation","HuggingFaceTB/SmolLM2-360M-Instruct",{dtype:"q4",progress_callback:x(d=>self.postMessage({type:"progress",progress:d}))}),self.postMessage({type:"ready"})}catch(e){self.postMessage({type:"error",message:String((e==null?void 0:e.message)??e)})}return}if(o==="generate"){if(!h||!w){self.postMessage({type:"done"});return}try{const e=new w(h.tokenizer,{skip_prompt:!0,skip_special_tokens:!0,callback_function:a=>{self.postMessage({type:"token",text:a})}});await h(t,{max_new_tokens:150,do_sample:!1,streamer:e}),self.postMessage({type:"done"})}catch(e){console.error("[LLM worker] generate error:",e),self.postMessage({type:"done"})}}}})();
@@ -0,0 +1 @@
1
+ (function(){"use strict";const x=/\.(onnx|onnx_data|safetensors|bin|ort)$/i;function M(n,{minBytes:a=1e6,cap:t=.99}={}){const c=new Map,l=(e,o)=>o>=a&&(x.test(e)||o>=5e6);let s=0;return(e={})=>{const o=e.file||e.name;if(o&&l(o,e.total)){const r=e.status==="done"?e.total:e.loaded??(typeof e.progress=="number"?e.total*e.progress/100:0),u=c.get(o);c.set(o,{loaded:Math.max((u==null?void 0:u.loaded)??0,r),total:e.total})}else if(o&&e.status==="done"&&c.has(o)){const r=c.get(o);r.loaded=r.total}let f=0,d=0;for(const r of c.values())f+=r.loaded,d+=r.total;if(d<=0)return;const i=Math.min(t,f/d);i>s&&(s=i,n(s))}}const P="tz-voice-chat-model-cache",C=4*1024*1024;let m=null;function S(){return m||(m=new Promise((n,a)=>{const t=indexedDB.open(P,1);t.onupgradeneeded=()=>{t.result.createObjectStore("meta"),t.result.createObjectStore("chunks")},t.onsuccess=()=>n(t.result),t.onerror=()=>a(t.error)})),m}async function p(n,a,t){const c=await S();return new Promise((l,s)=>{const e=c.transaction(n,a),o=t(e.objectStore(n));e.oncomplete=()=>l(o==null?void 0:o.result),e.onerror=e.onabort=()=>s(e.error)})}const g=n=>typeof n=="string"?n:n.url,w=(n,a)=>`${n}\0${a}`;async function b(n){const a=await p("meta","readonly",t=>t.get(n));if(a)for(let t=0;t<a.chunks;t++)await p("chunks","readwrite",c=>c.delete(w(n,t)));await p("meta","readwrite",t=>t.delete(n))}function W(){return{async match(n){try{const a=g(n),t=await p("meta","readonly",s=>s.get(a));if(!t||!t.complete)return;let c=0;const l=new ReadableStream({async pull(s){if(c>=t.chunks){s.close();return}const e=await p("chunks","readonly",o=>o.get(w(a,c)));if(!e){s.error(new Error("model cache entry is incomplete"));return}s.enqueue(new Uint8Array(e)),c++}});return new Response(l,{status:200,headers:new Headers(t.headers)})}catch(a){console.warn("[tz-voice-chat] model cache read failed:",a);return}},async put(n,a){const t=g(n);try{await b(t);const c=a.body.getReader();let l=[],s=0,e=0,o=0;const f=async i=>{if(!s||!i&&s<C)return;const r=new Uint8Array(s);let u=0;for(const h of l)r.set(h,u),u+=h.length;l=[],s=0,await p("chunks","readwrite",h=>h.put(r.buffer,w(t,e))),e++};for(;;){const{done:i,value:r}=await c.read();if(i)break;l.push(r),s+=r.length,o+=r.length,await f(!1)}await f(!0);const d=[];a.headers.forEach((i,r)=>{r!=="content-encoding"&&r!=="content-length"&&d.push([r,i])}),d.push(["content-length",String(o)]),await p("meta","readwrite",i=>i.put({complete:!0,chunks:e,size:o,headers:d},t))}catch(c){console.warn("[tz-voice-chat] could not cache a model file (continuing without):",c);try{await b(t)}catch{}}}}}function B(n){return typeof caches<"u"||typeof indexedDB>"u"?!1:(n.useBrowserCache=!1,n.useCustomCache=!0,n.customCache=W(),!0)}let y=null,k=Promise.resolve();self.onmessage=async n=>{var c,l;const{type:a,audio:t}=n.data;if(a==="init"){const s=n.data.model||"onnx-community/whisper-tiny.en",e=n.data.device||"wasm",o=e==="cpu"?"wasm":e,f=n.data.modelProxyUrl||"/api/models/";let d=n.data.dtype||"q8";o==="webgpu"&&(d==="q4"||d==="q8")&&(console.warn(`[Whisper worker] dtype "${d}" not supported on WebGPU — using "fp32".`),d="fp32");try{const{pipeline:i,env:r}=await import("/vendor/transformers/transformers.min.js");r.remoteHost=f,B(r),(l=(c=r==null?void 0:r.backends)==null?void 0:c.onnx)!=null&&l.wasm&&(r.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),y=await i("automatic-speech-recognition",s,{dtype:d,device:o,progress_callback:M(u=>self.postMessage({type:"progress",progress:u}))}),self.postMessage({type:"ready"})}catch(i){self.postMessage({type:"error",message:String((i==null?void 0:i.message)??i)})}return}a==="transcribe"&&(console.log("[Whisper worker] transcribe — samples:",t==null?void 0:t.length),k=k.then(async()=>{var s;try{if(!y){console.warn("[Whisper worker] pipeline not ready, dropping segment"),self.postMessage({type:"transcript",text:""});return}const e=await y(t),o=(e==null?void 0:e.text)??((s=e==null?void 0:e[0])==null?void 0:s.text)??"";self.postMessage({type:"transcript",text:o})}catch(e){console.error("[Whisper worker] transcription error:",e),self.postMessage({type:"transcript",text:""})}}))}})();
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Pe=Object.create;var xe=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,Ge=Object.prototype.hasOwnProperty;var Be=(e,s,r,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let t of Ue(s))!Ge.call(e,t)&&t!==r&&xe(e,t,{get:()=>s[t],enumerable:!(i=Oe(s,t))||i.enumerable});return e};var Se=(e,s,r)=>(r=e!=null?Pe(Ke(e)):{},Be(s||!e||!e.__esModule?xe(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react"),a=require("react/jsx-runtime");var Z=typeof document<"u"?document.currentScript:null;const he=60,ne=200;function _e(){let e="",s=!0;function r(t,o,n){t.push(o),e=n,s=!1}function i(){const t=[];for(;;){const o=/([.!?]{1,3})(\s|$)/.exec(e);if(o){const n=e.slice(0,o.index+o[0].length).trim();if(n.length>=10){r(t,n,e.slice(o.index+o[0].length));continue}}if(s){if(e.length>=25){const n=/[,;:—–](\s|$)/.exec(e);if(n){const u=e.slice(0,n.index+n[0].length).trim();if(u.length>=20){r(t,u,e.slice(n.index+n[0].length));continue}}}if(e.length>=he){const n=e.lastIndexOf(" ",he-1),u=n>10?n:he;r(t,e.slice(0,u).trim(),e.slice(u).trimStart());continue}}else if(e.length>=ne){const n=e.slice(0,ne),u=Math.max(n.lastIndexOf(", "),n.lastIndexOf("; "),n.lastIndexOf(": ")),c=u>ne/2?u+1:n.lastIndexOf(" ")>10?n.lastIndexOf(" "):ne;r(t,e.slice(0,c).trim(),e.slice(c).trimStart());continue}break}return t}return{write(t){return e+=t,i()},flush(){const t=e.trim();return e="",t}}}async function Fe(e,{dtype:s="q8",device:r="cpu",modelProxyUrl:i="/api/models/"}={}){var d,f;const{env:t}=await import("/vendor/transformers/transformers.min.js");t.remoteHost=i,(f=(d=t==null?void 0:t.backends)==null?void 0:d.onnx)!=null&&f.wasm&&(t.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),t!=null&&t.onnx&&(t.onnx.logSeverityLevel=3);const o=await import("/vendor/kokoro/kokoro.web.js"),{KokoroTTS:n}=o;let u=s;r==="webgpu"&&(s==="q4"||s==="q8")&&(console.warn(`[modelLoader] dtype "${s}" not supported on WebGPU — using "fp32".`),u="fp32");let c=0;const h=w=>{typeof(w==null?void 0:w.progress)=="number"&&(c=Math.max(c,w.progress/100),e==null||e("kokoro",Math.min(.99,c)))};async function l(w,g){return n.from_pretrained("onnx-community/Kokoro-82M-ONNX",{dtype:g,device:w,progress_callback:h})}let v;try{v=await l(r,u)}catch(w){if(r!=="wasm")console.warn(`[modelLoader] Kokoro on "${r}" failed (${w==null?void 0:w.message}) — falling back to WASM.`),c=0,v=await l("wasm",s);else throw w}return e==null||e("kokoro",1),{kokoro:v}}function re(e,s,{threshold:r=.01,padMs:i=25}={}){const{numberOfChannels:t,length:o,sampleRate:n}=s;let u=o,c=-1;for(let f=0;f<t;f++){const w=s.getChannelData(f);for(let g=0;g<o;g++)if(Math.abs(w[g])>r){g<u&&(u=g);break}for(let g=o-1;g>=0;g--)if(Math.abs(w[g])>r){g>c&&(c=g);break}}if(c<u)return s;const h=Math.round(i/1e3*n),l=Math.max(0,u-h),v=Math.min(o,c+1+h);if(l===0&&v===o)return s;const d=e.createBuffer(t,v-l,n);for(let f=0;f<t;f++)d.copyToChannel(s.getChannelData(f).subarray(l,v),f);return d}function We(e,{voice:s="af_bella",speed:r=1,onPlayStart:i}={}){const t=new AudioContext,o=[];let n=!1,u=null,c=!1;async function h(d){if(d instanceof AudioBuffer)return re(t,d);const f=(d==null?void 0:d.audio)??d;if(f instanceof ArrayBuffer)return re(t,await t.decodeAudioData(f.slice(0)));if(f instanceof Float32Array){const w=(d==null?void 0:d.samplingRate)??24e3,g=t.createBuffer(1,f.length,w);return g.copyToChannel(f,0),re(t,g)}throw new Error("Unsupported TTS payload")}async function l(d){await t.resume();const f=t.createBufferSource();return f.buffer=d,f.connect(t.destination),new Promise(w=>{f.onended=()=>{u===f&&(u=null),w()},u=f,f.start(),c||(c=!0,i==null||i())})}async function v(){if(!n){for(n=!0;o.length>0;){const d=o.shift();try{const f=await d;f&&await l(f)}catch(f){console.error("[TtsQueue]",f)}}n=!1}}return{enqueue(d){o.push(e.generate(d,{voice:s,speed:r}).then(h)),v()},cancel(){if(o.length=0,c=!1,u){try{u.stop()}catch{}u=null}},async finished(){for(;n||o.length>0;)await new Promise(d=>setTimeout(d,200))}}}function He({voice:e="",speed:s=1,onPlayStart:r,url:i="/api/tts"}={}){const t=new AudioContext,o=[];let n=!1,u=null,c=!1;async function h(d){const f={text:d};e&&(f.voice=e),s!==1&&(f.speed=s);const w=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});if(!w.ok)throw new Error(`TTS ${w.status}: ${await w.text()}`);return re(t,await t.decodeAudioData(await w.arrayBuffer()))}async function l(d){await t.resume();const f=t.createBufferSource();return f.buffer=d,f.connect(t.destination),new Promise(w=>{f.onended=()=>{u===f&&(u=null),w()},u=f,f.start(),c||(c=!0,r==null||r())})}async function v(){if(!n){for(n=!0;o.length>0;){const d=o.shift();try{await l(await d)}catch(f){console.error("[ServerTTS]",f)}}n=!1}}return{enqueue(d){d!=null&&d.trim()&&(o.push(h(d)),v())},cancel(){if(o.length=0,u){try{u.stop()}catch{}u=null}c=!1},async finished(){for(;n||o.length>0;)await new Promise(d=>setTimeout(d,100))}}}function Qe({voice:e="",rate:s=1,pitch:r=1,onPlayStart:i}={}){const t=[];let o=!1,n=!1;function u(){return e?speechSynthesis.getVoices().find(l=>l.name===e||l.voiceURI===e)??null:null}function c(){if(o||t.length===0)return;o=!0;const h=t.shift(),l=new SpeechSynthesisUtterance(h),v=u();v&&(l.voice=v),l.rate=s,l.pitch=r,l.onstart=()=>{n||(n=!0,i==null||i())},l.onend=()=>{o=!1,c()},l.onerror=d=>{console.error("[WebSpeech TTS] error",d.error),o=!1,c()},speechSynthesis.speak(l)}return{enqueue(h){h!=null&&h.trim()&&(t.push(h),c())},cancel(){t.length=0,speechSynthesis.cancel(),o=!1,n=!1},async finished(){for(;o||t.length>0;)await new Promise(h=>setTimeout(h,100))}}}async function Ze({onSpeechStart:e,onSpeechEnd:s,onError:r,deviceId:i}){try{const{MicVAD:t}=window.vad;return await t.new({model:"legacy",baseAssetPath:"/vendor/vad/",onnxWASMBasePath:"/vendor/ort/",additionalAudioConstraints:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!1,...i?{deviceId:{exact:i}}:{}},onSpeechStart:()=>e==null?void 0:e(),onSpeechEnd:n=>{console.log("[VAD] onSpeechEnd — samples:",n==null?void 0:n.length),s==null||s(n)},onVADMisfire:()=>{},negativeSpeechThreshold:.25,positiveSpeechThreshold:.5,redemptionFrames:4,minSpeechFrames:3,preSpeechPadFrames:1})}catch(t){throw r==null||r("VAD initialization failed. Falling back to manual microphone capture."),t}}const j={IDLE:"idle",LISTENING:"listening",TRANSCRIBING:"transcribing",THINKING:"thinking",SPEAKING:"speaking"},Je="You are a friendly assistant for quick voice interactions. Provide answers only in the form of a single concise sentence, without any introductory phrases. Don't use any formatting, markdown, emoji, or code blocks — just plain text. The answers will be spoken aloud, so keep them short and natural.";function Me({processInput:e,systemPrompt:s=Je,ttsProvider:r="server-kokoro",ttsVoice:i="af_bella",ttsSpeed:t=1,ttsServerUrl:o="/api/tts",ttsSpeechRate:n=1,ttsSpeechPitch:u=1,whisperModel:c="onnx-community/whisper-tiny.en",whisperDtype:h="q8",whisperDevice:l="cpu",kokoroDtype:v="q8",kokoroBrowserDevice:d="wasm",modelProxyUrl:f="/api/models/"}={}){const[w,g]=p.useState(j.IDLE),[N,R]=p.useState(!0),[I,x]=p.useState({whisper:0,kokoro:0}),[z,T]=p.useState(null),[q,$]=p.useState([]),[S,E]=p.useState(null),[L,P]=p.useState(!1),[k,b]=p.useState(""),[K,ae]=p.useState([]),[ie,Y]=p.useState(null),W=p.useRef(j.IDLE),H=p.useRef(!1),V=p.useRef(null),G=p.useRef(null),O=p.useRef(null),B=p.useRef(null),oe=p.useRef(null),ce=p.useRef(null),X=p.useRef([{role:"system",content:s}]),le=p.useRef(e),me=p.useRef(0),we=p.useRef({id:null,enqueuedAt:null,ttsMs:null}),Re=p.useRef(1);p.useEffect(()=>{W.current=w},[w]),p.useEffect(()=>{H.current=L},[L]),p.useEffect(()=>{le.current=e},[e]),p.useEffect(()=>{async function _(){try{const A=await navigator.mediaDevices.enumerateDevices();ae(A.filter(y=>y.kind==="audioinput"))}catch{}}return _(),navigator.mediaDevices.addEventListener("devicechange",_),()=>navigator.mediaDevices.removeEventListener("devicechange",_)},[L]),p.useEffect(()=>{let _=!1;async function A(){try{const y=()=>{var M;const m=we.current;m.enqueuedAt!=null&&m.ttsMs==null&&(m.ttsMs=Math.round(performance.now()-m.enqueuedAt),m.id!=null&&ze(m.id,{timings:{ttsMs:m.ttsMs}})),r==="webspeech"&&((M=G.current)==null||M.pause())};if(r==="webspeech")V.current=Qe({voice:i,rate:n,pitch:u,onPlayStart:y}),x(m=>({...m,kokoro:1}));else if(r==="kokoro"){const{kokoro:m}=await Fe((M,F)=>x(U=>({...U,[M]:F})),{dtype:v,device:d,modelProxyUrl:f});if(_)return;V.current=We(m,{voice:i,speed:t,onPlayStart:y})}else V.current=He({voice:i,speed:t,onPlayStart:y,url:o}),x(m=>({...m,kokoro:1}));if(_)return;B.current=new Worker(new URL("./assets/whisperWorker-BJuP9cl9.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Z&&Z.tagName.toUpperCase()==="SCRIPT"&&Z.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),B.current.onmessage=m=>{m.data.type==="transcript"?ye(m.data.text,{transcribeMs:Math.round(performance.now()-me.current)}):m.data.type==="progress"?x(M=>({...M,whisper:m.data.progress})):m.data.type==="ready"?(x(M=>({...M,whisper:1})),R(!1)):m.data.type==="error"&&(T(`Whisper: ${m.data.message}`),R(!1))},B.current.onerror=()=>{T("Model load failed. Check WebGPU/WASM browser support."),R(!1)},B.current.postMessage({type:"init",model:c,dtype:h,device:l,modelProxyUrl:f})}catch(y){_||(T("Initialisation failed: "+((y==null?void 0:y.message)??String(y))),R(!1))}}return A(),()=>{var y;_=!0,(y=B.current)==null||y.terminate()}},[r,c,h,l,v,d]);function ge(_,A,y){const m=Re.current++;return $(M=>[...M,{id:m,role:_,content:A,timings:y,time:new Date().toISOString()}]),m}function ze(_,{timings:A}){$(y=>y.map(m=>m.id===_?{...m,timings:{...m.timings,...A}}:m))}async function ye(_,{transcribeMs:A}={}){if(!(_!=null&&_.trim())){g(H.current?j.LISTENING:j.IDLE);return}g(j.THINKING),ge("user",_,A!=null?{transcribeMs:A}:void 0);const y=[...X.current,{role:"user",content:_}];X.current=y,await $e(_,y)}async function $e(_,A){var y,m,M,F;(y=O.current)==null||y.abort(),O.current=new AbortController,(m=V.current)==null||m.cancel();try{if(!le.current)throw new Error("processInput is not provided");const U=_e();let ee="",ue=!1,fe=null;const Ve=performance.now(),Q={id:null,enqueuedAt:null,ttsMs:null};we.current=Q;const ve=te=>{var de;Q.enqueuedAt==null&&(Q.enqueuedAt=performance.now()),(de=V.current)==null||de.enqueue(te)};E("");for await(const te of le.current(_,A,O.current.signal))fe==null&&(fe=Math.round(performance.now()-Ve)),ee+=te,E(ee),U.write(te).forEach(Ce=>{ue||(ue=!0,g(j.SPEAKING)),ve(Ce)});const be=U.flush();be&&(ue||g(j.SPEAKING),ve(be)),Q.id=ge("assistant",ee,{thinkMs:fe,...Q.ttsMs!=null?{ttsMs:Q.ttsMs}:{}}),E(null),X.current=[...X.current,{role:"assistant",content:ee}],await((M=V.current)==null?void 0:M.finished()),r==="webspeech"&&((F=G.current)==null||F.start())}catch(U){E(null),U.name!=="AbortError"&&T(U.message||"Processing failed.")}finally{g(H.current?j.LISTENING:j.IDLE)}}async function Ee(){var _,A;T(null),W.current===j.SPEAKING&&((_=V.current)==null||_.cancel(),(A=O.current)==null||A.abort());try{g(j.LISTENING),P(!0);try{const y=await navigator.mediaDevices.getUserMedia({audio:k?{deviceId:{exact:k}}:!0,video:!1});ce.current=y;const m=new AudioContext;oe.current=m;const M=m.createAnalyser();M.fftSize=256,m.createMediaStreamSource(y).connect(M),Y(M)}catch(y){console.warn("[TZVoiceChat] waveform analyser unavailable:",y)}G.current=await Ze({onSpeechStart:()=>{var y,m;r==="webspeech"&&W.current===j.SPEAKING||(W.current===j.SPEAKING&&((y=V.current)==null||y.cancel(),(m=O.current)==null||m.abort()),g(j.LISTENING))},onSpeechEnd:y=>{var m;r==="webspeech"&&W.current===j.SPEAKING||(g(j.TRANSCRIBING),me.current=performance.now(),(m=B.current)==null||m.postMessage({type:"transcribe",audio:y},[y.buffer]))},onError:y=>{T(y),g(j.IDLE)},deviceId:k||void 0})}catch(y){console.error("[TZVoiceChat] startListening failed:",y),T("Microphone access failed. Allow audio permissions and refresh."),g(j.IDLE),P(!1)}}function De(){var _,A,y,m,M;P(!1),(_=G.current)==null||_.destroy(),G.current=null,(A=ce.current)==null||A.getTracks().forEach(F=>F.stop()),ce.current=null,(y=oe.current)==null||y.close(),oe.current=null,Y(null),(m=V.current)==null||m.cancel(),(M=O.current)==null||M.abort(),g(j.IDLE)}function qe(_){var M;if(!(_!=null&&_.trim()))return;g(j.SPEAKING);const A=_e(),y=A.write(_),m=A.flush();[...y,...m?[m]:[]].forEach(F=>{var U;return(U=V.current)==null?void 0:U.enqueue(F)}),(M=V.current)==null||M.finished().then(()=>{g(H.current?j.LISTENING:j.IDLE)})}return{status:w,loading:N,progress:I,error:z,transcript:q,streamingMessage:S,micEnabled:L,startListening:Ee,stopListening:De,speak:qe,submitText:ye,liveAnalyser:ie,devices:K,selectedMicId:k,setSelectedMicId:b}}function je(e){const s=e.replace("#",""),r=s.length===3?s.split("").map(i=>i+i).join(""):s;return[parseInt(r.slice(0,2),16),parseInt(r.slice(2,4),16),parseInt(r.slice(4,6),16)]}function Ye(e,s,r){e/=255,s/=255,r/=255;const i=Math.max(e,s,r),t=Math.min(e,s,r),o=(i+t)/2;if(i===t)return[0,0,o*100];const n=i-t,u=o>.5?n/(2-i-t):n/(i+t);let c;switch(i){case e:c=((s-r)/n+(s<r?6:0))/6;break;case s:c=((r-e)/n+2)/6;break;default:c=((e-s)/n+4)/6}return[c*360,u*100,o*100]}function Xe(e,s,r){s/=100,r/=100;const i=n=>(n+e/30)%12,t=s*Math.min(r,1-r),o=n=>r-t*Math.max(-1,Math.min(i(n)-3,Math.min(9-i(n),1)));return[Math.round(o(0)*255),Math.round(o(8)*255),Math.round(o(4)*255)]}function C(e,s){const[r,i,t]=je(e),[o,n,u]=Ye(r,i,t),[c,h,l]=Xe(o,n,Math.max(0,Math.min(100,u+s)));return`rgb(${c}, ${h}, ${l})`}function D(e,s){const[r,i,t]=je(e);return`rgba(${r}, ${i}, ${t}, ${s})`}function J(e,s){return e.replace("rgb(","rgba(").replace(")",`, ${s})`)}const se=10;function et({analyser:e}){const s=p.useRef(null),r=p.useRef(null);return p.useEffect(()=>{if(cancelAnimationFrame(r.current),!e)return;const i=s.current;if(!i)return;const t=i.getContext("2d"),o=e.frequencyBinCount,n=new Uint8Array(o),u=Math.max(1,Math.floor(o/se)),c=getComputedStyle(i),h=+c.getPropertyValue("--bar-hue"),l=+c.getPropertyValue("--bar-hue-range"),v=+c.getPropertyValue("--bar-sat"),d=+c.getPropertyValue("--bar-lit"),f=+c.getPropertyValue("--bar-lit-range"),w=()=>{r.current=requestAnimationFrame(w),e.getByteFrequencyData(n);const g=i.width,N=i.height;t.clearRect(0,0,g,N);const R=(g-(se-1)*2)/se;for(let I=0;I<se;I++){const x=n[I*u]/255,z=Math.max(3,x*N*.88);t.fillStyle=`hsl(${h+x*l}, ${v}%, ${d+x*f}%)`,t.beginPath(),t.roundRect(I*(R+2),(N-z)/2,R,z,[2]),t.fill()}};return w(),()=>cancelAnimationFrame(r.current)},[e]),a.jsx("canvas",{ref:s,width:55,height:35,className:"ai-btn__canvas"})}function Te({status:e="idle",active:s=!1,loading:r=!1,analyser:i=null,onToggle:t,devices:o=[],selectedMicId:n="",onDeviceChange:u,inputData:c="",sendData:h,accentColor:l="#f97316",uiColor:v="#64748b",size:d=70,barHue:f=25,barHueRange:w=20,barSat:g=88,barLit:N=65,barLitRange:R=20}){var P;const[I,x]=p.useState(!1),z=p.useRef(null);p.useEffect(()=>{if(!I)return;function k(b){var K;(K=z.current)!=null&&K.contains(b.target)||x(!1)}return document.addEventListener("pointerdown",k),()=>document.removeEventListener("pointerdown",k)},[I]);function T(k){u==null||u(k),x(!1)}const q=p.useMemo(()=>{const k=C(l,-8),b=C(l,-15),K=C(l,-22),ae=C(l,-30),ie=C(l,-42),Y=C(l,8),W=C(l,20),H=C(l,30),V=C(v,-22),G=C(v,-30),O=C(v,18),B=C(v,37);return{"--tz-size":`${d}px`,"--tz-a":l,"--tz-a-d8":k,"--tz-a-d15":b,"--tz-a-d22":K,"--tz-a-d30":ae,"--tz-a-d42":ie,"--tz-a-l8":Y,"--tz-a-l20":W,"--tz-a-l30":H,"--tz-a-25":D(l,.25),"--tz-a-28":D(l,.28),"--tz-a-30":D(l,.3),"--tz-a-32":D(l,.32),"--tz-a-34":D(l,.34),"--tz-a-35":D(l,.35),"--tz-a-38":D(l,.38),"--tz-a-45":D(l,.45),"--tz-a-50":D(l,.5),"--tz-a-55":D(l,.55),"--tz-a-60":D(l,.6),"--tz-a-65":D(l,.65),"--tz-a-68":D(l,.68),"--tz-u":v,"--tz-u-d22":V,"--tz-u-d30":G,"--tz-u-l18":O,"--tz-u-l37":B,"--tz-u-30":D(v,.3),"--tz-u-55":D(v,.55),"--tz-u-d30-a85":J(G,.85),"--tz-u-l18-a18":J(O,.18),"--tz-u-l18-a20":J(O,.2),"--tz-u-l18-a32":J(O,.32),"--tz-u-d22-a90":J(V,.9),"--bar-hue":f,"--bar-hue-range":w,"--bar-sat":g,"--bar-lit":N,"--bar-lit-range":R}},[l,v,d,f,w,g,N,R]),$=((P=o.find(k=>k.deviceId===n))==null?void 0:P.label)||(n?`Mic ${n.slice(0,6)}…`:"Default mic"),S=c.trim().length>0,E=S?"ready":s?e:"off";let L;return S?L=a.jsx("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:a.jsx("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})}):!s||e==="idle"?L=a.jsxs("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[a.jsx("path",{fillOpacity:"0.52",d:"M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4zm6 10a1 1 0 0 1 2 0 8 8 0 0 1-7 7.94V21h2a1 1 0 0 1 0 2H9a1 1 0 0 1 0-2h2v-2.06A8 8 0 0 1 4 11a1 1 0 0 1 2 0 6 6 0 0 0 12 0z"}),a.jsx("path",{fill:"white",fillOpacity:"0.98",d:"M14.5 0L15.65 3.45L19.1 4.6L15.65 5.75L14.5 9.2L13.35 5.75L9.9 4.6L13.35 3.45Z"}),a.jsx("path",{fill:"white",fillOpacity:"0.88",d:"M19 8.62L19.75 10.75L21.88 11.5L19.75 12.25L19 14.38L18.25 12.25L16.12 11.5L18.25 10.75Z"})]}):e==="listening"?L=a.jsx(et,{analyser:i}):e==="transcribing"?L=a.jsx("div",{className:"ai-btn__bars ai-btn__bars--transcribing",children:Array.from({length:7},(k,b)=>a.jsx("span",{style:{animationDelay:`${b*.1}s`}},b))}):e==="thinking"?L=a.jsxs("div",{className:"ai-btn__dots",children:[a.jsx("span",{}),a.jsx("span",{style:{animationDelay:"0.18s"}}),a.jsx("span",{style:{animationDelay:"0.36s"}})]}):e==="speaking"&&(L=a.jsx("div",{className:"ai-btn__bars ai-btn__bars--speaking",children:Array.from({length:7},(k,b)=>a.jsx("span",{style:{animationDelay:`${b*.11}s`}},b))})),a.jsxs("div",{className:"ai-btn-root",style:q,children:[a.jsxs("div",{className:`ai-btn-rings ai-btn-rings--${E}`,"aria-hidden":"true",children:[a.jsx("span",{className:"ai-ring ai-ring--1"}),a.jsx("span",{className:"ai-ring ai-ring--2"})]}),a.jsxs("button",{className:`ai-btn ai-btn--${E}`,disabled:r,onClick:S?()=>h==null?void 0:h(c):t,"aria-label":S?"Send message":s?"Stop assistant":"Start assistant","aria-pressed":S?void 0:s,children:[L,s&&!S&&a.jsx("span",{className:"ai-btn__hover-stop","aria-hidden":"true",children:"■"})]}),a.jsxs("div",{className:`ai-mic-sel${I?" open":""}`,ref:z,children:[a.jsxs("button",{className:"ai-mic-sel__trigger",onClick:()=>x(k=>!k),title:"Change microphone","aria-label":"Change microphone","aria-expanded":I,children:[a.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[a.jsx("path",{d:"M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4z"}),a.jsx("path",{d:"M5 11a1 1 0 0 0-2 0 9 9 0 0 0 8 8.94V22H9a1 1 0 0 0 0 2h6a1 1 0 0 0 0-2h-2v-2.06A9 9 0 0 0 21 11a1 1 0 0 0-2 0 7 7 0 0 1-14 0z"})]}),a.jsx("span",{className:"ai-mic-sel__label",children:$}),a.jsx("svg",{className:`ai-mic-sel__caret${I?" open":""}`,width:"9",height:"9",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:a.jsx("path",{d:"M12 16L4 8h16l-8 8z"})})]}),I&&a.jsxs("ul",{className:"ai-mic-sel__menu",role:"listbox","aria-label":"Select microphone",children:[a.jsx("li",{role:"option",className:`ai-mic-sel__option${n===""?" selected":""}`,onClick:()=>T(""),"aria-selected":n==="",children:"Default microphone"}),o.map(k=>a.jsx("li",{role:"option",className:`ai-mic-sel__option${n===k.deviceId?" selected":""}`,onClick:()=>T(k.deviceId),"aria-selected":n===k.deviceId,children:k.label||`Microphone ${k.deviceId.slice(0,8)}`},k.deviceId))]})]})]})}async function Ae(e,s,r="/api/chat"){var u;const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},signal:s,body:JSON.stringify({messages:e})});if(!i.ok){const c=await i.text();throw new Error(`Server error: ${i.status} ${c}`)}const t=(u=i.body)==null?void 0:u.getReader();if(!t){const c=await i.json();return{stream:async function*(){yield c.text}}}const o=new TextDecoder;let n="";return{stream:async function*(){var h,l,v;let c="";for(;;){const{value:d,done:f}=await t.read();if(f)break;n+=o.decode(d,{stream:!0});const w=n.split(`
2
- `);n=w.pop();for(const g of w){const N=g.trim();if(!N.startsWith("data:"))continue;const R=N.slice(5).trimStart();if(R==="[DONE]")return;try{const x=(v=(l=(h=JSON.parse(R).choices)==null?void 0:h[0])==null?void 0:l.delta)==null?void 0:v.content;x&&(c&&/\w/.test(c)&&/\w/.test(x[0])&&(yield" "),c=x[x.length-1],yield x)}catch{}}}}}}function Ne(e,s,r){return{stream:async function*(){const i=[];let t=null,o=!1,n="";const u=({data:h})=>{h.type==="token"?(i.push(h.text),t==null||t(),t=null):h.type==="done"&&(o=!0,t==null||t(),t=null)},c=()=>{o=!0,t==null||t(),t=null};e.addEventListener("message",u),r==null||r.addEventListener("abort",c),e.postMessage({type:"generate",messages:s});try{for(;!o||i.length>0;)if(i.length>0){const h=i.shift();n&&/\w/.test(n)&&/\w/.test(h[0])&&(yield" "),n=h[h.length-1],yield h}else await new Promise(h=>{t=h})}finally{e.removeEventListener("message",u),r==null||r.removeEventListener("abort",c)}}}}function Ie({apiBase:e="/api",systemPrompt:s}={}){const[r,i]=p.useState(!0),[t,o]=p.useState(0),[n,u]=p.useState(""),[c,h]=p.useState({}),[l,v]=p.useState(null),[d,f]=p.useState({}),w=p.useRef(null),g=p.useRef(null);p.useEffect(()=>{let x=!1;async function z(){let T=!0,q={};try{const S=await(await fetch(`${e}/config`)).json();T=S.hasApiKey,v(S),q={ttsProvider:S.ttsProvider||"server-kokoro",ttsVoice:S.ttsProvider==="openai"?S.openaiTtsVoice||"alloy":S.kokoroVoice||"af_bella",ttsServerUrl:`${e}/tts`,ttsSpeed:S.kokoroSpeed??1,ttsSpeechRate:S.webSpeechRate??1,ttsSpeechPitch:S.webSpeechPitch??1,whisperModel:S.whisperModel||"onnx-community/whisper-tiny.en",whisperDtype:S.whisperDtype||"q8",whisperDevice:S.whisperDevice||"cpu",kokoroDtype:S.kokoroDtype||"q8",kokoroBrowserDevice:S.kokoroBrowserDevice||"wasm",modelProxyUrl:`${e}/models/`}}catch{q={ttsProvider:"server-kokoro",ttsServerUrl:`${e}/tts`,modelProxyUrl:`${e}/models/`}}if(!x)if(T)w.current=async function*($,S,E){const{stream:L}=await Ae(S,E,`${e}/chat`);yield*L()},h(q),i(!1);else{u("No API key — using SmolLM2-360M-Instruct locally in your browser.");const $=new Worker(new URL("./assets/llmWorker-CVEGn6yI.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Z&&Z.tagName.toUpperCase()==="SCRIPT"&&Z.src||new URL("index.cjs",document.baseURI).href),{type:"module"});g.current=$,$.onmessage=S=>{S.data.type==="progress"?o(S.data.progress??0):S.data.type==="ready"?(o(1),w.current=async function*(E,L,P){const{stream:k}=Ne($,L,P);yield*k()},h(q),i(!1)):S.data.type==="error"&&i(!1)},$.onerror=()=>i(!1),$.postMessage({type:"init",modelProxyUrl:`${e}/models/`})}}return z(),()=>{var T;x=!0,(T=g.current)==null||T.terminate()}},[e]);const N=Me({processInput:async function*(x,z,T){w.current&&(yield*w.current(x,z,T))},...s?{systemPrompt:s}:{},...c});p.useEffect(()=>{let x=!1;async function z(){const q={};typeof performance<"u"&&performance.memory&&(q.browser=performance.memory.usedJSHeapSize);try{const $=await fetch(`${e}/stats`);$.ok&&(q.server=(await $.json()).rss)}catch{}x||f(q)}z();const T=setInterval(z,3e3);return()=>{x=!0,clearInterval(T)}},[e]);const{micEnabled:R,stopListening:I}=N;return p.useEffect(()=>{if(!R)return;const x=z=>{z.key==="Escape"&&I()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[R,I]),{chat:N,info:l,config:c,memory:d,llmProgress:t,note:n,loading:N.loading||r}}const Le=(e,s)=>e==="webgpu"&&(s==="q4"||s==="q8")?"fp32":s,pe=e=>e>=1e3?`${(e/1e3).toFixed(1)} s`:`${e} ms`,ke=e=>`${(e/1048576).toFixed(0)} MB`;function tt(e){switch(e.ttsProvider){case"openai":return`OpenAI · ${e.openaiTtsModel} · ${e.ttsVoice}`;case"webspeech":return`Web Speech API · rate ${e.ttsSpeechRate} · pitch ${e.ttsSpeechPitch}`;case"server-kokoro":return`Kokoro (server) · ${e.ttsVoice} · ${e.kokoroDtype}/${e.kokoroDevice}`;default:return`Kokoro (browser) · ${e.ttsVoice} · ${Le(e.kokoroBrowserDevice,e.kokoroDtype)}/${e.kokoroBrowserDevice}`}}const nt=e=>e.replace(/\b\w/g,s=>s.toUpperCase());function st({apiBase:e="/api",title:s="Voice Assistant",showInfo:r=!0,systemPrompt:i,className:t=""}={}){const{chat:o,info:n,config:u,memory:c,llmProgress:h,note:l,loading:v}=Ie({apiBase:e,systemPrompt:i}),{status:d,progress:f,error:w,transcript:g,streamingMessage:N,micEnabled:R,startListening:I,stopListening:x,submitText:z,liveAnalyser:T,devices:q,selectedMicId:$,setSelectedMicId:S}=o,[E,L]=p.useState(""),P=p.useRef(null);p.useEffect(()=>{var b;(b=P.current)==null||b.scrollIntoView({behavior:N!==null?"auto":"smooth"})},[g,N]);const k=n&&u.whisperDevice&&[["STT",`Whisper · ${(u.whisperModel||n.whisperModel).split("/").pop()} · ${Le(u.whisperDevice,u.whisperDtype)}/${u.whisperDevice}`],["TTS",tt({...n,...u})],["Chat",n.hasApiKey?`${n.chatProvider} · ${n.chatModel}`:"SmolLM2-360M-Instruct (in-browser)"],["Memory",[c.browser!=null?`browser heap ${ke(c.browser)}`:"browser heap n/a",c.server!=null?`server ${ke(c.server)}`:null].filter(Boolean).join(" · ")]];return a.jsxs("div",{className:`tz-va ${t}`.trim(),children:[a.jsxs("section",{className:"tz-va__card tz-va__header",children:[a.jsx("h1",{children:s}),a.jsx("span",{className:`tz-va__chip tz-va__chip--${d}`,children:nt(d)})]}),r&&k&&a.jsx("section",{className:"tz-va__card tz-va__info",children:k.map(([b,K])=>a.jsxs("div",{className:"tz-va__info-row",children:[a.jsx("span",{className:"tz-va__info-label",children:b}),a.jsx("span",{className:"tz-va__info-value",children:K})]},b))}),a.jsxs("section",{className:"tz-va__card",children:[v&&a.jsxs("div",{className:"tz-va__progress",children:[a.jsxs("label",{children:["Whisper STT",a.jsx("div",{className:"tz-va__bar",children:a.jsx("span",{style:{width:`${f.whisper*100}%`}})})]}),a.jsxs("label",{children:["Kokoro TTS",a.jsx("div",{className:"tz-va__bar",children:a.jsx("span",{style:{width:`${f.kokoro*100}%`}})})]}),h>0&&a.jsxs("label",{children:["Local LLM",a.jsx("div",{className:"tz-va__bar",children:a.jsx("span",{style:{width:`${h*100}%`}})})]})]}),a.jsx("div",{className:"tz-va__button",children:a.jsx(Te,{status:d,active:R,loading:v,analyser:T,onToggle:R?x:I,devices:q,selectedMicId:$,onDeviceChange:S,inputData:E,sendData:b=>{L(""),z(b)}})}),a.jsx("div",{className:"tz-va__input-row",children:a.jsx("input",{type:"text",className:"tz-va__input",value:E,onChange:b=>L(b.target.value),onKeyDown:b=>{b.key==="Enter"&&E.trim()&&(L(""),z(E))},placeholder:"Type a message…",disabled:v})}),a.jsx("p",{className:"tz-va__note",children:v?f.kokoro<1?"Loading Kokoro TTS…":f.whisper<1?"Loading Whisper STT…":h>0&&h<1?"Loading local LLM (SmolLM2-360M, ~200 MB)…":"Finishing up…":"Ready."}),l&&a.jsx("p",{className:"tz-va__note",children:l})]}),a.jsxs("section",{className:"tz-va__card tz-va__transcript",children:[g.map(b=>a.jsxs("div",{className:`tz-va__message tz-va__message--${b.role}`,children:[a.jsx("small",{children:b.role==="user"?"You":"Assistant"}),a.jsx("p",{children:b.content}),b.timings&&a.jsxs("div",{className:"tz-va__timings",children:[b.timings.transcribeMs!=null&&a.jsxs("span",{children:["transcribe ",pe(b.timings.transcribeMs)]}),b.timings.thinkMs!=null&&a.jsxs("span",{children:["think ",pe(b.timings.thinkMs)]}),b.timings.ttsMs!=null&&a.jsxs("span",{children:["tts ",pe(b.timings.ttsMs)]})]})]},b.id)),N!==null&&a.jsxs("div",{className:"tz-va__message tz-va__message--assistant tz-va__message--streaming",children:[a.jsx("small",{children:"Assistant"}),a.jsxs("p",{children:[N,a.jsx("span",{className:"tz-va__cursor"})]})]}),a.jsx("div",{ref:P})]}),w?a.jsxs("section",{className:"tz-va__card",children:[a.jsx("strong",{children:"Error:"}),a.jsx("p",{children:w})]}):null]})}exports.AIAssistantButton=Te;exports.STATES=j;exports.TZVoiceChat=Me;exports.VoiceAssistant=st;exports.createLocalChatStream=Ne;exports.sendChatRequest=Ae;exports.useVoiceAssistant=Ie;
1
+ "use strict";var ct=Object.create;var Ce=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var dt=Object.getPrototypeOf,ht=Object.prototype.hasOwnProperty;var pt=(e,s,a,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let t of ut(s))!ht.call(e,t)&&t!==a&&Ce(e,t,{get:()=>s[t],enumerable:!(i=lt(s,t))||i.enumerable});return e};var $e=(e,s,a)=>(a=e!=null?ct(dt(e)):{},pt(s||!e||!e.__esModule?Ce(a,"default",{value:e,enumerable:!0}):a,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react"),r=require("react/jsx-runtime");var ge=typeof document<"u"?document.currentScript:null;const Pe=60,ke=200;function We(){let e="",s=!0;function a(t,o,n){t.push(o),e=n,s=!1}function i(){const t=[];for(;;){const o=/([.!?]{1,3})(\s|$)/.exec(e);if(o){const n=e.slice(0,o.index+o[0].length).trim();if(n.length>=10){a(t,n,e.slice(o.index+o[0].length));continue}}if(s){if(e.length>=25){const n=/[,;:—–](\s|$)/.exec(e);if(n){const c=e.slice(0,n.index+n[0].length).trim();if(c.length>=20){a(t,c,e.slice(n.index+n[0].length));continue}}}if(e.length>=Pe){const n=e.lastIndexOf(" ",Pe-1),c=n>10?n:Pe;a(t,e.slice(0,c).trim(),e.slice(c).trimStart());continue}}else if(e.length>=ke){const n=e.slice(0,ke),c=Math.max(n.lastIndexOf(", "),n.lastIndexOf("; "),n.lastIndexOf(": ")),l=c>ke/2?c+1:n.lastIndexOf(" ")>10?n.lastIndexOf(" "):ke;a(t,e.slice(0,l).trim(),e.slice(l).trimStart());continue}break}return t}return{write(t){return e+=t,i()},flush(){const t=e.trim();return e="",t}}}const ft=/\.(onnx|onnx_data|safetensors|bin|ort)$/i;function Ue(e,{minBytes:s=1e6,cap:a=.99}={}){const i=new Map,t=(n,c)=>c>=s&&(ft.test(n)||c>=5e6);let o=0;return(n={})=>{const c=n.file||n.name;if(c&&t(c,n.total)){const y=n.status==="done"?n.total:n.loaded??(typeof n.progress=="number"?n.total*n.progress/100:0),m=i.get(c);i.set(c,{loaded:Math.max((m==null?void 0:m.loaded)??0,y),total:n.total})}else if(c&&n.status==="done"&&i.has(c)){const y=i.get(c);y.loaded=y.total}let l=0,f=0;for(const y of i.values())l+=y.loaded,f+=y.total;if(f<=0)return;const d=Math.min(a,l/f);d>o&&(o=d,e(o))}}const mt="tz-voice-chat-model-cache",gt=4*1024*1024;let Me=null;function yt(){return Me||(Me=new Promise((e,s)=>{const a=indexedDB.open(mt,1);a.onupgradeneeded=()=>{a.result.createObjectStore("meta"),a.result.createObjectStore("chunks")},a.onsuccess=()=>e(a.result),a.onerror=()=>s(a.error)})),Me}async function de(e,s,a){const i=await yt();return new Promise((t,o)=>{const n=i.transaction(e,s),c=a(n.objectStore(e));n.oncomplete=()=>t(c==null?void 0:c.result),n.onerror=n.onabort=()=>o(n.error)})}const Ve=e=>typeof e=="string"?e:e.url,Ne=(e,s)=>`${e}\0${s}`;async function Ke(e){const s=await de("meta","readonly",a=>a.get(e));if(s)for(let a=0;a<s.chunks;a++)await de("chunks","readwrite",i=>i.delete(Ne(e,a)));await de("meta","readwrite",a=>a.delete(e))}function vt(){return{async match(e){try{const s=Ve(e),a=await de("meta","readonly",o=>o.get(s));if(!a||!a.complete)return;let i=0;const t=new ReadableStream({async pull(o){if(i>=a.chunks){o.close();return}const n=await de("chunks","readonly",c=>c.get(Ne(s,i)));if(!n){o.error(new Error("model cache entry is incomplete"));return}o.enqueue(new Uint8Array(n)),i++}});return new Response(t,{status:200,headers:new Headers(a.headers)})}catch(s){console.warn("[tz-voice-chat] model cache read failed:",s);return}},async put(e,s){const a=Ve(e);try{await Ke(a);const i=s.body.getReader();let t=[],o=0,n=0,c=0;const l=async d=>{if(!o||!d&&o<gt)return;const y=new Uint8Array(o);let m=0;for(const h of t)y.set(h,m),m+=h.length;t=[],o=0,await de("chunks","readwrite",h=>h.put(y.buffer,Ne(a,n))),n++};for(;;){const{done:d,value:y}=await i.read();if(d)break;t.push(y),o+=y.length,c+=y.length,await l(!1)}await l(!0);const f=[];s.headers.forEach((d,y)=>{y!=="content-encoding"&&y!=="content-length"&&f.push([y,d])}),f.push(["content-length",String(c)]),await de("meta","readwrite",d=>d.put({complete:!0,chunks:n,size:c,headers:f},a))}catch(i){console.warn("[tz-voice-chat] could not cache a model file (continuing without):",i);try{await Ke(a)}catch{}}}}}function wt(e){return typeof caches<"u"||typeof indexedDB>"u"?!1:(e.useBrowserCache=!1,e.useCustomCache=!0,e.customCache=vt(),!0)}async function bt(e,{dtype:s="q8",device:a="cpu",modelProxyUrl:i="/api/models/"}={}){var y,m;const{env:t}=await import("/vendor/transformers/transformers.min.js");t.remoteHost=i,wt(t),(m=(y=t==null?void 0:t.backends)==null?void 0:y.onnx)!=null&&m.wasm&&(t.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),t!=null&&t.onnx&&(t.onnx.logSeverityLevel=3);const o=await import("/vendor/kokoro/kokoro.web.js"),{KokoroTTS:n}=o;let c=s;a==="webgpu"&&(s==="q4"||s==="q8")&&(console.warn(`[modelLoader] dtype "${s}" not supported on WebGPU — using "fp32".`),c="fp32");let l=Ue(h=>e==null?void 0:e("kokoro",h));async function f(h,x){return n.from_pretrained("onnx-community/Kokoro-82M-ONNX",{dtype:x,device:h,progress_callback:l})}let d;try{d=await f(a,c)}catch(h){if(a!=="wasm")console.warn(`[modelLoader] Kokoro on "${a}" failed (${h==null?void 0:h.message}) — falling back to WASM.`),l=Ue(x=>e==null?void 0:e("kokoro",x)),d=await f("wasm",s);else throw h}return e==null||e("kokoro",1),{kokoro:d}}function _e(e,s,{threshold:a=.01,padMs:i=25}={}){const{numberOfChannels:t,length:o,sampleRate:n}=s;let c=o,l=-1;for(let h=0;h<t;h++){const x=s.getChannelData(h);for(let E=0;E<o;E++)if(Math.abs(x[E])>a){E<c&&(c=E);break}for(let E=o-1;E>=0;E--)if(Math.abs(x[E])>a){E>l&&(l=E);break}}if(l<c)return s;const f=Math.round(i/1e3*n),d=Math.max(0,c-f),y=Math.min(o,l+1+f);if(d===0&&y===o)return s;const m=e.createBuffer(t,y-d,n);for(let h=0;h<t;h++)m.copyToChannel(s.getChannelData(h).subarray(d,y),h);return m}function kt(e,{voice:s="af_bella",speed:a=1,onPlayStart:i}={}){const t=new AudioContext,o=[];let n=!1,c=null,l=!1;async function f(m){if(m instanceof AudioBuffer)return _e(t,m);const h=(m==null?void 0:m.audio)??m;if(h instanceof ArrayBuffer)return _e(t,await t.decodeAudioData(h.slice(0)));if(h instanceof Float32Array){const x=(m==null?void 0:m.samplingRate)??24e3,E=t.createBuffer(1,h.length,x);return E.copyToChannel(h,0),_e(t,E)}throw new Error("Unsupported TTS payload")}async function d(m){await t.resume();const h=t.createBufferSource();return h.buffer=m,h.connect(t.destination),new Promise(x=>{h.onended=()=>{c===h&&(c=null),x()},c=h,h.start(),l||(l=!0,i==null||i())})}async function y(){if(!n){for(n=!0;o.length>0;){const m=o.shift();try{const h=await m;h&&await d(h)}catch(h){console.error("[TtsQueue]",h)}}n=!1}}return{enqueue(m){o.push(e.generate(m,{voice:s,speed:a}).then(f)),y()},cancel(){if(o.length=0,l=!1,c){try{c.stop()}catch{}c=null}},async finished(){for(;n||o.length>0;)await new Promise(m=>setTimeout(m,200))}}}function xt({voice:e="",speed:s=1,onPlayStart:a,url:i="/api/tts"}={}){const t=new AudioContext,o=[];let n=!1,c=null,l=!1;async function f(m){const h={text:m};e&&(h.voice=e),s!==1&&(h.speed=s);const x=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});if(!x.ok)throw new Error(`TTS ${x.status}: ${await x.text()}`);return _e(t,await t.decodeAudioData(await x.arrayBuffer()))}async function d(m){await t.resume();const h=t.createBufferSource();return h.buffer=m,h.connect(t.destination),new Promise(x=>{h.onended=()=>{c===h&&(c=null),x()},c=h,h.start(),l||(l=!0,a==null||a())})}async function y(){if(!n){for(n=!0;o.length>0;){const m=o.shift();try{await d(await m)}catch(h){console.error("[ServerTTS]",h)}}n=!1}}return{enqueue(m){m!=null&&m.trim()&&(o.push(f(m)),y())},cancel(){if(o.length=0,c){try{c.stop()}catch{}c=null}l=!1},async finished(){for(;n||o.length>0;)await new Promise(m=>setTimeout(m,100))}}}function _t({voice:e="",rate:s=1,pitch:a=1,onPlayStart:i}={}){const t=[];let o=!1,n=!1;function c(){return e?speechSynthesis.getVoices().find(d=>d.name===e||d.voiceURI===e)??null:null}function l(){if(o||t.length===0)return;o=!0;const f=t.shift(),d=new SpeechSynthesisUtterance(f),y=c();y&&(d.voice=y),d.rate=s,d.pitch=a,d.onstart=()=>{n||(n=!0,i==null||i())},d.onend=()=>{o=!1,l()},d.onerror=m=>{console.error("[WebSpeech TTS] error",m.error),o=!1,l()},speechSynthesis.speak(d)}return{enqueue(f){f!=null&&f.trim()&&(t.push(f),l())},cancel(){t.length=0,speechSynthesis.cancel(),o=!1,n=!1},async finished(){for(;o||t.length>0;)await new Promise(f=>setTimeout(f,100))}}}async function St({onSpeechStart:e,onSpeechEnd:s,onError:a,deviceId:i}){try{const{MicVAD:t}=window.vad;return await t.new({model:"legacy",baseAssetPath:"/vendor/vad/",onnxWASMBasePath:"/vendor/ort/",additionalAudioConstraints:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!1,...i?{deviceId:{exact:i}}:{}},onSpeechStart:()=>e==null?void 0:e(),onSpeechEnd:n=>{console.log("[VAD] onSpeechEnd — samples:",n==null?void 0:n.length),s==null||s(n)},onVADMisfire:()=>{},negativeSpeechThreshold:.25,positiveSpeechThreshold:.5,redemptionFrames:4,minSpeechFrames:3,preSpeechPadFrames:1})}catch(t){throw a==null||a("VAD initialization failed. Falling back to manual microphone capture."),t}}function At(e,s=16e3){const a=e.length*2,i=new ArrayBuffer(44+a),t=new DataView(i),o=(n,c)=>{for(let l=0;l<c.length;l++)t.setUint8(n+l,c.charCodeAt(l))};o(0,"RIFF"),t.setUint32(4,36+a,!0),o(8,"WAVE"),o(12,"fmt "),t.setUint32(16,16,!0),t.setUint16(20,1,!0),t.setUint16(22,1,!0),t.setUint32(24,s,!0),t.setUint32(28,s*2,!0),t.setUint16(32,2,!0),t.setUint16(34,16,!0),o(36,"data"),t.setUint32(40,a,!0);for(let n=0,c=44;n<e.length;n++,c+=2){const l=Math.max(-1,Math.min(1,e[n]));t.setInt16(c,l<0?l*32768:l*32767,!0)}return new Blob([i],{type:"audio/wav"})}const z={IDLE:"idle",LISTENING:"listening",TRANSCRIBING:"transcribing",THINKING:"thinking",SPEAKING:"speaking"},Et="You are a friendly assistant for quick voice interactions. Provide answers only in the form of a single concise sentence, without any introductory phrases. Don't use any formatting, markdown, emoji, or code blocks — just plain text. The answers will be spoken aloud, so keep them short and natural.";function Ge({processInput:e,systemPrompt:s=Et,ttsProvider:a="server-kokoro",ttsVoice:i="af_bella",ttsSpeed:t=1,ttsServerUrl:o="/api/tts",ttsSpeechRate:n=1,ttsSpeechPitch:c=1,sttProvider:l="whisper",sttServerUrl:f="/api/stt",whisperModel:d="onnx-community/whisper-tiny.en",whisperDtype:y="q8",whisperDevice:m="wasm",kokoroDtype:h="q8",kokoroBrowserDevice:x="wasm",modelProxyUrl:E="/api/models/"}={}){const[W,M]=p.useState(z.IDLE),[N,T]=p.useState(!0),[V,D]=p.useState({whisper:0,kokoro:0}),[U,C]=p.useState(null),[u,_]=p.useState([]),[b,L]=p.useState(null),[g,R]=p.useState(!1),[$,X]=p.useState(""),[ie,J]=p.useState([]),[te,Q]=p.useState(null),K=p.useRef(z.IDLE),F=p.useRef(!1),A=p.useRef(null),k=p.useRef(null),v=p.useRef(null),P=p.useRef(null),B=p.useRef(null),ye=p.useRef(null),se=p.useRef([{role:"system",content:s}]),he=p.useRef(e),ce=p.useRef(0),H=p.useRef({id:null,enqueuedAt:null,ttsMs:null}),le=p.useRef(1),Z=p.useRef({provider:l,url:f});Z.current={provider:l,url:f},p.useEffect(()=>{se.current=[{role:"system",content:s},...se.current.slice(1)]},[s]),p.useEffect(()=>{K.current=W},[W]),p.useEffect(()=>{F.current=g},[g]),p.useEffect(()=>{he.current=e},[e]),p.useEffect(()=>{const j=navigator.mediaDevices;if(!j)return;async function O(){try{const w=await j.enumerateDevices();J(w.filter(I=>I.kind==="audioinput"))}catch{}}return O(),j.addEventListener("devicechange",O),()=>j.removeEventListener("devicechange",O)},[g]),p.useEffect(()=>{let j=!1;T(!0),D({whisper:0,kokoro:0});async function O(){try{const w=()=>{var q;const S=H.current;S.enqueuedAt!=null&&S.ttsMs==null&&(S.ttsMs=Math.round(performance.now()-S.enqueuedAt),S.id!=null&&ue(S.id,{timings:{ttsMs:S.ttsMs}})),a==="webspeech"&&((q=k.current)==null||q.pause())};if(a==="webspeech")A.current=_t({voice:i,rate:n,pitch:c,onPlayStart:w}),D(S=>({...S,kokoro:1}));else if(a==="kokoro"){const{kokoro:S}=await bt((q,ee)=>D(pe=>({...pe,[q]:ee})),{dtype:h,device:x,modelProxyUrl:E});if(j)return;A.current=kt(S,{voice:i,speed:t,onPlayStart:w})}else A.current=xt({voice:i,speed:t,onPlayStart:w,url:o}),D(S=>({...S,kokoro:1}));if(j)return;const I=typeof navigator>"u"||!navigator.mediaDevices;if(l==="server"||l==="none"||I){P.current=null,D(S=>({...S,whisper:1})),T(!1);return}P.current=new Worker(new URL("./assets/whisperWorker-rOnua0b5.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ge&&ge.tagName.toUpperCase()==="SCRIPT"&&ge.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),P.current.onmessage=S=>{S.data.type==="transcript"?ve(S.data.text,{transcribeMs:Math.round(performance.now()-ce.current)}):S.data.type==="progress"?D(q=>({...q,whisper:S.data.progress})):S.data.type==="ready"?(D(q=>({...q,whisper:1})),T(!1)):S.data.type==="error"&&(C(`Whisper: ${S.data.message}`),T(!1))},P.current.onerror=()=>{C("Model load failed. Check WebGPU/WASM browser support."),T(!1)},P.current.postMessage({type:"init",model:d,dtype:y,device:m,modelProxyUrl:E})}catch(w){j||(C("Initialisation failed: "+((w==null?void 0:w.message)??String(w))),T(!1))}}return O(),()=>{var w,I;j=!0,(w=P.current)==null||w.terminate(),(I=A.current)==null||I.cancel()}},[a,i,t,n,c,o,l,f,d,y,m,h,x]);function ne(j,O,w){const I=le.current++;return _(S=>[...S,{id:I,role:j,content:O,timings:w,time:new Date().toISOString()}]),I}function ue(j,{timings:O}){_(w=>w.map(I=>I.id===j?{...I,timings:{...I.timings,...O}}:I))}async function Ae(j){const O=ce.current;try{const w=await fetch(Z.current.url,{method:"POST",headers:{"Content-Type":"audio/wav"},body:At(j,16e3)});if(!w.ok)throw new Error(`Speech-to-text failed: ${w.status} ${await w.text()}`);const{text:I}=await w.json();await ve(I,{transcribeMs:Math.round(performance.now()-O)})}catch(w){C(w.message||"Speech-to-text failed."),M(F.current?z.LISTENING:z.IDLE)}}async function ve(j,{transcribeMs:O}={}){if(!(j!=null&&j.trim())){M(F.current?z.LISTENING:z.IDLE);return}M(z.THINKING),ne("user",j,O!=null?{transcribeMs:O}:void 0);const w=[...se.current,{role:"user",content:j}];se.current=w,await Ee(j,w)}async function Ee(j,O){var w,I,S,q;(w=v.current)==null||w.abort(),v.current=new AbortController,(I=A.current)==null||I.cancel();try{if(!he.current)throw new Error("processInput is not provided");const ee=We();let pe="",je=!1,Ie=null;const ot=performance.now(),fe={id:null,enqueuedAt:null,ttsMs:null};H.current=fe;const ze=be=>{var Le;fe.enqueuedAt==null&&(fe.enqueuedAt=performance.now()),(Le=A.current)==null||Le.enqueue(be)};L("");for await(const be of he.current(j,O,v.current.signal))Ie==null&&(Ie=Math.round(performance.now()-ot)),pe+=be,L(pe),ee.write(be).forEach(it=>{je||(je=!0,M(z.SPEAKING)),ze(it)});const De=ee.flush();De&&(je||M(z.SPEAKING),ze(De)),fe.id=ne("assistant",pe,{thinkMs:Ie,...fe.ttsMs!=null?{ttsMs:fe.ttsMs}:{}}),L(null),se.current=[...se.current,{role:"assistant",content:pe}],await((S=A.current)==null?void 0:S.finished()),a==="webspeech"&&((q=k.current)==null||q.start())}catch(ee){L(null),ee.name!=="AbortError"&&C(ee.message||"Processing failed.")}finally{M(F.current?z.LISTENING:z.IDLE)}}async function st(){var j,O;if(C(null),!navigator.mediaDevices){C("The microphone is unavailable: browsers only allow it on https:// pages or on localhost. You can still type messages; for voice, open this page over HTTPS.");return}K.current===z.SPEAKING&&((j=A.current)==null||j.cancel(),(O=v.current)==null||O.abort());try{M(z.LISTENING),R(!0);try{const w=await navigator.mediaDevices.getUserMedia({audio:$?{deviceId:{exact:$}}:!0,video:!1});ye.current=w;const I=new AudioContext;B.current=I;const S=I.createAnalyser();S.fftSize=256,I.createMediaStreamSource(w).connect(S),Q(S)}catch(w){console.warn("[TZVoiceChat] waveform analyser unavailable:",w)}k.current=await St({onSpeechStart:()=>{var w,I;a==="webspeech"&&K.current===z.SPEAKING||(K.current===z.SPEAKING&&((w=A.current)==null||w.cancel(),(I=v.current)==null||I.abort()),M(z.LISTENING))},onSpeechEnd:w=>{var I;a==="webspeech"&&K.current===z.SPEAKING||(M(z.TRANSCRIBING),ce.current=performance.now(),Z.current.provider==="server"?Ae(w):(I=P.current)==null||I.postMessage({type:"transcribe",audio:w},[w.buffer]))},onError:w=>{C(w),M(z.IDLE)},deviceId:$||void 0})}catch(w){console.error("[TZVoiceChat] startListening failed:",w),C("Microphone access failed. Allow audio permissions and refresh."),M(z.IDLE),R(!1)}}function rt(){var j,O,w,I,S;R(!1),(j=k.current)==null||j.destroy(),k.current=null,(O=ye.current)==null||O.getTracks().forEach(q=>q.stop()),ye.current=null,(w=B.current)==null||w.close(),B.current=null,Q(null),(I=A.current)==null||I.cancel(),(S=v.current)==null||S.abort(),M(z.IDLE)}function at(j){var S;if(!(j!=null&&j.trim()))return;M(z.SPEAKING);const O=We(),w=O.write(j),I=O.flush();[...w,...I?[I]:[]].forEach(q=>{var ee;return(ee=A.current)==null?void 0:ee.enqueue(q)}),(S=A.current)==null||S.finished().then(()=>{M(F.current?z.LISTENING:z.IDLE)})}return{status:W,loading:N,progress:V,error:U,transcript:u,streamingMessage:b,micAvailable:typeof navigator<"u"&&!!navigator.mediaDevices,micEnabled:g,startListening:st,stopListening:rt,speak:at,submitText:ve,liveAnalyser:te,devices:ie,selectedMicId:$,setSelectedMicId:X}}function Fe(e){const s=e.replace("#",""),a=s.length===3?s.split("").map(i=>i+i).join(""):s;return[parseInt(a.slice(0,2),16),parseInt(a.slice(2,4),16),parseInt(a.slice(4,6),16)]}function jt(e,s,a){e/=255,s/=255,a/=255;const i=Math.max(e,s,a),t=Math.min(e,s,a),o=(i+t)/2;if(i===t)return[0,0,o*100];const n=i-t,c=o>.5?n/(2-i-t):n/(i+t);let l;switch(i){case e:l=((s-a)/n+(s<a?6:0))/6;break;case s:l=((a-e)/n+2)/6;break;default:l=((e-s)/n+4)/6}return[l*360,c*100,o*100]}function It(e,s,a){s/=100,a/=100;const i=n=>(n+e/30)%12,t=s*Math.min(a,1-a),o=n=>a-t*Math.max(-1,Math.min(i(n)-3,Math.min(9-i(n),1)));return[Math.round(o(0)*255),Math.round(o(8)*255),Math.round(o(4)*255)]}function Y(e,s){const[a,i,t]=Fe(e),[o,n,c]=jt(a,i,t),[l,f,d]=It(o,n,Math.max(0,Math.min(100,c+s)));return`rgb(${l}, ${f}, ${d})`}function G(e,s){const[a,i,t]=Fe(e);return`rgba(${a}, ${i}, ${t}, ${s})`}function we(e,s){return e.replace("rgb(","rgba(").replace(")",`, ${s})`)}const xe=10;function Lt({analyser:e}){const s=p.useRef(null),a=p.useRef(null);return p.useEffect(()=>{if(cancelAnimationFrame(a.current),!e)return;const i=s.current;if(!i)return;const t=i.getContext("2d"),o=e.frequencyBinCount,n=new Uint8Array(o),c=Math.max(1,Math.floor(o/xe)),l=getComputedStyle(i),f=+l.getPropertyValue("--bar-hue"),d=+l.getPropertyValue("--bar-hue-range"),y=+l.getPropertyValue("--bar-sat"),m=+l.getPropertyValue("--bar-lit"),h=+l.getPropertyValue("--bar-lit-range"),x=()=>{a.current=requestAnimationFrame(x),e.getByteFrequencyData(n);const E=i.width,W=i.height;t.clearRect(0,0,E,W);const M=(E-(xe-1)*2)/xe;for(let N=0;N<xe;N++){const T=n[N*c]/255,V=Math.max(3,T*W*.88);t.fillStyle=`hsl(${f+T*d}, ${y}%, ${m+T*h}%)`,t.beginPath(),t.roundRect(N*(M+2),(W-V)/2,M,V,[2]),t.fill()}};return x(),()=>cancelAnimationFrame(a.current)},[e]),r.jsx("canvas",{ref:s,width:55,height:35,className:"ai-btn__canvas"})}function He({status:e="idle",active:s=!1,loading:a=!1,analyser:i=null,onToggle:t,devices:o=[],selectedMicId:n="",onDeviceChange:c,inputData:l="",sendData:f,accentColor:d="#f97316",uiColor:y="#64748b",size:m=70,barHue:h=25,barHueRange:x=20,barSat:E=88,barLit:W=65,barLitRange:M=20}){var L;const[N,T]=p.useState(!1),V=p.useRef(null);p.useEffect(()=>{if(!N)return;function g(R){var $;($=V.current)!=null&&$.contains(R.target)||T(!1)}return document.addEventListener("pointerdown",g),()=>document.removeEventListener("pointerdown",g)},[N]);function D(g){c==null||c(g),T(!1)}const U=p.useMemo(()=>{const g=Y(d,-8),R=Y(d,-15),$=Y(d,-22),X=Y(d,-30),ie=Y(d,-42),J=Y(d,8),te=Y(d,20),Q=Y(d,30),K=Y(y,-22),F=Y(y,-30),A=Y(y,18),k=Y(y,37);return{"--tz-size":`${m}px`,"--tz-a":d,"--tz-a-d8":g,"--tz-a-d15":R,"--tz-a-d22":$,"--tz-a-d30":X,"--tz-a-d42":ie,"--tz-a-l8":J,"--tz-a-l20":te,"--tz-a-l30":Q,"--tz-a-25":G(d,.25),"--tz-a-28":G(d,.28),"--tz-a-30":G(d,.3),"--tz-a-32":G(d,.32),"--tz-a-34":G(d,.34),"--tz-a-35":G(d,.35),"--tz-a-38":G(d,.38),"--tz-a-45":G(d,.45),"--tz-a-50":G(d,.5),"--tz-a-55":G(d,.55),"--tz-a-60":G(d,.6),"--tz-a-65":G(d,.65),"--tz-a-68":G(d,.68),"--tz-u":y,"--tz-u-d22":K,"--tz-u-d30":F,"--tz-u-l18":A,"--tz-u-l37":k,"--tz-u-30":G(y,.3),"--tz-u-55":G(y,.55),"--tz-u-d30-a85":we(F,.85),"--tz-u-l18-a18":we(A,.18),"--tz-u-l18-a20":we(A,.2),"--tz-u-l18-a32":we(A,.32),"--tz-u-d22-a90":we(K,.9),"--bar-hue":h,"--bar-hue-range":x,"--bar-sat":E,"--bar-lit":W,"--bar-lit-range":M}},[d,y,m,h,x,E,W,M]),C=((L=o.find(g=>g.deviceId===n))==null?void 0:L.label)||(n?`Mic ${n.slice(0,6)}…`:"Default mic"),u=l.trim().length>0,_=u?"ready":s?e:"off";let b;return u?b=r.jsx("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:r.jsx("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})}):!s||e==="idle"?b=r.jsxs("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[r.jsx("path",{fillOpacity:"0.52",d:"M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4zm6 10a1 1 0 0 1 2 0 8 8 0 0 1-7 7.94V21h2a1 1 0 0 1 0 2H9a1 1 0 0 1 0-2h2v-2.06A8 8 0 0 1 4 11a1 1 0 0 1 2 0 6 6 0 0 0 12 0z"}),r.jsx("path",{fill:"white",fillOpacity:"0.98",d:"M14.5 0L15.65 3.45L19.1 4.6L15.65 5.75L14.5 9.2L13.35 5.75L9.9 4.6L13.35 3.45Z"}),r.jsx("path",{fill:"white",fillOpacity:"0.88",d:"M19 8.62L19.75 10.75L21.88 11.5L19.75 12.25L19 14.38L18.25 12.25L16.12 11.5L18.25 10.75Z"})]}):e==="listening"?b=r.jsx(Lt,{analyser:i}):e==="transcribing"?b=r.jsx("div",{className:"ai-btn__bars ai-btn__bars--transcribing",children:Array.from({length:7},(g,R)=>r.jsx("span",{style:{animationDelay:`${R*.1}s`}},R))}):e==="thinking"?b=r.jsxs("div",{className:"ai-btn__dots",children:[r.jsx("span",{}),r.jsx("span",{style:{animationDelay:"0.18s"}}),r.jsx("span",{style:{animationDelay:"0.36s"}})]}):e==="speaking"&&(b=r.jsx("div",{className:"ai-btn__bars ai-btn__bars--speaking",children:Array.from({length:7},(g,R)=>r.jsx("span",{style:{animationDelay:`${R*.11}s`}},R))})),r.jsxs("div",{className:"ai-btn-root",style:U,children:[r.jsxs("div",{className:`ai-btn-rings ai-btn-rings--${_}`,"aria-hidden":"true",children:[r.jsx("span",{className:"ai-ring ai-ring--1"}),r.jsx("span",{className:"ai-ring ai-ring--2"})]}),r.jsxs("button",{className:`ai-btn ai-btn--${_}`,disabled:a,onClick:u?()=>f==null?void 0:f(l):t,"aria-label":u?"Send message":s?"Stop assistant":"Start assistant","aria-pressed":u?void 0:s,children:[b,s&&!u&&r.jsx("span",{className:"ai-btn__hover-stop","aria-hidden":"true",children:"■"})]}),r.jsxs("div",{className:`ai-mic-sel${N?" open":""}`,ref:V,children:[r.jsxs("button",{className:"ai-mic-sel__trigger",onClick:()=>T(g=>!g),title:"Change microphone","aria-label":"Change microphone","aria-expanded":N,children:[r.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[r.jsx("path",{d:"M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4z"}),r.jsx("path",{d:"M5 11a1 1 0 0 0-2 0 9 9 0 0 0 8 8.94V22H9a1 1 0 0 0 0 2h6a1 1 0 0 0 0-2h-2v-2.06A9 9 0 0 0 21 11a1 1 0 0 0-2 0 7 7 0 0 1-14 0z"})]}),r.jsx("span",{className:"ai-mic-sel__label",children:C}),r.jsx("svg",{className:`ai-mic-sel__caret${N?" open":""}`,width:"9",height:"9",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:r.jsx("path",{d:"M12 16L4 8h16l-8 8z"})})]}),N&&r.jsxs("ul",{className:"ai-mic-sel__menu",role:"listbox","aria-label":"Select microphone",children:[r.jsx("li",{role:"option",className:`ai-mic-sel__option${n===""?" selected":""}`,onClick:()=>D(""),"aria-selected":n==="",children:"Default microphone"}),o.map(g=>r.jsx("li",{role:"option",className:`ai-mic-sel__option${n===g.deviceId?" selected":""}`,onClick:()=>D(g.deviceId),"aria-selected":n===g.deviceId,children:g.label||`Microphone ${g.deviceId.slice(0,8)}`},g.deviceId))]})]})]})}async function Ye(e,s,a="/api/chat"){var c;const i=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},signal:s,body:JSON.stringify({messages:e})});if(!i.ok){const l=await i.text();throw new Error(`Server error: ${i.status} ${l}`)}const t=(c=i.body)==null?void 0:c.getReader();if(!t){const l=await i.json();return{stream:async function*(){yield l.text}}}const o=new TextDecoder;let n="";return{stream:async function*(){var f,d,y;let l="";for(;;){const{value:m,done:h}=await t.read();if(h)break;n+=o.decode(m,{stream:!0});const x=n.split(`
2
+ `);n=x.pop();for(const E of x){const W=E.trim();if(!W.startsWith("data:"))continue;const M=W.slice(5).trimStart();if(M==="[DONE]")return;try{const T=(y=(d=(f=JSON.parse(M).choices)==null?void 0:f[0])==null?void 0:d.delta)==null?void 0:y.content;T&&(l&&/\w/.test(l)&&/\w/.test(T[0])&&(yield" "),l=T[T.length-1],yield T)}catch{}}}}}}function Je(e,s,a){return{stream:async function*(){const i=[];let t=null,o=!1,n="";const c=({data:f})=>{f.type==="token"?(i.push(f.text),t==null||t(),t=null):f.type==="done"&&(o=!0,t==null||t(),t=null)},l=()=>{o=!0,t==null||t(),t=null};e.addEventListener("message",c),a==null||a.addEventListener("abort",l),e.postMessage({type:"generate",messages:s});try{for(;!o||i.length>0;)if(i.length>0){const f=i.shift();n&&/\w/.test(n)&&/\w/.test(f[0])&&(yield" "),n=f[f.length-1],yield f}else await new Promise(f=>{t=f})}finally{e.removeEventListener("message",c),a==null||a.removeEventListener("abort",l)}}}}const Se="tz-voice-chat:boot",Qe="tz-voice-chat:stage",Be="tz-voice-chat:allowLocalLlm",oe={get(e){try{return JSON.parse(localStorage.getItem(e)||"null")}catch{return null}},set(e,s){try{localStorage.setItem(e,JSON.stringify(s))}catch{}}},ae=e=>oe.set(Qe,{s:e,at:Date.now()}),Re=()=>{if(typeof navigator>"u")return!1;const e=typeof location<"u"?new URLSearchParams(location.search).get("phone"):null;return e==="1"?!0:e==="0"?!1:/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1},Pt=()=>Re()?2:3;function Mt(){var n;const e=Date.now(),s=oe.get(Se),a=s&&!s.done&&e-s.at<10*60*1e3,i=a?((n=oe.get(Qe))==null?void 0:n.s)??null:null,t=a?s.attempts+1:1,o=!!(s!=null&&s.safe)||t>=Pt();return oe.set(Se,{attempts:s!=null&&s.safe?s.attempts:t,at:e,done:!1,safe:o}),ae("page started"),{attempts:t,lastStage:i,safe:o}}const Tt=()=>{const e=typeof location<"u"?new URLSearchParams(location.search).get("stagedLoad"):null;return e==="1"?!0:e==="0"?!1:Re()};function Ze({apiBase:e="/api",systemPrompt:s}={}){const[a,i]=p.useState(!0),[t,o]=p.useState(0),[n,c]=p.useState(""),[l,f]=p.useState({}),[d,y]=p.useState(null),[m,h]=p.useState({}),[x,E]=p.useState(0),[W,M]=p.useState([]),[N,T]=p.useState(null),[V,D]=p.useState("idle"),U=p.useRef(null),C=p.useRef(null),u=p.useRef(null),_=p.useRef(null);_.current===null&&(_.current=Mt());const b=_.current,L=b.attempts,g=b.safe,[R,$]=p.useState(!1),X=p.useCallback(()=>E(A=>A+1),[]),ie=p.useCallback(()=>{oe.set(Be,!0),E(A=>A+1)},[]);p.useEffect(()=>{let A=!1;c(""),o(0);async function k(){let v=null,P={};try{v=await(await fetch(`${e}/config`)).json(),y(v),P={ttsProvider:v.ttsProvider||"kokoro",ttsVoice:v.ttsProvider==="openai"?v.openaiTtsVoice||"alloy":v.ttsProvider==="elevenlabs"?v.elevenlabsVoiceId:v.ttsProvider==="webspeech"?v.webSpeechVoice||"":v.kokoroVoice||"af_bella",ttsSpeed:v.kokoroSpeed??1,ttsServerUrl:`${e}/tts`,ttsSpeechRate:v.webSpeechRate??1,ttsSpeechPitch:v.webSpeechPitch??1,sttProvider:v.sttProvider==="elevenlabs"||v.sttProvider==="openai"?"server":"whisper",sttServerUrl:`${e}/stt`,whisperModel:v.whisperModel||"onnx-community/whisper-tiny.en",whisperDtype:v.whisperDtype||"q8",whisperDevice:v.whisperDevice||"wasm",kokoroDtype:v.kokoroDtype||"q8",kokoroBrowserDevice:v.kokoroBrowserDevice||"wasm",modelProxyUrl:`${e}/models/`,...v.systemPrompt?{systemPrompt:v.systemPrompt}:{}}}catch{P={ttsProvider:"kokoro",ttsServerUrl:`${e}/tts`,modelProxyUrl:`${e}/models/`}}if(A)return;ae("config loaded");const B=[],ye=typeof window<"u"&&window.isSecureContext===!1,se=typeof navigator<"u"&&!navigator.gpu;ye&&B.push('This page is not served over HTTPS (or localhost), so the browser blocks the microphone and WebGPU. Typed chat still works; for voice open it over https:// (see "Use it from a phone" in the README).');const he=typeof navigator>"u"||!navigator.mediaDevices;if(he&&(P={...P,sttProvider:"none"},B.push("Speech recognition is not loaded because this page has no microphone. Typed messages and spoken replies still work.")),se){const H=[];!he&&P.whisperDevice==="webgpu"&&(P={...P,whisperDevice:"wasm",whisperDtype:"q8"},H.push("speech recognition runs on the CPU (Whisper, q8)")),P.ttsProvider==="kokoro"&&P.kokoroBrowserDevice==="webgpu"&&(P={...P,ttsProvider:"webspeech",ttsVoice:""},H.push("replies are spoken with the browser's built-in voice instead of Kokoro")),H.length&&B.push(`WebGPU is not available here, so ${H.join(" and ")}.`)}g?(P.sttProvider==="whisper"&&(P={...P,whisperModel:"onnx-community/whisper-tiny.en",whisperDtype:"q8",whisperDevice:"wasm"}),P.ttsProvider==="kokoro"&&(P={...P,ttsProvider:"webspeech",ttsVoice:""}),B.push(`This page restarted ${L} times before it finished loading — usually the device ran out of memory. `+(b.lastStage?`It had reached: ${b.lastStage}. `:"")+"Heavy models are switched off for now: the smallest speech model and the browser voice are used, and the in-browser chat model is not loaded. Pick a cloud chat provider in Settings, or retry the full load.")):b.attempts>=2&&b.lastStage&&B.push(`The page restarted before it finished loading (attempt ${b.attempts}); it had reached: ${b.lastStage}.`);const ce=(v==null?void 0:v.chatProvider)==="local"&&Re()&&!g&&!oe.get(Be);if($(ce),ce&&B.push("The in-browser chat model needs a lot of memory and often makes phone browsers restart the page, so it is not loaded automatically here. Pick a cloud chat provider in Settings (recommended), or load it anyway."),M(B),ce){U.current=async function*(){throw new Error('The in-browser chat model is not loaded on phones by default. Choose a cloud chat provider in Settings, or press "Load it anyway".')},f(P),D("off"),i(!1);return}if((v==null?void 0:v.chatProvider)==="local"&&g){U.current=async function*(){throw new Error('The in-browser chat model is switched off because this page kept restarting while loading. Choose a cloud chat provider in Settings, or use "Retry full load".')},f(P),i(!1);return}if((v==null?void 0:v.chatProvider)==="local"){i(!0),c("Using SmolLM2-360M-Instruct locally in your browser — slow and simple; pick a cloud model in Settings for better answers.");const H=()=>{D("loading"),ae("chat model: downloading");let le=-1;const Z=new Worker(new URL("./assets/llmWorker-CmV-b4uq.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ge&&ge.tagName.toUpperCase()==="SCRIPT"&&ge.src||new URL("index.cjs",document.baseURI).href),{type:"module"});C.current=Z,Z.onmessage=ne=>{if(ne.data.type==="progress"){const ue=ne.data.progress??0;o(ue),ue>=.98?ae("chat model: downloaded, creating the model session (the memory peak)"):Math.floor(ue*4)!==le&&(le=Math.floor(ue*4),ae(`chat model: downloading (${le*25}%+)`))}else ne.data.type==="ready"?(ae("chat model: ready"),o(1),U.current=async function*(ue,Ae,ve){const{stream:Ee}=Je(Z,Ae,ve);yield*Ee()},D("ready"),i(!1)):ne.data.type==="error"&&(D("error"),i(!1))},Z.onerror=()=>{D("error"),i(!1)},Z.postMessage({type:"init",modelProxyUrl:`${e}/models/`})};f(P),Tt()?(D("waiting"),ae("waiting for the speech models"),u.current=H):H();return}v!=null&&v.hasApiKey?U.current=async function*(H,le,Z){const{stream:ne}=await Ye(le,Z,`${e}/chat`);yield*ne()}:U.current=async function*(){throw new Error("The chat model is not configured yet — open Settings and choose a provider.")},f(P),i(!1)}return k(),()=>{var v;A=!0,u.current=null,(v=C.current)==null||v.terminate(),C.current=null}},[e,x]);const J=Ge({processInput:async function*(A,k,v){U.current&&(yield*U.current(A,k,v))},...s?{systemPrompt:s}:{},...l});p.useEffect(()=>{T(l)},[l]),p.useEffect(()=>{if(u.current&&N===l&&!J.loading){const A=u.current;u.current=null,A()}},[N,l,J.loading]);const te=J.loading||a;p.useEffect(()=>{d&&!te&&(ae("ready"),oe.set(Se,{attempts:g?b.attempts:0,at:Date.now(),done:!0,safe:g}))},[d,te,g,b.attempts]);const Q=p.useCallback(()=>{oe.set(Se,{attempts:0,at:Date.now(),done:!0,safe:!1}),window.location.reload()},[]);p.useEffect(()=>{let A=!1;async function k(){const P={};typeof performance<"u"&&performance.memory&&(P.browser=performance.memory.usedJSHeapSize);try{const B=await fetch(`${e}/stats`);B.ok&&(P.server=(await B.json()).rss)}catch{}A||h(P)}k();const v=setInterval(k,3e3);return()=>{A=!0,clearInterval(v)}},[e]);const{micEnabled:K,stopListening:F}=J;return p.useEffect(()=>{if(!K)return;const A=k=>{k.key==="Escape"&&F()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[K,F]),{chat:J,info:d,config:l,memory:m,llmProgress:t,note:n,loading:te,missing:(d==null?void 0:d.missing)??[],warnings:W,llmPhase:V,localLlmBlocked:R,loadLocalModelAnyway:ie,safeMode:g,retryFullLoad:Q,reload:X}}const Nt=["q8","q4","q4f16","fp16","fp32"],me="Local · free",re="Cloud",Oe=[{group:"Chat model",fields:[{key:"chatProvider",label:"Provider",type:"select",env:"OPENAI_PROVIDER",default:"local",options:[["","Not configured"],["local","In-browser model (SmolLM2, no key, ~200 MB) — slow and simple",me],["openai-compatible","OpenAI-compatible server (Ollama, LM Studio, vLLM, on-premise…)",me],["openrouter","OpenRouter",re],["openai","OpenAI",re],["anthropic","Anthropic (Claude)",re],["huggingface","Hugging Face",re]]},{key:"openrouterApiKey",label:"OpenRouter API key",type:"password",secret:!0,env:"OPENROUTER_API_KEY",showWhen:{chatProvider:"openrouter"},hint:"Get one at https://openrouter.ai/keys"},{key:"openrouterModel",label:"OpenRouter model",type:"text",env:"OPENROUTER_MODEL",default:"gpt-4o-mini",showWhen:{chatProvider:"openrouter"},hint:'e.g. openai/gpt-4o-mini, or a ":free" model'},{key:"openaiApiKey",label:"OpenAI API key",type:"password",secret:!0,env:"OPENAI_API_KEY",showWhenAny:[{chatProvider:"openai"},{sttProvider:"openai"},{ttsProvider:"openai"}],hint:"Used for OpenAI chat, transcription and/or TTS. Get one at https://platform.openai.com/api-keys"},{key:"openaiChatModel",label:"OpenAI model",type:"text",env:"OPENAI_CHAT_MODEL",default:"gpt-4o-mini",showWhen:{chatProvider:"openai"},suggestions:["gpt-4o-mini","gpt-4o","gpt-4.1-mini","gpt-4.1"]},{key:"anthropicApiKey",label:"Anthropic API key",type:"password",secret:!0,env:"ANTHROPIC_API_KEY",showWhen:{chatProvider:"anthropic"},hint:"Get one at https://console.anthropic.com/settings/keys"},{key:"anthropicModel",label:"Anthropic model",type:"text",env:"ANTHROPIC_MODEL",default:"claude-haiku-5-5",showWhen:{chatProvider:"anthropic"},suggestions:["claude-haiku-5-5","claude-sonnet-5-5","claude-opus-5-5","claude-fable-5-2"],hint:"Haiku is the fastest — best for voice"},{key:"huggingfaceApiKey",label:"Hugging Face token",type:"password",secret:!0,env:"HUGGINGFACE_API_KEY",showWhen:{chatProvider:"huggingface"},hint:"A token with read scope"},{key:"compatBaseUrl",label:"Server base URL",type:"text",env:"OPENAI_COMPAT_BASE_URL",default:"http://localhost:11434/v1",showWhen:{chatProvider:"openai-compatible"},suggestions:["http://localhost:11434/v1","http://localhost:1234/v1","http://localhost:8000/v1"],hint:"Must serve /chat/completions. Ollama :11434, LM Studio :1234, vLLM :8000. From inside Docker use host.docker.internal instead of localhost."},{key:"compatModel",label:"Model name",type:"text",env:"OPENAI_COMPAT_MODEL",default:"",showWhen:{chatProvider:"openai-compatible"},hint:"Exactly as the server names it, e.g. llama3.2 or qwen2.5:7b-instruct"},{key:"compatApiKey",label:"API key (optional)",type:"password",secret:!0,env:"OPENAI_COMPAT_API_KEY",showWhen:{chatProvider:"openai-compatible"},hint:"Leave empty if the server needs no key (most local servers)."},{key:"systemPrompt",label:"System prompt",type:"textarea",default:"",hint:"Leave blank for the built-in short, spoken-style prompt."}]},{group:"Speech-to-text",fields:[{key:"sttProvider",label:"Provider",type:"select",env:"STT_PROVIDER",default:"whisper",options:[["whisper","Whisper in the browser",me],["openai","OpenAI transcription",re],["elevenlabs","ElevenLabs Scribe",re]]},{key:"openaiSttModel",label:"OpenAI model",type:"text",env:"OPENAI_STT_MODEL",default:"whisper-1",showWhen:{sttProvider:"openai"},suggestions:["whisper-1","gpt-4o-mini-transcribe","gpt-4o-transcribe"],hint:"Uses the OpenAI API key below"},{key:"openaiSttLanguage",label:"OpenAI language",type:"text",env:"OPENAI_STT_LANGUAGE",default:"",showWhen:{sttProvider:"openai"},hint:"ISO-639-1 code such as en; blank = detect automatically"},{key:"elevenlabsApiKey",label:"ElevenLabs API key",type:"password",secret:!0,env:"ELEVENLABS_API_KEY",showWhenAny:[{sttProvider:"elevenlabs"},{ttsProvider:"elevenlabs"}],hint:"Used for ElevenLabs speech-to-text and/or text-to-speech. Get one at https://elevenlabs.io/app/settings/api-keys"},{key:"elevenlabsSttModel",label:"ElevenLabs model",type:"text",env:"ELEVENLABS_STT_MODEL",default:"scribe_v2",showWhen:{sttProvider:"elevenlabs"},suggestions:["scribe_v2","scribe_v3","scribe_v2_medical"]},{key:"elevenlabsLanguage",label:"ElevenLabs language",type:"text",env:"ELEVENLABS_STT_LANGUAGE",default:"",showWhen:{sttProvider:"elevenlabs"},hint:"ISO code such as en or de; blank = detect automatically"},{key:"whisperModel",label:"Model",type:"select",env:"WHISPER_MODEL",default:"onnx-community/whisper-small.en",showWhen:{sttProvider:"whisper"},allowCustom:!0,options:[["onnx-community/whisper-tiny.en","whisper-tiny.en — fastest, ~40 MB, more errors"],["onnx-community/whisper-base.en","whisper-base.en — better, ~74 MB, recommended"],["onnx-community/whisper-small.en","whisper-small.en — good, ~244 MB, significantly more accurate"]]},{key:"whisperDtype",label:"Precision",type:"select",env:"WHISPER_DTYPE",default:"fp32",showWhen:{sttProvider:"whisper"},options:[["q8","q8"],["q4","q4"],["fp16","fp16 (WebGPU)"],["fp32","fp32"]]},{key:"whisperDevice",label:"Device",type:"select",env:"WHISPER_DEVICE",default:"webgpu",showWhen:{sttProvider:"whisper"},aliases:{cpu:"wasm"},options:[["wasm","wasm (CPU)"],["webgpu","webgpu"]]}]},{group:"Text-to-speech",fields:[{key:"ttsProvider",label:"Provider",type:"select",env:"TTS_PROVIDER",default:"kokoro",options:[["kokoro","Kokoro in the browser",me],["server-kokoro","Kokoro on the server (needs: npm install kokoro-js)",me],["webspeech","Browser Web Speech API (built-in voices)",me],["openai","OpenAI TTS",re],["elevenlabs","ElevenLabs",re]]},{key:"kokoroVoice",label:"Kokoro voice",type:"text",env:"KOKORO_VOICE",default:"af_bella",showWhen:{ttsProvider:["kokoro","server-kokoro"]},hint:"e.g. af_bella, af_sarah, am_adam"},{key:"kokoroSpeed",label:"Kokoro speed",type:"number",env:"KOKORO_SPEED",default:1,showWhen:{ttsProvider:["kokoro","server-kokoro"]},hint:"1 = normal; 1.1–1.2 often sounds more natural"},{key:"kokoroDtype",label:"Kokoro precision",type:"select",env:"KOKORO_DTYPE",default:"fp32",showWhen:{ttsProvider:["kokoro","server-kokoro"]},options:Nt.map(e=>[e,e]),hint:"q4/q8 are promoted to fp32 on WebGPU"},{key:"kokoroBrowserDevice",label:"Kokoro device (browser)",type:"select",env:"KOKORO_BROWSER_DEVICE",default:"webgpu",showWhen:{ttsProvider:"kokoro"},options:[["wasm","wasm"],["webgpu","webgpu"]]},{key:"kokoroDevice",label:"Kokoro device (server)",type:"select",env:"KOKORO_DEVICE",default:"cpu",showWhen:{ttsProvider:"server-kokoro"},options:[["cpu","cpu"]]},{key:"openaiTtsModel",label:"OpenAI TTS model",type:"text",env:"OPENAI_TTS_MODEL",default:"tts-1",showWhen:{ttsProvider:"openai"},suggestions:["tts-1","tts-1-hd","gpt-4o-mini-tts"]},{key:"openaiTtsVoice",label:"OpenAI voice",type:"text",env:"OPENAI_TTS_VOICE",default:"alloy",showWhen:{ttsProvider:"openai"},suggestions:["alloy","echo","fable","onyx","nova","shimmer"]},{key:"elevenlabsVoiceId",label:"ElevenLabs voice ID",type:"text",env:"ELEVENLABS_VOICE_ID",default:"21m00Tcm4TlvDq8ikWAM",showWhen:{ttsProvider:"elevenlabs"},hint:`Default is the premade "Rachel" voice. Copy another voice's ID from your ElevenLabs voice library.`},{key:"elevenlabsTtsModel",label:"ElevenLabs model",type:"text",env:"ELEVENLABS_TTS_MODEL",default:"eleven_flash_v2_5",showWhen:{ttsProvider:"elevenlabs"},suggestions:["eleven_flash_v2_5","eleven_turbo_v2_5","eleven_multilingual_v2"],hint:"Flash is the lowest latency — best for voice chat"},{key:"webSpeechVoice",label:"Web Speech voice",type:"text",env:"WEBSPEECH_VOICE",default:"",showWhen:{ttsProvider:"webspeech"},hint:"Exact voice name; blank = browser default"},{key:"webSpeechRate",label:"Web Speech rate",type:"number",env:"WEBSPEECH_RATE",default:1,showWhen:{ttsProvider:"webspeech"},hint:"0.1 – 10"},{key:"webSpeechPitch",label:"Web Speech pitch",type:"number",env:"WEBSPEECH_PITCH",default:1,showWhen:{ttsProvider:"webspeech"},hint:"0 – 2"}]}],Xe=Oe.flatMap(e=>e.fields);Object.fromEntries(Xe.map(e=>[e.key,e]));Xe.filter(e=>e.secret).map(e=>e.key);function Rt(e,s){const a=i=>Object.entries(i).every(([t,o])=>(Array.isArray(o)?o:[o]).includes(s[t]));return e.showWhenAny?e.showWhenAny.some(a):e.showWhen?a(e.showWhen):!0}function et(e,s={}){const a=[],i=n=>!!s[n],t=e.chatProvider;t||a.push({key:"chatProvider",message:"No chat model provider is configured.",scope:"chat"}),t==="openai-compatible"&&(e.compatBaseUrl||a.push({key:"compatBaseUrl",message:"The OpenAI-compatible server URL is missing.",scope:"chat"}),e.compatModel||a.push({key:"compatModel",message:"The model name for the OpenAI-compatible server is missing.",scope:"chat"}));const o=[{key:"openrouterApiKey",name:"OpenRouter API key",uses:[t==="openrouter"&&["chat","chat"]]},{key:"anthropicApiKey",name:"Anthropic API key",uses:[t==="anthropic"&&["chat","chat"]]},{key:"huggingfaceApiKey",name:"Hugging Face token",uses:[t==="huggingface"&&["chat","chat"]]},{key:"openaiApiKey",name:"OpenAI API key",uses:[t==="openai"&&["chat","chat"],e.sttProvider==="openai"&&["speech-to-text","stt"],e.ttsProvider==="openai"&&["text-to-speech","tts"]]},{key:"elevenlabsApiKey",name:"ElevenLabs API key",uses:[e.sttProvider==="elevenlabs"&&["speech-to-text","stt"],e.ttsProvider==="elevenlabs"&&["text-to-speech","tts"]]}];for(const{key:n,name:c,uses:l}of o){const f=l.filter(Boolean);if(!f.length||i(n))continue;const d=f.some(m=>m[1]==="chat")?"chat":f[0][1],y=f.length===1&&f[0][0]==="chat"?`${c} is missing.`:`${c} (for ${f.map(m=>m[0]).join(", ").replace(/, ([^,]*)$/," and $1")}) is missing.`;a.push({key:n,message:y,scope:d})}return a}function tt({apiBase:e="/api",onSaved:s,onClose:a}){const[i,t]=p.useState(null),[o,n]=p.useState({}),[c,l]=p.useState(null),[f,d]=p.useState(!1),y=p.useRef(null),m=p.useCallback(async()=>{try{const u=await fetch(`${e}/settings`);if(!u.ok)throw new Error(await u.text());t(await u.json())}catch(u){l({kind:"error",text:`Could not load settings: ${u.message}`})}},[e]);if(p.useEffect(()=>{m()},[m]),!i)return r.jsx("section",{className:"tz-va__card",children:c?c.text:"Loading settings…"});const h={...i.values,...Object.fromEntries(Object.entries(o).filter(([,u])=>u!==null))},x={...i.secretsSet};for(const[u,_]of Object.entries(o))u in x&&(x[u]=_===null?!1:_?!0:x[u]);const E=et(h,x),W=new Set(E.map(u=>u.key)),M=Object.keys(o).length>0,N=(u,_)=>n(b=>({...b,[u]:_}));async function T(u,_){var b;d(!0);try{const L=await fetch(`${e}/settings`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!L.ok)throw new Error(await L.text());const g=await L.json();t(g),n({});const R=(b=g.ignored)!=null&&b.length?` Ignored unknown/invalid keys: ${g.ignored.join(", ")}.`:"";l({kind:"ok",text:_+R}),s==null||s(g)}catch(L){l({kind:"error",text:L.message})}finally{d(!1)}}async function V(){try{const u=await fetch(`${e}/settings/export`);if(!u.ok)throw new Error(await u.text());const _=new Blob([JSON.stringify(await u.json(),null,2)],{type:"application/json"}),b=document.createElement("a");b.href=URL.createObjectURL(_),b.download="tz-voice-chat-settings.json",b.click(),URL.revokeObjectURL(b.href),l({kind:"ok",text:"Exported. The file contains your API keys — keep it private."})}catch(u){l({kind:"error",text:`Export failed: ${u.message}`})}}async function D(u){var b;const _=(b=u.target.files)==null?void 0:b[0];if(u.target.value="",!!_)try{const L=JSON.parse(await _.text()),g=L&&typeof L.settings=="object"?L.settings:L;if(!g||typeof g!="object"||Array.isArray(g))throw new Error("not a settings object");await T({settings:g},`Imported ${_.name} and applied it.`)}catch(L){l({kind:"error",text:`Import failed: ${L.message}`})}}function U(u){const _=[];for(const[b,L,g]of u){const R=_[_.length-1],$=r.jsx("option",{value:b,children:L},b);g?R&&R.group===g?R.items.push($):_.push({group:g,items:[$]}):_.push($)}return _.map(b=>b.group?r.jsx("optgroup",{label:b.group,children:b.items},b.group):b)}function C(u){const _=`tz-va-set-${u.key}`,b=W.has(u.key);let L;if(u.type==="select")L=r.jsxs("select",{id:_,value:h[u.key]??"",onChange:g=>N(u.key,g.target.value),children:[U(u.options),u.allowCustom&&h[u.key]&&!u.options.some(([g])=>g===h[u.key])&&r.jsxs("option",{value:h[u.key],children:[h[u.key]," (custom)"]})]});else if(u.type==="textarea")L=r.jsx("textarea",{id:_,rows:4,value:h[u.key]??"",onChange:g=>N(u.key,g.target.value)});else if(u.type==="password"){const g=u.key in o,R=o[u.key]===null?"Will be cleared on save":i.secretsSet[u.key]?"Saved — type to replace":"Not set";L=r.jsxs("span",{className:"tz-va__secret",children:[r.jsx("input",{id:_,type:"password",autoComplete:"off",value:o[u.key]??"",placeholder:R,onChange:$=>N(u.key,$.target.value)}),(i.secretsSet[u.key]||g)&&r.jsx("button",{type:"button",className:"tz-va__link",onClick:()=>g?n($=>{const X={...$};return delete X[u.key],X}):N(u.key,null),children:g?"Undo":"Clear"})]})}else L=r.jsxs(r.Fragment,{children:[r.jsx("input",{id:_,type:u.type==="number"?"number":"text",step:u.type==="number"?"any":void 0,list:u.suggestions?`${_}-list`:void 0,value:h[u.key]??"",onChange:g=>N(u.key,g.target.value)}),u.suggestions&&r.jsx("datalist",{id:`${_}-list`,children:u.suggestions.map(g=>r.jsx("option",{value:g},g))})]});return r.jsxs("div",{className:`tz-va__field${b?" tz-va__field--missing":""}`,children:[r.jsxs("label",{htmlFor:_,children:[u.label,b&&r.jsx("em",{children:" — required"})]}),L,u.hint&&r.jsx("small",{children:u.hint})]},u.key)}return r.jsxs(r.Fragment,{children:[r.jsxs("section",{className:"tz-va__card tz-va__settings",children:[E.length>0&&r.jsxs("div",{className:"tz-va__notice",role:"alert",children:[r.jsx("strong",{children:"Setup incomplete:"})," ",E.map(u=>u.message).join(" ")]}),Oe.map(u=>r.jsxs("fieldset",{children:[r.jsx("legend",{children:u.group}),u.fields.filter(_=>Rt(_,h)).map(C)]},u.group)),r.jsxs("p",{className:"tz-va__note",children:["Saved to ",r.jsx("code",{children:i.file})," and applied immediately. Environment variables provide the initial values."]}),r.jsxs("div",{className:"tz-va__actions",children:[r.jsx("button",{type:"button",disabled:f||!M,onClick:()=>T(o,"Settings saved and applied."),children:"Save"}),r.jsx("button",{type:"button",className:"tz-va__secondary",disabled:!M,onClick:()=>n({}),children:"Discard"}),r.jsx("span",{className:"tz-va__spacer"}),r.jsx("button",{type:"button",className:"tz-va__secondary",onClick:()=>{var u;return(u=y.current)==null?void 0:u.click()},children:"Import…"}),r.jsx("button",{type:"button",className:"tz-va__secondary",onClick:V,children:"Export"}),r.jsx("input",{ref:y,type:"file",accept:"application/json,.json",hidden:!0,onChange:D})]}),c&&r.jsx("p",{className:`tz-va__status tz-va__status--${c.kind}`,children:c.text})]}),a&&r.jsx("div",{className:"tz-va__actions",children:r.jsx("button",{type:"button",className:"tz-va__secondary",onClick:a,children:"← Back to chat"})})]})}const nt=(e,s)=>e==="webgpu"&&(s==="q4"||s==="q8")?"fp32":s,Te=e=>e>=1e3?`${(e/1e3).toFixed(1)} s`:`${e} ms`,qe=e=>`${(e/1048576).toFixed(0)} MB`;function Ot(e){switch(e.ttsProvider){case"openai":return`OpenAI · ${e.openaiTtsModel} · ${e.ttsVoice}`;case"elevenlabs":return`ElevenLabs · ${e.elevenlabsTtsModel} · ${e.ttsVoice}`;case"webspeech":return`Web Speech API · rate ${e.ttsSpeechRate} · pitch ${e.ttsSpeechPitch}`;case"server-kokoro":return`Kokoro (server) · ${e.ttsVoice} · ${e.kokoroDtype}/${e.kokoroDevice}`;default:return`Kokoro (browser) · ${e.ttsVoice} · ${nt(e.kokoroBrowserDevice,e.kokoroDtype)}/${e.kokoroBrowserDevice}`}}const zt=e=>e.replace(/\b\w/g,s=>s.toUpperCase());function Dt({apiBase:e="/api",title:s="Voice Assistant",showInfo:a=!0,systemPrompt:i,className:t=""}={}){const{chat:o,info:n,config:c,memory:l,llmProgress:f,llmPhase:d,localLlmBlocked:y,loadLocalModelAnyway:m,note:h,loading:x,missing:E,warnings:W,safeMode:M,retryFullLoad:N,reload:T}=Ze({apiBase:e,systemPrompt:i}),[V,D]=p.useState("chat"),{status:U,progress:C,error:u,transcript:_,streamingMessage:b,micEnabled:L,startListening:g,stopListening:R,submitText:$,liveAnalyser:X,devices:ie,selectedMicId:J,setSelectedMicId:te}=o,[Q,K]=p.useState(""),F=p.useRef(null);p.useEffect(()=>{var k;(k=F.current)==null||k.scrollIntoView({behavior:b!==null?"auto":"smooth"})},[_,b]);const A=n&&c.whisperDevice&&[["STT",c.sttProvider==="none"||!o.micAvailable?"off — no microphone on this page":n.sttProvider==="elevenlabs"?`ElevenLabs · ${n.elevenlabsSttModel}`:n.sttProvider==="openai"?`OpenAI · ${n.openaiSttModel}`:`Whisper · ${(c.whisperModel||n.whisperModel).split("/").pop()} · ${nt(c.whisperDevice,c.whisperDtype)}/${c.whisperDevice}`],["TTS",Ot({...n,...c})],["Chat",n.chatProvider==="local"&&y?"in-browser model not loaded on phones":n.chatProvider==="local"&&M?"in-browser model switched off (safe mode)":n.chatProvider==="local"?"SmolLM2-360M-Instruct (in-browser) — slow and simple":n.chatReady?`${n.chatProvider} · ${n.chatModel}`:"not configured"],["Memory",[l.browser!=null?`browser heap ${qe(l.browser)}`:"browser heap n/a",l.server!=null?`server ${qe(l.server)}`:null].filter(Boolean).join(" · ")]];return r.jsxs("div",{className:`tz-va ${t}`.trim(),children:[r.jsxs("section",{className:"tz-va__card tz-va__header",children:[r.jsx("h1",{children:s}),r.jsxs("span",{className:"tz-va__header-right",children:[r.jsx("span",{className:`tz-va__chip tz-va__chip--${U}`,children:zt(U)}),r.jsx("button",{type:"button",className:`tz-va__gear${V==="settings"?" tz-va__gear--on":""}`,"aria-label":"Settings",title:"Settings",onClick:()=>D(k=>k==="settings"?"chat":"settings"),children:r.jsxs("svg",{viewBox:"0 0 24 24",width:"18",height:"18",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("circle",{cx:"12",cy:"12",r:"3"}),r.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h0a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51h0a1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v0a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})})]})]}),W.length>0&&V!=="settings"&&r.jsxs("section",{className:"tz-va__card tz-va__notice tz-va__notice--info",role:"status",children:[r.jsx("div",{children:W.map((k,v)=>r.jsx("p",{children:k},v))}),M&&r.jsx("button",{type:"button",onClick:N,children:"Retry full load"}),y&&r.jsx("button",{type:"button",onClick:m,children:"Load it anyway"})]}),E.length>0&&V!=="settings"&&r.jsxs("section",{className:"tz-va__card tz-va__notice",role:"alert",children:[r.jsxs("div",{children:[r.jsx("strong",{children:"Setup incomplete."})," ",E.map(k=>k.message).join(" ")]}),r.jsx("button",{type:"button",onClick:()=>D("settings"),children:"Open Settings"})]}),V==="settings"?r.jsx(tt,{apiBase:e,onSaved:T,onClose:()=>D("chat")}):r.jsxs(r.Fragment,{children:[a&&A&&r.jsx("section",{className:"tz-va__card tz-va__info",children:A.map(([k,v])=>r.jsxs("div",{className:"tz-va__info-row",children:[r.jsx("span",{className:"tz-va__info-label",children:k}),r.jsx("span",{className:"tz-va__info-value",children:v})]},k))}),r.jsxs("section",{className:"tz-va__card",children:[x&&r.jsxs("div",{className:"tz-va__progress",children:[c.sttProvider==="whisper"&&o.micAvailable&&r.jsxs("label",{children:["Whisper STT",r.jsx("div",{className:"tz-va__bar",children:r.jsx("span",{style:{width:`${C.whisper*100}%`}})})]}),r.jsxs("label",{children:["Kokoro TTS",r.jsx("div",{className:"tz-va__bar",children:r.jsx("span",{style:{width:`${C.kokoro*100}%`}})})]}),(f>0||d==="waiting"||d==="loading")&&r.jsxs("label",{children:["Local LLM",r.jsx("div",{className:"tz-va__bar",children:r.jsx("span",{style:{width:`${f*100}%`}})})]})]}),r.jsx("div",{className:"tz-va__button",children:r.jsx(He,{status:U,active:L,loading:x,analyser:X,onToggle:L?R:g,devices:ie,selectedMicId:J,onDeviceChange:te,inputData:Q,sendData:k=>{K(""),$(k)}})}),r.jsx("div",{className:"tz-va__input-row",children:r.jsx("input",{type:"text",className:"tz-va__input",value:Q,onChange:k=>K(k.target.value),onKeyDown:k=>{k.key==="Enter"&&Q.trim()&&(K(""),$(Q))},placeholder:"Type a message…",disabled:x})}),r.jsx("p",{className:"tz-va__note",children:x?C.kokoro<1?"Loading Kokoro TTS…":C.whisper<1?"Loading Whisper STT…":f>0&&f<1?"Loading local LLM (SmolLM2-360M, ~200 MB)…":d==="waiting"?"Speech is ready — starting the in-browser chat model next…":d==="loading"?"Starting the in-browser chat model…":"Finishing up…":"Ready."}),h&&r.jsx("p",{className:"tz-va__note",children:h})]}),r.jsxs("section",{className:"tz-va__card tz-va__transcript",children:[_.map(k=>r.jsxs("div",{className:`tz-va__message tz-va__message--${k.role}`,children:[r.jsx("small",{children:k.role==="user"?"You":"Assistant"}),r.jsx("p",{children:k.content}),k.timings&&r.jsxs("div",{className:"tz-va__timings",children:[k.timings.transcribeMs!=null&&r.jsxs("span",{children:["transcribe ",Te(k.timings.transcribeMs)]}),k.timings.thinkMs!=null&&r.jsxs("span",{children:["think ",Te(k.timings.thinkMs)]}),k.timings.ttsMs!=null&&r.jsxs("span",{children:["tts ",Te(k.timings.ttsMs)]})]})]},k.id)),b!==null&&r.jsxs("div",{className:"tz-va__message tz-va__message--assistant tz-va__message--streaming",children:[r.jsx("small",{children:"Assistant"}),r.jsxs("p",{children:[b,r.jsx("span",{className:"tz-va__cursor"})]})]}),r.jsx("div",{ref:F})]}),u?r.jsxs("section",{className:"tz-va__card",children:[r.jsx("strong",{children:"Error:"}),r.jsx("p",{children:u})]}):null]})]})}class Ct extends p.Component{constructor(s){super(s),this.state={error:null}}static getDerivedStateFromError(s){return{error:s}}componentDidCatch(s,a){console.error("[tz-voice-chat]",s,a==null?void 0:a.componentStack)}render(){var s;return this.state.error?r.jsx("div",{className:`tz-va ${this.props.className||""}`.trim(),children:r.jsxs("section",{className:"tz-va__card tz-va__notice",role:"alert",children:[r.jsxs("div",{children:[r.jsx("strong",{children:"Something went wrong."})," ",String(((s=this.state.error)==null?void 0:s.message)||this.state.error)]}),r.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:"Reload"})]})}):this.props.children}}function $t(e){return r.jsx(Ct,{className:e==null?void 0:e.className,children:r.jsx(Dt,{...e})})}exports.AIAssistantButton=He;exports.SETTINGS_SCHEMA=Oe;exports.STATES=z;exports.SettingsPanel=tt;exports.TZVoiceChat=Ge;exports.VoiceAssistant=$t;exports.computeMissing=et;exports.createLocalChatStream=Je;exports.sendChatRequest=Ye;exports.useVoiceAssistant=Ze;