protocol: keep selected environment cwd as PathUri

This commit is contained in:
Adam Perry
2026-06-13 05:55:47 +00:00
parent fc3d68468d
commit 10d930f17b
20 changed files with 113 additions and 85 deletions
+1
View File
@@ -3583,6 +3583,7 @@ dependencies = [
"codex-network-proxy",
"codex-utils-absolute-path",
"codex-utils-image",
"codex-utils-path-uri",
"codex-utils-string",
"encoding_rs",
"globset",
@@ -339,7 +339,6 @@ use codex_core_plugins::remote::RemotePluginShareContext as RemoteCatalogPluginS
use codex_core_plugins::remote::RemotePluginShareSummary as RemoteCatalogPluginShareSummary;
use codex_core_plugins::remote::RemotePluginSummary as RemoteCatalogPluginSummary;
use codex_exec_server::EnvironmentManager;
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
use codex_exec_server::LOCAL_FS;
use codex_features::FEATURES;
use codex_features::Feature;
@@ -1292,7 +1292,7 @@ impl ThreadRequestProcessor {
.into_iter()
.map(|environment| TurnEnvironmentSelection {
environment_id: environment.environment_id,
cwd: environment.cwd,
cwd: codex_utils_path_uri::PathUri::from_abs_path(&environment.cwd),
})
.collect::<Vec<_>>()
});
@@ -339,7 +339,7 @@ impl TurnRequestProcessor {
.into_iter()
.map(|environment| TurnEnvironmentSelection {
environment_id: environment.environment_id,
cwd: environment.cwd,
cwd: codex_utils_path_uri::PathUri::from_abs_path(&environment.cwd),
})
.collect::<Vec<_>>()
});
@@ -519,13 +519,7 @@ impl TurnRequestProcessor {
let snapshot = thread.config_snapshot().await;
let environment_selections =
environment_selections.unwrap_or_else(|| snapshot.environment_selections().to_vec());
let legacy_fallback_cwd = cwd.unwrap_or_else(|| {
environment_selections
.iter()
.find(|selection| selection.environment_id == LOCAL_ENVIRONMENT_ID)
.map(|selection| selection.cwd.clone())
.unwrap_or_else(|| snapshot.cwd().clone())
});
let legacy_fallback_cwd = cwd.unwrap_or_else(|| snapshot.cwd().clone());
Some(TurnEnvironmentSelections::new(
legacy_fallback_cwd,
environment_selections,
@@ -2609,14 +2609,6 @@ async fn turn_start_resolves_sticky_thread_local_environment_and_turn_overrides(
let server = create_mock_responses_server_repeating_assistant("done").await;
create_config_toml(&codex_home, &server.uri(), "never", &BTreeMap::default())?;
std::fs::write(
codex_home.join("environments.toml"),
r#"
[[environments]]
id = "remote"
url = "ws://127.0.0.1:1"
"#,
)?;
let mut mcp = TestAppServer::new(&codex_home).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
+22 -26
View File
@@ -7,6 +7,7 @@ use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use codex_protocol::protocol::TurnEnvironmentSelection;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use crate::session::turn_context::TurnEnvironment;
use crate::shell::Shell;
@@ -20,7 +21,7 @@ pub(crate) fn default_thread_environment_selections(
.into_iter()
.map(|environment_id| TurnEnvironmentSelection {
environment_id,
cwd: cwd.clone(),
cwd: PathUri::from_abs_path(cwd),
})
.collect()
}
@@ -81,27 +82,22 @@ pub(crate) async fn resolve_environment_selections(
.ok_or_else(|| {
CodexErr::InvalidRequest(format!("unknown turn environment id `{environment_id}`"))
})?;
let shell = match environment.info().await {
Ok(info) => match Shell::from_environment_shell_info(info.shell) {
Ok(shell) => Some(shell),
Err(err) => {
tracing::warn!(
"failed to resolve shell for environment `{environment_id}`: {err}"
);
None
}
},
Err(err) => {
tracing::warn!("failed to get info for environment `{environment_id}`: {err}");
None
}
};
turn_environments.push(TurnEnvironment::new(
let info = environment.info().await.map_err(|err| {
CodexErr::InvalidRequest(format!(
"failed to get info for environment `{environment_id}`: {err}"
))
})?;
let shell = Shell::from_environment_shell_info(info.shell).map_err(|err| {
CodexErr::InvalidRequest(format!(
"failed to resolve shell for environment `{environment_id}`: {err}"
))
})?;
turn_environments.push(TurnEnvironment::new_with_uri(
environment_id,
environment,
selected_environment.cwd.clone(),
shell,
));
Some(shell),
)?);
}
Ok(ResolvedTurnEnvironments { turn_environments })
}
@@ -139,7 +135,7 @@ mod tests {
default_thread_environment_selections(&manager, &cwd),
vec![TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd,
cwd: PathUri::from_abs_path(&cwd),
}]
);
}
@@ -167,11 +163,11 @@ url = "ws://127.0.0.1:8765"
vec![
TurnEnvironmentSelection {
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
cwd: cwd.clone(),
cwd: PathUri::from_abs_path(&cwd),
},
TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd,
cwd: PathUri::from_abs_path(&cwd),
},
]
);
@@ -198,11 +194,11 @@ url = "ws://127.0.0.1:8765"
&[
TurnEnvironmentSelection {
environment_id: "local".to_string(),
cwd: cwd.clone(),
cwd: PathUri::from_abs_path(&cwd),
},
TurnEnvironmentSelection {
environment_id: "local".to_string(),
cwd: cwd.join("other"),
cwd: PathUri::from_abs_path(&cwd.join("other")),
},
],
)
@@ -222,7 +218,7 @@ url = "ws://127.0.0.1:8765"
&manager,
&[TurnEnvironmentSelection {
environment_id: "local".to_string(),
cwd: selected_cwd,
cwd: PathUri::from_abs_path(&selected_cwd),
}],
)
.await
@@ -260,7 +256,7 @@ url = "ws://127.0.0.1:8765"
&local_manager,
&[TurnEnvironmentSelection {
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
cwd: cwd.clone(),
cwd: PathUri::from_abs_path(&cwd),
}],
)
.await
+21 -4
View File
@@ -149,6 +149,7 @@ use codex_thread_store::ResumeThreadParams;
use codex_thread_store::ThreadPersistenceMetadata;
use codex_thread_store::ThreadStore;
use codex_utils_output_truncation::TruncationPolicy;
use codex_utils_path_uri::PathUri;
use futures::future::BoxFuture;
use futures::future::Shared;
use futures::prelude::*;
@@ -2205,6 +2206,21 @@ impl Session {
| AskForApproval::Granular(_) => {}
}
let compatibility_cwd = match environment.cwd.to_abs_path() {
Ok(cwd) => cwd,
Err(err) => {
warn!(
"request_permissions cwd for environment `{}` cannot be projected onto this host: {err}",
environment.environment_id
);
return Some(RequestPermissionsResponse {
permissions: RequestPermissionProfile::default(),
scope: PermissionGrantScope::Turn,
strict_auto_review: false,
});
}
};
let requested_permissions = args.permissions;
if crate::guardian::routes_approval_to_guardian(turn_context.as_ref()) {
@@ -2273,7 +2289,7 @@ impl Session {
let response = Self::normalize_request_permissions_response(
requested_permissions,
response,
environment.cwd.as_path(),
compatibility_cwd.as_path(),
);
self.record_granted_request_permissions_for_turn(
&response,
@@ -2296,6 +2312,7 @@ impl Session {
tx_response,
requested_permissions: requested_permissions.clone(),
environment: environment.clone(),
compatibility_cwd: compatibility_cwd.clone(),
},
)
}
@@ -2313,7 +2330,7 @@ impl Session {
started_at_ms: now_unix_timestamp_ms(),
reason: args.reason,
permissions: requested_permissions,
cwd: Some(environment.cwd),
cwd: Some(compatibility_cwd),
});
self.send_event(turn_context.as_ref(), event).await;
tokio::select! {
@@ -2354,7 +2371,7 @@ impl Session {
});
};
let mut environment = turn_environment.selection();
environment.cwd = cwd;
environment.cwd = PathUri::from_abs_path(&cwd);
self.request_permissions_for_environment(
turn_context,
call_id,
@@ -2460,7 +2477,7 @@ impl Session {
let response = Self::normalize_request_permissions_response(
entry.requested_permissions,
response,
entry.environment.cwd.as_path(),
entry.compatibility_cwd.as_path(),
);
self.record_granted_request_permissions_for_turn(
&response,
+6 -5
View File
@@ -4677,7 +4677,7 @@ async fn relative_cwd_update_without_environments_resolves_under_session_cwd() {
}
#[tokio::test]
async fn cwd_update_rewrites_sticky_environment_cwd() {
async fn cwd_update_preserves_sticky_environment_cwd() {
let (session, _turn_context) = make_session_and_context().await;
let (original_cwd, environment_cwd, environments) = {
let mut state = session.state.lock().await;
@@ -4705,7 +4705,7 @@ async fn cwd_update_rewrites_sticky_environment_cwd() {
assert_eq!(state.session_configuration.cwd(), &updated_cwd);
assert_eq!(
state.session_configuration.environment_selections()[0].cwd,
updated_cwd
PathUri::from_abs_path(&environment_cwd)
);
assert_ne!(environment_cwd, updated_cwd);
}
@@ -6195,7 +6195,7 @@ async fn turn_environments_set_primary_environment() {
}
#[tokio::test]
async fn default_turn_does_not_overlay_legacy_fallback_cwd_onto_stored_thread_environments() {
async fn default_turn_keeps_legacy_fallback_cwd_separate_from_stored_thread_environments() {
let (session, _turn_context, _rx) = make_session_and_context_with_rx().await;
let session_cwd = session.get_config().await.cwd.clone();
let selected_cwd =
@@ -6218,10 +6218,11 @@ async fn default_turn_does_not_overlay_legacy_fallback_cwd_onto_stored_thread_en
&turn_environment.environment,
&turn_environments.turn_environments[0].environment
));
assert_eq!(turn_environment.cwd(), &selected_cwd);
#[allow(deprecated)]
let turn_cwd = turn_context.cwd.clone();
assert_eq!(turn_cwd, selected_cwd);
assert_eq!(turn_context.config.cwd, selected_cwd);
assert_eq!(turn_cwd, session_cwd);
assert_eq!(turn_context.config.cwd, session_cwd);
}
#[tokio::test]
+24 -7
View File
@@ -52,20 +52,40 @@ pub(crate) struct TurnEnvironment {
}
impl TurnEnvironment {
#[cfg(test)]
pub(crate) fn new(
environment_id: String,
environment: Arc<Environment>,
cwd: AbsolutePathBuf,
shell: Option<shell::Shell>,
) -> Self {
let cwd_uri = PathUri::from_abs_path(&cwd);
Self {
environment_id,
environment,
cwd_uri: PathUri::from_abs_path(&cwd),
cwd,
shell,
}
}
pub(crate) fn new_with_uri(
environment_id: String,
environment: Arc<Environment>,
cwd_uri: PathUri,
shell: Option<shell::Shell>,
) -> CodexResult<Self> {
let cwd = cwd_uri.to_abs_path().map_err(|err| {
CodexErr::InvalidRequest(format!(
"turn environment cwd `{cwd_uri}` cannot be projected onto this host: {err}"
))
})?;
Ok(Self {
environment_id,
environment,
cwd,
cwd_uri,
shell,
}
})
}
pub(crate) fn cwd(&self) -> &AbsolutePathBuf {
@@ -79,7 +99,7 @@ impl TurnEnvironment {
pub(crate) fn selection(&self) -> TurnEnvironmentSelection {
TurnEnvironmentSelection {
environment_id: self.environment_id.clone(),
cwd: self.cwd.clone(),
cwd: self.cwd_uri.clone(),
}
}
}
@@ -743,10 +763,7 @@ impl Session {
ResolvedTurnEnvironments::default()
});
let primary_turn_environment = turn_environments.primary().cloned();
let cwd = primary_turn_environment
.as_ref()
.map(|turn_environment| turn_environment.cwd().clone())
.unwrap_or_else(|| session_configuration.cwd().clone());
let cwd = session_configuration.cwd().clone();
let per_turn_config = Self::build_per_turn_config(&session_configuration, cwd.clone());
{
let mcp_connection_manager = self.services.mcp_connection_manager.load_full();
+2
View File
@@ -15,6 +15,7 @@ use codex_protocol::request_permissions::RequestPermissionsResponse;
use codex_protocol::request_user_input::RequestUserInputResponse;
use codex_rmcp_client::ElicitationResponse;
use codex_sandboxing::policy_transforms::merge_permission_profiles;
use codex_utils_absolute_path::AbsolutePathBuf;
use rmcp::model::RequestId;
use tokio::sync::oneshot;
@@ -103,6 +104,7 @@ pub(crate) struct PendingRequestPermissions {
pub(crate) tx_response: oneshot::Sender<RequestPermissionsResponse>,
pub(crate) requested_permissions: RequestPermissionProfile,
pub(crate) environment: TurnEnvironmentSelection,
pub(crate) compatibility_cwd: AbsolutePathBuf,
}
impl TurnState {
+3 -2
View File
@@ -23,6 +23,7 @@ use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::ThreadSource;
use codex_protocol::protocol::TurnStartedEvent;
use codex_protocol::protocol::UserMessageEvent;
use codex_utils_path_uri::PathUri;
use core_test_support::PathBufExt;
use core_test_support::PathExt;
use core_test_support::responses::mount_models_once;
@@ -331,7 +332,7 @@ async fn start_thread_rejects_explicit_local_environment_when_default_provider_i
parent_trace: None,
environments: vec![TurnEnvironmentSelection {
environment_id: "local".to_string(),
cwd: config.cwd.clone(),
cwd: PathUri::from_abs_path(&config.cwd),
}],
thread_extension_init: Default::default(),
})
@@ -594,7 +595,7 @@ async fn resume_and_fork_do_not_restore_thread_environments_from_rollout() {
std::fs::create_dir_all(&selected_cwd).expect("create selected cwd");
let environments = vec![TurnEnvironmentSelection {
environment_id: "local".to_string(),
cwd: selected_cwd.clone(),
cwd: PathUri::from_abs_path(&selected_cwd),
}];
let default_cwd = config.cwd.clone();
let mut source_config = config.clone();
+1 -1
View File
@@ -104,7 +104,7 @@ impl UserInstructionsProvider for RecordingUserInstructionsProvider {
pub fn local(cwd: AbsolutePathBuf) -> TurnEnvironmentSelection {
TurnEnvironmentSelection {
environment_id: codex_exec_server::LOCAL_ENVIRONMENT_ID.to_string(),
cwd,
cwd: PathUri::from_abs_path(&cwd),
}
}
@@ -16,6 +16,7 @@ wine_rust_test(
"//codex-rs/features",
"//codex-rs/protocol",
"//codex-rs/utils/cargo-bin",
"//codex-rs/utils/path-uri",
"@crates//:anyhow",
"@crates//:pretty_assertions",
"@crates//:serde_json",
@@ -13,6 +13,7 @@ use codex_protocol::protocol::Op;
use codex_protocol::protocol::TurnEnvironmentSelection;
use codex_protocol::protocol::TurnEnvironmentSelections;
use codex_protocol::user_input::UserInput;
use codex_utils_path_uri::PathUri;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_function_call;
@@ -93,7 +94,7 @@ async fn windows_exec_server_records_host_shell_mismatch() -> Result<()> {
test.config.cwd.clone(),
vec![TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: test.config.cwd.clone(),
cwd: PathUri::from_abs_path(&test.config.cwd),
}],
);
+2 -2
View File
@@ -646,11 +646,11 @@ async fn multi_environment_thread_loads_every_project_and_keeps_creation_snapsho
environments: vec![
TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: test.config.cwd.clone(),
cwd: PathUri::from_abs_path(&test.config.cwd),
},
TurnEnvironmentSelection {
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
cwd: local_root.path().to_path_buf().try_into()?,
cwd: PathUri::from_path(local_root.path())?,
},
],
thread_extension_init: Default::default(),
+1 -1
View File
@@ -1635,7 +1635,7 @@ async fn apply_patch_turn_diff_tracks_local_and_remote_environment_paths() -> Re
local(shared_cwd.clone()),
TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: shared_cwd.clone(),
cwd: PathUri::from_abs_path(&shared_cwd),
},
];
test.codex
+5 -5
View File
@@ -352,7 +352,7 @@ async fn exec_command_routes_to_selected_remote_environment() -> Result<()> {
.await?;
let remote_selection = TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: remote_cwd.clone(),
cwd: PathUri::from_abs_path(&remote_cwd),
};
let multi_env_output = exec_command_routing_output(
&test,
@@ -508,7 +508,7 @@ async fn remote_request_permissions_grant_unblocks_later_remote_exec() -> Result
local(local_cwd.path().abs()),
TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: remote_cwd.clone(),
cwd: PathUri::from_abs_path(&remote_cwd),
},
],
)
@@ -648,7 +648,7 @@ async fn apply_patch_freeform_routes_to_selected_remote_environment() -> Result<
local(local_cwd.path().abs()),
TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: remote_cwd.clone(),
cwd: PathUri::from_abs_path(&remote_cwd),
},
]),
)
@@ -731,7 +731,7 @@ async fn apply_patch_approvals_are_remembered_per_environment() -> Result<()> {
local(local_cwd.path().abs()),
TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: remote_cwd.clone(),
cwd: PathUri::from_abs_path(&remote_cwd),
},
];
let local_patch = format!(
@@ -929,7 +929,7 @@ async fn apply_patch_intercepted_exec_command_routes_to_selected_remote_environm
local(local_cwd.path().abs()),
TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: remote_cwd.clone(),
cwd: PathUri::from_abs_path(&remote_cwd),
},
]),
)
+1 -1
View File
@@ -624,7 +624,7 @@ async fn view_image_routes_to_selected_remote_environment() -> anyhow::Result<()
.await?;
let remote_selection = TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: remote_cwd.clone(),
cwd: PathUri::from_abs_path(&remote_cwd),
};
let call_id = "call-view-image-multi-env";
let response_mock = mount_sse_sequence(
+1
View File
@@ -20,6 +20,7 @@ codex-execpolicy = { workspace = true }
codex-network-proxy = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-image = { workspace = true }
codex-utils-path-uri = { workspace = true }
codex-utils-string = { workspace = true }
encoding_rs = { workspace = true }
globset = { workspace = true }
+17 -12
View File
@@ -52,6 +52,7 @@ use crate::request_permissions::RequestPermissionsResponse;
use crate::request_user_input::RequestUserInputResponse;
use crate::user_input::UserInput;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
@@ -109,7 +110,7 @@ pub const USER_MESSAGE_BEGIN: &str = "## My request for Codex:";
#[derive(Debug, Clone, PartialEq)]
pub struct TurnEnvironmentSelection {
pub environment_id: String,
pub cwd: AbsolutePathBuf,
pub cwd: PathUri,
}
#[derive(Debug, Clone, PartialEq)]
@@ -123,19 +124,9 @@ impl TurnEnvironmentSelections {
legacy_fallback_cwd: AbsolutePathBuf,
environments: Vec<TurnEnvironmentSelection>,
) -> Self {
let mut settings = Self {
Self {
legacy_fallback_cwd,
environments,
};
settings.sync_primary_environment_cwd();
settings
}
fn sync_primary_environment_cwd(&mut self) {
if let Some(turn_environment) = self.environments.first_mut()
&& turn_environment.cwd != self.legacy_fallback_cwd
{
turn_environment.cwd = self.legacy_fallback_cwd.clone();
}
}
}
@@ -5464,4 +5455,18 @@ mod tests {
assert_eq!(info.model_context_window, Some(258_400));
}
#[test]
fn legacy_fallback_cwd_does_not_replace_selected_environment_cwd() {
let selected_cwd = PathUri::parse("file:///C:/workspace/project").expect("selected cwd");
let settings = TurnEnvironmentSelections::new(
AbsolutePathBuf::current_dir().expect("legacy cwd"),
vec![TurnEnvironmentSelection {
environment_id: "windows".to_string(),
cwd: selected_cwd.clone(),
}],
);
assert_eq!(settings.environments[0].cwd, selected_cwd);
}
}