Files
hermeven/tests/integration/wake.test.ts
T
DanandClaude Fable 5.2 e1d183b54d Opening menu and hands-free mode: call an agent by name (0.3.0)
The app now opens on a menu, which is the root page: "Hands free" first,
"Agents" second. Agents is the 0.2.0 app unchanged. Hands free is the same
agents, conversations and question path with one flag set: the microphone
listens while the app is at rest and the app does not leave by itself.
The mode is never remembered; every launch starts at the menu with the
microphone closed, and double tap at Ready returns to the menu and closes
it.

Client: a loudness-only speech segmenter (core/vad.ts) cuts the stream
into utterances; each goes to the bridge for a wake check. "Wendy, <q>"
becomes a text turn to Wendy, with what was heard shown while she works.
A name alone starts a recording that sends itself when the speaker stops.
The status line starts with a dot for exactly as long as the microphone is
open at rest. In wake mode every microphone open and close goes through
one serialised reconciler; without the option the old path is untouched.

Bridge: POST /v1/wake transcribes one utterance in memory and reports
whether it BEGAN with an agent's name (first word of the display name, or
an alias from HERMEVEN_AGENT_<ID>_WAKE). Exact match only; a near miss is
reported as one word and never acted on. Creates no turn, stores nothing,
returns and logs nothing that was not addressed to an agent. One check at
a time per device, HERMEVEN_WAKE_CHECKS_PER_MINUTE (30).

Docs: decision 0004, bridge API, security gaps 3c/3d, device plan D.
The manifest's microphone description changed.

Not reviewed, not deployed, not uploaded, not device-tested.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 10:52:06 -08:00

