Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Frontend resilience: failed-upload recovery, nav guard, chunking msg fix, chat partial preserve, markRaw multi-upload perf (#297, #287, #283, #282, #280)
Murtaza Nasirb0d9d2af7075
diff --git a/static/js/modules/composables/audio.js b/static/js/modules/composables/audio.jsindex 0ac77abc..96258f25 100644--- a/static/js/modules/composables/audio.js+++ b/static/js/modules/composables/audio.js@@ -506,7 +506,12 @@ export function useAudio(state, utils) {return;}const timestamp = new Date().toISOString().replace(/[:.]/g, '-');- const recordedFile = new File(audioChunks.value, `recording-${timestamp}.webm`, { type: 'audio/webm' });+ const _rawRecordedFile = new File(audioChunks.value, `recording-${timestamp}.webm`, { type: 'audio/webm' });+ // Prevent Vue from wrapping the binary File in a reactive proxy. See+ // upload.js for rationale (issue #280).+ const recordedFile = (typeof Vue !== 'undefined' && Vue.markRaw)+ ? Vue.markRaw(_rawRecordedFile)+ : _rawRecordedFile;// Get selected tags as objects and create a DEEP copy to prevent reactivity issuesconst selectedTagsTemp = selectedTagIds.value.map(tagId => {@@ -517,7 +522,12 @@ export function useAudio(state, utils) {// Deep clone to completely break reactivity chain - JSON parse/stringify removes all proxiesconst selectedTags = JSON.parse(JSON.stringify(selectedTagsTemp));- // Add to upload queue+ // Add to upload queue. The recording session in IndexedDB is+ // intentionally NOT cleared here (issue #287(b)). It is the user's+ // crash-recovery copy; we only clear it once the upload has reached+ // the server successfully. The clientId on the queue item is what the+ // upload-success handler uses to find and clear the matching session.+ const queueClientId = `client-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;uploadQueue.value.push({file: recordedFile,notes: recordingNotes.value,@@ -531,19 +541,30 @@ export function useAudio(state, utils) {},status: 'queued',recordingId: null,- clientId: `client-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,+ clientId: queueClientId,+ fromInProgressRecording: true, // marker: upload-success handler clears RecordingDB sessionerror: null,willAutoSummarize: false // Server will tell us via SUMMARIZING status});- // Clear IndexedDB session after successful queue- try {- await RecordingDB.clearRecordingSession();- } catch (dbError) {- console.warn('[Recording] Failed to clear IndexedDB session:', dbError);+ // Release the in-memory audio resources so the recording view does not+ // keep showing the old waveform, but DO NOT clear the IndexedDB session+ // (that happens only on upload success — see upload.js).+ if (audioBlobURL.value) {+ URL.revokeObjectURL(audioBlobURL.value);}-- discardRecording();+ audioBlobURL.value = null;+ audioChunks.value = [];+ isRecording.value = false;+ recordingTime.value = 0;+ if (recordingInterval.value) clearInterval(recordingInterval.value);+ recordingNotes.value = '';+ selectedTagIds.value = [];+ asrLanguage.value = '';+ asrMinSpeakers.value = '';+ asrMaxSpeakers.value = '';+ await releaseWakeLock();+ await hideRecordingNotification();// Return to upload view (main UI)currentView.value = 'upload';@@ -572,7 +593,12 @@ export function useAudio(state, utils) {}const timestamp = new Date().toISOString().replace(/[:.]/g, '-');- const recordedFile = new File(audioChunks.value, `recording-${timestamp}.webm`, { type: 'audio/webm' });+ const _rawRecordedFile = new File(audioChunks.value, `recording-${timestamp}.webm`, { type: 'audio/webm' });+ // Prevent Vue from wrapping the binary File in a reactive proxy. See+ // upload.js for rationale (issue #280).+ const recordedFile = (typeof Vue !== 'undefined' && Vue.markRaw)+ ? Vue.markRaw(_rawRecordedFile)+ : _rawRecordedFile;incognitoProcessing.value = true;processingMessage.value = 'Processing recording in incognito mode...';diff --git a/static/js/modules/composables/chat.js b/static/js/modules/composables/chat.jsindex f202e8f6..5d540b38 100644--- a/static/js/modules/composables/chat.js+++ b/static/js/modules/composables/chat.js@@ -211,9 +211,21 @@ export function useChat(state, utils) {} catch (error) {console.error('Chat Error:', error);+ // Preserve any partial assistant content that was already streamed+ // before the connection dropped (issue #282). Reverse-proxy read+ // timeouts on long-thinking responses used to wipe the visible+ // response entirely; now we keep what arrived and append an error+ // note below it so the user can still copy what they got.if (assistantMessage) {- assistantMessage.content = `Error: ${error.message}`;- assistantMessage.html = `<span class="text-red-500">Error: ${error.message}</span>`;+ const partial = (assistantMessage.content || '').trim();+ const errSuffix = `\n\n_⚠️ Connection ended before the response completed: ${error.message}_`;+ if (partial) {+ assistantMessage.content = partial + errSuffix;+ assistantMessage.html = marked.parse(assistantMessage.content);+ } else {+ assistantMessage.content = `Error: ${error.message}`;+ assistantMessage.html = `<span class="text-red-500">Error: ${error.message}</span>`;+ }} else {chatMessages.value.push({role: 'assistant',diff --git a/static/js/modules/composables/ui.js b/static/js/modules/composables/ui.jsindex dd43795b..3764da81 100644--- a/static/js/modules/composables/ui.js+++ b/static/js/modules/composables/ui.js@@ -136,8 +136,23 @@ export function useUI(state, utils, processedTranscription) {}};- // Switch to upload view+ // Switch to upload view. Guarded against silently abandoning an unsaved+ // in-app recording (issue #287(a)): if a recording is in progress or+ // stopped-but-not-yet-uploaded, confirm before leaving the recording view.const switchToUploadView = () => {+ const isRecording = state.isRecording;+ const audioBlobURL = state.audioBlobURL;+ const hasUnsaved = currentView.value === 'recording'+ && ((isRecording && isRecording.value === true)+ || (audioBlobURL && audioBlobURL.value));+ if (hasUnsaved) {+ const tFn = utils.t || ((key) => key);+ const message = tFn('confirms.discardUnsavedRecording')+ || 'You have an unsaved recording. Are you sure you want to leave?';+ if (!window.confirm(message)) {+ return;+ }+ }currentView.value = 'upload';if (isMobileScreen.value) {isSidebarCollapsed.value = true;diff --git a/static/js/modules/composables/upload.js b/static/js/modules/composables/upload.jsindex 77f54564..f68490e2 100644--- a/static/js/modules/composables/upload.js+++ b/static/js/modules/composables/upload.js@@ -5,6 +5,7 @@import * as FailedUploads from '../db/failed-uploads.js';import * as IncognitoStorage from '../db/incognito-storage.js';+import * as RecordingDB from '../db/recording-persistence.js';// Parse error message and return friendly error infofunction getFriendlyError(errorMessage, t) {@@ -12,7 +13,11 @@ function getFriendlyError(errorMessage, t) {if (!errorMessage) return { title: _t('errors.processingError'), message: _t('errors.processingErrorMessage') };const lowerText = errorMessage.toLowerCase();const patterns = [- { patterns: ['maximum content size limit', 'file too large', '413', 'payload too large', 'exceeded'], title: _t('errors.fileTooLargeTitle'), guidance: _t('errors.enableChunkingGuidance') },+ // Reverse-proxy 413 (nginx / NPM default). Must match BEFORE the+ // generic 413 pattern below; the proxy rejects the request body before+ // Speakr sees it, so enabling chunking on the Speakr side will not help.+ { patterns: ['request entity too large', 'request body is too large', '413 request entity too large'], title: _t('errors.uploadBlockedByProxyTitle'), guidance: _t('errors.uploadBlockedByProxyGuidance') },+ { patterns: ['maximum content size limit', 'file too large', 'payload too large', 'exceeded', 'content too large'], title: _t('errors.fileTooLargeTitle'), guidance: _t('errors.enableChunkingGuidance') },{ patterns: ['timed out', 'timeout', 'deadline exceeded'], title: _t('errors.processingTimeout'), guidance: _t('errors.splitAudioGuidance') },{ patterns: ['401', 'unauthorized', 'invalid api key', 'authentication failed', 'incorrect api key'], title: _t('errors.authenticationError'), guidance: _t('errors.checkApiKeyGuidance') },{ patterns: ['rate limit', 'too many requests', '429', 'quota exceeded'], title: _t('errors.rateLimitExceeded'), guidance: _t('errors.waitAndRetryGuidance') },@@ -48,7 +53,7 @@ export function useUpload(state, utils) {uploadDisclaimer, showUploadDisclaimerModal} = state;- const { computed, nextTick, ref } = Vue;+ const { computed, nextTick, ref, markRaw } = Vue;const { setGlobalError, showToast, formatFileSize, onChatComplete, t } = utils;@@ -195,8 +200,13 @@ export function useUpload(state, utils) {const clientId = `client-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;+ // markRaw prevents Vue from wrapping the File in a reactive+ // proxy. Vue's proxy walks object properties when accessed,+ // which is extremely expensive for binary File/Blob payloads+ // and was a likely cause of the UI freeze seen when 10+ files+ // were queued at once (issue #280).uploadQueue.value.push({- file: fileObject,+ file: markRaw ? markRaw(fileObject) : fileObject,notes: notes,tags: tags,asrOptions: asrOptions,@@ -468,6 +478,18 @@ export function useUpload(state, utils) {fileItem.recordingId = data.id;fileItem.progress = 100;+ // The in-progress recording session is now safe to clear (issue+ // #287(b)): the audio is on the server. Only do this for queue+ // items that came from an in-app recording, to avoid touching the+ // session for file-drag-drop uploads that never wrote one.+ if (fileItem.fromInProgressRecording) {+ try {+ await RecordingDB.clearRecordingSession();+ } catch (dbError) {+ console.warn('[Upload] Failed to clear recording session after successful upload:', dbError);+ }+ }+// Add to recordings listrecordings.value.unshift(data);totalRecordings.value++;@@ -496,7 +518,15 @@ export function useUpload(state, utils) {const friendlyErr = getFriendlyError(error.message, t);setGlobalError(`${friendlyErr.title}: ${friendlyErr.guidance}`);- // Store failed upload in IndexedDB for background sync retry+ // Defense-in-depth recovery (issue #297, #287):+ // 1. Persist the file to IndexedDB so background sync can retry.+ // 2. If IndexedDB persistence fails (quota exceeded, private mode,+ // missing IndexedDB), fall back to triggering a browser-side+ // download so the user keeps a local copy of the audio. The+ // worst possible outcome is permanent audio loss on upload+ // failure, so we treat both layers as best-effort and only+ // stop trying once one succeeded.+ let persistedToIndexedDB = false;try {await FailedUploads.storeFailedUpload({file: fileItem.file,@@ -508,14 +538,42 @@ export function useUpload(state, utils) {asrOptions: fileItem.asrOptions,error: error.message});+ persistedToIndexedDB = true;+ } catch (dbError) {+ console.warn('[Upload] IndexedDB persistence failed for failed upload:', dbError);+ }- if ('serviceWorker' in navigator && 'sync' in ServiceWorkerRegistration.prototype) {- const registration = await navigator.serviceWorker.ready;- await registration.sync.register('sync-uploads');- console.log('[Upload] Registered background sync for failed upload');+ if (persistedToIndexedDB) {+ try {+ if ('serviceWorker' in navigator && 'sync' in ServiceWorkerRegistration.prototype) {+ const registration = await navigator.serviceWorker.ready;+ await registration.sync.register('sync-uploads');+ console.log('[Upload] Registered background sync for failed upload');+ }+ } catch (syncError) {+ console.warn('[Upload] Failed to register background sync:', syncError);+ }+ } else {+ // IndexedDB rejected the failed-upload write. Last-resort:+ // hand the audio back to the user as a browser download so it+ // survives a tab close.+ const downloaded = FailedUploads.triggerLocalDownload(+ fileItem.file,+ fileItem.file?.name || `speakr-recording-${Date.now()}.webm`+ );+ if (downloaded) {+ showToast?.(+ (t && t('toasts.uploadFailedDownloadedLocally'))+ || 'Upload failed. Audio saved to your Downloads folder for retry.',+ 'fa-file-download'+ );+ } else {+ showToast?.(+ (t && t('toasts.uploadFailedNoRecovery'))+ || 'Upload failed and audio could not be saved locally. Please record again.',+ 'fa-triangle-exclamation'+ );}- } catch (syncError) {- console.warn('[Upload] Failed to register background sync:', syncError);}} finally {fileItem._xhr = null;diff --git a/static/js/modules/db/failed-uploads.js b/static/js/modules/db/failed-uploads.jsindex 9d4cf581..2d732d21 100644--- a/static/js/modules/db/failed-uploads.js+++ b/static/js/modules/db/failed-uploads.js@@ -240,6 +240,37 @@ export const clearAllFailedUploads = async () => {}};+/**+ * Last-resort safety net: trigger a browser-side download of the audio blob so+ * the user keeps a local copy even if neither the upload nor IndexedDB+ * persistence succeeded. Returns true if the download was triggered, false if+ * we could not build a downloadable URL (e.g. blob revoked, empty data).+ */+export const triggerLocalDownload = (file, suggestedName) => {+ if (!file || !file.size) {+ return false;+ }+ try {+ const url = URL.createObjectURL(file);+ const anchor = document.createElement('a');+ anchor.href = url;+ anchor.download = suggestedName || file.name || `speakr-recording-${Date.now()}.webm`;+ anchor.style.display = 'none';+ document.body.appendChild(anchor);+ anchor.click();+ document.body.removeChild(anchor);+ // Revoke after a delay so the browser has time to start the download+ setTimeout(() => {+ try { URL.revokeObjectURL(url); } catch (_) { /* ignore */ }+ }, 60_000);+ console.warn('[FailedUploadsDB] Triggered local download as safety fallback');+ return true;+ } catch (error) {+ console.error('[FailedUploadsDB] Local download fallback failed:', error);+ return false;+ }+};+/*** Get count of failed uploads*/diff --git a/static/js/modules/db/failed-uploads.test.js b/static/js/modules/db/failed-uploads.test.jsnew file mode 100644index 00000000..67bc1420--- /dev/null+++ b/static/js/modules/db/failed-uploads.test.js@@ -0,0 +1,85 @@+/**+ * Tests for the local-download safety-net helper (issue #297).+ *+ * triggerLocalDownload is the last-resort fallback when both the upload and+ * IndexedDB persistence fail. It builds a blob URL, attaches an anchor,+ * synthesises a click, and revokes the URL afterwards. We mock the DOM+ * and URL APIs to verify the call shape.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { triggerLocalDownload } from './failed-uploads.js';++describe('triggerLocalDownload', () => {+ let originalDocument;+ let originalURL;+ let createObjectURL;+ let revokeObjectURL;+ let appendChild;+ let removeChild;+ let click;+ let anchor;++ beforeEach(() => {+ createObjectURL = vi.fn(() => 'blob:test-url');+ revokeObjectURL = vi.fn();+ click = vi.fn();+ appendChild = vi.fn();+ removeChild = vi.fn();+ anchor = {+ click,+ style: {},+ set href(val) { this._href = val; },+ get href() { return this._href; },+ set download(val) { this._download = val; },+ get download() { return this._download; },+ };+ originalURL = global.URL;+ originalDocument = global.document;+ global.URL = { createObjectURL, revokeObjectURL };+ global.document = {+ createElement: vi.fn(() => anchor),+ body: { appendChild, removeChild },+ };+ });++ afterEach(() => {+ global.URL = originalURL;+ global.document = originalDocument;+ });++ it('returns false for falsy file', () => {+ expect(triggerLocalDownload(null, 'a.webm')).toBe(false);+ expect(triggerLocalDownload(undefined, 'a.webm')).toBe(false);+ });++ it('returns false for zero-size blob', () => {+ expect(triggerLocalDownload({ size: 0 }, 'a.webm')).toBe(false);+ expect(createObjectURL).not.toHaveBeenCalled();+ });++ it('synthesises a click on an anchor for a non-empty blob', () => {+ const fakeFile = { name: 'recording.webm', size: 1024, type: 'audio/webm' };+ const result = triggerLocalDownload(fakeFile, 'recording.webm');+ expect(result).toBe(true);+ expect(createObjectURL).toHaveBeenCalledWith(fakeFile);+ expect(global.document.createElement).toHaveBeenCalledWith('a');+ expect(anchor.href).toBe('blob:test-url');+ expect(anchor.download).toBe('recording.webm');+ expect(click).toHaveBeenCalledOnce();+ expect(appendChild).toHaveBeenCalledWith(anchor);+ expect(removeChild).toHaveBeenCalledWith(anchor);+ });++ it('falls back to a generated name when none is supplied', () => {+ const fakeFile = { size: 100 };+ triggerLocalDownload(fakeFile);+ expect(anchor.download).toMatch(/^speakr-recording-\d+\.webm$/);+ });++ it('returns false when DOM access throws', () => {+ global.URL.createObjectURL = vi.fn(() => { throw new Error('boom'); });+ const result = triggerLocalDownload({ size: 1 }, 'x.webm');+ expect(result).toBe(false);+ });+});diff --git a/static/js/modules/utils/errorDisplay.js b/static/js/modules/utils/errorDisplay.jsindex 6671c2d6..2c0df054 100644--- a/static/js/modules/utils/errorDisplay.js+++ b/static/js/modules/utils/errorDisplay.js@@ -63,10 +63,27 @@ function parseUnformattedError(text) {// Known error patternsconst patterns = [{- patterns: ['maximum content size limit', 'file too large', '413', 'payload too large', 'exceeded'],+ // Reverse-proxy 413 (nginx default "Request Entity Too Large", Apache+ // "Request body is too large", Nginx Proxy Manager defaults). The+ // request never reached Speakr, so enabling chunking on the Speakr+ // side cannot help; the proxy must allow a larger body. Match this+ // BEFORE the generic 413/file-too-large pattern below.+ patterns: ['request entity too large', 'request body is too large', '413 request entity too large'],+ title: 'Upload Blocked by Reverse Proxy',+ message: 'The reverse proxy in front of Speakr rejected the upload before it reached Speakr.',+ guidance: 'Increase the client body size limit on your reverse proxy. For nginx, set client_max_body_size to a value larger than your audio file. For Nginx Proxy Manager the default is 2000m and is adjustable per host in the Advanced tab. The chunking and compression options in Speakr do not apply here because the upload is rejected before Speakr sees it.',+ icon: 'fa-shield-halved',+ type: 'proxy_limit'+ },+ {+ // Speakr's own MAX_FILE_SIZE_MB rejection (returns JSON with a+ // specific "File too large. Max: N MB" payload) and downstream+ // transcription-service size limits (e.g. OpenAI Whisper 25 MB).+ // Both are addressable from the Speakr side via chunking.+ patterns: ['maximum content size limit', 'file too large', 'payload too large', 'exceeded', 'content too large'],title: 'File Too Large',message: 'The audio file exceeds the maximum size allowed by the transcription service.',- guidance: 'Try enabling audio chunking in your settings, or compress the audio file before uploading.',+ guidance: 'Enable audio chunking in your admin settings if it is off, or compress the audio file before uploading. If chunking is already enabled, the file may still exceed the per-chunk limit; lower the chunk size or compress the source.',icon: 'fa-file-audio',type: 'size_limit'},