@ds-hu/dsh-better-voice-input 0.1.0 → 0.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/docs/CONTRACTS.md CHANGED
@@ -1,4 +1,4 @@
1
- # Module contracts (v0.1)
1
+ # Module contracts (v0.3)
2
2
 
3
3
  Implementation contract between the five packages. Names are exact: the same identifiers are
4
4
  imported across packages and asserted by tests. Plain ESM, JSDoc only.
@@ -30,7 +30,9 @@ One JSON document per data root (`<dataRoot>/config.json`):
30
30
  providers: { 'bvi-cloud-openai': { apiKey: '…', baseURL: '…', model: '…' } },
31
31
  local: { 'bvi-local-sensevoice': { variant: 'small-int8' } },
32
32
  preferences: { releaseAction: 'insert', holdDelayMs: 280, cancelDistancePx: 72,
33
- hintDismissed: false, composerHint: true },
33
+ hintDismissed: false, composerHint: true, streaming: true,
34
+ shortcut: { enabled: false, code: 'Space', ctrl: true, alt: false,
35
+ shift: true, meta: false } },
34
36
  }
35
37
  ```
36
38
 
@@ -39,8 +41,10 @@ One JSON document per data root (`<dataRoot>/config.json`):
39
41
  `ConfigError('missing-data-root')`. The service row resolves the root before calling it
40
42
  (`config.dataRoot`, else `ctx.get('dshHomePath')('better-voice-input')`).
41
43
  - `defaultConfig()` — `{ version: 1, providers: {}, local: {}, preferences: defaultPreferences() }`.
42
- - `defaultPreferences()` — the five keys above; `composerHint` defaults to `true` (the composer
43
- shows the “发消息或按住说话” hint until the user hides it in the settings page).
44
+ - `defaultPreferences()` — the keys above; `composerHint` defaults to `true` (the composer
45
+ shows the “发消息或按住说话” hint until the user hides it in the settings page); `streaming`
46
+ defaults to `true` (streaming-capable providers show live text while recording); `shortcut`
47
+ defaults to disabled with `Ctrl+Shift+Space` as the suggested combination.
44
48
  - `readConfig(dataRoot)` — missing file → default config; unknown keys are dropped; each invalid
45
49
  preference falls back to its default (tolerant read). A structurally corrupt document throws
46
50
  `ConfigError` with code `invalid-json`, `invalid-config`, `unsupported-version` or
@@ -52,8 +56,15 @@ One JSON document per data root (`<dataRoot>/config.json`):
52
56
  returns the next document. A rejected mutation does not break the queue.
53
57
  - `sanitizePreferences(patch, base)` — strict validation for the HTTP path: known keys only,
54
58
  `releaseAction ∈ {'insert','send'}`, `holdDelayMs ∈ [150, 1000]`, `cancelDistancePx ∈ [40, 200]`,
55
- `hintDismissed`/`composerHint` booleans; invalid known values throw
59
+ `hintDismissed`/`composerHint`/`streaming` booleans; invalid known values throw
56
60
  `ConfigError('invalid-preferences')`.
61
+ - `shortcut` is `{ enabled: boolean, code: string, ctrl, alt, shift, meta: boolean }`. `code` is
62
+ a `KeyboardEvent.code` value (`Space`, `KeyV`, `F2`, …) of 1–32 `[A-Za-z0-9]` characters and
63
+ cannot be a bare modifier (`ShiftLeft`, `ControlRight`, …). A shortcut must carry at least one
64
+ of `ctrl`/`alt`/`meta`, or be a function key (`F1`–`F12`), so a plain letter/space can never
65
+ hijack typing. `holdDelayMs` is the hold duration for both pointer and keyboard triggers.
66
+ A partial `shortcut` patch is merged over the current value (for example `{ enabled: true }`
67
+ toggles the stored combination); unknown keys are dropped and an invalid result throws.
57
68
  - `maskSecret(value)` — `''` for an empty value, `'…'` for short ones, otherwise
58
69
  `first3…last4`; never returns the full value.
59
70
 
@@ -110,6 +121,10 @@ object from a **runtime descriptor** (metadata + one of `buildRequest`/`parseRes
110
121
  (the user's saved value wins; an empty string counts as “not set” and falls back to the
111
122
  environment again). Returns `{ settings, missing }` where `missing` lists required keys as
112
123
  `{ key, env? }`. Saved keys without a field descriptor are kept for the adapter.
124
+ - Optional credentials: a field with `required: false` may stay empty; `bearerHeaders('')`
125
+ returns `{}` so an OpenAI-compatible self-hosted gateway receives no `Authorization` header
126
+ (the vendor answers 401 if it actually needs one). All required fields are still enforced by
127
+ `readProviderSettings` before any request is built.
113
128
  - The factory trims the transcript text, falls back to the WAV header for `audioSeconds` and to
114
129
  the elapsed wall time for `inferenceSeconds`, and maps unexpected adapter errors to
115
130
  `ProviderError('parse'|'unsupported')`; `ProviderError`s and caller aborts pass through
