Files
hermeven/tests/integration/client-bridge.test.ts
T
DanandClaude Fable 5.2 4687cc0114 First vertical slice: Even client, bridge, contract v1, tests, docs
Client (apps/even-client): pure interaction reducer with generation-based
stale-result rejection, HUD renderer, measured pagination, Even Hub SDK
0.0.16 adapter, bridge HTTP client, phone pairing/status/diagnostics page.

Bridge (services/bridge): device pairing and revocable expiring credentials,
turn engine with idempotent submit, cancel, deadlines and restart recovery,
Hermes Runs API adapter, OpenAI-compatible STT adapter, operator CLI.

Contract (packages/contracts): versioned schemas, types and error codes.

Tests: 122 unit/integration (fakes), 6 simulator scenarios (Even Hub
simulator 0.9.5), 9 scenarios against a real Hermes v0.23.1 gateway with a
stub model. No real STT, real model or physical device has been exercised;
see docs/test-evidence.md and docs/device-test-plan.md.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 18:21:49 -08:00

343 lines
14 KiB
TypeScript

import { measureTextWrap } from '@evenrealities/pretext';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { Controller, type Snapshot } from '../../apps/even-client/src/core/controller.ts';
import { MENU_ITEM } from '../../apps/even-client/src/device/events.ts';
import { BridgeClient } from '../../apps/even-client/src/net/bridgeClient.ts';
import { FakeDevice } from '../fakes/fakeDevice.ts';
import { createHarness, type Harness } from './harness.ts';
/**
* The whole software path in one process: the client's controller, reducer,
* pagination and HTTP client -> the real bridge over HTTP -> TEST FAKES for
* the glasses, the speech recogniser and Hermes. No hardware, no simulator,
* no real model. See docs/device-test-plan.md for what this does not cover.
*/
let h: Harness;
let device: FakeDevice;
let controller: Controller;
let snapshot: Snapshot;
let network: { down: boolean };
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;
function makeController(dev: FakeDevice): Controller {
return new Controller({
device: dev,
measure: (text, width) => measureTextWrap(text, width).lineCount,
locale: 'en-US',
pollIntervalMs: 20,
submitAttempts: 3,
submitRetryMs: 30,
micStallMs: 300,
makeClient: (baseUrl, token) =>
new BridgeClient({
baseUrl,
token,
timeoutMs: 500,
fetchImpl: (input, init) => (network.down ? Promise.reject(new TypeError('offline')) : fetch(input, init)),
}),
onChange: (s) => {
snapshot = s;
},
});
}
async function pairedController(): Promise<void> {
device = new FakeDevice();
controller = makeController(device);
await controller.start();
expect(phase()).toBe('unpaired');
const { code } = h.bridge.devices.createPairingCode();
await controller.pair(h.url, code, 'fake-g2');
expect(phase()).toBe('ready');
}
beforeEach(async () => {
network = { down: false };
h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2' } });
});
afterEach(async () => {
await controller?.stop();
await h?.close();
});
describe('voice question, answer and follow-up', () => {
it('tap -> record -> tap -> transcribe -> think -> paged answer -> follow-up with context', async () => {
await pairedController();
expect(device.frame.status).toContain('Tap: ask');
expect(device.micOpens).toBe(0);
const answer = Array.from({ length: 60 }, (_, i) => `Sentence number ${i + 1} of a long answer about Mount Everest.`).join(' ');
h.stt.next({ text: 'how tall is mount everest' });
h.hermes.next({ kind: 'complete', output: `**Mount Everest** is 8,849 m tall.\n\n${answer}` });
device.tap();
await until('listening with mic open', () => phase() === 'listening' && device.micOpen);
await until('REC indicator', () => device.frame.status.includes('● REC'));
device.speak(1.2);
device.tap();
await until('answer', () => phase() === 'answer');
expect(device.micOpen).toBe(false);
expect(device.micCloses).toBe(1);
// 1.2 s of 16 kHz 16-bit mono reached the recogniser as a WAV.
expect(h.stt.lastWav).toEqual({ sampleRate: 16000, channels: 1, bitsPerSample: 16, dataBytes: 38400 });
expect(h.hermes.lastRun()!.input).toBe('how tall is mount everest');
// Paged, plain text, complete.
const pages = snapshot.state.pages;
expect(pages.length).toBeGreaterThan(2);
expect(pages[0]).toMatch(/^Mount Everest is 8,849 m tall\./);
expect(pages.join(' ')).toContain('Sentence number 60 of a long answer');
expect(device.frame.body).toBe(pages[0]);
expect(device.frame.status).toContain(`1/${pages.length}`);
device.swipeDown();
expect(device.frame.body).toBe(pages[1]);
device.swipeUp();
device.swipeUp();
expect(device.frame.body).toBe(pages[0]);
for (let i = 0; i < pages.length + 3; i++) device.swipeDown();
expect(device.frame.body).toBe(pages.at(-1));
// The phone keeps the complete original, Markdown and all.
expect(snapshot.lastTurn!.answer_text).toContain('**Mount Everest**');
// Follow-up in the same conversation.
h.stt.next({ text: 'and in feet' });
device.tap();
await until('listening again', () => phase() === 'listening' && device.micOpen);
device.speak(0.6);
device.tap();
await until('second answer', () => phase() === 'answer');
expect(device.frame.body).toContain('turn=2');
expect(device.frame.body).toContain('previous="how tall is mount everest"');
expect(h.hermes.sessions.size).toBe(1);
expect(h.hermes.executions).toBe(2);
});
it('recording stops by itself at the cap and submits what was captured', async () => {
await pairedController();
device.tap();
await until('listening', () => phase() === 'listening' && device.micOpen);
device.speak(5); // cap is 2 s
await until('answer', () => phase() === 'answer');
expect(device.micOpen).toBe(false);
expect(h.stt.lastWav!.dataBytes).toBe(2 * 32000);
});
it('explicit new conversation from the glasses menu starts a fresh agent session', async () => {
await pairedController();
controller.askText('remember the word pineapple');
await until('answer', () => phase() === 'answer');
device.menu(MENU_ITEM.NEW_CONVERSATION);
await until('new conversation ready', () => phase() === 'ready' && snapshot.state.conversationId !== null);
expect(device.frame.body).toContain('New conversation');
controller.askText('what word?');
await until('answer', () => phase() === 'answer');
expect(device.frame.body).toContain('turn=1');
expect(h.hermes.sessions.size).toBe(2);
});
});
describe('cancel and stale results', () => {
it('double-tap while recording discards the audio: nothing is uploaded', async () => {
await pairedController();
device.tap();
await until('listening', () => phase() === 'listening' && device.micOpen);
device.speak(0.5);
device.doubleTap();
await until('cancelled', () => phase() === 'cancelled' && !device.micOpen);
await new Promise((r) => setTimeout(r, 100));
expect(h.stt.calls).toBe(0);
expect(h.hermes.executions).toBe(0);
// Audio arriving after the stop is ignored.
device.micOpen = true;
device.speak(0.3);
device.micOpen = false;
expect(phase()).toBe('cancelled');
});
it('cancel while thinking stops the agent, and its late answer never reaches the HUD', async () => {
await pairedController();
h.hermes.next({ kind: 'complete', afterMs: 250, output: 'LATE ANSWER' });
h.hermes.ignoreStop(); // the agent finishes anyway
controller.askText('slow question');
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
device.doubleTap();
expect(phase()).toBe('cancelled');
expect(device.frame.body).toContain('not undone');
await new Promise((r) => setTimeout(r, 500));
expect(phase()).toBe('cancelled');
expect(device.frames.some((f) => f.body.includes('LATE ANSWER'))).toBe(false);
expect(h.hermes.requests.filter((r) => r.path.endsWith('/stop')).length).toBeGreaterThanOrEqual(1);
// A newer question is answered normally and the old one cannot overwrite it.
h.hermes.ignoreStop(false);
h.hermes.next({ kind: 'complete', output: 'NEW ANSWER' });
controller.askText('new question');
await until('answer', () => phase() === 'answer');
expect(device.frame.body).toBe('NEW ANSWER');
});
it('cancel from the glasses menu works while thinking', async () => {
await pairedController();
h.hermes.next({ kind: 'hang' });
controller.askText('q');
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
device.menu(MENU_ITEM.CANCEL);
expect(phase()).toBe('cancelled');
await until('bridge saw the cancel', () => h.hermes.requests.some((r) => r.path.endsWith('/stop')));
});
});
describe('connection loss', () => {
it('bridge unreachable at submit: nothing is sent; tap resends the same request exactly once', async () => {
await pairedController();
network.down = true;
device.tap();
await until('listening', () => phase() === 'listening' && device.micOpen);
device.speak(0.5);
device.tap();
await until('disconnected', () => phase() === 'disconnected');
expect(device.frame.body).toContain('has not been sent');
expect(device.micOpen).toBe(false);
const requestId = snapshot.state.requestId;
network.down = false;
device.tap();
await until('answer', () => phase() === 'answer');
expect(snapshot.lastTurn!.request_id).toBe(requestId);
expect(h.hermes.executions).toBe(1);
expect(h.stt.calls).toBe(1);
// The microphone was not reopened by the retry.
expect(device.micOpens).toBe(1);
});
it('connection lost while waiting: keeps the turn, shows it, and delivers the answer on return', async () => {
await pairedController();
h.hermes.next({ kind: 'complete', afterMs: 500, output: 'worth the wait' });
controller.askText('q');
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
network.down = true;
await until('disconnected', () => phase() === 'disconnected');
expect(device.frame.body).toContain('Still waiting');
device.tap(); // must not resubmit
network.down = false;
await until('answer', () => phase() === 'answer');
expect(device.frame.body).toBe('worth the wait');
expect(h.hermes.executions).toBe(1);
});
it('glasses disconnect while recording stops capture; reconnecting does not reopen the microphone', async () => {
await pairedController();
device.tap();
await until('listening', () => phase() === 'listening' && device.micOpen);
device.connection(false);
await until('mic closed', () => !device.micOpen);
expect(phase()).toBe('disconnected');
device.connection(true);
await new Promise((r) => setTimeout(r, 100));
expect(phase()).toBe('ready');
expect(device.micOpen).toBe(false);
expect(device.micOpens).toBe(1);
expect(h.stt.calls).toBe(0);
});
it('a microphone that stops delivering audio ends the capture with an error', async () => {
await pairedController();
device.tap();
await until('listening', () => phase() === 'listening' && device.micOpen);
await until('stall detected', () => phase() === 'error', 3000);
expect(snapshot.state.error!.code).toBe('mic_stalled');
expect(device.micOpen).toBe(false);
});
it('a refused microphone is reported and nothing is recorded', async () => {
await pairedController();
device.micAllowed = false;
device.tap();
await until('error', () => phase() === 'error');
expect(snapshot.state.error!.code).toBe('mic_refused');
expect(device.frame.body).toContain('Microphone unavailable');
});
});
describe('restart, revocation and disconnect', () => {
it('a page restart mid-turn re-attaches to the turn without resubmitting or recording', async () => {
await pairedController();
h.hermes.next({ kind: 'complete', afterMs: 300, output: 'found after restart' });
controller.askText('q');
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
await until('active request persisted', () => (device.storage.get('hermeven.v1') ?? '').includes('"activeRequestId":"'));
await controller.stop();
// New page, same app storage.
const reborn = new FakeDevice();
for (const [k, v] of device.storage) reborn.storage.set(k, v);
device = reborn;
controller = makeController(device);
await controller.start();
await until('answer', () => phase() === 'answer');
expect(device.frame.body).toBe('found after restart');
expect(h.hermes.executions).toBe(1);
expect(device.micOpens).toBe(0);
});
it('a credential revoked on the bridge sends the app back to unpaired and wipes local state', async () => {
await pairedController();
const [paired] = h.bridge.devices.list();
h.bridge.devices.revoke(paired!.id);
controller.askText('q');
await until('unpaired', () => phase() === 'unpaired');
expect(device.storage.get('hermeven.v1')).toBe('');
expect(snapshot.paired).toBe(false);
expect(h.hermes.executions).toBe(0);
});
it('disconnect revokes on the bridge and clears the phone', async () => {
await pairedController();
const stored = JSON.parse(device.storage.get('hermeven.v1')!);
expect((await controller.disconnect()).revoked).toBe(true);
expect(phase()).toBe('unpaired');
expect(device.storage.get('hermeven.v1')).toBe('');
expect((await h.api('GET', '/v1/device', { token: stored.token })).status).toBe(401);
});
it('double-tap on the root page asks the OS for its exit dialog', async () => {
await pairedController();
device.doubleTap();
await until('exit requested', () => device.exitRequests === 1);
expect(phase()).toBe('ready');
});
it('pairing with a wrong code fails without storing anything', async () => {
device = new FakeDevice();
controller = makeController(device);
await controller.start();
await expect(controller.pair(h.url, 'WRONG-CODE1', 'x')).rejects.toMatchObject({ body: { code: 'pairing_invalid' } });
expect(phase()).toBe('unpaired');
expect(device.storage.get('hermeven.v1') ?? '').toBe('');
});
it('diagnostics never contain the question, the answer or the credential', async () => {
await pairedController();
h.stt.next({ text: 'SECRET-QUESTION-walrus' });
h.hermes.next({ kind: 'complete', output: 'SECRET-ANSWER-narwhal' });
device.tap();
await until('listening', () => phase() === 'listening' && device.micOpen);
device.speak(0.4);
device.tap();
await until('answer', () => phase() === 'answer');
const log = snapshot.log.map((e) => `${e.kind} ${e.detail}`).join('\n');
const token = JSON.parse(device.storage.get('hermeven.v1')!).token;
expect(log).toContain('done');
for (const secret of ['walrus', 'narwhal', token]) expect(log).not.toContain(secret);
});
});