feat(items): voice dictation with Gemma 4 and a reworked list UI
Dictation: a mic button in the add field uses the Web Speech API (es-AR) and
shows the partial transcript in the input. POST /api/voice/split asks Gemma 4
(Gemini API, plain fetch) to split the sentence into one string per item,
written the way the existing parser reads typed text; each string then goes
through the usual add flow. The endpoint never fails because of the model:
missing key, timeout, 429 or invalid JSON fall back to splitting on commas,
semicolons, " y " and " e ". A toast offers "Deshacer" for the whole dictation;
if the request fails, the transcript is added as a single item.
UI: "+" instead of the search icon, quantity tags ("2 L", "×12", "1 kg"), the
list name with a list switcher and the pending/bought count in the header,
"Comprados (N)" folded by default, and a bottom sheet to edit name, quantity
(− / + and unit), note and delete. PATCH items now accepts a name.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
151
apps/api/src/modules/voice/split/route.test.ts
Normal file
151
apps/api/src/modules/voice/split/route.test.ts
Normal file
@@ -0,0 +1,151 @@
|
||||
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<AppEnv>,
|
||||
}))
|
||||
|
||||
const { voiceModule } = await import('@/modules/voice')
|
||||
|
||||
const warnings: unknown[] = []
|
||||
const originalFetch = globalThis.fetch
|
||||
const originalEnv = { ...process.env }
|
||||
|
||||
function createTestApp() {
|
||||
return new Hono<AppEnv>()
|
||||
.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<Response>) {
|
||||
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'
|
||||
})
|
||||
|
||||
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('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)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user