Preserve --add-dir when starting local TUI threads (#65087)

## Why

Selecting a permission profile for a new local thread could drop directories
explicitly supplied with `--add-dir`. Starting a thread in a different
directory could also lose those additions.

## What changed

Carry explicit additions into local thread starts. When a permission profile
is selected, send the working directory and the explicit additions as
runtime workspace roots. Require the app server to confirm each added
directory before accepting the thread. Decode local workspace roots as
native paths so tabs and newlines in directory names survive.

## Testing

Extend tests for startup, managed worktree creation, and permission-profile
selection. Cover an added directory with a tab in its name on Unix and the
error for an unconfirmed directory.

GitOrigin-RevId: 97beb528aa396b97d6d0ad664fde8abe3b9e2bbf
This commit is contained in:
Eric Traut
2026-12-01 21:18:55 +00:00
committed by copyberry
parent 1e832a92c2
commit 6801507507
13 changed files with 164 additions and 52 deletions
+1 -1
View File
@@ -171,7 +171,7 @@ impl App {
local_settings: &local_settings,
config: &config,
},
Some(choices),
crate::app_server_session::ThreadStartChoices::Launch(&choices),
/*session_start_source*/ None,
remote_cwd.as_deref(),
selected_profile.as_ref(),
+1 -1
View File
@@ -298,7 +298,7 @@ impl App {
local_settings: &local_settings,
config: &config,
},
Some(choices),
crate::app_server_session::ThreadStartChoices::Launch(&choices),
/*session_start_source*/ None,
/*remote_cwd_override*/ None,
/*selected_profile*/ None,
+1 -1
View File
@@ -1555,7 +1555,7 @@ impl App {
local_settings: &local_settings,
config: &config
},
Some(choices),
crate::app_server_session::ThreadStartChoices::Launch(&choices),
session_start_source,
/*remote_cwd_override*/ None,
/*selected_profile*/ None,
@@ -740,14 +740,7 @@ async fn command_center_new_preserves_only_selected_server_profiles() -> Result<
display_label: "server-only".into(),
};
let started = server
.start_thread_with_session_start_source(
&app.local_settings,
&app.config,
/*session_start_source*/ None,
/*remote_cwd_override*/ None,
Some(&selection),
/*host_project_cwd*/ None,
)
.start_thread_in_directory(&app.local_settings, &app.config, Some(&selection), &[])
.await?;
app.enqueue_primary_thread_session(started.session, started.turns)
.await?;
@@ -7043,7 +7043,21 @@ terminal_visualization_instructions = true
.lock()
.await
.set_turns(vec![completed]);
let extra = dunce::canonicalize(root.path())?.join("shared");
fs::create_dir(&extra)?;
for mode in [ManagedWorktreeMode::Fork, ManagedWorktreeMode::New] {
if mode == ManagedWorktreeMode::New {
app.harness_overrides.additional_writable_roots = vec![extra.clone()];
app.agents_overview.requested_permission_profiles.insert(
unsaved,
PermissionProfileSelection {
profile_id: ":workspace".into(),
approval_policy: None,
approvals_reviewer: None,
display_label: "Workspace".into(),
},
);
}
requests.lock().expect("request recorder lock").clear();
crate::boxed_future!(app.handle_event(
&mut tui,
@@ -7058,6 +7072,12 @@ terminal_visualization_instructions = true
.await?;
}
assert_eq!(app.chat_widget.thread_id() != Some(unsaved), is_new);
if is_new {
assert_eq!(
recorded_params(&requests, "thread/start")[0]["runtimeWorkspaceRoots"],
serde_json::json!([app.config.cwd, extra])
);
}
assert_eq!(recorded_params(&requests, "thread/fork").len(), 0);
}
let saved_owner = entries
@@ -358,6 +358,9 @@ requires_openai_auth = false
let mut cli_kv_overrides = Vec::new();
let mut loader_overrides = LoaderOverrides::without_managed_config_for_tests();
match choice {
"embedded_saved" => harness_overrides
.additional_writable_roots
.push(client_home.path().canonicalize()?.abs().into_path_buf()),
"tier_reset" => harness_overrides.service_tier = Some(None),
"disabled_fast" => cli_kv_overrides.extend([
("service_tier".into(), "fast".into()),
@@ -556,6 +559,12 @@ requires_openai_auth = false
);
}
if choice == "embedded_saved" {
assert!(
started
.session
.runtime_workspace_roots
.contains(&client_home.path().canonicalize()?.abs().into())
);
assert_eq!(
started.session.approvals_reviewer,
ApprovalsReviewer::AutoReview
+2 -4
View File
@@ -479,13 +479,11 @@ impl App {
.await
} else {
app_server
.start_thread_with_session_start_source(
.start_thread_in_directory(
&local_settings,
&config,
/*session_start_source*/ None,
/*remote_cwd_override*/ None,
selected_profile.as_ref(),
/*host_project_cwd*/ None,
&self.harness_overrides.additional_writable_roots,
)
.await
};
+89 -31
View File
@@ -624,6 +624,11 @@ pub(crate) enum TurnPermissionsOverride {
)]
pub(crate) struct UnsupportedLegacyPermissionProfile;
pub(crate) enum ThreadStartChoices<'a> {
Launch(&'a StartupLaunchChoices),
Session(&'a [PathBuf]),
}
/// The environment choice for a new Cloud thread.
pub(crate) enum CloudThreadStart<'a> {
Project(Option<&'a std::path::Path>),
@@ -1223,36 +1228,32 @@ impl AppServerSession {
#[cfg(test)]
pub(crate) async fn start_thread(&mut self, config: &Config) -> Result<AppServerStartedThread> {
self.start_thread_with_session_start_source(
self.start_thread_in_directory(
&crate::test_support::client_settings(config),
config,
/*session_start_source*/ None,
/*remote_cwd_override*/ None,
/*selected_profile*/ None,
/*host_project_cwd*/ None,
&[],
)
.await
}
pub(crate) async fn start_thread_with_session_start_source(
pub(crate) async fn start_thread_in_directory(
&mut self,
local_settings: &LocalSettings,
config: &Config,
session_start_source: Option<ThreadStartSource>,
remote_cwd_override: Option<&std::path::Path>,
selected_profile: Option<&PermissionProfileSelection>,
host_project_cwd: Option<&std::path::Path>,
additional_dirs: &[PathBuf],
) -> Result<AppServerStartedThread> {
self.start_thread_with_environment(
crate::session_start::SessionStartConfig {
local_settings,
config,
},
/*choices*/ None,
session_start_source,
remote_cwd_override,
ThreadStartChoices::Session(additional_dirs),
/*session_start_source*/ None,
/*remote_cwd_override*/ None,
selected_profile,
CloudThreadStart::Project(host_project_cwd),
CloudThreadStart::Project(None),
)
.await
}
@@ -1260,7 +1261,7 @@ impl AppServerSession {
pub(crate) async fn start_thread_with_environment(
&mut self,
settings: crate::session_start::SessionStartConfig<'_>,
choices: Option<StartupLaunchChoices>,
choices: ThreadStartChoices<'_>,
session_start_source: Option<ThreadStartSource>,
remote_cwd_override: Option<&std::path::Path>,
selected_profile: Option<&PermissionProfileSelection>,
@@ -1278,7 +1279,13 @@ impl AppServerSession {
local_settings,
config,
} = settings;
let mut launch = match choices.as_ref() {
let (choices, additions) = match choices {
ThreadStartChoices::Launch(choices) => {
(Some(choices), choices.additional_dirs.as_slice())
}
ThreadStartChoices::Session(additions) => (None, additions),
};
let mut launch = match choices {
Some(choices) => LaunchOverrides::for_launch(
&config.config_layer_stack,
config.features.get(),
@@ -1288,15 +1295,11 @@ impl AppServerSession {
),
None => LaunchOverrides::for_session(config, self.thread_params_mode()),
};
let defaults_unavailable = choices
.as_ref()
.is_some_and(|choices| choices.server_defaults_unavailable);
let defaults_unavailable =
choices.is_some_and(|choices| choices.server_defaults_unavailable);
let tier_model = if defaults_unavailable && launch.service_tier.is_none() {
None
} else if choices
.as_ref()
.is_some_and(|choices| choices.server_model_cleared)
{
} else if choices.is_some_and(|choices| choices.server_model_cleared) {
config.model.as_deref().or_else(|| {
self.available_models
.iter()
@@ -1340,8 +1343,19 @@ impl AppServerSession {
params.daybreak_enabled =
(config.daybreak_enabled && !config.ephemeral).then_some(true);
}
let additions = if self.thread_params_mode == ThreadParamsMode::Embedded {
additions
} else {
&[]
};
if let Some(selected_profile) = selected_profile {
params.runtime_workspace_roots = None;
// Carry only deliberate additions into a different server-resolved policy.
params.runtime_workspace_roots = (!additions.is_empty()).then(|| {
std::iter::once(config.cwd.clone())
.chain(additions.iter().map(|dir| config.cwd.join(dir)))
.map(LegacyAppPathString::from)
.collect()
});
params.permissions = Some(selected_profile.profile_id.clone());
params.sandbox = None;
params.approval_policy = selected_profile.approval_policy;
@@ -1385,6 +1399,10 @@ impl AppServerSession {
cwd,
)
.await?;
if let Err(error) = confirm_added_directories(&started.session, additions) {
let _ = self.thread_unsubscribe(started.session.thread_id).await;
return Err(error);
}
if let Some(permissions) = selected_permissions {
started.session.permission_profile = permissions;
}
@@ -2588,6 +2606,7 @@ pub(crate) async fn start_thread_with_request_handle(
&launch_choices.approval_policy,
);
apply_prewarm_reasoning_summary(&mut params, &config, &request_handle);
let additional_dirs = std::mem::take(&mut launch_choices.additional_dirs);
if thread_params_mode.settings_owner() == ThreadSettingsOwner::Client {
thread_tool_transport
.check_namespace(&request_handle, &config.cwd)
@@ -2612,10 +2631,26 @@ pub(crate) async fn start_thread_with_request_handle(
cwd,
)
.await?;
if thread_params_mode == ThreadParamsMode::Embedded {
confirm_added_directories(&started.session, &additional_dirs)?;
}
started.task_tools_available = task_tools_available;
Ok(started)
}
fn confirm_added_directories(session: &ThreadSessionState, additions: &[PathBuf]) -> Result<()> {
for path in additions {
let root = PathUri::from(AbsolutePathBuf::from_absolute_path(path)?);
if !session.runtime_workspace_roots.contains(&root) {
color_eyre::eyre::bail!(
"The app server did not confirm --add-dir {}.",
path.display()
);
}
}
Ok(())
}
pub(crate) fn workspace_display(
name: Option<String>,
routing: Option<codex_app_server_protocol::WorkspaceRouting>,
@@ -3257,7 +3292,10 @@ async fn thread_session_state_from_thread_start_response(
Some(&response.sandbox),
response.active_permission_profile.clone().map(Into::into),
cwd,
response.runtime_workspace_roots.clone(),
decode_workspace_roots(
&response.runtime_workspace_roots,
thread_params_mode == ThreadParamsMode::Embedded,
)?,
response.instruction_source_path_uris(),
response.reasoning_effort.clone(),
local_settings,
@@ -3297,7 +3335,10 @@ async fn thread_session_state_from_thread_resume_response(
Some(&response.sandbox),
response.active_permission_profile.clone().map(Into::into),
cwd,
response.runtime_workspace_roots.clone(),
decode_workspace_roots(
&response.runtime_workspace_roots,
/*local_start*/ false,
)?,
response.instruction_source_path_uris(),
response.reasoning_effort.clone(),
local_settings,
@@ -3336,7 +3377,10 @@ async fn thread_session_state_from_thread_fork_response(
Some(&response.sandbox),
response.active_permission_profile.clone().map(Into::into),
cwd,
response.runtime_workspace_roots.clone(),
decode_workspace_roots(
&response.runtime_workspace_roots,
/*local_start*/ false,
)?,
response.instruction_source_path_uris(),
response.reasoning_effort.clone(),
local_settings,
@@ -3373,6 +3417,25 @@ fn display_permission_profile_from_thread_response(
}
}
fn decode_workspace_roots(
roots: &[LegacyAppPathString],
local_start: bool,
) -> Result<Vec<PathUri>, String> {
roots
.iter()
.cloned()
.map(|root| {
if local_start && root.as_path().is_absolute() {
// Native conversion preserves tabs and newlines that URL parsing would strip.
AbsolutePathBuf::try_from(root).map(PathUri::from)
} else {
PathUri::try_from(root)
}
})
.collect::<Result<_, _>>()
.map_err(|err| err.to_string())
}
pub(crate) fn decode_thread_cwd(
cwd: &LegacyAppPathString,
convention: Option<PathConvention>,
@@ -3402,7 +3465,7 @@ async fn thread_session_state_from_thread_response(
sandbox: Option<&codex_app_server_protocol::SandboxPolicy>,
active_permission_profile: Option<ActivePermissionProfile>,
cwd: PathUri,
runtime_workspace_roots: Vec<LegacyAppPathString>,
runtime_workspace_roots: Vec<PathUri>,
instruction_source_paths: Vec<PathUri>,
reasoning_effort: Option<codex_protocol::openai_models::ReasoningEffort>,
local_settings: &LocalSettings,
@@ -3419,11 +3482,6 @@ async fn thread_session_state_from_thread_response(
&local_settings.history,
);
let (log_id, entry_count) = codex_message_history::history_metadata(&history_config).await;
let runtime_workspace_roots = runtime_workspace_roots
.into_iter()
.map(PathUri::try_from)
.collect::<Result<Vec<_>, _>>()
.map_err(|err| err.to_string())?;
// Embedded sessions may substitute a local execution profile. Keep the wire
// projection even then, without changing how execution settings are adopted.
let confirmed_permissions = sandbox
@@ -149,7 +149,7 @@ async fn cloud_starts_use_each_requests_host_project_without_caching() {
local_settings: &local_settings,
config: &config,
},
/*choices*/ None,
crate::app_server_session::ThreadStartChoices::Session(&[]),
/*session_start_source*/ None,
/*remote_cwd_override*/ None,
/*selected_profile*/ None,
@@ -54,13 +54,11 @@ async fn lifecycle_metadata_uses_local_prompt_history() -> Result<()> {
app_server.thread_params_mode = mode;
let started = app_server
.start_thread_with_session_start_source(
.start_thread_in_directory(
&local_settings,
&config,
/*session_start_source*/ None,
/*remote_cwd_override*/ None,
/*selected_profile*/ None,
/*host_project_cwd*/ None,
&[],
)
.await?;
assert_eq!(started.session.message_history, expected);
@@ -95,7 +95,11 @@ impl AppServerSession {
/*sandbox*/ None,
config.permissions.active_permission_profile(),
super::decode_thread_cwd(&thread.cwd, self.path_convention())?,
LegacyAppPathString::from_abs_paths(&config.workspace_roots),
super::decode_workspace_roots(
&LegacyAppPathString::from_abs_paths(&config.workspace_roots),
/*local_start*/ false,
)
.map_err(color_eyre::eyre::Report::msg)?,
Vec::new(),
thread.reasoning_effort,
local_settings,
@@ -19,6 +19,7 @@ pub(crate) struct StartupLaunchChoices {
pub(crate) effort: Option<serde_json::Value>,
pub(crate) cloud_environment: Option<codex_app_server_client::EnvironmentSelection>,
pub(crate) accepted_model_migration: bool,
pub(super) additional_dirs: Vec<std::path::PathBuf>,
provider: Option<String>,
selected_profile: bool,
pub(super) approval_policy: StartupApprovalPolicy,
@@ -58,8 +59,10 @@ impl StartupLaunchChoices {
});
let effort = super::launch_value(layers, "model_reasoning_effort")
.map(|value| serde_json::json!(value));
let additional_dirs = harness_overrides.additional_writable_roots.clone();
if loader_overrides.user_config_profile.is_some() {
return Self {
additional_dirs,
service_tier,
model,
effort,
@@ -109,6 +112,7 @@ impl StartupLaunchChoices {
StartupApprovalPolicy::Invocation(None)
};
Self {
additional_dirs,
service_tier,
model,
effort,
@@ -242,6 +242,34 @@ stream_max_retries = 0
started.session.runtime_workspace_roots,
vec![default_cwd.into()]
);
// A local New with an explicit server profile carries only --add-dir.
app_server.thread_params_mode = ThreadParamsMode::Embedded;
let mut choices = StartupLaunchChoices::default();
let added = client_config.cwd.join(if cfg!(unix) { "shared\tfiles" } else { "shared files" });
std::fs::create_dir(added.as_path())?;
choices.additional_dirs = vec![added.to_path_buf()];
let selected = app_server.start_thread_with_environment(
crate::session_start::SessionStartConfig {
local_settings: &local_settings,
config: &server_config,
},
crate::app_server_session::ThreadStartChoices::Launch(&choices),
/*session_start_source*/ None,
/*remote_cwd_override*/ None,
Some(&PermissionProfileSelection {
profile_id: ":read-only".into(),
approval_policy: None,
approvals_reviewer: None,
display_label: "Read Only".into(),
}),
CloudThreadStart::Project(None),
).await?;
assert_eq!(selected.session.permission_profile, PermissionProfile::read_only());
assert_eq!(selected.session.runtime_workspace_roots,
vec![server_config.cwd.clone().into(), added.into()]);
let missing = confirm_added_directories(&selected.session, &[extra_root.to_path_buf()])
.unwrap_err().to_string().replace(&extra_root.display().to_string(), "<DIR>");
insta::assert_snapshot!(missing, @"The app server did not confirm --add-dir <DIR>.");
app_server.shutdown().await?;
Ok(())
})