diff --git a/src-tauri/crates/berd-call/PROTOCOL.md b/src-tauri/crates/berd-call/PROTOCOL.md index 410801034..d38454cab 100644 --- a/src-tauri/crates/berd-call/PROTOCOL.md +++ b/src-tauri/crates/berd-call/PROTOCOL.md @@ -74,8 +74,8 @@ Detailed backend errors are diagnostics on stderr only; protocol rejection and fatal messages are sanitized at the stdout boundary. `session.tts` describes the voice that speaks replies, and `set_tts_settings` changes it: in Expert-Spokesperson sessions, that is the configured TTS backend -with `--expert-voice tts` and otherwise the Spokesperson's own voice. With -`--expert-voice tts`, `session.spokesperson` is the Spokesperson's own OpenAI +with `--allow-direct-agent-speech` and otherwise the Spokesperson's own voice. With +`--allow-direct-agent-speech`, `session.spokesperson` is the Spokesperson's own OpenAI snapshot, with its own revision, and `set_spokesperson_settings` changes it the way `set_tts_settings` changes the Spokesperson's voice in other sessions. A reply in the Expert's own voice reports the same `admitted`, `speech_completed`, @@ -206,7 +206,7 @@ it never admits a replacement while old host audio may still be active. {"type":"set_spokesperson_settings","id":u64,"expected_revision":u64,"settings":TtsSettings} {"type":"set_input_during_tts","id":u64,"expected_revision":u64,"policy":"allow_barge_in"|"suppress_input"} {"type":"reset_input","id":u64} -{"type":"prepare_speak","id":u64,"acknowledgement":u64|null,"text":string,"resolved_handoff_ids":[string]?,"voice":string?,"language":string?} +{"type":"prepare_speak","id":u64,"acknowledgement":u64|null,"text":string,"resolved_handoff_ids":[string]?,"voice":string?,"language":string?,"relay":bool?} {"type":"output_ready","id":u64,"speech_id":u64} audio acknowledgements listed above {"type":"query_state","id":u64,"after":u64} @@ -219,7 +219,16 @@ Unknown fields are rejected. IDs are positive. Speak text is at most 16 KiB. `prepare_speak.voice` speaks that one utterance in another voice of the reply backend, keeping its other settings; `language` changes a Siri voice's locale too. A voice the backend doesn't offer, or a voice for a call whose replies -are spoken by the Spokesperson, is `not_admitted(invalid_voice)`. +are spoken by the Spokesperson, is `not_admitted(invalid_voice)`. In a call +whose replies have their own voice, a reply needs the same `acknowledgement` +as a directive. With `relay: true` (what +`berd-call message-spokesperson` sends), the reply is a directive in any +Expert-Spokesperson call, even one whose replies have their own voice: the +Spokesperson says it, on the same `acknowledgement` and `resolved_handoff_ids` +terms. A call whose replies have their own voice holds no handoff open: the +Expert still hears each one, but `unresolved_handoff_ids` stays empty, no +reminder or renewal waits on them, and naming one in `resolved_handoff_ids` is +`not_admitted(invalid_handoff)`. The parent cannot author speaking state or finalized input; those are derived only from PCM by the child runtime. @@ -254,6 +263,11 @@ linearization point. A speech reservation holds a configuration lease: speech admitted before the response retains its old backend/settings, while later admission receives the new revision. Pocket's public model identifier cannot be changed without selecting and validating another bundle at process startup. +In a `berd-call start` realtime call, a Spokesperson voice or rate change that +the conversation overtakes while its new session is being built is not +rejected: the candidate is discarded and the change is tried again, with the +conversation as it then stands, once the call is idle. Its one result comes +when it finally applies or fails. `set_input_during_tts` changes the policy for later admissions. Its expected revision must be positive. The correlated result is always authoritative: diff --git a/src-tauri/crates/berd-call/README.md b/src-tauri/crates/berd-call/README.md index 77cb30a97..75d8628c6 100644 --- a/src-tauri/crates/berd-call/README.md +++ b/src-tauri/crates/berd-call/README.md @@ -68,16 +68,14 @@ without changing the call's voice, so agents sharing a call can sound distinct. server listens only on `127.0.0.1:5222` by default; all four commands accept `--port` when more than one local call must be addressed. `--stream` writes one TSV row per delivered transcript event after the `cursor`, `role`, and `text` -header. In Expert-Spokesperson mode the Expert, like a GPT-Live delegate, hears -the conversation only when the Spokesperson hands off: the stream prints -nothing until then, and then every row since the last handoff, ending with the -`handoff` row. `--stream live` instead shows the conversation as it happens: a +header. In Expert-Spokesperson mode the stream hears the call as Berd's Expert +does: a batch of every row since the last one after each Spokesperson reply, +and at each handoff, ending with the `handoff` row. `--stream live` instead shows the conversation as it happens: a `user` row as soon as the words are transcribed, and a `spokesperson_generated` row with cursor `0` as soon as a reply is generated, before it is spoken. The `spokesperson` or `spokesperson_interrupted` row after playback carries the reply's cursor and what was heard. A conventional call has no handoffs, so it -always streams each row. A `--codex` task, like `--stream`, wakes only at -handoffs. The standalone host intentionally uses only the default devices. It +always streams each row. A `--codex` task gets the same batches as `--stream`. The standalone host intentionally uses only the default devices. It suppresses recognition during playback when the default output identifies itself as built-in speakers, preventing the call from transcribing its own speech; headphone-like outputs retain barge-in. @@ -146,12 +144,12 @@ berd-call session --tts-backend pocket --model-dir /path/to/native-voice-v2 --vo berd-call session --stt-backend parakeet --stt-model-dir /path/to/parakeet berd-call session --stt-backend openai berd-call session --tts-backend openai --mode expert-spokesperson --realtime-url ws://127.0.0.1:18870/v1/realtime -berd-call session --voice Aaron --language en-US --mode expert-spokesperson --expert-voice tts +berd-call session --voice Aaron --language en-US --mode expert-spokesperson --allow-direct-agent-speech berd-call session --tts-backend openai --tts-url https://proxy.example/v1/audio/speech berd-call session --stt-backend openai --stt-url wss://proxy.example/v1/realtime?intent=transcription ``` -By default the Spokesperson reads the Expert's replies aloud in its own voice. With `--expert-voice tts`, the Expert speaks for itself: berd-call plays each reply through the configured TTS backend, taking turns with the Spokesperson's audio, and your speech interrupts either of them. Afterwards the Spokesperson gets a silent note of what you heard, so it can follow up without repeating it. A reply settles the handoffs it answers once you hear any of it. `--voice`, `--rate`, `status` and `settings --tts` describe and change the Expert's voice. The Spokesperson keeps its own, shown as `session.spokesperson`: choose it with `--spokesperson-voice NAME` and `--spokesperson-rate 0.25–1.5`, at `start` or live with `settings`, and the menu bar offers both voices. Saved settings keep the Spokesperson's voice for the next call whose replies have their own, but not `--expert-voice`, so pass that on each `start`. +In an Expert–Spokesperson call, the Expert reaches you through the Spokesperson: `berd-call message-spokesperson --re CURSOR [--resolves HANDOFF_ID]... TEXT` has it tell you in its own voice. Like the directives of Berd's Expert, the message must acknowledge the latest input (the Spokesperson's own speech doesn't count), or it comes back `spoke:false` with what was missed, and a handoff it names settles once the Spokesperson has said it. `speak` is refused unless the call was started with `--allow-direct-agent-speech`. With it, the Expert can also speak for itself: berd-call plays each `speak` reply through the configured TTS backend, taking turns with the Spokesperson's audio, and your speech interrupts either of them. Afterwards the Spokesperson gets a silent note of what you heard, so it can follow up without repeating it. A reply has to acknowledge everything you've said, as `speak --re` always does. Such a call holds no handoff open: each still reaches the Expert as a `handoff` row, but nothing waits for an answer, reminds the Expert, or holds back renewing or recovering the Spokesperson's session, and there is nothing for `--resolves` to name. `--voice`, `--rate`, `status` and `settings --tts` describe and change the Expert's voice. The Spokesperson keeps its own, shown as `session.spokesperson`: choose it with `--spokesperson-voice NAME` and `--spokesperson-rate 0.25–1.5`, at `start` or live with `settings`, and the menu bar offers both voices. Saved settings keep the Spokesperson's voice for the next call whose replies have their own, but not `--allow-direct-agent-speech`, so pass that on each `start`. The three URL flags take full endpoints and override only their matching service for that call. Expert–Spokesperson uses `--realtime-url` for both input and output; `--stt-url` applies only to conventional mode, and `--tts-url` also applies to the Expert's own voice. Without an override, each service uses its OpenAI endpoint (or its existing environment override). `OPENAI_API_KEY` supplies the CLI credential; the desktop app stores keys separately by endpoint URL in Keychain. diff --git a/src-tauri/crates/berd-call/src/cli_help.rs b/src-tauri/crates/berd-call/src/cli_help.rs index 64125af97..5c2ffc270 100644 --- a/src-tauri/crates/berd-call/src/cli_help.rs +++ b/src-tauri/crates/berd-call/src/cli_help.rs @@ -8,6 +8,7 @@ Usage: Call runtime: start Run a microphone-backed local voice call speak Speak through the active local call + message-spokesperson Have the Spokesperson tell the user status Inspect the active local call catch-up Read finalized input after a cursor wait-for-input Wait for finalized input after a cursor @@ -33,17 +34,17 @@ Run `berd-call help ` for command-specific usage."#; const START_HELP: &str = r#"Run a local voice call backed by the shared session runtime. Usage: - berd-call start [--port PORT] [--stream [handoffs|live] | --codex] [--non-blocking] + berd-call start [--port PORT] [--stream [live] | --codex] [--non-blocking] [--no-menu-bar] --voice NAME --language BCP47 [session options] The foreground process owns the default microphone and audio output. Session options are the same as `berd-call session`, except the PCM descriptor is owned internally. `--stream` prints cursor, role, and text as TSV. In -Expert-Spokesperson mode it prints nothing until the Spokesperson hands off, -then everything since the last handoff; `--stream live` prints each row as it -happens. `--codex` delivers the handoff batches to the calling Codex task -(requires CODEX_THREAD_ID). A +Expert-Spokesperson mode it prints a batch after every Spokesperson reply and +at each handoff, as Berd's Expert hears the call; `--stream live` prints each +row as it happens. `--codex` delivers the same batches as `--stream` to the +calling Codex task (requires CODEX_THREAD_ID). A menu-bar item controls speech rate, input muting, and ending the call; pass `--no-menu-bar` to omit it. @@ -65,7 +66,23 @@ for delivery. Non-blocking sessions require --stream or --codex and emit speech_ rows only for interruptions, failures, or pending user input. Interrupted results include estimatedSpokenText, a best-effort prefix based on delivered audio. --voice speaks this text in another voice of the call's reply backend without changing its saved -voice, so several agents can share one call in distinct voices."#; +voice, so several agents can share one call in distinct voices. An +Expert-Spokesperson call refuses speak unless started with +--allow-direct-agent-speech; otherwise use message-spokesperson. With it, a +reply acknowledging the latest input is spoken in the Expert's own voice, and +handoffs are never held open, so there is nothing for --resolves to name."#; + +const MESSAGE_SPOKESPERSON_HELP: &str = r#"Message the Spokesperson of the active realtime call. + +Usage: + berd-call message-spokesperson [--port PORT] --re CURSOR + [--resolves HANDOFF_ID]... TEXT + +The Spokesperson tells the user in its own voice, even in a call with +--allow-direct-agent-speech, where `speak` uses the Expert's. Like a directive +from Berd's Expert, the message must acknowledge the latest input (the +Spokesperson's own speech doesn't count), each --resolves settles that handoff +once the Spokesperson has said it, and the result is the same as `speak`'s."#; const SETTINGS_HELP: &str = r#"Update settings for the active local voice call. @@ -81,7 +98,7 @@ Usage: berd-call settings [--port PORT] --restart [session options] The setting applies to subsequent speak calls. In a call started with ---expert-voice tts, --voice and --rate change the agents' voice, and +--allow-direct-agent-speech, --voice and --rate change the agents' voice, and --spokesperson-voice and --spokesperson-rate change the Spokesperson's (an OpenAI realtime voice, 0.25 to 1.5). Non-blocking delivery requires a call started with --stream or --codex. Successful delivery produces no notification."#; @@ -120,7 +137,7 @@ Usage: Each form also accepts: [--rate FLOAT] [--stt-backend macos|parakeet|openai] [--stt-model-dir PATH] - [--mode conventional|expert-spokesperson] [--expert-voice tts|spokesperson] + [--mode conventional|expert-spokesperson] [--allow-direct-agent-speech] [--spokesperson-voice NAME] [--spokesperson-rate 0.25..1.5] [--realtime-url WS_URL] [--stt-url WS_URL] [--tts-url HTTP_URL] @@ -129,9 +146,9 @@ agent integration. See PROTOCOL.md for the framed stdin, stdout, and PCM contracts. Endpoint URL flags override only the matching service for this call and default to OpenAI when no environment override is set. -In expert-spokesperson mode, --expert-voice tts speaks the Expert's replies -through the configured TTS backend, in its own voice beside the Spokesperson's, -instead of having the Spokesperson read them aloud. --spokesperson-voice and +In expert-spokesperson mode, the Expert speaks through the Spokesperson. +--allow-direct-agent-speech also lets it speak to the user itself, through the +configured TTS backend, in its own voice beside the Spokesperson's. --spokesperson-voice and --spokesperson-rate then choose the Spokesperson's own voice and speed."#; const SYNTHESIZE_HELP: &str = r#"Render text through a configured TTS backend into a new WAV file. @@ -211,6 +228,7 @@ fn help_for(topic: &[&str]) -> Option<&'static str> { [] => Some(TOP_LEVEL_HELP), ["start"] => Some(START_HELP), ["speak"] => Some(SPEAK_HELP), + ["message-spokesperson"] => Some(MESSAGE_SPOKESPERSON_HELP), ["status"] => Some(STATUS_HELP), ["catch-up"] | ["wait-for-input"] => Some(POLL_INPUT_HELP), ["settings"] => Some(SETTINGS_HELP), diff --git a/src-tauri/crates/berd-call/src/host_control.rs b/src-tauri/crates/berd-call/src/host_control.rs index e98cadecf..3cd9ea101 100644 --- a/src-tauri/crates/berd-call/src/host_control.rs +++ b/src-tauri/crates/berd-call/src/host_control.rs @@ -30,6 +30,7 @@ pub(crate) trait HostControl: Send + Sync + 'static { resolved_handoff_ids: Vec, voice: Option, language: Option, + relay: bool, ) -> Result; fn stop(&self) -> Result; fn set_non_blocking(&self, enabled: bool) -> Result; @@ -121,6 +122,8 @@ pub(crate) enum ControlRequest { voice: Option, #[serde(default, skip_serializing_if = "Option::is_none")] language: Option, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + relay: bool, }, Stop, NonBlocking { @@ -239,6 +242,7 @@ fn handle_connection(mut stream: TcpStream, control: &dyn HostControl) -> Result resolved_handoff_ids, voice, language, + relay, } => { validate_speak( &text, @@ -246,7 +250,17 @@ fn handle_connection(mut stream: TcpStream, control: &dyn HostControl) -> Result voice.as_deref(), language.is_some(), )?; - control.speak(text, acknowledgement, resolved_handoff_ids, voice, language) + if relay && voice.is_some() { + return Err("a message to the Spokesperson takes no voice".into()); + } + control.speak( + text, + acknowledgement, + resolved_handoff_ids, + voice, + language, + relay, + ) } ControlRequest::Stop => control.stop(), ControlRequest::TtsSettings { settings } => control.set_tts(settings), @@ -413,6 +427,7 @@ mod tests { resolved_handoff_ids: Vec, voice: Option, language: Option, + relay: bool, ) -> Result { Ok(json!({ "spoken":text, @@ -420,6 +435,7 @@ mod tests { "resolvedHandoffIds":resolved_handoff_ids, "voice":voice, "language":language, + "relay":relay, })) } @@ -468,6 +484,7 @@ mod tests { resolved_handoff_ids: vec!["call-1".into()], voice: Some("Nora".into()), language: Some("en-GB".into()), + relay: false, } ) .unwrap(), @@ -477,6 +494,7 @@ mod tests { "resolvedHandoffIds":["call-1"], "voice":"Nora", "language":"en-GB", + "relay":false, }) ); assert_eq!( diff --git a/src-tauri/crates/berd-call/src/host_session.rs b/src-tauri/crates/berd-call/src/host_session.rs index 71b09af77..507bc9e82 100644 --- a/src-tauri/crates/berd-call/src/host_session.rs +++ b/src-tauri/crates/berd-call/src/host_session.rs @@ -462,6 +462,10 @@ fn start_session( stop_requested: Arc::clone(stop_requested), muted: Arc::clone(&actor.muted), transcript: Arc::clone(transcript), + speaks: !expert_spokesperson + || arguments + .iter() + .any(|argument| argument == crate::DIRECT_AGENT_SPEECH), session_arguments: arguments, }); Ok(StartedSession { @@ -519,6 +523,7 @@ enum ControlCommand { resolved_handoff_ids: Vec, voice: Option, language: Option, + relay: bool, non_blocking: bool, response: SyncSender>, }, @@ -546,6 +551,8 @@ struct SessionControl { stop_requested: Arc, muted: Arc, transcript: Arc, + // Whether the Expert may speak to the user rather than only through the Spokesperson. + speaks: bool, session_arguments: Vec, } @@ -743,7 +750,14 @@ impl HostControl for SessionControl { resolved_handoff_ids: Vec, voice: Option, language: Option, + relay: bool, ) -> Result { + if !relay && !self.speaks { + return Err(format!( + "the Expert speaks through the Spokesperson: use message-spokesperson, or start the call with {}", + crate::DIRECT_AGENT_SPEECH + )); + } let (tx, rx) = mpsc::sync_channel(1); self.commands .send(ControlCommand::Speak { @@ -752,6 +766,7 @@ impl HostControl for SessionControl { resolved_handoff_ids, voice, language, + relay, non_blocking: self.non_blocking.load(Ordering::SeqCst), response: tx, }) @@ -819,8 +834,6 @@ struct SessionActor { expert_spokesperson: bool, // User rows already streamed when transcribed, left out of the Expert batch. transcribed: HashSet, - // Rows a handoffs stream or Codex task gets only when the Spokesperson hands off. - held: Vec, stopping: bool, restart: Option, muted: Arc, @@ -883,7 +896,6 @@ impl SessionActor { transcript, expert_spokesperson, transcribed: HashSet::new(), - held: Vec::new(), stopping: false, restart: None, muted: Arc::new(AtomicBool::new(false)), @@ -1100,6 +1112,7 @@ impl SessionActor { resolved_handoff_ids, voice, language, + relay, non_blocking, response, } => { @@ -1114,6 +1127,7 @@ impl SessionActor { resolved_handoff_ids, voice, language, + relay, non_blocking, response, }); @@ -1129,6 +1143,7 @@ impl SessionActor { resolved_handoff_ids, voice, language, + relay, }, )?; self.pending_speak = Some(PendingSpeak { @@ -1292,12 +1307,8 @@ impl SessionActor { self.transcript .record(None, "spokesperson_generated", None, &text)? } - SessionMessage::ExpertDelivery { - events, - handoff_ids, - .. - } if self.expert_spokesperson => { - self.stream_expert_delivery(events, !handoff_ids.is_empty())? + SessionMessage::ExpertDelivery { events, .. } if self.expert_spokesperson => { + self.stream_expert_delivery(&events)? } SessionMessage::Pending { id, utterances } if self.pending_prepare_id() == Some(id) => { self.respond_speak(Ok(json!({"spoke":false,"utterances":utterances}))); @@ -1413,19 +1424,9 @@ impl SessionActor { fn stream_expert_delivery( &mut self, - events: Vec, - handoff: bool, + events: &[RealtimeExpertDeliveryEvent], ) -> Result<(), String> { - self.held.extend(events); - if !handoff - && matches!( - *self.transcript, - Transcript::Stdout { live: false } | Transcript::Codex(_) - ) - { - return Ok(()); - } - for event in unstreamed(&std::mem::take(&mut self.held), &mut self.transcribed) { + for event in unstreamed(events, &mut self.transcribed) { self.transcript.record( Some(event.cursor), expert_delivery_role_name(event.role), @@ -2308,6 +2309,16 @@ impl AudioPlaybackState { } } + /// What the host played of this speech, once it has ended it. The session may not have heard yet, so its records for it can still arrive. + fn retired(&self, speech_id: u64) -> Option { + match self { + Self::Finished(retired) if retired.speech_id == speech_id => { + Some(retired.played_frames) + } + _ => None, + } + } + fn finish(&mut self, speech_id: u64, played_frames: u64) { *self = Self::Finished(RetiredAudio { speech_id, @@ -2522,6 +2533,9 @@ fn handle_audio_record( AUDIO_CHUNK_KIND if payload.len() >= 16 && (payload.len() - 16).is_multiple_of(4) => { let speech_id = le_u64(&payload[0..8])?; let sequence = le_u64(&payload[8..16])?; + if playback.retired(speech_id).is_some() { + return Ok(()); + } let active = playback .playing_mut(speech_id) .ok_or_else(|| "voice session sent audio for an inactive speech".to_string())?; @@ -2554,6 +2568,9 @@ fn handle_audio_record( AUDIO_END_KIND if payload.len() == 24 => { let speech_id = le_u64(&payload[0..8])?; let sequence = le_u64(&payload[8..16])?; + if playback.retired(speech_id).is_some() { + return Ok(()); + } let active = playback .playing_mut(speech_id) .ok_or_else(|| "voice session ended inactive audio".to_string())?; @@ -2562,6 +2579,15 @@ fn handle_audio_record( } AUDIO_CANCEL_KIND if payload.len() == 8 => { let speech_id = le_u64(payload)?; + if let Some(played_frames) = playback.retired(speech_id) { + return send_request( + writer, + &SessionRequest::AudioCancelled { + speech_id, + played_frames, + }, + ); + } let active = playback .playing_mut(speech_id) .ok_or_else(|| "voice session cancelled inactive audio".to_string())?; @@ -2722,43 +2748,6 @@ mod tests { assert_eq!(transcribed, HashSet::from([3])); } - #[test] - fn handoffs_stream_holds_rows_until_a_handoff() { - let mut child = Command::new("/bin/cat") - .stdin(Stdio::piped()) - .stdout(Stdio::null()) - .spawn() - .unwrap(); - let writer = Arc::new(Mutex::new(child.stdin.take().unwrap())); - let (_event_tx, events) = mpsc::sync_channel(1); - let (_command_tx, commands) = mpsc::sync_channel(1); - let (audio, _audio_rx) = mpsc::sync_channel(1); - let mut actor = test_actor(writer, events, commands, audio); - let event = |cursor, role| RealtimeExpertDeliveryEvent { - cursor, - role, - text: format!("event {cursor}"), - handoff_id: None, - }; - actor - .stream_expert_delivery( - vec![ - event(1, RealtimeExpertDeliveryRole::User), - event(2, RealtimeExpertDeliveryRole::Spokesperson), - ], - false, - ) - .unwrap(); - assert_eq!(actor.held.len(), 2); - actor - .stream_expert_delivery(vec![event(3, RealtimeExpertDeliveryRole::Handoff)], true) - .unwrap(); - assert!(actor.held.is_empty()); - drop(actor); - let _ = child.kill(); - let _ = child.wait(); - } - #[test] fn microphone_teardown_reports_a_blocked_forwarder() { let (_release, blocked) = mpsc::sync_channel::<()>(1); @@ -3371,6 +3360,7 @@ mod tests { resolved_handoff_ids: Vec::new(), voice: None, language: None, + relay: false, non_blocking: true, response: next_tx, }) @@ -4343,6 +4333,7 @@ mod tests { stop_requested: Arc::clone(&stop_requested), muted: Arc::new(AtomicBool::new(false)), transcript: Arc::new(Transcript::Silent), + speaks: true, session_arguments: vec!["session".into()], }; drop(receiver); @@ -4350,6 +4341,42 @@ mod tests { assert!(stop_requested.load(Ordering::SeqCst)); } + #[test] + fn the_expert_speaks_only_through_the_spokesperson_unless_allowed() { + let (commands, receiver) = mpsc::sync_channel(1); + let control = SessionControl { + commands, + running: Arc::new(AtomicBool::new(true)), + ready: ReadyState { + session: Arc::new(Mutex::new(test_snapshot())), + }, + non_blocking: Arc::new(AtomicBool::new(false)), + stop_requested: Arc::new(AtomicBool::new(false)), + muted: Arc::new(AtomicBool::new(false)), + transcript: Arc::new(Transcript::Silent), + speaks: false, + session_arguments: vec!["session".into()], + }; + let refusal = control + .speak("Hello".into(), None, Vec::new(), None, None, false) + .unwrap_err(); + assert!(refusal.contains("message-spokesperson"), "{refusal}"); + assert!(receiver.try_recv().is_err()); + let worker = thread::spawn(move || match receiver.recv().unwrap() { + ControlCommand::Speak { + relay, response, .. + } => { + response.send(Ok(json!({}))).unwrap(); + relay + } + _ => panic!("expected a message to the Spokesperson"), + }); + control + .speak("Hello".into(), None, Vec::new(), None, None, true) + .unwrap(); + assert!(worker.join().unwrap()); + } + #[test] fn voice_updates_preserve_the_latest_rate_and_revision() { let (commands, receiver) = mpsc::sync_channel(1); @@ -4365,6 +4392,7 @@ mod tests { stop_requested: Arc::new(AtomicBool::new(false)), muted: Arc::new(AtomicBool::new(false)), transcript: Arc::new(Transcript::Silent), + speaks: true, session_arguments: vec!["session".into()], }; let worker = thread::spawn(move || match receiver.recv().unwrap() { @@ -4407,6 +4435,7 @@ mod tests { stop_requested: Arc::new(AtomicBool::new(false)), muted: Arc::new(AtomicBool::new(false)), transcript: Arc::new(Transcript::Silent), + speaks: true, session_arguments: vec!["session".into()], }; let worker = thread::spawn(move || match receiver.recv().unwrap() { @@ -4434,6 +4463,64 @@ mod tests { ); } + #[test] + fn spokesperson_updates_keep_its_other_setting_and_revision() { + let (commands, receiver) = mpsc::sync_channel(1); + let mut snapshot = test_snapshot(); + let openai = |voice: &str, rate| berd_call::TtsSettings::OpenAi { + model: "gpt-realtime".into(), + voice: voice.into(), + rate, + }; + let session = Arc::new(Mutex::new(snapshot.clone())); + let control = SessionControl { + commands, + running: Arc::new(AtomicBool::new(true)), + ready: ReadyState { + session: Arc::clone(&session), + }, + non_blocking: Arc::new(AtomicBool::new(false)), + stop_requested: Arc::new(AtomicBool::new(false)), + muted: Arc::new(AtomicBool::new(false)), + transcript: Arc::new(Transcript::Silent), + speaks: true, + session_arguments: vec!["session".into()], + }; + let refusal = control.set_spokesperson(None, Some(1.5)).unwrap_err(); + assert!( + refusal.contains("no separate Spokesperson voice"), + "{refusal}" + ); + snapshot.spokesperson = Some(berd_call::TtsConfigurationSnapshot { + revision: 3, + settings: openai("marin", 1.25), + }); + *session.lock().unwrap() = snapshot; + let worker = thread::spawn(move || { + (0..2) + .map(|_| match receiver.recv().unwrap() { + ControlCommand::SpokespersonSettings { + settings, + expected_revision, + response, + } => { + response.send(Ok(json!({}))).unwrap(); + (settings, expected_revision) + } + _ => panic!("expected a Spokesperson settings command"), + }) + .collect::>() + }); + control.set_spokesperson(None, Some(1.5)).unwrap(); + control + .set_spokesperson(Some("cedar".into()), None) + .unwrap(); + assert_eq!( + worker.join().unwrap(), + [(openai("marin", 1.5), 3), (openai("cedar", 1.25), 3)] + ); + } + #[test] fn stop_cancels_a_pending_restart() { let mut child = Command::new("/bin/cat") @@ -4550,6 +4637,17 @@ mod tests { assert_eq!(playback.played_frames(18), 0); } + #[test] + fn only_the_ended_speech_is_retired() { + let playback = AudioPlaybackState::Finished(RetiredAudio { + speech_id: 17, + played_frames: 4_096, + }); + assert_eq!(playback.retired(17), Some(4_096)); + assert_eq!(playback.retired(18), None); + assert_eq!(AudioPlaybackState::Idle.retired(17), None); + } + #[test] fn suspension_settle_time_preserves_route_safety_duration() { assert_eq!( diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index ed85acaf7..11ae20517 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -81,7 +81,7 @@ mod system_input_mute; use session_audio::{ AudioHostAck, AudioOutputControlRequest, AudioPipeTransport, RemotePcmAudioOutput, - AUDIO_CANCELLED, + AUDIO_CANCELLED, AUDIO_HOST_FAILED, }; use session_framing::{ @@ -561,11 +561,29 @@ fn main() { resolved_handoff_ids, voice, language, + relay: false, }, ) .unwrap_or_else(|error| operational_error("speak", error)); print_pretty_json(&response).unwrap_or_else(|error| operational_error("speak", error)); } + Some("message-spokesperson") => { + let options = parse_or_exit(parse_message_spokesperson_args(&args), &args); + let response = host_control::request( + options.port, + host_control::ControlRequest::Speak { + text: options.text, + acknowledgement: options.acknowledgement, + resolved_handoff_ids: options.resolved_handoff_ids, + voice: None, + language: None, + relay: true, + }, + ) + .unwrap_or_else(|error| operational_error("message-spokesperson", error)); + print_pretty_json(&response) + .unwrap_or_else(|error| operational_error("message-spokesperson", error)); + } Some("status") => { let port = parse_or_exit(parse_control_port(&args), &args); let response = host_control::request(port, host_control::ControlRequest::Status) @@ -805,9 +823,8 @@ fn parse_start_args(args: &[String]) -> Result { transcript = if flag == "--codex" { TranscriptDestination::Codex } else { - let mode = args.get(index).map(String::as_str); - let live = mode == Some("live"); - if matches!(mode, Some("live" | "handoffs")) { + let live = args.get(index).map(String::as_str) == Some("live"); + if live { index += 1; } TranscriptDestination::Stdout { live } @@ -881,10 +898,7 @@ fn parse_saved_start_args_at(args: &[String], path: PathBuf) -> Result Result Result { + let options = parse_speak_control_args(args)?; + if options.voice.is_some() { + return Err("message-spokesperson takes no --voice".into()); + } + if options.acknowledgement.is_none() { + return Err("message-spokesperson requires --re CURSOR".into()); + } + Ok(options) +} + fn parse_host_settings_args( args: &[String], ) -> Result<(u16, host_control::ControlRequest), ParseFailure> { @@ -2417,6 +2443,7 @@ fn run_session(config: SessionConfig, pcm_output_fd: RawFd) -> Result<(), String resolved_handoff_ids: _, voice, language, + relay: _, }) => { let request = PrepareRequest { id, @@ -2740,6 +2767,8 @@ struct PendingExpertPrepare { resolved_handoff_ids: Vec, /// The Expert's voice for this reply, when not its usual one. voice: Option, + /// The Spokesperson says it, even when the Expert has its own voice. + relay: bool, } struct PendingSpokespersonSettingsUpdate { @@ -2767,6 +2796,32 @@ fn rollback_spokesperson_voice_update( } } +fn is_settings_update(pending: &Option) -> bool { + pending + .as_ref() + .is_some_and(|update| matches!(update.purpose(), VoiceUpdatePurpose::Settings)) +} + +/// Puts back a settings change the conversation overtook while its session +/// was being built, to be tried again, with the conversation as it then +/// stands, once the call is idle. +fn requeue_spokesperson_voice_update( + pending: &mut Option, + old_runtime: &OpenAiSpokespersonRuntime, + queue: &mut VoiceUpdateQueue, +) -> Result<(), String> { + let update = pending.take().expect("matched settings update"); + let request = PendingSpokespersonSettingsUpdate { + id: update.id, + base_revision: update.base_revision, + settings: update.settings.clone(), + }; + update.abort(old_runtime)?; + queue + .try_enqueue(false, request) + .map_err(|_| "a Spokesperson settings update was already queued".to_string()) +} + fn activate_spokesperson_voice_update( pending: &mut Option, runtime: &mut Option, @@ -2975,9 +3030,9 @@ struct LiveResponse { prepare_id: Option, speech_id: Option, expert_text: Option, - /// An Expert reply spoken in its own voice, with the handoffs it answers. - /// It has no provider response; its whole text is played at once. - reply: Option>, + /// An Expert reply spoken in its own voice. It has no provider + /// response; its whole text is played at once. + reply: bool, /// The voice it asked for, when not the Expert's usual one. voice: Option, /// Whether the parent has accepted the reply's output, so it may play. @@ -2999,7 +3054,7 @@ impl LiveResponse { prepare_id, speech_id, expert_text: None, - reply: None, + reply: false, voice: None, output_ready: false, delivery: RealtimeAudioDelivery::default(), @@ -3106,30 +3161,50 @@ fn spokesperson_pcm_allowed( && input_policy.policy == berd_call::input::InputDuringTtsPolicy::SuppressInput) } -fn set_spokesperson_input_muted( - id: u64, - muted: bool, - input_muted: &mut bool, - mut reset_input: impl FnMut() -> Result<(), String>, - writer: &mut impl Write, -) -> Result<(), String> { - *input_muted = muted; - if muted { - reset_input()?; - } - write_message( - writer, - &SessionMessage::InputMuteApplied { id, active: muted }, - ) +/// Input controls waiting on the provider to clear its input buffer, so microphone audio keeps flowing meanwhile. +/// Each clear goes out where its control arrived; controls answer in order once no clear is outstanding. +#[derive(Default)] +struct InputResets { + clearing: VecDeque>>, + replies: Vec, } -fn reset_spokesperson_input( - id: u64, - mut reset_input: impl FnMut() -> Result<(), String>, - writer: &mut impl Write, -) -> Result<(), String> { - reset_input()?; - write_message(writer, &SessionMessage::InputResetApplied { id }) +impl InputResets { + fn idle(&self) -> bool { + self.clearing.is_empty() + } + + fn apply( + &mut self, + reply: SessionMessage, + clear: bool, + reset_input: impl FnOnce() -> Result>, String>, + writer: &mut impl Write, + ) -> Result<(), String> { + if clear { + self.clearing.push_back(reset_input()?); + } else if self.idle() { + return write_message(writer, &reply); + } + self.replies.push(reply); + Ok(()) + } + + fn poll(&mut self, writer: &mut impl Write) -> Result<(), String> { + while let Some(clearing) = self.clearing.front() { + match clearing.try_recv() { + Err(mpsc::TryRecvError::Empty) => return Ok(()), + Err(mpsc::TryRecvError::Disconnected) => { + return Err("Spokesperson runtime is closed".into()) + } + Ok(result) => result?, + } + self.clearing.pop_front(); + } + self.replies + .drain(..) + .try_for_each(|reply| write_message(writer, &reply)) + } } fn set_spokesperson_input_policy( @@ -3197,6 +3272,7 @@ fn queued_spokesperson_settings_are_ready( responses: &HashMap, directive_speeches: &HashMap, cancelled_directives: &HashSet, + expert_tts: bool, ) -> bool { let work = spokesperson_host_work( gate, @@ -3205,7 +3281,8 @@ fn queued_spokesperson_settings_are_ready( directive_speeches, cancelled_directives, ); - gate.lifecycle.queued_settings_are_ready(work) + // A held directive would make the change unsafe, so it goes first. + !(work.pending_expert_prepare && !expert_tts) && gate.lifecycle.queued_settings_are_ready(work) } fn validate_queued_spokesperson_settings( @@ -3224,10 +3301,17 @@ fn validate_queued_spokesperson_settings( fn spokesperson_voice_update_is_safe( update: &VoiceUpdateTransaction, core: &RealtimeExpertSpokespersonSession, + expert_tts: bool, snapshot: &berd_call::TtsConfigurationSnapshot, gate: &ExpertTurnGate, work: RealtimeHostWork, ) -> bool { + // When the Expert has its own voice, a held reply waits for the + // replacement, and adds nothing to what it was given. + let work = RealtimeHostWork { + pending_expert_prepare: work.pending_expert_prepare && !expert_tts, + ..work + }; gate.lifecycle.voice_update_is_safe( update.purpose(), update.semantic_revision, @@ -3283,14 +3367,19 @@ fn run_expert_spokesperson_session( let (audio_control_tx, audio_control_rx) = mpsc::channel(); let (playback_tx, playback_rx) = mpsc::channel::(); let (reply_tx, reply_rx) = mpsc::channel::(); - // The Expert's own voice, with `--expert-voice tts`. + // The Expert's own voice, with `--allow-direct-agent-speech`. let mut reply_tts: Option> = None; let (tts_configuration_tx, tts_configuration_rx) = mpsc::channel::(); let mut tts_update: Option = None; let mut next_tts_update_attempt = 0_u64; let stdout = io::stdout(); let mut writer = BufWriter::new(stdout.lock()); + // An Expert that may speak for itself answers handoffs when it likes, so + // nothing holds them open. let mut core = RealtimeExpertSpokespersonSession::new(0, "external"); + if config.expert_tts { + core = core.without_handoff_tracking(); + } let mut runtime: Option = None; let mut runtime_events: Option> = None; let mut runtime_config: Option = None; @@ -3310,12 +3399,14 @@ fn run_expert_spokesperson_session( let mut session_tts: Option = None; let mut input_during_tts_slot: Option = None; let mut input_muted = false; + let mut input_resets = InputResets::default(); let mut queued_tts_settings = VoiceUpdateQueue::::default(); let mut pending_voice_update: Option = None; let mut status_sound_runtime = StatusSoundRuntime::default(); loop { if initialized { + input_resets.poll(&mut writer)?; let work = spokesperson_host_work( &turn_gate, active.as_ref(), @@ -3348,7 +3439,11 @@ fn run_expert_spokesperson_session( )?); } } - if let Some(update) = pending_voice_update.as_ref() { + // A voice change waits for input resets, which clear the same provider input buffer it does. + if let Some(update) = pending_voice_update + .as_ref() + .filter(|_| input_resets.idle()) + { let work = spokesperson_host_work( &turn_gate, active.as_ref(), @@ -3359,6 +3454,7 @@ fn run_expert_spokesperson_session( let safe = spokesperson_voice_update_is_safe( update, &core, + reply_tts.is_some(), session_tts.as_ref().expect("initialized TTS snapshot"), &turn_gate, work, @@ -3380,6 +3476,15 @@ fn run_expert_spokesperson_session( )?; turn_gate.lifecycle.session_started(Instant::now()); } + VoiceUpdateAction::Reject(_) + if !safe && is_settings_update(&pending_voice_update) => + { + requeue_spokesperson_voice_update( + &mut pending_voice_update, + runtime.as_ref().expect("initialized runtime"), + &mut queued_tts_settings, + )?; + } VoiceUpdateAction::Reject(message) => { let expiry_cause = pending_voice_update.as_ref().and_then(|update| { if let VoiceUpdatePurpose::SessionRecovery { cause } = update.purpose() { @@ -3420,6 +3525,7 @@ fn run_expert_spokesperson_session( &responses, &directive_speeches, &cancelled_directives, + reply_tts.is_some(), ); if let Some(request) = queued_tts_settings.take_ready(pending_voice_update.is_some(), queued_settings_ready) @@ -3686,12 +3792,8 @@ fn run_expert_spokesperson_session( .expect("streaming response state exists") .queue_audio(samples, total_pending_frames)?; } - Err(mpsc::TrySendError::Disconnected(_)) => { - return Err( - "Spokesperson playback worker closed while streaming" - .into(), - ) - } + // The worker has stopped; its result settles this reply. + Err(mpsc::TrySendError::Disconnected(_)) => {} Err(mpsc::TrySendError::Full(LivePlaybackInput::Finish)) => { unreachable!("streaming sends samples") } @@ -3808,8 +3910,8 @@ fn run_expert_spokesperson_session( } } SpokespersonEvent::InputCutoverFinished { request_id, result } => { - let action = pending_voice_update.as_ref().map_or( - VoiceBarrierAction::Ignore, + let (action, safe) = pending_voice_update.as_ref().map_or( + (VoiceBarrierAction::Ignore, true), |update| { let work = spokesperson_host_work( &turn_gate, @@ -3821,16 +3923,18 @@ fn run_expert_spokesperson_session( let safe = spokesperson_voice_update_is_safe( update, &core, + reply_tts.is_some(), session_tts.as_ref().expect("initialized TTS snapshot"), &turn_gate, work, ); - match update.next_action(Instant::now(), safe) { + let action = match update.next_action(Instant::now(), safe) { VoiceUpdateAction::Reject(message) => { VoiceBarrierAction::Reject(message) } _ => update.finish_barrier(request_id, result, safe), - } + }; + (action, safe) }, ); if action == VoiceBarrierAction::Activate { @@ -3843,6 +3947,15 @@ fn run_expert_spokesperson_session( &mut writer, )?; turn_gate.lifecycle.session_started(Instant::now()); + } else if matches!(action, VoiceBarrierAction::Reject(_)) + && !safe + && is_settings_update(&pending_voice_update) + { + requeue_spokesperson_voice_update( + &mut pending_voice_update, + runtime.as_ref().expect("initialized runtime"), + &mut queued_tts_settings, + )?; } else if let VoiceBarrierAction::Reject(message) = action { rollback_spokesperson_voice_update( &mut pending_voice_update, @@ -4108,7 +4221,8 @@ fn run_expert_spokesperson_session( else { continue; }; - if message == AUDIO_CANCELLED { + // A reply the host stopped playing ends where it was cut off, as if you had interrupted it; the next gets a new player. + if message == AUDIO_CANCELLED || message == AUDIO_HOST_FAILED { apply_external_coordinator_event( &mut core, runtime.as_ref().expect("initialized runtime"), @@ -4119,6 +4233,10 @@ fn run_expert_spokesperson_session( )?; if let Some(response) = responses.get_mut(&response_id) { emit_live_interrupted_terminal(response, &playback, &mut writer)?; + if message == AUDIO_HOST_FAILED { + // The model hears only what played, as when the user talks over it. + require_live_response_truncation(response)?; + } send_live_response_truncation( &response_id, response, @@ -4212,7 +4330,6 @@ fn run_expert_spokesperson_session( runtime.as_ref().expect("initialized runtime"), &text[..heard], interrupted, - response.reply.as_deref().unwrap_or_default(), )?; } if initialized && !turn_gate.input_blocks_output() { @@ -4240,7 +4357,7 @@ fn run_expert_spokesperson_session( if let Some(request) = turn_gate.take_ready( active.is_some() || pending_voice_update.is_some() - || queued_tts_settings.is_pending(), + || reply_tts.is_some() && queued_tts_settings.is_pending(), responses.len(), ) { submit_expert_prepare( @@ -4456,6 +4573,7 @@ fn run_expert_spokesperson_session( resolved_handoff_ids, voice, language, + relay, }) => { let Some(voice) = speak_voice(reply_tts.as_deref(), voice, language, id, &mut writer)? @@ -4468,6 +4586,7 @@ fn run_expert_spokesperson_session( text, resolved_handoff_ids, voice, + relay, }; let routing = route_expert_prepare( &mut turn_gate, @@ -4478,7 +4597,8 @@ fn run_expert_spokesperson_session( active.as_ref(), &responses, ), - pending_voice_update.is_some() || queued_tts_settings.is_pending(), + pending_voice_update.is_some() + || reply_tts.is_some() && queued_tts_settings.is_pending(), active.is_some(), responses.len(), ); @@ -4508,7 +4628,7 @@ fn run_expert_spokesperson_session( response.prepare_id == Some(id) && response.speech_id == Some(speech_id) }; let reply = responses.iter_mut().find(|(_, response)| { - response.reply.is_some() && !response.output_ready && matches(response) + response.reply && !response.output_ready && matches(response) }); let valid = if let Some((response_id, response)) = reply { response.output_ready = true; @@ -4520,7 +4640,7 @@ fn run_expert_spokesperson_session( .is_some_and(|directive| directive.speech_id == speech_id) || responses .values() - .any(|response| response.reply.is_none() && matches(response)) + .any(|response| !response.reply && matches(response)) }; write_message( &mut writer, @@ -4790,9 +4910,7 @@ fn run_expert_spokesperson_session( CancelOutcome::Cancelled } else if let Some(response_id) = responses .iter() - .find(|(_, response)| { - response.reply.is_some() && response.prepare_id == Some(id) - }) + .find(|(_, response)| response.reply && response.prepare_id == Some(id)) .map(|(response_id, _)| response_id.clone()) { waiting_responses.retain(|waiting| *waiting != response_id); @@ -4873,10 +4991,10 @@ fn run_expert_spokesperson_session( &mut writer, )?; } - set_spokesperson_input_muted( - id, + input_muted = muted; + input_resets.apply( + SessionMessage::InputMuteApplied { id, active: muted }, muted, - &mut input_muted, || runtime.as_ref().expect("initialized runtime").reset_input(), &mut writer, )?; @@ -4891,8 +5009,9 @@ fn run_expert_spokesperson_session( &mut writer, )?; } - reset_spokesperson_input( - id, + input_resets.apply( + SessionMessage::InputResetApplied { id }, + true, || runtime.as_ref().expect("initialized runtime").reset_input(), &mut writer, )?; @@ -5074,7 +5193,7 @@ fn drop_waiting_replies( if Some(response_id.as_str()) == active_response_id || !responses .get(response_id) - .is_some_and(|response| response.reply.is_some()) + .is_some_and(|response| response.reply) { continue; } @@ -5089,39 +5208,19 @@ fn drop_waiting_replies( spoken_through_utf8: 0, }, )?; - finish_expert_reply( - core, - runtime, - "", - true, - response.reply.as_deref().unwrap_or_default(), - )?; + finish_expert_reply(core, runtime, "", true)?; } Ok(()) } -/// Tells the Spokesperson what the user heard of an Expert reply, and settles -/// the handoffs it answers. +/// Tells the Spokesperson what the user heard of an Expert reply. fn finish_expert_reply( core: &mut RealtimeExpertSpokespersonSession, runtime: &OpenAiSpokespersonRuntime, heard: &str, interrupted: bool, - handoff_ids: &[String], ) -> Result<(), String> { let heard = heard.trim(); - // Handoffs settled elsewhere while the reply played need no settling here. - let unknown = core.unknown_handoff_ids(handoff_ids); - let open: Vec = handoff_ids - .iter() - .filter(|id| !unknown.contains(id)) - .cloned() - .collect(); - if heard.is_empty() { - core.release_handoffs(&open); - } else { - core.dismiss_handoffs(&open)?; - } let message = match (heard.is_empty(), interrupted) { (true, _) => "The user interrupted the Expert's spoken reply before hearing any of it.".into(), (false, false) => format!("The Expert said this to the user in its own voice:\n{heard}"), @@ -5209,6 +5308,7 @@ fn submit_expert_prepare( next_speech_id: &mut u64, writer: &mut impl Write, ) -> Result<(), String> { + let own_voice = expert_tts && !request.relay; if !core .unknown_handoff_ids(&request.resolved_handoff_ids) .is_empty() @@ -5244,21 +5344,21 @@ fn submit_expert_prepare( let speech_id = *next_speech_id; *next_speech_id += 1; core.record_expert_turn(message.clone()); - let resolved_handoff_ids = request.resolved_handoff_ids; - core.mark_handoffs_resolving(&resolved_handoff_ids)?; - if expert_tts { + if own_voice { // Played in turn with the Spokesperson's responses, without one of its own, // once the parent is ready for its output. let response_id = format!("expert-reply-{speech_id}"); let mut response = LiveResponse::new(Some(request.id), Some(speech_id)); response.expert_text = Some(message); - response.reply = Some(resolved_handoff_ids); + response.reply = true; response.voice = request.voice; response.audio_done = true; response.finish_sent = true; response.server_finished = true; responses.insert(response_id, response); } else { + let resolved_handoff_ids = request.resolved_handoff_ids; + core.mark_handoffs_resolving(&resolved_handoff_ids)?; directive_speeches.insert( request.id, DirectiveSpeech { @@ -5427,7 +5527,7 @@ fn start_next_live_playback( if response.interrupted || response.playback_complete { continue; } - if response.reply.is_some() { + if response.reply { let tts = reply_tts.ok_or("an Expert reply has no voice of its own")?; *active = Some(spawn_reply_playback( response_id, @@ -5520,8 +5620,11 @@ fn flush_active_live_playback( response.pending_audio.push_front(samples); break; } + // The worker has stopped, and the result it sent first settles this reply. Err(mpsc::TrySendError::Disconnected(_)) => { - return Err("Spokesperson playback worker closed while streaming".into()) + response.pending_audio.clear(); + response.pending_frames = 0; + return Ok(()); } Err(mpsc::TrySendError::Full(LivePlaybackInput::Finish)) => { unreachable!("audio queue contains samples") @@ -5531,10 +5634,10 @@ fn flush_active_live_playback( if response.audio_done && response.pending_audio.is_empty() && !response.finish_sent { match playback.sender.try_send(LivePlaybackInput::Finish) { Ok(()) => response.finish_sent = true, - Err(mpsc::TrySendError::Full(LivePlaybackInput::Finish)) => {} - Err(mpsc::TrySendError::Disconnected(_)) => { - return Err("Spokesperson playback worker closed before finish".into()) - } + Err( + mpsc::TrySendError::Full(LivePlaybackInput::Finish) + | mpsc::TrySendError::Disconnected(_), + ) => {} Err(mpsc::TrySendError::Full(LivePlaybackInput::Samples(_))) => { unreachable!("finish queue contains finish") } @@ -5880,6 +5983,10 @@ fn finish_unready_input_runtime(runtime: VoiceInputRuntime) -> Result<(), String .map_err(|error| format!("finish unready voice input runtime: {error}")) } +/// Lets the Expert speak to the user in its own voice in an +/// Expert-Spokesperson call, rather than only through the Spokesperson. +pub(crate) const DIRECT_AGENT_SPEECH: &str = "--allow-direct-agent-speech"; + fn parse_args(args: &[String]) -> Result { if args.get(1).map(String::as_str) != Some("session") { return Err("the only supported command is session".into()); @@ -5902,6 +6009,11 @@ fn parse_args(args: &[String]) -> Result { if is_help_flag(flag) { return Err(ParseFailure::HelpRequested); } + if flag == DIRECT_AGENT_SPEECH { + expert_tts = true; + index += 1; + continue; + } let value = args .get(index + 1) .ok_or_else(|| format!("{flag} requires a value"))?; @@ -5931,13 +6043,6 @@ fn parse_args(args: &[String]) -> Result { _ => return Err("--mode must be conventional or expert-spokesperson".into()), } } - "--expert-voice" => { - expert_tts = match value.as_str() { - "tts" => true, - "spokesperson" => false, - _ => return Err("--expert-voice must be tts or spokesperson".into()), - } - } "--spokesperson-voice" => spokesperson_voice = Some(value.clone()), "--spokesperson-rate" => { spokesperson_rate = Some( @@ -5957,12 +6062,13 @@ fn parse_args(args: &[String]) -> Result { return Err("--realtime-url requires --mode expert-spokesperson".into()); } if expert_tts && mode != SessionMode::ExpertSpokesperson { - return Err("--expert-voice requires --mode expert-spokesperson".into()); + return Err(format!("{DIRECT_AGENT_SPEECH} requires --mode expert-spokesperson").into()); } if (spokesperson_voice.is_some() || spokesperson_rate.is_some()) && !expert_tts { - return Err( - "--spokesperson-voice and --spokesperson-rate require --expert-voice tts".into(), - ); + return Err(format!( + "--spokesperson-voice and --spokesperson-rate require {DIRECT_AGENT_SPEECH}" + ) + .into()); } if let Some(voice) = &spokesperson_voice { if !berd_call::openai_realtime_protocol::OPENAI_REALTIME_VOICE_IDS.contains(&voice.as_str()) @@ -6012,6 +6118,10 @@ fn parse_pcm_output_fd(args: &[String]) -> Result { let mut value = None; let mut index = 2; while index < args.len() { + if args[index] == DIRECT_AGENT_SPEECH { + index += 1; + continue; + } if args[index] == "--pcm-output-fd" { if value.is_some() { return Err("--pcm-output-fd may be provided only once".into()); @@ -8505,6 +8615,7 @@ mod tests { text: "answer".into(), resolved_handoff_ids: Vec::new(), voice: None, + relay: false, }; assert!(matches!( gate.defer_if_busy(request, false, 1), @@ -8545,6 +8656,7 @@ mod tests { text: "first".into(), resolved_handoff_ids: Vec::new(), voice: None, + relay: false, }, false, 1, @@ -8559,6 +8671,7 @@ mod tests { text: "second".into(), resolved_handoff_ids: Vec::new(), voice: None, + relay: false, }, false, 1, @@ -8590,6 +8703,7 @@ mod tests { text: "second".into(), resolved_handoff_ids: Vec::new(), voice: None, + relay: false, }, expert_output_reserved(&directives, &HashSet::new(), None, &responses), false, @@ -8929,31 +9043,99 @@ mod tests { } #[test] - fn spokesperson_input_controls_are_nonfatal_revisioned_and_gate_pcm() { - let mut muted = false; - let mut reset_count = 0; + fn input_controls_answer_in_order_once_the_provider_has_cleared_their_input() { + let clears = std::cell::RefCell::new(Vec::new()); + let reset_input = || { + let (completed, result) = mpsc::sync_channel(1); + clears.borrow_mut().push(completed); + Ok(result) + }; + let mut resets = InputResets::default(); let mut output = Vec::new(); - set_spokesperson_input_muted( - 1, - true, - &mut muted, - || { - reset_count += 1; - Ok(()) - }, - &mut output, - ) - .unwrap(); - reset_spokesperson_input( - 2, - || { - reset_count += 1; - Ok(()) - }, - &mut output, - ) - .unwrap(); + resets + .apply( + SessionMessage::InputMuteApplied { + id: 1, + active: true, + }, + true, + reset_input, + &mut output, + ) + .unwrap(); + resets + .apply( + SessionMessage::InputResetApplied { id: 2 }, + true, + reset_input, + &mut output, + ) + .unwrap(); + resets + .apply( + SessionMessage::InputMuteApplied { + id: 3, + active: false, + }, + false, + reset_input, + &mut output, + ) + .unwrap(); + // The reset asked for during the first clear gets a clear of its own, at once. + resets.poll(&mut output).unwrap(); + assert_eq!(clears.borrow().len(), 2); + assert!(output.is_empty()); + clears.borrow()[0].send(Ok(())).unwrap(); + resets.poll(&mut output).unwrap(); + assert!(output.is_empty()); + clears.borrow()[1].send(Ok(())).unwrap(); + resets.poll(&mut output).unwrap(); + assert!(resets.idle()); + assert_eq!( + messages(&output), + [ + json!({"type":"input_mute_applied","id":1,"active":true}), + json!({"type":"input_reset_applied","id":2}), + json!({"type":"input_mute_applied","id":3,"active":false}), + ] + ); + output.clear(); + resets + .apply( + SessionMessage::InputMuteApplied { + id: 4, + active: false, + }, + false, + reset_input, + &mut output, + ) + .unwrap(); + assert_eq!(clears.borrow().len(), 2); + assert_eq!( + messages(&output), + [json!({"type":"input_mute_applied","id":4,"active":false})] + ); + + resets + .apply( + SessionMessage::InputResetApplied { id: 5 }, + true, + reset_input, + &mut output, + ) + .unwrap(); + clears.borrow()[2] + .send(Err("provider refused".into())) + .unwrap(); + assert_eq!(resets.poll(&mut output).unwrap_err(), "provider refused"); + } + + #[test] + fn spokesperson_input_policy_is_nonfatal_revisioned_and_gates_pcm() { + let mut output = Vec::new(); let slot = InputDuringTtsSlot::new(InputDuringTtsPolicy::AllowBargeIn); set_spokesperson_input_policy( 3, @@ -8966,8 +9148,6 @@ mod tests { set_spokesperson_input_policy(4, 1, InputDuringTtsPolicy::AllowBargeIn, &slot, &mut output) .unwrap(); - assert!(muted); - assert_eq!(reset_count, 2); assert!(!spokesperson_pcm_allowed( false, true, @@ -8984,15 +9164,10 @@ mod tests { slot.snapshot().unwrap() )); let messages = messages(&output); - assert_eq!( - messages[0], - json!({"type":"input_mute_applied","id":1,"active":true}) - ); - assert_eq!(messages[1], json!({"type":"input_reset_applied","id":2})); - assert_eq!(messages[2]["outcome"], "applied"); - assert_eq!(messages[2]["snapshot"]["revision"], 2); - assert_eq!(messages[3]["outcome"], "rejected"); - assert_eq!(messages[3]["snapshot"]["revision"], 2); + assert_eq!(messages[0]["outcome"], "applied"); + assert_eq!(messages[0]["snapshot"]["revision"], 2); + assert_eq!(messages[1]["outcome"], "rejected"); + assert_eq!(messages[1]["snapshot"]["revision"], 2); } #[test] @@ -9117,6 +9292,7 @@ mod tests { text: "answer after the user".into(), resolved_handoff_ids: Vec::new(), voice: None, + relay: false, }, false, 1, @@ -9130,6 +9306,23 @@ mod tests { assert_eq!(gate.take_ready(false, 0).map(|request| request.id), Some(7)); } + #[test] + fn audio_for_a_playback_worker_that_stopped_waits_for_its_result() { + let (playback, _controls) = live_playback_fixture(None); + let (sender, receiver) = mpsc::sync_channel(1); + drop(receiver); + let active = Some(LivePlayback { sender, ..playback }); + let mut response = LiveResponse::new(None, Some(3)); + response.queue_audio(vec![0.25; 32], 0).unwrap(); + mark_live_response_server_finished(&mut response); + let mut responses = HashMap::from([("response-a".into(), response)]); + + // The worker sent the result that settles this reply before it stopped taking audio. + flush_active_live_playback(&active, &mut responses).unwrap(); + + assert!(responses["response-a"].pending_audio.is_empty()); + } + #[test] fn response_done_finishes_playback_without_a_separate_audio_done() { let (playback, _controls) = live_playback_fixture(None); @@ -9559,6 +9752,7 @@ mod tests { resolved_handoff_ids: Vec::new(), voice: Some(voice.into()), language: None, + relay: false, }) }; let next = || { @@ -10666,18 +10860,12 @@ mod tests { parse(&all) }; assert!(!expert(&["--tts-backend", "openai"]).unwrap().expert_tts); - assert!( - !expert(&["--tts-backend", "openai", "--expert-voice", "spokesperson"]) - .unwrap() - .expert_tts - ); let own = expert(&[ "--tts-backend", "openai", "--rate", "2.0", - "--expert-voice", - "tts", + "--allow-direct-agent-speech", "--tts-url", "http://127.0.0.1:18870/v1/audio/speech", ]) @@ -10703,8 +10891,7 @@ mod tests { let chosen = expert(&[ "--tts-backend", "openai", - "--expert-voice", - "tts", + "--allow-direct-agent-speech", "--spokesperson-voice", "cedar", "--spokesperson-rate", @@ -10714,13 +10901,17 @@ mod tests { apply_spokesperson_startup_settings(&chosen, &mut realtime).unwrap(); assert_eq!((realtime.voice(), realtime.speed()), ("cedar", 1.25)); for (extra, error) in [ - (&["--spokesperson-voice", "cedar"][..], "--expert-voice tts"), + (&["--spokesperson-voice", "cedar"][..], DIRECT_AGENT_SPEECH), ( - &["--expert-voice", "tts", "--spokesperson-voice", "nobody"], + &[ + "--allow-direct-agent-speech", + "--spokesperson-voice", + "nobody", + ], "no realtime voice named nobody", ), ( - &["--expert-voice", "tts", "--spokesperson-rate", "2"], + &["--allow-direct-agent-speech", "--spokesperson-rate", "2"], "between 0.25 and 1.5", ), ] { @@ -10729,20 +10920,20 @@ mod tests { } let read_aloud = expert(&["--tts-backend", "openai", "--rate", "2.0"]).unwrap(); assert!(apply_spokesperson_startup_settings(&read_aloud, &mut realtime).is_err()); - assert!(expert(&["--expert-voice", "loud"]) - .unwrap_err() - .contains("tts or spokesperson")); - assert!(parse(&["--tts-backend", "openai", "--expert-voice", "tts"]) - .unwrap_err() - .contains("--mode expert-spokesperson")); + assert!( + parse(&["--tts-backend", "openai", "--allow-direct-agent-speech"]) + .unwrap_err() + .contains("--mode expert-spokesperson") + ); assert_eq!( saved_settings::persistable_arguments(&args(&[ "--mode", "expert-spokesperson", - "--expert-voice", - "tts" + "--allow-direct-agent-speech", + "--voice", + "Aaron" ])), - args(&["--mode", "expert-spokesperson"]) + args(&["--mode", "expert-spokesperson", "--voice", "Aaron"]) ); } @@ -11385,6 +11576,18 @@ mod tests { assert!( parse_pcm_output_fd(&args(&["berd-call", "session", "--pcm-output-fd", "2"])).is_err() ); + // As the host spawns it, after a flag that takes no value. + assert_eq!( + parse_pcm_output_fd(&args(&[ + "berd-call", + "session", + DIRECT_AGENT_SPEECH, + "--pcm-output-fd", + "9" + ])) + .unwrap(), + 9 + ); assert!(parse_pcm_output_fd(&args(&[ "berd-call", "session", @@ -11550,6 +11753,7 @@ mod tests { resolved_handoff_ids: vec![" ".into()], voice: None, language: None, + relay: false, }; assert_eq!( validate_request(empty).unwrap_err(), @@ -12396,7 +12600,6 @@ mod tests { assert!(parsed.non_blocking); for (flags, live) in [ (&["--stream"][..], false), - (&["--stream", "handoffs"], false), (&["--stream", "live", "--non-blocking"], true), ] { let parsed = start(flags).unwrap(); @@ -12491,10 +12694,14 @@ mod tests { .iter() .any(|flag| flag.starts_with("--spokesperson"))); assert!(conventional.saved.unwrap().1.arguments.starts_with(&chosen)); - let own = start(&["--mode", "expert-spokesperson", "--expert-voice", "tts"]); + let own = start(&[ + "--mode", + "expert-spokesperson", + "--allow-direct-agent-speech", + ]); assert!(own .session_arguments - .ends_with(&args(&["--expert-voice", "tts"]))); + .ends_with(&args(&["--allow-direct-agent-speech"]))); assert!(own .session_arguments .windows(2) @@ -12751,6 +12958,34 @@ mod tests { text: "hello".into(), } ); + assert_eq!( + parse_message_spokesperson_args(&args(&[ + "berd-call", + "message-spokesperson", + "--port", + "5300", + "--re", + "4", + "--resolves", + "handoff-1", + "Tell them it's fixed." + ])) + .unwrap(), + SpeakOptions { + port: 5300, + acknowledgement: Some(4), + resolved_handoff_ids: vec!["handoff-1".into()], + voice: None, + language: None, + text: "Tell them it's fixed.".into(), + } + ); + for extra in [&["--voice", "Nora"][..], &[]] { + let mut given = args(&["berd-call", "message-spokesperson"]); + given.extend(args(extra)); + given.push("hello".into()); + assert!(parse_message_spokesperson_args(&given).is_err()); + } assert!(parse_speak_control_args(&args(&[ "berd-call", "speak", diff --git a/src-tauri/crates/berd-call/src/openai_realtime_protocol.rs b/src-tauri/crates/berd-call/src/openai_realtime_protocol.rs index 570299a09..7a68cef77 100644 --- a/src-tauri/crates/berd-call/src/openai_realtime_protocol.rs +++ b/src-tauri/crates/berd-call/src/openai_realtime_protocol.rs @@ -1287,6 +1287,7 @@ pub struct RealtimeExpertSpokespersonSession { responses: RealtimeResponseCoordinator, conversation: ExpertSpokespersonCore, open_handoffs: HashMap, + tracks_handoffs: bool, call_scope: String, pending_expert_events: Vec, } @@ -1387,11 +1388,21 @@ impl RealtimeExpertSpokespersonSession { responses: RealtimeResponseCoordinator::default(), conversation: ExpertSpokespersonCore::new(initial_cursor), open_handoffs: HashMap::new(), + tracks_handoffs: true, call_scope: call_scope.into(), pending_expert_events: Vec::new(), } } + /// A session whose handoffs reach the Expert but are never held open: + /// nothing waits on them, so nothing reminds, resolves or keeps them. + pub fn without_handoff_tracking(self) -> Self { + Self { + tracks_handoffs: false, + ..self + } + } + pub fn handle_provider_event( &mut self, event: &Value, @@ -1726,14 +1737,16 @@ impl RealtimeExpertSpokespersonSession { let handoff_id = require_non_empty(handoff_id, "handoff id")?; let message = require_non_empty(message, "handoff message")?; let expert_message = expert_handoff_message(&handoff_id, cursor, &message); - self.open_handoffs.insert( - handoff_id, - RealtimeOpenHandoff { - message, - reminder_attempts: 0, - resolving: false, - }, - ); + if self.tracks_handoffs { + self.open_handoffs.insert( + handoff_id, + RealtimeOpenHandoff { + message, + reminder_attempts: 0, + resolving: false, + }, + ); + } Ok(expert_message) } @@ -1783,16 +1796,6 @@ impl RealtimeExpertSpokespersonSession { Ok(()) } - /// Leaves handoffs open for another reply once the one meant to answer - /// them went unheard. - pub fn release_handoffs(&mut self, handoff_ids: &[String]) { - for handoff_id in handoff_ids { - if let Some(handoff) = self.open_handoffs.get_mut(handoff_id) { - handoff.resolving = false; - } - } - } - pub fn dismiss_handoffs(&mut self, handoff_ids: &[String]) -> Result<(), String> { let unknown = self.unknown_handoff_ids(handoff_ids); if !unknown.is_empty() { @@ -3093,6 +3096,24 @@ mod tests { ); } + #[test] + fn untracked_handoffs_reach_the_expert_and_stay_closed() { + let mut session = + RealtimeExpertSpokespersonSession::new(0, "test-call").without_handoff_tracking(); + let (_, delivery) = session + .record_live_event_with_delivery(LiveSideEvent::Handoff { + call_id: "call-1".into(), + message: "First request".into(), + }) + .unwrap(); + assert_eq!(delivery.unwrap().handoff_ids, ["handoff-test-call-1"]); + assert!(!session.has_unresolved_handoff()); + assert_eq!( + session.complete_expert_turn(&[], 3), + RealtimeHandoffReminder::None + ); + } + #[test] fn native_session_records_every_semantic_turn_for_replacement() { let mut session = RealtimeExpertSpokespersonSession::new(0, "test-call"); diff --git a/src-tauri/crates/berd-call/src/openai_spokesperson.rs b/src-tauri/crates/berd-call/src/openai_spokesperson.rs index ba57624f6..2c6c62737 100644 --- a/src-tauri/crates/berd-call/src/openai_spokesperson.rs +++ b/src-tauri/crates/berd-call/src/openai_spokesperson.rs @@ -226,7 +226,7 @@ pub enum SpokespersonResponseStatus { pub struct OpenAiSpokespersonRuntime { commands: mpsc::UnboundedSender, - audio: mpsc::Sender>, + audio: mpsc::Sender, worker: Option>, } @@ -367,8 +367,10 @@ impl OpenAiSpokespersonRuntime { command => command, }; match command { - SpokespersonCommand::InputPcm48Khz(samples) => { - self.audio.try_send(samples).map_err(|error| match error { + // Input and the clears that discard it share one queue, so they stay in order. + command @ (SpokespersonCommand::InputPcm48Khz(_) + | SpokespersonCommand::ResetInput { .. }) => { + self.audio.try_send(command).map_err(|error| match error { mpsc::error::TrySendError::Full(_) => "Spokesperson input queue is full".into(), mpsc::error::TrySendError::Closed(_) => "Spokesperson runtime is closed".into(), }) @@ -380,12 +382,11 @@ impl OpenAiSpokespersonRuntime { } } - pub fn reset_input(&self) -> Result<(), String> { + /// Clears the provider's input buffer of earlier input but not later input; the result arrives once the provider confirms. + pub fn reset_input(&self) -> Result>, String> { let (completed, result) = std::sync::mpsc::sync_channel(1); self.send(SpokespersonCommand::ResetInput { completed })?; - result - .recv_timeout(std::time::Duration::from_secs(5)) - .map_err(|_| "Spokesperson input reset timed out".to_string())? + Ok(result) } pub fn abort_input_cutover(&self) -> Result<(), String> { @@ -425,7 +426,7 @@ impl Drop for OpenAiSpokespersonRuntime { fn reap_spokesperson_worker( worker: thread::JoinHandle<()>, - audio_lifetime: mpsc::Sender>, + audio_lifetime: mpsc::Sender, ) { let _ = thread::Builder::new() .name("berd-call-spokesperson-reaper".into()) @@ -445,10 +446,21 @@ async fn run( run_inner(config, commands, audio_rx, events, false).await } +/// The next command, or `None` once the runtime is shut down. +async fn next_command( + commands: &mut mpsc::UnboundedReceiver, + audio: &mut mpsc::Receiver, +) -> Result, String> { + tokio::select! { + command = commands.recv() => Ok(command), + command = audio.recv() => command.map(Some).ok_or_else(|| "Spokesperson input queue is closed".into()), + } +} + async fn run_inner( mut config: OpenAiSpokespersonConfig, mut commands: mpsc::UnboundedReceiver, - mut audio: mpsc::Receiver>, + mut audio: mpsc::Receiver, events: &std::sync::mpsc::Sender, forward_provider_events: bool, ) -> Result<(), String> { @@ -488,7 +500,8 @@ async fn run_inner( let mut cancellation_events = HashMap::::new(); let mut pending_truncations = HashMap::<(String, u64), PendingTruncation>::new(); let mut pending_input_cutover: Option = None; - let mut pending_input_reset: Option = None; + // Clears in the order sent; the provider confirms them in that order. + let mut pending_input_resets = VecDeque::::new(); let mut started_input_items = HashSet::::new(); let mut committed_input_items = HashSet::::new(); let mut seed_turns = VecDeque::from(std::mem::take(&mut config.semantic_transcript)); @@ -524,7 +537,7 @@ async fn run_inner( let cutover_deadline = pending_input_cutover .as_ref() .map(|cutover| cutover.deadline); - let reset_deadline = pending_input_reset.as_ref().map(|reset| reset.deadline); + let reset_deadline = pending_input_resets.front().map(|reset| reset.deadline); tokio::select! { _ = async { match shutdown_not_before { @@ -549,11 +562,11 @@ async fn run_inner( None => std::future::pending().await, } }, if reset_deadline.is_some() => { - if pending_input_reset - .as_ref() + if pending_input_resets + .front() .is_some_and(|reset| tokio::time::Instant::now() >= reset.deadline) { - let reset = pending_input_reset.take().expect("expired input reset"); + let reset = pending_input_resets.pop_front().expect("expired input reset"); let _ = reset.completed.send(Err("Spokesperson input reset timed out".into())); return Err("Spokesperson input reset timed out; provider input state is indeterminate".into()); } @@ -590,18 +603,8 @@ async fn run_inner( return Err("Spokesperson output truncation timed out; server context is indeterminate".into()); } } - samples = audio.recv(), if shutdown_deadline.is_none() => { - let Some(samples) = samples else { - return Err("Spokesperson input queue is closed".into()); - }; - let pcm = downsample_pcm16(&samples); - send_json(&mut socket, serde_json::json!({ - "type": "input_audio_buffer.append", - "audio": BASE64.encode(pcm), - })).await?; - } - command = commands.recv(), if shutdown_deadline.is_none() => { - match command { + command = next_command(&mut commands, &mut audio), if shutdown_deadline.is_none() => { + match command? { Some(SpokespersonCommand::Provider(event)) => { send_json(&mut socket, event).await?; } @@ -613,7 +616,7 @@ async fn run_inner( })).await?; } Some(SpokespersonCommand::ResetInput { completed }) => { - if pending_input_cutover.is_some() || pending_input_reset.is_some() { + if pending_input_cutover.is_some() { let _ = completed.send(Err( "another Spokesperson input clear is in progress".into(), )); @@ -625,7 +628,7 @@ async fn run_inner( "event_id": event_id, "type": "input_audio_buffer.clear", })).await?; - pending_input_reset = Some(PendingInputReset { + pending_input_resets.push_back(PendingInputReset { event_id, deadline: tokio::time::Instant::now() + CONTROL_ACK_TIMEOUT, completed, @@ -646,7 +649,7 @@ async fn run_inner( } } Some(SpokespersonCommand::BeginInputCutover { request_id }) => { - if pending_input_cutover.is_some() || pending_input_reset.is_some() { + if pending_input_cutover.is_some() || !pending_input_resets.is_empty() { return Err("Spokesperson input cutover was requested twice".into()); } let event_id = format!("berd-cutover-{next_control_event_id}"); @@ -719,7 +722,8 @@ async fn run_inner( Some(SpokespersonCommand::Shutdown) | None => { commands.close(); audio.close(); - while let Ok(samples) = audio.try_recv() { + while let Ok(command) = audio.try_recv() { + let SpokespersonCommand::InputPcm48Khz(samples) = command else { continue }; let pcm = downsample_pcm16(&samples); send_json(&mut socket, serde_json::json!({ "type": "input_audio_buffer.append", @@ -926,7 +930,7 @@ async fn run_inner( &committed_input_items, events, )?; - } else if let Some(reset) = pending_input_reset.take() { + } else if let Some(reset) = pending_input_resets.pop_front() { let _ = reset.completed.send(Ok(())); } } @@ -1039,11 +1043,9 @@ async fn run_inner( } "error" => { let message = value.pointer("/error/message").and_then(|value| value.as_str()).unwrap_or("OpenAI Realtime failed").to_string(); - if pending_input_reset.as_ref().is_some_and(|reset| { - value.pointer("/error/event_id").and_then(|value| value.as_str()) - == Some(reset.event_id.as_str()) - }) { - let reset = pending_input_reset.take().expect("matched input reset"); + let event_id = value.pointer("/error/event_id").and_then(|value| value.as_str()); + if let Some(index) = pending_input_resets.iter().position(|reset| Some(reset.event_id.as_str()) == event_id) { + let reset = pending_input_resets.remove(index).expect("matched input reset"); let _ = reset.completed.send(Err(message)); } else if pending_input_cutover.as_ref().is_some_and(|cutover| { value.pointer("/error/event_id").and_then(|value| value.as_str()) @@ -1942,6 +1944,93 @@ mod tests { server.await.unwrap(); } + #[tokio::test(flavor = "multi_thread")] + async fn input_reset_clears_input_sent_before_it_but_not_after() { + const FRAMES: usize = 10; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("ws://{}/", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut socket = accept_hdr_async(stream, require_test_authorization) + .await + .unwrap(); + let update = receive_json(&mut socket).await; + acknowledge_initial_session(&mut socket, &update, "test-model").await; + let mut types = Vec::new(); + for _ in 0..=2 * FRAMES { + types.push(receive_json(&mut socket).await["type"].clone()); + } + send_json(&mut socket, json!({"type":"input_audio_buffer.cleared"})).await; + let _ = socket.next().await; + types + }); + let (runtime, events) = + OpenAiSpokespersonRuntime::spawn(test_config(endpoint, "test-voice", 1.0, Vec::new())) + .unwrap(); + assert!(matches!( + events.recv_timeout(Duration::from_secs(2)).unwrap(), + SpokespersonEvent::Ready + )); + let pcm = || SpokespersonCommand::InputPcm48Khz(vec![0.5; 960]); + (0..FRAMES).for_each(|_| runtime.send(pcm()).unwrap()); + let reset = runtime.reset_input().unwrap(); + (0..FRAMES).for_each(|_| runtime.send(pcm()).unwrap()); + tokio::task::spawn_blocking(move || reset.recv_timeout(Duration::from_secs(2))) + .await + .unwrap() + .unwrap() + .unwrap(); + runtime.finish().unwrap(); + let append = json!("input_audio_buffer.append"); + let mut expected = vec![append.clone(); 2 * FRAMES]; + expected.insert(FRAMES, json!("input_audio_buffer.clear")); + assert_eq!(server.await.unwrap(), expected); + } + + #[tokio::test(flavor = "multi_thread")] + async fn input_resets_sent_together_are_each_answered_in_turn() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("ws://{}/", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut socket = accept_hdr_async(stream, require_test_authorization) + .await + .unwrap(); + let update = receive_json(&mut socket).await; + acknowledge_initial_session(&mut socket, &update, "test-model").await; + let first = receive_json(&mut socket).await; + let second = receive_json(&mut socket).await; + assert_eq!(first["type"], "input_audio_buffer.clear"); + assert_eq!(second["type"], "input_audio_buffer.clear"); + send_json( + &mut socket, + json!({"type":"error","error":{"message":"refused","event_id":second["event_id"]}}), + ) + .await; + send_json(&mut socket, json!({"type":"input_audio_buffer.cleared"})).await; + let _ = socket.next().await; + }); + let (runtime, events) = + OpenAiSpokespersonRuntime::spawn(test_config(endpoint, "test-voice", 1.0, Vec::new())) + .unwrap(); + assert!(matches!( + events.recv_timeout(Duration::from_secs(2)).unwrap(), + SpokespersonEvent::Ready + )); + let first = runtime.reset_input().unwrap(); + let second = runtime.reset_input().unwrap(); + let wait = |reset: std::sync::mpsc::Receiver>| { + reset.recv_timeout(Duration::from_secs(2)).unwrap() + }; + let (first, second) = tokio::task::spawn_blocking(move || (wait(first), wait(second))) + .await + .unwrap(); + assert_eq!(first, Ok(())); + assert_eq!(second, Err("refused".into())); + runtime.finish().unwrap(); + server.await.unwrap(); + } + #[test] fn output_truncation_timeout_is_bounded() { let now = tokio::time::Instant::now(); diff --git a/src-tauri/crates/berd-call/src/protocol.rs b/src-tauri/crates/berd-call/src/protocol.rs index 02e58c261..cf6d578d5 100644 --- a/src-tauri/crates/berd-call/src/protocol.rs +++ b/src-tauri/crates/berd-call/src/protocol.rs @@ -56,6 +56,9 @@ pub enum SessionRequest { voice: Option, #[serde(default, skip_serializing_if = "Option::is_none")] language: Option, + /// The Spokesperson says it, even in a call where the Expert has its own voice. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + relay: bool, }, OutputReady { id: u64, @@ -401,6 +404,7 @@ mod tests { resolved_handoff_ids: Vec::new(), voice: None, language: None, + relay: false, } ); assert_eq!( diff --git a/src-tauri/crates/berd-call/src/saved_settings.rs b/src-tauri/crates/berd-call/src/saved_settings.rs index e9ff2f081..cc83d2396 100644 --- a/src-tauri/crates/berd-call/src/saved_settings.rs +++ b/src-tauri/crates/berd-call/src/saved_settings.rs @@ -128,12 +128,17 @@ pub(crate) fn merge_arguments(saved: &[String], explicit: &[String]) -> Vec Vec { + let arguments: Vec<_> = arguments + .iter() + .filter(|argument| *argument != crate::DIRECT_AGENT_SPEECH) + .cloned() + .collect(); arguments .chunks_exact(2) .filter(|pair| { !matches!( pair[0].as_str(), - "--realtime-url" | "--stt-url" | "--tts-url" | "--expert-voice" + "--realtime-url" | "--stt-url" | "--tts-url" ) }) .flatten() diff --git a/src-tauri/crates/berd-call/src/session_audio.rs b/src-tauri/crates/berd-call/src/session_audio.rs index 0368d6a9d..7f2aabbc6 100644 --- a/src-tauri/crates/berd-call/src/session_audio.rs +++ b/src-tauri/crates/berd-call/src/session_audio.rs @@ -17,12 +17,16 @@ pub const AUDIO_END_KIND: u8 = 3; pub const AUDIO_CANCEL_KIND: u8 = 4; pub const AUDIO_FRAME_HEADER_BYTES: usize = 8; pub const MAX_AUDIO_CHUNK_FRAMES: usize = 4096; -const MIN_ACCEPTED_AUDIO_RUNWAY_MS: f64 = 400.0; +/// Audio the host may hold beyond what it reports played. It reports a chunk played only once the output device has played it, +/// up to a few hundred milliseconds after it is heard on Bluetooth headphones, so this must outlast that delay or playback runs dry. +const MIN_ACCEPTED_AUDIO_RUNWAY_MS: f64 = 1_000.0; const MAX_ACCEPTED_NOT_PLAYED_CHUNKS: usize = 64; const AUDIO_PIPE_WRITE_TIMEOUT: Duration = Duration::from_secs(2); const AUDIO_OPERATION_TIMEOUT: Duration = Duration::from_secs(3); pub const AUDIO_CANCELLED: &str = "remote PCM output was cancelled"; +/// The host's player stopped, as when the output device changes under it; the host has ended that speech. +pub const AUDIO_HOST_FAILED: &str = "host audio output failed"; #[derive(Clone, Debug, PartialEq)] pub enum AudioHostAck { @@ -619,7 +623,7 @@ impl RemotePcmAudioOutput { Err(state .failure .clone() - .unwrap_or_else(|| "host audio output failed".into())) + .unwrap_or_else(|| AUDIO_HOST_FAILED.into())) } else { Ok(()) } @@ -666,7 +670,7 @@ impl RemotePcmAudioOutput { return Err(state .failure .clone() - .unwrap_or_else(|| "host audio output failed".into())); + .unwrap_or_else(|| AUDIO_HOST_FAILED.into())); } Phase::Cancelling => false, Phase::WaitingBegin @@ -710,7 +714,7 @@ impl RemotePcmAudioOutput { return Err(state .failure .clone() - .unwrap_or_else(|| "host audio output failed".into())) + .unwrap_or_else(|| AUDIO_HOST_FAILED.into())) } Phase::Drained => return Err("remote PCM output is already drained".into()), _ => {} @@ -759,7 +763,7 @@ impl RemotePcmAudioOutput { return Err(state .failure .clone() - .unwrap_or_else(|| "host audio output failed".into())); + .unwrap_or_else(|| AUDIO_HOST_FAILED.into())); } if state.suspension == SuspensionPhase::Suspended && state.suspension_requested { while state.suspension_requested && self.active.load(Ordering::SeqCst) { @@ -889,7 +893,7 @@ impl PcmAudioOutput for RemotePcmAudioOutput { Err(state .failure .clone() - .unwrap_or_else(|| "host audio output failed".into())) + .unwrap_or_else(|| AUDIO_HOST_FAILED.into())) } else { Ok(()) } @@ -912,7 +916,7 @@ fn accepted_audio_runway_frames(spec: TtsPcmSpec) -> u64 { } fn public_host_failure(_message: String) -> String { - "host audio output failed".into() + AUDIO_HOST_FAILED.into() } #[cfg(test)] @@ -1040,8 +1044,8 @@ mod tests { let (output, mut host) = fixture(); start(&output, &mut host); let current = Arc::clone(&output); - let worker = thread::spawn(move || current.write(&vec![0.25; 4096 * 4])); - for sequence in 1..=3 { + let worker = thread::spawn(move || current.write(&vec![0.25; 4096 * 7])); + for sequence in 1..=6 { let (kind, _) = read_record(&mut host); assert_eq!(kind, AUDIO_CHUNK_KIND); let started = output @@ -1062,7 +1066,7 @@ mod tests { let (kind, _) = read_record(&mut host); assert_eq!(kind, AUDIO_CHUNK_KIND); output - .handle_ack(AudioHostAck::ChunkAccepted { sequence: 4 }) + .handle_ack(AudioHostAck::ChunkAccepted { sequence: 7 }) .unwrap(); worker.join().unwrap().unwrap(); } @@ -1525,14 +1529,14 @@ mod tests { sample_rate: 48_000, playback_rate: 1.5, }, - 8, + 18, ), ( TtsPcmSpec { sample_rate: 24_000, playback_rate: 2.0, }, - 5, + 12, ), ] { let (output, mut host) = @@ -1579,6 +1583,86 @@ mod tests { worker.join().unwrap().unwrap(); } + /// The silence, in milliseconds, a host playing in real time leaves in 3 s of audio written at once, when it reports each chunk played `lag` after it is heard, as the output device does. + fn silence_when_played_reports_lag(lag: Duration) -> f64 { + let (output, mut host) = fixture(); + start(&output, &mut host); + // When each chunk is heard, and its frames. + let heard = Arc::new(Mutex::new(Vec::<(Instant, Instant, u64)>::new())); + let writing = Arc::new(AtomicBool::new(true)); + let reporter = { + let (output, heard, writing) = ( + Arc::clone(&output), + Arc::clone(&heard), + Arc::clone(&writing), + ); + thread::spawn(move || { + while writing.load(Ordering::SeqCst) { + let now = Instant::now(); + let done: u64 = heard + .lock() + .unwrap() + .iter() + .filter(|(_, end, _)| *end + lag <= now) + .map(|(_, _, frames)| frames) + .sum(); + // Less the host's delivery safety, 100 ms. + let played = done.saturating_sub(2_400); + if played > output.played_frames() { + output + .handle_ack(AudioHostAck::Played { + played_frames: played, + }) + .unwrap(); + } + thread::sleep(Duration::from_millis(1)); + } + }) + }; + let writer = { + let output = Arc::clone(&output); + thread::spawn(move || { + output.write(&vec![0.25; 72_000])?; + output.finish_writes() + }) + }; + loop { + let (kind, payload) = read_record(&mut host); + if kind == AUDIO_END_KIND { + break; + } + let frames = (payload.len() as u64 - 16) / 4; + let mut heard = heard.lock().unwrap(); + let start = heard + .last() + .map_or_else(Instant::now, |(_, end, _)| (*end).max(Instant::now())); + heard.push(( + start, + start + Duration::from_micros(frames * 1_000 / 24), + frames, + )); + drop(heard); + let sequence = u64::from_le_bytes(payload[8..16].try_into().unwrap()); + output + .handle_ack(AudioHostAck::ChunkAccepted { sequence }) + .unwrap(); + } + writer.join().unwrap().unwrap(); + writing.store(false, Ordering::SeqCst); + reporter.join().unwrap(); + let heard = heard.lock().unwrap(); + heard + .windows(2) + .map(|pair| pair[1].0.duration_since(pair[0].1).as_secs_f64() * 1_000.0) + .sum() + } + + #[test] + fn playback_outlasts_bluetooth_played_reports() { + let silence = silence_when_played_reports_lag(Duration::from_millis(300)); + assert!(silence < 20.0, "{silence:.0} ms of silence"); + } + #[test] fn empty_output_fails_before_emitting_audio_end() { let (output, mut host) = fixture(); diff --git a/src-tauri/crates/berd-call/tests/session_protocol.rs b/src-tauri/crates/berd-call/tests/session_protocol.rs index dd2da7a78..964da9e72 100644 --- a/src-tauri/crates/berd-call/tests/session_protocol.rs +++ b/src-tauri/crates/berd-call/tests/session_protocol.rs @@ -65,12 +65,18 @@ impl ExpertSpokespersonTestSession { played_frame_limit, played_ready, cancellation_gate, + false, &[], ) } + /// A session whose host player stops once it has played this much of the first speech, as when the output device changes under it. + fn start_with_failing_audio(endpoint: String, played_frames: u64) -> Self { + Self::launch(endpoint, None, Some(played_frames), None, None, true, &[]) + } + fn start_with_args(endpoint: String, args: &[&str]) -> Self { - Self::launch(endpoint, None, None, None, None, args) + Self::launch(endpoint, None, None, None, None, false, args) } fn launch( @@ -79,6 +85,7 @@ impl ExpertSpokespersonTestSession { played_frame_limit: Option, played_ready: Option>, cancellation_gate: Option, + fail_at_limit: bool, args: &[&str], ) -> Self { let (mut command, _pcm, audio_host) = session_command(); @@ -119,6 +126,7 @@ impl ExpertSpokespersonTestSession { played_frame_limit, played_ready, cancellation_gate, + fail_at_limit, ); let mut session = Self { child, @@ -328,7 +336,7 @@ fn spawn_audio_host( reader: UnixStream, stdin: Arc>, ) -> std::thread::JoinHandle<()> { - spawn_audio_host_with_played_limit(reader, stdin, None, None, None) + spawn_audio_host_with_played_limit(reader, stdin, None, None, None, false) } fn spawn_audio_host_with_played_limit( @@ -337,9 +345,12 @@ fn spawn_audio_host_with_played_limit( played_frame_limit: Option, mut played_ready: Option>, mut cancellation_gate: Option, + mut fail_at_limit: bool, ) -> std::thread::JoinHandle<()> { std::thread::spawn(move || { let mut current = None::<(u64, u64, u64)>; + // The speech whose player failed, and what it played: like the real host, it ignores what the session sent before hearing. + let mut failed = None::<(u64, u64)>; loop { let mut header = [0_u8; 8]; match reader.read_exact(&mut header) { @@ -362,6 +373,9 @@ fn spawn_audio_host_with_played_limit( 2 => { assert!(payload.len() >= 20); let speech_id = u64::from_le_bytes(payload[..8].try_into().unwrap()); + if failed.is_some_and(|(id, _)| id == speech_id) { + continue; + } let sequence = u64::from_le_bytes(payload[8..16].try_into().unwrap()); let frames = u64::try_from((payload.len() - 16) / 4).unwrap(); let state = current.as_mut().expect("chunk follows begin"); @@ -379,6 +393,16 @@ fn spawn_audio_host_with_played_limit( &mut *writer, &json!({"type":"audio_played","speech_id":speech_id,"played_frames":played_frame_limit.map_or(state.2, |limit| state.2.min(limit))}), ); + if reached_limit && fail_at_limit { + fail_at_limit = false; + let played_frames = played_frame_limit.unwrap(); + failed = Some((speech_id, played_frames)); + current = None; + write_session_json( + &mut *writer, + &json!({"type":"audio_failed","speech_id":speech_id,"played_frames":played_frames,"message":"PCM audio output stopped unexpectedly"}), + ); + } writer.flush().unwrap(); if reached_limit { if let Some(ready) = played_ready.take() { @@ -390,6 +414,9 @@ fn spawn_audio_host_with_played_limit( 3 => { assert_eq!(payload.len(), 24); let speech_id = u64::from_le_bytes(payload[..8].try_into().unwrap()); + if failed.is_some_and(|(id, _)| id == speech_id) { + continue; + } let sequence = u64::from_le_bytes(payload[8..16].try_into().unwrap()); let frames = u64::from_le_bytes(payload[16..24].try_into().unwrap()); assert_eq!(current, Some((speech_id, sequence, frames))); @@ -406,6 +433,15 @@ fn spawn_audio_host_with_played_limit( 4 => { assert_eq!(payload.len(), 8); let speech_id = u64::from_le_bytes(payload.try_into().unwrap()); + if let Some((_, played_frames)) = failed.filter(|(id, _)| *id == speech_id) { + let mut writer = stdin.lock().unwrap(); + write_session_json( + &mut *writer, + &json!({"type":"audio_cancelled","speech_id":speech_id,"played_frames":played_frames}), + ); + writer.flush().unwrap(); + continue; + } let played_frames = current .take() .filter(|state| state.0 == speech_id) @@ -1175,6 +1211,110 @@ fn one_realtime_response_with_two_audio_parts_completes_without_identity_failure server.join().unwrap(); } +#[test] +fn a_reply_whose_player_stops_ends_where_it_was_heard_and_the_call_goes_on() { + let (endpoint_tx, endpoint_rx) = mpsc::sync_channel(1); + let server = std::thread::spawn(move || { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(async move { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + endpoint_tx + .send(format!("ws://{}/", listener.local_addr().unwrap())) + .unwrap(); + let (stream, _) = listener.accept().await.unwrap(); + let mut socket = accept_async(stream).await.unwrap(); + let update = receive_realtime_json(&mut socket).await; + acknowledge_realtime_session(&mut socket, &update).await; + // Two seconds of audio, of which the host plays a fraction before its player stops; then a short reply. + for (directive, response, bytes) in [("2", "response-cut", 96_000), ("3", "response-next", 4_096)] { + assert_eq!( + receive_realtime_json(&mut socket).await["type"], + "conversation.item.create" + ); + assert_eq!( + receive_realtime_json(&mut socket).await["type"], + "response.create" + ); + send_realtime_json( + &mut socket, + json!({"type":"response.created","response":{"id":response,"metadata":{"berd_expert_directive_id":directive}}}), + ) + .await; + let item = format!("{response}-item"); + for event in [ + json!({"type":"response.output_audio.delta","response_id":response,"item_id":item,"output_index":0,"content_index":0,"delta":BASE64.encode(vec![0_u8; bytes])}), + json!({"type":"response.output_audio.done","response_id":response,"item_id":item,"output_index":0,"content_index":0}), + json!({"type":"response.output_audio_transcript.done","response_id":response,"item_id":item,"output_index":0,"content_index":0,"transcript":"a reply"}), + json!({"type":"response.done","response":{"id":response,"status":"completed"}}), + ] { + send_realtime_json(&mut socket, event).await; + } + if directive == "2" { + // The model learns the user heard the 4,096 frames (170 ms) played before the player stopped. + let truncate = receive_realtime_json(&mut socket).await; + assert_eq!(truncate["type"], "conversation.item.truncate"); + assert_eq!(truncate["item_id"], item); + assert_eq!(truncate["audio_end_ms"], 170); + send_realtime_json( + &mut socket, + json!({"type":"conversation.item.truncated","item_id":item,"content_index":0}), + ) + .await; + } + } + let _ = socket.next().await; + }); + }); + let mut session = + ExpertSpokespersonTestSession::start_with_failing_audio(endpoint_rx.recv().unwrap(), 4_096); + let mut seen = Vec::new(); + let mut until = + |session: &mut ExpertSpokespersonTestSession, what: &str, done: &dyn Fn(&Value) -> bool| { + let deadline = std::time::Instant::now() + Duration::from_secs(5); + loop { + let remaining = deadline + .checked_duration_since(std::time::Instant::now()) + .unwrap_or_else(|| panic!("no {what}: {seen:?}")); + let message = session + .output + .recv_timeout(remaining) + .unwrap_or_else(|error| panic!("no {what} ({error}): {seen:?}")); + assert_ne!(message["type"], "fatal", "unexpected fatal: {message}"); + let found = done(&message); + seen.push(message); + if found { + break; + } + } + }; + let speak = |session: &mut ExpertSpokespersonTestSession, id: u64| { + session.send( + json!({"type":"prepare_speak","id":id,"acknowledgement":null,"text":"say something"}), + ); + let admitted = std::iter::repeat_with(|| session.recv(Duration::from_secs(2))) + .find(|message| message["id"] == id) + .unwrap(); + assert_eq!(admitted["type"], "admitted", "{admitted}"); + session.send(json!({"type":"output_ready","id":id,"speech_id":admitted["speech_id"]})); + }; + speak(&mut session, 2); + until(&mut session, "interruption", &|message| { + message["id"] == 2 && message["type"] == "speech_interrupted" + }); + until(&mut session, "cut transcript", &|message| { + message["type"] == "live_event" && message["origin"] == "spokesperson" + }); + speak(&mut session, 3); + until(&mut session, "next reply", &|message| { + message["id"] == 3 && message["type"] == "speech_completed" + }); + session.shutdown(); + server.join().unwrap(); +} + #[test] fn expert_spokesperson_expiry_recovery_failure_reports_the_specific_terminal() { let (endpoint_tx, endpoint_rx) = mpsc::sync_channel(1); @@ -1590,7 +1730,104 @@ fn expert_spokesperson_voice_change_swaps_atomically_and_flushes_gated_pcm_once( } #[test] -fn user_activity_during_voice_cutover_rolls_back_and_flushes_gated_pcm_once() { +fn user_activity_during_voice_cutover_rolls_back_then_retries_once_idle() { + retries_a_voice_change_the_user_overtook( + &[], + json!({ + "type":"set_tts_settings", + "id":2, + "expected_revision":1, + "settings":{"backend":"openai","model":"test-model","voice":"new-voice","rate":1.0} + }), + ); +} + +#[test] +fn a_spokesperson_rate_change_the_user_overtook_is_retried_beside_the_agents_voice() { + let (speech_url, _speech_requests) = spawn_speech_server(); + retries_a_voice_change_the_user_overtook( + &["--allow-direct-agent-speech", "--tts-url", &speech_url], + json!({ + "type":"set_spokesperson_settings", + "id":2, + "expected_revision":1, + "settings":{"backend":"openai","model":"test-model","voice":"old-voice","rate":1.5} + }), + ); +} + +#[test] +fn a_message_held_for_a_voice_change_is_said_before_the_change_is_retried() { + let (endpoint_tx, endpoint_rx) = mpsc::sync_channel(1); + let (candidate_seen_tx, candidate_seen_rx) = mpsc::sync_channel(1); + let (held_tx, held_rx) = mpsc::sync_channel(1); + let (first_tx, first_rx) = mpsc::sync_channel(1); + std::thread::spawn(move || { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(async move { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + endpoint_tx + .send(format!("ws://{}/", listener.local_addr().unwrap())) + .unwrap(); + let (old_stream, _) = listener.accept().await.unwrap(); + let mut old = accept_async(old_stream).await.unwrap(); + let initial = receive_realtime_json(&mut old).await; + acknowledge_realtime_session(&mut old, &initial).await; + let (candidate_stream, _) = listener.accept().await.unwrap(); + let mut candidate = accept_async(candidate_stream).await.unwrap(); + let update = receive_realtime_json(&mut candidate).await; + candidate_seen_tx.send(()).unwrap(); + tokio::task::spawn_blocking(move || held_rx.recv().unwrap()) + .await + .unwrap(); + acknowledge_realtime_session(&mut candidate, &update).await; + let said = async { + while !receive_realtime_json(&mut old) + .await + .to_string() + .contains("I checked the repository.") + {} + }; + let first = tokio::select! { + () = said => "said", + _ = listener.accept() => "retried", + }; + first_tx.send(first).unwrap(); + while old.next().await.is_some() {} + }); + }); + let mut session = ExpertSpokespersonTestSession::start(endpoint_rx.recv().unwrap()); + session.send(json!({ + "type":"set_tts_settings", + "id":2, + "expected_revision":1, + "settings":{"backend":"openai","model":"test-model","voice":"new-voice","rate":1.0} + })); + candidate_seen_rx + .recv_timeout(Duration::from_secs(2)) + .unwrap(); + // The message waits for the voice change, and the change can't land while the message waits. + session.send(json!({ + "type":"prepare_speak", + "id":3, + "acknowledgement":null, + "text":"I checked the repository.", + "relay":true + })); + session.flush(); + held_tx.send(()).unwrap(); + assert_eq!( + first_rx.recv_timeout(Duration::from_secs(3)).unwrap(), + "said" + ); +} + +/// Starts a call with `args`, makes the Spokesperson change in `request`, and speaks while its session is being built: the change rolls back, then lands once the call is idle. +fn retries_a_voice_change_the_user_overtook(args: &[&str], request: Value) { + let output = request["settings"].clone(); let (endpoint_tx, endpoint_rx) = mpsc::sync_channel(1); let (clear_seen_tx, clear_seen_rx) = mpsc::sync_channel(1); let (release_activity_tx, release_activity_rx) = mpsc::sync_channel(1); @@ -1664,17 +1901,36 @@ fn user_activity_during_voice_cutover_rolls_back_and_flushes_gated_pcm_once() { .is_err()); rollback_seen_tx.send(()).unwrap(); let _ = candidate.next().await; + + // Once the conversation is idle, the change is tried again, with the user's words. + let (retry_stream, _) = listener.accept().await.unwrap(); + let mut retry = accept_async(retry_stream).await.unwrap(); + let retry_update = receive_realtime_json(&mut retry).await; + assert_eq!(retry_update["session"]["audio"]["output"]["voice"], output["voice"]); + assert_eq!(retry_update["session"]["audio"]["output"]["speed"], output["rate"]); + acknowledge_realtime_session(&mut retry, &retry_update).await; + let seeds = tokio::spawn(async move { + while let Some(Ok(Message::Text(text))) = retry.next().await { + let seed: Value = serde_json::from_str(&text).unwrap(); + if seed["type"] == "conversation.item.create" { + send_realtime_json( + &mut retry, + json!({"type":"conversation.item.created","item":{"id":seed["item"]["id"]}}), + ) + .await; + } + } + }); + while receive_realtime_json(&mut old).await["type"] != "input_audio_buffer.clear" {} + send_realtime_json(&mut old, json!({"type":"input_audio_buffer.cleared"})).await; + let _ = old.next().await; + seeds.await.unwrap(); }); }); let endpoint = endpoint_rx.recv().unwrap(); - let mut session = ExpertSpokespersonTestSession::start(endpoint); - session.send(json!({ - "type":"set_tts_settings", - "id":2, - "expected_revision":1, - "settings":{"backend":"openai","model":"test-model","voice":"new-voice","rate":1.0} - })); + let mut session = ExpertSpokespersonTestSession::start_with_args(endpoint, args); + session.send(request.clone()); clear_seen_rx.recv_timeout(Duration::from_secs(2)).unwrap(); session.send_pcm(0.25); session.flush(); @@ -1682,18 +1938,20 @@ fn user_activity_during_voice_cutover_rolls_back_and_flushes_gated_pcm_once() { let deadline = std::time::Instant::now() + Duration::from_secs(3); let mut saw_user = false; - let mut saw_rejection = false; - while !(saw_user && saw_rejection) { + let mut applied = false; + while !(saw_user && applied) { let remaining = deadline .checked_duration_since(std::time::Instant::now()) - .expect("rollback did not publish user input and settings rejection promptly"); + .expect("the retried change did not apply promptly after the user's input"); let message = session.recv(remaining); saw_user |= message["type"] == "live_event"; if message["type"] == "tts_settings_result" { - assert_eq!(message["outcome"], "rejected"); - assert_eq!(message["snapshot"]["revision"], 1); - assert_eq!(message["snapshot"]["voice"], "old-voice"); - saw_rejection = true; + assert!(saw_user, "{message}"); + assert_eq!(message["outcome"], "applied", "{message}"); + assert_eq!(message["snapshot"]["revision"], 2); + assert_eq!(message["snapshot"]["voice"], request["settings"]["voice"]); + assert_eq!(message["snapshot"]["rate"], request["settings"]["rate"]); + applied = true; } } rollback_seen_rx @@ -1703,6 +1961,156 @@ fn user_activity_during_voice_cutover_rolls_back_and_flushes_gated_pcm_once() { server.join().unwrap(); } +type RealtimeSocket = tokio_tungstenite::WebSocketStream; + +/// Accepts the realtime session a Spokesperson voice or speed change builds, checks it asks for `voice` at `speed`, and lets the call move to it from `current`. +async fn cut_over( + listener: &TcpListener, + current: &mut RealtimeSocket, + voice: &str, + speed: f64, +) -> RealtimeSocket { + let (stream, _) = listener.accept().await.unwrap(); + let mut candidate = accept_async(stream).await.unwrap(); + let update = receive_realtime_json(&mut candidate).await; + assert_eq!(update["session"]["audio"]["output"]["voice"], voice); + assert_eq!(update["session"]["audio"]["output"]["speed"], speed); + acknowledge_realtime_session(&mut candidate, &update).await; + while receive_realtime_json(current).await["type"] != "input_audio_buffer.clear" {} + send_realtime_json(current, json!({"type":"input_audio_buffer.cleared"})).await; + candidate +} + +/// Serves a call whose Spokesperson changes speed, then voice, and is then muted. +fn serve_spokesperson_changes() -> (String, std::thread::JoinHandle<()>) { + let (endpoint_tx, endpoint_rx) = mpsc::sync_channel(1); + let server = std::thread::spawn(move || { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(async move { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + endpoint_tx + .send(format!("ws://{}/", listener.local_addr().unwrap())) + .unwrap(); + let (stream, _) = listener.accept().await.unwrap(); + let mut first = accept_async(stream).await.unwrap(); + let initial = receive_realtime_json(&mut first).await; + assert_eq!(initial["session"]["audio"]["output"]["voice"], "old-voice"); + acknowledge_realtime_session(&mut first, &initial).await; + let mut faster = cut_over(&listener, &mut first, "old-voice", 1.5).await; + let mut voiced = cut_over(&listener, &mut faster, "new-voice", 1.5).await; + // Muting clears what the Spokesperson has heard. + let clear = loop { + let request = receive_realtime_json(&mut voiced).await; + if request["type"] == "input_audio_buffer.clear" { + break request; + } + }; + assert!(clear["event_id"] + .as_str() + .unwrap() + .starts_with("berd-reset-")); + send_realtime_json(&mut voiced, json!({"type":"input_audio_buffer.cleared"})).await; + while voiced.next().await.is_some() {} + drop((first, faster)); + }); + }); + (endpoint_rx.recv().unwrap(), server) +} + +/// Sends a settings change on a live call and returns its result. +fn change(session: &mut ExpertSpokespersonTestSession, request: Value) -> Value { + session.send(request); + session.recv(Duration::from_secs(3)) +} + +/// Changes the Spokesperson's speed, then its voice, with `change_type`, then the input policy and mute, checking each lands. +fn change_spokesperson_and_input(session: &mut ExpertSpokespersonTestSession, change_type: &str) { + for (id, voice, revision) in [(2, "old-voice", 2), (3, "new-voice", 3)] { + let result = change( + session, + json!({ + "type":change_type, + "id":id, + "expected_revision":revision - 1, + "settings":{"backend":"openai","model":"test-model","voice":voice,"rate":1.5} + }), + ); + assert_eq!(result["type"], "tts_settings_result", "{result}"); + assert_eq!(result["outcome"], "applied", "{result}"); + assert_eq!(result["snapshot"]["revision"], revision); + assert_eq!(result["snapshot"]["voice"], voice); + assert_eq!(result["snapshot"]["rate"], 1.5); + } + let policy = change( + session, + json!({"type":"set_input_during_tts","id":4,"expected_revision":1,"policy":"suppress_input"}), + ); + assert_eq!(policy["type"], "input_during_tts_result", "{policy}"); + assert_eq!(policy["outcome"], "applied"); + assert_eq!( + policy["snapshot"], + json!({"revision":2,"policy":"suppress_input"}) + ); + for (id, active) in [(5, true), (6, false)] { + let muted = change( + session, + json!({"type":"set_input_muted","id":id,"active":active}), + ); + assert_eq!( + muted, + json!({"type":"input_mute_applied","id":id,"active":active}) + ); + } +} + +#[test] +fn every_setting_changes_in_a_live_call_with_one_voice() { + let (endpoint, server) = serve_spokesperson_changes(); + let mut session = ExpertSpokespersonTestSession::start(endpoint); + assert!(session.ready["session"]["spokesperson"].is_null()); + change_spokesperson_and_input(&mut session, "set_tts_settings"); + session.shutdown(); + server.join().unwrap(); +} + +#[test] +fn every_setting_changes_in_a_live_call_with_separate_voices() { + let (speech_url, _speech_requests) = spawn_speech_server(); + let (endpoint, server) = serve_spokesperson_changes(); + let mut session = ExpertSpokespersonTestSession::start_with_args( + endpoint, + &["--allow-direct-agent-speech", "--tts-url", &speech_url], + ); + let model = session.ready["session"]["tts"]["model"].clone(); + assert_eq!( + session.ready["session"]["spokesperson"]["voice"], + "old-voice" + ); + // The agent's own voice, then its speed, change without touching the Spokesperson's session. + for (id, voice, rate, revision) in [(7, "cedar", 1.0, 2), (8, "cedar", 1.5, 3)] { + let result = change( + &mut session, + json!({ + "type":"set_tts_settings", + "id":id, + "expected_revision":revision - 1, + "settings":{"backend":"openai","model":model,"voice":voice,"rate":rate} + }), + ); + assert_eq!(result["type"], "tts_settings_result", "{result}"); + assert_eq!(result["outcome"], "applied", "{result}"); + assert_eq!(result["snapshot"]["revision"], revision); + assert_eq!(result["snapshot"]["voice"], voice); + assert_eq!(result["snapshot"]["rate"], rate); + } + change_spokesperson_and_input(&mut session, "set_spokesperson_settings"); + session.shutdown(); + server.join().unwrap(); +} + #[test] fn expert_spokesperson_voice_candidate_mismatch_preserves_old_snapshot() { let (endpoint_tx, endpoint_rx) = mpsc::sync_channel(1); @@ -1878,6 +2286,71 @@ fn voice_cutover_pcm_overflow_rolls_back_every_frame_to_the_old_runtime() { server.join().unwrap(); } +/// The host resets input whenever it restarts the microphone, as when the output device changes, and keeps sending audio while the provider confirms. +#[test] +fn microphone_audio_keeps_flowing_while_the_provider_confirms_an_input_reset() { + const FRAMES: usize = 40; + let (endpoint_tx, endpoint_rx) = mpsc::sync_channel(1); + let (clear_seen_tx, clear_seen_rx) = mpsc::sync_channel(1); + let (appended_tx, appended_rx) = mpsc::sync_channel(1); + let server = std::thread::spawn(move || { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(async move { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + endpoint_tx + .send(format!("ws://{}/", listener.local_addr().unwrap())) + .unwrap(); + let (stream, _) = listener.accept().await.unwrap(); + let mut socket = accept_async(stream).await.unwrap(); + let update = receive_realtime_json(&mut socket).await; + acknowledge_realtime_session(&mut socket, &update).await; + let clear = receive_realtime_json(&mut socket).await; + assert_eq!(clear["type"], "input_audio_buffer.clear"); + clear_seen_tx.send(()).unwrap(); + // Longer than the session can buffer microphone audio. + tokio::time::sleep(Duration::from_millis(1_200)).await; + send_realtime_json(&mut socket, json!({"type":"input_audio_buffer.cleared"})).await; + let mut appended = 0; + while let Some(Ok(Message::Text(text))) = socket.next().await { + let message: Value = serde_json::from_str(&text).unwrap(); + if message["type"] == "input_audio_buffer.append" + && BASE64 + .decode(message["audio"].as_str().unwrap()) + .unwrap() + .iter() + .any(|sample| *sample != 0) + { + appended += 1; + } + } + appended_tx.send(appended).unwrap(); + }); + }); + let endpoint = endpoint_rx.recv().unwrap(); + let mut session = ExpertSpokespersonTestSession::start(endpoint); + session.send(json!({"type":"reset_input","id":3})); + clear_seen_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + for _ in 0..FRAMES { + session.send_pcm(0.25); + session.flush(); + std::thread::sleep(Duration::from_millis(20)); + } + assert_eq!( + session.recv(Duration::from_secs(3)), + json!({"type":"input_reset_applied","id":3}) + ); + let messages = session.shutdown_and_collect(); + assert!( + messages.iter().all(|message| message["type"] != "fatal"), + "{messages:?}" + ); + server.join().unwrap(); + assert_eq!(appended_rx.recv().unwrap(), FRAMES); +} + #[test] fn reset_input_during_voice_cutover_rolls_back_then_clears_the_old_runtime() { let (endpoint_tx, endpoint_rx) = mpsc::sync_channel(1); @@ -2278,6 +2751,7 @@ fn voice_cutover_timeout_is_terminal_and_never_reports_a_settings_result() { fn live_event_promptly_aborts_a_stalled_voice_candidate_and_replies_on_old_runtime() { let (endpoint_tx, endpoint_rx) = mpsc::sync_channel(1); let (candidate_seen_tx, candidate_seen_rx) = mpsc::sync_channel(1); + let (retry_seen_tx, retry_seen_rx) = mpsc::sync_channel(1); let server = std::thread::spawn(move || { tokio::runtime::Builder::new_current_thread() .enable_all() @@ -2324,6 +2798,9 @@ fn live_event_promptly_aborts_a_stalled_voice_candidate_and_replies_on_old_runti .expect("stalled candidate should be cancelled promptly") .unwrap(); assert!(!pending_handshake.is_empty()); + // The change is tried again once the user's turn is over. + let (_retry, _) = listener.accept().await.unwrap(); + retry_seen_tx.send(()).unwrap(); let _ = old.next().await; }); }); @@ -2338,21 +2815,18 @@ fn live_event_promptly_aborts_a_stalled_voice_candidate_and_replies_on_old_runti candidate_seen_rx .recv_timeout(Duration::from_secs(2)) .unwrap(); - let mut saw_user = false; - let mut saw_rejection = false; let deadline = std::time::Instant::now() + Duration::from_secs(2); - while !(saw_user && saw_rejection) { + loop { let remaining = deadline .checked_duration_since(std::time::Instant::now()) - .expect("session did not report user input and voice rejection promptly"); + .expect("session did not report user input promptly"); let message = session.recv(remaining); - saw_user |= message["type"] == "live_event"; - if message["type"] == "tts_settings_result" { - assert_eq!(message["outcome"], "rejected"); - assert_eq!(message["snapshot"]["voice"], "old-voice"); - saw_rejection = true; + assert_ne!(message["type"], "tts_settings_result", "{message}"); + if message["type"] == "live_event" { + break; } } + retry_seen_rx.recv_timeout(Duration::from_secs(2)).unwrap(); session.shutdown(); server.join().unwrap(); } @@ -2769,8 +3243,7 @@ fn expert_voice_keeps_a_separate_spokesperson_voice_control() { let mut session = ExpertSpokespersonTestSession::start_with_args( endpoint, &[ - "--expert-voice", - "tts", + "--allow-direct-agent-speech", "--tts-url", &speech_url, "--spokesperson-voice", @@ -2844,7 +3317,8 @@ fn interrupt_expert_reply(interruption: ReplyInterruption) -> (Value, usize) { release, at_drain: true, }), - &["--expert-voice", "tts", "--tts-url", &speech_url], + false, + &["--allow-direct-agent-speech", "--tts-url", &speech_url], ); let text = "I checked the repository and found three failing tests in the parser."; session.send(json!({"type":"prepare_speak","id":2,"acknowledgement":null,"text":text})); @@ -2923,7 +3397,8 @@ fn expert_voice_reply_whose_audio_never_settles_ends_the_session() { release, at_drain: true, }), - &["--expert-voice", "tts", "--tts-url", &speech_url], + false, + &["--allow-direct-agent-speech", "--tts-url", &speech_url], ); session.send(json!({ "type":"prepare_speak", @@ -3016,7 +3491,7 @@ fn expert_voice_speaks_replies_itself_and_tells_the_spokesperson_what_was_heard( let endpoint = endpoint_rx.recv().unwrap(); let mut session = ExpertSpokespersonTestSession::start_with_args( endpoint, - &["--expert-voice", "tts", "--tts-url", &speech_url], + &["--allow-direct-agent-speech", "--tts-url", &speech_url], ); assert_eq!(session.ready["session"]["tts"]["backend"], "openai"); assert_eq!( @@ -3034,7 +3509,6 @@ fn expert_voice_speaks_replies_itself_and_tells_the_spokesperson_what_was_heard( "id":2, "acknowledgement":1, "text":"I checked the repository.", - "resolved_handoff_ids":["handoff-external-1"], "voice":"coral" })); let admitted = session.recv(Duration::from_secs(2)); @@ -3116,7 +3590,7 @@ fn expert_voice_reply_waits_for_output_ready_before_playing() { }); let mut session = ExpertSpokespersonTestSession::start_with_args( endpoint_rx.recv().unwrap(), - &["--expert-voice", "tts", "--tts-url", &speech_url], + &["--allow-direct-agent-speech", "--tts-url", &speech_url], ); session.send(json!({ "type":"prepare_speak", @@ -3161,9 +3635,9 @@ fn expert_voice_reply_waits_for_output_ready_before_playing() { session.shutdown(); } -/// Fails an Expert reply answering a handoff once the host has played `played_frames` of it, -/// returning the failure, what the Spokesperson was told, and the handoffs left open. -fn fail_expert_reply_after(played_frames: u64) -> (Value, String, Value) { +/// Fails an Expert reply once the host has played `played_frames` of it, returning the +/// failure and what the Spokesperson was told. +fn fail_expert_reply_after(played_frames: u64) -> (Value, String) { let (speech_url, _speech_requests) = spawn_speech_server(); let (endpoint_tx, endpoint_rx) = mpsc::sync_channel(1); let (context_tx, context_rx) = mpsc::sync_channel(1); @@ -3181,17 +3655,6 @@ fn fail_expert_reply_after(played_frames: u64) -> (Value, String, Value) { let mut socket = accept_async(stream).await.unwrap(); let initial = receive_realtime_json(&mut socket).await; acknowledge_realtime_session(&mut socket, &initial).await; - send_realtime_json( - &mut socket, - json!({ - "type":"response.function_call_arguments.done", - "response_id":"response-handoff", - "call_id":"handoff-reply", - "name":"handoff", - "arguments":"{\"message\":\"inspect the repository\"}" - }), - ) - .await; let context = loop { let text = receive_realtime_json(&mut socket).await.to_string(); if text.contains("spoken reply") || text.contains("in its own voice") { @@ -3214,19 +3677,14 @@ fn fail_expert_reply_after(played_frames: u64) -> (Value, String, Value) { release, at_drain: true, }), - &["--expert-voice", "tts", "--tts-url", &speech_url], - ); - assert_eq!(session.recv(Duration::from_secs(2))["origin"], "handoff"); - assert_eq!( - session.recv(Duration::from_secs(2))["handoff_ids"], - json!(["handoff-external-1"]) + false, + &["--allow-direct-agent-speech", "--tts-url", &speech_url], ); session.send(json!({ "type":"prepare_speak", "id":2, - "acknowledgement":1, - "text":"I checked the repository and found three failing tests in the parser.", - "resolved_handoff_ids":["handoff-external-1"] + "acknowledgement":null, + "text":"I checked the repository and found three failing tests in the parser." })); let admitted = session.recv(Duration::from_secs(2)); assert_eq!(admitted["type"], "admitted", "{admitted}"); @@ -3253,33 +3711,272 @@ fn fail_expert_reply_after(played_frames: u64) -> (Value, String, Value) { } }; let context = context_rx.recv_timeout(Duration::from_secs(2)).unwrap(); - session.send(json!({"type":"query_state","id":3,"after":0})); - let state = loop { - let message = session.recv(Duration::from_secs(2)); - if message["type"] == "state" { - break message; - } - }; session.shutdown(); - (failed, context, state["unresolved_handoff_ids"].clone()) + (failed, context) } #[test] fn a_failed_expert_reply_tells_the_spokesperson_what_was_heard() { - let (failed, context, unresolved) = fail_expert_reply_after(1_000); + let (failed, context) = fail_expert_reply_after(1_000); assert_eq!(failed["id"], 2); assert!( context.contains("in its own voice") && context.contains("I checked the repository"), "{context}" ); assert!(!context.contains("in the parser"), "{context}"); - assert!(unresolved.is_null(), "{unresolved}"); } #[test] -fn an_expert_reply_that_fails_unheard_leaves_its_handoffs_open() { - let (failed, context, unresolved) = fail_expert_reply_after(0); +fn an_expert_reply_that_fails_unheard_tells_the_spokesperson_so() { + let (failed, context) = fail_expert_reply_after(0); assert_eq!(failed["id"], 2); assert!(context.contains("before hearing any of it"), "{context}"); - assert_eq!(unresolved, json!(["handoff-external-1"])); +} + +#[test] +fn a_message_to_the_spokesperson_is_a_directive_it_says() { + let (endpoint_tx, endpoint_rx) = mpsc::sync_channel(1); + let (relay_tx, relay_rx) = mpsc::sync_channel(1); + let server = std::thread::spawn(move || { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(async move { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + endpoint_tx + .send(format!("ws://{}/", listener.local_addr().unwrap())) + .unwrap(); + let (stream, _) = listener.accept().await.unwrap(); + let mut socket = accept_async(stream).await.unwrap(); + let initial = receive_realtime_json(&mut socket).await; + acknowledge_realtime_session(&mut socket, &initial).await; + for (call_id, message) in [ + ("handoff-1", "inspect the repository"), + ("handoff-2", "check the tests"), + ] { + send_realtime_json( + &mut socket, + json!({ + "type":"response.function_call_arguments.done", + "response_id":format!("response-{call_id}"), + "call_id":call_id, + "name":"handoff", + "arguments":json!({"message":message}).to_string() + }), + ) + .await; + while receive_realtime_json(&mut socket) + .await + .pointer("/item/type") + != Some(&json!("function_call_output")) + {} + } + while let Some(Ok(Message::Text(text))) = socket.next().await { + if text.contains("I checked the repository.") { + let _ = relay_tx.try_send(serde_json::from_str::(&text).unwrap()); + } + } + }); + }); + let mut session = ExpertSpokespersonTestSession::start(endpoint_rx.recv().unwrap()); + let handoffs = loop { + session.send(json!({"type":"query_state","id":1,"after":0})); + let state = loop { + let message = session.recv(Duration::from_secs(2)); + assert_ne!(message["type"], "fatal", "{message}"); + if message["type"] == "state" { + break message; + } + }; + if let Some(ids) = state["unresolved_handoff_ids"] + .as_array() + .filter(|ids| ids.len() == 2) + { + break ids.clone(); + } + std::thread::sleep(Duration::from_millis(20)); + }; + + // A stale message waits for what it missed, like a directive. + let prepare = |acknowledgement: &Value| { + json!({ + "type":"prepare_speak", + "id":2, + "acknowledgement":acknowledgement, + "resolved_handoff_ids":[&handoffs[0]], + "text":"I checked the repository.", + "relay":true + }) + }; + let reply = |session: &mut ExpertSpokespersonTestSession, request| { + session.send(request); + loop { + let message = session.recv(Duration::from_secs(2)); + assert_ne!(message["type"], "fatal", "{message}"); + if message["id"] == 2 { + break message; + } + } + }; + let pending = reply(&mut session, prepare(&json!(0))); + assert_eq!(pending["type"], "pending", "{pending}"); + let latest = &pending["utterances"].as_array().unwrap().last().unwrap()["token"]; + // Current, it is the Spokesperson's to say, and answers only the handoff it names. + let admitted = reply(&mut session, prepare(latest)); + assert_eq!(admitted["type"], "admitted", "{admitted}"); + let relayed = relay_rx.recv_timeout(Duration::from_secs(3)).unwrap(); + assert!( + relayed.to_string().contains("Speak it naturally"), + "{relayed}" + ); + session.send(json!({"type":"query_state","id":3,"after":0})); + let state = loop { + let message = session.recv(Duration::from_secs(2)); + if message["type"] == "state" { + break message; + } + }; + assert_eq!( + state["unresolved_handoff_ids"], + json!([&handoffs[1]]), + "{state}" + ); + session.shutdown(); + server.join().unwrap(); +} + +#[test] +fn handoffs_hold_nothing_open_when_the_expert_may_speak() { + let (speech_url, speech_requests) = spawn_speech_server(); + let (endpoint_tx, endpoint_rx) = mpsc::sync_channel(1); + let (renewed_tx, renewed_rx) = mpsc::sync_channel(1); + let server = std::thread::spawn(move || { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(async move { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + endpoint_tx + .send(format!("ws://{}/", listener.local_addr().unwrap())) + .unwrap(); + let (old_stream, _) = listener.accept().await.unwrap(); + let mut old = accept_async(old_stream).await.unwrap(); + let initial = receive_realtime_json(&mut old).await; + acknowledge_realtime_session(&mut old, &initial).await; + send_realtime_json( + &mut old, + json!({ + "type":"conversation.item.input_audio_transcription.completed", + "item_id":"user-1", + "transcript":"What changed in the repository?" + }), + ) + .await; + send_realtime_json( + &mut old, + json!({ + "type":"response.function_call_arguments.done", + "response_id":"response-handoff", + "call_id":"handoff-1", + "name":"handoff", + "arguments":"{\"message\":\"inspect the repository\"}" + }), + ) + .await; + while receive_realtime_json(&mut old).await.pointer("/item/type") + != Some(&json!("function_call_output")) + {} + send_realtime_json( + &mut old, + json!({ + "type":"error", + "error":{"code":"session_expired","message":"provider session expired"} + }), + ) + .await; + + // The handoff was never held open, so the call renews. + let (stream, _) = listener.accept().await.unwrap(); + let mut replacement = accept_async(stream).await.unwrap(); + let update = receive_realtime_json(&mut replacement).await; + acknowledge_realtime_session(&mut replacement, &update).await; + renewed_tx.send(()).unwrap(); + while let Some(Ok(Message::Text(text))) = replacement.next().await { + let seed: Value = serde_json::from_str(&text).unwrap(); + if seed["type"] == "conversation.item.create" { + send_realtime_json( + &mut replacement, + json!({"type":"conversation.item.created","item":{"id":seed["item"]["id"]}}), + ) + .await; + } + } + }); + }); + let endpoint = endpoint_rx.recv().unwrap(); + let mut session = ExpertSpokespersonTestSession::start_with_args( + endpoint, + &["--allow-direct-agent-speech", "--tts-url", &speech_url], + ); + renewed_rx.recv_timeout(Duration::from_secs(3)).unwrap(); + + // A reply written before everything since waits for it, and is said once + // it acknowledges the latest. + session.send(json!({ + "type":"prepare_speak", + "id":2, + "acknowledgement":0, + "text":"I checked the repository." + })); + let pending = loop { + let message = session.recv(Duration::from_secs(2)); + assert_ne!(message["type"], "fatal", "{message}"); + if message["id"] == 2 { + break message; + } + }; + assert_eq!(pending["type"], "pending", "{pending}"); + let latest = pending["utterances"].as_array().unwrap().last().unwrap()["token"].clone(); + session.send(json!({ + "type":"prepare_speak", + "id":2, + "acknowledgement":latest, + "text":"I checked the repository." + })); + let admitted = loop { + let message = session.recv(Duration::from_secs(2)); + assert_ne!(message["type"], "fatal", "{message}"); + if message["id"] == 2 { + break message; + } + }; + assert_eq!(admitted["type"], "admitted", "{admitted}"); + session.send(json!({"type":"query_state","id":3,"after":0})); + session.send(json!({ + "type":"output_ready", + "id":2, + "speech_id":admitted["speech_id"] + })); + let (mut state, mut completed) = (None, false); + while state.is_none() || !completed { + let message = session.recv(Duration::from_secs(3)); + assert_ne!(message["type"], "fatal", "{message}"); + assert_ne!(message["type"], "speech_failed", "{message}"); + match message["type"].as_str() { + Some("state") => state = Some(message), + Some("speech_completed") => completed = true, + _ => {} + } + } + assert_eq!(state.unwrap().get("unresolved_handoff_ids"), None); + assert_eq!( + speech_requests + .recv_timeout(Duration::from_secs(1)) + .unwrap()["input"], + "I checked the repository." + ); + session.shutdown(); + server.join().unwrap(); }