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:
@@ -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';
|
||||
}
|
||||
@@ -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',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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 : [''];
|
||||
}
|
||||
@@ -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(/ /g, ' ')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/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();
|
||||
}
|
||||
@@ -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' }],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 */
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 : ''}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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>;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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');
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user