mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
include summary items in turn projections
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
use crate::protocol::thread_history::ThreadHistoryState;
|
||||
use crate::protocol::v2::ThreadItem;
|
||||
use crate::protocol::v2::Turn;
|
||||
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;
|
||||
@@ -14,8 +16,7 @@ mod tests;
|
||||
|
||||
/// Observes append batches and emits only turn-summary mutations.
|
||||
pub struct TurnSummaryProjectionObserver {
|
||||
current_turn_id: Option<String>,
|
||||
turn_order: Vec<String>,
|
||||
reducer: ThreadHistoryState,
|
||||
summaries: HashMap<String, TurnSummaryState>,
|
||||
}
|
||||
|
||||
@@ -28,8 +29,7 @@ impl Default for TurnSummaryProjectionObserver {
|
||||
impl TurnSummaryProjectionObserver {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
current_turn_id: None,
|
||||
turn_order: Vec::new(),
|
||||
reducer: ThreadHistoryState::new(),
|
||||
summaries: HashMap::new(),
|
||||
}
|
||||
}
|
||||
@@ -39,106 +39,23 @@ impl TurnSummaryProjectionObserver {
|
||||
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;
|
||||
let mut mutations = Vec::new();
|
||||
for rollout_item in source_rollout_items(persisted_rollout_items, projection_source_events)
|
||||
{
|
||||
self.reducer.handle_rollout_item(rollout_item);
|
||||
let turns = self.reducer.turns_snapshot();
|
||||
self.summaries
|
||||
.retain(|turn_id, _summary| turns.iter().any(|turn| turn.id == *turn_id));
|
||||
for turn in turns {
|
||||
let summary = TurnSummaryState::from_turn(&turn);
|
||||
if self.summaries.get(&turn.id) == Some(&summary) {
|
||||
continue;
|
||||
}
|
||||
(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_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;
|
||||
self.summaries.insert(turn.id.clone(), summary.clone());
|
||||
mutations.push(turn_summary_mutation(&turn.id, &summary));
|
||||
}
|
||||
}
|
||||
mutations
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,21 +73,45 @@ impl ThreadHistoryProjectionObserver for TurnSummaryProjectionObserver {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct TurnSummaryState {
|
||||
status: TurnStatus,
|
||||
started_at: Option<i64>,
|
||||
completed_at: Option<i64>,
|
||||
duration_ms: Option<i64>,
|
||||
summary_items: Vec<ThreadItem>,
|
||||
}
|
||||
|
||||
impl Default for TurnSummaryState {
|
||||
fn default() -> Self {
|
||||
impl TurnSummaryState {
|
||||
fn from_turn(turn: &Turn) -> Self {
|
||||
let first_user_message = turn
|
||||
.items
|
||||
.iter()
|
||||
.find(|item| matches!(item, ThreadItem::UserMessage { .. }))
|
||||
.cloned();
|
||||
let final_agent_message = turn
|
||||
.items
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|item| matches!(item, ThreadItem::AgentMessage { .. }))
|
||||
.cloned();
|
||||
let summary_items = match (first_user_message, final_agent_message) {
|
||||
(Some(user_message), Some(agent_message))
|
||||
if user_message.id() != agent_message.id() =>
|
||||
{
|
||||
vec![user_message, agent_message]
|
||||
}
|
||||
(Some(user_message), Some(_agent_message)) => vec![user_message],
|
||||
(Some(user_message), None) => vec![user_message],
|
||||
(None, Some(agent_message)) => vec![agent_message],
|
||||
(None, None) => Vec::new(),
|
||||
};
|
||||
Self {
|
||||
status: TurnStatus::Completed,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
status: turn.status.clone(),
|
||||
started_at: turn.started_at,
|
||||
completed_at: turn.completed_at,
|
||||
duration_ms: turn.duration_ms,
|
||||
summary_items,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -185,6 +126,7 @@ fn turn_summary_mutation(turn_id: &str, summary: &TurnSummaryState) -> ThreadHis
|
||||
"startedAt": summary.started_at,
|
||||
"completedAt": summary.completed_at,
|
||||
"durationMs": summary.duration_ms,
|
||||
"summaryItems": summary.summary_items,
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use codex_protocol::protocol::AgentMessageEvent;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::RolloutItem;
|
||||
use codex_protocol::protocol::TurnCompleteEvent;
|
||||
@@ -8,7 +9,7 @@ use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn ignores_item_only_events_between_turn_summary_updates() {
|
||||
fn emits_turn_summary_mutations_with_summary_items() {
|
||||
let mut observer = TurnSummaryProjectionObserver::new();
|
||||
let persisted_rollout_items = vec![
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
|
||||
@@ -26,6 +27,16 @@ fn ignores_item_only_events_between_turn_summary_updates() {
|
||||
local_images: Vec::new(),
|
||||
..Default::default()
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::AgentMessage(AgentMessageEvent {
|
||||
message: "first answer".into(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::AgentMessage(AgentMessageEvent {
|
||||
message: "final answer".into(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent {
|
||||
turn_id: "turn-a".into(),
|
||||
last_agent_message: None,
|
||||
@@ -46,6 +57,90 @@ fn ignores_item_only_events_between_turn_summary_updates() {
|
||||
"startedAt": 10,
|
||||
"completedAt": null,
|
||||
"durationMs": null,
|
||||
"summaryItems": [],
|
||||
},
|
||||
}),
|
||||
json!({
|
||||
"turnId": "turn-a",
|
||||
"mutation": {
|
||||
"status": "inProgress",
|
||||
"startedAt": 10,
|
||||
"completedAt": null,
|
||||
"durationMs": null,
|
||||
"summaryItems": [
|
||||
{
|
||||
"type": "userMessage",
|
||||
"id": "item-1",
|
||||
"clientId": null,
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "hello",
|
||||
"text_elements": [],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
json!({
|
||||
"turnId": "turn-a",
|
||||
"mutation": {
|
||||
"status": "inProgress",
|
||||
"startedAt": 10,
|
||||
"completedAt": null,
|
||||
"durationMs": null,
|
||||
"summaryItems": [
|
||||
{
|
||||
"type": "userMessage",
|
||||
"id": "item-1",
|
||||
"clientId": null,
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "hello",
|
||||
"text_elements": [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
"type": "agentMessage",
|
||||
"id": "item-2",
|
||||
"text": "first answer",
|
||||
"phase": null,
|
||||
"memoryCitation": null,
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
json!({
|
||||
"turnId": "turn-a",
|
||||
"mutation": {
|
||||
"status": "inProgress",
|
||||
"startedAt": 10,
|
||||
"completedAt": null,
|
||||
"durationMs": null,
|
||||
"summaryItems": [
|
||||
{
|
||||
"type": "userMessage",
|
||||
"id": "item-1",
|
||||
"clientId": null,
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "hello",
|
||||
"text_elements": [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
"type": "agentMessage",
|
||||
"id": "item-3",
|
||||
"text": "final answer",
|
||||
"phase": null,
|
||||
"memoryCitation": null,
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
json!({
|
||||
@@ -55,6 +150,27 @@ fn ignores_item_only_events_between_turn_summary_updates() {
|
||||
"startedAt": 10,
|
||||
"completedAt": 11,
|
||||
"durationMs": 1_000,
|
||||
"summaryItems": [
|
||||
{
|
||||
"type": "userMessage",
|
||||
"id": "item-1",
|
||||
"clientId": null,
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "hello",
|
||||
"text_elements": [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
"type": "agentMessage",
|
||||
"id": "item-3",
|
||||
"text": "final answer",
|
||||
"phase": null,
|
||||
"memoryCitation": null,
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user