Files
hermeven/tests/integration/durableRequestId.test.ts
DanandClaude Fable 5.2 1507cea077 Address Cody review round 3: CODY-003 and CODY-006
CODY-003 Request identity is durable before submission. Storage results are
         explicit at the DevicePort boundary (storageSet resolves true only
         on the host's own timely confirmation; storageGet distinguishes
         unknown from empty). A request is not sent until the phone has
         confirmed storing its id; a timeout or refusal holds it back,
         unsent and retryable under the same id. Unreadable storage at
         start is not treated as unpaired; an unsaveable pairing is revoked.
CODY-006 The state directory is set to 0700 on every open, including when
         it already existed, and the bridge refuses to start with an
         operator-facing error if it cannot be. Deployment guide creates
         it with install -d -m 0700.

Checks: typecheck clean; npm test 194 passed; client build ok;
test:real-stt 11 passed; 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 20:29:05 -08:00

317 lines
14 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 { renderHud } from '../../apps/even-client/src/core/hud.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';
/**
* CODY-003, at the production seam: the REAL EvenDevice adapter (the one that ships), driven
* by a stand-in Even host whose `setLocalStorage` settles only when the test says so. The
* bridge is real; Hermes is the test fake. No glasses are involved.
*
* What is being proven: a request is never sent until the phone has positively confirmed
* storing its id, and a wait that merely ran out is not treated as confirmation.
*/
const STORAGE_KEY = 'hermeven.v1';
const ADAPTER_TIMEOUT_MS = 120;
/** Stand-in for the Even app host. Storage here is the "durable" copy that survives a page restart. */
class FakeEvenHost {
readonly durable = new Map<string, string>();
stallWrites = false;
private held: Array<() => void> = [];
writesStarted = 0;
texts: string[] = [];
private hub = new Set<(event: unknown) => void>();
readonly bridge = {
createStartUpPageContainer: async () => 0,
textContainerUpgrade: async (update: { content?: string }) => {
this.texts.push(String(update.content ?? ''));
return true;
},
audioControl: async () => true,
shutDownPageContainer: async () => true,
getLocalStorage: async (key: string) => this.durable.get(key) ?? '',
setLocalStorage: (key: string, value: string) =>
new Promise<boolean>((resolve) => {
this.writesStarted += 1;
const apply = () => {
this.durable.set(key, value);
resolve(true);
};
if (this.stallWrites) this.held.push(apply);
else apply();
}),
onEvenHubEvent: (cb: (event: unknown) => void) => {
this.hub.add(cb);
return () => this.hub.delete(cb);
},
onDeviceStatusChanged: () => () => undefined,
};
heldWrites(): number {
return this.held.length;
}
/** The host finally completes the writes it was sitting on, in order. */
releaseWrites(): void {
for (const apply of this.held.splice(0)) apply();
}
stored(): { activeRequestId: string | null; activeCancelled?: boolean; token: string } {
return JSON.parse(this.durable.get(STORAGE_KEY) || '{}');
}
tap(): void {
for (const cb of this.hub) cb({ sysEvent: {} }); // a tap arrives with no eventType
}
doubleTap(): void {
for (const cb of this.hub) cb({ sysEvent: { eventType: 3 } });
}
}
let h: Harness;
let host: FakeEvenHost;
let controller: Controller;
let snapshot: Snapshot;
let net: { dropReplies: boolean; turnPosts: string[] };
function makeController(): 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,
submitAttempts: 2,
submitRetryMs: 20,
makeClient: (baseUrl, token) =>
new BridgeClient({
baseUrl,
token,
timeoutMs: 500,
fetchImpl: async (input, init) => {
const url = new URL(String(input));
if (init?.method === 'POST' && url.pathname === '/v1/turns') {
net.turnPosts.push(JSON.parse(String(init.body)).request_id);
}
const res = await fetch(input, init);
if (net.dropReplies) {
await res.arrayBuffer();
throw new TypeError('reply lost');
}
return res;
},
}),
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}/${snapshot?.state.disconnectedFrom}`);
await new Promise((r) => setTimeout(r, 10));
}
}
const phase = () => snapshot.state.phase;
const hud = () => renderHud(snapshot.state, Date.now()).body;
const bridgeTurn = (id: string) => h.bridge.db.prepare('SELECT state, outcome, cancel_requested FROM turns WHERE request_id = ?').get(id) as
| { state: string; outcome: string | null; cancel_requested: number }
| undefined;
/** Pair, and ask one ordinary question so a conversation exists. */
async function ready(): Promise<void> {
host = new FakeEvenHost();
controller = makeController();
await controller.start();
const { code } = h.bridge.devices.createPairingCode();
await controller.pair(h.url, code, 'production-adapter');
controller.askText('hello');
await until('first answer', () => phase() === 'answer');
expect(h.hermes.executions).toBe(1);
net.turnPosts.length = 0;
}
/** Storage stalls beyond the adapter timeout: the request must be held back, provably unsent. */
async function stallThenAsk(question: string): Promise<string> {
host.stallWrites = true;
controller.askText(question);
await until('held back for storage', () => phase() === 'disconnected' && snapshot.state.disconnectedFrom === 'storage');
const requestId = snapshot.state.requestId!;
// Well past the adapter's timeout, and still nothing has gone to the bridge.
await new Promise((r) => setTimeout(r, ADAPTER_TIMEOUT_MS * 2));
expect(host.heldWrites()).toBeGreaterThanOrEqual(1);
expect(net.turnPosts).toEqual([]);
expect(bridgeTurn(requestId)).toBeUndefined();
expect(h.hermes.executions).toBe(1);
// The durable copy does not have the id: the caller's timeout was not a successful write.
expect(host.stored().activeRequestId).toBeNull();
// Before admission, "nothing has been sent" is simply true.
expect(hud()).toContain('Nothing has been sent');
return requestId;
}
async function restartPage(): Promise<void> {
await controller.stop();
controller = makeController(); // a new page: new adapter, same host storage
await controller.start();
}
beforeEach(async () => {
net = { dropReplies: false, turnPosts: [] };
h = await createHarness();
});
afterEach(async () => {
await controller?.stop();
host?.releaseWrites();
await h?.close();
});
describe('CODY-003 with the production EvenDevice adapter and a stalled host storage write', () => {
it('stalled storage: zero submits. Confirmed storage, admitted, reply dropped, page restart: same id, one execution, never a false "not sent"', async () => {
await ready();
h.hermes.next({ kind: 'complete', afterMs: 400, output: 'invoice paid once' });
const requestId = await stallThenAsk('pay the invoice');
// A retry while storage is still stuck is held back again, under the same request id.
host.tap();
await new Promise((r) => setTimeout(r, ADAPTER_TIMEOUT_MS * 2));
expect(snapshot.state.requestId).toBe(requestId);
expect(snapshot.state.disconnectedFrom).toBe('storage');
expect(net.turnPosts).toEqual([]);
// The host recovers and completes the writes it was holding. Persistence is now real.
host.stallWrites = false;
host.releaseWrites();
await until('id durable on the host', () => host.stored().activeRequestId === requestId);
expect(net.turnPosts).toEqual([]); // a late write landing must not, by itself, send anything
// Deliberate retry: admitted by the bridge, but every reply is lost.
net.dropReplies = true;
host.tap();
await until('ambiguous after admission', () => phase() === 'disconnected' && snapshot.state.disconnectedFrom === 'bridge');
await until('admitted and running', () => h.hermes.executions === 2);
expect(new Set(net.turnPosts)).toEqual(new Set([requestId])); // the same immutable id on every attempt
expect(bridgeTurn(requestId)).toBeDefined();
expect(host.stored().activeRequestId).toBe(requestId);
// After admission the HUD makes no claim that the request was not sent.
expect(hud()).not.toMatch(/nothing has been sent|not been sent|was not sent/i);
expect(hud()).toContain('not confirmed yet');
const textsAtAdmission = host.texts.length;
// The page dies and restarts; only host storage survives.
net.dropReplies = false;
await restartPage();
await until('answer after restart', () => phase() === 'answer');
expect(snapshot.lastTurn!.request_id).toBe(requestId);
expect(snapshot.lastTurn!.answer_text).toBe('invoice paid once');
expect(h.hermes.executions).toBe(2); // "hello" plus exactly one run of this request
expect(h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs')).toHaveLength(2);
expect(net.turnPosts.filter((id) => id === requestId).length).toBe(net.turnPosts.length);
// Nothing drawn on the glasses after admission said "not sent" either.
for (const text of host.texts.slice(textsAtAdmission)) expect(text).not.toMatch(/nothing has been sent|not been sent/i);
await until('slot cleared durably', () => host.stored().activeRequestId === null);
});
it('cancellation remains possible after the same sequence and a restart', async () => {
await ready();
h.hermes.next({ kind: 'hang' });
const requestId = await stallThenAsk('start the long job');
host.stallWrites = false;
host.releaseWrites();
await until('id durable on the host', () => host.stored().activeRequestId === requestId);
net.dropReplies = true;
host.tap();
await until('admitted and running', () => h.hermes.executions === 2);
await until('ambiguous', () => phase() === 'disconnected' && snapshot.state.disconnectedFrom === 'bridge');
net.dropReplies = false;
await restartPage();
await until('re-attached', () => phase() === 'thinking' && snapshot.state.requestId === requestId);
host.doubleTap();
expect(phase()).toBe('cancelled');
await until('Hermes asked to stop', () => h.hermes.requests.some((r) => r.path.endsWith('/stop')));
await until('turn settled as cancelled', () => bridgeTurn(requestId)?.state === 'done');
expect(bridgeTurn(requestId)).toEqual({ state: 'done', outcome: 'cancelled', cancel_requested: 1 });
expect(h.hermes.executions).toBe(2);
await until('slot cleared durably', () => host.stored().activeRequestId === null);
});
it('cancelling while still held back for storage sends nothing and leaves nothing on the bridge', async () => {
await ready();
const requestId = await stallThenAsk('never mind');
host.doubleTap();
expect(phase()).toBe('cancelled');
host.stallWrites = false;
host.releaseWrites();
await new Promise((r) => setTimeout(r, 300));
expect(net.turnPosts).toEqual([]);
expect(bridgeTurn(requestId)).toBeUndefined();
expect(h.hermes.executions).toBe(1);
// And the app is usable again afterwards.
controller.askText('something else');
await until('answer', () => phase() === 'answer');
expect(h.hermes.executions).toBe(2);
});
it('a host that answers the write with false (refused, not timed out) also holds the request back', async () => {
await ready();
const realSet = host.bridge.setLocalStorage;
host.bridge.setLocalStorage = async () => false;
controller.askText('refused write');
await until('held back', () => phase() === 'disconnected' && snapshot.state.disconnectedFrom === 'storage');
expect(net.turnPosts).toEqual([]);
host.bridge.setLocalStorage = realSet;
host.tap();
await until('answer', () => phase() === 'answer');
expect(net.turnPosts).toHaveLength(1);
expect(h.hermes.executions).toBe(2);
});
it('if the page dies while the write is still stalled, the late write is harmless: nothing ran, and the next start says so', async () => {
await ready();
const requestId = await stallThenAsk('lost with the page');
await controller.stop();
// The host finishes the write after the page is gone.
host.stallWrites = false;
host.releaseWrites();
expect(host.stored().activeRequestId).toBe(requestId);
controller = makeController();
await controller.start();
await until('confirmed absent', () => phase() === 'error');
expect(snapshot.state.error).toMatchObject({ code: 'not_delivered', retryable: true });
expect(bridgeTurn(requestId)).toBeUndefined();
expect(h.hermes.executions).toBe(1);
});
});
describe('storage results are explicit at the device boundary', () => {
it('unreadable storage at start is not mistaken for "not paired", and pairing over it is refused', async () => {
host = new FakeEvenHost();
host.bridge.getLocalStorage = () => new Promise<string>(() => undefined); // never answers
controller = makeController();
await controller.start();
expect(phase()).toBe('unpaired');
expect(snapshot.state.storageFault).toBe(true);
expect(hud()).toContain('Saved settings could not be read');
const { code } = h.bridge.devices.createPairingCode();
await expect(controller.pair(h.url, code, 'x')).rejects.toThrow(/could not be read/);
expect(h.bridge.devices.list()).toHaveLength(0); // the pairing code was not even spent
});
it('a pairing the phone cannot save is undone on the bridge rather than kept in memory only', async () => {
host = new FakeEvenHost();
controller = makeController();
await controller.start();
host.stallWrites = true;
const { code } = h.bridge.devices.createPairingCode();
await expect(controller.pair(h.url, code, 'x')).rejects.toThrow(/could not save the pairing/);
expect(snapshot?.paired ?? false).toBe(false);
const [device] = h.bridge.devices.list();
expect(device!.revoked_at).not.toBeNull();
});
});