Skip to main content

ringo_agent/
proto.rs

1//! The wire protocol between the parent and a `ringo-flow agent` worker process.
2//!
3//! Length-prefixed frames (`[kind][len][payload]`, see [`write_frame`]) so JSON
4//! control and raw binary audio share one stream per direction:
5//!   * **parent → child** (worker stdin): control frames carrying [`ToWorker`]
6//!     (a [`Command`] or an id-correlated [`Query`]), plus raw audio frames (TTS
7//!     PCM played into the call after `StartTxAudio`).
8//!   * **child → parent** (worker stdout): control frames carrying [`FromWorker`]
9//!     (events, query replies, header pushes, readiness), plus raw audio frames
10//!     (received-call PCM after `StartRxAudio`, preceded by `RxAudioStarted`).
11//!
12//! The worker's **stderr** carries logs / SIP traces and is never part of the
13//! protocol, so the framed stream stays clean.
14
15use ringo_core::account::{Account, BackendOptions};
16use ringo_core::event::{AppEvent, InviteHeaders, MediaStats};
17use serde::{Deserialize, Serialize};
18use std::io::{self, Read, Write};
19
20// ── wire framing ──────────────────────────────────────────────────────────--
21//
22// The wire is length-prefixed frames (not line-delimited), so raw binary audio
23// and JSON control can share one stream without escaping: `[kind:u8][len:u32
24// LE][payload]`. A control frame's payload is JSON (a `ToWorker`/`FromWorker`);
25// an audio frame's payload is raw mono s16le PCM.
26
27/// Frame kind: JSON control message.
28pub(crate) const FRAME_CONTROL: u8 = 0;
29/// Frame kind: raw mono s16le PCM audio.
30pub(crate) const FRAME_AUDIO: u8 = 1;
31
32/// Reject absurd frame lengths from a corrupt stream (far above any real frame).
33const MAX_FRAME_LEN: usize = 16 * 1024 * 1024;
34
35/// Write one frame: `[kind][len][payload]`, flushed.
36pub(crate) fn write_frame<W: Write>(w: &mut W, kind: u8, payload: &[u8]) -> io::Result<()> {
37    if payload.len() > MAX_FRAME_LEN {
38        return Err(io::Error::new(
39            io::ErrorKind::InvalidInput,
40            "frame too large",
41        ));
42    }
43    w.write_all(&[kind])?;
44    w.write_all(&(payload.len() as u32).to_le_bytes())?;
45    w.write_all(payload)?;
46    w.flush()
47}
48
49/// Read one frame; `Ok(None)` only on a *clean* EOF at a frame boundary (no
50/// bytes of a new frame seen). EOF partway through the header or payload is a
51/// torn frame and surfaces as an error, not a clean close.
52pub(crate) fn read_frame<R: Read>(r: &mut R) -> io::Result<Option<(u8, Vec<u8>)>> {
53    let mut hdr = [0u8; 5];
54    // Read the header byte-by-byte so we can tell "nothing arrived" (clean EOF)
55    // from "EOF mid-header" (torn frame). read_exact can't distinguish them.
56    let mut filled = 0;
57    while filled < hdr.len() {
58        match r.read(&mut hdr[filled..]) {
59            Ok(0) if filled == 0 => return Ok(None), // clean frame-boundary EOF
60            Ok(0) => {
61                return Err(io::Error::new(
62                    io::ErrorKind::UnexpectedEof,
63                    "EOF in frame header",
64                ));
65            }
66            Ok(n) => filled += n,
67            Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
68            Err(e) => return Err(e),
69        }
70    }
71    let kind = hdr[0];
72    let len = u32::from_le_bytes([hdr[1], hdr[2], hdr[3], hdr[4]]) as usize;
73    if len > MAX_FRAME_LEN {
74        return Err(io::Error::new(
75            io::ErrorKind::InvalidData,
76            "frame too large",
77        ));
78    }
79    let mut payload = vec![0u8; len];
80    r.read_exact(&mut payload)?;
81    Ok(Some((kind, payload)))
82}
83
84/// Mono s16 samples → little-endian audio-frame bytes.
85pub(crate) fn pcm_to_bytes(samples: &[i16]) -> Vec<u8> {
86    let mut v = Vec::with_capacity(samples.len() * 2);
87    for &s in samples {
88        v.extend_from_slice(&s.to_le_bytes());
89    }
90    v
91}
92
93/// Little-endian audio-frame bytes → mono s16 samples (trailing odd byte ignored).
94pub(crate) fn bytes_to_pcm(bytes: &[u8]) -> Vec<i16> {
95    bytes
96        .chunks_exact(2)
97        .map(|c| i16::from_le_bytes([c[0], c[1]]))
98        .collect()
99}
100
101// ── handshake ─────────────────────────────────────────────────────────────--
102
103/// Wire-protocol version. Parent and worker are normally the same binary, but a
104/// stale worker (old binary on `$PATH`, a half-finished upgrade) would otherwise
105/// desync silently on the framed stream. The worker rejects a mismatching
106/// version at the handshake instead. Bump on any incompatible wire change.
107pub(crate) const PROTO_VERSION: u32 = 1;
108
109/// The first frame the parent sends: the protocol version plus the agent config.
110/// Versioning lives here, on the wire envelope, so the public [`AgentConfig`]
111/// stays a plain user-facing struct.
112#[derive(Debug, Clone, Serialize, Deserialize)]
113pub(crate) struct Handshake {
114    /// Sender's [`PROTO_VERSION`]; the worker bails if it doesn't match its own.
115    pub proto_version: u32,
116    /// The agent configuration to spawn.
117    pub config: AgentConfig,
118}
119
120/// The full agent configuration the parent sends as the worker's first stdin
121/// line (before any command/query). Carrying it on stdin rather than argv keeps
122/// credentials out of the process table. The `Account`/`BackendOptions` are
123/// embedded verbatim (they are `Serialize`/`Deserialize` in ringo-core), so the
124/// worker rebuilds the *exact* account the in-process path would — adding a
125/// field to either struct can't silently drift out of sync.
126#[derive(Debug, Clone, Default, Serialize, Deserialize)]
127pub struct AgentConfig {
128    /// Label for the agent (used in logs / per-agent log file names).
129    pub name: String,
130    /// The SIP account to register.
131    pub account: Account,
132    /// Backend options (audio driver, timeouts, recording, …).
133    pub options: BackendOptions,
134}
135
136// ── parent → child ──────────────────────────────────────────────────────────
137
138/// A fire-and-forget phone action.
139#[derive(Debug, Clone, Serialize, Deserialize)]
140#[serde(tag = "cmd", rename_all = "snake_case")]
141pub enum Command {
142    Register {
143        aor: String,
144        regint: u32,
145    },
146    Dial {
147        number: String,
148    },
149    Hangup,
150    HangupAll,
151    Accept,
152    Hold,
153    Resume,
154    Mute,
155    Dtmf {
156        digit: char,
157    },
158    SwitchLine {
159        line: usize,
160    },
161    Transfer {
162        uri: String,
163    },
164    AttendedTransferStart {
165        uri: String,
166    },
167    AttendedTransferExec,
168    AttendedTransferAbort,
169    AddHeader {
170        key: String,
171        value: String,
172    },
173    RmHeader {
174        key: String,
175    },
176    SetAudioSource {
177        spec: String,
178    },
179    ArmInviteResponse {
180        scode: u16,
181        reason: String,
182        headers: Vec<String>,
183    },
184    DisarmInviteResponse,
185    /// Switch the agent's audio source to live-streamed PCM at `rate` Hz; raw
186    /// audio frames (kind=1) on stdin are then played into the call (TTS).
187    StartTxAudio {
188        rate: u32,
189    },
190    /// Begin streaming the agent's received audio: the worker emits an
191    /// `RxAudioStarted` control message then raw audio frames (kind=1) on stdout.
192    StartRxAudio,
193    /// Graceful shutdown request (also triggered by stdin EOF).
194    Shutdown,
195}
196
197/// A request that expects exactly one [`Reply`] with the matching `id`.
198#[derive(Debug, Clone, Serialize, Deserialize)]
199#[serde(tag = "query", rename_all = "snake_case")]
200pub enum Query {
201    /// RTP media stats for the active/last call.
202    MediaStats,
203    /// DTMF digits received so far.
204    ReceivedDtmf,
205    /// Write the agent's captured sent/received audio as WAV files named
206    /// `<prefix>-sent.wav` / `<prefix>-recv.wav`; returns the paths written.
207    SaveAudio { prefix: String },
208    /// Number of active calls (for teardown's BYE-flush wait).
209    CallCount,
210}
211
212/// A [`Query`] tagged with a correlation id.
213#[derive(Debug, Clone, Serialize, Deserialize)]
214pub struct QueryEnvelope {
215    pub id: u64,
216    #[serde(flatten)]
217    pub query: Query,
218}
219
220/// Anything the parent writes to the worker's stdin. Untagged — disjoint by the
221/// distinguishing key `cmd` (Command) vs `query` (QueryEnvelope). Do NOT add a
222/// variant whose payload reuses either key.
223#[derive(Debug, Clone, Serialize, Deserialize)]
224#[serde(untagged)]
225pub enum ToWorker {
226    Cmd(Command),
227    Query(QueryEnvelope),
228}
229
230// ── child → parent ──────────────────────────────────────────────────────────
231
232/// RTP media stats, mirroring [`MediaStats`] (which carries no serde derives).
233#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
234pub struct WireMediaStats {
235    pub rtt_ms: f64,
236    pub jitter_ms: f64,
237    pub rx_lost: i32,
238    pub packet_loss_pct: f64,
239    pub mos: f64,
240}
241
242impl From<MediaStats> for WireMediaStats {
243    fn from(s: MediaStats) -> Self {
244        Self {
245            rtt_ms: s.rtt_ms,
246            jitter_ms: s.jitter_ms,
247            rx_lost: s.rx_lost,
248            packet_loss_pct: s.packet_loss_pct,
249            mos: s.mos,
250        }
251    }
252}
253
254impl From<WireMediaStats> for MediaStats {
255    fn from(s: WireMediaStats) -> Self {
256        Self {
257            rtt_ms: s.rtt_ms,
258            jitter_ms: s.jitter_ms,
259            rx_lost: s.rx_lost,
260            packet_loss_pct: s.packet_loss_pct,
261            mos: s.mos,
262        }
263    }
264}
265
266/// The payload of a [`Reply`], one variant per [`Query`]. Externally tagged
267/// (e.g. `{"call_count":2}`) so newtype variants over primitives/sequences
268/// round-trip — internal tagging can't carry those.
269#[derive(Debug, Clone, Serialize, Deserialize)]
270#[serde(rename_all = "snake_case")]
271pub enum ReplyResult {
272    MediaStats(Option<WireMediaStats>),
273    Dtmf(String),
274    Saved(Vec<String>),
275    CallCount(u32),
276}
277
278/// A response to a [`Query`], correlated by `id` (e.g.
279/// `{"reply":7,"result":{"call_count":2}}`).
280#[derive(Debug, Clone, Serialize, Deserialize)]
281pub struct Reply {
282    pub reply: u64,
283    pub result: ReplyResult,
284}
285
286/// A push of received INVITE headers (keyed by SIP Call-ID).
287#[derive(Debug, Clone, Serialize, Deserialize)]
288pub struct Headers {
289    pub headers: InviteHeaders,
290}
291
292/// Readiness handshake: the worker emits this as its FIRST stdout message once
293/// the backend is up, so [`crate::client::ProcessClient::spawn`] can surface a
294/// bad config / failed backend at spawn time instead of as a later query timeout.
295#[derive(Debug, Clone, Serialize, Deserialize)]
296pub struct Ready {
297    pub ready: bool,
298}
299
300/// Sent once after `StartRxAudio`, before the raw RX audio frames, so the parent
301/// knows the sample rate of the mono s16 frames that follow.
302#[derive(Debug, Clone, Serialize, Deserialize)]
303pub struct RxAudioStarted {
304    pub rx_audio_rate: u32,
305}
306
307/// A control message the worker writes to its stdout (the `control`-kind frame
308/// payload). Untagged — the variants are disjoint by their distinguishing key:
309/// `ready` / `event` / `reply` / `headers` / `rx_audio_rate`. Do NOT add a
310/// variant whose payload reuses one of those keys.
311#[derive(Debug, Clone, Serialize, Deserialize)]
312#[serde(untagged)]
313pub enum FromWorker {
314    Ready(Ready),
315    Event(WireEvent),
316    Reply(Reply),
317    Headers(Headers),
318    RxAudioStarted(RxAudioStarted),
319}
320
321/// A serializable mirror of [`AppEvent`] (which lives in `ringo-core` and
322/// carries no serde derives).
323#[derive(Debug, Clone, Serialize, Deserialize)]
324#[serde(tag = "event", rename_all = "snake_case")]
325pub enum WireEvent {
326    Registering {
327        account: String,
328    },
329    RegisterOk {
330        account: String,
331    },
332    RegisterFailed {
333        reason: String,
334    },
335    Unregistered {
336        account: String,
337    },
338    CallIncoming {
339        call_id: String,
340        number: String,
341        display_name: Option<String>,
342    },
343    CallOutgoing {
344        call_id: String,
345        number: String,
346    },
347    CallRinging {
348        call_id: String,
349    },
350    CallEstablished {
351        call_id: String,
352    },
353    CallClosed {
354        call_id: String,
355        reason: String,
356        error: bool,
357    },
358    VoicemailStatus {
359        waiting: bool,
360        new_count: u32,
361    },
362    Response {
363        ok: bool,
364        data: String,
365    },
366    Unknown {
367        class: String,
368        type_: String,
369    },
370    BackendConnectFailed {
371        reason: String,
372    },
373}
374
375impl From<&AppEvent> for WireEvent {
376    fn from(e: &AppEvent) -> Self {
377        match e {
378            AppEvent::Registering { account } => Self::Registering {
379                account: account.clone(),
380            },
381            AppEvent::RegisterOk { account } => Self::RegisterOk {
382                account: account.clone(),
383            },
384            AppEvent::RegisterFailed { reason } => Self::RegisterFailed {
385                reason: reason.clone(),
386            },
387            AppEvent::Unregistered { account } => Self::Unregistered {
388                account: account.clone(),
389            },
390            AppEvent::CallIncoming {
391                call_id,
392                number,
393                display_name,
394            } => Self::CallIncoming {
395                call_id: call_id.clone(),
396                number: number.clone(),
397                display_name: display_name.clone(),
398            },
399            AppEvent::CallOutgoing { call_id, number } => Self::CallOutgoing {
400                call_id: call_id.clone(),
401                number: number.clone(),
402            },
403            AppEvent::CallRinging { call_id } => Self::CallRinging {
404                call_id: call_id.clone(),
405            },
406            AppEvent::CallEstablished { call_id } => Self::CallEstablished {
407                call_id: call_id.clone(),
408            },
409            AppEvent::CallClosed {
410                call_id,
411                reason,
412                error,
413            } => Self::CallClosed {
414                call_id: call_id.clone(),
415                reason: reason.clone(),
416                error: *error,
417            },
418            AppEvent::VoicemailStatus { waiting, new_count } => Self::VoicemailStatus {
419                waiting: *waiting,
420                new_count: *new_count,
421            },
422            AppEvent::Response { ok, data } => Self::Response {
423                ok: *ok,
424                data: data.clone(),
425            },
426            AppEvent::Unknown { class, type_ } => Self::Unknown {
427                class: class.clone(),
428                type_: type_.clone(),
429            },
430            AppEvent::BackendConnectFailed { reason } => Self::BackendConnectFailed {
431                reason: reason.clone(),
432            },
433        }
434    }
435}
436
437impl From<WireEvent> for AppEvent {
438    fn from(w: WireEvent) -> Self {
439        match w {
440            WireEvent::Registering { account } => AppEvent::Registering { account },
441            WireEvent::RegisterOk { account } => AppEvent::RegisterOk { account },
442            WireEvent::RegisterFailed { reason } => AppEvent::RegisterFailed { reason },
443            WireEvent::Unregistered { account } => AppEvent::Unregistered { account },
444            WireEvent::CallIncoming {
445                call_id,
446                number,
447                display_name,
448            } => AppEvent::CallIncoming {
449                call_id,
450                number,
451                display_name,
452            },
453            WireEvent::CallOutgoing { call_id, number } => {
454                AppEvent::CallOutgoing { call_id, number }
455            }
456            WireEvent::CallRinging { call_id } => AppEvent::CallRinging { call_id },
457            WireEvent::CallEstablished { call_id } => AppEvent::CallEstablished { call_id },
458            WireEvent::CallClosed {
459                call_id,
460                reason,
461                error,
462            } => AppEvent::CallClosed {
463                call_id,
464                reason,
465                error,
466            },
467            WireEvent::VoicemailStatus { waiting, new_count } => {
468                AppEvent::VoicemailStatus { waiting, new_count }
469            }
470            WireEvent::Response { ok, data } => AppEvent::Response { ok, data },
471            WireEvent::Unknown { class, type_ } => AppEvent::Unknown { class, type_ },
472            WireEvent::BackendConnectFailed { reason } => AppEvent::BackendConnectFailed { reason },
473        }
474    }
475}
476
477#[cfg(test)]
478mod tests {
479    use super::*;
480
481    #[test]
482    fn command_roundtrips_as_to_worker() {
483        let line = serde_json::to_string(&ToWorker::Cmd(Command::Dial {
484            number: "sip:1@example.com".into(),
485        }))
486        .unwrap();
487        assert_eq!(line, r#"{"cmd":"dial","number":"sip:1@example.com"}"#);
488        assert!(matches!(
489            serde_json::from_str::<ToWorker>(&line).unwrap(),
490            ToWorker::Cmd(Command::Dial { .. })
491        ));
492    }
493
494    #[test]
495    fn query_envelope_roundtrips_as_to_worker() {
496        let line = serde_json::to_string(&ToWorker::Query(QueryEnvelope {
497            id: 7,
498            query: Query::SaveAudio {
499                prefix: "rec".into(),
500            },
501        }))
502        .unwrap();
503        let back: ToWorker = serde_json::from_str(&line).unwrap();
504        match back {
505            ToWorker::Query(QueryEnvelope {
506                id,
507                query: Query::SaveAudio { prefix },
508            }) => {
509                assert_eq!((id, prefix.as_str()), (7, "rec"));
510            }
511            _ => panic!("expected save_audio query"),
512        }
513    }
514
515    #[test]
516    fn event_and_reply_disambiguate_as_from_worker() {
517        let ev = serde_json::to_string(&FromWorker::Event(WireEvent::RegisterOk {
518            account: "a".into(),
519        }))
520        .unwrap();
521        assert!(matches!(
522            serde_json::from_str::<FromWorker>(&ev).unwrap(),
523            FromWorker::Event(WireEvent::RegisterOk { .. })
524        ));
525
526        let rep = serde_json::to_string(&FromWorker::Reply(Reply {
527            reply: 7,
528            result: ReplyResult::CallCount(2),
529        }))
530        .unwrap();
531        match serde_json::from_str::<FromWorker>(&rep).unwrap() {
532            FromWorker::Reply(Reply {
533                reply,
534                result: ReplyResult::CallCount(n),
535            }) => {
536                assert_eq!((reply, n), (7, 2));
537            }
538            _ => panic!("expected call_count reply"),
539        }
540    }
541
542    #[test]
543    fn app_event_mirrors_both_ways() {
544        let ev = AppEvent::CallIncoming {
545            call_id: "abc".into(),
546            number: "sip:1@x".into(),
547            display_name: Some("Bob".into()),
548        };
549        let line = serde_json::to_string(&WireEvent::from(&ev)).unwrap();
550        let back: AppEvent = serde_json::from_str::<WireEvent>(&line).unwrap().into();
551        assert!(matches!(back, AppEvent::CallIncoming { .. }));
552    }
553
554    #[test]
555    fn ready_disambiguates_from_an_event() {
556        let ready = serde_json::to_string(&FromWorker::Ready(Ready { ready: true })).unwrap();
557        assert!(matches!(
558            serde_json::from_str::<FromWorker>(&ready).unwrap(),
559            FromWorker::Ready(Ready { ready: true })
560        ));
561        // An event must NOT be mis-parsed as Ready (disjoint keys).
562        let ev = serde_json::to_string(&FromWorker::Event(WireEvent::RegisterOk {
563            account: "a".into(),
564        }))
565        .unwrap();
566        assert!(matches!(
567            serde_json::from_str::<FromWorker>(&ev).unwrap(),
568            FromWorker::Event(_)
569        ));
570    }
571
572    #[test]
573    fn handshake_carries_version_and_config() {
574        let mut cfg = AgentConfig {
575            name: "A".into(),
576            ..Default::default()
577        };
578        cfg.account.username = "alice".into();
579        let hs = Handshake {
580            proto_version: PROTO_VERSION,
581            config: cfg,
582        };
583        let line = serde_json::to_string(&hs).unwrap();
584        let back: Handshake = serde_json::from_str(&line).unwrap();
585        assert_eq!(back.proto_version, PROTO_VERSION);
586        assert_eq!(back.config.account.username, "alice");
587    }
588
589    #[test]
590    fn agent_config_roundtrips_with_embedded_account() {
591        let mut cfg = AgentConfig {
592            name: "A".into(),
593            ..Default::default()
594        };
595        cfg.account.username = "alice".into();
596        cfg.account.catchall = true;
597        cfg.options.audio_driver = Some("aubridge".into());
598        let line = serde_json::to_string(&cfg).unwrap();
599        let back: AgentConfig = serde_json::from_str(&line).unwrap();
600        assert_eq!(back.name, "A");
601        assert_eq!(back.account.username, "alice");
602        assert!(back.account.catchall);
603        assert_eq!(back.options.audio_driver.as_deref(), Some("aubridge"));
604    }
605
606    #[test]
607    fn frames_roundtrip_control_then_audio() {
608        let mut buf: Vec<u8> = Vec::new();
609        write_frame(&mut buf, FRAME_CONTROL, b"{\"cmd\":\"accept\"}").unwrap();
610        write_frame(&mut buf, FRAME_AUDIO, &pcm_to_bytes(&[1, -2, 3])).unwrap();
611        let mut r = &buf[..];
612        let (k1, p1) = read_frame(&mut r).unwrap().unwrap();
613        assert_eq!(k1, FRAME_CONTROL);
614        assert_eq!(p1, b"{\"cmd\":\"accept\"}");
615        let (k2, p2) = read_frame(&mut r).unwrap().unwrap();
616        assert_eq!(k2, FRAME_AUDIO);
617        assert_eq!(bytes_to_pcm(&p2), vec![1, -2, 3]);
618        assert!(read_frame(&mut r).unwrap().is_none()); // clean EOF
619    }
620
621    #[test]
622    fn audio_frame_can_contain_newline_bytes() {
623        // 0x0A (\n) in PCM must NOT break framing (the whole point of length-prefix).
624        let samples = vec![0x0A0Ai16, 0x000A, -1];
625        let mut buf = Vec::new();
626        write_frame(&mut buf, FRAME_AUDIO, &pcm_to_bytes(&samples)).unwrap();
627        let (_k, p) = read_frame(&mut &buf[..]).unwrap().unwrap();
628        assert_eq!(bytes_to_pcm(&p), samples);
629    }
630
631    #[test]
632    fn rx_audio_started_disambiguates_from_event_and_reply() {
633        let started = serde_json::to_string(&FromWorker::RxAudioStarted(RxAudioStarted {
634            rx_audio_rate: 8000,
635        }))
636        .unwrap();
637        assert!(matches!(
638            serde_json::from_str::<FromWorker>(&started).unwrap(),
639            FromWorker::RxAudioStarted(RxAudioStarted {
640                rx_audio_rate: 8000
641            })
642        ));
643        // Neither an event nor a reply carries the `rx_audio_rate` key.
644        let ev = serde_json::to_string(&FromWorker::Event(WireEvent::RegisterOk {
645            account: "a".into(),
646        }))
647        .unwrap();
648        let rep = serde_json::to_string(&FromWorker::Reply(Reply {
649            reply: 1,
650            result: ReplyResult::CallCount(0),
651        }))
652        .unwrap();
653        assert!(matches!(
654            serde_json::from_str::<FromWorker>(&ev).unwrap(),
655            FromWorker::Event(_)
656        ));
657        assert!(matches!(
658            serde_json::from_str::<FromWorker>(&rep).unwrap(),
659            FromWorker::Reply(_)
660        ));
661    }
662
663    #[test]
664    fn read_frame_distinguishes_clean_eof_from_torn_header() {
665        // Nothing buffered → clean frame-boundary EOF.
666        assert!(read_frame(&mut &b""[..]).unwrap().is_none());
667        // A partial header (2 of 5 bytes) is a torn frame, not a clean close.
668        let err = read_frame(&mut &[FRAME_CONTROL, 0x01][..]).unwrap_err();
669        assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
670    }
671
672    #[test]
673    fn read_frame_rejects_oversized_length() {
674        // Header claiming a payload above MAX_FRAME_LEN must be rejected, not allocated.
675        let mut buf = vec![FRAME_AUDIO];
676        buf.extend_from_slice(&(MAX_FRAME_LEN as u32 + 1).to_le_bytes());
677        let err = read_frame(&mut &buf[..]).unwrap_err();
678        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
679    }
680
681    #[test]
682    fn read_frame_errors_on_truncated_payload() {
683        // Full header but a short payload (EOF mid-payload) is a torn frame.
684        let mut buf = vec![FRAME_AUDIO];
685        buf.extend_from_slice(&4u32.to_le_bytes()); // claims 4 bytes
686        buf.extend_from_slice(&[1, 2]); // only 2 follow
687        let err = read_frame(&mut &buf[..]).unwrap_err();
688        assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
689    }
690
691    #[test]
692    fn audio_commands_disambiguate_as_to_worker_cmd() {
693        // The audio control commands must parse as Cmd, not Query (untagged split).
694        for cmd in [Command::StartRxAudio, Command::StartTxAudio { rate: 8000 }] {
695            let line = serde_json::to_string(&ToWorker::Cmd(cmd)).unwrap();
696            assert!(
697                matches!(
698                    serde_json::from_str::<ToWorker>(&line).unwrap(),
699                    ToWorker::Cmd(_)
700                ),
701                "expected Cmd for {line}"
702            );
703        }
704    }
705}