Opening menu and hands-free mode: call an agent by name (0.3.0)
The app now opens on a menu, which is the root page: "Hands free" first, "Agents" second. Agents is the 0.2.0 app unchanged. Hands free is the same agents, conversations and question path with one flag set: the microphone listens while the app is at rest and the app does not leave by itself. The mode is never remembered; every launch starts at the menu with the microphone closed, and double tap at Ready returns to the menu and closes it. Client: a loudness-only speech segmenter (core/vad.ts) cuts the stream into utterances; each goes to the bridge for a wake check. "Wendy, <q>" becomes a text turn to Wendy, with what was heard shown while she works. A name alone starts a recording that sends itself when the speaker stops. The status line starts with a dot for exactly as long as the microphone is open at rest. In wake mode every microphone open and close goes through one serialised reconciler; without the option the old path is untouched. Bridge: POST /v1/wake transcribes one utterance in memory and reports whether it BEGAN with an agent's name (first word of the display name, or an alias from HERMEVEN_AGENT_<ID>_WAKE). Exact match only; a near miss is reported as one word and never acted on. Creates no turn, stores nothing, returns and logs nothing that was not addressed to an agent. One check at a time per device, HERMEVEN_WAKE_CHECKS_PER_MINUTE (30). Docs: decision 0004, bridge API, security gaps 3c/3d, device plan D. The manifest's microphone description changed. Not reviewed, not deployed, not uploaded, not device-tested. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
"package_id": "xylo.hermeven",
|
||||
"edition": "202601",
|
||||
"name": "Pepper",
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.0",
|
||||
"min_sdk_version": "0.0.16",
|
||||
"entrypoint": "index.html",
|
||||
"permissions": [
|
||||
@@ -13,7 +13,7 @@
|
||||
},
|
||||
{
|
||||
"name": "g2-microphone",
|
||||
"desc": "Records your question from the glasses microphone, only while you have tapped to ask."
|
||||
"desc": "Records your question from the glasses microphone when you tap to ask. In hands-free mode, which you choose on the opening menu, it listens while the app is open for an agent's name and your question."
|
||||
}
|
||||
],
|
||||
"supported_languages": ["en"]
|
||||
|
||||
@@ -31,6 +31,10 @@ export interface BootOptions {
|
||||
dev?: boolean;
|
||||
/** `false` keeps the app on the glasses indefinitely; an object overrides the times. Both are for automated simulator runs. */
|
||||
idleExit?: boolean | Partial<IdleExitMs>;
|
||||
/** `false` removes hands-free mode (the microphone then opens only on a tap). */
|
||||
wake?: boolean;
|
||||
/** `false` opens at Ready instead of on the menu. For automated simulator runs. */
|
||||
menu?: boolean;
|
||||
/** Reload hook, replaceable in tests. */
|
||||
reload?: () => void;
|
||||
}
|
||||
@@ -92,6 +96,9 @@ export async function boot(doc: Document, win: Window, options: BootOptions = {}
|
||||
measure: (text, width) => measureTextWrap(text, width).lineCount,
|
||||
locale: win.navigator.language || 'en-US',
|
||||
onChange: (snapshot) => update(snapshot),
|
||||
// Hands free needs the glasses' microphone: never in the browser preview.
|
||||
wake: mode === 'even' && options.wake !== false ? {} : null,
|
||||
menu: options.menu !== false,
|
||||
...(options.idleExit === false ? { idleExit: null } : typeof options.idleExit === 'object' ? { idleExit: options.idleExit } : {}),
|
||||
// Development builds mirror diagnostics to the console (visible in the simulator and the
|
||||
// Even dev console). Diagnostics never contain questions, answers or credentials.
|
||||
|
||||
@@ -6,6 +6,7 @@ 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';
|
||||
|
||||
@@ -88,9 +89,38 @@ export interface Snapshot {
|
||||
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 };
|
||||
log: DiagEntry[];
|
||||
}
|
||||
|
||||
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 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;
|
||||
@@ -129,6 +159,18 @@ export interface ControllerOptions {
|
||||
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;
|
||||
/**
|
||||
* 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. */
|
||||
@@ -142,6 +184,11 @@ interface Capture {
|
||||
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;
|
||||
}
|
||||
|
||||
type PendingInput = { requestId: string; kind: 'text'; text: string } | { requestId: string; kind: 'audio'; pcm: Uint8Array };
|
||||
@@ -206,6 +253,25 @@ export class Controller {
|
||||
/** Set while a long press that STARTED a recording is still held down. */
|
||||
private heldPress: { generation: number; at: number } | 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;
|
||||
@@ -220,6 +286,7 @@ export class Controller {
|
||||
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;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ public
|
||||
@@ -290,8 +357,184 @@ export class Controller {
|
||||
storageFault: this.storageFault,
|
||||
agents,
|
||||
agentId: this.stored?.agentId ?? null,
|
||||
menu: this.options.menu === true,
|
||||
handsFree: this.handsFreeAvailable(),
|
||||
});
|
||||
if (abandoned) void this.cancelTurn(abandoned);
|
||||
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.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
|
||||
@@ -394,6 +637,8 @@ export class Controller {
|
||||
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();
|
||||
await this.closeMic();
|
||||
}
|
||||
@@ -411,6 +656,11 @@ export class Controller {
|
||||
launchSource: this.launchSource,
|
||||
glassesInput: this.device.inputSummary?.() ?? '',
|
||||
lastTurn: this.lastTurn,
|
||||
wake: {
|
||||
available: this.handsFreeAvailable(),
|
||||
enabled: this.wakeOn(),
|
||||
listening: this.state.wakeListening,
|
||||
},
|
||||
log: [...this.log],
|
||||
};
|
||||
}
|
||||
@@ -453,7 +703,17 @@ export class Controller {
|
||||
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 });
|
||||
this.dispatch({
|
||||
type: 'init',
|
||||
paired: true,
|
||||
conversationId: null,
|
||||
captureMaxSeconds,
|
||||
resumeRequestId: null,
|
||||
agents,
|
||||
agentId: null,
|
||||
menu: this.options.menu === true,
|
||||
handsFree: this.handsFreeAvailable(),
|
||||
});
|
||||
}
|
||||
|
||||
/** Disconnect: revoke the credential on the bridge, then clear everything held locally. */
|
||||
@@ -520,6 +780,7 @@ export class Controller {
|
||||
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.afterChange();
|
||||
this.render();
|
||||
this.emit();
|
||||
this.scheduleIdleExit();
|
||||
@@ -546,11 +807,13 @@ export class Controller {
|
||||
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;
|
||||
const phase = this.state.phase;
|
||||
const wait =
|
||||
phase === 'answer'
|
||||
? this.idleExitMs.answer
|
||||
: phase === 'ready'
|
||||
: phase === 'ready' || phase === 'menu'
|
||||
? this.idleExitMs.ready
|
||||
: phase === 'error' || phase === 'cancelled'
|
||||
? this.idleExitMs.message
|
||||
@@ -598,6 +861,7 @@ export class Controller {
|
||||
// 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) {
|
||||
@@ -616,7 +880,7 @@ export class Controller {
|
||||
try {
|
||||
switch (effect.type) {
|
||||
case 'start_capture':
|
||||
return await this.startCapture(effect.generation);
|
||||
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':
|
||||
@@ -642,7 +906,7 @@ export class Controller {
|
||||
}
|
||||
}
|
||||
|
||||
private async startCapture(generation: number): Promise<void> {
|
||||
private async startCapture(generation: number, auto = false): Promise<void> {
|
||||
const capture: Capture = {
|
||||
generation,
|
||||
chunks: [],
|
||||
@@ -650,36 +914,72 @@ export class Controller {
|
||||
maxBytes: this.state.captureMaxSeconds * AUDIO_FORMAT.bytesPerSecond,
|
||||
lastFrameAt: this.now(),
|
||||
limitSent: false,
|
||||
auto,
|
||||
startedAt: this.now(),
|
||||
complete: false,
|
||||
};
|
||||
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;
|
||||
this.micOpen = true;
|
||||
const ok = await this.device.startMic();
|
||||
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.micOpen = false;
|
||||
this.stopTicker();
|
||||
await this.device.stopMic();
|
||||
if (this.wake) {
|
||||
await this.syncMic();
|
||||
} else {
|
||||
this.micOpen = false;
|
||||
await this.device.stopMic();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!ok) {
|
||||
this.capture = null;
|
||||
this.micOpen = false;
|
||||
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 || capture.generation !== this.state.generation || this.state.phase !== 'listening') return;
|
||||
if (capture.generation !== this.state.generation || this.state.phase !== 'listening') return;
|
||||
capture.lastFrameAt = this.now();
|
||||
const room = capture.maxBytes - capture.bytes;
|
||||
if (room > 0) {
|
||||
@@ -692,6 +992,23 @@ export class Controller {
|
||||
this.note('capture', 'capture limit reached');
|
||||
this.dispatch({ type: 'capture_limit', generation: capture.generation });
|
||||
}
|
||||
if (capture.auto && !capture.limitSent) this.followAutoCapture(capture, pcm);
|
||||
}
|
||||
|
||||
/** 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> {
|
||||
@@ -718,6 +1035,12 @@ export class Controller {
|
||||
}
|
||||
|
||||
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();
|
||||
@@ -1008,6 +1331,7 @@ export class Controller {
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { currentAgent, type AppState } from './reducer.ts';
|
||||
import { currentAgent, menuItems, MODE_LABEL, type AppState } from './reducer.ts';
|
||||
|
||||
/**
|
||||
* HUD geometry. Canvas size and line height are documented by Even
|
||||
@@ -41,8 +41,37 @@ function clock(seconds: number): string {
|
||||
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** The longest question shown back while the agent works; the rest is on the phone. */
|
||||
const HEARD_MAX = 160;
|
||||
|
||||
/** Shown in the status bar for as long as the microphone is open at rest. */
|
||||
export const MIC_OPEN = '● ';
|
||||
|
||||
/**
|
||||
* The names to call, as they are said: the first word of each agent's name. As many as fit
|
||||
* comfortably; the rest are still reachable by swiping.
|
||||
*/
|
||||
function callNames(state: AppState): string {
|
||||
const names: string[] = [];
|
||||
let used = 0;
|
||||
for (const { name } of state.agents) {
|
||||
const word = name.trim().split(/\s+/)[0] ?? name;
|
||||
if (names.length > 0 && used + word.length > 80) return `${names.join(' · ')} …`;
|
||||
names.push(word);
|
||||
used += word.length + 3;
|
||||
}
|
||||
return names.join(' · ');
|
||||
}
|
||||
|
||||
/** Pure: the complete HUD text for a state at a moment in time. */
|
||||
export function renderHud(state: AppState, nowMs: number): HudFrame {
|
||||
const frame = renderFrame(state, nowMs);
|
||||
// The microphone is open and listening for a name: every resting screen says so.
|
||||
const resting = state.phase === 'ready' || state.phase === 'answer' || state.phase === 'error' || state.phase === 'cancelled';
|
||||
return state.wakeListening && resting ? { body: frame.body, status: `${MIC_OPEN}${frame.status}` } : frame;
|
||||
}
|
||||
|
||||
function renderFrame(state: AppState, nowMs: number): HudFrame {
|
||||
// With more than one agent on offer, every screen of an exchange says who it is with.
|
||||
const agent = state.agents.length > 1 ? currentAgent(state) : undefined;
|
||||
switch (state.phase) {
|
||||
@@ -55,21 +84,34 @@ export function renderHud(state: AppState, nowMs: number): HudFrame {
|
||||
}
|
||||
return { body: 'Hermeven\n\nNot connected.\nOpen Hermeven on your phone to pair.', status: 'Double-tap: exit' };
|
||||
|
||||
case 'ready':
|
||||
if (agent) {
|
||||
return {
|
||||
body: state.notice ? `${agent.name}\n\n${state.notice}.` : `${agent.name}\n\nReady.`,
|
||||
status: 'Tap: ask · Swipe: agent · 2×: exit',
|
||||
};
|
||||
case 'menu': {
|
||||
// Plain ASCII marker: the firmware font silently drops characters it does not have.
|
||||
const lines = menuItems(state).map((mode, i) => `${i === state.menuIndex ? '>' : ' '} ${MODE_LABEL[mode]}`);
|
||||
return { body: `Hermeven\n\n${lines.join('\n')}`, status: lines.length > 1 ? 'Tap: open · Swipe: move · 2×: exit' : 'Tap: open · Double-tap: exit' };
|
||||
}
|
||||
|
||||
case 'ready': {
|
||||
// With a menu, double tap goes back to it; without one it leaves the app.
|
||||
const out = state.menu ? 'menu' : 'exit';
|
||||
const status = agent ? `Tap: ask · Swipe: agent · 2×: ${out}` : `Tap: ask · Double-tap: ${out}`;
|
||||
if (state.wakeListening && !state.notice) {
|
||||
return agent
|
||||
? { body: `${agent.name}\n\nListening. Say a name, then your question:\n${callNames(state)}`, status }
|
||||
: { body: 'Hermeven\n\nListening. Say your agent’s name, then your question.', status };
|
||||
}
|
||||
return {
|
||||
body: state.notice ? `Hermeven\n\n${state.notice}.` : 'Hermeven\n\nReady.',
|
||||
status: 'Tap: ask · Double-tap: exit',
|
||||
};
|
||||
if (agent) return { body: state.notice ? `${agent.name}\n\n${state.notice}.` : `${agent.name}\n\nReady.`, status };
|
||||
return { body: state.notice ? `Hermeven\n\n${state.notice}.` : 'Hermeven\n\nReady.', status };
|
||||
}
|
||||
|
||||
case 'listening': {
|
||||
const elapsed = state.captureStartedAt === null ? 0 : (nowMs - state.captureStartedAt) / 1000;
|
||||
const cap = state.captureMaxSeconds;
|
||||
if (state.captureAuto) {
|
||||
return {
|
||||
body: `${agent ? `${agent.name} is listening…` : 'Listening…'}\n\nAsk your question. It is sent when you stop speaking.`,
|
||||
status: `● REC ${clock(elapsed)} / ${clock(cap)} · Tap: send · 2×: cancel`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
body: `${agent ? `${agent.name} is listening…` : 'Listening…'}\n\nRecording stops by itself after ${cap} seconds.`,
|
||||
status: `● REC ${clock(elapsed)} / ${clock(cap)} · Tap or release: send · 2×: cancel`,
|
||||
@@ -79,8 +121,14 @@ export function renderHud(state: AppState, nowMs: number): HudFrame {
|
||||
case 'transcribing':
|
||||
return { body: 'Transcribing…', status: 'Double-tap: cancel' };
|
||||
|
||||
case 'thinking':
|
||||
return { body: agent ? `${agent.name} is thinking…` : 'Thinking…', status: 'Double-tap: cancel' };
|
||||
case 'thinking': {
|
||||
const title = agent ? `${agent.name} is thinking…` : 'Thinking…';
|
||||
if (!state.heard) return { body: title, status: 'Double-tap: cancel' };
|
||||
// Asked by voice with nothing pressed: show what was understood, so a mishearing is seen
|
||||
// while it can still be cancelled.
|
||||
const heard = state.heard.length > HEARD_MAX ? `${state.heard.slice(0, HEARD_MAX - 1).trimEnd()}…` : state.heard;
|
||||
return { body: `${title}\n\nHeard: ${heard}`, status: 'Double-tap: cancel' };
|
||||
}
|
||||
|
||||
case 'approval':
|
||||
return {
|
||||
|
||||
@@ -10,6 +10,8 @@ import type { TurnResult } from '@hermeven/contracts';
|
||||
*/
|
||||
export type Phase =
|
||||
| 'unpaired'
|
||||
/** The opening menu: choose a mode. Nothing records and nothing is in flight. */
|
||||
| 'menu'
|
||||
| 'ready'
|
||||
| 'listening'
|
||||
| 'transcribing'
|
||||
@@ -35,8 +37,24 @@ export interface Agent {
|
||||
name: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* How the app is being used. Both modes talk to the same agents through the same path; the
|
||||
* only difference is whether the microphone listens for a name while at rest.
|
||||
* - agents: the microphone opens on a tap, and the app leaves the glasses when idle.
|
||||
* - handsfree: the microphone is open at rest, and the app stays until closed.
|
||||
*/
|
||||
export type Mode = 'agents' | 'handsfree';
|
||||
|
||||
export const MODE_LABEL: Record<Mode, string> = { handsfree: 'Hands free', agents: 'Agents' };
|
||||
|
||||
export interface AppState {
|
||||
phase: Phase;
|
||||
/** The app opens on a menu, and double tap at Ready goes back to it (instead of exiting). */
|
||||
menu: boolean;
|
||||
menuIndex: number;
|
||||
mode: Mode;
|
||||
/** Hands free can be offered: this build has it, and nothing has said the bridge cannot do it. */
|
||||
handsFree: boolean;
|
||||
/**
|
||||
* The agents the bridge offers, default first. Empty when there is only one (or the bridge
|
||||
* predates agent selection): nothing about agents is then shown or sent.
|
||||
@@ -58,6 +76,15 @@ export interface AppState {
|
||||
requestId: string | null;
|
||||
captureStartedAt: number | null;
|
||||
captureMaxSeconds: number;
|
||||
/** The recording was started by saying an agent's name: it sends itself when the speaker stops. */
|
||||
captureAuto: boolean;
|
||||
/**
|
||||
* The microphone is open at rest, listening for an agent's name. Reported by the controller
|
||||
* from what the microphone actually did, so the HUD's indicator is never a guess.
|
||||
*/
|
||||
wakeListening: boolean;
|
||||
/** The question as it was heard, when it was spoken after a name. Shown while the agent works. */
|
||||
heard: string | null;
|
||||
pages: string[];
|
||||
pageIndex: number;
|
||||
/** The answer is a partial one (agent stopped short). Shown on the HUD. */
|
||||
@@ -77,6 +104,10 @@ export interface AppState {
|
||||
|
||||
export const initialState: AppState = {
|
||||
phase: 'unpaired',
|
||||
menu: false,
|
||||
menuIndex: 0,
|
||||
mode: 'agents',
|
||||
handsFree: false,
|
||||
agents: [],
|
||||
agentId: null,
|
||||
generation: 0,
|
||||
@@ -86,6 +117,9 @@ export const initialState: AppState = {
|
||||
requestId: null,
|
||||
captureStartedAt: null,
|
||||
captureMaxSeconds: 30,
|
||||
captureAuto: false,
|
||||
wakeListening: false,
|
||||
heard: null,
|
||||
pages: [],
|
||||
pageIndex: 0,
|
||||
partial: false,
|
||||
@@ -106,7 +140,12 @@ export type AppEvent =
|
||||
storageFault?: boolean;
|
||||
agents?: Agent[];
|
||||
agentId?: string | null;
|
||||
/** Open on the menu. Without it the app opens at Ready, hands free if that is available. */
|
||||
menu?: boolean;
|
||||
handsFree?: boolean;
|
||||
}
|
||||
/** Hands free turned out not to be possible (the bridge cannot do it): fall back to Agents. */
|
||||
| { type: 'handsfree_lost' }
|
||||
/** The user picked another agent (a swipe at Ready). `conversationId` is that agent's own, if it has one. */
|
||||
| { type: 'agent_selected'; agentId: string; conversationId: string | null }
|
||||
/**
|
||||
@@ -116,6 +155,16 @@ export type AppEvent =
|
||||
*/
|
||||
| { type: 'agent_reconciled'; agentId: string; conversationId: string | null }
|
||||
| { type: 'unpaired' }
|
||||
/**
|
||||
* An agent was addressed by name and the question followed in the same breath ("Wendy, what
|
||||
* time is it"). `agentId` and `conversationId` are that agent's; null agent = no choice offered.
|
||||
*/
|
||||
| { type: 'wake_text'; freshId: string; agentId: string | null; conversationId: string | null; text: string }
|
||||
/** Only the name was said: record what follows and send it when the speaker stops. */
|
||||
| { type: 'wake_listen'; freshId: string; agentId: string | null; conversationId: string | null }
|
||||
/** A recording started by name heard nothing: back to rest, nothing sent. */
|
||||
| { type: 'capture_abandoned'; generation: number }
|
||||
| { type: 'wake_status'; listening: boolean }
|
||||
/** Semantic actions. `freshId` is a new UUID supplied by the caller in case a turn starts. */
|
||||
| { type: 'activate'; freshId: string }
|
||||
| { type: 'back' }
|
||||
@@ -140,7 +189,7 @@ export type AppEvent =
|
||||
| { type: 'app_exit' };
|
||||
|
||||
export type Effect =
|
||||
| { type: 'start_capture'; generation: number }
|
||||
| { type: 'start_capture'; generation: number; auto?: boolean }
|
||||
| { type: 'stop_capture_and_submit'; generation: number; requestId: string }
|
||||
| { type: 'discard_capture' }
|
||||
| { type: 'submit_text'; generation: number; requestId: string; text: string }
|
||||
@@ -158,6 +207,11 @@ export interface Step {
|
||||
const IDLE: ReadonlySet<Phase> = new Set(['ready', 'answer', 'error', 'cancelled']);
|
||||
const IN_FLIGHT: ReadonlySet<Phase> = new Set(['transcribing', 'thinking', 'approval']);
|
||||
|
||||
/** The menu's entries, in order. Hands free comes first whenever it can be offered. */
|
||||
export function menuItems(state: Pick<AppState, 'handsFree'>): Mode[] {
|
||||
return state.handsFree ? ['handsfree', 'agents'] : ['agents'];
|
||||
}
|
||||
|
||||
/** The agent questions go to now, or undefined when the bridge offers no choice. */
|
||||
export function currentAgent(state: AppState): Agent | undefined {
|
||||
if (state.agents.length === 0) return undefined;
|
||||
@@ -169,6 +223,8 @@ function clearTurn(state: AppState): AppState {
|
||||
...state,
|
||||
requestId: null,
|
||||
captureStartedAt: null,
|
||||
captureAuto: false,
|
||||
heard: null,
|
||||
pages: [],
|
||||
pageIndex: 0,
|
||||
partial: false,
|
||||
@@ -183,6 +239,24 @@ function same(state: AppState): Step {
|
||||
return { state, effects: [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn to the agent that was addressed by name, with its own conversation. Null when that
|
||||
* agent is not one on offer. A change of agent or conversation starts a new conversation epoch,
|
||||
* so a conversation still being created for the previous one cannot land here.
|
||||
*/
|
||||
function address(state: AppState, agentId: string | null, conversationId: string | null): AppState | null {
|
||||
if (state.agents.length > 0 && agentId !== null && !state.agents.some((a) => a.id === agentId)) return null;
|
||||
const sameAgent = state.agents.length === 0 || agentId === null || agentId === currentAgent(state)?.id;
|
||||
if (sameAgent && conversationId === state.conversationId) return state;
|
||||
return {
|
||||
...state,
|
||||
agentId: sameAgent ? state.agentId : agentId,
|
||||
conversationId,
|
||||
conversationEpoch: state.conversationEpoch + 1,
|
||||
creatingConversation: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** Abandon whatever is in progress. The generation bump is what silences late results. */
|
||||
function abandon(state: AppState): Step {
|
||||
const effects: Effect[] = [];
|
||||
@@ -209,6 +283,10 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
storageFault: event.storageFault === true,
|
||||
agents: event.agents ?? [],
|
||||
agentId: event.agentId ?? null,
|
||||
menu: event.menu === true,
|
||||
handsFree: event.handsFree === true,
|
||||
// With a menu, hands free is something the user chooses. Without one it is simply on.
|
||||
mode: event.menu !== true && event.handsFree === true ? 'handsfree' : 'agents',
|
||||
};
|
||||
if (!event.paired) return same({ ...base, phase: 'unpaired' });
|
||||
if (event.resumeRequestId) {
|
||||
@@ -219,7 +297,20 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
effects: [{ type: 'poll', generation: base.generation, requestId: event.resumeRequestId }],
|
||||
};
|
||||
}
|
||||
return same({ ...base, phase: 'ready' });
|
||||
return same({ ...base, phase: base.menu ? 'menu' : 'ready' });
|
||||
}
|
||||
|
||||
case 'handsfree_lost': {
|
||||
if (!state.handsFree) return same(state);
|
||||
const wasOn = state.mode === 'handsfree';
|
||||
return same({
|
||||
...state,
|
||||
handsFree: false,
|
||||
mode: 'agents',
|
||||
menuIndex: 0,
|
||||
wakeListening: false,
|
||||
notice: wasOn && state.phase === 'ready' ? 'Hands free is not available' : state.notice,
|
||||
});
|
||||
}
|
||||
|
||||
case 'agent_selected': {
|
||||
@@ -264,7 +355,44 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
};
|
||||
}
|
||||
|
||||
case 'wake_text': {
|
||||
if (!IDLE.has(state.phase)) return same(state);
|
||||
const addressed = address(state, event.agentId, event.conversationId);
|
||||
if (!addressed) return same(state);
|
||||
const generation = state.generation + 1;
|
||||
return {
|
||||
state: { ...clearTurn(addressed), phase: 'thinking', generation, requestId: event.freshId, heard: event.text },
|
||||
effects: [{ type: 'submit_text', generation, requestId: event.freshId, text: event.text }],
|
||||
};
|
||||
}
|
||||
|
||||
case 'wake_listen': {
|
||||
if (!IDLE.has(state.phase)) return same(state);
|
||||
const addressed = address(state, event.agentId, event.conversationId);
|
||||
if (!addressed) return same(state);
|
||||
const generation = state.generation + 1;
|
||||
return {
|
||||
state: { ...clearTurn(addressed), phase: 'listening', generation, requestId: event.freshId, captureAuto: true },
|
||||
effects: [{ type: 'start_capture', generation, auto: true }],
|
||||
};
|
||||
}
|
||||
|
||||
case 'capture_abandoned': {
|
||||
if (event.generation !== state.generation || state.phase !== 'listening') return same(state);
|
||||
return {
|
||||
state: { ...clearTurn(state), phase: 'ready', generation: state.generation + 1 },
|
||||
effects: [{ type: 'discard_capture' }],
|
||||
};
|
||||
}
|
||||
|
||||
case 'wake_status':
|
||||
return same(event.listening === state.wakeListening ? state : { ...state, wakeListening: event.listening });
|
||||
|
||||
case 'activate': {
|
||||
if (state.phase === 'menu') {
|
||||
const mode = menuItems(state)[state.menuIndex] ?? 'agents';
|
||||
return same({ ...clearTurn(state), phase: 'ready', mode, generation: state.generation + 1 });
|
||||
}
|
||||
if (IDLE.has(state.phase)) {
|
||||
const generation = state.generation + 1;
|
||||
return {
|
||||
@@ -297,7 +425,8 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
}
|
||||
|
||||
case 'submit_text': {
|
||||
if (!IDLE.has(state.phase)) return same(state);
|
||||
// Typed on the phone. Also accepted on the menu: it does not need a mode.
|
||||
if (!IDLE.has(state.phase) && state.phase !== 'menu') return same(state);
|
||||
const generation = state.generation + 1;
|
||||
return {
|
||||
state: { ...clearTurn(state), phase: 'thinking', generation, requestId: event.freshId },
|
||||
@@ -306,7 +435,11 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
}
|
||||
|
||||
case 'back': {
|
||||
if (state.phase === 'ready' || state.phase === 'unpaired') return { state, effects: [{ type: 'exit_dialog' }] };
|
||||
if (state.phase === 'ready' && state.menu) {
|
||||
// Leaving a mode. Hands free ends here: the microphone closes with it.
|
||||
return same({ ...clearTurn(state), phase: 'menu', mode: 'agents', menuIndex: 0, generation: state.generation + 1 });
|
||||
}
|
||||
if (state.phase === 'ready' || state.phase === 'unpaired' || state.phase === 'menu') return { state, effects: [{ type: 'exit_dialog' }] };
|
||||
if (state.phase === 'listening' || IN_FLIGHT.has(state.phase) || state.phase === 'disconnected') return abandon(state);
|
||||
// answer / error / cancelled: step back to the root page.
|
||||
return same({ ...clearTurn(state), phase: 'ready' });
|
||||
@@ -319,8 +452,12 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
|
||||
case 'next_page':
|
||||
case 'prev_page': {
|
||||
if (state.phase !== 'answer') return same(state);
|
||||
const delta = event.type === 'next_page' ? 1 : -1;
|
||||
if (state.phase === 'menu') {
|
||||
const menuIndex = Math.min(menuItems(state).length - 1, Math.max(0, state.menuIndex + delta));
|
||||
return same(menuIndex === state.menuIndex ? state : { ...state, menuIndex });
|
||||
}
|
||||
if (state.phase !== 'answer') return same(state);
|
||||
const pageIndex = Math.min(state.pages.length - 1, Math.max(0, state.pageIndex + delta));
|
||||
return same(pageIndex === state.pageIndex ? state : { ...state, pageIndex });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* Finds stretches of speech in a continuous microphone stream, by loudness alone.
|
||||
*
|
||||
* Pure: no clock (time is counted in samples), no I/O. It is not a speech recogniser and does
|
||||
* not know words; it only decides "someone started talking" and "they stopped", so that the
|
||||
* app can send one utterance at a time instead of a never-ending stream.
|
||||
*
|
||||
* Audio is 16 kHz signed 16-bit little-endian mono (the only format the app handles). It is
|
||||
* examined in 20 ms windows. A window is "voiced" when its level is clearly above the
|
||||
* background, which is tracked continuously while nobody is speaking.
|
||||
*
|
||||
* NOT device-tested: the thresholds are first guesses for a microphone whose levels have not
|
||||
* been measured (see docs/device-test-plan.md).
|
||||
*/
|
||||
export interface SegmenterOptions {
|
||||
/** A pause this long ends the utterance. */
|
||||
endSilenceMs: number;
|
||||
/** Less voiced sound than this in total is a click or a cough, not an utterance. */
|
||||
minSpeechMs: number;
|
||||
/** Audio kept from just before speech was detected, so the first syllable is not clipped. */
|
||||
prerollMs: number;
|
||||
/** An utterance is cut off (and still delivered) at this length. */
|
||||
maxMs: number;
|
||||
/** A window is never voiced below this RMS level (full scale is 32768). */
|
||||
minRms: number;
|
||||
/** A window is voiced when its level is at least this many times the background level. */
|
||||
ratio: number;
|
||||
}
|
||||
|
||||
export const WAKE_SEGMENTER: SegmenterOptions = {
|
||||
endSilenceMs: 700,
|
||||
minSpeechMs: 240,
|
||||
prerollMs: 400,
|
||||
maxMs: 30_000,
|
||||
minRms: 260,
|
||||
ratio: 3,
|
||||
};
|
||||
|
||||
export type SegmentEvent =
|
||||
| { type: 'start' }
|
||||
/** The utterance, from the preroll to the end of the closing pause. */
|
||||
| { type: 'end'; pcm: Uint8Array }
|
||||
/** What looked like speech was too short to be an utterance. */
|
||||
| { type: 'discard' };
|
||||
|
||||
const WINDOW_BYTES = 640; // 20 ms
|
||||
const WINDOW_MS = 20;
|
||||
/** This many voiced windows in a row start an utterance. */
|
||||
const ONSET_WINDOWS = 3;
|
||||
|
||||
export class SpeechSegmenter {
|
||||
private options: SegmenterOptions;
|
||||
/** Bytes that do not yet fill a window. */
|
||||
private carry = new Uint8Array(0);
|
||||
/** Recent windows while nobody is speaking: the preroll. */
|
||||
private recent: Uint8Array[] = [];
|
||||
/** Windows of the utterance in progress. */
|
||||
private speech: Uint8Array[] | null = null;
|
||||
private voicedRun = 0;
|
||||
private voicedWindows = 0;
|
||||
private silentRun = 0;
|
||||
private levelSum = 0;
|
||||
/** Background level, learned while nobody is speaking. */
|
||||
private floor = 0;
|
||||
|
||||
constructor(options: SegmenterOptions = WAKE_SEGMENTER) {
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
/** Someone is talking right now (an utterance has started and not yet ended). */
|
||||
get speaking(): boolean {
|
||||
return this.speech !== null;
|
||||
}
|
||||
|
||||
/** Change the timing rules from the next window on, without losing what has been heard. */
|
||||
configure(options: SegmenterOptions): void {
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
/** Forget everything heard so far, keeping what was learned about the background level. */
|
||||
reset(): void {
|
||||
this.carry = new Uint8Array(0);
|
||||
this.recent = [];
|
||||
this.speech = null;
|
||||
this.voicedRun = 0;
|
||||
this.voicedWindows = 0;
|
||||
this.silentRun = 0;
|
||||
this.levelSum = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything currently held: the utterance in progress, or else the preroll. Used when a
|
||||
* recording takes over from listening, so that what was already being said is not lost.
|
||||
*/
|
||||
buffered(): Uint8Array {
|
||||
return concat(this.speech ?? this.recent);
|
||||
}
|
||||
|
||||
push(pcm: Uint8Array): SegmentEvent[] {
|
||||
const events: SegmentEvent[] = [];
|
||||
let data = pcm;
|
||||
if (this.carry.length) {
|
||||
data = new Uint8Array(this.carry.length + pcm.length);
|
||||
data.set(this.carry);
|
||||
data.set(pcm, this.carry.length);
|
||||
}
|
||||
let offset = 0;
|
||||
for (; offset + WINDOW_BYTES <= data.length; offset += WINDOW_BYTES) {
|
||||
this.window(data.slice(offset, offset + WINDOW_BYTES), events);
|
||||
}
|
||||
this.carry = data.slice(offset);
|
||||
return events;
|
||||
}
|
||||
|
||||
private window(win: Uint8Array, events: SegmentEvent[]): void {
|
||||
const level = rms(win);
|
||||
const voiced = level >= Math.max(this.options.minRms, this.floor * this.options.ratio);
|
||||
|
||||
if (!this.speech) {
|
||||
this.recent.push(win);
|
||||
const keep = Math.max(ONSET_WINDOWS, Math.ceil(this.options.prerollMs / WINDOW_MS));
|
||||
if (this.recent.length > keep) this.recent.shift();
|
||||
if (!voiced) {
|
||||
this.voicedRun = 0;
|
||||
// Follows a quieter room at once and a louder one slowly.
|
||||
this.floor = this.floor === 0 || level < this.floor ? level : this.floor * 0.98 + level * 0.02;
|
||||
return;
|
||||
}
|
||||
this.voicedRun += 1;
|
||||
if (this.voicedRun < ONSET_WINDOWS) return;
|
||||
this.speech = this.recent;
|
||||
this.recent = [];
|
||||
this.voicedWindows = this.voicedRun;
|
||||
this.voicedRun = 0;
|
||||
this.silentRun = 0;
|
||||
this.levelSum = 0;
|
||||
events.push({ type: 'start' });
|
||||
return;
|
||||
}
|
||||
|
||||
this.speech.push(win);
|
||||
this.levelSum += level;
|
||||
if (voiced) {
|
||||
this.voicedWindows += 1;
|
||||
this.silentRun = 0;
|
||||
} else {
|
||||
this.silentRun += 1;
|
||||
}
|
||||
const paused = this.silentRun * WINDOW_MS >= this.options.endSilenceMs;
|
||||
const tooLong = this.speech.length * WINDOW_MS >= this.options.maxMs;
|
||||
if (!paused && !tooLong) return;
|
||||
|
||||
const speech = this.speech;
|
||||
const enough = this.voicedWindows * WINDOW_MS >= this.options.minSpeechMs;
|
||||
if (tooLong && !paused) {
|
||||
// Never a pause in all that time: this is a steady noise, not a voice. Treat its level as
|
||||
// the new background so the next thing delivered is something that stands out from it.
|
||||
this.floor = this.levelSum / speech.length;
|
||||
}
|
||||
this.speech = null;
|
||||
this.voicedWindows = 0;
|
||||
this.silentRun = 0;
|
||||
events.push(enough ? { type: 'end', pcm: concat(speech) } : { type: 'discard' });
|
||||
}
|
||||
}
|
||||
|
||||
function rms(win: Uint8Array): number {
|
||||
let sum = 0;
|
||||
const samples = win.length >> 1;
|
||||
for (let i = 0; i < samples; i++) {
|
||||
let v = win[2 * i]! | (win[2 * i + 1]! << 8);
|
||||
if (v & 0x8000) v -= 0x10000;
|
||||
sum += v * v;
|
||||
}
|
||||
return Math.sqrt(sum / samples);
|
||||
}
|
||||
|
||||
function concat(chunks: Uint8Array[]): Uint8Array {
|
||||
let total = 0;
|
||||
for (const chunk of chunks) total += chunk.length;
|
||||
const out = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
out.set(chunk, offset);
|
||||
offset += chunk.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -21,6 +21,10 @@ const { controller } = await boot(document, window, {
|
||||
// Development only, for automated simulator runs: `?idleExit=off` keeps the app open and
|
||||
// `?idleExit=fast` shortens the waits. Production builds always use the defaults.
|
||||
idleExit: devIdleExit(),
|
||||
// Development only, for automated simulator runs: `?wake=off` removes hands-free mode and
|
||||
// `?menu=off` opens at Ready instead of on the menu.
|
||||
wake: !(import.meta.env.DEV && new URLSearchParams(location.search).get('wake') === 'off'),
|
||||
menu: !(import.meta.env.DEV && new URLSearchParams(location.search).get('menu') === 'off'),
|
||||
});
|
||||
|
||||
// Development-only convenience for automated simulator runs, where nothing can type into the
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
RevokeResponse,
|
||||
SCHEMA_VERSION,
|
||||
TurnResult,
|
||||
WakeResponse,
|
||||
type ErrorBody,
|
||||
} from '@hermeven/contracts';
|
||||
import type { TSchema } from '@sinclair/typebox';
|
||||
@@ -175,6 +176,21 @@ export class BridgeClient {
|
||||
return this.call(TurnResult, 'POST', `/v1/turns?${query}`, { binary: args.pcm }) as Promise<TurnResult>;
|
||||
}
|
||||
|
||||
/**
|
||||
* One stretch of speech heard while listening: did it begin with an agent's name? Creates
|
||||
* nothing on the bridge. A bridge without wake names answers `not_found`.
|
||||
*/
|
||||
wake(args: { locale: string; pcm: Uint8Array }): Promise<WakeResponse> {
|
||||
const query = new URLSearchParams({
|
||||
schema_version: String(SCHEMA_VERSION),
|
||||
locale: args.locale,
|
||||
encoding: AUDIO_FORMAT.encoding,
|
||||
sample_rate: String(AUDIO_FORMAT.sampleRate),
|
||||
channels: String(AUDIO_FORMAT.channels),
|
||||
});
|
||||
return this.call(WakeResponse, 'POST', `/v1/wake?${query}`, { binary: args.pcm });
|
||||
}
|
||||
|
||||
getTurn(requestId: string): Promise<TurnResult> {
|
||||
return this.call(TurnResult, 'GET', `/v1/turns/${requestId}`) as Promise<TurnResult>;
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ function explain(err: unknown): string {
|
||||
|
||||
const PHASE_LABEL: Record<string, string> = {
|
||||
unpaired: 'Not paired',
|
||||
menu: 'Menu (choose a mode on the glasses)',
|
||||
ready: 'Ready',
|
||||
listening: 'Listening (microphone open)',
|
||||
transcribing: 'Transcribing',
|
||||
@@ -163,8 +164,13 @@ export function mountPhoneUi(root: HTMLElement, controller: Controller, defaults
|
||||
|
||||
phase.textContent = PHASE_LABEL[s.state.phase] ?? s.state.phase;
|
||||
captureNote.textContent =
|
||||
`Recording starts only when you tap the glasses, shows “● REC” for as long as the microphone is open, ` +
|
||||
`and stops by itself after ${s.state.captureMaxSeconds} seconds.`;
|
||||
s.wake.enabled
|
||||
? `Hands free: the glasses’ microphone is open whenever the app is at rest (the status line starts with “●”). ` +
|
||||
`Each stretch of speech goes to your bridge, which keeps it only if it begins with an agent’s name. ` +
|
||||
`Say a name and then your question, or tap to ask. Double tap at Ready goes back to the menu and closes the microphone. ` +
|
||||
(s.wake.listening ? 'Listening now.' : 'Not listening at the moment.')
|
||||
: `Recording starts only when you tap the glasses, shows “● REC” for as long as the microphone is open, ` +
|
||||
`and stops by itself after ${s.state.captureMaxSeconds} seconds.`;
|
||||
const inFlight = ['listening', 'transcribing', 'thinking', 'approval', 'disconnected'].includes(s.state.phase);
|
||||
askButton.disabled = inFlight;
|
||||
newButton.disabled = inFlight;
|
||||
|
||||
@@ -151,13 +151,14 @@ describe('plain text', () => {
|
||||
});
|
||||
|
||||
describe('HUD frames', () => {
|
||||
const phases: Phase[] = ['unpaired', 'ready', 'listening', 'transcribing', 'thinking', 'approval', 'answer', 'error', 'disconnected', 'cancelled'];
|
||||
const phases: Phase[] = ['unpaired', 'menu', 'ready', 'listening', 'transcribing', 'thinking', 'approval', 'answer', 'error', 'disconnected', 'cancelled'];
|
||||
const variants = (phase: Phase): AppState[] => {
|
||||
const base: AppState = { ...initialState, phase, captureStartedAt: 0, captureMaxSeconds: 120 };
|
||||
if (phase === 'answer') {
|
||||
return [
|
||||
{ ...base, pages: ['x'], pageIndex: 0 },
|
||||
{ ...base, pages: Array(99).fill('x'), pageIndex: 98, partial: true },
|
||||
{ ...base, pages: Array(99).fill('x'), pageIndex: 98, partial: true, wakeListening: true, agents: [{ id: 'default', name: 'Pepper' }, { id: 'natalie', name: 'Natalie' }], agentId: 'natalie' },
|
||||
];
|
||||
}
|
||||
if (phase === 'disconnected') {
|
||||
@@ -172,9 +173,24 @@ describe('HUD frames', () => {
|
||||
return [
|
||||
{ ...base, error: { code: 'outcome_unknown', hud: 'The outcome is unknown. Check the agent before asking again.', retryable: false } },
|
||||
{ ...base, error: { code: 'agent_timeout', hud: 'The agent ran out of time and was stopped. Actions it had already taken are not undone.', retryable: true } },
|
||||
{ ...base, wakeListening: true, error: { code: 'agent_timeout', hud: 'The agent ran out of time and was stopped.', retryable: true } },
|
||||
];
|
||||
}
|
||||
if (phase === 'ready') return [base, { ...base, notice: 'New conversation' }];
|
||||
// Listening for a name: sixteen agents with the longest names allowed, and none.
|
||||
const many = Array.from({ length: 16 }, (_, i) => ({ id: `a${i}`, name: 'Wwwwwwwwwwwwwwwwwwwwwwww' }));
|
||||
const few = [
|
||||
{ id: 'default', name: 'Pepper' },
|
||||
{ id: 'wendy', name: 'Wendy' },
|
||||
{ id: 'cody', name: 'Cody' },
|
||||
];
|
||||
const wake = { wakeListening: true };
|
||||
if (phase === 'menu') return [base, { ...base, handsFree: true }, { ...base, handsFree: true, menuIndex: 1 }];
|
||||
if (phase === 'ready') {
|
||||
return [{ ...base, menu: true }, { ...base, menu: true, ...wake, agents: few }, base, { ...base, notice: 'New conversation' }, { ...base, ...wake }, { ...base, ...wake, agents: few }, { ...base, ...wake, agents: many }, { ...base, ...wake, agents: few, notice: 'New conversation' }];
|
||||
}
|
||||
if (phase === 'listening') return [base, { ...base, captureAuto: true }, { ...base, captureAuto: true, agents: few }];
|
||||
if (phase === 'thinking') return [base, { ...base, heard: 'W'.repeat(4000) }, { ...base, agents: few, heard: 'What is on my calendar tomorrow?' }];
|
||||
if (phase === 'cancelled') return [base, { ...base, ...wake }];
|
||||
if (phase === 'unpaired') return [base, { ...base, storageFault: true }];
|
||||
return [base];
|
||||
};
|
||||
@@ -201,6 +217,20 @@ describe('HUD frames', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('an open microphone at rest is always marked, and never claimed while it is closed', () => {
|
||||
for (const phase of ['ready', 'answer', 'error', 'cancelled'] as Phase[]) {
|
||||
const state: AppState = { ...initialState, phase, pages: ['x'] };
|
||||
expect(renderHud({ ...state, wakeListening: true }, 0).status.startsWith('● ')).toBe(true);
|
||||
expect(renderHud(state, 0).status).not.toContain('●');
|
||||
}
|
||||
// In flight the microphone is closed, whatever the flag last said.
|
||||
for (const phase of ['transcribing', 'thinking', 'approval', 'disconnected', 'unpaired'] as Phase[]) {
|
||||
expect(renderHud({ ...initialState, phase, wakeListening: true }, 0).status).not.toContain('●');
|
||||
}
|
||||
const ready = renderHud({ ...initialState, phase: 'ready', wakeListening: true, agents: [{ id: 'default', name: 'Pepper' }, { id: 'wendy', name: 'Wendy' }] }, 0);
|
||||
expect(ready.body).toBe('Pepper\n\nListening. Say a name, then your question:\nPepper · Wendy');
|
||||
});
|
||||
|
||||
it('errors offer a recovery action and send detail to the phone', () => {
|
||||
const frame = renderHud({ ...initialState, phase: 'error', error: { code: 'stt_empty', hud: 'No speech was recognised.', retryable: true } }, 0);
|
||||
expect(frame.body).toContain('No speech was recognised.');
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { SpeechSegmenter, WAKE_SEGMENTER, type SegmentEvent } from '../src/core/vad.ts';
|
||||
|
||||
/** Synthetic audio: a tone stands in for a voice, low noise for a room. Not speech. */
|
||||
function tone(ms: number, amplitude = 6000): Uint8Array {
|
||||
const samples = (ms * 16000) / 1000;
|
||||
const out = new Uint8Array(samples * 2);
|
||||
for (let i = 0; i < samples; i++) {
|
||||
const v = Math.round(Math.sin((2 * Math.PI * 300 * i) / 16000) * amplitude) & 0xffff;
|
||||
out[2 * i] = v & 0xff;
|
||||
out[2 * i + 1] = v >> 8;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const room = (ms: number, amplitude = 40) => tone(ms, amplitude);
|
||||
|
||||
function feed(segmenter: SpeechSegmenter, ...clips: Uint8Array[]): SegmentEvent[] {
|
||||
const events: SegmentEvent[] = [];
|
||||
for (const clip of clips) {
|
||||
// In 100 ms frames, as the glasses deliver them.
|
||||
for (let offset = 0; offset < clip.length; offset += 3200) events.push(...segmenter.push(clip.subarray(offset, offset + 3200)));
|
||||
}
|
||||
return events;
|
||||
}
|
||||
const ms = (pcm: Uint8Array) => pcm.length / 32;
|
||||
|
||||
describe('speech segmenter', () => {
|
||||
it('silence and steady room noise produce nothing', () => {
|
||||
const segmenter = new SpeechSegmenter();
|
||||
expect(feed(segmenter, new Uint8Array(32000 * 5), room(5000))).toEqual([]);
|
||||
expect(segmenter.speaking).toBe(false);
|
||||
});
|
||||
|
||||
it('delivers one utterance, with its lead-in, once the speaker pauses', () => {
|
||||
const segmenter = new SpeechSegmenter();
|
||||
const events = feed(segmenter, room(1000), tone(1500), room(1000));
|
||||
expect(events.map((e) => e.type)).toEqual(['start', 'end']);
|
||||
const end = events[1] as Extract<SegmentEvent, { type: 'end' }>;
|
||||
// Speech, the preroll before it and the closing pause; not the whole second of lead-in.
|
||||
expect(ms(end.pcm)).toBeGreaterThanOrEqual(1500 + WAKE_SEGMENTER.endSilenceMs);
|
||||
expect(ms(end.pcm)).toBeLessThanOrEqual(1500 + WAKE_SEGMENTER.endSilenceMs + WAKE_SEGMENTER.prerollMs + 60);
|
||||
expect(end.pcm.length % 2).toBe(0);
|
||||
expect(segmenter.speaking).toBe(false);
|
||||
});
|
||||
|
||||
it('a short pause inside a sentence does not split it; a long one does', () => {
|
||||
const segmenter = new SpeechSegmenter();
|
||||
const one = feed(segmenter, room(500), tone(600), room(300), tone(600), room(1000));
|
||||
expect(one.map((e) => e.type)).toEqual(['start', 'end']);
|
||||
const two = feed(segmenter, tone(600), room(900), tone(600), room(900));
|
||||
expect(two.map((e) => e.type)).toEqual(['start', 'end', 'start', 'end']);
|
||||
});
|
||||
|
||||
it('a click is discarded, not delivered', () => {
|
||||
const segmenter = new SpeechSegmenter();
|
||||
expect(feed(segmenter, room(500), tone(100), room(1000)).map((e) => e.type)).toEqual(['start', 'discard']);
|
||||
});
|
||||
|
||||
it('frames of any size give the same result', () => {
|
||||
const clip = new Uint8Array([...room(600), ...tone(900), ...room(900)]);
|
||||
const a = new SpeechSegmenter();
|
||||
const b = new SpeechSegmenter();
|
||||
const whole = a.push(clip);
|
||||
const pieces: SegmentEvent[] = [];
|
||||
for (let offset = 0; offset < clip.length; offset += 1001) pieces.push(...b.push(clip.subarray(offset, offset + 1001)));
|
||||
expect(pieces).toEqual(whole);
|
||||
});
|
||||
|
||||
it('a noise that never pauses is cut at the limit and then becomes the background', () => {
|
||||
const segmenter = new SpeechSegmenter({ ...WAKE_SEGMENTER, maxMs: 3000 });
|
||||
const events = feed(segmenter, room(500), tone(10_000, 3000));
|
||||
expect(events.filter((e) => e.type === 'end')).toHaveLength(1);
|
||||
// Something clearly louder than that noise is still heard as speech.
|
||||
expect(feed(segmenter, tone(1000, 20_000), tone(1000, 3000)).map((e) => e.type)).toEqual(['start', 'end']);
|
||||
});
|
||||
|
||||
it('adapts to a louder room: steady noise above the minimum level stops counting as speech', () => {
|
||||
const segmenter = new SpeechSegmenter({ ...WAKE_SEGMENTER, maxMs: 2000 });
|
||||
feed(segmenter, room(4000, 600));
|
||||
expect(feed(segmenter, room(4000, 600))).toEqual([]);
|
||||
});
|
||||
|
||||
it('hands over what it is holding, and can be retimed without losing it', () => {
|
||||
const segmenter = new SpeechSegmenter();
|
||||
feed(segmenter, room(1000), tone(800));
|
||||
expect(segmenter.speaking).toBe(true);
|
||||
expect(ms(segmenter.buffered())).toBeGreaterThanOrEqual(800);
|
||||
segmenter.configure({ ...WAKE_SEGMENTER, endSilenceMs: 1200 });
|
||||
expect(feed(segmenter, room(1000))).toEqual([]);
|
||||
expect(feed(segmenter, room(300)).map((e) => e.type)).toEqual(['end']);
|
||||
segmenter.reset();
|
||||
expect(segmenter.buffered().length).toBe(0);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user