tz-voice-chat 1.2.1 → 1.3.0

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.
package/README.md CHANGED
@@ -14,7 +14,7 @@ Microphone → VAD → speech-to-text → your chat logic (or an LLM) → text-t
14
14
  |---|---|---|
15
15
  | Speech-to-text | Whisper in the browser | OpenAI transcription, ElevenLabs Scribe |
16
16
  | Chat | In-browser SmolLM2 (slow and simple), any OpenAI-compatible server (Ollama, LM Studio, vLLM, on-premise) | OpenRouter, OpenAI, Anthropic (Claude), Hugging Face |
17
- | Text-to-speech | Kokoro (browser or server), Web Speech API | OpenAI, ElevenLabs |
17
+ | Text-to-speech | Kokoro (browser or server), Web Speech API, any OpenAI-compatible TTS server (e.g. Piper) | OpenAI, ElevenLabs |
18
18
 
19
19
  ## Contents
20
20
 
@@ -109,7 +109,7 @@ Then open `https://192.168.1.50:4007` on the phone. The phone must trust mkcert'
109
109
  │ server-to-server — the keys are attached here
110
110
  ┌─ PROVIDERS ──────────────────────────────────────────────────────────────────────┐
111
111
  │ Chat OpenAI · Anthropic · OpenRouter · Hugging Face · Ollama/LM Studio/vLLM │
