Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Add markdown transcript export, bulk export of existing recordings to disk, and audio-level recording merge; remove orphaned bulk-action-bar template
Murtaza Nasir7903a2113d95
diff --git a/src/api/recordings.py b/src/api/recordings.pyindex e484ca33..cff24fee 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -337,17 +337,36 @@ def download_transcript_with_template(recording_id):# Join linesformatted_transcript = '\n'.join(output_lines)+ # Output format: 'txt' (default) or 'md'. Markdown wraps the templated+ # body with a title heading so it renders as a proper document, and+ # swaps the extension + content-type. The transcript body itself is the+ # same templated text in both cases (the template lines are valid+ # markdown as-is).+ output_format = (request.args.get('format') or 'txt').lower()+ if output_format not in ('txt', 'md'):+ output_format = 'txt'++ if output_format == 'md':+ title = recording.title or 'Transcript'+ body = f"# {title}\n\n{formatted_transcript}\n"+ response = make_response(body)+ ext = 'md'+ content_type = 'text/markdown; charset=utf-8'+ else:+ response = make_response(formatted_transcript)+ ext = 'txt'+ content_type = 'text/plain; charset=utf-8'+# Create response- response = make_response(formatted_transcript)if is_diarized and template:- filename = f"{recording.title or 'transcript'}_{template.name}.txt"+ filename = f"{recording.title or 'transcript'}_{template.name}.{ext}"elif is_diarized:- filename = f"{recording.title or 'transcript'}_formatted.txt"+ filename = f"{recording.title or 'transcript'}_formatted.{ext}"else:# Plain text transcription- filename = f"{recording.title or 'transcript'}.txt"+ filename = f"{recording.title or 'transcript'}.{ext}"filename = re.sub(r'[^a-zA-Z0-9_\-\.]', '_', filename)- response.headers['Content-Type'] = 'text/plain; charset=utf-8'+ response.headers['Content-Type'] = content_typeresponse.headers['Content-Disposition'] = f'attachment; filename="{filename}"'return response@@ -722,6 +741,112 @@ def download_notes_word(recording_id):+@recordings_bp.route('/api/recordings/export-existing', methods=['POST'])+@login_required+def export_existing_recordings():+ """Export the current user's already-processed recordings to disk.++ Auto-export only fires when a recording finishes processing, so anything+ transcribed before the feature was enabled never got written. This endpoint+ lets a user backfill those files to the configured AUTO_EXPORT_DIR on demand.+ It reuses the same writer as auto-export (`export_recording`), so the output+ format, per-user directory, and template resolution are all identical.+ """+ from src.file_exporter import ENABLE_AUTO_EXPORT, export_recording++ if not ENABLE_AUTO_EXPORT:+ return jsonify({'error': 'Auto-export is not enabled on this server'}), 400++ try:+ # Candidate recordings: owned by the user and holding exportable content.+ recordings = Recording.query.filter(+ Recording.user_id == current_user.id,+ Recording.status == 'COMPLETED'+ ).filter(+ (Recording.transcription.isnot(None)) | (Recording.summary.isnot(None))+ ).all()++ recording_ids = [r.id for r in recordings]+ total = len(recording_ids)++ exported = 0+ failed = 0+ # export_recording opens its own app context and re-fetches by id, so it+ # is safe to call per-recording from within this request.+ for rid in recording_ids:+ try:+ if export_recording(rid):+ exported += 1+ else:+ failed += 1+ except Exception as e:+ current_app.logger.error(f"Bulk export failed for recording {rid}: {e}")+ failed += 1++ return jsonify({+ 'exported': exported,+ 'failed': failed,+ 'total': total,+ })++ except Exception as e:+ current_app.logger.error(f"Error during bulk export: {e}")+ return jsonify({'error': 'Failed to export recordings'}), 500+++@recordings_bp.route('/api/recordings/merge', methods=['POST'])+@login_required+def merge_recordings_endpoint():+ """Merge two or more of the current user's recordings into a new one.++ Body (JSON):+ - recording_ids (list[int], required, ordered): sources to merge, in the+ order they should be concatenated.+ - title (str, optional): title for the merged recording.+ - delete_originals (bool, optional): delete the sources after a successful+ merge (default False).++ Validation happens in-request; the audio concat runs later on a worker+ (job_type 'merge'), so a long merge never blocks the request. The merged+ recording is created immediately in PROCESSING and queued for the normal+ transcription + summarization pipeline. See src/services/recording_merge.py.+ """+ from src.services.recording_merge import create_merge_recording, MergeError++ data = request.get_json(silent=True) or {}+ raw_ids = data.get('recording_ids')++ if not isinstance(raw_ids, list) or len(raw_ids) < 2:+ return jsonify({'error': 'Select at least two recordings to merge'}), 400++ try:+ recording_ids = [int(rid) for rid in raw_ids]+ except (ValueError, TypeError):+ return jsonify({'error': 'Invalid recording ids'}), 400++ title = data.get('title')+ delete_originals = bool(data.get('delete_originals', False))++ try:+ recording = create_merge_recording(+ current_user,+ recording_ids,+ title=title,+ delete_originals=delete_originals,+ )+ except MergeError as e:+ return jsonify({'error': str(e)}), 400+ except Exception as e:+ current_app.logger.error(f"Error merging recordings: {e}")+ return jsonify({'error': 'Failed to merge recordings'}), 500++ return jsonify({+ 'success': True,+ 'recording_id': recording.id,+ 'recording': recording.to_dict(viewer_user=current_user),+ })++@recordings_bp.route('/recording/<int:recording_id>/generate_summary', methods=['POST'])@login_requireddef generate_summary_endpoint(recording_id):diff --git a/src/services/job_queue.py b/src/services/job_queue.pyindex 6fd30f6e..f18d9d51 100644--- a/src/services/job_queue.py+++ b/src/services/job_queue.py@@ -35,7 +35,7 @@ POLL_INTERVAL = 1.0 # seconds between checking for new jobs# get_position_in_queue places it — no separate worker pool or queue needed.# Every consumer routes via "SUMMARY_JOBS if ... else TRANSCRIPTION_JOBS", so# membership in this list is the single source of truth for the whole pipeline.-TRANSCRIPTION_JOBS = ['transcribe', 'reprocess_transcription', 'stitch']+TRANSCRIPTION_JOBS = ['transcribe', 'reprocess_transcription', 'stitch', 'merge']SUMMARY_JOBS = ['summarize', 'reprocess_summary']@@ -344,6 +344,8 @@ class FairJobQueue:self._run_reprocess_summary(job, recording, params)elif job_type == 'stitch':self._run_stitch(job, recording, params)+ elif job_type == 'merge':+ self._run_merge(job, recording, params)else:raise ValueError(f"Unknown job type: {job_type}")@@ -562,6 +564,25 @@ class FairJobQueue:metadata=metadata,)+ def _run_merge(self, job, recording, params):+ """Concatenate source recordings' audio into this recording (#323).++ The heavy ffmpeg concat runs here, off the request path, so hours-long+ merges do not time out the HTTP request. On success the recording's+ audio_path is set and a follow-up ``transcribe`` job is enqueued; on+ failure the recording is flipped to FAILED with the error visible.+ """+ from src.services.recording_merge import run_merge_job, MergeError++ try:+ run_merge_job(recording, params)+ except MergeError as e:+ recording.status = 'FAILED'+ recording.error_message = str(e)+ recording.transcription = f"Processing failed: {e}"+ db.session.commit()+ raise+def enqueue(self,user_id: int,diff --git a/src/services/recording_merge.py b/src/services/recording_merge.pynew file mode 100644index 00000000..dd184d65--- /dev/null+++ b/src/services/recording_merge.py@@ -0,0 +1,325 @@+"""+Merge multiple recordings into a single new recording.++Use case (issue #323): a call drops or a meeting freezes, leaving the user with+two (or more) separate recordings of what was really one session. Merging+concatenates the source audio, in the order the user chooses, into one new+recording that is then run through the standard processing pipeline+(transcription + diarization + summarization). The result is a single coherent+transcript and summary instead of several partial ones.++Design notes:+- We merge at the AUDIO level and re-process, rather than stitching transcripts.+ Re-transcribing costs time/API, but it is the only way to get continuous+ speaker diarization and one unified summary. Transcript-level stitching cannot+ reconcile speaker identities across independently-diarized files.+- Two phases, mirroring the recording-session ``stitch`` flow:+ 1. ``create_merge_recording`` runs IN the request. It validates cheaply+ (ownership, audio present, stable status, count), creates a placeholder+ recording in PROCESSING, and enqueues a ``merge`` job. It does NO ffmpeg,+ so the request returns immediately even for hours-long sources.+ 2. ``run_merge_job`` runs in a background worker. It does the heavy ffmpeg+ concat, uploads the result via the storage facade, sets ``audio_path``,+ optionally deletes the originals, then enqueues the ``transcribe`` job.+ This keeps a long re-encode off the request path (a synchronous concat would+ exceed reverse-proxy timeouts on multi-hour meetings).+- The concat uses ffmpeg's concat FILTER (not the demuxer), decoding and+ re-encoding each input. Every input is first normalized to a common sample+ rate / channel layout via ``aformat`` so the filter accepts heterogeneous+ sources (different codecs, sample rates, mono vs stereo). Only the first audio+ stream of each input is used, so video streams are ignored and the merged+ output is audio-only (which is what the transcription pipeline consumes).+"""++import os+from contextlib import ExitStack+from datetime import datetime++from flask import current_app++from src.database import db+from src.models import Recording, RecordingTag+from src.services.job_queue import job_queue+from src.services.storage.service import get_storage_service+from src.utils.ffmpeg_utils import _run_ffmpeg_command, FFmpegError++# Normalization target for the concat filter. 44.1 kHz stereo is a safe,+# widely-supported baseline; the ASR downsamples as needed downstream.+_TARGET_SAMPLE_RATE = '44100'+_TARGET_CHANNEL_LAYOUT = 'stereo'+_MERGED_BITRATE = '192k'++# Statuses whose audio file is guaranteed stable (not being written/converted by+# the pipeline). A source mid-transcription may have its audio_path swapped when+# video is extracted to audio, so PENDING/PROCESSING sources are rejected.+_STABLE_STATUSES = {'COMPLETED', 'SUMMARIZING', 'FAILED'}+++class MergeError(Exception):+ """Raised when a merge cannot be performed. The message is user-safe."""+++def _build_concat_filter(num_inputs: int) -> str:+ """Build an ffmpeg -filter_complex string that normalizes then concatenates+ the first audio stream of each input."""+ normalize = []+ labels = []+ for i in range(num_inputs):+ normalize.append(+ f"[{i}:a:0]aformat=sample_rates={_TARGET_SAMPLE_RATE}:"+ f"channel_layouts={_TARGET_CHANNEL_LAYOUT}[a{i}]"+ )+ labels.append(f"[a{i}]")+ return (+ ";".join(normalize)+ + ";"+ + "".join(labels)+ + f"concat=n={num_inputs}:v=0:a=1[out]"+ )+++def _concat_audio(input_paths: list, output_path: str) -> None:+ """Concatenate local audio files into output_path (AAC/.m4a)."""+ cmd = ['ffmpeg', '-y']+ for path in input_paths:+ cmd += ['-i', path]+ cmd += [+ '-filter_complex', _build_concat_filter(len(input_paths)),+ '-map', '[out]',+ '-c:a', 'aac',+ '-b:a', _MERGED_BITRATE,+ output_path,+ ]+ _run_ffmpeg_command(cmd, f"merge concat of {len(input_paths)} recordings")+++def _validate_sources(user, recording_ids, storage):+ """Validate the requested sources and return them in caller order.++ Raises MergeError on any problem. Returns the list of Recording rows.+ """+ if not recording_ids or len(recording_ids) < 2:+ raise MergeError("Select at least two recordings to merge.")++ # Preserve caller order while rejecting duplicates.+ seen = set()+ ordered_ids = []+ for rid in recording_ids:+ if rid in seen:+ raise MergeError("A recording cannot be merged with itself.")+ seen.add(rid)+ ordered_ids.append(rid)++ recordings = []+ for rid in ordered_ids:+ 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:+ raise MergeError(+ f"\"{rec.title or 'A recording'}\" is still processing. "+ "Wait for it to finish before merging."+ )+ if not rec.audio_path or not storage.exists(rec.audio_path):+ raise MergeError(+ f"Audio for \"{rec.title or 'a recording'}\" is unavailable "+ "(it may have been auto-deleted)."+ )+ recordings.append(rec)+ return recordings+++def create_merge_recording(user, recording_ids, title=None, delete_originals=False):+ """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.++ Raises:+ MergeError: on validation failure.+ """+ storage = get_storage_service()+ recordings = _validate_sources(user, recording_ids, storage)+ ordered_ids = [r.id for r in recordings]++ first = recordings[0]+ merged_title = (title or '').strip() or f"{first.title or 'Recording'} (merged)"++ now = datetime.utcnow()++ # Inherit folder from the first source; leave meeting_date at the earliest+ # source's date so the merged session sorts where the conversation began.+ meeting_dates = [r.meeting_date for r in recordings if r.meeting_date]+ merged_meeting_date = min(meeting_dates) if meeting_dates else now++ recording = Recording(+ audio_path=None,+ original_filename=f"{merged_title}.m4a",+ title=merged_title,+ # 'QUEUED' matches what job_queue.enqueue() sets for a transcription-side+ # job; set it here too so the row is consistent even before enqueue.+ status='QUEUED',+ meeting_date=merged_meeting_date,+ user_id=user.id,+ mime_type='audio/mp4',+ notes=first.notes,+ folder_id=first.folder_id,+ processing_source='merge',+ )+ db.session.add(recording)+ db.session.flush() # assign recording.id++ # Inherit the first source's tags (preserving order).+ for order, tag in enumerate(first.tags, 1):+ db.session.add(RecordingTag(+ recording_id=recording.id,+ tag_id=tag.id,+ order=order,+ added_at=datetime.utcnow(),+ ))++ db.session.commit()++ try:+ job_queue.enqueue(+ user_id=user.id,+ recording_id=recording.id,+ job_type='merge',+ params={+ 'source_ids': ordered_ids,+ 'delete_originals': bool(delete_originals),+ },+ is_new_upload=True,+ )+ except Exception as e:+ current_app.logger.error(f"Merge enqueue failed for recording {recording.id}: {e}")+ recording.status = 'FAILED'+ recording.error_message = f"Processing failed: {e}"+ db.session.commit()+ raise MergeError("Could not queue the merge for processing.")++ return recording+++def run_merge_job(recording, params):+ """Perform the audio concat for a queued merge, then queue transcription.++ Runs on a background worker (see JobQueue._run_merge). On success the merged+ recording's audio_path/file_size are set and a ``transcribe`` job is queued.+ Raises MergeError on failure so the worker can flip the recording to FAILED.+ """+ source_ids = (params or {}).get('source_ids') or []+ delete_originals = bool((params or {}).get('delete_originals', False))++ if len(source_ids) < 2:+ raise MergeError("Merge job is missing its source recordings.")++ storage = get_storage_service()++ # Re-fetch and re-validate sources at run time (they may have changed since+ # the request was made).+ sources = []+ for rid in source_ids:+ rec = db.session.get(Recording, rid)+ if not rec or rec.user_id != recording.user_id:+ raise MergeError("A source recording is no longer available.")+ if not rec.audio_path or not storage.exists(rec.audio_path):+ raise MergeError("Audio for a source recording is unavailable.")+ sources.append(rec)++ now = datetime.utcnow()+ upload_folder = current_app.config['UPLOAD_FOLDER']+ os.makedirs(upload_folder, exist_ok=True)+ staging_path = os.path.join(+ upload_folder, f"merged_{now.strftime('%Y%m%d%H%M%S')}_{recording.id}.m4a"+ )++ try:+ with ExitStack() as stack:+ local_paths = []+ for rec in sources:+ materialized = stack.enter_context(storage.materialize(rec.audio_path))+ local_paths.append(materialized.local_path)+ _concat_audio(local_paths, staging_path)++ # Guard against a silent success that produced nothing usable. Capture+ # the size now, before upload — upload_local_file(delete_source=True)+ # removes the staging file, so getsize would fail afterwards.+ if not os.path.exists(staging_path):+ raise MergeError("The merged audio came out empty.")+ merged_size = os.path.getsize(staging_path)+ if merged_size == 0:+ raise MergeError("The merged audio came out empty.")+ except FFmpegError as e:+ current_app.logger.error(f"Merge ffmpeg failed for recording {recording.id}: {e}")+ _safe_unlink(staging_path)+ raise MergeError("Failed to combine the audio files.")+ except MergeError:+ _safe_unlink(staging_path)+ raise+ except Exception as e:+ current_app.logger.error(f"Merge concat failed for recording {recording.id}: {e}")+ _safe_unlink(staging_path)+ raise MergeError("Failed to combine the audio files.")++ try:+ storage_key = storage.build_recording_key(recording.original_filename, recording.id, now=now)+ stored_object = storage.upload_local_file(+ staging_path,+ storage_key,+ content_type='audio/mp4',+ delete_source=True,+ )+ recording.audio_path = stored_object.locator+ recording.file_size = merged_size+ db.session.commit()+ except Exception as e:+ current_app.logger.error(f"Merge storage upload failed for recording {recording.id}: {e}")+ db.session.rollback()+ _safe_unlink(staging_path)+ raise MergeError("Failed to store the merged recording.")++ # Delete originals only after the merged audio is safely stored.+ if delete_originals:+ for rec in sources:+ try:+ _delete_recording(rec, storage)+ except Exception as e:+ current_app.logger.warning(f"Failed to delete source recording {rec.id} after merge: {e}")+ db.session.commit()++ # Queue transcription using the user's defaults.+ from src.models import User+ owner = db.session.get(User, recording.user_id)+ first_tag = recording.tags[0] if recording.tags else None+ job_params = {+ 'language': owner.transcription_language if owner else None,+ 'hotwords': owner.transcription_hotwords if owner else None,+ 'initial_prompt': owner.transcription_initial_prompt if owner else None,+ 'tag_id': first_tag.id if first_tag else None,+ }+ job_queue.enqueue(+ user_id=recording.user_id,+ recording_id=recording.id,+ job_type='transcribe',+ params=job_params,+ is_new_upload=True,+ )+++def _delete_recording(recording, storage):+ """Delete a source recording's audio and row. Best-effort on the file."""+ if recording.audio_path:+ try:+ storage.delete(recording.audio_path, missing_ok=True)+ except Exception as e:+ current_app.logger.warning(f"Could not delete audio for recording {recording.id}: {e}")+ db.session.delete(recording)+++def _safe_unlink(path):+ try:+ if path and os.path.exists(path):+ os.remove(path)+ except OSError:+ passdiff --git a/static/js/app.modular.js b/static/js/app.modular.jsindex 2de0a576..c2c9453a 100644--- a/static/js/app.modular.js+++ b/static/js/app.modular.js@@ -715,6 +715,11 @@ document.addEventListener('DOMContentLoaded', async () => {const legendExpanded = ref(false);const highlightedSpeaker = ref(null);const showDownloadMenu = ref(false);+ // Preferred transcript download format ('txt' | 'md'), persisted.+ const transcriptDownloadFormat = ref(localStorage.getItem('transcriptDownloadFormat') === 'md' ? 'md' : 'txt');+ watch(transcriptDownloadFormat, (val) => {+ localStorage.setItem('transcriptDownloadFormat', val === 'md' ? 'md' : 'txt');+ });const currentPlayingSegmentIndex = ref(null);const followPlayerMode = ref(false);const processingIndicatorMinimized = ref(false);@@ -1681,6 +1686,7 @@ document.addEventListener('DOMContentLoaded', async () => {// TranscriptiontranscriptionViewMode, legendExpanded, highlightedSpeaker, showDownloadMenu,+ transcriptDownloadFormat,currentPlayingSegmentIndex, followPlayerMode, processingIndicatorMinimized,// Chatdiff --git a/static/js/modules/composables/bulk-operations.js b/static/js/modules/composables/bulk-operations.jsindex 3d3d8c6c..7532f046 100644--- a/static/js/modules/composables/bulk-operations.js+++ b/static/js/modules/composables/bulk-operations.js@@ -15,6 +15,7 @@ export function useBulkOperations({availableFolders,showToast,setGlobalError,+ exitSelectionMode,startReprocessingPoll}) {// Modal state@@ -22,10 +23,17 @@ export function useBulkOperations({const showBulkTagModal = ref(false);const showBulkReprocessModal = ref(false);const showBulkFolderModal = ref(false);+ const showBulkMergeModal = ref(false);const bulkTagAction = ref('add'); // 'add' or 'remove'const bulkTagSelectedId = ref('');const bulkReprocessType = ref('summary'); // 'transcription' or 'summary'+ // Merge state+ const mergeOrderedList = ref([]); // ordered array of recording objects+ const mergeTitle = ref('');+ const mergeDeleteOriginals = ref(false);+ const mergeInProgress = ref(false);+// Get CSRF tokenconst getCsrfToken = () => {return document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');@@ -259,6 +267,85 @@ export function useBulkOperations({}};+ // =========================================+ // Merge Recordings (issue #323)+ // =========================================++ const openBulkMergeModal = () => {+ // Seed the ordered list from the current selection. Order matters for a+ // merge, so present the selection as an explicit, reorderable list.+ mergeOrderedList.value = selectedRecordings.value.slice();+ mergeTitle.value = '';+ mergeDeleteOriginals.value = false;+ showBulkMergeModal.value = true;+ };++ const closeBulkMergeModal = () => {+ showBulkMergeModal.value = false;+ };++ const moveMergeItem = (index, direction) => {+ const list = mergeOrderedList.value;+ const target = index + direction;+ if (target < 0 || target >= list.length) return;+ const next = list.slice();+ [next[index], next[target]] = [next[target], next[index]];+ mergeOrderedList.value = next;+ };++ const executeBulkMerge = async () => {+ const orderedIds = mergeOrderedList.value.map(r => r.id);+ if (orderedIds.length < 2) return;++ mergeInProgress.value = true;+ bulkActionInProgress.value = true;++ try {+ const response = await fetch('/api/recordings/merge', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': getCsrfToken()+ },+ body: JSON.stringify({+ recording_ids: orderedIds,+ title: mergeTitle.value.trim() || undefined,+ delete_originals: mergeDeleteOriginals.value+ })+ });++ const data = await response.json();++ if (!response.ok) {+ throw new Error(data.error || 'Failed to merge recordings');+ }++ // The audio concat runs on a worker; originals are deleted there+ // only after it succeeds, so we do NOT remove them optimistically.+ // They disappear on the next recordings refresh if delete was chosen.++ // Surface the new merged recording immediately (in PROCESSING).+ if (data.recording) {+ recordings.value.unshift(data.recording);+ if (startReprocessingPoll) {+ startReprocessingPoll(data.recording.id);+ }+ }++ closeBulkMergeModal();+ if (exitSelectionMode) exitSelectionMode();++ const count = orderedIds.length;+ showToast(`Merging ${count} recordings — the combined recording is processing`, 'fa-object-group', 4000, 'success');+ } catch (error) {+ console.error('Merge error:', error);+ setGlobalError(`Failed to merge recordings: ${error.message}`);+ } finally {+ mergeInProgress.value = false;+ bulkActionInProgress.value = false;+ }+ };+// =========================================// Bulk Toggle (Inbox/Highlight)// =========================================@@ -446,9 +533,14 @@ export function useBulkOperations({showBulkTagModal,showBulkReprocessModal,showBulkFolderModal,+ showBulkMergeModal,bulkTagAction,bulkTagSelectedId,bulkReprocessType,+ mergeOrderedList,+ mergeTitle,+ mergeDeleteOriginals,+ mergeInProgress,// Bulk DeleteopenBulkDeleteModal,@@ -465,6 +557,12 @@ export function useBulkOperations({closeBulkReprocessModal,executeBulkReprocess,+ // Merge+ openBulkMergeModal,+ closeBulkMergeModal,+ moveMergeItem,+ executeBulkMerge,+// Bulk TogglebulkToggleInbox,bulkToggleHighlight,diff --git a/static/js/modules/composables/ui.js b/static/js/modules/composables/ui.jsindex 0823b61b..d492a15b 100644--- a/static/js/modules/composables/ui.js+++ b/static/js/modules/composables/ui.js@@ -15,7 +15,7 @@ export function useUI(state, utils, processedTranscription) {editingNotes, tempNotesContent, transcriptionViewMode,notesMarkdownEditor, markdownEditorInstance, autoSaveTimer, csrfToken,summaryMarkdownEditor, recordingNotesEditor, recordingMarkdownEditorInstance,- recordingNotes, showDownloadMenu, currentPlayingSegmentIndex, followPlayerMode,+ recordingNotes, showDownloadMenu, transcriptDownloadFormat, currentPlayingSegmentIndex, followPlayerMode,playbackRate, showSpeedMenu, playbackSpeeds, modalPlaybackRate, speedMenuPosition,videoFullscreen, fullscreenControlsVisible, fullscreenControlsTimer, videoCollapsed,regeneratingTitle,@@ -1708,6 +1708,8 @@ export function useUI(state, utils, processedTranscription) {}}+ const fmt = transcriptDownloadFormat.value === 'md' ? 'md' : 'txt';+// If templateId is 'none', download raw transcript without any templateif (templateId === 'none') {let rawText = '';@@ -1726,11 +1728,14 @@ export function useUI(state, utils, processedTranscription) {rawText = selectedRecording.value.transcription;}- const blob = new Blob([rawText], { type: 'text/plain;charset=utf-8' });+ const title = selectedRecording.value.title || 'transcript';+ const content = fmt === 'md' ? `# ${title}\n\n${rawText}\n` : rawText;+ const mime = fmt === 'md' ? 'text/markdown;charset=utf-8' : 'text/plain;charset=utf-8';+ const blob = new Blob([content], { type: mime });const downloadUrl = URL.createObjectURL(blob);const a = document.createElement('a');a.href = downloadUrl;- a.download = `${selectedRecording.value.title || 'transcript'}_raw.txt`;+ a.download = `${title}_raw.${fmt}`;document.body.appendChild(a);a.click();document.body.removeChild(a);@@ -1742,8 +1747,8 @@ export function useUI(state, utils, processedTranscription) {// Download the transcript with the selected templateconst url = templateId- ? `/recording/${selectedRecording.value.id}/download/transcript?template_id=${templateId}`- : `/recording/${selectedRecording.value.id}/download/transcript`;+ ? `/recording/${selectedRecording.value.id}/download/transcript?template_id=${templateId}&format=${fmt}`+ : `/recording/${selectedRecording.value.id}/download/transcript?format=${fmt}`;const response = await fetch(url);if (!response.ok) {@@ -1752,7 +1757,7 @@ export function useUI(state, utils, processedTranscription) {const blob = await response.blob();const contentDisposition = response.headers.get('content-disposition');- let filename = 'transcript.txt';+ let filename = `transcript.${fmt}`;if (contentDisposition) {const matches = contentDisposition.match(/filename="([^"]+)"/);if (matches && matches[1]) {@@ -1784,15 +1789,16 @@ export function useUI(state, utils, processedTranscription) {}try {+ const fmt = transcriptDownloadFormat.value === 'md' ? 'md' : 'txt';// Download using the default template (server will use user's default)- const response = await fetch(`/recording/${selectedRecording.value.id}/download/transcript`);+ const response = await fetch(`/recording/${selectedRecording.value.id}/download/transcript?format=${fmt}`);if (!response.ok) {throw new Error(t('messages.transcriptDownloadFailed'));}const blob = await response.blob();const contentDisposition = response.headers.get('content-disposition');- let filename = 'transcript.txt';+ let filename = `transcript.${fmt}`;if (contentDisposition) {const matches = contentDisposition.match(/filename="([^"]+)"/);if (matches && matches[1]) {diff --git a/static/locales/de.json b/static/locales/de.jsonindex 7e41ab7f..93db2d71 100644--- a/static/locales/de.json+++ b/static/locales/de.json@@ -742,7 +742,13 @@"templateDescription": "Beschreibung","templateName": "Vorlagenname","title": "Export-Vorlagen",- "viewGuide": "Vorlagen-Leitfaden anzeigen"+ "viewGuide": "Vorlagen-Leitfaden anzeigen",+ "bulkExportTitle": "Vorhandene Aufnahmen exportieren",+ "bulkExportDescription": "Schreibt alle Ihre verarbeiteten Aufnahmen in das Exportverzeichnis. Nützlich für Aufnahmen, die vor Aktivierung des automatischen Exports erstellt wurden.",+ "bulkExportButton": "Alle auf Datenträger exportieren",+ "bulkExportRunning": "Exportiere…",+ "bulkExportResult": "{{exported}} von {{total}} Aufnahmen exportiert.",+ "bulkExportFailed": "Export der Aufnahmen fehlgeschlagen."},"fileSize": {"bytes": "{{count}} B",@@ -1619,7 +1625,8 @@"template": "Vorlage","templateName": "Vorlagenname","title": "Transkript-Vorlagen",- "viewGuide": "Vorlagen-Leitfaden Anzeigen"+ "viewGuide": "Vorlagen-Leitfaden Anzeigen",+ "format": "Format"},"initialPromptTemplates": {"tabTitle": "Transkriptionsvorlagen",@@ -1852,5 +1859,22 @@"noUsersFound": "Keine Benutzer gefunden","add": "Hinzufügen","notSharedYet": "Noch nicht freigegeben"+ },+ "mergeRecordings": {+ "title": "Aufnahmen zusammenführen",+ "action": "Zusammenführen",+ "subtitle": "Zu einer Aufnahme kombinieren",+ "orderHint": "Die Aufnahmen werden in dieser Reihenfolge zusammengefügt. Ordnen Sie sie so an, dass sie dem Verlauf des Gesprächs entsprechen.",+ "untitled": "Aufnahme ohne Titel",+ "moveUp": "Nach oben",+ "moveDown": "Nach unten",+ "titleLabel": "Titel (optional)",+ "titlePlaceholder": "Leer lassen, um den Titel der ersten Aufnahme zu verwenden",+ "deleteOriginals": "Ursprüngliche Aufnahmen löschen",+ "deleteOriginalsHint": "Entfernt die Quellaufnahmen, nachdem die zusammengeführte Aufnahme erstellt wurde. Standardmäßig deaktiviert.",+ "reprocessNote": "Das kombinierte Audio wird erneut transkribiert und zusammengefasst, um eine durchgehende Transkription und Zusammenfassung zu erstellen.",+ "merging": "Wird zusammengeführt…",+ "confirm": "Zusammenführen",+ "videoNote": "Diese Aufnahmen enthalten Video. Beim Zusammenführen wird nur der Ton kombiniert; die zusammengeführte Aufnahme enthält kein Video."}-}+}\ No newline at end of filediff --git a/static/locales/en.json b/static/locales/en.jsonindex 4d899c70..f1d74a8b 100644--- a/static/locales/en.json+++ b/static/locales/en.json@@ -742,7 +742,13 @@"templateDescription": "Description","templateName": "Template Name","title": "Export Templates",- "viewGuide": "View Template Guide"+ "viewGuide": "View Template Guide",+ "bulkExportTitle": "Export existing recordings",+ "bulkExportDescription": "Write all of your processed recordings to the export directory. Useful for recordings created before auto-export was enabled.",+ "bulkExportButton": "Export all to disk",+ "bulkExportRunning": "Exporting…",+ "bulkExportResult": "Exported {{exported}} of {{total}} recordings.",+ "bulkExportFailed": "Failed to export recordings."},"fileSize": {"bytes": "{{count}} B",@@ -1628,7 +1634,8 @@"template": "Template","templateName": "Template Name","title": "Transcript Templates",- "viewGuide": "View Template Guide"+ "viewGuide": "View Template Guide",+ "format": "Format"},"initialPromptTemplates": {"tabTitle": "Transcription Templates",@@ -1852,5 +1859,22 @@"noUsersFound": "No users found","add": "Add","notSharedYet": "Not shared with anyone yet"+ },+ "mergeRecordings": {+ "title": "Merge Recordings",+ "action": "Merge",+ "subtitle": "Combine into one recording",+ "orderHint": "Recordings will be joined in this order. Reorder them to match the sequence of the conversation.",+ "untitled": "Untitled recording",+ "moveUp": "Move up",+ "moveDown": "Move down",+ "titleLabel": "Title (optional)",+ "titlePlaceholder": "Leave blank to use the first recording's title",+ "deleteOriginals": "Delete original recordings",+ "deleteOriginalsHint": "Remove the source recordings after the merged one is created. Off by default.",+ "reprocessNote": "The combined audio will be transcribed and summarized again to produce one continuous transcript and summary.",+ "merging": "Merging…",+ "confirm": "Merge recordings",+ "videoNote": "These recordings include video. Merging combines the audio only; the merged recording will not have video."}-}+}\ No newline at end of filediff --git a/static/locales/es.json b/static/locales/es.jsonindex ea1e45bc..2c2ba486 100644--- a/static/locales/es.json+++ b/static/locales/es.json@@ -742,7 +742,13 @@"templateDescription": "Descripción","templateName": "Nombre de la plantilla","title": "Plantillas de exportación",- "viewGuide": "Ver guía de plantillas"+ "viewGuide": "Ver guía de plantillas",+ "bulkExportTitle": "Exportar grabaciones existentes",+ "bulkExportDescription": "Escribe todas tus grabaciones procesadas en el directorio de exportación. Útil para grabaciones creadas antes de habilitar la exportación automática.",+ "bulkExportButton": "Exportar todo al disco",+ "bulkExportRunning": "Exportando…",+ "bulkExportResult": "{{exported}} de {{total}} grabaciones exportadas.",+ "bulkExportFailed": "No se pudieron exportar las grabaciones."},"fileSize": {"bytes": "{{count}} B",@@ -1619,7 +1625,8 @@"template": "Plantilla","templateName": "Nombre de Plantilla","title": "Plantillas de Transcripción",- "viewGuide": "Ver Guía de Plantillas"+ "viewGuide": "Ver Guía de Plantillas",+ "format": "Formato"},"initialPromptTemplates": {"tabTitle": "Plantillas de transcripción",@@ -1852,5 +1859,22 @@"noUsersFound": "No se encontraron usuarios","add": "Añadir","notSharedYet": "Aún no compartido con nadie"+ },+ "mergeRecordings": {+ "title": "Combinar grabaciones",+ "action": "Combinar",+ "subtitle": "Unir en una sola grabación",+ "orderHint": "Las grabaciones se unirán en este orden. Reordénalas para que coincidan con la secuencia de la conversación.",+ "untitled": "Grabación sin título",+ "moveUp": "Subir",+ "moveDown": "Bajar",+ "titleLabel": "Título (opcional)",+ "titlePlaceholder": "Déjalo en blanco para usar el título de la primera grabación",+ "deleteOriginals": "Eliminar las grabaciones originales",+ "deleteOriginalsHint": "Elimina las grabaciones de origen después de crear la combinada. Desactivado de forma predeterminada.",+ "reprocessNote": "El audio combinado se transcribirá y resumirá de nuevo para producir una transcripción y un resumen continuos.",+ "merging": "Combinando…",+ "confirm": "Combinar",+ "videoNote": "Estas grabaciones incluyen vídeo. La combinación une solo el audio; la grabación combinada no tendrá vídeo."}-}+}\ No newline at end of filediff --git a/static/locales/fr.json b/static/locales/fr.jsonindex 9ca85fc2..26f49ce1 100644--- a/static/locales/fr.json+++ b/static/locales/fr.json@@ -742,7 +742,13 @@"templateDescription": "Description","templateName": "Nom du modèle","title": "Modèles d'exportation",- "viewGuide": "Voir le guide des modèles"+ "viewGuide": "Voir le guide des modèles",+ "bulkExportTitle": "Exporter les enregistrements existants",+ "bulkExportDescription": "Écrit tous vos enregistrements traités dans le répertoire d'exportation. Utile pour les enregistrements créés avant l'activation de l'exportation automatique.",+ "bulkExportButton": "Tout exporter sur le disque",+ "bulkExportRunning": "Exportation…",+ "bulkExportResult": "{{exported}} enregistrement(s) sur {{total}} exporté(s).",+ "bulkExportFailed": "Échec de l'exportation des enregistrements."},"fileSize": {"bytes": "{{count}} B",@@ -1619,7 +1625,8 @@"template": "Modèle","templateName": "Nom du Modèle","title": "Modèles de Transcription",- "viewGuide": "Voir le Guide des Modèles"+ "viewGuide": "Voir le Guide des Modèles",+ "format": "Format"},"initialPromptTemplates": {"tabTitle": "Modèles de transcription",@@ -1852,5 +1859,22 @@"noUsersFound": "Aucun utilisateur trouvé","add": "Ajouter","notSharedYet": "Pas encore partagé"+ },+ "mergeRecordings": {+ "title": "Fusionner les enregistrements",+ "action": "Fusionner",+ "subtitle": "Combiner en un seul enregistrement",+ "orderHint": "Les enregistrements seront joints dans cet ordre. Réorganisez-les pour correspondre au déroulement de la conversation.",+ "untitled": "Enregistrement sans titre",+ "moveUp": "Monter",+ "moveDown": "Descendre",+ "titleLabel": "Titre (facultatif)",+ "titlePlaceholder": "Laissez vide pour utiliser le titre du premier enregistrement",+ "deleteOriginals": "Supprimer les enregistrements d'origine",+ "deleteOriginalsHint": "Supprime les enregistrements sources après la création de l'enregistrement fusionné. Désactivé par défaut.",+ "reprocessNote": "L'audio combiné sera de nouveau transcrit et résumé afin de produire une transcription et un résumé continus.",+ "merging": "Fusion…",+ "confirm": "Fusionner",+ "videoNote": "Ces enregistrements contiennent de la vidéo. La fusion ne combine que l'audio ; l'enregistrement fusionné n'aura pas de vidéo."}-}+}\ No newline at end of filediff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.jsonindex 38cbdf56..93cdc6d5 100644--- a/static/locales/pt-BR.json+++ b/static/locales/pt-BR.json@@ -742,7 +742,13 @@"templateDescription": "Descrição","templateName": "Nome do Modelo","title": "Modelos de Exportação",- "viewGuide": "Ver Guia de Modelo"+ "viewGuide": "Ver Guia de Modelo",+ "bulkExportTitle": "Exportar gravações existentes",+ "bulkExportDescription": "Grava todas as suas gravações processadas no diretório de exportação. Útil para gravações criadas antes de a exportação automática ser ativada.",+ "bulkExportButton": "Exportar tudo para o disco",+ "bulkExportRunning": "Exportando…",+ "bulkExportResult": "{{exported}} de {{total}} gravações exportadas.",+ "bulkExportFailed": "Falha ao exportar as gravações."},"fileSize": {"bytes": "{{count}} B",@@ -1619,7 +1625,8 @@"template": "Modelo","templateName": "Nome do Modelo","title": "Modelos de Transcrição",- "viewGuide": "Ver Guia de Modelo"+ "viewGuide": "Ver Guia de Modelo",+ "format": "Formato"},"initialPromptTemplates": {"tabTitle": "Modelos de transcrição",@@ -1852,5 +1859,22 @@"noUsersFound": "Nenhum usuário encontrado","add": "Adicionar","notSharedYet": "Ainda não compartilhado"+ },+ "mergeRecordings": {+ "title": "Mesclar gravações",+ "action": "Mesclar",+ "subtitle": "Combinar em uma única gravação",+ "orderHint": "As gravações serão unidas nesta ordem. Reordene-as para corresponder à sequência da conversa.",+ "untitled": "Gravação sem título",+ "moveUp": "Mover para cima",+ "moveDown": "Mover para baixo",+ "titleLabel": "Título (opcional)",+ "titlePlaceholder": "Deixe em branco para usar o título da primeira gravação",+ "deleteOriginals": "Excluir gravações originais",+ "deleteOriginalsHint": "Remove as gravações de origem após a criação da mesclada. Desativado por padrão.",+ "reprocessNote": "O áudio combinado será transcrito e resumido novamente para produzir uma transcrição e um resumo contínuos.",+ "merging": "Mesclando…",+ "confirm": "Mesclar",+ "videoNote": "Estas gravações incluem vídeo. A mesclagem combina apenas o áudio; a gravação mesclada não terá vídeo."}-}+}\ No newline at end of filediff --git a/static/locales/ru.json b/static/locales/ru.jsonindex 47b90a8d..98e24ed2 100644--- a/static/locales/ru.json+++ b/static/locales/ru.json@@ -742,7 +742,13 @@"templateDescription": "Описание","templateName": "Название шаблона","title": "Шаблоны экспорта",- "viewGuide": "Просмотреть руководство по шаблонам"+ "viewGuide": "Просмотреть руководство по шаблонам",+ "bulkExportTitle": "Экспортировать существующие записи",+ "bulkExportDescription": "Записывает все обработанные записи в каталог экспорта. Полезно для записей, созданных до включения автоэкспорта.",+ "bulkExportButton": "Экспортировать всё на диск",+ "bulkExportRunning": "Экспорт…",+ "bulkExportResult": "Экспортировано {{exported}} из {{total}} записей.",+ "bulkExportFailed": "Не удалось экспортировать записи."},"fileSize": {"bytes": "{{count}} Б",@@ -1619,7 +1625,8 @@"template": "Шаблон","templateName": "Название шаблона","title": "Шаблоны транскриптов",- "viewGuide": "Посмотреть руководство по шаблонам"+ "viewGuide": "Посмотреть руководство по шаблонам",+ "format": "Формат"},"initialPromptTemplates": {"tabTitle": "Шаблоны транскрипции",@@ -1852,5 +1859,22 @@"noUsersFound": "Пользователи не найдены","add": "Добавить","notSharedYet": "Пока ни с кем не поделились"+ },+ "mergeRecordings": {+ "title": "Объединить записи",+ "action": "Объединить",+ "subtitle": "Собрать в одну запись",+ "orderHint": "Записи будут объединены в этом порядке. Измените порядок в соответствии с ходом разговора.",+ "untitled": "Запись без названия",+ "moveUp": "Вверх",+ "moveDown": "Вниз",+ "titleLabel": "Название (необязательно)",+ "titlePlaceholder": "Оставьте пустым, чтобы использовать название первой записи",+ "deleteOriginals": "Удалить исходные записи",+ "deleteOriginalsHint": "Удаляет исходные записи после создания объединённой. По умолчанию отключено.",+ "reprocessNote": "Объединённый звук будет заново расшифрован и обобщён, чтобы создать непрерывную расшифровку и резюме.",+ "merging": "Объединение…",+ "confirm": "Объединить",+ "videoNote": "Эти записи содержат видео. При объединении сохраняется только звук; в объединённой записи видео не будет."}-}+}\ No newline at end of filediff --git a/static/locales/zh.json b/static/locales/zh.jsonindex 385033e0..45245f58 100644--- a/static/locales/zh.json+++ b/static/locales/zh.json@@ -742,7 +742,13 @@"templateDescription": "描述","templateName": "模板名称","title": "导出模板",- "viewGuide": "查看模板指南"+ "viewGuide": "查看模板指南",+ "bulkExportTitle": "导出现有录音",+ "bulkExportDescription": "将您所有已处理的录音写入导出目录。适用于在启用自动导出之前创建的录音。",+ "bulkExportButton": "全部导出到磁盘",+ "bulkExportRunning": "正在导出…",+ "bulkExportResult": "已导出 {{total}} 条录音中的 {{exported}} 条。",+ "bulkExportFailed": "导出录音失败。"},"fileSize": {"bytes": "{{count}} B",@@ -1619,7 +1625,8 @@"template": "模板","templateName": "模板名称","title": "转录模板",- "viewGuide": "查看模板指南"+ "viewGuide": "查看模板指南",+ "format": "格式"},"initialPromptTemplates": {"tabTitle": "转录模板",@@ -1852,5 +1859,22 @@"noUsersFound": "未找到用户","add": "添加","notSharedYet": "尚未与任何人分享"+ },+ "mergeRecordings": {+ "title": "合并录音",+ "action": "合并",+ "subtitle": "合并为一条录音",+ "orderHint": "录音将按此顺序拼接。请调整顺序以匹配对话的实际先后。",+ "untitled": "未命名录音",+ "moveUp": "上移",+ "moveDown": "下移",+ "titleLabel": "标题(可选)",+ "titlePlaceholder": "留空则使用第一条录音的标题",+ "deleteOriginals": "删除原始录音",+ "deleteOriginalsHint": "创建合并录音后删除源录音。默认关闭。",+ "reprocessNote": "合并后的音频将被重新转录和总结,以生成连续的转录文本和摘要。",+ "merging": "正在合并…",+ "confirm": "合并",+ "videoNote": "这些录音包含视频。合并仅会合并音频;合并后的录音将不包含视频。"}-}+}\ No newline at end of filediff --git a/templates/account.html b/templates/account.htmlindex 9911650c..5770a89c 100644--- a/templates/account.html+++ b/templates/account.html@@ -1408,6 +1408,23 @@</button></div>+ {% if enable_auto_export %}+ <!-- Bulk export existing recordings to the auto-export directory -->+ <div class="bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] p-6">+ <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">+ <div class="min-w-0">+ <h3 class="text-lg font-semibold text-[var(--text-primary)]" data-i18n="exportTemplates.bulkExportTitle">Export existing recordings</h3>+ <p class="text-sm text-[var(--text-secondary)]" data-i18n="exportTemplates.bulkExportDescription">Write all of your processed recordings to the export directory. Useful for recordings created before auto-export was enabled.</p>+ <p id="bulkExportStatus" class="text-sm mt-2 hidden"></p>+ </div>+ <button id="bulkExportBtn" class="inline-flex items-center px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200 whitespace-nowrap disabled:opacity-60 disabled:cursor-not-allowed">+ <i class="fas fa-file-export mr-2"></i>+ <span data-i18n="exportTemplates.bulkExportButton">Export all to disk</span>+ </button>+ </div>+ </div>+ {% endif %}+<!-- Export Templates Grid --><div class="grid grid-cols-1 lg:grid-cols-3 gap-6"><!-- Export Templates List (Left) -->@@ -7687,6 +7704,48 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co}});+ // Bulk-export existing recordings to the auto-export directory. Reuses+ // the same server-side writer as auto-export; only present when the+ // server has auto-export enabled (the card is Jinja-gated).+ document.getElementById('bulkExportBtn')?.addEventListener('click', async (e) => {+ const btn = e.currentTarget;+ const statusEl = document.getElementById('bulkExportStatus');+ const original = btn.innerHTML;+ btn.disabled = true;+ btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i><span>' + t('exportTemplates.bulkExportRunning') + '</span>';+ if (statusEl) { statusEl.classList.add('hidden'); }+ try {+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');+ const response = await fetch('/api/recordings/export-existing', {+ method: 'POST',+ headers: { 'X-CSRFToken': csrfToken }+ });+ const result = await response.json();+ if (!response.ok) {+ throw new Error(result.error || t('exportTemplates.bulkExportFailed'));+ }+ const msg = t('exportTemplates.bulkExportResult', { exported: result.exported, total: result.total });+ if (statusEl) {+ statusEl.textContent = msg;+ statusEl.classList.remove('hidden', 'text-red-500');+ statusEl.style.color = 'var(--text-secondary)';+ }+ showToast(msg, 'success');+ } catch (error) {+ console.error('Bulk export error:', error);+ const msg = (error && error.message) || t('exportTemplates.bulkExportFailed');+ if (statusEl) {+ statusEl.textContent = msg;+ statusEl.classList.remove('hidden');+ statusEl.style.color = 'var(--color-danger, #ef4444)';+ }+ showToast(t('exportTemplates.bulkExportFailed'), 'error');+ } finally {+ btn.disabled = false;+ btn.innerHTML = original;+ }+ });+// ============================================// Naming Templates Management// ============================================diff --git a/templates/components/detail/desktop-transcription-panel.html b/templates/components/detail/desktop-transcription-panel.htmlindex b6b141cd..53263480 100644--- a/templates/components/detail/desktop-transcription-panel.html+++ b/templates/components/detail/desktop-transcription-panel.html@@ -53,6 +53,17 @@data-download-dropdownclass="absolute right-0 top-full mt-1 surface-raised z-50 overflow-hidden whitespace-nowrap"style="min-width: 220px;">+ <!-- Output format toggle (TXT / MD) — a persisted preference+ applied to whichever download action is chosen below. -->+ <div class="flex items-center justify-between gap-2 px-3 py-2 border-b border-[var(--border-primary)]">+ <span class="text-xs text-[var(--text-muted)]" v-text="t('transcriptTemplates.format')"></span>+ <div class="inline-flex rounded-md overflow-hidden border border-[var(--border-primary)]">+ <button @click.stop="transcriptDownloadFormat = 'txt'"+ :class="['px-2.5 py-1 text-xs transition-colors', transcriptDownloadFormat === 'txt' ? 'bg-[var(--text-accent)] text-white' : 'hover:bg-[var(--bg-tertiary)]']">TXT</button>+ <button @click.stop="transcriptDownloadFormat = 'md'"+ :class="['px-2.5 py-1 text-xs transition-colors border-l border-[var(--border-primary)]', transcriptDownloadFormat === 'md' ? 'bg-[var(--text-accent)] text-white' : 'hover:bg-[var(--bg-tertiary)]']">MD</button>+ </div>+ </div><button @click="downloadWithDefaultTemplate(); showDownloadMenu = false"class="w-full text-left px-3 py-2 text-sm hover:bg-[var(--bg-tertiary)] transition-colors flex items-center gap-2"><i class="fas fa-star text-[var(--text-accent)] text-[10px]"></i>diff --git a/templates/components/sidebar.html b/templates/components/sidebar.htmlindex f3d4dd54..9eab6482 100644--- a/templates/components/sidebar.html+++ b/templates/components/sidebar.html@@ -629,6 +629,13 @@<i class="fas fa-redo text-[var(--text-muted)]"></i></button>+ <button v-if="selectedCount >= 2"+ @click="openBulkMergeModal"+ class="w-10 h-10 flex items-center justify-center bg-[var(--bg-tertiary)] hover:bg-[var(--bg-input)] rounded-lg transition-colors border border-[var(--border-secondary)]"+ :title="t('mergeRecordings.title')">+ <i class="fas fa-object-group text-purple-500"></i>+ </button>+<div class="border-t border-[var(--border-primary)] my-1"></div><button @click="openBulkDeleteModal"diff --git a/templates/index.html b/templates/index.htmlindex 80ec13cb..011aaf77 100644--- a/templates/index.html+++ b/templates/index.html@@ -182,6 +182,7 @@{% include 'modals/bulk-delete-modal.html' %}{% include 'modals/bulk-tag-modal.html' %}{% include 'modals/bulk-reprocess-modal.html' %}+ {% include 'modals/bulk-merge-modal.html' %}</div><!-- CSRF Token Management -->diff --git a/templates/modals/bulk-action-bar.html b/templates/modals/bulk-action-bar.htmldeleted file mode 100644index 572433c2..00000000--- a/templates/modals/bulk-action-bar.html+++ /dev/null@@ -1,79 +0,0 @@-<!-- Bulk Action Bar - Fixed at bottom of sidebar when in selection mode -->-<transition name="slide-up">- <div v-if="selectionMode && selectedCount > 0"- class="fixed bottom-0 left-0 w-80 bg-[var(--bg-secondary)] border-t border-r border-[var(--border-primary)] shadow-lg z-50 transform transition-transform duration-300"- :class="[- { 'translate-y-full': bulkActionInProgress },- isSidebarCollapsed ? '-translate-x-full' : ''- ]">- <div class="px-3 py-2">- <!-- Compact vertical layout for sidebar width -->- <div class="flex flex-col gap-2">- <!-- Selection info row -->- <div class="flex items-center justify-between">- <span class="text-sm font-medium text-[var(--text-primary)]">- ${ selectedCount } selected- </span>- <div class="flex items-center gap-2">- <button @click="allVisibleSelected ? clearSelection() : selectAll()"- class="text-xs text-[var(--text-accent)] hover:underline">- ${ allVisibleSelected ? 'Clear' : 'All' }- </button>- <button @click="exitSelectionMode"- class="p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] rounded transition-colors"- title="Exit selection mode">- <i class="fas fa-times text-xs"></i>- </button>- </div>- </div>-- <!-- Action buttons row -->- <div class="flex items-center justify-between gap-1">- <button @click="openBulkTagModal('add')"- class="flex-1 px-2 py-1.5 text-xs bg-[var(--bg-tertiary)] hover:bg-[var(--bg-input)] rounded-md transition-colors flex items-center justify-center gap-1"- title="Add or remove tags">- <i class="fas fa-tags text-[var(--text-muted)]"></i>- <span>Tags</span>- </button>-- <button @click="bulkToggleInbox()"- class="flex-1 px-2 py-1.5 text-xs bg-[var(--bg-tertiary)] hover:bg-[var(--bg-input)] rounded-md transition-colors flex items-center justify-center gap-1"- title="Toggle inbox status">- <i class="fas fa-inbox text-blue-500"></i>- <span>Inbox</span>- </button>-- <button @click="bulkToggleHighlight()"- class="flex-1 px-2 py-1.5 text-xs bg-[var(--bg-tertiary)] hover:bg-[var(--bg-input)] rounded-md transition-colors flex items-center justify-center gap-1"- title="Toggle highlight">- <i class="fas fa-star text-amber-500"></i>- <span>Star</span>- </button>-- <button @click="openBulkReprocessModal"- class="flex-1 px-2 py-1.5 text-xs bg-[var(--bg-tertiary)] hover:bg-[var(--bg-input)] rounded-md transition-colors flex items-center justify-center gap-1"- title="Reprocess">- <i class="fas fa-redo text-[var(--text-muted)]"></i>- <span>Redo</span>- </button>-- <button @click="openBulkDeleteModal"- class="flex-1 px-2 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-md transition-colors flex items-center justify-center gap-1"- title="Delete selected">- <i class="fas fa-trash"></i>- <span>Delete</span>- </button>- </div>- </div>- </div>-- <!-- Loading overlay -->- <div v-if="bulkActionInProgress"- class="absolute inset-0 bg-[var(--bg-secondary)] bg-opacity-80 flex items-center justify-center">- <div class="flex items-center gap-2">- <i class="fas fa-spinner fa-spin text-[var(--text-accent)]"></i>- <span class="text-xs text-[var(--text-secondary)]">Processing...</span>- </div>- </div>- </div>-</transition>diff --git a/templates/modals/bulk-merge-modal.html b/templates/modals/bulk-merge-modal.htmlnew file mode 100644index 00000000..c6f57d65--- /dev/null+++ b/templates/modals/bulk-merge-modal.html@@ -0,0 +1,76 @@+<!-- Bulk Merge Modal (issue #323) -->+<div v-if="showBulkMergeModal" @click.self="closeBulkMergeModal" class="modal-overlay">+ <div class="modal-panel modal-panel--md">+ <div class="modal-header">+ <i class="fas fa-object-group text-2xl text-purple-500"></i>+ <div class="flex-1">+ <h3 class="modal-title" v-text="t('mergeRecordings.title')"></h3>+ <div class="modal-subtitle" v-text="t('mergeRecordings.subtitle')"></div>+ </div>+ <button @click="closeBulkMergeModal" class="modal-close" :title="t('buttons.close')"><i class="fas fa-times"></i></button>+ </div>+ <div class="modal-body">+ <p class="t-meta mb-4" v-text="t('mergeRecordings.orderHint')"></p>++ <!-- Ordered source list -->+ <div class="space-y-2 mb-5">+ <div v-for="(rec, index) in mergeOrderedList" :key="rec.id"+ 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-meta truncate" v-if="rec.meeting_date">${ formatDisplayDate(rec.meeting_date) }</div>+ </div>+ <div class="flex flex-col gap-0.5 flex-shrink-0">+ <button @click="moveMergeItem(index, -1)" :disabled="index === 0"+ class="px-2 py-0.5 text-xs rounded hover:bg-[var(--bg-tertiary)] transition-colors disabled:opacity-30 disabled:cursor-not-allowed"+ :title="t('mergeRecordings.moveUp')">+ <i class="fas fa-chevron-up"></i>+ </button>+ <button @click="moveMergeItem(index, 1)" :disabled="index === mergeOrderedList.length - 1"+ class="px-2 py-0.5 text-xs rounded hover:bg-[var(--bg-tertiary)] transition-colors disabled:opacity-30 disabled:cursor-not-allowed"+ :title="t('mergeRecordings.moveDown')">+ <i class="fas fa-chevron-down"></i>+ </button>+ </div>+ </div>+ </div>++ <!-- Title -->+ <div class="mb-4">+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1" v-text="t('mergeRecordings.titleLabel')"></label>+ <input type="text" v-model="mergeTitle"+ class="w-full px-3 py-2 bg-[var(--bg-input)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]"+ :placeholder="t('mergeRecordings.titlePlaceholder')">+ </div>++ <!-- Delete originals -->+ <label class="flex items-start gap-3 p-3 rounded-md border border-[var(--border-primary)] cursor-pointer hover:bg-[var(--bg-tertiary)] transition-colors">+ <input type="checkbox" v-model="mergeDeleteOriginals" class="mt-1">+ <div>+ <span class="t-body-strong" v-text="t('mergeRecordings.deleteOriginals')"></span>+ <p class="t-meta mt-0.5" v-text="t('mergeRecordings.deleteOriginalsHint')"></p>+ </div>+ </label>++ <div class="banner banner--warn mt-4" style="display: flex; align-items: flex-start; gap: var(--sp-2);">+ <i class="fas fa-info-circle" style="margin-top: 2px;"></i>+ <div class="t-meta" v-text="t('mergeRecordings.reprocessNote')"></div>+ </div>++ <!-- Shown only when a video source is selected: the merged output is audio-only. -->+ <div v-if="mergeOrderedList.some(r => (r.mime_type || '').startsWith('video'))"+ class="banner banner--warn mt-2" style="display: flex; align-items: flex-start; gap: var(--sp-2);">+ <i class="fas fa-video" style="margin-top: 2px;"></i>+ <div class="t-meta" v-text="t('mergeRecordings.videoNote')"></div>+ </div>+ </div>+ <div class="modal-footer">+ <button @click="closeBulkMergeModal" class="btn btn--ghost" v-text="t('buttons.cancel')"></button>+ <button @click="executeBulkMerge" class="btn btn--primary" :disabled="mergeInProgress || mergeOrderedList.length < 2">+ <i class="fas" :class="mergeInProgress ? 'fa-spinner fa-spin' : 'fa-object-group'"></i>+ <span v-text="mergeInProgress ? t('mergeRecordings.merging') : t('mergeRecordings.confirm')"></span>+ </button>+ </div>+ </div>+</div>diff --git a/tests/test_merge_export_features.py b/tests/test_merge_export_features.pynew file mode 100644index 00000000..0f237b6b--- /dev/null+++ b/tests/test_merge_export_features.py@@ -0,0 +1,385 @@+"""Tests for the v0.9.6 export/merge features.++Covers:+ - #322 Markdown transcript export: ?format=md on /download/transcript+ - #321 Bulk export existing recordings to disk: /api/recordings/export-existing+ - #323 Merge recordings: /api/recordings/merge + src.services.recording_merge++External effects (ffmpeg, storage, job queue, file_exporter) are mocked so the+suite touches no real storage and shells out to nothing.++SHARED-DB: every assertion is scoped to the user/recordings the test created.+"""++import os+import sys+import uuid+from contextlib import contextmanager+from unittest.mock import patch, MagicMock++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from src.app import app, db+from src.models import User, Recording, Tag, RecordingTag++app.config["WTF_CSRF_ENABLED"] = False+++# --------------------------------------------------------------------------- #+# Helpers+# --------------------------------------------------------------------------- #++def _mk_user(prefix="mx"):+ suffix = uuid.uuid4().hex[:8]+ user = User(username=f"{prefix}_{suffix}", email=f"{prefix}_{suffix}@local.test", password="x")+ db.session.add(user)+ db.session.commit()+ return user+++def _login(client, user):+ with client.session_transaction() as sess:+ sess["_user_id"] = str(user.id)+ sess["_fresh"] = True+++def _mk_recording(user, **kwargs):+ rec = Recording(+ user_id=user.id,+ title=kwargs.pop("title", f"rec_{uuid.uuid4().hex[:8]}"),+ status=kwargs.pop("status", "COMPLETED"),+ audio_path=kwargs.pop("audio_path", "local://recordings/x.mp3"),+ original_filename=kwargs.pop("original_filename", "x.mp3"),+ **kwargs,+ )+ db.session.add(rec)+ db.session.commit()+ return rec+++# --------------------------------------------------------------------------- #+# #322 — Markdown transcript export+# --------------------------------------------------------------------------- #++def test_transcript_download_markdown_format():+ with app.app_context():+ user = _mk_user()+ rec = _mk_recording(user, title="Weekly Sync", transcription="Alice: hello\nBob: hi")+ client = app.test_client()+ _login(client, user)++ resp = client.get(f"/recording/{rec.id}/download/transcript?format=md")+ assert resp.status_code == 200+ assert resp.headers["Content-Type"].startswith("text/markdown")+ assert resp.headers["Content-Disposition"].endswith('.md"')+ body = resp.get_data(as_text=True)+ assert body.startswith("# Weekly Sync")+ assert "Alice: hello" in body+++def test_transcript_download_txt_default_unchanged():+ with app.app_context():+ user = _mk_user()+ rec = _mk_recording(user, title="Plain One", transcription="just some text")+ client = app.test_client()+ _login(client, user)++ resp = client.get(f"/recording/{rec.id}/download/transcript")+ assert resp.status_code == 200+ assert resp.headers["Content-Type"].startswith("text/plain")+ assert resp.headers["Content-Disposition"].endswith('.txt"')+ body = resp.get_data(as_text=True)+ # No markdown heading injected in txt mode+ assert not body.startswith("# ")+++def test_transcript_download_invalid_format_falls_back_to_txt():+ with app.app_context():+ user = _mk_user()+ rec = _mk_recording(user, title="X", transcription="text")+ client = app.test_client()+ _login(client, user)+ resp = client.get(f"/recording/{rec.id}/download/transcript?format=bogus")+ assert resp.status_code == 200+ assert resp.headers["Content-Type"].startswith("text/plain")+++# --------------------------------------------------------------------------- #+# #321 — Bulk export existing recordings+# --------------------------------------------------------------------------- #++def test_bulk_export_disabled_returns_400():+ with app.app_context():+ user = _mk_user()+ client = app.test_client()+ _login(client, user)+ with patch("src.file_exporter.ENABLE_AUTO_EXPORT", False):+ resp = client.post("/api/recordings/export-existing")+ assert resp.status_code == 400+++def test_bulk_export_exports_completed_recordings():+ with app.app_context():+ user = _mk_user()+ r1 = _mk_recording(user, transcription="a", status="COMPLETED")+ r2 = _mk_recording(user, summary="s", status="COMPLETED")+ # Not exportable: no transcription/summary+ _mk_recording(user, status="COMPLETED", transcription=None, summary=None)+ # Not exportable: not completed+ _mk_recording(user, transcription="x", status="PROCESSING")+ client = app.test_client()+ _login(client, user)++ exported_ids = []++ def _fake_export(rid):+ exported_ids.append(rid)+ return f"/data/exports/user/recording_{rid}.md"++ with patch("src.file_exporter.ENABLE_AUTO_EXPORT", True), \+ patch("src.file_exporter.export_recording", side_effect=_fake_export):+ resp = client.post("/api/recordings/export-existing")++ assert resp.status_code == 200+ data = resp.get_json()+ assert data["exported"] == 2+ assert data["total"] == 2+ assert set(exported_ids) == {r1.id, r2.id}+++def test_bulk_export_only_touches_own_recordings():+ with app.app_context():+ me = _mk_user()+ other = _mk_user()+ mine = _mk_recording(me, transcription="a", status="COMPLETED")+ _mk_recording(other, transcription="b", status="COMPLETED")+ client = app.test_client()+ _login(client, me)++ seen = []+ with patch("src.file_exporter.ENABLE_AUTO_EXPORT", True), \+ patch("src.file_exporter.export_recording", side_effect=lambda rid: seen.append(rid) or "p"):+ resp = client.post("/api/recordings/export-existing")++ assert resp.status_code == 200+ assert seen == [mine.id]+++# --------------------------------------------------------------------------- #+# #323 — Merge recordings+# --------------------------------------------------------------------------- #++class _FakeStoredObject:+ def __init__(self, locator, key):+ self.locator = locator+ self.key = key+ self.size = 1024+ self.content_type = None+ self.etag = None+++class _FakeMaterialized:+ def __init__(self, path):+ self.local_path = path+++class _FakeStorage:+ def __init__(self):+ self.deleted = []++ def exists(self, locator):+ return True++ @contextmanager+ def materialize(self, locator):+ yield _FakeMaterialized(f"/tmp/{uuid.uuid4().hex}.wav")++ def build_recording_key(self, original_filename, recording_id=None, *, now=None):+ return f"recordings/test/{recording_id}/{original_filename}"++ def upload_local_file(self, local_path, key, *, content_type=None, delete_source=False):+ return _FakeStoredObject(locator=f"local://{key}", key=key)++ def delete(self, locator, missing_ok=True):+ self.deleted.append(locator)+ return True+++@contextmanager+def _endpoint_mocks():+ """Mock only the enqueue for the request-phase (create_merge_recording).+ The endpoint does NO ffmpeg — that is deferred to the worker."""+ with patch("src.services.recording_merge.get_storage_service", return_value=_FakeStorage()), \+ patch("src.services.recording_merge.job_queue.enqueue", return_value=1) as enqueue_mock:+ yield enqueue_mock+++@contextmanager+def _worker_mocks():+ """Mock the worker-phase (run_merge_job): storage + ffmpeg concat + enqueue."""+ fake_storage = _FakeStorage()++ def _fake_concat(input_paths, output_path):+ with open(output_path, "wb") as f:+ f.write(b"\x00" * 2048)++ with patch("src.services.recording_merge.get_storage_service", return_value=fake_storage), \+ patch("src.services.recording_merge._concat_audio", side_effect=_fake_concat), \+ patch("src.services.recording_merge.job_queue.enqueue", return_value=1) as enqueue_mock:+ yield fake_storage, enqueue_mock+++def test_merge_requires_two_recordings():+ with app.app_context():+ user = _mk_user()+ client = app.test_client()+ _login(client, user)+ r1 = _mk_recording(user)+ resp = client.post("/api/recordings/merge", json={"recording_ids": [r1.id]})+ assert resp.status_code == 400+++def test_merge_endpoint_creates_processing_recording_and_enqueues_merge_job():+ with app.app_context():+ user = _mk_user()+ tag = Tag(name=f"t_{uuid.uuid4().hex[:6]}", user_id=user.id)+ db.session.add(tag)+ db.session.commit()+ r1 = _mk_recording(user, title="Part 1")+ db.session.add(RecordingTag(recording_id=r1.id, tag_id=tag.id, order=1))+ db.session.commit()+ r2 = _mk_recording(user, title="Part 2")+ client = app.test_client()+ _login(client, user)++ with _endpoint_mocks() as enqueue:+ resp = client.post("/api/recordings/merge",+ json={"recording_ids": [r1.id, r2.id]})++ assert resp.status_code == 200, resp.get_data(as_text=True)+ data = resp.get_json()+ new_id = data["recording_id"]+ assert new_id not in (r1.id, r2.id)++ merged = db.session.get(Recording, new_id)+ assert merged.processing_source == "merge"+ # Non-terminal: enqueue() would set QUEUED; create sets it too.+ assert merged.status == "QUEUED"+ assert merged.mime_type == "audio/mp4"+ # No audio yet — concat happens on the worker+ assert merged.audio_path is None+ # Inherited the first source's tag+ assert tag.id in [t.id for t in merged.tags]+ # Sources preserved and untouched at request time+ assert db.session.get(Recording, r1.id) is not None+ assert db.session.get(Recording, r2.id) is not None+ # A 'merge' job was enqueued carrying the ordered source ids+ enqueue.assert_called_once()+ kwargs = enqueue.call_args.kwargs+ assert kwargs["job_type"] == "merge"+ assert kwargs["params"]["source_ids"] == [r1.id, r2.id]+++def test_merge_endpoint_rejects_processing_source():+ with app.app_context():+ user = _mk_user()+ r1 = _mk_recording(user, title="Done", status="COMPLETED")+ r2 = _mk_recording(user, title="Busy", status="PROCESSING")+ client = app.test_client()+ _login(client, user)+ with _endpoint_mocks():+ resp = client.post("/api/recordings/merge",+ json={"recording_ids": [r1.id, r2.id]})+ assert resp.status_code == 400+ assert "processing" in resp.get_json()["error"].lower()+++def test_merge_endpoint_rejects_other_users_recording():+ with app.app_context():+ me = _mk_user()+ other = _mk_user()+ mine = _mk_recording(me, title="Mine")+ theirs = _mk_recording(other, title="Theirs")+ client = app.test_client()+ _login(client, me)+ with _endpoint_mocks():+ resp = client.post("/api/recordings/merge",+ json={"recording_ids": [mine.id, theirs.id]})+ assert resp.status_code == 400+++def test_merge_endpoint_custom_title_applied():+ with app.app_context():+ user = _mk_user()+ r1 = _mk_recording(user, title="A")+ r2 = _mk_recording(user, title="B")+ client = app.test_client()+ _login(client, user)+ with _endpoint_mocks():+ resp = client.post("/api/recordings/merge",+ json={"recording_ids": [r1.id, r2.id], "title": "Combined Call"})+ assert resp.status_code == 200+ merged = db.session.get(Recording, resp.get_json()["recording_id"])+ assert merged.title == "Combined Call"+++def test_run_merge_job_concats_uploads_and_enqueues_transcribe():+ from src.services.recording_merge import create_merge_recording, run_merge_job+ with app.app_context():+ user = _mk_user()+ r1 = _mk_recording(user, title="A")+ r2 = _mk_recording(user, title="B")+ with _endpoint_mocks():+ merged = create_merge_recording(user, [r1.id, r2.id])++ params = {"source_ids": [r1.id, r2.id], "delete_originals": False}+ with _worker_mocks() as (storage, enqueue):+ run_merge_job(merged, params)++ db.session.refresh(merged)+ assert merged.audio_path.startswith("local://")+ assert merged.file_size and merged.file_size > 0+ # Sources kept+ assert db.session.get(Recording, r1.id) is not None+ # Transcription queued+ enqueue.assert_called_once()+ assert enqueue.call_args.kwargs["job_type"] == "transcribe"+++def test_run_merge_job_delete_originals_removes_sources_after_concat():+ from src.services.recording_merge import create_merge_recording, run_merge_job+ with app.app_context():+ user = _mk_user()+ r1 = _mk_recording(user, title="A")+ r2 = _mk_recording(user, title="B")+ with _endpoint_mocks():+ merged = create_merge_recording(user, [r1.id, r2.id], delete_originals=True)++ params = {"source_ids": [r1.id, r2.id], "delete_originals": True}+ with _worker_mocks():+ run_merge_job(merged, params)++ assert db.session.get(Recording, r1.id) is None+ assert db.session.get(Recording, r2.id) is None+ # Merged recording itself survives+ assert db.session.get(Recording, merged.id) is not None+++def test_run_merge_job_empty_output_raises():+ from src.services.recording_merge import create_merge_recording, run_merge_job, MergeError+ import pytest+ with app.app_context():+ user = _mk_user()+ r1 = _mk_recording(user, title="A")+ r2 = _mk_recording(user, title="B")+ with _endpoint_mocks():+ merged = create_merge_recording(user, [r1.id, r2.id])++ def _empty_concat(input_paths, output_path):+ open(output_path, "wb").close() # zero-byte++ with patch("src.services.recording_merge.get_storage_service", return_value=_FakeStorage()), \+ patch("src.services.recording_merge._concat_audio", side_effect=_empty_concat), \+ 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]})