diff --git a/services/asterisk_bridge_service/reconcile.py b/services/asterisk_bridge_service/reconcile.py index 9b1ff58..67c491f 100644 --- a/services/asterisk_bridge_service/reconcile.py +++ b/services/asterisk_bridge_service/reconcile.py @@ -60,7 +60,7 @@ def latest_recording_for_call(session, *, call_id: str) -> CallRecordingRow | No def _voice_session_recently_active(session, *, link: AsteriskCallLinkRow, now: datetime) -> bool: bridge = _bridge_app() - if str(link.ai_state or "").strip() not in { + non_terminal_states = { "queued", "greeting", "active", @@ -69,15 +69,18 @@ def _voice_session_recently_active(session, *, link: AsteriskCallLinkRow, now: d "listening", "handoff_requested", "handoff_required", - }: - return False + } + link_ai_state = str(link.ai_state or "").strip() voice_session_id = str(link.voice_session_id or "").strip() - if not voice_session_id: + if not voice_session_id and link_ai_state not in non_terminal_states: return False voice_session = session.execute( select(VoiceAISessionRow).where(VoiceAISessionRow.session_id == voice_session_id) ).scalar_one_or_none() if voice_session is None: + return link_ai_state in non_terminal_states + effective_ai_state = link_ai_state or str(voice_session.status or "").strip() + if effective_ai_state not in non_terminal_states: return False recent_points = [ bridge._parse_iso(voice_session.last_media_frame_at), diff --git a/tests/test_asterisk_bridge_service.py b/tests/test_asterisk_bridge_service.py index c871455..5efa445 100644 --- a/tests/test_asterisk_bridge_service.py +++ b/tests/test_asterisk_bridge_service.py @@ -1086,7 +1086,7 @@ def test_reconcile_keeps_live_call_active_when_ami_still_sees_channels(monkeypat assert link.telephony_status == "connected" assert link.ended_at is None assert link.channel_name == "PJSIP/2001-00009999" - assert emitted == [] + assert [item for item in emitted if item["call_id"] == call_id] == [] finally: session.close() @@ -1145,7 +1145,7 @@ def test_reconcile_skips_synthetic_end_when_channel_lookup_is_unavailable(monkey assert link.status == "active" assert link.telephony_status == "connected" assert link.ended_at is None - assert emitted == [] + assert [item for item in emitted if item["call_id"] == call_id] == [] finally: session.close() @@ -1302,7 +1302,7 @@ def test_reconcile_keeps_recent_active_ai_call_open(monkeypatch, tmp_path): assert link.status == "active" assert link.telephony_status == "connected" assert link.ended_at is None - assert emitted == [] + assert [item for item in emitted if item["call_id"] == call_id] == [] finally: session.close() @@ -1371,7 +1371,7 @@ def test_reconcile_closes_active_call_without_duplicate_end_event(monkeypatch, t assert link.status == "ended" assert link.telephony_status == "ended" assert link.ended_at is not None - assert emitted == [] + assert [item for item in emitted if item["call_id"] == call_id] == [] finally: session.close()