Skip to content

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

Python

Route the merge-from-recording flow through a merge intent so the stitched clip goes straight into the merge, eliminating its standalone transcription

Murtaza Nasird801a8f31a2b
diff --git a/src/services/recording_merge.py b/src/services/recording_merge.py
index c72f8cfb..8ab5e463 100644
--- a/src/services/recording_merge.py
+++ b/src/services/recording_merge.py
@@ -93,9 +93,17 @@ def _concat_audio(input_paths: list, output_path: str) -> None:
_run_ffmpeg_command(cmd, f"merge concat of {len(input_paths)} recordings")
-def _validate_sources(user, recording_ids, storage):
+def _validate_sources(user, recording_ids, storage, require_settled=True):
"""Validate the requested sources and return them in caller order.
+ ``require_settled`` gates the "must be a settled/COMPLETED recording" check.
+ User-initiated merges keep it on (a source mid-processing could still have
+ its audio_path mutated by video->audio extraction). Trusted internal callers
+ that just produced the audio themselves — the recording-session stitch that
+ routes straight into a merge — pass False, since the audio is final the
+ moment the stitch finishes even though the recording is not COMPLETED. The
+ ownership and audio-existence checks always apply.
+
Raises MergeError on any problem. Returns the list of Recording rows.
"""
if not recording_ids or len(recording_ids) < 2:
@@ -115,7 +123,7 @@ def _validate_sources(user, recording_ids, storage):
rec = db.session.get(Recording, rid)
if not rec or rec.user_id != user.id:
raise MergeError("One or more recordings were not found.")
- if rec.status not in _STABLE_STATUSES:
+ if require_settled and rec.status not in _STABLE_STATUSES:
raise MergeError(
f"\"{rec.title or 'A recording'}\" is still processing. "
"Wait for it to finish before merging."
@@ -129,17 +137,19 @@ def _validate_sources(user, recording_ids, storage):
return recordings
-def create_merge_recording(user, recording_ids, title=None, delete_originals=False):
+def create_merge_recording(user, recording_ids, title=None, delete_originals=False,
+ require_settled=True):
"""Validate sources and create a placeholder recording queued for merging.
- Runs in the request. Does NO ffmpeg — the heavy concat happens later in
- ``run_merge_job`` on a worker. Returns the new (PROCESSING) Recording.
+ Runs in the request (or, with ``require_settled=False``, from the stitch
+ worker for the merge-from-recording flow). Does NO ffmpeg — the heavy concat
+ happens later in ``run_merge_job``. Returns the new (QUEUED) Recording.
Raises:
MergeError: on validation failure.
"""
storage = get_storage_service()
- recordings = _validate_sources(user, recording_ids, storage)
+ recordings = _validate_sources(user, recording_ids, storage, require_settled=require_settled)
ordered_ids = [r.id for r in recordings]
first = recordings[0]
diff --git a/src/services/recording_stitch.py b/src/services/recording_stitch.py
index 0badd568..086a0083 100644
--- a/src/services/recording_stitch.py
+++ b/src/services/recording_stitch.py
@@ -416,6 +416,71 @@ def stitch_recording_session(session_id: str) -> Tuple[int, str, dict]:
return recording.id, final_path, metadata
+def _try_kickoff_merge(recording, user_id, metadata) -> bool:
+ """If the finalize metadata carries a ``merge_intent``, create the merged
+ recording (this clip + the chosen existing recordings, in the chosen order)
+ and enqueue the merge job, skipping this clip's standalone transcription.
+
+ Returns True when a merge was enqueued, False to fall through to the normal
+ transcribe. Any failure returns False so the clip is transcribed normally
+ rather than left in limbo.
+ """
+ intent = (metadata or {}).get('merge_intent')
+ if not isinstance(intent, dict):
+ return False
+
+ order = intent.get('order')
+ if not isinstance(order, list) or '__self__' not in order:
+ return False
+
+ from flask import current_app
+ from src.database import db
+ from src.models import User
+ from src.services.recording_merge import create_merge_recording, MergeError
+
+ try:
+ # Substitute this clip's real id for the "__self__" placeholder, coercing
+ # the existing ids to ints and dropping anything unusable.
+ source_ids = []
+ for entry in order:
+ if entry == '__self__':
+ source_ids.append(recording.id)
+ else:
+ try:
+ source_ids.append(int(entry))
+ except (TypeError, ValueError):
+ continue
+
+ if len(source_ids) < 2 or recording.id not in source_ids:
+ return False
+
+ user = db.session.get(User, user_id)
+ if not user:
+ return False
+
+ # Trusted path: the clip's audio was just produced by the stitch, so it
+ # is final even though the recording is not COMPLETED (require_settled
+ # off). Ownership + audio-existence are still enforced.
+ create_merge_recording(
+ user,
+ source_ids,
+ title=(intent.get('title') or None),
+ delete_originals=bool(intent.get('delete_originals', False)),
+ require_settled=False,
+ )
+ return True
+ except MergeError as e:
+ current_app.logger.warning(
+ f"Merge-from-recording for {recording.id} failed ({e}); transcribing normally instead."
+ )
+ return False
+ except Exception as e:
+ current_app.logger.error(
+ f"Unexpected error routing recording {recording.id} into a merge: {e}; transcribing normally."
+ )
+ return False
+
+
def kickoff_transcription_for_stitched(
recording_id: int,
user_id: int,
@@ -433,6 +498,15 @@ def kickoff_transcription_for_stitched(
recording = db.session.get(Recording, recording_id)
+ # Merge-from-recording (issue #323): if the user chose to merge this clip
+ # into existing recording(s) BEFORE finishing, route the freshly-stitched
+ # audio straight into a merge instead of transcribing it on its own. The clip
+ # is therefore never transcribed standalone — only the combined recording is,
+ # once. Falls back to a normal transcribe on any problem so the clip is never
+ # left orphaned.
+ if _try_kickoff_merge(recording, user_id, metadata):
+ return
+
overrides = {
'min_speakers': metadata.get('min_speakers'),
'max_speakers': metadata.get('max_speakers'),
diff --git a/static/js/app.modular.js b/static/js/app.modular.js
index be6a2b18..e3cb79a5 100644
--- a/static/js/app.modular.js
+++ b/static/js/app.modular.js
@@ -2408,13 +2408,17 @@ document.addEventListener('DOMContentLoaded', async () => {
showToast,
setGlobalError,
exitSelectionMode: bulkSelectionComposable.exitSelectionMode,
- startReprocessingPoll: reprocessComposable.startReprocessingPoll
+ startReprocessingPoll: reprocessComposable.startReprocessingPoll,
+ t,
+ finalizeRecordingMerge: audioComposable.finalizeRecordingMerge
});
- // Bridge merge-modal opener to the audio composable so the
+ // Bridge merge-modal openers to the audio composable so the
// "merge this recording with an existing one" split-button action in
- // the recording view can seed and open the merge modal after upload.
+ // the recording view can open the merge modal (recording mode) and,
+ // on confirm, finalize the session with the merge intent.
utils.openMergeWith = bulkOperationsComposable.openMergeWith;
+ utils.openMergeForRecording = bulkOperationsComposable.openMergeForRecording;
// =========================================================================
// VIRTUAL SCROLL SETUP (for performance with long transcriptions)
diff --git a/static/js/modules/composables/audio.js b/static/js/modules/composables/audio.js
index 255d937c..520c3c89 100644
--- a/static/js/modules/composables/audio.js
+++ b/static/js/modules/composables/audio.js
@@ -913,11 +913,15 @@ export function useAudio(state, utils) {
};
// Upload recorded audio
- const uploadRecordedAudio = async () => {
+ const uploadRecordedAudio = async (opts = {}) => {
if (!audioBlobURL.value) {
setGlobalError("No recorded audio to upload.");
return;
}
+ // Optional merge intent: when present, the server routes the stitched
+ // clip straight into a merge (no standalone transcription). See
+ // finalizeRecordingMerge / mergeRecordedWithExisting.
+ const mergeIntent = opts.mergeIntent || null;
// Get selected tags as objects and create a DEEP copy to prevent reactivity issues
const selectedTagsTemp = selectedTagIds.value.map(tagId => {
@@ -950,6 +954,9 @@ export function useAudio(state, utils) {
min_speakers: asrMinSpeakers.value || null,
max_speakers: asrMaxSpeakers.value || null,
};
+ if (mergeIntent) {
+ metadata.merge_intent = mergeIntent;
+ }
const result = await ServerSessions.finalizeSession(serverSessionId, metadata);
showToast?.((utils.t && utils.t('toasts.recordingFinalized')) || 'Recording uploaded for processing', 'fa-cloud-upload-alt');
@@ -1055,65 +1062,40 @@ export function useAudio(state, utils) {
}
};
- // Poll a recording until its audio is settled and it is mergeable
- // (COMPLETED), then return its full dict. Used by mergeRecordedWithExisting.
- const _pollUntilMergeable = async (recordingId, { timeoutMs = 15 * 60 * 1000, intervalMs = 3000 } = {}) => {
- const start = Date.now();
- while (Date.now() - start < timeoutMs) {
- try {
- const resp = await fetch(`/recording/${recordingId}/status`);
- if (resp.ok) {
- const s = await resp.json();
- if (s.status === 'COMPLETED' && s.audio_ready !== false) {
- const full = await fetch(`/api/recordings/${recordingId}`);
- return full.ok ? await full.json() : null;
- }
- if (s.status === 'FAILED') return null;
- }
- } catch (_) { /* transient; keep polling */ }
- await new Promise(r => setTimeout(r, intervalMs));
- }
- return null;
- };
-
- // Split-button action: upload the just-recorded clip, then open the merge
- // modal seeded with it so the user can combine it with existing
- // recording(s). The merge service only accepts settled sources, so we upload
- // first and wait for the clip to finish processing before opening the modal.
+ // 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
+ // finalizeRecordingMerge, which finalizes the session carrying that intent —
+ // the server stitches the clip and routes it straight into the merge, so the
+ // clip is never transcribed on its own (only the combined recording is).
const mergeRecordedWithExisting = async () => {
const t = (k, p) => (utils.t ? utils.t(k, p) : k);
if (!audioBlobURL.value) {
setGlobalError(t('mergeRecordings.noClip') || 'No recorded audio to merge.');
return;
}
-
- let result;
- try {
- result = await uploadRecordedAudio();
- } catch (e) {
- setGlobalError(`Upload failed: ${e.message}`);
- return;
- }
-
- const newId = result && result.recording_id;
- if (!newId) {
- // Legacy single-shot path or a failure — the clip uploaded normally
- // but we can't chain a merge automatically.
+ if (!serverSessionId) {
+ // Legacy single-shot recordings have no server session to attach the
+ // intent to. Tell the user to upload and merge from the list.
showToast?.(t('mergeRecordings.uploadedMergeManually'), 'fa-info-circle', 6000);
return;
}
-
- showToast?.(t('mergeRecordings.preparingClip'), 'fa-spinner');
- const rec = await _pollUntilMergeable(newId);
- if (!rec) {
- setGlobalError(t('mergeRecordings.clipNotReady'));
- return;
+ if (utils.openMergeForRecording) {
+ utils.openMergeForRecording();
}
+ };
- if (utils.openMergeWith) {
- // Default to replacing the sources (the chosen behavior for this flow).
- utils.openMergeWith([rec], { deleteOriginals: true });
- }
+ // Called by the merge modal (recording mode) on confirm: finalize the
+ // recording session with the merge intent. `orderedSpec` is the ordered
+ // source list with the string '__self__' marking this clip's position.
+ const finalizeRecordingMerge = async (orderedSpec, { deleteOriginals = true, title = undefined } = {}) => {
+ return uploadRecordedAudio({
+ mergeIntent: {
+ order: orderedSpec,
+ delete_originals: !!deleteOriginals,
+ title: title || undefined,
+ },
+ });
};
// Upload recorded audio in incognito mode
@@ -1496,6 +1478,7 @@ export function useAudio(state, utils) {
normalizeLiveMediaDuration,
uploadRecordedAudio,
mergeRecordedWithExisting,
+ finalizeRecordingMerge,
uploadRecordedAudioIncognito,
acceptRecordingDisclaimer,
cancelRecordingDisclaimer,
diff --git a/static/js/modules/composables/bulk-operations.js b/static/js/modules/composables/bulk-operations.js
index b4554ab9..fb8cac82 100644
--- a/static/js/modules/composables/bulk-operations.js
+++ b/static/js/modules/composables/bulk-operations.js
@@ -16,8 +16,11 @@ export function useBulkOperations({
showToast,
setGlobalError,
exitSelectionMode,
- startReprocessingPoll
+ startReprocessingPoll,
+ t,
+ finalizeRecordingMerge
}) {
+ const _t = (k, fallback) => (typeof t === 'function' ? t(k) : (fallback || k));
// Modal state
const showBulkDeleteModal = ref(false);
const showBulkTagModal = ref(false);
@@ -33,6 +36,11 @@ export function useBulkOperations({
const mergeTitle = ref('');
const mergeDeleteOriginals = ref(false);
const mergeInProgress = ref(false);
+ // 'bulk' = merge existing recordings (POST /api/recordings/merge).
+ // 'recording' = merge a just-recorded clip into existing ones; the list
+ // holds a virtual { __self__: true } entry for the not-yet-uploaded clip and
+ // confirm finalizes the recording session with the merge intent instead.
+ const mergeMode = ref('bulk');
// In-modal "add recording" picker (lets the user append existing recordings
// to the merge from within the modal — used by the normal merge and by the
// merge-from-recording flow that seeds the modal with a just-recorded clip).
@@ -291,9 +299,26 @@ export function useBulkOperations({
const openBulkMergeModal = () => {
// Seed the ordered list from the current selection. Order matters for a
// merge, so present the selection as an explicit, reorderable list.
+ mergeMode.value = 'bulk';
mergeOrderedList.value = selectedRecordings.value.slice();
mergeTitle.value = '';
mergeDeleteOriginals.value = false;
+ mergeAddPickerOpen.value = false;
+ mergeAddSearch.value = '';
+ showBulkMergeModal.value = true;
+ };
+
+ // Open the merge modal for a just-recorded clip that has NOT been uploaded
+ // yet. The list starts with a virtual placeholder for the clip; the user
+ // adds existing recordings to merge it into. Defaults to replacing the
+ // sources (the chosen behavior for this flow).
+ const openMergeForRecording = () => {
+ mergeMode.value = 'recording';
+ mergeOrderedList.value = [{ id: '__self__', __self__: true, title: _t('mergeRecordings.thisRecording', 'This recording') }];
+ mergeTitle.value = '';
+ mergeDeleteOriginals.value = true;
+ mergeAddPickerOpen.value = false;
+ mergeAddSearch.value = '';
showBulkMergeModal.value = true;
};
@@ -307,6 +332,7 @@ export function useBulkOperations({
// Used by the "merge this recording with an existing one" flow (upload view)
// — it seeds the just-recorded clip and defaults to replacing the sources.
const openMergeWith = (seedRecordings, { deleteOriginals = false, title = '' } = {}) => {
+ mergeMode.value = 'bulk';
mergeOrderedList.value = (seedRecordings || []).slice();
mergeTitle.value = title || '';
mergeDeleteOriginals.value = !!deleteOriginals;
@@ -324,6 +350,9 @@ export function useBulkOperations({
};
const removeMergeItem = (index) => {
+ // The virtual clip entry is the anchor of a recording-mode merge and
+ // cannot be removed.
+ if (mergeOrderedList.value[index] && mergeOrderedList.value[index].__self__) return;
const next = mergeOrderedList.value.slice();
next.splice(index, 1);
mergeOrderedList.value = next;
@@ -339,6 +368,28 @@ export function useBulkOperations({
};
const executeBulkMerge = async () => {
+ if (mergeOrderedList.value.length < 2) return;
+
+ // Recording mode: hand off to the recorder, which finalizes the session
+ // carrying the ordered merge intent (with '__self__' marking the clip).
+ // The server routes the stitched clip straight into the merge — no
+ // standalone transcription of the clip.
+ if (mergeMode.value === 'recording') {
+ const orderedSpec = mergeOrderedList.value.map(r => (r.__self__ ? '__self__' : r.id));
+ const hasExisting = orderedSpec.some(x => x !== '__self__');
+ if (!hasExisting || typeof finalizeRecordingMerge !== 'function') return;
+ const title = mergeTitle.value.trim() || undefined;
+ const deleteOriginals = mergeDeleteOriginals.value;
+ closeBulkMergeModal();
+ try {
+ await finalizeRecordingMerge(orderedSpec, { deleteOriginals, title });
+ } catch (error) {
+ console.error('Recording merge finalize error:', error);
+ setGlobalError(`Failed to start merge: ${error.message}`);
+ }
+ return;
+ }
+
const orderedIds = mergeOrderedList.value.map(r => r.id);
if (orderedIds.length < 2) return;
@@ -605,6 +656,7 @@ export function useBulkOperations({
mergeAddPickerOpen,
mergeAddSearch,
mergeCandidates,
+ mergeMode,
// Bulk Delete
openBulkDeleteModal,
@@ -623,6 +675,7 @@ export function useBulkOperations({
// Merge
openBulkMergeModal,
+ openMergeForRecording,
closeBulkMergeModal,
openMergeWith,
addMergeCandidate,
diff --git a/static/locales/de.json b/static/locales/de.json
index 830b26ba..a41d3b45 100644
--- a/static/locales/de.json
+++ b/static/locales/de.json
@@ -1886,6 +1886,7 @@
"noClip": "Keine aufgenommene Audiodatei zum Zusammenführen.",
"uploadedMergeManually": "Ihr Clip wurde hochgeladen. Wählen Sie ihn und eine weitere Aufnahme in der Liste aus, um sie zusammenzuführen.",
"preparingClip": "Ihr Clip wird vorbereitet — die Optionen zum Zusammenführen öffnen sich, sobald er bereit ist.",
- "clipNotReady": "Der Clip konnte nicht zum Zusammenführen vorbereitet werden."
+ "clipNotReady": "Der Clip konnte nicht zum Zusammenführen vorbereitet werden.",
+ "thisRecording": "Diese Aufnahme"
}
}
\ No newline at end of file
diff --git a/static/locales/en.json b/static/locales/en.json
index 88273cdb..b3f1bfd5 100644
--- a/static/locales/en.json
+++ b/static/locales/en.json
@@ -1886,6 +1886,7 @@
"noClip": "No recorded audio to merge.",
"uploadedMergeManually": "Your clip was uploaded. Select it and another recording in the list to merge them.",
"preparingClip": "Preparing your clip — the merge options will open when it's ready.",
- "clipNotReady": "The clip could not be prepared for merging."
+ "clipNotReady": "The clip could not be prepared for merging.",
+ "thisRecording": "This recording"
}
}
\ No newline at end of file
diff --git a/static/locales/es.json b/static/locales/es.json
index 4a02607f..095ad499 100644
--- a/static/locales/es.json
+++ b/static/locales/es.json
@@ -1886,6 +1886,7 @@
"noClip": "No hay audio grabado para combinar.",
"uploadedMergeManually": "Tu clip se ha subido. Selecciónalo junto con otra grabación de la lista para combinarlos.",
"preparingClip": "Preparando tu clip: las opciones de combinación se abrirán cuando esté listo.",
- "clipNotReady": "No se pudo preparar el clip para la combinación."
+ "clipNotReady": "No se pudo preparar el clip para la combinación.",
+ "thisRecording": "Esta grabación"
}
}
\ No newline at end of file
diff --git a/static/locales/fr.json b/static/locales/fr.json
index 8f432e9c..e9f9af3b 100644
--- a/static/locales/fr.json
+++ b/static/locales/fr.json
@@ -1886,6 +1886,7 @@
"noClip": "Aucun audio enregistré à fusionner.",
"uploadedMergeManually": "Votre extrait a été téléversé. Sélectionnez-le ainsi qu'un autre enregistrement de la liste pour les fusionner.",
"preparingClip": "Préparation de votre extrait — les options de fusion s'ouvriront dès qu'il sera prêt.",
- "clipNotReady": "Impossible de préparer l'extrait pour la fusion."
+ "clipNotReady": "Impossible de préparer l'extrait pour la fusion.",
+ "thisRecording": "Cet enregistrement"
}
}
\ No newline at end of file
diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.json
index bd215b62..99b8b850 100644
--- a/static/locales/pt-BR.json
+++ b/static/locales/pt-BR.json
@@ -1886,6 +1886,7 @@
"noClip": "Nenhum áudio gravado para mesclar.",
"uploadedMergeManually": "Seu clipe foi enviado. Selecione-o e outra gravação da lista para mesclá-los.",
"preparingClip": "Preparando seu clipe — as opções de mesclagem abrirão quando estiver pronto.",
- "clipNotReady": "Não foi possível preparar o clipe para a mesclagem."
+ "clipNotReady": "Não foi possível preparar o clipe para a mesclagem.",
+ "thisRecording": "Esta gravação"
}
}
\ No newline at end of file
diff --git a/static/locales/ru.json b/static/locales/ru.json
index 25c757ae..3f355f48 100644
--- a/static/locales/ru.json
+++ b/static/locales/ru.json
@@ -1886,6 +1886,7 @@
"noClip": "Нет записанного звука для объединения.",
"uploadedMergeManually": "Ваш фрагмент загружен. Выберите его и другую запись в списке, чтобы объединить их.",
"preparingClip": "Подготовка фрагмента — параметры объединения откроются, когда он будет готов.",
- "clipNotReady": "Не удалось подготовить фрагмент к объединению."
+ "clipNotReady": "Не удалось подготовить фрагмент к объединению.",
+ "thisRecording": "Эта запись"
}
}
\ No newline at end of file
diff --git a/static/locales/zh.json b/static/locales/zh.json
index 0de392e3..21f55291 100644
--- a/static/locales/zh.json
+++ b/static/locales/zh.json
@@ -1886,6 +1886,7 @@
"noClip": "没有可合并的录音。",
"uploadedMergeManually": "您的片段已上传。请在列表中选择它和另一条录音以进行合并。",
"preparingClip": "正在准备您的片段——准备就绪后将打开合并选项。",
- "clipNotReady": "无法准备该片段以进行合并。"
+ "clipNotReady": "无法准备该片段以进行合并。",
+ "thisRecording": "此录音"
}
}
\ No newline at end of file
diff --git a/templates/modals/bulk-merge-modal.html b/templates/modals/bulk-merge-modal.html
index 3b5008e7..f4f35512 100644
--- a/templates/modals/bulk-merge-modal.html
+++ b/templates/modals/bulk-merge-modal.html
@@ -18,7 +18,10 @@
class="flex items-center gap-3 p-3 rounded-md border border-[var(--border-primary)] bg-[var(--bg-secondary)]">
<span class="flex-shrink-0 w-6 h-6 rounded-full bg-[var(--bg-tertiary)] text-[var(--text-secondary)] text-xs flex items-center justify-center font-medium">${ index + 1 }</span>
<div class="flex-1 min-w-0">
- <div class="t-body-strong truncate">${ rec.title || t('mergeRecordings.untitled') }</div>
+ <div class="t-body-strong truncate flex items-center gap-1.5">
+ <i v-if="rec.__self__" class="fas fa-microphone text-[var(--text-accent)] text-xs"></i>
+ <span class="truncate">${ rec.title || t('mergeRecordings.untitled') }</span>
+ </div>
<div class="t-meta truncate" v-if="rec.meeting_date">${ formatDisplayDate(rec.meeting_date) }</div>
</div>
<div class="flex flex-col gap-0.5 flex-shrink-0">
@@ -33,11 +36,12 @@
<i class="fas fa-chevron-down"></i>
</button>
</div>
- <button @click="removeMergeItem(index)"
+ <button v-if="!rec.__self__" @click="removeMergeItem(index)"
class="flex-shrink-0 w-7 h-7 flex items-center justify-center rounded text-[var(--text-muted)] hover:text-[var(--color-danger,#ef4444)] hover:bg-[var(--bg-tertiary)] transition-colors"
:title="t('mergeRecordings.remove')">
<i class="fas fa-times"></i>
</button>
+ <span v-else class="flex-shrink-0 w-7"></span>
</div>
</div>
diff --git a/tests/test_merge_export_features.py b/tests/test_merge_export_features.py
index 0f237b6b..4a9fa867 100644
--- a/tests/test_merge_export_features.py
+++ b/tests/test_merge_export_features.py
@@ -383,3 +383,66 @@ def test_run_merge_job_empty_output_raises():
patch("src.services.recording_merge.job_queue.enqueue", return_value=1):
with pytest.raises(MergeError):
run_merge_job(merged, {"source_ids": [r1.id, r2.id]})
+
+
+# --------------------------------------------------------------------------- #
+# #323 — Merge-from-recording (stitch straight into a merge, no double transcribe)
+# --------------------------------------------------------------------------- #
+
+def test_create_merge_recording_require_settled_false_accepts_processing_source():
+ from src.services.recording_merge import create_merge_recording, MergeError
+ with app.app_context():
+ user = _mk_user()
+ done = _mk_recording(user, title="Existing", status="COMPLETED")
+ # The freshly-stitched clip is NOT completed yet, but its audio is ready.
+ clip = _mk_recording(user, title="Clip", status="PROCESSING")
+ # With the guard on, the clip is rejected...
+ with _endpoint_mocks():
+ import pytest
+ with pytest.raises(MergeError):
+ create_merge_recording(user, [done.id, clip.id])
+ # ...with require_settled off (trusted stitch path), it is accepted.
+ with _endpoint_mocks() as enqueue:
+ merged = create_merge_recording(user, [done.id, clip.id], require_settled=False)
+ assert merged.processing_source == "merge"
+ assert enqueue.call_args.kwargs["job_type"] == "merge"
+ assert enqueue.call_args.kwargs["params"]["source_ids"] == [done.id, clip.id]
+
+
+def test_try_kickoff_merge_substitutes_self_and_enqueues():
+ from src.services.recording_stitch import _try_kickoff_merge
+ with app.app_context():
+ user = _mk_user()
+ existing = _mk_recording(user, title="Existing", status="COMPLETED")
+ clip = _mk_recording(user, title="Clip", status="PROCESSING") # just stitched
+ metadata = {"merge_intent": {"order": [existing.id, "__self__"], "delete_originals": True, "title": "Combined"}}
+ with _endpoint_mocks() as enqueue:
+ handled = _try_kickoff_merge(clip, user.id, metadata)
+ assert handled is True
+ # A merge job was enqueued with the clip's real id substituted for __self__
+ assert enqueue.call_args.kwargs["job_type"] == "merge"
+ assert enqueue.call_args.kwargs["params"]["source_ids"] == [existing.id, clip.id]
+ assert enqueue.call_args.kwargs["params"]["delete_originals"] is True
+
+
+def test_try_kickoff_merge_no_intent_falls_through():
+ from src.services.recording_stitch import _try_kickoff_merge
+ with app.app_context():
+ user = _mk_user()
+ clip = _mk_recording(user, title="Clip", status="PROCESSING")
+ assert _try_kickoff_merge(clip, user.id, {}) is False
+ # order without the __self__ placeholder is ignored (falls through)
+ assert _try_kickoff_merge(clip, user.id, {"merge_intent": {"order": [1, 2]}}) is False
+
+
+def test_try_kickoff_merge_other_users_source_falls_through():
+ from src.services.recording_stitch import _try_kickoff_merge
+ with app.app_context():
+ me = _mk_user()
+ other = _mk_user()
+ clip = _mk_recording(me, title="Clip", status="PROCESSING")
+ theirs = _mk_recording(other, title="Theirs", status="COMPLETED")
+ metadata = {"merge_intent": {"order": [theirs.id, "__self__"], "delete_originals": True}}
+ with _endpoint_mocks():
+ # create_merge_recording raises MergeError (not owned) -> falls through
+ assert _try_kickoff_merge(clip, me.id, metadata) is False