112
- │ STT OpenAI · ElevenLabs TTS OpenAI · ElevenLabs · Kokoro (server) │
112
+ │ STT OpenAI · ElevenLabs TTS OpenAI · ElevenLabs · Kokoro (server) · OpenAI-compatible │
113
113
  │ Models huggingface.co (reached only through /models/*) │
114
114
  └──────────────────────────────────────────────────────────────────────────────────┘
115
115
  ```
@@ -137,7 +137,7 @@ The browser can do speech recognition, speech synthesis and even a small LLM by
137
137
  | **One streaming format** | Anthropic streams differently from OpenAI. The server converts every chat provider to the same OpenAI-style event stream, so the client has a single parser. |
138
138
  | **Model files** | `GET /models/*` proxies Hugging Face downloads through your origin (cacheable, mirrorable, works behind a firewall). The browser never talks to huggingface.co directly. |
139
139
  | **Runtime assets** | ONNX Runtime WASM files, the VAD model and the transformers/Kokoro bundles are loaded **by URL** at runtime, and must be same-origin. They ship inside the package (`vendor/`, about 62 MB — a ~16 MB download), and `createVendorRouter()` serves them at `/vendor/*`. Nothing is fetched from a CDN, and nothing native is installed. |
140
- | **Server-side speech** | `server-kokoro` runs Kokoro in Node, so browsers without WebGPU still get good TTS. OpenAI/ElevenLabs STT and TTS are proxied here too. |
140
+ | **Server-side speech** | `server-kokoro` runs Kokoro in Node, so browsers without WebGPU still get good TTS. OpenAI/ElevenLabs STT and TTS are proxied here too, as is any OpenAI-compatible TTS server (Piper, LocalAI, Kokoro-FastAPI…). |
141
141
  | **Persistent settings** | The Settings page saves to a file; the server applies changes live (and reloads server-side Kokoro when its parameters change). |
142
142
 
143
143
  **When you don't need it:** if everything runs in the browser (Whisper + Web Speech or Kokoro on WebGPU + a `processInput` that calls your own backend) you only have to serve `/vendor/*` and the model downloads yourself. The moment you use any cloud provider, the server is what keeps the key safe.
@@ -158,7 +158,7 @@ The browser can do speech recognition, speech synthesis and even a small LLM by
158
158
  ▼
159
159
  SENTENCE CHUNKER small first chunk (fast first audio), then whole sentences (natural prosody)
160
160
  ▼
161
- TEXT-TO-SPEECH queue ── Kokoro (browser) ─ Web Speech ─ or ── POST /api/tts ──▶ server Kokoro / OpenAI / ElevenLabs
161
+ TEXT-TO-SPEECH queue ── Kokoro (browser) ─ Web Speech ─ or ── POST /api/tts ──▶ server Kokoro / OpenAI / ElevenLabs / compatible
162
162
  │ audio clips are trimmed of silence and played back to back
163
163
  │ → timing "tts" = first sentence queued → audio starts
164
164
  ▼
@@ -208,7 +208,7 @@ tz-voice-chat
208
208
  ├── Server (import from 'tz-voice-chat/server')
209
209
  │ ├── createVoiceAssistantRouter() Express router: /config /settings /stats /chat /stt /tts /models/*
210
210
  │ │ ├── settings store defaults < env < options < saved file; secrets stay server-side
211
- │ │ └── adapters chat (OpenAI-compatible · Anthropic) · stt (OpenAI · ElevenLabs) · tts (Kokoro · OpenAI · ElevenLabs)
211
+ │ │ └── adapters chat (OpenAI-compatible · Anthropic) · stt (OpenAI · ElevenLabs) · tts (Kokoro · OpenAI · OpenAI-compatible · ElevenLabs)
212
212
  │ └── createVendorRouter() /vendor/* — ONNX runtime, VAD, transformers, Kokoro (from node_modules)
213
213
  │
214
214
  └── CLI `tz-voice-chat` server + vendor assets + prebuilt web page, in one command
@@ -560,7 +560,7 @@ The pipeline hook. Returns the state and controls below. Option changes re-initi
560
560
  | `whisperModel` | `'onnx-community/whisper-tiny.en'` | Hugging Face model id |
561
561
  | `whisperDtype` | `'q8'` | `'q4'` · `'q8'` · `'fp16'` · `'fp32'` (q4/q8 are promoted to fp32 on WebGPU) |
562
562
  | `whisperDevice` | `'wasm'` | `'wasm'` (CPU) or `'webgpu'` (`'cpu'` is accepted as an alias for `'wasm'`) |
563
- | `ttsProvider` | `'server-kokoro'` | `'kokoro'` (browser) · `'server-kokoro'` · `'openai'` · `'elevenlabs'` · `'webspeech'`; every value except `kokoro` and `webspeech` posts to `ttsServerUrl` |
563
+ | `ttsProvider` | `'server-kokoro'` | `'kokoro'` (browser) · `'server-kokoro'` · `'openai'` · `'openai-compatible'` · `'elevenlabs'` · `'webspeech'`; every value except `kokoro` and `webspeech` posts to `ttsServerUrl` |
564
564
  | `ttsVoice` | `'af_bella'` | Voice name / id for the provider |
565
565
  | `ttsSpeed` | `1` | Kokoro speech-rate multiplier |
566
566
  | `ttsServerUrl` | `'/api/tts'` | POST `{ text, voice }` → audio |
@@ -620,12 +620,26 @@ The Settings page. `onSaved` receives the saved result (call `reload()` there);
620
620
  | `GET /settings/export` | Every setting **including secrets**, as a download |
621
621
  | `POST /chat` | Body `{ messages }` → OpenAI-style SSE stream for any configured chat provider |
622
622
  | `POST /stt` | Body: a WAV file → `{ text }` (OpenAI or ElevenLabs) |
623
- | `POST /tts` | Body `{ text, voice? }` → audio (Kokoro WAV, or MP3 from OpenAI/ElevenLabs) |
623
+ | `POST /tts` | Body `{ text, voice? }` → audio (Kokoro WAV, or MP3/WAV from OpenAI, ElevenLabs or a compatible server) |
624
624
  | `GET /models/*` | Hugging Face model-file proxy |
625
625
  | `GET /stats` | Server memory (`rss`, `heapUsed`) |
626
626
 
627
627
  Also: `OPENAI_BASE_URL`, `ANTHROPIC_BASE_URL`, `ELEVENLABS_BASE_URL` override the vendor endpoints (proxies, gateways, test doubles).
628
628
 
629
+ ### Text-to-speech from your own server (Piper and others)
630
+
631
+ Choose **OpenAI-compatible server** under Text-to-speech and point it at any server that implements the OpenAI `POST /v1/audio/speech` protocol: the app sends `{ model, input, voice, response_format }` and plays back the audio that comes back. LocalAI and Kokoro-FastAPI speak this protocol, and so can an on-premise gateway (openedai-speech did too, but its README says it is obsolete and no longer updated). Set the base URL (for example `http://localhost:8000/v1`), the model name and the voice exactly as that server names them.
632
+
633
+ [Piper](https://github.com/OHF-Voice/piper1-gpl) has its own `/synthesize` API rather than the OpenAI one, so it cannot be used directly. The repository ships a ready-made adapter in [`examples/piper`](https://github.com/yuriyo/tz-voice-chat/tree/main/examples/piper): a `Dockerfile`, a `docker-compose.yml` and one Python file that serves `POST /v1/audio/speech` and downloads each voice the first time it is used.
634
+
635
+ ```sh
636
+ docker compose -f examples/piper/docker-compose.yml up -d --build
637
+ ```
638
+
639
+ (or without Compose: `docker build -t piper-openai examples/piper && docker run -d --name piper-openai -p 8000:8000 -v piper-voices:/voices piper-openai`.)
640
+
641
+ Nothing is downloaded at start: the first request for a voice downloads it (60–140 MB, a few seconds) into the volume and uses it, and every later request or restart is instant. Any [Piper voice](https://rhasspy.github.io/piper-samples) name works, and `GET /v1/models` lists them all. Then choose the "OpenAI-compatible server" provider with base URL `http://localhost:8000/v1` and a voice name from `GET /v1/models` as both model and voice, for example `en_US-lessac-high`. Piper and its espeak-ng phonemizer are GPL-licensed: they are installed when you build that image and run as a separate service, and nothing from them ships in this package. The example is not part of the npm package. From inside Docker use `host.docker.internal` instead of `localhost`.
642
+
629
643
  ### Settings reference
630
644
 
631
645
  Every setting can be set as an environment variable (initial value) or on the Settings page (saved to the settings file). Secrets are never sent to the browser.
@@ -673,6 +687,11 @@ Every setting can be set as an environment variable (initial value) or on the Se
673
687
  | `kokoroDevice` | `KOKORO_DEVICE` | `cpu` | `cpu` |
674
688
  | `openaiTtsModel` | `OPENAI_TTS_MODEL` | `tts-1` | |
675
689
  | `openaiTtsVoice` | `OPENAI_TTS_VOICE` | `alloy` | |
690
+ | `ttsCompatBaseUrl` | `TTS_COMPAT_BASE_URL` | `http://localhost:8000/v1` | Used when `ttsProvider` is `openai-compatible`. Must serve `POST /audio/speech`. |
691
+ | `ttsCompatModel` | `TTS_COMPAT_MODEL` | `tts-1` | Model name exactly as the server calls it (for Piper-style servers often the voice name). |
692
+ | `ttsCompatVoice` | `TTS_COMPAT_VOICE` | `alloy` | |
693
+ | `ttsCompatFormat` | `TTS_COMPAT_FORMAT` | — | `mp3`, `wav` or blank for the server default. |
694
+ | `ttsCompatApiKey` | `TTS_COMPAT_API_KEY` | — | Secret. Leave empty if the server needs no key. |
676
695
  | `elevenlabsVoiceId` | `ELEVENLABS_VOICE_ID` | `21m00Tcm4TlvDq8ikWAM` | Default is the premade "Rachel" voice. Copy another voice's ID from your ElevenLabs voice library. |
677
696
  | `elevenlabsTtsModel` | `ELEVENLABS_TTS_MODEL` | `eleven_flash_v2_5` | Flash is the lowest latency — best for voice chat |
678
697
  | `webSpeechVoice` | `WEBSPEECH_VOICE` | — | Exact voice name; blank = browser default |
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
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;
1
+ "use strict";var ct=Object.create;var De=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var dt=Object.getPrototypeOf,ht=Object.prototype.hasOwnProperty;var pt=(e,n,a,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of ut(n))!ht.call(e,s)&&s!==a&&De(e,s,{get:()=>n[s],enumerable:!(r=lt(n,s))||r.enumerable});return e};var $e=(e,n,a)=>(a=e!=null?ct(dt(e)):{},pt(n||!e||!e.__esModule?De(a,"default",{value:e,enumerable:!0}):a,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("react"),o=require("react/jsx-runtime");var ve=typeof document<"u"?document.currentScript:null;const Ie=60,ke=200;function We(){let e="",n=!0;function a(s,i,t){s.push(i),e=t,n=!1}function r(){const s=[];for(;;){const i=/([.!?]{1,3})(\s|$)/.exec(e);if(i){const t=e.slice(0,i.index+i[0].length).trim();if(t.length>=10){a(s,t,e.slice(i.index+i[0].length));continue}}if(n){if(e.length>=25){const t=/[,;:—–](\s|$)/.exec(e);if(t){const c=e.slice(0,t.index+t[0].length).trim();if(c.length>=20){a(s,c,e.slice(t.index+t[0].length));continue}}}if(e.length>=Ie){const t=e.lastIndexOf(" ",Ie-1),c=t>10?t:Ie;a(s,e.slice(0,c).trim(),e.slice(c).trimStart());continue}}else if(e.length>=ke){const t=e.slice(0,ke),c=Math.max(t.lastIndexOf(", "),t.lastIndexOf("; "),t.lastIndexOf(": ")),l=c>ke/2?c+1:t.lastIndexOf(" ")>10?t.lastIndexOf(" "):ke;a(s,e.slice(0,l).trim(),e.slice(l).trimStart());continue}break}return s}return{write(s){return e+=s,r()},flush(){const s=e.trim();return e="",s}}}const ft=/\.(onnx|onnx_data|safetensors|bin|ort)$/i;function Ue(e,{minBytes:n=1e6,cap:a=.99}={}){const r=new Map,s=(t,c)=>c>=n&&(ft.test(t)||c>=5e6);let i=0;return(t={})=>{const c=t.file||t.name;if(c&&s(c,t.total)){const v=t.status==="done"?t.total:t.loaded??(typeof t.progress=="number"?t.total*t.progress/100:0),y=r.get(c);r.set(c,{loaded:Math.max((y==null?void 0:y.loaded)??0,v),total:t.total})}else if(c&&t.status==="done"&&r.has(c)){const v=r.get(c);v.loaded=v.total}let l=0,p=0;for(const v of r.values())l+=v.loaded,p+=v.total;if(p<=0)return;const d=Math.min(a,l/p);d>i&&(i=d,e(i))}}const mt="tz-voice-chat-model-cache",vt=4*1024*1024;let Le=null;function yt(){return Le||(Le=new Promise((e,n)=>{const a=indexedDB.open(mt,1);a.onupgradeneeded=()=>{a.result.createObjectStore("meta"),a.result.createObjectStore("chunks")},a.onsuccess=()=>e(a.result),a.onerror=()=>n(a.error)})),Le}async function he(e,n,a){const r=await yt();return new Promise((s,i)=>{const t=r.transaction(e,n),c=a(t.objectStore(e));t.oncomplete=()=>s(c==null?void 0:c.result),t.onerror=t.onabort=()=>i(t.error)})}const Ve=e=>typeof e=="string"?e:e.url,Ne=(e,n)=>`${e}\0${n}`;async function Ke(e){const n=await he("meta","readonly",a=>a.get(e));if(n)for(let a=0;a<n.chunks;a++)await he("chunks","readwrite",r=>r.delete(Ne(e,a)));await he("meta","readwrite",a=>a.delete(e))}function gt(){return{async match(e){try{const n=Ve(e),a=await he("meta","readonly",i=>i.get(n));if(!a||!a.complete)return;let r=0;const s=new ReadableStream({async pull(i){if(r>=a.chunks){i.close();return}const t=await he("chunks","readonly",c=>c.get(Ne(n,r)));if(!t){i.error(new Error("model cache entry is incomplete"));return}i.enqueue(new Uint8Array(t)),r++}});return new Response(s,{status:200,headers:new Headers(a.headers)})}catch(n){console.warn("[tz-voice-chat] model cache read failed:",n);return}},async put(e,n){const a=Ve(e);try{await Ke(a);const r=n.body.getReader();let s=[],i=0,t=0,c=0;const l=async d=>{if(!i||!d&&i<vt)return;const v=new Uint8Array(i);let y=0;for(const h of s)v.set(h,y),y+=h.length;s=[],i=0,await he("chunks","readwrite",h=>h.put(v.buffer,Ne(a,t))),t++};for(;;){const{done:d,value:v}=await r.read();if(d)break;s.push(v),i+=v.length,c+=v.length,await l(!1)}await l(!0);const p=[];n.headers.forEach((d,v)=>{v!=="content-encoding"&&v!=="content-length"&&p.push([v,d])}),p.push(["content-length",String(c)]),await he("meta","readwrite",d=>d.put({complete:!0,chunks:t,size:c,headers:p},a))}catch(r){console.warn("[tz-voice-chat] could not cache a model file (continuing without):",r);try{await Ke(a)}catch{}}}}}function wt(e){return typeof caches<"u"||typeof indexedDB>"u"?!1:(e.useBrowserCache=!1,e.useCustomCache=!0,e.customCache=gt(),!0)}async function bt(e,{dtype:n="q8",device:a="cpu",modelProxyUrl:r="/api/models/"}={}){var v,y;const{env:s}=await import("/vendor/transformers/transformers.min.js");s.remoteHost=r,wt(s),(y=(v=s==null?void 0:s.backends)==null?void 0:v.onnx)!=null&&y.wasm&&(s.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),s!=null&&s.onnx&&(s.onnx.logSeverityLevel=3);const i=await import("/vendor/kokoro/kokoro.web.js"),{KokoroTTS:t}=i;let c=n;a==="webgpu"&&(n==="q4"||n==="q8")&&(console.warn(`[modelLoader] dtype "${n}" not supported on WebGPU — using "fp32".`),c="fp32");let l=Ue(h=>e==null?void 0:e("kokoro",h));async function p(h,b){return t.from_pretrained("onnx-community/Kokoro-82M-ONNX",{dtype:b,device:h,progress_callback:l})}let d;try{d=await p(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(b=>e==null?void 0:e("kokoro",b)),d=await p("wasm",n);else throw h}return e==null||e("kokoro",1),{kokoro:d}}function xe(e,n,{threshold:a=.01,padMs:r=25}={}){const{numberOfChannels:s,length:i,sampleRate:t}=n;let c=i,l=-1;for(let h=0;h<s;h++){const b=n.getChannelData(h);for(let x=0;x<i;x++)if(Math.abs(b[x])>a){x<c&&(c=x);break}for(let x=i-1;x>=0;x--)if(Math.abs(b[x])>a){x>l&&(l=x);break}}if(l<c)return n;const p=Math.round(r/1e3*t),d=Math.max(0,c-p),v=Math.min(i,l+1+p);if(d===0&&v===i)return n;const y=e.createBuffer(s,v-d,t);for(let h=0;h<s;h++)y.copyToChannel(n.getChannelData(h).subarray(d,v),h);return y}function kt(e,{voice:n="af_bella",speed:a=1,onPlayStart:r}={}){const s=new AudioContext,i=[];let t=!1,c=null,l=!1;async function p(y){if(y instanceof AudioBuffer)return xe(s,y);const h=(y==null?void 0:y.audio)??y;if(h instanceof ArrayBuffer)return xe(s,await s.decodeAudioData(h.slice(0)));if(h instanceof Float32Array){const b=(y==null?void 0:y.samplingRate)??24e3,x=s.createBuffer(1,h.length,b);return x.copyToChannel(h,0),xe(s,x)}throw new Error("Unsupported TTS payload")}async function d(y){await s.resume();const h=s.createBufferSource();return h.buffer=y,h.connect(s.destination),new Promise(b=>{h.onended=()=>{c===h&&(c=null),b()},c=h,h.start(),l||(l=!0,r==null||r())})}async function v(){if(!t){for(t=!0;i.length>0;){const y=i.shift();try{const h=await y;h&&await d(h)}catch(h){console.error("[TtsQueue]",h)}}t=!1}}return{enqueue(y){i.push(e.generate(y,{voice:n,speed:a}).then(p)),v()},cancel(){if(i.length=0,l=!1,c){try{c.stop()}catch{}c=null}},async finished(){for(;t||i.length>0;)await new Promise(y=>setTimeout(y,200))}}}function _t({voice:e="",speed:n=1,onPlayStart:a,onError:r,url:s="/api/tts"}={}){const i=new AudioContext,t=[];let c=!1,l=null,p=!1;async function d(h){const b={text:h};e&&(b.voice=e),n!==1&&(b.speed=n);const x=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!x.ok)throw new Error(`TTS ${x.status}: ${await x.text()}`);return xe(i,await i.decodeAudioData(await x.arrayBuffer()))}async function v(h){await i.resume();const b=i.createBufferSource();return b.buffer=h,b.connect(i.destination),new Promise(x=>{b.onended=()=>{l===b&&(l=null),x()},l=b,b.start(),p||(p=!0,a==null||a())})}async function y(){if(!c){for(c=!0;t.length>0;){const h=t.shift();try{await v(await h)}catch(b){console.error("[ServerTTS]",b),r==null||r((b==null?void 0:b.message)||"Text-to-speech failed.")}}c=!1}}return{enqueue(h){h!=null&&h.trim()&&(t.push(d(h)),y())},cancel(){if(t.length=0,l){try{l.stop()}catch{}l=null}p=!1},async finished(){for(;c||t.length>0;)await new Promise(h=>setTimeout(h,100))}}}function xt({voice:e="",rate:n=1,pitch:a=1,onPlayStart:r}={}){const s=[];let i=!1,t=!1;function c(){return e?speechSynthesis.getVoices().find(d=>d.name===e||d.voiceURI===e)??null:null}function l(){if(i||s.length===0)return;i=!0;const p=s.shift(),d=new SpeechSynthesisUtterance(p),v=c();v&&(d.voice=v),d.rate=n,d.pitch=a,d.onstart=()=>{t||(t=!0,r==null||r())},d.onend=()=>{i=!1,l()},d.onerror=y=>{console.error("[WebSpeech TTS] error",y.error),i=!1,l()},speechSynthesis.speak(d)}return{enqueue(p){p!=null&&p.trim()&&(s.push(p),l())},cancel(){s.length=0,speechSynthesis.cancel(),i=!1,t=!1},async finished(){for(;i||s.length>0;)await new Promise(p=>setTimeout(p,100))}}}async function St({onSpeechStart:e,onSpeechEnd:n,onError:a,deviceId:r}){try{const{MicVAD:s}=window.vad;return await s.new({model:"legacy",baseAssetPath:"/vendor/vad/",onnxWASMBasePath:"/vendor/ort/",additionalAudioConstraints:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!1,...r?{deviceId:{exact:r}}:{}},onSpeechStart:()=>e==null?void 0:e(),onSpeechEnd:t=>{console.log("[VAD] onSpeechEnd — samples:",t==null?void 0:t.length),n==null||n(t)},onVADMisfire:()=>{},negativeSpeechThreshold:.25,positiveSpeechThreshold:.5,redemptionFrames:4,minSpeechFrames:3,preSpeechPadFrames:1})}catch(s){throw a==null||a("VAD initialization failed. Falling back to manual microphone capture."),s}}function At(e,n=16e3){const a=e.length*2,r=new ArrayBuffer(44+a),s=new DataView(r),i=(t,c)=>{for(let l=0;l<c.length;l++)s.setUint8(t+l,c.charCodeAt(l))};i(0,"RIFF"),s.setUint32(4,36+a,!0),i(8,"WAVE"),i(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,1,!0),s.setUint32(24,n,!0),s.setUint32(28,n*2,!0),s.setUint16(32,2,!0),s.setUint16(34,16,!0),i(36,"data"),s.setUint32(40,a,!0);for(let t=0,c=44;t<e.length;t++,c+=2){const l=Math.max(-1,Math.min(1,e[t]));s.setInt16(c,l<0?l*32768:l*32767,!0)}return new Blob([r],{type:"audio/wav"})}const C={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:n=Et,ttsProvider:a="server-kokoro",ttsVoice:r="af_bella",ttsSpeed:s=1,ttsServerUrl:i="/api/tts",ttsSpeechRate:t=1,ttsSpeechPitch:c=1,sttProvider:l="whisper",sttServerUrl:p="/api/stt",whisperModel:d="onnx-community/whisper-tiny.en",whisperDtype:v="q8",whisperDevice:y="wasm",kokoroDtype:h="q8",kokoroBrowserDevice:b="wasm",modelProxyUrl:x="/api/models/"}={}){const[W,L]=f.useState(C.IDLE),[N,M]=f.useState(!0),[V,z]=f.useState({whisper:0,kokoro:0}),[U,D]=f.useState(null),[u,S]=f.useState([]),[k,j]=f.useState(null),[m,O]=f.useState(!1),[$,X]=f.useState(""),[ie,J]=f.useState([]),[te,Q]=f.useState(null),K=f.useRef(C.IDLE),F=f.useRef(!1),E=f.useRef(null),_=f.useRef(null),g=f.useRef(null),I=f.useRef(null),B=f.useRef(null),ye=f.useRef(null),se=f.useRef([{role:"system",content:n}]),pe=f.useRef(e),ce=f.useRef(0),H=f.useRef({id:null,enqueuedAt:null,ttsMs:null}),le=f.useRef(1),Z=f.useRef({provider:l,url:p});Z.current={provider:l,url:p},f.useEffect(()=>{se.current=[{role:"system",content:n},...se.current.slice(1)]},[n]),f.useEffect(()=>{K.current=W},[W]),f.useEffect(()=>{F.current=m},[m]),f.useEffect(()=>{pe.current=e},[e]),f.useEffect(()=>{const T=navigator.mediaDevices;if(!T)return;async function R(){try{const w=await T.enumerateDevices();J(w.filter(P=>P.kind==="audioinput"))}catch{}}return R(),T.addEventListener("devicechange",R),()=>T.removeEventListener("devicechange",R)},[m]),f.useEffect(()=>{let T=!1;M(!0),z({whisper:0,kokoro:0});async function R(){try{const w=()=>{var q;const A=H.current;A.enqueuedAt!=null&&A.ttsMs==null&&(A.ttsMs=Math.round(performance.now()-A.enqueuedAt),A.id!=null&&ue(A.id,{timings:{ttsMs:A.ttsMs}})),a==="webspeech"&&((q=_.current)==null||q.pause())};if(a==="webspeech")E.current=xt({voice:r,rate:t,pitch:c,onPlayStart:w}),z(A=>({...A,kokoro:1}));else if(a==="kokoro"){const{kokoro:A}=await bt((q,ee)=>z(fe=>({...fe,[q]:ee})),{dtype:h,device:b,modelProxyUrl:x});if(T)return;E.current=kt(A,{voice:r,speed:s,onPlayStart:w})}else E.current=_t({voice:r,speed:s,onPlayStart:w,url:i,onError:A=>D(A)}),z(A=>({...A,kokoro:1}));if(T)return;const P=typeof navigator>"u"||!navigator.mediaDevices;if(l==="server"||l==="none"||P){I.current=null,z(A=>({...A,whisper:1})),M(!1);return}I.current=new Worker(new URL("./assets/whisperWorker-rOnua0b5.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ve&&ve.tagName.toUpperCase()==="SCRIPT"&&ve.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),I.current.onmessage=A=>{A.data.type==="transcript"?ge(A.data.text,{transcribeMs:Math.round(performance.now()-ce.current)}):A.data.type==="progress"?z(q=>({...q,whisper:A.data.progress})):A.data.type==="ready"?(z(q=>({...q,whisper:1})),M(!1)):A.data.type==="error"&&(D(`Whisper: ${A.data.message}`),M(!1))},I.current.onerror=()=>{D("Model load failed. Check WebGPU/WASM browser support."),M(!1)},I.current.postMessage({type:"init",model:d,dtype:v,device:y,modelProxyUrl:x})}catch(w){T||(D("Initialisation failed: "+((w==null?void 0:w.message)??String(w))),M(!1))}}return R(),()=>{var w,P;T=!0,(w=I.current)==null||w.terminate(),(P=E.current)==null||P.cancel()}},[a,r,s,t,c,i,l,p,d,v,y,h,b]);function ne(T,R,w){const P=le.current++;return S(A=>[...A,{id:P,role:T,content:R,timings:w,time:new Date().toISOString()}]),P}function ue(T,{timings:R}){S(w=>w.map(P=>P.id===T?{...P,timings:{...P.timings,...R}}:P))}async function Ae(T){const R=ce.current;try{const w=await fetch(Z.current.url,{method:"POST",headers:{"Content-Type":"audio/wav"},body:At(T,16e3)});if(!w.ok)throw new Error(`Speech-to-text failed: ${w.status} ${await w.text()}`);const{text:P}=await w.json();await ge(P,{transcribeMs:Math.round(performance.now()-R)})}catch(w){D(w.message||"Speech-to-text failed."),L(F.current?C.LISTENING:C.IDLE)}}async function ge(T,{transcribeMs:R}={}){if(!(T!=null&&T.trim())){L(F.current?C.LISTENING:C.IDLE);return}L(C.THINKING),ne("user",T,R!=null?{transcribeMs:R}:void 0);const w=[...se.current,{role:"user",content:T}];se.current=w,await Ee(T,w)}async function Ee(T,R){var w,P,A,q;(w=g.current)==null||w.abort(),g.current=new AbortController,(P=E.current)==null||P.cancel();try{if(!pe.current)throw new Error("processInput is not provided");const ee=We();let fe="",Te=!1,Pe=null;const rt=performance.now(),me={id:null,enqueuedAt:null,ttsMs:null};H.current=me;const Ce=be=>{var je;me.enqueuedAt==null&&(me.enqueuedAt=performance.now()),(je=E.current)==null||je.enqueue(be)};j("");for await(const be of pe.current(T,R,g.current.signal))Pe==null&&(Pe=Math.round(performance.now()-rt)),fe+=be,j(fe),ee.write(be).forEach(it=>{Te||(Te=!0,L(C.SPEAKING)),Ce(it)});const ze=ee.flush();ze&&(Te||L(C.SPEAKING),Ce(ze)),me.id=ne("assistant",fe,{thinkMs:Pe,...me.ttsMs!=null?{ttsMs:me.ttsMs}:{}}),j(null),se.current=[...se.current,{role:"assistant",content:fe}],await((A=E.current)==null?void 0:A.finished()),a==="webspeech"&&((q=_.current)==null||q.start())}catch(ee){j(null),ee.name!=="AbortError"&&D(ee.message||"Processing failed.")}finally{L(F.current?C.LISTENING:C.IDLE)}}async function st(){var T,R;if(D(null),!navigator.mediaDevices){D("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===C.SPEAKING&&((T=E.current)==null||T.cancel(),(R=g.current)==null||R.abort());try{L(C.LISTENING),O(!0);try{const w=await navigator.mediaDevices.getUserMedia({audio:$?{deviceId:{exact:$}}:!0,video:!1});ye.current=w;const P=new AudioContext;B.current=P;const A=P.createAnalyser();A.fftSize=256,P.createMediaStreamSource(w).connect(A),Q(A)}catch(w){console.warn("[TZVoiceChat] waveform analyser unavailable:",w)}_.current=await St({onSpeechStart:()=>{var w,P;a==="webspeech"&&K.current===C.SPEAKING||(K.current===C.SPEAKING&&((w=E.current)==null||w.cancel(),(P=g.current)==null||P.abort()),L(C.LISTENING))},onSpeechEnd:w=>{var P;a==="webspeech"&&K.current===C.SPEAKING||(L(C.TRANSCRIBING),ce.current=performance.now(),Z.current.provider==="server"?Ae(w):(P=I.current)==null||P.postMessage({type:"transcribe",audio:w},[w.buffer]))},onError:w=>{D(w),L(C.IDLE)},deviceId:$||void 0})}catch(w){console.error("[TZVoiceChat] startListening failed:",w),D("Microphone access failed. Allow audio permissions and refresh."),L(C.IDLE),O(!1)}}function ot(){var T,R,w,P,A;O(!1),(T=_.current)==null||T.destroy(),_.current=null,(R=ye.current)==null||R.getTracks().forEach(q=>q.stop()),ye.current=null,(w=B.current)==null||w.close(),B.current=null,Q(null),(P=E.current)==null||P.cancel(),(A=g.current)==null||A.abort(),L(C.IDLE)}function at(T){var A;if(!(T!=null&&T.trim()))return;L(C.SPEAKING);const R=We(),w=R.write(T),P=R.flush();[...w,...P?[P]:[]].forEach(q=>{var ee;return(ee=E.current)==null?void 0:ee.enqueue(q)}),(A=E.current)==null||A.finished().then(()=>{L(F.current?C.LISTENING:C.IDLE)})}return{status:W,loading:N,progress:V,error:U,transcript:u,streamingMessage:k,micAvailable:typeof navigator<"u"&&!!navigator.mediaDevices,micEnabled:m,startListening:st,stopListening:ot,speak:at,submitText:ge,liveAnalyser:te,devices:ie,selectedMicId:$,setSelectedMicId:X}}function Fe(e){const n=e.replace("#",""),a=n.length===3?n.split("").map(r=>r+r).join(""):n;return[parseInt(a.slice(0,2),16),parseInt(a.slice(2,4),16),parseInt(a.slice(4,6),16)]}function Tt(e,n,a){e/=255,n/=255,a/=255;const r=Math.max(e,n,a),s=Math.min(e,n,a),i=(r+s)/2;if(r===s)return[0,0,i*100];const t=r-s,c=i>.5?t/(2-r-s):t/(r+s);let l;switch(r){case e:l=((n-a)/t+(n<a?6:0))/6;break;case n:l=((a-e)/t+2)/6;break;default:l=((e-n)/t+4)/6}return[l*360,c*100,i*100]}function Pt(e,n,a){n/=100,a/=100;const r=t=>(t+e/30)%12,s=n*Math.min(a,1-a),i=t=>a-s*Math.max(-1,Math.min(r(t)-3,Math.min(9-r(t),1)));return[Math.round(i(0)*255),Math.round(i(8)*255),Math.round(i(4)*255)]}function Y(e,n){const[a,r,s]=Fe(e),[i,t,c]=Tt(a,r,s),[l,p,d]=Pt(i,t,Math.max(0,Math.min(100,c+n)));return`rgb(${l}, ${p}, ${d})`}function G(e,n){const[a,r,s]=Fe(e);return`rgba(${a}, ${r}, ${s}, ${n})`}function we(e,n){return e.replace("rgb(","rgba(").replace(")",`, ${n})`)}const _e=10;function jt({analyser:e}){const n=f.useRef(null),a=f.useRef(null);return f.useEffect(()=>{if(cancelAnimationFrame(a.current),!e)return;const r=n.current;if(!r)return;const s=r.getContext("2d"),i=e.frequencyBinCount,t=new Uint8Array(i),c=Math.max(1,Math.floor(i/_e)),l=getComputedStyle(r),p=+l.getPropertyValue("--bar-hue"),d=+l.getPropertyValue("--bar-hue-range"),v=+l.getPropertyValue("--bar-sat"),y=+l.getPropertyValue("--bar-lit"),h=+l.getPropertyValue("--bar-lit-range"),b=()=>{a.current=requestAnimationFrame(b),e.getByteFrequencyData(t);const x=r.width,W=r.height;s.clearRect(0,0,x,W);const L=(x-(_e-1)*2)/_e;for(let N=0;N<_e;N++){const M=t[N*c]/255,V=Math.max(3,M*W*.88);s.fillStyle=`hsl(${p+M*d}, ${v}%, ${y+M*h}%)`,s.beginPath(),s.roundRect(N*(L+2),(W-V)/2,L,V,[2]),s.fill()}};return b(),()=>cancelAnimationFrame(a.current)},[e]),o.jsx("canvas",{ref:n,width:55,height:35,className:"ai-btn__canvas"})}function He({status:e="idle",active:n=!1,loading:a=!1,analyser:r=null,onToggle:s,devices:i=[],selectedMicId:t="",onDeviceChange:c,inputData:l="",sendData:p,accentColor:d="#f97316",uiColor:v="#64748b",size:y=70,barHue:h=25,barHueRange:b=20,barSat:x=88,barLit:W=65,barLitRange:L=20}){var j;const[N,M]=f.useState(!1),V=f.useRef(null);f.useEffect(()=>{if(!N)return;function m(O){var $;($=V.current)!=null&&$.contains(O.target)||M(!1)}return document.addEventListener("pointerdown",m),()=>document.removeEventListener("pointerdown",m)},[N]);function z(m){c==null||c(m),M(!1)}const U=f.useMemo(()=>{const m=Y(d,-8),O=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(v,-22),F=Y(v,-30),E=Y(v,18),_=Y(v,37);return{"--tz-size":`${y}px`,"--tz-a":d,"--tz-a-d8":m,"--tz-a-d15":O,"--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":v,"--tz-u-d22":K,"--tz-u-d30":F,"--tz-u-l18":E,"--tz-u-l37":_,"--tz-u-30":G(v,.3),"--tz-u-55":G(v,.55),"--tz-u-d30-a85":we(F,.85),"--tz-u-l18-a18":we(E,.18),"--tz-u-l18-a20":we(E,.2),"--tz-u-l18-a32":we(E,.32),"--tz-u-d22-a90":we(K,.9),"--bar-hue":h,"--bar-hue-range":b,"--bar-sat":x,"--bar-lit":W,"--bar-lit-range":L}},[d,v,y,h,b,x,W,L]),D=((j=i.find(m=>m.deviceId===t))==null?void 0:j.label)||(t?`Mic ${t.slice(0,6)}…`:"Default mic"),u=l.trim().length>0,S=u?"ready":n?e:"off";let k;return u?k=o.jsx("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:o.jsx("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})}):!n||e==="idle"?k=o.jsxs("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[o.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"}),o.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"}),o.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"?k=o.jsx(jt,{analyser:r}):e==="transcribing"?k=o.jsx("div",{className:"ai-btn__bars ai-btn__bars--transcribing",children:Array.from({length:7},(m,O)=>o.jsx("span",{style:{animationDelay:`${O*.1}s`}},O))}):e==="thinking"?k=o.jsxs("div",{className:"ai-btn__dots",children:[o.jsx("span",{}),o.jsx("span",{style:{animationDelay:"0.18s"}}),o.jsx("span",{style:{animationDelay:"0.36s"}})]}):e==="speaking"&&(k=o.jsx("div",{className:"ai-btn__bars ai-btn__bars--speaking",children:Array.from({length:7},(m,O)=>o.jsx("span",{style:{animationDelay:`${O*.11}s`}},O))})),o.jsxs("div",{className:"ai-btn-root",style:U,children:[o.jsxs("div",{className:`ai-btn-rings ai-btn-rings--${S}`,"aria-hidden":"true",children:[o.jsx("span",{className:"ai-ring ai-ring--1"}),o.jsx("span",{className:"ai-ring ai-ring--2"})]}),o.jsxs("button",{className:`ai-btn ai-btn--${S}`,disabled:a,onClick:u?()=>p==null?void 0:p(l):s,"aria-label":u?"Send message":n?"Stop assistant":"Start assistant","aria-pressed":u?void 0:n,children:[k,n&&!u&&o.jsx("span",{className:"ai-btn__hover-stop","aria-hidden":"true",children:"■"})]}),o.jsxs("div",{className:`ai-mic-sel${N?" open":""}`,ref:V,children:[o.jsxs("button",{className:"ai-mic-sel__trigger",onClick:()=>M(m=>!m),title:"Change microphone","aria-label":"Change microphone","aria-expanded":N,children:[o.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[o.jsx("path",{d:"M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4z"}),o.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"})]}),o.jsx("span",{className:"ai-mic-sel__label",children:D}),o.jsx("svg",{className:`ai-mic-sel__caret${N?" open":""}`,width:"9",height:"9",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:o.jsx("path",{d:"M12 16L4 8h16l-8 8z"})})]}),N&&o.jsxs("ul",{className:"ai-mic-sel__menu",role:"listbox","aria-label":"Select microphone",children:[o.jsx("li",{role:"option",className:`ai-mic-sel__option${t===""?" selected":""}`,onClick:()=>z(""),"aria-selected":t==="",children:"Default microphone"}),i.map(m=>o.jsx("li",{role:"option",className:`ai-mic-sel__option${t===m.deviceId?" selected":""}`,onClick:()=>z(m.deviceId),"aria-selected":t===m.deviceId,children:m.label||`Microphone ${m.deviceId.slice(0,8)}`},m.deviceId))]})]})]})}async function Ye(e,n,a="/api/chat"){var c;const r=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},signal:n,body:JSON.stringify({messages:e})});if(!r.ok){const l=await r.text();throw new Error(`Server error: ${r.status} ${l}`)}const s=(c=r.body)==null?void 0:c.getReader();if(!s){const l=await r.json();return{stream:async function*(){yield l.text}}}const i=new TextDecoder;let t="";return{stream:async function*(){var p,d,v;let l="";for(;;){const{value:y,done:h}=await s.read();if(h)break;t+=i.decode(y,{stream:!0});const b=t.split(`
2
+ `);t=b.pop();for(const x of b){const W=x.trim();if(!W.startsWith("data:"))continue;const L=W.slice(5).trimStart();if(L==="[DONE]")return;try{const M=(v=(d=(p=JSON.parse(L).choices)==null?void 0:p[0])==null?void 0:d.delta)==null?void 0:v.content;M&&(l&&/\w/.test(l)&&/\w/.test(M[0])&&(yield" "),l=M[M.length-1],yield M)}catch{}}}}}}function Je(e,n,a){return{stream:async function*(){const r=[];let s=null,i=!1,t="";const c=({data:p})=>{p.type==="token"?(r.push(p.text),s==null||s(),s=null):p.type==="done"&&(i=!0,s==null||s(),s=null)},l=()=>{i=!0,s==null||s(),s=null};e.addEventListener("message",c),a==null||a.addEventListener("abort",l),e.postMessage({type:"generate",messages:n});try{for(;!i||r.length>0;)if(r.length>0){const p=r.shift();t&&/\w/.test(t)&&/\w/.test(p[0])&&(yield" "),t=p[p.length-1],yield p}else await new Promise(p=>{s=p})}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",re={get(e){try{return JSON.parse(localStorage.getItem(e)||"null")}catch{return null}},set(e,n){try{localStorage.setItem(e,JSON.stringify(n))}catch{}}},ae=e=>re.set(Qe,{s:e,at:Date.now()}),Oe=()=>{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},It=()=>Oe()?2:3;function Lt(){var t;const e=Date.now(),n=re.get(Se),a=n&&!n.done&&e-n.at<10*60*1e3,r=a?((t=re.get(Qe))==null?void 0:t.s)??null:null,s=a?n.attempts+1:1,i=!!(n!=null&&n.safe)||s>=It();return re.set(Se,{attempts:n!=null&&n.safe?n.attempts:s,at:e,done:!1,safe:i}),ae("page started"),{attempts:s,lastStage:r,safe:i}}const Mt=()=>{const e=typeof location<"u"?new URLSearchParams(location.search).get("stagedLoad"):null;return e==="1"?!0:e==="0"?!1:Oe()};function Ze({apiBase:e="/api",systemPrompt:n}={}){const[a,r]=f.useState(!0),[s,i]=f.useState(0),[t,c]=f.useState(""),[l,p]=f.useState({}),[d,v]=f.useState(null),[y,h]=f.useState({}),[b,x]=f.useState(0),[W,L]=f.useState([]),[N,M]=f.useState(null),[V,z]=f.useState("idle"),U=f.useRef(null),D=f.useRef(null),u=f.useRef(null),S=f.useRef(null);S.current===null&&(S.current=Lt());const k=S.current,j=k.attempts,m=k.safe,[O,$]=f.useState(!1),X=f.useCallback(()=>x(E=>E+1),[]),ie=f.useCallback(()=>{re.set(Be,!0),x(E=>E+1)},[]);f.useEffect(()=>{let E=!1;c(""),i(0);async function _(){let g=null,I={};try{g=await(await fetch(`${e}/config`)).json(),v(g),I={ttsProvider:g.ttsProvider||"kokoro",ttsVoice:g.ttsProvider==="openai"?g.openaiTtsVoice||"alloy":g.ttsProvider==="openai-compatible"?g.ttsCompatVoice||"alloy":g.ttsProvider==="elevenlabs"?g.elevenlabsVoiceId:g.ttsProvider==="webspeech"?g.webSpeechVoice||"":g.kokoroVoice||"af_bella",ttsSpeed:g.kokoroSpeed??1,ttsServerUrl:`${e}/tts`,ttsSpeechRate:g.webSpeechRate??1,ttsSpeechPitch:g.webSpeechPitch??1,sttProvider:g.sttProvider==="elevenlabs"||g.sttProvider==="openai"?"server":"whisper",sttServerUrl:`${e}/stt`,whisperModel:g.whisperModel||"onnx-community/whisper-tiny.en",whisperDtype:g.whisperDtype||"q8",whisperDevice:g.whisperDevice||"wasm",kokoroDtype:g.kokoroDtype||"q8",kokoroBrowserDevice:g.kokoroBrowserDevice||"wasm",modelProxyUrl:`${e}/models/`,...g.systemPrompt?{systemPrompt:g.systemPrompt}:{}}}catch{I={ttsProvider:"kokoro",ttsServerUrl:`${e}/tts`,modelProxyUrl:`${e}/models/`}}if(E)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 pe=typeof navigator>"u"||!navigator.mediaDevices;if(pe&&(I={...I,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=[];!pe&&I.whisperDevice==="webgpu"&&(I={...I,whisperDevice:"wasm",whisperDtype:"q8"},H.push("speech recognition runs on the CPU (Whisper, q8)")),I.ttsProvider==="kokoro"&&I.kokoroBrowserDevice==="webgpu"&&(I={...I,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 ")}.`)}m?(I.sttProvider==="whisper"&&(I={...I,whisperModel:"onnx-community/whisper-tiny.en",whisperDtype:"q8",whisperDevice:"wasm"}),I.ttsProvider==="kokoro"&&(I={...I,ttsProvider:"webspeech",ttsVoice:""}),B.push(`This page restarted ${j} times before it finished loading — usually the device ran out of memory. `+(k.lastStage?`It had reached: ${k.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.")):k.attempts>=2&&k.lastStage&&B.push(`The page restarted before it finished loading (attempt ${k.attempts}); it had reached: ${k.lastStage}.`);const ce=(g==null?void 0:g.chatProvider)==="local"&&Oe()&&!m&&!re.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."),L(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".')},p(I),z("off"),r(!1);return}if((g==null?void 0:g.chatProvider)==="local"&&m){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".')},p(I),r(!1);return}if((g==null?void 0:g.chatProvider)==="local"){r(!0),c("Using SmolLM2-360M-Instruct locally in your browser — slow and simple; pick a cloud model in Settings for better answers.");const H=()=>{z("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:ve&&ve.tagName.toUpperCase()==="SCRIPT"&&ve.src||new URL("index.cjs",document.baseURI).href),{type:"module"});D.current=Z,Z.onmessage=ne=>{if(ne.data.type==="progress"){const ue=ne.data.progress??0;i(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"),i(1),U.current=async function*(ue,Ae,ge){const{stream:Ee}=Je(Z,Ae,ge);yield*Ee()},z("ready"),r(!1)):ne.data.type==="error"&&(z("error"),r(!1))},Z.onerror=()=>{z("error"),r(!1)},Z.postMessage({type:"init",modelProxyUrl:`${e}/models/`})};p(I),Mt()?(z("waiting"),ae("waiting for the speech models"),u.current=H):H();return}g!=null&&g.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.")},p(I),r(!1)}return _(),()=>{var g;E=!0,u.current=null,(g=D.current)==null||g.terminate(),D.current=null}},[e,b]);const J=Ge({processInput:async function*(E,_,g){U.current&&(yield*U.current(E,_,g))},...n?{systemPrompt:n}:{},...l});f.useEffect(()=>{M(l)},[l]),f.useEffect(()=>{if(u.current&&N===l&&!J.loading){const E=u.current;u.current=null,E()}},[N,l,J.loading]);const te=J.loading||a;f.useEffect(()=>{d&&!te&&(ae("ready"),re.set(Se,{attempts:m?k.attempts:0,at:Date.now(),done:!0,safe:m}))},[d,te,m,k.attempts]);const Q=f.useCallback(()=>{re.set(Se,{attempts:0,at:Date.now(),done:!0,safe:!1}),window.location.reload()},[]);f.useEffect(()=>{let E=!1;async function _(){const I={};typeof performance<"u"&&performance.memory&&(I.browser=performance.memory.usedJSHeapSize);try{const B=await fetch(`${e}/stats`);B.ok&&(I.server=(await B.json()).rss)}catch{}E||h(I)}_();const g=setInterval(_,3e3);return()=>{E=!0,clearInterval(g)}},[e]);const{micEnabled:K,stopListening:F}=J;return f.useEffect(()=>{if(!K)return;const E=_=>{_.key==="Escape"&&F()};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[K,F]),{chat:J,info:d,config:l,memory:y,llmProgress:s,note:t,loading:te,missing:(d==null?void 0:d.missing)??[],warnings:W,llmPhase:V,localLlmBlocked:O,loadLocalModelAnyway:ie,safeMode:m,retryFullLoad:Q,reload:X}}const Nt=["q8","q4","q4f16","fp16","fp32"],de="Local · free",oe="Cloud",Re=[{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",de],["openai-compatible","OpenAI-compatible server (Ollama, LM Studio, vLLM, on-premise…)",de],["openrouter","OpenRouter",oe],["openai","OpenAI",oe],["anthropic","Anthropic (Claude)",oe],["huggingface","Hugging Face",oe]]},{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",de],["openai","OpenAI transcription",oe],["elevenlabs","ElevenLabs Scribe",oe]]},{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",de],["server-kokoro","Kokoro on the server (needs: npm install kokoro-js)",de],["webspeech","Browser Web Speech API (built-in voices)",de],["openai-compatible","OpenAI-compatible server (Piper, LocalAI, Kokoro-FastAPI… any /audio/speech)",de],["openai","OpenAI TTS",oe],["elevenlabs","ElevenLabs",oe]]},{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:"ttsCompatBaseUrl",label:"TTS server base URL",type:"text",env:"TTS_COMPAT_BASE_URL",default:"http://localhost:8000/v1",showWhen:{ttsProvider:"openai-compatible"},suggestions:["http://localhost:8000/v1","http://localhost:8080/v1","http://localhost:8880/v1"],hint:"Must serve POST /audio/speech (the OpenAI text-to-speech protocol). From inside Docker use host.docker.internal instead of localhost."},{key:"ttsCompatModel",label:"TTS model name",type:"text",env:"TTS_COMPAT_MODEL",default:"tts-1",showWhen:{ttsProvider:"openai-compatible"},hint:"Exactly as the server names it — e.g. tts-1, or a Piper voice such as en_US-lessac-medium"},{key:"ttsCompatVoice",label:"TTS voice",type:"text",env:"TTS_COMPAT_VOICE",default:"alloy",showWhen:{ttsProvider:"openai-compatible"},hint:"Voice name the server understands (alloy, af_bella, a Piper voice…)"},{key:"ttsCompatFormat",label:"Audio format",type:"select",env:"TTS_COMPAT_FORMAT",default:"",showWhen:{ttsProvider:"openai-compatible"},options:[["","Server default"],["mp3","mp3"],["wav","wav (no encoding delay)"]]},{key:"ttsCompatApiKey",label:"TTS API key (optional)",type:"password",secret:!0,env:"TTS_COMPAT_API_KEY",showWhen:{ttsProvider:"openai-compatible"},hint:"Leave empty if the server needs no key (most local servers)."},{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=Re.flatMap(e=>e.fields);Object.fromEntries(Xe.map(e=>[e.key,e]));Xe.filter(e=>e.secret).map(e=>e.key);function Ot(e,n){const a=r=>Object.entries(r).every(([s,i])=>(Array.isArray(i)?i:[i]).includes(n[s]));return e.showWhenAny?e.showWhenAny.some(a):e.showWhen?a(e.showWhen):!0}function et(e,n={}){const a=[],r=t=>!!n[t],s=e.chatProvider;s||a.push({key:"chatProvider",message:"No chat model provider is configured.",scope:"chat"}),s==="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"})),e.ttsProvider==="openai-compatible"&&!e.ttsCompatBaseUrl&&a.push({key:"ttsCompatBaseUrl",message:"The OpenAI-compatible text-to-speech server URL is missing.",scope:"tts"});const i=[{key:"openrouterApiKey",name:"OpenRouter API key",uses:[s==="openrouter"&&["chat","chat"]]},{key:"anthropicApiKey",name:"Anthropic API key",uses:[s==="anthropic"&&["chat","chat"]]},{key:"huggingfaceApiKey",name:"Hugging Face token",uses:[s==="huggingface"&&["chat","chat"]]},{key:"openaiApiKey",name:"OpenAI API key",uses:[s==="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:t,name:c,uses:l}of i){const p=l.filter(Boolean);if(!p.length||r(t))continue;const d=p.some(y=>y[1]==="chat")?"chat":p[0][1],v=p.length===1&&p[0][0]==="chat"?`${c} is missing.`:`${c} (for ${p.map(y=>y[0]).join(", ").replace(/, ([^,]*)$/," and $1")}) is missing.`;a.push({key:t,message:v,scope:d})}return a}function tt({apiBase:e="/api",onSaved:n,onClose:a}){const[r,s]=f.useState(null),[i,t]=f.useState({}),[c,l]=f.useState(null),[p,d]=f.useState(!1),v=f.useRef(null),y=f.useCallback(async()=>{try{const u=await fetch(`${e}/settings`);if(!u.ok)throw new Error(await u.text());s(await u.json())}catch(u){l({kind:"error",text:`Could not load settings: ${u.message}`})}},[e]);if(f.useEffect(()=>{y()},[y]),!r)return o.jsx("section",{className:"tz-va__card",children:c?c.text:"Loading settings…"});const h={...r.values,...Object.fromEntries(Object.entries(i).filter(([,u])=>u!==null))},b={...r.secretsSet};for(const[u,S]of Object.entries(i))u in b&&(b[u]=S===null?!1:S?!0:b[u]);const x=et(h,b),W=new Set(x.map(u=>u.key)),L=Object.keys(i).length>0,N=(u,S)=>t(k=>({...k,[u]:S}));async function M(u,S){var k;d(!0);try{const j=await fetch(`${e}/settings`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!j.ok)throw new Error(await j.text());const m=await j.json();s(m),t({});const O=(k=m.ignored)!=null&&k.length?` Ignored unknown/invalid keys: ${m.ignored.join(", ")}.`:"";l({kind:"ok",text:S+O}),n==null||n(m)}catch(j){l({kind:"error",text:j.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 S=new Blob([JSON.stringify(await u.json(),null,2)],{type:"application/json"}),k=document.createElement("a");k.href=URL.createObjectURL(S),k.download="tz-voice-chat-settings.json",k.click(),URL.revokeObjectURL(k.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 z(u){var k;const S=(k=u.target.files)==null?void 0:k[0];if(u.target.value="",!!S)try{const j=JSON.parse(await S.text()),m=j&&typeof j.settings=="object"?j.settings:j;if(!m||typeof m!="object"||Array.isArray(m))throw new Error("not a settings object");await M({settings:m},`Imported ${S.name} and applied it.`)}catch(j){l({kind:"error",text:`Import failed: ${j.message}`})}}function U(u){const S=[];for(const[k,j,m]of u){const O=S[S.length-1],$=o.jsx("option",{value:k,children:j},k);m?O&&O.group===m?O.items.push($):S.push({group:m,items:[$]}):S.push($)}return S.map(k=>k.group?o.jsx("optgroup",{label:k.group,children:k.items},k.group):k)}function D(u){const S=`tz-va-set-${u.key}`,k=W.has(u.key);let j;if(u.type==="select")j=o.jsxs("select",{id:S,value:h[u.key]??"",onChange:m=>N(u.key,m.target.value),children:[U(u.options),u.allowCustom&&h[u.key]&&!u.options.some(([m])=>m===h[u.key])&&o.jsxs("option",{value:h[u.key],children:[h[u.key]," (custom)"]})]});else if(u.type==="textarea")j=o.jsx("textarea",{id:S,rows:4,value:h[u.key]??"",onChange:m=>N(u.key,m.target.value)});else if(u.type==="password"){const m=u.key in i,O=i[u.key]===null?"Will be cleared on save":r.secretsSet[u.key]?"Saved — type to replace":"Not set";j=o.jsxs("span",{className:"tz-va__secret",children:[o.jsx("input",{id:S,type:"password",autoComplete:"off",value:i[u.key]??"",placeholder:O,onChange:$=>N(u.key,$.target.value)}),(r.secretsSet[u.key]||m)&&o.jsx("button",{type:"button",className:"tz-va__link",onClick:()=>m?t($=>{const X={...$};return delete X[u.key],X}):N(u.key,null),children:m?"Undo":"Clear"})]})}else j=o.jsxs(o.Fragment,{children:[o.jsx("input",{id:S,type:u.type==="number"?"number":"text",step:u.type==="number"?"any":void 0,list:u.suggestions?`${S}-list`:void 0,value:h[u.key]??"",onChange:m=>N(u.key,m.target.value)}),u.suggestions&&o.jsx("datalist",{id:`${S}-list`,children:u.suggestions.map(m=>o.jsx("option",{value:m},m))})]});return o.jsxs("div",{className:`tz-va__field${k?" tz-va__field--missing":""}`,children:[o.jsxs("label",{htmlFor:S,children:[u.label,k&&o.jsx("em",{children:" — required"})]}),j,u.hint&&o.jsx("small",{children:u.hint})]},u.key)}return o.jsxs(o.Fragment,{children:[o.jsxs("section",{className:"tz-va__card tz-va__settings",children:[x.length>0&&o.jsxs("div",{className:"tz-va__notice",role:"alert",children:[o.jsx("strong",{children:"Setup incomplete:"})," ",x.map(u=>u.message).join(" ")]}),Re.map(u=>o.jsxs("fieldset",{children:[o.jsx("legend",{children:u.group}),u.fields.filter(S=>Ot(S,h)).map(D)]},u.group)),o.jsxs("p",{className:"tz-va__note",children:["Saved to ",o.jsx("code",{children:r.file})," and applied immediately. Environment variables provide the initial values."]}),o.jsxs("div",{className:"tz-va__actions",children:[o.jsx("button",{type:"button",disabled:p||!L,onClick:()=>M(i,"Settings saved and applied."),children:"Save"}),o.jsx("button",{type:"button",className:"tz-va__secondary",disabled:!L,onClick:()=>t({}),children:"Discard"}),o.jsx("span",{className:"tz-va__spacer"}),o.jsx("button",{type:"button",className:"tz-va__secondary",onClick:()=>{var u;return(u=v.current)==null?void 0:u.click()},children:"Import…"}),o.jsx("button",{type:"button",className:"tz-va__secondary",onClick:V,children:"Export"}),o.jsx("input",{ref:v,type:"file",accept:"application/json,.json",hidden:!0,onChange:z})]}),c&&o.jsx("p",{className:`tz-va__status tz-va__status--${c.kind}`,children:c.text})]}),a&&o.jsx("div",{className:"tz-va__actions",children:o.jsx("button",{type:"button",className:"tz-va__secondary",onClick:a,children:"← Back to chat"})})]})}const nt=(e,n)=>e==="webgpu"&&(n==="q4"||n==="q8")?"fp32":n,Me=e=>e>=1e3?`${(e/1e3).toFixed(1)} s`:`${e} ms`,qe=e=>`${(e/1048576).toFixed(0)} MB`;function Rt(e){switch(e.ttsProvider){case"openai":return`OpenAI · ${e.openaiTtsModel} · ${e.ttsVoice}`;case"openai-compatible":return`OpenAI-compatible server · ${e.ttsCompatModel} · ${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 Ct=e=>e.replace(/\b\w/g,n=>n.toUpperCase());function zt({apiBase:e="/api",title:n="Voice Assistant",showInfo:a=!0,systemPrompt:r,className:s=""}={}){const{chat:i,info:t,config:c,memory:l,llmProgress:p,llmPhase:d,localLlmBlocked:v,loadLocalModelAnyway:y,note:h,loading:b,missing:x,warnings:W,safeMode:L,retryFullLoad:N,reload:M}=Ze({apiBase:e,systemPrompt:r}),[V,z]=f.useState("chat"),{status:U,progress:D,error:u,transcript:S,streamingMessage:k,micEnabled:j,startListening:m,stopListening:O,submitText:$,liveAnalyser:X,devices:ie,selectedMicId:J,setSelectedMicId:te}=i,[Q,K]=f.useState(""),F=f.useRef(null);f.useEffect(()=>{var _;(_=F.current)==null||_.scrollIntoView({behavior:k!==null?"auto":"smooth"})},[S,k]);const E=t&&c.whisperDevice&&[["STT",c.sttProvider==="none"||!i.micAvailable?"off — no microphone on this page":t.sttProvider==="elevenlabs"?`ElevenLabs · ${t.elevenlabsSttModel}`:t.sttProvider==="openai"?`OpenAI · ${t.openaiSttModel}`:`Whisper · ${(c.whisperModel||t.whisperModel).split("/").pop()} · ${nt(c.whisperDevice,c.whisperDtype)}/${c.whisperDevice}`],["TTS",Rt({...t,...c})],["Chat",t.chatProvider==="local"&&v?"in-browser model not loaded on phones":t.chatProvider==="local"&&L?"in-browser model switched off (safe mode)":t.chatProvider==="local"?"SmolLM2-360M-Instruct (in-browser) — slow and simple":t.chatReady?`${t.chatProvider} · ${t.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 o.jsxs("div",{className:`tz-va ${s}`.trim(),children:[o.jsxs("section",{className:"tz-va__card tz-va__header",children:[o.jsx("h1",{children:n}),o.jsxs("span",{className:"tz-va__header-right",children:[o.jsx("span",{className:`tz-va__chip tz-va__chip--${U}`,children:Ct(U)}),o.jsx("button",{type:"button",className:`tz-va__gear${V==="settings"?" tz-va__gear--on":""}`,"aria-label":"Settings",title:"Settings",onClick:()=>z(_=>_==="settings"?"chat":"settings"),children:o.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:[o.jsx("circle",{cx:"12",cy:"12",r:"3"}),o.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"&&o.jsxs("section",{className:"tz-va__card tz-va__notice tz-va__notice--info",role:"status",children:[o.jsx("div",{children:W.map((_,g)=>o.jsx("p",{children:_},g))}),L&&o.jsx("button",{type:"button",onClick:N,children:"Retry full load"}),v&&o.jsx("button",{type:"button",onClick:y,children:"Load it anyway"})]}),x.length>0&&V!=="settings"&&o.jsxs("section",{className:"tz-va__card tz-va__notice",role:"alert",children:[o.jsxs("div",{children:[o.jsx("strong",{children:"Setup incomplete."})," ",x.map(_=>_.message).join(" ")]}),o.jsx("button",{type:"button",onClick:()=>z("settings"),children:"Open Settings"})]}),V==="settings"?o.jsx(tt,{apiBase:e,onSaved:M,onClose:()=>z("chat")}):o.jsxs(o.Fragment,{children:[a&&E&&o.jsx("section",{className:"tz-va__card tz-va__info",children:E.map(([_,g])=>o.jsxs("div",{className:"tz-va__info-row",children:[o.jsx("span",{className:"tz-va__info-label",children:_}),o.jsx("span",{className:"tz-va__info-value",children:g})]},_))}),o.jsxs("section",{className:"tz-va__card",children:[b&&o.jsxs("div",{className:"tz-va__progress",children:[c.sttProvider==="whisper"&&i.micAvailable&&o.jsxs("label",{children:["Whisper STT",o.jsx("div",{className:"tz-va__bar",children:o.jsx("span",{style:{width:`${D.whisper*100}%`}})})]}),o.jsxs("label",{children:["Kokoro TTS",o.jsx("div",{className:"tz-va__bar",children:o.jsx("span",{style:{width:`${D.kokoro*100}%`}})})]}),(p>0||d==="waiting"||d==="loading")&&o.jsxs("label",{children:["Local LLM",o.jsx("div",{className:"tz-va__bar",children:o.jsx("span",{style:{width:`${p*100}%`}})})]})]}),o.jsx("div",{className:"tz-va__button",children:o.jsx(He,{status:U,active:j,loading:b,analyser:X,onToggle:j?O:m,devices:ie,selectedMicId:J,onDeviceChange:te,inputData:Q,sendData:_=>{K(""),$(_)}})}),o.jsx("div",{className:"tz-va__input-row",children:o.jsx("input",{type:"text",className:"tz-va__input",value:Q,onChange:_=>K(_.target.value),onKeyDown:_=>{_.key==="Enter"&&Q.trim()&&(K(""),$(Q))},placeholder:"Type a message…",disabled:b})}),o.jsx("p",{className:"tz-va__note",children:b?D.kokoro<1?"Loading Kokoro TTS…":D.whisper<1?"Loading Whisper STT…":p>0&&p<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&&o.jsx("p",{className:"tz-va__note",children:h})]}),o.jsxs("section",{className:"tz-va__card tz-va__transcript",children:[S.map(_=>o.jsxs("div",{className:`tz-va__message tz-va__message--${_.role}`,children:[o.jsx("small",{children:_.role==="user"?"You":"Assistant"}),o.jsx("p",{children:_.content}),_.timings&&o.jsxs("div",{className:"tz-va__timings",children:[_.timings.transcribeMs!=null&&o.jsxs("span",{children:["transcribe ",Me(_.timings.transcribeMs)]}),_.timings.thinkMs!=null&&o.jsxs("span",{children:["think ",Me(_.timings.thinkMs)]}),_.timings.ttsMs!=null&&o.jsxs("span",{children:["tts ",Me(_.timings.ttsMs)]})]})]},_.id)),k!==null&&o.jsxs("div",{className:"tz-va__message tz-va__message--assistant tz-va__message--streaming",children:[o.jsx("small",{children:"Assistant"}),o.jsxs("p",{children:[k,o.jsx("span",{className:"tz-va__cursor"})]})]}),o.jsx("div",{ref:F})]}),u?o.jsxs("section",{className:"tz-va__card",children:[o.jsx("strong",{children:"Error:"}),o.jsx("p",{children:u})]}):null]})]})}class Dt extends f.Component{constructor(n){super(n),this.state={error:null}}static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n,a){console.error("[tz-voice-chat]",n,a==null?void 0:a.componentStack)}render(){var n;return this.state.error?o.jsx("div",{className:`tz-va ${this.props.className||""}`.trim(),children:o.jsxs("section",{className:"tz-va__card tz-va__notice",role:"alert",children:[o.jsxs("div",{children:[o.jsx("strong",{children:"Something went wrong."})," ",String(((n=this.state.error)==null?void 0:n.message)||this.state.error)]}),o.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:"Reload"})]})}):this.props.children}}function $t(e){return o.jsx(Dt,{className:e==null?void 0:e.className,children:o.jsx(zt,{...e})})}exports.AIAssistantButton=He;exports.SETTINGS_SCHEMA=Re;exports.STATES=C;exports.SettingsPanel=tt;exports.TZVoiceChat=Ge;exports.VoiceAssistant=$t;exports.computeMissing=et;exports.createLocalChatStream=Je;exports.sendChatRequest=Ye;exports.useVoiceAssistant=Ze;