@@ -128,13 +143,13 @@ cloud package and is joined with these records there:
128
143
  ```js
129
144
  {
130
145
  id: 'bvi-cloud-openai', vendor: 'openai', location: 'cloud',
131
- name: { zh: 'OpenAI 语音识别', en: 'OpenAI speech recognition' },
146
+ name: { zh: 'OpenAI / OpenAI 兼容服务', en: 'OpenAI / OpenAI-compatible' },
132
147
  languages: ['auto', 'zh', 'en', ...],
133
148
  docs: 'https://platform.openai.com/docs/guides/speech-to-text',
134
149
  env: ['OPENAI_API_KEY'],
135
150
  fields: [
136
- { key: 'apiKey', type: 'secret', required: true, env: 'OPENAI_API_KEY',
137
- label: { zh: 'API Key', en: 'API key' } },
151
+ { key: 'apiKey', type: 'secret', env: 'OPENAI_API_KEY',
152
+ label: { zh: 'API Key(自部署服务可留空)', en: 'API key (blank for self-hosted)' } },
138
153
  { key: 'baseURL', type: 'url', default: 'https://api.openai.com/v1', label: {...} },
139
154
  { key: 'model', type: 'text', default: 'gpt-4o-transcribe', label: {...} },
140
155
  { key: 'mode', type: 'select', default: 'fast', label: {...},
@@ -164,6 +179,7 @@ sherpa-onnx configuration inside its worker:
164
179
  docs: 'https://…',
165
180
  downloadSources: ['https://huggingface.co', 'https://hf-mirror.com'],
166
181
  defaultVariant: 'small-int8',
182
+ streaming: false, // optional; exactly X-ASR sets true (native online recognizer)
167
183
  runtime: { kind: 'offline' | 'online', threads, vad, segmentation },
168
184
  setupEstimate: { recommendedDiskBytes, expectedMemoryBytes, minimumMinutes, maximumMinutes },
169
185
  variants: [{
@@ -190,7 +206,7 @@ input bundle is disabled.
190
206
  `apply(ctx, config)` resolves the data root (`config.dataRoot`, else
191
207
  `ctx.get('dshHomePath')('better-voice-input')`; both go through `resolveDataRoot`), loads the two
192
208
  catalogs tolerantly (`import.meta.resolve` + `existsSync`; a missing component package means an
193
- empty list, a present-but-broken catalog rejects the row), then registers **seven exact Fetch
209
+ empty list, a present-but-broken catalog rejects the row), then registers **eleven exact Fetch
194
210
  routes** with `ctx.connection.fetch.register({ path, methods, requestBody: 'buffered', fetch })`
195
211
  inside `ctx.effect`. The Connection layer owns the Host/Origin fence and browser authentication
196
212
  (the owner Peer), so the handlers contain no hand-written same-origin check.
@@ -204,16 +220,31 @@ inside `ctx.effect`. The Connection layer owns the Host/Origin fence and browser
204
220
  | `POST /api/better-voice-input/cancel-preparation` | `{ providerId }` | `ctx.speechToText.cancelPreparation(id)` |
205
221
  | `POST /api/better-voice-input/transcribe?language=…` | raw `audio/wav` (≤ 8 MiB) | validate canonical WAV, `ctx.speechToText.transcribe`, `{ ok: true, text, audioSeconds, inferenceSeconds }` |
206
222
  | `POST /api/better-voice-input/preferences` | partial preferences | validate with `sanitizePreferences` and persist |
223
+ | `POST /api/better-voice-input/stream/start` | `{ providerId?, language? }` | open a live streaming session for a streaming-capable provider → `{ ok:true, sessionId, sampleRate:16000, providerId }` |
224
+ | `POST /api/better-voice-input/stream/chunk?session=…` | raw `application/octet-stream` PCM16LE mono 16 kHz (≤ 1 MiB) | push one live audio chunk → `{ ok:true, partial, bytes }` |
225
+ | `POST /api/better-voice-input/stream/finish?session=…` | — | close the session and return the final transcript `{ ok:true, text, audioSeconds, inferenceSeconds }` |
226
+ | `POST /api/better-voice-input/stream/cancel?session=…` | — | abort and dispose the session (idempotent) |
207
227
 
208
228
  Body limits: JSON mutations 64 KiB (`MAX_JSON_BODY_BYTES`), transcribe 8 MiB
209
229
  (`MAX_TRANSCRIBE_BODY_BYTES`), audio then capped by `limits.maxAudioBytes` after the WAV header is
210
- checked. `/transcribe` also accepts the JSON compatibility form `{ audioBase64, language?,
211
- providerId? }` for tests and non-browser callers.
230
+ checked; streaming chunks are capped at 1 MiB each and the session total at
231
+ `limits.maxAudioBytes`. A `/stream/chunk` body must be `application/octet-stream`
232
+ (`unsupported-media-type`, 415), non-empty (`stream-chunk-empty`, 400), even-length PCM16
233
+ (`invalid-body`, 400) and within the caps (`body-too-large`, 413). Unknown or idle-expired
234
+ session ids answer `stream-unknown` (404); a fifth concurrent session answers `stream-limit`
235
+ (429); a provider without `bviStreaming` answers `streaming-unavailable` (409); a provider handle
236
+ that misbehaves during start answers `streaming-failed` (502). `/transcribe` also accepts the JSON
237
+ compatibility form `{ audioBase64, language?, providerId? }` for tests and non-browser callers.
238
+
239
+ Streaming sessions live in the service's `api` closure (never in the browser): at most four
240
+ concurrent sessions, 120 s idle TTL with a `.unref()`ed timer, one provider handle each; `finish`,
241
+ `cancel` and expiry dispose the handle, and the row's `ctx.effect` cleanup disposes every live
242
+ session when the plugin unloads. Session ids come from `crypto.randomUUID()`.
212
243
 
213
244
  Success is HTTP 2xx with `{ ok: true, ... }`; failure is a non-2xx with
214
245
  `{ ok: false, code, message }`, where the code is stable (`audio-*`, `provider-*`,
215
- `invalid-*`, `config-error`, `dependency-missing`, `unknown-provider`, `body-too-large`,
216
- `unsupported-media-type`, `cancelled`, `internal`, …).
246
+ `invalid-*`, `stream-*`, `config-error`, `dependency-missing`, `unknown-provider`,
247
+ `body-too-large`, `unsupported-media-type`, `cancelled`, `internal`, …).
217
248
 
218
249
  `GET /state` document (frozen; the settings page and the input component rely on it):
219
250
 
@@ -223,17 +254,22 @@ Success is HTTP 2xx with `{ ok: true, ... }`; failure is a non-2xx with
223
254
  "dependency": { "speechToText": true },
224
255
  "providers": [{ "id": "bvi-cloud-openai", "name": "…", "location": "cloud",
225
256
  "languages": ["auto", "zh"],
226
- "preparation": { "phase": "ready" } }],
257
+ "preparation": { "phase": "ready" },
258
+ "streaming": true }],
227
259
  "selection": { "providerId": "bvi-cloud-openai", "language": "zh" },
228
260
  "config": { "bvi-cloud-openai": { "configured": true,
229
261
  "fields": { "apiKey": "sk-…4f2a", "baseURL": "…" } } },
230
262
  "cloud": [{ "id": "bvi-cloud-openai", "name": { "zh": "…", "en": "…" },
231
- "languages": [], "env": [], "fields": [], "docs": "…", "configured": true }],
263
+ "languages": [], "env": [], "fields": [], "docs": "…", "configured": true,
264
+ "streaming": false }],
232
265
  "local": [{ "id": "bvi-local-sensevoice", "name": { "zh": "…", "en": "…" },
233
266
  "languages": [], "variants": [], "defaultVariant": "…", "variant": "…",
234
- "downloadSources": [], "install": { "phase": "unprepared" } }],
267
+ "downloadSources": [], "streaming": false,
268
+ "install": { "phase": "unprepared" } }],
235
269
  "preferences": { "releaseAction": "insert", "holdDelayMs": 280, "cancelDistancePx": 72,
236
- "hintDismissed": false, "composerHint": true },
270
+ "hintDismissed": false, "composerHint": true, "streaming": true,
271
+ "shortcut": { "enabled": false, "code": "Space", "ctrl": true,
272
+ "alt": false, "shift": true, "meta": false } },
237
273
  "limits": { "maxAudioBytes": 4194304, "maxDurationSeconds": 120 }
238
274
  }
239
275
  ```
