Cotton code
554 lines · 34.7 KB · RustRaw
use super::*;use crate::calling::wire::{ClientFrame, Joined, MediaState, Mode, RoomFrame, RoomState, SfuOp, Started, Track};const ROOM: &str = "0123456789abcdef0123456789abcdef";const NUMBER: &str = "+919000000201";const T0: i64 = 1_762_934_400_000;fn started() -> Started {    Started { room: ROOM.into(), credential: format!("ccr_{ROOM}_secret"), ice_servers: vec![], ttl: 3600, ring_for: 45, mode: Mode::P2p, me: None, group: None }}fn joined() -> Joined {    Joined { room: ROOM.into(), from: NUMBER.into(), video: false, credential: format!("ccr_{ROOM}_callee"), ice_servers: vec![], ttl: 3600, mode: Mode::P2p, me: Some("callee:d1".into()), group: None }}fn run(call: &Call, events: impl IntoIterator<Item = (Event, i64)>) -> (Call, Vec<Effect>) {    let mut call = call.clone();    let mut all = Vec::new();    for (event, at) in events {        let (next, effects) = step(&call, event, at);        call = next;        all.extend(effects);    }    (call, all)}fn dial(video: bool) -> Event {    Event::Dial { uuid: "11111111-2222-4333-8444-555555555555".into(), callees: vec![Callee { number: NUMBER.into(), person: Some("p-1".into()), name: Some("An Invented Friend".into()) }], video, group: None }}fn frame(json: serde_json::Value) -> Event {    Event::Frame(serde_json::from_value(json).expect("a room frame"))}fn ringing_out() -> Call {    run(&Call::idle(), [(dial(false), T0), (Event::Started(started()), T0 + 300)]).0}fn live_out() -> Call {    run(&ringing_out(), [(frame(serde_json::json!({"t": "state", "state": "connecting"})), T0 + 5_000), (Event::Media(MediaState::Connected), T0 + 6_000)]).0}fn ringing_in() -> Call {    run(&Call::idle(), [(Event::Incoming { room: ROOM.into(), video: false }, T0)]).0}fn sends(effects: &[Effect]) -> Vec<ClientFrame> {    effects.iter().filter_map(|e| if let Effect::Send { frame } = e { Some(frame.clone()) } else { None }).collect()}fn ended_with(effects: &[Effect]) -> Option<SystemEnd> {    effects.iter().find_map(|e| if let Effect::SystemCallEnded { cause, .. } = e { Some(*cause) } else { None })}// RULE: a dial reports the outgoing call to CallKit, asks the object to start it, readies the audio (and the camera for video) and waits at most START_MS.#[test]fn a_dial_reports_asks_and_readies() {    let (call, effects) = step(&Call::idle(), dial(true), T0);    assert_eq!(call.phase, Phase::Dialling);    assert_eq!(call.direction, Direction::Out);    assert!(matches!(&effects[0], Effect::SystemCallOutgoing { handle, video: true, .. } if handle == NUMBER));    assert_eq!(effects[1], Effect::AskStart { to: vec![NUMBER.into()], video: true, group: None });    assert!(effects.contains(&Effect::StartCamera));    assert_eq!(effects.last(), Some(&Effect::Timer { after_ms: START_MS }));    let (again, none) = step(&call, dial(false), T0 + 1);    assert!(none.is_empty() && again == call, "one call at a time");}// RULE: once the room is made the caller opens its socket with the room credential, makes the offer at once, plays ringback and rings out.#[test]fn the_room_made_rings_out() {    let call = ringing_out();    assert_eq!(call.phase, Phase::RingingOut);    let (_, effects) = run(&Call::idle(), [(dial(false), T0), (Event::Started(started()), T0 + 300)]);    assert!(effects.contains(&Effect::OpenSocket { path: "/v1/calls/socket".into(), credential: format!("ccr_{ROOM}_secret"), after_ms: 0 }));    assert!(effects.contains(&Effect::CreatePeer { offerer: true, ice_servers: vec![] }));    assert!(effects.contains(&Effect::PlayTone { tone: Tone::Ringback }));    assert!(serde_json::to_value(&call).unwrap().get("credential").is_none(), "the credential is never answered as state");}// RULE: the shell's own offer and candidates go to the room as frames; a remote answer and candidate come back as effects.#[test]fn signals_pass_both_ways() {    let call = ringing_out();    let offer = ClientFrame::Signal { kind: SignalKind::Offer, sdp: Some("v=0".into()), candidate: None, mid: None, mline: None };    let (_, effects) = step(&call, Event::Out(offer.clone()), T0 + 400);    assert_eq!(effects, vec![Effect::Send { frame: offer }]);    let (_, effects) = step(&call, frame(serde_json::json!({"t": "signal", "from": "callee:d1", "kind": "answer", "sdp": "v=1"})), T0 + 500);    assert_eq!(effects, vec![Effect::ApplyRemote { kind: SignalKind::Answer, sdp: "v=1".into() }]);    let (_, effects) = step(&call, frame(serde_json::json!({"t": "signal", "from": "callee:d1", "kind": "ice", "candidate": "candidate:9", "mid": "0", "mline": 0})), T0 + 500);    assert_eq!(effects, vec![Effect::AddCandidate { candidate: "candidate:9".into(), mid: Some("0".into()), mline: Some(0) }]);}// RULE: answered: connecting stops the ringback and reports connecting; the media connecting makes the call live, once, and reports it connected.#[test]fn answered_goes_connecting_then_live() {    let (call, effects) = step(&ringing_out(), frame(serde_json::json!({"t": "state", "state": "connecting"})), T0 + 5_000);    assert_eq!(call.phase, Phase::Connecting);    assert!(effects.contains(&Effect::StopTone) && effects.iter().any(|e| matches!(e, Effect::SystemCallConnecting { .. })));    let (call, effects) = step(&call, Event::Media(MediaState::Connected), T0 + 6_000);    assert_eq!(call.phase, Phase::Live);    assert_eq!(call.live_at, Some(T0 + 6_000));    assert_eq!(sends(&effects), vec![ClientFrame::Media { state: MediaState::Connected }]);    assert!(effects.iter().any(|e| matches!(e, Effect::SystemCallConnected { .. })));    let (still, effects) = step(&call, frame(serde_json::json!({"t": "state", "state": "live"})), T0 + 6_100);    assert_eq!(still.live_at, Some(T0 + 6_000));    assert!(effects.is_empty(), "live once: {effects:?}");}// RULE: hanging up a live call sends end, tears down, asks CallKit's end action and writes the history.#[test]fn hanging_up_a_live_call() {    let (call, effects) = step(&live_out(), Event::HangUp, T0 + 66_000);    assert_eq!((call.phase, call.reason), (Phase::Ended, Some(EndReason::HungUp)));    assert_eq!(sends(&effects), vec![ClientFrame::End]);    assert_eq!(ended_with(&effects), Some(SystemEnd::Local), "this person ended it");    for teardown in [Effect::ClosePeer, Effect::StopAudio, Effect::CloseSocket, Effect::WriteHistory] {        assert!(effects.contains(&teardown), "{teardown:?}");    }    let send = effects.iter().position(|e| matches!(e, Effect::Send { .. })).unwrap();    let close = effects.iter().position(|e| *e == Effect::CloseSocket).unwrap();    assert!(send < close, "end goes before the socket closes");    assert_eq!(call.duration_s(T0 + 99_000), 60);}// RULE: every end the room says is the call's end, mapped to CallKit's reason from this side.#[test]fn the_rooms_end_maps_to_callkit() {    let cases = [        ("declined", SystemEnd::RemoteDeclined),        ("busy", SystemEnd::Busy),        ("no_answer", SystemEnd::Unanswered),        ("failed", SystemEnd::Failed),    ];    for (reason, cause) in cases {        let (call, effects) = step(&ringing_out(), frame(serde_json::json!({"t": "ended", "reason": reason})), T0 + 45_000);        assert_eq!(call.reason.map(EndReason::as_str), Some(reason));        assert_eq!(ended_with(&effects), Some(cause), "{reason}");        assert!(sends(&effects).is_empty(), "the room already knows");    }    let (_, effects) = step(&live_out(), frame(serde_json::json!({"t": "ended", "reason": "remote_hung_up"})), T0 + 70_000);    assert_eq!(ended_with(&effects), Some(SystemEnd::Remote));}// RULE: the caller cancelling while it rings sends end and ends `cancelled`; while the room is still being made, the room is ended once it arrives.#[test]fn the_caller_cancels() {    let (call, effects) = step(&ringing_out(), Event::HangUp, T0 + 3_000);    assert_eq!(call.reason, Some(EndReason::Cancelled));    assert_eq!(sends(&effects), vec![ClientFrame::End]);    assert!(effects.contains(&Effect::StopTone));    let dialling = step(&Call::idle(), dial(false), T0).0;    let (cancelled, effects) = step(&dialling, Event::HangUp, T0 + 100);    assert_eq!(cancelled.reason, Some(EndReason::Cancelled));    assert!(!effects.contains(&Effect::WriteHistory), "no room yet");    let (late, effects) = step(&cancelled, Event::Started(started()), T0 + 300);    assert_eq!(effects, vec![Effect::AskEnd { room: ROOM.into() }, Effect::WriteHistory]);    assert_eq!(late.room.as_deref(), Some(ROOM));}// RULE: a start the object refuses ends the call: too_many_calls by name, anything else as the network.#[test]fn a_refused_start_ends() {    let dialling = step(&Call::idle(), dial(false), T0).0;    assert_eq!(step(&dialling, Event::StartFailed { code: "too_many_calls".into() }, T0 + 1).0.reason, Some(EndReason::TooManyCalls));    assert_eq!(step(&dialling, Event::StartFailed { code: "offline".into() }, T0 + 1).0.reason, Some(EndReason::UnreachableNetwork));    assert_eq!(step(&dialling, Event::Tick, T0 + START_MS).0.reason, Some(EndReason::UnreachableNetwork));}// RULE: a ring reports "Cotton" to CallKit at once (no number reaches Apple), asks the join, and names the caller once the object answers.#[test]fn a_ring_reports_then_joins() {    let (call, effects) = step(&Call::idle(), Event::Incoming { room: ROOM.into(), video: true }, T0);    assert_eq!(call.phase, Phase::RingingIn);    assert_eq!(call.uuid, "01234567-89AB-CDEF-0123-456789ABCDEF");    assert_eq!(effects[0], Effect::SystemCallIncoming { uuid: call.uuid.clone(), title: "Cotton".into(), video: true });    assert_eq!(effects[1], Effect::AskJoin { room: ROOM.into() });    let (call, effects) = step(&call, Event::Joined { answer: joined(), person: Some("p-2".into()), name: Some("A Caller".into()) }, T0 + 400);    assert_eq!(call.number.as_deref(), Some(NUMBER));    assert!(matches!(&effects[0], Effect::SystemCallUpdate { handle, name: Some(name), .. } if handle == NUMBER && name == "A Caller"));    assert!(matches!(&effects[1], Effect::OpenSocket { credential, .. } if credential.ends_with("_callee")));    let (_, effects) = step(&call, Event::Incoming { room: ROOM.into(), video: true }, T0 + 500);    assert_eq!(effects.len(), 1, "the same push again is reported again, nothing more");}// RULE: accepting sends accept, makes the answering peer and readies audio; accepting before the join answered waits for it.#[test]fn accepting_before_and_after_the_join() {    let joined_call = step(&ringing_in(), Event::Joined { answer: joined(), person: None, name: None }, T0 + 200).0;    let (call, effects) = step(&joined_call, Event::Accept, T0 + 1_000);    assert_eq!(call.phase, Phase::Connecting);    assert_eq!(sends(&effects), vec![ClientFrame::Accept]);    assert!(effects.contains(&Effect::CreatePeer { offerer: false, ice_servers: vec![] }));    let (early, effects) = step(&ringing_in(), Event::Accept, T0 + 100);    assert!(early.accepted && early.phase == Phase::RingingIn && effects.is_empty());    let (call, effects) = step(&early, Event::Joined { answer: joined(), person: None, name: None }, T0 + 200);    assert_eq!(call.phase, Phase::Connecting);    assert_eq!(sends(&effects), vec![ClientFrame::Accept]);    let (call, effects) = step(&call, frame(serde_json::json!({"t": "signal", "from": "caller", "kind": "offer", "sdp": "v=0"})), T0 + 300);    assert_eq!(effects, vec![Effect::ApplyRemote { kind: SignalKind::Offer, sdp: "v=0".into() }]);    assert_eq!(step(&call, Event::Media(MediaState::Connected), T0 + 900).0.phase, Phase::Live);}// RULE: declining or busy before the join goes over HTTP, after it on the socket; either is this person's end, with no peer to close.#[test]fn declining_and_busy() {    let (call, effects) = step(&ringing_in(), Event::Decline, T0 + 100);    assert_eq!(call.reason, Some(EndReason::Declined));    assert_eq!(effects[0], Effect::AskDecline { room: ROOM.into(), busy: false });    assert_eq!(ended_with(&effects), Some(SystemEnd::Rejected));    assert!(!effects.contains(&Effect::ClosePeer));    let joined_call = step(&ringing_in(), Event::Joined { answer: joined(), person: None, name: None }, T0 + 200).0;    let (call, effects) = step(&joined_call, Event::Busy, T0 + 300);    assert_eq!(call.reason, Some(EndReason::Busy));    assert_eq!(sends(&effects), vec![ClientFrame::Busy]);    assert_eq!(step(&ringing_in(), Event::HangUp, T0 + 1).0.reason, Some(EndReason::Declined), "hanging up a ring declines it");}// RULE: the ring ending elsewhere ends it here by the push or the room's frame, and only a ring nobody else took writes history here.#[test]fn the_ring_ends_elsewhere() {    let (call, effects) = step(&ringing_in(), Event::Stop { reason: EndReason::AnsweredElsewhere }, T0 + 4_000);    assert_eq!(call.reason, Some(EndReason::AnsweredElsewhere));    assert_eq!(ended_with(&effects), Some(SystemEnd::AnsweredElsewhere));    assert!(!effects.contains(&Effect::WriteHistory), "the device that answered writes it");    let joined_call = step(&ringing_in(), Event::Joined { answer: joined(), person: None, name: None }, T0 + 200).0;    let (_, effects) = step(&joined_call, frame(serde_json::json!({"t": "ended", "reason": "declined_elsewhere"})), T0 + 300);    assert_eq!(ended_with(&effects), Some(SystemEnd::DeclinedElsewhere));    let (_, effects) = step(&joined_call, frame(serde_json::json!({"t": "ended", "reason": "cancelled"})), T0 + 300);    assert_eq!(ended_with(&effects), Some(SystemEnd::Cancelled));    assert!(effects.contains(&Effect::WriteHistory), "a missed call is this device's to write");    let (missed, _) = step(&ringing_in(), Event::JoinFailed { code: "not_ringing".into() }, T0 + 200);    assert_eq!(missed.reason, Some(EndReason::Missed));}// RULE: a ring of another room during a call is reported, answered busy and ended; a stop push for no call here is reported and ended.#[test]fn rings_with_no_place_here() {    let other = "fedcba9876543210fedcba9876543210";    let effects = ring_while_busy(other);    assert!(matches!(&effects[0], Effect::SystemCallIncoming { .. }));    assert_eq!(effects[1], Effect::AskDecline { room: other.into(), busy: true });    assert!(matches!(&effects[2], Effect::SystemCallEnded { cause: SystemEnd::Missed, ios: Some(3), android: 5, .. }));    let stray = stray_stop(other, EndReason::AnsweredElsewhere);    assert!(matches!(&stray[1], Effect::SystemCallEnded { cause: SystemEnd::AnsweredElsewhere, ios: Some(4), android: 11, .. }));    let (_, effects) = step(&live_out(), Event::Incoming { room: other.into(), video: false }, T0 + 70_000);    assert!(effects.is_empty(), "the machine leaves another room's ring to ring_while_busy");}// RULE: the media dropping makes a live call reconnecting (the caller restarts ICE); back in time it is live again, else it ends lost.#[test]fn reconnecting_and_lost() {    let (call, effects) = step(&live_out(), Event::Media(MediaState::Disconnected), T0 + 20_000);    assert_eq!(call.phase, Phase::Reconnecting);    assert!(effects.contains(&Effect::RestartIce));    assert_eq!(sends(&effects), vec![ClientFrame::Media { state: MediaState::Disconnected }]);    let (back, _) = step(&call, Event::Media(MediaState::Connected), T0 + 25_000);    assert_eq!((back.phase, back.live_at), (Phase::Live, Some(T0 + 6_000)), "the call keeps its first live moment");    let (lost, effects) = step(&call, Event::Tick, T0 + 20_000 + RECONNECT_MS);    assert_eq!(lost.reason, Some(EndReason::Lost));    assert_eq!(sends(&effects), vec![ClientFrame::End]);    assert_eq!(ended_with(&effects), Some(SystemEnd::Failed));}// RULE: a socket that closes under a call is opened again with the same credential after REOPEN_MS; a live call is reconnecting meanwhile.#[test]fn a_closed_socket_reopens() {    let (call, effects) = step(&live_out(), Event::SocketClosed, T0 + 30_000);    assert_eq!(call.phase, Phase::Reconnecting);    assert!(effects.contains(&Effect::OpenSocket { path: "/v1/calls/socket".into(), credential: format!("ccr_{ROOM}_secret"), after_ms: REOPEN_MS }));    let ended = step(&live_out(), Event::HangUp, T0 + 30_000).0;    assert!(step(&ended, Event::SocketClosed, T0 + 30_001).1.is_empty(), "an ended call reopens nothing");}// RULE: the timers end what nobody ended: ringing out → no_answer (and tells the room), ringing in → missed, connecting → failed; early ticks change nothing.#[test]fn timers_end_what_nobody_ended() {    assert_eq!(step(&ringing_out(), Event::Tick, T0 + 300 + RING_OUT_MS - 1).0.phase, Phase::RingingOut);    let (call, effects) = step(&ringing_out(), Event::Tick, T0 + 300 + RING_OUT_MS);    assert_eq!(call.reason, Some(EndReason::NoAnswer));    assert_eq!(sends(&effects), vec![ClientFrame::End]);    assert_eq!(step(&ringing_in(), Event::Tick, T0 + RING_IN_MS).0.reason, Some(EndReason::Missed));    let connecting = step(&ringing_out(), frame(serde_json::json!({"t": "state", "state": "connecting"})), T0 + 5_000).0;    assert_eq!(step(&connecting, Event::Tick, T0 + 5_000 + CONNECT_MS).0.reason, Some(EndReason::Failed));    let (failed, effects) = step(&connecting, Event::Media(MediaState::Failed), T0 + 6_000);    assert_eq!(failed.reason, Some(EndReason::Failed));    assert_eq!(sends(&effects), vec![ClientFrame::Media { state: MediaState::Failed }]);}// RULE: every end has its system word from each side, and each word its CallKit reason and Android DisconnectCause; an ended call takes no frame.#[test]fn system_words_and_ended_calls() {    assert_eq!(system_end(EndReason::Cancelled, Direction::Out), SystemEnd::Local);    assert_eq!(system_end(EndReason::Cancelled, Direction::In), SystemEnd::Cancelled);    assert_eq!(system_end(EndReason::Declined, Direction::In), SystemEnd::Rejected);    assert_eq!(system_end(EndReason::Missed, Direction::In), SystemEnd::Missed);    let table = [        (SystemEnd::Local, None, 2),        (SystemEnd::Rejected, None, 6),        (SystemEnd::Remote, Some(2), 3),        (SystemEnd::RemoteDeclined, Some(2), 3),        (SystemEnd::Busy, Some(2), 7),        (SystemEnd::Cancelled, Some(2), 5),        (SystemEnd::Missed, Some(3), 5),        (SystemEnd::Unanswered, Some(3), 3),        (SystemEnd::AnsweredElsewhere, Some(4), 11),        (SystemEnd::DeclinedElsewhere, Some(5), 6),        (SystemEnd::Failed, Some(1), 1),    ];    for (cause, ios, android) in table {        assert_eq!((cause.ios(), cause.android()), (ios, android), "{cause:?}");    }    let ended = step(&live_out(), Event::HangUp, T0 + 70_000).0;    assert!(step(&ended, frame(serde_json::json!({"t": "ended", "reason": "remote_hung_up"})), T0 + 70_001).1.is_empty());    assert!(step(&ended, Event::Out(ClientFrame::Ping), T0 + 70_001).1.is_empty());}// RULE: effects serialise as the shell reads them: `do` names the effect, fields camelCase-free snake as declared.#[test]fn effects_serialise_for_the_shell() {    let effect = Effect::SystemCallEnded { uuid: "U".into(), cause: SystemEnd::AnsweredElsewhere, ios: Some(4), android: 11 };    assert_eq!(serde_json::to_value(&effect).unwrap(), serde_json::json!({"do": "system_call_ended", "uuid": "U", "cause": "answered_elsewhere", "ios": 4, "android": 11}));    let send = Effect::Send { frame: ClientFrame::Accept };    assert_eq!(serde_json::to_value(&send).unwrap(), serde_json::json!({"do": "send", "frame": {"t": "accept"}}));}const SECOND: &str = "+919000000203";fn group_dial() -> Event {    Event::Dial {        uuid: "11111111-2222-4333-8444-666666666666".into(),        callees: vec![            Callee { number: NUMBER.into(), person: Some("p-1".into()), name: Some("An Invented Friend".into()) },            Callee { number: SECOND.into(), person: None, name: None },        ],        video: true,        group: None,    }}fn group_ringing() -> Call {    run(&Call::idle(), [(group_dial(), T0), (Event::Started(Started { mode: Mode::Sfu, ..started() }), T0 + 300)]).0}fn member(id: &str, number: &str, state: &str) -> serde_json::Value {    serde_json::json!({"id": id, "number": number, "state": state, "audio": true, "video": true, "speaking": false})}// RULE: a call to several people goes through the SFU from the start: one ask to all, each shown invited, the SFU connection made and the tracks pushed — no peer-to-peer offer.#[test]fn a_group_call_starts_on_the_sfu() {    let (call, effects) = run(&Call::idle(), [(group_dial(), T0), (Event::Started(Started { mode: Mode::Sfu, ..started() }), T0 + 300)]);    assert_eq!(call.mode, Mode::Sfu);    assert!(effects.contains(&Effect::AskStart { to: vec![NUMBER.into(), SECOND.into()], video: true, group: None }));    assert!(matches!(&effects[0], Effect::SystemCallOutgoing { name: None, .. }), "a group is not one person's call");    assert_eq!(call.members.iter().map(|m| (m.number.clone().unwrap(), m.state)).collect::<Vec<_>>(), vec![(NUMBER.to_string(), MemberState::Invited), (SECOND.to_string(), MemberState::Invited)]);    assert!(effects.contains(&Effect::SwitchToSfu { ice_servers: vec![] }));    assert!(effects.contains(&Effect::PushTracks { audio: true, video: true }));    assert!(!effects.iter().any(|e| matches!(e, Effect::CreatePeer { .. })));    let (alone, none) = step(&Call::idle(), Event::Dial { uuid: "u".into(), callees: (0..9).map(|n| Callee { number: format!("+9190000004{n:02}"), person: None, name: None }).collect(), video: false, group: None }, T0);    assert!(none.is_empty() && alone.phase == Phase::Idle, "nine invitees is too many");}// RULE: the roster, a member's change, their tracks, their speaking and the SFU's SDP each come to the shell; a member who leaves takes their tracks; hanging up a group call leaves it.#[test]fn a_group_calls_room_frames() {    let call = group_ringing();    let (call, effects) = step(&call, frame(serde_json::json!({"t": "roster", "members": [member("caller", "+919000000200", "joined"), member("m-1", NUMBER, "joined"), member("m-2", SECOND, "invited")]})), T0 + 400);    assert_eq!(call.members.len(), 3, "the invited rows became the room's members: {:?}", call.members);    assert_eq!(call.members.iter().find(|m| m.id == "m-1").unwrap().name.as_deref(), Some("An Invented Friend"), "who this copy knows them as stays");    assert!(matches!(&effects[..], [Effect::ShowRoster { .. }]));    let (call, effects) = step(&call, frame(serde_json::json!({"t": "state", "state": "live"})), T0 + 500);    assert_eq!(call.phase, Phase::Live);    assert!(effects.iter().any(|e| matches!(e, Effect::SystemCallConnected { outgoing: true, .. })));    let (call, effects) = step(&call, frame(serde_json::json!({"t": "tracks", "member": "m-1", "tracks": [{"name": "a"}, {"name": "v"}]})), T0 + 600);    assert_eq!(effects[0], Effect::Send { frame: ClientFrame::Sfu { op: SfuOp::Pull, sdp: None, tracks: Some(vec![Track { mid: None, member: Some("m-1".into()), name: "a".into(), kind: None }, Track { mid: None, member: Some("m-1".into()), name: "v".into(), kind: None }]), mids: None } });    assert_eq!(effects[1], Effect::PullTracks { member: "m-1".into(), names: vec!["a".into(), "v".into()] });    let (_, effects) = step(&call, frame(serde_json::json!({"t": "sfu", "op": "offer", "sdp": "v=9"})), T0 + 700);    assert_eq!(effects, vec![Effect::ApplyRemoteSdp { op: SfuOp::Offer, sdp: "v=9".into(), tracks: vec![] }]);    let (call, effects) = step(&call, frame(serde_json::json!({"t": "speaking", "member": "m-1", "on": true})), T0 + 800);    assert!(call.members.iter().find(|m| m.id == "m-1").unwrap().speaking);    assert_eq!(effects.len(), 1);    assert!(step(&call, frame(serde_json::json!({"t": "speaking", "member": "m-1", "on": true})), T0 + 900).1.is_empty(), "no change, nothing drawn");    let (call, effects) = step(&call, frame(serde_json::json!({"t": "member", "member": member("m-1", NUMBER, "left")})), T0 + 1_000);    assert_eq!(effects[0], Effect::CloseTracks { member: "m-1".into() });    assert!(step(&call, frame(serde_json::json!({"t": "e2ee", "from": "m-2", "epoch": 1, "data": "opaque"})), T0 + 1_001).1.is_empty(), "frame encryption is not built: relayed, never read");    let (left, effects) = step(&call, Event::Leave, T0 + 2_000);    assert_eq!(left.reason, Some(EndReason::HungUp));    assert_eq!(sends(&effects), vec![ClientFrame::Leave]);    let history = crate::calling::history::history_row(&left, "ns").unwrap();    assert_eq!(history.person_id, None);    assert_eq!(history.who.as_deref(), Some(&*format!("{NUMBER}, {SECOND}")), "everyone but this device");}// RULE: a call of two that gains a third moves to the SFU once: the peer connection closed, the SFU connection made, the tracks pushed; a mode frame again moves nothing.#[test]fn two_become_a_group() {    let (call, effects) = step(&live_out(), frame(serde_json::json!({"t": "mode", "mode": "sfu"})), T0 + 10_000);    assert_eq!(call.mode, Mode::Sfu);    assert_eq!(effects, vec![Effect::ClosePeer, Effect::SwitchToSfu { ice_servers: vec![] }, Effect::PushTracks { audio: true, video: false }]);    assert!(step(&call, frame(serde_json::json!({"t": "mode", "mode": "sfu"})), T0 + 10_001).1.is_empty());    assert!(step(&call, frame(serde_json::json!({"t": "mode", "mode": "p2p"})), T0 + 10_002).1.is_empty(), "never back");    let rung = step(&ringing_in(), frame(serde_json::json!({"t": "mode", "mode": "sfu"})), T0 + 1);    assert!(rung.1.is_empty(), "a ring not taken has no socket to move");}// RULE: inviting during a call asks the object and shows the invitee; someone already joined is not invited again; nobody is invited before the room exists.#[test]fn inviting_more_people() {    let invite = Event::Invite { callees: vec![Callee { number: SECOND.into(), person: None, name: Some("A Third".into()) }] };    let (call, effects) = step(&live_out(), invite.clone(), T0 + 20_000);    assert_eq!(effects[0], Effect::AskInvite { room: ROOM.into(), to: vec![SECOND.into()] });    assert!(call.members.iter().any(|m| m.number.as_deref() == Some(SECOND) && m.state == MemberState::Invited));    let dialling = step(&Call::idle(), dial(false), T0).0;    assert!(step(&dialling, invite, T0 + 1).1.is_empty());}// RULE: muting sets what the device sends and tells the room; a camera turns on only in a video call; speaking is sent on a change, while live.#[test]fn muting_and_speaking() {    let (call, effects) = step(&live_out(), Event::Mute { audio: false, video: true }, T0 + 20_000);    assert_eq!((call.own.audio, call.own.video), (false, false), "an audio call has no camera to turn on");    assert_eq!(effects, vec![Effect::SetSending { audio: false, video: false }, Effect::Send { frame: ClientFrame::Mute { audio: false, video: false } }]);    let (call, effects) = step(&call, Event::Speaking { on: true }, T0 + 20_100);    assert_eq!(sends(&effects), vec![ClientFrame::Speaking { on: true }]);    assert!(step(&call, Event::Speaking { on: true }, T0 + 20_200).1.is_empty());    assert!(step(&ringing_out(), Event::Speaking { on: true }, T0 + 1).1.is_empty(), "not before the call is live");}// RULE: a ring of a group room is taken on the SFU: accepting makes the SFU connection and pushes the tracks.#[test]fn a_ring_of_a_group_is_taken_on_the_sfu() {    let answer = Joined { mode: Mode::Sfu, ..joined() };    let joined_call = step(&ringing_in(), Event::Joined { answer, person: None, name: None }, T0 + 200).0;    assert_eq!(joined_call.mode, Mode::Sfu);    // A group's ring, named by its group as it rang, keeps that name once joined; a one-to-one ring takes its caller's.    let named = Call { name: Some("Invented Family".into()), ..ringing_in() };    let answer = Joined { mode: Mode::Sfu, group: Some(GROUP.into()), ..joined() };    let kept = step(&named, Event::Joined { answer, person: None, name: Some("An Invented Friend".into()) }, T0 + 200).0;    assert_eq!(kept.name.as_deref(), Some("Invented Family"));    let one = step(&named, Event::Joined { answer: joined(), person: None, name: Some("An Invented Friend".into()) }, T0 + 200).0;    assert_eq!(one.name.as_deref(), Some("An Invented Friend"));    let (_, effects) = step(&joined_call, Event::Accept, T0 + 300);    assert_eq!(sends(&effects), vec![ClientFrame::Accept]);    assert!(effects.contains(&Effect::SwitchToSfu { ice_servers: vec![] }));    assert!(effects.contains(&Effect::PushTracks { audio: true, video: false }));}// RULE: a video call's caller is asked for its camera again once its peer is made, after CreatePeer: asked only at the dial, Android's camera had no video source to feed and the caller sent no video (21 Nov 2026); a voice call is not.#[test]fn a_video_callers_camera_starts_once_its_peer_stands() {    let (_, effects) = run(&Call::idle(), [(dial(true), T0), (Event::Started(started()), T0 + 300)]);    let peer = effects.iter().position(|e| matches!(e, Effect::CreatePeer { offerer: true, .. })).expect("the peer");    let camera = effects.iter().rposition(|e| *e == Effect::StartCamera).expect("the camera");    assert!(camera > peer, "{effects:?}");    let (_, voice) = run(&Call::idle(), [(dial(false), T0), (Event::Started(started()), T0 + 300)]);    assert!(!voice.contains(&Effect::StartCamera));}// ── a group's call (23 Nov 2026) ─────────────────────const GROUP: &str = "0123456789abcdef0123456789abcdef";#[test]fn a_groups_call_is_the_sfus_even_with_one_other_member_and_asks_with_the_group() {    let dial = Event::Dial { uuid: "u-g".into(), callees: vec![Callee { number: NUMBER.into(), person: None, name: Some("An Invented Friend".into()) }], video: false, group: Some(GROUP.into()) };    let (call, effects) = step(&Call::idle(), dial, T0);    assert_eq!(call.mode, Mode::Sfu);    assert_eq!(call.group.as_deref(), Some(GROUP));    assert!(effects.contains(&Effect::AskStart { to: vec![NUMBER.into()], video: false, group: Some(GROUP.into()) }));    // The system's call UI is not told a single person's name for a group's call.    assert!(matches!(&effects[0], Effect::SystemCallOutgoing { name: None, .. }));    let (call, effects) = step(&call, Event::Started(Started { mode: Mode::Sfu, group: Some(GROUP.into()), ..started() }), T0 + 300);    assert_eq!(call.phase, Phase::RingingOut);    assert!(effects.iter().any(|e| matches!(e, Effect::SwitchToSfu { .. })));    assert!(effects.iter().any(|e| matches!(e, Effect::PushTracks { audio: true, video: false })));}fn entered() -> Joined {    Joined { room: ROOM.into(), from: NUMBER.into(), video: true, credential: format!("ccr_{ROOM}_late"), ice_servers: vec![], ttl: 3600, mode: Mode::Sfu, me: Some("m2".into()), group: Some(GROUP.into()) }}#[test]fn coming_in_late_asks_enter_and_takes_the_call_as_soon_as_the_room_lets_it_in() {    let (call, effects) = step(&Call::idle(), Event::Enter { room: ROOM.into(), video: true, group: Some(GROUP.into()), name: Some("Invented Family".into()) }, T0);    assert_eq!(call.phase, Phase::Dialling);    assert!(call.entered && call.accepted);    assert_eq!(effects[0], Effect::SystemCallOutgoing { uuid: uuid_of_entry(ROOM, T0), handle: String::new(), name: Some("Invented Family".into()), video: true });    assert_eq!(effects[1], Effect::AskEnter { room: ROOM.into() });    let (call, effects) = step(&call, Event::Joined { answer: entered(), person: None, name: Some("The Caller".into()) }, T0 + 200);    assert_eq!(call.phase, Phase::Connecting);    assert_eq!(call.name.as_deref(), Some("Invented Family"), "the group's name stands, not the caller's");    assert_eq!(call.me.as_deref(), Some("m2"));    assert!(effects.iter().any(|e| matches!(e, Effect::OpenSocket { .. })));    assert!(effects.contains(&Effect::Send { frame: ClientFrame::Accept }));    assert!(effects.iter().any(|e| matches!(e, Effect::SwitchToSfu { .. })));    assert!(!effects.iter().any(|e| matches!(e, Effect::SystemCallIncoming { .. })), "coming in never rings");    let (call, _) = step(&call, Event::Media(MediaState::Connected), T0 + 900);    assert_eq!(call.phase, Phase::Live);}// RULE: each time this phone comes into a call it is a new call to the system's call UI, never the room's ring id: iPhone's// CallKit drops a call under an id it has already ended (the ring missed here, or this phone's last time in), as seen// walking a group call on dev (launch-ios, 23 Nov 2026: every rejoin hung up a second after the SFU answered).#[test]fn each_time_in_is_its_own_call_to_the_system() {    let enter = Event::Enter { room: ROOM.into(), video: false, group: Some(GROUP.into()), name: None };    let uuid = |effects: &[Effect]| effects.iter().find_map(|e| if let Effect::SystemCallOutgoing { uuid, .. } = e { Some(uuid.clone()) } else { None }).unwrap();    let (first, effects) = step(&Call::idle(), enter.clone(), T0);    let once = uuid(&effects);    let (left, _) = step(&first, Event::HangUp, T0 + 100);    let (_, effects) = step(&left, enter, T0 + 60_000);    let again = uuid(&effects);    assert_ne!(once, again, "back in: a new id");    assert_ne!(once, uuid_of_room(ROOM), "never the ring's");    assert_eq!(once.len(), 36);}#[test]fn a_late_entry_refused_or_given_up_leaves_no_history() {    let enter = Event::Enter { room: ROOM.into(), video: false, group: Some(GROUP.into()), name: None };    let (call, _) = step(&Call::idle(), enter.clone(), T0);    let (refused, effects) = step(&call, Event::JoinFailed { code: "no_call".into() }, T0 + 200);    assert_eq!(refused.phase, Phase::Ended);    assert!(!effects.contains(&Effect::WriteHistory));    let (given_up, effects) = step(&call, Event::HangUp, T0 + 100);    assert_eq!(given_up.phase, Phase::Ended);    assert!(effects.contains(&Effect::AskDecline { room: ROOM.into(), busy: false }));    assert!(!effects.contains(&Effect::WriteHistory));}#[test]fn notes_go_to_the_room_and_who_takes_them_is_kept() {    let (call, _) = run(&group_ringing(), [(Event::Frame(RoomFrame::State { state: RoomState::Live, at: None }), T0 + 500)]);    let (_, effects) = step(&call, Event::Notes { on: true }, T0 + 600);    assert_eq!(effects, vec![Effect::Send { frame: ClientFrame::Notes { on: true } }]);    // Who takes notes is the members' own flag, on the member frame.    let taking: RoomFrame = serde_json::from_value(serde_json::json!({ "t": "member", "member": { "id": "caller", "number": NUMBER, "state": "joined", "notes": true, "can": ["notes"] } })).unwrap();    let (call, effects) = step(&call, Event::Frame(taking), T0 + 700);    assert_eq!(call.notes, vec!["caller".to_string()]);    assert!(matches!(effects[..], [Effect::ShowRoster { .. }]));    // A refusal said to this phone alone asks the screen again.    let refused: RoomFrame = serde_json::from_value(serde_json::json!({ "t": "notes", "refused": "cannot_show", "members": ["m1"] })).unwrap();    let (_, effects) = step(&call, Event::Frame(refused), T0 + 800);    assert!(matches!(effects[..], [Effect::ShowRoster { .. }]));}#[test]fn an_sfu_offer_says_whose_each_track_is() {    let call = group_ringing();    let tracks = vec![Track { mid: Some("100".into()), member: Some("m1".into()), name: "m1-audio".into(), kind: None }];    let (_, effects) = step(&call, Event::Frame(RoomFrame::Sfu { op: SfuOp::Offer, sdp: Some("v=1".into()), tracks: tracks.clone() }), T0 + 500);    assert_eq!(effects, vec![Effect::ApplyRemoteSdp { op: SfuOp::Offer, sdp: "v=1".into(), tracks }]);}