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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(voice): read aloud survives a strict CSP, blob URLs instead of data URLs
purple3908eefe0662
diff --git a/e2e/tts-csp.spec.ts b/e2e/tts-csp.spec.tsnew file mode 100644index 00000000..c94c8857--- /dev/null+++ b/e2e/tts-csp.spec.ts@@ -0,0 +1,79 @@+import { test, expect } from '@playwright/test'+import { readFileSync } from 'node:fs'+import { join, dirname } from 'node:path'+import { fileURLToPath } from 'node:url'++const here = dirname(fileURLToPath(import.meta.url))++/**+ * GH #77, the CSP half: the shipped policy decides whether read-aloud makes a+ * sound. WKWebView is lax about it, so every Mac here played fine while+ * WebView2's Chromium blocked every data:audio URL on the reporters' Windows.+ *+ * This spec loads the EXACT csp from tauri.conf.json into a Chromium page and+ * pins the contract the voice layer relies on:+ * - a data:audio URL does not play (which is why synthesis must hand out+ * blob URLs, never data URLs)+ * - a blob URL plays (media-src blob:)+ * - fetch() of a blob URL works (connect-src blob:, the codec-free Web+ * Audio fallback for Windows N reads its bytes this way)+ */++const csp = (+ JSON.parse(readFileSync(join(here, '..', 'src-tauri', 'tauri.conf.json'), 'utf8')) as {+ app: { security: { csp: string } }+ }+).app.security.csp++test('the shipped CSP blocks data:audio and allows blob playback + blob fetch', async ({ page }) => {+ await page.setContent(+ `<!doctype html><meta http-equiv="Content-Security-Policy" content="${csp.replace(/"/g, '"')}"><body></body>`,+ )++ const verdict = await page.evaluate(async () => {+ // A minimal valid 16-bit PCM wav (4 frames of silence, 22.05 kHz mono),+ // built in-page so both URL flavors carry identical bytes.+ const dataLen = 8+ const buf = new ArrayBuffer(44 + dataLen)+ const v = new DataView(buf)+ const w = (o: number, s: string) => {+ for (let i = 0; i < s.length; i++) v.setUint8(o + i, s.charCodeAt(i))+ }+ w(0, 'RIFF'); v.setUint32(4, 36 + dataLen, true); w(8, 'WAVE')+ w(12, 'fmt '); v.setUint32(16, 16, true)+ v.setUint16(20, 1, true); v.setUint16(22, 1, true)+ v.setUint32(24, 22050, true); v.setUint32(28, 44100, true)+ v.setUint16(32, 2, true); v.setUint16(34, 16, true)+ w(36, 'data'); v.setUint32(40, dataLen, true)+ const bytes = new Uint8Array(buf)++ let bin = ''+ for (const b of bytes) bin += String.fromCharCode(b)+ const dataUrl = `data:audio/wav;base64,${btoa(bin)}`+ const blobUrl = URL.createObjectURL(new Blob([bytes], { type: 'audio/wav' }))++ const tryPlay = (url: string) =>+ new Promise<string>((resolve) => {+ const a = new Audio(url)+ a.muted = true+ a.onerror = () => resolve('error')+ a.play().then(() => resolve('playing'), (e: Error) => resolve(`rejected:${e.name}`))+ setTimeout(() => resolve('timeout'), 3000)+ })++ const dataPlay = await tryPlay(dataUrl)+ const blobPlay = await tryPlay(blobUrl)+ const blobFetch = await fetch(blobUrl).then(+ (r) => (r.ok ? 'ok' : `status:${r.status}`),+ (e: Error) => `rejected:${e.name}`,+ )+ return { dataPlay, blobPlay, blobFetch }+ })++ // The bug: a data URL under this policy never plays. If this ever flips to+ // 'playing', someone widened media-src — the blob conversion stays either way.+ expect(verdict.dataPlay).not.toBe('playing')+ // The fix: identical bytes as a blob URL play, and their fetch is allowed.+ expect(verdict.blobPlay).toBe('playing')+ expect(verdict.blobFetch).toBe('ok')+})diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex ae9362e7..40cf7f24 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -24,7 +24,7 @@}],"security": {- "csp": "default-src 'self' http://ipc.localhost; connect-src 'self' http://ipc.localhost http://tauri.localhost http://localhost:* http://127.0.0.1:* https://lu-labs.ai https://lrrhheztdytyfpizvuup.supabase.co https://civitai.com https://*.civitai.com https://huggingface.co https://*.huggingface.co https://ollama.com https://openrouter.ai https://api.openai.com https://api.groq.com https://api.together.xyz https://api.deepseek.com https://api.mistral.ai https://api.anthropic.com ws://localhost:* ws://127.0.0.1:*; img-src 'self' data: blob: http://localhost:* http://127.0.0.1:* https://lrrhheztdytyfpizvuup.supabase.co https://*.civitai.com https://*.githubusercontent.com; media-src 'self' blob: http://localhost:* http://127.0.0.1:* https://lrrhheztdytyfpizvuup.supabase.co https://lu-labs.ai; font-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'wasm-unsafe-eval'"+ "csp": "default-src 'self' http://ipc.localhost; connect-src 'self' blob: http://ipc.localhost http://tauri.localhost http://localhost:* http://127.0.0.1:* https://lu-labs.ai https://lrrhheztdytyfpizvuup.supabase.co https://civitai.com https://*.civitai.com https://huggingface.co https://*.huggingface.co https://ollama.com https://openrouter.ai https://api.openai.com https://api.groq.com https://api.together.xyz https://api.deepseek.com https://api.mistral.ai https://api.anthropic.com ws://localhost:* ws://127.0.0.1:*; img-src 'self' data: blob: http://localhost:* http://127.0.0.1:* https://lrrhheztdytyfpizvuup.supabase.co https://*.civitai.com https://*.githubusercontent.com; media-src 'self' blob: http://localhost:* http://127.0.0.1:* https://lrrhheztdytyfpizvuup.supabase.co https://lu-labs.ai; font-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'wasm-unsafe-eval'"}},"plugins": {diff --git a/src/api/__tests__/voice-blob-url.test.ts b/src/api/__tests__/voice-blob-url.test.tsnew file mode 100644index 00000000..ac32932d--- /dev/null+++ b/src/api/__tests__/voice-blob-url.test.ts@@ -0,0 +1,71 @@+import { describe, it, expect, vi, afterEach } from 'vitest'+import { readFileSync } from 'node:fs'+import { base64ToBlobUrl } from '../voice'++// GH #77, round two: the wav was fine, the URL was not. A data:audio URL is+// blocked by our own CSP (media-src allows blob: only), and the Web Audio+// fallback fetch()ing that data URL is blocked by connect-src the same way.+// WKWebView shrugs the policy off, WebView2's Chromium enforces it, which is+// why read-aloud worked on every Mac here and on no reporter's Windows. So no+// synthesis path may ever hand out a data: URL again, and the CSP must allow+// fetching our own blobs for the codec-free fallback.++describe('base64ToBlobUrl', () => {+ afterEach(() => vi.restoreAllMocks())++ it('decodes base64 into a Blob of the declared mime and returns its object URL', () => {+ const bytes = new Uint8Array([82, 73, 70, 70, 0, 255]) // "RIFF" + binary tail+ const b64 = btoa(String.fromCharCode(...bytes))++ let captured: Blob | undefined+ vi.spyOn(URL, 'createObjectURL').mockImplementation((b) => {+ captured = b as Blob+ return 'blob:mock/1'+ })++ expect(base64ToBlobUrl(b64, 'audio/wav')).toBe('blob:mock/1')+ expect(captured?.type).toBe('audio/wav')+ expect(captured?.size).toBe(bytes.length)+ })++ it('round-trips the exact bytes', async () => {+ const bytes = new Uint8Array(256).map((_, i) => i)+ const b64 = btoa(String.fromCharCode(...bytes))++ let captured: Blob | undefined+ vi.spyOn(URL, 'createObjectURL').mockImplementation((b) => {+ captured = b as Blob+ return 'blob:mock/2'+ })++ base64ToBlobUrl(b64, 'audio/wav')+ expect(new Uint8Array(await captured!.arrayBuffer())).toEqual(bytes)+ })+})++describe('no synthesis path builds a data: URL', () => {+ it('voice.ts no longer builds a data: URL from synthesis output', () => {+ const src = readFileSync(new URL('../voice.ts', import.meta.url), 'utf8')+ expect(src).not.toMatch(/`data:/)+ })+})++describe('the CSP carries the fix', () => {+ const csp = (+ JSON.parse(+ readFileSync(new URL('../../../src-tauri/tauri.conf.json', import.meta.url), 'utf8'),+ ) as { app: { security: { csp: string } } }+ ).app.security.csp++ it('media-src allows blob playback', () => {+ expect(csp).toMatch(/media-src[^;]*blob:/)+ })++ it('connect-src allows fetching our own blobs (the Web Audio fallback)', () => {+ expect(csp).toMatch(/connect-src[^;]*blob:/)+ })++ it('connect-src does not open data: (only blob is needed)', () => {+ expect(csp).not.toMatch(/connect-src[^;]*data:/)+ })+})diff --git a/src/api/voice.ts b/src/api/voice.tsindex f054e55b..30a2e83a 100644--- a/src/api/voice.ts+++ b/src/api/voice.ts@@ -378,23 +378,35 @@ export async function recheckTtsAvailable(voice?: string): Promise<boolean> {return initTtsCheck(voice);}-/** Synthesize text to a playable WAV data URL via a local Piper voice. */+/** Decode a synthesis result into a blob: object URL. A data: URL is the+ * obvious carrier but the CSP only allows media-src blob:, so on the strict+ * Chromium of WebView2 every data:audio playback is silently blocked while+ * the lax WKWebView plays it (GitHub #77, the reason "read aloud" worked on+ * every Mac here and on no reporter's Windows). */+export function base64ToBlobUrl(b64: string, mime: string): string {+ const bin = atob(b64);+ const bytes = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);+ return URL.createObjectURL(new Blob([bytes], { type: mime }));+}++/** Synthesize text to a playable WAV blob URL via a local Piper voice. */export async function synthesizeNeural(text: string, voice?: string): Promise<string> {const data = await backendCall<{ audio_base64?: string; mime?: string }>("synthesize", { text, voice });if (!data?.audio_base64) throw new Error("neural TTS returned no audio");- return `data:${data.mime || "audio/wav"};base64,${data.audio_base64}`;+ return base64ToBlobUrl(data.audio_base64, data.mime || "audio/wav");}/*** Synthesize text via a user-configured external HTTP TTS engine (GitHub #58).* `url` is an OpenAI-compatible endpoint (e.g. Kokoro-FastAPI at* http://localhost:8880/v1/audio/speech); `voice` is that engine's voice name.- * Returns a playable data URL (the Rust side honors the returned audio type).+ * Returns a playable blob URL (the Rust side honors the returned audio type).*/export async function synthesizeExternal(text: string, url: string, voice?: string): Promise<string> {const data = await backendCall<{ audio_base64?: string; mime?: string }>("synthesize_external", { text, url, voice });if (!data?.audio_base64) throw new Error("external TTS returned no audio");- return `data:${data.mime || "audio/wav"};base64,${data.audio_base64}`;+ return base64ToBlobUrl(data.audio_base64, data.mime || "audio/wav");}/** Download a Piper voice model on demand. Blocks until done (~63 MB). */@@ -495,9 +507,9 @@ async function playViaWebAudio(dataUrl: string): Promise<void> {}}-/** Play a WAV data URL or MP3 blob URL; resolves when playback ends (or is- * stopped via stopNeuralAudio). Replaces any current clip. Object URLs are- * revoked once the clip settles so cloud TTS blobs don't pin memory. */+/** Play a WAV/MP3 blob URL; resolves when playback ends (or is stopped via+ * stopNeuralAudio). Replaces any current clip. Object URLs are revoked once+ * the clip settles so TTS blobs don't pin memory. */export function playNeuralAudio(dataUrl: string): Promise<void> {return new Promise((resolve, reject) => {stopNeuralAudio();