Preserve workspace roots across client and server platforms (#62377)

## Why

A TUI connected to an app server on another platform can receive workspace
roots that its own filesystem cannot represent. For example, a Windows
drive path from the server cannot be stored as a native absolute path on
a Unix client.

## What changed

Keep `runtimeWorkspaceRoots` as native path strings on the wire for thread
start, resume, and fork. Validate absolute paths on the server and store
the returned roots as `PathUri` values in the TUI. Use the session's roots
for active remote forks, including side chats, and preserve permissions
for those roots in the TUI's permission display.

## Testing

Cover thread startup with workspace and writable roots from another
platform, remote root retention through start, turn, resume, and fork,
and server rejection of relative roots.

GitOrigin-RevId: 1e9e3bff64a6e7ddadb941f16c4952c44724af54
This commit is contained in:
Eric Traut
2026-11-18 22:40:03 +00:00
committed by copyberry
parent 7d458c8fc5
commit b967993f35
41 changed files with 492 additions and 169 deletions
@@ -5231,6 +5231,7 @@ fn thread_lifecycle_responses_default_missing_optional_fields() {
"cwd": cwd,
"approvalPolicy": "on-request",
"approvalsReviewer": "user",
"runtimeWorkspaceRoots": [cwd],
"sandbox": { "type": "workspaceWrite", "writableRoots": [cwd] },
"reasoningEffort": null
});
@@ -5245,6 +5246,7 @@ fn thread_lifecycle_responses_default_missing_optional_fields() {
for encoded in [json!(start), json!(resume), json!(fork)] {
assert_eq!(encoded["thread"]["cwd"], cwd);
assert_eq!(encoded["cwd"], cwd);
assert_eq!(encoded["runtimeWorkspaceRoots"], json!([cwd]));
assert_eq!(encoded["sandbox"]["writableRoots"], json!([cwd]));
}
assert_eq!(start.instruction_sources, Vec::<LegacyAppPathString>::new());
@@ -37,7 +37,6 @@ use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::ThreadGoalStatus as CoreThreadGoalStatus;
use codex_protocol::protocol::TokenUsage as CoreTokenUsage;
use codex_protocol::protocol::TokenUsageInfo as CoreTokenUsageInfo;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::LegacyAppPathString;
use codex_utils_path_uri::PathUri;
use serde::Deserialize;
@@ -85,7 +84,9 @@ pub struct ThreadStartParams {
/// Replace the thread's runtime workspace roots. Paths must be absolute.
#[experimental("thread/start.runtimeWorkspaceRoots")]
#[ts(optional = nullable)]
pub runtime_workspace_roots: Option<Vec<AbsolutePathBuf>>,
#[schemars(with = "Option<Vec<codex_utils_absolute_path::AbsolutePathBuf>>")]
#[ts(as = "Option<Vec<codex_utils_absolute_path::AbsolutePathBuf>>")]
pub runtime_workspace_roots: Option<Vec<LegacyAppPathString>>,
#[experimental(nested)]
#[ts(optional = nullable)]
pub approval_policy: Option<AskForApproval>,
@@ -196,14 +197,16 @@ pub struct ThreadStartResponse {
/// Saved list of disabled plugin IDs. Does not yet filter plugin capabilities.
#[serde(default)]
pub disabled_plugin_ids: Vec<String>,
#[schemars(with = "AbsolutePathBuf")]
#[ts(as = "AbsolutePathBuf")]
#[schemars(with = "codex_utils_absolute_path::AbsolutePathBuf")]
#[ts(as = "codex_utils_absolute_path::AbsolutePathBuf")]
pub cwd: LegacyAppPathString,
/// Thread-scoped runtime workspace roots used to materialize
/// `:workspace_roots`.
#[experimental("thread/start.runtimeWorkspaceRoots")]
#[serde(default)]
pub runtime_workspace_roots: Vec<AbsolutePathBuf>,
#[schemars(with = "Vec<codex_utils_absolute_path::AbsolutePathBuf>")]
#[ts(as = "Vec<codex_utils_absolute_path::AbsolutePathBuf>")]
pub runtime_workspace_roots: Vec<LegacyAppPathString>,
/// Environment-native paths to instruction source files currently loaded for this thread.
#[serde(default)]
pub instruction_sources: Vec<LegacyAppPathString>,
@@ -316,8 +319,8 @@ pub struct ThreadSettings {
/// Saved list of disabled plugin IDs. Does not yet filter plugin capabilities.
#[serde(default)]
pub disabled_plugin_ids: Vec<String>,
#[schemars(with = "AbsolutePathBuf")]
#[ts(as = "AbsolutePathBuf")]
#[schemars(with = "codex_utils_absolute_path::AbsolutePathBuf")]
#[ts(as = "codex_utils_absolute_path::AbsolutePathBuf")]
pub cwd: LegacyAppPathString,
/// Environments configured for future turns, in priority order, primary first.
/// `null` means the server does not expose the selection; [] means none are selected.
@@ -409,7 +412,9 @@ pub struct ThreadResumeParams {
/// Replace the thread's runtime workspace roots. Paths must be absolute.
#[experimental("thread/resume.runtimeWorkspaceRoots")]
#[ts(optional = nullable)]
pub runtime_workspace_roots: Option<Vec<AbsolutePathBuf>>,
#[schemars(with = "Option<Vec<codex_utils_absolute_path::AbsolutePathBuf>>")]
#[ts(as = "Option<Vec<codex_utils_absolute_path::AbsolutePathBuf>>")]
pub runtime_workspace_roots: Option<Vec<LegacyAppPathString>>,
#[experimental(nested)]
#[ts(optional = nullable)]
pub approval_policy: Option<AskForApproval>,
@@ -459,14 +464,16 @@ pub struct ThreadResumeResponse {
/// Saved list of disabled plugin IDs. Does not yet filter plugin capabilities.
#[serde(default)]
pub disabled_plugin_ids: Vec<String>,
#[schemars(with = "AbsolutePathBuf")]
#[ts(as = "AbsolutePathBuf")]
#[schemars(with = "codex_utils_absolute_path::AbsolutePathBuf")]
#[ts(as = "codex_utils_absolute_path::AbsolutePathBuf")]
pub cwd: LegacyAppPathString,
/// Thread-scoped runtime workspace roots used to materialize
/// `:workspace_roots`.
#[experimental("thread/resume.runtimeWorkspaceRoots")]
#[serde(default)]
pub runtime_workspace_roots: Vec<AbsolutePathBuf>,
#[schemars(with = "Vec<codex_utils_absolute_path::AbsolutePathBuf>")]
#[ts(as = "Vec<codex_utils_absolute_path::AbsolutePathBuf>")]
pub runtime_workspace_roots: Vec<LegacyAppPathString>,
/// Environment-native paths to instruction source files currently loaded for this thread.
#[serde(default)]
pub instruction_sources: Vec<LegacyAppPathString>,
@@ -620,7 +627,9 @@ pub struct ThreadForkParams {
/// Replace the thread's runtime workspace roots. Paths must be absolute.
#[experimental("thread/fork.runtimeWorkspaceRoots")]
#[ts(optional = nullable)]
pub runtime_workspace_roots: Option<Vec<AbsolutePathBuf>>,
#[schemars(with = "Option<Vec<codex_utils_absolute_path::AbsolutePathBuf>>")]
#[ts(as = "Option<Vec<codex_utils_absolute_path::AbsolutePathBuf>>")]
pub runtime_workspace_roots: Option<Vec<LegacyAppPathString>>,
#[experimental(nested)]
#[ts(optional = nullable)]
pub approval_policy: Option<AskForApproval>,
@@ -678,14 +687,16 @@ pub struct ThreadForkResponse {
/// Saved list of disabled plugin IDs. Does not yet filter plugin capabilities.
#[serde(default)]
pub disabled_plugin_ids: Vec<String>,
#[schemars(with = "AbsolutePathBuf")]
#[ts(as = "AbsolutePathBuf")]
#[schemars(with = "codex_utils_absolute_path::AbsolutePathBuf")]
#[ts(as = "codex_utils_absolute_path::AbsolutePathBuf")]
pub cwd: LegacyAppPathString,
/// Thread-scoped runtime workspace roots used to materialize
/// `:workspace_roots`.
#[experimental("thread/fork.runtimeWorkspaceRoots")]
#[serde(default)]
pub runtime_workspace_roots: Vec<AbsolutePathBuf>,
#[schemars(with = "Vec<codex_utils_absolute_path::AbsolutePathBuf>")]
#[ts(as = "Vec<codex_utils_absolute_path::AbsolutePathBuf>")]
pub runtime_workspace_roots: Vec<LegacyAppPathString>,
/// Environment-native paths to instruction source files currently loaded for this thread.
#[serde(default)]
pub instruction_sources: Vec<LegacyAppPathString>,
@@ -1292,7 +1292,9 @@ pub(super) async fn handle_pending_thread_resume_request(
model_provider: model_provider_id,
service_tier,
cwd,
runtime_workspace_roots: workspace_roots,
runtime_workspace_roots: codex_utils_path_uri::LegacyAppPathString::from_abs_paths(
&workspace_roots,
),
instruction_sources,
approval_policy: approval_policy.into(),
approvals_reviewer: approvals_reviewer.into(),
@@ -61,6 +61,7 @@ use codex_thread_store::PersistContext;
use codex_thread_store::StoredThreadSearchResult;
use codex_thread_store::ThreadSearchObserver;
use codex_thread_store::ThreadSearchSourceKind;
use codex_utils_path_uri::LegacyAppPathString;
use std::ops::ControlFlow;
use tokio::sync::mpsc;
@@ -164,11 +165,30 @@ struct ThreadRevertRuntimeSnapshot {
client_mcp_extensions: ClientMcpExtensions,
}
fn native_runtime_workspace_roots(
roots: Vec<LegacyAppPathString>,
) -> Result<Vec<AbsolutePathBuf>, JSONRPCErrorError> {
let roots = roots
.into_iter()
.map(|root| {
if !root.as_path().is_absolute() {
return Err(invalid_request(format!(
"invalid runtimeWorkspaceRoots: path is not absolute: {}",
root.as_str(),
)));
}
AbsolutePathBuf::try_from(root)
.map_err(|err| invalid_request(format!("invalid runtimeWorkspaceRoots: {err}")))
})
.collect::<Result<_, _>>()?;
Ok(resolve_runtime_workspace_roots(roots))
}
fn collect_resume_override_mismatches(
request: &ThreadResumeParams,
config_snapshot: &ThreadConfigSnapshot,
selected_service_tier: Option<&str>,
) -> Vec<String> {
) -> Result<Vec<String>, JSONRPCErrorError> {
let mut mismatch_details = Vec::new();
if let Some(requested_model) = request.model.as_deref()
@@ -206,7 +226,8 @@ fn collect_resume_override_mismatches(
}
}
if let Some(requested_runtime_workspace_roots) = request.runtime_workspace_roots.as_ref() {
let requested_runtime_workspace_roots = requested_runtime_workspace_roots.to_vec();
let requested_runtime_workspace_roots =
native_runtime_workspace_roots(requested_runtime_workspace_roots.to_vec())?;
if requested_runtime_workspace_roots != config_snapshot.workspace_roots {
mismatch_details.push(format!(
"runtime_workspace_roots requested={requested_runtime_workspace_roots:?} active={:?}",
@@ -279,7 +300,7 @@ fn collect_resume_override_mismatches(
"developerInstructions override was provided and ignored while running".to_string(),
);
}
mismatch_details
Ok(mismatch_details)
}
fn merge_persisted_resume_metadata(
@@ -1359,7 +1380,9 @@ impl ThreadRequestProcessor {
return Err(invalid_request(format!("project not found: {project_id}")));
}
}
let runtime_workspace_roots = runtime_workspace_roots.map(resolve_runtime_workspace_roots);
let runtime_workspace_roots = runtime_workspace_roots
.map(native_runtime_workspace_roots)
.transpose()?;
let environment_requests =
resolve_turn_environment_requests(self.thread_manager.as_ref(), environments)?;
let mut typesafe_overrides = self.build_thread_config_overrides(
@@ -1790,7 +1813,9 @@ impl ThreadRequestProcessor {
model_provider: config_snapshot.model_provider_id,
service_tier: config_snapshot.service_tier,
cwd,
runtime_workspace_roots: config_snapshot.workspace_roots,
runtime_workspace_roots: LegacyAppPathString::from_abs_paths(
&config_snapshot.workspace_roots,
),
instruction_sources,
approval_policy: config_snapshot.approval_policy.into(),
approvals_reviewer: config_snapshot.approvals_reviewer.into(),
@@ -4307,8 +4332,9 @@ impl ThreadRequestProcessor {
let history_cwd = history_settings
.map(|settings| settings.cwd.to_path_buf())
.or_else(|| thread_history.session_cwd());
let mut runtime_workspace_roots =
runtime_workspace_roots.map(resolve_runtime_workspace_roots);
let mut runtime_workspace_roots = runtime_workspace_roots
.map(native_runtime_workspace_roots)
.transpose()?;
if runtime_workspace_roots.is_none() {
// A retained owned snapshot is authoritative. Only use startup metadata when
// no such snapshot exists; missing roots do not resurrect an older selection.
@@ -4694,7 +4720,9 @@ impl ThreadRequestProcessor {
model_provider: session_configured.model_provider_id,
service_tier: session_configured.service_tier,
cwd: thread_cwd_for_api(&session_configured.cwd)?,
runtime_workspace_roots: config_snapshot.workspace_roots,
runtime_workspace_roots: LegacyAppPathString::from_abs_paths(
&config_snapshot.workspace_roots,
),
instruction_sources,
approval_policy: session_configured.approval_policy.into(),
approvals_reviewer: session_configured.approvals_reviewer.into(),
@@ -4877,7 +4905,7 @@ impl ThreadRequestProcessor {
params,
&config_snapshot,
selected_service_tier.as_deref(),
);
)?;
if !mismatch_details.is_empty() {
let has_subscribers = !self
.thread_state_manager
@@ -5692,7 +5720,9 @@ impl ThreadRequestProcessor {
} else {
Some(cli_overrides)
};
let runtime_workspace_roots = runtime_workspace_roots.map(resolve_runtime_workspace_roots);
let runtime_workspace_roots = runtime_workspace_roots
.map(native_runtime_workspace_roots)
.transpose()?;
let mut typesafe_overrides = self.build_thread_config_overrides(
model,
model_provider,
@@ -6081,7 +6111,9 @@ impl ThreadRequestProcessor {
model_provider: session_configured.model_provider_id,
service_tier: config_snapshot.service_tier.clone(),
cwd: thread_cwd_for_api(&session_configured.cwd)?,
runtime_workspace_roots: config_snapshot.workspace_roots,
runtime_workspace_roots: LegacyAppPathString::from_abs_paths(
&config_snapshot.workspace_roots,
),
instruction_sources,
approval_policy: session_configured.approval_policy.into(),
approvals_reviewer: session_configured.approvals_reviewer.into(),
@@ -22,6 +22,25 @@ fn thread_cwd_rejects_invalid_utf8() {
);
}
#[test]
fn runtime_workspace_roots_reject_home_relative_paths() {
use codex_utils_absolute_path::AbsolutePathBufGuard;
use codex_utils_path_uri::LegacyAppPathString;
let home = std::env::current_dir().expect("current directory");
let result = AbsolutePathBufGuard::with_home_directory(&home, || {
super::native_runtime_workspace_roots(vec![LegacyAppPathString::from_string("~/extra")])
});
assert_eq!(
result.expect_err("runtime workspace root must be absolute"),
JSONRPCErrorError {
code: crate::error_code::INVALID_REQUEST_ERROR_CODE,
message: "invalid runtimeWorkspaceRoots: path is not absolute: ~/extra".into(),
data: None,
}
);
}
#[test]
fn storage_failure_classification_does_not_change_mutation_error_policy() {
for error in [
@@ -791,7 +810,8 @@ mod thread_processor_behavior_tests {
&request,
&config_snapshot,
/* selected_service_tier */ Some("flex"),
),
)
.unwrap(),
vec!["service_tier requested=Some(\"priority\") active=Some(\"flex\")".to_string()]
);
}
@@ -36,6 +36,7 @@ use codex_app_server_protocol::UserInput as V2UserInput;
use codex_config::types::AuthCredentialsStoreMode;
use codex_features::Feature;
use codex_utils_absolute_path::test_support::PathExt;
use codex_utils_path_uri::LegacyAppPathString;
use core_test_support::responses;
use core_test_support::skip_if_no_network;
use pretty_assertions::assert_eq;
@@ -604,7 +605,10 @@ async fn thread_compact_start_triggers_compaction_and_returns_empty_response() -
} = timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_id)).await??;
assert_eq!(
(cwd.as_path(), runtime_workspace_roots),
(updated_cwd.path(), updated_roots)
(
updated_cwd.path(),
LegacyAppPathString::from_abs_paths(&updated_roots)
)
);
Ok(())
@@ -1,3 +1,4 @@
use codex_utils_path_uri::LegacyAppPathString;
use std::path::Path;
use std::time::Duration;
@@ -73,7 +74,7 @@ async fn thread_start_reports_selected_environment_metadata() -> Result<()> {
(
// TODO(anp): Return the selected environment's native cwd from thread/start.
host_cwd,
selected_workspace_roots,
LegacyAppPathString::from_abs_paths(&selected_workspace_roots),
// TODO(anp): Report the implicit built-in permission profile instead of None.
None,
)
@@ -110,13 +110,8 @@ async fn thread_environments_follow_the_loaded_thread_selection() -> Result<()>
timeout(DEFAULT_READ_TIMEOUT, second.read_response(request)).await??;
let expected = Some(vec![ThreadEnvironment {
environment_id: second.auto_env_params()?.environment_id,
cwd: resumed.cwd.clone(),
runtime_workspace_roots: resumed
.runtime_workspace_roots
.iter()
.cloned()
.map(Into::into)
.collect(),
cwd: resumed.cwd,
runtime_workspace_roots: resumed.runtime_workspace_roots,
}]);
assert_eq!(resumed.thread.environments, expected);
assert_read_and_list_environments(&mut second, &thread_id, &expected).await?;
@@ -784,7 +784,7 @@ async fn thread_resume_restores_startup_and_updated_runtime_workspace_roots() ->
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.4".to_string()),
cwd: Some(initial_cwd.to_string_lossy().into_owned()),
runtime_workspace_roots: Some(initial_roots.clone()),
runtime_workspace_roots: Some(LegacyAppPathString::from_abs_paths(&initial_roots)),
environments: Some(explicit_environments.clone()),
..Default::default()
})
@@ -828,7 +828,7 @@ async fn thread_resume_restores_startup_and_updated_runtime_workspace_roots() ->
runtime_workspace_roots,
..
} = timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_id)).await??;
assert_eq!(runtime_workspace_roots, vec![explicit_cwd.clone()]);
assert_eq!(runtime_workspace_roots, vec![explicit_cwd.clone().into()]);
// A cwd-only update must retain the fallback's additional folder, not the live roots.
mcp.clear_message_buffer();
@@ -901,7 +901,10 @@ async fn thread_resume_restores_startup_and_updated_runtime_workspace_roots() ->
} = timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_id)).await??;
assert_eq!(
(cwd, runtime_workspace_roots),
(initial_cwd.clone().into(), expected_roots)
(
initial_cwd.clone().into(),
LegacyAppPathString::from_abs_paths(&expected_roots)
)
);
Ok(())
@@ -1003,7 +1006,9 @@ sandbox = "unelevated"
.send_thread_resume_request(ThreadResumeParams {
thread_id: thread_id.clone(),
cwd: cwd_override.map(|cwd| cwd.to_string_lossy().into_owned()),
runtime_workspace_roots: roots_override,
runtime_workspace_roots: roots_override
.as_deref()
.map(LegacyAppPathString::from_abs_paths),
service_tier: (index == 2).then_some(Some("priority".to_string())),
personality: (index == 2).then_some(Personality::None),
config: (index == 1).then(|| {
@@ -1019,7 +1024,10 @@ sandbox = "unelevated"
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_id)).await??;
assert_eq!(
(resumed.cwd, resumed.runtime_workspace_roots),
(expected_cwd.clone().into(), expected_roots.clone())
(
expected_cwd.clone().into(),
LegacyAppPathString::from_abs_paths(&expected_roots)
)
);
if index < 3 {
mcp.start_turn_and_wait_for_completion(TurnStartParams {
@@ -1236,7 +1244,11 @@ async fn cold_resume_workspace_roots_validate_foreign_startup_paths() -> Result<
} = timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_id)).await??;
assert_eq!(
(thread.id, cwd, runtime_workspace_roots),
(thread_id, local_cwd.clone().into(), expected_roots)
(
thread_id,
local_cwd.clone().into(),
LegacyAppPathString::from_abs_paths(&expected_roots)
)
);
} else {
let error = timeout(
@@ -1983,7 +1995,7 @@ async fn cold_resume_reresolves_persisted_active_permission_profile() -> Result<
);
assert_eq!(
runtime_workspace_roots,
vec![previous_workspace_root.path().abs()]
vec![previous_workspace_root.path().abs().into()]
);
}
Ok(())
@@ -45,6 +45,7 @@ use codex_protocol::protocol::MultiAgentVersion;
use codex_rollout::RolloutItem;
use codex_rollout::read_session_meta_line;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::LegacyAppPathString;
use core_test_support::load_default_config_for_test;
use core_test_support::responses;
use pretty_assertions::assert_eq;
@@ -384,7 +385,10 @@ async fn thread_revert_preserves_fork_cutoff_after_cold_resume() -> Result<()> {
.await?;
assert_eq!(
(cwd.as_path(), runtime_workspace_roots),
(saved_cwd.as_path(), saved_roots.clone())
(
saved_cwd.as_path(),
LegacyAppPathString::from_abs_paths(&saved_roots)
)
);
mcp.start_turn_and_wait_for_completion(TurnStartParams {
thread_id: child.id.clone(),
@@ -559,10 +559,26 @@ async fn thread_start_accepts_absolute_runtime_workspace_roots() -> Result<()> {
.build_initialized()
.await?;
let invalid_id = mcp
.send_thread_start_request(ThreadStartParams {
runtime_workspace_roots: Some(vec![
codex_utils_path_uri::LegacyAppPathString::from_string("relative"),
]),
..Default::default()
})
.await?;
let invalid = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(invalid_id)),
)
.await??;
assert_eq!(invalid.error.code, INVALID_REQUEST_ERROR_CODE);
assert!(invalid.error.message.contains("runtimeWorkspaceRoots"));
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
cwd: Some(cwd.to_string_lossy().to_string()),
runtime_workspace_roots: Some(vec![extra_root.abs()]),
runtime_workspace_roots: Some(vec![extra_root.abs().into()]),
sandbox: Some(SandboxMode::WorkspaceWrite),
..Default::default()
})
@@ -576,7 +592,7 @@ async fn thread_start_accepts_absolute_runtime_workspace_roots() -> Result<()> {
} = timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(req_id)).await??;
assert_eq!(response_cwd, cwd.abs().into());
assert_eq!(runtime_workspace_roots, vec![extra_root.abs()]);
assert_eq!(runtime_workspace_roots, vec![extra_root.abs().into()]);
#[cfg(windows)]
let _ = sandbox;
#[cfg(not(windows))]
@@ -596,7 +612,7 @@ async fn thread_start_accepts_absolute_runtime_workspace_roots() -> Result<()> {
environment.runtime_workspace_roots = Some(vec![environment_root.abs().into()]);
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
runtime_workspace_roots: Some(vec![extra_root.abs()]),
runtime_workspace_roots: Some(vec![extra_root.abs().into()]),
environments: Some(vec![environment]),
sandbox: Some(SandboxMode::WorkspaceWrite),
..Default::default()
@@ -607,7 +623,7 @@ async fn thread_start_accepts_absolute_runtime_workspace_roots() -> Result<()> {
sandbox,
..
} = timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(req_id)).await??;
assert_eq!(runtime_workspace_roots, vec![environment_root.abs()]);
assert_eq!(runtime_workspace_roots, vec![environment_root.abs().into()]);
#[cfg(windows)]
let _ = sandbox;
#[cfg(not(windows))]
@@ -656,7 +672,7 @@ async fn thread_start_excludes_profile_workspace_roots_from_runtime_workspace_ro
assert_eq!(
runtime_workspace_roots,
vec![cwd.path().to_path_buf().abs()]
vec![cwd.path().to_path_buf().abs().into()]
);
Ok(())
+11 -4
View File
@@ -1156,7 +1156,11 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
first_turn_cwd = None;
resumed_workspace_roots = Some(permissions.workspace_roots);
if !overrides.additional_writable_roots.is_empty() {
let mut roots = response.runtime_workspace_roots;
let mut roots = response
.runtime_workspace_roots
.into_iter()
.map(AbsolutePathBuf::try_from)
.collect::<Result<Vec<_>, _>>()?;
roots.extend(overrides.additional_writable_roots.into_iter().map(|path| {
AbsolutePathBuf::resolve_path_against_base(path, config.cwd.as_path())
}));
@@ -1221,7 +1225,9 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
model: config.model.clone(),
model_provider: Some(config.model_provider_id.clone()),
cwd: Some(config.cwd.to_string_lossy().to_string()),
runtime_workspace_roots: Some(config.workspace_roots.clone()),
runtime_workspace_roots: Some(LegacyAppPathString::from_abs_paths(
&config.workspace_roots,
)),
approval_policy: Some(config.permissions.approval_policy.value().into()),
approvals_reviewer: resume_approvals_reviewer_override,
sandbox: sandbox.flatten(),
@@ -1641,7 +1647,7 @@ fn thread_start_params_from_config(
ThreadStartParams {
model: config.model.clone(),
model_provider: Some(config.model_provider_id.clone()),
runtime_workspace_roots: Some(config.workspace_roots.clone()),
runtime_workspace_roots: Some(LegacyAppPathString::from_abs_paths(&config.workspace_roots)),
approval_policy: Some(config.permissions.approval_policy.value().into()),
approvals_reviewer: Some(config.approvals_reviewer.into()),
sandbox: sandbox.flatten(),
@@ -1698,7 +1704,8 @@ fn thread_resume_params_from_config(
.and_then(|settings| settings.get("writable_roots"))
.is_some()
{
runtime_workspace_roots = Some(config.workspace_roots.clone());
runtime_workspace_roots =
Some(LegacyAppPathString::from_abs_paths(&config.workspace_roots));
}
}
ThreadResumeParams {
+1 -5
View File
@@ -777,11 +777,6 @@ impl App {
.await;
let mut fork_config = self.config.clone();
fork_config.daybreak_enabled = self.chat_widget.daybreak_enabled;
if app_server.uses_remote_workspace() {
fork_config.workspace_roots.clone_from(
&self.chat_widget.config_ref().workspace_roots,
);
}
fork_config.model_provider_id.clone_from(&self.chat_widget.config_ref().model_provider_id);
fork_config.model = Some(self.chat_widget.current_model().to_string());
fork_config.model_reasoning_effort =
@@ -790,6 +785,7 @@ impl App {
match app_server.fork_thread_at(
&self.local_settings,
fork_config,
app_server.uses_remote_workspace().then(|| self.chat_widget.session_workspace_roots()),
thread_id,
/*last_turn_id*/ None,
/*before_turn_id*/ None,
+4 -2
View File
@@ -169,8 +169,10 @@ impl App {
return;
};
params.cwd = Some(cwd);
params.runtime_workspace_roots =
Some(config.permissions.user_visible_workspace_roots().to_vec());
params.runtime_workspace_roots = app_server
.thread_params_mode()
.local_workspace_roots(config.permissions.user_visible_workspace_roots())
.map(<[_]>::to_vec);
params.approval_policy = Some(config.permissions.approval_policy.value().into());
params.sandbox_policy = sandbox_policy;
params.permissions = permissions;
+1
View File
@@ -202,6 +202,7 @@ impl App {
.fork_thread_at(
&self.local_settings,
retry_config,
Some(self.chat_widget.session_workspace_roots()),
thread_id,
/*last_turn_id*/ None,
/*before_turn_id*/ Some(turn_id),
+1
View File
@@ -60,6 +60,7 @@ pub(super) async fn continue_with_rewrite(
.fork_thread_at(
&app.local_settings,
config.clone(),
Some(app.chat_widget.session_workspace_roots()),
thread_id,
/*last_turn_id*/ None,
/*before_turn_id*/ Some(turn_id.clone()),
+1
View File
@@ -847,6 +847,7 @@ impl App {
let fork = app_server.sidebar_fork(
self.local_settings.clone(),
self.side_fork_config(),
Some(self.chat_widget.session_workspace_roots().to_vec()),
parent_thread_id,
self.selected_server_profile(parent_thread_id),
if workspace && app_server.can_list_saved_side_chats(parent_thread_id) {
+8 -5
View File
@@ -3361,6 +3361,7 @@ async fn reopen_saved_side_chat(during: DuringOpen) -> Result<()> {
.fork_side_thread(
&app.local_settings,
config.clone(),
/*workspace_roots*/ None,
parent,
/*selected_profile*/ None,
SideChatStorage::Attached,
@@ -3372,6 +3373,7 @@ async fn reopen_saved_side_chat(during: DuringOpen) -> Result<()> {
.sidebar_fork(
app.local_settings.clone(),
config.clone(),
/*workspace_roots*/ None,
parent,
/*profile*/ None,
SideChatStorage::Attached,
@@ -3382,6 +3384,7 @@ async fn reopen_saved_side_chat(during: DuringOpen) -> Result<()> {
.fork_side_thread(
&app.local_settings,
config.clone(),
/*workspace_roots*/ None,
parent,
/*selected_profile*/ None,
SideChatStorage::Attached,
@@ -7586,7 +7589,7 @@ async fn inactive_thread_started_notification_initializes_replay_session() -> Re
windows_sandbox_host: WindowsSandboxHost::Local,
approval_policy: AskForApproval::OnRequest,
permission_profile: PermissionProfile::workspace_write(),
runtime_workspace_roots: vec![primary_cwd.clone(), shared_root.clone()],
runtime_workspace_roots: vec![primary_cwd.clone().into(), shared_root.clone().into()],
..test_thread_session(main_thread_id, primary_cwd.to_path_buf())
};
@@ -7671,7 +7674,7 @@ async fn inactive_thread_started_notification_initializes_replay_session() -> Re
assert_eq!(session.cwd.to_path_buf(), test_path_buf("/tmp/agent"));
assert_eq!(
session.runtime_workspace_roots,
vec![test_path_buf("/tmp/agent").abs(), shared_root]
vec![test_path_buf("/tmp/agent").abs().into(), shared_root.into()]
);
assert_eq!(session.rollout_path, Some(rollout_path));
assert_eq!(
@@ -7711,7 +7714,7 @@ async fn inactive_thread_started_notification_preserves_primary_model_when_path_
let primary_session = ThreadSessionState {
approval_policy: AskForApproval::OnRequest,
permission_profile: PermissionProfile::workspace_write(),
runtime_workspace_roots: vec![primary_cwd.clone()],
runtime_workspace_roots: vec![primary_cwd.clone().into()],
..test_thread_session(main_thread_id, primary_cwd.to_path_buf())
};
@@ -7801,7 +7804,7 @@ async fn thread_read_session_state_does_not_reuse_primary_permission_profile() {
let primary_session = ThreadSessionState {
approval_policy: AskForApproval::OnRequest,
permission_profile: PermissionProfile::workspace_write(),
runtime_workspace_roots: vec![primary_cwd.clone()],
runtime_workspace_roots: vec![primary_cwd.clone().into()],
..test_thread_session(main_thread_id, primary_cwd.to_path_buf())
};
@@ -7857,7 +7860,7 @@ async fn thread_read_session_state_does_not_reuse_primary_permission_profile() {
assert_eq!(session.cwd.to_path_buf(), test_path_buf("/tmp/read"));
assert_eq!(
session.runtime_workspace_roots,
vec![test_path_buf("/tmp/read").abs()]
vec![test_path_buf("/tmp/read").abs().into()]
);
let expected_permission_profile = app
.chat_widget
@@ -80,7 +80,13 @@ async fn check_fork_dispatch(mode: ThreadParamsMode) -> Result<()> {
)
.await?;
let expected_roots = vec![remote_cwd, server_root];
assert_eq!(started.session.runtime_workspace_roots, expected_roots);
assert_eq!(
started.session.runtime_workspace_roots,
expected_roots
.iter()
.map(codex_utils_path_uri::PathUri::from_abs_path)
.collect::<Vec<_>>()
);
app.enqueue_primary_thread_session(started.session, started.turns)
.await?;
app.thread_event_listener_tasks
@@ -420,6 +420,7 @@ async fn custom_permission_selection_scenario() -> Result<()> {
server.fork_side_thread(
&app.local_settings,
app.config.clone(),
/*workspace_roots*/ None,
thread_id,
app.agents_overview
.requested_permission_profiles
@@ -2259,6 +2259,7 @@ async fn delete_current_thread_navigates_only_after_success() -> Result<()> {
.fork_side_thread(
&app.local_settings,
side_config.clone(),
/*workspace_roots*/ None,
thread_id,
/*selected_profile*/ None,
crate::app_server_session::SideChatStorage::Temporary,
@@ -2277,6 +2278,7 @@ async fn delete_current_thread_navigates_only_after_success() -> Result<()> {
.fork_side_thread(
&app.local_settings,
side_config,
/*workspace_roots*/ None,
thread_id,
/*selected_profile*/ None,
crate::app_server_session::SideChatStorage::Temporary,
@@ -2788,6 +2790,7 @@ async fn archive_current_thread_returns_to_agents() -> Result<()> {
.fork_side_thread(
&app.local_settings,
side_config,
/*workspace_roots*/ None,
thread_id,
/*selected_profile*/ None,
crate::app_server_session::SideChatStorage::Temporary,
@@ -4738,6 +4741,7 @@ async fn paginated_workflows_never_request_full_thread_history() -> Result<()> {
Box::pin(app_server.fork_side_thread(
&crate::local_settings::LocalSettings::from(&side_config),
side_config,
/*workspace_roots*/ None,
paginated_thread_id,
/*selected_profile*/ None,
crate::app_server_session::SideChatStorage::Temporary,
@@ -5723,19 +5727,26 @@ terminal_visualization_instructions = true
#[test]
fn changing_directory_preserves_project_trust_permissions_history_and_hooks() -> Result<()> {
run_embedded_tui_scenario("tui-change-directory", change_directory_scenario)
}
fn run_embedded_tui_scenario(
name: &str,
scenario: impl AsyncFnOnce() -> Result<()> + Send + 'static,
) -> Result<()> {
// The TUI and embedded app-server load full configurations on the same test thread.
const TEST_STACK_SIZE_BYTES: usize = 16 * 1024 * 1024;
std::thread::Builder::new()
.name("tui-change-directory".into())
.name(name.to_owned())
.stack_size(TEST_STACK_SIZE_BYTES)
.spawn(|| {
.spawn(move || {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?
.block_on(boxed_future!(change_directory_scenario()))
.block_on(boxed_future!(scenario()))
})?
.join()
.expect("directory change test thread panicked")
.expect("embedded TUI test thread panicked")
}
async fn change_directory_scenario() -> Result<()> {
@@ -77,6 +77,7 @@ async fn temporary_side_chat_sends_policy_on_its_first_request() -> Result<()> {
.sidebar_fork(
app.local_settings.clone(),
app.side_fork_config(),
/*workspace_roots*/ None,
parent,
/*profile*/ None,
crate::app_server_session::SideChatStorage::Temporary,
@@ -757,8 +757,12 @@ async fn fresh_startup_reads_destination_and_cleared_model_uses_catalog() -> Res
Ok(())
}
#[tokio::test]
async fn fresh_startup_observes_config_edits_after_directory_trust() -> Result<()> {
#[test]
fn fresh_startup_observes_config_edits_after_directory_trust() -> Result<()> {
run_embedded_tui_scenario("tui-startup-after-trust", startup_after_directory_trust)
}
async fn startup_after_directory_trust() -> Result<()> {
let home = tempdir()?;
let destination = tempdir()?;
std::fs::create_dir(destination.path().join(".git"))?;
@@ -817,8 +821,12 @@ async fn fresh_startup_observes_config_edits_after_directory_trust() -> Result<(
Ok(())
}
#[tokio::test]
async fn startup_reads_server_defaults_before_starting_thread() -> Result<()> {
#[test]
fn startup_reads_server_defaults_before_starting_thread() -> Result<()> {
run_embedded_tui_scenario("tui-startup-defaults", startup_with_server_defaults)
}
async fn startup_with_server_defaults() -> Result<()> {
let client_home = tempdir()?;
let server_home = tempdir()?;
let projectless_cwd = tempdir()?;
+8 -7
View File
@@ -1599,7 +1599,10 @@ impl App {
.permissions
.set_permission_profile_from_session_snapshot(
PermissionProfileSnapshot::from_session_snapshot(
session.permission_profile.clone(),
crate::session_state::display_profile_for_roots(
session.permission_profile.clone(),
&session.runtime_workspace_roots,
),
session.active_permission_profile.clone(),
),
)
@@ -1608,12 +1611,10 @@ impl App {
}
self.config.approvals_reviewer = session.approvals_reviewer;
if !self.app_server_target.uses_remote_workspace() {
self.config
.workspace_roots
.clone_from(&session.runtime_workspace_roots);
self.config
.permissions
.set_workspace_roots(session.runtime_workspace_roots.clone());
crate::session_state::sync_local_workspace_roots(
&mut self.config,
&session.runtime_workspace_roots,
);
}
let thread_id = session.thread_id;
+7 -2
View File
@@ -112,7 +112,12 @@ impl App {
cwd: cwd
.clone()
.unwrap_or_else(|| self.config.cwd.clone().into()),
runtime_workspace_roots: self.config.workspace_roots.clone(),
runtime_workspace_roots: self
.config
.workspace_roots
.iter()
.map(codex_utils_path_uri::PathUri::from_abs_path)
.collect(),
instruction_source_paths: Vec::new(),
reasoning_effort: self.chat_widget.current_reasoning_effort(),
collaboration_mode: None,
@@ -206,7 +211,7 @@ mod tests {
permission_profile: PermissionProfile::read_only(),
active_permission_profile: None,
cwd: cwd.abs().into(),
runtime_workspace_roots: vec![cwd.abs()],
runtime_workspace_roots: vec![cwd.abs().into()],
instruction_source_paths: Vec::new(),
reasoning_effort: None,
collaboration_mode: None,
+6 -1
View File
@@ -494,7 +494,12 @@ impl App {
};
if session.thread_id == thread_id
|| crate::session_resume::cwds_differ(&session.cwd.to_path_buf(), cwd.as_path())
|| session.runtime_workspace_roots != config.workspace_roots
|| session.runtime_workspace_roots
!= config
.workspace_roots
.iter()
.map(codex_utils_path_uri::PathUri::from_abs_path)
.collect::<Vec<_>>()
|| !permissions_match
{
if session.thread_id != thread_id {
+75 -25
View File
@@ -242,9 +242,11 @@ impl SideChatStorage {
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ForkConfigSource {
enum ForkConfigSource<'a> {
Local,
Session,
Session {
workspace_roots: Option<&'a [PathUri]>,
},
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -524,11 +526,18 @@ impl ThreadParamsMode {
}
}
fn workspace_roots_from_config(self, config: &Config) -> Option<Vec<AbsolutePathBuf>> {
fn workspace_roots_from_config(self, config: &Config) -> Option<Vec<LegacyAppPathString>> {
self.local_workspace_roots(&config.workspace_roots)
.map(LegacyAppPathString::from_abs_paths)
}
pub(crate) fn local_workspace_roots(
self,
roots: &[AbsolutePathBuf],
) -> Option<&[AbsolutePathBuf]> {
// A remote server owns its workspace roots. A client config can only hold local paths.
match self {
Self::Embedded => Some(config.workspace_roots.clone()),
// Client config paths belong to the client host. Let the server resolve its
// defaults or restore the saved roots, then adopt the roots in its response.
Self::Embedded => Some(roots),
Self::Remote | Self::Cloud => None,
}
}
@@ -1313,6 +1322,7 @@ impl AppServerSession {
&mut self,
local_settings: &LocalSettings,
config: Config,
workspace_roots: Option<&[PathUri]>,
thread_id: ThreadId,
last_turn_id: Option<String>,
before_turn_id: Option<String>,
@@ -1329,7 +1339,7 @@ impl AppServerSession {
ForkPresentation::Regular,
selected_profile,
ForkPermissionMode::InheritSaved,
ForkConfigSource::Session,
ForkConfigSource::Session { workspace_roots },
)
.await
}
@@ -1355,7 +1365,9 @@ impl AppServerSession {
ForkPresentation::Regular,
selected_profile,
permission_mode,
ForkConfigSource::Session,
ForkConfigSource::Session {
workspace_roots: None,
},
)
.await
}
@@ -1366,6 +1378,7 @@ impl AppServerSession {
&self,
settings: LocalSettings,
config: Config,
workspace_roots: Option<Vec<PathUri>>,
parent: ThreadId,
profile: Option<PermissionProfileSelection>,
preferred_storage: SideChatStorage,
@@ -1388,7 +1401,14 @@ impl AppServerSession {
storage = SideChatStorage::Attached;
}
let fork = view
.fork_side_thread(&settings, config.clone(), parent, profile.as_ref(), storage)
.fork_side_thread(
&settings,
config.clone(),
workspace_roots.as_deref(),
parent,
profile.as_ref(),
storage,
)
.await;
let thread = match fork {
Err(err)
@@ -1396,8 +1416,15 @@ impl AppServerSession {
&& side_chat_history::is_attached_thread_store_unsupported(&err) =>
{
storage = SideChatStorage::Temporary;
view.fork_side_thread(&settings, config, parent, profile.as_ref(), storage)
.await?
view.fork_side_thread(
&settings,
config,
workspace_roots.as_deref(),
parent,
profile.as_ref(),
storage,
)
.await?
}
result => result?,
};
@@ -1452,6 +1479,7 @@ impl AppServerSession {
&mut self,
local_settings: &LocalSettings,
mut config: Config,
workspace_roots: Option<&[PathUri]>,
thread_id: ThreadId,
selected_profile: Option<&PermissionProfileSelection>,
storage: SideChatStorage,
@@ -1467,7 +1495,7 @@ impl AppServerSession {
ForkPresentation::SideConversation(storage),
selected_profile,
ForkPermissionMode::InheritSaved,
ForkConfigSource::Session,
ForkConfigSource::Session { workspace_roots },
)
.await
}
@@ -1487,7 +1515,7 @@ impl AppServerSession {
presentation: ForkPresentation,
selected_profile: Option<&PermissionProfileSelection>,
permission_mode: ForkPermissionMode,
config_source: ForkConfigSource,
config_source: ForkConfigSource<'_>,
) -> Result<AppServerStartedThread> {
if self.thread_params_mode == ThreadParamsMode::Cloud {
color_eyre::eyre::bail!("Cloud conversations cannot be forked in the TUI yet.");
@@ -1537,12 +1565,18 @@ impl AppServerSession {
.model_provider_override
.clone()
.or(params.model_provider),
ForkConfigSource::Session => Some(config.model_provider_id.clone()),
ForkConfigSource::Session { .. } => Some(config.model_provider_id.clone()),
};
if config_source == ForkConfigSource::Session {
// Active-session config has already adopted the server's roots. Fork does
// not restore saved roots when omitted, so preserve this explicit selection.
params.runtime_workspace_roots = Some(config.workspace_roots.clone());
if let ForkConfigSource::Session { workspace_roots } = config_source {
// Omitting roots on fork lets the server recompute them from its current defaults.
params.runtime_workspace_roots = Some(match workspace_roots {
Some(roots) => roots
.iter()
.cloned()
.map(LegacyAppPathString::from)
.collect(),
None => LegacyAppPathString::from_abs_paths(&config.workspace_roots),
});
if permission_mode == ForkPermissionMode::InheritSaved && selected_profile.is_none() {
params.approvals_reviewer = None;
if let Some(overrides) = params.config.as_mut() {
@@ -1947,7 +1981,10 @@ impl AppServerSession {
let (sandbox_policy, permissions) =
turn_permissions_overrides(permissions_override, cwd.as_path())?;
params.cwd = Some(cwd);
params.runtime_workspace_roots = Some(workspace_roots.to_vec());
params.runtime_workspace_roots = self
.thread_params_mode
.local_workspace_roots(workspace_roots)
.map(<[_]>::to_vec);
params.approval_policy = approval_policy;
params.approvals_reviewer = approvals_reviewer;
params.sandbox_policy = sandbox_policy;
@@ -3253,7 +3290,7 @@ async fn thread_session_state_from_thread_response(
permission_profile: PermissionProfile,
active_permission_profile: Option<ActivePermissionProfile>,
cwd: PathUri,
runtime_workspace_roots: Vec<AbsolutePathBuf>,
runtime_workspace_roots: Vec<LegacyAppPathString>,
instruction_source_paths: Vec<PathUri>,
reasoning_effort: Option<codex_protocol::openai_models::ReasoningEffort>,
local_settings: &LocalSettings,
@@ -3290,7 +3327,11 @@ async fn thread_session_state_from_thread_response(
permission_profile,
active_permission_profile,
cwd,
runtime_workspace_roots,
runtime_workspace_roots: runtime_workspace_roots
.into_iter()
.map(PathUri::try_from)
.collect::<Result<_, _>>()
.map_err(|err| err.to_string())?,
instruction_source_paths,
reasoning_effort,
collaboration_mode: None,
@@ -4083,7 +4124,7 @@ mod tests {
assert_eq!(params.cwd, Some(config.cwd.to_string_lossy().to_string()));
assert_eq!(
params.runtime_workspace_roots,
Some(config.workspace_roots.clone())
Some(LegacyAppPathString::from_abs_paths(&config.workspace_roots))
);
assert_eq!(params.sandbox, None);
assert_eq!(
@@ -4849,6 +4890,7 @@ mod tests {
.fork_side_thread(
&LocalSettings::from(&ephemeral_config),
ephemeral_config,
/*workspace_roots*/ None,
source_thread_id,
/*selected_profile*/ None,
crate::app_server_session::SideChatStorage::Temporary,
@@ -4977,6 +5019,7 @@ mod tests {
.fork_side_thread(
&LocalSettings::from(&side_config),
side_config,
/*workspace_roots*/ None,
source_thread_id,
/*selected_profile*/ None,
crate::app_server_session::SideChatStorage::Temporary,
@@ -5081,6 +5124,7 @@ mod tests {
.fork_side_thread(
&LocalSettings::from(&config),
config,
/*workspace_roots*/ None,
thread_id,
/*selected_profile*/ None,
crate::app_server_session::SideChatStorage::Temporary,
@@ -5263,8 +5307,8 @@ mod tests {
service_tier: None,
cwd: test_path_buf("/tmp/project").abs().into(),
runtime_workspace_roots: vec![
test_path_buf("/tmp/project").abs(),
test_path_buf("/tmp/project/extra").abs(),
test_path_buf("/tmp/project").abs().into(),
test_path_buf("/tmp/project/extra").abs().into(),
],
instruction_sources: vec![LegacyAppPathString::from_abs_path(
&test_path_buf("/tmp/project/AGENTS.md").abs(),
@@ -5301,7 +5345,13 @@ mod tests {
assert_eq!(started.session.forked_from_id, Some(forked_from_id));
assert_eq!(
started.session.runtime_workspace_roots,
response.runtime_workspace_roots
response
.runtime_workspace_roots
.clone()
.into_iter()
.map(PathUri::try_from)
.collect::<Result<Vec<_>, _>>()
.unwrap()
);
assert_eq!(
started.session.instruction_source_paths,
@@ -97,6 +97,7 @@ async fn starts_and_forks_use_server_provider_unless_explicitly_selected() -> Re
.fork_thread_at(
&local_settings,
server_config,
/*workspace_roots*/ None,
parent,
/*last_turn_id*/ None,
/*before_turn_id*/ None,
@@ -26,6 +26,7 @@ use codex_app_server_protocol::ThreadTurnsListResponse;
use codex_app_server_protocol::TurnItemsView;
use codex_protocol::ThreadId;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::LegacyAppPathString;
use color_eyre::eyre::Result;
// Bound recovery to recent messages when item paging is unavailable.
@@ -93,7 +94,7 @@ impl AppServerSession {
config.permissions.permission_profile().clone(),
config.permissions.active_permission_profile(),
super::decode_thread_cwd(&thread.cwd, self.path_convention())?,
config.workspace_roots.clone(),
LegacyAppPathString::from_abs_paths(&config.workspace_roots),
Vec::new(),
thread.reasoning_effort,
local_settings,
@@ -151,6 +151,7 @@ async fn resume_with_saved_server_profile() -> Result<()> {
.fork_thread_at(
&local_settings,
client_config.clone(),
/*workspace_roots*/ None,
thread_id,
/*last_turn_id*/ None,
/*before_turn_id*/ None,
@@ -178,6 +179,7 @@ async fn resume_with_saved_server_profile() -> Result<()> {
.fork_side_thread(
&local_settings,
client_config,
/*workspace_roots*/ None,
thread_id,
/*selected_profile*/ None,
crate::app_server_session::SideChatStorage::Temporary,
@@ -239,7 +241,11 @@ async fn resume_with_saved_server_profile() -> Result<()> {
.await?;
assert_eq!(
resumed.session.runtime_workspace_roots,
config.workspace_roots
config
.workspace_roots
.iter()
.map(codex_utils_path_uri::PathUri::from_abs_path)
.collect::<Vec<_>>()
);
assert!(
resumed
@@ -8,6 +8,60 @@ use codex_app_server_protocol::ServerNotification;
use core_test_support::responses;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn thread_start_preserves_foreign_workspace_and_writable_roots() -> Result<()> {
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemSandboxEntry;
let temp = tempfile::tempdir()?;
let config = ConfigBuilder::default()
.codex_home(temp.path().to_path_buf())
.build()
.await?;
let (cwd, workspace, writable) = if cfg!(windows) {
("/repo", "/workspaces/shared", "/output")
} else {
(r"D:\repo", r"D:\workspaces\shared", r"E:\output")
};
let id = ThreadId::new();
let response = serde_json::from_value(serde_json::json!({
"thread": {
"id": id, "sessionId": id, "preview": "", "ephemeral": false,
"modelProvider": "openai", "createdAt": 0, "updatedAt": 0,
"status": { "type": "idle" }, "cwd": cwd, "cliVersion": "test",
"source": "cli", "turns": []
},
"cwd": cwd, "model": "model", "modelProvider": "openai",
"approvalPolicy": "on-request", "approvalsReviewer": "user",
"runtimeWorkspaceRoots": [workspace],
"sandbox": { "type": "workspaceWrite", "writableRoots": [writable] }
}))?;
let path_uri = |text: &str| PathUri::try_from(LegacyAppPathString::from_string(text));
let started = started_thread_from_start_response(
response,
&LocalSettings::from(&config),
&config,
ThreadParamsMode::Remote,
path_uri(cwd)?,
)
.await?;
assert_eq!(started.session.cwd, path_uri(cwd)?);
assert_eq!(
started.session.runtime_workspace_roots,
vec![path_uri(workspace)?]
);
let (mut chat, _sender, _events, _commands) =
crate::chatwidget::tests::helpers::make_chatwidget_manual_with_sender().await;
chat.handle_thread_session(started.session);
let policy = chat.config_ref().permissions.file_system_sandbox_policy();
for root in [workspace, writable] {
assert!(policy.entries.contains(&FileSystemSandboxEntry::new(
path_uri(root)?.into(),
FileSystemAccessMode::Write,
)));
}
Ok(())
}
#[test]
fn remote_workspace_roots_survive_start_turn_resume_and_fork() -> Result<()> {
const TEST_STACK_SIZE_BYTES: usize = 16 * 1024 * 1024;
@@ -74,6 +128,8 @@ stream_max_retries = 0
.await?;
let local_settings = LocalSettings::from(&client_config);
let expected_roots = vec![remote_cwd.clone(), extra_root.clone()];
let expected_uris: Vec<PathUri> =
expected_roots.iter().map(PathUri::from_abs_path).collect();
let mut app_server =
crate::start_embedded_app_server_for_picker(&server_config).await?;
// Exercise remote request semantics with a real server and separate client config.
@@ -82,7 +138,7 @@ stream_max_retries = 0
let started = app_server.start_thread(&client_config).await?;
let thread_id = started.session.thread_id;
assert_eq!(started.session.cwd, remote_cwd.clone().into());
assert_eq!(started.session.runtime_workspace_roots, expected_roots);
assert_eq!(started.session.runtime_workspace_roots, expected_uris);
let (mut chat, _sender, _events, _commands) =
crate::chatwidget::tests::helpers::make_chatwidget_manual_with_sender().await;
@@ -102,7 +158,7 @@ stream_max_retries = 0
/*approval_policy*/ None,
/*approvals_reviewer*/ None,
TurnPermissionsOverride::Preserve,
config.permissions.user_visible_workspace_roots(),
/*workspace_roots*/ &[],
"gpt-5.2".to_string(),
/*effort*/ None,
/*summary*/ None,
@@ -138,11 +194,11 @@ stream_max_retries = 0
ResumeModelSettings::RestoreFromThread,
)
.await?;
assert_eq!(resumed.session.runtime_workspace_roots, expected_roots);
assert_eq!(resumed.session.runtime_workspace_roots, expected_uris);
let forked = app_server
.fork_thread(&local_settings, client_config.clone(), thread_id)
.await?;
assert_eq!(forked.session.runtime_workspace_roots, expected_roots);
assert_eq!(forked.session.runtime_workspace_roots, expected_uris);
// Existing tasks may retain roots that are no longer in the server defaults.
let config_path = server_home.path().join("config.toml");
@@ -151,11 +207,14 @@ stream_max_retries = 0
"writable_roots = []",
);
std::fs::write(config_path, updated_config)?;
let session_config = chat.config_ref().clone();
let mut session_config = chat.config_ref().clone();
// A foreign session has no host-local workspace roots.
session_config.workspace_roots.clear();
let forked = app_server
.fork_thread_at(
&local_settings,
session_config.clone(),
Some(chat.session_workspace_roots()),
thread_id,
/*last_turn_id*/ None,
/*before_turn_id*/ None,
@@ -163,23 +222,27 @@ stream_max_retries = 0
/*selected_profile*/ None,
)
.await?;
assert_eq!(forked.session.runtime_workspace_roots, expected_roots);
assert_eq!(forked.session.runtime_workspace_roots, expected_uris);
let side = app_server
.fork_side_thread(
&local_settings,
session_config,
Some(chat.session_workspace_roots()),
thread_id,
/*selected_profile*/ None,
crate::app_server_session::SideChatStorage::Temporary,
)
.await?;
assert_eq!(side.session.runtime_workspace_roots, expected_roots);
assert_eq!(side.session.runtime_workspace_roots, expected_uris);
app_server.remote_cwd_override = None;
let started = app_server.start_thread(&client_config).await?;
let default_cwd = AbsolutePathBuf::current_dir()?;
assert_eq!(started.session.cwd, default_cwd.clone().into());
assert_eq!(started.session.runtime_workspace_roots, vec![default_cwd]);
assert_eq!(
started.session.runtime_workspace_roots,
vec![default_cwd.into()]
);
app_server.shutdown().await?;
Ok(())
})
@@ -199,7 +262,7 @@ async fn embedded_lifecycle_requests_preserve_explicit_workspace_roots() -> Resu
})
.build()
.await?;
let expected = Some(config.workspace_roots.clone());
let expected = Some(LegacyAppPathString::from_abs_paths(&config.workspace_roots));
let thread_id = ThreadId::new();
let start = thread_start_params_from_config(
&config,
+1
View File
@@ -755,6 +755,7 @@ pub(crate) struct ChatWidget {
current_rollout_path: Option<PathBuf>,
// Working directory of the displayed session.
current_cwd: PathUri,
current_workspace_roots: Vec<PathUri>,
primary_environment_cwd: Option<crate::session_state::EnvironmentCwd>,
// App-server-backed command runner for status-line workspace metadata lookups.
workspace_command_runner: Option<WorkspaceCommandRunner>,
@@ -70,6 +70,11 @@ impl ChatWidget {
let active_cell = Some(header);
let current_cwd = PathUri::from_abs_path(&config.cwd);
let current_workspace_roots = config
.workspace_roots
.iter()
.map(PathUri::from_abs_path)
.collect();
let effective_service_tier = crate::service_tier_resolution::effective_service_tier(
&config,
&local_settings.notices,
@@ -283,6 +288,7 @@ impl ChatWidget {
feedback,
current_rollout_path: None,
current_cwd,
current_workspace_roots,
primary_environment_cwd: None,
workspace_command_runner,
instruction_source_paths: Vec::new(),
+10 -6
View File
@@ -158,11 +158,12 @@ impl ChatWidget {
if connector_scope_changed {
self.invalidate_connector_scope();
}
let runtime_workspace_roots = session.runtime_workspace_roots.clone();
self.config.workspace_roots = runtime_workspace_roots.clone();
self.config
.permissions
.set_workspace_roots(runtime_workspace_roots);
self.current_workspace_roots
.clone_from(&session.runtime_workspace_roots);
crate::session_state::sync_local_workspace_roots(
&mut self.config,
&self.current_workspace_roots,
);
self.config.service_tier = session.service_tier.clone();
self.effective_service_tier = session.service_tier.clone();
if let Err(err) = self
@@ -176,7 +177,10 @@ impl ChatWidget {
Constrained::allow_only(session.approval_policy.to_core());
}
let permission_snapshot = PermissionProfileSnapshot::from_session_snapshot(
session.permission_profile.clone(),
crate::session_state::display_profile_for_roots(
session.permission_profile.clone(),
&session.runtime_workspace_roots,
),
session.active_permission_profile.clone(),
);
let permission_sync = self
+18 -24
View File
@@ -554,9 +554,21 @@ impl ChatWidget {
};
let cwd_changed = self.current_cwd != cwd;
self.status_line_project_root_name_cache = None;
if let Ok(local) = cwd.to_abs_path() {
self.apply_thread_settings_cwd(local);
if let Ok(local) = cwd.to_abs_path()
&& local != self.config.cwd
{
self.config.cwd = local;
self.permission_discovery = None;
}
crate::session_state::retarget_workspace_root(
&mut self.current_workspace_roots,
&self.current_cwd,
&cwd,
);
crate::session_state::sync_local_workspace_roots(
&mut self.config,
&self.current_workspace_roots,
);
self.current_cwd = cwd;
self.config.model_provider_id = settings.model_provider.clone();
self.set_daybreak_enabled(self.daybreak_enabled);
@@ -574,7 +586,10 @@ impl ChatWidget {
self.set_approvals_reviewer(settings.approvals_reviewer.to_core());
let permission_snapshot = PermissionProfileSnapshot::from_session_snapshot(
permission_profile,
crate::session_state::display_profile_for_roots(
permission_profile,
&self.current_workspace_roots,
),
settings.active_permission_profile.take().map(Into::into),
);
if let Err(err) = self
@@ -623,27 +638,6 @@ impl ChatWidget {
self.request_redraw();
}
fn apply_thread_settings_cwd(&mut self, cwd: AbsolutePathBuf) {
let previous_cwd = std::mem::replace(&mut self.config.cwd, cwd.clone());
if previous_cwd != cwd {
self.permission_discovery = None;
}
if !self.config.workspace_roots.contains(&previous_cwd) {
return;
}
let previous_roots = std::mem::take(&mut self.config.workspace_roots);
self.config.workspace_roots.push(cwd);
for root in previous_roots {
if root != previous_cwd && !self.config.workspace_roots.contains(&root) {
self.config.workspace_roots.push(root);
}
}
self.config
.permissions
.set_workspace_roots(self.config.workspace_roots.clone());
}
pub(crate) fn set_effective_collaboration_mode(&mut self, mode: CollaborationMode) {
let mode_kind = mode.mode;
let settings = mode.settings;
@@ -492,6 +492,10 @@ impl ChatWidget {
&self.current_cwd
}
pub(crate) fn session_workspace_roots(&self) -> &[PathUri] {
&self.current_workspace_roots
}
pub(super) fn status_line_workspace_cwd(&self) -> PathBuf {
self.primary_environment_cwd
.as_ref()
@@ -66,7 +66,7 @@ pub(super) fn configured_thread_session(
permission_profile: PermissionProfile::read_only(),
active_permission_profile: None,
cwd: test_path_buf("/tmp/thread-settings").abs().into(),
runtime_workspace_roots: vec![test_path_buf("/tmp/thread-settings").abs()],
runtime_workspace_roots: vec![test_path_buf("/tmp/thread-settings").abs().into()],
instruction_source_paths: Vec::new(),
reasoning_effort: None,
collaboration_mode: None,
@@ -764,6 +764,7 @@ async fn thread_settings_updated_updates_visible_state_without_transcript() {
let thread_id = ThreadId::new();
let mut session = configured_thread_session(thread_id);
session.cwd = test_path_buf("/tmp/original-workspace").abs().into();
session.runtime_workspace_roots = vec![session.cwd.clone()];
session.thread_settings_confirmed = false;
chat.handle_thread_session(session);
chat.config.permissions.approval_policy =
@@ -790,6 +791,11 @@ async fn thread_settings_updated_updates_visible_state_without_transcript() {
);
assert_eq!(chat.session_cwd().inferred_native_path_string(), remote_cwd);
assert_eq!(
chat.current_workspace_roots.as_slice(),
std::slice::from_ref(chat.session_cwd())
);
assert!(chat.config_ref().workspace_roots.is_empty());
assert_ne!(chat.connector_scope_generation(), previous_generation);
assert!(chat.connectors_for_mentions().is_none());
assert!(chat.connectors.mention_refresh_in_flight);
@@ -710,7 +710,7 @@ async fn session_configured_syncs_widget_config_permissions_and_cwd() {
permission_profile: expected_permission_profile,
active_permission_profile: None,
cwd: expected_cwd.clone().into(),
runtime_workspace_roots: vec![expected_cwd.clone()],
runtime_workspace_roots: vec![expected_cwd.clone().into()],
instruction_source_paths: Vec::new(),
reasoning_effort: Some(ReasoningEffortConfig::default()),
collaboration_mode: None,
@@ -792,7 +792,10 @@ async fn session_configured_preserves_profile_workspace_roots() {
permission_profile: session_permission_profile.clone(),
active_permission_profile: None,
cwd: session_cwd.clone().into(),
runtime_workspace_roots: session_runtime_workspace_roots.clone(),
runtime_workspace_roots: session_runtime_workspace_roots
.iter()
.map(PathUri::from_abs_path)
.collect(),
instruction_source_paths: Vec::new(),
reasoning_effort: Some(ReasoningEffortConfig::default()),
collaboration_mode: None,
@@ -141,6 +141,7 @@ async fn creation_attaches_to_original_task_and_survives_service_restart_scenari
let saved_side = Box::pin(server.fork_side_thread(
&LocalSettings::from(&config),
config.clone(),
/*workspace_roots*/ None,
started.session.thread_id,
/*selected_profile*/ None,
SideChatStorage::Attached,
+45 -15
View File
@@ -11,7 +11,6 @@ use codex_protocol::ThreadId;
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::models::ActivePermissionProfile;
use codex_protocol::models::PermissionProfile;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::LegacyAppPathString;
use codex_utils_path_uri::PathUri;
@@ -56,7 +55,7 @@ pub(crate) struct ThreadSessionState {
pub(crate) cwd: PathUri,
/// Native cwd of the primary executor, which can differ from the app-server cwd.
pub(crate) primary_environment_cwd: Option<EnvironmentCwd>,
pub(crate) runtime_workspace_roots: Vec<AbsolutePathBuf>,
pub(crate) runtime_workspace_roots: Vec<PathUri>,
pub(crate) instruction_source_paths: Vec<PathUri>,
pub(crate) reasoning_effort: Option<codex_protocol::openai_models::ReasoningEffort>,
pub(crate) collaboration_mode: Option<Box<CollaborationMode>>,
@@ -92,20 +91,51 @@ impl ThreadSessionState {
pub(crate) fn set_cwd_retargeting_implicit_runtime_workspace_root(&mut self, cwd: PathUri) {
let previous_cwd = std::mem::replace(&mut self.cwd, cwd);
let (Ok(previous_cwd), Ok(cwd)) = (previous_cwd.to_abs_path(), self.cwd.to_abs_path())
else {
return;
};
if !self.runtime_workspace_roots.contains(&previous_cwd) {
return;
}
retarget_workspace_root(&mut self.runtime_workspace_roots, &previous_cwd, &self.cwd);
}
}
let previous_roots = std::mem::take(&mut self.runtime_workspace_roots);
self.runtime_workspace_roots.push(cwd);
for root in previous_roots {
if root != previous_cwd && !self.runtime_workspace_roots.contains(&root) {
self.runtime_workspace_roots.push(root);
}
/// Sync the native portion of the server's root list into both host-local config views.
pub(crate) fn sync_local_workspace_roots(
config: &mut crate::legacy_core::config::Config,
roots: &[PathUri],
) {
config.workspace_roots = roots
.iter()
.filter_map(|root| root.to_abs_path().ok())
.collect();
config
.permissions
.set_workspace_roots(config.workspace_roots.clone());
}
/// Retarget an implicit cwd root while preserving other roots and their order.
pub(crate) fn retarget_workspace_root(
roots: &mut Vec<PathUri>,
previous_cwd: &PathUri,
cwd: &PathUri,
) {
if !roots.contains(previous_cwd) {
return;
}
let previous_roots = std::mem::take(roots);
roots.push(cwd.clone());
for root in previous_roots {
if &root != previous_cwd && !roots.contains(&root) {
roots.push(root);
}
}
}
/// Local config materializes native workspace roots itself. Resolve foreign roots before storing
/// the display profile so permissions for those workspaces survive that host-local step.
pub(crate) fn display_profile_for_roots(
profile: PermissionProfile,
roots: &[PathUri],
) -> PermissionProfile {
if roots.iter().any(|root| root.to_abs_path().is_err()) {
profile.materialize_project_roots_with_path_uris(roots)
} else {
profile
}
}
@@ -60,6 +60,11 @@ impl LegacyAppPathString {
Self::from_path(path.as_path())
}
/// Renders host-native absolute paths for a legacy API path list.
pub fn from_abs_paths(paths: &[AbsolutePathBuf]) -> Vec<Self> {
paths.iter().map(Self::from_abs_path).collect()
}
/// Renders a path URI using the requested native path convention.
///
/// Rendering fails when the URI shape does not match the convention, such