fix(app-server): refresh running threads on resume

This commit is contained in:
Peter Steinberger
2026-07-01 13:45:14 -07:00
parent 0846c126ea
commit 4412251d32
20 changed files with 4720 additions and 370 deletions
@@ -32,9 +32,25 @@ pub fn item_event_to_server_notification(
thread_id: &str,
turn_id: &str,
) -> ServerNotification {
let Some(notification) = try_item_event_to_server_notification(msg, thread_id, turn_id) else {
unreachable!("unsupported item event");
};
notification
}
/// Build a v2 notification when a core event has a stateless item-event projection.
///
/// Unlike [`item_event_to_server_notification`], this accepts any event so callers that inspect
/// mixed event streams can share the exact live item conversion without maintaining a second
/// event-variant allowlist.
pub fn try_item_event_to_server_notification(
msg: EventMsg,
thread_id: &str,
turn_id: &str,
) -> Option<ServerNotification> {
let thread_id = thread_id.to_string();
let turn_id = turn_id.to_string();
match msg {
let notification = match msg {
EventMsg::DynamicToolCallResponse(response) => {
let status = if response.success {
DynamicToolCallStatus::Completed
@@ -228,7 +244,9 @@ pub fn item_event_to_server_notification(
} else {
CollabAgentToolCallStatus::Completed
};
let receiver_thread_ids = end_event.statuses.keys().map(ToString::to_string).collect();
let mut receiver_thread_ids: Vec<String> =
end_event.statuses.keys().map(ToString::to_string).collect();
receiver_thread_ids.sort();
let agents_states = end_event
.statuses
.iter()
@@ -459,18 +477,23 @@ pub fn item_event_to_server_notification(
completed_at_ms: exec_command_end_event.completed_at_ms,
})
}
_ => unreachable!("unsupported item event"),
}
_ => return None,
};
Some(notification)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::protocol::thread_history::ThreadHistoryBuilder;
use codex_protocol::ThreadId;
use codex_protocol::protocol::AgentStatus;
use codex_protocol::protocol::CollabResumeBeginEvent;
use codex_protocol::protocol::CollabResumeEndEvent;
use codex_protocol::protocol::CollabWaitingEndEvent;
use codex_protocol::protocol::ExecCommandOutputDeltaEvent;
use codex_protocol::protocol::ExecOutputStream;
use codex_protocol::protocol::TurnStartedEvent;
use pretty_assertions::assert_eq;
fn assert_item_started_server_notification(
@@ -586,6 +609,43 @@ mod tests {
);
}
#[test]
fn collab_wait_completion_matches_sorted_history_projection() {
let receiver_a = ThreadId::new();
let receiver_b = ThreadId::new();
let mut statuses = HashMap::new();
statuses.insert(receiver_b, AgentStatus::Completed(None));
statuses.insert(receiver_a, AgentStatus::Running);
let event = CollabWaitingEndEvent {
sender_thread_id: ThreadId::new(),
call_id: "wait-1".to_string(),
completed_at_ms: 456,
agent_statuses: Vec::new(),
statuses,
};
let notification = item_event_to_server_notification(
EventMsg::CollabWaitingEnd(event.clone()),
"thread-1",
"turn-1",
);
let ServerNotification::ItemCompleted(notification) = notification else {
panic!("expected item completion");
};
let mut history = ThreadHistoryBuilder::new();
history.handle_event(&EventMsg::TurnStarted(TurnStartedEvent {
turn_id: "turn-1".to_string(),
trace_id: None,
started_at: Some(1),
model_context_window: None,
collaboration_mode_kind: Default::default(),
}));
history.handle_event(&EventMsg::CollabWaitingEnd(event));
let snapshot = history.active_turn_snapshot().expect("active turn");
assert_eq!(snapshot.items, vec![notification.item]);
}
#[test]
fn exec_command_output_delta_maps_to_command_execution_output_delta() {
let notification = item_event_to_server_notification(
@@ -225,6 +225,7 @@ impl ThreadHistoryChangeAccumulator {
}
}
#[derive(Clone)]
pub struct ThreadHistoryBuilder {
turns: Vec<Turn>,
current_turn: Option<PendingTurn>,
@@ -1479,6 +1480,7 @@ fn upsert_turn_item(items: &mut Vec<ThreadItem>, item: ThreadItem) -> &ThreadIte
&items[inserted_item_index]
}
#[derive(Clone)]
struct PendingTurn {
id: String,
items: Vec<ThreadItem>,
+2
View File
@@ -315,6 +315,8 @@ Valid `personality` values are `"friendly"`, `"pragmatic"`, and `"none"`. When `
To continue a stored session, call `thread/resume` with the `thread.id` you previously recorded. The response shape matches `thread/start`. When the stored session includes persisted token usage, the server emits `thread/tokenUsage/updated` immediately after the response so clients can render restored usage before the next turn starts. You can also pass the same configuration overrides supported by `thread/start`, including `approvalsReviewer`.
When the thread is already loaded and idle, `thread/resume` reconciles completed history written by another app-server process into the live session before responding. This supports sequential handoff between clients without restarting the first app-server. An active local turn is never overwritten; if persisted history is still incomplete or the live session changes during reconciliation, retry `thread/resume` after the writer finishes.
By default, `thread/resume` includes the reconstructed turn history in `thread.turns`. Experimental clients can pass `excludeTurns: true` to return only thread metadata and live resume state, then call `thread/turns/list` separately if they want to page the turn history over the network. In that mode the server also skips replaying restored `thread/tokenUsage/updated`, which avoids rebuilding turns just to attribute historical usage.
Experimental clients that want the live resume subscription plus a turns page in one round trip can pass `initialTurnsPage`. It accepts the same `limit`, `sortDirection`, and `itemsView` controls as `thread/turns/list`; omitted controls use its defaults. The response includes `initialTurnsPage` with `nextCursor` and `backwardsCursor` for follow-up pagination.
@@ -147,6 +147,35 @@ pub(crate) async fn apply_bespoke_event_handling(
thread_list_state_permit: Arc<tokio::sync::Semaphore>,
fallback_model_provider: String,
) {
apply_bespoke_event_handling_with_item_lifecycle_outgoing(
event,
conversation_id,
conversation,
thread_manager,
outgoing,
thread_state,
thread_watch_manager,
thread_list_state_permit,
fallback_model_provider,
/*item_lifecycle_outgoing*/ None,
)
.await;
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn apply_bespoke_event_handling_with_item_lifecycle_outgoing(
event: Event,
conversation_id: ThreadId,
conversation: Arc<CodexThread>,
thread_manager: Arc<ThreadManager>,
outgoing: ThreadScopedOutgoingMessageSender,
thread_state: Arc<tokio::sync::Mutex<ThreadState>>,
thread_watch_manager: ThreadWatchManager,
thread_list_state_permit: Arc<tokio::sync::Semaphore>,
fallback_model_provider: String,
item_lifecycle_outgoing: Option<ThreadScopedOutgoingMessageSender>,
) {
let item_lifecycle_outgoing = item_lifecycle_outgoing.as_ref().unwrap_or(&outgoing);
let Event {
id: event_turn_id,
msg,
@@ -282,7 +311,7 @@ pub(crate) async fn apply_bespoke_event_handling(
completion_item.cwd.clone(),
completion_item.command_actions.clone(),
CommandExecutionSource::Agent,
&outgoing,
item_lifecycle_outgoing,
&thread_state,
)
.await;
@@ -317,7 +346,7 @@ pub(crate) async fn apply_bespoke_event_handling(
CommandExecutionSource::Agent,
completion_item.command_actions,
completion_status,
&outgoing,
item_lifecycle_outgoing,
&thread_state,
)
.await;
@@ -844,7 +873,7 @@ pub(crate) async fn apply_bespoke_event_handling(
started_at_ms: request.started_at_ms,
item,
};
outgoing
item_lifecycle_outgoing
.send_server_notification(ServerNotification::ItemStarted(notification))
.await;
let params = DynamicToolCallParams {
@@ -1190,7 +1219,8 @@ pub(crate) async fn apply_bespoke_event_handling(
state.pending_rollbacks.take()
};
if let Some(request_id) = pending {
if let Some(pending) = pending {
let request_id = pending.request_id.clone();
let _thread_list_state_permit = match thread_list_state_permit.acquire().await {
Ok(permit) => permit,
Err(err) => {
@@ -1202,6 +1232,7 @@ pub(crate) async fn apply_bespoke_event_handling(
)),
)
.await;
pending.complete();
return;
}
};
@@ -1222,6 +1253,7 @@ pub(crate) async fn apply_bespoke_event_handling(
)),
)
.await;
pending.complete();
return;
}
};
@@ -1240,11 +1272,13 @@ pub(crate) async fn apply_bespoke_event_handling(
outgoing
.send_error(request_id.clone(), internal_error(err))
.await;
pending.complete();
return;
}
};
outgoing.send_response(request_id, response).await;
pending.complete();
}
}
EventMsg::ThreadGoalUpdated(thread_goal_event) => {
@@ -1460,7 +1494,7 @@ async fn complete_command_execution_item(
.await;
}
async fn maybe_emit_raw_response_item_completed(
pub(crate) async fn maybe_emit_raw_response_item_completed(
conversation_id: ThreadId,
turn_id: &str,
item: codex_protocol::models::ResponseItem,
@@ -1482,18 +1516,7 @@ pub(crate) async fn maybe_emit_hook_prompt_item_completed(
item: &codex_protocol::models::ResponseItem,
outgoing: &ThreadScopedOutgoingMessageSender,
) {
let codex_protocol::models::ResponseItem::Message {
role, content, id, ..
} = item
else {
return;
};
if role != "user" {
return;
}
let Some(hook_prompt) = parse_hook_prompt_message(id.as_ref(), content) else {
let Some(item) = hook_prompt_thread_item(item) else {
return;
};
@@ -1501,20 +1524,39 @@ pub(crate) async fn maybe_emit_hook_prompt_item_completed(
thread_id: conversation_id.to_string(),
turn_id: turn_id.to_string(),
completed_at_ms: now_unix_timestamp_ms(),
item: ThreadItem::HookPrompt {
id: hook_prompt.id,
fragments: hook_prompt
.fragments
.into_iter()
.map(codex_app_server_protocol::HookPromptFragment::from)
.collect(),
},
item,
};
outgoing
.send_server_notification(ServerNotification::ItemCompleted(notification))
.await;
}
pub(crate) fn hook_prompt_thread_item(
item: &codex_protocol::models::ResponseItem,
) -> Option<ThreadItem> {
let codex_protocol::models::ResponseItem::Message {
role, content, id, ..
} = item
else {
return None;
};
if role != "user" {
return None;
}
let hook_prompt = parse_hook_prompt_message(id.as_ref(), content)?;
Some(ThreadItem::HookPrompt {
id: hook_prompt.id,
fragments: hook_prompt
.fragments
.into_iter()
.map(codex_app_server_protocol::HookPromptFragment::from)
.collect(),
})
}
async fn find_and_remove_turn_summary(
_conversation_id: ThreadId,
thread_state: &Arc<Mutex<ThreadState>>,
@@ -1584,10 +1626,14 @@ async fn handle_thread_rollback_failed(
) {
let pending_rollback = thread_state.lock().await.pending_rollbacks.take();
if let Some(request_id) = pending_rollback {
if let Some(pending_rollback) = pending_rollback {
outgoing
.send_error(request_id, invalid_request(message))
.send_error(
pending_rollback.request_id.clone(),
invalid_request(message),
)
.await;
pending_rollback.complete();
}
}
@@ -1,4 +1,5 @@
use crate::bespoke_event_handling::apply_bespoke_event_handling;
use crate::bespoke_event_handling::apply_bespoke_event_handling_with_item_lifecycle_outgoing;
use crate::bespoke_event_handling::maybe_emit_hook_prompt_item_completed;
use crate::command_exec::CommandExecManager;
use crate::command_exec::StartCommandExecParams;
@@ -318,6 +319,7 @@ use codex_core::SessionMeta;
use codex_core::StartThreadOptions;
use codex_core::SteerInputError;
use codex_core::ThreadConfigSnapshot;
use codex_core::ThreadHistoryReconciliationOutcome;
use codex_core::ThreadManager;
use codex_core::config::Config;
use codex_core::config::ConfigOverrides;
@@ -541,9 +543,12 @@ use crate::filters::compute_source_filters;
use crate::filters::source_kind_matches;
use crate::thread_state::ConnectionCapabilities;
use crate::thread_state::ThreadListenerCommand;
use crate::thread_state::ThreadPointOperationLeaseAcquireResult;
use crate::thread_state::ThreadState;
use crate::thread_state::ThreadStateManager;
use token_usage_replay::latest_token_usage_info_from_rollout_items;
use token_usage_replay::latest_token_usage_turn_id_from_rollout_items;
use token_usage_replay::send_thread_token_usage_snapshot_to_connection;
use token_usage_replay::send_thread_token_usage_update_to_connection;
fn resolve_request_cwd(cwd: Option<PathBuf>) -> Result<Option<AbsolutePathBuf>, JSONRPCErrorError> {
@@ -1,5 +1,11 @@
use super::*;
use crate::bespoke_event_handling::hook_prompt_thread_item;
use crate::bespoke_event_handling::maybe_emit_raw_response_item_completed;
use codex_protocol::config_types::MultiAgentMode;
use codex_protocol::protocol::Event;
use std::collections::VecDeque;
use std::future::Future;
use tokio::sync::mpsc;
pub(super) const THREAD_UNLOADING_DELAY: Duration = Duration::from_secs(30 * 60);
@@ -20,6 +26,7 @@ struct UnloadingState {
delay: Duration,
has_subscribers_rx: watch::Receiver<bool>,
has_subscribers: (bool, Instant),
point_operation_count_rx: watch::Receiver<usize>,
thread_status_rx: watch::Receiver<ThreadStatus>,
is_active: (bool, Instant),
}
@@ -34,6 +41,10 @@ impl UnloadingState {
.thread_state_manager
.subscribe_to_has_connections(thread_id)
.await?;
let point_operation_count_rx = listener_task_context
.thread_state_manager
.subscribe_to_point_operation_count(thread_id)
.await?;
let thread_status_rx = listener_task_context
.thread_watch_manager
.subscribe(thread_id)
@@ -47,12 +58,16 @@ impl UnloadingState {
delay,
has_subscribers_rx,
has_subscribers,
point_operation_count_rx,
thread_status_rx,
is_active,
})
}
fn unloading_target(&self) -> Option<Instant> {
if *self.point_operation_count_rx.borrow() != 0 {
return None;
}
match (self.has_subscribers, self.is_active) {
((false, has_no_subscribers_since), (false, is_inactive_since)) => {
Some(std::cmp::max(has_no_subscribers_since, is_inactive_since) + self.delay)
@@ -109,6 +124,11 @@ impl UnloadingState {
}
self.sync_receiver_values();
},
changed = self.point_operation_count_rx.changed() => {
if changed.is_err() {
return false;
}
},
changed = self.thread_status_rx.changed() => {
if changed.is_err() {
return false;
@@ -131,6 +151,31 @@ pub(super) enum EnsureConversationListenerResult {
ConnectionClosed,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) struct ResumeEventCoverage {
pub(super) represented_in_resume_snapshot: bool,
pub(super) request_live_for_resumed_connection: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum ResumePayloadMode {
Full,
Redacted,
}
impl ResumePayloadMode {
fn is_redacted(self) -> bool {
matches!(self, Self::Redacted)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) struct BufferedRawResponseRouting {
pub(super) event_coverage: ResumeEventCoverage,
pub(super) raw_events_enabled: bool,
pub(super) resume_payload_mode: ResumePayloadMode,
}
#[expect(
clippy::await_holding_invalid_type,
reason = "listener subscription must be serialized against pending unloads"
@@ -240,7 +285,7 @@ pub(super) async fn ensure_listener_task_running(
.await;
let thread_settings_baseline =
thread_settings_from_config_snapshot(&conversation.config_snapshot().await);
let (mut listener_command_rx, listener_generation) = {
let (mut listener_command_rx, listener_command_tx, listener_generation) = {
let mut thread_state = thread_state.lock().await;
if thread_state.listener_matches(&conversation) {
return Ok(());
@@ -259,8 +304,12 @@ pub(super) async fn ensure_listener_task_running(
};
listener_task_context
.thread_state_manager
.register_listener_command_tx(conversation_id, listener_command_tx);
(listener_command_rx, listener_generation)
.register_listener_command_tx(conversation_id, listener_command_tx.clone());
(
listener_command_rx,
listener_command_tx,
listener_generation,
)
};
let ListenerTaskContext {
outgoing,
@@ -275,7 +324,40 @@ pub(super) async fn ensure_listener_task_running(
} = listener_task_context;
let outgoing_for_task = Arc::clone(&outgoing);
tokio::spawn(async move {
let resume_worker_cancel = CancellationToken::new();
let _resume_worker_cancel_guard = resume_worker_cancel.clone().drop_guard();
let mut resume_in_flight = false;
let mut buffered_resume_events = Vec::new();
let mut resume_exec_delta_replay = ResumeExecDeltaReplay::default();
let mut deferred_listener_commands = VecDeque::new();
loop {
if !resume_in_flight {
while let Some(listener_command) = deferred_listener_commands.pop_front() {
let transition = handle_thread_listener_command(
conversation_id,
&conversation,
codex_home.as_path(),
&thread_manager,
&thread_state_manager,
&thread_state,
&thread_watch_manager,
&thread_list_state_permit,
&fallback_model_provider,
&outgoing_for_task,
&pending_thread_unloads,
&listener_command_tx,
&resume_worker_cancel,
&mut buffered_resume_events,
&mut resume_exec_delta_replay,
listener_command,
)
.await;
apply_listener_command_transition(&mut resume_in_flight, transition);
if resume_in_flight {
break;
}
}
}
tokio::select! {
biased;
_ = &mut cancel_rx => {
@@ -286,18 +368,30 @@ pub(super) async fn ensure_listener_task_running(
let Some(listener_command) = listener_command else {
break;
};
handle_thread_listener_command(
if should_defer_listener_command(resume_in_flight, &listener_command) {
deferred_listener_commands.push_back(listener_command);
continue;
}
let transition = handle_thread_listener_command(
conversation_id,
&conversation,
codex_home.as_path(),
&thread_manager,
&thread_state_manager,
&thread_state,
&thread_watch_manager,
&thread_list_state_permit,
&fallback_model_provider,
&outgoing_for_task,
&pending_thread_unloads,
&listener_command_tx,
&resume_worker_cancel,
&mut buffered_resume_events,
&mut resume_exec_delta_replay,
listener_command,
)
.await;
apply_listener_command_transition(&mut resume_in_flight, transition);
}
event = conversation.next_event() => {
let event = match event {
@@ -308,46 +402,42 @@ pub(super) async fn ensure_listener_task_running(
}
};
// Track the event before emitting any typed translations
// so thread-local state such as raw event opt-in stays
// synchronized with the conversation.
let raw_events_enabled = {
let mut thread_state = thread_state.lock().await;
thread_state.track_current_turn_event(&event.id, &event.msg);
thread_state.experimental_raw_events
let event = if resume_in_flight {
match route_resume_in_flight_event(
event,
/*has_buffered_prefix*/ !buffered_resume_events.is_empty(),
) {
ResumeInFlightEvent::DispatchImmediately(event) => {
resume_exec_delta_replay.retain(&event);
event
}
ResumeInFlightEvent::Buffer(buffered) => {
buffered_resume_events.push(buffered);
continue;
}
}
} else {
event
};
let raw_events_enabled =
track_thread_event(&thread_state, &event).await;
let subscribed_connection_ids = thread_state_manager
.subscribed_connection_ids(conversation_id)
.await;
let thread_outgoing = ThreadScopedOutgoingMessageSender::new(
outgoing_for_task.clone(),
dispatch_thread_event(
event,
conversation_id,
&conversation,
&thread_manager,
&thread_state,
&thread_watch_manager,
&thread_list_state_permit,
&fallback_model_provider,
&outgoing_for_task,
subscribed_connection_ids,
conversation_id,
);
if let EventMsg::RawResponseItem(raw_response_item_event) = &event.msg
&& !raw_events_enabled
{
maybe_emit_hook_prompt_item_completed(
conversation_id,
&event.id,
&raw_response_item_event.item,
&thread_outgoing,
)
.await;
continue;
}
apply_bespoke_event_handling(
event.clone(),
conversation_id,
conversation.clone(),
thread_manager.clone(),
thread_outgoing,
thread_state.clone(),
thread_watch_manager.clone(),
thread_list_state_permit.clone(),
fallback_model_provider.clone(),
/*item_lifecycle_connection_ids*/ None,
raw_events_enabled,
)
.await;
}
@@ -387,6 +477,8 @@ pub(super) async fn ensure_listener_task_running(
}
}
resume_worker_cancel.cancel();
let mut thread_state = thread_state.lock().await;
if thread_state.listener_generation == listener_generation {
thread_state_manager.unregister_listener_command_tx(conversation_id);
@@ -396,6 +488,93 @@ pub(super) async fn ensure_listener_task_running(
Ok(())
}
async fn track_thread_event(thread_state: &Arc<Mutex<ThreadState>>, event: &Event) -> bool {
// Track before emitting typed translations so thread-local state, including the active-turn
// overlay and raw event opt-in, stays synchronized with the core conversation.
let mut thread_state = thread_state.lock().await;
thread_state.track_current_turn_event(&event.id, &event.msg);
thread_state.experimental_raw_events
}
#[allow(clippy::too_many_arguments)]
async fn dispatch_thread_event(
event: Event,
conversation_id: ThreadId,
conversation: &Arc<CodexThread>,
thread_manager: &Arc<ThreadManager>,
thread_state: &Arc<Mutex<ThreadState>>,
thread_watch_manager: &ThreadWatchManager,
thread_list_state_permit: &Arc<Semaphore>,
fallback_model_provider: &str,
outgoing: &Arc<OutgoingMessageSender>,
subscribed_connection_ids: Vec<ConnectionId>,
item_lifecycle_connection_ids: Option<Vec<ConnectionId>>,
raw_events_enabled: bool,
) {
let thread_outgoing = ThreadScopedOutgoingMessageSender::new(
Arc::clone(outgoing),
subscribed_connection_ids,
conversation_id,
);
if let EventMsg::RawResponseItem(raw_response_item_event) = &event.msg
&& !raw_events_enabled
{
maybe_emit_hook_prompt_item_completed(
conversation_id,
&event.id,
&raw_response_item_event.item,
&thread_outgoing,
)
.await;
return;
}
let item_lifecycle_outgoing = item_lifecycle_connection_ids.map(|connection_ids| {
ThreadScopedOutgoingMessageSender::new(
Arc::clone(outgoing),
connection_ids,
conversation_id,
)
});
if let Some(item_lifecycle_outgoing) = item_lifecycle_outgoing {
apply_bespoke_event_handling_with_item_lifecycle_outgoing(
event,
conversation_id,
Arc::clone(conversation),
Arc::clone(thread_manager),
thread_outgoing,
Arc::clone(thread_state),
thread_watch_manager.clone(),
Arc::clone(thread_list_state_permit),
fallback_model_provider.to_string(),
Some(item_lifecycle_outgoing),
)
.await;
} else {
apply_bespoke_event_handling(
event,
conversation_id,
Arc::clone(conversation),
Arc::clone(thread_manager),
thread_outgoing,
Arc::clone(thread_state),
thread_watch_manager.clone(),
Arc::clone(thread_list_state_permit),
fallback_model_provider.to_string(),
)
.await;
}
}
#[path = "thread_lifecycle/resume_event_coverage.rs"]
mod resume_event_coverage;
use resume_event_coverage::*;
#[path = "thread_lifecycle/resume_event_dispatch.rs"]
mod resume_event_dispatch;
use resume_event_dispatch::*;
pub(super) async fn wait_for_thread_shutdown(thread: &Arc<CodexThread>) -> ThreadShutdownResult {
match tokio::time::timeout(Duration::from_secs(10), thread.shutdown_and_wait()).await {
Ok(Ok(())) => ThreadShutdownResult::Complete,
@@ -456,258 +635,13 @@ pub(super) async fn unload_thread_without_subscribers(
});
}
#[allow(clippy::too_many_arguments)]
pub(super) async fn handle_thread_listener_command(
conversation_id: ThreadId,
conversation: &Arc<CodexThread>,
codex_home: &Path,
thread_state_manager: &ThreadStateManager,
thread_state: &Arc<Mutex<ThreadState>>,
thread_watch_manager: &ThreadWatchManager,
outgoing: &Arc<OutgoingMessageSender>,
pending_thread_unloads: &Arc<Mutex<HashSet<ThreadId>>>,
listener_command: ThreadListenerCommand,
) {
match listener_command {
ThreadListenerCommand::SendThreadResumeResponse(resume_request) => {
handle_pending_thread_resume_request(
conversation_id,
conversation,
codex_home,
thread_state_manager,
thread_state,
thread_watch_manager,
outgoing,
pending_thread_unloads,
*resume_request,
)
.await;
}
ThreadListenerCommand::EmitThreadGoalUpdated { turn_id, goal } => {
outgoing
.send_server_notification(ServerNotification::ThreadGoalUpdated(
ThreadGoalUpdatedNotification {
thread_id: conversation_id.to_string(),
turn_id,
goal,
},
))
.await;
}
ThreadListenerCommand::EmitThreadGoalCleared => {
outgoing
.send_server_notification(ServerNotification::ThreadGoalCleared(
ThreadGoalClearedNotification {
thread_id: conversation_id.to_string(),
},
))
.await;
}
ThreadListenerCommand::EmitThreadGoalSnapshot { state_db } => {
send_thread_goal_snapshot_notification(outgoing, conversation_id, &state_db).await;
}
ThreadListenerCommand::ResolveServerRequest {
request_id,
completion_tx,
} => {
resolve_pending_server_request(
conversation_id,
thread_state_manager,
outgoing,
request_id,
)
.await;
let _ = completion_tx.send(());
}
}
}
#[allow(clippy::too_many_arguments)]
#[expect(
clippy::await_holding_invalid_type,
reason = "running-thread resume subscription must be serialized against pending unloads"
)]
pub(super) async fn handle_pending_thread_resume_request(
conversation_id: ThreadId,
conversation: &Arc<CodexThread>,
_codex_home: &Path,
thread_state_manager: &ThreadStateManager,
thread_state: &Arc<Mutex<ThreadState>>,
thread_watch_manager: &ThreadWatchManager,
outgoing: &Arc<OutgoingMessageSender>,
pending_thread_unloads: &Arc<Mutex<HashSet<ThreadId>>>,
pending: crate::thread_state::PendingThreadResumeRequest,
) {
let active_turn = {
let state = thread_state.lock().await;
state.active_turn_snapshot()
};
tracing::debug!(
thread_id = %conversation_id,
request_id = ?pending.request_id,
active_turn_present = active_turn.is_some(),
active_turn_id = ?active_turn.as_ref().map(|turn| turn.id.as_str()),
active_turn_status = ?active_turn.as_ref().map(|turn| &turn.status),
"composing running thread resume response"
);
let has_live_in_progress_turn =
matches!(conversation.agent_status().await, AgentStatus::Running)
|| active_turn
.as_ref()
.is_some_and(|turn| matches!(turn.status, TurnStatus::InProgress));
let request_id = pending.request_id;
let connection_id = request_id.connection_id;
let mut thread = pending.thread_summary;
if pending.include_turns {
populate_thread_turns_from_history(
&mut thread,
&pending.history_items,
active_turn.as_ref(),
);
}
let thread_status = thread_watch_manager
.loaded_status_for_thread(&thread.id)
.await;
set_thread_status_and_interrupt_stale_turns(
&mut thread,
thread_status,
has_live_in_progress_turn,
);
let token_usage_thread = pending.include_turns.then(|| thread.clone());
let mut initial_turns_page = if let Some(params) = pending.initial_turns_page.as_ref() {
match super::thread_processor::build_thread_resume_initial_turns_page(
&pending.history_items,
thread.status.clone(),
has_live_in_progress_turn,
active_turn,
params,
) {
Ok(page) => Some(page),
Err(error) => {
outgoing.send_error(request_id, error).await;
return;
}
}
} else {
None
};
if pending.redact_resume_payloads {
redact_thread_resume_payloads(&mut thread.turns);
if let Some(initial_turns_page) = initial_turns_page.as_mut() {
redact_thread_resume_payloads(&mut initial_turns_page.data);
}
}
{
let pending_thread_unloads = pending_thread_unloads.lock().await;
if pending_thread_unloads.contains(&conversation_id) {
drop(pending_thread_unloads);
outgoing
.send_error(
request_id,
invalid_request(format!(
"thread {conversation_id} is closing; retry thread/resume after the thread is closed"
)),
)
.await;
return;
}
if !thread_state_manager
.try_add_connection_to_thread(conversation_id, connection_id)
.await
{
tracing::debug!(
thread_id = %conversation_id,
connection_id = ?connection_id,
"skipping running thread resume for closed connection"
);
return;
}
}
let config_snapshot = pending.config_snapshot;
let cwd = config_snapshot.cwd().clone();
let ThreadConfigSnapshot {
model,
model_provider_id,
service_tier,
approval_policy,
approvals_reviewer,
permission_profile,
active_permission_profile,
workspace_roots,
reasoning_effort,
originator,
..
} = config_snapshot;
let instruction_sources = pending.instruction_sources;
let sandbox = thread_response_sandbox_policy(&permission_profile, cwd.as_path());
let active_permission_profile =
thread_response_active_permission_profile(active_permission_profile);
let session_id = conversation.session_configured().session_id.to_string();
thread.session_id = session_id;
let response = ThreadResumeResponse {
thread,
model,
model_provider: model_provider_id,
service_tier,
cwd,
runtime_workspace_roots: workspace_roots,
instruction_sources,
approval_policy: approval_policy.into(),
approvals_reviewer: approvals_reviewer.into(),
sandbox,
active_permission_profile,
reasoning_effort,
multi_agent_mode: MultiAgentMode::ExplicitRequestOnly,
initial_turns_page,
};
outgoing
.send_response_with_thread_originator(request_id, response, originator)
.await;
// Match cold resume: metadata-only resume should attach the listener without
// paying the cost of turn reconstruction for historical usage replay.
if let Some(token_usage_thread) = token_usage_thread {
let token_usage_turn_id = latest_token_usage_turn_id_from_rollout_items(
&pending.history_items,
token_usage_thread.turns.as_slice(),
);
// Rejoining a loaded thread has the same UI contract as a cold resume, but
// uses the live conversation state instead of reconstructing a new session.
send_thread_token_usage_update_to_connection(
outgoing,
connection_id,
conversation_id,
&token_usage_thread,
conversation.as_ref(),
token_usage_turn_id,
)
.await;
}
if pending.emit_thread_goal_update {
if let Some(state_db) = pending.thread_goal_state_db {
send_thread_goal_snapshot_notification(outgoing, conversation_id, &state_db).await;
} else {
tracing::warn!(
thread_id = %conversation_id,
"state db unavailable when reading thread goal for running thread resume"
);
}
}
outgoing
.replay_requests_to_connection_for_thread(connection_id, conversation_id)
.await;
// App-server owns resume response and snapshot ordering, so wait until
// replay completes before letting extensions react to the idle thread.
if pending.emit_thread_goal_update {
conversation.emit_thread_idle_lifecycle_if_idle().await;
}
}
#[path = "thread_lifecycle/resume_response.rs"]
mod resume_response;
use resume_response::*;
#[path = "thread_lifecycle/resume_worker.rs"]
mod resume_worker;
use resume_worker::*;
pub(super) async fn send_thread_goal_snapshot_notification(
outgoing: &Arc<OutgoingMessageSender>,
thread_id: ThreadId,
@@ -800,3 +734,7 @@ pub(super) fn set_thread_status_and_interrupt_stale_turns(
}
thread.status = status;
}
#[cfg(test)]
#[path = "thread_lifecycle_tests.rs"]
mod tests;
@@ -0,0 +1,441 @@
//! Classifies pre-cut thread events against a running-thread resume snapshot.
use super::*;
use std::collections::HashMap;
pub(super) struct BufferedThreadEvent {
pub(super) event: Event,
pub(super) represented_in_resume_snapshot: bool,
pub(super) request_live_for_resumed_connection: bool,
}
impl BufferedThreadEvent {
pub(super) fn from_resume_cut(event: Event) -> Self {
let represented_in_resume_snapshot =
is_persisted_rollout_item(&RolloutItem::EventMsg(event.msg.clone()));
Self {
event,
represented_in_resume_snapshot,
request_live_for_resumed_connection: true,
}
}
}
fn buffered_event_creates_pending_server_request(event: &EventMsg) -> bool {
matches!(
event,
EventMsg::ExecApprovalRequest(_)
| EventMsg::RequestPermissions(_)
| EventMsg::RequestUserInput(_)
| EventMsg::DynamicToolCallRequest(_)
| EventMsg::ElicitationRequest(_)
| EventMsg::ApplyPatchApprovalRequest(_)
)
}
fn buffered_event_cancels_pending_server_requests(event: &EventMsg) -> bool {
matches!(
event,
EventMsg::TurnStarted(_) | EventMsg::TurnComplete(_) | EventMsg::TurnAborted(_)
)
}
/// Marks buffered request events that remain live at the resume snapshot boundary.
///
/// Existing subscribers still receive the full event sequence. The resumed connection starts
/// from the final snapshot, so it must not receive a request that a later buffered turn transition
/// has already invalidated. The return value applies the same projection to requests that were
/// pending before the cut.
pub(super) fn project_buffered_request_liveness(
buffered_events: &mut [BufferedThreadEvent],
) -> bool {
let mut later_event_cancels_requests = false;
for buffered in buffered_events.iter_mut().rev() {
if buffered_event_creates_pending_server_request(&buffered.event.msg) {
buffered.request_live_for_resumed_connection = !later_event_cancels_requests;
}
if buffered_event_cancels_pending_server_requests(&buffered.event.msg) {
later_event_cancels_requests = true;
}
}
!later_event_cancels_requests
}
fn turn_in_resume_payload<'a>(
turn_id: &str,
thread_turns: &'a [Turn],
initial_turns_page: Option<&'a codex_app_server_protocol::TurnsPage>,
) -> Option<&'a Turn> {
let mut turns = thread_turns.iter().chain(
initial_turns_page
.into_iter()
.flat_map(|page| page.data.iter()),
);
// The same turn can appear in both response fields. Prefer a full item view so an
// item-producing event is suppressed only when one of those fields actually carries it.
turns
.clone()
.find(|turn| turn.id == turn_id && matches!(turn.items_view, TurnItemsView::Full))
.or_else(|| turns.find(|turn| turn.id == turn_id))
}
fn serialized_thread_items(
left: &ThreadItem,
right: &ThreadItem,
) -> Option<(serde_json::Value, serde_json::Value)> {
let left = serde_json::to_value(left).ok()?;
let right = serde_json::to_value(right).ok()?;
(left.get("type") == right.get("type")).then_some((left, right))
}
fn thread_items_share_stable_id(left: &ThreadItem, right: &ThreadItem) -> bool {
let Some((left, right)) = serialized_thread_items(left, right) else {
return false;
};
left.get("id").is_some() && left.get("id") == right.get("id")
}
fn thread_items_match_without_generated_id(left: &ThreadItem, right: &ThreadItem) -> bool {
let Some((mut left, mut right)) = serialized_thread_items(left, right) else {
return false;
};
// Legacy history reconstruction assigns generated ids to user/agent items while the
// canonical lifecycle event retains the model item id. Compare their remaining content so a
// Full resume payload does not get followed by a duplicate item notification.
let Some(left) = left.as_object_mut() else {
return false;
};
let Some(right) = right.as_object_mut() else {
return false;
};
left.remove("id");
right.remove("id");
left == right
}
struct ResumePayloadItemCoverageEntry {
turn_id: String,
item: ThreadItem,
claimed_canonical_id: Option<String>,
}
pub(super) struct ResumePayloadItemCoverage {
entries: Vec<ResumePayloadItemCoverageEntry>,
}
impl ResumePayloadItemCoverage {
pub(super) fn new<'a>(
thread_turns: &'a [Turn],
initial_turns_page: Option<&'a codex_app_server_protocol::TurnsPage>,
) -> Self {
let mut entries = Vec::new();
let mut selected_turns: Vec<&Turn> = Vec::new();
let mut selected_turn_indexes: HashMap<&str, usize> = HashMap::new();
for turn in thread_turns.iter().chain(
initial_turns_page
.into_iter()
.flat_map(|page| page.data.iter()),
) {
if let Some(index) = selected_turn_indexes.get(turn.id.as_str()).copied() {
if !matches!(selected_turns[index].items_view, TurnItemsView::Full)
&& matches!(turn.items_view, TurnItemsView::Full)
{
selected_turns[index] = turn;
}
} else {
selected_turn_indexes.insert(turn.id.as_str(), selected_turns.len());
selected_turns.push(turn);
}
}
for turn in selected_turns {
entries.extend(
turn.items
.iter()
.cloned()
.map(|item| ResumePayloadItemCoverageEntry {
turn_id: turn.id.clone(),
item,
claimed_canonical_id: None,
}),
);
}
Self { entries }
}
fn consume_canonical_item(
&mut self,
turn_id: &str,
item: &ThreadItem,
phase: CanonicalItemPhase,
) -> bool {
if let Some(entry) = self.entries.iter_mut().find(|entry| {
entry.turn_id == turn_id && thread_items_share_stable_id(&entry.item, item)
}) {
// A final snapshot dominates ItemStarted. ItemCompleted additionally requires the
// returned item to carry the completed state/content; an in-progress same-id item is
// not enough when the durable legacy end fell after the cut.
let represented = matches!(phase, CanonicalItemPhase::Started)
|| thread_items_match_without_generated_id(&entry.item, item);
if represented && matches!(phase, CanonicalItemPhase::Completed) {
let canonical_id = item.id();
if entry
.claimed_canonical_id
.as_deref()
.is_some_and(|claimed| claimed != canonical_id)
{
return false;
}
entry.claimed_canonical_id = Some(canonical_id.to_string());
}
return represented;
}
if !item_can_have_generated_history_id(item) {
return false;
}
let canonical_id = item.id();
if let Some(entry) = self.entries.iter().find(|entry| {
entry.turn_id == turn_id && entry.claimed_canonical_id.as_deref() == Some(canonical_id)
}) {
// The completion is processed first (classification runs in reverse), binding the
// generated history occurrence. Its earlier ItemStarted may reuse that binding even
// when the start payload was partial. A completion still requires exact final state.
return matches!(phase, CanonicalItemPhase::Started)
|| thread_items_match_without_generated_id(&entry.item, item);
}
// A different canonical id consumes a different generated-id occurrence.
let Some(entry) = self.entries.iter_mut().find(|entry| {
entry.turn_id == turn_id
&& entry.claimed_canonical_id.is_none()
&& thread_items_match_without_generated_id(&entry.item, item)
}) else {
return false;
};
entry.claimed_canonical_id = Some(canonical_id.to_string());
true
}
fn covers_item_delta(&self, turn_id: &str, canonical_item_id: &str) -> bool {
self.entries.iter().any(|entry| {
entry.turn_id == turn_id
&& entry.claimed_canonical_id.as_deref() == Some(canonical_item_id)
})
}
}
#[derive(Clone, Copy)]
enum CanonicalItemPhase {
Started,
Completed,
}
fn item_can_have_generated_history_id(item: &ThreadItem) -> bool {
matches!(
item,
ThreadItem::UserMessage { .. }
| ThreadItem::HookPrompt { .. }
| ThreadItem::AgentMessage { .. }
| ThreadItem::Reasoning { .. }
| ThreadItem::ContextCompaction { .. }
)
}
fn projected_item_event(event: &Event) -> Option<(String, ThreadItem, CanonicalItemPhase)> {
if let EventMsg::GuardianAssessment(payload) = &event.msg {
let (status, phase) = match payload.status {
codex_protocol::protocol::GuardianAssessmentStatus::InProgress => (
codex_app_server_protocol::CommandExecutionStatus::InProgress,
CanonicalItemPhase::Started,
),
codex_protocol::protocol::GuardianAssessmentStatus::Denied
| codex_protocol::protocol::GuardianAssessmentStatus::Aborted => (
codex_app_server_protocol::CommandExecutionStatus::Declined,
CanonicalItemPhase::Completed,
),
codex_protocol::protocol::GuardianAssessmentStatus::TimedOut => (
codex_app_server_protocol::CommandExecutionStatus::Failed,
CanonicalItemPhase::Completed,
),
codex_protocol::protocol::GuardianAssessmentStatus::Approved => return None,
};
let item = codex_app_server_protocol::build_item_from_guardian_event(payload, status)?;
let turn_id = if payload.turn_id.is_empty() {
event.id.clone()
} else {
payload.turn_id.clone()
};
return Some((turn_id, item, phase));
}
if let EventMsg::DynamicToolCallRequest(payload) = &event.msg {
let turn_id = if payload.turn_id.is_empty() {
event.id.clone()
} else {
payload.turn_id.clone()
};
let item = ThreadItem::DynamicToolCall {
id: payload.call_id.clone(),
namespace: payload.namespace.clone(),
tool: payload.tool.clone(),
arguments: payload.arguments.clone(),
status: codex_app_server_protocol::DynamicToolCallStatus::InProgress,
content_items: None,
success: None,
duration_ms: None,
};
return Some((turn_id, item, CanonicalItemPhase::Started));
}
if let Some(notification) = codex_app_server_protocol::try_item_event_to_server_notification(
event.msg.clone(),
"",
&event.id,
) {
return match notification {
ServerNotification::ItemStarted(notification) => Some((
notification.turn_id,
notification.item,
CanonicalItemPhase::Started,
)),
ServerNotification::ItemCompleted(notification) => Some((
notification.turn_id,
notification.item,
CanonicalItemPhase::Completed,
)),
_ => None,
};
}
// Patch lifecycle notifications are intentionally hidden from v2 clients, but the final
// patch item still needs to claim its snapshot occurrence so a preceding patch delta is not
// replayed after that final state.
if let EventMsg::PatchApplyEnd(event_msg) = &event.msg {
let turn_id = if event_msg.turn_id.is_empty() {
event.id.clone()
} else {
event_msg.turn_id.clone()
};
return Some((
turn_id,
codex_app_server_protocol::build_file_change_end_item(event_msg),
CanonicalItemPhase::Completed,
));
}
None
}
fn buffered_item_delta_target(event: &Event) -> Option<(&str, &str)> {
match &event.msg {
EventMsg::AgentMessageContentDelta(event) => Some((&event.turn_id, &event.item_id)),
EventMsg::PlanDelta(event) => Some((&event.turn_id, &event.item_id)),
EventMsg::ReasoningContentDelta(event) => Some((&event.turn_id, &event.item_id)),
EventMsg::ReasoningRawContentDelta(event) => Some((&event.turn_id, &event.item_id)),
EventMsg::AgentReasoningSectionBreak(payload) => Some((&event.id, &payload.item_id)),
EventMsg::ExecCommandOutputDelta(payload) => Some((&event.id, &payload.call_id)),
EventMsg::PatchApplyUpdated(payload) => Some((&event.id, &payload.call_id)),
_ => None,
}
}
fn item_payload_is_redacted_on_resume(item: &ThreadItem) -> bool {
matches!(
item,
ThreadItem::McpToolCall { .. } | ThreadItem::ImageGeneration { .. }
)
}
pub(super) fn buffered_event_is_represented_in_resume_payload(
buffered: &BufferedThreadEvent,
thread_turns: &[Turn],
initial_turns_page: Option<&codex_app_server_protocol::TurnsPage>,
item_coverage: &mut ResumePayloadItemCoverage,
resume_payload_mode: ResumePayloadMode,
) -> bool {
// A raw hook prompt has two independently routed projections: the typed HookPrompt can be
// represented in the snapshot, while the experimental raw notification never is. This
// classifier owns only the typed side; buffered dispatch handles the raw channel separately.
if let EventMsg::RawResponseItem(event) = &buffered.event.msg {
if let Some(item) = hook_prompt_thread_item(&event.item) {
return item_coverage.consume_canonical_item(
&buffered.event.id,
&item,
CanonicalItemPhase::Completed,
);
}
// Other raw response items have no typed projection.
return true;
}
if let Some((turn_id, item, phase)) = projected_item_event(&buffered.event) {
// Remote resume redaction removes image items and scrubs MCP payloads. Never follow that
// response with the original unredacted canonical event, even when pagination omitted it.
if resume_payload_mode.is_redacted() && item_payload_is_redacted_on_resume(&item) {
return true;
}
return item_coverage.consume_canonical_item(&turn_id, &item, phase);
}
if let Some((turn_id, item_id)) = buffered_item_delta_target(&buffered.event) {
// Classification runs in reverse, so a represented completion has already bound the
// canonical id to the final snapshot occurrence. Only then is it safe to drop deltas;
// omitted/partial items keep their stream updates.
return item_coverage.covers_item_delta(turn_id, item_id);
}
if !buffered.represented_in_resume_snapshot {
return false;
}
// Usage and goal state are not stored in a Turn. Replaying buffered TokenCount preserves both
// its usage and rate-limit notifications; the separate restored-usage replay is skipped below
// when this event already supplied it. Goal updates likewise use their notification/snapshot
// channel rather than turn coverage.
if matches!(
buffered.event.msg,
EventMsg::TokenCount(_) | EventMsg::ThreadGoalUpdated(_)
) {
return false;
}
let turn_id = match &buffered.event.msg {
EventMsg::TurnStarted(event) => event.turn_id.as_str(),
EventMsg::TurnComplete(event) => event.turn_id.as_str(),
EventMsg::TurnAborted(event) => event
.turn_id
.as_deref()
.unwrap_or(buffered.event.id.as_str()),
_ => buffered.event.id.as_str(),
};
let Some(turn) = turn_in_resume_payload(turn_id, thread_turns, initial_turns_page) else {
return false;
};
match &buffered.event.msg {
// Turn metadata is present even in summary/not-loaded pages.
EventMsg::TurnStarted(_) => true,
EventMsg::TurnComplete(_) | EventMsg::TurnAborted(_) => {
!matches!(turn.status, TurnStatus::InProgress)
}
// Other persisted turn events materialize as items. A summary or not-loaded page may
// omit that item, so only a full view proves the notification is represented.
_ => matches!(turn.items_view, TurnItemsView::Full),
}
}
pub(super) fn should_replay_reconciled_token_usage(
buffered_events: &[BufferedThreadEvent],
reconciled: Option<&codex_protocol::protocol::TokenUsageInfo>,
reconciled_turn_id: Option<&str>,
) -> bool {
let latest_buffered = buffered_events.iter().rev().find_map(|buffered| {
let EventMsg::TokenCount(event) = &buffered.event.msg else {
return None;
};
event
.info
.as_ref()
.map(|info| (info, buffered.event.id.as_str()))
});
match (latest_buffered, reconciled) {
(_, None) => false,
(None, Some(_)) => true,
(Some((buffered_info, buffered_turn_id)), Some(reconciled_info)) => {
buffered_info != reconciled_info || Some(buffered_turn_id) != reconciled_turn_id
}
}
}
@@ -0,0 +1,673 @@
use super::*;
#[test]
fn resume_cut_routes_snapshot_and_stream_events_without_duplicates_or_loss() {
let existing = ConnectionId(1);
let joining = ConnectionId(2);
assert_eq!(
buffered_event_recipients(
&[existing],
Some(joining),
ResumeEventCoverage {
represented_in_resume_snapshot: true,
request_live_for_resumed_connection: true,
},
),
vec![existing],
"a pre-cut persisted event belongs in the snapshot, not a joiner notification"
);
assert_eq!(
buffered_event_recipients(
&[existing],
Some(joining),
ResumeEventCoverage {
represented_in_resume_snapshot: false,
request_live_for_resumed_connection: true,
},
),
vec![existing, joining],
"a pre-cut stream-only event must be replayed to the joiner after the response"
);
assert_eq!(
buffered_event_recipients(
&[existing, joining],
Some(joining),
ResumeEventCoverage {
represented_in_resume_snapshot: true,
request_live_for_resumed_connection: true,
},
),
vec![existing],
"re-resume must not duplicate a snapshot event on an existing connection"
);
assert_eq!(
buffered_event_recipients(
&[existing, joining],
None,
ResumeEventCoverage {
represented_in_resume_snapshot: true,
request_live_for_resumed_connection: true,
},
),
vec![existing, joining],
"a failed resume must leave the original event stream untouched"
);
}
fn buffered_user_input_request(turn_id: &str) -> BufferedThreadEvent {
BufferedThreadEvent {
event: Event {
id: turn_id.to_string(),
msg: EventMsg::RequestUserInput(RequestUserInputEvent {
call_id: format!("request-{turn_id}"),
turn_id: turn_id.to_string(),
questions: Vec::new(),
auto_resolution_ms: None,
}),
},
represented_in_resume_snapshot: false,
request_live_for_resumed_connection: true,
}
}
fn buffered_turn_completion(turn_id: &str) -> BufferedThreadEvent {
BufferedThreadEvent {
event: Event {
id: turn_id.to_string(),
msg: EventMsg::TurnComplete(TurnCompleteEvent {
turn_id: turn_id.to_string(),
last_agent_message: None,
completed_at: Some(2),
duration_ms: Some(1_000),
time_to_first_token_ms: None,
}),
},
represented_in_resume_snapshot: true,
request_live_for_resumed_connection: true,
}
}
#[test]
fn resume_cut_projects_request_liveness_before_joiner_delivery() {
let existing = ConnectionId(1);
let joining = ConnectionId(2);
let mut terminal_only = vec![buffered_turn_completion("turn-a")];
assert!(
!project_buffered_request_liveness(&mut terminal_only),
"a buffered terminal transition invalidates pre-cut pending requests"
);
let mut dead_buffered_request = vec![
buffered_user_input_request("turn-a"),
buffered_turn_completion("turn-a"),
];
assert!(!project_buffered_request_liveness(
&mut dead_buffered_request
));
assert!(!dead_buffered_request[0].request_live_for_resumed_connection);
assert_eq!(
buffered_event_recipients(
&[existing],
Some(joining),
ResumeEventCoverage {
represented_in_resume_snapshot: false,
request_live_for_resumed_connection: dead_buffered_request[0]
.request_live_for_resumed_connection,
},
),
vec![existing],
"a request already canceled by the final snapshot must not reach the joiner"
);
let mut live_buffered_request = vec![
buffered_turn_completion("turn-a"),
buffered_user_input_request("turn-b"),
];
assert!(!project_buffered_request_liveness(
&mut live_buffered_request
));
assert!(live_buffered_request[1].request_live_for_resumed_connection);
assert_eq!(
buffered_event_recipients(
&[existing],
Some(joining),
ResumeEventCoverage {
represented_in_resume_snapshot: false,
request_live_for_resumed_connection: live_buffered_request[1]
.request_live_for_resumed_connection,
},
),
vec![existing, joining],
"a request created after the last canceling transition must reach the joiner once"
);
let mut no_transitions = vec![buffered_user_input_request("turn-a")];
assert!(
project_buffered_request_liveness(&mut no_transitions),
"without a buffered transition, pre-cut pending requests remain replayable"
);
}
fn buffered_completed_item(turn_id: &str, item: TurnItem) -> BufferedThreadEvent {
BufferedThreadEvent {
event: Event {
id: turn_id.to_string(),
msg: EventMsg::ItemCompleted(ItemCompletedEvent {
thread_id: ThreadId::new(),
turn_id: turn_id.to_string(),
item,
completed_at_ms: 2_000,
}),
},
represented_in_resume_snapshot: false,
request_live_for_resumed_connection: true,
}
}
fn buffered_started_item(turn_id: &str, item: TurnItem) -> BufferedThreadEvent {
BufferedThreadEvent {
event: Event {
id: turn_id.to_string(),
msg: EventMsg::ItemStarted(ItemStartedEvent {
thread_id: ThreadId::new(),
turn_id: turn_id.to_string(),
item,
started_at_ms: 1_000,
}),
},
represented_in_resume_snapshot: false,
request_live_for_resumed_connection: true,
}
}
fn buffered_exec_lifecycle(turn_id: &str) -> (BufferedThreadEvent, BufferedThreadEvent) {
let command = vec!["printf".to_string(), "done".to_string()];
let begin = ExecCommandBeginEvent {
call_id: "exec-1".to_string(),
process_id: Some("process-1".to_string()),
turn_id: turn_id.to_string(),
started_at_ms: 1_000,
command: command.clone(),
cwd: "file:///tmp".parse().expect("path uri"),
parsed_cmd: Vec::new(),
source: ExecCommandSource::Agent,
interaction_input: None,
};
let end = ExecCommandEndEvent {
call_id: "exec-1".to_string(),
process_id: Some("process-1".to_string()),
turn_id: turn_id.to_string(),
completed_at_ms: 2_000,
command,
cwd: "file:///tmp".parse().expect("path uri"),
parsed_cmd: Vec::new(),
source: ExecCommandSource::Agent,
interaction_input: None,
stdout: "done".to_string(),
stderr: String::new(),
aggregated_output: "done".to_string(),
exit_code: 0,
duration: Duration::from_millis(250),
formatted_output: "done".to_string(),
status: ExecCommandStatus::Completed,
};
(
BufferedThreadEvent {
event: Event {
id: turn_id.to_string(),
msg: EventMsg::ExecCommandBegin(begin),
},
represented_in_resume_snapshot: false,
request_live_for_resumed_connection: true,
},
BufferedThreadEvent {
event: Event {
id: turn_id.to_string(),
msg: EventMsg::ExecCommandEnd(end),
},
represented_in_resume_snapshot: false,
request_live_for_resumed_connection: true,
},
)
}
fn mcp_tool_item(id: &str, status: codex_protocol::items::McpToolCallStatus) -> TurnItem {
TurnItem::McpToolCall(McpToolCallItem {
id: id.to_string(),
server: "private".to_string(),
tool: "lookup".to_string(),
arguments: serde_json::json!({"secret": true}),
connector_id: None,
mcp_app_resource_uri: None,
link_id: None,
app_name: None,
template_id: None,
action_name: None,
plugin_id: None,
status,
result: None,
error: None,
duration: None,
})
}
#[test]
fn canonical_item_coverage_matches_generated_history_ids_and_respects_redaction() {
let buffered_agent = buffered_completed_item(
"latest-turn",
TurnItem::AgentMessage(AgentMessageItem {
id: "canonical-agent-id".to_string(),
content: vec![AgentMessageContent::Text {
text: "durable answer".to_string(),
}],
phase: None,
memory_citation: None,
}),
);
let mut full_turn = turn_with_view("latest-turn", TurnItemsView::Full, TurnStatus::Completed);
full_turn.items.push(ThreadItem::AgentMessage {
id: "item-2".to_string(),
text: "durable answer".to_string(),
phase: None,
memory_citation: None,
});
let full_turns = vec![full_turn];
assert!(
event_is_represented(&buffered_agent, &full_turns, None, ResumePayloadMode::Full,),
"canonical and rebuilt agent items with different ids must not be delivered twice"
);
let second_identical_agent = buffered_completed_item(
"latest-turn",
TurnItem::AgentMessage(AgentMessageItem {
id: "second-canonical-agent-id".to_string(),
content: vec![AgentMessageContent::Text {
text: "durable answer".to_string(),
}],
phase: None,
memory_citation: None,
}),
);
let mut occurrence_coverage = ResumePayloadItemCoverage::new(&full_turns, None);
assert!(buffered_event_is_represented_in_resume_payload(
&buffered_agent,
&full_turns,
None,
&mut occurrence_coverage,
ResumePayloadMode::Full,
));
assert!(
!buffered_event_is_represented_in_resume_payload(
&second_identical_agent,
&full_turns,
None,
&mut occurrence_coverage,
ResumePayloadMode::Full,
),
"one durable item cannot cover two identical canonical occurrences"
);
let same_canonical_id_item = AgentMessageItem {
id: "shared-canonical-agent-id".to_string(),
content: vec![AgentMessageContent::Text {
text: "durable answer".to_string(),
}],
phase: None,
memory_citation: None,
};
let mut lifecycle_pair = [
buffered_started_item(
"latest-turn",
TurnItem::AgentMessage(same_canonical_id_item.clone()),
),
buffered_completed_item(
"latest-turn",
TurnItem::AgentMessage(same_canonical_id_item),
),
];
let mut lifecycle_coverage = ResumePayloadItemCoverage::new(&full_turns, None);
for buffered in lifecycle_pair.iter_mut().rev() {
buffered.represented_in_resume_snapshot = buffered_event_is_represented_in_resume_payload(
buffered,
&full_turns,
None,
&mut lifecycle_coverage,
ResumePayloadMode::Full,
);
}
assert!(
lifecycle_pair
.iter()
.all(|buffered| buffered.represented_in_resume_snapshot),
"one generated-id final item must cover start and completion for the same canonical id"
);
let redacted_items = [
TurnItem::ImageGeneration(ImageGenerationItem {
id: "image-1".to_string(),
status: "completed".to_string(),
revised_prompt: Some("secret prompt".to_string()),
result: "secret image payload".to_string(),
saved_path: None,
}),
TurnItem::McpToolCall(McpToolCallItem {
id: "mcp-1".to_string(),
server: "private".to_string(),
tool: "lookup".to_string(),
arguments: serde_json::json!({"secret": true}),
connector_id: None,
mcp_app_resource_uri: None,
link_id: None,
app_name: None,
template_id: None,
action_name: None,
plugin_id: None,
status: codex_protocol::items::McpToolCallStatus::Completed,
result: None,
error: None,
duration: None,
}),
];
for item in redacted_items {
let buffered = buffered_completed_item("omitted-turn", item);
assert!(event_is_represented(
&buffered,
&[],
None,
ResumePayloadMode::Redacted,
));
assert!(
!event_is_represented(&buffered, &[], None, ResumePayloadMode::Full,),
"an omitted item remains replayable for an unredacted client"
);
}
let buffered_raw_image = BufferedThreadEvent {
event: Event {
id: "omitted-turn".to_string(),
msg: EventMsg::RawResponseItem(RawResponseItemEvent {
item: ResponseItem::ImageGenerationCall {
id: Some("raw-image".to_string()),
status: "completed".to_string(),
revised_prompt: Some("secret prompt".to_string()),
result: "secret base64".to_string(),
internal_chat_message_metadata_passthrough: None,
},
}),
},
represented_in_resume_snapshot: false,
request_live_for_resumed_connection: true,
};
assert!(event_is_represented(
&buffered_raw_image,
&[],
None,
ResumePayloadMode::Redacted,
));
assert!(event_is_represented(
&buffered_raw_image,
&[],
None,
ResumePayloadMode::Full,
));
}
#[test]
fn full_busy_snapshot_covers_projected_exec_lifecycle_but_omitted_items_do_not() {
let (begin, end) = buffered_exec_lifecycle("busy-turn");
let EventMsg::ExecCommandEnd(end_event) = &end.event.msg else {
unreachable!();
};
let mut full_turn = turn_with_view("busy-turn", TurnItemsView::Full, TurnStatus::InProgress);
full_turn
.items
.push(build_command_execution_end_item(end_event));
let full_turns = vec![full_turn];
let mut buffered = [begin, end];
let mut coverage = ResumePayloadItemCoverage::new(&full_turns, None);
for event in buffered.iter_mut().rev() {
event.represented_in_resume_snapshot = buffered_event_is_represented_in_resume_payload(
event,
&full_turns,
None,
&mut coverage,
ResumePayloadMode::Full,
);
}
assert!(
buffered
.iter()
.all(|event| event.represented_in_resume_snapshot),
"the final command in a busy snapshot dominates both buffered lifecycle events"
);
let omitted_turns = vec![turn_with_view(
"busy-turn",
TurnItemsView::NotLoaded,
TurnStatus::InProgress,
)];
assert!(
buffered.iter().all(|event| !event_is_represented(
event,
&omitted_turns,
None,
ResumePayloadMode::Full,
)),
"omitted lifecycle items must still be replayed after resume"
);
}
#[test]
fn raw_hook_prompt_routes_typed_and_raw_channels_independently() {
let fragments = vec![
HookPromptFragment::from_single_hook("Retry with tests.", "hook-run-1"),
HookPromptFragment::from_single_hook("Then summarize.", "hook-run-2"),
];
let mut raw_item = build_hook_prompt_message(&fragments).expect("hook prompt message");
let ResponseItem::Message { id, .. } = &mut raw_item else {
unreachable!();
};
*id = None;
let buffered = BufferedThreadEvent {
event: Event {
id: "busy-turn".to_string(),
msg: EventMsg::RawResponseItem(RawResponseItemEvent {
item: raw_item.clone(),
}),
},
represented_in_resume_snapshot: false,
request_live_for_resumed_connection: true,
};
let mut full_turn = turn_with_view("busy-turn", TurnItemsView::Full, TurnStatus::InProgress);
full_turn.items.push(ThreadItem::HookPrompt {
id: "history-generated-id".to_string(),
fragments: fragments
.iter()
.cloned()
.map(codex_app_server_protocol::HookPromptFragment::from)
.collect(),
});
let full_turns = vec![full_turn];
let mut typed_coverage = ResumePayloadItemCoverage::new(&full_turns, None);
assert!(buffered_event_is_represented_in_resume_payload(
&buffered,
&full_turns,
None,
&mut typed_coverage,
ResumePayloadMode::Full,
));
let second_identical = BufferedThreadEvent {
event: Event {
id: "busy-turn".to_string(),
msg: EventMsg::RawResponseItem(RawResponseItemEvent { item: raw_item }),
},
represented_in_resume_snapshot: false,
request_live_for_resumed_connection: true,
};
assert!(
!buffered_event_is_represented_in_resume_payload(
&second_identical,
&full_turns,
None,
&mut typed_coverage,
ResumePayloadMode::Full,
),
"one durable hook occurrence cannot cover two buffered hook prompts"
);
assert!(!event_is_represented(
&buffered,
&[],
None,
ResumePayloadMode::Full,
));
assert!(
!event_is_represented(&buffered, &[], None, ResumePayloadMode::Redacted),
"an omitted hook remains safe to replay as a typed item on redacted resume"
);
let existing = ConnectionId(1);
let joining = ConnectionId(2);
let (typed_recipients, raw_recipients) = buffered_raw_response_recipients(
&[existing],
Some(joining),
BufferedRawResponseRouting {
event_coverage: ResumeEventCoverage {
represented_in_resume_snapshot: true,
request_live_for_resumed_connection: true,
},
raw_events_enabled: true,
resume_payload_mode: ResumePayloadMode::Full,
},
);
assert_eq!(typed_recipients, vec![existing]);
assert_eq!(raw_recipients, vec![existing, joining]);
let (typed_recipients, raw_recipients) = buffered_raw_response_recipients(
&[existing],
Some(joining),
BufferedRawResponseRouting {
event_coverage: ResumeEventCoverage {
represented_in_resume_snapshot: false,
request_live_for_resumed_connection: true,
},
raw_events_enabled: true,
resume_payload_mode: ResumePayloadMode::Redacted,
},
);
assert_eq!(typed_recipients, vec![existing, joining]);
assert_eq!(raw_recipients, vec![existing]);
}
#[test]
fn canonical_completion_requires_final_state_and_stable_call_ids_never_normalize() {
use codex_protocol::items::McpToolCallStatus;
let mut in_progress_turn =
turn_with_view("latest-turn", TurnItemsView::Full, TurnStatus::InProgress);
let in_progress_api_item: ThreadItem =
mcp_tool_item("mcp-a", McpToolCallStatus::InProgress).into();
in_progress_turn.items.push(in_progress_api_item);
let completed_a = buffered_completed_item(
"latest-turn",
mcp_tool_item("mcp-a", McpToolCallStatus::Completed),
);
assert!(
!event_is_represented(
&completed_a,
&[in_progress_turn],
None,
ResumePayloadMode::Full,
),
"same-id in-progress state cannot cover a buffered completion"
);
let mut completed_turn =
turn_with_view("latest-turn", TurnItemsView::Full, TurnStatus::Completed);
let completed_api_item: ThreadItem =
mcp_tool_item("mcp-a", McpToolCallStatus::Completed).into();
completed_turn.items.push(completed_api_item);
assert!(event_is_represented(
&completed_a,
&[completed_turn.clone()],
None,
ResumePayloadMode::Full,
));
let completed_b = buffered_completed_item(
"latest-turn",
mcp_tool_item("mcp-b", McpToolCallStatus::Completed),
);
assert!(
!event_is_represented(
&completed_b,
&[completed_turn],
None,
ResumePayloadMode::Full,
),
"a different stable call id must not match by normalized payload"
);
}
#[test]
fn final_item_coverage_suppresses_folded_deltas_but_omitted_items_replay_them() {
let item = AgentMessageItem {
id: "canonical-agent-id".to_string(),
content: vec![AgentMessageContent::Text {
text: "final answer".to_string(),
}],
phase: None,
memory_citation: None,
};
let mut buffered = [
buffered_started_item("busy-turn", TurnItem::AgentMessage(item.clone())),
BufferedThreadEvent {
event: Event {
id: "busy-turn".to_string(),
msg: EventMsg::AgentMessageContentDelta(AgentMessageContentDeltaEvent {
thread_id: ThreadId::new().to_string(),
turn_id: "busy-turn".to_string(),
item_id: "canonical-agent-id".to_string(),
delta: "final answer".to_string(),
}),
},
represented_in_resume_snapshot: false,
request_live_for_resumed_connection: true,
},
buffered_completed_item("busy-turn", TurnItem::AgentMessage(item)),
];
let mut full_turn = turn_with_view("busy-turn", TurnItemsView::Full, TurnStatus::InProgress);
full_turn.items.push(ThreadItem::AgentMessage {
id: "history-generated-id".to_string(),
text: "final answer".to_string(),
phase: None,
memory_citation: None,
});
let full_turns = vec![full_turn];
let mut coverage = ResumePayloadItemCoverage::new(&full_turns, None);
for event in buffered.iter_mut().rev() {
event.represented_in_resume_snapshot = buffered_event_is_represented_in_resume_payload(
event,
&full_turns,
None,
&mut coverage,
ResumePayloadMode::Full,
);
}
assert!(
buffered
.iter()
.all(|event| event.represented_in_resume_snapshot),
"a full final item must own its start, folded delta, and completion"
);
assert!(buffered.iter().all(|event| !event_is_represented(
event,
&[],
None,
ResumePayloadMode::Full,
)));
}
@@ -0,0 +1,208 @@
//! Delivers pre-cut thread events after the resume response without loss or duplication.
use super::*;
pub(super) fn buffered_event_recipients(
pre_cut_connection_ids: &[ConnectionId],
resumed_connection_id: Option<ConnectionId>,
event_coverage: ResumeEventCoverage,
) -> Vec<ConnectionId> {
let mut recipients = pre_cut_connection_ids.to_vec();
if let Some(resumed_connection_id) = resumed_connection_id {
if event_coverage.represented_in_resume_snapshot
|| !event_coverage.request_live_for_resumed_connection
{
recipients.retain(|connection_id| *connection_id != resumed_connection_id);
} else if !recipients.contains(&resumed_connection_id) {
recipients.push(resumed_connection_id);
}
}
recipients
}
pub(super) fn buffered_raw_response_recipients(
pre_cut_connection_ids: &[ConnectionId],
resumed_connection_id: Option<ConnectionId>,
routing: BufferedRawResponseRouting,
) -> (Vec<ConnectionId>, Vec<ConnectionId>) {
let typed_hook_recipients = buffered_event_recipients(
pre_cut_connection_ids,
resumed_connection_id,
routing.event_coverage,
);
let mut raw_recipients = if routing.raw_events_enabled {
pre_cut_connection_ids.to_vec()
} else {
Vec::new()
};
if let Some(resumed_connection_id) = resumed_connection_id {
if routing.raw_events_enabled && !routing.resume_payload_mode.is_redacted() {
if !raw_recipients.contains(&resumed_connection_id) {
raw_recipients.push(resumed_connection_id);
}
} else {
raw_recipients.retain(|connection_id| *connection_id != resumed_connection_id);
}
}
(typed_hook_recipients, raw_recipients)
}
pub(super) fn buffered_event_delivery_recipients(
pre_cut_connection_ids: &[ConnectionId],
resumed_connection_id: Option<ConnectionId>,
event: &EventMsg,
event_coverage: ResumeEventCoverage,
) -> (Vec<ConnectionId>, Option<Vec<ConnectionId>>) {
let item_lifecycle_recipients = buffered_event_recipients(
pre_cut_connection_ids,
resumed_connection_id,
event_coverage,
);
let split_item_lifecycle = event_coverage.represented_in_resume_snapshot
&& matches!(
event,
EventMsg::GuardianAssessment(_) | EventMsg::DynamicToolCallRequest(_)
);
let mut recipients = item_lifecycle_recipients.clone();
if split_item_lifecycle
&& let Some(resumed_connection_id) = resumed_connection_id
&& (event_coverage.request_live_for_resumed_connection
|| matches!(event, EventMsg::GuardianAssessment(_)))
&& !recipients.contains(&resumed_connection_id)
{
// Guardian review notifications and dynamic-tool server requests are not represented by
// the item snapshot. Deliver those companions to the joiner while routing their
// already-snapshotted ItemStarted/ItemCompleted lifecycle only to prior subscribers.
recipients.push(resumed_connection_id);
}
(
recipients,
split_item_lifecycle.then_some(item_lifecycle_recipients),
)
}
pub(super) async fn dispatch_replayed_exec_deltas_to_connection(
replay: ResumeExecDeltaReplay,
connection_id: ConnectionId,
conversation_id: ThreadId,
outgoing: &Arc<OutgoingMessageSender>,
) {
let outgoing = ThreadScopedOutgoingMessageSender::new(
Arc::clone(outgoing),
vec![connection_id],
conversation_id,
);
let thread_id = conversation_id.to_string();
for buffered in replay.into_events() {
if buffered.represented_in_resume_snapshot {
continue;
}
let Event {
id: turn_id,
msg: EventMsg::ExecCommandOutputDelta(delta),
} = buffered.event
else {
debug_assert!(false, "resume exec replay contains a non-delta event");
continue;
};
let notification = codex_app_server_protocol::item_event_to_server_notification(
EventMsg::ExecCommandOutputDelta(delta),
&thread_id,
&turn_id,
);
outgoing.send_server_notification(notification).await;
}
}
#[allow(clippy::too_many_arguments)]
pub(super) async fn dispatch_buffered_thread_events(
buffered_events: Vec<BufferedThreadEvent>,
pre_cut_connection_ids: &[ConnectionId],
resumed_connection_id: Option<ConnectionId>,
conversation_id: ThreadId,
conversation: &Arc<CodexThread>,
thread_manager: &Arc<ThreadManager>,
thread_state: &Arc<Mutex<ThreadState>>,
thread_watch_manager: &ThreadWatchManager,
thread_list_state_permit: &Arc<Semaphore>,
fallback_model_provider: &str,
resume_payload_mode: ResumePayloadMode,
outgoing: &Arc<OutgoingMessageSender>,
) {
for buffered in buffered_events {
// Preserve normal listener semantics: every event mutates the live tracker immediately
// before its bespoke handler observes that state. The resume response used a clone-based
// final projection, so it never needs to pre-apply the backlog here.
let raw_events_enabled = track_thread_event(thread_state, &buffered.event).await;
if let EventMsg::RawResponseItem(raw_response_item_event) = &buffered.event.msg {
let (typed_hook_recipients, raw_recipients) = buffered_raw_response_recipients(
pre_cut_connection_ids,
resumed_connection_id,
BufferedRawResponseRouting {
event_coverage: ResumeEventCoverage {
represented_in_resume_snapshot: buffered.represented_in_resume_snapshot,
request_live_for_resumed_connection: true,
},
raw_events_enabled,
resume_payload_mode,
},
);
if !typed_hook_recipients.is_empty() {
let typed_outgoing = ThreadScopedOutgoingMessageSender::new(
Arc::clone(outgoing),
typed_hook_recipients,
conversation_id,
);
maybe_emit_hook_prompt_item_completed(
conversation_id,
&buffered.event.id,
&raw_response_item_event.item,
&typed_outgoing,
)
.await;
}
if !raw_recipients.is_empty() {
let raw_outgoing = ThreadScopedOutgoingMessageSender::new(
Arc::clone(outgoing),
raw_recipients,
conversation_id,
);
maybe_emit_raw_response_item_completed(
conversation_id,
&buffered.event.id,
raw_response_item_event.item.clone(),
&raw_outgoing,
)
.await;
}
continue;
}
// Persisted events are already reflected in the resume payload, so suppress their queued
// notification only for the joiner. Non-persisted stream events cannot be reconstructed
// and must be replayed after the response instead.
let (recipients, item_lifecycle_recipients) = buffered_event_delivery_recipients(
pre_cut_connection_ids,
resumed_connection_id,
&buffered.event.msg,
ResumeEventCoverage {
represented_in_resume_snapshot: buffered.represented_in_resume_snapshot,
request_live_for_resumed_connection: buffered.request_live_for_resumed_connection,
},
);
dispatch_thread_event(
buffered.event,
conversation_id,
conversation,
thread_manager,
thread_state,
thread_watch_manager,
thread_list_state_permit,
fallback_model_provider,
outgoing,
recipients,
item_lifecycle_recipients,
raw_events_enabled,
)
.await;
}
}
@@ -0,0 +1,197 @@
use super::*;
use codex_app_server_protocol::CommandExecutionStatus;
use codex_app_server_protocol::DynamicToolCallStatus;
use codex_app_server_protocol::build_item_from_guardian_event;
use codex_protocol::dynamic_tools::DynamicToolCallRequest;
use codex_protocol::protocol::GuardianAssessmentEvent;
use codex_protocol::protocol::GuardianAssessmentStatus;
fn guardian_assessment(status: GuardianAssessmentStatus) -> GuardianAssessmentEvent {
GuardianAssessmentEvent {
id: "guardian-review".to_string(),
target_item_id: Some("guardian-command".to_string()),
turn_id: "busy-turn".to_string(),
started_at_ms: 1_000,
completed_at_ms: (!matches!(status, GuardianAssessmentStatus::InProgress)).then_some(1_042),
status,
risk_level: None,
user_authorization: None,
rationale: None,
decision_source: None,
action: serde_json::from_value(serde_json::json!({
"type": "command",
"source": "shell",
"command": "printf guardian",
"cwd": "/tmp",
}))
.expect("guardian command action"),
}
}
fn dynamic_tool_request() -> DynamicToolCallRequest {
DynamicToolCallRequest {
call_id: "dynamic-call".to_string(),
turn_id: "busy-turn".to_string(),
started_at_ms: 1_000,
namespace: Some("workspace".to_string()),
tool: "lookup".to_string(),
arguments: serde_json::json!({"query": "active"}),
}
}
fn buffered_event(msg: EventMsg) -> BufferedThreadEvent {
BufferedThreadEvent {
event: Event {
id: "busy-turn".to_string(),
msg,
},
represented_in_resume_snapshot: true,
request_live_for_resumed_connection: true,
}
}
fn buffered_completed_item(turn_id: &str, item: TurnItem) -> BufferedThreadEvent {
BufferedThreadEvent {
event: Event {
id: turn_id.to_string(),
msg: EventMsg::ItemCompleted(ItemCompletedEvent {
thread_id: ThreadId::new(),
turn_id: turn_id.to_string(),
item,
completed_at_ms: 2_000,
}),
},
represented_in_resume_snapshot: false,
request_live_for_resumed_connection: true,
}
}
fn mcp_tool_item(id: &str, status: codex_protocol::items::McpToolCallStatus) -> TurnItem {
TurnItem::McpToolCall(McpToolCallItem {
id: id.to_string(),
server: "private".to_string(),
tool: "lookup".to_string(),
arguments: serde_json::json!({"secret": true}),
connector_id: None,
mcp_app_resource_uri: None,
link_id: None,
app_name: None,
template_id: None,
action_name: None,
plugin_id: None,
status,
result: None,
error: None,
duration: None,
})
}
#[test]
fn busy_snapshot_covers_guardian_and_dynamic_tool_projected_items() {
let guardian_started = guardian_assessment(GuardianAssessmentStatus::InProgress);
let guardian_denied = guardian_assessment(GuardianAssessmentStatus::Denied);
let dynamic_request = dynamic_tool_request();
let mut turn = turn_with_view("busy-turn", TurnItemsView::Full, TurnStatus::InProgress);
turn.items.push(
build_item_from_guardian_event(&guardian_denied, CommandExecutionStatus::Declined)
.expect("guardian command item"),
);
turn.items.push(ThreadItem::DynamicToolCall {
id: dynamic_request.call_id.clone(),
namespace: dynamic_request.namespace.clone(),
tool: dynamic_request.tool.clone(),
arguments: dynamic_request.arguments.clone(),
status: DynamicToolCallStatus::InProgress,
content_items: None,
success: None,
duration_ms: None,
});
let turns = vec![turn];
for msg in [
EventMsg::GuardianAssessment(guardian_started),
EventMsg::GuardianAssessment(guardian_denied),
EventMsg::DynamicToolCallRequest(dynamic_request),
] {
assert!(
event_is_represented(&buffered_event(msg), &turns, None, ResumePayloadMode::Full,),
"the projected item lifecycle must be covered by the busy snapshot"
);
}
}
#[test]
fn represented_guardian_and_dynamic_events_split_companion_and_item_recipients() {
let existing = ConnectionId(1);
let joining = ConnectionId(2);
let coverage = ResumeEventCoverage {
represented_in_resume_snapshot: true,
request_live_for_resumed_connection: true,
};
for msg in [
EventMsg::GuardianAssessment(guardian_assessment(GuardianAssessmentStatus::InProgress)),
EventMsg::DynamicToolCallRequest(dynamic_tool_request()),
] {
let (companion_recipients, item_recipients) =
buffered_event_delivery_recipients(&[existing, joining], Some(joining), &msg, coverage);
assert_eq!(companion_recipients, vec![existing, joining]);
assert_eq!(item_recipients, Some(vec![existing]));
}
let (companion_recipients, item_recipients) = buffered_event_delivery_recipients(
&[existing],
Some(joining),
&EventMsg::DynamicToolCallRequest(dynamic_tool_request()),
ResumeEventCoverage {
represented_in_resume_snapshot: true,
request_live_for_resumed_connection: false,
},
);
assert_eq!(companion_recipients, vec![existing]);
assert_eq!(item_recipients, Some(vec![existing]));
}
#[test]
fn duplicate_summary_and_full_turn_coverage_prefers_the_full_item_view() {
let mut summary_turn = turn_with_view(
"duplicate-turn",
TurnItemsView::Summary,
TurnStatus::InProgress,
);
summary_turn.items.push(
mcp_tool_item(
"mcp-duplicate",
codex_protocol::items::McpToolCallStatus::InProgress,
)
.into(),
);
let mut full_turn =
turn_with_view("duplicate-turn", TurnItemsView::Full, TurnStatus::Completed);
full_turn.items.push(
mcp_tool_item(
"mcp-duplicate",
codex_protocol::items::McpToolCallStatus::Completed,
)
.into(),
);
let page = TurnsPage {
data: vec![full_turn],
next_cursor: None,
backwards_cursor: None,
};
let buffered = buffered_completed_item(
"duplicate-turn",
mcp_tool_item(
"mcp-duplicate",
codex_protocol::items::McpToolCallStatus::Completed,
),
);
assert!(event_is_represented(
&buffered,
&[summary_turn],
Some(&page),
ResumePayloadMode::Full,
));
}
@@ -0,0 +1,487 @@
//! Composes a loaded-thread resume response at the exact history/event cut.
use super::*;
#[allow(clippy::too_many_arguments)]
#[expect(
clippy::await_holding_invalid_type,
reason = "running-thread resume subscription must be serialized against pending unloads"
)]
pub(super) async fn handle_pending_thread_resume_request(
conversation_id: ThreadId,
conversation: &Arc<CodexThread>,
_codex_home: &Path,
thread_manager: &Arc<ThreadManager>,
thread_state_manager: &ThreadStateManager,
thread_state: &Arc<Mutex<ThreadState>>,
thread_watch_manager: &ThreadWatchManager,
thread_list_state_permit: &Arc<Semaphore>,
fallback_model_provider: &str,
outgoing: &Arc<OutgoingMessageSender>,
pending_thread_unloads: &Arc<Mutex<HashSet<ThreadId>>>,
pending: crate::thread_state::PendingThreadResumeRequest,
history_result: Result<crate::thread_state::PreparedThreadResumeHistory, JSONRPCErrorError>,
mut buffered_events: Vec<BufferedThreadEvent>,
mut exec_delta_replay: ResumeExecDeltaReplay,
release_event_cut_tx: oneshot::Sender<()>,
) {
let pre_cut_connection_ids = thread_state_manager
.subscribed_connection_ids(conversation_id)
.await;
// Drain exactly the queue depth observed at the cut. A direct legacy-exec producer may keep
// appending output deltas, so an open-ended try-receive loop could otherwise starve the
// response forever. Later events remain queued for the listener after the cut is released.
let queued_event_count = conversation.pending_event_count();
for _ in 0..queued_event_count {
let event = match conversation.try_next_event() {
Ok(Some(event)) => event,
Ok(None) => break,
Err(err) => {
drop(release_event_cut_tx);
outgoing
.send_error(
pending.request_id.clone(),
internal_error(format!(
"failed to finish resuming thread {conversation_id}: {err}"
)),
)
.await;
dispatch_buffered_thread_events(
buffered_events,
&pre_cut_connection_ids,
None,
conversation_id,
conversation,
thread_manager,
thread_state,
thread_watch_manager,
thread_list_state_permit,
fallback_model_provider,
ResumePayloadMode::Full,
outgoing,
)
.await;
return;
}
};
match route_resume_in_flight_event(
event,
/*has_buffered_prefix*/ !buffered_events.is_empty(),
) {
ResumeInFlightEvent::DispatchImmediately(event) => {
exec_delta_replay.retain(&event);
let raw_events_enabled = track_thread_event(thread_state, &event).await;
dispatch_thread_event(
event,
conversation_id,
conversation,
thread_manager,
thread_state,
thread_watch_manager,
thread_list_state_permit,
fallback_model_provider,
outgoing,
pre_cut_connection_ids.clone(),
/*item_lifecycle_connection_ids*/ None,
raw_events_enabled,
)
.await;
}
ResumeInFlightEvent::Buffer(buffered) => buffered_events.push(buffered),
}
}
let crate::thread_state::PreparedThreadResumeHistory {
stored_thread,
history_items,
reconciliation_outcome,
} = match history_result {
Ok(history) => history,
Err(error) => {
drop(release_event_cut_tx);
outgoing.send_error(pending.request_id, error).await;
dispatch_buffered_thread_events(
buffered_events,
&pre_cut_connection_ids,
None,
conversation_id,
conversation,
thread_manager,
thread_state,
thread_watch_manager,
thread_list_state_permit,
fallback_model_provider,
ResumePayloadMode::Full,
outgoing,
)
.await;
return;
}
};
let pre_cut_pending_requests_survive = project_buffered_request_liveness(&mut buffered_events);
let active_turn = {
let state = thread_state.lock().await;
matches!(
reconciliation_outcome,
ThreadHistoryReconciliationOutcome::Busy
)
.then(|| {
state.projected_active_turn_snapshot(
buffered_events
.iter()
.map(|buffered| (buffered.event.id.as_str(), &buffered.event.msg)),
)
})
.flatten()
};
tracing::debug!(
thread_id = %conversation_id,
request_id = ?pending.request_id,
active_turn_present = active_turn.is_some(),
active_turn_id = ?active_turn.as_ref().map(|turn| turn.id.as_str()),
active_turn_status = ?active_turn.as_ref().map(|turn| &turn.status),
"composing running thread resume response"
);
let has_live_in_progress_turn =
matches!(conversation.agent_status().await, AgentStatus::Running)
|| active_turn
.as_ref()
.is_some_and(|turn| matches!(turn.status, TurnStatus::InProgress));
let request_id = pending.request_id;
let connection_id = request_id.connection_id;
let was_subscribed = pre_cut_connection_ids.contains(&connection_id);
let mut thread = super::thread_processor::thread_from_stored_thread(
stored_thread,
pending.config_snapshot.model_provider_id.as_str(),
pending.config_snapshot.cwd(),
)
.0;
thread.thread_source = pending
.config_snapshot
.thread_source
.clone()
.map(Into::into);
thread.session_id = conversation.session_configured().session_id.to_string();
if pending.include_turns {
populate_thread_turns_from_history(&mut thread, &history_items, active_turn.as_ref());
}
let loaded_thread_status = thread_watch_manager
.loaded_status_for_thread(&thread.id)
.await;
let thread_status = project_thread_status_after_buffered_events(
loaded_thread_status,
has_live_in_progress_turn,
buffered_events.iter().map(|buffered| &buffered.event.msg),
);
set_thread_status_and_interrupt_stale_turns(
&mut thread,
thread_status,
has_live_in_progress_turn,
);
let token_usage_thread = pending.include_turns.then(|| thread.clone());
let mut initial_turns_page = if let Some(params) = pending.initial_turns_page.as_ref() {
match super::thread_processor::build_thread_resume_initial_turns_page(
&history_items,
thread.status.clone(),
has_live_in_progress_turn,
active_turn,
params,
) {
Ok(page) => Some(page),
Err(error) => {
drop(release_event_cut_tx);
outgoing.send_error(request_id, error).await;
dispatch_buffered_thread_events(
buffered_events,
&pre_cut_connection_ids,
None,
conversation_id,
conversation,
thread_manager,
thread_state,
thread_watch_manager,
thread_list_state_permit,
fallback_model_provider,
ResumePayloadMode::Full,
outgoing,
)
.await;
return;
}
}
} else {
None
};
let resume_payload_mode = if pending.redact_resume_payloads {
ResumePayloadMode::Redacted
} else {
ResumePayloadMode::Full
};
let reconciled_token_usage = latest_token_usage_info_from_rollout_items(&history_items);
let reconciled_token_usage_turn_id = token_usage_thread.as_ref().and_then(|thread| {
latest_token_usage_turn_id_from_rollout_items(&history_items, thread.turns.as_slice())
});
let replay_reconciled_token_usage = should_replay_reconciled_token_usage(
&buffered_events,
reconciled_token_usage.as_ref(),
reconciled_token_usage_turn_id.as_deref(),
);
if !buffered_events.is_empty() || !exec_delta_replay.is_empty() {
let mut item_coverage =
ResumePayloadItemCoverage::new(thread.turns.as_slice(), initial_turns_page.as_ref());
// Classify in reverse so a final canonical item claims its durable response occurrence
// before the earlier ItemStarted for the same canonical id asks to reuse that claim.
// Direct-dispatched exec deltas always precede the ordinary buffered prefix, so visit
// that prefix first in reverse order. A later command completion can then suppress
// replayed output already represented by its final snapshot item.
for buffered in buffered_events
.iter_mut()
.rev()
.chain(exec_delta_replay.events_mut().iter_mut().rev())
{
buffered.represented_in_resume_snapshot =
buffered_event_is_represented_in_resume_payload(
buffered,
thread.turns.as_slice(),
initial_turns_page.as_ref(),
&mut item_coverage,
resume_payload_mode,
);
}
}
if resume_payload_mode.is_redacted() {
redact_thread_resume_payloads(&mut thread.turns);
if let Some(initial_turns_page) = initial_turns_page.as_mut() {
redact_thread_resume_payloads(&mut initial_turns_page.data);
}
}
{
let pending_thread_unloads = pending_thread_unloads.lock().await;
if pending_thread_unloads.contains(&conversation_id) {
drop(pending_thread_unloads);
drop(release_event_cut_tx);
outgoing
.send_error(
request_id,
invalid_request(format!(
"thread {conversation_id} is closing; retry thread/resume after the thread is closed"
)),
)
.await;
dispatch_buffered_thread_events(
buffered_events,
&pre_cut_connection_ids,
None,
conversation_id,
conversation,
thread_manager,
thread_state,
thread_watch_manager,
thread_list_state_permit,
fallback_model_provider,
ResumePayloadMode::Full,
outgoing,
)
.await;
return;
}
if !thread_state_manager
.try_add_connection_to_thread(conversation_id, connection_id)
.await
{
tracing::debug!(
thread_id = %conversation_id,
connection_id = ?connection_id,
"skipping running thread resume for closed connection"
);
drop(pending_thread_unloads);
drop(release_event_cut_tx);
dispatch_buffered_thread_events(
buffered_events,
&pre_cut_connection_ids,
None,
conversation_id,
conversation,
thread_manager,
thread_state,
thread_watch_manager,
thread_list_state_permit,
fallback_model_provider,
ResumePayloadMode::Full,
outgoing,
)
.await;
return;
}
// Client compatibility settings are live thread state. Apply them only after every
// resume validation succeeds so a rejected resume cannot affect attached clients.
if let Err(error) =
super::thread_processor::ThreadRequestProcessor::set_app_server_client_info(
conversation.as_ref(),
pending.app_server_client_name,
pending.app_server_client_version,
)
.await
{
if !was_subscribed {
thread_state_manager
.unsubscribe_connection_from_thread(conversation_id, connection_id)
.await;
}
drop(pending_thread_unloads);
drop(release_event_cut_tx);
outgoing.send_error(request_id, error).await;
dispatch_buffered_thread_events(
buffered_events,
&pre_cut_connection_ids,
None,
conversation_id,
conversation,
thread_manager,
thread_state,
thread_watch_manager,
thread_list_state_permit,
fallback_model_provider,
ResumePayloadMode::Full,
outgoing,
)
.await;
return;
}
}
let config_snapshot = pending.config_snapshot;
let cwd = config_snapshot.cwd().clone();
let ThreadConfigSnapshot {
model,
model_provider_id,
service_tier,
approval_policy,
approvals_reviewer,
permission_profile,
active_permission_profile,
workspace_roots,
reasoning_effort,
originator,
..
} = config_snapshot;
let instruction_sources = pending.instruction_sources;
let sandbox = thread_response_sandbox_policy(&permission_profile, cwd.as_path());
let active_permission_profile =
thread_response_active_permission_profile(active_permission_profile);
let session_id = conversation.session_configured().session_id.to_string();
thread.session_id = session_id;
let response = ThreadResumeResponse {
thread,
model,
model_provider: model_provider_id,
service_tier,
cwd,
runtime_workspace_roots: workspace_roots,
instruction_sources,
approval_policy: approval_policy.into(),
approvals_reviewer: approvals_reviewer.into(),
sandbox,
active_permission_profile,
reasoning_effort,
multi_agent_mode: MultiAgentMode::ExplicitRequestOnly,
initial_turns_page,
};
outgoing
.send_response_with_thread_originator(request_id, response, originator)
.await;
// Replay only requests that predate the resume cut. Buffered request-producing events have
// not run their bespoke handlers yet, so their requests will be created exactly once below
// and can retain companion notifications such as item/started for the joining connection.
if pre_cut_pending_requests_survive {
outgoing
.replay_requests_to_connection_for_thread(connection_id, conversation_id)
.await;
}
drop(release_event_cut_tx);
if !was_subscribed {
dispatch_replayed_exec_deltas_to_connection(
exec_delta_replay,
connection_id,
conversation_id,
outgoing,
)
.await;
}
dispatch_buffered_thread_events(
buffered_events,
&pre_cut_connection_ids,
Some(connection_id),
conversation_id,
conversation,
thread_manager,
thread_state,
thread_watch_manager,
thread_list_state_permit,
fallback_model_provider,
resume_payload_mode,
outgoing,
)
.await;
// Match cold resume: metadata-only resume should attach the listener without
// paying the cost of turn reconstruction for historical usage replay.
if let Some(token_usage_thread) = token_usage_thread
&& replay_reconciled_token_usage
&& let Some(reconciled_token_usage) = reconciled_token_usage
{
// Rejoining a loaded thread has the same UI contract as a cold resume, but
// uses the live conversation state instead of reconstructing a new session.
send_thread_token_usage_snapshot_to_connection(
outgoing,
connection_id,
conversation_id,
&token_usage_thread,
reconciled_token_usage,
reconciled_token_usage_turn_id,
)
.await;
}
if pending.emit_thread_goal_update {
if let Some(state_db) = pending.thread_goal_state_db {
send_thread_goal_snapshot_notification(outgoing, conversation_id, &state_db).await;
} else {
tracing::warn!(
thread_id = %conversation_id,
"state db unavailable when reading thread goal for running thread resume"
);
}
}
// App-server owns resume response and snapshot ordering, so wait until every replay completes
// before letting extensions react to the idle thread.
if pending.emit_thread_goal_update {
conversation.emit_thread_idle_lifecycle_if_idle().await;
}
}
pub(super) fn project_thread_status_after_buffered_events<'a>(
loaded_status: ThreadStatus,
has_live_in_progress_turn: bool,
events: impl IntoIterator<Item = &'a EventMsg>,
) -> ThreadStatus {
let latest_turn_transition_is_terminal = events
.into_iter()
.fold(None, |projected, event| match event {
EventMsg::TurnStarted(_) => Some(false),
EventMsg::TurnComplete(_) | EventMsg::TurnAborted(_) => Some(true),
_ => projected,
})
.unwrap_or(false);
let projected_loaded_status = if latest_turn_transition_is_terminal
&& !has_live_in_progress_turn
&& matches!(loaded_status, ThreadStatus::Active { .. })
{
ThreadStatus::Idle
} else {
loaded_status
};
resolve_thread_status(projected_loaded_status, has_live_in_progress_turn)
}
@@ -0,0 +1,186 @@
use super::*;
fn token_usage_info(total_tokens: i64) -> TokenUsageInfo {
TokenUsageInfo {
total_token_usage: TokenUsage {
total_tokens,
..TokenUsage::default()
},
last_token_usage: TokenUsage {
total_tokens,
..TokenUsage::default()
},
model_context_window: Some(100_000),
}
}
#[test]
fn buffered_token_usage_dedupes_only_the_reconciled_final_snapshot() {
let usage_a = token_usage_info(10);
let usage_b = token_usage_info(20);
let mut buffered = vec![BufferedThreadEvent {
event: Event {
id: "turn-a".to_string(),
msg: EventMsg::TokenCount(TokenCountEvent {
info: Some(usage_a.clone()),
rate_limits: Some(RateLimitSnapshot {
limit_id: Some("codex".to_string()),
limit_name: None,
primary: None,
secondary: None,
credits: None,
individual_limit: None,
plan_type: None,
rate_limit_reached_type: None,
}),
}),
},
represented_in_resume_snapshot: true,
request_live_for_resumed_connection: true,
}];
assert!(!should_replay_reconciled_token_usage(
&buffered,
Some(&usage_a),
Some("turn-a"),
));
assert!(
should_replay_reconciled_token_usage(&buffered, Some(&usage_b), Some("turn-b")),
"an externally reconciled newer snapshot must follow an older buffered update"
);
assert!(
should_replay_reconciled_token_usage(&buffered, Some(&usage_a), Some("turn-b")),
"equal usage still needs replay when the persisted owner advanced to a new turn"
);
assert!(
should_replay_reconciled_token_usage(&[], Some(&usage_a), None),
"a captured snapshot with no recoverable owner still uses the sender's fallback"
);
buffered.push(BufferedThreadEvent {
event: Event {
id: "turn-a".to_string(),
msg: EventMsg::TokenCount(TokenCountEvent {
info: None,
rate_limits: None,
}),
},
represented_in_resume_snapshot: true,
request_live_for_resumed_connection: true,
});
assert!(
!should_replay_reconciled_token_usage(&buffered, Some(&usage_a), Some("turn-a")),
"a later rate-limit-only event must not hide the last buffered usage snapshot"
);
assert!(
!event_is_represented(&buffered[0], &[], None, ResumePayloadMode::Full,),
"the buffered event still delivers its rate-limit side effect exactly once"
);
}
#[test]
fn resume_payload_coverage_replays_events_omitted_by_initial_turns_page() {
let buffered_message = BufferedThreadEvent {
event: Event {
id: "latest-turn".to_string(),
msg: EventMsg::AgentMessage(AgentMessageEvent {
message: "buffered".to_string(),
phase: None,
memory_citation: None,
}),
},
represented_in_resume_snapshot: true,
request_live_for_resumed_connection: true,
};
let mut page = TurnsPage {
data: vec![turn_with_view(
"older-turn",
TurnItemsView::Full,
TurnStatus::Completed,
)],
next_cursor: Some("older-page".to_string()),
backwards_cursor: None,
};
assert!(
!event_is_represented(&buffered_message, &[], Some(&page), ResumePayloadMode::Full,),
"a paginated response that omits the event's turn must replay it"
);
page.data = vec![turn_with_view(
"latest-turn",
TurnItemsView::Summary,
TurnStatus::Completed,
)];
assert!(
!event_is_represented(&buffered_message, &[], Some(&page), ResumePayloadMode::Full,),
"a summary page does not prove an arbitrary buffered item is present"
);
page.data[0].items_view = TurnItemsView::Full;
assert!(event_is_represented(
&buffered_message,
&[],
Some(&page),
ResumePayloadMode::Full,
));
let buffered_completion = BufferedThreadEvent {
event: Event {
id: "latest-turn".to_string(),
msg: EventMsg::TurnComplete(TurnCompleteEvent {
turn_id: "latest-turn".to_string(),
last_agent_message: None,
completed_at: Some(2),
duration_ms: Some(1_000),
time_to_first_token_ms: None,
}),
},
represented_in_resume_snapshot: true,
request_live_for_resumed_connection: true,
};
page.data = vec![turn_with_view(
"older-turn",
TurnItemsView::NotLoaded,
TurnStatus::Completed,
)];
assert!(
!event_is_represented(
&buffered_completion,
&[],
Some(&page),
ResumePayloadMode::Full,
),
"turn metadata from an omitted page must still be replayed"
);
page.data = vec![turn_with_view(
"latest-turn",
TurnItemsView::NotLoaded,
TurnStatus::Completed,
)];
assert!(
event_is_represented(
&buffered_completion,
&[],
Some(&page),
ResumePayloadMode::Full,
),
"terminal turn metadata is represented even when items are not loaded"
);
let buffered_usage = BufferedThreadEvent {
event: Event {
id: "latest-turn".to_string(),
msg: EventMsg::TokenCount(TokenCountEvent {
info: None,
rate_limits: None,
}),
},
represented_in_resume_snapshot: true,
request_live_for_resumed_connection: true,
};
assert!(
!event_is_represented(&buffered_usage, &[], Some(&page), ResumePayloadMode::Full,),
"token usage is not represented by a turn page"
);
}
@@ -0,0 +1,416 @@
//! Serializes running-thread resume storage work with listener commands.
use super::*;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum BusyHistoryReadDisposition {
ReturnBusy,
RetryIdle,
Conflict,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum ListenerCommandTransition {
None,
ResumeStarted,
ResumeFinished,
}
pub(super) enum ResumeInFlightEvent {
DispatchImmediately(Event),
Buffer(BufferedThreadEvent),
}
pub(super) const RESUME_EXEC_DELTA_REPLAY_MAX_EVENTS: usize = 10_000;
pub(super) const RESUME_EXEC_DELTA_REPLAY_TRUNCATION_MARKER: &[u8] =
b"\n[output replay truncated while thread resume was in progress]\n";
#[derive(Default)]
pub(super) struct ResumeExecDeltaReplay {
events: Vec<BufferedThreadEvent>,
payload_bytes: usize,
truncated: bool,
}
impl ResumeExecDeltaReplay {
pub(super) fn retain(&mut self, event: &Event) {
if self.truncated {
return;
}
let EventMsg::ExecCommandOutputDelta(delta) = &event.msg else {
debug_assert!(false, "only exec output deltas can enter resume replay");
return;
};
let payload_limit = DEFAULT_OUTPUT_BYTES_CAP
.saturating_sub(RESUME_EXEC_DELTA_REPLAY_TRUNCATION_MARKER.len());
let event_limit = RESUME_EXEC_DELTA_REPLAY_MAX_EVENTS.saturating_sub(1);
if self.events.len() < event_limit
&& self.payload_bytes.saturating_add(delta.chunk.len()) <= payload_limit
{
self.payload_bytes += delta.chunk.len();
self.events
.push(BufferedThreadEvent::from_resume_cut(event.clone()));
return;
}
let mut marker = delta.clone();
marker.chunk = RESUME_EXEC_DELTA_REPLAY_TRUNCATION_MARKER.to_vec();
self.payload_bytes += marker.chunk.len();
self.events
.push(BufferedThreadEvent::from_resume_cut(Event {
id: event.id.clone(),
msg: EventMsg::ExecCommandOutputDelta(marker),
}));
self.truncated = true;
}
pub(super) fn is_empty(&self) -> bool {
self.events.is_empty()
}
pub(super) fn events_mut(&mut self) -> &mut [BufferedThreadEvent] {
self.events.as_mut_slice()
}
pub(super) fn into_events(self) -> Vec<BufferedThreadEvent> {
self.events
}
#[cfg(test)]
pub(super) fn payload_bytes(&self) -> usize {
self.payload_bytes
}
#[cfg(test)]
pub(super) fn is_truncated(&self) -> bool {
self.truncated
}
}
pub(super) fn route_resume_in_flight_event(
event: Event,
has_buffered_prefix: bool,
) -> ResumeInFlightEvent {
if !has_buffered_prefix && matches!(&event.msg, EventMsg::ExecCommandOutputDelta(_)) {
// Legacy exec can enqueue thousands of large output chunks without taking the event cut.
// With no earlier queued event, its notification-only handler can safely stream those
// chunks to existing subscribers while storage IO runs. Once any event is buffered, FIFO
// takes priority so output cannot overtake its TurnStarted or ExecCommandBegin.
ResumeInFlightEvent::DispatchImmediately(event)
} else {
ResumeInFlightEvent::Buffer(BufferedThreadEvent::from_resume_cut(event))
}
}
pub(super) fn apply_listener_command_transition(
resume_in_flight: &mut bool,
transition: ListenerCommandTransition,
) {
match transition {
ListenerCommandTransition::ResumeStarted => *resume_in_flight = true,
ListenerCommandTransition::ResumeFinished => *resume_in_flight = false,
ListenerCommandTransition::None => {}
}
}
pub(super) fn should_defer_listener_command(
resume_in_flight: bool,
listener_command: &ThreadListenerCommand,
) -> bool {
resume_in_flight
&& !matches!(
listener_command,
ThreadListenerCommand::FinishThreadResumeResponse { .. }
)
}
pub(super) async fn run_cancelable_resume_worker(
cancellation_token: CancellationToken,
resume: impl Future<Output = ()>,
) {
tokio::select! {
_ = cancellation_token.cancelled() => {}
_ = resume => {}
}
}
pub(super) fn classify_busy_history_read(
attempt: usize,
thread_became_idle: bool,
) -> BusyHistoryReadDisposition {
if !thread_became_idle {
BusyHistoryReadDisposition::ReturnBusy
} else if attempt == 0 {
BusyHistoryReadDisposition::RetryIdle
} else {
BusyHistoryReadDisposition::Conflict
}
}
#[allow(clippy::too_many_arguments)]
pub(super) async fn handle_thread_listener_command(
conversation_id: ThreadId,
conversation: &Arc<CodexThread>,
codex_home: &Path,
thread_manager: &Arc<ThreadManager>,
thread_state_manager: &ThreadStateManager,
thread_state: &Arc<Mutex<ThreadState>>,
thread_watch_manager: &ThreadWatchManager,
thread_list_state_permit: &Arc<Semaphore>,
fallback_model_provider: &str,
outgoing: &Arc<OutgoingMessageSender>,
pending_thread_unloads: &Arc<Mutex<HashSet<ThreadId>>>,
listener_command_tx: &mpsc::UnboundedSender<ThreadListenerCommand>,
resume_worker_cancel: &CancellationToken,
buffered_resume_events: &mut Vec<BufferedThreadEvent>,
resume_exec_delta_replay: &mut ResumeExecDeltaReplay,
listener_command: ThreadListenerCommand,
) -> ListenerCommandTransition {
match listener_command {
ThreadListenerCommand::SendThreadResumeResponse {
request: resume_request,
completion_tx,
} => {
debug_assert!(buffered_resume_events.is_empty());
debug_assert!(resume_exec_delta_replay.is_empty());
if begin_pending_thread_resume_request(
conversation_id,
conversation,
thread_state,
outgoing,
listener_command_tx,
resume_worker_cancel,
resume_request,
completion_tx,
)
.await
{
ListenerCommandTransition::ResumeStarted
} else {
ListenerCommandTransition::None
}
}
ThreadListenerCommand::FinishThreadResumeResponse {
request: resume_request,
completion_tx,
history_result,
release_event_cut_tx,
} => {
handle_pending_thread_resume_request(
conversation_id,
conversation,
codex_home,
thread_manager,
thread_state_manager,
thread_state,
thread_watch_manager,
thread_list_state_permit,
fallback_model_provider,
outgoing,
pending_thread_unloads,
*resume_request,
*history_result,
std::mem::take(buffered_resume_events),
std::mem::take(resume_exec_delta_replay),
release_event_cut_tx,
)
.await;
let _ = completion_tx.send(());
ListenerCommandTransition::ResumeFinished
}
ThreadListenerCommand::EmitThreadGoalUpdated { turn_id, goal } => {
outgoing
.send_server_notification(ServerNotification::ThreadGoalUpdated(
ThreadGoalUpdatedNotification {
thread_id: conversation_id.to_string(),
turn_id,
goal,
},
))
.await;
ListenerCommandTransition::None
}
ThreadListenerCommand::EmitThreadGoalCleared => {
outgoing
.send_server_notification(ServerNotification::ThreadGoalCleared(
ThreadGoalClearedNotification {
thread_id: conversation_id.to_string(),
},
))
.await;
ListenerCommandTransition::None
}
ThreadListenerCommand::EmitThreadGoalSnapshot { state_db } => {
send_thread_goal_snapshot_notification(outgoing, conversation_id, &state_db).await;
ListenerCommandTransition::None
}
ThreadListenerCommand::ResolveServerRequest {
request_id,
completion_tx,
} => {
resolve_pending_server_request(
conversation_id,
thread_state_manager,
outgoing,
request_id,
)
.await;
let _ = completion_tx.send(());
ListenerCommandTransition::None
}
}
}
#[allow(clippy::too_many_arguments)]
async fn begin_pending_thread_resume_request(
conversation_id: ThreadId,
conversation: &Arc<CodexThread>,
thread_state: &Arc<Mutex<ThreadState>>,
outgoing: &Arc<OutgoingMessageSender>,
listener_command_tx: &mpsc::UnboundedSender<ThreadListenerCommand>,
resume_worker_cancel: &CancellationToken,
request: Box<crate::thread_state::PendingThreadResumeRequest>,
completion_tx: oneshot::Sender<()>,
) -> bool {
if thread_state.lock().await.pending_rollbacks.is_some() {
outgoing
.send_error(
request.request_id.clone(),
invalid_request(format!(
"thread {conversation_id} has a rollback in progress; retry thread/resume after it finishes"
)),
)
.await;
let _ = completion_tx.send(());
return false;
}
let conversation = Arc::clone(conversation);
let listener_command_tx = listener_command_tx.clone();
let resume_worker_cancel = resume_worker_cancel.child_token();
tokio::spawn(async move {
let resume = async move {
// This worker owns all storage IO. Holding the event-delivery cut makes the loaded
// history and queued-event boundary exact while the listener remains responsive to
// cancellation and unload signals; the event queue is drained by Finish.
let event_cut_guards = conversation
.acquire_history_reconciliation_event_cut()
.await;
let history_result =
read_pending_thread_resume_history(conversation_id, &conversation).await;
let (release_event_cut_tx, release_event_cut_rx) = oneshot::channel();
let command = ThreadListenerCommand::FinishThreadResumeResponse {
request,
completion_tx,
history_result: Box::new(history_result),
release_event_cut_tx,
};
if listener_command_tx.send(command).is_ok() {
let _ = release_event_cut_rx.await;
}
drop(event_cut_guards);
};
run_cancelable_resume_worker(resume_worker_cancel, resume).await;
});
true
}
pub(super) async fn read_pending_thread_resume_history(
conversation_id: ThreadId,
conversation: &Arc<CodexThread>,
) -> Result<crate::thread_state::PreparedThreadResumeHistory, JSONRPCErrorError> {
let mut attempt = 0;
let (history_items, reconciliation_outcome) = loop {
let Some(snapshot) = conversation.history_reconciliation_snapshot().await else {
// The event cut blocks new persisted event delivery, and the rollout guard blocks
// every other append. Flush even while active so any queued event classified as
// snapshot-represented is guaranteed to be present in this read.
conversation.flush_rollout().await.map_err(|err| {
internal_error(format!(
"failed to flush thread {conversation_id} before resuming: {err}"
))
})?;
let history_items = conversation
.load_history(/*include_archived*/ true)
.await
.map_err(super::thread_processor::thread_store_resume_read_error)?
.items;
let thread_became_idle = conversation
.history_reconciliation_snapshot()
.await
.is_some();
match classify_busy_history_read(attempt, thread_became_idle) {
BusyHistoryReadDisposition::RetryIdle => {
// The loaded history may predate the terminal event. Retry through the idle
// flush/read path so the response includes the completed turn.
attempt += 1;
continue;
}
BusyHistoryReadDisposition::Conflict => {
break (history_items, ThreadHistoryReconciliationOutcome::Conflict);
}
BusyHistoryReadDisposition::ReturnBusy => {}
}
break (history_items, ThreadHistoryReconciliationOutcome::Busy);
};
conversation.flush_rollout().await.map_err(|err| {
internal_error(format!(
"failed to flush thread {conversation_id} before resuming: {err}"
))
})?;
let history_items = conversation
.load_history(/*include_archived*/ true)
.await
.map_err(super::thread_processor::thread_store_resume_read_error)?
.items;
let outcome = conversation
.reconcile_persisted_history(snapshot, &history_items)
.await;
if attempt == 0
&& matches!(
outcome,
ThreadHistoryReconciliationOutcome::Conflict
| ThreadHistoryReconciliationOutcome::Incomplete
)
{
attempt += 1;
continue;
}
break (history_items, outcome);
};
match reconciliation_outcome {
ThreadHistoryReconciliationOutcome::Incomplete => {
return Err(invalid_request(format!(
"thread {conversation_id} has an incomplete persisted turn; retry thread/resume after it finishes"
)));
}
ThreadHistoryReconciliationOutcome::Conflict => {
return Err(invalid_request(format!(
"thread {conversation_id} changed while resuming; retry thread/resume"
)));
}
ThreadHistoryReconciliationOutcome::Unchanged
| ThreadHistoryReconciliationOutcome::Refreshed
| ThreadHistoryReconciliationOutcome::Busy => {}
}
// Refresh metadata after the authoritative history/reconciliation read while the worker still
// owns the history/event/rollout cut. Paginated-history threads cannot use read_thread with
// history attached, so keep the canonical history load above and pair it with this fresh
// metadata-only read in the same worker phase.
let stored_thread = conversation
.read_thread(
/*include_archived*/ true, /*include_history*/ false,
)
.await
.map_err(super::thread_processor::thread_store_resume_read_error)?;
if stored_thread.archived_at.is_some() {
return Err(invalid_request(format!(
"session {conversation_id} is archived. Run `codex unarchive {conversation_id}` to unarchive it first."
)));
}
Ok(crate::thread_state::PreparedThreadResumeHistory {
stored_thread,
history_items,
reconciliation_outcome,
})
}
@@ -0,0 +1,430 @@
use super::*;
#[test]
fn busy_history_read_retries_once_then_fails_closed_after_idle_transition() {
assert_eq!(
classify_busy_history_read(/*attempt*/ 0, /*thread_became_idle*/ false),
BusyHistoryReadDisposition::ReturnBusy
);
assert_eq!(
classify_busy_history_read(/*attempt*/ 0, /*thread_became_idle*/ true),
BusyHistoryReadDisposition::RetryIdle
);
assert_eq!(
classify_busy_history_read(/*attempt*/ 1, /*thread_became_idle*/ true),
BusyHistoryReadDisposition::Conflict
);
}
#[test]
fn resume_status_projects_buffered_terminal_turn_before_listener_tracking() {
let complete = EventMsg::TurnComplete(TurnCompleteEvent {
turn_id: "completed-turn".to_string(),
last_agent_message: None,
completed_at: Some(2),
duration_ms: Some(1_000),
time_to_first_token_ms: None,
});
let aborted = EventMsg::TurnAborted(TurnAbortedEvent {
turn_id: Some("aborted-turn".to_string()),
reason: TurnAbortReason::Interrupted,
completed_at: Some(2),
duration_ms: Some(1_000),
});
for terminal_event in [&complete, &aborted] {
assert_eq!(
project_thread_status_after_buffered_events(
ThreadStatus::Active {
active_flags: vec![ThreadActiveFlag::WaitingOnUserInput],
},
/*has_live_in_progress_turn*/ false,
[terminal_event],
),
ThreadStatus::Idle
);
}
}
#[test]
fn resume_status_keeps_active_when_a_later_turn_started_or_is_live() {
let complete = EventMsg::TurnComplete(TurnCompleteEvent {
turn_id: "completed-turn".to_string(),
last_agent_message: None,
completed_at: Some(2),
duration_ms: Some(1_000),
time_to_first_token_ms: None,
});
let started = EventMsg::TurnStarted(TurnStartedEvent {
turn_id: "next-turn".to_string(),
trace_id: None,
started_at: Some(3),
model_context_window: None,
collaboration_mode_kind: Default::default(),
});
let active_status = ThreadStatus::Active {
active_flags: vec![ThreadActiveFlag::WaitingOnApproval],
};
assert_eq!(
project_thread_status_after_buffered_events(
active_status.clone(),
/*has_live_in_progress_turn*/ false,
[&complete, &started],
),
active_status
);
assert_eq!(
project_thread_status_after_buffered_events(
ThreadStatus::Idle,
/*has_live_in_progress_turn*/ true,
[&complete],
),
ThreadStatus::Active {
active_flags: Vec::new(),
}
);
}
#[test]
fn rejected_resume_begin_does_not_defer_following_listener_command() {
let mut resume_in_flight = false;
// A Begin that rejects before spawning its worker returns `None`; no Finish command is
// guaranteed in that case, so the listener must remain available for ordinary commands.
apply_listener_command_transition(&mut resume_in_flight, ListenerCommandTransition::None);
assert!(!resume_in_flight);
assert!(!should_defer_listener_command(
resume_in_flight,
&ThreadListenerCommand::EmitThreadGoalCleared,
));
}
#[tokio::test]
async fn blocked_resume_worker_drains_high_volume_exec_deltas_to_existing_subscriber() {
let cancellation_token = CancellationToken::new();
let (worker_started_tx, worker_started_rx) = oneshot::channel();
let blocked_worker = tokio::spawn(run_cancelable_resume_worker(
cancellation_token.child_token(),
async move {
let _ = worker_started_tx.send(());
futures::future::pending::<()>().await;
},
));
worker_started_rx
.await
.expect("resume worker should reach blocked storage phase");
let (event_tx, mut event_rx) = tokio::sync::mpsc::unbounded_channel::<Event>();
let queued_depth = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let consumer_queued_depth = std::sync::Arc::clone(&queued_depth);
let (subscriber_tx, mut subscriber_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
let drain = tokio::spawn(async move {
let mut buffered = Vec::new();
let mut exec_delta_replay = ResumeExecDeltaReplay::default();
while let Some(event) = event_rx.recv().await {
consumer_queued_depth.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
match route_resume_in_flight_event(
event,
/*has_buffered_prefix*/ !buffered.is_empty(),
) {
ResumeInFlightEvent::DispatchImmediately(event) => {
exec_delta_replay.retain(&event);
subscriber_tx
.send(event.id)
.expect("existing subscriber should remain attached");
}
ResumeInFlightEvent::Buffer(event) => buffered.push(event),
}
}
(buffered, exec_delta_replay)
});
let delta = Event {
id: "large-output-turn".to_string(),
msg: EventMsg::ExecCommandOutputDelta(ExecCommandOutputDeltaEvent {
call_id: "large-output-command".to_string(),
stream: ExecOutputStream::Stdout,
chunk: vec![b'x'; 8 * 1024],
}),
};
let mut max_queue_depth = 0;
for _ in 0..100 {
for _ in 0..100 {
let queue_depth = queued_depth.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
event_tx
.send(delta.clone())
.expect("listener channel should stay open");
max_queue_depth = max_queue_depth.max(queue_depth);
}
timeout(Duration::from_secs(1), async {
while queued_depth.load(std::sync::atomic::Ordering::SeqCst) != 0 {
tokio::task::yield_now().await;
}
})
.await
.expect("listener should drain each output batch while storage remains blocked");
assert!(!blocked_worker.is_finished());
}
queued_depth.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
event_tx
.send(Event {
id: "ordinary-event".to_string(),
msg: EventMsg::TurnStarted(TurnStartedEvent {
turn_id: "ordinary-event".to_string(),
trace_id: None,
started_at: None,
model_context_window: None,
collaboration_mode_kind: Default::default(),
}),
})
.expect("listener channel should stay open");
drop(event_tx);
let (buffered, exec_delta_replay) = drain.await.expect("resume event drain should not panic");
assert!(
max_queue_depth <= 100,
"queue depth should stay bounded by one producer batch, got {max_queue_depth}"
);
let mut subscriber_event_count = 0;
while subscriber_rx.try_recv().is_ok() {
subscriber_event_count += 1;
}
assert_eq!(subscriber_event_count, 10_000);
assert_eq!(buffered.len(), 1);
assert!(matches!(&buffered[0].event.msg, EventMsg::TurnStarted(_)));
assert!(exec_delta_replay.is_truncated());
assert!(exec_delta_replay.payload_bytes() <= DEFAULT_OUTPUT_BYTES_CAP);
let replayed_events = exec_delta_replay.into_events();
assert!(replayed_events.len() <= RESUME_EXEC_DELTA_REPLAY_MAX_EVENTS);
let EventMsg::ExecCommandOutputDelta(last_replayed_delta) = &replayed_events
.last()
.expect("replay should retain output")
.event
.msg
else {
panic!("exec replay must contain only output deltas");
};
assert_eq!(
last_replayed_delta.chunk,
RESUME_EXEC_DELTA_REPLAY_TRUNCATION_MARKER
);
cancellation_token.cancel();
blocked_worker
.await
.expect("cancelled resume worker should not panic");
}
#[tokio::test]
async fn resume_exec_delta_replay_targets_only_the_joiner_and_skips_covered_output() {
let conversation_id = ThreadId::new();
let connection_id = ConnectionId(17);
let (tx, mut rx) = tokio::sync::mpsc::channel(4);
let outgoing = Arc::new(OutgoingMessageSender::new(
tx,
codex_analytics::AnalyticsEventsClient::disabled(),
));
let mut replay = ResumeExecDeltaReplay::default();
for chunk in [b"missing".to_vec(), b"covered".to_vec()] {
replay.retain(&Event {
id: "active-turn".to_string(),
msg: EventMsg::ExecCommandOutputDelta(ExecCommandOutputDeltaEvent {
call_id: "active-command".to_string(),
stream: ExecOutputStream::Stdout,
chunk,
}),
});
}
replay.events_mut()[1].represented_in_resume_snapshot = true;
dispatch_replayed_exec_deltas_to_connection(replay, connection_id, conversation_id, &outgoing)
.await;
let envelope = rx
.recv()
.await
.expect("joiner should receive retained output");
let OutgoingEnvelope::ToConnection {
connection_id: actual_connection_id,
message:
OutgoingMessage::AppServerNotification(ServerNotification::CommandExecutionOutputDelta(
notification,
)),
..
} = envelope
else {
panic!("expected one connection-scoped exec output notification");
};
assert_eq!(actual_connection_id, connection_id);
assert_eq!(notification.thread_id, conversation_id.to_string());
assert_eq!(notification.turn_id, "active-turn");
assert_eq!(notification.item_id, "active-command");
assert_eq!(notification.delta, "missing");
assert!(
rx.try_recv().is_err(),
"covered output must not be replayed"
);
}
#[test]
fn resume_event_routing_preserves_exec_begin_before_output_delta() {
let begin = Event {
id: "turn-with-command".to_string(),
msg: EventMsg::ExecCommandBegin(ExecCommandBeginEvent {
call_id: "ordered-command".to_string(),
process_id: None,
turn_id: "turn-with-command".to_string(),
started_at_ms: 1,
command: vec!["printf".to_string(), "output".to_string()],
cwd: "file:///tmp".parse().expect("path uri"),
parsed_cmd: Vec::new(),
source: ExecCommandSource::Agent,
interaction_input: None,
}),
};
let delta = Event {
id: "turn-with-command".to_string(),
msg: EventMsg::ExecCommandOutputDelta(ExecCommandOutputDeltaEvent {
call_id: "ordered-command".to_string(),
stream: ExecOutputStream::Stdout,
chunk: b"output".to_vec(),
}),
};
let mut buffered = Vec::new();
match route_resume_in_flight_event(begin, /*has_buffered_prefix*/ false) {
ResumeInFlightEvent::Buffer(event) => buffered.push(event),
ResumeInFlightEvent::DispatchImmediately(_) => panic!("exec begin must be buffered"),
}
match route_resume_in_flight_event(delta, /*has_buffered_prefix*/ true) {
ResumeInFlightEvent::Buffer(event) => buffered.push(event),
ResumeInFlightEvent::DispatchImmediately(_) => {
panic!("output must not overtake a buffered exec begin")
}
}
assert!(matches!(
&buffered[0].event.msg,
EventMsg::ExecCommandBegin(_)
));
assert!(matches!(
&buffered[1].event.msg,
EventMsg::ExecCommandOutputDelta(_)
));
}
#[tokio::test]
async fn resume_worker_reads_metadata_after_acquiring_history_event_cut() {
let harness = TestCodexHarness::new()
.await
.expect("test Codex thread should start");
let conversation = Arc::clone(&harness.test().codex);
let conversation_id = harness.test().session_configured.thread_id;
conversation
.update_thread_metadata(
ThreadMetadataPatch {
name: Some(Some("captured before cut".to_string())),
..Default::default()
},
/*include_archived*/ true,
)
.await
.expect("initial metadata should update");
let captured_source_thread = conversation
.read_thread(
/*include_archived*/ true, /*include_history*/ false,
)
.await
.expect("request should capture pre-cut metadata");
assert_eq!(
captured_source_thread.name.as_deref(),
Some("captured before cut")
);
let held_cut = conversation
.acquire_history_reconciliation_event_cut()
.await;
let (cut_attempt_tx, cut_attempt_rx) = oneshot::channel();
let (cut_acquired_tx, mut cut_acquired_rx) = oneshot::channel();
let worker_conversation = Arc::clone(&conversation);
let worker = tokio::spawn(async move {
let _ = cut_attempt_tx.send(());
let worker_cut = worker_conversation
.acquire_history_reconciliation_event_cut()
.await;
let _ = cut_acquired_tx.send(());
let result =
read_pending_thread_resume_history(conversation_id, &worker_conversation).await;
drop(worker_cut);
result
});
cut_attempt_rx
.await
.expect("resume worker should attempt to acquire the cut");
assert!(
timeout(Duration::from_millis(25), &mut cut_acquired_rx)
.await
.is_err(),
"held cut must block the resume worker after pre-cut metadata capture"
);
conversation
.update_thread_metadata(
ThreadMetadataPatch {
name: Some(Some("updated while worker blocked".to_string())),
..Default::default()
},
/*include_archived*/ true,
)
.await
.expect("external metadata update should not require the history/event cut");
drop(held_cut);
cut_acquired_rx
.await
.expect("resume worker should acquire the released cut");
let prepared = worker
.await
.expect("resume worker should not panic")
.expect("resume worker should prepare history and metadata");
let response_thread = crate::request_processors::thread_processor::thread_from_stored_thread(
prepared.stored_thread,
harness.test().config.model_provider_id.as_str(),
&harness.test().config.cwd,
)
.0;
assert_eq!(
response_thread.name.as_deref(),
Some("updated while worker blocked")
);
assert_ne!(response_thread.name, captured_source_thread.name);
}
#[tokio::test]
async fn listener_cancellation_drops_blocked_resume_worker_and_completion_state() {
let cancellation_token = CancellationToken::new();
let (started_tx, started_rx) = oneshot::channel();
let (completion_tx, completion_rx) = oneshot::channel::<()>();
let worker_cancel = cancellation_token.child_token();
let worker = tokio::spawn(async move {
run_cancelable_resume_worker(worker_cancel, async move {
// Mirrors the real worker's cut guards, resume lease, and completion sender: all
// are owned by this future and must drop if the listener is cancelled mid-read.
let _completion_tx = completion_tx;
let _ = started_tx.send(());
futures::future::pending::<()>().await;
})
.await;
});
started_rx.await.expect("worker should enter blocked read");
cancellation_token.cancel();
timeout(Duration::from_secs(1), worker)
.await
.expect("cancelled worker should exit promptly")
.expect("cancelled worker should not panic");
assert!(
completion_rx.await.is_err(),
"listener cancellation must drop the pending request completion sender"
);
}
@@ -0,0 +1,35 @@
use super::*;
#[test]
fn app_history_requires_event_only_rollback_marker_to_remove_turn() {
let mut rollout = vec![RolloutItem::EventMsg(EventMsg::TurnStarted(
TurnStartedEvent {
turn_id: "event-only-turn".to_string(),
trace_id: None,
started_at: Some(1),
model_context_window: None,
collaboration_mode_kind: Default::default(),
},
))];
rollout.push(RolloutItem::EventMsg(EventMsg::TurnComplete(
TurnCompleteEvent {
turn_id: "event-only-turn".to_string(),
last_agent_message: None,
completed_at: Some(2),
duration_ms: Some(1_000),
time_to_first_token_ms: None,
},
)));
let stale_turns = build_api_turns_from_rollout_items(&rollout);
assert_eq!(stale_turns.len(), 1);
assert_eq!(stale_turns[0].id, "event-only-turn");
rollout.push(RolloutItem::EventMsg(EventMsg::ThreadRolledBack(
ThreadRolledBackEvent { num_turns: 1 },
)));
assert!(
build_api_turns_from_rollout_items(&rollout).is_empty(),
"a resume may expose this history only after the proven rollback marker removes the event-only turn"
);
}
@@ -0,0 +1,121 @@
use super::BufferedRawResponseRouting;
use super::BufferedThreadEvent;
use super::BusyHistoryReadDisposition;
use super::ListenerCommandTransition;
use super::RESUME_EXEC_DELTA_REPLAY_MAX_EVENTS;
use super::RESUME_EXEC_DELTA_REPLAY_TRUNCATION_MARKER;
use super::ResumeEventCoverage;
use super::ResumeExecDeltaReplay;
use super::ResumeInFlightEvent;
use super::ResumePayloadItemCoverage;
use super::ResumePayloadMode;
use super::apply_listener_command_transition;
use super::buffered_event_delivery_recipients;
use super::buffered_event_is_represented_in_resume_payload;
use super::buffered_event_recipients;
use super::buffered_raw_response_recipients;
use super::classify_busy_history_read;
use super::dispatch_replayed_exec_deltas_to_connection;
use super::project_buffered_request_liveness;
use super::project_thread_status_after_buffered_events;
use super::read_pending_thread_resume_history;
use super::route_resume_in_flight_event;
use super::run_cancelable_resume_worker;
use super::should_defer_listener_command;
use super::should_replay_reconciled_token_usage;
use crate::outgoing_message::ConnectionId;
use crate::outgoing_message::OutgoingEnvelope;
use crate::outgoing_message::OutgoingMessage;
use crate::outgoing_message::OutgoingMessageSender;
use crate::request_processors::build_api_turns_from_rollout_items;
use crate::thread_state::ThreadListenerCommand;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::ThreadActiveFlag;
use codex_app_server_protocol::ThreadItem;
use codex_app_server_protocol::ThreadStatus;
use codex_app_server_protocol::Turn;
use codex_app_server_protocol::TurnItemsView;
use codex_app_server_protocol::TurnStatus;
use codex_app_server_protocol::TurnsPage;
use codex_app_server_protocol::build_command_execution_end_item;
use codex_protocol::ThreadId;
use codex_protocol::items::AgentMessageContent;
use codex_protocol::items::AgentMessageItem;
use codex_protocol::items::HookPromptFragment;
use codex_protocol::items::ImageGenerationItem;
use codex_protocol::items::McpToolCallItem;
use codex_protocol::items::TurnItem;
use codex_protocol::items::build_hook_prompt_message;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::AgentMessageContentDeltaEvent;
use codex_protocol::protocol::AgentMessageEvent;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ExecCommandBeginEvent;
use codex_protocol::protocol::ExecCommandEndEvent;
use codex_protocol::protocol::ExecCommandOutputDeltaEvent;
use codex_protocol::protocol::ExecCommandSource;
use codex_protocol::protocol::ExecCommandStatus;
use codex_protocol::protocol::ExecOutputStream;
use codex_protocol::protocol::ItemCompletedEvent;
use codex_protocol::protocol::ItemStartedEvent;
use codex_protocol::protocol::RateLimitSnapshot;
use codex_protocol::protocol::RawResponseItemEvent;
use codex_protocol::protocol::RequestUserInputEvent;
use codex_protocol::protocol::RolloutItem;
use codex_protocol::protocol::ThreadRolledBackEvent;
use codex_protocol::protocol::TokenCountEvent;
use codex_protocol::protocol::TokenUsage;
use codex_protocol::protocol::TokenUsageInfo;
use codex_protocol::protocol::TurnAbortReason;
use codex_protocol::protocol::TurnAbortedEvent;
use codex_protocol::protocol::TurnCompleteEvent;
use codex_protocol::protocol::TurnStartedEvent;
use codex_thread_store::ThreadMetadataPatch;
use codex_utils_pty::DEFAULT_OUTPUT_BYTES_CAP;
use core_test_support::test_codex::TestCodexHarness;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::oneshot;
use tokio::time::timeout;
use tokio_util::sync::CancellationToken;
fn event_is_represented(
buffered: &BufferedThreadEvent,
thread_turns: &[Turn],
initial_turns_page: Option<&TurnsPage>,
resume_payload_mode: ResumePayloadMode,
) -> bool {
let mut item_coverage = ResumePayloadItemCoverage::new(thread_turns, initial_turns_page);
buffered_event_is_represented_in_resume_payload(
buffered,
thread_turns,
initial_turns_page,
&mut item_coverage,
resume_payload_mode,
)
}
fn turn_with_view(id: &str, items_view: TurnItemsView, status: TurnStatus) -> Turn {
Turn {
id: id.to_string(),
items: Vec::new(),
items_view,
status,
error: None,
started_at: Some(1),
completed_at: None,
duration_ms: None,
}
}
#[path = "thread_lifecycle/resume_event_coverage_tests.rs"]
mod resume_event_coverage_tests;
#[path = "thread_lifecycle/resume_projected_item_tests.rs"]
mod resume_projected_item_tests;
#[path = "thread_lifecycle/resume_token_replay_tests.rs"]
mod resume_token_replay_tests;
#[path = "thread_lifecycle/resume_worker_tests.rs"]
mod resume_worker_tests;
#[path = "thread_lifecycle/thread_history_tests.rs"]
mod thread_history_tests;
@@ -369,7 +369,10 @@ pub(crate) struct ThreadRequestProcessor {
/// Outcome of trying to satisfy a resume request from an already loaded thread.
enum RunningThreadResumeResult {
/// The request was delegated to the loaded thread.
Handled,
Pending {
completion_rx: oneshot::Receiver<()>,
thread_id: ThreadId,
},
/// No loaded thread handled the request.
///
/// The optional stored thread contains the history-bearing probe that cold
@@ -769,7 +772,7 @@ impl ThreadRequestProcessor {
})
}
async fn set_app_server_client_info(
pub(super) async fn set_app_server_client_info(
thread: &CodexThread,
app_server_client_name: Option<String>,
app_server_client_version: Option<String>,
@@ -1731,16 +1734,46 @@ impl ThreadRequestProcessor {
}
let (thread_id, thread) = self.load_thread(&thread_id).await?;
let (thread_state, _listener_lease) = match self
.thread_state_manager
.acquire_point_operation_lease(
&self.pending_thread_unloads,
thread_id,
request_id.connection_id,
)
.await
{
ThreadPointOperationLeaseAcquireResult::Acquired {
thread_state,
lease,
} => (thread_state, lease),
ThreadPointOperationLeaseAcquireResult::ConnectionClosed => {
return Err(invalid_request(
"cannot roll back a thread for a closed connection",
));
}
ThreadPointOperationLeaseAcquireResult::ThreadClosing => {
return Err(invalid_request(format!(
"thread {thread_id} is closing; retry after the thread is closed"
)));
}
};
// Rollback is a point request, not a subscription API. It still needs the listener to
// serialize and complete the response, but must preserve an explicit unsubscribe.
self.ensure_listener_task_running(thread_id, thread.clone(), thread_state.clone())
.await?;
let request = request_id.clone();
let (completion_tx, completion_rx) = oneshot::channel();
let rollback_already_in_progress = {
let thread_state = self.thread_state_manager.thread_state(thread_id).await;
let mut thread_state = thread_state.lock().await;
if thread_state.pending_rollbacks.is_some() {
true
} else {
thread_state.pending_rollbacks = Some(request.clone());
thread_state.pending_rollbacks = Some(
crate::thread_state::PendingThreadRollback::new(request.clone(), completion_tx),
);
false
}
};
@@ -1760,11 +1793,15 @@ impl ThreadRequestProcessor {
{
// No ThreadRollback event will arrive if an error occurs.
// Clean up and reply immediately.
let thread_state = self.thread_state_manager.thread_state(thread_id).await;
thread_state.lock().await.pending_rollbacks = None;
return Err(internal_error(format!("failed to start rollback: {err}")));
}
if completion_rx.await.is_err() {
return Err(internal_error(format!(
"failed to complete rollback for thread {thread_id}: thread listener stopped"
)));
}
Ok(())
}
@@ -2650,7 +2687,7 @@ impl ThreadRequestProcessor {
let redact_resume_payloads =
should_redact_thread_resume_payloads(app_server_client_name.as_deref());
let _thread_list_state_permit = match self.acquire_thread_list_state_permit().await {
let thread_list_state_permit = match self.acquire_thread_list_state_permit().await {
Ok(permit) => permit,
Err(error) => {
self.outgoing.send_error(request_id, error).await;
@@ -2666,7 +2703,23 @@ impl ThreadRequestProcessor {
)
.await
{
Ok(RunningThreadResumeResult::Handled) => return Ok(()),
Ok(RunningThreadResumeResult::Pending {
completion_rx,
thread_id,
}) => {
drop(thread_list_state_permit);
if completion_rx.await.is_err() {
self.outgoing
.send_error(
request_id,
internal_error(format!(
"failed to complete running thread resume for thread {thread_id}: thread listener stopped"
)),
)
.await;
}
return Ok(());
}
Ok(RunningThreadResumeResult::NotRunning(stored_thread)) => stored_thread,
Err(error) => {
self.outgoing.send_error(request_id, error).await;
@@ -2977,7 +3030,7 @@ impl ThreadRequestProcessor {
.read_stored_thread_for_resume(
&params.thread_id,
/*path*/ None,
/*include_history*/ true,
/*include_history*/ false,
)
.await?;
Some((existing_thread_id, existing_thread, source_thread))
@@ -3000,7 +3053,7 @@ impl ThreadRequestProcessor {
}
};
if let Some((existing_thread_id, existing_thread, mut source_thread)) = running_thread {
if let Some((existing_thread_id, existing_thread, source_thread)) = running_thread {
let existing_thread_rollout_path = existing_thread.rollout_path();
let active_path = existing_thread_rollout_path
.as_ref()
@@ -3014,6 +3067,41 @@ impl ThreadRequestProcessor {
active_path.display()
)));
}
let (thread_state, resume_lease) = match self
.thread_state_manager
.acquire_point_operation_lease(
&self.pending_thread_unloads,
existing_thread_id,
request_id.connection_id,
)
.await
{
ThreadPointOperationLeaseAcquireResult::Acquired {
thread_state,
lease,
} => (thread_state, lease),
ThreadPointOperationLeaseAcquireResult::ConnectionClosed => {
return Err(invalid_request(
"cannot resume a thread for a closed connection",
));
}
ThreadPointOperationLeaseAcquireResult::ThreadClosing => {
return Err(invalid_request(format!(
"thread {existing_thread_id} is closing; retry after the thread is closed"
)));
}
};
// The initial running-thread probe precedes lease acquisition. If an unload completed
// during that store read, do not resurrect the stale Arc after its closing marker was
// removed; fall back to a fresh stored-thread read instead.
if !self
.thread_manager
.get_thread(existing_thread_id)
.await
.is_ok_and(|current| Arc::ptr_eq(&current, &existing_thread))
{
return Ok(RunningThreadResumeResult::NotRunning(None));
}
let config_snapshot = existing_thread.config_snapshot().await;
let mismatch_details = collect_resume_override_mismatches(params, &config_snapshot);
if !mismatch_details.is_empty() {
@@ -3060,39 +3148,12 @@ impl ThreadRequestProcessor {
}
let redact_resume_payloads =
should_redact_thread_resume_payloads(app_server_client_name.as_deref());
let history_items = source_thread
.history
.take()
.map(|history| history.items)
.ok_or_else(|| {
internal_error(format!(
"thread {existing_thread_id} did not include persisted history"
))
})?;
let thread_state = self
.thread_state_manager
.thread_state(existing_thread_id)
.await;
self.ensure_listener_task_running(
existing_thread_id,
existing_thread.clone(),
thread_state.clone(),
)
.await?;
Self::set_app_server_client_info(
existing_thread.as_ref(),
app_server_client_name,
app_server_client_version,
)
.await?;
let mut thread_summary = self.stored_thread_to_api_thread(
source_thread,
config_snapshot.model_provider_id.as_str(),
/*include_turns*/ false,
);
thread_summary.session_id = existing_thread.session_configured().session_id.to_string();
let instruction_sources = existing_thread.legacy_instruction_sources().await;
let listener_command_tx = {
@@ -3110,26 +3171,32 @@ impl ThreadRequestProcessor {
.pending_resume_goal_state(existing_thread.as_ref())
.await;
let command = crate::thread_state::ThreadListenerCommand::SendThreadResumeResponse(
Box::new(crate::thread_state::PendingThreadResumeRequest {
let (completion_tx, completion_rx) = oneshot::channel();
let command = crate::thread_state::ThreadListenerCommand::SendThreadResumeResponse {
request: Box::new(crate::thread_state::PendingThreadResumeRequest {
request_id: request_id.clone(),
history_items,
app_server_client_name,
app_server_client_version,
config_snapshot,
instruction_sources,
thread_summary,
emit_thread_goal_update,
thread_goal_state_db,
include_turns: !params.exclude_turns,
initial_turns_page: params.initial_turns_page.clone(),
redact_resume_payloads,
_resume_lease: resume_lease,
}),
);
completion_tx,
};
if listener_command_tx.send(command).is_err() {
return Err(internal_error(format!(
"failed to enqueue running thread resume for thread {existing_thread_id}: thread listener command channel is closed"
)));
}
return Ok(RunningThreadResumeResult::Handled);
return Ok(RunningThreadResumeResult::Pending {
completion_rx,
thread_id: existing_thread_id,
});
}
Ok(RunningThreadResumeResult::NotRunning(None))
}
@@ -4107,7 +4174,7 @@ fn thread_store_list_error(err: ThreadStoreError) -> JSONRPCErrorError {
}
}
fn thread_store_resume_read_error(err: ThreadStoreError) -> JSONRPCErrorError {
pub(super) fn thread_store_resume_read_error(err: ThreadStoreError) -> JSONRPCErrorError {
match err {
ThreadStoreError::InvalidRequest { message } => invalid_request(message),
ThreadStoreError::Unsupported { operation } => {
@@ -22,6 +22,7 @@ use codex_core::CodexThread;
use codex_protocol::ThreadId;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::RolloutItem;
use codex_protocol::protocol::TokenUsageInfo;
use crate::outgoing_message::ConnectionId;
use crate::outgoing_message::OutgoingMessageSender;
@@ -44,6 +45,27 @@ pub(super) async fn send_thread_token_usage_update_to_connection(
let Some(info) = conversation.token_usage_info().await else {
return;
};
send_thread_token_usage_snapshot_to_connection(
outgoing,
connection_id,
thread_id,
thread,
info,
token_usage_turn_id,
)
.await;
}
/// Sends a token snapshot captured from the same persisted-history cut that supplied its owner.
/// Running-thread resume uses this to avoid pairing a post-cut live value with a pre-cut turn id.
pub(super) async fn send_thread_token_usage_snapshot_to_connection(
outgoing: &Arc<OutgoingMessageSender>,
connection_id: ConnectionId,
thread_id: ThreadId,
thread: &Thread,
info: TokenUsageInfo,
token_usage_turn_id: Option<String>,
) {
let notification = ThreadTokenUsageUpdatedNotification {
thread_id: thread_id.to_string(),
turn_id: token_usage_turn_id.unwrap_or_else(|| latest_token_usage_turn_id(thread)),
@@ -57,6 +79,17 @@ pub(super) async fn send_thread_token_usage_update_to_connection(
.await;
}
pub(super) fn latest_token_usage_info_from_rollout_items(
rollout_items: &[RolloutItem],
) -> Option<TokenUsageInfo> {
rollout_items.iter().rev().find_map(|item| {
let RolloutItem::EventMsg(EventMsg::TokenCount(event)) = item else {
return None;
};
event.info.clone()
})
}
/// Identifies the turn that was active when a `TokenCount` record appeared.
///
/// The id is preferred when it still appears in the rebuilt thread. The position is a
@@ -74,7 +107,10 @@ pub(super) fn latest_token_usage_turn_id_from_rollout_items(
let mut token_usage_turn_owner = None;
for item in rollout_items {
if matches!(item, RolloutItem::EventMsg(EventMsg::TokenCount(_))) {
if matches!(
item,
RolloutItem::EventMsg(EventMsg::TokenCount(event)) if event.info.is_some()
) {
token_usage_turn_owner =
builder
.active_turn_snapshot()
@@ -119,6 +155,9 @@ mod tests {
use codex_app_server_protocol::build_turns_from_rollout_items;
use codex_protocol::protocol::AgentMessageEvent;
use codex_protocol::protocol::TokenCountEvent;
use codex_protocol::protocol::TokenUsage;
use codex_protocol::protocol::TokenUsageInfo;
use codex_protocol::protocol::TurnStartedEvent;
use codex_protocol::protocol::UserMessageEvent;
use pretty_assertions::assert_eq;
@@ -145,6 +184,130 @@ mod tests {
);
}
#[test]
fn persisted_cut_captures_token_value_and_owner_without_post_cut_live_state() {
let usage_b = TokenUsageInfo {
total_token_usage: TokenUsage {
total_tokens: 20,
..TokenUsage::default()
},
last_token_usage: TokenUsage {
total_tokens: 10,
..TokenUsage::default()
},
model_context_window: Some(100_000),
};
let history_items = vec![
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
turn_id: "turn-b".to_string(),
trace_id: None,
started_at: Some(1),
model_context_window: Some(100_000),
collaboration_mode_kind: Default::default(),
})),
RolloutItem::EventMsg(EventMsg::TokenCount(TokenCountEvent {
info: Some(usage_b.clone()),
rate_limits: None,
})),
];
let turns = build_turns_from_rollout_items(&history_items);
assert_eq!(
latest_token_usage_info_from_rollout_items(&history_items),
Some(usage_b)
);
assert_eq!(
latest_token_usage_turn_id_from_rollout_items(&history_items, &turns),
Some("turn-b".to_string())
);
// A post-cut turn C is deliberately absent: running resume passes this captured B pair
// directly to the sender, so live state cannot relabel B or duplicate C.
}
#[test]
fn rate_limit_only_token_event_does_not_relabel_previous_usage_owner() {
let usage_a = TokenUsageInfo {
total_token_usage: TokenUsage {
total_tokens: 10,
..TokenUsage::default()
},
last_token_usage: TokenUsage {
total_tokens: 10,
..TokenUsage::default()
},
model_context_window: Some(100_000),
};
let usage_c = TokenUsageInfo {
total_token_usage: TokenUsage {
total_tokens: 30,
..TokenUsage::default()
},
last_token_usage: TokenUsage {
total_tokens: 20,
..TokenUsage::default()
},
model_context_window: Some(100_000),
};
let mut history = vec![
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
turn_id: "turn-a".to_string(),
trace_id: None,
started_at: Some(1),
model_context_window: Some(100_000),
collaboration_mode_kind: Default::default(),
})),
RolloutItem::EventMsg(EventMsg::TokenCount(TokenCountEvent {
info: Some(usage_a.clone()),
rate_limits: None,
})),
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
turn_id: "turn-b".to_string(),
trace_id: None,
started_at: Some(2),
model_context_window: Some(100_000),
collaboration_mode_kind: Default::default(),
})),
RolloutItem::EventMsg(EventMsg::TokenCount(TokenCountEvent {
info: None,
rate_limits: None,
})),
];
let turns = build_turns_from_rollout_items(&history);
assert_eq!(
latest_token_usage_info_from_rollout_items(&history),
Some(usage_a)
);
assert_eq!(
latest_token_usage_turn_id_from_rollout_items(&history, &turns),
Some("turn-a".to_string())
);
history.push(RolloutItem::EventMsg(EventMsg::TurnStarted(
TurnStartedEvent {
turn_id: "turn-c".to_string(),
trace_id: None,
started_at: Some(3),
model_context_window: Some(100_000),
collaboration_mode_kind: Default::default(),
},
)));
history.push(RolloutItem::EventMsg(EventMsg::TokenCount(
TokenCountEvent {
info: Some(usage_c.clone()),
rate_limits: None,
},
)));
let turns = build_turns_from_rollout_items(&history);
assert_eq!(
latest_token_usage_info_from_rollout_items(&history),
Some(usage_c)
);
assert_eq!(
latest_token_usage_turn_id_from_rollout_items(&history, &turns),
Some("turn-c".to_string())
);
}
fn token_usage_history() -> Vec<RolloutItem> {
vec![
RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
@@ -161,7 +324,17 @@ mod tests {
memory_citation: None,
})),
RolloutItem::EventMsg(EventMsg::TokenCount(TokenCountEvent {
info: None,
info: Some(TokenUsageInfo {
total_token_usage: TokenUsage {
total_tokens: 10,
..TokenUsage::default()
},
last_token_usage: TokenUsage {
total_tokens: 10,
..TokenUsage::default()
},
model_context_window: Some(100_000),
}),
rate_limits: None,
})),
RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
+298 -4
View File
@@ -1,5 +1,6 @@
use crate::outgoing_message::ConnectionId;
use crate::outgoing_message::ConnectionRequestId;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::ThreadGoal;
use codex_app_server_protocol::ThreadHistoryBuilder;
@@ -8,6 +9,7 @@ use codex_app_server_protocol::Turn;
use codex_app_server_protocol::TurnError;
use codex_core::CodexThread;
use codex_core::ThreadConfigSnapshot;
use codex_core::ThreadHistoryReconciliationOutcome;
use codex_file_watcher::WatchRegistration;
use codex_protocol::ThreadId;
#[cfg(test)]
@@ -15,6 +17,7 @@ use codex_protocol::config_types::MultiAgentMode;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::RolloutItem;
use codex_rollout::state_db::StateDbHandle;
use codex_thread_store::StoredThread;
use codex_utils_path_uri::LegacyAppPathString;
use std::collections::HashMap;
use std::collections::HashSet;
@@ -29,24 +32,63 @@ use tracing::error;
type PendingInterruptQueue = Vec<ConnectionRequestId>;
pub(crate) struct PendingThreadRollback {
pub(crate) request_id: ConnectionRequestId,
completion_tx: Option<oneshot::Sender<()>>,
}
impl PendingThreadRollback {
pub(crate) fn new(request_id: ConnectionRequestId, completion_tx: oneshot::Sender<()>) -> Self {
Self {
request_id,
completion_tx: Some(completion_tx),
}
}
pub(crate) fn complete(mut self) {
if let Some(completion_tx) = self.completion_tx.take() {
let _ = completion_tx.send(());
}
}
}
pub(crate) struct PendingThreadResumeRequest {
pub(crate) request_id: ConnectionRequestId,
pub(crate) history_items: Vec<RolloutItem>,
pub(crate) app_server_client_name: Option<String>,
pub(crate) app_server_client_version: Option<String>,
pub(crate) config_snapshot: ThreadConfigSnapshot,
pub(crate) instruction_sources: Vec<LegacyAppPathString>,
pub(crate) thread_summary: codex_app_server_protocol::Thread,
pub(crate) emit_thread_goal_update: bool,
pub(crate) thread_goal_state_db: Option<StateDbHandle>,
pub(crate) include_turns: bool,
pub(crate) initial_turns_page:
Option<codex_app_server_protocol::ThreadResumeInitialTurnsPageParams>,
pub(crate) redact_resume_payloads: bool,
pub(crate) _resume_lease: ThreadPointOperationLease,
}
pub(crate) struct PreparedThreadResumeHistory {
pub(crate) stored_thread: StoredThread,
pub(crate) history_items: Vec<RolloutItem>,
pub(crate) reconciliation_outcome: ThreadHistoryReconciliationOutcome,
}
// ThreadListenerCommand is used to perform operations in the context of the thread listener, for serialization purposes.
pub(crate) enum ThreadListenerCommand {
// SendThreadResumeResponse is used to resume an already running thread by sending the thread's history to the client and atomically subscribing for new updates.
SendThreadResumeResponse(Box<PendingThreadResumeRequest>),
SendThreadResumeResponse {
request: Box<PendingThreadResumeRequest>,
completion_tx: oneshot::Sender<()>,
},
// Completes the storage phase of a running-thread resume. The worker retains the core event
// cut until `release_event_cut_tx` is dropped, so the listener can drain the exact pre-cut
// event queue before subscribing the requesting connection.
FinishThreadResumeResponse {
request: Box<PendingThreadResumeRequest>,
completion_tx: oneshot::Sender<()>,
history_result: Box<Result<PreparedThreadResumeHistory, JSONRPCErrorError>>,
release_event_cut_tx: oneshot::Sender<()>,
},
// EmitThreadGoalUpdated is used to order goal updates with running-thread resume responses and goal clears.
EmitThreadGoalUpdated {
turn_id: Option<String>,
@@ -77,7 +119,7 @@ pub(crate) struct TurnSummary {
#[derive(Default)]
pub(crate) struct ThreadState {
pub(crate) pending_interrupts: PendingInterruptQueue,
pub(crate) pending_rollbacks: Option<ConnectionRequestId>,
pub(crate) pending_rollbacks: Option<PendingThreadRollback>,
pub(crate) turn_summary: TurnSummary,
pub(crate) last_terminal_turn_id: Option<String>,
pub(crate) cancel_tx: Option<oneshot::Sender<()>>,
@@ -122,6 +164,7 @@ impl ThreadState {
let _ = cancel_tx.send(());
}
self.listener_command_tx = None;
drop(self.pending_rollbacks.take());
self.current_turn_history.reset();
self.listener_thread = None;
self.watch_registration = WatchRegistration::default();
@@ -141,6 +184,22 @@ impl ThreadState {
self.current_turn_history.active_turn_snapshot()
}
pub(crate) fn projected_active_turn_snapshot<'a>(
&self,
events: impl IntoIterator<Item = (&'a str, &'a EventMsg)>,
) -> Option<Turn> {
let mut projected_history = self.current_turn_history.clone();
for (_event_turn_id, event) in events {
projected_history.handle_event(event);
if matches!(event, EventMsg::TurnAborted(_) | EventMsg::TurnComplete(_))
&& !projected_history.has_active_turn()
{
projected_history.reset();
}
}
projected_history.active_turn_snapshot()
}
pub(crate) fn track_current_turn_event(&mut self, event_turn_id: &str, event: &EventMsg) {
if let EventMsg::TurnStarted(payload) = event {
self.turn_summary.started_at = payload.started_at;
@@ -202,6 +261,8 @@ mod tests {
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::config_types::ModeKind;
use codex_protocol::config_types::Settings;
use codex_protocol::protocol::TurnCompleteEvent;
use codex_protocol::protocol::TurnStartedEvent;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
@@ -221,6 +282,174 @@ mod tests {
assert_eq!(results, vec![true, false, true, false]);
}
#[test]
fn projected_resume_overlay_does_not_advance_live_backlog_state() {
let mut state = ThreadState::default();
let a_start = EventMsg::TurnStarted(TurnStartedEvent {
turn_id: "turn-a".to_string(),
trace_id: None,
started_at: Some(1),
model_context_window: None,
collaboration_mode_kind: Default::default(),
});
let a_complete = EventMsg::TurnComplete(TurnCompleteEvent {
turn_id: "turn-a".to_string(),
last_agent_message: None,
completed_at: Some(2),
duration_ms: Some(1_000),
time_to_first_token_ms: None,
});
let b_start = EventMsg::TurnStarted(TurnStartedEvent {
turn_id: "turn-b".to_string(),
trace_id: None,
started_at: Some(3),
model_context_window: None,
collaboration_mode_kind: Default::default(),
});
let backlog = [
("turn-a", &a_start),
("turn-a", &a_complete),
("turn-b", &b_start),
];
let projected = state
.projected_active_turn_snapshot(backlog)
.expect("resume overlay should project the final active turn");
assert_eq!(projected.id, "turn-b");
assert!(state.active_turn_snapshot().is_none());
state.track_current_turn_event("turn-a", &a_start);
assert_eq!(
state
.active_turn_snapshot()
.expect("A should be active while dispatching A start")
.id,
"turn-a"
);
state.track_current_turn_event("turn-a", &a_complete);
assert!(state.active_turn_snapshot().is_none());
state.track_current_turn_event("turn-b", &b_start);
assert_eq!(
state
.active_turn_snapshot()
.expect("B should be active while dispatching B start")
.id,
"turn-b"
);
}
#[tokio::test]
#[expect(
clippy::await_holding_invalid_type,
reason = "the test proves lease acquisition waits for the unload commit guard"
)]
async fn point_operation_lease_preserves_unsubscribe_and_blocks_idle_unload() {
let manager = ThreadStateManager::new();
let thread_id = ThreadId::new();
let connection_id = ConnectionId(1);
let pending_thread_unloads = Arc::new(Mutex::new(HashSet::new()));
manager
.connection_initialized(connection_id, ConnectionCapabilities::default())
.await;
manager
.try_ensure_connection_subscribed(
thread_id,
connection_id,
/*experimental_raw_events*/ false,
)
.await
.expect("connection should be live");
assert!(
manager
.unsubscribe_connection_from_thread(thread_id, connection_id)
.await
);
assert!(!manager.has_subscribers(thread_id).await);
let lease = match manager
.acquire_point_operation_lease(&pending_thread_unloads, thread_id, connection_id)
.await
{
ThreadPointOperationLeaseAcquireResult::Acquired { lease, .. } => lease,
_ => panic!("point operation should accept a live unsubscribed connection"),
};
assert!(!manager.has_subscribers(thread_id).await);
assert!(
manager
.subscribed_connection_ids(thread_id)
.await
.is_empty()
);
let mut point_operation_count = manager
.subscribe_to_point_operation_count(thread_id)
.await
.expect("point-operation watcher");
assert_eq!(*point_operation_count.borrow(), 1);
let simulated_idle_unload = async {
loop {
let operation_in_flight = *point_operation_count.borrow_and_update() != 0;
if !operation_in_flight {
break;
}
point_operation_count
.changed()
.await
.expect("point-operation watcher should remain open");
}
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
};
tokio::pin!(simulated_idle_unload);
assert!(
tokio::time::timeout(
std::time::Duration::from_millis(20),
simulated_idle_unload.as_mut(),
)
.await
.is_err(),
"an idle unload must remain blocked while the point operation is leased"
);
drop(lease);
tokio::time::timeout(std::time::Duration::from_secs(1), simulated_idle_unload)
.await
.expect("idle unload should proceed after the point operation completes");
// Hold the same mutex across the unload path's final eligibility check and marker
// commit. A racing acquisition cannot slip into that interval and must observe closing.
let mut unload_commit = pending_thread_unloads.lock().await;
let racing_acquire = manager.acquire_point_operation_lease(
&pending_thread_unloads,
thread_id,
connection_id,
);
tokio::pin!(racing_acquire);
assert!(
tokio::time::timeout(
std::time::Duration::from_millis(20),
racing_acquire.as_mut(),
)
.await
.is_err(),
"lease acquisition must wait for the unload commit section"
);
unload_commit.insert(thread_id);
drop(unload_commit);
assert!(matches!(
racing_acquire.await,
ThreadPointOperationLeaseAcquireResult::ThreadClosing
));
pending_thread_unloads.lock().await.clear();
manager.remove_connection(connection_id).await;
assert!(matches!(
manager
.acquire_point_operation_lease(&pending_thread_unloads, thread_id, connection_id,)
.await,
ThreadPointOperationLeaseAcquireResult::ConnectionClosed
));
}
fn thread_settings(model: &str) -> ThreadSettings {
ThreadSettings {
cwd: AbsolutePathBuf::from_absolute_path("/tmp").expect("absolute path"),
@@ -253,6 +482,7 @@ struct ThreadEntry {
state: Arc<Mutex<ThreadState>>,
connection_ids: HashSet<ConnectionId>,
has_connections_watcher: watch::Sender<bool>,
point_operation_count_watcher: watch::Sender<usize>,
}
impl Default for ThreadEntry {
@@ -261,6 +491,7 @@ impl Default for ThreadEntry {
state: Arc::new(Mutex::new(ThreadState::default())),
connection_ids: HashSet::new(),
has_connections_watcher: watch::channel(false).0,
point_operation_count_watcher: watch::channel(0).0,
}
}
}
@@ -296,6 +527,26 @@ pub(crate) struct ThreadStateManager {
Arc<StdMutex<HashMap<ThreadId, mpsc::UnboundedSender<ThreadListenerCommand>>>>,
}
pub(crate) struct ThreadPointOperationLease {
point_operation_count_watcher: watch::Sender<usize>,
}
pub(crate) enum ThreadPointOperationLeaseAcquireResult {
Acquired {
thread_state: Arc<Mutex<ThreadState>>,
lease: ThreadPointOperationLease,
},
ConnectionClosed,
ThreadClosing,
}
impl Drop for ThreadPointOperationLease {
fn drop(&mut self) {
self.point_operation_count_watcher
.send_modify(|count| *count = count.saturating_sub(1));
}
}
impl ThreadStateManager {
pub(crate) fn new() -> Self {
Self::default()
@@ -519,6 +770,38 @@ impl ThreadStateManager {
Some(thread_state)
}
#[expect(
clippy::await_holding_invalid_type,
reason = "lease acquisition must serialize with the unload marker commit"
)]
pub(crate) async fn acquire_point_operation_lease(
&self,
pending_thread_unloads: &Arc<Mutex<HashSet<ThreadId>>>,
thread_id: ThreadId,
connection_id: ConnectionId,
) -> ThreadPointOperationLeaseAcquireResult {
// Serialize against the unload path's final eligibility check and closing-marker commit.
// Once this guard is released, the watch-backed lease makes that final check fail.
let pending_thread_unloads = pending_thread_unloads.lock().await;
if pending_thread_unloads.contains(&thread_id) {
return ThreadPointOperationLeaseAcquireResult::ThreadClosing;
}
let mut state = self.state.lock().await;
if !state.live_connections.contains_key(&connection_id) {
return ThreadPointOperationLeaseAcquireResult::ConnectionClosed;
}
let thread_entry = state.threads.entry(thread_id).or_default();
thread_entry
.point_operation_count_watcher
.send_modify(|count| *count = count.saturating_add(1));
ThreadPointOperationLeaseAcquireResult::Acquired {
thread_state: thread_entry.state.clone(),
lease: ThreadPointOperationLease {
point_operation_count_watcher: thread_entry.point_operation_count_watcher.clone(),
},
}
}
pub(crate) async fn try_add_connection_to_thread(
&self,
thread_id: ThreadId,
@@ -575,4 +858,15 @@ impl ThreadStateManager {
.get(&thread_id)
.map(|thread_entry| thread_entry.has_connections_watcher.subscribe())
}
pub(crate) async fn subscribe_to_point_operation_count(
&self,
thread_id: ThreadId,
) -> Option<watch::Receiver<usize>> {
let state = self.state.lock().await;
state
.threads
.get(&thread_id)
.map(|thread_entry| thread_entry.point_operation_count_watcher.subscribe())
}
}
@@ -22,6 +22,7 @@ use codex_app_server_protocol::FileChangeApprovalDecision;
use codex_app_server_protocol::FileChangeRequestApprovalResponse;
use codex_app_server_protocol::ItemStartedNotification;
use codex_app_server_protocol::JSONRPCError;
use codex_app_server_protocol::JSONRPCMessage;
use codex_app_server_protocol::JSONRPCResponse;
use codex_app_server_protocol::McpToolCallAppContext;
use codex_app_server_protocol::PatchApplyStatus;
@@ -33,6 +34,7 @@ use codex_app_server_protocol::SessionSource;
use codex_app_server_protocol::ThreadGoalClearResponse;
use codex_app_server_protocol::ThreadGoalSetResponse;
use codex_app_server_protocol::ThreadGoalStatus;
use codex_app_server_protocol::ThreadInjectItemsParams;
use codex_app_server_protocol::ThreadItem;
use codex_app_server_protocol::ThreadListResponse;
use codex_app_server_protocol::ThreadMetadataGitInfoUpdateParams;
@@ -42,6 +44,8 @@ use codex_app_server_protocol::ThreadReadResponse;
use codex_app_server_protocol::ThreadResumeInitialTurnsPageParams;
use codex_app_server_protocol::ThreadResumeParams;
use codex_app_server_protocol::ThreadResumeResponse;
use codex_app_server_protocol::ThreadRollbackParams;
use codex_app_server_protocol::ThreadRollbackResponse;
use codex_app_server_protocol::ThreadSource;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
@@ -149,6 +153,18 @@ async fn wait_for_responses_request_count(
Ok(())
}
async fn read_next_response(mcp: &mut TestAppServer) -> Result<JSONRPCResponse> {
loop {
match mcp.read_next_message().await? {
JSONRPCMessage::Response(response) => return Ok(response),
JSONRPCMessage::Error(error) => {
anyhow::bail!("unexpected app-server error response: {error:?}")
}
_ => {}
}
}
}
#[tokio::test]
async fn thread_resume_rejects_unmaterialized_thread() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
@@ -681,6 +697,7 @@ async fn thread_resume_running_thread_tracks_thread_originator_in_analytics() ->
let ThreadResumeResponse {
thread: resumed, ..
} = to_response::<ThreadResumeResponse>(resume_resp)?;
assert_eq!(resumed.thread_source, Some(ThreadSource::User));
let event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_thread_initialized"
@@ -3211,6 +3228,15 @@ async fn thread_resume_replays_pending_command_execution_request_approval() -> R
)
.await??;
pretty_assertions::assert_eq!(replayed_request, original_request);
assert!(
timeout(
Duration::from_millis(100),
primary.read_stream_until_request_message(),
)
.await
.is_err(),
"thread/resume must replay each pending approval request ID exactly once"
);
let ServerRequest::CommandExecutionRequestApproval { request_id, .. } = replayed_request else {
panic!("expected CommandExecutionRequestApproval request");
@@ -3728,6 +3754,549 @@ async fn thread_resume_supports_history_and_overrides() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn thread_resume_reconciles_history_appended_by_another_app_server() -> Result<()> {
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_response_created("primary-response"),
responses::ev_assistant_message("primary-message", "primary complete"),
responses::ev_completed("primary-response"),
]),
responses::sse(vec![
responses::ev_response_created("secondary-response"),
responses::ev_assistant_message("secondary-message", "secondary complete"),
responses::ev_completed("secondary-response"),
]),
responses::sse(vec![
responses::ev_response_created("final-response"),
responses::ev_assistant_message("final-message", "final complete"),
responses::ev_completed("final-response"),
]),
],
)
.await;
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), &server.uri())?;
let mut primary = TestAppServer::new_with_auto_env(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, primary.initialize()).await??;
let start_id = primary
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
let start_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
primary.read_stream_until_response_message(RequestId::Integer(start_id)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response::<ThreadStartResponse>(start_resp)?;
let seed_turn_id = primary
.send_turn_start_request(TurnStartParams {
thread_id: thread.id.clone(),
client_user_message_id: None,
input: vec![UserInput::Text {
text: "primary seed".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
timeout(
DEFAULT_READ_TIMEOUT,
primary.read_stream_until_response_message(RequestId::Integer(seed_turn_id)),
)
.await??;
timeout(
DEFAULT_READ_TIMEOUT,
primary.read_stream_until_notification_message("turn/completed"),
)
.await??;
let mut secondary = TestAppServer::new_with_auto_env(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, secondary.initialize()).await??;
let secondary_resume_id = secondary
.send_thread_resume_request(ThreadResumeParams {
thread_id: thread.id.clone(),
..Default::default()
})
.await?;
timeout(
DEFAULT_READ_TIMEOUT,
secondary.read_stream_until_response_message(RequestId::Integer(secondary_resume_id)),
)
.await??;
let secondary_turn_id = secondary
.send_turn_start_request(TurnStartParams {
thread_id: thread.id.clone(),
client_user_message_id: None,
input: vec![UserInput::Text {
text: "secondary external turn".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
timeout(
DEFAULT_READ_TIMEOUT,
secondary.read_stream_until_response_message(RequestId::Integer(secondary_turn_id)),
)
.await??;
timeout(
DEFAULT_READ_TIMEOUT,
secondary.read_stream_until_notification_message("turn/completed"),
)
.await??;
let metadata_update_id = secondary
.send_thread_metadata_update_request(ThreadMetadataUpdateParams {
thread_id: thread.id.clone(),
git_info: Some(ThreadMetadataGitInfoUpdateParams {
sha: None,
branch: Some(Some("secondary/external-update".to_string())),
origin_url: None,
}),
})
.await?;
timeout(
DEFAULT_READ_TIMEOUT,
secondary.read_stream_until_response_message(RequestId::Integer(metadata_update_id)),
)
.await??;
let secondary_read_id = secondary
.send_thread_read_request(ThreadReadParams {
thread_id: thread.id.clone(),
include_turns: false,
})
.await?;
let secondary_read_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
secondary.read_stream_until_response_message(RequestId::Integer(secondary_read_id)),
)
.await??;
let ThreadReadResponse {
thread: authoritative_thread,
} = to_response::<ThreadReadResponse>(secondary_read_resp)?;
let primary_resume_id = primary
.send_thread_resume_request(ThreadResumeParams {
thread_id: thread.id.clone(),
exclude_turns: true,
initial_turns_page: Some(ThreadResumeInitialTurnsPageParams {
limit: Some(5),
sort_direction: None,
items_view: Some(TurnItemsView::Full),
}),
..Default::default()
})
.await?;
let primary_resume_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
primary.read_stream_until_response_message(RequestId::Integer(primary_resume_id)),
)
.await??;
let ThreadResumeResponse {
thread: resumed_thread,
initial_turns_page,
..
} = to_response::<ThreadResumeResponse>(primary_resume_resp)?;
assert!(resumed_thread.turns.is_empty());
assert_eq!(resumed_thread.git_info, authoritative_thread.git_info);
assert_eq!(resumed_thread.updated_at, authoritative_thread.updated_at);
assert_eq!(resumed_thread.recency_at, authoritative_thread.recency_at);
assert_eq!(resumed_thread.preview, authoritative_thread.preview);
let initial_turns_page = initial_turns_page.expect("Desktop-style initial turns page");
assert!(
initial_turns_page
.data
.iter()
.flat_map(|turn| &turn.items)
.any(|item| matches!(
item,
ThreadItem::UserMessage { content, .. }
if content.iter().any(|input| matches!(
input,
UserInput::Text { text, .. } if text == "secondary external turn"
))
)),
"primary resume response should include the externally appended turn"
);
let final_turn_id = primary
.send_turn_start_request(TurnStartParams {
thread_id: thread.id,
client_user_message_id: None,
input: vec![UserInput::Text {
text: "primary final turn".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
timeout(
DEFAULT_READ_TIMEOUT,
primary.read_stream_until_response_message(RequestId::Integer(final_turn_id)),
)
.await??;
timeout(
DEFAULT_READ_TIMEOUT,
primary.read_stream_until_notification_message("turn/completed"),
)
.await??;
let requests = response_mock.requests();
assert_eq!(requests.len(), 3, "expected one model call per turn");
let final_request = requests.last().expect("final primary model request");
let final_input = final_request.body_json()["input"].to_string();
assert_eq!(
final_input.matches("secondary external turn").count(),
1,
"the externally appended turn must appear exactly once in the resumed model context: {final_input}"
);
assert_eq!(
final_input.matches("secondary complete").count(),
1,
"the external assistant response must appear exactly once in the resumed model context: {final_input}"
);
Ok(())
}
#[tokio::test]
async fn running_thread_resume_does_not_reappend_stale_interrupted_turn() -> Result<()> {
#[cfg(target_os = "windows")]
let sleep_command = vec![
"powershell".to_string(),
"-Command".to_string(),
"Start-Sleep -Seconds 10".to_string(),
];
#[cfg(not(target_os = "windows"))]
let sleep_command = vec!["sleep".to_string(), "10".to_string()];
let server = create_mock_responses_server_sequence_unchecked(vec![
create_shell_command_sse_response(
sleep_command,
/*workdir*/ None,
Some(10_000),
"interrupted-command",
)?,
create_final_assistant_message_sse_response("external complete")?,
])
.await;
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), &server.uri())?;
let mut primary = TestAppServer::new_with_auto_env(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, primary.initialize()).await??;
let start_id = primary
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
let start_response = timeout(
DEFAULT_READ_TIMEOUT,
primary.read_stream_until_response_message(RequestId::Integer(start_id)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response(start_response)?;
let interrupted_request_id = primary
.send_turn_start_request(TurnStartParams {
thread_id: thread.id.clone(),
input: vec![UserInput::Text {
text: "primary interrupted turn".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
let interrupted_response = timeout(
DEFAULT_READ_TIMEOUT,
primary.read_stream_until_response_message(RequestId::Integer(interrupted_request_id)),
)
.await??;
let TurnStartResponse {
turn: interrupted_turn,
} = to_response(interrupted_response)?;
timeout(
DEFAULT_READ_TIMEOUT,
primary.read_stream_until_notification_message("turn/started"),
)
.await??;
timeout(DEFAULT_READ_TIMEOUT, async {
loop {
let notification = primary
.read_stream_until_notification_message("item/started")
.await?;
let started: ItemStartedNotification =
serde_json::from_value(notification.params.expect("item/started params"))?;
if matches!(started.item, ThreadItem::CommandExecution { .. }) {
return Ok::<(), anyhow::Error>(());
}
}
})
.await??;
primary
.interrupt_turn_and_wait_for_aborted(
thread.id.clone(),
interrupted_turn.id.clone(),
DEFAULT_READ_TIMEOUT,
)
.await?;
let mut secondary = TestAppServer::new_with_auto_env(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, secondary.initialize()).await??;
let secondary_resume_id = secondary
.send_thread_resume_request(ThreadResumeParams {
thread_id: thread.id.clone(),
..Default::default()
})
.await?;
timeout(
DEFAULT_READ_TIMEOUT,
secondary.read_stream_until_response_message(RequestId::Integer(secondary_resume_id)),
)
.await??;
let external_turn_request_id = secondary
.send_turn_start_request(TurnStartParams {
thread_id: thread.id.clone(),
input: vec![UserInput::Text {
text: "secondary external turn".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
let external_turn_response = timeout(
DEFAULT_READ_TIMEOUT,
secondary.read_stream_until_response_message(RequestId::Integer(external_turn_request_id)),
)
.await??;
let TurnStartResponse {
turn: external_turn,
} = to_response(external_turn_response)?;
timeout(
DEFAULT_READ_TIMEOUT,
secondary.read_stream_until_notification_message("turn/completed"),
)
.await??;
let primary_resume_id = primary
.send_thread_resume_request(ThreadResumeParams {
thread_id: thread.id,
..Default::default()
})
.await?;
let primary_resume_response = timeout(
DEFAULT_READ_TIMEOUT,
primary.read_stream_until_response_message(RequestId::Integer(primary_resume_id)),
)
.await??;
let ThreadResumeResponse {
thread: resumed_thread,
..
} = to_response(primary_resume_response)?;
assert_eq!(resumed_thread.turns.len(), 2);
assert_eq!(resumed_thread.turns[0].id, interrupted_turn.id);
assert_eq!(resumed_thread.turns[0].status, TurnStatus::Interrupted);
assert_eq!(resumed_thread.turns[1].id, external_turn.id);
assert_eq!(resumed_thread.turns[1].status, TurnStatus::Completed);
Ok(())
}
#[tokio::test]
async fn running_thread_resume_serializes_with_following_history_injection() -> Result<()> {
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_response_created("seed-response"),
responses::ev_assistant_message("seed-message", "seed complete"),
responses::ev_completed("seed-response"),
]),
responses::sse(vec![
responses::ev_response_created("final-response"),
responses::ev_assistant_message("final-message", "final complete"),
responses::ev_completed("final-response"),
]),
],
)
.await;
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), &server.uri())?;
let mut mcp = TestAppServer::new_with_auto_env(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
let start_response = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(start_id)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response(start_response)?;
let seed_id = mcp
.send_turn_start_request(TurnStartParams {
thread_id: thread.id.clone(),
input: vec![UserInput::Text {
text: "seed turn".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(seed_id)),
)
.await??;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
mcp.clear_message_buffer();
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
thread_id: thread.id.clone(),
exclude_turns: true,
..Default::default()
})
.await?;
let injected_text = "injected after queued resume";
let injected_item = ResponseItem::Message {
id: None,
role: "assistant".to_string(),
content: vec![ContentItem::OutputText {
text: injected_text.to_string(),
}],
phase: None,
internal_chat_message_metadata_passthrough: None,
};
let inject_id = mcp
.send_thread_inject_items_request(ThreadInjectItemsParams {
thread_id: thread.id.clone(),
items: vec![serde_json::to_value(injected_item)?],
})
.await?;
let first_response = timeout(DEFAULT_READ_TIMEOUT, read_next_response(&mut mcp)).await??;
assert_eq!(first_response.id, RequestId::Integer(resume_id));
let second_response = timeout(DEFAULT_READ_TIMEOUT, read_next_response(&mut mcp)).await??;
assert_eq!(second_response.id, RequestId::Integer(inject_id));
let final_id = mcp
.send_turn_start_request(TurnStartParams {
thread_id: thread.id,
input: vec![UserInput::Text {
text: "final turn".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(final_id)),
)
.await??;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
let requests = response_mock.requests();
let final_input =
requests.last().expect("final model request").body_json()["input"].to_string();
assert_eq!(
final_input.matches(injected_text).count(),
1,
"{final_input}"
);
Ok(())
}
#[tokio::test]
async fn running_thread_resume_waits_for_preceding_rollback() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), &server.uri())?;
let mut mcp = TestAppServer::new_with_auto_env(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
let start_response = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(start_id)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response(start_response)?;
for prompt in ["first turn", "second turn"] {
let turn_id = mcp
.send_turn_start_request(TurnStartParams {
thread_id: thread.id.clone(),
input: vec![UserInput::Text {
text: prompt.to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(turn_id)),
)
.await??;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
}
mcp.clear_message_buffer();
let rollback_id = mcp
.send_thread_rollback_request(ThreadRollbackParams {
thread_id: thread.id.clone(),
num_turns: 1,
})
.await?;
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
thread_id: thread.id,
..Default::default()
})
.await?;
let rollback_response = timeout(DEFAULT_READ_TIMEOUT, read_next_response(&mut mcp)).await??;
assert_eq!(rollback_response.id, RequestId::Integer(rollback_id));
let rollback: ThreadRollbackResponse = to_response(rollback_response)?;
assert_eq!(rollback.thread.turns.len(), 1);
let resume_response = timeout(DEFAULT_READ_TIMEOUT, read_next_response(&mut mcp)).await??;
assert_eq!(resume_response.id, RequestId::Integer(resume_id));
let resumed: ThreadResumeResponse = to_response(resume_response)?;
assert_eq!(resumed.thread.turns.len(), 1);
Ok(())
}
struct RestartedThreadFixture {
mcp: TestAppServer,
thread_id: String,