Preserve environment configuration ownership (#38678)

## Why

Environment attachments can either inherit configuration from their thread or
provide their own. Later thread setting updates must refresh inherited
configuration without overwriting attachment-owned permissions and capability
roots.

## What changed

- Resolve each attachment's configuration when it is selected and retain
  whether it came from the thread or the attachment owner.
- Apply subsequent thread configuration updates only to thread-owned
  attachments, while preserving ownership across snapshots and child threads.
- Keep the resolved configuration with the environment selection so runtime
  consumers use a single canonical value.

## Testing

- Extend remote-environment coverage to verify that thread-owned permissions
  follow thread updates while owner-provided read-only permissions remain in
  effect.
- Cover configuration inheritance, attachment replacement, and owner-configured
  capability roots.

GitOrigin-RevId: fe70c4be5f151432b69bf4b141e316faa89036ae
This commit is contained in:
sayan-oai authored and copyberry committed 2026-08-15 00:43:44 +00:00
1 parent 233739e76a
commit 22bf16a37e
23 files changed
+343 -192

No files matched your search

+118 -65
View File
@@ -34,6 +34,26 @@ use crate::session::turn_context::TurnEnvironment;
use crate::shell::Shell;
use crate::shell_snapshot::ShellSnapshot;
/// Records whether a normalized config should follow later thread setting updates.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum EnvironmentConfigOrigin {
Thread,
Owner,
}
impl EnvironmentConfigOrigin {
/// Reconstructs the input form so another attachment boundary preserves config ownership.
pub(crate) fn into_input_selection(
self,
mut selection: TurnEnvironmentSelection,
) -> TurnEnvironmentSelection {
if self == Self::Thread {
selection.config = EnvironmentConfigState::FromThread;
}
selection
}
}
pub(crate) fn default_thread_environment_selections(
environment_manager: &EnvironmentManager,
cwd: &AbsolutePathBuf,
@@ -66,7 +86,7 @@ struct ResolvedEnvironment {
#[derive(Clone)]
struct SelectedTurnEnvironment {
selection: TurnEnvironmentSelection,
config: EnvironmentConfig,
config_origin: EnvironmentConfigOrigin,
environment: Arc<Environment>,
// Selection clones share one listener; the final handle drop aborts it.
connection_events_task: Option<Arc<AbortOnDropHandle<()>>>,
@@ -76,24 +96,33 @@ struct SelectedTurnEnvironment {
#[derive(Clone)]
pub(crate) struct StartingTurnEnvironment {
pub(crate) selection: TurnEnvironmentSelection,
config: EnvironmentConfig,
config_origin: EnvironmentConfigOrigin,
resolution: TurnEnvironmentResolution,
}
/// Resolves config once at the attachment boundary and records who owns future updates.
fn resolve_selection_config(
mut selection: TurnEnvironmentSelection,
thread_config: &EnvironmentConfig,
) -> (TurnEnvironmentSelection, EnvironmentConfigOrigin) {
let (config, origin) = match selection.config {
EnvironmentConfigState::FromThread => {
(thread_config.clone(), EnvironmentConfigOrigin::Thread)
}
EnvironmentConfigState::Ready(config) => (config, EnvironmentConfigOrigin::Owner),
EnvironmentConfigState::Pending => {
unreachable!("pending environment configuration is not supported yet")
}
};
selection.config = EnvironmentConfigState::Ready(config);
(selection, origin)
}
impl SelectedTurnEnvironment {
fn apply_configuration(
&mut self,
selection_config: EnvironmentConfigState,
thread_config: &EnvironmentConfig,
) {
self.config = match &selection_config {
EnvironmentConfigState::FromThread => thread_config.clone(),
EnvironmentConfigState::Ready(config) => config.clone(),
EnvironmentConfigState::Pending => {
unreachable!("pending environment configuration is not supported yet")
}
};
self.selection.config = selection_config;
fn refresh_thread_config(&mut self, config: &EnvironmentConfig) {
if self.config_origin == EnvironmentConfigOrigin::Thread {
self.selection.config = EnvironmentConfigState::Ready(config.clone());
}
}
}
@@ -139,9 +168,9 @@ impl ThreadEnvironments {
let TurnEnvironmentState::Ready(environment) = environment else {
return None;
};
let selection = environment.selection();
let selection = environment.selection;
let config_origin = environment.config_origin;
let selected_environment = Arc::clone(&environment.environment);
let inherited_config = environment.config;
let resolution: TurnEnvironmentResolution =
futures::future::ready(Ok(ResolvedEnvironment {
environment: environment.environment,
@@ -152,17 +181,13 @@ impl ThreadEnvironments {
.shared();
let mut inherited_environment = SelectedTurnEnvironment {
selection,
config: inherited_config,
config_origin,
environment: selected_environment,
connection_events_task: None,
resolution,
};
// Child threads get their own settings, but inherit any
// environment-owned policy that was already installed.
inherited_environment.apply_configuration(
inherited_environment.selection.config.clone(),
&thread_environment_config,
);
// Child threads re-infer thread-owned config while preserving owner config.
inherited_environment.refresh_thread_config(&thread_environment_config);
Some(inherited_environment)
})
.collect();
@@ -188,6 +213,8 @@ impl ThreadEnvironments {
if !seen_environment_ids.insert(selected_environment.environment_id.as_str()) {
continue;
}
let (selected_environment, config_origin) =
resolve_selection_config(selected_environment.clone(), thread_environment_config);
if let Some(environment) = previous.iter().find(|environment| {
let previous = &environment.selection;
previous.environment_id == selected_environment.environment_id
@@ -196,10 +223,8 @@ impl ThreadEnvironments {
}) && !matches!(environment.resolution.clone().now_or_never(), Some(Err(_)))
{
let mut environment = environment.clone();
environment.apply_configuration(
selected_environment.config.clone(),
thread_environment_config,
);
environment.selection = selected_environment;
environment.config_origin = config_origin;
next.push(environment);
continue;
}
@@ -235,17 +260,13 @@ impl ThreadEnvironments {
.remote_handle();
drop(tokio::spawn(resolution_task));
let resolution = resolution.boxed().shared();
let mut selected = SelectedTurnEnvironment {
selection: selected_environment.clone(),
config: thread_environment_config.clone(),
let selected = SelectedTurnEnvironment {
selection: selected_environment,
config_origin,
environment,
connection_events_task,
resolution,
};
selected.apply_configuration(
selected_environment.config.clone(),
thread_environment_config,
);
next.push(selected);
}
let removed_connection_tasks = previous
@@ -267,11 +288,16 @@ impl ThreadEnvironments {
}
}
/// Projects canonical selections back to caller input form without losing config ownership.
pub(crate) fn selections(&self) -> Vec<TurnEnvironmentSelection> {
self.environments
.load()
.iter()
.map(|environment| environment.selection.clone())
.map(|environment| {
environment
.config_origin
.into_input_selection(environment.selection.clone())
})
.collect()
}
@@ -299,14 +325,15 @@ impl ThreadEnvironments {
.unwrap_or_default()
}
pub(crate) fn update_environment_configs(&self, config: &EnvironmentConfig) {
/// Refreshes attachments whose configuration is inferred from the thread.
pub(crate) fn update_thread_config(&self, config: &EnvironmentConfig) {
let environments = self
.environments
.load()
.iter()
.map(|environment| {
let mut environment = environment.clone();
environment.apply_configuration(environment.selection.config.clone(), config);
environment.refresh_thread_config(config);
environment
})
.collect();
@@ -331,8 +358,8 @@ impl ThreadEnvironments {
)));
};
let thread_config = environment.config.clone();
environment.apply_configuration(EnvironmentConfigState::Ready(config), &thread_config);
environment.selection.config = EnvironmentConfigState::Ready(config);
environment.config_origin = EnvironmentConfigOrigin::Owner;
self.environments.store(Arc::new(environments));
Ok(())
}
@@ -346,8 +373,10 @@ impl ThreadEnvironments {
let environments = self.environments.load();
let mut selected_capability_roots = thread_selected_capability_roots.to_vec();
for environment in environments.iter() {
selected_capability_roots
.extend(environment.config.selected_capability_roots.iter().cloned());
let EnvironmentConfigState::Ready(config) = &environment.selection.config else {
unreachable!("selected environments always carry resolved configuration")
};
selected_capability_roots.extend(config.selected_capability_roots.iter().cloned());
}
let mut seen_root_ids = HashSet::with_capacity(selected_capability_roots.len());
selected_capability_roots.retain(|root| seen_root_ids.insert(root.id.clone()));
@@ -491,7 +520,7 @@ impl ThreadEnvironments {
if let Some(environment) = TurnEnvironmentState::from_resolution(
StartingTurnEnvironment {
selection: environment.selection.clone(),
config: environment.config.clone(),
config_origin: environment.config_origin,
resolution: environment.resolution.clone(),
},
resolved,
@@ -522,9 +551,9 @@ impl TurnEnvironmentState {
Some(Ok(environment)) => {
let mut turn_environment = TurnEnvironment::new(
starting.selection,
starting.config_origin,
environment.environment,
environment.shell,
starting.config,
);
turn_environment.shell_snapshot = environment.shell_snapshot;
Some(Self::Ready(turn_environment))
@@ -897,7 +926,7 @@ url = "ws://127.0.0.1:8765"
let environment = snapshot.primary().expect("local environment");
assert_eq!(environment.shell.as_ref(), Some(&local_shell));
assert_eq!(environment.config, expected_config);
assert_eq!(environment.config(), &expected_config);
}
#[tokio::test]
@@ -1107,6 +1136,10 @@ url = "ws://127.0.0.1:8765"
turn_environments.update_selections(&[remote.clone(), local.clone()], &expected_config);
let starting = turn_environments.snapshot().await;
let resolved_remote = TurnEnvironmentSelection {
config: EnvironmentConfigState::Ready(expected_config.clone()),
..remote.clone()
};
assert_eq!(
starting
.turn_environments()
@@ -1117,7 +1150,7 @@ url = "ws://127.0.0.1:8765"
assert_eq!(
starting
.turn_environments()
.map(|environment| environment.config.clone())
.map(|environment| environment.config().clone())
.collect::<Vec<_>>(),
vec![expected_config.clone()]
);
@@ -1126,13 +1159,13 @@ url = "ws://127.0.0.1:8765"
.starting()
.map(|environment| environment.selection.clone())
.collect::<Vec<_>>(),
vec![remote.clone()]
vec![resolved_remote.clone()]
);
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);
turn_environments.update_thread_config(&next_config);
let next_starting = turn_environments.snapshot().await;
let server = tokio::spawn(serve_environment_info(listener));
@@ -1161,7 +1194,7 @@ url = "ws://127.0.0.1:8765"
assert_eq!(
attached
.turn_environments()
.map(|environment| environment.config.clone())
.map(|environment| environment.config().clone())
.collect::<Vec<_>>(),
vec![expected_config.clone(), expected_config]
);
@@ -1170,7 +1203,7 @@ url = "ws://127.0.0.1:8765"
next_starting
.refresh_readiness()
.turn_environments()
.map(|environment| environment.config.clone())
.map(|environment| environment.config().clone())
.collect::<Vec<_>>(),
vec![next_config.clone(), next_config]
);
@@ -1240,7 +1273,7 @@ url = "ws://127.0.0.1:8765"
allow_login_shell: false,
..test_environment_config()
};
environments.update_environment_configs(&next_config);
environments.update_thread_config(&next_config);
assert!(
failed_resolution.ptr_eq(&environments.environments.load()[0].resolution),
"updating environment config must not retry a failed environment"
@@ -1252,7 +1285,14 @@ url = "ws://127.0.0.1:8765"
.starting()
.next()
.expect("expected the replacement environment to be starting");
assert_eq!(replacement.selection, selection);
assert_eq!(
replacement.selection,
TurnEnvironmentSelection {
config: EnvironmentConfigState::Ready(next_config),
..selection.clone()
}
);
assert_eq!(environments.selections(), vec![selection]);
assert!(!failed_resolution.ptr_eq(&replacement.resolution));
}
@@ -1373,10 +1413,13 @@ url = "ws://127.0.0.1:8765"
.expect("inherited environment"),
);
let inherited = TurnEnvironment::new(
selection.clone(),
TurnEnvironmentSelection {
config: EnvironmentConfigState::Ready(test_environment_config()),
..selection.clone()
},
EnvironmentConfigOrigin::Thread,
Arc::clone(&inherited_environment),
/*shell*/ None,
test_environment_config(),
);
let manager = Arc::new(environment_manager_without_environments());
manager
@@ -1411,7 +1454,7 @@ url = "ws://127.0.0.1:8765"
let inherited = snapshot.primary().expect("inherited environment");
assert!(Arc::ptr_eq(&inherited.environment, &inherited_environment));
assert_eq!(inherited.config, child_config);
assert_eq!(inherited.config(), &child_config);
}
#[tokio::test]
@@ -1448,6 +1491,16 @@ url = "ws://127.0.0.1:8765"
),
..test_environment_config()
};
parent.update_thread_config(&child_thread_config);
assert_eq!(
parent
.snapshot()
.await
.primary()
.expect("owner-configured environment")
.config(),
&parent_owner_config
);
let child = ThreadEnvironments::new(
manager,
crate::shell::default_user_shell(),
@@ -1471,10 +1524,10 @@ url = "ws://127.0.0.1:8765"
cleared_snapshot
.primary()
.expect("environment with cleared roots")
.config,
cleared_parent_owner_config
.config(),
&cleared_parent_owner_config
);
assert_eq!(child_environment.config, parent_owner_config);
assert_eq!(child_environment.config(), &parent_owner_config);
let changed_selection = TurnEnvironmentSelection {
cwd: PathUri::from_abs_path(&cwd.join("changed")),
@@ -1484,7 +1537,7 @@ url = "ws://127.0.0.1:8765"
parent.update_selections(std::slice::from_ref(&changed_selection), &new_thread_config);
let changed_snapshot = parent.snapshot().await;
let changed_environment = changed_snapshot.primary().expect("changed environment");
assert_eq!(changed_environment.config, new_thread_config);
assert_eq!(changed_environment.config(), &new_thread_config);
}
#[tokio::test]
@@ -1514,11 +1567,11 @@ url = "ws://127.0.0.1:8765"
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: remote_cwd_uri.clone(),
workspace_roots: Vec::new(),
config: EnvironmentConfigState::FromThread,
config: EnvironmentConfigState::Ready(test_environment_config()),
},
EnvironmentConfigOrigin::Thread,
remote_environment.clone(),
/*shell*/ None,
test_environment_config(),
))],
};
let multiple = TurnEnvironmentSnapshot {
@@ -1528,11 +1581,11 @@ url = "ws://127.0.0.1:8765"
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: remote_cwd_uri,
workspace_roots: Vec::new(),
config: EnvironmentConfigState::FromThread,
config: EnvironmentConfigState::Ready(test_environment_config()),
},
EnvironmentConfigOrigin::Thread,
remote_environment,
/*shell*/ None,
test_environment_config(),
)),
TurnEnvironmentState::Ready(local.primary().expect("local environment").clone()),
],
@@ -1555,9 +1608,9 @@ url = "ws://127.0.0.1:8765"
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
cwd: PathUri::from_abs_path(&cwd),
workspace_roots: Vec::new(),
config: EnvironmentConfigState::FromThread,
config: EnvironmentConfigState::Ready(test_environment_config()),
},
config: test_environment_config(),
config_origin: EnvironmentConfigOrigin::Thread,
resolution: futures::future::pending().boxed().shared(),
})],
};