Carry fork lineage in initial history

This commit is contained in:
Ahmed Ibrahim
2026-06-15 23:01:19 -07:00
parent 1e015884c5
commit d944966608
17 changed files with 216 additions and 147 deletions
@@ -404,6 +404,7 @@ use codex_protocol::protocol::ConversationStartParams;
use codex_protocol::protocol::ConversationStartTransport;
use codex_protocol::protocol::ConversationTextParams;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ForkedHistory;
#[cfg(test)]
use codex_protocol::protocol::GitInfo as CoreGitInfo;
use codex_protocol::protocol::InitialHistory;
@@ -2597,7 +2597,7 @@ impl ThreadRequestProcessor {
let include_turns = !exclude_turns;
let resume_result = if let Some(history) = history {
self.resume_thread_from_history(history.as_slice())
self.resume_thread_from_history(&thread_id, history.as_slice())
.await
.map(|thread_history| (thread_history, None))
} else if let Some(stored_thread) = stored_thread_from_running_probe {
@@ -3034,18 +3034,20 @@ impl ThreadRequestProcessor {
#[tracing::instrument(level = "trace", skip_all)]
async fn resume_thread_from_history(
&self,
thread_id: &str,
history: &[ResponseItem],
) -> Result<InitialHistory, JSONRPCErrorError> {
if history.is_empty() {
return Err(invalid_request("history must not be empty"));
}
Ok(InitialHistory::Forked(
history
Ok(InitialHistory::Forked(ForkedHistory {
parent_id: ThreadId::from_string(thread_id).ok(),
history: history
.iter()
.cloned()
.map(RolloutItem::ResponseItem)
.collect(),
))
}))
}
#[tracing::instrument(level = "trace", skip_all)]
@@ -3227,14 +3229,15 @@ impl ThreadRequestProcessor {
}
}
}
InitialHistory::Forked(items) => {
InitialHistory::Forked(forked) => {
let mut thread = build_thread_from_snapshot(
thread_id,
session_id.clone(),
&config_snapshot,
Some(rollout_path.into()),
);
thread.preview = preview_from_rollout_items(items);
thread.preview = preview_from_rollout_items(&forked.history);
thread.forked_from_id = forked.parent_id.map(|id| id.to_string());
Ok(thread)
}
InitialHistory::New | InitialHistory::Cleared => Err(format!(
@@ -3448,6 +3448,7 @@ async fn thread_resume_supports_history_and_overrides() -> Result<()> {
let RestartedThreadFixture {
mut mcp, thread_id, ..
} = start_materialized_thread_and_restart(codex_home.path(), "seed history").await?;
let expected_forked_from_id = thread_id.clone();
let history_text = "Hello from history";
let history = vec![ResponseItem::Message {
@@ -3480,10 +3481,64 @@ async fn thread_resume_supports_history_and_overrides() -> Result<()> {
model_provider,
..
} = to_response::<ThreadResumeResponse>(resume_resp)?;
assert!(!resumed.id.is_empty());
assert_eq!(model_provider, "mock_provider");
assert_eq!(resumed.preview, history_text);
assert_eq!(resumed.status, ThreadStatus::Idle);
assert_eq!(
(
resumed.id.is_empty(),
model_provider.as_str(),
resumed.preview.as_str(),
resumed.status,
resumed.forked_from_id,
),
(
false,
"mock_provider",
history_text,
ThreadStatus::Idle,
Some(expected_forked_from_id),
)
);
Ok(())
}
#[tokio::test]
async fn thread_resume_history_accepts_placeholder_thread_id() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), &server.uri())?;
let RestartedThreadFixture { mut mcp, .. } =
start_materialized_thread_and_restart(codex_home.path(), "seed history").await?;
let history_text = "Hello from supplied history";
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
thread_id: "placeholder".to_string(),
history: Some(vec![ResponseItem::Message {
id: None,
role: "user".to_string(),
content: vec![ContentItem::InputText {
text: history_text.to_string(),
}],
phase: None,
metadata: None,
}]),
..Default::default()
})
.await?;
let resume_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(resume_id)),
)
.await??;
let ThreadResumeResponse {
thread: resumed, ..
} = to_response::<ThreadResumeResponse>(resume_resp)?;
assert_eq!(
(resumed.preview.as_str(), resumed.forked_from_id),
(history_text, None)
);
Ok(())
}
+1
View File
@@ -21,6 +21,7 @@ use codex_protocol::error::Result as CodexResult;
use codex_protocol::models::ContentItem;
use codex_protocol::models::MessagePhase;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::ForkedHistory;
use codex_protocol::protocol::InitialHistory;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::MultiAgentVersion;
@@ -139,7 +139,6 @@ async fn spawn_v2_subagent(
control.clone(),
SessionSource::SubAgent(SubAgentSource::Other(label.to_string())),
Some(parent_thread_id),
/*forked_from_thread_id*/ None,
Some(ThreadSource::Subagent),
/*metrics_service_name*/ None,
/*inherited_environments*/ None,
+4 -5
View File
@@ -204,7 +204,6 @@ impl AgentControl {
&InitialHistory::New,
session_source.as_ref(),
options.parent_thread_id,
/*forked_from_thread_id*/ None,
&config,
)
.await;
@@ -280,7 +279,6 @@ impl AgentControl {
self.clone(),
session_source,
options.parent_thread_id,
/*forked_from_thread_id*/ None,
/*thread_source*/ Some(ThreadSource::Subagent),
/*metrics_service_name*/ None,
inheritance.environments,
@@ -507,12 +505,14 @@ impl AgentControl {
state
.fork_thread_with_source(
config.clone(),
InitialHistory::Forked(forked_rollout_items),
InitialHistory::Forked(ForkedHistory {
parent_id: Some(parent_thread_id),
history: forked_rollout_items,
}),
self.clone(),
session_source,
/*thread_source*/ Some(ThreadSource::Subagent),
/*parent_thread_id*/ Some(parent_thread_id),
/*forked_from_thread_id*/ Some(parent_thread_id),
inherited_environments,
inherited_exec_policy,
options.environments.clone(),
@@ -629,7 +629,6 @@ impl AgentControl {
&initial_history,
Some(&session_source),
parent_thread_id,
/*forked_from_thread_id*/ None,
&config,
)
.await;
-2
View File
@@ -79,7 +79,6 @@ pub(crate) async fn run_codex_thread_interactive(
let (tx_sub, rx_sub) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY);
let (tx_ops, rx_ops) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY);
let conversation_history = initial_history.unwrap_or(InitialHistory::New);
let forked_from_thread_id = conversation_history.forked_from_id();
let user_instructions = LoadedUserInstructions {
instructions: parent_session.user_instructions().await,
warnings: Vec::new(),
@@ -100,7 +99,6 @@ pub(crate) async fn run_codex_thread_interactive(
extensions: Arc::clone(&parent_session.services.extensions),
conversation_history,
session_source: SessionSource::SubAgent(subagent_source.clone()),
forked_from_thread_id,
parent_thread_id: Some(parent_session.thread_id),
thread_source: Some(ThreadSource::Subagent),
agent_control: parent_session.services.agent_control.clone(),
+6 -2
View File
@@ -21,6 +21,7 @@ use codex_protocol::protocol::CodexErrorInfo;
use codex_protocol::protocol::ErrorEvent;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ForkedHistory;
use codex_protocol::protocol::InitialHistory;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::RolloutItem;
@@ -236,7 +237,10 @@ impl GuardianReviewSession {
let prior_review_count = state.prior_review_count;
let last_reviewed_transcript_cursor = state.last_reviewed_transcript_cursor;
state.last_committed_fork_snapshot = Some(GuardianReviewForkSnapshot {
initial_history: InitialHistory::Forked(items),
initial_history: InitialHistory::Forked(ForkedHistory {
parent_id: Some(self.codex.session.thread_id()),
history: items,
}),
prior_review_count,
last_reviewed_transcript_cursor,
});
@@ -496,7 +500,7 @@ impl GuardianReviewSessionManager {
let state = trunk.state.lock().await;
let snapshot = state.last_committed_fork_snapshot.as_ref()?;
match &snapshot.initial_history {
InitialHistory::Forked(items) => Some(items.clone()),
InitialHistory::Forked(forked) => Some(forked.history.clone()),
InitialHistory::New | InitialHistory::Cleared | InitialHistory::Resumed(_) => None,
}
}
+6 -8
View File
@@ -415,7 +415,6 @@ pub(crate) struct CodexSpawnArgs {
pub(crate) extensions: Arc<codex_extension_api::ExtensionRegistry<crate::config::Config>>,
pub(crate) conversation_history: InitialHistory,
pub(crate) session_source: SessionSource,
pub(crate) forked_from_thread_id: Option<ThreadId>,
pub(crate) parent_thread_id: Option<ThreadId>,
pub(crate) thread_source: Option<ThreadSource>,
pub(crate) agent_control: AgentControl,
@@ -501,7 +500,6 @@ impl Codex {
extensions,
conversation_history,
session_source,
forked_from_thread_id,
parent_thread_id,
thread_source,
agent_control,
@@ -628,7 +626,7 @@ impl Codex {
app_server_client_name: None,
app_server_client_version: None,
session_source,
forked_from_thread_id,
forked_from_thread_id: conversation_history.forked_from_id(),
parent_thread_id,
thread_source,
dynamic_tools,
@@ -1279,21 +1277,21 @@ impl Session {
let _ = self.flush_rollout().await;
}
}
InitialHistory::Forked(rollout_items) => {
InitialHistory::Forked(forked) => {
let turn_context = self.new_default_turn().await;
self.apply_rollout_reconstruction(&turn_context, &rollout_items)
self.apply_rollout_reconstruction(&turn_context, &forked.history)
.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) {
if let Some(info) = Self::last_token_info_from_rollout(&forked.history) {
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;
if !forked.history.is_empty() {
self.persist_rollout_items(&forked.history).await;
}
// Forked threads should remain file-backed immediately after startup.
+6 -10
View File
@@ -496,14 +496,10 @@ impl Session {
session_configuration.collaboration_mode.model(),
session_configuration.provider
);
let forked_from_id = session_configuration
.forked_from_thread_id
.or_else(|| initial_history.forked_from_id());
session_configuration.forked_from_thread_id = forked_from_id;
let parent_thread_id = session_configuration
session_configuration.forked_from_thread_id = initial_history.forked_from_id();
session_configuration.parent_thread_id = session_configuration
.parent_thread_id
.or_else(|| initial_history.get_resumed_parent_thread_id());
session_configuration.parent_thread_id = parent_thread_id;
let multi_agent_version = multi_agent_version.map(OnceLock::from).unwrap_or_default();
let initial_multi_agent_version = multi_agent_version.get().copied();
@@ -532,8 +528,8 @@ impl Session {
let params = CreateThreadParams {
thread_id,
extra_config: config.extra_config.clone(),
forked_from_id,
parent_thread_id,
forked_from_id: session_configuration.forked_from_thread_id,
parent_thread_id: session_configuration.parent_thread_id,
source: session_source,
thread_source: session_configuration.thread_source.clone(),
base_instructions: BaseInstructions {
@@ -1070,8 +1066,8 @@ impl Session {
msg: EventMsg::SessionConfigured(SessionConfiguredEvent {
session_id,
thread_id,
forked_from_id,
parent_thread_id,
forked_from_id: session_configuration.forked_from_thread_id,
parent_thread_id: session_configuration.parent_thread_id,
thread_source: session_configuration.thread_source.clone(),
thread_name: session_configuration.thread_name.clone(),
model: session_configuration.collaboration_mode.model().to_string(),
+27 -7
View File
@@ -111,6 +111,7 @@ use codex_protocol::protocol::CodexErrorInfo;
use codex_protocol::protocol::CompactedItem;
use codex_protocol::protocol::ConversationAudioParams;
use codex_protocol::protocol::CreditsSnapshot;
use codex_protocol::protocol::ForkedHistory;
use codex_protocol::protocol::GranularApprovalConfig;
use codex_protocol::protocol::InitialHistory;
use codex_protocol::protocol::InterAgentCommunication;
@@ -1813,17 +1814,30 @@ fn resolve_multi_agent_version_handles_unset_and_legacy_history() {
);
assert_eq!(
resolve_multi_agent_version(
&InitialHistory::Forked(vec![session_meta_item(
thread_id,
Some(MultiAgentVersion::V2)
)]),
&InitialHistory::Forked(ForkedHistory {
parent_id: Some(thread_id),
history: vec![session_meta_item(thread_id, Some(MultiAgentVersion::V2))],
}),
Some(MultiAgentVersion::Disabled),
),
Some(MultiAgentVersion::Disabled)
);
assert_eq!(
resolve_multi_agent_version(
&InitialHistory::Forked(Vec::new()),
&InitialHistory::Forked(ForkedHistory {
parent_id: None,
history: vec![session_meta_item(thread_id, Some(MultiAgentVersion::V2))],
}),
/*inherited_multi_agent_version*/ None,
),
Some(MultiAgentVersion::V2)
);
assert_eq!(
resolve_multi_agent_version(
&InitialHistory::Forked(ForkedHistory {
parent_id: None,
history: Vec::new(),
}),
/*inherited_multi_agent_version*/ None
),
Some(MultiAgentVersion::V1)
@@ -2471,7 +2485,10 @@ async fn record_initial_history_reconstructs_forked_transcript() {
let (rollout_items, expected) = sample_rollout(&session, &turn_context).await;
session
.record_initial_history(InitialHistory::Forked(rollout_items))
.record_initial_history(InitialHistory::Forked(ForkedHistory {
parent_id: None,
history: rollout_items,
}))
.await;
let history = session.state.lock().await.clone_history();
@@ -2728,7 +2745,10 @@ async fn record_initial_history_forked_hydrates_previous_turn_settings() {
];
session
.record_initial_history(InitialHistory::Forked(rollout_items))
.record_initial_history(InitialHistory::Forked(ForkedHistory {
parent_id: None,
history: rollout_items,
}))
.await;
let history = session.clone_history().await;
@@ -719,7 +719,6 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() {
session_source: SessionSource::SubAgent(SubAgentSource::Other(
GUARDIAN_REVIEWER_NAME.to_string(),
)),
forked_from_thread_id: None,
parent_thread_id: None,
thread_source: None,
agent_control: AgentControl::default(),
+33 -59
View File
@@ -40,6 +40,7 @@ use codex_protocol::error::Result as CodexResult;
use codex_protocol::openai_models::ModelPreset;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ForkedHistory;
use codex_protocol::protocol::InitialHistory;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::Op;
@@ -611,15 +612,6 @@ impl ThreadManager {
pub async fn start_thread_with_options(
&self,
options: StartThreadOptions,
) -> CodexResult<NewThread> {
self.start_thread_with_options_and_fork_source(options, /*forked_from_thread_id*/ None)
.await
}
async fn start_thread_with_options_and_fork_source(
&self,
options: StartThreadOptions,
forked_from_thread_id: Option<ThreadId>,
) -> CodexResult<NewThread> {
let (resumed_session_source, resumed_thread_source) = options
.initial_history
@@ -634,7 +626,6 @@ impl ThreadManager {
self.agent_control(),
session_source,
/*parent_thread_id*/ None,
forked_from_thread_id,
thread_source,
options.dynamic_tools,
options.metrics_service_name,
@@ -681,8 +672,7 @@ impl ThreadManager {
inherited_multi_agent_version,
),
);
self.start_thread_with_options_and_fork_source(options, Some(forked_from_thread_id))
.await
self.start_thread_with_options(options).await
}
pub async fn resume_thread_from_rollout(
@@ -724,7 +714,6 @@ impl ThreadManager {
self.agent_control(),
session_source,
/*parent_thread_id*/ None,
/*forked_from_thread_id*/ None,
thread_source,
Vec::new(),
/*metrics_service_name*/ None,
@@ -753,7 +742,6 @@ impl ThreadManager {
Arc::clone(&self.state.auth_manager),
self.agent_control(),
/*parent_thread_id*/ None,
/*forked_from_thread_id*/ None,
/*thread_source*/ None,
Vec::new(),
/*metrics_service_name*/ None,
@@ -787,7 +775,6 @@ impl ThreadManager {
self.agent_control(),
session_source,
/*parent_thread_id*/ None,
/*forked_from_thread_id*/ None,
thread_source,
Vec::new(),
/*metrics_service_name*/ None,
@@ -928,21 +915,10 @@ impl ThreadManager {
thread_source: Option<ThreadSource>,
parent_trace: Option<W3cTraceContext>,
) -> CodexResult<NewThread> {
// `forked_from_id()` describes this history's existing lineage. When
// forking a resumed thread, the child copies the resumed thread itself.
let forked_from_thread_id = match &history {
InitialHistory::Resumed(resumed) => Some(resumed.conversation_id),
InitialHistory::Forked(_) => history.forked_from_id(),
InitialHistory::New | InitialHistory::Cleared => None,
};
let multi_agent_version = self
.state
.effective_multi_agent_version_for_spawn(
&history,
/*session_source*/ None,
/*parent_thread_id*/ None,
forked_from_thread_id,
&config,
&history, /*session_source*/ None, /*parent_thread_id*/ None, &config,
)
.await;
let interrupted_marker =
@@ -958,7 +934,6 @@ impl ThreadManager {
Arc::clone(&self.state.auth_manager),
self.agent_control(),
/*parent_thread_id*/ None,
forked_from_thread_id,
thread_source,
Vec::new(),
/*metrics_service_name*/ None,
@@ -1076,14 +1051,12 @@ impl ThreadManagerState {
initial_history: &InitialHistory,
session_source: Option<&SessionSource>,
parent_thread_id: Option<ThreadId>,
forked_from_thread_id: Option<ThreadId>,
config: &Config,
) -> MultiAgentVersion {
self.initial_multi_agent_version_for_spawn(
initial_history,
session_source,
parent_thread_id,
forked_from_thread_id,
)
.await
.unwrap_or_else(|| config.multi_agent_version_from_features())
@@ -1094,7 +1067,6 @@ impl ThreadManagerState {
initial_history: &InitialHistory,
session_source: Option<&SessionSource>,
parent_thread_id: Option<ThreadId>,
forked_from_thread_id: Option<ThreadId>,
) -> Option<MultiAgentVersion> {
let inherited_thread_id = match session_source {
Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
@@ -1102,7 +1074,7 @@ impl ThreadManagerState {
})) => Some(*parent_thread_id),
_ => match initial_history {
InitialHistory::Resumed(resumed) => Some(resumed.conversation_id),
InitialHistory::Forked(_) => forked_from_thread_id.or(parent_thread_id),
InitialHistory::Forked(forked) => forked.parent_id.or(parent_thread_id),
InitialHistory::New | InitialHistory::Cleared => parent_thread_id,
},
};
@@ -1134,9 +1106,9 @@ impl ThreadManagerState {
/// than loading independently.
async fn user_instructions_for_spawn(
&self,
initial_history: &InitialHistory,
session_source: &SessionSource,
parent_thread_id: Option<ThreadId>,
forked_from_thread_id: Option<ThreadId>,
) -> LoadedUserInstructions {
let is_root_agent = !session_source.is_non_root_agent();
if is_root_agent {
@@ -1150,7 +1122,7 @@ impl ThreadManagerState {
SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id, ..
}) => Some(*parent_thread_id),
_ => parent_thread_id.or(forked_from_thread_id),
_ => parent_thread_id.or_else(|| initial_history.forked_from_id()),
};
let instructions = match inherited_thread_id {
// The spawn path retains only thread IDs, so look up the live
@@ -1178,7 +1150,6 @@ impl ThreadManagerState {
agent_control,
self.session_source.clone(),
/*parent_thread_id*/ None,
/*forked_from_thread_id*/ None,
/*thread_source*/ None,
/*metrics_service_name*/ None,
/*inherited_environments*/ None,
@@ -1195,7 +1166,6 @@ impl ThreadManagerState {
agent_control: AgentControl,
session_source: SessionSource,
parent_thread_id: Option<ThreadId>,
forked_from_thread_id: Option<ThreadId>,
thread_source: Option<ThreadSource>,
metrics_service_name: Option<String>,
inherited_environments: Option<TurnEnvironmentSnapshot>,
@@ -1212,7 +1182,6 @@ impl ThreadManagerState {
agent_control,
session_source,
parent_thread_id,
forked_from_thread_id,
thread_source,
Vec::new(),
metrics_service_name,
@@ -1249,7 +1218,6 @@ impl ThreadManagerState {
agent_control,
session_source,
parent_thread_id,
/*forked_from_thread_id*/ None,
thread_source,
Vec::new(),
/*metrics_service_name*/ None,
@@ -1272,7 +1240,6 @@ impl ThreadManagerState {
session_source: SessionSource,
thread_source: Option<ThreadSource>,
parent_thread_id: Option<ThreadId>,
forked_from_thread_id: Option<ThreadId>,
inherited_environments: Option<TurnEnvironmentSnapshot>,
inherited_exec_policy: Option<Arc<crate::exec_policy::ExecPolicyManager>>,
environments: Option<Vec<TurnEnvironmentSelection>>,
@@ -1287,7 +1254,6 @@ impl ThreadManagerState {
agent_control,
session_source,
parent_thread_id,
forked_from_thread_id,
thread_source,
Vec::new(),
/*metrics_service_name*/ None,
@@ -1310,7 +1276,6 @@ impl ThreadManagerState {
auth_manager: Arc<AuthManager>,
agent_control: AgentControl,
parent_thread_id: Option<ThreadId>,
forked_from_thread_id: Option<ThreadId>,
thread_source: Option<ThreadSource>,
dynamic_tools: Vec<codex_protocol::dynamic_tools::DynamicToolSpec>,
metrics_service_name: Option<String>,
@@ -1326,7 +1291,6 @@ impl ThreadManagerState {
agent_control,
self.session_source.clone(),
parent_thread_id,
forked_from_thread_id,
thread_source,
dynamic_tools,
metrics_service_name,
@@ -1349,7 +1313,6 @@ impl ThreadManagerState {
agent_control: AgentControl,
session_source: SessionSource,
parent_thread_id: Option<ThreadId>,
forked_from_thread_id: Option<ThreadId>,
thread_source: Option<ThreadSource>,
dynamic_tools: Vec<codex_protocol::dynamic_tools::DynamicToolSpec>,
metrics_service_name: Option<String>,
@@ -1383,7 +1346,7 @@ impl ThreadManagerState {
}
}
let user_instructions = self
.user_instructions_for_spawn(&session_source, parent_thread_id, forked_from_thread_id)
.user_instructions_for_spawn(&initial_history, &session_source, parent_thread_id)
.await;
let parent_rollout_thread_trace = self
.parent_rollout_thread_trace_for_source(&session_source, &initial_history)
@@ -1394,7 +1357,6 @@ impl ThreadManagerState {
&initial_history,
Some(&session_source),
parent_thread_id,
forked_from_thread_id,
)
.await;
let CodexSpawnOk {
@@ -1412,7 +1374,6 @@ impl ThreadManagerState {
extensions: Arc::clone(&self.extensions),
conversation_history: initial_history,
session_source,
forked_from_thread_id,
parent_thread_id,
thread_source,
agent_control,
@@ -1567,6 +1528,11 @@ fn truncate_before_nth_user_message(
n: usize,
snapshot_state: &SnapshotTurnState,
) -> InitialHistory {
let parent_id = match &history {
InitialHistory::New | InitialHistory::Cleared => None,
InitialHistory::Resumed(resumed) => Some(resumed.conversation_id),
InitialHistory::Forked(forked) => forked.parent_id,
};
let items: Vec<RolloutItem> = history.get_rollout_items();
let user_positions = truncation::user_message_positions_in_rollout(&items);
let rolled = if snapshot_state.ends_mid_turn && n >= user_positions.len() {
@@ -1582,11 +1548,10 @@ fn truncate_before_nth_user_message(
truncation::truncate_rollout_before_nth_user_message_from_start(&items, n)
};
if rolled.is_empty() {
InitialHistory::New
} else {
InitialHistory::Forked(rolled)
}
InitialHistory::Forked(ForkedHistory {
parent_id,
history: rolled,
})
}
#[derive(Debug, Eq, PartialEq)]
@@ -1663,8 +1628,11 @@ fn fork_history_from_snapshot(
let history = match history {
InitialHistory::New => InitialHistory::New,
InitialHistory::Cleared => InitialHistory::Cleared,
InitialHistory::Forked(history) => InitialHistory::Forked(history),
InitialHistory::Resumed(resumed) => InitialHistory::Forked(resumed.history),
forked @ InitialHistory::Forked(_) => forked,
InitialHistory::Resumed(resumed) => InitialHistory::Forked(ForkedHistory {
parent_id: Some(resumed.conversation_id),
history: resumed.history,
}),
};
if snapshot_state.ends_mid_turn {
append_interrupted_boundary(
@@ -1701,21 +1669,27 @@ fn append_interrupted_boundary(
history.push(RolloutItem::ResponseItem(marker));
}
history.push(aborted_event);
InitialHistory::Forked(history)
InitialHistory::Forked(ForkedHistory {
parent_id: None,
history,
})
}
InitialHistory::Forked(mut history) => {
InitialHistory::Forked(mut forked) => {
if let Some(marker) = interrupted_turn_history_marker(interrupted_marker) {
history.push(RolloutItem::ResponseItem(marker));
forked.history.push(RolloutItem::ResponseItem(marker));
}
history.push(aborted_event);
InitialHistory::Forked(history)
forked.history.push(aborted_event);
InitialHistory::Forked(forked)
}
InitialHistory::Resumed(mut resumed) => {
if let Some(marker) = interrupted_turn_history_marker(interrupted_marker) {
resumed.history.push(RolloutItem::ResponseItem(marker));
}
resumed.history.push(aborted_event);
InitialHistory::Forked(resumed.history)
InitialHistory::Forked(ForkedHistory {
parent_id: Some(resumed.conversation_id),
history: resumed.history,
})
}
}
}
+27 -18
View File
@@ -67,6 +67,13 @@ fn developer_interrupted_marker() -> ResponseItem {
.expect("developer interrupted marker should be enabled")
}
fn forked_history(history: Vec<RolloutItem>) -> InitialHistory {
InitialHistory::Forked(ForkedHistory {
parent_id: None,
history,
})
}
#[test]
fn truncates_before_requested_user_message() {
let items = [
@@ -100,8 +107,12 @@ fn truncates_before_requested_user_message() {
.cloned()
.map(RolloutItem::ResponseItem)
.collect();
let parent_id = ThreadId::new();
let truncated = truncate_before_nth_user_message(
InitialHistory::Forked(initial),
InitialHistory::Forked(ForkedHistory {
parent_id: Some(parent_id),
history: initial,
}),
/*n*/ 1,
&SnapshotTurnState {
ends_mid_turn: false,
@@ -116,8 +127,8 @@ fn truncates_before_requested_user_message() {
RolloutItem::ResponseItem(items[2].clone()),
];
assert_eq!(
serde_json::to_value(&got_items).unwrap(),
serde_json::to_value(&expected_items).unwrap()
(truncated.forked_from_id(), got_items),
(Some(parent_id), expected_items)
);
let initial2: Vec<RolloutItem> = items
@@ -126,7 +137,7 @@ fn truncates_before_requested_user_message() {
.map(RolloutItem::ResponseItem)
.collect();
let truncated2 = truncate_before_nth_user_message(
InitialHistory::Forked(initial2.clone()),
forked_history(initial2.clone()),
/*n*/ 2,
&SnapshotTurnState {
ends_mid_turn: false,
@@ -150,7 +161,7 @@ fn out_of_range_truncation_drops_only_unfinished_suffix_mid_turn() {
];
let truncated = truncate_before_nth_user_message(
InitialHistory::Forked(items.clone()),
forked_history(items.clone()),
usize::MAX,
&SnapshotTurnState {
ends_mid_turn: true,
@@ -200,7 +211,7 @@ fn out_of_range_truncation_drops_pre_user_active_turn_prefix() {
RolloutItem::ResponseItem(assistant_msg("partial")),
];
let snapshot_state = snapshot_turn_state(&InitialHistory::Forked(items.clone()));
let snapshot_state = snapshot_turn_state(&forked_history(items.clone()));
assert_eq!(
snapshot_state,
SnapshotTurnState {
@@ -211,7 +222,7 @@ fn out_of_range_truncation_drops_pre_user_active_turn_prefix() {
);
let truncated = truncate_before_nth_user_message(
InitialHistory::Forked(items.clone()),
forked_history(items.clone()),
usize::MAX,
&snapshot_state,
);
@@ -238,7 +249,7 @@ async fn ignores_session_prefix_messages_when_truncating() {
.collect();
let truncated = truncate_before_nth_user_message(
InitialHistory::Forked(rollout_items),
forked_history(rollout_items),
/*n*/ 1,
&SnapshotTurnState {
ends_mid_turn: false,
@@ -1030,8 +1041,7 @@ async fn new_uses_active_provider_for_model_refresh() {
#[test]
fn interrupted_fork_snapshot_appends_interrupt_boundary() {
let committed_history =
InitialHistory::Forked(vec![RolloutItem::ResponseItem(user_msg("hello"))]);
let committed_history = forked_history(vec![RolloutItem::ResponseItem(user_msg("hello"))]);
assert_eq!(
serde_json::to_value(
@@ -1080,8 +1090,7 @@ fn interrupted_fork_snapshot_appends_interrupt_boundary() {
#[test]
fn disabled_interrupted_fork_snapshot_appends_only_interrupt_event() {
let committed_history =
InitialHistory::Forked(vec![RolloutItem::ResponseItem(user_msg("hello"))]);
let committed_history = forked_history(vec![RolloutItem::ResponseItem(user_msg("hello"))]);
assert_eq!(
serde_json::to_value(
@@ -1128,7 +1137,7 @@ fn disabled_interrupted_fork_snapshot_appends_only_interrupt_event() {
#[test]
fn interrupted_snapshot_is_not_mid_turn() {
let interrupted_history = InitialHistory::Forked(vec![
let interrupted_history = forked_history(vec![
RolloutItem::ResponseItem(user_msg("hello")),
RolloutItem::ResponseItem(assistant_msg("partial")),
RolloutItem::ResponseItem(contextual_user_interrupted_marker()),
@@ -1170,7 +1179,7 @@ fn multi_agent_v2_interrupted_marker_uses_developer_input_message() {
#[test]
fn completed_legacy_event_history_is_not_mid_turn() {
let completed_history = InitialHistory::Forked(vec![
let completed_history = forked_history(vec![
RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
client_id: None,
message: "hello".to_string(),
@@ -1198,7 +1207,7 @@ fn completed_legacy_event_history_is_not_mid_turn() {
#[test]
fn mixed_response_and_legacy_user_event_history_is_mid_turn() {
let mixed_history = InitialHistory::Forked(vec![
let mixed_history = forked_history(vec![
RolloutItem::ResponseItem(user_msg("hello")),
RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
client_id: None,
@@ -1248,7 +1257,7 @@ async fn interrupted_fork_snapshot_does_not_synthesize_turn_id_for_legacy_histor
let source = manager
.resume_thread_with_history(
config.clone(),
InitialHistory::Forked(vec![
forked_history(vec![
RolloutItem::ResponseItem(user_msg("hello")),
RolloutItem::ResponseItem(assistant_msg("partial")),
]),
@@ -1355,7 +1364,7 @@ async fn interrupted_fork_snapshot_preserves_explicit_turn_id() {
let source = manager
.resume_thread_with_history(
config.clone(),
InitialHistory::Forked(vec![
forked_history(vec![
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
turn_id: "turn-explicit".to_string(),
trace_id: None,
@@ -1452,7 +1461,7 @@ async fn interrupted_fork_snapshot_uses_persisted_mid_turn_history_without_live_
let source = manager
.resume_thread_with_history(
config.clone(),
InitialHistory::Forked(vec![
forked_history(vec![
RolloutItem::ResponseItem(user_msg("hello")),
RolloutItem::ResponseItem(assistant_msg("partial")),
]),
@@ -41,6 +41,7 @@ use codex_protocol::protocol::FileSystemAccessMode;
use codex_protocol::protocol::FileSystemPath;
use codex_protocol::protocol::FileSystemSandboxEntry;
use codex_protocol::protocol::FileSystemSandboxPolicy;
use codex_protocol::protocol::ForkedHistory;
use codex_protocol::protocol::InitialHistory;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::NetworkSandboxPolicy;
@@ -2790,15 +2791,18 @@ async fn resume_agent_restores_closed_agent_and_accepts_send_input() {
let thread = manager
.resume_thread_with_history(
config.clone(),
InitialHistory::Forked(vec![RolloutItem::ResponseItem(ResponseItem::Message {
id: None,
role: "user".to_string(),
content: vec![ContentItem::InputText {
text: "materialized".to_string(),
}],
phase: None,
metadata: None,
})]),
InitialHistory::Forked(ForkedHistory {
parent_id: None,
history: vec![RolloutItem::ResponseItem(ResponseItem::Message {
id: None,
role: "user".to_string(),
content: vec![ContentItem::InputText {
text: "materialized".to_string(),
}],
phase: None,
metadata: None,
})],
}),
AuthManager::from_auth_for_testing(CodexAuth::from_api_key("dummy")),
/*parent_trace*/ None,
)
@@ -15,6 +15,7 @@ use codex_protocol::protocol::ConversationStartTransport;
use codex_protocol::protocol::ConversationTextParams;
use codex_protocol::protocol::ConversationTextRole;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ForkedHistory;
use codex_protocol::protocol::InitialHistory;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::RealtimeAudioFrame;
@@ -2216,7 +2217,10 @@ async fn conversation_startup_context_current_thread_selects_many_turns_by_budge
.thread_manager
.resume_thread_with_history(
test.config.clone(),
InitialHistory::Forked(history),
InitialHistory::Forked(ForkedHistory {
parent_id: None,
history,
}),
auth_manager_from_auth(CodexAuth::from_api_key("dummy")),
/*parent_trace*/ None,
)
+19 -14
View File
@@ -2405,12 +2405,19 @@ pub struct ResumedHistory {
pub rollout_path: Option<PathBuf>,
}
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)]
pub struct ForkedHistory {
/// Thread whose history was copied into this fork.
pub parent_id: Option<ThreadId>,
pub history: Vec<RolloutItem>,
}
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)]
pub enum InitialHistory {
New,
Cleared,
Resumed(ResumedHistory),
Forked(Vec<RolloutItem>),
Forked(ForkedHistory),
}
impl InitialHistory {
@@ -2418,7 +2425,7 @@ impl InitialHistory {
match self {
InitialHistory::New | InitialHistory::Cleared => false,
InitialHistory::Resumed(resumed) => resumed.history.iter().any(&mut predicate),
InitialHistory::Forked(items) => items.iter().any(predicate),
InitialHistory::Forked(forked) => forked.history.iter().any(predicate),
}
}
@@ -2431,10 +2438,7 @@ impl InitialHistory {
_ => None,
})
}
InitialHistory::Forked(items) => items.iter().find_map(|item| match item {
RolloutItem::SessionMeta(meta_line) => Some(meta_line.meta.id),
_ => None,
}),
InitialHistory::Forked(forked) => forked.parent_id,
}
}
@@ -2442,7 +2446,7 @@ impl InitialHistory {
match self {
InitialHistory::New | InitialHistory::Cleared => None,
InitialHistory::Resumed(resumed) => session_cwd_from_items(&resumed.history),
InitialHistory::Forked(items) => session_cwd_from_items(items),
InitialHistory::Forked(forked) => session_cwd_from_items(&forked.history),
}
}
@@ -2450,7 +2454,7 @@ impl InitialHistory {
match self {
InitialHistory::New | InitialHistory::Cleared => Vec::new(),
InitialHistory::Resumed(resumed) => resumed.history.clone(),
InitialHistory::Forked(items) => items.clone(),
InitialHistory::Forked(forked) => forked.history.clone(),
}
}
@@ -2467,8 +2471,9 @@ impl InitialHistory {
})
.collect(),
),
InitialHistory::Forked(items) => Some(
items
InitialHistory::Forked(forked) => Some(
forked
.history
.iter()
.filter_map(|ri| match ri {
RolloutItem::EventMsg(ev) => Some(ev.clone()),
@@ -2489,7 +2494,7 @@ impl InitialHistory {
_ => None,
})
}
InitialHistory::Forked(items) => items.iter().find_map(|item| match item {
InitialHistory::Forked(forked) => forked.history.iter().find_map(|item| match item {
RolloutItem::SessionMeta(meta_line) => meta_line.meta.base_instructions.clone(),
_ => None,
}),
@@ -2505,7 +2510,7 @@ impl InitialHistory {
_ => None,
})
}
InitialHistory::Forked(items) => items.iter().find_map(|item| match item {
InitialHistory::Forked(forked) => forked.history.iter().find_map(|item| match item {
RolloutItem::SessionMeta(meta_line) => meta_line.meta.dynamic_tools.clone(),
_ => None,
}),
@@ -2518,8 +2523,8 @@ impl InitialHistory {
InitialHistory::Resumed(resumed) => {
multi_agent_version_from_items(&resumed.history, Some(resumed.conversation_id))
}
InitialHistory::Forked(items) => {
multi_agent_version_from_items(items, /*thread_id*/ None)
InitialHistory::Forked(forked) => {
multi_agent_version_from_items(&forked.history, forked.parent_id)
}
}
}