mirror of
https://github.com/openai/codex.git
synced 2026-11-25 23:30:49 +00:00
add thread history projection observers
This commit is contained in:
@@ -0,0 +1,114 @@
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::RolloutItem;
|
||||
use codex_thread_store_protocol::LifecycleMutation;
|
||||
use codex_thread_store_protocol::ThreadHistoryMutation;
|
||||
use codex_thread_store_protocol::ThreadHistoryMutationMetadata;
|
||||
use codex_thread_store_protocol::ThreadHistoryProjectionObserver;
|
||||
use serde_json::json;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lifecycle_projection_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
/// Observes append batches and emits only thread lifecycle mutations.
|
||||
pub struct LifecycleProjectionObserver;
|
||||
|
||||
impl Default for LifecycleProjectionObserver {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl LifecycleProjectionObserver {
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
pub fn observe_append(
|
||||
&mut self,
|
||||
persisted_rollout_items: &[RolloutItem],
|
||||
projection_source_events: &[RolloutItem],
|
||||
) -> Vec<ThreadHistoryMutation> {
|
||||
source_rollout_items(persisted_rollout_items, projection_source_events)
|
||||
.iter()
|
||||
.filter_map(lifecycle_mutation)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadHistoryProjectionObserver for LifecycleProjectionObserver {
|
||||
fn observe_append(
|
||||
&mut self,
|
||||
persisted_rollout_items: &[RolloutItem],
|
||||
projection_source_events: &[RolloutItem],
|
||||
) -> Vec<ThreadHistoryMutation> {
|
||||
LifecycleProjectionObserver::observe_append(
|
||||
self,
|
||||
persisted_rollout_items,
|
||||
projection_source_events,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn lifecycle_mutation(rollout_item: &RolloutItem) -> Option<ThreadHistoryMutation> {
|
||||
let RolloutItem::EventMsg(event) = rollout_item else {
|
||||
return None;
|
||||
};
|
||||
let (event_type, turn_id, payload) = match event {
|
||||
EventMsg::TurnStarted(payload) => (
|
||||
"turn.started",
|
||||
Some(payload.turn_id.clone()),
|
||||
json!({
|
||||
"startedAt": payload.started_at,
|
||||
}),
|
||||
),
|
||||
EventMsg::TurnComplete(payload) => (
|
||||
"turn.completed",
|
||||
Some(payload.turn_id.clone()),
|
||||
json!({
|
||||
"completedAt": payload.completed_at,
|
||||
"durationMs": payload.duration_ms,
|
||||
}),
|
||||
),
|
||||
EventMsg::TurnAborted(payload) => (
|
||||
"turn.cancelled",
|
||||
payload.turn_id.clone(),
|
||||
json!({
|
||||
"reason": payload.reason,
|
||||
"completedAt": payload.completed_at,
|
||||
"durationMs": payload.duration_ms,
|
||||
}),
|
||||
),
|
||||
EventMsg::ThreadRolledBack(payload) => (
|
||||
"thread.rolled_back",
|
||||
None,
|
||||
json!({
|
||||
"numTurns": payload.num_turns,
|
||||
}),
|
||||
),
|
||||
_ => return None,
|
||||
};
|
||||
Some(ThreadHistoryMutation::Lifecycle(LifecycleMutation {
|
||||
metadata: mutation_metadata(),
|
||||
payload: json!({
|
||||
"eventType": event_type,
|
||||
"turnId": turn_id,
|
||||
"payload": payload,
|
||||
}),
|
||||
}))
|
||||
}
|
||||
|
||||
fn mutation_metadata() -> ThreadHistoryMutationMetadata {
|
||||
ThreadHistoryMutationMetadata { schema_version: 1 }
|
||||
}
|
||||
|
||||
fn source_rollout_items<'a>(
|
||||
persisted_rollout_items: &'a [RolloutItem],
|
||||
projection_source_events: &'a [RolloutItem],
|
||||
) -> &'a [RolloutItem] {
|
||||
if projection_source_events.is_empty() {
|
||||
persisted_rollout_items
|
||||
} else {
|
||||
projection_source_events
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
use super::*;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::RolloutItem;
|
||||
use codex_protocol::protocol::ThreadRolledBackEvent;
|
||||
use codex_protocol::protocol::TurnCompleteEvent;
|
||||
use codex_protocol::protocol::TurnStartedEvent;
|
||||
use codex_protocol::protocol::UserMessageEvent;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn emits_lifecycle_mutations_from_lifecycle_events_only() {
|
||||
let mut observer = LifecycleProjectionObserver::new();
|
||||
let persisted_rollout_items = vec![
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
|
||||
turn_id: "turn-a".into(),
|
||||
trace_id: None,
|
||||
started_at: Some(10),
|
||||
model_context_window: None,
|
||||
collaboration_mode_kind: Default::default(),
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
|
||||
client_id: None,
|
||||
message: "hello".into(),
|
||||
images: None,
|
||||
text_elements: Vec::new(),
|
||||
local_images: Vec::new(),
|
||||
..Default::default()
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent {
|
||||
turn_id: "turn-a".into(),
|
||||
last_agent_message: None,
|
||||
completed_at: Some(11),
|
||||
duration_ms: Some(1_000),
|
||||
time_to_first_token_ms: None,
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::ThreadRolledBack(ThreadRolledBackEvent {
|
||||
num_turns: 1,
|
||||
})),
|
||||
];
|
||||
let mutations = observer.observe_append(&persisted_rollout_items, &[]);
|
||||
|
||||
assert_eq!(
|
||||
lifecycle_payloads(mutations),
|
||||
vec![
|
||||
json!({
|
||||
"eventType": "turn.started",
|
||||
"turnId": "turn-a",
|
||||
"payload": {
|
||||
"startedAt": 10,
|
||||
},
|
||||
}),
|
||||
json!({
|
||||
"eventType": "turn.completed",
|
||||
"turnId": "turn-a",
|
||||
"payload": {
|
||||
"completedAt": 11,
|
||||
"durationMs": 1_000,
|
||||
},
|
||||
}),
|
||||
json!({
|
||||
"eventType": "thread.rolled_back",
|
||||
"turnId": null,
|
||||
"payload": {
|
||||
"numTurns": 1,
|
||||
},
|
||||
}),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
fn lifecycle_payloads(mutations: Vec<ThreadHistoryMutation>) -> Vec<serde_json::Value> {
|
||||
mutations
|
||||
.into_iter()
|
||||
.map(|mutation| match mutation {
|
||||
ThreadHistoryMutation::Lifecycle(mutation) => mutation.payload,
|
||||
ThreadHistoryMutation::ThreadItem(_) | ThreadHistoryMutation::TurnSummary(_) => {
|
||||
panic!("lifecycle observer emitted non-lifecycle mutation")
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -4,8 +4,12 @@
|
||||
pub mod common;
|
||||
pub mod event_mapping;
|
||||
pub mod item_builders;
|
||||
mod lifecycle_projection;
|
||||
mod mappers;
|
||||
mod serde_helpers;
|
||||
pub mod thread_history;
|
||||
mod thread_history_builder;
|
||||
mod thread_item_projection;
|
||||
mod turn_summary_projection;
|
||||
pub mod v1;
|
||||
pub mod v2;
|
||||
|
||||
@@ -58,6 +58,11 @@ use std::collections::HashMap;
|
||||
use tracing::warn;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub use super::lifecycle_projection::*;
|
||||
pub use super::thread_history_builder::*;
|
||||
pub use super::thread_item_projection::*;
|
||||
pub use super::turn_summary_projection::*;
|
||||
|
||||
#[cfg(test)]
|
||||
use crate::protocol::v2::CommandAction;
|
||||
#[cfg(test)]
|
||||
@@ -71,19 +76,7 @@ use codex_protocol::protocol::ExecCommandStatus as CoreExecCommandStatus;
|
||||
#[cfg(test)]
|
||||
use codex_protocol::protocol::PatchApplyStatus as CorePatchApplyStatus;
|
||||
|
||||
/// Convert persisted [`RolloutItem`] entries into a sequence of [`Turn`] values.
|
||||
///
|
||||
/// When available, this uses `TurnContext.turn_id` as the canonical turn id so
|
||||
/// resumed/rebuilt thread history preserves the original turn identifiers.
|
||||
pub fn build_turns_from_rollout_items(items: &[RolloutItem]) -> Vec<Turn> {
|
||||
let mut builder = ThreadHistoryBuilder::new();
|
||||
for item in items {
|
||||
builder.handle_rollout_item(item);
|
||||
}
|
||||
builder.finish()
|
||||
}
|
||||
|
||||
pub struct ThreadHistoryBuilder {
|
||||
pub(super) struct ThreadHistoryState {
|
||||
turns: Vec<Turn>,
|
||||
current_turn: Option<PendingTurn>,
|
||||
next_item_index: i64,
|
||||
@@ -91,14 +84,8 @@ pub struct ThreadHistoryBuilder {
|
||||
next_rollout_index: usize,
|
||||
}
|
||||
|
||||
impl Default for ThreadHistoryBuilder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadHistoryBuilder {
|
||||
pub fn new() -> Self {
|
||||
impl ThreadHistoryState {
|
||||
pub(super) fn new() -> Self {
|
||||
Self {
|
||||
turns: Vec::new(),
|
||||
current_turn: None,
|
||||
@@ -108,27 +95,31 @@ impl ThreadHistoryBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
*self = Self::new();
|
||||
}
|
||||
|
||||
pub fn finish(mut self) -> Vec<Turn> {
|
||||
pub(super) fn finish(mut self) -> Vec<Turn> {
|
||||
self.finish_current_turn();
|
||||
self.turns
|
||||
}
|
||||
|
||||
pub fn active_turn_snapshot(&self) -> Option<Turn> {
|
||||
pub(super) fn active_turn_snapshot(&self) -> Option<Turn> {
|
||||
self.current_turn
|
||||
.as_ref()
|
||||
.map(Turn::from)
|
||||
.or_else(|| self.turns.last().cloned())
|
||||
}
|
||||
|
||||
pub(super) fn turns_snapshot(&self) -> Vec<Turn> {
|
||||
let mut turns = self.turns.clone();
|
||||
if let Some(turn) = self.current_turn.as_ref() {
|
||||
turns.push(Turn::from(turn));
|
||||
}
|
||||
turns
|
||||
}
|
||||
|
||||
/// Returns the index of the active turn snapshot within the finished turn list.
|
||||
///
|
||||
/// When a turn is still open, this is the index it will occupy after
|
||||
/// `finish`. When no turn is open, it is the index of the last finished turn.
|
||||
pub fn active_turn_position(&self) -> Option<usize> {
|
||||
pub(super) fn active_turn_position(&self) -> Option<usize> {
|
||||
if self.current_turn.is_some() {
|
||||
Some(self.turns.len())
|
||||
} else if self.turns.is_empty() {
|
||||
@@ -138,29 +129,49 @@ impl ThreadHistoryBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_active_turn(&self) -> bool {
|
||||
pub(super) fn has_active_turn(&self) -> bool {
|
||||
self.current_turn.is_some()
|
||||
}
|
||||
|
||||
pub fn active_turn_id_if_explicit(&self) -> Option<String> {
|
||||
pub(super) fn active_turn_id_if_explicit(&self) -> Option<String> {
|
||||
self.current_turn
|
||||
.as_ref()
|
||||
.filter(|turn| turn.opened_explicitly)
|
||||
.map(|turn| turn.id.clone())
|
||||
}
|
||||
|
||||
pub fn active_turn_start_index(&self) -> Option<usize> {
|
||||
pub(super) fn active_turn_start_index(&self) -> Option<usize> {
|
||||
self.current_turn
|
||||
.as_ref()
|
||||
.map(|turn| turn.rollout_start_index)
|
||||
}
|
||||
|
||||
pub(super) fn set_next_item_index(&mut self, next_item_index: i64) {
|
||||
self.next_item_index = next_item_index;
|
||||
}
|
||||
|
||||
pub(super) fn next_item_index(&self) -> i64 {
|
||||
self.next_item_index
|
||||
}
|
||||
|
||||
pub(super) fn current_turn_id(&self) -> Option<String> {
|
||||
self.current_turn.as_ref().map(|turn| turn.id.clone())
|
||||
}
|
||||
|
||||
pub(super) fn restore_current_turn(&mut self, turn_id: String) {
|
||||
self.current_turn = Some(
|
||||
self.new_turn(Some(turn_id))
|
||||
.with_status(TurnStatus::InProgress)
|
||||
.opened_explicitly(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Shared reducer for persisted rollout replay and in-memory current-turn
|
||||
/// tracking used by running thread resume/rejoin.
|
||||
///
|
||||
/// This function should handle all EventMsg variants that can be persisted in a rollout file.
|
||||
/// See `should_persist_event_msg` in `codex-rs/core/rollout/policy.rs`.
|
||||
pub fn handle_event(&mut self, event: &EventMsg) {
|
||||
pub(super) fn handle_event(&mut self, event: &EventMsg) {
|
||||
match event {
|
||||
EventMsg::UserMessage(payload) => self.handle_user_message(payload),
|
||||
EventMsg::AgentMessage(payload) => self.handle_agent_message(
|
||||
@@ -225,7 +236,7 @@ impl ThreadHistoryBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_rollout_item(&mut self, item: &RolloutItem) {
|
||||
pub(super) fn handle_rollout_item(&mut self, item: &RolloutItem) {
|
||||
self.current_rollout_index = self.next_rollout_index;
|
||||
self.next_rollout_index += 1;
|
||||
match item {
|
||||
@@ -236,6 +247,12 @@ impl ThreadHistoryBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn handle_rollout_items(&mut self, items: &[RolloutItem]) {
|
||||
for item in items {
|
||||
self.handle_rollout_item(item);
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_response_item(&mut self, item: &codex_protocol::models::ResponseItem) {
|
||||
let codex_protocol::models::ResponseItem::Message {
|
||||
role, content, id, ..
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
use crate::protocol::thread_history::ThreadHistoryState;
|
||||
use crate::protocol::v2::Turn;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::RolloutItem;
|
||||
|
||||
/// Convert persisted [`RolloutItem`] entries into a sequence of [`Turn`] values.
|
||||
///
|
||||
/// When available, this uses `TurnContext.turn_id` as the canonical turn id so
|
||||
/// resumed/rebuilt thread history preserves the original turn identifiers.
|
||||
pub fn build_turns_from_rollout_items(items: &[RolloutItem]) -> Vec<Turn> {
|
||||
let mut state = ThreadHistoryState::new();
|
||||
state.handle_rollout_items(items);
|
||||
state.finish()
|
||||
}
|
||||
|
||||
/// Full-history compatibility adapter over the event-to-turn reducer.
|
||||
pub struct ThreadHistoryBuilder {
|
||||
state: ThreadHistoryState,
|
||||
}
|
||||
|
||||
impl Default for ThreadHistoryBuilder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadHistoryBuilder {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
state: ThreadHistoryState::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.state = ThreadHistoryState::new();
|
||||
}
|
||||
|
||||
pub fn finish(self) -> Vec<Turn> {
|
||||
self.state.finish()
|
||||
}
|
||||
|
||||
pub fn active_turn_snapshot(&self) -> Option<Turn> {
|
||||
self.state.active_turn_snapshot()
|
||||
}
|
||||
|
||||
pub fn active_turn_position(&self) -> Option<usize> {
|
||||
self.state.active_turn_position()
|
||||
}
|
||||
|
||||
pub fn has_active_turn(&self) -> bool {
|
||||
self.state.has_active_turn()
|
||||
}
|
||||
|
||||
pub fn active_turn_id_if_explicit(&self) -> Option<String> {
|
||||
self.state.active_turn_id_if_explicit()
|
||||
}
|
||||
|
||||
pub fn active_turn_start_index(&self) -> Option<usize> {
|
||||
self.state.active_turn_start_index()
|
||||
}
|
||||
|
||||
pub fn handle_event(&mut self, event: &EventMsg) {
|
||||
self.state.handle_event(event);
|
||||
}
|
||||
|
||||
pub fn handle_rollout_item(&mut self, item: &RolloutItem) {
|
||||
self.state.handle_rollout_item(item);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
use crate::protocol::thread_history::ThreadHistoryState;
|
||||
use crate::protocol::v2::CollabAgentToolCallStatus;
|
||||
use crate::protocol::v2::CommandExecutionStatus;
|
||||
use crate::protocol::v2::DynamicToolCallStatus;
|
||||
use crate::protocol::v2::McpToolCallStatus;
|
||||
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::ThreadHistoryMutation;
|
||||
use codex_thread_store_protocol::ThreadHistoryMutationMetadata;
|
||||
use codex_thread_store_protocol::ThreadHistoryProjectionObserver;
|
||||
use codex_thread_store_protocol::ThreadItemMutation;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "thread_item_projection_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
/// Incremental thread-item materialization state that a durable store can persist between appends.
|
||||
///
|
||||
/// Persisting it lets the next append reuse stable item ordinals and update non-terminal
|
||||
/// ThreadItems without replaying the full rollout history first.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ThreadItemProjectionCheckpoint {
|
||||
pub next_thread_item_ordinal: i64,
|
||||
/// Next fallback `item-N` ThreadItem id index used when the source event has no durable id.
|
||||
pub next_generated_thread_item_id_index: i64,
|
||||
pub current_turn: Option<CurrentTurnThreadItemState>,
|
||||
pub current_reasoning_item: Option<ReasoningAccumulator>,
|
||||
pub open_items: HashMap<String, OpenThreadItemState>,
|
||||
}
|
||||
|
||||
/// Active turn fields needed by incremental thread item projection.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CurrentTurnThreadItemState {
|
||||
pub turn_id: String,
|
||||
}
|
||||
|
||||
/// Last reasoning item while reasoning deltas are still coalescing.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ReasoningAccumulator {
|
||||
pub turn_id: String,
|
||||
pub item_key: String,
|
||||
}
|
||||
|
||||
/// Latest durable identity for an item that may receive a later upsert.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct OpenThreadItemState {
|
||||
pub turn_id: String,
|
||||
pub item_ordinal: i64,
|
||||
}
|
||||
|
||||
/// Thread-item mutations emitted after applying one materialization batch.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ThreadItemProjectionOutputBatch {
|
||||
pub updated_checkpoint: ThreadItemProjectionCheckpoint,
|
||||
pub thread_history_mutations: Vec<ThreadHistoryMutation>,
|
||||
}
|
||||
|
||||
/// One raw append item reduced into before/after thread-history snapshots.
|
||||
#[derive(Clone, Debug)]
|
||||
struct ThreadItemProjectionObservation {
|
||||
before_turns: Vec<Turn>,
|
||||
after_turns: Vec<Turn>,
|
||||
}
|
||||
|
||||
/// Incrementally applies the event-to-turn reduction needed by ThreadItem materialization.
|
||||
struct ThreadItemProjectionReducer {
|
||||
state: ThreadHistoryState,
|
||||
}
|
||||
|
||||
impl ThreadItemProjectionReducer {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
state: ThreadHistoryState::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn materialized_turns(&self) -> Vec<Turn> {
|
||||
self.state.turns_snapshot()
|
||||
}
|
||||
|
||||
fn reduce_append(
|
||||
&mut self,
|
||||
persisted_rollout_items: &[RolloutItem],
|
||||
projection_source_events: &[RolloutItem],
|
||||
) -> Vec<ThreadItemProjectionObservation> {
|
||||
source_rollout_items(persisted_rollout_items, projection_source_events)
|
||||
.iter()
|
||||
.map(|item| {
|
||||
let before_turns = self.state.turns_snapshot();
|
||||
self.state.handle_rollout_item(item);
|
||||
ThreadItemProjectionObservation {
|
||||
before_turns,
|
||||
after_turns: self.state.turns_snapshot(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Observes append batches and emits only ThreadItem upserts and tombstones.
|
||||
pub struct ThreadItemProjectionObserver {
|
||||
reducer: ThreadItemProjectionReducer,
|
||||
checkpoint: ThreadItemProjectionCheckpoint,
|
||||
item_ordinals: HashMap<String, i64>,
|
||||
}
|
||||
|
||||
impl Default for ThreadItemProjectionObserver {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadItemProjectionObserver {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
reducer: ThreadItemProjectionReducer::new(),
|
||||
checkpoint: ThreadItemProjectionCheckpoint {
|
||||
next_thread_item_ordinal: 1,
|
||||
next_generated_thread_item_id_index: 1,
|
||||
..Default::default()
|
||||
},
|
||||
item_ordinals: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_checkpoint(checkpoint: ThreadItemProjectionCheckpoint) -> Self {
|
||||
let checkpoint = ThreadItemProjectionCheckpoint {
|
||||
next_thread_item_ordinal: checkpoint.next_thread_item_ordinal.max(1),
|
||||
next_generated_thread_item_id_index: checkpoint
|
||||
.next_generated_thread_item_id_index
|
||||
.max(1),
|
||||
..checkpoint
|
||||
};
|
||||
let item_ordinals = checkpoint
|
||||
.open_items
|
||||
.iter()
|
||||
.map(|(item_key, item)| (item_key.clone(), item.item_ordinal))
|
||||
.collect();
|
||||
let mut reducer = ThreadItemProjectionReducer::new();
|
||||
reducer
|
||||
.state
|
||||
.set_next_item_index(checkpoint.next_generated_thread_item_id_index);
|
||||
if let Some(current_turn) = checkpoint.current_turn.as_ref() {
|
||||
reducer
|
||||
.state
|
||||
.restore_current_turn(current_turn.turn_id.clone());
|
||||
}
|
||||
Self {
|
||||
reducer,
|
||||
checkpoint,
|
||||
item_ordinals,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn checkpoint(&self) -> &ThreadItemProjectionCheckpoint {
|
||||
&self.checkpoint
|
||||
}
|
||||
|
||||
pub fn materialized_turns(&self) -> Vec<Turn> {
|
||||
self.reducer.materialized_turns()
|
||||
}
|
||||
|
||||
pub fn observe_append(
|
||||
&mut self,
|
||||
persisted_rollout_items: &[RolloutItem],
|
||||
projection_source_events: &[RolloutItem],
|
||||
) -> ThreadItemProjectionOutputBatch {
|
||||
let mut thread_history_mutations = Vec::new();
|
||||
for observation in self
|
||||
.reducer
|
||||
.reduce_append(persisted_rollout_items, projection_source_events)
|
||||
{
|
||||
self.emit_upserted_thread_items(&observation, &mut thread_history_mutations);
|
||||
self.emit_removed_thread_items(&observation, &mut thread_history_mutations);
|
||||
}
|
||||
self.refresh_checkpoint();
|
||||
ThreadItemProjectionOutputBatch {
|
||||
updated_checkpoint: self.checkpoint.clone(),
|
||||
thread_history_mutations,
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_upserted_thread_items(
|
||||
&mut self,
|
||||
observation: &ThreadItemProjectionObservation,
|
||||
mutations: &mut Vec<ThreadHistoryMutation>,
|
||||
) {
|
||||
for turn in &observation.after_turns {
|
||||
let previous_turn = observation
|
||||
.before_turns
|
||||
.iter()
|
||||
.find(|previous| previous.id == turn.id);
|
||||
for item in &turn.items {
|
||||
let previous_item = previous_turn
|
||||
.and_then(|previous| previous.items.iter().find(|old| old.id() == item.id()));
|
||||
if previous_item == Some(item) {
|
||||
continue;
|
||||
}
|
||||
let item_key = item.id().to_string();
|
||||
let item_ordinal =
|
||||
*self
|
||||
.item_ordinals
|
||||
.entry(item_key.clone())
|
||||
.or_insert_with(|| {
|
||||
let item_ordinal = self.checkpoint.next_thread_item_ordinal;
|
||||
self.checkpoint.next_thread_item_ordinal += 1;
|
||||
item_ordinal
|
||||
});
|
||||
mutations.push(thread_item_mutation(json!({
|
||||
"turnId": turn.id,
|
||||
"itemKey": item_key,
|
||||
"itemOrdinal": item_ordinal,
|
||||
"mutationKind": "upsert",
|
||||
"isOpen": is_open_item(item),
|
||||
"materializedThreadItem": item,
|
||||
})));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_removed_thread_items(
|
||||
&self,
|
||||
observation: &ThreadItemProjectionObservation,
|
||||
mutations: &mut Vec<ThreadHistoryMutation>,
|
||||
) {
|
||||
for turn in &observation.before_turns {
|
||||
let current_turn = observation
|
||||
.after_turns
|
||||
.iter()
|
||||
.find(|current| current.id == turn.id);
|
||||
for item in &turn.items {
|
||||
if current_turn
|
||||
.and_then(|current| current.items.iter().find(|new| new.id() == item.id()))
|
||||
.is_some()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let item_key = item.id().to_string();
|
||||
let Some(item_ordinal) = self.item_ordinals.get(&item_key).copied() else {
|
||||
continue;
|
||||
};
|
||||
mutations.push(thread_item_mutation(json!({
|
||||
"turnId": turn.id,
|
||||
"itemKey": item_key,
|
||||
"itemOrdinal": item_ordinal,
|
||||
"mutationKind": "tombstone",
|
||||
"isOpen": false,
|
||||
"materializedThreadItem": item,
|
||||
})));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh_checkpoint(&mut self) {
|
||||
let turns = self.reducer.materialized_turns();
|
||||
self.checkpoint.next_generated_thread_item_id_index = self.reducer.state.next_item_index();
|
||||
self.checkpoint.current_turn = self
|
||||
.reducer
|
||||
.state
|
||||
.current_turn_id()
|
||||
.map(|turn_id| CurrentTurnThreadItemState { turn_id });
|
||||
self.checkpoint.current_reasoning_item = turns.last().and_then(|turn| {
|
||||
let item = turn.items.last()?;
|
||||
matches!(item, ThreadItem::Reasoning { .. }).then(|| ReasoningAccumulator {
|
||||
turn_id: turn.id.clone(),
|
||||
item_key: item.id().to_string(),
|
||||
})
|
||||
});
|
||||
self.checkpoint.open_items = turns
|
||||
.iter()
|
||||
.flat_map(|turn| {
|
||||
turn.items.iter().filter_map(|item| {
|
||||
if !is_open_item(item) {
|
||||
return None;
|
||||
}
|
||||
let item_key = item.id().to_string();
|
||||
let item_ordinal = self.item_ordinals.get(&item_key).copied()?;
|
||||
Some((
|
||||
item_key,
|
||||
OpenThreadItemState {
|
||||
turn_id: turn.id.clone(),
|
||||
item_ordinal,
|
||||
},
|
||||
))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadHistoryProjectionObserver for ThreadItemProjectionObserver {
|
||||
fn observe_append(
|
||||
&mut self,
|
||||
persisted_rollout_items: &[RolloutItem],
|
||||
projection_source_events: &[RolloutItem],
|
||||
) -> Vec<ThreadHistoryMutation> {
|
||||
ThreadItemProjectionObserver::observe_append(
|
||||
self,
|
||||
persisted_rollout_items,
|
||||
projection_source_events,
|
||||
)
|
||||
.thread_history_mutations
|
||||
}
|
||||
}
|
||||
|
||||
fn thread_item_mutation(payload: serde_json::Value) -> ThreadHistoryMutation {
|
||||
ThreadHistoryMutation::ThreadItem(ThreadItemMutation {
|
||||
metadata: mutation_metadata(),
|
||||
payload,
|
||||
})
|
||||
}
|
||||
|
||||
fn mutation_metadata() -> ThreadHistoryMutationMetadata {
|
||||
ThreadHistoryMutationMetadata { schema_version: 1 }
|
||||
}
|
||||
|
||||
fn source_rollout_items<'a>(
|
||||
persisted_rollout_items: &'a [RolloutItem],
|
||||
projection_source_events: &'a [RolloutItem],
|
||||
) -> &'a [RolloutItem] {
|
||||
if projection_source_events.is_empty() {
|
||||
persisted_rollout_items
|
||||
} else {
|
||||
projection_source_events
|
||||
}
|
||||
}
|
||||
|
||||
fn is_open_item(item: &ThreadItem) -> bool {
|
||||
match item {
|
||||
ThreadItem::CommandExecution { status, .. } => {
|
||||
matches!(status, CommandExecutionStatus::InProgress)
|
||||
}
|
||||
ThreadItem::McpToolCall { status, .. } => matches!(status, McpToolCallStatus::InProgress),
|
||||
ThreadItem::DynamicToolCall { status, .. } => {
|
||||
matches!(status, DynamicToolCallStatus::InProgress)
|
||||
}
|
||||
ThreadItem::CollabAgentToolCall { status, .. } => {
|
||||
matches!(status, CollabAgentToolCallStatus::InProgress)
|
||||
}
|
||||
ThreadItem::WebSearch { action, .. } => action.is_none(),
|
||||
ThreadItem::ImageGeneration { status, .. } => status.is_empty(),
|
||||
ThreadItem::FileChange { status, .. } => matches!(status, PatchApplyStatus::InProgress),
|
||||
ThreadItem::UserMessage { .. }
|
||||
| ThreadItem::HookPrompt { .. }
|
||||
| ThreadItem::AgentMessage { .. }
|
||||
| ThreadItem::Plan { .. }
|
||||
| ThreadItem::Reasoning { .. }
|
||||
| ThreadItem::ImageView { .. }
|
||||
| ThreadItem::EnteredReviewMode { .. }
|
||||
| ThreadItem::ExitedReviewMode { .. }
|
||||
| ThreadItem::ContextCompaction { .. } => false,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
use super::*;
|
||||
use codex_protocol::parse_command::ParsedCommand;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::ExecCommandBeginEvent;
|
||||
use codex_protocol::protocol::ExecCommandEndEvent;
|
||||
use codex_protocol::protocol::ExecCommandSource;
|
||||
use codex_protocol::protocol::ExecCommandStatus as CoreExecCommandStatus;
|
||||
use codex_protocol::protocol::RolloutItem;
|
||||
use codex_protocol::protocol::TurnStartedEvent;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use codex_utils_absolute_path::test_support::test_path_buf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn reuses_thread_item_ordinal_for_open_item_upserts() {
|
||||
let mut observer = ThreadItemProjectionObserver::new();
|
||||
let begin_projection_source_events = vec![
|
||||
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::ExecCommandBegin(ExecCommandBeginEvent {
|
||||
call_id: "exec-1".into(),
|
||||
process_id: Some("pid-1".into()),
|
||||
turn_id: "turn-a".into(),
|
||||
started_at_ms: 0,
|
||||
command: vec!["echo".into(), "hello".into()],
|
||||
cwd: test_path_buf("/tmp").abs(),
|
||||
parsed_cmd: vec![ParsedCommand::Unknown {
|
||||
cmd: "echo hello".into(),
|
||||
}],
|
||||
source: ExecCommandSource::Agent,
|
||||
interaction_input: None,
|
||||
})),
|
||||
];
|
||||
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 end_projection_source_events = vec![RolloutItem::EventMsg(EventMsg::ExecCommandEnd(
|
||||
ExecCommandEndEvent {
|
||||
call_id: "exec-1".into(),
|
||||
process_id: Some("pid-1".into()),
|
||||
turn_id: "turn-a".into(),
|
||||
completed_at_ms: 1,
|
||||
command: vec!["echo".into(), "hello".into()],
|
||||
cwd: test_path_buf("/tmp").abs(),
|
||||
parsed_cmd: vec![ParsedCommand::Unknown {
|
||||
cmd: "echo hello".into(),
|
||||
}],
|
||||
source: ExecCommandSource::Agent,
|
||||
interaction_input: None,
|
||||
stdout: "hello\n".into(),
|
||||
stderr: String::new(),
|
||||
aggregated_output: "hello\n".into(),
|
||||
exit_code: 0,
|
||||
duration: Duration::from_millis(1),
|
||||
formatted_output: "hello\n".into(),
|
||||
status: CoreExecCommandStatus::Completed,
|
||||
},
|
||||
))];
|
||||
let end_mutations = resumed_observer
|
||||
.observe_append(&[], &end_projection_source_events)
|
||||
.thread_history_mutations;
|
||||
|
||||
let begin_payload = only_thread_item_payload(begin_mutations);
|
||||
let end_payload = only_thread_item_payload(end_mutations);
|
||||
assert_eq!(begin_payload["itemOrdinal"], end_payload["itemOrdinal"]);
|
||||
assert_eq!(begin_payload["isOpen"], true);
|
||||
assert_eq!(end_payload["isOpen"], false);
|
||||
}
|
||||
|
||||
fn only_thread_item_payload(mutations: Vec<ThreadHistoryMutation>) -> Value {
|
||||
let mut payloads = mutations.into_iter().filter_map(|mutation| match mutation {
|
||||
ThreadHistoryMutation::ThreadItem(mutation) => Some(mutation.payload),
|
||||
ThreadHistoryMutation::TurnSummary(_) | ThreadHistoryMutation::Lifecycle(_) => None,
|
||||
});
|
||||
let payload = payloads.next().expect("thread item mutation");
|
||||
assert!(payloads.next().is_none());
|
||||
payload
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
use crate::protocol::v2::TurnStatus;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::RolloutItem;
|
||||
use codex_thread_store_protocol::ThreadHistoryMutation;
|
||||
use codex_thread_store_protocol::ThreadHistoryMutationMetadata;
|
||||
use codex_thread_store_protocol::ThreadHistoryProjectionObserver;
|
||||
use codex_thread_store_protocol::TurnSummaryMutation;
|
||||
use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "turn_summary_projection_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
/// Observes append batches and emits only turn-summary mutations.
|
||||
pub struct TurnSummaryProjectionObserver {
|
||||
current_turn_id: Option<String>,
|
||||
turn_order: Vec<String>,
|
||||
summaries: HashMap<String, TurnSummaryState>,
|
||||
}
|
||||
|
||||
impl Default for TurnSummaryProjectionObserver {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl TurnSummaryProjectionObserver {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
current_turn_id: None,
|
||||
turn_order: Vec::new(),
|
||||
summaries: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn observe_append(
|
||||
&mut self,
|
||||
persisted_rollout_items: &[RolloutItem],
|
||||
projection_source_events: &[RolloutItem],
|
||||
) -> Vec<ThreadHistoryMutation> {
|
||||
source_rollout_items(persisted_rollout_items, projection_source_events)
|
||||
.iter()
|
||||
.filter_map(|rollout_item| self.observe_item(rollout_item))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn observe_item(&mut self, rollout_item: &RolloutItem) -> Option<ThreadHistoryMutation> {
|
||||
let RolloutItem::EventMsg(event) = rollout_item else {
|
||||
return None;
|
||||
};
|
||||
let (turn_id, summary) = match event {
|
||||
EventMsg::TurnStarted(payload) => {
|
||||
let summary = TurnSummaryState {
|
||||
status: TurnStatus::InProgress,
|
||||
started_at: payload.started_at,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
};
|
||||
self.upsert_summary(payload.turn_id.clone(), summary.clone());
|
||||
self.current_turn_id = Some(payload.turn_id.clone());
|
||||
(payload.turn_id.clone(), summary)
|
||||
}
|
||||
EventMsg::TurnComplete(payload) => {
|
||||
let turn_id = self
|
||||
.summaries
|
||||
.contains_key(&payload.turn_id)
|
||||
.then(|| payload.turn_id.clone())
|
||||
.or_else(|| self.current_turn_id.clone())?;
|
||||
let summary = self.update_summary(&turn_id, |summary| {
|
||||
if matches!(
|
||||
summary.status,
|
||||
TurnStatus::Completed | TurnStatus::InProgress
|
||||
) {
|
||||
summary.status = TurnStatus::Completed;
|
||||
}
|
||||
summary.completed_at = payload.completed_at;
|
||||
summary.duration_ms = payload.duration_ms;
|
||||
});
|
||||
if self.current_turn_id.as_deref() == Some(turn_id.as_str()) {
|
||||
self.current_turn_id = None;
|
||||
}
|
||||
(turn_id, summary)
|
||||
}
|
||||
EventMsg::TurnAborted(payload) => {
|
||||
let turn_id = payload
|
||||
.turn_id
|
||||
.clone()
|
||||
.filter(|turn_id| self.summaries.contains_key(turn_id))
|
||||
.or_else(|| self.current_turn_id.clone())?;
|
||||
let summary = self.update_summary(&turn_id, |summary| {
|
||||
summary.status = TurnStatus::Interrupted;
|
||||
summary.completed_at = payload.completed_at;
|
||||
summary.duration_ms = payload.duration_ms;
|
||||
});
|
||||
(turn_id, summary)
|
||||
}
|
||||
EventMsg::Error(payload) if payload.affects_turn_status() => {
|
||||
let turn_id = self.current_turn_id.clone()?;
|
||||
let summary = self.update_summary(&turn_id, |summary| {
|
||||
summary.status = TurnStatus::Failed;
|
||||
});
|
||||
(turn_id, summary)
|
||||
}
|
||||
EventMsg::ThreadRolledBack(payload) => {
|
||||
self.roll_back(payload.num_turns);
|
||||
return None;
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some(turn_summary_mutation(&turn_id, &summary))
|
||||
}
|
||||
|
||||
fn upsert_summary(&mut self, turn_id: String, summary: TurnSummaryState) {
|
||||
if !self.summaries.contains_key(&turn_id) {
|
||||
self.turn_order.push(turn_id.clone());
|
||||
}
|
||||
self.summaries.insert(turn_id, summary);
|
||||
}
|
||||
|
||||
fn update_summary(
|
||||
&mut self,
|
||||
turn_id: &str,
|
||||
update: impl FnOnce(&mut TurnSummaryState),
|
||||
) -> TurnSummaryState {
|
||||
let summary = self
|
||||
.summaries
|
||||
.entry(turn_id.to_string())
|
||||
.or_insert_with(TurnSummaryState::default);
|
||||
update(summary);
|
||||
summary.clone()
|
||||
}
|
||||
|
||||
fn roll_back(&mut self, num_turns: u32) {
|
||||
let num_turns = usize::try_from(num_turns).unwrap_or(usize::MAX);
|
||||
for _ in 0..num_turns.min(self.turn_order.len()) {
|
||||
let Some(turn_id) = self.turn_order.pop() else {
|
||||
return;
|
||||
};
|
||||
self.summaries.remove(&turn_id);
|
||||
if self.current_turn_id.as_deref() == Some(turn_id.as_str()) {
|
||||
self.current_turn_id = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadHistoryProjectionObserver for TurnSummaryProjectionObserver {
|
||||
fn observe_append(
|
||||
&mut self,
|
||||
persisted_rollout_items: &[RolloutItem],
|
||||
projection_source_events: &[RolloutItem],
|
||||
) -> Vec<ThreadHistoryMutation> {
|
||||
TurnSummaryProjectionObserver::observe_append(
|
||||
self,
|
||||
persisted_rollout_items,
|
||||
projection_source_events,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TurnSummaryState {
|
||||
status: TurnStatus,
|
||||
started_at: Option<i64>,
|
||||
completed_at: Option<i64>,
|
||||
duration_ms: Option<i64>,
|
||||
}
|
||||
|
||||
impl Default for TurnSummaryState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
status: TurnStatus::Completed,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn turn_summary_mutation(turn_id: &str, summary: &TurnSummaryState) -> ThreadHistoryMutation {
|
||||
ThreadHistoryMutation::TurnSummary(TurnSummaryMutation {
|
||||
metadata: mutation_metadata(),
|
||||
payload: json!({
|
||||
"turnId": turn_id,
|
||||
"mutation": {
|
||||
"status": summary.status,
|
||||
"startedAt": summary.started_at,
|
||||
"completedAt": summary.completed_at,
|
||||
"durationMs": summary.duration_ms,
|
||||
},
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
fn mutation_metadata() -> ThreadHistoryMutationMetadata {
|
||||
ThreadHistoryMutationMetadata { schema_version: 1 }
|
||||
}
|
||||
|
||||
fn source_rollout_items<'a>(
|
||||
persisted_rollout_items: &'a [RolloutItem],
|
||||
projection_source_events: &'a [RolloutItem],
|
||||
) -> &'a [RolloutItem] {
|
||||
if projection_source_events.is_empty() {
|
||||
persisted_rollout_items
|
||||
} else {
|
||||
projection_source_events
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
use super::*;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::RolloutItem;
|
||||
use codex_protocol::protocol::TurnCompleteEvent;
|
||||
use codex_protocol::protocol::TurnStartedEvent;
|
||||
use codex_protocol::protocol::UserMessageEvent;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn ignores_item_only_events_between_turn_summary_updates() {
|
||||
let mut observer = TurnSummaryProjectionObserver::new();
|
||||
let persisted_rollout_items = vec![
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
|
||||
turn_id: "turn-a".into(),
|
||||
trace_id: None,
|
||||
started_at: Some(10),
|
||||
model_context_window: None,
|
||||
collaboration_mode_kind: Default::default(),
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
|
||||
client_id: None,
|
||||
message: "hello".into(),
|
||||
images: None,
|
||||
text_elements: Vec::new(),
|
||||
local_images: Vec::new(),
|
||||
..Default::default()
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent {
|
||||
turn_id: "turn-a".into(),
|
||||
last_agent_message: None,
|
||||
completed_at: Some(11),
|
||||
duration_ms: Some(1_000),
|
||||
time_to_first_token_ms: None,
|
||||
})),
|
||||
];
|
||||
let mutations = observer.observe_append(&persisted_rollout_items, &[]);
|
||||
|
||||
assert_eq!(
|
||||
turn_summary_payloads(mutations),
|
||||
vec![
|
||||
json!({
|
||||
"turnId": "turn-a",
|
||||
"mutation": {
|
||||
"status": "inProgress",
|
||||
"startedAt": 10,
|
||||
"completedAt": null,
|
||||
"durationMs": null,
|
||||
},
|
||||
}),
|
||||
json!({
|
||||
"turnId": "turn-a",
|
||||
"mutation": {
|
||||
"status": "completed",
|
||||
"startedAt": 10,
|
||||
"completedAt": 11,
|
||||
"durationMs": 1_000,
|
||||
},
|
||||
}),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
fn turn_summary_payloads(mutations: Vec<ThreadHistoryMutation>) -> Vec<serde_json::Value> {
|
||||
mutations
|
||||
.into_iter()
|
||||
.map(|mutation| match mutation {
|
||||
ThreadHistoryMutation::TurnSummary(mutation) => mutation.payload,
|
||||
ThreadHistoryMutation::ThreadItem(_) | ThreadHistoryMutation::Lifecycle(_) => {
|
||||
panic!("turn summary observer emitted non-turn-summary mutation")
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
Reference in New Issue
Block a user