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
+5 -2
View File
@@ -33,8 +33,11 @@ the implementer read from the server's log, and what Cody reproduced independent
| Clean-host install (`deploy/install.sh`) | Proven on a disposable Ubuntu 24.04 container with systemd (`tests/deploy/runbook-proof.sh`), not on a second real server. | | Clean-host install (`deploy/install.sh`) | Proven on a disposable Ubuntu 24.04 container with systemd (`tests/deploy/runbook-proof.sh`), not on a second real server. |
The product's first goal needs the microphone to work while the phone is locked in a pocket. The product's first goal needs the microphone to work while the phone is locked in a pocket.
Even's documentation says capture stops if the app's WebView is suspended. That is the first Even's documentation says capture stops if the app's WebView is suspended. What is known so far is
thing to test on a device and it is not known to work. one owner-reported run on 2026-11-21 with the beta build: Dan reported that a spoken question was
answered with the phone locked. Still unverified: the phone locked **in a pocket**, survival after
five minutes locked, and the specification's ten-cycle acceptance run. That one observation is not
the acceptance test.
## How it fits together ## How it fits together
+4 -4
View File
@@ -1,6 +1,6 @@
import { waitForEvenAppBridge } from '@evenrealities/even_hub_sdk'; import { waitForEvenAppBridge } from '@evenrealities/even_hub_sdk';
import { measureTextWrap } from '@evenrealities/pretext'; 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 { EvenDevice } from './device/evenAdapter.ts';
import { waitForEvenHost, watchForLateHost, type HostWindow } from './device/hostDetect.ts'; import { waitForEvenHost, watchForLateHost, type HostWindow } from './device/hostDetect.ts';
import { BrowserPreviewDevice } from './device/previewDevice.ts'; import { BrowserPreviewDevice } from './device/previewDevice.ts';
@@ -29,8 +29,8 @@ export interface BootOptions {
hostWaitMs?: number; hostWaitMs?: number;
/** Development build: mirror diagnostics to the console. */ /** Development build: mirror diagnostics to the console. */
dev?: boolean; dev?: boolean;
/** `false` keeps the app on the glasses indefinitely (automated simulator runs). */ /** `false` keeps the app on the glasses indefinitely; an object overrides the times. Both are for automated simulator runs. */
idleExit?: boolean; idleExit?: boolean | Partial<IdleExitMs>;
/** Reload hook, replaceable in tests. */ /** Reload hook, replaceable in tests. */
reload?: () => void; reload?: () => void;
} }
@@ -92,7 +92,7 @@ export async function boot(doc: Document, win: Window, options: BootOptions = {}
measure: (text, width) => measureTextWrap(text, width).lineCount, measure: (text, width) => measureTextWrap(text, width).lineCount,
locale: win.navigator.language || 'en-US', locale: win.navigator.language || 'en-US',
onChange: (snapshot) => update(snapshot), 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 // Development builds mirror diagnostics to the console (visible in the simulator and the
// Even dev console). Diagnostics never contain questions, answers or credentials. // Even dev console). Diagnostics never contain questions, answers or credentials.
onNote: options.dev ? (entry) => console.info(`[hermeven] ${entry.kind}: ${entry.detail}`) : undefined, onNote: options.dev ? (entry) => console.info(`[hermeven] ${entry.kind}: ${entry.detail}`) : undefined,
+57 -5
View File
@@ -90,6 +90,10 @@ export interface ControllerOptions {
phoneGraceMs?: number; phoneGraceMs?: number;
/** A question asked after this long a silence starts a new conversation. */ /** A question asked after this long a silence starts a new conversation. */
conversationGapMs?: number; 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 { interface Capture {
@@ -146,7 +150,14 @@ export class Controller {
private idleArmed = false; private idleArmed = false;
private phoneBusyUntil = 0; private phoneBusyUntil = 0;
private launchSource: 'appMenu' | 'glassesMenu' | 'unknown' = 'unknown'; private launchSource: 'appMenu' | 'glassesMenu' | 'unknown' = 'unknown';
private readonly exitRetryMs: number;
private readonly exitAttempts: number;
/** The host confirmed we left. Final. */
private exited = false; 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. */ /** Set while a long press that STARTED a recording is still held down. */
private heldPress: { generation: number; at: number } | null = null; 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.idleExitMs = options.idleExit === null ? null : { ...DEFAULT_IDLE_EXIT_MS, ...options.idleExit };
this.phoneGraceMs = options.phoneGraceMs ?? 120_000; this.phoneGraceMs = options.phoneGraceMs ?? 120_000;
this.conversationGapMs = options.conversationGapMs ?? 10 * 60_000; this.conversationGapMs = options.conversationGapMs ?? 10 * 60_000;
this.exitRetryMs = options.exitRetryMs ?? 3_000;
this.exitAttempts = Math.max(1, options.exitAttempts ?? 4);
} }
// ------------------------------------------------------------------ public // ------------------------------------------------------------------ public
@@ -380,9 +393,11 @@ export class Controller {
* recording, transcribing, waiting for the agent or for an approval, or while disconnected * recording, transcribing, waiting for the agent or for an approval, or while disconnected
* with a request outstanding. * with a request outstanding.
*/ */
private scheduleIdleExit(): void { private scheduleIdleExit(retry = false): void {
if (this.idleTimer) clearTimeout(this.idleTimer); if (this.idleTimer) clearTimeout(this.idleTimer);
this.idleTimer = null; 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; if (this.stopped || this.exited || !this.idleExitMs || !this.idleArmed || !this.hudReady) return;
const phase = this.state.phase; const phase = this.state.phase;
const wait = const wait =
@@ -394,24 +409,56 @@ export class Controller {
? this.idleExitMs.message ? this.idleExitMs.message
: null; : null;
if (wait === null) return; 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; const generation = this.state.generation;
this.idleTimer = setTimeout(() => { this.idleTimer = setTimeout(() => {
this.idleTimer = null; this.idleTimer = null;
// Something happened in the meantime, or the screen is no longer a resting one. // 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.stopped || this.exited || this.state.generation !== generation || this.state.phase !== phase) return;
if (this.now() < this.phoneBusyUntil) return this.scheduleIdleExit(); 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}`); void this.leaveGlasses(`idle on ${phase}`);
}, delay); }, delay);
} }
private async leaveGlasses(reason: string): Promise<void> { private async leaveGlasses(reason: string): Promise<void> {
if (this.exited) return; if (this.exited || this.leaving) return;
this.exited = true; this.leaving = true;
const generation = this.state.generation;
this.note('lifecycle', `leaving the glasses: ${reason}`); this.note('lifecycle', `leaving the glasses: ${reason}`);
this.emit(); this.emit();
let confirmed = false;
try {
await this.closeMic(); await this.closeMic();
await this.device.exitNow(); 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 // ----------------------------------------------------------------- effects
@@ -799,6 +846,11 @@ export class Controller {
return; return;
case 'system_exit': case 'system_exit':
case 'abnormal_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); this.note('lifecycle', event.type);
return this.dispatch({ type: 'app_exit' }); return this.dispatch({ type: 'app_exit' });
case 'foreground_enter': case 'foreground_enter':
+43 -4
View File
@@ -46,7 +46,21 @@ export class EvenDevice implements DevicePort {
constructor( constructor(
private readonly bridge: EvenAppBridge, private readonly bridge: EvenAppBridge,
private readonly callTimeoutMs: number = CALL_TIMEOUT_MS, 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>> { private enqueueBounded<T>(call: () => Promise<T>, fallback: T): Promise<Bounded<T>> {
// What the host really does, serialised behind every earlier call. // 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); 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. // 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 { 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> { 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 * 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 * 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. * 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; onLaunchSource?(listener: (source: 'appMenu' | 'glassesMenu') => void): () => void;
/** /**
* Read a stored value. `{ ok: false }` means the host did not answer (or failed): the value * 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> {} async requestExit(): Promise<void> {}
/** The preview cannot leave anything; it only says so. */ /** 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.body.textContent = '(Pepper would now leave the glasses.)';
this.status.textContent = ''; this.status.textContent = '';
return true;
} }
async storageGet(key: string): Promise<StorageRead> { 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 * is no bridge, so a clearly-labelled preview device is used instead: it has no microphone and
* proves nothing about hardware. * 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, { const { controller } = await boot(document, window, {
bridgeUrl: import.meta.env.VITE_HERMEVEN_BRIDGE_URL ?? '', bridgeUrl: import.meta.env.VITE_HERMEVEN_BRIDGE_URL ?? '',
dev: import.meta.env.DEV, dev: import.meta.env.DEV,
// Development only: `?idleExit=off` keeps the app open, for automated simulator runs. // Development only, for automated simulator runs: `?idleExit=off` keeps the app open and
idleExit: !(import.meta.env.DEV && new URLSearchParams(location.search).get('idleExit') === 'off'), // `?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 // Development-only convenience for automated simulator runs, where nothing can type into the
+12 -3
View File
@@ -51,17 +51,26 @@ export class FakeDevice implements DevicePort {
async requestExit(): Promise<void> { async requestExit(): Promise<void> {
this.exitRequests += 1; this.exitRequests += 1;
} }
/** Times the app left the glasses by itself. */ /** Times the app asked to leave the glasses by itself, and times that was confirmed. */
exitAttempts = 0;
exits = 0; exits = 0;
async exitNow(): Promise<void> { /** Scripted answers for the next exit attempts (`false` = refused); then it succeeds. */
this.exits += 1; exitResults: boolean[] = [];
async exitNow(): Promise<boolean> {
this.exitAttempts += 1;
const ok = this.exitResults.shift() ?? true;
if (ok) this.exits += 1;
return ok;
} }
private launched: 'appMenu' | 'glassesMenu' | null = null;
private readonly launchListeners = new Set<(source: 'appMenu' | 'glassesMenu') => void>(); private readonly launchListeners = new Set<(source: 'appMenu' | 'glassesMenu') => void>();
onLaunchSource(listener: (source: 'appMenu' | 'glassesMenu') => void): () => void { onLaunchSource(listener: (source: 'appMenu' | 'glassesMenu') => void): () => void {
this.launchListeners.add(listener); this.launchListeners.add(listener);
if (this.launched) listener(this.launched);
return () => this.launchListeners.delete(listener); return () => this.launchListeners.delete(listener);
} }
launchedFrom(source: 'appMenu' | 'glassesMenu'): void { launchedFrom(source: 'appMenu' | 'glassesMenu'): void {
this.launched = source;
for (const l of this.launchListeners) l(source); for (const l of this.launchListeners) l(source);
} }
/** Set to make storage writes report "not confirmed" without writing. */ /** Set to make storage writes report "not confirmed" without writing. */
+67
View File
@@ -707,6 +707,73 @@ describe('leaving the glasses when idle (the app blocks notifications while it i
expect(snapshot.log.some((e) => e.detail.includes('leaving the glasses: idle on answer'))).toBe(true); expect(snapshot.log.some((e) => e.detail.includes('leaving the glasses: idle on answer'))).toBe(true);
}); });
it('an exit the host does not confirm is tried again, and a confirmed one is final', async () => {
controllerExtras = { idleExit: FAST, exitRetryMs: 60, exitAttempts: 4 };
await pairedController();
device.exitResults = [false, false];
device.launchedFrom('glassesMenu');
await until('left on the third attempt', () => device.exits === 1, 2000);
expect(device.exitAttempts).toBe(3);
await quiet(400);
expect(device.exitAttempts).toBe(3);
expect(snapshot.log.some((e) => e.detail === 'left the glasses')).toBe(true);
});
it('a host that keeps refusing is asked a bounded number of times, then again only after activity', async () => {
controllerExtras = { idleExit: FAST, exitRetryMs: 40, exitAttempts: 3 };
await pairedController();
device.exitResults = Array.from({ length: 10 }, () => false);
device.launchedFrom('glassesMenu');
await until('three attempts', () => device.exitAttempts === 3, 2000);
await quiet(500);
expect(device.exitAttempts).toBe(3);
expect(device.exits).toBe(0);
// A gesture is activity: the countdown and the attempts start again, and the app still works.
device.exitResults = [];
device.swipeDown();
await until('left after the next idle period', () => device.exits === 1, 2000);
expect(device.exitAttempts).toBe(4);
});
it('never leaves while a request is outstanding and the bridge cannot be reached', async () => {
controllerExtras = { idleExit: FAST };
await pairedController();
device.launchedFrom('glassesMenu');
h.hermes.next({ kind: 'complete', afterMs: 300, output: 'worth the wait' });
controller.askText('q');
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
network.down = true;
await until('disconnected', () => phase() === 'disconnected');
await quiet(600); // four timeouts' worth
expect(phase()).toBe('disconnected');
expect(device.exitAttempts).toBe(0);
network.down = false;
await until('answer', () => phase() === 'answer');
await until('left once the answer had been shown and left alone', () => device.exits === 1, 2000);
});
it('once the glasses report the app closed, no idle exit is sent, and a failed one is not retried', async () => {
controllerExtras = { idleExit: FAST, exitRetryMs: 60, exitAttempts: 4 };
await pairedController();
device.launchedFrom('glassesMenu');
device.emit({ type: 'system_exit' });
await quiet(600);
expect(device.exitAttempts).toBe(0);
await controller.stop();
const stored = device.storage;
device = new FakeDevice();
for (const [k, v] of stored) device.storage.set(k, v);
controller = makeController(device);
await controller.start();
device.exitResults = Array.from({ length: 10 }, () => false);
device.launchedFrom('glassesMenu');
await until('first attempt refused', () => device.exitAttempts === 1, 2000);
device.emit({ type: 'abnormal_exit' });
await quiet(600);
expect(device.exitAttempts).toBe(1);
});
it('paging, or any gesture, restarts the countdown', async () => { it('paging, or any gesture, restarts the countdown', async () => {
controllerExtras = { idleExit: FAST }; controllerExtras = { idleExit: FAST };
await pairedController(); await pairedController();
+28
View File
@@ -126,6 +126,7 @@ describe('CODY-002: host calls stay serialised and a late microphone start ends
shutDownPageContainer: (...a: unknown[]) => call('exit', a), shutDownPageContainer: (...a: unknown[]) => call('exit', a),
getLocalStorage: (...a: unknown[]) => call('get', a), getLocalStorage: (...a: unknown[]) => call('get', a),
setLocalStorage: (...a: unknown[]) => call('set', a), setLocalStorage: (...a: unknown[]) => call('set', a),
onLaunchSource: () => () => undefined,
}; };
return { bridge, calls, micOpen: () => micOpen, maxInFlight: () => maxInFlight, pending: () => calls.filter((c) => !c.settled) }; return { bridge, calls, micOpen: () => micOpen, maxInFlight: () => maxInFlight, pending: () => calls.filter((c) => !c.settled) };
} }
@@ -165,6 +166,33 @@ describe('CODY-002: host calls stay serialised and a late microphone start ends
expect(host.pending()).toEqual([]); expect(host.pending()).toEqual([]);
}); });
it('an idle exit waits its turn behind a host call that is still in flight, and is asked only once', async () => {
const host = fakeHost();
const device = new EvenDevice(host.bridge as never);
const writing = device.storageSet('k', 'v');
await tick();
const leaving = device.exitNow();
const leavingAgain = device.exitNow();
await tick();
// The write has not settled: the exit has not been sent.
expect(host.calls.map((c) => c.name)).toEqual(['set']);
host.pending()[0]!.resolve(true);
await tick();
expect(await writing).toBe(true);
expect(host.calls.map((c) => c.name)).toEqual(['set', 'exit']);
expect(host.calls[1]!.args).toEqual([0]); // immediate mode, no dialog
host.pending()[0]!.resolve(true);
await tick();
expect(await leaving).toBe(true);
expect(await leavingAgain).toBe(true);
// Confirmed: nothing further is ever sent for an exit.
expect(await device.exitNow()).toBe(true);
expect(host.calls.map((c) => c.name)).toEqual(['set', 'exit']);
expect(host.maxInFlight()).toBe(1);
});
it('a stop requested while the start is still pending waits its turn and still leaves the microphone closed', async () => { it('a stop requested while the start is still pending waits its turn and still leaves the microphone closed', async () => {
const host = fakeHost(); const host = fakeHost();
const device = new EvenDevice(host.bridge as never); const device = new EvenDevice(host.bridge as never);
+375
View File
@@ -0,0 +1,375 @@
import { measureTextWrap } from '@evenrealities/pretext';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { Controller, type Snapshot } from '../../apps/even-client/src/core/controller.ts';
import { EvenDevice } from '../../apps/even-client/src/device/evenAdapter.ts';
import { BridgeClient } from '../../apps/even-client/src/net/bridgeClient.ts';
import { createHarness, type Harness } from './harness.ts';
/**
* Leaving the glasses when idle, at the production seam: the REAL EvenDevice adapter driven by
* a stand-in Even host. The bridge is real; Hermes is the test fake. No glasses are involved,
* and nothing here shows what the real Even app does on `shutDownPageContainer(0)`.
*/
const ADAPTER_TIMEOUT_MS = 100;
class FakeEvenHost {
readonly durable = new Map<string, string>();
/** Reads settle only when released, to hold start-up open. */
stallReads = false;
private heldReads: Array<() => void> = [];
/** What the next exit calls answer; 'hold' settles only on `releaseExit`. Then `true`. */
exitScript: Array<boolean | 'hold' | 'throw'> = [];
private heldExit: ((ok: boolean) => void) | null = null;
exitCalls: number[] = [];
hudCreates = 0;
inFlight = 0;
maxInFlight = 0;
private launch = new Set<(source: string) => void>();
private hub = new Set<(event: unknown) => void>();
private async track<T>(call: () => Promise<T>): Promise<T> {
this.inFlight += 1;
this.maxInFlight = Math.max(this.maxInFlight, this.inFlight);
try {
return await call();
} finally {
this.inFlight -= 1;
}
}
readonly bridge = {
createStartUpPageContainer: () =>
this.track(async () => {
this.hudCreates += 1;
return 0;
}),
textContainerUpgrade: () => this.track(async () => true),
audioControl: () => this.track(async () => true),
shutDownPageContainer: (mode: number) =>
this.track(() => {
this.exitCalls.push(mode);
const next = this.exitScript.shift() ?? true;
if (next === 'throw') return Promise.reject(new Error('host error'));
if (next === 'hold') return new Promise<boolean>((resolve) => (this.heldExit = resolve));
return Promise.resolve(next);
}),
getLocalStorage: (key: string) =>
this.track(
() =>
new Promise<string>((resolve) => {
const answer = () => resolve(this.durable.get(key) ?? '');
if (this.stallReads) this.heldReads.push(answer);
else answer();
}),
),
setLocalStorage: (key: string, value: string) =>
this.track(async () => {
this.durable.set(key, value);
return true;
}),
onEvenHubEvent: (cb: (event: unknown) => void) => {
this.hub.add(cb);
return () => this.hub.delete(cb);
},
onDeviceStatusChanged: () => () => undefined,
onLaunchSource: (cb: (source: string) => void) => {
this.launch.add(cb);
return () => this.launch.delete(cb);
},
};
/** The host's one-shot launch-source push: delivered once, to whoever is subscribed NOW. */
pushLaunchSource(source: string): number {
for (const cb of this.launch) cb(source);
return this.launch.size;
}
releaseReads(): void {
for (const answer of this.heldReads.splice(0)) answer();
}
exitHeld(): boolean {
return this.heldExit !== null;
}
releaseExit(ok: boolean): void {
const resolve = this.heldExit;
this.heldExit = null;
resolve?.(ok);
}
systemExit(): void {
for (const cb of this.hub) cb({ sysEvent: { eventType: 7 } });
}
swipeDown(): void {
for (const cb of this.hub) cb({ sysEvent: { eventType: 2 } });
}
}
let h: Harness;
let host: FakeEvenHost;
let controller: Controller;
let snapshot: Snapshot;
const unhandled: unknown[] = [];
const onUnhandled = (reason: unknown) => unhandled.push(reason);
function makeController(extra: Partial<ConstructorParameters<typeof Controller>[0]> = {}): Controller {
return new Controller({
device: new EvenDevice(host.bridge as never, ADAPTER_TIMEOUT_MS),
measure: (text, width) => measureTextWrap(text, width).lineCount,
locale: 'en-US',
pollIntervalMs: 20,
idleExit: { answer: 150, ready: 150, message: 100 },
exitRetryMs: 40,
exitAttempts: 4,
makeClient: (baseUrl, token) => new BridgeClient({ baseUrl, token, timeoutMs: 500 }),
onChange: (s) => {
snapshot = s;
},
...extra,
});
}
async function until(what: string, predicate: () => boolean, timeoutMs = 4000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (!predicate()) {
if (Date.now() > deadline) throw new Error(`timed out waiting for: ${what}; phase=${snapshot?.state.phase}`);
await new Promise((r) => setTimeout(r, 10));
}
}
const quiet = (ms: number) => new Promise((r) => setTimeout(r, ms));
const logged = (text: string) => snapshot.log.filter((e) => e.detail.includes(text)).length;
/** A host that already holds a pairing, as after an earlier session. Idle exit off while pairing. */
async function pairedHost(): Promise<void> {
host = new FakeEvenHost();
controller = makeController({ idleExit: null });
await controller.start();
await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'idle-exit');
await until('ready', () => snapshot.state.phase === 'ready');
await controller.stop();
// That was the earlier page, with its own adapter. Let its last host calls finish, then count
// overlap from zero: the claim under test is about ONE adapter's calls.
await until('earlier page is quiet', () => host.inFlight === 0);
await quiet(30);
host.maxInFlight = 0;
}
beforeEach(async () => {
h = await createHarness();
unhandled.length = 0;
process.on('unhandledRejection', onUnhandled);
});
afterEach(async () => {
vi.useRealTimers();
await controller?.stop();
await quiet(20);
process.off('unhandledRejection', onUnhandled);
expect(unhandled).toEqual([]);
await h.close();
});
describe('the one-shot launch source is not lost during start-up', () => {
it('pushed while storage is still being read and before the HUD exists: Ready is armed and the app leaves exactly once', async () => {
await pairedHost();
host.stallReads = true;
host.hudCreates = 0;
controller = makeController();
const starting = controller.start();
await quiet(30);
// Start-up is parked on the storage read; the HUD has not been created.
expect(host.hudCreates).toBe(0);
// The host pushes its one-shot event now. Someone must already be listening.
expect(host.pushLaunchSource('glassesMenu')).toBeGreaterThan(0);
await quiet(30);
host.stallReads = false;
host.releaseReads();
await starting;
await until('ready', () => snapshot.state.phase === 'ready');
expect(snapshot.launchSource).toBe('glassesMenu');
expect(host.exitCalls).toEqual([]);
await until('left the glasses', () => logged('left the glasses') === 1, 2000);
await quiet(400);
expect(host.exitCalls).toEqual([0]); // one call, immediate mode
expect(host.maxInFlight).toBe(1);
});
it('control: with no launch source and no gesture, the same start-up does not leave', async () => {
await pairedHost();
controller = makeController();
await controller.start();
await until('ready', () => snapshot.state.phase === 'ready');
await quiet(500);
expect(host.exitCalls).toEqual([]);
});
});
describe('an exit the host does not complete', () => {
async function launchedFromGlasses(): Promise<void> {
await pairedHost();
controller = makeController();
host.pushLaunchSource('glassesMenu');
await controller.start();
await until('ready', () => snapshot.state.phase === 'ready');
}
it('answered false, then true: a second call is made, and only then is it final', async () => {
host = new FakeEvenHost();
await launchedFromGlasses();
host.exitScript = [false];
await until('left the glasses', () => logged('left the glasses') === 1, 2000);
expect(host.exitCalls).toEqual([0, 0]);
expect(logged('did not confirm leaving; will try again')).toBe(1);
await quiet(400);
expect(host.exitCalls).toEqual([0, 0]);
expect(host.maxInFlight).toBe(1);
});
it('a host call that throws is treated the same way, with no unhandled rejection', async () => {
await launchedFromGlasses();
host.exitScript = ['throw'];
await until('left the glasses', () => logged('left the glasses') === 1, 2000);
expect(host.exitCalls).toEqual([0, 0]);
expect(host.maxInFlight).toBe(1);
});
it('no answer in time, then a late success: one host call ever, never two in flight, and it ends as left', async () => {
await launchedFromGlasses();
host.exitScript = ['hold'];
await until('the exit is with the host', () => host.exitHeld());
// Longer than the adapter's wait plus a retry: the controller has asked again by now.
await until('a retry was scheduled', () => logged('will try again') >= 1, 2000);
await quiet(ADAPTER_TIMEOUT_MS);
expect(host.exitCalls).toEqual([0]); // the retry waited on the same call
expect(host.inFlight).toBe(1);
host.releaseExit(true);
await until('left the glasses', () => logged('left the glasses') === 1, 2000);
await quiet(400);
expect(host.exitCalls).toEqual([0]);
expect(host.maxInFlight).toBe(1);
});
it('the host answers only after every attempt has run out: still one call, and no exit is sent afterwards', async () => {
await launchedFromGlasses();
host.exitScript = ['hold'];
await until('gave up for now', () => logged('staying until the next activity') === 1, 4000);
expect(host.exitCalls).toEqual([0]);
host.releaseExit(true); // the Even app finally acts on it
await quiet(50);
host.swipeDown(); // activity re-arms the countdown; the adapter knows it already left
await until('recorded as left', () => logged('left the glasses') === 1, 2000);
await quiet(300);
expect(host.exitCalls).toEqual([0]);
expect(host.maxInFlight).toBe(1);
});
it('no answer, then a late refusal: a fresh call follows it, in order', async () => {
await launchedFromGlasses();
host.exitScript = ['hold'];
await until('the exit is with the host', () => host.exitHeld());
await quiet(ADAPTER_TIMEOUT_MS + 30);
host.releaseExit(false);
await until('left the glasses', () => logged('left the glasses') === 1, 2000);
expect(host.exitCalls).toEqual([0, 0]);
expect(host.maxInFlight).toBe(1);
});
});
/**
* The DEFAULT times, under fake time, with the production adapter. Only the clock and the timers
* are faked; the bridge calls made during start-up are real and are awaited as promises.
*/
describe('default idle times with the production adapter (fake clock)', () => {
const fakeClock = () => vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'] });
const defaults = () =>
makeController({ idleExit: {}, exitRetryMs: undefined as never, exitAttempts: undefined as never });
async function expectOneExitAtThirtySeconds(): Promise<void> {
await vi.advanceTimersByTimeAsync(29_900);
expect(host.exitCalls).toEqual([]);
await vi.advanceTimersByTimeAsync(200);
expect(host.exitCalls).toEqual([0]);
await vi.advanceTimersByTimeAsync(10 * 60_000);
expect(host.exitCalls).toEqual([0]); // exactly once, however long it is left
expect(logged('left the glasses')).toBe(1);
expect(host.maxInFlight).toBe(1);
}
it('glassesMenu pushed BEFORE the controller starts: one exit, 30 s after Ready', async () => {
await pairedHost();
fakeClock();
controller = defaults();
expect(host.pushLaunchSource('glassesMenu')).toBeGreaterThan(0); // the adapter is already listening
await controller.start();
expect(snapshot.state.phase).toBe('ready');
await expectOneExitAtThirtySeconds();
});
it('glassesMenu pushed AFTER the controller subscribed: one exit, 30 s later', async () => {
await pairedHost();
fakeClock();
controller = defaults();
await controller.start();
await vi.advanceTimersByTimeAsync(5 * 60_000);
expect(host.exitCalls).toEqual([]); // nothing has said the glasses are in use
host.pushLaunchSource('glassesMenu');
await expectOneExitAtThirtySeconds();
});
it('appMenu pushed early does not arm it; the first glasses gesture does', async () => {
await pairedHost();
fakeClock();
controller = defaults();
host.pushLaunchSource('appMenu');
await controller.start();
expect(snapshot.launchSource).toBe('appMenu');
await vi.advanceTimersByTimeAsync(10 * 60_000);
expect(host.exitCalls).toEqual([]);
host.swipeDown();
await expectOneExitAtThirtySeconds();
});
it('unsubscribing is preserved: a stopped controller no longer hears the launch source', async () => {
await pairedHost();
fakeClock();
controller = defaults();
await controller.start();
await controller.stop();
host.pushLaunchSource('glassesMenu');
await vi.advanceTimersByTimeAsync(10 * 60_000);
expect(host.exitCalls).toEqual([]);
});
it('a real exit event from the glasses is final: no idle exit follows it', async () => {
await pairedHost();
fakeClock();
controller = defaults();
host.pushLaunchSource('glassesMenu');
await controller.start();
await vi.advanceTimersByTimeAsync(10_000);
host.systemExit();
await vi.advanceTimersByTimeAsync(10 * 60_000);
expect(host.exitCalls).toEqual([]);
});
it('default retry: refused, then thrown, then no answer, then confirmed, one call at a time', async () => {
await pairedHost();
fakeClock();
controller = defaults();
host.pushLaunchSource('glassesMenu');
host.exitScript = [false, 'throw', 'hold'];
await controller.start();
await vi.advanceTimersByTimeAsync(30_100);
expect(host.exitCalls).toEqual([0]); // refused
await vi.advanceTimersByTimeAsync(3_100);
expect(host.exitCalls).toEqual([0, 0]); // threw
await vi.advanceTimersByTimeAsync(3_100);
expect(host.exitCalls).toEqual([0, 0, 0]); // held by the host
await vi.advanceTimersByTimeAsync(1_000);
// The wait for an answer has run out and a retry is pending; no second call is in flight.
expect(logged('will try again')).toBe(3);
expect(host.exitCalls).toEqual([0, 0, 0]);
expect(host.inFlight).toBe(1);
host.releaseExit(true); // the host finally acts on the call it was holding
await vi.advanceTimersByTimeAsync(10 * 60_000);
expect(host.exitCalls).toEqual([0, 0, 0]);
expect(logged('left the glasses')).toBe(1);
expect(host.maxInFlight).toBe(1);
});
});
+64 -18
View File
@@ -31,6 +31,7 @@ let automation = '';
let lastConsoleId = 0; let lastConsoleId = 0;
const consoleLines: string[] = []; const consoleLines: string[] = [];
let audioEchoLines = 0; let audioEchoLines = 0;
let simulatorExitOutcome = 'not run';
async function freePort(): Promise<number> { async function freePort(): Promise<number> {
return new Promise((resolvePort) => { return new Promise((resolvePort) => {
@@ -145,29 +146,16 @@ function litInBand(shot: { rows: Buffer[]; width: number }, fromY: number, toY:
return lit; return lit;
} }
beforeAll(async () => { let pageOriginForRelaunch = '';
mkdirSync(artifacts, { recursive: true });
const vitePort = await freePort();
vite = await createServer({
root: resolve(here, '../../apps/even-client'),
configFile: resolve(here, '../../apps/even-client/vite.config.ts'),
server: { host: '127.0.0.1', port: vitePort, strictPort: true },
logLevel: 'error',
});
await vite.listen();
const pageOrigin = `http://127.0.0.1:${vitePort}`;
h = await createHarness({
env: { HERMEVEN_ALLOWED_ORIGINS: pageOrigin, HERMEVEN_CAPTURE_MAX_SECONDS: '120' },
timing: { agentDeadlineMs: 20_000, transcribeDeadlineMs: 10_000 },
});
const { code } = h.bridge.devices.createPairingCode();
/** Start a simulator on the page. `idleExit` is the development-only switch read by main.ts. */
async function launchSimulator(idleExit: 'off' | 'fast', code: string): Promise<void> {
const pageOrigin = pageOriginForRelaunch;
const automationPort = await freePort(); const automationPort = await freePort();
automation = `http://127.0.0.1:${automationPort}`; automation = `http://127.0.0.1:${automationPort}`;
const bin = require.resolve('@evenrealities/sim-linux-x64/bin/evenhub-simulator'); const bin = require.resolve('@evenrealities/sim-linux-x64/bin/evenhub-simulator');
// idleExit=off: this suite drives the app for longer than the idle timeout between steps. // idleExit=off: this suite drives the app for longer than the idle timeout between steps.
const url = `${pageOrigin}/?idleExit=off&bridge=${encodeURIComponent(h.url)}&pair=${encodeURIComponent(code)}`; const url = `${pageOrigin}/?idleExit=${idleExit}&bridge=${encodeURIComponent(h.url)}&pair=${encodeURIComponent(code)}`;
// alsa:null yields silence: the simulator never opens a real microphone in this test. // alsa:null yields silence: the simulator never opens a real microphone in this test.
sim = spawn(bin, [url, '--automation-port', String(automationPort), '--no-glow', '--aid', 'alsa:null'], { sim = spawn(bin, [url, '--automation-port', String(automationPort), '--no-glow', '--aid', 'alsa:null'], {
stdio: ['ignore', 'pipe', 'pipe'], stdio: ['ignore', 'pipe', 'pipe'],
@@ -186,6 +174,28 @@ beforeAll(async () => {
if (Date.now() > deadline) throw new Error(`simulator automation API did not start.\n${simOutput.slice(-2000)}`); if (Date.now() > deadline) throw new Error(`simulator automation API did not start.\n${simOutput.slice(-2000)}`);
await new Promise((r) => setTimeout(r, 250)); await new Promise((r) => setTimeout(r, 250));
} }
}
beforeAll(async () => {
mkdirSync(artifacts, { recursive: true });
const vitePort = await freePort();
vite = await createServer({
root: resolve(here, '../../apps/even-client'),
configFile: resolve(here, '../../apps/even-client/vite.config.ts'),
server: { host: '127.0.0.1', port: vitePort, strictPort: true },
logLevel: 'error',
});
await vite.listen();
const pageOrigin = `http://127.0.0.1:${vitePort}`;
h = await createHarness({
env: { HERMEVEN_ALLOWED_ORIGINS: pageOrigin, HERMEVEN_CAPTURE_MAX_SECONDS: '120' },
timing: { agentDeadlineMs: 20_000, transcribeDeadlineMs: 10_000 },
});
const { code } = h.bridge.devices.createPairingCode();
pageOriginForRelaunch = pageOrigin;
await launchSimulator('off', code);
}); });
afterAll(async () => { afterAll(async () => {
@@ -330,4 +340,40 @@ describe('Even Hub simulator 0.9.5', () => {
const problems = consoleLines.filter((l) => /\[uncaught\]|\[unhandledrejection\]|\[fetch\]/.test(l)); const problems = consoleLines.filter((l) => /\[uncaught\]|\[unhandledrejection\]|\[fetch\]/.test(l));
expect(problems).toEqual([]); expect(problems).toEqual([]);
}); });
it('idle exit for real: with short waits, the app calls the simulator\'s shutDownPageContainer(0) and records the answer', async () => {
// A second simulator, this time WITHOUT idle exit disabled (development-only short waits:
// 5 s at Ready). Everything above ran with it off because the steps take longer than that.
sim.kill('SIGTERM');
await new Promise((r) => setTimeout(r, 500));
if (sim.exitCode === null) sim.kill('SIGKILL');
await pumpConsole().catch(() => undefined);
const from = consoleLines.length;
lastConsoleId = 0;
await launchSimulator('fast', h.bridge.devices.createPairingCode().code);
await waitConsole('hud: HUD page created', 30_000, from);
await waitConsole('-> ready', 20_000, from);
await new Promise((r) => setTimeout(r, 6_500));
await pumpConsole();
// Opened by URL, no gesture yet: not armed, so it must still be there.
expect(consoleLines.slice(from).some((l) => l.includes('leaving the glasses'))).toBe(false);
await input('down'); // a glasses gesture arms it
await waitConsole('leaving the glasses: idle on ready', 15_000, from);
await new Promise((r) => setTimeout(r, 1_500));
await pumpConsole();
const after = consoleLines.slice(from);
const confirmed = after.some((l) => l.includes('lifecycle: left the glasses'));
const refused = after.some((l) => l.includes('did not confirm leaving'));
simulatorExitOutcome = confirmed ? 'confirmed' : refused ? 'not confirmed' : 'no answer recorded';
console.log(`[simulator] shutDownPageContainer(0): ${simulatorExitOutcome}`);
const shot = await screenshot('08-after-idle-exit');
// Observed on simulator 0.9.5: the call is confirmed and the display is cleared.
expect(simulatorExitOutcome).toBe('confirmed');
expect(shot.lit).toBeLessThan(50);
// What the simulator does with the call is recorded, not assumed; either way the app must
// have asked, and must not have thrown.
expect(confirmed || refused).toBe(true);
const problems = after.filter((l) => /\[uncaught\]|\[unhandledrejection\]/.test(l));
expect(problems).toEqual([]);
}, 120_000);
}); });