Run Whisper in a worker thread; shorten polling

The speech model now lives in a worker thread (whisperWorker.mjs), so
loading and transcribing no longer block the bridge's HTTP server or its
Hermes polling. Measured longest event-loop pause during transcription:
387 ms before, 3 ms after. A dead worker is replaced on the next request;
closing the bridge terminates it.

Polling: bridge to Hermes every 150 ms (was 500). The app polls the bridge
every 200 ms for the first 8 s of a turn, 400 ms until 30 s, then 1 s
(was a fixed 700 ms).

Tests: 131 unit/integration, 7 real-speech, 9 real-Hermes, 6 simulator,
all passing. Effect on a phone or a droplet is not measured.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Dan
2026-11-18 18:39:28 -08:00
co-authored by Claude Fable 5.2
parent 6d74f9e121
commit 0c9dcd864f
14 changed files with 212 additions and 31 deletions
+66 -13
View File
@@ -1,10 +1,14 @@
import { Worker } from 'node:worker_threads';
import { AUDIO_FORMAT } from '@hermeven/contracts';
import { SttError, type SttAdapter, type TranscribeRequest } from './adapter.ts';
/**
* Built-in speech-to-text: OpenAI's Whisper model run inside the bridge process
* on the CPU (ONNX Runtime via @huggingface/transformers). No audio leaves the
* bridge host and no provider account is needed.
* Built-in speech-to-text: OpenAI's Whisper model run on the bridge host's CPU
* (ONNX Runtime via @huggingface/transformers). No audio leaves the bridge host
* and no provider account is needed.
*
* The model lives in a worker thread (whisperWorker.mjs), so loading it and
* transcribing never block the bridge's HTTP server or its Hermes polling.
*
* The model files are downloaded from the Hugging Face hub the first time the
* bridge starts and are then read from `cacheDir`.
@@ -15,7 +19,7 @@ export interface BuiltinWhisperOptions {
/** Weight precision. `q8` is the small, CPU-friendly default. */
dtype: string;
cacheDir: string;
/** Test seam: replaces the model loader. */
/** Test seam: replaces the worker thread with an in-process recogniser. */
load?: () => Promise<Recognizer>;
}
@@ -52,6 +56,8 @@ export function cleanTranscript(text: string): string {
export class BuiltinWhisperStt implements SttAdapter {
readonly configured = true;
private recognizer: Promise<Recognizer> | null = null;
private worker: Worker | null = null;
private closed = false;
/** One transcription at a time: the model is CPU-bound and this is a single-user bridge. */
private queue: Promise<unknown> = Promise.resolve();
@@ -64,7 +70,7 @@ export class BuiltinWhisperStt implements SttAdapter {
private load(): Promise<Recognizer> {
if (!this.recognizer) {
const loading = (this.opts.load ?? (() => this.loadModel()))();
const loading = (this.opts.load ?? (() => this.startWorker()))();
this.recognizer = loading;
// A failed load (no network on first start) must be retried on the next request.
loading.catch(() => {
@@ -74,13 +80,60 @@ export class BuiltinWhisperStt implements SttAdapter {
return this.recognizer;
}
private async loadModel(): Promise<Recognizer> {
const { pipeline } = await import('@huggingface/transformers');
const asr = await pipeline('automatic-speech-recognition', this.opts.model, {
dtype: this.opts.dtype as never,
cache_dir: this.opts.cacheDir,
/** Start the worker, load the model in it, and return a function that runs one clip there. */
private startWorker(): Promise<Recognizer> {
return new Promise<Recognizer>((resolve, reject) => {
if (this.closed) return reject(new Error('closed'));
const worker = new Worker(new URL('./whisperWorker.mjs', import.meta.url));
this.worker = worker;
// The model must never keep a stopping bridge alive.
worker.unref();
const waiting = new Map<number, { resolve: (text: string) => void; reject: (err: Error) => void }>();
let nextId = 1;
let loaded = false;
const fail = (reason: string) => {
// Worker died or was terminated: forget it so the next request starts a fresh one.
if (this.worker === worker) this.worker = null;
if (this.recognizer && loaded) this.recognizer = null;
for (const pending of waiting.values()) pending.reject(new Error(reason));
waiting.clear();
if (!loaded) reject(new Error(reason));
};
worker.on('error', () => fail('worker error'));
worker.on('exit', () => fail('worker exited'));
worker.on('message', (message: { type: string; id?: number; text?: string }) => {
if (message.type === 'loaded') {
loaded = true;
resolve(
(audio, options) =>
new Promise((res, rej) => {
const id = nextId++;
waiting.set(id, { resolve: (text) => res({ text }), reject: rej });
// Transfer, not copy: the samples are not needed on this side again.
worker.postMessage({ type: 'run', id, samples: audio, options }, [audio.buffer as ArrayBuffer]);
}),
);
} else if (message.type === 'load_failed') {
void worker.terminate();
} else if (message.id !== undefined) {
const pending = waiting.get(message.id);
waiting.delete(message.id);
if (message.type === 'result') pending?.resolve(message.text ?? '');
else pending?.reject(new Error('recognition failed'));
}
});
worker.postMessage({ type: 'load', model: this.opts.model, dtype: this.opts.dtype, cacheDir: this.opts.cacheDir });
});
return asr as unknown as Recognizer;
}
/** Stop the worker thread and free the model. Safe to call more than once. */
async close(): Promise<void> {
this.closed = true;
const worker = this.worker;
this.worker = null;
this.recognizer = null;
if (worker) await worker.terminate();
}
async transcribe(request: TranscribeRequest): Promise<string> {
@@ -110,8 +163,8 @@ export class BuiltinWhisperStt implements SttAdapter {
});
this.queue = run.catch(() => undefined);
// Inference cannot be interrupted. On cancel or deadline the caller stops waiting; the
// result is discarded when it arrives and the queue keeps later requests in order.
// A clip already in the model is left to finish. On cancel or deadline the caller stops
// waiting; the result is discarded when it arrives and the queue keeps later requests in order.
return new Promise<string>((resolve, reject) => {
const onAbort = () => reject(new DOMException('Aborted', 'AbortError'));
if (request.signal.aborted) return onAbort();