Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Close mutation-sweep survivors (batch 1): SSO redirect, email-verify, webhook SSRF, group auto-share, inquire filters, recordings downloads, LLM tracking
Murtaza Nasir3d7444eb8d38
diff --git a/tests/test_cov_auth.py b/tests/test_cov_auth.pyindex f10e2771..47fe266f 100644--- a/tests/test_cov_auth.py+++ b/tests/test_cov_auth.py@@ -182,6 +182,31 @@ def test_logout_clears_session(cleanup_users):assert '_user_id' not in s+def test_login_blocked_when_email_unverified(cleanup_users):+ # auth.py:205 — verification required AND user not verified ⇒ login+ # is gated: the check-email page renders and no session is established.+ user = _mk_user(cleanup_users, email_verified=False)+ with mock.patch.object(auth_mod, 'is_email_verification_required', return_value=True):+ client = app.test_client()+ resp = client.post('/login', data={'email': user.email, 'password': GOOD_PW})+ assert resp.status_code == 200 # check_email page, not a login redirect+ with client.session_transaction() as s:+ assert '_user_id' not in s+++def test_login_succeeds_when_email_verified(cleanup_users):+ # The companion: even with verification required, a VERIFIED user logs+ # in. This kills the and->or mutation on auth.py:205 (under `or`, a+ # verified user would be wrongly blocked).+ user = _mk_user(cleanup_users, email_verified=True)+ with mock.patch.object(auth_mod, 'is_email_verification_required', return_value=True):+ client = app.test_client()+ resp = client.post('/login', data={'email': user.email, 'password': GOOD_PW})+ assert resp.status_code == 302+ with client.session_transaction() as s:+ assert s.get('_user_id') == str(user.id)++def test_login_sso_only_user_prompted_to_use_sso(cleanup_users):# User with no local password → account uses SSO, password login refused.user = _mk_user(cleanup_users, password=None, sso_subject="sub-" + uuid.uuid4().hex)@@ -558,6 +583,34 @@ def test_sso_login_disabled_redirects():assert '/login' in resp.headers['Location']+def test_sso_login_does_not_store_unsafe_next(cleanup_users):+ # auth.py:249 open-redirect guard — a dangerous ?next must NOT be+ # persisted to session['sso_next'] (it would be honoured after the+ # IdP round-trip). Both an absolute and a scheme-relative target.+ oauth = mock.MagicMock()+ oauth.sso.authorize_redirect.return_value = 'redirecting' # valid view return+ with _sso_on(), mock.patch.object(auth_mod, 'get_sso_client', return_value=oauth):+ for evil in ('http://evil.com', '//evil.com'):+ client = app.test_client()+ resp = client.get('/auth/sso/login', query_string={'next': evil})+ assert resp.status_code == 200+ with client.session_transaction() as s:+ assert s.get('sso_next') != evil+ assert 'sso_next' not in s+++def test_sso_login_stores_safe_next(cleanup_users):+ # The safe-path companion: a local relative target IS stored.+ oauth = mock.MagicMock()+ oauth.sso.authorize_redirect.return_value = 'redirecting'+ with _sso_on(), mock.patch.object(auth_mod, 'get_sso_client', return_value=oauth):+ client = app.test_client()+ resp = client.get('/auth/sso/login', query_string={'next': '/recordings'})+ assert resp.status_code == 200+ with client.session_transaction() as s:+ assert s.get('sso_next') == '/recordings'++def test_sso_unlink_with_password(cleanup_users):user = _mk_user(cleanup_users, sso_subject="sub-" + uuid.uuid4().hex, sso_provider='Keycloak')uid = user.iddiff --git a/tests/test_cov_inquire.py b/tests/test_cov_inquire.pyindex f9e27b7b..ae5f579f 100644--- a/tests/test_cov_inquire.py+++ b/tests/test_cov_inquire.py@@ -800,6 +800,251 @@ def test_chat_token_budget_exceeded(client):assert any(e.get('budget_exceeded') for e in events)+# --------------------------------------------------------------------------- #+# RAG generator internals: dedup, sort, speaker post-filter (mutation-targeted)+#+# These drive the streaming chat generator and inspect either the system prompt+# handed to call_chat_completion (which embeds the retrieved context) or the+# sequence of queries handed to semantic_search_chunks. Each test below is+# pinned to a specific surviving mutant in src/api/inquire.py.+# --------------------------------------------------------------------------- #++def _rag_router_then(enrichment_json):+ """call_llm_completion side_effect: route to RAG, then return the given JSON+ string as the query-enrichment response."""+ def _se(messages, **kwargs):+ if kwargs.get('operation_type') == 'query_routing':+ return _llm_msg("RAG")+ return _llm_msg(enrichment_json)+ return _se+++def _capturing_chat_completion(captured, texts=("answer",)):+ """call_chat_completion side_effect that records the system prompt + kwargs of+ the (first) answer call, then streams `texts` back."""+ def _se(messages, **kwargs):+ if 'system_prompt' not in captured:+ captured['system_prompt'] = messages[0]['content']+ captured['kwargs'] = kwargs+ return _stream_chunks(list(texts))+ return _se+++def test_chat_rag_dedups_repeated_chunks(client):+ """inquire.py:398 — a chunk returned twice by search must appear once in context.++ MUTATION-VERIFIED: 398 `not in`->`in` makes the dedup guard reject every chunk+ (the seen-set starts empty), so the context ends up empty and the marker count+ drops to 0 -> this test FAILS.+ """+ user_id = _make_user()+ rec_id = _make_recording(user_id, title="Dedup Rec", participants=None)+ marker = "DEDUPUNIQUECONTENT_" + _suffix()+ chunk_id = _make_chunk(user_id, rec_id, content=marker, chunk_index=0)++ def search_se(uid, query, filters, top_k):+ # Same chunk id returned twice within a single search result.+ return [_get_chunk_pair(chunk_id, 0.8), _get_chunk_pair(chunk_id, 0.8)]++ captured = {}+ with _login(client, user_id), \+ patch('src.api.inquire.ENABLE_INQUIRE_MODE', True), \+ patch('src.api.inquire.client', MagicMock()), \+ patch('src.api.inquire.EMBEDDINGS_AVAILABLE', True), \+ patch('src.api.inquire.call_llm_completion', side_effect=_rag_router_then('[]')), \+ patch('src.api.inquire.semantic_search_chunks', side_effect=search_se), \+ patch('src.api.inquire.call_chat_completion',+ side_effect=_capturing_chat_completion(captured)):+ resp = client.post('/api/inquire/chat', json={'message': 'tell me about the topic'})+ assert resp.status_code == 200+ _sse_events(resp)+ assert captured.get('system_prompt', '').count(marker) == 1+++def test_chat_rag_sorts_by_similarity_desc(client):+ """inquire.py:403 — combined results are sorted by similarity DESCENDING before+ the top-N truncation, so the highest-scored chunk survives a top-1 cut.++ MUTATION-VERIFIED: 403 `reverse=True`->`reverse=False` sorts ascending, so the+ top-1 cut keeps the LOW-scored chunk instead -> this test FAILS.+ """+ user_id = _make_user()+ rec_id = _make_recording(user_id, title="Sort Rec", participants=None)+ high = "HIGHSCORECONTENT_" + _suffix()+ low = "LOWSCORECONTENT_" + _suffix()+ high_id = _make_chunk(user_id, rec_id, content=high, chunk_index=0)+ low_id = _make_chunk(user_id, rec_id, content=low, chunk_index=1)++ def search_se(uid, query, filters, top_k):+ # Returned low-first so input order differs from the sorted order.+ return [_get_chunk_pair(low_id, 0.1), _get_chunk_pair(high_id, 0.9)]++ captured = {}+ with _login(client, user_id), \+ patch('src.api.inquire.ENABLE_INQUIRE_MODE', True), \+ patch('src.api.inquire.client', MagicMock()), \+ patch('src.api.inquire.EMBEDDINGS_AVAILABLE', True), \+ patch('src.api.inquire.call_llm_completion', side_effect=_rag_router_then('[]')), \+ patch('src.api.inquire.semantic_search_chunks', side_effect=search_se), \+ patch('src.api.inquire.call_chat_completion',+ side_effect=_capturing_chat_completion(captured)):+ resp = client.post('/api/inquire/chat',+ json={'message': 'budget', 'context_chunks': 1})+ assert resp.status_code == 200+ _sse_events(resp)+ sp = captured.get('system_prompt', '')+ assert high in sp+ assert low not in sp+++def test_chat_rag_speaker_postfilter(client):+ """inquire.py:427-436/458 — when a mentioned speaker is absent from the initial+ results, a speaker-filtered re-search runs; non-matching chunk is dropped and+ the matching speaker's chunks are kept (and deduped).++ MUTATION-VERIFIED:+ * 436 `if not speaker_in_results`->`if speaker_in_results` suppresses the+ auto speaker filter, so the non-Alice chunk is kept -> this test FAILS.+ * 458 `not in`->`in` makes the re-search dedup reject every chunk, so the+ auto-filtered set is empty and the code keeps the original chunk -> FAILS.+ """+ user_id = _make_user()+ # alice_rec's participants make 'Alice' an available speaker for this user.+ alice_rec = _make_recording(user_id, title="Alice Rec", participants="Alice")+ other_rec = _make_recording(user_id, title="Other Rec", participants=None)++ other_content = "OTHERSPEAKERCONTENT_" + _suffix()+ alice1_content = "ALICEONECONTENT_" + _suffix()+ alice2_content = "ALICETWOCONTENT_" + _suffix()+ other_id = _make_chunk(user_id, other_rec, content=other_content,+ speaker_name="Bob", chunk_index=0)+ alice1_id = _make_chunk(user_id, alice_rec, content=alice1_content,+ speaker_name="Alice", chunk_index=0)+ alice2_id = _make_chunk(user_id, alice_rec, content=alice2_content,+ speaker_name="Alice", chunk_index=1)++ def search_se(uid, query, filters, top_k):+ if filters.get('speaker_names'):+ # Speaker-filtered re-search: Alice chunks, with alice1 duplicated to+ # also exercise the 458 dedup guard. Two distinct ids -> len >= 2 so the+ # downstream "<2 results" broader re-search is skipped.+ return [_get_chunk_pair(alice1_id, 0.95),+ _get_chunk_pair(alice1_id, 0.95),+ _get_chunk_pair(alice2_id, 0.85)]+ return [_get_chunk_pair(other_id, 0.5)]++ captured = {}+ with _login(client, user_id), \+ patch('src.api.inquire.ENABLE_INQUIRE_MODE', True), \+ patch('src.api.inquire.client', MagicMock()), \+ patch('src.api.inquire.EMBEDDINGS_AVAILABLE', True), \+ patch('src.api.inquire.call_llm_completion', side_effect=_rag_router_then('[]')), \+ patch('src.api.inquire.semantic_search_chunks', side_effect=search_se), \+ patch('src.api.inquire.call_chat_completion',+ side_effect=_capturing_chat_completion(captured)):+ resp = client.post('/api/inquire/chat', json={'message': 'what did Alice say?'})+ assert resp.status_code == 200+ _sse_events(resp)+ sp = captured.get('system_prompt', '')+ assert alice1_content in sp # matching speaker kept+ assert alice2_content in sp+ assert other_content not in sp # non-matching speaker dropped+ assert sp.count(alice1_content) == 1 # 458: re-search dedup+++def test_chat_rag_uses_enriched_terms(client):+ """inquire.py:360 — a non-empty enrichment response is parsed and its terms are+ actually searched (not discarded as if empty).++ MUTATION-VERIFIED: 360 `not raw_content`->`raw_content` treats the (truthy)+ enrichment JSON as empty, raises, and falls back to the original query only, so+ the enriched term is never searched -> this test FAILS.+ """+ user_id = _make_user()+ rec_id = _make_recording(user_id, participants=None)+ chunk_id = _make_chunk(user_id, rec_id, content="enr content " + _suffix())++ queries_seen = []++ def search_se(uid, query, filters, top_k):+ queries_seen.append(query)+ return [_get_chunk_pair(chunk_id, 0.7)]++ with _login(client, user_id), \+ patch('src.api.inquire.ENABLE_INQUIRE_MODE', True), \+ patch('src.api.inquire.client', MagicMock()), \+ patch('src.api.inquire.EMBEDDINGS_AVAILABLE', True), \+ patch('src.api.inquire.call_llm_completion',+ side_effect=_rag_router_then('["alphaterm"]')), \+ patch('src.api.inquire.semantic_search_chunks', side_effect=search_se), \+ patch('src.api.inquire.call_chat_completion',+ return_value=_stream_chunks(["answer"])):+ resp = client.post('/api/inquire/chat', json={'message': 'orig query'})+ assert resp.status_code == 200+ _sse_events(resp)+ assert 'orig query' in queries_seen # original query always searched+ assert 'alphaterm' in queries_seen # enriched term also searched+++def test_chat_direct_path_passes_stream_true(client):+ """inquire.py:284 — the DIRECT-path completion is invoked with stream=True.++ MUTATION-VERIFIED: 284 `stream=True`->`stream=False` changes the kwarg passed+ to call_llm_completion for the 'chat' operation -> this test FAILS.+ """+ user_id = _make_user()+ router = MagicMock(return_value=_llm_msg("DIRECT"))+ with _login(client, user_id), \+ patch('src.api.inquire.ENABLE_INQUIRE_MODE', True), \+ patch('src.api.inquire.client', MagicMock()), \+ patch('src.api.inquire.call_llm_completion', router), \+ patch('src.api.inquire.process_streaming_with_thinking',+ return_value=iter(["data: " + json.dumps({'end_of_stream': True}) + "\n\n"])), \+ patch('src.api.inquire.semantic_search_chunks') as search:+ resp = client.post('/api/inquire/chat', json={'message': 'format this'})+ assert resp.status_code == 200+ _sse_events(resp)+ search.assert_not_called()+ chat_calls = [c for c in router.call_args_list+ if c.kwargs.get('operation_type') == 'chat']+ assert len(chat_calls) == 1+ assert chat_calls[0].kwargs.get('stream') is True+++def test_chat_empty_router_falls_back_to_rag(client):+ """inquire.py:257 — an empty router response is treated as a failure: the code+ must NOT take the DIRECT path and instead falls through to RAG (search + the+ streaming answer via call_chat_completion).+ """+ user_id = _make_user()+ rec_id = _make_recording(user_id, participants=None)+ chunk_id = _make_chunk(user_id, rec_id, content="rag content " + _suffix())++ def llm_se(messages, **kwargs):+ if kwargs.get('operation_type') == 'query_routing':+ return _llm_msg("") # empty router content+ return _llm_msg('["t"]')++ with _login(client, user_id), \+ patch('src.api.inquire.ENABLE_INQUIRE_MODE', True), \+ patch('src.api.inquire.client', MagicMock()), \+ patch('src.api.inquire.EMBEDDINGS_AVAILABLE', True), \+ patch('src.api.inquire.call_llm_completion', side_effect=llm_se), \+ patch('src.api.inquire.semantic_search_chunks',+ side_effect=lambda *a, **k: [_get_chunk_pair(chunk_id, 0.7)]), \+ patch('src.api.inquire.process_streaming_with_thinking') as pst, \+ patch('src.api.inquire.call_chat_completion',+ return_value=_stream_chunks(["rag answer"])):+ resp = client.post('/api/inquire/chat', json={'message': 'who said what?'})+ assert resp.status_code == 200+ events = _sse_events(resp)+ deltas = "".join(e['delta'] for e in events if 'delta' in e)+ # RAG answer streamed (DIRECT path, which uses process_streaming_with_thinking,+ # was not taken).+ assert 'rag answer' in deltas+ pst.assert_not_called()++# --------------------------------------------------------------------------- ## available_filters endpoint# --------------------------------------------------------------------------- #diff --git a/tests/test_cov_llm.py b/tests/test_cov_llm.pyindex 9f65145d..6a185189 100644--- a/tests/test_cov_llm.py+++ b/tests/test_cov_llm.py@@ -672,3 +672,277 @@ def test_streaming_usage_record_error_non_blocking(monkeypatch):)# Generator must still complete despite recording failure.assert events[-1] == {"end_of_stream": True}+++# ===========================================================================+# MUTATION-VERIFIED coverage for budget / token-usage / GPT-5 / stream-options+# logic that no existing test catches.+#+# Each test below is paired with the exact source line + mutation it kills.+# ===========================================================================++def _msgs():+ return [{"role": "user", "content": "q"}]+++# --- line 192: budget check only when BOTH user_id and operation_type set ---++def test_call_llm_budget_skipped_with_only_user_id(monkeypatch):+ # user_id set but operation_type None -> budget check AND usage record must+ # both be skipped. Kills line 192 `and operation_type`->`or operation_type`+ # and line 261 `and operation_type`->`or operation_type`.+ install_client(monkeypatch, return_value=make_completion("ok", usage=make_usage()))+ monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", "test-key")+ monkeypatch.setattr(llm, "TEXT_MODEL_NAME", "gpt-4o")+ fake_tracker = MagicMock()+ with patch("src.services.token_tracking.token_tracker", fake_tracker):+ call_llm_completion(_msgs(), user_id=42) # no operation_type+ fake_tracker.check_budget.assert_not_called()+ fake_tracker.record_usage.assert_not_called()+++def test_call_llm_budget_skipped_with_only_operation_type(monkeypatch):+ # operation_type set but user_id None -> still skipped. Kills line 192/261+ # `user_id and`->`user_id or` mutations.+ install_client(monkeypatch, return_value=make_completion("ok", usage=make_usage()))+ monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", "test-key")+ monkeypatch.setattr(llm, "TEXT_MODEL_NAME", "gpt-4o")+ fake_tracker = MagicMock()+ with patch("src.services.token_tracking.token_tracker", fake_tracker):+ call_llm_completion(_msgs(), operation_type="chat") # no user_id+ fake_tracker.check_budget.assert_not_called()+ fake_tracker.record_usage.assert_not_called()+++# --- line 261: usage recorded only on non-stream response with all conditions ---++def test_call_llm_records_usage_only_when_not_streaming(monkeypatch):+ # stream=True with usage present -> record_usage must NOT fire (the+ # `not stream` guard). Kills line 261 `not stream`->`stream`.+ install_client(monkeypatch, return_value=iter([]))+ monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", "test-key")+ monkeypatch.setattr(llm, "TEXT_MODEL_NAME", "gpt-4o")+ fake_tracker = MagicMock()+ fake_tracker.check_budget.return_value = (True, 10.0, None)+ with patch("src.services.token_tracking.token_tracker", fake_tracker):+ call_llm_completion(_msgs(), user_id=1, operation_type="chat", stream=True)+ fake_tracker.record_usage.assert_not_called()+++# --- line 198: near-limit WARNING logged at usage_pct >= 80 (exactly) ---++def test_call_llm_budget_warning_logged_at_80(monkeypatch):+ install_client(monkeypatch, return_value=make_completion("ok", usage=make_usage()))+ monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", "test-key")+ monkeypatch.setattr(llm, "TEXT_MODEL_NAME", "gpt-4o")+ fake_logger = MagicMock()+ monkeypatch.setattr(llm, "logger", fake_logger)+ fake_tracker = MagicMock()+ fake_tracker.check_budget.return_value = (True, 80.0, None)+ with patch("src.services.token_tracking.token_tracker", fake_tracker):+ call_llm_completion(_msgs(), user_id=7, operation_type="chat")+ assert any("of token budget" in str(c.args[0]) for c in fake_logger.warning.call_args_list)+++def test_call_llm_budget_no_warning_below_80(monkeypatch):+ install_client(monkeypatch, return_value=make_completion("ok", usage=make_usage()))+ monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", "test-key")+ monkeypatch.setattr(llm, "TEXT_MODEL_NAME", "gpt-4o")+ fake_logger = MagicMock()+ monkeypatch.setattr(llm, "logger", fake_logger)+ fake_tracker = MagicMock()+ fake_tracker.check_budget.return_value = (True, 79.0, None)+ with patch("src.services.token_tracking.token_tracker", fake_tracker):+ call_llm_completion(_msgs(), user_id=7, operation_type="chat")+ assert not any("of token budget" in str(c.args[0]) for c in fake_logger.warning.call_args_list)+++# --- line 208: GPT-5 path requires gpt-5 model AND OpenAI API ---++def test_call_llm_gpt5_not_triggered_on_non_openai_api(monkeypatch):+ # gpt-5 model name but a non-OpenAI base URL -> GPT-5 branch must NOT be+ # taken. Kills line 208 `and is_using_openai_api()`->`or is_using_openai_api()`.+ fake = install_client(monkeypatch, return_value=make_completion("ok"))+ monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", "test-key")+ monkeypatch.setattr(llm, "TEXT_MODEL_NAME", "gpt-5")+ monkeypatch.setattr(llm, "TEXT_MODEL_BASE_URL", "https://openrouter.ai/api/v1")+ call_llm_completion(_msgs(), temperature=0.5, max_tokens=100)+ kwargs = fake.create.call_args.kwargs+ assert "reasoning_effort" not in kwargs+ assert "verbosity" not in kwargs+ assert "max_completion_tokens" not in kwargs+ assert kwargs["temperature"] == 0.5+ assert kwargs["max_tokens"] == 100+++# --- line 279: empty-content path logs a warning; non-empty does not ---++def test_call_llm_empty_content_logs_warning(monkeypatch):+ install_client(monkeypatch, return_value=make_completion(content=""))+ monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", "test-key")+ monkeypatch.setattr(llm, "TEXT_MODEL_NAME", "gpt-4o")+ fake_logger = MagicMock()+ monkeypatch.setattr(llm, "logger", fake_logger)+ call_llm_completion(_msgs())+ assert any("empty content" in str(c.args[0]).lower() for c in fake_logger.warning.call_args_list)+++def test_call_llm_nonempty_content_no_empty_warning(monkeypatch):+ install_client(monkeypatch, return_value=make_completion("hello"))+ monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", "test-key")+ monkeypatch.setattr(llm, "TEXT_MODEL_NAME", "gpt-4o")+ fake_logger = MagicMock()+ monkeypatch.setattr(llm, "logger", fake_logger)+ call_llm_completion(_msgs())+ assert not any("empty content" in str(c.args[0]).lower() for c in fake_logger.warning.call_args_list)+++# --- line 218: stream_options only added when streaming AND the flag ---++def test_call_llm_no_stream_options_when_not_streaming(monkeypatch):+ # stream=False with flag enabled -> no stream_options. Kills line 218+ # `stream and ENABLE_STREAM_OPTIONS`->`stream or ENABLE_STREAM_OPTIONS`.+ fake = install_client(monkeypatch, return_value=make_completion("ok"))+ monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", "test-key")+ monkeypatch.setattr(llm, "TEXT_MODEL_NAME", "gpt-4o")+ monkeypatch.setattr(llm, "ENABLE_STREAM_OPTIONS", True)+ call_llm_completion(_msgs()) # stream defaults to False+ assert "stream_options" not in fake.create.call_args.kwargs+++# --- line 364: same gating in call_chat_completion ---++def test_call_chat_no_stream_options_when_not_streaming(monkeypatch):+ fake = FakeClient(return_value=make_completion("ok"))+ monkeypatch.setattr(llm, "chat_client", fake)+ monkeypatch.setattr(llm, "CHAT_MODEL_API_KEY", None)+ monkeypatch.setattr(llm, "CHAT_MODEL_NAME", None)+ monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", "test-key")+ monkeypatch.setattr(llm, "TEXT_MODEL_NAME", "gpt-4o")+ monkeypatch.setattr(llm, "TEXT_MODEL_BASE_URL", "https://openrouter.ai/api/v1")+ monkeypatch.setattr(llm, "ENABLE_STREAM_OPTIONS", True)+ call_chat_completion(_msgs()) # stream defaults to False+ assert "stream_options" not in fake.create.call_args.kwargs+++def test_call_chat_no_stream_options_when_flag_disabled(monkeypatch):+ fake = FakeClient(return_value=iter([]))+ monkeypatch.setattr(llm, "chat_client", fake)+ monkeypatch.setattr(llm, "CHAT_MODEL_API_KEY", None)+ monkeypatch.setattr(llm, "CHAT_MODEL_NAME", None)+ monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", "test-key")+ monkeypatch.setattr(llm, "TEXT_MODEL_NAME", "gpt-4o")+ monkeypatch.setattr(llm, "TEXT_MODEL_BASE_URL", "https://openrouter.ai/api/v1")+ monkeypatch.setattr(llm, "ENABLE_STREAM_OPTIONS", False)+ call_chat_completion(_msgs(), stream=True)+ assert "stream_options" not in fake.create.call_args.kwargs+++# --- lines 335/341/395: budget/usage gating mirrored in call_chat_completion ---++def test_call_chat_budget_skipped_with_only_user_id(monkeypatch):+ fake = FakeClient(return_value=make_completion("ok", usage=make_usage()))+ monkeypatch.setattr(llm, "chat_client", fake)+ monkeypatch.setattr(llm, "CHAT_MODEL_API_KEY", None)+ monkeypatch.setattr(llm, "CHAT_MODEL_NAME", None)+ monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", "test-key")+ monkeypatch.setattr(llm, "TEXT_MODEL_NAME", "gpt-4o")+ monkeypatch.setattr(llm, "TEXT_MODEL_BASE_URL", "https://openrouter.ai/api/v1")+ fake_tracker = MagicMock()+ with patch("src.services.token_tracking.token_tracker", fake_tracker):+ call_chat_completion(_msgs(), user_id=42) # no operation_type+ fake_tracker.check_budget.assert_not_called()+ fake_tracker.record_usage.assert_not_called()+++def test_call_chat_budget_warning_logged_at_80(monkeypatch):+ fake = FakeClient(return_value=make_completion("ok", usage=make_usage()))+ monkeypatch.setattr(llm, "chat_client", fake)+ monkeypatch.setattr(llm, "CHAT_MODEL_API_KEY", None)+ monkeypatch.setattr(llm, "CHAT_MODEL_NAME", None)+ monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", "test-key")+ monkeypatch.setattr(llm, "TEXT_MODEL_NAME", "gpt-4o")+ monkeypatch.setattr(llm, "TEXT_MODEL_BASE_URL", "https://openrouter.ai/api/v1")+ fake_logger = MagicMock()+ monkeypatch.setattr(llm, "logger", fake_logger)+ fake_tracker = MagicMock()+ fake_tracker.check_budget.return_value = (True, 80.0, None)+ with patch("src.services.token_tracking.token_tracker", fake_tracker):+ call_chat_completion(_msgs(), user_id=7, operation_type="chat")+ assert any("of token budget" in str(c.args[0]) for c in fake_logger.warning.call_args_list)+++def test_call_chat_budget_no_warning_below_80(monkeypatch):+ fake = FakeClient(return_value=make_completion("ok", usage=make_usage()))+ monkeypatch.setattr(llm, "chat_client", fake)+ monkeypatch.setattr(llm, "CHAT_MODEL_API_KEY", None)+ monkeypatch.setattr(llm, "CHAT_MODEL_NAME", None)+ monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", "test-key")+ monkeypatch.setattr(llm, "TEXT_MODEL_NAME", "gpt-4o")+ monkeypatch.setattr(llm, "TEXT_MODEL_BASE_URL", "https://openrouter.ai/api/v1")+ fake_logger = MagicMock()+ monkeypatch.setattr(llm, "logger", fake_logger)+ fake_tracker = MagicMock()+ fake_tracker.check_budget.return_value = (True, 79.0, None)+ with patch("src.services.token_tracking.token_tracker", fake_tracker):+ call_chat_completion(_msgs(), user_id=7, operation_type="chat")+ assert not any("of token budget" in str(c.args[0]) for c in fake_logger.warning.call_args_list)+++# --- line 68: get_chat_config selects dedicated chat only when BOTH key+name set ---++def test_get_chat_config_falls_back_when_chat_name_missing(monkeypatch):+ # CHAT_MODEL_API_KEY set but CHAT_MODEL_NAME None -> must fall back to TEXT.+ # Kills line 68 `and CHAT_MODEL_NAME`->`or CHAT_MODEL_NAME`.+ monkeypatch.setattr(llm, "CHAT_MODEL_API_KEY", "chat-key")+ monkeypatch.setattr(llm, "CHAT_MODEL_NAME", None)+ monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", "text-key")+ monkeypatch.setattr(llm, "TEXT_MODEL_BASE_URL", "https://text.example/v1")+ monkeypatch.setattr(llm, "TEXT_MODEL_NAME", "text-model")+ cfg = get_chat_config()+ assert cfg["api_key"] == "text-key"+ assert cfg["model_name"] == "text-model"+++# --- line 122: separate chat client only when CHAT key set AND differs from TEXT ---++def _load_fresh_llm(monkeypatch, env):+ """Import a fresh, isolated copy of src.services.llm under the given env so+ the module-level chat-client selection (line 122) can be exercised without+ clobbering the shared module instance other tests rely on."""+ import importlib.util+ for k, v in env.items():+ if v is None:+ monkeypatch.delenv(k, raising=False)+ else:+ monkeypatch.setenv(k, v)+ spec = importlib.util.spec_from_file_location("src.services._llm_fresh", llm.__file__)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++def test_chat_client_separate_when_keys_differ(monkeypatch):+ mod = _load_fresh_llm(monkeypatch, {+ "TEXT_MODEL_API_KEY": "text-key",+ "TEXT_MODEL_BASE_URL": "https://openrouter.ai/api/v1",+ "CHAT_MODEL_API_KEY": "chat-key",+ "CHAT_MODEL_NAME": "chat-model",+ "CHAT_MODEL_BASE_URL": "https://chat.example/v1",+ })+ assert mod.client is not None+ assert mod.chat_client is not None+ assert mod.chat_client is not mod.client+++def test_chat_client_shared_when_keys_match(monkeypatch):+ # CHAT key equals TEXT key -> reuse the main client. Kills line 122+ # `and CHAT_MODEL_API_KEY != TEXT_MODEL_API_KEY`->`or ...`.+ mod = _load_fresh_llm(monkeypatch, {+ "TEXT_MODEL_API_KEY": "same-key",+ "TEXT_MODEL_BASE_URL": "https://openrouter.ai/api/v1",+ "CHAT_MODEL_API_KEY": "same-key",+ "CHAT_MODEL_NAME": "chat-model",+ "CHAT_MODEL_BASE_URL": None,+ })+ assert mod.chat_client is mod.clientdiff --git a/tests/test_cov_processing.py b/tests/test_cov_processing.pyindex 47f483c0..ae52bb5f 100644--- a/tests/test_cov_processing.py+++ b/tests/test_cov_processing.py@@ -22,7 +22,11 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))import pytestfrom src.app import app, db-from src.models import User, Recording, Event, SystemSetting+from src.models import (+ User, Recording, Event, SystemSetting,+ Group, GroupMembership, Tag, RecordingTag, InternalShare,+ SharedRecordingState, NamingTemplate,+)import src.tasks.processing as proc@@ -640,5 +644,191 @@ def test_transcribe_audio_task_sets_processing_time():assert out.processing_time_seconds >= 0+# ---------------------------------------------------------------------------+# apply_team_tag_auto_shares — group-tag -> auto-share fan-out+# ---------------------------------------------------------------------------++def _make_group(prefix):+ grp = Group(name=f"{prefix}_{uuid.uuid4().hex[:8]}")+ db.session.add(grp)+ db.session.commit()+ return grp+++def _add_membership(group_id, user_id, role="member"):+ m = GroupMembership(group_id=group_id, user_id=user_id, role=role)+ db.session.add(m)+ db.session.commit()+ return m+++def _make_group_tag(owner_id, group_id, auto_share=True, share_lead=False):+ tag = Tag(+ name=f"gtag_{uuid.uuid4().hex[:8]}",+ user_id=owner_id,+ group_id=group_id,+ auto_share_on_apply=auto_share,+ share_with_group_lead=share_lead,+ )+ db.session.add(tag)+ db.session.commit()+ return tag+++def _apply_tag(recording_id, tag_id):+ db.session.add(RecordingTag(recording_id=recording_id, tag_id=tag_id, order=0))+ db.session.commit()+++class TestApplyTeamTagAutoShares:+ """Coverage for apply_team_tag_auto_shares — every assertion scoped to the+ recording/user IDs this test creates (shared session DB)."""++ def _build(self, prefix, auto_share=True, share_lead=False):+ """Build a group with an owner + two other members, a group tag, and a+ recording owned by the owner with that tag applied. Returns a dict of ids."""+ owner = _make_user(f"{prefix}_owner")+ member_a = _make_user(f"{prefix}_a")+ member_b = _make_user(f"{prefix}_b")+ grp = _make_group(prefix)+ _add_membership(grp.id, owner.id, role="member")+ _add_membership(grp.id, member_a.id, role="member")+ _add_membership(grp.id, member_b.id, role="admin")+ tag = _make_group_tag(owner.id, grp.id, auto_share=auto_share, share_lead=share_lead)+ rec = _make_recording(owner.id)+ _apply_tag(rec.id, tag.id)+ return {+ "owner": owner.id,+ "member_a": member_a.id,+ "member_b": member_b.id,+ "group": grp.id,+ "tag": tag.id,+ "rid": rec.id,+ }++ def test_auto_share_creates_shares_for_other_members_only(self):+ with app.app_context():+ ids = self._build("ats_main")+ with patch.object(proc, "ENABLE_INTERNAL_SHARING", True):+ proc.apply_team_tag_auto_shares(ids["rid"])++ # Drop any uncommitted pending state, then read fresh from the DB.+ # This proves the function COMMITTED (lines 162-163): if the commit+ # were skipped the pending rows would be discarded by the rollback.+ db.session.rollback()++ shares = InternalShare.query.filter_by(recording_id=ids["rid"]).all()+ by_user = {s.shared_with_user_id: s for s in shares}++ # Owner is NOT self-shared (line 127).+ assert ids["owner"] not in by_user+ # Each OTHER group member gets exactly one share.+ assert set(by_user.keys()) == {ids["member_a"], ids["member_b"]}++ # Flag assertions (lines 143-147).+ for s in shares:+ assert s.can_reshare is False # line 144+ assert s.source_type == "group_tag"+ assert s.source_tag_id == ids["tag"]+ assert s.owner_id == ids["owner"]+ # Group admin gets edit, regular member does not (line 143).+ assert by_user[ids["member_b"]].can_edit is True+ assert by_user[ids["member_a"]].can_edit is False++ # Per-recipient state created with inbox=True, highlighted=False.+ states = SharedRecordingState.query.filter_by(recording_id=ids["rid"]).all()+ states_by_user = {st.user_id: st for st in states}+ assert set(states_by_user.keys()) == {ids["member_a"], ids["member_b"]}+ for st in states:+ assert st.is_inbox is True # line 154+ assert st.is_highlighted is False # line 155++ def test_auto_share_is_idempotent_no_duplicates(self):+ with app.app_context():+ ids = self._build("ats_dup")+ with patch.object(proc, "ENABLE_INTERNAL_SHARING", True):+ proc.apply_team_tag_auto_shares(ids["rid"])+ first = InternalShare.query.filter_by(recording_id=ids["rid"]).count()+ # Second call must NOT create duplicates (line 136).+ proc.apply_team_tag_auto_shares(ids["rid"])+ second = InternalShare.query.filter_by(recording_id=ids["rid"]).count()+ assert first == 2+ assert second == 2++ def test_disabled_internal_sharing_creates_no_shares(self):+ with app.app_context():+ ids = self._build("ats_disabled")+ with patch.object(proc, "ENABLE_INTERNAL_SHARING", False):+ proc.apply_team_tag_auto_shares(ids["rid"])+ assert InternalShare.query.filter_by(recording_id=ids["rid"]).count() == 0++ def test_missing_recording_returns_quietly(self):+ with app.app_context():+ with patch.object(proc, "ENABLE_INTERNAL_SHARING", True):+ # Non-existent recording must return without raising (line 99).+ assert proc.apply_team_tag_auto_shares(99999999) is None+ assert InternalShare.query.filter_by(recording_id=99999999).count() == 0++ def test_non_auto_share_tag_creates_nothing(self):+ """A group tag with both auto_share_on_apply and share_with_group_lead+ False is filtered out (lines 104/106/108/111)."""+ with app.app_context():+ ids = self._build("ats_noflag", auto_share=False, share_lead=False)+ with patch.object(proc, "ENABLE_INTERNAL_SHARING", True):+ proc.apply_team_tag_auto_shares(ids["rid"])+ assert InternalShare.query.filter_by(recording_id=ids["rid"]).count() == 0++ def test_personal_tag_is_ignored(self):+ """A non-group (personal) tag with auto_share_on_apply True must NOT+ trigger any share — the Tag.group_id.isnot(None) filter excludes it."""+ with app.app_context():+ owner = _make_user("ats_personal_owner")+ other = _make_user("ats_personal_other")+ grp = _make_group("ats_personal")+ _add_membership(grp.id, owner.id, role="member")+ _add_membership(grp.id, other.id, role="member")+ # Personal tag: group_id is None.+ tag = Tag(name=f"ptag_{uuid.uuid4().hex[:8]}", user_id=owner.id,+ group_id=None, auto_share_on_apply=True)+ db.session.add(tag)+ db.session.commit()+ rec = _make_recording(owner.id)+ _apply_tag(rec.id, tag.id)+ with patch.object(proc, "ENABLE_INTERNAL_SHARING", True):+ proc.apply_team_tag_auto_shares(rec.id)+ assert InternalShare.query.filter_by(recording_id=rec.id).count() == 0+++# ---------------------------------------------------------------------------+# generate_title_task — user default naming-template resolution (line 276)+# ---------------------------------------------------------------------------++def test_title_uses_user_default_naming_template():+ """When the recording has no tag-supplied template, the owner's default+ naming template must be applied (line 276)."""+ with app.app_context():+ user = _make_user("title_deftmpl")+ # Template needs no AI title, so no LLM call is required.+ tmpl = NamingTemplate(user_id=user.id, name="Call template",+ template="Call {{filename}}")+ db.session.add(tmpl)+ db.session.commit()+ user.default_naming_template_id = tmpl.id+ db.session.commit()++ # Placeholder title + no tags -> falls through to the user-default path.+ rec = _make_recording(user.id, title="Recording - cov.mp3")+ rid = rec.id+ with patch.object(proc, "client", None), \+ patch.object(proc, "ENABLE_INQUIRE_MODE", False):+ proc.generate_title_task(app.app_context(), rid, will_auto_summarize=False)++ db.session.expire_all()+ out = db.session.get(Recording, rid)+ # original_filename is "cov.mp3" -> {{filename}} == "cov".+ assert out.title == "Call cov"+ assert out.status == "COMPLETED"++if __name__ == "__main__":sys.exit(pytest.main([__file__, "-q"]))diff --git a/tests/test_cov_recordings_read.py b/tests/test_cov_recordings_read.pyindex 6d613080..e7e13082 100644--- a/tests/test_cov_recordings_read.py+++ b/tests/test_cov_recordings_read.py@@ -69,6 +69,7 @@ import src.api.recordings as rec_modulefrom src.app import app, dbfrom src.models import User, Recordingfrom src.models.organization import Tag, Folder, RecordingTag+from src.models.templates import TranscriptTemplateapp.config["WTF_CSRF_ENABLED"] = False@@ -1122,3 +1123,279 @@ def test_process_chunks_non_owner_denied(owner, other):login(c, other)resp = c.post(f"/api/recording/{rid}/process_chunks")assert resp.status_code == 403+++# =========================================================================== #+# DOWNLOAD: transcript-with-template / summary / chat (owner content checks ++# diarized-vs-plain template formatting). These close mutation survivors in the+# download handlers that no other test reaches; the 403/authz side is owned by+# tests/test_cov_recordings_download_authz.py.+# =========================================================================== #++def _diarized_json():+ """A speaker-labelled (diarized) transcript: a JSON list of segments.++ download_transcript_with_template treats a JSON *list* as diarized and runs+ the per-segment template formatter; anything else is plain text returned+ verbatim. Keys match what the handler reads: speaker / sentence /+ start_time / end_time.+ """+ return json.dumps([+ {"speaker": "Alice", "sentence": "Hello there", "start_time": 0.0, "end_time": 1.5},+ {"speaker": "Bob", "sentence": "Hi back", "start_time": 1.5, "end_time": 3.0},+ ])+++def _make_template(user, *, name, template, is_default=False):+ t = TranscriptTemplate(user_id=user.id, name=name, template=template,+ is_default=is_default)+ db.session.add(t)+ db.session.commit()+ return t+++# --- /download/transcript : content-presence guard (line 173) ------------- #++def test_download_transcript_empty_transcription_400(owner):+ """No transcription -> 400 (guard at recordings.py:173).++ MUTATION-VERIFIED: `if not recording.transcription` -> `if recording.transcription`+ makes the empty-transcript recording fall through to a 200 download; this test+ then FAILS.+ """+ with _db():+ u = db.session.get(User, owner)+ rid = make_recording(u, transcription="").id++ c = new_client()+ login(c, owner)+ resp = c.get(f"/recording/{rid}/download/transcript")+ assert resp.status_code == 400+ assert "transcription" in resp.get_json()["error"].lower()+++def test_download_transcript_present_returns_file_not_400(owner):+ """A transcription present -> a 200 text file, NOT a 400 (line 173 inverse)."""+ with _db():+ u = db.session.get(User, owner)+ rid = make_recording(u, transcription="hello plain transcript body").id++ c = new_client()+ login(c, owner)+ resp = c.get(f"/recording/{rid}/download/transcript")+ assert resp.status_code == 200+ assert b"hello plain transcript body" in resp.data+ assert resp.headers["Content-Type"].startswith("text/plain")+++# --- /download/transcript : plain-text vs diarized branch (221/226/232) ---- #++def test_download_transcript_plain_text_returned_verbatim(owner):+ """A non-JSON transcription is returned as-is (is_diarized False path).++ MUTATION-VERIFIED: flipping line 232 `if not is_diarized` -> `if is_diarized`+ sends plain text down the segment-iteration branch (iterating None) -> 500;+ this test (expecting 200 + verbatim body) then FAILS.+ """+ with _db():+ u = db.session.get(User, owner)+ rid = make_recording(u, transcription="just some words, not json").id++ c = new_client()+ login(c, owner)+ resp = c.get(f"/recording/{rid}/download/transcript")+ assert resp.status_code == 200+ assert resp.data.decode() == "just some words, not json"+ # Plain-text filename branch (line 272): no "_formatted" / template suffix.+ cd = resp.headers.get("Content-Disposition", "")+ assert "_formatted" not in cd+++def test_download_transcript_diarized_no_template_basic_format(owner):+ """A diarized transcript with no template uses the basic `[speaker]: text`+ format and a `_formatted` filename.++ MUTATION-VERIFIED: line 226 (`is_diarized = True`) or line 232 flips send the+ JSON list down the plain-text branch (raw JSON returned), failing the body+ assertion; line 193 (`if not template`) flipped dereferences None.template+ -> 500; line 266/268 filename branch flip drops `_formatted`.+ """+ with _db():+ u = db.session.get(User, owner)+ rid = make_recording(u, transcription=_diarized_json(), title="diar-basic").id++ c = new_client()+ login(c, owner)+ resp = c.get(f"/recording/{rid}/download/transcript")+ assert resp.status_code == 200+ body = resp.data.decode()+ # Template applied per segment -> formatted lines, NOT the raw JSON string.+ assert "[Alice]: Hello there" in body+ assert "[Bob]: Hi back" in body+ assert '"sentence"' not in body # raw JSON would contain this key+ assert "_formatted" in resp.headers.get("Content-Disposition", "")+++def test_download_transcript_diarized_uses_default_template(owner):+ """Without an explicit template_id, the user's *default* template is chosen+ (lines 187-189) and used to format (line 196), and its name lands in the+ filename (line 266).++ MUTATION-VERIFIED: line 189 `is_default=True` -> `is_default=False` selects the+ non-default template ("OTH ..."), failing the "DEF ..." body assertion; line 193+ flip uses the basic `[..]` format instead of template.template, also failing.+ """+ with _db():+ u = db.session.get(User, owner)+ _make_template(u, name="OtherTmpl", template="OTH {{speaker}}={{text}}",+ is_default=False)+ _make_template(u, name="DefaultTmpl", template="DEF {{speaker}}={{text}}",+ is_default=True)+ rid = make_recording(u, transcription=_diarized_json(), title="diar-tmpl").id++ c = new_client()+ login(c, owner)+ resp = c.get(f"/recording/{rid}/download/transcript")+ assert resp.status_code == 200+ body = resp.data.decode()+ assert "DEF Alice=Hello there" in body+ assert "DEF Bob=Hi back" in body+ assert "OTH " not in body+ # is_diarized and template -> filename embeds the template name (line 266/267).+ assert "DefaultTmpl" in resp.headers.get("Content-Disposition", "")+++def test_download_transcript_explicit_template_id(owner):+ """An explicit ?template_id= selects that template (lines 180-184) over the+ default."""+ with _db():+ u = db.session.get(User, owner)+ _make_template(u, name="DefaultTmpl", template="DEF {{speaker}}={{text}}",+ is_default=True)+ chosen = _make_template(u, name="ChosenTmpl",+ template="PICK {{speaker}}/{{text}}", is_default=False)+ chosen_id = chosen.id+ rid = make_recording(u, transcription=_diarized_json(), title="diar-pick").id++ c = new_client()+ login(c, owner)+ resp = c.get(f"/recording/{rid}/download/transcript?template_id={chosen_id}")+ assert resp.status_code == 200+ body = resp.data.decode()+ assert "PICK Alice/Hello there" in body+ assert "DEF " not in body+++# --- /download/summary : content-presence guard (line 303) ---------------- #++def test_download_summary_empty_400(owner):+ """No summary -> 400 (guard at recordings.py:303).++ MUTATION-VERIFIED: `if not recording.summary` -> `if recording.summary` lets the+ empty-summary recording fall through to a 200 .docx; this test then FAILS.+ """+ with _db():+ u = db.session.get(User, owner)+ rid = make_recording(u, summary="").id++ c = new_client()+ login(c, owner)+ resp = c.get(f"/recording/{rid}/download/summary")+ assert resp.status_code == 400+ assert "summary" in resp.get_json()["error"].lower()+++def test_download_summary_present_returns_docx(owner):+ """A summary present -> a 200 Word document, not a 400 (line 303 inverse).++ Also pins recordings.py:368 `as_attachment=False`: the doc is a BytesIO with+ no download_name, so MUTATION-VERIFIED flipping it to `as_attachment=True`+ raises "No name provided for attachment" -> 500, and this 200 assertion FAILS.+ """+ with _db():+ u = db.session.get(User, owner)+ rid = make_recording(u, summary="## Heading\n\nSome **summary** content.").id++ c = new_client()+ login(c, owner)+ resp = c.get(f"/recording/{rid}/download/summary")+ assert resp.status_code == 200+ assert "wordprocessingml" in resp.headers["Content-Type"]+ assert len(resp.data) > 0+++# --- /download/chat : messages-presence guard (line 421) ------------------ #++def test_download_chat_empty_messages_400(owner):+ """An empty messages list -> 400 (guard at recordings.py:421, distinct from+ the missing-key guard at 417).++ MUTATION-VERIFIED: `if not messages` -> `if messages` lets the empty list build+ an empty .docx and return 200; this test then FAILS.+ """+ with _db():+ u = db.session.get(User, owner)+ rid = make_recording(u).id++ c = new_client()+ login(c, owner)+ resp = c.post(f"/recording/{rid}/download/chat", json={"messages": []})+ assert resp.status_code == 400+ assert "messages" in resp.get_json()["error"].lower()+++def test_download_chat_missing_key_400(owner):+ """No 'messages' key at all -> 400 (guard at recordings.py:417)."""+ with _db():+ u = db.session.get(User, owner)+ rid = make_recording(u).id++ c = new_client()+ login(c, owner)+ resp = c.post(f"/recording/{rid}/download/chat", json={})+ assert resp.status_code == 400+++def test_download_chat_with_messages_returns_docx(owner):+ """Messages present -> a 200 Word document (line 421 inverse).++ Also pins recordings.py:507 `as_attachment=False` (same BytesIO/no-name+ mechanism as the summary download): MUTATION-VERIFIED flipping it to True -> 500.+ """+ with _db():+ u = db.session.get(User, owner)+ rid = make_recording(u).id++ c = new_client()+ login(c, owner)+ resp = c.post(+ f"/recording/{rid}/download/chat",+ json={"messages": [+ {"role": "user", "content": "What was discussed?"},+ {"role": "assistant", "content": "The **roadmap**."},+ ]},+ )+ assert resp.status_code == 200+ assert "wordprocessingml" in resp.headers["Content-Type"]+ assert len(resp.data) > 0+++# --- ENABLE_INQUIRE_MODE gate on the async reindex helper (line 118) ------- #++def test_reindex_chunks_noop_when_inquire_disabled(owner):+ """reindex_recording_chunks_async is a no-op when Inquire mode is off+ (guard at recordings.py:118).++ MUTATION-VERIFIED: `if not ENABLE_INQUIRE_MODE` -> `if ENABLE_INQUIRE_MODE`+ makes the disabled-mode call spawn a reindex thread; this test (asserting no+ thread / no process_recording_chunks call) then FAILS.+ """+ # Force the disabled state (the test image may have inquire enabled), so the+ # gate is exercised regardless of environment.+ with _db():+ with patch.object(rec_module, "ENABLE_INQUIRE_MODE", False), \+ patch.object(rec_module, "process_recording_chunks") as proc, \+ patch.object(rec_module.threading, "Thread") as thread_cls:+ rec_module.reindex_recording_chunks_async(987654321)+ thread_cls.assert_not_called()+ proc.assert_not_called()diff --git a/tests/test_webhooks.py b/tests/test_webhooks.pyindex 136a34e9..e48e38da 100644--- a/tests/test_webhooks.py+++ b/tests/test_webhooks.py@@ -31,6 +31,7 @@ from src.services.webhook_dispatch import (emit_webhook_event,run_dispatcher_pass,_delay_for_attempt,+ _is_retryable_status,)@@ -691,6 +692,85 @@ def test_autopaused_webhook_resumes_on_successful_trial_delivery():db.session.commit()+def test_is_url_safe_rejects_reserved_ip():+ """webhook_dispatch.py:193 — an address flagged is_reserved (but not+ otherwise private/multicast in this Python) must be rejected. Mocks+ DNS to a reserved-only IPv6 (5f00::/16). Kills the+ `or ip.is_reserved` -> `and ip.is_reserved` survivor: under the+ mutation this address is no longer caught and is wrongly allowed."""+ with patch.dict(os.environ, {}, clear=False):+ os.environ.pop('WEBHOOK_INTRANET_HOST_ALLOWLIST', None)+ with patch('src.services.webhook_dispatch.socket.getaddrinfo') as mock_resolve:+ mock_resolve.return_value = [+ (None, None, None, None, ('5f00::1', 0, 0, 0)),+ ]+ ok, reason = is_url_safe_for_webhook('http://reserved.example.test/x', allow_http=True)+ assert not ok+ assert '5f00::1' in reason+++def test_is_url_safe_rejects_multicast_ip():+ """webhook_dispatch.py:193 — a multicast address (224.0.0.0/4) must be+ rejected. 224.0.0.1 is multicast but NOT private, so only the+ is_multicast clause catches it."""+ with patch.dict(os.environ, {}, clear=False):+ os.environ.pop('WEBHOOK_INTRANET_HOST_ALLOWLIST', None)+ with patch('src.services.webhook_dispatch.socket.getaddrinfo') as mock_resolve:+ mock_resolve.return_value = [+ (None, None, None, None, ('224.0.0.1', 0)),+ ]+ ok, reason = is_url_safe_for_webhook('http://multicast.example.test/x', allow_http=True)+ assert not ok+ assert '224.0.0.1' in reason+++def test_is_url_safe_allows_public_ip():+ """A host resolving to a genuinely public address is allowed."""+ with patch.dict(os.environ, {}, clear=False):+ os.environ.pop('WEBHOOK_INTRANET_HOST_ALLOWLIST', None)+ with patch('src.services.webhook_dispatch.socket.getaddrinfo') as mock_resolve:+ mock_resolve.return_value = [+ (None, None, None, None, ('8.8.8.8', 0)),+ ]+ ok, reason = is_url_safe_for_webhook('http://public.example.test/x', allow_http=True)+ assert ok, reason+++def test_dispatcher_post_does_not_follow_redirects():+ """webhook_dispatch.py:317 — the delivery POST must be made with+ allow_redirects=False so a 3xx from the receiver cannot bounce the+ signed payload to an attacker-controlled location (SSRF via+ redirect). Kills the allow_redirects=False -> True survivor."""+ with app.app_context():+ user = _make_user('wh_noredir')+ wh, d = _seed_pending(user.id)+ mock_resp = MagicMock(status_code=204, text='')+ with patch('src.services.webhook_dispatch.requests.post', return_value=mock_resp) as post:+ run_dispatcher_pass()+ post.assert_called_once()+ assert post.call_args.kwargs.get('allow_redirects') is False++ for x in WebhookDelivery.query.filter_by(webhook_id=wh.id).all():+ db.session.delete(x)+ db.session.delete(wh)+ db.session.delete(user)+ db.session.commit()+++def test_is_retryable_status_classification():+ """webhook_dispatch.py:_is_retryable_status — network errors and+ transient HTTP statuses retry; success and permanent 4xx do not.+ The 2xx case (`return False`) is the line-329 survivor: under the+ `return True` mutation a delivered 2xx would be retried forever."""+ assert _is_retryable_status(None) is True # network/timeout error+ assert _is_retryable_status(200) is False # success — must NOT retry+ assert _is_retryable_status(204) is False # success — must NOT retry+ assert _is_retryable_status(408) is True # request timeout+ assert _is_retryable_status(429) is True # rate limited+ assert _is_retryable_status(503) is True # server error+ assert _is_retryable_status(404) is False # permanent client error++def test_is_url_safe_inspects_all_resolved_addresses():"""Sanity: even when the hostname is fine, every resolved addressmust be inspected. Tested by mocking getaddrinfo to return mixed