diff --git a/codex-rs/app-server-protocol/src/protocol/lifecycle_projection.rs b/codex-rs/app-server-protocol/src/protocol/lifecycle_projection.rs index ab5d211c05..34d40ea82c 100644 --- a/codex-rs/app-server-protocol/src/protocol/lifecycle_projection.rs +++ b/codex-rs/app-server-protocol/src/protocol/lifecycle_projection.rs @@ -1,6 +1,7 @@ use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::RolloutItem; use codex_thread_store_protocol::LifecycleMutation; +use codex_thread_store_protocol::StoredLifecycleProjectionState; use codex_thread_store_protocol::ThreadHistoryMutation; use codex_thread_store_protocol::ThreadHistoryMutationMetadata; use codex_thread_store_protocol::ThreadHistoryProjectionObserver; @@ -12,8 +13,6 @@ mod tests; /// Observes append batches and emits only thread lifecycle mutations. pub struct LifecycleProjectionObserver { - // TODO(wiltzius): Persist this in a lifecycle projection checkpoint once stores persist - // lifecycle mutations, so a resumed observer can restore its prior in-memory state. current_turn_id: Option, } @@ -30,6 +29,12 @@ impl LifecycleProjectionObserver { } } + pub fn from_stored_state(state: &StoredLifecycleProjectionState) -> Self { + Self { + current_turn_id: state.current_turn_id.clone(), + } + } + pub fn observe_append( &mut self, persisted_rollout_items: &[RolloutItem], diff --git a/codex-rs/app-server-protocol/src/protocol/lifecycle_projection_tests.rs b/codex-rs/app-server-protocol/src/protocol/lifecycle_projection_tests.rs index ead748e1b5..d1e7e60398 100644 --- a/codex-rs/app-server-protocol/src/protocol/lifecycle_projection_tests.rs +++ b/codex-rs/app-server-protocol/src/protocol/lifecycle_projection_tests.rs @@ -6,6 +6,7 @@ use codex_protocol::protocol::ThreadRolledBackEvent; use codex_protocol::protocol::TurnCompleteEvent; use codex_protocol::protocol::TurnStartedEvent; use codex_protocol::protocol::UserMessageEvent; +use codex_thread_store_protocol::StoredLifecycleProjectionState; use pretty_assertions::assert_eq; use serde_json::json; @@ -110,6 +111,34 @@ fn emits_turn_failed_for_turn_affecting_errors() { ); } +#[test] +fn restores_current_turn_for_later_turn_failure() { + let mut observer = + LifecycleProjectionObserver::from_stored_state(&StoredLifecycleProjectionState { + current_turn_id: Some("turn-a".into()), + }); + + let mutations = observer.observe_append( + &[], + &[RolloutItem::EventMsg(EventMsg::Error(ErrorEvent { + message: "boom".into(), + codex_error_info: None, + }))], + ); + + assert_eq!( + lifecycle_payloads(mutations), + vec![json!({ + "eventType": "turn.failed", + "turnId": "turn-a", + "payload": { + "message": "boom", + "codexErrorInfo": null, + }, + })] + ); +} + fn lifecycle_payloads(mutations: Vec) -> Vec { mutations .into_iter() diff --git a/codex-rs/app-server-protocol/src/protocol/thread_history.rs b/codex-rs/app-server-protocol/src/protocol/thread_history.rs index a25173ab53..a66fea1dad 100644 --- a/codex-rs/app-server-protocol/src/protocol/thread_history.rs +++ b/codex-rs/app-server-protocol/src/protocol/thread_history.rs @@ -54,6 +54,12 @@ use codex_protocol::protocol::UserMessageEvent; use codex_protocol::protocol::ViewImageToolCallEvent; use codex_protocol::protocol::WebSearchBeginEvent; use codex_protocol::protocol::WebSearchEndEvent; +use codex_thread_store_protocol::StoredThreadItem; +use codex_thread_store_protocol::StoredThreadItemProjectionState; +use codex_thread_store_protocol::StoredTurn; +use codex_thread_store_protocol::StoredTurnError; +use codex_thread_store_protocol::StoredTurnStatus; +use codex_thread_store_protocol::StoredTurnSummaryProjectionState; use std::collections::HashMap; use tracing::warn; use uuid::Uuid; @@ -166,6 +172,29 @@ impl ThreadHistoryState { ); } + pub(super) fn restore_materialized_turns( + &mut self, + turns: Vec, + current_turn_id: Option<&str>, + next_item_index: i64, + ) { + self.turns.clear(); + self.current_turn = None; + self.next_item_index = next_item_index.max(1); + for turn in turns { + if current_turn_id == Some(turn.id.as_str()) { + self.current_turn = Some(PendingTurn::from(turn)); + } else { + self.turns.push(turn); + } + } + if let Some(current_turn_id) = current_turn_id + && self.current_turn.is_none() + { + self.restore_current_turn(current_turn_id.to_string()); + } + } + /// Shared reducer for persisted rollout replay and in-memory current-turn /// tracking used by running thread resume/rejoin. /// @@ -1206,6 +1235,23 @@ impl From for Turn { } } +impl From for PendingTurn { + fn from(value: Turn) -> Self { + Self { + id: value.id, + items: value.items, + error: value.error, + status: value.status, + started_at: value.started_at, + completed_at: value.completed_at, + duration_ms: value.duration_ms, + opened_explicitly: true, + saw_compaction: false, + rollout_start_index: 0, + } + } +} + impl From<&PendingTurn> for Turn { fn from(value: &PendingTurn) -> Self { Self { @@ -1221,6 +1267,76 @@ impl From<&PendingTurn> for Turn { } } +pub(super) fn materialized_turns_from_stored_thread_item_projection_state( + state: &StoredThreadItemProjectionState, +) -> Result, serde_json::Error> { + state + .turns + .iter() + .map(|stored_turn| { + let mut stored_items = state + .items + .iter() + .filter(|item| item.turn_id == stored_turn.turn_id) + .collect::>(); + stored_items.sort_by_key(|item| item.item_ordinal); + materialized_turn_from_stored_items(stored_turn, stored_items) + }) + .collect() +} + +pub(super) fn materialized_turns_from_stored_turn_summary_projection_state( + state: &StoredTurnSummaryProjectionState, +) -> Result, serde_json::Error> { + state + .turns + .iter() + .map(|stored_turn| { + materialized_turn_from_stored_items(stored_turn, stored_turn.items.iter().collect()) + }) + .collect() +} + +fn materialized_turn_from_stored_items( + stored_turn: &StoredTurn, + stored_items: Vec<&StoredThreadItem>, +) -> Result { + Ok(Turn { + id: stored_turn.turn_id.clone(), + items: stored_items + .into_iter() + .map(stored_thread_item) + .collect::, _>>()?, + items_view: TurnItemsView::Full, + error: stored_turn.error.as_ref().map(turn_error_from_stored), + status: turn_status_from_stored(stored_turn.status), + started_at: stored_turn.started_at, + completed_at: stored_turn.completed_at, + duration_ms: stored_turn.duration_ms, + }) +} + +fn stored_thread_item(item: &StoredThreadItem) -> Result { + serde_json::from_value(item.item.clone()) +} + +fn turn_status_from_stored(status: StoredTurnStatus) -> TurnStatus { + match status { + StoredTurnStatus::Completed => TurnStatus::Completed, + StoredTurnStatus::Interrupted => TurnStatus::Interrupted, + StoredTurnStatus::Failed => TurnStatus::Failed, + StoredTurnStatus::InProgress => TurnStatus::InProgress, + } +} + +fn turn_error_from_stored(error: &StoredTurnError) -> TurnError { + TurnError { + message: error.message.clone(), + codex_error_info: None, + additional_details: error.additional_details.clone(), + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/codex-rs/app-server-protocol/src/protocol/thread_item_projection.rs b/codex-rs/app-server-protocol/src/protocol/thread_item_projection.rs index 845689a948..b89265a09e 100644 --- a/codex-rs/app-server-protocol/src/protocol/thread_item_projection.rs +++ b/codex-rs/app-server-protocol/src/protocol/thread_item_projection.rs @@ -1,4 +1,5 @@ use crate::protocol::thread_history::ThreadHistoryState; +use crate::protocol::thread_history::materialized_turns_from_stored_thread_item_projection_state; use crate::protocol::v2::CollabAgentToolCallStatus; use crate::protocol::v2::CommandExecutionStatus; use crate::protocol::v2::DynamicToolCallStatus; @@ -7,6 +8,7 @@ use crate::protocol::v2::PatchApplyStatus; use crate::protocol::v2::ThreadItem; use crate::protocol::v2::Turn; use codex_protocol::protocol::RolloutItem; +use codex_thread_store_protocol::StoredThreadItemProjectionState; use codex_thread_store_protocol::ThreadHistoryMutation; use codex_thread_store_protocol::ThreadHistoryMutationMetadata; use codex_thread_store_protocol::ThreadHistoryProjectionObserver; @@ -25,9 +27,6 @@ mod tests; /// Persisting it lets the next append reuse stable item ordinals and update non-terminal /// ThreadItems without replaying the full rollout history first. /// -/// TODO(wiltzius): Before stores persist or restore this checkpoint, include enough reducer state -/// to resume reasoning coalescing, complete open items from any turn, and tombstone rolled-back -/// closed items after restart. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct ThreadItemProjectionCheckpoint { pub next_thread_item_ordinal: i64, @@ -162,6 +161,34 @@ impl ThreadItemProjectionObserver { } } + pub fn from_stored_state( + state: &StoredThreadItemProjectionState, + ) -> Result { + let mut reducer = ThreadItemProjectionReducer::new(); + reducer.state.restore_materialized_turns( + materialized_turns_from_stored_thread_item_projection_state(state)?, + state.current_turn_id.as_deref(), + state.next_generated_thread_item_id_index, + ); + let mut observer = Self { + reducer, + checkpoint: ThreadItemProjectionCheckpoint { + next_thread_item_ordinal: state.next_thread_item_ordinal.max(1), + next_generated_thread_item_id_index: state + .next_generated_thread_item_id_index + .max(1), + ..Default::default() + }, + item_ordinals: state + .items + .iter() + .map(|item| (item.item_key.clone(), item.item_ordinal)) + .collect(), + }; + observer.refresh_checkpoint(); + Ok(observer) + } + pub fn checkpoint(&self) -> &ThreadItemProjectionCheckpoint { &self.checkpoint } diff --git a/codex-rs/app-server-protocol/src/protocol/thread_item_projection_tests.rs b/codex-rs/app-server-protocol/src/protocol/thread_item_projection_tests.rs index 9197b52820..636ea948b4 100644 --- a/codex-rs/app-server-protocol/src/protocol/thread_item_projection_tests.rs +++ b/codex-rs/app-server-protocol/src/protocol/thread_item_projection_tests.rs @@ -7,6 +7,14 @@ use codex_protocol::protocol::ExecCommandSource; use codex_protocol::protocol::ExecCommandStatus as CoreExecCommandStatus; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::TurnStartedEvent; +use codex_thread_store_protocol::StoredLifecycleProjectionState; +use codex_thread_store_protocol::StoredThreadHistoryProjectionState; +use codex_thread_store_protocol::StoredThreadItem; +use codex_thread_store_protocol::StoredThreadItemProjectionState; +use codex_thread_store_protocol::StoredTurn; +use codex_thread_store_protocol::StoredTurnItemsView; +use codex_thread_store_protocol::StoredTurnStatus; +use codex_thread_store_protocol::StoredTurnSummaryProjectionState; use codex_utils_absolute_path::test_support::PathBufExt; use codex_utils_absolute_path::test_support::test_path_buf; use pretty_assertions::assert_eq; @@ -14,7 +22,7 @@ use serde_json::Value; use std::time::Duration; #[test] -fn reuses_thread_item_ordinal_for_open_item_upserts() { +fn restores_thread_item_ordinal_for_open_item_upserts() { let mut observer = ThreadItemProjectionObserver::new(); let begin_projection_source_events = vec![ RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent { @@ -41,8 +49,10 @@ fn reuses_thread_item_ordinal_for_open_item_upserts() { let begin_mutations = observer .observe_append(&[], &begin_projection_source_events) .thread_history_mutations; - let checkpoint = observer.checkpoint().clone(); - let mut resumed_observer = ThreadItemProjectionObserver::from_checkpoint(checkpoint); + let stored_state = stored_projection_state(&observer, "turn-a"); + let mut resumed_observer = + ThreadItemProjectionObserver::from_stored_state(&stored_state.thread_items) + .expect("restore observer"); let end_projection_source_events = vec![RolloutItem::EventMsg(EventMsg::ExecCommandEnd( ExecCommandEndEvent { call_id: "exec-1".into(), @@ -76,6 +86,109 @@ fn reuses_thread_item_ordinal_for_open_item_upserts() { assert_eq!(end_payload["isOpen"], false); } +#[test] +fn restores_current_reasoning_item_for_later_coalescing() { + let mut observer = ThreadItemProjectionObserver::new(); + observer.observe_append( + &[], + &[ + RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-a".into(), + trace_id: None, + started_at: None, + model_context_window: None, + collaboration_mode_kind: Default::default(), + })), + RolloutItem::EventMsg(EventMsg::AgentReasoning( + codex_protocol::protocol::AgentReasoningEvent { + text: "thinking".into(), + }, + )), + ], + ); + let stored_state = stored_projection_state(&observer, "turn-a"); + let mut resumed_observer = + ThreadItemProjectionObserver::from_stored_state(&stored_state.thread_items) + .expect("restore observer"); + + let mutations = resumed_observer + .observe_append( + &[], + &[RolloutItem::EventMsg(EventMsg::AgentReasoning( + codex_protocol::protocol::AgentReasoningEvent { + text: "more".into(), + }, + ))], + ) + .thread_history_mutations; + + let payload = only_thread_item_payload(mutations); + assert_eq!(payload["itemKey"], "item-1"); + assert_eq!(payload["itemOrdinal"], 1); + assert_eq!( + payload["materializedThreadItem"]["summary"], + serde_json::json!(["thinking", "more"]) + ); +} + +fn stored_projection_state( + observer: &ThreadItemProjectionObserver, + current_turn_id: &str, +) -> StoredThreadHistoryProjectionState { + let checkpoint = observer.checkpoint(); + let turns = observer.materialized_turns(); + StoredThreadHistoryProjectionState { + thread_items: StoredThreadItemProjectionState { + turns: turns + .iter() + .map(|turn| stored_turn(turn, StoredTurnItemsView::NotLoaded)) + .collect(), + items: turns + .iter() + .flat_map(|turn| { + turn.items.iter().map(|item| StoredThreadItem { + turn_id: turn.id.clone(), + item_key: item.id().to_string(), + item_ordinal: checkpoint + .open_items + .get(item.id()) + .map_or(1, |item| item.item_ordinal), + is_open: checkpoint.open_items.contains_key(item.id()), + item: serde_json::to_value(item).expect("serialize item"), + }) + }) + .collect(), + current_turn_id: Some(current_turn_id.to_string()), + next_thread_item_ordinal: checkpoint.next_thread_item_ordinal, + next_generated_thread_item_id_index: checkpoint.next_generated_thread_item_id_index, + }, + turn_summaries: StoredTurnSummaryProjectionState { + turns: turns + .iter() + .map(|turn| stored_turn(turn, StoredTurnItemsView::Summary)) + .collect(), + current_turn_id: Some(current_turn_id.to_string()), + next_generated_thread_item_id_index: checkpoint.next_generated_thread_item_id_index, + }, + lifecycle: StoredLifecycleProjectionState { + current_turn_id: Some(current_turn_id.to_string()), + }, + } +} + +fn stored_turn(turn: &Turn, items_view: StoredTurnItemsView) -> StoredTurn { + StoredTurn { + turn_id: turn.id.clone(), + items: Vec::new(), + items_view, + status: StoredTurnStatus::InProgress, + error: None, + started_at: turn.started_at, + completed_at: turn.completed_at, + duration_ms: turn.duration_ms, + } +} + fn only_thread_item_payload(mutations: Vec) -> Value { let mut payloads = mutations.into_iter().filter_map(|mutation| match mutation { ThreadHistoryMutation::ThreadItem(mutation) => Some(mutation.payload), diff --git a/codex-rs/app-server-protocol/src/protocol/turn_summary_projection.rs b/codex-rs/app-server-protocol/src/protocol/turn_summary_projection.rs index d0178b6fec..caaed6889d 100644 --- a/codex-rs/app-server-protocol/src/protocol/turn_summary_projection.rs +++ b/codex-rs/app-server-protocol/src/protocol/turn_summary_projection.rs @@ -1,8 +1,10 @@ use crate::protocol::thread_history::ThreadHistoryState; +use crate::protocol::thread_history::materialized_turns_from_stored_turn_summary_projection_state; use crate::protocol::v2::ThreadItem; use crate::protocol::v2::Turn; use crate::protocol::v2::TurnStatus; use codex_protocol::protocol::RolloutItem; +use codex_thread_store_protocol::StoredTurnSummaryProjectionState; use codex_thread_store_protocol::ThreadHistoryMutation; use codex_thread_store_protocol::ThreadHistoryMutationMetadata; use codex_thread_store_protocol::ThreadHistoryProjectionObserver; @@ -34,6 +36,23 @@ impl TurnSummaryProjectionObserver { } } + pub fn from_stored_state( + state: &StoredTurnSummaryProjectionState, + ) -> Result { + let turns = materialized_turns_from_stored_turn_summary_projection_state(state)?; + let summaries = turns + .iter() + .map(|turn| (turn.id.clone(), TurnSummaryState::from_turn(turn))) + .collect(); + let mut reducer = ThreadHistoryState::new(); + reducer.restore_materialized_turns( + turns, + state.current_turn_id.as_deref(), + state.next_generated_thread_item_id_index, + ); + Ok(Self { reducer, summaries }) + } + pub fn observe_append( &mut self, persisted_rollout_items: &[RolloutItem], diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 8ce16de740..1efa1dfc1e 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -136,9 +136,11 @@ use codex_terminal_detection::user_agent; use codex_thread_store::CreateThreadParams; use codex_thread_store::LiveThread; use codex_thread_store::LiveThreadInitGuard; +use codex_thread_store::LoadThreadHistoryProjectionStateParams; use codex_thread_store::LocalThreadStore; use codex_thread_store::ReadThreadParams; use codex_thread_store::ResumeThreadParams; +use codex_thread_store::ThreadHistoryProjectionObserver; use codex_thread_store::ThreadPersistenceMetadata; use codex_thread_store::ThreadStore; use codex_utils_output_truncation::TruncationPolicy; @@ -1262,6 +1264,8 @@ impl Session { // If persisting, persist all rollout items as-is (the store filters). if !rollout_items.is_empty() { + // TODO(wiltzius): Projection-aware stores need fork bootstrap mutations here, + // derived from source stored projection state plus fork-only synthetic deltas. self.persist_rollout_items(&rollout_items).await; } diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index a44f626c8c..38950020ed 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -594,15 +594,28 @@ impl Session { .await? } }; - let thread_history_projection_observers: Vec< - Box, - > = vec![ - Box::new(codex_app_server_protocol::ThreadItemProjectionObserver::new()), - Box::new(codex_app_server_protocol::TurnSummaryProjectionObserver::new()), - Box::new(codex_app_server_protocol::LifecycleProjectionObserver::new()), - ]; - // TODO(wiltzius): Once stores persist projections, restore each observer from the - // stored projection checkpoint on resume instead of always starting fresh. + let thread_history_projection_observers = match &initial_history { + InitialHistory::Resumed(resumed_history) => match thread_store + .load_thread_history_projection_state( + LoadThreadHistoryProjectionStateParams { + thread_id: resumed_history.conversation_id, + include_archived: true, + }, + ) + .await + { + Ok(state) => thread_history_projection_observers_from_stored_state(&state)?, + Err(codex_thread_store::ThreadStoreError::Unsupported { .. }) => { + // Stores without durable projections, including LocalThreadStore today, + // preserve the existing fresh-observer resume behavior. + new_thread_history_projection_observers() + } + Err(err) => return Err(err.into()), + }, + InitialHistory::New | InitialHistory::Cleared | InitialHistory::Forked(_) => { + new_thread_history_projection_observers() + } + }; Ok(Some(live_thread.with_thread_history_projection_observers( thread_history_projection_observers, ))) @@ -1263,3 +1276,33 @@ impl Session { } } } + +fn new_thread_history_projection_observers() -> Vec> { + vec![ + Box::new(codex_app_server_protocol::ThreadItemProjectionObserver::new()), + Box::new(codex_app_server_protocol::TurnSummaryProjectionObserver::new()), + Box::new(codex_app_server_protocol::LifecycleProjectionObserver::new()), + ] +} + +fn thread_history_projection_observers_from_stored_state( + state: &codex_thread_store::StoredThreadHistoryProjectionState, +) -> anyhow::Result>> { + Ok(vec![ + Box::new( + codex_app_server_protocol::ThreadItemProjectionObserver::from_stored_state( + &state.thread_items, + )?, + ), + Box::new( + codex_app_server_protocol::TurnSummaryProjectionObserver::from_stored_state( + &state.turn_summaries, + )?, + ), + Box::new( + codex_app_server_protocol::LifecycleProjectionObserver::from_stored_state( + &state.lifecycle, + ), + ), + ]) +} diff --git a/codex-rs/thread-store-protocol/src/lib.rs b/codex-rs/thread-store-protocol/src/lib.rs index b7b13e2c45..ed86c46c56 100644 --- a/codex-rs/thread-store-protocol/src/lib.rs +++ b/codex-rs/thread-store-protocol/src/lib.rs @@ -51,6 +51,136 @@ pub enum ThreadHistoryMutation { Lifecycle(LifecycleMutation), } +/// Requested amount of item detail for stored turns. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum StoredTurnItemsView { + /// Return turn metadata only. + NotLoaded, + /// Return display summary items for each turn. + #[default] + Summary, + /// Return every projected thread item available for each turn. + Full, +} + +/// Store-owned status for a persisted turn. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum StoredTurnStatus { + /// The turn completed normally. + Completed, + /// The turn was interrupted before normal completion. + Interrupted, + /// The turn failed. + Failed, + /// The turn is still in progress. + InProgress, +} + +/// Store-owned error details for a failed persisted turn. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct StoredTurnError { + /// User-visible error message. + pub message: String, + /// Optional additional detail for clients that expose expanded error context. + pub additional_details: Option, +} + +/// Store-owned projected ThreadItem row. +/// +/// The store keeps `item` storage-neutral because app-server owns the concrete `ThreadItem` type. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct StoredThreadItem { + /// Turn that owns this projected item. + pub turn_id: String, + /// Stable projection key for upserting/tombstoning this item. + pub item_key: String, + /// Stable order of this item within the projected thread history. + pub item_ordinal: i64, + /// Whether the item may receive future updates. + pub is_open: bool, + /// Materialized app-server `ThreadItem` JSON. + pub item: Value, +} + +/// Store-owned turn representation used by turn pagination APIs. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct StoredTurn { + /// Turn id. + pub turn_id: String, + /// Projected thread items associated with this turn, according to `items_view`. + pub items: Vec, + /// Amount of item detail included in `items`. + pub items_view: StoredTurnItemsView, + /// Store-owned status for API layer projection. + pub status: StoredTurnStatus, + /// Error message when the turn failed. + pub error: Option, + /// Unix timestamp (seconds) when the turn started. + pub started_at: Option, + /// Unix timestamp (seconds) when the turn completed. + pub completed_at: Option, + /// Duration between turn start and completion in milliseconds, if known. + pub duration_ms: Option, +} + +/// Store-owned current materialized thread-item projection state. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct StoredThreadItemProjectionState { + /// Current projected turns in turn order, without requiring app-server `ThreadItem` decoding. + pub turns: Vec, + /// Current non-tombstoned materialized ThreadItem rows in item ordinal order. + pub items: Vec, + /// Current active turn, if one exists. + pub current_turn_id: Option, + pub next_thread_item_ordinal: i64, + pub next_generated_thread_item_id_index: i64, +} + +impl Default for StoredThreadItemProjectionState { + fn default() -> Self { + Self { + turns: Vec::new(), + items: Vec::new(), + current_turn_id: None, + next_thread_item_ordinal: 1, + next_generated_thread_item_id_index: 1, + } + } +} + +/// Store-owned current materialized turn-summary projection state. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct StoredTurnSummaryProjectionState { + pub turns: Vec, + /// Current active turn, if one exists. + pub current_turn_id: Option, + pub next_generated_thread_item_id_index: i64, +} + +impl Default for StoredTurnSummaryProjectionState { + fn default() -> Self { + Self { + turns: Vec::new(), + current_turn_id: None, + next_generated_thread_item_id_index: 1, + } + } +} + +/// Store-owned current lifecycle projection state. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct StoredLifecycleProjectionState { + pub current_turn_id: Option, +} + +/// Store-owned current state for each thread-history projection observer. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct StoredThreadHistoryProjectionState { + pub thread_items: StoredThreadItemProjectionState, + pub turn_summaries: StoredTurnSummaryProjectionState, + pub lifecycle: StoredLifecycleProjectionState, +} + /// Observes a live append batch and derives typed thread-history mutations for the store. /// /// Implementations may materialize higher-level ThreadItem views from rollout items, but the diff --git a/codex-rs/thread-store/src/lib.rs b/codex-rs/thread-store/src/lib.rs index 0e94c3453c..7ab24fa620 100644 --- a/codex-rs/thread-store/src/lib.rs +++ b/codex-rs/thread-store/src/lib.rs @@ -13,6 +13,15 @@ mod thread_metadata_sync; mod types; pub use codex_thread_store_protocol::LifecycleMutation; +pub use codex_thread_store_protocol::StoredLifecycleProjectionState; +pub use codex_thread_store_protocol::StoredThreadHistoryProjectionState; +pub use codex_thread_store_protocol::StoredThreadItem; +pub use codex_thread_store_protocol::StoredThreadItemProjectionState; +pub use codex_thread_store_protocol::StoredTurn; +pub use codex_thread_store_protocol::StoredTurnError; +pub use codex_thread_store_protocol::StoredTurnItemsView; +pub use codex_thread_store_protocol::StoredTurnStatus; +pub use codex_thread_store_protocol::StoredTurnSummaryProjectionState; pub use codex_thread_store_protocol::ThreadHistoryMutation; pub use codex_thread_store_protocol::ThreadHistoryMutationMetadata; pub use codex_thread_store_protocol::ThreadHistoryProjectionObserver; @@ -37,6 +46,7 @@ pub use types::ListItemsParams; pub use types::ListThreadsParams; pub use types::ListTurnsParams; pub use types::LoadThreadHistoryParams; +pub use types::LoadThreadHistoryProjectionStateParams; pub use types::ReadThreadByRolloutPathParams; pub use types::ReadThreadParams; pub use types::ResumeThreadParams; @@ -44,12 +54,7 @@ pub use types::SearchThreadsParams; pub use types::SortDirection; pub use types::StoredThread; pub use types::StoredThreadHistory; -pub use types::StoredThreadItem; pub use types::StoredThreadSearchResult; -pub use types::StoredTurn; -pub use types::StoredTurnError; -pub use types::StoredTurnItemsView; -pub use types::StoredTurnStatus; pub use types::ThreadMetadataPatch; pub use types::ThreadPage; pub use types::ThreadPersistenceMetadata; diff --git a/codex-rs/thread-store/src/store.rs b/codex-rs/thread-store/src/store.rs index 7276a980da..112f7f442d 100644 --- a/codex-rs/thread-store/src/store.rs +++ b/codex-rs/thread-store/src/store.rs @@ -10,12 +10,14 @@ use crate::ListItemsParams; use crate::ListThreadsParams; use crate::ListTurnsParams; use crate::LoadThreadHistoryParams; +use crate::LoadThreadHistoryProjectionStateParams; use crate::ReadThreadByRolloutPathParams; use crate::ReadThreadParams; use crate::ResumeThreadParams; use crate::SearchThreadsParams; use crate::StoredThread; use crate::StoredThreadHistory; +use crate::StoredThreadHistoryProjectionState; use crate::ThreadPage; use crate::ThreadSearchPage; use crate::ThreadStoreError; @@ -64,6 +66,18 @@ pub trait ThreadStore: Any + Send + Sync { params: LoadThreadHistoryParams, ) -> ThreadStoreResult; + /// Loads store-owned current state for each thread-history projection observer. + /// + /// Stores that do not persist these projections yet may leave this unsupported. + async fn load_thread_history_projection_state( + &self, + _params: LoadThreadHistoryProjectionStateParams, + ) -> ThreadStoreResult { + Err(ThreadStoreError::Unsupported { + operation: "load_thread_history_projection_state", + }) + } + /// Reads a thread summary and optionally its persisted history. async fn read_thread(&self, params: ReadThreadParams) -> ThreadStoreResult; diff --git a/codex-rs/thread-store/src/types.rs b/codex-rs/thread-store/src/types.rs index d9d48cd469..db67559076 100644 --- a/codex-rs/thread-store/src/types.rs +++ b/codex-rs/thread-store/src/types.rs @@ -15,12 +15,14 @@ use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::ThreadMemoryMode as MemoryMode; use codex_protocol::protocol::ThreadSource; use codex_protocol::protocol::TokenUsage; +use codex_thread_store_protocol::StoredThreadItem; +use codex_thread_store_protocol::StoredTurn; +use codex_thread_store_protocol::StoredTurnItemsView; use codex_thread_store_protocol::ThreadHistoryMutation; use serde::Deserialize; use serde::Deserializer; use serde::Serialize; use serde::Serializer; -use serde_json::Value; mod optional_option { use super::*; @@ -116,6 +118,15 @@ pub struct LoadThreadHistoryParams { pub include_archived: bool, } +/// Parameters for loading store-owned thread-history projection state. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct LoadThreadHistoryProjectionStateParams { + /// Thread id to load. + pub thread_id: ThreadId, + /// Whether archived threads are eligible. + pub include_archived: bool, +} + /// Persisted rollout history for a thread, without any filesystem path requirement. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct StoredThreadHistory { @@ -237,57 +248,6 @@ pub struct ThreadSearchPage { pub next_cursor: Option, } -/// Requested amount of item detail for stored turns. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum StoredTurnItemsView { - /// Return turn metadata only. - NotLoaded, - /// Return display summary items for each turn. - #[default] - Summary, - /// Return every projected thread item available for each turn. - Full, -} - -/// Store-owned status for a persisted turn. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum StoredTurnStatus { - /// The turn completed normally. - Completed, - /// The turn was interrupted before normal completion. - Interrupted, - /// The turn failed. - Failed, - /// The turn is still in progress. - InProgress, -} - -/// Store-owned error details for a failed persisted turn. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct StoredTurnError { - /// User-visible error message. - pub message: String, - /// Optional additional detail for clients that expose expanded error context. - pub additional_details: Option, -} - -/// Store-owned projected ThreadItem row. -/// -/// The store keeps `item` storage-neutral because app-server owns the concrete `ThreadItem` type. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct StoredThreadItem { - /// Turn that owns this projected item. - pub turn_id: String, - /// Stable projection key for upserting/tombstoning this item. - pub item_key: String, - /// Stable order of this item within the projected thread history. - pub item_ordinal: i64, - /// Whether the item may receive future updates. - pub is_open: bool, - /// Materialized app-server `ThreadItem` JSON. - pub item: Value, -} - /// Parameters for listing turns within a stored thread. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct ListTurnsParams { @@ -305,30 +265,6 @@ pub struct ListTurnsParams { pub items_view: StoredTurnItemsView, } -/// Store-owned turn representation used by turn pagination APIs. -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct StoredTurn { - /// Turn id. - pub turn_id: String, - /// Projected thread items associated with this turn, according to `items_view`. - /// - /// `NotLoaded` returns no items, `Summary` returns the display summary items for the turn, and - /// `Full` is reserved for stores that can inline the complete item list. - pub items: Vec, - /// Amount of item detail included in `items`. - pub items_view: StoredTurnItemsView, - /// Store-owned status for API layer projection. - pub status: StoredTurnStatus, - /// Error message when the turn failed. - pub error: Option, - /// Unix timestamp (seconds) when the turn started. - pub started_at: Option, - /// Unix timestamp (seconds) when the turn completed. - pub completed_at: Option, - /// Duration between turn start and completion in milliseconds, if known. - pub duration_ms: Option, -} - /// A page of stored turns. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct TurnPage {