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>
This commit is contained in:
Dan
2026-11-18 18:21:49 -08:00
co-authored by Claude Fable 5.2
commit 4687cc0114
79 changed files with 11685 additions and 0 deletions
+86
View File
@@ -0,0 +1,86 @@
import type { HudFrame } from '../../apps/even-client/src/core/hud.ts';
import type { DeviceEvent } from '../../apps/even-client/src/device/events.ts';
import type { DevicePort } from '../../apps/even-client/src/device/port.ts';
/**
* TEST FAKE. Not glasses, not the simulator.
*
* Records what the app would draw, and lets a test play gestures and audio
* frames. It proves the app's logic against the DevicePort contract only.
*/
export class FakeDevice implements DevicePort {
frames: HudFrame[] = [];
micOpen = false;
micOpens = 0;
micCloses = 0;
micAllowed = true;
exitRequests = 0;
readonly storage = new Map<string, string>();
private readonly listeners = new Set<(event: DeviceEvent) => void>();
private readonly connectionListeners = new Set<(connected: boolean) => void>();
get frame(): HudFrame {
return this.frames.at(-1) ?? { body: '', status: '' };
}
async init(frame: HudFrame): Promise<boolean> {
this.frames.push(frame);
return true;
}
show(frame: HudFrame): void {
this.frames.push(frame);
}
async startMic(): Promise<boolean> {
if (!this.micAllowed) return false;
this.micOpen = true;
this.micOpens += 1;
return true;
}
async stopMic(): Promise<void> {
if (this.micOpen) this.micCloses += 1;
this.micOpen = false;
}
onEvent(listener: (event: DeviceEvent) => void): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
onConnection(listener: (connected: boolean) => void): () => void {
this.connectionListeners.add(listener);
return () => this.connectionListeners.delete(listener);
}
async requestExit(): Promise<void> {
this.exitRequests += 1;
}
async storageGet(key: string): Promise<string> {
return this.storage.get(key) ?? '';
}
async storageSet(key: string, value: string): Promise<void> {
this.storage.set(key, value);
}
// ---- test controls
emit(event: DeviceEvent): void {
for (const l of this.listeners) l(event);
}
tap = () => this.emit({ type: 'tap' });
doubleTap = () => this.emit({ type: 'double_tap' });
swipeDown = () => this.emit({ type: 'swipe_down' });
swipeUp = () => this.emit({ type: 'swipe_up' });
menu = (itemId: number) => this.emit({ type: 'menu', itemId });
connection(connected: boolean): void {
for (const l of this.connectionListeners) l(connected);
}
/** Deliver audio the way the SDK documents it: 100 ms frames of 3,200 bytes. Only while the mic is open. */
speak(seconds: number): void {
const frames = Math.round(seconds * 10);
for (let i = 0; i < frames && this.micOpen; i++) {
const pcm = new Uint8Array(3200);
for (let s = 0; s < 1600; s++) {
const v = Math.round(Math.sin((2 * Math.PI * 440 * (i * 1600 + s)) / 16000) * 8000);
pcm[s * 2] = v & 0xff;
pcm[s * 2 + 1] = (v >> 8) & 0xff;
}
this.emit({ type: 'audio', pcm });
}
}
}
+258
View File
@@ -0,0 +1,258 @@
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
import type { AddressInfo } from 'node:net';
/**
* TEST FAKE. Not Hermes.
*
* A deterministic stand-in for the Hermes API server's Runs API, written from
* the hermes-agent v0.23.1 source (gateway/platforms/api_server_runs.py). It
* exists so the bridge's real HTTP adapter can be exercised against scripted
* outcomes and faults. A passing test against this file is evidence about
* Hermeven's logic only, never about Hermes or about hardware.
*/
export interface FakeRun {
runId: string;
key: string;
body: string;
sessionId: string;
input: string;
status: string;
output: string;
extra: Record<string, unknown>;
stopRequested: boolean;
timer: ReturnType<typeof setTimeout> | null;
}
export type Script =
| { kind: 'complete'; afterMs?: number; output?: string }
| { kind: 'fail'; afterMs?: number; error?: string }
| { kind: 'incomplete'; afterMs?: number; output: string }
| { kind: 'approval' }
| { kind: 'hang' }
| { kind: 'unknown'; afterMs?: number }
| { kind: 'interrupted'; afterMs?: number };
export class FakeHermes {
readonly apiKey = 'fake-hermes-key';
/** How many turns actually "executed". The duplicate-execution counter. */
executions = 0;
readonly runs = new Map<string, FakeRun>();
private readonly byKey = new Map<string, FakeRun>();
/** session id -> inputs seen, to prove follow-ups land in the same session. */
readonly sessions = new Map<string, string[]>();
readonly requests: Array<{ method: string; path: string; idempotencyKey?: string }> = [];
private script: Script[] = [];
private defaultScript: Script = { kind: 'complete' };
/** Faults applied to upcoming POST /v1/runs calls, in order. */
private submitFaults: Array<'drop_response' | 'http_503' | 'http_500' | 'http_400'> = [];
/** When true, every request is refused at the socket level. */
private server: Server | null = null;
private stopIgnored = false;
private statusDown = false;
private seq = 0;
url = '';
async start(port = 0): Promise<void> {
this.server = createServer((req, res) => void this.handle(req, res));
await new Promise<void>((resolve) => this.server!.listen(port, '127.0.0.1', resolve));
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
}
get port(): number {
return Number(new URL(this.url).port);
}
async stop(): Promise<void> {
for (const run of this.runs.values()) if (run.timer) clearTimeout(run.timer);
const server = this.server;
this.server = null;
if (server) {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
}
next(...scripts: Script[]): void {
this.script.push(...scripts);
}
setDefault(script: Script): void {
this.defaultScript = script;
}
failNextSubmit(...faults: Array<'drop_response' | 'http_503' | 'http_500' | 'http_400'>): void {
this.submitFaults.push(...faults);
}
ignoreStop(value = true): void {
this.stopIgnored = value;
}
setStatusDown(value: boolean): void {
this.statusDown = value;
}
/** Resolve a pending approval the way another, verified surface would. */
approve(runId: string, output = 'approved and done'): void {
const run = this.runs.get(runId)!;
run.status = 'running';
this.finishLater(run, { kind: 'complete', afterMs: 30, output });
}
/** Forget every run, as if status retention had expired. */
forgetRuns(): void {
this.runs.clear();
}
lastRun(): FakeRun | undefined {
return [...this.runs.values()].at(-1);
}
private json(res: ServerResponse, status: number, body: unknown, headers: Record<string, string> = {}): void {
res.writeHead(status, { 'Content-Type': 'application/json', ...headers });
res.end(JSON.stringify(body));
}
private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
const url = new URL(req.url ?? '/', 'http://x');
const path = url.pathname;
const key = req.headers['idempotency-key'];
this.requests.push({ method: req.method ?? '', path, idempotencyKey: typeof key === 'string' ? key : undefined });
if (path === '/health') return this.json(res, 200, { status: 'ok' });
if (req.headers.authorization !== `Bearer ${this.apiKey}`) {
return this.json(res, 401, { error: { message: 'Invalid API key', code: 'invalid_api_key' } });
}
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk as Buffer);
const raw = Buffer.concat(chunks).toString('utf8');
if (req.method === 'POST' && path === '/v1/runs') return this.submit(req, res, raw);
const match = /^\/v1\/runs\/([^/]+)(\/stop)?$/.exec(path);
if (match) {
const run = this.runs.get(decodeURIComponent(match[1]!));
if (req.method === 'GET' && !match[2]) {
if (this.statusDown) return this.json(res, 503, { error: { message: 'storage_unavailable' } });
if (!run) return this.json(res, 404, { error: { message: 'Run not found', code: 'run_not_found' } });
return this.json(res, 200, {
object: 'hermes.run',
run_id: run.runId,
status: run.status,
session_id: run.sessionId,
...(run.output ? { output: run.output } : {}),
...run.extra,
});
}
if (req.method === 'POST' && match[2]) {
if (!run) return this.json(res, 404, { error: { message: 'Run not found', code: 'run_not_found' } });
if (['completed', 'failed', 'cancelled', 'interrupted'].includes(run.status)) {
return this.json(res, 200, { run_id: run.runId, status: run.status });
}
if (!this.stopIgnored) {
run.stopRequested = true;
run.status = 'stopping';
if (run.timer) clearTimeout(run.timer);
run.timer = setTimeout(() => {
run.status = 'cancelled';
run.extra = { completed: false, partial: false, interrupted: true };
}, 25);
}
return this.json(res, 200, { run_id: run.runId, status: 'stopping' });
}
}
this.json(res, 404, { error: { message: 'not found' } });
}
private submit(req: IncomingMessage, res: ServerResponse, raw: string): void {
const key = String(req.headers['idempotency-key'] ?? '');
const fault = this.submitFaults.shift();
if (fault === 'http_503') return this.json(res, 503, { error: { message: 'runtime_draining' } }, { 'Retry-After': '1' });
if (fault === 'http_400') return this.json(res, 400, { error: { message: "Missing 'input' field" } });
let body: { input?: string; session_id?: string; instructions?: string };
try {
body = JSON.parse(raw);
} catch {
return this.json(res, 400, { error: { message: 'Invalid JSON' } });
}
if (!body.input) return this.json(res, 400, { error: { message: "Missing 'input' field" } });
const existing = key ? this.byKey.get(key) : undefined;
let run: FakeRun;
let replayed = false;
if (existing) {
if (existing.body !== raw) {
return this.json(res, 409, {
error: { message: 'Idempotency-Key was already used with a different request payload', code: 'idempotency_key_conflict' },
});
}
run = existing;
replayed = true;
} else {
const sessionId = body.session_id || `run-session-${this.seq}`;
run = {
runId: `run_${String(++this.seq).padStart(6, '0')}`,
key,
body: raw,
sessionId,
input: body.input,
status: 'running',
output: '',
extra: {},
stopRequested: false,
timer: null,
};
this.runs.set(run.runId, run);
if (key) this.byKey.set(key, run);
// The turn "executes" exactly once, at admission.
this.executions += 1;
const history = this.sessions.get(sessionId) ?? [];
this.sessions.set(sessionId, history);
const script = this.script.shift() ?? this.defaultScript;
const defaultOutput = `FAKE-ANSWER turn=${history.length + 1} previous=${JSON.stringify(history.at(-1) ?? null)} input=${JSON.stringify(body.input)}`;
history.push(body.input);
this.finishLater(run, script, defaultOutput);
}
// Admitted, but the answer never reaches the caller.
if (fault === 'drop_response') return void res.destroy();
if (fault === 'http_500') return this.json(res, 500, { error: { message: 'boom' } });
this.json(res, 202, { run_id: run.runId, status: replayed ? run.status : 'started', replayed }, replayed ? { 'Idempotency-Replayed': 'true' } : {});
}
private finishLater(run: FakeRun, script: Script, defaultOutput = ''): void {
const settle = (fn: () => void, afterMs = 30) => {
run.timer = setTimeout(() => {
if (!run.stopRequested) fn();
}, afterMs);
};
switch (script.kind) {
case 'complete':
return settle(() => {
run.status = 'completed';
run.output = script.output ?? defaultOutput;
run.extra = { completed: true, partial: false, interrupted: false };
}, script.afterMs);
case 'fail':
return settle(() => {
run.status = 'failed';
run.extra = { completed: false, partial: false, interrupted: false, error: script.error ?? 'agent run failed' };
}, script.afterMs);
case 'incomplete':
return settle(() => {
run.status = 'failed';
run.output = script.output;
run.extra = { completed: false, partial: true, interrupted: false, turn_exit_reason: 'max_iterations' };
}, script.afterMs);
case 'approval':
run.status = 'waiting_for_approval';
return;
case 'unknown':
return settle(() => {
run.status = 'unknown';
}, script.afterMs);
case 'interrupted':
return settle(() => {
run.status = 'interrupted';
run.extra = { error: 'Gateway shutdown interrupted the run.' };
}, script.afterMs);
case 'hang':
return;
}
}
}
+84
View File
@@ -0,0 +1,84 @@
import { createServer, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
/**
* TEST FAKE. Not a speech recogniser.
*
* Accepts the OpenAI-style `POST /audio/transcriptions` multipart upload,
* checks that what arrived really is a 16 kHz mono 16-bit WAV, and returns a
* scripted transcript. It proves the bridge's upload format and failure
* handling, and nothing about real transcription quality or latency.
*/
export class FakeStt {
readonly apiKey = 'fake-stt-key';
calls = 0;
lastWav: { sampleRate: number; channels: number; bitsPerSample: number; dataBytes: number } | null = null;
lastFields: Record<string, string> = {};
private replies: Array<{ text?: string; status?: number; delayMs?: number }> = [];
private server: Server | null = null;
url = '';
async start(): Promise<void> {
this.server = createServer(async (req, res) => {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk as Buffer);
const body = Buffer.concat(chunks);
if (req.method !== 'POST' || !req.url?.endsWith('/audio/transcriptions')) {
res.writeHead(404).end();
return;
}
if (req.headers.authorization !== `Bearer ${this.apiKey}`) {
res.writeHead(401, { 'Content-Type': 'application/json' }).end('{"error":"unauthorized"}');
return;
}
this.calls += 1;
const riff = body.indexOf('RIFF');
if (riff >= 0 && body.toString('ascii', riff + 8, riff + 12) === 'WAVE') {
this.lastWav = {
channels: body.readUInt16LE(riff + 22),
sampleRate: body.readUInt32LE(riff + 24),
bitsPerSample: body.readUInt16LE(riff + 34),
dataBytes: body.readUInt32LE(riff + 40),
};
} else {
this.lastWav = null;
}
const text = body.toString('latin1');
this.lastFields = {};
for (const m of text.matchAll(/name="(model|language|response_format)"\r\n\r\n([^\r]*)\r\n/g)) {
this.lastFields[m[1]!] = m[2]!;
}
const reply = this.replies.shift() ?? { text: 'what is the capital of france' };
if (reply.delayMs) await new Promise((r) => setTimeout(r, reply.delayMs));
if (res.destroyed) return;
if (reply.status && reply.status !== 200) {
res.writeHead(reply.status, { 'Content-Type': 'application/json' }).end('{"error":"scripted failure"}');
return;
}
res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ text: reply.text ?? '' }));
});
await new Promise<void>((resolve) => this.server!.listen(0, '127.0.0.1', resolve));
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
}
next(...replies: Array<{ text?: string; status?: number; delayMs?: number }>): void {
this.replies.push(...replies);
}
async stop(): Promise<void> {
const server = this.server;
this.server = null;
if (server) {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
}
}
/** Deterministic synthetic PCM (a sine tone). Stands in for speech in tests; it is not speech. */
export function syntheticPcm(seconds: number, sampleRate = 16000): Buffer {
const samples = Math.floor(seconds * sampleRate);
const buf = Buffer.alloc(samples * 2);
for (let i = 0; i < samples; i++) buf.writeInt16LE(Math.round(Math.sin((2 * Math.PI * 440 * i) / sampleRate) * 8000), i * 2);
return buf;
}
+98
View File
@@ -0,0 +1,98 @@
import { createServer, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
/**
* TEST STUB. Not a language model.
*
* A minimal OpenAI-compatible chat endpoint so a REAL Hermes gateway can run
* whole agent turns without any provider account or cost. Its "answer" is a
* deterministic description of the conversation it was handed, which is how
* the real-Hermes test proves that Hermes itself carried the earlier turns.
*/
export class StubLlm {
/** Agent turns served. */
calls = 0;
auxiliaryCalls = 0;
delayMs = 0;
/** User messages seen in the most recent request, oldest first. */
lastUserMessages: string[] = [];
lastSystem = '';
private server: Server | null = null;
url = '';
async start(): Promise<void> {
this.server = createServer(async (req, res) => {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk as Buffer);
const path = (req.url ?? '').split('?')[0]!;
if (req.method === 'GET' && path.endsWith('/models')) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ object: 'list', data: [{ id: 'stub-model', object: 'model', owned_by: 'hermeven-test' }] }));
return;
}
if (req.method !== 'POST' || !path.endsWith('/chat/completions')) {
res.writeHead(404, { 'Content-Type': 'application/json' }).end('{"error":{"message":"not found"}}');
return;
}
let body: { messages?: Array<{ role: string; content: unknown }>; stream?: boolean; model?: string };
try {
body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
} catch {
res.writeHead(400).end('{}');
return;
}
const text = (c: unknown): string =>
typeof c === 'string' ? c : Array.isArray(c) ? c.map((p) => (p && typeof p === 'object' && 'text' in p ? String((p as { text: unknown }).text) : '')).join('') : '';
const messages = body.messages ?? [];
const users = messages.filter((m) => m.role === 'user').map((m) => text(m.content));
// Hermes also calls the model for housekeeping (naming the chat, compressing history).
// Those are not agent turns and must not be counted as executions.
const system = text(messages.find((m) => m.role === 'system')?.content).slice(0, 600);
const isTurn = users.length > 0 && !/you name chat sessions|generate a (short )?title|summari[sz]e/i.test(system);
if (!isTurn) this.auxiliaryCalls += 1;
if (isTurn) {
this.calls += 1;
this.lastUserMessages = users;
this.lastSystem = messages.filter((m) => m.role === 'system').map((m) => text(m.content)).join('\n');
}
const answer = `STUB-ANSWER users=${users.length} first=${JSON.stringify(users[0] ?? null)} last=${JSON.stringify(users.at(-1) ?? null)}`;
if (this.delayMs) await new Promise((r) => setTimeout(r, this.delayMs));
if (res.destroyed) return;
const id = `chatcmpl-stub-${this.calls}`;
const created = Math.floor(Date.now() / 1000);
const usage = { prompt_tokens: 10, completion_tokens: 10, total_tokens: 20 };
if (body.stream) {
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' });
const chunk = (delta: object, finish: string | null, extra: object = {}) =>
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model: body.model ?? 'stub-model', choices: [{ index: 0, delta, finish_reason: finish }], ...extra })}\n\n`);
chunk({ role: 'assistant', content: '' }, null);
chunk({ content: answer }, null);
chunk({}, 'stop', { usage });
res.end('data: [DONE]\n\n');
return;
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(
JSON.stringify({
id,
object: 'chat.completion',
created,
model: body.model ?? 'stub-model',
choices: [{ index: 0, message: { role: 'assistant', content: answer }, finish_reason: 'stop' }],
usage,
}),
);
});
await new Promise<void>((resolve) => this.server!.listen(0, '127.0.0.1', resolve));
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}/v1`;
}
async stop(): Promise<void> {
const server = this.server;
this.server = null;
if (server) {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
}
}
+648
View File
@@ -0,0 +1,648 @@
import { randomUUID } from 'node:crypto';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { check, DeviceStatusResponse, SCHEMA_VERSION, TurnResult } from '@hermeven/contracts';
import { syntheticPcm } from '../fakes/fakeStt.ts';
import { createHarness, type Harness } from './harness.ts';
/**
* Bridge behaviour over real HTTP, with the real Hermes Runs adapter and the real
* STT adapter talking to TEST FAKES. Evidence about Hermeven's own logic only.
*/
let h: Harness;
afterEach(async () => {
await h?.close();
});
describe('health, auth and binding', () => {
beforeEach(async () => {
h = await createHarness();
});
it('healthz is minimal and unauthenticated', async () => {
const res = await h.api('GET', '/healthz');
expect(res.status).toBe(200);
expect(res.body).toEqual({ status: 'ok', schema_version: SCHEMA_VERSION });
});
it('rejects missing, malformed and unknown credentials', async () => {
expect((await h.api('GET', '/v1/device')).status).toBe(401);
expect((await h.api('GET', '/v1/device', { token: 'hvn_nope' })).status).toBe(401);
expect((await h.api('GET', '/v1/device', { headers: { Authorization: 'Basic abc' } })).status).toBe(401);
const turn = await h.textTurn('hvn_nope', randomUUID(), 'hi');
expect(turn.status).toBe(401);
expect(turn.body.error.code).toBe('unauthorized');
expect(h.hermes.executions).toBe(0);
});
it('device status matches the contract and exposes no secrets', async () => {
const cred = await h.pair();
const res = await h.api('GET', '/v1/device', { token: cred.token });
expect(res.status).toBe(200);
expect(check(DeviceStatusResponse, res.body)).toBe(true);
expect(res.body.agent_reachable).toBe(true);
expect(res.body.stt_configured).toBe(true);
const text = JSON.stringify(res.body);
expect(text).not.toContain(h.hermes.apiKey);
expect(text).not.toContain(h.stt.apiKey);
expect(text).not.toContain(h.hermes.url);
});
it('a device cannot use, read or cancel another device’s conversation or turn', async () => {
const a = await h.pair('a');
const b = await h.pair('b');
const convA = await h.conversation(a.token);
h.hermes.next({ kind: 'hang' });
const turnA = await h.textTurn(a.token, convA, 'private question');
expect(turnA.status).toBe(202);
const id = turnA.body.request_id;
expect((await h.textTurn(b.token, convA, 'intrude')).body.error.code).toBe('not_found');
expect((await h.api('GET', `/v1/turns/${id}`, { token: b.token })).status).toBe(404);
expect((await h.api('POST', `/v1/turns/${id}/cancel`, { token: b.token, json: {} })).status).toBe(404);
// Reusing A's request id from B is a conflict and never reveals A's turn.
const reuse = await h.textTurn(b.token, await h.conversation(b.token), 'private question', id);
expect(reuse.status).toBe(409);
expect(reuse.body.error.code).toBe('request_id_conflict');
expect(JSON.stringify(reuse.body)).not.toContain('private');
await h.api('POST', `/v1/turns/${id}/cancel`, { token: a.token, json: {} });
await h.waitTerminal(a.token, id);
});
it('never forwards a client-chosen Hermes session: unknown fields are rejected', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
const res = await h.api('POST', '/v1/turns', {
token: cred.token,
json: {
schema_version: SCHEMA_VERSION,
request_id: randomUUID(),
conversation_id: conv,
locale: 'en-US',
input: { kind: 'text', text: 'hi' },
session_id: 'someone-elses-session',
},
});
expect(res.status).toBe(400);
expect(h.hermes.executions).toBe(0);
});
it('revocation takes effect immediately and closes the conversation', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
expect((await h.api('DELETE', '/v1/device', { token: cred.token })).body).toEqual({ schema_version: 1, revoked: true });
expect((await h.api('GET', '/v1/device', { token: cred.token })).status).toBe(401);
expect((await h.textTurn(cred.token, conv, 'hi')).status).toBe(401);
expect(h.hermes.executions).toBe(0);
});
it('renewal rotates the token; the old one stops working', async () => {
const cred = await h.pair();
const renewed = await h.api('POST', '/v1/device/renew', { token: cred.token, json: {} });
expect(renewed.status).toBe(200);
expect(renewed.body.token).not.toBe(cred.token);
expect((await h.api('GET', '/v1/device', { token: cred.token })).status).toBe(401);
expect((await h.api('GET', '/v1/device', { token: renewed.body.token })).status).toBe(200);
});
it('CORS allows only the configured origin and is not a substitute for auth', async () => {
const ok = await h.api('OPTIONS', '/v1/turns', {
headers: { Origin: 'https://app.example', 'Access-Control-Request-Method': 'POST', 'Access-Control-Request-Headers': 'authorization,content-type' },
});
expect(ok.headers.get('access-control-allow-origin')).toBe('https://app.example');
const bad = await h.api('OPTIONS', '/v1/turns', {
headers: { Origin: 'https://evil.example', 'Access-Control-Request-Method': 'POST' },
});
expect(bad.headers.get('access-control-allow-origin')).toBeNull();
const authed = await h.api('GET', '/v1/device', { headers: { Origin: 'https://app.example' } });
expect(authed.status).toBe(401);
});
});
describe('pairing', () => {
it('codes are single-use', async () => {
h = await createHarness();
const { code } = h.bridge.devices.createPairingCode();
const claim = () => h.api('POST', '/v1/pairing/claim', { json: { schema_version: 1, code, device_name: 'x' } });
expect((await claim()).status).toBe(201);
const second = await claim();
expect(second.status).toBe(401);
expect(second.body.error.code).toBe('pairing_invalid');
});
it('wrong guesses burn the outstanding code', async () => {
h = await createHarness({ env: { HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE: '50', HERMEVEN_PAIRING_CODE_MAX_FAILURES: '3' } });
const { code } = h.bridge.devices.createPairingCode();
const guess = (c: string) => h.api('POST', '/v1/pairing/claim', { json: { schema_version: 1, code: c, device_name: 'x' } });
expect((await guess('AAAAA-AAAAA')).body.error.code).toBe('pairing_invalid');
expect((await guess('AAAAA-AAAAB')).body.error.code).toBe('pairing_invalid');
expect((await guess('AAAAA-AAAAC')).body.error.code).toBe('pairing_locked');
// The real code no longer works.
expect((await guess(code)).status).toBe(401);
});
it('claim attempts are rate limited per client', async () => {
h = await createHarness({ env: { HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE: '2' } });
const guess = () => h.api('POST', '/v1/pairing/claim', { json: { schema_version: 1, code: 'AAAAA-AAAAA', device_name: 'x' } });
await guess();
await guess();
const third = await guess();
expect(third.status).toBe(429);
expect(third.body.error.code).toBe('rate_limited');
});
});
describe('validation and limits', () => {
beforeEach(async () => {
h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2', HERMEVEN_TURNS_PER_MINUTE: '3' } });
});
it('rejects unknown schema versions', async () => {
const cred = await h.pair();
const res = await h.api('POST', '/v1/turns', {
token: cred.token,
json: { schema_version: 2, request_id: randomUUID(), conversation_id: randomUUID(), locale: 'en-US', input: { kind: 'text', text: 'hi' } },
});
expect(res.status).toBe(400);
expect(res.body.error.code).toBe('unsupported_schema_version');
});
it('rejects oversized audio, odd byte counts, wrong formats and wrong content types', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
// Cap is 2 s (+1 s headroom) = 96,000 bytes.
const big = await h.audioTurn(cred.token, conv, syntheticPcm(4));
expect(big.status).toBe(413);
expect(big.body.error.code).toBe('payload_too_large');
const odd = await h.audioTurn(cred.token, conv, Buffer.alloc(1001));
expect(odd.status).toBe(400);
const rate = await h.audioTurn(cred.token, conv, syntheticPcm(0.5), randomUUID(), { sample_rate: '44100' });
expect(rate.status).toBe(415);
expect(rate.body.error.code).toBe('unsupported_media');
const type = await h.api('POST', '/v1/turns', { token: cred.token, body: Buffer.from('x'), headers: { 'Content-Type': 'text/plain' } });
expect(type.status).toBe(415);
const bigJson = await h.textTurn(cred.token, conv, 'x'.repeat(5000));
expect(bigJson.status).toBe(400);
expect(h.hermes.executions).toBe(0);
expect(h.stt.calls).toBe(0);
});
it('rate limits new turns per device but never a duplicate of an existing one', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
const ids: string[] = [];
for (let i = 0; i < 3; i++) {
const res = await h.textTurn(cred.token, conv, `q${i}`);
expect(res.status).toBe(202);
ids.push(res.body.request_id);
await h.waitTerminal(cred.token, res.body.request_id);
}
const over = await h.textTurn(cred.token, conv, 'q4');
expect(over.status).toBe(429);
const dup = await h.textTurn(cred.token, conv, 'q0', ids[0]);
expect(dup.status).toBe(200);
expect(dup.body.replayed).toBe(true);
expect(h.hermes.executions).toBe(3);
});
});
describe('turn lifecycle', () => {
beforeEach(async () => {
h = await createHarness();
});
it('typed text -> agent -> complete answer, result matches the contract', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
const long = 'Paris. '.repeat(900); // ~6 kB: must come back untruncated
h.hermes.next({ kind: 'complete', output: long });
const res = await h.textTurn(cred.token, conv, 'What is the capital of France?');
expect(res.status).toBe(202);
const done = await h.waitTerminal(cred.token, res.body.request_id);
expect(check(TurnResult, done)).toBe(true);
expect(done.outcome).toBe('succeeded');
expect(done.answer_text).toBe(long);
expect(done.error).toBeNull();
expect(done.timings.agent_ms).toBeGreaterThanOrEqual(0);
// Hermes received our own opaque session id and the forwarded idempotency key.
const run = h.hermes.lastRun()!;
expect(run.sessionId).toMatch(/^hermeven-[0-9a-f-]{36}$/);
expect(run.key).toBe(`hermeven-turn-${res.body.request_id}`);
});
it('audio -> STT -> agent: uploads a valid 16 kHz mono WAV and sends the transcript', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.stt.next({ text: 'how tall is mount everest' });
const res = await h.audioTurn(cred.token, conv, syntheticPcm(1.5));
expect(res.status).toBe(202);
const done = await h.waitTerminal(cred.token, res.body.request_id);
expect(done.outcome).toBe('succeeded');
expect(done.input_text).toBe('how tall is mount everest');
expect(h.stt.lastWav).toEqual({ sampleRate: 16000, channels: 1, bitsPerSample: 16, dataBytes: 48000 });
expect(h.stt.lastFields).toMatchObject({ model: 'fake-whisper', language: 'en' });
expect(h.hermes.lastRun()!.input).toBe('how tall is mount everest');
expect(done.timings.transcribe_ms).toBeGreaterThanOrEqual(0);
});
it('a follow-up lands in the same Hermes session; a new conversation gets a fresh one', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
const first = await h.textTurn(cred.token, conv, 'My name is Ada.');
await h.waitTerminal(cred.token, first.body.request_id);
const second = await h.textTurn(cred.token, conv, 'What is my name?');
const answer = await h.waitTerminal(cred.token, second.body.request_id);
// The fake echoes the previous input of the same session.
expect(answer.answer_text).toContain('turn=2');
expect(answer.answer_text).toContain('previous="My name is Ada."');
const conv2 = await h.conversation(cred.token);
expect(conv2).not.toBe(conv);
const third = await h.textTurn(cred.token, conv2, 'What is my name?');
const fresh = await h.waitTerminal(cred.token, third.body.request_id);
expect(fresh.answer_text).toContain('turn=1');
expect(fresh.answer_text).toContain('previous=null');
// The old conversation is closed, not silently reused.
const stale = await h.textTurn(cred.token, conv, 'still there?');
expect(stale.status).toBe(409);
expect(stale.body.error.code).toBe('conversation_closed');
expect(h.hermes.sessions.size).toBe(2);
});
it('turns in one conversation are serialised', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.hermes.next({ kind: 'complete', afterMs: 200 });
const first = await h.textTurn(cred.token, conv, 'one');
const second = await h.textTurn(cred.token, conv, 'two');
expect(second.status).toBe(409);
expect(second.body.error.code).toBe('conversation_busy');
await h.waitTerminal(cred.token, first.body.request_id);
expect(h.hermes.executions).toBe(1);
});
it('distinguishes failed, incomplete, interrupted and unknown agent outcomes', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
const run = async (text: string) => {
const res = await h.textTurn(cred.token, conv, text);
return h.waitTerminal(cred.token, res.body.request_id);
};
h.hermes.next({ kind: 'fail', error: 'provider said sk-secret-123' });
const failed = await run('a');
expect(failed.outcome).toBe('failed');
expect(failed.error).toMatchObject({ code: 'agent_failed', retryable: false });
// Hermes' diagnostic text is never relayed to the client.
expect(JSON.stringify(failed)).not.toContain('sk-secret-123');
h.hermes.next({ kind: 'incomplete', output: 'So far I found two of three.' });
const incomplete = await run('b');
expect(incomplete.outcome).toBe('incomplete');
expect(incomplete.answer_text).toBe('So far I found two of three.');
expect(incomplete.error?.code).toBe('agent_incomplete');
h.hermes.next({ kind: 'interrupted' });
const interrupted = await run('c');
expect(interrupted.outcome).toBe('failed');
expect(interrupted.error?.code).toBe('agent_interrupted');
h.hermes.next({ kind: 'unknown' });
const unknown = await run('d');
expect(unknown.outcome).toBe('unknown');
expect(unknown.error).toMatchObject({ code: 'outcome_unknown', retryable: false });
});
it('approval-required is surfaced, never auto-approved, and resolves when approved elsewhere', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.hermes.next({ kind: 'approval' });
const res = await h.textTurn(cred.token, conv, 'delete the file');
const waiting = await h.waitState(cred.token, res.body.request_id, 'approval_required');
expect(waiting.terminal).toBe(false);
expect(h.hermes.requests.some((r) => r.path.endsWith('/approval'))).toBe(false);
h.hermes.approve(h.hermes.lastRun()!.runId, 'file deleted');
const done = await h.waitTerminal(cred.token, res.body.request_id);
expect(done.outcome).toBe('succeeded');
expect(done.answer_text).toBe('file deleted');
});
it('an approval that never arrives ends as stopped, with a distinct code', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.hermes.next({ kind: 'approval' });
const res = await h.textTurn(cred.token, conv, 'delete the file');
const done = await h.waitTerminal(cred.token, res.body.request_id);
expect(done.outcome).toBe('cancelled');
expect(done.error?.code).toBe('approval_timeout');
expect(h.hermes.requests.some((r) => r.path.endsWith('/approval'))).toBe(false);
});
it('agent deadline: stop is requested and confirmed; unconfirmed stop is unknown, not replayed', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.hermes.next({ kind: 'hang' });
const a = await h.textTurn(cred.token, conv, 'slow');
const timedOut = await h.waitTerminal(cred.token, a.body.request_id);
expect(timedOut.outcome).toBe('cancelled');
expect(timedOut.error?.code).toBe('agent_timeout');
h.hermes.next({ kind: 'hang' });
h.hermes.ignoreStop();
const b = await h.textTurn(cred.token, conv, 'slow and stubborn');
const unknown = await h.waitTerminal(cred.token, b.body.request_id);
expect(unknown.outcome).toBe('unknown');
expect(unknown.error?.code).toBe('outcome_unknown');
expect(h.hermes.executions).toBe(2);
});
});
describe('STT failures', () => {
beforeEach(async () => {
h = await createHarness();
});
it('provider error, empty transcript and timeout each fail cleanly without reaching the agent', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
const run = async () => {
const res = await h.audioTurn(cred.token, conv, syntheticPcm(0.5));
return h.waitTerminal(cred.token, res.body.request_id);
};
h.stt.next({ status: 500 });
expect((await run()).error).toMatchObject({ code: 'stt_unavailable', retryable: true });
h.stt.next({ status: 400 });
expect((await run()).error?.code).toBe('stt_failed');
h.stt.next({ text: ' ' });
expect((await run()).error?.code).toBe('stt_empty');
h.stt.next({ delayMs: 1500, text: 'too late' });
expect((await run()).error?.code).toBe('stt_timeout');
expect(h.hermes.executions).toBe(0);
});
it('with no STT configured, audio fails cleanly and typed text still works', async () => {
await h.close();
h = await createHarness({ stt: false });
const cred = await h.pair();
const conv = await h.conversation(cred.token);
const audio = await h.audioTurn(cred.token, conv, syntheticPcm(0.5));
expect((await h.waitTerminal(cred.token, audio.body.request_id)).error?.code).toBe('stt_unavailable');
const text = await h.textTurn(cred.token, conv, 'hello');
expect((await h.waitTerminal(cred.token, text.body.request_id)).outcome).toBe('succeeded');
});
});
describe('duplicates, retries, cancellation and recovery', () => {
beforeEach(async () => {
h = await createHarness();
});
it('duplicate submits of one request id execute once', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
const id = randomUUID();
const results = await Promise.all(Array.from({ length: 8 }, () => h.textTurn(cred.token, conv, 'run the tool', id)));
expect(results.filter((r) => r.status === 202)).toHaveLength(1);
expect(results.filter((r) => r.status === 200 && r.body.replayed)).toHaveLength(7);
await h.waitTerminal(cred.token, id);
const late = await h.textTurn(cred.token, conv, 'run the tool', id);
expect(late.status).toBe(200);
expect(late.body.outcome).toBe('succeeded');
expect(h.hermes.executions).toBe(1);
// Same id, different payload: refused.
const conflict = await h.textTurn(cred.token, conv, 'run a different tool', id);
expect(conflict.status).toBe(409);
expect(h.hermes.executions).toBe(1);
});
it('a lost Hermes response is retried under the same idempotency key: one execution', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.hermes.failNextSubmit('drop_response', 'http_500');
const res = await h.textTurn(cred.token, conv, 'charge the card');
const done = await h.waitTerminal(cred.token, res.body.request_id);
expect(done.outcome).toBe('succeeded');
expect(h.hermes.executions).toBe(1);
const posts = h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs');
expect(posts).toHaveLength(3);
expect(new Set(posts.map((p) => p.idempotencyKey)).size).toBe(1);
});
it('if no answer to the submit ever arrives, the deadline ends as unknown, never as "safe to retry"', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.hermes.failNextSubmit(...Array(500).fill('drop_response'));
const res = await h.textTurn(cred.token, conv, 'send the email');
const done = await h.waitTerminal(cred.token, res.body.request_id);
expect(done.outcome).toBe('unknown');
expect(done.error).toMatchObject({ code: 'outcome_unknown', retryable: false });
// Hermes did run it (once); the bridge could not know, and said so.
expect(h.hermes.executions).toBe(1);
const posts = h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs');
expect(posts.length).toBeGreaterThan(1);
expect(new Set(posts.map((p) => p.idempotencyKey)).size).toBe(1);
});
it('busy Hermes (503) is retried; a 4xx rejection is final and nothing ran', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.hermes.failNextSubmit('http_503', 'http_503');
const ok = await h.textTurn(cred.token, conv, 'hello');
expect((await h.waitTerminal(cred.token, ok.body.request_id)).outcome).toBe('succeeded');
h.hermes.failNextSubmit('http_400');
const bad = await h.textTurn(cred.token, conv, 'hello again');
const rejected = await h.waitTerminal(cred.token, bad.body.request_id);
expect(rejected.error?.code).toBe('agent_rejected');
expect(h.hermes.executions).toBe(1);
});
it('Hermes down before anything was sent: fails as retryable, provably nothing ran', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
await h.hermes.stop();
const res = await h.textTurn(cred.token, conv, 'anyone there');
const done = await h.waitTerminal(cred.token, res.body.request_id);
expect(done.outcome).toBe('failed');
expect(done.error).toMatchObject({ code: 'agent_unreachable', retryable: true });
expect(h.hermes.executions).toBe(0);
});
it('cancel during transcription is clean and never reaches the agent', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.stt.next({ delayMs: 300, text: 'never used' });
const res = await h.audioTurn(cred.token, conv, syntheticPcm(0.5));
await h.waitState(cred.token, res.body.request_id, 'transcribing');
const cancel = await h.api('POST', `/v1/turns/${res.body.request_id}/cancel`, { token: cred.token, json: {} });
expect(cancel.status).toBe(200);
const done = await h.waitTerminal(cred.token, res.body.request_id);
expect(done.outcome).toBe('cancelled');
expect(done.error).toBeNull();
expect(h.hermes.executions).toBe(0);
});
it('cancel while the agent runs asks Hermes to stop; repeated cancels are idempotent', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.hermes.next({ kind: 'hang' });
const res = await h.textTurn(cred.token, conv, 'long job');
await h.waitState(cred.token, res.body.request_id, 'thinking');
const cancels = await Promise.all(
Array.from({ length: 5 }, () => h.api('POST', `/v1/turns/${res.body.request_id}/cancel`, { token: cred.token, json: {} })),
);
expect(cancels.every((c) => c.status === 200 && c.body.cancel_requested)).toBe(true);
const done = await h.waitTerminal(cred.token, res.body.request_id);
expect(done.outcome).toBe('cancelled');
expect(done.cancel_requested).toBe(true);
expect(h.hermes.requests.filter((r) => r.path.endsWith('/stop'))).toHaveLength(1);
// Cancelling a finished turn changes nothing.
const after = await h.api('POST', `/v1/turns/${res.body.request_id}/cancel`, { token: cred.token, json: {} });
expect(after.body.outcome).toBe('cancelled');
// The conversation is usable again.
const next = await h.textTurn(cred.token, conv, 'next');
expect((await h.waitTerminal(cred.token, next.body.request_id)).outcome).toBe('succeeded');
});
it('a cancel that loses the race reports what really happened', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.hermes.next({ kind: 'complete', afterMs: 60, output: 'already done' });
h.hermes.ignoreStop();
const res = await h.textTurn(cred.token, conv, 'quick job');
await h.waitState(cred.token, res.body.request_id, 'thinking');
await h.api('POST', `/v1/turns/${res.body.request_id}/cancel`, { token: cred.token, json: {} });
const done = await h.waitTerminal(cred.token, res.body.request_id);
expect(done.outcome).toBe('succeeded');
expect(done.cancel_requested).toBe(true);
expect(done.answer_text).toBe('already done');
});
it('bridge restart mid-run re-attaches to the same run: one execution, answer delivered', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.hermes.next({ kind: 'complete', afterMs: 400, output: 'survived the restart' });
const res = await h.textTurn(cred.token, conv, 'long job');
await h.waitState(cred.token, res.body.request_id, 'thinking');
await h.restartBridge();
const done = await h.waitTerminal(cred.token, res.body.request_id);
expect(done.outcome).toBe('succeeded');
expect(done.answer_text).toBe('survived the restart');
expect(h.hermes.executions).toBe(1);
});
it('bridge crash between sending and recording the run id replays the same key, not a new run', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.hermes.next({ kind: 'complete', afterMs: 300, output: 'only once' });
// Hermes admits the run but the bridge never learns the run id, then the bridge dies.
h.hermes.failNextSubmit('drop_response', 'drop_response', 'drop_response', 'drop_response');
const res = await h.textTurn(cred.token, conv, 'transfer money');
await new Promise((r) => setTimeout(r, 80));
expect(h.hermes.executions).toBe(1);
await h.restartBridge();
h.hermes.failNextSubmit(); // no more faults
const done = await h.waitTerminal(cred.token, res.body.request_id);
expect(done.outcome).toBe('succeeded');
expect(done.answer_text).toBe('only once');
expect(h.hermes.executions).toBe(1);
});
it('bridge restart during transcription fails the turn as provably-not-run', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.stt.next({ delayMs: 350, text: 'lost' });
const res = await h.audioTurn(cred.token, conv, syntheticPcm(0.5));
await h.waitState(cred.token, res.body.request_id, 'transcribing');
await h.restartBridge();
const done = await h.waitTerminal(cred.token, res.body.request_id);
expect(done.outcome).toBe('failed');
expect(done.error).toMatchObject({ code: 'interrupted_before_agent', retryable: true });
expect(h.hermes.executions).toBe(0);
});
it('if Hermes no longer knows the run, the outcome is unknown and nothing is resent', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.hermes.next({ kind: 'hang' });
const res = await h.textTurn(cred.token, conv, 'job');
await h.waitState(cred.token, res.body.request_id, 'thinking');
h.hermes.forgetRuns();
const done = await h.waitTerminal(cred.token, res.body.request_id);
expect(done.outcome).toBe('unknown');
expect(h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs')).toHaveLength(1);
});
it('status outage during a run is ridden out without resubmitting', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.hermes.next({ kind: 'complete', afterMs: 250, output: 'fine' });
const res = await h.textTurn(cred.token, conv, 'job');
await h.waitState(cred.token, res.body.request_id, 'thinking');
h.hermes.setStatusDown(true);
await new Promise((r) => setTimeout(r, 200));
h.hermes.setStatusDown(false);
const done = await h.waitTerminal(cred.token, res.body.request_id);
expect(done.outcome).toBe('succeeded');
expect(h.hermes.executions).toBe(1);
});
});
describe('logging and retention', () => {
it('logs carry ids, states and timings but never questions, answers, audio, tokens or keys', async () => {
h = await createHarness();
const cred = await h.pair('pocket-g2');
const conv = await h.conversation(cred.token);
h.stt.next({ text: 'SECRET-TRANSCRIPT-zebra' });
h.hermes.next({ kind: 'complete', output: 'SECRET-ANSWER-giraffe' });
const audio = await h.audioTurn(cred.token, conv, syntheticPcm(0.5));
await h.waitTerminal(cred.token, audio.body.request_id);
h.hermes.next({ kind: 'fail', error: 'SECRET-DIAGNOSTIC-okapi' });
const text = await h.textTurn(cred.token, conv, 'SECRET-QUESTION-lemur');
await h.waitTerminal(cred.token, text.body.request_id);
await h.api('GET', '/v1/device', { token: 'hvn_SECRET-BAD-TOKEN' });
const all = h.logs.join('');
expect(all).toContain(audio.body.request_id);
expect(all).toContain('turn.done');
expect(all).toContain('transcribe_ms');
for (const secret of ['zebra', 'giraffe', 'okapi', 'lemur', 'SECRET-BAD-TOKEN', cred.token, h.hermes.apiKey, h.stt.apiKey]) {
expect(all).not.toContain(secret);
}
});
it('cached question and answer text is dropped after the retention window', async () => {
h = await createHarness({ env: { HERMEVEN_RESULT_RETENTION_SECONDS: '10' } });
const cred = await h.pair();
const conv = await h.conversation(cred.token);
const res = await h.textTurn(cred.token, conv, 'remember me?');
const done = await h.waitTerminal(cred.token, res.body.request_id);
expect(done.answer_text).toBeTruthy();
// Age the row past retention, then run the same purge the bridge runs every minute.
h.bridge.db.prepare('UPDATE turns SET completed_at = completed_at - 11000').run();
expect(h.bridge.engine.purgeExpired()).toBe(1);
const after = await h.api('GET', `/v1/turns/${res.body.request_id}`, { token: cred.token });
expect(after.body.outcome).toBe('succeeded');
expect(after.body.answer_text).toBeNull();
expect(after.body.input_text).toBeNull();
const row = h.bridge.db.prepare('SELECT pending_body, input_text, answer_text FROM turns').get();
expect(row).toEqual({ pending_body: null, input_text: null, answer_text: null });
});
it('the exact Hermes body is held only until the run id is recorded', async () => {
h = await createHarness();
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.hermes.next({ kind: 'hang' });
const res = await h.textTurn(cred.token, conv, 'hold on');
await h.waitState(cred.token, res.body.request_id, 'thinking');
await new Promise((r) => setTimeout(r, 60));
const row = h.bridge.db.prepare('SELECT pending_body, hermes_run_id FROM turns').get() as any;
expect(row.hermes_run_id).toBeTruthy();
expect(row.pending_body).toBeNull();
await h.api('POST', `/v1/turns/${res.body.request_id}/cancel`, { token: cred.token, json: {} });
await h.waitTerminal(cred.token, res.body.request_id);
});
});
+342
View File
@@ -0,0 +1,342 @@
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);
});
});
+181
View File
@@ -0,0 +1,181 @@
import { randomUUID } from 'node:crypto';
import { mkdtempSync, rmSync } from 'node:fs';
import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Writable } from 'node:stream';
import { pino } from 'pino';
import { SCHEMA_VERSION, type DeviceCredential, type TurnResult } from '@hermeven/contracts';
import { LOG_REDACT, createBridge, type Bridge } from '../../services/bridge/src/app.ts';
import { loadConfig, type BridgeConfig } from '../../services/bridge/src/config.ts';
import type { EngineTiming } from '../../services/bridge/src/turns.ts';
import { FakeHermes } from '../fakes/fakeHermes.ts';
import { FakeStt } from '../fakes/fakeStt.ts';
export const FAST: EngineTiming = {
transcribeDeadlineMs: 400,
agentDeadlineMs: 900,
approvalWaitMs: 500,
cancelGraceMs: 400,
pollIntervalMs: 20,
submitRetryMs: 30,
notSentAttempts: 3,
};
export interface Harness {
hermes: FakeHermes;
stt: FakeStt;
bridge: Bridge;
config: BridgeConfig;
url: string;
/** Every log line the bridge wrote, for redaction assertions. */
logs: string[];
dir: string;
pair(name?: string): Promise<DeviceCredential>;
api(method: string, path: string, opts?: { token?: string; json?: unknown; body?: Buffer; headers?: Record<string, string> }): Promise<{ status: number; body: any; headers: Headers }>;
conversation(token: string): Promise<string>;
textTurn(token: string, conversationId: string, text: string, requestId?: string): Promise<{ status: number; body: any }>;
audioTurn(token: string, conversationId: string, pcm: Buffer, requestId?: string, query?: Record<string, string>): Promise<{ status: number; body: any }>;
waitTerminal(token: string, requestId: string, timeoutMs?: number): Promise<TurnResult>;
waitState(token: string, requestId: string, state: string, timeoutMs?: number): Promise<TurnResult>;
/** Stop the bridge process-equivalent and start a new one on the same database. */
restartBridge(): Promise<void>;
close(): Promise<void>;
}
export async function createHarness(
opts: { env?: Record<string, string>; timing?: Partial<EngineTiming>; stt?: boolean } = {},
): Promise<Harness> {
const hermes = new FakeHermes();
const stt = new FakeStt();
await hermes.start();
await stt.start();
const dir = mkdtempSync(join(tmpdir(), 'hermeven-test-'));
const logs: string[] = [];
const sink = new Writable({
write(chunk, _enc, cb) {
logs.push(String(chunk));
cb();
},
});
const env: Record<string, string> = {
HERMEVEN_HOST: '127.0.0.1',
HERMEVEN_PORT: '0',
HERMEVEN_DB_PATH: join(dir, 'bridge.sqlite'),
HERMES_BASE_URL: hermes.url,
HERMES_API_KEY: hermes.apiKey,
HERMEVEN_ALLOWED_ORIGINS: 'https://app.example',
HERMES_REQUEST_TIMEOUT_MS: '300',
...(opts.stt === false
? {}
: { STT_PROVIDER: 'openai-compatible', STT_BASE_URL: stt.url, STT_API_KEY: stt.apiKey, STT_MODEL: 'fake-whisper' }),
...opts.env,
};
const config = loadConfig(env);
const timing = { ...FAST, ...opts.timing };
const h = {} as Harness;
const boot = async () => {
h.bridge = await createBridge(config, {
timing,
logger: pino({ level: 'debug', redact: { paths: LOG_REDACT, censor: '[redacted]' } }, sink),
});
await h.bridge.app.listen({ host: '127.0.0.1', port: 0 });
h.url = `http://127.0.0.1:${(h.bridge.app.server.address() as AddressInfo).port}`;
};
Object.assign(h, { hermes, stt, config, logs, dir });
await boot();
h.api = async (method, path, o = {}) => {
const headers: Record<string, string> = { ...(o.headers ?? {}) };
if (o.token) headers.Authorization = `Bearer ${o.token}`;
let body: BodyInit | undefined;
if (o.json !== undefined) {
headers['Content-Type'] = 'application/json';
body = JSON.stringify(o.json);
} else if (o.body) {
headers['Content-Type'] ??= 'application/octet-stream';
body = new Uint8Array(o.body);
}
const res = await fetch(`${h.url}${path}`, { method, headers, body });
const text = await res.text();
let parsed: unknown = text;
try {
parsed = JSON.parse(text);
} catch {
/* keep raw text */
}
return { status: res.status, body: parsed, headers: res.headers };
};
h.pair = async (name = 'test-g2') => {
const { code } = h.bridge.devices.createPairingCode();
const res = await h.api('POST', '/v1/pairing/claim', { json: { schema_version: SCHEMA_VERSION, code, device_name: name } });
if (res.status !== 201) throw new Error(`pairing failed: ${res.status} ${JSON.stringify(res.body)}`);
return res.body as DeviceCredential;
};
h.conversation = async (token) => {
const res = await h.api('POST', '/v1/conversations', { token, json: { schema_version: SCHEMA_VERSION } });
if (res.status !== 201) throw new Error(`conversation failed: ${res.status} ${JSON.stringify(res.body)}`);
return res.body.conversation_id as string;
};
h.textTurn = (token, conversationId, text, requestId = randomUUID()) =>
h.api('POST', '/v1/turns', {
token,
json: {
schema_version: SCHEMA_VERSION,
request_id: requestId,
conversation_id: conversationId,
locale: 'en-US',
input: { kind: 'text', text },
},
});
h.audioTurn = (token, conversationId, pcm, requestId = randomUUID(), query = {}) => {
const q = new URLSearchParams({
schema_version: String(SCHEMA_VERSION),
request_id: requestId,
conversation_id: conversationId,
locale: 'en-US',
input_kind: 'audio',
encoding: 'pcm_s16le',
sample_rate: '16000',
channels: '1',
...query,
});
return h.api('POST', `/v1/turns?${q}`, { token, body: pcm });
};
const waitFor = async (token: string, requestId: string, done: (t: TurnResult) => boolean, timeoutMs: number) => {
const deadline = Date.now() + timeoutMs;
let last: TurnResult | undefined;
while (Date.now() < deadline) {
const res = await h.api('GET', `/v1/turns/${requestId}`, { token });
if (res.status === 200) {
last = res.body as TurnResult;
if (done(last)) return last;
}
await new Promise((r) => setTimeout(r, 15));
}
throw new Error(`timed out waiting for turn ${requestId}; last=${JSON.stringify(last)}`);
};
h.waitTerminal = (token, requestId, timeoutMs = 5000) => waitFor(token, requestId, (t) => t.terminal, timeoutMs);
h.waitState = (token, requestId, state, timeoutMs = 5000) => waitFor(token, requestId, (t) => t.state === state, timeoutMs);
h.restartBridge = async () => {
await h.bridge.close();
await boot();
};
h.close = async () => {
await h.bridge.close().catch(() => undefined);
await hermes.stop();
await stt.stop();
rmSync(dir, { recursive: true, force: true });
};
return h;
}
+298
View File
@@ -0,0 +1,298 @@
import { execFileSync, spawn, type ChildProcess } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { createServer } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { SCHEMA_VERSION, type TurnResult } from '@hermeven/contracts';
import { createBridge, type Bridge } from '../../services/bridge/src/app.ts';
import { loadConfig, type BridgeConfig } from '../../services/bridge/src/config.ts';
import { StubLlm } from '../fakes/stubLlm.ts';
/**
* REAL HERMES, STUB MODEL.
*
* The bridge (real code, real HTTP adapter) talks to a real `hermes gateway`
* process: the installed hermes-agent, started in a throwaway HERMES_HOME so
* the operator's own profile, sessions and credentials are never read or
* written. The only fake is the language model behind Hermes (tests/fakes/
* stubLlm.ts), which costs nothing and answers deterministically.
*
* So this verifies Hermeven against Hermes's actual API server behaviour
* (admission, idempotency, session continuity, stop). It does not verify a
* real model, real tools, a deployed Hermes, or any hardware.
*/
const API_KEY = `test-${randomUUID()}`;
let home: string;
let gateway: ChildProcess;
let gatewayLog = '';
let hermesUrl: string;
let llm: StubLlm;
let bridge: Bridge;
let config: BridgeConfig;
let token: string;
let hermesVersion = '';
async function freePort(): Promise<number> {
return new Promise((resolve) => {
const srv = createServer();
srv.listen(0, '127.0.0.1', () => {
const { port } = srv.address() as { port: number };
srv.close(() => resolve(port));
});
});
}
async function startBridge(): Promise<void> {
bridge = await createBridge(config);
}
async function api(method: string, path: string, json?: unknown, auth = token) {
const res = await bridge.app.inject({
method: method as 'GET',
url: path,
headers: { authorization: `Bearer ${auth}`, ...(json !== undefined ? { 'content-type': 'application/json' } : {}) },
payload: json !== undefined ? JSON.stringify(json) : undefined,
});
return { status: res.statusCode, body: res.json() };
}
async function ask(conversationId: string, text: string, requestId = randomUUID()) {
return api('POST', '/v1/turns', {
schema_version: SCHEMA_VERSION,
request_id: requestId,
conversation_id: conversationId,
locale: 'en-US',
input: { kind: 'text', text },
});
}
async function settle(requestId: string, timeoutMs = 60_000): Promise<TurnResult> {
const deadline = Date.now() + timeoutMs;
for (;;) {
const res = await api('GET', `/v1/turns/${requestId}`);
if (res.body.terminal) return res.body as TurnResult;
if (Date.now() > deadline) throw new Error(`turn did not settle: ${JSON.stringify(res.body)}\n${gatewayLog.slice(-1500)}`);
await new Promise((r) => setTimeout(r, 100));
}
}
async function newConversation(): Promise<string> {
return (await api('POST', '/v1/conversations', { schema_version: SCHEMA_VERSION })).body.conversation_id;
}
beforeAll(async () => {
hermesVersion = execFileSync('hermes', ['--version'], { encoding: 'utf8' }).split('\n')[0]!.trim();
llm = new StubLlm();
await llm.start();
home = mkdtempSync(join(tmpdir(), 'hermeven-hermes-home-'));
writeFileSync(
join(home, 'config.yaml'),
['model:', ' default: "stub-model"', ' provider: "custom"', ` base_url: "${llm.url}"`, ' api_key: "stub-key-not-a-secret"', ''].join('\n'),
);
const port = await freePort();
hermesUrl = `http://127.0.0.1:${port}`;
gateway = spawn('hermes', ['gateway', 'run'], {
cwd: home,
env: {
...process.env,
HERMES_HOME: home,
API_SERVER_ENABLED: 'true',
API_SERVER_KEY: API_KEY,
API_SERVER_PORT: String(port),
API_SERVER_HOST: '127.0.0.1',
},
stdio: ['ignore', 'pipe', 'pipe'],
});
gateway.stdout!.on('data', (d) => (gatewayLog += String(d)));
gateway.stderr!.on('data', (d) => (gatewayLog += String(d)));
const deadline = Date.now() + 200_000;
for (;;) {
try {
if ((await fetch(`${hermesUrl}/health`)).ok) break;
} catch {
/* starting */
}
if (gateway.exitCode !== null) throw new Error(`hermes gateway exited early:\n${gatewayLog.slice(-3000)}`);
if (Date.now() > deadline) throw new Error(`hermes gateway did not become healthy:\n${gatewayLog.slice(-3000)}`);
await new Promise((r) => setTimeout(r, 500));
}
config = loadConfig({
HERMEVEN_DB_PATH: join(home, 'hermeven-bridge.sqlite'),
HERMES_BASE_URL: hermesUrl,
HERMES_API_KEY: API_KEY,
HERMES_POLL_INTERVAL_MS: '100',
HERMEVEN_AGENT_DEADLINE_SECONDS: '60',
HERMEVEN_CANCEL_GRACE_SECONDS: '30',
});
await startBridge();
const { code } = bridge.devices.createPairingCode();
const claim = await bridge.app.inject({
method: 'POST',
url: '/v1/pairing/claim',
headers: { 'content-type': 'application/json' },
payload: JSON.stringify({ schema_version: SCHEMA_VERSION, code, device_name: 'real-hermes-test' }),
});
token = claim.json().token;
});
afterAll(async () => {
await bridge?.close().catch(() => undefined);
try {
execFileSync('hermes', ['gateway', 'stop'], { env: { ...process.env, HERMES_HOME: home }, cwd: home, timeout: 60_000, stdio: 'ignore' });
} catch {
gateway?.kill('SIGTERM');
}
await new Promise((r) => setTimeout(r, 500));
if (gateway && gateway.exitCode === null) gateway.kill('SIGKILL');
await llm?.stop();
if (home) rmSync(home, { recursive: true, force: true });
});
describe('bridge against a real Hermes gateway (stub model)', () => {
it('records which Hermes was tested', async () => {
const health = await (await fetch(`${hermesUrl}/health`)).json();
console.info(`[real-hermes] CLI: ${hermesVersion}; /health: ${JSON.stringify(health)}`);
expect(health.status).toBe('ok');
const caps = await (await fetch(`${hermesUrl}/v1/capabilities`, { headers: { Authorization: `Bearer ${API_KEY}` } })).json();
expect(caps.features.run_submission).toBe(true);
expect(caps.features.run_status).toBe(true);
expect(caps.features.run_stop).toBe(true);
expect(caps.features.runs_idempotency).toMatchObject({ supported: true, durable: true });
console.info(`[real-hermes] runs_idempotency: ${JSON.stringify(caps.features.runs_idempotency)}`);
});
it('device status reports the agent as reachable', async () => {
expect((await api('GET', '/v1/device')).body.agent_reachable).toBe(true);
});
it('a typed question is answered through Hermes, with Hermeven instructions layered on', async () => {
const conv = await newConversation();
const res = await ask(conv, 'My favourite colour is teal.');
expect(res.status).toBe(202);
const done = await settle(res.body.request_id);
expect(done.outcome).toBe('succeeded');
expect(done.answer_text).toContain('STUB-ANSWER users=1');
expect(done.answer_text).toContain('My favourite colour is teal.');
// The per-request instructions reached the model's system prompt, alongside Hermes' own.
expect(llm.lastSystem).toContain('heads-up display');
console.info(`[real-hermes] first turn agent_ms=${done.timings.agent_ms}`);
});
it('a follow-up carries the earlier turn through Hermes’ own session store; a new conversation does not', async () => {
const conv = await newConversation();
await settle((await ask(conv, 'Remember the word pineapple.')).body.request_id);
const followUp = await settle((await ask(conv, 'What word did I ask you to remember?')).body.request_id);
expect(followUp.outcome).toBe('succeeded');
// The model was handed both user turns by Hermes; the bridge sent only the new one.
expect(llm.lastUserMessages).toEqual(['Remember the word pineapple.', 'What word did I ask you to remember?']);
expect(followUp.answer_text).toContain('users=2');
const fresh = await newConversation();
const first = await settle((await ask(fresh, 'What word did I ask you to remember?')).body.request_id);
expect(first.answer_text).toContain('users=1');
expect(llm.lastUserMessages).toEqual(['What word did I ask you to remember?']);
});
it('duplicate submits reach the model exactly once (backend invocation counter)', async () => {
const conv = await newConversation();
const before = llm.calls;
const id = randomUUID();
const results = await Promise.all(Array.from({ length: 6 }, () => ask(conv, 'Count me once.', id)));
expect(results.filter((r) => r.status === 202)).toHaveLength(1);
expect(results.filter((r) => r.status === 200 && r.body.replayed)).toHaveLength(5);
await settle(id);
await ask(conv, 'Count me once.', id);
expect(llm.calls - before).toBe(1);
});
it('Hermes replays an identical keyed submit and refuses a changed one (the adapter’s premise)', async () => {
const key = `hermeven-test-${randomUUID()}`;
const body = JSON.stringify({ input: 'idempotency probe', session_id: `hermeven-${randomUUID()}` });
const post = (payload: string) =>
fetch(`${hermesUrl}/v1/runs`, {
method: 'POST',
headers: { Authorization: `Bearer ${API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': key },
body: payload,
});
const before = llm.calls;
const first = await post(body);
expect(first.status).toBe(202);
const runId = (await first.json()).run_id;
const again = await post(body);
expect(again.status).toBe(202);
expect(again.headers.get('idempotency-replayed')).toBe('true');
expect((await again.json()).run_id).toBe(runId);
const changed = await post(JSON.stringify({ input: 'something else', session_id: 'x' }));
expect(changed.status).toBe(409);
expect((await changed.json()).error.code).toBe('idempotency_key_conflict');
await new Promise((r) => setTimeout(r, 3000));
expect(llm.calls - before).toBe(1);
});
it('cancel during a slow turn: Hermes confirms the stop and no answer is delivered', async () => {
const conv = await newConversation();
llm.delayMs = 15_000;
try {
const res = await ask(conv, 'This will take a while.');
const id = res.body.request_id;
const deadline = Date.now() + 20_000;
while ((await api('GET', `/v1/turns/${id}`)).body.state !== 'thinking') {
if (Date.now() > deadline) throw new Error('never reached thinking');
await new Promise((r) => setTimeout(r, 100));
}
await new Promise((r) => setTimeout(r, 1500));
const started = Date.now();
const cancel = await api('POST', `/v1/turns/${id}/cancel`, {});
expect(cancel.body.cancel_requested).toBe(true);
const done = await settle(id, 45_000);
console.info(`[real-hermes] cancel settled as ${done.outcome} in ${Date.now() - started} ms`);
expect(done.outcome).toBe('cancelled');
expect(done.answer_text).toBeNull();
} finally {
llm.delayMs = 0;
}
});
it('a bridge restart mid-turn re-attaches to the same Hermes run', async () => {
const conv = await newConversation();
llm.delayMs = 4000;
try {
const before = llm.calls;
const res = await ask(conv, 'Survive a restart.');
const id = res.body.request_id;
await new Promise((r) => setTimeout(r, 1200));
await bridge.close();
await startBridge();
const done = await settle(id, 60_000);
expect(done.outcome).toBe('succeeded');
expect(done.answer_text).toContain('Survive a restart.');
expect(llm.calls - before).toBe(1);
} finally {
llm.delayMs = 0;
}
});
it('a wrong Hermes key is a definite rejection: nothing runs', async () => {
await bridge.close();
const good = config;
config = { ...good, hermes: { ...good.hermes, apiKey: 'wrong-key' } };
await startBridge();
try {
const conv = await newConversation();
const before = llm.calls;
const done = await settle((await ask(conv, 'Should not run.')).body.request_id);
expect(done.outcome).toBe('failed');
expect(done.error?.code).toBe('agent_rejected');
expect(llm.calls).toBe(before);
} finally {
await bridge.close();
config = good;
await startBridge();
}
});
});
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig } from 'vitest/config';
// Opt-in: needs the `hermes` CLI installed. Runs a REAL Hermes gateway in a throwaway
// HERMES_HOME against a stub model, so no account, key or spend is involved.
export default defineConfig({
test: {
name: 'real-hermes',
root: new URL('../..', import.meta.url).pathname,
include: ['tests/real-hermes/**/*.test.ts'],
testTimeout: 90_000,
hookTimeout: 240_000,
fileParallelism: false,
},
});
+312
View File
@@ -0,0 +1,312 @@
import { spawn, type ChildProcess } from 'node:child_process';
import { mkdirSync, writeFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { createServer as createNetServer } from 'node:net';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { inflateSync } from 'node:zlib';
import { createServer, type ViteDevServer } from 'vite';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { createHarness, type Harness } from '../integration/harness.ts';
/**
* SIMULATOR TEST: the real client, loaded in the official Even Hub simulator
* (@evenrealities/evenhub-simulator), driven through its automation API,
* talking over HTTP to the real bridge. Hermes and the speech recogniser are
* TEST FAKES, and the simulator's audio input is ALSA's null device (silence),
* so no real microphone is opened and no real speech is transcribed.
*
* This is simulator evidence. It is not device evidence: Even documents that
* the simulator differs from hardware in font rendering, events and lifecycle.
*/
const here = dirname(fileURLToPath(import.meta.url));
const artifacts = resolve(here, '.artifacts');
const require = createRequire(import.meta.url);
let h: Harness;
let vite: ViteDevServer;
let sim: ChildProcess;
let simOutput = '';
let automation = '';
let lastConsoleId = 0;
const consoleLines: string[] = [];
let audioEchoLines = 0;
async function freePort(): Promise<number> {
return new Promise((resolvePort) => {
const srv = createNetServer();
srv.listen(0, '127.0.0.1', () => {
const { port } = srv.address() as { port: number };
srv.close(() => resolvePort(port));
});
});
}
async function pumpConsole(): Promise<void> {
const res = await fetch(`${automation}/api/console?since_id=${lastConsoleId}`);
const body = (await res.json()) as { entries: Array<{ id: number; level: string; message: string }> };
for (const entry of body.entries) {
lastConsoleId = Math.max(lastConsoleId, entry.id);
// In the simulator every hub event, including each raw PCM frame, is echoed to the webview
// console with an "[EvenAppBridge]" prefix. Those lines are counted, not kept.
if (entry.message.includes('audioPcm')) {
audioEchoLines += 1;
continue;
}
consoleLines.push(`${entry.level}: ${entry.message}`.slice(0, 600));
}
}
async function waitConsole(needle: string, timeoutMs = 20_000, from = 0): Promise<void> {
const deadline = Date.now() + timeoutMs;
for (;;) {
await pumpConsole();
if (consoleLines.slice(from).some((l) => l.includes(needle))) return;
if (Date.now() > deadline) {
throw new Error(`simulator console never showed "${needle}".\nConsole:\n${consoleLines.join('\n')}\nSimulator output:\n${simOutput.slice(-2000)}`);
}
await new Promise((r) => setTimeout(r, 150));
}
}
async function input(action: string): Promise<void> {
const res = await fetch(`${automation}/api/input`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action }),
});
expect(res.status, `input ${action}`).toBe(200);
}
/** Minimal RGBA8 PNG decoder (non-interlaced), enough to count lit pixels. */
function decodePng(png: Buffer): { width: number; height: number; lit: number; rows: Buffer[] } {
let offset = 8;
let width = 0;
let height = 0;
let colorType = 0;
const idat: Buffer[] = [];
while (offset < png.length) {
const length = png.readUInt32BE(offset);
const type = png.toString('ascii', offset + 4, offset + 8);
const data = png.subarray(offset + 8, offset + 8 + length);
if (type === 'IHDR') {
width = data.readUInt32BE(0);
height = data.readUInt32BE(4);
colorType = data[9]!;
} else if (type === 'IDAT') idat.push(data);
offset += 12 + length;
}
expect(colorType, 'glasses screenshot should be RGBA').toBe(6);
const raw = inflateSync(Buffer.concat(idat));
const bpp = 4;
const stride = width * bpp;
const rows: Buffer[] = [];
let prev = Buffer.alloc(stride);
let lit = 0;
for (let y = 0; y < height; y++) {
const filter = raw[y * (stride + 1)]!;
const line = Buffer.from(raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1)));
for (let x = 0; x < stride; x++) {
const a = x >= bpp ? line[x - bpp]! : 0;
const b = prev[x]!;
const c = x >= bpp ? prev[x - bpp]! : 0;
let add = 0;
if (filter === 1) add = a;
else if (filter === 2) add = b;
else if (filter === 3) add = (a + b) >> 1;
else if (filter === 4) {
const p = a + b - c;
const pa = Math.abs(p - a);
const pb = Math.abs(p - b);
const pc = Math.abs(p - c);
add = pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
}
line[x] = (line[x]! + add) & 0xff;
}
for (let x = 0; x < width; x++) if (line[x * 4 + 3]! > 0) lit += 1;
rows.push(line);
prev = line;
}
return { width, height, lit, rows };
}
async function screenshot(name: string) {
const res = await fetch(`${automation}/api/screenshot/glasses`);
expect(res.status).toBe(200);
const png = Buffer.from(await res.arrayBuffer());
writeFileSync(resolve(artifacts, `${name}.png`), png);
return { png, ...decodePng(png) };
}
/** Lit pixels inside a horizontal band of the canvas. */
function litInBand(shot: { rows: Buffer[]; width: number }, fromY: number, toY: number): number {
let lit = 0;
for (let y = fromY; y < toY; y++) for (let x = 0; x < shot.width; x++) if (shot.rows[y]![x * 4 + 3]! > 0) lit += 1;
return lit;
}
beforeAll(async () => {
mkdirSync(artifacts, { recursive: true });
const vitePort = await freePort();
vite = await createServer({
root: resolve(here, '../../apps/even-client'),
configFile: resolve(here, '../../apps/even-client/vite.config.ts'),
server: { host: '127.0.0.1', port: vitePort, strictPort: true },
logLevel: 'error',
});
await vite.listen();
const pageOrigin = `http://127.0.0.1:${vitePort}`;
h = await createHarness({
env: { HERMEVEN_ALLOWED_ORIGINS: pageOrigin, HERMEVEN_CAPTURE_MAX_SECONDS: '120' },
timing: { agentDeadlineMs: 20_000, transcribeDeadlineMs: 10_000 },
});
const { code } = h.bridge.devices.createPairingCode();
const automationPort = await freePort();
automation = `http://127.0.0.1:${automationPort}`;
const bin = require.resolve('@evenrealities/sim-linux-x64/bin/evenhub-simulator');
const url = `${pageOrigin}/?bridge=${encodeURIComponent(h.url)}&pair=${encodeURIComponent(code)}`;
// alsa:null yields silence: the simulator never opens a real microphone in this test.
sim = spawn(bin, [url, '--automation-port', String(automationPort), '--no-glow', '--aid', 'alsa:null'], {
stdio: ['ignore', 'pipe', 'pipe'],
cwd: artifacts,
});
sim.stdout!.on('data', (d) => (simOutput += String(d)));
sim.stderr!.on('data', (d) => (simOutput += String(d)));
const deadline = Date.now() + 30_000;
for (;;) {
try {
if ((await fetch(`${automation}/api/ping`)).ok) break;
} catch {
/* not up yet */
}
if (Date.now() > deadline) throw new Error(`simulator automation API did not start.\n${simOutput.slice(-2000)}`);
await new Promise((r) => setTimeout(r, 250));
}
});
afterAll(async () => {
sim?.kill('SIGTERM');
await new Promise((r) => setTimeout(r, 300));
if (sim && sim.exitCode === null) sim.kill('SIGKILL');
await vite?.close();
await h?.close();
writeFileSync(
resolve(artifacts, 'console.log'),
`${consoleLines.join('\n')}\n(audio frame echo lines omitted: ${audioEchoLines})\n`,
);
});
describe('Even Hub simulator 0.9.5', () => {
it('boots through the real SDK bridge, creates the HUD page and pairs', async () => {
await waitConsole('hud: HUD page created', 30_000);
await waitConsole('state: unpaired -> ready');
expect(consoleLines.some((l) => l.includes('HUD page was refused'))).toBe(false);
await new Promise((r) => setTimeout(r, 800));
const shot = await screenshot('01-ready');
expect([shot.width, shot.height]).toEqual([576, 288]);
// Body text at the top and the status bar in the bottom band are both drawn.
expect(litInBand(shot, 0, 120)).toBeGreaterThan(200);
expect(litInBand(shot, 251, 288)).toBeGreaterThan(100);
});
it('tap opens the microphone, audio frames arrive as 16 kHz PCM, tap submits, the answer is drawn', async () => {
const answer = Array.from({ length: 40 }, (_, i) => `Simulator sentence ${i + 1} of the answer.`).join(' ');
h.stt.next({ text: 'simulated question' });
h.hermes.next({ kind: 'complete', afterMs: 600, output: answer });
const mark = consoleLines.length;
await input('click');
await waitConsole('state: ready -> listening', 10_000, mark);
await new Promise((r) => setTimeout(r, 300));
const recording = await screenshot('02-listening');
expect(litInBand(recording, 251, 288)).toBeGreaterThan(100);
// Second tap = stop and send. With the unpaced null audio device the capture cap can be
// reached first, in which case this tap is a harmless no-op; both are valid ways to end a
// capture and the assertions below hold for either.
await input('click');
await waitConsole('state: listening -> transcribing', 10_000, mark);
await waitConsole('-> answer', 20_000, mark);
await pumpConsole();
// No stall: the simulator really delivered audio frames while the mic was open.
expect(consoleLines.slice(mark).some((l) => l.includes('no audio frames'))).toBe(false);
const captured = consoleLines.slice(mark).find((l) => l.includes('capture: captured'));
expect(captured, 'capture summary').toBeTruthy();
const seconds = Number(/captured ([\d.]+) s/.exec(captured!)![1]);
// The null audio device is not paced in real time, so the amount captured in a fixed wall
// time says nothing about a real microphone. What matters: frames arrived, the explicit tap
// (not the cap) ended the capture, and exactly those bytes reached the recogniser as WAV.
const endedByCap = consoleLines.slice(mark).some((l) => l.includes('capture limit reached'));
console.info(`[simulator] capture ended by ${endedByCap ? 'the 120 s cap' : 'the second tap'} with ${seconds} s of null-device audio`);
expect(seconds).toBeGreaterThan(0);
expect(seconds).toBeLessThanOrEqual(120);
if (endedByCap) expect(seconds).toBe(120);
expect(audioEchoLines).toBeGreaterThan(0);
expect(h.stt.lastWav).toMatchObject({ sampleRate: 16000, channels: 1, bitsPerSample: 16 });
expect(h.stt.lastWav!.dataBytes % 3200).toBe(0);
expect(h.stt.lastWav!.dataBytes / 32000).toBeCloseTo(seconds, 1);
expect(h.hermes.lastRun()!.input).toBe('simulated question');
expect(h.hermes.executions).toBe(1);
await new Promise((r) => setTimeout(r, 800));
const page1 = await screenshot('03-answer-page-1');
expect(litInBand(page1, 0, 251)).toBeGreaterThan(2000);
expect(consoleLines.slice(mark).some((l) => /answer laid out on [2-9] page/.test(l))).toBe(true);
});
it('swipe down turns the page, swipe up returns, and the page fits without firmware scrolling', async () => {
const page1 = await screenshot('04-before-swipe');
await input('down');
await new Promise((r) => setTimeout(r, 900));
const page2 = await screenshot('05-answer-page-2');
expect(page2.png.equals(page1.png)).toBe(false);
await input('up');
await new Promise((r) => setTimeout(r, 900));
const back = await screenshot('06-answer-page-1-again');
expect(back.png.equals(page1.png)).toBe(true);
});
it('a follow-up tap continues the same conversation', async () => {
h.stt.next({ text: 'simulated follow-up' });
const mark = consoleLines.length;
await input('click');
await waitConsole('state: answer -> listening', 10_000, mark);
// Give the microphone a moment to deliver frames (an instant second tap records nothing,
// which the app correctly reports as "Nothing was recorded"). If the unpaced null device
// has already hit the cap, the capture is over and a tap now would start a new question.
await new Promise((r) => setTimeout(r, 200));
await pumpConsole();
if (!consoleLines.slice(mark).some((l) => l.includes('capture limit reached'))) await input('click');
await waitConsole('-> answer', 20_000, mark);
expect(h.hermes.sessions.size).toBe(1);
expect(h.hermes.executions).toBe(2);
await new Promise((r) => setTimeout(r, 800));
await screenshot('07-follow-up-answer');
});
it('double-tap while recording cancels and uploads nothing; double-tap on an answer goes back', async () => {
const sttCalls = h.stt.calls;
let mark = consoleLines.length;
await input('click');
// Sent back to back, so the cancel lands before the unpaced null device can fill the cap.
await input('double_click');
await waitConsole('state: listening -> cancelled', 10_000, mark);
await new Promise((r) => setTimeout(r, 800));
await screenshot('08-cancelled');
expect(h.stt.calls).toBe(sttCalls);
mark = consoleLines.length;
await input('double_click');
await waitConsole('state: cancelled -> ready', 10_000, mark);
expect(h.hermes.executions).toBe(2);
});
it('no uncaught errors or failed fetches were reported by the webview', async () => {
await pumpConsole();
const problems = consoleLines.filter((l) => /\[uncaught\]|\[unhandledrejection\]|\[fetch\]/.test(l));
expect(problems).toEqual([]);
});
});
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig } from 'vitest/config';
// Separate from the default suite: needs a desktop session and the official
// Even Hub simulator binary. Run with `npm run test:simulator`.
export default defineConfig({
test: {
name: 'simulator',
root: new URL('../..', import.meta.url).pathname,
include: ['tests/simulator/**/*.test.ts'],
testTimeout: 120_000,
hookTimeout: 120_000,
fileParallelism: false,
},
});
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": { "lib": ["ES2024", "DOM", "DOM.Iterable"], "types": ["node"] },
"include": ["."]
}