Files
hermeven/tests/integration/client-bridge.test.ts
T
DanandClaude Fable 5.2 bbde3c86a8 CODY-016, 017, 018: launch source cannot be missed; a failed idle exit is retried
CODY-016. The SDK pushes the launch source once, early. The Even adapter now
subscribes in its constructor, remembers the value and replays it to a
listener that subscribes later. appMenu still does not arm idle exit.

CODY-018. exitNow() returns whether the host confirmed. The adapter keeps at
most one shutdown call in flight (through the same queue as every other host
call), lets a repeat request wait on that call, and never calls the host
again after a confirmed exit, including one confirmed late. The controller
marks itself as gone only on confirmation or on a system_exit/abnormal_exit
event; otherwise it retries after 3 s, at most 4 attempts in a row, under the
same resting-screen and phone-grace guards, and starts again after activity.

CODY-017. README: one owner-reported locked-phone success; pocketed,
five-minute and ten-cycle runs unverified.

Tests: production-adapter tests with a stand-in host, including the default
30 s under a fake clock; a simulator scenario that performs the real exit
(development-only ?idleExit=fast). Not reviewed. 0.1.1 is not uploaded.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 14:38:29 -08:00

910 lines
40 KiB
TypeScript

import { measureTextWrap } from '@evenrealities/pretext';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { Controller, type Snapshot } from '../../apps/even-client/src/core/controller.ts';
import { MENU_ITEM } from '../../apps/even-client/src/device/events.ts';
import { BridgeClient } from '../../apps/even-client/src/net/bridgeClient.ts';
import { FakeDevice } from '../fakes/fakeDevice.ts';
import { createHarness, type Harness } from './harness.ts';
/**
* The whole software path in one process: the client's controller, reducer,
* pagination and HTTP client -> the real bridge over HTTP -> TEST FAKES for
* the glasses, the speech recogniser and Hermes. No hardware, no simulator,
* no real model. See docs/device-test-plan.md for what this does not cover.
*/
let h: Harness;
let device: FakeDevice;
let controller: Controller;
let snapshot: Snapshot;
let network: {
down: boolean;
/** Runs the real request, then loses the reply: the bridge acts, the client hears nothing. */
dropReplies: boolean;
/** Optional per-request hook: return a promise to delay or reorder a reply. */
hook: ((url: string, init: RequestInit | undefined, send: () => Promise<Response>) => Promise<Response> | null) | null;
sent: Array<{ method: string; path: string }>;
};
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;
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',
pollIntervalMs: 20,
submitAttempts: 3,
submitRetryMs: 30,
micStallMs: 300,
holdToTalkMs: 150,
makeClient: (baseUrl, token) =>
new BridgeClient({
baseUrl,
token,
timeoutMs: 500,
fetchImpl: async (input, init) => {
if (network.down) throw new TypeError('offline');
const url = String(input);
network.sent.push({ method: init?.method ?? 'GET', path: new URL(url).pathname });
const send = () => fetch(input, init);
const hooked = network.hook?.(url, init, send);
if (hooked) return hooked;
const res = await send();
if (network.dropReplies) {
await res.arrayBuffer();
throw new TypeError('reply lost');
}
return res;
},
}),
onChange: (s) => {
snapshot = s;
},
});
}
async function pairedController(): Promise<void> {
device = new FakeDevice();
controller = makeController(device);
await controller.start();
expect(phase()).toBe('unpaired');
const { code } = h.bridge.devices.createPairingCode();
await controller.pair(h.url, code, 'fake-g2');
expect(phase()).toBe('ready');
}
beforeEach(async () => {
network = { down: false, dropReplies: false, hook: null, sent: [] };
controllerExtras = {};
h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2' } });
});
afterEach(async () => {
await controller?.stop();
await h?.close();
});
describe('voice question, answer and follow-up', () => {
it('tap -> record -> tap -> transcribe -> think -> paged answer -> follow-up with context', async () => {
await pairedController();
expect(device.frame.status).toContain('Tap: ask');
expect(device.micOpens).toBe(0);
const answer = Array.from({ length: 60 }, (_, i) => `Sentence number ${i + 1} of a long answer about Mount Everest.`).join(' ');
h.stt.next({ text: 'how tall is mount everest' });
h.hermes.next({ kind: 'complete', output: `**Mount Everest** is 8,849 m tall.\n\n${answer}` });
device.tap();
await until('listening with mic open', () => phase() === 'listening' && device.micOpen);
await until('REC indicator', () => device.frame.status.includes('● REC'));
device.speak(1.2);
device.tap();
await until('answer', () => phase() === 'answer');
expect(device.micOpen).toBe(false);
expect(device.micCloses).toBe(1);
// 1.2 s of 16 kHz 16-bit mono reached the recogniser as a WAV.
expect(h.stt.lastWav).toEqual({ sampleRate: 16000, channels: 1, bitsPerSample: 16, dataBytes: 38400 });
expect(h.hermes.lastRun()!.input).toBe('how tall is mount everest');
// Paged, plain text, complete.
const pages = snapshot.state.pages;
expect(pages.length).toBeGreaterThan(2);
expect(pages[0]).toMatch(/^Mount Everest is 8,849 m tall\./);
expect(pages.join(' ')).toContain('Sentence number 60 of a long answer');
expect(device.frame.body).toBe(pages[0]);
expect(device.frame.status).toContain(`1/${pages.length}`);
device.swipeDown();
expect(device.frame.body).toBe(pages[1]);
device.swipeUp();
device.swipeUp();
expect(device.frame.body).toBe(pages[0]);
for (let i = 0; i < pages.length + 3; i++) device.swipeDown();
expect(device.frame.body).toBe(pages.at(-1));
// The phone keeps the complete original, Markdown and all.
expect(snapshot.lastTurn!.answer_text).toContain('**Mount Everest**');
// Follow-up in the same conversation.
h.stt.next({ text: 'and in feet' });
device.tap();
await until('listening again', () => phase() === 'listening' && device.micOpen);
device.speak(0.6);
device.tap();
await until('second answer', () => phase() === 'answer');
expect(device.frame.body).toContain('turn=2');
expect(device.frame.body).toContain('previous="how tall is mount everest"');
expect(h.hermes.sessions.size).toBe(1);
expect(h.hermes.executions).toBe(2);
});
it('recording stops by itself at the cap and submits what was captured', async () => {
await pairedController();
device.tap();
await until('listening', () => phase() === 'listening' && device.micOpen);
device.speak(5); // cap is 2 s
await until('answer', () => phase() === 'answer');
expect(device.micOpen).toBe(false);
expect(h.stt.lastWav!.dataBytes).toBe(2 * 32000);
});
it('explicit new conversation from the glasses menu starts a fresh agent session', async () => {
await pairedController();
controller.askText('remember the word pineapple');
await until('answer', () => phase() === 'answer');
device.menu(MENU_ITEM.NEW_CONVERSATION);
await until('new conversation ready', () => phase() === 'ready' && snapshot.state.conversationId !== null);
expect(device.frame.body).toContain('New conversation');
controller.askText('what word?');
await until('answer', () => phase() === 'answer');
expect(device.frame.body).toContain('turn=1');
expect(h.hermes.sessions.size).toBe(2);
});
});
describe('cancel and stale results', () => {
it('double-tap while recording discards the audio: nothing is uploaded', async () => {
await pairedController();
device.tap();
await until('listening', () => phase() === 'listening' && device.micOpen);
device.speak(0.5);
device.doubleTap();
await until('cancelled', () => phase() === 'cancelled' && !device.micOpen);
await new Promise((r) => setTimeout(r, 100));
expect(h.stt.calls).toBe(0);
expect(h.hermes.executions).toBe(0);
// Audio arriving after the stop is ignored.
device.micOpen = true;
device.speak(0.3);
device.micOpen = false;
expect(phase()).toBe('cancelled');
});
it('cancel while thinking stops the agent, and its late answer never reaches the HUD', async () => {
await pairedController();
h.hermes.next({ kind: 'complete', afterMs: 250, output: 'LATE ANSWER' });
h.hermes.ignoreStop(); // the agent finishes anyway
controller.askText('slow question');
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
device.doubleTap();
expect(phase()).toBe('cancelled');
expect(device.frame.body).toContain('not undone');
await new Promise((r) => setTimeout(r, 500));
expect(phase()).toBe('cancelled');
expect(device.frames.some((f) => f.body.includes('LATE ANSWER'))).toBe(false);
expect(h.hermes.requests.filter((r) => r.path.endsWith('/stop')).length).toBeGreaterThanOrEqual(1);
// A newer question is answered normally and the old one cannot overwrite it.
h.hermes.ignoreStop(false);
h.hermes.next({ kind: 'complete', output: 'NEW ANSWER' });
controller.askText('new question');
await until('answer', () => phase() === 'answer');
expect(device.frame.body).toBe('NEW ANSWER');
});
it('cancel from the glasses menu works while thinking', async () => {
await pairedController();
h.hermes.next({ kind: 'hang' });
controller.askText('q');
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
device.menu(MENU_ITEM.CANCEL);
expect(phase()).toBe('cancelled');
await until('bridge saw the cancel', () => h.hermes.requests.some((r) => r.path.endsWith('/stop')));
});
});
describe('connection loss', () => {
it('bridge unreachable at submit: tap resends the same request exactly once', async () => {
await pairedController();
network.down = true;
device.tap();
await until('listening', () => phase() === 'listening' && device.micOpen);
device.speak(0.5);
device.tap();
await until('disconnected', () => phase() === 'disconnected');
expect(device.frame.body).toContain('not confirmed yet');
expect(device.frame.body).not.toContain('not been sent');
expect(device.micOpen).toBe(false);
const requestId = snapshot.state.requestId;
network.down = false;
device.tap();
await until('answer', () => phase() === 'answer');
expect(snapshot.lastTurn!.request_id).toBe(requestId);
expect(h.hermes.executions).toBe(1);
expect(h.stt.calls).toBe(1);
// The microphone was not reopened by the retry.
expect(device.micOpens).toBe(1);
});
it('connection lost while waiting: keeps the turn, shows it, and delivers the answer on return', async () => {
await pairedController();
h.hermes.next({ kind: 'complete', afterMs: 500, output: 'worth the wait' });
controller.askText('q');
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
network.down = true;
await until('disconnected', () => phase() === 'disconnected');
expect(device.frame.body).toContain('Still waiting');
device.tap(); // must not resubmit
network.down = false;
await until('answer', () => phase() === 'answer');
expect(device.frame.body).toBe('worth the wait');
expect(h.hermes.executions).toBe(1);
});
it('glasses disconnect while recording stops capture; reconnecting does not reopen the microphone', async () => {
await pairedController();
device.tap();
await until('listening', () => phase() === 'listening' && device.micOpen);
device.connection(false);
await until('mic closed', () => !device.micOpen);
expect(phase()).toBe('disconnected');
device.connection(true);
await new Promise((r) => setTimeout(r, 100));
expect(phase()).toBe('ready');
expect(device.micOpen).toBe(false);
expect(device.micOpens).toBe(1);
expect(h.stt.calls).toBe(0);
});
it('a microphone that stops delivering audio ends the capture with an error', async () => {
await pairedController();
device.tap();
await until('listening', () => phase() === 'listening' && device.micOpen);
await until('stall detected', () => phase() === 'error', 3000);
expect(snapshot.state.error!.code).toBe('mic_stalled');
expect(device.micOpen).toBe(false);
});
it('a refused microphone is reported and nothing is recorded', async () => {
await pairedController();
device.micAllowed = false;
device.tap();
await until('error', () => phase() === 'error');
expect(snapshot.state.error!.code).toBe('mic_refused');
expect(device.frame.body).toContain('Microphone unavailable');
});
});
describe('restart, revocation and disconnect', () => {
it('a page restart mid-turn re-attaches to the turn without resubmitting or recording', async () => {
await pairedController();
h.hermes.next({ kind: 'complete', afterMs: 300, output: 'found after restart' });
controller.askText('q');
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
await until('active request persisted', () => (device.storage.get('hermeven.v1') ?? '').includes('"activeRequestId":"'));
await controller.stop();
// New page, same app storage.
const reborn = new FakeDevice();
for (const [k, v] of device.storage) reborn.storage.set(k, v);
device = reborn;
controller = makeController(device);
await controller.start();
await until('answer', () => phase() === 'answer');
expect(device.frame.body).toBe('found after restart');
expect(h.hermes.executions).toBe(1);
expect(device.micOpens).toBe(0);
});
it('a credential revoked on the bridge sends the app back to unpaired and wipes local state', async () => {
await pairedController();
const [paired] = h.bridge.devices.list();
h.bridge.devices.revoke(paired!.id);
controller.askText('q');
await until('unpaired', () => phase() === 'unpaired');
expect(device.storage.get('hermeven.v1')).toBe('');
expect(snapshot.paired).toBe(false);
expect(h.hermes.executions).toBe(0);
});
it('disconnect revokes on the bridge and clears the phone', async () => {
await pairedController();
const stored = JSON.parse(device.storage.get('hermeven.v1')!);
expect((await controller.disconnect()).revoked).toBe(true);
expect(phase()).toBe('unpaired');
expect(device.storage.get('hermeven.v1')).toBe('');
expect((await h.api('GET', '/v1/device', { token: stored.token })).status).toBe(401);
});
it('double-tap on the root page asks the OS for its exit dialog', async () => {
await pairedController();
device.doubleTap();
await until('exit requested', () => device.exitRequests === 1);
expect(phase()).toBe('ready');
});
it('pairing with a wrong code fails without storing anything', async () => {
device = new FakeDevice();
controller = makeController(device);
await controller.start();
await expect(controller.pair(h.url, 'WRONG-CODE1', 'x')).rejects.toMatchObject({ body: { code: 'pairing_invalid' } });
expect(phase()).toBe('unpaired');
expect(device.storage.get('hermeven.v1') ?? '').toBe('');
});
it('diagnostics never contain the question, the answer or the credential', async () => {
await pairedController();
h.stt.next({ text: 'SECRET-QUESTION-walrus' });
h.hermes.next({ kind: 'complete', output: 'SECRET-ANSWER-narwhal' });
device.tap();
await until('listening', () => phase() === 'listening' && device.micOpen);
device.speak(0.4);
device.tap();
await until('answer', () => phase() === 'answer');
const log = snapshot.log.map((e) => `${e.kind} ${e.detail}`).join('\n');
const token = JSON.parse(device.storage.get('hermeven.v1')!).token;
expect(log).toContain('done');
for (const secret of ['walrus', 'narwhal', token]) expect(log).not.toContain(secret);
});
});
describe('CODY-003: a submit whose reply is lost is ambiguous, never "not sent"', () => {
it('replies dropped after the bridge admitted the turn, then a client restart: one execution, same request id, re-attached', async () => {
await pairedController();
// An ordinary first question, so a conversation exists before the connection turns bad.
controller.askText('hello');
await until('first answer', () => phase() === 'answer');
h.hermes.next({ kind: 'complete', afterMs: 400, output: 'the one and only answer' });
h.stt.next({ text: 'transfer ten pounds' });
device.tap();
await until('listening', () => phase() === 'listening' && device.micOpen);
device.speak(0.5);
// From now on every request reaches the bridge and is acted on, but no reply comes back.
network.dropReplies = true;
device.tap();
await until('disconnected', () => phase() === 'disconnected');
const requestId = snapshot.state.requestId!;
// The bridge really did admit it, and Hermes really is running it.
await until('admitted by the bridge', () => h.hermes.executions === 2);
// The HUD does not claim the request was not sent.
for (const frame of device.frames) expect(frame.body).not.toMatch(/not been sent|was not sent|has not been sent/i);
expect(device.frame.body).toContain('not confirmed yet');
// The id was stored before the first attempt, so a restart can find the turn.
expect(JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId).toBe(requestId);
// The page dies and comes back. The recording is gone; only storage survives.
await controller.stop();
const reborn = new FakeDevice();
for (const [k, v] of device.storage) reborn.storage.set(k, v);
device = reborn;
network.dropReplies = false;
controller = makeController(device);
await controller.start();
await until('answer after restart', () => phase() === 'answer');
expect(device.frame.body).toBe('the one and only answer');
expect(snapshot.lastTurn!.request_id).toBe(requestId);
// Two questions were asked in this test; the lost-reply one ran exactly once.
expect(h.hermes.executions).toBe(2);
expect(h.hermes.lastRun()!.input).toBe('transfer ten pounds');
expect(h.stt.calls).toBe(1);
expect(device.micOpens).toBe(0);
expect(JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId).toBeNull();
});
it('same loss without a restart: tapping retry re-attaches under the same id and still executes once', async () => {
await pairedController();
controller.askText('hello');
await until('first answer', () => phase() === 'answer');
h.hermes.next({ kind: 'complete', afterMs: 200, output: 'answered once' });
network.dropReplies = true;
controller.askText('do the thing');
await until('disconnected', () => phase() === 'disconnected');
const requestId = snapshot.state.requestId!;
network.dropReplies = false;
device.tap();
await until('answer', () => phase() === 'answer');
expect(snapshot.lastTurn!.request_id).toBe(requestId);
expect(device.frame.body).toBe('answered once');
expect(h.hermes.executions).toBe(2);
expect(h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs')).toHaveLength(2);
});
it('a request that truly never arrived is reported as such only after the bridge confirms it has no record', async () => {
await pairedController();
network.down = true;
controller.askText('lost in the tunnel');
await until('disconnected', () => phase() === 'disconnected');
const requestId = snapshot.state.requestId!;
expect(JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId).toBe(requestId);
await controller.stop();
const reborn = new FakeDevice();
for (const [k, v] of device.storage) reborn.storage.set(k, v);
device = reborn;
network.down = false;
controller = makeController(device);
await controller.start();
await until('confirmed absent', () => phase() === 'error');
expect(snapshot.state.error).toMatchObject({ code: 'not_delivered', retryable: true });
expect(device.frame.body).toContain('did not reach the bridge');
expect(h.hermes.executions).toBe(0);
expect(JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId).toBeNull();
});
it('a cancel that cannot be delivered is remembered and delivered on the next start, without showing the abandoned turn', async () => {
await pairedController();
h.hermes.next({ kind: 'hang' });
controller.askText('abandon me');
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
const requestId = snapshot.state.requestId!;
network.down = true;
device.doubleTap();
expect(phase()).toBe('cancelled');
await until('cancel recorded as pending', () => JSON.parse(device.storage.get('hermeven.v1')!).activeCancelled === true);
await new Promise((r) => setTimeout(r, 200));
expect(JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId).toBe(requestId);
expect(h.hermes.requests.some((r) => r.path.endsWith('/stop'))).toBe(false);
await controller.stop();
const reborn = new FakeDevice();
for (const [k, v] of device.storage) reborn.storage.set(k, v);
device = reborn;
network.down = false;
controller = makeController(device);
await controller.start();
expect(phase()).toBe('ready');
await until('stop reached Hermes', () => h.hermes.requests.some((r) => r.path.endsWith('/stop')));
await until('slot cleared', () => JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId === null);
expect(device.frames.every((f) => !f.body.includes('Thinking'))).toBe(true);
});
});
describe('CODY-007: an expired credential is treated like a revoked one', () => {
const expireNow = () => h.bridge.db.prepare('UPDATE devices SET token_expires_at = ?').run(Date.now() - 1000);
it('expiry during a live session: asking clears the local pairing and brings pairing back', async () => {
await pairedController();
expect(snapshot.paired).toBe(true);
expireNow();
controller.askText('still there?');
await until('unpaired', () => phase() === 'unpaired');
expect(snapshot.paired).toBe(false);
expect(device.storage.get('hermeven.v1')).toBe('');
expect(device.frame.body).toContain('Open Hermeven on your phone to pair');
expect(h.hermes.executions).toBe(0);
// Pairing works again straight away.
const { code } = h.bridge.devices.createPairingCode();
await controller.pair(h.url, code, 'again');
expect(phase()).toBe('ready');
controller.askText('hello again');
await until('answer', () => phase() === 'answer');
});
it('expiry while waiting for an answer', async () => {
await pairedController();
h.hermes.next({ kind: 'hang' });
controller.askText('long one');
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
expireNow();
await until('unpaired', () => phase() === 'unpaired');
expect(device.storage.get('hermeven.v1')).toBe('');
});
it('expiry noticed by the status refresh, by renew, and by new conversation', async () => {
for (const action of ['refresh', 'renew', 'conversation'] as const) {
await controller?.stop();
await pairedController();
expireNow();
if (action === 'refresh') await controller.refreshStatus();
else if (action === 'renew') await expect(controller.renew()).rejects.toMatchObject({ body: { code: 'credential_expired' } });
else controller.newConversation();
await until(`unpaired after ${action}`, () => phase() === 'unpaired');
expect(snapshot.paired, action).toBe(false);
expect(device.storage.get('hermeven.v1'), action).toBe('');
}
});
});
describe('CODY-009: exactly one conversation is created, whatever the timing', () => {
const creates = () => network.sent.filter((r) => r.method === 'POST' && r.path === '/v1/conversations').length;
const serverActive = async () => {
const token = JSON.parse(device.storage.get('hermeven.v1')!).token;
return (await h.api('GET', '/v1/device', { token })).body.active_conversation_id as string;
};
/** Hold every reply to a conversation create until released. */
function holdCreates() {
const held: Array<() => void> = [];
network.hook = (url, init, send) => {
if (init?.method !== 'POST' || !url.endsWith('/v1/conversations')) return null;
return send().then((res) => new Promise<Response>((resolve) => held.push(() => resolve(res))));
};
return {
count: () => held.length,
release: (index: number) => held[index]!(),
};
}
it('"new conversation" pressed twice and a question asked at once, with the create reply delayed: one create, one stored id, the question succeeds', async () => {
await pairedController();
const gate = holdCreates();
device.menu(MENU_ITEM.NEW_CONVERSATION);
device.menu(MENU_ITEM.NEW_CONVERSATION);
controller.askText('first question in the new conversation');
await until('create reached the bridge', () => gate.count() === 1);
await new Promise((r) => setTimeout(r, 150));
expect(creates()).toBe(1);
expect(h.hermes.executions).toBe(0); // the turn is waiting for its conversation, not racing it
gate.release(0);
await until('answer', () => phase() === 'answer');
expect(creates()).toBe(1);
const stored = JSON.parse(device.storage.get('hermeven.v1')!).conversationId;
expect(stored).toBe(snapshot.state.conversationId);
expect(stored).toBe(await serverActive());
expect(snapshot.lastTurn!.conversation_id).toBe(stored);
expect(snapshot.lastTurn!.outcome).toBe('succeeded');
expect(h.hermes.sessions.size).toBe(1);
});
it('first question right after pairing, cancelled and asked again while the lazy create is still pending: still one create', async () => {
await pairedController();
const gate = holdCreates();
controller.askText('one');
await until('create reached the bridge', () => gate.count() === 1);
device.doubleTap(); // abandon the first question; the create it started is still in flight
controller.askText('two');
await new Promise((r) => setTimeout(r, 150));
expect(creates()).toBe(1);
gate.release(0);
await until('answer', () => phase() === 'answer');
expect(creates()).toBe(1);
expect(h.hermes.lastRun()!.input).toBe('two');
expect(h.hermes.executions).toBe(1);
expect(JSON.parse(device.storage.get('hermeven.v1')!).conversationId).toBe(await serverActive());
});
it('a reset during a pending create: replies arrive out of order, yet app and bridge agree on the live conversation and the next question succeeds', async () => {
await pairedController();
const gate = holdCreates();
controller.askText('one'); // lazy create A
await until('create A at the bridge', () => gate.count() === 1);
device.doubleTap();
device.menu(MENU_ITEM.NEW_CONVERSATION); // reset: create B is wanted while A is unanswered
await new Promise((r) => setTimeout(r, 150));
// B is not sent until A has settled, so the bridge can never process them in the wrong order.
expect(creates()).toBe(1);
expect(JSON.parse(device.storage.get('hermeven.v1')!).conversationId).toBeNull();
gate.release(0); // A's reply arrives late, for a conversation the user has already replaced
await until('create B at the bridge', () => gate.count() === 2);
// A's result was dropped before persistence.
expect(JSON.parse(device.storage.get('hermeven.v1')!).conversationId).toBeNull();
expect(snapshot.state.conversationId).toBeNull();
controller.askText('first question after the reset'); // immediate first turn, B still pending
gate.release(1);
await until('answer', () => phase() === 'answer');
expect(creates()).toBe(2); // one per conversation the user asked for, never more
const stored = JSON.parse(device.storage.get('hermeven.v1')!).conversationId;
expect(stored).toBe(await serverActive());
expect(snapshot.lastTurn!.conversation_id).toBe(stored);
expect(snapshot.lastTurn!.outcome).toBe('succeeded');
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('opened from the phone with no gesture yet, it stays: setting up on the phone is not interrupted', async () => {
controllerExtras = { idleExit: FAST };
await pairedController();
device.launchedFrom('appMenu');
controller.askText('typed on the phone');
await until('answer', () => phase() === 'answer');
await quiet(500);
expect(device.exits).toBe(0);
// The first gesture on the glasses means they are in use: from then on it applies.
device.swipeDown();
await until('left after the glasses were used', () => device.exits === 1, 1500);
});
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);
});
});