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
+20
View File
@@ -0,0 +1,20 @@
{
"package_id": "gg.xylo.hermeven",
"edition": "202601",
"name": "Hermeven",
"version": "0.1.0",
"min_sdk_version": "0.0.16",
"entrypoint": "index.html",
"permissions": [
{
"name": "network",
"desc": "Sends your question to the Hermeven bridge you paired with and receives the answer.",
"whitelist": ["__HERMEVEN_BRIDGE_ORIGIN__"]
},
{
"name": "g2-microphone",
"desc": "Records your question from the glasses microphone, only while you have tapped to ask."
}
],
"supported_languages": ["en"]
}
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"
/>
<title>Hermeven</title>
</head>
<body>
<div id="app"></div>
<div id="preview" hidden></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+23
View File
@@ -0,0 +1,23 @@
{
"name": "@hermeven/even-client",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit -p . && vite build && node scripts/write-manifest.mjs",
"pack": "npm run build && evenhub pack dist-manifest/app.json dist -o hermeven.ehpk --sdk-ver 0.0.16",
"simulate": "node ../../node_modules/@evenrealities/evenhub-simulator/bin/index.js http://localhost:5173",
"qr": "evenhub qr"
},
"dependencies": {
"@evenrealities/even_hub_sdk": "0.0.16",
"@evenrealities/pretext": "0.1.4",
"@hermeven/contracts": "*"
},
"devDependencies": {
"@evenrealities/evenhub-cli": "0.2.0",
"@evenrealities/evenhub-simulator": "0.9.5",
"vite": "^8.3.8"
}
}
@@ -0,0 +1,34 @@
// Writes dist-manifest/app.json from app.template.json.
//
// Even Hub enforces a per-app network whitelist of exact origins, so the bridge
// origin has to be in the packaged manifest. It is supplied at build time and is
// never committed: no deployment hostname lives in this repository.
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const here = dirname(fileURLToPath(import.meta.url));
const raw = process.env.HERMEVEN_BRIDGE_ORIGIN ?? '';
if (!raw) {
console.warn('[manifest] HERMEVEN_BRIDGE_ORIGIN is not set: skipping app.json. Set it before `npm run pack`.');
process.exit(0);
}
let origin;
try {
origin = new URL(raw).origin;
} catch {
console.error('[manifest] HERMEVEN_BRIDGE_ORIGIN is not a URL.');
process.exit(1);
}
if (origin !== raw) {
console.error(`[manifest] HERMEVEN_BRIDGE_ORIGIN must be a bare origin (scheme://host[:port]), got a path or trailing slash.`);
process.exit(1);
}
if (!origin.startsWith('https://')) {
console.warn('[manifest] The bridge origin is not https. Acceptable only for a local development build.');
}
const template = readFileSync(resolve(here, '../app.template.json'), 'utf8');
const out = resolve(here, '../dist-manifest/app.json');
mkdirSync(dirname(out), { recursive: true });
writeFileSync(out, template.replace('__HERMEVEN_BRIDGE_ORIGIN__', origin));
console.log(`[manifest] wrote ${out}`);
+663
View File
@@ -0,0 +1,663 @@
import { AUDIO_FORMAT, DEFAULT_LIMITS, type DeviceStatusResponse, type TurnResult } from '@hermeven/contracts';
import { MENU_ITEM, type DeviceEvent } from '../device/events.ts';
import type { DevicePort } from '../device/port.ts';
import { BridgeApiError, BridgeClient, BridgeNetworkError } from '../net/bridgeClient.ts';
import { BODY_BOX, HUD, renderHud } from './hud.ts';
import { paginate, type MeasureLines } from './paginate.ts';
import { toPlainText } from './plaintext.ts';
import { initialState, reduce, type AppEvent, type AppState, type Effect, type HudError } from './reducer.ts';
const STORAGE_KEY = 'hermeven.v1';
interface Stored {
bridgeUrl: string;
token: string;
deviceId: string;
tokenExpiresAt: string;
pairingExpiresAt: string;
conversationId: string | null;
/** A turn that was in flight; re-attached by polling after a restart, never resubmitted. */
activeRequestId: string | null;
}
export interface DiagEntry {
at: number;
kind: string;
detail: string;
}
export interface Snapshot {
state: AppState;
paired: boolean;
bridgeUrl: string;
deviceId: string;
tokenExpiresAt: string;
pairingExpiresAt: string;
status: DeviceStatusResponse | null;
hudReady: boolean;
/** Last settled turn, complete and untruncated, for the phone. */
lastTurn: TurnResult | null;
log: DiagEntry[];
}
export interface ControllerOptions {
device: DevicePort;
measure: MeasureLines;
locale: string;
newId?: () => string;
now?: () => number;
makeClient?: (baseUrl: string, token: string) => BridgeClient;
onChange?: (snapshot: Snapshot) => void;
/** Receives each diagnostic entry (ids, codes, timings; never content). */
onNote?: (entry: DiagEntry) => void;
pollIntervalMs?: number;
submitAttempts?: number;
submitRetryMs?: number;
/** No audio frames for this long while recording means the microphone is gone. */
micStallMs?: number;
}
interface Capture {
generation: number;
chunks: Uint8Array[];
bytes: number;
maxBytes: number;
lastFrameAt: number;
limitSent: boolean;
}
type PendingInput = { requestId: string; kind: 'text'; text: string } | { requestId: string; kind: 'audio'; pcm: Uint8Array };
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
export class Controller {
private state: AppState = initialState;
private stored: Stored | null = null;
private client: BridgeClient | null = null;
private status: DeviceStatusResponse | null = null;
private capture: Capture | null = null;
private micOpen = false;
private pending: PendingInput | null = null;
private lastTurn: TurnResult | null = null;
private hudReady = false;
private stopped = false;
private ticker: ReturnType<typeof setInterval> | null = null;
private readonly log: DiagEntry[] = [];
private readonly unsubscribers: Array<() => void> = [];
private readonly device: DevicePort;
private readonly now: () => number;
private readonly newId: () => string;
private readonly pollIntervalMs: number;
private readonly submitAttempts: number;
private readonly submitRetryMs: number;
private readonly micStallMs: number;
constructor(private readonly options: ControllerOptions) {
this.device = options.device;
this.now = options.now ?? Date.now;
this.newId = options.newId ?? (() => crypto.randomUUID());
this.pollIntervalMs = options.pollIntervalMs ?? 700;
this.submitAttempts = options.submitAttempts ?? 4;
this.submitRetryMs = options.submitRetryMs ?? 1500;
this.micStallMs = options.micStallMs ?? 3000;
}
// ------------------------------------------------------------------ public
async start(): Promise<void> {
this.stored = await this.load();
this.hudReady = await this.device.init(renderHud(this.state, this.now()));
this.note('hud', this.hudReady ? 'HUD page created' : 'HUD page was refused by the host');
this.unsubscribers.push(
this.device.onEvent((event) => this.onDeviceEvent(event)),
this.device.onConnection((connected) => {
this.note('glasses', connected ? 'connected' : 'disconnected');
this.dispatch({ type: 'glasses_status', connected });
}),
);
let captureMaxSeconds: number = DEFAULT_LIMITS.captureMaxSeconds;
if (this.stored) {
this.client = this.makeClient(this.stored.bridgeUrl, this.stored.token);
try {
this.status = await this.client.device();
captureMaxSeconds = this.status.limits.capture_max_seconds;
await this.maybeRenew();
} catch (err) {
if (err instanceof BridgeApiError && (err.body.code === 'unauthorized' || err.body.code === 'credential_expired')) {
this.note('auth', `stored credential rejected: ${err.body.code}`);
await this.forget();
} else {
this.note('bridge', `status check failed: ${describe(err)}`);
}
}
}
this.dispatch({
type: 'init',
paired: this.stored !== null,
conversationId: this.stored?.conversationId ?? null,
captureMaxSeconds,
resumeRequestId: this.stored?.activeRequestId ?? null,
});
}
/** Stop for good: every pending retry and poll loop winds down and nothing more is drawn or emitted. */
async stop(): Promise<void> {
this.stopped = true;
for (const off of this.unsubscribers.splice(0)) off();
this.stopTicker();
await this.closeMic();
}
snapshot(): Snapshot {
return {
state: this.state,
paired: this.stored !== null,
bridgeUrl: this.stored?.bridgeUrl ?? '',
deviceId: this.stored?.deviceId ?? '',
tokenExpiresAt: this.stored?.tokenExpiresAt ?? '',
pairingExpiresAt: this.stored?.pairingExpiresAt ?? '',
status: this.status,
hudReady: this.hudReady,
lastTurn: this.lastTurn,
log: [...this.log],
};
}
/** Explicit pairing from the phone. Throws with a user-presentable message on failure. */
async pair(bridgeUrl: string, code: string, deviceName: string): Promise<void> {
const client = this.makeClient(bridgeUrl, '');
const credential = await client.claim(code, deviceName);
client.token = credential.token;
this.client = client;
this.stored = {
bridgeUrl,
token: credential.token,
deviceId: credential.device_id,
tokenExpiresAt: credential.token_expires_at,
pairingExpiresAt: credential.pairing_expires_at,
conversationId: null,
activeRequestId: null,
};
await this.save();
this.note('pairing', `paired as ${credential.device_id}`);
let captureMaxSeconds: number = DEFAULT_LIMITS.captureMaxSeconds;
try {
this.status = await client.device();
captureMaxSeconds = this.status.limits.capture_max_seconds;
} catch (err) {
this.note('bridge', `status check failed: ${describe(err)}`);
}
this.dispatch({ type: 'init', paired: true, conversationId: null, captureMaxSeconds, resumeRequestId: null });
}
/** Disconnect: revoke the credential on the bridge, then clear everything held locally. */
async disconnect(): Promise<{ revoked: boolean }> {
let revoked = false;
try {
await this.client?.revoke();
revoked = true;
} catch (err) {
// Local state is cleared regardless; the phone tells the user to revoke on the bridge.
this.note('pairing', `remote revoke failed: ${describe(err)}`);
}
await this.forget();
this.dispatch({ type: 'unpaired' });
return { revoked };
}
async renew(): Promise<void> {
if (!this.client || !this.stored) return;
const credential = await this.client.renew();
this.client.token = credential.token;
this.stored = { ...this.stored, token: credential.token, tokenExpiresAt: credential.token_expires_at };
await this.save();
this.note('pairing', 'credential renewed');
this.emit();
}
async refreshStatus(): Promise<void> {
if (!this.client) return;
try {
this.status = await this.client.device();
} catch (err) {
this.note('bridge', `status check failed: ${describe(err)}`);
}
this.emit();
}
askText(text: string): void {
const trimmed = text.trim();
if (trimmed) this.dispatch({ type: 'submit_text', freshId: this.newId(), text: trimmed });
}
newConversation(): void {
this.dispatch({ type: 'new_conversation' });
}
cancel(): void {
this.dispatch({ type: 'cancel' });
}
dispatch(event: AppEvent): void {
if (this.stopped) return;
const before = this.state;
const step = reduce(before, event);
this.state = step.state;
if (before.phase !== step.state.phase) this.note('state', `${before.phase} -> ${step.state.phase}`);
for (const effect of step.effects) void this.run(effect);
this.render();
this.emit();
}
// ----------------------------------------------------------------- effects
private async run(effect: Effect): Promise<void> {
try {
switch (effect.type) {
case 'start_capture':
return await this.startCapture(effect.generation);
case 'stop_capture_and_submit':
return await this.stopCaptureAndSubmit(effect.generation, effect.requestId);
case 'discard_capture':
this.capture = null;
this.pending = null;
return await this.closeMic();
case 'submit_text':
this.pending = { requestId: effect.requestId, kind: 'text', text: effect.text };
return await this.submit(effect.generation, effect.requestId);
case 'resubmit':
return await this.submit(effect.generation, effect.requestId);
case 'poll':
return await this.poll(effect.generation, effect.requestId);
case 'cancel_turn':
return await this.cancelTurn(effect.requestId);
case 'create_conversation':
return await this.createConversation(effect.generation);
case 'exit_dialog':
return await this.device.requestExit();
}
} catch (err) {
this.note('internal', `effect ${effect.type} failed: ${describe(err)}`);
}
}
private async startCapture(generation: number): Promise<void> {
const capture: Capture = {
generation,
chunks: [],
bytes: 0,
maxBytes: this.state.captureMaxSeconds * AUDIO_FORMAT.bytesPerSecond,
lastFrameAt: this.now(),
limitSent: false,
};
this.capture = capture;
this.micOpen = true;
const ok = await this.device.startMic();
if (this.capture !== capture) {
// Cancelled while the microphone was opening.
if (!this.capture) await this.closeMic();
return;
}
if (!ok) {
this.capture = null;
this.micOpen = false;
this.dispatch({ type: 'capture_failed', generation, reason: 'mic_refused' });
return;
}
capture.lastFrameAt = this.now();
this.dispatch({ type: 'capture_started', generation, at: this.now() });
this.startTicker();
}
private onAudio(pcm: Uint8Array): void {
const capture = this.capture;
// Frames outside an active, current-generation capture are dropped on the floor.
if (!capture || capture.generation !== this.state.generation || this.state.phase !== 'listening') return;
capture.lastFrameAt = this.now();
const room = capture.maxBytes - capture.bytes;
if (room > 0) {
const chunk = pcm.length > room ? pcm.slice(0, room) : pcm.slice();
capture.chunks.push(chunk);
capture.bytes += chunk.length;
}
if (capture.bytes >= capture.maxBytes && !capture.limitSent) {
capture.limitSent = true;
this.note('capture', 'capture limit reached');
this.dispatch({ type: 'capture_limit', generation: capture.generation });
}
}
private async stopCaptureAndSubmit(generation: number, requestId: string): Promise<void> {
const capture = this.capture;
this.capture = null;
this.stopTicker();
await this.closeMic();
if (!capture || capture.generation !== generation) return;
const usable = capture.bytes - (capture.bytes % 2);
if (usable === 0) {
this.dispatch({ type: 'capture_failed', generation, reason: 'empty' });
return;
}
const pcm = new Uint8Array(usable);
let offset = 0;
for (const chunk of capture.chunks) {
const take = Math.min(chunk.length, usable - offset);
pcm.set(chunk.subarray(0, take), offset);
offset += take;
}
this.note('capture', `captured ${(usable / AUDIO_FORMAT.bytesPerSecond).toFixed(1)} s`);
this.pending = { requestId, kind: 'audio', pcm };
await this.submit(generation, requestId);
}
private async closeMic(): Promise<void> {
if (!this.micOpen) return;
this.micOpen = false;
this.stopTicker();
await this.device.stopMic();
}
private stale(generation: number): boolean {
return this.stopped || generation !== this.state.generation;
}
private async ensureConversation(): Promise<string> {
if (this.state.conversationId) return this.state.conversationId;
const created = await this.client!.createConversation();
if (this.stored) {
this.stored = { ...this.stored, conversationId: created.conversation_id };
await this.save();
}
this.dispatch({ type: 'conversation_created', generation: this.state.generation, conversationId: created.conversation_id });
return created.conversation_id;
}
private async submit(generation: number, requestId: string): Promise<void> {
const pending = this.pending;
if (!this.client || !pending || pending.requestId !== requestId) return;
for (let attempt = 1; ; attempt++) {
if (this.stale(generation)) return;
try {
const conversationId = await this.ensureConversation();
if (this.stale(generation)) return;
const base = { requestId, conversationId, locale: this.options.locale };
// The same request id on every attempt: the bridge deduplicates, so a retry after a
// lost response cannot create a second turn.
const result =
pending.kind === 'text'
? await this.client.submitText({ ...base, text: pending.text })
: await this.client.submitAudio({ ...base, pcm: pending.pcm });
if (this.pending === pending) this.pending = null;
if (this.stale(generation)) {
// Cancelled while the request was on the wire: the cancel may have beaten it there.
void this.cancelTurn(requestId);
return;
}
await this.setActiveRequest(requestId);
this.note('turn', `accepted ${requestId}${result.replayed ? ' (duplicate ignored by bridge)' : ''}`);
this.onResult(generation, result);
if (!result.terminal) await this.poll(generation, requestId);
return;
} catch (err) {
if (err instanceof BridgeApiError) {
this.note('turn', `rejected: ${err.body.code}`);
this.pending = null;
if (!this.stale(generation)) this.dispatch({ type: 'turn_rejected', generation, error: this.hudError(err) });
await this.afterAuthFailure(err);
return;
}
if (!(err instanceof BridgeNetworkError)) throw err;
this.note('bridge', `submit attempt ${attempt} failed: ${err.message}`);
if (attempt >= this.submitAttempts) {
if (!this.stale(generation)) this.dispatch({ type: 'network_lost', generation, stage: 'submit' });
return;
}
await sleep(this.submitRetryMs);
}
}
}
private async poll(generation: number, requestId: string): Promise<void> {
if (!this.client) return;
let failures = 0;
for (;;) {
await sleep(failures ? Math.min(5000, this.pollIntervalMs * 2 ** Math.min(failures, 3)) : this.pollIntervalMs);
if (this.stale(generation)) return;
try {
const result = await this.client.getTurn(requestId);
if (this.stale(generation)) return;
if (failures >= 3) this.dispatch({ type: 'network_restored', generation });
failures = 0;
this.onResult(generation, result);
if (result.terminal) return;
} catch (err) {
if (this.stale(generation)) return;
if (err instanceof BridgeApiError) {
this.note('turn', `status rejected: ${err.body.code}`);
await this.setActiveRequest(null);
this.dispatch({ type: 'turn_rejected', generation, error: this.hudError(err) });
await this.afterAuthFailure(err);
return;
}
if (!(err instanceof BridgeNetworkError)) throw err;
failures += 1;
if (failures === 3) {
this.note('bridge', 'lost contact while waiting for the answer');
this.dispatch({ type: 'network_lost', generation, stage: 'poll' });
}
}
}
}
private onResult(generation: number, result: TurnResult): void {
let pages: string[] | null = null;
if (result.terminal) {
this.lastTurn = result;
void this.setActiveRequest(null);
this.note(
'turn',
`done ${result.request_id}: ${result.outcome}${result.error ? ` (${result.error.code})` : ''}` +
` stt=${result.timings.transcribe_ms ?? '-'}ms agent=${result.timings.agent_ms ?? '-'}ms`,
);
if (result.outcome === 'succeeded' || result.outcome === 'incomplete') {
const plain = toPlainText(result.answer_text ?? '') || '(The agent returned no text.)';
const started = this.now();
pages = paginate(
plain,
{ width: BODY_BOX.innerWidth, maxLines: HUD.bodyLines, maxBytes: HUD.pageMaxBytes },
this.options.measure,
);
this.note('hud', `answer laid out on ${pages.length} page(s) in ${this.now() - started} ms`);
}
}
this.dispatch({ type: 'turn_update', generation, result, pages });
}
private async cancelTurn(requestId: string): Promise<void> {
await this.setActiveRequest(null);
if (!this.client) return;
for (let attempt = 1; attempt <= 3; attempt++) {
try {
const result = await this.client.cancelTurn(requestId);
this.note('turn', `cancel requested for ${requestId}; bridge state ${result.state}`);
return;
} catch (err) {
if (err instanceof BridgeApiError) {
// not_found: the request never reached the bridge, so there is nothing to cancel.
this.note('turn', `cancel answered ${err.body.code}`);
return;
}
await sleep(this.submitRetryMs);
}
}
this.note('turn', `cancel for ${requestId} could not be delivered; the agent may still be running`);
}
private async createConversation(generation: number): Promise<void> {
if (!this.client) return;
try {
const created = await this.client.createConversation();
if (this.stored) {
this.stored = { ...this.stored, conversationId: created.conversation_id };
await this.save();
}
this.note('conversation', `new conversation ${created.conversation_id}`);
this.dispatch({ type: 'conversation_created', generation, conversationId: created.conversation_id });
} catch (err) {
const error: HudError =
err instanceof BridgeApiError
? this.hudError(err)
: { code: 'network', hud: 'Could not reach the bridge.', retryable: true };
this.note('conversation', `create failed: ${describe(err)}`);
this.dispatch({ type: 'conversation_failed', generation, error });
if (err instanceof BridgeApiError) await this.afterAuthFailure(err);
}
}
// ------------------------------------------------------------------ device
private onDeviceEvent(event: DeviceEvent): void {
switch (event.type) {
case 'audio':
return this.onAudio(event.pcm);
case 'tap':
return this.dispatch({ type: 'activate', freshId: this.newId() });
case 'double_tap':
return this.dispatch({ type: 'back' });
case 'swipe_down':
return this.dispatch({ type: 'next_page' });
case 'swipe_up':
return this.dispatch({ type: 'prev_page' });
case 'menu':
if (event.itemId === MENU_ITEM.NEW_CONVERSATION) return this.dispatch({ type: 'new_conversation' });
if (event.itemId === MENU_ITEM.CANCEL) return this.dispatch({ type: 'cancel' });
return;
case 'system_exit':
case 'abnormal_exit':
this.note('lifecycle', event.type);
return this.dispatch({ type: 'app_exit' });
case 'foreground_enter':
case 'foreground_exit':
// Also fired when the OS menu opens and closes; nothing is torn down here.
this.note('lifecycle', event.type);
return this.render();
}
}
private render(): void {
if (this.hudReady && !this.stopped) this.device.show(renderHud(this.state, this.now()));
}
private startTicker(): void {
this.stopTicker();
this.ticker = setInterval(() => {
const capture = this.capture;
if (capture && this.state.phase === 'listening' && this.now() - capture.lastFrameAt > this.micStallMs) {
// Permission loss or a suspended audio stream both look like silence on the wire.
this.note('capture', 'no audio frames; stopping capture');
this.dispatch({ type: 'capture_failed', generation: capture.generation, reason: 'mic_stalled' });
return;
}
this.render();
}, 1000);
}
private stopTicker(): void {
if (this.ticker) clearInterval(this.ticker);
this.ticker = null;
}
// ----------------------------------------------------------------- helpers
private makeClient(baseUrl: string, token: string): BridgeClient {
return this.options.makeClient?.(baseUrl, token) ?? new BridgeClient({ baseUrl, token });
}
private hudError(err: BridgeApiError): HudError {
const code = err.body.code;
if (code === 'unauthorized' || code === 'credential_expired') {
return { code, hud: 'Not connected. Pair again on your phone.', retryable: false };
}
if (code === 'conversation_closed') return { code, hud: 'Conversation ended. Start a new one from the menu.', retryable: false };
return { code, hud: err.body.message, retryable: err.body.retryable };
}
private async afterAuthFailure(err: BridgeApiError): Promise<void> {
if (err.body.code !== 'unauthorized') return;
// Revoked or unknown credential: holding on to it helps nobody.
await this.forget();
this.dispatch({ type: 'unpaired' });
}
private async maybeRenew(): Promise<void> {
if (!this.stored) return;
const remaining = Date.parse(this.stored.tokenExpiresAt) - this.now();
if (Number.isFinite(remaining) && remaining < 2 * 86_400_000) {
try {
await this.renew();
} catch (err) {
this.note('pairing', `renewal failed: ${describe(err)}`);
}
}
}
private async setActiveRequest(requestId: string | null): Promise<void> {
if (!this.stored || this.stored.activeRequestId === requestId) return;
this.stored = { ...this.stored, activeRequestId: requestId };
await this.save();
}
private async load(): Promise<Stored | null> {
try {
const raw = await this.device.storageGet(STORAGE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as Partial<Stored>;
if (typeof parsed.bridgeUrl !== 'string' || typeof parsed.token !== 'string' || !parsed.token) return null;
return {
bridgeUrl: parsed.bridgeUrl,
token: parsed.token,
deviceId: String(parsed.deviceId ?? ''),
tokenExpiresAt: String(parsed.tokenExpiresAt ?? ''),
pairingExpiresAt: String(parsed.pairingExpiresAt ?? ''),
conversationId: typeof parsed.conversationId === 'string' ? parsed.conversationId : null,
activeRequestId: typeof parsed.activeRequestId === 'string' ? parsed.activeRequestId : null,
};
} catch {
return null;
}
}
private async save(): Promise<void> {
await this.device.storageSet(STORAGE_KEY, this.stored ? JSON.stringify(this.stored) : '');
}
private async forget(): Promise<void> {
this.stored = null;
this.client = null;
this.status = null;
this.pending = null;
this.lastTurn = null;
await this.save();
}
/** Diagnostics for the phone only: ids, codes and timings. Never transcript or answer text. */
private note(kind: string, detail: string): void {
const entry = { at: this.now(), kind, detail };
this.log.push(entry);
this.options.onNote?.(entry);
if (this.log.length > 200) this.log.splice(0, this.log.length - 200);
}
private emit(): void {
if (this.stopped) return;
this.options.onChange?.(this.snapshot());
}
}
function describe(err: unknown): string {
if (err instanceof BridgeApiError) return `${err.body.code} (HTTP ${err.status})`;
if (err instanceof Error) return `${err.name}: ${err.message}`;
return 'unknown error';
}
+105
View File
@@ -0,0 +1,105 @@
import type { AppState } from './reducer.ts';
/**
* HUD geometry. Canvas size and line height are documented by Even
* (576 x 288 px; 27 px fixed line height); see docs/feasibility.md, "HUD".
* Two text containers: a body that takes the gestures, and a one-line status
* bar pinned underneath so the recording indicator never scrolls away.
*/
export const HUD = {
width: 576,
height: 288,
lineHeight: 27,
padding: 4,
bodyLines: 9,
/** Kept well under the firmware's 999-byte create/rebuild limit. */
pageMaxBytes: 900,
} as const;
export const BODY_BOX = {
x: 0,
y: 0,
width: HUD.width,
height: HUD.bodyLines * HUD.lineHeight + 2 * HUD.padding, // 251
innerWidth: HUD.width - 2 * HUD.padding, // 568
} as const;
export const STATUS_BOX = {
x: 0,
y: BODY_BOX.height,
width: HUD.width,
height: HUD.height - BODY_BOX.height, // 37: one 27 px line plus padding
} as const;
export interface HudFrame {
body: string;
status: string;
}
function clock(seconds: number): string {
const s = Math.max(0, Math.floor(seconds));
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
}
/** Pure: the complete HUD text for a state at a moment in time. */
export function renderHud(state: AppState, nowMs: number): HudFrame {
switch (state.phase) {
case 'unpaired':
return { body: 'Hermeven\n\nNot connected.\nOpen Hermeven on your phone to pair.', status: 'Double-tap: exit' };
case 'ready':
return {
body: state.notice ? `Hermeven\n\n${state.notice}.` : 'Hermeven\n\nReady.',
status: 'Tap: ask · Double-tap: exit',
};
case 'listening': {
const elapsed = state.captureStartedAt === null ? 0 : (nowMs - state.captureStartedAt) / 1000;
const cap = state.captureMaxSeconds;
return {
body: `Listening…\n\nRecording stops by itself after ${cap} seconds.`,
status: `● REC ${clock(elapsed)} / ${clock(cap)} · Tap: send · 2×: cancel`,
};
}
case 'transcribing':
return { body: 'Transcribing…', status: 'Double-tap: cancel' };
case 'thinking':
return { body: 'Thinking…', status: 'Double-tap: cancel' };
case 'approval':
return {
body: 'Approval required.\n\nThe agent is waiting for you to approve an action. Approve or deny it where you normally manage the agent. It cannot be approved from the glasses.',
status: 'Waiting · Double-tap: cancel',
};
case 'answer': {
const total = state.pages.length;
const page = state.pages[state.pageIndex] ?? '';
const position = total > 1 ? `${state.pageIndex + 1}/${total} · Swipe: page · ` : '';
const partial = state.partial ? 'PARTIAL · ' : '';
return { body: page, status: `${partial}${position}Tap: ask` };
}
case 'cancelled':
return {
body: 'Cancelled.\n\nAnything the agent had already done is not undone.',
status: 'Tap: ask · Double-tap: back',
};
case 'disconnected':
if (state.disconnectedFrom === 'glasses') {
return { body: 'Glasses disconnected.', status: 'Reconnect to continue' };
}
return state.canResend
? { body: 'No connection to the bridge.\n\nYour request has not been sent.', status: 'Tap: retry · Double-tap: discard' }
: { body: 'Connection lost.\n\nStill waiting for the answer…', status: 'Reconnecting · Double-tap: cancel' };
case 'error':
return {
body: `${state.error?.hud ?? 'Something went wrong.'}\n\nDetails are on your phone.`,
status: state.error?.retryable ? 'Tap: ask again · Double-tap: back' : 'Double-tap: back',
};
}
}
+90
View File
@@ -0,0 +1,90 @@
/**
* Split a complete answer into HUD pages without dropping any text.
*
* Page size comes from measurement, not character counts: `measure` reports
* how many firmware lines a string wraps to at the container's inner width
* (production uses @evenrealities/pretext, which mirrors the firmware's LVGL
* line breaking). A second, independent budget keeps each page under the
* firmware's text-container byte limit.
*/
export interface PageBox {
/** Inner width in px: container width minus 2 x (padding + border). */
width: number;
/** Lines available for answer text on one page. */
maxLines: number;
/** UTF-8 byte budget for the answer text on one page. */
maxBytes: number;
}
export type MeasureLines = (text: string, width: number) => number;
const encoder = new TextEncoder();
export function utf8Bytes(text: string): number {
return encoder.encode(text).length;
}
/** Grapheme-safe split so surrogate pairs, combining marks and ZWJ sequences stay intact. */
function graphemes(text: string): string[] {
if (typeof Intl !== 'undefined' && 'Segmenter' in Intl) {
return Array.from(new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(text), (s) => s.segment);
}
return Array.from(text);
}
export function paginate(source: string, box: PageBox, measure: MeasureLines): string[] {
const text = source
.replace(/\r\n?/g, '\n')
.replace(/[ \t]+\n/g, '\n')
.replace(/\n{3,}/g, '\n\n')
.trim();
if (!text) return [''];
const fits = (candidate: string) =>
utf8Bytes(candidate) <= box.maxBytes && measure(candidate, box.width) <= box.maxLines;
const pages: string[] = [];
let page = '';
const flush = () => {
if (page) pages.push(page);
page = '';
};
// Alternating [word, separator, word, ...]; separators are kept verbatim inside a
// page (so line breaks survive) and dropped only where a page break replaces them.
const tokens = text.split(/(\s+)/);
let separator = '';
for (const token of tokens) {
if (!token) continue;
if (/^\s+$/.test(token)) {
separator = token;
continue;
}
const candidate = page ? page + separator + token : token;
separator = '';
if (fits(candidate)) {
page = candidate;
continue;
}
flush();
if (fits(token)) {
page = token;
continue;
}
// One unbroken run longer than a whole page (long URL, unspaced CJK): split by grapheme.
let chunk = '';
for (const g of graphemes(token)) {
if (fits(chunk + g)) {
chunk += g;
} else if (chunk) {
pages.push(chunk);
chunk = g;
} else {
// A single grapheme that cannot fit an empty page: emit it alone rather than lose it.
pages.push(g);
}
}
page = chunk;
}
flush();
return pages.length ? pages : [''];
}
+66
View File
@@ -0,0 +1,66 @@
/**
* Convert an agent answer to plain text for the HUD.
*
* The HUD renders one firmware font with no styling, so Markdown and HTML
* markup would show up as literal noise. This only removes markup; it never
* shortens or rewords the answer. Unicode is preserved as-is (NFC-normalised);
* whether a glyph exists in the firmware font is a device property we cannot
* check here (see docs/feasibility.md, "HUD").
*/
export function toPlainText(input: string): string {
let text = input.replace(/\r\n?/g, '\n').normalize('NFC');
// Fenced code: keep the code, drop the fence lines.
text = text.replace(/^[ \t]*(```|~~~)[^\n]*\n?/gm, '');
// HTML: turn structural breaks into newlines, drop remaining tags, decode common entities.
text = text.replace(/<br\s*\/?>/gi, '\n').replace(/<\/(p|div|li|h[1-6])>/gi, '\n');
text = text.replace(/<\/?[a-zA-Z][^<>\n]*>/g, '');
text = text
.replace(/&nbsp;/g, ' ')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
.replace(/&amp;/g, '&');
// Images and links: keep the human-readable part, keep the URL only when it adds information.
text = text.replace(/!\[([^\]]*)\]\([^)\s]+(?:\s+"[^"]*")?\)/g, '$1');
text = text.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_m, label: string, url: string) =>
label === url || /^#/.test(url) ? label : `${label} (${url})`,
);
const lines = text.split('\n').map((line) => {
let l = line;
l = l.replace(/^\s{0,3}#{1,6}\s+/, ''); // headings
l = l.replace(/^\s{0,3}>\s?/, ''); // block quotes
l = l.replace(/^(\s*)[-*+]\s+(?=\S)/, '$1• '); // bullets
if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(l)) return ''; // horizontal rules
if (/^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(l)) return null; // table separator rows
if (/^\s*\|.*\|\s*$/.test(l)) {
l = l
.trim()
.replace(/^\||\|$/g, '')
.split('|')
.map((cell) => cell.trim())
.join(' · ');
}
return l;
});
text = lines.filter((l): l is string => l !== null).join('\n');
// Inline emphasis and code. Order matters: longest markers first.
text = text.replace(/(\*\*\*|___)(?=\S)([\s\S]*?\S)\1/g, '$2');
text = text.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g, '$2');
text = text.replace(/(?<![\w*])\*(?=\S)([^*\n]*?\S)\*(?![\w*])/g, '$1');
text = text.replace(/(?<![\w_])_(?=\S)([^_\n]*?\S)_(?![\w_])/g, '$1');
text = text.replace(/~~(?=\S)([\s\S]*?\S)~~/g, '$1');
text = text.replace(/`([^`\n]+)`/g, '$1');
// Whitespace: tabs to spaces, strip trailing space, at most one blank line in a row.
text = text
.replace(/\t/g, ' ')
.replace(/[ \t]+$/gm, '')
.replace(/\n{3,}/g, '\n\n');
return text.trim();
}
+367
View File
@@ -0,0 +1,367 @@
import type { TurnResult } from '@hermeven/contracts';
/**
* Pure interaction state machine. No I/O, no clocks, no randomness: everything
* that varies arrives inside an event, and everything to be done leaves as an
* effect. That is what makes cancellation and stale-result races testable.
*
* READY -> LISTENING -> TRANSCRIBING -> THINKING -> ANSWER
* with ERROR, DISCONNECTED and CANCELLED as explicit outcomes.
*/
export type Phase =
| 'unpaired'
| 'ready'
| 'listening'
| 'transcribing'
| 'thinking'
| 'approval'
| 'answer'
| 'error'
| 'disconnected'
| 'cancelled';
export interface HudError {
/** Stable code for the phone diagnostics view. */
code: string;
/** One short line for the HUD. */
hud: string;
/** Whether asking again (as a deliberate new turn) is reasonable. */
retryable: boolean;
}
export interface AppState {
phase: Phase;
/**
* Bumped whenever the user starts, cancels or abandons something. Every
* asynchronous effect carries the generation it was issued under, and an
* event from an older generation is dropped.
*/
generation: number;
conversationId: string | null;
requestId: string | null;
captureStartedAt: number | null;
captureMaxSeconds: number;
pages: string[];
pageIndex: number;
/** The answer is a partial one (agent stopped short). Shown on the HUD. */
partial: boolean;
error: HudError | null;
/** In DISCONNECTED: the request never reached the bridge, so resending it is safe. */
canResend: boolean;
/** Why we are disconnected: the bridge link, or the glasses themselves. */
disconnectedFrom: 'bridge' | 'glasses' | null;
notice: string | null;
}
export const initialState: AppState = {
phase: 'unpaired',
generation: 0,
conversationId: null,
requestId: null,
captureStartedAt: null,
captureMaxSeconds: 30,
pages: [],
pageIndex: 0,
partial: false,
error: null,
canResend: false,
disconnectedFrom: null,
notice: null,
};
export type AppEvent =
| { type: 'init'; paired: boolean; conversationId: string | null; captureMaxSeconds: number; resumeRequestId: string | null }
| { type: 'unpaired' }
/** Semantic actions. `freshId` is a new UUID supplied by the caller in case a turn starts. */
| { type: 'activate'; freshId: string }
| { type: 'back' }
| { type: 'next_page' }
| { type: 'prev_page' }
| { type: 'new_conversation' }
| { type: 'cancel' }
| { type: 'submit_text'; freshId: string; text: string }
| { type: 'capture_started'; generation: number; at: number }
| { type: 'capture_failed'; generation: number; reason: 'mic_refused' | 'mic_stalled' | 'empty' }
| { type: 'capture_limit'; generation: number }
| { type: 'conversation_created'; generation: number; conversationId: string }
| { type: 'conversation_failed'; generation: number; error: HudError }
/** `pages` is the already-paginated plain-text answer when the result carries one. */
| { type: 'turn_update'; generation: number; result: TurnResult; pages: string[] | null }
| { type: 'turn_rejected'; generation: number; error: HudError }
| { type: 'network_lost'; generation: number; stage: 'submit' | 'poll' }
| { type: 'network_restored'; generation: number }
| { type: 'glasses_status'; connected: boolean }
| { type: 'app_exit' };
export type Effect =
| { type: 'start_capture'; generation: number }
| { type: 'stop_capture_and_submit'; generation: number; requestId: string }
| { type: 'discard_capture' }
| { type: 'submit_text'; generation: number; requestId: string; text: string }
| { type: 'resubmit'; generation: number; requestId: string }
| { type: 'poll'; generation: number; requestId: string }
| { type: 'cancel_turn'; requestId: string }
| { type: 'create_conversation'; generation: number }
| { type: 'exit_dialog' };
export interface Step {
state: AppState;
effects: Effect[];
}
const IDLE: ReadonlySet<Phase> = new Set(['ready', 'answer', 'error', 'cancelled']);
const IN_FLIGHT: ReadonlySet<Phase> = new Set(['transcribing', 'thinking', 'approval']);
function clearTurn(state: AppState): AppState {
return {
...state,
requestId: null,
captureStartedAt: null,
pages: [],
pageIndex: 0,
partial: false,
error: null,
canResend: false,
disconnectedFrom: null,
notice: null,
};
}
function same(state: AppState): Step {
return { state, effects: [] };
}
/** Abandon whatever is in progress. The generation bump is what silences late results. */
function abandon(state: AppState): Step {
const effects: Effect[] = [];
if (state.phase === 'listening') effects.push({ type: 'discard_capture' });
else if (state.requestId && (IN_FLIGHT.has(state.phase) || state.phase === 'disconnected')) {
// Also drops any audio still held for a resend, and asks the bridge to stop the agent.
effects.push({ type: 'discard_capture' }, { type: 'cancel_turn', requestId: state.requestId });
}
return {
state: { ...clearTurn(state), phase: 'cancelled', generation: state.generation + 1 },
effects,
};
}
export function reduce(state: AppState, event: AppEvent): Step {
switch (event.type) {
case 'init': {
const base: AppState = {
...initialState,
generation: state.generation + 1,
captureMaxSeconds: event.captureMaxSeconds,
conversationId: event.conversationId,
};
if (!event.paired) return same({ ...base, phase: 'unpaired' });
if (event.resumeRequestId) {
// A turn was in flight when the page last died. Re-attach by polling: never resubmit,
// and never reopen the microphone on our own.
return {
state: { ...base, phase: 'thinking', requestId: event.resumeRequestId },
effects: [{ type: 'poll', generation: base.generation, requestId: event.resumeRequestId }],
};
}
return same({ ...base, phase: 'ready' });
}
case 'unpaired': {
const effects: Effect[] = state.phase === 'listening' ? [{ type: 'discard_capture' }] : [];
return {
state: { ...initialState, generation: state.generation + 1, captureMaxSeconds: state.captureMaxSeconds },
effects,
};
}
case 'activate': {
if (IDLE.has(state.phase)) {
const generation = state.generation + 1;
return {
state: { ...clearTurn(state), phase: 'listening', generation, requestId: event.freshId },
effects: [{ type: 'start_capture', generation }],
};
}
if (state.phase === 'listening' && state.requestId) {
return {
state: { ...state, phase: 'transcribing', captureStartedAt: null },
effects: [{ type: 'stop_capture_and_submit', generation: state.generation, requestId: state.requestId }],
};
}
if (state.phase === 'disconnected' && state.canResend && state.requestId) {
// Same request id: the bridge deduplicates, so this cannot run the turn twice.
return {
state: { ...state, phase: 'transcribing', disconnectedFrom: null },
effects: [{ type: 'resubmit', generation: state.generation, requestId: state.requestId }],
};
}
return same(state);
}
case 'capture_limit': {
if (event.generation !== state.generation || state.phase !== 'listening' || !state.requestId) return same(state);
return {
state: { ...state, phase: 'transcribing', captureStartedAt: null },
effects: [{ type: 'stop_capture_and_submit', generation: state.generation, requestId: state.requestId }],
};
}
case 'submit_text': {
if (!IDLE.has(state.phase)) return same(state);
const generation = state.generation + 1;
return {
state: { ...clearTurn(state), phase: 'thinking', generation, requestId: event.freshId },
effects: [{ type: 'submit_text', generation, requestId: event.freshId, text: event.text }],
};
}
case 'back': {
if (state.phase === 'ready' || state.phase === 'unpaired') return { state, effects: [{ type: 'exit_dialog' }] };
if (state.phase === 'listening' || IN_FLIGHT.has(state.phase) || state.phase === 'disconnected') return abandon(state);
// answer / error / cancelled: step back to the root page.
return same({ ...clearTurn(state), phase: 'ready' });
}
case 'cancel': {
if (state.phase === 'listening' || IN_FLIGHT.has(state.phase) || state.phase === 'disconnected') return abandon(state);
return same(state);
}
case 'next_page':
case 'prev_page': {
if (state.phase !== 'answer') return same(state);
const delta = event.type === 'next_page' ? 1 : -1;
const pageIndex = Math.min(state.pages.length - 1, Math.max(0, state.pageIndex + delta));
return same(pageIndex === state.pageIndex ? state : { ...state, pageIndex });
}
case 'new_conversation': {
// Only from a resting state: a reset must never be mistaken for cancelling the backend.
if (!IDLE.has(state.phase)) return same(state);
const generation = state.generation + 1;
return {
state: { ...clearTurn(state), phase: 'ready', generation, conversationId: null, notice: 'New conversation' },
effects: [{ type: 'create_conversation', generation }],
};
}
case 'conversation_created': {
if (event.generation !== state.generation) return same(state);
return same({ ...state, conversationId: event.conversationId });
}
case 'conversation_failed': {
if (event.generation !== state.generation) return same(state);
return same({ ...clearTurn(state), phase: 'error', error: event.error });
}
case 'capture_started': {
if (event.generation !== state.generation || state.phase !== 'listening') return same(state);
return same({ ...state, captureStartedAt: event.at });
}
case 'capture_failed': {
if (event.generation !== state.generation) return same(state);
if (state.phase !== 'listening' && state.phase !== 'transcribing') return same(state);
const hud =
event.reason === 'mic_refused'
? 'Microphone unavailable.'
: event.reason === 'mic_stalled'
? 'Microphone stopped.'
: 'Nothing was recorded.';
return {
state: { ...clearTurn(state), phase: 'error', error: { code: event.reason, hud, retryable: true } },
effects: [{ type: 'discard_capture' }],
};
}
case 'turn_update': {
if (event.generation !== state.generation || event.result.request_id !== state.requestId) return same(state);
if (!IN_FLIGHT.has(state.phase) && state.phase !== 'disconnected') return same(state);
const result = event.result;
if (!result.terminal) {
const phase: Phase =
result.state === 'transcribing' ? 'transcribing' : result.state === 'approval_required' ? 'approval' : 'thinking';
return same({ ...state, phase, disconnectedFrom: null, canResend: false });
}
const settled = { ...clearTurn(state), requestId: state.requestId };
switch (result.outcome) {
case 'succeeded':
case 'incomplete':
return same({
...settled,
phase: 'answer',
pages: event.pages ?? [''],
pageIndex: 0,
partial: result.outcome === 'incomplete',
});
case 'cancelled':
return same({
...settled,
phase: result.error ? 'error' : 'cancelled',
error: result.error ? { code: result.error.code, hud: result.error.message, retryable: result.error.retryable } : null,
});
default:
return same({
...settled,
phase: 'error',
error: {
code: result.error?.code ?? 'internal',
hud: result.error?.message ?? 'The request did not complete.',
retryable: result.error?.retryable ?? false,
},
});
}
}
case 'turn_rejected': {
if (event.generation !== state.generation) return same(state);
return { state: { ...clearTurn(state), phase: 'error', error: event.error }, effects: [{ type: 'discard_capture' }] };
}
case 'network_lost': {
if (event.generation !== state.generation) return same(state);
if (!IN_FLIGHT.has(state.phase) && state.phase !== 'disconnected') return same(state);
return same({ ...state, phase: 'disconnected', disconnectedFrom: 'bridge', canResend: event.stage === 'submit' });
}
case 'network_restored': {
if (event.generation !== state.generation || state.phase !== 'disconnected' || state.disconnectedFrom !== 'bridge') {
return same(state);
}
return same({ ...state, phase: 'thinking', disconnectedFrom: null, canResend: false });
}
case 'glasses_status': {
if (event.connected) {
if (state.phase === 'disconnected' && state.disconnectedFrom === 'glasses') {
// Back to rest. The microphone is never reopened without a fresh tap.
return same({ ...clearTurn(state), phase: 'ready' });
}
return same(state);
}
if (state.phase === 'listening') {
return {
state: {
...clearTurn(state),
phase: 'disconnected',
disconnectedFrom: 'glasses',
generation: state.generation + 1,
},
effects: [{ type: 'discard_capture' }],
};
}
if (IDLE.has(state.phase)) return same({ ...state, phase: 'disconnected', disconnectedFrom: 'glasses', canResend: false });
// A turn already in flight keeps running on the bridge; its result is still wanted.
return same(state);
}
case 'app_exit': {
if (state.phase !== 'listening') return same(state);
return {
state: { ...clearTurn(state), phase: 'ready', generation: state.generation + 1 },
effects: [{ type: 'discard_capture' }],
};
}
}
}
+178
View File
@@ -0,0 +1,178 @@
import {
AudioInputSource,
CreateStartUpPageContainer,
DeviceConnectType,
StartUpPageCreateResult,
TextContainerProperty,
TextContainerUpgrade,
type EvenAppBridge,
} from '@evenrealities/even_hub_sdk';
import { BODY_BOX, HUD, STATUS_BOX, type HudFrame } from '../core/hud.ts';
import { MENU_ITEM, normalizeEvent, type DeviceEvent, type RawEvenHubEvent } from './events.ts';
import type { DevicePort } from './port.ts';
const BODY = { id: 1, name: 'body' } as const;
const STATUS = { id: 2, name: 'status' } as const;
/** A flaky BLE hop can hang a bridge call for a long time; never let one block the UI forever. */
const CALL_TIMEOUT_MS = 8000;
function withTimeout<T>(promise: Promise<T>, fallback: T): Promise<T> {
return new Promise((resolve) => {
const timer = setTimeout(() => resolve(fallback), CALL_TIMEOUT_MS);
promise.then(
(value) => {
clearTimeout(timer);
resolve(value);
},
() => {
clearTimeout(timer);
resolve(fallback);
},
);
});
}
/**
* Adapter over the public Even Hub SDK (0.0.16). Only documented SDK calls are
* used: createStartUpPageContainer, textContainerUpgrade, audioControl,
* shutDownPageContainer, set/getLocalStorage, onEvenHubEvent, onDeviceStatusChanged.
*/
export class EvenDevice implements DevicePort {
private shown: HudFrame = { body: '', status: '' };
private pending: HudFrame | null = null;
private flushing = false;
private ready = false;
/** All host calls go through one queue: concurrent bridge calls are documented as unsafe. */
private queue: Promise<unknown> = Promise.resolve();
constructor(private readonly bridge: EvenAppBridge) {}
private enqueue<T>(call: () => Promise<T>, fallback: T): Promise<T> {
const next = this.queue.then(() => withTimeout(call(), fallback));
this.queue = next.catch(() => undefined);
return next;
}
async init(frame: HudFrame): Promise<boolean> {
const page = new CreateStartUpPageContainer({
containerTotalNum: 2,
textObject: [
new TextContainerProperty({
xPosition: BODY_BOX.x,
yPosition: BODY_BOX.y,
width: BODY_BOX.width,
height: BODY_BOX.height,
borderWidth: 0,
paddingLength: HUD.padding,
containerID: BODY.id,
containerName: BODY.name,
content: frame.body || ' ',
isEventCapture: 1,
}),
new TextContainerProperty({
xPosition: STATUS_BOX.x,
yPosition: STATUS_BOX.y,
width: STATUS_BOX.width,
height: STATUS_BOX.height,
borderWidth: 0,
paddingLength: HUD.padding,
containerID: STATUS.id,
containerName: STATUS.name,
content: frame.status || ' ',
isEventCapture: 0,
}),
],
// Extra entries in the OS contextual menu (tap, then long press). The OS adds its
// own "Close" entry, so no exit item is declared here.
menuObject: {
menuItems: [
{ itemName: 'New conversation', itemID: MENU_ITEM.NEW_CONVERSATION },
{ itemName: 'Cancel request', itemID: MENU_ITEM.CANCEL },
],
} as never,
});
const result = await this.enqueue(() => this.bridge.createStartUpPageContainer(page), StartUpPageCreateResult.invalid);
this.ready = result === StartUpPageCreateResult.success;
if (this.ready) this.shown = { body: frame.body || ' ', status: frame.status || ' ' };
return this.ready;
}
show(frame: HudFrame): void {
this.pending = { body: frame.body || ' ', status: frame.status || ' ' };
if (!this.flushing) void this.flush();
}
private async flush(): Promise<void> {
this.flushing = true;
try {
while (this.pending && this.ready) {
const frame = this.pending;
this.pending = null;
// In-place text updates are flicker-free; a page rebuild is not needed for text changes.
if (frame.body !== this.shown.body) {
const ok = await this.enqueue(
() =>
this.bridge.textContainerUpgrade(
new TextContainerUpgrade({ containerID: BODY.id, containerName: BODY.name, content: frame.body }),
),
false,
);
if (ok) this.shown.body = frame.body;
}
if (frame.status !== this.shown.status) {
const ok = await this.enqueue(
() =>
this.bridge.textContainerUpgrade(
new TextContainerUpgrade({ containerID: STATUS.id, containerName: STATUS.name, content: frame.status }),
),
false,
);
if (ok) this.shown.status = frame.status;
}
}
} finally {
this.flushing = false;
}
}
startMic(): Promise<boolean> {
return this.enqueue(() => this.bridge.audioControl(true, AudioInputSource.Glasses), false);
}
async stopMic(): Promise<void> {
await this.enqueue(() => this.bridge.audioControl(false), false);
}
onEvent(listener: (event: DeviceEvent) => void): () => void {
return this.bridge.onEvenHubEvent((event) => {
for (const normalized of normalizeEvent(event as RawEvenHubEvent)) listener(normalized);
});
}
onConnection(listener: (connected: boolean) => void): () => void {
return this.bridge.onDeviceStatusChanged((status) => {
if (status.connectType === DeviceConnectType.Connected) listener(true);
else if (
status.connectType === DeviceConnectType.Disconnected ||
status.connectType === DeviceConnectType.ConnectionFailed
) {
listener(false);
}
});
}
async requestExit(): Promise<void> {
// Mode 1: the OS shows its own confirmation. Cleanup happens on SYSTEM_EXIT, not here,
// because the user can still decline.
await this.enqueue(() => this.bridge.shutDownPageContainer(1), false);
}
storageGet(key: string): Promise<string> {
return this.enqueue(() => this.bridge.getLocalStorage(key), '');
}
async storageSet(key: string, value: string): Promise<void> {
await this.enqueue(() => this.bridge.setLocalStorage(key, value), false);
}
}
+100
View File
@@ -0,0 +1,100 @@
/**
* Normalise raw Even Hub events into Hermeven's device-neutral vocabulary.
*
* Kept free of SDK imports (numbers below are the SDK's `OsEventTypeList`
* values, asserted against the real enum in the tests) so the mapping is a
* pure function over plain objects.
*/
export const OS_EVENT = {
CLICK: 0,
SCROLL_TOP: 1,
SCROLL_BOTTOM: 2,
DOUBLE_CLICK: 3,
FOREGROUND_ENTER: 4,
FOREGROUND_EXIT: 5,
ABNORMAL_EXIT: 6,
SYSTEM_EXIT: 7,
IMU_DATA_REPORT: 8,
LONG_PRESS: 9,
LONG_PRESS_RELEASE: 10,
} as const;
export const MENU_ITEM = { NEW_CONVERSATION: 1, CANCEL: 2 } as const;
export type DeviceEvent =
| { type: 'tap' }
| { type: 'double_tap' }
| { type: 'swipe_up' }
| { type: 'swipe_down' }
| { type: 'menu'; itemId: number }
| { type: 'audio'; pcm: Uint8Array }
| { type: 'foreground_enter' }
| { type: 'foreground_exit' }
| { type: 'system_exit' }
| { type: 'abnormal_exit' };
interface Envelope {
eventType?: number;
}
export interface RawEvenHubEvent {
listEvent?: Envelope;
textEvent?: Envelope;
sysEvent?: Envelope;
audioEvent?: { audioPcm?: Uint8Array };
menuItemClickEvent?: { itemID?: number };
}
/**
* CLICK_EVENT is 0 and protobuf omits zero-valued fields, so a tap arrives as
* an envelope with no `eventType` at all. The default must be applied per
* envelope: an event with no gesture envelope (audio, menu) is not a tap.
*/
function typeOf(envelope: Envelope | undefined): number | null {
if (!envelope) return null;
return envelope.eventType ?? OS_EVENT.CLICK;
}
export function normalizeEvent(event: RawEvenHubEvent): DeviceEvent[] {
const out: DeviceEvent[] = [];
const pcm = event.audioEvent?.audioPcm;
if (pcm && pcm.length > 0) out.push({ type: 'audio', pcm });
const itemId = event.menuItemClickEvent?.itemID;
if (typeof itemId === 'number') out.push({ type: 'menu', itemId });
// Official sources disagree on whether gestures arrive on textEvent or sysEvent,
// so both are read. One raw event carries one gesture; the first envelope wins.
const gesture = typeOf(event.sysEvent) ?? typeOf(event.textEvent) ?? typeOf(event.listEvent);
switch (gesture) {
case OS_EVENT.DOUBLE_CLICK:
out.push({ type: 'double_tap' });
break;
case OS_EVENT.SCROLL_TOP:
out.push({ type: 'swipe_up' });
break;
case OS_EVENT.SCROLL_BOTTOM:
out.push({ type: 'swipe_down' });
break;
case OS_EVENT.FOREGROUND_ENTER:
out.push({ type: 'foreground_enter' });
break;
case OS_EVENT.FOREGROUND_EXIT:
out.push({ type: 'foreground_exit' });
break;
case OS_EVENT.ABNORMAL_EXIT:
out.push({ type: 'abnormal_exit' });
break;
case OS_EVENT.SYSTEM_EXIT:
out.push({ type: 'system_exit' });
break;
case OS_EVENT.CLICK:
out.push({ type: 'tap' });
break;
default:
// IMU reports and long press are not part of the interaction contract.
break;
}
return out;
}
+19
View File
@@ -0,0 +1,19 @@
import type { HudFrame } from '../core/hud.ts';
import type { DeviceEvent } from './events.ts';
/** Everything Hermeven needs from the glasses runtime. Implemented by the Even adapter and by test fakes. */
export interface DevicePort {
/** Create the HUD page. Resolves false when the host refused it. */
init(frame: HudFrame): Promise<boolean>;
/** Show a frame. Calls are serialised and coalesced; only the latest pending frame is sent. */
show(frame: HudFrame): void;
/** Open the glasses microphone. Resolves false when the host refused (for example no permission). */
startMic(): Promise<boolean>;
stopMic(): Promise<void>;
onEvent(listener: (event: DeviceEvent) => void): () => void;
onConnection(listener: (connected: boolean) => void): () => void;
/** Ask the OS to show its own exit confirmation. */
requestExit(): Promise<void>;
storageGet(key: string): Promise<string>;
storageSet(key: string, value: string): Promise<void>;
}
@@ -0,0 +1,87 @@
import type { HudFrame } from '../core/hud.ts';
import type { DeviceEvent } from './events.ts';
import type { DevicePort } from './port.ts';
/**
* Stand-in for the glasses when the page runs in a plain browser (no Even host).
* Draws the two HUD text areas in the page and offers buttons for the gestures.
* It has NO microphone: a tap that would start recording reports the mic as
* unavailable. Nothing shown here is evidence about real hardware.
*/
export class BrowserPreviewDevice implements DevicePort {
private readonly body = document.createElement('pre');
private readonly status = document.createElement('pre');
private readonly listeners = new Set<(event: DeviceEvent) => void>();
constructor(container: HTMLElement) {
this.body.className = 'hud-body';
this.status.className = 'hud-status';
const label = document.createElement('p');
label.className = 'hint';
label.textContent = 'Browser preview of the HUD text. Not the glasses, not the simulator; fonts and wrapping differ.';
const controls = document.createElement('div');
controls.className = 'row';
const gestures: Array<[string, DeviceEvent]> = [
['Tap', { type: 'tap' }],
['Double-tap', { type: 'double_tap' }],
['Swipe up', { type: 'swipe_up' }],
['Swipe down', { type: 'swipe_down' }],
];
for (const [text, event] of gestures) {
const button = document.createElement('button');
button.type = 'button';
button.className = 'secondary';
button.textContent = text;
button.addEventListener('click', () => this.listeners.forEach((l) => l(event)));
controls.append(button);
}
const screen = document.createElement('div');
screen.className = 'hud';
screen.append(this.body, this.status);
container.append(label, screen, controls);
}
async init(frame: HudFrame): Promise<boolean> {
this.show(frame);
return true;
}
show(frame: HudFrame): void {
this.body.textContent = frame.body;
this.status.textContent = frame.status;
}
async startMic(): Promise<boolean> {
return false;
}
async stopMic(): Promise<void> {}
onEvent(listener: (event: DeviceEvent) => void): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
onConnection(): () => void {
return () => undefined;
}
async requestExit(): Promise<void> {}
async storageGet(key: string): Promise<string> {
try {
return localStorage.getItem(key) ?? '';
} catch {
return '';
}
}
async storageSet(key: string, value: string): Promise<void> {
try {
if (value) localStorage.setItem(key, value);
else localStorage.removeItem(key);
} catch {
/* preview only */
}
}
}
+64
View File
@@ -0,0 +1,64 @@
import { waitForEvenAppBridge } from '@evenrealities/even_hub_sdk';
import { measureTextWrap } from '@evenrealities/pretext';
import { Controller } from './core/controller.ts';
import { EvenDevice } from './device/evenAdapter.ts';
import { BrowserPreviewDevice } from './device/previewDevice.ts';
import type { DevicePort } from './device/port.ts';
import { mountPhoneUi } from './ui/phone.ts';
import './ui/phone.css';
/**
* Entry point. Inside the Even app (or the Even Hub simulator) the SDK bridge
* is present and the real adapter is used. In a plain browser there is no
* bridge, so a clearly-labelled preview device is used instead: it has no
* microphone and proves nothing about hardware.
*/
async function resolveDevice(): Promise<{ device: DevicePort; runtime: string }> {
const hasHost = typeof (window as { flutter_inappwebview?: unknown }).flutter_inappwebview !== 'undefined';
if (hasHost) {
const bridge = await waitForEvenAppBridge();
return { device: new EvenDevice(bridge), runtime: 'Even app host (SDK 0.0.16)' };
}
const preview = document.getElementById('preview')!;
preview.hidden = false;
return { device: new BrowserPreviewDevice(preview), runtime: 'Browser preview: no glasses, no microphone' };
}
const { device, runtime } = await resolveDevice();
const root = document.getElementById('app')!;
let update: (snapshot: ReturnType<Controller['snapshot']>) => void = () => undefined;
const controller = new Controller({
device,
measure: (text, width) => measureTextWrap(text, width).lineCount,
locale: navigator.language || 'en-US',
onChange: (snapshot) => update(snapshot),
// Development builds mirror diagnostics to the console (visible in the simulator and the
// Even dev console). Diagnostics never contain questions, answers or credentials.
onNote: import.meta.env.DEV ? (entry) => console.info(`[hermeven] ${entry.kind}: ${entry.detail}`) : undefined,
});
update = mountPhoneUi(root, controller, {
bridgeUrl: import.meta.env.VITE_HERMEVEN_BRIDGE_URL ?? '',
runtime,
});
// Never leave the microphone open behind a page that is going away.
window.addEventListener('beforeunload', () => void controller.stop());
await controller.start();
update(controller.snapshot());
// Development-only convenience for automated simulator runs, where nothing can type into the
// phone page: `?bridge=<url>&pair=<code>` pairs on load. Compiled out of production builds.
if (import.meta.env.DEV) {
const params = new URLSearchParams(location.search);
const bridgeUrl = params.get('bridge');
const code = params.get('pair');
if (bridgeUrl && code && !controller.snapshot().paired) {
try {
await controller.pair(bridgeUrl, code, 'dev');
} catch (err) {
console.info(`[hermeven] dev-pair: failed ${err instanceof Error ? err.name : ''}`);
}
}
}
+156
View File
@@ -0,0 +1,156 @@
import {
AUDIO_FORMAT,
check,
ConversationResponse,
DeviceCredential,
DeviceStatusResponse,
ErrorResponse,
RevokeResponse,
SCHEMA_VERSION,
TurnResult,
type ErrorBody,
} from '@hermeven/contracts';
import type { TSchema } from '@sinclair/typebox';
/** The bridge answered with a contract error. */
export class BridgeApiError extends Error {
override name = 'BridgeApiError';
constructor(
readonly status: number,
readonly body: ErrorBody,
) {
super(body.message);
}
}
/** No usable answer: offline, timeout, CORS/whitelist block, or a non-contract response. */
export class BridgeNetworkError extends Error {
override name = 'BridgeNetworkError';
}
export interface BridgeClientOptions {
baseUrl: string;
token?: string;
timeoutMs?: number;
fetchImpl?: typeof fetch;
}
export function normalizeBridgeUrl(raw: string): string {
const url = new URL(raw.trim());
if (url.protocol !== 'https:' && url.protocol !== 'http:') throw new Error('Bridge URL must start with https://');
return url.origin + url.pathname.replace(/\/+$/, '');
}
export class BridgeClient {
private readonly baseUrl: string;
private readonly timeoutMs: number;
private readonly fetchImpl: typeof fetch;
token: string;
constructor(options: BridgeClientOptions) {
this.baseUrl = normalizeBridgeUrl(options.baseUrl);
this.token = options.token ?? '';
this.timeoutMs = options.timeoutMs ?? 15_000;
this.fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init));
}
private async call<T extends TSchema>(
schema: T,
method: string,
path: string,
init: { json?: unknown; binary?: Uint8Array; auth?: boolean } = {},
): Promise<T['static']> {
const headers: Record<string, string> = { Accept: 'application/json' };
if (init.auth !== false) headers.Authorization = `Bearer ${this.token}`;
let body: BodyInit | undefined;
if (init.json !== undefined) {
headers['Content-Type'] = 'application/json';
body = JSON.stringify(init.json);
} else if (init.binary) {
headers['Content-Type'] = 'application/octet-stream';
body = init.binary as unknown as BodyInit;
}
let res: Response;
let payload: unknown;
try {
res = await this.fetchImpl(`${this.baseUrl}${path}`, {
method,
headers,
body,
signal: AbortSignal.timeout(this.timeoutMs),
credentials: 'omit',
cache: 'no-store',
});
payload = await res.json();
} catch (err) {
throw new BridgeNetworkError(err instanceof Error ? err.name : 'network error');
}
if (!res.ok) {
if (check(ErrorResponse, payload)) throw new BridgeApiError(res.status, payload.error as ErrorBody);
// A proxy or captive portal answered instead of the bridge.
throw new BridgeNetworkError(`unexpected HTTP ${res.status}`);
}
// A 200 that is not a valid contract response is not proof of anything.
if (!check(schema, payload)) throw new BridgeNetworkError('response did not match the contract');
return payload;
}
claim(code: string, deviceName: string): Promise<DeviceCredential> {
return this.call(DeviceCredential, 'POST', '/v1/pairing/claim', {
auth: false,
json: { schema_version: SCHEMA_VERSION, code, device_name: deviceName },
});
}
device(): Promise<DeviceStatusResponse> {
return this.call(DeviceStatusResponse, 'GET', '/v1/device');
}
renew(): Promise<DeviceCredential> {
return this.call(DeviceCredential, 'POST', '/v1/device/renew', { json: {} });
}
revoke(): Promise<RevokeResponse> {
return this.call(RevokeResponse, 'DELETE', '/v1/device');
}
createConversation(): Promise<ConversationResponse> {
return this.call(ConversationResponse, 'POST', '/v1/conversations', { json: { schema_version: SCHEMA_VERSION } });
}
submitText(args: { requestId: string; conversationId: string; locale: string; text: string }): Promise<TurnResult> {
return this.call(TurnResult, 'POST', '/v1/turns', {
json: {
schema_version: SCHEMA_VERSION,
request_id: args.requestId,
conversation_id: args.conversationId,
locale: args.locale,
input: { kind: 'text', text: args.text },
},
}) as Promise<TurnResult>;
}
/** Raw PCM as the request body; metadata travels in the query string, never the audio in JSON. */
submitAudio(args: { requestId: string; conversationId: string; locale: string; pcm: Uint8Array }): Promise<TurnResult> {
const query = new URLSearchParams({
schema_version: String(SCHEMA_VERSION),
request_id: args.requestId,
conversation_id: args.conversationId,
locale: args.locale,
input_kind: 'audio',
encoding: AUDIO_FORMAT.encoding,
sample_rate: String(AUDIO_FORMAT.sampleRate),
channels: String(AUDIO_FORMAT.channels),
});
return this.call(TurnResult, 'POST', `/v1/turns?${query}`, { binary: args.pcm }) as Promise<TurnResult>;
}
getTurn(requestId: string): Promise<TurnResult> {
return this.call(TurnResult, 'GET', `/v1/turns/${requestId}`) as Promise<TurnResult>;
}
cancelTurn(requestId: string): Promise<TurnResult> {
return this.call(TurnResult, 'POST', `/v1/turns/${requestId}/cancel`, { json: {} }) as Promise<TurnResult>;
}
}
+171
View File
@@ -0,0 +1,171 @@
:root {
color-scheme: light dark;
--bg: #f6f6f4;
--surface: #ffffff;
--text: #1c1c1a;
--muted: #62625c;
--line: #d9d9d3;
--accent: #1f5fbf;
--danger: #b3261e;
font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
-webkit-text-size-adjust: 100%;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #131312;
--surface: #1e1e1c;
--text: #ececE6;
--muted: #a3a39b;
--line: #3a3a36;
--accent: #8ab4f8;
--danger: #f2b8b5;
}
}
* {
box-sizing: border-box;
}
body {
margin: 0;
background: var(--bg);
color: var(--text);
line-height: 1.45;
overscroll-behavior: none;
touch-action: manipulation;
}
#app,
#preview {
max-width: 40rem;
margin: 0 auto;
padding: 0 16px 16px;
}
h1 {
font-size: 1.4rem;
margin: 20px 0 8px;
}
h2 {
font-size: 1.05rem;
margin: 0 0 8px;
}
h3 {
font-size: 0.85rem;
margin: 12px 0 2px;
color: var(--muted);
font-weight: 600;
}
section,
details {
background: var(--surface);
border: 1px solid var(--line);
border-radius: 10px;
padding: 14px;
margin: 12px 0;
}
label {
display: block;
font-size: 0.85rem;
color: var(--muted);
margin: 10px 0;
}
input,
textarea {
display: block;
width: 100%;
margin-top: 4px;
padding: 10px;
font: inherit;
color: var(--text);
background: var(--bg);
border: 1px solid var(--line);
border-radius: 8px;
}
button {
font: inherit;
font-weight: 600;
min-height: 44px;
padding: 8px 16px;
border-radius: 8px;
border: 1px solid var(--accent);
background: var(--accent);
color: var(--bg);
}
button.secondary {
background: transparent;
color: var(--accent);
}
button.danger {
background: transparent;
border-color: var(--danger);
color: var(--danger);
}
button:disabled {
opacity: 0.45;
}
.row {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 10px;
}
.hint {
font-size: 0.85rem;
color: var(--muted);
margin: 4px 0;
}
.message {
min-height: 1.4em;
margin: 4px 0;
}
.bad {
color: var(--danger);
}
.phase {
font-weight: 600;
margin: 0;
}
dl {
display: grid;
grid-template-columns: minmax(7rem, auto) 1fr;
gap: 4px 12px;
margin: 0;
font-size: 0.9rem;
}
dt {
color: var(--muted);
}
dd {
margin: 0;
overflow-wrap: anywhere;
}
.answer,
.turn p {
white-space: pre-wrap;
overflow-wrap: anywhere;
margin: 0;
}
.log {
font-size: 0.72rem;
overflow-x: auto;
max-height: 16rem;
margin: 10px 0 0;
white-space: pre;
}
.hud {
background: #000;
border-radius: 8px;
padding: 8px;
margin: 8px 0;
}
.hud pre {
margin: 0;
color: #d8ffd8;
font-size: 0.85rem;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.hud-body {
min-height: 9em;
}
.hud-status {
border-top: 1px solid #244;
padding-top: 4px;
}
+217
View File
@@ -0,0 +1,217 @@
import type { Controller, Snapshot } from '../core/controller.ts';
import { BridgeApiError, BridgeNetworkError, normalizeBridgeUrl } from '../net/bridgeClient.ts';
/**
* Phone-side page: pairing, status, diagnostics, typed input and disconnect.
* Built with DOM APIs and textContent only, so nothing from the bridge or the
* agent is ever interpreted as HTML.
*/
function el<K extends keyof HTMLElementTagNameMap>(
tag: K,
props: Partial<HTMLElementTagNameMap[K]> & { class?: string } = {},
children: Array<Node | string> = [],
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag);
const { class: className, ...rest } = props;
if (className) node.className = className;
Object.assign(node, rest);
for (const child of children) node.append(child);
return node;
}
function explain(err: unknown): string {
if (err instanceof BridgeApiError) return `${err.body.message} (${err.body.code})`;
if (err instanceof BridgeNetworkError) {
return (
'Could not reach the bridge. Check the address, that the bridge is running, that this app build ' +
"lists the bridge in its network whitelist, and that the bridge allows this page's origin."
);
}
return err instanceof Error ? err.message : 'Something went wrong.';
}
const PHASE_LABEL: Record<string, string> = {
unpaired: 'Not paired',
ready: 'Ready',
listening: 'Listening (microphone open)',
transcribing: 'Transcribing',
thinking: 'Thinking',
approval: 'Approval required',
answer: 'Answer shown',
error: 'Error',
disconnected: 'Disconnected',
cancelled: 'Cancelled',
};
export function mountPhoneUi(root: HTMLElement, controller: Controller, defaults: { bridgeUrl: string; runtime: string }): (s: Snapshot) => void {
root.replaceChildren();
const message = el('p', { class: 'message', role: 'status' } as never);
const say = (text: string, bad = false) => {
message.textContent = text;
message.className = bad ? 'message bad' : 'message';
};
async function guarded(button: HTMLButtonElement, action: () => Promise<string | void>): Promise<void> {
button.disabled = true;
try {
const result = await action();
if (result) say(result);
} catch (err) {
say(explain(err), true);
} finally {
button.disabled = false;
}
}
// ---- pairing
const urlInput = el('input', { type: 'url', value: defaults.bridgeUrl, placeholder: 'https://bridge.example', autocomplete: 'off' });
const codeInput = el('input', { type: 'text', placeholder: 'ABCDE-FGHJK', autocomplete: 'off', autocapitalize: 'characters' } as never);
const nameInput = el('input', { type: 'text', value: 'G2', maxLength: 60 });
const pairButton = el('button', { type: 'button', textContent: 'Pair' });
pairButton.addEventListener('click', () =>
guarded(pairButton, async () => {
const url = normalizeBridgeUrl(urlInput.value);
await controller.pair(url, codeInput.value.trim(), nameInput.value.trim() || 'G2');
codeInput.value = '';
return 'Paired.';
}),
);
const pairing = el('section', {}, [
el('h2', { textContent: 'Pair with your bridge' }),
el('p', { class: 'hint', textContent: 'On the bridge host run “npm run bridge:cli -- pair” and enter the code it prints. Codes work once and expire in a few minutes.' }),
el('label', {}, ['Bridge address', urlInput]),
el('label', {}, ['Pairing code', codeInput]),
el('label', {}, ['Device name', nameInput]),
pairButton,
]);
// ---- status
const statusList = el('dl');
const refreshButton = el('button', { type: 'button', class: 'secondary', textContent: 'Refresh' });
refreshButton.addEventListener('click', () => guarded(refreshButton, () => controller.refreshStatus()));
const renewButton = el('button', { type: 'button', class: 'secondary', textContent: 'Renew credential' });
renewButton.addEventListener('click', () => guarded(renewButton, async () => (await controller.renew(), 'Credential renewed.')));
const disconnectButton = el('button', { type: 'button', class: 'danger', textContent: 'Disconnect' });
disconnectButton.addEventListener('click', () =>
guarded(disconnectButton, async () => {
const { revoked } = await controller.disconnect();
return revoked
? 'Disconnected. The credential was revoked and removed from this phone.'
: 'Removed from this phone, but the bridge could not be reached. Revoke this device on the bridge host to finish.';
}),
);
const status = el('section', {}, [
el('h2', { textContent: 'Connection' }),
statusList,
el('div', { class: 'row' }, [refreshButton, renewButton, disconnectButton]),
]);
// ---- conversation and typed input
const textInput = el('textarea', { rows: 3, placeholder: 'Type a question (for testing, or when speaking is not possible)' });
const askButton = el('button', { type: 'button', textContent: 'Ask' });
askButton.addEventListener('click', () => {
controller.askText(textInput.value);
textInput.value = '';
});
const cancelButton = el('button', { type: 'button', class: 'secondary', textContent: 'Cancel request' });
cancelButton.addEventListener('click', () => controller.cancel());
const newButton = el('button', { type: 'button', class: 'secondary', textContent: 'New conversation' });
newButton.addEventListener('click', () => controller.newConversation());
const phase = el('p', { class: 'phase' });
const captureNote = el('p', { class: 'hint' });
const turnView = el('div', { class: 'turn' });
const conversation = el('section', {}, [
el('h2', { textContent: 'Conversation' }),
phase,
captureNote,
el('label', {}, ['Typed question', textInput]),
el('div', { class: 'row' }, [askButton, cancelButton, newButton]),
turnView,
]);
// ---- diagnostics
const diagList = el('dl');
const logView = el('pre', { class: 'log' });
const diagnostics = el('details', {}, [
el('summary', { textContent: 'Diagnostics' }),
el('p', { class: 'hint', textContent: 'Identifiers, states and timings only. Questions and answers are not written to this log.' }),
diagList,
logView,
]);
root.append(el('h1', { textContent: 'Hermeven' }), message, pairing, status, conversation, diagnostics);
const rows = (list: HTMLElement, entries: Array<[string, string]>) => {
list.replaceChildren(...entries.flatMap(([k, v]) => [el('dt', { textContent: k }), el('dd', { textContent: v })]));
};
const when = (iso: string) => (iso ? new Date(iso).toLocaleString() : 'unknown');
return (s: Snapshot) => {
pairing.hidden = s.paired;
status.hidden = !s.paired;
conversation.hidden = !s.paired;
rows(statusList, [
['Bridge', s.bridgeUrl],
['Agent', s.status ? (s.status.agent_reachable ? 'reachable' : 'not reachable from the bridge') : 'not checked'],
['Speech-to-text', s.status ? (s.status.stt_configured ? 'configured' : 'not configured (typed questions only)') : 'not checked'],
['Credential valid until', when(s.tokenExpiresAt)],
['Pairing valid until', when(s.pairingExpiresAt)],
['Stored on this phone', 'In the Even app’s app storage, which is not an encrypted vault. The credential is revocable and expires.'],
]);
phase.textContent = PHASE_LABEL[s.state.phase] ?? s.state.phase;
captureNote.textContent =
`Recording starts only when you tap the glasses, shows “● REC” for as long as the microphone is open, ` +
`and stops by itself after ${s.state.captureMaxSeconds} seconds.`;
const inFlight = ['listening', 'transcribing', 'thinking', 'approval', 'disconnected'].includes(s.state.phase);
askButton.disabled = inFlight;
newButton.disabled = inFlight;
cancelButton.disabled = !inFlight;
const t = s.lastTurn;
turnView.replaceChildren();
if (s.state.error) {
turnView.append(el('p', { class: 'bad', textContent: `${s.state.error.hud} [${s.state.error.code}]` }));
}
if (t) {
if (t.input_text) turnView.append(el('h3', { textContent: 'Sent to the agent' }), el('p', { textContent: t.input_text }));
if (t.answer_text !== null) {
turnView.append(
el('h3', { textContent: t.outcome === 'incomplete' ? 'Partial answer' : 'Answer' }),
el('p', { class: 'answer', textContent: t.answer_text }),
);
}
turnView.append(
el('p', {
class: 'hint',
textContent:
`Outcome: ${t.outcome ?? 'pending'}${t.error ? ` · ${t.error.code}` : ''}` +
`${t.cancel_requested ? ' · cancel was requested' : ''}`,
}),
);
}
rows(diagList, [
['Runtime', defaults.runtime],
['Page origin', location.origin],
['HUD page', s.hudReady ? 'created' : 'not created'],
['Device id', s.deviceId || 'none'],
['Conversation id', s.state.conversationId ?? 'none'],
['Request id', s.state.requestId ?? 'none'],
['Generation', String(s.state.generation)],
['Audio format', s.status ? `${s.status.audio_format.encoding} ${s.status.audio_format.sample_rate} Hz × ${s.status.audio_format.channels}` : 'unknown'],
[
'Deadlines',
s.status
? `transcribe ${s.status.limits.transcribe_deadline_seconds} s · agent ${s.status.limits.agent_deadline_seconds} s · approval ${s.status.limits.approval_wait_seconds} s`
: 'unknown',
],
]);
logView.textContent = s.log
.slice(-60)
.map((e) => `${new Date(e.at).toISOString().slice(11, 23)} ${e.kind.padEnd(12)} ${e.detail}`)
.join('\n');
};
}
+77
View File
@@ -0,0 +1,77 @@
import { evenHubEventFromJson, OsEventTypeList } from '@evenrealities/even_hub_sdk';
import { describe, expect, it } from 'vitest';
import { normalizeEvent, OS_EVENT, type RawEvenHubEvent } from '../src/device/events.ts';
/**
* These run the published SDK's own parser (`evenHubEventFromJson`) over host
* payload shapes, then our normaliser. They verify our mapping against the SDK
* as shipped, not against a pair of glasses.
*/
const parse = (payload: unknown) => normalizeEvent(evenHubEventFromJson(payload) as RawEvenHubEvent);
describe('event constants', () => {
it('match the SDK enum', () => {
expect(OS_EVENT).toEqual({
CLICK: OsEventTypeList.CLICK_EVENT,
SCROLL_TOP: OsEventTypeList.SCROLL_TOP_EVENT,
SCROLL_BOTTOM: OsEventTypeList.SCROLL_BOTTOM_EVENT,
DOUBLE_CLICK: OsEventTypeList.DOUBLE_CLICK_EVENT,
FOREGROUND_ENTER: OsEventTypeList.FOREGROUND_ENTER_EVENT,
FOREGROUND_EXIT: OsEventTypeList.FOREGROUND_EXIT_EVENT,
ABNORMAL_EXIT: OsEventTypeList.ABNORMAL_EXIT_EVENT,
SYSTEM_EXIT: OsEventTypeList.SYSTEM_EXIT_EVENT,
IMU_DATA_REPORT: OsEventTypeList.IMU_DATA_REPORT,
LONG_PRESS: OsEventTypeList.LONG_PRESS_EVENT,
LONG_PRESS_RELEASE: OsEventTypeList.LONG_PRESS_RELEASE_EVENT,
});
});
});
describe('gestures through the SDK parser', () => {
it('a tap arrives with no eventType (protobuf omits zero) on either envelope', () => {
expect(parse({ type: 'sysEvent', jsonData: { eventSource: 1 } })).toEqual([{ type: 'tap' }]);
expect(parse({ type: 'textEvent', jsonData: { containerID: 1, containerName: 'body' } })).toEqual([{ type: 'tap' }]);
expect(parse({ type: 'sysEvent', jsonData: { eventType: 0 } })).toEqual([{ type: 'tap' }]);
});
it('double tap, swipes and lifecycle map from sysEvent and textEvent', () => {
expect(parse({ type: 'sysEvent', jsonData: { eventType: 3 } })).toEqual([{ type: 'double_tap' }]);
expect(parse({ type: 'textEvent', jsonData: { eventType: 3 } })).toEqual([{ type: 'double_tap' }]);
expect(parse({ type: 'textEvent', jsonData: { eventType: 1 } })).toEqual([{ type: 'swipe_up' }]);
expect(parse({ type: 'textEvent', jsonData: { eventType: 2 } })).toEqual([{ type: 'swipe_down' }]);
expect(parse({ type: 'sysEvent', jsonData: { eventType: 'SCROLL_BOTTOM_EVENT' } })).toEqual([{ type: 'swipe_down' }]);
expect(parse({ type: 'sysEvent', jsonData: { eventType: 4 } })).toEqual([{ type: 'foreground_enter' }]);
expect(parse({ type: 'sysEvent', jsonData: { eventType: 5 } })).toEqual([{ type: 'foreground_exit' }]);
expect(parse({ type: 'sysEvent', jsonData: { eventType: 6 } })).toEqual([{ type: 'abnormal_exit' }]);
expect(parse({ type: 'sysEvent', jsonData: { eventType: 7 } })).toEqual([{ type: 'system_exit' }]);
});
it('ring and left-temple sources produce the same semantic gestures', () => {
for (const eventSource of [1, 2, 3]) {
expect(parse({ type: 'sysEvent', jsonData: { eventSource } })).toEqual([{ type: 'tap' }]);
expect(parse({ type: 'sysEvent', jsonData: { eventSource, eventType: 3 } })).toEqual([{ type: 'double_tap' }]);
}
});
it('audio frames are never mistaken for taps', () => {
const out = parse({ type: 'audioEvent', jsonData: { audioPcm: [1, 2, 3, 4] } });
expect(out).toHaveLength(1);
expect(out[0]!.type).toBe('audio');
expect(Array.from((out[0] as { pcm: Uint8Array }).pcm)).toEqual([1, 2, 3, 4]);
});
it('menu selections carry their item id and are not taps', () => {
expect(parse({ type: 'menuItemClickEvent', jsonData: { itemID: 2 } })).toEqual([{ type: 'menu', itemId: 2 }]);
});
it('IMU reports and long presses are outside the interaction contract', () => {
expect(parse({ type: 'sysEvent', jsonData: { eventType: 8, imuData: { x: 1, y: 2, z: 3 } } })).toEqual([]);
expect(parse({ type: 'sysEvent', jsonData: { eventType: 9 } })).toEqual([]);
expect(parse({ type: 'sysEvent', jsonData: { eventType: 10 } })).toEqual([]);
});
it('an empty or unknown event produces nothing', () => {
expect(normalizeEvent({})).toEqual([]);
expect(parse({ type: 'somethingNew', jsonData: {} })).toEqual([]);
});
});
+208
View File
@@ -0,0 +1,208 @@
import { measureTextWrap } from '@evenrealities/pretext';
import { describe, expect, it } from 'vitest';
import { BODY_BOX, HUD, STATUS_BOX, renderHud } from '../src/core/hud.ts';
import { paginate, utf8Bytes, type MeasureLines } from '../src/core/paginate.ts';
import { toPlainText } from '../src/core/plaintext.ts';
import { initialState, type AppState, type Phase } from '../src/core/reducer.ts';
/**
* Layout tests use Even's own measurement library (@evenrealities/pretext),
* which mirrors the firmware's LVGL line breaking. That makes these
* measured-against-the-vendor-model tests, not device tests.
*/
const measure: MeasureLines = (text, width) => measureTextWrap(text, width).lineCount;
const box = { width: BODY_BOX.innerWidth, maxLines: HUD.bodyLines, maxBytes: HUD.pageMaxBytes };
const squash = (s: string) => s.replace(/\s+/g, '');
function expectValidPages(source: string, pages: string[]) {
for (const page of pages) {
expect(measure(page, box.width)).toBeLessThanOrEqual(box.maxLines);
expect(utf8Bytes(page)).toBeLessThanOrEqual(box.maxBytes);
expect(page.length).toBeGreaterThan(0);
}
// Nothing dropped, nothing duplicated, order preserved (whitespace at page breaks aside).
expect(squash(pages.join(' '))).toBe(squash(source));
}
describe('geometry', () => {
it('the two containers tile the 576x288 canvas exactly', () => {
expect(BODY_BOX.height + STATUS_BOX.height).toBe(HUD.height);
expect(STATUS_BOX.y).toBe(BODY_BOX.height);
expect(BODY_BOX.height - 2 * HUD.padding).toBe(HUD.bodyLines * HUD.lineHeight);
expect(STATUS_BOX.height - 2 * HUD.padding).toBeGreaterThanOrEqual(HUD.lineHeight);
});
});
describe('paginate', () => {
it('keeps a short answer on one page', () => {
expect(paginate('Paris.', box, measure)).toEqual(['Paris.']);
expect(paginate(' ', box, measure)).toEqual(['']);
});
it('splits a long answer into pages that each fit, losing nothing', () => {
const sentence = 'The quick brown fox jumps over the lazy dog near the riverbank at dawn. ';
const source = Array.from({ length: 80 }, (_, i) => `${i + 1}. ${sentence}`).join('').trim();
const pages = paginate(source, box, measure);
expect(pages.length).toBeGreaterThan(5);
expectValidPages(source, pages);
});
it('preserves line breaks inside a page', () => {
const source = 'First line\nSecond line\n\nNew paragraph';
expect(paginate(source, box, measure)).toEqual([source]);
});
it('handles many short lines (lists) by line count, not characters', () => {
const source = Array.from({ length: 40 }, (_, i) => `• item ${i + 1}`).join('\n');
const pages = paginate(source, box, measure);
expect(pages).toHaveLength(Math.ceil(40 / HUD.bodyLines));
expectValidPages(source, pages);
});
it('splits an unbroken run longer than a page without cutting a character in half', () => {
const url = 'https://example.com/' + 'a'.repeat(1500);
const pages = paginate(`See ${url} now`, box, measure);
expectValidPages(`See ${url} now`, pages);
});
it('keeps multi-byte text intact and within the byte budget', () => {
const cjk = '東京は日本の首都であり、世界でも有数の大都市です。'.repeat(40);
const accents = 'Voilà: café, naïve, façade, São Paulo, Zürich, Kraków, Ελληνικά, кириллица. '.repeat(30);
for (const source of [cjk, accents]) {
const pages = paginate(source, box, measure);
expect(pages.length).toBeGreaterThan(1);
expectValidPages(source, pages);
// Every page is still well-formed UTF-16 (no lone surrogates).
for (const page of pages) expect(page.isWellFormed()).toBe(true);
}
});
it('never splits a surrogate pair or a ZWJ sequence', () => {
const family = '👨‍👩‍👧‍👦';
const source = family.repeat(300);
const pages = paginate(source, box, measure);
expectValidPages(source, pages);
for (const page of pages) {
expect(page.isWellFormed()).toBe(true);
expect(page.length % family.length).toBe(0);
}
});
it('respects a byte budget tighter than the line budget', () => {
const source = 'é'.repeat(4000); // 2 bytes each
const pages = paginate(source, { ...box, maxLines: 1000 }, measure);
for (const page of pages) expect(utf8Bytes(page)).toBeLessThanOrEqual(box.maxBytes);
expect(pages.join('')).toBe(source);
});
it('a 20,000-character answer paginates quickly', () => {
const source = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. '.repeat(360);
const started = performance.now();
const pages = paginate(source, box, measure);
const elapsed = performance.now() - started;
expectValidPages(source, pages);
expect(elapsed).toBeLessThan(3000);
});
});
describe('plain text', () => {
it('removes Markdown markup but keeps every word', () => {
const md = [
'# Answer',
'',
'The **capital** of *France* is `Paris`. See [the docs](https://example.com/x) or [the anchor](#a).',
'',
'- one',
'* two',
'1. three',
'',
'> quoted',
'',
'```js',
'const a = b * c * d;',
'```',
'',
'| City | Country |',
'|------|---------|',
'| Paris | France |',
'',
'---',
'<b>bold</b> &amp; <br/>done',
].join('\n');
const out = toPlainText(md);
expect(out).not.toMatch(/[`#>]|\*\*|\]\(|<b>|\|/);
for (const word of ['Answer', 'capital', 'France', 'Paris', 'the docs (https://example.com/x)', 'or the anchor.', '• one', '• two', '1. three', 'quoted', 'const a = b * c * d;', 'City · Country', 'Paris · France', 'bold &\ndone']) {
expect(out).toContain(word);
}
});
it('leaves ordinary punctuation, maths and identifiers alone', () => {
for (const text of ['2 * 3 * 4 = 24', 'snake_case_name and another_one', 'a < b and b > c', 'Price: $5 * 2', 'Use the -v flag']) {
expect(toPlainText(text)).toBe(text);
}
});
it('preserves Unicode and normalises line endings', () => {
expect(toPlainText('Zürich — 東京 – naïve\r\nline two\r\n\r\n\r\n\r\nline three')).toBe('Zürich — 東京 – naïve\nline two\n\nline three');
// Decomposed input is composed, so the firmware sees one code point per accented letter.
expect(toPlainText('é')).toBe('é');
});
});
describe('HUD frames', () => {
const phases: Phase[] = ['unpaired', 'ready', 'listening', 'transcribing', 'thinking', 'approval', 'answer', 'error', 'disconnected', 'cancelled'];
const variants = (phase: Phase): AppState[] => {
const base: AppState = { ...initialState, phase, captureStartedAt: 0, captureMaxSeconds: 120 };
if (phase === 'answer') {
return [
{ ...base, pages: ['x'], pageIndex: 0 },
{ ...base, pages: Array(99).fill('x'), pageIndex: 98, partial: true },
];
}
if (phase === 'disconnected') {
return [
{ ...base, disconnectedFrom: 'glasses' },
{ ...base, disconnectedFrom: 'bridge', canResend: true },
{ ...base, disconnectedFrom: 'bridge', canResend: false },
];
}
if (phase === 'error') {
return [
{ ...base, error: { code: 'outcome_unknown', hud: 'The outcome is unknown. Check the agent before asking again.', retryable: false } },
{ ...base, error: { code: 'agent_timeout', hud: 'The agent ran out of time and was stopped. Actions it had already taken are not undone.', retryable: true } },
];
}
if (phase === 'ready') return [base, { ...base, notice: 'New conversation' }];
return [base];
};
it('every status line fits on one HUD line and every body fits without scrolling', () => {
for (const phase of phases) {
for (const state of variants(phase)) {
const frame = renderHud(state, 119_000);
expect(measure(frame.status, STATUS_BOX.width - 2 * HUD.padding), `status of ${phase}: ${frame.status}`).toBe(1);
expect(measure(frame.body, BODY_BOX.innerWidth), `body of ${phase}`).toBeLessThanOrEqual(HUD.bodyLines);
expect(utf8Bytes(frame.body)).toBeLessThanOrEqual(999);
expect(frame.status.length).toBeGreaterThan(0);
}
}
});
it('the recording indicator and elapsed time are visible for the whole capture', () => {
const state: AppState = { ...initialState, phase: 'listening', captureStartedAt: 10_000, captureMaxSeconds: 30 };
expect(renderHud(state, 10_000).status).toContain('● REC 0:00 / 0:30');
expect(renderHud(state, 17_400).status).toContain('● REC 0:07 / 0:30');
expect(renderHud(state, 17_400).body).toContain('30 seconds');
for (const phase of phases.filter((p) => p !== 'listening')) {
expect(renderHud({ ...initialState, phase }, 0).status).not.toContain('REC');
}
});
it('errors offer a recovery action and send detail to the phone', () => {
const frame = renderHud({ ...initialState, phase: 'error', error: { code: 'stt_empty', hud: 'No speech was recognised.', retryable: true } }, 0);
expect(frame.body).toContain('No speech was recognised.');
expect(frame.body).toContain('phone');
expect(frame.status).toContain('Tap');
});
});
+332
View File
@@ -0,0 +1,332 @@
import { describe, expect, it } from 'vitest';
import { SCHEMA_VERSION, type TurnResult } from '@hermeven/contracts';
import { initialState, reduce, type AppEvent, type AppState, type Effect } from '../src/core/reducer.ts';
const ID1 = '11111111-1111-4111-8111-111111111111';
const ID2 = '22222222-2222-4222-8222-222222222222';
const CONV = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
function run(state: AppState, ...events: AppEvent[]): { state: AppState; effects: Effect[] } {
let effects: Effect[] = [];
for (const event of events) {
const step = reduce(state, event);
state = step.state;
effects = step.effects;
}
return { state, effects };
}
const ready = () =>
run(initialState, { type: 'init', paired: true, conversationId: CONV, captureMaxSeconds: 30, resumeRequestId: null }).state;
function result(requestId: string, over: Partial<TurnResult> = {}): TurnResult {
return {
schema_version: SCHEMA_VERSION,
request_id: requestId,
conversation_id: CONV,
state: 'done',
terminal: true,
outcome: 'succeeded',
cancel_requested: false,
input_text: 'q',
answer_text: 'a',
error: null,
replayed: false,
created_at: '2026-01-01T00:00:00.000Z',
updated_at: '2026-01-01T00:00:01.000Z',
timings: { transcribe_ms: 1, agent_ms: 2 },
...over,
};
}
describe('happy path', () => {
it('READY -> LISTENING -> TRANSCRIBING -> THINKING -> ANSWER', () => {
let s = ready();
expect(s.phase).toBe('ready');
let step = reduce(s, { type: 'activate', freshId: ID1 });
s = step.state;
expect(s.phase).toBe('listening');
expect(step.effects).toEqual([{ type: 'start_capture', generation: s.generation }]);
s = reduce(s, { type: 'capture_started', generation: s.generation, at: 1000 }).state;
expect(s.captureStartedAt).toBe(1000);
step = reduce(s, { type: 'activate', freshId: ID2 });
s = step.state;
expect(s.phase).toBe('transcribing');
// The request id chosen at activation is the one submitted: the stop tap's id is unused.
expect(step.effects).toEqual([{ type: 'stop_capture_and_submit', generation: s.generation, requestId: ID1 }]);
s = reduce(s, {
type: 'turn_update',
generation: s.generation,
result: result(ID1, { state: 'thinking', terminal: false, outcome: null, answer_text: null }),
pages: null,
}).state;
expect(s.phase).toBe('thinking');
s = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['p1', 'p2', 'p3'] }).state;
expect(s.phase).toBe('answer');
expect(s.pages).toEqual(['p1', 'p2', 'p3']);
expect(s.pageIndex).toBe(0);
});
it('a tap on the answer starts a follow-up in the same conversation', () => {
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
s = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['p'] }).state;
const step = reduce(s, { type: 'activate', freshId: ID2 });
expect(step.state.phase).toBe('listening');
expect(step.state.conversationId).toBe(CONV);
expect(step.state.requestId).toBe(ID2);
expect(step.state.pages).toEqual([]);
});
it('the capture cap stops and submits exactly once', () => {
let s = run(ready(), { type: 'activate', freshId: ID1 }).state;
const step = reduce(s, { type: 'capture_limit', generation: s.generation });
expect(step.state.phase).toBe('transcribing');
expect(step.effects).toHaveLength(1);
s = step.state;
expect(reduce(s, { type: 'capture_limit', generation: s.generation }).effects).toEqual([]);
});
});
describe('paging', () => {
it('moves within bounds and only in ANSWER', () => {
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
expect(reduce(s, { type: 'next_page' }).state).toBe(s);
s = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['a', 'b', 'c'] }).state;
s = run(s, { type: 'next_page' }, { type: 'next_page' }, { type: 'next_page' }).state;
expect(s.pageIndex).toBe(2);
s = run(s, { type: 'prev_page' }, { type: 'prev_page' }, { type: 'prev_page' }, { type: 'prev_page' }).state;
expect(s.pageIndex).toBe(0);
});
});
describe('cancellation and stale results', () => {
it('double-tap while listening discards the capture and never submits', () => {
const s = run(ready(), { type: 'activate', freshId: ID1 }).state;
const step = reduce(s, { type: 'back' });
expect(step.state.phase).toBe('cancelled');
expect(step.effects).toEqual([{ type: 'discard_capture' }]);
expect(step.state.generation).toBe(s.generation + 1);
});
it('cancel while thinking asks the bridge to cancel, and a late answer cannot resurrect the UI', () => {
const s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
const step = reduce(s, { type: 'back' });
expect(step.state.phase).toBe('cancelled');
expect(step.effects).toContainEqual({ type: 'cancel_turn', requestId: ID1 });
const late = reduce(step.state, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['LATE'] });
expect(late.state).toBe(step.state);
expect(late.state.pages).toEqual([]);
});
it('a late result for an older request cannot replace a newer answer', () => {
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'first' }).state;
const gen1 = s.generation;
s = reduce(s, { type: 'back' }).state; // cancelled
s = reduce(s, { type: 'submit_text', freshId: ID2, text: 'second' }).state;
s = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID2), pages: ['NEW'] }).state;
expect(s.pages).toEqual(['NEW']);
// Old generation.
expect(reduce(s, { type: 'turn_update', generation: gen1, result: result(ID1), pages: ['OLD'] }).state).toBe(s);
// Right generation, wrong request id.
expect(reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['OLD'] }).state).toBe(s);
});
it('a late result for a cancelled request is ignored while a newer request is still in flight', () => {
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'first' }).state;
const gen1 = s.generation;
s = reduce(s, { type: 'back' }).state;
s = reduce(s, { type: 'submit_text', freshId: ID2, text: 'second' }).state;
expect(s.phase).toBe('thinking');
// The old turn finishes late, under its old generation.
expect(reduce(s, { type: 'turn_update', generation: gen1, result: result(ID1), pages: ['OLD'] }).state).toBe(s);
// Even mislabelled with the current generation, the request id does not match.
expect(reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['OLD'] }).state).toBe(s);
// And an old-generation event cannot smuggle in the current request id either.
expect(reduce(s, { type: 'turn_update', generation: gen1, result: result(ID2), pages: ['OLD'] }).state).toBe(s);
});
it('stale capture and network events are ignored', () => {
let s = run(ready(), { type: 'activate', freshId: ID1 }).state;
const gen = s.generation;
s = reduce(s, { type: 'back' }).state;
for (const event of [
{ type: 'capture_started', generation: gen, at: 5 },
{ type: 'capture_failed', generation: gen, reason: 'mic_refused' },
{ type: 'capture_limit', generation: gen },
{ type: 'network_lost', generation: gen, stage: 'submit' },
{ type: 'turn_rejected', generation: gen, error: { code: 'x', hud: 'x', retryable: false } },
] as AppEvent[]) {
expect(reduce(s, event).state).toBe(s);
}
});
it('a second cancel is a no-op', () => {
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }, { type: 'cancel' }).state;
const again = reduce(s, { type: 'cancel' });
expect(again.state).toBe(s);
expect(again.effects).toEqual([]);
s = again.state;
expect(s.phase).toBe('cancelled');
});
it('back from ANSWER, ERROR and CANCELLED returns to READY; back from READY asks the OS to exit', () => {
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
s = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['p'] }).state;
s = reduce(s, { type: 'back' }).state;
expect(s.phase).toBe('ready');
expect(reduce(s, { type: 'back' }).effects).toEqual([{ type: 'exit_dialog' }]);
expect(reduce(initialState, { type: 'back' }).effects).toEqual([{ type: 'exit_dialog' }]);
});
});
describe('outcomes', () => {
const thinking = () => run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
it('incomplete answers are shown and flagged as partial', () => {
const s = thinking();
const next = reduce(s, {
type: 'turn_update',
generation: s.generation,
result: result(ID1, { outcome: 'incomplete', error: { code: 'agent_incomplete', message: 'partial', retryable: false } }),
pages: ['half'],
}).state;
expect(next.phase).toBe('answer');
expect(next.partial).toBe(true);
});
it('failed and unknown become ERROR with the stable code; unknown is not retryable', () => {
const s = thinking();
const unknown = reduce(s, {
type: 'turn_update',
generation: s.generation,
result: result(ID1, { outcome: 'unknown', answer_text: null, error: { code: 'outcome_unknown', message: 'Unknown.', retryable: false } }),
pages: null,
}).state;
expect(unknown.phase).toBe('error');
expect(unknown.error).toEqual({ code: 'outcome_unknown', hud: 'Unknown.', retryable: false });
});
it('approval-required is its own phase and can still be cancelled', () => {
let s = thinking();
s = reduce(s, {
type: 'turn_update',
generation: s.generation,
result: result(ID1, { state: 'approval_required', terminal: false, outcome: null, answer_text: null }),
pages: null,
}).state;
expect(s.phase).toBe('approval');
const step = reduce(s, { type: 'back' });
expect(step.state.phase).toBe('cancelled');
expect(step.effects).toContainEqual({ type: 'cancel_turn', requestId: ID1 });
});
it('a stopped-by-deadline turn is an error, a user cancel confirmed by the bridge is CANCELLED', () => {
const s = thinking();
const timeout = reduce(s, {
type: 'turn_update',
generation: s.generation,
result: result(ID1, { outcome: 'cancelled', answer_text: null, error: { code: 'agent_timeout', message: 'Stopped.', retryable: false } }),
pages: null,
}).state;
expect(timeout.phase).toBe('error');
const plain = reduce(s, {
type: 'turn_update',
generation: s.generation,
result: result(ID1, { outcome: 'cancelled', answer_text: null }),
pages: null,
}).state;
expect(plain.phase).toBe('cancelled');
});
});
describe('connection loss', () => {
it('submit never delivered: DISCONNECTED with a safe resend of the same request id', () => {
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
s = reduce(s, { type: 'network_lost', generation: s.generation, stage: 'submit' }).state;
expect(s.phase).toBe('disconnected');
expect(s.canResend).toBe(true);
const step = reduce(s, { type: 'activate', freshId: ID2 });
expect(step.effects).toEqual([{ type: 'resubmit', generation: s.generation, requestId: ID1 }]);
expect(step.state.requestId).toBe(ID1);
});
it('lost while waiting: no resend is offered, and the answer is still accepted when it arrives', () => {
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
s = reduce(s, { type: 'network_lost', generation: s.generation, stage: 'poll' }).state;
expect(s.canResend).toBe(false);
expect(reduce(s, { type: 'activate', freshId: ID2 }).effects).toEqual([]);
const restored = reduce(s, { type: 'network_restored', generation: s.generation }).state;
expect(restored.phase).toBe('thinking');
const answered = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['p'] }).state;
expect(answered.phase).toBe('answer');
});
it('glasses disconnect while listening stops capture; reconnect never reopens the microphone', () => {
let s = run(ready(), { type: 'activate', freshId: ID1 }).state;
const step = reduce(s, { type: 'glasses_status', connected: false });
expect(step.effects).toEqual([{ type: 'discard_capture' }]);
expect(step.state.phase).toBe('disconnected');
s = step.state;
const back = reduce(s, { type: 'glasses_status', connected: true });
expect(back.state.phase).toBe('ready');
expect(back.effects).toEqual([]);
});
it('glasses disconnect during a running turn keeps the turn', () => {
const s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
expect(reduce(s, { type: 'glasses_status', connected: false }).state).toBe(s);
});
it('app exit while listening stops capture', () => {
const s = run(ready(), { type: 'activate', freshId: ID1 }).state;
const step = reduce(s, { type: 'app_exit' });
expect(step.effects).toEqual([{ type: 'discard_capture' }]);
expect(step.state.phase).toBe('ready');
});
});
describe('pairing, restore and conversations', () => {
it('unpaired ignores taps', () => {
const step = reduce(initialState, { type: 'activate', freshId: ID1 });
expect(step.state.phase).toBe('unpaired');
expect(step.effects).toEqual([]);
});
it('restoring an in-flight turn polls it and neither resubmits nor records', () => {
const step = reduce(initialState, {
type: 'init',
paired: true,
conversationId: CONV,
captureMaxSeconds: 20,
resumeRequestId: ID1,
});
expect(step.state.phase).toBe('thinking');
expect(step.effects).toEqual([{ type: 'poll', generation: step.state.generation, requestId: ID1 }]);
});
it('new conversation is refused mid-turn and resets cleanly at rest', () => {
const busy = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
expect(reduce(busy, { type: 'new_conversation' }).state).toBe(busy);
const s = ready();
const step = reduce(s, { type: 'new_conversation' });
expect(step.state.conversationId).toBeNull();
expect(step.effects).toEqual([{ type: 'create_conversation', generation: step.state.generation }]);
const stale = reduce(step.state, { type: 'conversation_created', generation: s.generation, conversationId: 'old' });
expect(stale.state.conversationId).toBeNull();
const fresh = reduce(step.state, { type: 'conversation_created', generation: step.state.generation, conversationId: 'new' });
expect(fresh.state.conversationId).toBe('new');
});
it('unpairing while listening closes the microphone', () => {
const s = run(ready(), { type: 'activate', freshId: ID1 }).state;
const step = reduce(s, { type: 'unpaired' });
expect(step.state.phase).toBe('unpaired');
expect(step.effects).toEqual([{ type: 'discard_capture' }]);
});
});
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": { "lib": ["ES2024", "DOM", "DOM.Iterable"], "types": ["vite/client"] },
"include": ["src", "test"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'vite';
// `host: true` so a phone on the same network can load the dev server (QR sideload).
// `esnext` because the entry point uses top-level await, as the official templates do.
export default defineConfig({
server: { host: true, port: 5173 },
build: { target: 'esnext' },
});