Wake idle root threads on persisted agent messages (#63312)

## Why

Plaintext agent messages injected through `thread/inject_items` could
be saved to root-thread history without waking the thread, even when
agent-message wakes were enabled.

## What changed

After persisting a batch of plaintext agent messages with unspecified
retention, let the native multi-agent v2 root thread's mailbox scheduler
apply its usual wake and turn-admission rules. Use the recorded history
sequence to skip a wake if another turn already read the messages and
to deliver the mail directly from history without re-enqueueing it.

## Testing

Cover app-server injection with wakes enabled and disabled, wake a
reloaded sleeping root with its previous turn context, and verify that
a paused turn-admission gate defers the wake and the eventual model
request contains the message once.

GitOrigin-RevId: 5fde8062a179fd7a7919d240373592f2dbb4a389
This commit is contained in:
jif
2026-11-23 11:16:31 +00:00
committed by copyberry
parent a1604a8c05
commit ca891cecdc
9 changed files with 237 additions and 101 deletions
+76 -5
View File
@@ -1,17 +1,58 @@
//! Records client injections and preserves their existing active-turn delivery.
use super::RealtimeRecord;
use super::TurnInput as PendingTurnInput;
use super::session::Session;
use super::turn_context::TurnContext;
use codex_features::Feature;
use codex_history::ResponseItemEnvelope;
use codex_protocol::AgentPath;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use codex_protocol::models::AgentMessageInputContent;
use codex_protocol::models::ResponseItem;
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::MultiAgentVersion;
use codex_thread_store::PersistContext;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
/// Native queue-only delivery accepts only ordinary plaintext agent messages.
pub(crate) fn plaintext_agent_messages<'a>(
items: impl IntoIterator<Item = &'a ResponseItem>,
) -> Option<Vec<InterAgentCommunication>> {
items
.into_iter()
.map(|item| {
let ResponseItem::AgentMessage {
id,
author,
recipient,
content,
internal_chat_message_metadata_passthrough,
} = item
else {
return None;
};
let [AgentMessageInputContent::InputText { text }] = content.as_slice() else {
return None;
};
Some(InterAgentCommunication {
id: id.clone(),
author: AgentPath::try_from(author.as_str()).ok()?,
recipient: AgentPath::try_from(recipient.as_str()).ok()?,
other_recipients: Vec::new(),
content: text.clone(),
encrypted_content: None,
internal_chat_message_metadata_passthrough:
internal_chat_message_metadata_passthrough.clone(),
trigger_turn: false,
})
})
.collect()
}
/// Uploaded files need the admission checks on typed turn input before entering history.
pub(crate) fn validate_injected_response_item(item: &ResponseItem) -> CodexResult<()> {
if item.file_audio_ids().next().is_some() {
@@ -23,6 +64,34 @@ pub(crate) fn validate_injected_response_item(item: &ResponseItem) -> CodexResul
}
impl Session {
/// Seal idle input before exposing its wake to the ordinary mailbox scheduler.
pub(crate) async fn checkpoint_client_injection(
self: &Arc<Self>,
recorded_mail: Option<u64>,
) -> std::io::Result<()> {
self.try_ensure_rollout_materialized(PersistContext::ThreadPreparation)
.await?;
if let Some(recorded_through) = recorded_mail.filter(|sequence| *sequence > 0)
&& self.multi_agent_version() == Some(MultiAgentVersion::V2)
&& !self.get_config().await.multi_agent_v2.disable_native_tools
{
{
let mut state = self.state.lock().await;
if state
.session_configuration
.session_source
.is_non_root_agent()
{
return Ok(());
}
state.pending_recorded_mail_sequence =
state.pending_recorded_mail_sequence.max(recorded_through);
}
self.maybe_start_turn_for_pending_work().await;
}
Ok(())
}
/// History injection can precede the first turn. Capture full initial context
/// only when the thread has no reference context, including after compaction.
pub(crate) async fn history_injection_context(
@@ -120,6 +189,7 @@ impl Session {
}
/// Applies client developer-message retention before queueing or recording items.
/// Returns the recorded history sequence, or zero for input queued into an active turn.
#[expect(
clippy::await_holding_invalid_type,
reason = "active turn checks and turn state updates must remain atomic"
@@ -128,7 +198,7 @@ impl Session {
&self,
items: Vec<impl Into<ResponseItemEnvelope>>,
turn_context: &TurnContext,
) {
) -> u64 {
let items = items
.into_iter()
.map(Into::into)
@@ -145,7 +215,7 @@ impl Session {
.collect(),
)
.await;
return;
return 0;
}
let finishing = active.as_ref().and_then(|turn| turn.finishing.clone());
drop(active);
@@ -153,7 +223,7 @@ impl Session {
finishing.cancelled().await;
}
self.record_annotated_conversation_items(turn_context, turn_context.model_info(), items)
.await;
.await
}
pub(crate) fn annotate_client_response_item(
@@ -183,7 +253,7 @@ impl Session {
turn_context: &TurnContext,
model_info: &ModelInfo,
items: Vec<ResponseItemEnvelope>,
) {
) -> u64 {
let (annotated_items, image_preparations) = self
.prepare_conversation_items_for_history(turn_context, model_info, items)
.await;
@@ -193,7 +263,7 @@ impl Session {
annotated_items,
image_preparations,
)
.await;
.await
}
pub(crate) async fn record_realtime_session_chunk(
@@ -214,6 +284,7 @@ impl Session {
Some(RealtimeRecord::Chunk),
)
.await
.map(|_| ())
}
/// Injects items into active work, or records them without starting a turn.
+17 -12
View File
@@ -4099,17 +4099,17 @@ impl Session {
model_info: &ModelInfo,
items: Vec<ResponseItemEnvelope>,
image_preparations: Vec<ImagePreparationMetadata>,
) {
) -> u64 {
// Ordinary history persistence retains its existing best-effort behavior.
let _ = self
.record_prepared_items(
turn_context,
model_info,
items,
image_preparations,
/*realtime*/ None,
)
.await;
self.record_prepared_items(
turn_context,
model_info,
items,
image_preparations,
/*realtime*/ None,
)
.await
.unwrap_or_default()
}
#[expect(
@@ -4123,7 +4123,7 @@ impl Session {
mut items: Vec<ResponseItemEnvelope>,
image_preparations: Vec<ImagePreparationMetadata>,
realtime: Option<RealtimeRecord<'_>>,
) -> std::io::Result<()> {
) -> std::io::Result<u64> {
// Save the originating history budget for replay.
// Preserve any existing tool-specific override.
let policy: codex_utils_output_truncation::TruncationPolicy =
@@ -4254,6 +4254,11 @@ impl Session {
.current_time_reminder
.note_recorded_items(&response_items);
}
let recorded_through = items
.iter()
.filter_map(|item| item.metadata.as_ref()?.history_sequence)
.max()
.unwrap_or_default();
for image in image_preparations {
self.services
.analytics_events_client
@@ -4297,7 +4302,7 @@ impl Session {
}
self.send_raw_response_items(turn_context, &response_items)
.await;
Ok(())
Ok(recorded_through)
}
pub(crate) async fn record_step_world_state_if_changed(
+12
View File
@@ -900,6 +900,7 @@ impl Session {
let mut state = self.state.lock().await;
state.last_started_turn_id = Some(turn_id.to_owned());
if let Some(attribution) = attribution {
state.pending_recorded_mail_sequence = 0;
state.turn_attribution = Some(attribution);
}
}
@@ -913,6 +914,17 @@ impl Session {
if active_turn.is_some() || self.turn_starts_closed() {
return None;
}
if !self.input_queue.has_pending_mailbox_items().await {
let mut state = self.state.lock().await;
// An intervening turn may already have sampled the durable injection.
if state.pending_recorded_mail_sequence == 0
|| state.pending_recorded_mail_sequence
<= crate::context_manager::sampled_through(state.history.annotated_items())
{
state.pending_recorded_mail_sequence = 0;
return None;
}
}
let has_trigger_turn = self.input_queue.has_trigger_turn_mailbox_items().await;
if !has_trigger_turn
&& !self.has_outstanding_durable_sleep()