CODY-016. The SDK pushes the launch source once, early. The Even adapter now subscribes in its constructor, remembers the value and replays it to a listener that subscribes later. appMenu still does not arm idle exit. CODY-018. exitNow() returns whether the host confirmed. The adapter keeps at most one shutdown call in flight (through the same queue as every other host call), lets a repeat request wait on that call, and never calls the host again after a confirmed exit, including one confirmed late. The controller marks itself as gone only on confirmation or on a system_exit/abnormal_exit event; otherwise it retries after 3 s, at most 4 attempts in a row, under the same resting-screen and phone-grace guards, and starts again after activity. CODY-017. README: one owner-reported locked-phone success; pocketed, five-minute and ten-cycle runs unverified. Tests: production-adapter tests with a stand-in host, including the default 30 s under a fake clock; a simulator scenario that performs the real exit (development-only ?idleExit=fast). Not reviewed. 0.1.1 is not uploaded. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
380 lines
17 KiB
TypeScript
380 lines
17 KiB
TypeScript
import { spawn, type ChildProcess } from 'node:child_process';
|
|
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
import { createRequire } from 'node:module';
|
|
import { createServer as createNetServer } from 'node:net';
|
|
import { dirname, resolve } from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { inflateSync } from 'node:zlib';
|
|
import { createServer, type ViteDevServer } from 'vite';
|
|
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
import { createHarness, type Harness } from '../integration/harness.ts';
|
|
|
|
/**
|
|
* SIMULATOR TEST: the real client, loaded in the official Even Hub simulator
|
|
* (@evenrealities/evenhub-simulator), driven through its automation API,
|
|
* talking over HTTP to the real bridge. Hermes and the speech recogniser are
|
|
* TEST FAKES, and the simulator's audio input is ALSA's null device (silence),
|
|
* so no real microphone is opened and no real speech is transcribed.
|
|
*
|
|
* This is simulator evidence. It is not device evidence: Even documents that
|
|
* the simulator differs from hardware in font rendering, events and lifecycle.
|
|
*/
|
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
const artifacts = resolve(here, '.artifacts');
|
|
const require = createRequire(import.meta.url);
|
|
|
|
let h: Harness;
|
|
let vite: ViteDevServer;
|
|
let sim: ChildProcess;
|
|
let simOutput = '';
|
|
let automation = '';
|
|
let lastConsoleId = 0;
|
|
const consoleLines: string[] = [];
|
|
let audioEchoLines = 0;
|
|
let simulatorExitOutcome = 'not run';
|
|
|
|
async function freePort(): Promise<number> {
|
|
return new Promise((resolvePort) => {
|
|
const srv = createNetServer();
|
|
srv.listen(0, '127.0.0.1', () => {
|
|
const { port } = srv.address() as { port: number };
|
|
srv.close(() => resolvePort(port));
|
|
});
|
|
});
|
|
}
|
|
|
|
async function pumpConsole(): Promise<void> {
|
|
const res = await fetch(`${automation}/api/console?since_id=${lastConsoleId}`);
|
|
const body = (await res.json()) as { entries: Array<{ id: number; level: string; message: string }> };
|
|
for (const entry of body.entries) {
|
|
lastConsoleId = Math.max(lastConsoleId, entry.id);
|
|
// In the simulator every hub event, including each raw PCM frame, is echoed to the webview
|
|
// console with an "[EvenAppBridge]" prefix. Those lines are counted, not kept.
|
|
if (entry.message.includes('audioPcm')) {
|
|
audioEchoLines += 1;
|
|
continue;
|
|
}
|
|
consoleLines.push(`${entry.level}: ${entry.message}`.slice(0, 600));
|
|
}
|
|
}
|
|
|
|
async function waitConsole(needle: string, timeoutMs = 20_000, from = 0): Promise<void> {
|
|
const deadline = Date.now() + timeoutMs;
|
|
for (;;) {
|
|
await pumpConsole();
|
|
if (consoleLines.slice(from).some((l) => l.includes(needle))) return;
|
|
if (Date.now() > deadline) {
|
|
throw new Error(`simulator console never showed "${needle}".\nConsole:\n${consoleLines.join('\n')}\nSimulator output:\n${simOutput.slice(-2000)}`);
|
|
}
|
|
await new Promise((r) => setTimeout(r, 150));
|
|
}
|
|
}
|
|
|
|
async function input(action: string): Promise<void> {
|
|
const res = await fetch(`${automation}/api/input`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ action }),
|
|
});
|
|
expect(res.status, `input ${action}`).toBe(200);
|
|
}
|
|
|
|
/** Minimal RGBA8 PNG decoder (non-interlaced), enough to count lit pixels. */
|
|
function decodePng(png: Buffer): { width: number; height: number; lit: number; rows: Buffer[] } {
|
|
let offset = 8;
|
|
let width = 0;
|
|
let height = 0;
|
|
let colorType = 0;
|
|
const idat: Buffer[] = [];
|
|
while (offset < png.length) {
|
|
const length = png.readUInt32BE(offset);
|
|
const type = png.toString('ascii', offset + 4, offset + 8);
|
|
const data = png.subarray(offset + 8, offset + 8 + length);
|
|
if (type === 'IHDR') {
|
|
width = data.readUInt32BE(0);
|
|
height = data.readUInt32BE(4);
|
|
colorType = data[9]!;
|
|
} else if (type === 'IDAT') idat.push(data);
|
|
offset += 12 + length;
|
|
}
|
|
expect(colorType, 'glasses screenshot should be RGBA').toBe(6);
|
|
const raw = inflateSync(Buffer.concat(idat));
|
|
const bpp = 4;
|
|
const stride = width * bpp;
|
|
const rows: Buffer[] = [];
|
|
let prev = Buffer.alloc(stride);
|
|
let lit = 0;
|
|
for (let y = 0; y < height; y++) {
|
|
const filter = raw[y * (stride + 1)]!;
|
|
const line = Buffer.from(raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1)));
|
|
for (let x = 0; x < stride; x++) {
|
|
const a = x >= bpp ? line[x - bpp]! : 0;
|
|
const b = prev[x]!;
|
|
const c = x >= bpp ? prev[x - bpp]! : 0;
|
|
let add = 0;
|
|
if (filter === 1) add = a;
|
|
else if (filter === 2) add = b;
|
|
else if (filter === 3) add = (a + b) >> 1;
|
|
else if (filter === 4) {
|
|
const p = a + b - c;
|
|
const pa = Math.abs(p - a);
|
|
const pb = Math.abs(p - b);
|
|
const pc = Math.abs(p - c);
|
|
add = pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
|
|
}
|
|
line[x] = (line[x]! + add) & 0xff;
|
|
}
|
|
for (let x = 0; x < width; x++) if (line[x * 4 + 3]! > 0) lit += 1;
|
|
rows.push(line);
|
|
prev = line;
|
|
}
|
|
return { width, height, lit, rows };
|
|
}
|
|
|
|
async function screenshot(name: string) {
|
|
const res = await fetch(`${automation}/api/screenshot/glasses`);
|
|
expect(res.status).toBe(200);
|
|
const png = Buffer.from(await res.arrayBuffer());
|
|
writeFileSync(resolve(artifacts, `${name}.png`), png);
|
|
return { png, ...decodePng(png) };
|
|
}
|
|
|
|
/** Lit pixels inside a horizontal band of the canvas. */
|
|
function litInBand(shot: { rows: Buffer[]; width: number }, fromY: number, toY: number): number {
|
|
let lit = 0;
|
|
for (let y = fromY; y < toY; y++) for (let x = 0; x < shot.width; x++) if (shot.rows[y]![x * 4 + 3]! > 0) lit += 1;
|
|
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): 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.
|
|
const url = `${pageOrigin}/?idleExit=${idleExit}&bridge=${encodeURIComponent(h.url)}&pair=${encodeURIComponent(code)}`;
|
|
// alsa:null yields silence: the simulator never opens a real microphone in this test.
|
|
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();
|
|
vite = await createServer({
|
|
root: resolve(here, '../../apps/even-client'),
|
|
configFile: resolve(here, '../../apps/even-client/vite.config.ts'),
|
|
server: { host: '127.0.0.1', port: vitePort, strictPort: true },
|
|
logLevel: 'error',
|
|
});
|
|
await vite.listen();
|
|
const pageOrigin = `http://127.0.0.1:${vitePort}`;
|
|
|
|
h = await createHarness({
|
|
env: { HERMEVEN_ALLOWED_ORIGINS: pageOrigin, HERMEVEN_CAPTURE_MAX_SECONDS: '120' },
|
|
timing: { agentDeadlineMs: 20_000, transcribeDeadlineMs: 10_000 },
|
|
});
|
|
const { code } = h.bridge.devices.createPairingCode();
|
|
|
|
pageOriginForRelaunch = pageOrigin;
|
|
await launchSimulator('off', code);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
sim?.kill('SIGTERM');
|
|
await new Promise((r) => setTimeout(r, 300));
|
|
if (sim && sim.exitCode === null) sim.kill('SIGKILL');
|
|
await vite?.close();
|
|
await h?.close();
|
|
writeFileSync(
|
|
resolve(artifacts, 'console.log'),
|
|
`${consoleLines.join('\n')}\n(audio frame echo lines omitted: ${audioEchoLines})\n`,
|
|
);
|
|
});
|
|
|
|
describe('Even Hub simulator 0.9.5', () => {
|
|
it('boots through the real SDK bridge, creates the HUD page and pairs', async () => {
|
|
await waitConsole('hud: HUD page created', 30_000);
|
|
await waitConsole('state: unpaired -> ready');
|
|
expect(consoleLines.some((l) => l.includes('HUD page was refused'))).toBe(false);
|
|
await new Promise((r) => setTimeout(r, 800));
|
|
const shot = await screenshot('01-ready');
|
|
expect([shot.width, shot.height]).toEqual([576, 288]);
|
|
// Body text at the top and the status bar in the bottom band are both drawn.
|
|
expect(litInBand(shot, 0, 120)).toBeGreaterThan(200);
|
|
expect(litInBand(shot, 251, 288)).toBeGreaterThan(100);
|
|
});
|
|
|
|
it('tap opens the microphone, audio frames arrive as 16 kHz PCM, tap submits, the answer is drawn', async () => {
|
|
const answer = Array.from({ length: 40 }, (_, i) => `Simulator sentence ${i + 1} of the answer.`).join(' ');
|
|
h.stt.next({ text: 'simulated question' });
|
|
h.hermes.next({ kind: 'complete', afterMs: 600, output: answer });
|
|
|
|
const mark = consoleLines.length;
|
|
await input('click');
|
|
await waitConsole('state: ready -> listening', 10_000, mark);
|
|
await new Promise((r) => setTimeout(r, 300));
|
|
const recording = await screenshot('02-listening');
|
|
expect(litInBand(recording, 251, 288)).toBeGreaterThan(100);
|
|
|
|
// Second tap = stop and send. With the unpaced null audio device the capture cap can be
|
|
// reached first, in which case this tap is a harmless no-op; both are valid ways to end a
|
|
// capture and the assertions below hold for either.
|
|
await input('click');
|
|
await waitConsole('state: listening -> transcribing', 10_000, mark);
|
|
await waitConsole('-> answer', 20_000, mark);
|
|
await pumpConsole();
|
|
// No stall: the simulator really delivered audio frames while the mic was open.
|
|
expect(consoleLines.slice(mark).some((l) => l.includes('no audio frames'))).toBe(false);
|
|
const captured = consoleLines.slice(mark).find((l) => l.includes('capture: captured'));
|
|
expect(captured, 'capture summary').toBeTruthy();
|
|
const seconds = Number(/captured ([\d.]+) s/.exec(captured!)![1]);
|
|
// The null audio device is not paced in real time, so the amount captured in a fixed wall
|
|
// time says nothing about a real microphone. What matters: frames arrived, the explicit tap
|
|
// (not the cap) ended the capture, and exactly those bytes reached the recogniser as WAV.
|
|
const endedByCap = consoleLines.slice(mark).some((l) => l.includes('capture limit reached'));
|
|
console.info(`[simulator] capture ended by ${endedByCap ? 'the 120 s cap' : 'the second tap'} with ${seconds} s of null-device audio`);
|
|
expect(seconds).toBeGreaterThan(0);
|
|
expect(seconds).toBeLessThanOrEqual(120);
|
|
if (endedByCap) expect(seconds).toBe(120);
|
|
expect(audioEchoLines).toBeGreaterThan(0);
|
|
expect(h.stt.lastWav).toMatchObject({ sampleRate: 16000, channels: 1, bitsPerSample: 16 });
|
|
expect(h.stt.lastWav!.dataBytes % 3200).toBe(0);
|
|
expect(h.stt.lastWav!.dataBytes / 32000).toBeCloseTo(seconds, 1);
|
|
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');
|
|
expect(litInBand(page1, 0, 251)).toBeGreaterThan(2000);
|
|
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');
|
|
expect(page2.png.equals(page1.png)).toBe(false);
|
|
await input('up');
|
|
await new Promise((r) => setTimeout(r, 900));
|
|
const back = await screenshot('06-answer-page-1-again');
|
|
expect(back.png.equals(page1.png)).toBe(true);
|
|
});
|
|
|
|
it('a follow-up tap continues the same conversation', async () => {
|
|
h.stt.next({ text: 'simulated follow-up' });
|
|
const mark = consoleLines.length;
|
|
await input('click');
|
|
await waitConsole('state: answer -> listening', 10_000, mark);
|
|
// Give the microphone a moment to deliver frames (an instant second tap records nothing,
|
|
// which the app correctly reports as "Nothing was recorded"). If the unpaced null device
|
|
// has already hit the cap, the capture is over and a tap now would start a new question.
|
|
await new Promise((r) => setTimeout(r, 200));
|
|
await pumpConsole();
|
|
if (!consoleLines.slice(mark).some((l) => l.includes('capture limit reached'))) await input('click');
|
|
await waitConsole('-> answer', 20_000, mark);
|
|
expect(h.hermes.sessions.size).toBe(1);
|
|
expect(h.hermes.executions).toBe(2);
|
|
await new Promise((r) => setTimeout(r, 800));
|
|
await screenshot('07-follow-up-answer');
|
|
});
|
|
|
|
it('double-tap while recording cancels and uploads nothing; double-tap on an answer goes back', async () => {
|
|
const sttCalls = h.stt.calls;
|
|
let mark = consoleLines.length;
|
|
await input('click');
|
|
// Sent back to back, so the cancel lands before the unpaced null device can fill the cap.
|
|
await input('double_click');
|
|
await waitConsole('state: listening -> cancelled', 10_000, mark);
|
|
await new Promise((r) => setTimeout(r, 800));
|
|
await screenshot('08-cancelled');
|
|
expect(h.stt.calls).toBe(sttCalls);
|
|
|
|
mark = consoleLines.length;
|
|
await input('double_click');
|
|
await waitConsole('state: cancelled -> ready', 10_000, mark);
|
|
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);
|
|
await new Promise((r) => setTimeout(r, 6_500));
|
|
await pumpConsole();
|
|
// Opened by URL, no gesture yet: not armed, so it must still be there.
|
|
expect(consoleLines.slice(from).some((l) => l.includes('leaving the glasses'))).toBe(false);
|
|
await input('down'); // a glasses gesture arms it
|
|
await waitConsole('leaving the glasses: idle on ready', 15_000, from);
|
|
await new Promise((r) => setTimeout(r, 1_500));
|
|
await pumpConsole();
|
|
const after = consoleLines.slice(from);
|
|
const confirmed = after.some((l) => l.includes('lifecycle: left the glasses'));
|
|
const refused = after.some((l) => l.includes('did not confirm leaving'));
|
|
simulatorExitOutcome = confirmed ? 'confirmed' : refused ? 'not confirmed' : 'no answer recorded';
|
|
console.log(`[simulator] shutDownPageContainer(0): ${simulatorExitOutcome}`);
|
|
const shot = await screenshot('08-after-idle-exit');
|
|
// Observed on simulator 0.9.5: the call is confirmed and the display is cleared.
|
|
expect(simulatorExitOutcome).toBe('confirmed');
|
|
expect(shot.lit).toBeLessThan(50);
|
|
// What the simulator does with the call is recorded, not assumed; either way the app must
|
|
// have asked, and must not have thrown.
|
|
expect(confirmed || refused).toBe(true);
|
|
const problems = after.filter((l) => /\[uncaught\]|\[unhandledrejection\]/.test(l));
|
|
expect(problems).toEqual([]);
|
|
}, 120_000);
|
|
});
|