Address Cody review round 8: CODY-014 start-up status; add acceptance contract

CODY-014 The page is no longer blank while it looks for the Even app. The
         static HTML carries an accessible status (#startup, role=status)
         visible from first paint; boot() keeps it until the real page is
         mounted, then removes it. Start-up moved from main.ts to boot.ts so
         the entry-point wiring can be exercised in a DOM. No eager browser
         fallback: the preview is chosen only after the host wait expires.

tests/integration/entryPoint.test.ts loads the real index.html and runs the
real boot() and the real Even Hub SDK in happy-dom: prompt status, preview
after timeout, real Even mode when a callable host appears during the wait
(SDK bridge initialised, HUD page created).

docs/contracts/: acceptance contract, written by the implementer on Dan's
instruction and tied to his quoted requests.
docs/evidence/device/2026-11-21.md: first run on a physical G2, as reported
by Dan plus the bridge log.

Not reviewed. This commit is not deployed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Dan
2026-11-21 12:50:45 -08:00
co-authored by Claude Fable 5.2
parent 09e21f6368
commit 7f055d490f
8 changed files with 605 additions and 64 deletions
+20
View File
@@ -7,8 +7,28 @@
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"
/>
<title>Hermeven</title>
<style>
/* Shown from the first paint, before any script or stylesheet has loaded. */
#startup {
font-family: system-ui, sans-serif;
max-width: 40rem;
margin: 0 auto;
padding: 20px 16px;
}
#startup h1 {
font-size: 1.4rem;
margin: 0 0 8px;
}
</style>
</head>
<body>
<!-- Visible immediately, so the page is never blank while it looks for the Even app.
Removed by the script once the real page is mounted. -->
<div id="startup" role="status" aria-live="polite">
<h1>Hermeven</h1>
<p data-startup-status>Starting. Looking for the Even app…</p>
<noscript><p>Hermeven needs JavaScript to run.</p></noscript>
</div>
<div id="app"></div>
<div id="preview" hidden></div>
<script type="module" src="/src/main.ts"></script>
+116
View File
@@ -0,0 +1,116 @@
import { waitForEvenAppBridge } from '@evenrealities/even_hub_sdk';
import { measureTextWrap } from '@evenrealities/pretext';
import { Controller } 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;
/** 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),
// 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();
// 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();
},
};
}
+7 -64
View File
@@ -1,74 +1,17 @@
import { waitForEvenAppBridge } from '@evenrealities/even_hub_sdk';
import { measureTextWrap } from '@evenrealities/pretext';
import { Controller } 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';
import { boot } from './boot.ts';
import './ui/phone.css';
/**
* Entry point. Inside the Even app (or the Even Hub simulator) the SDK bridge
* is present and the real adapter is used. In a plain browser there is no
* bridge, so a clearly-labelled preview device is used instead: it has no
* microphone and proves nothing about hardware.
* Entry point. All start-up logic is in boot.ts. Inside the Even app (or the Even Hub
* simulator) the SDK bridge is present and the real adapter is used. In a plain browser there
* is no bridge, so a clearly-labelled preview device is used instead: it has no microphone and
* proves nothing about hardware.
*/
const RELOAD_FLAG = 'hermeven.reloadedForHost';
async function resolveDevice(): Promise<{ device: DevicePort; runtime: string }> {
const host = window as unknown as HostWindow;
// Wait briefly for the Even app's connection rather than deciding on the first instant
// (a precaution; see device/hostDetect.ts).
const detection = await waitForEvenHost(host);
if (detection.found) {
const bridge = await waitForEvenAppBridge();
return { device: new EvenDevice(bridge), runtime: `Even app host (SDK 0.0.16), found after ${detection.waitedMs} ms` };
}
const preview = document.getElementById('preview')!;
preview.hidden = false;
// 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).
watchForLateHost(host, () => {
let already = false;
try {
already = sessionStorage.getItem(RELOAD_FLAG) === '1';
sessionStorage.setItem(RELOAD_FLAG, '1');
} catch {
already = true;
}
if (!already) location.reload();
});
return {
device: new BrowserPreviewDevice(preview),
runtime: `Browser preview: no glasses, no microphone (no Even host after ${detection.waitedMs} ms)`,
};
}
const { device, runtime } = await resolveDevice();
const root = document.getElementById('app')!;
let update: (snapshot: ReturnType<Controller['snapshot']>) => void = () => undefined;
const controller = new Controller({
device,
measure: (text, width) => measureTextWrap(text, width).lineCount,
locale: navigator.language || 'en-US',
onChange: (snapshot) => update(snapshot),
// Development builds mirror diagnostics to the console (visible in the simulator and the
// Even dev console). Diagnostics never contain questions, answers or credentials.
onNote: import.meta.env.DEV ? (entry) => console.info(`[hermeven] ${entry.kind}: ${entry.detail}`) : undefined,
});
update = mountPhoneUi(root, controller, {
const { controller } = await boot(document, window, {
bridgeUrl: import.meta.env.VITE_HERMEVEN_BRIDGE_URL ?? '',
runtime,
dev: import.meta.env.DEV,
});
// Never leave the microphone open behind a page that is going away.
window.addEventListener('beforeunload', () => void controller.stop());
await controller.start();
update(controller.snapshot());
// Development-only convenience for automated simulator runs, where nothing can type into the
// phone page: `?bridge=<url>&pair=<code>` pairs on load. Compiled out of production builds.
if (import.meta.env.DEV) {
@@ -0,0 +1,84 @@
# Acceptance contract: droplet deployment and first device run
**Provenance, stated plainly.** This contract was written by Claude, the implementer, on
2026-11-21. Cody's Round 6 and Round 8 reviews asked for a contract independent of the
implementer. Dan, the owner, was asked to supply one and replied, in conversation:
> "you supply the contract. why am I needed for this trivial nonsense?"
So it is supplied here on Dan's instruction. It is not independent of the implementer and does
not pretend to be. What makes it checkable is that every requirement below is tied to something
Dan asked for in his own words (quoted), or to a correction Cody required. Anything the
implementer added beyond those is marked as such.
## What Dan asked for
Quoted from the conversation of 2026-11-21, in order.
1. "that's easy - ip of the hermes droplet is: [the droplet]. Let's tackle that first. I think
you can ssh right in and see what's missing."
2. "pepper is default (also, i'd like to be able to summon other agents by name, but that's
another phase once MVP is done)"
3. On restarting the Hermes gateway to enable its API server: "approved".
4. On the unfinished browser-extension service occupying port 8642: "Can you deprecate that
process, use 8642 for the even bridge, and we'll defer the extension work and assign it a
different port at some point in the future?"
5. "I'm okay with the risk."
6. "we'll use hermeven.xylo.gg"
7. On where the bridge should live, after being told the Hermes server was the simpler choice
for now, no objection; and on capacity: "easier would be to just upgrade the droplet."
## Acceptance criteria
### A. Deployment (from requests 1 to 7)
| # | Criterion |
|---|---|
| A1 | The bridge runs on the Hermes droplet at the commit Cody marked SHIP (`f02715f`), as an unprivileged service, listening on loopback only. |
| A2 | The Hermes API server is enabled on `127.0.0.1:8642` for the `default` profile (Pepper), requires its key, and is not reachable from outside the droplet. |
| A3 | The unfinished extension service and its tunnel are stopped and disabled, not deleted. |
| A4 | The bridge is reachable at `https://hermeven.xylo.gg` with a valid certificate; plain HTTP redirects; ports 8787 and 8642 do not answer from outside. |
| A5 | A question sent through the bridge is answered by Pepper, and a follow-up shows the conversation was kept. |
| A6 | Other agents on the droplet and the n8n webhook are running after the change. |
| A7 | Secrets are not printed, committed or copied off the droplet; previous Hermes configuration is backed up before it is edited. |
### B. Documentation of the deployment (required by Cody, Rounds 6 and 8)
| # | Criterion |
|---|---|
| B1 | The deployment guide works end to end on a clean Ubuntu 24.04 host with no undocumented step. |
| B2 | Dependencies are installed and the client is built as the unprivileged user, only inside `app.new`; the final application tree is root-owned and not writable by the service; secrets, state and model paths are outside every recursive ownership change. |
| B3 | The static client is explicitly installed into `/opt/hermeven/www`, root-owned, directories 0755, files 0644, and is served with the intended security headers. |
| B4 | The README and the dated evidence say exactly which commit is deployed, what the static page was built from, and what remains unverified. |
### C. Page start-up (required by Cody, Round 8, CODY-014)
| # | Criterion |
|---|---|
| C1 | The page shows a meaningful, accessible status from the first paint, before any script runs. |
| C2 | In an ordinary browser the labelled browser preview appears only after the host wait has expired; there is no eager fallback. |
| C3 | A callable Even host appearing during the wait selects the real Even adapter, not the preview. |
| C4 | The start-up status is removed when the real page mounts. |
| C5 | A physical Even-app run shows SDK bridge initialisation and HUD creation for the build under review. |
### D. Standing constraints
| # | Criterion |
|---|---|
| D1 | CODY-001 to CODY-013 stay resolved. |
| D2 | No merge to `main` and no further change to the production host without Dan's explicit go-ahead for that change. |
| D3 | Nothing is claimed as deployed or device-verified unless it was, for that exact build. |
## Out of scope for this contract
Wake word ("Hey Pepper"), automatic end-of-speech detection, summoning other agents by name,
locked-phone operation, a beta-channel install, backups, monitoring and upgrades. Dan has raised
the first three as the next phase; they will get their own contract.
## Added by the implementer, not requested by Dan
- Rotating the Hermes API key (the old one was also in the retired extension's configuration).
- Serving the phone page from the bridge's own hostname.
- `deploy/install.sh` and `tests/deploy/runbook-proof.sh`.
- The precautionary host-detection wait (see `docs/handoff/2026-11-21-cody-round-7.md`: it was
introduced on a wrong diagnosis and kept only as a short precaution).
+65
View File
@@ -0,0 +1,65 @@
# First run on a physical G2, 2026-11-21
**Whose evidence this is.** The glasses and phone were in Dan's hands. The implementer (Claude)
saw nothing on the device: what the HUD showed is Dan's report, quoted. What the server recorded
is the implementer's reading of the bridge log (ids, states and timings; the log holds no
question or answer text).
## Conditions
| Item | Value |
|---|---|
| Glasses | Even G2 (Dan's). Firmware version not recorded. |
| Phone | Android (Dan's). Model, OS and Even app version not recorded. |
| How the app was loaded | QR sideload from inside the Even app's developer section (Even Hub tab), pointing at `https://hermeven.xylo.gg` |
| Phone state | Unlocked, Even app in the foreground |
| Static page build on the server | Built from `09e21f6368deed7917a9f5dcd2eadce5547eca04` (asset `index-84WTYY_U.js`, installed 20:31 UTC) |
| Bridge on the server | `f02715fb6487f4e2ff0adeccfaad2403e1724aa5` |
| Agent | Pepper (Hermes `default` profile), real model |
| Speech-to-text | Built-in `whisper-base` on the server |
## What Dan reported
| Time (UTC) | Dan's words | What it establishes |
|---|---|---|
| about 20:36 | "okay, page is open in the even app, need a code" | The Even app loaded the page from the server. |
| about 20:37 | "paired, runtime says even app host" | Inside the Even app the page found the SDK host (Diagnostics, Runtime), the pairing request reached the bridge, and the app's storage confirmed saving the credential (pairing refuses to complete otherwise). |
| about 20:40 | "Very cool. it worked, but we have a long way to go. When I exited, I just wanted to end the conversation, but it shut down the whole app." | Spoken questions were answered on the glasses. Exiting closed the whole app. |
Dan did not report the exact Runtime line (so the detection delay is unknown), the Diagnostics
"HUD page" value, transcription accuracy, legibility, or how he exited.
## What the server recorded
| Time (UTC) | Event | Transcription | Agent | Total |
|---|---|---|---|---|
| 20:37:30 | device paired | | | |
| 20:38:12 | conversation created | | | |
| 20:38:13 to 20:38:16 | audio turn, succeeded | 1.4 s | 2.2 s | 3.6 s |
| 20:38:26 to 20:38:30 | audio turn, succeeded | 1.1 s | 3.0 s | 4.1 s |
| 20:38:47 to 20:38:54 | audio turn, succeeded | 1.7 s | 4.9 s | 6.6 s |
| 20:39:14 to 20:39:24 | audio turn, succeeded | 1.7 s | 8.7 s | 10.5 s |
Four audio turns means the glasses' microphone was opened and closed by gestures four times and
real G2 audio was transcribed. Totals are measured on the server from accepting the upload to
having the answer; they exclude recording time, upload, polling and drawing on the glasses.
That HUD creation succeeded is inferred, not observed directly: the glasses microphone only
opens after the HUD page exists (Even's documentation), and Dan read answers on the glasses.
## Earlier the same day: a run that was NOT in the Even app
About 20:07 to 20:20 UTC the same page was opened by scanning the QR code with the phone's camera,
which opens it in Chrome. Pairing and a typed question worked (device "Flip", one text turn,
2.1 s). Diagnostics said "Browser preview: no glasses, no microphone". That run shows phone
browser to bridge to Pepper only. The implementer first misread it as an Even-app run; see
`docs/evidence/droplet/2026-11-21.md`.
## Not shown by this run
- Locked phone or backgrounded app. Even's documentation says sideloaded apps stop when the phone
locks; this was not tried.
- The ring, the left temple, the contextual menu, paging a long answer, cancel, the capture cap.
- Accuracy of transcription, legibility, battery, any latency as experienced on the glasses.
- A beta-channel install.
- Any build other than the one named above.
+95
View File
@@ -14,6 +14,7 @@
],
"devDependencies": {
"@types/node": "^22.19.0",
"happy-dom": "^21.0.4",
"tsx": "^4.23.15",
"typescript": "^5.9.3",
"vitest": "^5.1.1"
@@ -1818,6 +1819,23 @@
"undici-types": "~6.21.0"
}
},
"node_modules/@types/whatwg-mimetype": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz",
"integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/ws": {
"version": "8.18.2",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz",
"integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@vitest/mocker": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.1.tgz",
@@ -1971,6 +1989,19 @@
"node": ">=22"
}
},
"node_modules/buffer-image-size": {
"version": "0.6.4",
"resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz",
"integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
},
"engines": {
"node": ">=4.0"
}
},
"node_modules/chai": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz",
@@ -2046,6 +2077,19 @@
"node": ">=8"
}
},
"node_modules/entities": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
"integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.12"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
@@ -2364,6 +2408,25 @@
"integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==",
"license": "ISC"
},
"node_modules/happy-dom": {
"version": "21.0.4",
"resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-21.0.4.tgz",
"integrity": "sha512-tFm+GaLBgo6o0awHnvHaNoraVo27qJ+2tZEtZ+cIa08hXbeitrxAJajLI05hsUy/2/YTKcUjQYzHe5mCcraLBw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": ">=20.0.0",
"@types/whatwg-mimetype": "^3.0.2",
"@types/ws": "^8.18.1",
"buffer-image-size": "^0.6.4",
"entities": "^7.0.1",
"whatwg-mimetype": "^3.0.0",
"ws": "^8.21.0"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/has-property-descriptors": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz",
@@ -3490,6 +3553,16 @@
}
}
},
"node_modules/whatwg-mimetype": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz",
"integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
}
},
"node_modules/why-is-node-running": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz",
@@ -3503,6 +3576,28 @@
"node": ">=20.11"
}
},
"node_modules/ws": {
"version": "8.23.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz",
"integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"packages/contracts": {
"name": "@hermeven/contracts",
"version": "0.1.0",
+1
View File
@@ -28,6 +28,7 @@
},
"devDependencies": {
"@types/node": "^22.19.0",
"happy-dom": "^21.0.4",
"tsx": "^4.23.15",
"typescript": "^5.9.3",
"vitest": "^5.1.1"
+217
View File
@@ -0,0 +1,217 @@
// @vitest-environment happy-dom
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { boot, STARTUP_TEXT, type Booted } from '../../apps/even-client/src/boot.ts';
import { HOST_WAIT_MS } from '../../apps/even-client/src/device/hostDetect.ts';
/**
* CODY-014, at the rendered-page seam: the real index.html markup, the real boot() that main.ts
* calls, the real Even Hub SDK bridge, in a DOM (happy-dom). The Even app host is a stand-in
* object providing `flutter_inappwebview.callHandler`; it is not the Even app and not glasses.
*/
// Resolved from the repository root (vitest's working directory): in this DOM environment
// `import.meta.url` is not a file URL.
const indexHtml = readFileSync(resolve(process.cwd(), 'apps/even-client/index.html'), 'utf8');
const bodyHtml = /<body>([\s\S]*)<\/body>/.exec(indexHtml)![1]!.replace(/<script[\s\S]*?<\/script>/g, '');
interface HostCall {
method: string;
handler: string;
type: string;
}
/** Stand-in for the Even app's WebView host: answers the SDK's calls and records them. */
function fakeEvenHost() {
const calls: HostCall[] = [];
const storage = new Map<string, string>();
// The SDK calls `callHandler('evenAppMessage', { type: 'call_even_app_method', method, data })`
// and awaits the returned value (observed from the published SDK 0.0.16).
const callHandler = async (name: string, raw: unknown) => {
const message = (typeof raw === 'string' ? JSON.parse(raw) : raw) as { type?: string; method?: string; data?: any };
const method = String(message?.method ?? '');
const data = message?.data ?? {};
calls.push({ method, handler: name, type: String(message?.type ?? '') });
switch (method) {
case 'createStartUpPageContainer':
return 0; // StartUpPageCreateResult.success
case 'getLocalStorage':
return storage.get(String(data.key)) ?? '';
case 'setLocalStorage':
storage.set(String(data.key), String(data.value));
return true;
default:
return true;
}
};
return { host: { callHandler }, calls };
}
const visibleText = () => (document.body.textContent ?? '').replace(/\s+/g, ' ').trim();
const diagnostics = () =>
Object.fromEntries([...document.querySelectorAll('details dl dt')].map((dt) => [dt.textContent, dt.nextElementSibling?.textContent ?? '']));
const flush = async (ms: number) => {
await vi.advanceTimersByTimeAsync(ms);
};
let booted: Booted | null = null;
beforeEach(() => {
vi.useFakeTimers();
document.body.innerHTML = bodyHtml;
delete (window as any).flutter_inappwebview;
// window.EvenAppBridge is the SDK's own singleton, created once when the SDK module loads;
// it is left alone, as it would be on a real page.
localStorage.clear();
sessionStorage.clear();
});
afterEach(async () => {
await booted?.dispose();
booted = null;
vi.useRealTimers();
});
describe('the page as served, before any script has run', () => {
it('already shows a meaningful, accessible status instead of a blank page', () => {
const startup = document.getElementById('startup')!;
expect(startup).not.toBeNull();
expect(startup.getAttribute('role')).toBe('status');
expect(startup.getAttribute('aria-live')).toBe('polite');
expect(startup.hasAttribute('hidden')).toBe(false);
expect(startup.textContent).toContain('Hermeven');
expect(startup.textContent).toContain('Looking for the Even app');
// The status is ahead of the (empty) app container in the document, and styled inline so it
// does not depend on the stylesheet or the script having loaded.
expect(indexHtml.indexOf('id="startup"')).toBeLessThan(indexHtml.indexOf('id="app"'));
expect(indexHtml).toMatch(/<style>[\s\S]*#startup[\s\S]*<\/style>/);
expect(indexHtml.indexOf('id="startup"')).toBeLessThan(indexHtml.indexOf('<script'));
});
});
describe('start-up in an ordinary browser (no Even host)', () => {
it('shows the status promptly, does not fall back early, then replaces it with the labelled browser preview', async () => {
const starting = boot(document, window, { bridgeUrl: 'https://bridge.example' });
let settled = false;
void starting.then(() => (settled = true));
// Immediately: a visible status, and nothing else decided.
await flush(0);
const startup = document.getElementById('startup')!;
expect(startup.querySelector('[data-startup-status]')!.textContent).toBe(STARTUP_TEXT.waiting);
expect(visibleText()).toContain('Looking for the Even app');
expect(document.getElementById('preview')!.hidden).toBe(true);
expect(document.getElementById('app')!.children.length).toBe(0);
// Most of the way through the wait: still waiting. No eager browser fallback.
await flush(HOST_WAIT_MS - 100);
expect(settled).toBe(false);
expect(document.getElementById('startup')).not.toBeNull();
expect(document.getElementById('preview')!.hidden).toBe(true);
expect(document.querySelector('.hud')).toBeNull();
expect(document.getElementById('app')!.children.length).toBe(0);
// After the timeout: the preview, clearly labelled, and the status is gone.
await flush(200);
booted = await starting;
expect(booted.mode).toBe('preview');
expect(document.getElementById('startup')).toBeNull();
expect(visibleText()).not.toContain('Looking for the Even app');
const preview = document.getElementById('preview')!;
expect(preview.hidden).toBe(false);
expect(preview.textContent).toContain('Browser preview of the HUD text. Not the glasses');
expect(preview.querySelector('.hud-body')!.textContent).toContain('Not connected');
expect(document.querySelector('#app h1')!.textContent).toBe('Hermeven');
expect(visibleText()).toContain('Pair with your bridge');
expect((document.querySelector('input[type=url]') as HTMLInputElement).value).toBe('https://bridge.example');
expect(diagnostics().Runtime).toBe(`Browser preview: no glasses, no microphone (no Even host after ${HOST_WAIT_MS} ms)`);
});
it('a host that appears after the preview was chosen triggers one reload into the real mode', async () => {
let reloads = 0;
const starting = boot(document, window, { reload: () => (reloads += 1) });
await flush(HOST_WAIT_MS + 50);
booted = await starting;
expect(booted.mode).toBe('preview');
(window as any).flutter_inappwebview = fakeEvenHost().host;
await flush(1200);
await flush(1200);
expect(reloads).toBe(1);
});
});
describe('start-up when a callable Even host appears during the wait', () => {
// Real time here: once a host is present the SDK drives its own timers, which a fake clock
// does not advance. The waits below are short and bounded.
beforeEach(() => vi.useRealTimers());
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
it('selects the real Even adapter, initialises the SDK bridge, creates the HUD page, and never shows the preview', async () => {
const even = fakeEvenHost();
const started = Date.now();
const starting = boot(document, window, { bridgeUrl: 'https://bridge.example' });
await wait(20);
expect(visibleText()).toContain('Looking for the Even app');
expect(document.getElementById('app')!.children.length).toBe(0);
// The host turns up 400 ms into the 2.5 s wait.
await wait(380);
expect(document.getElementById('startup')).not.toBeNull();
(window as any).flutter_inappwebview = even.host;
booted = await starting;
// Well before the timeout: detection reacted to the host, it did not wait it out.
expect(Date.now() - started).toBeLessThan(HOST_WAIT_MS - 500);
expect(booted.mode).toBe('even');
expect(booted.runtime).toMatch(/^Even app host \(SDK 0\.0\.16\), found after [34]\d\d ms$/);
// The SDK's own bridge object exists and really talked to the host, in the SDK's protocol.
expect((window as any).EvenAppBridge).toBeDefined();
const methods = even.calls.map((c) => c.method);
expect(methods).toContain('getLocalStorage');
expect(methods).toContain('createStartUpPageContainer');
expect(even.calls.every((c) => c.handler === 'evenAppMessage' && c.type === 'call_even_app_method')).toBe(true);
// The real page is mounted, the status is gone, and the preview was never shown.
expect(document.getElementById('startup')).toBeNull();
const preview = document.getElementById('preview')!;
expect(preview.hidden).toBe(true);
expect(preview.children.length).toBe(0);
expect(document.querySelector('.hud')).toBeNull();
expect(visibleText()).toContain('Pair with your bridge');
const diag = diagnostics();
expect(diag.Runtime).toContain('Even app host');
expect(diag['HUD page']).toBe('created');
});
it('a host present from the first instant is used without waiting out the timeout', async () => {
const even = fakeEvenHost();
(window as any).flutter_inappwebview = even.host;
const started = Date.now();
booted = await boot(document, window);
expect(Date.now() - started).toBeLessThan(1500);
expect(booted.mode).toBe('even');
expect(booted.runtime).toMatch(/found after \d{1,2} ms$/);
expect(document.getElementById('startup')).toBeNull();
expect(diagnostics()['HUD page']).toBe('created');
});
it('a host that refuses the HUD page is still the Even app, and the page says the HUD was not created', async () => {
const even = fakeEvenHost();
const realHandler = even.host.callHandler;
// 1 = StartUpPageCreateResult.invalid
(even.host as { callHandler: (name: string, raw: unknown) => Promise<unknown> }).callHandler = async (name, raw) => {
const message = (typeof raw === 'string' ? JSON.parse(raw) : raw) as { method?: string };
return message?.method === 'createStartUpPageContainer' ? 1 : realHandler(name, raw);
};
(window as any).flutter_inappwebview = even.host;
booted = await boot(document, window);
expect(booted.mode).toBe('even');
expect(diagnostics()['HUD page']).toBe('not created');
});
});
describe('an object that only looks like a host', () => {
it('without a callable callHandler it is not treated as the Even app', async () => {
(window as any).flutter_inappwebview = {};
const starting = boot(document, window);
await flush(HOST_WAIT_MS + 50);
booted = await starting;
expect(booted.mode).toBe('preview');
});
});