Persist realtime events in the thread timeline (#40508)

## Why

Clients need a bounded view of realtime conversations that preserves the order of speech, agent work, and turn lifecycle events without loading the full thread history.

## What changed

- Persist realtime session boundaries, transcript segments, and promoted agent items in paginated thread rollouts.
- Add the experimental `thread/timeline/list` API to page ordinary items, realtime items, and turn boundaries in canonical rollout order. Include `activeRealtimeSessionAtPageStart` so each page can be rendered independently.
- Emit typed `thread/realtime/item/started`, `thread/realtime/item/transcript/delta`, and `thread/realtime/item/completed` notifications around durable realtime items.
- Keep the existing `thread/items/list` response and legacy thread history behavior unchanged.

## Testing

- Cover mixed timeline pagination, realtime-session state at page boundaries, rollout replay, subagent history prefixes, transcript streaming, steering, and promoted agent artifacts.

GitOrigin-RevId: faa2c420192d63e060e8fb32446e3c797422656e
This commit is contained in:
guinness-oai authored and copyberry committed 2026-08-25 01:03:20 +00:00
1 parent 80e871309a
commit 41ca88e95c
80 files changed
+5140 -47

No files matched your search

@@ -1,8 +1,12 @@
use super::*;
use crate::extensions::send_thread_warning;
use crate::realtime_event_handling::apply_realtime_event_effects;
use crate::realtime_event_handling::persist_realtime_items;
use crate::realtime_history::RealtimeEventEffects;
use codex_app_server_protocol::ThreadQueueChangedNotification;
use codex_extension_api::ThreadIdleCause;
use codex_protocol::config_types::MultiAgentMode;
use codex_protocol::protocol::ThreadHistoryMode;
pub(super) const THREAD_UNLOADING_DELAY: Duration = Duration::from_secs(30 * 60);
@@ -242,8 +246,10 @@ pub(super) async fn ensure_listener_task_running(
&environments,
)
.await;
let thread_settings_baseline =
thread_settings_from_config_snapshot(&conversation.config_snapshot().await);
let config_snapshot = conversation.config_snapshot().await;
let realtime_history_enabled =
matches!(config_snapshot.history_mode, ThreadHistoryMode::Paginated);
let thread_settings_baseline = thread_settings_from_config_snapshot(&config_snapshot);
let (mut listener_command_rx, listener_generation) = {
let mut thread_state = thread_state.lock().await;
if thread_state.listener_matches(&conversation) {
@@ -325,10 +331,20 @@ 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 (raw_events_enabled, realtime_effects) = {
let mut thread_state = thread_state.lock().await;
thread_state.track_current_turn_event(&event.id, &event.msg);
thread_state.experimental_raw_events
let realtime_effects = if realtime_history_enabled
&& thread_state.realtime_history.should_observe(&event.msg)
{
let active_turn_id = thread_state.active_turn_snapshot().map(|turn| turn.id);
thread_state
.realtime_history
.observe(&event.msg, active_turn_id.as_deref())
} else {
RealtimeEventEffects::default()
};
(thread_state.experimental_raw_events, realtime_effects)
};
if matches!(
&event.msg,
@@ -346,6 +362,14 @@ pub(super) async fn ensure_listener_task_running(
conversation_id,
);
apply_realtime_event_effects(
conversation.as_ref(),
&thread_outgoing,
conversation_id,
realtime_effects,
)
.await;
apply_bespoke_event_handling(
event.clone(),
conversation_id,
@@ -558,6 +582,32 @@ pub(super) async fn handle_thread_listener_command(
.await;
let _ = completion_tx.send(());
}
ThreadListenerCommand::SealRealtimeUserInput {
input,
completion_tx,
} => {
let items = thread_state
.lock()
.await
.realtime_history
.seal_user_input(&input);
let subscribed_connection_ids = thread_state_manager
.subscribed_connection_ids(conversation_id)
.await;
let thread_outgoing = ThreadScopedOutgoingMessageSender::new(
outgoing.clone(),
subscribed_connection_ids,
conversation_id,
);
let result = persist_realtime_items(
conversation.as_ref(),
&thread_outgoing,
&conversation_id.to_string(),
items,
)
.await;
let _ = completion_tx.send(result);
}
}
}
@@ -870,6 +870,35 @@ impl ThreadRequestProcessor {
.map(|response| Some(response.into()))
}
pub(crate) async fn thread_timeline_list(
&self,
params: ThreadTimelineListParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let thread_id = ThreadId::from_string(&params.thread_id)
.map_err(|error| invalid_request(format!("invalid thread id: {error}")))?;
let page = self
.thread_store
.list_timeline(StoreListTimelineParams {
thread_id,
cursor: params.cursor,
page_size: params
.limit
.map(|limit| limit as usize)
.unwrap_or(THREAD_ITEMS_DEFAULT_LIMIT)
.clamp(1, THREAD_ITEMS_MAX_LIMIT),
})
.await
.map_err(paginated_history_list_error)?;
Ok(Some(
ThreadTimelineListResponse {
data: page.items,
next_cursor: page.next_cursor,
active_realtime_session_at_page_start: page.active_realtime_session_at_page_start,
}
.into(),
))
}
pub(crate) async fn thread_shell_command(
&self,
request_id: &ConnectionRequestId,
@@ -528,6 +528,9 @@ impl TurnRequestProcessor {
},
)
.await?;
self.seal_realtime_transcript_before_user_input(thread_id, &mapped_items)
.await?;
let submission = thread
.start_or_steer_turn(
TurnInputRequest::new(TurnInput::UserInput {
@@ -901,12 +904,12 @@ impl TurnRequestProcessor {
request_id: &ConnectionRequestId,
params: TurnSteerParams,
) -> Result<TurnSteerResponse, JSONRPCErrorError> {
let (_, thread) = self
.load_thread(&params.thread_id)
.await
.inspect_err(|error| {
self.track_error_response(request_id, error, /*error_type*/ None);
})?;
let (thread_id, thread) =
self.load_thread(&params.thread_id)
.await
.inspect_err(|error| {
self.track_error_response(request_id, error, /*error_type*/ None);
})?;
self.ensure_direct_input_allowed(request_id, thread.as_ref())
.await?;
@@ -932,6 +935,9 @@ impl TurnRequestProcessor {
.collect();
let additional_context = map_additional_context(params.additional_context);
self.seal_realtime_transcript_before_user_input(thread_id, &mapped_items)
.await?;
let submission = thread
.steer_turn(
TurnInputRequest::new(TurnInput::UserInput {
@@ -1027,6 +1033,37 @@ impl TurnRequestProcessor {
Ok(TurnSteerResponse { turn_id })
}
async fn seal_realtime_transcript_before_user_input(
&self,
thread_id: ThreadId,
input: &[CoreInputItem],
) -> Result<(), JSONRPCErrorError> {
let thread_state = self.thread_state_manager.thread_state(thread_id).await;
if !thread_state
.lock()
.await
.realtime_history
.should_seal_user_input(input)
{
return Ok(());
}
let listener = self
.thread_state_manager
.current_listener_command_tx(thread_id)
.ok_or_else(|| internal_error("thread listener is not running"))?;
let (completion_tx, completion_rx) = tokio::sync::oneshot::channel();
listener
.send(ThreadListenerCommand::SealRealtimeUserInput {
input: input.to_vec(),
completion_tx,
})
.map_err(|_| internal_error("thread listener is not running"))?;
completion_rx
.await
.map_err(|_| internal_error("thread listener stopped before sealing realtime input"))?
.map_err(internal_error)
}
async fn prepare_realtime_conversation_thread(
&self,
request_id: &ConnectionRequestId,