Preserve rollback session context semantics

Keep thread rollback reconstruction from replacing current persistent
session settings while still restoring reference context on resume and fork.
Preserve legacy UserInput environment selections for callers that do not
send full turn context, without changing UserTurn turn-scoped behavior.

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
starr-openai
2026-05-01 04:34:03 +00:00
co-authored by Codex
parent b95cb23f84
commit 10c03f9bdd
9 changed files with 182 additions and 66 deletions
@@ -70,6 +70,31 @@ impl NetworkContext {
}
impl EnvironmentContext {
fn should_render_environments(environment_count: usize) -> bool {
environment_count > 1
}
fn model_facing_environments(
environments: Vec<EnvironmentContextEnvironment>,
) -> Vec<EnvironmentContextEnvironment> {
// Preserve the legacy model-facing cwd/shell context for zero- and
// single-environment turns; only render explicit choices for multi-env.
if Self::should_render_environments(environments.len()) {
environments
} else {
Vec::new()
}
}
fn turn_context_item_has_model_facing_environments(
turn_context_item: &TurnContextItem,
) -> bool {
turn_context_item
.environments
.as_ref()
.is_some_and(|environments| Self::should_render_environments(environments.len()))
}
pub(crate) fn new(
cwd: Option<PathBuf>,
shell: String,
@@ -116,7 +141,10 @@ impl EnvironmentContext {
after: &EnvironmentContext,
) -> Self {
let before_network = Self::network_from_turn_context_item(before);
let before_had_environments = Self::turn_context_item_has_model_facing_environments(before);
let environments = Self::model_facing_environments(after.environments.clone());
let cwd = match &after.cwd {
Some(cwd) if before_had_environments && environments.is_empty() => Some(cwd.clone()),
Some(cwd) if before.cwd.as_path() != cwd.as_path() => Some(cwd.clone()),
_ => None,
};
@@ -125,15 +153,6 @@ impl EnvironmentContext {
} else {
before_network
};
let before_had_environments = before
.environments
.as_ref()
.is_some_and(|environments| environments.len() > 1);
let environments = if before_had_environments || after.environments.len() > 1 {
after.environments.clone()
} else {
Vec::new()
};
EnvironmentContext::new(
cwd,
after.shell.clone(),
@@ -148,11 +167,7 @@ impl EnvironmentContext {
pub(crate) fn from_turn_context(turn_context: &TurnContext, shell: &Shell) -> Self {
let environments =
EnvironmentContextEnvironment::from_turn_environments(&turn_context.environments);
let environments = if environments.len() > 1 {
environments
} else {
Vec::new()
};
let environments = Self::model_facing_environments(environments);
Self::new(
Some(turn_context.cwd.to_path_buf()),
shell.name().to_string(),
@@ -171,9 +186,9 @@ impl EnvironmentContext {
let environments = turn_context_item
.environments
.as_deref()
.filter(|environments| environments.len() > 1)
.map(EnvironmentContextEnvironment::from_selected_environments)
.unwrap_or_default();
let environments = Self::model_facing_environments(environments);
Self::new(
Some(turn_context_item.cwd.clone()),
shell,
@@ -235,14 +250,10 @@ impl ContextualUserFragment for EnvironmentContext {
fn body(&self) -> String {
let mut lines = Vec::new();
if self.environments.len() <= 1 {
// Only change the model-facing surface when more than one selected
// environment is in use. Zero- and single-environment turns keep
// the existing cwd/shell shape.
if let Some(cwd) = &self.cwd {
lines.push(format!(" <cwd>{}</cwd>", cwd.to_string_lossy()));
}
} else {
// `self.environments` is pre-filtered to only contain model-facing
// environments for multi-env turns, preserving the legacy cwd/shell
// context for zero- and single-environment turns.
if !self.environments.is_empty() {
lines.push(" <environments>".to_string());
for environment in &self.environments {
lines.push(format!(
@@ -256,6 +267,8 @@ impl ContextualUserFragment for EnvironmentContext {
lines.push(" </environment>".to_string());
}
lines.push(" </environments>".to_string());
} else if let Some(cwd) = &self.cwd {
lines.push(format!(" <cwd>{}</cwd>", cwd.to_string_lossy()));
}
lines.push(format!(" <shell>{}</shell>", self.shell));
@@ -1,6 +1,12 @@
use crate::shell::ShellType;
use super::*;
use codex_protocol::config_types::ReasoningSummary as ReasoningSummaryConfig;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::SandboxPolicy;
use codex_protocol::protocol::TurnContextItem;
use codex_protocol::protocol::TurnEnvironmentSelection;
use core_test_support::test_absolute_path;
use core_test_support::test_path_buf;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
@@ -14,6 +20,42 @@ fn fake_shell_name() -> String {
shell.name().to_string()
}
fn turn_environment_selection(id: &str, cwd: &str) -> TurnEnvironmentSelection {
TurnEnvironmentSelection {
environment_id: id.to_string(),
cwd: test_absolute_path(cwd),
}
}
fn turn_context_item(
cwd: &str,
environments: Option<Vec<TurnEnvironmentSelection>>,
) -> TurnContextItem {
TurnContextItem {
turn_id: None,
trace_id: None,
cwd: test_path_buf(cwd),
environments,
current_date: None,
timezone: None,
approval_policy: AskForApproval::Never,
sandbox_policy: SandboxPolicy::DangerFullAccess,
permission_profile: None,
network: None,
file_system_sandbox_policy: None,
model: "gpt-5".to_string(),
personality: None,
collaboration_mode: None,
realtime_active: None,
effort: None,
summary: ReasoningSummaryConfig::Auto,
user_instructions: None,
developer_instructions: None,
final_output_json_schema: None,
truncation_policy: None,
}
}
#[test]
fn serialize_workspace_write_environment_context() {
let cwd = test_path_buf("/repo");
@@ -166,6 +208,62 @@ fn equals_except_shell_ignores_shell() {
assert!(context1.equals_except_shell(&context2));
}
#[test]
fn from_turn_context_item_omits_single_environment() {
let context = EnvironmentContext::from_turn_context_item(
&turn_context_item(
"/repo",
Some(vec![turn_environment_selection("local", "/repo")]),
),
fake_shell_name(),
);
assert!(context.environments.is_empty());
assert_eq!(
context.render(),
format!(
r#"<environment_context>
<cwd>{}</cwd>
<shell>bash</shell>
</environment_context>"#,
test_path_buf("/repo").display()
)
);
}
#[test]
fn diff_reintroduces_cwd_when_environment_block_clears() {
let before = turn_context_item(
"/repo",
Some(vec![
turn_environment_selection("local", "/repo"),
turn_environment_selection("remote", "/remote/repo"),
]),
);
let after = EnvironmentContext::from_turn_context_item(
&turn_context_item(
"/repo",
Some(vec![turn_environment_selection("local", "/repo")]),
),
fake_shell_name(),
);
let diff = EnvironmentContext::diff_from_turn_context_item(&before, &after);
assert!(diff.environments.is_empty());
assert_eq!(diff.cwd, Some(test_path_buf("/repo")));
assert_eq!(
diff.render(),
format!(
r#"<environment_context>
<cwd>{}</cwd>
<shell>bash</shell>
</environment_context>"#,
test_path_buf("/repo").display()
)
);
}
#[test]
fn serialize_environment_context_with_subagents() {
let context = EnvironmentContext::new(
+3 -3
View File
@@ -176,13 +176,13 @@ mod tests {
}
#[tokio::test]
async fn resolved_environment_selections_use_fallback_without_selections() {
let cwd = AbsolutePathBuf::current_dir().expect("cwd");
async fn resolved_environment_selections_allow_empty_selection_list() {
let manager = EnvironmentManager::default_for_tests();
let resolved =
resolve_environment_selections(&manager, &[]).expect("empty selections are valid");
assert_eq!(resolved.primary_cwd_or_fallback(&cwd), cwd);
assert!(resolved.primary_turn_environment().is_none());
assert!(resolved.to_selections().is_empty());
}
}
+19 -9
View File
@@ -168,6 +168,8 @@ pub(super) async fn user_input_or_turn_inner(
service_tier,
final_output_json_schema: Some(final_output_json_schema),
environments,
persist_environments: false,
sync_single_environment_cwd: false,
personality,
app_server_client_name: None,
app_server_client_version: None,
@@ -220,6 +222,8 @@ pub(super) async fn user_input_or_turn_inner(
service_tier,
final_output_json_schema: Some(final_output_json_schema),
environments,
persist_environments: false,
sync_single_environment_cwd: false,
personality,
app_server_client_name: None,
app_server_client_version: None,
@@ -232,15 +236,19 @@ pub(super) async fn user_input_or_turn_inner(
environments,
final_output_json_schema,
responsesapi_client_metadata,
} => (
items,
SessionSettingsUpdate {
final_output_json_schema: Some(final_output_json_schema),
environments,
..Default::default()
},
responsesapi_client_metadata,
),
} => {
let persist_environments = environments.is_some();
(
items,
SessionSettingsUpdate {
final_output_json_schema: Some(final_output_json_schema),
environments,
persist_environments,
..Default::default()
},
responsesapi_client_metadata,
)
}
_ => unreachable!(),
};
@@ -1040,11 +1048,13 @@ pub(super) async fn submission_loop(
/*developer_instructions*/ None,
)
};
let sync_single_environment_cwd = cwd.is_some();
override_turn_context(
&sess,
sub.id.clone(),
SessionSettingsUpdate {
cwd,
sync_single_environment_cwd,
approval_policy,
approvals_reviewer,
sandbox_policy,
+17 -29
View File
@@ -207,13 +207,18 @@ impl SessionConfiguration {
.unwrap_or_else(|| self.cwd.clone());
let cwd_changed = absolute_cwd.as_path() != self.cwd.as_path();
next_configuration.cwd = absolute_cwd.clone();
if updates.environments.is_none()
&& cwd_changed
next_configuration.cwd = absolute_cwd;
if updates.persist_environments
&& let Some(environments) = updates.environments.clone()
{
next_configuration.environments = environments;
}
if updates.sync_single_environment_cwd
&& updates.environments.is_none()
&& next_configuration.environments.len() == 1
&& let Some(turn_environment) = next_configuration.environments.first_mut()
{
turn_environment.cwd = absolute_cwd;
turn_environment.cwd = next_configuration.cwd.clone();
}
if let Some(permission_profile) = updates.permission_profile.clone() {
@@ -316,6 +321,12 @@ pub(crate) struct SessionSettingsUpdate {
/// environments stored on `SessionConfiguration`; `Some([])` explicitly
/// disables environments for this turn.
pub(crate) environments: Option<Vec<TurnEnvironmentSelection>>,
/// Promote `environments` into sticky thread state after resolving this
/// update. Used by legacy input paths that do not carry full turn context.
pub(crate) persist_environments: bool,
/// When a legacy context override changes cwd without explicit environment
/// selections, keep the single stored environment aligned with that cwd.
pub(crate) sync_single_environment_cwd: bool,
pub(crate) personality: Option<Personality>,
pub(crate) app_server_client_name: Option<String>,
pub(crate) app_server_client_version: Option<String>,
@@ -923,31 +934,8 @@ impl Session {
cancel_guard.cancel();
*cancel_guard = CancellationToken::new();
}
let turn_environment = crate::environment_selection::resolve_environment_selections(
sess.services.environment_manager.as_ref(),
&session_configuration.environments,
)
.map_err(|err| {
CodexErr::InvalidRequest(err.to_string().replace(
"unknown turn environment id",
"unknown stored MCP environment id",
))
})?
.primary_turn_environment()
.cloned();
let mcp_runtime_environment = match turn_environment {
Some(turn_environment) => McpRuntimeEnvironment::new(
Arc::clone(&turn_environment.environment),
turn_environment.cwd.to_path_buf(),
),
None => McpRuntimeEnvironment::new(
sess.services
.environment_manager
.default_environment()
.unwrap_or_else(|| sess.services.environment_manager.local_environment()),
session_configuration.cwd.to_path_buf(),
),
};
let mcp_runtime_environment =
sess.mcp_runtime_environment_for_configuration(&session_configuration)?;
let (mcp_connection_manager, cancel_token) = McpConnectionManager::new(
&mcp_servers,
config.mcp_oauth_credentials_store_mode,
@@ -274,6 +274,8 @@ impl TurnContext {
}
pub(crate) fn has_multiple_selected_environments(&self) -> bool {
// Keep model-facing tool signatures on the legacy single-environment
// surface; only expose environment choices when the turn has >1.
self.environments.len() > 1
}
@@ -506,6 +508,8 @@ impl Session {
.with_web_search_config(per_turn_config.web_search_config.clone())
.with_allow_login_shell(per_turn_config.permissions.allow_login_shell)
.with_has_environment(!environments.is_empty())
// Keep model-facing tool signatures on the legacy single-environment
// surface; only expose environment choices when the turn has >1.
.with_has_multiple_selected_environments(environments.len() > 1)
.with_spawn_agent_usage_hint(per_turn_config.multi_agent_v2.usage_hint_enabled)
.with_spawn_agent_usage_hint_text(per_turn_config.multi_agent_v2.usage_hint_text.clone())
+3
View File
@@ -107,6 +107,9 @@ pub(crate) fn resolve_process_tool_environment(
turn: &TurnContext,
environment_id: Option<&str>,
) -> Result<Option<ProcessToolEnvironment>, FunctionCallError> {
// Preserve the legacy model-facing process-tool behavior for zero- and
// single-environment turns; explicit environment routing is only exposed
// when the model sees multiple selected environments.
if environment_id.is_none() && !turn.has_multiple_selected_environments() {
return Ok(turn
.primary_environment()
-1
View File
@@ -44,7 +44,6 @@ use codex_protocol::protocol::McpToolCallBeginEvent;
use codex_protocol::protocol::Op;
use codex_protocol::user_input::UserInput;
use codex_utils_cargo_bin::cargo_bin;
use core_test_support::PathBufExt;
use core_test_support::assert_regex_match;
use core_test_support::remote_env_env_var;
use core_test_support::responses;
+2 -1
View File
@@ -435,7 +435,8 @@ pub enum Op {
UserInput {
/// User input items, see `InputItem`
items: Vec<UserInput>,
/// Optional turn-scoped environments.
/// Optional legacy environment selections. Prefer `UserTurn` or
/// `UserInputWithTurnContext` for turn-scoped environment selections.
#[serde(default, skip_serializing_if = "Option::is_none")]
environments: Option<Vec<TurnEnvironmentSelection>>,
/// Optional JSON Schema used to constrain the final assistant message for this turn.