active-call 0.3.54

A SIP/WebRTC voice agent
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
use crate::call::active_call::ActiveCallStateRef;
use crate::callrecord::CallRecordHangupReason;
use crate::event::EventSender;
use crate::media::TrackId;
use crate::media::stream::MediaStream;
use crate::useragent::invitation::PendingDialog;
use anyhow::Result;
use chrono::Utc;
use rsipstack::dialog::DialogId;
use rsipstack::dialog::dialog::{
    Dialog, DialogState, DialogStateReceiver, DialogStateSender, TerminatedReason,
};
use rsipstack::dialog::dialog_layer::DialogLayer;
use rsipstack::dialog::invitation::InviteOption;
use std::collections::HashMap;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
use tracing::{info, warn};

pub struct DialogStateReceiverGuard {
    pub(super) dialog_layer: Arc<DialogLayer>,
    pub(super) receiver: DialogStateReceiver,
    pub(super) dialog_id: Option<DialogId>,
    pub(super) hangup_headers: Option<Vec<rsipstack::rsip::Header>>,
}

impl DialogStateReceiverGuard {
    pub fn new(
        dialog_layer: Arc<DialogLayer>,
        receiver: DialogStateReceiver,
        hangup_headers: Option<Vec<rsipstack::rsip::Header>>,
    ) -> Self {
        Self {
            dialog_layer,
            receiver,
            dialog_id: None,
            hangup_headers,
        }
    }
    pub async fn recv(&mut self) -> Option<DialogState> {
        let state = self.receiver.recv().await;
        if let Some(ref s) = state {
            self.dialog_id = Some(s.id().clone());
        }
        state
    }

    fn take_dialog(&mut self) -> Option<Dialog> {
        let id = match self.dialog_id.take() {
            Some(id) => id,
            None => return None,
        };

        match self.dialog_layer.get_dialog(&id) {
            Some(dialog) => {
                info!(%id, "dialog removed on  drop");
                self.dialog_layer.remove_dialog(&id);
                return Some(dialog);
            }
            _ => {}
        }
        None
    }

    pub async fn drop_async(&mut self) {
        if let Some(dialog) = self.take_dialog() {
            if let Err(e) = dialog.hangup_with_headers(self.hangup_headers.take()).await {
                warn!(id=%dialog.id(), "error hanging up dialog on drop: {}", e);
            }
        }
    }
}

impl Drop for DialogStateReceiverGuard {
    fn drop(&mut self) {
        if let Some(dialog) = self.take_dialog() {
            crate::spawn(async move {
                if let Err(e) = dialog.hangup().await {
                    warn!(id=%dialog.id(), "error hanging up dialog on drop: {}", e);
                }
            });
        }
    }
}

pub(super) struct InviteDialogStates {
    pub is_client: bool,
    pub session_id: String,
    pub track_id: TrackId,
    pub cancel_token: CancellationToken,
    pub event_sender: EventSender,
    pub call_state: ActiveCallStateRef,
    pub media_stream: Arc<MediaStream>,
    pub terminated_reason: Option<TerminatedReason>,
    pub has_early_media: bool,
}

