Files
hermeven/apps/even-client/src/core/controller.ts
T
DanandClaude Fable 5.2 bb3a309427 CODY-021: a removed agent is reconciled the moment its turn settles
If the current agent was taken off the bridge's list while its request was
in flight, start-up rightly kept it for that request, but nothing fell back
afterwards: the screen named the default (first in the list) while state,
storage and the conversation were still the removed agent's.

The controller now reconciles inside dispatch, in the same step as any
state change and before anything is drawn: on a resting screen, if the
stored agent is not offered, the stored agent and thread are swapped to the
default's own and the state follows (agent_reconciled). While a request is
in flight nothing changes, so the turn is never moved or repeated. This
also covers an abandoned turn at start.

CODY-022: README scope list no longer says multiple agents are excluded.

Not reviewed, not deployed, not uploaded.

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

1180 lines
50 KiB
TypeScript

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 { currentAgent, initialState, reduce, type Agent, 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;
/**
* The request id of a turn that may exist on the bridge. Written BEFORE the first submit and
* cleared only on a definitive answer: a terminal result, a definite rejection, or the bridge
* confirming it has no such turn. After a restart it is re-attached by polling.
*/
activeRequestId: string | null;
/** The user abandoned that turn but the bridge has not yet acknowledged the cancel. */
activeCancelled: boolean;
/** When the last turn in `conversationId` finished (ms since epoch), if known. */
lastTurnAt?: number;
/**
* The agent `conversationId` and `lastTurnAt` belong to: the one questions go to. Absent =
* the default agent.
*/
agentId?: string;
/** The same two values for every other agent that has been talked to, by agent id. */
others?: Record<string, AgentThread>;
/** The agent list as the bridge last gave it, used if the bridge cannot be asked at start. */
agents?: Agent[];
}
interface AgentThread {
conversationId: string | null;
lastTurnAt?: number;
}
const DEFAULT_AGENT = 'default';
/** Screens on which nothing is recording or in flight. */
const RESTING: ReadonlySet<AppState['phase']> = new Set(['ready', 'answer', 'error', 'cancelled']);
function validAgents(value: unknown): Agent[] | undefined {
if (!Array.isArray(value)) return undefined;
const agents = value.filter(
(a): a is Agent => !!a && typeof (a as Agent).id === 'string' && typeof (a as Agent).name === 'string' && (a as Agent).name.length <= 24,
);
return agents.length === value.length && agents.length <= 16 ? agents.map(({ id, name }) => ({ id, name })) : undefined;
}
function validThreads(value: unknown): Record<string, AgentThread> | undefined {
if (!value || typeof value !== 'object') return undefined;
const out: Record<string, AgentThread> = {};
for (const [id, thread] of Object.entries(value as Record<string, Partial<AgentThread>>)) {
if (!thread || typeof thread !== 'object') continue;
out[id] = {
conversationId: typeof thread.conversationId === 'string' ? thread.conversationId : null,
lastTurnAt: typeof thread.lastTurnAt === 'number' ? thread.lastTurnAt : undefined,
};
}
return out;
}
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;
/** How this session was opened, when the device says. */
launchSource: string;
/** What the glasses runtime has delivered, by type only (empty when the device cannot say). */
glassesInput: string;
/** Last settled turn, complete and untruncated, for the phone. */
lastTurn: TurnResult | null;
log: DiagEntry[];
}
export interface IdleExitMs {
/** An answer is on screen and has not been touched. Paging or any gesture restarts it. */
answer: number | null;
/** Ready and waiting for a question. */
ready: number | null;
/** An error or "Cancelled" message is on screen. */
message: number | null;
}
export const DEFAULT_IDLE_EXIT_MS: IdleExitMs = { answer: 20_000, ready: 30_000, message: 10_000 };
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;
/** Override the poll schedule with one fixed interval (tests). */
pollIntervalMs?: number;
submitAttempts?: number;
submitRetryMs?: number;
/** No audio frames for this long while recording means the microphone is gone. */
micStallMs?: number;
/** A long press held at least this long, then released, sends what was recorded (push-to-talk). */
holdToTalkMs?: number;
/**
* Leave the glasses after this long with nothing happening, per resting screen. `null`
* disables it for that screen; `idleExit: null` disables it altogether.
*/
idleExit?: Partial<IdleExitMs> | null;
/** After a phone-page interaction, do not leave by ourselves for this long. */
phoneGraceMs?: number;
/** A question asked after this long a silence starts a new conversation. */
conversationGapMs?: number;
/** If the host does not confirm the exit, try again after this long... */
exitRetryMs?: number;
/** ...up to this many attempts in a row. Any activity starts the count again. */
exitAttempts?: 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;
/** The request id last CONFIRMED stored by the host (`undefined` = not known). */
private confirmedActive: string | null | undefined = undefined;
/** App storage could not be read at start: nothing is assumed about what it holds. */
private storageFault = false;
private creating: { epoch: number; promise: Promise<string> } | null = null;
private createChain: Promise<void> = Promise.resolve();
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 | null;
private readonly submitAttempts: number;
private readonly submitRetryMs: number;
private readonly micStallMs: number;
private readonly holdToTalkMs: number;
private readonly idleExitMs: IdleExitMs | null;
private readonly phoneGraceMs: number;
private readonly conversationGapMs: number;
private idleTimer: ReturnType<typeof setTimeout> | null = null;
// Idle exit applies however the session was opened. It used to wait for a `glassesMenu`
// launch source or a first gesture; on a real G2 (2026-11-21, build 0.1.1) a voice launch
// delivered no such signal and the app stayed until the glasses were touched. Setting up on
// the phone is still protected: nothing leaves while unpaired, and a touch on the phone page
// holds the app open for the grace period.
private phoneBusyUntil = 0;
private launchSource: 'appMenu' | 'glassesMenu' | 'unknown' = 'unknown';
private readonly exitRetryMs: number;
private readonly exitAttempts: number;
/** The host confirmed we left. Final. */
private exited = false;
/** An exit attempt is in progress: no second one starts until it has answered. */
private leaving = false;
/** Unconfirmed exit attempts since the last activity. */
private exitFailures = 0;
/**
* Counts every restart of the normal countdown: a gesture, a state change, a touch on the
* phone page. Reducer generation is not enough, because a gesture can change no state (a
* swipe at Ready). An exit attempt that started before the latest activity must not schedule
* its short retry over the countdown that activity restarted.
*/
private activityEpoch = 0;
/** Set while a long press that STARTED a recording is still held down. */
private heldPress: { generation: number; at: number } | null = null;
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 ?? null;
this.submitAttempts = options.submitAttempts ?? 4;
this.submitRetryMs = options.submitRetryMs ?? 1500;
this.micStallMs = options.micStallMs ?? 3000;
this.holdToTalkMs = options.holdToTalkMs ?? 700;
this.idleExitMs = options.idleExit === null ? null : { ...DEFAULT_IDLE_EXIT_MS, ...options.idleExit };
this.phoneGraceMs = options.phoneGraceMs ?? 120_000;
this.conversationGapMs = options.conversationGapMs ?? 10 * 60_000;
this.exitRetryMs = options.exitRetryMs ?? 3_000;
this.exitAttempts = Math.max(1, options.exitAttempts ?? 4);
}
// ------------------------------------------------------------------ public
async start(): Promise<void> {
const loaded = await this.load();
this.storageFault = loaded === 'unreadable';
this.stored = loaded === 'unreadable' ? null : loaded;
if (this.stored) this.confirmedActive = this.stored.activeCancelled ? undefined : this.stored.activeRequestId;
// Pepper now leaves the glasses between questions, so "the same conversation" cannot mean
// "until the app closes". A question after a long silence starts a new conversation; one
// soon after the last answer continues it.
if (
this.stored?.conversationId &&
!this.stored.activeRequestId &&
this.stored.lastTurnAt !== undefined &&
this.now() - this.stored.lastTurnAt > this.conversationGapMs
) {
this.note('conversation', 'last question was a while ago: the next one starts a new conversation');
this.stored = { ...this.stored, conversationId: null };
}
if (this.storageFault) this.note('storage', 'app storage could not be read; saved pairing state is unknown');
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)),
// Refresh the phone's Diagnostics when the glasses deliver something, even if it changes
// no state (an ignored or unrecognised event is exactly what needs to be visible).
this.device.onInputActivity?.(() => this.emit()) ?? (() => undefined),
this.device.onLaunchSource?.((source) => {
this.launchSource = source;
this.note('lifecycle', `opened from ${source}`);
// Shown in Diagnostics only. It does not decide anything: see the note on idle exit.
this.emit();
}) ?? (() => undefined),
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)}`);
}
}
}
const agents = this.stored ? await this.loadAgents() : [];
if (this.stored) this.settleStartingAgent(agents);
// A turn the user had abandoned is not shown again; its cancel is simply delivered now.
const abandoned = this.stored?.activeCancelled ? this.stored.activeRequestId : null;
this.dispatch({
type: 'init',
paired: this.stored !== null,
conversationId: this.stored?.conversationId ?? null,
captureMaxSeconds,
resumeRequestId: abandoned ? null : (this.stored?.activeRequestId ?? null),
storageFault: this.storageFault,
agents,
agentId: this.stored?.agentId ?? null,
});
if (abandoned) void this.cancelTurn(abandoned);
}
// ------------------------------------------------------------------ agents
/**
* The agents the bridge offers. A single agent, or a bridge from before agent selection
* (`not_found`), gives an empty list: nothing about agents is then shown or sent. If the
* bridge cannot be asked right now, the list it gave last time is used.
*/
private async loadAgents(): Promise<Agent[]> {
if (!this.client || !this.stored) return [];
let agents: Agent[];
try {
const listed = (await this.client.agents()).agents;
agents = listed.length > 1 ? listed.map(({ id, name }) => ({ id, name })) : [];
} catch (err) {
if (err instanceof BridgeApiError && err.body.code === 'not_found') agents = [];
else {
this.note('agents', `agent list not available: ${describe(err)}`);
return this.stored?.agents ?? [];
}
}
if (this.stored && JSON.stringify(this.stored.agents ?? []) !== JSON.stringify(agents)) {
this.stored = { ...this.stored, agents };
void this.save();
}
return agents;
}
/** Make `agentId` the stored current agent, swapping in its own conversation. No I/O. */
private swapStoredAgent(agentId: string): void {
if (!this.stored) return;
const from = this.stored.agentId ?? DEFAULT_AGENT;
if (from === agentId) return;
const others = { ...(this.stored.others ?? {}) };
others[from] = { conversationId: this.stored.conversationId, lastTurnAt: this.stored.lastTurnAt };
let thread: AgentThread = others[agentId] ?? { conversationId: null };
delete others[agentId];
// The same rule as at start: after a long silence with that agent, the next question to it
// starts a new conversation.
if (thread.conversationId && thread.lastTurnAt !== undefined && this.now() - thread.lastTurnAt > this.conversationGapMs) {
thread = { conversationId: null, lastTurnAt: thread.lastTurnAt };
}
this.stored = { ...this.stored, agentId, conversationId: thread.conversationId, lastTurnAt: thread.lastTurnAt, others };
}
/**
* Which agent the app opens on. It reopens on the agent last talked to only while that
* conversation is still current (the same window that decides whether a conversation
* continues); otherwise, or if that agent is no longer offered, it opens on the default.
* A turn still in flight keeps its agent.
*/
private settleStartingAgent(agents: Agent[]): void {
if (!this.stored) return;
const current = this.stored.agentId ?? DEFAULT_AGENT;
if (current === DEFAULT_AGENT) return;
if (this.stored.activeRequestId) return;
const offered = agents.some((a) => a.id === current);
const recent = this.stored.lastTurnAt !== undefined && this.now() - this.stored.lastTurnAt <= this.conversationGapMs;
if (offered && recent) return;
this.note('agents', offered ? 'last agent was a while ago: opening on the default' : 'last agent is no longer offered: opening on the default');
this.swapStoredAgent(DEFAULT_AGENT);
void this.save();
}
/**
* The current agent has been taken off the bridge's list. While its request is still in
* flight it stays the current agent, so that turn is followed to its end and never moved or
* repeated elsewhere. The moment nothing is in flight, the stored agent, its conversation and
* the state all fall back to the default together; otherwise the screen would name the
* default while the next question was still filed under the removed agent's conversation.
*/
private reconcileRemovedAgent(): void {
if (!this.stored) return;
const current = this.stored.agentId ?? DEFAULT_AGENT;
if (current === DEFAULT_AGENT) return;
if (!RESTING.has(this.state.phase)) return;
if (this.state.agents.some((a) => a.id === current)) return;
this.swapStoredAgent(DEFAULT_AGENT);
void this.save();
this.note('agents', `${current} is no longer offered: back to the default agent`);
this.state = reduce(this.state, { type: 'agent_reconciled', agentId: DEFAULT_AGENT, conversationId: this.stored.conversationId }).state;
}
/** A swipe at Ready: move to the next or previous agent. Does nothing unless there is a choice. */
private cycleAgent(delta: 1 | -1): void {
const agents = this.state.agents;
if (this.state.phase !== 'ready' || agents.length < 2 || !this.stored) return;
const index = agents.findIndex((a) => a.id === currentAgent(this.state)?.id);
const next = agents[(Math.max(0, index) + delta + agents.length) % agents.length]!;
this.swapStoredAgent(next.id);
void this.save();
this.note('agents', `now talking to ${next.id}`);
this.dispatch({ type: 'agent_selected', agentId: next.id, conversationId: this.stored.conversationId });
}
/** 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();
if (this.idleTimer) clearTimeout(this.idleTimer);
this.idleTimer = null;
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,
launchSource: this.launchSource,
glassesInput: this.device.inputSummary?.() ?? '',
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> {
if (this.storageFault) {
// Pairing now would overwrite storage we could not read, which may hold a running turn.
throw new Error('Saved settings could not be read. Close Hermeven and open it again before pairing.');
}
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,
activeCancelled: false,
};
if (!(await this.save())) {
// A pairing that exists only in memory would vanish on the next start and leave a live
// credential behind on the bridge. Undo it instead.
this.stored = null;
this.client = null;
await client.revoke().catch(() => undefined);
throw new Error('The phone could not save the pairing, so it was not kept. Get a new pairing code and try again.');
}
this.confirmedActive = null;
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)}`);
}
const agents = await this.loadAgents();
this.dispatch({ type: 'init', paired: true, conversationId: null, captureMaxSeconds, resumeRequestId: null, agents, agentId: 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;
let credential;
try {
credential = await this.client.renew();
} catch (err) {
if (err instanceof BridgeApiError) await this.afterAuthFailure(err);
throw err;
}
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)}`);
if (err instanceof BridgeApiError) await this.afterAuthFailure(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;
// In the same step, before anything is drawn or another question can start.
this.reconcileRemovedAgent();
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();
this.scheduleIdleExit();
}
/** The phone page is being used (touch or key): do not leave under the user's fingers. */
notePhoneActivity(): void {
this.phoneBusyUntil = this.now() + this.phoneGraceMs;
this.scheduleIdleExit();
}
/**
* (Re)start the countdown to leaving the glasses. Called after every state change and every
* gesture, so any activity restarts it. It only runs on a resting screen: never while
* recording, transcribing, waiting for the agent or for an approval, or while disconnected
* with a request outstanding.
*/
private scheduleIdleExit(retry = false): void {
if (this.idleTimer) clearTimeout(this.idleTimer);
this.idleTimer = null;
// Anything other than our own retry is activity: the full wait and the attempt count restart.
if (!retry) {
this.exitFailures = 0;
this.activityEpoch += 1;
}
if (this.stopped || this.exited || !this.idleExitMs || !this.hudReady) return;
const phase = this.state.phase;
const wait =
phase === 'answer'
? this.idleExitMs.answer
: phase === 'ready'
? this.idleExitMs.ready
: phase === 'error' || phase === 'cancelled'
? this.idleExitMs.message
: null;
if (wait === null) return;
const delay = retry ? this.exitRetryMs : Math.max(wait, this.phoneBusyUntil - this.now() + wait);
const generation = this.state.generation;
this.idleTimer = setTimeout(() => {
this.idleTimer = null;
// Something happened in the meantime, or the screen is no longer a resting one.
if (this.stopped || this.exited || this.state.generation !== generation || this.state.phase !== phase) return;
if (this.now() < this.phoneBusyUntil) return this.scheduleIdleExit();
// An earlier attempt has not answered yet: look again shortly, never start a second.
if (this.leaving) return this.scheduleIdleExit(true);
void this.leaveGlasses(`idle on ${phase}`);
}, delay);
}
private async leaveGlasses(reason: string): Promise<void> {
if (this.exited || this.leaving) return;
this.leaving = true;
const epoch = this.activityEpoch;
this.note('lifecycle', `leaving the glasses: ${reason}`);
this.emit();
let confirmed = false;
try {
await this.closeMic();
confirmed = await this.device.exitNow();
} catch {
confirmed = false;
} finally {
this.leaving = false;
}
if (this.stopped) return;
if (confirmed) {
this.exited = true;
if (this.idleTimer) clearTimeout(this.idleTimer);
this.idleTimer = null;
this.note('lifecycle', 'left the glasses');
this.emit();
return;
}
// Not confirmed: refused, failed, or no answer in time. We are still on the glasses as far
// as we know, so this must not be final. If anything happened meanwhile (a gesture, even one
// that changed no state, or a touch on the phone page), that activity already restarted the
// full countdown or the phone grace period, and that timer stands: no short retry replaces
// it. Otherwise try again, a bounded number of times.
if (this.activityEpoch !== epoch) return;
this.exitFailures += 1;
if (this.exitFailures >= this.exitAttempts) {
this.note('lifecycle', `the host did not confirm leaving after ${this.exitFailures} attempts; staying until the next activity`);
this.emit();
return;
}
this.note('lifecycle', 'the host did not confirm leaving; will try again');
this.emit();
this.scheduleIdleExit(true);
}
// ----------------------------------------------------------------- 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.epoch);
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 || this.stale(generation)) {
// Cancelled while the microphone was opening. Stop unconditionally unless a newer
// capture now owns the microphone: a stop that turns out to be redundant is harmless.
if (!this.capture || this.capture === capture) {
this.capture = null;
this.micOpen = false;
this.stopTicker();
await this.device.stopMic();
}
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;
}
/**
* The current conversation id, creating one if there is none. At most one create is in
* flight per conversation epoch, and creates are sent strictly one after another, so the
* bridge and the app can never disagree about which conversation is the live one: the last
* create the app sent is the last one the bridge processed.
*/
private ensureConversation(): Promise<string> {
if (this.state.conversationId) return Promise.resolve(this.state.conversationId);
const epoch = this.state.conversationEpoch;
if (this.creating && this.creating.epoch === epoch) return this.creating.promise;
const client = this.client;
const promise = this.createChain.then(async () => {
if (!client || this.stopped || epoch !== this.state.conversationEpoch) throw new StaleConversationError();
// Named only when the bridge offered a choice; captured now, and the epoch check below
// drops the result if the user has moved to another agent meanwhile.
const created = await client.createConversation(this.state.agents.length ? (currentAgent(this.state)?.id ?? DEFAULT_AGENT) : undefined);
// Checked BEFORE anything is stored: a result for a conversation the user has since
// replaced (or for a pairing that has ended) is dropped, not persisted.
if (this.stopped || epoch !== this.state.conversationEpoch || this.client !== client) throw new StaleConversationError();
if (this.stored) {
this.stored = { ...this.stored, conversationId: created.conversation_id };
await this.save();
}
this.note('conversation', `conversation ${created.conversation_id}`);
this.dispatch({ type: 'conversation_created', epoch, conversationId: created.conversation_id });
return created.conversation_id;
});
this.createChain = promise.then(
() => undefined,
() => undefined,
);
const entry = { epoch, promise };
this.creating = entry;
void this.createChain.then(() => {
if (this.creating === entry) this.creating = null;
});
return promise;
}
private async submit(generation: number, requestId: string): Promise<void> {
const pending = this.pending;
if (!this.client || !pending || pending.requestId !== requestId) return;
// Remember the request id before anything is sent. From here until the bridge gives a
// definite answer, this request may or may not exist there; if the page dies in between,
// the next start re-attaches to it by id instead of forgetting a turn that is running.
//
// Nothing is sent until the phone has CONFIRMED storing the id. An unanswered or refused
// write stops here, with the request provably unsent and kept for a retry under the same id.
if (!(await this.setActiveRequest(requestId))) {
this.note('turn', `request ${requestId} held back: its id could not be stored`);
if (!this.stale(generation)) this.dispatch({ type: 'not_saved', generation });
return;
}
if (this.stale(generation)) return;
for (let attempt = 1; ; attempt++) {
if (this.stale(generation)) return;
try {
let conversationId: string;
try {
conversationId = await this.ensureConversation();
} catch (err) {
if (!(err instanceof StaleConversationError)) throw err;
// The conversation was replaced while it was being created; use the new one.
if (this.stale(generation)) return;
attempt -= 1;
continue;
}
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;
}
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) {
// A contract error is a definite "this turn was not created".
this.note('turn', `rejected: ${err.body.code}`);
this.pending = null;
await this.setActiveRequest(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) {
// Ambiguous: a request may have been admitted even though no reply came back. The
// request id stays stored; a retry or a restart reconciles under the same id.
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;
const started = this.now();
for (;;) {
const interval = this.pollIntervalMs ?? pollDelay(this.now() - started);
await sleep(failures ? Math.min(5000, Math.max(interval, 250) * 2 ** Math.min(failures, 3)) : interval);
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}`);
// not_found is the bridge confirming the turn does not exist: it was never admitted.
await this.setActiveRequest(null);
const error: HudError =
err.body.code === 'not_found'
? { code: 'not_delivered', hud: 'Your last request did not reach the bridge. Please ask again.', retryable: true }
: this.hudError(err);
this.dispatch({ type: 'turn_rejected', generation, error });
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;
if (this.stored) this.stored = { ...this.stored, lastTurnAt: this.now() };
void this.clearActiveRequest(result.request_id);
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> {
// Keep the id, marked as abandoned, until the bridge acknowledges the cancel. If the cancel
// cannot be delivered now it is retried on the next start, so an abandoned turn is not
// left running unnoticed and is never shown to the user again.
if (this.stored && this.stored.activeRequestId === requestId && !this.stored.activeCancelled) {
this.stored = { ...this.stored, activeCancelled: true };
await this.save();
}
const client = this.client;
if (!client) return;
for (let attempt = 1; attempt <= 3; attempt++) {
try {
const result = await client.cancelTurn(requestId);
this.note('turn', `cancel requested for ${requestId}; bridge state ${result.state}`);
await this.clearActiveRequest(requestId);
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}`);
await this.clearActiveRequest(requestId);
await this.afterAuthFailure(err);
return;
}
if (this.stopped) return;
await sleep(this.submitRetryMs);
}
}
this.note('turn', `cancel for ${requestId} could not be delivered yet; it will be retried`);
}
private async createConversation(epoch: number): Promise<void> {
if (!this.client || epoch !== this.state.conversationEpoch) return;
try {
await this.ensureConversation();
} catch (err) {
if (err instanceof StaleConversationError) return;
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', epoch, error });
if (err instanceof BridgeApiError) await this.afterAuthFailure(err);
}
}
// ------------------------------------------------------------------ device
private onDeviceEvent(event: DeviceEvent): void {
if (event.type !== 'audio') {
// Any gesture or lifecycle event from the glasses restarts the idle countdown, even when
// it changes no state (paging past the last page, for example).
this.scheduleIdleExit();
}
switch (event.type) {
case 'audio':
return this.onAudio(event.pcm);
case 'tap':
this.heldPress = null;
return this.dispatch({ type: 'activate', freshId: this.newId() });
case 'long_press': {
// First seen on a real G2 (2026-11-21): a touch held a little too long arrives as a
// long press, not a tap. It does what a tap does, so the user need not care which the
// glasses decided it was. If it started a recording, remember that the finger is down.
const wasListening = this.state.phase === 'listening';
this.dispatch({ type: 'activate', freshId: this.newId() });
this.heldPress =
!wasListening && this.state.phase === 'listening' ? { generation: this.state.generation, at: this.now() } : null;
return;
}
case 'long_press_release': {
// Push-to-talk: held while speaking, then released, sends. A press released quickly is
// treated like a tap and leaves the recording running until the next tap or press.
const held = this.heldPress;
this.heldPress = null;
if (!held || held.generation !== this.state.generation || this.state.phase !== 'listening') return;
if (this.now() - held.at < this.holdToTalkMs) return;
return this.dispatch({ type: 'activate', freshId: this.newId() });
}
case 'double_tap':
this.heldPress = null;
return this.dispatch({ type: 'back' });
case 'swipe_down':
// At Ready a swipe chooses the agent; on an answer it turns the page.
if (this.state.phase === 'ready' && this.state.agents.length > 1) return this.cycleAgent(1);
return this.dispatch({ type: 'next_page' });
case 'swipe_up':
if (this.state.phase === 'ready' && this.state.agents.length > 1) return this.cycleAgent(-1);
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':
// The glasses say we are gone (the user or the system closed the app). That is as final
// as our own confirmed exit: no idle exit, and no retry of one, is sent after it.
this.exited = true;
if (this.idleTimer) clearTimeout(this.idleTimer);
this.idleTimer = null;
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' && err.body.code !== 'credential_expired') return;
if (!this.stored) return;
// Revoked, unknown or expired: the stored credential can no longer do anything (an expired
// token cannot even renew itself), so it is forgotten and the pairing screen comes back.
this.note('auth', `credential no longer accepted: ${err.body.code}`);
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)}`);
}
}
}
/**
* Record which request may exist on the bridge. Resolves true only when the phone has
* positively confirmed storing it; a write that timed out or failed is retried on the next
* call rather than assumed.
*/
private async setActiveRequest(requestId: string | null): Promise<boolean> {
if (!this.stored) return false;
const unchanged = this.stored.activeRequestId === requestId && !this.stored.activeCancelled;
if (unchanged && this.confirmedActive === requestId) return true;
if (!unchanged) this.stored = { ...this.stored, activeRequestId: requestId, activeCancelled: false };
const ok = await this.save();
this.confirmedActive = ok ? requestId : undefined;
return ok;
}
/** Clear the stored request id only if it is still this one (a newer turn may own the slot). */
private async clearActiveRequest(requestId: string): Promise<void> {
if (this.stored?.activeRequestId === requestId) await this.setActiveRequest(null);
}
/** `'unreadable'` when the host would not say what is stored; never guessed as "nothing". */
private async load(): Promise<Stored | null | 'unreadable'> {
let raw = '';
for (let attempt = 1; ; attempt++) {
const read = await this.device.storageGet(STORAGE_KEY);
if (read.ok) {
raw = read.value;
break;
}
if (attempt >= 3) return 'unreadable';
}
try {
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,
activeCancelled: parsed.activeCancelled === true,
lastTurnAt: typeof parsed.lastTurnAt === 'number' ? parsed.lastTurnAt : undefined,
agentId: typeof parsed.agentId === 'string' ? parsed.agentId : undefined,
others: validThreads(parsed.others),
agents: validAgents(parsed.agents),
};
} catch {
return null;
}
}
/** True only when the host confirmed the write. See DevicePort.storageSet. */
private async save(): Promise<boolean> {
const ok = await this.device.storageSet(STORAGE_KEY, this.stored ? JSON.stringify(this.stored) : '');
if (!ok) this.note('storage', 'a write to app storage was not confirmed');
return ok;
}
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());
}
}
/**
* How long to wait before asking the bridge again, given how long this turn has been running.
* Most answers arrive within a few seconds, so checks are frequent then; a long agent run is
* checked less often to spare the phone's radio and battery.
*/
export function pollDelay(elapsedMs: number): number {
if (elapsedMs < 8_000) return 200;
if (elapsedMs < 30_000) return 400;
return 1000;
}
/** The conversation this create was for has been replaced; its result must not be used. */
class StaleConversationError extends Error {
override name = 'StaleConversationError';
}
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';
}