Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Phase B: client streaming + finalize for server-side recording chunks (#287 c/d)
Murtaza Nasir02caa225d7c2
diff --git a/src/api/recordings.py b/src/api/recordings.pyindex f6d931a0..7d9dac29 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -1367,6 +1367,15 @@ def index():except Exception as e:current_app.logger.warning(f"Could not get connector capabilities: {e}")+ # Phase B of #287 (c)(d): server-side chunk streaming for in-app+ # recordings. Off by default; enabling the env var flips the+ # data-server-recording-chunks attribute and the audio composable+ # opens an /upload/session for each in-app recording instead of+ # accumulating the whole blob in RAM.+ server_recording_chunks_enabled = os.environ.get(+ 'ENABLE_SERVER_RECORDING_CHUNKS', 'false'+ ).lower() == 'true'+return render_template('index.html',use_asr_endpoint=USE_ASR_ENDPOINT, # Backwards compatconnector_supports_diarization=connector_supports_diarization,@@ -1377,7 +1386,8 @@ def index():enable_archive_toggle=enable_archive_toggle,enable_internal_sharing=ENABLE_INTERNAL_SHARING,user_language=user_language,- is_team_admin=is_team_admin)+ is_team_admin=is_team_admin,+ server_recording_chunks_enabled=server_recording_chunks_enabled)diff --git a/static/js/modules/composables/audio.js b/static/js/modules/composables/audio.jsindex 96258f25..40929dad 100644--- a/static/js/modules/composables/audio.js+++ b/static/js/modules/composables/audio.js@@ -5,6 +5,7 @@import * as RecordingDB from '../db/recording-persistence.js';import * as IncognitoStorage from '../db/incognito-storage.js';+import * as ServerSessions from '../db/server-recording-sessions.js';export function useAudio(state, utils) {const {@@ -28,6 +29,32 @@ export function useAudio(state, utils) {let pendingDisplayStream = null;let currentChunkIndex = 0;+ // Phase B: server-side chunk streaming (#287 c/d). Feature-flagged via+ // the page-level dataset attribute `data-server-recording-chunks`+ // (rendered by Flask from ENABLE_SERVER_RECORDING_CHUNKS). When the+ // flag is on, every MediaRecorder chunk is also POSTed to the server+ // via createUploader; on Stop+Upload, finalizeSession runs instead of+ // the legacy single-shot upload path.+ //+ // None of this is exposed on the shared state surface yet; the UI to+ // monitor sync backlog lands in Phase C.+ let serverSessionId = null;+ let serverSessionUploader = null;+ let serverSessionMimeType = 'audio/webm';+ let serverSessionLastError = null;++ function _serverRecordingChunksEnabled() {+ const el = document.getElementById('app');+ if (!el || !el.dataset) return false;+ return (el.dataset.serverRecordingChunks || '').toLowerCase() === 'true';+ }++ function _resetServerSessionState() {+ serverSessionId = null;+ serverSessionUploader = null;+ serverSessionLastError = null;+ }+// iOS detectionconst isiOS = () => {return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;@@ -389,6 +416,32 @@ export function useAudio(state, utils) {console.warn('[Recording] IndexedDB persistence failed, continuing without persistence:', dbError);}+ // If server-side chunk streaming is enabled (#287 c/d), open the+ // session up front so the very first ondataavailable can post+ // straight to the server. A failure here logs and falls back to+ // local-only recording — the user's audio is never blocked on+ // a network round-trip.+ if (_serverRecordingChunksEnabled()) {+ try {+ serverSessionMimeType = mimeType.split(';')[0]; // strip codecs= suffix+ const session = await ServerSessions.createSession(serverSessionMimeType);+ serverSessionId = session.session_id;+ serverSessionUploader = ServerSessions.createUploader(serverSessionId, {+ onError: (info) => {+ serverSessionLastError = info.error;+ if (info.droppedFromQueue) {+ console.warn('[Recording] dropped chunk after max retries:', info);+ }+ },+ });+ 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);+ _resetServerSessionState();+ }+ }+recorder.ondataavailable = async (event) => {if (event.data.size > 0) {audioChunks.value.push(event.data);@@ -404,6 +457,15 @@ export function useAudio(state, utils) {} catch (dbError) {// Don't spam console - recording continues in memory regardless}++ // Server-side streaming (Phase B of #287 c/d). The+ // uploader handles ordering + retries internally; we+ // fire-and-forget here so MediaRecorder is never+ // blocked on the network. Failures are surfaced via+ // serverSessionUploader.lastError().+ if (serverSessionUploader) {+ serverSessionUploader.enqueue(event.data);+ }}};@@ -505,13 +567,6 @@ export function useAudio(state, utils) {setGlobalError("No recorded audio to upload.");return;}- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');- 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 => {@@ -522,6 +577,60 @@ export function useAudio(state, utils) {// Deep clone to completely break reactivity chain - JSON parse/stringify removes all proxiesconst selectedTags = JSON.parse(JSON.stringify(selectedTagsTemp));+ // Server-side streaming path (Phase B of #287 c/d): if the recording+ // was streamed chunk-by-chunk to the server, drain the uploader and+ // call finalize. The backend stitches the chunks via ffmpeg concat+ // demux into the final audio file, then enqueues a transcribe job.+ // The legacy in-memory single-shot path below stays as fallback for+ // recordings that were captured before this feature was enabled.+ if (serverSessionId && serverSessionUploader) {+ try {+ await serverSessionUploader.drain();+ const metadata = {+ title: `Recording ${new Date().toLocaleString()}`,+ notes: recordingNotes.value || null,+ folder_id: selectedFolderId.value || null,+ tags: selectedTags,+ language: asrLanguage.value || null,+ min_speakers: asrMinSpeakers.value || null,+ max_speakers: asrMaxSpeakers.value || null,+ };+ const result = await ServerSessions.finalizeSession(serverSessionId, metadata);+ showToast?.((utils.t && utils.t('toasts.recordingFinalized')) || 'Recording uploaded for processing', 'fa-cloud-upload-alt');++ // Tear down local state the same way the legacy path does.+ if (audioBlobURL.value) URL.revokeObjectURL(audioBlobURL.value);+ 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();+ try { await RecordingDB.clearRecordingSession(); } catch (_) { /* ignore */ }+ _resetServerSessionState();+ currentView.value = 'upload';+ return result;+ } catch (e) {+ console.error('[Recording] finalize failed; falling back to single-shot upload:', e);+ setGlobalError((utils.t && utils.t('errors.recordingFinalizeFallback')) || `Server-side stitch failed (${e.message}); uploading as a single file instead.`);+ // Fall through to the legacy upload path below.+ }+ }++ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');+ 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;+// 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@@ -724,6 +833,18 @@ export function useAudio(state, utils) {asrMinSpeakers.value = '';asrMaxSpeakers.value = '';+ // If a server-side session was open (Phase B of #287 c/d), abort it+ // so the chunks on disk are reaped immediately rather than waiting+ // for the cleanup sweep.+ if (serverSessionId) {+ try {+ await ServerSessions.abortSession(serverSessionId);+ } catch (e) {+ console.warn('[Recording] Could not abort server session during discard:', e);+ }+ _resetServerSessionState();+ }+// Clear IndexedDB sessiontry {await RecordingDB.clearRecordingSession();diff --git a/static/js/modules/db/server-recording-sessions.js b/static/js/modules/db/server-recording-sessions.jsnew file mode 100644index 00000000..f4787775--- /dev/null+++ b/static/js/modules/db/server-recording-sessions.js@@ -0,0 +1,285 @@+/**+ * Client wrapper around the server-side recording-session API (#287 c/d).+ *+ * Pairs with src/api/recording_sessions.py on the backend. While the user+ * is recording in-browser, every MediaRecorder chunk is POSTed to+ * /upload/session/{id}/chunks/{N}. On Stop + Upload, the client calls+ * /finalize and the backend stitch worker assembles the file via+ * ffmpeg concat demux.+ *+ * This module owns:+ * - Session lifecycle: createSession, finalizeSession, abortSession,+ * getSessionStatus.+ * - The retry queue: chunks that fail to POST are pushed onto an+ * in-memory queue and re-tried with exponential backoff. While the+ * queue is non-empty, callers can read `getSyncBacklog()` to drive+ * a "X chunks waiting to sync" banner.+ * - CSRF: every POST/DELETE attaches the page's meta csrf-token.+ *+ * Feature-flagged off by default; the audio composable checks+ * `state.serverRecordingChunksEnabled` before opening a session.+ */++const SESSION_BASE = '/upload/session';++const PENDING_KEY = 'speakr.serverRecordingSession';++/** Read the CSRF token written into the page by Flask-WTF. */+function csrfToken() {+ const el = document.querySelector('meta[name="csrf-token"]');+ return el ? el.getAttribute('content') : '';+}++/** Persist the active session id so we can resume after refresh. */+function rememberActiveSession(sessionId, mimeType) {+ try {+ localStorage.setItem(PENDING_KEY, JSON.stringify({+ session_id: sessionId,+ mime_type: mimeType,+ stamped_at: Date.now(),+ }));+ } catch (_) { /* private mode: best-effort */ }+}++function forgetActiveSession() {+ try { localStorage.removeItem(PENDING_KEY); } catch (_) { /* ignore */ }+}++export function getRememberedSession() {+ try {+ const raw = localStorage.getItem(PENDING_KEY);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (!parsed || !parsed.session_id) return null;+ return parsed;+ } catch (_) {+ return null;+ }+}++/**+ * POST /upload/session → { session_id, expires_at, max_chunk_bytes, ... }+ */+export async function createSession(mimeType = 'audio/webm') {+ const resp = await fetch(SESSION_BASE, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': csrfToken(),+ },+ credentials: 'same-origin',+ body: JSON.stringify({ mime_type: mimeType }),+ });+ if (!resp.ok) {+ const body = await safeJson(resp);+ const err = new Error(body?.error || `Could not open recording session (HTTP ${resp.status})`);+ err.status = resp.status;+ err.body = body;+ throw err;+ }+ const data = await resp.json();+ rememberActiveSession(data.session_id, data.mime_type);+ return data;+}++/**+ * POST /upload/session/{id}/chunks/{N} with the raw blob body.+ * Returns true on 204, throws otherwise.+ */+export async function uploadChunk(sessionId, chunkIndex, blob) {+ const resp = await fetch(`${SESSION_BASE}/${encodeURIComponent(sessionId)}/chunks/${chunkIndex}`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/octet-stream',+ 'X-CSRFToken': csrfToken(),+ },+ credentials: 'same-origin',+ body: blob,+ });+ if (resp.status === 204) return { ok: true };+ if (resp.status === 409) {+ // Out of order; the body tells us the expected index so we can+ // resync. The caller decides whether to back off and replay.+ const body = await safeJson(resp);+ const err = new Error(body?.error || 'Chunk out of order');+ err.status = 409;+ err.expectedChunkIndex = body?.expected_chunk_index;+ err.body = body;+ throw err;+ }+ const body = await safeJson(resp);+ const err = new Error(body?.error || `Chunk POST failed (HTTP ${resp.status})`);+ err.status = resp.status;+ err.body = body;+ throw err;+}++/**+ * GET /upload/session/{id} → status payload from the server.+ */+export async function getSessionStatus(sessionId) {+ const resp = await fetch(`${SESSION_BASE}/${encodeURIComponent(sessionId)}`, {+ method: 'GET',+ credentials: 'same-origin',+ headers: { 'X-CSRFToken': csrfToken() },+ });+ if (resp.status === 404) return null;+ if (!resp.ok) {+ const body = await safeJson(resp);+ throw new Error(body?.error || `Could not read session status (HTTP ${resp.status})`);+ }+ return resp.json();+}++/**+ * POST /upload/session/{id}/finalize with the user's metadata.+ * Returns { recording_id, status } from the backend.+ */+export async function finalizeSession(sessionId, metadata = {}) {+ const resp = await fetch(`${SESSION_BASE}/${encodeURIComponent(sessionId)}/finalize`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': csrfToken(),+ },+ credentials: 'same-origin',+ body: JSON.stringify(metadata || {}),+ });+ const body = await safeJson(resp);+ if (resp.status === 202) {+ forgetActiveSession();+ return body;+ }+ const err = new Error(body?.error || `Finalize failed (HTTP ${resp.status})`);+ err.status = resp.status;+ err.body = body;+ throw err;+}++/**+ * DELETE /upload/session/{id} to abort. 204 on success, 404 if gone.+ */+export async function abortSession(sessionId) {+ const resp = await fetch(`${SESSION_BASE}/${encodeURIComponent(sessionId)}`, {+ method: 'DELETE',+ credentials: 'same-origin',+ headers: { 'X-CSRFToken': csrfToken() },+ });+ forgetActiveSession();+ if (resp.status === 204 || resp.status === 404) return { ok: true };+ const body = await safeJson(resp);+ throw new Error(body?.error || `Abort failed (HTTP ${resp.status})`);+}++async function safeJson(resp) {+ try { return await resp.json(); } catch (_) { return null; }+}+++/**+ * createUploader(sessionId, opts)+ *+ * Returns a queue helper that callers (audio composable's+ * MediaRecorder.ondataavailable) push blobs into. Chunks POST in order;+ * failures retry with exponential backoff (1s, 2s, 4s, 8s, 16s, capped+ * at 30s, max 6 attempts) and the queue blocks subsequent chunks until+ * the head succeeds — preserving on-disk ordering on the server.+ *+ * const uploader = createUploader(sessionId);+ * recorder.ondataavailable = (e) => uploader.enqueue(e.data);+ * await uploader.drain(); // optional: wait for backlog to clear+ * uploader.getBacklog(); // number of pending chunks+ * uploader.lastError(); // most recent network/server error+ */+export function createUploader(sessionId, opts = {}) {+ const onError = opts.onError || (() => {});+ const onProgress = opts.onProgress || (() => {});+ const maxAttempts = opts.maxAttempts || 6;+ const baseDelayMs = opts.baseDelayMs || 1000;+ const maxDelayMs = opts.maxDelayMs || 30000;++ const queue = []; // [{blob, attempts}]+ let nextIndex = 1; // server expects 1-based, monotonic+ let pumpRunning = false;+ let lastErrorObj = null;+ let drainResolvers = [];++ const sleep = (ms) => new Promise(r => setTimeout(r, ms));+ const backoff = (attempts) => Math.min(maxDelayMs, baseDelayMs * Math.pow(2, attempts));++ async function pump() {+ if (pumpRunning) return;+ pumpRunning = true;+ try {+ while (queue.length > 0) {+ const head = queue[0];+ const indexForThis = nextIndex;+ try {+ await uploadChunk(sessionId, indexForThis, head.blob);+ queue.shift();+ nextIndex++;+ lastErrorObj = null;+ onProgress({ uploaded: indexForThis, backlog: queue.length });+ } catch (e) {+ head.attempts = (head.attempts || 0) + 1;+ lastErrorObj = e;++ // 409 out-of-order: re-sync nextIndex from the server's+ // expected value, drop chunks already on disk, and retry.+ if (e.status === 409 && Number.isInteger(e.expectedChunkIndex)) {+ const expected = e.expectedChunkIndex;+ // If the server expects an index we already passed,+ // assume the server got the chunk and we lost the+ // response. Drop the head and resume.+ if (expected > indexForThis) {+ queue.shift();+ nextIndex = expected;+ continue;+ }+ // Otherwise the server expects fewer than we have;+ // realign nextIndex and retry.+ nextIndex = expected;+ continue;+ }++ if (head.attempts >= maxAttempts) {+ // Give up on this chunk; surface the error so the+ // caller can decide (typically: pause recording and+ // surface a banner).+ onError({+ error: e,+ chunkIndex: indexForThis,+ droppedFromQueue: true,+ });+ queue.shift();+ nextIndex++;+ continue;+ }++ onError({ error: e, chunkIndex: indexForThis, droppedFromQueue: false });+ await sleep(backoff(head.attempts));+ }+ }+ } finally {+ pumpRunning = false;+ const resolvers = drainResolvers;+ drainResolvers = [];+ resolvers.forEach(r => r());+ }+ }++ return {+ enqueue(blob) {+ queue.push({ blob, attempts: 0 });+ // Fire-and-forget pump+ pump();+ },+ drain() {+ if (queue.length === 0 && !pumpRunning) return Promise.resolve();+ return new Promise(resolve => { drainResolvers.push(resolve); });+ },+ getBacklog() { return queue.length; },+ lastError() { return lastErrorObj; },+ sessionId,+ };+}diff --git a/static/js/modules/db/server-recording-sessions.test.js b/static/js/modules/db/server-recording-sessions.test.jsnew file mode 100644index 00000000..c0166fd4--- /dev/null+++ b/static/js/modules/db/server-recording-sessions.test.js@@ -0,0 +1,228 @@+/**+ * Vitest tests for the server-recording-session client (#287 c/d Phase B).+ *+ * The interesting code is the uploader queue's retry + ordering semantics.+ * The HTTP wrappers themselves are thin; we exercise them via a fetch mock.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import {+ createSession,+ uploadChunk,+ finalizeSession,+ abortSession,+ createUploader,+ getRememberedSession,+} from './server-recording-sessions.js';+++function _installFetchMock(responses) {+ // responses: array of { status, body } -- consumed in order+ let i = 0;+ return vi.fn(async () => {+ const r = responses[i++] ?? responses[responses.length - 1];+ const status = r.status ?? 200;+ return {+ status,+ ok: status >= 200 && status < 300,+ json: async () => r.body ?? null,+ };+ });+}+++function _installDOM() {+ // Provide just enough of document + localStorage for the module.+ const meta = { getAttribute: (k) => (k === 'content' ? 'csrf-test-token' : null) };+ global.document = { querySelector: () => meta };+ const store = new Map();+ global.localStorage = {+ getItem: (k) => (store.has(k) ? store.get(k) : null),+ setItem: (k, v) => store.set(k, String(v)),+ removeItem: (k) => store.delete(k),+ clear: () => store.clear(),+ };+}+++describe('createSession', () => {+ beforeEach(() => { _installDOM(); });+ afterEach(() => { vi.restoreAllMocks(); delete global.fetch; });++ it('POSTs to /upload/session with csrf header and remembers the session', async () => {+ global.fetch = _installFetchMock([{+ status: 201,+ body: { session_id: 'abc-123', mime_type: 'audio/webm', max_chunk_bytes: 16 * 1024 * 1024 },+ }]);++ const res = await createSession('audio/webm');+ expect(res.session_id).toBe('abc-123');++ const call = global.fetch.mock.calls[0];+ expect(call[0]).toBe('/upload/session');+ expect(call[1].method).toBe('POST');+ expect(call[1].headers['X-CSRFToken']).toBe('csrf-test-token');+ expect(call[1].credentials).toBe('same-origin');+ expect(JSON.parse(call[1].body)).toEqual({ mime_type: 'audio/webm' });++ // Remembered for resume-on-reload+ const remembered = getRememberedSession();+ expect(remembered.session_id).toBe('abc-123');+ });++ it('throws with a useful message on non-201 response', async () => {+ global.fetch = _installFetchMock([{ status: 400, body: { error: 'Unsupported mime_type' } }]);+ await expect(createSession('video/h264')).rejects.toThrow(/Unsupported mime_type/);+ });+});+++describe('uploadChunk', () => {+ beforeEach(() => { _installDOM(); });+ afterEach(() => { vi.restoreAllMocks(); delete global.fetch; });++ it('returns {ok:true} on 204', async () => {+ global.fetch = _installFetchMock([{ status: 204, body: null }]);+ const result = await uploadChunk('s-1', 1, new Uint8Array([1, 2, 3]));+ expect(result).toEqual({ ok: true });+ });++ it('throws with expectedChunkIndex on 409', async () => {+ global.fetch = _installFetchMock([{+ status: 409,+ body: { error: 'Out-of-order chunk', expected_chunk_index: 3, got: 5 },+ }]);+ try {+ await uploadChunk('s-1', 5, new Uint8Array([1]));+ expect.fail('should have thrown');+ } catch (e) {+ expect(e.status).toBe(409);+ expect(e.expectedChunkIndex).toBe(3);+ }+ });++ it('throws on 500', async () => {+ global.fetch = _installFetchMock([{ status: 500, body: { error: 'server boom' } }]);+ await expect(uploadChunk('s-1', 1, new Uint8Array([1]))).rejects.toThrow(/server boom/);+ });+});+++describe('finalizeSession', () => {+ beforeEach(() => { _installDOM(); });+ afterEach(() => { vi.restoreAllMocks(); delete global.fetch; });++ it('forgets the remembered session on 202 success', async () => {+ global.fetch = _installFetchMock([+ { status: 201, body: { session_id: 'fin-1', mime_type: 'audio/webm', max_chunk_bytes: 1 } },+ { status: 202, body: { recording_id: 42, status: 'finalizing' } },+ ]);+ await createSession('audio/webm');+ expect(getRememberedSession().session_id).toBe('fin-1');+ const result = await finalizeSession('fin-1', { title: 't' });+ expect(result.recording_id).toBe(42);+ expect(getRememberedSession()).toBeNull();+ });++ it('throws on non-202 response', async () => {+ global.fetch = _installFetchMock([{ status: 409, body: { error: 'No chunks uploaded yet' } }]);+ await expect(finalizeSession('x', {})).rejects.toThrow(/No chunks uploaded/);+ });+});+++describe('abortSession', () => {+ beforeEach(() => { _installDOM(); });+ afterEach(() => { vi.restoreAllMocks(); delete global.fetch; });++ it('returns {ok:true} on 204', async () => {+ global.fetch = _installFetchMock([{ status: 204, body: null }]);+ const r = await abortSession('abort-1');+ expect(r).toEqual({ ok: true });+ });++ it('returns {ok:true} on 404 (already gone)', async () => {+ global.fetch = _installFetchMock([{ status: 404, body: null }]);+ const r = await abortSession('gone-1');+ expect(r).toEqual({ ok: true });+ });+});+++describe('createUploader queue', () => {+ beforeEach(() => { _installDOM(); });+ afterEach(() => { vi.restoreAllMocks(); delete global.fetch; });++ it('uploads chunks in order with monotonic index', async () => {+ global.fetch = _installFetchMock([+ { status: 204 }, { status: 204 }, { status: 204 },+ ]);+ const uploader = createUploader('sid');+ uploader.enqueue(new Uint8Array([1]));+ uploader.enqueue(new Uint8Array([2]));+ uploader.enqueue(new Uint8Array([3]));+ await uploader.drain();+ expect(uploader.getBacklog()).toBe(0);+ // Verify the URLs (in order) include the right index+ const urls = global.fetch.mock.calls.map(c => c[0]);+ expect(urls).toEqual([+ '/upload/session/sid/chunks/1',+ '/upload/session/sid/chunks/2',+ '/upload/session/sid/chunks/3',+ ]);+ });++ it('retries with backoff on 500 then succeeds', async () => {+ global.fetch = _installFetchMock([+ { status: 500, body: { error: 'transient' } },+ { status: 500, body: { error: 'transient' } },+ { status: 204 },+ ]);+ const errors = [];+ const uploader = createUploader('sid', {+ baseDelayMs: 1,+ maxDelayMs: 2,+ onError: (info) => errors.push(info),+ });+ uploader.enqueue(new Uint8Array([1]));+ await uploader.drain();+ expect(uploader.getBacklog()).toBe(0);+ expect(global.fetch.mock.calls).toHaveLength(3);+ expect(errors.filter(e => !e.droppedFromQueue)).toHaveLength(2);+ });++ it('drops a chunk after maxAttempts', async () => {+ global.fetch = _installFetchMock(+ new Array(10).fill({ status: 500, body: { error: 'down' } })+ );+ const errors = [];+ const uploader = createUploader('sid', {+ maxAttempts: 3,+ baseDelayMs: 1,+ maxDelayMs: 1,+ onError: (info) => errors.push(info),+ });+ uploader.enqueue(new Uint8Array([1]));+ await uploader.drain();+ expect(uploader.getBacklog()).toBe(0);+ const dropped = errors.filter(e => e.droppedFromQueue);+ expect(dropped).toHaveLength(1);+ });++ it('resyncs nextIndex on 409 (server expects different index)', async () => {+ // Simulate: client sends chunk 1, server says "I already have 2,+ // give me 3". The uploader should skip the locally-staged chunk and+ // advance nextIndex to 3, then continue.+ global.fetch = _installFetchMock([+ { status: 409, body: { error: 'out of order', expected_chunk_index: 3 } },+ { status: 204 },+ ]);+ const uploader = createUploader('sid', { baseDelayMs: 1, maxDelayMs: 1 });+ uploader.enqueue(new Uint8Array([1]));+ uploader.enqueue(new Uint8Array([2]));+ await uploader.drain();+ // After the resync, the second enqueued chunk was sent as index 3+ const urls = global.fetch.mock.calls.map(c => c[0]);+ expect(urls[urls.length - 1]).toBe('/upload/session/sid/chunks/3');+ });+});diff --git a/templates/index.html b/templates/index.htmlindex 593e4b59..c1a02ba8 100644--- a/templates/index.html+++ b/templates/index.html@@ -56,6 +56,7 @@data-user-language="{{ user_language }}"data-show-timestamps-simple-view="{{ 'True' if (current_user.is_authenticated and current_user.show_timestamps_simple_view) else 'False' }}"data-editor-autosave="{{ 'True' if (current_user.is_authenticated and current_user.editor_autosave) else 'False' }}"+ data-server-recording-chunks="{{ 'True' if server_recording_chunks_enabled else 'False' }}"class="h-full flex flex-col opacity-0 transition-opacity duration-500"><!-- Header -->