From af09dab27497a0443ca70eac8f81c183a7b90c2f Mon Sep 17 00:00:00 2001 From: John Tennant Date: Mon, 19 Oct 2026 20:25:50 -0400 Subject: [PATCH 01/24] berd-call: let any reply in the Expert's own voice answer every handoff With --expert-voice tts, a reply could be dropped: one written before the user's latest words came back pending, and one naming a handoff already settled was not admitted. An open handoff also kept the Spokesperson's session from renewing, and ended the call if the provider expired it. Such a reply is now always admitted, whatever its cursor, and settles every open handoff as soon as it is, so --resolves is ignored. Open handoffs no longer hold back renewal, recovery or a voice change, and the replacement session is told what they asked so it doesn't hand them off again. A reply that arrives during a replacement waits for it rather than failing it. Calls whose replies the Spokesperson says, and the Berd app, behave as before. Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- src-tauri/crates/berd-call/PROTOCOL.md | 7 +- src-tauri/crates/berd-call/README.md | 2 +- src-tauri/crates/berd-call/src/cli_help.rs | 4 +- .../berd-call/src/expert_spokesperson.rs | 5 + src-tauri/crates/berd-call/src/main.rs | 93 ++++++------- .../berd-call/src/openai_realtime_protocol.rs | 78 +++++++++-- .../berd-call/tests/session_protocol.rs | 126 ++++++++++++++++++ 7 files changed, 256 insertions(+), 59 deletions(-) diff --git a/src-tauri/crates/berd-call/PROTOCOL.md b/src-tauri/crates/berd-call/PROTOCOL.md index 410801034..b598059cb 100644 --- a/src-tauri/crates/berd-call/PROTOCOL.md +++ b/src-tauri/crates/berd-call/PROTOCOL.md @@ -219,7 +219,12 @@ 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 is admitted however stale its +`acknowledgement`, never `pending`, and answers every open handoff once +admitted, so `resolved_handoff_ids` is ignored. Open handoffs there don't hold +back a renewal or recovery of the Spokesperson's session; the replacement is +told what they asked. The parent cannot author speaking state or finalized input; those are derived only from PCM by the child runtime. diff --git a/src-tauri/crates/berd-call/README.md b/src-tauri/crates/berd-call/README.md index 77cb30a97..f842d5ea3 100644 --- a/src-tauri/crates/berd-call/README.md +++ b/src-tauri/crates/berd-call/README.md @@ -151,7 +151,7 @@ berd-call session --tts-backend openai --tts-url https://proxy.example/v1/audio/ 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`. +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. Every reply is spoken, even one written before what you said since, and it settles every open handoff once admitted, so `--resolves` isn't needed. Open handoffs no longer hold back renewing or recovering the Spokesperson's session; the new session is told what they asked, so it doesn't hand them off again. `--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`. 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..da80b19f2 100644 --- a/src-tauri/crates/berd-call/src/cli_help.rs +++ b/src-tauri/crates/berd-call/src/cli_help.rs @@ -65,7 +65,9 @@ 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. In a call with +--expert-voice tts, every reply is spoken however stale --re is, and answers +every open handoff, so --resolves is ignored."#; const SETTINGS_HELP: &str = r#"Update settings for the active local voice call. diff --git a/src-tauri/crates/berd-call/src/expert_spokesperson.rs b/src-tauri/crates/berd-call/src/expert_spokesperson.rs index ef9cf322a..433e99877 100644 --- a/src-tauri/crates/berd-call/src/expert_spokesperson.rs +++ b/src-tauri/crates/berd-call/src/expert_spokesperson.rs @@ -155,6 +155,11 @@ impl ExpertSpokespersonCore { self.pipe.cursor(RealtimePipePeer::Expert) } + /// The newest message the Expert has been sent, read or not. + pub fn delivered_token(&self) -> u64 { + self.pipe.delivery_cursor(RealtimePipePeer::Expert) + } + pub fn next_live_token(&self) -> u64 { self.pipe.next_message_id() } diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index ed85acaf7..e073c9108 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -2975,9 +2975,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 +2999,7 @@ impl LiveResponse { prepare_id, speech_id, expert_text: None, - reply: None, + reply: false, voice: None, output_ready: false, delivery: RealtimeAudioDelivery::default(), @@ -3224,21 +3224,35 @@ 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 { + // A reply in the Expert's own voice 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, core.semantic_revision(), update.base_revision, snapshot.revision, - core.has_unresolved_handoff(), + handoffs_hold_session(core, expert_tts), work, ) } +/// Whether open handoffs keep the Spokesperson's session from being +/// replaced: only while it says their replies itself. Replies in the +/// Expert's own voice need nothing from it. +fn handoffs_hold_session(core: &RealtimeExpertSpokespersonSession, expert_tts: bool) -> bool { + !expert_tts && core.has_unresolved_handoff() +} + fn unavailable_spokesperson_title(connection_lost: bool, quiescent: bool) -> &'static str { match (connection_lost, quiescent) { (true, false) => "Spokesperson connection was lost during an active turn", @@ -3326,7 +3340,7 @@ fn run_expert_spokesperson_session( if turn_gate.lifecycle.renewal_is_due( Instant::now(), work, - core.has_unresolved_handoff(), + handoffs_hold_session(&core, reply_tts.is_some()), pending_voice_update.is_some(), ) { let snapshot = session_tts.as_ref().expect("initialized TTS snapshot"); @@ -3343,7 +3357,7 @@ fn run_expert_spokesperson_session( runtime_config .as_ref() .expect("initialized Spokesperson config"), - core.semantic_transcript(), + core.replacement_transcript(), VoiceUpdatePurpose::Renewal, )?); } @@ -3359,6 +3373,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, @@ -3438,7 +3453,7 @@ fn run_expert_spokesperson_session( runtime_config .as_ref() .expect("initialized Spokesperson config"), - core.semantic_transcript(), + core.replacement_transcript(), ) { Ok(update) => Some(update), Err(message) => { @@ -3821,6 +3836,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, @@ -3942,7 +3958,7 @@ fn run_expert_spokesperson_session( &cancelled_directives, ); let quiescent = turn_gate.lifecycle.settings_are_quiescent(work) - && !core.has_unresolved_handoff(); + && !handoffs_hold_session(&core, reply_tts.is_some()); if !quiescent { write_protocol_fatal( &mut writer, @@ -3957,7 +3973,7 @@ fn run_expert_spokesperson_session( .as_ref() .map(VoiceUpdateTransaction::purpose), work, - core.has_unresolved_handoff(), + handoffs_hold_session(&core, reply_tts.is_some()), ); let start_recovery = match recovery_action { RealtimeSessionLossAction::ContinuePendingRecovery => { @@ -3999,7 +4015,7 @@ fn run_expert_spokesperson_session( runtime_config .as_ref() .expect("initialized Spokesperson config"), - core.semantic_transcript(), + core.replacement_transcript(), VoiceUpdatePurpose::SessionRecovery { cause: message.clone(), }, @@ -4212,7 +4228,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() { @@ -4790,9 +4805,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); @@ -5074,7 +5087,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 +5102,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,9 +5202,12 @@ fn submit_expert_prepare( next_speech_id: &mut u64, writer: &mut impl Write, ) -> Result<(), String> { - if !core - .unknown_handoff_ids(&request.resolved_handoff_ids) - .is_empty() + // A reply in the Expert's own voice answers every open handoff, so the + // ones it names don't matter. + if !expert_tts + && !core + .unknown_handoff_ids(&request.resolved_handoff_ids) + .is_empty() { return write_message( writer, @@ -5221,7 +5217,12 @@ fn submit_expert_prepare( }, ); } - match core.prepare_expert_directive(request.acknowledgement, request.text) { + let outcome = if expert_tts { + core.prepare_expert_reply(request.text) + } else { + core.prepare_expert_directive(request.acknowledgement, request.text) + }; + match outcome { ExpertDirectiveOutcome::Pending(events) => write_message( writer, &SessionMessage::Pending { @@ -5244,21 +5245,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 { // 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 +5428,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, 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..c037297fb 100644 --- a/src-tauri/crates/berd-call/src/openai_realtime_protocol.rs +++ b/src-tauri/crates/berd-call/src/openai_realtime_protocol.rs @@ -1587,6 +1587,20 @@ impl RealtimeExpertSpokespersonSession { }) } + /// Prepares an Expert reply spoken in its own voice: it is admitted + /// however much was said since it was written, and answers every open + /// handoff. + pub fn prepare_expert_reply(&mut self, message: String) -> ExpertDirectiveOutcome { + let outcome = self.conversation.prepare_directive(ExpertDirective { + acknowledgement: Some(self.conversation.delivered_token()), + message, + }); + if matches!(outcome, ExpertDirectiveOutcome::Accepted { .. }) { + self.open_handoffs.clear(); + } + outcome + } + pub fn record_live_event_with_delivery( &mut self, event: LiveSideEvent, @@ -1680,6 +1694,25 @@ impl RealtimeExpertSpokespersonSession { self.conversation.semantic_transcript() } + /// The transcript a replacement Spokesperson session starts from: the + /// conversation so far, and the handoffs still waiting for a reply, so it + /// doesn't hand them off again. + pub fn replacement_transcript(&self) -> Vec { + let mut turns = self.semantic_transcript(); + let mut open: Vec<_> = self.open_handoffs.iter().collect(); + open.sort_by_key(|(id, _)| *id); + if !open.is_empty() { + turns.push(SemanticTurn::Expert(format!( + "The Expert is still working on these handoffs and will answer in its own voice, so do not hand them off again:\n{}", + open.iter() + .map(|(_, handoff)| format!("- {}", handoff.message)) + .collect::>() + .join("\n") + ))); + } + turns + } + pub fn request_expert_message( &mut self, message: RealtimeExpertMessage, @@ -1783,16 +1816,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 +3116,41 @@ mod tests { ); } + #[test] + fn expert_reply_answers_every_handoff_however_late() { + let mut session = RealtimeExpertSpokespersonSession::new(0, "test-call"); + session + .register_handoff("handoff-1", 1, "First request") + .unwrap(); + session + .register_handoff("handoff-2", 1, "Second request") + .unwrap(); + let note = SemanticTurn::Expert( + "The Expert is still working on these handoffs and will answer in its own voice, so do not hand them off again:\n- First request\n- Second request".into(), + ); + assert_eq!(session.replacement_transcript(), [note]); + session + .record_live_event_with_delivery(LiveSideEvent::UserTranscript { + text: "And one more thing".into(), + }) + .unwrap(); + + // A directive written before the user's latest words waits for them. + assert!(matches!( + session.prepare_expert_directive(None, "Stale".into()), + ExpertDirectiveOutcome::Pending(_) + )); + assert!(matches!( + session.prepare_expert_reply("The answer".into()), + ExpertDirectiveOutcome::Accepted { + confirmed_token: 1, + .. + } + )); + assert!(!session.has_unresolved_handoff()); + assert_eq!(session.replacement_transcript(), []); + } + #[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/tests/session_protocol.rs b/src-tauri/crates/berd-call/tests/session_protocol.rs index dd2da7a78..72d79e988 100644 --- a/src-tauri/crates/berd-call/tests/session_protocol.rs +++ b/src-tauri/crates/berd-call/tests/session_protocol.rs @@ -3283,3 +3283,129 @@ fn an_expert_reply_that_fails_unheard_leaves_its_handoffs_open() { assert!(context.contains("before hearing any of it"), "{context}"); assert_eq!(unresolved, json!(["handoff-external-1"])); } + +#[test] +fn expert_voice_handoffs_survive_provider_expiry_and_any_late_reply_answers_them() { + let (speech_url, speech_requests) = spawn_speech_server(); + let (endpoint_tx, endpoint_rx) = mpsc::sync_channel(1); + let (note_tx, note_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 open handoff doesn't stop the replacement, which is told of it. + 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; + 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" { + continue; + } + send_realtime_json( + &mut replacement, + json!({"type":"conversation.item.created","item":{"id":seed["item"]["id"]}}), + ) + .await; + if text.contains("do not hand them off again") { + let _ = note_tx.try_send(seed); + } + } + }); + }); + let endpoint = endpoint_rx.recv().unwrap(); + let mut session = ExpertSpokespersonTestSession::start_with_args( + endpoint, + &["--expert-voice", "tts", "--tts-url", &speech_url], + ); + let note = note_rx.recv_timeout(Duration::from_secs(3)).unwrap(); + assert!( + note.to_string().contains("- inspect the repository"), + "{note}" + ); + + // A reply written before everything since, naming no handoff, is still spoken. + session.send(json!({ + "type":"prepare_speak", + "id":2, + "acknowledgement":0, + "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(); +} From e1c8d0f8d3fc737562d6818ed5924ab1e24481fc Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 07:26:26 -0400 Subject: [PATCH 02/24] berd-call: let the Expert message the Spokesperson in an own-voice call In a call with --expert-voice tts, every speak played in the Expert's voice, so an Expert couldn't have the Spokesperson tell the user something instead. `berd-call message-spokesperson TEXT` (protocol: `prepare_speak.relay`) hands the text to the Spokesperson to say, on the same terms as an own-voice reply there: admitted however stale, and answering every open handoff once admitted. Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- src-tauri/crates/berd-call/PROTOCOL.md | 6 +- src-tauri/crates/berd-call/README.md | 2 +- src-tauri/crates/berd-call/src/cli_help.rs | 12 ++ .../crates/berd-call/src/host_control.rs | 20 +++- .../crates/berd-call/src/host_session.rs | 7 ++ src-tauri/crates/berd-call/src/main.rs | 77 ++++++++++++- .../berd-call/src/openai_realtime_protocol.rs | 7 +- src-tauri/crates/berd-call/src/protocol.rs | 4 + .../berd-call/tests/session_protocol.rs | 106 ++++++++++++++++++ 9 files changed, 228 insertions(+), 13 deletions(-) diff --git a/src-tauri/crates/berd-call/PROTOCOL.md b/src-tauri/crates/berd-call/PROTOCOL.md index b598059cb..eae984e98 100644 --- a/src-tauri/crates/berd-call/PROTOCOL.md +++ b/src-tauri/crates/berd-call/PROTOCOL.md @@ -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} @@ -222,7 +222,9 @@ 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)`. In a call whose replies have their own voice, a reply is admitted however stale its `acknowledgement`, never `pending`, and answers every open handoff once -admitted, so `resolved_handoff_ids` is ignored. Open handoffs there don't hold +admitted, so `resolved_handoff_ids` is ignored. With `relay: true` (what +`berd-call message-spokesperson` sends), the Spokesperson says such a reply instead, as it would in a call without its own +voice, and it reports the same lifecycle. Open handoffs there don't hold back a renewal or recovery of the Spokesperson's session; the replacement is told what they asked. The parent cannot author speaking state or finalized input; those are derived diff --git a/src-tauri/crates/berd-call/README.md b/src-tauri/crates/berd-call/README.md index f842d5ea3..f05af6c83 100644 --- a/src-tauri/crates/berd-call/README.md +++ b/src-tauri/crates/berd-call/README.md @@ -151,7 +151,7 @@ berd-call session --tts-backend openai --tts-url https://proxy.example/v1/audio/ 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. Every reply is spoken, even one written before what you said since, and it settles every open handoff once admitted, so `--resolves` isn't needed. Open handoffs no longer hold back renewing or recovering the Spokesperson's session; the new session is told what they asked, so it doesn't hand them off again. `--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`. +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. Every reply is spoken, even one written before what you said since, and it settles every open handoff once admitted, so `--resolves` isn't needed. `berd-call message-spokesperson TEXT` has the Spokesperson tell you instead, in its own voice, on the same terms. Open handoffs no longer hold back renewing or recovering the Spokesperson's session; the new session is told what they asked, so it doesn't hand them off again. `--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`. 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 da80b19f2..0aaa7de06 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 @@ -69,6 +70,16 @@ voice, so several agents can share one call in distinct voices. In a call with --expert-voice tts, every reply is spoken however stale --re is, and answers every open handoff, so --resolves is ignored."#; +const MESSAGE_SPOKESPERSON_HELP: &str = r#"Message the Spokesperson of the active realtime call. + +Usage: + berd-call message-spokesperson [--port PORT] TEXT + +The Spokesperson tells the user in its own voice, even in a call with +--expert-voice tts, where `speak` uses the Expert's. Like `speak` there, it is +admitted however much the user has said since, answers every open handoff, and +reports the same result."#; + const SETTINGS_HELP: &str = r#"Update settings for the active local voice call. Usage: @@ -213,6 +224,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..973a7dc7c 100644 --- a/src-tauri/crates/berd-call/src/host_session.rs +++ b/src-tauri/crates/berd-call/src/host_session.rs @@ -519,6 +519,7 @@ enum ControlCommand { resolved_handoff_ids: Vec, voice: Option, language: Option, + relay: bool, non_blocking: bool, response: SyncSender>, }, @@ -743,6 +744,7 @@ impl HostControl for SessionControl { resolved_handoff_ids: Vec, voice: Option, language: Option, + relay: bool, ) -> Result { let (tx, rx) = mpsc::sync_channel(1); self.commands @@ -752,6 +754,7 @@ impl HostControl for SessionControl { resolved_handoff_ids, voice, language, + relay, non_blocking: self.non_blocking.load(Ordering::SeqCst), response: tx, }) @@ -1100,6 +1103,7 @@ impl SessionActor { resolved_handoff_ids, voice, language, + relay, non_blocking, response, } => { @@ -1114,6 +1118,7 @@ impl SessionActor { resolved_handoff_ids, voice, language, + relay, non_blocking, response, }); @@ -1129,6 +1134,7 @@ impl SessionActor { resolved_handoff_ids, voice, language, + relay, }, )?; self.pending_speak = Some(PendingSpeak { @@ -3371,6 +3377,7 @@ mod tests { resolved_handoff_ids: Vec::new(), voice: None, language: None, + relay: false, non_blocking: true, response: next_tx, }) diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index e073c9108..d4b134ff5 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -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 (port, text) = parse_or_exit(parse_message_spokesperson_args(&args), &args); + let response = host_control::request( + port, + host_control::ControlRequest::Speak { + text, + acknowledgement: None, + resolved_handoff_ids: Vec::new(), + 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) @@ -1031,6 +1049,18 @@ fn parse_speak_control_args(args: &[String]) -> Result Result<(u16, String), ParseFailure> { + let options = parse_speak_control_args(args)?; + if options.acknowledgement.is_some() + || !options.resolved_handoff_ids.is_empty() + || options.voice.is_some() + { + return Err("message-spokesperson accepts only --port PORT and TEXT".into()); + } + Ok((options.port, options.text)) +} + fn parse_host_settings_args( args: &[String], ) -> Result<(u16, host_control::ControlRequest), ParseFailure> { @@ -2417,6 +2447,7 @@ fn run_session(config: SessionConfig, pcm_output_fd: RawFd) -> Result<(), String resolved_handoff_ids: _, voice, language, + relay: _, }) => { let request = PrepareRequest { id, @@ -2740,6 +2771,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 { @@ -3229,8 +3262,8 @@ fn spokesperson_voice_update_is_safe( gate: &ExpertTurnGate, work: RealtimeHostWork, ) -> bool { - // A reply in the Expert's own voice waits for the replacement, and adds - // nothing to what it was given. + // 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 @@ -4471,6 +4504,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)? @@ -4483,6 +4517,7 @@ fn run_expert_spokesperson_session( text, resolved_handoff_ids, voice, + relay, }; let routing = route_expert_prepare( &mut turn_gate, @@ -5202,8 +5237,8 @@ fn submit_expert_prepare( next_speech_id: &mut u64, writer: &mut impl Write, ) -> Result<(), String> { - // A reply in the Expert's own voice answers every open handoff, so the - // ones it names don't matter. + // When the Expert has its own voice, any reply answers every open + // handoff, so the ones it names don't matter. if !expert_tts && !core .unknown_handoff_ids(&request.resolved_handoff_ids) @@ -5245,7 +5280,7 @@ fn submit_expert_prepare( let speech_id = *next_speech_id; *next_speech_id += 1; core.record_expert_turn(message.clone()); - if expert_tts { + if expert_tts && !request.relay { // 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}"); @@ -5258,7 +5293,12 @@ fn submit_expert_prepare( response.server_finished = true; responses.insert(response_id, response); } else { - let resolved_handoff_ids = request.resolved_handoff_ids; + // A relayed reply already answered every handoff when admitted. + let resolved_handoff_ids = if expert_tts { + Vec::new() + } else { + request.resolved_handoff_ids + }; core.mark_handoffs_resolving(&resolved_handoff_ids)?; directive_speeches.insert( request.id, @@ -8506,6 +8546,7 @@ mod tests { text: "answer".into(), resolved_handoff_ids: Vec::new(), voice: None, + relay: false, }; assert!(matches!( gate.defer_if_busy(request, false, 1), @@ -8546,6 +8587,7 @@ mod tests { text: "first".into(), resolved_handoff_ids: Vec::new(), voice: None, + relay: false, }, false, 1, @@ -8560,6 +8602,7 @@ mod tests { text: "second".into(), resolved_handoff_ids: Vec::new(), voice: None, + relay: false, }, false, 1, @@ -8591,6 +8634,7 @@ mod tests { text: "second".into(), resolved_handoff_ids: Vec::new(), voice: None, + relay: false, }, expert_output_reserved(&directives, &HashSet::new(), None, &responses), false, @@ -9118,6 +9162,7 @@ mod tests { text: "answer after the user".into(), resolved_handoff_ids: Vec::new(), voice: None, + relay: false, }, false, 1, @@ -11551,6 +11596,7 @@ mod tests { resolved_handoff_ids: vec![" ".into()], voice: None, language: None, + relay: false, }; assert_eq!( validate_request(empty).unwrap_err(), @@ -12752,6 +12798,25 @@ mod tests { text: "hello".into(), } ); + assert_eq!( + parse_message_spokesperson_args(&args(&[ + "berd-call", + "message-spokesperson", + "--port", + "5300", + "Tell them it's fixed." + ])) + .unwrap(), + (5300, "Tell them it's fixed.".into()) + ); + assert!(parse_message_spokesperson_args(&args(&[ + "berd-call", + "message-spokesperson", + "--voice", + "Nora", + "hello" + ])) + .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 c037297fb..c3299cd1d 100644 --- a/src-tauri/crates/berd-call/src/openai_realtime_protocol.rs +++ b/src-tauri/crates/berd-call/src/openai_realtime_protocol.rs @@ -1587,9 +1587,10 @@ impl RealtimeExpertSpokespersonSession { }) } - /// Prepares an Expert reply spoken in its own voice: it is admitted - /// however much was said since it was written, and answers every open - /// handoff. + /// Prepares an Expert reply in a call where the Expert has its own voice, + /// whether it speaks the reply or the Spokesperson relays it: it is + /// admitted however much was said since it was written, and answers + /// every open handoff. pub fn prepare_expert_reply(&mut self, message: String) -> ExpertDirectiveOutcome { let outcome = self.conversation.prepare_directive(ExpertDirective { acknowledgement: Some(self.conversation.delivered_token()), 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/tests/session_protocol.rs b/src-tauri/crates/berd-call/tests/session_protocol.rs index 72d79e988..4a50ad928 100644 --- a/src-tauri/crates/berd-call/tests/session_protocol.rs +++ b/src-tauri/crates/berd-call/tests/session_protocol.rs @@ -3284,6 +3284,112 @@ fn an_expert_reply_that_fails_unheard_leaves_its_handoffs_open() { assert_eq!(unresolved, json!(["handoff-external-1"])); } +#[test] +fn a_relayed_reply_is_said_by_the_spokesperson_and_answers_every_handoff() { + let (speech_url, speech_requests) = spawn_speech_server(); + 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 endpoint = endpoint_rx.recv().unwrap(); + let mut session = ExpertSpokespersonTestSession::start_with_args( + endpoint, + &["--expert-voice", "tts", "--tts-url", &speech_url], + ); + 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 state["unresolved_handoff_ids"] + .as_array() + .is_some_and(|ids| ids.len() == 2) + { + break; + } + std::thread::sleep(Duration::from_millis(20)); + } + + // Stale, naming no handoff, and still the Spokesperson's to say. + session.send(json!({ + "type":"prepare_speak", + "id":2, + "acknowledgement":0, + "text":"I checked the repository.", + "relay":true + })); + 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}"); + 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.get("unresolved_handoff_ids"), None, "{state}"); + assert!(speech_requests + .recv_timeout(Duration::from_millis(300)) + .is_err()); + session.shutdown(); + server.join().unwrap(); +} + #[test] fn expert_voice_handoffs_survive_provider_expiry_and_any_late_reply_answers_them() { let (speech_url, speech_requests) = spawn_speech_server(); From 7e2a9a4d958f72582f715bce0890b5cd78a5c722 Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 07:29:18 -0400 Subject: [PATCH 03/24] berd-call: let a message to the Spokesperson answer handoffs in any call `message-spokesperson` is how an Expert answers through the Spokesperson, so it now works the same in a call without --expert-voice tts: admitted however much the user has said since, and answering every open handoff, with no --re or --resolves. `speak` there keeps today's rules. Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- src-tauri/crates/berd-call/PROTOCOL.md | 5 +++-- src-tauri/crates/berd-call/README.md | 2 +- src-tauri/crates/berd-call/src/cli_help.rs | 6 +++--- src-tauri/crates/berd-call/src/main.rs | 13 +++++++------ .../berd-call/src/openai_realtime_protocol.rs | 7 +++---- .../crates/berd-call/tests/session_protocol.rs | 10 ++++++++-- 6 files changed, 25 insertions(+), 18 deletions(-) diff --git a/src-tauri/crates/berd-call/PROTOCOL.md b/src-tauri/crates/berd-call/PROTOCOL.md index eae984e98..0b7215e3f 100644 --- a/src-tauri/crates/berd-call/PROTOCOL.md +++ b/src-tauri/crates/berd-call/PROTOCOL.md @@ -223,8 +223,9 @@ are spoken by the Spokesperson, is `not_admitted(invalid_voice)`. In a call whose replies have their own voice, a reply is admitted however stale its `acknowledgement`, never `pending`, and answers every open handoff once admitted, so `resolved_handoff_ids` is ignored. With `relay: true` (what -`berd-call message-spokesperson` sends), the Spokesperson says such a reply instead, as it would in a call without its own -voice, and it reports the same lifecycle. Open handoffs there don't hold +`berd-call message-spokesperson` sends), the Spokesperson says the reply in any +Expert-Spokesperson call, on those same terms, with the same lifecycle. Open +handoffs in a call whose replies have their own voice don't hold back a renewal or recovery of the Spokesperson's session; the replacement is told what they asked. The parent cannot author speaking state or finalized input; those are derived diff --git a/src-tauri/crates/berd-call/README.md b/src-tauri/crates/berd-call/README.md index f05af6c83..ae292f9fc 100644 --- a/src-tauri/crates/berd-call/README.md +++ b/src-tauri/crates/berd-call/README.md @@ -151,7 +151,7 @@ berd-call session --tts-backend openai --tts-url https://proxy.example/v1/audio/ 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. Every reply is spoken, even one written before what you said since, and it settles every open handoff once admitted, so `--resolves` isn't needed. `berd-call message-spokesperson TEXT` has the Spokesperson tell you instead, in its own voice, on the same terms. Open handoffs no longer hold back renewing or recovering the Spokesperson's session; the new session is told what they asked, so it doesn't hand them off again. `--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`. +By default the Spokesperson reads the Expert's replies aloud in its own voice. `berd-call message-spokesperson TEXT` always has it tell you, in any Expert–Spokesperson call: the message is admitted however much you've said since, and answers every open handoff, with no `--re` or `--resolves`. 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. Every reply is spoken, even one written before what you said since, and it settles every open handoff once admitted, so `--resolves` isn't needed. Open handoffs no longer hold back renewing or recovering the Spokesperson's session; the new session is told what they asked, so it doesn't hand them off again. `--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`. 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 0aaa7de06..05c77ad6a 100644 --- a/src-tauri/crates/berd-call/src/cli_help.rs +++ b/src-tauri/crates/berd-call/src/cli_help.rs @@ -76,9 +76,9 @@ Usage: berd-call message-spokesperson [--port PORT] TEXT The Spokesperson tells the user in its own voice, even in a call with ---expert-voice tts, where `speak` uses the Expert's. Like `speak` there, it is -admitted however much the user has said since, answers every open handoff, and -reports the same result."#; +--expert-voice tts, where `speak` uses the Expert's. It is admitted however much +the user has said since, answers every open handoff, and reports the same result +as `speak`."#; const SETTINGS_HELP: &str = r#"Update settings for the active local voice call. diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index d4b134ff5..7cabd79f3 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -5237,9 +5237,10 @@ fn submit_expert_prepare( next_speech_id: &mut u64, writer: &mut impl Write, ) -> Result<(), String> { - // When the Expert has its own voice, any reply answers every open - // handoff, so the ones it names don't matter. - if !expert_tts + // A message to the Spokesperson, or any reply when the Expert has its own + // voice, answers every open handoff, so the ones it names don't matter. + let answers_all = expert_tts || request.relay; + if !answers_all && !core .unknown_handoff_ids(&request.resolved_handoff_ids) .is_empty() @@ -5252,7 +5253,7 @@ fn submit_expert_prepare( }, ); } - let outcome = if expert_tts { + let outcome = if answers_all { core.prepare_expert_reply(request.text) } else { core.prepare_expert_directive(request.acknowledgement, request.text) @@ -5293,8 +5294,8 @@ fn submit_expert_prepare( response.server_finished = true; responses.insert(response_id, response); } else { - // A relayed reply already answered every handoff when admitted. - let resolved_handoff_ids = if expert_tts { + // A message to the Spokesperson already answered every handoff when admitted. + let resolved_handoff_ids = if answers_all { Vec::new() } else { request.resolved_handoff_ids 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 c3299cd1d..ff2148772 100644 --- a/src-tauri/crates/berd-call/src/openai_realtime_protocol.rs +++ b/src-tauri/crates/berd-call/src/openai_realtime_protocol.rs @@ -1587,10 +1587,9 @@ impl RealtimeExpertSpokespersonSession { }) } - /// Prepares an Expert reply in a call where the Expert has its own voice, - /// whether it speaks the reply or the Spokesperson relays it: it is - /// admitted however much was said since it was written, and answers - /// every open handoff. + /// Prepares an Expert message to the Spokesperson, or any reply when the + /// Expert has its own voice: it is admitted however much was said since + /// it was written, and answers every open handoff. pub fn prepare_expert_reply(&mut self, message: String) -> ExpertDirectiveOutcome { let outcome = self.conversation.prepare_directive(ExpertDirective { acknowledgement: Some(self.conversation.delivered_token()), diff --git a/src-tauri/crates/berd-call/tests/session_protocol.rs b/src-tauri/crates/berd-call/tests/session_protocol.rs index 4a50ad928..0b7c91d2d 100644 --- a/src-tauri/crates/berd-call/tests/session_protocol.rs +++ b/src-tauri/crates/berd-call/tests/session_protocol.rs @@ -3285,7 +3285,12 @@ fn an_expert_reply_that_fails_unheard_leaves_its_handoffs_open() { } #[test] -fn a_relayed_reply_is_said_by_the_spokesperson_and_answers_every_handoff() { +fn a_message_to_the_spokesperson_is_said_by_it_and_answers_every_handoff() { + message_the_spokesperson(false); + message_the_spokesperson(true); +} + +fn message_the_spokesperson(expert_voice: bool) { let (speech_url, speech_requests) = spawn_speech_server(); let (endpoint_tx, endpoint_rx) = mpsc::sync_channel(1); let (relay_tx, relay_rx) = mpsc::sync_channel(1); @@ -3332,9 +3337,10 @@ fn a_relayed_reply_is_said_by_the_spokesperson_and_answers_every_handoff() { }); }); let endpoint = endpoint_rx.recv().unwrap(); + let own = ["--expert-voice", "tts", "--tts-url", &speech_url]; let mut session = ExpertSpokespersonTestSession::start_with_args( endpoint, - &["--expert-voice", "tts", "--tts-url", &speech_url], + if expert_voice { &own } else { &[] }, ); loop { session.send(json!({"type":"query_state","id":1,"after":0})); From ee04961521c4f91c16049a145a58e8c7a1bffe0c Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 07:40:30 -0400 Subject: [PATCH 04/24] berd-call: let the Expert speak directly only with --allow-direct-agent-speech In an Expert-Spokesperson call, the Expert now reaches the user through the Spokesperson with `message-spokesperson`, and `speak` is refused unless the call was started with --allow-direct-agent-speech. That flag replaces --expert-voice tts. With it, a reply in the Expert's own voice must acknowledge the latest input, as `speak --re` does everywhere, and once admitted it still answers every open handoff. A message to the Spokesperson stays admitted however stale. Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- src-tauri/crates/berd-call/PROTOCOL.md | 13 +-- src-tauri/crates/berd-call/README.md | 4 +- src-tauri/crates/berd-call/src/cli_help.rs | 20 +++-- .../crates/berd-call/src/host_session.rs | 51 +++++++++++ src-tauri/crates/berd-call/src/main.rs | 85 ++++++++++--------- .../berd-call/src/openai_realtime_protocol.rs | 34 +++++--- .../crates/berd-call/src/saved_settings.rs | 7 +- .../berd-call/tests/session_protocol.rs | 29 +++++-- 8 files changed, 165 insertions(+), 78 deletions(-) diff --git a/src-tauri/crates/berd-call/PROTOCOL.md b/src-tauri/crates/berd-call/PROTOCOL.md index 0b7215e3f..fbb87488b 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`, @@ -220,11 +220,12 @@ Unknown fields are rejected. IDs are positive. Speak text is at most 16 KiB. 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)`. In a call -whose replies have their own voice, a reply is admitted however stale its -`acknowledgement`, never `pending`, and answers every open handoff once -admitted, so `resolved_handoff_ids` is ignored. With `relay: true` (what +whose replies have their own voice, a reply needs the same `acknowledgement` +as a directive, and answers every open handoff once admitted, so +`resolved_handoff_ids` is ignored. With `relay: true` (what `berd-call message-spokesperson` sends), the Spokesperson says the reply in any -Expert-Spokesperson call, on those same terms, with the same lifecycle. Open +Expert-Spokesperson call; it is admitted however stale its `acknowledgement`, +never `pending`, and answers every open handoff. Open handoffs in a call whose replies have their own voice don't hold back a renewal or recovery of the Spokesperson's session; the replacement is told what they asked. diff --git a/src-tauri/crates/berd-call/README.md b/src-tauri/crates/berd-call/README.md index ae292f9fc..4da9813e0 100644 --- a/src-tauri/crates/berd-call/README.md +++ b/src-tauri/crates/berd-call/README.md @@ -146,12 +146,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. `berd-call message-spokesperson TEXT` always has it tell you, in any Expert–Spokesperson call: the message is admitted however much you've said since, and answers every open handoff, with no `--re` or `--resolves`. 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. Every reply is spoken, even one written before what you said since, and it settles every open handoff once admitted, so `--resolves` isn't needed. Open handoffs no longer hold back renewing or recovering the Spokesperson's session; the new session is told what they asked, so it doesn't hand them off again. `--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 TEXT` has it tell you in its own voice. The message is admitted however much you've said since, and answers every open handoff, with no `--re` or `--resolves`. `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, and it settles every open handoff once admitted, so `--resolves` isn't needed. Open handoffs no longer hold back renewing or recovering the Spokesperson's session; the new session is told what they asked, so it doesn't hand them off again. `--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 05c77ad6a..86711efab 100644 --- a/src-tauri/crates/berd-call/src/cli_help.rs +++ b/src-tauri/crates/berd-call/src/cli_help.rs @@ -66,9 +66,11 @@ 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. In a call with ---expert-voice tts, every reply is spoken however stale --re is, and answers -every open handoff, so --resolves is ignored."#; +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 +answers every open handoff, so --resolves is ignored."#; const MESSAGE_SPOKESPERSON_HELP: &str = r#"Message the Spokesperson of the active realtime call. @@ -76,7 +78,7 @@ Usage: berd-call message-spokesperson [--port PORT] TEXT The Spokesperson tells the user in its own voice, even in a call with ---expert-voice tts, where `speak` uses the Expert's. It is admitted however much +--allow-direct-agent-speech, where `speak` uses the Expert's. It is admitted however much the user has said since, answers every open handoff, and reports the same result as `speak`."#; @@ -94,7 +96,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."#; @@ -133,7 +135,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] @@ -142,9 +144,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. diff --git a/src-tauri/crates/berd-call/src/host_session.rs b/src-tauri/crates/berd-call/src/host_session.rs index 973a7dc7c..3cdc50d3f 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 { @@ -547,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, } @@ -746,6 +752,12 @@ impl HostControl for SessionControl { 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 { @@ -4350,6 +4362,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); @@ -4357,6 +4370,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); @@ -4372,6 +4421,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() { @@ -4414,6 +4464,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() { diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index 7cabd79f3..79ba32fac 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -899,10 +899,7 @@ fn parse_saved_start_args_at(args: &[String], path: PathBuf) -> Result(); 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; @@ -5253,8 +5250,10 @@ fn submit_expert_prepare( }, ); } - let outcome = if answers_all { - core.prepare_expert_reply(request.text) + let outcome = if request.relay { + core.prepare_expert_message(request.text) + } else if expert_tts { + core.prepare_expert_reply(request.acknowledgement, request.text) } else { core.prepare_expert_directive(request.acknowledgement, request.text) }; @@ -5922,6 +5921,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()); @@ -5944,6 +5947,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"))?; @@ -5973,13 +5981,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( @@ -5999,12 +6000,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()) @@ -10713,18 +10715,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", ]) @@ -10750,8 +10746,7 @@ mod tests { let chosen = expert(&[ "--tts-backend", "openai", - "--expert-voice", - "tts", + "--allow-direct-agent-speech", "--spokesperson-voice", "cedar", "--spokesperson-rate", @@ -10761,13 +10756,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", ), ] { @@ -10776,20 +10775,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"]) ); } @@ -12539,10 +12538,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) 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 ff2148772..d6482ba5f 100644 --- a/src-tauri/crates/berd-call/src/openai_realtime_protocol.rs +++ b/src-tauri/crates/berd-call/src/openai_realtime_protocol.rs @@ -1587,14 +1587,22 @@ impl RealtimeExpertSpokespersonSession { }) } - /// Prepares an Expert message to the Spokesperson, or any reply when the - /// Expert has its own voice: it is admitted however much was said since - /// it was written, and answers every open handoff. - pub fn prepare_expert_reply(&mut self, message: String) -> ExpertDirectiveOutcome { - let outcome = self.conversation.prepare_directive(ExpertDirective { - acknowledgement: Some(self.conversation.delivered_token()), - message, - }); + /// Prepares an Expert message to the Spokesperson: it is admitted however + /// much was said since it was written, and answers every open handoff. + pub fn prepare_expert_message(&mut self, message: String) -> ExpertDirectiveOutcome { + let acknowledgement = Some(self.conversation.delivered_token()); + self.prepare_expert_reply(acknowledgement, message) + } + + /// Prepares a reply in the Expert's own voice: like a directive, it waits + /// for whatever the Expert hasn't acknowledged, and once admitted it + /// answers every open handoff. + pub fn prepare_expert_reply( + &mut self, + acknowledgement: Option, + message: String, + ) -> ExpertDirectiveOutcome { + let outcome = self.prepare_expert_directive(acknowledgement, message); if matches!(outcome, ExpertDirectiveOutcome::Accepted { .. }) { self.open_handoffs.clear(); } @@ -3117,7 +3125,7 @@ mod tests { } #[test] - fn expert_reply_answers_every_handoff_however_late() { + fn expert_message_answers_every_handoff_however_late() { let mut session = RealtimeExpertSpokespersonSession::new(0, "test-call"); session .register_handoff("handoff-1", 1, "First request") @@ -3135,13 +3143,15 @@ mod tests { }) .unwrap(); - // A directive written before the user's latest words waits for them. + // A reply written before the user's latest words waits for them, and + // answers no handoff until it is admitted. assert!(matches!( - session.prepare_expert_directive(None, "Stale".into()), + session.prepare_expert_reply(None, "Stale".into()), ExpertDirectiveOutcome::Pending(_) )); + assert!(session.has_unresolved_handoff()); assert!(matches!( - session.prepare_expert_reply("The answer".into()), + session.prepare_expert_message("The answer".into()), ExpertDirectiveOutcome::Accepted { confirmed_token: 1, .. 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/tests/session_protocol.rs b/src-tauri/crates/berd-call/tests/session_protocol.rs index 0b7c91d2d..457cd69c6 100644 --- a/src-tauri/crates/berd-call/tests/session_protocol.rs +++ b/src-tauri/crates/berd-call/tests/session_protocol.rs @@ -2769,8 +2769,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", @@ -3016,7 +3015,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!( @@ -3337,7 +3336,7 @@ fn message_the_spokesperson(expert_voice: bool) { }); }); let endpoint = endpoint_rx.recv().unwrap(); - let own = ["--expert-voice", "tts", "--tts-url", &speech_url]; + let own = ["--allow-direct-agent-speech", "--tts-url", &speech_url]; let mut session = ExpertSpokespersonTestSession::start_with_args( endpoint, if expert_voice { &own } else { &[] }, @@ -3397,7 +3396,7 @@ fn message_the_spokesperson(expert_voice: bool) { } #[test] -fn expert_voice_handoffs_survive_provider_expiry_and_any_late_reply_answers_them() { +fn expert_voice_handoffs_survive_provider_expiry_and_a_current_reply_answers_them() { let (speech_url, speech_requests) = spawn_speech_server(); let (endpoint_tx, endpoint_rx) = mpsc::sync_channel(1); let (note_tx, note_rx) = mpsc::sync_channel(1); @@ -3471,7 +3470,7 @@ fn expert_voice_handoffs_survive_provider_expiry_and_any_late_reply_answers_them 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], ); let note = note_rx.recv_timeout(Duration::from_secs(3)).unwrap(); assert!( @@ -3479,13 +3478,29 @@ fn expert_voice_handoffs_survive_provider_expiry_and_any_late_reply_answers_them "{note}" ); - // A reply written before everything since, naming no handoff, is still spoken. + // A reply written before everything since waits for it, and once it + // acknowledges the latest, naming no handoff, it answers them all. 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}"); From 156d8f82985f102abd7ac8dcb9b6bbd49b19d8fc Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 07:54:15 -0400 Subject: [PATCH 05/24] berd-call: let a Codex task hear the call as Berd's Expert does A `--codex` task heard a realtime call only at handoffs. It now gets a batch after every Spokesperson reply and at each handoff, as Berd's Expert and berd-call before the handoffs stream did, so it can follow the conversation and answer what was said last. `--stream` (handoffs) still holds rows until a handoff, and `--stream live` is unchanged. Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- src-tauri/crates/berd-call/README.md | 4 ++-- src-tauri/crates/berd-call/src/cli_help.rs | 3 ++- src-tauri/crates/berd-call/src/host_session.rs | 5 +---- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src-tauri/crates/berd-call/README.md b/src-tauri/crates/berd-call/README.md index 4da9813e0..b5ea6d21c 100644 --- a/src-tauri/crates/berd-call/README.md +++ b/src-tauri/crates/berd-call/README.md @@ -76,8 +76,8 @@ nothing until then, and then every row since the last handoff, ending with the 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 hears the call as Berd's Expert +does: a batch after every Spokesperson reply, and at each handoff. 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. diff --git a/src-tauri/crates/berd-call/src/cli_help.rs b/src-tauri/crates/berd-call/src/cli_help.rs index 86711efab..d304643f3 100644 --- a/src-tauri/crates/berd-call/src/cli_help.rs +++ b/src-tauri/crates/berd-call/src/cli_help.rs @@ -43,7 +43,8 @@ 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 +happens. `--codex` delivers a batch to the calling Codex task after every +Spokesperson reply and at each handoff, as Berd's Expert hears the call (requires CODEX_THREAD_ID). A menu-bar item controls speech rate, input muting, and ending the call; pass `--no-menu-bar` to omit it. diff --git a/src-tauri/crates/berd-call/src/host_session.rs b/src-tauri/crates/berd-call/src/host_session.rs index 3cdc50d3f..6038be16f 100644 --- a/src-tauri/crates/berd-call/src/host_session.rs +++ b/src-tauri/crates/berd-call/src/host_session.rs @@ -1436,10 +1436,7 @@ impl SessionActor { ) -> Result<(), String> { self.held.extend(events); if !handoff - && matches!( - *self.transcript, - Transcript::Stdout { live: false } | Transcript::Codex(_) - ) + && matches!(*self.transcript, Transcript::Stdout { live: false }) { return Ok(()); } From 0afc16a680f7c2f92e7be606541f8ef63a4ab0ea Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 07:57:12 -0400 Subject: [PATCH 06/24] berd-call: make a message to the Spokesperson an Expert directive `message-spokesperson` was admitted however stale and answered every open handoff. It now takes the terms of a directive from Berd's Expert: `--re CURSOR` is required and must acknowledge the latest input (the Spokesperson's own speech doesn't count), or the message comes back `spoke:false` with what was missed, and each `--resolves HANDOFF_ID` settles that handoff once the Spokesperson has said it. This holds in any Expert-Spokesperson call, including one with --allow-direct-agent-speech, where `speak` still answers every handoff. Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- src-tauri/crates/berd-call/PROTOCOL.md | 7 +- src-tauri/crates/berd-call/README.md | 2 +- src-tauri/crates/berd-call/src/cli_help.rs | 10 +-- .../berd-call/src/expert_spokesperson.rs | 5 -- .../crates/berd-call/src/host_session.rs | 4 +- src-tauri/crates/berd-call/src/main.rs | 72 ++++++++++--------- .../berd-call/src/openai_realtime_protocol.rs | 11 +-- .../berd-call/tests/session_protocol.rs | 55 ++++++++------ 8 files changed, 86 insertions(+), 80 deletions(-) diff --git a/src-tauri/crates/berd-call/PROTOCOL.md b/src-tauri/crates/berd-call/PROTOCOL.md index fbb87488b..9e10acd4a 100644 --- a/src-tauri/crates/berd-call/PROTOCOL.md +++ b/src-tauri/crates/berd-call/PROTOCOL.md @@ -223,9 +223,10 @@ 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, and answers every open handoff once admitted, so `resolved_handoff_ids` is ignored. With `relay: true` (what -`berd-call message-spokesperson` sends), the Spokesperson says the reply in any -Expert-Spokesperson call; it is admitted however stale its `acknowledgement`, -never `pending`, and answers every open handoff. Open +`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. Open handoffs in a call whose replies have their own voice don't hold back a renewal or recovery of the Spokesperson's session; the replacement is told what they asked. diff --git a/src-tauri/crates/berd-call/README.md b/src-tauri/crates/berd-call/README.md index b5ea6d21c..40f6b25c7 100644 --- a/src-tauri/crates/berd-call/README.md +++ b/src-tauri/crates/berd-call/README.md @@ -151,7 +151,7 @@ berd-call session --tts-backend openai --tts-url https://proxy.example/v1/audio/ berd-call session --stt-backend openai --stt-url wss://proxy.example/v1/realtime?intent=transcription ``` -In an Expert–Spokesperson call, the Expert reaches you through the Spokesperson: `berd-call message-spokesperson TEXT` has it tell you in its own voice. The message is admitted however much you've said since, and answers every open handoff, with no `--re` or `--resolves`. `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, and it settles every open handoff once admitted, so `--resolves` isn't needed. Open handoffs no longer hold back renewing or recovering the Spokesperson's session; the new session is told what they asked, so it doesn't hand them off again. `--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`. +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, and it settles every open handoff once admitted, so `--resolves` isn't needed. Open handoffs no longer hold back renewing or recovering the Spokesperson's session; the new session is told what they asked, so it doesn't hand them off again. `--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 d304643f3..dabffbff0 100644 --- a/src-tauri/crates/berd-call/src/cli_help.rs +++ b/src-tauri/crates/berd-call/src/cli_help.rs @@ -76,12 +76,14 @@ answers every open handoff, so --resolves is ignored."#; const MESSAGE_SPOKESPERSON_HELP: &str = r#"Message the Spokesperson of the active realtime call. Usage: - berd-call message-spokesperson [--port PORT] TEXT + 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. It is admitted however much -the user has said since, answers every open handoff, and reports the same result -as `speak`."#; +--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. diff --git a/src-tauri/crates/berd-call/src/expert_spokesperson.rs b/src-tauri/crates/berd-call/src/expert_spokesperson.rs index 433e99877..ef9cf322a 100644 --- a/src-tauri/crates/berd-call/src/expert_spokesperson.rs +++ b/src-tauri/crates/berd-call/src/expert_spokesperson.rs @@ -155,11 +155,6 @@ impl ExpertSpokespersonCore { self.pipe.cursor(RealtimePipePeer::Expert) } - /// The newest message the Expert has been sent, read or not. - pub fn delivered_token(&self) -> u64 { - self.pipe.delivery_cursor(RealtimePipePeer::Expert) - } - pub fn next_live_token(&self) -> u64 { self.pipe.next_message_id() } diff --git a/src-tauri/crates/berd-call/src/host_session.rs b/src-tauri/crates/berd-call/src/host_session.rs index 6038be16f..a039ef1e0 100644 --- a/src-tauri/crates/berd-call/src/host_session.rs +++ b/src-tauri/crates/berd-call/src/host_session.rs @@ -1435,9 +1435,7 @@ impl SessionActor { handoff: bool, ) -> Result<(), String> { self.held.extend(events); - if !handoff - && matches!(*self.transcript, Transcript::Stdout { live: false }) - { + if !handoff && matches!(*self.transcript, Transcript::Stdout { live: false }) { return Ok(()); } for event in unstreamed(&std::mem::take(&mut self.held), &mut self.transcribed) { diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index 79ba32fac..330560db1 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -568,13 +568,13 @@ fn main() { print_pretty_json(&response).unwrap_or_else(|error| operational_error("speak", error)); } Some("message-spokesperson") => { - let (port, text) = parse_or_exit(parse_message_spokesperson_args(&args), &args); + let options = parse_or_exit(parse_message_spokesperson_args(&args), &args); let response = host_control::request( - port, + options.port, host_control::ControlRequest::Speak { - text, - acknowledgement: None, - resolved_handoff_ids: Vec::new(), + text: options.text, + acknowledgement: options.acknowledgement, + resolved_handoff_ids: options.resolved_handoff_ids, voice: None, language: None, relay: true, @@ -1047,15 +1047,15 @@ fn parse_speak_control_args(args: &[String]) -> Result Result<(u16, String), ParseFailure> { +fn parse_message_spokesperson_args(args: &[String]) -> Result { let options = parse_speak_control_args(args)?; - if options.acknowledgement.is_some() - || !options.resolved_handoff_ids.is_empty() - || options.voice.is_some() - { - return Err("message-spokesperson accepts only --port PORT and TEXT".into()); + 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.port, options.text)) + Ok(options) } fn parse_host_settings_args( @@ -5234,10 +5234,10 @@ fn submit_expert_prepare( next_speech_id: &mut u64, writer: &mut impl Write, ) -> Result<(), String> { - // A message to the Spokesperson, or any reply when the Expert has its own - // voice, answers every open handoff, so the ones it names don't matter. - let answers_all = expert_tts || request.relay; - if !answers_all + // A reply in the Expert's own voice answers every open handoff, so the + // ones it names don't matter. A message to the Spokesperson is a directive. + let own_voice = expert_tts && !request.relay; + if !own_voice && !core .unknown_handoff_ids(&request.resolved_handoff_ids) .is_empty() @@ -5250,9 +5250,7 @@ fn submit_expert_prepare( }, ); } - let outcome = if request.relay { - core.prepare_expert_message(request.text) - } else if expert_tts { + let outcome = if own_voice { core.prepare_expert_reply(request.acknowledgement, request.text) } else { core.prepare_expert_directive(request.acknowledgement, request.text) @@ -5280,7 +5278,7 @@ fn submit_expert_prepare( let speech_id = *next_speech_id; *next_speech_id += 1; core.record_expert_turn(message.clone()); - if expert_tts && !request.relay { + 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}"); @@ -5293,12 +5291,7 @@ fn submit_expert_prepare( response.server_finished = true; responses.insert(response_id, response); } else { - // A message to the Spokesperson already answered every handoff when admitted. - let resolved_handoff_ids = if answers_all { - Vec::new() - } else { - request.resolved_handoff_ids - }; + let resolved_handoff_ids = request.resolved_handoff_ids; core.mark_handoffs_resolving(&resolved_handoff_ids)?; directive_speeches.insert( request.id, @@ -12808,19 +12801,28 @@ mod tests { "message-spokesperson", "--port", "5300", + "--re", + "4", + "--resolves", + "handoff-1", "Tell them it's fixed." ])) .unwrap(), - (5300, "Tell them it's fixed.".into()) + SpeakOptions { + port: 5300, + acknowledgement: Some(4), + resolved_handoff_ids: vec!["handoff-1".into()], + voice: None, + language: None, + text: "Tell them it's fixed.".into(), + } ); - assert!(parse_message_spokesperson_args(&args(&[ - "berd-call", - "message-spokesperson", - "--voice", - "Nora", - "hello" - ])) - .is_err()); + 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 d6482ba5f..d79829184 100644 --- a/src-tauri/crates/berd-call/src/openai_realtime_protocol.rs +++ b/src-tauri/crates/berd-call/src/openai_realtime_protocol.rs @@ -1587,13 +1587,6 @@ impl RealtimeExpertSpokespersonSession { }) } - /// Prepares an Expert message to the Spokesperson: it is admitted however - /// much was said since it was written, and answers every open handoff. - pub fn prepare_expert_message(&mut self, message: String) -> ExpertDirectiveOutcome { - let acknowledgement = Some(self.conversation.delivered_token()); - self.prepare_expert_reply(acknowledgement, message) - } - /// Prepares a reply in the Expert's own voice: like a directive, it waits /// for whatever the Expert hasn't acknowledged, and once admitted it /// answers every open handoff. @@ -3125,7 +3118,7 @@ mod tests { } #[test] - fn expert_message_answers_every_handoff_however_late() { + fn expert_reply_answers_every_handoff_once_current() { let mut session = RealtimeExpertSpokespersonSession::new(0, "test-call"); session .register_handoff("handoff-1", 1, "First request") @@ -3151,7 +3144,7 @@ mod tests { )); assert!(session.has_unresolved_handoff()); assert!(matches!( - session.prepare_expert_message("The answer".into()), + session.prepare_expert_reply(Some(1), "The answer".into()), ExpertDirectiveOutcome::Accepted { confirmed_token: 1, .. diff --git a/src-tauri/crates/berd-call/tests/session_protocol.rs b/src-tauri/crates/berd-call/tests/session_protocol.rs index 457cd69c6..930d49b53 100644 --- a/src-tauri/crates/berd-call/tests/session_protocol.rs +++ b/src-tauri/crates/berd-call/tests/session_protocol.rs @@ -3284,7 +3284,7 @@ fn an_expert_reply_that_fails_unheard_leaves_its_handoffs_open() { } #[test] -fn a_message_to_the_spokesperson_is_said_by_it_and_answers_every_handoff() { +fn a_message_to_the_spokesperson_is_a_directive_it_says() { message_the_spokesperson(false); message_the_spokesperson(true); } @@ -3341,7 +3341,7 @@ fn message_the_spokesperson(expert_voice: bool) { endpoint, if expert_voice { &own } else { &[] }, ); - loop { + let handoffs = loop { session.send(json!({"type":"query_state","id":1,"after":0})); let state = loop { let message = session.recv(Duration::from_secs(2)); @@ -3350,30 +3350,41 @@ fn message_the_spokesperson(expert_voice: bool) { break message; } }; - if state["unresolved_handoff_ids"] + if let Some(ids) = state["unresolved_handoff_ids"] .as_array() - .is_some_and(|ids| ids.len() == 2) + .filter(|ids| ids.len() == 2) { - break; + break ids.clone(); } std::thread::sleep(Duration::from_millis(20)); - } + }; - // Stale, naming no handoff, and still the Spokesperson's to say. - session.send(json!({ - "type":"prepare_speak", - "id":2, - "acknowledgement":0, - "text":"I checked the repository.", - "relay":true - })); - let admitted = loop { - let message = session.recv(Duration::from_secs(2)); - assert_ne!(message["type"], "fatal", "{message}"); - if message["id"] == 2 { - break message; + // 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 mut 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!( @@ -3387,7 +3398,11 @@ fn message_the_spokesperson(expert_voice: bool) { break message; } }; - assert_eq!(state.get("unresolved_handoff_ids"), None, "{state}"); + assert_eq!( + state["unresolved_handoff_ids"], + json!([&handoffs[1]]), + "{state}" + ); assert!(speech_requests .recv_timeout(Duration::from_millis(300)) .is_err()); From d43e83e392c8a9bc5cf245813d22307c8b15250a Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 07:58:30 -0400 Subject: [PATCH 07/24] berd-call: stream realtime calls the way Berd's Expert hears them `--stream` (or `--stream handoffs`) printed nothing in an Expert-Spokesperson call until a handoff. It now prints the same batches as `--codex`, after every Spokesperson reply and at each handoff, so the CLI has two ways to hear a realtime call: as Berd's Expert does, or as it happens with `--stream live`. `handoffs` is no longer accepted after `--stream`. Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- src-tauri/crates/berd-call/README.md | 10 ++-- src-tauri/crates/berd-call/src/cli_help.rs | 11 ++-- .../crates/berd-call/src/host_session.rs | 57 ++----------------- src-tauri/crates/berd-call/src/main.rs | 6 +- 4 files changed, 15 insertions(+), 69 deletions(-) diff --git a/src-tauri/crates/berd-call/README.md b/src-tauri/crates/berd-call/README.md index 40f6b25c7..4fef37df9 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 hears the call as Berd's Expert -does: a batch after every Spokesperson reply, and at each handoff. 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. diff --git a/src-tauri/crates/berd-call/src/cli_help.rs b/src-tauri/crates/berd-call/src/cli_help.rs index dabffbff0..6be273470 100644 --- a/src-tauri/crates/berd-call/src/cli_help.rs +++ b/src-tauri/crates/berd-call/src/cli_help.rs @@ -34,18 +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 a batch to the calling Codex task after every -Spokesperson reply and at each handoff, as Berd's Expert hears the call -(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. diff --git a/src-tauri/crates/berd-call/src/host_session.rs b/src-tauri/crates/berd-call/src/host_session.rs index a039ef1e0..dd0dfe108 100644 --- a/src-tauri/crates/berd-call/src/host_session.rs +++ b/src-tauri/crates/berd-call/src/host_session.rs @@ -834,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, @@ -898,7 +896,6 @@ impl SessionActor { transcript, expert_spokesperson, transcribed: HashSet::new(), - held: Vec::new(), stopping: false, restart: None, muted: Arc::new(AtomicBool::new(false)), @@ -1310,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}))); @@ -1431,14 +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 }) { - 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), @@ -2735,43 +2723,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); diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index 330560db1..3819280b0 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -823,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 } @@ -12436,7 +12435,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(); From b205cdcab707f9475c5f3fbc35b64c167473241f Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 08:03:49 -0400 Subject: [PATCH 08/24] berd-call: hold no handoff open when the Expert may speak for itself With --allow-direct-agent-speech the Spokesperson still hands off and the Expert still hears each handoff, but nothing tracks it: no reminders, no renewal or recovery held back, no note for a replacement session, and nothing for --resolves to name. A reply is said once it acknowledges the latest input, as before. Calls without the flag keep Berd's handoff rules. Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- src-tauri/crates/berd-call/PROTOCOL.md | 11 +- src-tauri/crates/berd-call/README.md | 2 +- src-tauri/crates/berd-call/src/cli_help.rs | 4 +- src-tauri/crates/berd-call/src/main.rs | 42 +++---- .../berd-call/src/openai_realtime_protocol.rs | 106 ++++++------------ .../berd-call/tests/session_protocol.rs | 52 +++------ 6 files changed, 72 insertions(+), 145 deletions(-) diff --git a/src-tauri/crates/berd-call/PROTOCOL.md b/src-tauri/crates/berd-call/PROTOCOL.md index 9e10acd4a..1ff842ecf 100644 --- a/src-tauri/crates/berd-call/PROTOCOL.md +++ b/src-tauri/crates/berd-call/PROTOCOL.md @@ -221,15 +221,14 @@ 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)`. In a call whose replies have their own voice, a reply needs the same `acknowledgement` -as a directive, and answers every open handoff once admitted, so -`resolved_handoff_ids` is ignored. With `relay: true` (what +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. Open -handoffs in a call whose replies have their own voice don't hold -back a renewal or recovery of the Spokesperson's session; the replacement is -told what they asked. +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. diff --git a/src-tauri/crates/berd-call/README.md b/src-tauri/crates/berd-call/README.md index 4fef37df9..75d8628c6 100644 --- a/src-tauri/crates/berd-call/README.md +++ b/src-tauri/crates/berd-call/README.md @@ -149,7 +149,7 @@ berd-call session --tts-backend openai --tts-url https://proxy.example/v1/audio/ berd-call session --stt-backend openai --stt-url wss://proxy.example/v1/realtime?intent=transcription ``` -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, and it settles every open handoff once admitted, so `--resolves` isn't needed. Open handoffs no longer hold back renewing or recovering the Spokesperson's session; the new session is told what they asked, so it doesn't hand them off again. `--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`. +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 6be273470..5c2ffc270 100644 --- a/src-tauri/crates/berd-call/src/cli_help.rs +++ b/src-tauri/crates/berd-call/src/cli_help.rs @@ -69,8 +69,8 @@ this text in another voice of the call's reply backend without changing its save 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 -answers every open handoff, so --resolves is ignored."#; +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. diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index 3819280b0..87a125304 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -3270,18 +3270,11 @@ fn spokesperson_voice_update_is_safe( core.semantic_revision(), update.base_revision, snapshot.revision, - handoffs_hold_session(core, expert_tts), + core.has_unresolved_handoff(), work, ) } -/// Whether open handoffs keep the Spokesperson's session from being -/// replaced: only while it says their replies itself. Replies in the -/// Expert's own voice need nothing from it. -fn handoffs_hold_session(core: &RealtimeExpertSpokespersonSession, expert_tts: bool) -> bool { - !expert_tts && core.has_unresolved_handoff() -} - fn unavailable_spokesperson_title(connection_lost: bool, quiescent: bool) -> &'static str { match (connection_lost, quiescent) { (true, false) => "Spokesperson connection was lost during an active turn", @@ -3333,7 +3326,12 @@ fn run_expert_spokesperson_session( 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; @@ -3369,7 +3367,7 @@ fn run_expert_spokesperson_session( if turn_gate.lifecycle.renewal_is_due( Instant::now(), work, - handoffs_hold_session(&core, reply_tts.is_some()), + core.has_unresolved_handoff(), pending_voice_update.is_some(), ) { let snapshot = session_tts.as_ref().expect("initialized TTS snapshot"); @@ -3386,7 +3384,7 @@ fn run_expert_spokesperson_session( runtime_config .as_ref() .expect("initialized Spokesperson config"), - core.replacement_transcript(), + core.semantic_transcript(), VoiceUpdatePurpose::Renewal, )?); } @@ -3482,7 +3480,7 @@ fn run_expert_spokesperson_session( runtime_config .as_ref() .expect("initialized Spokesperson config"), - core.replacement_transcript(), + core.semantic_transcript(), ) { Ok(update) => Some(update), Err(message) => { @@ -3987,7 +3985,7 @@ fn run_expert_spokesperson_session( &cancelled_directives, ); let quiescent = turn_gate.lifecycle.settings_are_quiescent(work) - && !handoffs_hold_session(&core, reply_tts.is_some()); + && !core.has_unresolved_handoff(); if !quiescent { write_protocol_fatal( &mut writer, @@ -4002,7 +4000,7 @@ fn run_expert_spokesperson_session( .as_ref() .map(VoiceUpdateTransaction::purpose), work, - handoffs_hold_session(&core, reply_tts.is_some()), + core.has_unresolved_handoff(), ); let start_recovery = match recovery_action { RealtimeSessionLossAction::ContinuePendingRecovery => { @@ -4044,7 +4042,7 @@ fn run_expert_spokesperson_session( runtime_config .as_ref() .expect("initialized Spokesperson config"), - core.replacement_transcript(), + core.semantic_transcript(), VoiceUpdatePurpose::SessionRecovery { cause: message.clone(), }, @@ -5233,13 +5231,10 @@ fn submit_expert_prepare( next_speech_id: &mut u64, writer: &mut impl Write, ) -> Result<(), String> { - // A reply in the Expert's own voice answers every open handoff, so the - // ones it names don't matter. A message to the Spokesperson is a directive. let own_voice = expert_tts && !request.relay; - if !own_voice - && !core - .unknown_handoff_ids(&request.resolved_handoff_ids) - .is_empty() + if !core + .unknown_handoff_ids(&request.resolved_handoff_ids) + .is_empty() { return write_message( writer, @@ -5249,12 +5244,7 @@ fn submit_expert_prepare( }, ); } - let outcome = if own_voice { - core.prepare_expert_reply(request.acknowledgement, request.text) - } else { - core.prepare_expert_directive(request.acknowledgement, request.text) - }; - match outcome { + match core.prepare_expert_directive(request.acknowledgement, request.text) { ExpertDirectiveOutcome::Pending(events) => write_message( writer, &SessionMessage::Pending { 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 d79829184..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, @@ -1587,21 +1598,6 @@ impl RealtimeExpertSpokespersonSession { }) } - /// Prepares a reply in the Expert's own voice: like a directive, it waits - /// for whatever the Expert hasn't acknowledged, and once admitted it - /// answers every open handoff. - pub fn prepare_expert_reply( - &mut self, - acknowledgement: Option, - message: String, - ) -> ExpertDirectiveOutcome { - let outcome = self.prepare_expert_directive(acknowledgement, message); - if matches!(outcome, ExpertDirectiveOutcome::Accepted { .. }) { - self.open_handoffs.clear(); - } - outcome - } - pub fn record_live_event_with_delivery( &mut self, event: LiveSideEvent, @@ -1695,25 +1691,6 @@ impl RealtimeExpertSpokespersonSession { self.conversation.semantic_transcript() } - /// The transcript a replacement Spokesperson session starts from: the - /// conversation so far, and the handoffs still waiting for a reply, so it - /// doesn't hand them off again. - pub fn replacement_transcript(&self) -> Vec { - let mut turns = self.semantic_transcript(); - let mut open: Vec<_> = self.open_handoffs.iter().collect(); - open.sort_by_key(|(id, _)| *id); - if !open.is_empty() { - turns.push(SemanticTurn::Expert(format!( - "The Expert is still working on these handoffs and will answer in its own voice, so do not hand them off again:\n{}", - open.iter() - .map(|(_, handoff)| format!("- {}", handoff.message)) - .collect::>() - .join("\n") - ))); - } - turns - } - pub fn request_expert_message( &mut self, message: RealtimeExpertMessage, @@ -1760,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) } @@ -3118,40 +3097,21 @@ mod tests { } #[test] - fn expert_reply_answers_every_handoff_once_current() { - let mut session = RealtimeExpertSpokespersonSession::new(0, "test-call"); - session - .register_handoff("handoff-1", 1, "First request") - .unwrap(); - session - .register_handoff("handoff-2", 1, "Second request") - .unwrap(); - let note = SemanticTurn::Expert( - "The Expert is still working on these handoffs and will answer in its own voice, so do not hand them off again:\n- First request\n- Second request".into(), - ); - assert_eq!(session.replacement_transcript(), [note]); - session - .record_live_event_with_delivery(LiveSideEvent::UserTranscript { - text: "And one more thing".into(), + 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(); - - // A reply written before the user's latest words waits for them, and - // answers no handoff until it is admitted. - assert!(matches!( - session.prepare_expert_reply(None, "Stale".into()), - ExpertDirectiveOutcome::Pending(_) - )); - assert!(session.has_unresolved_handoff()); - assert!(matches!( - session.prepare_expert_reply(Some(1), "The answer".into()), - ExpertDirectiveOutcome::Accepted { - confirmed_token: 1, - .. - } - )); + assert_eq!(delivery.unwrap().handoff_ids, ["handoff-test-call-1"]); assert!(!session.has_unresolved_handoff()); - assert_eq!(session.replacement_transcript(), []); + assert_eq!( + session.complete_expert_turn(&[], 3), + RealtimeHandoffReminder::None + ); } #[test] diff --git a/src-tauri/crates/berd-call/tests/session_protocol.rs b/src-tauri/crates/berd-call/tests/session_protocol.rs index 930d49b53..8b9f41860 100644 --- a/src-tauri/crates/berd-call/tests/session_protocol.rs +++ b/src-tauri/crates/berd-call/tests/session_protocol.rs @@ -3033,7 +3033,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)); @@ -3285,12 +3284,6 @@ fn an_expert_reply_that_fails_unheard_leaves_its_handoffs_open() { #[test] fn a_message_to_the_spokesperson_is_a_directive_it_says() { - message_the_spokesperson(false); - message_the_spokesperson(true); -} - -fn message_the_spokesperson(expert_voice: bool) { - let (speech_url, speech_requests) = spawn_speech_server(); let (endpoint_tx, endpoint_rx) = mpsc::sync_channel(1); let (relay_tx, relay_rx) = mpsc::sync_channel(1); let server = std::thread::spawn(move || { @@ -3335,12 +3328,7 @@ fn message_the_spokesperson(expert_voice: bool) { } }); }); - let endpoint = endpoint_rx.recv().unwrap(); - let own = ["--allow-direct-agent-speech", "--tts-url", &speech_url]; - let mut session = ExpertSpokespersonTestSession::start_with_args( - endpoint, - if expert_voice { &own } else { &[] }, - ); + 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 { @@ -3370,7 +3358,7 @@ fn message_the_spokesperson(expert_voice: bool) { "relay":true }) }; - let mut reply = |session: &mut ExpertSpokespersonTestSession, request| { + let reply = |session: &mut ExpertSpokespersonTestSession, request| { session.send(request); loop { let message = session.recv(Duration::from_secs(2)); @@ -3403,18 +3391,15 @@ fn message_the_spokesperson(expert_voice: bool) { json!([&handoffs[1]]), "{state}" ); - assert!(speech_requests - .recv_timeout(Duration::from_millis(300)) - .is_err()); session.shutdown(); server.join().unwrap(); } #[test] -fn expert_voice_handoffs_survive_provider_expiry_and_a_current_reply_answers_them() { +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 (note_tx, note_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() @@ -3461,23 +3446,20 @@ fn expert_voice_handoffs_survive_provider_expiry_and_a_current_reply_answers_the ) .await; - // The open handoff doesn't stop the replacement, which is told of it. + // 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" { - continue; - } - send_realtime_json( - &mut replacement, - json!({"type":"conversation.item.created","item":{"id":seed["item"]["id"]}}), - ) - .await; - if text.contains("do not hand them off again") { - let _ = note_tx.try_send(seed); + if seed["type"] == "conversation.item.create" { + send_realtime_json( + &mut replacement, + json!({"type":"conversation.item.created","item":{"id":seed["item"]["id"]}}), + ) + .await; } } }); @@ -3487,14 +3469,10 @@ fn expert_voice_handoffs_survive_provider_expiry_and_a_current_reply_answers_the endpoint, &["--allow-direct-agent-speech", "--tts-url", &speech_url], ); - let note = note_rx.recv_timeout(Duration::from_secs(3)).unwrap(); - assert!( - note.to_string().contains("- inspect the repository"), - "{note}" - ); + renewed_rx.recv_timeout(Duration::from_secs(3)).unwrap(); - // A reply written before everything since waits for it, and once it - // acknowledges the latest, naming no handoff, it answers them all. + // 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, From f822edc5fc0fe8614c2827b3c5579e2e99a40d55 Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 08:18:34 -0400 Subject: [PATCH 09/24] berd-call: find the PCM descriptor after --allow-direct-agent-speech The voice session read its arguments in pairs to find --pcm-output-fd, which the host appends last. The valueless --allow-direct-agent-speech shifted the pairs, so every call started with it failed with "voice session event stream closed during startup". Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- src-tauri/crates/berd-call/src/main.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index 87a125304..655f7068b 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -6038,6 +6038,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()); @@ -11413,6 +11417,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", From a3ebee4805daf332990680a5a3c6494894f815dc Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 08:25:14 -0400 Subject: [PATCH 10/24] berd-call: retry a Spokesperson voice change the conversation overtook A Spokesperson voice or rate change builds a new realtime session, and if anyone spoke before it was ready, the change was rejected with "Spokesperson conversation changed during voice replacement", so a menu-bar change made mid-conversation never took. In a berd-call start call it is now tried again once the call is idle, with the conversation as it then stands, and reports one result when it applies. The Berd app's handling is unchanged. Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- src-tauri/crates/berd-call/PROTOCOL.md | 5 ++ src-tauri/crates/berd-call/src/main.rs | 53 +++++++++++++++-- .../berd-call/tests/session_protocol.rs | 59 +++++++++++++------ 3 files changed, 96 insertions(+), 21 deletions(-) diff --git a/src-tauri/crates/berd-call/PROTOCOL.md b/src-tauri/crates/berd-call/PROTOCOL.md index 1ff842ecf..d38454cab 100644 --- a/src-tauri/crates/berd-call/PROTOCOL.md +++ b/src-tauri/crates/berd-call/PROTOCOL.md @@ -263,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/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index 655f7068b..74f937c19 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -2796,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, @@ -3422,6 +3448,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() { @@ -3850,8 +3885,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, @@ -3868,12 +3903,13 @@ fn run_expert_spokesperson_session( &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 { @@ -3886,6 +3922,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, diff --git a/src-tauri/crates/berd-call/tests/session_protocol.rs b/src-tauri/crates/berd-call/tests/session_protocol.rs index 8b9f41860..8993d73bd 100644 --- a/src-tauri/crates/berd-call/tests/session_protocol.rs +++ b/src-tauri/crates/berd-call/tests/session_protocol.rs @@ -1590,7 +1590,7 @@ 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() { 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,6 +1664,29 @@ 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"], "new-voice"); + 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(); @@ -1682,18 +1705,19 @@ 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"], "new-voice"); + applied = true; } } rollback_seen_rx @@ -2278,6 +2302,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 +2349,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 +2366,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(); } From 963deb74bb2eb2a01e9d2597c8de15c8c55c4962 Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 08:43:26 -0400 Subject: [PATCH 11/24] berd-call: gather a lead before playing the Spokesperson's audio OpenAI sends the Spokesperson's audio about as fast as it plays. Playback sent it to the host only in whole 170 ms chunks and started on the first one, so the speaker often ran dry before the next chunk was complete, and any late delta left an audible gap. Gather 300 ms of each reply before it plays, then send each delta as it arrives. A test plays a reply arriving in real time with one 150 ms stall: whole chunks leave a 109 ms silence; the lead plays through. Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- src-tauri/crates/berd-call/src/main.rs | 26 ++-- .../crates/berd-call/src/session_audio.rs | 135 +++++++++++++++++- 2 files changed, 147 insertions(+), 14 deletions(-) diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index 74f937c19..6d60e8451 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -5209,6 +5209,9 @@ fn finish_expert_reply( Ok(()) } +/// The Spokesperson's audio gathered before each reply plays, 300 ms at 24 kHz: OpenAI sends it about as fast as it plays, so this covers a delta that comes late. +const SPOKESPERSON_AUDIO_LEAD_FRAMES: usize = 7_200; + fn spawn_live_playback( response_id: String, speech_id: u64, @@ -5218,16 +5221,19 @@ fn spawn_live_playback( completed: mpsc::Sender, ) -> Result { let active = Arc::new(AtomicBool::new(true)); - let output = Arc::new(RemotePcmAudioOutput::new( - speech_id, - TtsPcmSpec { - sample_rate: 24_000, - playback_rate: 1.0, - }, - transport, - Arc::clone(&active), - control, - )?); + let output = Arc::new( + RemotePcmAudioOutput::new( + speech_id, + TtsPcmSpec { + sample_rate: 24_000, + playback_rate: 1.0, + }, + transport, + Arc::clone(&active), + control, + )? + .streaming_after(SPOKESPERSON_AUDIO_LEAD_FRAMES), + ); let (sender, receiver) = mpsc::sync_channel::(64); let worker_output = Arc::clone(&output); let worker_response_id = response_id.clone(); diff --git a/src-tauri/crates/berd-call/src/session_audio.rs b/src-tauri/crates/berd-call/src/session_audio.rs index 0368d6a9d..e4fc2543c 100644 --- a/src-tauri/crates/berd-call/src/session_audio.rs +++ b/src-tauri/crates/berd-call/src/session_audio.rs @@ -2,7 +2,7 @@ use std::collections::VecDeque; use std::fs::File; use std::io; use std::os::fd::{AsRawFd, FromRawFd, RawFd}; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant}; @@ -190,6 +190,8 @@ pub struct RemotePcmAudioOutput { operation_timeout: Duration, minimum_accepted_runway_frames: u64, pending_samples: Mutex>, + /// Frames to gather before streaming each write as it comes, or `None` to send whole chunks. + stream_after: Option, state: Mutex, changed: Condvar, } @@ -236,6 +238,7 @@ impl RemotePcmAudioOutput { operation_timeout, minimum_accepted_runway_frames: accepted_audio_runway_frames(spec), pending_samples: Mutex::new(Vec::with_capacity(MAX_AUDIO_CHUNK_FRAMES)), + stream_after: None, state: Mutex::new(State { phase: Phase::New, begin_accepted: false, @@ -257,6 +260,12 @@ impl RemotePcmAudioOutput { }) } + /// Holds back the first `frames` of audio, then sends each write at once, for a source that arrives about as fast as it plays: what is held covers its late arrivals. + pub fn streaming_after(mut self, frames: usize) -> Self { + self.stream_after = Some(AtomicUsize::new(frames)); + self + } + pub fn start(&self) -> Result<(), String> { { let mut state = self.state.lock().expect("remote output state"); @@ -860,11 +869,18 @@ impl PcmAudioOutput for RemotePcmAudioOutput { .lock() .expect("remote pending PCM lock"); pending.extend_from_slice(samples); - let complete_len = pending.len() / MAX_AUDIO_CHUNK_FRAMES * MAX_AUDIO_CHUNK_FRAMES; - let tail = pending.split_off(complete_len); + let ready = match &self.stream_after { + None => pending.len() / MAX_AUDIO_CHUNK_FRAMES * MAX_AUDIO_CHUNK_FRAMES, + Some(held) if pending.len() >= held.load(Ordering::SeqCst) => { + held.store(0, Ordering::SeqCst); + pending.len() + } + Some(_) => 0, + }; + let tail = pending.split_off(ready); std::mem::replace(&mut *pending, tail) }; - for chunk in complete_samples.chunks_exact(MAX_AUDIO_CHUNK_FRAMES) { + for chunk in complete_samples.chunks(MAX_AUDIO_CHUNK_FRAMES) { self.write_chunk(chunk)?; } Ok(()) @@ -921,6 +937,7 @@ mod tests { use std::io::Read; use std::os::fd::IntoRawFd; use std::os::unix::net::UnixStream; + use std::sync::atomic::AtomicU64; use std::sync::Arc; use std::thread; @@ -1579,6 +1596,116 @@ mod tests { worker.join().unwrap().unwrap(); } + fn remote(stream_after: Option) -> (Arc, UnixStream) { + let (child, host) = UnixStream::pair().unwrap(); + let transport = unsafe { AudioPipeTransport::from_raw_fd(child.into_raw_fd()) }.unwrap(); + let spec = TtsPcmSpec { + sample_rate: 24_000, + playback_rate: 1.0, + }; + let output = RemotePcmAudioOutput::new( + 7, + spec, + Arc::new(transport), + Arc::new(AtomicBool::new(true)), + mpsc::channel().0, + ) + .unwrap(); + ( + Arc::new(match stream_after { + Some(frames) => output.streaming_after(frames), + None => output, + }), + host, + ) + } + + /// The longest silence, in milliseconds, between the first sound and the last that a host playing in real time hears from `output`, as each of `deltas` (its frames, and the millisecond it arrives) is written to it. + fn longest_gap( + (output, mut host): (Arc, UnixStream), + deltas: &[(usize, u64)], + ) -> f64 { + start(&output, &mut host); + let now = Arc::new(AtomicU64::new(0)); + let arrivals = Arc::new(Mutex::new(Vec::<(u64, usize)>::new())); + let player = { + let (output, now, arrivals) = + (Arc::clone(&output), Arc::clone(&now), Arc::clone(&arrivals)); + thread::spawn(move || loop { + let (kind, payload) = read_record(&mut host); + if kind == AUDIO_END_KIND { + return; + } + assert_eq!(kind, AUDIO_CHUNK_KIND); + arrivals + .lock() + .unwrap() + .push((now.load(Ordering::SeqCst), (payload.len() - 16) / 4)); + let sequence = u64::from_le_bytes(payload[8..16].try_into().unwrap()); + output + .handle_ack(AudioHostAck::ChunkAccepted { sequence }) + .unwrap(); + }) + }; + // When each chunk the host was sent starts and stops playing, and its frames. + let played = || { + let arrivals = arrivals.lock().unwrap(); + arrivals + .iter() + .scan(0.0, |end: &mut f64, &(at, frames)| { + let start = end.max(at as f64); + *end = start + frames as f64 / 24.0; + Some((start, *end, frames as u64)) + }) + .collect::>() + }; + for &(frames, at) in deltas { + now.store(at, Ordering::SeqCst); + let done = played() + .iter() + .filter(|(_, end, _)| *end <= at as f64) + .map(|(_, _, frames)| frames) + .sum(); + if done > output.played_frames() { + output + .handle_ack(AudioHostAck::Played { + played_frames: done, + }) + .unwrap(); + } + output.write(&vec![0.25; frames]).unwrap(); + } + output.finish_writes().unwrap(); + player.join().unwrap(); + played() + .windows(2) + .map(|pair| pair[1].0 - pair[0].1) + .fold(0.0, f64::max) + } + + #[test] + fn streaming_after_a_lead_plays_a_realtime_source_through_a_stall() { + // A reply arriving as fast as it plays, in 100 ms deltas, two of them held up until 950 ms. + let deltas: Vec<_> = (0..20) + .map(|index| { + ( + 2400, + if index == 8 || index == 9 { + 950 + } else { + index * 100 + }, + ) + }) + .collect(); + let chunked = longest_gap(remote(None), &deltas); + assert!( + chunked > 100.0, + "whole chunks fell silent for only {chunked} ms" + ); + assert_eq!(longest_gap(remote(Some(7200)), &deltas), 0.0); + } + #[test] fn empty_output_fails_before_emitting_audio_end() { let (output, mut host) = fixture(); From cd90b8c83e8d4528a108d4aed44d55e4b9dabd8b Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 08:48:32 -0400 Subject: [PATCH 12/24] berd-call: test changing every setting in a live call On a live realtime call, in both modes, change the Spokesperson's speed, then its voice, then the input policy, then mute and unmute, and check each one lands. With a separate agent voice, also change the agent's voice and speed. Check that the Spokesperson's realtime session is rebuilt with each new voice and speed. Run the retry test for a change the user overtook in both modes as well. With a separate agent voice, the Spokesperson rate change it retries fails without the retry. On the host, a Spokesperson voice or rate change keeps the other setting and the revision, and is refused when the call has no separate Spokesperson voice. Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- .../crates/berd-call/src/host_session.rs | 58 ++++++ .../berd-call/tests/session_protocol.rs | 193 +++++++++++++++++- 2 files changed, 242 insertions(+), 9 deletions(-) diff --git a/src-tauri/crates/berd-call/src/host_session.rs b/src-tauri/crates/berd-call/src/host_session.rs index dd0dfe108..537d5f522 100644 --- a/src-tauri/crates/berd-call/src/host_session.rs +++ b/src-tauri/crates/berd-call/src/host_session.rs @@ -4438,6 +4438,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") diff --git a/src-tauri/crates/berd-call/tests/session_protocol.rs b/src-tauri/crates/berd-call/tests/session_protocol.rs index 8993d73bd..860dd9f5a 100644 --- a/src-tauri/crates/berd-call/tests/session_protocol.rs +++ b/src-tauri/crates/berd-call/tests/session_protocol.rs @@ -1591,6 +1591,34 @@ fn expert_spokesperson_voice_change_swaps_atomically_and_flushes_gated_pcm_once( #[test] 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} + }), + ); +} + +/// 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); @@ -1669,7 +1697,8 @@ fn user_activity_during_voice_cutover_rolls_back_then_retries_once_idle() { 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"], "new-voice"); + 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 { @@ -1691,13 +1720,8 @@ fn user_activity_during_voice_cutover_rolls_back_then_retries_once_idle() { }); 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(); @@ -1716,7 +1740,8 @@ fn user_activity_during_voice_cutover_rolls_back_then_retries_once_idle() { assert!(saw_user, "{message}"); assert_eq!(message["outcome"], "applied", "{message}"); assert_eq!(message["snapshot"]["revision"], 2); - assert_eq!(message["snapshot"]["voice"], "new-voice"); + assert_eq!(message["snapshot"]["voice"], request["settings"]["voice"]); + assert_eq!(message["snapshot"]["rate"], request["settings"]["rate"]); applied = true; } } @@ -1727,6 +1752,156 @@ fn user_activity_during_voice_cutover_rolls_back_then_retries_once_idle() { 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); From 2a053509d1960b3b8076003eb6cbb8a0cb632d96 Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 09:00:55 -0400 Subject: [PATCH 13/24] Revert "berd-call: gather a lead before playing the Spokesperson's audio" This reverts commit aad01ee8. Its premise was wrong: measured on six live replies, OpenAI Realtime sends a reply's audio 3 to 5.5 times faster than it plays, in 150 to 400 ms deltas, so a lead covers no late arrival and only delays the first sound. Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- src-tauri/crates/berd-call/src/main.rs | 26 ++-- .../crates/berd-call/src/session_audio.rs | 135 +----------------- 2 files changed, 14 insertions(+), 147 deletions(-) diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index 6d60e8451..74f937c19 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -5209,9 +5209,6 @@ fn finish_expert_reply( Ok(()) } -/// The Spokesperson's audio gathered before each reply plays, 300 ms at 24 kHz: OpenAI sends it about as fast as it plays, so this covers a delta that comes late. -const SPOKESPERSON_AUDIO_LEAD_FRAMES: usize = 7_200; - fn spawn_live_playback( response_id: String, speech_id: u64, @@ -5221,19 +5218,16 @@ fn spawn_live_playback( completed: mpsc::Sender, ) -> Result { let active = Arc::new(AtomicBool::new(true)); - let output = Arc::new( - RemotePcmAudioOutput::new( - speech_id, - TtsPcmSpec { - sample_rate: 24_000, - playback_rate: 1.0, - }, - transport, - Arc::clone(&active), - control, - )? - .streaming_after(SPOKESPERSON_AUDIO_LEAD_FRAMES), - ); + let output = Arc::new(RemotePcmAudioOutput::new( + speech_id, + TtsPcmSpec { + sample_rate: 24_000, + playback_rate: 1.0, + }, + transport, + Arc::clone(&active), + control, + )?); let (sender, receiver) = mpsc::sync_channel::(64); let worker_output = Arc::clone(&output); let worker_response_id = response_id.clone(); diff --git a/src-tauri/crates/berd-call/src/session_audio.rs b/src-tauri/crates/berd-call/src/session_audio.rs index e4fc2543c..0368d6a9d 100644 --- a/src-tauri/crates/berd-call/src/session_audio.rs +++ b/src-tauri/crates/berd-call/src/session_audio.rs @@ -2,7 +2,7 @@ use std::collections::VecDeque; use std::fs::File; use std::io; use std::os::fd::{AsRawFd, FromRawFd, RawFd}; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant}; @@ -190,8 +190,6 @@ pub struct RemotePcmAudioOutput { operation_timeout: Duration, minimum_accepted_runway_frames: u64, pending_samples: Mutex>, - /// Frames to gather before streaming each write as it comes, or `None` to send whole chunks. - stream_after: Option, state: Mutex, changed: Condvar, } @@ -238,7 +236,6 @@ impl RemotePcmAudioOutput { operation_timeout, minimum_accepted_runway_frames: accepted_audio_runway_frames(spec), pending_samples: Mutex::new(Vec::with_capacity(MAX_AUDIO_CHUNK_FRAMES)), - stream_after: None, state: Mutex::new(State { phase: Phase::New, begin_accepted: false, @@ -260,12 +257,6 @@ impl RemotePcmAudioOutput { }) } - /// Holds back the first `frames` of audio, then sends each write at once, for a source that arrives about as fast as it plays: what is held covers its late arrivals. - pub fn streaming_after(mut self, frames: usize) -> Self { - self.stream_after = Some(AtomicUsize::new(frames)); - self - } - pub fn start(&self) -> Result<(), String> { { let mut state = self.state.lock().expect("remote output state"); @@ -869,18 +860,11 @@ impl PcmAudioOutput for RemotePcmAudioOutput { .lock() .expect("remote pending PCM lock"); pending.extend_from_slice(samples); - let ready = match &self.stream_after { - None => pending.len() / MAX_AUDIO_CHUNK_FRAMES * MAX_AUDIO_CHUNK_FRAMES, - Some(held) if pending.len() >= held.load(Ordering::SeqCst) => { - held.store(0, Ordering::SeqCst); - pending.len() - } - Some(_) => 0, - }; - let tail = pending.split_off(ready); + let complete_len = pending.len() / MAX_AUDIO_CHUNK_FRAMES * MAX_AUDIO_CHUNK_FRAMES; + let tail = pending.split_off(complete_len); std::mem::replace(&mut *pending, tail) }; - for chunk in complete_samples.chunks(MAX_AUDIO_CHUNK_FRAMES) { + for chunk in complete_samples.chunks_exact(MAX_AUDIO_CHUNK_FRAMES) { self.write_chunk(chunk)?; } Ok(()) @@ -937,7 +921,6 @@ mod tests { use std::io::Read; use std::os::fd::IntoRawFd; use std::os::unix::net::UnixStream; - use std::sync::atomic::AtomicU64; use std::sync::Arc; use std::thread; @@ -1596,116 +1579,6 @@ mod tests { worker.join().unwrap().unwrap(); } - fn remote(stream_after: Option) -> (Arc, UnixStream) { - let (child, host) = UnixStream::pair().unwrap(); - let transport = unsafe { AudioPipeTransport::from_raw_fd(child.into_raw_fd()) }.unwrap(); - let spec = TtsPcmSpec { - sample_rate: 24_000, - playback_rate: 1.0, - }; - let output = RemotePcmAudioOutput::new( - 7, - spec, - Arc::new(transport), - Arc::new(AtomicBool::new(true)), - mpsc::channel().0, - ) - .unwrap(); - ( - Arc::new(match stream_after { - Some(frames) => output.streaming_after(frames), - None => output, - }), - host, - ) - } - - /// The longest silence, in milliseconds, between the first sound and the last that a host playing in real time hears from `output`, as each of `deltas` (its frames, and the millisecond it arrives) is written to it. - fn longest_gap( - (output, mut host): (Arc, UnixStream), - deltas: &[(usize, u64)], - ) -> f64 { - start(&output, &mut host); - let now = Arc::new(AtomicU64::new(0)); - let arrivals = Arc::new(Mutex::new(Vec::<(u64, usize)>::new())); - let player = { - let (output, now, arrivals) = - (Arc::clone(&output), Arc::clone(&now), Arc::clone(&arrivals)); - thread::spawn(move || loop { - let (kind, payload) = read_record(&mut host); - if kind == AUDIO_END_KIND { - return; - } - assert_eq!(kind, AUDIO_CHUNK_KIND); - arrivals - .lock() - .unwrap() - .push((now.load(Ordering::SeqCst), (payload.len() - 16) / 4)); - let sequence = u64::from_le_bytes(payload[8..16].try_into().unwrap()); - output - .handle_ack(AudioHostAck::ChunkAccepted { sequence }) - .unwrap(); - }) - }; - // When each chunk the host was sent starts and stops playing, and its frames. - let played = || { - let arrivals = arrivals.lock().unwrap(); - arrivals - .iter() - .scan(0.0, |end: &mut f64, &(at, frames)| { - let start = end.max(at as f64); - *end = start + frames as f64 / 24.0; - Some((start, *end, frames as u64)) - }) - .collect::>() - }; - for &(frames, at) in deltas { - now.store(at, Ordering::SeqCst); - let done = played() - .iter() - .filter(|(_, end, _)| *end <= at as f64) - .map(|(_, _, frames)| frames) - .sum(); - if done > output.played_frames() { - output - .handle_ack(AudioHostAck::Played { - played_frames: done, - }) - .unwrap(); - } - output.write(&vec![0.25; frames]).unwrap(); - } - output.finish_writes().unwrap(); - player.join().unwrap(); - played() - .windows(2) - .map(|pair| pair[1].0 - pair[0].1) - .fold(0.0, f64::max) - } - - #[test] - fn streaming_after_a_lead_plays_a_realtime_source_through_a_stall() { - // A reply arriving as fast as it plays, in 100 ms deltas, two of them held up until 950 ms. - let deltas: Vec<_> = (0..20) - .map(|index| { - ( - 2400, - if index == 8 || index == 9 { - 950 - } else { - index * 100 - }, - ) - }) - .collect(); - let chunked = longest_gap(remote(None), &deltas); - assert!( - chunked > 100.0, - "whole chunks fell silent for only {chunked} ms" - ); - assert_eq!(longest_gap(remote(Some(7200)), &deltas), 0.0); - } - #[test] fn empty_output_fails_before_emitting_audio_end() { let (output, mut host) = fixture(); From d314cdc6692cbd273678ab5cba2fb1f410abea69 Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 09:05:19 -0400 Subject: [PATCH 14/24] berd-call: keep a second of audio ahead of the host's played reports The host reports a chunk played only when the output device has played it: about 60 ms after it is heard on a MacBook's speakers, and a few hundred more on Bluetooth headphones. Playback held at most 400 ms beyond what was reported played (less 100 ms of delivery safety), so on headphones the player ran dry while waiting for credit, and the Spokesperson's speech, and an agent's, came out in short gaps. Let the host hold a second beyond its reports, which plays through reports up to about 800 ms late. A test plays 3 s of audio with reports 300 ms late: the old limit leaves 1041 ms of silence; this leaves none. Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- .../crates/berd-call/src/session_audio.rs | 94 +++++++++++++++++-- 1 file changed, 88 insertions(+), 6 deletions(-) diff --git a/src-tauri/crates/berd-call/src/session_audio.rs b/src-tauri/crates/berd-call/src/session_audio.rs index 0368d6a9d..210adbe50 100644 --- a/src-tauri/crates/berd-call/src/session_audio.rs +++ b/src-tauri/crates/berd-call/src/session_audio.rs @@ -17,7 +17,9 @@ 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); @@ -1040,8 +1042,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 +1064,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 +1527,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 +1581,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(); From 24123fdb887ece665712fab2a8ecd38f0725b3c6 Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 09:50:41 -0400 Subject: [PATCH 15/24] berd-call: let the host ignore records for speech it already ended When the host's player stops, as when the output device changes, the host ends that speech and reports audio_failed. The session can still send chunk, end or cancel records for it before hearing the report. The host treated those as protocol errors and ended the call. It now drops late chunk and end records for the speech it retired and answers a late cancel with what it played. Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- .../crates/berd-call/src/host_session.rs | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src-tauri/crates/berd-call/src/host_session.rs b/src-tauri/crates/berd-call/src/host_session.rs index 537d5f522..507bc9e82 100644 --- a/src-tauri/crates/berd-call/src/host_session.rs +++ b/src-tauri/crates/berd-call/src/host_session.rs @@ -2309,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, @@ -2523,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())?; @@ -2555,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())?; @@ -2563,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())?; @@ -4612,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!( From 078da1748bb5cd7f31089791c4f939bf36aa9ab6 Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 09:50:42 -0400 Subject: [PATCH 16/24] berd-call: keep a realtime call going when the host's player stops A Spokesperson reply whose host player stopped ended the whole call with "host audio output failed". The session now ends that reply where the host stopped, as if the user had interrupted it: the provider's item is truncated to what played, the transcript is published as interrupted, and the next reply gets a new player. Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- src-tauri/crates/berd-call/src/main.rs | 9 +- .../crates/berd-call/src/session_audio.rs | 14 +- .../berd-call/tests/session_protocol.rs | 144 +++++++++++++++++- 3 files changed, 157 insertions(+), 10 deletions(-) diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index 74f937c19..9473fd0ba 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::{ @@ -4196,7 +4196,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"), @@ -4207,6 +4208,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, diff --git a/src-tauri/crates/berd-call/src/session_audio.rs b/src-tauri/crates/berd-call/src/session_audio.rs index 210adbe50..7f2aabbc6 100644 --- a/src-tauri/crates/berd-call/src/session_audio.rs +++ b/src-tauri/crates/berd-call/src/session_audio.rs @@ -25,6 +25,8 @@ 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 { @@ -621,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(()) } @@ -668,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 @@ -712,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()), _ => {} @@ -761,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) { @@ -891,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(()) } @@ -914,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)] diff --git a/src-tauri/crates/berd-call/tests/session_protocol.rs b/src-tauri/crates/berd-call/tests/session_protocol.rs index 860dd9f5a..24b271bc8 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); From 1f48fc55c9ac5052ed1c604bf59b2bdba93b5a75 Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 11:00:05 -0400 Subject: [PATCH 17/24] Keep microphone input flowing while an input reset clears Switching the output device restarts the microphone and resets the Spokesperson's input. The realtime loop waited for the provider to confirm the clear, so microphone audio stopped draining, the 32-frame session queue filled, and the session failed with "session PCM input queue is full". Input resets and mutes now send the clear without waiting. The loop answers them in order once the provider confirms, coalesces a request that arrives while a clear is outstanding into one follow-up clear, and holds a pending voice change until no clear is outstanding. Resets share the input queue with microphone audio, so a clear discards exactly the audio sent before it. Signed-off-by: John Tennant Co-Authored-By: Claude Opus 5.5 --- src-tauri/crates/berd-call/src/main.rs | 233 +++++++++++++----- .../berd-call/src/openai_spokesperson.rs | 90 +++++-- .../berd-call/tests/session_protocol.rs | 65 +++++ 3 files changed, 304 insertions(+), 84 deletions(-) diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index 9473fd0ba..65ce8660c 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -3161,30 +3161,63 @@ 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. +/// Controls answer in order once no clear is outstanding; one that needs a clear while another is outstanding gets the next. +#[derive(Default)] +struct InputResets { + clearing: Option>>, + again: bool, + 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_none() + } + + fn apply( + &mut self, + reply: SessionMessage, + clear: bool, + reset_input: impl FnOnce() -> Result>, String>, + writer: &mut impl Write, + ) -> Result<(), String> { + if self.idle() { + if !clear { + return write_message(writer, &reply); + } + self.clearing = Some(reset_input()?); + } else { + self.again |= clear; + } + self.replies.push(reply); + Ok(()) + } + + fn poll( + &mut self, + reset_input: impl FnOnce() -> Result>, String>, + writer: &mut impl Write, + ) -> Result<(), String> { + let Some(clearing) = &self.clearing else { + return Ok(()); + }; + match clearing.try_recv() { + Err(mpsc::TryRecvError::Empty) => return Ok(()), + Err(mpsc::TryRecvError::Disconnected) => { + return Err("Spokesperson runtime is closed".into()) + } + Ok(result) => result?, + } + if std::mem::take(&mut self.again) { + self.clearing = Some(reset_input()?); + return Ok(()); + } + self.clearing = None; + self.replies + .drain(..) + .try_for_each(|reply| write_message(writer, &reply)) + } } fn set_spokesperson_input_policy( @@ -3377,12 +3410,17 @@ 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( + || runtime.as_ref().expect("initialized runtime").reset_input(), + &mut writer, + )?; let work = spokesperson_host_work( &turn_gate, active.as_ref(), @@ -3415,7 +3453,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(), @@ -4965,10 +5007,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, )?; @@ -4983,8 +5025,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, )?; @@ -9013,31 +9056,104 @@ 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(); + resets.poll(reset_input, &mut output).unwrap(); + assert_eq!(clears.borrow().len(), 1); + assert!(output.is_empty()); + // The reset asked for during the first clear needs a clear of its own. + clears.borrow()[0].send(Ok(())).unwrap(); + resets.poll(reset_input, &mut output).unwrap(); + assert_eq!(clears.borrow().len(), 2); + assert!(output.is_empty()); + clears.borrow()[1].send(Ok(())).unwrap(); + resets.poll(reset_input, &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(reset_input, &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, @@ -9050,8 +9166,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, @@ -9068,15 +9182,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] diff --git a/src-tauri/crates/berd-call/src/openai_spokesperson.rs b/src-tauri/crates/berd-call/src/openai_spokesperson.rs index ba57624f6..1141185d6 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> { @@ -590,18 +602,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?; } @@ -719,7 +721,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", @@ -1942,6 +1945,49 @@ 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); + } + #[test] fn output_truncation_timeout_is_bounded() { let now = tokio::time::Instant::now(); diff --git a/src-tauri/crates/berd-call/tests/session_protocol.rs b/src-tauri/crates/berd-call/tests/session_protocol.rs index 24b271bc8..e21b0df77 100644 --- a/src-tauri/crates/berd-call/tests/session_protocol.rs +++ b/src-tauri/crates/berd-call/tests/session_protocol.rs @@ -2217,6 +2217,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); From 4f54948ebcabfc76a6121d237fc273c512846a34 Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 11:29:38 -0400 Subject: [PATCH 18/24] Adapt the Expert reply tests to direct agent speech The tests restacked from below still started sessions with `--expert-voice tts` and built speech requests without `relay`. Signed-off-by: John Tennant Co-Authored-By: Claude Opus 5.5 --- src-tauri/crates/berd-call/src/main.rs | 1 + src-tauri/crates/berd-call/tests/session_protocol.rs | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index 65ce8660c..5405fdaf1 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -9753,6 +9753,7 @@ mod tests { resolved_handoff_ids: Vec::new(), voice: Some(voice.into()), language: None, + relay: false, }) }; let next = || { diff --git a/src-tauri/crates/berd-call/tests/session_protocol.rs b/src-tauri/crates/berd-call/tests/session_protocol.rs index e21b0df77..041cb5c57 100644 --- a/src-tauri/crates/berd-call/tests/session_protocol.rs +++ b/src-tauri/crates/berd-call/tests/session_protocol.rs @@ -3327,7 +3327,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", From 986a17edfca3f0811c53baf8acf0a64ea2791c13 Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 11:34:00 -0400 Subject: [PATCH 19/24] Say a held message before retrying the voice change it waited for In Berd mode, a message-spokesperson that arrived while a Spokesperson voice change was being built was held for the change, but the held message made the change unsafe. The change was rejected, queued and restarted at once, so neither could ever go through. Let a held directive go before a queued change starts again, and keep queued changes from holding directives back. Signed-off-by: John Tennant Co-Authored-By: Claude Opus 5.5 --- src-tauri/crates/berd-call/src/main.rs | 10 ++- .../berd-call/tests/session_protocol.rs | 69 +++++++++++++++++++ 2 files changed, 76 insertions(+), 3 deletions(-) diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index 5405fdaf1..870ccf737 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -3285,6 +3285,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, @@ -3293,7 +3294,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( @@ -3539,6 +3541,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) @@ -4374,7 +4377,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( @@ -4614,7 +4617,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(), ); diff --git a/src-tauri/crates/berd-call/tests/session_protocol.rs b/src-tauri/crates/berd-call/tests/session_protocol.rs index 041cb5c57..195c460e4 100644 --- a/src-tauri/crates/berd-call/tests/session_protocol.rs +++ b/src-tauri/crates/berd-call/tests/session_protocol.rs @@ -1756,6 +1756,75 @@ fn a_spokesperson_rate_change_the_user_overtook_is_retried_beside_the_agents_voi ); } +#[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(); From cad868b178762e2862726b685e2830df381362c8 Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 11:39:47 -0400 Subject: [PATCH 20/24] Give each input reset its own clear A reset that arrived while another clear was outstanding was folded into one follow-up clear sent only after the first was confirmed, so audio heard between the two controls survived the second reset. Send every clear where its control arrives and answer the queued controls once the provider has confirmed them all, in order. Signed-off-by: John Tennant Co-Authored-By: Claude Opus 5.5 --- src-tauri/crates/berd-call/src/main.rs | 64 ++++++----------- .../berd-call/src/openai_spokesperson.rs | 71 +++++++++++++++---- 2 files changed, 80 insertions(+), 55 deletions(-) diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index 870ccf737..f1865c15c 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -3162,17 +3162,16 @@ fn spokesperson_pcm_allowed( } /// Input controls waiting on the provider to clear its input buffer, so microphone audio keeps flowing meanwhile. -/// Controls answer in order once no clear is outstanding; one that needs a clear while another is outstanding gets the next. +/// Each clear goes out where its control arrived; controls answer in order once no clear is outstanding. #[derive(Default)] struct InputResets { - clearing: Option>>, - again: bool, + clearing: VecDeque>>, replies: Vec, } impl InputResets { fn idle(&self) -> bool { - self.clearing.is_none() + self.clearing.is_empty() } fn apply( @@ -3182,38 +3181,26 @@ impl InputResets { reset_input: impl FnOnce() -> Result>, String>, writer: &mut impl Write, ) -> Result<(), String> { - if self.idle() { - if !clear { - return write_message(writer, &reply); - } - self.clearing = Some(reset_input()?); - } else { - self.again |= clear; + 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, - reset_input: impl FnOnce() -> Result>, String>, - writer: &mut impl Write, - ) -> Result<(), String> { - let Some(clearing) = &self.clearing else { - return Ok(()); - }; - match clearing.try_recv() { - Err(mpsc::TryRecvError::Empty) => return Ok(()), - Err(mpsc::TryRecvError::Disconnected) => { - return Err("Spokesperson runtime is closed".into()) + 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?, } - Ok(result) => result?, - } - if std::mem::take(&mut self.again) { - self.clearing = Some(reset_input()?); - return Ok(()); + self.clearing.pop_front(); } - self.clearing = None; self.replies .drain(..) .try_for_each(|reply| write_message(writer, &reply)) @@ -3419,10 +3406,7 @@ fn run_expert_spokesperson_session( loop { if initialized { - input_resets.poll( - || runtime.as_ref().expect("initialized runtime").reset_input(), - &mut writer, - )?; + input_resets.poll(&mut writer)?; let work = spokesperson_host_work( &turn_gate, active.as_ref(), @@ -9099,17 +9083,15 @@ mod tests { &mut output, ) .unwrap(); - resets.poll(reset_input, &mut output).unwrap(); - assert_eq!(clears.borrow().len(), 1); + // 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()); - - // The reset asked for during the first clear needs a clear of its own. clears.borrow()[0].send(Ok(())).unwrap(); - resets.poll(reset_input, &mut output).unwrap(); - assert_eq!(clears.borrow().len(), 2); + resets.poll(&mut output).unwrap(); assert!(output.is_empty()); clears.borrow()[1].send(Ok(())).unwrap(); - resets.poll(reset_input, &mut output).unwrap(); + resets.poll(&mut output).unwrap(); assert!(resets.idle()); assert_eq!( messages(&output), @@ -9150,7 +9132,7 @@ mod tests { .send(Err("provider refused".into())) .unwrap(); assert_eq!( - resets.poll(reset_input, &mut output).unwrap_err(), + resets.poll(&mut output).unwrap_err(), "provider refused" ); } diff --git a/src-tauri/crates/berd-call/src/openai_spokesperson.rs b/src-tauri/crates/berd-call/src/openai_spokesperson.rs index 1141185d6..2c6c62737 100644 --- a/src-tauri/crates/berd-call/src/openai_spokesperson.rs +++ b/src-tauri/crates/berd-call/src/openai_spokesperson.rs @@ -500,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)); @@ -536,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 { @@ -561,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()); } @@ -615,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(), )); @@ -627,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, @@ -648,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}"); @@ -929,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(())); } } @@ -1042,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()) @@ -1988,6 +1987,50 @@ mod tests { 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(); From edd6abf66070ae629dd041a533e79ed65015c52d Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 11:41:28 -0400 Subject: [PATCH 21/24] Adapt the Expert reply interruption tests to direct agent speech Signed-off-by: John Tennant Co-Authored-By: Claude Opus 5.5 --- src-tauri/crates/berd-call/tests/session_protocol.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src-tauri/crates/berd-call/tests/session_protocol.rs b/src-tauri/crates/berd-call/tests/session_protocol.rs index 195c460e4..04597afac 100644 --- a/src-tauri/crates/berd-call/tests/session_protocol.rs +++ b/src-tauri/crates/berd-call/tests/session_protocol.rs @@ -3317,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})); From 33a47fe089a7e8dec4e5141b11eb77bbea829161 Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 11:46:45 -0400 Subject: [PATCH 22/24] Format the input reset test Signed-off-by: John Tennant Co-Authored-By: Claude Opus 5.5 --- src-tauri/crates/berd-call/src/main.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index f1865c15c..30855a02e 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -9131,10 +9131,7 @@ mod tests { clears.borrow()[2] .send(Err("provider refused".into())) .unwrap(); - assert_eq!( - resets.poll(&mut output).unwrap_err(), - "provider refused" - ); + assert_eq!(resets.poll(&mut output).unwrap_err(), "provider refused"); } #[test] From d3189a0f0f8972b0c97f3dcd0ba6c2e61785abcd Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 11:52:46 -0400 Subject: [PATCH 23/24] Let a stopped playback worker's result settle its reply When the host's player stops, the Spokesperson playback worker sends its result and stops taking audio. Provider audio that arrived in the meantime hit the closed worker first and ended the call, before the loop read the result that interrupts the reply where it was heard. Drop that audio instead and let the result settle the reply. Signed-off-by: John Tennant Co-Authored-By: Claude Opus 5.5 --- src-tauri/crates/berd-call/src/main.rs | 38 ++++++++++++++++++-------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index 30855a02e..c8f67a226 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -3792,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") } @@ -5624,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") @@ -5635,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") } @@ -9307,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); From 0fc4238fdd61dba0009110d91b351054a6dd1ed7 Mon Sep 17 00:00:00 2001 From: John Tennant Date: Tue, 20 Oct 2026 13:20:58 -0400 Subject: [PATCH 24/24] Adapt the Expert reply fixes to direct agent speech The output_ready gate and failure tests restacked from below used the reply's old optional text and started sessions with `--expert-voice tts`. A call that lets the agent speak holds no handoff open, so the failure tests now check only what the Spokesperson is told. Signed-off-by: John Tennant Co-Authored-By: Claude Opus 5.5 --- src-tauri/crates/berd-call/src/main.rs | 4 +- .../berd-call/tests/session_protocol.rs | 49 +++++-------------- 2 files changed, 14 insertions(+), 39 deletions(-) diff --git a/src-tauri/crates/berd-call/src/main.rs b/src-tauri/crates/berd-call/src/main.rs index c8f67a226..11ae20517 100644 --- a/src-tauri/crates/berd-call/src/main.rs +++ b/src-tauri/crates/berd-call/src/main.rs @@ -4628,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; @@ -4640,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, diff --git a/src-tauri/crates/berd-call/tests/session_protocol.rs b/src-tauri/crates/berd-call/tests/session_protocol.rs index 04597afac..964da9e72 100644 --- a/src-tauri/crates/berd-call/tests/session_protocol.rs +++ b/src-tauri/crates/berd-call/tests/session_protocol.rs @@ -3590,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", @@ -3635,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); @@ -3655,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") { @@ -3688,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}"); @@ -3727,35 +3711,26 @@ 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]