Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Make recording-session finalize idempotent (atomic claim + replay returns the same recording) and give the Upload button an immediate disabled/spinner state so double-clicks can't mint duplicate recordings; sweep orphaned session dirs in cleanup

Murtaza Nasirbdb6a687ffbe
diff --git a/src/api/recording_sessions.py b/src/api/recording_sessions.py
index 7a4db83d..0c6f6326 100644
--- a/src/api/recording_sessions.py
+++ b/src/api/recording_sessions.py
@@ -163,8 +163,25 @@ def _finalize_session_into_stitch(session, *, user_id, title, notes=None,
endpoint and the abandoned-session auto-finalize in cleanup, so the two
behave identically (same Recording shape, same job, same downstream
transcription kickoff). Returns ``(recording, enqueue_error)`` where
- ``enqueue_error`` is ``None`` on success.
+ ``enqueue_error`` is ``None`` on success, or ``(None, None)`` when the
+ session was not in ``recording`` status at claim time — i.e. a concurrent
+ finalize won the race and the caller should replay its result instead.
"""
+ # Atomically claim the session (recording -> finalizing). Concurrent
+ # finalize calls — a double-clicked Upload button whose requests all
+ # fire the moment the chunk drain completes — must not each mint a
+ # Recording: before this claim, three clicks created three rows racing
+ # to stitch the same session, and every row except the one the session
+ # ended up pointing at was orphaned in PROCESSING forever (no audio, no
+ # transcribe job, since both key off session.finalized_recording_id).
+ claimed = db.session.query(RecordingSession).filter(
+ RecordingSession.id == session.id,
+ RecordingSession.status == 'recording',
+ ).update({'status': 'finalizing'}, synchronize_session=False)
+ if not claimed:
+ db.session.rollback()
+ return None, None
+
recording = Recording(
user_id=user_id,
title=(title or 'Recording')[:200],
@@ -202,6 +219,43 @@ def _finalize_session_into_stitch(session, *, user_id, title, notes=None,
return recording, e
+def _replay_finalize_response(session):
+ """Idempotent response for finalize on an already-finalizing session.
+
+ Duplicate finalize calls (a double-clicked Upload button, a network
+ retry) return the recording created by the first call instead of
+ minting another one. If the first call's stitch enqueue failed, this is
+ also the retry path: re-enqueue for the SAME recording — enqueue dedupes
+ an already-active (recording, job_type) pair, so replays are safe.
+ """
+ existing = (db.session.get(Recording, session.finalized_recording_id)
+ if session.finalized_recording_id else None)
+ if existing is None or existing.user_id != current_user.id:
+ return jsonify({'error': 'Session was already finalized and its recording no longer exists'}), 409
+
+ if existing.status == 'STITCHING':
+ try:
+ job_queue.enqueue(
+ user_id=current_user.id,
+ recording_id=existing.id,
+ job_type='stitch',
+ params={'session_id': session.id},
+ is_new_upload=True,
+ )
+ except Exception as e:
+ current_app.logger.error(f"Could not re-enqueue stitch job for session {session.id}: {e}")
+ return jsonify({
+ 'recording_id': existing.id,
+ 'status': session.status,
+ 'queue_error': str(e),
+ }), 500
+
+ return jsonify({
+ 'recording_id': existing.id,
+ 'status': session.status,
+ }), 202
+
+
# --- Endpoints --------------------------------------------------------------
@recording_sessions_bp.route('/upload/session', methods=['POST'])
@@ -389,6 +443,12 @@ def finalize_session(session_id):
'error': f'Session is in status {session.status!r}; cannot finalize',
}), 409
+ # Idempotent replay: the session is already finalizing, so a recording
+ # exists (or its enqueue needs retrying). Return that same recording
+ # instead of creating another — see _replay_finalize_response.
+ if session.status == 'finalizing':
+ return _replay_finalize_response(session)
+
if session.chunk_count <= 0:
return jsonify({'error': 'No chunks uploaded yet'}), 409
@@ -439,6 +499,15 @@ def finalize_session(session_id):
resolved_folder_id=resolved_folder_id,
metadata=metadata,
)
+ if recording is None:
+ # Lost the atomic claim: a concurrent finalize committed first.
+ # Re-read the session and replay that call's recording.
+ db.session.expire_all()
+ session = db.session.get(RecordingSession, session_id)
+ err = _ensure_owned(session)
+ if err is not None:
+ return err
+ return _replay_finalize_response(session)
if enqueue_error is not None:
# Leave the session in `finalizing` so the client can retry; the
# placeholder recording stays in STITCHING so the user can see it.
@@ -518,10 +587,14 @@ def cleanup_expired_sessions(app=None):
if s.status == 'recording' and (s.chunk_count or 0) > 0:
when = s.created_at.strftime('%Y-%m-%d %H:%M') if s.created_at else ''
title = f"Recovered recording {when}".strip()
- _finalize_session_into_stitch(
+ recovered_rec, _enq_err = _finalize_session_into_stitch(
s, user_id=s.user_id, title=title,
metadata={'recovered': True},
)
+ if recovered_rec is None:
+ # A concurrent finalize claimed this session between
+ # the candidate query and now — nothing to do.
+ continue
finalized += 1
app.logger.info(
f"Auto-finalized abandoned recording session {s.id} "
@@ -553,10 +626,35 @@ def cleanup_expired_sessions(app=None):
app.logger.error(f"Cleanup failed for session {s.id}: {e}", exc_info=True)
db.session.rollback()
- total = finalized + rekicked + expired
+ # Orphaned directories: a session dir whose DB row no longer exists
+ # (wiped dev database, manual row deletion) is invisible to the
+ # row-driven sweep above and lingers forever. Remove any directory
+ # older than the TTL that has no matching RecordingSession row.
+ orphans = 0
+ try:
+ root = _session_root()
+ if os.path.isdir(root):
+ cutoff_ts = cutoff.timestamp()
+ for name in os.listdir(root):
+ path = os.path.join(root, name)
+ if not os.path.isdir(path):
+ continue
+ try:
+ if os.path.getmtime(path) >= cutoff_ts:
+ continue
+ except OSError:
+ continue
+ if db.session.get(RecordingSession, name) is None:
+ _remove_session_dir(name, app)
+ orphans += 1
+ except Exception as e:
+ app.logger.warning(f"Orphaned session-dir sweep failed: {e}")
+
+ total = finalized + rekicked + expired + orphans
if total:
app.logger.info(
f"Recording-session cleanup: {finalized} auto-finalized, "
- f"{rekicked} re-enqueued, {expired} expired"
+ f"{rekicked} re-enqueued, {expired} expired, "
+ f"{orphans} orphaned dir(s) removed"
)
return total
diff --git a/static/js/app.modular.js b/static/js/app.modular.js
index b4e7812f..f76de772 100644
--- a/static/js/app.modular.js
+++ b/static/js/app.modular.js
@@ -536,6 +536,13 @@ document.addEventListener('DOMContentLoaded', async () => {
// size-limit warning UI, which is meaningless when streaming
// (#332: there is no size cap in that mode, only an hours cap).
const isServerStreamedRecording = ref(false);
+ // True from the moment the user clicks Upload on a finished
+ // recording until the finalize (or legacy queue hand-off)
+ // resolves. Drives the button's disabled/spinner state and the
+ // re-entrancy guard in uploadRecordedAudio: draining the chunk
+ // backlog can take many seconds, and without immediate feedback
+ // users double-click — which used to create duplicate recordings.
+ const isFinalizingRecording = ref(false);
// Advanced Options for ASR
const showAdvancedOptions = ref(false);
@@ -1647,7 +1654,7 @@ document.addEventListener('DOMContentLoaded', async () => {
systemVisualizer, animationFrameId, recordingMode, activeStreams,
wakeLock, recordingNotification, isPageVisible,
estimatedFileSize, fileSizeWarningShown, recordingQuality, actualBitrate,
- maxRecordingMB, sizeCheckInterval, isServerStreamedRecording,
+ maxRecordingMB, sizeCheckInterval, isServerStreamedRecording, isFinalizingRecording,
// PWA Features
deferredInstallPrompt, showInstallButton, isPWAInstalled,
diff --git a/static/js/modules/composables/audio.js b/static/js/modules/composables/audio.js
index 12c72b61..e788ec58 100644
--- a/static/js/modules/composables/audio.js
+++ b/static/js/modules/composables/audio.js
@@ -12,7 +12,7 @@ export function useAudio(state, utils) {
isRecording, mediaRecorder, audioContext, analyser, micAnalyser, systemAnalyser,
audioChunks, recordingTime, recordingInterval, recordingMode, audioBlobURL,
estimatedFileSize, actualBitrate, recordingNotes, recordingQuality,
- maxRecordingMB, fileSizeWarningShown, sizeCheckInterval, isServerStreamedRecording, recordingDisclaimer,
+ maxRecordingMB, fileSizeWarningShown, sizeCheckInterval, isServerStreamedRecording, isFinalizingRecording, recordingDisclaimer,
showRecordingDisclaimerModal, pendingRecordingMode, currentView, showUploadModal, showSystemAudioHelp, disableAudioProcessing,
recordSystemVideo, recordingVideoActive, videoRetentionEnabled,
selectedMicDeviceId, selectedSecondaryDeviceId,
@@ -957,8 +957,9 @@ export function useAudio(state, utils) {
}
};
- // Upload recorded audio
- const uploadRecordedAudio = async (opts = {}) => {
+ // Upload recorded audio (inner implementation — call uploadRecordedAudio,
+ // which adds the re-entrancy guard and button state around this).
+ const _uploadRecordedAudioInner = async (opts = {}) => {
if (!audioBlobURL.value) {
setGlobalError("No recorded audio to upload.");
return;
@@ -1107,6 +1108,27 @@ export function useAudio(state, utils) {
}
};
+ // Public entry point: re-entrancy guard + button state around the inner
+ // upload. Draining the chunk backlog before finalize can take many
+ // seconds with no other visible change, so users double-click — and
+ // every extra call used to send another finalize for the same session,
+ // minting duplicate recordings. The server is idempotent about replayed
+ // finalizes now, but the first line of defense is not sending them:
+ // ignore clicks while one upload is in flight and let the template
+ // disable the buttons via isFinalizingRecording.
+ const uploadRecordedAudio = async (opts = {}) => {
+ if (isFinalizingRecording && isFinalizingRecording.value) {
+ console.log('[Recording] Upload already in progress; ignoring duplicate request');
+ return;
+ }
+ if (isFinalizingRecording) isFinalizingRecording.value = true;
+ try {
+ return await _uploadRecordedAudioInner(opts);
+ } finally {
+ if (isFinalizingRecording) isFinalizingRecording.value = false;
+ }
+ };
+
// Split-button action: open the merge modal in "recording" mode BEFORE
// finalizing, so the user picks which existing recording(s) to merge this
// clip into and in what order. On confirm the modal calls
diff --git a/static/locales/de.json b/static/locales/de.json
index b3679586..9a58ee06 100644
--- a/static/locales/de.json
+++ b/static/locales/de.json
@@ -1019,6 +1019,7 @@
"unsupportedBrowser": "Nicht unterstützter Browser",
"untitled": "Unbenannte Aufnahme",
"uploadRecordingNotes": "Aufnahme und Notizen hochladen",
+ "uploadingRecording": "Aufnahme wird hochgeladen…",
"whatWillHappen": "Was wird passieren?",
"whyNotWorking": "Warum funktioniert es nicht?",
"youHaveXSpeakers": "Sie haben {{count}} Sprecher, aber nur 16 eindeutige Farben sind verfügbar. Die Farben wiederholen sich nach dem 16. Sprecher."
diff --git a/static/locales/en.json b/static/locales/en.json
index fa13fe47..3ed209df 100644
--- a/static/locales/en.json
+++ b/static/locales/en.json
@@ -1019,6 +1019,7 @@
"unsupportedBrowser": "Unsupported Browser",
"untitled": "Untitled Recording",
"uploadRecordingNotes": "Upload Recording & Notes",
+ "uploadingRecording": "Uploading recording…",
"whatWillHappen": "What will happen?",
"whyNotWorking": "Why isn't it working?",
"youHaveXSpeakers": "You have {{count}} speakers, but only 16 unique colors are available. Colors will repeat after the 16th speaker."
diff --git a/static/locales/es.json b/static/locales/es.json
index 7c9cac9c..3303d2c6 100644
--- a/static/locales/es.json
+++ b/static/locales/es.json
@@ -1019,6 +1019,7 @@
"unsupportedBrowser": "Navegador No Soportado",
"untitled": "Grabación Sin Título",
"uploadRecordingNotes": "Subir Grabación y Notas",
+ "uploadingRecording": "Subiendo la grabación…",
"whatWillHappen": "¿Qué pasará?",
"whyNotWorking": "¿Por qué no funciona?",
"youHaveXSpeakers": "Tiene {{count}} oradores, pero solo hay 16 colores únicos disponibles. Los colores se repetirán después del decimosexto orador."
diff --git a/static/locales/fr.json b/static/locales/fr.json
index 87d009b1..4d20b83c 100644
--- a/static/locales/fr.json
+++ b/static/locales/fr.json
@@ -1019,6 +1019,7 @@
"unsupportedBrowser": "Navigateur Non Pris en Charge",
"untitled": "Enregistrement Sans Titre",
"uploadRecordingNotes": "Télécharger l'Enregistrement et les Notes",
+ "uploadingRecording": "Envoi de l'enregistrement…",
"whatWillHappen": "Que va-t-il se passer?",
"whyNotWorking": "Pourquoi ça ne marche pas?",
"youHaveXSpeakers": "Vous avez {{count}} locuteurs, mais seulement 16 couleurs uniques sont disponibles. Les couleurs se répéteront après le 16ème locuteur."
diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.json
index 2a1d2b59..ba4366f7 100644
--- a/static/locales/pt-BR.json
+++ b/static/locales/pt-BR.json
@@ -1019,6 +1019,7 @@
"unsupportedBrowser": "Navegador Não Suportado",
"untitled": "Gravação Sem Título",
"uploadRecordingNotes": "Enviar Gravação e Notas",
+ "uploadingRecording": "Enviando a gravação…",
"whatWillHappen": "O que acontecerá?",
"whyNotWorking": "Por que não está funcionando?",
"youHaveXSpeakers": "Você tem {{count}} oradores, mas apenas 16 cores únicas estão disponíveis. As cores se repetirão após o 16º orador."
diff --git a/static/locales/ru.json b/static/locales/ru.json
index e1374917..28c215e7 100644
--- a/static/locales/ru.json
+++ b/static/locales/ru.json
@@ -1019,6 +1019,7 @@
"unsupportedBrowser": "Неподдерживаемый браузер",
"untitled": "Запись без названия",
"uploadRecordingNotes": "Загрузить запись и заметки",
+ "uploadingRecording": "Загрузка записи…",
"whatWillHappen": "Что произойдёт?",
"whyNotWorking": "Почему не работает?",
"youHaveXSpeakers": "У вас {{count}} спикеров, но доступно только 16 уникальных цветов. Цвета будут повторяться после 16-го спикера."
diff --git a/static/locales/zh.json b/static/locales/zh.json
index 9253eaae..408349e8 100644
--- a/static/locales/zh.json
+++ b/static/locales/zh.json
@@ -1019,6 +1019,7 @@
"unsupportedBrowser": "不支持的浏览器",
"untitled": "无标题录音",
"uploadRecordingNotes": "上传录音和笔记",
+ "uploadingRecording": "正在上传录音…",
"whatWillHappen": "会发生什么?",
"whyNotWorking": "为什么不工作?",
"youHaveXSpeakers": "您有 {{count}} 位发言人,但只有16种独特的颜色可用。颜色将在第16位发言人之后重复。"
diff --git a/templates/components/recording-view.html b/templates/components/recording-view.html
index a83dd647..188af6f6 100644
--- a/templates/components/recording-view.html
+++ b/templates/components/recording-view.html
@@ -402,13 +402,19 @@
<div v-if="!isRecording && audioBlobURL" class="flex flex-col sm:flex-row gap-3 justify-center">
<!-- Normal Upload Button (split: main uploads, caret opens options) -->
<div v-if="!incognitoMode || !enableIncognitoMode" class="flex-1 flex relative">
+ <!-- Disabled + spinner while finalizing: draining the chunk
+ backlog can take many seconds, and without immediate
+ feedback users double-click (which used to create
+ duplicate recordings). -->
<button @click="uploadRecordedAudio"
- class="flex-1 px-6 py-3 bg-[var(--bg-button)] text-[var(--text-button)] rounded-l-lg hover:bg-[var(--bg-button-hover)] transition-colors flex items-center justify-center gap-2">
- <i class="fas fa-upload"></i>
- <span v-text="t('help.uploadRecordingNotes')"></span>
+ :disabled="isFinalizingRecording"
+ class="flex-1 px-6 py-3 bg-[var(--bg-button)] text-[var(--text-button)] rounded-l-lg hover:bg-[var(--bg-button-hover)] disabled:opacity-60 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2">
+ <i :class="isFinalizingRecording ? 'fas fa-spinner fa-spin' : 'fas fa-upload'"></i>
+ <span v-text="isFinalizingRecording ? t('help.uploadingRecording') : t('help.uploadRecordingNotes')"></span>
</button>
<button @click="showUploadSplitMenu = !showUploadSplitMenu"
- class="px-3 bg-[var(--bg-button)] text-[var(--text-button)] rounded-r-lg hover:bg-[var(--bg-button-hover)] transition-colors border-l border-white/25 flex items-center justify-center"
+ :disabled="isFinalizingRecording"
+ class="px-3 bg-[var(--bg-button)] text-[var(--text-button)] rounded-r-lg hover:bg-[var(--bg-button-hover)] disabled:opacity-60 disabled:cursor-not-allowed transition-colors border-l border-white/25 flex items-center justify-center"
:title="t('mergeRecordings.moreOptions')">
<i class="fas fa-chevron-down text-xs"></i>
</button>
@@ -435,7 +441,8 @@
<span v-else>Process in Incognito</span>
</button>
<button @click="discardRecording"
- class="px-6 py-3 bg-[var(--bg-danger)] text-white rounded-lg hover:bg-[var(--bg-danger-hover)] transition-colors flex items-center justify-center gap-2">
+ :disabled="isFinalizingRecording"
+ class="px-6 py-3 bg-[var(--bg-danger)] text-white rounded-lg hover:bg-[var(--bg-danger-hover)] disabled:opacity-60 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2">
<i class="fas fa-trash"></i>
<span v-text="t('help.discard')"></span>
</button>
diff --git a/tests/test_recording_sessions.py b/tests/test_recording_sessions.py
index cb44afa3..66ee171f 100644
--- a/tests/test_recording_sessions.py
+++ b/tests/test_recording_sessions.py
@@ -253,6 +253,61 @@ def test_finalize_creates_recording_and_enqueues_stitch_job():
shutil.rmtree(upload_folder, ignore_errors=True)
+def test_finalize_is_idempotent_under_duplicate_calls():
+ """A double-clicked Upload button (or a network retry) replays finalize
+ on a session that is already finalizing. Every replay must return the
+ SAME recording_id, and exactly one Recording row may exist — before this
+ guard, each replay minted another placeholder Recording racing over the
+ same session's chunks, and all but the last were orphaned in PROCESSING
+ forever (observed live on 2026-07-14 with a triple-clicked upload)."""
+ upload_folder = _make_tmp_upload_folder()
+ with app.app_context():
+ app.config["UPLOAD_FOLDER"] = upload_folder
+ user = _setup_user("sess_dup")
+ client = app.test_client()
+ _login(client, user)
+ sid = client.post("/upload/session", json={"mime_type": "audio/webm"}).get_json()["session_id"]
+ client.post(f"/upload/session/{sid}/chunks/1", data=b"\x00" * 100, content_type="application/octet-stream")
+
+ enqueue_calls = []
+
+ def fake_enqueue(*args, **kwargs):
+ enqueue_calls.append(kwargs)
+ return 999
+
+ with patch("src.services.job_queue.job_queue.enqueue", side_effect=fake_enqueue):
+ first = client.post(f"/upload/session/{sid}/finalize", json={"title": "Dup test"})
+ second = client.post(f"/upload/session/{sid}/finalize", json={"title": "Dup test"})
+ third = client.post(f"/upload/session/{sid}/finalize", json={"title": "Dup test"})
+
+ assert first.status_code == 202, first.data
+ assert second.status_code == 202, second.data
+ assert third.status_code == 202, third.data
+ rid = first.get_json()["recording_id"]
+ assert second.get_json()["recording_id"] == rid
+ assert third.get_json()["recording_id"] == rid
+
+ # Exactly ONE Recording row was created for this session
+ session_row = db.session.get(RecordingSession, sid)
+ assert session_row.finalized_recording_id == rid
+ rows = Recording.query.filter_by(user_id=user.id).all()
+ assert len(rows) == 1 and rows[0].id == rid
+
+ # Replays may re-enqueue the stitch (enqueue dedupes an active job),
+ # but always for the SAME recording id.
+ assert {c.get("recording_id") for c in enqueue_calls} == {rid}
+ assert all(c.get("job_type") == "stitch" for c in enqueue_calls)
+
+ # Cleanup
+ session_row.status = 'aborted'
+ db.session.commit()
+ client.delete(f"/upload/session/{sid}")
+ db.session.delete(rows[0])
+ db.session.delete(user)
+ db.session.commit()
+ shutil.rmtree(upload_folder, ignore_errors=True)
+
+
def test_finalize_rejects_finalizing_into_other_users_personal_folder():
"""IDOR regression. Without folder-access validation in finalize,
user A could submit a personal folder_id belonging to user B and the