From a814b3403693e5dc8f686165c399b3588a4db637 Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Wed, 28 Oct 2026 19:25:10 -0300 Subject: [PATCH] feat(items): voice dictation with Gemma 4 and a reworked list UI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .env.example | 8 + AGENTS.md | 6 +- apps/api/.env.example | 8 + apps/api/src/app.ts | 2 + apps/api/src/lib/gemini.ts | 123 +++++++++ .../src/modules/lists/items/update/route.ts | 5 +- .../src/modules/lists/items/update/schema.ts | 11 +- .../lists/items/update/use-case.test.ts | 21 +- .../modules/lists/items/update/use-case.ts | 9 +- apps/api/src/modules/voice/index.ts | 8 + .../api/src/modules/voice/split/items.test.ts | 60 +++++ apps/api/src/modules/voice/split/items.ts | 91 +++++++ apps/api/src/modules/voice/split/prompt.ts | 30 +++ .../api/src/modules/voice/split/route.test.ts | 151 +++++++++++ apps/api/src/modules/voice/split/route.ts | 23 ++ apps/api/src/modules/voice/split/schema.ts | 13 + apps/api/src/modules/voice/split/use-case.ts | 54 ++++ .../src/components/items/bought-item-list.tsx | 59 +++-- .../src/components/items/create-item-form.tsx | 241 +++++++++++++---- apps/web/src/components/items/item-editor.tsx | 106 -------- apps/web/src/components/items/item-list.tsx | 24 +- apps/web/src/components/items/item-row.tsx | 62 +---- apps/web/src/components/items/item-sheet.tsx | 245 ++++++++++++++++++ .../src/components/items/list-progress.tsx | 23 +- apps/web/src/components/layout/app-header.tsx | 14 +- .../src/components/layout/list-switcher.tsx | 95 +++++++ apps/web/src/components/theme-toggle.tsx | 2 +- apps/web/src/hooks/use-dictation.ts | 131 ++++++++++ apps/web/src/hooks/use-items.ts | 38 ++- apps/web/src/hooks/use-voice-split.ts | 20 ++ apps/web/src/lib/item-quantity.test.ts | 47 ++++ apps/web/src/lib/item-quantity.ts | 64 +++++ apps/web/src/lib/items.test.ts | 28 +- apps/web/src/lib/items.ts | 28 +- .../lib/natural-input/voice-examples.test.ts | 53 ++++ docker-compose.yml | 4 + packages/shared/src/index.ts | 1 + packages/shared/src/voice.ts | 45 ++++ turbo.json | 8 +- 39 files changed, 1673 insertions(+), 288 deletions(-) create mode 100644 apps/api/src/lib/gemini.ts create mode 100644 apps/api/src/modules/voice/index.ts create mode 100644 apps/api/src/modules/voice/split/items.test.ts create mode 100644 apps/api/src/modules/voice/split/items.ts create mode 100644 apps/api/src/modules/voice/split/prompt.ts create mode 100644 apps/api/src/modules/voice/split/route.test.ts create mode 100644 apps/api/src/modules/voice/split/route.ts create mode 100644 apps/api/src/modules/voice/split/schema.ts create mode 100644 apps/api/src/modules/voice/split/use-case.ts delete mode 100644 apps/web/src/components/items/item-editor.tsx create mode 100644 apps/web/src/components/items/item-sheet.tsx create mode 100644 apps/web/src/components/layout/list-switcher.tsx create mode 100644 apps/web/src/hooks/use-dictation.ts create mode 100644 apps/web/src/hooks/use-voice-split.ts create mode 100644 apps/web/src/lib/item-quantity.test.ts create mode 100644 apps/web/src/lib/item-quantity.ts create mode 100644 apps/web/src/lib/natural-input/voice-examples.test.ts create mode 100644 packages/shared/src/voice.ts diff --git a/.env.example b/.env.example index 921d211..13f0941 100644 --- a/.env.example +++ b/.env.example @@ -19,6 +19,14 @@ NODE_ENV="development" # MAIL_FROM="Superlist " # Public URL of the web app, used to build the accept-invitation links WEB_APP_URL="http://localhost:7153" +# Dictation: AI Studio (Gemini API) key, backend only. NEVER prefix it with VITE_ +# or Vite would put it in the browser bundle. Without it, dictated text is split +# on commas and "y" instead of by the model. +# GEMINI_API_KEY="" +# Optional: model id (defaults to Gemma 4's small variant) +# GEMINI_MODEL="gemma-4-26b-a4b-it" +# Optional: timeout of the model request, in milliseconds +# GEMINI_TIMEOUT_MS="8000" # --- apps/web --- # Optional. In dev, Vite proxies /api/* to the API (http://localhost:4100), so diff --git a/AGENTS.md b/AGENTS.md index bc70ea3..4725e1b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,8 @@ Biome as the only JS/TS tool and the text Bun lockfile committed. It is deployed Dokploy (`docker-compose.yml`); there is no hosted CI. Not done yet: product features are just starting (sign-up, shopping lists, list items and invitations exist; -there is no Google login and no email verification). The `health` module is the reference example. +there is no Google login and no email verification; the `voice` module splits dictated text with Gemma 4 +through the Gemini API). The `health` module is the reference example. ## Stack (source of truth: `STACK.md`) @@ -99,7 +100,8 @@ Run from the repo root. Verification order is `build`, then `lint` → `typechec `apps/web/nginx.conf`, which also proxies `/api/*` to `http://superlist-api:4100` (re-resolved through Docker's DNS, so API redeploys don't leave nginx on a stale IP). Required env vars are interpolated by Compose (`DATABASE_URL`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `CORS_ORIGIN`, `WEB_APP_URL`); set them - in Dokploy. There is no hosted CI. + in Dokploy. The dictation variables (`GEMINI_API_KEY`, `GEMINI_MODEL`, `GEMINI_TIMEOUT_MS`) are optional and + backend-only — never give them a `VITE_` prefix, or Vite would ship the key in the browser bundle. There is no hosted CI. - Generated files are gitignored and must never be edited by hand: `apps/web/src/routeTree.gen.ts`, `apps/api/src/generated/`. - Tests live next to the code as `*.test.ts`. The API uses `bun test` (`src/lib/result-json.test.ts`, diff --git a/apps/api/.env.example b/apps/api/.env.example index ee34b20..40ffdd5 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -12,3 +12,11 @@ NODE_ENV="development" # MAIL_FROM="Superlist " # Public URL of the web app, used to build the accept-invitation links WEB_APP_URL="http://localhost:7153" +# Dictation: AI Studio (Gemini API) key, backend only. NEVER prefix it with VITE_ +# or Vite would put it in the browser bundle. Without it, dictated text is split +# on commas and "y" instead of by the model. +# GEMINI_API_KEY="" +# Optional: model id (defaults to Gemma 4's small variant) +# GEMINI_MODEL="gemma-4-26b-a4b-it" +# Optional: timeout of the model request, in milliseconds +# GEMINI_TIMEOUT_MS="8000" diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 6733eba..78d7579 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -9,6 +9,7 @@ import { errorHandler, notFoundHandler } from '@/lib/problem-details' import { healthModule } from '@/modules/health' import { invitationsModule } from '@/modules/invitations' import { listsModule } from '@/modules/lists' +import { voiceModule } from '@/modules/voice' import type { AppEnv } from '@/types' const allowedOrigins = (process.env.CORS_ORIGIN ?? 'http://localhost:7153') @@ -47,6 +48,7 @@ export function createApp() { app.route('/api/health', healthModule) app.route('/api/lists', listsModule) app.route('/api/invitations', invitationsModule) + app.route('/api/voice', voiceModule) app.notFound(notFoundHandler) app.onError(errorHandler) diff --git a/apps/api/src/lib/gemini.ts b/apps/api/src/lib/gemini.ts new file mode 100644 index 0000000..6abb93f --- /dev/null +++ b/apps/api/src/lib/gemini.ts @@ -0,0 +1,123 @@ +/** + * Minimal client for the Gemini API `generateContent` REST endpoint (Google AI Studio), + * called with `fetch` — no SDK. It serves Gemma models too, which is what the API uses. + * + * Configuration (backend only — never prefix these with `VITE_`, or Vite would put the + * key in the browser bundle): + * - `GEMINI_API_KEY`: AI Studio API key. Without it every call fails with `missing-key`. + * - `GEMINI_MODEL`: model id, `gemma-4-26b-a4b-it` by default. + * - `GEMINI_TIMEOUT_MS`: request timeout, 8000 ms by default. + */ + +const GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models' + +/** Gemma 4's small, fast variant (a mixture of experts with ~4B active parameters). */ +export const DEFAULT_GEMINI_MODEL = 'gemma-4-26b-a4b-it' + +export const DEFAULT_GEMINI_TIMEOUT_MS = 8000 + +export type GeminiConfig = { + apiKey: string | undefined + model: string + timeoutMs: number +} + +/** Reads the configuration from the environment, with the defaults above. */ +export function geminiConfigFromEnv(env: Record = process.env) { + const timeout = Number.parseInt(env.GEMINI_TIMEOUT_MS ?? '', 10) + + return { + apiKey: env.GEMINI_API_KEY?.trim() || undefined, + model: env.GEMINI_MODEL?.trim() || DEFAULT_GEMINI_MODEL, + timeoutMs: Number.isFinite(timeout) && timeout > 0 ? timeout : DEFAULT_GEMINI_TIMEOUT_MS, + } satisfies GeminiConfig +} + +/** Why a call failed, short enough to log (it never includes the prompt). */ +export type GeminiFailureReason = + | 'missing-key' + | 'timeout' + | 'rate-limited' + | `http-${number}` + | 'network' + | 'empty-response' + +export class GeminiError extends Error { + constructor(readonly reason: GeminiFailureReason) { + super(`Gemini request failed: ${reason}`) + this.name = 'GeminiError' + } +} + +/** One turn of the conversation: `user` for the input, `model` for an example answer. */ +export type GeminiTurn = { role: 'user' | 'model'; text: string } + +export type GenerateInput = { + systemInstruction: string + turns: GeminiTurn[] +} + +type GenerateContentResponse = { + candidates?: { content?: { parts?: { text?: string; thought?: boolean }[] } }[] +} + +/** Something that answers a prompt with text: the Gemini client, or a fake in tests. */ +export type TextGenerator = { generate(input: GenerateInput): Promise } + +export class GeminiClient implements TextGenerator { + constructor( + private readonly config: GeminiConfig = geminiConfigFromEnv(), + private readonly fetchFn: typeof fetch = fetch, + ) {} + + /** The model's text answer. Throws `GeminiError` on any failure. */ + async generate({ systemInstruction, turns }: GenerateInput): Promise { + if (!this.config.apiKey) throw new GeminiError('missing-key') + + let response: Response + try { + response = await this.fetchFn( + `${GEMINI_API_URL}/${encodeURIComponent(this.config.model)}:generateContent`, + { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-goog-api-key': this.config.apiKey }, + body: JSON.stringify({ + systemInstruction: { parts: [{ text: systemInstruction }] }, + contents: turns.map(({ role, text }) => ({ role, parts: [{ text }] })), + generationConfig: { temperature: 0 }, + }), + signal: AbortSignal.timeout(this.config.timeoutMs), + }, + ) + } catch (error) { + const name = error instanceof Error ? error.name : '' + throw new GeminiError( + name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'network', + ) + } + + if (response.status === 429) throw new GeminiError('rate-limited') + if (!response.ok) throw new GeminiError(`http-${response.status}`) + + let body: GenerateContentResponse + try { + body = (await response.json()) as GenerateContentResponse + } catch (error) { + const name = error instanceof Error ? error.name : '' + throw new GeminiError( + name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'empty-response', + ) + } + + // Thinking models may send their reasoning as `thought` parts: only the answer counts. + const text = (body.candidates?.[0]?.content?.parts ?? []) + .filter((part) => !part.thought && typeof part.text === 'string') + .map((part) => part.text) + .join('') + .trim() + + if (!text) throw new GeminiError('empty-response') + + return text + } +} diff --git a/apps/api/src/modules/lists/items/update/route.ts b/apps/api/src/modules/lists/items/update/route.ts index 1e939d4..08c38c2 100644 --- a/apps/api/src/modules/lists/items/update/route.ts +++ b/apps/api/src/modules/lists/items/update/route.ts @@ -9,7 +9,7 @@ import type { AppEnv } from '@/types' import { ItemParamsSchema, UpdateItemSchema } from './schema' import { UpdateItem } from './use-case' -/** PATCH /lists/:listId/items/:itemId — updates an item's bought state, quantity and/or notes. */ +/** PATCH /lists/:listId/items/:itemId — updates an item's name, bought state, quantity and/or notes. */ export const updateItemRoute = new Hono().patch( '/:itemId', requireSession, @@ -17,11 +17,12 @@ export const updateItemRoute = new Hono().patch( validate.json(UpdateItemSchema), async (c) => { const { listId, itemId } = c.req.valid('param') - const { completed, quantity, notes } = c.req.valid('json') + const { name, completed, quantity, notes } = c.req.valid('json') const result = await new UpdateItem(prisma).execute({ listId, itemId, userId: c.get('user').id, + name, completed, quantity, notes, diff --git a/apps/api/src/modules/lists/items/update/schema.ts b/apps/api/src/modules/lists/items/update/schema.ts index 5229186..09a343e 100644 --- a/apps/api/src/modules/lists/items/update/schema.ts +++ b/apps/api/src/modules/lists/items/update/schema.ts @@ -11,13 +11,22 @@ export type ItemParams = z.infer /** Body of `PATCH /lists/:listId/items/:itemId` — at least one field is required. */ export const UpdateItemSchema = z .object({ + name: z + .string() + .trim() + .min(1, 'El nombre es obligatorio') + .max(120, 'Máximo 120 caracteres') + .optional(), completed: z.boolean().optional(), quantity: z.string().trim().max(40, 'Máximo 40 caracteres').nullable().optional(), notes: z.string().trim().max(280, 'Máximo 280 caracteres').nullable().optional(), }) .refine( (value) => - value.completed !== undefined || value.quantity !== undefined || value.notes !== undefined, + value.name !== undefined || + value.completed !== undefined || + value.quantity !== undefined || + value.notes !== undefined, { message: 'Indica al menos un campo para actualizar.', }, diff --git a/apps/api/src/modules/lists/items/update/use-case.test.ts b/apps/api/src/modules/lists/items/update/use-case.test.ts index 770bd6e..4b770ef 100644 --- a/apps/api/src/modules/lists/items/update/use-case.test.ts +++ b/apps/api/src/modules/lists/items/update/use-case.test.ts @@ -48,7 +48,7 @@ function createDb(options: { membership: unknown; item: ItemRow | null }) { // The use case only sends the fields it changes, so the stored row is // simulated by merging those fields into the row the query returned. update: async (args: { - data: Partial> + data: Partial> }) => { updates.push(args) return { ...options.item, ...args.data } as ItemRow @@ -170,6 +170,25 @@ describe('UpdateItem', () => { expect(result.value.quantity).toBeNull() }) + it('renames the item, leaving the rest untouched', async () => { + const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) }) + const { events } = createBus() + const result = await new UpdateItem(db, events).execute({ + listId: 'list-1', + itemId: 'item-1', + userId: 'user-1', + name: ' Leche descremada ', + }) + + expect(result.ok).toBe(true) + if (!result.ok) throw new Error('expected the use case to succeed') + + const data = updates[0] as { data: { name?: string } } + expect(data.data).toEqual({ name: 'Leche descremada' }) + expect(result.value.name).toBe('Leche descremada') + expect(result.value.quantity).toBe('1 L') + }) + it('updates only the notes, leaving the rest untouched', async () => { const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) }) const { events, published } = createBus() diff --git a/apps/api/src/modules/lists/items/update/use-case.ts b/apps/api/src/modules/lists/items/update/use-case.ts index db7ca15..6813c98 100644 --- a/apps/api/src/modules/lists/items/update/use-case.ts +++ b/apps/api/src/modules/lists/items/update/use-case.ts @@ -16,6 +16,8 @@ type UpdateItemFields = { listId: string itemId: string userId: string + /** New name (already trimmed and non-empty); when omitted it stays untouched. */ + name?: string /** New bought state; when omitted the state stays untouched. */ completed?: boolean /** New quantity (`null` or an empty string clears it); when omitted it stays untouched. */ @@ -25,7 +27,7 @@ type UpdateItemFields = { } /** - * Updates an item's bought state, its quantity and/or its notes. Only members can do it. + * Updates an item's name, its bought state, its quantity and/or its notes. Only members can do it. * `boughtAt` records the moment an item was marked as bought, for future * statistics, and is cleared when the item goes back to pending. */ @@ -53,12 +55,17 @@ export class UpdateItem { } const data: { + name?: string completed?: boolean boughtAt?: Date | null quantity?: string | null notes?: string | null } = {} + if (input.name !== undefined) { + data.name = input.name.trim() + } + if (input.completed !== undefined) { data.completed = input.completed data.boughtAt = input.completed ? new Date() : null diff --git a/apps/api/src/modules/voice/index.ts b/apps/api/src/modules/voice/index.ts new file mode 100644 index 0000000..b1744d9 --- /dev/null +++ b/apps/api/src/modules/voice/index.ts @@ -0,0 +1,8 @@ +import { Hono } from 'hono' + +import type { AppEnv } from '@/types' + +import { splitVoiceRoute } from './split/route' + +/** `voice` module: every feature of the module is mounted here. */ +export const voiceModule = new Hono().route('/', splitVoiceRoute) diff --git a/apps/api/src/modules/voice/split/items.test.ts b/apps/api/src/modules/voice/split/items.test.ts new file mode 100644 index 0000000..5d3f9c4 --- /dev/null +++ b/apps/api/src/modules/voice/split/items.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from 'bun:test' + +import { fallbackSplit, parseModelItems } from './items' + +describe('fallbackSplit', () => { + it('splits on commas, semicolons, " y " and " e "', () => { + expect(fallbackSplit('dos litros de leche, una docena de huevos y bolsas; pan e hilo')).toEqual( + ['dos litros de leche', 'una docena de huevos', 'bolsas', 'pan', 'hilo'], + ) + }) + + it('keeps decimal commas and drops empty segments', () => { + expect(fallbackSplit('1,5 kg de papas, , cebolla ;')).toEqual(['1,5 kg de papas', 'cebolla']) + }) + + it('does not split inside words', () => { + expect(fallbackSplit('yerba y yogur')).toEqual(['yerba', 'yogur']) + expect(fallbackSplit('mayonesa')).toEqual(['mayonesa']) + }) + + it('caps the number and the length of the items', () => { + const many = Array.from({ length: 40 }, (_, index) => `item ${index}`).join(', ') + expect(fallbackSplit(many)).toHaveLength(30) + expect(fallbackSplit('a'.repeat(150))[0]).toHaveLength(100) + }) +}) + +describe('parseModelItems', () => { + it('reads a valid array, trimming and dropping empty items', () => { + expect(parseModelItems('["2 l de leche", " 12 huevos ", ""]')).toEqual([ + '2 l de leche', + '12 huevos', + ]) + }) + + it('reads JSON inside a code fence or surrounded by prose', () => { + expect(parseModelItems('```json\n["pan", "queso"]\n```')).toEqual(['pan', 'queso']) + expect(parseModelItems('Claro, acá va: ["pan", "queso [rallado]"] ¡Listo!')).toEqual([ + 'pan', + 'queso [rallado]', + ]) + expect(parseModelItems('{"items": ["pan"]}')).toEqual(['pan']) + }) + + it('rejects invalid JSON and anything that is not an array of strings', () => { + expect(parseModelItems('no sé')).toBeNull() + expect(parseModelItems('["pan", ')).toBeNull() + expect(parseModelItems('[1, 2]')).toBeNull() + expect(parseModelItems('{"producto": "pan"}')).toBeNull() + }) + + it('keeps at most 30 items of at most 100 characters', () => { + const items = parseModelItems( + JSON.stringify([...Array.from({ length: 35 }, (_, i) => `item ${i}`), 'x']), + ) + expect(items).toHaveLength(30) + expect(items?.at(-1)).toBe('item 29') + expect(parseModelItems(JSON.stringify(['b'.repeat(120)]))?.[0]).toHaveLength(100) + }) +}) diff --git a/apps/api/src/modules/voice/split/items.ts b/apps/api/src/modules/voice/split/items.ts new file mode 100644 index 0000000..b21e59a --- /dev/null +++ b/apps/api/src/modules/voice/split/items.ts @@ -0,0 +1,91 @@ +import { VOICE_ITEM_MAX_LENGTH, VOICE_MAX_ITEMS } from '@superlist/shared' + +/** + * Trims every item, drops empty ones and caps the result: at most `VOICE_MAX_ITEMS` + * items of at most `VOICE_ITEM_MAX_LENGTH` characters each. + */ +export function cleanItems(items: string[]): string[] { + return items + .map((item) => item.trim().slice(0, VOICE_ITEM_MAX_LENGTH).trim()) + .filter(Boolean) + .slice(0, VOICE_MAX_ITEMS) +} + +/** + * Plan B when the model cannot be used: splits on commas, semicolons, " y " and " e ". + * A comma between digits is a decimal ("1,5 kg") and stays. + */ +export function fallbackSplit(text: string): string[] { + return cleanItems(text.split(/\s*[;\n]\s*|\s*,\s*(?!\d)|\s+[ye]\s+/i)) +} + +/** Removes a Markdown code fence around the answer (```json … ```), if any. */ +function stripCodeFences(text: string): string { + const fenced = /```(?:json|JSON)?\s*([\s\S]*?)```/.exec(text) + + return (fenced?.[1] ?? text).trim() +} + +/** + * The first balanced JSON array or object in `text`, skipping brackets inside strings. + * Returns `null` when there is none. + */ +function firstJsonValue(text: string): string | null { + const start = text.search(/[[{]/) + if (start === -1) return null + + let depth = 0 + let inString = false + let escaped = false + + for (let index = start; index < text.length; index++) { + const char = text[index] + + if (inString) { + if (escaped) escaped = false + else if (char === '\\') escaped = true + else if (char === '"') inString = false + continue + } + + if (char === '"') inString = true + else if (char === '[' || char === '{') depth++ + else if (char === ']' || char === '}') { + depth-- + if (depth === 0) return text.slice(start, index + 1) + } + } + + return null +} + +function tryParse(text: string): unknown { + try { + return JSON.parse(text) + } catch { + return undefined + } +} + +/** + * Reads the model's answer: a JSON array of strings, possibly inside a code fence, + * surrounded by prose or wrapped as `{ "items": [...] }`. Returns the cleaned items, + * or `null` when the answer is not an array of strings. + */ +export function parseModelItems(answer: string): string[] | null { + const unfenced = stripCodeFences(answer) + let value = tryParse(unfenced) + + if (value === undefined) { + const json = firstJsonValue(unfenced) + value = json ? tryParse(json) : undefined + } + + if (value && typeof value === 'object' && !Array.isArray(value) && 'items' in value) { + value = value.items + } + + if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) return null + + return cleanItems(value) +} diff --git a/apps/api/src/modules/voice/split/prompt.ts b/apps/api/src/modules/voice/split/prompt.ts new file mode 100644 index 0000000..ec90267 --- /dev/null +++ b/apps/api/src/modules/voice/split/prompt.ts @@ -0,0 +1,30 @@ +import { VOICE_SPLIT_EXAMPLES } from '@superlist/shared' + +import type { GeminiTurn, GenerateInput } from '@/lib/gemini' + +/** What the model is told to do. Gemma accepts it as `systemInstruction`. */ +export const SPLIT_INSTRUCTION = `Sos un asistente que arma listas de compras en español rioplatense. +Recibís la transcripción de lo que alguien dictó y respondés SOLO con un array JSON de strings, sin texto antes ni después. + +Reglas: +- Un elemento por producto. +- Números en dígitos: "dos" → 2, "media docena" → 6, "una docena" → 12, "un kilo" → 1 kg, "un kilo y medio" → 1,5 kg. +- Unidades abreviadas: g, kg, ml, l. Los envases quedan como palabra: "1 lata", "2 paquetes". +- La cantidad va al principio: "2 l de leche", "400 g de queso", "12 huevos". +- Detalles como marca, color, tipo o corte van como nota, después de un punto: "Bolsas de residuos. Negras y verdes". +- No inventes productos ni cantidades: si no se dijo una cantidad, no pongas ninguna. +- Corregí errores obvios de la transcripción (palabras mal reconocidas, mayúsculas). +- Si no hay ningún producto, respondé [].` + +/** The conversation sent to the model: the few-shot examples, then the transcript. */ +export function buildSplitPrompt(text: string): GenerateInput { + const examples: GeminiTurn[] = VOICE_SPLIT_EXAMPLES.flatMap(({ said, items }) => [ + { role: 'user' as const, text: said }, + { role: 'model' as const, text: JSON.stringify(items) }, + ]) + + return { + systemInstruction: SPLIT_INSTRUCTION, + turns: [...examples, { role: 'user', text }], + } +} diff --git a/apps/api/src/modules/voice/split/route.test.ts b/apps/api/src/modules/voice/split/route.test.ts new file mode 100644 index 0000000..4abd7bd --- /dev/null +++ b/apps/api/src/modules/voice/split/route.test.ts @@ -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, +})) + +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' +}) + +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) + }) +}) diff --git a/apps/api/src/modules/voice/split/route.ts b/apps/api/src/modules/voice/split/route.ts new file mode 100644 index 0000000..b46d670 --- /dev/null +++ b/apps/api/src/modules/voice/split/route.ts @@ -0,0 +1,23 @@ +import { Hono } from 'hono' + +import { requireSession } from '@/lib/auth-session' +import { GeminiClient } from '@/lib/gemini' +import { resultJson } from '@/lib/result-json' +import { validate } from '@/lib/validate' +import type { AppEnv } from '@/types' + +import { SplitVoiceSchema } from './schema' +import { SplitVoiceText } from './use-case' + +/** POST /voice/split — splits a dictated sentence into one string per item. */ +export const splitVoiceRoute = new Hono().post( + '/split', + requireSession, + validate.json(SplitVoiceSchema), + async (c) => { + const { text } = c.req.valid('json') + const result = await new SplitVoiceText(new GeminiClient(), c.get('logger')).execute({ text }) + + return resultJson(c, result) + }, +) diff --git a/apps/api/src/modules/voice/split/schema.ts b/apps/api/src/modules/voice/split/schema.ts new file mode 100644 index 0000000..eb06b0d --- /dev/null +++ b/apps/api/src/modules/voice/split/schema.ts @@ -0,0 +1,13 @@ +import { VOICE_TEXT_MAX_LENGTH } from '@superlist/shared' +import { z } from 'zod' + +/** Body of `POST /voice/split`. Longer transcripts are cut to `VOICE_TEXT_MAX_LENGTH`. */ +export const SplitVoiceSchema = z.object({ + text: z + .string() + .trim() + .min(1, 'El texto no puede estar vacío') + .transform((text) => text.slice(0, VOICE_TEXT_MAX_LENGTH)), +}) + +export type SplitVoiceInput = z.infer diff --git a/apps/api/src/modules/voice/split/use-case.ts b/apps/api/src/modules/voice/split/use-case.ts new file mode 100644 index 0000000..e5678d4 --- /dev/null +++ b/apps/api/src/modules/voice/split/use-case.ts @@ -0,0 +1,54 @@ +import { + Ok, + type ProblemDetails, + type Result, + VOICE_TEXT_MAX_LENGTH, + type VoiceSplitResponse, +} from '@superlist/shared' + +import { GeminiError, type TextGenerator } from '@/lib/gemini' +import type { Logger } from '@/lib/logger' + +import { cleanItems, fallbackSplit, parseModelItems } from './items' +import { buildSplitPrompt } from './prompt' + +/** + * Splits a dictated sentence into one string per item ("dos litros de leche y doce + * huevos" → ["2 l de leche", "12 huevos"]), asking the model first. The model only + * splits and normalizes; the web app reads each string with its usual parser. + * + * It never fails because of the model: when the model is not configured, times out, + * is rate limited or answers something that is not an array of strings, the text is + * split on commas, semicolons, " y " and " e " instead, and the reason is logged + * (never the transcript). + */ +export class SplitVoiceText { + constructor( + private readonly model: TextGenerator, + private readonly logger: Pick, + ) {} + + async execute(input: { text: string }): Promise> { + const text = input.text.trim().slice(0, VOICE_TEXT_MAX_LENGTH) + if (!text) return Ok({ items: [] }) + + let answer: string + try { + answer = await this.model.generate(buildSplitPrompt(text)) + } catch (error) { + return this.fallback(text, error instanceof GeminiError ? error.reason : 'unexpected-error') + } + + const items = parseModelItems(answer) + if (items === null) return this.fallback(text, 'invalid-json') + if (items.length === 0) return this.fallback(text, 'no-items') + + return Ok({ items: cleanItems(items) }) + } + + private fallback(text: string, reason: string): Result { + this.logger.warn({ reason, textLength: text.length }, 'voice split: using the fallback split') + + return Ok({ items: fallbackSplit(text) }) + } +} diff --git a/apps/web/src/components/items/bought-item-list.tsx b/apps/web/src/components/items/bought-item-list.tsx index d46ec07..220b50d 100644 --- a/apps/web/src/components/items/bought-item-list.tsx +++ b/apps/web/src/components/items/bought-item-list.tsx @@ -1,58 +1,63 @@ import type { ListItem } from '@superlist/shared' -import { ChevronDownIcon } from 'lucide-react' +import { CheckIcon, ChevronDownIcon } from 'lucide-react' import { Card } from '@/components/ui/card' import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible' import type { useUpdateItem } from '@/hooks/use-items' -import { ItemRow, type ItemRowProps } from './item-row' +import { ItemRow } from './item-row' type BoughtItemListProps = { items: ListItem[] updateItem: ReturnType savingIds: string[] - /** The editing state of each row, owned by the parent so only one row edits at a time. */ - editingProps: (itemId: string) => Pick + onEdit: (item: ListItem) => void onMove: (item: ListItem) => void onDelete: (item: ListItem) => void } /** - * Collapsible "Comprados" card below the pending items. Expanded by default so - * marking an item visibly moves it down; the user can fold it. Tapping an item - * here un-buys it and it returns to the pending list. + * Collapsible "Comprados (N)" section at the end of the list, folded by default so + * the pending items stay in focus. Tapping an item here un-buys it and it returns + * to the pending list. */ export function BoughtItemList({ items, updateItem, savingIds, - editingProps, + onEdit, onMove, onDelete, }: BoughtItemListProps) { return ( - - - - - Comprados · {items.length} + +
+ + + Comprados ({items.length}) + -
    - {items.map((item) => ( - onMove(item)} - onDelete={() => onDelete(item)} - /> - ))} -