@@ -246,8 +282,9 @@ uses the same normalization for the local provider's official preparation state
246
282
  (`{ phase: 'unprepared' }` while the row is not registered). Secrets only ever appear masked.
247
283
 
248
284
  `lib/api.js` is the testable half: `createApi({ store, catalogs, getSpeech, env, logger, limits })`
249
- returns `state`, `saveConfig`, `select`, `prepare`, `cancelPreparation`, `transcribe` and
250
- `savePreferences`; `toErrorPayload(error)` maps `ApiError` / `WavError` / `ProviderError` /
285
+ returns `state`, `saveConfig`, `select`, `prepare`, `cancelPreparation`, `transcribe`,
286
+ `savePreferences`, `startStream`, `pushStream`, `finishStream`, `cancelStream` and `dispose`
287
+ (plus an optional `sessionIdleTimeoutMs` test seam, default 120 s); `toErrorPayload(error)` maps `ApiError` / `WavError` / `ProviderError` /
251
288
  `ConfigError` / aborts to the HTTP status and envelope above. `lib/store.js` wraps the data root
252
289
  in `read()`/`update()`.
253
290
 
@@ -266,11 +303,12 @@ ctx.slots.inject('plugins.bundle.config', () =>
266
303
 
267
304
  The owner passes `{ view: 'summary' | 'page' }` and no `form`, so the page draws its own form and
268
305
  persists through the HTTP API above (`GET /state` once on open, then polls every 1.5 s while a
269
- local model is preparing). Sections: dependency status, default provider/language, cloud vendor
270
- cards (write-only + masked secrets, env fallback hint, docs link), local model cards (variant,
271
- download/cancel/progress, estimate), composer preferences (`releaseAction`, `holdDelayMs`,
272
- `cancelDistancePx`, `composerHint`, first-run hint reset) and a notes card. The summary view shows
273
- the configured cloud/local counts.
306
+ local model is preparing). Sections: dependency status, default provider/language, the
307
+ **master-detail** cloud and local lists (only the selected entry renders its card: write-only +
308
+ masked secrets, env fallback hint, docs link; variant, download/cancel/progress, estimate),
309
+ composer preferences (`releaseAction`, `holdDelayMs`, `cancelDistancePx`, `composerHint`,
310
+ `streaming`, first-run hint reset), the keyboard-shortcut recorder and a notes card. The summary
311
+ view shows the configured cloud/local counts.
274
312
 
275
313
  ## `@ds-hu/dsh-bvi-input` (client)
276
314
 
@@ -280,6 +318,163 @@ the configured cloud/local counts.
280
318
  `POST /api/better-voice-input/transcribe?language=…`). Gesture, overlay and audio rules:
281
319
  `docs/ARCHITECTURE.md` §4.
282
320
 