528 lines
23 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { measureTextWrap } from '@evenrealities/pretext';
import { SCHEMA_VERSION } from '@hermeven/contracts';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { Controller, type Snapshot } from '../../apps/even-client/src/core/controller.ts';
import { BridgeClient } from '../../apps/even-client/src/net/bridgeClient.ts';
import { FakeDevice } from '../fakes/fakeDevice.ts';
import { syntheticPcm } from '../fakes/fakeStt.ts';
import { createHarness, type Harness } from './harness.ts';
/**
* Listening for an agent's name. The bridge is real. Hermes, speech-to-text and the glasses are
* TEST FAKES: the "speech" is a tone, and what it "says" is whatever the fake recogniser is
* scripted to return. This proves the plumbing and the rules, and nothing about how well a
* real microphone or a real recogniser hears a name.
*/
const WENDY_KEY = 'wendy-profile-key-0123456789';
const CODY_KEY = 'cody-profile-key-0123456789';
const AGENT_ENV = {
HERMEVEN_AGENT_NAME: 'Pepper',
HERMEVEN_AGENTS: 'wendy,cody',
HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY,
HERMEVEN_AGENT_CODY_API_KEY: CODY_KEY,
HERMEVEN_AGENT_CODY_NAME: 'Cody R.',
HERMEVEN_AGENT_CODY_WAKE: 'kody',
};
let h: Harness;
async function harness(env: Record<string, string> = AGENT_ENV, opts: { stt?: boolean } = {}): Promise<void> {
h = await createHarness({ env, ...opts });
h.hermes.profiles.set('wendy', WENDY_KEY);
h.hermes.profiles.set('cody', CODY_KEY);
}
const wakeQuery = (extra: Record<string, string> = {}) =>
new URLSearchParams({ schema_version: '1', locale: 'en-US', encoding: 'pcm_s16le', sample_rate: '16000', channels: '1', ...extra });
const wake = (token: string | undefined, said: string, query = wakeQuery()) => {
h.stt.next({ text: said });
return h.api('POST', `/v1/wake?${query}`, { token, body: syntheticPcm(1) });
};
const runsPosted = () => h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs');
afterEach(async () => {
await h?.close();
});
describe('bridge: POST /v1/wake', () => {
it('says who was addressed and what followed, and creates nothing', async () => {
await harness();
const { token } = await h.pair();
const res = await wake(token, ' Wendy, what is on my calendar?');
expect(res.status).toBe(200);
expect(res.body).toEqual({ schema_version: SCHEMA_VERSION, matched: true, agent_id: 'wendy', text: 'What is on my calendar?', near_miss: null });
expect((await wake(token, 'Kody.')).body).toMatchObject({ matched: true, agent_id: 'cody', text: '' });
expect((await wake(token, 'hey pepper turn it off')).body).toMatchObject({ matched: true, agent_id: 'default', text: 'Turn it off' });
// The recogniser got a proper WAV, as for a question.
expect(h.stt.lastWav).toMatchObject({ sampleRate: 16000, channels: 1, bitsPerSample: 16 });
expect(h.hermes.requests.filter((r) => r.method === 'POST')).toEqual([]);
expect(h.bridge.engine.activeConversation((await h.api('GET', '/v1/device', { token })).body.device_id)).toBeFalsy();
});
it('speech that is not for an agent is not returned, not kept and not logged', async () => {
await harness();
const { token } = await h.pair();
const secret = 'my card number is four one one one';
expect((await wake(token, secret)).body).toEqual({ schema_version: SCHEMA_VERSION, matched: false, agent_id: null, text: '', near_miss: null });
expect((await wake(token, `I told Wendy that ${secret}`)).body).toMatchObject({ matched: false, text: '' });
expect((await wake(token, 'Wendi, hello')).body).toEqual({ schema_version: SCHEMA_VERSION, matched: false, agent_id: null, text: '', near_miss: 'wendi' });
await wake(token, `Wendy, ${secret}`);
const logs = h.logs.join('\n');
for (const fragment of ['card number', 'four one one', 'wendi', 'Wendi']) expect(logs).not.toContain(fragment);
expect(logs).toContain('wake.matched');
});
it('needs a device credential and a well-formed request', async () => {
await harness();
const { token } = await h.pair();
expect((await wake(undefined, 'Wendy')).status).toBe(401);
expect((await h.api('POST', `/v1/wake?${wakeQuery()}`, { token, json: { a: 1 } })).status).toBe(415);
expect((await wake(token, 'Wendy', wakeQuery({ sample_rate: '8000' }))).status).toBe(400);
expect((await wake(token, 'Wendy', wakeQuery({ schema_version: '2' }))).status).toBe(400);
expect((await h.api('POST', `/v1/wake?${wakeQuery()}`, { token, body: Buffer.alloc(3) })).status).toBe(400);
});
it('a failed transcription is "nobody was addressed"', async () => {
await harness();
const { token } = await h.pair();
h.stt.next({ status: 500 });
const res = await h.api('POST', `/v1/wake?${wakeQuery()}`, { token, body: syntheticPcm(1) });
expect(res.status).toBe(200);
expect(res.body.matched).toBe(false);
});
it('answers not_found when nobody can be called by voice', async () => {
await harness(AGENT_ENV, { stt: false });
expect((await wake((await h.pair()).token, 'Wendy')).status).toBe(404);
await h.close();
// One agent, never given a name: there is no word to listen for.
await harness({});
expect((await wake((await h.pair()).token, 'Agent, hello')).status).toBe(404);
});
it('checks one stretch of speech at a time per device, within a per-minute budget', async () => {
await harness({ ...AGENT_ENV, HERMEVEN_WAKE_CHECKS_PER_MINUTE: '2' });
const { token } = await h.pair();
h.stt.next({ text: 'hello', delayMs: 150 });
const first = h.api('POST', `/v1/wake?${wakeQuery()}`, { token, body: syntheticPcm(1) });
await new Promise((r) => setTimeout(r, 40));
expect((await h.api('POST', `/v1/wake?${wakeQuery()}`, { token, body: syntheticPcm(1) })).status).toBe(429);
expect((await first).status).toBe(200);
expect((await wake(token, 'hello')).status).toBe(200);
expect((await wake(token, 'hello')).status).toBe(429);
// Questions have their own budget.
const conversation = await h.conversation(token);
expect((await h.textTurn(token, conversation, 'still fine')).status).toBe(202);
});
});
// ------------------------------------------------------------------ the app
let device: FakeDevice;
let controller: Controller;
let snapshot: Snapshot;
let sent: Array<{ method: string; path: string }>;
let wakeRoute: 'real' | 'not_found';
let extras: Partial<ConstructorParameters<typeof Controller>[0]>;
function makeController(dev: FakeDevice): Controller {
return new Controller({
wake: { armTimeoutMs: 250, watchMs: 40, stallMs: 150, retryMs: 120, pauseMs: 100 },
...extras,
device: dev,
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) => {
const path = new URL(String(input)).pathname;
sent.push({ method: init?.method ?? 'GET', path });
if (path === '/v1/wake' && wakeRoute === 'not_found') {
return new Response(JSON.stringify({ schema_version: SCHEMA_VERSION, error: { code: 'not_found', message: 'Not found.', retryable: false } }), {
status: 404,
headers: { 'Content-Type': 'application/json' },
});
}
return fetch(input, init);
},
}),
onChange: (s) => {
snapshot = s;
},
});
}
async function until(what: string, predicate: () => boolean, timeoutMs = 4000): Promise<void> {
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 phase = () => snapshot.state.phase;
const pause = (ms: number) => new Promise((r) => setTimeout(r, ms));
const listening = () => until('listening for a name', () => device.micOpen && snapshot.state.wakeListening);
async function paired(): Promise<void> {
device = new FakeDevice();
controller = makeController(device);
await controller.start();
await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2');
expect(phase()).toBe('ready');
}
/** Someone says something and stops: a tone, then a pause long enough to end the utterance. */
function say(seconds = 1, pauseSeconds = 0.8): void {
device.speak(seconds);
device.silence(pauseSeconds);
}
const posts = (path: string) => sent.filter((s) => s.method === 'POST' && s.path === path).length;
describe('glasses: always listening for a name', () => {
beforeEach(async () => {
sent = [];
wakeRoute = 'real';
extras = {};
await harness();
});
afterEach(async () => {
await controller?.stop();
});
it('opens the microphone by itself once paired, says so on the HUD, and stays on the glasses', async () => {
extras = { idleExit: { ready: 60, answer: 60, message: 60 } };
device = new FakeDevice();
controller = makeController(device);
await controller.start();
// Not paired: nothing to listen for, microphone closed.
await pause(60);
expect(device.micOpens).toBe(0);
await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2');
await listening();
expect(device.frame).toEqual({
body: 'Pepper\n\nListening. Say a name, then your question:\nPepper · Wendy · Cody',
status: '● Tap: ask · Swipe: agent · 2×: exit',
});
expect(snapshot.wake).toEqual({ available: true, enabled: true, listening: true });
// Well past every idle time: still here, still listening.
await pause(250);
expect(device.exitAttempts).toBe(0);
expect(device.micOpen).toBe(true);
});
it('"Wendy, <question>" in one breath is asked of Wendy, with what was heard shown while she works', async () => {
await paired();
await listening();
h.stt.next({ text: 'Wendy, what is on my calendar?' });
h.hermes.next({ kind: 'complete', afterMs: 200 });
say();
await until('thinking', () => phase() === 'thinking');
expect(device.frame.body).toBe('Wendy is thinking…\n\nHeard: What is on my calendar?');
// While the question is with the agent the microphone is closed.
await until('microphone closed', () => !device.micOpen);
expect(device.frame.status).not.toContain('●');
await until('answer', () => phase() === 'answer');
expect(h.hermes.executedBy).toEqual(['wendy']);
expect(snapshot.lastTurn?.input_text).toBe('What is on my calendar?');
// One recogniser call (the wake check); the question itself went as text, once.
expect(h.stt.calls).toBe(1);
expect(posts('/v1/turns')).toBe(1);
// Back at rest it listens again, on the answer screen too.
await listening();
expect(device.frame.status).toBe('● Wendy · Tap: ask');
});
it('a second name on the answer screen switches agent; each agent keeps its own conversation', async () => {
await paired();
await listening();
h.stt.next({ text: 'Wendy, first' });
say();
await until('answer', () => phase() === 'answer');
await listening();
h.stt.next({ text: 'Hey Kody, second' });
say();
await until('second answer', () => phase() === 'answer' && h.hermes.executedBy.length === 2);
await listening();
h.stt.next({ text: 'Wendy, third' });
say();
await until('third answer', () => phase() === 'answer' && h.hermes.executedBy.length === 3);
expect(h.hermes.executedBy).toEqual(['wendy', 'cody', 'wendy']);
expect([...h.hermes.sessions.values()].map((inputs) => inputs.length).sort()).toEqual([1, 2]);
expect(device.frame.status).toContain('Wendy · Tap: ask');
});
it('speech that is not addressed to an agent goes nowhere and changes nothing on screen', async () => {
await paired();
await listening();
const frames = device.frames.length;
h.stt.next({ text: 'so I told Wendy we would be late' }, { text: 'Wendi, are you there' });
say();
await until('first check', () => h.stt.calls === 1);
await pause(80);
say();
await until('second check', () => h.stt.calls === 2);
await pause(80);
expect(phase()).toBe('ready');
expect(device.frames.length).toBe(frames);
expect(posts('/v1/turns')).toBe(0);
expect(posts('/v1/conversations')).toBe(0);
expect(runsPosted()).toEqual([]);
// The near miss is visible on the phone, as one word; the other sentence is nowhere.
const log = snapshot.log.map((e) => e.detail).join('\n');
expect(log).toContain('heard "wendi"');
expect(log).not.toContain('late');
expect(device.micOpen).toBe(true);
});
it('a name alone starts a recording that sends itself when the speaker stops', async () => {
await paired();
await listening();
h.stt.next({ text: 'Cody.' }, { text: 'are the tests passing' });
say(0.6);
await until('recording for Cody', () => phase() === 'listening');
expect(device.frame.body).toBe('Cody R. is listening…\n\nAsk your question. It is sent when you stop speaking.');
expect(device.frame.status).toContain('● REC');
// Going from listening to recording did not close and reopen the microphone.
expect(device.micOpens).toBe(1);
expect(device.micCloses).toBe(0);
device.speak(1.2);
device.silence(1);
expect(phase()).toBe('listening'); // a pause shorter than the limit does not send
device.silence(0.4);
await until('answer', () => phase() === 'answer');
expect(h.hermes.executedBy).toEqual(['cody']);
expect(snapshot.lastTurn?.input_text).toBe('are the tests passing');
await listening();
});
it('a question spoken before the name has been recognised is not lost', async () => {
await paired();
await listening();
h.stt.next({ text: 'Wendy', delayMs: 300 }, { text: 'what time is it' });
say(0.5);
await until('check started', () => posts('/v1/wake') === 1);
say(1.5); // spoken, and finished, while the name is still being checked
await until('answer', () => phase() === 'answer');
expect(h.hermes.executedBy).toEqual(['wendy']);
expect(snapshot.lastTurn?.input_text).toBe('what time is it');
expect(posts('/v1/wake')).toBe(1);
// What was sent as the question is at least the 1.5 s that was spoken.
expect(h.stt.lastWav!.dataBytes).toBeGreaterThanOrEqual(1.5 * 32000);
});
it('a name alone followed by nothing goes back to rest and sends nothing', async () => {
await paired();
await listening();
h.stt.next({ text: 'Pepper' });
say(0.5);
await until('recording', () => phase() === 'listening');
await pause(300);
device.silence(0.2);
await until('ready', () => phase() === 'ready');
expect(posts('/v1/turns')).toBe(0);
expect(runsPosted()).toEqual([]);
await listening();
});
it('tapping still works while listening, and a tap during a check wins over what was heard', async () => {
await paired();
await listening();
h.stt.next({ text: 'Wendy, ignore this', delayMs: 250 }, { text: 'the tapped question' });
say();
await until('check started', () => posts('/v1/wake') === 1);
device.tap();
expect(phase()).toBe('listening');
device.speak(1);
await pause(350); // the check has come back by now
expect(phase()).toBe('listening');
expect(device.micOpens).toBe(1);
device.tap();
await until('answer', () => phase() === 'answer');
expect(h.hermes.executedBy).toEqual([null]);
expect(snapshot.lastTurn?.input_text).toBe('the tapped question');
});
it('a bridge that cannot do it ends hands free for the session, and says so', async () => {
wakeRoute = 'not_found';
await paired();
await listening();
say();
await until('microphone closed', () => !device.micOpen);
expect(snapshot.wake).toEqual({ available: false, enabled: false, listening: false });
expect(device.frame.body).toBe('Pepper\n\nHands free is not available.');
// Tap to ask still works.
device.tap();
await until('recording', () => phase() === 'listening' && device.micOpen);
});
it('a refused microphone is retried, and one that goes quiet is reopened', async () => {
device = new FakeDevice();
device.micAllowed = false;
controller = makeController(device);
await controller.start();
await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2');
await pause(100);
expect(device.frame.status).not.toContain('●');
device.micAllowed = true;
await listening();
const opens = device.micOpens;
// No frames at all: the watchdog closes and reopens it.
await until('reopened', () => device.micOpens > opens, 2000);
expect(device.micOpen).toBe(true);
});
it('closes the microphone when the glasses disconnect and when the app stops', async () => {
await paired();
await listening();
device.connection(false);
await until('closed on disconnect', () => !device.micOpen);
device.connection(true);
await listening();
await controller.stop();
expect(device.micOpen).toBe(false);
});
it('without the option nothing listens: the microphone opens only on a tap', async () => {
extras = { wake: null, idleExit: null };
await paired();
await pause(100);
expect(device.micOpens).toBe(0);
expect(snapshot.wake).toEqual({ available: false, enabled: false, listening: false });
expect(device.frame.body).toBe('Pepper\n\nReady.');
});
});
describe('glasses: the opening menu', () => {
beforeEach(async () => {
sent = [];
wakeRoute = 'real';
extras = { menu: true, idleExit: null };
await harness();
});
afterEach(async () => {
await controller?.stop();
});
async function atMenu(): Promise<void> {
device = new FakeDevice();
controller = makeController(device);
await controller.start();
await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2');
expect(phase()).toBe('menu');
}
it('opens on the menu with Hands free first, microphone closed, nothing sent', async () => {
await atMenu();
expect(device.frame).toEqual({ body: 'Hermeven\n\n> Hands free\n Agents', status: 'Tap: open · Swipe: move · 2×: exit' });
await pause(80);
expect(device.micOpens).toBe(0);
expect(snapshot.wake).toEqual({ available: true, enabled: false, listening: false });
device.speak(1);
expect(posts('/v1/wake') + posts('/v1/turns') + posts('/v1/conversations')).toBe(0);
});
it('one tap on the menu is hands free: listening, a name works, and double tap at Ready returns to the menu and closes the microphone', async () => {
await atMenu();
device.tap();
expect(phase()).toBe('ready');
await listening();
expect(device.frame).toEqual({
body: 'Pepper\n\nListening. Say a name, then your question:\nPepper · Wendy · Cody',
status: '● Tap: ask · Swipe: agent · 2×: menu',
});
h.stt.next({ text: 'Wendy, hello' });
say();
await until('answer', () => phase() === 'answer');
expect(h.hermes.executedBy).toEqual(['wendy']);
await listening();
device.doubleTap(); // answer -> Ready, still hands free
expect(phase()).toBe('ready');
expect(snapshot.wake.enabled).toBe(true);
device.doubleTap(); // Ready -> menu
expect(phase()).toBe('menu');
await until('microphone closed', () => !device.micOpen);
expect(device.exitRequests).toBe(0);
// Speech at the menu goes nowhere.
const checks = posts('/v1/wake');
device.speak(1);
await pause(60);
expect(posts('/v1/wake')).toBe(checks);
// The menu is the root page: double tap there asks the system to exit.
device.doubleTap();
expect(device.exitRequests).toBe(1);
});
it('Agents is the tap-to-ask app as before: no listening, the chosen agent, and it leaves when idle', async () => {
extras = { menu: true, idleExit: { ready: 150, answer: 150, message: 150 } };
await atMenu();
device.swipeDown();
expect(device.frame.body).toBe('Hermeven\n\n Hands free\n> Agents');
device.swipeDown(); // already on the last entry
device.tap();
expect(device.frame).toEqual({ body: 'Pepper\n\nReady.', status: 'Tap: ask · Swipe: agent · 2×: menu' });
device.swipeDown();
expect(device.frame.body).toBe('Wendy\n\nReady.');
say();
await pause(60);
expect(device.micOpens).toBe(0);
expect(posts('/v1/wake')).toBe(0);
h.stt.next({ text: 'a tapped question' });
device.tap();
await until('recording', () => phase() === 'listening' && device.micOpen);
device.speak(1);
device.tap();
await until('answer', () => phase() === 'answer');
expect(h.hermes.executedBy).toEqual(['wendy']);
await until('microphone closed', () => !device.micOpen);
expect(device.frame.status).not.toContain('●');
await until('left the glasses', () => device.exits === 1);
});
it('an untouched menu leaves the glasses; hands free does not', async () => {
extras = { menu: true, idleExit: { ready: 80, answer: 80, message: 80 } };
await atMenu();
await until('left the glasses', () => device.exits === 1);
await controller.stop();
await atMenu();
device.tap();
await listening();
await pause(250);
expect(device.exitAttempts).toBe(0);
});
it('where hands free cannot work the menu offers Agents only', async () => {
extras = { menu: true, wake: null, idleExit: null };
await atMenu();
expect(device.frame).toEqual({ body: 'Hermeven\n\n> Agents', status: 'Tap: open · Double-tap: exit' });
device.tap();
expect(device.frame.body).toBe('Pepper\n\nReady.');
expect(device.micOpens).toBe(0);
});
it('a question still running when the app was closed is shown on reopening, not the menu; a typed question works from the menu', async () => {
await atMenu();
controller.askText('typed from the phone');
await until('answer', () => phase() === 'answer');
expect(snapshot.wake.enabled).toBe(false);
device.doubleTap();
device.doubleTap();
expect(phase()).toBe('menu');
h.hermes.next({ kind: 'complete', afterMs: 400 });
const polls = () => sent.filter((r) => r.method === 'GET' && r.path.startsWith('/v1/turns/')).length;
const before = polls();
controller.askText('a slow one');
// Accepted by the bridge and being polled: only then is there a turn to come back to.
await until('accepted and polling', () => phase() === 'thinking' && polls() > before);
await controller.stop();
const reborn = new FakeDevice();
for (const [k, v] of device.storage) reborn.storage.set(k, v);
device = reborn;
controller = makeController(device);
await controller.start();
expect(phase()).toBe('thinking');
await until('answer', () => phase() === 'answer');
expect(device.micOpens).toBe(0);
});
});