From b82943092cf52b69ab13ab1a5bb2beb7820deef7 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Wed, 18 Nov 2026 21:50:26 +0000 Subject: [PATCH] Preserve app-server thread working directories across platforms (#62375) ## Why A remote app server can report a working directory in a different path convention from the client. Decoding a Windows drive path as a client-native absolute path can make a Unix client reject the thread response. ## What changed Keep thread `cwd` values as server-native strings in summaries, settings, and start, resume, and fork responses. Preserve the JSON and generated SDK types. In the TUI, store the session directory as a `PathUri` using the server's path convention when available. Use that directory to match diff and skill results and to display the project name in the terminal title. ## Testing Add regression coverage for foreign-path response round trips, diff results matched against a remote session directory, and terminal titles derived from a Windows path. Verify that the server rejects a working directory that cannot be encoded as UTF-8. GitOrigin-RevId: 600f0b531939db4cd4ec884de166224082995e00 --- codex-rs/analytics/src/client_tests.rs | 13 ++- codex-rs/analytics/src/reducer.rs | 11 +-- .../src/tests/suite/threads_tests.rs | 3 +- codex-rs/analytics/src/tests/support.rs | 6 +- codex-rs/app-server-client/src/lib.rs | 11 +++ codex-rs/app-server-client/src/remote.rs | 2 + .../src/protocol/common.rs | 6 +- .../src/protocol/v2/tests.rs | 17 +++- .../src/protocol/v2/thread.rs | 16 +++- .../src/protocol/v2/thread_data.rs | 9 +- .../app-server/src/bespoke_event_handling.rs | 8 +- .../request_processors/thread_lifecycle.rs | 10 ++- .../request_processors/thread_processor.rs | 88 ++++++++++--------- .../thread_processor_tests.rs | 20 +++++ .../thread_resume_redaction.rs | 2 +- .../src/request_processors/thread_summary.rs | 19 ++-- codex-rs/app-server/src/thread_state.rs | 8 +- codex-rs/app-server/tests/prompt_prefix.rs | 2 +- .../tests/suite/v2/selected_environment.rs | 5 +- .../tests/suite/v2/thread_environments.rs | 2 +- .../app-server/tests/suite/v2/thread_list.rs | 8 +- .../app-server/tests/suite/v2/thread_read.rs | 2 +- .../tests/suite/v2/thread_resume.rs | 13 +-- .../tests/suite/v2/thread_settings_update.rs | 4 +- .../app-server/tests/suite/v2/thread_start.rs | 2 +- .../app-server/tests/suite/v2/turn_start.rs | 5 +- codex-rs/exec/src/lib.rs | 5 +- codex-rs/exec/src/lib_tests.rs | 6 +- codex-rs/tui/src/app.rs | 9 -- codex-rs/tui/src/app/agent_center_tests.rs | 6 +- codex-rs/tui/src/app/agents_overview.rs | 17 ++-- .../agents_overview_action_progress_tests.rs | 2 +- .../src/app/agents_overview_actions_tests.rs | 6 +- .../tui/src/app/agents_overview_details.rs | 4 +- .../tui/src/app/agents_overview_discovery.rs | 2 +- .../app/agents_overview_discovery_tests.rs | 2 +- codex-rs/tui/src/app/agents_overview_new.rs | 39 ++++---- codex-rs/tui/src/app/agents_overview_tests.rs | 18 ++-- codex-rs/tui/src/app/agents_overview_view.rs | 8 +- .../tui/src/app/app_server_event_targets.rs | 2 +- codex-rs/tui/src/app/backend_registry.rs | 7 ++ codex-rs/tui/src/app/background_requests.rs | 10 ++- codex-rs/tui/src/app/config_persistence.rs | 2 +- codex-rs/tui/src/app/event_dispatch.rs | 15 ++-- codex-rs/tui/src/app/history_pagination.rs | 7 +- codex-rs/tui/src/app/loaded_threads.rs | 2 +- codex-rs/tui/src/app/misalignment_policy.rs | 5 +- .../tui/src/app/owned_transcript_tests.rs | 2 +- codex-rs/tui/src/app/reconnect.rs | 1 + codex-rs/tui/src/app/session_lifecycle.rs | 20 ++++- codex-rs/tui/src/app/side.rs | 2 +- codex-rs/tui/src/app/side_companion.rs | 4 +- codex-rs/tui/src/app/side_companion_tests.rs | 2 +- codex-rs/tui/src/app/sidebar_files.rs | 2 +- codex-rs/tui/src/app/startup.rs | 1 + codex-rs/tui/src/app/tests.rs | 39 ++++---- .../tests/background_task_defaults_tests.rs | 11 +-- .../tui/src/app/tests/new_session_tests.rs | 4 +- .../tui/src/app/tests/projectless_tests.rs | 2 +- .../tui/src/app/tests/safety_buffering.rs | 11 ++- .../app/tests/session_lifecycle_requests.rs | 43 +++++++-- codex-rs/tui/src/app/tests/startup.rs | 2 +- .../src/app/tests/startup_defaults_tests.rs | 6 +- .../src/app/tests/startup_warnings_tests.rs | 12 ++- codex-rs/tui/src/app/thread_attachment.rs | 8 ++ codex-rs/tui/src/app/thread_events.rs | 2 +- codex-rs/tui/src/app/thread_routing.rs | 27 +++--- codex-rs/tui/src/app/thread_session_state.rs | 19 ++-- codex-rs/tui/src/app/thread_settings.rs | 15 +++- codex-rs/tui/src/app/transcript_export.rs | 2 +- codex-rs/tui/src/app/working_directory.rs | 2 +- codex-rs/tui/src/app_command.rs | 7 +- codex-rs/tui/src/app_event.rs | 10 +-- codex-rs/tui/src/app_server_session.rs | 86 +++++++++++++----- .../tui/src/app_server_session/history.rs | 2 +- .../src/app_server_session/rollout_history.rs | 20 ++--- .../workspace_roots_tests.rs | 4 +- codex-rs/tui/src/chatwidget.rs | 14 ++- codex-rs/tui/src/chatwidget/constructor.rs | 3 +- .../tui/src/chatwidget/input_submission.rs | 2 +- .../src/chatwidget/permission_discovery.rs | 2 +- .../tui/src/chatwidget/protocol_requests.rs | 4 - codex-rs/tui/src/chatwidget/session_flow.rs | 12 +-- codex-rs/tui/src/chatwidget/settings.rs | 18 ++-- codex-rs/tui/src/chatwidget/skills.rs | 31 ++++--- codex-rs/tui/src/chatwidget/slash_dispatch.rs | 28 +++--- .../tui/src/chatwidget/status_surfaces.rs | 45 +++++----- .../tui/src/chatwidget/statusline_reader.rs | 12 ++- .../src/chatwidget/statusline_reader_tests.rs | 4 +- .../tui/src/chatwidget/statusline_state.rs | 2 +- codex-rs/tui/src/chatwidget/streaming.rs | 2 +- .../tui/src/chatwidget/tests/app_server.rs | 19 ++-- .../chatwidget/tests/composer_submission.rs | 18 ++-- .../tui/src/chatwidget/tests/exec_flow.rs | 2 +- .../src/chatwidget/tests/history_replay.rs | 28 +++--- .../tui/src/chatwidget/tests/permissions.rs | 6 +- .../tui/src/chatwidget/tests/plan_mode.rs | 4 +- .../src/chatwidget/tests/slash_commands.rs | 7 +- .../src/chatwidget/tests/status_and_layout.rs | 2 +- .../tests/status_surface_previews.rs | 11 +++ codex-rs/tui/src/dynamic_tools.rs | 2 +- codex-rs/tui/src/history_cell/session.rs | 2 +- codex-rs/tui/src/history_cell/tests.rs | 9 +- codex-rs/tui/src/lib_tests.rs | 2 +- codex-rs/tui/src/resume_picker.rs | 8 +- codex-rs/tui/src/session_state.rs | 13 +-- codex-rs/tui/src/task_mentions.rs | 2 +- codex-rs/tui/src/thread_transcript.rs | 27 +++--- .../tui/src/thread_transcript/other_items.rs | 11 +-- codex-rs/tui/src/worktree_startup.rs | 2 +- .../utils/path-uri/src/api_path_string.rs | 11 +++ 111 files changed, 720 insertions(+), 479 deletions(-) diff --git a/codex-rs/analytics/src/client_tests.rs b/codex-rs/analytics/src/client_tests.rs index ab47becf11..958269ae3c 100644 --- a/codex-rs/analytics/src/client_tests.rs +++ b/codex-rs/analytics/src/client_tests.rs @@ -687,7 +687,7 @@ fn sample_thread(thread_id: &str) -> Thread { recency_at: Some(2), status: AppServerThreadStatus::Idle, path: None, - cwd: test_path_buf("/tmp").abs(), + cwd: test_path_buf("/tmp").abs().into(), cli_version: "0.0.0".to_string(), source: AppServerSessionSource::Exec, can_accept_direct_input: None, @@ -707,7 +707,7 @@ fn sample_thread_start_response() -> ClientResponsePayload { model: "gpt-5".to_string(), model_provider: "openai".to_string(), service_tier: None, - cwd: test_path_buf("/tmp").abs(), + cwd: test_path_buf("/tmp").abs().into(), runtime_workspace_roots: Vec::new(), instruction_sources: Vec::new(), approval_policy: AppServerAskForApproval::OnRequest, @@ -726,7 +726,7 @@ fn sample_thread_resume_response() -> ClientResponsePayload { model: "gpt-5".to_string(), model_provider: "openai".to_string(), service_tier: None, - cwd: test_path_buf("/tmp").abs(), + cwd: test_path_buf("/tmp").abs().into(), runtime_workspace_roots: Vec::new(), instruction_sources: Vec::new(), approval_policy: AppServerAskForApproval::OnRequest, @@ -749,7 +749,7 @@ fn sample_thread_fork_response() -> ClientResponsePayload { model: "gpt-5".to_string(), model_provider: "openai".to_string(), service_tier: None, - cwd: test_path_buf("/tmp").abs(), + cwd: test_path_buf("/tmp").abs().into(), runtime_workspace_roots: Vec::new(), instruction_sources: Vec::new(), approval_policy: AppServerAskForApproval::OnRequest, @@ -935,10 +935,7 @@ fn track_response_ignores_unserializable_thread_responses() { let ClientResponsePayload::ThreadStart(thread_start) = &mut response else { panic!("expected thread/start response"); }; - thread_start.cwd = codex_utils_absolute_path::AbsolutePathBuf::from_absolute_path( - std::path::PathBuf::from(OsString::from_vec(vec![b'/', b'b', b'a', b'd', 0xff])), - ) - .expect("non-UTF-8 Unix paths are valid absolute paths"); + thread_start.thread.path = Some(OsString::from_vec(b"/bad\xff".to_vec()).into()); client.track_response(/*connection_id*/ 7, RequestId::Integer(1), &response); diff --git a/codex-rs/analytics/src/reducer.rs b/codex-rs/analytics/src/reducer.rs index 3d2b32e1c3..d4d5bc90b3 100644 --- a/codex-rs/analytics/src/reducer.rs +++ b/codex-rs/analytics/src/reducer.rs @@ -2476,11 +2476,12 @@ impl AnalyticsReducer { out: &mut Vec, ) { let session_source: SessionSource = thread.source.into(); - let is_worktree = - codex_git_utils::repository_identity(thread.cwd.as_path()).and_then(|_| { - codex_git_utils::get_git_repo_root(thread.cwd.canonicalize().ok()?.as_path()) - .map(|root| root.join(".git").is_file()) - }); + let is_worktree = thread.cwd.to_inferred_path_uri().and_then(|cwd| { + let cwd = cwd.to_abs_path().ok()?; + codex_git_utils::repository_identity(cwd.as_path())?; + codex_git_utils::get_git_repo_root(cwd.canonicalize().ok()?.as_path()) + .map(|root| root.join(".git").is_file()) + }); let session_id = thread.session_id; let thread_id = thread.id; let parent_thread_id = thread.parent_thread_id; diff --git a/codex-rs/analytics/src/tests/suite/threads_tests.rs b/codex-rs/analytics/src/tests/suite/threads_tests.rs index 9c0dd2dd79..870d0e937b 100644 --- a/codex-rs/analytics/src/tests/suite/threads_tests.rs +++ b/codex-rs/analytics/src/tests/suite/threads_tests.rs @@ -164,8 +164,7 @@ async fn thread_initialized_classifies_validated_linked_worktrees() { let ClientResponsePayload::ThreadStart(start) = &mut response else { panic!("expected thread/start response"); }; - start.thread.cwd = codex_utils_absolute_path::AbsolutePathBuf::from_absolute_path(cwd) - .expect("absolute checkout path"); + start.thread.cwd = codex_utils_path_uri::LegacyAppPathString::from_path(cwd); reducer .ingest( AnalyticsFact::ClientResponse { diff --git a/codex-rs/analytics/src/tests/support.rs b/codex-rs/analytics/src/tests/support.rs index 04ba40cfc9..ed0fe1a3be 100644 --- a/codex-rs/analytics/src/tests/support.rs +++ b/codex-rs/analytics/src/tests/support.rs @@ -129,7 +129,7 @@ pub(super) fn sample_thread_with_metadata( recency_at: Some(2), status: AppServerThreadStatus::Idle, path: None, - cwd: test_path_buf("/tmp").abs(), + cwd: test_path_buf("/tmp").abs().into(), cli_version: "0.0.0".to_string(), source, can_accept_direct_input: None, @@ -159,7 +159,7 @@ pub(super) fn sample_thread_start_response( model: model.to_string(), model_provider: "openai".to_string(), service_tier: None, - cwd: test_path_buf("/tmp").abs(), + cwd: test_path_buf("/tmp").abs().into(), runtime_workspace_roots: Vec::new(), instruction_sources: Vec::new(), approval_policy: AppServerAskForApproval::OnRequest, @@ -225,7 +225,7 @@ pub(super) fn sample_thread_resume_response_with_source( model: model.to_string(), model_provider: "openai".to_string(), service_tier: None, - cwd: test_path_buf("/tmp").abs(), + cwd: test_path_buf("/tmp").abs().into(), runtime_workspace_roots: Vec::new(), instruction_sources: Vec::new(), approval_policy: AppServerAskForApproval::OnRequest, diff --git a/codex-rs/app-server-client/src/lib.rs b/codex-rs/app-server-client/src/lib.rs index 75819aa2fd..f2ec8661d4 100644 --- a/codex-rs/app-server-client/src/lib.rs +++ b/codex-rs/app-server-client/src/lib.rs @@ -382,6 +382,17 @@ pub enum AppServerRequestHandle { Remote(crate::remote::RemoteAppServerRequestHandle), } +impl AppServerRequestHandle { + /// Operating system reported by the app-server that serves these requests. + pub fn platform_os(&self) -> Option<&str> { + match self { + Self::InProcess(_) => Some(std::env::consts::OS), + Self::Remote(client) => client.platform_os.as_deref(), + Self::Cloud(_) => None, + } + } +} + pub enum AppServerClient { Cloud(CloudClient), InProcess(InProcessAppServerClient), diff --git a/codex-rs/app-server-client/src/remote.rs b/codex-rs/app-server-client/src/remote.rs index 5321c0600a..17be3b290e 100644 --- a/codex-rs/app-server-client/src/remote.rs +++ b/codex-rs/app-server-client/src/remote.rs @@ -174,6 +174,7 @@ pub struct RemoteAppServerClient { #[derive(Clone)] pub struct RemoteAppServerRequestHandle { command_tx: mpsc::Sender, + pub(crate) platform_os: Option, } enum SocketPeerPolicy { @@ -536,6 +537,7 @@ impl RemoteAppServerClient { pub fn request_handle(&self) -> RemoteAppServerRequestHandle { RemoteAppServerRequestHandle { command_tx: self.command_tx.clone(), + platform_os: self.metadata.platform_os.clone(), } } diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 3a42d10451..2cc4d935ec 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -3379,7 +3379,7 @@ mod tests { recency_at: Some(3), status: v2::ThreadStatus::Idle, path: None, - cwd: cwd.clone(), + cwd: cwd.clone().into(), cli_version: "0.0.0".to_string(), source: v2::SessionSource::Exec, can_accept_direct_input: None, @@ -3394,7 +3394,7 @@ mod tests { model: "gpt-5".to_string(), model_provider: "openai".to_string(), service_tier: None, - cwd, + cwd: cwd.into(), runtime_workspace_roots: Vec::new(), instruction_sources: vec![ codex_utils_path_uri::LegacyAppPathString::from_abs_path(&absolute_path( @@ -4644,7 +4644,7 @@ mod tests { thread_settings: v2::ThreadSettings { disabled_plugin_ids: Vec::new(), environments: Some(Vec::new()), - cwd: absolute_path("/tmp/repo"), + cwd: absolute_path("/tmp/repo").into(), approval_policy: v2::AskForApproval::Never, approvals_reviewer: v2::ApprovalsReviewer::User, sandbox_policy: v2::SandboxPolicy::DangerFullAccess, diff --git a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs index 148621e7f1..36042c4ddc 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs @@ -324,7 +324,7 @@ fn thread_resume_response_round_trips_initial_turns_page() { recency_at: Some(1), status: ThreadStatus::Idle, path: None, - cwd: absolute_path("tmp"), + cwd: absolute_path("tmp").into(), cli_version: "0.0.0".to_string(), source: SessionSource::Exec, can_accept_direct_input: None, @@ -339,7 +339,7 @@ fn thread_resume_response_round_trips_initial_turns_page() { model: "gpt-5".to_string(), model_provider: "openai".to_string(), service_tier: None, - cwd: absolute_path("tmp"), + cwd: absolute_path("tmp").into(), runtime_workspace_roots: Vec::new(), instruction_sources: Vec::new(), approval_policy: AskForApproval::OnRequest, @@ -5162,6 +5162,11 @@ fn thread_start_params_preserve_explicit_null_service_tier() { #[test] fn thread_lifecycle_responses_default_missing_optional_fields() { + let cwd = if cfg!(windows) { + "/home/alice/repo" + } else { + r"D:\repo" + }; let response = json!({ "thread": { "id": "thread-id", @@ -5174,7 +5179,7 @@ fn thread_lifecycle_responses_default_missing_optional_fields() { "updatedAt": 1, "status": { "type": "idle" }, "path": null, - "cwd": absolute_path_string("tmp"), + "cwd": cwd, "cliVersion": "0.0.0", "source": "exec", "agentNickname": null, @@ -5186,7 +5191,7 @@ fn thread_lifecycle_responses_default_missing_optional_fields() { "model": "gpt-5", "modelProvider": "openai", "serviceTier": null, - "cwd": absolute_path_string("tmp"), + "cwd": cwd, "approvalPolicy": "on-request", "approvalsReviewer": "user", "sandbox": { "type": "dangerFullAccess" }, @@ -5200,6 +5205,10 @@ fn thread_lifecycle_responses_default_missing_optional_fields() { let fork: ThreadForkResponse = serde_json::from_value(response.clone()).expect("thread/fork response"); + for encoded in [json!(start), json!(resume), json!(fork)] { + assert_eq!(encoded["thread"]["cwd"], cwd); + assert_eq!(encoded["cwd"], cwd); + } assert_eq!(start.instruction_sources, Vec::::new()); assert_eq!(start.thread.parent_thread_id, None); assert_eq!(start.thread.recency_at, None); diff --git a/codex-rs/app-server-protocol/src/protocol/v2/thread.rs b/codex-rs/app-server-protocol/src/protocol/v2/thread.rs index 0f2bb10f5e..f26b572a9a 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/thread.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/thread.rs @@ -196,7 +196,9 @@ pub struct ThreadStartResponse { /// Saved list of disabled plugin IDs. Does not yet filter plugin capabilities. #[serde(default)] pub disabled_plugin_ids: Vec, - pub cwd: AbsolutePathBuf, + #[schemars(with = "AbsolutePathBuf")] + #[ts(as = "AbsolutePathBuf")] + pub cwd: LegacyAppPathString, /// Thread-scoped runtime workspace roots used to materialize /// `:workspace_roots`. #[experimental("thread/start.runtimeWorkspaceRoots")] @@ -314,7 +316,9 @@ pub struct ThreadSettings { /// Saved list of disabled plugin IDs. Does not yet filter plugin capabilities. #[serde(default)] pub disabled_plugin_ids: Vec, - pub cwd: AbsolutePathBuf, + #[schemars(with = "AbsolutePathBuf")] + #[ts(as = "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. #[experimental("thread/settings.environments")] @@ -455,7 +459,9 @@ pub struct ThreadResumeResponse { /// Saved list of disabled plugin IDs. Does not yet filter plugin capabilities. #[serde(default)] pub disabled_plugin_ids: Vec, - pub cwd: AbsolutePathBuf, + #[schemars(with = "AbsolutePathBuf")] + #[ts(as = "AbsolutePathBuf")] + pub cwd: LegacyAppPathString, /// Thread-scoped runtime workspace roots used to materialize /// `:workspace_roots`. #[experimental("thread/resume.runtimeWorkspaceRoots")] @@ -672,7 +678,9 @@ pub struct ThreadForkResponse { /// Saved list of disabled plugin IDs. Does not yet filter plugin capabilities. #[serde(default)] pub disabled_plugin_ids: Vec, - pub cwd: AbsolutePathBuf, + #[schemars(with = "AbsolutePathBuf")] + #[ts(as = "AbsolutePathBuf")] + pub cwd: LegacyAppPathString, /// Thread-scoped runtime workspace roots used to materialize /// `:workspace_roots`. #[experimental("thread/fork.runtimeWorkspaceRoots")] diff --git a/codex-rs/app-server-protocol/src/protocol/v2/thread_data.rs b/codex-rs/app-server-protocol/src/protocol/v2/thread_data.rs index 33aa92edd3..3ab9937098 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/thread_data.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/thread_data.rs @@ -14,7 +14,7 @@ use codex_protocol::protocol::SessionSource as CoreSessionSource; use codex_protocol::protocol::SubAgentSource as CoreSubAgentSource; use codex_protocol::protocol::ThreadHistoryMode as CoreThreadHistoryMode; use codex_protocol::protocol::ThreadSource as CoreThreadSource; -use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_path_uri::LegacyAppPathString; #[cfg(test)] use schemars::r#gen::SchemaGenerator; #[cfg(test)] @@ -265,7 +265,10 @@ pub struct Thread { /// [UNSTABLE] Path to the thread on disk. pub path: Option, /// Working directory captured for the thread. - pub cwd: AbsolutePathBuf, + // Preserve the published SDK type for this server-native absolute path. + #[schemars(with = "codex_utils_absolute_path::AbsolutePathBuf")] + #[ts(as = "codex_utils_absolute_path::AbsolutePathBuf")] + pub cwd: LegacyAppPathString, /// Version of the CLI that created the thread. pub cli_version: String, /// Originator recorded when the thread was created, independent of its current client or executor. @@ -328,7 +331,7 @@ struct ThreadCompatibility { recency_at: Option, status: ThreadStatus, path: Option, - cwd: AbsolutePathBuf, + cwd: LegacyAppPathString, cli_version: String, originator: Option, source: SessionSource, diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index c64be6aed7..5dfbfab653 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -1320,7 +1320,13 @@ pub(crate) async fn apply_bespoke_event_handling( let (mut config_snapshot, selected_service_tier) = conversation.resume_config_snapshot().await; config_snapshot.service_tier = selected_service_tier; - let thread_settings = thread_settings_from_config_snapshot(&config_snapshot); + let thread_settings = match thread_settings_from_config_snapshot(&config_snapshot) { + Ok(settings) => settings, + Err(error) => { + tracing::warn!(%conversation_id, message = %error.message, "cannot publish thread settings"); + return; + } + }; let changed = { let mut state = thread_state.lock().await; state.note_thread_settings(thread_settings.clone()) diff --git a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs index f95d09f8cc..80d3e41cc7 100644 --- a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs +++ b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs @@ -351,7 +351,7 @@ async fn start_listener( .await; let is_v2_child = conversation.multi_agent_version() == Some(MultiAgentVersion::V2) && matches!(config_snapshot.session_source, SessionSource::SubAgent(_)); - let thread_settings_baseline = thread_settings_from_config_snapshot(&config_snapshot); + let thread_settings_baseline = thread_settings_from_config_snapshot(&config_snapshot).ok(); let thread_state = Arc::clone(listener_state.state()); let (mut listener_command_rx, listener_generation, mut unloading_state, attached) = { let (created, connection_ids, raw_events_enabled) = match &startup { @@ -1258,7 +1258,13 @@ pub(super) async fn handle_pending_thread_resume_request( let config_snapshot = pending.config_snapshot; let sandbox = config_snapshot.sandbox_policy().into(); - let cwd = config_snapshot.cwd().clone(); + let cwd = match thread_cwd_for_api(config_snapshot.cwd()) { + Ok(cwd) => cwd, + Err(error) => { + outgoing.send_error(request_id, error).await; + return; + } + }; let ThreadConfigSnapshot { model, disabled_plugin_ids, diff --git a/codex-rs/app-server/src/request_processors/thread_processor.rs b/codex-rs/app-server/src/request_processors/thread_processor.rs index 333c1c70bc..28dd5e81e9 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor.rs @@ -1733,7 +1733,7 @@ impl ThreadRequestProcessor { thread.multi_agent_version(), &config_snapshot, session_configured.rollout_path.clone(), - ); + )?; thread.project_id = project_id.clone(); thread.daybreak_enabled = daybreak_enabled; @@ -1778,7 +1778,7 @@ impl ThreadRequestProcessor { ); let sandbox = config_snapshot.sandbox_policy().into(); - let cwd = config_snapshot.cwd().clone(); + let cwd = thread.cwd.clone(); let active_permission_profile = thread_response_active_permission_profile(config_snapshot.active_permission_profile); let thread_originator = config_snapshot.originator.clone(); @@ -2214,7 +2214,7 @@ impl ThreadRequestProcessor { updated_thread, self.config.model_provider_id.as_str(), &self.config.cwd, - ); + )?; if let Ok(loaded_thread) = self.thread_manager.get_thread(thread_uuid).await { thread.session_id = loaded_thread.startup_metadata().session_id.to_string(); let config_snapshot = loaded_thread.config_snapshot().await; @@ -2272,7 +2272,7 @@ impl ThreadRequestProcessor { .await .map_err(|err| thread_store_mutation_error("unarchive", err))?; let (mut thread, _) = - thread_from_stored_thread(stored_thread, fallback_provider.as_str(), &self.config.cwd); + thread_from_stored_thread(stored_thread, fallback_provider.as_str(), &self.config.cwd)?; if let Ok(loaded_thread) = self.thread_manager.get_thread(thread_id).await { let config_snapshot = loaded_thread.config_snapshot().await; @@ -2932,7 +2932,7 @@ impl ThreadRequestProcessor { stored_thread, fallback_provider.as_str(), &self.config.cwd, - ); + )?; data.push(thread); } @@ -3073,7 +3073,7 @@ impl ThreadRequestProcessor { let data = tokio::select! { biased; page = &mut search => break page, - data = self.thread_search_provisional_rows(batch) => data, + data = self.thread_search_provisional_rows(batch) => data?, }; if self.outgoing.try_send_server_notification( crate::outgoing_message::NotificationTarget::Connection(request_id.connection_id), @@ -3114,7 +3114,7 @@ impl ThreadRequestProcessor { let data = tokio::select! { biased; () = cancellation.cancelled() => return Err(invalid_request("thread search cancelled")), - data = self.thread_search_rows(search_results) => data, + data = self.thread_search_rows(search_results) => data?, }; Ok(ThreadSearchResponse { data, @@ -3126,28 +3126,28 @@ impl ThreadRequestProcessor { fn thread_search_stored_rows( &self, search_results: Vec, - ) -> Vec { + ) -> Result, JSONRPCErrorError> { let mut data = Vec::with_capacity(search_results.len()); for result in search_results { let (thread, _) = thread_from_stored_thread( result.thread, &self.config.model_provider_id, &self.config.cwd, - ); + )?; data.push(ThreadSearchResult { thread, snippet: result.snippet, }); } - data + Ok(data) } async fn thread_search_provisional_rows( &self, search_results: Vec, - ) -> Vec { - let mut data = self.thread_search_stored_rows(search_results); + ) -> Result, JSONRPCErrorError> { + let mut data = self.thread_search_stored_rows(search_results)?; let statuses = self .thread_watch_manager .loaded_statuses_for_threads(data.iter().map(|result| result.thread.id.clone())) @@ -3157,14 +3157,14 @@ impl ThreadRequestProcessor { result.thread.status = status.clone(); } } - data + Ok(data) } async fn thread_search_rows( &self, search_results: Vec, - ) -> Vec { - let mut data = self.thread_search_stored_rows(search_results); + ) -> Result, JSONRPCErrorError> { + let mut data = self.thread_search_stored_rows(search_results)?; enrich_loaded_threads( &self.thread_manager, &self.thread_watch_manager, @@ -3173,7 +3173,7 @@ impl ThreadRequestProcessor { ) .await; - data + Ok(data) } async fn thread_loaded_list_response_inner( @@ -3314,7 +3314,8 @@ impl ThreadRequestProcessor { }; if matches!(stored_thread.history_mode, ThreadHistoryMode::Paginated) { let (mut thread, _) = - thread_from_stored_thread(stored_thread, fallback_provider, &self.config.cwd); + thread_from_stored_thread(stored_thread, fallback_provider, &self.config.cwd) + .map_err(ThreadReadViewError::JsonRpc)?; thread.turns = self .paginated_thread_full_turns(thread_id) .await @@ -3329,7 +3330,8 @@ impl ThreadRequestProcessor { return Ok(None); }; let (mut thread, history) = - thread_from_stored_thread(stored_thread, fallback_provider, &self.config.cwd); + thread_from_stored_thread(stored_thread, fallback_provider, &self.config.cwd) + .map_err(ThreadReadViewError::JsonRpc)?; if include_turns && let Some(history) = history { thread.turns = build_legacy_api_turns_from_rollout_items(&history.items); } @@ -3405,6 +3407,7 @@ impl ThreadRequestProcessor { thread } else { build_thread_from_loaded_snapshot(thread_id, &config_snapshot, loaded_thread) + .map_err(ThreadReadViewError::JsonRpc)? }; self.attach_thread_name(thread_id, &mut thread).await; if include_turns { @@ -4690,7 +4693,7 @@ impl ThreadRequestProcessor { model: session_configured.model, model_provider: session_configured.model_provider_id, service_tier: session_configured.service_tier, - cwd: session_configured.cwd, + cwd: thread_cwd_for_api(&session_configured.cwd)?, runtime_workspace_roots: config_snapshot.workspace_roots, instruction_sources, approval_policy: session_configured.approval_policy.into(), @@ -5002,7 +5005,7 @@ impl ThreadRequestProcessor { source_thread, config_snapshot.model_provider_id.as_str(), /*include_turns*/ false, - ); + )?; thread_summary.session_id = existing_thread.startup_metadata().session_id.to_string(); thread_summary.thread_source = config_snapshot.thread_source.clone().map(Into::into); apply_live_thread_settings(&mut thread_summary, &config_snapshot); @@ -5270,9 +5273,9 @@ impl ThreadRequestProcessor { stored_thread: StoredThread, fallback_provider: &str, include_turns: bool, - ) -> Thread { + ) -> Result { let (mut thread, history) = - thread_from_stored_thread(stored_thread, fallback_provider, &self.config.cwd); + thread_from_stored_thread(stored_thread, fallback_provider, &self.config.cwd)?; if include_turns && let Some(history) = history { populate_thread_turns_from_history( &mut thread, @@ -5280,7 +5283,7 @@ impl ThreadRequestProcessor { /*active_turn*/ None, ); } - thread + Ok(thread) } async fn read_stored_thread_for_new_fork( @@ -5343,12 +5346,9 @@ impl ThreadRequestProcessor { ..stored_thread }) }; - Ok(thread_from_stored_thread( - stored_thread, - fallback_provider, - &self.config.cwd, - ) - .0) + thread_from_stored_thread(stored_thread, fallback_provider, &self.config.cwd) + .map(|(thread, _)| thread) + .map_err(|error| error.message) } else { match self .thread_store @@ -5359,12 +5359,13 @@ impl ThreadRequestProcessor { }) .await { - Ok(stored_thread) => Ok(thread_from_stored_thread( + Ok(stored_thread) => thread_from_stored_thread( stored_thread, fallback_provider, &self.config.cwd, ) - .0), + .map(|(thread, _)| thread) + .map_err(|error| error.message), Err(read_err) => { Err(format!("failed to read thread from store: {read_err}")) } @@ -5378,7 +5379,8 @@ impl ThreadRequestProcessor { thread.multi_agent_version(), &config_snapshot, Some(rollout_path.into()), - ); + ) + .map_err(|error| error.message)?; thread.preview = preview_from_rollout_items(items); Ok(thread) } @@ -6001,7 +6003,7 @@ impl ThreadRequestProcessor { stored_thread, fallback_model_provider.as_str(), &self.config.cwd, - ); + )?; if include_turns && let Some(history) = history.as_ref() { populate_thread_turns_from_history( &mut thread, @@ -6027,7 +6029,7 @@ impl ThreadRequestProcessor { forked_thread.multi_agent_version(), &config_snapshot, /*path*/ None, - ); + )?; thread.preview = inherited_preview; thread.forked_from_id = Some(source_thread_id.to_string()); thread.turns = ephemeral_turns; @@ -6078,7 +6080,7 @@ impl ThreadRequestProcessor { model: config_snapshot.model.clone(), model_provider: session_configured.model_provider_id, service_tier: config_snapshot.service_tier.clone(), - cwd: session_configured.cwd, + cwd: thread_cwd_for_api(&session_configured.cwd)?, runtime_workspace_roots: config_snapshot.workspace_roots, instruction_sources, approval_policy: session_configured.approval_policy.into(), @@ -6883,7 +6885,7 @@ fn thread_from_stored_thread( thread: StoredThread, fallback_provider: &str, fallback_cwd: &AbsolutePathBuf, -) -> (Thread, Option) { +) -> Result<(Thread, Option), JSONRPCErrorError> { let path = thread.rollout_path; let git_info = thread.git_info.map(|info| ApiGitInfo { sha: info.commit_hash.map(|sha| sha.0), @@ -6941,7 +6943,7 @@ fn thread_from_stored_thread( recency_at: Some(thread.recency_at.timestamp()), status: ThreadStatus::NotLoaded, path, - cwd, + cwd: thread_cwd_for_api(&cwd)?, cli_version: thread.cli_version, originator: thread.originator, agent_nickname: source.get_nickname(), @@ -6954,7 +6956,7 @@ fn thread_from_stored_thread( daybreak_enabled: thread.daybreak_enabled, turns: Vec::new(), }; - (thread, history) + Ok((thread, history)) } fn summary_from_stored_thread( @@ -7097,9 +7099,9 @@ fn build_thread_from_snapshot( multi_agent_version: Option, config_snapshot: &ThreadConfigSnapshot, path: Option, -) -> Thread { +) -> Result { let now = time::OffsetDateTime::now_utc().unix_timestamp(); - Thread { + Ok(Thread { id: thread_id.to_string(), environments: Some( config_snapshot @@ -7127,7 +7129,7 @@ fn build_thread_from_snapshot( recency_at: Some(now), status: ThreadStatus::NotLoaded, path, - cwd: config_snapshot.cwd().clone(), + cwd: thread_cwd_for_api(config_snapshot.cwd())?, cli_version: env!("CARGO_PKG_VERSION").to_string(), originator: (!config_snapshot.originator.is_empty()) .then(|| config_snapshot.originator.clone()), @@ -7143,7 +7145,7 @@ fn build_thread_from_snapshot( name: None, daybreak_enabled: None, turns: Vec::new(), - } + }) } fn paginate_background_terminals( @@ -7178,7 +7180,7 @@ fn build_thread_from_loaded_snapshot( thread_id: ThreadId, config_snapshot: &ThreadConfigSnapshot, loaded_thread: &CodexThread, -) -> Thread { +) -> Result { build_thread_from_snapshot( thread_id, loaded_thread.startup_metadata().session_id.to_string(), diff --git a/codex-rs/app-server/src/request_processors/thread_processor_tests.rs b/codex-rs/app-server/src/request_processors/thread_processor_tests.rs index d0695f55bf..b5d65f9d68 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor_tests.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor_tests.rs @@ -2,6 +2,26 @@ use codex_app_server_protocol::JSONRPCErrorError; use codex_thread_store::ThreadStoreError; use pretty_assertions::assert_eq; +#[cfg(unix)] +#[test] +fn thread_cwd_rejects_invalid_utf8() { + use std::ffi::OsStr; + use std::os::unix::ffi::OsStrExt; + + let cwd = codex_utils_absolute_path::AbsolutePathBuf::from_absolute_path(OsStr::from_bytes( + b"/workspace-\xFF", + )) + .expect("absolute native path"); + assert_eq!( + super::thread_cwd_for_api(&cwd).expect_err("cwd cannot be represented as a wire string"), + JSONRPCErrorError { + code: crate::error_code::INTERNAL_ERROR_CODE, + message: "cannot encode thread cwd: path contains invalid UTF-8".into(), + data: None, + } + ); +} + #[test] fn storage_failure_classification_does_not_change_mutation_error_policy() { for error in [ diff --git a/codex-rs/app-server/src/request_processors/thread_resume_redaction.rs b/codex-rs/app-server/src/request_processors/thread_resume_redaction.rs index 6c2e876591..d9980749bc 100644 --- a/codex-rs/app-server/src/request_processors/thread_resume_redaction.rs +++ b/codex-rs/app-server/src/request_processors/thread_resume_redaction.rs @@ -241,7 +241,7 @@ mod tests { recency_at: Some(0), status: ThreadStatus::Idle, path: None, - cwd: test_path_buf("/tmp").abs(), + cwd: test_path_buf("/tmp").abs().into(), cli_version: "0.0.0".to_string(), source: SessionSource::Cli, can_accept_direct_input: None, diff --git a/codex-rs/app-server/src/request_processors/thread_summary.rs b/codex-rs/app-server/src/request_processors/thread_summary.rs index 07826f26cc..6715b65e6a 100644 --- a/codex-rs/app-server/src/request_processors/thread_summary.rs +++ b/codex-rs/app-server/src/request_processors/thread_summary.rs @@ -4,6 +4,7 @@ use chrono::DateTime; #[cfg(test)] use chrono::Utc; use codex_protocol::config_types::MultiAgentMode; +use codex_utils_path_uri::LegacyAppPathString; #[cfg(test)] pub(crate) async fn read_summary_from_rollout( @@ -172,12 +173,20 @@ pub(crate) fn thread_response_active_permission_profile( active_permission_profile.map(Into::into) } +pub(super) fn thread_cwd_for_api( + cwd: &AbsolutePathBuf, +) -> Result { + cwd.to_str() + .map(LegacyAppPathString::from_string) + .ok_or_else(|| internal_error("cannot encode thread cwd: path contains invalid UTF-8")) +} + pub(crate) fn thread_settings_from_config_snapshot( config_snapshot: &ThreadConfigSnapshot, -) -> ThreadSettings { - ThreadSettings { +) -> Result { + Ok(ThreadSettings { disabled_plugin_ids: config_snapshot.disabled_plugin_ids.clone(), - cwd: config_snapshot.cwd().clone(), + cwd: thread_cwd_for_api(config_snapshot.cwd())?, environments: Some( config_snapshot .environment_selections() @@ -199,7 +208,7 @@ pub(crate) fn thread_settings_from_config_snapshot( collaboration_mode: config_snapshot.collaboration_mode.clone(), multi_agent_mode: MultiAgentMode::ExplicitRequestOnly, personality: config_snapshot.personality, - } + }) } #[cfg(test)] @@ -289,7 +298,7 @@ pub(crate) fn summary_to_thread( recency_at: updated_at.map(|dt| dt.timestamp()), status: ThreadStatus::NotLoaded, path: (!path.as_os_str().is_empty()).then_some(path), - cwd, + cwd: cwd.into(), cli_version, agent_nickname: source.get_nickname(), agent_role: source.get_agent_role(), diff --git a/codex-rs/app-server/src/thread_state.rs b/codex-rs/app-server/src/thread_state.rs index 42e46cab00..7c6429b0c8 100644 --- a/codex-rs/app-server/src/thread_state.rs +++ b/codex-rs/app-server/src/thread_state.rs @@ -173,7 +173,7 @@ impl ThreadState { shutdown_drain: watch::Receiver, conversation: &Arc, watch_registration: WatchRegistration, - thread_settings_baseline: ThreadSettings, + thread_settings_baseline: Option, history_mode: ThreadHistoryMode, ) -> (mpsc::UnboundedReceiver, u64) { if let Some(previous) = self.cancel_tx.replace(cancel_tx) { @@ -185,7 +185,7 @@ impl ThreadState { self.shutdown_drain = Some(shutdown_drain); self.listener_generation = self.listener_generation.wrapping_add(1); self.listener_shutdown = false; - self.last_thread_settings = Some(thread_settings_baseline); + self.last_thread_settings = thread_settings_baseline; self.history_mode = history_mode; self.evict_superseded_agent_text = history_mode == ThreadHistoryMode::Paginated && conversation.rollout_path().is_some(); @@ -393,7 +393,9 @@ mod tests { ThreadSettings { disabled_plugin_ids: Vec::new(), environments: Some(Vec::new()), - cwd: AbsolutePathBuf::from_absolute_path("/tmp").expect("absolute path"), + cwd: AbsolutePathBuf::from_absolute_path("/tmp") + .expect("absolute path") + .into(), approval_policy: AskForApproval::OnRequest, approvals_reviewer: ApprovalsReviewer::User, sandbox_policy: SandboxPolicy::ReadOnly { diff --git a/codex-rs/app-server/tests/prompt_prefix.rs b/codex-rs/app-server/tests/prompt_prefix.rs index ee8dbd3f01..ac3134c555 100644 --- a/codex-rs/app-server/tests/prompt_prefix.rs +++ b/codex-rs/app-server/tests/prompt_prefix.rs @@ -110,7 +110,7 @@ async fn prompt_prefix_matches_release() -> Result<()> { let environment = app.auto_env_params()?; for (value, replacement) in [ (environment.cwd.as_str(), ""), - (thread.cwd.to_string_lossy().as_ref(), ""), + (thread.cwd.as_str(), ""), (home.path().to_string_lossy().as_ref(), ""), (thread.id.as_str(), ""), (thread.session_id.as_str(), ""), diff --git a/codex-rs/app-server/tests/suite/v2/selected_environment.rs b/codex-rs/app-server/tests/suite/v2/selected_environment.rs index d07ce4f048..0d1bbd4152 100644 --- a/codex-rs/app-server/tests/suite/v2/selected_environment.rs +++ b/codex-rs/app-server/tests/suite/v2/selected_environment.rs @@ -4,7 +4,6 @@ use std::time::Duration; use anyhow::Context; use anyhow::Result; use app_test_support::MockResponsesConfig; -use app_test_support::PathBufExt; use app_test_support::TestAppServer; use app_test_support::create_final_assistant_message_sse_response; use app_test_support::create_mock_responses_server_sequence; @@ -67,8 +66,8 @@ async fn thread_start_reports_selected_environment_metadata() -> Result<()> { } = app_server .start_thread(ThreadStartParams::default()) .await?; - let host_cwd = codex_home.path().to_path_buf().abs().canonicalize()?; - let cwd = cwd.canonicalize()?; + let host_cwd = codex_home.path().canonicalize()?; + let cwd = cwd.as_path().canonicalize()?; assert_eq!( (cwd, runtime_workspace_roots, active_permission_profile), ( diff --git a/codex-rs/app-server/tests/suite/v2/thread_environments.rs b/codex-rs/app-server/tests/suite/v2/thread_environments.rs index c9bc999f6d..0b5bcab0cb 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_environments.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_environments.rs @@ -110,7 +110,7 @@ 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().into(), + cwd: resumed.cwd.clone(), runtime_workspace_roots: resumed .runtime_workspace_roots .iter() diff --git a/codex-rs/app-server/tests/suite/v2/thread_list.rs b/codex-rs/app-server/tests/suite/v2/thread_list.rs index 4524b7dec8..3e9f143d09 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_list.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_list.rs @@ -757,7 +757,7 @@ async fn thread_list_pagination_next_cursor_none_on_last_page() -> Result<()> { assert_eq!(thread.model_provider, "mock_provider"); assert!(thread.created_at > 0); assert_eq!(thread.updated_at, thread.created_at); - assert_eq!(thread.cwd, test_absolute_path("/")); + assert_eq!(thread.cwd, test_absolute_path("/").into()); assert_eq!(thread.cli_version, "0.0.0"); assert_eq!(thread.source, SessionSource::Cli); assert_eq!(thread.git_info, None); @@ -785,7 +785,7 @@ async fn thread_list_pagination_next_cursor_none_on_last_page() -> Result<()> { assert_eq!(thread.model_provider, "mock_provider"); assert!(thread.created_at > 0); assert_eq!(thread.updated_at, thread.created_at); - assert_eq!(thread.cwd, test_absolute_path("/")); + assert_eq!(thread.cwd, test_absolute_path("/").into()); assert_eq!(thread.cli_version, "0.0.0"); assert_eq!(thread.source, SessionSource::Cli); assert_eq!(thread.git_info, None); @@ -841,7 +841,7 @@ async fn thread_list_respects_provider_filter() -> Result<()> { let expected_ts = chrono::DateTime::parse_from_rfc3339("2025-01-02T11:00:00Z")?.timestamp(); assert_eq!(thread.created_at, expected_ts); assert_eq!(thread.updated_at, expected_ts); - assert_eq!(thread.cwd, test_absolute_path("/")); + assert_eq!(thread.cwd, test_absolute_path("/").into()); assert_eq!(thread.cli_version, "0.0.0"); assert_eq!(thread.source, SessionSource::Cli); assert_eq!(thread.git_info, None); @@ -2536,7 +2536,7 @@ async fn thread_list_includes_git_info() -> Result<()> { }; assert_eq!(thread.git_info, Some(expected_git)); assert_eq!(thread.source, SessionSource::Cli); - assert_eq!(thread.cwd, test_absolute_path("/")); + assert_eq!(thread.cwd, test_absolute_path("/").into()); assert_eq!(thread.cli_version, "0.0.0"); Ok(()) diff --git a/codex-rs/app-server/tests/suite/v2/thread_read.rs b/codex-rs/app-server/tests/suite/v2/thread_read.rs index dc24b4dfdd..151f86068f 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_read.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_read.rs @@ -161,7 +161,7 @@ async fn thread_read_returns_summary_without_turns() -> Result<()> { assert_eq!(thread.model_provider, "mock_provider"); assert!(!thread.ephemeral, "stored rollouts should not be ephemeral"); assert!(thread.path.as_ref().expect("thread path").is_absolute()); - assert_eq!(thread.cwd, test_absolute_path("/")); + assert_eq!(thread.cwd, test_absolute_path("/").into()); assert_eq!(thread.cli_version, "0.0.0"); assert_eq!(thread.source, SessionSource::Cli); assert_eq!(thread.git_info, None); diff --git a/codex-rs/app-server/tests/suite/v2/thread_resume.rs b/codex-rs/app-server/tests/suite/v2/thread_resume.rs index 10d5572bbd..e4cb77971b 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -901,7 +901,7 @@ 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(), expected_roots) + (initial_cwd.clone().into(), expected_roots) ); Ok(()) @@ -1019,7 +1019,7 @@ sandbox = "unelevated" timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_id)).await??; assert_eq!( (resumed.cwd, resumed.runtime_workspace_roots), - (expected_cwd.clone(), expected_roots.clone()) + (expected_cwd.clone().into(), expected_roots.clone()) ); if index < 3 { mcp.start_turn_and_wait_for_completion(TurnStartParams { @@ -1236,7 +1236,7 @@ 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(), expected_roots) + (thread_id, local_cwd.clone().into(), expected_roots) ); } else { let error = timeout( @@ -2930,7 +2930,7 @@ async fn thread_resume_returns_rollout_history() -> Result<()> { assert_eq!(thread.model_provider, "mock_provider"); assert!(thread.path.as_ref().expect("thread path").is_absolute()); assert_eq!(thread.cwd.as_path(), cwd.as_path()); - assert_eq!(cwd, test_absolute_path("/")); + assert_eq!(cwd, test_absolute_path("/").into()); assert_eq!(thread.cli_version, "0.0.0"); assert_eq!(thread.source, SessionSource::Cli); assert_eq!(thread.git_info, None); @@ -5211,7 +5211,10 @@ async fn thread_resume_checkpoints_settings_without_advancing_recency() -> Resul .await?; let ThreadResumeResponse { cwd, .. } = timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_id)).await??; - assert_eq!(cwd, AbsolutePathBuf::from_absolute_path(codex_home.path())?); + assert_eq!( + cwd, + AbsolutePathBuf::from_absolute_path(codex_home.path())?.into() + ); let turn_id = mcp .send_turn_start_request(TurnStartParams { diff --git a/codex-rs/app-server/tests/suite/v2/thread_settings_update.rs b/codex-rs/app-server/tests/suite/v2/thread_settings_update.rs index 0a83f8133d..ba86dd259d 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_settings_update.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_settings_update.rs @@ -87,8 +87,8 @@ url = "ws://127.0.0.1:2" let started: ThreadStartResponse = mcp.read_response(request_id).await?; let environment_a = ThreadEnvironment { environment_id: "remote-a".to_string(), - cwd: started.cwd.clone().into(), - runtime_workspace_roots: vec![started.cwd.clone().into()], + cwd: started.cwd.clone(), + runtime_workspace_roots: vec![started.cwd.clone()], }; let environment_b = ThreadEnvironment { environment_id: "remote-b".to_string(), diff --git a/codex-rs/app-server/tests/suite/v2/thread_start.rs b/codex-rs/app-server/tests/suite/v2/thread_start.rs index 6c2aefad7b..104a980819 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_start.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_start.rs @@ -575,7 +575,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()); + assert_eq!(response_cwd, cwd.abs().into()); assert_eq!(runtime_workspace_roots, vec![extra_root.abs()]); #[cfg(windows)] let _ = sandbox; diff --git a/codex-rs/app-server/tests/suite/v2/turn_start.rs b/codex-rs/app-server/tests/suite/v2/turn_start.rs index 5419761db5..9ac22017ee 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -3609,7 +3609,10 @@ async fn turn_start_explicit_local_environment_updates_legacy_cwd_between_turns( mcp.read_notification("thread/settings/updated"), ) .await??; - assert_eq!(settings_updated.thread_settings.cwd, second_cwd.abs()); + assert_eq!( + settings_updated.thread_settings.cwd, + second_cwd.abs().into() + ); let command_exec_item = timeout(DEFAULT_READ_TIMEOUT, async { loop { diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 9c331f4a27..16be1ff5e9 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -122,6 +122,7 @@ use codex_utils_absolute_path::canonicalize_existing_preserving_symlinks; use codex_utils_cli::SharedCliOptions; use codex_utils_oss::ensure_oss_provider_ready; use codex_utils_oss::get_default_model_for_oss_provider; +use codex_utils_path_uri::LegacyAppPathString; use codex_worktree::CreateWorktree; use codex_worktree::WorktreeManager; use codex_worktree::WorktreeSettings; @@ -1852,7 +1853,7 @@ fn session_configured_from_thread_response( approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer, permission_profile: PermissionProfile, active_permission_profile: Option, - cwd: AbsolutePathBuf, + cwd: LegacyAppPathString, reasoning_effort: Option, ) -> Result { let session_id = SessionId::from_string(session_id) @@ -1882,7 +1883,7 @@ fn session_configured_from_thread_response( approvals_reviewer, permission_profile, active_permission_profile, - cwd, + cwd: AbsolutePathBuf::try_from(cwd).map_err(|err| err.to_string())?, reasoning_effort, network_proxy: None, rollout_path, diff --git a/codex-rs/exec/src/lib_tests.rs b/codex-rs/exec/src/lib_tests.rs index 9477014fb6..1177082b84 100644 --- a/codex-rs/exec/src/lib_tests.rs +++ b/codex-rs/exec/src/lib_tests.rs @@ -375,7 +375,7 @@ fn turn_items_for_thread_returns_matching_turn_items() { recency_at: Some(0), status: codex_app_server_protocol::ThreadStatus::Idle, path: None, - cwd: test_path_buf("/tmp/project").abs(), + cwd: test_path_buf("/tmp/project").abs().into(), cli_version: "0.0.0-test".to_string(), originator: None, source: codex_app_server_protocol::SessionSource::Exec, @@ -896,7 +896,7 @@ fn sample_thread_start_response() -> ThreadStartResponse { recency_at: Some(0), status: codex_app_server_protocol::ThreadStatus::Idle, path: Some(PathBuf::from("/tmp/rollout.jsonl")), - cwd: test_path_buf("/tmp").abs(), + cwd: test_path_buf("/tmp").abs().into(), cli_version: "0.0.0".to_string(), source: codex_app_server_protocol::SessionSource::Cli, can_accept_direct_input: None, @@ -910,7 +910,7 @@ fn sample_thread_start_response() -> ThreadStartResponse { model: "gpt-5.4".to_string(), model_provider: "openai".to_string(), service_tier: None, - cwd: test_path_buf("/tmp").abs(), + cwd: test_path_buf("/tmp").abs().into(), runtime_workspace_roots: Vec::new(), instruction_sources: Vec::new(), approval_policy: codex_app_server_protocol::AskForApproval::OnRequest, diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 76b1db454d..55b7892751 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -546,15 +546,6 @@ fn rollout_path_is_resumable(rollout_path: &Path) -> bool { std::fs::metadata(rollout_path).is_ok_and(|metadata| metadata.is_file() && metadata.len() > 0) } -fn errors_for_cwd(cwd: &Path, response: &SkillsListResponse) -> Vec { - response - .data - .iter() - .find(|entry| entry.cwd.as_path() == cwd) - .map(|entry| entry.errors.clone()) - .unwrap_or_default() -} - #[derive(Debug, Default)] struct InitialHistoryReplayBuffer { retained_lines: VecDeque, diff --git a/codex-rs/tui/src/app/agent_center_tests.rs b/codex-rs/tui/src/app/agent_center_tests.rs index 566b87e567..eee2ead05b 100644 --- a/codex-rs/tui/src/app/agent_center_tests.rs +++ b/codex-rs/tui/src/app/agent_center_tests.rs @@ -415,7 +415,7 @@ async fn live_center_pages_visible_rows_without_wrapping() { ); thread.updated_at -= index as i64; if index >= 10 { - thread.cwd = test_path_buf("/tmp/second-project").abs(); + thread.cwd = test_path_buf("/tmp/second-project").abs().into(); } thread }) @@ -477,7 +477,9 @@ async fn live_center_navigates_sections() { ThreadStatus::Idle, ); thread.updated_at -= index as i64; - thread.cwd = test_path_buf(&format!("/tmp/project-{}", index / 2)).abs(); + thread.cwd = test_path_buf(&format!("/tmp/project-{}", index / 2)) + .abs() + .into(); thread }) .collect(); diff --git a/codex-rs/tui/src/app/agents_overview.rs b/codex-rs/tui/src/app/agents_overview.rs index aff2d056a2..5cbf8cf457 100644 --- a/codex-rs/tui/src/app/agents_overview.rs +++ b/codex-rs/tui/src/app/agents_overview.rs @@ -1256,7 +1256,7 @@ impl App { &mut self, tui: &mut tui::Tui, app_server: &mut AppServerSession, - cwd: Option, + cwd: Option, mut startup_draft: Option<&mut StartupDraftPump>, ) -> Option<(Config, Option)> { if self @@ -1269,17 +1269,12 @@ impl App { ); return None; } - let remote = app_server.uses_remote_workspace(); - let remote_cwd = cwd - .as_ref() - .filter(|_| remote) - .map(AbsolutePathBuf::to_path_buf); - let local_cwd = if remote { - self.config.cwd.to_path_buf() + let (local_cwd, remote_cwd) = if app_server.uses_remote_workspace() { + (self.config.cwd.to_path_buf(), cwd) } else { - cwd.map_or_else( - || self.chat_widget.config_ref().cwd.to_path_buf(), - |cwd| cwd.to_path_buf(), + ( + cwd.unwrap_or_else(|| self.chat_widget.session_cwd().to_path_buf()), + None, ) }; let mut config = match StartupDraftPump::run_with_optional_draft( diff --git a/codex-rs/tui/src/app/agents_overview_action_progress_tests.rs b/codex-rs/tui/src/app/agents_overview_action_progress_tests.rs index 3be55d62cc..8caffb7b85 100644 --- a/codex-rs/tui/src/app/agents_overview_action_progress_tests.rs +++ b/codex-rs/tui/src/app/agents_overview_action_progress_tests.rs @@ -34,7 +34,7 @@ async fn modal_consumes_input_and_finishes_after_input_closes() -> color_eyre::R .expect("materialize task"), )?; let mut thread = server.thread_read(id, /*include_turns*/ false).await?; - thread.cwd = test_path_buf("/tmp/project").abs(); + thread.cwd = test_path_buf("/tmp/project").abs().into(); app.agents_overview.threads.insert(id, Some(thread)); } let threads = app diff --git a/codex-rs/tui/src/app/agents_overview_actions_tests.rs b/codex-rs/tui/src/app/agents_overview_actions_tests.rs index df833a27b2..52e4354f0f 100644 --- a/codex-rs/tui/src/app/agents_overview_actions_tests.rs +++ b/codex-rs/tui/src/app/agents_overview_actions_tests.rs @@ -407,7 +407,7 @@ async fn archiving_selects_the_next_displayed_task() -> Result<()> { &title, ThreadStatus::Idle, ); - thread.cwd = test_path_buf(&format!("/tmp/project-{index}")).abs(); + thread.cwd = test_path_buf(&format!("/tmp/project-{index}")).abs().into(); thread.model = Some(format!("model-{index}")); thread.updated_at = index as i64; app.agents_overview.threads.insert(id, Some(thread.clone())); @@ -611,7 +611,7 @@ async fn external_removals_preserve_adjacent_selection() { if index == 1 { "Other" } else { "Task" }, ThreadStatus::Idle, ); - thread.cwd = test_path_buf(&format!("/tmp/project-{index}")).abs(); + thread.cwd = test_path_buf(&format!("/tmp/project-{index}")).abs().into(); thread.model = Some(format!("model-{index}")); thread.updated_at = index as i64; thread @@ -704,7 +704,7 @@ async fn hiding_tasks_keeps_selection_adjacent_in_display_order() -> Result<()> ThreadStatus::Idle, ); thread.name = Some(format!("{} {index}", thread.preview)); - thread.cwd = test_path_buf(&format!("/tmp/project-{index}")).abs(); + thread.cwd = test_path_buf(&format!("/tmp/project-{index}")).abs().into(); thread.model = Some(format!("model-{index}")); thread.updated_at = index as i64; thread diff --git a/codex-rs/tui/src/app/agents_overview_details.rs b/codex-rs/tui/src/app/agents_overview_details.rs index 8ca7288aee..0eddff0b13 100644 --- a/codex-rs/tui/src/app/agents_overview_details.rs +++ b/codex-rs/tui/src/app/agents_overview_details.rs @@ -17,7 +17,7 @@ use codex_app_server_protocol::ThreadHistoryMode; use codex_app_server_protocol::ThreadItemPayload; use codex_app_server_protocol::ThreadStatus; use codex_protocol::ThreadId; -use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_path_uri::LegacyAppPathString; use ratatui::style::Stylize; use ratatui::text::Line; use std::collections::HashMap; @@ -40,7 +40,7 @@ pub(super) struct AgentsOverviewDetails { pub(super) latest_prompt: Option, pub(super) lines: Vec>, pub(super) usage_lines: Vec>, - pub(super) last_message: Option<(String, AbsolutePathBuf)>, + pub(super) last_message: Option<(String, LegacyAppPathString)>, } pub(super) fn preview_text(text: &str) -> String { diff --git a/codex-rs/tui/src/app/agents_overview_discovery.rs b/codex-rs/tui/src/app/agents_overview_discovery.rs index 5be6dcc594..d5b2161e8d 100644 --- a/codex-rs/tui/src/app/agents_overview_discovery.rs +++ b/codex-rs/tui/src/app/agents_overview_discovery.rs @@ -270,7 +270,7 @@ pub(super) struct HistorySearch { pub(super) fn matches_query(thread: &Thread, query: &str) -> bool { let name = thread.name.as_deref().unwrap_or_default(); - let cwd = thread.cwd.display(); + let cwd = &thread.cwd; format!("{name} {} {cwd}", thread.preview) .to_lowercase() .contains(query) diff --git a/codex-rs/tui/src/app/agents_overview_discovery_tests.rs b/codex-rs/tui/src/app/agents_overview_discovery_tests.rs index f1c41fdcb7..94d4848ec4 100644 --- a/codex-rs/tui/src/app/agents_overview_discovery_tests.rs +++ b/codex-rs/tui/src/app/agents_overview_discovery_tests.rs @@ -342,7 +342,7 @@ async fn overview_local_enter_drops_the_displayed_cloud_list_before_detach() -> "Local saved chat", ThreadStatus::Idle, ); - local_row.cwd = local_session.cwd; + local_row.cwd = local_session.cwd.into(); let cloud_owner = BackendId::new(); let cloud_id = ThreadId::new(); diff --git a/codex-rs/tui/src/app/agents_overview_new.rs b/codex-rs/tui/src/app/agents_overview_new.rs index fef1206945..3cb590b303 100644 --- a/codex-rs/tui/src/app/agents_overview_new.rs +++ b/codex-rs/tui/src/app/agents_overview_new.rs @@ -42,7 +42,7 @@ impl App { &mut self, tui: &mut tui::Tui, app_server: &mut AppServerSession, - cwd: Option, + cwd: Option, ) -> Result { if self.reconnect.offline || self.windows_sandbox_blocks_thread_switch() { return Ok(AppRunControl::Continue); @@ -59,13 +59,10 @@ impl App { StartupDraftSessionAction::NewWhileRunning, )) }); - let mut display_config = self.chat_widget.config_ref().clone(); - if let Some(cwd) = cwd.as_ref() { - display_config.cwd = cwd.clone(); - } draft.apply_settings( - &crate::local_settings::LocalSettings::from(&display_config), - display_config.cwd.as_path(), + &crate::local_settings::LocalSettings::from(self.chat_widget.config_ref()), + cwd.as_deref() + .unwrap_or(&self.chat_widget.session_cwd().to_path_buf()), ); draft.show(tui)?; // Keep the large session-start future off the TUI's stack in dev builds. @@ -97,7 +94,7 @@ impl App { &mut self, tui: &mut tui::Tui, app_server: &mut AppServerSession, - cwd: Option, + cwd: Option, managed_worktree: Option<( codex_worktree::WorktreeManager, codex_worktree::ManagedWorktree, @@ -207,15 +204,16 @@ impl App { .insert(thread_id, selected.profile_id); } if let Some((manager, checkout)) = &managed_worktree { - let result = - if crate::session_resume::cwds_differ(started.session.cwd.as_path(), &checkout.cwd) - { - Err(anyhow::anyhow!( - "The server did not apply the worktree directory." - )) - } else { - manager.bind_thread(&checkout.root, &thread_id.to_string()) - }; + let result = if crate::session_resume::cwds_differ( + &started.session.cwd.to_path_buf(), + &checkout.cwd, + ) { + Err(anyhow::anyhow!( + "The server did not apply the worktree directory." + )) + } else { + manager.bind_thread(&checkout.root, &thread_id.to_string()) + }; if let Err(error) = result { let _ = app_server.thread_unsubscribe(thread_id).await; self.agents_overview_retained_worktree_error(checkout, /*title*/ None, error); @@ -273,7 +271,12 @@ impl App { return; } let Some((config, _)) = self - .agents_overview_session_config(tui, app_server, cwd, /*startup_draft*/ None) + .agents_overview_session_config( + tui, + app_server, + cwd.map(Into::into), + /*startup_draft*/ None, + ) .await else { return; diff --git a/codex-rs/tui/src/app/agents_overview_tests.rs b/codex-rs/tui/src/app/agents_overview_tests.rs index 98e0445bdb..b1c44cf0f0 100644 --- a/codex-rs/tui/src/app/agents_overview_tests.rs +++ b/codex-rs/tui/src/app/agents_overview_tests.rs @@ -721,7 +721,7 @@ pub(in crate::app) fn overview_thread( recency_at: Some(*OVERVIEW_TIMESTAMP), status, path: None, - cwd: test_path_buf("/tmp/project").abs(), + cwd: test_path_buf("/tmp/project").abs().into(), cli_version: "0.0.0".to_string(), source: parent_thread_id.map_or(SessionSource::Cli, |parent_thread_id| { SessionSource::SubAgent(SubAgentSource::ThreadSpawn { @@ -1740,7 +1740,7 @@ async fn worktrees_overview_groups_by_project_or_directory() { title, ThreadStatus::Idle, ); - thread.cwd = AbsolutePathBuf::from_absolute_path(cwd).unwrap(); + thread.cwd = AbsolutePathBuf::from_absolute_path(cwd).unwrap().into(); thread }) .collect::>(); @@ -2036,9 +2036,11 @@ async fn shared_overview_shows_only_root_sessions() { } candidate.updated_at = index; candidate.cwd = if index == 0 { - test_path_buf("/tmp/project-selected").abs() + test_path_buf("/tmp/project-selected").abs().into() } else { - test_path_buf(&format!("/tmp/project-{}", index % 3)).abs() + test_path_buf(&format!("/tmp/project-{}", index % 3)) + .abs() + .into() }; candidate }) @@ -2658,7 +2660,7 @@ async fn overview_cold_resume_honors_working_directory_selection() -> Result<()> .session; assert_eq!( (app.config.cwd.clone(), observed.cwd), - (expected_cwd.clone(), expected_cwd), + (expected_cwd.clone(), expected_cwd.into()), ); app_server.shutdown().await?; } @@ -3925,7 +3927,7 @@ async fn command_center_new_actions_use_selection_and_leave_metadata_text_alone( ); let owner = BackendId::new(); app.backend_registry.observe(owner, id); - target.cwd = test_path_buf("/tmp/checkout/subdir").abs(); + target.cwd = test_path_buf("/tmp/checkout/subdir").abs().into(); app.agents_overview.pins_by_backend = [(crate::backend_id::BackendId::new(), Some(Vec::new()))].into(); let mut view = app.agents_overview_view(vec![target.clone()], Some(id)); @@ -3936,11 +3938,11 @@ async fn command_center_new_actions_use_selection_and_leave_metadata_text_alone( for grouping_index in 0..3 { view.handle_key_event(KeyCode::Char('n').into()); assert!( - matches!(rx.try_recv(), Ok(AppEvent::NewAgentsOverviewSession { backend_id: Some(id), cwd: Some(cwd) }) if id == owner && cwd == target.cwd) + matches!(rx.try_recv(), Ok(AppEvent::NewAgentsOverviewSession { backend_id: Some(id), cwd: Some(cwd) }) if id == owner && cwd.as_path() == target.cwd.as_path()) ); view.handle_key_event(KeyCode::Char('w').into()); assert!( - matches!(rx.try_recv(), Ok(AppEvent::NewAgentsOverviewWorktree { backend_id: Some(id), cwd: Some(cwd) }) if id == owner && cwd == target.cwd) + matches!(rx.try_recv(), Ok(AppEvent::NewAgentsOverviewWorktree { backend_id: Some(id), cwd: Some(cwd) }) if id == owner && cwd.as_path() == target.cwd.as_path()) ); view.handle_key_event(KeyCode::Char('g').into()); if grouping_index == 0 { diff --git a/codex-rs/tui/src/app/agents_overview_view.rs b/codex-rs/tui/src/app/agents_overview_view.rs index 710240629c..f7752f44cb 100644 --- a/codex-rs/tui/src/app/agents_overview_view.rs +++ b/codex-rs/tui/src/app/agents_overview_view.rs @@ -533,7 +533,7 @@ impl AgentsOverviewView { reasoning, Line::default(), Line::from("Project".dim()), - Line::from(row.thread.cwd.display().to_string()), + Line::from(row.thread.cwd.to_string()), ]; lines.extend(row.details.usage_lines.clone()); if let Some(branch) = row @@ -801,7 +801,7 @@ impl BottomPaneView for AgentsOverviewView { if self.agents_keymap.new_task.is_pressed(key) { self.app_event_tx.send(AppEvent::NewAgentsOverviewSession { backend_id: self.selected_row().and_then(|row| row.backend_id), - cwd: self.selected_row().map(|row| row.thread.cwd.clone()), + cwd: self.selected_row().map(|row| row.thread.cwd.to_path_buf()), }); return; } @@ -809,7 +809,9 @@ impl BottomPaneView for AgentsOverviewView { if self.worktrees_enabled { self.app_event_tx.send(AppEvent::NewAgentsOverviewWorktree { backend_id: self.selected_row().and_then(|row| row.backend_id), - cwd: self.selected_row().map(|row| row.thread.cwd.clone()), + cwd: self + .selected_row() + .and_then(|row| row.thread.cwd.to_inferred_abs_path()), }); } return; diff --git a/codex-rs/tui/src/app/app_server_event_targets.rs b/codex-rs/tui/src/app/app_server_event_targets.rs index 7c1406080b..34e923a088 100644 --- a/codex-rs/tui/src/app/app_server_event_targets.rs +++ b/codex-rs/tui/src/app/app_server_event_targets.rs @@ -261,7 +261,7 @@ mod tests { ThreadSettings { disabled_plugin_ids: Vec::new(), environments: None, - cwd: test_path_buf("/tmp/thread-settings").abs(), + cwd: test_path_buf("/tmp/thread-settings").abs().into(), approval_policy: codex_app_server_protocol::AskForApproval::Never, approvals_reviewer: codex_app_server_protocol::ApprovalsReviewer::User, sandbox_policy: codex_app_server_protocol::SandboxPolicy::ReadOnly { diff --git a/codex-rs/tui/src/app/backend_registry.rs b/codex-rs/tui/src/app/backend_registry.rs index 5fea49bfb9..728049d899 100644 --- a/codex-rs/tui/src/app/backend_registry.rs +++ b/codex-rs/tui/src/app/backend_registry.rs @@ -6,6 +6,8 @@ use crate::app_server_session::AppServerStartedThread; use crate::backend_id::BackendId; use codex_app_server_client::AppServerRequestHandle; use codex_protocol::ThreadId; +use codex_utils_path_uri::PathConvention; +use codex_utils_path_uri::Platform; use std::collections::HashMap; use std::collections::HashSet; @@ -64,6 +66,11 @@ impl BackendRegistry { self.connections.remove(&owner); } + pub(super) fn thread_path_convention(&self, thread_id: ThreadId) -> Option { + let handle = self.connections.get(&self.owner(thread_id)?)?; + Platform::from_platform_os(handle.platform_os()).path_convention() + } + pub(super) fn request_handle(&self, owner: BackendId) -> Option { self.connections.get(&owner).cloned() } diff --git a/codex-rs/tui/src/app/background_requests.rs b/codex-rs/tui/src/app/background_requests.rs index bab924254d..bfc796b1f3 100644 --- a/codex-rs/tui/src/app/background_requests.rs +++ b/codex-rs/tui/src/app/background_requests.rs @@ -267,20 +267,24 @@ impl App { /// app-server RPC finishes. User-initiated skills refreshes still use the blocking app command path so /// callers that explicitly asked for fresh skill state do not race ahead of their own refresh. pub(super) fn refresh_startup_skills(&mut self, app_server: &AppServerSession) { - if app_server.thread_params_mode() == crate::ThreadParamsMode::Cloud { + // A remote session refreshes its skills when thread/start supplies its cwd. + if app_server.thread_params_mode() == crate::ThreadParamsMode::Cloud + || (app_server.thread_params_mode() == crate::ThreadParamsMode::Remote + && self.chat_widget.thread_id().is_none()) + { self.skill_load_warnings.startup_complete = true; return; } let request_handle = app_server.request_handle(); let app_event_tx = self.app_event_tx.clone(); - let cwd = self.config.cwd.to_path_buf(); + let cwd = self.chat_widget.session_cwd().clone(); tokio::spawn(async move { let request_id = RequestId::String(format!("startup-skills-list-{}", Uuid::new_v4())); let result = fetch_skills_list( request_handle, request_id, SkillsListParams { - cwds: vec![cwd.clone()], + cwds: vec![cwd.to_path_buf()], force_reload: true, }, ) diff --git a/codex-rs/tui/src/app/config_persistence.rs b/codex-rs/tui/src/app/config_persistence.rs index 9a0fba459b..1e13c977db 100644 --- a/codex-rs/tui/src/app/config_persistence.rs +++ b/codex-rs/tui/src/app/config_persistence.rs @@ -1960,7 +1960,7 @@ enabled = false approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: next_cwd.clone().abs(), + cwd: next_cwd.clone().abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: None, diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index f4f9b9cb59..512781c238 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -265,7 +265,7 @@ impl App { AppEvent::CloseMisalignmentReview => self.chat_widget.show_misalignment_policy_precaution(), AppEvent::SkillsListLoaded { ref cwd, .. } if app_server.thread_params_mode() == crate::ThreadParamsMode::Cloud - || cwds_differ(cwd, self.config.cwd.as_path()) => + || self.chat_widget.session_cwd() != cwd => { self.skill_load_warnings.startup_complete = true; } @@ -1411,15 +1411,14 @@ impl App { // The Cloud preview does not have a skills catalog. AppEvent::CodexOp(AppCommand::ListSkills { .. }) if app_server.thread_params_mode() == crate::ThreadParamsMode::Cloud => {} - AppEvent::CodexOp(AppCommand::ListSkills { cwds, force_reload: true }) + AppEvent::CodexOp(AppCommand::ListSkills { cwd, force_reload: true }) if self.awaiting_side_replay(tui) && let Some(thread_id) = self.active_thread_id && self.side_pair_key(thread_id).is_some() && !self.thread_unavailable(thread_id) => { // Session replay refreshes skill metadata. Let focus paint while that RPC is pending. - let cwd = self.chat_widget.config_ref().cwd.to_path_buf(); - if cwds.contains(&cwd) { + if &cwd == self.chat_widget.session_cwd() { let request_id = Uuid::new_v4(); app_server.pending_side_skills_refresh = Some(request_id); let rpc_id = app_server.next_request_id(); @@ -1429,7 +1428,7 @@ impl App { let result = background_requests::fetch_skills_list( request_handle, rpc_id, - SkillsListParams { cwds, force_reload: true }, + SkillsListParams { cwds: vec![cwd.to_path_buf()], force_reload: true }, ) .await .map_err(|err| format!("{err:#}")); @@ -1661,7 +1660,7 @@ impl App { .await?; } AppEvent::DiffResult(cwd, text) => { - if cwds_differ(&cwd, self.chat_widget.config_ref().cwd.as_path()) { + if &cwd != self.chat_widget.session_cwd() { return Ok(AppRunControl::Continue); } // Clear the in-progress state in the bottom pane @@ -2103,7 +2102,7 @@ impl App { app_server.pending_side_skills_refresh = None; if !self.awaiting_side_replay(tui) && self.current_displayed_thread_id() == Some(thread_id) - && !cwds_differ(&cwd, self.chat_widget.config_ref().cwd.as_path()) + && self.chat_widget.session_cwd() == &cwd { self.handle_skills_list_result( result.map_err(|err| color_eyre::eyre::eyre!(err)), @@ -3482,7 +3481,7 @@ impl App { }; let manager = pending.manager.clone(); let cwd = AbsolutePathBuf::try_from(checkout.cwd.clone())?; - return Box::pin(self.start_agents_overview_session(tui, app_server, Some(cwd), Some((manager, checkout)), /*startup_draft*/ None)).await; + return Box::pin(self.start_agents_overview_session(tui, app_server, Some(cwd.into()), Some((manager, checkout)), /*startup_draft*/ None)).await; } Err(error) => self.add_agents_overview_error(error), } diff --git a/codex-rs/tui/src/app/history_pagination.rs b/codex-rs/tui/src/app/history_pagination.rs index 499cac8f27..ce918c3456 100644 --- a/codex-rs/tui/src/app/history_pagination.rs +++ b/codex-rs/tui/src/app/history_pagination.rs @@ -94,7 +94,8 @@ impl App { store .session .as_ref() - .map_or_else(|| self.config.cwd.clone(), |session| session.cwd.clone()), + .map(|session| session.cwd.to_path_buf()) + .unwrap_or_else(|| self.config.cwd.to_path_buf()), store.turns.clone(), ) }; @@ -203,7 +204,7 @@ impl App { turns: &[Turn], hidden_item_ids: &HashSet<(&str, &str)>, thread_id: ThreadId, - cwd: &AbsolutePathBuf, + cwd: &std::path::Path, visibility: RawReasoningVisibility, ) { if hidden_item_ids.is_empty() { @@ -289,7 +290,7 @@ impl App { turns: &[Turn], hidden_item_ids: &HashSet<(&str, &str)>, thread_id: ThreadId, - cwd: &AbsolutePathBuf, + cwd: &std::path::Path, visibility: RawReasoningVisibility, relocate_split_images: bool, ) -> (TranscriptCells, TranscriptCells) { diff --git a/codex-rs/tui/src/app/loaded_threads.rs b/codex-rs/tui/src/app/loaded_threads.rs index 25ad6a72fd..5977e454fa 100644 --- a/codex-rs/tui/src/app/loaded_threads.rs +++ b/codex-rs/tui/src/app/loaded_threads.rs @@ -158,7 +158,7 @@ mod tests { recency_at: Some(0), status: ThreadStatus::Idle, path: None, - cwd: test_path_buf("/tmp").abs(), + cwd: test_path_buf("/tmp").abs().into(), cli_version: "0.0.0".to_string(), source, can_accept_direct_input: None, diff --git a/codex-rs/tui/src/app/misalignment_policy.rs b/codex-rs/tui/src/app/misalignment_policy.rs index 7eb6f5b58a..22bdcc00f2 100644 --- a/codex-rs/tui/src/app/misalignment_policy.rs +++ b/codex-rs/tui/src/app/misalignment_policy.rs @@ -158,8 +158,9 @@ impl App { explicit_profile .and_then(RuntimePermissionProfileOverride::turn_permission_profile), ); + let cwd = self.chat_widget.session_cwd().to_path_buf(); let Ok((sandbox_policy, permissions)) = - turn_permissions_overrides(permissions_override, config.cwd.as_path()) + turn_permissions_overrides(permissions_override, &cwd) else { self.chat_widget.add_error_message( "Couldn’t continue this chat. Review its latest status before trying again." @@ -167,7 +168,7 @@ impl App { ); return; }; - params.cwd = Some(config.cwd.to_path_buf()); + params.cwd = Some(cwd); params.runtime_workspace_roots = Some(config.permissions.user_visible_workspace_roots().to_vec()); params.approval_policy = Some(config.permissions.approval_policy.value().into()); diff --git a/codex-rs/tui/src/app/owned_transcript_tests.rs b/codex-rs/tui/src/app/owned_transcript_tests.rs index 6b76d69a08..0a2293389b 100644 --- a/codex-rs/tui/src/app/owned_transcript_tests.rs +++ b/codex-rs/tui/src/app/owned_transcript_tests.rs @@ -51,7 +51,7 @@ pub(in crate::app) fn attach_thread(app: &mut App, thread_id: ThreadId) { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/tmp/project").abs(), + cwd: test_path_buf("/tmp/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: None, diff --git a/codex-rs/tui/src/app/reconnect.rs b/codex-rs/tui/src/app/reconnect.rs index bb2f0966b5..c31cf3bde2 100644 --- a/codex-rs/tui/src/app/reconnect.rs +++ b/codex-rs/tui/src/app/reconnect.rs @@ -359,6 +359,7 @@ impl App { ) { self.chat_widget.snapshot_local_images = self.app_server_target.uses_remote_workspace(); self.chat_widget.thread_params_mode = app_server.thread_params_mode(); + self.chat_widget.app_server_path_convention = app_server.path_convention(); self.chat_widget.pending_cloud_turn_settings = app_server.pending_cloud_turn_settings(); self.chat_widget.set_local_worktree_operations( !crate::uses_remote_workspace_or_environment( diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs index 5935131e0d..d56a192ba0 100644 --- a/codex-rs/tui/src/app/session_lifecycle.rs +++ b/codex-rs/tui/src/app/session_lifecycle.rs @@ -485,10 +485,16 @@ impl App { } (started.session, started.turns, true) } - PreparedAttachment::ReplayOnly { thread, read_only } => { + PreparedAttachment::ReplayOnly { + thread, + cwd, + read_only, + } => { external_writer |= read_only == Some(crate::chatwidget::ReadOnlyThread::ExternalWriter); - let mut session = self.session_state_for_thread_read(thread_id, &thread).await; + let mut session = self + .session_state_for_thread_read(thread_id, &thread, cwd) + .await; // Reads have no settings. Keep this cached thread's permissions rather than // inferring them from the conversation that is currently displayed. if let Some(channel) = self.thread_event_channels.get(&thread_id) @@ -555,8 +561,13 @@ impl App { } } let mut store = channel.store.lock().await; - if let Some(settings) = incoming.and_then(|updates| updates.settings.as_ref()) { - super::thread_settings::apply_thread_settings_to_session(&mut session, settings); + if let Some(settings) = incoming.and_then(|updates| updates.settings.as_ref()) + && let Ok(cwd) = crate::app_server_session::decode_thread_cwd( + &settings.cwd, + app_server.path_convention(), + ) + { + super::thread_settings::apply_thread_settings_to_session(&mut session, settings, &cwd); } let live_turn = incoming.filter(|updates| updates.turn_changed).map(|_| { ( @@ -622,6 +633,7 @@ impl App { chat_widget.remote_connection = self.chat_widget.remote_connection.clone(); chat_widget.snapshot_local_images = self.app_server_target.uses_remote_workspace(); chat_widget.thread_params_mode = self.chat_widget.thread_params_mode; + chat_widget.app_server_path_convention = self.chat_widget.app_server_path_convention; chat_widget.pending_cloud_turn_settings = self.chat_widget.pending_cloud_turn_settings.clone(); chat_widget.set_local_worktree_operations(self.chat_widget.local_worktree_operations); diff --git a/codex-rs/tui/src/app/side.rs b/codex-rs/tui/src/app/side.rs index 9d6dc97665..002eca9663 100644 --- a/codex-rs/tui/src/app/side.rs +++ b/codex-rs/tui/src/app/side.rs @@ -983,7 +983,7 @@ impl App { if !enter { self.side_companions .entry(child_thread_id) - .or_insert_with(|| SideCompanion::empty(forked.session.cwd.clone())); + .or_insert_with(|| SideCompanion::empty(forked.session.cwd.to_path_buf())); } let channel = self.ensure_thread_channel(child_thread_id); channel.backend_id = Some(app_server.backend_id()); diff --git a/codex-rs/tui/src/app/side_companion.rs b/codex-rs/tui/src/app/side_companion.rs index 3222ec91ec..b2e641c267 100644 --- a/codex-rs/tui/src/app/side_companion.rs +++ b/codex-rs/tui/src/app/side_companion.rs @@ -14,7 +14,7 @@ use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ThreadItemPayload; use codex_app_server_protocol::TurnStatus; use codex_protocol::items::AsyncUserInputQuestion; -use codex_utils_absolute_path::AbsolutePathBuf; +use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; use std::time::Instant; @@ -59,7 +59,7 @@ impl SideCompanion { .can_scroll_without_refresh(&self.cells, /*live_key*/ None) } - pub(super) fn empty(cwd: AbsolutePathBuf) -> Self { + pub(super) fn empty(cwd: PathBuf) -> Self { Self { display: CapturedSideDisplay { rendered_completion_turn_ids: Default::default(), diff --git a/codex-rs/tui/src/app/side_companion_tests.rs b/codex-rs/tui/src/app/side_companion_tests.rs index ee5c64d294..1907f59037 100644 --- a/codex-rs/tui/src/app/side_companion_tests.rs +++ b/codex-rs/tui/src/app/side_companion_tests.rs @@ -6,7 +6,7 @@ use ratatui::layout::Rect; #[test] fn buffered_answer_requires_a_paint_before_wheel_input() { - let cwd = AbsolutePathBuf::try_from(std::env::current_dir().unwrap()).unwrap(); + let cwd = std::env::current_dir().unwrap(); let mut pane = SideCompanion::empty(cwd); let area = Rect::new( /*x*/ 0, /*y*/ 0, /*width*/ 20, /*height*/ 4, diff --git a/codex-rs/tui/src/app/sidebar_files.rs b/codex-rs/tui/src/app/sidebar_files.rs index 899fcaab2b..8c5b8bf90a 100644 --- a/codex-rs/tui/src/app/sidebar_files.rs +++ b/codex-rs/tui/src/app/sidebar_files.rs @@ -315,7 +315,7 @@ impl App { .as_ref() .is_none_or(|environment| environment.is_server_local); let cwd = if inspect_local_paths { - Some(PathUri::from_abs_path(&session.cwd)) + Some(session.cwd.clone()) } else { session .primary_environment_cwd diff --git a/codex-rs/tui/src/app/startup.rs b/codex-rs/tui/src/app/startup.rs index 44f74d575e..8cea2f977e 100644 --- a/codex-rs/tui/src/app/startup.rs +++ b/codex-rs/tui/src/app/startup.rs @@ -940,6 +940,7 @@ impl App { chat_widget.remote_connection = remote_connection; chat_widget.snapshot_local_images = app_server_target.uses_remote_workspace(); chat_widget.thread_params_mode = app_server.thread_params_mode(); + chat_widget.app_server_path_convention = app_server.path_convention(); chat_widget.pending_cloud_turn_settings = app_server.pending_cloud_turn_settings(); chat_widget.set_local_worktree_operations(!crate::uses_remote_workspace_or_environment( &app_server_target, diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 081322f184..f63cbb439a 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -3234,7 +3234,10 @@ async fn docked_replay_finishes_while_skills_refresh_is_pending() -> Result<()> app.chat_widget.sync_plugin_mentions_config(&app.config); let mut tui = crate::tui::test_support::make_test_tui()?; tui.set_owned_screen(/*owned*/ true)?; - let cwd = app.chat_widget.config_ref().cwd.to_path_buf(); + let mut session = test_thread_session(parent, app.config.cwd.to_path_buf()); + session.cwd = codex_utils_path_uri::PathUri::parse("file:///D:/Workspace")?; + app.chat_widget.handle_thread_session(session); + let cwd = codex_utils_path_uri::PathUri::parse("file:///D:/workspace")?; let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; let endpoint = crate::resolve_remote_addr(&format!("ws://{}", listener.local_addr()?))?; @@ -3268,7 +3271,7 @@ async fn docked_replay_finishes_while_skills_refresh_is_pending() -> Result<()> app.pending_thread_switch_resets = 1; app.app_event_tx .send(AppEvent::CodexOp(AppCommand::list_skills( - vec![cwd.clone()], + cwd.clone(), /*force_reload*/ true, ))); app.app_event_tx @@ -3284,7 +3287,7 @@ async fn docked_replay_finishes_while_skills_refresh_is_pending() -> Result<()> .expect("skills/list should be requested"); assert_eq!( params, - Some(serde_json::json!({"cwds": [cwd], "forceReload": true})) + Some(serde_json::json!({"cwds": [r"D:\workspace"], "forceReload": true})) ); assert!(!app.awaiting_side_replay(&tui)); @@ -7631,7 +7634,7 @@ async fn inactive_thread_started_notification_initializes_replay_session() -> Re recency_at: Some(2), status: codex_app_server_protocol::ThreadStatus::Idle, path: Some(rollout_path.clone()), - cwd: test_path_buf("/tmp/agent").abs(), + cwd: test_path_buf("/tmp/agent").abs().into(), cli_version: "0.0.0".to_string(), source: codex_app_server_protocol::SessionSource::Unknown, can_accept_direct_input: None, @@ -7665,7 +7668,7 @@ async fn inactive_thread_started_notification_initializes_replay_session() -> Re assert_eq!(session.model, "gpt-agent"); assert_eq!(session.model_provider_id, "openai"); assert_eq!(session.approval_policy, primary_session.approval_policy); - assert_eq!(session.cwd.as_path(), test_path_buf("/tmp/agent").as_path()); + 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] @@ -7751,7 +7754,7 @@ async fn inactive_thread_started_notification_preserves_primary_model_when_path_ recency_at: Some(2), status: codex_app_server_protocol::ThreadStatus::Idle, path: None, - cwd: test_path_buf("/tmp/agent").abs(), + cwd: test_path_buf("/tmp/agent").abs().into(), cli_version: "0.0.0".to_string(), source: codex_app_server_protocol::SessionSource::Unknown, can_accept_direct_input: None, @@ -7826,7 +7829,7 @@ async fn thread_read_session_state_does_not_reuse_primary_permission_profile() { recency_at: Some(2), status: codex_app_server_protocol::ThreadStatus::Idle, path: None, - cwd: test_path_buf("/tmp/read").abs(), + cwd: test_path_buf("/tmp/read").abs().into(), cli_version: "0.0.0".to_string(), source: codex_app_server_protocol::SessionSource::Unknown, can_accept_direct_input: None, @@ -7839,19 +7842,19 @@ async fn thread_read_session_state_does_not_reuse_primary_permission_profile() { }; let cold_session = app - .session_state_for_thread_read(read_thread_id, &thread) + .session_state_for_thread_read(read_thread_id, &thread, thread.cwd.to_inferred_path_uri()) .await; assert!(cold_session.read_only_history); app.primary_session_configured = Some(primary_session); let session = app - .session_state_for_thread_read(read_thread_id, &thread) + .session_state_for_thread_read(read_thread_id, &thread, thread.cwd.to_inferred_path_uri()) .await; assert!(session.read_only_history); assert_eq!(session.thread_id, read_thread_id); assert_eq!(session.model, "server-reported-model"); - assert_eq!(session.cwd.as_path(), test_path_buf("/tmp/read").as_path()); + 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()] @@ -8975,7 +8978,7 @@ async fn render_clear_ui_header_after_long_transcript_for_snapshot() -> String { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/tmp/project").abs(), + cwd: test_path_buf("/tmp/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::High), @@ -9719,7 +9722,7 @@ pub(super) fn test_thread_session(thread_id: ThreadId, cwd: PathBuf) -> ThreadSe approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: cwd.abs(), + cwd: cwd.abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: None, @@ -10982,7 +10985,7 @@ async fn backtrack_selection_preserves_selected_prompt_and_requests_branch() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: None, @@ -11058,7 +11061,7 @@ async fn backtrack_selection_preserves_selected_prompt_and_requests_branch() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: None, @@ -12385,7 +12388,7 @@ async fn refreshed_snapshot_session_persists_resumed_turns() { }], )]; let resumed_session = ThreadSessionState { - cwd: test_path_buf("/tmp/refreshed").abs(), + cwd: test_path_buf("/tmp/refreshed").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), ..initial_session.clone() @@ -12457,7 +12460,7 @@ async fn new_session_requests_shutdown_for_previous_conversation() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: None, @@ -13159,7 +13162,7 @@ async fn inactive_thread_settings_notification_updates_cached_collaboration_mode thread_settings: ThreadSettings { disabled_plugin_ids: Vec::new(), environments: None, - cwd: test_absolute_path("/tmp/thread-settings"), + cwd: test_absolute_path("/tmp/thread-settings").into(), approval_policy: AskForApproval::OnRequest, approvals_reviewer: codex_app_server_protocol::ApprovalsReviewer::AutoReview, sandbox_policy: codex_app_server_protocol::SandboxPolicy::ReadOnly { @@ -13239,7 +13242,7 @@ async fn clear_only_ui_reset_preserves_chat_session_state() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/tmp/project").abs(), + cwd: test_path_buf("/tmp/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: None, diff --git a/codex-rs/tui/src/app/tests/background_task_defaults_tests.rs b/codex-rs/tui/src/app/tests/background_task_defaults_tests.rs index 0337fd0fe8..c4d7e1721b 100644 --- a/codex-rs/tui/src/app/tests/background_task_defaults_tests.rs +++ b/codex-rs/tui/src/app/tests/background_task_defaults_tests.rs @@ -363,7 +363,7 @@ async fn command_center_new_reads_server_defaults_for_actual_destination() -> Re app.new_agents_overview_session( &mut tui, &mut server, - explicit_cwd.then(|| destination.path().to_path_buf().abs()), + explicit_cwd.then(|| destination.path().to_path_buf()), ) .await?; assert_eq!( @@ -1191,11 +1191,8 @@ async fn command_center_new_checkout_and_worktree_preserve_source_and_default_br .await?; let mut tui = make_test_tui()?; tui.pause_events(); - let new_session = app.new_agents_overview_session( - &mut tui, - &mut server, - Some(selected.cwd.clone().abs()), - ); + let new_session = + app.new_agents_overview_session(&mut tui, &mut server, Some(selected.cwd.clone())); let size = std::mem::size_of_val(&new_session); assert!( size < 64 * 1024, @@ -1304,7 +1301,7 @@ async fn command_center_new_checkout_and_worktree_preserve_source_and_default_br app.start_agents_overview_session( &mut tui, &mut failed_server, - Some(unused.cwd.clone().abs()), + Some(unused.cwd.clone()), Some((manager.clone(), unused.clone())), /*startup_draft*/ None, ) diff --git a/codex-rs/tui/src/app/tests/new_session_tests.rs b/codex-rs/tui/src/app/tests/new_session_tests.rs index 44eede8383..193f61e019 100644 --- a/codex-rs/tui/src/app/tests/new_session_tests.rs +++ b/codex-rs/tui/src/app/tests/new_session_tests.rs @@ -559,7 +559,7 @@ async fn widget_replacement_preserves_mention_usage_with_history_disabled() -> R /*initial_user_message*/ None, ); app.replace_chat_widget(ChatWidget::new_with_app_event(init)); - app.chat_widget.set_skills_from_response(&skills); + app.chat_widget.set_skills_from_response(skills.clone()); app.chat_widget.insert_str("$status"); app.chat_widget.handle_key_event(KeyCode::Enter.into()); @@ -569,7 +569,7 @@ async fn widget_replacement_preserves_mention_usage_with_history_disabled() -> R /*initial_user_message*/ None, ); app.replace_chat_widget(ChatWidget::new_with_app_event(init)); - app.chat_widget.set_skills_from_response(&skills); + app.chat_widget.set_skills_from_response(skills); app.chat_widget.insert_str("$stat"); insta::assert_snapshot!(normalize_snapshot_paths(render_bottom_popup( &app.chat_widget, diff --git a/codex-rs/tui/src/app/tests/projectless_tests.rs b/codex-rs/tui/src/app/tests/projectless_tests.rs index 8007b7ee5f..476b0f5106 100644 --- a/codex-rs/tui/src/app/tests/projectless_tests.rs +++ b/codex-rs/tui/src/app/tests/projectless_tests.rs @@ -212,7 +212,7 @@ sandbox = "unelevated" std::fs::create_dir(untrusted.path().join(".codex"))?; std::fs::write(untrusted.path().join(".codex/config.toml"), "")?; crate::config_update::write_trusted_project(server.request_handle(), untrusted.path()).await?; - app.new_agents_overview_session(&mut tui, &mut server, Some(untrusted.path().abs())) + app.new_agents_overview_session(&mut tui, &mut server, Some(untrusted.path().to_path_buf())) .await?; server .thread_inject_items( diff --git a/codex-rs/tui/src/app/tests/safety_buffering.rs b/codex-rs/tui/src/app/tests/safety_buffering.rs index 945307db67..e5340a2af1 100644 --- a/codex-rs/tui/src/app/tests/safety_buffering.rs +++ b/codex-rs/tui/src/app/tests/safety_buffering.rs @@ -372,7 +372,7 @@ async fn embedded_session_switch_routes_background_approval_and_restores_draft() app.start_agents_overview_session( &mut tui, &mut server, - Some(cwd.clone().abs()), + Some(cwd.clone()), /*managed_worktree*/ None, /*startup_draft*/ None, ) @@ -387,7 +387,7 @@ async fn embedded_session_switch_routes_background_approval_and_restores_draft() app.start_agents_overview_session( &mut tui, &mut server, - Some(cwd.abs()), + Some(cwd), /*managed_worktree*/ None, /*startup_draft*/ None, ) @@ -547,10 +547,13 @@ stream_max_retries = 0 crate::app_server_session::ResumeModelSettings::PreserveExistingThread, ) .await?; - for cwd in [&app.config.cwd, &other.session.cwd] { + for cwd in [ + app.config.cwd.to_path_buf(), + other.session.cwd.to_path_buf(), + ] { crate::legacy_core::config::set_project_trust_level( app.config.codex_home.as_path(), - cwd.as_path(), + &cwd, codex_protocol::config_types::TrustLevel::Trusted, ) .map_err(std::io::Error::other)?; diff --git a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs index c0ffb0290c..5b0159b485 100644 --- a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs +++ b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs @@ -49,6 +49,35 @@ use tokio_tungstenite::tungstenite::Error as WebSocketError; use tokio_tungstenite::tungstenite::Message; use tokio_tungstenite::tungstenite::error::ProtocolError; +#[tokio::test] +async fn diff_result_matches_the_server_session_cwd() -> Result<()> { + use codex_utils_path_uri::LegacyAppPathString; + use codex_utils_path_uri::PathUri; + + let mut app = make_test_app().await; + let (client, _commands, _events) = + codex_app_server_client::CloudClient::channel(/*capacity*/ 1); + let mut server = AppServerSession::new( + crate::backend_id::BackendId::new(), + codex_app_server_client::AppServerClient::Cloud(client), + crate::ThreadParamsMode::Cloud, + ); + let mut tui = crate::tui::test_support::make_test_tui()?; + let foreign_cwd = if cfg!(windows) { "/repo" } else { r"D:\repo" }; + let cwd = PathUri::try_from(LegacyAppPathString::from_string(foreign_cwd))?; + let mut session = test_thread_session(ThreadId::new(), app.config.cwd.to_path_buf()); + session.cwd = cwd.clone(); + app.chat_widget.handle_thread_session(session); + let stale = AppEvent::DiffResult(app.config.cwd.clone().into(), "old diff".into()); + Box::pin(app.handle_event(&mut tui, &mut server, stale)).await?; + assert!(app.overlay.is_none()); + + let current = AppEvent::DiffResult(cwd, "current diff".into()); + Box::pin(app.handle_event(&mut tui, &mut server, current)).await?; + assert!(app.overlay.is_some()); + Ok(()) +} + #[tokio::test] async fn cloud_skips_skills_refresh_and_ignores_stale_local_result() -> Result<()> { use futures::FutureExt; @@ -74,7 +103,7 @@ async fn cloud_skips_skills_refresh_and_ignores_stale_local_result() -> Result<( for event in [ AppEvent::CodexOp(refresh), AppEvent::SkillsListLoaded { - cwd, + cwd: app.config.cwd.clone().into(), result: Err("stale local skills refresh".into()), }, ] { @@ -401,7 +430,7 @@ async fn cloud_resume_picker_reconciles_admitted_steers() -> Result<()> { "Original", ThreadStatus::Idle, ); - original_thread.cwd = app.config.cwd.clone(); + original_thread.cwd = app.config.cwd.clone().into(); original_thread.turns = vec![test_turn( turn_id, TurnStatus::Completed, @@ -415,7 +444,7 @@ async fn cloud_resume_picker_reconciles_admitted_steers() -> Result<()> { active_flags: Vec::new(), }, ); - other_thread.cwd = app.config.cwd.clone(); + other_thread.cwd = app.config.cwd.clone().into(); other_thread.turns = vec![ongoing_turn]; let (client, mut commands, _server_events) = @@ -5999,18 +6028,18 @@ async fn change_directory_scenario() -> Result<()> { let earlier_skills_requests = recorded_params(&requests, "skills/list"); app.submit_active_thread_op( &mut server, - AppCommand::list_skills(vec![current.clone()], /*force_reload*/ true), + AppCommand::list_skills(current.clone().abs().into(), /*force_reload*/ true), ) .await?; assert_eq!( recorded_params(&requests, "skills/list"), earlier_skills_requests ); - let (cwd, result) = (current.clone(), Err("stale skills".into())); + let (cwd, result) = (current.clone().abs().into(), Err("stale skills".into())); let skills = AppEvent::SkillsListLoaded { cwd, result }; let (cwd, plugins) = (current.clone(), Some(vec![])); let plugins = AppEvent::PluginMentionsLoaded { cwd, plugins }; - let diff = AppEvent::DiffResult(current.clone(), "stale diff".to_string()); + let diff = AppEvent::DiffResult(current.clone().abs().into(), "stale diff".to_string()); let branch = AppEvent::SyncThreadGitBranch { thread_id: original, branch: "stale".to_string(), @@ -6051,7 +6080,7 @@ async fn change_directory_scenario() -> Result<()> { let found = |id: ThreadId| removed.iter().any(|p| p["threadId"] == id.to_string()); assert!([original, child].into_iter().all(found)); let retained = server.thread_read(original, /*include_turns*/ false); - assert_eq!(retained.await?.cwd, current.abs().canonicalize()?); + assert_eq!(retained.await?.cwd, current.abs().canonicalize()?.into()); assert_eq!(app.chat_widget.config_ref().cwd, trusted.clone().abs()); assert!(render_bottom_popup(&app.chat_widget, /*width*/ 80).contains("SessionStart")); app.chat_widget diff --git a/codex-rs/tui/src/app/tests/startup.rs b/codex-rs/tui/src/app/tests/startup.rs index 0b37763914..59a6920ade 100644 --- a/codex-rs/tui/src/app/tests/startup.rs +++ b/codex-rs/tui/src/app/tests/startup.rs @@ -1323,7 +1323,7 @@ async fn known_thread_started_preserves_session_without_reading_unmaterialized_r recency_at: Some(2), status: codex_app_server_protocol::ThreadStatus::Idle, path: Some(temp_dir.path().join("not-yet-materialized.jsonl")), - cwd: session.cwd.clone(), + cwd: session.cwd.clone().into(), cli_version: "0.0.0".to_string(), source: codex_app_server_protocol::SessionSource::Unknown, can_accept_direct_input: None, diff --git a/codex-rs/tui/src/app/tests/startup_defaults_tests.rs b/codex-rs/tui/src/app/tests/startup_defaults_tests.rs index 467d87aba3..5bfc1a8835 100644 --- a/codex-rs/tui/src/app/tests/startup_defaults_tests.rs +++ b/codex-rs/tui/src/app/tests/startup_defaults_tests.rs @@ -702,15 +702,13 @@ async fn fresh_startup_reads_destination_and_cleared_model_uses_catalog() -> Res ) .await?; assert_eq!(started.session.model, selected_model); + let cwd = started.session.cwd.to_path_buf(); assert!( !started .session .permission_profile .file_system_sandbox_policy() - .can_write_local_path_with_cwd( - started.session.cwd.as_path(), - started.session.cwd.as_path() - ) + .can_write_local_path_with_cwd(&cwd, &cwd) ); let starts = recorded_params(&requests, "thread/start"); assert_eq!(starts.len(), if remote { 1 } else { 2 }); diff --git a/codex-rs/tui/src/app/tests/startup_warnings_tests.rs b/codex-rs/tui/src/app/tests/startup_warnings_tests.rs index 47c251339a..da0ee539a6 100644 --- a/codex-rs/tui/src/app/tests/startup_warnings_tests.rs +++ b/codex-rs/tui/src/app/tests/startup_warnings_tests.rs @@ -3,6 +3,8 @@ use super::*; use crate::history_cell::StartupWarningsCell; use codex_app_server_protocol::McpServerStartupFailureReason; +use codex_utils_path_uri::LegacyAppPathString; +use codex_utils_path_uri::PathConvention; use pretty_assertions::assert_eq; use tokio::sync::mpsc::UnboundedReceiver; @@ -268,10 +270,16 @@ async fn startup_skill_load_order_preserves_runtime_error_recurrence() -> Result let (mut app, mut events, _op_rx) = make_test_app_with_channels().await; let mut tui = crate::tui::test_support::make_test_tui()?; let mut server = start_config_write_test_app_server(&app).await?; - let cwd = app.config.cwd.to_path_buf(); + let server_cwd = r"/\repo"; + let cwd = + LegacyAppPathString::from_string(server_cwd).to_path_uri(PathConvention::Posix)?; + let mut session = test_thread_session(ThreadId::new(), app.config.cwd.to_path_buf()); + session.cwd = cwd.clone(); + app.chat_widget.app_server_path_convention = Some(PathConvention::Posix); + app.chat_widget.handle_thread_session_quiet(session); let response = SkillsListResponse { data: vec![codex_app_server_protocol::SkillsListEntry { - cwd: cwd.clone(), + cwd: PathBuf::from(server_cwd), skills: vec![], errors: vec![SkillErrorInfo { path: PathBuf::from("bad/SKILL.md"), diff --git a/codex-rs/tui/src/app/thread_attachment.rs b/codex-rs/tui/src/app/thread_attachment.rs index cee4ce8378..6e9867bdd1 100644 --- a/codex-rs/tui/src/app/thread_attachment.rs +++ b/codex-rs/tui/src/app/thread_attachment.rs @@ -26,6 +26,7 @@ pub(crate) enum PreparedAttachment { Live(Box), ReplayOnly { thread: Box, + cwd: Option, read_only: Option, }, } @@ -247,8 +248,15 @@ pub(super) async fn prepare( "Agent thread {thread_id} is not yet available for replay or live attach." )); } + let convention = app_server.path_convention(); + let cwd = match crate::app_server_session::decode_thread_cwd(&thread.cwd, convention) { + Ok(cwd) => Some(cwd), + Err(error) if convention.is_some() => return Err(error.into()), + Err(_) => None, + }; Ok(PreparedAttachment::ReplayOnly { thread: Box::new(thread), + cwd, read_only: if crate::session_start::is_archived_session_error( &resume_err, thread_id, diff --git a/codex-rs/tui/src/app/thread_events.rs b/codex-rs/tui/src/app/thread_events.rs index c65182c129..2159cadd17 100644 --- a/codex-rs/tui/src/app/thread_events.rs +++ b/codex-rs/tui/src/app/thread_events.rs @@ -763,7 +763,7 @@ mod tests { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: cwd.abs(), + cwd: cwd.abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: None, diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rs index f1a0b5fc6a..79636de83c 100644 --- a/codex-rs/tui/src/app/thread_routing.rs +++ b/codex-rs/tui/src/app/thread_routing.rs @@ -12,6 +12,7 @@ use codex_app_server_protocol::ThreadStartedNotification; use codex_app_server_protocol::TurnInterruptParams; use codex_app_server_protocol::TurnInterruptResponse; use codex_app_server_protocol::WarningNotification; +use codex_utils_path_uri::PathUri; // Leave time for side-thread cleanup and unsubscribe inside the two-second exit budget. const REALTIME_STOP_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 1); @@ -321,7 +322,7 @@ impl App { self.sync_side_thread_ui(); } - pub(super) async fn thread_cwd(&self, thread_id: ThreadId) -> Option { + pub(super) async fn thread_cwd(&self, thread_id: ThreadId) -> Option { let channel = self.thread_event_channels.get(&thread_id)?; let store = channel.store.lock().await; store.session.as_ref().map(|session| session.cwd.clone()) @@ -386,6 +387,7 @@ impl App { cwd: self .thread_cwd(thread_id) .await + .and_then(|cwd| cwd.to_abs_path().ok()) .unwrap_or_else(|| self.config.cwd.clone()), changes: self .thread_file_change_changes(thread_id, ¶ms.turn_id, ¶ms.item_id) @@ -854,18 +856,15 @@ impl App { }); Ok(true) } - AppCommand::ListSkills { cwds, force_reload } => { + AppCommand::ListSkills { cwd, force_reload } => { // A queued refresh can outlive the workspace it was requested for. - if !cwds - .iter() - .any(|cwd| cwd == self.chat_widget.config_ref().cwd.as_path()) - { + if self.chat_widget.session_cwd() != cwd { return Ok(true); } self.handle_skills_list_result( app_server .skills_list(codex_app_server_protocol::SkillsListParams { - cwds: cwds.clone(), + cwds: vec![cwd.to_path_buf()], force_reload: *force_reload, }) .await, @@ -1461,8 +1460,13 @@ impl App { .clone_from(¬ification.thread.reasoning_effort); session.thread_name = notification.thread.name.clone(); session.model_provider_id = notification.thread.model_provider.clone(); - session - .set_cwd_retargeting_implicit_runtime_workspace_root(notification.thread.cwd.clone()); + session.set_cwd_retargeting_implicit_runtime_workspace_root( + crate::app_server_session::decode_thread_cwd( + ¬ification.thread.cwd, + self.backend_registry.thread_path_convention(thread_id), + ) + .ok()?, + ); let rollout_path = notification.thread.path.clone(); if let Some(model) = ¬ification.thread.model { session.model = model.clone(); @@ -2071,8 +2075,7 @@ impl App { #[allow(clippy::too_many_arguments)] pub(super) fn handle_skills_list_response(&mut self, response: SkillsListResponse) { - let cwd = self.chat_widget.config_ref().cwd.clone(); - let errors = errors_for_cwd(&cwd, &response); + let errors = self.chat_widget.set_skills_from_response(response); let errors = self.skill_load_warnings.newly_active_errors(&errors); let warnings = skill_load_warning_messages(&errors); if self.skill_load_warnings.startup_complete { @@ -2087,7 +2090,7 @@ impl App { ), ))); } - self.chat_widget.handle_skills_list_response(response); + self.chat_widget.refresh_plugin_mentions(); } fn startup_request_may_open_protected_view(&self, request: &ServerRequest) -> bool { diff --git a/codex-rs/tui/src/app/thread_session_state.rs b/codex-rs/tui/src/app/thread_session_state.rs index 40bd9d9f9b..dde09a09b5 100644 --- a/codex-rs/tui/src/app/thread_session_state.rs +++ b/codex-rs/tui/src/app/thread_session_state.rs @@ -74,6 +74,7 @@ impl App { &self, thread_id: ThreadId, thread: &Thread, + cwd: Option, ) -> ThreadSessionState { let permission_profile = self.current_permission_profile(); let active_permission_profile = self.current_active_permission_profile(); @@ -108,7 +109,9 @@ impl App { approvals_reviewer: self.config.approvals_reviewer, permission_profile: permission_profile.clone(), active_permission_profile: active_permission_profile.clone(), - cwd: thread.cwd.clone(), + cwd: cwd + .clone() + .unwrap_or_else(|| self.config.cwd.clone().into()), runtime_workspace_roots: self.config.workspace_roots.clone(), instruction_source_paths: Vec::new(), reasoning_effort: self.chat_widget.current_reasoning_effort(), @@ -129,7 +132,9 @@ impl App { session.daybreak_enabled = thread.daybreak_enabled.unwrap_or(false); session.thread_name = thread.name.clone(); session.model_provider_id = thread.model_provider.clone(); - session.set_cwd_retargeting_implicit_runtime_workspace_root(thread.cwd.clone()); + if let Some(cwd) = cwd { + session.set_cwd_retargeting_implicit_runtime_workspace_root(cwd); + } session.permission_profile = permission_profile; session.active_permission_profile = active_permission_profile; session.instruction_source_paths = Vec::new(); @@ -200,7 +205,7 @@ mod tests { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: cwd.abs(), + cwd: cwd.abs().into(), runtime_workspace_roots: vec![cwd.abs()], instruction_source_paths: Vec::new(), reasoning_effort: None, @@ -452,7 +457,7 @@ mod tests { recency_at: Some(2), status: codex_app_server_protocol::ThreadStatus::Idle, path: None, - cwd: test_path_buf("/tmp/read").abs(), + cwd: test_path_buf("/tmp/read").abs().into(), cli_version: "0.0.0".to_string(), source: codex_app_server_protocol::SessionSource::Unknown, can_accept_direct_input: None, @@ -468,7 +473,11 @@ mod tests { app.chat_widget.handle_thread_session(primary_session); let session = app - .session_state_for_thread_read(read_thread_id, &read_thread) + .session_state_for_thread_read( + read_thread_id, + &read_thread, + read_thread.cwd.to_inferred_path_uri(), + ) .await; assert_eq!( diff --git a/codex-rs/tui/src/app/thread_settings.rs b/codex-rs/tui/src/app/thread_settings.rs index f33597b493..d7a26bdcc8 100644 --- a/codex-rs/tui/src/app/thread_settings.rs +++ b/codex-rs/tui/src/app/thread_settings.rs @@ -215,19 +215,25 @@ impl App { thread_id: ThreadId, settings: &ThreadSettings, ) { + let Ok(cwd) = crate::app_server_session::decode_thread_cwd( + &settings.cwd, + self.backend_registry.thread_path_convention(thread_id), + ) else { + return; + }; if let Some(blank) = self.agents_overview.blank_sessions.get_mut(&thread_id) { - apply_thread_settings_to_session(&mut blank.session, settings); + apply_thread_settings_to_session(&mut blank.session, settings, &cwd); } if self.primary_thread_id == Some(thread_id) && let Some(session) = self.primary_session_configured.as_mut() { - apply_thread_settings_to_session(session, settings); + apply_thread_settings_to_session(session, settings, &cwd); } if let Some(channel) = self.thread_event_channels.get(&thread_id) { let mut store = channel.store.lock().await; if let Some(session) = store.session.as_mut() { - apply_thread_settings_to_session(session, settings); + apply_thread_settings_to_session(session, settings, &cwd); } } } @@ -276,6 +282,7 @@ impl App { pub(super) fn apply_thread_settings_to_session( session: &mut ThreadSessionState, settings: &ThreadSettings, + cwd: &codex_utils_path_uri::PathUri, ) { if settings.collaboration_mode.mode == ModeKind::Default { session.model = settings.model.clone(); @@ -294,7 +301,7 @@ pub(super) fn apply_thread_settings_to_session( session.primary_environment_cwd = crate::session_state::primary_environment_cwd(environments); } - session.set_cwd_retargeting_implicit_runtime_workspace_root(settings.cwd.clone()); + session.set_cwd_retargeting_implicit_runtime_workspace_root(cwd.clone()); let mut collaboration_mode = settings.collaboration_mode.clone(); collaboration_mode .settings diff --git a/codex-rs/tui/src/app/transcript_export.rs b/codex-rs/tui/src/app/transcript_export.rs index 00775bba50..f0cafead5a 100644 --- a/codex-rs/tui/src/app/transcript_export.rs +++ b/codex-rs/tui/src/app/transcript_export.rs @@ -126,7 +126,7 @@ pub(super) async fn load_export_transcript( } else { cells.extend(thread_items_to_transcript_cells( Some(thread_id), - &thread.cwd, + thread.cwd.as_path(), [item], visibility, config, diff --git a/codex-rs/tui/src/app/working_directory.rs b/codex-rs/tui/src/app/working_directory.rs index 7a3a7966fb..1c5bfabdcb 100644 --- a/codex-rs/tui/src/app/working_directory.rs +++ b/codex-rs/tui/src/app/working_directory.rs @@ -493,7 +493,7 @@ impl App { == config.permissions.active_permission_profile() }; if session.thread_id == thread_id - || crate::session_resume::cwds_differ(session.cwd.as_path(), cwd.as_path()) + || crate::session_resume::cwds_differ(&session.cwd.to_path_buf(), cwd.as_path()) || session.runtime_workspace_roots != config.workspace_roots || !permissions_match { diff --git a/codex-rs/tui/src/app_command.rs b/codex-rs/tui/src/app_command.rs index fe69981dd0..3bb5d5ebdc 100644 --- a/codex-rs/tui/src/app_command.rs +++ b/codex-rs/tui/src/app_command.rs @@ -20,6 +20,7 @@ use codex_protocol::models::ActivePermissionProfile; use codex_protocol::models::PermissionProfile; use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig; use codex_protocol::request_permissions::RequestPermissionsResponse; +use codex_utils_path_uri::PathUri; use serde::Serialize; use serde::Serializer; use serde_json::Value; @@ -188,7 +189,7 @@ pub(crate) enum AppCommand { }, ReloadUserConfig, ListSkills { - cwds: Vec, + cwd: PathUri, force_reload: bool, }, Compact, @@ -357,8 +358,8 @@ impl AppCommand { Self::ReloadUserConfig } - pub(crate) fn list_skills(cwds: Vec, force_reload: bool) -> Self { - Self::ListSkills { cwds, force_reload } + pub(crate) fn list_skills(cwd: PathUri, force_reload: bool) -> Self { + Self::ListSkills { cwd, force_reload } } pub(crate) fn compact() -> Self { diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 95b3a70f86..e49a439619 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -322,7 +322,7 @@ pub(crate) struct CapturedSideDisplay { pub(crate) status_line: Option, pub(crate) work: Option, pub(crate) last_completed_agent_message: Option<(String, String)>, - pub(crate) cwd: AbsolutePathBuf, + pub(crate) cwd: PathBuf, pub(crate) visualizations: Option, } @@ -402,7 +402,7 @@ pub(crate) enum AppEvent { /// Create an empty thread from the command center. NewAgentsOverviewSession { backend_id: Option, - cwd: Option, + cwd: Option, }, /// Update the agents overview after a background thread listing finishes. AgentsOverviewThreadsLoaded { @@ -1086,7 +1086,7 @@ pub(crate) enum AppEvent { }, /// Result of computing a `/diff` command. - DiffResult(PathBuf, String), + DiffResult(PathUri, String), /// Open the app link view in the bottom pane. OpenAppLink { @@ -1379,7 +1379,7 @@ pub(crate) enum AppEvent { /// command path because those callers expect the visible skill state to be current when their command /// completes. SkillsListLoaded { - cwd: PathBuf, + cwd: PathUri, result: Result, }, @@ -1387,7 +1387,7 @@ pub(crate) enum AppEvent { SideReplaySkillsLoaded { request_id: Uuid, thread_id: ThreadId, - cwd: PathBuf, + cwd: PathUri, result: Result, }, diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs index 3c98fb3aae..db4c64e4c1 100644 --- a/codex-rs/tui/src/app_server_session.rs +++ b/codex-rs/tui/src/app_server_session.rs @@ -166,7 +166,11 @@ use codex_protocol::permissions::FileSystemSandboxPolicy; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::SubAgentSource; use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_path_uri::LegacyAppPathString; +use codex_utils_path_uri::LegacyAppPathStringError; +use codex_utils_path_uri::PathConvention; use codex_utils_path_uri::PathUri; +use codex_utils_path_uri::Platform; use color_eyre::eyre::Result; use color_eyre::eyre::WrapErr; use futures::FutureExt; @@ -617,6 +621,10 @@ pub(crate) enum CloudThreadStart<'a> { } impl AppServerSession { + pub(crate) fn path_convention(&self) -> Option { + Platform::from_platform_os(self.request_handle.platform_os()).path_convention() + } + /// Platform of the app-server process, not necessarily its executor. pub(crate) fn app_server_platform_family(&self) -> Option<&str> { self.connection_owner @@ -1248,6 +1256,7 @@ impl AppServerSession { local_settings, config, self.thread_params_mode(), + self.path_convention(), ) .await?; if let Some(permissions) = selected_permissions { @@ -1625,6 +1634,7 @@ impl AppServerSession { local_settings, &config, self.thread_params_mode(), + self.path_convention(), ) .await?; if let Some(permissions) = selected_permissions { @@ -2405,9 +2415,14 @@ pub(crate) async fn start_thread_with_request_handle( .map_err(|err| { bootstrap_request_error("thread/start failed during TUI bootstrap", err) })?; - let mut started = - started_thread_from_start_response(response, local_settings, &config, thread_params_mode) - .await?; + let mut started = started_thread_from_start_response( + response, + local_settings, + &config, + thread_params_mode, + Platform::from_platform_os(request_handle.platform_os()).path_convention(), + ) + .await?; started.task_tools_available = task_tools_available; Ok(started) } @@ -2953,6 +2968,7 @@ async fn started_thread_from_start_response( local_settings: &LocalSettings, config: &Config, thread_params_mode: ThreadParamsMode, + cwd_convention: Option, ) -> Result { let blocks_direct_input = thread_blocks_direct_input(&response.thread); let session = thread_session_state_from_thread_start_response( @@ -2960,6 +2976,7 @@ async fn started_thread_from_start_response( local_settings, config, thread_params_mode, + cwd_convention, ) .await .map_err(color_eyre::eyre::Report::msg)?; @@ -2974,16 +2991,13 @@ async fn started_thread_from_start_response( async fn started_thread_from_resume_response( response: ThreadResumeResponse, local_settings: &LocalSettings, - thread_params_mode: ThreadParamsMode, + cwd_convention: Option, ) -> Result { let blocks_direct_input = thread_blocks_direct_input(&response.thread); - let session = thread_session_state_from_thread_resume_response( - &response, - local_settings, - thread_params_mode, - ) - .await - .map_err(color_eyre::eyre::Report::msg)?; + let session = + thread_session_state_from_thread_resume_response(&response, local_settings, cwd_convention) + .await + .map_err(color_eyre::eyre::Report::msg)?; Ok(AppServerStartedThread { session, turns: response.thread.turns, @@ -2997,6 +3011,7 @@ async fn started_thread_from_fork_response( local_settings: &LocalSettings, config: &Config, thread_params_mode: ThreadParamsMode, + cwd_convention: Option, ) -> Result { let blocks_direct_input = thread_blocks_direct_input(&response.thread); let session = thread_session_state_from_thread_fork_response( @@ -3004,6 +3019,7 @@ async fn started_thread_from_fork_response( local_settings, config, thread_params_mode, + cwd_convention, ) .await .map_err(color_eyre::eyre::Report::msg)?; @@ -3020,6 +3036,7 @@ async fn thread_session_state_from_thread_start_response( local_settings: &LocalSettings, config: &Config, thread_params_mode: ThreadParamsMode, + cwd_convention: Option, ) -> Result { let permission_profile = display_permission_profile_from_thread_response( &response.sandbox, @@ -3040,7 +3057,7 @@ async fn thread_session_state_from_thread_start_response( response.approvals_reviewer.to_core(), permission_profile, response.active_permission_profile.clone().map(Into::into), - response.cwd.clone(), + decode_thread_cwd(&response.cwd, cwd_convention).map_err(|err| err.to_string())?, response.runtime_workspace_roots.clone(), response.instruction_source_path_uris(), response.reasoning_effort.clone(), @@ -3057,7 +3074,7 @@ async fn thread_session_state_from_thread_start_response( async fn thread_session_state_from_thread_resume_response( response: &ThreadResumeResponse, local_settings: &LocalSettings, - _thread_params_mode: ThreadParamsMode, + cwd_convention: Option, ) -> Result { // The server owns restored rules. This legacy projection is for display only; // normal turns do not send it back as an execution override. @@ -3078,7 +3095,7 @@ async fn thread_session_state_from_thread_resume_response( response.approvals_reviewer.to_core(), permission_profile, response.active_permission_profile.clone().map(Into::into), - response.cwd.clone(), + decode_thread_cwd(&response.cwd, cwd_convention).map_err(|err| err.to_string())?, response.runtime_workspace_roots.clone(), response.instruction_source_path_uris(), response.reasoning_effort.clone(), @@ -3095,6 +3112,7 @@ async fn thread_session_state_from_thread_fork_response( local_settings: &LocalSettings, config: &Config, thread_params_mode: ThreadParamsMode, + cwd_convention: Option, ) -> Result { let permission_profile = display_permission_profile_from_thread_response( &response.sandbox, @@ -3115,7 +3133,7 @@ async fn thread_session_state_from_thread_fork_response( response.approvals_reviewer.to_core(), permission_profile, response.active_permission_profile.clone().map(Into::into), - response.cwd.clone(), + decode_thread_cwd(&response.cwd, cwd_convention).map_err(|err| err.to_string())?, response.runtime_workspace_roots.clone(), response.instruction_source_path_uris(), response.reasoning_effort.clone(), @@ -3151,6 +3169,16 @@ fn display_permission_profile_from_thread_response( } } +pub(crate) fn decode_thread_cwd( + cwd: &LegacyAppPathString, + convention: Option, +) -> Result { + match convention { + Some(convention) => cwd.to_path_uri(convention), + None => PathUri::try_from(cwd.clone()), + } +} + #[expect( clippy::too_many_arguments, reason = "session mapping keeps explicit fields" @@ -3168,7 +3196,7 @@ async fn thread_session_state_from_thread_response( approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer, permission_profile: PermissionProfile, active_permission_profile: Option, - cwd: AbsolutePathBuf, + cwd: PathUri, runtime_workspace_roots: Vec, instruction_source_paths: Vec, reasoning_effort: Option, @@ -3962,7 +3990,7 @@ mod tests { started.session.permission_profile.network_sandbox_policy(), started.session.model.as_str(), started.session.approval_policy, - started.session.cwd.as_path(), + started.session.cwd.to_path_buf().as_path(), ), ( NetworkSandboxPolicy::Restricted, @@ -5131,7 +5159,7 @@ mod tests { recency_at: Some(2), status: ThreadStatus::Idle, path: None, - cwd: test_path_buf("/tmp/project").abs(), + cwd: test_path_buf("/tmp/project").abs().into(), cli_version: "0.0.0".to_string(), source: codex_app_server_protocol::SessionSource::Cli, can_accept_direct_input: None, @@ -5177,7 +5205,7 @@ mod tests { model: "gpt-5.5".to_string(), model_provider: "openai".to_string(), service_tier: None, - cwd: test_path_buf("/tmp/project").abs(), + 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(), @@ -5210,7 +5238,7 @@ mod tests { let started = started_thread_from_resume_response( response.clone(), &LocalSettings::from(&config), - ThreadParamsMode::Remote, + /*cwd_convention*/ None, ) .await .expect("resume response should map"); @@ -5264,7 +5292,7 @@ mod tests { let started = started_thread_from_resume_response( response.clone(), &LocalSettings::from(&embedded_config), - ThreadParamsMode::Embedded, + /*cwd_convention*/ None, ) .await .expect("embedded resume response should map"); @@ -5273,14 +5301,24 @@ mod tests { let mut thread = response.thread.clone(); let mut empty_roots_response = response; empty_roots_response.runtime_workspace_roots = Vec::new(); + let server_cwd = r"/\repo"; + empty_roots_response.cwd = LegacyAppPathString::from_string(server_cwd); let started = started_thread_from_resume_response( empty_roots_response, &LocalSettings::from(&config), - ThreadParamsMode::Remote, + Some(PathConvention::Posix), ) .await .expect("resume response should map"); assert_eq!(started.session.runtime_workspace_roots, Vec::new()); + assert_eq!( + started.session.cwd.infer_path_convention(), + Some(PathConvention::Posix) + ); + assert_eq!( + started.session.cwd.inferred_native_path_string(), + server_cwd + ); // Cloud can filter every item in its newest page while older prompts remain. thread.history_mode = ThreadHistoryMode::Paginated; @@ -5419,7 +5457,7 @@ mod tests { codex_protocol::config_types::ApprovalsReviewer::User, PermissionProfile::read_only(), /*active_permission_profile*/ None, - test_path_buf("/tmp/project").abs(), + test_path_buf("/tmp/project").abs().into(), Vec::new(), Vec::new(), /*reasoning_effort*/ None, @@ -5455,7 +5493,7 @@ mod tests { codex_protocol::config_types::ApprovalsReviewer::User, PermissionProfile::read_only(), /*active_permission_profile*/ None, - test_path_buf("/tmp/project").abs(), + test_path_buf("/tmp/project").abs().into(), Vec::new(), Vec::new(), /*reasoning_effort*/ None, diff --git a/codex-rs/tui/src/app_server_session/history.rs b/codex-rs/tui/src/app_server_session/history.rs index 3c8419619f..c66718a61c 100644 --- a/codex-rs/tui/src/app_server_session/history.rs +++ b/codex-rs/tui/src/app_server_session/history.rs @@ -513,7 +513,7 @@ fn rendered_history_rows( }; thread_items_to_transcript_cells( Some(thread_id), - &thread.cwd, + thread.cwd.as_path(), items.into_iter().map(|(_, item)| item), visibility, Some(config), diff --git a/codex-rs/tui/src/app_server_session/rollout_history.rs b/codex-rs/tui/src/app_server_session/rollout_history.rs index ce014c5761..2948a3c87c 100644 --- a/codex-rs/tui/src/app_server_session/rollout_history.rs +++ b/codex-rs/tui/src/app_server_session/rollout_history.rs @@ -92,7 +92,7 @@ impl AppServerSession { config.approvals_reviewer, config.permissions.permission_profile().clone(), config.permissions.active_permission_profile(), - thread.cwd.clone(), + super::decode_thread_cwd(&thread.cwd, self.path_convention())?, config.workspace_roots.clone(), Vec::new(), thread.reasoning_effort, @@ -199,9 +199,12 @@ impl AppServerSession { HistoryHydrationScope::Initial, ) .await?; - let mut started = - started_thread_from_resume_response(response, local_settings, ThreadParamsMode::Cloud) - .await?; + let mut started = started_thread_from_resume_response( + response, + local_settings, + /*cwd_convention*/ None, + ) + .await?; scoped.commit_prepared_resume().await.map_err(|err| { bootstrap_request_error("thread/resume failed during TUI bootstrap", err) })?; @@ -346,12 +349,9 @@ impl AppServerSession { let fork_parent_title = self .fork_parent_title_from_app_server(response.thread.forked_from_id.as_deref()) .await; - let mut started = started_thread_from_resume_response( - response, - local_settings, - self.thread_params_mode(), - ) - .await?; + let mut started = + started_thread_from_resume_response(response, local_settings, self.path_convention()) + .await?; started.session.fork_parent_title = fork_parent_title; if self.task_tools_available(thread_id) { self.remember_task_tool_thread(thread_id); diff --git a/codex-rs/tui/src/app_server_session/workspace_roots_tests.rs b/codex-rs/tui/src/app_server_session/workspace_roots_tests.rs index 5a22921782..54072405b1 100644 --- a/codex-rs/tui/src/app_server_session/workspace_roots_tests.rs +++ b/codex-rs/tui/src/app_server_session/workspace_roots_tests.rs @@ -81,7 +81,7 @@ stream_max_retries = 0 app_server.remote_cwd_override = Some(remote_cwd.to_path_buf()); let started = app_server.start_thread(&client_config).await?; let thread_id = started.session.thread_id; - assert_eq!(started.session.cwd, remote_cwd); + assert_eq!(started.session.cwd, remote_cwd.clone().into()); assert_eq!(started.session.runtime_workspace_roots, expected_roots); let (mut chat, _sender, _events, _commands) = @@ -178,7 +178,7 @@ stream_max_retries = 0 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); + assert_eq!(started.session.cwd, default_cwd.clone().into()); assert_eq!(started.session.runtime_workspace_roots, vec![default_cwd]); app_server.shutdown().await?; Ok(()) diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 49fc5164bb..d92c94f582 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -102,7 +102,6 @@ use codex_app_server_protocol::ReviewTarget; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequest; use codex_app_server_protocol::SkillMetadata; -use codex_app_server_protocol::SkillsListResponse; use codex_app_server_protocol::ThreadGoal as AppThreadGoal; use codex_app_server_protocol::ThreadGoalStatus as AppThreadGoalStatus; use codex_app_server_protocol::ThreadItemPayload; @@ -150,6 +149,7 @@ use codex_protocol::request_permissions::RequestPermissionsEvent; use codex_protocol::user_input::ByteRange; use codex_protocol::user_input::TextElement; use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_path_uri::PathConvention; use codex_utils_path_uri::PathUri; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; @@ -576,6 +576,7 @@ pub(crate) struct ChatWidget { pub(crate) initial_user_message: Option, status_account_display: Option, pub(crate) remote_connection: Option, + pub(crate) app_server_path_convention: Option, statusline_read: Option, pub(crate) statusline_disconnected: bool, /// Remote app servers cannot read image paths on the TUI host. @@ -752,8 +753,8 @@ pub(crate) struct ChatWidget { feedback: codex_feedback::CodexFeedback, // Current session rollout path (if known) current_rollout_path: Option, - // Current working directory (if known) - current_cwd: Option, + // Working directory of the displayed session. + current_cwd: PathUri, primary_environment_cwd: Option, // App-server-backed command runner for status-line workspace metadata lookups. workspace_command_runner: Option, @@ -1880,7 +1881,7 @@ impl ChatWidget { fn refresh_skills_for_current_cwd(&mut self, force_reload: bool) { self.submit_op(AppCommand::list_skills( - vec![self.config.cwd.to_path_buf()], + self.session_cwd().clone(), force_reload, )); } @@ -1961,11 +1962,6 @@ impl ChatWidget { } } - fn on_list_skills(&mut self, ev: SkillsListResponse) { - self.set_skills_from_response(&ev); - self.refresh_plugin_mentions(); - } - pub(crate) fn refresh_plugin_mentions(&mut self) { if !self.config.features.enabled(Feature::Plugins) { self.bottom_pane.set_plugin_mentions(/*plugins*/ None); diff --git a/codex-rs/tui/src/chatwidget/constructor.rs b/codex-rs/tui/src/chatwidget/constructor.rs index 3fd5b570e8..ea6b13cb95 100644 --- a/codex-rs/tui/src/chatwidget/constructor.rs +++ b/codex-rs/tui/src/chatwidget/constructor.rs @@ -69,7 +69,7 @@ impl ChatWidget { let header = Self::placeholder_session_header_cell(&config); let active_cell = Some(header); - let current_cwd = Some(config.cwd.to_path_buf()); + let current_cwd = PathUri::from_abs_path(&config.cwd); let effective_service_tier = crate::service_tier_resolution::effective_service_tier( &config, &local_settings.notices, @@ -148,6 +148,7 @@ impl ChatWidget { initial_user_message, status_account_display, remote_connection: None, + app_server_path_convention: None, statusline_read: None, statusline_disconnected: false, snapshot_local_images: false, diff --git a/codex-rs/tui/src/chatwidget/input_submission.rs b/codex-rs/tui/src/chatwidget/input_submission.rs index a2da2d3461..0a34081f74 100644 --- a/codex-rs/tui/src/chatwidget/input_submission.rs +++ b/codex-rs/tui/src/chatwidget/input_submission.rs @@ -512,7 +512,7 @@ impl ChatWidget { cloud_submission, client_user_message_id.clone(), items, - self.config.cwd.to_path_buf(), + self.session_cwd().to_path_buf(), AskForApproval::from(self.config.permissions.approval_policy.value()), active_permission_profile, effective_mode.model().to_string(), diff --git a/codex-rs/tui/src/chatwidget/permission_discovery.rs b/codex-rs/tui/src/chatwidget/permission_discovery.rs index 9ad6179e17..27c6c04538 100644 --- a/codex-rs/tui/src/chatwidget/permission_discovery.rs +++ b/codex-rs/tui/src/chatwidget/permission_discovery.rs @@ -164,7 +164,7 @@ impl ChatWidget { self.permission_popup_request_id = Some(request_id); self.app_event_tx.send(AppEvent::FetchPermissionProfiles { request_id, - thread_cwd: self.thread_id.and(self.current_cwd.clone()), + thread_cwd: self.thread_id.map(|_| self.session_cwd().to_path_buf()), }); } diff --git a/codex-rs/tui/src/chatwidget/protocol_requests.rs b/codex-rs/tui/src/chatwidget/protocol_requests.rs index 8a4db4964a..bae49e848a 100644 --- a/codex-rs/tui/src/chatwidget/protocol_requests.rs +++ b/codex-rs/tui/src/chatwidget/protocol_requests.rs @@ -60,10 +60,6 @@ impl ChatWidget { } } - pub(crate) fn handle_skills_list_response(&mut self, response: SkillsListResponse) { - self.on_list_skills(response); - } - pub(super) fn on_patch_apply_output_delta(&mut self, _item_id: String, _delta: String) {} pub(super) fn on_guardian_review_notification( diff --git a/codex-rs/tui/src/chatwidget/session_flow.rs b/codex-rs/tui/src/chatwidget/session_flow.rs index ac84bff791..429939d624 100644 --- a/codex-rs/tui/src/chatwidget/session_flow.rs +++ b/codex-rs/tui/src/chatwidget/session_flow.rs @@ -93,8 +93,8 @@ impl ChatWidget { if previous_thread_id != Some(session.thread_id) || self.cloud_picker_selection.is_some() { self.dismiss_stale_model_picker(); } - let connector_scope_changed = previous_thread_id != Some(session.thread_id) - || self.config.cwd.as_path() != session.cwd.as_path(); + let cwd_changed = self.current_cwd != session.cwd; + let connector_scope_changed = previous_thread_id != Some(session.thread_id) || cwd_changed; self.thread_id = Some(session.thread_id); self.read_only_history = session.read_only_history; self.thread_settings_confirmed = session.thread_settings_confirmed; @@ -119,7 +119,7 @@ impl ChatWidget { self.bottom_pane .set_queue_submissions(/*queue_submissions*/ false); if previous_thread_id != self.thread_id { - if (previous_thread_id.is_some() || self.config.cwd != session.cwd) + if (previous_thread_id.is_some() || cwd_changed) && self.status_account_display == Some(StatusAccountDisplay::ApiKey) { self.refresh_account_scoped_models(); @@ -144,8 +144,10 @@ impl ChatWidget { self.current_rollout_path = session.rollout_path.clone(); self.primary_environment_cwd .clone_from(&session.primary_environment_cwd); - self.current_cwd = Some(session.cwd.to_path_buf()); - self.config.cwd = session.cwd.clone(); + self.current_cwd = session.cwd.clone(); + if let Ok(native_cwd) = session.cwd.to_abs_path() { + self.config.cwd = native_cwd; + } self.config.model_provider_id = session.model_provider_id.clone(); if previous_thread_id.is_none() && let Some(event) = crate::app::provider::refresh_list_if_present(self) diff --git a/codex-rs/tui/src/chatwidget/settings.rs b/codex-rs/tui/src/chatwidget/settings.rs index a1345c5954..261b19c994 100644 --- a/codex-rs/tui/src/chatwidget/settings.rs +++ b/codex-rs/tui/src/chatwidget/settings.rs @@ -534,12 +534,23 @@ impl ChatWidget { fn apply_thread_settings(&mut self, mut settings: ThreadSettings) { self.invalidate_permission_discovery(); - let cwd_changed = self.config.cwd != settings.cwd; if let Some(environments) = &settings.environments { self.primary_environment_cwd = crate::session_state::primary_environment_cwd(environments); } - self.apply_thread_settings_cwd(settings.cwd.clone()); + let Ok(cwd) = crate::app_server_session::decode_thread_cwd( + &settings.cwd, + self.app_server_path_convention, + ) else { + tracing::warn!("Invalid cwd in thread settings"); + return; + }; + 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); + } + self.current_cwd = cwd; self.config.model_provider_id = settings.model_provider.clone(); self.set_daybreak_enabled(self.daybreak_enabled); self.set_service_tier(settings.service_tier.clone()); @@ -614,9 +625,6 @@ impl ChatWidget { if previous_cwd != cwd { self.permission_discovery = None; } - self.current_cwd = Some(cwd.to_path_buf()); - self.status_line_project_root_name_cache = None; - if !self.config.workspace_roots.contains(&previous_cwd) { return; } diff --git a/codex-rs/tui/src/chatwidget/skills.rs b/codex-rs/tui/src/chatwidget/skills.rs index bc04a38fff..a81a0149fe 100644 --- a/codex-rs/tui/src/chatwidget/skills.rs +++ b/codex-rs/tui/src/chatwidget/skills.rs @@ -13,12 +13,11 @@ use crate::mention_codec::is_mention_name_char; use crate::mention_codec::parse_linked_tool_mention; use crate::skills_helpers::skill_description; use crate::skills_helpers::skill_display_name; +use codex_app_server_protocol::SkillErrorInfo; use codex_app_server_protocol::SkillMetadata; -use codex_app_server_protocol::SkillsListEntry; use codex_app_server_protocol::SkillsListResponse; use codex_connectors::AppInfo; use codex_protocol::parse_command::ParsedCommand; -use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_path_uri::LegacyAppPathString; use codex_utils_path_uri::PathUri; use codex_utils_plugins::mention_syntax::PLUGIN_TEXT_MENTION_SIGIL; @@ -143,10 +142,26 @@ impl ChatWidget { self.add_info_message(summary, /*hint*/ None); } - pub(crate) fn set_skills_from_response(&mut self, response: &SkillsListResponse) { - let skills = skills_for_cwd(&self.config.cwd, &response.data); + /// Updates skills for the displayed session and returns its load errors. + pub(crate) fn set_skills_from_response( + &mut self, + response: SkillsListResponse, + ) -> Vec { + let (skills, errors) = response + .data + .into_iter() + .find(|entry| { + crate::app_server_session::decode_thread_cwd( + &LegacyAppPathString::from_path(&entry.cwd), + self.app_server_path_convention, + ) + .is_ok_and(|cwd| cwd == self.current_cwd) + }) + .map(|entry| (entry.skills, entry.errors)) + .unwrap_or_default(); self.skills_all = skills; self.set_skills(Some(enabled_skills_for_mentions(&self.skills_all))); + errors } pub(crate) fn annotate_skill_reads_in_parsed_cmd( @@ -180,14 +195,6 @@ impl ChatWidget { } } -fn skills_for_cwd(cwd: &AbsolutePathBuf, skills_entries: &[SkillsListEntry]) -> Vec { - skills_entries - .iter() - .find(|entry| entry.cwd.as_path() == cwd.as_path()) - .map(|entry| entry.skills.clone()) - .unwrap_or_default() -} - fn enabled_skills_for_mentions(skills: &[SkillMetadata]) -> Vec { skills .iter() diff --git a/codex-rs/tui/src/chatwidget/slash_dispatch.rs b/codex-rs/tui/src/chatwidget/slash_dispatch.rs index f985b03356..b4fd5e2232 100644 --- a/codex-rs/tui/src/chatwidget/slash_dispatch.rs +++ b/codex-rs/tui/src/chatwidget/slash_dispatch.rs @@ -502,22 +502,21 @@ impl ChatWidget { self.add_diff_in_progress(); let tx = self.app_event_tx.clone(); let runner = self.workspace_command_runner.clone(); - let cwd = self - .current_cwd - .clone() - .unwrap_or_else(|| self.config.cwd.to_path_buf()); + let cwd = self.session_cwd().clone(); tokio::spawn(async move { let text = match runner { - Some(runner) => match get_git_diff(runner.as_ref(), &cwd).await { - Ok((is_git_repo, diff_text)) => { - if is_git_repo { - diff_text - } else { - "`/diff` — _not inside a git repository_".to_string() + Some(runner) => { + match get_git_diff(runner.as_ref(), &cwd.to_path_buf()).await { + Ok((is_git_repo, diff_text)) => { + if is_git_repo { + diff_text + } else { + "`/diff` — _not inside a git repository_".to_string() + } } + Err(e) => format!("Failed to compute diff: {e}"), } - Err(e) => format!("Failed to compute diff: {e}"), - }, + } None => "Failed to compute diff: workspace command runner unavailable" .to_string(), }; @@ -562,7 +561,10 @@ impl ChatWidget { } SlashCommand::Pwd => { self.add_info_message( - format!("Current working directory: {}", self.config.cwd.display()), + format!( + "Current working directory: {}", + self.session_cwd().inferred_native_path_string() + ), /*hint*/ None, ); } diff --git a/codex-rs/tui/src/chatwidget/status_surfaces.rs b/codex-rs/tui/src/chatwidget/status_surfaces.rs index 881cd0eebb..7be6bf50c0 100644 --- a/codex-rs/tui/src/chatwidget/status_surfaces.rs +++ b/codex-rs/tui/src/chatwidget/status_surfaces.rs @@ -145,7 +145,7 @@ impl ChatWidget { self.status_line_branch_pending = false; self.status_line_branch_lookup_complete = false; } else { - let cwd = self.status_line_cwd().to_path_buf(); + let cwd = self.session_cwd().to_path_buf(); self.sync_status_line_branch_state(&cwd); if !self.status_line_branch_lookup_complete { self.request_status_line_branch(cwd); @@ -157,7 +157,7 @@ impl ChatWidget { self.status_line_git_summary_pending = false; self.status_line_git_summary_lookup_complete = false; } else { - let cwd = self.status_line_cwd().to_path_buf(); + let cwd = self.session_cwd().to_path_buf(); self.sync_status_line_git_summary_state(&cwd); if !self.status_line_git_summary_lookup_complete { self.request_status_line_git_summary(cwd); @@ -428,7 +428,7 @@ impl ChatWidget { if !selections.uses_git_branch() { return; } - let cwd = self.status_line_cwd().to_path_buf(); + let cwd = self.session_cwd().to_path_buf(); self.sync_status_line_branch_state(&cwd); self.request_status_line_branch(cwd); } @@ -438,7 +438,7 @@ impl ChatWidget { if !selections.uses_git_summary() { return; } - let cwd = self.status_line_cwd().to_path_buf(); + let cwd = self.session_cwd().to_path_buf(); self.sync_status_line_git_summary_state(&cwd); self.request_status_line_git_summary(cwd); } @@ -487,17 +487,16 @@ impl ChatWidget { }) } - pub(super) fn status_line_cwd(&self) -> &Path { - self.current_cwd - .as_deref() - .unwrap_or(self.config.cwd.as_path()) + /// Working directory reported by the server, falling back to config during startup. + pub(crate) fn session_cwd(&self) -> &PathUri { + &self.current_cwd } - pub(super) fn status_line_workspace_cwd(&self) -> &Path { + pub(super) fn status_line_workspace_cwd(&self) -> PathBuf { self.primary_environment_cwd .as_ref() - .map(|cwd| Path::new(cwd.path.as_str())) - .unwrap_or_else(|| self.status_line_cwd()) + .map(|cwd| cwd.path.to_path_buf()) + .unwrap_or_else(|| self.session_cwd().to_path_buf()) } fn workspace_directory_display(&self) -> String { @@ -512,7 +511,7 @@ impl ChatWidget { .as_ref() .is_none_or(|cwd| cwd.is_server_local) { - format_directory_display(cwd, /*max_width*/ None) + format_directory_display(&cwd, /*max_width*/ None) } else { cwd.display().to_string() } @@ -549,7 +548,14 @@ impl ChatWidget { /// Returns a cached project-root display name for the active cwd. fn status_line_project_root_name(&mut self) -> Option { - let cwd = self.status_line_cwd().to_path_buf(); + if self + .remote_connection + .as_ref() + .is_some_and(|connection| !connection.is_local_daemon) + { + return None; + } + let cwd = self.session_cwd().to_abs_path().ok()?.into_path_buf(); if let Some(cache) = &self.status_line_project_root_name_cache && cache.cwd == cwd { @@ -569,14 +575,11 @@ impl ChatWidget { /// This prefers the cached project-root name and falls back to the current /// directory name when no project root can be inferred. fn terminal_title_project_name(&mut self) -> Option { - let project = self.status_line_project_root_name().or_else(|| { - let cwd = self.status_line_cwd(); - Some( - cwd.file_name() - .map(|name| name.to_string_lossy().to_string()) - .unwrap_or_else(|| format_directory_display(cwd, /*max_width*/ None)), - ) - })?; + let project = self.status_line_project_root_name().unwrap_or_else(|| { + self.session_cwd() + .basename() + .unwrap_or_else(|| self.session_cwd().inferred_native_path_string()) + }); Some(Self::truncate_terminal_title_part( project, /*max_chars*/ 24, )) diff --git a/codex-rs/tui/src/chatwidget/statusline_reader.rs b/codex-rs/tui/src/chatwidget/statusline_reader.rs index d2f083560e..8f8595107c 100644 --- a/codex-rs/tui/src/chatwidget/statusline_reader.rs +++ b/codex-rs/tui/src/chatwidget/statusline_reader.rs @@ -25,8 +25,7 @@ use codex_config::types::StatusLineProviderId; use codex_config::types::StatusLineSelection; use codex_features::Feature; use codex_protocol::ThreadId; -use codex_utils_path_uri::LegacyAppPathString; -use std::path::PathBuf; +use codex_utils_path_uri::PathUri; use std::time::Duration; use tokio::sync::oneshot; use tokio::sync::watch; @@ -41,7 +40,7 @@ pub(super) struct ActiveStatuslineRead { thread: Option, selection: ProviderId, provider_from_picker: Option, - host_cwd: PathBuf, + host_cwd: PathUri, startup: watch::Sender<()>, cancel: CancellationToken, } @@ -145,7 +144,7 @@ impl ChatWidget { thread: self.thread_id, selection, provider_from_picker, - host_cwd: self.status_line_cwd().to_owned(), + host_cwd: self.session_cwd().clone(), startup, cancel: CancellationToken::new(), }); @@ -236,7 +235,7 @@ impl ActiveStatuslineRead { self.selection.server.as_str() == id.server && self.selection.tool.as_str() == id.tool }) - && self.host_cwd == chat.status_line_cwd() + && &self.host_cwd == chat.session_cwd() } pub(super) fn server_ready(&self, server: &str) { @@ -258,12 +257,11 @@ impl ActiveStatuslineRead { let events = events.clone(); let client = owner.request_handle(); let backend = owner.backend_id(); - let cwd = LegacyAppPathString::from_path(&self.host_cwd).to_inferred_path_uri(); + let cwd = self.host_cwd.clone(); let cancel = self.cancel.clone(); tokio::spawn(async move { let result: Option> = cancel .run_until_cancelled(async { - let cwd = cwd.ok_or(Failure::LookupUnavailable)?; let deadline = Instant::now() + LOOKUP_TIMEOUT; let provider = loop { let choice = provider_from_picker diff --git a/codex-rs/tui/src/chatwidget/statusline_reader_tests.rs b/codex-rs/tui/src/chatwidget/statusline_reader_tests.rs index 28479899d5..f83e64bb0d 100644 --- a/codex-rs/tui/src/chatwidget/statusline_reader_tests.rs +++ b/codex-rs/tui/src/chatwidget/statusline_reader_tests.rs @@ -169,12 +169,12 @@ async fn statusline_reader_waits_for_the_displayed_thread_and_keeps_its_result() assert_eq!(footer(&chat).as_deref(), Some("Initializing…")); let token = resumed.token; chat.primary_environment_cwd = Some(crate::session_state::EnvironmentCwd { - path: LegacyAppPathString::from_path(chat.config.cwd.join("executor-checkout").as_path()), + path: chat.config.cwd.join("executor-checkout").into(), is_server_local: false, }); chat.refresh_status_line(); assert!(read_events(&mut rx).is_empty()); - chat.current_cwd = Some(chat.config.cwd.join("another-project").to_path_buf()); + chat.current_cwd = chat.config.cwd.join("another-project").into(); let (reply, snapshot) = oneshot::channel(); chat.handle_statusline_read( StatuslineReadEvent { diff --git a/codex-rs/tui/src/chatwidget/statusline_state.rs b/codex-rs/tui/src/chatwidget/statusline_state.rs index 553b65e807..22a73221bc 100644 --- a/codex-rs/tui/src/chatwidget/statusline_state.rs +++ b/codex-rs/tui/src/chatwidget/statusline_state.rs @@ -333,7 +333,7 @@ impl ChatWidget { usage: self.into(), workspace: StatuslineStateWorkspace { cwd: codex_utils_path_uri::LegacyAppPathString::from_path( - self.status_line_workspace_cwd(), + &self.status_line_workspace_cwd(), ), }, approval, diff --git a/codex-rs/tui/src/chatwidget/streaming.rs b/codex-rs/tui/src/chatwidget/streaming.rs index de3f7b05bd..e72d790d8d 100644 --- a/codex-rs/tui/src/chatwidget/streaming.rs +++ b/codex-rs/tui/src/chatwidget/streaming.rs @@ -281,7 +281,7 @@ impl ChatWidget { self.bottom_pane.status_elapsed().unwrap_or_default(), ) }), - cwd: self.config.cwd.clone(), + cwd: self.session_cwd().to_path_buf(), visualizations, }; (stream, display) diff --git a/codex-rs/tui/src/chatwidget/tests/app_server.rs b/codex-rs/tui/src/chatwidget/tests/app_server.rs index a4ceff486e..f38c1a047e 100644 --- a/codex-rs/tui/src/chatwidget/tests/app_server.rs +++ b/codex-rs/tui/src/chatwidget/tests/app_server.rs @@ -17,7 +17,7 @@ fn thread_settings_for_test( thread_settings: codex_app_server_protocol::ThreadSettings { disabled_plugin_ids: Vec::new(), environments: None, - cwd: test_path_buf("/tmp/thread-settings").abs(), + cwd: test_path_buf("/tmp/thread-settings").abs().into(), approval_policy: AskForApproval::OnRequest, approvals_reviewer: codex_app_server_protocol::ApprovalsReviewer::AutoReview, sandbox_policy: codex_app_server_protocol::SandboxPolicy::ReadOnly { @@ -65,7 +65,7 @@ pub(super) fn configured_thread_session( approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/tmp/thread-settings").abs(), + cwd: test_path_buf("/tmp/thread-settings").abs().into(), runtime_workspace_roots: vec![test_path_buf("/tmp/thread-settings").abs()], instruction_source_paths: Vec::new(), reasoning_effort: None, @@ -693,7 +693,7 @@ async fn statusline_workspace_follows_primary_executor_and_legacy_settings() { let id = ThreadId::new(); chat.handle_thread_session(configured_thread_session(id)); let mut update = thread_settings_for_test("gpt-5.2", id); - let host = update.thread_settings.cwd.to_string_lossy().into_owned(); + let host = update.thread_settings.cwd.to_string(); let remote = r"C:\executor\checkout"; let primary = codex_app_server_protocol::ThreadEnvironment { environment_id: "remote".into(), @@ -763,7 +763,7 @@ async fn thread_settings_updated_updates_visible_state_without_transcript() { chat.set_feature_enabled(Feature::Apps, /*enabled*/ true); let thread_id = ThreadId::new(); let mut session = configured_thread_session(thread_id); - session.cwd = test_path_buf("/tmp/original-workspace").abs(); + session.cwd = test_path_buf("/tmp/original-workspace").abs().into(); session.thread_settings_confirmed = false; chat.handle_thread_session(session); chat.config.permissions.approval_policy = @@ -776,11 +776,20 @@ async fn thread_settings_updated_updates_visible_state_without_transcript() { }); let _ = drain_insert_history(&mut rx); + let remote_cwd = if cfg!(windows) { + "/home/alice/repo" + } else { + r"D:\repo" + }; + let mut notification = thread_settings_for_test("gpt-5.4", thread_id); + notification.thread_settings.cwd = + codex_utils_path_uri::LegacyAppPathString::from_string(remote_cwd); chat.handle_server_notification( - ServerNotification::ThreadSettingsUpdated(thread_settings_for_test("gpt-5.4", thread_id)), + ServerNotification::ThreadSettingsUpdated(notification), /*replay_kind*/ None, ); + assert_eq!(chat.session_cwd().inferred_native_path_string(), remote_cwd); assert_ne!(chat.connector_scope_generation(), previous_generation); assert!(chat.connectors_for_mentions().is_none()); assert!(chat.connectors.mention_refresh_in_flight); diff --git a/codex-rs/tui/src/chatwidget/tests/composer_submission.rs b/codex-rs/tui/src/chatwidget/tests/composer_submission.rs index f9de576cda..7efdd8b90e 100644 --- a/codex-rs/tui/src/chatwidget/tests/composer_submission.rs +++ b/codex-rs/tui/src/chatwidget/tests/composer_submission.rs @@ -645,7 +645,7 @@ async fn submission_preserves_text_elements_and_local_images() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -758,7 +758,7 @@ async fn submission_includes_configured_active_permission_profile() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: expected_permission_profile, active_permission_profile: Some(expected_active_permission_profile.clone()), - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -817,7 +817,7 @@ async fn submission_omits_active_permission_profile_for_legacy_snapshot() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: expected_permission_profile, active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -866,7 +866,7 @@ async fn submission_with_remote_and_local_images_keeps_local_placeholder_numberi approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -970,7 +970,7 @@ async fn enter_with_only_remote_images_submits_user_turn() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -1043,7 +1043,7 @@ async fn shift_enter_with_only_remote_images_does_not_submit_user_turn() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -1088,7 +1088,7 @@ async fn enter_with_only_remote_images_does_not_submit_when_modal_is_active() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -1133,7 +1133,7 @@ async fn enter_with_only_remote_images_does_not_submit_when_input_disabled() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -1181,7 +1181,7 @@ async fn submission_prefers_selected_duplicate_skill_path() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), diff --git a/codex-rs/tui/src/chatwidget/tests/exec_flow.rs b/codex-rs/tui/src/chatwidget/tests/exec_flow.rs index 838363ffc2..f2cabb6d07 100644 --- a/codex-rs/tui/src/chatwidget/tests/exec_flow.rs +++ b/codex-rs/tui/src/chatwidget/tests/exec_flow.rs @@ -1304,7 +1304,7 @@ async fn bang_shell_enter_while_task_running_submits_run_user_shell_command() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), diff --git a/codex-rs/tui/src/chatwidget/tests/history_replay.rs b/codex-rs/tui/src/chatwidget/tests/history_replay.rs index 2ca1cf1d1e..071e68074b 100644 --- a/codex-rs/tui/src/chatwidget/tests/history_replay.rs +++ b/codex-rs/tui/src/chatwidget/tests/history_replay.rs @@ -36,7 +36,7 @@ async fn resumed_initial_messages_render_history() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -90,7 +90,7 @@ async fn resumed_initial_messages_render_history() { chat.set_feature_enabled(Feature::CliDaybreak, /*enabled*/ true); chat.show_welcome_banner = false; chat.local_settings.tui.show_tooltips = false; - chat.config.cwd = configured.cwd.clone(); + chat.config.cwd = configured.cwd.to_abs_path().ok().unwrap(); chat.transcript.active_cell = Some(ChatWidget::placeholder_session_header_cell(&chat.config)); configured.thread_id = ThreadId::new(); chat.handle_thread_session(configured); @@ -201,7 +201,7 @@ async fn restored_conversation_ultra_remains_selected_after_switching_to_plan() approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::Ultra), @@ -527,7 +527,7 @@ async fn replayed_user_message_preserves_text_elements_and_local_images() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -603,7 +603,7 @@ async fn replayed_user_message_preserves_remote_image_urls() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -709,7 +709,7 @@ async fn session_configured_syncs_widget_config_permissions_and_cwd() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: expected_permission_profile, active_permission_profile: None, - cwd: expected_cwd.clone(), + cwd: expected_cwd.clone().into(), runtime_workspace_roots: vec![expected_cwd.clone()], instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -734,8 +734,8 @@ async fn session_configured_syncs_widget_config_permissions_and_cwd() { chat.handle_manage_skills_closed(); assert!(matches!( ops.try_recv(), - Ok(AppCommand::ListSkills { cwds, force_reload: true }) - if cwds == vec![expected_cwd.to_path_buf()] + Ok(AppCommand::ListSkills { cwd, force_reload: true }) + if cwd == PathUri::from_abs_path(&expected_cwd) )); let updated_profile = PermissionProfile::workspace_write(); @@ -791,7 +791,7 @@ async fn session_configured_preserves_profile_workspace_roots() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: session_permission_profile.clone(), active_permission_profile: None, - cwd: session_cwd.clone(), + cwd: session_cwd.clone().into(), runtime_workspace_roots: session_runtime_workspace_roots.clone(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -839,7 +839,7 @@ async fn session_configured_external_sandbox_keeps_external_runtime_policy() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: expected_permission_profile, active_permission_profile: None, - cwd: test_path_buf("/home/user/external").abs(), + cwd: test_path_buf("/home/user/external").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -882,7 +882,7 @@ async fn replayed_user_message_with_only_remote_images_renders_history_cell() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -946,7 +946,7 @@ async fn replayed_user_message_with_only_local_images_renders_history_cell() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -1307,7 +1307,7 @@ async fn replayed_reasoning_item_preserves_summary_parts_and_hides_raw_reasoning approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_project_path().abs(), + cwd: test_project_path().abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: None, @@ -1362,7 +1362,7 @@ async fn replayed_reasoning_item_shows_raw_reasoning_when_enabled() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_project_path().abs(), + cwd: test_project_path().abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: None, diff --git a/codex-rs/tui/src/chatwidget/tests/permissions.rs b/codex-rs/tui/src/chatwidget/tests/permissions.rs index 8d514f0ab8..77d22f66ff 100644 --- a/codex-rs/tui/src/chatwidget/tests/permissions.rs +++ b/codex-rs/tui/src/chatwidget/tests/permissions.rs @@ -1178,7 +1178,7 @@ async fn required_windows_sandbox_setup_defers_configured_initial_prompt() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::workspace_write(), active_permission_profile: None, - cwd: test_project_path().abs(), + cwd: test_project_path().abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: None, @@ -1631,7 +1631,7 @@ async fn permissions_selection_marks_auto_review_current_after_session_configure approvals_reviewer: ApprovalsReviewer::AutoReview, permission_profile: PermissionProfile::workspace_write(), active_permission_profile: None, - cwd: test_project_path().abs(), + cwd: test_project_path().abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: None, @@ -1688,7 +1688,7 @@ async fn permissions_selection_marks_auto_review_current_with_custom_workspace_w approvals_reviewer: ApprovalsReviewer::AutoReview, permission_profile, active_permission_profile: None, - cwd, + cwd: cwd.into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: None, diff --git a/codex-rs/tui/src/chatwidget/tests/plan_mode.rs b/codex-rs/tui/src/chatwidget/tests/plan_mode.rs index f2353b97eb..9a32aeb3fe 100644 --- a/codex-rs/tui/src/chatwidget/tests/plan_mode.rs +++ b/codex-rs/tui/src/chatwidget/tests/plan_mode.rs @@ -32,7 +32,7 @@ fn plan_test_session(thread_id: ThreadId) -> crate::session_state::ThreadSession approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), @@ -1248,7 +1248,7 @@ async fn submit_user_message_emits_structured_plugin_mentions_from_bindings() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), diff --git a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs index 0ac63dd273..ec8c3073b7 100644 --- a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs +++ b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs @@ -3389,6 +3389,11 @@ async fn slash_pwd_and_cwd_alias_display_current_working_directory_from_composer let mut output = Vec::new(); for (command, side) in [("/pwd", false), ("/cwd", true), ("/pwd x", false)] { let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + if side { + chat.current_cwd = + PathUri::try_from(LegacyAppPathString::from_string(r"D:\workspace\remote")) + .expect("absolute server path"); + } chat.set_side_conversation_active(side); chat.bottom_pane.set_task_running(!side); chat.bottom_pane @@ -3400,7 +3405,7 @@ async fn slash_pwd_and_cwd_alias_display_current_working_directory_from_composer } insta::assert_snapshot!(output.join(""), @r" • Current working directory: /tmp/project -• Current working directory: /tmp/project +• Current working directory: D:\workspace\remote ■ Usage: /pwd "); } diff --git a/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs b/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs index 917f1ad904..382b560c7b 100644 --- a/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs +++ b/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs @@ -4800,7 +4800,7 @@ async fn session_configured_clears_goal_status_footer() { approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/home/user/project").abs(), + cwd: test_path_buf("/home/user/project").abs().into(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: Some(ReasoningEffortConfig::default()), diff --git a/codex-rs/tui/src/chatwidget/tests/status_surface_previews.rs b/codex-rs/tui/src/chatwidget/tests/status_surface_previews.rs index 80af40369d..21dbc0d032 100644 --- a/codex-rs/tui/src/chatwidget/tests/status_surface_previews.rs +++ b/codex-rs/tui/src/chatwidget/tests/status_surface_previews.rs @@ -565,6 +565,17 @@ async fn missing_project_root_uses_different_status_and_title_preview_sources() assert_eq!(status_preview, "my-project"); assert_eq!(title_preview, "project"); + + chat.remote_connection = crate::status::remote_connection::remote_connection_status_value( + &crate::AppServerTarget::Cloud, + /*server_version*/ None, + ); + chat.current_cwd = PathUri::try_from(LegacyAppPathString::from_string(r"D:\workspace\remote")) + .expect("absolute server path"); + assert_snapshot!( + title_preview_line(&mut chat, &[TerminalTitleItem::Project]), + @"remote" + ); } #[tokio::test] diff --git a/codex-rs/tui/src/dynamic_tools.rs b/codex-rs/tui/src/dynamic_tools.rs index 949662ace6..39838132cd 100644 --- a/codex-rs/tui/src/dynamic_tools.rs +++ b/codex-rs/tui/src/dynamic_tools.rs @@ -537,7 +537,7 @@ async fn execute_inner( ); } thread_start_params.model_provider = Some(source_thread.model_provider.clone()); - thread_start_params.cwd = Some(source_thread.cwd.to_string_lossy().into_owned()); + thread_start_params.cwd = Some(source_thread.cwd.as_str().to_owned()); thread_start_params.project_id = source_thread.project_id.clone(); thread_start_params.ephemeral = Some(source_thread.ephemeral); if features.enabled(Feature::CliDaybreak) diff --git a/codex-rs/tui/src/history_cell/session.rs b/codex-rs/tui/src/history_cell/session.rs index 120454d1ea..ac64947c8c 100644 --- a/codex-rs/tui/src/history_cell/session.rs +++ b/codex-rs/tui/src/history_cell/session.rs @@ -204,7 +204,7 @@ pub(crate) fn new_session_info( let header = SessionHeaderHistoryCell::new( model_display_name.to_string(), session.reasoning_effort.clone(), - config.cwd.to_path_buf(), + session.cwd.to_path_buf(), CODEX_CLI_VERSION, ) .with_yolo_mode(has_yolo_permissions( diff --git a/codex-rs/tui/src/history_cell/tests.rs b/codex-rs/tui/src/history_cell/tests.rs index 6822d4f578..eb65626440 100644 --- a/codex-rs/tui/src/history_cell/tests.rs +++ b/codex-rs/tui/src/history_cell/tests.rs @@ -652,7 +652,7 @@ fn session_configured_event(model: &str) -> ThreadSessionState { approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), active_permission_profile: None, - cwd: test_path_buf("/tmp/project").abs(), + cwd: codex_utils_path_uri::PathUri::parse("file:///tmp/project").unwrap(), runtime_workspace_roots: Vec::new(), instruction_source_paths: Vec::new(), reasoning_effort: None, @@ -790,13 +790,8 @@ async fn session_info_uses_availability_nux_tooltip_override() { } #[tokio::test] -#[cfg_attr( - target_os = "windows", - ignore = "snapshot path rendering differs on Windows" -)] async fn session_info_availability_nux_tooltip_snapshot() { - let mut config = test_config().await; - config.cwd = test_path_buf("/tmp/project").abs(); + let config = test_config().await; let cell = new_session_info( &config, &crate::local_settings::LocalSettings::from(&config), diff --git a/codex-rs/tui/src/lib_tests.rs b/codex-rs/tui/src/lib_tests.rs index 010698e638..954fc2311e 100644 --- a/codex-rs/tui/src/lib_tests.rs +++ b/codex-rs/tui/src/lib_tests.rs @@ -597,7 +597,7 @@ async fn startup_resume_and_fork_use_configured_or_explicit_cwd() -> color_eyre: }; assert!(!session_resume::cwds_differ( - started.session.cwd.as_path(), + &started.session.cwd.to_path_buf(), &expected_cwd, )); app_server.shutdown().await?; diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rs index 65561aa22c..e67e693236 100644 --- a/codex-rs/tui/src/resume_picker.rs +++ b/codex-rs/tui/src/resume_picker.rs @@ -7744,7 +7744,7 @@ session_picker_view = "dense" recency_at: Some(2), status: codex_app_server_protocol::ThreadStatus::Idle, path: None, - cwd: test_path_buf("/tmp").abs(), + cwd: test_path_buf("/tmp").abs().into(), cli_version: String::from("0.0.0"), source: codex_app_server_protocol::SessionSource::Cli, can_accept_direct_input: None, @@ -7792,7 +7792,7 @@ session_picker_view = "dense" recency_at: Some(2), status: codex_app_server_protocol::ThreadStatus::Idle, path: None, - cwd: test_path_buf("/tmp").abs(), + cwd: test_path_buf("/tmp").abs().into(), cli_version: String::from("0.0.0"), source: codex_app_server_protocol::SessionSource::Cli, can_accept_direct_input: None, @@ -7895,7 +7895,7 @@ session_picker_view = "dense" recency_at: Some(2), status: codex_app_server_protocol::ThreadStatus::Idle, path: None, - cwd: test_path_buf("/tmp").abs(), + cwd: test_path_buf("/tmp").abs().into(), cli_version: String::from("0.0.0"), source: codex_app_server_protocol::SessionSource::Cli, can_accept_direct_input: None, @@ -7975,7 +7975,7 @@ session_picker_view = "dense" recency_at: Some(2), status: codex_app_server_protocol::ThreadStatus::Idle, path: None, - cwd: test_path_buf("/tmp").abs(), + cwd: test_path_buf("/tmp").abs().into(), cli_version: String::from("0.0.0"), source: codex_app_server_protocol::SessionSource::Cli, can_accept_direct_input: None, diff --git a/codex-rs/tui/src/session_state.rs b/codex-rs/tui/src/session_state.rs index 0f22e97627..797c260a04 100644 --- a/codex-rs/tui/src/session_state.rs +++ b/codex-rs/tui/src/session_state.rs @@ -53,7 +53,7 @@ pub(crate) struct ThreadSessionState { /// Named or implicit built-in profile that produced `permission_profile`, /// when the server knows it. pub(crate) active_permission_profile: Option, - pub(crate) cwd: AbsolutePathBuf, + pub(crate) cwd: PathUri, /// Native cwd of the primary executor, which can differ from the app-server cwd. pub(crate) primary_environment_cwd: Option, pub(crate) runtime_workspace_roots: Vec, @@ -90,11 +90,12 @@ impl ThreadSessionState { self.forked_from_id = parent; } - pub(crate) fn set_cwd_retargeting_implicit_runtime_workspace_root( - &mut self, - cwd: AbsolutePathBuf, - ) { - let previous_cwd = std::mem::replace(&mut self.cwd, cwd.clone()); + 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; } diff --git a/codex-rs/tui/src/task_mentions.rs b/codex-rs/tui/src/task_mentions.rs index 7ad4286f7f..a52e439af8 100644 --- a/codex-rs/tui/src/task_mentions.rs +++ b/codex-rs/tui/src/task_mentions.rs @@ -195,7 +195,7 @@ impl TaskSearch { thread_id: thread.id, title, label_style, - cwd: thread.cwd.to_string_lossy().into_owned(), + cwd: thread.cwd.into_string(), snippet: result.snippet, }) }) diff --git a/codex-rs/tui/src/thread_transcript.rs b/codex-rs/tui/src/thread_transcript.rs index 060d4a9c41..761317c8e2 100644 --- a/codex-rs/tui/src/thread_transcript.rs +++ b/codex-rs/tui/src/thread_transcript.rs @@ -20,8 +20,8 @@ use codex_app_server_protocol::ThreadItemPayload; use codex_app_server_protocol::UserInput; use codex_protocol::ThreadId; use codex_protocol::items::UserMessageItem; -use codex_utils_absolute_path::AbsolutePathBuf; use ratatui::style::Stylize as _; +use std::path::Path; mod activity_pages; mod computer_groups; @@ -105,7 +105,7 @@ pub(crate) fn thread_to_transcript_cells( .flat_map(|turn| { let mut cells = thread_items_to_transcript_cells( thread_id, - &cwd, + cwd.as_path(), turn.items.into_iter().map(|entry| entry.payload), raw_reasoning_visibility, config, @@ -128,7 +128,7 @@ pub(crate) fn thread_to_transcript_cells( pub(crate) fn thread_items_to_transcript_cells( thread_id: Option, - cwd: &AbsolutePathBuf, + cwd: &Path, items: impl IntoIterator, raw_reasoning_visibility: RawReasoningVisibility, config: Option<&Config>, @@ -226,7 +226,7 @@ pub(crate) fn thread_items_to_transcript_cells( /// Project one item without changing the active widget or its turn lifecycle. fn item_to_cells( item: ThreadItemPayload, - cwd: &AbsolutePathBuf, + cwd: &Path, raw_reasoning_visibility: RawReasoningVisibility, inline_visualization_context: Option, ) -> TranscriptCells { @@ -272,7 +272,7 @@ fn item_to_cells( item.local_image_paths(), item.image_urls(), ); - cells.push(Arc::new(cell.with_async_replies(replies, cwd.as_path()))); + cells.push(Arc::new(cell.with_async_replies(replies, cwd))); } ThreadItemPayload::AgentMessage { text, @@ -280,12 +280,12 @@ fn item_to_cells( phase, .. } => { - let parsed = parse_assistant_markdown(&text, cwd.as_path()); + let parsed = parse_assistant_markdown(&text, cwd); if !parsed.visible_markdown.trim().is_empty() { cells.push(Arc::new( AgentMarkdownCell::new_with_inline_visualizations( parsed.visible_markdown, - cwd.as_path(), + cwd, inline_visualization_context, ) .with_phase(phase) @@ -314,10 +314,7 @@ fn item_to_cells( } ThreadItemPayload::Plan { text, .. } => { if !text.trim().is_empty() { - cells.push(Arc::new(crate::history_cell::new_proposed_plan( - text, - cwd.as_path(), - ))); + cells.push(Arc::new(crate::history_cell::new_proposed_plan(text, cwd))); } } ThreadItemPayload::Reasoning { @@ -335,12 +332,8 @@ fn item_to_cells( text.push_str(&content.join("\n\n")); } if !text.trim().is_empty() { - let mut cell = ReasoningSummaryCell::new( - header, - text, - cwd.as_path(), - /*transcript_only*/ true, - ); + let mut cell = + ReasoningSummaryCell::new(header, text, cwd, /*transcript_only*/ true); cell.set_source_item_id(id); cells.push(Arc::new(cell)); } diff --git a/codex-rs/tui/src/thread_transcript/other_items.rs b/codex-rs/tui/src/thread_transcript/other_items.rs index b5f87b7b26..a77f6736e8 100644 --- a/codex-rs/tui/src/thread_transcript/other_items.rs +++ b/codex-rs/tui/src/thread_transcript/other_items.rs @@ -11,11 +11,11 @@ use crate::multi_agents; use codex_app_server_protocol::PatchApplyStatus; use codex_app_server_protocol::ThreadItemPayload; use codex_app_server_protocol::WebSearchAction; -use codex_utils_absolute_path::AbsolutePathBuf; use ratatui::style::Stylize as _; +use std::path::Path; use std::sync::Arc; -pub(super) fn cells(item: ThreadItemPayload, cwd: &AbsolutePathBuf) -> TranscriptCells { +pub(super) fn cells(item: ThreadItemPayload, cwd: &Path) -> TranscriptCells { let mut cells: TranscriptCells = Vec::new(); match item { ThreadItemPayload::FileChange { @@ -25,11 +25,8 @@ pub(super) fn cells(item: ThreadItemPayload, cwd: &AbsolutePathBuf) -> Transcrip } => match status { PatchApplyStatus::Completed if !changes.is_empty() => { cells.push(Arc::new( - history_cell::new_patch_event( - file_update_changes_to_display(changes), - cwd.as_path(), - ) - .with_activity_id(id), + history_cell::new_patch_event(file_update_changes_to_display(changes), cwd) + .with_activity_id(id), )); } PatchApplyStatus::Completed => {} diff --git a/codex-rs/tui/src/worktree_startup.rs b/codex-rs/tui/src/worktree_startup.rs index 232388197a..df836630f5 100644 --- a/codex-rs/tui/src/worktree_startup.rs +++ b/codex-rs/tui/src/worktree_startup.rs @@ -191,7 +191,7 @@ pub(super) async fn prepare( shutdown?; cli.fork_session_id = Some(thread.id); if cli.cwd.is_none() { - let cwd = latest_thread_cwd(thread.path, thread.cwd.into_path_buf()).await; + let cwd = latest_thread_cwd(thread.path, PathBuf::from(thread.cwd.into_string())).await; let cwd = AbsolutePathBuf::from_absolute_path(cwd)?; let bootstrap = load_bootstrap_config_or_exit( &source.codex_home, diff --git a/codex-rs/utils/path-uri/src/api_path_string.rs b/codex-rs/utils/path-uri/src/api_path_string.rs index db4d8b664f..915752d14a 100644 --- a/codex-rs/utils/path-uri/src/api_path_string.rs +++ b/codex-rs/utils/path-uri/src/api_path_string.rs @@ -9,6 +9,7 @@ use serde::Serialize; use serde::Serializer; use std::fmt; use std::path::Path; +use std::path::PathBuf; use thiserror::Error; use ts_rs::TS; @@ -188,6 +189,16 @@ impl LegacyAppPathString { } } + /// Borrows the API string as a path without validating it for this host. + pub fn as_path(&self) -> &Path { + Path::new(&self.0) + } + + /// Copies the API path text into a path buffer without normalization. + pub fn to_path_buf(&self) -> PathBuf { + self.as_path().to_owned() + } + pub fn as_str(&self) -> &str { &self.0 }