Files
hermeven/services/bridge/test/builtinWhisper.test.ts
T
DanandClaude Fable 5.2 e1c02d5266 Address Cody review round 2: all ten findings (CODY-001 to CODY-010)
CODY-001 Bridge URL must be HTTPS (HTTP only to loopback), in the client and
         in manifest generation.
CODY-002 Even host calls stay serialised until the SDK call really settles;
         a microphone start that completes after its timeout is followed by
         a stop.
CODY-003 Request id is stored before the first submit and cleared only on a
         definitive answer; lost replies are treated as ambiguous and
         reconciled under the same id; HUD no longer claims "not sent".
CODY-004 Revoking a device cancels its in-flight turns, aborts
         transcription and asks Hermes to stop, from HTTP and CLI paths.
CODY-005 Speech model pinned to a commit with per-file SHA-256; fetched and
         verified ahead of time; verified on every load; never downloaded
         at run time; no unpinned configuration.
CODY-006 State directory 0700, database/WAL/SHM 0600 regardless of umask.
CODY-007 credential_expired handled like unauthorized on every path.
CODY-008 Approval wait start and paused agent deadline persisted and
         restored across restarts (schema v2).
CODY-009 Exactly one conversation create per epoch, sent in sequence, with
         stale results dropped before persistence.
CODY-010 Wrong pairing guesses no longer consume the outstanding code;
         failures are indistinguishable.

Checks: typecheck clean; npm test 182 passed; client build ok;
test:real-stt 11 passed (including with no network); test:real-hermes 9
passed; test:simulator 6 passed; git diff --check clean.

Not reviewed. No physical-device, droplet or production evidence.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 19:49:14 -08:00

125 lines
5.5 KiB
TypeScript

import { describe, expect, it } from 'vitest';
import { SttError } from '../src/stt/adapter.ts';
import { BuiltinWhisperStt, cleanTranscript, pcmToFloat32, rms, SILENCE_RMS, type Recognizer } from '../src/stt/builtinWhisper.ts';
/** These use a stand-in recogniser. The real model is exercised by `npm run test:real-stt`. */
function tone(seconds: number, amplitude = 8000): Buffer {
const buf = Buffer.alloc(Math.floor(seconds * 16000) * 2);
for (let i = 0; i < buf.length / 2; i++) buf.writeInt16LE(Math.round(Math.sin(i / 5) * amplitude), i * 2);
return buf;
}
const never = new AbortController().signal;
const manifestFor = (model: string) => ({ name: 'test', model, revision: 'a'.repeat(40), dtype: 'q8', files: [] });
function make(recognizer: Recognizer, model = 'onnx-community/whisper-base') {
let loads = 0;
const calls: Array<{ samples: number; options: Record<string, unknown> }> = [];
const stt = new BuiltinWhisperStt({
manifest: manifestFor(model),
modelDir: '/nonexistent',
load: async () => {
loads += 1;
return async (audio, options) => {
calls.push({ samples: audio.length, options });
return recognizer(audio, options);
};
},
});
return { stt, calls, loads: () => loads };
}
describe('built-in Whisper adapter', () => {
it('converts PCM to normalised floats', () => {
const buf = Buffer.alloc(6);
buf.writeInt16LE(32767, 0);
buf.writeInt16LE(-32768, 2);
buf.writeInt16LE(0, 4);
const f = pcmToFloat32(buf);
expect(f[0]).toBeCloseTo(1, 3);
expect(f[1]).toBe(-1);
expect(f[2]).toBe(0);
expect(rms(pcmToFloat32(tone(1)))).toBeGreaterThan(SILENCE_RMS * 50);
});
it('never loads or runs the model for silence or for a clip too short to hold a word', async () => {
const { stt, calls, loads } = make(async () => ({ text: 'Thank you.' }));
expect(await stt.transcribe({ pcm: Buffer.alloc(32000), locale: 'en-US', signal: never })).toBe('');
expect(await stt.transcribe({ pcm: tone(1, 20), locale: 'en-US', signal: never })).toBe('');
expect(await stt.transcribe({ pcm: tone(0.05), locale: 'en-US', signal: never })).toBe('');
expect(calls).toHaveLength(0);
expect(loads()).toBe(0);
});
it('passes the device language to a multilingual model and nothing to an English-only one', async () => {
const multi = make(async () => ({ text: ' Bonjour. ' }));
expect(await multi.stt.transcribe({ pcm: tone(1), locale: 'fr-CA', signal: never })).toBe('Bonjour.');
expect(multi.calls[0]).toEqual({ samples: 16000, options: { language: 'fr', task: 'transcribe' } });
const en = make(async () => ({ text: 'Hello.' }), 'onnx-community/whisper-base.en');
await en.stt.transcribe({ pcm: tone(1), locale: 'fr-CA', signal: never });
expect(en.calls[0]!.options).toEqual({});
});
it('strips non-speech tags, so a clip of only noise tags is empty', () => {
expect(cleanTranscript(' [BLANK_AUDIO] ')).toBe('');
expect(cleanTranscript('(wind blowing) Hello there [MUSIC]')).toBe('Hello there');
});
it('runs one transcription at a time, in order', async () => {
let running = 0;
let peak = 0;
const { stt } = make(async (audio) => {
running += 1;
peak = Math.max(peak, running);
await new Promise((r) => setTimeout(r, 30));
running -= 1;
return { text: `len ${audio.length}` };
});
const results = await Promise.all([1, 2, 3].map((s) => stt.transcribe({ pcm: tone(s), locale: 'en-US', signal: never })));
expect(results).toEqual(['len 16000', 'len 32000', 'len 48000']);
expect(peak).toBe(1);
});
it('a cancelled request stops waiting at once and does not block the next one', async () => {
const { stt } = make(async () => {
await new Promise((r) => setTimeout(r, 150));
return { text: 'slow' };
});
const abort = new AbortController();
const first = stt.transcribe({ pcm: tone(1), locale: 'en-US', signal: abort.signal });
setTimeout(() => abort.abort(), 20);
const started = Date.now();
await expect(first).rejects.toMatchObject({ name: 'AbortError' });
expect(Date.now() - started).toBeLessThan(120);
expect(await stt.transcribe({ pcm: tone(1), locale: 'en-US', signal: never })).toBe('slow');
const already = new AbortController();
already.abort();
await expect(stt.transcribe({ pcm: tone(1), locale: 'en-US', signal: already.signal })).rejects.toMatchObject({ name: 'AbortError' });
});
it('a model that fails to load is "unavailable" and is retried next time', async () => {
let attempts = 0;
const stt = new BuiltinWhisperStt({
manifest: manifestFor('onnx-community/whisper-base'),
modelDir: '/nonexistent',
load: async () => {
attempts += 1;
if (attempts === 1) throw new Error('no network');
return async () => ({ text: 'recovered' });
},
});
await expect(stt.transcribe({ pcm: tone(1), locale: 'en-US', signal: never })).rejects.toMatchObject({ kind: 'unavailable' });
await new Promise((r) => setTimeout(r, 5));
expect(await stt.transcribe({ pcm: tone(1), locale: 'en-US', signal: never })).toBe('recovered');
expect(attempts).toBe(2);
});
it('a model that throws on a recording is "failed", not a crash', async () => {
const { stt } = make(async () => {
throw new Error('bad tensor');
});
const err = await stt.transcribe({ pcm: tone(1), locale: 'en-US', signal: never }).catch((e) => e);
expect(err).toBeInstanceOf(SttError);
expect(err.kind).toBe('failed');
});
});