Answers read aloud: Voice on the menu, ElevenLabs voices per agent via the bridge (0.5.0)

- bridge: GET /v1/speech (which agents have a voice) and GET /v1/turns/{id}/speech (MP3 of the
  caller's own finished answer, markup removed, first 900 characters). ElevenLabs adapter; key
  and voice ids from the environment; per-device budget; last three clips kept in memory.
  speech.done / speech.failed log ids, lengths and durations only.
- bridge: forceCloseConnections. A request the client had abandoned kept shutdown waiting for
  ever (also true of /v1/transcribe as deployed). Regression test for both routes.
- client: 'Voice: off/on' on the opening menu when the bridge offers it and the page can play
  sound; off at every launch. With it on, a finished answer is fetched and played; it stops
  when the answer leaves the screen; the app does not leave the glasses while it plays.
- tests: fake provider, fake loudspeaker (tests/integration/voice.test.ts).
- docs: 0006, security 3g-3i, device plan E, 0.4.1 rollout and Dan's sound check report.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Dan
2026-11-29 12:11:38 -08:00
co-authored by Claude Fable 5.2
parent d65beeab77
commit 9874e1bb5b
25 changed files with 1199 additions and 17 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
"package_id": "xylo.hermeven",
"edition": "202601",
"name": "Pepper",
"version": "0.4.1",
"version": "0.5.0",
"min_sdk_version": "0.0.16",
"entrypoint": "index.html",
"permissions": [
+5
View File
@@ -6,6 +6,7 @@ import { waitForEvenHost, watchForLateHost, type HostWindow } from './device/hos
import { BrowserPreviewDevice } from './device/previewDevice.ts';
import type { DevicePort } from './device/port.ts';
import { mountPhoneUi } from './ui/phone.ts';
import { createSpeaker } from './ui/speaker.ts';
/**
* Page start-up, kept out of main.ts so it can be exercised against a real DOM in tests.
@@ -37,6 +38,8 @@ export interface BootOptions {
menu?: boolean;
/** `false`: no words shown while recording. For automated simulator runs. */
livePreview?: boolean;
/** `false`: answers are never read aloud and the menu has no Voice entry. */
voice?: boolean;
/** Reload hook, replaceable in tests. */
reload?: () => void;
}
@@ -102,6 +105,8 @@ export async function boot(doc: Document, win: Window, options: BootOptions = {}
wake: mode === 'even' && options.wake !== false ? {} : null,
menu: options.menu !== false,
livePreview: mode === 'even' && options.livePreview !== false,
// Spoken answers: only in the Even app (the menu entry is on the glasses).
speaker: mode === 'even' && options.voice !== false ? createSpeaker(win) : null,
...(options.idleExit === false ? { idleExit: null } : typeof options.idleExit === 'object' ? { idleExit: options.idleExit } : {}),
// Development builds mirror diagnostics to the console (visible in the simulator and the
// Even dev console). Diagnostics never contain questions, answers or credentials.
+95
View File
@@ -94,9 +94,18 @@ export interface Snapshot {
* it. `enabled`: that mode is the one in use. `listening`: the microphone is open for it now.
*/
wake: { available: boolean; enabled: boolean; listening: boolean };
/** Reading answers aloud. `offered`: possible here. `on`: switched on. `speaking`: playing now. */
voice: { offered: boolean; on: boolean; speaking: boolean };
log: DiagEntry[];
}
/** Something that can play an answer's audio. The real one is the page's sound engine. */
export interface SpeakerPort {
/** Play MP3 audio. Resolves when it has finished or was stopped; rejects if it cannot play. */
play(audio: Uint8Array): Promise<void>;
stop(): void;
}
export interface WakeTiming {
/** After a name alone, a pause this long ends the question that follows. */
commandEndSilenceMs: number;
@@ -154,6 +163,11 @@ export interface ControllerOptions {
now?: () => number;
makeClient?: (baseUrl: string, token: string) => BridgeClient;
onChange?: (snapshot: Snapshot) => void;
/**
* Lets answers be read aloud when the bridge can do it and the user switches Voice on (a
* menu entry, so it needs `menu`). Without it nothing is ever fetched or played.
*/
speaker?: SpeakerPort | null;
/** Receives each diagnostic entry (ids, codes, timings; never content). */
onNote?: (entry: DiagEntry) => void;
/** Override the poll schedule with one fixed interval (tests). */
@@ -281,6 +295,12 @@ export class Controller {
/** The bridge said it cannot do previews (or is too old): stop asking for this session. */
private previewUnsupported = false;
// ---- reading answers aloud (all unused without a speaker)
/** The agents the bridge has a voice for. */
private speechAgents: string[] = [];
/** The answer being fetched or played. `abort` stops the fetch. */
private speaking: { requestId: string; abort: AbortController; playing: boolean } | null = null;
// ---- listening for a name (all unused when `wake` is null)
private readonly wake: WakeTiming | null;
private readonly segmenter = new SpeechSegmenter();
@@ -390,6 +410,7 @@ export class Controller {
handsFree: this.handsFreeAvailable(),
});
if (abandoned) void this.cancelTurn(abandoned);
void this.loadSpeech();
if (this.wake) this.wakeWatch = setInterval(() => this.watchWakeMic(), this.wake.watchMs);
}
@@ -672,6 +693,7 @@ export class Controller {
if (this.wakeWatch) clearInterval(this.wakeWatch);
this.wakeWatch = null;
this.stopTicker();
this.quiet();
await this.closeMic();
}
@@ -693,6 +715,7 @@ export class Controller {
enabled: this.wakeOn(),
listening: this.state.wakeListening,
},
voice: { offered: this.state.voiceOffered, on: this.state.voice, speaking: this.speaking?.playing === true },
log: [...this.log],
};
}
@@ -746,6 +769,7 @@ export class Controller {
menu: this.options.menu === true,
handsFree: this.handsFreeAvailable(),
});
void this.loadSpeech();
}
/** Disconnect: revoke the credential on the bridge, then clear everything held locally. */
@@ -810,6 +834,8 @@ export class Controller {
this.state = step.state;
// In the same step, before anything is drawn or another question can start.
this.reconcileRemovedAgent();
// An answer is only read while it is the one on screen: anything that moves on stops it.
if (this.speaking && (this.state.phase !== 'answer' || this.state.requestId !== this.speaking.requestId || !this.state.voice)) this.quiet();
if (before.phase !== step.state.phase) this.note('state', `${before.phase} -> ${step.state.phase}`);
for (const effect of step.effects) void this.run(effect);
this.afterChange();
@@ -841,6 +867,8 @@ export class Controller {
if (this.stopped || this.exited || !this.idleExitMs || !this.hudReady) return;
// Listening for a name is the point of staying open: the app does not leave by itself.
if (this.wakeOn()) return;
// Not while an answer is being read out: the countdown starts when it ends.
if (this.speaking) return;
const phase = this.state.phase;
const wait =
phase === 'answer'
@@ -1316,6 +1344,73 @@ export class Controller {
}
}
this.dispatch({ type: 'turn_update', generation, result, pages });
if (result.terminal && (result.outcome === 'succeeded' || result.outcome === 'incomplete') && result.answer_text) {
void this.speak(result.request_id);
}
}
// ------------------------------------------------------ reading answers aloud
/** Ask the bridge whether it can read answers aloud. Quietly "no" on any failure. */
private async loadSpeech(): Promise<void> {
const client = this.client;
if (!this.options.speaker || !client) return;
let agents: string[] = [];
try {
const info = await client.speech();
agents = info.available ? info.agent_ids : [];
} catch (err) {
if (!(err instanceof BridgeApiError && err.body.code === 'not_found')) this.note('voice', `not available: ${describe(err)}`);
}
if (this.stopped || this.client !== client) return;
this.speechAgents = agents;
this.dispatch({ type: 'voice_offered', offered: agents.length > 0 });
}
/** Read the answer on screen aloud, if Voice is on and its agent has a voice. */
private async speak(requestId: string): Promise<void> {
const speaker = this.options.speaker;
const client = this.client;
if (!speaker || !client || !this.state.voice) return;
if (this.state.phase !== 'answer' || this.state.requestId !== requestId) return;
if (!this.speechAgents.includes(this.state.agentId ?? 'default')) return;
this.quiet();
const mine = { requestId, abort: new AbortController(), playing: false };
this.speaking = mine;
this.scheduleIdleExit();
const startedAt = this.now();
try {
const audio = await client.turnSpeech(requestId, mine.abort.signal);
if (this.speaking !== mine) return;
this.note('voice', `audio for ${requestId}: ${audio.length} bytes in ${this.now() - startedAt} ms`);
mine.playing = true;
this.emit();
await speaker.play(audio);
if (this.speaking === mine) this.note('voice', `finished ${requestId} after ${this.now() - startedAt} ms`);
} catch (err) {
// No speech this time. The answer is on the glasses either way.
if (this.speaking === mine) this.note('voice', `not spoken: ${describe(err)}`);
} finally {
if (this.speaking === mine) {
this.speaking = null;
this.emit();
this.scheduleIdleExit();
}
}
}
/** Stop reading aloud, and stop waiting for audio that has not arrived. */
private quiet(): void {
const was = this.speaking;
if (!was) return;
this.speaking = null;
was.abort.abort();
try {
this.options.speaker?.stop();
} catch {
// Nothing was playing.
}
this.note('voice', `stopped ${was.requestId}`);
}
private async cancelTurn(requestId: string): Promise<void> {
+2 -2
View File
@@ -1,4 +1,4 @@
import { currentAgent, menuItems, MODE_LABEL, type AppState } from './reducer.ts';
import { currentAgent, menuItems, menuLabel, type AppState } from './reducer.ts';
/**
* HUD geometry. Canvas size and line height are documented by Even
@@ -86,7 +86,7 @@ function renderFrame(state: AppState, nowMs: number): HudFrame {
case 'menu': {
// Plain ASCII marker: the firmware font silently drops characters it does not have.
const lines = menuItems(state).map((mode, i) => `${i === state.menuIndex ? '>' : ' '} ${MODE_LABEL[mode]}`);
const lines = menuItems(state).map((item, i) => `${i === state.menuIndex ? '>' : ' '} ${menuLabel(item, state)}`);
return { body: `Hermeven\n\n${lines.join('\n')}`, status: lines.length > 1 ? 'Tap: open · Swipe: move · 2×: exit' : 'Tap: open · Double-tap: exit' };
}
+27 -3
View File
@@ -55,6 +55,10 @@ export interface AppState {
mode: Mode;
/** Hands free can be offered: this build has it, and nothing has said the bridge cannot do it. */
handsFree: boolean;
/** The bridge can read answers aloud and this page can play sound: the menu offers Voice. */
voiceOffered: boolean;
/** Answers are read aloud. Chosen on the menu; off at every launch, never saved. */
voice: boolean;
/**
* The agents the bridge offers, default first. Empty when there is only one (or the bridge
* predates agent selection): nothing about agents is then shown or sent.
@@ -115,6 +119,8 @@ export const initialState: AppState = {
menuIndex: 0,
mode: 'agents',
handsFree: false,
voiceOffered: false,
voice: false,
agents: [],
agentId: null,
generation: 0,
@@ -155,6 +161,8 @@ export type AppEvent =
}
/** Hands free turned out not to be possible (the bridge cannot do it): fall back to Agents. */
| { type: 'handsfree_lost' }
/** Whether answers can be read aloud at all (asked of the bridge after pairing). */
| { type: 'voice_offered'; offered: boolean }
/** The user picked another agent (a swipe at Ready). `conversationId` is that agent's own, if it has one. */
| { type: 'agent_selected'; agentId: string; conversationId: string | null }
/**
@@ -219,8 +227,15 @@ const IDLE: ReadonlySet<Phase> = new Set(['ready', 'answer', 'error', 'cancelled
const IN_FLIGHT: ReadonlySet<Phase> = new Set(['transcribing', 'thinking', 'approval']);
/** The menu's entries, in order. Hands free comes first whenever it can be offered. */
export function menuItems(state: Pick<AppState, 'handsFree'>): Mode[] {
return state.handsFree ? ['handsfree', 'agents'] : ['agents'];
export type MenuItem = Mode | 'voice';
export function menuItems(state: Pick<AppState, 'handsFree' | 'voiceOffered'>): MenuItem[] {
const modes: MenuItem[] = state.handsFree ? ['handsfree', 'agents'] : ['agents'];
return state.voiceOffered ? [...modes, 'voice'] : modes;
}
/** How a menu entry reads. Voice is a switch, so it shows its setting. */
export function menuLabel(item: MenuItem, state: Pick<AppState, 'voice'>): string {
return item === 'voice' ? `Voice: ${state.voice ? 'on' : 'off'}` : MODE_LABEL[item];
}
/** The agent questions go to now, or undefined when the bridge offers no choice. */
@@ -313,6 +328,12 @@ export function reduce(state: AppState, event: AppEvent): Step {
return same({ ...base, phase: base.menu ? 'menu' : 'ready' });
}
case 'voice_offered': {
if (event.offered === state.voiceOffered) return same(state);
const next = { ...state, voiceOffered: event.offered, voice: event.offered && state.voice };
return same({ ...next, menuIndex: Math.min(state.menuIndex, menuItems(next).length - 1) });
}
case 'handsfree_lost': {
if (!state.handsFree) return same(state);
const wasOn = state.mode === 'handsfree';
@@ -403,7 +424,10 @@ export function reduce(state: AppState, event: AppEvent): Step {
case 'activate': {
if (state.phase === 'menu') {
const mode = menuItems(state)[state.menuIndex] ?? 'agents';
const item = menuItems(state)[state.menuIndex] ?? 'agents';
// Voice is a switch: it flips and the menu stays.
if (item === 'voice') return same({ ...state, voice: !state.voice });
const mode: Mode = item;
return same({ ...clearTurn(state), phase: 'ready', mode, generation: state.generation + 1 });
}
if (IDLE.has(state.phase)) {
+1
View File
@@ -26,6 +26,7 @@ const { controller } = await boot(document, window, {
wake: !(import.meta.env.DEV && new URLSearchParams(location.search).get('wake') === 'off'),
menu: !(import.meta.env.DEV && new URLSearchParams(location.search).get('menu') === 'off'),
livePreview: !(import.meta.env.DEV && new URLSearchParams(location.search).get('preview') === 'off'),
voice: !(import.meta.env.DEV && new URLSearchParams(location.search).get('voice') === 'off'),
});
// Development-only convenience for automated simulator runs, where nothing can type into the
+41
View File
@@ -8,6 +8,7 @@ import {
ErrorResponse,
RevokeResponse,
SCHEMA_VERSION,
SpeechInfoResponse,
TranscribeResponse,
TurnResult,
WakeResponse,
@@ -207,6 +208,46 @@ export class BridgeClient {
return this.call(TranscribeResponse, 'POST', `/v1/transcribe?${query}`, { binary: args.pcm });
}
/** Whether answers can be read aloud, and for which agents. An older bridge answers `not_found`. */
speech(): Promise<SpeechInfoResponse> {
return this.call(SpeechInfoResponse, 'GET', '/v1/speech');
}
/** A finished answer read aloud, as MP3. Not JSON, so it does not go through `call`. */
async turnSpeech(requestId: string, signal?: AbortSignal): Promise<Uint8Array> {
let res: Response;
try {
res = await this.fetchImpl(`${this.baseUrl}/v1/turns/${requestId}/speech`, {
method: 'GET',
headers: { Accept: 'audio/mpeg', Authorization: `Bearer ${this.token}` },
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(this.timeoutMs * 2)]) : AbortSignal.timeout(this.timeoutMs * 2),
credentials: 'omit',
cache: 'no-store',
});
} catch (err) {
throw new BridgeNetworkError(err instanceof Error ? err.name : 'network error');
}
if (!res.ok) {
let payload: unknown;
try {
payload = await res.json();
} catch {
payload = null;
}
if (check(ErrorResponse, payload)) throw new BridgeApiError(res.status, payload.error as ErrorBody);
throw new BridgeNetworkError(`unexpected HTTP ${res.status}`);
}
const type = (res.headers.get('Content-Type') ?? '').split(';')[0]!.trim().toLowerCase();
if (type !== 'audio/mpeg') throw new BridgeNetworkError('response was not audio');
try {
const audio = new Uint8Array(await res.arrayBuffer());
if (audio.length === 0) throw new Error('empty');
return audio;
} catch (err) {
throw new BridgeNetworkError(err instanceof Error ? err.name : 'network error');
}
}
getTurn(requestId: string): Promise<TurnResult> {
return this.call(TurnResult, 'GET', `/v1/turns/${requestId}`) as Promise<TurnResult>;
}
+8
View File
@@ -158,6 +158,14 @@ export function mountPhoneUi(root: HTMLElement, controller: Controller, defaults
['Bridge', s.bridgeUrl],
['Agent', s.status ? (s.status.agent_reachable ? 'reachable' : 'not reachable from the bridge') : 'not checked'],
['Speech-to-text', s.status ? (s.status.stt_configured ? 'configured' : 'not configured (typed questions only)') : 'not checked'],
[
'Spoken answers',
!s.voice.offered
? 'not available (the bridge has no voices set up, or this page cannot play sound)'
: s.voice.on
? `on${s.voice.speaking ? ', speaking now' : ''}: answers are sent to the speech provider and played on whatever sound output the phone is using`
: 'off. Switch on with “Voice” on the glasses’ opening menu; it is off again at every launch.',
],
['Credential valid until', when(s.tokenExpiresAt)],
['Pairing valid until', when(s.pairingExpiresAt)],
['Stored on this phone', 'In the Even app’s app storage, which is not an encrypted vault. The credential is revocable and expires.'],
+58
View File
@@ -0,0 +1,58 @@
import type { SpeakerPort } from '../core/controller.ts';
/**
* Plays an answer's audio through the page's sound engine (Web Audio). Where it is heard is
* Android's choice, not ours: whatever output is selected (earbuds, car, or the phone itself).
* The page cannot tell which, so speech is only ever played after the user switched Voice on.
*
* Device evidence (docs/evidence/device/2026-11-29.md): in the Even app on Dan's phone a page
* may play sound without a touch, and did so 20 s after a press. Playing an MP3 this way has
* NOT been tried on the device.
*/
export function createSpeaker(win: Window): SpeakerPort | null {
const w = win as unknown as { AudioContext?: typeof AudioContext; webkitAudioContext?: typeof AudioContext };
const Ctor = w.AudioContext ?? w.webkitAudioContext;
if (!Ctor) return null;
let context: AudioContext | null = null;
let current: { source: AudioBufferSourceNode; done: () => void } | null = null;
const stop = () => {
const playing = current;
current = null;
if (!playing) return;
try {
playing.source.onended = null;
playing.source.stop();
} catch {
// Already stopped.
}
playing.done();
};
return {
async play(audio: Uint8Array): Promise<void> {
stop();
context ??= new Ctor();
const ctx = context;
await Promise.race([ctx.resume(), new Promise((r) => win.setTimeout(r, 800))]);
if (ctx.state !== 'running') throw new Error(`sound is blocked (${ctx.state})`);
// decodeAudioData takes ownership of the buffer it is given: hand it a copy.
const copy = audio.buffer.slice(audio.byteOffset, audio.byteOffset + audio.byteLength) as ArrayBuffer;
const buffer = await ctx.decodeAudioData(copy);
// Stopped, or replaced by a newer answer, while decoding.
if (current) stop();
const source = ctx.createBufferSource();
source.buffer = buffer;
source.connect(ctx.destination);
await new Promise<void>((resolve) => {
current = { source, done: resolve };
source.onended = () => {
if (current?.source === source) current = null;
resolve();
};
source.start();
});
},
stop,
};
}
+1 -1
View File
@@ -184,7 +184,7 @@ describe('HUD frames', () => {
{ id: 'cody', name: 'Cody' },
];
const wake = { wakeListening: true };
if (phase === 'menu') return [base, { ...base, handsFree: true }, { ...base, handsFree: true, menuIndex: 1 }];
if (phase === 'menu') return [base, { ...base, handsFree: true }, { ...base, handsFree: true, menuIndex: 1 }, { ...base, handsFree: true, voiceOffered: true, menuIndex: 2 }, { ...base, voiceOffered: true, voice: true, menuIndex: 1 }];
if (phase === 'ready') {
return [{ ...base, menu: true }, { ...base, menu: true, ...wake, agents: few }, base, { ...base, notice: 'New conversation' }, { ...base, ...wake }, { ...base, ...wake, agents: few }, { ...base, ...wake, agents: many }, { ...base, ...wake, agents: few, notice: 'New conversation' }];
}