Files
hermeven/apps/even-client/test/reducer.test.ts
T
DanandClaude Fable 5.2 9394c249ad Choose an agent with a swipe at Ready (0.2.0)
Bridge: an owner-configured list of agents (HERMEVEN_AGENTS). Each extra
agent is another profile of the same Hermes gateway, reached at
/p/<profile> with that profile's own key. GET /v1/agents lists ids and
names; POST /v1/conversations takes an optional agent_id checked against
the list. A conversation belongs to one agent (migration v3) and its turns
are submitted, polled and stopped at that agent. /v1/device is unchanged so
clients built earlier keep working.

Client: at Ready a swipe moves between agents; the name is shown through
the exchange; each agent keeps its own conversation; a follow-up goes to
the agent that answered. Reopened within the conversation window it opens
on the last agent, otherwise on the default. With one agent, or a bridge
without /v1/agents, nothing changes.

Also: contract section G, server survey and key evidence, the 0.1.2
upload, and the CODY-020 correction. Not reviewed, not deployed, not
uploaded.

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

432 lines
20 KiB
TypeScript

import { describe, expect, it } from 'vitest';
import { SCHEMA_VERSION, type TurnResult } from '@hermeven/contracts';
import { pollDelay } from '../src/core/controller.ts';
import { renderHud } from '../src/core/hud.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' }]);
});
});
describe('choosing an agent', () => {
const AGENTS = [
{ id: 'default', name: 'Pepper' },
{ id: 'wendy', name: 'Wendy' },
];
const WENDY_CONV = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';
const readyWithAgents = () =>
run(initialState, { type: 'init', paired: true, conversationId: CONV, captureMaxSeconds: 30, resumeRequestId: null, agents: AGENTS, agentId: null }).state;
const select: AppEvent = { type: 'agent_selected', agentId: 'wendy', conversationId: WENDY_CONV };
it('at Ready: the agent and its own conversation are swapped in under a new conversation epoch', () => {
const before = readyWithAgents();
const { state, effects } = run(before, select);
expect(effects).toEqual([]);
expect(state.phase).toBe('ready');
expect(state.agentId).toBe('wendy');
expect(state.conversationId).toBe(WENDY_CONV);
expect(state.conversationEpoch).toBe(before.conversationEpoch + 1);
expect(state.generation).toBe(before.generation + 1);
expect(renderHud(state, 0).body).toBe('Wendy\n\nReady.');
});
it('is ignored on every other screen: listening, in flight, an answer, an error, cancelled, unpaired', () => {
const base = readyWithAgents();
const others: AppState[] = [
run(base, { type: 'activate', freshId: ID1 }).state,
run(base, { type: 'submit_text', freshId: ID1, text: 'q' }).state,
run(base, { type: 'submit_text', freshId: ID1, text: 'q' }, { type: 'turn_update', generation: base.generation + 1, result: result(ID1), pages: ['a'] }).state,
run(base, { type: 'activate', freshId: ID1 }, { type: 'capture_failed', generation: base.generation + 1, reason: 'mic_refused' }).state,
run(base, { type: 'activate', freshId: ID1 }, { type: 'cancel' }).state,
{ ...initialState, agents: AGENTS },
];
expect(others.map((s) => s.phase)).toEqual(['listening', 'thinking', 'answer', 'error', 'cancelled', 'unpaired']);
for (const state of others) expect(reduce(state, select).state, state.phase).toBe(state);
});
it('an agent that is not offered, or the one already current, changes nothing', () => {
const base = readyWithAgents();
expect(reduce(base, { type: 'agent_selected', agentId: 'natalie', conversationId: null }).state).toBe(base);
expect(reduce(base, { type: 'agent_selected', agentId: 'default', conversationId: null }).state).toBe(base);
});
it('a conversation created for the previous agent cannot land on the new one', () => {
const base = readyWithAgents();
const creating = run(base, { type: 'new_conversation' }).state;
const moved = run(creating, { type: 'agent_selected', agentId: 'wendy', conversationId: null }).state;
const late = reduce(moved, { type: 'conversation_created', epoch: creating.conversationEpoch, conversationId: CONV }).state;
expect(late.conversationId).toBeNull();
expect(late.creatingConversation).toBe(false);
});
it('with one agent, or none listed, no screen mentions an agent', () => {
for (const agents of [[], [AGENTS[0]!]]) {
const state = run(initialState, { type: 'init', paired: true, conversationId: CONV, captureMaxSeconds: 30, resumeRequestId: null, agents }).state;
expect(renderHud(state, 0)).toEqual({ body: 'Hermeven\n\nReady.', status: 'Tap: ask · Double-tap: exit' });
}
});
});