tz-voice-chat 1.2.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +47 -6
- package/bin/tz-voice-chat.js +12 -1
- package/dist/assets/llmWorker-CmV-b4uq.js +1 -0
- package/dist/assets/whisperWorker-rOnua0b5.js +1 -0
- package/dist/index.cjs +2 -2
- package/dist/index.js +1014 -785
- package/dist/style.css +1 -1
- package/dist-app/assets/{index-BDMCgrF_.css → index-Bcmhe9G_.css} +1 -1
- package/dist-app/assets/index-Wcfqx97N.js +41 -0
- package/dist-app/assets/llmWorker-CmV-b4uq.js +1 -0
- package/dist-app/assets/whisperWorker-rOnua0b5.js +1 -0
- package/dist-app/index.html +2 -2
- package/package.json +1 -1
- package/server/run.js +17 -3
- package/dist/assets/llmWorker-CVEGn6yI.js +0 -1
- package/dist/assets/whisperWorker-D69IwlqW.js +0 -1
- package/dist-app/assets/index-CFWv17S2.js +0 -41
- package/dist-app/assets/llmWorker-CVEGn6yI.js +0 -1
- package/dist-app/assets/whisperWorker-D69IwlqW.js +0 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 yuriyo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -19,11 +19,12 @@ Microphone → VAD → speech-to-text → your chat logic (or an LLM) → text-t
|
|
|
19
19
|
## Contents
|
|
20
20
|
|
|
21
21
|
1. [Quick start](#quick-start)
|
|
22
|
-
2. [
|
|
23
|
-
3. [
|
|
24
|
-
4. [
|
|
25
|
-
5. [
|
|
26
|
-
6. [
|
|
22
|
+
2. [Use it from a phone or another computer](#use-it-from-a-phone-or-another-computer) — the microphone needs HTTPS
|
|
23
|
+
3. [Architecture overview](#architecture-overview) — the big picture, **why a server is needed**, one conversation turn, the state machine
|
|
24
|
+
4. [Components](#components) — what each piece does and where it lives
|
|
25
|
+
5. [Build your own chat](#build-your-own-chat) — a complete, tested project, step by step
|
|
26
|
+
6. [Reference](#reference) — hooks, components, server API, settings
|
|
27
|
+
7. [Troubleshooting](#troubleshooting)
|
|
27
28
|
|
|
28
29
|
---
|
|
29
30
|
|
|
@@ -41,6 +42,7 @@ Open the **Settings** page (gear icon) to choose a better chat model (OpenAI, Cl
|
|
|
41
42
|
-p, --port <n> Port (default $PORT or 3000)
|
|
42
43
|
--host <addr> Address to bind (default 127.0.0.1)
|
|
43
44
|
--settings <file> Settings file (default ~/.tz-voice-chat/settings.json, or $TZ_VOICE_CHAT_SETTINGS)
|
|
45
|
+
--cert <file> --key <file> Serve HTTPS (needed for the microphone on other devices — see below)
|
|
44
46
|
```
|
|
45
47
|
|
|
46
48
|
- **Export / Import** on the Settings page saves/loads every setting as a JSON file. The export **includes your API keys** — keep it private.
|
|
@@ -50,6 +52,42 @@ Open the **Settings** page (gear icon) to choose a better chat model (OpenAI, Cl
|
|
|
50
52
|
|
|
51
53
|
---
|
|
52
54
|
|
|
55
|
+
## Use it from a phone or another computer
|
|
56
|
+
|
|
57
|
+
Browsers only expose the **microphone** (and **WebGPU**) to pages served over **`https://`** or from **`localhost`**. So:
|
|
58
|
+
|
|
59
|
+
| You open it as… | Page loads | Typed chat | Microphone / WebGPU |
|
|
60
|
+
|---|---|---|---|
|
|
61
|
+
| `http://localhost:4007` on the same computer | ✅ | ✅ | ✅ |
|
|
62
|
+
| `http://192.168.x.x:4007` from a phone or another computer | ✅ (needs `--host 0.0.0.0`) | ✅ | ❌ blocked by the browser |
|
|
63
|
+
| `https://…` with a trusted certificate | ✅ | ✅ | ✅ |
|
|
64
|
+
|
|
65
|
+
On a plain-`http` address the app still works: it shows a notice, **does not load speech recognition at all** (without a microphone Whisper could never be used, so nothing is downloaded for it), speaks replies with the browser's own voice, and typed chat runs. To talk to it from a phone you need HTTPS. Pick one:
|
|
66
|
+
|
|
67
|
+
**A. A local certificate (stays on your network).** [mkcert](https://github.com/FiloSottile/mkcert) makes certificates your devices can trust:
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
brew install mkcert # macOS; see the mkcert README for other systems
|
|
71
|
+
mkcert -install
|
|
72
|
+
mkcert 192.168.1.50 localhost # use your computer's LAN IP; writes 192.168.1.50+1.pem and ...-key.pem
|
|
73
|
+
npx tz-voice-chat --host 0.0.0.0 --port 4007 \
|
|
74
|
+
--cert 192.168.1.50+1.pem --key 192.168.1.50+1-key.pem
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Then open `https://192.168.1.50:4007` on the phone. The phone must trust mkcert's root certificate: copy `rootCA.pem` (folder shown by `mkcert -CAROOT`) to it, install the profile, and on iPhone enable it under *Settings → General → About → Certificate Trust Settings* (see the mkcert README).
|
|
78
|
+
|
|
79
|
+
**B. A private network with HTTPS** such as Tailscale, or a tunnel (Cloudflare Tunnel, ngrok) pointing at `localhost:4007`. Tunnels are reachable from the internet: anyone with the URL could use your chat model and read or change the saved API keys, so protect them with the tunnel's access controls.
|
|
80
|
+
|
|
81
|
+
**C. For development only:** desktop Chrome has `chrome://flags/#unsafely-treat-insecure-origin-as-secure`. Safari on iPhone has no equivalent.
|
|
82
|
+
|
|
83
|
+
**Models are cached even without HTTPS.** Browsers provide the Cache API only on secure pages, so on a plain-`http` address the models used to be downloaded again on every page load. They are now kept in IndexedDB instead, in small chunks. (Over HTTPS or on `localhost` the normal browser cache is used.)
|
|
84
|
+
|
|
85
|
+
**The in-browser chat model is opt-in on phones.** It needs far more memory than most phone browsers allow and is a common cause of the page restarting, so on a phone it is not loaded automatically: the page offers *Load it anyway* and recommends a cloud chat provider. A good phone setup is a cloud model, or a model on your own computer: pick *OpenAI-compatible server* in Settings and point it at Ollama or LM Studio on your computer. The request is made by the tz-voice-chat server, so nothing heavy runs on the phone. If a page restarts while loading, it remembers the stage it had reached and, after two restarts on a phone, switches to a light *safe mode* and tells you where it stopped.
|
|
86
|
+
|
|
87
|
+
**Tips for phones:** models such as Whisper and Kokoro are hundreds of MB. On a phone it is usually nicer to use cloud speech and chat in Settings (OpenAI or ElevenLabs for speech, any chat provider), or the browser's built-in voice. WebGPU only exists in recent browsers and only over HTTPS; the app falls back when it is missing.
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
53
91
|
## Architecture overview
|
|
54
92
|
|
|
55
93
|
### The big picture
|
|
@@ -517,7 +555,7 @@ The pipeline hook. Returns the state and controls below. Option changes re-initi
|
|
|
517
555
|
|---|---|---|
|
|
518
556
|
| `processInput` | — (**required**) | `async function*(text, history, signal)` yielding text chunks |
|
|
519
557
|
| `systemPrompt` | short spoken-style prompt | First message of every conversation |
|
|
520
|
-
| `sttProvider` | `'whisper'` | `'whisper'` (in the browser)
|
|
558
|
+
| `sttProvider` | `'whisper'` | `'whisper'` (in the browser), `'server'` (POST a WAV to `sttServerUrl`, expects `{ text }`) or `'none'`. Speech recognition is never loaded when the page has no microphone API |
|
|
521
559
|
| `sttServerUrl` | `'/api/stt'` | Endpoint for `sttProvider: 'server'` |
|
|
522
560
|
| `whisperModel` | `'onnx-community/whisper-tiny.en'` | Hugging Face model id |
|
|
523
561
|
| `whisperDtype` | `'q8'` | `'q4'` · `'q8'` · `'fp16'` · `'fp32'` (q4/q8 are promoted to fp32 on WebGPU) |
|
|
@@ -647,6 +685,9 @@ Every setting can be set as an environment variable (initial value) or on the Se
|
|
|
647
685
|
|
|
648
686
|
| Symptom | Cause and fix |
|
|
649
687
|
|---|---|
|
|
688
|
+
| **Blank or black page on a phone / another computer** | The page was opened over plain `http://` on a network address. Older versions crashed there (no `navigator.mediaDevices`); current versions load and explain. For the microphone use HTTPS — see [Use it from a phone](#use-it-from-a-phone-or-another-computer). |
|
|
689
|
+
| **The page restarts and downloads again and again on a phone** | Two causes. (1) On plain `http` there was no cache, so every reload re-downloaded the models — fixed, they are now kept in IndexedDB. (2) The tab may run out of memory while loading and the browser reloads it. On phones the in-browser chat model now loads only after the speech models are ready, and after 3 starts that never finished loading the app enters **safe mode** (smallest Whisper model, browser voice, no in-browser chat model) until you press *Retry full load*. For a lasting fix on a phone use cloud chat and speech in Settings. |
|
|
690
|
+
| **Stuck on "Finishing up…"** | Fixed in recent versions: the in-browser chat model never started on pages with nothing slow to load. Update the package; the status line now says "Starting the in-browser chat model…" with its own progress gauge. |
|
|
650
691
|
| **Microphone never starts**, `window.vad` is undefined | Your page is missing the `ort` / VAD `<script>` tags or the import map ([step 3](#3-the-page--indexhtml)). Microphone access also needs `https://` or `localhost`. |
|
|
651
692
|
| **`Unsupported device: "cpu"`** | The browser build accepts only `wasm` or `webgpu`. Use `whisperDevice: 'wasm'` (`'cpu'` is auto-mapped by this package). |
|
|
652
693
|
| **Kokoro never finishes loading / is very slow** | The model is 80–330 MB depending on precision, and it downloads through your server — a slow link means a long first load. Browser Kokoro on `wasm` runs on the main thread and can be very slow; prefer `webgpu`, `server-kokoro`, or the Web Speech API. |
|
package/bin/tz-voice-chat.js
CHANGED
|
@@ -9,6 +9,8 @@ Usage: tz-voice-chat [options]
|
|
|
9
9
|
--host <addr> Address to bind to (default: 127.0.0.1)
|
|
10
10
|
--settings <file> Settings file to read/write (default: ~/.tz-voice-chat/settings.json,
|
|
11
11
|
or $TZ_VOICE_CHAT_SETTINGS)
|
|
12
|
+
--cert <file> PEM certificate } serve HTTPS — browsers only allow the microphone
|
|
13
|
+
--key <file> PEM private key } on https:// pages and localhost (phones need this)
|
|
12
14
|
-h, --help Show this help
|
|
13
15
|
|
|
14
16
|
Open the printed URL and finish setup on the Settings page (chat provider and key).
|
|
@@ -25,18 +27,27 @@ for (let i = 0; i < args.length; i++) {
|
|
|
25
27
|
else if (a === '-p' || a === '--port') opts.port = Number(next());
|
|
26
28
|
else if (a === '--host') opts.host = next();
|
|
27
29
|
else if (a === '--settings') opts.settingsFile = next();
|
|
30
|
+
else if (a === '--cert') opts.cert = next();
|
|
31
|
+
else if (a === '--key') opts.key = next();
|
|
28
32
|
else { console.error(`Unknown option: ${a}\n\n${HELP}`); process.exit(1); }
|
|
29
33
|
}
|
|
30
34
|
if (!Number.isInteger(opts.port) || opts.port < 0 || opts.port > 65535) {
|
|
31
35
|
console.error('Invalid --port'); process.exit(1);
|
|
32
36
|
}
|
|
33
37
|
|
|
38
|
+
if (Boolean(opts.cert) !== Boolean(opts.key)) { console.error('--cert and --key must be used together'); process.exit(1); }
|
|
39
|
+
|
|
34
40
|
try {
|
|
35
|
-
const { url, settings, host } = await startServer(opts);
|
|
41
|
+
const { url, network, secure, settings, host } = await startServer(opts);
|
|
36
42
|
console.log(`tz-voice-chat running at ${url}`);
|
|
37
43
|
console.log(`Settings file: ${settings.file}`);
|
|
44
|
+
if (network.length) console.log(`On your network: ${network.join(' ')}`);
|
|
38
45
|
if (!['127.0.0.1', 'localhost', '::1'].includes(host)) {
|
|
39
46
|
console.warn('Warning: listening on a non-loopback address — anyone who can reach this port can read/change the saved API keys.');
|
|
47
|
+
if (!secure) {
|
|
48
|
+
console.warn('Note: other devices (phones!) load this page over plain http, and browsers then block the microphone and WebGPU.\n' +
|
|
49
|
+
' The page will load and typed chat works. For voice use HTTPS: --cert/--key (e.g. made with mkcert) or a private tunnel.');
|
|
50
|
+
}
|
|
40
51
|
}
|
|
41
52
|
const { missing } = settings.getPublic();
|
|
42
53
|
if (missing.length) console.log(`Needs setup: ${missing.map(m => m.message).join(' ')} Open ${url} and use Settings.`);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(function(){"use strict";const M=/\.(onnx|onnx_data|safetensors|bin|ort)$/i;function x(n,{minBytes:o=1e6,cap:t=.99}={}){const s=new Map,i=(e,a)=>a>=o&&(M.test(e)||a>=5e6);let r=0;return(e={})=>{const a=e.file||e.name;if(a&&i(a,e.total)){const c=e.status==="done"?e.total:e.loaded??(typeof e.progress=="number"?e.total*e.progress/100:0),p=s.get(a);s.set(a,{loaded:Math.max((p==null?void 0:p.loaded)??0,c),total:e.total})}else if(a&&e.status==="done"&&s.has(a)){const c=s.get(a);c.loaded=c.total}let l=0,d=0;for(const c of s.values())l+=c.loaded,d+=c.total;if(d<=0)return;const u=Math.min(t,l/d);u>r&&(r=u,n(r))}}const _="tz-voice-chat-model-cache",S=4*1024*1024;let g=null;function C(){return g||(g=new Promise((n,o)=>{const t=indexedDB.open(_,1);t.onupgradeneeded=()=>{t.result.createObjectStore("meta"),t.result.createObjectStore("chunks")},t.onsuccess=()=>n(t.result),t.onerror=()=>o(t.error)})),g}async function f(n,o,t){const s=await C();return new Promise((i,r)=>{const e=s.transaction(n,o),a=t(e.objectStore(n));e.oncomplete=()=>i(a==null?void 0:a.result),e.onerror=e.onabort=()=>r(e.error)})}const b=n=>typeof n=="string"?n:n.url,y=(n,o)=>`${n}\0${o}`;async function k(n){const o=await f("meta","readonly",t=>t.get(n));if(o)for(let t=0;t<o.chunks;t++)await f("chunks","readwrite",s=>s.delete(y(n,t)));await f("meta","readwrite",t=>t.delete(n))}function B(){return{async match(n){try{const o=b(n),t=await f("meta","readonly",r=>r.get(o));if(!t||!t.complete)return;let s=0;const i=new ReadableStream({async pull(r){if(s>=t.chunks){r.close();return}const e=await f("chunks","readonly",a=>a.get(y(o,s)));if(!e){r.error(new Error("model cache entry is incomplete"));return}r.enqueue(new Uint8Array(e)),s++}});return new Response(i,{status:200,headers:new Headers(t.headers)})}catch(o){console.warn("[tz-voice-chat] model cache read failed:",o);return}},async put(n,o){const t=b(n);try{await k(t);const s=o.body.getReader();let i=[],r=0,e=0,a=0;const l=async u=>{if(!r||!u&&r<S)return;const c=new Uint8Array(r);let p=0;for(const m of i)c.set(m,p),p+=m.length;i=[],r=0,await f("chunks","readwrite",m=>m.put(c.buffer,y(t,e))),e++};for(;;){const{done:u,value:c}=await s.read();if(u)break;i.push(c),r+=c.length,a+=c.length,await l(!1)}await l(!0);const d=[];o.headers.forEach((u,c)=>{c!=="content-encoding"&&c!=="content-length"&&d.push([c,u])}),d.push(["content-length",String(a)]),await f("meta","readwrite",u=>u.put({complete:!0,chunks:e,size:a,headers:d},t))}catch(s){console.warn("[tz-voice-chat] could not cache a model file (continuing without):",s);try{await k(t)}catch{}}}}}function H(n){return typeof caches<"u"||typeof indexedDB>"u"?!1:(n.useBrowserCache=!1,n.useCustomCache=!0,n.customCache=B(),!0)}let h=null,w=null;self.onmessage=async n=>{var i,r;const{type:o,messages:t,modelProxyUrl:s}=n.data;if(o==="init"){try{const{pipeline:e,TextStreamer:a,env:l}=await import("/vendor/transformers/transformers.min.js");l.remoteHost=s||"/api/models/",H(l),(r=(i=l==null?void 0:l.backends)==null?void 0:i.onnx)!=null&&r.wasm&&(l.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),w=a,h=await e("text-generation","HuggingFaceTB/SmolLM2-360M-Instruct",{dtype:"q4",progress_callback:x(d=>self.postMessage({type:"progress",progress:d}))}),self.postMessage({type:"ready"})}catch(e){self.postMessage({type:"error",message:String((e==null?void 0:e.message)??e)})}return}if(o==="generate"){if(!h||!w){self.postMessage({type:"done"});return}try{const e=new w(h.tokenizer,{skip_prompt:!0,skip_special_tokens:!0,callback_function:a=>{self.postMessage({type:"token",text:a})}});await h(t,{max_new_tokens:150,do_sample:!1,streamer:e}),self.postMessage({type:"done"})}catch(e){console.error("[LLM worker] generate error:",e),self.postMessage({type:"done"})}}}})();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(function(){"use strict";const x=/\.(onnx|onnx_data|safetensors|bin|ort)$/i;function M(n,{minBytes:a=1e6,cap:t=.99}={}){const c=new Map,l=(e,o)=>o>=a&&(x.test(e)||o>=5e6);let s=0;return(e={})=>{const o=e.file||e.name;if(o&&l(o,e.total)){const r=e.status==="done"?e.total:e.loaded??(typeof e.progress=="number"?e.total*e.progress/100:0),u=c.get(o);c.set(o,{loaded:Math.max((u==null?void 0:u.loaded)??0,r),total:e.total})}else if(o&&e.status==="done"&&c.has(o)){const r=c.get(o);r.loaded=r.total}let f=0,d=0;for(const r of c.values())f+=r.loaded,d+=r.total;if(d<=0)return;const i=Math.min(t,f/d);i>s&&(s=i,n(s))}}const P="tz-voice-chat-model-cache",C=4*1024*1024;let m=null;function S(){return m||(m=new Promise((n,a)=>{const t=indexedDB.open(P,1);t.onupgradeneeded=()=>{t.result.createObjectStore("meta"),t.result.createObjectStore("chunks")},t.onsuccess=()=>n(t.result),t.onerror=()=>a(t.error)})),m}async function p(n,a,t){const c=await S();return new Promise((l,s)=>{const e=c.transaction(n,a),o=t(e.objectStore(n));e.oncomplete=()=>l(o==null?void 0:o.result),e.onerror=e.onabort=()=>s(e.error)})}const g=n=>typeof n=="string"?n:n.url,w=(n,a)=>`${n}\0${a}`;async function b(n){const a=await p("meta","readonly",t=>t.get(n));if(a)for(let t=0;t<a.chunks;t++)await p("chunks","readwrite",c=>c.delete(w(n,t)));await p("meta","readwrite",t=>t.delete(n))}function W(){return{async match(n){try{const a=g(n),t=await p("meta","readonly",s=>s.get(a));if(!t||!t.complete)return;let c=0;const l=new ReadableStream({async pull(s){if(c>=t.chunks){s.close();return}const e=await p("chunks","readonly",o=>o.get(w(a,c)));if(!e){s.error(new Error("model cache entry is incomplete"));return}s.enqueue(new Uint8Array(e)),c++}});return new Response(l,{status:200,headers:new Headers(t.headers)})}catch(a){console.warn("[tz-voice-chat] model cache read failed:",a);return}},async put(n,a){const t=g(n);try{await b(t);const c=a.body.getReader();let l=[],s=0,e=0,o=0;const f=async i=>{if(!s||!i&&s<C)return;const r=new Uint8Array(s);let u=0;for(const h of l)r.set(h,u),u+=h.length;l=[],s=0,await p("chunks","readwrite",h=>h.put(r.buffer,w(t,e))),e++};for(;;){const{done:i,value:r}=await c.read();if(i)break;l.push(r),s+=r.length,o+=r.length,await f(!1)}await f(!0);const d=[];a.headers.forEach((i,r)=>{r!=="content-encoding"&&r!=="content-length"&&d.push([r,i])}),d.push(["content-length",String(o)]),await p("meta","readwrite",i=>i.put({complete:!0,chunks:e,size:o,headers:d},t))}catch(c){console.warn("[tz-voice-chat] could not cache a model file (continuing without):",c);try{await b(t)}catch{}}}}}function B(n){return typeof caches<"u"||typeof indexedDB>"u"?!1:(n.useBrowserCache=!1,n.useCustomCache=!0,n.customCache=W(),!0)}let y=null,k=Promise.resolve();self.onmessage=async n=>{var c,l;const{type:a,audio:t}=n.data;if(a==="init"){const s=n.data.model||"onnx-community/whisper-tiny.en",e=n.data.device||"wasm",o=e==="cpu"?"wasm":e,f=n.data.modelProxyUrl||"/api/models/";let d=n.data.dtype||"q8";o==="webgpu"&&(d==="q4"||d==="q8")&&(console.warn(`[Whisper worker] dtype "${d}" not supported on WebGPU — using "fp32".`),d="fp32");try{const{pipeline:i,env:r}=await import("/vendor/transformers/transformers.min.js");r.remoteHost=f,B(r),(l=(c=r==null?void 0:r.backends)==null?void 0:c.onnx)!=null&&l.wasm&&(r.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),y=await i("automatic-speech-recognition",s,{dtype:d,device:o,progress_callback:M(u=>self.postMessage({type:"progress",progress:u}))}),self.postMessage({type:"ready"})}catch(i){self.postMessage({type:"error",message:String((i==null?void 0:i.message)??i)})}return}a==="transcribe"&&(console.log("[Whisper worker] transcribe — samples:",t==null?void 0:t.length),k=k.then(async()=>{var s;try{if(!y){console.warn("[Whisper worker] pipeline not ready, dropping segment"),self.postMessage({type:"transcript",text:""});return}const e=await y(t),o=(e==null?void 0:e.text)??((s=e==null?void 0:e[0])==null?void 0:s.text)??"";self.postMessage({type:"transcript",text:o})}catch(e){console.error("[Whisper worker] transcription error:",e),self.postMessage({type:"transcript",text:""})}}))}})();
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Je=Object.create;var je=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var Xe=Object.getPrototypeOf,et=Object.prototype.hasOwnProperty;var tt=(e,a,o,c)=>{if(a&&typeof a=="object"||typeof a=="function")for(let t of Ze(a))!et.call(e,t)&&t!==o&&je(e,t,{get:()=>a[t],enumerable:!(c=Qe(a,t))||c.enumerable});return e};var Ie=(e,a,o)=>(o=e!=null?Je(Xe(e)):{},tt(a||!e||!e.__esModule?je(o,"default",{value:e,enumerable:!0}):o,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("react"),n=require("react/jsx-runtime");var ne=typeof document<"u"?document.currentScript:null;const be=60,ce=200;function Me(){let e="",a=!0;function o(t,i,r){t.push(i),e=r,a=!1}function c(){const t=[];for(;;){const i=/([.!?]{1,3})(\s|$)/.exec(e);if(i){const r=e.slice(0,i.index+i[0].length).trim();if(r.length>=10){o(t,r,e.slice(i.index+i[0].length));continue}}if(a){if(e.length>=25){const r=/[,;:—–](\s|$)/.exec(e);if(r){const u=e.slice(0,r.index+r[0].length).trim();if(u.length>=20){o(t,u,e.slice(r.index+r[0].length));continue}}}if(e.length>=be){const r=e.lastIndexOf(" ",be-1),u=r>10?r:be;o(t,e.slice(0,u).trim(),e.slice(u).trimStart());continue}}else if(e.length>=ce){const r=e.slice(0,ce),u=Math.max(r.lastIndexOf(", "),r.lastIndexOf("; "),r.lastIndexOf(": ")),l=u>ce/2?u+1:r.lastIndexOf(" ")>10?r.lastIndexOf(" "):ce;o(t,e.slice(0,l).trim(),e.slice(l).trimStart());continue}break}return t}return{write(t){return e+=t,c()},flush(){const t=e.trim();return e="",t}}}async function nt(e,{dtype:a="q8",device:o="cpu",modelProxyUrl:c="/api/models/"}={}){var f,h;const{env:t}=await import("/vendor/transformers/transformers.min.js");t.remoteHost=c,(h=(f=t==null?void 0:t.backends)==null?void 0:f.onnx)!=null&&h.wasm&&(t.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),t!=null&&t.onnx&&(t.onnx.logSeverityLevel=3);const i=await import("/vendor/kokoro/kokoro.web.js"),{KokoroTTS:r}=i;let u=a;o==="webgpu"&&(a==="q4"||a==="q8")&&(console.warn(`[modelLoader] dtype "${a}" not supported on WebGPU — using "fp32".`),u="fp32");let l=0;const p=b=>{typeof(b==null?void 0:b.progress)=="number"&&(l=Math.max(l,b.progress/100),e==null||e("kokoro",Math.min(.99,l)))};async function d(b,_){return r.from_pretrained("onnx-community/Kokoro-82M-ONNX",{dtype:_,device:b,progress_callback:p})}let x;try{x=await d(o,u)}catch(b){if(o!=="wasm")console.warn(`[modelLoader] Kokoro on "${o}" failed (${b==null?void 0:b.message}) — falling back to WASM.`),l=0,x=await d("wasm",a);else throw b}return e==null||e("kokoro",1),{kokoro:x}}function ue(e,a,{threshold:o=.01,padMs:c=25}={}){const{numberOfChannels:t,length:i,sampleRate:r}=a;let u=i,l=-1;for(let h=0;h<t;h++){const b=a.getChannelData(h);for(let _=0;_<i;_++)if(Math.abs(b[_])>o){_<u&&(u=_);break}for(let _=i-1;_>=0;_--)if(Math.abs(b[_])>o){_>l&&(l=_);break}}if(l<u)return a;const p=Math.round(c/1e3*r),d=Math.max(0,u-p),x=Math.min(i,l+1+p);if(d===0&&x===i)return a;const f=e.createBuffer(t,x-d,r);for(let h=0;h<t;h++)f.copyToChannel(a.getChannelData(h).subarray(d,x),h);return f}function st(e,{voice:a="af_bella",speed:o=1,onPlayStart:c}={}){const t=new AudioContext,i=[];let r=!1,u=null,l=!1;async function p(f){if(f instanceof AudioBuffer)return ue(t,f);const h=(f==null?void 0:f.audio)??f;if(h instanceof ArrayBuffer)return ue(t,await t.decodeAudioData(h.slice(0)));if(h instanceof Float32Array){const b=(f==null?void 0:f.samplingRate)??24e3,_=t.createBuffer(1,h.length,b);return _.copyToChannel(h,0),ue(t,_)}throw new Error("Unsupported TTS payload")}async function d(f){await t.resume();const h=t.createBufferSource();return h.buffer=f,h.connect(t.destination),new Promise(b=>{h.onended=()=>{u===h&&(u=null),b()},u=h,h.start(),l||(l=!0,c==null||c())})}async function x(){if(!r){for(r=!0;i.length>0;){const f=i.shift();try{const h=await f;h&&await d(h)}catch(h){console.error("[TtsQueue]",h)}}r=!1}}return{enqueue(f){i.push(e.generate(f,{voice:a,speed:o}).then(p)),x()},cancel(){if(i.length=0,l=!1,u){try{u.stop()}catch{}u=null}},async finished(){for(;r||i.length>0;)await new Promise(f=>setTimeout(f,200))}}}function rt({voice:e="",speed:a=1,onPlayStart:o,url:c="/api/tts"}={}){const t=new AudioContext,i=[];let r=!1,u=null,l=!1;async function p(f){const h={text:f};e&&(h.voice=e),a!==1&&(h.speed=a);const b=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});if(!b.ok)throw new Error(`TTS ${b.status}: ${await b.text()}`);return ue(t,await t.decodeAudioData(await b.arrayBuffer()))}async function d(f){await t.resume();const h=t.createBufferSource();return h.buffer=f,h.connect(t.destination),new Promise(b=>{h.onended=()=>{u===h&&(u=null),b()},u=h,h.start(),l||(l=!0,o==null||o())})}async function x(){if(!r){for(r=!0;i.length>0;){const f=i.shift();try{await d(await f)}catch(h){console.error("[ServerTTS]",h)}}r=!1}}return{enqueue(f){f!=null&&f.trim()&&(i.push(p(f)),x())},cancel(){if(i.length=0,u){try{u.stop()}catch{}u=null}l=!1},async finished(){for(;r||i.length>0;)await new Promise(f=>setTimeout(f,100))}}}function at({voice:e="",rate:a=1,pitch:o=1,onPlayStart:c}={}){const t=[];let i=!1,r=!1;function u(){return e?speechSynthesis.getVoices().find(d=>d.name===e||d.voiceURI===e)??null:null}function l(){if(i||t.length===0)return;i=!0;const p=t.shift(),d=new SpeechSynthesisUtterance(p),x=u();x&&(d.voice=x),d.rate=a,d.pitch=o,d.onstart=()=>{r||(r=!0,c==null||c())},d.onend=()=>{i=!1,l()},d.onerror=f=>{console.error("[WebSpeech TTS] error",f.error),i=!1,l()},speechSynthesis.speak(d)}return{enqueue(p){p!=null&&p.trim()&&(t.push(p),l())},cancel(){t.length=0,speechSynthesis.cancel(),i=!1,r=!1},async finished(){for(;i||t.length>0;)await new Promise(p=>setTimeout(p,100))}}}async function ot({onSpeechStart:e,onSpeechEnd:a,onError:o,deviceId:c}){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,...c?{deviceId:{exact:c}}:{}},onSpeechStart:()=>e==null?void 0:e(),onSpeechEnd:r=>{console.log("[VAD] onSpeechEnd — samples:",r==null?void 0:r.length),a==null||a(r)},onVADMisfire:()=>{},negativeSpeechThreshold:.25,positiveSpeechThreshold:.5,redemptionFrames:4,minSpeechFrames:3,preSpeechPadFrames:1})}catch(t){throw o==null||o("VAD initialization failed. Falling back to manual microphone capture."),t}}function it(e,a=16e3){const o=e.length*2,c=new ArrayBuffer(44+o),t=new DataView(c),i=(r,u)=>{for(let l=0;l<u.length;l++)t.setUint8(r+l,u.charCodeAt(l))};i(0,"RIFF"),t.setUint32(4,36+o,!0),i(8,"WAVE"),i(12,"fmt "),t.setUint32(16,16,!0),t.setUint16(20,1,!0),t.setUint16(22,1,!0),t.setUint32(24,a,!0),t.setUint32(28,a*2,!0),t.setUint16(32,2,!0),t.setUint16(34,16,!0),i(36,"data"),t.setUint32(40,o,!0);for(let r=0,u=44;r<e.length;r++,u+=2){const l=Math.max(-1,Math.min(1,e[r]));t.setInt16(u,l<0?l*32768:l*32767,!0)}return new Blob([c],{type:"audio/wav"})}const P={IDLE:"idle",LISTENING:"listening",TRANSCRIBING:"transcribing",THINKING:"thinking",SPEAKING:"speaking"},ct="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 Te({processInput:e,systemPrompt:a=ct,ttsProvider:o="server-kokoro",ttsVoice:c="af_bella",ttsSpeed:t=1,ttsServerUrl:i="/api/tts",ttsSpeechRate:r=1,ttsSpeechPitch:u=1,sttProvider:l="whisper",sttServerUrl:p="/api/stt",whisperModel:d="onnx-community/whisper-tiny.en",whisperDtype:x="q8",whisperDevice:f="wasm",kokoroDtype:h="q8",kokoroBrowserDevice:b="wasm",modelProxyUrl:_="/api/models/"}={}){const[T,E]=m.useState(P.IDLE),[L,I]=m.useState(!0),[C,D]=m.useState({whisper:0,kokoro:0}),[$,O]=m.useState(null),[s,k]=m.useState([]),[w,S]=m.useState(null),[v,M]=m.useState(!1),[R,K]=m.useState(""),[Q,j]=m.useState([]),[se,ae]=m.useState(null),B=m.useRef(P.IDLE),G=m.useRef(!1),W=m.useRef(null),Y=m.useRef(null),Z=m.useRef(null),J=m.useRef(null),de=m.useRef(null),he=m.useRef(null),X=m.useRef([{role:"system",content:a}]),pe=m.useRef(e),fe=m.useRef(0),_e=m.useRef({id:null,enqueuedAt:null,ttsMs:null}),Ve=m.useRef(1),me=m.useRef({provider:l,url:p});me.current={provider:l,url:p},m.useEffect(()=>{X.current=[{role:"system",content:a},...X.current.slice(1)]},[a]),m.useEffect(()=>{B.current=T},[T]),m.useEffect(()=>{G.current=v},[v]),m.useEffect(()=>{pe.current=e},[e]),m.useEffect(()=>{async function A(){try{const N=await navigator.mediaDevices.enumerateDevices();j(N.filter(g=>g.kind==="audioinput"))}catch{}}return A(),navigator.mediaDevices.addEventListener("devicechange",A),()=>navigator.mediaDevices.removeEventListener("devicechange",A)},[v]),m.useEffect(()=>{let A=!1;I(!0),D({whisper:0,kokoro:0});async function N(){try{const g=()=>{var z;const y=_e.current;y.enqueuedAt!=null&&y.ttsMs==null&&(y.ttsMs=Math.round(performance.now()-y.enqueuedAt),y.id!=null&&Ue(y.id,{timings:{ttsMs:y.ttsMs}})),o==="webspeech"&&((z=Y.current)==null||z.pause())};if(o==="webspeech")W.current=at({voice:c,rate:r,pitch:u,onPlayStart:g}),D(y=>({...y,kokoro:1}));else if(o==="kokoro"){const{kokoro:y}=await nt((z,F)=>D(q=>({...q,[z]:F})),{dtype:h,device:b,modelProxyUrl:_});if(A)return;W.current=st(y,{voice:c,speed:t,onPlayStart:g})}else W.current=rt({voice:c,speed:t,onPlayStart:g,url:i}),D(y=>({...y,kokoro:1}));if(A)return;if(l==="server"){J.current=null,D(y=>({...y,whisper:1})),I(!1);return}J.current=new Worker(new URL("./assets/whisperWorker-D69IwlqW.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ne&&ne.tagName.toUpperCase()==="SCRIPT"&&ne.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),J.current.onmessage=y=>{y.data.type==="transcript"?ve(y.data.text,{transcribeMs:Math.round(performance.now()-fe.current)}):y.data.type==="progress"?D(z=>({...z,whisper:y.data.progress})):y.data.type==="ready"?(D(z=>({...z,whisper:1})),I(!1)):y.data.type==="error"&&(O(`Whisper: ${y.data.message}`),I(!1))},J.current.onerror=()=>{O("Model load failed. Check WebGPU/WASM browser support."),I(!1)},J.current.postMessage({type:"init",model:d,dtype:x,device:f,modelProxyUrl:_})}catch(g){A||(O("Initialisation failed: "+((g==null?void 0:g.message)??String(g))),I(!1))}}return N(),()=>{var g,y;A=!0,(g=J.current)==null||g.terminate(),(y=W.current)==null||y.cancel()}},[o,c,t,r,u,i,l,p,d,x,f,h,b]);function Se(A,N,g){const y=Ve.current++;return k(z=>[...z,{id:y,role:A,content:N,timings:g,time:new Date().toISOString()}]),y}function Ue(A,{timings:N}){k(g=>g.map(y=>y.id===A?{...y,timings:{...y.timings,...N}}:y))}async function Ke(A){const N=fe.current;try{const g=await fetch(me.current.url,{method:"POST",headers:{"Content-Type":"audio/wav"},body:it(A,16e3)});if(!g.ok)throw new Error(`Speech-to-text failed: ${g.status} ${await g.text()}`);const{text:y}=await g.json();await ve(y,{transcribeMs:Math.round(performance.now()-N)})}catch(g){O(g.message||"Speech-to-text failed."),E(G.current?P.LISTENING:P.IDLE)}}async function ve(A,{transcribeMs:N}={}){if(!(A!=null&&A.trim())){E(G.current?P.LISTENING:P.IDLE);return}E(P.THINKING),Se("user",A,N!=null?{transcribeMs:N}:void 0);const g=[...X.current,{role:"user",content:A}];X.current=g,await qe(A,g)}async function qe(A,N){var g,y,z,F;(g=Z.current)==null||g.abort(),Z.current=new AbortController,(y=W.current)==null||y.cancel();try{if(!pe.current)throw new Error("processInput is not provided");const q=Me();let oe="",ye=!1,ge=null;const He=performance.now(),ee={id:null,enqueuedAt:null,ttsMs:null};_e.current=ee;const Ee=ie=>{var we;ee.enqueuedAt==null&&(ee.enqueuedAt=performance.now()),(we=W.current)==null||we.enqueue(ie)};S("");for await(const ie of pe.current(A,N,Z.current.signal))ge==null&&(ge=Math.round(performance.now()-He)),oe+=ie,S(oe),q.write(ie).forEach(Ye=>{ye||(ye=!0,E(P.SPEAKING)),Ee(Ye)});const Ae=q.flush();Ae&&(ye||E(P.SPEAKING),Ee(Ae)),ee.id=Se("assistant",oe,{thinkMs:ge,...ee.ttsMs!=null?{ttsMs:ee.ttsMs}:{}}),S(null),X.current=[...X.current,{role:"assistant",content:oe}],await((z=W.current)==null?void 0:z.finished()),o==="webspeech"&&((F=Y.current)==null||F.start())}catch(q){S(null),q.name!=="AbortError"&&O(q.message||"Processing failed.")}finally{E(G.current?P.LISTENING:P.IDLE)}}async function Be(){var A,N;O(null),B.current===P.SPEAKING&&((A=W.current)==null||A.cancel(),(N=Z.current)==null||N.abort());try{E(P.LISTENING),M(!0);try{const g=await navigator.mediaDevices.getUserMedia({audio:R?{deviceId:{exact:R}}:!0,video:!1});he.current=g;const y=new AudioContext;de.current=y;const z=y.createAnalyser();z.fftSize=256,y.createMediaStreamSource(g).connect(z),ae(z)}catch(g){console.warn("[TZVoiceChat] waveform analyser unavailable:",g)}Y.current=await ot({onSpeechStart:()=>{var g,y;o==="webspeech"&&B.current===P.SPEAKING||(B.current===P.SPEAKING&&((g=W.current)==null||g.cancel(),(y=Z.current)==null||y.abort()),E(P.LISTENING))},onSpeechEnd:g=>{var y;o==="webspeech"&&B.current===P.SPEAKING||(E(P.TRANSCRIBING),fe.current=performance.now(),me.current.provider==="server"?Ke(g):(y=J.current)==null||y.postMessage({type:"transcribe",audio:g},[g.buffer]))},onError:g=>{O(g),E(P.IDLE)},deviceId:R||void 0})}catch(g){console.error("[TZVoiceChat] startListening failed:",g),O("Microphone access failed. Allow audio permissions and refresh."),E(P.IDLE),M(!1)}}function Ge(){var A,N,g,y,z;M(!1),(A=Y.current)==null||A.destroy(),Y.current=null,(N=he.current)==null||N.getTracks().forEach(F=>F.stop()),he.current=null,(g=de.current)==null||g.close(),de.current=null,ae(null),(y=W.current)==null||y.cancel(),(z=Z.current)==null||z.abort(),E(P.IDLE)}function Fe(A){var z;if(!(A!=null&&A.trim()))return;E(P.SPEAKING);const N=Me(),g=N.write(A),y=N.flush();[...g,...y?[y]:[]].forEach(F=>{var q;return(q=W.current)==null?void 0:q.enqueue(F)}),(z=W.current)==null||z.finished().then(()=>{E(G.current?P.LISTENING:P.IDLE)})}return{status:T,loading:L,progress:C,error:$,transcript:s,streamingMessage:w,micEnabled:v,startListening:Be,stopListening:Ge,speak:Fe,submitText:ve,liveAnalyser:se,devices:Q,selectedMicId:R,setSelectedMicId:K}}function Pe(e){const a=e.replace("#",""),o=a.length===3?a.split("").map(c=>c+c).join(""):a;return[parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)]}function lt(e,a,o){e/=255,a/=255,o/=255;const c=Math.max(e,a,o),t=Math.min(e,a,o),i=(c+t)/2;if(c===t)return[0,0,i*100];const r=c-t,u=i>.5?r/(2-c-t):r/(c+t);let l;switch(c){case e:l=((a-o)/r+(a<o?6:0))/6;break;case a:l=((o-e)/r+2)/6;break;default:l=((e-a)/r+4)/6}return[l*360,u*100,i*100]}function ut(e,a,o){a/=100,o/=100;const c=r=>(r+e/30)%12,t=a*Math.min(o,1-o),i=r=>o-t*Math.max(-1,Math.min(c(r)-3,Math.min(9-c(r),1)));return[Math.round(i(0)*255),Math.round(i(8)*255),Math.round(i(4)*255)]}function U(e,a){const[o,c,t]=Pe(e),[i,r,u]=lt(o,c,t),[l,p,d]=ut(i,r,Math.max(0,Math.min(100,u+a)));return`rgb(${l}, ${p}, ${d})`}function V(e,a){const[o,c,t]=Pe(e);return`rgba(${o}, ${c}, ${t}, ${a})`}function re(e,a){return e.replace("rgb(","rgba(").replace(")",`, ${a})`)}const le=10;function dt({analyser:e}){const a=m.useRef(null),o=m.useRef(null);return m.useEffect(()=>{if(cancelAnimationFrame(o.current),!e)return;const c=a.current;if(!c)return;const t=c.getContext("2d"),i=e.frequencyBinCount,r=new Uint8Array(i),u=Math.max(1,Math.floor(i/le)),l=getComputedStyle(c),p=+l.getPropertyValue("--bar-hue"),d=+l.getPropertyValue("--bar-hue-range"),x=+l.getPropertyValue("--bar-sat"),f=+l.getPropertyValue("--bar-lit"),h=+l.getPropertyValue("--bar-lit-range"),b=()=>{o.current=requestAnimationFrame(b),e.getByteFrequencyData(r);const _=c.width,T=c.height;t.clearRect(0,0,_,T);const E=(_-(le-1)*2)/le;for(let L=0;L<le;L++){const I=r[L*u]/255,C=Math.max(3,I*T*.88);t.fillStyle=`hsl(${p+I*d}, ${x}%, ${f+I*h}%)`,t.beginPath(),t.roundRect(L*(E+2),(T-C)/2,E,C,[2]),t.fill()}};return b(),()=>cancelAnimationFrame(o.current)},[e]),n.jsx("canvas",{ref:a,width:55,height:35,className:"ai-btn__canvas"})}function Ne({status:e="idle",active:a=!1,loading:o=!1,analyser:c=null,onToggle:t,devices:i=[],selectedMicId:r="",onDeviceChange:u,inputData:l="",sendData:p,accentColor:d="#f97316",uiColor:x="#64748b",size:f=70,barHue:h=25,barHueRange:b=20,barSat:_=88,barLit:T=65,barLitRange:E=20}){var S;const[L,I]=m.useState(!1),C=m.useRef(null);m.useEffect(()=>{if(!L)return;function v(M){var R;(R=C.current)!=null&&R.contains(M.target)||I(!1)}return document.addEventListener("pointerdown",v),()=>document.removeEventListener("pointerdown",v)},[L]);function D(v){u==null||u(v),I(!1)}const $=m.useMemo(()=>{const v=U(d,-8),M=U(d,-15),R=U(d,-22),K=U(d,-30),Q=U(d,-42),j=U(d,8),se=U(d,20),ae=U(d,30),B=U(x,-22),G=U(x,-30),W=U(x,18),Y=U(x,37);return{"--tz-size":`${f}px`,"--tz-a":d,"--tz-a-d8":v,"--tz-a-d15":M,"--tz-a-d22":R,"--tz-a-d30":K,"--tz-a-d42":Q,"--tz-a-l8":j,"--tz-a-l20":se,"--tz-a-l30":ae,"--tz-a-25":V(d,.25),"--tz-a-28":V(d,.28),"--tz-a-30":V(d,.3),"--tz-a-32":V(d,.32),"--tz-a-34":V(d,.34),"--tz-a-35":V(d,.35),"--tz-a-38":V(d,.38),"--tz-a-45":V(d,.45),"--tz-a-50":V(d,.5),"--tz-a-55":V(d,.55),"--tz-a-60":V(d,.6),"--tz-a-65":V(d,.65),"--tz-a-68":V(d,.68),"--tz-u":x,"--tz-u-d22":B,"--tz-u-d30":G,"--tz-u-l18":W,"--tz-u-l37":Y,"--tz-u-30":V(x,.3),"--tz-u-55":V(x,.55),"--tz-u-d30-a85":re(G,.85),"--tz-u-l18-a18":re(W,.18),"--tz-u-l18-a20":re(W,.2),"--tz-u-l18-a32":re(W,.32),"--tz-u-d22-a90":re(B,.9),"--bar-hue":h,"--bar-hue-range":b,"--bar-sat":_,"--bar-lit":T,"--bar-lit-range":E}},[d,x,f,h,b,_,T,E]),O=((S=i.find(v=>v.deviceId===r))==null?void 0:S.label)||(r?`Mic ${r.slice(0,6)}…`:"Default mic"),s=l.trim().length>0,k=s?"ready":a?e:"off";let w;return s?w=n.jsx("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:n.jsx("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})}):!a||e==="idle"?w=n.jsxs("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[n.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"}),n.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"}),n.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"?w=n.jsx(dt,{analyser:c}):e==="transcribing"?w=n.jsx("div",{className:"ai-btn__bars ai-btn__bars--transcribing",children:Array.from({length:7},(v,M)=>n.jsx("span",{style:{animationDelay:`${M*.1}s`}},M))}):e==="thinking"?w=n.jsxs("div",{className:"ai-btn__dots",children:[n.jsx("span",{}),n.jsx("span",{style:{animationDelay:"0.18s"}}),n.jsx("span",{style:{animationDelay:"0.36s"}})]}):e==="speaking"&&(w=n.jsx("div",{className:"ai-btn__bars ai-btn__bars--speaking",children:Array.from({length:7},(v,M)=>n.jsx("span",{style:{animationDelay:`${M*.11}s`}},M))})),n.jsxs("div",{className:"ai-btn-root",style:$,children:[n.jsxs("div",{className:`ai-btn-rings ai-btn-rings--${k}`,"aria-hidden":"true",children:[n.jsx("span",{className:"ai-ring ai-ring--1"}),n.jsx("span",{className:"ai-ring ai-ring--2"})]}),n.jsxs("button",{className:`ai-btn ai-btn--${k}`,disabled:o,onClick:s?()=>p==null?void 0:p(l):t,"aria-label":s?"Send message":a?"Stop assistant":"Start assistant","aria-pressed":s?void 0:a,children:[w,a&&!s&&n.jsx("span",{className:"ai-btn__hover-stop","aria-hidden":"true",children:"■"})]}),n.jsxs("div",{className:`ai-mic-sel${L?" open":""}`,ref:C,children:[n.jsxs("button",{className:"ai-mic-sel__trigger",onClick:()=>I(v=>!v),title:"Change microphone","aria-label":"Change microphone","aria-expanded":L,children:[n.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[n.jsx("path",{d:"M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4z"}),n.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"})]}),n.jsx("span",{className:"ai-mic-sel__label",children:O}),n.jsx("svg",{className:`ai-mic-sel__caret${L?" open":""}`,width:"9",height:"9",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:n.jsx("path",{d:"M12 16L4 8h16l-8 8z"})})]}),L&&n.jsxs("ul",{className:"ai-mic-sel__menu",role:"listbox","aria-label":"Select microphone",children:[n.jsx("li",{role:"option",className:`ai-mic-sel__option${r===""?" selected":""}`,onClick:()=>D(""),"aria-selected":r==="",children:"Default microphone"}),i.map(v=>n.jsx("li",{role:"option",className:`ai-mic-sel__option${r===v.deviceId?" selected":""}`,onClick:()=>D(v.deviceId),"aria-selected":r===v.deviceId,children:v.label||`Microphone ${v.deviceId.slice(0,8)}`},v.deviceId))]})]})]})}async function Oe(e,a,o="/api/chat"){var u;const c=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},signal:a,body:JSON.stringify({messages:e})});if(!c.ok){const l=await c.text();throw new Error(`Server error: ${c.status} ${l}`)}const t=(u=c.body)==null?void 0:u.getReader();if(!t){const l=await c.json();return{stream:async function*(){yield l.text}}}const i=new TextDecoder;let r="";return{stream:async function*(){var p,d,x;let l="";for(;;){const{value:f,done:h}=await t.read();if(h)break;r+=i.decode(f,{stream:!0});const b=r.split(`
|
|
2
|
-
`);r=b.pop();for(const _ of b){const T=_.trim();if(!T.startsWith("data:"))continue;const E=T.slice(5).trimStart();if(E==="[DONE]")return;try{const I=(x=(d=(p=JSON.parse(E).choices)==null?void 0:p[0])==null?void 0:d.delta)==null?void 0:x.content;I&&(l&&/\w/.test(l)&&/\w/.test(I[0])&&(yield" "),l=I[I.length-1],yield I)}catch{}}}}}}function Re(e,a,o){return{stream:async function*(){const c=[];let t=null,i=!1,r="";const u=({data:p})=>{p.type==="token"?(c.push(p.text),t==null||t(),t=null):p.type==="done"&&(i=!0,t==null||t(),t=null)},l=()=>{i=!0,t==null||t(),t=null};e.addEventListener("message",u),o==null||o.addEventListener("abort",l),e.postMessage({type:"generate",messages:a});try{for(;!i||c.length>0;)if(c.length>0){const p=c.shift();r&&/\w/.test(r)&&/\w/.test(p[0])&&(yield" "),r=p[p.length-1],yield p}else await new Promise(p=>{t=p})}finally{e.removeEventListener("message",u),o==null||o.removeEventListener("abort",l)}}}}function ze({apiBase:e="/api",systemPrompt:a}={}){const[o,c]=m.useState(!0),[t,i]=m.useState(0),[r,u]=m.useState(""),[l,p]=m.useState({}),[d,x]=m.useState(null),[f,h]=m.useState({}),[b,_]=m.useState(0),T=m.useRef(null),E=m.useRef(null),L=m.useCallback(()=>_($=>$+1),[]);m.useEffect(()=>{let $=!1;u(""),i(0);async function O(){let s=null,k={};try{s=await(await fetch(`${e}/config`)).json(),x(s),k={ttsProvider:s.ttsProvider||"kokoro",ttsVoice:s.ttsProvider==="openai"?s.openaiTtsVoice||"alloy":s.ttsProvider==="elevenlabs"?s.elevenlabsVoiceId:s.ttsProvider==="webspeech"?s.webSpeechVoice||"":s.kokoroVoice||"af_bella",ttsSpeed:s.kokoroSpeed??1,ttsServerUrl:`${e}/tts`,ttsSpeechRate:s.webSpeechRate??1,ttsSpeechPitch:s.webSpeechPitch??1,sttProvider:s.sttProvider==="elevenlabs"||s.sttProvider==="openai"?"server":"whisper",sttServerUrl:`${e}/stt`,whisperModel:s.whisperModel||"onnx-community/whisper-tiny.en",whisperDtype:s.whisperDtype||"q8",whisperDevice:s.whisperDevice||"wasm",kokoroDtype:s.kokoroDtype||"q8",kokoroBrowserDevice:s.kokoroBrowserDevice||"wasm",modelProxyUrl:`${e}/models/`,...s.systemPrompt?{systemPrompt:s.systemPrompt}:{}}}catch{k={ttsProvider:"kokoro",ttsServerUrl:`${e}/tts`,modelProxyUrl:`${e}/models/`}}if(!$){if((s==null?void 0:s.chatProvider)==="local"){c(!0),u("Using SmolLM2-360M-Instruct locally in your browser — slow and simple; pick a cloud model in Settings for better answers.");const w=new Worker(new URL("./assets/llmWorker-CVEGn6yI.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ne&&ne.tagName.toUpperCase()==="SCRIPT"&&ne.src||new URL("index.cjs",document.baseURI).href),{type:"module"});E.current=w,w.onmessage=S=>{S.data.type==="progress"?i(S.data.progress??0):S.data.type==="ready"?(i(1),T.current=async function*(v,M,R){const{stream:K}=Re(w,M,R);yield*K()},p(k),c(!1)):S.data.type==="error"&&c(!1)},w.onerror=()=>c(!1),p(k),w.postMessage({type:"init",modelProxyUrl:`${e}/models/`});return}s!=null&&s.hasApiKey?T.current=async function*(w,S,v){const{stream:M}=await Oe(S,v,`${e}/chat`);yield*M()}:T.current=async function*(){throw new Error("The chat model is not configured yet — open Settings and choose a provider.")},p(k),c(!1)}}return O(),()=>{var s;$=!0,(s=E.current)==null||s.terminate(),E.current=null}},[e,b]);const I=Te({processInput:async function*($,O,s){T.current&&(yield*T.current($,O,s))},...a?{systemPrompt:a}:{},...l});m.useEffect(()=>{let $=!1;async function O(){const k={};typeof performance<"u"&&performance.memory&&(k.browser=performance.memory.usedJSHeapSize);try{const w=await fetch(`${e}/stats`);w.ok&&(k.server=(await w.json()).rss)}catch{}$||h(k)}O();const s=setInterval(O,3e3);return()=>{$=!0,clearInterval(s)}},[e]);const{micEnabled:C,stopListening:D}=I;return m.useEffect(()=>{if(!C)return;const $=O=>{O.key==="Escape"&&D()};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[C,D]),{chat:I,info:d,config:l,memory:f,llmProgress:t,note:r,loading:I.loading||o,missing:(d==null?void 0:d.missing)??[],reload:L}}const ht=["q8","q4","q4f16","fp16","fp32"],te="Local · free",H="Cloud",xe=[{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",te],["openai-compatible","OpenAI-compatible server (Ollama, LM Studio, vLLM, on-premise…)",te],["openrouter","OpenRouter",H],["openai","OpenAI",H],["anthropic","Anthropic (Claude)",H],["huggingface","Hugging Face",H]]},{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",te],["openai","OpenAI transcription",H],["elevenlabs","ElevenLabs Scribe",H]]},{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",te],["server-kokoro","Kokoro on the server (needs: npm install kokoro-js)",te],["webspeech","Browser Web Speech API (built-in voices)",te],["openai","OpenAI TTS",H],["elevenlabs","ElevenLabs",H]]},{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:ht.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"}]}],$e=xe.flatMap(e=>e.fields);Object.fromEntries($e.map(e=>[e.key,e]));$e.filter(e=>e.secret).map(e=>e.key);function pt(e,a){const o=c=>Object.entries(c).every(([t,i])=>(Array.isArray(i)?i:[i]).includes(a[t]));return e.showWhenAny?e.showWhenAny.some(o):e.showWhen?o(e.showWhen):!0}function De(e,a={}){const o=[],c=r=>!!a[r],t=e.chatProvider;t||o.push({key:"chatProvider",message:"No chat model provider is configured.",scope:"chat"}),t==="openai-compatible"&&(e.compatBaseUrl||o.push({key:"compatBaseUrl",message:"The OpenAI-compatible server URL is missing.",scope:"chat"}),e.compatModel||o.push({key:"compatModel",message:"The model name for the OpenAI-compatible server is missing.",scope:"chat"}));const i=[{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:r,name:u,uses:l}of i){const p=l.filter(Boolean);if(!p.length||c(r))continue;const d=p.some(f=>f[1]==="chat")?"chat":p[0][1],x=p.length===1&&p[0][0]==="chat"?`${u} is missing.`:`${u} (for ${p.map(f=>f[0]).join(", ").replace(/, ([^,]*)$/," and $1")}) is missing.`;o.push({key:r,message:x,scope:d})}return o}function Ce({apiBase:e="/api",onSaved:a,onClose:o}){const[c,t]=m.useState(null),[i,r]=m.useState({}),[u,l]=m.useState(null),[p,d]=m.useState(!1),x=m.useRef(null),f=m.useCallback(async()=>{try{const s=await fetch(`${e}/settings`);if(!s.ok)throw new Error(await s.text());t(await s.json())}catch(s){l({kind:"error",text:`Could not load settings: ${s.message}`})}},[e]);if(m.useEffect(()=>{f()},[f]),!c)return n.jsx("section",{className:"tz-va__card",children:u?u.text:"Loading settings…"});const h={...c.values,...Object.fromEntries(Object.entries(i).filter(([,s])=>s!==null))},b={...c.secretsSet};for(const[s,k]of Object.entries(i))s in b&&(b[s]=k===null?!1:k?!0:b[s]);const _=De(h,b),T=new Set(_.map(s=>s.key)),E=Object.keys(i).length>0,L=(s,k)=>r(w=>({...w,[s]:k}));async function I(s,k){var w;d(!0);try{const S=await fetch(`${e}/settings`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!S.ok)throw new Error(await S.text());const v=await S.json();t(v),r({});const M=(w=v.ignored)!=null&&w.length?` Ignored unknown/invalid keys: ${v.ignored.join(", ")}.`:"";l({kind:"ok",text:k+M}),a==null||a(v)}catch(S){l({kind:"error",text:S.message})}finally{d(!1)}}async function C(){try{const s=await fetch(`${e}/settings/export`);if(!s.ok)throw new Error(await s.text());const k=new Blob([JSON.stringify(await s.json(),null,2)],{type:"application/json"}),w=document.createElement("a");w.href=URL.createObjectURL(k),w.download="tz-voice-chat-settings.json",w.click(),URL.revokeObjectURL(w.href),l({kind:"ok",text:"Exported. The file contains your API keys — keep it private."})}catch(s){l({kind:"error",text:`Export failed: ${s.message}`})}}async function D(s){var w;const k=(w=s.target.files)==null?void 0:w[0];if(s.target.value="",!!k)try{const S=JSON.parse(await k.text()),v=S&&typeof S.settings=="object"?S.settings:S;if(!v||typeof v!="object"||Array.isArray(v))throw new Error("not a settings object");await I({settings:v},`Imported ${k.name} and applied it.`)}catch(S){l({kind:"error",text:`Import failed: ${S.message}`})}}function $(s){const k=[];for(const[w,S,v]of s){const M=k[k.length-1],R=n.jsx("option",{value:w,children:S},w);v?M&&M.group===v?M.items.push(R):k.push({group:v,items:[R]}):k.push(R)}return k.map(w=>w.group?n.jsx("optgroup",{label:w.group,children:w.items},w.group):w)}function O(s){const k=`tz-va-set-${s.key}`,w=T.has(s.key);let S;if(s.type==="select")S=n.jsxs("select",{id:k,value:h[s.key]??"",onChange:v=>L(s.key,v.target.value),children:[$(s.options),s.allowCustom&&h[s.key]&&!s.options.some(([v])=>v===h[s.key])&&n.jsxs("option",{value:h[s.key],children:[h[s.key]," (custom)"]})]});else if(s.type==="textarea")S=n.jsx("textarea",{id:k,rows:4,value:h[s.key]??"",onChange:v=>L(s.key,v.target.value)});else if(s.type==="password"){const v=s.key in i,M=i[s.key]===null?"Will be cleared on save":c.secretsSet[s.key]?"Saved — type to replace":"Not set";S=n.jsxs("span",{className:"tz-va__secret",children:[n.jsx("input",{id:k,type:"password",autoComplete:"off",value:i[s.key]??"",placeholder:M,onChange:R=>L(s.key,R.target.value)}),(c.secretsSet[s.key]||v)&&n.jsx("button",{type:"button",className:"tz-va__link",onClick:()=>v?r(R=>{const K={...R};return delete K[s.key],K}):L(s.key,null),children:v?"Undo":"Clear"})]})}else S=n.jsxs(n.Fragment,{children:[n.jsx("input",{id:k,type:s.type==="number"?"number":"text",step:s.type==="number"?"any":void 0,list:s.suggestions?`${k}-list`:void 0,value:h[s.key]??"",onChange:v=>L(s.key,v.target.value)}),s.suggestions&&n.jsx("datalist",{id:`${k}-list`,children:s.suggestions.map(v=>n.jsx("option",{value:v},v))})]});return n.jsxs("div",{className:`tz-va__field${w?" tz-va__field--missing":""}`,children:[n.jsxs("label",{htmlFor:k,children:[s.label,w&&n.jsx("em",{children:" — required"})]}),S,s.hint&&n.jsx("small",{children:s.hint})]},s.key)}return n.jsxs(n.Fragment,{children:[n.jsxs("section",{className:"tz-va__card tz-va__settings",children:[_.length>0&&n.jsxs("div",{className:"tz-va__notice",role:"alert",children:[n.jsx("strong",{children:"Setup incomplete:"})," ",_.map(s=>s.message).join(" ")]}),xe.map(s=>n.jsxs("fieldset",{children:[n.jsx("legend",{children:s.group}),s.fields.filter(k=>pt(k,h)).map(O)]},s.group)),n.jsxs("p",{className:"tz-va__note",children:["Saved to ",n.jsx("code",{children:c.file})," and applied immediately. Environment variables provide the initial values."]}),n.jsxs("div",{className:"tz-va__actions",children:[n.jsx("button",{type:"button",disabled:p||!E,onClick:()=>I(i,"Settings saved and applied."),children:"Save"}),n.jsx("button",{type:"button",className:"tz-va__secondary",disabled:!E,onClick:()=>r({}),children:"Discard"}),n.jsx("span",{className:"tz-va__spacer"}),n.jsx("button",{type:"button",className:"tz-va__secondary",onClick:()=>{var s;return(s=x.current)==null?void 0:s.click()},children:"Import…"}),n.jsx("button",{type:"button",className:"tz-va__secondary",onClick:C,children:"Export"}),n.jsx("input",{ref:x,type:"file",accept:"application/json,.json",hidden:!0,onChange:D})]}),u&&n.jsx("p",{className:`tz-va__status tz-va__status--${u.kind}`,children:u.text})]}),o&&n.jsx("div",{className:"tz-va__actions",children:n.jsx("button",{type:"button",className:"tz-va__secondary",onClick:o,children:"← Back to chat"})})]})}const We=(e,a)=>e==="webgpu"&&(a==="q4"||a==="q8")?"fp32":a,ke=e=>e>=1e3?`${(e/1e3).toFixed(1)} s`:`${e} ms`,Le=e=>`${(e/1048576).toFixed(0)} MB`;function ft(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} · ${We(e.kokoroBrowserDevice,e.kokoroDtype)}/${e.kokoroBrowserDevice}`}}const mt=e=>e.replace(/\b\w/g,a=>a.toUpperCase());function vt({apiBase:e="/api",title:a="Voice Assistant",showInfo:o=!0,systemPrompt:c,className:t=""}={}){const{chat:i,info:r,config:u,memory:l,llmProgress:p,note:d,loading:x,missing:f,reload:h}=ze({apiBase:e,systemPrompt:c}),[b,_]=m.useState("chat"),{status:T,progress:E,error:L,transcript:I,streamingMessage:C,micEnabled:D,startListening:$,stopListening:O,submitText:s,liveAnalyser:k,devices:w,selectedMicId:S,setSelectedMicId:v}=i,[M,R]=m.useState(""),K=m.useRef(null);m.useEffect(()=>{var j;(j=K.current)==null||j.scrollIntoView({behavior:C!==null?"auto":"smooth"})},[I,C]);const Q=r&&u.whisperDevice&&[["STT",r.sttProvider==="elevenlabs"?`ElevenLabs · ${r.elevenlabsSttModel}`:r.sttProvider==="openai"?`OpenAI · ${r.openaiSttModel}`:`Whisper · ${(u.whisperModel||r.whisperModel).split("/").pop()} · ${We(u.whisperDevice,u.whisperDtype)}/${u.whisperDevice}`],["TTS",ft({...r,...u})],["Chat",r.chatProvider==="local"?"SmolLM2-360M-Instruct (in-browser) — slow and simple":r.chatReady?`${r.chatProvider} · ${r.chatModel}`:"not configured"],["Memory",[l.browser!=null?`browser heap ${Le(l.browser)}`:"browser heap n/a",l.server!=null?`server ${Le(l.server)}`:null].filter(Boolean).join(" · ")]];return n.jsxs("div",{className:`tz-va ${t}`.trim(),children:[n.jsxs("section",{className:"tz-va__card tz-va__header",children:[n.jsx("h1",{children:a}),n.jsxs("span",{className:"tz-va__header-right",children:[n.jsx("span",{className:`tz-va__chip tz-va__chip--${T}`,children:mt(T)}),n.jsx("button",{type:"button",className:`tz-va__gear${b==="settings"?" tz-va__gear--on":""}`,"aria-label":"Settings",title:"Settings",onClick:()=>_(j=>j==="settings"?"chat":"settings"),children:n.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:[n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.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"})]})})]})]}),f.length>0&&b!=="settings"&&n.jsxs("section",{className:"tz-va__card tz-va__notice",role:"alert",children:[n.jsxs("div",{children:[n.jsx("strong",{children:"Setup incomplete."})," ",f.map(j=>j.message).join(" ")]}),n.jsx("button",{type:"button",onClick:()=>_("settings"),children:"Open Settings"})]}),b==="settings"?n.jsx(Ce,{apiBase:e,onSaved:h,onClose:()=>_("chat")}):n.jsxs(n.Fragment,{children:[o&&Q&&n.jsx("section",{className:"tz-va__card tz-va__info",children:Q.map(([j,se])=>n.jsxs("div",{className:"tz-va__info-row",children:[n.jsx("span",{className:"tz-va__info-label",children:j}),n.jsx("span",{className:"tz-va__info-value",children:se})]},j))}),n.jsxs("section",{className:"tz-va__card",children:[x&&n.jsxs("div",{className:"tz-va__progress",children:[u.sttProvider!=="server"&&n.jsxs("label",{children:["Whisper STT",n.jsx("div",{className:"tz-va__bar",children:n.jsx("span",{style:{width:`${E.whisper*100}%`}})})]}),n.jsxs("label",{children:["Kokoro TTS",n.jsx("div",{className:"tz-va__bar",children:n.jsx("span",{style:{width:`${E.kokoro*100}%`}})})]}),p>0&&n.jsxs("label",{children:["Local LLM",n.jsx("div",{className:"tz-va__bar",children:n.jsx("span",{style:{width:`${p*100}%`}})})]})]}),n.jsx("div",{className:"tz-va__button",children:n.jsx(Ne,{status:T,active:D,loading:x,analyser:k,onToggle:D?O:$,devices:w,selectedMicId:S,onDeviceChange:v,inputData:M,sendData:j=>{R(""),s(j)}})}),n.jsx("div",{className:"tz-va__input-row",children:n.jsx("input",{type:"text",className:"tz-va__input",value:M,onChange:j=>R(j.target.value),onKeyDown:j=>{j.key==="Enter"&&M.trim()&&(R(""),s(M))},placeholder:"Type a message…",disabled:x})}),n.jsx("p",{className:"tz-va__note",children:x?E.kokoro<1?"Loading Kokoro TTS…":E.whisper<1?"Loading Whisper STT…":p>0&&p<1?"Loading local LLM (SmolLM2-360M, ~200 MB)…":"Finishing up…":"Ready."}),d&&n.jsx("p",{className:"tz-va__note",children:d})]}),n.jsxs("section",{className:"tz-va__card tz-va__transcript",children:[I.map(j=>n.jsxs("div",{className:`tz-va__message tz-va__message--${j.role}`,children:[n.jsx("small",{children:j.role==="user"?"You":"Assistant"}),n.jsx("p",{children:j.content}),j.timings&&n.jsxs("div",{className:"tz-va__timings",children:[j.timings.transcribeMs!=null&&n.jsxs("span",{children:["transcribe ",ke(j.timings.transcribeMs)]}),j.timings.thinkMs!=null&&n.jsxs("span",{children:["think ",ke(j.timings.thinkMs)]}),j.timings.ttsMs!=null&&n.jsxs("span",{children:["tts ",ke(j.timings.ttsMs)]})]})]},j.id)),C!==null&&n.jsxs("div",{className:"tz-va__message tz-va__message--assistant tz-va__message--streaming",children:[n.jsx("small",{children:"Assistant"}),n.jsxs("p",{children:[C,n.jsx("span",{className:"tz-va__cursor"})]})]}),n.jsx("div",{ref:K})]}),L?n.jsxs("section",{className:"tz-va__card",children:[n.jsx("strong",{children:"Error:"}),n.jsx("p",{children:L})]}):null]})]})}exports.AIAssistantButton=Ne;exports.SETTINGS_SCHEMA=xe;exports.STATES=P;exports.SettingsPanel=Ce;exports.TZVoiceChat=Te;exports.VoiceAssistant=vt;exports.computeMissing=De;exports.createLocalChatStream=Re;exports.sendChatRequest=Oe;exports.useVoiceAssistant=ze;
|
|
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;
|