import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test' import type { MiddlewareHandler } from 'hono' import { Hono } from 'hono' import type { AppEnv } from '@/types' // The session is BetterAuth's (and its database's) business: here every request is signed in. mock.module('@/lib/auth-session', () => ({ requireSession: (async (c, next) => { c.set('user', { id: 'user-1', name: 'Ana', email: 'ana@example.com' }) await next() }) satisfies MiddlewareHandler, })) const { voiceModule } = await import('@/modules/voice') const warnings: unknown[] = [] const originalFetch = globalThis.fetch const originalEnv = { ...process.env } function createTestApp() { return new Hono() .use(async (c, next) => { c.set('logger', { warn: (...args: unknown[]) => warnings.push(args) } as never) await next() }) .route('/api/voice', voiceModule) } function split(body: unknown) { return createTestApp().request('/api/voice/split', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), }) } function mockFetch(handler: (url: string, init: RequestInit) => Promise) { const fn = mock(handler) globalThis.fetch = fn as unknown as typeof fetch return fn } function modelAnswer(text: string) { return Response.json({ candidates: [{ content: { parts: [{ text }] } }] }) } const TEXT = 'dos litros de leche descremada, una docena de huevos y bolsas de residuos' beforeEach(() => { warnings.length = 0 process.env.GEMINI_API_KEY = 'test-key' process.env.GEMINI_MODEL = 'gemma-test' process.env.GEMINI_TIMEOUT_MS = '50' // `bun test` loads `.env`: a real Groq key there would take over these Gemini tests. delete process.env.GROQ_API_KEY delete process.env.GROQ_MODEL delete process.env.GROQ_TIMEOUT_MS }) afterEach(() => { globalThis.fetch = originalFetch process.env = { ...originalEnv } }) describe('POST /api/voice/split', () => { it('returns the items the model answers with', async () => { const fetchMock = mockFetch(async () => modelAnswer('["2 l de leche descremada", "12 huevos", "Bolsas de residuos"]'), ) const response = await split({ text: TEXT }) expect(response.status).toBe(200) expect(await response.json()).toEqual({ items: ['2 l de leche descremada', '12 huevos', 'Bolsas de residuos'], }) expect(warnings).toHaveLength(0) const [url, init] = fetchMock.mock.calls[0] ?? [] expect(url).toContain('/models/gemma-test:generateContent') expect(new Headers(init?.headers).get('x-goog-api-key')).toBe('test-key') const sent = JSON.parse(String(init?.body)) expect(sent.generationConfig.temperature).toBe(0) expect(sent.systemInstruction.parts[0].text).toContain('array JSON') expect(sent.contents.at(-1)).toEqual({ role: 'user', parts: [{ text: TEXT }] }) }) it('falls back to splitting the text when the model times out', async () => { mockFetch( (_url, init) => new Promise((_resolve, reject) => { init.signal?.addEventListener('abort', () => reject(init.signal?.reason)) }), ) const response = await split({ text: TEXT }) expect(response.status).toBe(200) expect(await response.json()).toEqual({ items: ['dos litros de leche descremada', 'una docena de huevos', 'bolsas de residuos'], }) expect(JSON.stringify(warnings)).toContain('timeout') // The transcript itself is never logged. expect(JSON.stringify(warnings)).not.toContain('leche') }) it('falls back when the model is rate limited (429)', async () => { mockFetch(async () => new Response('quota', { status: 429 })) const response = await split({ text: 'pan y queso' }) expect(response.status).toBe(200) expect(await response.json()).toEqual({ items: ['pan', 'queso'] }) expect(JSON.stringify(warnings)).toContain('rate-limited') }) it('falls back when the model answers invalid JSON', async () => { mockFetch(async () => modelAnswer('Perdón, no entendí.')) const response = await split({ text: 'pan, queso' }) expect(await response.json()).toEqual({ items: ['pan', 'queso'] }) expect(JSON.stringify(warnings)).toContain('invalid-json') }) it('asks for minimal thinking and retries a 5xx once', async () => { let calls = 0 const fetchMock = mockFetch(async () => ++calls === 1 ? new Response('{}', { status: 500 }) : modelAnswer('["Azúcar", "Leche", "Café"]'), ) const response = await split({ text: 'azúcar leche y café' }) expect(await response.json()).toEqual({ items: ['Azúcar', 'Leche', 'Café'] }) expect(fetchMock).toHaveBeenCalledTimes(2) const sent = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)) expect(sent.generationConfig.thinkingConfig).toEqual({ thinkingLevel: 'minimal' }) }) it('falls back when the model answers 5xx twice', async () => { const fetchMock = mockFetch(async () => new Response('{}', { status: 503 })) const response = await split({ text: 'pan y leche' }) expect(await response.json()).toEqual({ items: ['pan', 'leche'] }) expect(fetchMock).toHaveBeenCalledTimes(2) expect(JSON.stringify(warnings)).toContain('http-503') }) it('falls back without calling the model when there is no API key', async () => { delete process.env.GEMINI_API_KEY const fetchMock = mockFetch(async () => modelAnswer('[]')) const response = await split({ text: 'pan' }) expect(await response.json()).toEqual({ items: ['pan'] }) expect(fetchMock).not.toHaveBeenCalled() }) it('rejects an empty text with a 422', async () => { const fetchMock = mockFetch(async () => modelAnswer('[]')) const response = await split({ text: ' ' }) expect(response.status).toBe(422) expect(response.headers.get('content-type')).toContain('application/problem+json') expect(fetchMock).not.toHaveBeenCalled() }) it('truncates the text to 500 characters', async () => { const fetchMock = mockFetch(async () => modelAnswer('["pan"]')) await split({ text: 'a'.repeat(800) }) const sent = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)) expect(sent.contents.at(-1).parts[0].text).toHaveLength(500) }) }) describe('POST /api/voice/split with Groq', () => { beforeEach(() => { process.env.GROQ_API_KEY = 'gsk_test' process.env.GROQ_MODEL = 'llama-test' process.env.GROQ_TIMEOUT_MS = '50' }) function groqAnswer(content: string) { return Response.json({ choices: [{ message: { role: 'assistant', content } }] }) } it('asks Groq instead of Gemini when its key is set', async () => { const fetchMock = mockFetch(async () => groqAnswer('["Azúcar", "Leche", "Café"]')) const response = await split({ text: 'azúcar leche y café' }) expect(await response.json()).toEqual({ items: ['Azúcar', 'Leche', 'Café'] }) expect(warnings).toHaveLength(0) const [url, init] = fetchMock.mock.calls[0] ?? [] expect(url).toBe('https://api.groq.com/openai/v1/chat/completions') expect(new Headers(init?.headers).get('authorization')).toBe('Bearer gsk_test') const sent = JSON.parse(String(init?.body)) expect(sent.model).toBe('llama-test') expect(sent.temperature).toBe(0) expect(sent.messages[0]).toEqual({ role: 'system', content: expect.stringContaining('array JSON'), }) expect(sent.messages[2].role).toBe('assistant') expect(sent.messages.at(-1)).toEqual({ role: 'user', content: 'azúcar leche y café' }) }) it('retries a 5xx once', async () => { let calls = 0 const fetchMock = mockFetch(async () => ++calls === 1 ? new Response('{}', { status: 502 }) : groqAnswer('["Pan"]'), ) const response = await split({ text: 'pan' }) expect(await response.json()).toEqual({ items: ['Pan'] }) expect(fetchMock).toHaveBeenCalledTimes(2) }) it('falls back when Groq is rate limited (429)', async () => { mockFetch(async () => new Response('{}', { status: 429 })) const response = await split({ text: 'pan y queso' }) expect(await response.json()).toEqual({ items: ['pan', 'queso'] }) expect(JSON.stringify(warnings)).toContain('rate-limited') }) it('falls back when Groq answers with no content', async () => { mockFetch(async () => groqAnswer('')) const response = await split({ text: 'pan, queso' }) expect(await response.json()).toEqual({ items: ['pan', 'queso'] }) expect(JSON.stringify(warnings)).toContain('empty-response') }) })