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:
Jose Selesan
2026-10-28 19:25:10 -03:00
parent eb1f6cb2a9
commit a814b34036
39 changed files with 1673 additions and 288 deletions

123
apps/api/src/lib/gemini.ts Normal file
View File

@@ -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<string, string | undefined> = 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<string> }
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<string> {
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
}
}