321
+ ## Streaming extension (v0.3, our providers only)
322
+
323
+ The official speech seam has no streaming API, so live transcripts use a **service-owned relay**
324
+ plus an optional extension object on our own registered providers. Nothing official is modified.
325
+
326
+ ### `provider.bviStreaming` (cloud/local packages → service)
327
+
328
+ ```js
329
+ provider.bviStreaming = {
330
+ /**
331
+ * @param {{ language?: string }} options - selected language, already validated by the caller.
332
+ * @returns {Promise<{
333
+ * push(pcm: Uint8Array): Promise<{ partial: string }>, // PCM16LE, mono, 16 kHz
334
+ * finish(): Promise<{ text: string, audioSeconds: number, inferenceSeconds: number }>,
335
+ * cancel(): Promise<void>,
336
+ * }>}
337
+ */
338
+ async start(options) { … },
339
+ }
340
+ ```
341
+
342
+ - Records omit `streaming` (or keep `false`) unless the family has a native incremental
343
+ recognizer; absence means `false`. Only a provider whose catalog record declares
344
+ `streaming: true` may implement the extension; the service marks those entries in `/state`
345
+ (`providers[].streaming`) and refuses `/stream/start` for any other provider
346
+ (`streaming-unavailable`, HTTP 409).
347
+ - v0.3 declares `streaming: true` for seven families: local X-ASR (sherpa `OnlineRecognizer`
348
+ in the worker, §"Worker private protocol") and six cloud vendors with real websocket
349
+ transports (ElevenLabs, Soniox, DashScope, OpenAI Realtime, Volcengine, Tencent, table
350
+ below). The other eight cloud vendors and six local families stay batch-only.
351
+ - The service obtains the provider object with `ctx.speechToText.resolve({ audio: new
352
+ Uint8Array(0), language, providerId })` and checks `provider.bviStreaming` at request time.
353
+ The pinned provider lifetime is the session lifetime; `/stream/finish|cancel` release it.
354
+ - `partial` is the **cumulative** transcript so far (the browser replaces the live line). Empty
355
+ strings are valid. `finish()` settles exactly once; `cancel()` is idempotent and must release
356
+ the worker stream.
357
+ - `bviStreaming` is the only non-official property we add to a provider object; official
358
+ consumers ignore it.
359
+
360
+ #### Cloud realtime implementation (`packages/cloud/lib/streaming/`)
361
+
362
+ The cloud row attaches `provider.bviStreaming = createCloudStreaming(descriptor, { readConfig,
363
+ env })` only when the joined descriptor has `streaming: true`; `packages/cloud/lib/catalog.js`
364
+ gives that descriptor a `streamingAdapter` (the vendor protocol module) and refuses to start if a
365
+ streaming record lacks one. The lifecycle lives in
366
+ `session.js`, the only `ws` import lives in `socket.js`, and each vendor file is a pure frame
367
+ codec:
368
+
369
+ ```js
370
+ // packages/cloud/lib/streaming/<vendor>.js
371
+ export function createStreamSession({ settings, language, sampleRate, emit }) {
372
+ return {
373
+ url() …, // -> ws(s) URL; may read settings/credentials
374
+ headers() …, // -> header-based auth only
375
+ open() { emit.send(JSON.stringify(initialFrame)) },
376
+ push(pcm) { emit.send(pcm) }, // PCM16LE mono 16 kHz, raw or base64 per vendor
377
+ finish() { emit.send(commitFrame) },
378
+ message(data) { … emit.partial(text) / emit.final(text) / emit.fail(error) },
379
+ close?() { … assemble a final from buffered state on server close },
380
+ }
381
+ }
382
+ ```
383
+
384
+ - `emit.send(data: string | Uint8Array)` is installed before the protocol is constructed (lazy
385
+ socket closure); it throws `ProviderError('network')` before the upgrade or after teardown.
386
+ - The shared session resolves credentials with `resolveProviderSettings` (same
387
+ `missing-credential` error as batch, before any socket), validates the language against the
388
+ catalog list, applies a 10 s HTTP-upgrade timeout, keeps a single terminal state and enforces
389
+ a 15 s finish deadline; a timed-out/closed/failed live take rejects, and the input component
390
+ falls back to `/transcribe` with the same recording, so live mode never loses a take.
391
+ - Vendor failures map onto the existing `ProviderError` codes (`http` with `status`, `timeout`,
392
+ `network`, `parse`, `unsupported`) so `/stream/*` and `/transcribe` report the same shapes.
393
+
394
+ | vendor | realtime endpoint | auth | realtime model field (default) | client frames | final signal |
395
+ | --- | --- | --- | --- | --- | --- |
396
+ | `elevenlabs` | `wss://…/v1/speech-to-text/realtime` | `xi-api-key` | `streamModel` (`scribe_v3_live`) | JSON `input_audio_chunk` with base64 PCM; commit chunk on finish | `committed_transcript` |
397
+ | `soniox` | `wss://…/transcribe-websocket` | `Authorization: Bearer` | `streamModel` (`stt-rt-v6`) | config JSON, then binary PCM; `{type:'finalize'}` + empty frame on finish | token stream `finished: true` |
398
+ | `dashscope` | `wss://…/api-ws/v1/realtime` | Bearer + `OpenAI-Beta: realtime=v1` | `streamModel` (`qwen3-asr-flash-realtime`) | `session.update`, base64 appends, `session.finish` | `.text` previews; final on `session.finished` (accumulated `.completed`) |
399
+ | `openai` | `wss://…/v1/realtime?intent=transcription` | Bearer (blank key = none) | `streamModel` (`gpt-4o-mini-transcribe`) | `session.update`, base64 appends, `input_audio_buffer.commit` | transcription `.completed` |
400
+ | `volc` | `wss://…/api/v3/sauc/bigmodel_async` | `X-Api-Key` or `X-Api-App-Key`+`X-Api-Access-Key` | `streamResourceId` (`volc.seedasr.sauc.duration`) | gzip binary protocol: full client request, audio frames, last frame | server frame with `flags & 3 === 3`, `result.text` |
401
+ | `tencent` | `wss://…/asr/v2/{appid}?{signed query}` | HMAC-SHA1 signed URL | `engineType` (`16k_zh`) | binary PCM, then `{"type":"end"}` | `final: 1` / `result.slice_type` |
402
+
403
+ ### Worker private protocol (`packages/local`, X-ASR only)
404
+
405
+ `sherpa-onnx-node`'s `OnlineRecognizer` provides incremental results. The worker child exposes
406
+ four authenticated loopback routes (bearer token, `127.0.0.1`, ephemeral port — same transport as
407
+ `/transcribe`):
408
+
409
+ | Method + path | Body | Answer |
410
+ | --- | --- | --- |
411
+ | `POST /stream/start?language=…` | — | `{ streamId }` (one live stream per worker) |
412
+ | `POST /stream/chunk?stream=…` | raw PCM16LE mono 16 kHz | `{ partial, bytes }` |
413
+ | `POST /stream/finish?stream=…` | — | `{ text, audioSeconds }` |
414
+ | `POST /stream/cancel?stream=…` | — | `{ ok: true }` |
415
+
416
+ The final decode uses the same drain protocol as the batch path (drain → two 480 ms silence
417
+ chunks → `inputFinished()` → drain) and the same `adapter.sanitize` text policy. Model
418
+ configuration literals are **unchanged** — streaming reuses the existing X-ASR
419
+ `OnlineRecognizer` config. The parent runtime exposes `startStream/pushStream/finishStream/
420
+ cancelStream` and measures `inferenceSeconds` on the parent side.
421
+
422
+ ### Browser contract (`packages/input`)
423
+
424
+ - Trigger rules: the pointer hold only starts when the composer editor is **not** focused on a
425
+ touch device and the virtual keyboard is closed (see ARCHITECTURE §4.2). The optional keyboard
426
+ shortcut follows the `preferences.shortcut` object.
427
+ - Streaming path is selected per recording: `preferences.streaming === true` **and**
428
+ `state.providers[selected].streaming === true` **and** `AudioWorklet` (or `ScriptProcessor`)
429
+ capture is available. Otherwise the existing whole-WAV `MediaRecorder` path runs unchanged.
430
+ - Audio: Float32 frames → 16 kHz PCM16LE; a `POST /stream/chunk` runs every ~200 ms (no
431
+ overlapping requests); overlay shows `partial` live above the waveform.
432
+ - Release: `POST /stream/finish` → final text → flight animation → `insertText`/`setDraft` as in
433
+ the batch path (`send` action and the conflict fallbacks are shared). Slide-up cancel and
434
+ Escape call `POST /stream/cancel` and insert nothing. If open/chunk fails mid-recording the
435
+ relay is abandoned and the take is transcribed as one WAV from the buffered PCM at release
436
+ (the overlay tells the user), so a relay fault never loses the recording.
437
+ - Keyboard shortcut: a configured `code`+modifier combination starts the same hold flow; keyup
438
+ releases, Escape cancels. It only fires while the composer exists and focus is not inside a
439
+ different input/textarea (so settings forms keep typing normally).
440
+ - The flight animation is DOM-only: a `.bvi-flight` clone of the final line is pinned over the
441
+ overlay, transformed to the composer input's `getBoundingClientRect()` (~360 ms
442
+ `cubic-bezier(.2,.8,.2,1)`, opacity/scale), then the real insertion happens. `prefers-reduced-
443
+ motion` skips the animation.
444
+
445
+ ### Settings page layout (v0.3)
446
+
447
+ The page is **container-width responsive, mobile-first**: one column, `container-type: inline-size`
448
+ on the root, and a single `@container (min-width: 560px)` refinement — never `@media` for the form
449
+ layout, because the host Plugins panel can be narrow inside a wide desktop viewport. Three
450
+ segmented tabs (服务 / 模型 / 交互) sit under a slim dependency status row; all three panels stay
451
+ mounted and are hidden with the `hidden` attribute so state survives tab switches and assistive
452
+ technology sees stable ids (`role="tablist"`, `aria-selected`, `aria-controls`, ArrowLeft/Right).
453
+
454
+ Cloud and local lists are **master-detail accordion rows** inside one inset hairline group: a
455
+ full-width row (name, secondary meta, streaming/configured chips, rotating chevron) and only the
456
+ selected entry expands its form in place (fields, env hint, docs, save; variant, estimate,
457
+ download/cancel/progress). Selecting a row is local component state; the first selection defaults
458
+ to the current `selection.providerId` (cloud) and the first installed local model (local); an empty
459
+ catalog shows a hint instead of a row. Touch targets are ≥ 40 px, inputs use 16 px text on mobile
460
+ to prevent iOS zoom, secret fields get an inline clear action, and the shortcut recorder renders as
461
+ a single `<kbd>` label. Motion is limited to short transitions and disabled by
462
+ `prefers-reduced-motion`. The summary view stays a flat two-line overview. No API change is needed
463
+ for this layout.
464
+
465
+ ### OpenAI-compatible endpoints and optional credentials
466
+
467
+ `bvi-cloud-openai` is the OpenAI **and** OpenAI-compatible entry: `baseURL` and `model` are
468
+ editable and `apiKey` is optional, so a self-hosted gateway (for example an X-ASR model exposed
469
+ through an OpenAI-compatible `/v1/audio/transcriptions` server) works with an empty key. The
470
+ adapter omits the `Authorization` header when the key is empty. In `/state`, `configured` means
471
+ "every required field is filled" for vendors with required fields; a vendor with no required
472
+ field (OpenAI-compatible) is configured once any effective value exists, so a key-less
473
+ self-hosted setup is not reported as unconfigured. CI proves this end-to-end with
474
+ the `openai-compat-smoke` workflow: it downloads the pinned X-ASR model, serves it through a
475
+ local OpenAI-compatible endpoint, runs the real cloud adapter with `apiKey: ''`, and asserts the
476
+ transcript (and that no authorization header was sent).
477
+
283
478
  ## Testing seams
