Leave the glasses when idle; new conversation after a long silence (0.1.1)

On a real G2 the app, while open, occupied the display indefinitely and a
phone notification did not reach the lenses. The app now leaves the glasses
by itself (shutDownPageContainer(0), no dialog) after a resting screen has
been untouched: 20 s on an answer, 30 s at Ready, 10 s on an error or
"Cancelled". Any gesture restarts the countdown. It never leaves while
recording, transcribing, waiting for the agent or for an approval.

It is armed only once the glasses are in use (a gesture arrived, or the
session was opened from the glasses, which includes voice launch), and
touching the phone page holds it open for two minutes, so setting up on the
phone is not interrupted.

Because the app now closes between questions, a question more than ten
minutes after the last one starts a new conversation; sooner continues it.

Diagnostics shows how the session was opened. Version 0.1.1.

Tests: 233 unit/integration; simulator 7. Not reviewed, not deployed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Dan
2026-11-21 14:12:58 -08:00
co-authored by Claude Fable 5.2
parent 38883b38f8
commit cf2cf66a35
12 changed files with 331 additions and 2 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
"package_id": "xylo.hermeven",
"edition": "202601",
"name": "Pepper",
"version": "0.1.0",
"version": "0.1.1",
"min_sdk_version": "0.0.16",
"entrypoint": "index.html",
"permissions": [
+9
View File
@@ -29,6 +29,8 @@ export interface BootOptions {
hostWaitMs?: number;
/** Development build: mirror diagnostics to the console. */
dev?: boolean;
/** `false` keeps the app on the glasses indefinitely (automated simulator runs). */
idleExit?: boolean;
/** Reload hook, replaceable in tests. */
reload?: () => void;
}
@@ -90,6 +92,7 @@ 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),
...(options.idleExit === false ? { idleExit: null } : {}),
// Development builds mirror diagnostics to the console (visible in the simulator and the
// Even dev console). Diagnostics never contain questions, answers or credentials.
onNote: options.dev ? (entry) => console.info(`[hermeven] ${entry.kind}: ${entry.detail}`) : undefined,
@@ -98,6 +101,12 @@ export async function boot(doc: Document, win: Window, options: BootOptions = {}
// The real page is on screen: the start-up status has done its job.
startup?.remove();
// Touching or typing on the phone page means someone is using it: Pepper does not leave the
// glasses (which also closes this page) while that is going on.
for (const type of ['pointerdown', 'keydown', 'input'] as const) {
doc.addEventListener(type, () => controller.notePhoneActivity(), { passive: true });
}
// Never leave the microphone open behind a page that is going away.
win.addEventListener('beforeunload', () => void controller.stop());
+120
View File
@@ -24,6 +24,8 @@ interface Stored {
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;
}
export interface DiagEntry {
@@ -41,6 +43,8 @@ export interface Snapshot {
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. */
@@ -48,6 +52,17 @@ export interface Snapshot {
log: DiagEntry[];
}
export interface IdleExitMs {
/** An answer is on screen and has not been touched. Paging or any gesture restarts it. */
answer: number | null;
/** Ready and waiting for a question. */
ready: number | null;
/** An error or "Cancelled" message is on screen. */
message: number | null;
}
export const DEFAULT_IDLE_EXIT_MS: IdleExitMs = { answer: 20_000, ready: 30_000, message: 10_000 };
export interface ControllerOptions {
device: DevicePort;
measure: MeasureLines;
@@ -66,6 +81,15 @@ export interface ControllerOptions {
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;
}
interface Capture {
@@ -110,6 +134,19 @@ export class Controller {
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;
/**
* Leaving by ourselves is only armed once the glasses are actually being used: a gesture has
* arrived, or the session was opened from the glasses. A page opened from the phone to set
* things up is never closed under the user's fingers.
*/
private idleArmed = false;
private phoneBusyUntil = 0;
private launchSource: 'appMenu' | 'glassesMenu' | 'unknown' = 'unknown';
private exited = false;
/** Set while a long press that STARTED a recording is still held down. */
private heldPress: { generation: number; at: number } | null = null;
@@ -122,6 +159,9 @@ export class Controller {
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;
}
// ------------------------------------------------------------------ public
@@ -131,6 +171,18 @@ export class Controller {
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');
@@ -139,6 +191,14 @@ export class Controller {
// 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}`);
// Opened from the glasses (their menu, or by voice): the glasses are in use.
if (source === 'glassesMenu') this.idleArmed = true;
this.scheduleIdleExit();
this.emit();
}) ?? (() => undefined),
this.device.onConnection((connected) => {
this.note('glasses', connected ? 'connected' : 'disconnected');
this.dispatch({ type: 'glasses_status', connected });
@@ -178,6 +238,8 @@ export class Controller {
async stop(): Promise<void> {
this.stopped = true;
for (const off of this.unsubscribers.splice(0)) off();
if (this.idleTimer) clearTimeout(this.idleTimer);
this.idleTimer = null;
this.stopTicker();
await this.closeMic();
}
@@ -192,6 +254,7 @@ export class Controller {
pairingExpiresAt: this.stored?.pairingExpiresAt ?? '',
status: this.status,
hudReady: this.hudReady,
launchSource: this.launchSource,
glassesInput: this.device.inputSummary?.() ?? '',
lastTurn: this.lastTurn,
log: [...this.log],
@@ -302,6 +365,53 @@ export class Controller {
for (const effect of step.effects) void this.run(effect);
this.render();
this.emit();
this.scheduleIdleExit();
}
/** The phone page is being used (touch or key): do not leave under the user's fingers. */
notePhoneActivity(): void {
this.phoneBusyUntil = this.now() + this.phoneGraceMs;
this.scheduleIdleExit();
}
/**
* (Re)start the countdown to leaving the glasses. Called after every state change and every
* gesture, so any activity restarts it. It only runs on a resting screen: never while
* recording, transcribing, waiting for the agent or for an approval, or while disconnected
* with a request outstanding.
*/
private scheduleIdleExit(): void {
if (this.idleTimer) clearTimeout(this.idleTimer);
this.idleTimer = null;
if (this.stopped || this.exited || !this.idleExitMs || !this.idleArmed || !this.hudReady) return;
const phase = this.state.phase;
const wait =
phase === 'answer'
? this.idleExitMs.answer
: phase === 'ready'
? this.idleExitMs.ready
: phase === 'error' || phase === 'cancelled'
? this.idleExitMs.message
: null;
if (wait === null) return;
const delay = 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();
void this.leaveGlasses(`idle on ${phase}`);
}, delay);
}
private async leaveGlasses(reason: string): Promise<void> {
if (this.exited) return;
this.exited = true;
this.note('lifecycle', `leaving the glasses: ${reason}`);
this.emit();
await this.closeMic();
await this.device.exitNow();
}
// ----------------------------------------------------------------- effects
@@ -572,6 +682,7 @@ export class Controller {
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',
@@ -642,6 +753,14 @@ export class Controller {
// ------------------------------------------------------------------ device
private onDeviceEvent(event: DeviceEvent): void {
if (event.type !== 'audio') {
// Any gesture from the glasses means they are in use, and restarts the idle countdown
// even when it changes no state (paging past the last page, for example).
if (event.type !== 'foreground_enter' && event.type !== 'foreground_exit' && event.type !== 'system_exit' && event.type !== 'abnormal_exit') {
this.idleArmed = true;
}
this.scheduleIdleExit();
}
switch (event.type) {
case 'audio':
return this.onAudio(event.pcm);
@@ -794,6 +913,7 @@ export class Controller {
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,
};
} catch {
return null;
@@ -234,6 +234,15 @@ export class EvenDevice implements DevicePort {
await this.enqueue(() => this.bridge.shutDownPageContainer(1), false);
}
async exitNow(): Promise<void> {
// Mode 0: leave immediately. The Even app then closes the phone-side page too.
await this.enqueue(() => this.bridge.shutDownPageContainer(0), false);
}
onLaunchSource(listener: (source: 'appMenu' | 'glassesMenu') => void): () => void {
return this.bridge.onLaunchSource((source) => listener(source));
}
async storageGet(key: string): Promise<StorageRead> {
const read = await this.enqueueBounded<string | null>(() => this.bridge.getLocalStorage(key), null);
// A timeout or a host error is "unknown", not "empty": the caller must not conclude that
+8
View File
@@ -16,6 +16,14 @@ export interface DevicePort {
onConnection(listener: (connected: boolean) => void): () => void;
/** Ask the OS to show its own exit confirmation. */
requestExit(): Promise<void>;
/**
* Leave the glasses now, with no confirmation, returning them to their normal screen. Used
* when the app has been idle: while it is open it occupies the display and (seen on a real
* G2) phone notifications do not reach the lenses.
*/
exitNow(): Promise<void>;
/** Optional: how this session was opened (`glassesMenu` covers the menu and voice launch). */
onLaunchSource?(listener: (source: 'appMenu' | 'glassesMenu') => void): () => void;
/**
* Read a stored value. `{ ok: false }` means the host did not answer (or failed): the value
* is UNKNOWN, which is different from "nothing stored" (`{ ok: true, value: '' }`).
@@ -68,6 +68,12 @@ export class BrowserPreviewDevice implements DevicePort {
async requestExit(): Promise<void> {}
/** The preview cannot leave anything; it only says so. */
async exitNow(): Promise<void> {
this.body.textContent = '(Pepper would now leave the glasses.)';
this.status.textContent = '';
}
async storageGet(key: string): Promise<StorageRead> {
try {
return { ok: true, value: localStorage.getItem(key) ?? '' };
+2
View File
@@ -10,6 +10,8 @@ import './ui/phone.css';
const { controller } = await boot(document, window, {
bridgeUrl: import.meta.env.VITE_HERMEVEN_BRIDGE_URL ?? '',
dev: import.meta.env.DEV,
// Development only: `?idleExit=off` keeps the app open, for automated simulator runs.
idleExit: !(import.meta.env.DEV && new URLSearchParams(location.search).get('idleExit') === 'off'),
});
// Development-only convenience for automated simulator runs, where nothing can type into the
+1
View File
@@ -198,6 +198,7 @@ export function mountPhoneUi(root: HTMLElement, controller: Controller, defaults
['Page origin', location.origin],
['Browser', navigator.userAgent],
['HUD page', s.hudReady ? 'created' : 'not created'],
['Opened from', s.launchSource === 'glassesMenu' ? 'the glasses (menu or voice)' : s.launchSource === 'appMenu' ? 'the phone app' : 'not reported'],
['Glasses input', s.glassesInput || 'not available in this mode'],
['Device id', s.deviceId || 'none'],
['Conversation id', s.state.conversationId ?? 'none'],