import { randomUUID } from 'node:crypto'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { check, DeviceStatusResponse, SCHEMA_VERSION, TurnResult } from '@hermeven/contracts'; import { syntheticPcm } from '../fakes/fakeStt.ts'; import { createHarness, type Harness } from './harness.ts'; /** * Bridge behaviour over real HTTP, with the real Hermes Runs adapter and the real * STT adapter talking to TEST FAKES. Evidence about Hermeven's own logic only. */ let h: Harness; afterEach(async () => { await h?.close(); }); describe('health, auth and binding', () => { beforeEach(async () => { h = await createHarness(); }); it('healthz is minimal and unauthenticated', async () => { const res = await h.api('GET', '/healthz'); expect(res.status).toBe(200); expect(res.body).toEqual({ status: 'ok', schema_version: SCHEMA_VERSION }); }); it('rejects missing, malformed and unknown credentials', async () => { expect((await h.api('GET', '/v1/device')).status).toBe(401); expect((await h.api('GET', '/v1/device', { token: 'hvn_nope' })).status).toBe(401); expect((await h.api('GET', '/v1/device', { headers: { Authorization: 'Basic abc' } })).status).toBe(401); const turn = await h.textTurn('hvn_nope', randomUUID(), 'hi'); expect(turn.status).toBe(401); expect(turn.body.error.code).toBe('unauthorized'); expect(h.hermes.executions).toBe(0); }); it('device status matches the contract and exposes no secrets', async () => { const cred = await h.pair(); const res = await h.api('GET', '/v1/device', { token: cred.token }); expect(res.status).toBe(200); expect(check(DeviceStatusResponse, res.body)).toBe(true); expect(res.body.agent_reachable).toBe(true); expect(res.body.stt_configured).toBe(true); const text = JSON.stringify(res.body); expect(text).not.toContain(h.hermes.apiKey); expect(text).not.toContain(h.stt.apiKey); expect(text).not.toContain(h.hermes.url); }); it('a device cannot use, read or cancel another device’s conversation or turn', async () => { const a = await h.pair('a'); const b = await h.pair('b'); const convA = await h.conversation(a.token); h.hermes.next({ kind: 'hang' }); const turnA = await h.textTurn(a.token, convA, 'private question'); expect(turnA.status).toBe(202); const id = turnA.body.request_id; expect((await h.textTurn(b.token, convA, 'intrude')).body.error.code).toBe('not_found'); expect((await h.api('GET', `/v1/turns/${id}`, { token: b.token })).status).toBe(404); expect((await h.api('POST', `/v1/turns/${id}/cancel`, { token: b.token, json: {} })).status).toBe(404); // Reusing A's request id from B is a conflict and never reveals A's turn. const reuse = await h.textTurn(b.token, await h.conversation(b.token), 'private question', id); expect(reuse.status).toBe(409); expect(reuse.body.error.code).toBe('request_id_conflict'); expect(JSON.stringify(reuse.body)).not.toContain('private'); await h.api('POST', `/v1/turns/${id}/cancel`, { token: a.token, json: {} }); await h.waitTerminal(a.token, id); }); it('never forwards a client-chosen Hermes session: unknown fields are rejected', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); const res = await h.api('POST', '/v1/turns', { token: cred.token, json: { schema_version: SCHEMA_VERSION, request_id: randomUUID(), conversation_id: conv, locale: 'en-US', input: { kind: 'text', text: 'hi' }, session_id: 'someone-elses-session', }, }); expect(res.status).toBe(400); expect(h.hermes.executions).toBe(0); }); it('revocation takes effect immediately and closes the conversation', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); expect((await h.api('DELETE', '/v1/device', { token: cred.token })).body).toEqual({ schema_version: 1, revoked: true }); expect((await h.api('GET', '/v1/device', { token: cred.token })).status).toBe(401); expect((await h.textTurn(cred.token, conv, 'hi')).status).toBe(401); expect(h.hermes.executions).toBe(0); }); it('renewal rotates the token; the old one stops working', async () => { const cred = await h.pair(); const renewed = await h.api('POST', '/v1/device/renew', { token: cred.token, json: {} }); expect(renewed.status).toBe(200); expect(renewed.body.token).not.toBe(cred.token); expect((await h.api('GET', '/v1/device', { token: cred.token })).status).toBe(401); expect((await h.api('GET', '/v1/device', { token: renewed.body.token })).status).toBe(200); }); it('CORS allows only the configured origin and is not a substitute for auth', async () => { const ok = await h.api('OPTIONS', '/v1/turns', { headers: { Origin: 'https://app.example', 'Access-Control-Request-Method': 'POST', 'Access-Control-Request-Headers': 'authorization,content-type' }, }); expect(ok.headers.get('access-control-allow-origin')).toBe('https://app.example'); const bad = await h.api('OPTIONS', '/v1/turns', { headers: { Origin: 'https://evil.example', 'Access-Control-Request-Method': 'POST' }, }); expect(bad.headers.get('access-control-allow-origin')).toBeNull(); const authed = await h.api('GET', '/v1/device', { headers: { Origin: 'https://app.example' } }); expect(authed.status).toBe(401); }); }); describe('pairing', () => { it('codes are single-use', async () => { h = await createHarness(); const { code } = h.bridge.devices.createPairingCode(); const claim = () => h.api('POST', '/v1/pairing/claim', { json: { schema_version: 1, code, device_name: 'x' } }); expect((await claim()).status).toBe(201); const second = await claim(); expect(second.status).toBe(401); expect(second.body.error.code).toBe('pairing_invalid'); }); it('unrelated wrong guesses cannot invalidate the owner\'s real code (CODY-010)', async () => { h = await createHarness({ env: { HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE: '60' } }); const { code } = h.bridge.devices.createPairingCode(); const guess = (c: string) => h.api('POST', '/v1/pairing/claim', { json: { schema_version: 1, code: c, device_name: 'x' } }); const responses = []; for (let i = 0; i < 40; i++) responses.push(await guess(`AAAAA-AAA${String(i).padStart(2, '0')}`.replace(/[01]/g, 'B'))); // Every failure looks the same: same status, same code, same message, nothing about lockout. expect(new Set(responses.map((r) => `${r.status} ${JSON.stringify(r.body)}`)).size).toBe(1); expect(responses[0]!.status).toBe(401); expect(responses[0]!.body.error).toEqual({ code: 'pairing_invalid', message: 'Pairing code is not valid.', retryable: false }); // The real code still works after forty wrong guesses. expect((await guess(code)).status).toBe(201); // And then it is spent, with the same indistinguishable failure. const spent = await guess(code); expect(`${spent.status} ${JSON.stringify(spent.body)}`).toBe(`${responses[0]!.status} ${JSON.stringify(responses[0]!.body)}`); }); it('an expired code fails exactly like a wrong one', async () => { h = await createHarness({ env: { HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE: '60' } }); const { code } = h.bridge.devices.createPairingCode(); h.bridge.db.prepare('UPDATE pairing_codes SET expires_at = 1').run(); const guess = (c: string) => h.api('POST', '/v1/pairing/claim', { json: { schema_version: 1, code: c, device_name: 'x' } }); const expired = await guess(code); const wrong = await guess('ZZZZZ-ZZZZZ'); expect(expired.status).toBe(401); expect(expired.body).toEqual(wrong.body); }); it('brute force stays bounded: a client gets its per-minute attempts and no more, and still cannot burn the code', async () => { h = await createHarness({ env: { HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE: '5' } }); const { code } = h.bridge.devices.createPairingCode(); const guess = (c: string) => h.api('POST', '/v1/pairing/claim', { json: { schema_version: 1, code: c, device_name: 'x' } }); const statuses = []; for (let i = 0; i < 30; i++) statuses.push((await guess('ZZZZZ-ZZZZZ')).status); expect(statuses.filter((s) => s === 401)).toHaveLength(5); expect(statuses.filter((s) => s === 429)).toHaveLength(25); // The limiter is per client address. The owner pairing from another address is unaffected, // which is exercised here at the layer below HTTP because the test has one address. expect(h.bridge.devices.claimPairingCode(code, 'owner').ok).toBe(true); }); it('claim attempts are rate limited per client', async () => { h = await createHarness({ env: { HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE: '2' } }); const guess = () => h.api('POST', '/v1/pairing/claim', { json: { schema_version: 1, code: 'AAAAA-AAAAA', device_name: 'x' } }); await guess(); await guess(); const third = await guess(); expect(third.status).toBe(429); expect(third.body.error.code).toBe('rate_limited'); }); }); describe('validation and limits', () => { beforeEach(async () => { h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2', HERMEVEN_TURNS_PER_MINUTE: '3' } }); }); it('rejects unknown schema versions', async () => { const cred = await h.pair(); const res = await h.api('POST', '/v1/turns', { token: cred.token, json: { schema_version: 2, request_id: randomUUID(), conversation_id: randomUUID(), locale: 'en-US', input: { kind: 'text', text: 'hi' } }, }); expect(res.status).toBe(400); expect(res.body.error.code).toBe('unsupported_schema_version'); }); it('rejects oversized audio, odd byte counts, wrong formats and wrong content types', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); // Cap is 2 s (+1 s headroom) = 96,000 bytes. const big = await h.audioTurn(cred.token, conv, syntheticPcm(4)); expect(big.status).toBe(413); expect(big.body.error.code).toBe('payload_too_large'); const odd = await h.audioTurn(cred.token, conv, Buffer.alloc(1001)); expect(odd.status).toBe(400); const rate = await h.audioTurn(cred.token, conv, syntheticPcm(0.5), randomUUID(), { sample_rate: '44100' }); expect(rate.status).toBe(415); expect(rate.body.error.code).toBe('unsupported_media'); const type = await h.api('POST', '/v1/turns', { token: cred.token, body: Buffer.from('x'), headers: { 'Content-Type': 'text/plain' } }); expect(type.status).toBe(415); const bigJson = await h.textTurn(cred.token, conv, 'x'.repeat(5000)); expect(bigJson.status).toBe(400); expect(h.hermes.executions).toBe(0); expect(h.stt.calls).toBe(0); }); it('rate limits new turns per device but never a duplicate of an existing one', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); const ids: string[] = []; for (let i = 0; i < 3; i++) { const res = await h.textTurn(cred.token, conv, `q${i}`); expect(res.status).toBe(202); ids.push(res.body.request_id); await h.waitTerminal(cred.token, res.body.request_id); } const over = await h.textTurn(cred.token, conv, 'q4'); expect(over.status).toBe(429); const dup = await h.textTurn(cred.token, conv, 'q0', ids[0]); expect(dup.status).toBe(200); expect(dup.body.replayed).toBe(true); expect(h.hermes.executions).toBe(3); }); }); describe('turn lifecycle', () => { beforeEach(async () => { h = await createHarness(); }); it('typed text -> agent -> complete answer, result matches the contract', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); const long = 'Paris. '.repeat(900); // ~6 kB: must come back untruncated h.hermes.next({ kind: 'complete', output: long }); const res = await h.textTurn(cred.token, conv, 'What is the capital of France?'); expect(res.status).toBe(202); const done = await h.waitTerminal(cred.token, res.body.request_id); expect(check(TurnResult, done)).toBe(true); expect(done.outcome).toBe('succeeded'); expect(done.answer_text).toBe(long); expect(done.error).toBeNull(); expect(done.timings.agent_ms).toBeGreaterThanOrEqual(0); // Hermes received our own opaque session id and the forwarded idempotency key. const run = h.hermes.lastRun()!; expect(run.sessionId).toMatch(/^hermeven-[0-9a-f-]{36}$/); expect(run.key).toBe(`hermeven-turn-${res.body.request_id}`); }); it('audio -> STT -> agent: uploads a valid 16 kHz mono WAV and sends the transcript', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.stt.next({ text: 'how tall is mount everest' }); const res = await h.audioTurn(cred.token, conv, syntheticPcm(1.5)); expect(res.status).toBe(202); const done = await h.waitTerminal(cred.token, res.body.request_id); expect(done.outcome).toBe('succeeded'); expect(done.input_text).toBe('how tall is mount everest'); expect(h.stt.lastWav).toEqual({ sampleRate: 16000, channels: 1, bitsPerSample: 16, dataBytes: 48000 }); expect(h.stt.lastFields).toMatchObject({ model: 'fake-whisper', language: 'en' }); expect(h.hermes.lastRun()!.input).toBe('how tall is mount everest'); expect(done.timings.transcribe_ms).toBeGreaterThanOrEqual(0); }); it('a follow-up lands in the same Hermes session; a new conversation gets a fresh one', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); const first = await h.textTurn(cred.token, conv, 'My name is Ada.'); await h.waitTerminal(cred.token, first.body.request_id); const second = await h.textTurn(cred.token, conv, 'What is my name?'); const answer = await h.waitTerminal(cred.token, second.body.request_id); // The fake echoes the previous input of the same session. expect(answer.answer_text).toContain('turn=2'); expect(answer.answer_text).toContain('previous="My name is Ada."'); const conv2 = await h.conversation(cred.token); expect(conv2).not.toBe(conv); const third = await h.textTurn(cred.token, conv2, 'What is my name?'); const fresh = await h.waitTerminal(cred.token, third.body.request_id); expect(fresh.answer_text).toContain('turn=1'); expect(fresh.answer_text).toContain('previous=null'); // The old conversation is closed, not silently reused. const stale = await h.textTurn(cred.token, conv, 'still there?'); expect(stale.status).toBe(409); expect(stale.body.error.code).toBe('conversation_closed'); expect(h.hermes.sessions.size).toBe(2); }); it('turns in one conversation are serialised', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'complete', afterMs: 200 }); const first = await h.textTurn(cred.token, conv, 'one'); const second = await h.textTurn(cred.token, conv, 'two'); expect(second.status).toBe(409); expect(second.body.error.code).toBe('conversation_busy'); await h.waitTerminal(cred.token, first.body.request_id); expect(h.hermes.executions).toBe(1); }); it('distinguishes failed, incomplete, interrupted and unknown agent outcomes', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); const run = async (text: string) => { const res = await h.textTurn(cred.token, conv, text); return h.waitTerminal(cred.token, res.body.request_id); }; h.hermes.next({ kind: 'fail', error: 'provider said sk-secret-123' }); const failed = await run('a'); expect(failed.outcome).toBe('failed'); expect(failed.error).toMatchObject({ code: 'agent_failed', retryable: false }); // Hermes' diagnostic text is never relayed to the client. expect(JSON.stringify(failed)).not.toContain('sk-secret-123'); h.hermes.next({ kind: 'incomplete', output: 'So far I found two of three.' }); const incomplete = await run('b'); expect(incomplete.outcome).toBe('incomplete'); expect(incomplete.answer_text).toBe('So far I found two of three.'); expect(incomplete.error?.code).toBe('agent_incomplete'); h.hermes.next({ kind: 'interrupted' }); const interrupted = await run('c'); expect(interrupted.outcome).toBe('failed'); expect(interrupted.error?.code).toBe('agent_interrupted'); h.hermes.next({ kind: 'unknown' }); const unknown = await run('d'); expect(unknown.outcome).toBe('unknown'); expect(unknown.error).toMatchObject({ code: 'outcome_unknown', retryable: false }); }); it('approval-required is surfaced, never auto-approved, and resolves when approved elsewhere', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'approval' }); const res = await h.textTurn(cred.token, conv, 'delete the file'); const waiting = await h.waitState(cred.token, res.body.request_id, 'approval_required'); expect(waiting.terminal).toBe(false); expect(h.hermes.requests.some((r) => r.path.endsWith('/approval'))).toBe(false); h.hermes.approve(h.hermes.lastRun()!.runId, 'file deleted'); const done = await h.waitTerminal(cred.token, res.body.request_id); expect(done.outcome).toBe('succeeded'); expect(done.answer_text).toBe('file deleted'); }); it('an approval that never arrives ends as stopped, with a distinct code', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'approval' }); const res = await h.textTurn(cred.token, conv, 'delete the file'); const done = await h.waitTerminal(cred.token, res.body.request_id); expect(done.outcome).toBe('cancelled'); expect(done.error?.code).toBe('approval_timeout'); expect(h.hermes.requests.some((r) => r.path.endsWith('/approval'))).toBe(false); }); it('agent deadline: stop is requested and confirmed; unconfirmed stop is unknown, not replayed', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'hang' }); const a = await h.textTurn(cred.token, conv, 'slow'); const timedOut = await h.waitTerminal(cred.token, a.body.request_id); expect(timedOut.outcome).toBe('cancelled'); expect(timedOut.error?.code).toBe('agent_timeout'); h.hermes.next({ kind: 'hang' }); h.hermes.ignoreStop(); const b = await h.textTurn(cred.token, conv, 'slow and stubborn'); const unknown = await h.waitTerminal(cred.token, b.body.request_id); expect(unknown.outcome).toBe('unknown'); expect(unknown.error?.code).toBe('outcome_unknown'); expect(h.hermes.executions).toBe(2); }); }); describe('STT failures', () => { beforeEach(async () => { h = await createHarness(); }); it('provider error, empty transcript and timeout each fail cleanly without reaching the agent', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); const run = async () => { const res = await h.audioTurn(cred.token, conv, syntheticPcm(0.5)); return h.waitTerminal(cred.token, res.body.request_id); }; h.stt.next({ status: 500 }); expect((await run()).error).toMatchObject({ code: 'stt_unavailable', retryable: true }); h.stt.next({ status: 400 }); expect((await run()).error?.code).toBe('stt_failed'); h.stt.next({ text: ' ' }); expect((await run()).error?.code).toBe('stt_empty'); h.stt.next({ delayMs: 1500, text: 'too late' }); expect((await run()).error?.code).toBe('stt_timeout'); expect(h.hermes.executions).toBe(0); }); it('with no STT configured, audio fails cleanly and typed text still works', async () => { await h.close(); h = await createHarness({ stt: false }); const cred = await h.pair(); const conv = await h.conversation(cred.token); const audio = await h.audioTurn(cred.token, conv, syntheticPcm(0.5)); expect((await h.waitTerminal(cred.token, audio.body.request_id)).error?.code).toBe('stt_unavailable'); const text = await h.textTurn(cred.token, conv, 'hello'); expect((await h.waitTerminal(cred.token, text.body.request_id)).outcome).toBe('succeeded'); }); }); describe('duplicates, retries, cancellation and recovery', () => { beforeEach(async () => { h = await createHarness(); }); it('duplicate submits of one request id execute once', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); const id = randomUUID(); const results = await Promise.all(Array.from({ length: 8 }, () => h.textTurn(cred.token, conv, 'run the tool', id))); expect(results.filter((r) => r.status === 202)).toHaveLength(1); expect(results.filter((r) => r.status === 200 && r.body.replayed)).toHaveLength(7); await h.waitTerminal(cred.token, id); const late = await h.textTurn(cred.token, conv, 'run the tool', id); expect(late.status).toBe(200); expect(late.body.outcome).toBe('succeeded'); expect(h.hermes.executions).toBe(1); // Same id, different payload: refused. const conflict = await h.textTurn(cred.token, conv, 'run a different tool', id); expect(conflict.status).toBe(409); expect(h.hermes.executions).toBe(1); }); it('a lost Hermes response is retried under the same idempotency key: one execution', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.failNextSubmit('drop_response', 'http_500'); const res = await h.textTurn(cred.token, conv, 'charge the card'); const done = await h.waitTerminal(cred.token, res.body.request_id); expect(done.outcome).toBe('succeeded'); expect(h.hermes.executions).toBe(1); const posts = h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs'); expect(posts).toHaveLength(3); expect(new Set(posts.map((p) => p.idempotencyKey)).size).toBe(1); }); it('if no answer to the submit ever arrives, the deadline ends as unknown, never as "safe to retry"', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.failNextSubmit(...Array(500).fill('drop_response')); const res = await h.textTurn(cred.token, conv, 'send the email'); const done = await h.waitTerminal(cred.token, res.body.request_id); expect(done.outcome).toBe('unknown'); expect(done.error).toMatchObject({ code: 'outcome_unknown', retryable: false }); // Hermes did run it (once); the bridge could not know, and said so. expect(h.hermes.executions).toBe(1); const posts = h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs'); expect(posts.length).toBeGreaterThan(1); expect(new Set(posts.map((p) => p.idempotencyKey)).size).toBe(1); }); it('busy Hermes (503) is retried; a 4xx rejection is final and nothing ran', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.failNextSubmit('http_503', 'http_503'); const ok = await h.textTurn(cred.token, conv, 'hello'); expect((await h.waitTerminal(cred.token, ok.body.request_id)).outcome).toBe('succeeded'); h.hermes.failNextSubmit('http_400'); const bad = await h.textTurn(cred.token, conv, 'hello again'); const rejected = await h.waitTerminal(cred.token, bad.body.request_id); expect(rejected.error?.code).toBe('agent_rejected'); expect(h.hermes.executions).toBe(1); }); it('Hermes down before anything was sent: fails as retryable, provably nothing ran', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); await h.hermes.stop(); const res = await h.textTurn(cred.token, conv, 'anyone there'); const done = await h.waitTerminal(cred.token, res.body.request_id); expect(done.outcome).toBe('failed'); expect(done.error).toMatchObject({ code: 'agent_unreachable', retryable: true }); expect(h.hermes.executions).toBe(0); }); it('cancel during transcription is clean and never reaches the agent', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.stt.next({ delayMs: 300, text: 'never used' }); const res = await h.audioTurn(cred.token, conv, syntheticPcm(0.5)); await h.waitState(cred.token, res.body.request_id, 'transcribing'); const cancel = await h.api('POST', `/v1/turns/${res.body.request_id}/cancel`, { token: cred.token, json: {} }); expect(cancel.status).toBe(200); const done = await h.waitTerminal(cred.token, res.body.request_id); expect(done.outcome).toBe('cancelled'); expect(done.error).toBeNull(); expect(h.hermes.executions).toBe(0); }); it('cancel while the agent runs asks Hermes to stop; repeated cancels are idempotent', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'hang' }); const res = await h.textTurn(cred.token, conv, 'long job'); await h.waitState(cred.token, res.body.request_id, 'thinking'); const cancels = await Promise.all( Array.from({ length: 5 }, () => h.api('POST', `/v1/turns/${res.body.request_id}/cancel`, { token: cred.token, json: {} })), ); expect(cancels.every((c) => c.status === 200 && c.body.cancel_requested)).toBe(true); const done = await h.waitTerminal(cred.token, res.body.request_id); expect(done.outcome).toBe('cancelled'); expect(done.cancel_requested).toBe(true); expect(h.hermes.requests.filter((r) => r.path.endsWith('/stop'))).toHaveLength(1); // Cancelling a finished turn changes nothing. const after = await h.api('POST', `/v1/turns/${res.body.request_id}/cancel`, { token: cred.token, json: {} }); expect(after.body.outcome).toBe('cancelled'); // The conversation is usable again. const next = await h.textTurn(cred.token, conv, 'next'); expect((await h.waitTerminal(cred.token, next.body.request_id)).outcome).toBe('succeeded'); }); it('a cancel that loses the race reports what really happened', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'complete', afterMs: 60, output: 'already done' }); h.hermes.ignoreStop(); const res = await h.textTurn(cred.token, conv, 'quick job'); await h.waitState(cred.token, res.body.request_id, 'thinking'); await h.api('POST', `/v1/turns/${res.body.request_id}/cancel`, { token: cred.token, json: {} }); const done = await h.waitTerminal(cred.token, res.body.request_id); expect(done.outcome).toBe('succeeded'); expect(done.cancel_requested).toBe(true); expect(done.answer_text).toBe('already done'); }); it('bridge restart mid-run re-attaches to the same run: one execution, answer delivered', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'complete', afterMs: 400, output: 'survived the restart' }); const res = await h.textTurn(cred.token, conv, 'long job'); await h.waitState(cred.token, res.body.request_id, 'thinking'); await h.restartBridge(); const done = await h.waitTerminal(cred.token, res.body.request_id); expect(done.outcome).toBe('succeeded'); expect(done.answer_text).toBe('survived the restart'); expect(h.hermes.executions).toBe(1); }); it('bridge crash between sending and recording the run id replays the same key, not a new run', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'complete', afterMs: 300, output: 'only once' }); // Hermes admits the run but the bridge never learns the run id, then the bridge dies. h.hermes.failNextSubmit('drop_response', 'drop_response', 'drop_response', 'drop_response'); const res = await h.textTurn(cred.token, conv, 'transfer money'); await new Promise((r) => setTimeout(r, 80)); expect(h.hermes.executions).toBe(1); await h.restartBridge(); h.hermes.failNextSubmit(); // no more faults const done = await h.waitTerminal(cred.token, res.body.request_id); expect(done.outcome).toBe('succeeded'); expect(done.answer_text).toBe('only once'); expect(h.hermes.executions).toBe(1); }); it('bridge restart during transcription fails the turn as provably-not-run', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.stt.next({ delayMs: 350, text: 'lost' }); const res = await h.audioTurn(cred.token, conv, syntheticPcm(0.5)); await h.waitState(cred.token, res.body.request_id, 'transcribing'); await h.restartBridge(); const done = await h.waitTerminal(cred.token, res.body.request_id); expect(done.outcome).toBe('failed'); expect(done.error).toMatchObject({ code: 'interrupted_before_agent', retryable: true }); expect(h.hermes.executions).toBe(0); }); it('if Hermes no longer knows the run, the outcome is unknown and nothing is resent', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'hang' }); const res = await h.textTurn(cred.token, conv, 'job'); await h.waitState(cred.token, res.body.request_id, 'thinking'); h.hermes.forgetRuns(); const done = await h.waitTerminal(cred.token, res.body.request_id); expect(done.outcome).toBe('unknown'); expect(h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs')).toHaveLength(1); }); it('status outage during a run is ridden out without resubmitting', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'complete', afterMs: 250, output: 'fine' }); const res = await h.textTurn(cred.token, conv, 'job'); await h.waitState(cred.token, res.body.request_id, 'thinking'); h.hermes.setStatusDown(true); await new Promise((r) => setTimeout(r, 200)); h.hermes.setStatusDown(false); const done = await h.waitTerminal(cred.token, res.body.request_id); expect(done.outcome).toBe('succeeded'); expect(h.hermes.executions).toBe(1); }); }); describe('device revocation stops what the device started (CODY-004)', () => { beforeEach(async () => { h = await createHarness({ timing: { agentDeadlineMs: 30_000, cancelGraceMs: 2000 } }); }); it('revoking over HTTP during a hanging run asks Hermes to stop and settles the turn', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'hang' }); const res = await h.textTurn(cred.token, conv, 'long job'); const id = res.body.request_id; await h.waitState(cred.token, id, 'thinking'); expect(h.hermes.requests.some((r) => r.path.endsWith('/stop'))).toBe(false); expect((await h.api('DELETE', '/v1/device', { token: cred.token })).status).toBe(200); // The device can no longer ask, so the outcome is read from the bridge's own records. const row = () => h.bridge.db.prepare('SELECT state, outcome, cancel_requested FROM turns WHERE request_id = ?').get(id) as any; const deadline = Date.now() + 3000; while (row().state !== 'done' && Date.now() < deadline) await new Promise((r) => setTimeout(r, 10)); expect(row()).toEqual({ state: 'done', outcome: 'cancelled', cancel_requested: 1 }); expect(h.hermes.requests.filter((r) => r.path.endsWith('/stop'))).toHaveLength(1); expect(h.hermes.lastRun()!.status).toBe('cancelled'); // Still unauthorized afterwards, for reads, new turns and cancels alike. expect((await h.api('GET', `/v1/turns/${id}`, { token: cred.token })).status).toBe(401); expect((await h.textTurn(cred.token, conv, 'again')).status).toBe(401); expect((await h.api('POST', `/v1/turns/${id}/cancel`, { token: cred.token, json: {} })).status).toBe(401); expect((await h.api('POST', '/v1/conversations', { token: cred.token, json: { schema_version: 1 } })).status).toBe(401); expect(h.hermes.executions).toBe(1); }); it('revoking from the operator CLI path (database only, no engine call) also stops the run', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'hang' }); const res = await h.textTurn(cred.token, conv, 'long job'); const id = res.body.request_id; await h.waitState(cred.token, id, 'thinking'); // Exactly what `bridge:cli revoke` does: a second Devices instance on the same database // file, as another process would have. The running engine is never called. const { Devices } = await import('../../services/bridge/src/devices.ts'); const { openDb } = await import('../../services/bridge/src/db.ts'); const otherProcessDb = openDb(h.config.dbPath); const [device] = h.bridge.devices.list(); expect(new Devices(otherProcessDb, h.config).revoke(device!.id)).toBe(true); otherProcessDb.close(); const row = () => h.bridge.db.prepare('SELECT state, outcome FROM turns WHERE request_id = ?').get(id) as any; const deadline = Date.now() + 3000; while (row().state !== 'done' && Date.now() < deadline) await new Promise((r) => setTimeout(r, 10)); expect(row()).toEqual({ state: 'done', outcome: 'cancelled' }); expect(h.hermes.requests.filter((r) => r.path.endsWith('/stop'))).toHaveLength(1); expect((await h.api('GET', '/v1/device', { token: cred.token })).status).toBe(401); }); it('revoking during transcription aborts it and nothing reaches the agent', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.stt.next({ delayMs: 350, text: 'never used' }); const res = await h.audioTurn(cred.token, conv, syntheticPcm(0.5)); const id = res.body.request_id; await h.waitState(cred.token, id, 'transcribing'); const started = Date.now(); await h.api('DELETE', '/v1/device', { token: cred.token }); const row = () => h.bridge.db.prepare('SELECT state, outcome FROM turns WHERE request_id = ?').get(id) as any; while (row().state !== 'done' && Date.now() - started < 3000) await new Promise((r) => setTimeout(r, 5)); expect(row()).toEqual({ state: 'done', outcome: 'cancelled' }); // Settled by the abort, not by waiting for the recogniser to finish. expect(Date.now() - started).toBeLessThan(250); await new Promise((r) => setTimeout(r, 400)); expect(h.hermes.executions).toBe(0); }); it('a CLI-path revocation during transcription is picked up by the sweep and aborts the recogniser', async () => { const cred = await h.pair(); const conv = await h.conversation(cred.token); h.stt.next({ delayMs: 380, text: 'never used' }); const res = await h.audioTurn(cred.token, conv, syntheticPcm(0.5)); const id = res.body.request_id; await h.waitState(cred.token, id, 'transcribing'); const { Devices } = await import('../../services/bridge/src/devices.ts'); const { openDb } = await import('../../services/bridge/src/db.ts'); const otherProcessDb = openDb(h.config.dbPath); const started = Date.now(); new Devices(otherProcessDb, h.config).revoke(h.bridge.devices.list()[0]!.id); otherProcessDb.close(); const row = () => h.bridge.db.prepare('SELECT state, outcome FROM turns WHERE request_id = ?').get(id) as any; while (row().state !== 'done' && Date.now() - started < 3000) await new Promise((r) => setTimeout(r, 5)); expect(row()).toEqual({ state: 'done', outcome: 'cancelled' }); // Nobody in this process was told; only the periodic sweep can have aborted it this early. expect(Date.now() - started).toBeLessThan(250); await new Promise((r) => setTimeout(r, 400)); expect(h.hermes.executions).toBe(0); }); it('revoking one device leaves another device\'s running turn alone', async () => { const a = await h.pair('a'); const b = await h.pair('b'); const convB = await h.conversation(b.token); h.hermes.next({ kind: 'complete', afterMs: 300, output: 'b is fine' }); const res = await h.textTurn(b.token, convB, 'b question'); await h.waitState(b.token, res.body.request_id, 'thinking'); await h.api('DELETE', '/v1/device', { token: a.token }); const done = await h.waitTerminal(b.token, res.body.request_id); expect(done.outcome).toBe('succeeded'); expect(done.cancel_requested).toBe(false); expect(h.hermes.requests.some((r) => r.path.endsWith('/stop'))).toBe(false); }); }); describe('approval wait and agent deadline survive a bridge restart (CODY-008)', () => { it('restart BEFORE the original agent deadline: the approval timeout still fires at its original time', async () => { h = await createHarness({ timing: { agentDeadlineMs: 5000, approvalWaitMs: 700, cancelGraceMs: 1000 } }); const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'approval' }); const res = await h.textTurn(cred.token, conv, 'needs approval'); const id = res.body.request_id; await h.waitState(cred.token, id, 'approval_required'); const before = h.bridge.db.prepare('SELECT approval_started_at, agent_deadline_at FROM turns').get() as any; expect(before.approval_started_at).toBeGreaterThan(0); await new Promise((r) => setTimeout(r, 400)); // Polling must not have moved the recorded start of the wait. expect((h.bridge.db.prepare('SELECT approval_started_at FROM turns').get() as any).approval_started_at).toBe(before.approval_started_at); await h.restartBridge(); const restartedAt = Date.now(); const done = await h.waitTerminal(cred.token, id); // 700 ms from first sight of the approval, not 700 ms from the restart. expect(Date.now() - before.approval_started_at).toBeGreaterThanOrEqual(690); expect(Date.now() - restartedAt).toBeLessThan(550); expect(done.outcome).toBe('cancelled'); expect(done.error?.code).toBe('approval_timeout'); }); it('restart AFTER the original agent deadline, still awaiting approval: classified as approval timeout, not agent timeout', async () => { h = await createHarness({ timing: { agentDeadlineMs: 300, approvalWaitMs: 1200, cancelGraceMs: 1000 } }); const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'approval' }); const res = await h.textTurn(cred.token, conv, 'needs approval'); const id = res.body.request_id; await h.waitState(cred.token, id, 'approval_required'); const startedAt = (h.bridge.db.prepare('SELECT approval_started_at FROM turns').get() as any).approval_started_at; await new Promise((r) => setTimeout(r, 500)); // the 300 ms agent deadline is now in the past await h.restartBridge(); // Not stopped on restart just because the unpaused agent deadline has passed. await new Promise((r) => setTimeout(r, 200)); expect((await h.api('GET', `/v1/turns/${id}`, { token: cred.token })).body.state).toBe('approval_required'); const done = await h.waitTerminal(cred.token, id); expect(done.error?.code).toBe('approval_timeout'); expect(Date.now() - startedAt).toBeGreaterThanOrEqual(1190); expect(Date.now() - startedAt).toBeLessThan(1900); }); it('restart while waiting, then approved elsewhere: the run keeps the time it had left and completes', async () => { h = await createHarness({ timing: { agentDeadlineMs: 600, approvalWaitMs: 5000, cancelGraceMs: 1000 } }); const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'approval' }); const res = await h.textTurn(cred.token, conv, 'needs approval'); const id = res.body.request_id; await h.waitState(cred.token, id, 'approval_required'); await new Promise((r) => setTimeout(r, 400)); await h.restartBridge(); await new Promise((r) => setTimeout(r, 500)); // 900 ms since start: past the unpaused 600 ms deadline const run = h.hermes.lastRun()!; run.status = 'running'; // approved on another surface; the agent carries on for a while await h.waitState(cred.token, id, 'thinking'); const row = h.bridge.db.prepare('SELECT approval_started_at, agent_deadline_at, agent_started_at FROM turns').get() as any; expect(row.approval_started_at).toBeNull(); // The deadline was pushed back by the time spent waiting (about 900 ms), and stored. expect(row.agent_deadline_at - row.agent_started_at).toBeGreaterThan(600 + 800); // A second restart must not lose or double the pause. await h.restartBridge(); await new Promise((r) => setTimeout(r, 150)); expect((await h.api('GET', `/v1/turns/${id}`, { token: cred.token })).body.state).toBe('thinking'); h.hermes.approve(run.runId, 'approved and finished'); const done = await h.waitTerminal(cred.token, id); expect(done.outcome).toBe('succeeded'); expect(done.answer_text).toBe('approved and finished'); expect(h.hermes.executions).toBe(1); }); it('after approval and restart, the paused agent deadline still ends a run that never finishes, as an agent timeout', async () => { h = await createHarness({ timing: { agentDeadlineMs: 500, approvalWaitMs: 5000, cancelGraceMs: 1000 } }); const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'approval' }); const res = await h.textTurn(cred.token, conv, 'needs approval'); const id = res.body.request_id; await h.waitState(cred.token, id, 'approval_required'); await new Promise((r) => setTimeout(r, 300)); h.hermes.lastRun()!.status = 'running'; await h.waitState(cred.token, id, 'thinking'); await h.restartBridge(); const done = await h.waitTerminal(cred.token, id); expect(done.outcome).toBe('cancelled'); expect(done.error?.code).toBe('agent_timeout'); }); }); describe('logging and retention', () => { it('logs carry ids, states and timings but never questions, answers, audio, tokens or keys', async () => { h = await createHarness(); const cred = await h.pair('pocket-g2'); const conv = await h.conversation(cred.token); h.stt.next({ text: 'SECRET-TRANSCRIPT-zebra' }); h.hermes.next({ kind: 'complete', output: 'SECRET-ANSWER-giraffe' }); const audio = await h.audioTurn(cred.token, conv, syntheticPcm(0.5)); await h.waitTerminal(cred.token, audio.body.request_id); h.hermes.next({ kind: 'fail', error: 'SECRET-DIAGNOSTIC-okapi' }); const text = await h.textTurn(cred.token, conv, 'SECRET-QUESTION-lemur'); await h.waitTerminal(cred.token, text.body.request_id); await h.api('GET', '/v1/device', { token: 'hvn_SECRET-BAD-TOKEN' }); const all = h.logs.join(''); expect(all).toContain(audio.body.request_id); expect(all).toContain('turn.done'); expect(all).toContain('transcribe_ms'); for (const secret of ['zebra', 'giraffe', 'okapi', 'lemur', 'SECRET-BAD-TOKEN', cred.token, h.hermes.apiKey, h.stt.apiKey]) { expect(all).not.toContain(secret); } }); it('cached question and answer text is dropped after the retention window', async () => { h = await createHarness({ env: { HERMEVEN_RESULT_RETENTION_SECONDS: '10' } }); const cred = await h.pair(); const conv = await h.conversation(cred.token); const res = await h.textTurn(cred.token, conv, 'remember me?'); const done = await h.waitTerminal(cred.token, res.body.request_id); expect(done.answer_text).toBeTruthy(); // Age the row past retention, then run the same purge the bridge runs every minute. h.bridge.db.prepare('UPDATE turns SET completed_at = completed_at - 11000').run(); expect(h.bridge.engine.purgeExpired()).toBe(1); const after = await h.api('GET', `/v1/turns/${res.body.request_id}`, { token: cred.token }); expect(after.body.outcome).toBe('succeeded'); expect(after.body.answer_text).toBeNull(); expect(after.body.input_text).toBeNull(); const row = h.bridge.db.prepare('SELECT pending_body, input_text, answer_text FROM turns').get(); expect(row).toEqual({ pending_body: null, input_text: null, answer_text: null }); }); it('the exact Hermes body is held only until the run id is recorded', async () => { h = await createHarness(); const cred = await h.pair(); const conv = await h.conversation(cred.token); h.hermes.next({ kind: 'hang' }); const res = await h.textTurn(cred.token, conv, 'hold on'); await h.waitState(cred.token, res.body.request_id, 'thinking'); await new Promise((r) => setTimeout(r, 60)); const row = h.bridge.db.prepare('SELECT pending_body, hermes_run_id FROM turns').get() as any; expect(row.hermes_run_id).toBeTruthy(); expect(row.pending_body).toBeNull(); await h.api('POST', `/v1/turns/${res.body.request_id}/cancel`, { token: cred.token, json: {} }); await h.waitTerminal(cred.token, res.body.request_id); }); });