diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index f131e3fc00..38ba81be84 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -135,33 +135,6 @@ struct CommandExecutionCompletionItem { command_actions: Vec, } -#[allow(clippy::too_many_arguments)] -pub(crate) async fn apply_bespoke_event_handling( - event: Event, - conversation_id: ThreadId, - conversation: Arc, - thread_manager: Arc, - outgoing: ThreadScopedOutgoingMessageSender, - thread_state: Arc>, - thread_watch_manager: ThreadWatchManager, - thread_list_state_permit: Arc, - 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, @@ -2458,7 +2431,7 @@ mod tests { impl GuardianAssessmentTestContext { async fn apply_guardian_assessment_event(&self, assessment: GuardianAssessmentEvent) { let event_turn_id = assessment.turn_id.clone(); - apply_bespoke_event_handling( + apply_bespoke_event_handling_with_item_lifecycle_outgoing( Event { id: event_turn_id, msg: EventMsg::GuardianAssessment(assessment), @@ -2471,6 +2444,7 @@ mod tests { self.thread_watch_manager.clone(), Arc::new(tokio::sync::Semaphore::new(/*permits*/ 1)), "test-provider".to_string(), + /*item_lifecycle_outgoing*/ None, ) .await; } @@ -3411,7 +3385,7 @@ mod tests { conversation_id, ); - apply_bespoke_event_handling( + apply_bespoke_event_handling_with_item_lifecycle_outgoing( Event { id: "turn-1".to_string(), msg: EventMsg::TurnStarted(codex_protocol::protocol::TurnStartedEvent { @@ -3430,6 +3404,7 @@ mod tests { thread_watch_manager, Arc::new(tokio::sync::Semaphore::new(/*permits*/ 1)), "test-provider".to_string(), + /*item_lifecycle_outgoing*/ None, ) .await; @@ -3480,7 +3455,7 @@ mod tests { conversation_id, ); - apply_bespoke_event_handling( + apply_bespoke_event_handling_with_item_lifecycle_outgoing( Event { id: "turn-1".to_string(), msg: EventMsg::SubAgentActivity(SubAgentActivityEvent { @@ -3500,6 +3475,7 @@ mod tests { thread_watch_manager.clone(), Arc::new(tokio::sync::Semaphore::new(/*permits*/ 1)), "test-provider".to_string(), + /*item_lifecycle_outgoing*/ None, ) .await; diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs index a2d425f0a2..a31756df91 100644 --- a/codex-rs/app-server/src/request_processors.rs +++ b/codex-rs/app-server/src/request_processors.rs @@ -1,4 +1,3 @@ -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; diff --git a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs index 7721cb5514..e3ef2e6de7 100644 --- a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs +++ b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs @@ -311,18 +311,6 @@ pub(super) async fn ensure_listener_task_running( listener_generation, ) }; - let ListenerTaskContext { - outgoing, - thread_manager, - thread_state_manager, - pending_thread_unloads, - thread_watch_manager, - thread_list_state_permit, - fallback_model_provider, - codex_home, - .. - } = 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(); @@ -336,15 +324,8 @@ pub(super) async fn ensure_listener_task_running( let transition = handle_thread_listener_command( conversation_id, &conversation, - codex_home.as_path(), - &thread_manager, - &thread_state_manager, + &listener_task_context, &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, @@ -375,15 +356,8 @@ pub(super) async fn ensure_listener_task_running( let transition = handle_thread_listener_command( conversation_id, &conversation, - codex_home.as_path(), - &thread_manager, - &thread_state_manager, + &listener_task_context, &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, @@ -422,19 +396,16 @@ pub(super) async fn ensure_listener_task_running( let raw_events_enabled = track_thread_event(&thread_state, &event).await; - let subscribed_connection_ids = thread_state_manager + let subscribed_connection_ids = listener_task_context + .thread_state_manager .subscribed_connection_ids(conversation_id) .await; dispatch_thread_event( event, conversation_id, &conversation, - &thread_manager, + &listener_task_context, &thread_state, - &thread_watch_manager, - &thread_list_state_permit, - &fallback_model_provider, - &outgoing_for_task, subscribed_connection_ids, /*item_lifecycle_connection_ids*/ None, raw_events_enabled, @@ -453,7 +424,10 @@ pub(super) async fn ensure_listener_task_running( continue; } { - let mut pending_thread_unloads = pending_thread_unloads.lock().await; + let mut pending_thread_unloads = listener_task_context + .pending_thread_unloads + .lock() + .await; if pending_thread_unloads.contains(&conversation_id) { continue; } @@ -463,11 +437,11 @@ pub(super) async fn ensure_listener_task_running( pending_thread_unloads.insert(conversation_id); } unload_thread_without_subscribers( - thread_manager.clone(), - outgoing_for_task.clone(), - pending_thread_unloads.clone(), - thread_state_manager.clone(), - thread_watch_manager.clone(), + Arc::clone(&listener_task_context.thread_manager), + Arc::clone(&listener_task_context.outgoing), + Arc::clone(&listener_task_context.pending_thread_unloads), + listener_task_context.thread_state_manager.clone(), + listener_task_context.thread_watch_manager.clone(), conversation_id, conversation.clone(), ) @@ -481,7 +455,9 @@ pub(super) async fn ensure_listener_task_running( let mut thread_state = thread_state.lock().await; if thread_state.listener_generation == listener_generation { - thread_state_manager.unregister_listener_command_tx(conversation_id); + listener_task_context + .thread_state_manager + .unregister_listener_command_tx(conversation_id); thread_state.clear_listener(); } }); @@ -501,16 +477,20 @@ async fn dispatch_thread_event( event: Event, conversation_id: ThreadId, conversation: &Arc, - thread_manager: &Arc, + listener_task_context: &ListenerTaskContext, thread_state: &Arc>, - thread_watch_manager: &ThreadWatchManager, - thread_list_state_permit: &Arc, - fallback_model_provider: &str, - outgoing: &Arc, subscribed_connection_ids: Vec, item_lifecycle_connection_ids: Option>, raw_events_enabled: bool, ) { + let ListenerTaskContext { + outgoing, + thread_manager, + thread_watch_manager, + thread_list_state_permit, + fallback_model_provider, + .. + } = listener_task_context; let thread_outgoing = ThreadScopedOutgoingMessageSender::new( Arc::clone(outgoing), subscribed_connection_ids, @@ -537,34 +517,19 @@ async fn dispatch_thread_event( 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; - } + 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(), + item_lifecycle_outgoing, + ) + .await; } #[path = "thread_lifecycle/resume_event_coverage.rs"] diff --git a/codex-rs/app-server/src/request_processors/thread_lifecycle/resume_event_dispatch.rs b/codex-rs/app-server/src/request_processors/thread_lifecycle/resume_event_dispatch.rs index 6469e8e911..d8878b34db 100644 --- a/codex-rs/app-server/src/request_processors/thread_lifecycle/resume_event_dispatch.rs +++ b/codex-rs/app-server/src/request_processors/thread_lifecycle/resume_event_dispatch.rs @@ -121,13 +121,9 @@ pub(super) async fn dispatch_buffered_thread_events( resumed_connection_id: Option, conversation_id: ThreadId, conversation: &Arc, - thread_manager: &Arc, + listener_task_context: &ListenerTaskContext, thread_state: &Arc>, - thread_watch_manager: &ThreadWatchManager, - thread_list_state_permit: &Arc, - fallback_model_provider: &str, resume_payload_mode: ResumePayloadMode, - outgoing: &Arc, ) { for buffered in buffered_events { // Preserve normal listener semantics: every event mutates the live tracker immediately @@ -149,7 +145,7 @@ pub(super) async fn dispatch_buffered_thread_events( ); if !typed_hook_recipients.is_empty() { let typed_outgoing = ThreadScopedOutgoingMessageSender::new( - Arc::clone(outgoing), + Arc::clone(&listener_task_context.outgoing), typed_hook_recipients, conversation_id, ); @@ -163,7 +159,7 @@ pub(super) async fn dispatch_buffered_thread_events( } if !raw_recipients.is_empty() { let raw_outgoing = ThreadScopedOutgoingMessageSender::new( - Arc::clone(outgoing), + Arc::clone(&listener_task_context.outgoing), raw_recipients, conversation_id, ); @@ -193,12 +189,8 @@ pub(super) async fn dispatch_buffered_thread_events( buffered.event, conversation_id, conversation, - thread_manager, + listener_task_context, thread_state, - thread_watch_manager, - thread_list_state_permit, - fallback_model_provider, - outgoing, recipients, item_lifecycle_recipients, raw_events_enabled, diff --git a/codex-rs/app-server/src/request_processors/thread_lifecycle/resume_response.rs b/codex-rs/app-server/src/request_processors/thread_lifecycle/resume_response.rs index 7c0f6c49f3..97a58ea63b 100644 --- a/codex-rs/app-server/src/request_processors/thread_lifecycle/resume_response.rs +++ b/codex-rs/app-server/src/request_processors/thread_lifecycle/resume_response.rs @@ -10,21 +10,21 @@ use super::*; pub(super) async fn handle_pending_thread_resume_request( conversation_id: ThreadId, conversation: &Arc, - _codex_home: &Path, - thread_manager: &Arc, - thread_state_manager: &ThreadStateManager, + listener_task_context: &ListenerTaskContext, thread_state: &Arc>, - thread_watch_manager: &ThreadWatchManager, - thread_list_state_permit: &Arc, - fallback_model_provider: &str, - outgoing: &Arc, - pending_thread_unloads: &Arc>>, pending: crate::thread_state::PendingThreadResumeRequest, history_result: Result, mut buffered_events: Vec, mut exec_delta_replay: ResumeExecDeltaReplay, release_event_cut_tx: oneshot::Sender<()>, ) { + let ListenerTaskContext { + thread_state_manager, + outgoing, + pending_thread_unloads, + thread_watch_manager, + .. + } = listener_task_context; let pre_cut_connection_ids = thread_state_manager .subscribed_connection_ids(conversation_id) .await; @@ -52,13 +52,9 @@ pub(super) async fn handle_pending_thread_resume_request( None, conversation_id, conversation, - thread_manager, + listener_task_context, thread_state, - thread_watch_manager, - thread_list_state_permit, - fallback_model_provider, ResumePayloadMode::Full, - outgoing, ) .await; return; @@ -75,12 +71,8 @@ pub(super) async fn handle_pending_thread_resume_request( event, conversation_id, conversation, - thread_manager, + listener_task_context, 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, @@ -105,13 +97,9 @@ pub(super) async fn handle_pending_thread_resume_request( None, conversation_id, conversation, - thread_manager, + listener_task_context, thread_state, - thread_watch_manager, - thread_list_state_permit, - fallback_model_provider, ResumePayloadMode::Full, - outgoing, ) .await; return; @@ -199,13 +187,9 @@ pub(super) async fn handle_pending_thread_resume_request( None, conversation_id, conversation, - thread_manager, + listener_task_context, thread_state, - thread_watch_manager, - thread_list_state_permit, - fallback_model_provider, ResumePayloadMode::Full, - outgoing, ) .await; return; @@ -277,13 +261,9 @@ pub(super) async fn handle_pending_thread_resume_request( None, conversation_id, conversation, - thread_manager, + listener_task_context, thread_state, - thread_watch_manager, - thread_list_state_permit, - fallback_model_provider, ResumePayloadMode::Full, - outgoing, ) .await; return; @@ -305,13 +285,9 @@ pub(super) async fn handle_pending_thread_resume_request( None, conversation_id, conversation, - thread_manager, + listener_task_context, thread_state, - thread_watch_manager, - thread_list_state_permit, - fallback_model_provider, ResumePayloadMode::Full, - outgoing, ) .await; return; @@ -340,13 +316,9 @@ pub(super) async fn handle_pending_thread_resume_request( None, conversation_id, conversation, - thread_manager, + listener_task_context, thread_state, - thread_watch_manager, - thread_list_state_permit, - fallback_model_provider, ResumePayloadMode::Full, - outgoing, ) .await; return; @@ -418,13 +390,9 @@ pub(super) async fn handle_pending_thread_resume_request( Some(connection_id), conversation_id, conversation, - thread_manager, + listener_task_context, 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 diff --git a/codex-rs/app-server/src/request_processors/thread_lifecycle/resume_worker.rs b/codex-rs/app-server/src/request_processors/thread_lifecycle/resume_worker.rs index d99c724613..e9e323a5be 100644 --- a/codex-rs/app-server/src/request_processors/thread_lifecycle/resume_worker.rs +++ b/codex-rs/app-server/src/request_processors/thread_lifecycle/resume_worker.rs @@ -151,15 +151,8 @@ pub(super) fn classify_busy_history_read( pub(super) async fn handle_thread_listener_command( conversation_id: ThreadId, conversation: &Arc, - codex_home: &Path, - thread_manager: &Arc, - thread_state_manager: &ThreadStateManager, + listener_task_context: &ListenerTaskContext, thread_state: &Arc>, - thread_watch_manager: &ThreadWatchManager, - thread_list_state_permit: &Arc, - fallback_model_provider: &str, - outgoing: &Arc, - pending_thread_unloads: &Arc>>, listener_command_tx: &mpsc::UnboundedSender, resume_worker_cancel: &CancellationToken, buffered_resume_events: &mut Vec, @@ -177,7 +170,7 @@ pub(super) async fn handle_thread_listener_command( conversation_id, conversation, thread_state, - outgoing, + &listener_task_context.outgoing, listener_command_tx, resume_worker_cancel, resume_request, @@ -199,15 +192,8 @@ pub(super) async fn handle_thread_listener_command( handle_pending_thread_resume_request( conversation_id, conversation, - codex_home, - thread_manager, - thread_state_manager, + listener_task_context, 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), @@ -219,7 +205,8 @@ pub(super) async fn handle_thread_listener_command( ListenerCommandTransition::ResumeFinished } ThreadListenerCommand::EmitThreadGoalUpdated { turn_id, goal } => { - outgoing + listener_task_context + .outgoing .send_server_notification(ServerNotification::ThreadGoalUpdated( ThreadGoalUpdatedNotification { thread_id: conversation_id.to_string(), @@ -231,7 +218,8 @@ pub(super) async fn handle_thread_listener_command( ListenerCommandTransition::None } ThreadListenerCommand::EmitThreadGoalCleared => { - outgoing + listener_task_context + .outgoing .send_server_notification(ServerNotification::ThreadGoalCleared( ThreadGoalClearedNotification { thread_id: conversation_id.to_string(), @@ -241,7 +229,12 @@ pub(super) async fn handle_thread_listener_command( ListenerCommandTransition::None } ThreadListenerCommand::EmitThreadGoalSnapshot { state_db } => { - send_thread_goal_snapshot_notification(outgoing, conversation_id, &state_db).await; + send_thread_goal_snapshot_notification( + &listener_task_context.outgoing, + conversation_id, + &state_db, + ) + .await; ListenerCommandTransition::None } ThreadListenerCommand::ResolveServerRequest { @@ -250,8 +243,8 @@ pub(super) async fn handle_thread_listener_command( } => { resolve_pending_server_request( conversation_id, - thread_state_manager, - outgoing, + &listener_task_context.thread_state_manager, + &listener_task_context.outgoing, request_id, ) .await; @@ -321,20 +314,21 @@ pub(super) async fn read_pending_thread_resume_history( ) -> Result { 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 snapshot = conversation.history_reconciliation_snapshot().await; + // 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 Some(snapshot) = snapshot else { let thread_became_idle = conversation .history_reconciliation_snapshot() .await @@ -353,16 +347,6 @@ pub(super) async fn read_pending_thread_resume_history( } 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; diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index 59068111aa..9b8214bf0d 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -3,8 +3,7 @@ use crate::config::ConstraintResult; use crate::session::Codex; use crate::session::SessionSettingsUpdate; use crate::session::SteerInputError; -use crate::state::PersistedHistoryCursor; -use crate::state::PersistedHistoryCursorUncertainty; +use crate::state::PersistedHistoryCursorState; use codex_features::Feature; use codex_otel::SessionTelemetry; use codex_protocol::ThreadId; @@ -104,9 +103,7 @@ pub struct ThreadHistoryReconciliationSnapshot { pub(crate) history: Vec, pub(crate) history_version: u64, pub(crate) known_persisted_incomplete_tail: Option, - pub(crate) known_persisted_history_cursor: Option, - pub(crate) persisted_history_cursor_uncertainty: Option, - pub(crate) uncertain_expected_persisted_history_cursor: Option, + pub(crate) persisted_history_cursor: PersistedHistoryCursorState, } /// Result of reconciling a loaded thread with its persisted rollout history. diff --git a/codex-rs/core/src/session/history_reconciliation.rs b/codex-rs/core/src/session/history_reconciliation.rs index 7cae61650d..6757086df1 100644 --- a/codex-rs/core/src/session/history_reconciliation.rs +++ b/codex-rs/core/src/session/history_reconciliation.rs @@ -19,6 +19,7 @@ use crate::codex_thread::ThreadHistoryReconciliationOutcome; use crate::codex_thread::ThreadHistoryReconciliationSnapshot; use crate::context_manager::ContextManager; use crate::image_preparation::prepare_response_items; +use crate::state::PersistedHistoryCursorState; use crate::state::PersistedHistoryCursorUncertainty; use codex_app_server_protocol::ThreadHistoryBuilder; use codex_app_server_protocol::TurnStatus; @@ -76,16 +77,23 @@ impl Session { items: &[RolloutItem], ) { let mut state = self.state.lock().await; - if let Some(cursor) = state.known_persisted_history_cursor() { - state.set_known_persisted_history_cursor(advance_persisted_history_cursor( - cursor, items, - )); - } else if state.persisted_history_cursor_uncertainty().is_some() { - let expected_cursor = state - .uncertain_expected_persisted_history_cursor() - .and_then(|cursor| advance_persisted_history_cursor(cursor, items)); - state.set_uncertain_expected_persisted_history_cursor(expected_cursor); - } + state.persisted_history_cursor = match state.persisted_history_cursor { + PersistedHistoryCursorState::Known(cursor) => { + advance_persisted_history_cursor(cursor, items).map_or( + PersistedHistoryCursorState::Unknown, + PersistedHistoryCursorState::Known, + ) + } + PersistedHistoryCursorState::Uncertain { + uncertainty, + expected, + } => PersistedHistoryCursorState::Uncertain { + uncertainty, + expected: expected + .and_then(|cursor| advance_persisted_history_cursor(cursor, items)), + }, + PersistedHistoryCursorState::Unknown => PersistedHistoryCursorState::Unknown, + }; } pub(crate) async fn invalidate_persisted_item_cursor( @@ -93,17 +101,29 @@ impl Session { _rollout_guard: &tokio::sync::OwnedMutexGuard<()>, items: &[RolloutItem], ) { - let uncertainty = if items.iter().any(is_persisted_history_rewrite_item) { + let mut state = self.state.lock().await; + let expected = match state.persisted_history_cursor { + PersistedHistoryCursorState::Known(cursor) => Some(cursor), + PersistedHistoryCursorState::Uncertain { expected, .. } => expected, + PersistedHistoryCursorState::Unknown => None, + } + .and_then(|cursor| advance_persisted_history_cursor(cursor, items)); + let uncertainty = if items.iter().any(is_persisted_history_rewrite_item) + || matches!( + state.persisted_history_cursor, + PersistedHistoryCursorState::Uncertain { + uncertainty: PersistedHistoryCursorUncertainty::HistoryRewrite, + .. + } + ) { PersistedHistoryCursorUncertainty::HistoryRewrite } else { PersistedHistoryCursorUncertainty::AppendOnly }; - let mut state = self.state.lock().await; - let expected_cursor = state - .known_persisted_history_cursor() - .or_else(|| state.uncertain_expected_persisted_history_cursor()) - .and_then(|cursor| advance_persisted_history_cursor(cursor, items)); - state.invalidate_persisted_item_cursor(uncertainty, expected_cursor); + state.persisted_history_cursor = PersistedHistoryCursorState::Uncertain { + uncertainty, + expected, + }; } #[expect( @@ -122,10 +142,7 @@ impl Session { history: state.history.raw_items().to_vec(), history_version: state.history.history_version(), known_persisted_incomplete_tail: state.known_persisted_incomplete_tail(), - known_persisted_history_cursor: state.known_persisted_history_cursor(), - persisted_history_cursor_uncertainty: state.persisted_history_cursor_uncertainty(), - uncertain_expected_persisted_history_cursor: state - .uncertain_expected_persisted_history_cursor(), + persisted_history_cursor: state.persisted_history_cursor, }) } @@ -148,31 +165,28 @@ impl Session { // Incremental replay is safe only when the loaded rollout still has the exact known // non-metadata prefix. A mismatch means another writer interleaved before a local append, // so fall back to canonical reconstruction instead of duplicating already-applied items. - let requires_uncertain_cursor_proof = snapshot.known_persisted_history_cursor.is_none() - && snapshot.persisted_history_cursor_uncertainty.is_some() - && snapshot - .uncertain_expected_persisted_history_cursor - .is_some(); - let reconciliation_cursor = match snapshot.known_persisted_history_cursor { - Some(cursor) => Some(cursor), - None if snapshot.persisted_history_cursor_uncertainty.is_some() => { - if let Some(expected_cursor) = snapshot.uncertain_expected_persisted_history_cursor - { - Some(expected_cursor) - } else if matches!( - snapshot.persisted_history_cursor_uncertainty, - Some(PersistedHistoryCursorUncertainty::HistoryRewrite) - ) { + let (reconciliation_cursor, requires_uncertain_cursor_proof) = + match snapshot.persisted_history_cursor { + PersistedHistoryCursorState::Known(cursor) => (Some(cursor), false), + PersistedHistoryCursorState::Uncertain { + expected: Some(expected), + .. + } => (Some(expected), true), + PersistedHistoryCursorState::Uncertain { + uncertainty: PersistedHistoryCursorUncertainty::HistoryRewrite, + expected: None, + } => { // Without a pre-failure cursor, model-history equality cannot prove that an // event-only rollback or compaction marker became durable. Restart is the // recovery boundary for this deliberately fail-closed state. return ThreadHistoryReconciliationOutcome::Conflict; - } else { - None } - } - None => None, - }; + PersistedHistoryCursorState::Uncertain { + uncertainty: PersistedHistoryCursorUncertainty::AppendOnly, + expected: None, + } + | PersistedHistoryCursorState::Unknown => (None, false), + }; let persisted_suffix = match reconciliation_cursor { Some(cursor) => match persisted_suffix_after_cursor(rollout_items, cursor) { PersistedCursorComparison::Matched(suffix) => Some(suffix), @@ -195,15 +209,12 @@ impl Session { .iter() .any(|item| matches!(item, RolloutItem::Compacted(_))) }); - let imports_history_rewrite = persisted_suffix.is_some_and(|suffix| { - suffix.iter().any(|item| { - matches!( - item, - RolloutItem::Compacted(_) - | RolloutItem::EventMsg(EventMsg::ThreadRolledBack(_)) - ) - }) + let imports_rollback = persisted_suffix.is_some_and(|suffix| { + suffix + .iter() + .any(|item| matches!(item, RolloutItem::EventMsg(EventMsg::ThreadRolledBack(_)))) }); + let imports_history_rewrite = imports_compaction || imports_rollback; let reconciliation_config = self.history_reconciliation_config().await; let mut reconstruction = self @@ -223,29 +234,28 @@ impl Session { reconstruction.history = history; } let final_history_extends_snapshot = reconstruction.history.starts_with(&snapshot.history); - match snapshot.persisted_history_cursor_uncertainty { - Some(PersistedHistoryCursorUncertainty::AppendOnly) - if !uncertainty_proven_by_cursor && !final_history_extends_snapshot => - { - // An append error does not reveal whether storage accepted the item. Never let an - // older or divergent read replace authoritative in-memory history in that state. - // Exact cursor agreement proves that the ambiguous append landed; without it, - // only exact model-history matches and strict extensions provide that proof. - return ThreadHistoryReconciliationOutcome::Conflict; + if matches!( + snapshot.persisted_history_cursor, + PersistedHistoryCursorState::Uncertain { + uncertainty: PersistedHistoryCursorUncertainty::AppendOnly, + .. } - _ => {} + ) && !uncertainty_proven_by_cursor + && !final_history_extends_snapshot + { + // An append error does not reveal whether storage accepted the item. Never let an + // older or divergent read replace authoritative in-memory history in that state. + // Exact cursor agreement proves that the ambiguous append landed; without it, + // only exact model-history matches and strict extensions provide that proof. + return ThreadHistoryReconciliationOutcome::Conflict; } let imports_effective_rollback = persisted_suffix.map_or_else( || { rollout_items.iter().any(|item| { matches!(item, RolloutItem::EventMsg(EventMsg::ThreadRolledBack(_))) - }) && !reconstruction.history.starts_with(&snapshot.history) - }, - |suffix| { - suffix.iter().any(|item| { - matches!(item, RolloutItem::EventMsg(EventMsg::ThreadRolledBack(_))) - }) + }) && !final_history_extends_snapshot }, + |_| imports_rollback, ); let token_info = Self::last_token_info_from_rollout(rollout_items); let token_budget_reminder_delivered = @@ -260,11 +270,7 @@ impl Session { || state.history.raw_items() != snapshot.history || state.known_persisted_incomplete_tail().as_ref() != snapshot.known_persisted_incomplete_tail.as_ref() - || state.known_persisted_history_cursor() != snapshot.known_persisted_history_cursor - || state.persisted_history_cursor_uncertainty() - != snapshot.persisted_history_cursor_uncertainty - || state.uncertain_expected_persisted_history_cursor() - != snapshot.uncertain_expected_persisted_history_cursor + || state.persisted_history_cursor != snapshot.persisted_history_cursor { return ThreadHistoryReconciliationOutcome::Conflict; } @@ -305,7 +311,10 @@ impl Session { let preserves_append_only_prefill = final_history_extends_snapshot && !imports_history_rewrite && (persisted_suffix.is_some() - || snapshot.persisted_history_cursor_uncertainty.is_some()); + || matches!( + snapshot.persisted_history_cursor, + PersistedHistoryCursorState::Uncertain { .. } + )); let preserves_rollback_prefill = imports_effective_rollback && !imports_compaction && preserves_auto_compact_window; let preserve_auto_compact_prefill = @@ -342,9 +351,10 @@ impl Session { { state.reset_additional_context(); } - if snapshot.known_persisted_history_cursor.is_some() - || snapshot.persisted_history_cursor_uncertainty.is_some() - || self.live_thread().is_some() + if !matches!( + snapshot.persisted_history_cursor, + PersistedHistoryCursorState::Unknown + ) || self.live_thread().is_some() { state.set_known_persisted_history_cursor(persisted_history_cursor(rollout_items)); } diff --git a/codex-rs/core/src/session/history_reconciliation/cursor_recovery_tests.rs b/codex-rs/core/src/session/history_reconciliation/cursor_recovery_tests.rs index b7229a6545..cd1889cdb1 100644 --- a/codex-rs/core/src/session/history_reconciliation/cursor_recovery_tests.rs +++ b/codex-rs/core/src/session/history_reconciliation/cursor_recovery_tests.rs @@ -47,7 +47,6 @@ fn persisted_cursor_canonicalizes_nested_map_order_and_round_trip() { async fn persisted_cursor_does_not_advance_for_session_metadata_append() { let (session, _turn_context) = make_session_and_context().await; let prefix = completed_turn("turn-1", "first user", "first assistant"); - let cursor = persisted_history_cursor(&prefix); set_known_persisted_history(&session, &prefix).await; let rollout_guard = session.acquire_rollout_persistence_lock().await; @@ -56,35 +55,26 @@ async fn persisted_cursor_does_not_advance_for_session_metadata_append() { .await; assert_eq!( - session.state.lock().await.known_persisted_history_cursor(), - cursor + session.state.lock().await.persisted_history_cursor, + persisted_cursor_state(&prefix) ); } #[tokio::test] async fn failed_persisted_append_invalidates_cursor() { let (session, _turn_context) = make_session_and_context().await; - let prefix = completed_turn("turn-1", "first user", "first assistant"); - set_known_persisted_history(&session, &prefix).await; - invalidate_persisted_history_cursor( - &session, - &[RolloutItem::ResponseItem(assistant_message( - "ambiguous append", - ))], - ) - .await; + let mut expected_rollout = completed_turn("turn-1", "first user", "first assistant"); + set_known_persisted_history(&session, &expected_rollout).await; + let append = RolloutItem::ResponseItem(assistant_message("ambiguous append")); + invalidate_persisted_history_cursor(&session, std::slice::from_ref(&append)).await; + expected_rollout.push(append); assert_eq!( - session.state.lock().await.known_persisted_history_cursor(), - None - ); - assert_eq!( - session - .state - .lock() - .await - .persisted_history_cursor_uncertainty(), - Some(PersistedHistoryCursorUncertainty::AppendOnly) + session.state.lock().await.persisted_history_cursor, + PersistedHistoryCursorState::Uncertain { + uncertainty: PersistedHistoryCursorUncertainty::AppendOnly, + expected: persisted_history_cursor(&expected_rollout), + } ); } @@ -96,9 +86,7 @@ async fn persisted_cursor_uncertainty_only_upgrades_to_history_rewrite() { let rollout_guard = session.acquire_rollout_persistence_lock().await; let append = RolloutItem::ResponseItem(assistant_message("ambiguous append")); let successful_append = RolloutItem::ResponseItem(assistant_message("successful append")); - let rollback = RolloutItem::EventMsg(EventMsg::ThreadRolledBack(ThreadRolledBackEvent { - num_turns: 1, - })); + let rollback = rollback(/*num_turns*/ 1); session .invalidate_persisted_item_cursor(&rollout_guard, std::slice::from_ref(&append)) @@ -112,23 +100,14 @@ async fn persisted_cursor_uncertainty_only_upgrades_to_history_rewrite() { session .invalidate_persisted_item_cursor(&rollout_guard, std::slice::from_ref(&append)) .await; + expected_rollout.extend([append.clone(), successful_append, rollback, append]); assert_eq!( - session - .state - .lock() - .await - .persisted_history_cursor_uncertainty(), - Some(PersistedHistoryCursorUncertainty::HistoryRewrite) - ); - expected_rollout.extend([append.clone(), successful_append, rollback, append]); - assert_eq!( - session - .state - .lock() - .await - .uncertain_expected_persisted_history_cursor(), - persisted_history_cursor(&expected_rollout) + session.state.lock().await.persisted_history_cursor, + PersistedHistoryCursorState::Uncertain { + uncertainty: PersistedHistoryCursorUncertainty::HistoryRewrite, + expected: persisted_history_cursor(&expected_rollout), + } ); } @@ -141,20 +120,21 @@ async fn uncertain_persisted_cursor_never_replaces_valid_in_memory_tail() { local_history.push(local_tail.clone()); session.replace_history(local_history.clone(), None).await; set_known_persisted_history(&session, &persisted_prefix).await; - invalidate_persisted_history_cursor(&session, &[RolloutItem::ResponseItem(local_tail.clone())]) - .await; + let append = RolloutItem::ResponseItem(local_tail.clone()); + invalidate_persisted_history_cursor(&session, std::slice::from_ref(&append)).await; + let mut expected_uncertain_rollout = persisted_prefix.clone(); + expected_uncertain_rollout.push(append); let outcome = reconcile_idle(&session, &persisted_prefix).await; assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Conflict); assert_eq!(session.clone_history().await.raw_items(), local_history); assert_eq!( - session - .state - .lock() - .await - .persisted_history_cursor_uncertainty(), - Some(PersistedHistoryCursorUncertainty::AppendOnly) + session.state.lock().await.persisted_history_cursor, + PersistedHistoryCursorState::Uncertain { + uncertainty: PersistedHistoryCursorUncertainty::AppendOnly, + expected: persisted_history_cursor(&expected_uncertain_rollout), + } ); // If a later read proves the exact ambiguous append reached storage, reconciliation can @@ -162,14 +142,10 @@ async fn uncertain_persisted_cursor_never_replaces_valid_in_memory_tail() { persisted_prefix.push(RolloutItem::ResponseItem(local_tail)); let retry_outcome = reconcile_idle(&session, &persisted_prefix).await; assert_eq!(retry_outcome, ThreadHistoryReconciliationOutcome::Unchanged); - { - let state = session.state.lock().await; - assert_eq!( - state.known_persisted_history_cursor(), - persisted_history_cursor(&persisted_prefix) - ); - assert_eq!(state.persisted_history_cursor_uncertainty(), None); - } + assert_eq!( + session.state.lock().await.persisted_history_cursor, + persisted_cursor_state(&persisted_prefix) + ); let second_ambiguous_append = assistant_message("second ambiguous append"); let mut local_history_with_second_append = local_history.clone(); @@ -201,10 +177,9 @@ async fn uncertain_persisted_cursor_never_replaces_valid_in_memory_tail() { assert_eq!(session.clone_history().await.raw_items(), expected); let state = session.state.lock().await; assert_eq!( - state.known_persisted_history_cursor(), - persisted_history_cursor(&persisted_prefix) + state.persisted_history_cursor, + persisted_cursor_state(&persisted_prefix) ); - assert_eq!(state.persisted_history_cursor_uncertainty(), None); } #[tokio::test] @@ -228,10 +203,9 @@ async fn uncertain_append_proven_by_cursor_allows_persisted_rollback_suffix() { assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Refreshed); assert_eq!(session.clone_history().await.raw_items(), first_history); let state = session.state.lock().await; - assert_eq!(state.persisted_history_cursor_uncertainty(), None); assert_eq!( - state.known_persisted_history_cursor(), - persisted_history_cursor(&landed_rollout) + state.persisted_history_cursor, + persisted_cursor_state(&landed_rollout) ); } @@ -247,23 +221,22 @@ async fn uncertain_history_rewrite_never_restores_pre_rollback_disk_history() { set_known_persisted_history(&session, &pre_rollback_rollout).await; let rollback = rollback(/*num_turns*/ 1); invalidate_persisted_history_cursor(&session, std::slice::from_ref(&rollback)).await; + let mut expected_landed_rollout = pre_rollback_rollout.clone(); + expected_landed_rollout.push(rollback.clone()); let stale_outcome = reconcile_idle(&session, &pre_rollback_rollout).await; assert_eq!(stale_outcome, ThreadHistoryReconciliationOutcome::Conflict); assert_eq!(session.clone_history().await.raw_items(), first_history); assert_eq!( - session - .state - .lock() - .await - .persisted_history_cursor_uncertainty(), - Some(PersistedHistoryCursorUncertainty::HistoryRewrite) + session.state.lock().await.persisted_history_cursor, + PersistedHistoryCursorState::Uncertain { + uncertainty: PersistedHistoryCursorUncertainty::HistoryRewrite, + expected: persisted_history_cursor(&expected_landed_rollout), + } ); - let mut landed_rollout = pre_rollback_rollout; - landed_rollout.push(rollback); - let landed_outcome = reconcile_idle(&session, &landed_rollout).await; + let landed_outcome = reconcile_idle(&session, &expected_landed_rollout).await; assert_eq!( landed_outcome, @@ -271,10 +244,9 @@ async fn uncertain_history_rewrite_never_restores_pre_rollback_disk_history() { ); assert_eq!(session.clone_history().await.raw_items(), first_history); let state = session.state.lock().await; - assert_eq!(state.persisted_history_cursor_uncertainty(), None); assert_eq!( - state.known_persisted_history_cursor(), - persisted_history_cursor(&landed_rollout) + state.persisted_history_cursor, + persisted_cursor_state(&expected_landed_rollout) ); } @@ -297,12 +269,11 @@ async fn uncertain_event_only_rollback_requires_the_durable_marker() { { let state = session.state.lock().await; assert_eq!( - state.persisted_history_cursor_uncertainty(), - Some(PersistedHistoryCursorUncertainty::HistoryRewrite) - ); - assert_eq!( - state.uncertain_expected_persisted_history_cursor(), - persisted_history_cursor(&expected_landed_rollout) + state.persisted_history_cursor, + PersistedHistoryCursorState::Uncertain { + uncertainty: PersistedHistoryCursorUncertainty::HistoryRewrite, + expected: persisted_history_cursor(&expected_landed_rollout), + } ); } @@ -314,9 +285,8 @@ async fn uncertain_event_only_rollback_requires_the_durable_marker() { ); assert!(session.clone_history().await.raw_items().is_empty()); let state = session.state.lock().await; - assert_eq!(state.persisted_history_cursor_uncertainty(), None); assert_eq!( - state.known_persisted_history_cursor(), - persisted_history_cursor(&expected_landed_rollout) + state.persisted_history_cursor, + persisted_cursor_state(&expected_landed_rollout) ); } diff --git a/codex-rs/core/src/session/history_reconciliation/install.rs b/codex-rs/core/src/session/history_reconciliation/install.rs index ded4f92171..f198b1f173 100644 --- a/codex-rs/core/src/session/history_reconciliation/install.rs +++ b/codex-rs/core/src/session/history_reconciliation/install.rs @@ -77,23 +77,17 @@ impl Session { history, reference_context_item, ); - state - .history - .replace_world_state_baseline(world_state_baseline); } RolloutHistoryInstallMode::Replace => { state.replace_history(history, reference_context_item); - state - .history - .replace_world_state_baseline(world_state_baseline); } RolloutHistoryInstallMode::KeepExisting => { state.set_reference_context_item(reference_context_item); - state - .history - .replace_world_state_baseline(world_state_baseline); } } + state + .history + .replace_world_state_baseline(world_state_baseline); let ids = Self::rollout_reconstruction_window_ids( first_window_id, previous_window_id, diff --git a/codex-rs/core/src/session/history_reconciliation/window_state_tests.rs b/codex-rs/core/src/session/history_reconciliation/window_state_tests.rs index 71086ed8e7..208516e27c 100644 --- a/codex-rs/core/src/session/history_reconciliation/window_state_tests.rs +++ b/codex-rs/core/src/session/history_reconciliation/window_state_tests.rs @@ -62,9 +62,9 @@ async fn reconcile_persisted_history_resets_runtime_state_for_new_compaction_win assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Unchanged); let mut state = session.state.lock().await; - assert_ne!( + assert_eq!( state.auto_compact_window_snapshot().prefill_input_tokens, - Some(777) + None ); assert!(!state.take_new_context_window_request()); assert!(state.claim_token_budget_reminder()); @@ -108,20 +108,10 @@ async fn reconcile_persisted_history_queues_only_unconsumed_imported_compaction_ .lock() .await .take_pending_session_start_source(); - if followed_by_turn { - assert!( - pending_source.is_none(), - "a later turn already consumed the imported compact lifecycle hook" - ); - } else { - assert!( - matches!( - pending_source, - Some(codex_hooks::SessionStartSource::Compact) - ), - "an imported compaction must queue its next-turn lifecycle hook" - ); - } + assert_eq!( + pending_source.map(codex_hooks::SessionStartSource::as_str), + (!followed_by_turn).then_some("compact") + ); } } @@ -394,8 +384,8 @@ async fn reconcile_persisted_history_preserves_loaded_prefix_truncation() { "suffix reconciliation must preserve the prefill after restoring the loaded prefix" ); assert_eq!( - session.state.lock().await.known_persisted_history_cursor(), - persisted_history_cursor(&rollout) + session.state.lock().await.persisted_history_cursor, + persisted_cursor_state(&rollout) ); assert_eq!( session @@ -464,8 +454,8 @@ async fn reconcile_persisted_history_ignores_interleaved_session_metadata_in_cur )); assert_eq!(session.clone_history().await.raw_items(), expected); assert_eq!( - session.state.lock().await.known_persisted_history_cursor(), - persisted_history_cursor(&rollout) + session.state.lock().await.persisted_history_cursor, + persisted_cursor_state(&rollout) ); } @@ -501,7 +491,7 @@ async fn reconcile_persisted_history_rebuilds_after_external_append_interleaves_ expected.push(local_item); assert_eq!(session.clone_history().await.raw_items(), expected); assert_eq!( - session.state.lock().await.known_persisted_history_cursor(), - persisted_history_cursor(&actual_rollout) + session.state.lock().await.persisted_history_cursor, + persisted_cursor_state(&actual_rollout) ); } diff --git a/codex-rs/core/src/session/history_reconciliation_tests.rs b/codex-rs/core/src/session/history_reconciliation_tests.rs index 9e4ab345ed..63610930bb 100644 --- a/codex-rs/core/src/session/history_reconciliation_tests.rs +++ b/codex-rs/core/src/session/history_reconciliation_tests.rs @@ -9,6 +9,7 @@ use crate::context::ContextualUserFragment; use crate::context::TokenBudgetReminder; use crate::state::ActiveTurn; use crate::state::AutoCompactWindowIds; +use crate::state::PersistedHistoryCursorState; use crate::state::PersistedHistoryCursorUncertainty; use codex_features::Feature; use codex_protocol::models::ContentItem; @@ -128,21 +129,14 @@ fn local_shell_call(env: HashMap) -> RolloutItem { } fn token_usage_info(total_tokens: i64) -> TokenUsageInfo { + let usage = TokenUsage { + input_tokens: total_tokens, + total_tokens, + ..Default::default() + }; TokenUsageInfo { - total_token_usage: TokenUsage { - input_tokens: total_tokens, - cached_input_tokens: 0, - output_tokens: 0, - reasoning_output_tokens: 0, - total_tokens, - }, - last_token_usage: TokenUsage { - input_tokens: total_tokens, - cached_input_tokens: 0, - output_tokens: 0, - reasoning_output_tokens: 0, - total_tokens, - }, + total_token_usage: usage.clone(), + last_token_usage: usage, model_context_window: Some(258_400), } } @@ -166,6 +160,13 @@ async fn set_known_persisted_history(session: &Session, rollout: &[RolloutItem]) .set_known_persisted_history_cursor(persisted_history_cursor(rollout)); } +fn persisted_cursor_state(rollout: &[RolloutItem]) -> PersistedHistoryCursorState { + persisted_history_cursor(rollout).map_or( + PersistedHistoryCursorState::Unknown, + PersistedHistoryCursorState::Known, + ) +} + async fn invalidate_persisted_history_cursor(session: &Session, items: &[RolloutItem]) { let rollout_guard = session.acquire_rollout_persistence_lock().await; session diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 576c5cf1ab..2917ae7884 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -1376,13 +1376,6 @@ impl Session { .await; } - // Seed usage info from the recorded rollout so UIs can show token counts - // immediately on resume/fork. - if let Some(info) = Self::last_token_info_from_rollout(&rollout_items) { - let mut state = self.state.lock().await; - state.set_token_info(Some(info)); - } - // Defer seeding the session's initial context until the first turn starts so // turn/start overrides can be merged before we write to the rollout. if !is_subagent { @@ -1401,13 +1394,6 @@ impl Session { self.apply_rollout_reconstruction(&turn_context, &rollout_items) .await; - // Seed usage info from the recorded rollout so UIs can show token counts - // immediately on resume/fork. - if let Some(info) = Self::last_token_info_from_rollout(&rollout_items) { - let mut state = self.state.lock().await; - state.set_token_info(Some(info)); - } - // If persisting, persist all rollout items as-is (the store filters). if !rollout_items.is_empty() { self.persist_rollout_items(&rollout_items).await; @@ -1455,7 +1441,7 @@ impl Session { turn_context.config.model_auto_compact_token_limit_scope, reconstruction, history_reconciliation::RolloutReconstructionInstallOptions { - token_info: None, + token_info: Self::last_token_info_from_rollout(rollout_items), history: history_reconciliation::RolloutHistoryInstallMode::Replace, auto_compact_window: history_reconciliation::AutoCompactWindowInstallMode::Restore, diff --git a/codex-rs/core/src/state/mod.rs b/codex-rs/core/src/state/mod.rs index dfa8748919..4252245d1e 100644 --- a/codex-rs/core/src/state/mod.rs +++ b/codex-rs/core/src/state/mod.rs @@ -9,6 +9,7 @@ pub(crate) use auto_compact_window::AutoCompactWindowIds; pub(crate) use auto_compact_window::AutoCompactWindowSnapshot; pub(crate) use service::SessionServices; pub(crate) use session::PersistedHistoryCursor; +pub(crate) use session::PersistedHistoryCursorState; pub(crate) use session::PersistedHistoryCursorUncertainty; pub(crate) use session::SessionState; pub(crate) use turn::ActiveTurn; diff --git a/codex-rs/core/src/state/session.rs b/codex-rs/core/src/state/session.rs index fbbaf6fc63..cb977e6a91 100644 --- a/codex-rs/core/src/state/session.rs +++ b/codex-rs/core/src/state/session.rs @@ -39,6 +39,17 @@ pub(crate) enum PersistedHistoryCursorUncertainty { HistoryRewrite, } +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub(crate) enum PersistedHistoryCursorState { + #[default] + Unknown, + Known(PersistedHistoryCursor), + Uncertain { + uncertainty: PersistedHistoryCursorUncertainty, + expected: Option, + }, +} + /// Persistent, session-scoped state previously stored directly on `Session`. pub(crate) struct SessionState { pub(crate) session_configuration: SessionConfiguration, @@ -61,9 +72,7 @@ pub(crate) struct SessionState { granted_permissions_by_environment_id: HashMap, next_turn_is_first: bool, known_persisted_incomplete_tail: Option, - known_persisted_history_cursor: Option, - persisted_history_cursor_uncertainty: Option, - uncertain_expected_persisted_history_cursor: Option, + pub(crate) persisted_history_cursor: PersistedHistoryCursorState, } impl SessionState { @@ -97,9 +106,7 @@ impl SessionState { granted_permissions_by_environment_id: HashMap::new(), next_turn_is_first: true, known_persisted_incomplete_tail: None, - known_persisted_history_cursor: None, - persisted_history_cursor_uncertainty: None, - uncertain_expected_persisted_history_cursor: None, + persisted_history_cursor: PersistedHistoryCursorState::Unknown, } } @@ -140,53 +147,13 @@ impl SessionState { self.known_persisted_incomplete_tail = tail; } - pub(crate) fn known_persisted_history_cursor(&self) -> Option { - self.known_persisted_history_cursor - } - pub(crate) fn set_known_persisted_history_cursor( &mut self, cursor: Option, ) { - self.known_persisted_history_cursor = cursor; - self.persisted_history_cursor_uncertainty = None; - self.uncertain_expected_persisted_history_cursor = None; - } - - pub(crate) fn persisted_history_cursor_uncertainty( - &self, - ) -> Option { - self.persisted_history_cursor_uncertainty - } - - pub(crate) fn uncertain_expected_persisted_history_cursor( - &self, - ) -> Option { - self.uncertain_expected_persisted_history_cursor - } - - pub(crate) fn set_uncertain_expected_persisted_history_cursor( - &mut self, - cursor: Option, - ) { - self.uncertain_expected_persisted_history_cursor = cursor; - } - - pub(crate) fn invalidate_persisted_item_cursor( - &mut self, - uncertainty: PersistedHistoryCursorUncertainty, - expected_cursor: Option, - ) { - self.known_persisted_history_cursor = None; - self.uncertain_expected_persisted_history_cursor = expected_cursor; - self.persisted_history_cursor_uncertainty = Some( - match (self.persisted_history_cursor_uncertainty, uncertainty) { - (Some(PersistedHistoryCursorUncertainty::HistoryRewrite), _) - | (_, PersistedHistoryCursorUncertainty::HistoryRewrite) => { - PersistedHistoryCursorUncertainty::HistoryRewrite - } - _ => PersistedHistoryCursorUncertainty::AppendOnly, - }, + self.persisted_history_cursor = cursor.map_or( + PersistedHistoryCursorState::Unknown, + PersistedHistoryCursorState::Known, ); }