tz-voice-chat 1.1.2 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +647 -148
  3. package/bin/tz-voice-chat.js +57 -0
  4. package/dist/assets/llmWorker-CmV-b4uq.js +1 -0
  5. package/dist/assets/whisperWorker-rOnua0b5.js +1 -0
  6. package/dist/index.cjs +2 -2
  7. package/dist/index.js +1557 -699
  8. package/dist/style.css +1 -1
  9. package/dist-app/assets/index-Bcmhe9G_.css +1 -0
  10. package/dist-app/assets/index-Wcfqx97N.js +41 -0
  11. package/dist-app/assets/llmWorker-CmV-b4uq.js +1 -0
  12. package/dist-app/assets/whisperWorker-rOnua0b5.js +1 -0
  13. package/dist-app/index.html +27 -0
  14. package/package.json +45 -11
  15. package/server/chat.js +91 -0
  16. package/server/elevenlabs.js +40 -0
  17. package/server/index.js +173 -92
  18. package/server/openai-stt.js +21 -0
  19. package/server/run.js +56 -0
  20. package/server/settings.js +102 -0
  21. package/server/tts.js +26 -3
  22. package/server/vendor.js +57 -0
  23. package/shared/settingsSchema.js +212 -0
  24. package/vendor/kokoro/kokoro.web.js +1 -0
  25. package/vendor/ort/ort-wasm-simd-threaded.jsep.mjs +125 -0
  26. package/vendor/ort/ort-wasm-simd-threaded.jsep.wasm +0 -0
  27. package/vendor/ort/ort-wasm-simd-threaded.mjs +70 -0
  28. package/vendor/ort/ort-wasm-simd-threaded.wasm +0 -0
  29. package/vendor/ort/ort.wasm.min.js +8 -0
  30. package/vendor/transformers/ort-wasm-simd-threaded.jsep.mjs +125 -0
  31. package/vendor/transformers/ort-wasm-simd-threaded.jsep.wasm +0 -0
  32. package/vendor/transformers/transformers.min.js +2 -0
  33. package/vendor/transformers/transformers.node.min.mjs +2 -0
  34. package/vendor/transformers/transformers.node.mjs +36472 -0
  35. package/vendor/vad/bundle.min.js +2 -0
  36. package/vendor/vad/silero_vad_legacy.onnx +0 -0
  37. package/vendor/vad/vad.worklet.bundle.min.js +1 -0
  38. package/dist/assets/llmWorker-CVEGn6yI.js +0 -1
  39. package/dist/assets/whisperWorker-BJuP9cl9.js +0 -1
package/README.md CHANGED
@@ -1,211 +1,710 @@
1
1
  # tz-voice-chat
2
2
 
3
- A self-contained React hook and UI component that wire together a full voice-chat pipeline:
3
+ A complete **voice assistant** you can run in one command, and the building blocks to make your own:
4
4
 
5
5
  ```
6
- Microphone → VAD → Whisper STT → your AI function → Kokoro / OpenAI / WebSpeech TTS
6
+ Microphone → VAD → speech-to-text → your chat logic (or an LLM) → text-to-speech → speaker
7
7
  ```
8
8
 
9
- You provide the AI logic. The hook handles everything else.
9
+ - **Run it now:** `npx tz-voice-chat` — a ready web app with a Settings page. No `.env`, no code.
10
+ - **Make it yours:** React hooks and components for the browser, plus an Express router for the server. Replace any stage — in particular the "chat logic" — with your own.
11
+ - **Pick your providers:** every stage works locally for free *or* in the cloud, switchable at runtime.
12
+
13
+ | Stage | Local · free | Cloud |
14
+ |---|---|---|
15
+ | Speech-to-text | Whisper in the browser | OpenAI transcription, ElevenLabs Scribe |
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 |
18
+
19
+ ## Contents
20
+
21
+ 1. [Quick start](#quick-start)
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)
10
28
 
11
29
  ---
12
30
 
13
- ## Install
31
+ ## Quick start
14
32
 
15
33
  ```bash
16
- npm install tz-voice-chat
34
+ npx tz-voice-chat # then open http://127.0.0.1:3000
17
35
  ```
18
36
 
19
- Peer dependencies (install separately):
37
+ Requires Node 18+ and a modern browser. The install is light: one runtime dependency (`express`), no native code and no install scripts. Defaults work without any keys: Whisper `small.en` for speech-to-text, Kokoro (`af_bella`) for text-to-speech — both on WebGPU — and the in-browser SmolLM2 model for chat. The first load downloads the models (hundreds of MB).
38
+
39
+ Open the **Settings** page (gear icon) to choose a better chat model (OpenAI, Claude, Ollama…), cloud speech, voices and so on. Changes are saved and applied immediately — no restart. If something required is missing (say an API key for the provider you picked), a notice tells you what.
20
40
 
21
- ```bash
22
- npm install react @huggingface/transformers @ricky0123/vad-web
23
- # Optional — only for ttsProvider: 'kokoro' (browser-side synthesis):
24
- npm install kokoro-js
25
41
  ```
42
+ -p, --port <n> Port (default $PORT or 3000)
43
+ --host <addr> Address to bind (default 127.0.0.1)
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)
46
+ ```
47
+
48
+ - **Export / Import** on the Settings page saves/loads every setting as a JSON file. The export **includes your API keys** — keep it private.
49
+ - The page never receives saved keys: a saved key shows as "Saved" and is replaced only when you type a new one.
50
+ - Environment variables (listed in the [settings reference](#settings-reference)) pre-seed the initial values; whatever you save in Settings wins.
51
+ - The server binds to loopback by default because the Settings endpoints can read and write API keys. Use `--host 0.0.0.0` only on a network you trust.
26
52
 
27
53
  ---
28
54
 
29
- ## Quick start
55
+ ## Use it from a phone or another computer
30
56
 
31
- ```jsx
32
- import { TZVoiceChat, AIAssistantButton } from 'tz-voice-chat';
33
- import 'tz-voice-chat/style.css';
57
+ Browsers only expose the **microphone** (and **WebGPU**) to pages served over **`https://`** or from **`localhost`**. So:
34
58
 
