- bridge: GET /v1/speech (which agents have a voice) and GET /v1/turns/{id}/speech (MP3 of the
caller's own finished answer, markup removed, first 900 characters). ElevenLabs adapter; key
and voice ids from the environment; per-device budget; last three clips kept in memory.
speech.done / speech.failed log ids, lengths and durations only.
- bridge: forceCloseConnections. A request the client had abandoned kept shutdown waiting for
ever (also true of /v1/transcribe as deployed). Regression test for both routes.
- client: 'Voice: off/on' on the opening menu when the bridge offers it and the page can play
sound; off at every launch. With it on, a finished answer is fetched and played; it stops
when the answer leaves the screen; the app does not leave the glasses while it plays.
- tests: fake provider, fake loudspeaker (tests/integration/voice.test.ts).
- docs: 0006, security 3g-3i, device plan E, 0.4.1 rollout and Dan's sound check report.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1693 lines
72 KiB
TypeScript
1693 lines
72 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';
|
|
import { SpeechSegmenter, WAKE_SEGMENTER, type SegmenterOptions } from './vad.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;
|
|
/**
|
|
* Hands free (listening for an agent's name). `available`: this build and this bridge can do
|
|
* it. `enabled`: that mode is the one in use. `listening`: the microphone is open for it now.
|
|
*/
|
|
wake: { available: boolean; enabled: boolean; listening: boolean };
|
|
/** Reading answers aloud. `offered`: possible here. `on`: switched on. `speaking`: playing now. */
|
|
voice: { offered: boolean; on: boolean; speaking: boolean };
|
|
log: DiagEntry[];
|
|
}
|
|
|
|
/** Something that can play an answer's audio. The real one is the page's sound engine. */
|
|
export interface SpeakerPort {
|
|
/** Play MP3 audio. Resolves when it has finished or was stopped; rejects if it cannot play. */
|
|
play(audio: Uint8Array): Promise<void>;
|
|
stop(): void;
|
|
}
|
|
|
|
export interface WakeTiming {
|
|
/** After a name alone, a pause this long ends the question that follows. */
|
|
commandEndSilenceMs: number;
|
|
/** After a name alone, nothing said for this long: back to rest, nothing sent. */
|
|
armTimeoutMs: number;
|
|
/** No audio frames for this long while listening: the microphone is reopened. */
|
|
stallMs: number;
|
|
/** How long to wait before trying again after the microphone was refused or stayed silent. */
|
|
retryMs: number;
|
|
/** How often the microphone is checked on. */
|
|
watchMs: number;
|
|
/** After the bridge refused or could not be reached, speech is not sent for this long. */
|
|
pauseMs: number;
|
|
}
|
|
|
|
export interface PreviewTiming {
|
|
/** Nothing is transcribed until this much has been recorded. */
|
|
firstMs: number;
|
|
/** A new preview is asked for once this much more has been recorded (and the last one is back). */
|
|
stepMs: number;
|
|
/** After a failure, previews are not asked for again for this long. */
|
|
pauseMs: number;
|
|
}
|
|
|
|
export const DEFAULT_PREVIEW_TIMING: PreviewTiming = { firstMs: 700, stepMs: 500, pauseMs: 5000 };
|
|
|
|
/** Lines of the body left for the words under the "… is listening…" title and a blank line. */
|
|
const PREVIEW_LINES = HUD.bodyLines - 2;
|
|
|
|
export const DEFAULT_WAKE_TIMING: WakeTiming = {
|
|
commandEndSilenceMs: 1200,
|
|
armTimeoutMs: 6000,
|
|
stallMs: 5000,
|
|
retryMs: 15_000,
|
|
watchMs: 2000,
|
|
pauseMs: 10_000,
|
|
};
|
|
|
|
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;
|
|
/**
|
|
* Lets answers be read aloud when the bridge can do it and the user switches Voice on (a
|
|
* menu entry, so it needs `menu`). Without it nothing is ever fetched or played.
|
|
*/
|
|
speaker?: SpeakerPort | null;
|
|
/** 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;
|
|
/**
|
|
* Make hands-free mode possible: while it is in use the microphone is open whenever the app is
|
|
* at rest, listening for an agent's name ("Wendy, ..."), and the app does not leave the
|
|
* glasses by itself. Absent or `null`: there is no such mode and the microphone opens only on
|
|
* a tap.
|
|
*/
|
|
wake?: Partial<WakeTiming> | null;
|
|
/**
|
|
* Show the words of a recording while it is being made: every so often the recording so far
|
|
* is sent to the bridge for transcription. Off unless set.
|
|
*/
|
|
livePreview?: boolean | Partial<PreviewTiming>;
|
|
/**
|
|
* Open on a menu (Hands free, Agents) instead of at Ready; double tap at Ready returns to it.
|
|
* Without it the app opens at Ready, in hands-free mode if `wake` is given.
|
|
*/
|
|
menu?: boolean;
|
|
/** 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;
|
|
/** Started by name: it ends when the speaker stops, and is given up if nobody speaks. */
|
|
auto: boolean;
|
|
startedAt: number;
|
|
/** The whole question was already spoken before the recording began: send it as it is. */
|
|
complete: boolean;
|
|
/** How much of it had been recorded when the last live preview was asked for. */
|
|
previewedBytes: number;
|
|
}
|
|
|
|
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;
|
|
|
|
// ---- words shown while recording (unused when `preview` is null)
|
|
private readonly preview: PreviewTiming | null;
|
|
private previewBusy = false;
|
|
private previewPausedUntil = 0;
|
|
/** The bridge said it cannot do previews (or is too old): stop asking for this session. */
|
|
private previewUnsupported = false;
|
|
|
|
// ---- reading answers aloud (all unused without a speaker)
|
|
/** The agents the bridge has a voice for. */
|
|
private speechAgents: string[] = [];
|
|
/** The answer being fetched or played. `abort` stops the fetch. */
|
|
private speaking: { requestId: string; abort: AbortController; playing: boolean } | null = null;
|
|
|
|
// ---- listening for a name (all unused when `wake` is null)
|
|
private readonly wake: WakeTiming | null;
|
|
private readonly segmenter = new SpeechSegmenter();
|
|
/** Every microphone open and close in wake mode goes through this, one after another. */
|
|
private micChain: Promise<void> = Promise.resolve();
|
|
private micRestart = false;
|
|
/** A stretch of speech is at the bridge being checked for a name. One at a time. */
|
|
private wakeChecking = false;
|
|
/** The latest stretch of speech that ended while a check was still out. */
|
|
private wakeBacklog: Uint8Array | null = null;
|
|
private wakePausedUntil = 0;
|
|
/** The bridge said it has no wake names (or is too old): stop asking for this session. */
|
|
private wakeUnsupported = false;
|
|
private wakeFrameAt = 0;
|
|
private wakeRetryAt = 0;
|
|
/** Already noted, so a repeated refusal or stall is logged once per streak. */
|
|
private wakeTrouble = false;
|
|
private wakeWatch: ReturnType<typeof setInterval> | 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);
|
|
this.wake = options.wake ? { ...DEFAULT_WAKE_TIMING, ...options.wake } : null;
|
|
this.preview = options.livePreview ? { ...DEFAULT_PREVIEW_TIMING, ...(options.livePreview === true ? {} : options.livePreview) } : null;
|
|
}
|
|
|
|
// ------------------------------------------------------------------ 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,
|
|
menu: this.options.menu === true,
|
|
handsFree: this.handsFreeAvailable(),
|
|
});
|
|
if (abandoned) void this.cancelTurn(abandoned);
|
|
void this.loadSpeech();
|
|
if (this.wake) this.wakeWatch = setInterval(() => this.watchWakeMic(), this.wake.watchMs);
|
|
}
|
|
|
|
// ------------------------------------------------------- listening for a name
|
|
|
|
/** This build has hands free, and nothing has said the bridge cannot do it. */
|
|
private handsFreeAvailable(): boolean {
|
|
return this.wake !== null && !this.wakeUnsupported && this.status?.stt_configured !== false;
|
|
}
|
|
|
|
/** Hands-free mode is the one in use. While true the app stays open. */
|
|
private wakeOn(): boolean {
|
|
return this.handsFreeAvailable() && this.stored !== null && this.state.mode === 'handsfree';
|
|
}
|
|
|
|
/** Right now the microphone should be open, listening for a name. Only ever at rest. */
|
|
private wakeActive(): boolean {
|
|
return (
|
|
this.wakeOn() && this.client !== null && this.hudReady && !this.stopped && !this.exited && !this.leaving && RESTING.has(this.state.phase)
|
|
);
|
|
}
|
|
|
|
private wakeSegmenter(endSilenceMs = WAKE_SEGMENTER.endSilenceMs): SegmenterOptions {
|
|
return { ...WAKE_SEGMENTER, endSilenceMs, maxMs: this.state.captureMaxSeconds * 1000 };
|
|
}
|
|
|
|
/** Wake mode: after anything that may change whether the microphone should be open. */
|
|
private afterChange(): void {
|
|
if (!this.wake) return;
|
|
if (this.capture?.auto) {
|
|
// The segmenter is following the recording that a name started.
|
|
} else if (this.wakeActive() && !this.capture) {
|
|
this.segmenter.configure(this.wakeSegmenter());
|
|
} else {
|
|
// Not listening: nothing half-heard is kept for later.
|
|
this.segmenter.reset();
|
|
this.wakeBacklog = null;
|
|
}
|
|
void this.syncMic();
|
|
}
|
|
|
|
/**
|
|
* Wake mode: bring the microphone to where it should be now (open for a recording or for
|
|
* listening, otherwise closed). Runs strictly one after another, and looks at what is wanted
|
|
* when its turn comes, so a burst of changes always ends in the right place. Resolves to
|
|
* whether the microphone is open.
|
|
*/
|
|
private syncMic(): Promise<boolean> {
|
|
const run = this.micChain.then(async () => {
|
|
if (this.micRestart && this.micOpen) {
|
|
this.micOpen = false;
|
|
await this.device.stopMic();
|
|
}
|
|
this.micRestart = false;
|
|
const want = !this.stopped && (this.capture !== null || this.wakeActive());
|
|
if (want && !this.micOpen) {
|
|
// A refused microphone is not asked for again at every turn of the app, only by the
|
|
// periodic check. A recording the user asked for always tries.
|
|
if (this.capture !== null || this.now() >= this.wakeRetryAt) {
|
|
this.micOpen = true;
|
|
const ok = await this.device.startMic();
|
|
if (ok) {
|
|
this.wakeFrameAt = this.now();
|
|
} else {
|
|
this.micOpen = false;
|
|
this.wakeRetryAt = this.now() + this.wake!.retryMs;
|
|
if (!this.wakeTrouble) this.note('wake', 'the microphone could not be opened; will keep trying');
|
|
this.wakeTrouble = true;
|
|
}
|
|
}
|
|
} else if (!want && this.micOpen) {
|
|
this.micOpen = false;
|
|
await this.device.stopMic();
|
|
}
|
|
const listening = this.micOpen && this.wakeActive();
|
|
if (listening !== this.state.wakeListening) {
|
|
this.note('wake', listening ? 'listening for a name' : 'stopped listening');
|
|
this.dispatch({ type: 'wake_status', listening });
|
|
}
|
|
return this.micOpen;
|
|
});
|
|
this.micChain = run.then(
|
|
() => undefined,
|
|
() => undefined,
|
|
);
|
|
return run.catch(() => false);
|
|
}
|
|
|
|
/** Periodic: a listening microphone that has gone quiet, or was refused, is opened again. */
|
|
private watchWakeMic(): void {
|
|
if (!this.wake || this.capture || !this.wakeActive()) return;
|
|
if (!this.micOpen) {
|
|
if (this.now() >= this.wakeRetryAt) void this.syncMic();
|
|
return;
|
|
}
|
|
if (this.now() - this.wakeFrameAt <= this.wake.stallMs) return;
|
|
// A suspended page or a dropped stream both look like silence on the wire.
|
|
if (!this.wakeTrouble) this.note('wake', 'no audio frames while listening; reopening the microphone');
|
|
this.wakeTrouble = true;
|
|
this.micRestart = true;
|
|
this.wakeFrameAt = this.now() + this.wake.retryMs - this.wake.stallMs;
|
|
void this.syncMic();
|
|
}
|
|
|
|
private onWakeAudio(pcm: Uint8Array): void {
|
|
this.wakeFrameAt = this.now();
|
|
this.wakeTrouble = false;
|
|
for (const event of this.segmenter.push(pcm)) {
|
|
if (event.type !== 'end') continue;
|
|
if (this.wakeChecking) this.wakeBacklog = event.pcm;
|
|
else void this.checkWake(event.pcm);
|
|
}
|
|
}
|
|
|
|
/** Ask the bridge whether this stretch of speech began with an agent's name. */
|
|
private async checkWake(pcm: Uint8Array): Promise<void> {
|
|
const client = this.client;
|
|
if (!client || this.wakeChecking || this.now() < this.wakePausedUntil) return;
|
|
this.wakeChecking = true;
|
|
const generation = this.state.generation;
|
|
let matched = false;
|
|
try {
|
|
const result = await client.wake({ pcm, locale: this.options.locale });
|
|
// Anything the user did meanwhile (a tap, a cancel, a new pairing) wins over what was heard.
|
|
if (this.stale(generation) || this.client !== client || !this.wakeActive()) return;
|
|
if (result.matched && result.agent_id) {
|
|
matched = true;
|
|
this.onWake(result.agent_id, result.text);
|
|
} else if (result.near_miss) {
|
|
// The one place a spoken word reaches Diagnostics: a single word that was nearly a
|
|
// name, so that an alias can be added for it on the bridge.
|
|
this.note('wake', `heard "${result.near_miss}", which is close to an agent's name but not one`);
|
|
this.emit();
|
|
}
|
|
} catch (err) {
|
|
if (err instanceof BridgeApiError && err.body.code === 'not_found') {
|
|
this.wakeUnsupported = true;
|
|
this.note('wake', 'this bridge has no agent that can be called by name; hands free is not available');
|
|
this.dispatch({ type: 'handsfree_lost' });
|
|
} else {
|
|
this.note('wake', `check failed: ${describe(err)}`);
|
|
this.wakePausedUntil = this.now() + this.wake!.pauseMs;
|
|
if (err instanceof BridgeApiError) await this.afterAuthFailure(err);
|
|
}
|
|
} finally {
|
|
this.wakeChecking = false;
|
|
}
|
|
// Something else was said while that check was out: it gets its own check, unless it was
|
|
// already used as the question that followed a name.
|
|
const next = this.wakeBacklog;
|
|
this.wakeBacklog = null;
|
|
if (next && !matched && !this.stale(generation) && this.wakeActive()) void this.checkWake(next);
|
|
}
|
|
|
|
/** An agent was called by name. `text` is what followed in the same breath, if anything. */
|
|
private onWake(agentId: string, text: string): void {
|
|
if (!this.stored) return;
|
|
const offered = this.state.agents;
|
|
// With no choice on offer there is only the default agent, and nothing about agents is sent.
|
|
if (offered.length === 0 ? agentId !== DEFAULT_AGENT : !offered.some((a) => a.id === agentId)) return;
|
|
const target = offered.length === 0 ? null : agentId;
|
|
const switching = target !== null && target !== currentAgent(this.state)?.id;
|
|
if (switching) this.swapStoredAgent(agentId);
|
|
let conversationId = switching ? this.stored.conversationId : this.state.conversationId;
|
|
// The app now stays open, so "a while since the last question" is checked here too, not
|
|
// only when the app starts.
|
|
if (conversationId && this.stored.lastTurnAt !== undefined && this.now() - this.stored.lastTurnAt > this.conversationGapMs) {
|
|
this.note('conversation', 'last question was a while ago: this one starts a new conversation');
|
|
conversationId = null;
|
|
this.stored = { ...this.stored, conversationId: null };
|
|
}
|
|
void this.save();
|
|
this.note('wake', `${agentId} was called by name${text ? '' : ' (name only: recording the question)'}`);
|
|
const freshId = this.newId();
|
|
this.dispatch(
|
|
text ? { type: 'wake_text', freshId, agentId: target, conversationId, text } : { type: 'wake_listen', freshId, agentId: target, conversationId },
|
|
);
|
|
}
|
|
|
|
// ------------------------------------------------------------------ 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;
|
|
if (this.wakeWatch) clearInterval(this.wakeWatch);
|
|
this.wakeWatch = null;
|
|
this.stopTicker();
|
|
this.quiet();
|
|
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,
|
|
wake: {
|
|
available: this.handsFreeAvailable(),
|
|
enabled: this.wakeOn(),
|
|
listening: this.state.wakeListening,
|
|
},
|
|
voice: { offered: this.state.voiceOffered, on: this.state.voice, speaking: this.speaking?.playing === true },
|
|
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,
|
|
menu: this.options.menu === true,
|
|
handsFree: this.handsFreeAvailable(),
|
|
});
|
|
void this.loadSpeech();
|
|
}
|
|
|
|
/** 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();
|
|
// An answer is only read while it is the one on screen: anything that moves on stops it.
|
|
if (this.speaking && (this.state.phase !== 'answer' || this.state.requestId !== this.speaking.requestId || !this.state.voice)) this.quiet();
|
|
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.afterChange();
|
|
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;
|
|
// Listening for a name is the point of staying open: the app does not leave by itself.
|
|
if (this.wakeOn()) return;
|
|
// Not while an answer is being read out: the countdown starts when it ends.
|
|
if (this.speaking) return;
|
|
const phase = this.state.phase;
|
|
const wait =
|
|
phase === 'answer'
|
|
? this.idleExitMs.answer
|
|
: phase === 'ready' || phase === 'menu'
|
|
? 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.
|
|
this.afterChange();
|
|
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, effect.auto === true && this.wake !== null);
|
|
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, auto = false): Promise<void> {
|
|
const capture: Capture = {
|
|
generation,
|
|
chunks: [],
|
|
bytes: 0,
|
|
maxBytes: this.state.captureMaxSeconds * AUDIO_FORMAT.bytesPerSecond,
|
|
lastFrameAt: this.now(),
|
|
limitSent: false,
|
|
auto,
|
|
startedAt: this.now(),
|
|
complete: false,
|
|
previewedBytes: 0,
|
|
};
|
|
if (auto) {
|
|
// The name was recognised a moment after it was said, and the speaker may not have
|
|
// waited: whatever has been said since belongs to this question.
|
|
for (const heard of [this.wakeBacklog, this.segmenter.buffered()]) {
|
|
const room = capture.maxBytes - capture.bytes;
|
|
if (!heard || heard.length === 0 || room <= 0) continue;
|
|
const chunk = heard.length > room ? heard.slice(0, room - (room % 2)) : heard;
|
|
capture.chunks.push(chunk);
|
|
capture.bytes += chunk.length;
|
|
}
|
|
capture.complete = this.wakeBacklog !== null && !this.segmenter.speaking;
|
|
this.wakeBacklog = null;
|
|
this.segmenter.configure(this.wakeSegmenter(this.wake!.commandEndSilenceMs));
|
|
}
|
|
this.capture = capture;
|
|
let ok: boolean;
|
|
if (this.wake) {
|
|
ok = await this.syncMic();
|
|
} else {
|
|
this.micOpen = true;
|
|
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.stopTicker();
|
|
if (this.wake) {
|
|
await this.syncMic();
|
|
} else {
|
|
this.micOpen = false;
|
|
await this.device.stopMic();
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
if (!ok) {
|
|
this.capture = null;
|
|
if (!this.wake) 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();
|
|
if (capture.complete && !capture.limitSent) {
|
|
capture.limitSent = true;
|
|
this.dispatch({ type: 'capture_limit', generation });
|
|
}
|
|
}
|
|
|
|
private onAudio(pcm: Uint8Array): void {
|
|
const capture = this.capture;
|
|
if (!capture) {
|
|
// No recording: while listening for a name the frame goes to the speech detector.
|
|
// Otherwise it is dropped on the floor.
|
|
if (this.wake && this.micOpen && this.wakeActive()) this.onWakeAudio(pcm);
|
|
return;
|
|
}
|
|
// Frames outside an active, current-generation capture are dropped on the floor.
|
|
if (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 });
|
|
}
|
|
if (capture.auto && !capture.limitSent) this.followAutoCapture(capture, pcm);
|
|
if (!capture.limitSent) this.maybePreview(capture);
|
|
}
|
|
|
|
/**
|
|
* Ask the bridge for the words so far, one request at a time. What comes back is only ever
|
|
* drawn: the recording that is finally sent is transcribed again as part of its own turn.
|
|
*/
|
|
private maybePreview(capture: Capture): void {
|
|
const timing = this.preview;
|
|
const client = this.client;
|
|
if (!timing || !client || this.previewUnsupported || this.previewBusy || this.now() < this.previewPausedUntil) return;
|
|
if (this.status?.stt_configured === false) return;
|
|
// Agents only (Dan, 2026-11-28). In hands free nothing but the wake check and the question
|
|
// itself is ever sent for transcription.
|
|
if (this.state.mode !== 'agents') return;
|
|
const ms = (bytes: number) => (bytes / AUDIO_FORMAT.bytesPerSecond) * 1000;
|
|
if (ms(capture.bytes) < timing.firstMs) return;
|
|
if (capture.previewedBytes > 0 && ms(capture.bytes - capture.previewedBytes) < timing.stepMs) return;
|
|
capture.previewedBytes = capture.bytes;
|
|
const usable = capture.bytes - (capture.bytes % 2);
|
|
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.previewBusy = true;
|
|
void client
|
|
.transcribe({ pcm, locale: this.options.locale })
|
|
.then(
|
|
(result) => {
|
|
// Only for the recording it was made from, and only while that is still being made.
|
|
if (this.capture !== capture || this.stale(capture.generation) || this.state.phase !== 'listening') return;
|
|
if (result.text) this.dispatch({ type: 'capture_preview', generation: capture.generation, text: this.fitPreview(result.text) });
|
|
},
|
|
(err) => {
|
|
if (err instanceof BridgeApiError && err.body.code === 'not_found') {
|
|
this.previewUnsupported = true;
|
|
this.note('preview', 'this bridge cannot show words while recording');
|
|
} else {
|
|
// Busy, over the limit or unreachable: the recording carries on without a preview.
|
|
this.previewPausedUntil = this.now() + (err instanceof BridgeApiError && err.body.code === 'rate_limited' ? 1000 : timing.pauseMs);
|
|
if (!(err instanceof BridgeApiError && err.body.code === 'rate_limited')) this.note('preview', `not available just now: ${describe(err)}`);
|
|
}
|
|
},
|
|
)
|
|
.finally(() => {
|
|
this.previewBusy = false;
|
|
});
|
|
}
|
|
|
|
/** The end of the text that fits under the title: the newest words are the ones to see. */
|
|
private fitPreview(text: string): string {
|
|
const words = toPlainText(text).split(/\s+/).filter(Boolean);
|
|
let from = 0;
|
|
for (;;) {
|
|
const shown = (from > 0 ? '… ' : '') + words.slice(from).join(' ');
|
|
if (from >= words.length - 1 || (shown.length <= 600 && this.options.measure(shown, BODY_BOX.innerWidth) <= PREVIEW_LINES)) return shown.slice(-600);
|
|
from += Math.max(1, Math.ceil((words.length - from) / 8));
|
|
}
|
|
}
|
|
|
|
/** A recording started by name: send when the speaker stops, give up if nobody speaks. */
|
|
private followAutoCapture(capture: Capture, pcm: Uint8Array): void {
|
|
for (const event of this.segmenter.push(pcm)) {
|
|
if (event.type !== 'end') continue;
|
|
capture.limitSent = true;
|
|
this.note('capture', 'the speaker stopped');
|
|
this.dispatch({ type: 'capture_limit', generation: capture.generation });
|
|
return;
|
|
}
|
|
if (!this.segmenter.speaking && this.now() - capture.startedAt > this.wake!.armTimeoutMs) {
|
|
capture.limitSent = true;
|
|
this.note('capture', 'nothing was said after the name');
|
|
this.dispatch({ type: 'capture_abandoned', 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.wake) {
|
|
// Wake mode: "close" means "put it where it should be", which at rest is open.
|
|
this.stopTicker();
|
|
await this.syncMic();
|
|
return;
|
|
}
|
|
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 });
|
|
if (result.terminal && (result.outcome === 'succeeded' || result.outcome === 'incomplete') && result.answer_text) {
|
|
void this.speak(result.request_id);
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------ reading answers aloud
|
|
|
|
/** Ask the bridge whether it can read answers aloud. Quietly "no" on any failure. */
|
|
private async loadSpeech(): Promise<void> {
|
|
const client = this.client;
|
|
if (!this.options.speaker || !client) return;
|
|
let agents: string[] = [];
|
|
try {
|
|
const info = await client.speech();
|
|
agents = info.available ? info.agent_ids : [];
|
|
} catch (err) {
|
|
if (!(err instanceof BridgeApiError && err.body.code === 'not_found')) this.note('voice', `not available: ${describe(err)}`);
|
|
}
|
|
if (this.stopped || this.client !== client) return;
|
|
this.speechAgents = agents;
|
|
this.dispatch({ type: 'voice_offered', offered: agents.length > 0 });
|
|
}
|
|
|
|
/** Read the answer on screen aloud, if Voice is on and its agent has a voice. */
|
|
private async speak(requestId: string): Promise<void> {
|
|
const speaker = this.options.speaker;
|
|
const client = this.client;
|
|
if (!speaker || !client || !this.state.voice) return;
|
|
if (this.state.phase !== 'answer' || this.state.requestId !== requestId) return;
|
|
if (!this.speechAgents.includes(this.state.agentId ?? 'default')) return;
|
|
this.quiet();
|
|
const mine = { requestId, abort: new AbortController(), playing: false };
|
|
this.speaking = mine;
|
|
this.scheduleIdleExit();
|
|
const startedAt = this.now();
|
|
try {
|
|
const audio = await client.turnSpeech(requestId, mine.abort.signal);
|
|
if (this.speaking !== mine) return;
|
|
this.note('voice', `audio for ${requestId}: ${audio.length} bytes in ${this.now() - startedAt} ms`);
|
|
mine.playing = true;
|
|
this.emit();
|
|
await speaker.play(audio);
|
|
if (this.speaking === mine) this.note('voice', `finished ${requestId} after ${this.now() - startedAt} ms`);
|
|
} catch (err) {
|
|
// No speech this time. The answer is on the glasses either way.
|
|
if (this.speaking === mine) this.note('voice', `not spoken: ${describe(err)}`);
|
|
} finally {
|
|
if (this.speaking === mine) {
|
|
this.speaking = null;
|
|
this.emit();
|
|
this.scheduleIdleExit();
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Stop reading aloud, and stop waiting for audio that has not arrived. */
|
|
private quiet(): void {
|
|
const was = this.speaking;
|
|
if (!was) return;
|
|
this.speaking = null;
|
|
was.abort.abort();
|
|
try {
|
|
this.options.speaker?.stop();
|
|
} catch {
|
|
// Nothing was playing.
|
|
}
|
|
this.note('voice', `stopped ${was.requestId}`);
|
|
}
|
|
|
|
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);
|
|
this.afterChange();
|
|
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';
|
|
}
|