Files
codex/codex-rs/core/src/context_manager/updates.rs
T
pakrym-oai 0df76892b1 Support ordered response items in world-state context updates (#50441)
## Why

World-state sections could return only a single optional text fragment, with message separation controlled by the fragment itself. They could not contribute explicit `ResponseItem` values alongside instructions.

## What changed

- Let sections return ordered `WorldStateUpdate` values containing fragments or response items, with `Prefix`, `Standalone`, or `Mergeable` placement.
- Preserve explicit item boundaries when grouping context updates, and place prefix updates first when assembling initial context.
- Move standalone-message decisions from fragments to world-state updates and retain snapshot handling.

## Testing

Add tests for mixed fragment/item ordering, role and standalone boundaries, initial-context prefix placement, and snapshot restoration without repeated updates.

GitOrigin-RevId: c2514c3c98538da83f5140c10a9d89f531de6549
2026-10-02 22:12:07 +00:00

63 lines
2.3 KiB
Rust

//! Groups contextual fragments without moving them across explicit response items.
use crate::context::world_state::Placement;
use crate::context::world_state::WorldStateUpdate;
use crate::context::world_state::WorldStateUpdateContent;
use codex_context_fragments::RenderedFragment;
use codex_protocol::models::InternalChatMessageMetadataPassthrough;
use codex_protocol::models::ResponseItem;
pub(crate) fn build_rendered_message(fragments: Vec<RenderedFragment>) -> Option<ResponseItem> {
let role = fragments.first()?.role();
debug_assert!(fragments.iter().all(|fragment| fragment.role() == role));
let (content, content_item_kinds): (Vec<_>, Vec<_>) = fragments
.into_iter()
.map(|fragment| fragment.into_parts().1.into_parts())
.unzip();
Some(ResponseItem::Message {
id: None,
role: role.to_string(),
content,
phase: None,
internal_chat_message_metadata_passthrough: Some(InternalChatMessageMetadataPassthrough {
content_item_kinds: Some(content_item_kinds),
..Default::default()
}),
})
}
pub(crate) fn merge_world_state_updates(updates: Vec<WorldStateUpdate>) -> Vec<ResponseItem> {
let mut items = Vec::new();
let mut pending = Vec::<RenderedFragment>::new();
for update in updates {
let fragment = match update.content {
WorldStateUpdateContent::Fragment(fragment) => fragment,
WorldStateUpdateContent::Item(item) => {
items.extend(build_rendered_message(std::mem::take(&mut pending)));
items.push(*item);
continue;
}
};
let rendered = fragment.render_fragment();
if update.placement != Placement::Mergeable {
items.extend(build_rendered_message(std::mem::take(&mut pending)));
items.extend(build_rendered_message(vec![rendered]));
continue;
}
if pending
.first()
.is_some_and(|previous| previous.role() != rendered.role())
{
items.extend(build_rendered_message(std::mem::take(&mut pending)));
}
pending.push(rendered);
}
items.extend(build_rendered_message(pending));
items
}
#[cfg(test)]
#[path = "updates_tests.rs"]
mod tests;