import { measureTextWrap } from '@evenrealities/pretext'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { Controller, type Snapshot, type SpeakerPort } from '../../apps/even-client/src/core/controller.ts'; import { BridgeClient } from '../../apps/even-client/src/net/bridgeClient.ts'; import { loadConfig } from '../../services/bridge/src/config.ts'; import { speechText } from '../../services/bridge/src/tts.ts'; import { FakeDevice } from '../fakes/fakeDevice.ts'; import { FakeTts } from '../fakes/fakeTts.ts'; import { createHarness, type Harness } from './harness.ts'; /** * Answers read aloud. The bridge is real. Hermes, the speech provider, the glasses and the * loudspeaker are TEST FAKES: the "audio" is a few labelled bytes that no player could play. * This proves who is asked for what, when, and what is kept out of logs; it proves nothing * about ElevenLabs, about MP3 playback in the Even app, or about where sound is heard. */ const WENDY_KEY = 'wendy-profile-key-0123456789'; const CODY_KEY = 'cody-profile-key-0123456789'; let h: Harness; let tts: FakeTts; async function harness(extra: Record = {}, voices = true): Promise { tts = new FakeTts(); await tts.start(); h = await createHarness({ env: { HERMEVEN_AGENT_NAME: 'Pepper', HERMEVEN_AGENTS: 'wendy,cody', HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY, HERMEVEN_AGENT_CODY_API_KEY: CODY_KEY, ...(voices ? { HERMEVEN_ELEVENLABS_BASE_URL: tts.url, HERMEVEN_ELEVENLABS_API_KEY: tts.apiKey, HERMEVEN_AGENT_VOICE: 'voicePepper01', HERMEVEN_AGENT_WENDY_VOICE: 'voiceWendy02', } : {}), ...extra, }, }); h.hermes.profiles.set('wendy', WENDY_KEY); h.hermes.profiles.set('cody', CODY_KEY); } afterEach(async () => { await h?.close(); await tts?.stop(); }); async function answered(token: string, output: string, agentId?: string): Promise { const conversation = (await h.api('POST', '/v1/conversations', { token, json: { schema_version: 1, ...(agentId ? { agent_id: agentId } : {}) } })).body.conversation_id; h.hermes.next({ kind: 'complete', output }); const turn = await h.textTurn(token, conversation, 'a question'); const id = turn.body.request_id as string; await h.waitTerminal(token, id); return id; } async function speech(token: string | undefined, requestId: string): Promise<{ status: number; type: string | null; bytes: Buffer }> { const res = await fetch(`${h.url}/v1/turns/${requestId}/speech`, { headers: token ? { Authorization: `Bearer ${token}` } : {} }); return { status: res.status, type: res.headers.get('content-type'), bytes: Buffer.from(await res.arrayBuffer()) }; } describe('what is read aloud (speechText)', () => { it('drops markup, code and web addresses', () => { const { text, truncated } = speechText('## Plan\n\n- **First**, open [the page](https://example.com/a?b=c)\n- Then run:\n```sh\nrm -rf /tmp/x\n```\nSee https://example.com/long/path for more.', 900); expect(truncated).toBe(false); expect(text).toBe('Plan. First , open the page. Then run: See link for more.'); }); it('cuts at the end of a sentence within the limit, or at a word', () => { const long = 'One short sentence. Another sentence that goes on. ' + 'word '.repeat(100); const cut = speechText(long, 60); expect(cut.truncated).toBe(true); expect(cut.text).toBe('One short sentence. Another sentence that goes on.'); const noStop = speechText('word '.repeat(100), 22); expect(noStop.text).toBe('word word word word'); expect(speechText(' \n', 900)).toEqual({ text: '', truncated: false }); }); }); describe('bridge: configuration for speech', () => { const base = { HERMES_API_KEY: 'k'.repeat(16) }; it('is off without a key, and rejects ids that are not ids', () => { expect(loadConfig(base).tts.apiKey).toBe(''); expect(loadConfig(base).agents[0]!.voiceId).toBe(''); expect(() => loadConfig({ ...base, HERMEVEN_AGENT_VOICE: 'a voice/../x' })).toThrow(/HERMEVEN_AGENT_VOICE/); expect(() => loadConfig({ ...base, HERMEVEN_ELEVENLABS_MODEL: 'bad model' })).toThrow(/HERMEVEN_ELEVENLABS_MODEL/); expect(() => loadConfig({ ...base, HERMEVEN_ELEVENLABS_BASE_URL: 'http://example.com' })).toThrow(/https/); const on = loadConfig({ ...base, HERMEVEN_ELEVENLABS_API_KEY: 'x', HERMEVEN_AGENT_VOICE: 'abcDEF123' }); expect(on.tts).toMatchObject({ baseUrl: 'https://api.elevenlabs.io', model: 'eleven_flash_v2_5' }); expect(on.limits).toMatchObject({ speechMaxChars: 900, speechPerMinute: 6 }); }); }); describe('bridge: GET /v1/speech and /v1/turns/{id}/speech', () => { it('says which agents have a voice; nothing is offered without a key or without voices', async () => { await harness(); const { token } = await h.pair(); expect((await h.api('GET', '/v1/speech', { token })).body).toEqual({ schema_version: 1, available: true, agent_ids: ['default', 'wendy'], max_chars: 900 }); expect((await h.api('GET', '/v1/speech')).status).toBe(401); await h.close(); await tts.stop(); await harness({}, false); const second = await h.pair(); expect((await h.api('GET', '/v1/speech', { token: second.token })).body).toEqual({ schema_version: 1, available: false, agent_ids: [], max_chars: 0 }); const id = await answered(second.token, 'An answer.'); expect((await speech(second.token, id)).status).toBe(404); expect(tts.requests).toEqual([]); }); it('reads a finished answer in its agent\'s voice, once, and logs no word of it', async () => { await harness(); const { token } = await h.pair(); const secret = 'The safe combination is four one one one.'; const pepper = await answered(token, `**Sure.** ${secret}`); const wendy = await answered(token, 'Wendy speaking.', 'wendy'); const first = await speech(token, pepper); expect(first.status).toBe(200); expect(first.type).toBe('audio/mpeg'); expect(first.bytes.toString()).toBe(`FAKE-MP3:voicePepper01:${`Sure. ${secret}`.length}`); // Asked again (a retry, a second page): the provider is not paid twice. expect((await speech(token, pepper)).bytes.equals(first.bytes)).toBe(true); expect((await speech(token, wendy)).bytes.toString()).toMatch(/^FAKE-MP3:voiceWendy02:/); expect(tts.requests).toEqual([ { voiceId: 'voicePepper01', text: `Sure. ${secret}`, model: 'eleven_flash_v2_5', outputFormat: 'mp3_44100_64' }, { voiceId: 'voiceWendy02', text: 'Wendy speaking.', model: 'eleven_flash_v2_5', outputFormat: 'mp3_44100_64' }, ]); const logs = h.logs.join('\n'); for (const fragment of ['safe combination', 'four one one', 'Wendy speaking', tts.apiKey, 'FAKE-MP3']) expect(logs).not.toContain(fragment); const done = h.logs.filter((l) => l.includes('speech.done')).map((l) => JSON.parse(l)); expect(done.map((d) => [d.agent_id, d.chars, d.truncated])).toEqual([['default', `Sure. ${secret}`.length, false], ['wendy', 15, false]]); }); it('only for this device\'s own finished answers, and only for agents with a voice', async () => { await harness(); const mine = await h.pair('one'); const other = await h.pair('two'); const id = await answered(mine.token, 'Mine.'); expect((await speech(other.token, id)).status).toBe(404); expect((await speech(undefined, id)).status).toBe(401); expect((await speech(mine.token, 'not-a-uuid')).status).toBe(404); expect((await speech(mine.token, '0b7e1c5e-3f0a-4c56-9d3b-2f6a9f1c7e11')).status).toBe(404); // Cody has no voice. const cody = await answered(mine.token, 'Cody here.', 'cody'); expect((await speech(mine.token, cody)).status).toBe(404); // Still running: nothing to read yet. const conversation = (await h.api('POST', '/v1/conversations', { token: mine.token, json: { schema_version: 1 } })).body.conversation_id; h.hermes.next({ kind: 'complete', afterMs: 400, output: 'Late.' }); const running = (await h.textTurn(mine.token, conversation, 'slow one')).body.request_id as string; expect((await speech(mine.token, running)).status).toBe(404); await h.waitTerminal(mine.token, running); expect(tts.requests).toEqual([]); }); it('reads no more than the limit, and no more often than the budget', async () => { await harness({ HERMEVEN_SPEECH_MAX_CHARS: '60', HERMEVEN_SPEECH_PER_MINUTE: '2' }); const { token } = await h.pair(); const long = await answered(token, 'One short sentence. Another sentence that goes on. ' + 'word '.repeat(200)); expect((await speech(token, long)).status).toBe(200); expect(tts.requests[0]!.text).toBe('One short sentence. Another sentence that goes on.'); expect((await speech(token, await answered(token, 'Second.'))).status).toBe(200); const third = await answered(token, 'Third.'); expect((await speech(token, third)).status).toBe(429); // What was already made is still served; it costs nothing. expect((await speech(token, long)).status).toBe(200); expect(tts.requests).toHaveLength(2); expect(JSON.parse(h.logs.find((l) => l.includes('speech.done'))!)).toMatchObject({ chars: 50, truncated: true }); }); it('a provider failure is an error without the provider\'s words, and two requests at once make one call', async () => { await harness(); const { token } = await h.pair(); const id = await answered(token, 'Private answer text.'); tts.next({ status: 401 }); const failed = await fetch(`${h.url}/v1/turns/${id}/speech`, { headers: { Authorization: `Bearer ${token}` } }); expect(failed.status).toBe(500); expect(await failed.json()).toEqual({ schema_version: 1, error: { code: 'internal', message: 'Speech could not be generated.', retryable: false } }); expect(JSON.parse(h.logs.find((l) => l.includes('speech.failed'))!)).toMatchObject({ provider_status: 401, agent_id: 'default' }); expect(h.logs.join('\n')).not.toContain('Private answer'); tts.next({ delayMs: 120 }); const [a, b] = await Promise.all([speech(token, id), speech(token, id)]); expect([a.status, b.status]).toEqual([200, 200]); expect(tts.requests).toHaveLength(2); // the failed one and one shared one }); }); describe('bridge: shutting down after the app gave up on a request', () => { // Found while building speech: with Fastify's default, a connection whose client had gone // away before the handler finished was waited for at shutdown and never ended. for (const route of ['speech', 'transcribe'] as const) { it(`closes promptly after an abandoned ${route} request`, async () => { await harness(); const { token } = await h.pair(); const id = await answered(token, 'An answer.'); const gaveUp = new AbortController(); let pending: Promise; if (route === 'speech') { tts.next({ delayMs: 150 }); pending = fetch(`${h.url}/v1/turns/${id}/speech`, { headers: { Authorization: `Bearer ${token}` }, signal: gaveUp.signal }); } else { h.stt.next({ text: 'words', delayMs: 150 }); pending = fetch(`${h.url}/v1/transcribe?schema_version=1&locale=en-US&encoding=pcm_s16le&sample_rate=16000&channels=1`, { method: 'POST', body: new Uint8Array(32_000), headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/octet-stream' }, signal: gaveUp.signal, }); } await new Promise((r) => setTimeout(r, 50)); gaveUp.abort(); await pending.catch(() => undefined); // Let the handler finish against the connection that has gone. await new Promise((r) => setTimeout(r, 350)); const outcome = await Promise.race([h.bridge.close().then(() => 'closed'), new Promise((r) => setTimeout(() => r('still waiting'), 3000))]); expect(outcome).toBe('closed'); }); } }); // ---------------------------------------------------------------- the app class FakeSpeaker implements SpeakerPort { played: string[] = []; stops = 0; playing = false; fail = false; private finish: (() => void) | null = null; play(audio: Uint8Array): Promise { if (this.fail) return Promise.reject(new Error('sound is blocked (suspended)')); this.played.push(Buffer.from(audio).toString()); this.playing = true; return new Promise((resolve) => { this.finish = () => { this.playing = false; this.finish = null; resolve(); }; }); } stop(): void { this.stops += 1; this.finish?.(); } /** The audio reaches its end by itself. */ end(): void { this.finish?.(); } } let device: FakeDevice; let controller: Controller; let snapshot: Snapshot; let speaker: FakeSpeaker; let sent: string[]; function makeController(extras: Partial[0]> = {}): Controller { return new Controller({ wake: { armTimeoutMs: 250, watchMs: 40, stallMs: 150, retryMs: 120, pauseMs: 100 }, menu: true, idleExit: null, speaker, ...extras, device, measure: (text, width) => measureTextWrap(text, width).lineCount, locale: 'en-US', pollIntervalMs: 20, submitAttempts: 3, submitRetryMs: 30, micStallMs: 2000, makeClient: (baseUrl, token) => new BridgeClient({ baseUrl, token, timeoutMs: 1500, fetchImpl: async (input, init) => { sent.push(`${init?.method ?? 'GET'} ${new URL(String(input)).pathname.replace(/[0-9a-f-]{36}/, ':id')}`); return fetch(input, init); }, }), onChange: (s) => { snapshot = s; }, }); } async function until(what: string, predicate: () => boolean, timeoutMs = 4000): Promise { const deadline = Date.now() + timeoutMs; while (!predicate()) { if (Date.now() > deadline) throw new Error(`timed out waiting for: ${what}; phase=${snapshot?.state.phase} hud=${JSON.stringify(device.frame)}`); await new Promise((r) => setTimeout(r, 10)); } } const pause = (ms: number) => new Promise((r) => setTimeout(r, ms)); const phase = () => snapshot.state.phase; const speechRequests = () => sent.filter((s) => s === 'GET /v1/turns/:id/speech').length; async function atMenu(extras: Partial[0]> = {}): Promise { device = new FakeDevice(); controller = makeController(extras); await controller.start(); await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2'); expect(phase()).toBe('menu'); } const voiceOffered = () => until('Voice on the menu', () => snapshot.voice.offered); /** Menu -> Voice on -> Agents -> Ready. */ async function voiceOnInAgents(): Promise { await voiceOffered(); device.swipeDown(); device.swipeDown(); device.tap(); device.swipeUp(); device.tap(); expect(phase()).toBe('ready'); } describe('glasses: Voice on the menu, and answers read aloud', () => { beforeEach(() => { sent = []; speaker = new FakeSpeaker(); }); afterEach(async () => { await controller?.stop(); }); it('the menu gains a Voice switch, off at first; a tap flips it and stays on the menu', async () => { await harness(); await atMenu(); await voiceOffered(); expect(device.frame.body).toBe('Hermeven\n\n> Hands free\n Agents\n Voice: off'); device.swipeDown(); device.swipeDown(); device.swipeDown(); // already on the last entry device.tap(); expect(phase()).toBe('menu'); expect(device.frame.body).toBe('Hermeven\n\n Hands free\n Agents\n> Voice: on'); expect(snapshot.voice).toEqual({ offered: true, on: true, speaking: false }); device.tap(); expect(device.frame.body).toBe('Hermeven\n\n Hands free\n Agents\n> Voice: off'); expect(device.micOpens).toBe(0); expect(speaker.played).toEqual([]); expect(tts.requests).toEqual([]); }); it('no Voice entry when the bridge has no voices, when it is an older bridge, or when the page cannot play sound', async () => { await harness({}, false); await atMenu(); await until('asked', () => sent.includes('GET /v1/speech')); await pause(50); expect(device.frame.body).toBe('Hermeven\n\n> Hands free\n Agents'); await controller.stop(); await h.close(); await tts.stop(); await harness(); sent = []; await atMenu({ speaker: null }); await pause(80); expect(sent).not.toContain('GET /v1/speech'); expect(device.frame.body).toBe('Hermeven\n\n> Hands free\n Agents'); }); it('with Voice off nothing is fetched or played', async () => { await harness(); await atMenu(); await voiceOffered(); device.swipeDown(); device.tap(); // Agents controller.askText('hello'); await until('answer', () => phase() === 'answer'); await pause(80); expect(speechRequests()).toBe(0); expect(speaker.played).toEqual([]); expect(tts.requests).toEqual([]); }); it('with Voice on the answer is shown and read; the next question stops it', async () => { await harness(); await atMenu(); await voiceOnInAgents(); h.hermes.next({ kind: 'complete', output: 'The first answer.' }); controller.askText('one'); await until('answer', () => phase() === 'answer'); expect(device.frame.body).toContain('The first answer.'); await until('speaking', () => speaker.playing && snapshot.voice.speaking); expect(speaker.played).toEqual(['FAKE-MP3:voicePepper01:17']); // Turning the page does not interrupt. device.swipeDown(); expect(speaker.playing).toBe(true); // Asking again does. h.hermes.next({ kind: 'complete', output: 'The second answer.' }); controller.askText('two'); expect(speaker.playing).toBe(false); expect(speaker.stops).toBeGreaterThan(0); await until('second spoken', () => speaker.played.length === 2 && speaker.playing); speaker.end(); await until('finished', () => !snapshot.voice.speaking); expect(phase()).toBe('answer'); expect(tts.requests.map((r) => r.text)).toEqual(['The first answer.', 'The second answer.']); expect(h.hermes.executions).toBe(2); }); it('double tap and a tap to record stop the reading; audio that arrives late is not played', async () => { await harness(); await atMenu(); await voiceOnInAgents(); controller.askText('one'); await until('speaking', () => speaker.playing); device.doubleTap(); // back to Ready expect(speaker.playing).toBe(false); expect(phase()).toBe('ready'); controller.askText('two'); await until('speaking again', () => speaker.playing); device.tap(); // starts a recording expect(speaker.playing).toBe(false); device.doubleTap(); // cancel the recording await until('rest', () => phase() !== 'listening'); // Slow audio, and the user has moved on before it arrives. tts.next({ delayMs: 250 }); const before = speaker.played.length; controller.askText('three'); await until('answer', () => phase() === 'answer'); device.doubleTap(); await pause(400); expect(speaker.played.length).toBe(before); expect(speaker.playing).toBe(false); }); it('an agent without a voice is not read, and a failure to play leaves the answer on screen', async () => { await harness(); await atMenu(); await voiceOnInAgents(); device.swipeDown(); device.swipeDown(); expect(device.frame.body).toContain('Cody'); controller.askText('for cody'); await until('answer', () => phase() === 'answer'); await pause(80); expect(speechRequests()).toBe(0); device.doubleTap(); device.swipeDown(); // back round to Pepper expect(device.frame.body).toContain('Pepper'); speaker.fail = true; h.hermes.next({ kind: 'complete', output: 'Still shown.' }); controller.askText('for pepper'); await until('tried', () => speechRequests() === 1); await until('gave up', () => snapshot.log.some((e) => e.kind === 'voice' && e.detail.startsWith('not spoken'))); expect(phase()).toBe('answer'); expect(device.frame.body).toContain('Still shown.'); expect(snapshot.log.map((e) => e.detail).join('\n')).not.toContain('Still shown'); }); it('the app does not leave the glasses while an answer is being read; the countdown starts when it ends', async () => { await harness(); await atMenu({ idleExit: { ready: 5000, answer: 150, message: 5000 } }); await voiceOnInAgents(); controller.askText('one'); await until('speaking', () => speaker.playing); await pause(400); expect(device.exits).toBe(0); speaker.end(); await until('left', () => device.exits === 1, 2000); }); it('hands free: an answer to a spoken name is read, and the microphone still listens', async () => { await harness(); await atMenu(); await voiceOffered(); device.swipeDown(); device.swipeDown(); device.tap(); // Voice on device.swipeUp(); device.swipeUp(); device.tap(); // Hands free await until('listening for a name', () => device.micOpen && snapshot.state.wakeListening); h.stt.next({ text: 'Wendy, hello' }); h.hermes.next({ kind: 'complete', output: 'Hello from Wendy.' }); device.speak(1); device.silence(0.8); await until('speaking', () => speaker.playing); expect(speaker.played).toEqual(['FAKE-MP3:voiceWendy02:17']); await until('listening again', () => device.micOpen && snapshot.state.wakeListening); // No preview, as before: the only audio sent for transcription was the name check. expect(sent.filter((s) => s === 'POST /v1/transcribe')).toEqual([]); }); });