Apply permission profile updates to future turn environments (#37031)

## What changed

- Include the current permission profile in each turn environment's configuration.
- Refresh retained environment configurations when session settings change, while preserving the configuration already captured by active turns.
- Keep environment connection and shell snapshot resolution reusable across configuration updates.

## Testing

- Cover permission profile updates applied through both session settings updates and per-turn updates.
- Verify that pending environment resolutions use the configuration captured by their turn and that configuration-only updates do not retry failed environments.

GitOrigin-RevId: 923694f0729b87a118d7635ade3a8ca9bcd4e7b1
This commit is contained in:
sayan-oai
2026-08-05 05:30:51 +00:00
committed by copyberry
parent 56b82e676c
commit 30d99232f4
15 changed files with 339 additions and 116 deletions
+178 -76
View File
@@ -23,6 +23,7 @@ use futures::future::Shared;
use tokio_util::task::AbortOnDropHandle;
use crate::session::turn_context::EnvironmentConfig;
use crate::session::turn_context::ShellSnapshotTask;
use crate::session::turn_context::TurnEnvironment;
use crate::shell::Shell;
use crate::shell_snapshot::ShellSnapshot;
@@ -43,12 +44,23 @@ pub(crate) fn default_thread_environment_selections(
.collect()
}
type TurnEnvironmentResult = Result<TurnEnvironment, Arc<ExecServerError>>;
type TurnEnvironmentResult = Result<ResolvedEnvironment, Arc<ExecServerError>>;
type TurnEnvironmentResolution = Shared<BoxFuture<'static, TurnEnvironmentResult>>;
// Shared startup result used to build each turn's environment with its own config
// without restarting the connection or shell resolution.
#[derive(Clone)]
struct ResolvedEnvironment {
environment: Arc<Environment>,
shell: Option<Shell>,
shell_snapshot: ShellSnapshotTask,
}
#[derive(Clone)]
struct SelectedTurnEnvironment {
selection: TurnEnvironmentSelection,
// Temporary: copied from thread settings until environments supply their own config.
config: EnvironmentConfig,
environment: Arc<Environment>,
// Selection clones share one listener; the final handle drop aborts it.
connection_events_task: Option<Arc<AbortOnDropHandle<()>>>,
@@ -58,6 +70,7 @@ struct SelectedTurnEnvironment {
#[derive(Clone)]
pub(crate) struct StartingTurnEnvironment {
pub(crate) selection: TurnEnvironmentSelection,
config: EnvironmentConfig,
resolution: TurnEnvironmentResolution,
}
@@ -80,8 +93,6 @@ impl StartingTurnEnvironment {
pub(crate) struct ThreadEnvironments {
environment_manager: Arc<EnvironmentManager>,
local_shell: Shell,
// Temporary thread-wide config source until environments supply their own config.
fallback_environment_config: EnvironmentConfig,
shell_snapshot: ShellSnapshot,
non_blocking_snapshots: bool,
environments: ArcSwap<Vec<SelectedTurnEnvironment>>,
@@ -92,7 +103,7 @@ impl ThreadEnvironments {
pub(crate) fn new(
environment_manager: Arc<EnvironmentManager>,
local_shell: Shell,
fallback_environment_config: EnvironmentConfig,
thread_environment_config: EnvironmentConfig,
shell_snapshot: ShellSnapshot,
current: TurnEnvironmentSnapshot,
non_blocking_snapshots: bool,
@@ -102,17 +113,23 @@ impl ThreadEnvironments {
.environments
.into_iter()
.filter_map(|environment| {
let TurnEnvironmentState::Ready(mut environment) = environment else {
let TurnEnvironmentState::Ready(environment) = environment else {
return None;
};
// Child threads can have a different shell policy from their parent.
environment.config = fallback_environment_config.clone();
let selection = environment.selection();
let selected_environment = Arc::clone(&environment.environment);
let resolution: TurnEnvironmentResolution =
futures::future::ready(Ok(environment)).boxed().shared();
futures::future::ready(Ok(ResolvedEnvironment {
environment: environment.environment,
shell: environment.shell,
shell_snapshot: environment.shell_snapshot,
}))
.boxed()
.shared();
Some(SelectedTurnEnvironment {
selection,
// Child threads can have different environment config from their parent.
config: thread_environment_config.clone(),
environment: selected_environment,
connection_events_task: None,
resolution,
@@ -122,7 +139,6 @@ impl ThreadEnvironments {
Self {
environment_manager,
local_shell,
fallback_environment_config,
shell_snapshot,
non_blocking_snapshots,
environments: ArcSwap::from_pointee(environments),
@@ -130,7 +146,11 @@ impl ThreadEnvironments {
}
}
pub(crate) fn update_selections(&self, environments: &[TurnEnvironmentSelection]) {
pub(crate) fn update_selections(
&self,
environments: &[TurnEnvironmentSelection],
thread_environment_config: &EnvironmentConfig,
) {
let previous = self.environments.load();
let mut seen_environment_ids = HashSet::with_capacity(environments.len());
let mut next = Vec::with_capacity(environments.len());
@@ -143,7 +163,9 @@ impl ThreadEnvironments {
.find(|environment| environment.selection == *selected_environment)
&& !matches!(environment.resolution.clone().now_or_never(), Some(Err(_)))
{
next.push(environment.clone());
let mut environment = environment.clone();
environment.config = thread_environment_config.clone();
next.push(environment);
continue;
}
@@ -173,7 +195,6 @@ impl ThreadEnvironments {
selected_environment.clone(),
Arc::clone(&environment),
self.local_shell.clone(),
self.fallback_environment_config.clone(),
self.shell_snapshot.clone(),
)
.remote_handle();
@@ -181,6 +202,7 @@ impl ThreadEnvironments {
let resolution = resolution.boxed().shared();
next.push(SelectedTurnEnvironment {
selection: selected_environment.clone(),
config: thread_environment_config.clone(),
environment,
connection_events_task,
resolution,
@@ -205,6 +227,20 @@ impl ThreadEnvironments {
}
}
pub(crate) fn update_environment_configs(&self, config: &EnvironmentConfig) {
let environments = self
.environments
.load()
.iter()
.map(|environment| {
let mut environment = environment.clone();
environment.config = config.clone();
environment
})
.collect();
self.environments.store(Arc::new(environments));
}
fn spawn_connection_event_listener(
environment: &Environment,
environment_id: String,
@@ -273,7 +309,6 @@ impl ThreadEnvironments {
selection: TurnEnvironmentSelection,
environment: Arc<Environment>,
local_shell: Shell,
config: EnvironmentConfig,
shell_snapshot: ShellSnapshot,
) -> BoxFuture<'static, TurnEnvironmentResult> {
async move {
@@ -303,21 +338,16 @@ impl ThreadEnvironments {
} else {
Some(local_shell)
};
let mut turn_environment = TurnEnvironment::new(
selection.environment_id,
environment,
selection.cwd,
selection.workspace_roots,
shell,
config,
);
let task = shell_snapshot
.build(turn_environment.clone())
.build(Arc::clone(&environment), selection.cwd, shell.clone())
.boxed()
.shared();
drop(tokio::spawn(task.clone()));
turn_environment.shell_snapshot = task;
Ok(turn_environment)
Ok(ResolvedEnvironment {
environment,
shell,
shell_snapshot: task,
})
}
.boxed()
}
@@ -335,6 +365,7 @@ impl ThreadEnvironments {
if let Some(environment) = TurnEnvironmentState::from_resolution(
StartingTurnEnvironment {
selection: environment.selection.clone(),
config: environment.config.clone(),
resolution: environment.resolution.clone(),
},
resolved,
@@ -362,7 +393,18 @@ impl TurnEnvironmentState {
resolved: Option<TurnEnvironmentResult>,
) -> Option<Self> {
match resolved {
Some(Ok(environment)) => Some(Self::Ready(environment)),
Some(Ok(environment)) => {
let mut turn_environment = TurnEnvironment::new(
starting.selection.environment_id,
environment.environment,
starting.selection.cwd,
starting.selection.workspace_roots,
environment.shell,
starting.config,
);
turn_environment.shell_snapshot = environment.shell_snapshot;
Some(Self::Ready(turn_environment))
}
Some(Err(err)) => {
tracing::debug!(
environment_id = %starting.selection.environment_id,
@@ -486,6 +528,7 @@ impl TurnEnvironmentSnapshot {
mod tests {
use std::time::Duration;
use crate::config::PermissionProfileSnapshot;
use codex_exec_server::Environment;
use codex_exec_server::ExecServerRuntimePaths;
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
@@ -493,6 +536,8 @@ mod tests {
use codex_exec_server_test_support::environment_manager_without_environments;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_protocol::models::ActivePermissionProfile;
use codex_protocol::models::PermissionProfile;
use codex_protocol::protocol::TurnEnvironmentSelection;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
@@ -509,6 +554,13 @@ mod tests {
use super::*;
fn test_environment_config() -> EnvironmentConfig {
EnvironmentConfig {
allow_login_shell: true,
permission_profile: PermissionProfileSnapshot::legacy(PermissionProfile::read_only()),
}
}
async fn resolve_turn_environments(
environment_manager: Arc<EnvironmentManager>,
selections: &[TurnEnvironmentSelection],
@@ -516,14 +568,12 @@ mod tests {
let turn_environments = Arc::new(ThreadEnvironments::new(
environment_manager,
crate::shell::default_user_shell(),
EnvironmentConfig {
allow_login_shell: true,
},
test_environment_config(),
ShellSnapshot::disabled(),
TurnEnvironmentSnapshot::default(),
/*non_blocking_snapshots*/ false,
));
turn_environments.update_selections(selections);
turn_environments.update_selections(selections, &test_environment_config());
turn_environments.snapshot().await;
turn_environments
}
@@ -668,27 +718,36 @@ url = "ws://127.0.0.1:8765"
shell_type: crate::shell::ShellType::Zsh,
shell_path: std::path::PathBuf::from("/configured/zsh"),
};
let expected_config = EnvironmentConfig {
allow_login_shell: false,
permission_profile: PermissionProfileSnapshot::active_with_profile_workspace_roots(
PermissionProfile::read_only(),
ActivePermissionProfile::read_only(),
vec![cwd.join("profile-root")],
),
};
let turn_environments = ThreadEnvironments::new(
Arc::new(EnvironmentManager::default_for_tests()),
local_shell.clone(),
EnvironmentConfig {
allow_login_shell: false,
},
expected_config.clone(),
ShellSnapshot::disabled(),
TurnEnvironmentSnapshot::default(),
/*non_blocking_snapshots*/ false,
);
turn_environments.update_selections(&[TurnEnvironmentSelection {
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
cwd: PathUri::from_abs_path(&cwd),
workspace_roots: Vec::new(),
}]);
turn_environments.update_selections(
&[TurnEnvironmentSelection {
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
cwd: PathUri::from_abs_path(&cwd),
workspace_roots: Vec::new(),
}],
&expected_config,
);
let snapshot = turn_environments.snapshot().await;
let environment = snapshot.primary().expect("local environment");
assert_eq!(environment.shell.as_ref(), Some(&local_shell));
assert!(!environment.config.allow_login_shell);
assert_eq!(environment.config, expected_config);
}
#[tokio::test]
@@ -810,14 +869,13 @@ url = "ws://127.0.0.1:8765"
let environments = Arc::new(ThreadEnvironments::new(
manager,
crate::shell::default_user_shell(),
EnvironmentConfig {
allow_login_shell: true,
},
test_environment_config(),
ShellSnapshot::disabled(),
TurnEnvironmentSnapshot::default(),
/*non_blocking_snapshots*/ false,
));
environments.update_selections(std::slice::from_ref(&selection));
environments
.update_selections(std::slice::from_ref(&selection), &test_environment_config());
let snapshot_task = tokio::spawn({
let environments = Arc::clone(&environments);
async move { environments.snapshot().await }
@@ -852,6 +910,14 @@ url = "ws://127.0.0.1:8765"
.await,
);
let cwd = AbsolutePathBuf::current_dir().expect("cwd");
let expected_config = EnvironmentConfig {
allow_login_shell: false,
permission_profile: PermissionProfileSnapshot::active_with_profile_workspace_roots(
PermissionProfile::read_only(),
ActivePermissionProfile::read_only(),
vec![cwd.join("profile-root")],
),
};
let cwd = PathUri::from_abs_path(&cwd);
let remote = TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
@@ -866,20 +932,19 @@ url = "ws://127.0.0.1:8765"
let turn_environments = ThreadEnvironments::new(
manager,
crate::shell::default_user_shell(),
EnvironmentConfig {
allow_login_shell: true,
},
test_environment_config(),
ShellSnapshot::disabled(),
TurnEnvironmentSnapshot::default(),
/*non_blocking_snapshots*/ true,
);
turn_environments.update_selections(std::slice::from_ref(&local));
turn_environments
.update_selections(std::slice::from_ref(&local), &test_environment_config());
turn_environments.environments.load()[0]
.resolution
.clone()
.await
.expect("local environment should resolve");
turn_environments.update_selections(&[remote.clone(), local.clone()]);
turn_environments.update_selections(&[remote.clone(), local.clone()], &expected_config);
let starting = turn_environments.snapshot().await;
assert_eq!(
@@ -889,6 +954,13 @@ url = "ws://127.0.0.1:8765"
.collect::<Vec<_>>(),
vec![local.clone()]
);
assert_eq!(
starting
.turn_environments()
.map(|environment| environment.config.clone())
.collect::<Vec<_>>(),
vec![expected_config.clone()]
);
assert_eq!(
starting
.starting()
@@ -899,6 +971,10 @@ url = "ws://127.0.0.1:8765"
assert_eq!(starting.to_selections(), vec![local.clone()]);
assert!(starting.single_local_environment().is_none());
let next_config = test_environment_config();
turn_environments.update_environment_configs(&next_config);
let next_starting = turn_environments.snapshot().await;
let server = tokio::spawn(serve_environment_info(listener));
timeout(
std::time::Duration::from_secs(5),
@@ -922,7 +998,22 @@ url = "ws://127.0.0.1:8765"
.collect::<Vec<_>>(),
vec![remote.clone(), local.clone()]
);
assert_eq!(
attached
.turn_environments()
.map(|environment| environment.config.clone())
.collect::<Vec<_>>(),
vec![expected_config.clone(), expected_config]
);
assert_eq!(attached.to_selections(), vec![remote, local]);
assert_eq!(
next_starting
.refresh_readiness()
.turn_environments()
.map(|environment| environment.config.clone())
.collect::<Vec<_>>(),
vec![next_config.clone(), next_config]
);
server.await.expect("server task");
}
@@ -943,14 +1034,13 @@ url = "ws://127.0.0.1:8765"
let environments = ThreadEnvironments::new(
Arc::clone(&manager),
crate::shell::default_user_shell(),
EnvironmentConfig {
allow_login_shell: true,
},
test_environment_config(),
ShellSnapshot::disabled(),
TurnEnvironmentSnapshot::default(),
/*non_blocking_snapshots*/ true,
);
environments.update_selections(std::slice::from_ref(&selection));
environments
.update_selections(std::slice::from_ref(&selection), &test_environment_config());
let failed_resolution = environments.environments.load()[0].resolution.clone();
assert!(failed_resolution.clone().await.is_err());
@@ -964,7 +1054,16 @@ url = "ws://127.0.0.1:8765"
/*connect_timeout*/ None,
)
.expect("replacement environment");
environments.update_selections(std::slice::from_ref(&selection));
let next_config = EnvironmentConfig {
allow_login_shell: false,
..test_environment_config()
};
environments.update_environment_configs(&next_config);
assert!(
failed_resolution.ptr_eq(&environments.environments.load()[0].resolution),
"updating environment config must not retry a failed environment"
);
environments.update_selections(std::slice::from_ref(&selection), &next_config);
let replacement = environments.snapshot().await;
let replacement = replacement
@@ -1000,15 +1099,14 @@ url = "ws://127.0.0.1:8765"
let environments = Arc::new(ThreadEnvironments::new(
Arc::clone(&manager),
crate::shell::default_user_shell(),
EnvironmentConfig {
allow_login_shell: true,
},
test_environment_config(),
ShellSnapshot::disabled(),
TurnEnvironmentSnapshot::default(),
/*non_blocking_snapshots*/ true,
));
environments.start_connection_event_forwarding(tx_event);
environments.update_selections(std::slice::from_ref(&selection));
environments
.update_selections(std::slice::from_ref(&selection), &test_environment_config());
let initial_snapshot = environments.snapshot().await;
let second_listener = TcpListener::bind("127.0.0.1:0")
.await
@@ -1026,12 +1124,16 @@ url = "ws://127.0.0.1:8765"
)
.expect("replace environment");
environments.update_selections(std::slice::from_ref(&selection));
environments
.update_selections(std::slice::from_ref(&selection), &test_environment_config());
let reused_snapshot = environments.snapshot().await;
environments.update_selections(&[TurnEnvironmentSelection {
cwd: PathUri::from_abs_path(&cwd.join("changed")),
..selection
}]);
environments.update_selections(
&[TurnEnvironmentSelection {
cwd: PathUri::from_abs_path(&cwd.join("changed")),
..selection
}],
&test_environment_config(),
);
let changed_snapshot = environments.snapshot().await;
let initial = initial_snapshot
@@ -1075,7 +1177,7 @@ url = "ws://127.0.0.1:8765"
}
#[tokio::test]
async fn inherited_environment_reuses_parent_handle_and_uses_child_login_policy() {
async fn inherited_environment_reuses_parent_handle_and_uses_child_config() {
let cwd = AbsolutePathBuf::current_dir().expect("cwd");
let selection = TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
@@ -1092,9 +1194,7 @@ url = "ws://127.0.0.1:8765"
selection.cwd.clone(),
Vec::new(),
/*shell*/ None,
EnvironmentConfig {
allow_login_shell: true,
},
test_environment_config(),
);
let manager = Arc::new(environment_manager_without_environments());
manager
@@ -1104,12 +1204,18 @@ url = "ws://127.0.0.1:8765"
/*connect_timeout*/ None,
)
.expect("replacement environment");
let child_config = EnvironmentConfig {
allow_login_shell: false,
permission_profile: PermissionProfileSnapshot::active_with_profile_workspace_roots(
PermissionProfile::read_only(),
ActivePermissionProfile::read_only(),
vec![cwd.join("child-profile-root")],
),
};
let environments = ThreadEnvironments::new(
manager,
crate::shell::default_user_shell(),
EnvironmentConfig {
allow_login_shell: false,
},
child_config.clone(),
ShellSnapshot::disabled(),
TurnEnvironmentSnapshot {
environments: vec![TurnEnvironmentState::Ready(inherited)],
@@ -1117,12 +1223,12 @@ url = "ws://127.0.0.1:8765"
/*non_blocking_snapshots*/ false,
);
environments.update_selections(std::slice::from_ref(&selection));
environments.update_selections(std::slice::from_ref(&selection), &child_config);
let snapshot = environments.snapshot().await;
let inherited = snapshot.primary().expect("inherited environment");
assert!(Arc::ptr_eq(&inherited.environment, &inherited_environment));
assert!(!inherited.config.allow_login_shell);
assert_eq!(inherited.config, child_config);
}
#[tokio::test]
@@ -1151,9 +1257,7 @@ url = "ws://127.0.0.1:8765"
cwd_uri.clone(),
Vec::new(),
/*shell*/ None,
EnvironmentConfig {
allow_login_shell: true,
},
test_environment_config(),
))],
};
let multiple = TurnEnvironmentSnapshot {
@@ -1165,9 +1269,7 @@ url = "ws://127.0.0.1:8765"
cwd_uri,
Vec::new(),
/*shell*/ None,
EnvironmentConfig {
allow_login_shell: true,
},
test_environment_config(),
)),
],
};