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' }],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user