mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Add live WebRTC voice conversations to the TUI (#43581)
## What changed - Add feature-gated `/voice`, `/voice mute`, and `/voice stop` commands with local WebRTC audio and app-server signaling. - Show live transcripts, conversation status, and microphone and speaker levels. Preserve captions and undelivered answers across thread switches. - Speak final answers from voice handoffs while keeping delegated reasoning and commentary hidden and typed answers unspoken. - Retry eligible startup failures once and clean up voice sessions on thread switches and disconnects. - Stop voice and block late handoffs after a misalignment policy violation. Remove realtime event payloads and spoken text from receipt and debug logs. ## Testing Add coverage for voice command mapping, rejected starts, disconnect cleanup, delegated final-answer speech, late handoff rejection, and transcript and footer rendering. GitOrigin-RevId: 11def1f86b0e023b21d0d92072d6636ccad89815
This commit is contained in:
1 parent
4110342321
commit
b01c3986fd
70 files changed
+4421
-69
No files matched your search
@@ -19,6 +19,22 @@ use crate::message_reader::MessageReader;
|
||||
const DEADLINE: Duration = Duration::from_secs(/*secs*/ 5);
|
||||
const RUNTIME_INITIALIZATION_DEADLINE: Duration = Duration::from_secs(/*secs*/ 30);
|
||||
|
||||
/// Startup failures eligible for recovery remain distinct from all other failures.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ConnectionError {
|
||||
NegotiationTimedOut,
|
||||
Failed,
|
||||
}
|
||||
impl std::fmt::Display for ConnectionError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::NegotiationTimedOut => "voice negotiation timed out",
|
||||
Self::Failed => "voice connection failed",
|
||||
})
|
||||
}
|
||||
}
|
||||
impl std::error::Error for ConnectionError {}
|
||||
|
||||
/// Owns one helper. Dropping it terminates the process and leaves its waiter to reap it.
|
||||
/// A successful handshake establishes compatibility only, not an active audio session.
|
||||
pub struct VoiceHost {
|
||||
@@ -94,6 +110,12 @@ impl VoiceHost {
|
||||
Duration::from_secs(/*secs*/ 20),
|
||||
)
|
||||
.await?;
|
||||
if response == (Message::TransportTimedOut {}) {
|
||||
self.process.terminate();
|
||||
// A lost exit notification or failed cleanup is not retryable.
|
||||
timeout(DEADLINE, &mut self.exit).await??;
|
||||
return Err(ConnectionError::NegotiationTimedOut.into());
|
||||
}
|
||||
ensure!(
|
||||
response == Message::TransportReady {},
|
||||
"unexpected voice helper response"
|
||||
|
||||
@@ -61,3 +61,52 @@ async fn cancelling_initialization_terminates_the_owned_helper() -> anyhow::Resu
|
||||
tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 1), spawned.exit_rx).await??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn negotiation_timeout_waits_for_helper_exit_before_allowing_retry() -> anyhow::Result<()> {
|
||||
let spawned = codex_utils_pty::spawn_pipe_process(
|
||||
std::path::Path::new("/bin/sleep"),
|
||||
&["30".to_owned()],
|
||||
std::path::Path::new("/"),
|
||||
&child_environment(std::iter::empty()),
|
||||
/*arg0*/ &None,
|
||||
&[],
|
||||
)
|
||||
.await?;
|
||||
let (output, receiver) = tokio::sync::mpsc::channel(/*buffer*/ 1);
|
||||
output
|
||||
.send(crate::encode_frame(&crate::Message::TransportTimedOut {})?)
|
||||
.await?;
|
||||
let (reaped, exit) = tokio::sync::oneshot::channel();
|
||||
let host = super::VoiceHost {
|
||||
process: spawned.session,
|
||||
output: crate::message_reader::MessageReader::new(receiver),
|
||||
exit,
|
||||
};
|
||||
let answer = crate::SessionDescription::try_from("synthetic-answer".to_owned()).unwrap();
|
||||
let mut connection = Box::pin(host.apply_answer(answer));
|
||||
std::future::poll_fn(|cx| {
|
||||
assert!(std::future::Future::poll(connection.as_mut(), cx).is_pending());
|
||||
std::task::Poll::Ready(())
|
||||
})
|
||||
.await;
|
||||
let code =
|
||||
tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 1), spawned.exit_rx).await??;
|
||||
// The process has exited, but the explicit reaping acknowledgement is still required.
|
||||
std::future::poll_fn(|cx| {
|
||||
assert!(std::future::Future::poll(connection.as_mut(), cx).is_pending());
|
||||
std::task::Poll::Ready(())
|
||||
})
|
||||
.await;
|
||||
reaped.send(code).unwrap();
|
||||
let error = connection
|
||||
.await
|
||||
.err()
|
||||
.expect("timeout must not return a connected helper");
|
||||
assert_eq!(
|
||||
error.downcast_ref::<crate::ConnectionError>(),
|
||||
Some(&crate::ConnectionError::NegotiationTimedOut)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -3,6 +3,7 @@ mod message_reader;
|
||||
mod protocol;
|
||||
mod session;
|
||||
|
||||
pub use client::ConnectionError;
|
||||
pub use client::VoiceHost;
|
||||
pub use protocol::AudioControls;
|
||||
pub use protocol::AudioState;
|
||||
|
||||
@@ -81,6 +81,7 @@ pub enum Message {
|
||||
Offer { sdp: SessionDescription },
|
||||
ApplyAnswer { sdp: SessionDescription },
|
||||
TransportReady {},
|
||||
TransportTimedOut {},
|
||||
OpenDevices {},
|
||||
DevicesOpened {},
|
||||
SetAudioControls { controls: AudioControls },
|
||||
|
||||
@@ -26,7 +26,10 @@ const ANSWER_WAIT: Duration = Duration::from_secs(/*secs*/ 40);
|
||||
static RUNTIME: Mutex<Option<Arc<tokio::runtime::Runtime>>> = Mutex::new(None);
|
||||
|
||||
enum Command {
|
||||
Answer(SessionDescription, blocking::SyncSender<()>),
|
||||
Answer(
|
||||
SessionDescription,
|
||||
blocking::SyncSender<std::result::Result<(), crate::ConnectionError>>,
|
||||
),
|
||||
Controls(AudioControls),
|
||||
}
|
||||
|
||||
@@ -196,15 +199,22 @@ impl RealtimeWebrtcSessionHandle {
|
||||
}
|
||||
|
||||
/// Called off the UI thread; return only after negotiation, device startup and restored controls.
|
||||
pub fn apply_answer_sdp(&self, answer: String) -> Result<()> {
|
||||
let sdp = SessionDescription::try_from(answer).map_err(anyhow::Error::msg)?;
|
||||
pub fn apply_answer_sdp(
|
||||
&self,
|
||||
answer: String,
|
||||
) -> std::result::Result<(), crate::ConnectionError> {
|
||||
let sdp =
|
||||
SessionDescription::try_from(answer).map_err(|_| crate::ConnectionError::Failed)?;
|
||||
let (complete, result) = blocking::sync_channel(/*bound*/ 1);
|
||||
self.send(Command::Answer(sdp, complete))?;
|
||||
if result.recv_timeout(ANSWER_WAIT).is_err() {
|
||||
self.close();
|
||||
anyhow::bail!("voice connection failed");
|
||||
self.send(Command::Answer(sdp, complete))
|
||||
.map_err(|_| crate::ConnectionError::Failed)?;
|
||||
match result.recv_timeout(ANSWER_WAIT) {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
self.close();
|
||||
Err(crate::ConnectionError::Failed)
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn take_error(&self) -> Option<String> {
|
||||
@@ -254,13 +264,23 @@ async fn run(
|
||||
biased;
|
||||
command = commands.recv() => match command {
|
||||
Some(Command::Answer(sdp, complete)) if !connected => {
|
||||
host = host.apply_answer(sdp).await?.open_devices().await?;
|
||||
host = match host.apply_answer(sdp).await {
|
||||
Ok(host) => host,
|
||||
Err(error) => {
|
||||
let failure = error.downcast_ref::<crate::ConnectionError>()
|
||||
.copied().unwrap_or(crate::ConnectionError::Failed);
|
||||
let _ = complete.send(Err(failure));
|
||||
// This failure is delivered by the startup completion only.
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
host = host.open_devices().await?;
|
||||
let applied = startup_controls(&mut commands, controls, |initial| {
|
||||
host.begin_audio_controls(initial)
|
||||
})?;
|
||||
applied.await?;
|
||||
connected = true;
|
||||
let _ = complete.send(());
|
||||
let _ = complete.send(Ok(()));
|
||||
}
|
||||
Some(Command::Controls(next)) => {
|
||||
if connected {
|
||||
|
||||
@@ -180,3 +180,21 @@ fn startup_dispatch_is_ordered_but_acknowledgement_does_not_block_setters() {
|
||||
);
|
||||
drop(applied);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_completion_preserves_classified_failure() {
|
||||
for failure in [
|
||||
crate::ConnectionError::NegotiationTimedOut,
|
||||
crate::ConnectionError::Failed,
|
||||
] {
|
||||
let (handle, mut commands, _) = handles();
|
||||
let caller = handle.clone();
|
||||
let thread = std::thread::spawn(move || caller.apply_answer_sdp("synthetic-answer".into()));
|
||||
let Some(Command::Answer(_, complete)) = commands.recv().await else {
|
||||
panic!("answer expected")
|
||||
};
|
||||
complete.send(Err(failure)).unwrap();
|
||||
assert_eq!(thread.join().unwrap(), Err(failure));
|
||||
assert_eq!(handle.take_error(), None);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user