Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Lifecycle webhooks from every path (#412 audit P11, P12): recording.created from the share target, watch folder, merge and session finalize too; the summary step reports summary.completed / summary.failed itself (first summaries now fire, failed summaries no longer report completed)
Murtaza Nasirc53f4f0060be
diff --git a/src/api/recording_sessions.py b/src/api/recording_sessions.pyindex 91b40588..abb38622 100644--- a/src/api/recording_sessions.py+++ b/src/api/recording_sessions.py@@ -292,6 +292,8 @@ def _finalize_session_into_stitch(session, *, user_id, title, notes=None,session.finalized_recording_id = recording.idsession.last_seen_at = datetime.utcnow()db.session.commit()+ from src.services.webhook_dispatch import emit_recording_created+ emit_recording_created(recording)try:job_queue.enqueue(diff --git a/src/api/recordings.py b/src/api/recordings.pyindex 2071c588..20450661 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -2145,6 +2145,8 @@ def share_target():)db.session.add(recording)db.session.commit()+ from src.services.webhook_dispatch import emit_recording_created+ emit_recording_created(recording)# Enqueue transcription through the shared resolver so a shared file honors# the same account defaults (and any future tag/folder context) as every@@ -2829,20 +2831,8 @@ def ingest_uploaded_recording(# Webhook event (#275). Fan-out happens off-request via the# dispatcher; this call only enqueues a delivery row per matching# subscription, so it is cheap and safe inside the request path.- try:- from src.services.webhook_dispatch import emit_webhook_event- emit_webhook_event(- user_id=owner.id,- event_type='recording.created',- data={- 'recording_id': recording.id,- 'title': recording.title,- 'file_size': recording.file_size,- 'original_filename': recording.original_filename,- },- )- except Exception as e:- current_app.logger.warning(f"Webhook emit (recording.created) failed: {e}")+ from src.services.webhook_dispatch import emit_recording_created+ emit_recording_created(recording)response_data = recording.to_dict(viewer_user=owner)if duplicate_warning:@@ -2911,16 +2901,8 @@ def _ingest_join_part(owner, join, filepath, storage, now, *, original_filename,owner, parts, title=title, notes=notes, folder=folder, tags=tags,prompt_variables=prompt_variables, transcribe_params=transcribe_params)current_app.logger.info(f"Joined {count} uploaded files into recording {recording.id}")- try:- from src.services.webhook_dispatch import emit_webhook_event- emit_webhook_event(- user_id=owner.id,- event_type='recording.created',- data={'recording_id': recording.id, 'title': recording.title,- 'file_size': recording.file_size, 'original_filename': recording.original_filename},- )- except Exception as e:- current_app.logger.warning(f"Webhook emit (recording.created) failed: {e}")+ from src.services.webhook_dispatch import emit_recording_created+ emit_recording_created(recording)response_data = recording.to_dict(viewer_user=owner)response_data['joined_parts'] = countif duplicate_warning:diff --git a/src/file_monitor.py b/src/file_monitor.pyindex 1811d1e3..99b49563 100644--- a/src/file_monitor.py+++ b/src/file_monitor.py@@ -534,6 +534,8 @@ class FileMonitor:self.logger.info(f"Applied tag '{tag.name}' (id={tag_id}) to recording {recording.id}")db.session.commit()+ from src.services.webhook_dispatch import emit_recording_created+ emit_recording_created(recording)# Resolve transcribe params through the shared chain so an# auto-processed file honors the same tag/folder/env/accountdiff --git a/src/services/job_queue.py b/src/services/job_queue.pyindex 99efb120..6b40952e 100644--- a/src/services/job_queue.py+++ b/src/services/job_queue.py@@ -790,11 +790,13 @@ class FairJobQueue:# --- Webhook emission helpers (#275) ---------------------------------+ # recording.summary.completed is emitted by the summary step itself+ # (processing.generate_summary_only_task, #412): a summary job can end with+ # a FAILED summary, and the first summary of an upload runs inside the+ # transcribe job, so the job type alone cannot say whether a summary exists._COMPLETION_EVENT_MAP = {'transcribe': 'recording.transcription.completed',- 'summarize': 'recording.summary.completed','reprocess_transcription': 'recording.transcription.completed',- 'reprocess_summary': 'recording.summary.completed',}_FAILURE_EVENT_MAP = {diff --git a/src/services/recording_merge.py b/src/services/recording_merge.pyindex a9cfa9a6..05652700 100644--- a/src/services/recording_merge.py+++ b/src/services/recording_merge.py@@ -266,6 +266,8 @@ def create_merge_recording(user, recording_ids, title=None, delete_originals=Falorder += 1db.session.commit()+ from src.services.webhook_dispatch import emit_recording_created+ emit_recording_created(recording)try:job_queue.enqueue(diff --git a/src/services/webhook_dispatch.py b/src/services/webhook_dispatch.pyindex ef978f7e..9aae3f4b 100644--- a/src/services/webhook_dispatch.py+++ b/src/services/webhook_dispatch.py@@ -679,3 +679,53 @@ def start_dispatcher_thread(app):t.start()_dispatcher_thread_started = Trueapp.logger.info("✅ Webhook dispatcher thread initialized")+++def emit_recording_created(recording):+ """recording.created, from every path that creates a recording (#412 audit P11).++ Upload, upload join, API v1 and integration uploads, the share target, the+ watch folder, merges and recording-session finalize all call this, so a+ subscriber hears about every new recording. Best-effort: never raises.+ """+ try:+ emit_webhook_event(+ user_id=recording.user_id,+ event_type='recording.created',+ data={+ 'recording_id': recording.id,+ 'title': recording.title,+ 'file_size': recording.file_size,+ 'original_filename': recording.original_filename,+ },+ )+ except Exception as e:+ logger.warning(f"Webhook emit (recording.created) failed for {getattr(recording, 'id', None)}: {e}")+++def emit_summary_result(recording, ok, error=None):+ """recording.summary.completed / .failed from the summary step itself (#412 audit P12).++ The job queue used to infer these from the job type: the first summary of+ an upload (run inside the transcription job) never fired, a summary that+ failed inside its job fired "completed", and "failed" never fired.+ Best-effort: never raises.+ """+ try:+ if ok:+ data = {+ 'recording_id': recording.id,+ 'title': recording.title,+ 'language': recording.transcription_language,+ 'audio_duration_seconds': recording.audio_duration_seconds,+ 'transcription_duration_seconds': recording.transcription_duration_seconds,+ 'summarization_duration_seconds': recording.summarization_duration_seconds,+ }+ emit_webhook_event(user_id=recording.user_id, event_type='recording.summary.completed',+ data={k: v for k, v in data.items() if v is not None})+ else:+ emit_webhook_event(user_id=recording.user_id, event_type='recording.summary.failed',+ data={'recording_id': recording.id, 'title': recording.title,+ 'error': (error or '')[:500]})+ except Exception as e:+ logger.warning(f"Webhook emit (summary result) failed for {getattr(recording, 'id', None)}: {e}")diff --git a/src/tasks/processing.py b/src/tasks/processing.pyindex d1c8e81d..75ce9861 100644--- a/src/tasks/processing.py+++ b/src/tasks/processing.py@@ -641,6 +641,8 @@ def generate_summary_only_task(app_context, recording_id, custom_prompt_overridecurrent_app.logger.warning(f"Skipping summary generation for {recording_id}: OpenRouter client not configured.")recording.summary = "[Summary skipped: OpenRouter client not configured]"db.session.commit()+ from src.services.webhook_dispatch import emit_summary_result+ emit_summary_result(recording, ok=False, error="LLM client not configured")returnrecording.status = 'SUMMARIZING'@@ -654,6 +656,8 @@ def generate_summary_only_task(app_context, recording_id, custom_prompt_overriderecording.summary = "[Summary skipped due to short transcription]"db.session.commit()finish_processing(recording_id)+ from src.services.webhook_dispatch import emit_summary_result+ emit_summary_result(db.session.get(Recording, recording_id), ok=True)return# Get user preferences and tag custom prompts@@ -937,6 +941,8 @@ Summarization Instructions:# overwrite a good summary with an error.finish_processing(recording_id, events_transcript=formatted_transcription,events_summary=summary or None)+ from src.services.webhook_dispatch import emit_summary_result+ emit_summary_result(db.session.get(Recording, recording_id), ok=True)except Exception as e:error_msg = format_api_error_message(str(e))@@ -944,6 +950,8 @@ Summarization Instructions:recording.summary = error_msgrecording.status = 'FAILED'db.session.commit()+ from src.services.webhook_dispatch import emit_summary_result+ emit_summary_result(recording, ok=False, error=error_msg)def extract_events_from_transcript(recording_id, transcript_text, summary_text):diff --git a/tests/test_cov_job_queue.py b/tests/test_cov_job_queue.pyindex 5b888b9d..3bbb8602 100644--- a/tests/test_cov_job_queue.py+++ b/tests/test_cov_job_queue.py@@ -702,9 +702,14 @@ def test_emit_completion_webhook_dispatches_event(track):rid = _make_recording(uid); track.recording_ids.append(rid)with patch("src.services.webhook_dispatch.emit_webhook_event") as emit:- job_queue._emit_completion_webhook("summarize", rid)+ job_queue._emit_completion_webhook("transcribe", rid)emit.assert_called_once()- assert emit.call_args[1]["event_type"] == "recording.summary.completed"+ assert emit.call_args[1]["event_type"] == "recording.transcription.completed"+ # recording.summary.completed comes from the summary step itself (#412),+ # not from the job type.+ with patch("src.services.webhook_dispatch.emit_webhook_event") as emit:+ job_queue._emit_completion_webhook("summarize", rid)+ emit.assert_not_called()def test_emit_failure_webhook_dispatches_event_and_truncates(track):diff --git a/tests/test_lifecycle_webhooks.py b/tests/test_lifecycle_webhooks.pynew file mode 100644index 00000000..4a3436f5--- /dev/null+++ b/tests/test_lifecycle_webhooks.py@@ -0,0 +1,121 @@+"""Lifecycle webhooks from every path (#412 audit P11, P12).++P11: recording.created fired only for /upload, upload join and the v1/ASR+uploads. The share target, watch folder, merge and recording-session finalize+now call the same emit_recording_created helper.+P12: the summary step reports its own result. The first summary of an upload+(run inside the transcription job) now fires recording.summary.completed, and+a failed summary fires recording.summary.failed instead of "completed".++SHARED-DB: users and recordings are removed afterwards.+"""++import ast+import os+import sys+import uuid+from unittest.mock import MagicMock, patch++import pytest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from src.app import app, db+from src.models import Recording, User+import src.tasks.processing as proc++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+++def rec():+ with app.app_context():+ s = uuid.uuid4().hex[:8]+ u = User(username=f"lc_{s}", email=f"lc_{s}@local.test", password="x")+ db.session.add(u)+ db.session.commit()+ r = Recording(user_id=u.id, title="Sync", original_filename="s.wav", status="PROCESSING",+ transcription="Speaker 1: " + "we agreed on the plan. " * 5)+ db.session.add(r)+ db.session.commit()+ ids = (u.id, r.id)+ yield ids+ with app.app_context():+ for model, oid in ((Recording, ids[1]), (User, ids[0])):+ obj = db.session.get(model, oid)+ if obj is not None:+ db.session.delete(obj)+ db.session.commit()+++def _quiet():+ return (patch.object(proc, "apply_team_tag_auto_shares"), patch.object(proc, "export_recording"),+ patch.object(proc, "process_recording_chunks"), patch.object(proc, "extract_events_from_transcript"))+++def _completion(text):+ return MagicMock(choices=[MagicMock(message=MagicMock(content=text, reasoning=None))])+++def test_a_summary_fires_summary_completed(rec):+ _, rid = rec+ a, b, c, d = _quiet()+ with app.app_context(), a, b, c, d, patch.object(proc, "client", MagicMock()), \+ patch.object(proc, "call_llm_completion", return_value=_completion("## Summary")), \+ patch("src.services.webhook_dispatch.emit_webhook_event") as emit:+ proc.generate_summary_only_task(app.app_context(), rid)+ types = [call.kwargs["event_type"] for call in emit.call_args_list]+ assert types.count("recording.summary.completed") == 1+ assert "recording.summary.failed" not in types+++def test_a_failed_summary_fires_summary_failed(rec):+ _, rid = rec+ a, b, c, d = _quiet()+ with app.app_context(), a, b, c, d, patch.object(proc, "client", MagicMock()), \+ patch.object(proc, "call_llm_completion", side_effect=RuntimeError("model unavailable")), \+ patch("src.services.webhook_dispatch.emit_webhook_event") as emit:+ proc.generate_summary_only_task(app.app_context(), rid)+ calls = [call for call in emit.call_args_list if call.kwargs["event_type"].startswith("recording.summary")]+ assert [c.kwargs["event_type"] for c in calls] == ["recording.summary.failed"]+ assert calls[0].kwargs["data"]["recording_id"] == rid+++def test_every_creation_path_emits_recording_created():+ """Each module that constructs a Recording row must call emit_recording_created."""+ creators = {+ "src/api/recordings.py": ("upload_file/ingest", "share target"),+ "src/file_monitor.py": ("watch folder",),+ "src/services/recording_merge.py": ("merge",),+ "src/api/recording_sessions.py": ("session finalize",),+ "src/services/upload_join.py": (),+ }+ missing = []+ for rel in creators:+ src = open(os.path.join(ROOT, rel), encoding="utf-8").read()+ constructs = any(isinstance(n, ast.Call) and getattr(n.func, "id", None) == "Recording"+ for n in ast.walk(ast.parse(src)))+ if constructs and rel != "src/services/upload_join.py" and "emit_recording_created(" not in src:+ missing.append(rel)+ assert not missing, f"Recording created without recording.created: {missing}"+ # upload join emits from the /upload route after create_joined_recording+ assert "emit_recording_created(recording)" in open(os.path.join(ROOT, "src/api/recordings.py")).read()+++def test_merge_emits_recording_created(rec):+ uid, rid = rec+ from src.services import recording_merge+ with app.app_context():+ user = db.session.get(User, uid)+ a = db.session.get(Recording, rid)+ b = Recording(user_id=uid, title="Sync 2", original_filename="t.wav", status="COMPLETED")+ db.session.add(b)+ db.session.commit()+ with patch.object(recording_merge, "_validate_sources", return_value=[a, b]), \+ patch("src.services.webhook_dispatch.emit_webhook_event") as emit:+ merged = recording_merge.create_merge_recording(user, [a.id, b.id])+ types = [c.kwargs["event_type"] for c in emit.call_args_list]+ assert "recording.created" in types+ for obj in (merged, b):+ db.session.delete(db.session.merge(obj))+ db.session.commit()