impl InviteDialogStates {
    pub(super) fn on_terminated(&mut self) {
        let mut call_state_ref = match self.call_state.try_write() {
            Ok(cs) => cs,
            Err(_) => {
                return;
            }
        };
        let reason = &self.terminated_reason;
        call_state_ref.last_status_code = match reason {
            Some(TerminatedReason::UacCancel) => 487,
            Some(TerminatedReason::UacBye) => 200,
            Some(TerminatedReason::UacBusy) => 486,
            Some(TerminatedReason::UasBye) => 200,
            Some(TerminatedReason::UasBusy) => 486,
            Some(TerminatedReason::UasDecline) => 603,
            Some(TerminatedReason::UacOther(code)) => code.code(),
            Some(TerminatedReason::UasOther(code)) => code.code(),
            _ => 500, // Default to internal server error
        };

        if call_state_ref.hangup_reason.is_none() {
            call_state_ref.hangup_reason.replace(match reason {
                Some(TerminatedReason::UacCancel) => CallRecordHangupReason::Canceled,
                Some(TerminatedReason::UacBye) | Some(TerminatedReason::UacBusy) => {
                    CallRecordHangupReason::ByCaller
                }
                Some(TerminatedReason::UasBye) | Some(TerminatedReason::UasBusy) => {
                    CallRecordHangupReason::ByCallee
                }
                Some(TerminatedReason::UasDecline) => CallRecordHangupReason::ByCallee,
                Some(TerminatedReason::UacOther(_)) => CallRecordHangupReason::ByCaller,
                Some(TerminatedReason::UasOther(_)) => CallRecordHangupReason::ByCallee,
                _ => CallRecordHangupReason::BySystem,
            });
        };
        let initiator = match reason {
            Some(TerminatedReason::UacCancel) => "caller".to_string(),
            Some(TerminatedReason::UacBye) | Some(TerminatedReason::UacBusy) => {
                "caller".to_string()
            }
            Some(TerminatedReason::UasBye)
            | Some(TerminatedReason::UasBusy)
            | Some(TerminatedReason::UasDecline) => "callee".to_string(),
            _ => "system".to_string(),
        };
        self.event_sender
            .send(crate::event::SessionEvent::TrackEnd {
                track_id: self.track_id.clone(),
                timestamp: crate::media::get_timestamp(),
                duration: call_state_ref
                    .answer_time
                    .map(|t| (Utc::now() - t).num_milliseconds())
                    .unwrap_or_default() as u64,
                ssrc: call_state_ref.ssrc,
                play_id: None,
            })
            .ok();
        let hangup_event =
            call_state_ref.build_hangup_event(self.track_id.clone(), Some(initiator));
        self.event_sender.send(hangup_event).ok();
    }
}

impl Drop for InviteDialogStates {
    fn drop(&mut self) {
        self.on_terminated();
        self.cancel_token.cancel();
    }
}