284
479
 
285
480
  Every module is testable without native dependencies and without a host process:
@@ -293,6 +488,11 @@ Every module is testable without native dependencies and without a host process:
293
488
  - service host: `apply(ctx, { dataRoot })` with a fake Cordis context whose
294
489
  `connection.fetch.register` records the routes; the tests drive the handlers with Fetch
295
490
  `Request`/`Response` objects (`test/service-host.test.mjs`).
491
+ - cloud realtime codecs: pure protocol modules instantiated with a captured `emit`
492
+ (`test/support/cloud-stream-harness.mjs`), fake server frames, and no socket; the shared
493
+ session lifecycle is driven with a fake transport that records `openSocket` options and lets a
494
+ test push server frames; the `ws` seam itself is exercised against loopback servers
495
+ (`test/cloud-stream-socket.test.mjs`), so no vendor account or external network is involved.
296
496
  - browser entries: `test/client-harness.mjs` evaluates the classic script in a `vm` context,
297
497
  captures `window.__ModuleLoader__.load({ id, factory })`, calls `factory(require)` with a
298
498
  minimal React hook runtime, a fake document, fake timers and a fetch stub, and exposes the
package/docs/DETAIL.md CHANGED
@@ -15,7 +15,9 @@ The official bundle ships one host-local model. This bundle registers **21 servi
15
15
  - **14 cloud providers** — SiliconFlow, Volcengine, ElevenLabs, OpenAI, OpenRouter, DashScope,
16
16
  DeepSeek, Gemini, Xiaomi MiMo, Tencent Cloud, Soniox, StepAudio, Zhipu and Cohere. Each has its
17
17
  own form for API key, base URL, model and vendor options; environment variables work as a
18
- read-only fallback.
18
+ read-only fallback. The OpenAI entry doubles as an **OpenAI-compatible** endpoint (any base URL
19
+ and model name, and an empty API key), so a self-hosted model exposed through
20
+ `/v1/audio/transcriptions` can be selected directly.
19
21
  - **7 local model families** — SenseVoice, FunASR Nano, Qwen3-ASR, Parakeet, GigaAM, FireRedASR
20
22
  and X-ASR, each with selectable variants. They run on this machine through `sherpa-onnx-node`,
21
23
  downloaded on first use into `$DSH_HOME/better-voice-input/models` and verified file by file
@@ -34,19 +36,38 @@ The official voice UI is click-to-record. This bundle reproduces the DeepSeek Ap
34
36
  - **Slide up to cancel.** The overlay turns from blue to red once you pass the cancel distance;
35
37
  release there to discard the recording. Release anywhere else to transcribe. A small dead band
36
38
  prevents accidental cancel/send toggling.
