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
+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)) {