impl DialogStateReceiverGuard {
    pub(self) async fn dialog_event_loop(&mut self, states: &mut InviteDialogStates) -> Result<()> {
        while let Some(event) = self.recv().await {
            match event {
                DialogState::Calling(dialog_id) => {
                    info!(session_id=states.session_id, %dialog_id, "dialog calling");
                    states.call_state.write().await.session_id = dialog_id.to_string();
                }
                DialogState::Trying(_) => {}
                DialogState::Early(dialog_id, resp) => {
                    let code = resp.status_code.code();
                    let body = resp.body();
                    let answer = String::from_utf8_lossy(body);
                    let has_sdp = !answer.is_empty();
                    info!(session_id=states.session_id, %dialog_id, has_sdp=%has_sdp, "dialog early ({}): \n{}", code, answer);

                    {
                        let mut cs = states.call_state.write().await;
                        if cs.ring_time.is_none() {
                            cs.ring_time.replace(Utc::now());
                        }
                        cs.last_status_code = code;
                    }

                    if !states.is_client {
                        continue;
                    }

                    let refer = states.call_state.read().await.is_refer;

                    states
                        .event_sender
                        .send(crate::event::SessionEvent::Ringing {
                            track_id: states.track_id.clone(),
                            timestamp: crate::media::get_timestamp(),
                            early_media: has_sdp,
                            refer: Some(refer),
                        })?;

                    if has_sdp {
                        states.has_early_media = true;
                        {
                            let mut cs = states.call_state.write().await;
                            if cs.answer.is_none() {
                                cs.answer = Some(answer.to_string());
                            }
                        }
                        states
                            .media_stream
                            .update_remote_description(&states.track_id, &answer.to_string())
                            .await?;
                    }
                }
                DialogState::Confirmed(dialog_id, msg) => {
                    info!(session_id=states.session_id, %dialog_id, has_early_media=%states.has_early_media, "dialog confirmed");
                    {
                        let mut cs = states.call_state.write().await;
                        cs.session_id = dialog_id.to_string();
                        cs.answer_time.replace(Utc::now());
                        cs.last_status_code = 200;
                    }
                    if states.is_client {
                        let answer = String::from_utf8_lossy(msg.body());
                        let answer = answer.trim();
                        if !answer.is_empty() {
                            if states.has_early_media {
                                info!(
                                    session_id = states.session_id,
                                    "updating remote description with final answer after early media (force=true)"
                                );
                                // Force update when transitioning from early media (183) to confirmed (200 OK)
                                // This ensures media parameters are properly updated even if SDP appears similar
                                if let Err(e) = states
                                    .media_stream
                                    .update_remote_description_force(
                                        &states.track_id,
                                        &answer.to_string(),
                                    )
                                    .await
                                {
                                    tracing::warn!(
                                        session_id = states.session_id,
                                        "failed to force update remote description on confirmed: {}",
                                        e
                                    );
                                }
                            } else {
                                if let Err(e) = states
                                    .media_stream
                                    .update_remote_description(
                                        &states.track_id,
                                        &answer.to_string(),
                                    )
                                    .await
                                {
                                    tracing::warn!(
                                        session_id = states.session_id,
                                        "failed to update remote description on confirmed: {}",
                                        e
                                    );
                                }
                            }
                        }
                    }
                }
                DialogState::Info(dialog_id, req, tx_handle) => {
                    let body_str = String::from_utf8_lossy(req.body());
                    info!(session_id=states.session_id, %dialog_id, body=%body_str, "dialog info received");
                    if body_str.starts_with("Signal=") {
                        let digit = body_str.trim_start_matches("Signal=").chars().next();
                        if let Some(digit) = digit {
                            states.event_sender.send(crate::event::SessionEvent::Dtmf {
                                track_id: states.track_id.clone(),
                                timestamp: crate::media::get_timestamp(),
                                digit: digit.to_string(),
                            })?;
                        }
                    }
                    tx_handle.reply(rsipstack::rsip::StatusCode::OK).await.ok();
                }
                DialogState::Updated(dialog_id, _req, tx_handle) => {
                    info!(session_id = states.session_id, %dialog_id, "dialog update received");
                    let mut answer_sdp = None;
                    if let Some(sdp_body) = _req.body().get(..) {
                        let sdp_str = String::from_utf8_lossy(sdp_body);
                        if !sdp_str.is_empty()
                            && (_req.method == rsipstack::rsip::Method::Invite
                                || _req.method == rsipstack::rsip::Method::Update)
                        {
                            info!(session_id=states.session_id, %dialog_id, method=%_req.method, "handling re-invite/update offer");

                            // Detect hold state from SDP
                            let is_on_hold =
                                crate::media::negotiate::detect_hold_state_from_sdp(&sdp_str);
                            info!(session_id=states.session_id, %dialog_id, is_on_hold=%is_on_hold, "detected hold state from re-invite SDP");

                            // Update media stream hold state
                            if is_on_hold {
                                states
                                    .media_stream
                                    .hold_track(Some(states.track_id.clone()))
                                    .await;
                            } else {
                                states
                                    .media_stream
                                    .resume_track(Some(states.track_id.clone()))
                                    .await;
                            }

                            // Emit hold event
                            states
                                .event_sender
                                .send(crate::event::SessionEvent::Hold {
                                    track_id: states.track_id.clone(),
                                    timestamp: crate::media::get_timestamp(),
                                    on_hold: is_on_hold,
                                })
                                .ok();

                            match states
                                .media_stream
                                .handshake(&states.track_id, sdp_str.to_string(), None)
                                .await
                            {
                                Ok(sdp) => answer_sdp = Some(sdp),
                                Err(e) => {
                                    warn!(
                                        session_id = states.session_id,
                                        "failed to handle re-invite: {}", e
                                    );
                                }
                            }
                        } else {
                            info!(session_id=states.session_id, %dialog_id, "updating remote description:\n{}", sdp_str);

                            // Also check hold state for non-INVITE/UPDATE messages with SDP
                            let is_on_hold =
                                crate::media::negotiate::detect_hold_state_from_sdp(&sdp_str);
                            if is_on_hold {
                                states
                                    .media_stream
                                    .hold_track(Some(states.track_id.clone()))
                                    .await;
                                states
                                    .event_sender
                                    .send(crate::event::SessionEvent::Hold {
                                        track_id: states.track_id.clone(),
                                        timestamp: crate::media::get_timestamp(),
                                        on_hold: true,
                                    })
                                    .ok();
                            } else {
                                states
                                    .media_stream
                                    .resume_track(Some(states.track_id.clone()))
                                    .await;
                                states
                                    .event_sender
                                    .send(crate::event::SessionEvent::Hold {
                                        track_id: states.track_id.clone(),
                                        timestamp: crate::media::get_timestamp(),
                                        on_hold: false,
                                    })
                                    .ok();
                            }

                            states
                                .media_stream
                                .update_remote_description(&states.track_id, &sdp_str.to_string())
                                .await?;
                        }
                    }

                    if let Some(sdp) = answer_sdp {
                        tx_handle
                            .respond(
                                rsipstack::rsip::StatusCode::OK,
                                Some(vec![rsipstack::rsip::Header::ContentType(
                                    "application/sdp".to_string().into(),
                                )]),
                                Some(sdp.into()),
                            )
                            .await
                            .ok();
                    } else {
                        tx_handle.reply(rsipstack::rsip::StatusCode::OK).await.ok();
                    }
                }
                DialogState::Options(dialog_id, _req, tx_handle) => {
                    info!(session_id = states.session_id, %dialog_id, "dialog options received");
                    tx_handle.reply(rsipstack::rsip::StatusCode::OK).await.ok();
                }
                DialogState::Terminated(dialog_id, reason) => {
                    info!(
                        session_id = states.session_id,
                        ?dialog_id,
                        ?reason,
                        "dialog terminated"
                    );
                    states.terminated_reason = Some(reason.clone());
                    return Ok(());
                }
                other_state => {
                    info!(
                        session_id = states.session_id,
                        %other_state,
                        "dialog received other state"
                    );
                }
            }
        }
        Ok(())
    }

