Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
In-app recording: real resume into same session, unified recovery modal, IndexedDB rolling buffer, live sidebar/queue updates, configurable chunk cadence
Murtaza Nasira3ccab41c4f9
diff --git a/static/js/app.modular.js b/static/js/app.modular.jsindex 8d3ec3ef..ce90cb74 100644--- a/static/js/app.modular.js+++ b/static/js/app.modular.js@@ -2266,6 +2266,12 @@ document.addEventListener('DOMContentLoaded', async () => {utils.startUploadQueue = uploadComposable.startUpload;const audioComposable = useAudio(state, utils);+ // Expose the full discard (clears the blob, aborts any server+ // session, clears IndexedDB) so the navigation guard can actually+ // tear down an unsaved/recovered recording when the user chooses to+ // leave — otherwise audioBlobURL lingers and the "unsaved recording"+ // prompt fires on every subsequent navigation.+ utils.discardActiveRecording = audioComposable.discardRecording;const uiComposable = useUI(state, utils, processedTranscription);const modalsComposable = useModals(state, utils);const sharingComposable = useSharing(state, utils);@@ -2677,6 +2683,19 @@ document.addEventListener('DOMContentLoaded', async () => {}};+ // Bridge for the in-app recorder (#287): a server-side recording+ // finalizes entirely on the backend, so nothing enters the client+ // uploadQueue to trip hasActiveProcessing. Without this nudge the+ // new recording + its stitch/transcribe jobs only appear after a+ // manual refresh. The audio composable calls this right after a+ // successful finalize so the sidebar and processing-queue panel+ // update live, exactly like a drag-drop upload.+ utils.onServerRecordingQueued = async () => {+ try { await recordingsComposable.loadRecordings(); } catch (_) { /* non-fatal */ }+ await fetchJobQueueStatus(true);+ startJobQueuePolling();+ };+// Check if we have active items that need pollingconst hasActiveProcessing = computed(() => {const completedStatuses = ['completed', 'failed', 'COMPLETED', 'FAILED'];@@ -2716,6 +2735,15 @@ document.addEventListener('DOMContentLoaded', async () => {// Watch allJobs for completed/failed transitions - update local recordings statewatch(allJobs, async (jobs) => {for (const job of jobs) {+ // A 'stitch' job is an intermediate step for server-side+ // recordings (#287): a 'transcribe' job always follows it.+ // Only the terminal job is the recording's completion. If+ // we acted on the stitch completion we would capture the+ // still-processing state and then dedupe away the real+ // transcribe completion — leaving the recording stuck on+ // "Processing". A FAILED stitch IS terminal (no transcribe+ // follows), so only skip the completed case.+ if (job.job_type === 'stitch' && job.job_status === 'completed') continue;if (job.job_status === 'completed' && !completedRecordingIds.has(job.recording_id)) {completedRecordingIds.add(job.recording_id);try {@@ -3377,55 +3405,61 @@ document.addEventListener('DOMContentLoaded', async () => {console.warn('[App] share-target query handling failed:', e);}- // Check for recoverable recording from IndexedDB- try {- const recoverable = await audioComposable.checkForRecoverableRecording();- if (recoverable && recoverable.chunks && recoverable.chunks.length > 0) {- recoverableRecording.value = recoverable;- showRecoveryModal.value = true;- console.log('[App] Found recoverable recording, showing recovery dialog');- }- } catch (error) {- console.error('[App] Failed to check for recoverable recording:', error);- }-- // Phase C of #287 (c)(d): also check for an in-progress- // server-side recording session. If localStorage remembers- // a session id and the server confirms it is still in the- // 'recording' state, surface a toast offering to abort it- // (the streaming client cannot resume a MediaRecorder mid-- // stream because the captured audio track does not survive- // page reload). For now we let the user confirm an abort- // to clean up the server-side chunks; full resume lands in- // a follow-up with a chunked-playback fallback.+ // Unified recording recovery (#287 task #4): ONE decision so+ // the user never sees two prompts for the same recording.+ // Preference order:+ // 1. A durable in-progress SERVER session (survives device+ // loss) → themed recovery modal (finish / discard).+ // 2. Otherwise a local IndexedDB copy → themed modal+ // (restore / discard). This is the fallback path used+ // when server chunking is off or the server was+ // unreachable.+ // If a remembered server session exists but is no longer+ // recoverable (already finalized / aborted / expired), we+ // forget it AND clear the now-redundant local copy so the old+ // double-prompt + duplicate-restore bug can't recur.try {const ServerSessions = await import('./modules/db/server-recording-sessions.js');const remembered = ServerSessions.getRememberedSession();+ let serverSession = null;if (remembered && remembered.session_id) {- const status = await ServerSessions.getSessionStatus(remembered.session_id);- if (status && status.status === 'recording' && status.chunk_count > 0) {- const msg = t('toasts.recordingResumeFound') || 'An in-progress recording from this browser was detected on the server.';- const confirmFinalize = window.confirm(msg);- if (confirmFinalize) {- // Finalize using the remembered session; the- // server stitches what was already uploaded.- try {- await ServerSessions.finalizeSession(remembered.session_id, {- title: `Recovered recording ${new Date().toLocaleString()}`,- });- showToast(t('toasts.recordingFinalized') || 'Recording uploaded for processing', 'fa-cloud-upload-alt');- await recordingsComposable.loadRecordings();- } catch (e) {- console.warn('[App] Could not finalize recovered server session:', e);- setGlobalError(`Could not recover the session: ${e.message}`);- }- } else {- try { await ServerSessions.abortSession(remembered.session_id); } catch (_) { /* ignore */ }- }+ try { serverSession = await ServerSessions.getSessionStatus(remembered.session_id); }+ catch (_) { serverSession = null; }+ }++ if (serverSession && serverSession.status === 'recording' && serverSession.chunk_count > 0) {+ // Pull any local metadata (mode/notes) just for display.+ let localMeta = null;+ try { localMeta = await audioComposable.checkForRecoverableRecording(); } catch (_) { /* ignore */ }+ recoverableRecording.value = {+ source: 'server',+ sessionId: remembered.session_id,+ mimeType: remembered.mime_type || (localMeta && localMeta.mimeType) || 'audio/webm',+ chunkCount: serverSession.chunk_count,+ totalSize: serverSession.bytes_received,+ duration: (localMeta && localMeta.duration) || null,+ startTime: serverSession.created_at,+ mode: (localMeta && localMeta.mode) || null,+ notes: (localMeta && localMeta.notes) || null,+ };+ showRecoveryModal.value = true;+ console.log('[App] In-progress server recording detected, offering recovery');+ } else if (remembered && remembered.session_id) {+ // Remembered session is no longer recoverable → forget+ // the pointer and clear the redundant local copy.+ ServerSessions.forgetActiveSession();+ try { await audioComposable.clearRecordingSession(); } catch (_) { /* ignore */ }+ } else {+ // No server session involved → legacy local recovery.+ const recoverable = await audioComposable.checkForRecoverableRecording();+ if (recoverable && recoverable.chunks && recoverable.chunks.length > 0) {+ recoverableRecording.value = { source: 'local', ...recoverable };+ showRecoveryModal.value = true;+ console.log('[App] Found local recoverable recording, showing recovery dialog');}}} catch (error) {- console.warn('[App] Server-session resume check failed:', error);+ console.warn('[App] Recording recovery check failed:', error);}// Detect the ?upload=1 deep-link (inquire mode's "+ New@@ -3647,6 +3681,90 @@ document.addEventListener('DOMContentLoaded', async () => {}};+ // Non-destructive close (X button / click-outside): just dismiss+ // the modal without finalizing or discarding. The recording stays+ // recoverable and is offered again next load.+ const dismissRecovery = () => {+ showRecoveryModal.value = false;+ recoverableRecording.value = null;+ };++ // Server-session recovery: finish processing what was uploaded.+ // Routes through the same finalize → stitch → transcribe pipeline+ // as a normal Stop+Upload, and clears the redundant local copy so+ // it isn't offered again.+ const finalizeRecoveredSession = async () => {+ const rec = recoverableRecording.value;+ showRecoveryModal.value = false;+ recoverableRecording.value = null;+ if (!rec || !rec.sessionId) return;+ try {+ const ServerSessions = await import('./modules/db/server-recording-sessions.js');+ await ServerSessions.finalizeSession(rec.sessionId, {});+ try { await audioComposable.clearRecordingSession(); } catch (_) { /* ignore */ }+ showToast(safeT('messages.recordingRecovered') || safeT('toasts.recordingFinalized') || 'Recording uploaded for processing', 'success');+ // Surface it live in the sidebar + processing-queue panel.+ try { await utils.onServerRecordingQueued?.(); } catch (_) { /* non-fatal */ }+ } catch (e) {+ console.warn('[App] Could not finalize recovered server session:', e);+ setGlobalError(`Could not recover the session: ${e.message}`);+ }+ };++ // Server-session recovery: RESUME. Continue recording into the+ // same server session — a fresh MediaRecorder appends a new segment+ // after the audio already on the server (the segment-aware stitch+ // concatenates them at finalize). We re-read the live chunk count so+ // the new segment starts at the correct index.+ const resumeRecoveredSession = async () => {+ const rec = recoverableRecording.value;+ showRecoveryModal.value = false;+ recoverableRecording.value = null;+ if (!rec || !rec.sessionId) return;+ try {+ const ServerSessions = await import('./modules/db/server-recording-sessions.js');+ let chunkCount = rec.chunkCount || 0;+ let priorBytes = rec.totalSize || 0;+ try {+ const status = await ServerSessions.getSessionStatus(rec.sessionId);+ if (!status || status.status !== 'recording') {+ setGlobalError(safeT('errors.recordingNotResumable') || 'That recording can no longer be resumed.');+ ServerSessions.forgetActiveSession();+ return;+ }+ if (typeof status.chunk_count === 'number') chunkCount = status.chunk_count;+ if (typeof status.bytes_received === 'number') priorBytes = status.bytes_received;+ } catch (_) { /* fall back to the modal's count */ }+ const mode = rec.mode || 'microphone';+ const priorSeconds = rec.duration || (chunkCount * 5);+ await audioComposable.startRecording(mode, {+ sessionId: rec.sessionId,+ mimeType: rec.mimeType,+ startIndex: chunkCount + 1,+ priorSeconds,+ priorBytes,+ });+ } catch (e) {+ console.warn('[App] Could not resume server session:', e);+ setGlobalError(`Could not resume the recording: ${e.message}`);+ }+ };++ // Server-session recovery: discard. Abort on the server (reaps the+ // chunks now) and clear the local copy.+ const discardRecoveredSession = async () => {+ const rec = recoverableRecording.value;+ showRecoveryModal.value = false;+ recoverableRecording.value = null;+ if (!rec || !rec.sessionId) return;+ try {+ const ServerSessions = await import('./modules/db/server-recording-sessions.js');+ await ServerSessions.abortSession(rec.sessionId);+ } catch (_) { /* ignore */ }+ try { await audioComposable.clearRecordingSession(); } catch (_) { /* ignore */ }+ showToast(safeT('messages.recordingDiscarded'), 'info');+ };+const formatRecordingMode = (mode) => {const modes = {'microphone': t('recording.modeMicrophone'),@@ -3789,6 +3907,10 @@ document.addEventListener('DOMContentLoaded', async () => {recoverableRecording,recoverRecording,cancelRecovery,+ dismissRecovery,+ finalizeRecoveredSession,+ discardRecoveredSession,+ resumeRecoveredSession,// Composable methods...recordingsComposable,diff --git a/static/js/modules/composables/audio.js b/static/js/modules/composables/audio.jsindex 88e8905e..93aba40c 100644--- a/static/js/modules/composables/audio.js+++ b/static/js/modules/composables/audio.js@@ -30,6 +30,13 @@ export function useAudio(state, utils) {// Local state for pending streams and chunk trackinglet pendingDisplayStream = null;let currentChunkIndex = 0;+ // Carries resume info ({sessionId, mimeType, startIndex, priorSeconds,+ // priorBytes}) across the disclaimer detour when resuming an existing+ // server session.+ let pendingResumeContext = null;+ // Bytes already uploaded to the server before a resume, so the live size+ // estimate reflects the WHOLE recording, not just the new segment.+ let serverResumePriorBytes = 0;// Phase B: server-side chunk streaming (#287 c/d). Feature-flagged via// the page-level dataset attribute `data-server-recording-chunks`@@ -51,6 +58,16 @@ export function useAudio(state, utils) {return (el.dataset.serverRecordingChunks || '').toLowerCase() === 'true';}+ // MediaRecorder timeslice in ms, from the page dataset (env+ // RECORDING_CHUNK_SECONDS, default 5). Controls chunk emit + upload+ // cadence. Clamped to [1, 60] seconds to match the server.+ function _recordingChunkMs() {+ const el = document.getElementById('app');+ const raw = el && el.dataset ? el.dataset.recordingChunkSeconds : '';+ const secs = parseInt(raw, 10);+ return (Number.isFinite(secs) && secs >= 1 && secs <= 60 ? secs : 5) * 1000;+ }+function _resetServerSessionState() {serverSessionId = null;serverSessionUploader = null;@@ -185,7 +202,7 @@ export function useAudio(state, utils) {// Start recording// IMPORTANT: For Firefox, getDisplayMedia MUST be the first async call from user gesture- const startRecording = async (mode = 'microphone') => {+ const startRecording = async (mode = 'microphone', resumeContext = null) => {const needsDisplayMedia = mode === 'system' || mode === 'both';// For system audio modes, get display media FIRST before any other operations@@ -225,16 +242,19 @@ export function useAudio(state, utils) {if (recordingDisclaimer.value && recordingDisclaimer.value.trim() !== '') {showRecordingDisclaimerModal.value = true;pendingRecordingMode.value = mode;+ pendingResumeContext = resumeContext;return;}- await startRecordingInternal(mode);+ await startRecordingInternal(mode, resumeContext);};// Accept recording disclaimer and start recordingconst acceptRecordingDisclaimer = async () => {showRecordingDisclaimerModal.value = false;- await startRecordingInternal(pendingRecordingMode.value || 'microphone');+ const resumeContext = pendingResumeContext;+ pendingResumeContext = null;+ await startRecordingInternal(pendingRecordingMode.value || 'microphone', resumeContext);};// Cancel recording disclaimer@@ -246,15 +266,23 @@ export function useAudio(state, utils) {pendingDisplayStream = null;}pendingRecordingMode.value = null;+ pendingResumeContext = null;};- // Internal start recording function- const startRecordingInternal = async (mode) => {+ // Internal start recording function. resumeContext (optional) continues an+ // existing server session after a page reload: a fresh MediaRecorder keeps+ // POSTing chunks to the same session id, and its header chunk starts a new+ // segment that the server-side assembly concatenates onto the prior audio.+ const startRecordingInternal = async (mode, resumeContext = null) => {try {recordingMode.value = mode;audioChunks.value = [];- recordingTime.value = 0;- estimatedFileSize.value = 0;+ // On resume, continue the on-screen timer and size estimate from+ // where the prior segment left off so both reflect the WHOLE+ // recording, not just the new segment.+ recordingTime.value = (resumeContext && resumeContext.priorSeconds) || 0;+ serverResumePriorBytes = (resumeContext && resumeContext.priorBytes) || 0;+ estimatedFileSize.value = serverResumePriorBytes;fileSizeWarningShown.value = false;// Initialize IndexedDB session@@ -520,10 +548,24 @@ export function useAudio(state, utils) {// a network round-trip.if (_serverRecordingChunksEnabled()) {try {- serverSessionMimeType = mimeType.split(';')[0]; // strip codecs= suffix- const session = await ServerSessions.createSession(serverSessionMimeType);- serverSessionId = session.session_id;+ let startIndex = 1;+ if (resumeContext && resumeContext.sessionId) {+ // RESUME: reuse the existing session; the new+ // MediaRecorder's chunks append after what the server+ // already has (its header chunk opens a new segment).+ serverSessionId = resumeContext.sessionId;+ serverSessionMimeType = resumeContext.mimeType || mimeType.split(';')[0];+ startIndex = (resumeContext.startIndex && resumeContext.startIndex > 1)+ ? resumeContext.startIndex : 1;+ console.log('[Recording] Resuming server session', serverSessionId, 'from chunk', startIndex);+ } else {+ serverSessionMimeType = mimeType.split(';')[0]; // strip codecs= suffix+ const session = await ServerSessions.createSession(serverSessionMimeType);+ serverSessionId = session.session_id;+ console.log('[Recording] Opened server session', serverSessionId);+ }serverSessionUploader = ServerSessions.createUploader(serverSessionId, {+ startIndex,onError: (info) => {serverSessionLastError = info.error;if (info.droppedFromQueue) {@@ -531,7 +573,6 @@ export function useAudio(state, utils) {}},});- console.log('[Recording] Opened server session', serverSessionId);} catch (e) {serverSessionLastError = e;console.warn('[Recording] Could not open server session; falling back to local-only:', e);@@ -562,6 +603,20 @@ export function useAudio(state, utils) {// serverSessionUploader.lastError().if (serverSessionUploader) {serverSessionUploader.enqueue(event.data);++ // Storage dedupe (#287 task 5): when the server is the+ // durable copy and keeping up, keep only a small rolling+ // IndexedDB buffer instead of every chunk — avoids the+ // IndexedDB quota blowing out on hours-long recordings.+ // Guard: only prune when the backlog is smaller than the+ // window we keep, so a not-yet-uploaded chunk is never+ // dropped from the local fallback. If the server falls+ // behind / is unreachable, the backlog grows past the+ // window and we keep the FULL buffer as the safety net.+ const ROLLING_KEEP = 5;+ if (serverSessionUploader.getBacklog() < ROLLING_KEEP) {+ RecordingDB.pruneOldChunks(ROLLING_KEEP).catch(() => {});+ }}}};@@ -573,7 +628,9 @@ export function useAudio(state, utils) {};mediaRecorder.value = recorder;- recorder.start(5000); // 5-second chunks for less overhead while still enabling crash recovery+ // Timeslice is configurable (RECORDING_CHUNK_SECONDS, default 5s):+ // smaller = finer crash recovery, larger = less server load.+ recorder.start(_recordingChunkMs());isRecording.value = true;// Switch to recording view immediately so pending wake-lock/notification awaits don't block Safari renderingcurrentView.value = 'recording';@@ -703,8 +760,12 @@ export function useAudio(state, utils) {if (serverSessionId && serverSessionUploader) {try {await serverSessionUploader.drain();+ // No title here on purpose: the in-app recorder has no title+ // field, so we must NOT fabricate one. The server resolves the+ // title through the shared resolve_upload_title helper — an+ // absent title becomes a recognised placeholder and the+ // recording gets an AI title, exactly like a drag-drop upload.const metadata = {- title: `Recording ${new Date().toLocaleString()}`,notes: recordingNotes.value || null,folder_id: selectedFolderId.value || null,tags: selectedTags,@@ -731,11 +792,15 @@ export function useAudio(state, utils) {await hideRecordingNotification();try { await RecordingDB.clearRecordingSession(); } catch (_) { /* ignore */ }_resetServerSessionState();- // Drop the recording view and reopen the upload modal- // over whatever was underneath so the finalized- // recording lands in the queue ready to finish.+ // The recording is already finalized server-side — there is+ // nothing left to "finish" in the upload modal. Drop back to+ // the main view and refresh the sidebar + processing-queue+ // panel so the queued recording appears immediately, the same+ // way a drag-drop upload does (instead of only after a manual+ // page refresh).currentView.value = null;- showUploadModal.value = true;+ showUploadModal.value = false;+ try { await utils.onServerRecordingQueued?.(); } catch (_) { /* non-fatal */ }return result;} catch (e) {console.error('[Recording] finalize failed; falling back to single-shot upload:', e);@@ -1046,7 +1111,11 @@ export function useAudio(state, utils) {const updateFileSizeEstimate = () => {if (!isRecording.value || !audioChunks.value.length) return;- const totalSize = audioChunks.value.reduce((sum, chunk) => sum + chunk.size, 0);+ // Include bytes already uploaded before a resume so the estimate (and+ // the derived bitrate) reflect the whole recording, not just the new+ // segment. serverResumePriorBytes is 0 for a fresh recording.+ const totalSize = serverResumePriorBytes+ + audioChunks.value.reduce((sum, chunk) => sum + chunk.size, 0);estimatedFileSize.value = totalSize;if (recordingTime.value > 0) {diff --git a/static/js/modules/composables/recordings.js b/static/js/modules/composables/recordings.jsindex 63f148ea..cc6e1aae 100644--- a/static/js/modules/composables/recordings.js+++ b/static/js/modules/composables/recordings.js@@ -189,6 +189,13 @@ export function useRecordings(state, utils, reprocessComposable) {if (!confirm('You have an unsaved recording. Are you sure you want to leave?')) {return;}+ // User chose to leave → actually discard the unsaved/recovered+ // recording so the guard doesn't keep firing on every subsequent+ // navigation (clears the blob, aborts any server session, clears+ // IndexedDB).+ if (utils.discardActiveRecording) {+ try { await utils.discardActiveRecording(); } catch (_) { /* non-fatal */ }+ }}// Check if switching away from incognito recording to a regular recordingdiff --git a/static/js/modules/db/recording-persistence.js b/static/js/modules/db/recording-persistence.jsindex ccfc1199..8cd81c8e 100644--- a/static/js/modules/db/recording-persistence.js+++ b/static/js/modules/db/recording-persistence.js@@ -149,6 +149,33 @@ export const updateRecordingMetadata = async (updates) => {}};+/**+ * Prune the IndexedDB buffer to the last `keepLast` chunks.+ *+ * Storage dedupe (#287 task 5): when server chunking is on and the server is+ * keeping up, the server is the durable copy, so the browser only needs a+ * small rolling buffer for the in-flight gap instead of every chunk (which+ * would blow the IndexedDB quota on hours-long recordings and double-store+ * everything). The caller MUST only prune when the upload backlog is smaller+ * than keepLast, so a not-yet-uploaded chunk is never dropped from the local+ * fallback. Non-fatal on error — pruning is an optimization, not correctness.+ */+export const pruneOldChunks = async (keepLast = 5) => {+ try {+ const db = await initDB();+ const transaction = db.transaction([STORE_NAME], 'readwrite');+ const objectStore = transaction.objectStore(STORE_NAME);+ const session = await promisifyRequest(objectStore.get('current'));+ if (!session || !Array.isArray(session.chunks) || session.chunks.length <= keepLast) {+ return;+ }+ session.chunks = session.chunks.slice(-keepLast);+ await promisifyRequest(objectStore.put(session));+ } catch (error) {+ // Pruning is best-effort; recording continues regardless.+ }+};+/*** Check if there's a recoverable recording*/@@ -167,8 +194,11 @@ export const checkForRecoverableRecording = async () => {// Calculate total sizeconst totalSize = session.chunks.reduce((sum, chunk) => sum + chunk.size, 0);- // Calculate approximate duration (1 second chunks)- const duration = session.chunks.length;+ // Real elapsed seconds are tracked on the session (updated every chunk+ // via updateRecordingMetadata). Fall back to an estimate from the chunk+ // count at the MediaRecorder timeslice (5s) — NOT 1s, which made a+ // 20s recording read as "4s".+ const duration = session.duration || (session.chunks.length * 5);console.log('[RecordingDB] Found recoverable recording:', {chunks: session.chunks.length,@@ -219,7 +249,7 @@ export const recoverRecording = async () => {tags: session.tags,asrOptions: session.asrOptions,mimeType: session.mimeType,- duration: session.chunks.length,+ duration: session.duration || (session.chunks.length * 5),startTime: session.startTime}};diff --git a/static/js/modules/db/server-recording-sessions.js b/static/js/modules/db/server-recording-sessions.jsindex f4787775..6e1f2530 100644--- a/static/js/modules/db/server-recording-sessions.js+++ b/static/js/modules/db/server-recording-sessions.js@@ -41,7 +41,7 @@ function rememberActiveSession(sessionId, mimeType) {} catch (_) { /* private mode: best-effort */ }}-function forgetActiveSession() {+export function forgetActiveSession() {try { localStorage.removeItem(PENDING_KEY); } catch (_) { /* ignore */ }}@@ -199,7 +199,10 @@ export function createUploader(sessionId, opts = {}) {const maxDelayMs = opts.maxDelayMs || 30000;const queue = []; // [{blob, attempts}]- let nextIndex = 1; // server expects 1-based, monotonic+ // 1-based, monotonic. On RESUME (a new MediaRecorder continuing an existing+ // session after a page reload), start from the server's next expected index+ // so the new segment's chunks append in order rather than colliding at 1.+ let nextIndex = opts.startIndex && opts.startIndex > 1 ? opts.startIndex : 1;let pumpRunning = false;let lastErrorObj = null;let drainResolvers = [];diff --git a/static/js/modules/db/server-recording-sessions.test.js b/static/js/modules/db/server-recording-sessions.test.jsindex c0166fd4..a9b97e18 100644--- a/static/js/modules/db/server-recording-sessions.test.js+++ b/static/js/modules/db/server-recording-sessions.test.js@@ -172,6 +172,23 @@ describe('createUploader queue', () => {]);});+ it('resumes from startIndex so a new segment appends in order', async () => {+ // After a reload, the server already has 5 chunks; the resumed+ // MediaRecorder must POST its first chunk as index 6.+ global.fetch = _installFetchMock([+ { status: 204 }, { status: 204 },+ ]);+ const uploader = createUploader('sid', { startIndex: 6 });+ uploader.enqueue(new Uint8Array([1]));+ uploader.enqueue(new Uint8Array([2]));+ await uploader.drain();+ const urls = global.fetch.mock.calls.map(c => c[0]);+ expect(urls).toEqual([+ '/upload/session/sid/chunks/6',+ '/upload/session/sid/chunks/7',+ ]);+ });+it('retries with backoff on 500 then succeeds', async () => {global.fetch = _installFetchMock([{ status: 500, body: { error: 'transient' } },diff --git a/templates/index.html b/templates/index.htmlindex 771db2e4..b1a14f0d 100644--- a/templates/index.html+++ b/templates/index.html@@ -60,6 +60,7 @@data-audio-player-position="{{ (current_user.audio_player_position or 'bottom') if current_user.is_authenticated else 'bottom' }}"data-server-recording-chunks="{{ 'True' if server_recording_chunks_enabled else 'False' }}"data-recording-max-hours="{{ recording_max_hours }}"+ data-recording-chunk-seconds="{{ recording_chunk_seconds }}"class="h-full flex flex-col opacity-0 transition-opacity duration-500"><!-- Header -->diff --git a/templates/modals/recording-recovery-modal.html b/templates/modals/recording-recovery-modal.htmlindex adf75742..0f385963 100644--- a/templates/modals/recording-recovery-modal.html+++ b/templates/modals/recording-recovery-modal.html@@ -1,52 +1,120 @@<!-- Recording Recovery Modal (design system v1) -->-<div v-if="showRecoveryModal" @click.self="cancelRecovery" class="modal-overlay">+<!--+ Unified recovery modal (#287 task #4). Handles two sources:+ - 'server': an in-progress server-side recording session (durable). The+ user can finish processing what was uploaded, or discard it.+ - 'local' : an unfinished recording buffered in the browser's IndexedDB+ (the legacy path, used when server chunking is off / was unreachable).+ The user can restore it into the recorder, or discard it.+ The X / click-outside is non-destructive (dismiss only) for both.+-->+<div v-if="showRecoveryModal" @click.self="dismissRecovery" class="modal-overlay"><div class="modal-panel modal-panel--sm"><div class="modal-header"><i class="fas fa-history text-2xl text-[var(--text-accent)]"></i><h3 class="modal-title" v-text="t('recording.recoveryTitle')"></h3>- <button @click="cancelRecovery" class="modal-close" :title="t('buttons.close')"><i class="fas fa-times"></i></button>+ <button @click="dismissRecovery" class="modal-close" :title="t('buttons.close')"><i class="fas fa-times"></i></button></div><div class="modal-body">- <div class="banner banner--info" style="display: flex; align-items: flex-start; gap: var(--sp-2); margin-bottom: var(--sp-4);">- <i class="fas fa-info-circle" style="margin-top: 2px;"></i>- <div>- <div class="t-body-strong" style="margin-bottom: var(--sp-1);">${ t('recording.recoveryFound') }</div>- <div class="t-meta">${ t('recording.recoveryDescription') }</div>+ <!-- SERVER session recovery -->+ <template v-if="recoverableRecording && recoverableRecording.source === 'server'">+ <div class="banner banner--info" style="display: flex; align-items: flex-start; gap: var(--sp-2); margin-bottom: var(--sp-4);">+ <i class="fas fa-cloud" style="margin-top: 2px;"></i>+ <div>+ <div class="t-body-strong" style="margin-bottom: var(--sp-1);">${ t('recording.recoveryServerFound') }</div>+ <div class="t-meta">${ t('recording.recoveryServerDescription') }</div>+ </div></div>- </div>- <div v-if="recoverableRecording" class="space-y-2 t-meta">- <div class="flex justify-between">- <span>${ t('recording.recordingMode') }:</span>- <span class="t-body-strong">${ formatRecordingMode(recoverableRecording.mode) }</span>+ <div class="space-y-2 t-meta">+ <div v-if="recoverableRecording.mode" class="flex justify-between">+ <span>${ t('recording.recordingMode') }:</span>+ <span class="t-body-strong">${ formatRecordingMode(recoverableRecording.mode) }</span>+ </div>+ <div class="flex justify-between">+ <span>${ t('recording.recoveryChunksUploaded') }:</span>+ <span class="t-body-strong">${ recoverableRecording.chunkCount }</span>+ </div>+ <div class="flex justify-between">+ <span>${ t('recording.size') }:</span>+ <span class="t-body-strong">${ formatFileSize(recoverableRecording.totalSize) }</span>+ </div>+ <div class="flex justify-between">+ <span>${ t('recording.startedAt') }:</span>+ <span class="t-body-strong">${ formatDateTime(recoverableRecording.startTime) }</span>+ </div>+ <div v-if="recoverableRecording.notes" class="pt-2 border-t border-[var(--border-primary)]">+ <span>${ t('recording.notes') }:</span>+ <p class="mt-1 t-body max-h-32 overflow-y-auto whitespace-pre-wrap">${ recoverableRecording.notes }</p>+ </div></div>- <div class="flex justify-between">- <span>${ t('recording.duration') }:</span>- <span class="t-body-strong">${ formatTime(recoverableRecording.duration) }</span>- </div>- <div class="flex justify-between">- <span>${ t('recording.size') }:</span>- <span class="t-body-strong">${ formatFileSize(recoverableRecording.totalSize) }</span>- </div>- <div class="flex justify-between">- <span>${ t('recording.startedAt') }:</span>- <span class="t-body-strong">${ formatDateTime(recoverableRecording.startTime) }</span>+ </template>++ <!-- LOCAL (IndexedDB) recovery -->+ <template v-else-if="recoverableRecording">+ <div class="banner banner--info" style="display: flex; align-items: flex-start; gap: var(--sp-2); margin-bottom: var(--sp-4);">+ <i class="fas fa-info-circle" style="margin-top: 2px;"></i>+ <div>+ <div class="t-body-strong" style="margin-bottom: var(--sp-1);">${ t('recording.recoveryFound') }</div>+ <div class="t-meta">${ t('recording.recoveryDescription') }</div>+ </div></div>- <div v-if="recoverableRecording.notes" class="pt-2 border-t border-[var(--border-primary)]">- <span>${ t('recording.notes') }:</span>- <p class="mt-1 t-body max-h-32 overflow-y-auto whitespace-pre-wrap">${ recoverableRecording.notes }</p>++ <div class="space-y-2 t-meta">+ <div class="flex justify-between">+ <span>${ t('recording.recordingMode') }:</span>+ <span class="t-body-strong">${ formatRecordingMode(recoverableRecording.mode) }</span>+ </div>+ <div class="flex justify-between">+ <span>${ t('recording.duration') }:</span>+ <span class="t-body-strong">${ formatTime(recoverableRecording.duration) }</span>+ </div>+ <div class="flex justify-between">+ <span>${ t('recording.size') }:</span>+ <span class="t-body-strong">${ formatFileSize(recoverableRecording.totalSize) }</span>+ </div>+ <div class="flex justify-between">+ <span>${ t('recording.startedAt') }:</span>+ <span class="t-body-strong">${ formatDateTime(recoverableRecording.startTime) }</span>+ </div>+ <div v-if="recoverableRecording.notes" class="pt-2 border-t border-[var(--border-primary)]">+ <span>${ t('recording.notes') }:</span>+ <p class="mt-1 t-body max-h-32 overflow-y-auto whitespace-pre-wrap">${ recoverableRecording.notes }</p>+ </div></div>- </div>+ </template></div>+<div class="modal-footer modal-footer--between">- <button @click="cancelRecovery" class="btn btn--ghost">- <i class="fas fa-trash"></i>- <span>${ t('recording.discardRecovery') }</span>- </button>- <button @click="recoverRecording" class="btn btn--primary">- <i class="fas fa-undo"></i>- <span>${ t('recording.restoreRecording') }</span>- </button>+ <!-- SERVER actions: discard | finish processing | resume -->+ <template v-if="recoverableRecording && recoverableRecording.source === 'server'">+ <button @click="discardRecoveredSession" class="btn btn--ghost">+ <i class="fas fa-trash"></i>+ <span>${ t('recording.discardRecovery') }</span>+ </button>+ <div style="display: flex; gap: var(--sp-2);">+ <button @click="finalizeRecoveredSession" class="btn btn--ghost">+ <i class="fas fa-cloud-upload-alt"></i>+ <span>${ t('recording.recoveryFinishProcessing') }</span>+ </button>+ <button @click="resumeRecoveredSession" class="btn btn--primary">+ <i class="fas fa-microphone"></i>+ <span>${ t('recording.resumeRecording') }</span>+ </button>+ </div>+ </template>++ <!-- LOCAL actions -->+ <template v-else>+ <button @click="cancelRecovery" class="btn btn--ghost">+ <i class="fas fa-trash"></i>+ <span>${ t('recording.discardRecovery') }</span>+ </button>+ <button @click="recoverRecording" class="btn btn--primary">+ <i class="fas fa-undo"></i>+ <span>${ t('recording.restoreRecording') }</span>+ </button>+ </template></div></div></div>