39
+ - **Live streaming text.** With a streaming model (local X-ASR) the cumulative transcript appears
40
+ above the overlay while you speak, then a smooth fly-to-composer animation moves the final line
41
+ into the input. The live display can be turned off in settings; providers without streaming keep
42
+ the batch behavior. Requires `AudioWorklet`; the plugin quietly falls back to whole-recording
43
+ recognition otherwise.
37
44
  - **Release behavior is yours.** By default the transcript is inserted into the draft at the
38
45
  caret; a setting switches release to *send*.
39
46
  - **The composer hint reads “发消息或按住说话”** when the draft is empty, and the overlay wording
40
47
  follows the release behavior (“松手插入,上滑取消” / “松手发送,上滑取消”).
48
+ - **Keyboard shortcut.** Record a hold-to-talk combination (for example `Ctrl+Shift+Space`) in the
49
+ settings and hold it from the conversation; releasing inserts, `Escape` cancels. It never fires
50
+ while the focus is in another form, so settings inputs keep typing normally.
51
+ - **No keyboard fight on phones.** On touch devices the hold does not start while the caret is in
52
+ the input box and the virtual keyboard is open — previously that pushed the keyboard away and
53
+ shifted the overlay. Dismiss the keyboard and hold to dictate.
41
54
  - Escape, a hidden tab or a lost focus cancels the recording — the microphone never stays open in
42
55
  the background.
43
56
 
57
+ The settings page is split into three tabs — Services, Models and Interaction — with the
58
+ dependency status and tab bar always within reach. Cloud services and local models stay
59
+ master-detail: pick an entry first, and only that entry's form expands in place, so a phone never
60
+ flattens every field into one long scroll. The interaction section decides release behavior, hold
61
+ delay, cancel distance, the composer hint and live text; the shortcut section records the keyboard
62
+ combination.
63
+
44
64
  Component: **更好的语音输入**.
45
65
 
46
66
  ## Requirements
47
67
 
48
- DeepSeek Harness **>= 0.2.2-rc.5 < 0.3.0** and Node.js **>= 20.19**. The official **Voice input**
49
- bundle must stay enabled — it provides the speech-to-text registry this bundle extends; its own
68
+ DeepSeek Harness **>= 0.2.2-rc.5 < 0.3.0** and Node.js **>= 20.19**. Live streaming needs
69
+ `AudioWorklet` (falls back to batch recognition otherwise); a plain `getUserMedia` browser is
70
+ enough for hold-to-talk. The official **Voice input** bundle must stay enabled — it provides the speech-to-text registry this bundle extends; its own
50
71
  mic UI may be disabled. Cloud providers need the vendor's API key; local models need disk space
51
72
  and a CPU (no GPU required).
52
73
 
package/docs/DETAIL.zh.md CHANGED
@@ -14,7 +14,9 @@
14
14
 
15
15
  - **14 家云端服务** —— 硅基流动、火山引擎、ElevenLabs、OpenAI、OpenRouter、阿里云百炼、
16
16
  DeepSeek、Gemini、小米 MiMo、腾讯云、Soniox、阶跃星辰、智谱、Cohere。每家都有独立表单
17
- (API Key、base URL、model、供应商选项),环境变量可作为只读兜底。
17
+ (API Key、base URL、model、供应商选项),环境变量可作为只读兜底。OpenAI 一项同时是
18
+ **OpenAI 兼容**入口:base URL、模型名都可改,API Key 允许留空,因此把本地模型以
19
+ `/v1/audio/transcriptions` 暴露出来的自部署服务可以直接接入。
18
20
  - **7 个本地模型系列** —— SenseVoice、FunASR Nano、Qwen3-ASR、Parakeet、GigaAM、FireRedASR、
19
21
  X-ASR,每个系列可选不同变体。它们通过 `sherpa-onnx-node` 在本机运行,首次使用时下载到
20
22
  `$DSH_HOME/better-voice-input/models`,逐文件校验固定的 SHA-256;推理在子进程中运行,
@@ -30,11 +32,23 @@
30
32
  - **按住输入框说话**(鼠标、触屏、手写笔共用同一套长按判定)。短暂按住后出现全屏浮层与实时波形。
31
33
  - **上滑取消**:上滑超过取消距离后浮层由蓝变红,此时松手放弃录音;在其他位置松手则开始转写。
32
34
  一段回滞区间避免松手瞬间在「取消/发送」之间抖动。
35
+ - **流式实时文字**:选中支持流式的模型(本地 X-ASR)时,录音过程中累计转写会实时出现在浮层
36
+ 上方;松手后最终文字从屏幕中间平滑飞入输入框。实时显示可在设置里关闭;不支持流式的服务仍
37
+ 走整段识别。需要浏览器支持 `AudioWorklet`,否则自动退回整段识别,功能不受影响。
33
38
  - **松手行为可配置**:默认把识别结果插入草稿光标处;在设置里可改为松手直接发送。
34
39
  - **草稿为空时组合框提示为「发消息或按住说话」**,浮层文案跟随松手行为(
35
40
  「松手插入,上滑取消」/「松手发送,上滑取消」)。
41
+ - **快捷键长按**:在设置里录制一个组合键(例如 `Ctrl+Shift+Space`),在对话里长按它即可开始
42
+ 语音输入;松手插入,`Esc` 取消。焦点在其他表单里时不会触发,设置页输入不受影响。
43
+ - **不与输入法打架**:触屏设备上,光标在输入框且虚拟键盘弹出时,长按输入框不会启动录音
44
+ (此前会把键盘推下去、浮层错位);收起键盘后按住即可说话。
36
45
  - Esc、切到后台标签页、窗口失焦都会取消录音——麦克风不会在后台保持开启。
37
46
 
47
+ 设置页按「服务 / 模型 / 交互」分成三个分区,依赖状态与分区切换始终在顶部可及;云端服务与本地
48
+ 模型采用「先选模型、再看设置」的 master-detail 折叠列表:先点一个服务或模型,只展开它自己的
49
+ 表单,手机上不需要在几十个输入框之间长距离滚动。交互区决定松手行为、长按时长、取消距离、输入框
50
+ 提示与实时文字;快捷键区负责录制组合键。
51
+
38
52
  组件:**更好的语音输入**。
