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