    pub(super) async fn process_dialog(&mut self, mut states: InviteDialogStates) {
        let token = states.cancel_token.clone();
        tokio::select! {
            _ = token.cancelled() => {
                states.terminated_reason = Some(TerminatedReason::UacCancel);
            }
            _ = self.dialog_event_loop(&mut states) => {}
        };

        // Update hangup headers from ActiveCallState if available
        {
            let state = states.call_state.read().await;
            if let Some(extras) = &state.extras {
                if let Some(h_val) = extras.get("_hangup_headers") {
                    if let Ok(headers_map) =
                        serde_json::from_value::<HashMap<String, String>>(h_val.clone())
                    {
                        let mut headers = Vec::new();
                        for (k, v) in headers_map {
                            headers.push(rsipstack::rsip::Header::Other(k.into(), v.into()));
                        }
                        if !headers.is_empty() {
                            if let Some(existing) = &mut self.hangup_headers {
                                existing.extend(headers);
                            } else {
                                self.hangup_headers = Some(headers);
                            }
                        }
                    }
                }
            }
        }

        self.drop_async().await;
    }
}

#[derive(Clone)]
pub struct Invitation {
    pub dialog_layer: Arc<DialogLayer>,
    pub pending_dialogs: Arc<std::sync::Mutex<HashMap<DialogId, PendingDialog>>>,
}

impl Invitation {
    pub fn new(dialog_layer: Arc<DialogLayer>) -> Self {
        Self {
            dialog_layer,
            pending_dialogs: Arc::new(std::sync::Mutex::new(HashMap::new())),
        }
    }

    pub fn add_pending(&self, dialog_id: DialogId, pending: PendingDialog) {
        self.pending_dialogs
            .lock()
            .map(|mut ps| ps.insert(dialog_id, pending))
            .ok();
    }

    pub fn get_pending_call(&self, dialog_id: &DialogId) -> Option<PendingDialog> {
        self.pending_dialogs
            .lock()
            .ok()
            .and_then(|mut ps| ps.remove(dialog_id))
    }

    pub fn has_pending_call(&self, dialog_id: &DialogId) -> bool {
        self.pending_dialogs
            .lock()
            .ok()
            .map(|ps| ps.contains_key(dialog_id))
            .unwrap_or(false)
    }

    pub fn find_dialog_id_by_session_id(&self, session_id: &str) -> Option<DialogId> {
        self.pending_dialogs.lock().ok().and_then(|ps| {
            ps.iter()
                .find(|(id, _)| id.to_string() == session_id)
                .map(|(id, _)| id.clone())
        })
    }

