Files
hermeven/tests/integration/client-bridge.test.ts
DanandClaude Fable 5.2 e1c02d5266 Address Cody review round 2: all ten findings (CODY-001 to CODY-010)
CODY-001 Bridge URL must be HTTPS (HTTP only to loopback), in the client and
         in manifest generation.
CODY-002 Even host calls stay serialised until the SDK call really settles;
         a microphone start that completes after its timeout is followed by
         a stop.
CODY-003 Request id is stored before the first submit and cleared only on a
         definitive answer; lost replies are treated as ambiguous and
         reconciled under the same id; HUD no longer claims "not sent".
CODY-004 Revoking a device cancels its in-flight turns, aborts
         transcription and asks Hermes to stop, from HTTP and CLI paths.
CODY-005 Speech model pinned to a commit with per-file SHA-256; fetched and
         verified ahead of time; verified on every load; never downloaded
         at run time; no unpinned configuration.
CODY-006 State directory 0700, database/WAL/SHM 0600 regardless of umask.
CODY-007 credential_expired handled like unauthorized on every path.
CODY-008 Approval wait start and paused agent deadline persisted and
         restored across restarts (schema v2).
CODY-009 Exactly one conversation create per epoch, sent in sequence, with
         stale results dropped before persistence.
CODY-010 Wrong pairing guesses no longer consume the outstanding code;
         failures are indistinguishable.

Checks: typecheck clean; npm test 182 passed; client build ok;
test:real-stt 11 passed (including with no network); test:real-hermes 9
passed; test:simulator 6 passed; git diff --check clean.

Not reviewed. No physical-device, droplet or production evidence.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 19:49:14 -08:00

611 lines
27 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;
function makeController(dev: FakeDevice): Controller {
return new Controller({
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) => {
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: [] };
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);
});
});