mirror of
https://github.com/openai/codex.git
synced 2026-11-24 23:20:47 +00:00
Forward realtime assistant output through handoffs
This commit is contained in:
@@ -61,14 +61,12 @@ use tracing::warn;
|
||||
|
||||
const AUDIO_IN_QUEUE_CAPACITY: usize = 256;
|
||||
const USER_TEXT_IN_QUEUE_CAPACITY: usize = 64;
|
||||
const TERMINAL_OUTPUT_QUEUE_CAPACITY: usize = 64;
|
||||
const ASSISTANT_OUTPUT_QUEUE_CAPACITY: usize = 64;
|
||||
const OUTPUT_EVENTS_QUEUE_CAPACITY: usize = 256;
|
||||
const REALTIME_STARTUP_CONTEXT_TOKEN_BUDGET: usize = 5_300;
|
||||
const DEFAULT_REALTIME_MODEL: &str = "gpt-realtime-1.5";
|
||||
pub(crate) const REALTIME_USER_TEXT_PREFIX: &str = "[USER] ";
|
||||
pub(crate) const REALTIME_BACKEND_TEXT_PREFIX: &str = "[BACKEND] ";
|
||||
const REALTIME_V2_HANDOFF_COMPLETE_ACKNOWLEDGEMENT: &str =
|
||||
"Background agent finished. Use the preceding [BACKEND] messages as the result.";
|
||||
const DEFAULT_HANDOFF_ID: &str = "codex";
|
||||
const REALTIME_V2_STEER_ACKNOWLEDGEMENT: &str =
|
||||
"This was sent to steer the previous background agent task.";
|
||||
const REALTIME_ACTIVE_RESPONSE_ERROR_PREFIX: &str =
|
||||
@@ -98,20 +96,14 @@ enum RealtimeSessionKind {
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct RealtimeHandoffState {
|
||||
terminal_output_tx: Sender<RealtimeTerminalOutput>,
|
||||
assistant_output_tx: Sender<RealtimeAssistantOutput>,
|
||||
active_handoff: Arc<Mutex<Option<String>>>,
|
||||
session_kind: RealtimeSessionKind,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum RealtimeTerminalOutput {
|
||||
Direct {
|
||||
output_text: String,
|
||||
},
|
||||
Handoff {
|
||||
handoff_id: String,
|
||||
output_text: String,
|
||||
},
|
||||
struct RealtimeAssistantOutput {
|
||||
handoff_id: Option<String>,
|
||||
output_text: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
@@ -186,50 +178,37 @@ struct RealtimeInputTask {
|
||||
writer: RealtimeWebsocketWriter,
|
||||
events: RealtimeWebsocketEvents,
|
||||
user_text_rx: Receiver<String>,
|
||||
terminal_output_rx: Receiver<RealtimeTerminalOutput>,
|
||||
assistant_output_rx: Receiver<RealtimeAssistantOutput>,
|
||||
audio_rx: Receiver<RealtimeAudioFrame>,
|
||||
events_tx: Sender<RealtimeEvent>,
|
||||
handoff_state: RealtimeHandoffState,
|
||||
session_kind: RealtimeSessionKind,
|
||||
event_parser: RealtimeEventParser,
|
||||
}
|
||||
|
||||
struct RealtimeInputChannels {
|
||||
user_text_rx: Receiver<String>,
|
||||
terminal_output_rx: Receiver<RealtimeTerminalOutput>,
|
||||
assistant_output_rx: Receiver<RealtimeAssistantOutput>,
|
||||
audio_rx: Receiver<RealtimeAudioFrame>,
|
||||
}
|
||||
|
||||
impl RealtimeHandoffState {
|
||||
fn new(
|
||||
terminal_output_tx: Sender<RealtimeTerminalOutput>,
|
||||
session_kind: RealtimeSessionKind,
|
||||
) -> Self {
|
||||
fn new(assistant_output_tx: Sender<RealtimeAssistantOutput>) -> Self {
|
||||
Self {
|
||||
terminal_output_tx,
|
||||
assistant_output_tx,
|
||||
active_handoff: Arc::new(Mutex::new(None)),
|
||||
session_kind,
|
||||
}
|
||||
}
|
||||
|
||||
async fn take_terminal_output(
|
||||
&self,
|
||||
output_text: Option<String>,
|
||||
) -> Option<RealtimeTerminalOutput> {
|
||||
let handoff_id = self.active_handoff.lock().await.take();
|
||||
let output_text = output_text?;
|
||||
match handoff_id {
|
||||
Some(handoff_id) => Some(RealtimeTerminalOutput::Handoff {
|
||||
handoff_id,
|
||||
output_text: prefix_realtime_text(
|
||||
output_text,
|
||||
REALTIME_BACKEND_TEXT_PREFIX,
|
||||
self.session_kind,
|
||||
),
|
||||
}),
|
||||
None => Some(RealtimeTerminalOutput::Direct { output_text }),
|
||||
async fn assistant_output(&self, output_text: String) -> RealtimeAssistantOutput {
|
||||
RealtimeAssistantOutput {
|
||||
handoff_id: self.active_handoff.lock().await.clone(),
|
||||
output_text,
|
||||
}
|
||||
}
|
||||
|
||||
async fn finish_turn(&self) {
|
||||
self.active_handoff.lock().await.take();
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
@@ -312,16 +291,16 @@ impl RealtimeConversationManager {
|
||||
async_channel::bounded::<RealtimeAudioFrame>(AUDIO_IN_QUEUE_CAPACITY);
|
||||
let (user_text_tx, user_text_rx) =
|
||||
async_channel::bounded::<String>(USER_TEXT_IN_QUEUE_CAPACITY);
|
||||
let (terminal_output_tx, terminal_output_rx) =
|
||||
async_channel::bounded::<RealtimeTerminalOutput>(TERMINAL_OUTPUT_QUEUE_CAPACITY);
|
||||
let (assistant_output_tx, assistant_output_rx) =
|
||||
async_channel::bounded::<RealtimeAssistantOutput>(ASSISTANT_OUTPUT_QUEUE_CAPACITY);
|
||||
let (events_tx, events_rx) =
|
||||
async_channel::bounded::<RealtimeEvent>(OUTPUT_EVENTS_QUEUE_CAPACITY);
|
||||
|
||||
let realtime_active = Arc::new(AtomicBool::new(true));
|
||||
let handoff = RealtimeHandoffState::new(terminal_output_tx, session_kind);
|
||||
let handoff = RealtimeHandoffState::new(assistant_output_tx);
|
||||
let input_channels = RealtimeInputChannels {
|
||||
user_text_rx,
|
||||
terminal_output_rx,
|
||||
assistant_output_rx,
|
||||
audio_rx,
|
||||
};
|
||||
|
||||
@@ -343,7 +322,6 @@ impl RealtimeConversationManager {
|
||||
events_tx,
|
||||
handoff_state: handoff.clone(),
|
||||
session_kind,
|
||||
event_parser,
|
||||
realtime_active: Arc::clone(&realtime_active),
|
||||
});
|
||||
(task, Some(call.sdp))
|
||||
@@ -360,12 +338,11 @@ impl RealtimeConversationManager {
|
||||
writer: connection.writer(),
|
||||
events: connection.events(),
|
||||
user_text_rx: input_channels.user_text_rx,
|
||||
terminal_output_rx: input_channels.terminal_output_rx,
|
||||
assistant_output_rx: input_channels.assistant_output_rx,
|
||||
audio_rx: input_channels.audio_rx,
|
||||
events_tx,
|
||||
handoff_state: handoff.clone(),
|
||||
session_kind,
|
||||
event_parser,
|
||||
});
|
||||
(task, None)
|
||||
};
|
||||
@@ -468,7 +445,7 @@ impl RealtimeConversationManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn finish_turn(&self, output_text: Option<String>) -> CodexResult<()> {
|
||||
pub(crate) async fn send_assistant_output(&self, output_text: String) -> CodexResult<()> {
|
||||
let handoff = {
|
||||
let guard = self.state.lock().await;
|
||||
guard.as_ref().map(|state| state.handoff.clone())
|
||||
@@ -477,17 +454,25 @@ impl RealtimeConversationManager {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let Some(terminal_output) = handoff.take_terminal_output(output_text).await else {
|
||||
return Ok(());
|
||||
};
|
||||
handoff
|
||||
.terminal_output_tx
|
||||
.send(terminal_output)
|
||||
.assistant_output_tx
|
||||
.send(handoff.assistant_output(output_text).await)
|
||||
.await
|
||||
.map_err(|_| CodexErr::InvalidRequest("conversation is not running".to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn finish_turn(&self) {
|
||||
let handoff = {
|
||||
let guard = self.state.lock().await;
|
||||
guard.as_ref().map(|state| state.handoff.clone())
|
||||
};
|
||||
let Some(handoff) = handoff else {
|
||||
return;
|
||||
};
|
||||
handoff.finish_turn().await;
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&self) -> CodexResult<()> {
|
||||
let state = {
|
||||
let mut guard = self.state.lock().await;
|
||||
@@ -987,7 +972,6 @@ struct RealtimeWebrtcSidebandInputTask {
|
||||
events_tx: Sender<RealtimeEvent>,
|
||||
handoff_state: RealtimeHandoffState,
|
||||
session_kind: RealtimeSessionKind,
|
||||
event_parser: RealtimeEventParser,
|
||||
realtime_active: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
@@ -1001,7 +985,6 @@ fn spawn_webrtc_sideband_input_task(input: RealtimeWebrtcSidebandInputTask) -> J
|
||||
events_tx,
|
||||
handoff_state,
|
||||
session_kind,
|
||||
event_parser,
|
||||
realtime_active,
|
||||
} = input;
|
||||
|
||||
@@ -1040,12 +1023,11 @@ fn spawn_webrtc_sideband_input_task(input: RealtimeWebrtcSidebandInputTask) -> J
|
||||
writer: connection.writer(),
|
||||
events: connection.events(),
|
||||
user_text_rx: input_channels.user_text_rx,
|
||||
terminal_output_rx: input_channels.terminal_output_rx,
|
||||
assistant_output_rx: input_channels.assistant_output_rx,
|
||||
audio_rx: input_channels.audio_rx,
|
||||
events_tx,
|
||||
handoff_state,
|
||||
session_kind,
|
||||
event_parser,
|
||||
})
|
||||
.await;
|
||||
})
|
||||
@@ -1056,12 +1038,11 @@ async fn run_realtime_input_task(input: RealtimeInputTask) {
|
||||
writer,
|
||||
events,
|
||||
user_text_rx,
|
||||
terminal_output_rx,
|
||||
assistant_output_rx,
|
||||
audio_rx,
|
||||
events_tx,
|
||||
handoff_state,
|
||||
session_kind,
|
||||
event_parser,
|
||||
} = input;
|
||||
|
||||
let mut output_audio_state: Option<OutputAudioState> = None;
|
||||
@@ -1078,14 +1059,12 @@ async fn run_realtime_input_task(input: RealtimeInputTask) {
|
||||
)
|
||||
.await
|
||||
}
|
||||
// Terminal Codex output that should be sent back to realtime.
|
||||
terminal_output = terminal_output_rx.recv() => {
|
||||
handle_terminal_output(
|
||||
terminal_output,
|
||||
// Assistant output that should be sent back to realtime.
|
||||
assistant_output = assistant_output_rx.recv() => {
|
||||
handle_assistant_output(
|
||||
assistant_output,
|
||||
&writer,
|
||||
&events_tx,
|
||||
event_parser,
|
||||
&mut response_create_queue,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -1132,70 +1111,31 @@ async fn handle_user_text_input(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_terminal_output(
|
||||
terminal_output: Result<RealtimeTerminalOutput, RecvError>,
|
||||
async fn handle_assistant_output(
|
||||
assistant_output: Result<RealtimeAssistantOutput, RecvError>,
|
||||
writer: &RealtimeWebsocketWriter,
|
||||
events_tx: &Sender<RealtimeEvent>,
|
||||
event_parser: RealtimeEventParser,
|
||||
response_create_queue: &mut RealtimeResponseCreateQueue,
|
||||
) -> anyhow::Result<()> {
|
||||
let terminal_output = terminal_output.context("terminal output channel closed")?;
|
||||
|
||||
let (result, request_response) = match terminal_output {
|
||||
RealtimeTerminalOutput::Direct { output_text } => {
|
||||
let request_response = match event_parser {
|
||||
RealtimeEventParser::V1 => false,
|
||||
RealtimeEventParser::RealtimeV2 => true,
|
||||
};
|
||||
(
|
||||
writer
|
||||
.send_conversation_developer_item_create(format!(
|
||||
"Speak the following text:\n{output_text}"
|
||||
))
|
||||
.await,
|
||||
request_response,
|
||||
)
|
||||
}
|
||||
RealtimeTerminalOutput::Handoff {
|
||||
handoff_id,
|
||||
output_text,
|
||||
} => match event_parser {
|
||||
RealtimeEventParser::V1 => (
|
||||
writer
|
||||
.send_conversation_handoff_append(Some(handoff_id), output_text)
|
||||
.await,
|
||||
false,
|
||||
let assistant_output = assistant_output.context("assistant output channel closed")?;
|
||||
if let Err(err) = writer
|
||||
.send_conversation_handoff_append(
|
||||
Some(
|
||||
assistant_output
|
||||
.handoff_id
|
||||
.unwrap_or_else(|| DEFAULT_HANDOFF_ID.to_string()),
|
||||
),
|
||||
RealtimeEventParser::RealtimeV2 => (
|
||||
if let Err(err) = writer.send_conversation_item_create(output_text).await {
|
||||
Err(err)
|
||||
} else {
|
||||
writer
|
||||
.send_conversation_function_call_output(
|
||||
handoff_id,
|
||||
REALTIME_V2_HANDOFF_COMPLETE_ACKNOWLEDGEMENT.to_string(),
|
||||
)
|
||||
.await
|
||||
},
|
||||
true,
|
||||
),
|
||||
},
|
||||
};
|
||||
if let Err(err) = result {
|
||||
assistant_output.output_text,
|
||||
)
|
||||
.await
|
||||
{
|
||||
let mapped_error = map_api_error(err);
|
||||
warn!("failed to send terminal output: {mapped_error}");
|
||||
warn!("failed to send assistant output: {mapped_error}");
|
||||
let _ = events_tx
|
||||
.send(RealtimeEvent::Error(mapped_error.to_string()))
|
||||
.await;
|
||||
return Err(mapped_error.into());
|
||||
}
|
||||
if request_response {
|
||||
response_create_queue
|
||||
.request_create(writer, events_tx, "terminal output")
|
||||
.await
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_realtime_server_event(
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use super::RealtimeAssistantOutput;
|
||||
use super::RealtimeHandoffState;
|
||||
use super::RealtimeSessionKind;
|
||||
use super::RealtimeTerminalOutput;
|
||||
use super::realtime_delegation_from_handoff;
|
||||
use super::realtime_request_headers;
|
||||
use super::realtime_text_from_handoff_request;
|
||||
@@ -127,71 +126,66 @@ fn wraps_realtime_delegation_input_with_xml_escaping_without_transcript() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn terminal_output_consumes_only_its_handoff() {
|
||||
for (session_kind, expected_output_text) in [
|
||||
(RealtimeSessionKind::V1, "finished"),
|
||||
(RealtimeSessionKind::V2, "[BACKEND] finished"),
|
||||
] {
|
||||
let (tx, _rx) = bounded(1);
|
||||
let state = RealtimeHandoffState::new(tx, session_kind);
|
||||
async fn assistant_outputs_preserve_active_handoff_until_turn_completion() {
|
||||
let (tx, _rx) = bounded(1);
|
||||
let state = RealtimeHandoffState::new(tx);
|
||||
*state.active_handoff.lock().await = Some("handoff_1".to_string());
|
||||
|
||||
*state.active_handoff.lock().await = Some("handoff_1".to_string());
|
||||
let first_output = state
|
||||
.take_terminal_output(Some("finished".to_string()))
|
||||
.await;
|
||||
*state.active_handoff.lock().await = Some("handoff_2".to_string());
|
||||
|
||||
assert_eq!(
|
||||
first_output,
|
||||
Some(RealtimeTerminalOutput::Handoff {
|
||||
handoff_id: "handoff_1".to_string(),
|
||||
output_text: expected_output_text.to_string(),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
state.active_handoff.lock().await.clone(),
|
||||
Some("handoff_2".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
state
|
||||
.take_terminal_output(Some("finished again".to_string()))
|
||||
.await,
|
||||
Some(RealtimeTerminalOutput::Handoff {
|
||||
handoff_id: "handoff_2".to_string(),
|
||||
output_text: format!("{expected_output_text} again"),
|
||||
})
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
state.assistant_output("working".to_string()).await,
|
||||
RealtimeAssistantOutput {
|
||||
handoff_id: Some("handoff_1".to_string()),
|
||||
output_text: "working".to_string(),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
state.active_handoff.lock().await.as_deref(),
|
||||
Some("handoff_1")
|
||||
);
|
||||
assert_eq!(
|
||||
state.assistant_output("finished".to_string()).await,
|
||||
RealtimeAssistantOutput {
|
||||
handoff_id: Some("handoff_1".to_string()),
|
||||
output_text: "finished".to_string(),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
state.active_handoff.lock().await.as_deref(),
|
||||
Some("handoff_1")
|
||||
);
|
||||
state.finish_turn().await;
|
||||
assert_eq!(state.active_handoff.lock().await.as_deref(), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn terminal_output_without_handoff_stays_plain() {
|
||||
for session_kind in [RealtimeSessionKind::V1, RealtimeSessionKind::V2] {
|
||||
let (tx, _rx) = bounded(1);
|
||||
let state = RealtimeHandoffState::new(tx, session_kind);
|
||||
async fn assistant_output_without_handoff_has_no_active_id() {
|
||||
let (tx, _rx) = bounded(1);
|
||||
let state = RealtimeHandoffState::new(tx);
|
||||
|
||||
assert_eq!(
|
||||
state
|
||||
.take_terminal_output(Some("finished".to_string()))
|
||||
.await,
|
||||
Some(RealtimeTerminalOutput::Direct {
|
||||
output_text: "finished".to_string(),
|
||||
})
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
state.assistant_output("working".to_string()).await,
|
||||
RealtimeAssistantOutput {
|
||||
handoff_id: None,
|
||||
output_text: "working".to_string(),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
state.assistant_output("finished".to_string()).await,
|
||||
RealtimeAssistantOutput {
|
||||
handoff_id: None,
|
||||
output_text: "finished".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn terminal_output_without_message_still_consumes_handoff() {
|
||||
for session_kind in [RealtimeSessionKind::V1, RealtimeSessionKind::V2] {
|
||||
let (tx, _rx) = bounded(1);
|
||||
let state = RealtimeHandoffState::new(tx, session_kind);
|
||||
async fn finishing_turn_consumes_handoff() {
|
||||
let (tx, _rx) = bounded(1);
|
||||
let state = RealtimeHandoffState::new(tx);
|
||||
*state.active_handoff.lock().await = Some("handoff_1".to_string());
|
||||
|
||||
*state.active_handoff.lock().await = Some("handoff_1".to_string());
|
||||
|
||||
assert_eq!(state.take_terminal_output(/*output_text*/ None).await, None);
|
||||
assert_eq!(state.active_handoff.lock().await.clone(), None);
|
||||
}
|
||||
state.finish_turn().await;
|
||||
assert_eq!(state.active_handoff.lock().await.as_deref(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1672,7 +1672,7 @@ impl Session {
|
||||
id: turn_context.sub_id.clone(),
|
||||
msg,
|
||||
};
|
||||
self.maybe_send_realtime_terminal_output(&legacy_source)
|
||||
self.maybe_send_realtime_assistant_output(&legacy_source)
|
||||
.await;
|
||||
self.send_event_raw(event).await;
|
||||
self.maybe_notify_parent_of_terminal_turn(turn_context, &legacy_source)
|
||||
@@ -1782,16 +1782,32 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
async fn maybe_send_realtime_terminal_output(&self, msg: &EventMsg) {
|
||||
let EventMsg::TurnComplete(event) = msg else {
|
||||
return;
|
||||
async fn maybe_send_realtime_assistant_output(&self, msg: &EventMsg) {
|
||||
let result = match msg {
|
||||
EventMsg::ItemCompleted(ItemCompletedEvent {
|
||||
item: TurnItem::AgentMessage(message),
|
||||
..
|
||||
}) => {
|
||||
let output_text = message
|
||||
.content
|
||||
.iter()
|
||||
.map(|content| match content {
|
||||
codex_protocol::items::AgentMessageContent::Text { text } => text.as_str(),
|
||||
})
|
||||
.collect::<String>();
|
||||
if output_text.trim().is_empty() {
|
||||
return;
|
||||
}
|
||||
self.conversation.send_assistant_output(output_text).await
|
||||
}
|
||||
EventMsg::TurnComplete(_) | EventMsg::TurnAborted(_) => {
|
||||
self.conversation.finish_turn().await;
|
||||
return;
|
||||
}
|
||||
_ => return,
|
||||
};
|
||||
if let Err(err) = self
|
||||
.conversation
|
||||
.finish_turn(event.last_agent_message.clone())
|
||||
.await
|
||||
{
|
||||
debug!("failed to send terminal output to realtime conversation: {err}");
|
||||
if let Err(err) = result {
|
||||
debug!("failed to send assistant output to realtime conversation: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2391,7 +2391,7 @@ async fn conversation_sends_terminal_assistant_message_to_realtime_handoff() ->
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn conversation_sends_only_last_assistant_message_at_turn_complete() -> Result<()> {
|
||||
async fn conversation_sends_each_assistant_message_once() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let (gate_second_message_tx, gate_second_message_rx) = oneshot::channel();
|
||||
@@ -2439,6 +2439,7 @@ async fn conversation_sends_only_last_assistant_message_at_turn_complete() -> Re
|
||||
}),
|
||||
],
|
||||
vec![],
|
||||
vec![],
|
||||
]])
|
||||
.await;
|
||||
|
||||
@@ -2481,14 +2482,16 @@ async fn conversation_sends_only_last_assistant_message_at_turn_complete() -> Re
|
||||
})
|
||||
.await;
|
||||
|
||||
let intermediate_output = timeout(
|
||||
Duration::from_millis(200),
|
||||
realtime_server.wait_for_request(/*connection_index*/ 0, /*request_index*/ 1),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
intermediate_output.is_err(),
|
||||
"assistant items should not be sent before turn completion"
|
||||
let first_output = realtime_server
|
||||
.wait_for_request(/*connection_index*/ 0, /*request_index*/ 1)
|
||||
.await;
|
||||
assert_eq!(
|
||||
first_output.body_json(),
|
||||
json!({
|
||||
"type": "conversation.handoff.append",
|
||||
"handoff_id": "handoff_item_done",
|
||||
"output_text": "assistant message 1"
|
||||
})
|
||||
);
|
||||
|
||||
let _ = gate_second_message_tx.send(());
|
||||
@@ -2505,11 +2508,11 @@ async fn conversation_sends_only_last_assistant_message_at_turn_complete() -> Re
|
||||
})
|
||||
.await;
|
||||
|
||||
let terminal_output = realtime_server
|
||||
.wait_for_request(/*connection_index*/ 0, /*request_index*/ 1)
|
||||
let second_output = realtime_server
|
||||
.wait_for_request(/*connection_index*/ 0, /*request_index*/ 2)
|
||||
.await;
|
||||
assert_eq!(
|
||||
terminal_output.body_json(),
|
||||
second_output.body_json(),
|
||||
json!({
|
||||
"type": "conversation.handoff.append",
|
||||
"handoff_id": "handoff_item_done",
|
||||
@@ -2518,12 +2521,133 @@ async fn conversation_sends_only_last_assistant_message_at_turn_complete() -> Re
|
||||
);
|
||||
let duplicate_output = timeout(
|
||||
Duration::from_millis(200),
|
||||
realtime_server.wait_for_request(/*connection_index*/ 0, /*request_index*/ 2),
|
||||
realtime_server.wait_for_request(/*connection_index*/ 0, /*request_index*/ 3),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
duplicate_output.is_err(),
|
||||
"turn completion should emit exactly one terminal output"
|
||||
"each assistant message should be emitted exactly once"
|
||||
);
|
||||
|
||||
realtime_server.shutdown().await;
|
||||
api_server.shutdown().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn conversation_clears_handoff_after_turn_abort() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let (gate_first_turn_tx, gate_first_turn_rx) = oneshot::channel();
|
||||
let first_chunks = vec![
|
||||
StreamingSseChunk {
|
||||
gate: None,
|
||||
body: sse_event(responses::ev_response_created("resp-1")),
|
||||
},
|
||||
StreamingSseChunk {
|
||||
gate: Some(gate_first_turn_rx),
|
||||
body: sse_event(responses::ev_completed("resp-1")),
|
||||
},
|
||||
];
|
||||
let second_chunks = vec![
|
||||
StreamingSseChunk {
|
||||
gate: None,
|
||||
body: sse_event(responses::ev_response_created("resp-2")),
|
||||
},
|
||||
StreamingSseChunk {
|
||||
gate: None,
|
||||
body: sse_event(responses::ev_assistant_message(
|
||||
"msg-2",
|
||||
"assistant after abort",
|
||||
)),
|
||||
},
|
||||
StreamingSseChunk {
|
||||
gate: None,
|
||||
body: sse_event(responses::ev_completed("resp-2")),
|
||||
},
|
||||
];
|
||||
let (api_server, _completions) =
|
||||
start_streaming_sse_server(vec![first_chunks, second_chunks]).await;
|
||||
|
||||
let realtime_server = start_websocket_server(vec![vec![
|
||||
vec![
|
||||
json!({
|
||||
"type": "session.updated",
|
||||
"session": { "id": "sess_abort", "instructions": "backend prompt" }
|
||||
}),
|
||||
json!({
|
||||
"type": "conversation.input_transcript.delta",
|
||||
"delta": "delegate then abort"
|
||||
}),
|
||||
json!({
|
||||
"type": "conversation.handoff.requested",
|
||||
"handoff_id": "handoff_abort",
|
||||
"item_id": "item_abort",
|
||||
"input_transcript": "delegate then abort"
|
||||
}),
|
||||
],
|
||||
vec![],
|
||||
]])
|
||||
.await;
|
||||
|
||||
let mut builder = test_codex().with_config({
|
||||
let realtime_base_url = realtime_server.uri().to_string();
|
||||
move |config| {
|
||||
config.experimental_realtime_ws_base_url = Some(realtime_base_url);
|
||||
config.realtime.version = RealtimeWsVersion::V1;
|
||||
}
|
||||
});
|
||||
let test = builder.build_with_streaming_server(&api_server).await?;
|
||||
|
||||
test.codex
|
||||
.submit(Op::RealtimeConversationStart(ConversationStartParams {
|
||||
output_modality: RealtimeOutputModality::Audio,
|
||||
prompt: Some(Some("backend prompt".to_string())),
|
||||
realtime_session_id: None,
|
||||
transport: None,
|
||||
voice: None,
|
||||
}))
|
||||
.await?;
|
||||
|
||||
let _ = wait_for_event_match(&test.codex, |msg| match msg {
|
||||
EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent {
|
||||
payload: RealtimeEvent::HandoffRequested(handoff),
|
||||
}) if handoff.handoff_id == "handoff_abort" => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
api_server.wait_for_request_count(1).await;
|
||||
|
||||
test.codex.submit(Op::Interrupt).await?;
|
||||
wait_for_event(&test.codex, |event| {
|
||||
matches!(event, EventMsg::TurnAborted(_))
|
||||
})
|
||||
.await;
|
||||
let _ = gate_first_turn_tx.send(());
|
||||
|
||||
test.codex
|
||||
.submit(Op::UserInput {
|
||||
items: vec![UserInput::Text {
|
||||
text: "continue after abort".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
final_output_json_schema: None,
|
||||
responsesapi_client_metadata: None,
|
||||
additional_context: Default::default(),
|
||||
thread_settings: Default::default(),
|
||||
})
|
||||
.await?;
|
||||
|
||||
let output = realtime_server
|
||||
.wait_for_request(/*connection_index*/ 0, /*request_index*/ 1)
|
||||
.await;
|
||||
assert_eq!(
|
||||
output.body_json(),
|
||||
json!({
|
||||
"type": "conversation.handoff.append",
|
||||
"handoff_id": "codex",
|
||||
"output_text": "assistant after abort"
|
||||
})
|
||||
);
|
||||
|
||||
realtime_server.shutdown().await;
|
||||
|
||||
Reference in New Issue
Block a user