39
53
 
40
54
  ## 环境要求
@@ -12,11 +12,48 @@ Node 22, then verifies the exact file list each package would publish
12
12
  publishing.
13
13
 
14
14
  - Latest green run on `main`: see the [CI runs](https://github.com/ds-hu/dsh-better-voice-input/actions/workflows/ci.yml).
15
+ - v0.3.0 pre-merge run on the feature branch:
16
+ [47636376413](https://github.com/ds-hu/dsh-better-voice-input/actions/runs/47636376413) —
17
+ 406 tests on Node 20 and 22 (eslint clean, every package tarball verified at 0.3.0).
15
18
  - Test suites: core config store / WAV / HTTP / cloud provider factory, 14 cloud wire-format
16
- adapters against recorded responses, service API and host routes against a fake speech registry,
17
- local catalog / downloads / zip extraction / provider preparation / worker protocol, both
18
- browser entries in a `vm` React harness, plus a cross-component test that holds the
19
- 21-provider, release-order and documentation contracts together.
19
+ adapters against recorded responses, six cloud realtime frame codecs plus the shared session
20
+ lifecycle (fake transport) and the `ws` seam against loopback servers, service API, streaming
21
+ session relay and host routes against a fake speech registry, local catalog / downloads / zip
22
+ extraction / provider preparation / worker protocol (including the X-ASR `/stream/*` relay),
23
+ both browser entries in a `vm` React harness (gesture state machine, virtual-keyboard guard,
24
+ keyboard shortcut, live streaming client, fly-to-composer animation degradation, tabbed
25
+ mobile settings page), plus a cross-component test that holds the 21-provider, seven-streaming-
26
+ family, release-order and documentation contracts together.
27
+
28
+ ## Cloud realtime streaming (v0.3)
29
+
30
+ No vendor account is part of this repository, so CI cannot open a real vendor websocket. The
31
+ realtime channels are verified in two layers instead:
32
+
33
+ 1. **Protocol codecs** (`test/cloud-stream-elevenlabs|soniox|dashscope|openai|volc|tencent.test.mjs`)
34
+ instantiate each vendor module with a captured `emit`, assert the exact URL/auth/query strings,
35
+ handshake frame bytes (including Volcengine's gzip binary framing), audio encodings
36
+ (base64/binary/resampled 24 kHz), server-frame parsing (partials, finals, error mapping) and the
37
+ exact commit/finalize frames.
38
+ 2. **Lifecycle and transport** (`test/cloud-streaming.test.mjs`, `test/cloud-stream-socket.test.mjs`)
39
+ drive the shared session with a fake transport (credentials, language checks, handshake failure,
40
+ early close, cancel, finish deadline, late sends) and the `ws` seam against loopback servers
41
+ (text/binary frames, 401 upgrade, handshake timeout, one close callback).
42
+
43
+ A live manual check per vendor is still the acceptance test. With a real key configured in
44
+ **Plugins → 更好的语音输入 → 设置 → 服务**, hold the composer and confirm:
45
+
46
+ | Vendor | What to check |
47
+ | --- | --- |
48
+ | ElevenLabs | live draft appears while speaking; release inserts the committed transcript; wrong key shows an error and the take is still retranscribed via batch |
49
+ | Soniox | live draft + final agree; a custom `baseURL` proxy reaches `<proxy>/transcribe-websocket` |
50
+ | DashScope | `qwen3-asr-flash-realtime` streaming model; preview keeps earlier utterances across pauses |
51
+ | OpenAI Realtime | official host uses 24 kHz internally (no config needed); a keyless compatible gateway also streams or falls back cleanly |
52
+ | Volcengine | `streamResourceId` resource id accepted; binary frames produce incremental text |
53
+ | Tencent | `engineType` (`16k_zh`) accepted; signed URL connects; `final:1` text inserted on release |
54
+
55
+ Falling back is not an error: if a live session fails at any step (handshake, vendor error,
56
+ 15 s finish deadline), the input component transcribes the same recording through the batch path.
20
57
 
21
58
  ## Local models — real download and inference
22
59
 
@@ -39,20 +76,61 @@ passed** before `v0.1.0`:
39
76
  | firered-asr / ctc-int8 | [47617247666](https://github.com/ds-hu/dsh-better-voice-input/actions/runs/47617247666) | 开放时间早上九点至下午五点 | 2.37 s |
40
77
  | x-asr / x-asr-480ms (streaming) | [47617254289](https://github.com/ds-hu/dsh-better-voice-input/actions/runs/47617254289) | 开放时间早上九点至下午五点 | 1.17 s |
41
78
 
79
+ The X-ASR row above exercised the batch path only. For v0.2 the same workflow also pushes the
80
+ recording through `provider.bviStreaming` in 200 ms chunks (after a cancelled session) and checks
81
+ both the cumulative partial text and the final transcript:
82
+
83
+ | Check | Workflow run | Result |
84
+ | --- | --- | --- |
85
+ | X-ASR batch + live streaming | [47626928831](https://github.com/ds-hu/dsh-better-voice-input/actions/runs/47626928831) | batch “开放时间早上九点至下午五点” (0.75 s inference); streaming produced 8 partial updates and the same final text |
86
+
42
87
  Sample: the 5.59 s Chinese test clip shipped upstream with the SenseVoice model; a fresh cache
43
88
  download was verified file by file against the pinned SHA-256 digests on each run (including the
44
89
  zip-archive sources for `mlt-int8` and `qwen3-1.7b-int8`). The sensevoice run that first exercised
45
90
  the download path also caught a real provisioning bug — a missing `Content-Length` header was
46
91
  treated as zero — which is fixed and covered by a unit test.
47
92
 
93
+ ## OpenAI-compatible endpoint (v0.2)
94
+
95
+ `.github/workflows/openai-compat-smoke.yml` is a manual workflow that proves the
96
+ OpenAI-compatible / self-hosted path end to end, with no vendor account: it prepares the real
97
+ X-ASR model, serves it through a loopback `POST /v1/audio/transcriptions` endpoint, writes a
98
+ temporary config with an **empty API key** and that loopback base URL, then transcribes the sample
99
+ through the real `bvi-cloud-openai` adapter.
100
+
101
+ | Check | Workflow run | Result |
102
+ | --- | --- | --- |
103
+ | OpenAI-compatible, keyless | [47626933281](https://github.com/ds-hu/dsh-better-voice-input/actions/runs/47626933281) | cloud transcript equals the local model output (“开放时间早上九点至下午五点”); server logged `authorization=none`; exactly one request, WAV bytes forwarded unchanged |
104
+
105
+ ## Release v0.2.0
106
+
107
+ The tag `v0.2.0` ran `.github/workflows/release.yml` on the exact tagged tree:
108
+ quality gate (Node 22) → publish-file verification → publish all six packages with
109
+ `--provenance` → poll the registry until every package resolves → create the GitHub release.
110
+
111
+ | Check | Run | Result |
112
+ | --- | --- | --- |
113
+ | Release pipeline | [47627124896](https://github.com/ds-hu/dsh-better-voice-input/actions/runs/47627124896) | success: `@ds-hu/dsh-bvi-{core,service,cloud,local,input}` and `@ds-hu/dsh-better-voice-input` all published and visible at `0.2.0` with SLSA provenance |
114
+
115
+ The GitHub release is
116
+ [v0.2.0](https://github.com/ds-hu/dsh-better-voice-input/releases/tag/v0.2.0).
117
+
48
118
  ## What is not verified end-to-end
49
119
 
50
120
  - **Cloud vendors** are implemented against their public HTTP APIs but were not called with real
51
- credentials (no vendor account is part of this repository). Wire formats and response parsing are
52
- unit-tested against documented response shapes; a live call is the first thing to try when a
53
- vendor changes its API.
121
+ credentials (no vendor account is part of this repository). The six **cloud realtime
122
+ websocket** channels (ElevenLabs, Soniox, DashScope, OpenAI Realtime, Volcengine, Tencent) are
123
+ likewise unit-tested at the frame level against the reference app and vendor docs, and their
124
+ handshake/teardown/timeout behaviour is exercised with fake transports and loopback sockets —
125
+ but no real vendor handshake, key, or final-transcript timing is part of CI. A live call per
126
+ vendor is the first thing to try when a vendor changes its realtime API; the input component
127
+ automatically falls back to batch transcription when a live take fails.
54
128
  - **The Web GUI integration** (slot rendering, the overlay's real-browser visuals, and the
55
129
  settings page styling) is exercised through a `vm` React harness and the official slot contract,
56
130
  not in a browser session, because this repository does not run browsers in CI.
57
- - **Real audio capture** (microphone → WAV → service) is covered by unit tests of the gesture,
58
- encoder and HTTP layers; it needs a user's browser and microphone to be observed.
131
+ - **Real audio capture** (microphone → WAV/PCM → service) is covered by unit tests of the
132
+ gesture, encoder, streaming client and HTTP layers; it needs a user's browser and microphone to
133
+ be observed. The real X-ASR worker streaming path is verified in CI (above), but the full
134
+ AudioWorklet → service relay → overlay → fly-to-composer chain still needs a GUI session.
135
+ - **Mobile virtual-keyboard behavior** (the v0.2 guard) is unit-tested against `visualViewport`
136
+ states; real iOS/Android keyboard geometry is observed by the user, not by CI.
@@ -44,6 +44,9 @@
44
44
  <rect x="460" y="80" width="360" height="640" rx="26" fill="url(#blueglow)"/>
45
45
  <rect x="460" y="80" width="360" height="640" rx="26" fill="url(#vig)"/>
46
46
  <text x="640" y="322" fill="#cfe6ff" font-size="25" text-anchor="middle" font-family="Source Serif Pro, Georgia, serif" letter-spacing="3">Release to insert · slide up to cancel</text>
47
+ <text x="640" y="356" fill="#9fc8ff" font-size="12" letter-spacing="2" text-anchor="middle" font-family="-apple-system, Segoe UI, sans-serif">LIVE TRANSCRIPT</text>
48
+ <text x="640" y="392" fill="#eef5ff" font-size="20" text-anchor="middle" font-family="Songti SC, Noto Serif SC, serif">Let's move today's meeting to 3 p.m.</text>
49
+ <text x="640" y="422" fill="#eef5ff" font-size="20" text-anchor="middle" font-family="Songti SC, Noto Serif SC, serif" opacity=".9">Bring the design doc with you.</text>
47
50
  <rect x="491.0" y="466.0" width="4" height="8.0" rx="2" fill="#dde8ff" opacity="0.55" style="filter:drop-shadow(0 0 6px #9fc8ff)"/>
48
51
  <rect x="505.0" y="463.8" width="4" height="12.3" rx="2" fill="#dde8ff" opacity="0.69" style="filter:drop-shadow(0 0 6px #9fc8ff)"/>
49
52
  <rect x="519.0" y="461.5" width="4" height="16.9" rx="2" fill="#dde8ff" opacity="0.77" style="filter:drop-shadow(0 0 6px #9fc8ff)"/>
@@ -93,5 +96,5 @@
93
96
  <rect x="1177.0" y="462.1" width="4" height="15.7" rx="2" fill="#e06770" opacity="0.77" style="filter:drop-shadow(0 0 6px #ff5f69)"/>
94
97
  <rect x="1191.0" y="462.5" width="4" height="14.9" rx="2" fill="#e06770" opacity="0.69" style="filter:drop-shadow(0 0 6px #ff5f69)"/>
95
98
  <rect x="1205.0" y="466.0" width="4" height="8.0" rx="2" fill="#e06770" opacity="0.55" style="filter:drop-shadow(0 0 6px #ff5f69)"/>
96
- <text x="640" y="770" fill="#6f7688" font-size="14" font-family="-apple-system, Segoe UI, sans-serif" text-anchor="middle">Hold the composer to talk: the overlay mirrors the DeepSeek App. Insert-draft is the default release action; send is one setting away.</text>
99
+ <text x="640" y="770" fill="#6f7688" font-size="14" font-family="-apple-system, Segoe UI, sans-serif" text-anchor="middle">Hold the composer: the transcript streams in live and flies into the input on release. Insert draft by default; send is a setting.</text>
97
100
  </svg>