@ds-hu/dsh-better-voice-input 0.0.0-stage → 0.2.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.
@@ -0,0 +1,437 @@
1
+ # Module contracts (v0.2)
2
+
3
+ Implementation contract between the five packages. Names are exact: the same identifiers are
4
+ imported across packages and asserted by tests. Plain ESM, JSDoc only.
5
+
6
+ ## `@ds-hu/dsh-bvi-core` (library, host)
7
+
8
+ ```js
9
+ // lib/index.js re-exports the modules below.
10
+ export { CONFIG_VERSION, ConfigError, defaultConfig, resolveDataRoot, readConfig, writeConfig,
11
+ updateConfig, defaultPreferences, sanitizePreferences, maskSecret } from './config-store.js'
12
+ export { WavError, parseWav, validateWav, wavToFloat32, wavToPcm16, encodeWav, resampleLinear,
13
+ MAX_WAV_BYTES } from './wav.js'
14
+ export { PROVIDER_ERROR_CODES, ProviderError, fetchJson, postJson, postMultipart,
15
+ timeoutSignal } from './http.js'
16
+ export { createCloudProvider, readProviderSettings } from './cloud-provider.js'
17
+ export { CLOUD_CATALOG } from './catalog/cloud.js'
18
+ export { LOCAL_MODELS, SHARED_ASSETS } from './catalog/local.js'
19
+ ```
20
+
21
+ `core` is a library, never a Loader row: it declares neither `dsh.bundle` nor `dsh.client`.
22
+
23
+ ### config-store.js
24
+
25
+ One JSON document per data root (`<dataRoot>/config.json`):
26
+
27
+ ```js
28
+ {
29
+ version: 1,
30
+ providers: { 'bvi-cloud-openai': { apiKey: '…', baseURL: '…', model: '…' } },
31
+ local: { 'bvi-local-sensevoice': { variant: 'small-int8' } },
32
+ preferences: { releaseAction: 'insert', holdDelayMs: 280, cancelDistancePx: 72,
33
+ hintDismissed: false, composerHint: true, streaming: true,
34
+ shortcut: { enabled: false, code: 'Space', ctrl: true, alt: false,
35
+ shift: true, meta: false } },
36
+ }
37
+ ```
38
+
39
+ - `resolveDataRoot(input)` — accepts an explicit absolute/relative path or `{ dataRoot }` and
40
+ returns it resolved. The library **never guesses a home directory**: a missing root throws
41
+ `ConfigError('missing-data-root')`. The service row resolves the root before calling it
42
+ (`config.dataRoot`, else `ctx.get('dshHomePath')('better-voice-input')`).
43
+ - `defaultConfig()` — `{ version: 1, providers: {}, local: {}, preferences: defaultPreferences() }`.
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.
48
+ - `readConfig(dataRoot)` — missing file → default config; unknown keys are dropped; each invalid
49
+ preference falls back to its default (tolerant read). A structurally corrupt document throws
50
+ `ConfigError` with code `invalid-json`, `invalid-config`, `unsupported-version` or
51
+ `read-failed` — it is never silently rewritten.
52
+ - `writeConfig(dataRoot, config)` — validates, writes atomically (`<pid>.<rand>.tmp` + `rename`),
53
+ directory `0700`, file `0600`; throws `ConfigError('write-failed')` on I/O errors.
54
+ - `updateConfig(dataRoot, mutate)` — serialized read-modify-write per data root (one promise
55
+ chain), passes a `structuredClone` to `mutate` (sync or async), persists the returned value and
56
+ returns the next document. A rejected mutation does not break the queue.
57
+ - `sanitizePreferences(patch, base)` — strict validation for the HTTP path: known keys only,
58
+ `releaseAction ∈ {'insert','send'}`, `holdDelayMs ∈ [150, 1000]`, `cancelDistancePx ∈ [40, 200]`,
59
+ `hintDismissed`/`composerHint`/`streaming` booleans; invalid known values throw
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.
68
+ - `maskSecret(value)` — `''` for an empty value, `'…'` for short ones, otherwise
69
+ `first3…last4`; never returns the full value.
70
+
71
+ ### wav.js
72
+
73
+ Canonical intake is a 16 kHz mono PCM16 WAV written by the browser recorder.
74
+
75
+ - `MAX_WAV_BYTES = 4 * 1024 * 1024` (the service may lower it through `limits`).
76
+ - `parseWav(bytes)` → `{ sampleRate, channels, bitsPerSample, audioFormat, dataOffset,
77
+ dataBytes, byteLength }`; walks RIFF chunks (extra chunks and word padding are accepted) and
78
+ rejects a header whose declared sizes disagree with the bytes.
79
+ - `validateWav(bytes, { maxAudioBytes, maxDurationSeconds })` → `{ sampleRate, channels,
80
+ bitsPerSample, durationSeconds, dataBytes }`; `WavError.code ∈ {'empty','too-large','not-wav',
81
+ 'unsupported-format','too-long'}` (format must be PCM16 mono 16 kHz; max duration default 120 s).
82
+ - `wavToPcm16` / `wavToFloat32` (mono `[-1,1]`) / `encodeWav(samples, sampleRate)` /
83
+ `resampleLinear(samples, fromRate, toRate)` — pure typed-array helpers, no Node built-ins.
84
+
85
+ ### http.js
86
+
87
+ - `ProviderError extends Error` with `code ∈ PROVIDER_ERROR_CODES = ['missing-credential', 'http',
88
+ 'timeout', 'network', 'parse', 'unsupported']` and optional `status`.
89
+ - `fetchJson(url, init, { timeoutMs = 30_000, fetchImpl = fetch })` → `{ status,
90
+ headers /* lowercase plain object */, body /* parsed JSON or undefined */, text }`. A non-2xx
91
+ status is a normal result; the vendor adapter decides whether to parse the error body. Transport
92
+ failures become `ProviderError('network')`, a fired timeout becomes `ProviderError('timeout')`,
93
+ and the caller's own abort is rethrown unchanged.
94
+ - `postJson` / `postMultipart(url, fields, fileField, file, init)` — request envelopes; the
95
+ multipart helper never sets a manual `Content-Type` (the runtime owns the boundary).
96
+ - `timeoutSignal(signal, ms)` — merges the caller signal with `AbortSignal.timeout(ms)`.
97
+
98
+ ### cloud-provider.js
99
+
100
+ `createCloudProvider(descriptor, { readConfig, env, fetchImpl })` builds the official provider
101
+ object from a **runtime descriptor** (metadata + one of `buildRequest`/`parseResponse` or
102
+ `execute`, assembled by `packages/cloud`, never by `core`):
103
+
104
+ ```js
105
+ {
106
+ info: { id, name, location: 'cloud', languages, setupEstimate?, downloadSources? },
107
+ async transcribe({ audio, language }, signal) {
108
+ const config = await readConfig() // re-read per recording
109
+ const { settings, missing } = readProviderSettings(config, descriptor, env)
110
+ if (missing.length > 0) throw ProviderError('missing-credential', 'Missing required setting: …')
111
+ if (descriptor.execute) return await descriptor.execute({ settings, wav: audio, language, signal, fetchImpl })
112
+ const request = await descriptor.buildRequest({ settings, wav: audio, language })
113
+ const response = await fetchJson(request.url, { ...request.init, signal }, { fetchImpl })
114
+ return descriptor.parseResponse(response) // { text, audioSeconds?, inferenceSeconds? }
115
+ },
116
+ }
117
+ ```
118
+
119
+ - `readProviderSettings(config, descriptor, env)` is a pure helper. Priority (lowest first):
120
+ field `default`, then `env[field.env]`, then the saved `config.providers[descriptor.id]` value
121
+ (the user's saved value wins; an empty string counts as “not set” and falls back to the
122
+ environment again). Returns `{ settings, missing }` where `missing` lists required keys as
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.
128
+ - The factory trims the transcript text, falls back to the WAV header for `audioSeconds` and to
129
+ the elapsed wall time for `inferenceSeconds`, and maps unexpected adapter errors to
130
+ `ProviderError('parse'|'unsupported')`; `ProviderError`s and caller aborts pass through
131
+ unchanged. The adapter owns the vendor wire format and the vendor error messages.
132
+ - The 13 single-request vendors use `buildRequest` + `parseResponse`. Soniox (`execute`) owns its
133
+ own upload → create → poll → transcript sequence, receives `signal`/`fetchImpl` and cleans up
134
+ remote resources best-effort.
135
+
136
+ ### catalog/cloud.js (metadata, owned by `packages/cloud`)
137
+
138
+ `CLOUD_CATALOG` exports **data only** — the single source of provider identity, settings form,
139
+ languages and docs. `core` must not import `packages/cloud` (one-way dependency) and a published
140
+ `core` tarball cannot resolve sibling workspace paths, so the request/response code stays in the
141
+ cloud package and is joined with these records there:
142
+
143
+ ```js
144
+ {
145
+ id: 'bvi-cloud-openai', vendor: 'openai', location: 'cloud',
146
+ name: { zh: 'OpenAI / OpenAI 兼容服务', en: 'OpenAI / OpenAI-compatible' },
147
+ languages: ['auto', 'zh', 'en', ...],
148
+ docs: 'https://platform.openai.com/docs/guides/speech-to-text',
149
+ env: ['OPENAI_API_KEY'],
150
+ fields: [
151
+ { key: 'apiKey', type: 'secret', env: 'OPENAI_API_KEY',
152
+ label: { zh: 'API Key(自部署服务可留空)', en: 'API key (blank for self-hosted)' } },
153
+ { key: 'baseURL', type: 'url', default: 'https://api.openai.com/v1', label: {...} },
154
+ { key: 'model', type: 'text', default: 'gpt-4o-transcribe', label: {...} },
155
+ { key: 'mode', type: 'select', default: 'fast', label: {...},
156
+ options: [{ value: 'fast', label: { zh: '快速', en: 'Fast' } }] },
157
+ ],
158
+ info: { id, name, location, languages }, // name is the zh display name
159
+ }
160
+ ```
161
+
162
+ The 14 vendors are the documented ones in `docs/research/cloud-providers.md`. The provider id is
163
+ `bvi-cloud-<vendor>`. `packages/cloud/lib/catalog.js` joins each record with its adapter
164
+ (`createCloudDescriptors()` / `CLOUD_DESCRIPTORS` / `getCloudDescriptor(id)`) to build the runtime
165
+ descriptors consumed by `createCloudProvider`.
166
+
167
+ ### catalog/local.js (metadata, owned by `packages/local`)
168
+
169
+ `LOCAL_MODELS` lists the seven sherpa-onnx families (11 variants) and `SHARED_ASSETS` the Silero
170
+ VAD / optional punctuation assets. The file is **data only** (no functions, no Node APIs) and
171
+ physically lives in `core` so the service can render the local-model settings page without
172
+ depending on the local row; its owner is `packages/local`, which turns `runtime` into the
173
+ sherpa-onnx configuration inside its worker:
174
+
175
+ ```js
176
+ {
177
+ id: 'bvi-local-sensevoice', family: 'sensevoice', location: 'host-local',
178
+ name: { zh, en }, languages: ['auto', 'zh', 'en', 'ja', 'ko', 'yue'],
179
+ docs: 'https://…',
180
+ downloadSources: ['https://huggingface.co', 'https://hf-mirror.com'],
181
+ defaultVariant: 'small-int8',
182
+ streaming: false, // optional; exactly X-ASR sets true (native online recognizer)
183
+ runtime: { kind: 'offline' | 'online', threads, vad, segmentation },
184
+ setupEstimate: { recommendedDiskBytes, expectedMemoryBytes, minimumMinutes, maximumMinutes },
185
+ variants: [{
186
+ id, label: { zh, en }, bytes,
187
+ files: [{ name, relativePath, bytes, sha256, url, mirrorURL? }],
188
+ }],
189
+ }
190
+ ```
191
+
192
+ `SHARED_ASSETS` carries the same `files`/`bytes`/`sha256` shape for the assets every family
193
+ shares. Variant selection is stored in `config.local[id].variant`; the service forwards it to the
194
+ local provider as `ctx.speechToText.prepare(id, { variant })` (the official seam passes the
195
+ options object through unchanged) so a custom data root cannot desynchronize the download from
196
+ the settings page.
197
+
198
+ ## `@ds-hu/dsh-bvi-service` (host + client)
199
+
200
+ ### Host (`lib/index.js`)
201
+
202
+ `name = 'bvi-service'`, `inject = ['connection']`; the speech registry is optional and read with
203
+ `ctx.get('speechToText')` so the settings page still loads while the official experimental voice
204
+ input bundle is disabled.
205
+
206
+ `apply(ctx, config)` resolves the data root (`config.dataRoot`, else
207
+ `ctx.get('dshHomePath')('better-voice-input')`; both go through `resolveDataRoot`), loads the two
208
+ catalogs tolerantly (`import.meta.resolve` + `existsSync`; a missing component package means an
209
+ empty list, a present-but-broken catalog rejects the row), then registers **eleven exact Fetch
210
+ routes** with `ctx.connection.fetch.register({ path, methods, requestBody: 'buffered', fetch })`
211
+ inside `ctx.effect`. The Connection layer owns the Host/Origin fence and browser authentication
212
+ (the owner Peer), so the handlers contain no hand-written same-origin check.
213
+
214
+ | Method + path | Request | Purpose |
215
+ | --- | --- | --- |
216
+ | `GET /api/better-voice-input/state` | — | provider views, masked config, catalogs, install state, preferences, limits, dependency status |
217
+ | `POST /api/better-voice-input/config` | `{ providerId, values }` | validate against the catalog field descriptors and persist |
218
+ | `POST /api/better-voice-input/select` | `{ providerId, language }` | `ctx.speechToText.configure(patch)` |
219
+ | `POST /api/better-voice-input/prepare` | `{ providerId, downloadSource? }` | `ctx.speechToText.prepare(id, { variant?, downloadSource? })` |
220
+ | `POST /api/better-voice-input/cancel-preparation` | `{ providerId }` | `ctx.speechToText.cancelPreparation(id)` |
221
+ | `POST /api/better-voice-input/transcribe?language=…` | raw `audio/wav` (≤ 8 MiB) | validate canonical WAV, `ctx.speechToText.transcribe`, `{ ok: true, text, audioSeconds, inferenceSeconds }` |
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) |
227
+
228
+ Body limits: JSON mutations 64 KiB (`MAX_JSON_BODY_BYTES`), transcribe 8 MiB
229
+ (`MAX_TRANSCRIBE_BODY_BYTES`), audio then capped by `limits.maxAudioBytes` after the WAV header is
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()`.
243
+
244
+ Success is HTTP 2xx with `{ ok: true, ... }`; failure is a non-2xx with
245
+ `{ ok: false, code, message }`, where the code is stable (`audio-*`, `provider-*`,
246
+ `invalid-*`, `stream-*`, `config-error`, `dependency-missing`, `unknown-provider`,
247
+ `body-too-large`, `unsupported-media-type`, `cancelled`, `internal`, …).
248
+
249
+ `GET /state` document (frozen; the settings page and the input component rely on it):
250
+
251
+ ```json
252
+ {
253
+ "ok": true,
254
+ "dependency": { "speechToText": true },
255
+ "providers": [{ "id": "bvi-cloud-openai", "name": "…", "location": "cloud",
256
+ "languages": ["auto", "zh"],
257
+ "preparation": { "phase": "ready" },
258
+ "streaming": false }],
259
+ "selection": { "providerId": "bvi-cloud-openai", "language": "zh" },
260
+ "config": { "bvi-cloud-openai": { "configured": true,
261
+ "fields": { "apiKey": "sk-…4f2a", "baseURL": "…" } } },
262
+ "cloud": [{ "id": "bvi-cloud-openai", "name": { "zh": "…", "en": "…" },
263
+ "languages": [], "env": [], "fields": [], "docs": "…", "configured": true,
264
+ "streaming": false }],
265
+ "local": [{ "id": "bvi-local-sensevoice", "name": { "zh": "…", "en": "…" },
266
+ "languages": [], "variants": [], "defaultVariant": "…", "variant": "…",
267
+ "downloadSources": [], "streaming": false,
268
+ "install": { "phase": "unprepared" } }],
269
+ "preferences": { "releaseAction": "insert", "holdDelayMs": 280, "cancelDistancePx": 72,
270
+ "hintDismissed": false, "composerHint": true, "streaming": true,
271
+ "shortcut": { "enabled": false, "code": "Space", "ctrl": true,
272
+ "alt": false, "shift": true, "meta": false } },
273
+ "limits": { "maxAudioBytes": 4194304, "maxDurationSeconds": 120 }
274
+ }
275
+ ```
276
+
277
+ `providers[].preparation` is normalized for the browser: in-flight official phases
278
+ (`downloading`, `checking`, `loading`, `cancelling`) become `preparing` with an integer
279
+ `progress` 0–100 when the download totals are known; `phase: 'failed'` carries `error`; other
280
+ phases pass through (`ready`, `standby`, `waking`, `unprepared`, `cancelled`). `local[].install`
281
+ uses the same normalization for the local provider's official preparation state
282
+ (`{ phase: 'unprepared' }` while the row is not registered). Secrets only ever appear masked.
283
+
284
+ `lib/api.js` is the testable half: `createApi({ store, catalogs, getSpeech, env, logger, limits })`
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` /
288
+ `ConfigError` / aborts to the HTTP status and envelope above. `lib/store.js` wraps the data root
289
+ in `read()`/`update()`.
290
+
291
+ ### Client (`lib/client.js`)
292
+
293
+ A classic lazy-CJS module (`window.__ModuleLoader__.load({ id, factory })`, `require('react')`
294
+ only). `apply(ctx)` registers the zh/en dictionaries (`ctx.locale.register(NS, …)`), a
295
+ module-owned `<style data-plugin="@ds-hu/dsh-better-voice-input">` using theme tokens only, and the
296
+ bundle configuration page:
297
+
298
+ ```js
299
+ ctx.slots.inject('plugins.bundle.config', () =>
300
+ ctx.slots.register({ name: 'plugins.bundle.config', key: '@ds-hu/dsh-better-voice-input',
301
+ locale: 'better-voice-input' }, SettingsPage))
302
+ ```
303
+
304
+ The owner passes `{ view: 'summary' | 'page' }` and no `form`, so the page draws its own form and
305
+ persists through the HTTP API above (`GET /state` once on open, then polls every 1.5 s while a
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.
312
+
313
+ ## `@ds-hu/dsh-bvi-input` (client)
314
+
315
+ `lib/client.js` registers the hold-to-talk component into `conversation.input.overlay`
316
+ (id `bvi-input`). It talks only to the service API (`GET /api/better-voice-input/state`,
317
+ `POST /api/better-voice-input/prepare`, `POST /api/better-voice-input/cancel-preparation`,
318
+ `POST /api/better-voice-input/transcribe?language=…`). Gesture, overlay and audio rules:
319
+ `docs/ARCHITECTURE.md` §4.
320
+
321
+ ## Streaming extension (v0.2, 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
345
+ marks those entries in `/state` (`providers[].streaming`) and refuses `/stream/start` for any
346
+ other provider (`streaming-unavailable`, HTTP 409).
347
+ - The service obtains the provider object with `ctx.speechToText.resolve({ audio: new
348
+ Uint8Array(0), language, providerId })` and checks `provider.bviStreaming` at request time.
349
+ The pinned provider lifetime is the session lifetime; `/stream/finish|cancel` release it.
350
+ - `partial` is the **cumulative** transcript so far (the browser replaces the live line). Empty
351
+ strings are valid. `finish()` settles exactly once; `cancel()` is idempotent and must release
352
+ the worker stream.
353
+ - `bviStreaming` is the only non-official property we add to a provider object; official
354
+ consumers ignore it.
355
+
356
+ ### Worker private protocol (`packages/local`, X-ASR only)
357
+
358
+ `sherpa-onnx-node`'s `OnlineRecognizer` provides incremental results. The worker child exposes
359
+ four authenticated loopback routes (bearer token, `127.0.0.1`, ephemeral port — same transport as
360
+ `/transcribe`):
361
+
362
+ | Method + path | Body | Answer |
363
+ | --- | --- | --- |
364
+ | `POST /stream/start?language=…` | — | `{ streamId }` (one live stream per worker) |
365
+ | `POST /stream/chunk?stream=…` | raw PCM16LE mono 16 kHz | `{ partial, bytes }` |
366
+ | `POST /stream/finish?stream=…` | — | `{ text, audioSeconds }` |
367
+ | `POST /stream/cancel?stream=…` | — | `{ ok: true }` |
368
+
369
+ The final decode uses the same drain protocol as the batch path (drain → two 480 ms silence
370
+ chunks → `inputFinished()` → drain) and the same `adapter.sanitize` text policy. Model
371
+ configuration literals are **unchanged** — streaming reuses the existing X-ASR
372
+ `OnlineRecognizer` config. The parent runtime exposes `startStream/pushStream/finishStream/
373
+ cancelStream` and measures `inferenceSeconds` on the parent side.
374
+
375
+ ### Browser contract (`packages/input`)
376
+
377
+ - Trigger rules: the pointer hold only starts when the composer editor is **not** focused on a
378
+ touch device and the virtual keyboard is closed (see ARCHITECTURE §4.2). The optional keyboard
379
+ shortcut follows the `preferences.shortcut` object.
380
+ - Streaming path is selected per recording: `preferences.streaming === true` **and**
381
+ `state.providers[selected].streaming === true` **and** `AudioWorklet` (or `ScriptProcessor`)
382
+ capture is available. Otherwise the existing whole-WAV `MediaRecorder` path runs unchanged.
383
+ - Audio: Float32 frames → 16 kHz PCM16LE; a `POST /stream/chunk` runs every ~200 ms (no
384
+ overlapping requests); overlay shows `partial` live above the waveform.
385
+ - Release: `POST /stream/finish` → final text → flight animation → `insertText`/`setDraft` as in
386
+ the batch path (`send` action and the conflict fallbacks are shared). Slide-up cancel and
387
+ Escape call `POST /stream/cancel` and insert nothing. If open/chunk fails mid-recording the
388
+ relay is abandoned and the take is transcribed as one WAV from the buffered PCM at release
389
+ (the overlay tells the user), so a relay fault never loses the recording.
390
+ - Keyboard shortcut: a configured `code`+modifier combination starts the same hold flow; keyup
391
+ releases, Escape cancels. It only fires while the composer exists and focus is not inside a
392
+ different input/textarea (so settings forms keep typing normally).
393
+ - The flight animation is DOM-only: a `.bvi-flight` clone of the final line is pinned over the
394
+ overlay, transformed to the composer input's `getBoundingClientRect()` (~360 ms
395
+ `cubic-bezier(.2,.8,.2,1)`, opacity/scale), then the real insertion happens. `prefers-reduced-
396
+ motion` skips the animation.
397
+
398
+ ### Settings page layout (v0.2)
399
+
400
+ Cloud and local sections are **master-detail**: a compact list of providers/models (name,
401
+ configured/install badge, chevron) and only the selected entry renders its detail card (fields,
402
+ env hint, docs, save; variant, estimate, download/cancel/progress). Selecting a row is local
403
+ component state; the first selection defaults to the current `selection.providerId` (cloud) and
404
+ the first installed local model (local); an empty catalog shows a hint instead of a card. The
405
+ summary view stays a flat two-line overview. No API change is needed for this layout.
406
+
407
+ ### OpenAI-compatible endpoints and optional credentials
408
+
409
+ `bvi-cloud-openai` is the OpenAI **and** OpenAI-compatible entry: `baseURL` and `model` are
410
+ editable and `apiKey` is optional, so a self-hosted gateway (for example an X-ASR model exposed
411
+ through an OpenAI-compatible `/v1/audio/transcriptions` server) works with an empty key. The
412
+ adapter omits the `Authorization` header when the key is empty. In `/state`, `configured` means
413
+ "every required field is filled" for vendors with required fields; a vendor with no required
414
+ field (OpenAI-compatible) is configured once any effective value exists, so a key-less
415
+ self-hosted setup is not reported as unconfigured. CI proves this end-to-end with
416
+ the `openai-compat-smoke` workflow: it downloads the pinned X-ASR model, serves it through a
417
+ local OpenAI-compatible endpoint, runs the real cloud adapter with `apiKey: ''`, and asserts the
418
+ transcript (and that no authorization header was sent).
419
+
420
+ ## Testing seams
421
+
422
+ Every module is testable without native dependencies and without a host process:
423
+
424
+ - `core`: `node:test` with temporary data roots and fake `fetch` implementations; no native code.
425
+ - cloud adapters: `createCloudProvider` with a fake `fetchImpl` + `readConfig`/`env` fixtures;
426
+ `test/cloud-adapters.test.mjs` imports the adapter modules and the shared data catalog.
427
+ - local catalog: data-only invariants (paths, byte counts, digests); no model download.
428
+ - service logic: `createApi` with an in-memory store, fake catalog arrays and a fake
429
+ `ctx.speechToText` registry (`test/service-api.test.mjs`).
430
+ - service host: `apply(ctx, { dataRoot })` with a fake Cordis context whose
431
+ `connection.fetch.register` records the routes; the tests drive the handlers with Fetch
432
+ `Request`/`Response` objects (`test/service-host.test.mjs`).
433
+ - browser entries: `test/client-harness.mjs` evaluates the classic script in a `vm` context,
434
+ captures `window.__ModuleLoader__.load({ id, factory })`, calls `factory(require)` with a
435
+ minimal React hook runtime, a fake document, fake timers and a fetch stub, and exposes the
436
+ rendered tree plus the static contract (module id, required modules, dictionaries, styles,
437
+ slot registration). The settings page and the input component are covered this way.
package/docs/DETAIL.md ADDED
@@ -0,0 +1,83 @@
1
+ # Better voice input for DeepSeek Harness
2
+
3
+ **21 speech-recognition services and a DeepSeek-App-style hold-to-talk composer.**
4
+
5
+ ![Hold the composer to record, slide up to cancel, release to insert](https://raw.githubusercontent.com/ds-hu/dsh-better-voice-input/main/docs/preview-en.svg)
6
+
7
+ This bundle extends the official experimental voice input plugin
8
+ (`@deepseek-ai/dsh-experimental-voice-input-bundle`) in two directions.
9
+
10
+ ## 1 · More recognizers
11
+
12
+ The official bundle ships one host-local model. This bundle registers **21 services** on the same
13
+ `ctx.speechToText` seam and adds a settings page to the Plugins panel:
14
+
15
+ - **14 cloud providers** — SiliconFlow, Volcengine, ElevenLabs, OpenAI, OpenRouter, DashScope,
16
+ DeepSeek, Gemini, Xiaomi MiMo, Tencent Cloud, Soniox, StepAudio, Zhipu and Cohere. Each has its
17
+ own form for API key, base URL, model and vendor options; environment variables work as a
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.
21
+ - **7 local model families** — SenseVoice, FunASR Nano, Qwen3-ASR, Parakeet, GigaAM, FireRedASR
22
+ and X-ASR, each with selectable variants. They run on this machine through `sherpa-onnx-node`,
23
+ downloaded on first use into `$DSH_HOME/better-voice-input/models` and verified file by file
24
+ against pinned SHA-256 digests. Local inference runs in a child process, so a model failure never
25
+ takes Harness down.
26
+
27
+ Components: **更多语音识别模型 · 云端**, **更多语音识别模型 · 本地**, and **语音识别服务**
28
+ (config store, the same-origin HTTP API, and this settings page).
29
+
30
+ ## 2 · A better composer interaction
31
+
32
+ The official voice UI is click-to-record. This bundle reproduces the DeepSeek App instead:
33
+
34
+ - **Press and hold the composer** (mouse, touch or pen — one gesture detector for desktop and
35
+ mobile). After a short hold the full-screen overlay appears with a live waveform.
36
+ - **Slide up to cancel.** The overlay turns from blue to red once you pass the cancel distance;
37
+ release there to discard the recording. Release anywhere else to transcribe. A small dead band
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.
44
+ - **Release behavior is yours.** By default the transcript is inserted into the draft at the
45
+ caret; a setting switches release to *send*.
46
+ - **The composer hint reads “发消息或按住说话”** when the draft is empty, and the overlay wording
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.
54
+ - Escape, a hidden tab or a lost focus cancels the recording — the microphone never stays open in
55
+ the background.
56
+
57
+ The settings page is master-detail: pick a cloud service or a local model first, and only that
58
+ entry's form appears, so a phone never flattens every field into one long scroll. The interaction
59
+ section decides release behavior, hold delay, cancel distance, the composer hint and live text;
60
+ the shortcut section records the keyboard combination.
61
+
62
+ Component: **更好的语音输入**.
63
+
64
+ ## Requirements
65
+
66
+ DeepSeek Harness **>= 0.2.2-rc.5 < 0.3.0** and Node.js **>= 20.19**. Live streaming needs
67
+ `AudioWorklet` (falls back to batch recognition otherwise); a plain `getUserMedia` browser is
68
+ 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
69
+ mic UI may be disabled. Cloud providers need the vendor's API key; local models need disk space
70
+ and a CPU (no GPU required).
71
+
72
+ ## Privacy
73
+
74
+ Speech is sent only to the service you chose — your configured vendor endpoint, or this machine for
75
+ local models. There is no telemetry and no relay. API keys stay on the host (masked in the browser,
76
+ `0600` on disk). Model downloads come from the upstream sherpa-onnx repositories and are verified
77
+ against pinned digests.
78
+
79
+ ## Links
80
+
81
+ - [Source, documentation and full model tables](https://github.com/ds-hu/dsh-better-voice-input)
82
+ - [Architecture](https://github.com/ds-hu/dsh-better-voice-input/blob/main/docs/ARCHITECTURE.md)
83
+ - [NOTICE (third-party attribution)](https://github.com/ds-hu/dsh-better-voice-input/blob/main/NOTICE)
@@ -0,0 +1,68 @@
1
+ # 更好的语音输入
2
+
3
+ **21 个语音识别服务,以及与 DeepSeek App 一致的「按住说话」输入体验。**
4
+
5
+ ![按住输入框录音,上滑取消,松手插入](https://raw.githubusercontent.com/ds-hu/dsh-better-voice-input/main/docs/preview.svg)
6
+
7
+ 本 bundle 从两个方向扩展官方实验性语音输入插件
8
+ (`@deepseek-ai/dsh-experimental-voice-input-bundle`)。
9
+
10
+ ## 一 · 更多识别模型
11
+
12
+ 官方 bundle 只内置一个本地模型。本 bundle 在同一个 `ctx.speechToText` 接缝上注册 **21 个服务**,
13
+ 并在插件面板里增加自己的设置页:
14
+
15
+ - **14 家云端服务** —— 硅基流动、火山引擎、ElevenLabs、OpenAI、OpenRouter、阿里云百炼、
16
+ DeepSeek、Gemini、小米 MiMo、腾讯云、Soniox、阶跃星辰、智谱、Cohere。每家都有独立表单
17
+ (API Key、base URL、model、供应商选项),环境变量可作为只读兜底。OpenAI 一项同时是
18
+ **OpenAI 兼容**入口:base URL、模型名都可改,API Key 允许留空,因此把本地模型以
19
+ `/v1/audio/transcriptions` 暴露出来的自部署服务可以直接接入。
20
+ - **7 个本地模型系列** —— SenseVoice、FunASR Nano、Qwen3-ASR、Parakeet、GigaAM、FireRedASR、
21
+ X-ASR,每个系列可选不同变体。它们通过 `sherpa-onnx-node` 在本机运行,首次使用时下载到
22
+ `$DSH_HOME/better-voice-input/models`,逐文件校验固定的 SHA-256;推理在子进程中运行,
23
+ 单个模型崩溃不会影响 Harness。
24
+
25
+ 组件:**更多语音识别模型 · 云端**、**更多语音识别模型 · 本地**、**语音识别服务**
26
+ (配置存储、同源 HTTP API、本设置页)。
27
+
28
+ ## 二 · 更好的输入交互
29
+
30
+ 官方语音 UI 是点击录音。本 bundle 复刻 DeepSeek App 的交互:
31
+
32
+ - **按住输入框说话**(鼠标、触屏、手写笔共用同一套长按判定)。短暂按住后出现全屏浮层与实时波形。
33
+ - **上滑取消**:上滑超过取消距离后浮层由蓝变红,此时松手放弃录音;在其他位置松手则开始转写。
34
+ 一段回滞区间避免松手瞬间在「取消/发送」之间抖动。
35
+ - **流式实时文字**:选中支持流式的模型(本地 X-ASR)时,录音过程中累计转写会实时出现在浮层
36
+ 上方;松手后最终文字从屏幕中间平滑飞入输入框。实时显示可在设置里关闭;不支持流式的服务仍
37
+ 走整段识别。需要浏览器支持 `AudioWorklet`,否则自动退回整段识别,功能不受影响。
38
+ - **松手行为可配置**:默认把识别结果插入草稿光标处;在设置里可改为松手直接发送。
39
+ - **草稿为空时组合框提示为「发消息或按住说话」**,浮层文案跟随松手行为(
40
+ 「松手插入,上滑取消」/「松手发送,上滑取消」)。
41
+ - **快捷键长按**:在设置里录制一个组合键(例如 `Ctrl+Shift+Space`),在对话里长按它即可开始
42
+ 语音输入;松手插入,`Esc` 取消。焦点在其他表单里时不会触发,设置页输入不受影响。
43
+ - **不与输入法打架**:触屏设备上,光标在输入框且虚拟键盘弹出时,长按输入框不会启动录音
44
+ (此前会把键盘推下去、浮层错位);收起键盘后按住即可说话。
45
+ - Esc、切到后台标签页、窗口失焦都会取消录音——麦克风不会在后台保持开启。
46
+
47
+ 设置页采用「先选模型、再看设置」的两栏结构:先点一个云端服务或本地模型,只展开它自己的表单,
48
+ 手机上不需要在几十个输入框之间长距离滚动。交互区决定松手行为、长按时长、取消距离、输入框提示
49
+ 与实时文字;快捷键区负责录制组合键。
50
+
51
+ 组件:**更好的语音输入**。
52
+
53
+ ## 环境要求
54
+
55
+ DeepSeek Harness **>= 0.2.2-rc.5 < 0.3.0**,Node.js **>= 20.19**。官方**语音输入** bundle 必须保持
56
+ 启用(它提供本 bundle 扩展的语音转写注册表),但它自带的麦克风 UI 可以关闭。云端服务需要供应商的
57
+ API Key;本地模型需要磁盘空间与 CPU,无需 GPU。
58
+
59
+ ## 隐私
60
+
61
+ 语音只会发送到你所选择的服务——你配置的云端接口,或本地模型(完全在本机)。没有遥测,没有中转。
62
+ API Key 保存在 host(浏览器只看掩码,磁盘权限 `0600`)。模型从 sherpa-onnx 上游仓库下载,并按固定摘要校验。
63
+
64
+ ## 链接
65
+
66
+ - [源码、文档与完整模型表](https://github.com/ds-hu/dsh-better-voice-input)
67
+ - [架构说明](https://github.com/ds-hu/dsh-better-voice-input/blob/main/docs/ARCHITECTURE.md)
68
+ - [NOTICE(第三方归属)](https://github.com/ds-hu/dsh-better-voice-input/blob/main/NOTICE)