    pub async fn hangup(
        &self,
        dialog_id: DialogId,
        code: Option<rsipstack::rsip::StatusCode>,
        reason: Option<String>,
    ) -> Result<()> {
        if let Some(call) = self.get_pending_call(&dialog_id) {
            call.dialog.reject(code, reason).ok();
            call.token.cancel();
        }
        match self.dialog_layer.get_dialog(&dialog_id) {
            Some(dialog) => {
                self.dialog_layer.remove_dialog(&dialog_id);
                dialog.hangup().await.ok();
            }
            None => {}
        }
        Ok(())
    }

    pub async fn reject(&self, dialog_id: DialogId) -> Result<()> {
        if let Some(call) = self.get_pending_call(&dialog_id) {
            call.dialog.reject(None, None).ok();
            call.token.cancel();
        }
        match self.dialog_layer.get_dialog(&dialog_id) {
            Some(dialog) => {
                self.dialog_layer.remove_dialog(&dialog_id);
                dialog.hangup().await.ok();
            }
            None => {}
        }
        Ok(())
    }

    pub async fn invite(
        &self,
        invite_option: InviteOption,
        state_sender: DialogStateSender,
    ) -> Result<(DialogId, Option<Vec<u8>>), rsipstack::Error> {
        let (dialog, resp) = self
            .dialog_layer
            .do_invite(invite_option, state_sender)
            .await?;

        let offer = match resp {
            Some(resp) => match resp.status_code.kind() {
                rsipstack::rsip::StatusCodeKind::Successful => {
                    let offer = resp.body.clone();
                    Some(offer)
                }
                _ => {
                    let reason = resp
                        .reason_phrase()
                        .unwrap_or(&resp.status_code.to_string())
                        .to_string();
                    return Err(rsipstack::Error::DialogError(
                        reason,
                        dialog.id(),
                        resp.status_code,
                    ));
                }
            },
            None => {
                return Err(rsipstack::Error::DialogError(
                    "no response received".to_string(),
                    dialog.id(),
                    rsipstack::rsip::StatusCode::NotAcceptableHere,
                ));
            }
        };
        Ok((dialog.id(), offer))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::call::active_call::ActiveCallState;
    use crate::media::stream::MediaStreamBuilder;
    use std::sync::Arc;
    use tokio::sync::RwLock;
    use tokio_util::sync::CancellationToken;

    // SDP used to simulate an early-media 183 Session Progress response.
    const EARLY_MEDIA_SDP: &str = "v=0\r\n\
        o=- 1000 1 IN IP4 192.168.1.100\r\n\
        s=SIP Call\r\n\
        t=0 0\r\n\
        m=audio 10000 RTP/AVP 0\r\n\
        c=IN IP4 192.168.1.100\r\n\
        a=rtpmap:0 PCMU/8000\r\n\
        a=sendrecv\r\n";

    fn make_response_with_body(body: Vec<u8>) -> rsipstack::rsip::Response {
        let mut resp = rsipstack::rsip::Response::default();
        resp.body = body;
        resp
    }

    /// Verify that when a 183 Session Progress with SDP arrives (`DialogState::Early`),
    /// the early SDP is stored in `call_state.answer` so it can serve as a fallback
    /// when the final 200 OK has an empty body.
    #[tokio::test]
    async fn test_early_sdp_stored_in_call_state() {
        let (event_tx, _event_rx) = tokio::sync::broadcast::channel(16);
        let media_stream = Arc::new(
            MediaStreamBuilder::new(event_tx.clone())
                .with_id("test-stream".to_string())
                .build(),
        );
        let call_state: ActiveCallStateRef = Arc::new(RwLock::new(ActiveCallState::default()));
        let cancel_token = CancellationToken::new();

        let mut states = InviteDialogStates {
            is_client: true,
            session_id: "test-session".to_string(),
            track_id: "test-track".to_string(),
            cancel_token: cancel_token.clone(),
            event_sender: event_tx.clone(),
            call_state: call_state.clone(),
            media_stream: media_stream.clone(),
            terminated_reason: None,
            has_early_media: false,
        };

        // Simulate DialogState::Early with SDP body (183 Session Progress)
        let early_resp = make_response_with_body(EARLY_MEDIA_SDP.as_bytes().to_vec());

        // Manually execute the Early branch logic (same as dialog_event_loop)
        let body = early_resp.body();
        let answer = String::from_utf8_lossy(body);
        let has_sdp = !answer.is_empty();
        if states.is_client && has_sdp {
            states.has_early_media = true;
            {
                let mut cs = states.call_state.write().await;
                if cs.answer.is_none() {
                    cs.answer = Some(answer.to_string());
                }
            }
            // (update_remote_description skipped — no real RTC peer)
        }

        // Assert: early SDP is stored in call_state.answer
        {
            let cs = call_state.read().await;
            assert!(
                cs.answer.is_some(),
                "call_state.answer should be set after 183 with SDP"
            );
            assert_eq!(
                cs.answer.as_deref().unwrap(),
                EARLY_MEDIA_SDP,
                "call_state.answer should contain the early SDP"
            );
        }
        assert!(states.has_early_media, "has_early_media should be true");
    }

    /// Verify that when a 200 OK arrives with an empty body after early media has been
    /// negotiated, `call_state.answer` retains the early SDP (not overwritten with "").
    ///
    /// This is the regression test for the bug where a late 200 OK with empty body would
    /// cause `SessionEvent::Answer { sdp: "" }` to be emitted, making the answer event
    /// appear as if no SDP was negotiated.
    #[tokio::test]
    async fn test_confirmed_empty_body_keeps_early_sdp() {
        let (event_tx, _event_rx) = tokio::sync::broadcast::channel(16);
        let media_stream = Arc::new(
            MediaStreamBuilder::new(event_tx.clone())
                .with_id("test-stream-2".to_string())
                .build(),
        );
        let call_state: ActiveCallStateRef = Arc::new(RwLock::new(ActiveCallState::default()));
        let cancel_token = CancellationToken::new();

        let mut states = InviteDialogStates {
            is_client: true,
            session_id: "test-session-2".to_string(),
            track_id: "test-track-2".to_string(),
            cancel_token: cancel_token.clone(),
            event_sender: event_tx.clone(),
            call_state: call_state.clone(),
            media_stream: media_stream.clone(),
            terminated_reason: None,
            has_early_media: false,
        };

        // Step 1: simulate 183 with SDP → set has_early_media and cs.answer
        {
            let answer_str = EARLY_MEDIA_SDP.to_string();
            states.has_early_media = true;
            let mut cs = states.call_state.write().await;
            if cs.answer.is_none() {
                cs.answer = Some(answer_str);
            }
        }

        // Step 2: simulate 200 OK with empty body (Confirmed handler logic)
        let confirmed_resp = make_response_with_body(vec![]); // empty body
        {
            let mut cs = states.call_state.write().await;
            cs.answer_time.replace(chrono::Utc::now());
            cs.last_status_code = 200;
        }
        // The Confirmed handler in dialog_event_loop only calls update_remote_description
        // when body is non-empty; it does NOT overwrite cs.answer.
        let body = confirmed_resp.body();
        let answer = String::from_utf8_lossy(body);
        let answer_trimmed = answer.trim();
        // Replicate Confirmed handler: only act on non-empty body
        if states.is_client && !answer_trimmed.is_empty() {
            // (Would call update_remote_description or update_remote_description_force)
            // This branch should NOT execute for empty-body 200 OK
            panic!("Confirmed handler should not update SDP for empty body");
        }

        // Assert: call_state.answer still holds the early SDP
        {
            let cs = call_state.read().await;
            assert!(
                cs.answer.is_some(),
                "call_state.answer must not be None after 200 OK with empty body"
            );
            let stored_answer = cs.answer.as_deref().unwrap();
            assert!(
                !stored_answer.is_empty(),
                "call_state.answer must not be empty after 200 OK with empty body"
            );
            assert_eq!(
                stored_answer, EARLY_MEDIA_SDP,
                "call_state.answer should still be the early SDP after 200 OK with empty body"
            );
        }
    }

    /// Verify that `create_outgoing_sip_track`'s fallback logic works:
    /// when the 200 OK body is empty but `call_state.answer` has the early SDP,
    /// the fallback path is taken and the early SDP is returned (not an empty string).
    ///
    /// This test directly validates the fix in `create_outgoing_sip_track` by
    /// simulating the state that would exist after a 183+early-media exchange.
    #[tokio::test]
    async fn test_answer_fallback_to_early_sdp_when_200ok_empty() {
        // Set up call state as it would be after early media (183 with SDP) was processed
        let call_state: ActiveCallStateRef = Arc::new(RwLock::new(ActiveCallState::default()));

        // Simulate what the Early (183) handler does: store the early SDP in cs.answer
        {
            let mut cs = call_state.write().await;
            cs.answer = Some(EARLY_MEDIA_SDP.to_string());
        }

        // Simulate what create_outgoing_sip_track does when 200 OK has empty body:
        //   answer = Some(vec![])  →  s = ""  →  s.trim().is_empty() → fallback
        let raw_answer: Option<Vec<u8>> = Some(vec![]); // empty body from 200 OK

        let resolved_answer = match raw_answer {
            Some(bytes) => {
                let s = String::from_utf8_lossy(&bytes).to_string();
                if s.trim().is_empty() {
                    // Fallback: use early SDP stored by the 183 handler
                    let cs = call_state.read().await;
                    match cs.answer.clone() {
                        Some(early_sdp) if !early_sdp.is_empty() => {
                            (early_sdp, true /* already applied */)
                        }
                        _ => (s, false),
                    }
                } else {
                    (s, false)
                }
            }
            None => {
                let cs = call_state.read().await;
                match cs.answer.clone() {
                    Some(early_sdp) if !early_sdp.is_empty() => (early_sdp, true),
                    _ => panic!("Expected early SDP fallback"),
                }
            }
        };

        let (answer, already_applied) = resolved_answer;

        // The answer returned to setup_caller_track (and used in SessionEvent::Answer)
        // must be the early SDP, not an empty string.
        assert!(
            !answer.is_empty(),
            "Resolved answer must not be empty — should contain the early SDP"
        );
        assert_eq!(
            answer, EARLY_MEDIA_SDP,
            "Resolved answer should be the early SDP from the 183 handler"
        );
        assert!(
            already_applied,
            "remote_description_already_applied should be true when using early SDP fallback"
        );
    }

    /// Verify the normal case: when 200 OK carries its own SDP body,
    /// that SDP is used directly (not the early SDP) and remote description
    /// should be applied.
    #[tokio::test]
    async fn test_answer_uses_200ok_sdp_when_present() {
        const FINAL_SDP: &str = "v=0\r\n\
            o=- 2000 2 IN IP4 10.0.0.1\r\n\
            s=SIP Call\r\n\
            t=0 0\r\n\
            m=audio 20000 RTP/AVP 0\r\n\
            c=IN IP4 10.0.0.1\r\n\
            a=rtpmap:0 PCMU/8000\r\n\
            a=sendrecv\r\n";

        let call_state: ActiveCallStateRef = Arc::new(RwLock::new(ActiveCallState::default()));

        // Even with early SDP stored, when 200 OK has SDP body it should be used
        {
            let mut cs = call_state.write().await;
            cs.answer = Some(EARLY_MEDIA_SDP.to_string());
        }

        let raw_answer: Option<Vec<u8>> = Some(FINAL_SDP.as_bytes().to_vec());

        let resolved_answer = match raw_answer {
            Some(bytes) => {
                let s = String::from_utf8_lossy(&bytes).to_string();
                if s.trim().is_empty() {
                    let cs = call_state.read().await;
                    match cs.answer.clone() {
                        Some(early_sdp) if !early_sdp.is_empty() => (early_sdp, true),
                        _ => (s, false),
                    }
                } else {
                    (s, false) // ← normal case: use 200 OK SDP, apply it
                }
            }
            None => panic!("Unexpected"),
        };

        let (answer, already_applied) = resolved_answer;

        assert_eq!(
            answer, FINAL_SDP,
            "When 200 OK has SDP, it should be used (not the early SDP)"
        );
        assert!(
            !already_applied,
            "remote_description_already_applied should be false when 200 OK has SDP body"
        );
    }
}