Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4c102a539 | ||
|
|
2a63b7796a | ||
|
|
31ae4efb13 | ||
|
|
f9946a027a | ||
|
|
44ea1148c3 | ||
|
|
e1d183b54d | ||
|
|
75b7ea1eff | ||
|
|
dcb373639e | ||
|
|
bb3a309427 | ||
|
|
c8b4fb0310 | ||
|
|
9394c249ad | ||
|
|
15714bd848 | ||
|
|
344a2288b8 | ||
|
|
3e0468802f | ||
|
|
d8582e99a2 | ||
|
|
3d0edebd13 | ||
|
|
bbde3c86a8 | ||
|
|
1ae105ed18 | ||
|
|
19a9d5e22e | ||
|
|
8171aee75a | ||
|
|
cf2cf66a35 | ||
|
|
38883b38f8 | ||
|
|
d90cd8972a | ||
|
|
fb0a6b926a | ||
|
|
bc00ae9fb1 | ||
|
|
fd992559af | ||
|
|
9cb34b3125 | ||
|
|
b8191a7bd2 | ||
|
|
7f055d490f | ||
|
|
09e21f6368 | ||
|
|
65260911ae | ||
|
|
e5559dc5e7 | ||
|
|
98c7b03aa7 |
@@ -21,6 +21,10 @@ HERMEVEN_DB_PATH=./data/hermeven.sqlite
|
||||
|
||||
# Exact origins of the page that calls the bridge (comma separated, no wildcards).
|
||||
# Read the real value from Diagnostics -> "Page origin" in the phone page.
|
||||
# One wildcard is accepted: the port of a loopback address, written http://127.0.0.1:*
|
||||
# The Even phone app serves an installed app from http://127.0.0.1:<port> and uses a new port
|
||||
# on every launch, so an installed app needs exactly that entry. A page served from the
|
||||
# bridge's own hostname (the QR sideload path) needs no entry at all.
|
||||
HERMEVEN_ALLOWED_ORIGINS=
|
||||
|
||||
# --- Speech-to-text -----------------------------------------------------------
|
||||
|
||||
@@ -7,22 +7,42 @@ Even supplies the microphone, gestures and display. Hermes stays in charge of th
|
||||
identity, memory, conversation, model, tools and approval rules. Hermeven is the glasses app and a
|
||||
small bridge between the two.
|
||||
|
||||
## Status: first software slice, not yet run on glasses
|
||||
## Status: deployed to one server; run in the Even app on one physical G2, with bounded checks
|
||||
|
||||
Physical testing so far is a handful of sessions on one pair of glasses on 2026-11-21 and one
|
||||
report on 2026-11-28. The full
|
||||
device checklist (`docs/device-test-plan.md`) has **not** been completed. Three kinds of evidence
|
||||
are kept apart below and in the evidence files: what Dan observed on the device and reported, what
|
||||
the implementer read from the server's log, and what Cody reproduced independently in review.
|
||||
|
||||
| Path | State |
|
||||
|---|---|
|
||||
| **What is where today** | Server (bridge and static page): `44ea1148c34a271f4fdc565ef71a145adf459b42`. Even account, beta channel: client 0.3.0, built from that commit. This repository's client is **0.4.0, a candidate: not deployed, not uploaded, not on the device.** |
|
||||
| Client, bridge and contract | Implemented. |
|
||||
| Automated tests with fakes (198) | Passing. |
|
||||
| Client in Even's official simulator | Passing (6 scenarios). Simulator only. |
|
||||
| Automated tests with fakes (349) | Passing. |
|
||||
| Client in Even's official simulator | 9 scenarios, run by the implementer, simulator only. Eight run with the menu, hands free and live preview switched off (the tap path and idle exit); the ninth launches the app as shipped and covers the menu and the microphone opening and closing for hands free, with a silent microphone, so no name is ever heard. Live preview is not exercised in the simulator. One unexplained failure of the idle-exit scenario in the Round 19 runs; see `docs/test-evidence.md`. |
|
||||
| Bridge against a real Hermes gateway | Passing (9 scenarios) with a **stub model**. |
|
||||
| Built-in speech-to-text (Whisper, in the bridge) | Passing (11 scenarios) on a real speech recording, including with no network. Not yet on audio from the glasses. |
|
||||
| Running on a droplet | **Not run.** See `docs/deploy-droplet.md`. |
|
||||
| Real model, real tools, approval flow | **Not run.** |
|
||||
| Physical G2, ring, locked-phone use, battery | **Not run.** See `docs/device-test-plan.md`. |
|
||||
| Running on a droplet | Since 2026-11-28 19:06 UTC the server runs commit `44ea1148c34a271f4fdc565ef71a145adf459b42` (bridge and static page), which holds Cody's SHIP FOR TRIAL (Round 18). Checks performed: `docs/evidence/device/2026-11-28.md`; earlier deployments: `docs/evidence/droplet/2026-11-21.md`. |
|
||||
| Phone page in an ordinary phone browser | Paired and answered one typed question (Chrome on Android, reported by Dan). This is **not** the Even app: a browser cannot reach the glasses. |
|
||||
| Phone page inside the Even app, physical G2 | First runs on 2026-11-21, QR-sideloaded, phone unlocked: paired, four spoken questions answered on the glasses. See `docs/evidence/device/2026-11-21.md` for exactly which builds and what was and was not observed. |
|
||||
| Installed as an Even Hub private build ("Pepper", `xylo.hermeven` 0.1.0) | Runs from the Even app with no QR code: paired, and four spoken questions answered on the glasses, including hold-to-talk and one that had the agent send a Telegram message (Dan's report plus the bridge log, 2026-11-21). Needs `HERMEVEN_ALLOWED_ORIGINS=http://127.0.0.1:*` on the bridge. |
|
||||
| Ring, paging, contextual menu, cancel, relaunch with the pairing kept, the system exit dialog on the device | **Not run.** |
|
||||
| Locked phone | First success on 2026-11-21 with the beta build: launched by voice ("Hey Even, open Pepper") and a spoken question answered with the phone locked (Dan's report). The specification's ten-cycle acceptance run has **not** been done. |
|
||||
| Leaving the glasses when idle | 0.1.1 on the device (2026-11-21, Dan's report): after one gesture the app left by itself and Telegram notifications returned to the lenses; after a voice launch with nothing touched it did **not** leave. 0.1.2 starts the countdown however the app was opened; tested with fakes and the simulator, **not installed on the device.** |
|
||||
| More than one agent (swipe at Ready to choose) | 0.2.0. Deployed on 2026-11-22 with three agents; a question sent through the bridge was answered by a second Hermes profile (`docs/evidence/droplet/2026-11-21.md`). Installed on the device and tried by Dan, who reported "All tests check out" without detail (`docs/evidence/device/2026-11-21.md`, sixth session). The agent screens have not been run in the simulator. |
|
||||
| Opening menu (Hands free, Agents); hands-free mode: calling an agent by name ("Wendy, ...") | 0.3.0, which is what is deployed and on beta (`44ea114`). Fakes: passing. Simulator: menu and microphone open/close only (scenario 9). Device: tried by Dan on 2026-11-28, "pretty cool"; a name reached an agent and a different name switched agent. No item-by-item report; section D of the device plan has not been run. `docs/decisions/0004-always-listening.md`, `docs/evidence/device/2026-11-28.md`. |
|
||||
| Words shown while recording (Agents only); "Heard: ..." while the agent works | 0.4.0 candidate. Fakes only. **Not in the simulator, not deployed, not uploaded, not on the device.** `docs/decisions/0005-live-preview.md`. |
|
||||
| Real tools and approval flow | One tool use seen (a Telegram message, reported by Dan). The approval path has **not** been exercised against a real agent. |
|
||||
| Sustained load, backups, monitoring, upgrades on the server | **Not verified.** |
|
||||
| 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.
|
||||
Even's documentation says capture stops if the app's WebView is suspended. That is the first
|
||||
thing to test on a device and it is not known to work.
|
||||
Even's documentation says capture stops if the app's WebView is suspended. What is known so far is
|
||||
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
|
||||
|
||||
@@ -57,18 +77,23 @@ instructions, including building for the glasses, are in `docs/setup.md`.
|
||||
|
||||
| You do | It does |
|
||||
|---|---|
|
||||
| Tap | Start recording. The display shows `● REC` and a timer the whole time. |
|
||||
| Open the app | From 0.3.0: a menu. Swipe to move, tap to open. **Hands free** is first, **Agents** (everything below, as before) second. |
|
||||
| In Hands free: say an agent's name, then your question | The microphone is open while the app is at rest (the status line starts with `●`). "Wendy, what's on my calendar" goes to Wendy. A name alone starts a recording that is sent when you stop speaking. Tap and swipe still work. The app stays on the glasses. |
|
||||
| Tap | Start recording. The display shows `● REC` and a timer the whole time. From 0.4.0, in Agents, the words appear as you speak, a second or two behind; "Heard: ..." shows what was sent while the agent works. |
|
||||
| Tap again | Stop and send. Recording also stops by itself after 30 seconds. |
|
||||
| Hold, speak, release | Push-to-talk: recording starts when the glasses register the hold and is sent when you let go. A hold released in under 0.7 s behaves like a tap. |
|
||||
| Swipe down / up | Next / previous page of the answer. |
|
||||
| Tap on an answer | Ask a follow-up in the same conversation. |
|
||||
| Double tap | Cancel what is in progress, or go back. At "Ready" it opens the system exit dialog. |
|
||||
| Double tap | Cancel what is in progress, or go back. At "Ready" it returns to the menu (closing the microphone if it was hands free); on the menu it opens the system exit dialog. |
|
||||
| Swipe at Ready | From 0.2.0, when the bridge offers more than one agent: choose who to talk to. The name is shown; on an answer a swipe still turns the page. |
|
||||
| Leave it alone | In Hands free the app stays open. On the menu and in Agents, as from 0.1.1: Pepper leaves the glasses by herself (20 s after an answer, 30 s at Ready, 10 s after an error), so the normal screen and notifications return. Call her back from the glasses' menu or with "Hey Even, open Pepper". |
|
||||
| Tap, then long press | The system menu, with "New conversation" and "Cancel request". |
|
||||
|
||||
Cancelling stops the agent as soon as Hermes can; it does not undo anything the agent already did.
|
||||
If the agent needs an approval, the display says so and you approve it where you normally manage
|
||||
the agent. Hermeven never approves anything for you.
|
||||
|
||||
These gestures are a first binding and have only been exercised in the simulator.
|
||||
Tap, hold-to-talk and a quickly released press have been used on a real G2 (2026-11-21, Dan's report). Paging, the menu, cancel and the ring have not.
|
||||
|
||||
## Tests
|
||||
|
||||
@@ -92,8 +117,8 @@ What each suite does and does not show is in `docs/test-evidence.md`.
|
||||
| `docs/bridge-api.md` | The bridge contract. |
|
||||
| `docs/security.md` | Threat model, controls, known gaps. |
|
||||
| `docs/setup.md` | Running, building, operating. |
|
||||
| `docs/deploy-droplet.md` | Running the bridge on a DigitalOcean droplet. Written, not yet run. |
|
||||
| `docs/device-test-plan.md` | The physical-device checklist. Not yet run. |
|
||||
| `docs/deploy-droplet.md` | Running the bridge on a server. Run once for real (`docs/evidence/droplet/2026-11-21.md`); the current steps are proven on a disposable host. |
|
||||
| `docs/device-test-plan.md` | The physical-device checklist. Partially exercised informally on 2026-11-21 (`docs/evidence/device/2026-11-21.md`); the complete checklist has not been run. |
|
||||
| `docs/test-evidence.md` | Commands run and their real results. |
|
||||
| `docs/decisions/` | Decision records. |
|
||||
| `docs/handoff/` | Review handoffs. |
|
||||
@@ -101,5 +126,6 @@ What each suite does and does not show is in `docs/test-evidence.md`.
|
||||
|
||||
## Not in this slice
|
||||
|
||||
Wake words, always-on listening, camera features, text-to-speech, multiple agents, billing, store
|
||||
launch, and running alongside Even's native captions (the public SDK does not offer it).
|
||||
On-device wake-word detection (names are recognised on the bridge), camera features,
|
||||
text-to-speech, billing, store launch, and running alongside Even's native captions (the public
|
||||
SDK does not offer it).
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"package_id": "gg.xylo.hermeven",
|
||||
"package_id": "xylo.hermeven",
|
||||
"edition": "202601",
|
||||
"name": "Hermeven",
|
||||
"version": "0.1.0",
|
||||
"name": "Pepper",
|
||||
"version": "0.4.0",
|
||||
"min_sdk_version": "0.0.16",
|
||||
"entrypoint": "index.html",
|
||||
"permissions": [
|
||||
@@ -13,7 +13,7 @@
|
||||
},
|
||||
{
|
||||
"name": "g2-microphone",
|
||||
"desc": "Records your question from the glasses microphone, only while you have tapped to ask."
|
||||
"desc": "Records your question from the glasses microphone when you tap to ask. In hands-free mode, which you choose on the opening menu, it listens while the app is open for an agent's name and your question."
|
||||
}
|
||||
],
|
||||
"supported_languages": ["en"]
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
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>;
|
||||
/** `false` removes hands-free mode (the microphone then opens only on a tap). */
|
||||
wake?: boolean;
|
||||
/** `false` opens at Ready instead of on the menu. For automated simulator runs. */
|
||||
menu?: boolean;
|
||||
/** `false`: no words shown while recording. For automated simulator runs. */
|
||||
livePreview?: 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),
|
||||
// Hands free needs the glasses' microphone: never in the browser preview.
|
||||
wake: mode === 'even' && options.wake !== false ? {} : null,
|
||||
menu: options.menu !== false,
|
||||
livePreview: mode === 'even' && options.livePreview !== false,
|
||||
...(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();
|
||||
},
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,4 @@
|
||||
import type { AppState } from './reducer.ts';
|
||||
import { currentAgent, menuItems, MODE_LABEL, type AppState } from './reducer.ts';
|
||||
|
||||
/**
|
||||
* HUD geometry. Canvas size and line height are documented by Even
|
||||
@@ -41,8 +41,39 @@ function clock(seconds: number): string {
|
||||
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** The longest question shown back while the agent works; the rest is on the phone. */
|
||||
const HEARD_MAX = 160;
|
||||
|
||||
/** Shown in the status bar for as long as the microphone is open at rest. */
|
||||
export const MIC_OPEN = '● ';
|
||||
|
||||
/**
|
||||
* The names to call, as they are said: the first word of each agent's name. As many as fit
|
||||
* comfortably; the rest are still reachable by swiping.
|
||||
*/
|
||||
function callNames(state: AppState): string {
|
||||
const names: string[] = [];
|
||||
let used = 0;
|
||||
for (const { name } of state.agents) {
|
||||
const word = name.trim().split(/\s+/)[0] ?? name;
|
||||
if (names.length > 0 && used + word.length > 80) return `${names.join(' · ')} …`;
|
||||
names.push(word);
|
||||
used += word.length + 3;
|
||||
}
|
||||
return names.join(' · ');
|
||||
}
|
||||
|
||||
/** Pure: the complete HUD text for a state at a moment in time. */
|
||||
export function renderHud(state: AppState, nowMs: number): HudFrame {
|
||||
const frame = renderFrame(state, nowMs);
|
||||
// The microphone is open and listening for a name: every resting screen says so.
|
||||
const resting = state.phase === 'ready' || state.phase === 'answer' || state.phase === 'error' || state.phase === 'cancelled';
|
||||
return state.wakeListening && resting ? { body: frame.body, status: `${MIC_OPEN}${frame.status}` } : frame;
|
||||
}
|
||||
|
||||
function renderFrame(state: AppState, nowMs: number): HudFrame {
|
||||
// With more than one agent on offer, every screen of an exchange says who it is with.
|
||||
const agent = state.agents.length > 1 ? currentAgent(state) : undefined;
|
||||
switch (state.phase) {
|
||||
case 'unpaired':
|
||||
if (state.storageFault) {
|
||||
@@ -53,26 +84,53 @@ export function renderHud(state: AppState, nowMs: number): HudFrame {
|
||||
}
|
||||
return { body: 'Hermeven\n\nNot connected.\nOpen Hermeven on your phone to pair.', status: 'Double-tap: exit' };
|
||||
|
||||
case 'ready':
|
||||
return {
|
||||
body: state.notice ? `Hermeven\n\n${state.notice}.` : 'Hermeven\n\nReady.',
|
||||
status: 'Tap: ask · Double-tap: exit',
|
||||
};
|
||||
case 'menu': {
|
||||
// Plain ASCII marker: the firmware font silently drops characters it does not have.
|
||||
const lines = menuItems(state).map((mode, i) => `${i === state.menuIndex ? '>' : ' '} ${MODE_LABEL[mode]}`);
|
||||
return { body: `Hermeven\n\n${lines.join('\n')}`, status: lines.length > 1 ? 'Tap: open · Swipe: move · 2×: exit' : 'Tap: open · Double-tap: exit' };
|
||||
}
|
||||
|
||||
case 'ready': {
|
||||
// With a menu, double tap goes back to it; without one it leaves the app.
|
||||
const out = state.menu ? 'menu' : 'exit';
|
||||
const status = agent ? `Tap: ask · Swipe: agent · 2×: ${out}` : `Tap: ask · Double-tap: ${out}`;
|
||||
if (state.wakeListening && !state.notice) {
|
||||
return agent
|
||||
? { body: `${agent.name}\n\nListening. Say a name, then your question:\n${callNames(state)}`, status }
|
||||
: { body: 'Hermeven\n\nListening. Say your agent’s name, then your question.', status };
|
||||
}
|
||||
if (agent) return { body: state.notice ? `${agent.name}\n\n${state.notice}.` : `${agent.name}\n\nReady.`, status };
|
||||
return { body: state.notice ? `Hermeven\n\n${state.notice}.` : 'Hermeven\n\nReady.', status };
|
||||
}
|
||||
|
||||
case 'listening': {
|
||||
const elapsed = state.captureStartedAt === null ? 0 : (nowMs - state.captureStartedAt) / 1000;
|
||||
const cap = state.captureMaxSeconds;
|
||||
const title = agent ? `${agent.name} is listening…` : 'Listening…';
|
||||
const status = state.captureAuto
|
||||
? `● REC ${clock(elapsed)} / ${clock(cap)} · Tap: send · 2×: cancel`
|
||||
: `● REC ${clock(elapsed)} / ${clock(cap)} · Tap or release: send · 2×: cancel`;
|
||||
// Once there are words, they replace the instructions.
|
||||
if (state.preview) return { body: `${title}\n\n${state.preview}`, status };
|
||||
return {
|
||||
body: `Listening…\n\nRecording stops by itself after ${cap} seconds.`,
|
||||
status: `● REC ${clock(elapsed)} / ${clock(cap)} · Tap: send · 2×: cancel`,
|
||||
body: state.captureAuto
|
||||
? `${title}\n\nAsk your question. It is sent when you stop speaking.`
|
||||
: `${title}\n\nRecording stops by itself after ${cap} seconds.`,
|
||||
status,
|
||||
};
|
||||
}
|
||||
|
||||
case 'transcribing':
|
||||
return { body: 'Transcribing…', status: 'Double-tap: cancel' };
|
||||
return { body: state.preview ? `Transcribing…\n\n${state.preview}` : 'Transcribing…', status: 'Double-tap: cancel' };
|
||||
|
||||
case 'thinking':
|
||||
return { body: 'Thinking…', status: 'Double-tap: cancel' };
|
||||
case 'thinking': {
|
||||
const title = agent ? `${agent.name} is thinking…` : 'Thinking…';
|
||||
if (!state.heard) return { body: title, status: 'Double-tap: cancel' };
|
||||
// Asked by voice with nothing pressed: show what was understood, so a mishearing is seen
|
||||
// while it can still be cancelled.
|
||||
const heard = state.heard.length > HEARD_MAX ? `${state.heard.slice(0, HEARD_MAX - 1).trimEnd()}…` : state.heard;
|
||||
return { body: `${title}\n\nHeard: ${heard}`, status: 'Double-tap: cancel' };
|
||||
}
|
||||
|
||||
case 'approval':
|
||||
return {
|
||||
@@ -85,7 +143,7 @@ export function renderHud(state: AppState, nowMs: number): HudFrame {
|
||||
const page = state.pages[state.pageIndex] ?? '';
|
||||
const position = total > 1 ? `${state.pageIndex + 1}/${total} · Swipe: page · ` : '';
|
||||
const partial = state.partial ? 'PARTIAL · ' : '';
|
||||
return { body: page, status: `${partial}${position}Tap: ask` };
|
||||
return { body: page, status: `${partial}${position}${agent ? `${agent.name} · ` : ''}Tap: ask` };
|
||||
}
|
||||
|
||||
case 'cancelled':
|
||||
|
||||
@@ -10,6 +10,8 @@ import type { TurnResult } from '@hermeven/contracts';
|
||||
*/
|
||||
export type Phase =
|
||||
| 'unpaired'
|
||||
/** The opening menu: choose a mode. Nothing records and nothing is in flight. */
|
||||
| 'menu'
|
||||
| 'ready'
|
||||
| 'listening'
|
||||
| 'transcribing'
|
||||
@@ -29,8 +31,37 @@ export interface HudError {
|
||||
retryable: boolean;
|
||||
}
|
||||
|
||||
/** An agent the bridge lets this device talk to. */
|
||||
export interface Agent {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* How the app is being used. Both modes talk to the same agents through the same path; the
|
||||
* only difference is whether the microphone listens for a name while at rest.
|
||||
* - agents: the microphone opens on a tap, and the app leaves the glasses when idle.
|
||||
* - handsfree: the microphone is open at rest, and the app stays until closed.
|
||||
*/
|
||||
export type Mode = 'agents' | 'handsfree';
|
||||
|
||||
export const MODE_LABEL: Record<Mode, string> = { handsfree: 'Hands free', agents: 'Agents' };
|
||||
|
||||
export interface AppState {
|
||||
phase: Phase;
|
||||
/** The app opens on a menu, and double tap at Ready goes back to it (instead of exiting). */
|
||||
menu: boolean;
|
||||
menuIndex: number;
|
||||
mode: Mode;
|
||||
/** Hands free can be offered: this build has it, and nothing has said the bridge cannot do it. */
|
||||
handsFree: boolean;
|
||||
/**
|
||||
* The agents the bridge offers, default first. Empty when there is only one (or the bridge
|
||||
* predates agent selection): nothing about agents is then shown or sent.
|
||||
*/
|
||||
agents: Agent[];
|
||||
/** The agent questions go to. Null = the default (the first in `agents`). */
|
||||
agentId: string | null;
|
||||
/**
|
||||
* Bumped whenever the user starts, cancels or abandons something. Every
|
||||
* asynchronous effect carries the generation it was issued under, and an
|
||||
@@ -45,6 +76,22 @@ export interface AppState {
|
||||
requestId: string | null;
|
||||
captureStartedAt: number | null;
|
||||
captureMaxSeconds: number;
|
||||
/** The recording was started by saying an agent's name: it sends itself when the speaker stops. */
|
||||
captureAuto: boolean;
|
||||
/**
|
||||
* The microphone is open at rest, listening for an agent's name. Reported by the controller
|
||||
* from what the microphone actually did, so the HUD's indicator is never a guess.
|
||||
*/
|
||||
wakeListening: boolean;
|
||||
/** The request in flight was spoken (recorded), not typed. */
|
||||
spoken: boolean;
|
||||
/** The spoken question as the bridge transcribed it. Shown while the agent works. */
|
||||
heard: string | null;
|
||||
/**
|
||||
* The words of the recording in progress, as far as they have been transcribed. Already cut
|
||||
* by the controller to what fits the screen. A preview only: it is never what is sent.
|
||||
*/
|
||||
preview: string | null;
|
||||
pages: string[];
|
||||
pageIndex: number;
|
||||
/** The answer is a partial one (agent stopped short). Shown on the HUD. */
|
||||
@@ -64,6 +111,12 @@ export interface AppState {
|
||||
|
||||
export const initialState: AppState = {
|
||||
phase: 'unpaired',
|
||||
menu: false,
|
||||
menuIndex: 0,
|
||||
mode: 'agents',
|
||||
handsFree: false,
|
||||
agents: [],
|
||||
agentId: null,
|
||||
generation: 0,
|
||||
conversationId: null,
|
||||
conversationEpoch: 0,
|
||||
@@ -71,6 +124,11 @@ export const initialState: AppState = {
|
||||
requestId: null,
|
||||
captureStartedAt: null,
|
||||
captureMaxSeconds: 30,
|
||||
captureAuto: false,
|
||||
wakeListening: false,
|
||||
spoken: false,
|
||||
heard: null,
|
||||
preview: null,
|
||||
pages: [],
|
||||
pageIndex: 0,
|
||||
partial: false,
|
||||
@@ -82,8 +140,40 @@ export const initialState: AppState = {
|
||||
};
|
||||
|
||||
export type AppEvent =
|
||||
| { type: 'init'; paired: boolean; conversationId: string | null; captureMaxSeconds: number; resumeRequestId: string | null; storageFault?: boolean }
|
||||
| {
|
||||
type: 'init';
|
||||
paired: boolean;
|
||||
conversationId: string | null;
|
||||
captureMaxSeconds: number;
|
||||
resumeRequestId: string | null;
|
||||
storageFault?: boolean;
|
||||
agents?: Agent[];
|
||||
agentId?: string | null;
|
||||
/** Open on the menu. Without it the app opens at Ready, hands free if that is available. */
|
||||
menu?: boolean;
|
||||
handsFree?: boolean;
|
||||
}
|
||||
/** Hands free turned out not to be possible (the bridge cannot do it): fall back to Agents. */
|
||||
| { type: 'handsfree_lost' }
|
||||
/** The user picked another agent (a swipe at Ready). `conversationId` is that agent's own, if it has one. */
|
||||
| { type: 'agent_selected'; agentId: string; conversationId: string | null }
|
||||
/**
|
||||
* The current agent is no longer offered and nothing is in flight with it: fall back to the
|
||||
* default agent and ITS conversation. Unlike a selection this applies on any resting screen,
|
||||
* and leaves what is on screen (the removed agent's last answer or error) in place.
|
||||
*/
|
||||
| { type: 'agent_reconciled'; agentId: string; conversationId: string | null }
|
||||
| { type: 'unpaired' }
|
||||
/**
|
||||
* An agent was addressed by name and the question followed in the same breath ("Wendy, what
|
||||
* time is it"). `agentId` and `conversationId` are that agent's; null agent = no choice offered.
|
||||
*/
|
||||
| { type: 'wake_text'; freshId: string; agentId: string | null; conversationId: string | null; text: string }
|
||||
/** Only the name was said: record what follows and send it when the speaker stops. */
|
||||
| { type: 'wake_listen'; freshId: string; agentId: string | null; conversationId: string | null }
|
||||
/** A recording started by name heard nothing: back to rest, nothing sent. */
|
||||
| { type: 'capture_abandoned'; generation: number }
|
||||
| { type: 'wake_status'; listening: boolean }
|
||||
/** Semantic actions. `freshId` is a new UUID supplied by the caller in case a turn starts. */
|
||||
| { type: 'activate'; freshId: string }
|
||||
| { type: 'back' }
|
||||
@@ -93,6 +183,8 @@ export type AppEvent =
|
||||
| { type: 'cancel' }
|
||||
| { type: 'submit_text'; freshId: string; text: string }
|
||||
| { type: 'capture_started'; generation: number; at: number }
|
||||
/** The words so far in the recording being made (already fitted to the screen). */
|
||||
| { type: 'capture_preview'; generation: number; text: string }
|
||||
| { type: 'capture_failed'; generation: number; reason: 'mic_refused' | 'mic_stalled' | 'empty' }
|
||||
| { type: 'capture_limit'; generation: number }
|
||||
| { type: 'conversation_created'; epoch: number; conversationId: string }
|
||||
@@ -108,7 +200,7 @@ export type AppEvent =
|
||||
| { type: 'app_exit' };
|
||||
|
||||
export type Effect =
|
||||
| { type: 'start_capture'; generation: number }
|
||||
| { type: 'start_capture'; generation: number; auto?: boolean }
|
||||
| { type: 'stop_capture_and_submit'; generation: number; requestId: string }
|
||||
| { type: 'discard_capture' }
|
||||
| { type: 'submit_text'; generation: number; requestId: string; text: string }
|
||||
@@ -126,11 +218,26 @@ export interface Step {
|
||||
const IDLE: ReadonlySet<Phase> = new Set(['ready', 'answer', 'error', 'cancelled']);
|
||||
const IN_FLIGHT: ReadonlySet<Phase> = new Set(['transcribing', 'thinking', 'approval']);
|
||||
|
||||
/** The menu's entries, in order. Hands free comes first whenever it can be offered. */
|
||||
export function menuItems(state: Pick<AppState, 'handsFree'>): Mode[] {
|
||||
return state.handsFree ? ['handsfree', 'agents'] : ['agents'];
|
||||
}
|
||||
|
||||
/** The agent questions go to now, or undefined when the bridge offers no choice. */
|
||||
export function currentAgent(state: AppState): Agent | undefined {
|
||||
if (state.agents.length === 0) return undefined;
|
||||
return state.agents.find((a) => a.id === state.agentId) ?? state.agents[0];
|
||||
}
|
||||
|
||||
function clearTurn(state: AppState): AppState {
|
||||
return {
|
||||
...state,
|
||||
requestId: null,
|
||||
captureStartedAt: null,
|
||||
captureAuto: false,
|
||||
spoken: false,
|
||||
heard: null,
|
||||
preview: null,
|
||||
pages: [],
|
||||
pageIndex: 0,
|
||||
partial: false,
|
||||
@@ -145,6 +252,24 @@ function same(state: AppState): Step {
|
||||
return { state, effects: [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn to the agent that was addressed by name, with its own conversation. Null when that
|
||||
* agent is not one on offer. A change of agent or conversation starts a new conversation epoch,
|
||||
* so a conversation still being created for the previous one cannot land here.
|
||||
*/
|
||||
function address(state: AppState, agentId: string | null, conversationId: string | null): AppState | null {
|
||||
if (state.agents.length > 0 && agentId !== null && !state.agents.some((a) => a.id === agentId)) return null;
|
||||
const sameAgent = state.agents.length === 0 || agentId === null || agentId === currentAgent(state)?.id;
|
||||
if (sameAgent && conversationId === state.conversationId) return state;
|
||||
return {
|
||||
...state,
|
||||
agentId: sameAgent ? state.agentId : agentId,
|
||||
conversationId,
|
||||
conversationEpoch: state.conversationEpoch + 1,
|
||||
creatingConversation: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** Abandon whatever is in progress. The generation bump is what silences late results. */
|
||||
function abandon(state: AppState): Step {
|
||||
const effects: Effect[] = [];
|
||||
@@ -169,6 +294,12 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
conversationId: event.conversationId,
|
||||
conversationEpoch: state.conversationEpoch + 1,
|
||||
storageFault: event.storageFault === true,
|
||||
agents: event.agents ?? [],
|
||||
agentId: event.agentId ?? null,
|
||||
menu: event.menu === true,
|
||||
handsFree: event.handsFree === true,
|
||||
// With a menu, hands free is something the user chooses. Without one it is simply on.
|
||||
mode: event.menu !== true && event.handsFree === true ? 'handsfree' : 'agents',
|
||||
};
|
||||
if (!event.paired) return same({ ...base, phase: 'unpaired' });
|
||||
if (event.resumeRequestId) {
|
||||
@@ -179,7 +310,49 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
effects: [{ type: 'poll', generation: base.generation, requestId: event.resumeRequestId }],
|
||||
};
|
||||
}
|
||||
return same({ ...base, phase: 'ready' });
|
||||
return same({ ...base, phase: base.menu ? 'menu' : 'ready' });
|
||||
}
|
||||
|
||||
case 'handsfree_lost': {
|
||||
if (!state.handsFree) return same(state);
|
||||
const wasOn = state.mode === 'handsfree';
|
||||
return same({
|
||||
...state,
|
||||
handsFree: false,
|
||||
mode: 'agents',
|
||||
menuIndex: 0,
|
||||
wakeListening: false,
|
||||
notice: wasOn && state.phase === 'ready' ? 'Hands free is not available' : state.notice,
|
||||
});
|
||||
}
|
||||
|
||||
case 'agent_selected': {
|
||||
// Only from Ready: never while something is recording, in flight or on screen. Each agent
|
||||
// has its own conversation, so the conversation is swapped with it, under a new epoch so a
|
||||
// conversation still being created for the previous agent cannot land on this one.
|
||||
if (state.phase !== 'ready') return same(state);
|
||||
if (!state.agents.some((a) => a.id === event.agentId)) return same(state);
|
||||
if (event.agentId === currentAgent(state)?.id) return same(state);
|
||||
return same({
|
||||
...clearTurn(state),
|
||||
phase: 'ready',
|
||||
generation: state.generation + 1,
|
||||
agentId: event.agentId,
|
||||
conversationId: event.conversationId,
|
||||
conversationEpoch: state.conversationEpoch + 1,
|
||||
creatingConversation: false,
|
||||
});
|
||||
}
|
||||
|
||||
case 'agent_reconciled': {
|
||||
if (!IDLE.has(state.phase)) return same(state);
|
||||
return same({
|
||||
...state,
|
||||
agentId: event.agentId,
|
||||
conversationId: event.conversationId,
|
||||
conversationEpoch: state.conversationEpoch + 1,
|
||||
creatingConversation: false,
|
||||
});
|
||||
}
|
||||
|
||||
case 'unpaired': {
|
||||
@@ -195,7 +368,44 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
};
|
||||
}
|
||||
|
||||
case 'wake_text': {
|
||||
if (!IDLE.has(state.phase)) return same(state);
|
||||
const addressed = address(state, event.agentId, event.conversationId);
|
||||
if (!addressed) return same(state);
|
||||
const generation = state.generation + 1;
|
||||
return {
|
||||
state: { ...clearTurn(addressed), phase: 'thinking', generation, requestId: event.freshId, heard: event.text },
|
||||
effects: [{ type: 'submit_text', generation, requestId: event.freshId, text: event.text }],
|
||||
};
|
||||
}
|
||||
|
||||
case 'wake_listen': {
|
||||
if (!IDLE.has(state.phase)) return same(state);
|
||||
const addressed = address(state, event.agentId, event.conversationId);
|
||||
if (!addressed) return same(state);
|
||||
const generation = state.generation + 1;
|
||||
return {
|
||||
state: { ...clearTurn(addressed), phase: 'listening', generation, requestId: event.freshId, captureAuto: true },
|
||||
effects: [{ type: 'start_capture', generation, auto: true }],
|
||||
};
|
||||
}
|
||||
|
||||
case 'capture_abandoned': {
|
||||
if (event.generation !== state.generation || state.phase !== 'listening') return same(state);
|
||||
return {
|
||||
state: { ...clearTurn(state), phase: 'ready', generation: state.generation + 1 },
|
||||
effects: [{ type: 'discard_capture' }],
|
||||
};
|
||||
}
|
||||
|
||||
case 'wake_status':
|
||||
return same(event.listening === state.wakeListening ? state : { ...state, wakeListening: event.listening });
|
||||
|
||||
case 'activate': {
|
||||
if (state.phase === 'menu') {
|
||||
const mode = menuItems(state)[state.menuIndex] ?? 'agents';
|
||||
return same({ ...clearTurn(state), phase: 'ready', mode, generation: state.generation + 1 });
|
||||
}
|
||||
if (IDLE.has(state.phase)) {
|
||||
const generation = state.generation + 1;
|
||||
return {
|
||||
@@ -205,7 +415,7 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
}
|
||||
if (state.phase === 'listening' && state.requestId) {
|
||||
return {
|
||||
state: { ...state, phase: 'transcribing', captureStartedAt: null },
|
||||
state: { ...state, phase: 'transcribing', captureStartedAt: null, spoken: true },
|
||||
effects: [{ type: 'stop_capture_and_submit', generation: state.generation, requestId: state.requestId }],
|
||||
};
|
||||
}
|
||||
@@ -222,13 +432,14 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
case 'capture_limit': {
|
||||
if (event.generation !== state.generation || state.phase !== 'listening' || !state.requestId) return same(state);
|
||||
return {
|
||||
state: { ...state, phase: 'transcribing', captureStartedAt: null },
|
||||
state: { ...state, phase: 'transcribing', captureStartedAt: null, spoken: true },
|
||||
effects: [{ type: 'stop_capture_and_submit', generation: state.generation, requestId: state.requestId }],
|
||||
};
|
||||
}
|
||||
|
||||
case 'submit_text': {
|
||||
if (!IDLE.has(state.phase)) return same(state);
|
||||
// Typed on the phone. Also accepted on the menu: it does not need a mode.
|
||||
if (!IDLE.has(state.phase) && state.phase !== 'menu') return same(state);
|
||||
const generation = state.generation + 1;
|
||||
return {
|
||||
state: { ...clearTurn(state), phase: 'thinking', generation, requestId: event.freshId },
|
||||
@@ -237,7 +448,11 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
}
|
||||
|
||||
case 'back': {
|
||||
if (state.phase === 'ready' || state.phase === 'unpaired') return { state, effects: [{ type: 'exit_dialog' }] };
|
||||
if (state.phase === 'ready' && state.menu) {
|
||||
// Leaving a mode. Hands free ends here: the microphone closes with it.
|
||||
return same({ ...clearTurn(state), phase: 'menu', mode: 'agents', menuIndex: 0, generation: state.generation + 1 });
|
||||
}
|
||||
if (state.phase === 'ready' || state.phase === 'unpaired' || state.phase === 'menu') return { state, effects: [{ type: 'exit_dialog' }] };
|
||||
if (state.phase === 'listening' || IN_FLIGHT.has(state.phase) || state.phase === 'disconnected') return abandon(state);
|
||||
// answer / error / cancelled: step back to the root page.
|
||||
return same({ ...clearTurn(state), phase: 'ready' });
|
||||
@@ -250,8 +465,12 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
|
||||
case 'next_page':
|
||||
case 'prev_page': {
|
||||
if (state.phase !== 'answer') return same(state);
|
||||
const delta = event.type === 'next_page' ? 1 : -1;
|
||||
if (state.phase === 'menu') {
|
||||
const menuIndex = Math.min(menuItems(state).length - 1, Math.max(0, state.menuIndex + delta));
|
||||
return same(menuIndex === state.menuIndex ? state : { ...state, menuIndex });
|
||||
}
|
||||
if (state.phase !== 'answer') return same(state);
|
||||
const pageIndex = Math.min(state.pages.length - 1, Math.max(0, state.pageIndex + delta));
|
||||
return same(pageIndex === state.pageIndex ? state : { ...state, pageIndex });
|
||||
}
|
||||
@@ -296,6 +515,11 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
return same({ ...state, captureStartedAt: event.at });
|
||||
}
|
||||
|
||||
case 'capture_preview': {
|
||||
if (event.generation !== state.generation || state.phase !== 'listening') return same(state);
|
||||
return same(event.text === state.preview ? state : { ...state, preview: event.text || null });
|
||||
}
|
||||
|
||||
case 'capture_failed': {
|
||||
if (event.generation !== state.generation) return same(state);
|
||||
if (state.phase !== 'listening' && state.phase !== 'transcribing') return same(state);
|
||||
@@ -316,9 +540,13 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
if (!IN_FLIGHT.has(state.phase) && state.phase !== 'disconnected') return same(state);
|
||||
const result = event.result;
|
||||
if (!result.terminal) {
|
||||
const phase: Phase =
|
||||
result.state === 'transcribing' ? 'transcribing' : result.state === 'approval_required' ? 'approval' : 'thinking';
|
||||
return same({ ...state, phase, disconnectedFrom: null, canResend: false });
|
||||
// A recording the bridge has accepted but not yet started on is still being transcribed.
|
||||
const waiting = result.state === 'transcribing' || (result.state === 'accepted' && state.spoken && !result.input_text);
|
||||
const phase: Phase = waiting ? 'transcribing' : result.state === 'approval_required' ? 'approval' : 'thinking';
|
||||
// Once the bridge has the transcript of a spoken question, that is what the agent is
|
||||
// being sent, and it is shown in place of the preview.
|
||||
const heard = state.heard ?? (state.spoken && !waiting ? (result.input_text ?? null) : null);
|
||||
return same({ ...state, phase, heard, preview: waiting ? state.preview : null, disconnectedFrom: null, canResend: false });
|
||||
}
|
||||
const settled = { ...clearTurn(state), requestId: state.requestId };
|
||||
switch (result.outcome) {
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* Finds stretches of speech in a continuous microphone stream, by loudness alone.
|
||||
*
|
||||
* Pure: no clock (time is counted in samples), no I/O. It is not a speech recogniser and does
|
||||
* not know words; it only decides "someone started talking" and "they stopped", so that the
|
||||
* app can send one utterance at a time instead of a never-ending stream.
|
||||
*
|
||||
* Audio is 16 kHz signed 16-bit little-endian mono (the only format the app handles). It is
|
||||
* examined in 20 ms windows. A window is "voiced" when its level is clearly above the
|
||||
* background, which is tracked continuously while nobody is speaking.
|
||||
*
|
||||
* NOT device-tested: the thresholds are first guesses for a microphone whose levels have not
|
||||
* been measured (see docs/device-test-plan.md).
|
||||
*/
|
||||
export interface SegmenterOptions {
|
||||
/** A pause this long ends the utterance. */
|
||||
endSilenceMs: number;
|
||||
/** Less voiced sound than this in total is a click or a cough, not an utterance. */
|
||||
minSpeechMs: number;
|
||||
/** Audio kept from just before speech was detected, so the first syllable is not clipped. */
|
||||
prerollMs: number;
|
||||
/** An utterance is cut off (and still delivered) at this length. */
|
||||
maxMs: number;
|
||||
/** A window is never voiced below this RMS level (full scale is 32768). */
|
||||
minRms: number;
|
||||
/** A window is voiced when its level is at least this many times the background level. */
|
||||
ratio: number;
|
||||
}
|
||||
|
||||
export const WAKE_SEGMENTER: SegmenterOptions = {
|
||||
endSilenceMs: 700,
|
||||
minSpeechMs: 240,
|
||||
prerollMs: 400,
|
||||
maxMs: 30_000,
|
||||
minRms: 260,
|
||||
ratio: 3,
|
||||
};
|
||||
|
||||
export type SegmentEvent =
|
||||
| { type: 'start' }
|
||||
/** The utterance, from the preroll to the end of the closing pause. */
|
||||
| { type: 'end'; pcm: Uint8Array }
|
||||
/** What looked like speech was too short to be an utterance. */
|
||||
| { type: 'discard' };
|
||||
|
||||
const WINDOW_BYTES = 640; // 20 ms
|
||||
const WINDOW_MS = 20;
|
||||
/** This many voiced windows in a row start an utterance. */
|
||||
const ONSET_WINDOWS = 3;
|
||||
|
||||
export class SpeechSegmenter {
|
||||
private options: SegmenterOptions;
|
||||
/** Bytes that do not yet fill a window. */
|
||||
private carry = new Uint8Array(0);
|
||||
/** Recent windows while nobody is speaking: the preroll. */
|
||||
private recent: Uint8Array[] = [];
|
||||
/** Windows of the utterance in progress. */
|
||||
private speech: Uint8Array[] | null = null;
|
||||
private voicedRun = 0;
|
||||
private voicedWindows = 0;
|
||||
private silentRun = 0;
|
||||
private levelSum = 0;
|
||||
/** Background level, learned while nobody is speaking. */
|
||||
private floor = 0;
|
||||
|
||||
constructor(options: SegmenterOptions = WAKE_SEGMENTER) {
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
/** Someone is talking right now (an utterance has started and not yet ended). */
|
||||
get speaking(): boolean {
|
||||
return this.speech !== null;
|
||||
}
|
||||
|
||||
/** Change the timing rules from the next window on, without losing what has been heard. */
|
||||
configure(options: SegmenterOptions): void {
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
/** Forget everything heard so far, keeping what was learned about the background level. */
|
||||
reset(): void {
|
||||
this.carry = new Uint8Array(0);
|
||||
this.recent = [];
|
||||
this.speech = null;
|
||||
this.voicedRun = 0;
|
||||
this.voicedWindows = 0;
|
||||
this.silentRun = 0;
|
||||
this.levelSum = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything currently held: the utterance in progress, or else the preroll. Used when a
|
||||
* recording takes over from listening, so that what was already being said is not lost.
|
||||
*/
|
||||
buffered(): Uint8Array {
|
||||
return concat(this.speech ?? this.recent);
|
||||
}
|
||||
|
||||
push(pcm: Uint8Array): SegmentEvent[] {
|
||||
const events: SegmentEvent[] = [];
|
||||
let data = pcm;
|
||||
if (this.carry.length) {
|
||||
data = new Uint8Array(this.carry.length + pcm.length);
|
||||
data.set(this.carry);
|
||||
data.set(pcm, this.carry.length);
|
||||
}
|
||||
let offset = 0;
|
||||
for (; offset + WINDOW_BYTES <= data.length; offset += WINDOW_BYTES) {
|
||||
this.window(data.slice(offset, offset + WINDOW_BYTES), events);
|
||||
}
|
||||
this.carry = data.slice(offset);
|
||||
return events;
|
||||
}
|
||||
|
||||
private window(win: Uint8Array, events: SegmentEvent[]): void {
|
||||
const level = rms(win);
|
||||
const voiced = level >= Math.max(this.options.minRms, this.floor * this.options.ratio);
|
||||
|
||||
if (!this.speech) {
|
||||
this.recent.push(win);
|
||||
const keep = Math.max(ONSET_WINDOWS, Math.ceil(this.options.prerollMs / WINDOW_MS));
|
||||
if (this.recent.length > keep) this.recent.shift();
|
||||
if (!voiced) {
|
||||
this.voicedRun = 0;
|
||||
// Follows a quieter room at once and a louder one slowly.
|
||||
this.floor = this.floor === 0 || level < this.floor ? level : this.floor * 0.98 + level * 0.02;
|
||||
return;
|
||||
}
|
||||
this.voicedRun += 1;
|
||||
if (this.voicedRun < ONSET_WINDOWS) return;
|
||||
this.speech = this.recent;
|
||||
this.recent = [];
|
||||
this.voicedWindows = this.voicedRun;
|
||||
this.voicedRun = 0;
|
||||
this.silentRun = 0;
|
||||
this.levelSum = 0;
|
||||
events.push({ type: 'start' });
|
||||
return;
|
||||
}
|
||||
|
||||
this.speech.push(win);
|
||||
this.levelSum += level;
|
||||
if (voiced) {
|
||||
this.voicedWindows += 1;
|
||||
this.silentRun = 0;
|
||||
} else {
|
||||
this.silentRun += 1;
|
||||
}
|
||||
const paused = this.silentRun * WINDOW_MS >= this.options.endSilenceMs;
|
||||
const tooLong = this.speech.length * WINDOW_MS >= this.options.maxMs;
|
||||
if (!paused && !tooLong) return;
|
||||
|
||||
const speech = this.speech;
|
||||
const enough = this.voicedWindows * WINDOW_MS >= this.options.minSpeechMs;
|
||||
if (tooLong && !paused) {
|
||||
// Never a pause in all that time: this is a steady noise, not a voice. Treat its level as
|
||||
// the new background so the next thing delivered is something that stands out from it.
|
||||
this.floor = this.levelSum / speech.length;
|
||||
}
|
||||
this.speech = null;
|
||||
this.voicedWindows = 0;
|
||||
this.silentRun = 0;
|
||||
events.push(enough ? { type: 'end', pcm: concat(speech) } : { type: 'discard' });
|
||||
}
|
||||
}
|
||||
|
||||
function rms(win: Uint8Array): number {
|
||||
let sum = 0;
|
||||
const samples = win.length >> 1;
|
||||
for (let i = 0; i < samples; i++) {
|
||||
let v = win[2 * i]! | (win[2 * i + 1]! << 8);
|
||||
if (v & 0x8000) v -= 0x10000;
|
||||
sum += v * v;
|
||||
}
|
||||
return Math.sqrt(sum / samples);
|
||||
}
|
||||
|
||||
function concat(chunks: Uint8Array[]): Uint8Array {
|
||||
let total = 0;
|
||||
for (const chunk of chunks) total += chunk.length;
|
||||
const out = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
out.set(chunk, offset);
|
||||
offset += chunk.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -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.
|
||||
@@ -170,10 +184,52 @@ export class EvenDevice implements DevicePort {
|
||||
|
||||
onEvent(listener: (event: DeviceEvent) => void): () => void {
|
||||
return this.bridge.onEvenHubEvent((event) => {
|
||||
for (const normalized of normalizeEvent(event as RawEvenHubEvent)) listener(normalized);
|
||||
const normalized = normalizeEvent(event as RawEvenHubEvent);
|
||||
this.recordInput(event as RawEvenHubEvent, normalized);
|
||||
for (const one of normalized) listener(one);
|
||||
});
|
||||
}
|
||||
|
||||
// ---- input diagnostics: what the host has delivered, by type only -------------------
|
||||
private input = { gestures: 0, audioFrames: 0, unrecognised: 0, last: 'none yet', lastAt: 0 };
|
||||
private readonly inputListeners = new Set<() => void>();
|
||||
|
||||
private recordInput(raw: RawEvenHubEvent, normalized: DeviceEvent[]): void {
|
||||
const audioOnly = normalized.length > 0 && normalized.every((e) => e.type === 'audio');
|
||||
if (audioOnly) {
|
||||
// Counted, not announced: frames arrive ten times a second.
|
||||
this.input.audioFrames += 1;
|
||||
return;
|
||||
}
|
||||
// Envelope names and numeric type codes only. Never payload content.
|
||||
const envelopes = (['sysEvent', 'textEvent', 'listEvent', 'menuItemClickEvent'] as const)
|
||||
.filter((key) => raw[key] !== undefined)
|
||||
.map((key) => {
|
||||
const env = raw[key] as { eventType?: number; eventSource?: number; itemID?: number };
|
||||
const parts = [`type=${env.eventType ?? 'none'}`];
|
||||
if (env.eventSource !== undefined) parts.push(`source=${env.eventSource}`);
|
||||
if (env.itemID !== undefined) parts.push(`item=${env.itemID}`);
|
||||
return `${key}(${parts.join(',')})`;
|
||||
});
|
||||
const meaning = normalized.filter((e) => e.type !== 'audio').map((e) => e.type);
|
||||
if (meaning.length) this.input.gestures += 1;
|
||||
else this.input.unrecognised += 1;
|
||||
this.input.last = `${envelopes.join('+') || 'no known envelope'} -> ${meaning.join(',') || 'ignored'}`;
|
||||
this.input.lastAt = Date.now();
|
||||
for (const l of this.inputListeners) l();
|
||||
}
|
||||
|
||||
inputSummary(): string {
|
||||
const { gestures, audioFrames, unrecognised, last, lastAt } = this.input;
|
||||
const when = lastAt ? ` at ${new Date(lastAt).toISOString().slice(11, 19)} UTC` : '';
|
||||
return `${gestures} gesture/lifecycle event(s), ${unrecognised} ignored, ${audioFrames} audio frame(s); last: ${last}${when}`;
|
||||
}
|
||||
|
||||
onInputActivity(listener: () => void): () => void {
|
||||
this.inputListeners.add(listener);
|
||||
return () => this.inputListeners.delete(listener);
|
||||
}
|
||||
|
||||
onConnection(listener: (connected: boolean) => void): () => void {
|
||||
return this.bridge.onDeviceStatusChanged((status) => {
|
||||
if (status.connectType === DeviceConnectType.Connected) listener(true);
|
||||
@@ -192,6 +248,40 @@ export class EvenDevice implements DevicePort {
|
||||
await this.enqueue(() => this.bridge.shutDownPageContainer(1), false);
|
||||
}
|
||||
|
||||
async exitNow(): Promise<boolean> {
|
||||
// Mode 0: leave immediately. The Even app then closes the phone-side page too.
|
||||
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 {
|
||||
this.launchListeners.add(listener);
|
||||
if (this.launchSource) listener(this.launchSource);
|
||||
return () => this.launchListeners.delete(listener);
|
||||
}
|
||||
|
||||
async storageGet(key: string): Promise<StorageRead> {
|
||||
const read = await this.enqueueBounded<string | null>(() => this.bridge.getLocalStorage(key), null);
|
||||
// A timeout or a host error is "unknown", not "empty": the caller must not conclude that
|
||||
|
||||
@@ -24,6 +24,10 @@ export const MENU_ITEM = { NEW_CONVERSATION: 1, CANCEL: 2 } as const;
|
||||
export type DeviceEvent =
|
||||
| { type: 'tap' }
|
||||
| { type: 'double_tap' }
|
||||
/** The touch has been held long enough for the glasses to call it a long press. */
|
||||
| { type: 'long_press' }
|
||||
/** The finger was lifted after a long press. */
|
||||
| { type: 'long_press_release' }
|
||||
| { type: 'swipe_up' }
|
||||
| { type: 'swipe_down' }
|
||||
| { type: 'menu'; itemId: number }
|
||||
@@ -89,11 +93,17 @@ export function normalizeEvent(event: RawEvenHubEvent): DeviceEvent[] {
|
||||
case OS_EVENT.SYSTEM_EXIT:
|
||||
out.push({ type: 'system_exit' });
|
||||
break;
|
||||
case OS_EVENT.LONG_PRESS:
|
||||
out.push({ type: 'long_press' });
|
||||
break;
|
||||
case OS_EVENT.LONG_PRESS_RELEASE:
|
||||
out.push({ type: 'long_press_release' });
|
||||
break;
|
||||
case OS_EVENT.CLICK:
|
||||
out.push({ type: 'tap' });
|
||||
break;
|
||||
default:
|
||||
// IMU reports and long press are not part of the interaction contract.
|
||||
// IMU reports are not part of the interaction contract.
|
||||
break;
|
||||
}
|
||||
return out;
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* Decide whether this page is running inside the Even app.
|
||||
*
|
||||
* The Even app's WebView provides `window.flutter_inappwebview.callHandler` (per the SDK's
|
||||
* README). The simulator provides it before the page's script runs. Whether the real Even app
|
||||
* always does is NOT known: this wait is a precaution, not a fix for an observed problem.
|
||||
* (It was written on 2026-11-21 after a wrong diagnosis: a page that showed "Browser preview"
|
||||
* on a phone had simply been opened in Chrome, not in the Even app.) The page waits briefly
|
||||
* for the host, and listens for the WebView's own "platform ready" event, before concluding
|
||||
* it is in an ordinary browser.
|
||||
*/
|
||||
export interface HostWindow {
|
||||
flutter_inappwebview?: { callHandler?: unknown };
|
||||
addEventListener(type: string, listener: () => void): void;
|
||||
removeEventListener(type: string, listener: () => void): void;
|
||||
}
|
||||
|
||||
export interface HostDetection {
|
||||
found: boolean;
|
||||
/** How long the page waited before deciding. */
|
||||
waitedMs: number;
|
||||
}
|
||||
|
||||
/** Short, because in an ordinary browser this is pure delay before the preview appears. */
|
||||
export const HOST_WAIT_MS = 2500;
|
||||
/** The event flutter_inappwebview dispatches on `window` once its JavaScript bridge is usable. */
|
||||
export const PLATFORM_READY_EVENT = 'flutterInAppWebViewPlatformReady';
|
||||
|
||||
export function hostPresent(win: HostWindow): boolean {
|
||||
return typeof win.flutter_inappwebview?.callHandler === 'function';
|
||||
}
|
||||
|
||||
export function waitForEvenHost(
|
||||
win: HostWindow,
|
||||
options: { timeoutMs?: number; pollMs?: number; now?: () => number } = {},
|
||||
): Promise<HostDetection> {
|
||||
const timeoutMs = options.timeoutMs ?? HOST_WAIT_MS;
|
||||
const pollMs = options.pollMs ?? 50;
|
||||
const now = options.now ?? Date.now;
|
||||
const started = now();
|
||||
return new Promise((resolve) => {
|
||||
let done = false;
|
||||
const finish = (found: boolean) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
clearInterval(poll);
|
||||
clearTimeout(deadline);
|
||||
win.removeEventListener(PLATFORM_READY_EVENT, onReady);
|
||||
resolve({ found, waitedMs: now() - started });
|
||||
};
|
||||
const check = () => {
|
||||
if (hostPresent(win)) finish(true);
|
||||
};
|
||||
// The event alone is not proof (anything can dispatch it); it only prompts a re-check.
|
||||
const onReady = () => check();
|
||||
const poll = setInterval(check, pollMs);
|
||||
const deadline = setTimeout(() => finish(hostPresent(win)), timeoutMs);
|
||||
win.addEventListener(PLATFORM_READY_EVENT, onReady);
|
||||
check();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* After the page has settled on browser-preview mode, keep watching: if the Even host turns
|
||||
* up after all, call `onLate` once (the page reloads itself into the real mode).
|
||||
*/
|
||||
export function watchForLateHost(win: HostWindow, onLate: () => void, pollMs = 500): () => void {
|
||||
let fired = false;
|
||||
const check = () => {
|
||||
if (fired || !hostPresent(win)) return;
|
||||
fired = true;
|
||||
stop();
|
||||
onLate();
|
||||
};
|
||||
const timer = setInterval(check, pollMs);
|
||||
win.addEventListener(PLATFORM_READY_EVENT, check);
|
||||
const stop = () => {
|
||||
clearInterval(timer);
|
||||
win.removeEventListener(PLATFORM_READY_EVENT, check);
|
||||
};
|
||||
return stop;
|
||||
}
|
||||
@@ -16,6 +16,23 @@ export interface DevicePort {
|
||||
onConnection(listener: (connected: boolean) => void): () => void;
|
||||
/** Ask the OS to show its own exit confirmation. */
|
||||
requestExit(): Promise<void>;
|
||||
/**
|
||||
* Leave the glasses now, with no confirmation, returning them to their normal screen. Used
|
||||
* when the app has been idle: while it is open it occupies the display and (seen on a real
|
||||
* G2) phone notifications do not reach the lenses.
|
||||
*
|
||||
* 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, for Diagnostics: how this session was opened, when the host says. On a real G2 a
|
||||
* voice launch was not reported as `glassesMenu`, so nothing may depend on it.
|
||||
* The host sends this once, early. An implementation must remember it and replay it to a
|
||||
* listener that subscribes later.
|
||||
*/
|
||||
onLaunchSource?(listener: (source: 'appMenu' | 'glassesMenu') => void): () => void;
|
||||
/**
|
||||
* Read a stored value. `{ ok: false }` means the host did not answer (or failed): the value
|
||||
* is UNKNOWN, which is different from "nothing stored" (`{ ok: true, value: '' }`).
|
||||
@@ -27,4 +44,11 @@ export interface DevicePort {
|
||||
* land later, so `false` is "not confirmed", never "not written" and never "written".
|
||||
*/
|
||||
storageSet(key: string, value: string): Promise<boolean>;
|
||||
/**
|
||||
* Optional, for the phone's Diagnostics only: a one-line summary of what the glasses runtime
|
||||
* has delivered (counts and event types; never audio or any content).
|
||||
*/
|
||||
inputSummary?(): string;
|
||||
/** Optional: called whenever `inputSummary()` would change. */
|
||||
onInputActivity?(listener: () => void): () => void;
|
||||
}
|
||||
|
||||
@@ -68,6 +68,13 @@ export class BrowserPreviewDevice implements DevicePort {
|
||||
|
||||
async requestExit(): Promise<void> {}
|
||||
|
||||
/** The preview cannot leave anything; it only says so. */
|
||||
async exitNow(): Promise<boolean> {
|
||||
this.body.textContent = '(Pepper would now leave the glasses.)';
|
||||
this.status.textContent = '';
|
||||
return true;
|
||||
}
|
||||
|
||||
async storageGet(key: string): Promise<StorageRead> {
|
||||
try {
|
||||
return { ok: true, value: localStorage.getItem(key) ?? '' };
|
||||
|
||||
@@ -1,53 +1,33 @@
|
||||
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 { 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.
|
||||
*/
|
||||
async function resolveDevice(): Promise<{ device: DevicePort; runtime: string }> {
|
||||
const hasHost = typeof (window as { flutter_inappwebview?: unknown }).flutter_inappwebview !== 'undefined';
|
||||
if (hasHost) {
|
||||
const bridge = await waitForEvenAppBridge();
|
||||
return { device: new EvenDevice(bridge), runtime: 'Even app host (SDK 0.0.16)' };
|
||||
}
|
||||
const preview = document.getElementById('preview')!;
|
||||
preview.hidden = false;
|
||||
return { device: new BrowserPreviewDevice(preview), runtime: 'Browser preview: no glasses, no microphone' };
|
||||
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 { 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,
|
||||
// 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, for automated simulator runs: `?wake=off` removes hands-free mode and
|
||||
// `?menu=off` opens at Ready instead of on the menu.
|
||||
wake: !(import.meta.env.DEV && new URLSearchParams(location.search).get('wake') === 'off'),
|
||||
menu: !(import.meta.env.DEV && new URLSearchParams(location.search).get('menu') === 'off'),
|
||||
livePreview: !(import.meta.env.DEV && new URLSearchParams(location.search).get('preview') === 'off'),
|
||||
});
|
||||
|
||||
// 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) {
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import {
|
||||
AUDIO_FORMAT,
|
||||
check,
|
||||
AgentsResponse,
|
||||
ConversationResponse,
|
||||
DeviceCredential,
|
||||
DeviceStatusResponse,
|
||||
ErrorResponse,
|
||||
RevokeResponse,
|
||||
SCHEMA_VERSION,
|
||||
TranscribeResponse,
|
||||
TurnResult,
|
||||
WakeResponse,
|
||||
type ErrorBody,
|
||||
} from '@hermeven/contracts';
|
||||
import type { TSchema } from '@sinclair/typebox';
|
||||
@@ -135,8 +138,16 @@ export class BridgeClient {
|
||||
return this.call(RevokeResponse, 'DELETE', '/v1/device');
|
||||
}
|
||||
|
||||
createConversation(): Promise<ConversationResponse> {
|
||||
return this.call(ConversationResponse, 'POST', '/v1/conversations', { json: { schema_version: SCHEMA_VERSION } });
|
||||
/** The agents this device may talk to. A bridge from before agent selection answers `not_found`. */
|
||||
agents(): Promise<AgentsResponse> {
|
||||
return this.call(AgentsResponse, 'GET', '/v1/agents');
|
||||
}
|
||||
|
||||
/** `agentId` is sent only when given, so a bridge from before agent selection still accepts the request. */
|
||||
createConversation(agentId?: string): Promise<ConversationResponse> {
|
||||
return this.call(ConversationResponse, 'POST', '/v1/conversations', {
|
||||
json: agentId === undefined ? { schema_version: SCHEMA_VERSION } : { schema_version: SCHEMA_VERSION, agent_id: agentId },
|
||||
});
|
||||
}
|
||||
|
||||
submitText(args: { requestId: string; conversationId: string; locale: string; text: string }): Promise<TurnResult> {
|
||||
@@ -166,6 +177,36 @@ export class BridgeClient {
|
||||
return this.call(TurnResult, 'POST', `/v1/turns?${query}`, { binary: args.pcm }) as Promise<TurnResult>;
|
||||
}
|
||||
|
||||
/**
|
||||
* One stretch of speech heard while listening: did it begin with an agent's name? Creates
|
||||
* nothing on the bridge. A bridge without wake names answers `not_found`.
|
||||
*/
|
||||
wake(args: { locale: string; pcm: Uint8Array }): Promise<WakeResponse> {
|
||||
const query = new URLSearchParams({
|
||||
schema_version: String(SCHEMA_VERSION),
|
||||
locale: args.locale,
|
||||
encoding: AUDIO_FORMAT.encoding,
|
||||
sample_rate: String(AUDIO_FORMAT.sampleRate),
|
||||
channels: String(AUDIO_FORMAT.channels),
|
||||
});
|
||||
return this.call(WakeResponse, 'POST', `/v1/wake?${query}`, { binary: args.pcm });
|
||||
}
|
||||
|
||||
/**
|
||||
* The words in a recording still being made, for showing while the user speaks. Creates
|
||||
* nothing on the bridge. A bridge without it answers `not_found`.
|
||||
*/
|
||||
transcribe(args: { locale: string; pcm: Uint8Array }): Promise<TranscribeResponse> {
|
||||
const query = new URLSearchParams({
|
||||
schema_version: String(SCHEMA_VERSION),
|
||||
locale: args.locale,
|
||||
encoding: AUDIO_FORMAT.encoding,
|
||||
sample_rate: String(AUDIO_FORMAT.sampleRate),
|
||||
channels: String(AUDIO_FORMAT.channels),
|
||||
});
|
||||
return this.call(TranscribeResponse, 'POST', `/v1/transcribe?${query}`, { binary: args.pcm });
|
||||
}
|
||||
|
||||
getTurn(requestId: string): Promise<TurnResult> {
|
||||
return this.call(TurnResult, 'GET', `/v1/turns/${requestId}`) as Promise<TurnResult>;
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ function explain(err: unknown): string {
|
||||
|
||||
const PHASE_LABEL: Record<string, string> = {
|
||||
unpaired: 'Not paired',
|
||||
menu: 'Menu (choose a mode on the glasses)',
|
||||
ready: 'Ready',
|
||||
listening: 'Listening (microphone open)',
|
||||
transcribing: 'Transcribing',
|
||||
@@ -163,8 +164,13 @@ export function mountPhoneUi(root: HTMLElement, controller: Controller, defaults
|
||||
|
||||
phase.textContent = PHASE_LABEL[s.state.phase] ?? s.state.phase;
|
||||
captureNote.textContent =
|
||||
`Recording starts only when you tap the glasses, shows “● REC” for as long as the microphone is open, ` +
|
||||
`and stops by itself after ${s.state.captureMaxSeconds} seconds.`;
|
||||
s.wake.enabled
|
||||
? `Hands free: the glasses’ microphone is open whenever the app is at rest (the status line starts with “●”). ` +
|
||||
`Each stretch of speech goes to your bridge, which keeps it only if it begins with an agent’s name. ` +
|
||||
`Say a name and then your question, or tap to ask. Double tap at Ready goes back to the menu and closes the microphone. ` +
|
||||
(s.wake.listening ? 'Listening now.' : 'Not listening at the moment.')
|
||||
: `Recording starts only when you tap the glasses, shows “● REC” for as long as the microphone is open, ` +
|
||||
`and stops by itself after ${s.state.captureMaxSeconds} seconds.`;
|
||||
const inFlight = ['listening', 'transcribing', 'thinking', 'approval', 'disconnected'].includes(s.state.phase);
|
||||
askButton.disabled = inFlight;
|
||||
newButton.disabled = inFlight;
|
||||
@@ -196,7 +202,10 @@ export function mountPhoneUi(root: HTMLElement, controller: Controller, defaults
|
||||
rows(diagList, [
|
||||
['Runtime', defaults.runtime],
|
||||
['Page origin', location.origin],
|
||||
['Browser', navigator.userAgent],
|
||||
['HUD page', s.hudReady ? 'created' : 'not created'],
|
||||
['Opened from', s.launchSource === 'glassesMenu' ? 'the glasses (menu or voice)' : s.launchSource === 'appMenu' ? 'the phone app' : 'not reported'],
|
||||
['Glasses input', s.glassesInput || 'not available in this mode'],
|
||||
['Device id', s.deviceId || 'none'],
|
||||
['Conversation id', s.state.conversationId ?? 'none'],
|
||||
['Request id', s.state.requestId ?? 'none'],
|
||||
|
||||
@@ -64,10 +64,15 @@ describe('gestures through the SDK parser', () => {
|
||||
expect(parse({ type: 'menuItemClickEvent', jsonData: { itemID: 2 } })).toEqual([{ type: 'menu', itemId: 2 }]);
|
||||
});
|
||||
|
||||
it('IMU reports and long presses are outside the interaction contract', () => {
|
||||
it('IMU reports are outside the interaction contract', () => {
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventType: 8, imuData: { x: 1, y: 2, z: 3 } } })).toEqual([]);
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventType: 9 } })).toEqual([]);
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventType: 10 } })).toEqual([]);
|
||||
});
|
||||
|
||||
it('long press and its release are recognised (a real G2 reported a slow tap as type 9)', () => {
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventType: 9, eventSource: 1 } })).toEqual([{ type: 'long_press' }]);
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventType: 10, eventSource: 1 } })).toEqual([{ type: 'long_press_release' }]);
|
||||
expect(parse({ type: 'textEvent', jsonData: { eventType: 9 } })).toEqual([{ type: 'long_press' }]);
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventType: 'LONG_PRESS_EVENT' } })).toEqual([{ type: 'long_press' }]);
|
||||
});
|
||||
|
||||
it('an empty or unknown event produces nothing', () => {
|
||||
|
||||
@@ -151,13 +151,14 @@ describe('plain text', () => {
|
||||
});
|
||||
|
||||
describe('HUD frames', () => {
|
||||
const phases: Phase[] = ['unpaired', 'ready', 'listening', 'transcribing', 'thinking', 'approval', 'answer', 'error', 'disconnected', 'cancelled'];
|
||||
const phases: Phase[] = ['unpaired', 'menu', 'ready', 'listening', 'transcribing', 'thinking', 'approval', 'answer', 'error', 'disconnected', 'cancelled'];
|
||||
const variants = (phase: Phase): AppState[] => {
|
||||
const base: AppState = { ...initialState, phase, captureStartedAt: 0, captureMaxSeconds: 120 };
|
||||
if (phase === 'answer') {
|
||||
return [
|
||||
{ ...base, pages: ['x'], pageIndex: 0 },
|
||||
{ ...base, pages: Array(99).fill('x'), pageIndex: 98, partial: true },
|
||||
{ ...base, pages: Array(99).fill('x'), pageIndex: 98, partial: true, wakeListening: true, agents: [{ id: 'default', name: 'Pepper' }, { id: 'natalie', name: 'Natalie' }], agentId: 'natalie' },
|
||||
];
|
||||
}
|
||||
if (phase === 'disconnected') {
|
||||
@@ -172,9 +173,26 @@ describe('HUD frames', () => {
|
||||
return [
|
||||
{ ...base, error: { code: 'outcome_unknown', hud: 'The outcome is unknown. Check the agent before asking again.', retryable: false } },
|
||||
{ ...base, error: { code: 'agent_timeout', hud: 'The agent ran out of time and was stopped. Actions it had already taken are not undone.', retryable: true } },
|
||||
{ ...base, wakeListening: true, error: { code: 'agent_timeout', hud: 'The agent ran out of time and was stopped.', retryable: true } },
|
||||
];
|
||||
}
|
||||
if (phase === 'ready') return [base, { ...base, notice: 'New conversation' }];
|
||||
// Listening for a name: sixteen agents with the longest names allowed, and none.
|
||||
const many = Array.from({ length: 16 }, (_, i) => ({ id: `a${i}`, name: 'Wwwwwwwwwwwwwwwwwwwwwwww' }));
|
||||
const few = [
|
||||
{ id: 'default', name: 'Pepper' },
|
||||
{ id: 'wendy', name: 'Wendy' },
|
||||
{ id: 'cody', name: 'Cody' },
|
||||
];
|
||||
const wake = { wakeListening: true };
|
||||
if (phase === 'menu') return [base, { ...base, handsFree: true }, { ...base, handsFree: true, menuIndex: 1 }];
|
||||
if (phase === 'ready') {
|
||||
return [{ ...base, menu: true }, { ...base, menu: true, ...wake, agents: few }, base, { ...base, notice: 'New conversation' }, { ...base, ...wake }, { ...base, ...wake, agents: few }, { ...base, ...wake, agents: many }, { ...base, ...wake, agents: few, notice: 'New conversation' }];
|
||||
}
|
||||
const words = 'what is on my calendar tomorrow and can you move the dentist to Thursday afternoon if that is free';
|
||||
if (phase === 'listening') return [base, { ...base, captureAuto: true }, { ...base, captureAuto: true, agents: few }, { ...base, agents: few, preview: `… ${words} ${words}` }];
|
||||
if (phase === 'transcribing') return [base, { ...base, preview: `… ${words} ${words}` }];
|
||||
if (phase === 'thinking') return [base, { ...base, heard: 'W'.repeat(4000) }, { ...base, agents: few, heard: 'What is on my calendar tomorrow?' }];
|
||||
if (phase === 'cancelled') return [base, { ...base, ...wake }];
|
||||
if (phase === 'unpaired') return [base, { ...base, storageFault: true }];
|
||||
return [base];
|
||||
};
|
||||
@@ -201,6 +219,20 @@ describe('HUD frames', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('an open microphone at rest is always marked, and never claimed while it is closed', () => {
|
||||
for (const phase of ['ready', 'answer', 'error', 'cancelled'] as Phase[]) {
|
||||
const state: AppState = { ...initialState, phase, pages: ['x'] };
|
||||
expect(renderHud({ ...state, wakeListening: true }, 0).status.startsWith('● ')).toBe(true);
|
||||
expect(renderHud(state, 0).status).not.toContain('●');
|
||||
}
|
||||
// In flight the microphone is closed, whatever the flag last said.
|
||||
for (const phase of ['transcribing', 'thinking', 'approval', 'disconnected', 'unpaired'] as Phase[]) {
|
||||
expect(renderHud({ ...initialState, phase, wakeListening: true }, 0).status).not.toContain('●');
|
||||
}
|
||||
const ready = renderHud({ ...initialState, phase: 'ready', wakeListening: true, agents: [{ id: 'default', name: 'Pepper' }, { id: 'wendy', name: 'Wendy' }] }, 0);
|
||||
expect(ready.body).toBe('Pepper\n\nListening. Say a name, then your question:\nPepper · Wendy');
|
||||
});
|
||||
|
||||
it('errors offer a recovery action and send detail to the phone', () => {
|
||||
const frame = renderHud({ ...initialState, phase: 'error', error: { code: 'stt_empty', hud: 'No speech was recognised.', retryable: true } }, 0);
|
||||
expect(frame.body).toContain('No speech was recognised.');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { SCHEMA_VERSION, type TurnResult } from '@hermeven/contracts';
|
||||
import { pollDelay } from '../src/core/controller.ts';
|
||||
import { renderHud } from '../src/core/hud.ts';
|
||||
import { initialState, reduce, type AppEvent, type AppState, type Effect } from '../src/core/reducer.ts';
|
||||
|
||||
const ID1 = '11111111-1111-4111-8111-111111111111';
|
||||
@@ -369,3 +370,76 @@ describe('pairing, restore and conversations', () => {
|
||||
expect(step.effects).toEqual([{ type: 'discard_capture' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('choosing an agent', () => {
|
||||
const AGENTS = [
|
||||
{ id: 'default', name: 'Pepper' },
|
||||
{ id: 'wendy', name: 'Wendy' },
|
||||
];
|
||||
const WENDY_CONV = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';
|
||||
const readyWithAgents = () =>
|
||||
run(initialState, { type: 'init', paired: true, conversationId: CONV, captureMaxSeconds: 30, resumeRequestId: null, agents: AGENTS, agentId: null }).state;
|
||||
const select: AppEvent = { type: 'agent_selected', agentId: 'wendy', conversationId: WENDY_CONV };
|
||||
|
||||
it('at Ready: the agent and its own conversation are swapped in under a new conversation epoch', () => {
|
||||
const before = readyWithAgents();
|
||||
const { state, effects } = run(before, select);
|
||||
expect(effects).toEqual([]);
|
||||
expect(state.phase).toBe('ready');
|
||||
expect(state.agentId).toBe('wendy');
|
||||
expect(state.conversationId).toBe(WENDY_CONV);
|
||||
expect(state.conversationEpoch).toBe(before.conversationEpoch + 1);
|
||||
expect(state.generation).toBe(before.generation + 1);
|
||||
expect(renderHud(state, 0).body).toBe('Wendy\n\nReady.');
|
||||
});
|
||||
|
||||
it('is ignored on every other screen: listening, in flight, an answer, an error, cancelled, unpaired', () => {
|
||||
const base = readyWithAgents();
|
||||
const others: AppState[] = [
|
||||
run(base, { type: 'activate', freshId: ID1 }).state,
|
||||
run(base, { type: 'submit_text', freshId: ID1, text: 'q' }).state,
|
||||
run(base, { type: 'submit_text', freshId: ID1, text: 'q' }, { type: 'turn_update', generation: base.generation + 1, result: result(ID1), pages: ['a'] }).state,
|
||||
run(base, { type: 'activate', freshId: ID1 }, { type: 'capture_failed', generation: base.generation + 1, reason: 'mic_refused' }).state,
|
||||
run(base, { type: 'activate', freshId: ID1 }, { type: 'cancel' }).state,
|
||||
{ ...initialState, agents: AGENTS },
|
||||
];
|
||||
expect(others.map((s) => s.phase)).toEqual(['listening', 'thinking', 'answer', 'error', 'cancelled', 'unpaired']);
|
||||
for (const state of others) expect(reduce(state, select).state, state.phase).toBe(state);
|
||||
});
|
||||
|
||||
it('an agent that is not offered, or the one already current, changes nothing', () => {
|
||||
const base = readyWithAgents();
|
||||
expect(reduce(base, { type: 'agent_selected', agentId: 'natalie', conversationId: null }).state).toBe(base);
|
||||
expect(reduce(base, { type: 'agent_selected', agentId: 'default', conversationId: null }).state).toBe(base);
|
||||
});
|
||||
|
||||
it('a conversation created for the previous agent cannot land on the new one', () => {
|
||||
const base = readyWithAgents();
|
||||
const creating = run(base, { type: 'new_conversation' }).state;
|
||||
const moved = run(creating, { type: 'agent_selected', agentId: 'wendy', conversationId: null }).state;
|
||||
const late = reduce(moved, { type: 'conversation_created', epoch: creating.conversationEpoch, conversationId: CONV }).state;
|
||||
expect(late.conversationId).toBeNull();
|
||||
expect(late.creatingConversation).toBe(false);
|
||||
});
|
||||
|
||||
it('falling back from a removed agent: applied on any resting screen without disturbing it, never while something is in flight', () => {
|
||||
const base = run(readyWithAgents(), select).state;
|
||||
const back: AppEvent = { type: 'agent_reconciled', agentId: 'default', conversationId: CONV };
|
||||
const answered = run(base, { type: 'submit_text', freshId: ID1, text: 'q' }, { type: 'turn_update', generation: base.generation + 1, result: result(ID1), pages: ['her answer'] }).state;
|
||||
const after = reduce(answered, back).state;
|
||||
expect(after.phase).toBe('answer');
|
||||
expect(after.pages).toEqual(['her answer']); // what she said stays on screen
|
||||
expect([after.agentId, after.conversationId]).toEqual(['default', CONV]);
|
||||
expect(after.conversationEpoch).toBe(answered.conversationEpoch + 1);
|
||||
for (const busy of [run(base, { type: 'activate', freshId: ID1 }).state, run(base, { type: 'submit_text', freshId: ID1, text: 'q' }).state]) {
|
||||
expect(reduce(busy, back).state, busy.phase).toBe(busy);
|
||||
}
|
||||
});
|
||||
|
||||
it('with one agent, or none listed, no screen mentions an agent', () => {
|
||||
for (const agents of [[], [AGENTS[0]!]]) {
|
||||
const state = run(initialState, { type: 'init', paired: true, conversationId: CONV, captureMaxSeconds: 30, resumeRequestId: null, agents }).state;
|
||||
expect(renderHud(state, 0)).toEqual({ body: 'Hermeven\n\nReady.', status: 'Tap: ask · Double-tap: exit' });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { SpeechSegmenter, WAKE_SEGMENTER, type SegmentEvent } from '../src/core/vad.ts';
|
||||
|
||||
/** Synthetic audio: a tone stands in for a voice, low noise for a room. Not speech. */
|
||||
function tone(ms: number, amplitude = 6000): Uint8Array {
|
||||
const samples = (ms * 16000) / 1000;
|
||||
const out = new Uint8Array(samples * 2);
|
||||
for (let i = 0; i < samples; i++) {
|
||||
const v = Math.round(Math.sin((2 * Math.PI * 300 * i) / 16000) * amplitude) & 0xffff;
|
||||
out[2 * i] = v & 0xff;
|
||||
out[2 * i + 1] = v >> 8;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const room = (ms: number, amplitude = 40) => tone(ms, amplitude);
|
||||
|
||||
function feed(segmenter: SpeechSegmenter, ...clips: Uint8Array[]): SegmentEvent[] {
|
||||
const events: SegmentEvent[] = [];
|
||||
for (const clip of clips) {
|
||||
// In 100 ms frames, as the glasses deliver them.
|
||||
for (let offset = 0; offset < clip.length; offset += 3200) events.push(...segmenter.push(clip.subarray(offset, offset + 3200)));
|
||||
}
|
||||
return events;
|
||||
}
|
||||
const ms = (pcm: Uint8Array) => pcm.length / 32;
|
||||
|
||||
describe('speech segmenter', () => {
|
||||
it('silence and steady room noise produce nothing', () => {
|
||||
const segmenter = new SpeechSegmenter();
|
||||
expect(feed(segmenter, new Uint8Array(32000 * 5), room(5000))).toEqual([]);
|
||||
expect(segmenter.speaking).toBe(false);
|
||||
});
|
||||
|
||||
it('delivers one utterance, with its lead-in, once the speaker pauses', () => {
|
||||
const segmenter = new SpeechSegmenter();
|
||||
const events = feed(segmenter, room(1000), tone(1500), room(1000));
|
||||
expect(events.map((e) => e.type)).toEqual(['start', 'end']);
|
||||
const end = events[1] as Extract<SegmentEvent, { type: 'end' }>;
|
||||
// Speech, the preroll before it and the closing pause; not the whole second of lead-in.
|
||||
expect(ms(end.pcm)).toBeGreaterThanOrEqual(1500 + WAKE_SEGMENTER.endSilenceMs);
|
||||
expect(ms(end.pcm)).toBeLessThanOrEqual(1500 + WAKE_SEGMENTER.endSilenceMs + WAKE_SEGMENTER.prerollMs + 60);
|
||||
expect(end.pcm.length % 2).toBe(0);
|
||||
expect(segmenter.speaking).toBe(false);
|
||||
});
|
||||
|
||||
it('a short pause inside a sentence does not split it; a long one does', () => {
|
||||
const segmenter = new SpeechSegmenter();
|
||||
const one = feed(segmenter, room(500), tone(600), room(300), tone(600), room(1000));
|
||||
expect(one.map((e) => e.type)).toEqual(['start', 'end']);
|
||||
const two = feed(segmenter, tone(600), room(900), tone(600), room(900));
|
||||
expect(two.map((e) => e.type)).toEqual(['start', 'end', 'start', 'end']);
|
||||
});
|
||||
|
||||
it('a click is discarded, not delivered', () => {
|
||||
const segmenter = new SpeechSegmenter();
|
||||
expect(feed(segmenter, room(500), tone(100), room(1000)).map((e) => e.type)).toEqual(['start', 'discard']);
|
||||
});
|
||||
|
||||
it('frames of any size give the same result', () => {
|
||||
const clip = new Uint8Array([...room(600), ...tone(900), ...room(900)]);
|
||||
const a = new SpeechSegmenter();
|
||||
const b = new SpeechSegmenter();
|
||||
const whole = a.push(clip);
|
||||
const pieces: SegmentEvent[] = [];
|
||||
for (let offset = 0; offset < clip.length; offset += 1001) pieces.push(...b.push(clip.subarray(offset, offset + 1001)));
|
||||
expect(pieces).toEqual(whole);
|
||||
});
|
||||
|
||||
it('a noise that never pauses is cut at the limit and then becomes the background', () => {
|
||||
const segmenter = new SpeechSegmenter({ ...WAKE_SEGMENTER, maxMs: 3000 });
|
||||
const events = feed(segmenter, room(500), tone(10_000, 3000));
|
||||
expect(events.filter((e) => e.type === 'end')).toHaveLength(1);
|
||||
// Something clearly louder than that noise is still heard as speech.
|
||||
expect(feed(segmenter, tone(1000, 20_000), tone(1000, 3000)).map((e) => e.type)).toEqual(['start', 'end']);
|
||||
});
|
||||
|
||||
it('adapts to a louder room: steady noise above the minimum level stops counting as speech', () => {
|
||||
const segmenter = new SpeechSegmenter({ ...WAKE_SEGMENTER, maxMs: 2000 });
|
||||
feed(segmenter, room(4000, 600));
|
||||
expect(feed(segmenter, room(4000, 600))).toEqual([]);
|
||||
});
|
||||
|
||||
it('hands over what it is holding, and can be retimed without losing it', () => {
|
||||
const segmenter = new SpeechSegmenter();
|
||||
feed(segmenter, room(1000), tone(800));
|
||||
expect(segmenter.speaking).toBe(true);
|
||||
expect(ms(segmenter.buffered())).toBeGreaterThanOrEqual(800);
|
||||
segmenter.configure({ ...WAKE_SEGMENTER, endSilenceMs: 1200 });
|
||||
expect(feed(segmenter, room(1000))).toEqual([]);
|
||||
expect(feed(segmenter, room(300)).map((e) => e.type)).toEqual(['end']);
|
||||
segmenter.reset();
|
||||
expect(segmenter.buffered().length).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,28 @@
|
||||
# Caddy terminates TLS (certificates are obtained automatically) and forwards to the bridge
|
||||
# on loopback. Replace the hostname. Example only: not yet run on a droplet.
|
||||
# Caddy terminates TLS (certificates are obtained automatically), forwards the bridge API to
|
||||
# loopback, and serves the built phone page from the same origin. Replace the hostname.
|
||||
# This is the shape running on the first droplet deployment (2026-11-21).
|
||||
bridge.example.com {
|
||||
encode zstd gzip
|
||||
# Audio uploads are at most about 1 MB at the default 30 s cap.
|
||||
request_body {
|
||||
max_size 2MB
|
||||
header {
|
||||
Strict-Transport-Security "max-age=31536000"
|
||||
X-Content-Type-Options "nosniff"
|
||||
Referrer-Policy "no-referrer"
|
||||
-Server
|
||||
}
|
||||
|
||||
# Bridge API. Audio uploads are at most about 1 MB at the default 30 s cap.
|
||||
@api path /v1/* /healthz
|
||||
handle @api {
|
||||
request_body {
|
||||
max_size 2MB
|
||||
}
|
||||
reverse_proxy 127.0.0.1:8787
|
||||
}
|
||||
|
||||
# The built client (apps/even-client/dist). Static files, no secrets. Serving it from the
|
||||
# bridge's own origin means the page needs no CORS allowance.
|
||||
handle {
|
||||
root * /opt/hermeven/www
|
||||
file_server
|
||||
}
|
||||
reverse_proxy 127.0.0.1:8787
|
||||
}
|
||||
|
||||
@@ -3,13 +3,27 @@ HERMES_BASE_URL=http://127.0.0.1:8642
|
||||
HERMES_API_KEY=replace-with-the-hermes-api-server-key
|
||||
HERMES_PROFILE_LABEL=default
|
||||
|
||||
# Optional: more agents on the glasses (swipe at Ready to choose). Each is another profile of the
|
||||
# same Hermes gateway and needs its OWN key: add API_SERVER_KEY to that profile's .env on the
|
||||
# Hermes side, then repeat it here. See docs/bridge-api.md, "More than one agent".
|
||||
# HERMEVEN_AGENT_NAME=Pepper
|
||||
# HERMEVEN_AGENTS=wendy,cody
|
||||
# HERMEVEN_AGENT_WENDY_API_KEY=replace-with-wendy-profile-api-server-key
|
||||
# HERMEVEN_AGENT_CODY_API_KEY=replace-with-cody-profile-api-server-key
|
||||
# Each agent is called by voice with the first word of its name. If the speech model writes a
|
||||
# name another way (the phone's Diagnostics shows near misses), add those spellings:
|
||||
# HERMEVEN_AGENT_CODY_WAKE=kody,codi
|
||||
# HERMEVEN_AGENT_WAKE=peper
|
||||
|
||||
HERMEVEN_HOST=127.0.0.1
|
||||
HERMEVEN_PORT=8787
|
||||
# Caddy is in front, so the client address comes from its forwarded header.
|
||||
HERMEVEN_TRUST_PROXY=true
|
||||
HERMEVEN_DB_PATH=/var/lib/hermeven/hermeven.sqlite
|
||||
# Read the real value from the phone page: Diagnostics -> "Page origin".
|
||||
HERMEVEN_ALLOWED_ORIGINS=
|
||||
# An app installed through Even Hub is served from http://127.0.0.1:<port>, with a new port on
|
||||
# every launch, so it needs the loopback any-port entry below. Remove it if you only ever load
|
||||
# the page from this bridge's own hostname (QR sideload), which needs no entry.
|
||||
HERMEVEN_ALLOWED_ORIGINS=http://127.0.0.1:*
|
||||
|
||||
# Built-in speech-to-text (the default). The model is pinned and verified; the running service
|
||||
# never downloads it and only reads this directory. Populate it at deploy time with
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
# systemd unit for the Hermeven bridge. Example only: it has not been run on a droplet yet.
|
||||
# systemd unit for the Hermeven bridge. This is the unit running on the first droplet
|
||||
# deployment (2026-11-21); see docs/evidence/droplet/2026-11-21.md.
|
||||
# Install: copy to /etc/systemd/system/, adjust paths, then
|
||||
# systemctl daemon-reload && systemctl enable --now hermeven-bridge
|
||||
[Unit]
|
||||
@@ -10,10 +11,13 @@ Wants=network-online.target
|
||||
Type=simple
|
||||
User=hermeven
|
||||
Group=hermeven
|
||||
WorkingDirectory=/opt/hermeven
|
||||
WorkingDirectory=/opt/hermeven/app/services/bridge
|
||||
# Secrets live here, mode 600, owned by the service user. Never in the repository.
|
||||
Environment=HERMEVEN_ENV_FILE=/etc/hermeven/bridge.env
|
||||
ExecStart=/usr/bin/npm run --silent bridge
|
||||
# Node is started directly rather than through `npm run`: npm wants a writable home
|
||||
# directory for its logs, and the service's file system is read-only.
|
||||
Environment=HOME=/var/lib/hermeven
|
||||
ExecStart=/opt/node/bin/node --import tsx src/main.ts
|
||||
Restart=on-failure
|
||||
RestartSec=3
|
||||
# In-flight turns are recovered from SQLite on the next start.
|
||||
|
||||
Executable
+105
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install or update the Hermeven bridge application tree and the static phone page.
|
||||
#
|
||||
# Run as root from a checkout (or extracted archive) of the release you want to deploy:
|
||||
#
|
||||
# sudo deploy/install.sh --bridge-url https://bridge.example.com
|
||||
#
|
||||
# What it does, in order:
|
||||
# 1. Creates the `hermeven` system user, /opt/hermeven, /etc/hermeven and the 0700 state
|
||||
# directory /var/lib/hermeven, if they do not exist.
|
||||
# 2. Copies this checkout to /opt/hermeven/app.new and gives ONLY that directory to `hermeven`.
|
||||
# 3. Runs `npm ci` there as `hermeven`, so no package install script ever runs as root.
|
||||
# 4. Builds the phone page with the bridge address preset (also as `hermeven`).
|
||||
# 5. Gives the finished tree back to root and removes group/other write, so the running
|
||||
# service cannot modify its own code.
|
||||
# 6. Installs the built page into /opt/hermeven/www (root-owned, world-readable) for Caddy.
|
||||
# 7. Swaps the new tree into /opt/hermeven/app (the previous one is kept as app.old) and
|
||||
# installs the systemd unit. It does not start or restart the service.
|
||||
#
|
||||
# What it never touches: /etc/hermeven/* (secrets), /var/lib/hermeven/* (state) and
|
||||
# /opt/hermeven/models (the verified speech model). No recursive ownership change reaches them.
|
||||
set -euo pipefail
|
||||
|
||||
NODE_BIN=${NODE_BIN:-/opt/node/bin}
|
||||
PREFIX=/opt/hermeven
|
||||
BRIDGE_URL=""
|
||||
SOURCE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--bridge-url) BRIDGE_URL="${2:-}"; shift 2 ;;
|
||||
--source) SOURCE="$(cd "${2:?}" && pwd)"; shift 2 ;;
|
||||
-h|--help) sed -n '2,24p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 0 ;;
|
||||
*) echo "Unknown option: $1" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
fail() { echo "install.sh: $*" >&2; exit 1; }
|
||||
[ "$(id -u)" = 0 ] || fail "must be run as root"
|
||||
[ -x "$NODE_BIN/node" ] || fail "Node.js not found at $NODE_BIN/node (see docs/deploy-droplet.md, step 2)"
|
||||
command -v make >/dev/null 2>&1 && command -v g++ >/dev/null 2>&1 || fail "a C/C++ toolchain is required (apt-get install -y build-essential python3)"
|
||||
[ -f "$SOURCE/package-lock.json" ] && [ -d "$SOURCE/services/bridge" ] || fail "$SOURCE is not a Hermeven checkout"
|
||||
case "$BRIDGE_URL" in
|
||||
https://*) ;;
|
||||
"") fail "--bridge-url https://<your-bridge-host> is required (it is built into the phone page)" ;;
|
||||
*) fail "--bridge-url must start with https://" ;;
|
||||
esac
|
||||
export PATH="$NODE_BIN:$PATH"
|
||||
|
||||
echo "==> 1/7 user and directories"
|
||||
id hermeven >/dev/null 2>&1 || useradd --system --home "$PREFIX" --shell /usr/sbin/nologin hermeven
|
||||
mkdir -p "$PREFIX" /etc/hermeven
|
||||
install -d -m 0700 -o hermeven -g hermeven /var/lib/hermeven
|
||||
|
||||
echo "==> 2/7 copy the release to $PREFIX/app.new"
|
||||
rm -rf "$PREFIX/app.new"
|
||||
mkdir "$PREFIX/app.new"
|
||||
if git -C "$SOURCE" rev-parse --git-dir >/dev/null 2>&1; then
|
||||
# Exactly the committed files, and a record of which commit this is.
|
||||
git -C "$SOURCE" archive --format=tar HEAD | tar -x -C "$PREFIX/app.new"
|
||||
git -C "$SOURCE" rev-parse HEAD > "$PREFIX/app.new/DEPLOYED_SHA"
|
||||
else
|
||||
tar -C "$SOURCE" --exclude=./node_modules --exclude='./*/*/node_modules' --exclude=./apps/even-client/dist -cf - . | tar -x -C "$PREFIX/app.new"
|
||||
fi
|
||||
# Ownership is handed over for this one directory only.
|
||||
chown -R hermeven:hermeven "$PREFIX/app.new"
|
||||
|
||||
echo "==> 3/7 npm ci as the unprivileged user"
|
||||
BUILD_HOME="$(mktemp -d)"
|
||||
chown hermeven:hermeven "$BUILD_HOME"
|
||||
as_hermeven() { runuser -u hermeven -- env PATH="$PATH" HOME="$BUILD_HOME" npm_config_cache="$BUILD_HOME/npm-cache" "$@"; }
|
||||
( cd "$PREFIX/app.new" && as_hermeven npm ci --no-audit --no-fund )
|
||||
|
||||
echo "==> 4/7 build the phone page for $BRIDGE_URL"
|
||||
( cd "$PREFIX/app.new" && as_hermeven env VITE_HERMEVEN_BRIDGE_URL="$BRIDGE_URL" npm run --silent client:build )
|
||||
[ -f "$PREFIX/app.new/apps/even-client/dist/index.html" ] || fail "the client build produced no index.html"
|
||||
rm -rf "$BUILD_HOME"
|
||||
|
||||
echo "==> 5/7 hand the tree back to root"
|
||||
chown -R root:root "$PREFIX/app.new"
|
||||
chmod -R go-w "$PREFIX/app.new"
|
||||
|
||||
echo "==> 6/7 install the phone page into $PREFIX/www"
|
||||
rm -rf "$PREFIX/www.new"
|
||||
mkdir "$PREFIX/www.new"
|
||||
cp -R "$PREFIX/app.new/apps/even-client/dist/." "$PREFIX/www.new/"
|
||||
chown -R root:root "$PREFIX/www.new"
|
||||
find "$PREFIX/www.new" -type d -exec chmod 0755 {} +
|
||||
find "$PREFIX/www.new" -type f -exec chmod 0644 {} +
|
||||
rm -rf "$PREFIX/www.old"
|
||||
[ -d "$PREFIX/www" ] && mv "$PREFIX/www" "$PREFIX/www.old"
|
||||
mv "$PREFIX/www.new" "$PREFIX/www"
|
||||
|
||||
echo "==> 7/7 activate the new tree and install the unit"
|
||||
rm -rf "$PREFIX/app.old"
|
||||
[ -d "$PREFIX/app" ] && mv "$PREFIX/app" "$PREFIX/app.old"
|
||||
mv "$PREFIX/app.new" "$PREFIX/app"
|
||||
install -m 0644 -o root -g root "$PREFIX/app/deploy/hermeven-bridge.service" /etc/systemd/system/hermeven-bridge.service
|
||||
command -v systemctl >/dev/null 2>&1 && systemctl daemon-reload || true
|
||||
|
||||
echo
|
||||
echo "Installed $(cat "$PREFIX/app/DEPLOYED_SHA" 2>/dev/null || echo '(no commit recorded)') to $PREFIX/app"
|
||||
echo "Phone page installed to $PREFIX/www"
|
||||
echo "Not started. Next: configuration, speech model, then 'systemctl enable --now hermeven-bridge'"
|
||||
echo "(or 'systemctl restart hermeven-bridge' for an update). See docs/deploy-droplet.md."
|
||||
@@ -40,7 +40,7 @@ answer text is erased from the bridge 15 minutes after a turn ends (configurable
|
||||
network and no randomness: request ids arrive inside events and work leaves as effects.
|
||||
|
||||
```
|
||||
READY -> LISTENING -> TRANSCRIBING -> THINKING -> ANSWER
|
||||
MENU -> READY -> LISTENING -> TRANSCRIBING -> THINKING -> ANSWER
|
||||
plus APPROVAL, ERROR, DISCONNECTED, CANCELLED, UNPAIRED
|
||||
```
|
||||
|
||||
@@ -103,4 +103,5 @@ automatically under a new request id.
|
||||
- Polling only; no streaming.
|
||||
- A second question while one is running in the same conversation is refused
|
||||
(`conversation_busy`), not queued.
|
||||
- Capture ends by tap or cap. There is no end-of-speech detection.
|
||||
- A tapped capture ends by tap or cap. Only a recording started by an agent's name ends when
|
||||
the speaker stops (`docs/decisions/0004-always-listening.md`).
|
||||
|
||||
+31
-1
@@ -18,14 +18,44 @@ Every error has the shape:
|
||||
| `GET /v1/device` | Pairing status, limits, whether the agent is reachable and STT is configured. | 200 |
|
||||
| `POST /v1/device/renew` | Rotate the device token. The old token stops working at once. | 200 |
|
||||
| `DELETE /v1/device` | Revoke this device and close its conversation. | 200 |
|
||||
| `POST /v1/conversations` | Start a new conversation; closes the device's previous one. | 201 |
|
||||
| `GET /v1/agents` | The agents this device may talk to, default first: `{agents: [{id, name}]}`. Ids and display names only; no address, profile or key. Added after 0.1.x: an older bridge answers 404 `not_found`, which a client must treat as "one agent". | 200 |
|
||||
| `POST /v1/conversations` | Start a new conversation. Optional `agent_id` (an id from `/v1/agents`; omitted = the default agent; anything else is 400 `invalid_request`). Closes the device's previous conversation **with that agent** only. | 201 |
|
||||
| `POST /v1/turns` | Create one turn (text or audio). | 202, or 200 for a duplicate |
|
||||
| `POST /v1/wake` | One stretch of speech heard while the app was open (raw audio body, same format as an audio turn; query: `schema_version`, `locale`, `encoding`, `sample_rate`, `channels`). Transcribed in memory and dropped. Answers `{matched, agent_id, text, near_miss}`: whether it **began** with an agent's name, which agent, and what was said after the name (empty for the name alone). When not matched `text` is always empty; `near_miss` is the first word if it was close to a name. Creates no turn and sends nothing to any agent. 404 `not_found` when speech-to-text is off or no agent has a usable name (also what an older bridge answers); 429 `rate_limited` over `HERMEVEN_WAKE_CHECKS_PER_MINUTE` (default 30) or while this device's previous check is still running. A failed transcription is answered as not matched. | 200 |
|
||||
| `POST /v1/transcribe` | The words in a recording that is still being made, for showing while the user speaks. Same body and query as `/v1/wake`. Answers `{text}` (empty if nothing was recognised or transcription failed). Transcribed in memory and dropped; creates no turn, sends nothing to any agent, logs no text. 404 `not_found` when speech-to-text is off (also what an older bridge answers); 429 `rate_limited` over `HERMEVEN_PREVIEWS_PER_MINUTE` (default 60) or while this device's previous preview is still running. | 200 |
|
||||
| `GET /v1/turns/{request_id}` | Current state and result. | 200 |
|
||||
| `POST /v1/turns/{request_id}/cancel` | Request cancellation. Idempotent. | 200 |
|
||||
|
||||
There is no SSE endpoint. Streaming through the Even WebView is undocumented and untested, so
|
||||
polling is the supported path.
|
||||
|
||||
## More than one agent
|
||||
|
||||
The bridge can be given further agents besides the default one. Each is another profile served by
|
||||
the same Hermes gateway (`gateway.multiplex_profiles`), reached at `<HERMES_BASE_URL>/p/<profile>`
|
||||
with that profile's own `API_SERVER_KEY`; Hermes refuses the default profile's key there.
|
||||
|
||||
```
|
||||
HERMEVEN_AGENT_NAME=Pepper # display name of the default agent (default: Agent)
|
||||
HERMEVEN_AGENTS=wendy,cody # extra agent ids, in display order
|
||||
HERMEVEN_AGENT_WENDY_API_KEY=... # required for each extra agent
|
||||
HERMEVEN_AGENT_WENDY_PROFILE=wendy # optional; default: the id
|
||||
HERMEVEN_AGENT_WENDY_NAME=Wendy # optional; default: the id, capitalised
|
||||
HERMEVEN_AGENT_WENDY_WAKE=wendi,windy # optional; extra spoken forms of the name
|
||||
HERMEVEN_AGENT_WAKE=peper # the same, for the default agent
|
||||
```
|
||||
|
||||
An agent is called by voice with the first word of its name ("Cody R." answers to "cody"), plus
|
||||
any aliases. The default agent answers to its name only once `HERMEVEN_AGENT_NAME` is set. Two
|
||||
agents may not answer to the same word. Wake words are never sent to a client. See
|
||||
`docs/decisions/0004-always-listening.md`.
|
||||
|
||||
The list is the owner's allow-list. A client names an agent only by id, only when creating a
|
||||
conversation, and the id is checked against the list; it is never used to build an address. A
|
||||
turn goes to the agent of its conversation. Each agent has its own conversation and its own
|
||||
Hermes session, so nothing said to one is sent to another. `/v1/device` is unchanged, and its
|
||||
`active_conversation_id` and `agent_reachable` describe the default agent.
|
||||
|
||||
## Creating a turn
|
||||
|
||||
Typed text (`Content-Type: application/json`):
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
# 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. |
|
||||
|
||||
### E. Found during the device session (from Dan's words on 2026-11-21)
|
||||
|
||||
| # | Dan said | Criterion |
|
||||
|---|---|---|
|
||||
| E1 | "Tap to ask isn't working though now. It worked before." then "okay, quick tap worked." and "long presses and release are the way. I get my ring in a few days, so we'll want the ring to work like that." | A touch the glasses report as a long press starts recording like a tap; holding while speaking and releasing sends; a quickly released press behaves like a tap. Nothing in the handling depends on which temple or the ring sent it. |
|
||||
| E2 | (to find out why the tap did nothing) | The phone's Diagnostics shows what the glasses deliver, by event type only, never audio or content. |
|
||||
| E3 | "so annoying to have to scan a qr code every tie." and, on the package: "calling it pepper is fine... xylo.hermeven seems reight for the package name." and "logged in, go ahead and upload" | The client is packaged as "Pepper", package id `xylo.hermeven`, and uploaded to Dan's Even developer account as a private build. |
|
||||
| E4 | "fucker. port changed" (the installed app's page origin was `http://127.0.0.1:40315`, then a different port) | The bridge can be configured to accept a loopback page on any port, and accepts no other wildcard. Being an allowed origin grants no access without the device credential. |
|
||||
| E5 | On deploying E4 before review: "send to cody" | E4 is **not** deployed to the server until Cody has reviewed it. |
|
||||
|
||||
### F. Leaving the glasses when idle (from Dan's words on 2026-11-21)
|
||||
|
||||
Cody recorded after Round 9 that Dan's direct confirmation validates this contract. Section F was
|
||||
added afterwards, in the same way: Dan's words, quoted.
|
||||
|
||||
**Status of section F.** Dan told Cody directly on 2026-11-21 that acceptance of behaviour
|
||||
follows a device trial, not the other way round, and Cody issued SHIP FOR TRIAL for
|
||||
`3e0468802f3ae23b30c39c48f36d489fa92f9658`. Dan then tried build 0.1.1 on the glasses. His
|
||||
decisions, in his words, are in the table under "Decisions after the 0.1.1 trial" below.
|
||||
|
||||
| # | Dan said | Criterion |
|
||||
|---|---|---|
|
||||
| F1 | "another annoyance is that it stays on screen and never times out. I want the app to work like any other even app. call it to be used, and then it disappears but stays callable" | After a resting screen has been untouched for a set time, the app leaves the glasses by itself and can be called again. |
|
||||
| F2 | "notification only shows in telegram... the even notification did not come trhough." and "also from before, to not have the app block the even app notificationss is it appears to be doing." | "Leaves" means a real exit that returns the glasses to their normal screen, not a blanked display that keeps the app in front. |
|
||||
| F3 | "now what we need is for the pepper app to timeout and not stay visible on the glasses for so long." | Default times: 20 s on an answer, 30 s at Ready, 10 s on an error or cancel. Any gesture restarts the countdown. |
|
||||
| F4 | (implementer's safeguard, not requested) | It never leaves while recording, transcribing, waiting for the agent or for an approval; it does not close a session opened from the phone until the glasses are used; touching the phone page holds it open. |
|
||||
| F5 | (implementer's consequence of F1, not requested) | Since the app closes between questions, a question within ten minutes of the last continues the conversation and a later one starts a new conversation. |
|
||||
| F6 | "yes, promote it to beta" | Build 0.1.0 is on the beta channel with Dan as tester. |
|
||||
| F7 | On 0.1.1: "send it to cody" | 0.1.1 is **not** uploaded to Even or installed until Dan says so. |
|
||||
|
||||
#### Decisions after the 0.1.1 trial (2026-11-21, Dan's words)
|
||||
|
||||
| Item | Decision | Dan said |
|
||||
|---|---|---|
|
||||
| F1, F2 | Keep | After a swipe: "cool, she did exit that way." And: "yes, am getting tg notifications after her close." |
|
||||
| F3 | Keep for now | "20s seems okay for now." The 30 s and 10 s waits were not commented on. |
|
||||
| F4 | **Changed** | On a voice launch with nothing touched: "she's not leaving." Asked whether the countdown should start however the app was opened, at the cost of closing an untouched phone-opened session: "I also will almost never open her from the phone app. I'll use telegram when I'm going to look at my phone so the change is good in my \"eyes\"". |
|
||||
| F5 | Not yet tried | No decision. |
|
||||
|
||||
F4 as revised (build 0.1.2): the countdown runs however the app was opened. It still never
|
||||
leaves while recording, transcribing, waiting for the agent or for an approval, or while
|
||||
unpaired, and a touch on the phone page still holds it open for two minutes.
|
||||
|
||||
### G. Choosing an agent (from Dan's words on 2026-11-21)
|
||||
|
||||
A build for trial. Per Dan's standing instruction, his keep/change/remove decisions follow the
|
||||
device trial; nothing here is pre-accepted beyond what he is quoted as asking for.
|
||||
|
||||
| # | Dan said | Criterion |
|
||||
|---|---|---|
|
||||
| G1 | "what I want to build next is the ability to chat with all my agents... wendy is a sub-agent of pepper and being able to summon her through the app would be ideal." | The app can talk to more than one agent through the one bridge. |
|
||||
| G2 | "when pepper opens, and is inthe ready state, what if swiping could change the active agent? So pepper would show, but if we swipe, it would move between different available agents?" | At Ready a swipe moves to the next or previous agent; the app opens on the default agent and shows the current agent's name. |
|
||||
| G3 | "when no name is stated, then it uses pepper/default." | With no choice made, questions go to the default agent exactly as before. |
|
||||
| G4 | Asked whether to reopen on Pepper or on the last agent: "could we use the same 15 minute time out (I think that's what it is) that determines if it's a new session, or picks up from the last?" | Reopened within the conversation window (ten minutes; Dan was told it is ten, not fifteen), the app opens on the agent last talked to, in the same conversation; otherwise on the default. |
|
||||
| G5 | On the agent list coming from the bridge's settings: "Yeah, sure. that's fine." | The list is configured on the bridge; the phone can only pick from it. |
|
||||
| G6 | "Pepper, wendy and cody. yes. go for it." | The three agents for the first trial. Also Dan's go-ahead for giving the wendy and cody profiles an API key on the server. |
|
||||
| G7 | (implementer's choices, not requested) | Each agent has its own conversation. A follow-up goes to the agent that answered. On an answer a swipe still turns the page. The agent's name is shown while listening, thinking and on the answer. With only one agent the screens are unchanged. |
|
||||
|
||||
Not built: saying a name to route a question. Dan first preferred it, then proposed the swipe.
|
||||
|
||||
## Out of scope for this contract
|
||||
|
||||
Wake word ("Hey Pepper"), automatic end-of-speech detection, summoning other agents by name,
|
||||
listening automatically on launch, ending a conversation without closing the app, 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).
|
||||
@@ -12,10 +12,15 @@ next/previous page, new conversation). Gestures are a replaceable binding.
|
||||
| next / previous page | swipe down / swipe up | Matches Even's text-heavy template. |
|
||||
| new conversation, cancel request | OS contextual menu items | Keeps a destructive-feeling action off a single accidental gesture. |
|
||||
|
||||
Rejected for now:
|
||||
Adopted on 2026-11-21, after the first device run:
|
||||
|
||||
- **Hold to talk** (long press, release to send). Attractive, but the OS claims tap-then-long-press
|
||||
for its menu, and the two official sources disagree about how long-press events are routed.
|
||||
- **Hold to talk.** On a real G2 a touch held slightly too long is reported as a long press
|
||||
(`sysEvent` type 9, then type 10 on release; source 1 for the right temple, 3 for the left) and
|
||||
was being ignored, so "tap" appeared not to work. A long press now does what a tap does; if it
|
||||
started the recording and is held at least 0.7 s, releasing it sends. Dan: "long presses and
|
||||
release are the way." Whether the OS's tap-then-long-press menu gesture interferes is untested.
|
||||
|
||||
Rejected for now:
|
||||
- **End-of-speech detection.** Not attempted. Capture ends on tap, cancel, or the visible cap.
|
||||
|
||||
Open for device testing: whether Even treats a double tap that cancels a request (not on the root
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
# 0004: An opening menu, and a hands-free mode that listens for an agent's name
|
||||
|
||||
Status: implemented with fakes only; **nothing here is device-tested**. Date: 2026-11-28.
|
||||
|
||||
Dan (2026-11-28) first asked for the app to be always listening ("I want to be able to say
|
||||
'Wendy' to send whatever follows to Wendy, Cody to Cody"), then, after reading what that costs,
|
||||
chose: leave the app as it is, add this as a "hands free" mode, and open on a menu with
|
||||
"Hands free" first and "Agents" second, so that after "Hey Even, launch Pepper" one tap starts it.
|
||||
|
||||
## The menu
|
||||
|
||||
The app opens on a menu, which is now the root page:
|
||||
|
||||
```
|
||||
Hermeven
|
||||
|
||||
> Hands free
|
||||
Agents
|
||||
```
|
||||
|
||||
Swipe moves, tap opens, double tap asks the system to exit. Double tap at Ready goes back to the
|
||||
menu (it used to exit). An untouched menu leaves the glasses after 30 s, like Ready does. A
|
||||
question that was still running when the app was last closed is shown instead of the menu.
|
||||
|
||||
**Agents** is the app exactly as it was in 0.2.0: tap or hold to ask, swipe to choose, leaves
|
||||
when idle, the microphone opens only on a tap.
|
||||
|
||||
**Hands free** is the same screens, agents, conversations and question path, with one flag set.
|
||||
The flag does two things: the microphone listens while the app is at rest, and the app does not
|
||||
leave by itself. There is no second implementation of agents. The mode is not remembered: every
|
||||
launch starts at the menu with the microphone closed, and going back to the menu closes it.
|
||||
|
||||
Later entries (Telegram, spoken answers through a headset or Android Auto) are not designed
|
||||
here. The menu takes more entries; a mode that needs its own screens will need more than a flag.
|
||||
|
||||
## Hands free
|
||||
|
||||
While in this mode and at rest (Ready, an answer, an error, "Cancelled") the glasses' microphone
|
||||
is open. The status line starts with `●` for exactly as long as it is.
|
||||
|
||||
- "Wendy, what is on my calendar" in one breath: the question goes to Wendy.
|
||||
- "Wendy" alone: a recording starts for Wendy and is sent when the speaker stops (1.2 s pause).
|
||||
If nothing is said for 6 s it is dropped.
|
||||
- The name must be the **first** thing said ("hey"/"ok" before it is allowed). A name in the
|
||||
middle of a sentence does nothing.
|
||||
- Tap, hold-to-talk and swipe-to-choose all still work.
|
||||
- While a question is being transcribed or answered the microphone is closed.
|
||||
- The app does not leave the glasses by itself while in this mode.
|
||||
|
||||
## How
|
||||
|
||||
| Step | Where | Why there |
|
||||
|---|---|---|
|
||||
| Find stretches of speech | Phone, `core/vad.ts`, loudness only | So silence is never uploaded, and one utterance is one request. |
|
||||
| Transcribe and test for a leading name | Bridge, `POST /v1/wake`, the Whisper already there | The SDK gives raw PCM only; a keyword model in the WebView would need training per name. |
|
||||
| Ask the agent | The existing turn path (a text turn, or an audio turn after a name alone) | Request ids, deduplication, cancel and recovery are unchanged. A wake check creates nothing. |
|
||||
|
||||
Matching is exact, against the first word of the agent's display name or an alias from
|
||||
`HERMEVEN_AGENT_<ID>_WAKE`. A word that is only close ("Wendi", "copy") is reported to the phone's
|
||||
Diagnostics as a near miss and is never acted on.
|
||||
|
||||
## What this reverses
|
||||
|
||||
- "The microphone opens only on a tap" and "is never reopened without a new tap"
|
||||
(`docs/feasibility.md` section 2) hold in Agents and not in Hands free.
|
||||
- Idle exit (0.1.1) is suspended in Hands free.
|
||||
- Double tap at Ready no longer opens the system exit dialog; the menu is the root page now.
|
||||
Whether Even's review accepts a root page reached by two double taps is unverified.
|
||||
- "There is no end-of-speech detection" (0003): there is now, for recordings started by name.
|
||||
- The phone's Diagnostics may now show one spoken word (a near miss). Nothing else spoken
|
||||
appears in any log.
|
||||
|
||||
## Owner decisions pending (decide on the device)
|
||||
|
||||
1. In Hands free, staying open means phone notifications may not reach the lenses (one observation, 2026-11-21).
|
||||
2. In Hands free, an agent that can act (Pepper sent a Telegram message) can be started by speech nobody
|
||||
pressed a button for. Mitigations are the first-word rule, exact matching, the "Heard: ..."
|
||||
line while the agent works, and double tap to cancel. There is no confirmation step.
|
||||
3. In Hands free, every stretch of speech near the glasses, addressed to an agent or not, is uploaded to the
|
||||
bridge and transcribed there before being dropped.
|
||||
4. The names are needed on every question, including follow-ups.
|
||||
5. The menu costs one extra tap before the first question in Agents.
|
||||
|
||||
## Unknown until tried on a G2
|
||||
|
||||
Microphone level and background noise against the detector's thresholds (first guesses); whether
|
||||
Whisper spells the names as configured; delay from the end of speech to "thinking" (one upload
|
||||
and one transcription, about 1 to 2 s on the server's figures); battery with the microphone open
|
||||
continuously; whether the stream survives a locked phone for long periods; the server's CPU with
|
||||
a conversation or a television nearby (each stretch of speech is a transcription; capped at 30
|
||||
checks a minute, one at a time).
|
||||
@@ -0,0 +1,54 @@
|
||||
# 0005: Words on the glasses while recording
|
||||
|
||||
Status: implemented with fakes only; **not device-tested**. Date: 2026-11-28.
|
||||
|
||||
Dan (2026-11-28): "have the live transcription going when in agent mode so that I can see what
|
||||
I'm sending to the agent. I realize I'll need to subscribe to a new, paid for service to enable
|
||||
this."
|
||||
|
||||
## What it does (0.4.0)
|
||||
|
||||
In **Agents** only, while a recording is being made (by tap or by hold) the screen shows
|
||||
the words so far under "... is listening…", newest words kept in view. After the recording is
|
||||
sent, the last preview stays under "Transcribing…" and is then replaced by "Heard: ..." with the
|
||||
transcript the bridge actually gave the agent.
|
||||
|
||||
## How, and why no paid service yet
|
||||
|
||||
No new service. About every half second of new audio, and never more than one request at a time,
|
||||
the app sends **the recording so far** to `POST /v1/transcribe`, and the Whisper already in the
|
||||
bridge transcribes it. On the server's own figures (1.1 to 1.7 s per clip) the words should trail
|
||||
the voice by roughly one to two seconds and arrive in phrases, not word by word.
|
||||
|
||||
A preview is only ever drawn. The question is transcribed again, whole, by its own turn, so a
|
||||
preview can never be what the agent receives, and nothing about request ids, deduplication or
|
||||
cancellation changes.
|
||||
|
||||
## What a paid streaming recogniser would change
|
||||
|
||||
Word-by-word text a few hundred milliseconds behind the voice, and less CPU on the server. It
|
||||
would mean audio leaving the bridge host for a third party, a streaming connection through the
|
||||
Even WebView (documented as allowed, untested), and a recurring cost. Not chosen or designed
|
||||
here: try this first.
|
||||
|
||||
## Costs of this version
|
||||
|
||||
- While recording, the server transcribes continuously: one core busy for the length of the
|
||||
recording.
|
||||
- When the recording is sent, a preview still running is finished first, so the real
|
||||
transcription can start up to one clip (about 1.5 s) later than before.
|
||||
- A preview is a guess at an unfinished sentence and can differ from the final transcript. The
|
||||
"Heard:" line is the one that is true.
|
||||
- "Heard:" is cut at 160 characters on the glasses; the phone page has the whole text.
|
||||
|
||||
## Owner decisions pending
|
||||
|
||||
Whether the delay is acceptable; whether the "Heard:" line during thinking is wanted in Agents
|
||||
(new there in 0.4.0).
|
||||
|
||||
Decided by Dan on 2026-11-28, after the Round 19 review: the live preview is for the Agents
|
||||
sub-app only ("I'd only invoke the live transcription when in agent sub-app"). The reviewed
|
||||
0.4.0 candidate (`31ae4ef`) also previewed recordings in hands free; that was removed. He also
|
||||
ruled out sending the hands-free listener's audio to a paid service. So if a paid recogniser is
|
||||
adopted it serves the Agents preview (and possibly the final transcript there); hands free stays
|
||||
on the bridge's own Whisper.
|
||||
+114
-38
@@ -1,8 +1,8 @@
|
||||
# Running the bridge on a DigitalOcean droplet
|
||||
|
||||
**Status: written, not run.** These steps have not been executed on a droplet. The bridge, the
|
||||
built-in speech model and the Hermes adapter have only been run on the development desktop.
|
||||
Creating the droplet, pointing DNS at it and starting services are Dan's actions.
|
||||
**Status: run once, on 2026-11-21**, on the existing Hermes droplet rather than a new one. What
|
||||
was actually done, including where it differed from the steps below, is recorded in
|
||||
`docs/evidence/droplet/2026-11-21.md`. The steps below have been corrected to match.
|
||||
|
||||
## What runs where
|
||||
|
||||
@@ -46,51 +46,127 @@ accurate) and run `fetch-model` again.
|
||||
|
||||
## Steps
|
||||
|
||||
1. **Droplet and DNS.** Ubuntu LTS. Point a hostname at it (for example `bridge.example.com`).
|
||||
Firewall: allow 22, 80 and 443 only.
|
||||
2. **Packages.** Node.js 22.13 or later, git, Caddy.
|
||||
3. **User and directories.**
|
||||
Every command below is run as root on the server unless it says otherwise. Replace
|
||||
`bridge.example.com` with your hostname throughout.
|
||||
|
||||
1. **Droplet and DNS.** Ubuntu 24.04. Point a hostname at it. Firewall: allow 22, 80 and 443 only.
|
||||
The bridge (8787) and the Hermes API (8642) stay on loopback and are never opened.
|
||||
|
||||
2. **Packages.** Caddy, git and a C/C++ toolchain from Ubuntu, and Node.js 22 from nodejs.org
|
||||
with its checksum verified, installed at `/opt/node` (where the unit and the install script
|
||||
expect it). The toolchain is needed because the SQLite library compiles itself during
|
||||
`npm ci` when no prebuilt binary is fetched for the machine:
|
||||
```sh
|
||||
useradd --system --home /opt/hermeven --shell /usr/sbin/nologin hermeven
|
||||
mkdir -p /opt/hermeven /etc/hermeven
|
||||
# The state directory is the service user's alone: mode 0700, set explicitly.
|
||||
install -d -m 0700 -o hermeven -g hermeven /var/lib/hermeven
|
||||
apt-get update && apt-get install -y caddy git curl xz-utils ca-certificates build-essential python3
|
||||
V=$(curl -fsSL https://nodejs.org/dist/latest-v22.x/SHASUMS256.txt | grep -oE 'v22\.[0-9]+\.[0-9]+' | head -1)
|
||||
cd /tmp && curl -fsSLO https://nodejs.org/dist/$V/node-$V-linux-x64.tar.xz
|
||||
curl -fsSL https://nodejs.org/dist/$V/SHASUMS256.txt | grep " node-$V-linux-x64.tar.xz\$" | sha256sum -c -
|
||||
mkdir -p /opt/node-$V && tar -xJf node-$V-linux-x64.tar.xz -C /opt/node-$V --strip-components=1
|
||||
ln -sfn /opt/node-$V /opt/node && /opt/node/bin/node -v
|
||||
```
|
||||
The bridge also enforces this itself at every start. The directory that holds the database
|
||||
must be owned by the user the bridge runs as: if it belongs to anyone else (including root)
|
||||
the bridge refuses to start and leaves the directory exactly as it found it, even if its
|
||||
mode is already 0700. If the owner is right but the mode is looser, the bridge sets it to
|
||||
0700. So `-o hermeven` in the command above matters as much as `-m 0700`.
|
||||
4. **Code.** Clone the repository into `/opt/hermeven`, then `npm ci`. (The dev dependencies are
|
||||
needed: the bridge runs through `tsx`.)
|
||||
5. **Configuration.** Copy `deploy/bridge.env.example` to `/etc/hermeven/bridge.env`, fill it
|
||||
in, `chmod 600`, `chown hermeven`.
|
||||
5a. **Speech model.** As root (not the service user), fetch and verify the pinned model into a
|
||||
directory the service can read but not write:
|
||||
|
||||
3. **Get the release onto the server**, anywhere outside `/opt/hermeven`, for example:
|
||||
```sh
|
||||
HERMEVEN_ENV_FILE=/etc/hermeven/bridge.env npm --prefix /opt/hermeven run bridge:cli -- fetch-model
|
||||
HERMEVEN_ENV_FILE=/etc/hermeven/bridge.env npm --prefix /opt/hermeven run bridge:cli -- verify-model
|
||||
git clone git@git.xylo.gg:Xylo-Digital/hermeven.git /root/hermeven-src
|
||||
git -C /root/hermeven-src checkout <the commit you are deploying>
|
||||
```
|
||||
(or, from your own machine: `git archive <sha> | ssh root@server 'mkdir -p /root/hermeven-src && tar -x -C /root/hermeven-src'`).
|
||||
|
||||
4. **Install the application and the phone page.** One script does the ownership-sensitive part,
|
||||
so it cannot be done in the wrong order:
|
||||
```sh
|
||||
/root/hermeven-src/deploy/install.sh --bridge-url https://bridge.example.com
|
||||
```
|
||||
In order, it: creates the `hermeven` system user, `/opt/hermeven`, `/etc/hermeven` and the
|
||||
state directory (`install -d -m 0700 -o hermeven -g hermeven /var/lib/hermeven`); copies the
|
||||
release to `/opt/hermeven/app.new` and **gives that one directory to `hermeven`**; runs
|
||||
`npm ci` **as `hermeven`**, so no package install script runs as root; builds the phone page
|
||||
with your bridge address preset; **gives the finished tree back to `root:root`** and removes
|
||||
group/other write, so the running service cannot change its own code; installs the built page
|
||||
into `/opt/hermeven/www` (root-owned, directories 0755, files 0644, readable by Caddy and not
|
||||
writable by the service); swaps the tree into `/opt/hermeven/app` (keeping the previous one as
|
||||
`app.old`); and installs the systemd unit without starting it.
|
||||
|
||||
It never touches `/etc/hermeven/*` (secrets), `/var/lib/hermeven/*` (state) or
|
||||
`/opt/hermeven/models` (the speech model); no recursive ownership change reaches them.
|
||||
|
||||
The state directory must be owned by the user the bridge runs as. The bridge checks this at
|
||||
every start: a directory owned by anyone else (including root) is refused and left exactly
|
||||
as found, even at mode 0700; with the right owner and a looser mode it is set to 0700.
|
||||
|
||||
The dev dependencies are installed too: the bridge runs through `tsx`.
|
||||
|
||||
5. **Configuration.**
|
||||
```sh
|
||||
install -m 0600 -o hermeven -g hermeven /opt/hermeven/app/deploy/bridge.env.example /etc/hermeven/bridge.env
|
||||
```
|
||||
Then edit `/etc/hermeven/bridge.env`: set `HERMES_API_KEY` at least.
|
||||
|
||||
6. **Speech model.** Fetch and verify the pinned model, as root, into a directory the service can
|
||||
read but not write:
|
||||
```sh
|
||||
cd /opt/hermeven/app/services/bridge
|
||||
HERMEVEN_ENV_FILE=/etc/hermeven/bridge.env /opt/node/bin/node --import tsx src/cli.ts fetch-model
|
||||
HERMEVEN_ENV_FILE=/etc/hermeven/bridge.env /opt/node/bin/node --import tsx src/cli.ts verify-model
|
||||
```
|
||||
Every file is checked against the SHA-256 committed in `services/bridge/models/`. The running
|
||||
service never downloads anything: it re-verifies these files each time it loads the model and
|
||||
refuses to load if one is missing or different. This is the only step that needs outbound
|
||||
access to huggingface.co.
|
||||
6. **Hermes.** Enable its API server with a key, bound to `127.0.0.1`. Use a read-only or test
|
||||
profile first.
|
||||
7. **Service.** Copy `deploy/hermeven-bridge.service` to `/etc/systemd/system/`, then
|
||||
`systemctl daemon-reload && systemctl enable --now hermeven-bridge`. Watch
|
||||
`journalctl -u hermeven-bridge -f` for `stt.ready`. `stt.load_failed` with `reason: missing`
|
||||
or `mismatch` means step 5a was skipped or the files changed.
|
||||
8. **TLS.** Put `deploy/Caddyfile.example` at `/etc/caddy/Caddyfile` with your hostname, reload
|
||||
Caddy, then check `curl https://bridge.example.com/healthz`.
|
||||
9. **App build.** On your own machine:
|
||||
`HERMEVEN_BRIDGE_ORIGIN=https://bridge.example.com npm run -w @hermeven/even-client pack`.
|
||||
10. **Pair.** On the droplet, as the service user with the same environment:
|
||||
|
||||
7. **Hermes.** Enable its API server with a key, bound to `127.0.0.1` (see `docs/setup.md`), and
|
||||
put the same key in `bridge.env`. Use a read-only or test profile first.
|
||||
|
||||
8. **Start the bridge.**
|
||||
```sh
|
||||
systemctl enable --now hermeven-bridge
|
||||
journalctl -u hermeven-bridge -f # wait for "stt.ready"
|
||||
curl http://127.0.0.1:8787/healthz
|
||||
```
|
||||
`stt.load_failed` with `reason: missing` or `mismatch` means step 6 was skipped or the files
|
||||
changed.
|
||||
|
||||
9. **HTTPS.** Put `deploy/Caddyfile.example` at `/etc/caddy/Caddyfile` with your hostname, then:
|
||||
```sh
|
||||
caddy validate --config /etc/caddy/Caddyfile && systemctl reload caddy
|
||||
curl https://bridge.example.com/healthz # the bridge, through Caddy
|
||||
curl -I https://bridge.example.com/ # the phone page: 200, text/html
|
||||
```
|
||||
Caddy sends `/v1/*` and `/healthz` to the bridge and serves everything else from
|
||||
`/opt/hermeven/www`.
|
||||
|
||||
10. **Pair.** As the service user:
|
||||
```sh
|
||||
sudo -u hermeven HERMEVEN_ENV_FILE=/etc/hermeven/bridge.env npm --prefix /opt/hermeven run bridge:cli -- pair
|
||||
cd /opt/hermeven/app/services/bridge
|
||||
runuser -u hermeven -- env HOME=/var/lib/hermeven HERMEVEN_ENV_FILE=/etc/hermeven/bridge.env \
|
||||
/opt/node/bin/node --import tsx src/cli.ts pair
|
||||
```
|
||||
11. **Origin.** Open the phone page, read Diagnostics, "Page origin", put it in
|
||||
`HERMEVEN_ALLOWED_ORIGINS`, restart the service.
|
||||
Open `https://bridge.example.com/` in the Even app (see below) and enter the code.
|
||||
|
||||
11. **Allowed origins.** A page served from the bridge's own hostname (the QR sideload path)
|
||||
shares the API's origin and needs no entry. An app **installed** through Even Hub does: the
|
||||
Even phone app serves it from `http://127.0.0.1:<port>` and uses a different port on each
|
||||
launch (seen on a real phone: 40315, then another), so no exact origin can be listed. Set
|
||||
`HERMEVEN_ALLOWED_ORIGINS=http://127.0.0.1:*`, the one wildcard the bridge accepts: any port,
|
||||
loopback only, plain http only. It lets a page running on the phone itself read the bridge's
|
||||
replies; it grants no access, since every request still needs the device credential.
|
||||
|
||||
**Updating.** Repeat steps 3 and 4 with the new commit, then `systemctl restart hermeven-bridge`.
|
||||
If a model manifest changed, repeat step 6 first.
|
||||
|
||||
## The two client artifacts: the web page and the `.ehpk`
|
||||
|
||||
Both come from the same source (`apps/even-client`) and you need only one of them at a time.
|
||||
|
||||
| Artifact | Made by | Lives | Used for |
|
||||
|---|---|---|---|
|
||||
| Web build (`dist/`) | `deploy/install.sh` on the server (`npm run client:build`) | `/opt/hermeven/www`, served by Caddy at `https://bridge.example.com/` | Loading Hermeven in the Even app by scanning a QR code for that address (`npx evenhub qr --url https://bridge.example.com`). This is the developer sideload path: nothing is uploaded to Even. Even's documentation says sideloaded apps stop when the phone locks. |
|
||||
| Package (`hermeven.ehpk`) | `HERMEVEN_BRIDGE_ORIGIN=https://bridge.example.com npm run -w @hermeven/even-client pack`, on your own machine | Uploaded to Even's portal by you (`evenhub create` / `upload`, then `promote --to beta`) | Installing Hermeven as a real app (beta channel), which is what the locked-phone test needs. The package carries its own copy of the page, with the bridge origin in its network whitelist; it does not use `/opt/hermeven/www`. |
|
||||
|
||||
For a first run on the glasses only the web build is needed, and the install script has already
|
||||
produced it. The `.ehpk` is needed only when you move to a beta-channel install. Keeping the web
|
||||
page in place afterwards is harmless (it is static and holds no secrets) and useful for
|
||||
diagnostics, but a server that only serves packaged apps does not need it.
|
||||
|
||||
## Things to check on the droplet and write down
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
# Physical-device test plan
|
||||
|
||||
**Status: not started. No step below has been run.** Only Dan, or someone holding the G2, can run
|
||||
**Status: the complete checklist has not been run.** Some of what it covers was exercised
|
||||
informally on 2026-11-21 (pairing, spoken questions, hold-to-talk, voice launch, a first
|
||||
locked-phone answer); those observations are in `docs/evidence/device/2026-11-21.md` and were not
|
||||
recorded step by step against this plan, so no step below is signed off. Only Dan, or someone holding the G2, can run
|
||||
these and sign them off. A passing simulator or test suite does not count toward any item here.
|
||||
|
||||
Record results in a copy of this file under `docs/evidence/device/<date>.md`: for every step
|
||||
@@ -74,6 +77,23 @@ If A13 fails, stop and report it. It is a product-level blocker, not a bug to wo
|
||||
| C10 | Battery: glasses and phone percentage at start and after a stated duration and number of questions. | The four numbers and the duration. Do not extrapolate. |
|
||||
| C11 | Per question: seconds from second tap to answer, noted for at least 10 questions. | The raw list. The phone page shows the STT and agent split for each. |
|
||||
|
||||
## D. The menu and hands-free mode (0.3.0; nothing here has been run)
|
||||
|
||||
| # | Do | Record | Answers |
|
||||
|---|---|---|---|
|
||||
| D0 | "Hey Even, launch Pepper". | Does the menu appear with `>` beside "Hands free"? Do swipes move it? Does double tap at Ready come back to it, and double tap on the menu show the exit dialog? | The menu on a real G2; whether `>` and the indent render. |
|
||||
| D1 | Tap "Hands free" and leave it. | Does the status line start with `●`? Does the body list the names? | The microphone opens without a further tap on a real G2. |
|
||||
| D2 | Say "Wendy, what time is it" at a normal volume. Repeat for each agent, five times each. | How many reached the right agent. For misses, the "heard ..." line in Diagnostics, if any. | Detector thresholds; how Whisper spells each name (aliases to add). |
|
||||
| D3 | Say only a name, wait for "... is listening", ask, stop speaking. | Seconds from the name to the screen changing; whether the question was sent whole. | Name-only flow; the 1.2 s end-of-speech pause. |
|
||||
| D4 | Talk to someone for two minutes without using a name. Then mention an agent mid-sentence. | Did anything start? | False triggers. |
|
||||
| D5 | Same with a television or music on. | Did anything start? Did a real "Wendy, ..." still work? | Noise. |
|
||||
| D6 | Leave it open 30 minutes, phone locked in a pocket, then say "Pepper, are you there". | Did it answer? Battery of glasses and phone before and after. | Whether the stream survives; battery cost. |
|
||||
| D7 | While it is open, have a notification arrive. | Did it reach the lenses? | The cost of staying open. |
|
||||
| D8 | Double tap back to the menu, choose "Agents". | Does `●` go away, does tap still work, does the app leave by itself again? | Leaving hands free. |
|
||||
|
||||
| D9 | In Agents, tap and speak a long sentence slowly. | Do words appear while speaking? How far behind? Do they jump or flicker? | Live preview on a real G2 and the real server. |
|
||||
| D10 | After sending, watch the screen. | Does "Heard: ..." show what you said? Seconds from tap to "thinking" compared with 0.3.0. | Whether a running preview delays the real transcription noticeably. |
|
||||
|
||||
## Reporting
|
||||
|
||||
Anything that fails in A13, A14, A15 or C1 is a blocker or a stated limitation of the product, to
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
# 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.
|
||||
|
||||
## Second session, about 20:56 to 21:30 UTC
|
||||
|
||||
Same glasses and phone, phone unlocked. Dan's reports are quoted; server facts are from the
|
||||
bridge log and the commands run on the server.
|
||||
|
||||
### QR-sideloaded page, build `7f055d4` (installed 20:55 UTC)
|
||||
|
||||
| Dan reported | Establishes |
|
||||
|---|---|
|
||||
| "1. Even app host (SDK 0.0.16), found after 4 ms / HUD created / 3. Hermevn Ready" | In the Even app, this build found the SDK host 4 ms after start, created the HUD page, and the glasses showed the Ready screen. The Even app provides its connection essentially at once, so the precautionary detection wait was never needed. |
|
||||
| "Tap to ask isn't working though now. It worked before." and "one tap stays on \"ready\"" | A touch on the temple did not start recording. The bridge log shows the page checked in at 20:56:13 and no turn afterwards. |
|
||||
|
||||
### QR-sideloaded page, build `b8191a7` (installed 21:06 UTC), which adds the "Glasses input" line
|
||||
|
||||
| Dan reported | Establishes |
|
||||
|---|---|
|
||||
| "event ignored in the glasses input line", "like the first one. syxEvent type 9" | The touch was delivered to the app as `sysEvent` type 9 (long press), which that build ignored. The earlier "tap not working" was this, not a regression. |
|
||||
| "left temple is 10/3", "right is 9/1" | Long-press release (type 10) is delivered as well as long-press start (type 9); event source is 1 for the right temple and 3 for the left, as Even documents. |
|
||||
| "okay, quick tap worked." | A short tap still starts recording on this build. |
|
||||
|
||||
### Installed private build "Pepper" (`xylo.hermeven` 0.1.0, built from `fd99255`, uploaded 21:22 UTC)
|
||||
|
||||
| Dan reported | Establishes |
|
||||
|---|---|
|
||||
| "Installed, looks like I had to hit \"open\" and when I do, need another pairing code" | The private build installs and opens from the Even app. Its storage is separate from the sideloaded page's. |
|
||||
| "failed, says cannot reach the bridge" | With no allowed origin configured, the installed app could not call the bridge. |
|
||||
| Page origin: "http://127.0.0.1:40315" | An installed app is served by the Even app from a loopback address on the phone. |
|
||||
| (after the bridge was set to allow exactly that origin and restarted at 21:26:57 UTC) "fucker. port changed" | The port is different on the next launch, so an exact origin cannot be listed. |
|
||||
|
||||
Not reported for the installed build: the Runtime and HUD page lines, whether the glasses showed
|
||||
anything, whether it appears in the glasses' own menu.
|
||||
|
||||
### Not tried in either session
|
||||
|
||||
Hold-to-talk on the device (the build that implements it, `9cb34b3` and later, was installed as a
|
||||
page at 21:18 UTC and is inside the private build, but Dan did not report using it), paging, the
|
||||
contextual menu, cancel, locked phone, voice launch through Even's assistant, and whether phone
|
||||
notifications reach the lenses while the app is open.
|
||||
|
||||
## Third session, 21:52 to 21:56 UTC: the installed app, on the build Cody reviewed
|
||||
|
||||
### Exactly what was running
|
||||
|
||||
| Piece | Identity |
|
||||
|---|---|
|
||||
| Commit under review | `d90cd8972af0ed26a1c4c25a6acdbda775fcf8a7` |
|
||||
| Bridge on the server | That commit, installed 21:50 UTC with `deploy/install.sh` (`/opt/hermeven/app/DEPLOYED_SHA`), on Dan's go-ahead ("yes, go ahead") |
|
||||
| Client on the phone | Private build "Pepper", `xylo.hermeven` 0.1.0: package `hermeven.ehpk`, 98,716 bytes, SHA-256 `dadb9d1160b81d2f307344d86bb36f78fd805da764bfe5b822dccfa429d6c285`, uploaded 21:22 UTC |
|
||||
| Is that package the reviewed client? | It was packed at `fd99255`. No file under `apps/even-client` or `packages/` differs between `fd99255` and `d90cd89` (`git diff --stat` is empty), and a fresh build of `d90cd89` produces the same script, `assets/index-DMY0MM6P.js`, SHA-256 `1eb2c95824b5f24b8dd0ce8b8eafde33d49d680f0a3abb0ec1235cc2badc5145`. So the client code is the reviewed code; the package file itself was produced one commit of documentation earlier. |
|
||||
| Server setting | `HERMEVEN_ALLOWED_ORIGINS=http://127.0.0.1:*` |
|
||||
| How it was opened | From the Even app's installed apps, not by QR. Phone unlocked. |
|
||||
|
||||
### What Dan reported (one message, about 21:57 UTC)
|
||||
|
||||
> "1 - We need to chill out with the runtime/hud checks. They are annoying to transpose. 0.0.16
|
||||
> and created / 2 - Works. / 3 - Yes, works."
|
||||
|
||||
in answer to these three requests:
|
||||
|
||||
1. Read the Runtime and HUD page lines from Diagnostics.
|
||||
2. Hold a temple, ask a short question while holding, release.
|
||||
3. Press and let go almost at once (it should stay recording), ask a short question, then tap once to send.
|
||||
|
||||
| Check | Dan's report | Establishes |
|
||||
|---|---|---|
|
||||
| 1 | "0.0.16 and created" | Inside the Even app the installed build reports the Even app host with SDK 0.0.16, and the HUD page was created. He did not read out the "found after N ms" figure. |
|
||||
| 2 | "Works." | Hold, speak, release: the question was sent on release and answered. |
|
||||
| 3 | "Yes, works." | A quickly released press left the recording running, and a following tap sent it. |
|
||||
|
||||
He also reported: "I asked pepper to say hello in telegram, and she did." That is the first turn
|
||||
through Hermeven in which the agent used a tool with an effect outside the conversation.
|
||||
|
||||
### What the server recorded
|
||||
|
||||
| Time (UTC) | Event | Transcription | Agent | Total |
|
||||
|---|---|---|---|---|
|
||||
| 21:52:01 | device paired (from an origin of the form `http://127.0.0.1:<port>`; pairing needs the allowed-origin rule) | | | |
|
||||
| 21:53:25 | conversation created | | | |
|
||||
| 21:53:25 to 21:53:29 | audio turn `ad1717fa`, succeeded | 1.2 s | 2.7 s | 3.9 s |
|
||||
| 21:53:41 to 21:54:02 | audio turn `75b23fce`, succeeded | 1.1 s | 19.8 s | 21.0 s |
|
||||
| 21:54:25 to 21:54:28 | audio turn `887da3c4`, succeeded | 1.2 s | 2.1 s | 3.3 s |
|
||||
| 21:55:27 to 21:56:12 | audio turn `8721c17a`, succeeded | 1.1 s | 43.5 s | 44.7 s |
|
||||
|
||||
Four recordings, four turns, four answers: no recording produced two turns and none was lost.
|
||||
Each has its own request id and exactly one `turn.accepted` and one `turn.done`.
|
||||
|
||||
### Limits of this evidence
|
||||
|
||||
- The server cannot tell a hold from a tap: both arrive as one audio upload. That checks 2 and 3
|
||||
were a hold-and-release and a quick-press-then-tap is Dan's statement. Which of the four turns
|
||||
was which was not recorded.
|
||||
- "Exactly one question sent" for the hold is supported by the count above (no extra turn appears
|
||||
anywhere in the session), not by a per-gesture trace.
|
||||
- The 19.8 s and 43.5 s turns are presumably the ones where the agent did more work (one of them
|
||||
the Telegram message); the log does not say which.
|
||||
- Still not tried: locked phone, relaunching and finding the pairing still present, paging, the
|
||||
contextual menu, cancel, the ring, voice launch, notifications over the app, the glasses' own
|
||||
app menu.
|
||||
|
||||
## Fourth session, about 21:58 to 22:10 UTC: private build, then beta
|
||||
|
||||
Same glasses and phone. Client: "Pepper" `xylo.hermeven` 0.1.0 (the package identified in the
|
||||
third session). Bridge: `d90cd89`. Everything here is Dan's report; the implementer did not ask
|
||||
him to read Diagnostics, at his request.
|
||||
|
||||
| Dan reported | Build channel | Establishes |
|
||||
|---|---|---|
|
||||
| "even says \"I don't have anything called pepper to open\"" | private | Even's assistant treats "open Pepper" as an app-launch request, and a private build is not known to it. |
|
||||
| "notification only shows in telegram... the even notification did not come trhough." | private | While the app was open on the glasses, a Telegram notification reached the phone but did not appear on the lenses. Whether Telegram notifications normally appear on his lenses was asked and not answered, so this is one observation, not a controlled comparison. |
|
||||
| (22:00 UTC: 0.1.0 promoted to beta and Dan invited as tester, on his instruction) | | |
|
||||
| "very cool, it's an app now in the menu." | beta | A beta build appears in the glasses' own app menu. |
|
||||
| "summoning pepper with hey even works too. Even from a locked phone." | beta | Even's assistant launches the beta build by name, including with the phone locked. |
|
||||
| "pepper answers on a locked phone too btw" | beta | With the phone locked, a spoken question was captured by the glasses, transcribed, answered by the agent and shown. This is the first outcome in the kickoff specification. |
|
||||
|
||||
Not recorded for this session: times of individual questions, how many, whether the phone was in
|
||||
a pocket, how long it had been locked, or battery. The specification's acceptance run (ten
|
||||
consecutive cycles, locked and pocketed, with failures counted) has **not** been done; this is a
|
||||
first success, not that test.
|
||||
|
||||
Build 0.1.1 (idle exit) has not been installed on the device.
|
||||
|
||||
## Fifth session, about 23:20 to 23:35 UTC: build 0.1.1, idle exit
|
||||
|
||||
| Piece | Identity |
|
||||
|---|---|
|
||||
| Client | "Pepper" `xylo.hermeven` 0.1.1, beta channel. Package 99,946 bytes, SHA-256 `7dd36b4c7c83191ed830d325204175ca1423ceda6167a683b31655cab80c6eeb`, built from `3e0468802f3ae23b30c39c48f36d489fa92f9658` (Cody: SHIP FOR TRIAL), uploaded 23:09:58 UTC |
|
||||
| Bridge | `d90cd89`, unchanged |
|
||||
|
||||
Everything below is Dan's report. None of it is visible to the server: leaving the glasses
|
||||
happens on the phone.
|
||||
|
||||
| Dan reported | Establishes |
|
||||
|---|---|
|
||||
| "updated, pairing code not needed." | The pairing survived an update from 0.1.0 to 0.1.1 on the beta channel. |
|
||||
| "pepper summoned. am waiting 30s now." then "she's not leaving." | After a voice launch with nothing touched, 0.1.1 did not leave. Under 0.1.1's rule that means no `glassesMenu` launch source reached the app. Whether the host sent nothing or sent `appMenu` was not determined. |
|
||||
| (asked to swipe once and wait) "cool, she did exit that way." | After one gesture, the app left the glasses by itself. This is the first time `shutDownPageContainer(0)` is known to work on a real G2 through the Even app. How long after the swipe was not timed. |
|
||||
| "yes, am getting tg notifications after her close." | With the app gone, Telegram notifications reach the lenses again. |
|
||||
| "20s seems okay for now." | The wait after an answer is acceptable for now. |
|
||||
|
||||
Not observed: an exit that the host refused, the retry path, exit from an error screen, the
|
||||
ten-minute conversation rule, a question asked after a relaunch.
|
||||
|
||||
Build 0.1.2 (countdown starts however the app was opened) has not been installed.
|
||||
|
||||
## Sixth session, 2026-11-22 after 00:38 UTC: build 0.2.0, choosing an agent
|
||||
|
||||
| Piece | Identity |
|
||||
|---|---|
|
||||
| Client | "Pepper" `xylo.hermeven` 0.2.0, beta channel, built from `dcb373639ef97d4c7f63abaddafadef7f6edf226` (package hash in the server evidence file) |
|
||||
| Bridge | the same commit, with Pepper, Wendy and Cody configured |
|
||||
|
||||
Dan was asked to update the app, open it by voice, check that Ready shows "Pepper", swipe to
|
||||
Wendy and then Cody, and ask a question, and to say if a name was cut off or the bottom line
|
||||
looked cramped. His whole report:
|
||||
|
||||
> "All tests check out. Fucking sweet. I think this is a good stopping point."
|
||||
|
||||
What that establishes: the owner tried 0.2.0 on the glasses and is satisfied with it. What it
|
||||
does not record: which agents he asked, how many questions, whether a follow-up or a reopen was
|
||||
tried, or how the names looked. No keep/change/remove decision was stated item by item for
|
||||
contract section G, and none for F5 (the ten-minute rule). No trial of 0.1.2 was reported
|
||||
separately; 0.2.0 contains the same idle-exit behaviour.
|
||||
@@ -0,0 +1,39 @@
|
||||
# 0.3.0 on the server and the glasses, 2026-11-28
|
||||
|
||||
**Whose evidence this is.** Server facts are the implementer's (Claude's) own commands and the
|
||||
bridge's replies. What happened on the glasses is Dan's report, quoted. Nothing on the device was
|
||||
seen by the implementer.
|
||||
|
||||
## Deployment and upload
|
||||
|
||||
Cody, Round 18: SHIP, trial designation SHIP FOR TRIAL, on
|
||||
`44ea1148c34a271f4fdc565ef71a145adf459b42`. Asked to confirm the bridge deployment and the
|
||||
upload, Dan: "go".
|
||||
|
||||
| Step | Result |
|
||||
|---|---|
|
||||
| `git archive 44ea114` to `/root/hermeven-src`, `deploy/install.sh --bridge-url https://hermeven.xylo.gg` | All seven steps. `DEPLOYED_SHA` is `44ea1148c34a271f4fdc565ef71a145adf459b42` (was `dcb3736`). 0 files in the application tree not owned by root. |
|
||||
| `systemctl restart hermeven-bridge`, 19:06 UTC | active; `stt.ready`; healthz ok locally and at `https://hermeven.xylo.gg`. Hermes was not restarted. `/etc/hermeven/bridge.env` was not changed. |
|
||||
| Paired devices | Preserved (three active, as before). |
|
||||
| Smoke test with a temporary device (`deploy-smoke-wake`, revoked afterwards) | `/v1/agents`: Pepper, Wendy, Cody. `POST /v1/wake` with the repository's 11 s archive speech clip (no agent name in it): 200, `matched: false`, empty text, 1.49 s. Without a credential: 401, locally and from outside. No `wake.*` log line was written for the unmatched clip. |
|
||||
| Not tested on the server | A clip that begins with an agent's name (none exists). |
|
||||
| Package | `hermeven.ehpk`, 104,464 bytes, SHA-256 `5c8de848431143bbf5638e3d8b192536ab4fb0f0d13b684f72450f6de77f9fcf`, built from `44ea114` with a clean tree; a second pack gave the same hash. |
|
||||
| Even account | `evenhub upload` 0.3.0, then `evenhub promote 0.3.0 --to beta`. `evenhub ls`: 0.3.0 Private, beta; 0.2.0 no longer on a channel. |
|
||||
|
||||
## What Dan reported
|
||||
|
||||
One message, after updating:
|
||||
|
||||
> "pretty cool. What's weird is that when I'm in an active wendy session, I still have to say her
|
||||
> name before any time i address her. I'm undecided if this is good or not. Saying the name of a
|
||||
> different agent does switch sessions... I'm tempted to leave it as is for now."
|
||||
|
||||
| Establishes | |
|
||||
|---|---|
|
||||
| Hands free works on a real G2 through the real server | A name spoken to the glasses reached an agent, more than once, and a different name switched agent. So the microphone opened without a tap, the loudness detector found speech from the G2 microphone, and Whisper wrote at least two of the names as configured. |
|
||||
| Owner decision, 0004 item 4 (the name is needed on every question) | Undecided; "leave it as is for now". No change made. |
|
||||
|
||||
Not reported: which agents, how many attempts or misses, any near miss in Diagnostics, the menu
|
||||
itself, the name-alone flow, the delay, false triggers, noise, battery, the locked phone,
|
||||
notifications while open, or Agents mode. Section D of `docs/device-test-plan.md` has not been
|
||||
run as a checklist.
|
||||
@@ -0,0 +1,312 @@
|
||||
# Droplet deployment record, 2026-11-21
|
||||
|
||||
First deployment of the bridge. Done by Claude over SSH with Dan's approval for each kind of
|
||||
change. This is evidence about the server only. **Nothing here involved the glasses or a phone.**
|
||||
|
||||
## Where
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Host | The existing Hermes droplet (Ubuntu 24.04, 4 vCPU "DO-Premium-AMD", 8 GB RAM), not a new one |
|
||||
| Public name | `hermeven.xylo.gg` |
|
||||
| Deployed commit | `f02715fb6487f4e2ff0adeccfaad2403e1724aa5` (the commit Cody marked SHIP), copied with `git archive` |
|
||||
| Hermes | v0.23.1; profile `default` (Pepper) |
|
||||
|
||||
## What was changed on the server
|
||||
|
||||
| Change | Detail |
|
||||
|---|---|
|
||||
| Retired the unfinished browser-extension service | `hermes-extension-api-v0222` (crash-looping on a missing module) and `hermes-fury-extension-tunnel` (an SSH reverse tunnel of port 8642 to Dan's desktop) stopped and disabled. Unit files left in place. |
|
||||
| Rotated `API_SERVER_KEY` | The old key was also in the retired extension's environment file. New 64-character key. |
|
||||
| Enabled the Hermes API server | `platforms.api_server.enabled: true`, loopback `127.0.0.1:8642`. Gateway restarted once; about 33 s of downtime for `default`, `cody`, `natalie`, `wendy`. |
|
||||
| Backups | The previous `config.yaml` and `.env` are in `~hermes/.hermes/backups/hermeven-20261121T195611Z/` (mode 600). |
|
||||
| Node.js | v22.23.5 from nodejs.org, SHA-256 verified, at `/opt/node`. |
|
||||
| Service user and state | `hermeven` (system user); `/var/lib/hermeven` 0700. |
|
||||
| Bridge | `/opt/hermeven/app`, dependencies installed as `hermeven`, tree owned by root. Service `hermeven-bridge` on `127.0.0.1:8787`. |
|
||||
| Speech model | Pinned `whisper-base` fetched and verified into `/opt/hermeven/models` (root-owned, read-only to the service). |
|
||||
| Caddy | Ubuntu package 2.6.2; Let's Encrypt certificate obtained. Proxies `/v1/*` and `/healthz` to the bridge; serves the built client from `/opt/hermeven/www`. |
|
||||
| Firewall | 80 and 443 opened. 8787 and 8642 are not reachable from outside. |
|
||||
|
||||
## Differences from the written guide (now corrected in it)
|
||||
|
||||
- The service starts Node directly (`node --import tsx src/main.ts`) instead of `npm run`.
|
||||
- The code lives in `/opt/hermeven/app`, not `/opt/hermeven`.
|
||||
- Caddy also serves the built phone page from the bridge's own origin.
|
||||
- The built client was compiled on the desktop with the bridge address preset and uploaded.
|
||||
|
||||
## What was verified, and how
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| Hermes API: `/health` | `{"status":"ok","platform":"hermes-agent","version":"0.23.1"}` |
|
||||
| Hermes API without a key, and with a wrong key | 401, 401 |
|
||||
| Hermes capabilities | runs, status, stop: true; idempotency supported, durable, 86,400 s |
|
||||
| Bridge start | `stt.loading` then `stt.ready` in 2.0 s; 462 MB resident |
|
||||
| State file modes | directory 700; database, WAL, SHM 600; owner `hermeven` |
|
||||
| Transcription of the 11 s speech fixture, three runs | 2.3 s, 2.1 s, 1.8 s; transcript correct. A 4 s clip: 1.3 s |
|
||||
| Typed question through the bridge to Pepper (real model) | "pong", outcome `succeeded`, 5.2 s in the agent |
|
||||
| Follow-up in the same conversation ("what word did you reply with?") | "pong", 1.8 s: Hermes carried the context |
|
||||
| From outside: `https://hermeven.xylo.gg/healthz` | 200 |
|
||||
| From outside: `/v1/device` with no credential | 401 |
|
||||
| From outside: plain HTTP | 308 redirect to HTTPS |
|
||||
| From outside: ports 8787 and 8642 directly | no connection |
|
||||
| The other agents and the n8n webhook after the restart | all five profiles `running`; webhook health ok |
|
||||
|
||||
The test device used for the two questions was revoked afterwards. Those two questions are real
|
||||
turns in Pepper's history, in their own session.
|
||||
|
||||
## Not verified
|
||||
|
||||
- Anything on a phone or the glasses: page load in the Even app, pairing from the phone, the
|
||||
microphone, the display, locked-phone behaviour.
|
||||
- Speech from the glasses' microphone. The transcription timings use a clean archive recording.
|
||||
- A question that makes Pepper use a tool or ask for approval.
|
||||
- Memory and latency under sustained use; behaviour when Whisper and several agents are busy at once.
|
||||
- Backups of `/var/lib/hermeven`, log rotation, monitoring, and an upgrade procedure.
|
||||
- The service was started with these hardening options and loaded the model, but no option was
|
||||
tested by trying to violate it.
|
||||
|
||||
## Later the same day
|
||||
|
||||
### The static phone page was replaced twice
|
||||
|
||||
The bridge on the server is still commit `f02715f`. Only the static page in `/opt/hermeven/www`
|
||||
changed, and it was built from client code that Cody has not reviewed:
|
||||
|
||||
| When (UTC) | Page built from | Why |
|
||||
|---|---|---|
|
||||
| 19:5x | `f02715f` | First deployment |
|
||||
| 20:1x | `e5559dc` | A host-detection change made on a wrong diagnosis (below) |
|
||||
| after this record | the commit that adds this section | Shorter detection wait; corrected comments |
|
||||
|
||||
### What happened on the phone, and a correction
|
||||
|
||||
Dan opened `https://hermeven.xylo.gg` on his Android phone, paired with a code from the server,
|
||||
and typed a question; Pepper answered (bridge log: device paired, one text turn, `succeeded`,
|
||||
2.1 s in the agent). **The page had been opened by scanning the QR code with the phone's camera,
|
||||
so it was running in Chrome, not in the Even app.** Its Diagnostics said "Browser preview: no
|
||||
glasses, no microphone", and the browser line had no WebView marker.
|
||||
|
||||
Before that was understood, the implementer (Claude) wrongly concluded that the Even app provides
|
||||
its connection late, told Dan that the Even app had loaded the page, allowed its network calls
|
||||
and confirmed storage writes, and shipped a change to wait for the connection. None of those
|
||||
three statements was supported: nothing has yet run inside the Even app. They were retracted
|
||||
the same day. What the phone run does show is phone browser -> HTTPS -> bridge -> Pepper.
|
||||
|
||||
### Loading the page in a desktop browser
|
||||
|
||||
Chrome on the development desktop, `https://hermeven.xylo.gg/`: the page rendered the pairing
|
||||
form with the bridge address preset to `https://hermeven.xylo.gg`, and Diagnostics reported
|
||||
`Page origin: https://hermeven.xylo.gg`. `HERMEVEN_ALLOWED_ORIGINS` on the server is empty: the
|
||||
page and the API share one origin, so no cross-origin allowance exists or is needed.
|
||||
|
||||
Through the server's Caddy 2.6.2, from outside:
|
||||
|
||||
| Request | Result |
|
||||
|---|---|
|
||||
| `GET /` | 200 `text/html` |
|
||||
| `GET /assets/index-<hash>.js` | 200 `text/javascript`, 296,329 bytes |
|
||||
| Headers on both | `strict-transport-security: max-age=31536000`, `x-content-type-options: nosniff`, `referrer-policy: no-referrer`, no `server` header |
|
||||
| `GET /v1/device` with `Origin: https://evil.example` | no `access-control-allow-origin` header |
|
||||
| `OPTIONS /v1/turns` preflight from that origin | 404, no `access-control-allow-origin` header |
|
||||
|
||||
## Clean-host proof of the written guide (not this server)
|
||||
|
||||
The guide's server-side steps were run from an empty `/opt/hermeven` on a disposable Ubuntu 24.04
|
||||
host: a privileged Docker container with systemd as PID 1, on the development desktop
|
||||
(`tests/deploy/runbook-proof.sh`). Hermes is not present there, and the hostname is `localhost`
|
||||
with a certificate from Caddy's local CA, so this proves the install sequence, ownership, the
|
||||
unit and the Caddy configuration. It does not prove a public certificate or a second real server.
|
||||
|
||||
The first attempt failed at `npm ci`: a clean Ubuntu has no compiler, and the SQLite library
|
||||
builds from source there. The guide and `install.sh` now require `build-essential` and `python3`.
|
||||
(The real server already had them, which is why the first deployment did not show this.)
|
||||
|
||||
Output of the passing run:
|
||||
|
||||
```
|
||||
### host image
|
||||
Ubuntu 24.04.5 LTS
|
||||
/opt/hermeven does not exist
|
||||
id: 'hermeven': no such user
|
||||
### step 2: packages (Caddy, git, Node.js with checksum)
|
||||
node-v22.23.5-linux-x64.tar.xz: OK
|
||||
v22.23.5
|
||||
2.6.2
|
||||
### step 3: get the release onto the server (git clone of 65260911ae907846ea7febd933e8c0e37c471c22)
|
||||
65260911ae907846ea7febd933e8c0e37c471c22
|
||||
### step 4: deploy/install.sh
|
||||
==> 1/7 user and directories
|
||||
==> 2/7 copy the release to /opt/hermeven/app.new
|
||||
==> 3/7 npm ci as the unprivileged user
|
||||
==> 4/7 build the phone page for https://localhost
|
||||
==> 5/7 hand the tree back to root
|
||||
==> 6/7 install the phone page into /opt/hermeven/www
|
||||
==> 7/7 activate the new tree and install the unit
|
||||
Installed 65260911ae907846ea7febd933e8c0e37c471c22 to /opt/hermeven/app
|
||||
Phone page installed to /opt/hermeven/www
|
||||
Not started. Next: configuration, speech model, then 'systemctl enable --now hermeven-bridge'
|
||||
### ownership and permissions after install
|
||||
DEPLOYED_SHA: 65260911ae907846ea7febd933e8c0e37c471c22
|
||||
app tree owner: root:root 755
|
||||
not root-owned in app: 0 group/other-writable in app: 0
|
||||
node_modules present: yes
|
||||
hermeven cannot write the app tree
|
||||
hermeven cannot create files in the source
|
||||
www: root:root 755 index root 644 files=3
|
||||
hermeven cannot write www
|
||||
caddy can read www
|
||||
state dir: hermeven:hermeven 700
|
||||
secrets dir entries: 0 (install.sh wrote none)
|
||||
models dir: not created by install.sh
|
||||
### steps 5, 6: configuration and speech model
|
||||
hermeven:hermeven 600 /etc/hermeven/bridge.env
|
||||
Verified 7 file(s); downloaded 7.
|
||||
Verified 7 file(s).
|
||||
models owner: root:root
|
||||
### step 8: start the bridge under systemd
|
||||
systemd-analyze verify: ok
|
||||
unit: active (running as hermeven, MainPID uid hermeven)
|
||||
"msg":"Server listening at http://127.0.0.1:8787" "msg":"stt.loading" "msg":"stt.ready"
|
||||
healthz (direct): {"status":"ok","schema_version":1}
|
||||
state files: 700 hermeven 600 /var/lib/hermeven/hermeven.sqlite;hermeven 600 /var/lib/hermeven/hermeven.sqlite-shm;hermeven 600 /var/lib/hermeven/hermeven.sqlite-wal;
|
||||
### step 9: HTTPS through Caddy (hostname replaced by localhost; certificate from Caddy's local CA)
|
||||
caddy fmt --diff on the example: exit 0, 0 changed line(s)
|
||||
Valid configuration
|
||||
caddy: active
|
||||
GET / -> 200 text/html; charset=utf-8
|
||||
GET /assets/index-DqyTqNG5.js -> 200 text/javascript; charset=utf-8 296323 bytes
|
||||
GET /healthz -> {"status":"ok","schema_version":1}
|
||||
GET /v1/device -> 401 (no credential)
|
||||
headers on /:
|
||||
referrer-policy: no-referrer
|
||||
strict-transport-security: max-age=31536000
|
||||
x-content-type-options: nosniff
|
||||
headers on the asset:
|
||||
referrer-policy: no-referrer
|
||||
strict-transport-security: max-age=31536000
|
||||
x-content-type-options: nosniff
|
||||
bridge address built into the page: 1 occurrence(s) of https://localhost
|
||||
CORS for a foreign origin: 0 allow-origin header(s)
|
||||
### done: 65260911ae907846ea7febd933e8c0e37c471c22
|
||||
```
|
||||
|
||||
## Evening: further changes to the server, each approved by Dan in conversation
|
||||
|
||||
| Time (UTC) | Change | Dan's approval |
|
||||
|---|---|---|
|
||||
| 20:55:16 | Static page replaced with a build of `7f055d4` | "1 - yes" |
|
||||
| 21:06:46 | Static page replaced with a build of `b8191a7` (adds the Glasses input diagnostic) | "yes, put on droplet" |
|
||||
| 21:18:07 | Static page replaced with a build of `fd99255` (hold-to-talk; packaged as "Pepper") | "go for it" (given in reply to a message asking for both the upload and this) |
|
||||
| 21:26:57 | `HERMEVEN_ALLOWED_ORIGINS` set to `http://127.0.0.1:40315` in `/etc/hermeven/bridge.env` (previous file kept alongside as a `.bak-` copy); bridge restarted, about 4 s down | "yes, go ahead" |
|
||||
|
||||
The bridge code on the server is still `f02715f`. The allowed-origin setting turned out to be
|
||||
useless (the port changes each launch) and is still in place; it should be replaced or cleared
|
||||
when the loopback any-port change is deployed.
|
||||
|
||||
After the 21:26 change, through the public hostname: a preflight from `http://127.0.0.1:40315`
|
||||
was answered 204 with `access-control-allow-origin: http://127.0.0.1:40315`; from
|
||||
`http://127.0.0.1:40316` and from `https://evil.example` there was no allow-origin header.
|
||||
|
||||
Outside the server: at 21:22 UTC the package `hermeven.ehpk` (app "Pepper", `xylo.hermeven`,
|
||||
0.1.0, built from `fd99255`) was uploaded to Dan's Even developer account as a private build with
|
||||
`evenhub create`, on Dan's instruction ("logged in, go ahead and upload"). It was not promoted to
|
||||
beta and not submitted for review.
|
||||
|
||||
**Not deployed:** `bc00ae9` (loopback any-port origins). Dan chose review first: "send to cody".
|
||||
|
||||
## 21:50 UTC: the bridge was updated to the commit under review
|
||||
|
||||
On Dan's go-ahead ("yes, go ahead", after being told the change had been reviewed without
|
||||
findings but not given a SHIP):
|
||||
|
||||
| Step | Result |
|
||||
|---|---|
|
||||
| `git archive d90cd89` to `/root/hermeven-src`, then `deploy/install.sh --bridge-url https://hermeven.xylo.gg` | All seven steps completed. `DEPLOYED_SHA` is `d90cd8972af0ed26a1c4c25a6acdbda775fcf8a7`. |
|
||||
| Application tree | `root:root`, 0 files not root-owned, 0 group/other-writable |
|
||||
| Untouched by the script | `/etc/hermeven/bridge.env` (hermeven, 600), `/var/lib/hermeven` (hermeven, 700), `/opt/hermeven/models` (root); `verify-model`: 7 files verified |
|
||||
| Static page after the script rebuilt it | Same three SHA-256 values as before and as a local build of `d90cd89` |
|
||||
| `HERMEVEN_ALLOWED_ORIGINS` | `http://127.0.0.1:*` (previous file kept as a `.bak-` copy) |
|
||||
| Restart | 21:50:41 to 21:50:45 UTC; `stt.ready`; state directory 700, database 600 |
|
||||
| From outside, preflight to `/v1/pairing/claim` | Allowed and echoed: `http://127.0.0.1:40315`, `:51877`, `:1`. No allow-origin header: `https://127.0.0.1:40315`, `http://localhost:40315`, `http://127.0.0.1.example.com:40315`, `http://192.168.1.20:40315`, `https://evil.example`, `http://127.0.0.1` |
|
||||
| From outside, `/v1/device` with an allowed origin and no credential | 401 |
|
||||
| From outside, ports 8787 and 8642 | no connection |
|
||||
| Paired devices | Preserved across the update |
|
||||
|
||||
So as of 21:50 UTC the server runs the bridge at `d90cd89`. This is the first time the deployed
|
||||
bridge is not the commit that holds Cody's SHIP (`f02715f`).
|
||||
|
||||
## 22:00 UTC: Even developer account
|
||||
|
||||
On Dan's instruction ("yes, promote it to beta"): `evenhub promote 0.1.0 --to beta` for
|
||||
`xylo.hermeven`, and `evenhub testers add` for the account's own email address (taken from the
|
||||
tool's own account check, not displayed or stored in this repository). The roster showed one
|
||||
tester, status "Invited". Dan subsequently installed and ran the beta build.
|
||||
|
||||
Package `hermeven-0.1.1.ehpk` (99,493 bytes, SHA-256
|
||||
`4a2c4ad8e27057df15aad81454fedde2296db3562ba28b29e0c5a4d87b9d23cf`, built from `cf2cf66`) exists
|
||||
on the development desktop only. It has **not** been uploaded.
|
||||
|
||||
## 23:09 UTC: build 0.1.1 uploaded to the Even developer account
|
||||
|
||||
Cody's Round 13 found no unresolved code finding on `3e0468802f3ae23b30c39c48f36d489fa92f9658` and
|
||||
blocked only on owner pre-acceptance. Dan: "Dan says ship. :) Send it." Then `evenhub upload`
|
||||
(version 0.1.1, id 155494) and `evenhub promote 0.1.1 --to beta`. Cody subsequently recorded
|
||||
"Exact SHA 3e0468802f3ae23b30c39c48f36d489fa92f9658 is SHIP FOR TRIAL."; the upload preceded that
|
||||
message by a few minutes, on the owner's instruction. `evenhub ls` at 23:21 UTC: beta channel at
|
||||
0.1.1; 0.1.0 retained, on no channel. The server was not changed.
|
||||
|
||||
Build 0.1.2 has **not** been uploaded.
|
||||
|
||||
## 23:48 UTC: build 0.1.2 uploaded
|
||||
|
||||
Cody, Round 14: SHIP (trial designation SHIP FOR TRIAL) on
|
||||
`15714bd848a7bf7230bb80d187de85af4b3fa66b`. Dan: "yes, upload 0.1.2". `evenhub upload` (id 155527,
|
||||
99,892 bytes, SHA-256 `3781f3e8256f0efdba4155fbd5d0926a6726f14ca3ed89bc039d34b48a0f608b`, built from
|
||||
that commit) and `evenhub promote 0.1.2 --to beta`. Dan has not reported a trial of 0.1.2.
|
||||
|
||||
## 23:52 to 23:58 UTC: Hermes profiles surveyed; keys added for wendy and cody
|
||||
|
||||
Read-only survey (Dan: "Yes, take a read-only survey"):
|
||||
|
||||
| Found | Detail |
|
||||
|---|---|
|
||||
| Profiles | default, cody, jeanette, natalie, wendy, all with a running gateway |
|
||||
| Gateways | `hermes-gateway.service` serves default, cody, natalie and wendy (`gateway.multiplex_profiles: true`); `hermes-gateway-jeanette.service` is separate and not on port 8642 |
|
||||
| API | Hermes v0.23.1 source: named profiles are served at `/p/<profile>/...` on the same port, each authorised by that profile's own `API_SERVER_KEY`, failing closed without one |
|
||||
| Unauthenticated probes | `/p/wendy/health`, `/p/cody/health`, `/p/natalie/health`: 200. `/p/jeanette/health`, `/p/nosuch/health`: 404 |
|
||||
| Keys before | Only the default profile had `API_SERVER_KEY` |
|
||||
|
||||
Changes (Dan: "Pepper, wendy and cody. yes. go for it."):
|
||||
|
||||
| Step | Result |
|
||||
|---|---|
|
||||
| `API_SERVER_KEY` (64 hex, generated on the server, never displayed) appended to `profiles/wendy/.env`; previous file kept as `.env.bak-hermeven-<time>` | File stays `hermes` 600. No gateway restart. |
|
||||
| Same for `profiles/cody/.env` | Same. |
|
||||
| Wendy's key at `/p/wendy/v1/runs/<unknown>` | 404: accepted, no such run. Effective without a restart. |
|
||||
| Wendy's key at the default address; the default key at `/p/wendy`; Cody's key at `/p/wendy` | 401 each |
|
||||
| One test question to Wendy through `POST /p/wendy/v1/runs` with an idempotency key ("connection test... Do not use any tools.") | 202; an identical resubmit returned the same run; completed in 4 s with a one-sentence answer identifying herself as Wendy. This created one session in Wendy's profile. |
|
||||
| That run looked up at the default address with the default key | 404 |
|
||||
| Cody's key at `/p/cody/v1/runs/<unknown>` | 404: accepted. No question was sent to Cody. |
|
||||
|
||||
`platforms.api_server.enabled` is `false` in wendy's and natalie's profile settings; the request
|
||||
above worked regardless. The bridge on the server was **not** changed: it still runs `d90cd89`
|
||||
with one agent, and the new keys are not yet in its settings.
|
||||
|
||||
## 2026-11-22 00:37 UTC: bridge updated to the multi-agent build; 00:38 UTC: 0.2.0 uploaded
|
||||
|
||||
Cody, Round 16: SHIP (trial designation SHIP FOR TRIAL) on
|
||||
`dcb373639ef97d4c7f63abaddafadef7f6edf226`. Asked to confirm the bridge update and the upload, Dan:
|
||||
"confirmed on both".
|
||||
|
||||
| Step | Result |
|
||||
|---|---|
|
||||
| `git archive dcb3736`, then `deploy/install.sh --bridge-url https://hermeven.xylo.gg` | `DEPLOYED_SHA` is `dcb373639ef97d4c7f63abaddafadef7f6edf226` (was `d90cd89`). Application tree `root:root`, 0 files not root-owned, 0 writable by others. |
|
||||
| `/etc/hermeven/bridge.env` (previous file kept as a `.bak-` copy) | Added `HERMEVEN_AGENT_NAME=Pepper`, `HERMEVEN_AGENTS=wendy,cody`, the two agents' keys copied on the server from their Hermes profile settings without being displayed (64 characters each), and `HERMEVEN_AGENT_CODY_NAME=Cody`. File stays `hermeven` 600. |
|
||||
| Restart | 00:37:47 to 00:37:52 UTC; `stt.ready`; healthz ok; state directory 700, database 600 (migration v3 applied on start). Hermes was not restarted. |
|
||||
| Configuration as loaded by the service user | default "Pepper" at the gateway address; "Wendy" at `/p/wendy`; "Cody" at `/p/cody` |
|
||||
| The bridge's copies of the keys at each agent's address | 404 (accepted, no such run) for both |
|
||||
| Paired devices | Preserved |
|
||||
| Smoke test with a temporary device (`deploy-smoke-agents`, revoked afterwards) | `/v1/agents`: Pepper, Wendy, Cody. `/v1/device`: its previous ten fields. Conversation with unlisted `natalie`: 400. One typed question to Wendy through the bridge: succeeded in 2.1 s, answered as Wendy; the bridge log names agent `wendy` for it. This left one more test session in Wendy's profile. No question was sent to Cody. |
|
||||
| From outside | healthz ok; `/v1/agents` without a credential: 401 |
|
||||
| Even account | `evenhub upload` 0.2.0 (id 155579, 100,912 bytes, SHA-256 `73179edaa84e261259a12226657f4e12f9f29138bf77236dc4388a6f6c73da5d`, built from `dcb3736`), then `evenhub promote 0.2.0 --to beta` |
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.9 KiB |
@@ -0,0 +1,44 @@
|
||||
# Handoff for Cody, Round 10
|
||||
|
||||
From: Claude (implementation). Date: 2026-11-21.
|
||||
|
||||
**Not reviewed.** Round 9's result applies to `d90cd89`.
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Branch | `cody/droplet-deploy` |
|
||||
| Reviewed in Round 9 | `d90cd8972af0ed26a1c4c25a6acdbda775fcf8a7` |
|
||||
| This push | **Documentation only** on top of it: evidence, README status, this file. `git diff d90cd89 HEAD -- apps services packages tests deploy` is empty. No code was changed to make a new SHA. |
|
||||
|
||||
## Round 9's two blocks
|
||||
|
||||
1. **Contract.** Cody's own message to Dan after Round 9: "Your Telegram confirmation
|
||||
independently validates the acceptance contract... Resolved: acceptance-contract blocker."
|
||||
2. **CODY-014, exact-build physical proof.** Recorded in
|
||||
`docs/evidence/device/2026-11-21.md`, "Third session":
|
||||
|
||||
| Required | Evidence |
|
||||
|---|---|
|
||||
| Build/package the exact SHA | The client on the phone is the private build packed at `fd99255`; no client or contract file differs between `fd99255` and `d90cd89`, and a build of `d90cd89` yields the identical script (hash in the evidence). The package's SHA-256 is recorded. The bridge on the server is `d90cd89` itself. |
|
||||
| Run it in the Even app on the G2 | Opened from the Even app's installed apps, no QR. |
|
||||
| Diagnostics: Even host/SDK, HUD created | Dan: "0.0.16 and created". |
|
||||
| Long press, speak while held, release: one question sent and answered | Dan: "Works." Bridge log: every recording in the session produced exactly one accepted and one completed turn. |
|
||||
| Quickly released long press behaves like a tap | Dan: "Yes, works." |
|
||||
| Dated, tied to commit and artifact | Yes. |
|
||||
|
||||
## What this evidence cannot show
|
||||
|
||||
Stated in the evidence file and repeated here: the server sees one audio upload per recording and
|
||||
cannot tell a hold from a tap. That the gestures were what was asked is the owner's report. Dan
|
||||
has also asked for fewer requests to read Diagnostics lines back ("They are annoying to
|
||||
transpose"), so the "found after N ms" figure was not collected this time.
|
||||
|
||||
## Production
|
||||
|
||||
With Dan's go-ahead the server now runs `d90cd89` and `HERMEVEN_ALLOWED_ORIGINS=http://127.0.0.1:*`.
|
||||
Details and the outside checks are in `docs/evidence/droplet/2026-11-21.md`. This was done before a
|
||||
SHIP, on the owner's decision, after Round 9 raised no finding against the code.
|
||||
|
||||
## Not claimed
|
||||
|
||||
No locked-phone, ring, paging, menu or cancel evidence. Nothing merged to `main`.
|
||||
@@ -0,0 +1,73 @@
|
||||
# Handoff for Cody, Round 11
|
||||
|
||||
From: Claude (implementation). Date: 2026-11-21.
|
||||
|
||||
**Not reviewed.** Round 10 (`38883b3`, documentation only, exact-build device evidence for
|
||||
CODY-014) had not returned a verdict when this was pushed. This round adds code on top of it.
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Branch | `cody/droplet-deploy` |
|
||||
| `main` | `f02715fb6487f4e2ff0adeccfaad2403e1724aa5` (SHIP; unchanged) |
|
||||
| Last reviewed | `d90cd8972af0ed26a1c4c25a6acdbda775fcf8a7` (Round 9) |
|
||||
| Round 10 push | `38883b38f80d95ec4cdbd5cd7e2941a9fac0dcde` (docs only) |
|
||||
| New head | the tip of `cody/droplet-deploy` after this push; exact SHA in the push report |
|
||||
|
||||
## What is new since Round 10
|
||||
|
||||
| Commit | Kind | Content |
|
||||
|---|---|---|
|
||||
| `cf2cf66` | **client code**, tests, manifest | Leave the glasses when idle; new conversation after a long silence; "Opened from" in Diagnostics; version 0.1.1 |
|
||||
| `8171aee` | docs | Contract section F; fourth device session; README |
|
||||
| next | docs | This handoff and the Round 11 evidence section |
|
||||
|
||||
No bridge, contract-package or deployment file changed: `git diff 38883b3 HEAD -- services packages deploy` is empty.
|
||||
|
||||
## Contract
|
||||
|
||||
`docs/contracts/2026-11-21-droplet-deployment-and-first-device-run.md`, section F. Cody recorded
|
||||
after Round 9 that Dan's direct confirmation validates the contract; section F was added later,
|
||||
again from Dan's quoted words. Whether that earlier confirmation extends to an added section is
|
||||
for Cody and Dan. F4 and F5 are marked as the implementer's additions, not Dan's requests.
|
||||
|
||||
## Why this exists
|
||||
|
||||
On the device, while the app was open it stayed on the display indefinitely, and a phone
|
||||
notification did not reach the lenses. Dan: "I want the app to work like any other even app. call
|
||||
it to be used, and then it disappears but stays callable." With the beta build he confirmed it is
|
||||
callable: it appears in the glasses' menu and "Hey Even, open Pepper" launches it, phone locked.
|
||||
|
||||
## What deserves scrutiny
|
||||
|
||||
1. **An unprompted exit.** `shutDownPageContainer(0)` is called by the app on a timer. Earlier
|
||||
rounds established that exit mode 0 is not acceptable for a double tap on the root page under
|
||||
Even's submission rules; this is a different trigger, but the same call. It has never been run
|
||||
against the simulator or the device, so what the Even app does on it is assumed from the docs.
|
||||
2. **Is "resting screen" drawn in the right place?** It leaves from answer, Ready, error and
|
||||
cancelled. It does not leave from the disconnected states or from approval-required. A turn
|
||||
whose answer arrives while nobody is looking is shown, then leaves 20 s later.
|
||||
3. **Arming.** It is armed by any glasses gesture or a `glassesMenu` launch source. Whether a
|
||||
voice launch reports `glassesMenu` on a real device is not known.
|
||||
4. **F5 changes conversation continuity silently**: after ten minutes the next question starts a
|
||||
new Hermes session without the user being told. The reset happens at start-up, in memory; the
|
||||
stored conversation id is replaced when the next conversation is created.
|
||||
5. **`lastTurnAt` is written to app storage without waiting for confirmation**, unlike the
|
||||
request id. Losing it only delays the reset.
|
||||
6. The idle timer reads `Date.now`-based `now()` and `setTimeout`; a suspended WebView will fire
|
||||
late, which is the safe direction.
|
||||
|
||||
## Device and production state
|
||||
|
||||
- Device evidence, including the first locked-phone success, is in
|
||||
`docs/evidence/device/2026-11-21.md`. Build 0.1.1 has **not** been installed on any device.
|
||||
- Server: bridge and page at `d90cd89`, unchanged by this round.
|
||||
- Even account: 0.1.0 on the beta channel. 0.1.1 is **not** uploaded; Dan said "send it to cody".
|
||||
|
||||
## Checks
|
||||
|
||||
All pass on `8171aee`, nothing omitted: `docs/test-evidence.md`, "Round 11".
|
||||
|
||||
## Not claimed
|
||||
|
||||
Idle exit has not run on a device or in the simulator. Nothing merged to `main`. The
|
||||
specification's ten-cycle locked-phone acceptance run has not been done.
|
||||
@@ -0,0 +1,55 @@
|
||||
# Handoff for Cody, Round 12
|
||||
|
||||
From: Claude (implementation). Date: 2026-11-21.
|
||||
|
||||
**Not reviewed.** Round 11 (`1ae105e`): REVIEW BLOCKED, CODY-016, 017, 018 and the section F gate.
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Branch | `cody/droplet-deploy` |
|
||||
| `main` | `f02715fb6487f4e2ff0adeccfaad2403e1724aa5` (unchanged) |
|
||||
| Reviewed in Round 11 | `1ae105ed18e2082ada59e4351136f5bc5e9cdca4` |
|
||||
| Code fix | `bbde3c8` |
|
||||
| New head | the tip after this push (this file and evidence only on top of `bbde3c8`) |
|
||||
|
||||
## Section F gate
|
||||
|
||||
Not resolved by this push, and not something the implementer can resolve. The contract now
|
||||
states that section F is a proposal until Dan accepts or rejects F1 to F5. Dan has been asked
|
||||
directly. No owner quote was added or changed. If Dan rejects F4 or F5, that behaviour will be
|
||||
removed or revised in a further commit.
|
||||
|
||||
## Findings
|
||||
|
||||
| Finding | Change | Files |
|
||||
|---|---|---|
|
||||
| CODY-016 | The adapter subscribes to the launch source in its constructor (boot creates it as soon as the Even bridge is in hand), remembers it, and replays it to later listeners. Unsubscribe removes the controller's listener. `appMenu` does not arm. | `device/evenAdapter.ts`, `device/port.ts` |
|
||||
| CODY-017 | README paragraph rewritten: one owner-reported beta run; pocketed, five-minute and ten-cycle runs unverified. | `README.md` |
|
||||
| CODY-018 | `exitNow()` returns confirmation. One shutdown call at most, through the host-call queue; a repeat waits on the same call; a confirmed exit (even a late one) ends it. The controller is "gone" only on confirmation or a `system_exit`/`abnormal_exit` event; otherwise it retries after 3 s, up to 4 attempts in a row, under the same resting-screen and phone-grace guards; activity starts the count again. | `device/evenAdapter.ts`, `core/controller.ts`, `device/previewDevice.ts` |
|
||||
|
||||
Also changed: a development-only `?idleExit=fast` (compiled out of production; checked in the
|
||||
bundle) so the simulator suite can perform the exit, as Round 11 asked.
|
||||
|
||||
## Where to push
|
||||
|
||||
1. After 4 unconfirmed attempts the app stays open until the next activity. If the host never
|
||||
confirms and nobody touches the glasses, Pepper stays on the display. That is the bounded
|
||||
behaviour asked for, and it is also the original complaint in its worst case.
|
||||
2. Confirmation is `=== true` from `shutDownPageContainer`. The simulator returns true. What the
|
||||
real Even app returns is unknown; if it returns something else on success, the page is torn
|
||||
down anyway, and if it returns something else while leaving the app open, the retries apply.
|
||||
3. A retry that finds the earlier call still with the host counts as an attempt.
|
||||
4. The fake-clock tests fake timers and `Date` only; start-up bridge calls are real.
|
||||
5. The simulator scenario relaunches the simulator inside the suite; its console capture is
|
||||
sliced from the relaunch.
|
||||
|
||||
## State
|
||||
|
||||
- 0.1.1 is **not** uploaded to Even, not installed on any device, not deployed. The pack check
|
||||
wrote a local, git-ignored `hermeven.ehpk` only.
|
||||
- Server: unchanged, bridge and page at `d90cd89`.
|
||||
- Idle exit has never run on the glasses.
|
||||
|
||||
## Checks
|
||||
|
||||
All pass on `bbde3c8`, nothing omitted: `docs/test-evidence.md`, "Round 12".
|
||||
@@ -0,0 +1,36 @@
|
||||
# Handoff for Cody, Round 13
|
||||
|
||||
From: Claude (implementation). Date: 2026-11-21.
|
||||
|
||||
**Not reviewed.** Round 12 (`3d0edeb`): REVIEW BLOCKED on CODY-019 and the section F gate.
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Branch | `cody/droplet-deploy` |
|
||||
| `main` | `f02715fb6487f4e2ff0adeccfaad2403e1724aa5` (unchanged) |
|
||||
| Reviewed in Round 12 | `3d0edebd131df974563ac13bc9f35c48bf221dcf` |
|
||||
| Code fix | `d8582e9` (`core/controller.ts` and one test file only) |
|
||||
| New head | the tip after this push (this file and evidence only on top of `d8582e9`) |
|
||||
|
||||
## Section F gate
|
||||
|
||||
Still open. Dan was asked directly for a yes or no on each of F1 to F5 and had not answered
|
||||
when this was pushed. The contract text is unchanged and still calls section F a proposal.
|
||||
|
||||
## CODY-019
|
||||
|
||||
`Controller` keeps an `activityEpoch`, incremented every time the normal countdown is
|
||||
(re)started, which is every gesture, every dispatched state change and every phone-page touch.
|
||||
`leaveGlasses()` captures it before calling the host and, on an unconfirmed result, schedules no
|
||||
retry if it has moved. The reducer-generation comparison is gone; a dispatch always moves the
|
||||
epoch, so nothing it covered is lost.
|
||||
|
||||
Consequence to check: an attempt overtaken by activity is not counted as a failure, so after
|
||||
activity the host can be asked up to four more times (tested: five calls in total, then none).
|
||||
|
||||
Tests, the control and its one limitation are in `docs/test-evidence.md`, "Round 13".
|
||||
|
||||
## State
|
||||
|
||||
0.1.1 is not uploaded, not installed, not deployed. Server unchanged at `d90cd89`. Idle exit has
|
||||
never run on the glasses.
|
||||
@@ -0,0 +1,60 @@
|
||||
# Handoff for Cody, Round 14
|
||||
|
||||
From: Claude (implementation). Date: 2026-11-21.
|
||||
|
||||
**Not reviewed.** Round 13: `3e0468802f3ae23b30c39c48f36d489fa92f9658`, SHIP FOR TRIAL.
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Branch | `cody/droplet-deploy` |
|
||||
| `main` | `f02715fb6487f4e2ff0adeccfaad2403e1724aa5` (unchanged) |
|
||||
| Trialled on the device | 0.1.1, built from `3e04688` |
|
||||
| Code change | `344a228` |
|
||||
| New head | the tip after this push (this file and evidence only on top of `344a228`) |
|
||||
|
||||
## Why there is a new SHA
|
||||
|
||||
The trial produced one "change". On the real G2, 0.1.1 did not leave after a voice launch with
|
||||
nothing touched, and did leave after one swipe. So the exit works on hardware, and the arming
|
||||
rule (a `glassesMenu` launch source or a first gesture) is what failed: no such launch source
|
||||
reached the app. Dan's words and decisions are in the contract, section F, "Decisions after the
|
||||
0.1.1 trial", and in `docs/evidence/device/2026-11-21.md`, fifth session.
|
||||
|
||||
## The change
|
||||
|
||||
`core/controller.ts`: the `idleArmed` flag is removed. The countdown runs on any resting screen
|
||||
once the HUD exists, however the session was opened. The launch source is kept and shown in
|
||||
Diagnostics, and decides nothing. `device/port.ts`: comment only. Manifest version 0.1.2.
|
||||
No bridge, contract-package or deployment file changed.
|
||||
|
||||
This reverses part of CODY-016's required behaviour ("do not classify appMenu as glasses
|
||||
activity"), on the owner's decision after the trial. The adapter's early subscription and replay
|
||||
from CODY-016 are kept.
|
||||
|
||||
## Owner decisions
|
||||
|
||||
| Item | State |
|
||||
|---|---|
|
||||
| F1, F2 real exit, notifications return | Keep (observed on device) |
|
||||
| F3 times | Keep for now |
|
||||
| F4 safeguards | Changed as above; the rest kept |
|
||||
| F5 ten-minute conversation rule | Pending: not yet tried |
|
||||
|
||||
## Where to look
|
||||
|
||||
1. An untouched session opened from the phone app now closes after 30 s, which also closes the
|
||||
phone page. Protection left: unpaired never leaves; a touch gives 120 s.
|
||||
2. Whether the real host sends nothing or `appMenu` on a voice launch is still unknown. The new
|
||||
rule does not depend on it.
|
||||
3. Every other controller in the test suites now has idle exit live by default at 30 s; none
|
||||
runs that long, and `client-bridge.test.ts` keeps it off unless a test turns it on.
|
||||
|
||||
## State
|
||||
|
||||
- Even account: beta channel at 0.1.1 (uploaded 23:09 UTC on Dan's instruction; recorded in
|
||||
`docs/evidence/droplet/2026-11-21.md`). 0.1.2 is **not** uploaded.
|
||||
- Server: unchanged at `d90cd89`.
|
||||
|
||||
## Checks
|
||||
|
||||
All pass on `344a228`, nothing omitted: `docs/test-evidence.md`, "Round 14".
|
||||
@@ -0,0 +1,71 @@
|
||||
# Handoff for Cody, Round 7
|
||||
|
||||
From: Claude (implementation). Date: 2026-11-21.
|
||||
|
||||
**Not reviewed.** Cody's Round 6 result (REVIEW BLOCKED) applies to `98c7b03` only.
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Repository | `git@git.xylo.gg:Xylo-Digital/hermeven.git` |
|
||||
| Branch | `cody/droplet-deploy` |
|
||||
| `main` | `f02715fb6487f4e2ff0adeccfaad2403e1724aa5` (Cody: SHIP; unchanged) |
|
||||
| Reviewed in Round 6 | `98c7b03aa78b3570592c17a1412a071e3499fce9` |
|
||||
| New head | the tip of `cody/droplet-deploy` after this push; exact SHA in the push report |
|
||||
|
||||
## The acceptance contract
|
||||
|
||||
**Not supplied.** Round 6 asks for a trusted, independent issue or task contract. The implementer
|
||||
cannot write an independent contract for its own work, so none is included. Dan has been asked to
|
||||
provide one (a Gitea issue or equivalent). Until he does, this round can only be judged against
|
||||
Round 6's own required corrections, listed below.
|
||||
|
||||
For context, not as a contract: the work on this branch came from three requests by Dan in
|
||||
conversation on 2026-11-21. (1) Inspect the Hermes droplet and deploy the bridge there. (2) Retire
|
||||
the unfinished browser-extension service and use port 8642 for the Hermes API. (3) Serve the
|
||||
bridge at `hermeven.xylo.gg`.
|
||||
|
||||
## Scope of this branch beyond `main`
|
||||
|
||||
| Commit | Kind | Content |
|
||||
|---|---|---|
|
||||
| `98c7b03` | docs, deploy examples | Deployment record; unit and Caddyfile aligned with what ran |
|
||||
| `e5559dc` | **client code** | Host detection waits for the Even app connection; Diagnostics shows the browser |
|
||||
| next | docs, deploy script, tests, small client change | Round 6 corrections; wait shortened to 2.5 s; a wrong diagnosis corrected |
|
||||
|
||||
So this is no longer documentation only: `apps/even-client/src/device/hostDetect.ts`,
|
||||
`src/main.ts` and `src/ui/phone.ts` changed. No bridge code changed.
|
||||
|
||||
## Round 6 corrections
|
||||
|
||||
| Finding | What was done | Proof |
|
||||
|---|---|---|
|
||||
| CODY-011 | `deploy/install.sh`: copy the release to `app.new`, `chown` only that directory to `hermeven`, `npm ci` as `hermeven`, then `chown -R root:root` and `chmod -R go-w` on it before it becomes `/opt/hermeven/app`. It does not touch `/etc/hermeven`, `/var/lib/hermeven` contents or `/opt/hermeven/models`. The guide gives exact commands and names the toolchain a clean host needs. | `tests/deploy/runbook-proof.sh`: from an empty `/opt/hermeven` on a disposable Ubuntu 24.04 host with systemd. Unprivileged `npm ci` succeeds; 0 files in the app tree not owned by root; 0 group/other-writable; `hermeven` cannot write the tree or create a file in the source; the unit is `active`, running as `hermeven`. |
|
||||
| CODY-012 | `install.sh` builds the client with the bridge address preset and installs it into `/opt/hermeven/www` as root (directories 0755, files 0644). The guide has a section on the web build versus the `.ehpk` and when each is needed. | Same run, Caddy 2.6.2: `GET /` 200, hashed asset 200, the three security headers on both, `/healthz` proxied, no CORS header for a foreign origin. On the live server: the same requests, and the page loaded in Chrome with Diagnostics reporting `Page origin: https://hermeven.xylo.gg`. |
|
||||
| CODY-013 | README states that `f02715f` was deployed with only the bounded server-side checks, and lists phone/glasses, locked-phone capture, tools/approvals, sustained load, backups, monitoring and upgrades as unverified. | Read the diff. |
|
||||
|
||||
One thing the README says that Round 6 did not anticipate: the static page on the server has since
|
||||
been rebuilt from this branch's unreviewed client commits. `98c7b03` itself was never deployed;
|
||||
the bridge on the server is still `f02715f`.
|
||||
|
||||
## Checks
|
||||
|
||||
`npm ci`, `npm run typecheck`, `npm test` (205), `npm run client:build`, `npm run test:real-stt`
|
||||
(11), `npm run test:real-hermes` (9), `npm run test:simulator` (6), `git diff --check`: all pass.
|
||||
`caddy validate` and `caddy fmt --diff` with 2.6.2, and `systemd-analyze verify`: pass on the
|
||||
disposable host. Nothing omitted. Details: `docs/test-evidence.md`, "Round 7".
|
||||
|
||||
## Things the author got wrong, and is unsure about
|
||||
|
||||
- **A wrong diagnosis reached a commit message.** `e5559dc` says the Even app's WebView provided
|
||||
its connection late on a real phone. That was not observed: the page was open in Chrome. The
|
||||
code comments are corrected in the next commit; the commit message of `e5559dc` is left as it is
|
||||
(already pushed) and is wrong.
|
||||
- Whether the precautionary wait is worth having at all. It delays the browser preview by 2.5 s
|
||||
and addresses nothing that has been seen.
|
||||
- The clean-host proof uses a container, `localhost` and Caddy's local CA, not a second server.
|
||||
- `install.sh` builds the client on the server as the service user, so build tooling runs there.
|
||||
- Nothing has run inside the Even app.
|
||||
|
||||
## Not claimed
|
||||
|
||||
No evidence from the Even app, the glasses, or a locked phone. Nothing merged to `main`.
|
||||
@@ -0,0 +1,103 @@
|
||||
# Handoff for Cody, Round 9
|
||||
|
||||
From: Claude (implementation). Date: 2026-11-21.
|
||||
|
||||
**Not reviewed.** Round 8's result (REVIEW BLOCKED) applies to `09e21f6` only.
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Repository | `git@git.xylo.gg:Xylo-Digital/hermeven.git` |
|
||||
| Branch | `cody/droplet-deploy` |
|
||||
| `main` | `f02715fb6487f4e2ff0adeccfaad2403e1724aa5` (SHIP; unchanged) |
|
||||
| Reviewed in Round 8 | `09e21f6368deed7917a9f5dcd2eadce5547eca04` |
|
||||
| New head | the tip of `cody/droplet-deploy` after this push; exact SHA in the push report |
|
||||
|
||||
## The contract
|
||||
|
||||
`docs/contracts/2026-11-21-droplet-deployment-and-first-device-run.md`.
|
||||
|
||||
It was written by the implementer. Dan was asked to supply an independent one and answered: "you
|
||||
supply the contract. why am I needed for this trivial nonsense?" The contract says so at the top,
|
||||
and ties each criterion to Dan's quoted words or to a correction Cody required. It is the owner's
|
||||
decision that this is the contract; it is not independent of the implementer.
|
||||
|
||||
## This branch is no longer small
|
||||
|
||||
Round 8 covered a start-up change. Since then Dan ran the app on his glasses for the first time
|
||||
and the branch grew. Commits since `09e21f6`:
|
||||
|
||||
| Commit | Kind | What |
|
||||
|---|---|---|
|
||||
| `7f055d4` | client, tests, docs | CODY-014; contract; first device evidence |
|
||||
| `b8191a7` | client | "Glasses input" line in Diagnostics (event types only) |
|
||||
| `9cb34b3` | client, tests | Long press handled; hold-to-talk |
|
||||
| `fd99255` | manifest | App name "Pepper", package id `xylo.hermeven` |
|
||||
| `bc00ae9` | **bridge**, tests | `HERMEVEN_ALLOWED_ORIGINS` accepts `http://127.0.0.1:*` |
|
||||
| `fb0a6b9` | docs | README, decision record, contract, evidence |
|
||||
| next | docs | This handoff and the Round 9 evidence section |
|
||||
|
||||
Bridge files changed since `main`: `services/bridge/src/config.ts`, `services/bridge/src/server.ts`
|
||||
(and their tests). Nothing else under `services/` or `packages/`.
|
||||
|
||||
## CODY-014
|
||||
|
||||
| Required | Done |
|
||||
|---|---|
|
||||
| 1. Immediate accessible loading surface | `#startup` in the static HTML, `role="status"`, `aria-live="polite"`, inline-styled, ahead of the script. |
|
||||
| 2. Keep delayed-host detection; select EvenDevice when a callable host appears | Unchanged logic, now in `src/boot.ts`. |
|
||||
| 3. After timeout, replace with the labelled preview | Yes. |
|
||||
| 4. No eager fallback | Nothing is mounted and no device chosen until detection answers. |
|
||||
| 5. Remove the start-up surface when the real page mounts | `startup.remove()` after `mountPhoneUi`. |
|
||||
| Proof 1 to 3 | `tests/integration/entryPoint.test.ts`, with the real `index.html`, `boot()` and Even SDK in happy-dom. |
|
||||
| Proof 4: physical Even-app probe | For the build of `7f055d4`: Dan read from the phone, inside the Even app, "Even app host (SDK 0.0.16), found after 4 ms", "HUD created", and the glasses showing the Ready screen. **Later client builds were not probed for those two lines**; see below. |
|
||||
|
||||
## What needs the most scrutiny
|
||||
|
||||
1. **`bc00ae9` loosens an origin restriction.** Earlier rounds said not to. It is the only way an
|
||||
Even Hub installed app can call the bridge: the Even phone app serves it from
|
||||
`http://127.0.0.1:<port>` with a new port each launch (Dan observed the change). It is off by
|
||||
default, loopback only, http only, numeric port only, and matched as whole-string text. It is
|
||||
**not deployed**: Dan was offered "deploy now, review after" and chose "send to cody".
|
||||
2. **Hold-to-talk keeps the microphone open for as long as a finger is down**, up to the capture
|
||||
cap, and a hold released in under 0.7 s leaves it open until the next tap. Is that the right
|
||||
reading of "explicit user-triggered capture"?
|
||||
3. **The Glasses input line** shows envelope names and numeric codes. Check that nothing derived
|
||||
from audio or content can reach it.
|
||||
4. **The precautionary host-detection wait** is still there (2.5 s) though the device showed the
|
||||
host arriving in 4 ms. It costs an ordinary browser 2.5 s and protects against nothing observed.
|
||||
|
||||
## What was and was not seen on the device
|
||||
|
||||
All in `docs/evidence/device/2026-11-21.md`. In short: four spoken questions were answered on the
|
||||
glasses (QR sideload, phone unlocked, build `09e21f6`); the `7f055d4` build was probed as above;
|
||||
long-press events were observed on `b8191a7`; the installed private build opens but cannot reach
|
||||
the bridge without `bc00ae9`. **Hold-to-talk has not been used on the device. The final client
|
||||
build's Runtime and HUD lines were not read back.**
|
||||
|
||||
## Production state right now
|
||||
|
||||
Changed today with Dan's approval each time (table in `docs/evidence/droplet/2026-11-21.md`):
|
||||
|
||||
- Bridge code: still `f02715f`.
|
||||
- Static page: a build of `fd99255` (unreviewed client code).
|
||||
- `HERMEVEN_ALLOWED_ORIGINS=http://127.0.0.1:40315`: a single exact origin that no longer matches
|
||||
anything, left in place.
|
||||
- Even's portal: private build "Pepper" `xylo.hermeven` 0.1.0, built from `fd99255`.
|
||||
|
||||
## Checks
|
||||
|
||||
All of Round 8's required checks pass on `fb0a6b9`, with nothing omitted: `docs/test-evidence.md`,
|
||||
"Round 9".
|
||||
|
||||
## Mistakes made this session, so they are not found later
|
||||
|
||||
- The implementer told Dan a tap failure might be a regression before knowing; it was a long
|
||||
press that the code ignored.
|
||||
- The first allowed-origin fix (`:40315`) was applied to production knowing the port might change.
|
||||
It did.
|
||||
- Earlier the same day: the Chrome-versus-Even-app misdiagnosis recorded in the Round 7 handoff.
|
||||
|
||||
## Not claimed
|
||||
|
||||
Nothing in this branch is merged. `bc00ae9` is not deployed. No locked-phone, ring, menu, paging
|
||||
or hold-to-talk evidence from the device.
|
||||
@@ -0,0 +1,73 @@
|
||||
# Handoff for Cody, Round 15
|
||||
|
||||
From: Claude (implementation). Date: 2026-11-22 (UTC).
|
||||
|
||||
**Not reviewed.** Round 14: `15714bd848a7bf7230bb80d187de85af4b3fa66b`, SHIP / SHIP FOR TRIAL.
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Branch | `cody/droplet-deploy` |
|
||||
| `main` | `f02715fb6487f4e2ff0adeccfaad2403e1724aa5` (unchanged) |
|
||||
| Code change | `9394c24` |
|
||||
| New head | the tip after this push (this file and evidence only on top of `9394c24`) |
|
||||
|
||||
## What this is
|
||||
|
||||
A new feature for trial: more than one agent through one bridge, chosen on the glasses with a
|
||||
swipe at Ready. Dan's requests, quoted, are contract section G; G7 lists what the implementer
|
||||
chose. Under the standing rule these are owner decisions pending the device trial.
|
||||
|
||||
Unlike the last few rounds this touches the **bridge**, the **contract package** and the
|
||||
**database schema** (migration v3, one nullable column), as well as the client.
|
||||
|
||||
## Design in five lines
|
||||
|
||||
1. `config.agents`: default first, then `HERMEVEN_AGENTS`. Extra agents are profiles of the same
|
||||
Hermes gateway at `<base>/p/<profile>`, each with its own key (Hermes refuses the default's).
|
||||
2. `GET /v1/agents` returns ids and names. `POST /v1/conversations` takes optional `agent_id`,
|
||||
checked against the list. `/v1/device` is untouched on purpose: installed 0.1.x clients reject
|
||||
unknown response fields.
|
||||
3. `conversations.agent_id` (NULL = default). A turn's adapter is looked up from its conversation
|
||||
every time it is driven, including after a restart.
|
||||
4. Client: `agents` and `agentId` in the reducer; the controller swaps the stored conversation
|
||||
per agent; requests name an agent only when the bridge offered a list.
|
||||
5. Old client with new bridge, and new client with old bridge, both behave as one agent.
|
||||
|
||||
## Where to push
|
||||
|
||||
1. **The id never builds an address.** The profile path comes only from configuration; the
|
||||
client-supplied id is a map key, pattern-checked by the schema and then by `knowsAgent`.
|
||||
`HERMEVEN_AGENT_<ID>_PROFILE` is pattern-checked too.
|
||||
2. **One device token now reaches every listed agent**, each with its own tools. That is the
|
||||
intent, and the list is the control. There is no per-device restriction.
|
||||
3. **Idempotency keys** are still `hermeven-turn-<request id>`; Hermes scopes them per profile and
|
||||
key. A request id cannot move between agents because a turn's conversation is fixed.
|
||||
4. **Agent removed mid-turn**: `outcome_unknown` if anything may have been sent, otherwise
|
||||
`agent_unreachable`. Re-adding the agent later does not revive the turn.
|
||||
5. **`activeConversation` and `agent_reachable`** on `/v1/device` now describe the default agent
|
||||
only. A non-default agent being down is discovered by asking it.
|
||||
6. **Client storage** gained `agentId`, `others` and `agents`, written without waiting for
|
||||
confirmation (like `lastTurnAt`). Losing them costs the reopen-on-last-agent convenience.
|
||||
7. **A conversation created for the previous agent** while the user swipes away is dropped on the
|
||||
client by epoch; the bridge keeps an unused conversation row for that agent.
|
||||
8. HUD status at Ready with several agents: "Tap: ask · Swipe: agent · 2×: exit". Not measured on
|
||||
the device or in the simulator.
|
||||
|
||||
## Production and account state
|
||||
|
||||
- Server, on Dan's go-ahead: `API_SERVER_KEY` added to the wendy and cody Hermes profiles; one
|
||||
test question sent to Wendy. Details and what was verified: `docs/evidence/droplet/2026-11-21.md`.
|
||||
- The bridge on the server is unchanged (`d90cd89`, one agent). The new keys are not in its
|
||||
settings. Nothing of 0.2.0 is deployed.
|
||||
- Even account: beta channel at 0.1.2 (uploaded on Dan's instruction after Round 14's SHIP).
|
||||
0.2.0 is not uploaded.
|
||||
- Dan has not reported a trial of 0.1.2, and F5 (ten-minute rule) is still undecided.
|
||||
|
||||
## Also in this push
|
||||
|
||||
CODY-020: the Round 14 control is now described as a stricter mutation, with the mutation text
|
||||
and Cody's exact-prior result (7 failed, 62 passed) attributed to Cody.
|
||||
|
||||
## Checks
|
||||
|
||||
All pass on `9394c24`, nothing omitted: `docs/test-evidence.md`, "Round 15".
|
||||
@@ -0,0 +1,49 @@
|
||||
# Handoff for Cody, Round 16
|
||||
|
||||
From: Claude (implementation). Date: 2026-11-22 (UTC).
|
||||
|
||||
**Not reviewed.** Round 15: `c8b4fb03102dc9a2aec0ffe64622443351c15b97`, NEEDS CHANGES (CODY-021;
|
||||
CODY-022 non-blocking).
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Branch | `cody/droplet-deploy` |
|
||||
| `main` | `f02715fb6487f4e2ff0adeccfaad2403e1724aa5` (unchanged) |
|
||||
| Code change | `bb3a309`: `core/controller.ts`, `core/reducer.ts`, two test files, README |
|
||||
| New head | the tip after this push (this file and evidence only on top of `bb3a309`) |
|
||||
|
||||
## CODY-021
|
||||
|
||||
Confirmed as described. The fix is one reconciliation point: `Controller.dispatch()` calls
|
||||
`reconcileRemovedAgent()` immediately after the reducer step, before effects run, before the HUD
|
||||
is drawn and before the snapshot is emitted. It acts only when all of these hold: there is a
|
||||
stored pairing, the stored agent is not the default, the phase is a resting one (ready, answer,
|
||||
error, cancelled), and the stored agent is not in the offered list. It then swaps the stored
|
||||
agent and thread to the default's own (`swapStoredAgent`, the same routine a swipe uses, so the
|
||||
removed agent's thread is set aside and the default's is restored with the usual window rule),
|
||||
saves, and applies `agent_reconciled` to the state.
|
||||
|
||||
- While a request is in flight the phase is not a resting one, so nothing changes: the turn is
|
||||
followed by its id and never moved or repeated.
|
||||
- Because it runs in the dispatch that makes the turn terminal, there is no step in which a
|
||||
question could start under the removed agent.
|
||||
- It also covers a case start-up previously missed: an abandoned (cancelled, unacknowledged)
|
||||
turn left `activeRequestId` set, which made `settleStartingAgent` return early.
|
||||
- The removed agent's answer or error stays on screen; from then on the agent name shown is the
|
||||
default's, which is who the next question goes to.
|
||||
|
||||
The save is not awaited (as for the other agent fields). If it is lost, the next start repeats
|
||||
the same reconciliation.
|
||||
|
||||
## CODY-022
|
||||
|
||||
README "Not in this slice" no longer lists multiple agents; it lists choosing an agent by name.
|
||||
|
||||
## State
|
||||
|
||||
Nothing deployed, uploaded or installed. Server and Even account as in Round 15. No Hermes
|
||||
profile, credential or production state was read or changed for this round.
|
||||
|
||||
## Checks
|
||||
|
||||
All pass on `bb3a309`, nothing omitted: `docs/test-evidence.md`, "Round 16".
|
||||
@@ -0,0 +1,75 @@
|
||||
# Handoff for Cody, Round 17
|
||||
|
||||
From: Claude (implementation). Date: 2026-11-28 (UTC).
|
||||
|
||||
**Not reviewed.** Round 16: `bb3a309` plus documentation, tip `75b7ea1`.
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Branch | `cody/droplet-deploy` |
|
||||
| `main` | `f02715fb6487f4e2ff0adeccfaad2403e1724aa5` (unchanged) |
|
||||
| Code change | `e1d183b54dc5aeb94822d8efeeeb358b6b14a664` |
|
||||
| New head | the tip after this push (this file and evidence only on top of the code change) |
|
||||
|
||||
## What this is
|
||||
|
||||
A new feature for trial, 0.3.0: an opening menu, and a hands-free mode in which an agent is called
|
||||
by name. Dan's requests are quoted in `docs/decisions/0004-always-listening.md`, which also lists
|
||||
what the implementer chose ("Owner decisions pending") and what the change reverses. Under the
|
||||
standing rule those are owner decisions pending the device trial.
|
||||
|
||||
It touches the **client**, the **bridge** (one new route, new config) and the **contract package**
|
||||
(two new schemas). No database change. No existing route, schema or error code changed.
|
||||
|
||||
## Design in six lines
|
||||
|
||||
1. `AppState.mode` is `agents` or `handsfree`. Everything else (agents, conversations, turns) is
|
||||
shared. A new `menu` phase is the root page; `back` at Ready returns to it and resets the mode.
|
||||
2. Hands free: at rest the microphone is open. `core/vad.ts` (pure, loudness only) emits
|
||||
utterances; each is sent to `POST /v1/wake`.
|
||||
3. The bridge transcribes, and `wake.ts` matches a leading agent name, exactly. It answers
|
||||
`{matched, agent_id, text, near_miss}` and creates nothing.
|
||||
4. A match with text becomes an ordinary **text turn** (`wake_text`); a name alone starts an
|
||||
ordinary **audio capture** that ends on a pause (`wake_listen`). Request-id persistence,
|
||||
deduplication, cancel and recovery are the existing code.
|
||||
5. The result of a wake check is dropped if the reducer generation changed meanwhile, so a tap,
|
||||
a cancel or a new pairing always wins over what was heard.
|
||||
6. With the `wake` option, all microphone opens and closes go through `Controller.syncMic()`,
|
||||
one at a time, each deciding from the state at its turn. Without the option (every test
|
||||
written before this round) the previous microphone code runs unchanged.
|
||||
|
||||
## Where to look hardest
|
||||
|
||||
- **A turn with tools can start with no button pressed** (security 3d). The guards are: first
|
||||
word only, exact match, "Heard: ..." on the HUD, double tap to cancel. No confirmation step.
|
||||
- **All nearby speech is uploaded while in hands free** (security 3c). `/v1/wake` returns empty
|
||||
`text` unless matched and logs ids only; one test asserts unaddressed speech is in no log line.
|
||||
- **One spoken word can reach the phone's Diagnostics**: a near miss, in memory only. This is a
|
||||
deliberate exception to "Diagnostics never contain content".
|
||||
- `syncMic` and `afterChange` in `core/controller.ts`: the ordering argument is in the comments.
|
||||
- `startCapture(auto)` seeds the recording from speech already heard while the name was being
|
||||
checked, capped at the capture limit.
|
||||
- The exit rule: the menu is the root page, so the system exit dialog is two double taps from
|
||||
Ready. Whether Even accepts that is unverified.
|
||||
- The manifest's `g2-microphone` description changed.
|
||||
|
||||
## Known limits, stated
|
||||
|
||||
- The segmenter's thresholds are guesses; no G2 audio has been through it. Tests use a tone.
|
||||
- The recogniser in the integration tests is the scripted fake. Whether Whisper writes "Wendy",
|
||||
"Cody" and "Pepper" as configured from G2 audio is unknown; aliases exist for that.
|
||||
- The simulator suite runs with `?wake=off&menu=off`: it still covers the tap path and idle exit
|
||||
and does **not** exercise the menu or hands free.
|
||||
- A wake check blocks further checks for that device until it returns; speech that ends during
|
||||
one is kept one deep (the latest), older is dropped.
|
||||
|
||||
## State
|
||||
|
||||
Nothing deployed, uploaded or installed. Server and Even account as in Round 16. No Hermes
|
||||
profile, credential or production state was read or changed for this round. An older bridge
|
||||
answers 404 to `/v1/wake`, on which the client ends hands free for the session, so the bridge
|
||||
must be deployed before 0.3.0 is useful.
|
||||
|
||||
## Checks
|
||||
|
||||
All pass, list and omissions in `docs/test-evidence.md`, "Round 17".
|
||||
@@ -0,0 +1,74 @@
|
||||
# Handoff for Cody, Round 19
|
||||
|
||||
From: Claude (implementation). Date: 2026-11-28 (UTC).
|
||||
|
||||
**Not reviewed.** Round 18: `44ea1148c34a271f4fdc565ef71a145adf459b42`, SHIP / SHIP FOR TRIAL.
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Branch | `cody/droplet-deploy` |
|
||||
| `main` | `f02715fb6487f4e2ff0adeccfaad2403e1724aa5` (unchanged) |
|
||||
| Code change | `f9946a027a92da79d9321bc7ca7e4555b8ba900f` |
|
||||
| New head | the tip after this push (this file and evidence only on top of the code change) |
|
||||
|
||||
## Since Round 18
|
||||
|
||||
On Dan's "go", `44ea114` was deployed to the server and 0.3.0 uploaded to beta, bridge first.
|
||||
Dan tried it; his whole report and exactly what it does and does not establish are in
|
||||
`docs/evidence/device/2026-11-28.md`. Decision 0004 item 4 (a name on every question) is
|
||||
"leave it as is for now". Nothing was changed in response.
|
||||
|
||||
## What this is
|
||||
|
||||
A new feature for trial, 0.4.0, requested by Dan (quoted in `docs/decisions/0005-live-preview.md`):
|
||||
see the words while recording. He expected to need a paid service; this uses the existing
|
||||
Whisper instead, and the decision record says what a streaming service would change.
|
||||
|
||||
Touches the **client**, the **bridge** (one new route, one new limit) and the **contract package**
|
||||
(one new response schema). No database change. No existing route, schema or error code changed.
|
||||
`/v1/wake`'s request checks were moved into a shared helper (`audioClip`); its one behavioural
|
||||
difference is the 400 message text ("Malformed request.").
|
||||
|
||||
## Design in five lines
|
||||
|
||||
1. `Controller.maybePreview` runs on each audio frame of a capture: after `firstMs` of audio,
|
||||
then every `stepMs` more, never with a request already out, it posts the capture so far.
|
||||
2. `POST /v1/transcribe` transcribes and returns `{text}`. Nothing else.
|
||||
3. The result is dispatched as `capture_preview` only if that same capture object is still the
|
||||
current one, its generation is current and the phase is still `listening`.
|
||||
4. The controller fits the text to seven lines with the same measurer as answers
|
||||
(`fitPreview`), keeping the end.
|
||||
5. Sending is unchanged: the audio turn transcribes the whole recording itself. `heard` is set
|
||||
from the turn's own `input_text`, only when the request was `spoken`.
|
||||
|
||||
## Where to look hardest
|
||||
|
||||
- The stale-result guard in 3, and that a preview for a cancelled or earlier recording is never
|
||||
drawn (one integration test, with a delayed recogniser).
|
||||
- A preview still running when the recording is sent holds the single-file recogniser queue, so
|
||||
the real transcription can start late by up to one clip. The route aborts on a closed
|
||||
connection, but the client does not close it, so this is a real cost today (0005, "Costs").
|
||||
- `accepted` now maps to the client phase `transcribing` for a spoken request without a
|
||||
transcript yet (it used to map to `thinking`). Typed requests are unchanged.
|
||||
- "Heard:" now appears in Agents mode for spoken questions. Typed questions never show it.
|
||||
- `fitPreview` always terminates: it drops at least one leading word per pass and stops at one.
|
||||
|
||||
## Round 18's required items
|
||||
|
||||
- Simulator: a ninth scenario launches the app with nothing switched off: menu drawn, swipe
|
||||
moves the marker (screenshots differ and return), tap gives hands free with the microphone
|
||||
opened through the real SDK bridge, double tap returns to the menu and closes it, Agents does
|
||||
not listen, silence is never sent. It cannot show a name being heard: the microphone is
|
||||
`alsa:null`.
|
||||
- The extra blank line at the end of `tests/integration/wake.test.ts` is gone.
|
||||
- Version is now 0.4.0, not 0.3.0: this is a new client behaviour. 0.3.0 is what is installed.
|
||||
|
||||
## State
|
||||
|
||||
Server: bridge `44ea114`. Even account: 0.3.0 on beta. Neither changed for this round. An older
|
||||
bridge answers 404 to `/v1/transcribe`, on which the client records as before, so 0.4.0 is
|
||||
safe against the deployed bridge but shows no words until the bridge is updated.
|
||||
|
||||
## Checks
|
||||
|
||||
`docs/test-evidence.md`, "Round 19", including one failed simulator run and what was not run.
|
||||
@@ -0,0 +1,68 @@
|
||||
# Handoff for Cody, Round 20
|
||||
|
||||
From: Claude (implementation). Date: 2026-11-28 (UTC).
|
||||
|
||||
**Not reviewed.** Round 19: `31ae4efb136abfe0dc7cfc564bbb30389fce8956`, SHIP / SHIP FOR TRIAL,
|
||||
with CODY-023 non-blocking. `31ae4ef` was **not** deployed or uploaded: Dan changed the contract
|
||||
before a rollout (below), and chose "one more review round".
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Branch | `cody/droplet-deploy` |
|
||||
| `main` | `f02715fb6487f4e2ff0adeccfaad2403e1724aa5` (unchanged) |
|
||||
| Code change | `2a63b7796a41280a27491039fcaa95e49ada5630` |
|
||||
| New head | the tip after this push (this file and evidence only on top of the code change) |
|
||||
|
||||
## 1. Contract change: the live preview is for Agents only
|
||||
|
||||
Dan, 2026-11-28, on being told what a paid recogniser would and would not offload:
|
||||
|
||||
> "I'd only invoke the live transciption when in agent sub-app. The main menu listener I would
|
||||
> not want it shipped like you imply."
|
||||
|
||||
and, of the resulting split (preview in Agents only; hands-free audio never to a paid service):
|
||||
"Right on all points. agreed. we're aligned. one more review round."
|
||||
|
||||
This narrows Round 19's first acceptance criterion: previews during tap and hold recordings **in
|
||||
Agents**; none in hands free, whether the recording was started by a name or by a tap.
|
||||
|
||||
The change is one guard in `Controller.maybePreview` (`state.mode !== 'agents'` returns). The
|
||||
hands-free test that asserted a preview now asserts the opposite: a name-started and a tapped
|
||||
recording in hands free make zero `/v1/transcribe` requests, show the ordinary instructions, and
|
||||
still reach the agent with the turn's own transcript. Nothing else in the client or bridge
|
||||
changed. No paid service is used, configured or designed.
|
||||
|
||||
Note for the reducer's two entry modes: without the `menu` option and with `wake`, the mode is
|
||||
`handsfree` from the start, so in that configuration there is no preview at all. The shipped
|
||||
configuration has the menu.
|
||||
|
||||
## 2. CODY-023
|
||||
|
||||
Confirmed. The README status table now has a first row, "What is where today", with one SHA or
|
||||
version per surface: server `44ea114`; Even beta channel 0.3.0 built from it; this repository's
|
||||
client 0.4.0, a candidate. The droplet row names `44ea114` and its evidence file. The simulator
|
||||
row says nine scenarios, which eight run with the new features off, what the ninth covers, that
|
||||
live preview is not exercised there, and that the runs are the implementer's. The 0.3.0 and
|
||||
0.4.0 rows each state their evidence level separately for fakes, simulator and device.
|
||||
|
||||
## 3. Simulator flake: one cause found, one not
|
||||
|
||||
Five runs before any change: four passed, one failed two scenarios. The failure was in "the
|
||||
answer is drawn": the screenshot taken a fixed 800 ms after the answer arrived had 790 lit pixels
|
||||
in the body, not over 2000, and the page-turn scenario then compared against that unfinished
|
||||
picture. The app had dispatched the answer; the simulator had not finished drawing it. From
|
||||
0.4.0 a spoken question draws one more frame before the answer ("Heard: ..."), so there is more
|
||||
queued in front of it than when the 800 ms was chosen. Those two scenarios now poll screenshots
|
||||
until the expected change appears (8 s limit). Six consecutive runs then passed all nine.
|
||||
|
||||
The Round 19 failure (idle exit never logging "leaving the glasses: idle on ready" within 15 s)
|
||||
did **not** recur in eleven runs and is still unexplained. It is not the same failure.
|
||||
|
||||
## State
|
||||
|
||||
Server: bridge `44ea114`. Even account: 0.3.0 on beta. Unchanged. Nothing deployed, uploaded or
|
||||
installed for Rounds 19 or 20.
|
||||
|
||||
## Checks
|
||||
|
||||
`docs/test-evidence.md`, "Round 20".
|
||||
+21
-1
@@ -33,7 +33,7 @@ devices. Not reviewed by anyone but its author yet; see `docs/handoff/`.
|
||||
| Blind replay after a timeout | A sent-but-unanswered request ends as `unknown`, never as retryable. | yes |
|
||||
| Oversized or malformed input | 32 kB JSON limit; audio capped at capture length + 1 s; schema validation; only one audio format accepted. | yes |
|
||||
| Request flooding | Per-device turn limit, per-address pairing limit, general per-device limit. | yes |
|
||||
| Cross-origin browser abuse | CORS allows only exact configured origins and sends no credentials mode. CORS is not treated as authentication: every route still needs the bearer credential. | yes |
|
||||
| Cross-origin browser abuse | CORS allows only exact configured origins, plus, only if configured, any port on a loopback address over http (`http://127.0.0.1:*`), which an Even Hub installed app requires. No other wildcard exists. CORS is not treated as authentication: every route still needs the bearer credential. | yes, including 17 look-alike and foreign origins |
|
||||
| Secrets or content in logs | Logs carry ids, states, codes and timings. Request logging is off, a redaction list backs it up, and Hermes's own diagnostic text is never relayed or logged. | yes |
|
||||
| Substituted speech-model files | The model is pinned to a commit id with a SHA-256 for every file. Files are fetched ahead of time and verified; the bridge re-verifies on every load, never downloads at run time, and reads from a directory that can be read-only. There is no unpinned mode. | yes, including with no network at all |
|
||||
| State files readable by other users | At every start the directory holding the database must be owned by the bridge's own user (a directory owned by anyone else is refused untouched, whatever its mode) and is set to 0700, whether it was just created or already existed; the bridge refuses to start otherwise. The database is created owner-only before SQLite opens it (so its WAL and SHM files inherit that); the systemd unit sets `UMask=0077`. | yes, under umask 0022, for new and pre-existing directories |
|
||||
@@ -69,12 +69,32 @@ Stated so they are not mistaken for protections.
|
||||
sandboxed process. It no longer stalls the bridge (measured 3 ms), but a crash inside the
|
||||
native runtime could still take the bridge down; systemd restarts it and in-flight turns are
|
||||
recovered or failed honestly.
|
||||
3c. **In hands-free mode (0.3.0; chosen on the opening menu at each launch, never on by itself)
|
||||
the microphone is open whenever the app is at rest**, and every stretch of speech near the glasses is uploaded to the bridge
|
||||
and transcribed, whoever is speaking and whether or not it is meant for an agent. The bridge
|
||||
keeps and returns only speech that begins with an agent's name; the rest is dropped after the
|
||||
transcription call and is not logged. That is a promise about this code, not a technical
|
||||
barrier: whoever controls the bridge host could record it. People near the wearer are not
|
||||
told. The HUD marks the open microphone with `●`; nothing outside the lenses does.
|
||||
3d. **In hands-free mode an agent can be started without a button.** Speech that begins with an agent's name is sent
|
||||
to that agent with whatever tools its Hermes profile allows, with no confirmation. A name is
|
||||
matched exactly and only as the first word, and what was heard is shown while the agent
|
||||
works, but a mis-transcription, another person saying the name, or audio from a speaker can
|
||||
all start a turn.
|
||||
3e. **From 0.4.0 a recording in progress is sent to the bridge repeatedly** (the whole recording
|
||||
so far, about twice a second) so its words can be shown. This is audio the user chose to
|
||||
record, going where the finished recording goes anyway; the text is returned to the app and
|
||||
not logged. A cancelled recording has therefore already reached the bridge, in memory only.
|
||||
4. **In the simulator, raw audio frames are echoed to the WebView console.** Whether the phone
|
||||
does the same is unknown and is on the device checklist. If it does, recordings would be
|
||||
visible to whoever can read that console.
|
||||
4a. **The state directory must be the bridge's own.** Because it is forced to 0700, pointing
|
||||
`HERMEVEN_DB_PATH` into a directory shared with other software will lock that software out;
|
||||
a directory owned by another user is refused.
|
||||
4b. **With `http://127.0.0.1:*` set, any page served from the phone's own loopback address may
|
||||
read the bridge's replies in a browser on that phone.** That includes a page served by some
|
||||
other app on the phone. It still cannot do anything without the device credential, which is
|
||||
held in the Even app's storage, not in a cookie the browser would attach by itself.
|
||||
5. **TLS is not terminated by the bridge.** A reverse proxy or private network must provide it. A
|
||||
misconfigured proxy could expose plain HTTP.
|
||||
6. **Rate limits are in memory** and reset on restart. Behind a proxy, per-address limits are only
|
||||
|
||||
@@ -417,3 +417,444 @@ parent-is-a-file refusal.
|
||||
|
||||
Three ways of removing the ownership check were tried against the suite; all three were caught
|
||||
(2 to 4 failing tests each).
|
||||
|
||||
## Round 7: after Cody's Round 6 review of the deployment documents (2026-11-21)
|
||||
|
||||
Cody reviewed `98c7b03` (deployment record and examples): REVIEW BLOCKED, with CODY-011
|
||||
(install sequence not executable on a clean host), CODY-012 (static client never installed) and
|
||||
CODY-013 (README contradicted the deployment evidence). The block also requires an independent
|
||||
acceptance contract, which only Dan can supply; none is included here.
|
||||
|
||||
```
|
||||
$ npm ci exit 0
|
||||
$ npm run typecheck exit 0
|
||||
$ npm test Tests 205 passed (205)
|
||||
$ npm run client:build built
|
||||
$ npm run test:real-stt Tests 11 passed (11)
|
||||
$ npm run test:real-hermes Tests 9 passed (9)
|
||||
$ npm run test:simulator Tests 6 passed (6)
|
||||
$ git diff --check clean
|
||||
$ tests/deploy/runbook-proof.sh exit 0 (on a disposable Ubuntu 24.04 host with systemd)
|
||||
caddy 2.6.2: validate "Valid configuration"; fmt --diff 0 changed lines
|
||||
systemd-analyze verify: ok (run on the disposable host, where /opt/node exists)
|
||||
```
|
||||
|
||||
`systemd-analyze verify` on the development desktop reports only that `/opt/node/bin/node` does
|
||||
not exist there, which is expected. No check was omitted.
|
||||
|
||||
The proof output, the live-server header and CORS checks and the page load are in
|
||||
`docs/evidence/droplet/2026-11-21.md`. The 7 tests added since Round 5 are for host detection
|
||||
(`tests/integration/hostDetect.test.ts`).
|
||||
|
||||
## Round 9: after Cody's Round 8 review, and the first device session (2026-11-21)
|
||||
|
||||
Cody reviewed `09e21f6`: REVIEW BLOCKED for lack of a contract, with CODY-014 open (blank page
|
||||
during host detection). Since then the branch also gained changes that came out of the first
|
||||
session on a physical G2. All checks below were run on `fb0a6b9`.
|
||||
|
||||
```
|
||||
$ npm ci exit 0
|
||||
$ npm run typecheck exit 0
|
||||
$ npm test Tests 224 passed (224)
|
||||
$ vitest hostDetect + entryPoint Tests 15 passed (15)
|
||||
$ npm run client:build built
|
||||
$ npm run test:real-stt Tests 11 passed (11)
|
||||
$ npm run test:real-hermes Tests 9 passed (9)
|
||||
$ npm run test:simulator Tests 7 passed (7)
|
||||
$ bash -n deploy/install.sh tests/deploy/runbook-proof.sh ok
|
||||
$ tests/deploy/runbook-proof.sh exit 0 (disposable Ubuntu 24.04 host with systemd)
|
||||
Caddy 2.6.2: "Valid configuration"; fmt --diff 0 changed lines
|
||||
systemd-analyze verify: ok; unit active, running as hermeven
|
||||
app tree: 0 files not root-owned, 0 group/other-writable
|
||||
$ git diff --check clean
|
||||
```
|
||||
|
||||
No check was omitted.
|
||||
|
||||
| Change | Tests | Negative control |
|
||||
|---|---|---|
|
||||
| CODY-014: start-up status, no eager fallback | `tests/integration/entryPoint.test.ts`: the real `index.html`, the real `boot()` and the real Even SDK in a DOM. Status visible before any script; still waiting just before the timeout; preview only after it; a callable host appearing mid-wait selects the Even adapter, initialises the SDK bridge and creates the HUD page; status removed on mount. | 6 ways of undoing it, all caught |
|
||||
| Glasses input diagnostic | Same file: events pushed through the SDK's own entry point show up by type; audio is counted and its payload never appears. | |
|
||||
| Long press and hold-to-talk | `tests/integration/client-bridge.test.ts` (5 tests), `apps/even-client/test/events.test.ts`, and the simulator's `long_press` / `long_press_release` actions. | |
|
||||
| Loopback any-port origins | `tests/integration/bridge.test.ts` (4 tests) and `services/bridge/test/units.test.ts`: any port on a configured loopback host is echoed; 17 look-alike, LAN, https and foreign origins are refused; no other wildcard is accepted by configuration; an allowed origin without a credential still gets 401. | 5 ways of loosening it; 4 caught, 1 is an equivalent change (an empty list already refuses) |
|
||||
|
||||
What happened on the device is in `docs/evidence/device/2026-11-21.md`; what was changed on the
|
||||
server, and with whose approval, is in `docs/evidence/droplet/2026-11-21.md`.
|
||||
|
||||
## Round 11: leaving the glasses when idle, version 0.1.1 (2026-11-21)
|
||||
|
||||
Run on `8171aee`.
|
||||
|
||||
```
|
||||
$ npm ci exit 0
|
||||
$ npm run typecheck exit 0
|
||||
$ npm test Tests 233 passed (233)
|
||||
$ vitest entryPoint + client-bridge + bridge + hostDetect Tests 111 passed (111)
|
||||
$ npm run client:build built
|
||||
$ npm run test:real-stt Tests 11 passed (11)
|
||||
$ npm run test:real-hermes Tests 9 passed (9)
|
||||
$ npm run test:simulator Tests 7 passed (7)
|
||||
$ bash -n deploy/install.sh tests/deploy/runbook-proof.sh ok
|
||||
$ tests/deploy/runbook-proof.sh exit 0 (Caddy 2.6.2 "Valid configuration", fmt 0 changed
|
||||
lines; systemd-analyze verify ok; unit active as hermeven)
|
||||
$ git diff --check clean
|
||||
```
|
||||
|
||||
No check was omitted.
|
||||
|
||||
New tests, all in `tests/integration/client-bridge.test.ts` (9):
|
||||
|
||||
| Behaviour | Proven by |
|
||||
|---|---|
|
||||
| After an answer sits untouched, the app leaves once, with the immediate exit and not the confirmation dialog | exit counter 1, dialog counter 0, microphone closed |
|
||||
| Any gesture restarts the countdown | six page turns, each inside the timeout, across more than three timeouts: no exit; then exit once left alone |
|
||||
| Never leaves while recording, transcribing, thinking, or awaiting approval | each held for more than two timeouts: no exit |
|
||||
| Leaves from Ready, and from an error screen | |
|
||||
| Opened from the phone with no gesture: stays; first glasses gesture arms it | |
|
||||
| Touching the phone page holds it open for the grace period | |
|
||||
| Can be switched off | |
|
||||
| A question soon after the last continues the conversation across a relaunch; after the gap it starts a new one | the fake agent's session count: 1, then 2 |
|
||||
|
||||
Six ways of breaking it were tried; five were caught. The sixth removed a line that restarts
|
||||
the countdown on a gesture, which is redundant because every gesture already passes through
|
||||
`dispatch()`, which restarts it.
|
||||
|
||||
The simulator suite runs with `?idleExit=off` (a development-only switch, compiled out of
|
||||
production builds) because it drives the app for longer than the idle timeout between steps.
|
||||
**The exit itself (`shutDownPageContainer(0)`) has not been run in the simulator or on a device.**
|
||||
|
||||
## Round 12: CODY-016, 017, 018 (2026-11-21)
|
||||
|
||||
Run on `bbde3c8`.
|
||||
|
||||
```
|
||||
$ npm ci exit 0
|
||||
$ npm run typecheck exit 0
|
||||
$ npm test Tests 251 passed (251)
|
||||
$ vitest --project integration entryPoint + client-bridge + bridge + idleExitHost + clientSecurity
|
||||
Tests 134 passed (134)
|
||||
$ npm run client:build built
|
||||
$ HERMEVEN_BRIDGE_ORIGIN=https://hermeven.xylo.gg npm run -w @hermeven/even-client pack
|
||||
Stamped hermeven.ehpk (99923 bytes); not uploaded
|
||||
$ npm run test:real-stt Tests 11 passed (11)
|
||||
$ npm run test:real-hermes Tests 9 passed (9)
|
||||
$ npm run test:simulator Tests 8 passed (8)
|
||||
$ bash -n deploy/install.sh tests/deploy/runbook-proof.sh ok
|
||||
$ tests/deploy/runbook-proof.sh exit 0 (Caddy "Valid configuration", fmt 0 changed lines;
|
||||
systemd-analyze verify ok; unit active as hermeven)
|
||||
$ git diff --check f02715f...HEAD ; git diff --check 1ae105e HEAD clean
|
||||
```
|
||||
|
||||
No check was omitted. The production bundle was searched for the development-only
|
||||
`?idleExit=` switch and its short timings: absent.
|
||||
|
||||
| Finding | Where | Proven by |
|
||||
|---|---|---|
|
||||
| CODY-016 | `tests/integration/idleExitHost.test.ts`, production adapter, stand-in host | `glassesMenu` pushed while start-up is parked on a stalled storage read and before the HUD exists: armed, one exit. Under a fake clock with the default times: pushed before the controller starts, and pushed after it subscribed, each gives no exit at 29.9 s, one at 30.1 s, still one after ten more minutes. `appMenu` pushed early: no exit in ten minutes; after one gesture, one exit 30 s later. A stopped controller hears nothing. |
|
||||
| CODY-018 | same file, plus `client-bridge.test.ts` and `clientSecurity.test.ts` | Host answers false, throws, or does not answer, then succeeds: retried and left exactly once. A held call is never joined by a second one (calls in flight never exceed 1), a late success after every attempt ran out is remembered and no further call is sent, a late refusal is followed by one fresh call. The exit waits behind an unfinished storage write. Bounded: a host that always refuses is asked 3 times (as configured), then again only after a gesture. A `system_exit` or `abnormal_exit` event stops both the exit and its retries. No unhandled rejection in any of these. No exit while recording, transcribing, thinking, awaiting approval, disconnected with a request outstanding, or in the phone grace period. |
|
||||
| CODY-017 | `README.md` | Read the status table and the paragraph beneath it. |
|
||||
|
||||
Deliberate breakages, each run against the new tests: launch source not replayed (6 tests
|
||||
fail), a failed exit treated as final (7), a second shutdown call issued while one is in flight
|
||||
(2), a late success forgotten (1), retries unbounded (2), the exit bypassing the host-call queue
|
||||
(first run: not caught; a test was added and it is now caught, 1).
|
||||
|
||||
Simulator (0.9.5), new eighth scenario, run with the development-only `?idleExit=fast` (5 s at
|
||||
Ready) and without idle exit disabled: opened by URL with no gesture, nothing happens for 6.5 s;
|
||||
after one swipe the app logs "leaving the glasses: idle on ready", the simulator's
|
||||
`shutDownPageContainer(0)` answers true, the app logs "left the glasses", and the display is
|
||||
empty (`docs/evidence/simulator/08-after-idle-exit.png`). This shows what the simulator does. It
|
||||
is not evidence of what the Even app or the glasses do.
|
||||
|
||||
## Round 13: CODY-019 (2026-11-21)
|
||||
|
||||
Run on `d8582e9`.
|
||||
|
||||
```
|
||||
$ npm ci exit 0
|
||||
$ npm run typecheck exit 0
|
||||
$ npm test Tests 257 passed (257)
|
||||
$ vitest --project integration idleExitHost + client-bridge + clientSecurity + entryPoint
|
||||
Tests 85 passed (85)
|
||||
$ npm run client:build built
|
||||
$ HERMEVEN_BRIDGE_ORIGIN=https://hermeven.xylo.gg npm run -w @hermeven/even-client pack
|
||||
Stamped hermeven.ehpk (99934 bytes); not uploaded
|
||||
$ npm run test:real-stt Tests 11 passed (11)
|
||||
$ npm run test:real-hermes Tests 9 passed (9)
|
||||
$ npm run test:simulator Tests 8 passed (8)
|
||||
$ bash -n deploy/install.sh tests/deploy/runbook-proof.sh ok
|
||||
$ tests/deploy/runbook-proof.sh exit 0 (Caddy "Valid configuration"; systemd-analyze verify ok)
|
||||
$ git diff --check f02715f...HEAD ; git diff --check 3d0edeb..HEAD clean
|
||||
```
|
||||
|
||||
No check was omitted.
|
||||
|
||||
Six new tests in `tests/integration/idleExitHost.test.ts` ("activity during a pending exit
|
||||
keeps its full countdown"), production adapter, default times, fake clock. In each, the first
|
||||
exit call (30 s after Ready) is held by the stand-in host, then:
|
||||
|
||||
| Activity while held | Host then | Proven |
|
||||
|---|---|---|
|
||||
| swipe at Ready (generation asserted unchanged) | answers false | no call for 29.8 s after the swipe; then one call, which succeeds; left once |
|
||||
| swipe at Ready | call rejects | same |
|
||||
| swipe at Ready | never answers in time | no "will try again" is logged; after the full countdown the retry waits on the same call; late success: one host call ever, left once |
|
||||
| touch on the phone page | answers false | no call for 149.5 s (120 s grace plus 30 s); one call by 150.5 s; left once |
|
||||
| swipe at Ready | refuses every time | four further attempts, then "staying until the next activity", no more |
|
||||
| none (control) | answers false | retried after 3 s |
|
||||
|
||||
Calls in flight never exceed one in any of them, and no unhandled rejection is raised.
|
||||
|
||||
Negative control: with the activity-epoch guard removed, four of the six fail (the three swipe
|
||||
cases and the bounded case). The phone-activity case does **not** fail without the guard: the
|
||||
timer callback's own phone-grace check already protected it. It is kept as a regression test,
|
||||
not claimed as a control.
|
||||
|
||||
## Round 14: idle exit starts however the app was opened, 0.1.2 (2026-11-21)
|
||||
|
||||
Run on `344a228`.
|
||||
|
||||
```
|
||||
$ npm ci exit 0
|
||||
$ npm run typecheck exit 0
|
||||
$ npm test Tests 262 passed (262)
|
||||
$ vitest --project integration idleExitHost + client-bridge + clientSecurity + entryPoint
|
||||
Tests 90 passed (90)
|
||||
$ npm run client:build built
|
||||
$ HERMEVEN_BRIDGE_ORIGIN=https://hermeven.xylo.gg npm run -w @hermeven/even-client pack
|
||||
Stamped hermeven.ehpk (99881 bytes); not uploaded
|
||||
$ npm run test:real-stt Tests 11 passed (11)
|
||||
$ npm run test:real-hermes Tests 9 passed (9)
|
||||
$ npm run test:simulator Tests 8 passed (8)
|
||||
$ bash -n deploy/install.sh tests/deploy/runbook-proof.sh ok
|
||||
$ tests/deploy/runbook-proof.sh exit 0 (Caddy "Valid configuration"; systemd-analyze verify ok)
|
||||
$ git diff --check f02715f...HEAD ; git diff --check 3e04688..HEAD clean
|
||||
```
|
||||
|
||||
No check was omitted.
|
||||
|
||||
| Behaviour | Proven by |
|
||||
|---|---|
|
||||
| No launch source and no gesture (what the real G2 gave on a voice launch): one exit, 30 s after Ready | `idleExitHost.test.ts`, fake clock, production adapter; and with short times in `client-bridge.test.ts` |
|
||||
| `appMenu`: leaves the same way | both files |
|
||||
| A `glassesMenu` that arrives late neither restarts nor doubles the countdown | no call at 29.9 s from Ready, one at 30.1 s, one after ten more minutes |
|
||||
| Phone page touched after opening: full 120 s grace, then 30 s | no call at 149.5 s from the touch, one by 150.5 s |
|
||||
| Never paired: nothing leaves in 30 minutes, even with a gesture and a `glassesMenu` source | both files |
|
||||
| Simulator: opened by URL with no gesture, leaves from Ready after the shortened wait; exit confirmed; display empty | eighth simulator scenario |
|
||||
|
||||
Correction (CODY-020, Round 14): the mutation described next is **stricter** than the previous
|
||||
implementation, which also armed after any gesture. It is
|
||||
`|| this.launchSource !== 'glassesMenu'` added to the guard in `scheduleIdleExit()`. Cody restored
|
||||
the exact previous controller from `3e04688` and reported 7 failed, 62 passed of 69; the
|
||||
implementer did not re-run that.
|
||||
|
||||
Negative control (stricter mutation): leave only after a `glassesMenu` launch source,
|
||||
11 of the 69 tests in the two files fail, including all five new cases above except "never
|
||||
paired". The CODY-019 control was not re-run; `activityEpoch` and its tests are unchanged and
|
||||
pass.
|
||||
|
||||
## Round 15: choosing an agent, 0.2.0 (2026-11-21/22)
|
||||
|
||||
Run on `9394c24`.
|
||||
|
||||
```
|
||||
$ npm ci exit 0
|
||||
$ npm run typecheck exit 0
|
||||
$ npm test Test Files 15 passed; Tests 296 passed (296)
|
||||
$ vitest --project integration agents + idleExitHost + client-bridge + clientSecurity + entryPoint + bridge
|
||||
Tests 174 passed (174)
|
||||
$ npm run client:build built
|
||||
$ HERMEVEN_BRIDGE_ORIGIN=https://hermeven.xylo.gg npm run -w @hermeven/even-client pack
|
||||
Stamped hermeven.ehpk (100769 bytes); not uploaded
|
||||
$ npm run test:real-stt Tests 11 passed (11)
|
||||
$ npm run test:real-hermes Tests 9 passed (9) (default agent only; see below)
|
||||
$ npm run test:simulator Tests 8 passed (8) (one agent: screens unchanged)
|
||||
$ bash -n deploy/install.sh tests/deploy/runbook-proof.sh ok
|
||||
$ tests/deploy/runbook-proof.sh exit 0 (Caddy "Valid configuration"; systemd-analyze verify ok)
|
||||
$ git diff --check f02715f...HEAD ; git diff --check 15714bd..HEAD clean
|
||||
```
|
||||
|
||||
No check was omitted.
|
||||
|
||||
New: `tests/integration/agents.test.ts` (29 tests) and five reducer tests. The Hermes in them is
|
||||
the test fake, extended to imitate multiplexed profiles: `/p/<profile>/...`, a separate key per
|
||||
profile, runs and idempotency keys invisible from any other profile, 404 for an unserved profile.
|
||||
|
||||
| Behaviour | Proven by |
|
||||
|---|---|
|
||||
| The list: ids and names only, default first; needs a credential; one agent when none are configured | response compared whole; searched for keys, `/p/` and the Hermes address |
|
||||
| `/v1/device` has exactly its previous fields | key list compared |
|
||||
| A Wendy conversation is submitted and polled only at her prefix, with her key | every `/v1/runs` request recorded by the fake carries profile `wendy` |
|
||||
| An id not on the list (including real profiles that are not listed) or a malformed one: 400, no conversation row, nothing sent to Hermes | |
|
||||
| Per-agent conversations: a new one with Wendy closes only her earlier one; Pepper's keeps its history | fake session count and turn numbers |
|
||||
| Lost Hermes reply, and bridge restart mid-run, for a non-default agent: one execution, same key, same agent | execution counter, posted keys |
|
||||
| Wrong key, or the default's key, at another agent: `agent_rejected`, nothing ran, other agents unaffected | |
|
||||
| Agent removed while its turn is in flight: `outcome_unknown` after restart, not sent to anyone else | |
|
||||
| Keys never in the bridge log | log searched |
|
||||
| Configuration errors refused | seven cases |
|
||||
| Glasses: opens on the default with its name; swipe moves through the list and wraps, sending nothing | |
|
||||
| Question, spoken or typed, goes to the chosen agent; name on listening, thinking and answer screens; follow-up continues with it | |
|
||||
| A swipe chooses only at Ready (pages on an answer, nothing while busy) | integration and reducer tests |
|
||||
| Reopen: within the window on the last agent and its conversation; after it, or if never asked, or if removed, on the default; list unavailable at start: last known list | |
|
||||
| One-agent bridge, and a bridge without `/v1/agents`: screens and requests exactly as before | request bodies compared |
|
||||
|
||||
Eight ways of breaking it were tried against `agents.test.ts`; seven failed tests there (13, 2,
|
||||
2, 6, 3, 2 and 1). The eighth (letting the reducer accept a selection on any screen) passed
|
||||
there because the controller refuses it too; a reducer test was added and now fails under it.
|
||||
|
||||
Not covered by an automated test against a real Hermes: profile multiplexing. The real-Hermes
|
||||
suite's isolated gateway serves one profile. What exists instead is one manual request on the
|
||||
server (`docs/evidence/droplet/2026-11-21.md`): Wendy's profile answered through `/p/wendy` with
|
||||
her own key, an identical resubmit returned the same run, and the keys were refused crosswise.
|
||||
The simulator suite runs with one agent; the agent screens have not been drawn in the simulator.
|
||||
|
||||
## Round 16: CODY-021, CODY-022 (2026-11-22)
|
||||
|
||||
Run on `bb3a309`.
|
||||
|
||||
```
|
||||
$ npm ci exit 0
|
||||
$ npm run typecheck exit 0
|
||||
$ npm test Test Files 15 passed; Tests 299 passed (299)
|
||||
$ vitest --project integration agents + idleExitHost + client-bridge + clientSecurity + entryPoint + bridge
|
||||
Tests 176 passed (176)
|
||||
$ npm run client:build built
|
||||
$ HERMEVEN_BRIDGE_ORIGIN=https://hermeven.xylo.gg npm run -w @hermeven/even-client pack
|
||||
Stamped hermeven.ehpk (100903 bytes); not uploaded
|
||||
$ npm run test:real-stt Tests 11 passed (11)
|
||||
$ npm run test:real-hermes Tests 9 passed (9)
|
||||
$ npm run test:simulator Tests 8 passed (8)
|
||||
$ bash -n deploy/install.sh tests/deploy/runbook-proof.sh ok
|
||||
$ tests/deploy/runbook-proof.sh exit 0 (Caddy "Valid configuration"; systemd-analyze verify ok)
|
||||
$ git diff --check f02715f...HEAD ; git diff --check c8b4fb0..HEAD clean
|
||||
```
|
||||
|
||||
No check was omitted.
|
||||
|
||||
CODY-021, two integration tests in `tests/integration/agents.test.ts` and one reducer test:
|
||||
|
||||
| Step | Asserted |
|
||||
|---|---|
|
||||
| Pepper is asked once; Wendy is chosen; a turn that never finishes is started with her | executions: default, wendy |
|
||||
| Wendy is removed from the list, the bridge restarts, the page is reopened | the app re-attaches to the same request id |
|
||||
| Her turn settles | `outcome_unknown` on screen; still exactly one execution at Wendy |
|
||||
| At that moment | state `agentId` is `default`; storage `agentId` becomes `default` |
|
||||
| Back to Ready | HUD `Pepper\n\nReady.` |
|
||||
| Another question | goes to the default agent in the default agent's OWN conversation (turn 2, containing the first Pepper question); executions: default, wendy, default; one POST ever under Wendy's prefix |
|
||||
| Variant: the next question is asked straight from her result screen | same routing; the conversation created names `default` |
|
||||
| Reducer | the fallback applies on a resting screen and keeps what is on it; ignored while listening or in flight |
|
||||
|
||||
Negative controls, each run against those tests: reconciliation removed (the reviewed
|
||||
behaviour): 2 failed, 63 passed of 65. Reconciling while her turn is still in flight: 2 failed.
|
||||
Relabelling her conversation as the default's instead of restoring the default's own: 2 failed.
|
||||
Reducer applying the fallback while busy: 1 failed.
|
||||
|
||||
## Round 17 (2026-11-28): menu and hands-free mode, on `e1d183b54dc5aeb94822d8efeeeb358b6b14a664`
|
||||
|
||||
```
|
||||
$ npm run typecheck clean
|
||||
$ npm test Test Files 18 passed (18); Tests 341 passed (341)
|
||||
$ npm run client:build built
|
||||
$ npm run test:real-hermes Tests 9 passed (9)
|
||||
$ npm run test:real-stt Tests 11 passed (11)
|
||||
$ npm run test:simulator Tests 8 passed (8) (launched with ?wake=off&menu=off)
|
||||
$ git diff --check clean
|
||||
```
|
||||
|
||||
Omitted: `pack` (nothing is being uploaded), `tests/deploy/runbook-proof.sh` (no deploy file
|
||||
changed except a comment block in `deploy/bridge.env.example`). No negative controls were run.
|
||||
|
||||
Everything about the menu and hands free is **fakes only**: a 440 Hz tone for speech, a scripted
|
||||
recogniser for what it "said", the fake glasses. New tests: `services/bridge/test/wake.test.ts`
|
||||
(9), `apps/even-client/test/vad.test.ts` (8), `tests/integration/wake.test.ts` (24), one HUD
|
||||
test and more variants in `apps/even-client/test/layout.test.ts`.
|
||||
|
||||
| Asserted in `tests/integration/wake.test.ts` | |
|
||||
|---|---|
|
||||
| `/v1/wake` | match with text, name alone, greeting, alias; unaddressed speech returns empty text and appears in no log line; near miss is one word; 401 / 400 / 415; failed transcription is "not matched"; 404 with no speech-to-text or no named agent; one check at a time and a per-minute budget separate from turns; no run is posted to Hermes |
|
||||
| Menu | opens on it with Hands free first, microphone closed, nothing sent; one tap is hands free; double tap at Ready returns to it and closes the microphone; double tap on it requests the system exit; Agents behaves as 0.2.0 including idle exit; an untouched menu leaves, hands free does not; Agents only where hands free cannot work; a turn in flight at relaunch is shown instead of the menu |
|
||||
| Hands free | one-breath question reaches the named agent as text with "Heard:" shown; microphone closed while in flight and reopened at rest; agents switch by name and keep their own conversations; name alone records and sends on a 1.2 s pause without reopening the microphone; a question finished before the name was recognised is not lost; name then silence sends nothing; a tap during a check wins; 404 from the bridge ends hands free and says so; refused or silent microphone is retried; closed on disconnect and stop |
|
||||
|
||||
## Round 19 (2026-11-28): live preview, on `f9946a027a92da79d9321bc7ca7e4555b8ba900f`
|
||||
|
||||
```
|
||||
$ npm run typecheck clean
|
||||
$ npm test Test Files 18 passed (18); Tests 349 passed (349)
|
||||
$ npx vitest run (the Round 18 list: wake, vad, layout, integration wake) Tests 66 passed (66)
|
||||
$ npm run client:build built
|
||||
$ HERMEVEN_BRIDGE_ORIGIN=https://hermeven.xylo.gg npm run -w @hermeven/even-client pack (twice)
|
||||
hermeven.ehpk 105146 bytes, SHA-256
|
||||
eba2103df81e0e7c35e5684fcd07915f03af1015f5f9c5acae730e25039f8d8f both times; not uploaded
|
||||
$ npm run test:real-stt Tests 11 passed (11)
|
||||
$ npm run test:real-hermes Tests 9 passed (9)
|
||||
$ npm run test:simulator 4 runs with the ninth scenario: 9 passed (9) three times;
|
||||
once 1 failed | 8 passed (see below)
|
||||
$ bash -n deploy/install.sh tests/deploy/runbook-proof.sh ok
|
||||
$ systemd-analyze verify deploy/hermeven-bridge.service exit 0; one message: /opt/node/bin/node
|
||||
"is not executable" (it does not exist on the development desktop)
|
||||
$ git diff --check origin/main...HEAD clean (run on the committed SHA)
|
||||
```
|
||||
|
||||
Everything except the last line was run on the working tree immediately before it was committed
|
||||
as the SHA above, not on a fresh checkout of it. `npm ci` was not re-run.
|
||||
|
||||
**The failed simulator run.** The first run after adding the ninth scenario failed in the
|
||||
existing eighth scenario (idle exit with short waits), at
|
||||
`waitConsole('leaving the glasses: idle on ready', 15_000)`: the line never appeared. The next
|
||||
three runs passed all nine. The cause was not found. That scenario launches with
|
||||
`wake=off&menu=off&preview=off`, where none of this round's client code runs
|
||||
(`afterChange` and `maybePreview` return at once), but that is an argument, not a diagnosis.
|
||||
|
||||
**Not run:** `caddy validate` (caddy is not installed here), `tests/deploy/runbook-proof.sh`
|
||||
(no file under `deploy/` changed in this round). No negative controls were run.
|
||||
|
||||
New tests, all in `tests/integration/wake.test.ts` (fakes: a tone, a scripted recogniser):
|
||||
|
||||
| | Asserted |
|
||||
|---|---|
|
||||
| `/v1/transcribe` | returns trimmed text; posts nothing to Hermes; the text is in no log line; 401, 400 (wrong format, odd byte count); failed transcription gives empty text; 404 without speech-to-text; one at a time per device and its own per-minute budget, separate from wake checks |
|
||||
| Words while recording | the HUD shows each preview as the recording grows; after sending, the last preview stays under "Transcribing…"; "Heard:" then shows the turn's own transcript (which differs from the previews in the test); exactly one turn and one execution |
|
||||
| Long text | the newest words are kept, with a leading "…", within nine measured lines |
|
||||
| Stale preview | one that returns after a cancel, during the next recording, is not drawn |
|
||||
| Fallbacks | without speech-to-text nothing is requested and recording works; a typed question never shows "Heard:" |
|
||||
| Hands free | the question after a name alone shows its words and reaches the named agent |
|
||||
|
||||
## Round 20 (2026-11-28): preview for Agents only, CODY-023, on `2a63b7796a41280a27491039fcaa95e49ada5630`
|
||||
|
||||
```
|
||||
$ npm run typecheck clean
|
||||
$ npm test Test Files 18 passed (18); Tests 349 passed (349)
|
||||
$ npx vitest run (the Round 18 list) Tests 66 passed (66)
|
||||
$ npm run client:build built (as part of pack)
|
||||
$ HERMEVEN_BRIDGE_ORIGIN=https://hermeven.xylo.gg npm run -w @hermeven/even-client pack (twice)
|
||||
hermeven.ehpk 105155 bytes, SHA-256
|
||||
311078550ed1a176b9a1530cced0c81a322b40e83ecdc9b21402fb08b1ebe58d both times; not uploaded
|
||||
$ npm run test:real-stt Tests 11 passed (11)
|
||||
$ npm run test:real-hermes Tests 9 passed (9)
|
||||
$ npm run test:simulator 11 runs, see below
|
||||
$ bash -n deploy/install.sh tests/deploy/runbook-proof.sh ok
|
||||
$ git diff --check origin/main...HEAD ; git diff --check 31ae4ef HEAD clean (on the committed SHA)
|
||||
```
|
||||
|
||||
Simulator runs, in order. Runs 1 to 5 were on the tree with the Agents-only guard and the README
|
||||
change but before the screenshot-polling change; runs 6 to 11 after it (the committed tree).
|
||||
|
||||
| Run | Result |
|
||||
|---|---|
|
||||
| 1, 2 | 9 passed |
|
||||
| 3 | 2 failed, 7 passed: "the answer is drawn" (`expected 790 to be greater than 2000` lit pixels, 800 ms after the answer) and, following from it, the page-turn comparison |
|
||||
| 4, 5 | 9 passed |
|
||||
| 6 to 11 | 9 passed, six times |
|
||||
|
||||
real-stt, real-hermes, `npm test` and the first five simulator runs were made before the
|
||||
screenshot-polling change to `tests/simulator/simulator.test.ts`, which touches no other file;
|
||||
`npm test`, typecheck and the two packs were repeated after it. `npm ci` was not re-run.
|
||||
|
||||
**Not run:** `caddy validate` (not installed here), `systemd-analyze verify` and
|
||||
`tests/deploy/runbook-proof.sh` (no file under `deploy/` changed since Round 18). No negative
|
||||
control was run for the Agents-only guard beyond the test having asserted the opposite, and
|
||||
passed, on the previous commit.
|
||||
|
||||
Negative coverage kept from Round 19, all still in `tests/integration/wake.test.ts`: stale
|
||||
preview completion; final transcript differing from the previews; old-bridge and no-STT
|
||||
fallback; per-device busy and rate limits for both routes; no transcript in any log line;
|
||||
exactly one turn and one execution. Added: zero preview requests in hands free.
|
||||
|
||||
Generated
+95
@@ -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",
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -127,8 +127,28 @@ export const RevokeResponse = Type.Object(
|
||||
export type RevokeResponse = Static<typeof RevokeResponse>;
|
||||
|
||||
// ---------------------------------------------------------- conversations
|
||||
/** Lower-case id of an agent the bridge is configured to reach. `default` is the main one. */
|
||||
const AgentId = Type.String({ pattern: '^[a-z][a-z0-9_-]{0,31}$' });
|
||||
|
||||
export const AgentsResponse = Type.Object(
|
||||
{
|
||||
schema_version: SchemaVersion,
|
||||
/** In the order the owner configured them; the first is the default. Never empty. */
|
||||
agents: Type.Array(
|
||||
Type.Object({ id: AgentId, name: Type.String({ minLength: 1, maxLength: 24 }) }, { additionalProperties: false }),
|
||||
{ minItems: 1, maxItems: 16 },
|
||||
),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type AgentsResponse = Static<typeof AgentsResponse>;
|
||||
|
||||
export const ConversationCreateRequest = Type.Object(
|
||||
{ schema_version: SchemaVersion },
|
||||
{
|
||||
schema_version: SchemaVersion,
|
||||
/** Which configured agent this conversation is with. Omitted = the default agent. */
|
||||
agent_id: Type.Optional(AgentId),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type ConversationCreateRequest = Static<typeof ConversationCreateRequest>;
|
||||
@@ -180,6 +200,54 @@ export const AudioTurnQuery = Type.Object(
|
||||
);
|
||||
export type AudioTurnQuery = Static<typeof AudioTurnQuery>;
|
||||
|
||||
// ------------------------------------------------------------------- wake
|
||||
/**
|
||||
* Query string of POST /v1/wake. The body is raw audio, as for an audio turn: one stretch of
|
||||
* speech heard while the app was open. The bridge transcribes it and says whether it began
|
||||
* with an agent's name. Nothing is stored and no turn is created.
|
||||
*/
|
||||
export const WakeQuery = Type.Object(
|
||||
{
|
||||
schema_version: Type.Literal(String(SCHEMA_VERSION)),
|
||||
locale: Locale,
|
||||
encoding: Type.Literal(AUDIO_FORMAT.encoding),
|
||||
sample_rate: Type.Literal(String(AUDIO_FORMAT.sampleRate)),
|
||||
channels: Type.Literal(String(AUDIO_FORMAT.channels)),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type WakeQuery = Static<typeof WakeQuery>;
|
||||
|
||||
export const WakeResponse = Type.Object(
|
||||
{
|
||||
schema_version: SchemaVersion,
|
||||
/** The speech began with an agent's name. */
|
||||
matched: Type.Boolean(),
|
||||
agent_id: Type.Union([AgentId, Type.Null()]),
|
||||
/**
|
||||
* What was said after the name, when matched (empty when only the name was said). Always
|
||||
* empty when not matched: speech that was not for an agent is not returned.
|
||||
*/
|
||||
text: Type.String({ maxLength: DEFAULT_LIMITS.textMaxChars }),
|
||||
/** Not matched, but the first word was close to an agent's name: that one word, for tuning aliases. */
|
||||
near_miss: Type.Union([Type.String({ maxLength: 24 }), Type.Null()]),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type WakeResponse = Static<typeof WakeResponse>;
|
||||
|
||||
/**
|
||||
* Answer of POST /v1/transcribe (same query string and body as /v1/wake): the words in a
|
||||
* recording that is still being made, so the app can show them while the user speaks. A
|
||||
* preview only: it creates nothing, and the question that is finally sent is transcribed again
|
||||
* by the turn itself.
|
||||
*/
|
||||
export const TranscribeResponse = Type.Object(
|
||||
{ schema_version: SchemaVersion, text: Type.String({ maxLength: DEFAULT_LIMITS.textMaxChars }) },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type TranscribeResponse = Static<typeof TranscribeResponse>;
|
||||
|
||||
export const TURN_STATES = [
|
||||
'accepted',
|
||||
'transcribing',
|
||||
|
||||
@@ -55,6 +55,13 @@ export async function createBridge(
|
||||
apiKey: config.hermes.apiKey,
|
||||
requestTimeoutMs: config.hermes.requestTimeoutMs,
|
||||
});
|
||||
// One adapter per extra agent: its own address under the same gateway, and its own key.
|
||||
const agents = new Map<string, HermesAdapter>(
|
||||
config.agents.slice(1).map((agent) => [
|
||||
agent.id,
|
||||
new HermesRunsAdapter({ baseUrl: agent.baseUrl, apiKey: agent.apiKey, requestTimeoutMs: config.hermes.requestTimeoutMs }),
|
||||
]),
|
||||
);
|
||||
const stt = overrides.stt ?? sttFromConfig(config);
|
||||
const devices = new Devices(db, config);
|
||||
|
||||
@@ -65,7 +72,7 @@ export async function createBridge(
|
||||
? (given as Logger)
|
||||
: pino(given as object)
|
||||
: pino({ level: 'silent' });
|
||||
const engine = new TurnEngine({ db, config, devices, hermes, stt, log: logger as unknown as EngineLog, timing: overrides.timing });
|
||||
const engine = new TurnEngine({ db, config, devices, hermes, agents, stt, log: logger as unknown as EngineLog, timing: overrides.timing });
|
||||
const app = await buildServer({ config, devices, hermes, stt, engine, logger });
|
||||
|
||||
engine.recover();
|
||||
|
||||
@@ -2,6 +2,23 @@ import { existsSync, readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { AUDIO_FORMAT, DEFAULT_LIMITS } from '@hermeven/contracts';
|
||||
import { validateManifest, type ModelManifest } from './stt/modelStore.mjs';
|
||||
import { wakeWordsFor } from './wake.ts';
|
||||
|
||||
export interface AgentConfig {
|
||||
/** `default` for the main agent; otherwise the id from HERMEVEN_AGENTS. */
|
||||
id: string;
|
||||
/** Shown on the glasses. */
|
||||
name: string;
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
/**
|
||||
* What this agent answers to when spoken first ("Wendy, ..."): the first word of its name plus
|
||||
* any aliases, lower-case. Empty = it cannot be called by voice. Never sent to a client.
|
||||
*/
|
||||
wakeWords: string[];
|
||||
}
|
||||
|
||||
export const DEFAULT_AGENT_ID = 'default';
|
||||
|
||||
export interface BridgeConfig {
|
||||
host: string;
|
||||
@@ -9,6 +26,12 @@ export interface BridgeConfig {
|
||||
dbPath: string;
|
||||
/** Exact browser origins allowed by CORS. Empty = no cross-origin browser access. */
|
||||
allowedOrigins: string[];
|
||||
/**
|
||||
* Loopback hosts whose pages are allowed from ANY port (`http://127.0.0.1:*`). Needed because
|
||||
* the Even phone app serves an installed app from `http://127.0.0.1:<port>` and picks a new
|
||||
* port on every launch (observed on a real phone, 2026-11-21). Empty unless configured.
|
||||
*/
|
||||
allowedLoopbackAnyPort: string[];
|
||||
/** Refuse to bind a non-loopback address without this (TLS must terminate in front). */
|
||||
allowNonLoopback: boolean;
|
||||
/** Trust X-Forwarded-For from a reverse proxy (only when one is actually in front). */
|
||||
@@ -24,6 +47,11 @@ export interface BridgeConfig {
|
||||
pollIntervalMs: number;
|
||||
requestTimeoutMs: number;
|
||||
};
|
||||
/**
|
||||
* Every agent a paired device may talk to, default first. The list is the owner's allow-list:
|
||||
* a client can only name an id from it. Each agent has its own Hermes address and its own key.
|
||||
*/
|
||||
agents: AgentConfig[];
|
||||
stt: {
|
||||
provider: 'none' | 'builtin' | 'openai-compatible';
|
||||
baseUrl: string;
|
||||
@@ -43,6 +71,10 @@ export interface BridgeConfig {
|
||||
textMaxChars: number;
|
||||
audioMaxBytes: number;
|
||||
turnsPerMinute: number;
|
||||
/** Wake checks (speech heard while the app is open, tested for a leading agent name). */
|
||||
wakeChecksPerMinute: number;
|
||||
/** Live previews of a recording in progress. */
|
||||
previewsPerMinute: number;
|
||||
pairingAttemptsPerMinute: number;
|
||||
};
|
||||
credentials: {
|
||||
@@ -128,6 +160,75 @@ function loadModelManifest(name: string, customPath: string | undefined): ModelM
|
||||
}
|
||||
}
|
||||
|
||||
const AGENT_ID = /^[a-z][a-z0-9_-]{0,31}$/;
|
||||
|
||||
function agentName(key: string, raw: string | undefined, fallback: string): string {
|
||||
const name = (raw ?? '').trim() || fallback;
|
||||
if (name.length > 24 || /[\u0000-\u001f]/.test(name)) throw new ConfigError(`${key} must be at most 24 printable characters`);
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* The default agent is the Hermes API server at HERMES_BASE_URL with HERMES_API_KEY. Further
|
||||
* agents are named in HERMEVEN_AGENTS (comma-separated ids) and are other profiles served by
|
||||
* the same Hermes gateway under `/p/<profile>` (gateway.multiplex_profiles). Hermes gives each
|
||||
* profile its own key and refuses the default's, so every extra agent needs
|
||||
* HERMEVEN_AGENT_<ID>_API_KEY. Optional: HERMEVEN_AGENT_<ID>_PROFILE (default: the id) and
|
||||
* HERMEVEN_AGENT_<ID>_NAME (default: the id, capitalised).
|
||||
*
|
||||
* An agent is called by voice with the first word of its name. HERMEVEN_AGENT_<ID>_WAKE (for the
|
||||
* default agent, HERMEVEN_AGENT_WAKE) adds comma-separated aliases, for spellings the speech
|
||||
* model produces instead ("kody"). Two agents may not answer to the same word.
|
||||
*/
|
||||
function wakeWords(key: string, raw: string | undefined, name: string): string[] {
|
||||
const aliases = (raw ?? '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
if (aliases.length > 8 || aliases.some((a) => a.length > 32)) throw new ConfigError(`${key} takes at most 8 aliases of at most 32 characters`);
|
||||
return wakeWordsFor(name, aliases);
|
||||
}
|
||||
|
||||
function agentsFromEnv(env: NodeJS.ProcessEnv, baseUrl: string, defaultKey: string): AgentConfig[] {
|
||||
const defaultName = agentName('HERMEVEN_AGENT_NAME', env.HERMEVEN_AGENT_NAME, 'Agent');
|
||||
const agents: AgentConfig[] = [
|
||||
{
|
||||
id: DEFAULT_AGENT_ID,
|
||||
name: defaultName,
|
||||
baseUrl,
|
||||
apiKey: defaultKey,
|
||||
// The placeholder name "Agent" is not something to listen for: the default agent answers
|
||||
// to a name only once the owner has given it one (or an alias).
|
||||
wakeWords: wakeWords('HERMEVEN_AGENT_WAKE', env.HERMEVEN_AGENT_WAKE, env.HERMEVEN_AGENT_NAME ? defaultName : ''),
|
||||
},
|
||||
];
|
||||
const ids = (env.HERMEVEN_AGENTS ?? '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
for (const id of ids) {
|
||||
if (!AGENT_ID.test(id)) throw new ConfigError('HERMEVEN_AGENTS entries must be lower-case ids (letters, digits, - and _)');
|
||||
if (agents.some((a) => a.id === id)) throw new ConfigError(`HERMEVEN_AGENTS names "${id}" more than once (or uses the reserved id "default")`);
|
||||
const prefix = `HERMEVEN_AGENT_${id.toUpperCase().replace(/-/g, '_')}`;
|
||||
const apiKey = env[`${prefix}_API_KEY`] || '';
|
||||
if (!apiKey) throw new ConfigError(`${prefix}_API_KEY is required: Hermes gives each profile its own API key`);
|
||||
const profile = env[`${prefix}_PROFILE`] || id;
|
||||
if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(profile)) throw new ConfigError(`${prefix}_PROFILE is not a valid profile name`);
|
||||
const name = agentName(`${prefix}_NAME`, env[`${prefix}_NAME`], id.charAt(0).toUpperCase() + id.slice(1));
|
||||
agents.push({ id, name, baseUrl: `${baseUrl}/p/${profile}`, apiKey, wakeWords: wakeWords(`${prefix}_WAKE`, env[`${prefix}_WAKE`], name) });
|
||||
}
|
||||
const claimed = new Map<string, string>();
|
||||
for (const agent of agents) {
|
||||
for (const word of agent.wakeWords) {
|
||||
const other = claimed.get(word);
|
||||
if (other) throw new ConfigError(`Agents "${other}" and "${agent.id}" would both answer to "${word}". Give one a different name or alias.`);
|
||||
claimed.set(word, agent.id);
|
||||
}
|
||||
}
|
||||
if (agents.length > 16) throw new ConfigError('HERMEVEN_AGENTS lists too many agents (at most 15 besides the default)');
|
||||
return agents;
|
||||
}
|
||||
|
||||
export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
|
||||
const host = env.HERMEVEN_HOST || '127.0.0.1';
|
||||
const allowNonLoopback = bool(env, 'HERMEVEN_ALLOW_NON_LOOPBACK');
|
||||
@@ -140,13 +241,30 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
|
||||
|
||||
const hermesKey = env.HERMES_API_KEY || '';
|
||||
if (!hermesKey) throw new ConfigError('HERMES_API_KEY is required (the Hermes API server refuses to start without one)');
|
||||
const hermesBaseUrl = httpUrl('HERMES_BASE_URL', env.HERMES_BASE_URL || 'http://127.0.0.1:8642').replace(/\/+$/, '');
|
||||
|
||||
const allowedOrigins = (env.HERMEVEN_ALLOWED_ORIGINS || '')
|
||||
const originEntries = (env.HERMEVEN_ALLOWED_ORIGINS || '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
// The one permitted wildcard: any port on a loopback address, over plain http, written
|
||||
// exactly as `http://127.0.0.1:*`, `http://localhost:*` or `http://[::1]:*`. A loopback
|
||||
// origin can only be a page served on the same device as the browser making the request.
|
||||
// No other wildcard exists: not for hosts, not for schemes, not for non-loopback ports.
|
||||
const allowedLoopbackAnyPort: string[] = [];
|
||||
const allowedOrigins: string[] = [];
|
||||
for (const entry of originEntries) {
|
||||
const anyPort = /^http:\/\/(127\.0\.0\.1|localhost|\[::1\]):\*$/.exec(entry);
|
||||
if (anyPort) allowedLoopbackAnyPort.push(anyPort[1]!);
|
||||
else allowedOrigins.push(entry);
|
||||
}
|
||||
for (const origin of allowedOrigins) {
|
||||
if (origin === '*' ) throw new ConfigError('HERMEVEN_ALLOWED_ORIGINS must list exact origins, not *');
|
||||
if (origin.includes('*')) {
|
||||
throw new ConfigError(
|
||||
'HERMEVEN_ALLOWED_ORIGINS must list exact origins. The only wildcard accepted is the port of a ' +
|
||||
'loopback address, written http://127.0.0.1:* (or localhost, or [::1]).',
|
||||
);
|
||||
}
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(origin);
|
||||
@@ -180,16 +298,18 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
|
||||
port: int(env, 'HERMEVEN_PORT', 8787, 0, 65535),
|
||||
dbPath: env.HERMEVEN_DB_PATH || './data/hermeven.sqlite',
|
||||
allowedOrigins,
|
||||
allowedLoopbackAnyPort,
|
||||
allowNonLoopback,
|
||||
trustProxy: bool(env, 'HERMEVEN_TRUST_PROXY'),
|
||||
hermes: {
|
||||
baseUrl: httpUrl('HERMES_BASE_URL', env.HERMES_BASE_URL || 'http://127.0.0.1:8642'),
|
||||
baseUrl: hermesBaseUrl,
|
||||
apiKey: hermesKey,
|
||||
profileLabel: env.HERMES_PROFILE_LABEL || 'default',
|
||||
instructions: env.HERMEVEN_INSTRUCTIONS === undefined ? DEFAULT_INSTRUCTIONS : env.HERMEVEN_INSTRUCTIONS,
|
||||
pollIntervalMs: int(env, 'HERMES_POLL_INTERVAL_MS', 150, 20, 10_000),
|
||||
requestTimeoutMs: int(env, 'HERMES_REQUEST_TIMEOUT_MS', 10_000, 50, 120_000),
|
||||
},
|
||||
agents: agentsFromEnv(env, hermesBaseUrl, hermesKey),
|
||||
stt: {
|
||||
provider: sttProvider,
|
||||
baseUrl: sttBaseUrl,
|
||||
@@ -208,6 +328,8 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
|
||||
// One extra second of headroom over the capture cap for frame alignment.
|
||||
audioMaxBytes: (captureMaxSeconds + 1) * AUDIO_FORMAT.bytesPerSecond,
|
||||
turnsPerMinute: int(env, 'HERMEVEN_TURNS_PER_MINUTE', 20, 1, 600),
|
||||
wakeChecksPerMinute: int(env, 'HERMEVEN_WAKE_CHECKS_PER_MINUTE', 30, 1, 600),
|
||||
previewsPerMinute: int(env, 'HERMEVEN_PREVIEWS_PER_MINUTE', 60, 1, 600),
|
||||
pairingAttemptsPerMinute: int(env, 'HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE', 5, 1, 60),
|
||||
},
|
||||
credentials: {
|
||||
|
||||
@@ -71,6 +71,11 @@ const MIGRATIONS: string[] = [
|
||||
`
|
||||
ALTER TABLE turns ADD COLUMN agent_deadline_at INTEGER;
|
||||
`,
|
||||
// v3: a conversation belongs to one configured agent. NULL means the default agent, which is
|
||||
// what every conversation created before this was.
|
||||
`
|
||||
ALTER TABLE conversations ADD COLUMN agent_id TEXT;
|
||||
`,
|
||||
];
|
||||
|
||||
/** The database holds credential hashes and, briefly, question and answer text. */
|
||||
|
||||
@@ -4,25 +4,30 @@ import {
|
||||
AUDIO_FORMAT,
|
||||
AudioTurnQuery,
|
||||
check,
|
||||
AgentsResponse,
|
||||
ConversationCreateRequest,
|
||||
httpStatusFor,
|
||||
isRetryable,
|
||||
PairingClaimRequest,
|
||||
SCHEMA_VERSION,
|
||||
TextTurnRequest,
|
||||
WakeQuery,
|
||||
type ConversationResponse,
|
||||
type DeviceCredential,
|
||||
type DeviceStatusResponse,
|
||||
type ErrorCode,
|
||||
type ErrorResponse,
|
||||
type Limits,
|
||||
type TranscribeResponse,
|
||||
type WakeResponse,
|
||||
} from '@hermeven/contracts';
|
||||
import type { BridgeConfig } from './config.ts';
|
||||
import { DEFAULT_AGENT_ID, type BridgeConfig } from './config.ts';
|
||||
import type { DeviceRow, Devices } from './devices.ts';
|
||||
import type { HermesAdapter } from './hermes/adapter.ts';
|
||||
import { RateLimiter } from './ratelimit.ts';
|
||||
import type { SttAdapter } from './stt/adapter.ts';
|
||||
import type { TurnEngine } from './turns.ts';
|
||||
import { matchWake } from './wake.ts';
|
||||
|
||||
export interface ServerDeps {
|
||||
config: BridgeConfig;
|
||||
@@ -64,6 +69,24 @@ export function effectiveLimits(config: BridgeConfig): Limits {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a browser page at `origin` may read this bridge's responses.
|
||||
* Exact matches against the configured list; otherwise, if a loopback host was configured with
|
||||
* `:*`, an `http://<that host>:<port>` origin with a numeric port. Nothing else, and never a
|
||||
* missing or `null` origin.
|
||||
*/
|
||||
export function isAllowedOrigin(config: Pick<BridgeConfig, 'allowedOrigins' | 'allowedLoopbackAnyPort'>, origin: string | undefined): boolean {
|
||||
if (!origin || origin === 'null') return false;
|
||||
if (config.allowedOrigins.includes(origin)) return true;
|
||||
if (config.allowedLoopbackAnyPort.length === 0) return false;
|
||||
// Matched as text, start to end, so look-alikes such as http://127.0.0.1.example.com:80 or
|
||||
// http://127.0.0.1:80@example.com cannot pass.
|
||||
const match = /^http:\/\/(127\.0\.0\.1|localhost|\[::1\]):(\d{1,5})$/.exec(origin);
|
||||
if (!match) return false;
|
||||
const port = Number(match[2]);
|
||||
return port >= 1 && port <= 65535 && config.allowedLoopbackAnyPort.includes(match[1]!);
|
||||
}
|
||||
|
||||
export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
||||
const { config, devices, engine } = deps;
|
||||
const app = Fastify({
|
||||
@@ -78,10 +101,11 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
||||
genReqId: () => crypto.randomUUID(),
|
||||
});
|
||||
|
||||
// Exact-origin CORS. CORS only tells browsers who may read answers; every route
|
||||
// except /healthz and the pairing claim still requires a device credential.
|
||||
// CORS: exact origins, plus (only if configured) any port on a loopback address.
|
||||
// CORS only tells browsers who may read answers; every route except /healthz and the
|
||||
// pairing claim still requires a device credential.
|
||||
await app.register(cors, {
|
||||
origin: config.allowedOrigins.length ? config.allowedOrigins : false,
|
||||
origin: (origin, callback) => callback(null, isAllowedOrigin(config, origin)),
|
||||
methods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
|
||||
allowedHeaders: ['Authorization', 'Content-Type'],
|
||||
credentials: false,
|
||||
@@ -122,6 +146,24 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
||||
const pairingLimiter = new RateLimiter(config.limits.pairingAttemptsPerMinute, 60_000);
|
||||
const turnLimiter = new RateLimiter(config.limits.turnsPerMinute, 60_000);
|
||||
const readLimiter = new RateLimiter(600, 60_000);
|
||||
const wakeLimiter = new RateLimiter(config.limits.wakeChecksPerMinute, 60_000);
|
||||
/** Devices with a wake check being transcribed: one at a time each. */
|
||||
const wakeBusy = new Set<string>();
|
||||
const previewLimiter = new RateLimiter(config.limits.previewsPerMinute, 60_000);
|
||||
const previewBusy = new Set<string>();
|
||||
|
||||
/** The checks shared by the two routes that take a clip of audio and create nothing. */
|
||||
function audioClip(req: FastifyRequest): { pcm: Buffer; locale: string } {
|
||||
const contentType = String(req.headers['content-type'] ?? '').split(';')[0]!.trim().toLowerCase();
|
||||
if (contentType !== 'application/octet-stream') throw new ApiError('unsupported_media', 'Unsupported content type.');
|
||||
const query = req.query as Record<string, unknown>;
|
||||
requireVersion(query.schema_version);
|
||||
if (!check(WakeQuery, query)) throw new ApiError('invalid_request', 'Malformed request.');
|
||||
const pcm = req.body as Buffer;
|
||||
if (!Buffer.isBuffer(pcm) || pcm.length === 0) throw new ApiError('invalid_request', 'Audio body is empty.');
|
||||
if (pcm.length % 2 !== 0) throw new ApiError('invalid_request', 'Audio is not whole 16-bit samples.');
|
||||
return { pcm, locale: query.locale };
|
||||
}
|
||||
|
||||
function authenticate(req: FastifyRequest): DeviceRow {
|
||||
const header = req.headers.authorization ?? '';
|
||||
@@ -199,6 +241,16 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* The agents this device may talk to, default first. Names only: no address, profile or key
|
||||
* ever leaves the bridge. A separate route (not a field on /v1/device) so that clients built
|
||||
* before it existed, which reject unknown fields, keep working.
|
||||
*/
|
||||
app.get('/v1/agents', async (req): Promise<AgentsResponse> => {
|
||||
authenticate(req);
|
||||
return { schema_version: SCHEMA_VERSION, agents: config.agents.map(({ id, name }) => ({ id, name })) };
|
||||
});
|
||||
|
||||
app.post('/v1/device/renew', async (req) => {
|
||||
const device = authenticate(req);
|
||||
const renewed = devices.renew(device.id);
|
||||
@@ -219,7 +271,10 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
||||
const body = req.body as Record<string, unknown> | undefined;
|
||||
requireVersion(body?.schema_version);
|
||||
if (!check(ConversationCreateRequest, body)) throw new ApiError('invalid_request', 'Malformed conversation request.');
|
||||
const conversation = engine.createConversation(device.id);
|
||||
const agentId = (body as { agent_id?: string }).agent_id ?? DEFAULT_AGENT_ID;
|
||||
// Only an agent the owner listed. The id is never used to build an address here.
|
||||
if (!engine.knowsAgent(agentId)) throw new ApiError('invalid_request', 'Unknown agent.');
|
||||
const conversation = engine.createConversation(device.id, agentId);
|
||||
reply.code(201);
|
||||
return { schema_version: SCHEMA_VERSION, conversation_id: conversation.id, created_at: iso(conversation.created_at) };
|
||||
});
|
||||
@@ -272,6 +327,74 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
||||
return engine.toResult(result.turn, result.replayed);
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------- wake
|
||||
/**
|
||||
* One stretch of speech heard while the app was open: does it begin with an agent's name?
|
||||
* Transcribed in memory and dropped. No turn, no row, nothing sent to any agent; a match only
|
||||
* tells the app who was addressed and what was said after the name, and the app then asks in
|
||||
* the ordinary way. Speech that was not for an agent is not returned and never logged.
|
||||
*/
|
||||
app.post('/v1/wake', async (req): Promise<WakeResponse> => {
|
||||
const device = authenticate(req);
|
||||
const { pcm, locale } = audioClip(req);
|
||||
// Nobody can be called by voice (no speech-to-text, or no agent with a usable name): the
|
||||
// app is told so once and stops sending audio.
|
||||
if (!deps.stt.configured || !config.agents.some((a) => a.wakeWords.length > 0)) throw new ApiError('not_found', 'Not found.');
|
||||
if (wakeBusy.has(device.id) || !wakeLimiter.take(device.id)) throw new ApiError('rate_limited', 'Too many requests. Wait a moment.');
|
||||
|
||||
const none: WakeResponse = { schema_version: SCHEMA_VERSION, matched: false, agent_id: null, text: '', near_miss: null };
|
||||
wakeBusy.add(device.id);
|
||||
const abort = new AbortController();
|
||||
const timer = setTimeout(() => abort.abort(), config.limits.transcribeDeadlineSeconds * 1000);
|
||||
try {
|
||||
const transcript = await deps.stt.transcribe({ pcm, locale, signal: abort.signal });
|
||||
const match = matchWake(transcript, config.agents);
|
||||
if (!match.matched) return { ...none, near_miss: match.nearMiss };
|
||||
req.log.info({ device_id: device.id, agent_id: match.agentId, name_only: match.text === '' }, 'wake.matched');
|
||||
return { ...none, matched: true, agent_id: match.agentId, text: match.text.slice(0, config.limits.textMaxChars) };
|
||||
} catch (err) {
|
||||
// A failed transcription is "nothing was addressed to anyone": there is no request to fail.
|
||||
req.log.warn({ device_id: device.id, err_name: err instanceof Error ? err.name : 'unknown' }, 'wake.transcription_failed');
|
||||
return none;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
wakeBusy.delete(device.id);
|
||||
}
|
||||
});
|
||||
|
||||
// ----------------------------------------------------------------- preview
|
||||
/**
|
||||
* The words in a recording that is still being made, for showing on the glasses while the
|
||||
* user speaks. Transcribed in memory and dropped: no turn, no row, nothing sent to any agent,
|
||||
* and the text is never logged. The question that is finally sent is transcribed by its own
|
||||
* turn, so a preview can never become what the agent receives.
|
||||
*/
|
||||
app.post('/v1/transcribe', async (req, reply): Promise<TranscribeResponse> => {
|
||||
const device = authenticate(req);
|
||||
const { pcm, locale } = audioClip(req);
|
||||
if (!deps.stt.configured) throw new ApiError('not_found', 'Not found.');
|
||||
if (previewBusy.has(device.id) || !previewLimiter.take(device.id)) throw new ApiError('rate_limited', 'Too many requests. Wait a moment.');
|
||||
previewBusy.add(device.id);
|
||||
const abort = new AbortController();
|
||||
const timer = setTimeout(() => abort.abort(), config.limits.transcribeDeadlineSeconds * 1000);
|
||||
// The app has stopped waiting (the recording was sent or cancelled): stop too, so the real
|
||||
// transcription is not kept waiting behind a preview nobody will see.
|
||||
reply.raw.on('close', () => {
|
||||
if (!reply.raw.writableEnded) abort.abort();
|
||||
});
|
||||
try {
|
||||
const text = await deps.stt.transcribe({ pcm, locale, signal: abort.signal });
|
||||
return { schema_version: SCHEMA_VERSION, text: text.trim().slice(0, config.limits.textMaxChars) };
|
||||
} catch (err) {
|
||||
// No preview this time. The recording itself is unaffected.
|
||||
req.log.warn({ device_id: device.id, err_name: err instanceof Error ? err.name : 'unknown' }, 'preview.transcription_failed');
|
||||
return { schema_version: SCHEMA_VERSION, text: '' };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
previewBusy.delete(device.id);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/v1/turns/:requestId', async (req) => {
|
||||
const device = authenticate(req);
|
||||
const { requestId } = req.params as { requestId: string };
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
type TurnResult,
|
||||
type TurnState,
|
||||
} from '@hermeven/contracts';
|
||||
import type { BridgeConfig } from './config.ts';
|
||||
import { DEFAULT_AGENT_ID, type BridgeConfig } from './config.ts';
|
||||
import type { Db } from './db.ts';
|
||||
import type { Devices } from './devices.ts';
|
||||
import {
|
||||
@@ -53,6 +53,8 @@ export interface ConversationRow {
|
||||
hermes_session_id: string;
|
||||
created_at: number;
|
||||
closed_at: number | null;
|
||||
/** The configured agent this conversation is with. NULL = the default agent. */
|
||||
agent_id: string | null;
|
||||
}
|
||||
|
||||
export interface EngineTiming {
|
||||
@@ -123,6 +125,8 @@ export class TurnEngine {
|
||||
config: BridgeConfig;
|
||||
devices: Devices;
|
||||
hermes: HermesAdapter;
|
||||
/** Adapters for the other configured agents, by id. The default one is `hermes`. */
|
||||
agents?: ReadonlyMap<string, HermesAdapter>;
|
||||
stt: SttAdapter;
|
||||
log: EngineLog;
|
||||
timing?: EngineTiming;
|
||||
@@ -138,8 +142,30 @@ export class TurnEngine {
|
||||
|
||||
// ------------------------------------------------------------ conversations
|
||||
|
||||
/** Start a fresh conversation for the device. Any earlier one is closed, not deleted. */
|
||||
createConversation(deviceId: string): ConversationRow {
|
||||
/** True when `agentId` names an agent this bridge is configured to reach. */
|
||||
knowsAgent(agentId: string): boolean {
|
||||
return agentId === DEFAULT_AGENT_ID || this.deps.agents?.has(agentId) === true;
|
||||
}
|
||||
|
||||
/** The Hermes adapter for a conversation's agent, or undefined if it is no longer configured. */
|
||||
private adapterFor(agentId: string | null): HermesAdapter | undefined {
|
||||
if (agentId === null || agentId === DEFAULT_AGENT_ID) return this.deps.hermes;
|
||||
return this.deps.agents?.get(agentId);
|
||||
}
|
||||
|
||||
private adapterForTurn(row: TurnRow): HermesAdapter | undefined {
|
||||
const conversation = this.deps.db.prepare('SELECT agent_id FROM conversations WHERE id = ?').get(row.conversation_id) as
|
||||
| { agent_id: string | null }
|
||||
| undefined;
|
||||
return conversation ? this.adapterFor(conversation.agent_id) : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a fresh conversation for the device with one agent. Any earlier conversation with
|
||||
* THAT agent is closed, not deleted; conversations with other agents are left open.
|
||||
*/
|
||||
createConversation(deviceId: string, agentId: string = DEFAULT_AGENT_ID): ConversationRow {
|
||||
const stored = agentId === DEFAULT_AGENT_ID ? null : agentId;
|
||||
const now = this.now();
|
||||
const row: ConversationRow = {
|
||||
id: randomUUID(),
|
||||
@@ -147,20 +173,25 @@ export class TurnEngine {
|
||||
hermes_session_id: `hermeven-${randomUUID()}`,
|
||||
created_at: now,
|
||||
closed_at: null,
|
||||
agent_id: stored,
|
||||
};
|
||||
this.deps.db.transaction(() => {
|
||||
this.deps.db.prepare('UPDATE conversations SET closed_at = ? WHERE device_id = ? AND closed_at IS NULL').run(now, deviceId);
|
||||
this.deps.db
|
||||
.prepare('INSERT INTO conversations (id, device_id, hermes_session_id, created_at) VALUES (@id, @device_id, @hermes_session_id, @created_at)')
|
||||
.prepare('UPDATE conversations SET closed_at = ? WHERE device_id = ? AND closed_at IS NULL AND agent_id IS ?')
|
||||
.run(now, deviceId, stored);
|
||||
this.deps.db
|
||||
.prepare(
|
||||
'INSERT INTO conversations (id, device_id, hermes_session_id, created_at, agent_id) VALUES (@id, @device_id, @hermes_session_id, @created_at, @agent_id)',
|
||||
)
|
||||
.run(row);
|
||||
})();
|
||||
this.deps.log.info({ device_id: deviceId, conversation_id: row.id }, 'conversation.created');
|
||||
this.deps.log.info({ device_id: deviceId, conversation_id: row.id, agent_id: agentId }, 'conversation.created');
|
||||
return row;
|
||||
}
|
||||
|
||||
activeConversation(deviceId: string): ConversationRow | undefined {
|
||||
return this.deps.db
|
||||
.prepare('SELECT * FROM conversations WHERE device_id = ? AND closed_at IS NULL ORDER BY created_at DESC LIMIT 1')
|
||||
.prepare('SELECT * FROM conversations WHERE device_id = ? AND closed_at IS NULL AND agent_id IS NULL ORDER BY created_at DESC LIMIT 1')
|
||||
.get(deviceId) as ConversationRow | undefined;
|
||||
}
|
||||
|
||||
@@ -477,13 +508,22 @@ export class TurnEngine {
|
||||
}
|
||||
|
||||
row = this.row(requestId)!;
|
||||
const hermes = this.adapterForTurn(row);
|
||||
if (!hermes) {
|
||||
// The conversation's agent was removed from the configuration. If anything may already
|
||||
// have been sent (a recovered turn), the outcome cannot be known from here.
|
||||
this.deps.log.warn({ request_id: requestId }, 'turn.agent_not_configured');
|
||||
if (recovered && (row.hermes_run_id || row.pending_body)) this.finish(requestId, 'unknown', { code: 'outcome_unknown' });
|
||||
else this.finish(requestId, 'failed', { code: 'agent_unreachable' });
|
||||
return;
|
||||
}
|
||||
if (!row.hermes_run_id) {
|
||||
// A recovered turn may already have been sent by the previous process.
|
||||
const runId = await this.submitToHermes(requestId, active, recovered);
|
||||
const runId = await this.submitToHermes(requestId, active, recovered, hermes);
|
||||
if (runId === null) return;
|
||||
this.update(requestId, { hermes_run_id: runId, pending_body: null });
|
||||
}
|
||||
await this.poll(requestId, active);
|
||||
await this.poll(requestId, active, hermes);
|
||||
}
|
||||
|
||||
private async transcribe(requestId: string, pcm: Buffer, active: ActiveTurn, locale: string): Promise<string | null> {
|
||||
@@ -519,7 +559,7 @@ export class TurnEngine {
|
||||
}
|
||||
|
||||
/** Returns the run id, or null when the turn was settled here. */
|
||||
private async submitToHermes(requestId: string, active: ActiveTurn, maybeAlreadySent: boolean): Promise<string | null> {
|
||||
private async submitToHermes(requestId: string, active: ActiveTurn, maybeAlreadySent: boolean, hermes: HermesAdapter): Promise<string | null> {
|
||||
const row = this.row(requestId)!;
|
||||
const deadline = row.agent_deadline_at ?? (row.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs;
|
||||
let ambiguous = maybeAlreadySent;
|
||||
@@ -528,7 +568,7 @@ export class TurnEngine {
|
||||
for (;;) {
|
||||
if (this.stopping) return null;
|
||||
try {
|
||||
const { runId } = await this.deps.hermes.submit({
|
||||
const { runId } = await hermes.submit({
|
||||
idempotencyKey: row.hermes_idempotency_key,
|
||||
body: row.pending_body!,
|
||||
});
|
||||
@@ -565,7 +605,7 @@ export class TurnEngine {
|
||||
}
|
||||
}
|
||||
|
||||
private async poll(requestId: string, active: ActiveTurn): Promise<void> {
|
||||
private async poll(requestId: string, active: ActiveTurn, hermes: HermesAdapter): Promise<void> {
|
||||
const start = this.row(requestId)!;
|
||||
const runId = start.hermes_run_id!;
|
||||
// Both clocks come from the database, so a bridge restart resumes them where they were:
|
||||
@@ -592,7 +632,7 @@ export class TurnEngine {
|
||||
}
|
||||
if (stopReason && !stopAccepted) {
|
||||
try {
|
||||
await this.deps.hermes.stop(runId);
|
||||
await hermes.stop(runId);
|
||||
stopAccepted = true;
|
||||
} catch (err) {
|
||||
if (!(err instanceof HermesUnavailableError)) throw err;
|
||||
@@ -601,7 +641,7 @@ export class TurnEngine {
|
||||
|
||||
let status: RunStatus | null = null;
|
||||
try {
|
||||
status = await this.deps.hermes.status(runId);
|
||||
status = await hermes.status(runId);
|
||||
} catch (err) {
|
||||
if (!(err instanceof HermesUnavailableError)) throw err;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Wake names: deciding whether something that was said is addressed to an agent.
|
||||
*
|
||||
* The glasses app listens all the time it is open and sends each stretch of speech here. Most
|
||||
* of it is not for an agent at all, so the rule is deliberately strict: the agent's name must
|
||||
* be the FIRST thing said (an optional "hey"/"ok" aside). A name in the middle of a sentence
|
||||
* never counts. A match is exact, against the name or an alias the owner configured; a
|
||||
* near-miss is reported as such and never acted on, because an agent can do things and a
|
||||
* misheard word must not start it.
|
||||
*/
|
||||
export interface WakeAgent {
|
||||
id: string;
|
||||
/** Lower-case words or short phrases, each already normalised with `wakeTokens`. */
|
||||
wakeWords: string[];
|
||||
}
|
||||
|
||||
export type WakeMatch =
|
||||
| { matched: true; agentId: string; text: string }
|
||||
| { matched: false; nearMiss: string | null };
|
||||
|
||||
const GREETINGS = new Set(['hey', 'hi', 'ok', 'okay', 'yo', 'hello']);
|
||||
const WORD = /[\p{L}\p{N}]+(?:['’][\p{L}]+)*/gu;
|
||||
|
||||
/** The words of a phrase, lower-case, without punctuation. */
|
||||
export function wakeTokens(phrase: string): string[] {
|
||||
return (phrase.normalize('NFC').toLowerCase().match(WORD) ?? []).map((w) => w.replace(/’/g, "'"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The wake words an agent answers to: the first word of its display name, plus any aliases.
|
||||
* A first word that is not at least three letters is not usable as a wake word.
|
||||
*/
|
||||
export function wakeWordsFor(name: string, aliases: string[]): string[] {
|
||||
const out: string[] = [];
|
||||
const first = wakeTokens(name)[0];
|
||||
if (first && /^\p{L}{3,}$/u.test(first)) out.push(first);
|
||||
for (const alias of aliases) {
|
||||
const phrase = wakeTokens(alias).join(' ');
|
||||
if (phrase && !out.includes(phrase)) out.push(phrase);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function distance(a: string, b: string): number {
|
||||
let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
|
||||
for (let i = 1; i <= a.length; i++) {
|
||||
const row = [i];
|
||||
for (let j = 1; j <= b.length; j++) {
|
||||
row[j] = Math.min(prev[j]! + 1, row[j - 1]! + 1, prev[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1));
|
||||
}
|
||||
prev = row;
|
||||
}
|
||||
return prev[b.length]!;
|
||||
}
|
||||
|
||||
export function matchWake(transcript: string, agents: WakeAgent[]): WakeMatch {
|
||||
const text = transcript.normalize('NFC');
|
||||
const words = [...text.matchAll(WORD)].map((m) => ({ word: m[0].toLowerCase().replace(/’/g, "'"), end: m.index + m[0].length }));
|
||||
// Anything before the first word other than space and punctuation (a bracketed sound
|
||||
// description, say) is still "before the first word": only words are compared.
|
||||
let start = 0;
|
||||
if (words.length > 1 && GREETINGS.has(words[0]!.word)) start = 1;
|
||||
if (words.length <= start) return { matched: false, nearMiss: null };
|
||||
|
||||
// Longest phrase first, so an alias of two words wins over a one-word name that begins it.
|
||||
const candidates = agents
|
||||
.flatMap((agent) => agent.wakeWords.map((phrase) => ({ agentId: agent.id, tokens: phrase.split(' ') })))
|
||||
.sort((a, b) => b.tokens.length - a.tokens.length);
|
||||
for (const candidate of candidates) {
|
||||
const { tokens } = candidate;
|
||||
if (words.length - start < tokens.length) continue;
|
||||
if (!tokens.every((token, i) => words[start + i]!.word === token)) continue;
|
||||
const rest = text
|
||||
.slice(words[start + tokens.length - 1]!.end)
|
||||
.replace(/^[\s,.:;!?…\-–—"'’”]+/u, '')
|
||||
.trim();
|
||||
return { matched: true, agentId: candidate.agentId, text: rest ? rest.charAt(0).toUpperCase() + rest.slice(1) : '' };
|
||||
}
|
||||
|
||||
const first = words[start]!.word;
|
||||
for (const candidate of candidates) {
|
||||
if (candidate.tokens.length !== 1) continue;
|
||||
const name = candidate.tokens[0]!;
|
||||
const allowed = name.length >= 6 ? 2 : name.length >= 4 ? 1 : 0;
|
||||
if (allowed > 0 && Math.abs(first.length - name.length) <= allowed && distance(first, name) <= allowed) {
|
||||
return { matched: false, nearMiss: first.slice(0, 24) };
|
||||
}
|
||||
}
|
||||
return { matched: false, nearMiss: null };
|
||||
}
|
||||
@@ -39,6 +39,28 @@ describe('configuration', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('the only origin wildcard is the port of a loopback address over http', () => {
|
||||
const c = loadConfig({ ...base, HERMEVEN_ALLOWED_ORIGINS: 'https://a.example, http://127.0.0.1:*' });
|
||||
expect(c.allowedOrigins).toEqual(['https://a.example']);
|
||||
expect(c.allowedLoopbackAnyPort).toEqual(['127.0.0.1']);
|
||||
expect(loadConfig(base).allowedLoopbackAnyPort).toEqual([]);
|
||||
for (const bad of [
|
||||
'*',
|
||||
'http://*',
|
||||
'http://*:8080',
|
||||
'https://127.0.0.1:*', // https wildcard not offered
|
||||
'http://192.168.1.20:*', // LAN
|
||||
'http://10.0.0.5:*',
|
||||
'http://example.com:*',
|
||||
'https://*.example.com',
|
||||
'http://127.0.0.1:*/', // trailing slash: not the exact form
|
||||
'http://127.0.0.2:*',
|
||||
'http://127.0.0.1.example.com:*',
|
||||
]) {
|
||||
expect(() => loadConfig({ ...base, HERMEVEN_ALLOWED_ORIGINS: bad }), bad).toThrow(ConfigError);
|
||||
}
|
||||
});
|
||||
|
||||
it('derives the audio byte cap from the capture cap and never puts secrets in error text', () => {
|
||||
const config = loadConfig({ ...base, HERMEVEN_CAPTURE_MAX_SECONDS: '10' });
|
||||
expect(config.limits.audioMaxBytes).toBe(11 * 32000);
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { ConfigError, loadConfig } from '../src/config.ts';
|
||||
import { matchWake, wakeWordsFor } from '../src/wake.ts';
|
||||
|
||||
const agents = [
|
||||
{ id: 'default', wakeWords: ['pepper'] },
|
||||
{ id: 'wendy', wakeWords: ['wendy'] },
|
||||
{ id: 'cody', wakeWords: ['cody', 'kody', 'code e'] },
|
||||
];
|
||||
|
||||
describe('wake names', () => {
|
||||
it('a name said first addresses that agent, and what follows is the question', () => {
|
||||
expect(matchWake(' Wendy, what is on my calendar?', agents)).toEqual({ matched: true, agentId: 'wendy', text: 'What is on my calendar?' });
|
||||
expect(matchWake('Pepper. Send Dan a message.', agents)).toEqual({ matched: true, agentId: 'default', text: 'Send Dan a message.' });
|
||||
expect(matchWake('cody are the tests passing', agents)).toEqual({ matched: true, agentId: 'cody', text: 'Are the tests passing' });
|
||||
});
|
||||
|
||||
it('a greeting before the name is allowed, and nothing else is', () => {
|
||||
expect(matchWake('Hey Wendy, hello', agents)).toMatchObject({ matched: true, agentId: 'wendy', text: 'Hello' });
|
||||
expect(matchWake('OK, Pepper: lights off', agents)).toMatchObject({ matched: true, agentId: 'default', text: 'Lights off' });
|
||||
expect(matchWake('So Wendy, hello', agents).matched).toBe(false);
|
||||
expect(matchWake('Hey', agents).matched).toBe(false);
|
||||
});
|
||||
|
||||
it('the name alone matches with an empty question', () => {
|
||||
expect(matchWake('Wendy.', agents)).toEqual({ matched: true, agentId: 'wendy', text: '' });
|
||||
expect(matchWake('Hey Cody!', agents)).toEqual({ matched: true, agentId: 'cody', text: '' });
|
||||
});
|
||||
|
||||
it('a name anywhere but first never matches', () => {
|
||||
for (const said of ['I told Wendy about it', 'ask Pepper later', 'is that Cody', '', ' ', '[BLANK_AUDIO]', '(wind blowing)']) {
|
||||
expect(matchWake(said, agents).matched, said).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('aliases match, including one of two words, and the longest wins', () => {
|
||||
expect(matchWake('Kody, status', agents)).toMatchObject({ matched: true, agentId: 'cody', text: 'Status' });
|
||||
expect(matchWake('Code E, status', agents)).toMatchObject({ matched: true, agentId: 'cody', text: 'Status' });
|
||||
});
|
||||
|
||||
it('a word that is only close to a name is reported as a near miss and does not match', () => {
|
||||
expect(matchWake('Wendi, what time is it', agents)).toEqual({ matched: false, nearMiss: 'wendi' });
|
||||
expect(matchWake('Copy that', agents)).toEqual({ matched: false, nearMiss: 'copy' });
|
||||
expect(matchWake('Paper is on the desk', agents)).toEqual({ matched: false, nearMiss: 'paper' });
|
||||
expect(matchWake('Wednesday works', agents)).toEqual({ matched: false, nearMiss: null });
|
||||
});
|
||||
|
||||
it('wake words come from the first word of the name plus aliases', () => {
|
||||
expect(wakeWordsFor('Cody R.', ['Kody', ' code-e '])).toEqual(['cody', 'kody', 'code e']);
|
||||
expect(wakeWordsFor('R2', [])).toEqual([]);
|
||||
expect(wakeWordsFor('', ['Friday'])).toEqual(['friday']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('wake names in configuration', () => {
|
||||
const base = { HERMES_API_KEY: 'k'.repeat(24), STT_PROVIDER: 'none' };
|
||||
|
||||
it('each agent answers to its name; the unnamed default agent answers to nothing', () => {
|
||||
const config = loadConfig({ ...base, HERMEVEN_AGENTS: 'wendy', HERMEVEN_AGENT_WENDY_API_KEY: 'w'.repeat(24), HERMEVEN_AGENT_WENDY_WAKE: 'wendi, windy' });
|
||||
expect(config.agents.map((a) => a.wakeWords)).toEqual([[], ['wendy', 'wendi', 'windy']]);
|
||||
expect(loadConfig({ ...base, HERMEVEN_AGENT_NAME: 'Pepper' }).agents[0]!.wakeWords).toEqual(['pepper']);
|
||||
expect(loadConfig({ ...base, HERMEVEN_AGENT_WAKE: 'friday' }).agents[0]!.wakeWords).toEqual(['friday']);
|
||||
});
|
||||
|
||||
it('two agents may not answer to the same word', () => {
|
||||
expect(() =>
|
||||
loadConfig({ ...base, HERMEVEN_AGENT_NAME: 'Pepper', HERMEVEN_AGENTS: 'wendy', HERMEVEN_AGENT_WENDY_API_KEY: 'w'.repeat(24), HERMEVEN_AGENT_WENDY_WAKE: 'pepper' }),
|
||||
).toThrow(ConfigError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
# Disposable Ubuntu 24.04 host with systemd as PID 1, for proving docs/deploy-droplet.md.
|
||||
# Only the operating system and systemd are prepared here. Everything the guide tells the
|
||||
# operator to install (Caddy, git, Node.js, Hermeven) is installed by the proof script.
|
||||
FROM ubuntu:24.04
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
RUN apt-get update -qq && apt-get install -y -qq systemd systemd-sysv dbus >/dev/null && apt-get clean
|
||||
STOPSIGNAL SIGRTMIN+3
|
||||
CMD ["/sbin/init"]
|
||||
Executable
+93
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env bash
|
||||
# Proves the server-side steps of docs/deploy-droplet.md on a disposable Ubuntu 24.04 host
|
||||
# (a privileged Docker container running systemd). Opt-in: needs Docker and network access.
|
||||
#
|
||||
# tests/deploy/runbook-proof.sh
|
||||
#
|
||||
# It deploys the CURRENT COMMIT (HEAD), from an empty /opt/hermeven, by running the commands
|
||||
# the guide gives. Hermes is not present in the container, so the bridge starts with the agent
|
||||
# unreachable; that is expected and is not what this proves.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "${BASH_SOURCE[0]}")/../.."
|
||||
NAME=hermeven-runbook-proof
|
||||
IMAGE=hermeven-runbook-host:24.04
|
||||
SHA=$(git rev-parse HEAD)
|
||||
[ -z "$(git status --porcelain)" ] || { echo "Commit or stash changes first: the proof deploys HEAD." >&2; exit 1; }
|
||||
|
||||
cleanup() { docker rm -f "$NAME" >/dev/null 2>&1 || true; rm -f "$BUNDLE"; }
|
||||
BUNDLE=$(mktemp --suffix=.bundle)
|
||||
trap cleanup EXIT
|
||||
docker rm -f "$NAME" >/dev/null 2>&1 || true
|
||||
|
||||
echo "### host image"
|
||||
docker build -q -t "$IMAGE" tests/deploy >/dev/null
|
||||
docker run -d --name "$NAME" --privileged --cgroupns=host -v /sys/fs/cgroup:/sys/fs/cgroup:rw --tmpfs /run --tmpfs /run/lock "$IMAGE" >/dev/null
|
||||
for _ in $(seq 1 30); do docker exec "$NAME" systemctl is-system-running 2>/dev/null | grep -qE 'running|degraded' && break; sleep 1; done
|
||||
in_host() { docker exec -i "$NAME" bash -euo pipefail -c "$1"; }
|
||||
in_host '. /etc/os-release; echo "$PRETTY_NAME"; test ! -e /opt/hermeven && echo "/opt/hermeven does not exist"; id hermeven 2>&1 | head -1 || true'
|
||||
|
||||
echo "### step 2: packages (Caddy, git, Node.js with checksum)"
|
||||
in_host 'export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update -qq >/dev/null && apt-get install -y -qq caddy git curl xz-utils ca-certificates build-essential python3 >/dev/null 2>&1
|
||||
V=$(curl -fsSL https://nodejs.org/dist/latest-v22.x/SHASUMS256.txt | grep -oE "v22\.[0-9]+\.[0-9]+" | head -1)
|
||||
cd /tmp && curl -fsSLO https://nodejs.org/dist/$V/node-$V-linux-x64.tar.xz
|
||||
curl -fsSL https://nodejs.org/dist/$V/SHASUMS256.txt | grep " node-$V-linux-x64.tar.xz\$" | sha256sum -c -
|
||||
mkdir -p /opt/node-$V && tar -xJf node-$V-linux-x64.tar.xz -C /opt/node-$V --strip-components=1
|
||||
ln -sfn /opt/node-$V /opt/node && /opt/node/bin/node -v
|
||||
caddy version | head -1'
|
||||
|
||||
echo "### step 3: get the release onto the server (git clone of $SHA)"
|
||||
git bundle create "$BUNDLE" HEAD >/dev/null 2>&1
|
||||
docker cp "$BUNDLE" "$NAME":/root/release.bundle
|
||||
in_host "git clone -q /root/release.bundle /root/hermeven-src 2>/dev/null && git -C /root/hermeven-src checkout -q $SHA && git -C /root/hermeven-src rev-parse HEAD"
|
||||
|
||||
echo "### step 4: deploy/install.sh"
|
||||
in_host '/root/hermeven-src/deploy/install.sh --bridge-url https://localhost >/tmp/install.log 2>&1 || { echo "install.sh FAILED:"; tail -25 /tmp/install.log; exit 1; }; grep -E "^==>|^Installed|^Phone page|^Not started" /tmp/install.log'
|
||||
|
||||
echo "### ownership and permissions after install"
|
||||
in_host 'echo "DEPLOYED_SHA: $(cat /opt/hermeven/app/DEPLOYED_SHA)"
|
||||
echo "app tree owner: $(stat -c "%U:%G %a" /opt/hermeven/app)"
|
||||
echo "not root-owned in app: $(find /opt/hermeven/app ! -user root | wc -l) group/other-writable in app: $(find /opt/hermeven/app -perm /022 ! -type l | wc -l)"
|
||||
echo "node_modules present: $(test -d /opt/hermeven/app/node_modules && echo yes)"
|
||||
runuser -u hermeven -- test -w /opt/hermeven/app && echo "hermeven CAN write app (BAD)" || echo "hermeven cannot write the app tree"
|
||||
runuser -u hermeven -- sh -c "touch /opt/hermeven/app/services/bridge/src/x 2>/dev/null" && echo "hermeven CAN create files in src (BAD)" || echo "hermeven cannot create files in the source"
|
||||
echo "www: $(stat -c "%U:%G %a" /opt/hermeven/www) index $(stat -c "%U %a" /opt/hermeven/www/index.html) files=$(find /opt/hermeven/www -type f | wc -l)"
|
||||
runuser -u hermeven -- test -w /opt/hermeven/www && echo "hermeven CAN write www (BAD)" || echo "hermeven cannot write www"
|
||||
runuser -u caddy -- test -r /opt/hermeven/www/index.html && echo "caddy can read www"
|
||||
echo "state dir: $(stat -c "%U:%G %a" /var/lib/hermeven)"
|
||||
echo "secrets dir entries: $(ls -A /etc/hermeven | wc -l) (install.sh wrote none)"
|
||||
echo "models dir: $(test -e /opt/hermeven/models && echo exists || echo "not created by install.sh")"'
|
||||
|
||||
echo "### steps 5, 6: configuration and speech model"
|
||||
in_host 'install -m 0600 -o hermeven -g hermeven /opt/hermeven/app/deploy/bridge.env.example /etc/hermeven/bridge.env
|
||||
sed -i "s/^HERMES_API_KEY=.*/HERMES_API_KEY=proof-run-not-a-real-key/" /etc/hermeven/bridge.env
|
||||
stat -c "%U:%G %a %n" /etc/hermeven/bridge.env
|
||||
cd /opt/hermeven/app/services/bridge
|
||||
HERMEVEN_ENV_FILE=/etc/hermeven/bridge.env /opt/node/bin/node --import tsx src/cli.ts fetch-model | tail -1
|
||||
HERMEVEN_ENV_FILE=/etc/hermeven/bridge.env /opt/node/bin/node --import tsx src/cli.ts verify-model | tail -1
|
||||
echo "models owner: $(stat -c "%U:%G" /opt/hermeven/models)"'
|
||||
|
||||
echo "### step 8: start the bridge under systemd"
|
||||
in_host 'systemd-analyze verify /etc/systemd/system/hermeven-bridge.service && echo "systemd-analyze verify: ok"
|
||||
systemctl enable --now hermeven-bridge 2>/dev/null
|
||||
for _ in $(seq 1 60); do journalctl -u hermeven-bridge --no-pager 2>/dev/null | grep -q "stt.ready\|stt.load_failed" && break; sleep 1; done
|
||||
echo "unit: $(systemctl is-active hermeven-bridge) (running as $(systemctl show hermeven-bridge -p User --value), MainPID uid $(stat -c %U /proc/$(systemctl show hermeven-bridge -p MainPID --value)))"
|
||||
journalctl -u hermeven-bridge --no-pager | grep -oE "\"msg\":\"(Server listening[^\"]*|stt\.[a-z_]+)\"|\"reason\":\"[a-z]+\"" | tr "\n" " "; echo
|
||||
echo "healthz (direct): $(curl -sS -m 5 http://127.0.0.1:8787/healthz)"
|
||||
echo "state files: $(stat -c "%a" /var/lib/hermeven) $(stat -c "%U %a %n" /var/lib/hermeven/* | tr "\n" ";")"'
|
||||
|
||||
echo "### step 9: HTTPS through Caddy (hostname replaced by localhost; certificate from Caddy's local CA)"
|
||||
in_host 'caddy fmt --diff /opt/hermeven/app/deploy/Caddyfile.example >/tmp/fmt.diff 2>&1; echo "caddy fmt --diff on the example: exit $?, $(grep -cE "^[-+]" /tmp/fmt.diff || true) changed line(s)"
|
||||
sed "s/^bridge\.example\.com {/localhost {/" /opt/hermeven/app/deploy/Caddyfile.example > /etc/caddy/Caddyfile
|
||||
caddy validate --config /etc/caddy/Caddyfile 2>&1 | tail -1
|
||||
systemctl restart caddy; sleep 4; echo "caddy: $(systemctl is-active caddy)"
|
||||
ASSET=$(curl -sSk https://localhost/ | grep -oE "assets/index-[A-Za-z0-9_-]+\.js" | head -1)
|
||||
echo "GET / -> $(curl -sSk -o /dev/null -w "%{http_code} %{content_type}" https://localhost/)"
|
||||
echo "GET /$ASSET -> $(curl -sSk -o /dev/null -w "%{http_code} %{content_type} %{size_download} bytes" https://localhost/$ASSET)"
|
||||
echo "GET /healthz -> $(curl -sSk https://localhost/healthz)"
|
||||
echo "GET /v1/device -> $(curl -sSk -o /dev/null -w "%{http_code}" https://localhost/v1/device) (no credential)"
|
||||
echo "headers on /:"; curl -sSkI https://localhost/ | grep -iE "^(strict-transport-security|x-content-type-options|referrer-policy|server):" | sed "s/^/ /"
|
||||
echo "headers on the asset:"; curl -sSkI https://localhost/$ASSET | grep -iE "^(strict-transport-security|x-content-type-options|referrer-policy|server):" | sed "s/^/ /"
|
||||
echo "bridge address built into the page: $(grep -c "https://localhost" /opt/hermeven/www/$ASSET) occurrence(s) of https://localhost"
|
||||
echo "CORS for a foreign origin: $(curl -sSkI -H "Origin: https://evil.example" https://localhost/v1/device | grep -ci "^access-control-allow-origin" || true) allow-origin header(s)"'
|
||||
echo "### done: $SHA"
|
||||
@@ -51,6 +51,28 @@ export class FakeDevice implements DevicePort {
|
||||
async requestExit(): Promise<void> {
|
||||
this.exitRequests += 1;
|
||||
}
|
||||
/** Times the app asked to leave the glasses by itself, and times that was confirmed. */
|
||||
exitAttempts = 0;
|
||||
exits = 0;
|
||||
/** Scripted answers for the next exit attempts (`false` = refused); then it succeeds. */
|
||||
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>();
|
||||
onLaunchSource(listener: (source: 'appMenu' | 'glassesMenu') => void): () => void {
|
||||
this.launchListeners.add(listener);
|
||||
if (this.launched) listener(this.launched);
|
||||
return () => this.launchListeners.delete(listener);
|
||||
}
|
||||
launchedFrom(source: 'appMenu' | 'glassesMenu'): void {
|
||||
this.launched = source;
|
||||
for (const l of this.launchListeners) l(source);
|
||||
}
|
||||
/** Set to make storage writes report "not confirmed" without writing. */
|
||||
storageWritesFail = false;
|
||||
storageReadsFail = false;
|
||||
@@ -70,12 +92,19 @@ export class FakeDevice implements DevicePort {
|
||||
}
|
||||
tap = () => this.emit({ type: 'tap' });
|
||||
doubleTap = () => this.emit({ type: 'double_tap' });
|
||||
longPress = () => this.emit({ type: 'long_press' });
|
||||
longPressRelease = () => this.emit({ type: 'long_press_release' });
|
||||
swipeDown = () => this.emit({ type: 'swipe_down' });
|
||||
swipeUp = () => this.emit({ type: 'swipe_up' });
|
||||
menu = (itemId: number) => this.emit({ type: 'menu', itemId });
|
||||
connection(connected: boolean): void {
|
||||
for (const l of this.connectionListeners) l(connected);
|
||||
}
|
||||
/** Frames of digital silence, delivered like `speak`. Only while the mic is open. */
|
||||
silence(seconds: number): void {
|
||||
const frames = Math.round(seconds * 10);
|
||||
for (let i = 0; i < frames && this.micOpen; i++) this.emit({ type: 'audio', pcm: new Uint8Array(3200) });
|
||||
}
|
||||
/** Deliver audio the way the SDK documents it: 100 ms frames of 3,200 bytes. Only while the mic is open. */
|
||||
speak(seconds: number): void {
|
||||
const frames = Math.round(seconds * 10);
|
||||
|
||||
@@ -16,6 +16,8 @@ export interface FakeRun {
|
||||
body: string;
|
||||
sessionId: string;
|
||||
input: string;
|
||||
/** The profile the run was submitted under (null = default). Invisible from any other. */
|
||||
profile: string | null;
|
||||
status: string;
|
||||
output: string;
|
||||
extra: Record<string, unknown>;
|
||||
@@ -40,7 +42,12 @@ export class FakeHermes {
|
||||
private readonly byKey = new Map<string, FakeRun>();
|
||||
/** session id -> inputs seen, to prove follow-ups land in the same session. */
|
||||
readonly sessions = new Map<string, string[]>();
|
||||
readonly requests: Array<{ method: string; path: string; idempotencyKey?: string }> = [];
|
||||
readonly requests: Array<{ method: string; path: string; idempotencyKey?: string; profile?: string | null }> = [];
|
||||
/** Named profiles served under `/p/<name>`, each with its own key. */
|
||||
readonly profiles = new Map<string, string>();
|
||||
/** Which profile each executed run belonged to (null = default), in order. */
|
||||
readonly executedBy: Array<string | null> = [];
|
||||
|
||||
private script: Script[] = [];
|
||||
private defaultScript: Script = { kind: 'complete' };
|
||||
/** Faults applied to upcoming POST /v1/runs calls, in order. */
|
||||
@@ -108,12 +115,24 @@ export class FakeHermes {
|
||||
|
||||
private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
const url = new URL(req.url ?? '/', 'http://x');
|
||||
const path = url.pathname;
|
||||
let path = url.pathname;
|
||||
// Like a gateway with multiplex_profiles: `/p/<profile>/...` selects a named profile, which
|
||||
// has its OWN key; the default's key is refused there, and an unserved profile is a 404.
|
||||
let profile: string | null = null;
|
||||
let expectedKey = this.apiKey;
|
||||
const prefixed = /^\/p\/([^/]+)(\/.*)$/.exec(path);
|
||||
if (prefixed) {
|
||||
profile = prefixed[1]!;
|
||||
path = prefixed[2]!;
|
||||
const profileKey = this.profiles.get(profile);
|
||||
if (profileKey === undefined) return this.json(res, 404, { error: { message: 'Unknown profile' } });
|
||||
expectedKey = profileKey;
|
||||
}
|
||||
const key = req.headers['idempotency-key'];
|
||||
this.requests.push({ method: req.method ?? '', path, idempotencyKey: typeof key === 'string' ? key : undefined });
|
||||
this.requests.push({ method: req.method ?? '', path, idempotencyKey: typeof key === 'string' ? key : undefined, profile });
|
||||
|
||||
if (path === '/health') return this.json(res, 200, { status: 'ok' });
|
||||
if (req.headers.authorization !== `Bearer ${this.apiKey}`) {
|
||||
if (req.headers.authorization !== `Bearer ${expectedKey}`) {
|
||||
return this.json(res, 401, { error: { message: 'Invalid API key', code: 'invalid_api_key' } });
|
||||
}
|
||||
|
||||
@@ -121,11 +140,12 @@ export class FakeHermes {
|
||||
for await (const chunk of req) chunks.push(chunk as Buffer);
|
||||
const raw = Buffer.concat(chunks).toString('utf8');
|
||||
|
||||
if (req.method === 'POST' && path === '/v1/runs') return this.submit(req, res, raw);
|
||||
if (req.method === 'POST' && path === '/v1/runs') return this.submit(req, res, raw, profile);
|
||||
|
||||
const match = /^\/v1\/runs\/([^/]+)(\/stop)?$/.exec(path);
|
||||
if (match) {
|
||||
const run = this.runs.get(decodeURIComponent(match[1]!));
|
||||
const found = this.runs.get(decodeURIComponent(match[1]!));
|
||||
const run = found && found.profile === profile ? found : undefined;
|
||||
if (req.method === 'GET' && !match[2]) {
|
||||
if (this.statusDown) return this.json(res, 503, { error: { message: 'storage_unavailable' } });
|
||||
if (!run) return this.json(res, 404, { error: { message: 'Run not found', code: 'run_not_found' } });
|
||||
@@ -158,8 +178,10 @@ export class FakeHermes {
|
||||
this.json(res, 404, { error: { message: 'not found' } });
|
||||
}
|
||||
|
||||
private submit(req: IncomingMessage, res: ServerResponse, raw: string): void {
|
||||
private submit(req: IncomingMessage, res: ServerResponse, raw: string, runProfile: string | null): void {
|
||||
// Keys are scoped to the profile, as in Hermes: the same key under another profile is a different run.
|
||||
const key = String(req.headers['idempotency-key'] ?? '');
|
||||
const scopedKey = key && `${runProfile ?? ''}|${key}`;
|
||||
const fault = this.submitFaults.shift();
|
||||
if (fault === 'http_503') return this.json(res, 503, { error: { message: 'runtime_draining' } }, { 'Retry-After': '1' });
|
||||
if (fault === 'http_400') return this.json(res, 400, { error: { message: "Missing 'input' field" } });
|
||||
@@ -172,7 +194,7 @@ export class FakeHermes {
|
||||
}
|
||||
if (!body.input) return this.json(res, 400, { error: { message: "Missing 'input' field" } });
|
||||
|
||||
const existing = key ? this.byKey.get(key) : undefined;
|
||||
const existing = scopedKey ? this.byKey.get(scopedKey) : undefined;
|
||||
let run: FakeRun;
|
||||
let replayed = false;
|
||||
if (existing) {
|
||||
@@ -191,6 +213,7 @@ export class FakeHermes {
|
||||
body: raw,
|
||||
sessionId,
|
||||
input: body.input,
|
||||
profile: runProfile,
|
||||
status: 'running',
|
||||
output: '',
|
||||
extra: {},
|
||||
@@ -198,9 +221,10 @@ export class FakeHermes {
|
||||
timer: null,
|
||||
};
|
||||
this.runs.set(run.runId, run);
|
||||
if (key) this.byKey.set(key, run);
|
||||
if (scopedKey) this.byKey.set(scopedKey, run);
|
||||
// The turn "executes" exactly once, at admission.
|
||||
this.executions += 1;
|
||||
this.executedBy.push(runProfile);
|
||||
const history = this.sessions.get(sessionId) ?? [];
|
||||
this.sessions.set(sessionId, history);
|
||||
const script = this.script.shift() ?? this.defaultScript;
|
||||
|
||||
@@ -0,0 +1,617 @@
|
||||
import { measureTextWrap } from '@evenrealities/pretext';
|
||||
import { SCHEMA_VERSION } from '@hermeven/contracts';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { Controller, type Snapshot } from '../../apps/even-client/src/core/controller.ts';
|
||||
import { BridgeClient } from '../../apps/even-client/src/net/bridgeClient.ts';
|
||||
import { ConfigError, loadConfig } from '../../services/bridge/src/config.ts';
|
||||
import { FakeDevice } from '../fakes/fakeDevice.ts';
|
||||
import { createHarness, type Harness } from './harness.ts';
|
||||
|
||||
/**
|
||||
* More than one agent behind one bridge. The bridge is real; Hermes is the TEST FAKE, which
|
||||
* imitates a gateway with multiplexed profiles: `/p/<profile>/...`, each profile with its own
|
||||
* key, runs invisible from any other profile. No real Hermes, no glasses.
|
||||
*/
|
||||
const WENDY_KEY = 'wendy-profile-key-0123456789';
|
||||
const CODY_KEY = 'cody-profile-key-0123456789';
|
||||
const AGENT_ENV = {
|
||||
HERMEVEN_AGENT_NAME: 'Pepper',
|
||||
HERMEVEN_AGENTS: 'wendy,cody',
|
||||
HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY,
|
||||
HERMEVEN_AGENT_CODY_API_KEY: CODY_KEY,
|
||||
HERMEVEN_AGENT_CODY_NAME: 'Cody R.',
|
||||
};
|
||||
|
||||
let h: Harness;
|
||||
|
||||
async function agentsHarness(env: Record<string, string> = AGENT_ENV): Promise<void> {
|
||||
h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2', ...env } });
|
||||
h.hermes.profiles.set('wendy', WENDY_KEY);
|
||||
h.hermes.profiles.set('cody', CODY_KEY);
|
||||
}
|
||||
const newConversation = (token: string, agentId?: string) =>
|
||||
h.api('POST', '/v1/conversations', { token, json: agentId === undefined ? { schema_version: SCHEMA_VERSION } : { schema_version: SCHEMA_VERSION, agent_id: agentId } });
|
||||
const runsPosted = () => h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs');
|
||||
|
||||
afterEach(async () => {
|
||||
await h?.close();
|
||||
});
|
||||
|
||||
describe('bridge: the agent list', () => {
|
||||
it('lists the configured agents, default first, by id and name only', async () => {
|
||||
await agentsHarness();
|
||||
const { token } = await h.pair();
|
||||
const res = await h.api('GET', '/v1/agents', { token });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({
|
||||
schema_version: SCHEMA_VERSION,
|
||||
agents: [
|
||||
{ id: 'default', name: 'Pepper' },
|
||||
{ id: 'wendy', name: 'Wendy' },
|
||||
{ id: 'cody', name: 'Cody R.' },
|
||||
],
|
||||
});
|
||||
const raw = JSON.stringify(res.body);
|
||||
for (const secret of [WENDY_KEY, CODY_KEY, h.hermes.apiKey, '/p/', h.hermes.url]) expect(raw).not.toContain(secret);
|
||||
});
|
||||
|
||||
it('needs a device credential', async () => {
|
||||
await agentsHarness();
|
||||
expect((await h.api('GET', '/v1/agents')).status).toBe(401);
|
||||
expect((await h.api('GET', '/v1/agents', { token: 'x'.repeat(40) })).status).toBe(401);
|
||||
});
|
||||
|
||||
it('with no extra agents configured there is exactly one, and nothing else changes', async () => {
|
||||
h = await createHarness();
|
||||
const { token } = await h.pair();
|
||||
const res = await h.api('GET', '/v1/agents', { token });
|
||||
expect(res.body.agents).toEqual([{ id: 'default', name: 'Agent' }]);
|
||||
const conversation = await h.conversation(token);
|
||||
const turn = await h.textTurn(token, conversation, 'hello');
|
||||
await h.waitTerminal(token, turn.body.request_id);
|
||||
expect(h.hermes.executedBy).toEqual([null]);
|
||||
});
|
||||
|
||||
it('/v1/device is unchanged, so a client built before agents (which rejects unknown fields) keeps working', async () => {
|
||||
await agentsHarness();
|
||||
const { token } = await h.pair();
|
||||
const res = await h.api('GET', '/v1/device', { token });
|
||||
expect(Object.keys(res.body).sort()).toEqual(
|
||||
['active_conversation_id', 'agent_reachable', 'audio_format', 'device_id', 'device_name', 'limits', 'pairing_expires_at', 'schema_version', 'stt_configured', 'token_expires_at'].sort(),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('bridge: a turn goes to the agent its conversation belongs to', () => {
|
||||
beforeEach(() => agentsHarness());
|
||||
|
||||
it('a conversation with Wendy is submitted and polled at her address with her key, and answered', async () => {
|
||||
const { token } = await h.pair();
|
||||
const created = await newConversation(token, 'wendy');
|
||||
expect(created.status).toBe(201);
|
||||
const turn = await h.textTurn(token, created.body.conversation_id, 'hello wendy');
|
||||
const done = await h.waitTerminal(token, turn.body.request_id);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(done.answer_text).toContain('hello wendy');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy']);
|
||||
// Every request about that run went through her prefix (the fake hides it from any other).
|
||||
const about = h.hermes.requests.filter((r) => r.path.startsWith('/v1/runs'));
|
||||
expect(about.length).toBeGreaterThan(1);
|
||||
expect(about.every((r) => r.profile === 'wendy')).toBe(true);
|
||||
});
|
||||
|
||||
it('no agent named, or "default", goes to the default agent', async () => {
|
||||
const { token } = await h.pair();
|
||||
const a = await h.conversation(token);
|
||||
const t1 = await h.textTurn(token, a, 'one');
|
||||
await h.waitTerminal(token, t1.body.request_id);
|
||||
const b = await newConversation(token, 'default');
|
||||
const t2 = await h.textTurn(token, b.body.conversation_id, 'two');
|
||||
await h.waitTerminal(token, t2.body.request_id);
|
||||
expect(h.hermes.executedBy).toEqual([null, null]);
|
||||
});
|
||||
|
||||
it('an agent that is not on the list is refused, and nothing reaches Hermes', async () => {
|
||||
const { token } = await h.pair();
|
||||
for (const bad of ['natalie', 'jeanette', 'nosuch']) {
|
||||
const res = await newConversation(token, bad);
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
}
|
||||
for (const malformed of ['../wendy', 'wendy/v1', 'Wendy', '', 'p/wendy', 'a'.repeat(40)]) {
|
||||
expect((await newConversation(token, malformed)).status).toBe(400);
|
||||
}
|
||||
expect(h.hermes.requests.filter((r) => r.path !== '/health')).toEqual([]);
|
||||
expect(h.bridge.db.prepare('SELECT COUNT(*) AS n FROM conversations').get()).toEqual({ n: 0 });
|
||||
});
|
||||
|
||||
it('each agent has its own conversation: starting one with Wendy does not close Pepper\'s', async () => {
|
||||
const { token } = await h.pair();
|
||||
const pepper = await h.conversation(token);
|
||||
const wendy1 = (await newConversation(token, 'wendy')).body.conversation_id as string;
|
||||
const t1 = await h.textTurn(token, pepper, 'still open?');
|
||||
expect(t1.status).toBeLessThan(300);
|
||||
await h.waitTerminal(token, t1.body.request_id);
|
||||
// A NEW conversation with Wendy closes only her earlier one.
|
||||
const wendy2 = (await newConversation(token, 'wendy')).body.conversation_id as string;
|
||||
const closed = await h.textTurn(token, wendy1, 'old thread');
|
||||
expect(closed.body.error.code).toBe('conversation_closed');
|
||||
const t2 = await h.textTurn(token, wendy2, 'new thread');
|
||||
await h.waitTerminal(token, t2.body.request_id);
|
||||
const t3 = await h.textTurn(token, pepper, 'and pepper again');
|
||||
const done = await h.waitTerminal(token, t3.body.request_id);
|
||||
expect(done.answer_text).toContain('turn=2'); // Pepper's conversation kept its history
|
||||
expect(h.hermes.executedBy).toEqual([null, 'wendy', null]);
|
||||
expect(h.hermes.sessions.size).toBe(2);
|
||||
});
|
||||
|
||||
it('a lost reply from Hermes is retried at the same agent under the same key: one execution', async () => {
|
||||
const { token } = await h.pair();
|
||||
const wendy = (await newConversation(token, 'wendy')).body.conversation_id as string;
|
||||
h.hermes.failNextSubmit('drop_response');
|
||||
const turn = await h.textTurn(token, wendy, 'do it once');
|
||||
const done = await h.waitTerminal(token, turn.body.request_id);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
const posts = runsPosted();
|
||||
expect(posts.length).toBe(2);
|
||||
expect(new Set(posts.map((p) => p.idempotencyKey)).size).toBe(1);
|
||||
expect(posts.every((p) => p.profile === 'wendy')).toBe(true);
|
||||
});
|
||||
|
||||
it('a bridge restart mid-run re-attaches to the same run at the same agent: one execution', async () => {
|
||||
const { token } = await h.pair();
|
||||
const cody = (await newConversation(token, 'cody')).body.conversation_id as string;
|
||||
h.hermes.next({ kind: 'complete', afterMs: 400, output: 'reviewed' });
|
||||
const turn = await h.textTurn(token, cody, 'review this');
|
||||
await h.waitState(token, turn.body.request_id, 'thinking');
|
||||
await h.restartBridge();
|
||||
const done = await h.waitTerminal(token, turn.body.request_id, 5000);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(done.answer_text).toBe('reviewed');
|
||||
expect(h.hermes.executedBy).toEqual(['cody']);
|
||||
expect(runsPosted().length).toBe(1);
|
||||
});
|
||||
|
||||
it('keys never appear in the bridge log', async () => {
|
||||
const { token } = await h.pair();
|
||||
const wendy = (await newConversation(token, 'wendy')).body.conversation_id as string;
|
||||
const turn = await h.textTurn(token, wendy, 'hello');
|
||||
await h.waitTerminal(token, turn.body.request_id);
|
||||
const log = h.logs.join('');
|
||||
expect(log).toContain('conversation.created');
|
||||
for (const secret of [WENDY_KEY, CODY_KEY, h.hermes.apiKey]) expect(log).not.toContain(secret);
|
||||
});
|
||||
});
|
||||
|
||||
describe('bridge: when an agent cannot be used', () => {
|
||||
it('a wrong key for one agent fails that turn as "nothing ran" and leaves the others working', async () => {
|
||||
await agentsHarness({ ...AGENT_ENV, HERMEVEN_AGENT_WENDY_API_KEY: 'not-her-key-0123456789' });
|
||||
const { token } = await h.pair();
|
||||
const wendy = (await newConversation(token, 'wendy')).body.conversation_id as string;
|
||||
const t1 = await h.textTurn(token, wendy, 'hello');
|
||||
const failed = await h.waitTerminal(token, t1.body.request_id);
|
||||
expect(failed.outcome).toBe('failed');
|
||||
expect(failed.error?.code).toBe('agent_rejected');
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
const pepper = await h.conversation(token);
|
||||
const t2 = await h.textTurn(token, pepper, 'hello');
|
||||
expect((await h.waitTerminal(token, t2.body.request_id)).outcome).toBe('succeeded');
|
||||
});
|
||||
|
||||
it("the default agent's key is refused at another agent's address (the reason each needs its own)", async () => {
|
||||
await agentsHarness({ ...AGENT_ENV, HERMEVEN_AGENT_WENDY_API_KEY: 'fake-hermes-key' });
|
||||
const { token } = await h.pair();
|
||||
const wendy = (await newConversation(token, 'wendy')).body.conversation_id as string;
|
||||
const turn = await h.textTurn(token, wendy, 'hello');
|
||||
expect((await h.waitTerminal(token, turn.body.request_id)).error?.code).toBe('agent_rejected');
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
});
|
||||
|
||||
it('an agent removed from the configuration: a turn in flight ends as unknown after a restart, never resent elsewhere', async () => {
|
||||
await agentsHarness();
|
||||
const { token } = await h.pair();
|
||||
const wendy = (await newConversation(token, 'wendy')).body.conversation_id as string;
|
||||
h.hermes.next({ kind: 'complete', afterMs: 600, output: 'late' });
|
||||
const turn = await h.textTurn(token, wendy, 'in flight');
|
||||
await h.waitState(token, turn.body.request_id, 'thinking');
|
||||
// The owner takes Wendy off the list and restarts the bridge.
|
||||
(h.config.agents as unknown[]).splice(1, 1);
|
||||
await h.restartBridge();
|
||||
const done = await h.waitTerminal(token, turn.body.request_id, 5000);
|
||||
expect(done.outcome).toBe('unknown');
|
||||
expect(done.error?.code).toBe('outcome_unknown');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy']); // it ran once, at Wendy, and was not sent to anyone else
|
||||
expect((await newConversation(token, 'wendy')).status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('bridge configuration', () => {
|
||||
const base = { HERMES_API_KEY: 'k'.repeat(20), HERMEVEN_ALLOWED_ORIGINS: 'https://app.example', STT_PROVIDER: 'none' };
|
||||
it('builds each extra agent as a profile under the same gateway', () => {
|
||||
const config = loadConfig({ ...base, HERMES_BASE_URL: 'http://127.0.0.1:8642/', ...AGENT_ENV, HERMEVEN_AGENT_CODY_PROFILE: 'cody-review' });
|
||||
expect(config.agents.map((a) => [a.id, a.name, a.baseUrl])).toEqual([
|
||||
['default', 'Pepper', 'http://127.0.0.1:8642'],
|
||||
['wendy', 'Wendy', 'http://127.0.0.1:8642/p/wendy'],
|
||||
['cody', 'Cody R.', 'http://127.0.0.1:8642/p/cody-review'],
|
||||
]);
|
||||
expect(config.agents[1]!.apiKey).toBe(WENDY_KEY);
|
||||
});
|
||||
it('refuses a missing key, a repeated or reserved id, a malformed id, a bad profile and an over-long name', () => {
|
||||
const bad: Array<Record<string, string>> = [
|
||||
{ HERMEVEN_AGENTS: 'wendy' },
|
||||
{ HERMEVEN_AGENTS: 'wendy,wendy', HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY },
|
||||
{ HERMEVEN_AGENTS: 'default', HERMEVEN_AGENT_DEFAULT_API_KEY: WENDY_KEY },
|
||||
{ HERMEVEN_AGENTS: 'Wendy', HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY },
|
||||
{ HERMEVEN_AGENTS: '../x' },
|
||||
{ HERMEVEN_AGENTS: 'wendy', HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY, HERMEVEN_AGENT_WENDY_PROFILE: '../default' },
|
||||
{ HERMEVEN_AGENTS: 'wendy', HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY, HERMEVEN_AGENT_WENDY_NAME: 'x'.repeat(25) },
|
||||
];
|
||||
for (const env of bad) expect(() => loadConfig({ ...base, ...env }), JSON.stringify(env)).toThrow(ConfigError);
|
||||
});
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ client
|
||||
|
||||
let device: FakeDevice;
|
||||
let controller: Controller;
|
||||
let snapshot: Snapshot;
|
||||
let sent: Array<{ method: string; path: string; body: string }>;
|
||||
let agentsRoute: 'real' | 'not_found' | 'offline';
|
||||
let extras: Partial<ConstructorParameters<typeof Controller>[0]>;
|
||||
|
||||
function makeController(dev: FakeDevice): Controller {
|
||||
return new Controller({
|
||||
idleExit: null,
|
||||
...extras,
|
||||
device: dev,
|
||||
measure: (text, width) => measureTextWrap(text, width).lineCount,
|
||||
locale: 'en-US',
|
||||
pollIntervalMs: 20,
|
||||
submitAttempts: 3,
|
||||
submitRetryMs: 30,
|
||||
micStallMs: 300,
|
||||
makeClient: (baseUrl, token) =>
|
||||
new BridgeClient({
|
||||
baseUrl,
|
||||
token,
|
||||
timeoutMs: 500,
|
||||
fetchImpl: async (input, init) => {
|
||||
const path = new URL(String(input)).pathname;
|
||||
sent.push({ method: init?.method ?? 'GET', path, body: typeof init?.body === 'string' ? init.body : '' });
|
||||
if (path === '/v1/agents' && agentsRoute === 'offline') throw new TypeError('offline');
|
||||
if (path === '/v1/agents' && agentsRoute === 'not_found') {
|
||||
// What a bridge from before agent selection answers.
|
||||
return new Response(JSON.stringify({ schema_version: SCHEMA_VERSION, error: { code: 'not_found', message: 'Not found.', retryable: false } }), {
|
||||
status: 404,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
return fetch(input, init);
|
||||
},
|
||||
}),
|
||||
onChange: (s) => {
|
||||
snapshot = s;
|
||||
},
|
||||
});
|
||||
}
|
||||
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} hud=${JSON.stringify(device.frame)}`);
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
}
|
||||
}
|
||||
const phase = () => snapshot.state.phase;
|
||||
const quiet = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
async function paired(): Promise<void> {
|
||||
device = new FakeDevice();
|
||||
controller = makeController(device);
|
||||
await controller.start();
|
||||
await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2');
|
||||
expect(phase()).toBe('ready');
|
||||
}
|
||||
/** The page is closed and opened again: same phone storage, new everything else. */
|
||||
async function relaunch(): Promise<void> {
|
||||
await controller.stop();
|
||||
const reborn = new FakeDevice();
|
||||
for (const [k, v] of device.storage) reborn.storage.set(k, v);
|
||||
device = reborn;
|
||||
controller = makeController(device);
|
||||
await controller.start();
|
||||
}
|
||||
async function ask(text: string): Promise<void> {
|
||||
controller.askText(text);
|
||||
await until('answer', () => phase() === 'answer');
|
||||
}
|
||||
const backToReady = async () => {
|
||||
device.doubleTap();
|
||||
await until('ready', () => phase() === 'ready');
|
||||
};
|
||||
|
||||
describe('glasses: choosing an agent', () => {
|
||||
beforeEach(async () => {
|
||||
sent = [];
|
||||
agentsRoute = 'real';
|
||||
extras = {};
|
||||
await agentsHarness();
|
||||
});
|
||||
afterEach(async () => {
|
||||
await controller?.stop();
|
||||
});
|
||||
|
||||
it('opens on the default agent and shows its name; a swipe at Ready moves through the list and wraps', async () => {
|
||||
await paired();
|
||||
expect(device.frame.body).toBe('Pepper\n\nReady.');
|
||||
expect(device.frame.status).toContain('Swipe: agent');
|
||||
const seen: string[] = [];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
device.swipeDown();
|
||||
seen.push(device.frame.body.split('\n')[0]!);
|
||||
}
|
||||
expect(seen).toEqual(['Wendy', 'Cody R.', 'Pepper']);
|
||||
device.swipeUp();
|
||||
expect(device.frame.body).toBe('Cody R.\n\nReady.');
|
||||
device.swipeUp();
|
||||
expect(device.frame.body).toBe('Wendy\n\nReady.');
|
||||
// Choosing asks the bridge for nothing and sends nothing to any agent.
|
||||
expect(sent.filter((s) => s.path === '/v1/conversations' || s.path === '/v1/turns')).toEqual([]);
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
});
|
||||
|
||||
it('a question after choosing Wendy goes to Wendy, every screen says so, and a follow-up continues with her', async () => {
|
||||
await paired();
|
||||
device.swipeDown();
|
||||
h.hermes.next({ kind: 'complete', afterMs: 250 });
|
||||
controller.askText('what is on the calendar');
|
||||
await until('thinking', () => phase() === 'thinking');
|
||||
expect(device.frame.body).toBe('Wendy is thinking…');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(device.frame.status).toContain('Wendy · Tap: ask');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy']);
|
||||
await ask('and tomorrow');
|
||||
expect(device.frame.body).toContain('turn=2');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy', 'wendy']);
|
||||
expect(h.hermes.sessions.size).toBe(1);
|
||||
const creates = sent.filter((s) => s.path === '/v1/conversations');
|
||||
expect(creates.map((c) => JSON.parse(c.body).agent_id)).toEqual(['wendy']);
|
||||
});
|
||||
|
||||
it('spoken questions too: the recording goes to the chosen agent', async () => {
|
||||
await paired();
|
||||
device.swipeDown();
|
||||
device.swipeDown();
|
||||
device.tap();
|
||||
await until('listening', () => phase() === 'listening' && device.micOpen);
|
||||
expect(device.frame.body).toContain('Cody R. is listening…');
|
||||
device.speak(0.5);
|
||||
device.tap();
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(h.hermes.executedBy).toEqual(['cody']);
|
||||
});
|
||||
|
||||
it('each agent keeps its own conversation across switches', async () => {
|
||||
await paired();
|
||||
await ask('pepper one');
|
||||
await backToReady();
|
||||
device.swipeDown();
|
||||
await ask('wendy one');
|
||||
await backToReady();
|
||||
device.swipeUp();
|
||||
expect(device.frame.body).toBe('Pepper\n\nReady.');
|
||||
await ask('pepper two');
|
||||
expect(device.frame.body).toContain('turn=2');
|
||||
expect(device.frame.body).toContain('pepper one');
|
||||
await backToReady();
|
||||
device.swipeDown();
|
||||
await ask('wendy two');
|
||||
expect(device.frame.body).toContain('turn=2');
|
||||
expect(device.frame.body).toContain('wendy one');
|
||||
expect(h.hermes.executedBy).toEqual([null, 'wendy', null, 'wendy']);
|
||||
expect(h.hermes.sessions.size).toBe(2);
|
||||
expect(sent.filter((s) => s.path === '/v1/conversations').length).toBe(2);
|
||||
});
|
||||
|
||||
it('a swipe only chooses at Ready: on an answer it turns the page, and while busy it does nothing', async () => {
|
||||
await paired();
|
||||
device.swipeDown(); // Wendy
|
||||
h.hermes.next({ kind: 'complete', afterMs: 250, output: Array.from({ length: 80 }, (_, i) => `Sentence ${i + 1} of a long answer.`).join(' ') });
|
||||
controller.askText('long one');
|
||||
await until('thinking', () => phase() === 'thinking');
|
||||
device.swipeDown();
|
||||
device.swipeUp();
|
||||
expect(snapshot.state.agentId).toBe('wendy');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(snapshot.state.pageIndex).toBe(0);
|
||||
device.swipeDown();
|
||||
expect(snapshot.state.pageIndex).toBe(1);
|
||||
expect(snapshot.state.agentId).toBe('wendy');
|
||||
device.tap();
|
||||
await until('listening', () => phase() === 'listening' && device.micOpen);
|
||||
device.swipeDown();
|
||||
expect(snapshot.state.agentId).toBe('wendy');
|
||||
expect(phase()).toBe('listening');
|
||||
device.doubleTap();
|
||||
});
|
||||
|
||||
it('moving to another agent while a conversation is being created does not hand it to the wrong one', async () => {
|
||||
await paired();
|
||||
device.swipeDown(); // Wendy
|
||||
controller.askText('for wendy');
|
||||
device.swipeDown(); // ignored: no longer at Ready
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy']);
|
||||
await backToReady();
|
||||
device.swipeDown(); // Cody
|
||||
await ask('for cody');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy', 'cody']);
|
||||
expect(device.frame.body).toContain('turn=1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('glasses: which agent it reopens on', () => {
|
||||
beforeEach(async () => {
|
||||
sent = [];
|
||||
agentsRoute = 'real';
|
||||
extras = {};
|
||||
await agentsHarness();
|
||||
});
|
||||
afterEach(async () => {
|
||||
await controller?.stop();
|
||||
});
|
||||
|
||||
it('reopened soon after talking to Wendy: opens on Wendy, same conversation', async () => {
|
||||
await paired();
|
||||
device.swipeDown();
|
||||
await ask('wendy one');
|
||||
await until('saved', () => JSON.parse(device.storage.get('hermeven.v1')!).agentId === 'wendy' && typeof JSON.parse(device.storage.get('hermeven.v1')!).lastTurnAt === 'number');
|
||||
await relaunch();
|
||||
expect(device.frame.body).toBe('Wendy\n\nReady.');
|
||||
await ask('wendy two');
|
||||
expect(device.frame.body).toContain('turn=2');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy', 'wendy']);
|
||||
});
|
||||
|
||||
it('reopened after the conversation window: opens on the default agent, and Wendy starts fresh when chosen again', async () => {
|
||||
extras = { conversationGapMs: 60 };
|
||||
await paired();
|
||||
device.swipeDown();
|
||||
await ask('wendy one');
|
||||
await until('saved', () => typeof JSON.parse(device.storage.get('hermeven.v1')!).lastTurnAt === 'number');
|
||||
await quiet(130);
|
||||
await relaunch();
|
||||
expect(device.frame.body).toBe('Pepper\n\nReady.');
|
||||
await ask('pepper one');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy', null]);
|
||||
await backToReady();
|
||||
device.swipeDown();
|
||||
await ask('wendy again');
|
||||
expect(device.frame.body).toContain('turn=1'); // a new conversation with her
|
||||
expect(h.hermes.sessions.size).toBe(3);
|
||||
});
|
||||
|
||||
it('chosen but never asked: reopening goes back to the default agent', async () => {
|
||||
await paired();
|
||||
device.swipeDown();
|
||||
await until('saved', () => JSON.parse(device.storage.get('hermeven.v1')!).agentId === 'wendy');
|
||||
await relaunch();
|
||||
expect(device.frame.body).toBe('Pepper\n\nReady.');
|
||||
});
|
||||
|
||||
it('the last agent has been taken off the list: opens on the default agent', async () => {
|
||||
await paired();
|
||||
device.swipeDown();
|
||||
await ask('wendy one');
|
||||
await until('saved', () => typeof JSON.parse(device.storage.get('hermeven.v1')!).lastTurnAt === 'number');
|
||||
(h.config.agents as unknown[]).splice(1, 1);
|
||||
await h.restartBridge();
|
||||
// (same address is not guaranteed after a restart in this harness: re-point the stored URL)
|
||||
const stored = JSON.parse(device.storage.get('hermeven.v1')!);
|
||||
device.storage.set('hermeven.v1', JSON.stringify({ ...stored, bridgeUrl: h.url }));
|
||||
await relaunch();
|
||||
expect(device.frame.body).toBe('Pepper\n\nReady.');
|
||||
expect(snapshot.state.agents.map((a) => a.id)).toEqual(['default', 'cody']);
|
||||
});
|
||||
|
||||
it('CODY-021: removed while her question is in flight: the turn stays hers and settles honestly, then screen, state, storage and routing all move to the default', async () => {
|
||||
await paired();
|
||||
await ask('pepper one');
|
||||
await backToReady();
|
||||
device.swipeDown(); // Wendy
|
||||
h.hermes.next({ kind: 'hang' });
|
||||
controller.askText('wendy, do the thing');
|
||||
await until('in flight with Wendy', () => phase() === 'thinking' && h.hermes.executions === 2);
|
||||
const wendyRequest = snapshot.state.requestId!;
|
||||
await until('request id saved', () => JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId === wendyRequest);
|
||||
// The owner takes Wendy off the list and restarts the bridge; the page is reopened.
|
||||
(h.config.agents as unknown[]).splice(1, 1);
|
||||
await h.restartBridge();
|
||||
const before = JSON.parse(device.storage.get('hermeven.v1')!);
|
||||
device.storage.set('hermeven.v1', JSON.stringify({ ...before, bridgeUrl: h.url }));
|
||||
await relaunch();
|
||||
// Still her turn while it is unresolved: re-attached by id, not moved, not repeated.
|
||||
expect(snapshot.state.requestId ?? wendyRequest).toBe(wendyRequest);
|
||||
await until('her turn settled', () => phase() === 'error');
|
||||
expect(snapshot.state.error?.code).toBe('outcome_unknown');
|
||||
expect(h.hermes.executedBy).toEqual([null, 'wendy']);
|
||||
// The moment it settled, everything agrees on the default agent.
|
||||
expect(snapshot.state.agentId).toBe('default');
|
||||
await until('saved', () => JSON.parse(device.storage.get('hermeven.v1')!).agentId === 'default');
|
||||
await backToReady();
|
||||
expect(device.frame.body).toBe('Pepper\n\nReady.');
|
||||
expect(snapshot.state.agentId).toBe('default');
|
||||
// The next question goes to the default agent, in the DEFAULT agent's own conversation.
|
||||
await ask('pepper two');
|
||||
expect(device.frame.body).toContain('turn=2');
|
||||
expect(device.frame.body).toContain('pepper one');
|
||||
expect(h.hermes.executedBy).toEqual([null, 'wendy', null]);
|
||||
const posts = h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs');
|
||||
expect(posts.filter((p) => p.profile === 'wendy').length).toBe(1);
|
||||
expect(snapshot.state.conversationId).toBe(JSON.parse(device.storage.get('hermeven.v1')!).conversationId);
|
||||
});
|
||||
|
||||
it('CODY-021: the same when the question is asked straight from the removed agent\'s result screen, without going back to Ready', async () => {
|
||||
await paired();
|
||||
device.swipeDown(); // Wendy
|
||||
h.hermes.next({ kind: 'hang' });
|
||||
controller.askText('wendy, do the thing');
|
||||
await until('in flight with Wendy', () => phase() === 'thinking' && h.hermes.executions === 1);
|
||||
await until('request id saved', () => typeof JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId === 'string');
|
||||
(h.config.agents as unknown[]).splice(1, 1);
|
||||
await h.restartBridge();
|
||||
const before = JSON.parse(device.storage.get('hermeven.v1')!);
|
||||
device.storage.set('hermeven.v1', JSON.stringify({ ...before, bridgeUrl: h.url }));
|
||||
await relaunch();
|
||||
await until('her turn settled', () => phase() === 'error');
|
||||
await ask('straight on'); // from the error screen
|
||||
expect(h.hermes.executedBy).toEqual(['wendy', null]);
|
||||
expect(device.frame.body).toContain('turn=1');
|
||||
expect(sent.filter((s) => s.path === '/v1/conversations').map((c) => JSON.parse(c.body).agent_id)).toEqual(['wendy', 'default']);
|
||||
});
|
||||
|
||||
it('the bridge cannot be reached for the list at start: the last known list is used', async () => {
|
||||
await paired();
|
||||
device.swipeDown();
|
||||
await ask('wendy one');
|
||||
await until('saved', () => typeof JSON.parse(device.storage.get('hermeven.v1')!).lastTurnAt === 'number');
|
||||
agentsRoute = 'offline';
|
||||
await relaunch();
|
||||
expect(snapshot.state.agents.map((a) => a.id)).toEqual(['default', 'wendy', 'cody']);
|
||||
expect(device.frame.body).toBe('Wendy\n\nReady.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('glasses: with a bridge that offers no choice', () => {
|
||||
afterEach(async () => {
|
||||
await controller?.stop();
|
||||
});
|
||||
|
||||
it('a bridge with one agent: the screen is as before, a swipe at Ready does nothing, and no agent is named in requests', async () => {
|
||||
sent = [];
|
||||
agentsRoute = 'real';
|
||||
extras = {};
|
||||
h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2' } });
|
||||
await paired();
|
||||
expect(device.frame).toEqual({ body: 'Hermeven\n\nReady.', status: 'Tap: ask · Double-tap: exit' });
|
||||
device.swipeDown();
|
||||
device.swipeUp();
|
||||
expect(device.frame.body).toBe('Hermeven\n\nReady.');
|
||||
await ask('hello');
|
||||
expect(device.frame.status).toBe('Tap: ask');
|
||||
expect(sent.filter((s) => s.path === '/v1/conversations').map((c) => JSON.parse(c.body))).toEqual([{ schema_version: SCHEMA_VERSION }]);
|
||||
});
|
||||
|
||||
it('a bridge from before agent selection (no /v1/agents): the same, and it still answers', async () => {
|
||||
sent = [];
|
||||
agentsRoute = 'not_found';
|
||||
extras = {};
|
||||
await agentsHarness();
|
||||
await paired();
|
||||
expect(snapshot.state.agents).toEqual([]);
|
||||
expect(device.frame.body).toBe('Hermeven\n\nReady.');
|
||||
device.swipeDown();
|
||||
await ask('hello');
|
||||
expect(h.hermes.executedBy).toEqual([null]);
|
||||
expect(sent.filter((s) => s.path === '/v1/conversations').map((c) => JSON.parse(c.body))).toEqual([{ schema_version: SCHEMA_VERSION }]);
|
||||
});
|
||||
});
|
||||
@@ -118,6 +118,69 @@ describe('health, auth and binding', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('loopback any-port origins (the Even app serves an installed app from 127.0.0.1 on a new port each launch)', () => {
|
||||
const preflight = (origin: string) =>
|
||||
h.api('OPTIONS', '/v1/pairing/claim', {
|
||||
headers: { Origin: origin, 'Access-Control-Request-Method': 'POST', 'Access-Control-Request-Headers': 'content-type' },
|
||||
});
|
||||
const allowed = async (origin: string) => (await preflight(origin)).headers.get('access-control-allow-origin');
|
||||
|
||||
it('off by default: a loopback page on another port is not allowed', async () => {
|
||||
h = await createHarness({ env: { HERMEVEN_ALLOWED_ORIGINS: 'http://127.0.0.1:40315' } });
|
||||
expect(await allowed('http://127.0.0.1:40315')).toBe('http://127.0.0.1:40315');
|
||||
expect(await allowed('http://127.0.0.1:40316')).toBeNull();
|
||||
});
|
||||
|
||||
it('with http://127.0.0.1:* configured: any port on 127.0.0.1 is allowed and echoed exactly; nothing else is', async () => {
|
||||
h = await createHarness({ env: { HERMEVEN_ALLOWED_ORIGINS: 'https://app.example, http://127.0.0.1:*' } });
|
||||
for (const origin of ['http://127.0.0.1:40315', 'http://127.0.0.1:51234', 'http://127.0.0.1:1', 'http://127.0.0.1:65535', 'https://app.example']) {
|
||||
expect(await allowed(origin), origin).toBe(origin);
|
||||
}
|
||||
for (const origin of [
|
||||
'http://127.0.0.1', // no port: not what the Even app uses, and not what was configured
|
||||
'https://127.0.0.1:40315', // https was not configured
|
||||
'http://localhost:40315', // a different loopback name, not configured
|
||||
'http://[::1]:40315',
|
||||
'http://127.0.0.2:40315',
|
||||
'http://127.0.0.1.example.com:40315',
|
||||
'http://127.0.0.1:40315.example.com',
|
||||
'http://127.0.0.1:40315@example.com',
|
||||
'http://example.com:40315',
|
||||
'http://192.168.1.20:40315',
|
||||
'http://10.0.0.5:8080',
|
||||
'http://127.0.0.1:0',
|
||||
'http://127.0.0.1:65536',
|
||||
'http://127.0.0.1:abc',
|
||||
'http://127.0.0.1:40315/',
|
||||
'https://evil.example',
|
||||
'null',
|
||||
]) {
|
||||
expect(await allowed(origin), origin).toBeNull();
|
||||
}
|
||||
// The response varies by Origin, so a cache cannot serve one origin's answer to another.
|
||||
expect((await preflight('http://127.0.0.1:40315')).headers.get('vary') ?? '').toMatch(/origin/i);
|
||||
});
|
||||
|
||||
it('being an allowed origin grants nothing: every route still needs the device credential', async () => {
|
||||
h = await createHarness({ env: { HERMEVEN_ALLOWED_ORIGINS: 'http://127.0.0.1:*' } });
|
||||
const origin = { Origin: 'http://127.0.0.1:40315' };
|
||||
expect((await h.api('GET', '/v1/device', { headers: origin })).status).toBe(401);
|
||||
expect((await h.textTurn('hvn_wrong', randomUUID(), 'hi')).status).toBe(401);
|
||||
const cred = await h.pair();
|
||||
const ok = await h.api('GET', '/v1/device', { token: cred.token, headers: origin });
|
||||
expect(ok.status).toBe(200);
|
||||
expect(ok.headers.get('access-control-allow-origin')).toBe('http://127.0.0.1:40315');
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
});
|
||||
|
||||
it('localhost and [::1] can be opted in separately', async () => {
|
||||
h = await createHarness({ env: { HERMEVEN_ALLOWED_ORIGINS: 'http://localhost:*,http://[::1]:*' } });
|
||||
expect(await allowed('http://localhost:5173')).toBe('http://localhost:5173');
|
||||
expect(await allowed('http://[::1]:5173')).toBe('http://[::1]:5173');
|
||||
expect(await allowed('http://127.0.0.1:5173')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('pairing', () => {
|
||||
it('codes are single-use', async () => {
|
||||
h = await createHarness();
|
||||
|
||||
@@ -34,8 +34,12 @@ async function until(what: string, predicate: () => boolean, timeoutMs = 4000):
|
||||
}
|
||||
const phase = () => snapshot.state.phase;
|
||||
|
||||
let controllerExtras: Partial<ConstructorParameters<typeof Controller>[0]> = {};
|
||||
function makeController(dev: FakeDevice): Controller {
|
||||
return new Controller({
|
||||
// Off unless a test turns it on: most tests sit on a screen longer than a short timeout.
|
||||
idleExit: null,
|
||||
...controllerExtras,
|
||||
device: dev,
|
||||
measure: (text, width) => measureTextWrap(text, width).lineCount,
|
||||
locale: 'en-US',
|
||||
@@ -43,6 +47,7 @@ function makeController(dev: FakeDevice): Controller {
|
||||
submitAttempts: 3,
|
||||
submitRetryMs: 30,
|
||||
micStallMs: 300,
|
||||
holdToTalkMs: 150,
|
||||
makeClient: (baseUrl, token) =>
|
||||
new BridgeClient({
|
||||
baseUrl,
|
||||
@@ -81,6 +86,7 @@ async function pairedController(): Promise<void> {
|
||||
|
||||
beforeEach(async () => {
|
||||
network = { down: false, dropReplies: false, hook: null, sent: [] };
|
||||
controllerExtras = {};
|
||||
h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2' } });
|
||||
});
|
||||
afterEach(async () => {
|
||||
@@ -608,3 +614,312 @@ describe('CODY-009: exactly one conversation is created, whatever the timing', (
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('long press (a real G2 reported a slow tap as a long press)', () => {
|
||||
it('push-to-talk: hold starts recording, speaking while held, releasing sends', async () => {
|
||||
await pairedController();
|
||||
h.stt.next({ text: 'held question' });
|
||||
device.longPress();
|
||||
await until('listening with mic open', () => phase() === 'listening' && device.micOpen);
|
||||
expect(device.frame.status).toContain('● REC');
|
||||
device.speak(0.5);
|
||||
await new Promise((r) => setTimeout(r, 200)); // held longer than the push-to-talk threshold
|
||||
device.longPressRelease();
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(h.hermes.lastRun()!.input).toBe('held question');
|
||||
expect(device.micOpen).toBe(false);
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
});
|
||||
|
||||
it('a press released quickly behaves like a tap: recording continues until the next tap', async () => {
|
||||
await pairedController();
|
||||
device.longPress();
|
||||
await until('listening', () => phase() === 'listening' && device.micOpen);
|
||||
device.longPressRelease(); // released at once: not push-to-talk
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
expect(phase()).toBe('listening');
|
||||
expect(device.micOpen).toBe(true);
|
||||
expect(h.stt.calls).toBe(0);
|
||||
device.speak(0.4);
|
||||
device.tap();
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
});
|
||||
|
||||
it('a long press while already recording sends, and its release does nothing more', async () => {
|
||||
await pairedController();
|
||||
device.tap();
|
||||
await until('listening', () => phase() === 'listening' && device.micOpen);
|
||||
device.speak(0.4);
|
||||
device.longPress();
|
||||
await until('answer', () => phase() === 'answer');
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
device.longPressRelease();
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
expect(phase()).toBe('answer'); // the late release did not start a new recording
|
||||
expect(device.micOpens).toBe(1);
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
});
|
||||
|
||||
it('a release with no press, or after a cancel, is ignored', async () => {
|
||||
await pairedController();
|
||||
device.longPressRelease();
|
||||
expect(phase()).toBe('ready');
|
||||
device.longPress();
|
||||
await until('listening', () => phase() === 'listening' && device.micOpen);
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
device.doubleTap(); // cancel while still holding
|
||||
expect(phase()).toBe('cancelled');
|
||||
device.longPressRelease();
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
expect(phase()).toBe('cancelled');
|
||||
expect(h.stt.calls).toBe(0);
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
});
|
||||
|
||||
it('a long press on an answer starts a follow-up, like a tap', async () => {
|
||||
await pairedController();
|
||||
controller.askText('first');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
device.longPress();
|
||||
await until('listening', () => phase() === 'listening' && device.micOpen);
|
||||
expect(snapshot.state.conversationId).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
const quiet = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
describe('leaving the glasses when idle (the app blocks notifications while it is open)', () => {
|
||||
const FAST = { answer: 150, ready: 250, message: 100 };
|
||||
|
||||
it('after an answer sits untouched, Pepper leaves the glasses once, without a confirmation dialog', async () => {
|
||||
controllerExtras = { idleExit: FAST };
|
||||
await pairedController();
|
||||
device.launchedFrom('glassesMenu');
|
||||
controller.askText('hello');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(device.exits).toBe(0);
|
||||
await until('left the glasses', () => device.exits === 1, 1500);
|
||||
await quiet(400);
|
||||
expect(device.exits).toBe(1);
|
||||
expect(device.exitRequests).toBe(0); // not the "are you sure?" dialog
|
||||
expect(device.micOpen).toBe(false);
|
||||
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 () => {
|
||||
controllerExtras = { idleExit: FAST };
|
||||
await pairedController();
|
||||
device.launchedFrom('glassesMenu');
|
||||
h.hermes.next({ kind: 'complete', output: Array.from({ length: 80 }, (_, i) => `Sentence ${i + 1} of a long answer.`).join(' ') });
|
||||
controller.askText('long one');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
for (let i = 0; i < 6; i++) {
|
||||
await quiet(90); // each gap is shorter than the 150 ms timeout
|
||||
device.swipeDown();
|
||||
}
|
||||
expect(device.exits).toBe(0); // 540 ms have passed, well over the timeout, but never idle
|
||||
await until('left once it was left alone', () => device.exits === 1, 1500);
|
||||
});
|
||||
|
||||
it('never leaves while recording, transcribing, thinking or waiting for an approval', async () => {
|
||||
controllerExtras = { idleExit: FAST };
|
||||
await pairedController();
|
||||
device.launchedFrom('glassesMenu');
|
||||
device.tap();
|
||||
await until('listening', () => phase() === 'listening' && device.micOpen);
|
||||
device.speak(0.2);
|
||||
await quiet(250); // (shorter than the 300 ms microphone-stall check in these tests)
|
||||
expect(device.exits).toBe(0);
|
||||
h.hermes.next({ kind: 'complete', afterMs: 500, output: 'slow answer' });
|
||||
device.tap();
|
||||
await until('thinking', () => phase() === 'thinking');
|
||||
await quiet(350);
|
||||
expect(phase()).toBe('thinking');
|
||||
expect(device.exits).toBe(0);
|
||||
await until('answer', () => phase() === 'answer');
|
||||
|
||||
h.hermes.next({ kind: 'approval' });
|
||||
controller.askText('needs approval');
|
||||
await until('approval', () => phase() === 'approval');
|
||||
await quiet(350);
|
||||
expect(device.exits).toBe(0);
|
||||
device.doubleTap();
|
||||
});
|
||||
|
||||
it('at Ready with nothing asked, and after an error or a cancel, it also leaves', async () => {
|
||||
controllerExtras = { idleExit: FAST };
|
||||
await pairedController();
|
||||
device.launchedFrom('glassesMenu');
|
||||
await until('left from Ready', () => device.exits === 1, 1500);
|
||||
|
||||
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.launchedFrom('glassesMenu');
|
||||
device.micAllowed = false;
|
||||
device.tap();
|
||||
await until('error', () => phase() === 'error');
|
||||
await until('left from the error screen', () => device.exits === 1, 1500);
|
||||
});
|
||||
|
||||
it('it leaves however it was opened: no launch source and no gesture at all (what a voice launch gave on a real G2)', async () => {
|
||||
controllerExtras = { idleExit: FAST };
|
||||
await pairedController();
|
||||
expect(snapshot.launchSource).toBe('unknown');
|
||||
await until('left from Ready with nothing ever touched', () => device.exits === 1, 1500);
|
||||
expect(device.exitAttempts).toBe(1);
|
||||
});
|
||||
|
||||
it('opened from the phone app, it leaves too', async () => {
|
||||
controllerExtras = { idleExit: FAST };
|
||||
await pairedController();
|
||||
device.launchedFrom('appMenu');
|
||||
controller.askText('typed on the phone');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
await until('left after the answer', () => device.exits === 1, 1500);
|
||||
});
|
||||
|
||||
it('an unpaired app never leaves: pairing on the phone is not interrupted', async () => {
|
||||
controllerExtras = { idleExit: FAST };
|
||||
device = new FakeDevice();
|
||||
controller = makeController(device);
|
||||
await controller.start();
|
||||
device.launchedFrom('glassesMenu');
|
||||
device.swipeDown();
|
||||
await quiet(700);
|
||||
expect(phase()).toBe('unpaired');
|
||||
expect(device.exitAttempts).toBe(0);
|
||||
});
|
||||
|
||||
it('touching the phone page holds it open for the grace period', async () => {
|
||||
controllerExtras = { idleExit: FAST, phoneGraceMs: 500 };
|
||||
await pairedController();
|
||||
device.launchedFrom('glassesMenu');
|
||||
controller.askText('hello');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
controller.notePhoneActivity();
|
||||
await quiet(450); // three timeouts' worth
|
||||
expect(device.exits).toBe(0);
|
||||
await until('left after the grace period', () => device.exits === 1, 2000);
|
||||
});
|
||||
|
||||
it('can be switched off entirely', async () => {
|
||||
controllerExtras = { idleExit: null };
|
||||
await pairedController();
|
||||
device.launchedFrom('glassesMenu');
|
||||
controller.askText('hello');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
await quiet(600);
|
||||
expect(device.exits).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('conversations now that Pepper leaves between questions', () => {
|
||||
it('a question soon after the last one continues the conversation across a relaunch', async () => {
|
||||
await pairedController();
|
||||
controller.askText('My dog is called Biscuit.');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
await until('saved', () => typeof JSON.parse(device.storage.get('hermeven.v1')!).lastTurnAt === 'number');
|
||||
await controller.stop();
|
||||
const reborn = new FakeDevice();
|
||||
for (const [k, v] of device.storage) reborn.storage.set(k, v);
|
||||
device = reborn;
|
||||
controller = makeController(device);
|
||||
await controller.start();
|
||||
controller.askText('What is my dog called?');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(device.frame.body).toContain('turn=2');
|
||||
expect(h.hermes.sessions.size).toBe(1);
|
||||
});
|
||||
|
||||
it('a question after a long silence starts a new conversation', async () => {
|
||||
await pairedController();
|
||||
controller.askText('My dog is called Biscuit.');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
await until('saved', () => typeof JSON.parse(device.storage.get('hermeven.v1')!).lastTurnAt === 'number');
|
||||
await controller.stop();
|
||||
const reborn = new FakeDevice();
|
||||
for (const [k, v] of device.storage) reborn.storage.set(k, v);
|
||||
device = reborn;
|
||||
controllerExtras = { conversationGapMs: 50 };
|
||||
await quiet(120);
|
||||
controller = makeController(device);
|
||||
await controller.start();
|
||||
expect(snapshot.state.conversationId).toBeNull();
|
||||
controller.askText('What is my dog called?');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(device.frame.body).toContain('turn=1');
|
||||
expect(h.hermes.sessions.size).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -126,6 +126,7 @@ describe('CODY-002: host calls stay serialised and a late microphone start ends
|
||||
shutDownPageContainer: (...a: unknown[]) => call('exit', a),
|
||||
getLocalStorage: (...a: unknown[]) => call('get', a),
|
||||
setLocalStorage: (...a: unknown[]) => call('set', a),
|
||||
onLaunchSource: () => () => undefined,
|
||||
};
|
||||
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([]);
|
||||
});
|
||||
|
||||
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 () => {
|
||||
const host = fakeHost();
|
||||
const device = new EvenDevice(host.bridge as never);
|
||||
|
||||
@@ -50,6 +50,7 @@ class FakeEvenHost {
|
||||
return () => this.hub.delete(cb);
|
||||
},
|
||||
onDeviceStatusChanged: () => () => undefined,
|
||||
onLaunchSource: () => () => undefined,
|
||||
};
|
||||
|
||||
heldWrites(): number {
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
// @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('Diagnostics shows what the glasses deliver, by type only: a tap is visible, an unknown event is visible as ignored, audio is only counted', async () => {
|
||||
const even = fakeEvenHost();
|
||||
(window as any).flutter_inappwebview = even.host;
|
||||
booted = await boot(document, window);
|
||||
expect(diagnostics()['Glasses input']).toContain('0 gesture/lifecycle event(s), 0 ignored, 0 audio frame(s); last: none yet');
|
||||
|
||||
// The Even app pushes events to the page through this SDK entry point.
|
||||
const push = (type: string, jsonData: unknown) => (window as any)._listenEvenAppMessage({ type: 'listen_even_app_data', method: 'evenHubEvent', data: { type, jsonData } });
|
||||
push('sysEvent', { eventSource: 1 }); // a tap: no eventType on the wire
|
||||
await wait(20);
|
||||
const afterTap = diagnostics()['Glasses input']!;
|
||||
expect(afterTap).toContain('1 gesture/lifecycle event(s)');
|
||||
expect(afterTap).not.toContain('ignored;');
|
||||
expect(afterTap).toContain('sysEvent(type=none,source=1) -> tap');
|
||||
// The tap really drove the app: unpaired, so the state stays put, but it was delivered.
|
||||
push('sysEvent', { eventType: 9, eventSource: 1 }); // long press: recognised
|
||||
await wait(20);
|
||||
expect(diagnostics()['Glasses input']).toContain('sysEvent(type=9,source=1) -> long_press');
|
||||
push('sysEvent', { eventType: 8, imuData: { x: 1, y: 2, z: 3 } }); // IMU: outside the contract
|
||||
await wait(20);
|
||||
const afterLongPress = diagnostics()['Glasses input']!;
|
||||
expect(afterLongPress).toContain('1 ignored');
|
||||
expect(afterLongPress).toContain('sysEvent(type=8) -> ignored');
|
||||
push('audioEvent', { audioPcm: [1, 2, 3, 4] });
|
||||
await wait(20);
|
||||
push('sysEvent', { eventType: 3 });
|
||||
await wait(20);
|
||||
const afterAudio = diagnostics()['Glasses input']!;
|
||||
expect(afterAudio).toContain('1 audio frame(s)');
|
||||
expect(afterAudio).toContain('-> double_tap');
|
||||
// Nothing from the audio payload appears anywhere in Diagnostics.
|
||||
expect(JSON.stringify(diagnostics())).not.toContain('1,2,3,4');
|
||||
});
|
||||
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { HOST_WAIT_MS, PLATFORM_READY_EVENT, waitForEvenHost, watchForLateHost, type HostWindow } from '../../apps/even-client/src/device/hostDetect.ts';
|
||||
|
||||
/**
|
||||
* Host detection waits briefly for the Even app's connection instead of deciding on the first
|
||||
* instant. This is a precaution: no real phone has yet been observed providing it late.
|
||||
*/
|
||||
function fakeWindow() {
|
||||
const listeners = new Map<string, Set<() => void>>();
|
||||
const win: HostWindow & { fire(type: string): void; listenerCount(): number } = {
|
||||
addEventListener: (type, l) => void (listeners.get(type) ?? listeners.set(type, new Set()).get(type)!).add(l),
|
||||
removeEventListener: (type, l) => void listeners.get(type)?.delete(l),
|
||||
fire: (type) => listeners.get(type)?.forEach((l) => l()),
|
||||
listenerCount: () => [...listeners.values()].reduce((n, s) => n + s.size, 0),
|
||||
};
|
||||
return win;
|
||||
}
|
||||
const host = { callHandler: () => undefined };
|
||||
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
describe('detecting the Even app host', () => {
|
||||
it('present from the start (the simulator): found at once', async () => {
|
||||
const win = fakeWindow();
|
||||
win.flutter_inappwebview = host;
|
||||
expect(await waitForEvenHost(win)).toEqual({ found: true, waitedMs: 0 });
|
||||
expect(win.listenerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('appears shortly after the page starts: found, not mistaken for a browser', async () => {
|
||||
const win = fakeWindow();
|
||||
const detecting = waitForEvenHost(win);
|
||||
await vi.advanceTimersByTimeAsync(800);
|
||||
win.flutter_inappwebview = host;
|
||||
await vi.advanceTimersByTimeAsync(60);
|
||||
const result = await detecting;
|
||||
expect(result.found).toBe(true);
|
||||
expect(result.waitedMs).toBeGreaterThanOrEqual(800);
|
||||
expect(result.waitedMs).toBeLessThan(1000);
|
||||
});
|
||||
|
||||
it("the WebView's platform-ready event triggers an immediate check", async () => {
|
||||
const win = fakeWindow();
|
||||
const detecting = waitForEvenHost(win, { pollMs: 100_000 });
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
win.flutter_inappwebview = host;
|
||||
win.fire(PLATFORM_READY_EVENT);
|
||||
expect((await detecting).found).toBe(true);
|
||||
});
|
||||
|
||||
it('the event alone, with no host object, proves nothing', async () => {
|
||||
const win = fakeWindow();
|
||||
const detecting = waitForEvenHost(win);
|
||||
win.fire(PLATFORM_READY_EVENT);
|
||||
await vi.advanceTimersByTimeAsync(HOST_WAIT_MS + 10);
|
||||
expect((await detecting).found).toBe(false);
|
||||
});
|
||||
|
||||
it('an object without a callable callHandler is not a host', async () => {
|
||||
const win = fakeWindow();
|
||||
win.flutter_inappwebview = {};
|
||||
const detecting = waitForEvenHost(win);
|
||||
await vi.advanceTimersByTimeAsync(HOST_WAIT_MS + 10);
|
||||
expect((await detecting).found).toBe(false);
|
||||
});
|
||||
|
||||
it('a plain browser: gives up after the wait and cleans up', async () => {
|
||||
const win = fakeWindow();
|
||||
const detecting = waitForEvenHost(win);
|
||||
await vi.advanceTimersByTimeAsync(HOST_WAIT_MS - 10);
|
||||
let settled = false;
|
||||
void detecting.then(() => (settled = true));
|
||||
await Promise.resolve();
|
||||
expect(settled).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(20);
|
||||
expect(await detecting).toEqual({ found: false, waitedMs: HOST_WAIT_MS });
|
||||
expect(win.listenerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('a host that turns up after preview mode was chosen triggers exactly one late callback', async () => {
|
||||
const win = fakeWindow();
|
||||
let late = 0;
|
||||
watchForLateHost(win, () => (late += 1));
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(late).toBe(0);
|
||||
win.flutter_inappwebview = host;
|
||||
await vi.advanceTimersByTimeAsync(600);
|
||||
win.fire(PLATFORM_READY_EVENT);
|
||||
await vi.advanceTimersByTimeAsync(5000);
|
||||
expect(late).toBe(1);
|
||||
expect(win.listenerCount()).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,526 @@
|
||||
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;
|
||||
private heldExitReject: ((err: Error) => 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, reject) => {
|
||||
this.heldExit = resolve;
|
||||
this.heldExitReject = reject;
|
||||
});
|
||||
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 } });
|
||||
}
|
||||
/** The held exit call fails with an error instead of answering. */
|
||||
rejectExit(): void {
|
||||
const reject = this.heldExitReject;
|
||||
this.heldExit = null;
|
||||
this.heldExitReject = null;
|
||||
reject?.(new Error('host error'));
|
||||
}
|
||||
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('with no launch source and no gesture at all, the same start-up still leaves, once', async () => {
|
||||
await pairedHost();
|
||||
controller = makeController();
|
||||
await controller.start();
|
||||
await until('ready', () => snapshot.state.phase === 'ready');
|
||||
await until('left the glasses', () => logged('left the glasses') === 1, 2000);
|
||||
await quiet(400);
|
||||
expect(host.exitCalls).toEqual([0]);
|
||||
});
|
||||
});
|
||||
|
||||
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: still one exit, 30 s after Ready', async () => {
|
||||
await pairedHost();
|
||||
fakeClock();
|
||||
controller = defaults();
|
||||
await controller.start();
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
host.pushLaunchSource('glassesMenu'); // arrives late: it must not restart or double the countdown
|
||||
await vi.advanceTimersByTimeAsync(19_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]);
|
||||
});
|
||||
|
||||
it('NO launch source is ever pushed (seen on a real G2 voice launch): one exit, 30 s after Ready', async () => {
|
||||
await pairedHost();
|
||||
fakeClock();
|
||||
controller = defaults();
|
||||
await controller.start();
|
||||
expect(snapshot.launchSource).toBe('unknown');
|
||||
await expectOneExitAtThirtySeconds();
|
||||
});
|
||||
|
||||
it('appMenu pushed early: opened from the phone app, it leaves the same way', async () => {
|
||||
await pairedHost();
|
||||
fakeClock();
|
||||
controller = defaults();
|
||||
host.pushLaunchSource('appMenu');
|
||||
await controller.start();
|
||||
expect(snapshot.launchSource).toBe('appMenu');
|
||||
await expectOneExitAtThirtySeconds();
|
||||
});
|
||||
|
||||
it('opened and then the phone page is touched: the full two-minute grace, then 30 s', async () => {
|
||||
await pairedHost();
|
||||
fakeClock();
|
||||
controller = defaults();
|
||||
await controller.start();
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
controller.notePhoneActivity();
|
||||
await vi.advanceTimersByTimeAsync(149_500);
|
||||
expect(host.exitCalls).toEqual([]);
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
expect(host.exitCalls).toEqual([0]);
|
||||
});
|
||||
|
||||
it('never paired: nothing leaves, however long it is left', async () => {
|
||||
host = new FakeEvenHost();
|
||||
fakeClock();
|
||||
controller = defaults();
|
||||
host.pushLaunchSource('glassesMenu');
|
||||
await controller.start();
|
||||
expect(snapshot.state.phase).toBe('unpaired');
|
||||
host.swipeDown();
|
||||
await vi.advanceTimersByTimeAsync(30 * 60_000);
|
||||
expect(host.exitCalls).toEqual([]);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* CODY-019. Activity that arrives while an exit call is still with the host restarts the full
|
||||
* countdown (or the phone grace period). When that call then fails, its short retry must not
|
||||
* replace the restarted timer. Default times, fake clock, production adapter.
|
||||
*/
|
||||
describe('activity during a pending exit keeps its full countdown (CODY-019)', () => {
|
||||
const fakeClock = () => vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'] });
|
||||
|
||||
/** Launched from the glasses, idle for 30 s: the first exit call is now held by the host. */
|
||||
async function firstExitHeld(): Promise<void> {
|
||||
await pairedHost();
|
||||
fakeClock();
|
||||
controller = makeController({ idleExit: {}, exitRetryMs: undefined as never, exitAttempts: undefined as never });
|
||||
host.pushLaunchSource('glassesMenu');
|
||||
host.exitScript = ['hold'];
|
||||
await controller.start();
|
||||
await vi.advanceTimersByTimeAsync(30_050);
|
||||
expect(host.exitCalls).toEqual([0]);
|
||||
expect(host.exitHeld()).toBe(true);
|
||||
}
|
||||
|
||||
/** From the activity: nothing for the full 30 s, then one more call, which succeeds. */
|
||||
async function fullCountdownThenLeaves(expectedCalls: number): Promise<void> {
|
||||
const before = host.exitCalls.length;
|
||||
await vi.advanceTimersByTimeAsync(29_800); // 3 s retry would have fired long ago
|
||||
expect(host.exitCalls.length).toBe(before);
|
||||
expect(logged('left the glasses')).toBe(0);
|
||||
await vi.advanceTimersByTimeAsync(10 * 60_000);
|
||||
expect(host.exitCalls.length).toBe(expectedCalls);
|
||||
expect(logged('left the glasses')).toBe(1);
|
||||
expect(host.maxInFlight).toBe(1);
|
||||
}
|
||||
|
||||
it('a swipe at Ready (no state change), then the host answers false', async () => {
|
||||
await firstExitHeld();
|
||||
const generation = snapshot.state.generation;
|
||||
host.swipeDown();
|
||||
expect(snapshot.state.generation).toBe(generation); // the gesture changed no state
|
||||
host.releaseExit(false);
|
||||
await fullCountdownThenLeaves(2);
|
||||
});
|
||||
|
||||
it('a swipe at Ready, then the host call fails with an error', async () => {
|
||||
await firstExitHeld();
|
||||
host.swipeDown();
|
||||
host.rejectExit();
|
||||
await fullCountdownThenLeaves(2);
|
||||
});
|
||||
|
||||
it('a swipe at Ready, then the host never answers in time; its late success is still final', async () => {
|
||||
await firstExitHeld();
|
||||
host.swipeDown();
|
||||
await vi.advanceTimersByTimeAsync(ADAPTER_TIMEOUT_MS + 50); // the wait for an answer runs out
|
||||
expect(logged('will try again')).toBe(0); // no short retry was scheduled over the swipe's countdown
|
||||
await vi.advanceTimersByTimeAsync(29_700);
|
||||
expect(host.exitCalls).toEqual([0]);
|
||||
// The full countdown from the swipe ends; the retry waits on the SAME held call.
|
||||
await vi.advanceTimersByTimeAsync(400);
|
||||
expect(host.exitCalls).toEqual([0]);
|
||||
expect(host.inFlight).toBe(1);
|
||||
host.releaseExit(true);
|
||||
await vi.advanceTimersByTimeAsync(10 * 60_000);
|
||||
expect(host.exitCalls).toEqual([0]); // one host call ever
|
||||
expect(logged('left the glasses')).toBe(1);
|
||||
expect(host.maxInFlight).toBe(1);
|
||||
});
|
||||
|
||||
it('a touch on the phone page, then the host answers false: the whole grace period stands', async () => {
|
||||
await firstExitHeld();
|
||||
controller.notePhoneActivity();
|
||||
host.releaseExit(false);
|
||||
// Grace is 120 s, then the 30 s Ready wait: nothing before 150 s from the touch.
|
||||
await vi.advanceTimersByTimeAsync(149_500);
|
||||
expect(host.exitCalls).toEqual([0]);
|
||||
expect(logged('left the glasses')).toBe(0);
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
expect(host.exitCalls).toEqual([0, 0]);
|
||||
await vi.advanceTimersByTimeAsync(10 * 60_000);
|
||||
expect(host.exitCalls).toEqual([0, 0]);
|
||||
expect(logged('left the glasses')).toBe(1);
|
||||
expect(host.maxInFlight).toBe(1);
|
||||
});
|
||||
|
||||
it('after such activity the attempts are still bounded: a host that keeps refusing gets four, then none', async () => {
|
||||
await firstExitHeld();
|
||||
host.swipeDown();
|
||||
host.exitScript = [false, false, false, false, false, false];
|
||||
host.releaseExit(false);
|
||||
await vi.advanceTimersByTimeAsync(10 * 60_000);
|
||||
expect(host.exitCalls).toEqual([0, 0, 0, 0, 0]); // the one overtaken by the swipe, then four
|
||||
expect(logged('staying until the next activity')).toBe(1);
|
||||
expect(host.maxInFlight).toBe(1);
|
||||
});
|
||||
|
||||
it('control: with no activity, the same refusal IS retried after 3 s', async () => {
|
||||
await firstExitHeld();
|
||||
host.releaseExit(false);
|
||||
await vi.advanceTimersByTimeAsync(3_100);
|
||||
expect(host.exitCalls).toEqual([0, 0]);
|
||||
expect(logged('left the glasses')).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,682 @@
|
||||
import { measureTextWrap } from '@evenrealities/pretext';
|
||||
import { SCHEMA_VERSION } from '@hermeven/contracts';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { Controller, type Snapshot } from '../../apps/even-client/src/core/controller.ts';
|
||||
import { BridgeClient } from '../../apps/even-client/src/net/bridgeClient.ts';
|
||||
import { FakeDevice } from '../fakes/fakeDevice.ts';
|
||||
import { syntheticPcm } from '../fakes/fakeStt.ts';
|
||||
import { createHarness, type Harness } from './harness.ts';
|
||||
|
||||
/**
|
||||
* Listening for an agent's name. The bridge is real. Hermes, speech-to-text and the glasses are
|
||||
* TEST FAKES: the "speech" is a tone, and what it "says" is whatever the fake recogniser is
|
||||
* scripted to return. This proves the plumbing and the rules, and nothing about how well a
|
||||
* real microphone or a real recogniser hears a name.
|
||||
*/
|
||||
const WENDY_KEY = 'wendy-profile-key-0123456789';
|
||||
const CODY_KEY = 'cody-profile-key-0123456789';
|
||||
const AGENT_ENV = {
|
||||
HERMEVEN_AGENT_NAME: 'Pepper',
|
||||
HERMEVEN_AGENTS: 'wendy,cody',
|
||||
HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY,
|
||||
HERMEVEN_AGENT_CODY_API_KEY: CODY_KEY,
|
||||
HERMEVEN_AGENT_CODY_NAME: 'Cody R.',
|
||||
HERMEVEN_AGENT_CODY_WAKE: 'kody',
|
||||
};
|
||||
|
||||
let h: Harness;
|
||||
async function harness(env: Record<string, string> = AGENT_ENV, opts: { stt?: boolean } = {}): Promise<void> {
|
||||
h = await createHarness({ env, ...opts });
|
||||
h.hermes.profiles.set('wendy', WENDY_KEY);
|
||||
h.hermes.profiles.set('cody', CODY_KEY);
|
||||
}
|
||||
const wakeQuery = (extra: Record<string, string> = {}) =>
|
||||
new URLSearchParams({ schema_version: '1', locale: 'en-US', encoding: 'pcm_s16le', sample_rate: '16000', channels: '1', ...extra });
|
||||
const wake = (token: string | undefined, said: string, query = wakeQuery()) => {
|
||||
h.stt.next({ text: said });
|
||||
return h.api('POST', `/v1/wake?${query}`, { token, body: syntheticPcm(1) });
|
||||
};
|
||||
const runsPosted = () => h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs');
|
||||
|
||||
afterEach(async () => {
|
||||
await h?.close();
|
||||
});
|
||||
|
||||
describe('bridge: POST /v1/wake', () => {
|
||||
it('says who was addressed and what followed, and creates nothing', async () => {
|
||||
await harness();
|
||||
const { token } = await h.pair();
|
||||
const res = await wake(token, ' Wendy, what is on my calendar?');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ schema_version: SCHEMA_VERSION, matched: true, agent_id: 'wendy', text: 'What is on my calendar?', near_miss: null });
|
||||
expect((await wake(token, 'Kody.')).body).toMatchObject({ matched: true, agent_id: 'cody', text: '' });
|
||||
expect((await wake(token, 'hey pepper turn it off')).body).toMatchObject({ matched: true, agent_id: 'default', text: 'Turn it off' });
|
||||
// The recogniser got a proper WAV, as for a question.
|
||||
expect(h.stt.lastWav).toMatchObject({ sampleRate: 16000, channels: 1, bitsPerSample: 16 });
|
||||
expect(h.hermes.requests.filter((r) => r.method === 'POST')).toEqual([]);
|
||||
expect(h.bridge.engine.activeConversation((await h.api('GET', '/v1/device', { token })).body.device_id)).toBeFalsy();
|
||||
});
|
||||
|
||||
it('speech that is not for an agent is not returned, not kept and not logged', async () => {
|
||||
await harness();
|
||||
const { token } = await h.pair();
|
||||
const secret = 'my card number is four one one one';
|
||||
expect((await wake(token, secret)).body).toEqual({ schema_version: SCHEMA_VERSION, matched: false, agent_id: null, text: '', near_miss: null });
|
||||
expect((await wake(token, `I told Wendy that ${secret}`)).body).toMatchObject({ matched: false, text: '' });
|
||||
expect((await wake(token, 'Wendi, hello')).body).toEqual({ schema_version: SCHEMA_VERSION, matched: false, agent_id: null, text: '', near_miss: 'wendi' });
|
||||
await wake(token, `Wendy, ${secret}`);
|
||||
const logs = h.logs.join('\n');
|
||||
for (const fragment of ['card number', 'four one one', 'wendi', 'Wendi']) expect(logs).not.toContain(fragment);
|
||||
expect(logs).toContain('wake.matched');
|
||||
});
|
||||
|
||||
it('needs a device credential and a well-formed request', async () => {
|
||||
await harness();
|
||||
const { token } = await h.pair();
|
||||
expect((await wake(undefined, 'Wendy')).status).toBe(401);
|
||||
expect((await h.api('POST', `/v1/wake?${wakeQuery()}`, { token, json: { a: 1 } })).status).toBe(415);
|
||||
expect((await wake(token, 'Wendy', wakeQuery({ sample_rate: '8000' }))).status).toBe(400);
|
||||
expect((await wake(token, 'Wendy', wakeQuery({ schema_version: '2' }))).status).toBe(400);
|
||||
expect((await h.api('POST', `/v1/wake?${wakeQuery()}`, { token, body: Buffer.alloc(3) })).status).toBe(400);
|
||||
});
|
||||
|
||||
it('a failed transcription is "nobody was addressed"', async () => {
|
||||
await harness();
|
||||
const { token } = await h.pair();
|
||||
h.stt.next({ status: 500 });
|
||||
const res = await h.api('POST', `/v1/wake?${wakeQuery()}`, { token, body: syntheticPcm(1) });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.matched).toBe(false);
|
||||
});
|
||||
|
||||
it('answers not_found when nobody can be called by voice', async () => {
|
||||
await harness(AGENT_ENV, { stt: false });
|
||||
expect((await wake((await h.pair()).token, 'Wendy')).status).toBe(404);
|
||||
await h.close();
|
||||
// One agent, never given a name: there is no word to listen for.
|
||||
await harness({});
|
||||
expect((await wake((await h.pair()).token, 'Agent, hello')).status).toBe(404);
|
||||
});
|
||||
|
||||
it('checks one stretch of speech at a time per device, within a per-minute budget', async () => {
|
||||
await harness({ ...AGENT_ENV, HERMEVEN_WAKE_CHECKS_PER_MINUTE: '2' });
|
||||
const { token } = await h.pair();
|
||||
h.stt.next({ text: 'hello', delayMs: 150 });
|
||||
const first = h.api('POST', `/v1/wake?${wakeQuery()}`, { token, body: syntheticPcm(1) });
|
||||
await new Promise((r) => setTimeout(r, 40));
|
||||
expect((await h.api('POST', `/v1/wake?${wakeQuery()}`, { token, body: syntheticPcm(1) })).status).toBe(429);
|
||||
expect((await first).status).toBe(200);
|
||||
expect((await wake(token, 'hello')).status).toBe(200);
|
||||
expect((await wake(token, 'hello')).status).toBe(429);
|
||||
// Questions have their own budget.
|
||||
const conversation = await h.conversation(token);
|
||||
expect((await h.textTurn(token, conversation, 'still fine')).status).toBe(202);
|
||||
});
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ the app
|
||||
let device: FakeDevice;
|
||||
let controller: Controller;
|
||||
let snapshot: Snapshot;
|
||||
let sent: Array<{ method: string; path: string }>;
|
||||
let wakeRoute: 'real' | 'not_found';
|
||||
let extras: Partial<ConstructorParameters<typeof Controller>[0]>;
|
||||
|
||||
function makeController(dev: FakeDevice): Controller {
|
||||
return new Controller({
|
||||
wake: { armTimeoutMs: 250, watchMs: 40, stallMs: 150, retryMs: 120, pauseMs: 100 },
|
||||
...extras,
|
||||
device: dev,
|
||||
measure: (text, width) => measureTextWrap(text, width).lineCount,
|
||||
locale: 'en-US',
|
||||
pollIntervalMs: 20,
|
||||
submitAttempts: 3,
|
||||
submitRetryMs: 30,
|
||||
micStallMs: 2000,
|
||||
makeClient: (baseUrl, token) =>
|
||||
new BridgeClient({
|
||||
baseUrl,
|
||||
token,
|
||||
timeoutMs: 1500,
|
||||
fetchImpl: async (input, init) => {
|
||||
const path = new URL(String(input)).pathname;
|
||||
sent.push({ method: init?.method ?? 'GET', path });
|
||||
if (path === '/v1/wake' && wakeRoute === 'not_found') {
|
||||
return new Response(JSON.stringify({ schema_version: SCHEMA_VERSION, error: { code: 'not_found', message: 'Not found.', retryable: false } }), {
|
||||
status: 404,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
return fetch(input, init);
|
||||
},
|
||||
}),
|
||||
onChange: (s) => {
|
||||
snapshot = s;
|
||||
},
|
||||
});
|
||||
}
|
||||
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} hud=${JSON.stringify(device.frame)}`);
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
}
|
||||
}
|
||||
const phase = () => snapshot.state.phase;
|
||||
const pause = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
const listening = () => until('listening for a name', () => device.micOpen && snapshot.state.wakeListening);
|
||||
async function paired(): Promise<void> {
|
||||
device = new FakeDevice();
|
||||
controller = makeController(device);
|
||||
await controller.start();
|
||||
await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2');
|
||||
expect(phase()).toBe('ready');
|
||||
}
|
||||
/** Someone says something and stops: a tone, then a pause long enough to end the utterance. */
|
||||
function say(seconds = 1, pauseSeconds = 0.8): void {
|
||||
device.speak(seconds);
|
||||
device.silence(pauseSeconds);
|
||||
}
|
||||
const posts = (path: string) => sent.filter((s) => s.method === 'POST' && s.path === path).length;
|
||||
|
||||
describe('glasses: always listening for a name', () => {
|
||||
beforeEach(async () => {
|
||||
sent = [];
|
||||
wakeRoute = 'real';
|
||||
extras = {};
|
||||
await harness();
|
||||
});
|
||||
afterEach(async () => {
|
||||
await controller?.stop();
|
||||
});
|
||||
|
||||
it('opens the microphone by itself once paired, says so on the HUD, and stays on the glasses', async () => {
|
||||
extras = { idleExit: { ready: 60, answer: 60, message: 60 } };
|
||||
device = new FakeDevice();
|
||||
controller = makeController(device);
|
||||
await controller.start();
|
||||
// Not paired: nothing to listen for, microphone closed.
|
||||
await pause(60);
|
||||
expect(device.micOpens).toBe(0);
|
||||
await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2');
|
||||
await listening();
|
||||
expect(device.frame).toEqual({
|
||||
body: 'Pepper\n\nListening. Say a name, then your question:\nPepper · Wendy · Cody',
|
||||
status: '● Tap: ask · Swipe: agent · 2×: exit',
|
||||
});
|
||||
expect(snapshot.wake).toEqual({ available: true, enabled: true, listening: true });
|
||||
// Well past every idle time: still here, still listening.
|
||||
await pause(250);
|
||||
expect(device.exitAttempts).toBe(0);
|
||||
expect(device.micOpen).toBe(true);
|
||||
});
|
||||
|
||||
it('"Wendy, <question>" in one breath is asked of Wendy, with what was heard shown while she works', async () => {
|
||||
await paired();
|
||||
await listening();
|
||||
h.stt.next({ text: 'Wendy, what is on my calendar?' });
|
||||
h.hermes.next({ kind: 'complete', afterMs: 200 });
|
||||
say();
|
||||
await until('thinking', () => phase() === 'thinking');
|
||||
expect(device.frame.body).toBe('Wendy is thinking…\n\nHeard: What is on my calendar?');
|
||||
// While the question is with the agent the microphone is closed.
|
||||
await until('microphone closed', () => !device.micOpen);
|
||||
expect(device.frame.status).not.toContain('●');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy']);
|
||||
expect(snapshot.lastTurn?.input_text).toBe('What is on my calendar?');
|
||||
// One recogniser call (the wake check); the question itself went as text, once.
|
||||
expect(h.stt.calls).toBe(1);
|
||||
expect(posts('/v1/turns')).toBe(1);
|
||||
// Back at rest it listens again, on the answer screen too.
|
||||
await listening();
|
||||
expect(device.frame.status).toBe('● Wendy · Tap: ask');
|
||||
});
|
||||
|
||||
it('a second name on the answer screen switches agent; each agent keeps its own conversation', async () => {
|
||||
await paired();
|
||||
await listening();
|
||||
h.stt.next({ text: 'Wendy, first' });
|
||||
say();
|
||||
await until('answer', () => phase() === 'answer');
|
||||
await listening();
|
||||
h.stt.next({ text: 'Hey Kody, second' });
|
||||
say();
|
||||
await until('second answer', () => phase() === 'answer' && h.hermes.executedBy.length === 2);
|
||||
await listening();
|
||||
h.stt.next({ text: 'Wendy, third' });
|
||||
say();
|
||||
await until('third answer', () => phase() === 'answer' && h.hermes.executedBy.length === 3);
|
||||
expect(h.hermes.executedBy).toEqual(['wendy', 'cody', 'wendy']);
|
||||
expect([...h.hermes.sessions.values()].map((inputs) => inputs.length).sort()).toEqual([1, 2]);
|
||||
expect(device.frame.status).toContain('Wendy · Tap: ask');
|
||||
});
|
||||
|
||||
it('speech that is not addressed to an agent goes nowhere and changes nothing on screen', async () => {
|
||||
await paired();
|
||||
await listening();
|
||||
const frames = device.frames.length;
|
||||
h.stt.next({ text: 'so I told Wendy we would be late' }, { text: 'Wendi, are you there' });
|
||||
say();
|
||||
await until('first check', () => h.stt.calls === 1);
|
||||
await pause(80);
|
||||
say();
|
||||
await until('second check', () => h.stt.calls === 2);
|
||||
await pause(80);
|
||||
expect(phase()).toBe('ready');
|
||||
expect(device.frames.length).toBe(frames);
|
||||
expect(posts('/v1/turns')).toBe(0);
|
||||
expect(posts('/v1/conversations')).toBe(0);
|
||||
expect(runsPosted()).toEqual([]);
|
||||
// The near miss is visible on the phone, as one word; the other sentence is nowhere.
|
||||
const log = snapshot.log.map((e) => e.detail).join('\n');
|
||||
expect(log).toContain('heard "wendi"');
|
||||
expect(log).not.toContain('late');
|
||||
expect(device.micOpen).toBe(true);
|
||||
});
|
||||
|
||||
it('a name alone starts a recording that sends itself when the speaker stops', async () => {
|
||||
await paired();
|
||||
await listening();
|
||||
h.stt.next({ text: 'Cody.' }, { text: 'are the tests passing' });
|
||||
say(0.6);
|
||||
await until('recording for Cody', () => phase() === 'listening');
|
||||
expect(device.frame.body).toBe('Cody R. is listening…\n\nAsk your question. It is sent when you stop speaking.');
|
||||
expect(device.frame.status).toContain('● REC');
|
||||
// Going from listening to recording did not close and reopen the microphone.
|
||||
expect(device.micOpens).toBe(1);
|
||||
expect(device.micCloses).toBe(0);
|
||||
device.speak(1.2);
|
||||
device.silence(1);
|
||||
expect(phase()).toBe('listening'); // a pause shorter than the limit does not send
|
||||
device.silence(0.4);
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(h.hermes.executedBy).toEqual(['cody']);
|
||||
expect(snapshot.lastTurn?.input_text).toBe('are the tests passing');
|
||||
await listening();
|
||||
});
|
||||
|
||||
it('a question spoken before the name has been recognised is not lost', async () => {
|
||||
await paired();
|
||||
await listening();
|
||||
h.stt.next({ text: 'Wendy', delayMs: 300 }, { text: 'what time is it' });
|
||||
say(0.5);
|
||||
await until('check started', () => posts('/v1/wake') === 1);
|
||||
say(1.5); // spoken, and finished, while the name is still being checked
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy']);
|
||||
expect(snapshot.lastTurn?.input_text).toBe('what time is it');
|
||||
expect(posts('/v1/wake')).toBe(1);
|
||||
// What was sent as the question is at least the 1.5 s that was spoken.
|
||||
expect(h.stt.lastWav!.dataBytes).toBeGreaterThanOrEqual(1.5 * 32000);
|
||||
});
|
||||
|
||||
it('a name alone followed by nothing goes back to rest and sends nothing', async () => {
|
||||
await paired();
|
||||
await listening();
|
||||
h.stt.next({ text: 'Pepper' });
|
||||
say(0.5);
|
||||
await until('recording', () => phase() === 'listening');
|
||||
await pause(300);
|
||||
device.silence(0.2);
|
||||
await until('ready', () => phase() === 'ready');
|
||||
expect(posts('/v1/turns')).toBe(0);
|
||||
expect(runsPosted()).toEqual([]);
|
||||
await listening();
|
||||
});
|
||||
|
||||
it('tapping still works while listening, and a tap during a check wins over what was heard', async () => {
|
||||
await paired();
|
||||
await listening();
|
||||
h.stt.next({ text: 'Wendy, ignore this', delayMs: 250 }, { text: 'the tapped question' });
|
||||
say();
|
||||
await until('check started', () => posts('/v1/wake') === 1);
|
||||
device.tap();
|
||||
expect(phase()).toBe('listening');
|
||||
device.speak(1);
|
||||
await pause(350); // the check has come back by now
|
||||
expect(phase()).toBe('listening');
|
||||
expect(device.micOpens).toBe(1);
|
||||
device.tap();
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(h.hermes.executedBy).toEqual([null]);
|
||||
expect(snapshot.lastTurn?.input_text).toBe('the tapped question');
|
||||
});
|
||||
|
||||
it('a bridge that cannot do it ends hands free for the session, and says so', async () => {
|
||||
wakeRoute = 'not_found';
|
||||
await paired();
|
||||
await listening();
|
||||
say();
|
||||
await until('microphone closed', () => !device.micOpen);
|
||||
expect(snapshot.wake).toEqual({ available: false, enabled: false, listening: false });
|
||||
expect(device.frame.body).toBe('Pepper\n\nHands free is not available.');
|
||||
// Tap to ask still works.
|
||||
device.tap();
|
||||
await until('recording', () => phase() === 'listening' && device.micOpen);
|
||||
});
|
||||
|
||||
it('a refused microphone is retried, and one that goes quiet is reopened', async () => {
|
||||
device = new FakeDevice();
|
||||
device.micAllowed = false;
|
||||
controller = makeController(device);
|
||||
await controller.start();
|
||||
await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2');
|
||||
await pause(100);
|
||||
expect(device.frame.status).not.toContain('●');
|
||||
device.micAllowed = true;
|
||||
await listening();
|
||||
const opens = device.micOpens;
|
||||
// No frames at all: the watchdog closes and reopens it.
|
||||
await until('reopened', () => device.micOpens > opens, 2000);
|
||||
expect(device.micOpen).toBe(true);
|
||||
});
|
||||
|
||||
it('closes the microphone when the glasses disconnect and when the app stops', async () => {
|
||||
await paired();
|
||||
await listening();
|
||||
device.connection(false);
|
||||
await until('closed on disconnect', () => !device.micOpen);
|
||||
device.connection(true);
|
||||
await listening();
|
||||
await controller.stop();
|
||||
expect(device.micOpen).toBe(false);
|
||||
});
|
||||
|
||||
it('without the option nothing listens: the microphone opens only on a tap', async () => {
|
||||
extras = { wake: null, idleExit: null };
|
||||
await paired();
|
||||
await pause(100);
|
||||
expect(device.micOpens).toBe(0);
|
||||
expect(snapshot.wake).toEqual({ available: false, enabled: false, listening: false });
|
||||
expect(device.frame.body).toBe('Pepper\n\nReady.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('glasses: the opening menu', () => {
|
||||
beforeEach(async () => {
|
||||
sent = [];
|
||||
wakeRoute = 'real';
|
||||
extras = { menu: true, idleExit: null };
|
||||
await harness();
|
||||
});
|
||||
afterEach(async () => {
|
||||
await controller?.stop();
|
||||
});
|
||||
async function atMenu(): Promise<void> {
|
||||
device = new FakeDevice();
|
||||
controller = makeController(device);
|
||||
await controller.start();
|
||||
await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2');
|
||||
expect(phase()).toBe('menu');
|
||||
}
|
||||
|
||||
it('opens on the menu with Hands free first, microphone closed, nothing sent', async () => {
|
||||
await atMenu();
|
||||
expect(device.frame).toEqual({ body: 'Hermeven\n\n> Hands free\n Agents', status: 'Tap: open · Swipe: move · 2×: exit' });
|
||||
await pause(80);
|
||||
expect(device.micOpens).toBe(0);
|
||||
expect(snapshot.wake).toEqual({ available: true, enabled: false, listening: false });
|
||||
device.speak(1);
|
||||
expect(posts('/v1/wake') + posts('/v1/turns') + posts('/v1/conversations')).toBe(0);
|
||||
});
|
||||
|
||||
it('one tap on the menu is hands free: listening, a name works, and double tap at Ready returns to the menu and closes the microphone', async () => {
|
||||
await atMenu();
|
||||
device.tap();
|
||||
expect(phase()).toBe('ready');
|
||||
await listening();
|
||||
expect(device.frame).toEqual({
|
||||
body: 'Pepper\n\nListening. Say a name, then your question:\nPepper · Wendy · Cody',
|
||||
status: '● Tap: ask · Swipe: agent · 2×: menu',
|
||||
});
|
||||
h.stt.next({ text: 'Wendy, hello' });
|
||||
say();
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy']);
|
||||
await listening();
|
||||
device.doubleTap(); // answer -> Ready, still hands free
|
||||
expect(phase()).toBe('ready');
|
||||
expect(snapshot.wake.enabled).toBe(true);
|
||||
device.doubleTap(); // Ready -> menu
|
||||
expect(phase()).toBe('menu');
|
||||
await until('microphone closed', () => !device.micOpen);
|
||||
expect(device.exitRequests).toBe(0);
|
||||
// Speech at the menu goes nowhere.
|
||||
const checks = posts('/v1/wake');
|
||||
device.speak(1);
|
||||
await pause(60);
|
||||
expect(posts('/v1/wake')).toBe(checks);
|
||||
// The menu is the root page: double tap there asks the system to exit.
|
||||
device.doubleTap();
|
||||
expect(device.exitRequests).toBe(1);
|
||||
});
|
||||
|
||||
it('Agents is the tap-to-ask app as before: no listening, the chosen agent, and it leaves when idle', async () => {
|
||||
extras = { menu: true, idleExit: { ready: 150, answer: 150, message: 150 } };
|
||||
await atMenu();
|
||||
device.swipeDown();
|
||||
expect(device.frame.body).toBe('Hermeven\n\n Hands free\n> Agents');
|
||||
device.swipeDown(); // already on the last entry
|
||||
device.tap();
|
||||
expect(device.frame).toEqual({ body: 'Pepper\n\nReady.', status: 'Tap: ask · Swipe: agent · 2×: menu' });
|
||||
device.swipeDown();
|
||||
expect(device.frame.body).toBe('Wendy\n\nReady.');
|
||||
say();
|
||||
await pause(60);
|
||||
expect(device.micOpens).toBe(0);
|
||||
expect(posts('/v1/wake')).toBe(0);
|
||||
h.stt.next({ text: 'a tapped question' });
|
||||
device.tap();
|
||||
await until('recording', () => phase() === 'listening' && device.micOpen);
|
||||
device.speak(1);
|
||||
device.tap();
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy']);
|
||||
await until('microphone closed', () => !device.micOpen);
|
||||
expect(device.frame.status).not.toContain('●');
|
||||
await until('left the glasses', () => device.exits === 1);
|
||||
});
|
||||
|
||||
it('an untouched menu leaves the glasses; hands free does not', async () => {
|
||||
extras = { menu: true, idleExit: { ready: 80, answer: 80, message: 80 } };
|
||||
await atMenu();
|
||||
await until('left the glasses', () => device.exits === 1);
|
||||
await controller.stop();
|
||||
await atMenu();
|
||||
device.tap();
|
||||
await listening();
|
||||
await pause(250);
|
||||
expect(device.exitAttempts).toBe(0);
|
||||
});
|
||||
|
||||
it('where hands free cannot work the menu offers Agents only', async () => {
|
||||
extras = { menu: true, wake: null, idleExit: null };
|
||||
await atMenu();
|
||||
expect(device.frame).toEqual({ body: 'Hermeven\n\n> Agents', status: 'Tap: open · Double-tap: exit' });
|
||||
device.tap();
|
||||
expect(device.frame.body).toBe('Pepper\n\nReady.');
|
||||
expect(device.micOpens).toBe(0);
|
||||
});
|
||||
|
||||
it('a question still running when the app was closed is shown on reopening, not the menu; a typed question works from the menu', async () => {
|
||||
await atMenu();
|
||||
controller.askText('typed from the phone');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(snapshot.wake.enabled).toBe(false);
|
||||
device.doubleTap();
|
||||
device.doubleTap();
|
||||
expect(phase()).toBe('menu');
|
||||
h.hermes.next({ kind: 'complete', afterMs: 400 });
|
||||
const polls = () => sent.filter((r) => r.method === 'GET' && r.path.startsWith('/v1/turns/')).length;
|
||||
const before = polls();
|
||||
controller.askText('a slow one');
|
||||
// Accepted by the bridge and being polled: only then is there a turn to come back to.
|
||||
await until('accepted and polling', () => phase() === 'thinking' && polls() > before);
|
||||
await controller.stop();
|
||||
const reborn = new FakeDevice();
|
||||
for (const [k, v] of device.storage) reborn.storage.set(k, v);
|
||||
device = reborn;
|
||||
controller = makeController(device);
|
||||
await controller.start();
|
||||
expect(phase()).toBe('thinking');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(device.micOpens).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('bridge: POST /v1/transcribe', () => {
|
||||
const clip = (token: string | undefined, said: string) => {
|
||||
h.stt.next({ text: said });
|
||||
return h.api('POST', `/v1/transcribe?${wakeQuery()}`, { token, body: syntheticPcm(1) });
|
||||
};
|
||||
|
||||
it('returns the words, creates nothing, and logs none of them', async () => {
|
||||
await harness();
|
||||
const { token } = await h.pair();
|
||||
const res = await clip(token, ' what is on my calendar ');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ schema_version: SCHEMA_VERSION, text: 'what is on my calendar' });
|
||||
expect(h.hermes.requests.filter((r) => r.method === 'POST')).toEqual([]);
|
||||
expect(h.logs.join('\n')).not.toContain('calendar');
|
||||
});
|
||||
|
||||
it('needs a credential and well-formed audio; a failed transcription is an empty preview; no speech-to-text is not_found', async () => {
|
||||
await harness();
|
||||
const { token } = await h.pair();
|
||||
expect((await h.api('POST', `/v1/transcribe?${wakeQuery()}`, { body: syntheticPcm(1) })).status).toBe(401);
|
||||
expect((await h.api('POST', `/v1/transcribe?${wakeQuery({ channels: '2' })}`, { token, body: syntheticPcm(1) })).status).toBe(400);
|
||||
expect((await h.api('POST', `/v1/transcribe?${wakeQuery()}`, { token, body: Buffer.alloc(5) })).status).toBe(400);
|
||||
h.stt.next({ status: 500 });
|
||||
expect((await h.api('POST', `/v1/transcribe?${wakeQuery()}`, { token, body: syntheticPcm(1) })).body).toEqual({ schema_version: SCHEMA_VERSION, text: '' });
|
||||
await h.close();
|
||||
await harness(AGENT_ENV, { stt: false });
|
||||
expect((await h.api('POST', `/v1/transcribe?${wakeQuery()}`, { token: (await h.pair()).token, body: syntheticPcm(1) })).status).toBe(404);
|
||||
});
|
||||
|
||||
it('one at a time per device, with its own per-minute budget', async () => {
|
||||
await harness({ ...AGENT_ENV, HERMEVEN_PREVIEWS_PER_MINUTE: '2' });
|
||||
const { token } = await h.pair();
|
||||
h.stt.next({ text: 'a', delayMs: 150 });
|
||||
const first = h.api('POST', `/v1/transcribe?${wakeQuery()}`, { token, body: syntheticPcm(1) });
|
||||
await new Promise((r) => setTimeout(r, 40));
|
||||
expect((await clip(token, 'b')).status).toBe(429);
|
||||
expect((await first).status).toBe(200);
|
||||
expect((await clip(token, 'c')).status).toBe(200);
|
||||
expect((await clip(token, 'd')).status).toBe(429);
|
||||
expect((await wake(token, 'Wendy, still fine')).status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('glasses: words shown while recording', () => {
|
||||
beforeEach(async () => {
|
||||
sent = [];
|
||||
wakeRoute = 'real';
|
||||
extras = { wake: null, idleExit: null, livePreview: { firstMs: 300, stepMs: 300, pauseMs: 200 } };
|
||||
await harness();
|
||||
});
|
||||
afterEach(async () => {
|
||||
await controller?.stop();
|
||||
});
|
||||
|
||||
it('the words appear as the recording grows, and what the agent is sent is the final transcript, not a preview', async () => {
|
||||
await paired();
|
||||
h.stt.next({ text: 'what is' }, { text: 'what is on my calender' }, { text: 'What is on my calendar?' });
|
||||
h.hermes.next({ kind: 'complete', afterMs: 250 });
|
||||
device.tap();
|
||||
await until('recording', () => phase() === 'listening' && device.micOpen);
|
||||
expect(device.frame.body).toContain('Recording stops by itself');
|
||||
device.speak(0.5);
|
||||
await until('first words', () => device.frame.body === 'Pepper is listening…\n\nwhat is');
|
||||
expect(device.frame.status).toContain('● REC');
|
||||
device.speak(0.5);
|
||||
await until('more words', () => device.frame.body === 'Pepper is listening…\n\nwhat is on my calender');
|
||||
device.tap();
|
||||
// The last preview stays up while the real transcription runs...
|
||||
expect(device.frame.body).toBe('Transcribing…\n\nwhat is on my calender');
|
||||
// ...and is replaced by what the bridge actually sent to the agent.
|
||||
await until('thinking', () => device.frame.body === 'Pepper is thinking…\n\nHeard: What is on my calendar?');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(snapshot.lastTurn?.input_text).toBe('What is on my calendar?');
|
||||
expect(posts('/v1/transcribe')).toBe(2);
|
||||
expect(posts('/v1/turns')).toBe(1);
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
});
|
||||
|
||||
it('a long recording shows its newest words, within the screen', async () => {
|
||||
await paired();
|
||||
const long = Array.from({ length: 150 }, (_, i) => `word${i}`).join(' ');
|
||||
h.stt.next({ text: long });
|
||||
device.tap();
|
||||
await until('recording', () => phase() === 'listening' && device.micOpen);
|
||||
device.speak(0.5);
|
||||
await until('preview', () => snapshot.state.preview !== null);
|
||||
const body = device.frame.body;
|
||||
expect(body.startsWith('Pepper is listening…\n\n… ')).toBe(true);
|
||||
expect(body.endsWith('word149')).toBe(true);
|
||||
expect(measureTextWrap(body, 568).lineCount).toBeLessThanOrEqual(9);
|
||||
device.doubleTap();
|
||||
});
|
||||
|
||||
it('a preview that comes back after cancel, or for an earlier recording, is not drawn', async () => {
|
||||
await paired();
|
||||
h.stt.next({ text: 'late words', delayMs: 200 });
|
||||
device.tap();
|
||||
await until('recording', () => phase() === 'listening' && device.micOpen);
|
||||
device.speak(0.5);
|
||||
await until('preview requested', () => posts('/v1/transcribe') === 1);
|
||||
device.doubleTap();
|
||||
expect(phase()).toBe('cancelled');
|
||||
device.tap();
|
||||
await until('recording again', () => phase() === 'listening' && device.micOpen);
|
||||
await pause(300);
|
||||
expect(snapshot.state.preview).toBeNull();
|
||||
expect(device.frame.body).not.toContain('late words');
|
||||
device.doubleTap();
|
||||
});
|
||||
|
||||
it('a bridge without previews just records as before; typed questions never say "Heard"', async () => {
|
||||
await controller?.stop();
|
||||
await h.close();
|
||||
await harness(AGENT_ENV, { stt: false });
|
||||
await paired();
|
||||
device.tap();
|
||||
await until('recording', () => phase() === 'listening' && device.micOpen);
|
||||
device.speak(1);
|
||||
await pause(80);
|
||||
expect(posts('/v1/transcribe')).toBe(0);
|
||||
device.doubleTap();
|
||||
h.hermes.next({ kind: 'complete', afterMs: 200 });
|
||||
controller.askText('typed');
|
||||
await until('thinking', () => phase() === 'thinking');
|
||||
await pause(80);
|
||||
expect(device.frame.body).toBe('Pepper is thinking…');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
});
|
||||
|
||||
it('is for Agents only: in hands free no recording is previewed, by name or by tap', async () => {
|
||||
extras = { livePreview: { firstMs: 300, stepMs: 300, pauseMs: 200 } };
|
||||
await paired();
|
||||
await listening();
|
||||
h.stt.next({ text: 'Wendy' }, { text: 'are you there' }, { text: 'a tapped one' });
|
||||
say(0.5);
|
||||
await until('recording for Wendy', () => phase() === 'listening');
|
||||
device.speak(1.2);
|
||||
await pause(80);
|
||||
expect(device.frame.body).toBe('Wendy is listening…\n\nAsk your question. It is sent when you stop speaking.');
|
||||
device.silence(1.4);
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(snapshot.lastTurn?.input_text).toBe('are you there');
|
||||
await listening();
|
||||
device.tap();
|
||||
await until('recording', () => phase() === 'listening');
|
||||
device.speak(1.2);
|
||||
await pause(80);
|
||||
device.tap();
|
||||
await until('second answer', () => phase() === 'answer' && h.hermes.executions === 2);
|
||||
expect(snapshot.lastTurn?.input_text).toBe('a tapped one');
|
||||
expect(posts('/v1/transcribe')).toBe(0);
|
||||
// What was sent is still shown while the agent works: that is the turn's own transcript.
|
||||
expect(h.stt.calls).toBe(3);
|
||||
});
|
||||
});
|
||||
@@ -31,6 +31,7 @@ let automation = '';
|
||||
let lastConsoleId = 0;
|
||||
const consoleLines: string[] = [];
|
||||
let audioEchoLines = 0;
|
||||
let simulatorExitOutcome = 'not run';
|
||||
|
||||
async function freePort(): Promise<number> {
|
||||
return new Promise((resolvePort) => {
|
||||
@@ -138,6 +139,20 @@ async function screenshot(name: string) {
|
||||
return { png, ...decodePng(png) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Take screenshots until one satisfies `ready`, and return it (or the last one, for the
|
||||
* assertion to fail on). The simulator draws some time after the app asks, and how long varies
|
||||
* with how many updates are queued, so a fixed wait before a single screenshot is a guess.
|
||||
*/
|
||||
async function screenshotWhen(name: string, ready: (shot: Awaited<ReturnType<typeof screenshot>>) => boolean, timeoutMs = 8000) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
for (;;) {
|
||||
const shot = await screenshot(name);
|
||||
if (ready(shot) || Date.now() > deadline) return shot;
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
}
|
||||
|
||||
/** Lit pixels inside a horizontal band of the canvas. */
|
||||
function litInBand(shot: { rows: Buffer[]; width: number }, fromY: number, toY: number): number {
|
||||
let lit = 0;
|
||||
@@ -145,6 +160,38 @@ function litInBand(shot: { rows: Buffer[]; width: number }, fromY: number, toY:
|
||||
return lit;
|
||||
}
|
||||
|
||||
let pageOriginForRelaunch = '';
|
||||
|
||||
/** Start a simulator on the page. `idleExit` is the development-only switch read by main.ts. */
|
||||
async function launchSimulator(idleExit: 'off' | 'fast', code: string, legacy = true): Promise<void> {
|
||||
const pageOrigin = pageOriginForRelaunch;
|
||||
const automationPort = await freePort();
|
||||
automation = `http://127.0.0.1:${automationPort}`;
|
||||
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.
|
||||
// wake=off, menu=off: this suite covers the tap path and idle exit from Ready, as before the menu.
|
||||
// `legacy = false` launches the app as it ships: opening menu, hands free and live preview on.
|
||||
const url = `${pageOrigin}/?idleExit=${idleExit}${legacy ? '&wake=off&menu=off&preview=off' : ''}&bridge=${encodeURIComponent(h.url)}&pair=${encodeURIComponent(code)}`;
|
||||
// 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'], {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
cwd: artifacts,
|
||||
});
|
||||
sim.stdout!.on('data', (d) => (simOutput += String(d)));
|
||||
sim.stderr!.on('data', (d) => (simOutput += String(d)));
|
||||
|
||||
const deadline = Date.now() + 30_000;
|
||||
for (;;) {
|
||||
try {
|
||||
if ((await fetch(`${automation}/api/ping`)).ok) break;
|
||||
} catch {
|
||||
/* not up yet */
|
||||
}
|
||||
if (Date.now() > deadline) throw new Error(`simulator automation API did not start.\n${simOutput.slice(-2000)}`);
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
mkdirSync(artifacts, { recursive: true });
|
||||
const vitePort = await freePort();
|
||||
@@ -163,28 +210,8 @@ beforeAll(async () => {
|
||||
});
|
||||
const { code } = h.bridge.devices.createPairingCode();
|
||||
|
||||
const automationPort = await freePort();
|
||||
automation = `http://127.0.0.1:${automationPort}`;
|
||||
const bin = require.resolve('@evenrealities/sim-linux-x64/bin/evenhub-simulator');
|
||||
const url = `${pageOrigin}/?bridge=${encodeURIComponent(h.url)}&pair=${encodeURIComponent(code)}`;
|
||||
// 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'], {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
cwd: artifacts,
|
||||
});
|
||||
sim.stdout!.on('data', (d) => (simOutput += String(d)));
|
||||
sim.stderr!.on('data', (d) => (simOutput += String(d)));
|
||||
|
||||
const deadline = Date.now() + 30_000;
|
||||
for (;;) {
|
||||
try {
|
||||
if ((await fetch(`${automation}/api/ping`)).ok) break;
|
||||
} catch {
|
||||
/* not up yet */
|
||||
}
|
||||
if (Date.now() > deadline) throw new Error(`simulator automation API did not start.\n${simOutput.slice(-2000)}`);
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
pageOriginForRelaunch = pageOrigin;
|
||||
await launchSimulator('off', code);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
@@ -251,21 +278,21 @@ describe('Even Hub simulator 0.9.5', () => {
|
||||
expect(h.hermes.lastRun()!.input).toBe('simulated question');
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
|
||||
await new Promise((r) => setTimeout(r, 800));
|
||||
const page1 = await screenshot('03-answer-page-1');
|
||||
const page1 = await screenshotWhen('03-answer-page-1', (shot) => litInBand(shot, 0, 251) > 2000);
|
||||
expect(litInBand(page1, 0, 251)).toBeGreaterThan(2000);
|
||||
// Let the drawing settle, so the next scenario compares against a finished page.
|
||||
await new Promise((r) => setTimeout(r, 800));
|
||||
expect(consoleLines.slice(mark).some((l) => /answer laid out on [2-9] page/.test(l))).toBe(true);
|
||||
});
|
||||
|
||||
it('swipe down turns the page, swipe up returns, and the page fits without firmware scrolling', async () => {
|
||||
const page1 = await screenshot('04-before-swipe');
|
||||
await input('down');
|
||||
await new Promise((r) => setTimeout(r, 900));
|
||||
const page2 = await screenshot('05-answer-page-2');
|
||||
const page2 = await screenshotWhen('05-answer-page-2', (shot) => !shot.png.equals(page1.png));
|
||||
expect(page2.png.equals(page1.png)).toBe(false);
|
||||
await new Promise((r) => setTimeout(r, 600));
|
||||
await input('up');
|
||||
await new Promise((r) => setTimeout(r, 900));
|
||||
const back = await screenshot('06-answer-page-1-again');
|
||||
const back = await screenshotWhen('06-answer-page-1-again', (shot) => shot.png.equals(page1.png));
|
||||
expect(back.png.equals(page1.png)).toBe(true);
|
||||
});
|
||||
|
||||
@@ -304,9 +331,125 @@ describe('Even Hub simulator 0.9.5', () => {
|
||||
expect(h.hermes.executions).toBe(2);
|
||||
});
|
||||
|
||||
it('hold to talk: a long press starts recording and releasing it sends', async () => {
|
||||
h.stt.next({ text: 'simulated held question' });
|
||||
const before = h.hermes.executions;
|
||||
const mark = consoleLines.length;
|
||||
await input('long_press');
|
||||
await waitConsole('-> listening', 10_000, mark);
|
||||
// Held well past the push-to-talk threshold. (With the unpaced null audio device the capture
|
||||
// cap may be reached first; either way the recording must end and be answered once.)
|
||||
await new Promise((r) => setTimeout(r, 1000));
|
||||
await input('long_press_release');
|
||||
await waitConsole('-> answer', 20_000, mark);
|
||||
expect(h.hermes.executions).toBe(before + 1);
|
||||
expect(h.hermes.lastRun()!.input).toBe('simulated held question');
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
await screenshot('09-hold-to-talk-answer');
|
||||
// Leave the app at rest for the checks that follow.
|
||||
await input('double_click');
|
||||
await waitConsole('state: answer -> ready', 10_000, mark);
|
||||
});
|
||||
|
||||
it('no uncaught errors or failed fetches were reported by the webview', async () => {
|
||||
await pumpConsole();
|
||||
const problems = consoleLines.filter((l) => /\[uncaught\]|\[unhandledrejection\]|\[fetch\]/.test(l));
|
||||
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);
|
||||
// No gesture and no launch source: it leaves from Ready after the (shortened) wait.
|
||||
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);
|
||||
|
||||
it('as shipped: opens on the menu; a tap starts hands free with the microphone open; double tap returns to the menu and closes it; Agents does not listen', async () => {
|
||||
// A third simulator, with nothing switched off. The microphone is alsa:null (silence), so
|
||||
// this shows the menu, the gestures and the microphone opening and closing through the
|
||||
// real SDK bridge. It shows nothing about hearing a name: no speech exists here.
|
||||
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;
|
||||
const sttBefore = h.stt.calls;
|
||||
const runsBefore = h.hermes.executions;
|
||||
await launchSimulator('off', h.bridge.devices.createPairingCode().code, false);
|
||||
await waitConsole('hud: HUD page created', 30_000, from);
|
||||
await waitConsole('-> menu', 20_000, from);
|
||||
await new Promise((r) => setTimeout(r, 800));
|
||||
const menu = await screenshot('10-menu');
|
||||
expect(litInBand(menu, 0, 120)).toBeGreaterThan(200);
|
||||
expect(litInBand(menu, 251, 288)).toBeGreaterThan(100);
|
||||
// Nothing listens on the menu.
|
||||
expect(consoleLines.slice(from).some((l) => l.includes('wake: listening for a name'))).toBe(false);
|
||||
|
||||
// Swiping moves the marker: the picture changes, and changes back.
|
||||
await input('down');
|
||||
await new Promise((r) => setTimeout(r, 600));
|
||||
const second = await screenshot('11-menu-agents-selected');
|
||||
expect(second.png.equals(menu.png)).toBe(false);
|
||||
await input('up');
|
||||
await new Promise((r) => setTimeout(r, 600));
|
||||
expect((await screenshot('12-menu-again')).png.equals(menu.png)).toBe(true);
|
||||
|
||||
// First entry: hands free.
|
||||
await input('click');
|
||||
await waitConsole('state: menu -> ready', 10_000, from);
|
||||
await waitConsole('wake: listening for a name', 10_000, from);
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
const handsFree = await screenshot('13-hands-free');
|
||||
expect(litInBand(handsFree, 251, 288)).toBeGreaterThan(100);
|
||||
await pumpConsole();
|
||||
// Silence is never sent anywhere.
|
||||
expect(h.stt.calls).toBe(sttBefore);
|
||||
|
||||
// Back to the menu: the microphone closes.
|
||||
let mark = consoleLines.length;
|
||||
await input('double_click');
|
||||
await waitConsole('state: ready -> menu', 10_000, mark);
|
||||
await waitConsole('wake: stopped listening', 10_000, mark);
|
||||
|
||||
// Second entry: Agents. No listening.
|
||||
mark = consoleLines.length;
|
||||
await input('down');
|
||||
await input('click');
|
||||
await waitConsole('state: menu -> ready', 10_000, mark);
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
await pumpConsole();
|
||||
expect(consoleLines.slice(mark).some((l) => l.includes('wake: listening for a name'))).toBe(false);
|
||||
await screenshot('14-agents-ready');
|
||||
|
||||
expect(h.stt.calls).toBe(sttBefore);
|
||||
expect(h.hermes.executions).toBe(runsBefore);
|
||||
const problems = consoleLines.slice(from).filter((l) => /\[uncaught\]|\[unhandledrejection\]|\[fetch\]/.test(l));
|
||||
expect(problems).toEqual([]);
|
||||
}, 120_000);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user