Files
hermeven/apps/even-client/src/boot.ts
T
DanandClaude Fable 5.2 bbde3c86a8 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>
2026-11-21 14:38:29 -08:00

126 lines
5.1 KiB
TypeScript

import { waitForEvenAppBridge } from '@evenrealities/even_hub_sdk';
import { measureTextWrap } from '@evenrealities/pretext';
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';
import type { DevicePort } from './device/port.ts';
import { mountPhoneUi } from './ui/phone.ts';
/**
* Page start-up, kept out of main.ts so it can be exercised against a real DOM in tests.
*
* Sequence:
* 1. The static HTML already shows a status line (`#startup`), so the page is never blank.
* 2. Wait briefly for the Even app's connection (see device/hostDetect.ts). There is no eager
* fallback: nothing is mounted, and no device is chosen, until that wait has an answer.
* 3. Even app found: use the real adapter. Not found: show the clearly-labelled browser preview.
* 4. Mount the phone page and remove the status line.
*/
const RELOAD_FLAG = 'hermeven.reloadedForHost';
export const STARTUP_TEXT = {
waiting: 'Starting. Looking for the Even app…',
found: 'Even app found. Connecting to your glasses…',
} as const;
export interface BootOptions {
bridgeUrl?: string;
hostWaitMs?: number;
/** Development build: mirror diagnostics to the console. */
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>;
/** Reload hook, replaceable in tests. */
reload?: () => void;
}
export interface Booted {
controller: Controller;
mode: 'even' | 'preview';
runtime: string;
/** Stop background watchers and the controller. */
dispose(): Promise<void>;
}
export async function boot(doc: Document, win: Window, options: BootOptions = {}): Promise<Booted> {
const root = doc.getElementById('app');
const previewRoot = doc.getElementById('preview');
if (!root || !previewRoot) throw new Error('index.html is missing #app or #preview');
const startup = doc.getElementById('startup');
const say = (text: string) => {
const line = startup?.querySelector('[data-startup-status]');
if (line) line.textContent = text;
};
say(STARTUP_TEXT.waiting);
const host = win as unknown as HostWindow;
const detection = await waitForEvenHost(host, options.hostWaitMs === undefined ? {} : { timeoutMs: options.hostWaitMs });
let device: DevicePort;
let mode: Booted['mode'];
let runtime: string;
let stopWatching: () => void = () => undefined;
if (detection.found) {
say(STARTUP_TEXT.found);
const bridge = await waitForEvenAppBridge();
device = new EvenDevice(bridge);
mode = 'even';
runtime = `Even app host (SDK 0.0.16), found after ${detection.waitedMs} ms`;
} else {
previewRoot.hidden = false;
device = new BrowserPreviewDevice(previewRoot);
mode = 'preview';
runtime = `Browser preview: no glasses, no microphone (no Even host after ${detection.waitedMs} ms)`;
// If the host appears later still, reload once into the real mode (once, so a host that
// comes and goes cannot put the page in a reload loop).
stopWatching = watchForLateHost(host, () => {
let already = false;
try {
already = win.sessionStorage.getItem(RELOAD_FLAG) === '1';
win.sessionStorage.setItem(RELOAD_FLAG, '1');
} catch {
already = true;
}
if (!already) (options.reload ?? (() => win.location.reload()))();
});
}
let update: (snapshot: ReturnType<Controller['snapshot']>) => void = () => undefined;
const controller = new Controller({
device,
measure: (text, width) => measureTextWrap(text, width).lineCount,
locale: win.navigator.language || 'en-US',
onChange: (snapshot) => update(snapshot),
...(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,
});
update = mountPhoneUi(root, controller, { bridgeUrl: options.bridgeUrl ?? '', runtime });
// 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());
await controller.start();
update(controller.snapshot());
return {
controller,
mode,
runtime,
async dispose() {
stopWatching();
await controller.stop();
},
};
}