CODY-016, 017, 018: launch source cannot be missed; a failed idle exit is retried

CODY-016. The SDK pushes the launch source once, early. The Even adapter now
subscribes in its constructor, remembers the value and replays it to a
listener that subscribes later. appMenu still does not arm idle exit.

CODY-018. exitNow() returns whether the host confirmed. The adapter keeps at
most one shutdown call in flight (through the same queue as every other host
call), lets a repeat request wait on that call, and never calls the host
again after a confirmed exit, including one confirmed late. The controller
marks itself as gone only on confirmation or on a system_exit/abnormal_exit
event; otherwise it retries after 3 s, at most 4 attempts in a row, under the
same resting-screen and phone-grace guards, and starts again after activity.

CODY-017. README: one owner-reported locked-phone success; pocketed,
five-minute and ten-cycle runs unverified.

Tests: production-adapter tests with a stand-in host, including the default
30 s under a fake clock; a simulator scenario that performs the real exit
(development-only ?idleExit=fast). Not reviewed. 0.1.1 is not uploaded.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Dan
2026-11-21 14:38:29 -08:00
co-authored by Claude Fable 5.2
parent 1ae105ed18
commit bbde3c86a8
12 changed files with 679 additions and 42 deletions
+4 -4
View File
@@ -1,6 +1,6 @@
import { waitForEvenAppBridge } from '@evenrealities/even_hub_sdk';
import { measureTextWrap } from '@evenrealities/pretext';
import { Controller } from './core/controller.ts';
import { Controller, type IdleExitMs } from './core/controller.ts';
import { EvenDevice } from './device/evenAdapter.ts';
import { waitForEvenHost, watchForLateHost, type HostWindow } from './device/hostDetect.ts';
import { BrowserPreviewDevice } from './device/previewDevice.ts';
@@ -29,8 +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;
/** `false` keeps the app on the glasses indefinitely; an object overrides the times. Both are for automated simulator runs. */
idleExit?: boolean | Partial<IdleExitMs>;
/** Reload hook, replaceable in tests. */
reload?: () => void;
}
@@ -92,7 +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 } : {}),
...(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.
onNote: options.dev ? (entry) => console.info(`[hermeven] ${entry.kind}: ${entry.detail}`) : undefined,
+58 -6
View File
@@ -90,6 +90,10 @@ export interface ControllerOptions {
phoneGraceMs?: number;
/** A question asked after this long a silence starts a new conversation. */
conversationGapMs?: number;
/** If the host does not confirm the exit, try again after this long... */
exitRetryMs?: number;
/** ...up to this many attempts in a row. Any activity starts the count again. */
exitAttempts?: number;
}
interface Capture {
@@ -146,7 +150,14 @@ export class Controller {
private idleArmed = false;
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;
/** Set while a long press that STARTED a recording is still held down. */
private heldPress: { generation: number; at: number } | null = null;
@@ -162,6 +173,8 @@ export class Controller {
this.idleExitMs = options.idleExit === null ? null : { ...DEFAULT_IDLE_EXIT_MS, ...options.idleExit };
this.phoneGraceMs = options.phoneGraceMs ?? 120_000;
this.conversationGapMs = options.conversationGapMs ?? 10 * 60_000;
this.exitRetryMs = options.exitRetryMs ?? 3_000;
this.exitAttempts = Math.max(1, options.exitAttempts ?? 4);
}
// ------------------------------------------------------------------ public
@@ -380,9 +393,11 @@ export class Controller {
* recording, transcribing, waiting for the agent or for an approval, or while disconnected
* with a request outstanding.
*/
private scheduleIdleExit(): void {
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;
if (this.stopped || this.exited || !this.idleExitMs || !this.idleArmed || !this.hudReady) return;
const phase = this.state.phase;
const wait =
@@ -394,24 +409,56 @@ export class Controller {
? this.idleExitMs.message
: null;
if (wait === null) return;
const delay = Math.max(wait, this.phoneBusyUntil - this.now() + wait);
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) return;
this.exited = true;
if (this.exited || this.leaving) return;
this.leaving = true;
const generation = this.state.generation;
this.note('lifecycle', `leaving the glasses: ${reason}`);
this.emit();
await this.closeMic();
await this.device.exitNow();
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 the user did something meanwhile, their activity
// already restarted the full countdown; otherwise try again, a bounded number of times.
if (this.state.generation !== generation) 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
@@ -799,6 +846,11 @@ export class Controller {
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':
+43 -4
View File
@@ -46,7 +46,21 @@ export class EvenDevice implements DevicePort {
constructor(
private readonly bridge: EvenAppBridge,
private readonly callTimeoutMs: number = CALL_TIMEOUT_MS,
) {}
) {
// The SDK documents the launch source as a ONE-SHOT event pushed soon after the page loads.
// Subscribe the moment the bridge is in hand and remember the answer, so a listener that
// arrives after storage and the HUD are set up still gets it.
this.bridge.onLaunchSource((source) => {
this.launchSource = source === 'glassesMenu' ? 'glassesMenu' : 'appMenu';
for (const listener of this.launchListeners) listener(this.launchSource);
});
}
private launchSource: 'appMenu' | 'glassesMenu' | null = null;
private readonly launchListeners = new Set<(source: 'appMenu' | 'glassesMenu') => void>();
/** The exit call the host has not yet answered, if any. Never more than one. */
private exitCall: Promise<boolean> | null = null;
private exitConfirmed = false;
private enqueueBounded<T>(call: () => Promise<T>, fallback: T): Promise<Bounded<T>> {
// What the host really does, serialised behind every earlier call.
@@ -234,13 +248,38 @@ export class EvenDevice implements DevicePort {
await this.enqueue(() => this.bridge.shutDownPageContainer(1), false);
}
async exitNow(): Promise<void> {
async exitNow(): Promise<boolean> {
// Mode 0: leave immediately. The Even app then closes the phone-side page too.
await this.enqueue(() => this.bridge.shutDownPageContainer(0), false);
if (this.exitConfirmed) return true;
if (!this.exitCall) {
// Through the same queue as every other host call, so it never overlaps one.
const call: Promise<boolean> = this.queue
.then(() => this.bridge.shutDownPageContainer(0))
.then((ok) => ok === true, () => false);
this.queue = call;
this.exitCall = call;
void call.then((ok) => {
if (ok) this.exitConfirmed = true;
if (this.exitCall === call) this.exitCall = null;
});
}
// A caller that asks again while the host is still thinking waits on the SAME call; a
// second one is never issued. If the wait runs out the answer is "not confirmed", and a
// late success is remembered so no further exit is ever sent.
const current = this.exitCall;
return new Promise((resolve) => {
const timer = setTimeout(() => resolve(false), this.callTimeoutMs);
void current.then((ok) => {
clearTimeout(timer);
resolve(ok);
});
});
}
onLaunchSource(listener: (source: 'appMenu' | 'glassesMenu') => void): () => void {
return this.bridge.onLaunchSource((source) => listener(source));
this.launchListeners.add(listener);
if (this.launchSource) listener(this.launchSource);
return () => this.launchListeners.delete(listener);
}
async storageGet(key: string): Promise<StorageRead> {
+10 -2
View File
@@ -20,9 +20,17 @@ export interface DevicePort {
* 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.
*
* Resolves `true` ONLY when the host confirmed the exit. `false` covers a refusal, an error
* and a wait that ran out; the caller may try again. An implementation must never have two
* exit calls in flight, and must not call the host again after a confirmed exit.
*/
exitNow(): Promise<boolean>;
/**
* Optional: how this session was opened (`glassesMenu` covers the menu and voice launch).
* The host sends this once, early. An implementation must remember it and replay it to a
* listener that subscribes later.
*/
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
+2 -1
View File
@@ -69,9 +69,10 @@ export class BrowserPreviewDevice implements DevicePort {
async requestExit(): Promise<void> {}
/** The preview cannot leave anything; it only says so. */
async exitNow(): Promise<void> {
async exitNow(): Promise<boolean> {
this.body.textContent = '(Pepper would now leave the glasses.)';
this.status.textContent = '';
return true;
}
async storageGet(key: string): Promise<StorageRead> {
+11 -2
View File
@@ -7,11 +7,20 @@ import './ui/phone.css';
* is no bridge, so a clearly-labelled preview device is used instead: it has no microphone and
* proves nothing about hardware.
*/
function devIdleExit(): boolean | { answer: number; ready: number; message: number } {
if (!import.meta.env.DEV) return true;
const value = new URLSearchParams(location.search).get('idleExit');
if (value === 'off') return false;
if (value === 'fast') return { answer: 4_000, ready: 5_000, message: 3_000 };
return true;
}
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, 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 convenience for automated simulator runs, where nothing can type into the