@juicesharp/rpiv-voice 2.9.0 → 2.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.md +4 -2
- package/audio/sherpa-onnx-node.d.ts +7 -2
- package/audio/stt-engine.ts +36 -12
- package/command/pipeline-runner.ts +46 -6
- package/command/voice-command.ts +74 -14
- package/config/voice-config.ts +40 -0
- package/docs/configuration.md +32 -2
- package/docs/keybindings.md +1 -1
- package/locales/de.json +4 -1
- package/locales/en.json +4 -1
- package/locales/es.json +4 -1
- package/locales/fr.json +4 -1
- package/locales/pt-BR.json +4 -1
- package/locales/pt.json +4 -1
- package/locales/ru.json +4 -1
- package/locales/uk.json +4 -1
- package/locales/zh.json +4 -1
- package/package.json +2 -2
- package/state/selectors/projections.ts +10 -0
- package/state/state-reducer.ts +33 -7
- package/state/state.ts +8 -1
- package/state/voice-session.ts +15 -6
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,20 @@ All notable changes to `@juicesharp/rpiv-voice` are documented here.
|
|
|
5
5
|
Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
6
6
|
Versioning: [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [2.10.1] - 2026-09-13
|
|
9
|
+
|
|
10
|
+
## [2.10.0] - 2026-09-12
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- **The dictation UI no longer freezes while a decode runs.** `recognizer.decode()` ran Whisper inference synchronously on the shared event loop, so the TUI froze for the length of every decode. Recognizer construction and decode now ride napi async work (`OfflineRecognizer.createAsync` / `decodeAsync`), keeping the splash render and the overlay responsive. Because a final decode can now still be in flight when the user commits, the session drains the finals chain before pasting to the editor; the drain races a 10 s timeout that falls back to the reducer merge (leaving an `stt.drain` breadcrumb), and commit teardown orders drain-then-abort so a drain-time failure still reaches `errors.log`. Once the signal is aborted the pipeline skips stranded decode work outright, and post-abort rejections no longer land in the error log as failures.
|
|
15
|
+
- **Decodes serialize on the one native recognizer handle.** `SttEngine.recognize` FIFO-serializes calls, so a rolling partial and a chained final can no longer overlap on the handle sherpa holds no lock over.
|
|
16
|
+
- **A settings save no longer reverts JSON-only keys.** Save handlers merge the draft against `voice.json` as read at save time, so a mid-session hand edit of a key the settings screen does not own round-trips instead of silently reverting.
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
|
|
20
|
+
- **`numThreads` in `voice.json`** tunes the recognizer's decode threads (default 4, integer 1–16, clamped). It is JSON-only: the settings screen shows it read-only and passes it through on save. Decode calls leave `stt.decode` latency breadcrumbs in the diagnostic log, and the diagnostic-log table documents the new `stt.decode` / `stt.drain` rows.
|
|
21
|
+
|
|
8
22
|
## [2.9.0] - 2026-09-01
|
|
9
23
|
|
|
10
24
|
## [2.8.0] - 2026-08-29
|
package/README.md
CHANGED
|
@@ -66,14 +66,16 @@ If you have remapped Pi's confirm/cancel keys, the overlay follows your remap.
|
|
|
66
66
|
|
|
67
67
|
## Configuration
|
|
68
68
|
|
|
69
|
-
`/voice` needs no config file.
|
|
69
|
+
`/voice` needs no config file. The two toggles are editable on the settings screen (`Tab`
|
|
70
70
|
from dictation, `Ctrl-S` to save, `Esc` to save silently and go back) and persist to
|
|
71
|
-
`~/.config/rpiv-voice/voice.json
|
|
71
|
+
`~/.config/rpiv-voice/voice.json`; `numThreads` is JSON-only — the settings screen shows
|
|
72
|
+
it read-only, so hand-edit the file and re-run `/voice` to apply a change:
|
|
72
73
|
|
|
73
74
|
| Key | Default | Effect |
|
|
74
75
|
| --- | --- | --- |
|
|
75
76
|
| `hallucinationFilterEnabled` | `true` | Drops Whisper's silence artifacts and repetition loops |
|
|
76
77
|
| `equalizerEnabled` | `false` | Renders the live audio waveform under the transcript |
|
|
78
|
+
| `numThreads` | `4` | Decode threads for the Whisper recognizer — integer `1`–`16`; below `1` (or any invalid value) falls back to the default `4`, above `16` clamps to `16`. JSON-only, applied on the next `/voice` run |
|
|
77
79
|
|
|
78
80
|
The file is written with mode `0600`.
|
|
79
81
|
|
|
@@ -18,12 +18,17 @@ declare module "sherpa-onnx-node" {
|
|
|
18
18
|
}
|
|
19
19
|
// Note: OfflineRecognizer has no release/destroy/free method in
|
|
20
20
|
// sherpa-onnx-node@1.13.0 — the native handle is GC-managed.
|
|
21
|
-
//
|
|
22
|
-
//
|
|
21
|
+
// The engine uses the async pair — `OfflineRecognizer.createAsync` for
|
|
22
|
+
// construction and `decodeAsync` for decoding — which runs as napi async
|
|
23
|
+
// work off the shared event loop. `decodeAsync` resolves the parsed
|
|
24
|
+
// result, so `getResult` is not needed on the async path. The
|
|
25
|
+
// synchronous `decode` + `getResult` pair stays declared: this d.ts
|
|
26
|
+
// mirrors the binding's full surface.
|
|
23
27
|
export interface Recognizer {
|
|
24
28
|
createStream(): Stream;
|
|
25
29
|
decode(stream: Stream): void;
|
|
26
30
|
getResult(stream: Stream): Result;
|
|
31
|
+
decodeAsync(stream: Stream): Promise<Result>;
|
|
27
32
|
}
|
|
28
33
|
// Whisper config: `language` and `task` are optional (and meaningless for
|
|
29
34
|
// the *.en monolingual variants — the upstream example omits them
|
package/audio/stt-engine.ts
CHANGED
|
@@ -17,11 +17,23 @@
|
|
|
17
17
|
* undefined, the multilingual model's built-in auto-detect runs — the
|
|
18
18
|
* historical default behavior.
|
|
19
19
|
*
|
|
20
|
-
* Decode path:
|
|
21
|
-
*
|
|
20
|
+
* Decode path: ASYNCHRONOUS `recognizer.decodeAsync(stream)` — the binding
|
|
21
|
+
* runs the decode as napi async work off the shared event loop, so the loop
|
|
22
|
+
* stays responsive while Whisper infers (the synchronous decode blocked it
|
|
23
|
+
* and froze the UI under load). Construction is asynchronous too
|
|
24
|
+
* (`OfflineRecognizer.createAsync`) — loading the engine no longer blocks
|
|
25
|
+
* the splash render.
|
|
26
|
+
*
|
|
27
|
+
* Serialization: `recognize` calls are FIFO-queued per engine. sherpa's
|
|
28
|
+
* `decodeAsync` holds no JS-side lock, and the native layer's tolerance for
|
|
29
|
+
* concurrent decodes on one recognizer handle is undocumented — the old
|
|
30
|
+
* synchronous decode was serialized for free by the event loop, and callers
|
|
31
|
+
* (the rolling-partial path vs the finals chain) still assume that. A queued
|
|
32
|
+
* caller waits at most one decode; it never queues behind a whole chain.
|
|
22
33
|
*/
|
|
23
34
|
|
|
24
35
|
import type { Config } from "sherpa-onnx-node";
|
|
36
|
+
import { DEFAULT_NUM_THREADS } from "../config/voice-config.js";
|
|
25
37
|
|
|
26
38
|
// ── Whisper fixed input contract ─────────────────────────────────────────────
|
|
27
39
|
// 16 kHz mono PCM. featureDim 80 matches the model's mel-spectrogram output.
|
|
@@ -29,11 +41,8 @@ const WHISPER_SAMPLE_RATE = 16000;
|
|
|
29
41
|
const WHISPER_FEATURE_DIM = 80;
|
|
30
42
|
|
|
31
43
|
// ── Defaults ─────────────────────────────────────────────────────────────────
|
|
32
|
-
//
|
|
33
|
-
//
|
|
34
|
-
// thread pool follows the same pattern). More than 4 shows diminishing
|
|
35
|
-
// returns and can starve other Pi work on smaller machines.
|
|
36
|
-
const DEFAULT_NUM_THREADS = 4;
|
|
44
|
+
// DEFAULT_NUM_THREADS is imported from voice-config — the single source shared
|
|
45
|
+
// with the settings-row fallback, so the two cannot silently diverge.
|
|
37
46
|
const DEFAULT_PROVIDER = "cpu";
|
|
38
47
|
// `tailPaddings` is the only decoder-adjacent knob sherpa-onnx exposes for
|
|
39
48
|
// Whisper. Per maintainer guidance in k2-fsa/sherpa-onnx#2787, audio under
|
|
@@ -63,15 +72,30 @@ export interface SttEngine {
|
|
|
63
72
|
|
|
64
73
|
export async function createSttEngine(config: SttEngineConfig): Promise<SttEngine> {
|
|
65
74
|
const ns = await loadSherpaNamespace();
|
|
66
|
-
const recognizer =
|
|
75
|
+
const recognizer = await ns.OfflineRecognizer.createAsync(buildRecognizerConfig(config));
|
|
76
|
+
|
|
77
|
+
// FIFO decode queue — see the "Serialization" note in the module doc. Each
|
|
78
|
+
// call awaits the previous call's release before touching the shared
|
|
79
|
+
// native handle; the finally guarantees release even on a decode failure.
|
|
80
|
+
let decodeQueue: Promise<void> = Promise.resolve();
|
|
67
81
|
|
|
68
82
|
return {
|
|
69
83
|
async recognize(samples: Float32Array, sampleRate: number): Promise<string> {
|
|
70
84
|
if (samples.length === 0) return "";
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
85
|
+
const previous = decodeQueue;
|
|
86
|
+
let release!: () => void;
|
|
87
|
+
decodeQueue = new Promise<void>((resolve) => {
|
|
88
|
+
release = resolve;
|
|
89
|
+
});
|
|
90
|
+
await previous;
|
|
91
|
+
try {
|
|
92
|
+
const stream = recognizer.createStream();
|
|
93
|
+
stream.acceptWaveform({ samples, sampleRate });
|
|
94
|
+
const result = await recognizer.decodeAsync(stream);
|
|
95
|
+
return result.text.trim();
|
|
96
|
+
} finally {
|
|
97
|
+
release();
|
|
98
|
+
}
|
|
75
99
|
},
|
|
76
100
|
release(): void {
|
|
77
101
|
// sherpa-onnx-node@1.13.0 exposes no destructor; the native handle is
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { appendErrorLog } from "../audio/error-log.js";
|
|
1
|
+
import { appendDiagnosticLog, appendErrorLog } from "../audio/error-log.js";
|
|
2
2
|
import { isHallucination } from "../audio/hallucination-filter.js";
|
|
3
3
|
import type { DecibriLike } from "../audio/mic-source.js";
|
|
4
4
|
import { TARGET_SAMPLE_RATE } from "../audio/mic-source.js";
|
|
@@ -72,8 +72,20 @@ export function startDictationPipeline(
|
|
|
72
72
|
// painting stale text after the final commit.
|
|
73
73
|
let utteranceEpoch = 0;
|
|
74
74
|
|
|
75
|
+
// Decode-latency breadcrumbs: one stt.decode line per completed recognize
|
|
76
|
+
// call (kind + wall-clock duration + sample count) so a freeze report shows
|
|
77
|
+
// how long each final/partial decode actually took.
|
|
78
|
+
const logDecode = (kind: "final" | "partial", sampleCount: number, startedAt: number): void => {
|
|
79
|
+
appendDiagnosticLog("stt.decode", `${kind} ${Date.now() - startedAt}ms ${sampleCount} samples`);
|
|
80
|
+
};
|
|
81
|
+
|
|
75
82
|
const recognizeFinal = async (chunks: Buffer[]): Promise<void> => {
|
|
76
83
|
if (chunks.length === 0) return;
|
|
84
|
+
// The signal aborts on cancel — the commit path drains first and aborts
|
|
85
|
+
// only after (voice-command teardown ordering). Post-abort the session
|
|
86
|
+
// is torn down and the drain result has no consumer, so skip the decode
|
|
87
|
+
// outright instead of running Whisper for a transcript nobody reads.
|
|
88
|
+
if (signal.aborted) return;
|
|
77
89
|
const samples = bufferToFloat32(Buffer.concat(chunks));
|
|
78
90
|
if (computeRmsFloat32(samples) < MIN_SEGMENT_RMS) {
|
|
79
91
|
// No audible content — but still finalize so any in-flight partial
|
|
@@ -82,7 +94,13 @@ export function startDictationPipeline(
|
|
|
82
94
|
return;
|
|
83
95
|
}
|
|
84
96
|
try {
|
|
97
|
+
const decodeStartedAt = Date.now();
|
|
85
98
|
const text = await sttEngine.recognize(samples, TARGET_SAMPLE_RATE);
|
|
99
|
+
logDecode("final", samples.length, decodeStartedAt);
|
|
100
|
+
// Canceled while the decode was in flight: discard the result — the
|
|
101
|
+
// accumulator is unconsumed on cancel and the session is done, so a
|
|
102
|
+
// dispatch would only churn a torn-down TUI.
|
|
103
|
+
if (signal.aborted) return;
|
|
86
104
|
if (!text || (hallucinationFilterEnabled && isHallucination(text))) {
|
|
87
105
|
session.dispatchAction({ kind: "audio_transcript_appended", text: "" });
|
|
88
106
|
return;
|
|
@@ -93,7 +111,11 @@ export function startDictationPipeline(
|
|
|
93
111
|
// We deliberately do not surface this to the TUI: writing to stderr
|
|
94
112
|
// corrupts the active render, and `notify` would churn the chat for
|
|
95
113
|
// every dropped segment. Instead, append a breadcrumb to a file the
|
|
96
|
-
// user can `cat` later when investigating transcript gaps.
|
|
114
|
+
// user can `cat` later when investigating transcript gaps. Only
|
|
115
|
+
// cancel teardown is exempt: the signal aborts pre-drain on cancel
|
|
116
|
+
// alone, so a post-abort rejection is a decode nobody consumes —
|
|
117
|
+
// the commit drain runs pre-abort and its failures always log.
|
|
118
|
+
if (signal.aborted) return;
|
|
97
119
|
appendErrorLog("stt.recognize", err);
|
|
98
120
|
session.dispatchAction({ kind: "audio_transcript_appended", text: "" });
|
|
99
121
|
}
|
|
@@ -123,10 +145,14 @@ export function startDictationPipeline(
|
|
|
123
145
|
};
|
|
124
146
|
|
|
125
147
|
// Rolling partial preview. Runs *outside* the `recognizing` chain so the
|
|
126
|
-
// preview latency isn't queued behind pending finals
|
|
127
|
-
//
|
|
128
|
-
//
|
|
148
|
+
// preview latency isn't queued behind pending finals — though the engine
|
|
149
|
+
// itself serializes decodes (native handle is not proven concurrency-safe),
|
|
150
|
+
// so a partial can wait behind at most the one in-flight decode, never the
|
|
151
|
+
// whole chain. Best-effort: a snapshot of the current buffer is decoded,
|
|
152
|
+
// and the result is dispatched as the new partial only if the utterance
|
|
153
|
+
// epoch hasn't advanced under us.
|
|
129
154
|
const tryEmitPartial = (): void => {
|
|
155
|
+
if (signal.aborted) return;
|
|
130
156
|
if (partialInFlight) return;
|
|
131
157
|
if (speechBuffer.length === 0) return;
|
|
132
158
|
const now = Date.now();
|
|
@@ -139,12 +165,16 @@ export function startDictationPipeline(
|
|
|
139
165
|
try {
|
|
140
166
|
const samples = bufferToFloat32(Buffer.concat(snapshot));
|
|
141
167
|
if (computeRmsFloat32(samples) < MIN_SEGMENT_RMS) return;
|
|
168
|
+
const decodeStartedAt = Date.now();
|
|
142
169
|
const text = await sttEngine.recognize(samples, TARGET_SAMPLE_RATE);
|
|
170
|
+
logDecode("partial", samples.length, decodeStartedAt);
|
|
171
|
+
// Session torn down (cancel) or drain-superseded — never paint.
|
|
172
|
+
if (signal.aborted) return;
|
|
143
173
|
if (snapshotEpoch !== utteranceEpoch) return;
|
|
144
174
|
if (hallucinationFilterEnabled && isHallucination(text)) return;
|
|
145
175
|
session.dispatchAction({ kind: "audio_partial_transcript_set", text });
|
|
146
176
|
} catch (err) {
|
|
147
|
-
appendErrorLog("stt.recognize.partial", err);
|
|
177
|
+
if (!signal.aborted) appendErrorLog("stt.recognize.partial", err);
|
|
148
178
|
} finally {
|
|
149
179
|
partialInFlight = false;
|
|
150
180
|
}
|
|
@@ -222,13 +252,23 @@ function waitForMicShutdown(mic: DecibriLike, signal: AbortSignal, onFinish: ()
|
|
|
222
252
|
const onAbort = () => {
|
|
223
253
|
mic.stop();
|
|
224
254
|
};
|
|
255
|
+
// The terminal events can arrive in sequence (a Readable emits `close`
|
|
256
|
+
// after `end`) — drain exactly once.
|
|
257
|
+
let finished = false;
|
|
225
258
|
const finish = async () => {
|
|
259
|
+
if (finished) return;
|
|
260
|
+
finished = true;
|
|
226
261
|
signal.removeEventListener("abort", onAbort);
|
|
227
262
|
await onFinish();
|
|
228
263
|
resolve();
|
|
229
264
|
};
|
|
230
265
|
mic.once("end", finish);
|
|
231
266
|
mic.once("error", finish);
|
|
267
|
+
// `close` is the third terminal event in the DecibriLike contract, and
|
|
268
|
+
// the adapters forward it. Nothing else consumes it, so without this a
|
|
269
|
+
// close-without-end shutdown would park the drain — and with it the
|
|
270
|
+
// committed paste — forever.
|
|
271
|
+
mic.once("close", finish);
|
|
232
272
|
if (signal.aborted) {
|
|
233
273
|
mic.stop();
|
|
234
274
|
} else {
|
package/command/voice-command.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { appendErrorLog } from "../audio/error-log.js";
|
|
2
3
|
import { createMic, type DecibriLike } from "../audio/mic-source.js";
|
|
3
4
|
import {
|
|
4
5
|
assertModelIntact,
|
|
@@ -9,13 +10,18 @@ import {
|
|
|
9
10
|
removeModelInstall,
|
|
10
11
|
} from "../audio/model-download.js";
|
|
11
12
|
import { createSttEngine, type SttEngine } from "../audio/stt-engine.js";
|
|
12
|
-
import {
|
|
13
|
+
import {
|
|
14
|
+
isHallucinationFilterEnabled,
|
|
15
|
+
loadVoiceConfig,
|
|
16
|
+
resolveNumThreads,
|
|
17
|
+
type VoiceConfig,
|
|
18
|
+
} from "../config/voice-config.js";
|
|
13
19
|
import { getActiveLocale, t } from "../state/i18n-bridge.js";
|
|
14
20
|
import type { VoiceResult } from "../state/state-reducer.js";
|
|
15
21
|
import { VoiceSession } from "../state/voice-session.js";
|
|
16
22
|
import type { SplashPhase } from "../view/components/splash-view.js";
|
|
17
23
|
import { STATUS_BAR_PULSE_FRAME_INTERVAL_MS } from "../view/components/status-bar-view.js";
|
|
18
|
-
import { startDictationPipeline } from "./pipeline-runner.js";
|
|
24
|
+
import { type PipelineHandle, startDictationPipeline } from "./pipeline-runner.js";
|
|
19
25
|
import { runWithSplash } from "./splash-runner.js";
|
|
20
26
|
|
|
21
27
|
export const VOICE_COMMAND_NAME = "voice";
|
|
@@ -56,6 +62,13 @@ function whisperLanguageForLocale(locale: string | undefined): string | undefine
|
|
|
56
62
|
return isWhisperSupported(base) ? base : undefined;
|
|
57
63
|
}
|
|
58
64
|
|
|
65
|
+
// Upper bound on the commit drain: mic shutdown plus one final Whisper decode
|
|
66
|
+
// of a sub-12 s segment (typically well under a second). A hung native decode
|
|
67
|
+
// or a mic that never emits a terminal event must not park the handler forever
|
|
68
|
+
// with the overlay already closed — on timeout the reducer's commit merge,
|
|
69
|
+
// already the floor, is pasted as-is and a breadcrumb lands in errors.log.
|
|
70
|
+
const COMMIT_DRAIN_TIMEOUT_MS = 10_000;
|
|
71
|
+
|
|
59
72
|
const SPLASH_INITIAL_ENGINE: SplashPhase = { kind: "loading_engine" };
|
|
60
73
|
function splashInitialDownload(): SplashPhase {
|
|
61
74
|
return { kind: "downloading", message: t("splash.preparing", "Preparing model…") };
|
|
@@ -90,16 +103,23 @@ async function handleVoiceCommand(ctx: ExtensionCommandContext): Promise<void> {
|
|
|
90
103
|
return;
|
|
91
104
|
}
|
|
92
105
|
|
|
93
|
-
|
|
106
|
+
// One config snapshot per invocation: engine construction (numThreads) and
|
|
107
|
+
// the dictation session (VoiceSession's persistedConfig, the hallucination
|
|
108
|
+
// filter default) must read the same load, so it happens once, here.
|
|
109
|
+
// Settings saves are the exception — they re-read the file at save time so
|
|
110
|
+
// mid-session hand edits of JSON-only keys round-trip.
|
|
111
|
+
const persistedConfig = loadVoiceConfig();
|
|
112
|
+
|
|
113
|
+
const preflight = await runPreflight(ctx, persistedConfig);
|
|
94
114
|
if (!preflight) return;
|
|
95
115
|
|
|
96
|
-
const result = await runDictationSession(ctx, preflight.sttEngine, preflight.mic);
|
|
116
|
+
const result = await runDictationSession(ctx, preflight.sttEngine, preflight.mic, persistedConfig);
|
|
97
117
|
if (result.intent === "commit" && result.transcript) {
|
|
98
118
|
ctx.ui.pasteToEditor(result.transcript);
|
|
99
119
|
}
|
|
100
120
|
}
|
|
101
121
|
|
|
102
|
-
async function runPreflight(ctx: ExtensionCommandContext): Promise<Preflight | null> {
|
|
122
|
+
async function runPreflight(ctx: ExtensionCommandContext, persistedConfig: VoiceConfig): Promise<Preflight | null> {
|
|
103
123
|
try {
|
|
104
124
|
return await runWithSplash<Preflight>(
|
|
105
125
|
ctx,
|
|
@@ -151,6 +171,7 @@ async function runPreflight(ctx: ExtensionCommandContext): Promise<Preflight | n
|
|
|
151
171
|
decoderPath: paths.decoderPath,
|
|
152
172
|
tokensPath: paths.tokensPath,
|
|
153
173
|
language: whisperLanguageForLocale(getActiveLocale()),
|
|
174
|
+
numThreads: resolveNumThreads(persistedConfig),
|
|
154
175
|
});
|
|
155
176
|
} catch (e) {
|
|
156
177
|
// Preserve the inner stage tag (e.g. "stale_install") instead of
|
|
@@ -209,17 +230,11 @@ async function runDictationSession(
|
|
|
209
230
|
ctx: ExtensionCommandContext,
|
|
210
231
|
sttEngine: SttEngine,
|
|
211
232
|
mic: DecibriLike,
|
|
233
|
+
persistedConfig: VoiceConfig,
|
|
212
234
|
): Promise<VoiceResult> {
|
|
213
235
|
const controller = new AbortController();
|
|
214
|
-
const persistedConfig = loadVoiceConfig();
|
|
215
236
|
|
|
216
|
-
let pipelineHandle:
|
|
217
|
-
| {
|
|
218
|
-
setPaused: (v: boolean) => void;
|
|
219
|
-
setHallucinationFilterEnabled: (v: boolean) => void;
|
|
220
|
-
stop: () => void;
|
|
221
|
-
}
|
|
222
|
-
| undefined;
|
|
237
|
+
let pipelineHandle: PipelineHandle | undefined;
|
|
223
238
|
let pulseTick: ReturnType<typeof setInterval> | undefined;
|
|
224
239
|
|
|
225
240
|
const result = await ctx.ui.custom<VoiceResult>((tui, theme, _kb, done) => {
|
|
@@ -245,7 +260,52 @@ async function runDictationSession(
|
|
|
245
260
|
});
|
|
246
261
|
|
|
247
262
|
if (pulseTick) clearInterval(pulseTick);
|
|
263
|
+
let finalResult: VoiceResult = result;
|
|
264
|
+
if (result.intent === "commit") {
|
|
265
|
+
// Commit-drain merge floor. The reducer's commit merge — committed
|
|
266
|
+
// finals plus the visible partial (`state.partialTranscript`, an
|
|
267
|
+
// accumulator in neither pipeline store) — is the floor.
|
|
268
|
+
// finalTranscriptPromise resolves only after the whole finals chain
|
|
269
|
+
// settles, so the drained text equals the committed finals plus the
|
|
270
|
+
// drain-time final only when that final was accepted; on
|
|
271
|
+
// hallucination/RMS disagreement or a drain-time decode error the drain
|
|
272
|
+
// collapses to the prior finals — text the merge already extends.
|
|
273
|
+
// Replace the merge only when the drain extends beyond it as text; an
|
|
274
|
+
// empty drain fails `if (drained)` outright.
|
|
275
|
+
//
|
|
276
|
+
// Ordering: stop the mic and drain BEFORE aborting. The drain-time
|
|
277
|
+
// final is the one decode whose outcome the user consumes; the pipeline
|
|
278
|
+
// treats an aborted signal as cancel teardown (it suppresses error
|
|
279
|
+
// breadcrumbs and skips stranded decode work), so the commit drain must
|
|
280
|
+
// run while the signal is live. Cancel inverts this: the reducer aborts
|
|
281
|
+
// first and the pipeline short-circuits the drain fire-and-forget.
|
|
282
|
+
pipelineHandle?.stop();
|
|
283
|
+
const drained = await boundedDrain(pipelineHandle?.finalTranscriptPromise);
|
|
284
|
+
if (drained && !result.transcript.startsWith(drained)) {
|
|
285
|
+
finalResult = { ...result, transcript: drained };
|
|
286
|
+
}
|
|
287
|
+
}
|
|
248
288
|
if (!controller.signal.aborted) controller.abort();
|
|
249
289
|
sttEngine.release();
|
|
250
|
-
return
|
|
290
|
+
return finalResult;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Bounds the commit-drain await so a mic that never emits a terminal event or
|
|
294
|
+
// a hung native decode cannot park the handler after the overlay closed.
|
|
295
|
+
// Resolves `undefined` on timeout — the caller then keeps the reducer merge.
|
|
296
|
+
async function boundedDrain(drain: Promise<string> | undefined): Promise<string | undefined> {
|
|
297
|
+
if (!drain) return undefined;
|
|
298
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
299
|
+
const timeout = new Promise<undefined>((resolve) => {
|
|
300
|
+
timer = setTimeout(() => resolve(undefined), COMMIT_DRAIN_TIMEOUT_MS);
|
|
301
|
+
});
|
|
302
|
+
try {
|
|
303
|
+
const drained = await Promise.race([drain, timeout]);
|
|
304
|
+
if (drained === undefined) {
|
|
305
|
+
appendErrorLog("stt.drain", new Error(`commit drain timed out after ${COMMIT_DRAIN_TIMEOUT_MS}ms`));
|
|
306
|
+
}
|
|
307
|
+
return drained;
|
|
308
|
+
} finally {
|
|
309
|
+
clearTimeout(timer);
|
|
310
|
+
}
|
|
251
311
|
}
|
package/config/voice-config.ts
CHANGED
|
@@ -22,6 +22,13 @@ const VOICE_STATE_KEY = Symbol.for("rpiv-voice");
|
|
|
22
22
|
export interface VoiceConfig {
|
|
23
23
|
readonly hallucinationFilterEnabled?: boolean;
|
|
24
24
|
readonly equalizerEnabled?: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Decode thread count for the STT engine. JSON-only key: the settings
|
|
27
|
+
* screen never writes it, and it applies when `/voice` next constructs the
|
|
28
|
+
* engine (restart-to-apply). Integer 1–16 — invalid values decode to the
|
|
29
|
+
* default 4 and integers above 16 clamp to 16; see `resolveNumThreads`.
|
|
30
|
+
*/
|
|
31
|
+
readonly numThreads?: number;
|
|
25
32
|
}
|
|
26
33
|
|
|
27
34
|
/**
|
|
@@ -41,6 +48,39 @@ export function isEqualizerEnabled(config: { equalizerEnabled?: boolean }): bool
|
|
|
41
48
|
return config.equalizerEnabled === true;
|
|
42
49
|
}
|
|
43
50
|
|
|
51
|
+
/**
|
|
52
|
+
* Decode-thread default — the single source. The engine
|
|
53
|
+
* (`audio/stt-engine.ts`) imports it as its constructor fallback and the
|
|
54
|
+
* settings row shows it, so the two surfaces cannot diverge. 4 threads is the
|
|
55
|
+
* sweet spot for Whisper base on a modern multi-core CPU per upstream tuning
|
|
56
|
+
* guidance (whisper.cpp benchmarks; the sherpa-onnx ORT thread pool follows
|
|
57
|
+
* the same pattern) — more shows diminishing returns and can starve other Pi
|
|
58
|
+
* work on smaller machines.
|
|
59
|
+
*/
|
|
60
|
+
export const DEFAULT_NUM_THREADS = 4;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Decode-thread ceiling. 16 covers the best datapoint measured while
|
|
64
|
+
* investigating issue #200 and bounds ONNX Runtime intra-op thread
|
|
65
|
+
* oversubscription — beyond it, extra threads only add contention.
|
|
66
|
+
*/
|
|
67
|
+
export const MAX_NUM_THREADS = 16;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Decode the JSON-only `numThreads` key for engine construction: missing /
|
|
71
|
+
* non-number ("8", null, NaN) / non-integer (8.5) / below-floor (0, negative)
|
|
72
|
+
* values fall back to `DEFAULT_NUM_THREADS`; integers 1–16 pass through;
|
|
73
|
+
* integers above 16 clamp to `MAX_NUM_THREADS`. Baked in when `/voice`
|
|
74
|
+
* starts — changing voice.json requires re-running `/voice` to apply.
|
|
75
|
+
*/
|
|
76
|
+
export function resolveNumThreads(config: { numThreads?: number }): number {
|
|
77
|
+
const value = config.numThreads;
|
|
78
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
|
|
79
|
+
return DEFAULT_NUM_THREADS;
|
|
80
|
+
}
|
|
81
|
+
return Math.min(value, MAX_NUM_THREADS);
|
|
82
|
+
}
|
|
83
|
+
|
|
44
84
|
export function loadVoiceConfig(): VoiceConfig {
|
|
45
85
|
return loadJsonConfigWithLegacyFallback<VoiceConfig>("rpiv-voice", "voice.json");
|
|
46
86
|
}
|
package/docs/configuration.md
CHANGED
|
@@ -32,13 +32,15 @@ Writes only ever go to the XDG-resolved path.
|
|
|
32
32
|
| --- | --- | --- | --- |
|
|
33
33
|
| `hallucinationFilterEnabled` | boolean | `true` | Drops Whisper's silence artifacts and repetition loops. Turn it off when you are dictating single words the filter might mistake for noise |
|
|
34
34
|
| `equalizerEnabled` | boolean | `false` | Renders the live audio waveform lattice under the transcript |
|
|
35
|
+
| `numThreads` | integer | `4` | Decode threads for the sherpa-onnx recognizer. JSON-only — the settings screen shows it read-only; re-run `/voice` to apply a change |
|
|
35
36
|
|
|
36
37
|
There are no other keys. A hand-written file looks like this:
|
|
37
38
|
|
|
38
39
|
```json
|
|
39
40
|
{
|
|
40
41
|
"hallucinationFilterEnabled": false,
|
|
41
|
-
"equalizerEnabled": true
|
|
42
|
+
"equalizerEnabled": true,
|
|
43
|
+
"numThreads": 8
|
|
42
44
|
}
|
|
43
45
|
```
|
|
44
46
|
|
|
@@ -46,9 +48,14 @@ Only non-default values are persisted — the filter key lands on disk only when
|
|
|
46
48
|
`false`, the equalizer key only when it is `true`. A default-settings install therefore
|
|
47
49
|
writes `{}`, and an absent key always means "the default", never "unset".
|
|
48
50
|
|
|
51
|
+
`numThreads` is the exception in how it gets on disk: the settings screen never writes
|
|
52
|
+
it (the row is read-only), so a hand-added value stays until you remove it. Every
|
|
53
|
+
settings save merges around it — your hand edit survives toggling and saving from the
|
|
54
|
+
overlay — and it takes effect the next time you run `/voice`.
|
|
55
|
+
|
|
49
56
|
## The settings screen
|
|
50
57
|
|
|
51
|
-
`Tab` from dictation opens a
|
|
58
|
+
`Tab` from dictation opens a five-row panel:
|
|
52
59
|
|
|
53
60
|
| Row | Kind | Value |
|
|
54
61
|
| --- | --- | --- |
|
|
@@ -56,6 +63,7 @@ writes `{}`, and an absent key always means "the default", never "unset".
|
|
|
56
63
|
| Language | read-only | the endonym of your active locale (`Deutsch`, `Русский`, `中文`, …) or `Auto-detect`. Hint: `Run /languages to change.` |
|
|
57
64
|
| Filter Whisper noise | toggle | `[ on ]` / `[ off ]` — writes `hallucinationFilterEnabled` |
|
|
58
65
|
| Equalizer | toggle | `[ on ]` / `[ off ]` — writes `equalizerEnabled` |
|
|
66
|
+
| Threads | read-only | the decode thread count baked at `/voice` start. Hint: `Set numThreads in voice.json; re-run /voice to apply.` |
|
|
59
67
|
|
|
60
68
|
Only the two toggles take focus. `Ctrl-S` saves and confirms; `Esc` and `Tab` save
|
|
61
69
|
silently on the way out. See [keybindings.md](./keybindings.md) for the full key table.
|
|
@@ -96,6 +104,8 @@ That path is hardcoded — unlike `voice.json`, it does **not** move when you se
|
|
|
96
104
|
| --- | --- |
|
|
97
105
|
| `stt.recognize` | A final segment failed to decode. The transcript skips it |
|
|
98
106
|
| `stt.recognize.partial` | A rolling partial decode failed. Harmless — the next one retries |
|
|
107
|
+
| `stt.decode` | Latency breadcrumb: one line per completed decode (final or partial) with its wall-clock duration and sample count. Informational |
|
|
108
|
+
| `stt.drain` | The commit drain timed out; the pasted text fell back to the on-screen merge |
|
|
99
109
|
| `mic.path` | Which capture strategy won at startup, and why the first one was refused |
|
|
100
110
|
|
|
101
111
|
Writes to this log are best-effort and never throw. The dictation pipeline cannot write
|
|
@@ -112,6 +122,9 @@ trail — check it first when a phrase silently fails to transcribe.
|
|
|
112
122
|
`/voice` starts, and is fixed for that session — see below.
|
|
113
123
|
- **Command flags.** `/voice` ignores any arguments you type after it.
|
|
114
124
|
|
|
125
|
+
Decode threads are the counter-example to this list: they *are* the tunable knob. Set
|
|
126
|
+
`numThreads` in `voice.json` (see [Keys](#keys)) and re-run `/voice`.
|
|
127
|
+
|
|
115
128
|
## How the recognition language is chosen
|
|
116
129
|
|
|
117
130
|
When `@juicesharp/rpiv-i18n` is installed and your active locale's base code is one of
|
|
@@ -123,3 +136,20 @@ and run `/voice` again.
|
|
|
123
136
|
|
|
124
137
|
With no locale active, or a locale outside that list, the engine falls back to Whisper's
|
|
125
138
|
built-in per-utterance auto-detect across the full multilingual model.
|
|
139
|
+
|
|
140
|
+
## How the decode thread count is chosen
|
|
141
|
+
|
|
142
|
+
`numThreads` sets how many threads sherpa-onnx may use to decode audio. The value is
|
|
143
|
+
resolved once, when `/voice` starts, and baked into the recognizer for the whole session —
|
|
144
|
+
editing `voice.json` mid-session does nothing until the next run.
|
|
145
|
+
|
|
146
|
+
The rules are applied silently — no warning is printed for a rejected value:
|
|
147
|
+
|
|
148
|
+
- an integer `1`–`16` is used as-is;
|
|
149
|
+
- an integer above `16` is clamped down to `16`;
|
|
150
|
+
- anything else — missing, not a number (`"8"`, `null`), not an integer (`8.5`), or below
|
|
151
|
+
`1` (`0`, negative) — falls back to `4`.
|
|
152
|
+
|
|
153
|
+
The default of `4` mirrors the engine's built-in fallback. `16` is the ceiling because it
|
|
154
|
+
covers the measured best datapoint while bounding ORT intra-op oversubscription on
|
|
155
|
+
smaller machines.
|
package/docs/keybindings.md
CHANGED
|
@@ -36,7 +36,7 @@ Any other keystroke is ignored — there is no text input on this screen.
|
|
|
36
36
|
Footer: `↑↓ to select · Enter to toggle · Ctrl-S to save · Esc to go back`.
|
|
37
37
|
|
|
38
38
|
Focus starts on **Filter Whisper noise** and cycles between it and **Equalizer**. The
|
|
39
|
-
**Microphone** and **
|
|
39
|
+
**Microphone**, **Language**, and **Threads** rows are read-only and are skipped by focus.
|
|
40
40
|
|
|
41
41
|
`Esc` and `Tab` persist your changes silently on the way out, so a
|
|
42
42
|
toggle-then-leave flow never loses the change. `Ctrl-S` is the explicit path that also
|
package/locales/de.json
CHANGED
|
@@ -35,5 +35,8 @@
|
|
|
35
35
|
"settings.language_value_auto": "Automatisch erkennen",
|
|
36
36
|
"settings.language_hint": "Mit /languages ändern.",
|
|
37
37
|
"settings.hallucination_filter_label": "Whisper-Rauschen filtern",
|
|
38
|
-
"settings.hallucination_filter_hint": "Entfernt Stille-Artefakte. Bei Einzelwort-Diktat ausschalten."
|
|
38
|
+
"settings.hallucination_filter_hint": "Entfernt Stille-Artefakte. Bei Einzelwort-Diktat ausschalten.",
|
|
39
|
+
|
|
40
|
+
"settings.threads_label": "Threads",
|
|
41
|
+
"settings.threads_hint": "numThreads in voice.json festlegen; /voice erneut ausführen, um die Änderung zu übernehmen."
|
|
39
42
|
}
|
package/locales/en.json
CHANGED
|
@@ -41,5 +41,8 @@
|
|
|
41
41
|
"settings.hallucination_filter_hint": "Drops silence-segment artifacts. Turn off for single-word dictation.",
|
|
42
42
|
|
|
43
43
|
"settings.equalizer_label": "Equalizer",
|
|
44
|
-
"settings.equalizer_hint": "Show the live audio waveform under the transcript. Off by default."
|
|
44
|
+
"settings.equalizer_hint": "Show the live audio waveform under the transcript. Off by default.",
|
|
45
|
+
|
|
46
|
+
"settings.threads_label": "Threads",
|
|
47
|
+
"settings.threads_hint": "Set numThreads in voice.json; re-run /voice to apply."
|
|
45
48
|
}
|
package/locales/es.json
CHANGED
|
@@ -35,5 +35,8 @@
|
|
|
35
35
|
"settings.language_value_auto": "Detección automática",
|
|
36
36
|
"settings.language_hint": "Ejecuta /languages para cambiar.",
|
|
37
37
|
"settings.hallucination_filter_label": "Filtrar ruido de Whisper",
|
|
38
|
-
"settings.hallucination_filter_hint": "Descarta artefactos de silencio. Desactívalo para dictar palabras sueltas."
|
|
38
|
+
"settings.hallucination_filter_hint": "Descarta artefactos de silencio. Desactívalo para dictar palabras sueltas.",
|
|
39
|
+
|
|
40
|
+
"settings.threads_label": "Hilos",
|
|
41
|
+
"settings.threads_hint": "Configura numThreads en voice.json; vuelve a ejecutar /voice para aplicarlo."
|
|
39
42
|
}
|
package/locales/fr.json
CHANGED
|
@@ -35,5 +35,8 @@
|
|
|
35
35
|
"settings.language_value_auto": "Détection automatique",
|
|
36
36
|
"settings.language_hint": "Exécutez /languages pour changer.",
|
|
37
37
|
"settings.hallucination_filter_label": "Filtrer le bruit de Whisper",
|
|
38
|
-
"settings.hallucination_filter_hint": "Supprime les artefacts des silences. À désactiver pour dicter un seul mot."
|
|
38
|
+
"settings.hallucination_filter_hint": "Supprime les artefacts des silences. À désactiver pour dicter un seul mot.",
|
|
39
|
+
|
|
40
|
+
"settings.threads_label": "Threads",
|
|
41
|
+
"settings.threads_hint": "Définissez numThreads dans voice.json ; relancez /voice pour l'appliquer."
|
|
39
42
|
}
|
package/locales/pt-BR.json
CHANGED
|
@@ -35,5 +35,8 @@
|
|
|
35
35
|
"settings.language_value_auto": "Detecção automática",
|
|
36
36
|
"settings.language_hint": "Execute /languages para mudar.",
|
|
37
37
|
"settings.hallucination_filter_label": "Filtrar ruído do Whisper",
|
|
38
|
-
"settings.hallucination_filter_hint": "Descarta artefatos de silêncio. Desligue ao ditar palavras isoladas."
|
|
38
|
+
"settings.hallucination_filter_hint": "Descarta artefatos de silêncio. Desligue ao ditar palavras isoladas.",
|
|
39
|
+
|
|
40
|
+
"settings.threads_label": "Threads",
|
|
41
|
+
"settings.threads_hint": "Configure numThreads em voice.json; execute /voice novamente para aplicar."
|
|
39
42
|
}
|
package/locales/pt.json
CHANGED
|
@@ -35,5 +35,8 @@
|
|
|
35
35
|
"settings.language_value_auto": "Deteção automática",
|
|
36
36
|
"settings.language_hint": "Executa /languages para mudar.",
|
|
37
37
|
"settings.hallucination_filter_label": "Filtrar ruído do Whisper",
|
|
38
|
-
"settings.hallucination_filter_hint": "Descarta artefactos de silêncio. Desliga ao ditar palavras isoladas."
|
|
38
|
+
"settings.hallucination_filter_hint": "Descarta artefactos de silêncio. Desliga ao ditar palavras isoladas.",
|
|
39
|
+
|
|
40
|
+
"settings.threads_label": "Threads",
|
|
41
|
+
"settings.threads_hint": "Define numThreads em voice.json; volta a executar /voice para aplicar."
|
|
39
42
|
}
|
package/locales/ru.json
CHANGED
|
@@ -35,5 +35,8 @@
|
|
|
35
35
|
"settings.language_value_auto": "Автоопределение",
|
|
36
36
|
"settings.language_hint": "Используйте /languages для смены.",
|
|
37
37
|
"settings.hallucination_filter_label": "Фильтр шумов Whisper",
|
|
38
|
-
"settings.hallucination_filter_hint": "Убирает артефакты тишины. Выключите для диктовки одного слова."
|
|
38
|
+
"settings.hallucination_filter_hint": "Убирает артефакты тишины. Выключите для диктовки одного слова.",
|
|
39
|
+
|
|
40
|
+
"settings.threads_label": "Потоки",
|
|
41
|
+
"settings.threads_hint": "Задайте numThreads в voice.json; перезапустите /voice, чтобы применить."
|
|
39
42
|
}
|
package/locales/uk.json
CHANGED
|
@@ -35,5 +35,8 @@
|
|
|
35
35
|
"settings.language_value_auto": "Автовизначення",
|
|
36
36
|
"settings.language_hint": "Використайте /languages, щоб змінити.",
|
|
37
37
|
"settings.hallucination_filter_label": "Фільтр шумів Whisper",
|
|
38
|
-
"settings.hallucination_filter_hint": "Прибирає артефакти тиші. Вимкніть для диктування одного слова."
|
|
38
|
+
"settings.hallucination_filter_hint": "Прибирає артефакти тиші. Вимкніть для диктування одного слова.",
|
|
39
|
+
|
|
40
|
+
"settings.threads_label": "Потоки",
|
|
41
|
+
"settings.threads_hint": "Задайте numThreads у voice.json; перезапустіть /voice, щоб застосувати."
|
|
39
42
|
}
|
package/locales/zh.json
CHANGED
|
@@ -43,5 +43,8 @@
|
|
|
43
43
|
"settings.hallucination_filter_hint": "丢弃静音段伪影。单词语音转写时可关闭。",
|
|
44
44
|
|
|
45
45
|
"settings.equalizer_label": "均衡器",
|
|
46
|
-
"settings.equalizer_hint": "在转录文本下方显示实时音频波形。默认关闭。"
|
|
46
|
+
"settings.equalizer_hint": "在转录文本下方显示实时音频波形。默认关闭。",
|
|
47
|
+
|
|
48
|
+
"settings.threads_label": "线程",
|
|
49
|
+
"settings.threads_hint": "在 voice.json 中设置 numThreads;重新运行 /voice 后生效。"
|
|
47
50
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juicesharp/rpiv-voice",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.10.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Pi extension. Voice dictation via /voice — local on-device STT with sherpa-onnx Whisper (base multilingual int8), microphone capture via decibri.",
|
|
6
6
|
"keywords": [
|
|
@@ -83,7 +83,7 @@
|
|
|
83
83
|
]
|
|
84
84
|
},
|
|
85
85
|
"dependencies": {
|
|
86
|
-
"@juicesharp/rpiv-config": "^2.
|
|
86
|
+
"@juicesharp/rpiv-config": "^2.10.1",
|
|
87
87
|
"sherpa-onnx-node": "^1.13.0",
|
|
88
88
|
"decibri": "^3.4.0"
|
|
89
89
|
},
|
|
@@ -110,3 +110,13 @@ export const selectLanguageReadonlyFieldProps: GlobalSelector<SettingsFieldViewP
|
|
|
110
110
|
hint: t("settings.language_hint", "Run /languages to change."),
|
|
111
111
|
};
|
|
112
112
|
};
|
|
113
|
+
|
|
114
|
+
// Decode threads are session-baked (VoiceState.numThreads) — display-only.
|
|
115
|
+
// The value is the raw count as a string; the hint points at voice.json
|
|
116
|
+
// because the settings screen cannot edit the key (JSON-only, restart-to-apply).
|
|
117
|
+
export const selectNumThreadsReadonlyFieldProps: GlobalSelector<SettingsFieldViewProps> = (state, _ctx) => ({
|
|
118
|
+
label: t("settings.threads_label", "Threads"),
|
|
119
|
+
active: false,
|
|
120
|
+
field: { kind: "readonly", value: String(state.numThreads) },
|
|
121
|
+
hint: t("settings.threads_hint", "Set numThreads in voice.json; re-run /voice to apply."),
|
|
122
|
+
});
|
package/state/state-reducer.ts
CHANGED
|
@@ -5,7 +5,13 @@ import { SETTINGS_FIELD_ORDER, type SettingsDraft, type SettingsFieldKey, type V
|
|
|
5
5
|
import { STATUS_META } from "./status-intent.js";
|
|
6
6
|
|
|
7
7
|
export interface ApplyContext {
|
|
8
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Fresh read of voice.json. Save handlers call it AT SAVE TIME so
|
|
10
|
+
* pass-through keys round-trip from the file as it is now — a mid-session
|
|
11
|
+
* hand edit of a JSON-only key (numThreads) must survive a settings save,
|
|
12
|
+
* not get reverted from the session-start snapshot.
|
|
13
|
+
*/
|
|
14
|
+
readPersistedConfig: () => VoiceConfig;
|
|
9
15
|
}
|
|
10
16
|
|
|
11
17
|
export type Effect =
|
|
@@ -103,9 +109,12 @@ const openSettings: Handler<"open_settings"> = (state, _action, _ctx) => ({
|
|
|
103
109
|
// Leaving the settings screen silently persists the draft. Ctrl-S remains the
|
|
104
110
|
// explicit save path (with a confirmation notify); this just makes the common
|
|
105
111
|
// "toggle then Esc/Tab" flow not lose changes.
|
|
106
|
-
const closeSettings: Handler<"close_settings"> = (state, _action,
|
|
112
|
+
const closeSettings: Handler<"close_settings"> = (state, _action, ctx) => ({
|
|
107
113
|
state: { ...state, currentScreen: "dictation" },
|
|
108
|
-
effects: [
|
|
114
|
+
effects: [
|
|
115
|
+
{ kind: "save_config", config: configFromDraft(state.settingsDraft, ctx.readPersistedConfig()) },
|
|
116
|
+
{ kind: "request_render" },
|
|
117
|
+
],
|
|
109
118
|
});
|
|
110
119
|
|
|
111
120
|
const toggleFocusedSetting: Handler<"toggle_focused_setting"> = (state, _action, _ctx) => {
|
|
@@ -150,8 +159,8 @@ function stepFocus(current: SettingsFieldKey, delta: 1 | -1): SettingsFieldKey {
|
|
|
150
159
|
// succeeds. A plain two-effect list ran both notifies unconditionally on
|
|
151
160
|
// failure because `return` inside runEffect()'s switch case exits the method,
|
|
152
161
|
// not the outer effect loop — review I1 caught this.
|
|
153
|
-
const settingsSave: Handler<"settings_save"> = (state, _action,
|
|
154
|
-
const config = configFromDraft(state.settingsDraft);
|
|
162
|
+
const settingsSave: Handler<"settings_save"> = (state, _action, ctx) => {
|
|
163
|
+
const config = configFromDraft(state.settingsDraft, ctx.readPersistedConfig());
|
|
155
164
|
return {
|
|
156
165
|
state,
|
|
157
166
|
effects: [
|
|
@@ -187,8 +196,25 @@ export function reduce(state: VoiceState, action: VoiceAction, ctx: ApplyContext
|
|
|
187
196
|
return handler(state, action as never, ctx);
|
|
188
197
|
}
|
|
189
198
|
|
|
190
|
-
|
|
191
|
-
|
|
199
|
+
// Keys whose value the settings screen re-derives from the draft on every
|
|
200
|
+
// save — the draft is authoritative for these, so any persisted value is
|
|
201
|
+
// replaced by the draft-derived one (or dropped at default). Every other
|
|
202
|
+
// persisted key (numThreads, language, and any future JSON-only key) is
|
|
203
|
+
// pass-through: a settings save must never drop config the screen cannot edit.
|
|
204
|
+
export const DRAFT_OWNED_CONFIG_KEYS: ReadonlySet<string> = new Set(["hallucinationFilterEnabled", "equalizerEnabled"]);
|
|
205
|
+
|
|
206
|
+
export function configFromDraft(draft: SettingsDraft, persisted: VoiceConfig): VoiceConfig {
|
|
207
|
+
// Widened accumulator: pass-through keys may fall outside VoiceConfig's
|
|
208
|
+
// known shape (a hand-edited voice.json), so writes go through a string
|
|
209
|
+
// index signature on top of the mapped known keys.
|
|
210
|
+
const out: { -readonly [K in keyof VoiceConfig]: VoiceConfig[K] } & Record<string, unknown> = {};
|
|
211
|
+
for (const [key, value] of Object.entries(persisted)) {
|
|
212
|
+
// `__proto__` is skipped: a computed assignment on a plain accumulator
|
|
213
|
+
// would invoke Object.prototype's setter — replacing the prototype —
|
|
214
|
+
// instead of round-tripping the key as an own property.
|
|
215
|
+
if (key === "__proto__" || DRAFT_OWNED_CONFIG_KEYS.has(key)) continue;
|
|
216
|
+
out[key] = value;
|
|
217
|
+
}
|
|
192
218
|
// Only persist the non-default state. Hallucination filter defaults ON, so
|
|
193
219
|
// only the off-state lands on disk; equalizer defaults OFF, so only the
|
|
194
220
|
// on-state does. Both rules keep voice.json minimal and forward-compatible.
|
package/state/state.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { DEFAULT_NUM_THREADS } from "../config/voice-config.js";
|
|
2
|
+
|
|
1
3
|
export type RecordingStatus = "recording" | "paused";
|
|
2
4
|
export type ScreenKind = "dictation" | "settings";
|
|
3
5
|
|
|
@@ -27,6 +29,10 @@ export interface VoiceState {
|
|
|
27
29
|
/** Which interactive settings field is currently focused. Up/Down arrows
|
|
28
30
|
* cycle through `SETTINGS_FIELD_ORDER`; Enter toggles the focused one. */
|
|
29
31
|
settingsFocus: SettingsFieldKey;
|
|
32
|
+
/** Decode thread count baked in when the session started — display-only
|
|
33
|
+
* (the settings Threads row). The running recognizer keeps the count it
|
|
34
|
+
* was constructed with; changes apply on the next `/voice` run. */
|
|
35
|
+
numThreads: number;
|
|
30
36
|
}
|
|
31
37
|
|
|
32
38
|
export const SETTINGS_FIELD_ORDER: readonly SettingsFieldKey[] = ["hallucination", "equalizer"];
|
|
@@ -35,7 +41,7 @@ export interface VoiceRuntime {
|
|
|
35
41
|
keybindings: { matches(data: string, name: string): boolean };
|
|
36
42
|
}
|
|
37
43
|
|
|
38
|
-
export function initialVoiceState(draft: SettingsDraft): VoiceState {
|
|
44
|
+
export function initialVoiceState(draft: SettingsDraft, numThreads = DEFAULT_NUM_THREADS): VoiceState {
|
|
39
45
|
return {
|
|
40
46
|
currentScreen: "dictation",
|
|
41
47
|
status: "recording",
|
|
@@ -44,5 +50,6 @@ export function initialVoiceState(draft: SettingsDraft): VoiceState {
|
|
|
44
50
|
audioLevel: 0,
|
|
45
51
|
settingsDraft: draft,
|
|
46
52
|
settingsFocus: SETTINGS_FIELD_ORDER[0]!,
|
|
53
|
+
numThreads,
|
|
47
54
|
};
|
|
48
55
|
}
|
package/state/voice-session.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { DynamicBorder, type Theme } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { getKeybindings } from "@earendil-works/pi-tui";
|
|
3
3
|
import type { VoiceConfig } from "../config/voice-config.js";
|
|
4
|
-
import { saveVoiceConfig } from "../config/voice-config.js";
|
|
4
|
+
import { loadVoiceConfig, resolveNumThreads, saveVoiceConfig } from "../config/voice-config.js";
|
|
5
5
|
import { globalBinding } from "../view/component-binding.js";
|
|
6
6
|
import { EqualizerView } from "../view/components/equalizer-view.js";
|
|
7
7
|
import { SettingsFieldView } from "../view/components/settings-field-view.js";
|
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
selectHallucinationFilterFieldProps,
|
|
20
20
|
selectLanguageReadonlyFieldProps,
|
|
21
21
|
selectMicReadonlyFieldProps,
|
|
22
|
+
selectNumThreadsReadonlyFieldProps,
|
|
22
23
|
selectStatusBarProps,
|
|
23
24
|
selectTranscriptProps,
|
|
24
25
|
} from "./selectors/projections.js";
|
|
@@ -50,7 +51,6 @@ export interface VoiceSessionComponent {
|
|
|
50
51
|
|
|
51
52
|
export class VoiceSession {
|
|
52
53
|
private state: VoiceState;
|
|
53
|
-
private readonly persistedConfig: VoiceConfig;
|
|
54
54
|
private readonly adapter: VoiceOverlayPropsAdapter;
|
|
55
55
|
private readonly overlay: OverlayView;
|
|
56
56
|
private readonly tui: VoiceSessionConfig["tui"];
|
|
@@ -64,8 +64,10 @@ export class VoiceSession {
|
|
|
64
64
|
this.tui = config.tui;
|
|
65
65
|
this.deps = config.deps;
|
|
66
66
|
this.done = config.done;
|
|
67
|
-
this.
|
|
68
|
-
|
|
67
|
+
this.state = initialVoiceState(
|
|
68
|
+
draftFromConfig(config.persistedConfig),
|
|
69
|
+
resolveNumThreads(config.persistedConfig),
|
|
70
|
+
);
|
|
69
71
|
|
|
70
72
|
const transcript = new TranscriptView(config.theme);
|
|
71
73
|
const divider = new DynamicBorder((s) => config.theme.fg("accent", s));
|
|
@@ -76,8 +78,9 @@ export class VoiceSession {
|
|
|
76
78
|
const languageField = new SettingsFieldView(config.theme);
|
|
77
79
|
const hallucinationField = new SettingsFieldView(config.theme);
|
|
78
80
|
const equalizerField = new SettingsFieldView(config.theme);
|
|
81
|
+
const numThreadsField = new SettingsFieldView(config.theme);
|
|
79
82
|
const settingsForm = new SettingsFormView({
|
|
80
|
-
fields: [micField, languageField, hallucinationField, equalizerField],
|
|
83
|
+
fields: [micField, languageField, hallucinationField, equalizerField, numThreadsField],
|
|
81
84
|
});
|
|
82
85
|
|
|
83
86
|
const dictation = new DictationScreenStrategy({ transcript, divider, equalizer, statusBar });
|
|
@@ -99,6 +102,7 @@ export class VoiceSession {
|
|
|
99
102
|
globalBinding({ component: languageField, select: selectLanguageReadonlyFieldProps }),
|
|
100
103
|
globalBinding({ component: hallucinationField, select: selectHallucinationFilterFieldProps }),
|
|
101
104
|
globalBinding({ component: equalizerField, select: selectEqualizerFieldProps }),
|
|
105
|
+
globalBinding({ component: numThreadsField, select: selectNumThreadsReadonlyFieldProps }),
|
|
102
106
|
globalBinding({ component: this.overlay, select: (state) => ({ state }) }),
|
|
103
107
|
];
|
|
104
108
|
|
|
@@ -185,6 +189,11 @@ export class VoiceSession {
|
|
|
185
189
|
}
|
|
186
190
|
|
|
187
191
|
private applyContext(): ApplyContext {
|
|
188
|
-
|
|
192
|
+
// A re-reader, not the constructor snapshot: save handlers must merge
|
|
193
|
+
// the draft against voice.json as it is at save time, so a mid-session
|
|
194
|
+
// hand edit of a JSON-only key round-trips instead of being reverted.
|
|
195
|
+
// Only the save handlers invoke it, so the hot dispatch path (one
|
|
196
|
+
// audio_chunk per mic frame) never touches disk.
|
|
197
|
+
return { readPersistedConfig: loadVoiceConfig };
|
|
189
198
|
}
|
|
190
199
|
}
|