35
- function MyApp() {
36
- const {
37
- status, // 'idle' | 'listening' | 'transcribing' | 'thinking' | 'speaking'
38
- loading, // true while Whisper + TTS models are loading
39
- progress, // { whisper: 0–1, kokoro: 0–1 }
40
- error,
41
- transcript, // [{ role, content, time }]
42
- streamingMessage,// partial assistant response, or null
43
- micEnabled,
44
- startListening,
45
- stopListening,
46
- speak, // speak(text) — directly synthesise any text
47
- liveAnalyser, // AnalyserNode for waveform UI, or null
48
- devices, // MediaDeviceInfo[] — audio inputs
49
- selectedMicId,
50
- setSelectedMicId,
51
- } = TZVoiceChat({
52
- // ── Required ─────────────────────────────────────────────────────────
53
- // Async generator that receives the user utterance, full conversation
54
- // history, and an AbortSignal. Yield response tokens/chunks.
55
- processInput: async function* (text, history, signal) {
56
- const res = await fetch('/api/chat', {
57
- method: 'POST',
58
- headers: { 'Content-Type': 'application/json' },
59
- body: JSON.stringify({ messages: history }),
60
- signal,
61
- });
62
- const reader = res.body.getReader();
63
- const dec = new TextDecoder();
64
- let buf = '';
65
- while (true) {
66
- const { value, done } = await reader.read();
67
- if (done) break;
68
- buf += dec.decode(value, { stream: true });
69
- const lines = buf.split('\n');
70
- buf = lines.pop();
71
- for (const line of lines) {
72
- const data = line.replace(/^data:\s*/, '');
73
- if (data === '[DONE]') return;
74
- try { const token = JSON.parse(data).choices?.[0]?.delta?.content; if (token) yield token; }
75
- catch (_) {}
76
- }
77
- }
78
- },
79
-
80
- // ── Optional ─────────────────────────────────────────────────────────
81
- ttsProvider: 'server-kokoro', // 'server-kokoro' | 'kokoro' | 'openai' | 'webspeech'
82
- ttsVoice: 'af_bella',
83
- ttsServerUrl: '/api/tts', // POST endpoint for server-side TTS
84
- whisperModel: 'onnx-community/whisper-tiny.en',
85
- whisperDtype: 'q8',
86
- whisperDevice: 'cpu', // 'cpu' | 'webgpu'
87
- modelProxyUrl: '/api/models/', // proxies HuggingFace model downloads
88
- });
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 | ✅ | ✅ | ✅ |
89
64
 
90
- return (
91
- <div>
92
- <p>Status: {status}</p>
93
- <button onClick={micEnabled ? stopListening : startListening} disabled={loading}>
94
- {micEnabled ? 'Stop' : 'Start'}
95
- </button>
96
- <button onClick={() => speak('Hello! How can I help you?')}>Say hello</button>
97
- {transcript.map((msg, i) => (
98
- <p key={i}><b>{msg.role}</b>: {msg.content}</p>
99
- ))}
100
- </div>
101
- );
102
- }
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
103
75
  ```
104
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
+
105
89
  ---
106
90
 
107
- ## API
91
+ ## Architecture overview
108
92
 
109
- ### `TZVoiceChat(options)`
93
+ ### The big picture
110
94
 
111
- #### Required option
95
+ ```
96
+ ┌─ BROWSER (your page) ───────────────────────────────────────────────────────────┐
97
+ │ UI VoiceAssistant · SettingsPanel · AIAssistantButton │
98
+ │ │ useVoiceAssistant (config, backends, Settings) │
99
+ │ Pipeline TZVoiceChat: mic → VAD → STT → processInput() → TTS → speaker │
100
+ │ │
101
+ │ Runs locally Whisper (Web Worker) · Kokoro (WebGPU) · SmolLM2 · Web Speech API │
102
+ └──────────────────────────────────────────────────────────────────────────────────┘
103
+ │ same-origin HTTP: /api/* and /vendor/*
104
+ ┌─ YOUR SERVER (tz-voice-chat/server, Express) ───────────────────────────────────┐
105
+ │ GET /config PUT /settings settings.json: API keys live HERE, not in the page│
106
+ │ POST /chat /stt /tts adapters: one request shape in, provider's out │
107
+ │ GET /models/* Hugging Face GET /vendor/* ONNX · VAD · transformers runtime │
108
+ └──────────────────────────────────────────────────────────────────────────────────┘
109
+ │ server-to-server — the keys are attached here
110
+ ┌─ PROVIDERS ──────────────────────────────────────────────────────────────────────┐
111
+ │ Chat OpenAI · Anthropic · OpenRouter · Hugging Face · Ollama/LM Studio/vLLM │
112
+ │ STT OpenAI · ElevenLabs TTS OpenAI · ElevenLabs · Kokoro (server) │
113
+ │ Models huggingface.co (reached only through /models/*) │
114
+ └──────────────────────────────────────────────────────────────────────────────────┘
115
+ ```
112
116
 
113
- | Option | Type | Description |
114
- |---|---|---|
115
- | `processInput` | `async function*(text, history, signal)` | Your AI processor. Called after each user utterance. `history` is the full `[{role,content}]` array. Yield response tokens. |
117
+ Everything in the top box runs in the page. Anything that needs a secret, a vendor API, or a large file goes through the server in the middle.
116
118
 
117
- #### Optional options
119
+ ### Why a server is required
118
120
 
119
- | Option | Default | Description |
120
- |---|---|---|
121
- | `systemPrompt` | friendly voice assistant prompt | System message prepended to all conversations |
122
- | `ttsProvider` | `'server-kokoro'` | `'server-kokoro'` \| `'kokoro'` \| `'openai'` \| `'webspeech'` |
123
- | `ttsVoice` | `'af_bella'` | Voice name for Kokoro / OpenAI TTS |
124
- | `ttsServerUrl` | `'/api/tts'` | POST endpoint for server-side TTS (receives `{text, voice}`, returns audio) |
125
- | `ttsSpeechRate` | `1` | WebSpeech rate |
126
- | `ttsSpeechPitch` | `1` | WebSpeech pitch |
127
- | `whisperModel` | `'onnx-community/whisper-tiny.en'` | HuggingFace model ID |
128
- | `whisperDtype` | `'q8'` | `'q4'` \| `'q8'` \| `'fp32'` |
129
- | `whisperDevice` | `'cpu'` | `'cpu'` \| `'webgpu'` |
130
- | `kokoroDtype` | `'q8'` | Browser Kokoro dtype (when `ttsProvider: 'kokoro'`) |
131
- | `kokoroBrowserDevice` | `'wasm'` | `'wasm'` \| `'webgpu'` |
132
- | `modelProxyUrl` | `'/api/models/'` | Base URL for model downloads (proxies HuggingFace) |
121
+ The browser can do speech recognition, speech synthesis and even a small LLM by itself. A server is needed for everything else — and it is intentionally thin:
133
122
 
134
- #### Return value
123
+ ```
124
+ WITHOUT a server WITH tz-voice-chat/server
125
+ ──────────────── ─────────────────────────
126
+ Browser ──(API key inside your JS)──▶ OpenAI Browser ──▶ /api/chat ──(key stays here)──▶ OpenAI
127
+ ✗ anyone can read the key in DevTools ✓ the key never reaches the page
128
+ ✗ many providers block or discourage direct ✓ same origin: no CORS problems
129
+ browser calls (CORS, keys in client code) ✓ one stream format for every provider
130
+ ✗ every provider streams in a different format ✓ settings survive reloads and restarts
131
+ ```
135
132
 
136
- | Field | Type | Description |
137
- |---|---|---|
138
- | `status` | `string` | `'idle'` \| `'listening'` \| `'transcribing'` \| `'thinking'` \| `'speaking'` |
139
- | `loading` | `boolean` | `true` while Whisper + TTS are loading |
140
- | `progress` | `{whisper:number, kokoro:number}` | Per-model load progress (0–1) |
141
- | `error` | `string\|null` | Last error message |
142
- | `transcript` | `{role,content,time}[]` | Completed conversation turns |
143
- | `streamingMessage` | `string\|null` | Partial assistant response being streamed |
144
- | `micEnabled` | `boolean` | Whether microphone is open |
145
- | `startListening()` | `() => Promise<void>` | Open microphone and start pipeline |
146
- | `stopListening()` | `() => void` | Close microphone and cancel in-progress pipeline |
147
- | `speak(text)` | `(text:string) => void` | Synthesise and play text immediately |
148
- | `liveAnalyser` | `AnalyserNode\|null` | Real-time frequency data for waveform UI |
149
- | `devices` | `MediaDeviceInfo[]` | Available audio input devices |
150
- | `selectedMicId` | `string` | Selected device ID (`''` = system default) |
151
- | `setSelectedMicId` | `(id:string) => void` | Select an audio input device |
133
+ | Reason | What the server does |
134
+ |---|---|
135
+ | **Secrets** | API keys (OpenAI, Anthropic, ElevenLabs, OpenRouter, Hugging Face) are stored in `settings.json` on the server. `GET /settings` never returns them — only whether each one is set. |
136
+ | **CORS and browser limits** | Calls to provider APIs are made server-to-server, so they work regardless of what the vendor allows from a web page. This is also how a local model (Ollama, LM Studio) on the server's network becomes reachable. |
137
+ | **One streaming format** | Anthropic streams differently from OpenAI. The server converts every chat provider to the same OpenAI-style event stream, so the client has a single parser. |
138
+ | **Model files** | `GET /models/*` proxies Hugging Face downloads through your origin (cacheable, mirrorable, works behind a firewall). The browser never talks to huggingface.co directly. |
139
+ | **Runtime assets** | ONNX Runtime WASM files, the VAD model and the transformers/Kokoro bundles are loaded **by URL** at runtime, and must be same-origin. They ship inside the package (`vendor/`, about 62 MB — a ~16 MB download), and `createVendorRouter()` serves them at `/vendor/*`. Nothing is fetched from a CDN, and nothing native is installed. |
140
+ | **Server-side speech** | `server-kokoro` runs Kokoro in Node, so browsers without WebGPU still get good TTS. OpenAI/ElevenLabs STT and TTS are proxied here too. |
141
+ | **Persistent settings** | The Settings page saves to a file; the server applies changes live (and reloads server-side Kokoro when its parameters change). |
152
142
 
153
- ---
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.
154
144
 
155
- ## Server requirements
145
+ ### One conversation turn
156
146
 
157
- For `ttsProvider: 'server-kokoro'` or `'openai'`:
147
+ ```
148
+ you speak
149
+ │ VAD (voice-activity detection) finds the end of the utterance → 16 kHz audio
150
+ ▼
151
+ SPEECH-TO-TEXT ── Whisper in a Web Worker ───────────────── or ── POST /api/stt ──▶ OpenAI / ElevenLabs
152
+ │ text (audio sent as a WAV file)
153
+ │ → timing "transcribe"
154
+ ▼
155
+ processInput(text, history, signal) ◀── YOUR CODE, or POST /api/chat ──▶ the configured provider
156
+ │ an async generator: yields text chunks as they are produced
157
+ │ → timing "think" = time to the first chunk
158
+ ▼
159
+ SENTENCE CHUNKER small first chunk (fast first audio), then whole sentences (natural prosody)
160
+ ▼
161
+ TEXT-TO-SPEECH queue ── Kokoro (browser) ─ Web Speech ─ or ── POST /api/tts ──▶ server Kokoro / OpenAI / ElevenLabs
162
+ │ audio clips are trimmed of silence and played back to back
163
+ │ → timing "tts" = first sentence queued → audio starts
164
+ ▼
165
+ speaker
166
+
167
+ BARGE-IN: if you start talking while it is speaking, playback stops and `signal` aborts the
168
+ in-flight request, so your processInput can cancel its LLM call.
169
+ ```
158
170
 
159
- - `POST /api/tts` — accepts `{ text: string, voice?: string }`, returns audio (`audio/wav` or `audio/mpeg`)
171
+ ### Status state machine
160
172
 
161
- For model downloads (Whisper STT, browser Kokoro TTS):
173
+ `status` (from `TZVoiceChat`) tells your UI what to show:
162
174
 
163
- - `GET /api/models/*` — proxies HuggingFace Hub downloads (or set `modelProxyUrl` to a direct URL)
175
+ ```
176
+ idle ──startListening()──▶ listening ──speech ends──▶ transcribing ──text──▶ thinking ──first chunk──▶ speaking
177
+ ▲ ▲ │
178
+ └────stopListening()────────┴───── playback finished (back to listening while the mic is on) ◀────────┘
179
+ ```
180
+
181
+ Typed messages (`submitText`) skip the first two steps and enter at `thinking`.
182
+
183
+ ### Where settings come from
184
+
185
+ ```
186
+ built-in defaults < environment variables < router `defaults` option < saved settings file
187
+ (shared/settingsSchema.js) (~/.tz-voice-chat/settings.json,
188
+ written by the Settings page)
189
+ ```
164
190
 
165
- The included example app ([`src/App.jsx`](../../src/App.jsx)) demonstrates a complete Express server setup for all of the above.
191
+ One schema file, `shared/settingsSchema.js`, defines every setting (key, label, env variable, default, whether it is secret, when it is shown) and the "what is still missing" rules. The server validates with it and the Settings form is generated from it — so adding a setting means adding one entry.
166
192
 
167
193
  ---
168
194
 
169
- ## Infrastructure diagram
195
+ ## Components
170
196
 
171
197
  ```
172
- TZVoiceChat hook
173
- ├── VAD (@ricky0123/vad-web, IIFE — loaded via <script> in index.html)
174
- ├── Whisper Worker (Web Worker — @huggingface/transformers, auto-speech-recognition)
175
- ├── TTS Queue (server-kokoro | kokoro | openai | webspeech)
176
- └── processInput ← YOU provide this (async generator)
198
+ tz-voice-chat
199
+ ├── Client (import from 'tz-voice-chat')
200
+ │ ├── VoiceAssistant full UI: status, setup notice, info card, mic button, input, transcript, Settings
201
+ │ │ ├── SettingsPanel Settings page (form from the schema, save, import / export)
202
+ │ │ └── AIAssistantButton animated mic button with waveform and microphone picker
203
+ │ ├── useVoiceAssistant "batteries included" hook: loads /config, picks the chat backend, tracks what's missing
204
+ │ │ └── TZVoiceChat the pipeline hook: VAD → STT → processInput → TTS (+ transcript, status, timings)
205
+ │ │ └── modules/ vad · whisperWorker · chunker · ttsQueue · serverTtsQueue · webSpeechTts · wav
206
+ │ └── sendChatRequest / createLocalChatStream the two ready-made `processInput` backends
207
+ │
208
+ ├── Server (import from 'tz-voice-chat/server')
209
+ │ ├── createVoiceAssistantRouter() Express router: /config /settings /stats /chat /stt /tts /models/*
210
+ │ │ ├── settings store defaults < env < options < saved file; secrets stay server-side
211
+ │ │ └── adapters chat (OpenAI-compatible · Anthropic) · stt (OpenAI · ElevenLabs) · tts (Kokoro · OpenAI · ElevenLabs)
212
+ │ └── createVendorRouter() /vendor/* — ONNX runtime, VAD, transformers, Kokoro (from node_modules)
213
+ │
214
+ └── CLI `tz-voice-chat` server + vendor assets + prebuilt web page, in one command
215
+ ```
216
+
217
+ | Component | You'd use it to… |
218
+ |---|---|
219
+ | `VoiceAssistant` | drop in a finished UI (one line) |
220
+ | `useVoiceAssistant` | build your own UI but keep config, backends and Settings handled for you |
221
+ | `TZVoiceChat` | build your own UI **and** your own chat logic, with full control over every option |
222
+ | `AIAssistantButton` | reuse just the animated mic button |
223
+ | `SettingsPanel` | reuse just the Settings page |
224
+ | `createVoiceAssistantRouter` | get `/stt` `/tts` `/chat` `/models` `/settings` without writing them |
225
+ | `createVendorRouter` | serve the browser runtime assets without copying files |
177
226
 
178
- AIAssistantButton component
179
- └── 5-state animated button with waveform visualiser and mic selector
227
+ ### Choose your level
228
+
229
+ ```
230
+ Level 1 CLI npx tz-voice-chat no code
231
+ Level 2 Drop-in UI <VoiceAssistant /> + router ~10 lines
232
+ Level 3 Your UI useVoiceAssistant + your JSX (+ SettingsPanel) your layout, our plumbing
233
+ Level 4 Your UI + your brain TZVoiceChat({ processInput }) + router for speech full control ◀── the tutorial below
180
234
  ```
181
235
 
182
236
  ---
183
237
 
184
- ## Full assistant in two files (UI + server)
238
+ ## Build your own chat
185
239
 
186
- Besides the `TZVoiceChat` hook, the package ships a ready-made UI and the matching Express backend.
240
+ This tutorial builds **Level 4**: your own React UI and your own chat logic (the "brain"), with tz-voice-chat doing the hard parts — microphone, voice detection, speech-to-text, sentence chunking, text-to-speech and interruptions. The brain here is a tiny echo so it runs without keys; in the last step you swap it for a real LLM, RAG, tools — anything that can produce text.
187
241
 
188
- **Client**
242
+ The project in steps 1–6, and the Level 3 shortcut after it, was built and run exactly as written (Node 20, Express 5, Vite). The Ollama snippet in step 7 is illustrative.
189
243
 
190
- ```jsx
191
- import { VoiceAssistant } from 'tz-voice-chat';
192
- import 'tz-voice-chat/style.css';
244
+ ### 1. Project setup
193
245
 
194
- export default () => <VoiceAssistant />; // props: apiBase='/api', title, showInfo, systemPrompt, className
246
+ ```bash
247
+ mkdir my-voice-chat && cd my-voice-chat
248
+ npm init -y && npm pkg set type=module
249
+ npm install tz-voice-chat express react react-dom
250
+ npm install -D vite @vitejs/plugin-react
251
+ mkdir src
252
+ npm pkg set scripts.dev="vite" scripts.build="vite build" scripts.start="node server.js"
195
253
  ```
196
254
 
197
- `VoiceAssistant` (built on the `useVoiceAssistant` hook) renders the status header, an info card (STT / TTS / chat model / memory), the mic button, a typed-message box, and a transcript with per-message timings (`transcribe`, `think`, `tts`). Esc stops listening. It uses the server chat proxy when the server has an API key, otherwise an in-browser SmolLM2 model.
255
+ ### 2. The server — `server.js`
198
256
 
199
- **Server** (`express` and, for `TTS_PROVIDER=server-kokoro`, `kokoro-js` are peer dependencies)
257
+ The server does what the browser must not: model downloads, runtime files, keys and cloud calls. You mount the package router, then add **your** endpoint beside it.
200
258
 
201
259
  ```js
202
260
  import express from 'express';
203
- import { createVoiceAssistantRouter } from 'tz-voice-chat/server';
261
+ import path from 'node:path';
262
+ import { fileURLToPath } from 'node:url';
263
+ import { createVoiceAssistantRouter, createVendorRouter } from 'tz-voice-chat/server';
204
264
 
205
265
  const app = express();
206
- const { router, ready } = createVoiceAssistantRouter(); // options default to env vars
207
- app.use('/api', router); // /config /stats /chat /tts /models/*
208
- ready().then(() => app.listen(3000));
266
+
267
+ // Everything the browser must not do itself: model downloads, API keys, cloud STT/TTS, settings.
268
+ const { router, ready } = createVoiceAssistantRouter();
269
+ app.use('/api', router); // /api/config /api/stt /api/tts /api/models/* ...
270
+ app.use('/vendor', createVendorRouter()); // ONNX / VAD / transformers runtime files
271
+
272
+ // YOUR chat logic. Swap this echo for an LLM call, RAG, tool use, a database lookup...
273
+ app.post('/api/ask', express.json(), async (req, res) => {
274
+ const { messages } = req.body;
275
+ const last = messages.at(-1)?.content ?? '';
276
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
277
+ for (const word of `You said: ${last}`.split(' ')) {
278
+ res.write(word + ' '); // stream as you generate
279
+ await new Promise((r) => setTimeout(r, 60));
280
+ }
281
+ res.end();
282
+ });
283
+
284
+ const dist = path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'dist');
285
+ app.use(express.static(dist));
286
+ app.use((req, res) => res.sendFile(path.join(dist, 'index.html'))); // SPA fallback (works in Express 4 and 5)
287
+
288
+ const port = process.env.PORT || 3000;
289
+ ready().then(() => app.listen(port, () => console.log(`http://localhost:${port}`)));
290
+ ```
291
+
292
+ - `createVoiceAssistantRouter()` gives you `/api/config`, `/api/stt`, `/api/tts`, `/api/models/*`, `/api/chat`, `/api/settings` …
293
+ - `createVendorRouter()` serves the browser runtime files at `/vendor/*`.
294
+ - `/api/ask` is your brain. It receives the whole conversation and streams plain text back. (Express 4 or 5 both work.)
295
+
296
+ ### 3. The page — `index.html`
297
+
298
+ Two things must exist before your app starts: an import map (Kokoro imports `@huggingface/transformers` by bare name) and the VAD scripts (a classic bundle that defines `window.vad`).
299
+
300
+ ```html
301
+ <!doctype html>
302
+ <html lang="en">
303
+ <head>
304
+ <meta charset="UTF-8" />
305
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
306
+ <title>My voice chat</title>
307
+ <style>body { margin: 0; background: #0f172a; }</style>
308
+ <!-- kokoro-js imports @huggingface/transformers as a bare specifier at runtime. -->
309
+ <script type="importmap">
310
+ { "imports": { "@huggingface/transformers": "/vendor/transformers/transformers.min.js" } }
311
+ </script>
312
+ <!-- The VAD bundle is a classic script that defines window.vad (and needs onnxruntime-web first). -->
313
+ <script src="/vendor/ort/ort.wasm.min.js"></script>
314
+ <script src="/vendor/vad/bundle.min.js"></script>
315
+ </head>
316
+ <body>
317
+ <div id="root"></div>
318
+ <script type="module" src="/src/main.jsx"></script>
319
+ </body>
320
+ </html>
321
+ ```
322
+
323
+ ### 4. Vite — `vite.config.js`
324
+
325
+ ```js
326
+ import { defineConfig } from 'vite';
327
+ import react from '@vitejs/plugin-react';
328
+
329
+ // /vendor/* files are served by the Express server at runtime, never bundled.
330
+ const isVendor = (id) => id.startsWith('/vendor/');
331
+
332
+ export default defineConfig({
333
+ plugins: [
334
+ react(),
335
+ { name: 'vendor-external', enforce: 'pre', resolveId: (id) => (isVendor(id) ? { id, external: true } : null) },
336
+ ],
337
+ // Serve the package as-is in dev: pre-bundling would break its relative Web Worker URLs.
338
+ optimizeDeps: { exclude: ['tz-voice-chat'] },
339
+ server: { proxy: { '/api': 'http://localhost:3000', '/vendor': 'http://localhost:3000' } },
340
+ build: { rollupOptions: { external: isVendor } },
341
+ worker: { rollupOptions: { external: isVendor } },
342
+ });
343
+ ```
344
+
345
+ - `/vendor/*` is never bundled — Express serves it at runtime.
346
+ - `optimizeDeps.exclude` is needed in dev because Vite's dependency pre-bundling breaks the package's Web Worker URLs.
347
+ - In dev the proxy sends `/api` and `/vendor` to Express, so run `npm start` (after one `npm run build`) in one terminal and `npm run dev` in another. Vite prints a harmless warning that the classic `<script>` tags "can't be bundled without type=module" — they are meant to stay as they are.
348
+
349
+ ### 5. The app — `src/main.jsx` and `src/App.jsx`
350
+
351
+ ```jsx
352
+ import { createRoot } from 'react-dom/client';
353
+ import App from './App.jsx';
354
+
355
+ createRoot(document.getElementById('root')).render(<App />);
356
+ ```
357
+
358
+ This is the heart of it:
359
+
360
+ ```jsx
361
+ import { useState } from 'react';
362
+ import { TZVoiceChat, AIAssistantButton } from 'tz-voice-chat';
363
+ import 'tz-voice-chat/style.css';
364
+
365
+ // Your "brain": an async generator. It receives what the user said, the whole conversation
366
+ // and an AbortSignal (fired when the user interrupts), and yields text as it is produced.
367
+ async function* ask(text, history, signal) {
368
+ const res = await fetch('/api/ask', {
369
+ method: 'POST',
370
+ headers: { 'Content-Type': 'application/json' },
371
+ body: JSON.stringify({ messages: history }),
372
+ signal,
373
+ });
374
+ if (!res.ok) throw new Error(await res.text());
375
+ const reader = res.body.getReader();
376
+ const decoder = new TextDecoder();
377
+ for (;;) {
378
+ const { value, done } = await reader.read();
379
+ if (done) return;
380
+ yield decoder.decode(value, { stream: true });
381
+ }
382
+ }
383
+
384
+ export default function App() {
385
+ const chat = TZVoiceChat({
386
+ processInput: ask,
387
+ systemPrompt: 'You are a concise voice assistant.',
388
+ // STT: Whisper runs in a Web Worker in the browser (downloaded once, ~40 MB for tiny).
389
+ whisperModel: 'onnx-community/whisper-tiny.en', whisperDtype: 'q8', whisperDevice: 'wasm',
390
+ // TTS: start with the browser's built-in voices — no download, works everywhere.
391
+ // Upgrade later: 'kokoro' (needs WebGPU), 'server-kokoro', 'openai' or 'elevenlabs'.
392
+ ttsProvider: 'webspeech',
393
+ modelProxyUrl: '/api/models/',
394
+ });
395
+ const [draft, setDraft] = useState('');
396
+
397
+ return (
398
+ <main style={{ maxWidth: 640, margin: '2rem auto', fontFamily: 'system-ui', color: '#e2e8f0' }}>
399
+ <h1>My voice chat <small>({chat.status})</small></h1>
400
+
401
+ <AIAssistantButton
402
+ status={chat.status}
403
+ active={chat.micEnabled}
404
+ loading={chat.loading}
405
+ analyser={chat.liveAnalyser}
406
+ onToggle={chat.micEnabled ? chat.stopListening : chat.startListening}
407
+ devices={chat.devices}
408
+ selectedMicId={chat.selectedMicId}
409
+ onDeviceChange={chat.setSelectedMicId}
410
+ />
411
+ {chat.loading && <p>Loading models… whisper {Math.round(chat.progress.whisper * 100)}%, tts {Math.round(chat.progress.kokoro * 100)}%</p>}
412
+
413
+ <form onSubmit={(e) => { e.preventDefault(); if (draft.trim()) { chat.submitText(draft); setDraft(''); } }}>
414
+ <input value={draft} onChange={(e) => setDraft(e.target.value)} placeholder="…or type a message" disabled={chat.loading} />
415
+ </form>
416
+
417
+ {chat.transcript.map((m) => (
418
+ <p key={m.id}>
419
+ <b>{m.role}:</b> {m.content}{' '}
420
+ {m.timings && <small>{Object.entries(m.timings).map(([k, v]) => `${k.replace('Ms', '')} ${v} ms`).join(' · ')}</small>}
421
+ </p>
422
+ ))}
423
+ {chat.streamingMessage !== null && <p><b>assistant:</b> {chat.streamingMessage}…</p>}
424
+ {chat.error && <p style={{ color: '#fca5a5' }}>Error: {chat.error}</p>}
425
+ </main>
426
+ );
427
+ }
428
+ ```
429
+
430
+ What to notice:
431
+
432
+ - **`processInput` is the only thing you must supply.** It is an async generator `(text, history, signal)`. `history` is the full `[{ role, content }]` array (system prompt first). Yield text as you get it — the pipeline speaks sentence by sentence while you are still generating. Throw an error and it appears in `chat.error`.
433
+ - **`signal`** aborts when the user interrupts (barge-in) or stops listening. Pass it to `fetch` (or your LLM SDK) so the request is cancelled.
434
+ - **`chat.status`** drives your UI (`idle` → `listening` → `transcribing` → `thinking` → `speaking`).
435
+ - **`chat.transcript`** entries have `id`, `role`, `content` and `timings` (`transcribeMs` on your messages; `thinkMs` and `ttsMs` on the assistant's).
436
+ - **`submitText(text)`** feeds typed text through the same pipeline as speech.
437
+ - **Speech options:** this example uses Whisper (in a Web Worker, downloaded once) and the browser's built-in voices, so it needs no big download. The comment shows the upgrade path; the table in [TZVoiceChat options](#tzvoicechatoptions) lists everything.
438
+
439
+ ### 6. Run it
440
+
441
+ ```bash
442
+ npm run build
443
+ npm start # http://localhost:3000 (PORT=3001 npm start to change the port)
444
+ ```
445
+
446
+ Open the page, wait for the models to load, then type a message or click the mic and talk. You should see your words, the streamed reply, and per-message timings. Click the mic button again to stop.
447
+
448
+ ### 7. Swap in a real brain
449
+
450
+ Only `/api/ask` changes. Keep the same contract — receive `messages`, stream text back — and the browser code stays as is. For example, with any OpenAI-compatible server (Ollama shown):
451
+
452
+ ```js
453
+ app.post('/api/ask', express.json(), async (req, res) => {
454
+ const upstream = await fetch('http://localhost:11434/v1/chat/completions', {
455
+ method: 'POST',
456
+ headers: { 'Content-Type': 'application/json' },
457
+ body: JSON.stringify({ model: 'llama3.2', messages: req.body.messages, stream: true }),
458
+ });
459
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
460
+ const decoder = new TextDecoder();
461
+ let buffer = '';
462
+ for await (const chunk of upstream.body) {
463
+ buffer += decoder.decode(chunk, { stream: true });
464
+ const lines = buffer.split('\n');
465
+ buffer = lines.pop();
466
+ for (const line of lines) {
467
+ if (!line.startsWith('data:') || line.includes('[DONE]')) continue;
468
+ const token = JSON.parse(line.slice(5)).choices?.[0]?.delta?.content;
469
+ if (token) res.write(token);
470
+ }
471
+ }
472
+ res.end();
473
+ });
474
+ ```
475
+
476
+ This is the place for retrieval over your documents, tool calls, a database lookup, or business rules — `history` has everything the user said so far. Or skip writing a brain at all and let the package do it:
477
+
478
+ ### Shortcut: keep our chat backends, build only the UI (Level 3)
479
+
480
+ If you don't need custom logic, `useVoiceAssistant` loads the settings from the server, wires STT/TTS/chat accordingly, tracks what is missing, and handles `Esc`. You write only the layout:
481
+
482
+ ```jsx
483
+ import { useState } from 'react';
484
+ import { useVoiceAssistant, AIAssistantButton, SettingsPanel } from 'tz-voice-chat';
485
+ import 'tz-voice-chat/style.css';
486
+
487
+ export default function App() {
488
+ // Reads /api/config, wires STT/TTS from the saved settings, picks the chat backend
489
+ // (server proxy or in-browser model), exposes what is still missing, and handles Esc.
490
+ const { chat, info, loading, missing, reload } = useVoiceAssistant();
491
+ const [showSettings, setShowSettings] = useState(false);
492
+
493
+ if (showSettings) {
494
+ return (
495
+ <div className="tz-va"> {/* the package's style scope */}
496
+ <SettingsPanel onSaved={reload} onClose={() => setShowSettings(false)} />
497
+ </div>
498
+ );
499
+ }
500
+
501
+ return (
502
+ <main style={{ maxWidth: 640, margin: '2rem auto', fontFamily: 'system-ui', color: '#e2e8f0' }}>
503
+ <h1>
504
+ My assistant <small>({chat.status})</small>{' '}
505
+ <button onClick={() => setShowSettings(true)}>Settings</button>
506
+ </h1>
507
+
508
+ {missing.length > 0 && <p style={{ color: '#fde68a' }}>Setup incomplete: {missing.map((m) => m.message).join(' ')}</p>}
509
+ {info && <p><small>Chat: {info.chatReady ? `${info.chatProvider} · ${info.chatModel}` : 'not configured'}</small></p>}
510
+
511
+ <AIAssistantButton
512
+ status={chat.status}
513
+ active={chat.micEnabled}
514
+ loading={loading}
515
+ analyser={chat.liveAnalyser}
516
+ onToggle={chat.micEnabled ? chat.stopListening : chat.startListening}
517
+ devices={chat.devices}
518
+ selectedMicId={chat.selectedMicId}
519
+ onDeviceChange={chat.setSelectedMicId}
520
+ />
521
+
522
+ {chat.transcript.map((m) => <p key={m.id}><b>{m.role}:</b> {m.content}</p>)}
523
+ {chat.streamingMessage !== null && <p><b>assistant:</b> {chat.streamingMessage}…</p>}
524
+ {chat.error && <p style={{ color: '#fca5a5' }}>Error: {chat.error}</p>}
525
+ </main>
526
+ );
527
+ }
209
528
  ```
210
529
 
211
- Environment variables: `OPENAI_PROVIDER`, `OPENROUTER_API_KEY`, `OPENROUTER_MODEL`, `HUGGINGFACE_API_KEY`, `TTS_PROVIDER`, `KOKORO_VOICE`, `KOKORO_DTYPE`, `KOKORO_DEVICE`, `KOKORO_SPEED`, `KOKORO_BROWSER_DEVICE`, `OPENAI_API_KEY`, `OPENAI_TTS_MODEL`, `OPENAI_TTS_VOICE`, `WHISPER_MODEL`, `WHISPER_DTYPE`, `WHISPER_DEVICE`, `WEBSPEECH_VOICE`, `WEBSPEECH_RATE`, `WEBSPEECH_PITCH`. Any of them can be overridden with the matching camelCase option.
530
+ With this, the chat model (OpenAI, Claude, Ollama, in-browser…) and the speech providers are whatever the user picks on the Settings page. Wrapping `SettingsPanel` in `<div className="tz-va">` gives it the package's styles.
531
+
532
+ ### Upgrading speech quality
533
+
534
+ Change only the speech options in `TZVoiceChat({...})` (or pick them in Settings when using `useVoiceAssistant`):
535
+
536
+ | Want | Use | Needs |
537
+ |---|---|---|
538
+ | Natural local voice | `ttsProvider: 'kokoro'`, `kokoroBrowserDevice: 'webgpu'`, `kokoroDtype: 'fp32'` | WebGPU browser; first load downloads 80–330 MB |
539
+ | Local voice, any browser | `ttsProvider: 'server-kokoro'` | runs in Node on your server (CPU) |
540
+ | Cloud voices | `ttsProvider: 'openai'` or `'elevenlabs'` | the key saved in Settings; `ttsServerUrl: '/api/tts'` |
541
+ | Cloud transcription | `sttProvider: 'server'` | `/api/stt` with OpenAI or ElevenLabs configured in Settings |
542
+ | More accurate local STT | `whisperModel: 'onnx-community/whisper-base.en'` or `small.en` | larger one-time download |
543
+
544
+ ---
545
+
546
+ ## Reference
547
+
548
+ ### `TZVoiceChat(options)`
549
+
550
+ The pipeline hook. Returns the state and controls below. Option changes re-initialise the speech models.
551
+
552
+ #### TZVoiceChat options
553
+
554
+ | Option | Default | Description |
555
+ |---|---|---|
556
+ | `processInput` | — (**required**) | `async function*(text, history, signal)` yielding text chunks |
557
+ | `systemPrompt` | short spoken-style prompt | First message of every conversation |
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 |
559
+ | `sttServerUrl` | `'/api/stt'` | Endpoint for `sttProvider: 'server'` |
560
+ | `whisperModel` | `'onnx-community/whisper-tiny.en'` | Hugging Face model id |
561
+ | `whisperDtype` | `'q8'` | `'q4'` · `'q8'` · `'fp16'` · `'fp32'` (q4/q8 are promoted to fp32 on WebGPU) |
562
+ | `whisperDevice` | `'wasm'` | `'wasm'` (CPU) or `'webgpu'` (`'cpu'` is accepted as an alias for `'wasm'`) |
563
+ | `ttsProvider` | `'server-kokoro'` | `'kokoro'` (browser) · `'server-kokoro'` · `'openai'` · `'elevenlabs'` · `'webspeech'`; every value except `kokoro` and `webspeech` posts to `ttsServerUrl` |
564
+ | `ttsVoice` | `'af_bella'` | Voice name / id for the provider |
565
+ | `ttsSpeed` | `1` | Kokoro speech-rate multiplier |
566
+ | `ttsServerUrl` | `'/api/tts'` | POST `{ text, voice }` → audio |
567
+ | `ttsSpeechRate` / `ttsSpeechPitch` | `1` / `1` | Web Speech |
568
+ | `kokoroDtype` | `'q8'` | Browser Kokoro precision |
569
+ | `kokoroBrowserDevice` | `'wasm'` | `'wasm'` or `'webgpu'` (see [Troubleshooting](#troubleshooting)) |
570
+ | `modelProxyUrl` | `'/api/models/'` | Base URL for model downloads |
571
+
572
+ #### Return value
573
+
574
+ | Field | Type | Description |
575
+ |---|---|---|
576
+ | `status` | `string` | `idle` · `listening` · `transcribing` · `thinking` · `speaking` |
577
+ | `loading` | `boolean` | Speech models still loading |
578
+ | `progress` | `{ whisper, kokoro }` | Load progress, 0–1 |
579
+ | `error` | `string \| null` | Last error (cleared by `startListening`) |
580
+ | `transcript` | `Array<{ id, role, content, time, timings? }>` | Completed turns. `timings`: `transcribeMs` (user), `thinkMs` and `ttsMs` (assistant) |
581
+ | `streamingMessage` | `string \| null` | The assistant reply while it streams |
582
+ | `micEnabled` | `boolean` | Microphone open |
583
+ | `startListening()` / `stopListening()` | `() => Promise \| void` | Open / close the mic and pipeline |
584
+ | `submitText(text)` | `(string) => void` | Send typed text through the pipeline |
585
+ | `speak(text)` | `(string) => void` | Speak text directly |
586
+ | `liveAnalyser` | `AnalyserNode \| null` | For waveform displays |
587
+ | `devices` · `selectedMicId` · `setSelectedMicId` | | Microphone list and selection |
588
+
589
+ ### `useVoiceAssistant({ apiBase = '/api', systemPrompt })`
590
+
591
+ Returns `{ chat, info, config, memory, llmProgress, note, loading, missing, reload }`: `chat` is the full `TZVoiceChat` result; `info` the server's `/config`; `missing` the list of unmet required settings (`{ key, message, scope }`); `reload()` re-reads the config after settings change; `memory` is `{ browser, server }` bytes. It also stops listening on `Esc`.
592
+
593
+ ### `<VoiceAssistant />`
594
+
595
+ Props: `apiBase` (`'/api'`), `title`, `showInfo` (`true`), `systemPrompt`, `className`.
596
+
597
+ ### `<AIAssistantButton />`
598
+
599
+ Props: `status`, `active`, `loading`, `analyser`, `onToggle`, `devices`, `selectedMicId`, `onDeviceChange`, `inputData` / `sendData` (a send state for typed text), and theming: `accentColor`, `uiColor`, `size`, `barHue`, `barHueRange`, `barSat`, `barLit`, `barLitRange`.
600
+
601
+ ### `<SettingsPanel apiBase onSaved onClose />`
602
+
603
+ The Settings page. `onSaved` receives the saved result (call `reload()` there); `onClose` shows a "Back" button.
604
+
605
+ ### Server exports (`tz-voice-chat/server`)
606
+
607
+ | Export | Description |
608
+ |---|---|
609
+ | `createVoiceAssistantRouter({ settingsFile?, defaults? })` | Returns `{ router, ready, settings }`. `defaults` are initial setting values (the saved file still wins). `await ready()` pre-loads server Kokoro if selected. |
610
+ | `createVendorRouter()` | Express router for `/vendor/*` runtime assets (bundled in the package) |
611
+ | `loadKokoro()` / `generateWav(text, voice, speed)` | Server-side Kokoro |
612
+
613
+ #### HTTP endpoints (relative to where you mount the router)
614
+
615
+ | Endpoint | Description |
616
+ |---|---|
617
+ | `GET /config` | Public configuration for the client, plus `missing`, `chatReady` |
618
+ | `GET /settings` | Editable values; secrets are **never** returned — only `secretsSet` |
619
+ | `PUT /settings` | Save a partial update (or `{ settings: {...} }` from an export). Unknown or invalid keys are reported in `ignored`. `null` clears a saved value. |
620
+ | `GET /settings/export` | Every setting **including secrets**, as a download |
621
+ | `POST /chat` | Body `{ messages }` → OpenAI-style SSE stream for any configured chat provider |
622
+ | `POST /stt` | Body: a WAV file → `{ text }` (OpenAI or ElevenLabs) |
623
+ | `POST /tts` | Body `{ text, voice? }` → audio (Kokoro WAV, or MP3 from OpenAI/ElevenLabs) |
624
+ | `GET /models/*` | Hugging Face model-file proxy |
625
+ | `GET /stats` | Server memory (`rss`, `heapUsed`) |
626
+
627
+ Also: `OPENAI_BASE_URL`, `ANTHROPIC_BASE_URL`, `ELEVENLABS_BASE_URL` override the vendor endpoints (proxies, gateways, test doubles).
628
+
629
+ ### Settings reference
630
+
631
+ 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.
632
+
633
+ **Chat model**
634
+
635
+ | Setting | Env variable | Default | Notes |
636
+ |---|---|---|---|
637
+ | `chatProvider` | `OPENAI_PROVIDER` | `local` | `(none)`, `local`, `openai-compatible`, `openrouter`, `openai`, `anthropic`, `huggingface` |
638
+ | `openrouterApiKey` | `OPENROUTER_API_KEY` | — | Secret. Get one at https://openrouter.ai/keys |
639
+ | `openrouterModel` | `OPENROUTER_MODEL` | `gpt-4o-mini` | e.g. openai/gpt-4o-mini, or a ":free" model |
640
+ | `openaiApiKey` | `OPENAI_API_KEY` | — | Secret. Used for OpenAI chat, transcription and/or TTS. Get one at https://platform.openai.com/api-keys |
641
+ | `openaiChatModel` | `OPENAI_CHAT_MODEL` | `gpt-4o-mini` | |
642
+ | `anthropicApiKey` | `ANTHROPIC_API_KEY` | — | Secret. Get one at https://console.anthropic.com/settings/keys |
643
+ | `anthropicModel` | `ANTHROPIC_MODEL` | `claude-haiku-5-5` | Haiku is the fastest — best for voice |
644
+ | `huggingfaceApiKey` | `HUGGINGFACE_API_KEY` | — | Secret. A token with read scope |
645
+ | `compatBaseUrl` | `OPENAI_COMPAT_BASE_URL` | `http://localhost:11434/v1` | Must serve /chat/completions. Ollama :11434, LM Studio :1234, vLLM :8000. From inside Docker use host.docker.internal instead of localhost. |
646
+ | `compatModel` | `OPENAI_COMPAT_MODEL` | — | Exactly as the server names it, e.g. llama3.2 or qwen2.5:7b-instruct |
647
+ | `compatApiKey` | `OPENAI_COMPAT_API_KEY` | — | Secret. Leave empty if the server needs no key (most local servers). |
648
+ | `systemPrompt` | — | — | Leave blank for the built-in short, spoken-style prompt. |
649
+
650
+ **Speech-to-text**
651
+
652
+ | Setting | Env variable | Default | Notes |
653
+ |---|---|---|---|
654
+ | `sttProvider` | `STT_PROVIDER` | `whisper` | `whisper`, `openai`, `elevenlabs` |
655
+ | `openaiSttModel` | `OPENAI_STT_MODEL` | `whisper-1` | Uses the OpenAI API key below |
656
+ | `openaiSttLanguage` | `OPENAI_STT_LANGUAGE` | — | ISO-639-1 code such as en; blank = detect automatically |
657
+ | `elevenlabsApiKey` | `ELEVENLABS_API_KEY` | — | Secret. Used for ElevenLabs speech-to-text and/or text-to-speech. Get one at https://elevenlabs.io/app/settings/api-keys |
658
+ | `elevenlabsSttModel` | `ELEVENLABS_STT_MODEL` | `scribe_v2` | |
659
+ | `elevenlabsLanguage` | `ELEVENLABS_STT_LANGUAGE` | — | ISO code such as en or de; blank = detect automatically |
660
+ | `whisperModel` | `WHISPER_MODEL` | `onnx-community/whisper-small.en` | `onnx-community/whisper-tiny.en`, `onnx-community/whisper-base.en`, `onnx-community/whisper-small.en` |
661
+ | `whisperDtype` | `WHISPER_DTYPE` | `fp32` | `q8`, `q4`, `fp16`, `fp32` |
662
+ | `whisperDevice` | `WHISPER_DEVICE` | `webgpu` | `wasm`, `webgpu` |
663
+
664
+ **Text-to-speech**
665
+
666
+ | Setting | Env variable | Default | Notes |
667
+ |---|---|---|---|
668
+ | `ttsProvider` | `TTS_PROVIDER` | `kokoro` | `kokoro`, `server-kokoro`, `webspeech`, `openai`, `elevenlabs` |
669
+ | `kokoroVoice` | `KOKORO_VOICE` | `af_bella` | e.g. af_bella, af_sarah, am_adam |
670
+ | `kokoroSpeed` | `KOKORO_SPEED` | `1` | 1 = normal; 1.1–1.2 often sounds more natural |
671
+ | `kokoroDtype` | `KOKORO_DTYPE` | `fp32` | `q8`, `q4`, `q4f16`, `fp16`, `fp32`. q4/q8 are promoted to fp32 on WebGPU |
672
+ | `kokoroBrowserDevice` | `KOKORO_BROWSER_DEVICE` | `webgpu` | `wasm`, `webgpu` |
673
+ | `kokoroDevice` | `KOKORO_DEVICE` | `cpu` | `cpu` |
674
+ | `openaiTtsModel` | `OPENAI_TTS_MODEL` | `tts-1` | |
675
+ | `openaiTtsVoice` | `OPENAI_TTS_VOICE` | `alloy` | |
676
+ | `elevenlabsVoiceId` | `ELEVENLABS_VOICE_ID` | `21m00Tcm4TlvDq8ikWAM` | Default is the premade "Rachel" voice. Copy another voice's ID from your ElevenLabs voice library. |
677
+ | `elevenlabsTtsModel` | `ELEVENLABS_TTS_MODEL` | `eleven_flash_v2_5` | Flash is the lowest latency — best for voice chat |
678
+ | `webSpeechVoice` | `WEBSPEECH_VOICE` | — | Exact voice name; blank = browser default |
679
+ | `webSpeechRate` | `WEBSPEECH_RATE` | `1` | 0.1 – 10 |
680
+ | `webSpeechPitch` | `WEBSPEECH_PITCH` | `1` | 0 – 2 |
681
+
682
+ ---
683
+
684
+ ## Troubleshooting
685
+
686
+ | Symptom | Cause and fix |
687
+ |---|---|
688
+ | **Blank or black page on a phone / another computer** | The page was opened over plain `http://` on a network address. Older versions crashed there (no `navigator.mediaDevices`); current versions load and explain. For the microphone use HTTPS — see [Use it from a phone](#use-it-from-a-phone-or-another-computer). |
689
+ | **The page restarts and downloads again and again on a phone** | Two causes. (1) On plain `http` there was no cache, so every reload re-downloaded the models — fixed, they are now kept in IndexedDB. (2) The tab may run out of memory while loading and the browser reloads it. On phones the in-browser chat model now loads only after the speech models are ready, and after 3 starts that never finished loading the app enters **safe mode** (smallest Whisper model, browser voice, no in-browser chat model) until you press *Retry full load*. For a lasting fix on a phone use cloud chat and speech in Settings. |
690
+ | **Stuck on "Finishing up…"** | Fixed in recent versions: the in-browser chat model never started on pages with nothing slow to load. Update the package; the status line now says "Starting the in-browser chat model…" with its own progress gauge. |
691
+ | **Microphone never starts**, `window.vad` is undefined | Your page is missing the `ort` / VAD `<script>` tags or the import map ([step 3](#3-the-page--indexhtml)). Microphone access also needs `https://` or `localhost`. |
692
+ | **`Unsupported device: "cpu"`** | The browser build accepts only `wasm` or `webgpu`. Use `whisperDevice: 'wasm'` (`'cpu'` is auto-mapped by this package). |
693
+ | **Kokoro never finishes loading / is very slow** | The model is 80–330 MB depending on precision, and it downloads through your server — a slow link means a long first load. Browser Kokoro on `wasm` runs on the main thread and can be very slow; prefer `webgpu`, `server-kokoro`, or the Web Speech API. |
694
+ | **Chat says "not configured"** | Open Settings and pick a provider. If the provider needs a key, the notice names it. |
695
+ | **OpenAI-compatible server unreachable** | The *tz-voice-chat server* makes the request, so the URL must be reachable from there. Inside Docker, use `host.docker.internal` instead of `localhost`. |
696
+ | **`app.get('*')` throws in your own server** | You are on Express 5, which dropped bare `*` routes. Use a final `app.use(...)` fallback as in [step 2](#2-the-server--serverjs). The package's own router works with either version. |
697
+ | **Vite dev: "Model load failed"** | Add `optimizeDeps: { exclude: ['tz-voice-chat'] }` ([step 4](#4-vite--viteconfigjs)). In dev, a package linked with a symlink from outside the project root is also blocked by Vite — install a real copy (`npm pack` + install the tarball) to test. |
698
+ | **`ttsProvider: 'server-kokoro'` says it needs `kokoro-js`** | Server-side Kokoro is an optional extra, so installing tz-voice-chat stays light and free of native code: run `npm install kokoro-js`. Its dependency `onnxruntime-node` downloads binaries at install time; on Linux x64 use `ONNXRUNTIME_NODE_INSTALL_CUDA=skip npm install kokoro-js` (CPU inference is unaffected). Or use Kokoro in the browser, OpenAI, ElevenLabs or Web Speech. |
699
+ | **Settings file is lost in Docker** | It lives in the container's home directory. Mount a volume at `~/.tz-voice-chat`, or pass `settingsFile`. |
700
+ | **Port already in use** | `--port` (CLI) or `PORT` (your server). |
701
+
702
+ ## Security notes
703
+
704
+ - Keep the server on loopback (the CLI default) or behind your own authentication: `/settings` can read and replace API keys, `/chat` spends your provider credits, and the OpenAI-compatible provider makes requests to a URL set in Settings.
705
+ - The settings file is written with owner-only permissions (`0600`).
706
+ - Exported settings contain secrets. Treat them like a password file.
707
+
708
+ ## License
709
+
710
+ MIT