Files
hermeven/apps/even-client/test/reducer.test.ts
T
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

372 lines
17 KiB
TypeScript

import { describe, expect, it } from 'vitest';
import { SCHEMA_VERSION, type TurnResult } from '@hermeven/contracts';
import { pollDelay } from '../src/core/controller.ts';
import { initialState, reduce, type AppEvent, type AppState, type Effect } from '../src/core/reducer.ts';
const ID1 = '11111111-1111-4111-8111-111111111111';
const ID2 = '22222222-2222-4222-8222-222222222222';
const CONV = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
function run(state: AppState, ...events: AppEvent[]): { state: AppState; effects: Effect[] } {
let effects: Effect[] = [];
for (const event of events) {
const step = reduce(state, event);
state = step.state;
effects = step.effects;
}
return { state, effects };
}
const ready = () =>
run(initialState, { type: 'init', paired: true, conversationId: CONV, captureMaxSeconds: 30, resumeRequestId: null }).state;
function result(requestId: string, over: Partial<TurnResult> = {}): TurnResult {
return {
schema_version: SCHEMA_VERSION,
request_id: requestId,
conversation_id: CONV,
state: 'done',
terminal: true,
outcome: 'succeeded',
cancel_requested: false,
input_text: 'q',
answer_text: 'a',
error: null,
replayed: false,
created_at: '2026-01-01T00:00:00.000Z',
updated_at: '2026-01-01T00:00:01.000Z',
timings: { transcribe_ms: 1, agent_ms: 2 },
...over,
};
}
describe('poll schedule', () => {
it('checks often while an answer is likely, and eases off for long runs', () => {
expect(pollDelay(0)).toBe(200);
expect(pollDelay(7_999)).toBe(200);
expect(pollDelay(8_000)).toBe(400);
expect(pollDelay(30_000)).toBe(1000);
expect(pollDelay(600_000)).toBe(1000);
// Stays far inside the bridge's 600 requests per minute per device.
expect(60_000 / pollDelay(0)).toBeLessThan(600);
});
});
describe('happy path', () => {
it('READY -> LISTENING -> TRANSCRIBING -> THINKING -> ANSWER', () => {
let s = ready();
expect(s.phase).toBe('ready');
let step = reduce(s, { type: 'activate', freshId: ID1 });
s = step.state;
expect(s.phase).toBe('listening');
expect(step.effects).toEqual([{ type: 'start_capture', generation: s.generation }]);
s = reduce(s, { type: 'capture_started', generation: s.generation, at: 1000 }).state;
expect(s.captureStartedAt).toBe(1000);
step = reduce(s, { type: 'activate', freshId: ID2 });
s = step.state;
expect(s.phase).toBe('transcribing');
// The request id chosen at activation is the one submitted: the stop tap's id is unused.
expect(step.effects).toEqual([{ type: 'stop_capture_and_submit', generation: s.generation, requestId: ID1 }]);
s = reduce(s, {
type: 'turn_update',
generation: s.generation,
result: result(ID1, { state: 'thinking', terminal: false, outcome: null, answer_text: null }),
pages: null,
}).state;
expect(s.phase).toBe('thinking');
s = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['p1', 'p2', 'p3'] }).state;
expect(s.phase).toBe('answer');
expect(s.pages).toEqual(['p1', 'p2', 'p3']);
expect(s.pageIndex).toBe(0);
});
it('a tap on the answer starts a follow-up in the same conversation', () => {
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
s = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['p'] }).state;
const step = reduce(s, { type: 'activate', freshId: ID2 });
expect(step.state.phase).toBe('listening');
expect(step.state.conversationId).toBe(CONV);
expect(step.state.requestId).toBe(ID2);
expect(step.state.pages).toEqual([]);
});
it('the capture cap stops and submits exactly once', () => {
let s = run(ready(), { type: 'activate', freshId: ID1 }).state;
const step = reduce(s, { type: 'capture_limit', generation: s.generation });
expect(step.state.phase).toBe('transcribing');
expect(step.effects).toHaveLength(1);
s = step.state;
expect(reduce(s, { type: 'capture_limit', generation: s.generation }).effects).toEqual([]);
});
});
describe('paging', () => {
it('moves within bounds and only in ANSWER', () => {
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
expect(reduce(s, { type: 'next_page' }).state).toBe(s);
s = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['a', 'b', 'c'] }).state;
s = run(s, { type: 'next_page' }, { type: 'next_page' }, { type: 'next_page' }).state;
expect(s.pageIndex).toBe(2);
s = run(s, { type: 'prev_page' }, { type: 'prev_page' }, { type: 'prev_page' }, { type: 'prev_page' }).state;
expect(s.pageIndex).toBe(0);
});
});
describe('cancellation and stale results', () => {
it('double-tap while listening discards the capture and never submits', () => {
const s = run(ready(), { type: 'activate', freshId: ID1 }).state;
const step = reduce(s, { type: 'back' });
expect(step.state.phase).toBe('cancelled');
expect(step.effects).toEqual([{ type: 'discard_capture' }]);
expect(step.state.generation).toBe(s.generation + 1);
});
it('cancel while thinking asks the bridge to cancel, and a late answer cannot resurrect the UI', () => {
const s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
const step = reduce(s, { type: 'back' });
expect(step.state.phase).toBe('cancelled');
expect(step.effects).toContainEqual({ type: 'cancel_turn', requestId: ID1 });
const late = reduce(step.state, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['LATE'] });
expect(late.state).toBe(step.state);
expect(late.state.pages).toEqual([]);
});
it('a late result for an older request cannot replace a newer answer', () => {
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'first' }).state;
const gen1 = s.generation;
s = reduce(s, { type: 'back' }).state; // cancelled
s = reduce(s, { type: 'submit_text', freshId: ID2, text: 'second' }).state;
s = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID2), pages: ['NEW'] }).state;
expect(s.pages).toEqual(['NEW']);
// Old generation.
expect(reduce(s, { type: 'turn_update', generation: gen1, result: result(ID1), pages: ['OLD'] }).state).toBe(s);
// Right generation, wrong request id.
expect(reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['OLD'] }).state).toBe(s);
});
it('a late result for a cancelled request is ignored while a newer request is still in flight', () => {
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'first' }).state;
const gen1 = s.generation;
s = reduce(s, { type: 'back' }).state;
s = reduce(s, { type: 'submit_text', freshId: ID2, text: 'second' }).state;
expect(s.phase).toBe('thinking');
// The old turn finishes late, under its old generation.
expect(reduce(s, { type: 'turn_update', generation: gen1, result: result(ID1), pages: ['OLD'] }).state).toBe(s);
// Even mislabelled with the current generation, the request id does not match.
expect(reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['OLD'] }).state).toBe(s);
// And an old-generation event cannot smuggle in the current request id either.
expect(reduce(s, { type: 'turn_update', generation: gen1, result: result(ID2), pages: ['OLD'] }).state).toBe(s);
});
it('stale capture and network events are ignored', () => {
let s = run(ready(), { type: 'activate', freshId: ID1 }).state;
const gen = s.generation;
s = reduce(s, { type: 'back' }).state;
for (const event of [
{ type: 'capture_started', generation: gen, at: 5 },
{ type: 'capture_failed', generation: gen, reason: 'mic_refused' },
{ type: 'capture_limit', generation: gen },
{ type: 'network_lost', generation: gen, stage: 'submit' },
{ type: 'turn_rejected', generation: gen, error: { code: 'x', hud: 'x', retryable: false } },
] as AppEvent[]) {
expect(reduce(s, event).state).toBe(s);
}
});
it('a second cancel is a no-op', () => {
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }, { type: 'cancel' }).state;
const again = reduce(s, { type: 'cancel' });
expect(again.state).toBe(s);
expect(again.effects).toEqual([]);
s = again.state;
expect(s.phase).toBe('cancelled');
});
it('back from ANSWER, ERROR and CANCELLED returns to READY; back from READY asks the OS to exit', () => {
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
s = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['p'] }).state;
s = reduce(s, { type: 'back' }).state;
expect(s.phase).toBe('ready');
expect(reduce(s, { type: 'back' }).effects).toEqual([{ type: 'exit_dialog' }]);
expect(reduce(initialState, { type: 'back' }).effects).toEqual([{ type: 'exit_dialog' }]);
});
});
describe('outcomes', () => {
const thinking = () => run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
it('incomplete answers are shown and flagged as partial', () => {
const s = thinking();
const next = reduce(s, {
type: 'turn_update',
generation: s.generation,
result: result(ID1, { outcome: 'incomplete', error: { code: 'agent_incomplete', message: 'partial', retryable: false } }),
pages: ['half'],
}).state;
expect(next.phase).toBe('answer');
expect(next.partial).toBe(true);
});
it('failed and unknown become ERROR with the stable code; unknown is not retryable', () => {
const s = thinking();
const unknown = reduce(s, {
type: 'turn_update',
generation: s.generation,
result: result(ID1, { outcome: 'unknown', answer_text: null, error: { code: 'outcome_unknown', message: 'Unknown.', retryable: false } }),
pages: null,
}).state;
expect(unknown.phase).toBe('error');
expect(unknown.error).toEqual({ code: 'outcome_unknown', hud: 'Unknown.', retryable: false });
});
it('approval-required is its own phase and can still be cancelled', () => {
let s = thinking();
s = reduce(s, {
type: 'turn_update',
generation: s.generation,
result: result(ID1, { state: 'approval_required', terminal: false, outcome: null, answer_text: null }),
pages: null,
}).state;
expect(s.phase).toBe('approval');
const step = reduce(s, { type: 'back' });
expect(step.state.phase).toBe('cancelled');
expect(step.effects).toContainEqual({ type: 'cancel_turn', requestId: ID1 });
});
it('a stopped-by-deadline turn is an error, a user cancel confirmed by the bridge is CANCELLED', () => {
const s = thinking();
const timeout = reduce(s, {
type: 'turn_update',
generation: s.generation,
result: result(ID1, { outcome: 'cancelled', answer_text: null, error: { code: 'agent_timeout', message: 'Stopped.', retryable: false } }),
pages: null,
}).state;
expect(timeout.phase).toBe('error');
const plain = reduce(s, {
type: 'turn_update',
generation: s.generation,
result: result(ID1, { outcome: 'cancelled', answer_text: null }),
pages: null,
}).state;
expect(plain.phase).toBe('cancelled');
});
});
describe('connection loss', () => {
it('submit never delivered: DISCONNECTED with a safe resend of the same request id', () => {
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
s = reduce(s, { type: 'network_lost', generation: s.generation, stage: 'submit' }).state;
expect(s.phase).toBe('disconnected');
expect(s.canResend).toBe(true);
const step = reduce(s, { type: 'activate', freshId: ID2 });
expect(step.effects).toEqual([{ type: 'resubmit', generation: s.generation, requestId: ID1 }]);
expect(step.state.requestId).toBe(ID1);
});
it('lost while waiting: no resend is offered, and the answer is still accepted when it arrives', () => {
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
s = reduce(s, { type: 'network_lost', generation: s.generation, stage: 'poll' }).state;
expect(s.canResend).toBe(false);
expect(reduce(s, { type: 'activate', freshId: ID2 }).effects).toEqual([]);
const restored = reduce(s, { type: 'network_restored', generation: s.generation }).state;
expect(restored.phase).toBe('thinking');
const answered = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['p'] }).state;
expect(answered.phase).toBe('answer');
});
it('glasses disconnect while listening stops capture; reconnect never reopens the microphone', () => {
let s = run(ready(), { type: 'activate', freshId: ID1 }).state;
const step = reduce(s, { type: 'glasses_status', connected: false });
expect(step.effects).toEqual([{ type: 'discard_capture' }]);
expect(step.state.phase).toBe('disconnected');
s = step.state;
const back = reduce(s, { type: 'glasses_status', connected: true });
expect(back.state.phase).toBe('ready');
expect(back.effects).toEqual([]);
});
it('glasses disconnect during a running turn keeps the turn', () => {
const s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
expect(reduce(s, { type: 'glasses_status', connected: false }).state).toBe(s);
});
it('app exit while listening stops capture', () => {
const s = run(ready(), { type: 'activate', freshId: ID1 }).state;
const step = reduce(s, { type: 'app_exit' });
expect(step.effects).toEqual([{ type: 'discard_capture' }]);
expect(step.state.phase).toBe('ready');
});
});
describe('pairing, restore and conversations', () => {
it('unpaired ignores taps', () => {
const step = reduce(initialState, { type: 'activate', freshId: ID1 });
expect(step.state.phase).toBe('unpaired');
expect(step.effects).toEqual([]);
});
it('restoring an in-flight turn polls it and neither resubmits nor records', () => {
const step = reduce(initialState, {
type: 'init',
paired: true,
conversationId: CONV,
captureMaxSeconds: 20,
resumeRequestId: ID1,
});
expect(step.state.phase).toBe('thinking');
expect(step.effects).toEqual([{ type: 'poll', generation: step.state.generation, requestId: ID1 }]);
});
it('new conversation is refused mid-turn and resets cleanly at rest', () => {
const busy = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
expect(reduce(busy, { type: 'new_conversation' }).state).toBe(busy);
const s = ready();
const step = reduce(s, { type: 'new_conversation' });
expect(step.state.conversationId).toBeNull();
expect(step.state.creatingConversation).toBe(true);
expect(step.effects).toEqual([{ type: 'create_conversation', epoch: step.state.conversationEpoch }]);
const stale = reduce(step.state, { type: 'conversation_created', epoch: s.conversationEpoch, conversationId: 'old' });
expect(stale.state.conversationId).toBeNull();
const fresh = reduce(step.state, { type: 'conversation_created', epoch: step.state.conversationEpoch, conversationId: 'new' });
expect(fresh.state.conversationId).toBe('new');
expect(fresh.state.creatingConversation).toBe(false);
});
it('a second "new conversation" while one is being created starts nothing (CODY-009)', () => {
const first = reduce(ready(), { type: 'new_conversation' });
const second = reduce(first.state, { type: 'new_conversation' });
expect(second.state).toBe(first.state);
expect(second.effects).toEqual([]);
});
it('the conversation result is accepted even after a question has started, because it is keyed to the conversation, not the turn (CODY-009)', () => {
const created = reduce(ready(), { type: 'new_conversation' });
const asking = reduce(created.state, { type: 'submit_text', freshId: ID1, text: 'hi' });
expect(asking.state.generation).toBeGreaterThan(created.state.generation);
const done = reduce(asking.state, { type: 'conversation_created', epoch: created.state.conversationEpoch, conversationId: 'new' });
expect(done.state.conversationId).toBe('new');
expect(done.state.phase).toBe('thinking');
});
it('a conversation result from before a re-pair or a later reset is dropped', () => {
const created = reduce(ready(), { type: 'new_conversation' });
const repaired = reduce(created.state, { type: 'init', paired: true, conversationId: null, captureMaxSeconds: 30, resumeRequestId: null });
expect(reduce(repaired.state, { type: 'conversation_created', epoch: created.state.conversationEpoch, conversationId: 'x' }).state).toBe(repaired.state);
const failedLate = reduce(repaired.state, { type: 'conversation_failed', epoch: created.state.conversationEpoch, error: { code: 'x', hud: 'x', retryable: false } });
expect(failedLate.state).toBe(repaired.state);
});
it('unpairing while listening closes the microphone', () => {
const s = run(ready(), { type: 'activate', freshId: ID1 }).state;
const step = reduce(s, { type: 'unpaired' });
expect(step.state.phase).toBe('unpaired');
expect(step.effects).toEqual([{ type: 'discard_capture' }]);
});
});