// Tests for the speech capability, in process: no network, no whisper, no piper. import { test } from 'node:test'; import assert from 'node:assert/strict'; import { Speech, MAX_CLIP_BYTES, MAX_SPEAK_CHARS } from './speech.js'; const clip = new Uint8Array([82, 73, 70, 70]); // "RIFF" test('transcribe takes bytes, and not too many', async () => { const speech = new Speech(async (c) => `${c.length} bytes`); assert.equal(await speech.transcribe(clip), '4 bytes'); assert.throws(() => speech.transcribe('UklGRg=='), /must be bytes/); assert.throws(() => speech.transcribe(new Uint8Array(MAX_CLIP_BYTES + 1)), /over/); }); test('one clip at a time, and a failure does not stall the next', async () => { const log = []; let n = 0; const speech = new Speech(async () => { const i = ++n; log.push(`start ${i}`); await new Promise((r) => setTimeout(r, 10)); log.push(`end ${i}`); if (i === 1) throw new Error('whisper failed'); return `text ${i}`; }); const [a, b] = await Promise.allSettled([speech.transcribe(clip), speech.transcribe(clip)]); assert.equal(a.status, 'rejected'); assert.equal(b.value, 'text 2'); assert.deepEqual(log, ['start 1', 'end 1', 'start 2', 'end 2']); }); test('speak takes text, not too much, and shares the one-at-a-time turn', async () => { const log = []; const speech = new Speech( async () => { log.push('transcribe'); return 'hi'; }, async (text) => { log.push(`speak ${text}`); return new Uint8Array([82, 73, 70, 70]); }, ); const [heard, wav] = await Promise.all([speech.transcribe(clip), speech.speak('Hello.')]); assert.equal(heard, 'hi'); assert.deepEqual([...wav], [82, 73, 70, 70]); assert.deepEqual(log, ['transcribe', 'speak Hello.']); assert.throws(() => speech.speak(''), /needs text/); assert.throws(() => speech.speak('x'.repeat(MAX_SPEAK_CHARS + 1)), /over/); assert.throws(() => new Speech(async () => '').speak('hi'), /no voice/); });