diff --git a/codex-rs/core/src/realtime_conversation.rs b/codex-rs/core/src/realtime_conversation.rs index 007898db4b..095ba94dd7 100644 --- a/codex-rs/core/src/realtime_conversation.rs +++ b/codex-rs/core/src/realtime_conversation.rs @@ -513,6 +513,8 @@ impl RealtimeHandoffState { #[allow(dead_code)] struct ConversationState { + session_id: Option, + sub_id: String, audio_tx: Sender, text_tx: Sender, session_kind: RealtimeSessionKind, @@ -614,23 +616,34 @@ impl RealtimeConversationManager { &self, start: RealtimeStart, mode_instructions: RealtimeModeInstructions, + sess: &Arc, + sub_id: &str, ) -> CodexResult { let previous_state = { let mut guard = self.state.lock().await; guard.conversation.take() }; if let Some(state) = previous_state { + let previous_sub_id = state.sub_id.clone(); stop_conversation_state(state, RealtimeFanoutTaskStop::Await).await; + send_realtime_conversation_closed( + sess, + previous_sub_id, + RealtimeConversationEnd::Requested, + ) + .await; } - self.start_inner(start, mode_instructions).await + self.start_inner(start, mode_instructions, sub_id).await } async fn start_inner( &self, start: RealtimeStart, mode_instructions: RealtimeModeInstructions, + sub_id: &str, ) -> CodexResult { + let session_id = start.session_config.session_id.clone(); let RealtimeStart { api_provider, http_client_factory, @@ -770,6 +783,8 @@ impl RealtimeConversationManager { let mut state = self.state.lock().await; state.conversation = Some(ConversationState { + session_id, + sub_id: sub_id.to_owned(), audio_tx, text_tx, session_kind, @@ -812,20 +827,32 @@ impl RealtimeConversationManager { } } - pub(crate) async fn finish_if_active(&self, realtime_active: &Arc) { - let state = { - let mut guard = self.state.lock().await; - match guard.conversation.as_ref() { - Some(state) if Arc::ptr_eq(&state.realtime_active, realtime_active) => { - guard.conversation.take() - } - _ => None, - } - }; - - if let Some(state) = state { - stop_conversation_state(state, RealtimeFanoutTaskStop::Detach).await; + #[expect( + clippy::await_holding_invalid_type, + reason = "Publish the matching close before a replacement can start its history segment." + )] + async fn finish_if_active( + &self, + sess: &Arc, + realtime_active: &Arc, + sub_id: String, + end: RealtimeConversationEnd, + ) { + // Keep selection and its close event together. An old fanout must not + // close the history segment that belongs to a replacement. + let mut guard = self.state.lock().await; + if !guard + .conversation + .as_ref() + .is_some_and(|state| Arc::ptr_eq(&state.realtime_active, realtime_active)) + { + return; } + let Some(state) = guard.conversation.take() else { + return; + }; + stop_conversation_state(state, RealtimeFanoutTaskStop::Detach).await; + send_realtime_conversation_closed(sess, sub_id, end).await; } pub(crate) async fn audio_in(&self, frame: RealtimeAudioFrame) -> CodexResult<()> { @@ -1717,7 +1744,10 @@ async fn handle_start_inner( sdp, existing_call_id, }; - let start_output = sess.conversation.start(start, mode_instructions).await?; + let start_output = sess + .conversation + .start(start, mode_instructions, sess, sub_id) + .await?; info!("realtime conversation started"); @@ -1802,7 +1832,14 @@ async fn handle_start_inner( } } // Make realtime_end eligible only after the tail has reached history. - sess_clone.conversation.state.lock().await.context_active = false; + { + let mut state = sess_clone.conversation.state.lock().await; + if state.conversation.as_ref().is_none_or(|current| { + Arc::ptr_eq(¤t.realtime_active, &fanout_realtime_active) + }) { + state.context_active = false; + } + } if let Some(error) = handoff_error { end = RealtimeConversationEnd::Error; sess_clone @@ -1822,9 +1859,8 @@ async fn handle_start_inner( } sess_clone .conversation - .finish_if_active(&fanout_realtime_active) + .finish_if_active(&sess_clone, &fanout_realtime_active, sub_id, end) .await; - send_realtime_conversation_closed(&sess_clone, sub_id, end).await; } }); sess.conversation @@ -1983,7 +2019,41 @@ pub(crate) async fn handle_speech( } pub(crate) async fn handle_close(sess: &Arc, sub_id: String) { - end_realtime_conversation(sess, sub_id, RealtimeConversationEnd::Requested).await; + handle_detach(sess, /*expected*/ None, &sub_id).await; +} + +/// Uses the ordinary sequential start path and reports its connection result. +pub(crate) async fn handle_attach( + sess: &Arc, + sub_id: String, + params: ConversationStartParams, +) -> CodexResult<()> { + let prepared = prepare_realtime_start(sess, params).await?; + handle_start_inner(sess, &sub_id, prepared).await +} + +pub(crate) async fn handle_detach(sess: &Arc, expected: Option<&str>, stop_sub_id: &str) { + let current = { + let mut state = sess.conversation.state.lock().await; + if expected.is_some_and(|expected| { + state + .conversation + .as_ref() + .and_then(|current| current.session_id.as_deref()) + != Some(expected) + }) { + return; + } + state.conversation.take() + }; + let sub_id = if let Some(current) = current { + let sub_id = current.sub_id.clone(); + stop_conversation_state(current, RealtimeFanoutTaskStop::Await).await; + sub_id + } else { + stop_sub_id.to_owned() + }; + send_realtime_conversation_closed(sess, sub_id, RealtimeConversationEnd::Requested).await; } fn spawn_realtime_input_task( @@ -2738,15 +2808,6 @@ async fn send_conversation_error( .await; } -async fn end_realtime_conversation( - sess: &Arc, - sub_id: String, - end: RealtimeConversationEnd, -) { - let _ = sess.conversation.shutdown().await; - send_realtime_conversation_closed(sess, sub_id, end).await; -} - async fn send_realtime_conversation_closed( sess: &Arc, sub_id: String, diff --git a/codex-rs/core/src/realtime_conversation_tests.rs b/codex-rs/core/src/realtime_conversation_tests.rs index 16af93eb53..98e1e61a18 100644 --- a/codex-rs/core/src/realtime_conversation_tests.rs +++ b/codex-rs/core/src/realtime_conversation_tests.rs @@ -29,6 +29,129 @@ use std::time::Instant; use test_case::test_case; use tokio::sync::Mutex; +/// Hold old input cleanup open while a successor tries to claim the connection. +#[tokio::test] +async fn natural_close_finishes_before_successor_and_ignores_old_identity() { + use super::ConversationState; + use super::RealtimeConversationEnd; + use super::RealtimeHandoffAdmission; + use codex_protocol::protocol::Event; + use codex_protocol::protocol::EventMsg; + use codex_protocol::protocol::RealtimeConversationStartedEvent; + use codex_protocol::protocol::RealtimeConversationVersion; + use std::sync::atomic::AtomicBool; + use tokio::sync::oneshot; + use tokio_util::sync::CancellationToken; + + let (sess, _turn, events) = crate::session::tests::make_session_and_context_with_rx().await; + let old_identity = Arc::new(AtomicBool::new(true)); + let stop_token = CancellationToken::new(); + let input_stop = stop_token.clone(); + let (entered, cleaning_up) = oneshot::channel(); + let (release, released) = oneshot::channel(); + let input_task = tokio::spawn(async move { + input_stop.cancelled().await; + entered.send(()).unwrap(); + released.await.unwrap(); + }); + let handoff = RealtimeHandoffState { + output_tx: bounded(1).0, + last_output: Arc::new(Mutex::new(None)), + stream: Arc::new(Mutex::new(Default::default())), + client_managed_handoffs: false, + codex_responses_as_items: false, + codex_response_item_prefix: None, + backend_reasoning_status: false, + codex_response_handoff_mode: CodexResponseHandoffMode::Thinking, + codex_response_handoff_channel_prefixes: Arc::new(BTreeMap::new()), + session_kind: RealtimeSessionKind::V1, + event_parser: RealtimeEventParser::V1, + }; + let connection = |identity, input_task, stop_token, session: &str| ConversationState { + session_id: Some(session.to_owned()), + sub_id: session.to_owned(), + audio_tx: bounded(1).0, + text_tx: bounded(1).0, + session_kind: RealtimeSessionKind::V1, + handoff: handoff.clone(), + input_task, + fanout_task: None, + realtime_active: identity, + route_handoffs: Arc::new(RealtimeHandoffAdmission::new()), + stop_token, + }; + sess.conversation.state.lock().await.conversation = Some(connection( + Arc::clone(&old_identity), + input_task, + stop_token, + "A", + )); + let close = sess.conversation.finish_if_active( + &sess, + &old_identity, + "A".to_owned(), + RealtimeConversationEnd::TransportClosed, + ); + tokio::pin!(close); + assert!(futures::poll!(&mut close).is_pending()); + cleaning_up.await.unwrap(); + + // This is the same state publication boundary used by start_inner. + let successor = async { + sess.conversation.state.lock().await.conversation = Some(connection( + Arc::new(AtomicBool::new(true)), + tokio::spawn(async {}), + CancellationToken::new(), + "B", + )); + sess.send_event_raw(Event { + id: "B".to_owned(), + msg: EventMsg::RealtimeConversationStarted(RealtimeConversationStartedEvent { + realtime_session_id: Some("B".to_owned()), + version: RealtimeConversationVersion::V3, + }), + }) + .await; + }; + tokio::pin!(successor); + assert!(futures::poll!(&mut successor).is_pending()); + release.send(()).unwrap(); + close.await; + successor.await; + sess.conversation + .finish_if_active( + &sess, + &old_identity, + "A".to_owned(), + RealtimeConversationEnd::TransportClosed, + ) + .await; + let observed = std::iter::from_fn(|| events.try_recv().ok()) + .filter_map(|event| match event.msg { + EventMsg::RealtimeConversationClosed(_) => Some((event.id, "closed")), + EventMsg::RealtimeConversationStarted(_) => Some((event.id, "started")), + _ => None, + }) + .collect::>(); + assert_eq!( + observed, + vec![("A".to_owned(), "closed"), ("B".to_owned(), "started")] + ); + assert_eq!( + sess.conversation + .state + .lock() + .await + .conversation + .as_ref() + .unwrap() + .session_id + .as_deref(), + Some("B") + ); + sess.conversation.shutdown().await.unwrap(); +} + #[test] fn prefers_handoff_input_transcript_over_active_transcript() { let handoff = RealtimeHandoffRequested { diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index c569b04ec9..72a6b55f6e 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -518,6 +518,25 @@ pub(super) async fn submission_loop( } false } + Op::RealtimeConversationAttach { params, reply } => { + let result = + crate::realtime_conversation::handle_attach(&sess, sub.id, params).await; + let _ = reply.send(result); + false + } + Op::RealtimeConversationDetach { + realtime_session_id, + reply, + } => { + crate::realtime_conversation::handle_detach( + &sess, + Some(&realtime_session_id), + &sub.id, + ) + .await; + let _ = reply.send(Ok(())); + false + } Op::RealtimeConversationAudio(params) => { handle_realtime_conversation_audio(&sess, sub.id.clone(), params).await; false diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index dada42382a..dff112241a 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -168,6 +168,7 @@ mod prompt_cache_key; mod prompt_caching; mod prompt_debug_tests; mod quota_exceeded; +mod realtime_attachment; mod realtime_conversation; mod realtime_initial_items; mod realtime_misalignment; diff --git a/codex-rs/core/tests/suite/realtime_attachment.rs b/codex-rs/core/tests/suite/realtime_attachment.rs new file mode 100644 index 0000000000..ea43c266ed --- /dev/null +++ b/codex-rs/core/tests/suite/realtime_attachment.rs @@ -0,0 +1,320 @@ +//! Exercises attachment races through Core submissions and real sideband sockets. + +use anyhow::Result; +use codex_protocol::protocol::ConversationStartParams; +use codex_protocol::protocol::ConversationStartTransport; +use codex_protocol::protocol::ConversationTextParams; +use codex_protocol::protocol::ConversationTextRole; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::RealtimeConversationVersion; +use codex_protocol::protocol::RealtimeOutputModality; +use codex_protocol::protocol::ThreadHistoryMode; +use core_test_support::responses::ResponsesRequest; +use core_test_support::responses::start_mock_server; +use core_test_support::test_codex::TestCodex; +use core_test_support::test_codex::test_codex; +use futures::SinkExt; +use futures::StreamExt; +use pretty_assertions::assert_eq; +use serde_json::Value; +use serde_json::json; +use std::time::Duration; +use tokio::net::TcpListener; +use tokio::sync::mpsc; +use tokio::sync::oneshot; +use tokio::time::timeout; +use tokio_tungstenite::tungstenite::Message; + +struct Sideband { + url: String, + connections: mpsc::UnboundedReceiver, + task: tokio::task::JoinHandle<()>, +} + +struct Connection { + accept: oneshot::Sender, + messages: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, +} + +struct Connected { + messages: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, +} + +impl Sideband { + async fn new() -> Result { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let url = format!("ws://{}", listener.local_addr()?); + let (connections_tx, connections) = mpsc::unbounded_channel(); + let task = tokio::spawn(async move { + while let Ok((stream, _)) = listener.accept().await { + let (accept, release) = oneshot::channel(); + let (messages_tx, messages) = mpsc::unbounded_channel(); + let (events, mut events_rx) = mpsc::unbounded_channel::(); + if connections_tx + .send(Connection { + accept, + messages, + events, + }) + .is_err() + { + return; + } + tokio::spawn(async move { + if release.await != Ok(true) { + // Read the handshake before rejecting it so closing the socket + // cannot turn the HTTP response into a Windows connection reset. + let _ = tokio_tungstenite::accept_hdr_async( + stream, + |_: &tokio_tungstenite::tungstenite::handshake::server::Request, + _: tokio_tungstenite::tungstenite::handshake::server::Response| { + Err(http::Response::builder() + .status(http::StatusCode::GONE) + .body(/*body*/ None) + .expect("valid handshake rejection")) + }, + ) + .await; + return; + } + let Ok(mut socket) = tokio_tungstenite::accept_async(stream).await else { + return; + }; + let _ = socket + .send(Message::Text( + json!({"type":"session.started", "session":{"id":"media-call"}}) + .to_string() + .into(), + )) + .await; + loop { + tokio::select! { + Some(event) = events_rx.recv() => { + if socket.send(Message::Text(event.to_string().into())).await.is_err() { return; } + } + message = socket.next() => match message { + Some(Ok(Message::Text(text))) => { let _ = messages_tx.send(serde_json::from_str(&text).expect("sideband request should be JSON")); } + Some(Ok(Message::Close(_))) => { let _ = socket.close(/*msg*/ None).await; return; } + Some(Ok(_)) => {} + _ => return, + }, + } + } + }); + } + }); + Ok(Self { + url, + connections, + task, + }) + } + + async fn connected(&mut self) -> Connection { + timeout(Duration::from_secs(10), self.connections.recv()) + .await + .expect("sideband should connect before timeout") + .expect("sideband listener should remain open") + } +} + +impl Drop for Sideband { + fn drop(&mut self) { + self.task.abort(); + } +} + +fn params(session: &str, url: &str) -> ConversationStartParams { + ConversationStartParams { + client_managed_handoffs: false, + delegation_ack_filler: None, + flush_transcript_tail_on_session_end: false, + codex_responses_as_items: false, + codex_response_item_prefix: None, + codex_response_handoff_mode: Default::default(), + backend_reasoning_status: false, + codex_response_handoff_channel_prefixes: None, + model: None, + output_modality: RealtimeOutputModality::Audio, + include_startup_context: false, + initial_items: Vec::new(), + realtime_start_instructions: None, + realtime_end_instructions: None, + prompt: None, + realtime_session_id: Some(session.to_owned()), + transport: Some(ConversationStartTransport::ExistingCall { + call_id: format!("rtc_{session}"), + sideband_base_url: Some(url.to_owned()), + }), + version: Some(RealtimeConversationVersion::V3), + voice: None, + } +} + +async fn start( + test: &TestCodex, + session: &str, + url: &str, +) -> Result<(String, oneshot::Receiver>)> { + let params = params(session, url); + let (reply, result) = oneshot::channel(); + let id = test + .codex + .submit(Op::RealtimeConversationAttach { params, reply }) + .await?; + Ok((id, result)) +} + +async fn detach(test: &TestCodex, session: &str) -> Result<()> { + let (reply, result) = oneshot::channel(); + test.codex + .submit(Op::RealtimeConversationDetach { + realtime_session_id: session.to_owned(), + reply, + }) + .await?; + timeout(Duration::from_secs(10), result).await???; + Ok(()) +} + +async fn attached( + test: &TestCodex, + server: &mut Sideband, + session: &str, +) -> Result<(String, Connected)> { + let (id, result) = start(test, session, &server.url).await?; + let connection = server.connected().await; + connection + .accept + .send(/*value*/ true) + .expect("candidate should still be waiting for its handshake"); + timeout(Duration::from_secs(10), result).await???; + Ok(( + id, + Connected { + messages: connection.messages, + events: connection.events, + }, + )) +} + +async fn assert_text_routes_to(test: &TestCodex, connection: &mut Connected) -> Result<()> { + test.codex + .submit(Op::RealtimeConversationText(ConversationTextParams { + text: "still selected".to_owned(), + role: ConversationTextRole::User, + })) + .await?; + timeout(Duration::from_secs(10), async { + while let Some(message) = connection.messages.recv().await { + if message.to_string().contains("still selected") { + return; + } + } + panic!("selected sideband closed"); + }) + .await?; + Ok(()) +} + +/// Starts are sequential; completion follows the handshake and a delayed stop A leaves B usable. +pub(super) async fn attachment_replacement_scenario() -> Result> { + let api = start_mock_server().await; + let response = core_test_support::responses::mount_sse_once( + &api, + core_test_support::responses::sse(vec![ + core_test_support::responses::ev_response_created("handoff"), + core_test_support::responses::ev_assistant_message("answer", "Selected call handled"), + core_test_support::responses::ev_completed("handoff"), + ]), + ) + .await; + let mut builder = test_codex() + .with_history_mode(ThreadHistoryMode::Paginated) + .with_model_info_override("gpt-5.5", |model| { + model.use_responses_lite = false; + }) + .with_config(|config| { + config.base_instructions = Some(String::new()); + }); + let test = builder.build_with_auto_env(&api).await?; + let mut original = Sideband::new().await?; + let mut newer = Sideband::new().await?; + let (original_id, mut original_messages) = attached(&test, &mut original, "original").await?; + let (newer_id, mut completion) = start(&test, "newer", &newer.url).await?; + let connection = newer.connected().await; + assert_eq!( + timeout(Duration::from_secs(10), original_messages.messages.recv()).await?, + None + ); + assert!(matches!( + completion.try_recv(), + Err(oneshot::error::TryRecvError::Empty) + )); + let (reply, stopped) = oneshot::channel(); + test.codex + .submit(Op::RealtimeConversationDetach { + realtime_session_id: "original".to_owned(), + reply, + }) + .await?; + connection.accept.send(true).expect("handshake pending"); + timeout(Duration::from_secs(10), completion).await???; + timeout(Duration::from_secs(10), stopped).await???; + detach(&test, "original").await?; + let mut messages = Connected { + messages: connection.messages, + events: connection.events, + }; + assert_text_routes_to(&test, &mut messages).await?; + messages.events.send(json!({"type":"delegation.created", "offset_ms": 0, "item": {"id":"handoff", "type":"delegation", "target":"client", "content":[{"type":"input_text", "text":"selected connection handoff"}]}}))?; + let lifecycle = timeout(Duration::from_secs(10), async { + let mut lifecycle = Vec::new(); + loop { + let event = test.codex.next_event().await?; + match event.msg { + EventMsg::RealtimeConversationStarted(_) => lifecycle.push((event.id, "started")), + EventMsg::RealtimeConversationClosed(_) => lifecycle.push((event.id, "closed")), + EventMsg::TurnComplete(_) => break, + _ => {} + } + } + anyhow::Ok(lifecycle) + }) + .await??; + assert_eq!( + lifecycle, + vec![ + (original_id.clone(), "started"), + (original_id, "closed"), + (newer_id, "started") + ] + ); + test.codex.shutdown_and_wait().await?; + Ok(response.requests()) +} + +/// A rejected replacement closes A and reports the failure; a later attempt can connect. +#[tokio::test] +async fn failed_attachment_leaves_core_disconnected() -> Result<()> { + let api = start_mock_server().await; + let test = test_codex().build_with_auto_env(&api).await?; + let mut original = Sideband::new().await?; + let mut newer = Sideband::new().await?; + let (_, mut current) = attached(&test, &mut original, "original").await?; + let (_, result) = start(&test, "newer", &newer.url).await?; + let connection = newer.connected().await; + assert_eq!( + timeout(Duration::from_secs(10), current.messages.recv()).await?, + None + ); + connection.accept.send(false).expect("handshake pending"); + assert!(timeout(Duration::from_secs(10), result).await??.is_err()); + let (_, mut retry) = attached(&test, &mut newer, "newer").await?; + assert_text_routes_to(&test, &mut retry).await?; + test.codex.shutdown_and_wait().await?; + Ok(()) +} diff --git a/codex-rs/core/tests/suite/scenarios.rs b/codex-rs/core/tests/suite/scenarios.rs index 53369836b0..e8bc176b80 100644 --- a/codex-rs/core/tests/suite/scenarios.rs +++ b/codex-rs/core/tests/suite/scenarios.rs @@ -270,6 +270,20 @@ fn configure_scenario_catalog(config: &mut Config) { config.cloud_skill_enabled = false; } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn realtime_attachment_replacement_preserves_handoff_context() -> Result<()> { + let requests = super::realtime_attachment::attachment_replacement_scenario().await?; + insta::assert_snapshot!( + "realtime_attachment_replacement", + context_snapshot::format_request_history_snapshot( + "A replacement fences an older pending connection and stale stops; only the selected call starts a Codex handoff.", + &requests, + &ContextSnapshotOptions::default().rewrite_known_segments(), + ) + ); + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn code_mode_mcp_schema_limits_preserve_explicit_overrides() -> Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__realtime_attachment_replacement.snap b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__realtime_attachment_replacement.snap new file mode 100644 index 0000000000..fdb0fa988b --- /dev/null +++ b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__realtime_attachment_replacement.snap @@ -0,0 +1,29 @@ +--- +source: core/tests/suite/scenarios.rs +assertion_line: 373 +expression: "context_snapshot::format_request_history_snapshot(\"A replacement fences an older pending connection and stale stops; only the selected call starts a Codex handoff.\",\n&requests, &ContextSnapshotOptions::default().rewrite_known_segments(),)" +--- +Scenario: A replacement fences an older pending connection and stale stops; only the selected call starts a Codex handoff. + +## Window 1 +-- request 1 (turn) -- +00:message/developer[2]: + [01] + Realtime conversation started. + + You are operating as a backend executor behind an intermediary. The user does not talk to you directly. ...ediary and may be summarized before the user sees it. [hash=5114d16b52865327] + + When invoked, you receive the latest conversation transcript and any relevant mode or metadata. The inte...void verbose responses that add user-visible latency. [hash=e229c6c9120dff28] + + When user text is routed from realtime, treat it as a transcript. It may be unpunctuated or contain recognition errors. + + - Keep responses concise and action-oriented. Your updates should help the intermediary respond to the user. + + [02] +01:message/user: + +02:message/user: + + selected connection handoff + user: selected connection handoff + diff --git a/codex-rs/protocol/src/conversation_start_params_tests.rs b/codex-rs/protocol/src/conversation_start_params_tests.rs new file mode 100644 index 0000000000..6ccb5e4f1e --- /dev/null +++ b/codex-rs/protocol/src/conversation_start_params_tests.rs @@ -0,0 +1,51 @@ +//! Start diagnostics retain routing-independent metadata without exposing input content. + +use super::*; +use pretty_assertions::assert_eq; + +#[test] +fn realtime_start_debug_redacts_text_and_transport() { + let secret = "credential-bearing-content"; + let mut params = ConversationStartParams { + client_managed_handoffs: false, + delegation_ack_filler: None, + flush_transcript_tail_on_session_end: false, + codex_responses_as_items: false, + codex_response_item_prefix: Some(secret.to_owned()), + codex_response_handoff_mode: Default::default(), + backend_reasoning_status: false, + codex_response_handoff_channel_prefixes: Some(BTreeMap::from([( + secret.to_owned(), + vec![secret.to_owned()], + )])), + model: Some(secret.to_owned()), + output_modality: RealtimeOutputModality::Audio, + include_startup_context: true, + initial_items: vec![ConversationTextParams { + role: ConversationTextRole::Developer, + text: secret.to_owned(), + }], + realtime_start_instructions: Some(secret.to_owned()), + realtime_end_instructions: Some(secret.to_owned()), + prompt: Some(Some(secret.to_owned())), + realtime_session_id: Some(secret.to_owned()), + transport: None, + version: Some(RealtimeConversationVersion::V3), + voice: None, + }; + for transport in [ + ConversationStartTransport::ExistingCall { + call_id: secret.to_owned(), + sideband_base_url: Some(format!("wss://example.test/?token={secret}")), + }, + ConversationStartTransport::Webrtc { + sdp: secret.to_owned(), + }, + ] { + params.transport = Some(transport); + assert_eq!( + format!("{params:?}"), + "ConversationStartParams { output_modality: Audio, initial_items_count: 1, version: Some(V3), .. }" + ); + } +} diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 841c794d4d..be48c2f152 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -173,7 +173,7 @@ pub struct W3cTraceContext { pub tracestate: Option, } -#[derive(Debug, Clone, PartialEq)] +#[derive(Clone, PartialEq)] pub struct ConversationStartParams { /// Whether Codex response handoffs are managed through explicit client append calls. pub client_managed_handoffs: bool, @@ -214,6 +214,17 @@ pub struct ConversationStartParams { pub voice: Option, } +impl fmt::Debug for ConversationStartParams { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Text, instructions, and transport endpoints can contain credentials. + f.debug_struct("ConversationStartParams") + .field("output_modality", &self.output_modality) + .field("initial_items_count", &self.initial_items.len()) + .field("version", &self.version) + .finish_non_exhaustive() + } +} + #[derive(Debug, Clone, PartialEq)] pub enum ConversationStartTransport { Websocket, @@ -594,6 +605,12 @@ pub enum Op { #[debug("RealtimeConversationStart {{ session_id: {:?}, version: {:?}, output_modality: {:?} }}", _0.realtime_session_id, _0.version, _0.output_modality)] RealtimeConversationStart(ConversationStartParams), + /// Start a realtime conversation and report completion of the connection attempt. + RealtimeConversationAttach { + params: ConversationStartParams, + reply: oneshot::Sender>, + }, + /// Send audio input to the running realtime conversation stream. #[debug("RealtimeConversationAudio {{ item_id: {:?}, sample_rate: {}, num_channels: {}, samples_per_channel: {:?} }}", _0.frame.item_id, _0.frame.sample_rate, _0.frame.num_channels, _0.frame.samples_per_channel)] RealtimeConversationAudio(ConversationAudioParams), @@ -609,6 +626,12 @@ pub enum Op { /// Close the running realtime conversation stream. RealtimeConversationClose, + /// Close only the matching session after earlier start operations finish. + RealtimeConversationDetach { + realtime_session_id: String, + reply: oneshot::Sender>, + }, + /// Request the list of voices supported by realtime conversation streams. RealtimeConversationListVoices, @@ -952,10 +975,12 @@ impl Op { Self::InterruptIfNoPendingInput { .. } => "interrupt_if_no_pending_input", Self::CleanBackgroundTerminals => "clean_background_terminals", Self::RealtimeConversationStart(_) => "realtime_conversation_start", + Self::RealtimeConversationAttach { .. } => "realtime_conversation_attach", Self::RealtimeConversationAudio(_) => "realtime_conversation_audio", Self::RealtimeConversationText(_) => "realtime_conversation_text", Self::RealtimeConversationSpeech(_) => "realtime_conversation_speech", Self::RealtimeConversationClose => "realtime_conversation_close", + Self::RealtimeConversationDetach { .. } => "realtime_conversation_detach", Self::RealtimeConversationListVoices => "realtime_conversation_list_voices", Self::TurnInput { .. } => "turn_input", Self::RecoverTurn { .. } => "recover_turn", @@ -4515,6 +4540,10 @@ pub struct CollabResumeEndEvent { pub status: AgentStatus, } +#[cfg(test)] +#[path = "conversation_start_params_tests.rs"] +mod conversation_start_params_tests; + #[cfg(test)] mod tests { use super::*;