+ +
    + {items.map((item) => ( + onEdit(item)} + onMove={() => onMove(item)} + onDelete={() => onDelete(item)} + /> + ))} +
+
- +
) } diff --git a/apps/web/src/components/items/create-item-form.tsx b/apps/web/src/components/items/create-item-form.tsx index 67dc80f..0d83d49 100644 --- a/apps/web/src/components/items/create-item-form.tsx +++ b/apps/web/src/components/items/create-item-form.tsx @@ -1,7 +1,7 @@ import { zodResolver } from '@hookform/resolvers/zod' import type { ListItem } from '@superlist/shared' -import { PlusIcon, SearchIcon } from 'lucide-react' -import { type ClipboardEvent, useState } from 'react' +import { Loader2Icon, MicIcon, PlusIcon } from 'lucide-react' +import { type ClipboardEvent, useEffect, useRef, useState } from 'react' import { useForm, useWatch } from 'react-hook-form' import { toast } from 'sonner' import { z } from 'zod' @@ -14,10 +14,19 @@ import { InputGroupButton, InputGroupInput, } from '@/components/ui/input-group' -import { isOptimisticItem, useCreateItem, useItems, useUpdateItem } from '@/hooks/use-items' +import { useDictation } from '@/hooks/use-dictation' +import { + isOptimisticItem, + useCreateItem, + useItems, + useRemoveItems, + useUpdateItem, +} from '@/hooks/use-items' +import { useVoiceSplit } from '@/hooks/use-voice-split' import { ApiError } from '@/lib/api-client' import { findDuplicate, mergeBatch, mergeInto } from '@/lib/natural-input/merge' import { isPlainItem, literalItem, parseItemInput } from '@/lib/natural-input/parse-item' +import { cn } from '@/lib/utils' // The input may hold several items ("leche, pan y 2 pascualinas" or a pasted list); // each one is checked against the API limits once the text is read. @@ -33,6 +42,9 @@ type CreateItemFormProps = { autoFocus?: boolean } +/** How long the "Deshacer" of a dictation stays on screen. */ +const DICTATION_UNDO_MS = 8000 + /** The input carries this id so it can be focused from outside the form (e.g. by the nav). */ const NEW_ITEM_INPUT_ID = 'new-item-input' @@ -64,15 +76,28 @@ function itemLimitError(item: PreviewItem): string | null { return null } +/** What adding a batch of items did, so a dictation can be undone. */ +type AddedItems = { + /** Ids of the items created (failed ones are left out). */ + created: Promise + /** The previous quantity/notes of the pending items that were added to. */ + merged: { itemId: string; quantity: string | null; notes: string | null }[] +} + /** - * Input to add items to a list. Submits with Enter or the button. The text is read + * Input to add items to a list. Submits with Enter or the "+" button. The text is read * as natural language ("400 de jamon", "Queso crema. Solo Tregar", "leche, pan y * 2 pascualinas"), previewed while typing, and an item already pending is added to * instead of repeated. + * + * The microphone dictates instead: the transcript is split into items by the API (with + * AI) and each one goes through this same flow. "Deshacer" removes the whole dictation. */ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProps) { const createItem = useCreateItem(listId) const updateItem = useUpdateItem(listId) + const removeItems = useRemoveItems(listId) + const voiceSplit = useVoiceSplit() const { data: items } = useItems(listId) // The text the user asked to add as typed; editing it brings the reading back. const [literalText, setLiteralText] = useState(null) @@ -86,8 +111,22 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp const literal = literalText !== null && literalText === text // Placeholders have no server id yet, so they cannot be added to. const existing = (items ?? []).filter((item) => !isOptimisticItem(item)) + // A dictation finishes after a request: by then the list may have changed. + const existingRef = useRef(existing) + existingRef.current = existing + + const dictation = useDictation({ onTranscript: (transcript) => void addDictation(transcript) }) + const processing = voiceSplit.isPending + const dictating = dictation.listening || processing + + // The partial transcript is shown in the input while the user talks. + useEffect(() => { + if (dictation.listening) form.setValue('name', dictation.interim) + }, [dictation.listening, dictation.interim, form]) + const preview = readItems(text, literal, existing) const showPreview = + !dictating && text.trim() !== '' && (literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate)) @@ -97,6 +136,58 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp form.setError('name', { message }) } + /** Adds the items, or adds to the pending ones they repeat. A failed one comes back to the input. */ + const addItems = (toAdd: PreviewItem[]): AddedItems => { + const created: Promise[] = [] + const merged: AddedItems['merged'] = [] + + for (const item of toAdd) { + if (item.duplicate) { + const patch = mergeInto(item.duplicate, item) + if (patch.quantity !== undefined || patch.notes !== undefined) { + updateItem.mutate({ itemId: item.duplicate.id, ...patch }) + merged.push({ + itemId: item.duplicate.id, + quantity: item.duplicate.quantity, + notes: item.duplicate.notes, + }) + } + toast( + patch.quantity + ? `Se sumó a «${item.duplicate.name}» (${patch.quantity})` + : `«${item.duplicate.name}» ya está en la lista`, + ) + continue + } + + created.push( + createItem + .mutateAsync({ + name: item.name, + quantity: item.quantity ?? undefined, + notes: item.notes ?? undefined, + }) + .then( + (createdItem) => createdItem.id, + (error) => { + restoreText( + item.source, + error instanceof ApiError + ? (error.problem.detail ?? error.problem.title) + : 'No pudimos añadir el artículo.', + ) + return null + }, + ), + ) + } + + return { + created: Promise.all(created).then((ids) => ids.filter((id): id is string => id !== null)), + merged, + } + } + // The input clears at once (items are added optimistically) so several items can be // typed in a row; if a request fails its text comes back with the error. const onSubmit = form.handleSubmit((values) => { @@ -112,35 +203,52 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp setLiteralText(null) form.setFocus('name') - for (const item of toAdd) { - if (item.duplicate) { - const patch = mergeInto(item.duplicate, item) - if (patch.quantity !== undefined || patch.notes !== undefined) { - updateItem.mutate({ itemId: item.duplicate.id, ...patch }) - } - toast( - patch.quantity - ? `Se sumó a «${item.duplicate.name}» (${patch.quantity})` - : `«${item.duplicate.name}» ya está en la lista`, - ) - continue - } - - createItem.mutate( - { name: item.name, quantity: item.quantity ?? undefined, notes: item.notes ?? undefined }, - { - onError: (error) => - restoreText( - item.source, - error instanceof ApiError - ? (error.problem.detail ?? error.problem.title) - : 'No pudimos añadir el artículo.', - ), - }, - ) - } + addItems(toAdd) }) + /** + * The API splits the transcript into one string per item and each one is read by the + * usual parser. If the request fails, the whole transcript is added as a single item. + */ + const addDictation = async (transcript: string) => { + form.reset() + setLiteralText(null) + + let toAdd: PreviewItem[] + try { + const { items: spoken } = await voiceSplit.mutateAsync({ text: transcript }) + toAdd = readItems(spoken.join('; '), false, existingRef.current) + } catch { + toAdd = readItems(transcript, true, existingRef.current) + } + + if (toAdd.length === 0) return + + const limitError = toAdd.map(itemLimitError).find(Boolean) + if (limitError) { + form.setValue('name', transcript) + form.setError('name', { message: limitError }) + return + } + + const { created, merged } = addItems(toAdd) + const createdIds = await created + const count = createdIds.length + merged.length + if (count === 0) return + + toast(`Se ${count === 1 ? 'agregó 1 producto' : `agregaron ${count} productos`}`, { + // Longer than a plain toast: the user has to check what was understood first. + duration: DICTATION_UNDO_MS, + action: { + label: 'Deshacer', + onClick: () => { + void removeItems(createdIds) + for (const previous of merged) updateItem.mutate(previous) + }, + }, + }) + } + // An drops line breaks, so a pasted list keeps one item per line as "; ". const onPaste = (event: ClipboardEvent) => { const pasted = event.clipboardData.getData('text') @@ -161,31 +269,24 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp }) } + const micLabel = processing + ? 'Procesando el dictado' + : dictation.listening + ? 'Dejar de escuchar' + : 'Dictar productos' + return (
- - - - - + event.preventDefault()} @@ -193,8 +294,52 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp + + {dictation.supported && ( + + + {processing ? ( + + ) : ( + + )} + + + )} + {dictation.error && ( +

+ {dictation.error} +

+ )} {showPreview && ( - -type ItemEditorProps = { - item: ListItem - updateItem: ReturnType - onClose: () => void - /** - * Receives the quantity input, so the row can focus it synchronously from the - * gesture that opened the editor (iOS only shows the keyboard that way). - */ - quantityInputRef?: Ref -} - -/** - * Inline editor for an item's quantity and notes, shown right below its row. - * Opened by swiping the row to the left or right-clicking it. - */ -export function ItemEditor({ item, updateItem, onClose, quantityInputRef }: ItemEditorProps) { - // The editor only exists while open, so it always starts from the current - // values (including another member's edit received over SSE). - const form = useForm({ - resolver: zodResolver(itemDetailsSchema), - defaultValues: { quantity: item.quantity ?? '', notes: item.notes ?? '' }, - }) - - const { ref: registerQuantityRef, ...quantityField } = form.register('quantity') - - const onSubmit = form.handleSubmit((values) => { - updateItem.mutate( - { itemId: item.id, quantity: values.quantity || null, notes: values.notes || null }, - { - // The row already shows the new values optimistically, so on success - // nothing else is left to do. On error the hook reports the problem - // details and the editor stays open, keeping the typed text for a retry. - onSuccess: onClose, - }, - ) - }) - - return ( - { - if (event.key !== 'Escape') return - event.preventDefault() - onClose() - }} - className="bg-muted/40 flex flex-col gap-3 border-t px-4 py-3" - > - - { - registerQuantityRef(element) - if (typeof quantityInputRef === 'function') quantityInputRef(element) - else if (quantityInputRef) quantityInputRef.current = element - }} - /> - - - -