import { measureTextWrap } from '@evenrealities/pretext'; import { SCHEMA_VERSION } from '@hermeven/contracts'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { Controller, type Snapshot } from '../../apps/even-client/src/core/controller.ts'; import { BridgeClient } from '../../apps/even-client/src/net/bridgeClient.ts'; import { ConfigError, loadConfig } from '../../services/bridge/src/config.ts'; import { FakeDevice } from '../fakes/fakeDevice.ts'; import { createHarness, type Harness } from './harness.ts'; /** * More than one agent behind one bridge. The bridge is real; Hermes is the TEST FAKE, which * imitates a gateway with multiplexed profiles: `/p//...`, each profile with its own * key, runs invisible from any other profile. No real Hermes, no glasses. */ const WENDY_KEY = 'wendy-profile-key-0123456789'; const CODY_KEY = 'cody-profile-key-0123456789'; const AGENT_ENV = { HERMEVEN_AGENT_NAME: 'Pepper', HERMEVEN_AGENTS: 'wendy,cody', HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY, HERMEVEN_AGENT_CODY_API_KEY: CODY_KEY, HERMEVEN_AGENT_CODY_NAME: 'Cody R.', }; let h: Harness; async function agentsHarness(env: Record = AGENT_ENV): Promise { h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2', ...env } }); h.hermes.profiles.set('wendy', WENDY_KEY); h.hermes.profiles.set('cody', CODY_KEY); } const newConversation = (token: string, agentId?: string) => h.api('POST', '/v1/conversations', { token, json: agentId === undefined ? { schema_version: SCHEMA_VERSION } : { schema_version: SCHEMA_VERSION, agent_id: agentId } }); const runsPosted = () => h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs'); afterEach(async () => { await h?.close(); }); describe('bridge: the agent list', () => { it('lists the configured agents, default first, by id and name only', async () => { await agentsHarness(); const { token } = await h.pair(); const res = await h.api('GET', '/v1/agents', { token }); expect(res.status).toBe(200); expect(res.body).toEqual({ schema_version: SCHEMA_VERSION, agents: [ { id: 'default', name: 'Pepper' }, { id: 'wendy', name: 'Wendy' }, { id: 'cody', name: 'Cody R.' }, ], }); const raw = JSON.stringify(res.body); for (const secret of [WENDY_KEY, CODY_KEY, h.hermes.apiKey, '/p/', h.hermes.url]) expect(raw).not.toContain(secret); }); it('needs a device credential', async () => { await agentsHarness(); expect((await h.api('GET', '/v1/agents')).status).toBe(401); expect((await h.api('GET', '/v1/agents', { token: 'x'.repeat(40) })).status).toBe(401); }); it('with no extra agents configured there is exactly one, and nothing else changes', async () => { h = await createHarness(); const { token } = await h.pair(); const res = await h.api('GET', '/v1/agents', { token }); expect(res.body.agents).toEqual([{ id: 'default', name: 'Agent' }]); const conversation = await h.conversation(token); const turn = await h.textTurn(token, conversation, 'hello'); await h.waitTerminal(token, turn.body.request_id); expect(h.hermes.executedBy).toEqual([null]); }); it('/v1/device is unchanged, so a client built before agents (which rejects unknown fields) keeps working', async () => { await agentsHarness(); const { token } = await h.pair(); const res = await h.api('GET', '/v1/device', { token }); expect(Object.keys(res.body).sort()).toEqual( ['active_conversation_id', 'agent_reachable', 'audio_format', 'device_id', 'device_name', 'limits', 'pairing_expires_at', 'schema_version', 'stt_configured', 'token_expires_at'].sort(), ); }); }); describe('bridge: a turn goes to the agent its conversation belongs to', () => { beforeEach(() => agentsHarness()); it('a conversation with Wendy is submitted and polled at her address with her key, and answered', async () => { const { token } = await h.pair(); const created = await newConversation(token, 'wendy'); expect(created.status).toBe(201); const turn = await h.textTurn(token, created.body.conversation_id, 'hello wendy'); const done = await h.waitTerminal(token, turn.body.request_id); expect(done.outcome).toBe('succeeded'); expect(done.answer_text).toContain('hello wendy'); expect(h.hermes.executedBy).toEqual(['wendy']); // Every request about that run went through her prefix (the fake hides it from any other). const about = h.hermes.requests.filter((r) => r.path.startsWith('/v1/runs')); expect(about.length).toBeGreaterThan(1); expect(about.every((r) => r.profile === 'wendy')).toBe(true); }); it('no agent named, or "default", goes to the default agent', async () => { const { token } = await h.pair(); const a = await h.conversation(token); const t1 = await h.textTurn(token, a, 'one'); await h.waitTerminal(token, t1.body.request_id); const b = await newConversation(token, 'default'); const t2 = await h.textTurn(token, b.body.conversation_id, 'two'); await h.waitTerminal(token, t2.body.request_id); expect(h.hermes.executedBy).toEqual([null, null]); }); it('an agent that is not on the list is refused, and nothing reaches Hermes', async () => { const { token } = await h.pair(); for (const bad of ['natalie', 'jeanette', 'nosuch']) { const res = await newConversation(token, bad); expect(res.status).toBe(400); expect(res.body.error.code).toBe('invalid_request'); } for (const malformed of ['../wendy', 'wendy/v1', 'Wendy', '', 'p/wendy', 'a'.repeat(40)]) { expect((await newConversation(token, malformed)).status).toBe(400); } expect(h.hermes.requests.filter((r) => r.path !== '/health')).toEqual([]); expect(h.bridge.db.prepare('SELECT COUNT(*) AS n FROM conversations').get()).toEqual({ n: 0 }); }); it('each agent has its own conversation: starting one with Wendy does not close Pepper\'s', async () => { const { token } = await h.pair(); const pepper = await h.conversation(token); const wendy1 = (await newConversation(token, 'wendy')).body.conversation_id as string; const t1 = await h.textTurn(token, pepper, 'still open?'); expect(t1.status).toBeLessThan(300); await h.waitTerminal(token, t1.body.request_id); // A NEW conversation with Wendy closes only her earlier one. const wendy2 = (await newConversation(token, 'wendy')).body.conversation_id as string; const closed = await h.textTurn(token, wendy1, 'old thread'); expect(closed.body.error.code).toBe('conversation_closed'); const t2 = await h.textTurn(token, wendy2, 'new thread'); await h.waitTerminal(token, t2.body.request_id); const t3 = await h.textTurn(token, pepper, 'and pepper again'); const done = await h.waitTerminal(token, t3.body.request_id); expect(done.answer_text).toContain('turn=2'); // Pepper's conversation kept its history expect(h.hermes.executedBy).toEqual([null, 'wendy', null]); expect(h.hermes.sessions.size).toBe(2); }); it('a lost reply from Hermes is retried at the same agent under the same key: one execution', async () => { const { token } = await h.pair(); const wendy = (await newConversation(token, 'wendy')).body.conversation_id as string; h.hermes.failNextSubmit('drop_response'); const turn = await h.textTurn(token, wendy, 'do it once'); const done = await h.waitTerminal(token, turn.body.request_id); expect(done.outcome).toBe('succeeded'); expect(h.hermes.executions).toBe(1); const posts = runsPosted(); expect(posts.length).toBe(2); expect(new Set(posts.map((p) => p.idempotencyKey)).size).toBe(1); expect(posts.every((p) => p.profile === 'wendy')).toBe(true); }); it('a bridge restart mid-run re-attaches to the same run at the same agent: one execution', async () => { const { token } = await h.pair(); const cody = (await newConversation(token, 'cody')).body.conversation_id as string; h.hermes.next({ kind: 'complete', afterMs: 400, output: 'reviewed' }); const turn = await h.textTurn(token, cody, 'review this'); await h.waitState(token, turn.body.request_id, 'thinking'); await h.restartBridge(); const done = await h.waitTerminal(token, turn.body.request_id, 5000); expect(done.outcome).toBe('succeeded'); expect(done.answer_text).toBe('reviewed'); expect(h.hermes.executedBy).toEqual(['cody']); expect(runsPosted().length).toBe(1); }); it('keys never appear in the bridge log', async () => { const { token } = await h.pair(); const wendy = (await newConversation(token, 'wendy')).body.conversation_id as string; const turn = await h.textTurn(token, wendy, 'hello'); await h.waitTerminal(token, turn.body.request_id); const log = h.logs.join(''); expect(log).toContain('conversation.created'); for (const secret of [WENDY_KEY, CODY_KEY, h.hermes.apiKey]) expect(log).not.toContain(secret); }); }); describe('bridge: when an agent cannot be used', () => { it('a wrong key for one agent fails that turn as "nothing ran" and leaves the others working', async () => { await agentsHarness({ ...AGENT_ENV, HERMEVEN_AGENT_WENDY_API_KEY: 'not-her-key-0123456789' }); const { token } = await h.pair(); const wendy = (await newConversation(token, 'wendy')).body.conversation_id as string; const t1 = await h.textTurn(token, wendy, 'hello'); const failed = await h.waitTerminal(token, t1.body.request_id); expect(failed.outcome).toBe('failed'); expect(failed.error?.code).toBe('agent_rejected'); expect(h.hermes.executions).toBe(0); const pepper = await h.conversation(token); const t2 = await h.textTurn(token, pepper, 'hello'); expect((await h.waitTerminal(token, t2.body.request_id)).outcome).toBe('succeeded'); }); it("the default agent's key is refused at another agent's address (the reason each needs its own)", async () => { await agentsHarness({ ...AGENT_ENV, HERMEVEN_AGENT_WENDY_API_KEY: 'fake-hermes-key' }); const { token } = await h.pair(); const wendy = (await newConversation(token, 'wendy')).body.conversation_id as string; const turn = await h.textTurn(token, wendy, 'hello'); expect((await h.waitTerminal(token, turn.body.request_id)).error?.code).toBe('agent_rejected'); expect(h.hermes.executions).toBe(0); }); it('an agent removed from the configuration: a turn in flight ends as unknown after a restart, never resent elsewhere', async () => { await agentsHarness(); const { token } = await h.pair(); const wendy = (await newConversation(token, 'wendy')).body.conversation_id as string; h.hermes.next({ kind: 'complete', afterMs: 600, output: 'late' }); const turn = await h.textTurn(token, wendy, 'in flight'); await h.waitState(token, turn.body.request_id, 'thinking'); // The owner takes Wendy off the list and restarts the bridge. (h.config.agents as unknown[]).splice(1, 1); await h.restartBridge(); const done = await h.waitTerminal(token, turn.body.request_id, 5000); expect(done.outcome).toBe('unknown'); expect(done.error?.code).toBe('outcome_unknown'); expect(h.hermes.executedBy).toEqual(['wendy']); // it ran once, at Wendy, and was not sent to anyone else expect((await newConversation(token, 'wendy')).status).toBe(400); }); }); describe('bridge configuration', () => { const base = { HERMES_API_KEY: 'k'.repeat(20), HERMEVEN_ALLOWED_ORIGINS: 'https://app.example', STT_PROVIDER: 'none' }; it('builds each extra agent as a profile under the same gateway', () => { const config = loadConfig({ ...base, HERMES_BASE_URL: 'http://127.0.0.1:8642/', ...AGENT_ENV, HERMEVEN_AGENT_CODY_PROFILE: 'cody-review' }); expect(config.agents.map((a) => [a.id, a.name, a.baseUrl])).toEqual([ ['default', 'Pepper', 'http://127.0.0.1:8642'], ['wendy', 'Wendy', 'http://127.0.0.1:8642/p/wendy'], ['cody', 'Cody R.', 'http://127.0.0.1:8642/p/cody-review'], ]); expect(config.agents[1]!.apiKey).toBe(WENDY_KEY); }); it('refuses a missing key, a repeated or reserved id, a malformed id, a bad profile and an over-long name', () => { const bad: Array> = [ { HERMEVEN_AGENTS: 'wendy' }, { HERMEVEN_AGENTS: 'wendy,wendy', HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY }, { HERMEVEN_AGENTS: 'default', HERMEVEN_AGENT_DEFAULT_API_KEY: WENDY_KEY }, { HERMEVEN_AGENTS: 'Wendy', HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY }, { HERMEVEN_AGENTS: '../x' }, { HERMEVEN_AGENTS: 'wendy', HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY, HERMEVEN_AGENT_WENDY_PROFILE: '../default' }, { HERMEVEN_AGENTS: 'wendy', HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY, HERMEVEN_AGENT_WENDY_NAME: 'x'.repeat(25) }, ]; for (const env of bad) expect(() => loadConfig({ ...base, ...env }), JSON.stringify(env)).toThrow(ConfigError); }); }); // ------------------------------------------------------------------ client let device: FakeDevice; let controller: Controller; let snapshot: Snapshot; let sent: Array<{ method: string; path: string; body: string }>; let agentsRoute: 'real' | 'not_found' | 'offline'; let extras: Partial[0]>; function makeController(dev: FakeDevice): Controller { return new Controller({ idleExit: null, ...extras, 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) => { const path = new URL(String(input)).pathname; sent.push({ method: init?.method ?? 'GET', path, body: typeof init?.body === 'string' ? init.body : '' }); if (path === '/v1/agents' && agentsRoute === 'offline') throw new TypeError('offline'); if (path === '/v1/agents' && agentsRoute === 'not_found') { // What a bridge from before agent selection answers. return new Response(JSON.stringify({ schema_version: SCHEMA_VERSION, error: { code: 'not_found', message: 'Not found.', retryable: false } }), { status: 404, headers: { 'Content-Type': 'application/json' }, }); } return fetch(input, init); }, }), onChange: (s) => { snapshot = s; }, }); } async function until(what: string, predicate: () => boolean, timeoutMs = 4000): Promise { 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; const quiet = (ms: number) => new Promise((r) => setTimeout(r, ms)); async function paired(): Promise { device = new FakeDevice(); controller = makeController(device); await controller.start(); await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2'); expect(phase()).toBe('ready'); } /** The page is closed and opened again: same phone storage, new everything else. */ async function relaunch(): Promise { 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(); } async function ask(text: string): Promise { controller.askText(text); await until('answer', () => phase() === 'answer'); } const backToReady = async () => { device.doubleTap(); await until('ready', () => phase() === 'ready'); }; describe('glasses: choosing an agent', () => { beforeEach(async () => { sent = []; agentsRoute = 'real'; extras = {}; await agentsHarness(); }); afterEach(async () => { await controller?.stop(); }); it('opens on the default agent and shows its name; a swipe at Ready moves through the list and wraps', async () => { await paired(); expect(device.frame.body).toBe('Pepper\n\nReady.'); expect(device.frame.status).toContain('Swipe: agent'); const seen: string[] = []; for (let i = 0; i < 3; i++) { device.swipeDown(); seen.push(device.frame.body.split('\n')[0]!); } expect(seen).toEqual(['Wendy', 'Cody R.', 'Pepper']); device.swipeUp(); expect(device.frame.body).toBe('Cody R.\n\nReady.'); device.swipeUp(); expect(device.frame.body).toBe('Wendy\n\nReady.'); // Choosing asks the bridge for nothing and sends nothing to any agent. expect(sent.filter((s) => s.path === '/v1/conversations' || s.path === '/v1/turns')).toEqual([]); expect(h.hermes.executions).toBe(0); }); it('a question after choosing Wendy goes to Wendy, every screen says so, and a follow-up continues with her', async () => { await paired(); device.swipeDown(); h.hermes.next({ kind: 'complete', afterMs: 250 }); controller.askText('what is on the calendar'); await until('thinking', () => phase() === 'thinking'); expect(device.frame.body).toBe('Wendy is thinking…'); await until('answer', () => phase() === 'answer'); expect(device.frame.status).toContain('Wendy · Tap: ask'); expect(h.hermes.executedBy).toEqual(['wendy']); await ask('and tomorrow'); expect(device.frame.body).toContain('turn=2'); expect(h.hermes.executedBy).toEqual(['wendy', 'wendy']); expect(h.hermes.sessions.size).toBe(1); const creates = sent.filter((s) => s.path === '/v1/conversations'); expect(creates.map((c) => JSON.parse(c.body).agent_id)).toEqual(['wendy']); }); it('spoken questions too: the recording goes to the chosen agent', async () => { await paired(); device.swipeDown(); device.swipeDown(); device.tap(); await until('listening', () => phase() === 'listening' && device.micOpen); expect(device.frame.body).toContain('Cody R. is listening…'); device.speak(0.5); device.tap(); await until('answer', () => phase() === 'answer'); expect(h.hermes.executedBy).toEqual(['cody']); }); it('each agent keeps its own conversation across switches', async () => { await paired(); await ask('pepper one'); await backToReady(); device.swipeDown(); await ask('wendy one'); await backToReady(); device.swipeUp(); expect(device.frame.body).toBe('Pepper\n\nReady.'); await ask('pepper two'); expect(device.frame.body).toContain('turn=2'); expect(device.frame.body).toContain('pepper one'); await backToReady(); device.swipeDown(); await ask('wendy two'); expect(device.frame.body).toContain('turn=2'); expect(device.frame.body).toContain('wendy one'); expect(h.hermes.executedBy).toEqual([null, 'wendy', null, 'wendy']); expect(h.hermes.sessions.size).toBe(2); expect(sent.filter((s) => s.path === '/v1/conversations').length).toBe(2); }); it('a swipe only chooses at Ready: on an answer it turns the page, and while busy it does nothing', async () => { await paired(); device.swipeDown(); // Wendy h.hermes.next({ kind: 'complete', afterMs: 250, output: Array.from({ length: 80 }, (_, i) => `Sentence ${i + 1} of a long answer.`).join(' ') }); controller.askText('long one'); await until('thinking', () => phase() === 'thinking'); device.swipeDown(); device.swipeUp(); expect(snapshot.state.agentId).toBe('wendy'); await until('answer', () => phase() === 'answer'); expect(snapshot.state.pageIndex).toBe(0); device.swipeDown(); expect(snapshot.state.pageIndex).toBe(1); expect(snapshot.state.agentId).toBe('wendy'); device.tap(); await until('listening', () => phase() === 'listening' && device.micOpen); device.swipeDown(); expect(snapshot.state.agentId).toBe('wendy'); expect(phase()).toBe('listening'); device.doubleTap(); }); it('moving to another agent while a conversation is being created does not hand it to the wrong one', async () => { await paired(); device.swipeDown(); // Wendy controller.askText('for wendy'); device.swipeDown(); // ignored: no longer at Ready await until('answer', () => phase() === 'answer'); expect(h.hermes.executedBy).toEqual(['wendy']); await backToReady(); device.swipeDown(); // Cody await ask('for cody'); expect(h.hermes.executedBy).toEqual(['wendy', 'cody']); expect(device.frame.body).toContain('turn=1'); }); }); describe('glasses: which agent it reopens on', () => { beforeEach(async () => { sent = []; agentsRoute = 'real'; extras = {}; await agentsHarness(); }); afterEach(async () => { await controller?.stop(); }); it('reopened soon after talking to Wendy: opens on Wendy, same conversation', async () => { await paired(); device.swipeDown(); await ask('wendy one'); await until('saved', () => JSON.parse(device.storage.get('hermeven.v1')!).agentId === 'wendy' && typeof JSON.parse(device.storage.get('hermeven.v1')!).lastTurnAt === 'number'); await relaunch(); expect(device.frame.body).toBe('Wendy\n\nReady.'); await ask('wendy two'); expect(device.frame.body).toContain('turn=2'); expect(h.hermes.executedBy).toEqual(['wendy', 'wendy']); }); it('reopened after the conversation window: opens on the default agent, and Wendy starts fresh when chosen again', async () => { extras = { conversationGapMs: 60 }; await paired(); device.swipeDown(); await ask('wendy one'); await until('saved', () => typeof JSON.parse(device.storage.get('hermeven.v1')!).lastTurnAt === 'number'); await quiet(130); await relaunch(); expect(device.frame.body).toBe('Pepper\n\nReady.'); await ask('pepper one'); expect(h.hermes.executedBy).toEqual(['wendy', null]); await backToReady(); device.swipeDown(); await ask('wendy again'); expect(device.frame.body).toContain('turn=1'); // a new conversation with her expect(h.hermes.sessions.size).toBe(3); }); it('chosen but never asked: reopening goes back to the default agent', async () => { await paired(); device.swipeDown(); await until('saved', () => JSON.parse(device.storage.get('hermeven.v1')!).agentId === 'wendy'); await relaunch(); expect(device.frame.body).toBe('Pepper\n\nReady.'); }); it('the last agent has been taken off the list: opens on the default agent', async () => { await paired(); device.swipeDown(); await ask('wendy one'); await until('saved', () => typeof JSON.parse(device.storage.get('hermeven.v1')!).lastTurnAt === 'number'); (h.config.agents as unknown[]).splice(1, 1); await h.restartBridge(); // (same address is not guaranteed after a restart in this harness: re-point the stored URL) const stored = JSON.parse(device.storage.get('hermeven.v1')!); device.storage.set('hermeven.v1', JSON.stringify({ ...stored, bridgeUrl: h.url })); await relaunch(); expect(device.frame.body).toBe('Pepper\n\nReady.'); expect(snapshot.state.agents.map((a) => a.id)).toEqual(['default', 'cody']); }); it('the bridge cannot be reached for the list at start: the last known list is used', async () => { await paired(); device.swipeDown(); await ask('wendy one'); await until('saved', () => typeof JSON.parse(device.storage.get('hermeven.v1')!).lastTurnAt === 'number'); agentsRoute = 'offline'; await relaunch(); expect(snapshot.state.agents.map((a) => a.id)).toEqual(['default', 'wendy', 'cody']); expect(device.frame.body).toBe('Wendy\n\nReady.'); }); }); describe('glasses: with a bridge that offers no choice', () => { afterEach(async () => { await controller?.stop(); }); it('a bridge with one agent: the screen is as before, a swipe at Ready does nothing, and no agent is named in requests', async () => { sent = []; agentsRoute = 'real'; extras = {}; h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2' } }); await paired(); expect(device.frame).toEqual({ body: 'Hermeven\n\nReady.', status: 'Tap: ask · Double-tap: exit' }); device.swipeDown(); device.swipeUp(); expect(device.frame.body).toBe('Hermeven\n\nReady.'); await ask('hello'); expect(device.frame.status).toBe('Tap: ask'); expect(sent.filter((s) => s.path === '/v1/conversations').map((c) => JSON.parse(c.body))).toEqual([{ schema_version: SCHEMA_VERSION }]); }); it('a bridge from before agent selection (no /v1/agents): the same, and it still answers', async () => { sent = []; agentsRoute = 'not_found'; extras = {}; await agentsHarness(); await paired(); expect(snapshot.state.agents).toEqual([]); expect(device.frame.body).toBe('Hermeven\n\nReady.'); device.swipeDown(); await ask('hello'); expect(h.hermes.executedBy).toEqual([null]); expect(sent.filter((s) => s.path === '/v1/conversations').map((c) => JSON.parse(c.body))).toEqual([{ schema_version: SCHEMA_VERSION }]); }); });