Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(voice): a refused transcription says what happened instead of blaming the mic

Davidd91ae9e2f5b4
diff --git a/src/api/__tests__/voice-transcribe-local-api.test.ts b/src/api/__tests__/voice-transcribe-local-api.test.ts
new file mode 100644
index 00000000..77d3397f
--- /dev/null
+++ b/src/api/__tests__/voice-transcribe-local-api.test.ts
@@ -0,0 +1,192 @@
+/**
+ * GitHub #115 (graysoncooper), browser voice recording always failed.
+ *
+ * Two halves:
+ * 1. The /local-api security middleware enforced application/json on EVERY
+ * POST body and 415'd the transcribe POST, whose body IS the recorded
+ * audio, before the whisper handler ever saw it.
+ * 2. The client called res.json() on whatever came back. The gates answer
+ * text/plain, so the refusal died in the JSON parser and the user was
+ * told to check the microphone while the real reason was thrown away.
+ *
+ * These tests drive the REAL client (transcribeAudio, checkWhisperAvailable)
+ * against a stub of the REAL middleware, built from the same local-api-guard
+ * module vite.config.ts uses, so the whole browser path from the recorded WAV
+ * to the transcript is exercised in one place.
+ *
+ * Run: npx vitest run src/api/__tests__/voice-transcribe-local-api.test.ts
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { transcribeAudio, checkWhisperAvailable, LocalSttError } from '../voice'
+import { postContentTypeAllowed, postContentTypeError } from '../../lib/local-api-guard'
+import { sttErrorMessage } from '../../hooks/useVoice'
+
+/** What createAudioRecorder() hands transcribeAudio in browser mode: a 16 kHz
+ * mono WAV blob, so Content-Type goes out as audio/wav. */
+function recordedTake(): Blob {
+ return new Blob([new Uint8Array([0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0])], { type: 'audio/wav' })
+}
+
+type Verdict = (url: string, contentType: string) => boolean
+
+interface Seen {
+ method: string
+ contentType: string | null
+ csrf: string | null
+}
+
+const seen: Seen[] = []
+
+/** The /local-api middleware as vite.config.ts runs it: content-type gate,
+ * then the CSRF header, then the whisper handler. `verdict` is swappable so
+ * a test can put the pre-fix JSON-only rule back and watch the 415 return. */
+function installLocalApi(opts: {
+ verdict?: Verdict
+ handler?: () => Response
+} = {}) {
+ const verdict = opts.verdict ?? postContentTypeAllowed
+ const handler = opts.handler ?? (() => new Response(
+ JSON.stringify({ transcript: 'hello from the microphone', language: 'en' }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ ))
+
+ vi.stubGlobal('fetch', async (input: string, init?: RequestInit) => {
+ const path = String(input).replace('/local-api', '')
+ const headers = new Headers(init?.headers as HeadersInit)
+ const method = (init?.method || 'GET').toUpperCase()
+ seen.push({
+ method,
+ contentType: headers.get('content-type'),
+ csrf: headers.get('x-locally-uncensored'),
+ })
+
+ if (method === 'POST' && !verdict(path, headers.get('content-type') || '')) {
+ return new Response(postContentTypeError(path), {
+ status: 415,
+ headers: { 'content-type': 'text/plain' },
+ })
+ }
+ if (headers.get('x-locally-uncensored') !== 'true') {
+ return new Response('Forbidden: Missing x-locally-uncensored header (CSRF Protection)', {
+ status: 403,
+ headers: { 'content-type': 'text/plain' },
+ })
+ }
+ if (path === '/transcribe-status') {
+ return new Response(JSON.stringify({ available: true, backend: 'faster-whisper' }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ }
+ return handler()
+ })
+}
+
+beforeEach(() => { seen.length = 0 })
+afterEach(() => { vi.unstubAllGlobals() })
+
+describe('#115: the recorded take reaches whisper in browser mode', () => {
+ it('transcribes instead of being refused, and sends both things the gates want', async () => {
+ installLocalApi()
+ await expect(transcribeAudio(recordedTake())).resolves.toBe('hello from the microphone')
+ expect(seen).toHaveLength(1)
+ expect(seen[0].method).toBe('POST')
+ // The clip's real type, which is exactly what the old JSON-only rule 415'd.
+ expect(seen[0].contentType).toBe('audio/wav')
+ expect(seen[0].csrf).toBe('true')
+ })
+
+ it('sends the CSRF header on the availability probe too, so the mic can light up', async () => {
+ installLocalApi()
+ await expect(checkWhisperAvailable()).resolves.toMatchObject({ available: true })
+ expect(seen[0].csrf).toBe('true')
+ })
+})
+
+describe("#115 NEGATIVE CONTROL: the pre-fix JSON-only rule brings the bug back", () => {
+ /** The middleware exactly as it read before the carve-out. */
+ const jsonOnly: Verdict = (_url, contentType) => contentType.includes('application/json')
+
+ it('refuses the audio POST with 415, and the client reports it in English', async () => {
+ installLocalApi({ verdict: jsonOnly })
+ const err = await transcribeAudio(recordedTake()).then(
+ () => null,
+ (e: unknown) => e,
+ )
+ // The reporter's exact failure: the take never reaches whisper.
+ expect(err).toBeInstanceOf(LocalSttError)
+ expect((err as LocalSttError).status).toBe(415)
+ // And it no longer dies in the JSON parser with the reason thrown away.
+ expect((err as Error).message).toContain('HTTP 415')
+ expect((err as Error).message).toContain('Unsupported Media Type')
+ expect((err as Error).name).not.toBe('SyntaxError')
+ })
+})
+
+describe('#115 second half: a refusal keeps its reason all the way to the bubble', () => {
+ it('a 403 on the missing CSRF header is reported as a 403, not as a parse error', async () => {
+ // Middleware installed, but this request goes out bare like the old client did.
+ installLocalApi()
+ const bare = await fetch('/local-api/transcribe', {
+ method: 'POST',
+ headers: { 'Content-Type': 'audio/wav' },
+ body: recordedTake(),
+ })
+ expect(bare.status).toBe(403)
+ // And through the client, the same refusal keeps its wording.
+ vi.stubGlobal('fetch', async () => new Response('Forbidden: Missing x-locally-uncensored header (CSRF Protection)', {
+ status: 403,
+ headers: { 'content-type': 'text/plain' },
+ }))
+ const err = await transcribeAudio(recordedTake()).then(() => null, (e: unknown) => e)
+ expect((err as Error).message).toContain('HTTP 403')
+ expect((err as Error).message).toContain('Forbidden')
+ })
+
+ it('the handler answering 200 with an error keeps its own English wording', async () => {
+ installLocalApi({
+ handler: () => new Response(
+ JSON.stringify({ error: 'Whisper model is still loading, please wait...', transcript: '' }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ ),
+ })
+ const err = await transcribeAudio(recordedTake()).then(() => null, (e: unknown) => e)
+ expect((err as Error).message).toBe('Whisper model is still loading, please wait...')
+ })
+
+ it('an empty take is reported as empty audio, not as raw JSON in the user message', async () => {
+ installLocalApi({
+ handler: () => new Response(
+ JSON.stringify({ error: 'Empty audio data', transcript: '' }),
+ { status: 400, headers: { 'content-type': 'application/json' } },
+ ),
+ })
+ const err = await transcribeAudio(recordedTake()).then(() => null, (e: unknown) => e)
+ expect((err as Error).message).toBe('Transcription request refused (HTTP 400): Empty audio data')
+ expect((err as Error).message).not.toContain('{')
+ })
+
+ it('a refused availability probe says why instead of leaving the mic silently dead', async () => {
+ vi.stubGlobal('fetch', async () => new Response('Forbidden: Invalid Origin (CSRF Protection)', {
+ status: 403,
+ headers: { 'content-type': 'text/plain' },
+ }))
+ const status = await checkWhisperAvailable()
+ expect(status.available).toBe(false)
+ expect(status.error).toContain('HTTP 403')
+ expect(status.error).toContain('Invalid Origin')
+ })
+})
+
+describe('#115 second half: useVoice shows the reason instead of the microphone hint', () => {
+ it('passes a local STT failure through verbatim', () => {
+ const msg = sttErrorMessage(new LocalSttError('Transcription request refused (HTTP 415): Unsupported Media Type: Must be an audio body', 415))
+ expect(msg).toBe('Transcription request refused (HTTP 415): Unsupported Media Type: Must be an audio body')
+ })
+
+ it('NEGATIVE CONTROL: a plain Error still gets the generic hint, nothing else changed', () => {
+ expect(sttErrorMessage(new Error('TypeError: fetch failed'))).toBe(
+ 'Transcription failed, check the microphone and try again',
+ )
+ })
+})
diff --git a/src/api/voice.ts b/src/api/voice.ts
index f9ec6ee1..1092f0dd 100644
--- a/src/api/voice.ts
+++ b/src/api/voice.ts
@@ -172,6 +172,48 @@ export function stopSpeaking(): void {
// --- Local Whisper STT ---
+/**
+ * A dictation failure whose message is already written FOR THE USER, so
+ * useVoice shows it verbatim instead of the generic microphone hint.
+ *
+ * GitHub #115 (graysoncooper) had a second half behind the 415: the browser
+ * transcribe path called res.json() on every answer. The /local-api gates
+ * reply in text/plain, so a refusal died in the JSON parser, the thrown
+ * SyntaxError carried no reason, and the bubble told the user to check the
+ * microphone while the truth was a refused request. The same happened to the
+ * handler's own 200-with-error bodies ("Whisper not available", "Whisper
+ * model is still loading, please wait..."), which are honest English already.
+ */
+export class LocalSttError extends Error {
+ readonly status: number;
+ constructor(message: string, status = 0) {
+ super(message);
+ this.name = "LocalSttError";
+ this.status = status;
+ }
+}
+
+/** Turn a refused /local-api answer into an English, user-facing failure.
+ * The gates answer text/plain, the handler answers JSON, so read the body as
+ * text and lift `error` out of it when it happens to be JSON. */
+async function localApiFailure(res: Response, what: string): Promise<LocalSttError> {
+ const raw = (await res.text().catch(() => "")).trim();
+ let detail = raw;
+ if (raw.startsWith("{")) {
+ try {
+ const parsed = JSON.parse(raw) as { error?: unknown };
+ if (typeof parsed.error === "string" && parsed.error.trim()) detail = parsed.error.trim();
+ } catch {
+ /* not JSON after all, keep the raw text */
+ }
+ }
+ detail = detail.slice(0, 200);
+ return new LocalSttError(
+ detail ? `${what} (HTTP ${res.status}): ${detail}` : `${what} (HTTP ${res.status})`,
+ res.status,
+ );
+}
+
export async function checkWhisperAvailable(): Promise<{
available: boolean;
backend: string | null;
@@ -189,6 +231,12 @@ export async function checkWhisperAvailable(): Promise<{
const res = await fetch("/local-api/transcribe-status", {
headers: { "x-locally-uncensored": "true" },
});
+ // A refused probe answers text/plain, which used to blow up in res.json()
+ // and left the mic disabled with no reason anywhere (#115).
+ if (!res.ok) {
+ const err = await localApiFailure(res, "Speech-to-text probe refused");
+ return { available: false, backend: null, error: err.message };
+ }
return res.json();
} catch {
return { available: false, backend: null, error: "Failed to reach transcribe-status endpoint" };
@@ -213,7 +261,9 @@ export async function transcribeAudio(audioBlob: Blob): Promise<string> {
audioBase64,
contentType: audioBlob.type || "audio/wav",
});
- if (data.error) throw new Error(data.error);
+ // The Rust side writes these for the user ("Speech-to-text needs
+ // faster-whisper, which is not installed"), so keep them readable.
+ if (data.error) throw new LocalSttError(String(data.error));
return data.transcript || "";
}
@@ -226,8 +276,20 @@ export async function transcribeAudio(audioBlob: Blob): Promise<string> {
},
body: audioBlob,
});
- const data = await res.json();
- if (data.error) throw new Error(data.error);
+ // Every refusal in front of the whisper handler (415 on the body type, 403
+ // on the CSRF header or the origin, 405, a 404 from a dev server without
+ // the plugin) answers in text/plain. Reading it as JSON threw a parse error
+ // that hid the reason and pointed the user at the microphone (#115).
+ if (!res.ok) throw await localApiFailure(res, "Transcription request refused");
+ let data: { error?: string; transcript?: string };
+ try {
+ data = await res.json();
+ } catch {
+ throw new LocalSttError("Transcription returned a non-JSON response", res.status);
+ }
+ // The handler reports "Whisper not available" and "Whisper model is still
+ // loading, please wait..." with HTTP 200, both are honest English already.
+ if (data.error) throw new LocalSttError(String(data.error), res.status);
return data.transcript || "";
}
diff --git a/src/hooks/useVoice.ts b/src/hooks/useVoice.ts
index b214599a..6bed4d47 100644
--- a/src/hooks/useVoice.ts
+++ b/src/hooks/useVoice.ts
@@ -20,6 +20,7 @@ import {
transcribeAudio,
transcribeAudioCloud,
getLastTtsStatus,
+ LocalSttError,
type AudioRecorder,
} from "../api/voice";
import { CloudJobError } from "../api/cloud/client";
@@ -30,7 +31,13 @@ import { registerAutoSpeak } from "../lib/ttsBridge";
// Honest, actionable copy for dictation failures. The cloud route's own error
// strings (403 "your plan does not include cloud voice", 429 "monthly credit
// budget exhausted") are already human-readable — pass those through.
-function sttErrorMessage(err: unknown): string {
+export function sttErrorMessage(err: unknown): string {
+ // A refused /local-api call, or the whisper handler's own report. Both
+ // already say what went wrong in English (#115): "Transcription request
+ // refused (HTTP 415): Unsupported Media Type...", "Whisper not available".
+ // These used to arrive as a bare Error and were replaced by the microphone
+ // hint, which sent people looking at their mic instead of the real cause.
+ if (err instanceof LocalSttError && err.message.trim()) return err.message.trim();
if (err instanceof CloudJobError) {
if (err.status === 401) return "Signed out, sign in again to use cloud dictation";
if (err.status === 413) return "Recording too long, try a shorter take";