Files
hermeven/tests/real-stt/realStt.test.ts
T
DanandClaude Fable 5.2 0c9dcd864f 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>
2026-11-18 18:39:28 -08:00

138 lines
6.4 KiB
TypeScript

import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { BuiltinWhisperStt } from '../../services/bridge/src/stt/builtinWhisper.ts';
import { createHarness, type Harness } from '../integration/harness.ts';
/**
* REAL SPEECH-TO-TEXT. The bridge's built-in Whisper model, really loaded and really run on
* this machine's CPU, transcribing a real human speech recording that is uploaded through the
* bridge's HTTP API exactly as the glasses app uploads a capture.
*
* Still fake: Hermes (tests/fakes/fakeHermes.ts) and the glasses. The recording is a clean
* archive clip, not audio from a G2 microphone.
*/
const here = dirname(fileURLToPath(import.meta.url));
const speech = readFileSync(resolve(here, 'fixtures/jfk.wav')).subarray(44); // strip the WAV header: raw PCM
let h: Harness;
let token: string;
let conversation: string;
beforeAll(async () => {
h = await createHarness({
stt: false,
env: {
STT_PROVIDER: 'builtin',
STT_CACHE_DIR: resolve(here, '.cache'),
HERMEVEN_CAPTURE_MAX_SECONDS: '30',
},
timing: { transcribeDeadlineMs: 120_000, agentDeadlineMs: 30_000 },
});
expect(h.bridge.stt).toBeInstanceOf(BuiltinWhisperStt);
const started = Date.now();
await (h.bridge.stt as BuiltinWhisperStt).warm();
console.info(`[real-stt] model ${h.config.stt.model} (${h.config.stt.dtype}) loaded in ${Date.now() - started} ms; rss ${Math.round(process.memoryUsage().rss / 1e6)} MB`);
token = (await h.pair()).token;
conversation = await h.conversation(token);
});
afterAll(async () => {
await h?.close();
});
describe('built-in Whisper speech-to-text', () => {
it('transcribes real speech uploaded as a capture and sends the words to the agent', async () => {
// Watch the event loop while the model runs: the bridge must stay responsive.
let worstLag = 0;
let last = performance.now();
const probe = setInterval(() => {
const now = performance.now();
worstLag = Math.max(worstLag, now - last - 20);
last = now;
}, 20);
const res = await h.audioTurn(token, conversation, Buffer.from(speech));
expect(res.status).toBe(202);
const health = await h.api('GET', '/healthz');
expect(health.status).toBe(200);
const done = await h.waitTerminal(token, res.body.request_id, 120_000);
clearInterval(probe);
console.info(
`[real-stt] ${(speech.length / 32000).toFixed(1)} s of speech transcribed in ${done.timings.transcribe_ms} ms; ` +
`worst event-loop stall ${Math.round(worstLag)} ms; rss ${Math.round(process.memoryUsage().rss / 1e6)} MB`,
);
console.info(`[real-stt] transcript: ${JSON.stringify(done.input_text)}`);
expect(done.outcome).toBe('succeeded');
const heard = (done.input_text ?? '').toLowerCase().replace(/[^a-z ]/g, '');
expect(heard).toContain('ask not what your country can do for you');
expect(heard).toContain('ask what you can do for your country');
// The agent received exactly the transcript.
expect(h.hermes.lastRun()!.input).toBe(done.input_text);
expect(h.hermes.executions).toBe(1);
});
it('a silent capture is reported as "no speech" and never reaches the agent', async () => {
const before = h.hermes.executions;
const res = await h.audioTurn(token, conversation, Buffer.alloc(3 * 32000));
const done = await h.waitTerminal(token, res.body.request_id, 60_000);
expect(done.outcome).toBe('failed');
expect(done.error?.code).toBe('stt_empty');
expect(h.hermes.executions).toBe(before);
});
it('a very quiet room-noise capture is also treated as no speech', async () => {
const noise = Buffer.alloc(3 * 32000);
for (let i = 0; i < noise.length / 2; i++) noise.writeInt16LE(Math.round((Math.random() - 0.5) * 40), i * 2);
const res = await h.audioTurn(token, conversation, noise);
const done = await h.waitTerminal(token, res.body.request_id, 60_000);
expect(done.error?.code).toBe('stt_empty');
});
it('two recordings submitted together are both transcribed, one after the other', async () => {
const other = await h.pair('second-device');
const otherConversation = await h.conversation(other.token);
const [a, b] = await Promise.all([
h.audioTurn(token, conversation, Buffer.from(speech)),
h.audioTurn(other.token, otherConversation, Buffer.from(speech)),
]);
const [doneA, doneB] = await Promise.all([
h.waitTerminal(token, a.body.request_id, 120_000),
h.waitTerminal(other.token, b.body.request_id, 120_000),
]);
expect(doneA.input_text).toContain('fellow Americans');
expect(doneB.input_text).toContain('fellow Americans');
});
it('a model that cannot be loaded makes speech "unavailable" without taking the bridge down', async () => {
const broken = new BuiltinWhisperStt({ model: 'hermeven-test/does-not-exist', dtype: 'q8', cacheDir: resolve(here, '.cache') });
try {
const err = await broken
.transcribe({ pcm: Buffer.from(speech.subarray(0, 32000)), locale: 'en-US', signal: new AbortController().signal })
.catch((e) => e);
expect(err).toMatchObject({ name: 'SttError', kind: 'unavailable' });
} finally {
await broken.close();
}
expect((await h.api('GET', '/healthz')).status).toBe(200);
});
it('closing the adapter stops its worker thread, and a closed adapter refuses further work', async () => {
const stt = new BuiltinWhisperStt({ model: h.config.stt.model, dtype: h.config.stt.dtype, cacheDir: resolve(here, '.cache') });
const signal = new AbortController().signal;
expect(await stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).toContain('fellow Americans');
await stt.close();
await stt.close();
await expect(stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).rejects.toMatchObject({ kind: 'unavailable' });
});
it('a second recording is transcribed with the model already warm', async () => {
const res = await h.audioTurn(token, conversation, Buffer.from(speech.subarray(0, 6 * 32000)));
const done = await h.waitTerminal(token, res.body.request_id, 120_000);
console.info(`[real-stt] warm: 6.0 s of speech in ${done.timings.transcribe_ms} ms -> ${JSON.stringify(done.input_text)}`);
expect(done.outcome).toBe('succeeded');
expect((done.input_text ?? '').toLowerCase()).toContain('fellow americans');
});
});